import { FreshContext, Handlers } from "$fresh/server.ts"; import { db } from "$root/databases/db.ts"; import { mobilites } from "$root/databases/schema.ts"; import { AuthenticatedState } from "$root/defaults/interfaces.ts"; import { eq } from "npm:drizzle-orm@0.45.2"; const VALID_STATUSES = [ "contracts_received", "under_revision", "done", "validated", "canceled", ] as const; export const handler: Handlers = { // GET /mobilites — list all, optional ?numEtud filter async GET(request) { try { const url = new URL(request.url); const numEtudParam = url.searchParams.get("numEtud"); let query = db.select().from(mobilites).$dynamic(); if (numEtudParam) { const numEtud = parseInt(numEtudParam); if (isNaN(numEtud)) { return new Response("Paramètre numEtud invalide", { status: 400 }); } query = query.where(eq(mobilites.numEtud, numEtud)); } const result = await query; return new Response(JSON.stringify(result), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { console.error("Error fetching mobilites:", error); return new Response("Failed to fetch data", { status: 500 }); } }, // POST /mobilites — create mobility async POST( request: Request, context: FreshContext, ): Promise { const isEmployee = context.state.session.eduPersonPrimaryAffiliation === "employee"; try { const body = await request.json(); const { numEtud, duree, ecole, pays, status, idStage } = body; // Students can only create mobilites for themselves if (!isEmployee && numEtud !== undefined) { // Students cannot set idStage or status if (idStage || (status && status !== "contracts_received")) { return new Response(null, { status: 403 }); } } if (!numEtud || duree === undefined) { return new Response( JSON.stringify({ error: "Champs requis: numEtud, duree" }), { status: 400, headers: { "content-type": "application/json" } }, ); } if (!Number.isInteger(duree) || duree < 1) { return new Response( JSON.stringify({ error: "duree doit être un entier >= 1" }), { status: 400, headers: { "content-type": "application/json" } }, ); } if ( status !== undefined && !VALID_STATUSES.includes(status) ) { return new Response( JSON.stringify({ error: `status invalide, valeurs: ${VALID_STATUSES.join(", ")}`, }), { status: 400, headers: { "content-type": "application/json" } }, ); } // Stage-linked mobilities are always validated const effectiveStatus = idStage ? "validated" : (status ?? "contracts_received"); const [created] = await db .insert(mobilites) .values({ numEtud, duree, ecole: ecole ?? null, pays: pays ?? null, status: effectiveStatus, idStage: idStage ?? null, }) .returning(); return new Response(JSON.stringify(created), { status: 201, headers: { "content-type": "application/json" }, }); } catch (error) { console.error("Error creating mobilite:", error); return new Response("Failed to create mobilite", { status: 500 }); } }, };