99 lines
2.9 KiB
TypeScript
99 lines
2.9 KiB
TypeScript
import { FreshContext, Handlers } from "$fresh/server.ts";
|
|
import { db } from "$root/databases/db.ts";
|
|
import { ajustements } from "$root/databases/schema.ts";
|
|
import { AuthenticatedState, isEmployee } from "$root/defaults/interfaces.ts";
|
|
import { eq } from "npm:drizzle-orm@0.45.2";
|
|
|
|
export const handler: Handlers<null, AuthenticatedState> = {
|
|
// #48 GET /ajustements
|
|
async GET(request) {
|
|
try {
|
|
const url = new URL(request.url);
|
|
const numEtudParam = url.searchParams.get("numEtud");
|
|
const idUEParam = url.searchParams.get("idUE");
|
|
|
|
let query = db.select().from(ajustements).$dynamic();
|
|
|
|
if (numEtudParam) {
|
|
const numEtud = parseInt(numEtudParam);
|
|
if (isNaN(numEtud)) {
|
|
return new Response("Paramètre numEtud invalide", { status: 400 });
|
|
}
|
|
query = query.where(eq(ajustements.numEtud, numEtud));
|
|
}
|
|
|
|
if (idUEParam) {
|
|
const idUE = parseInt(idUEParam);
|
|
if (isNaN(idUE)) {
|
|
return new Response("Paramètre idUE invalide", { status: 400 });
|
|
}
|
|
query = query.where(eq(ajustements.idUE, idUE));
|
|
}
|
|
|
|
const result = await query;
|
|
|
|
return new Response(JSON.stringify(result), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
});
|
|
} catch (error) {
|
|
console.error("Error fetching ajustements:", error);
|
|
return new Response("Failed to fetch data", { status: 500 });
|
|
}
|
|
},
|
|
|
|
// #49 POST /ajustements
|
|
async POST(
|
|
request: Request,
|
|
context: FreshContext<AuthenticatedState>,
|
|
): Promise<Response> {
|
|
if (!isEmployee(context.state.session)) {
|
|
return new Response(null, { status: 403 });
|
|
}
|
|
|
|
try {
|
|
const body: {
|
|
numEtud: number;
|
|
idUE: number;
|
|
valeur: number;
|
|
malus?: number;
|
|
} = await request.json();
|
|
|
|
if (!body.numEtud || !body.idUE || body.valeur === undefined) {
|
|
return new Response(
|
|
JSON.stringify({ error: "Champs requis: numEtud, idUE, valeur" }),
|
|
{ status: 400, headers: { "content-type": "application/json" } },
|
|
);
|
|
}
|
|
|
|
if (
|
|
body.malus !== undefined &&
|
|
(!Number.isInteger(body.malus) || body.malus < 0)
|
|
) {
|
|
return new Response(
|
|
JSON.stringify({ error: "malus doit être un entier >= 0" }),
|
|
{ status: 400, headers: { "content-type": "application/json" } },
|
|
);
|
|
}
|
|
|
|
const [created] = await db
|
|
.insert(ajustements)
|
|
.values({
|
|
numEtud: body.numEtud,
|
|
idUE: body.idUE,
|
|
valeur: body.valeur,
|
|
malus: body.malus ?? 0,
|
|
})
|
|
.returning();
|
|
|
|
return new Response(JSON.stringify(created), {
|
|
status: 201,
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
} catch (error) {
|
|
console.error("Error creating ajustement:", error);
|
|
return new Response("Failed to create ajustement", { status: 500 });
|
|
}
|
|
},
|
|
};
|