From 91fe9f849b6efd4e8348a3552dc6fdb618a0372b Mon Sep 17 00:00:00 2001 From: tuanvu Date: Sat, 13 Dec 2025 12:02:20 +0100 Subject: [PATCH] borrow and return Ressource -- need to test --- services/borrowRessource.ts | 24 ++++++++++++++++++++++++ services/returnRessource.ts | 21 +++++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 services/borrowRessource.ts create mode 100644 services/returnRessource.ts diff --git a/services/borrowRessource.ts b/services/borrowRessource.ts new file mode 100644 index 0000000..3abe69f --- /dev/null +++ b/services/borrowRessource.ts @@ -0,0 +1,24 @@ +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), + }); + }); +} diff --git a/services/returnRessource.ts b/services/returnRessource.ts new file mode 100644 index 0000000..9e0c24b --- /dev/null +++ b/services/returnRessource.ts @@ -0,0 +1,21 @@ +import { Ressources } from "@/class/class"; +import { db } from "@/firebase_config"; +import { arrayRemove, doc, increment, runTransaction } from "firebase/firestore"; + +export async function returnRessource(chantierId: string, ressource: Ressources) { + 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"); + + transaction.update(ressourceRef, { + available_quantity: increment(ressource.quantity), + }); + + transaction.update(chantierRef, { + vehicules: arrayRemove(ressource), + }); + }); +} \ No newline at end of file