Trying to make EditMobility works

This commit is contained in:
Clayzxr
2025-01-24 19:46:53 +01:00
parent f07b4dc616
commit c3d3354537
+149 -133
View File
@@ -1,10 +1,20 @@
import { useEffect, useState } from "preact/hooks"; import { useEffect, useState } from "preact/hooks";
interface MobilityData { interface Student {
id: number; id: string;
studentId: string;
firstName: string; firstName: string;
lastName: string; lastName: string;
promotionId: number;
}
interface Promotion {
id: number;
name: string;
}
interface Mobility {
id: number;
studentId: string;
startDate: string | null; startDate: string | null;
endDate: string | null; endDate: string | null;
weeksCount: number | null; weeksCount: number | null;
@@ -14,12 +24,13 @@ interface MobilityData {
} }
export default function EditMobility() { export default function EditMobility() {
const [mobilityData, setMobilityData] = useState<MobilityData[]>([]); const [data, setData] = useState<{ promotions?: Promotion[]; students?: Student[]; mobilities?: Mobility[] } | null>(null);
const [error, setError] = useState<string | null>(null);
const [isSaving, setIsSaving] = useState(false); const [isSaving, setIsSaving] = useState(false);
useEffect(() => { useEffect(() => {
const fetchMobilityData = async () => { const fetchData = async () => {
console.log("EditMobility: Fetching mobility data..."); console.log("EditMobility: Fetching data from API...");
try { try {
const response = await fetch("/mobility/api/insert_mobility"); const response = await fetch("/mobility/api/insert_mobility");
console.log("EditMobility: API response status:", response.status); console.log("EditMobility: API response status:", response.status);
@@ -28,33 +39,54 @@ export default function EditMobility() {
throw new Error(`Error fetching data: ${response.statusText}`); throw new Error(`Error fetching data: ${response.statusText}`);
} }
const data = await response.json(); const result = await response.json();
console.log("EditMobility: Data fetched successfully:", data); console.log("EditMobility: Data fetched successfully:", result);
setMobilityData(data.mobilities || []); setData(result);
} catch (err) { } catch (err) {
console.error("EditMobility: Error fetching data:", err); console.error("EditMobility: Error fetching data:", err);
setError("Failed to load mobility data. Please try again later.");
} }
}; };
fetchMobilityData(); 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) {
return { ...mobility, [field]: value };
}
return mobility;
}) || [];
return { ...prevData, mobilities: updatedMobilities };
});
};
const handleSave = async () => { const handleSave = async () => {
console.log("EditMobility: Saving data...");
setIsSaving(true); setIsSaving(true);
try { try {
const response = await fetch("/mobility/api/insert_mobility", { const response = await fetch("/mobility/api/insert_mobility", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: mobilityData }), body: JSON.stringify({ data: data?.mobilities }),
}); });
console.log("EditMobility: Save response status:", response.status); console.log("EditMobility: Save response status:", response.status);
if (response.ok) { if (response.ok) {
console.log("EditMobility: Data saved successfully.");
alert("Data saved successfully!"); alert("Data saved successfully!");
window.location.reload(); // Refresh the page to load updated data
} else { } else {
throw new Error(`Failed to save data: ${response.statusText}`); throw new Error(`Failed to save data: ${response.statusText}`);
} }
@@ -66,128 +98,112 @@ export default function EditMobility() {
} }
}; };
if (error) {
return <p className="error">{error}</p>;
}
if (!data?.promotions) {
return <p>Loading data...</p>;
}
return ( return (
<div> <section>
<table> <h2>Edit Mobility</h2>
<thead> {data.promotions.map((promo) => (
<tr> <div key={promo.id}>
<th>First Name</th> <h3>Promotion: {promo.name}</h3>
<th>Last Name</th> <table>
<th>Start Date</th> <thead>
<th>End Date</th> <tr>
<th>Weeks Count</th> <th>ID</th>
<th>Destination Country</th> <th>First Name</th>
<th>Destination Name</th> <th>Last Name</th>
<th>Status</th> <th>Start Date</th>
</tr> <th>End Date</th>
</thead> <th>Weeks Count</th>
<tbody> <th>Destination Country</th>
{mobilityData.map((mobility) => ( <th>Destination Name</th>
<tr key={mobility.id}> <th>Status</th>
<td>{mobility.firstName}</td> </tr>
<td>{mobility.lastName}</td> </thead>
<td> <tbody>
<input {data.students
type="date" ?.filter((student) => student.promotionId === promo.id)
value={mobility.startDate || ""} .map((student) => {
onChange={(e) => const mobility = data.mobilities?.find((mob) => mob.studentId === student.id) || {
setMobilityData((prev) => studentId: student.id,
prev.map((entry) => startDate: null,
entry.id === mobility.id endDate: null,
? { ...entry, startDate: e.target.value } weeksCount: null,
: entry destinationCountry: null,
) destinationName: null,
) mobilityStatus: "N/A",
} };
/>
</td> return (
<td> <tr key={student.id}>
<input <td>{student.id}</td>
type="date" <td>{student.firstName}</td>
value={mobility.endDate || ""} <td>{student.lastName}</td>
onChange={(e) => <td>
setMobilityData((prev) => <input
prev.map((entry) => type="date"
entry.id === mobility.id value={mobility.startDate || ""}
? { ...entry, endDate: e.target.value } onChange={(e) => handleChange(student.id, "startDate", e.target.value)}
: entry />
) </td>
) <td>
} <input
/> type="date"
</td> value={mobility.endDate || ""}
<td> onChange={(e) => handleChange(student.id, "endDate", e.target.value)}
<input />
type="number" </td>
value={mobility.weeksCount || ""} <td>
onChange={(e) => <input
setMobilityData((prev) => type="number"
prev.map((entry) => value={mobility.weeksCount || ""}
entry.id === mobility.id onChange={(e) =>
? { ...entry, weeksCount: Number(e.target.value) || null } handleChange(student.id, "weeksCount", Number(e.target.value) || null)
: entry }
) />
) </td>
} <td>
/> <input
</td> type="text"
<td> value={mobility.destinationCountry || ""}
<input onChange={(e) => handleChange(student.id, "destinationCountry", e.target.value)}
type="text" />
value={mobility.destinationCountry || ""} </td>
onChange={(e) => <td>
setMobilityData((prev) => <input
prev.map((entry) => type="text"
entry.id === mobility.id value={mobility.destinationName || ""}
? { ...entry, destinationCountry: e.target.value } onChange={(e) => handleChange(student.id, "destinationName", e.target.value)}
: entry />
) </td>
) <td>
} <select
/> value={mobility.mobilityStatus}
</td> onChange={(e) => handleChange(student.id, "mobilityStatus", e.target.value)}
<td> >
<input <option value="N/A">N/A</option>
type="text" <option value="Planned">Planned</option>
value={mobility.destinationName || ""} <option value="In Progress">In Progress</option>
onChange={(e) => <option value="Completed">Completed</option>
setMobilityData((prev) => <option value="Validated">Validated</option>
prev.map((entry) => </select>
entry.id === mobility.id </td>
? { ...entry, destinationName: e.target.value } </tr>
: entry );
) })}
) </tbody>
} </table>
/> </div>
</td> ))}
<td>
<select
value={mobility.mobilityStatus}
onChange={(e) =>
setMobilityData((prev) =>
prev.map((entry) =>
entry.id === mobility.id
? { ...entry, mobilityStatus: e.target.value }
: entry
)
)
}
>
<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>
<button onClick={handleSave} disabled={isSaving}> <button onClick={handleSave} disabled={isSaving}>
{isSaving ? "Saving..." : "Save Changes"} {isSaving ? "Saving..." : "Confirm"}
</button> </button>
</div> </section>
); );
} }