Files
mmm-projet/services/borrowRessource.ts
2025-12-13 12:02:20 +01:00

25 lines
1014 B
TypeScript

import { Ressources } from "@/class/class";
import { db } from "@/firebase_config";
import { doc, runTransaction, increment, arrayUnion } from "firebase/firestore";
export async function borrowRessource(chantierId: string, ressource: Ressources, quantity: number) {
const chantierRef = doc(db, "chantier", chantierId);
const ressourceRef = doc(db, "ressources", ressource.id.toString());
await runTransaction(db, async (transaction) => {
const resSnap = await transaction.get(ressourceRef);
if (!resSnap.exists()) throw new Error("Ressource not found");
const available = resSnap.data().available_quantity;
if (available < quantity) throw new Error("Not enough quantity available");
transaction.update(ressourceRef, {
available_quantity: increment(-quantity),
});
const borrowed: Ressources = { ...ressource, quantity };
transaction.update(chantierRef, {
vehicules: arrayUnion(borrowed),
});
});
}