Files
livedash-node/pages/api/admin/trigger-processing.ts
Max Kowalski 653d70022b Broken shit
2025-06-26 21:00:19 +02:00

110 lines
3.0 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/processingSchedulerNoCron";
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 || undefined, 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),
});
}
}