113 lines
2.8 KiB
TypeScript
113 lines
2.8 KiB
TypeScript
export const dynamic = "force-dynamic";
|
|
|
|
import { requireAdmin } from "@/lib/auth/session";
|
|
import { handleAuthError, fail, ok } from "@/lib/api";
|
|
import { prisma } from "@/lib/prisma";
|
|
import { syncCalendarConnectionWithLogger } from "@/lib/services/caldav";
|
|
import {
|
|
appendCalendarSyncLog,
|
|
finishCalendarSyncRun,
|
|
getCalendarSyncRunWithLogs,
|
|
startCalendarSyncRun
|
|
} from "@/lib/services/caldav-sync-logs";
|
|
import { validateMutationRequestOrigin } from "@/lib/security/request";
|
|
|
|
async function getConnection(id: string) {
|
|
return prisma.calendarConn.findFirst({
|
|
where: {
|
|
id,
|
|
user: {
|
|
role: "STAFF"
|
|
}
|
|
},
|
|
select: { id: true }
|
|
});
|
|
}
|
|
|
|
export async function GET(
|
|
req: Request,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
await requireAdmin();
|
|
const { id } = await params;
|
|
|
|
const connection = await getConnection(id);
|
|
if (!connection) {
|
|
return fail("Personen-Kalender nicht gefunden", 404);
|
|
}
|
|
|
|
const { searchParams } = new URL(req.url);
|
|
const runId = searchParams.get("runId")?.trim() || undefined;
|
|
const run = await getCalendarSyncRunWithLogs({
|
|
calendarConnId: connection.id,
|
|
runId
|
|
});
|
|
|
|
return ok({ run });
|
|
} catch (error) {
|
|
return handleAuthError(error);
|
|
}
|
|
}
|
|
|
|
export async function POST(
|
|
req: Request,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const originError = validateMutationRequestOrigin(req);
|
|
if (originError) return originError;
|
|
|
|
await requireAdmin();
|
|
const { id } = await params;
|
|
|
|
const connection = await getConnection(id);
|
|
|
|
if (!connection) {
|
|
return fail("Personen-Kalender nicht gefunden", 404);
|
|
}
|
|
|
|
const run = await startCalendarSyncRun(connection.id);
|
|
void (async () => {
|
|
try {
|
|
await appendCalendarSyncLog(run.id, "INFO", "Sync-Job wurde gestartet.");
|
|
const result = await syncCalendarConnectionWithLogger(
|
|
connection.id,
|
|
async (level, message) => {
|
|
await appendCalendarSyncLog(run.id, level, message);
|
|
}
|
|
);
|
|
|
|
if (result.ok) {
|
|
await finishCalendarSyncRun(
|
|
run.id,
|
|
"SUCCESS",
|
|
`Synchronisiert: ${result.count ?? 0} Termin(e).`
|
|
);
|
|
return;
|
|
}
|
|
|
|
await finishCalendarSyncRun(
|
|
run.id,
|
|
"FAILED",
|
|
result.message ?? "Synchronisierung fehlgeschlagen"
|
|
);
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : "Unbekannter Fehler";
|
|
await appendCalendarSyncLog(run.id, "ERROR", message);
|
|
await finishCalendarSyncRun(run.id, "FAILED", message);
|
|
}
|
|
})();
|
|
|
|
return ok(
|
|
{
|
|
message: "Kalender-Synchronisierung gestartet",
|
|
runId: run.id
|
|
},
|
|
202
|
|
);
|
|
} catch (error) {
|
|
return handleAuthError(error);
|
|
}
|
|
}
|