feat: stages module, mobility frontend, theme toggle, employeeOnly access control
- Add stages module with full CRUD API and admin overview island - Add mobility overview island (Liste, Kanban, Detail CRUD views) - Add contract PDF upload/download endpoints for mobilites - Add light/dark theme toggle in header - Add employeeOnly flag to hide entire modules from students (admin, students, stages) - Add read-only GET endpoints for modules/ues/ue-modules in notes module - Add [slug].tsx catch-all routes for direct URL navigation - Replace old mobility table with mobilites + stages schema (migration 0004) - Allow students to create mobilites and upload contracts - Redirect authenticated users from / to /apps catalog
This commit is contained in:
@@ -1,115 +0,0 @@
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
interface Promotion {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Student {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
promotionId: number;
|
||||
}
|
||||
|
||||
interface Mobility {
|
||||
id: number;
|
||||
studentId: string;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
weeksCount: number | null;
|
||||
destinationCountry: string | null;
|
||||
destinationName: string | null;
|
||||
mobilityStatus: string;
|
||||
}
|
||||
|
||||
export default function ConsultMobility() {
|
||||
const [data, setData] = useState<
|
||||
| {
|
||||
promotions?: Promotion[];
|
||||
students?: Student[];
|
||||
mobilities?: Mobility[];
|
||||
}
|
||||
| null
|
||||
>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
console.log("ConsultMobility: Fetching data from API...");
|
||||
try {
|
||||
const response = await fetch("/mobility/api/insert_mobility");
|
||||
console.log("ConsultMobility: API response status:", response.status);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching data: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
console.log("ConsultMobility: Data fetched successfully:", result);
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
console.error("ConsultMobility: Error fetching data:", err);
|
||||
setError("Failed to load mobility data. Please try again later.");
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
if (error) {
|
||||
return <p className="error">{error}</p>;
|
||||
}
|
||||
|
||||
if (!data?.promotions) {
|
||||
return <p>No promotions found.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h2>Consult Mobility</h2>
|
||||
{data.promotions.map((promo) => (
|
||||
<div key={promo.id}>
|
||||
<h3>Promotion: {promo.name}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>First Name</th>
|
||||
<th>Last Name</th>
|
||||
<th>Start Date</th>
|
||||
<th>End Date</th>
|
||||
<th>Weeks Count</th>
|
||||
<th>Destination Country</th>
|
||||
<th>Destination Name</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.students
|
||||
?.filter((student) => student.promotionId === promo.id)
|
||||
.map((student) => {
|
||||
const mobility = data.mobilities?.find((mob) =>
|
||||
mob.studentId === student.id
|
||||
);
|
||||
return (
|
||||
<tr key={student.id}>
|
||||
<td>{student.id}</td>
|
||||
<td>{student.firstName}</td>
|
||||
<td>{student.lastName}</td>
|
||||
<td>{mobility?.startDate || "N/A"}</td>
|
||||
<td>{mobility?.endDate || "N/A"}</td>
|
||||
<td>{mobility?.weeksCount ?? "N/A"}</td>
|
||||
<td>{mobility?.destinationCountry || "N/A"}</td>
|
||||
<td>{mobility?.destinationName || "N/A"}</td>
|
||||
<td>{mobility?.mobilityStatus || "N/A"}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
interface Promotion {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Student {
|
||||
id: number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
mail: string;
|
||||
promotionId: number;
|
||||
promotionName: string;
|
||||
}
|
||||
|
||||
export default function ConsultStudents_test() {
|
||||
const [data, setData] = useState<
|
||||
{ promotions: Promotion[]; students: Student[] } | null
|
||||
>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const response = await fetch("/students/api/insert_students");
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching data: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
console.error("Error fetching data:", err);
|
||||
setError("Failed to load data. Please try again later.");
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h2>Consult Students</h2>
|
||||
{error && <p className="error">{error}</p>}
|
||||
{data?.promotions.map((promo) => (
|
||||
<div key={promo.id}>
|
||||
<h3>Promotion: {promo.id}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>First Name</th>
|
||||
<th>Last Name</th>
|
||||
<th>Email</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.students
|
||||
.filter((student) => student.promotionId === promo.id)
|
||||
.map((student) => (
|
||||
<tr key={student.id}>
|
||||
<td>{student.id}</td>
|
||||
<td>{student.firstName}</td>
|
||||
<td>{student.lastName}</td>
|
||||
<td>{student.mail}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -1,248 +0,0 @@
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
interface Student {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
promotionId: number;
|
||||
}
|
||||
|
||||
interface Promotion {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface Mobility {
|
||||
id: number | null;
|
||||
studentId: string;
|
||||
startDate: string | null;
|
||||
endDate: string | null;
|
||||
weeksCount: number | null;
|
||||
destinationCountry: string | null;
|
||||
destinationName: string | null;
|
||||
mobilityStatus: string;
|
||||
}
|
||||
|
||||
export default function EditMobility() {
|
||||
const [data, setData] = useState<
|
||||
| {
|
||||
promotions?: Promotion[];
|
||||
students?: Student[];
|
||||
mobilities?: Mobility[];
|
||||
}
|
||||
| null
|
||||
>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
console.log("EditMobility: Fetching data from API...");
|
||||
try {
|
||||
const response = await fetch("/mobility/api/insert_mobility");
|
||||
console.log("EditMobility: API response status:", response.status);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Error fetching data: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
console.log("EditMobility: Data fetched successfully:", result);
|
||||
setData(result);
|
||||
} catch (err) {
|
||||
console.error("EditMobility: Error fetching data:", err);
|
||||
setError("Failed to load mobility data. Please try again later.");
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
const handleChange = (
|
||||
studentId: string,
|
||||
field: keyof Mobility,
|
||||
value: string | number | null,
|
||||
) => {
|
||||
if (!data) return;
|
||||
|
||||
setData((prevData) => {
|
||||
if (!prevData) return null;
|
||||
|
||||
const updatedMobilities = prevData.mobilities?.map((mobility) => {
|
||||
if (mobility.studentId === studentId) {
|
||||
const updatedMobility = { ...mobility, [field]: value };
|
||||
|
||||
if (field === "startDate" || field === "endDate") {
|
||||
const startDate = new Date(updatedMobility.startDate || "");
|
||||
const endDate = new Date(updatedMobility.endDate || "");
|
||||
if (startDate && endDate && startDate <= endDate) {
|
||||
const weeks = Math.ceil(
|
||||
(endDate.getTime() - startDate.getTime()) /
|
||||
(7 * 24 * 60 * 60 * 1000),
|
||||
);
|
||||
updatedMobility.weeksCount = weeks;
|
||||
} else {
|
||||
updatedMobility.weeksCount = null;
|
||||
}
|
||||
}
|
||||
|
||||
return updatedMobility;
|
||||
}
|
||||
return mobility;
|
||||
}) || [];
|
||||
|
||||
return { ...prevData, mobilities: updatedMobilities };
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setIsSaving(true);
|
||||
|
||||
try {
|
||||
const response = await fetch("/mobility/api/insert_mobility", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ data: data?.mobilities }),
|
||||
});
|
||||
|
||||
console.log("EditMobility: Save response status:", response.status);
|
||||
|
||||
if (response.ok) {
|
||||
alert("Data saved successfully!");
|
||||
globalThis.location.reload();
|
||||
} else {
|
||||
throw new Error(`Failed to save data: ${response.statusText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("EditMobility: Error saving data:", error);
|
||||
alert("An error occurred while saving data.");
|
||||
} finally {
|
||||
setIsSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (error) {
|
||||
return <p className="error">{error}</p>;
|
||||
}
|
||||
|
||||
if (!data?.promotions) {
|
||||
return <p>Loading data...</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<section>
|
||||
<h2>Edit Mobility</h2>
|
||||
{data.promotions.map((promo) => (
|
||||
<div key={promo.id}>
|
||||
<h3>Promotion: {promo.name}</h3>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>First Name</th>
|
||||
<th>Last Name</th>
|
||||
<th>Start Date</th>
|
||||
<th>End Date</th>
|
||||
<th>Weeks Count</th>
|
||||
<th>Destination Country</th>
|
||||
<th>Destination Name</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{data.students
|
||||
?.filter((student) => student.promotionId === promo.id)
|
||||
.map((student) => {
|
||||
const mobility = data.mobilities?.find((mob) =>
|
||||
mob.studentId === student.id
|
||||
) || {
|
||||
id: null,
|
||||
studentId: student.id,
|
||||
startDate: null,
|
||||
endDate: null,
|
||||
weeksCount: null,
|
||||
destinationCountry: null,
|
||||
destinationName: null,
|
||||
mobilityStatus: "N/A",
|
||||
};
|
||||
|
||||
return (
|
||||
<tr key={student.id}>
|
||||
<td>{student.id}</td>
|
||||
<td>{student.firstName}</td>
|
||||
<td>{student.lastName}</td>
|
||||
<td>
|
||||
<input
|
||||
type="date"
|
||||
value={mobility.startDate || ""}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
student.id,
|
||||
"startDate",
|
||||
e.target.value,
|
||||
)}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="date"
|
||||
value={mobility.endDate || ""}
|
||||
onChange={(e) =>
|
||||
handleChange(student.id, "endDate", e.target.value)}
|
||||
/>
|
||||
</td>
|
||||
<td>{mobility.weeksCount ?? "N/A"}</td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={mobility.destinationCountry || ""}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
student.id,
|
||||
"destinationCountry",
|
||||
e.target.value,
|
||||
)}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<input
|
||||
type="text"
|
||||
value={mobility.destinationName || ""}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
student.id,
|
||||
"destinationName",
|
||||
e.target.value,
|
||||
)}
|
||||
/>
|
||||
</td>
|
||||
<td>
|
||||
<select
|
||||
value={mobility.mobilityStatus}
|
||||
onChange={(e) =>
|
||||
handleChange(
|
||||
student.id,
|
||||
"mobilityStatus",
|
||||
e.target.value,
|
||||
)}
|
||||
>
|
||||
<option value="N/A">N/A</option>
|
||||
<option value="Planned">Planned</option>
|
||||
<option value="In Progress">In Progress</option>
|
||||
<option value="Completed">Completed</option>
|
||||
<option value="Validated">Validated</option>
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
<button type="button" onClick={handleSave} disabled={isSaving}>
|
||||
{isSaving ? "Saving..." : "Confirm"}
|
||||
</button>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,931 @@
|
||||
import { useEffect, useState } from "preact/hooks";
|
||||
|
||||
type Student = {
|
||||
numEtud: number;
|
||||
nom: string;
|
||||
prenom: string;
|
||||
idPromo: string;
|
||||
};
|
||||
type Promotion = { id: string; annee: string };
|
||||
type Mobilite = {
|
||||
id: number;
|
||||
numEtud: number;
|
||||
duree: number;
|
||||
contratMob: string | null;
|
||||
ecole: string | null;
|
||||
pays: string | null;
|
||||
status: string;
|
||||
idStage: number | null;
|
||||
};
|
||||
type Stage = {
|
||||
id: number;
|
||||
numEtud: number;
|
||||
duree: number;
|
||||
nomEntreprise: string;
|
||||
mission: string | null;
|
||||
};
|
||||
|
||||
const REQUIRED_WEEKS = 12;
|
||||
|
||||
const STATUS_ORDER = [
|
||||
"contracts_received",
|
||||
"under_revision",
|
||||
"done",
|
||||
"validated",
|
||||
"canceled",
|
||||
] as const;
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
contracts_received: "Contrats reçus",
|
||||
under_revision: "En révision",
|
||||
done: "Signé",
|
||||
validated: "Validé",
|
||||
canceled: "Annulé",
|
||||
};
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
contracts_received: "#f5a623",
|
||||
under_revision: "#dc2626",
|
||||
done: "#22c55e",
|
||||
validated: "light-dark(var(--light-accent-color), var(--dark-accent-color))",
|
||||
canceled:
|
||||
"light-dark(var(--light-foreground-dim), var(--dark-foreground-dim))",
|
||||
};
|
||||
|
||||
function lowestStatus(mobs: Mobilite[]): string {
|
||||
let lowest = STATUS_ORDER.length - 1;
|
||||
for (const m of mobs) {
|
||||
const idx = STATUS_ORDER.indexOf(m.status as typeof STATUS_ORDER[number]);
|
||||
if (idx >= 0 && idx < lowest) lowest = idx;
|
||||
}
|
||||
return STATUS_ORDER[lowest];
|
||||
}
|
||||
|
||||
function validatedWeeks(mobs: Mobilite[]): number {
|
||||
return mobs
|
||||
.filter((m) => m.status === "validated")
|
||||
.reduce((sum, m) => sum + m.duree, 0);
|
||||
}
|
||||
|
||||
export default function MobilityOverview() {
|
||||
const [students, setStudents] = useState<Student[]>([]);
|
||||
const [promos, setPromos] = useState<Promotion[]>([]);
|
||||
const [mobilites, setMobilites] = useState<Mobilite[]>([]);
|
||||
const [stagesMap, setStagesMap] = useState<Record<number, Stage>>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [tab, setTab] = useState<"liste" | "kanban">("liste");
|
||||
const [filterPromo, setFilterPromo] = useState("");
|
||||
const [filterNom, setFilterNom] = useState("");
|
||||
|
||||
// Detail view state
|
||||
const [detailStudent, setDetailStudent] = useState<Student | null>(null);
|
||||
const [editingMob, setEditingMob] = useState<Mobilite | null>(null);
|
||||
const [showAddForm, setShowAddForm] = useState(false);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
const [sRes, pRes, mRes, stRes] = await Promise.all([
|
||||
fetch("/students/api/students"),
|
||||
fetch("/students/api/promotions"),
|
||||
fetch("/mobility/api/mobilites"),
|
||||
fetch("/stages/api/stages"),
|
||||
]);
|
||||
if (!sRes.ok) throw new Error("Impossible de charger les données");
|
||||
const [sData, pData, mData, stData] = await Promise.all([
|
||||
sRes.json(),
|
||||
pRes.ok ? pRes.json() : [],
|
||||
mRes.ok ? mRes.json() : [],
|
||||
stRes.ok ? stRes.json() : [],
|
||||
]);
|
||||
setStudents(sData);
|
||||
setPromos(pData);
|
||||
setMobilites(mData);
|
||||
setStagesMap(
|
||||
Object.fromEntries((stData as Stage[]).map((s) => [s.id, s])),
|
||||
);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Erreur");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
|
||||
// If in detail view, render that
|
||||
if (detailStudent) {
|
||||
return (
|
||||
<DetailView
|
||||
student={detailStudent}
|
||||
mobilites={mobilites.filter((m) => m.numEtud === detailStudent.numEtud)}
|
||||
allMobilites={mobilites}
|
||||
stagesMap={stagesMap}
|
||||
editingMob={editingMob}
|
||||
setEditingMob={setEditingMob}
|
||||
showAddForm={showAddForm}
|
||||
setShowAddForm={setShowAddForm}
|
||||
onBack={() => {
|
||||
setDetailStudent(null);
|
||||
setEditingMob(null);
|
||||
setShowAddForm(false);
|
||||
}}
|
||||
onReload={load}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div class="page-content">
|
||||
<p class="state-loading">Chargement...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (error) {
|
||||
return (
|
||||
<div class="page-content">
|
||||
<p class="state-error">{error}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const filtered = students.filter((s) => {
|
||||
const matchPromo = !filterPromo || s.idPromo === filterPromo;
|
||||
const matchNom = !filterNom ||
|
||||
`${s.nom} ${s.prenom}`.toLowerCase().includes(filterNom.toLowerCase());
|
||||
return matchPromo && matchNom;
|
||||
});
|
||||
|
||||
const mobsByStudent = (numEtud: number) =>
|
||||
mobilites.filter((m) => m.numEtud === numEtud);
|
||||
|
||||
return (
|
||||
<div class="page-content">
|
||||
<h2 class="page-title">Suivi des mobilités</h2>
|
||||
|
||||
<div class="tabs">
|
||||
<button
|
||||
type="button"
|
||||
class={`tab-btn${tab === "liste" ? " active" : ""}`}
|
||||
onClick={() => setTab("liste")}
|
||||
>
|
||||
Liste
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class={`tab-btn${tab === "kanban" ? " active" : ""}`}
|
||||
onClick={() => setTab("kanban")}
|
||||
>
|
||||
Kanban
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="filters">
|
||||
<select
|
||||
class="filter-select"
|
||||
value={filterPromo}
|
||||
onChange={(e) =>
|
||||
setFilterPromo((e.target as HTMLSelectElement).value)}
|
||||
>
|
||||
<option value="">Toutes les promos</option>
|
||||
{promos.map((p) => <option key={p.id} value={p.id}>{p.id}</option>)}
|
||||
</select>
|
||||
<input
|
||||
class="filter-input"
|
||||
placeholder="Rechercher..."
|
||||
value={filterNom}
|
||||
onInput={(e) => setFilterNom((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{tab === "liste"
|
||||
? (
|
||||
<ListView
|
||||
students={filtered}
|
||||
mobsByStudent={mobsByStudent}
|
||||
onConsult={(s) => setDetailStudent(s)}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<KanbanView
|
||||
students={filtered}
|
||||
mobsByStudent={mobsByStudent}
|
||||
onConsult={(s) => setDetailStudent(s)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Liste View ─────────────────────────────────────────────
|
||||
|
||||
function ListView(
|
||||
{ students, mobsByStudent, onConsult }: {
|
||||
students: Student[];
|
||||
mobsByStudent: (n: number) => Mobilite[];
|
||||
onConsult: (s: Student) => void;
|
||||
},
|
||||
) {
|
||||
return (
|
||||
<div class="data-table-wrap">
|
||||
<table class="data-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>N° étud.</th>
|
||||
<th>Nom</th>
|
||||
<th>Prénom</th>
|
||||
<th>Semaines</th>
|
||||
<th>Actions</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{students.length === 0
|
||||
? (
|
||||
<tr>
|
||||
<td colspan={5} class="state-empty">Aucun élève trouvé</td>
|
||||
</tr>
|
||||
)
|
||||
: students.map((s) => {
|
||||
const mobs = mobsByStudent(s.numEtud);
|
||||
const weeks = validatedWeeks(mobs);
|
||||
const ok = weeks >= REQUIRED_WEEKS;
|
||||
return (
|
||||
<tr key={s.numEtud}>
|
||||
<td class="col-dim">{s.numEtud}</td>
|
||||
<td>{s.nom}</td>
|
||||
<td>{s.prenom}</td>
|
||||
<td>
|
||||
<span
|
||||
style={{
|
||||
color: ok ? "var(--ok-color,#22c55e)" : "#dc2626",
|
||||
fontWeight: "var(--font-weight-bold)",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
>
|
||||
{weeks}/{REQUIRED_WEEKS}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-primary"
|
||||
onClick={() => onConsult(s)}
|
||||
>
|
||||
Consulter
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Kanban View ────────────────────────────────────────────
|
||||
|
||||
function KanbanView(
|
||||
{ students, mobsByStudent, onConsult }: {
|
||||
students: Student[];
|
||||
mobsByStudent: (n: number) => Mobilite[];
|
||||
onConsult: (s: Student) => void;
|
||||
},
|
||||
) {
|
||||
// Students who have at least one mobility
|
||||
const studentsWithMobs = students.filter(
|
||||
(s) => mobsByStudent(s.numEtud).length > 0,
|
||||
);
|
||||
|
||||
// Group students by their lowest status
|
||||
const columns: Record<string, Student[]> = {};
|
||||
for (const status of STATUS_ORDER) columns[status] = [];
|
||||
|
||||
for (const s of studentsWithMobs) {
|
||||
const mobs = mobsByStudent(s.numEtud);
|
||||
// Filter out canceled for lowest-status calc (canceled is separate)
|
||||
const activeMobs = mobs.filter((m) => m.status !== "canceled");
|
||||
if (activeMobs.length === 0) {
|
||||
// All canceled
|
||||
columns["canceled"].push(s);
|
||||
} else {
|
||||
const lowest = lowestStatus(activeMobs);
|
||||
columns[lowest].push(s);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.75rem",
|
||||
overflowX: "auto",
|
||||
paddingBottom: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{STATUS_ORDER.map((status) => (
|
||||
<div
|
||||
key={status}
|
||||
style={{
|
||||
minWidth: "14rem",
|
||||
flex: "1",
|
||||
borderRadius: "4px",
|
||||
border:
|
||||
"1px solid light-dark(var(--light-foreground-dimmer), var(--dark-foreground-dimmer))",
|
||||
background: "light-dark(white, #141228)",
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
padding: "0.6rem 0.75rem",
|
||||
borderBottom:
|
||||
"1px solid light-dark(var(--light-foreground-dimmer), var(--dark-foreground-dimmer))",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
gap: "0.5rem",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
style={{
|
||||
width: "0.6rem",
|
||||
height: "0.6rem",
|
||||
borderRadius: "50%",
|
||||
background: STATUS_COLORS[status],
|
||||
display: "inline-block",
|
||||
}}
|
||||
/>
|
||||
<span
|
||||
style={{
|
||||
fontWeight: "var(--font-weight-bold)",
|
||||
fontSize: "0.82rem",
|
||||
}}
|
||||
>
|
||||
{STATUS_LABELS[status]}
|
||||
</span>
|
||||
<span
|
||||
style={{
|
||||
fontSize: "0.7rem",
|
||||
opacity: "0.7",
|
||||
marginLeft: "auto",
|
||||
}}
|
||||
>
|
||||
{columns[status].length}
|
||||
</span>
|
||||
</div>
|
||||
<div style={{ padding: "0.5rem" }}>
|
||||
{columns[status].length === 0
|
||||
? (
|
||||
<p
|
||||
style={{
|
||||
fontSize: "0.75rem",
|
||||
opacity: "0.5",
|
||||
textAlign: "center",
|
||||
margin: "1rem 0",
|
||||
}}
|
||||
>
|
||||
Aucun
|
||||
</p>
|
||||
)
|
||||
: columns[status].map((s) => {
|
||||
const mobs = mobsByStudent(s.numEtud);
|
||||
const weeks = validatedWeeks(mobs);
|
||||
return (
|
||||
<div
|
||||
key={s.numEtud}
|
||||
style={{
|
||||
padding: "0.5rem 0.6rem",
|
||||
marginBottom: "0.4rem",
|
||||
borderRadius: "3px",
|
||||
border:
|
||||
"1px solid light-dark(var(--light-foreground-dimmer), var(--dark-foreground-dimmer))",
|
||||
cursor: "pointer",
|
||||
fontSize: "0.8rem",
|
||||
}}
|
||||
onClick={() => onConsult(s)}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
fontWeight: "var(--font-weight-bold)",
|
||||
marginBottom: "0.15rem",
|
||||
}}
|
||||
>
|
||||
{s.nom} {s.prenom}
|
||||
</div>
|
||||
<div
|
||||
style={{
|
||||
fontSize: "0.72rem",
|
||||
display: "flex",
|
||||
justifyContent: "space-between",
|
||||
}}
|
||||
>
|
||||
<span style={{ opacity: "0.7" }}>{s.numEtud}</span>
|
||||
<span
|
||||
style={{
|
||||
color: weeks >= REQUIRED_WEEKS
|
||||
? "#22c55e"
|
||||
: "#dc2626",
|
||||
fontWeight: "var(--font-weight-bold)",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
>
|
||||
{weeks}/{REQUIRED_WEEKS} sem.
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Detail View ────────────────────────────────────────────
|
||||
|
||||
function DetailView(
|
||||
{
|
||||
student,
|
||||
mobilites,
|
||||
allMobilites,
|
||||
stagesMap,
|
||||
editingMob,
|
||||
setEditingMob,
|
||||
showAddForm,
|
||||
setShowAddForm,
|
||||
onBack,
|
||||
onReload,
|
||||
}: {
|
||||
student: Student;
|
||||
mobilites: Mobilite[];
|
||||
allMobilites: Mobilite[];
|
||||
stagesMap: Record<number, Stage>;
|
||||
editingMob: Mobilite | null;
|
||||
setEditingMob: (m: Mobilite | null) => void;
|
||||
showAddForm: boolean;
|
||||
setShowAddForm: (v: boolean) => void;
|
||||
onBack: () => void;
|
||||
onReload: () => Promise<void>;
|
||||
},
|
||||
) {
|
||||
const weeks = validatedWeeks(mobilites);
|
||||
const ecoles = [...new Set(allMobilites.map((m) => m.ecole).filter(Boolean))];
|
||||
const paysList = [
|
||||
...new Set(allMobilites.map((m) => m.pays).filter(Boolean)),
|
||||
];
|
||||
|
||||
async function deleteMob(id: number) {
|
||||
if (!confirm("Supprimer cette mobilité ?")) return;
|
||||
await fetch(`/mobility/api/mobilites/${id}`, { method: "DELETE" });
|
||||
await onReload();
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="page-content">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-secondary"
|
||||
onClick={onBack}
|
||||
style={{ marginBottom: "0.75rem" }}
|
||||
>
|
||||
Retour
|
||||
</button>
|
||||
<h2 class="page-title">
|
||||
Consulter : {student.prenom} {student.nom}
|
||||
<span
|
||||
style={{
|
||||
fontSize: "0.8rem",
|
||||
fontWeight: "normal",
|
||||
marginLeft: "0.75rem",
|
||||
color: weeks >= REQUIRED_WEEKS ? "#22c55e" : "#dc2626",
|
||||
fontFamily: "monospace",
|
||||
}}
|
||||
>
|
||||
{weeks}/{REQUIRED_WEEKS} semaines validées
|
||||
</span>
|
||||
</h2>
|
||||
|
||||
{mobilites.length === 0 && (
|
||||
<p class="state-empty">Aucune mobilité enregistrée.</p>
|
||||
)}
|
||||
|
||||
{mobilites.map((mob, i) => {
|
||||
const stage = mob.idStage ? stagesMap[mob.idStage] : null;
|
||||
const isEditing = editingMob?.id === mob.id;
|
||||
|
||||
if (isEditing) {
|
||||
return (
|
||||
<MobEditForm
|
||||
key={mob.id}
|
||||
mob={mob}
|
||||
ecoles={ecoles}
|
||||
paysList={paysList}
|
||||
onCancel={() => setEditingMob(null)}
|
||||
onSave={async () => {
|
||||
setEditingMob(null);
|
||||
await onReload();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div key={mob.id} class="ue-card" style={{ marginBottom: "1rem" }}>
|
||||
<div class="ue-card-header">
|
||||
<p class="ue-card-title">
|
||||
Mobilité {i + 1}
|
||||
{stage ? " : Stage" : " : Étude"}
|
||||
</p>
|
||||
<p
|
||||
class="ue-card-avg"
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.75rem",
|
||||
alignItems: "center",
|
||||
}}
|
||||
>
|
||||
<span
|
||||
class={`note-chip ${
|
||||
mob.status === "validated"
|
||||
? "note-chip--ok"
|
||||
: mob.status === "canceled"
|
||||
? "note-chip--fail"
|
||||
: "note-chip--none"
|
||||
}`}
|
||||
>
|
||||
{STATUS_LABELS[mob.status] ?? mob.status}
|
||||
</span>
|
||||
<span>Durée : {mob.duree} semaine(s)</span>
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ padding: "0.6rem 1.1rem" }}>
|
||||
{stage
|
||||
? (
|
||||
<p style={{ fontSize: "0.82rem", margin: "0 0 0.4rem" }}>
|
||||
Entreprise : <strong>{stage.nomEntreprise}</strong>
|
||||
{stage.mission && <span>— {stage.mission}</span>}
|
||||
</p>
|
||||
)
|
||||
: (
|
||||
<p style={{ fontSize: "0.82rem", margin: "0 0 0.4rem" }}>
|
||||
{mob.ecole && (
|
||||
<>
|
||||
École : <strong>{mob.ecole}</strong>
|
||||
</>
|
||||
)}
|
||||
{mob.ecole && mob.pays && <span>,</span>}
|
||||
{mob.pays && (
|
||||
<>
|
||||
Pays : <strong>{mob.pays}</strong>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
gap: "0.5rem",
|
||||
flexWrap: "wrap",
|
||||
marginTop: "0.5rem",
|
||||
}}
|
||||
>
|
||||
{mob.contratMob && (
|
||||
<a
|
||||
class="btn btn-sm btn-primary"
|
||||
href={`/mobility/api/mobilites/${mob.id}/contrat`}
|
||||
target="_blank"
|
||||
>
|
||||
Télécharger contrat
|
||||
</a>
|
||||
)}
|
||||
{!mob.idStage && (
|
||||
<UploadContratBtn
|
||||
mobId={mob.id}
|
||||
hasContrat={!!mob.contratMob}
|
||||
onDone={onReload}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-secondary"
|
||||
onClick={() =>
|
||||
setEditingMob(mob)}
|
||||
>
|
||||
Modifier
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-danger"
|
||||
onClick={() =>
|
||||
deleteMob(mob.id)}
|
||||
>
|
||||
Supprimer
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
{showAddForm
|
||||
? (
|
||||
<MobAddForm
|
||||
numEtud={student.numEtud}
|
||||
ecoles={ecoles}
|
||||
paysList={paysList}
|
||||
onCancel={() => setShowAddForm(false)}
|
||||
onSave={async () => {
|
||||
setShowAddForm(false);
|
||||
await onReload();
|
||||
}}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-primary"
|
||||
onClick={() => setShowAddForm(true)}
|
||||
>
|
||||
+ Nouvelle mobilité
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Inline forms ───────────────────────────────────────────
|
||||
|
||||
function MobEditForm(
|
||||
{ mob, ecoles, paysList, onCancel, onSave }: {
|
||||
mob: Mobilite;
|
||||
ecoles: string[];
|
||||
paysList: string[];
|
||||
onCancel: () => void;
|
||||
onSave: () => Promise<void>;
|
||||
},
|
||||
) {
|
||||
const [duree, setDuree] = useState(String(mob.duree));
|
||||
const [ecole, setEcole] = useState(mob.ecole ?? "");
|
||||
const [pays, setPays] = useState(mob.pays ?? "");
|
||||
const [status, setStatus] = useState(mob.status);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch(`/mobility/api/mobilites/${mob.id}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
duree: parseInt(duree),
|
||||
ecole: ecole || null,
|
||||
pays: pays || null,
|
||||
status,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error("Erreur");
|
||||
await onSave();
|
||||
} catch {
|
||||
alert("Erreur lors de la modification");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="edit-section" style={{ marginBottom: "1rem" }}>
|
||||
<p class="edit-section-title">Modifier la mobilité #{mob.id}</p>
|
||||
<div class="form-grid">
|
||||
<div class="form-field">
|
||||
<label>Durée (semaines)</label>
|
||||
<input
|
||||
class="form-input"
|
||||
type="number"
|
||||
min="1"
|
||||
value={duree}
|
||||
onInput={(e) => setDuree((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
{!mob.idStage && (
|
||||
<>
|
||||
<div class="form-field">
|
||||
<label>École</label>
|
||||
<input
|
||||
class="form-input"
|
||||
list="edit-ecoles"
|
||||
value={ecole}
|
||||
onInput={(e) => setEcole((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
<datalist id="edit-ecoles">
|
||||
{ecoles.map((e) => <option key={e} value={e} />)}
|
||||
</datalist>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Pays</label>
|
||||
<input
|
||||
class="form-input"
|
||||
list="edit-pays"
|
||||
value={pays}
|
||||
onInput={(e) => setPays((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
<datalist id="edit-pays">
|
||||
{paysList.map((p) => <option key={p} value={p} />)}
|
||||
</datalist>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Status</label>
|
||||
<select
|
||||
class="filter-select"
|
||||
value={status}
|
||||
onChange={(e) =>
|
||||
setStatus((e.target as HTMLSelectElement).value)}
|
||||
>
|
||||
{STATUS_ORDER.map((s) => (
|
||||
<option key={s} value={s}>{STATUS_LABELS[s]}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "0.5rem", marginTop: "0.5rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-primary"
|
||||
disabled={busy}
|
||||
onClick={submit}
|
||||
>
|
||||
Enregistrer
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-secondary"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MobAddForm(
|
||||
{ numEtud, ecoles, paysList, onCancel, onSave }: {
|
||||
numEtud: number;
|
||||
ecoles: string[];
|
||||
paysList: string[];
|
||||
onCancel: () => void;
|
||||
onSave: () => Promise<void>;
|
||||
},
|
||||
) {
|
||||
const [duree, setDuree] = useState("4");
|
||||
const [ecole, setEcole] = useState("");
|
||||
const [pays, setPays] = useState("");
|
||||
const [status, setStatus] = useState("contracts_received");
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function submit() {
|
||||
setBusy(true);
|
||||
try {
|
||||
const res = await fetch("/mobility/api/mobilites", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
numEtud,
|
||||
duree: parseInt(duree),
|
||||
ecole: ecole || null,
|
||||
pays: pays || null,
|
||||
status,
|
||||
}),
|
||||
});
|
||||
if (!res.ok) throw new Error("Erreur");
|
||||
await onSave();
|
||||
} catch {
|
||||
alert("Erreur lors de la création");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="edit-section" style={{ marginBottom: "1rem" }}>
|
||||
<p class="edit-section-title">Nouvelle mobilité</p>
|
||||
<div class="form-grid">
|
||||
<div class="form-field">
|
||||
<label>Durée (semaines)</label>
|
||||
<input
|
||||
class="form-input"
|
||||
type="number"
|
||||
min="1"
|
||||
value={duree}
|
||||
onInput={(e) => setDuree((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>École</label>
|
||||
<input
|
||||
class="form-input"
|
||||
list="add-ecoles"
|
||||
value={ecole}
|
||||
onInput={(e) => setEcole((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
<datalist id="add-ecoles">
|
||||
{ecoles.map((e) => <option key={e} value={e} />)}
|
||||
</datalist>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Pays</label>
|
||||
<input
|
||||
class="form-input"
|
||||
list="add-pays"
|
||||
value={pays}
|
||||
onInput={(e) => setPays((e.target as HTMLInputElement).value)}
|
||||
/>
|
||||
<datalist id="add-pays">
|
||||
{paysList.map((p) => <option key={p} value={p} />)}
|
||||
</datalist>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Status</label>
|
||||
<select
|
||||
class="filter-select"
|
||||
value={status}
|
||||
onChange={(e) => setStatus((e.target as HTMLSelectElement).value)}
|
||||
>
|
||||
{STATUS_ORDER.map((s) => (
|
||||
<option key={s} value={s}>{STATUS_LABELS[s]}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: "flex", gap: "0.5rem", marginTop: "0.5rem" }}>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-primary"
|
||||
disabled={busy || !duree}
|
||||
onClick={submit}
|
||||
>
|
||||
Créer
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-secondary"
|
||||
onClick={onCancel}
|
||||
>
|
||||
Annuler
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function UploadContratBtn(
|
||||
{ mobId, hasContrat, onDone }: {
|
||||
mobId: number;
|
||||
hasContrat: boolean;
|
||||
onDone: () => Promise<void>;
|
||||
},
|
||||
) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
function upload() {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = "application/pdf";
|
||||
input.onchange = async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("contrat", file);
|
||||
const res = await fetch(`/mobility/api/mobilites/${mobId}/contrat`, {
|
||||
method: "POST",
|
||||
body: fd,
|
||||
});
|
||||
if (!res.ok) throw new Error("Erreur upload");
|
||||
await onDone();
|
||||
} catch {
|
||||
alert("Erreur lors de l'upload du contrat");
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-secondary"
|
||||
disabled={busy}
|
||||
onClick={upload}
|
||||
>
|
||||
{busy ? "..." : hasContrat ? "Remplacer contrat" : "Ajouter contrat"}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -3,14 +3,14 @@ import { AppProperties } from "$root/defaults/interfaces.ts";
|
||||
const properties: AppProperties = {
|
||||
name: "PolyMobility",
|
||||
icon: "flight_takeoff",
|
||||
hint: "Student mobility management",
|
||||
hint: "Suivi des mobilités internationales",
|
||||
pages: {
|
||||
index: "Homepage",
|
||||
overview: "Mobility overview",
|
||||
edit_mobility: "Mobility management",
|
||||
consult_students_test: "Test consult students",
|
||||
index: "Accueil",
|
||||
overview: "Suivi des mobilités",
|
||||
"my-mobility": "Ma mobilité",
|
||||
},
|
||||
adminOnly: ["edit_mobility", "consult_students_test"],
|
||||
adminOnly: ["overview"],
|
||||
studentOnly: ["my-mobility"],
|
||||
};
|
||||
|
||||
export default properties;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
import makeSlug from "$root/defaults/makeSlug.ts";
|
||||
export default makeSlug(import.meta.dirname!);
|
||||
@@ -1,122 +0,0 @@
|
||||
import { Handlers } from "$fresh/server.ts";
|
||||
import { db } from "$root/databases/db.ts";
|
||||
import { mobility, promotions, students } from "$root/databases/schema.ts";
|
||||
import { eq } from "npm:drizzle-orm@0.45.2";
|
||||
|
||||
export const handler: Handlers = {
|
||||
async GET() {
|
||||
try {
|
||||
const studentRows = await db
|
||||
.select({
|
||||
id: students.userId,
|
||||
firstName: students.firstName,
|
||||
lastName: students.lastName,
|
||||
promotionId: students.promotionId,
|
||||
endyear: promotions.endyear,
|
||||
current: promotions.current,
|
||||
})
|
||||
.from(students)
|
||||
.leftJoin(promotions, eq(students.promotionId, promotions.id));
|
||||
|
||||
const mobilityRows = await db.select().from(mobility);
|
||||
|
||||
const promotionRows = await db
|
||||
.select({
|
||||
id: promotions.id,
|
||||
endyear: promotions.endyear,
|
||||
current: promotions.current,
|
||||
})
|
||||
.from(promotions);
|
||||
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
mobilities: mobilityRows,
|
||||
students: studentRows,
|
||||
promotions: promotionRows,
|
||||
}),
|
||||
{ status: 200, headers: { "Content-Type": "application/json" } },
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Error fetching mobility data:", error);
|
||||
return new Response("Failed to fetch data", { status: 500 });
|
||||
}
|
||||
},
|
||||
|
||||
async POST(request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { data } = body;
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error("Invalid request body");
|
||||
}
|
||||
|
||||
for (const entry of data) {
|
||||
const {
|
||||
id,
|
||||
studentId,
|
||||
startDate,
|
||||
endDate,
|
||||
weeksCount,
|
||||
destinationCountry,
|
||||
destinationName,
|
||||
mobilityStatus = "N/A",
|
||||
} = entry;
|
||||
|
||||
const studentExists = await db
|
||||
.select({ userId: students.userId })
|
||||
.from(students)
|
||||
.where(eq(students.userId, studentId))
|
||||
.limit(1)
|
||||
.then((rows) => rows.length > 0);
|
||||
|
||||
if (!studentExists) {
|
||||
console.warn(`Skipping mobility for unknown studentId: ${studentId}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
let calculatedWeeksCount = weeksCount;
|
||||
if (startDate && endDate) {
|
||||
const start = new Date(startDate);
|
||||
const end = new Date(endDate);
|
||||
calculatedWeeksCount = start <= end
|
||||
? Math.ceil(
|
||||
(end.getTime() - start.getTime()) / (7 * 24 * 60 * 60 * 1000),
|
||||
)
|
||||
: null;
|
||||
}
|
||||
|
||||
await db
|
||||
.insert(mobility)
|
||||
.values({
|
||||
id,
|
||||
studentId,
|
||||
startDate,
|
||||
endDate,
|
||||
weeksCount: calculatedWeeksCount,
|
||||
destinationCountry,
|
||||
destinationName,
|
||||
mobilityStatus,
|
||||
})
|
||||
.onConflictDoUpdate({
|
||||
target: mobility.id,
|
||||
set: {
|
||||
startDate,
|
||||
endDate,
|
||||
weeksCount: calculatedWeeksCount,
|
||||
destinationCountry,
|
||||
destinationName,
|
||||
mobilityStatus,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return new Response("Data inserted/updated successfully", {
|
||||
status: 200,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error inserting mobility data:", error);
|
||||
return new Response("Failed to insert/update data", { status: 500 });
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
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<null, AuthenticatedState> = {
|
||||
// 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<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
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 });
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,149 @@
|
||||
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;
|
||||
|
||||
const NOT_FOUND = () =>
|
||||
new Response(
|
||||
JSON.stringify({ error: "Mobilité introuvable" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
|
||||
const FORBIDDEN = () => new Response(null, { status: 403 });
|
||||
|
||||
export const handler: Handlers<null, AuthenticatedState> = {
|
||||
// GET /mobilites/:idMob
|
||||
async GET(
|
||||
_request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
const row = await db
|
||||
.select()
|
||||
.from(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!row) return NOT_FOUND();
|
||||
|
||||
return new Response(JSON.stringify(row), {
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
},
|
||||
|
||||
// PUT /mobilites/:idMob (employee only)
|
||||
async PUT(
|
||||
request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
|
||||
return FORBIDDEN();
|
||||
}
|
||||
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { duree, ecole, pays, status, idStage } = body;
|
||||
|
||||
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" } },
|
||||
);
|
||||
}
|
||||
|
||||
if (duree !== undefined && (!Number.isInteger(duree) || duree < 1)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "duree doit être un entier >= 1" }),
|
||||
{ status: 400, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
const set: Record<string, unknown> = {};
|
||||
if (duree !== undefined) set.duree = duree;
|
||||
if (ecole !== undefined) set.ecole = ecole;
|
||||
if (pays !== undefined) set.pays = pays;
|
||||
if (status !== undefined) set.status = status;
|
||||
if (idStage !== undefined) {
|
||||
set.idStage = idStage;
|
||||
if (idStage) set.status = "validated";
|
||||
}
|
||||
|
||||
if (Object.keys(set).length === 0) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Au moins un champ à modifier requis" }),
|
||||
{ status: 400, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(mobilites)
|
||||
.set(set)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.returning();
|
||||
|
||||
if (!updated) return NOT_FOUND();
|
||||
|
||||
return new Response(JSON.stringify(updated), {
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
},
|
||||
|
||||
// DELETE /mobilites/:idMob (employee only)
|
||||
async DELETE(
|
||||
_request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
|
||||
return FORBIDDEN();
|
||||
}
|
||||
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
// Delete contract file if exists
|
||||
const row = await db
|
||||
.select({ contratMob: mobilites.contratMob })
|
||||
.from(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (row?.contratMob) {
|
||||
try {
|
||||
await Deno.remove(`uploads/contracts/${row.contratMob}`);
|
||||
} catch { /* file may not exist */ }
|
||||
}
|
||||
|
||||
const [deleted] = await db
|
||||
.delete(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.returning();
|
||||
|
||||
if (!deleted) return NOT_FOUND();
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,156 @@
|
||||
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 CONTRACTS_DIR = "uploads/contracts";
|
||||
|
||||
export const handler: Handlers<null, AuthenticatedState> = {
|
||||
// GET /mobilites/:idMob/contrat — download contract PDF
|
||||
async GET(
|
||||
_request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
const row = await db
|
||||
.select({ contratMob: mobilites.contratMob })
|
||||
.from(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!row) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Mobilité introuvable" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
if (!row.contratMob) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Aucun contrat pour cette mobilité" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const file = await Deno.readFile(`${CONTRACTS_DIR}/${row.contratMob}`);
|
||||
return new Response(file, {
|
||||
headers: {
|
||||
"Content-Type": "application/pdf",
|
||||
"Content-Disposition": `inline; filename="${row.contratMob}"`,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Fichier contrat introuvable" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
// POST /mobilites/:idMob/contrat — upload contract PDF
|
||||
async POST(
|
||||
request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
// Check mobility exists
|
||||
const row = await db
|
||||
.select({ id: mobilites.id })
|
||||
.from(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!row) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Mobilité introuvable" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
const formData = await request.formData();
|
||||
const file = formData.get("contrat");
|
||||
|
||||
if (!file || !(file instanceof File)) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Fichier 'contrat' requis (PDF)" }),
|
||||
{ status: 400, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
if (file.type !== "application/pdf") {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Le fichier doit être un PDF" }),
|
||||
{ status: 400, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
const filename = `mob_${idMob}.pdf`;
|
||||
await Deno.mkdir(CONTRACTS_DIR, { recursive: true });
|
||||
await Deno.writeFile(
|
||||
`${CONTRACTS_DIR}/${filename}`,
|
||||
new Uint8Array(await file.arrayBuffer()),
|
||||
);
|
||||
|
||||
const [updated] = await db
|
||||
.update(mobilites)
|
||||
.set({ contratMob: filename })
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.returning();
|
||||
|
||||
return new Response(JSON.stringify(updated), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
},
|
||||
|
||||
// DELETE /mobilites/:idMob/contrat — remove contract (employee only)
|
||||
async DELETE(
|
||||
_request: Request,
|
||||
context: FreshContext<AuthenticatedState>,
|
||||
): Promise<Response> {
|
||||
if (context.state.session.eduPersonPrimaryAffiliation !== "employee") {
|
||||
return new Response(null, { status: 403 });
|
||||
}
|
||||
|
||||
const idMob = Number(context.params.idMob);
|
||||
if (isNaN(idMob)) {
|
||||
return new Response("Paramètre idMob invalide", { status: 400 });
|
||||
}
|
||||
|
||||
const row = await db
|
||||
.select({ contratMob: mobilites.contratMob })
|
||||
.from(mobilites)
|
||||
.where(eq(mobilites.id, idMob))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (!row) {
|
||||
return new Response(
|
||||
JSON.stringify({ error: "Mobilité introuvable" }),
|
||||
{ status: 404, headers: { "content-type": "application/json" } },
|
||||
);
|
||||
}
|
||||
|
||||
if (row.contratMob) {
|
||||
try {
|
||||
await Deno.remove(`${CONTRACTS_DIR}/${row.contratMob}`);
|
||||
} catch { /* file may not exist */ }
|
||||
}
|
||||
|
||||
await db
|
||||
.update(mobilites)
|
||||
.set({ contratMob: null })
|
||||
.where(eq(mobilites.id, idMob));
|
||||
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
};
|
||||
@@ -1,21 +0,0 @@
|
||||
import ConsultStudents_test from "$root/routes/(apps)/mobility/(_islands)/ConsultStudents_test.tsx";
|
||||
import {
|
||||
getPartialsConfig,
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
//import EditStudents from "../(_islands)/EditStudents.tsx";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async function Mobility(_request: Request, _context: FreshContext<State>) {
|
||||
return (
|
||||
<>
|
||||
<h1>Test consult students</h1>
|
||||
<ConsultStudents_test />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config = getPartialsConfig();
|
||||
export default makePartials(Mobility);
|
||||
@@ -1,20 +0,0 @@
|
||||
import EditMobility from "$root/routes/(apps)/mobility/(_islands)/EditMobility.tsx";
|
||||
import {
|
||||
getPartialsConfig,
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async function Mobility(_request: Request, _context: FreshContext<State>) {
|
||||
return (
|
||||
<>
|
||||
<h1>Edit mobility</h1>
|
||||
<EditMobility />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const config = getPartialsConfig();
|
||||
export default makePartials(Mobility);
|
||||
@@ -3,11 +3,27 @@ import {
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
export async function Index(_request: Request, context: FreshContext<State>) {
|
||||
return <h2>Welcome to {context.state.session?.displayName}.</h2>;
|
||||
export async function Index(
|
||||
_request: Request,
|
||||
context: FreshContext<State>,
|
||||
) {
|
||||
return (
|
||||
<div class="page-content">
|
||||
<h2 class="page-title">Mobilité internationale</h2>
|
||||
<p>
|
||||
Bienvenue{" "}
|
||||
<strong>
|
||||
{(context.state as unknown as { session: Record<string, string> })
|
||||
.session.displayName}
|
||||
</strong>
|
||||
.
|
||||
</p>
|
||||
<p>Suivi des mobilités : 12 semaines validées requises par élève.</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const config = getPartialsConfig();
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
import ConsultMobility from "$root/routes/(apps)/mobility/(_islands)/ConsultMobility.tsx";
|
||||
import {
|
||||
getPartialsConfig,
|
||||
makePartials,
|
||||
} from "$root/defaults/makePartials.tsx";
|
||||
import { FreshContext } from "$fresh/server.ts";
|
||||
import { State } from "$root/routes/_middleware.ts";
|
||||
import { State } from "$root/defaults/interfaces.ts";
|
||||
import MobilityOverview from "../(_islands)/MobilityOverview.tsx";
|
||||
|
||||
// deno-lint-ignore require-await
|
||||
async function Mobility(_request: Request, _context: FreshContext<State>) {
|
||||
return (
|
||||
<>
|
||||
<h1>Edit mobility</h1>
|
||||
<ConsultMobility />
|
||||
</>
|
||||
);
|
||||
async function Overview(
|
||||
_request: Request,
|
||||
_context: FreshContext<State>,
|
||||
) {
|
||||
return <MobilityOverview />;
|
||||
}
|
||||
|
||||
export { Overview as Page };
|
||||
export const config = getPartialsConfig();
|
||||
export default makePartials(Mobility);
|
||||
export default makePartials(Overview);
|
||||
|
||||
Reference in New Issue
Block a user