From 7b4e2c1130d3c4bf175162c6cfa51a0959f90502 Mon Sep 17 00:00:00 2001 From: Rochas Date: Sun, 14 Dec 2025 15:00:11 +0100 Subject: [PATCH] gestion des ressources fonctionnelle, mais pas fini --- README.md | 34 ++++- app/(tabs)/home.tsx | 2 + app/ContextReservation.tsx | 33 ++++ app/_layout.tsx | 28 ++-- class/class.tsx | 2 +- class/utils.tsx | 31 ++++ components/add/addRessource.tsx | 107 ++++++------- components/add/select/ressourceSummary.tsx | 27 +++- components/anomaly.tsx | 6 +- components/chantierSummary.tsx | 14 +- components/selectChantier.tsx | 4 +- services/ressourcesService.ts | 168 +++++++++++++-------- 12 files changed, 308 insertions(+), 148 deletions(-) create mode 100644 app/ContextReservation.tsx create mode 100644 class/utils.tsx diff --git a/README.md b/README.md index 552565d..59ae7d6 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ Lien du git : gitlab2.istic.univ-rennes1.fr/trochas/mmm-projet -Différentes commandes a effectuer pour lancer le projet: + +#### Différentes commandes a effectuer pour lancer le projet: npx expo install react-native-maps@1.9.0 npm install react-native-maps @react-navigation/native @react-navigation/bottom-tabs react-native-safe-area-context react-native-screens firebase @@ -20,4 +21,33 @@ npm install @react-native-community/datetimepicker npx expo install expo-image-picker npx expo install expo-location -npx expo start \ No newline at end of file +npx expo start + + +#### Présentation de l'application : + +##### 5 écrans : +Accuil : +- Affiche le chantier sélectionné : + - Résumé du chantier + - état éditable par l'utilisateur + - Liste d'anomalies, possibilité d'en ajouter ou de les supprimer +- Sélectionner un chantier via le bouton en haut à gauche. + +Ressources : + +Ouvriers : + +MapScreen : + +Ajouter : +Permet d'ajouter un chantier ou une ressource (ouvrier,véhicule,outil) +##### Fonctionnalité manquante : + +Par manque de temps nous n'avons pas peu finnalité certaine fonctionnalité + +- possibilité de modifier les ressources d'un chantier (ex: réajustement des besoins) +- modifier la quantité totale d'une ressource (ex: restock de ressources) +- gestion des stocks non finalisée : + Un chantier comptabilise du stock uniquement quand il est "En cours", s'il est dans un autre été, ses réservations ne sont pas comptabilisées, donc les autres chantiers peuvent utiliser le stock libéré. Si on le remet l'état à "En cours" et que le stock n'est pas suffisant, alors la quantité disponible du stock passe en négatif. + Ce problème peut être corrigé en bloquant le changement d'état si la quantité de stock n'est pas suffisante, mais aurait besoin de la possibilité de modifier les ressources du chantier, ou la quantité des ressources. \ No newline at end of file diff --git a/app/(tabs)/home.tsx b/app/(tabs)/home.tsx index a9af9b7..fd502d8 100644 --- a/app/(tabs)/home.tsx +++ b/app/(tabs)/home.tsx @@ -23,9 +23,11 @@ export default function Home() { + {chantier&& + } diff --git a/app/ContextReservation.tsx b/app/ContextReservation.tsx new file mode 100644 index 0000000..c0805e4 --- /dev/null +++ b/app/ContextReservation.tsx @@ -0,0 +1,33 @@ +import { Reservation } from "@/class/class"; +import { createContext, ReactNode, useContext, useMemo, useState } from "react"; + +type ReservationContextType = { + reservations: Reservation[]; + setReservations: (list: Reservation[]) => void; +}; + +const ReservationsContext = createContext(null); + +type ReservationsProviderProps = { + children: ReactNode; +}; + +export const ReservationsProvider = ({ children }: ReservationsProviderProps) => { + const [reservations, setReservations] = useState([]); + + const value = useMemo(() => ({ reservations, setReservations }), [reservations]); + + return ( + + {children} + + ); +}; + +export const useReservations = () => { + const context = useContext(ReservationsContext); + if (!context) { + throw new Error("useRessources doit être utilisé dans "); + } + return context; +}; \ No newline at end of file diff --git a/app/_layout.tsx b/app/_layout.tsx index 6f6e328..a036b39 100644 --- a/app/_layout.tsx +++ b/app/_layout.tsx @@ -16,9 +16,11 @@ import { Platform, UIManager } from 'react-native'; import { ChantierProvider } from "./ContextChantier"; import { UserProvider } from "./ContextUser"; import { RessourcesProvider } from "./ContextRessource"; +import { ReservationsProvider } from "./ContextReservation"; import LoginScreen from "./login/login"; + export const unstable_settings = { anchor: "(tabs)", }; @@ -60,18 +62,20 @@ export default function RootLayout() { - - - - - - - - - + + + + + + + + + + + diff --git a/class/class.tsx b/class/class.tsx index 0bb40f2..e25ef99 100644 --- a/class/class.tsx +++ b/class/class.tsx @@ -27,7 +27,7 @@ export type User = { export type Ressources = { id: string; name: string; - type: string; //"machine","outil","ouvrier" + type: string; //"Machine","Outil","Ouvrier" Image: string; quantity: number; available_quantity: number; diff --git a/class/utils.tsx b/class/utils.tsx new file mode 100644 index 0000000..e06ad30 --- /dev/null +++ b/class/utils.tsx @@ -0,0 +1,31 @@ +import { Reservation,Chantier,User, Ressources } from "./class"; + +export function getNbItemReservation(reservations:Reservation[]):number{ + var res = 0; + reservations.forEach(reserv => { + res += reserv.quantity; + }); + return res; +} + + +export function getReservationOfRessource(ressource:Ressources, allReservations:Reservation[]):Reservation[]{ + const res:Reservation[] = []; + allReservations.forEach(reserv => { + if(reserv.ressource.name===ressource.name){ + res.push(reserv); + } + }); + return res; +} + + +export function getNbUseRessources(ressource:Ressources, allReservations:Reservation[]):number{ + var res:number = 0; + getReservationOfRessource(ressource,allReservations).forEach(reserv => { + if(reserv.chantier.etat==="En cours"){ + res+=reserv.quantity; + } + }) + return res; +} \ No newline at end of file diff --git a/components/add/addRessource.tsx b/components/add/addRessource.tsx index 7962432..50d94c8 100644 --- a/components/add/addRessource.tsx +++ b/components/add/addRessource.tsx @@ -52,73 +52,74 @@ export default function AddRessource({ressourceType, ...otherProps }: Props) { const [quantiteDisponible,setQuantiteDisponible] = useState(''); const [openConfirmation,setOpenConfirmation] = useState(false); - async function handleAddRessource() { + async function handleAddRessource() { setLoading(true); setOpenConfirmation(true); } - async function onConfirm(): Promise { - if(isValidRessource()){ - try{ - setLoading(true); - const nouvelleRessource : Ressources = { - id : '', - name: nom, - type : ressourceType, - quantity : parseInt(quantite), - available_quantity : parseInt(quantite), - Image : "", - allocation : [], - }; - const id = await addRessources(nouvelleRessource); + async function onConfirm(): Promise { + if(isValidRessource()){ + try{ + setLoading(true); + const nouvelleRessource : Ressources = { + id : '', + name: nom, + type : ressourceType, + quantity : parseInt(quantite), + available_quantity : parseInt(quantite), + Image : "", + allocation : [], + }; + const id = await addRessources(nouvelleRessource); - if(id){ - setRessources([...ressources,{...nouvelleRessource, id}]); - setOpenConfirmation(false); - setNom(''); - setQuantite(''); - setQuantiteDisponible(''); - } - }catch(error){ - }finally{ + if(id){ + setRessources([...ressources,{...nouvelleRessource, id}]); setOpenConfirmation(false); - setLoading(false); + setNom(''); + setQuantite(''); + setQuantiteDisponible(''); } + }catch(error){ + }finally{ + setOpenConfirmation(false); + setLoading(false); } } + } + + function onCancel(): void { + setOpenConfirmation(false); + } - function onCancel(): void { - setOpenConfirmation(false); - } function isValidRessource():Boolean{ return nom!= "" && quantite != "" } - const renderValidationScreen = () => { - return( - - - - Créer la nouvelle ressource {ressourceType} suivante ? : - - Nom: {nom===''?"NONE":nom} - Quantité Total: {quantite===''?"0":quantite} - - - onConfirm()}> - Confirmer - - - - onCancel()}> - Annuler - - + const renderValidationScreen = () => { + return( + + + + Créer la nouvelle ressource {ressourceType} suivante ? : + + Nom: {nom===''?"NONE":nom} + Quantité Total: {quantite===''?"0":quantite} - - - ) - } + + onConfirm()}> + Confirmer + + + + onCancel()}> + Annuler + + + + + + ) + } const renderInut = (name : string, preFill : string, value : string, setValue : ((text:string) => void),numeric:boolean) => { return ( @@ -129,7 +130,7 @@ export default function AddRessource({ressourceType, ...otherProps }: Props) { ); }; -return ( + return ( {editMode && diff --git a/components/add/select/ressourceSummary.tsx b/components/add/select/ressourceSummary.tsx index 2013e06..96a3b24 100644 --- a/components/add/select/ressourceSummary.tsx +++ b/components/add/select/ressourceSummary.tsx @@ -1,9 +1,12 @@ import { Chantier, Ressources } from '@/class/class'; import { ThemedView, } from '@/components/theme/themed-view'; -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import { Image, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'; import { ThemedText } from '@/components/theme/themed-text'; import { ThemedButton } from '@/components/theme/themed-button'; +import { getNbUseRessources } from '@/class/utils'; +import { useReservations } from '@/app/ContextReservation'; +import { getReservations } from '@/services/ressourcesService'; type RessourcesQte = [Ressources, number]; @@ -16,11 +19,11 @@ type Props = { export default function RessourceSummary({ressource: ressource,qte,style,sendRessource: sendRessource, ...otherProps }: Props) { - + const { reservations, setReservations } = useReservations(); const [count,setCount] = useState(qte); function onPressAdd(ressource: Ressources): void { - if(count { + async function loadReservations() { + const list = await getReservations(); + setReservations(list); + } + + loadReservations(); + }, []); + + return( - {ressource.id} - {ressource.name} - {ressource.quantity} - {ressource.type} + Nom : {ressource.name} + Restant : {ressource.quantity-getNbUseRessources(ressource,reservations)}/{ressource.quantity} onPressAdd(ressource)}> + - {count}/{ressource.quantity} + {count}/{ressource.quantity-getNbUseRessources(ressource,reservations)} onPressSub(ressource)}> - diff --git a/components/anomaly.tsx b/components/anomaly.tsx index 6d2be82..64b6506 100644 --- a/components/anomaly.tsx +++ b/components/anomaly.tsx @@ -67,10 +67,10 @@ export default function Anomaly({data,style}: Props) { - Ajouter + Ajouter - Choisir une image + Choisir une image {imageUri && ( @@ -151,13 +151,11 @@ const styles = StyleSheet.create({ marginRight: 8, }, addButton: { - color: "white", paddingVertical: 8, paddingHorizontal: 12, borderRadius: 8, }, addButtonText: { - color: "white", fontWeight: "bold", }, image: { width: 200, height: 200, borderRadius: 10 } diff --git a/components/chantierSummary.tsx b/components/chantierSummary.tsx index b44e544..e49c425 100644 --- a/components/chantierSummary.tsx +++ b/components/chantierSummary.tsx @@ -3,6 +3,7 @@ import { ThemedView, } from '@/components/theme/themed-view'; import React from 'react'; import { Image, StyleProp, StyleSheet, View, ViewStyle } from 'react-native'; import { ThemedText } from './theme/themed-text'; +import { getNbItemReservation } from '@/class/utils'; type Props = { data: { @@ -20,9 +21,20 @@ export default function ChantierSummary({data,style , ...otherProps }: Props) { + Id: {data.chantier.id} + Objet: {data.chantier.name} Adresse: {data.chantier.adresse} Chef de chantier: {data.chantier.chef.last_name}{" "}{data.chantier.chef.name} État: {data.chantier.etat} + equipe: + {getNbItemReservation(data.chantier.equipe)} ({data.chantier.equipe.length} type{data.chantier.equipe.length>1&&"s"}) + + materiel: + {getNbItemReservation(data.chantier.materiel)} ({data.chantier.materiel.length} type{data.chantier.materiel.length>1&&"s"}) + + vehicules: + {getNbItemReservation(data.chantier.vehicules)} ({data.chantier.vehicules.length} type{data.chantier.vehicules.length>1&&"s"}) + ) : @@ -42,7 +54,7 @@ const styles = StyleSheet.create({ borderRadius: 10, //borderWidth: 1, flexDirection: 'row', - height: 150, + //height: 150, gap: 10, }, image:{ diff --git a/components/selectChantier.tsx b/components/selectChantier.tsx index a7d32a5..c02f8db 100644 --- a/components/selectChantier.tsx +++ b/components/selectChantier.tsx @@ -65,14 +65,14 @@ export default function SelectChantier() { open.value = withTiming(isOpen ? 1 : 0); }, [isOpen]); - useEffect(() => { + /*useEffect(() => { async function loadChantiers() { const list = await getChantiers(); setChantiers(list); } loadChantiers(); - }, []); + }, []);*/ const filteredChantiers = chantiers.filter((chantier) => { var keyWords:string[] = search.toLowerCase().split(" ") ; diff --git a/services/ressourcesService.ts b/services/ressourcesService.ts index ac7ed0d..67f2a76 100644 --- a/services/ressourcesService.ts +++ b/services/ressourcesService.ts @@ -1,4 +1,4 @@ -import { addDoc, arrayUnion, collection, doc, Firestore, getDoc, getDocs, Timestamp, updateDoc, DocumentReference } from "firebase/firestore"; +import { addDoc, arrayUnion, collection, doc, Firestore, getDoc, getDocs, Timestamp, updateDoc, DocumentReference, query, where } from "firebase/firestore"; import { Chantier, Reservation, Ressources, User } from "../class/class"; import { db } from "../firebase_config"; @@ -53,67 +53,100 @@ export async function addRessources(ressourceData: Omit): Prom } ///////////////////////////////////CHANTIER///////////////////////////////// export async function getChantiers(): Promise { - const snap = await getDocs(collection(db, "chantier")); const chantiers: Chantier[] = []; + try { + const snap = await getDocs(collection(db, "chantier")); - for (const docSnap of snap.docs) { - const data = docSnap.data(); - //Faut convertir les Timestamp en Date ( merci à firebase :) ) - 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: Reservation[] = []; - 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 Reservation) : null; - }) - ).then(list => list.filter(x => x !== null)) as Reservation[]; - } + - let vehicules: Reservation[] = []; - if (Array.isArray(data.vehicules)) { - vehicules = await Promise.all( - data.vehicules.map(async (ref: any) => { - const snap = await getDoc(ref); - return snap.exists() ? (snap.data() as Reservation) : null; - }) - ).then(list => list.filter(x => x !== null)) as Reservation[]; - } + for (const docSnap of snap.docs) { + try { + const data = docSnap.data(); + //Faut convertir les Timestamp en Date ( merci à firebase :) ) + 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; + } + } + const equipe:Reservation[] = []; + const vehicules:Reservation[] = []; + const materiel:Reservation[] = []; + const all:Reservation[] = await getReservationsByChantier(docSnap.id); - let materiel: Reservation[] = []; - if (Array.isArray(data.materiel)) { - materiel = await Promise.all( - data.materiel.map(async (ref: any) => { - const snap = await getDoc(ref); - return snap.exists() ? (snap.data() as Reservation) : null; - }) - ).then(list => list.filter(x => x !== null)) as Reservation[]; - } - */ - var equipe:Reservation[] = []; - var vehicules:Reservation[] = []; - var materiel:Reservation[] = []; - chantiers.push({ - ...data, - id: docSnap.id, - dateDep, - chef, - equipe, - vehicules, - materiel, - } as Chantier); + all.forEach(element => { + if(element.ressource.type==="Ouvrier"){ + equipe.push(element) + } + else if(element.ressource.type==="Machine"){ + vehicules.push(element) + } + else if(element.ressource.type==="Outil"){ + materiel.push(element) + } + }); + + chantiers.push({ + ...data, + id: docSnap.id, + dateDep, + chef, + equipe, + vehicules, + materiel, + } as Chantier); + } catch (error) { + console.error("Erreur lors de la lecture d'un chantiers : " + error); + //alert("Erreur lors de la lecture d'un chantiers : " + error); } + } return chantiers; + } catch (error) { + alert("Erreur lors de la lecture des chantiers : " + error); + } + return chantiers } +//récupère les reservations d'un chantier +export async function getReservationsByChantier(chantierId: string): Promise { + const q = query( + collection(db, "Reservation"), + where("chantier", "==", doc(db, "chantier", chantierId)), + ); + + const snap = await getDocs(q); + + const results = await Promise.all( + snap.docs.map(convertReservation) + ); + + return results.filter( + (r): r is Reservation => r !== null + ); +} + +///////////////////////////////////RESERVATION///////////////////////////////// +export async function getReservations(): Promise { + try { + const snap = await getDocs(collection(db, "Reservation")); + + const results = await Promise.all( + snap.docs.map(convertReservation) + ); + + return results.filter( + (r): r is Reservation => r !== null + ); + + } catch (error) { + console.error("Erreur lors de la lecture des Reservations : " + error); + return []; + } +} + + //CHANGE CHANTIER STATUS export async function changeChantierStatus(chantierId: string, newStatus: string): Promise { try { @@ -177,18 +210,23 @@ type ReservationFirestore = { quantity: number; }; -async function convertReservation(res: any): Promise { +async function convertReservation(res: any): Promise { + try { + const data = res.data() as ReservationFirestore; - const data = res.data() as ReservationFirestore; - const chantierSnap = await getDoc(data.chantier as DocumentReference); - const ressourceSnap = await getDoc(data.ressource as DocumentReference); + const chantierSnap = await getDoc(data.chantier as DocumentReference); + const ressourceSnap = await getDoc(data.ressource as DocumentReference); - return { - id: res.id, - chantier: chantierSnap.data() as Chantier, - ressource: ressourceSnap.data() as Ressources, - quantity: data.quantity, - }; + return { + id: res.id, + chantier: chantierSnap.data() as Chantier, + ressource: ressourceSnap.data() as Ressources, + quantity: data.quantity, + }; + } catch (err) { + console.warn("Reservation ignorée :", res.id , err); + return null; + } } @@ -201,7 +239,7 @@ export async function sendNewChantier(chantier:Chantier): Promise { adresse:chantier.adresse, etat:chantier.etat, contact:chantier.contact, - chef: doc(db, "users", chantier.chef.id), //un objet déjà dans la base de donné + chef: doc(db, "user", chantier.chef.id), //un objet déjà dans la base de donné date: Timestamp.fromDate(chantier.dateDep), tempsEst: chantier.tempsEst, anomalies: chantier.anomalies ?? [], //strings[]