Enhance session management with filtering, sorting, and pagination features; implement API for fetching filter options and update session API to support advanced querying.

This commit is contained in:
2025-05-22 08:15:25 +02:00
parent 97af5d9dcf
commit 4d29e444ef
7 changed files with 513 additions and 99 deletions

View File

@ -0,0 +1,70 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import { prisma } from "../../../lib/prisma";
import { SessionFilterOptions } from "../../../lib/types";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<SessionFilterOptions | { error: string; details?: string; }>
) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Method not allowed" });
}
const authSession = await getServerSession(req, res, authOptions);
if (!authSession || !authSession.user?.companyId) {
return res.status(401).json({ error: "Unauthorized" });
}
const companyId = authSession.user.companyId;
try {
const categories = await prisma.session.findMany({
where: {
companyId,
category: {
not: null, // Ensure category is not null
},
},
distinct: ["category"],
select: {
category: true,
},
orderBy: {
category: "asc",
},
});
const languages = await prisma.session.findMany({
where: {
companyId,
language: {
not: null, // Ensure language is not null
},
},
distinct: ["language"],
select: {
language: true,
},
orderBy: {
language: "asc",
},
});
const distinctCategories = categories.map((s) => s.category).filter(Boolean) as string[]; // Filter out any nulls and assert as string[]
const distinctLanguages = languages.map((s) => s.language).filter(Boolean) as string[]; // Filter out any nulls and assert as string[]
return res
.status(200)
.json({ categories: distinctCategories, languages: distinctLanguages });
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";
return res.status(500).json({
error: "Failed to fetch filter options",
details: errorMessage,
});
}
}

View File

@ -2,11 +2,11 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../auth/[...nextauth]";
import { prisma } from "../../../lib/prisma";
import { ChatSession } from "../../../lib/types";
import { ChatSession, SessionApiResponse, SessionQuery } from "../../../lib/types";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
res: NextApiResponse<SessionApiResponse | { error: string; details?: string; }>
) {
if (req.method !== "GET") {
return res.status(405).json({ error: "Method not allowed" });
@ -19,11 +19,25 @@ export default async function handler(
}
const companyId = authSession.user.companyId;
const { searchTerm } = req.query;
const {
searchTerm,
category,
language,
startDate,
endDate,
sortKey,
sortOrder,
page: queryPage,
pageSize: queryPageSize,
} = req.query as SessionQuery;
const page = Number(queryPage) || 1;
const pageSize = Number(queryPageSize) || 10;
try {
const whereClause: any = { companyId };
// Search Term
if (
searchTerm &&
typeof searchTerm === "string" &&
@ -31,6 +45,7 @@ export default async function handler(
) {
const searchConditions = [
{ id: { contains: searchTerm, mode: "insensitive" } },
{ sessionId: { contains: searchTerm, mode: "insensitive" } },
{ category: { contains: searchTerm, mode: "insensitive" } },
{ initialMsg: { contains: searchTerm, mode: "insensitive" } },
{ transcriptContent: { contains: searchTerm, mode: "insensitive" } },
@ -38,13 +53,55 @@ export default async function handler(
whereClause.OR = searchConditions;
}
// Category Filter
if (category && typeof category === "string" && category.trim() !== "") {
whereClause.category = category;
}
// Language Filter
if (language && typeof language === "string" && language.trim() !== "") {
whereClause.language = language;
}
// Date Range Filter
if (startDate && typeof startDate === "string") {
if (!whereClause.startTime) whereClause.startTime = {};
whereClause.startTime.gte = new Date(startDate);
}
if (endDate && typeof endDate === "string") {
if (!whereClause.startTime) whereClause.startTime = {};
const inclusiveEndDate = new Date(endDate);
inclusiveEndDate.setDate(inclusiveEndDate.getDate() + 1);
whereClause.startTime.lt = inclusiveEndDate;
}
// Sorting
let orderByClause: any = { startTime: "desc" };
if (sortKey && typeof sortKey === "string") {
const order =
sortOrder === "asc" || sortOrder === "desc" ? sortOrder : "desc";
const validSortKeys: { [key: string]: string; } = {
startTime: "startTime",
category: "category",
language: "language",
sentiment: "sentiment",
messagesSent: "messagesSent",
avgResponseTime: "avgResponseTime",
};
if (validSortKeys[sortKey]) {
orderByClause = { [validSortKeys[sortKey]]: order };
}
}
const prismaSessions = await prisma.session.findMany({
where: whereClause,
orderBy: {
startTime: "desc",
},
orderBy: orderByClause,
skip: (page - 1) * pageSize,
take: pageSize,
});
const totalSessions = await prisma.session.count({ where: whereClause });
const sessions: ChatSession[] = prismaSessions.map((ps) => ({
id: ps.id,
sessionId: ps.id,
@ -70,7 +127,7 @@ export default async function handler(
transcriptContent: ps.transcriptContent ?? null,
}));
return res.status(200).json({ sessions });
return res.status(200).json({ sessions, totalSessions });
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : "An unknown error occurred";

View File

@ -44,7 +44,7 @@ export default async function handler(
return res.status(400).json({ error: "Missing fields" });
const exists = await prisma.user.findUnique({ where: { email } });
if (exists) return res.status(409).json({ error: "Email exists" });
const tempPassword = crypto.randomBytes(12).toString('base64').slice(0, 12); // secure random initial password
const tempPassword = crypto.randomBytes(12).toString("base64").slice(0, 12); // secure random initial password
await prisma.user.create({
data: {
email,
@ -53,7 +53,7 @@ export default async function handler(
role,
},
});
// TODO: Email user their temp password (stub, for demo)
// TODO: Email user their temp password (stub, for demo) - Implement a robust and secure email sending mechanism. Consider using a transactional email service.
res.json({ ok: true, tempPassword });
} else res.status(405).end();
}