Files
livedash-node/pages/api/admin/trigger-processing.ts
Max Kowalski 5c1ced5900 feat: add rawTranscriptContent field to SessionImport model
feat: enhance server initialization with environment validation and import processing scheduler

test: add Jest setup for unit tests and mock console methods

test: implement unit tests for environment management and validation

test: create unit tests for transcript fetcher functionality
2025-06-27 19:00:22 +02:00

104 lines
2.9 KiB
TypeScript

import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "../auth/[...nextauth]";
import { prisma } from "../../../lib/prisma";
import { processUnprocessedSessions } from "../../../lib/processingScheduler";
interface SessionUser {
email: string;
name?: string;
}
interface SessionData {
user: SessionUser;
}
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== "POST") {
return res.status(405).json({ error: "Method not allowed" });
}
const session = (await getServerSession(
req,
res,
authOptions
)) as SessionData | null;
if (!session?.user) {
return res.status(401).json({ error: "Not logged in" });
}
const user = await prisma.user.findUnique({
where: { email: session.user.email },
include: { company: true },
});
if (!user) {
return res.status(401).json({ error: "No user found" });
}
// Check if user has ADMIN role
if (user.role !== "ADMIN") {
return res.status(403).json({ error: "Admin access required" });
}
try {
// Get optional parameters from request body
const { batchSize, maxConcurrency } = req.body;
// Validate parameters
const validatedBatchSize = batchSize && batchSize > 0 ? parseInt(batchSize) : null;
const validatedMaxConcurrency = maxConcurrency && maxConcurrency > 0 ? parseInt(maxConcurrency) : 5;
// Check how many unprocessed sessions exist
const unprocessedCount = await prisma.session.count({
where: {
companyId: user.companyId,
processed: false,
messages: { some: {} }, // Must have messages
},
});
if (unprocessedCount === 0) {
return res.json({
success: true,
message: "No unprocessed sessions found",
unprocessedCount: 0,
processedCount: 0,
});
}
// Start processing (this will run asynchronously)
const startTime = Date.now();
// Note: We're calling the function but not awaiting it to avoid timeout
// The processing will continue in the background
processUnprocessedSessions(validatedBatchSize, validatedMaxConcurrency)
.then(() => {
console.log(`[Manual Trigger] Processing completed for company ${user.companyId}`);
})
.catch((error) => {
console.error(`[Manual Trigger] Processing failed for company ${user.companyId}:`, error);
});
return res.json({
success: true,
message: `Started processing ${unprocessedCount} unprocessed sessions`,
unprocessedCount,
batchSize: validatedBatchSize || unprocessedCount,
maxConcurrency: validatedMaxConcurrency,
startedAt: new Date().toISOString(),
});
} catch (error) {
console.error("[Manual Trigger] Error:", error);
return res.status(500).json({
error: "Failed to trigger processing",
details: error instanceof Error ? error.message : String(error),
});
}
}