borrow and return Ressource -- need to test
This commit is contained in:
24
services/borrowRessource.ts
Normal file
24
services/borrowRessource.ts
Normal file
@@ -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),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
21
services/returnRessource.ts
Normal file
21
services/returnRessource.ts
Normal file
@@ -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),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user