import { collection, getDocs, getDoc } from "firebase/firestore"; import { db } from "../firebase_config"; import { Timestamp } from "firebase/firestore"; import { Chantier, User, Ressources, Reservation } from "../class/class"; export async function getUsers(): Promise { try { const colRef = collection(db, "user"); const snapshot = await getDocs(colRef); return snapshot.docs.map((doc) => { const data = doc.data(); return { ...data, allocation: data.allocation?.map(convertReservation) || [], } as User; }); } catch (err) { console.error("Firestore Users Error:", err); return []; } } export async function getRessources(): Promise { try { const colRef = collection(db, "ressources"); const snapshot = await getDocs(colRef); return snapshot.docs.map((doc) => { const data = doc.data(); return { ...data, allocation: data.allocation?.map(convertReservation) || [], } as Ressources; }); } catch (err) { console.error("Firestore Ressources Error:", err); return []; } } export async function getChantiers(): Promise { const snap = await getDocs(collection(db, "chantiers")); const chantiers: Chantier[] = []; for (const docSnap of snap.docs) { const data = docSnap.data(); const dateDep = data.dateDep instanceof Timestamp ? data.dateDep.toDate() : new Date(data.dateDep); let chef: User | null = null; if (data.chef) { const chefSnap = await getDoc(data.chef); if (chefSnap.exists()) { chef = chefSnap.data() as User; } } let equipe: User[] = []; if (Array.isArray(data.equipe)) { equipe = await Promise.all( data.equipe.map(async (ref: any) => { const snap = await getDoc(ref); return snap.exists() ? (snap.data() as User) : null; }) ).then(list => list.filter(x => x !== null)) as User[]; } chantiers.push({ ...data, dateDep, chef, equipe } as Chantier); } return chantiers; } function convertReservation(res: any): Reservation { return { id: res.id, dateChantier: res.dateChantier instanceof Timestamp ? res.dateChantier.toDate() : new Date(res.dateChantier), dateFin: res.dateFin instanceof Timestamp ? res.dateFin.toDate() : new Date(res.dateFin), }; }