From 4bb6633568f8fc37d2389e16e4ef5ed9e1284b37 Mon Sep 17 00:00:00 2001 From: eribe255 <eribe255@student.liu.se> Date: Wed, 6 Dec 2023 14:03:54 +0100 Subject: [PATCH] update db --- client/Database/database.js | 2027 ++++++++++++++++------------------- 1 file changed, 906 insertions(+), 1121 deletions(-) diff --git a/client/Database/database.js b/client/Database/database.js index df449da..b8f9ba2 100644 --- a/client/Database/database.js +++ b/client/Database/database.js @@ -1,62 +1,24 @@ -var __awaiter = - (this && this.__awaiter) || - function (thisArg, _arguments, P, generator) { - function adopt(value) { - return value instanceof P - ? value - : new P(function (resolve) { - resolve(value); - }); - } +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { - try { - step(generator.next(value)); - } catch (e) { - reject(e); - } - } - function rejected(value) { - try { - step(generator["throw"](value)); - } catch (e) { - reject(e); - } - } - function step(result) { - result.done - ? resolve(result.value) - : adopt(result.value).then(fulfilled, rejected); - } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); }); - }; +}; import { initializeApp } from "firebase/app"; -import { - getFirestore, - collection, - doc, - setDoc, - updateDoc, - arrayUnion, - getDocs, - getDoc, - where, - query, - deleteDoc, - orderBy, - arrayRemove, -} from "firebase/firestore"; +import { getFirestore, collection, doc, setDoc, updateDoc, arrayUnion, getDocs, getDoc, where, query, deleteDoc, orderBy, arrayRemove, } from "firebase/firestore"; import { getAuth } from "firebase/auth"; // C3 solutions databasen - ska användas för P&S const firebaseConfig = { - apiKey: "AIzaSyB7n9YIDCmeyzeZzteFnXqOUBijzEO59ls", - authDomain: "backup-277c3.firebaseapp.com", - projectId: "backup-277c3", - storageBucket: "backup-277c3.appspot.com", - messagingSenderId: "296015398098", - appId: "1:296015398098:web:71e1d1ec2b0c370e5a590b", - measurementId: "G-E933CXWWCG", + apiKey: "AIzaSyB7n9YIDCmeyzeZzteFnXqOUBijzEO59ls", + authDomain: "backup-277c3.firebaseapp.com", + projectId: "backup-277c3", + storageBucket: "backup-277c3.appspot.com", + messagingSenderId: "296015398098", + appId: "1:296015398098:web:71e1d1ec2b0c370e5a590b", + measurementId: "G-E933CXWWCG", }; //Backup databas - ska användas av R&D // const firebaseConfig = { @@ -93,170 +55,133 @@ const userTaskCollection = collection(db, "userTask"); // Function to create user a new user in database // takes in userId, unitId, firstname, lastname, email and password as string // throws error if transaction failed -function createUser( - hsaId, - unitId, - firstName, - lastName, - email, - manager, - role, - uid -) { - return __awaiter(this, void 0, void 0, function* () { - //Passwords needs to be hashed, part of atuh0? - try { - const userRef = doc(userCollection, hsaId); - yield setDoc(userRef, { - id: userRef.id, - uid: uid, - unitId: unitId, - firstName: firstName, - lastName: lastName, - email: email, - role: role, - manager: manager, - notes: "", - }); - } catch (error) { - console.log(error); - } - }); +function createUser(hsaId, unitId, firstName, lastName, email, manager, role, uid) { + return __awaiter(this, void 0, void 0, function* () { + //Passwords needs to be hashed, part of atuh0? + try { + const userRef = doc(userCollection, hsaId); + yield setDoc(userRef, { + id: userRef.id, + uid: uid, + unitId: unitId, + firstName: firstName, + lastName: lastName, + email: email, + role: role, + manager: manager, + notes: "", + }); + } + catch (error) { + console.log(error); + } + }); } -function createImprovementWork( - id, - name, - currentStage, - content, // Är detta description bör detta förtydligas. JA - unitId, - purpose, //Bör tas bort motsvaras av p2- mål med projektet - patientRiskLevel, - area, - projectLeader, //Adding projectleader & members to the project - members, - resources = "Inte definerat ännu", - hospitalId, - //Questions in planning stage - p1 = "", - p2 = "", - p3 = "", - p4 = "", - p5 = "", - p6 = "", - p7 = "", - //Questions in Doing (G) stage - g1 = "", - g2 = "", - g3 = "", - g4 = "", - g5 = "", - //Questions in stydy stage - s1 = "", - s2 = "", - s3 = "", - //Questions in acting stage - a1 = "", - a2 = "", - a3 = "", - a4 = "" -) { - return __awaiter(this, void 0, void 0, function* () { - //ID has to be a string - try { - const improvementWorkData = { - name: name, - lowerCaseName: name.toLowerCase(), - currentStage: currentStage, - content: content, - purpose: purpose, - dateStarted: new Date(), - unitId: unitId, - completed: false, - ongoing: false, - patientRiskLevel: patientRiskLevel, - area: area, - p1: p1, - p2: p2, - p3: p3, - p4: p4, - p5: p5, - p6: p6, - p7: p7, - g1: g1, - g2: g2, - g3: g3, - g4: g4, - g5: g5, - s1: s1, - s2: s2, - s3: s3, - a1: a1, - a2: a2, - a3: a3, - a4: a4, - resources: resources, - endDate: new Date(0), - hospitalId: hospitalId, - }; - if (id) { - const improvementWorkRef = doc(improvementWorkCollection, id); - yield setDoc( - improvementWorkRef, - Object.assign({ id: improvementWorkRef.id }, improvementWorkData) - ); - } else { - const improvementWorkRef = doc(improvementWorkCollection); - yield setDoc(improvementWorkRef, improvementWorkData); - id = improvementWorkRef.id; - } - //adding the projectleader and users to the project - addMemberToImprovementWork(projectLeader, id, false, true); - members.forEach((member) => { - addMemberToImprovementWork(member, id, false, false); - }); - } catch (error) { - console.log("Error creating improvementWork: ", error); - throw error; - } - }); +function createImprovementWork(id, name, currentStage, content, // Är detta description bör detta förtydligas. JA +unitId, purpose, //Bör tas bort motsvaras av p2- mål med projektet +patientRiskLevel, area, projectLeader, //Adding projectleader & members to the project +members, resources = "Inte definerat ännu", hospitalId, +//Questions in planning stage +p1 = "", p2 = "", p3 = "", p4 = "", p5 = "", p6 = "", p7 = "", +//Questions in Doing (G) stage +g1 = "", g2 = "", g3 = "", g4 = "", g5 = "", +//Questions in stydy stage +s1 = "", s2 = "", s3 = "", +//Questions in acting stage +a1 = "", a2 = "", a3 = "", a4 = "") { + return __awaiter(this, void 0, void 0, function* () { + //ID has to be a string + try { + const improvementWorkData = { + name: name, + lowerCaseName: name.toLowerCase(), + currentStage: currentStage, + content: content, + purpose: purpose, + dateStarted: new Date(), + unitId: unitId, + completed: false, + ongoing: false, + patientRiskLevel: patientRiskLevel, + area: area, + p1: p1, + p2: p2, + p3: p3, + p4: p4, + p5: p5, + p6: p6, + p7: p7, + g1: g1, + g2: g2, + g3: g3, + g4: g4, + g5: g5, + s1: s1, + s2: s2, + s3: s3, + a1: a1, + a2: a2, + a3: a3, + a4: a4, + resources: resources, + endDate: new Date(0), + hospitalId: hospitalId, + }; + if (id) { + const improvementWorkRef = doc(improvementWorkCollection, id); + yield setDoc(improvementWorkRef, Object.assign({ id: improvementWorkRef.id }, improvementWorkData)); + } + else { + const improvementWorkRef = doc(improvementWorkCollection); + yield setDoc(improvementWorkRef, improvementWorkData); + id = improvementWorkRef.id; + } + //adding the projectleader and users to the project + addMemberToImprovementWork(projectLeader, id, false, true); + members.forEach((member) => { + addMemberToImprovementWork(member, id, false, false); + }); + } + catch (error) { + console.log("Error creating improvementWork: ", error); + throw error; + } + }); } function addMemberToTask(userHsaId, taskId, isResponsibleFor) { - return __awaiter(this, void 0, void 0, function* () { - try { - const relationRef = doc(userTaskCollection); - yield setDoc(relationRef, { - id: relationRef.id, - userHsaId: userHsaId, - taskId: taskId, - isResponsibleFor: isResponsibleFor, - }); - } catch (error) { - console.log("Error adding member to task: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const relationRef = doc(userTaskCollection); + yield setDoc(relationRef, { + id: relationRef.id, + userHsaId: userHsaId, + taskId: taskId, + isResponsibleFor: isResponsibleFor, + }); + } + catch (error) { + console.log("Error adding member to task: ", error); + throw error; + } + }); } -function addMemberToImprovementWork( - userHsaId, - improvementWorkId, - isOwner, - isResponsibleFor -) { - return __awaiter(this, void 0, void 0, function* () { - try { - const relationRef = doc(userImprovementWorkCollection); - yield setDoc(relationRef, { - id: relationRef.id, - userHsaId: userHsaId, - improvementWorkId: improvementWorkId, - isOwner: isOwner, - isResponsibleFor: isResponsibleFor, - }); - } catch (error) { - console.log("Error adding member to improvementWork: ", error); - throw error; - } - }); +function addMemberToImprovementWork(userHsaId, improvementWorkId, isOwner, isResponsibleFor) { + return __awaiter(this, void 0, void 0, function* () { + try { + const relationRef = doc(userImprovementWorkCollection); + yield setDoc(relationRef, { + id: relationRef.id, + userHsaId: userHsaId, + improvementWorkId: improvementWorkId, + isOwner: isOwner, + isResponsibleFor: isResponsibleFor, + }); + } + catch (error) { + console.log("Error adding member to improvementWork: ", error); + throw error; + } + }); } /** * async function deleteSuggestion(suggestionId: string): Promise<void> { @@ -270,368 +195,326 @@ function addMemberToImprovementWork( } */ function removeMemberFromImprovementWork(userHsaId, improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - let constraints = []; - if (userHsaId && improvementWorkId) { - constraints.push(where("improvementWorkId", "==", improvementWorkId)); - constraints.push(where("userHsaId", "==", userHsaId)); - const q = query(userImprovementWorkCollection, ...constraints); - const querySnapshot = yield getDocs(q); - if (!querySnapshot.empty) { - const docSnapshot = querySnapshot.docs[0]; - yield deleteDoc(doc(db, "userImprovementWork", docSnapshot.id)); - console.log( - "userImprovementWork with id ", - docSnapshot.id, - " deleted" - ); - } - } else { - console.log( - "Both improvementWorkId and userHsaId need to be provided!" - ); - } - } catch (error) { - console.log("Error removing member from improvementWork: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let constraints = []; + if (userHsaId && improvementWorkId) { + constraints.push(where("improvementWorkId", "==", improvementWorkId)); + constraints.push(where("userHsaId", "==", userHsaId)); + const q = query(userImprovementWorkCollection, ...constraints); + const querySnapshot = yield getDocs(q); + if (!querySnapshot.empty) { + const docSnapshot = querySnapshot.docs[0]; + yield deleteDoc(doc(db, "userImprovementWork", docSnapshot.id)); + console.log("userImprovementWork with id ", docSnapshot.id, " deleted"); + } + } + else { + console.log("Both improvementWorkId and userHsaId need to be provided!"); + } + } + catch (error) { + console.log("Error removing member from improvementWork: ", error); + throw error; + } + }); } -function createTaskOnImprovementWork( - taskId, - improvementWorkId, - name, - deadlineDate, - startDate, - stage, - content -) { - return __awaiter(this, void 0, void 0, function* () { - try { - const taskData = { - improvementWorkId, - name, - deadlineDate, - startDate, - stage, - content, - completed: false, - }; - if (taskId) { - const taskRef = doc(taskCollection, taskId); - yield setDoc(taskRef, Object.assign({ id: taskRef.id }, taskData)); - } else { - const taskRef = doc(taskCollection); - yield setDoc(taskRef, taskData); - } - } catch (error) { - console.log("Error creating task: ", error); - throw error; - } - }); +function createTaskOnImprovementWork(taskId, improvementWorkId, name, deadlineDate, startDate, stage, content) { + return __awaiter(this, void 0, void 0, function* () { + try { + const taskData = { + improvementWorkId, + name, + deadlineDate, + startDate, + stage, + content, + completed: false, + }; + if (taskId) { + const taskRef = doc(taskCollection, taskId); + yield setDoc(taskRef, Object.assign({ id: taskRef.id }, taskData)); + } + else { + const taskRef = doc(taskCollection); + yield setDoc(taskRef, taskData); + } + } + catch (error) { + console.log("Error creating task: ", error); + throw error; + } + }); } //add a document to a improvementWork // takes in, document url, name and improvementWork id refering to as string // throws error if transaction failed function createdDocumentInKnowledgeBank(documentUrl, name, projectId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const docRef = doc(knowledgeDocumentCollection); - yield setDoc(docRef, { - id: docRef.id, - documentUrl: documentUrl, - name: name, - projectId: projectId, - }); - } catch (error) { - console.log("Error adding document: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const docRef = doc(knowledgeDocumentCollection); + yield setDoc(docRef, { + id: docRef.id, + documentUrl: documentUrl, + name: name, + projectId: projectId, + }); + } + catch (error) { + console.log("Error adding document: ", error); + throw error; + } + }); } //add a document to a improvementWork // takes in, document url, name and improvementWork id refering to as string // throws error if transaction failed function addDocumentToImprovementWork(documentUrl, name, improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const improvementWorkRef = doc( - improvementWorkCollection, - improvementWorkId - ); - const docRef = doc(improvementWorkRef, "documents"); - yield setDoc(docRef, { - id: docRef.id, - documentUrl: documentUrl, - timestamp: new Date(), - name: name, - }); - } catch (error) { - console.log("Error adding document: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const improvementWorkRef = doc(improvementWorkCollection, improvementWorkId); + const docRef = doc(improvementWorkRef, "documents"); + yield setDoc(docRef, { + id: docRef.id, + documentUrl: documentUrl, + timestamp: new Date(), + name: name, + }); + } + catch (error) { + console.log("Error adding document: ", error); + throw error; + } + }); } function getDocumentsByImprovementWork(improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - console.log("Getting documents for improvementwork: ", improvementWorkId); - // Query the userImprovementWork collection for relations involving this user - const q = query( - knowledgeDocumentCollection, - where("projectId", "==", improvementWorkId) - ); - const querySnapshot = yield getDocs(q); - // Fetch each related improvementWork document - const documents = []; - for (const doc of querySnapshot.docs) { - const documentId = doc.data().id; - const documentDoc = yield getObjectById( - "knowledgeDocument", - documentId - ); - documents.push(documentDoc); - } - return documents; - } catch (error) { - console.error("Error getting documents for improvmentwork: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + console.log("Getting documents for improvementwork: ", improvementWorkId); + // Query the userImprovementWork collection for relations involving this user + const q = query(knowledgeDocumentCollection, where("projectId", "==", improvementWorkId)); + const querySnapshot = yield getDocs(q); + // Fetch each related improvementWork document + const documents = []; + for (const doc of querySnapshot.docs) { + const documentId = doc.data().id; + const documentDoc = yield getObjectById("knowledgeDocument", documentId); + documents.push(documentDoc); + } + return documents; + } + catch (error) { + console.error("Error getting documents for improvmentwork: ", error); + throw error; + } + }); } -function createHospital( - hospitalId, // should be auto? - name -) { - return __awaiter(this, void 0, void 0, function* () { - try { - const hospitalData = { - name, - }; - if (hospitalId) { - const hospitalRef = doc(hospitalCollection, hospitalId); - yield setDoc( - hospitalRef, - Object.assign({ id: hospitalRef.id }, hospitalData) - ); - } else { - const hospitalRef = doc(hospitalCollection); - yield setDoc(hospitalRef, hospitalData); - } - } catch (error) { - console.log("Error creating hospital: ", error); - throw error; - } - }); +function createHospital(hospitalId, // should be auto? +name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const hospitalData = { + name, + }; + if (hospitalId) { + const hospitalRef = doc(hospitalCollection, hospitalId); + yield setDoc(hospitalRef, Object.assign({ id: hospitalRef.id }, hospitalData)); + } + else { + const hospitalRef = doc(hospitalCollection); + yield setDoc(hospitalRef, hospitalData); + } + } + catch (error) { + console.log("Error creating hospital: ", error); + throw error; + } + }); } -function createUnit( - unitId, //should be auto? - hospitalId, - name -) { - return __awaiter(this, void 0, void 0, function* () { - try { - const unitData = { - hospitalId, - name, - }; - if (unitId) { - const unitRef = doc(unitCollection, unitId); - yield setDoc(unitRef, Object.assign({ id: unitRef.id }, unitData)); - } else { - const unitRef = doc(unitCollection); - yield setDoc(unitRef, unitData); - } - } catch (error) { - console.log("Error creating unit: ", error); - throw error; - } - }); +function createUnit(unitId, //should be auto? +hospitalId, name) { + return __awaiter(this, void 0, void 0, function* () { + try { + const unitData = { + hospitalId, + name, + }; + if (unitId) { + const unitRef = doc(unitCollection, unitId); + yield setDoc(unitRef, Object.assign({ id: unitRef.id }, unitData)); + } + else { + const unitRef = doc(unitCollection); + yield setDoc(unitRef, unitData); + } + } + catch (error) { + console.log("Error creating unit: ", error); + throw error; + } + }); } -function createSuggestion( - id, - creatorHsaId, - name, - area, - content, - purpose, - measure, - ideas, - //need: boolean, - unitId, - departmentId, - isPublic -) { - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionData = { - creatorHsaId, - name, - area, - content, - purpose, - measure, - ideas, - //need, - unitId, - departmentId, - public: isPublic, - upvotes: [], - comments: [], - dateCreated: new Date(), - }; - if (id) { - const suggestionRef = doc(suggestionCollection, id); - yield setDoc( - suggestionRef, - Object.assign({ id: suggestionRef.id }, suggestionData) - ); - } else { - const suggestionRef = doc(suggestionCollection); - yield setDoc(suggestionRef, suggestionData); - } - } catch (error) { - console.log("Error creating suggestion: ", error); - throw error; - } - }); +function createSuggestion(id, creatorHsaId, name, area, content, purpose, measure, ideas, +//need: boolean, +unitId, departmentId, isPublic) { + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionData = { + creatorHsaId, + name, + area, + content, + purpose, + measure, + ideas, + //need, + unitId, + departmentId, + public: isPublic, + upvotes: [], + comments: [], + dateCreated: new Date(), + }; + if (id) { + const suggestionRef = doc(suggestionCollection, id); + yield setDoc(suggestionRef, Object.assign({ id: suggestionRef.id }, suggestionData)); + } + else { + const suggestionRef = doc(suggestionCollection); + yield setDoc(suggestionRef, suggestionData); + } + } + catch (error) { + console.log("Error creating suggestion: ", error); + throw error; + } + }); } function deleteSuggestion(suggestionId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionRef = doc(suggestionCollection, suggestionId); - yield deleteDoc(suggestionRef); - } catch (error) { - console.log("Error deleting suggestion: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionRef = doc(suggestionCollection, suggestionId); + yield deleteDoc(suggestionRef); + } + catch (error) { + console.log("Error deleting suggestion: ", error); + throw error; + } + }); } // Upvote a suggestion for a user // takes in suggestion id, user HSAid // returns error if transaction failed function upvoteSuggestion(suggestionId, userHsaId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionRef = doc(suggestionCollection, suggestionId); - const suggestionDoc = yield getDoc(suggestionRef); - // if already liked, unlike - if ( - suggestionDoc.exists() && - suggestionDoc.data().upvotes.includes(userHsaId) - ) { - yield updateDoc(suggestionRef, { - upvotes: arrayRemove(userHsaId), - }); - return false; - } else { - // Atomically add a update to the upvote array field. - yield updateDoc(suggestionRef, { - upvotes: arrayUnion(userHsaId), - }); - return true; - } - } catch (error) { - console.log("Error upvoting suggestion: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionRef = doc(suggestionCollection, suggestionId); + const suggestionDoc = yield getDoc(suggestionRef); + // if already liked, unlike + if (suggestionDoc.exists() && + suggestionDoc.data().upvotes.includes(userHsaId)) { + yield updateDoc(suggestionRef, { + upvotes: arrayRemove(userHsaId), + }); + return false; + } + else { + // Atomically add a update to the upvote array field. + yield updateDoc(suggestionRef, { + upvotes: arrayUnion(userHsaId), + }); + return true; + } + } + catch (error) { + console.log("Error upvoting suggestion: ", error); + throw error; + } + }); } //creates a comment // takes in commenters id, suggestion id and content as string // throws error if transaction failed -function createComment(commenterHsaId, suggestionId, content) { // change to subcollection - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionRef = doc(suggestionCollection, suggestionId); - const commentCollection = yield collection(suggestionRef, "comment"); - const commentRef = yield doc(commentCollection); - yield setDoc(commentRef, { - id: commentRef.id, - commenterHsaId: commenterHsaId, - content: content, - dateCreated: new Date(), - upvotes: [], - }); - } catch (error) { - console.log("Error creating comment: ", error); - throw error; - } - }); +function createComment(// change to subcollection +commenterHsaId, suggestionId, content) { + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionRef = doc(suggestionCollection, suggestionId); + const commentCollection = yield collection(suggestionRef, "comment"); + const commentRef = yield doc(commentCollection); + yield setDoc(commentRef, { + id: commentRef.id, + commenterHsaId: commenterHsaId, + content: content, + dateCreated: new Date(), + upvotes: [], + }); + } + catch (error) { + console.log("Error creating comment: ", error); + throw error; + } + }); } // Upvote a comment for a user // takes in suggestionId, commentId and userId as strings // return error if transaction failed function upvoteComment(suggestionId, commentId, userHsaId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionRef = doc(suggestionCollection, suggestionId); - const commentRef = doc(suggestionRef, "comment", commentId); - // Atomically add a update to the upvote array field. - yield updateDoc(commentRef, { - upvotes: arrayUnion(userHsaId), - }); - } catch (error) { - console.log("Error upvoting comment: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionRef = doc(suggestionCollection, suggestionId); + const commentRef = doc(suggestionRef, "comment", commentId); + // Atomically add a update to the upvote array field. + yield updateDoc(commentRef, { + upvotes: arrayUnion(userHsaId), + }); + } + catch (error) { + console.log("Error upvoting comment: ", error); + throw error; + } + }); } //add a note to a user // takes in userHsaId and content as string // throws error if transaction failed function addNoteToUser(userHsaId, content) { - return __awaiter(this, void 0, void 0, function* () { - try { - const userRef = doc(userCollection, userHsaId); - yield updateDoc(userRef, { - notes: content, - dateCreated: new Date(), - }); - } catch (error) { - console.log("Error updating document: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const userRef = doc(userCollection, userHsaId); + yield updateDoc(userRef, { + notes: content, + dateCreated: new Date(), + }); + } + catch (error) { + console.log("Error updating document: ", error); + throw error; + } + }); } // export to setters to be able to use in other files -export { - createComment, - createHospital, - createImprovementWork, - createSuggestion, - createTaskOnImprovementWork, - createUnit, - createUser, - createdDocumentInKnowledgeBank, - addNoteToUser, - addDocumentToImprovementWork, - addMemberToImprovementWork, - addMemberToTask, - upvoteSuggestion, - upvoteComment, - deleteSuggestion, -}; +export { createComment, createHospital, createImprovementWork, createSuggestion, createTaskOnImprovementWork, createUnit, createUser, createdDocumentInKnowledgeBank, addNoteToUser, addDocumentToImprovementWork, addMemberToImprovementWork, addMemberToTask, upvoteSuggestion, upvoteComment, deleteSuggestion, }; //////////////////////////////////////////////GETTERS///////////////////////////////////////////////////////////////////// // Get any object // input is the database type as a string. // output is the whole collection of that type. function getObject(collectionPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, collectionPath); - const querySnapshot = yield getDocs(collectionRef); - const result = []; - querySnapshot.forEach((doc) => { - result.push(doc.data()); - }); - return result; - } catch (error) { - console.error("Error getting collection data", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, collectionPath); + const querySnapshot = yield getDocs(collectionRef); + const result = []; + querySnapshot.forEach((doc) => { + result.push(doc.data()); + }); + return result; + } + catch (error) { + console.error("Error getting collection data", error); + throw error; + } + }); } /** * Asynchronously retrieves a single document object from the specified collection path and document ID. @@ -644,21 +527,23 @@ function getObject(collectionPath) { * @throws Will throw an error if there is an issue during retrieval from the database. */ function getObjectById(collectionPath, documentId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const docRef = doc(db, collectionPath, documentId); - const docSnapshot = yield getDoc(docRef); - if (docSnapshot.exists()) { - return Object.assign({ id: docSnapshot.id }, docSnapshot.data()); - } else { - console.warn(`No such document! ${collectionPath}/${documentId}`); - return null; - } - } catch (error) { - console.error("Error getting object", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const docRef = doc(db, collectionPath, documentId); + const docSnapshot = yield getDoc(docRef); + if (docSnapshot.exists()) { + return Object.assign({ id: docSnapshot.id }, docSnapshot.data()); + } + else { + console.warn(`No such document! ${collectionPath}/${documentId}`); + return null; + } + } + catch (error) { + console.error("Error getting object", error); + throw error; + } + }); } /** * Asynchronously retrieves comments for a given suggestion. @@ -671,29 +556,23 @@ function getObjectById(collectionPath, documentId) { * * @throws Will throw an error if the comments cannot be retrieved. */ -function getComments({ - suggestionId, - sortBy = "dateCreated", - ascending = false, -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const suggestionRef = doc(db, "suggestionCollection", suggestionId); - const commentsQuery = query( - collection(suggestionRef, "comment"), - orderBy(sortBy, ascending ? "asc" : "desc") - ); - const commentsSnapshot = yield getDocs(commentsQuery); - const comments = []; - commentsSnapshot.forEach((doc) => { - comments.push(doc.data()); - }); - return comments; - } catch (error) { - console.error("Error getting comments for suggestion: ", error); - throw error; - } - }); +function getComments({ suggestionId, sortBy = "dateCreated", ascending = false, }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const suggestionRef = doc(db, "suggestionCollection", suggestionId); + const commentsQuery = query(collection(suggestionRef, "comment"), orderBy(sortBy, ascending ? "asc" : "desc")); + const commentsSnapshot = yield getDocs(commentsQuery); + const comments = []; + commentsSnapshot.forEach((doc) => { + comments.push(doc.data()); + }); + return comments; + } + catch (error) { + console.error("Error getting comments for suggestion: ", error); + throw error; + } + }); } //Filtering suggestions on unitId AND creatorHsaId //Sort suggestions on dateCreated OR upvotes @@ -711,50 +590,44 @@ function getComments({ * * @throws Will throw an error if there is an issue retrieving suggestions. */ -function getSuggestions({ - id, - creatorHsaId, - name, - unitId, - sortBy = "dateCreated", // Default sort by dateCreated - ascending = false, // Sort descending by default - isPublic = true, - departmentId, -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "suggestion"); - let constraints = []; - if (id) { - constraints.push(where("id", "==", id)); - } - if (unitId) { - constraints.push(where("unitId", "==", unitId)); - } - if (creatorHsaId) { - constraints.push(where("creatorHsaId", "==", creatorHsaId)); - } - if (name) { - constraints.push(where("name", "==", name)); - sortBy = "name"; - } - if (departmentId) { - constraints.push(where("departmentId", "==", departmentId)); - } - constraints.push(where("public", "==", isPublic)); - constraints.push(orderBy(sortBy, ascending ? "asc" : "desc")); - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - const suggestions = []; - querySnapshot.forEach((doc) => { - suggestions.push(Object.assign({ id: doc.id }, doc.data())); - }); - return suggestions; - } catch (error) { - console.log("Error retrieving suggestions by department: ", error); - throw error; - } - }); +function getSuggestions({ id, creatorHsaId, name, unitId, sortBy = "dateCreated", // Default sort by dateCreated +ascending = false, // Sort descending by default +isPublic = true, departmentId, }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "suggestion"); + let constraints = []; + if (id) { + constraints.push(where("id", "==", id)); + } + if (unitId) { + constraints.push(where("unitId", "==", unitId)); + } + if (creatorHsaId) { + constraints.push(where("creatorHsaId", "==", creatorHsaId)); + } + if (name) { + constraints.push(where("name", "==", name)); + sortBy = "name"; + } + if (departmentId) { + constraints.push(where("departmentId", "==", departmentId)); + } + constraints.push(where("public", "==", isPublic)); + constraints.push(orderBy(sortBy, ascending ? "asc" : "desc")); + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + const suggestions = []; + querySnapshot.forEach((doc) => { + suggestions.push(Object.assign({ id: doc.id }, doc.data())); + }); + return suggestions; + } + catch (error) { + console.log("Error retrieving suggestions by department: ", error); + throw error; + } + }); } /** * Asynchronously searches for hospital documents in the database. @@ -768,29 +641,30 @@ function getSuggestions({ * * @throws Will throw an error if there is an issue during the retrieval process. */ -function getHospitals({ hospitalName, hospitalId }) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "hospital"); - let constraints = []; - if (hospitalName) { - constraints.push(where("name", "==", hospitalName)); - } - if (hospitalId) { - constraints.push(where("id", "==", hospitalId)); - } - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - const hospitals = []; - querySnapshot.forEach((doc) => { - hospitals.push(Object.assign({ id: doc.id }, doc.data())); - }); - return hospitals; - } catch (error) { - console.log("Error retrieving Hospitals", error); - throw error; - } - }); +function getHospitals({ hospitalName, hospitalId, }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "hospital"); + let constraints = []; + if (hospitalName) { + constraints.push(where("name", "==", hospitalName)); + } + if (hospitalId) { + constraints.push(where("id", "==", hospitalId)); + } + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + const hospitals = []; + querySnapshot.forEach((doc) => { + hospitals.push(Object.assign({ id: doc.id }, doc.data())); + }); + return hospitals; + } + catch (error) { + console.log("Error retrieving Hospitals", error); + throw error; + } + }); } /** * Asynchronously retrieves an array of improvement work documents based on various filter criteria. @@ -809,161 +683,138 @@ function getHospitals({ hospitalName, hospitalId }) { * * @throws Will throw an error if there is a problem retrieving the improvement works. */ -function getImprovementWorks({ - id, - name, - nolanStage, - unitId, - completed, - ongoing, - patientRiskLevel, - ascendingDates = false, //Descending dates by default -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "improvementWork"); - let constraints = []; - if (id) { - constraints.push(where("id", "==", id)); - } - if (unitId) { - console.log("inne i ifsatsen i databasen"); - constraints.push(where("unitId", "==", unitId)); - } - if (nolanStage) { - constraints.push(where("currentStage", "==", nolanStage)); - } - if (completed != undefined) { - constraints.push(where("completed", "==", completed)); - } - if (ongoing !== undefined) { - constraints.push(where("ongoing", "==", ongoing)); - } - if (patientRiskLevel) { - constraints.push(where("patientRiskLevel", "==", patientRiskLevel)); - } - if (name) { - constraints.push(where("lowerCaseName", ">=", name.toLowerCase())); - constraints.push( - where("lowerCaseName", "<=", name.toLowerCase() + "~") - ); - } else { - constraints.push( - orderBy("dateStarted", ascendingDates ? "asc" : "desc") - ); - } - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - const improvementWorks = []; - querySnapshot.forEach((doc) => { - improvementWorks.push(Object.assign({ id: doc.id }, doc.data())); - }); - return improvementWorks; - } catch (error) { - console.log("Error retrieving improvementWorks: ", error); - throw error; - } - }); +function getImprovementWorks({ id, name, nolanStage, unitId, completed, ongoing, patientRiskLevel, ascendingDates = false, //Descending dates by default + }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "improvementWork"); + let constraints = []; + if (id) { + constraints.push(where("id", "==", id)); + } + if (unitId) { + console.log("inne i ifsatsen i databasen"); + constraints.push(where("unitId", "==", unitId)); + } + if (nolanStage) { + constraints.push(where("currentStage", "==", nolanStage)); + } + if (completed != undefined) { + constraints.push(where("completed", "==", completed)); + } + if (ongoing !== undefined) { + constraints.push(where("ongoing", "==", ongoing)); + } + if (patientRiskLevel) { + constraints.push(where("patientRiskLevel", "==", patientRiskLevel)); + } + if (name) { + constraints.push(where("lowerCaseName", ">=", name.toLowerCase())); + constraints.push(where("lowerCaseName", "<=", name.toLowerCase() + "~")); + } + else { + constraints.push(orderBy("dateStarted", ascendingDates ? "asc" : "desc")); + } + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + const improvementWorks = []; + querySnapshot.forEach((doc) => { + improvementWorks.push(Object.assign({ id: doc.id }, doc.data())); + }); + return improvementWorks; + } + catch (error) { + console.log("Error retrieving improvementWorks: ", error); + throw error; + } + }); } // Gets improvementWorks where each field matches the union of elements in the input array for each fo the fields -function getFilteredImprovementWorks({ - patientRiskLevels, - nolanStages, - units, - ascendingDates = false, //Descending dates by default - completed, -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - console.log( - "Getting improvement works with the following constraints", - patientRiskLevels, - nolanStages, - units, - ascendingDates, - hospitalIds - ); - const collectionRef = collection(db, "improvementWork"); - let constraints = []; - if (patientRiskLevels && patientRiskLevels.length) { - constraints.push(where("patientRiskLevel", "in", patientRiskLevels)); - } - if (nolanStages && nolanStages.length) { - constraints.push(where("currentStage", "in", nolanStages)); - } - if (units && units.length) { - constraints.push(where("unitId", "in", units)); - } - // If none of the array filters are provided, default to ordering by date. - if (!patientRiskLevels.length && !nolanStages.length && !units.length) { - constraints.push( - orderBy("dateStarted", ascendingDates ? "asc" : "desc") - ); - } - // Handle filtering by completion status - if (completed !== null && completed !== undefined) { - constraints.push(where("completed", "==", completed)); - } - if (hospitalIds && hospitalIds.length) { - constraints.push(where("hospitalId", "in", hospitalIds)); - } - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - const improvementWorks = []; - querySnapshot.forEach((doc) => { - improvementWorks.push(Object.assign({ id: doc.id }, doc.data())); - }); - return improvementWorks; - } catch (error) { - console.error("Error retrieving filtered improvementWorks: ", error); - throw error; - } - }); +function getFilteredImprovementWorks({ patientRiskLevels, nolanStages, units, ascendingDates = false, // Descending dates by default +completed, hospitalIds, }) { + return __awaiter(this, void 0, void 0, function* () { + try { + console.log("Getting improvement works with the following constraints", patientRiskLevels, nolanStages, units, ascendingDates, hospitalIds); + const collectionRef = collection(db, "improvementWork"); + let constraints = []; + if (patientRiskLevels && patientRiskLevels.length) { + constraints.push(where("patientRiskLevel", "in", patientRiskLevels)); + } + if (nolanStages && nolanStages.length) { + constraints.push(where("currentStage", "in", nolanStages)); + } + if (units && units.length) { + constraints.push(where("unitId", "in", units)); + } + // If none of the array filters are provided, default to ordering by date. + if (!patientRiskLevels.length && !nolanStages.length && !units.length) { + constraints.push(orderBy("dateStarted", ascendingDates ? "asc" : "desc")); + } + // Handle filtering by completion status + if (completed !== null && completed !== undefined) { + constraints.push(where("completed", "==", completed)); + } + if (hospitalIds && hospitalIds.length) { + constraints.push(where("hospitalId", "in", hospitalIds)); + } + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + const improvementWorks = []; + querySnapshot.forEach((doc) => { + improvementWorks.push(Object.assign({ id: doc.id }, doc.data())); + }); + return improvementWorks; + } + catch (error) { + console.error("Error retrieving filtered improvementWorks: ", error); + throw error; + } + }); } function getImprovementWorkOwner(improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - let constraints = []; - constraints.push(where("improvementWorkId", "==", improvementWorkId)); - constraints.push(where("isOwner", "==", true)); - const q = query(userImprovementWorkCollection, ...constraints); - const querySnapshot = yield getDocs(q); - if (querySnapshot.empty) { - console.log("Improvement work ", improvementWorkId, " has no owner"); - return null; - } else { - const owner = querySnapshot.docs[0].data().userHsaId; - return owner; - } - } catch (error) { - console.log(error); - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let constraints = []; + constraints.push(where("improvementWorkId", "==", improvementWorkId)); + constraints.push(where("isOwner", "==", true)); + const q = query(userImprovementWorkCollection, ...constraints); + const querySnapshot = yield getDocs(q); + if (querySnapshot.empty) { + console.log("Improvement work ", improvementWorkId, " has no owner"); + return null; + } + else { + const owner = querySnapshot.docs[0].data().userHsaId; + return owner; + } + } + catch (error) { + console.log(error); + } + }); } function getImprovementWorkResponsible(improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - let constraints = []; - constraints.push(where("improvementWorkId", "==", improvementWorkId)); - constraints.push(where("isResponsibleFor", "==", true)); - const q = query(userImprovementWorkCollection, ...constraints); - const querySnapshot = yield getDocs(q); - if (querySnapshot.empty) { - console.log( - "Improvement work ", - improvementWorkId, - " has no responsible" - ); - return null; - } else { - const responsibleId = querySnapshot.docs[0].data().userHsaId; - const responsible = yield getObjectById("users", responsibleId); - return responsible; - } - } catch (error) { - console.log(error); - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let constraints = []; + constraints.push(where("improvementWorkId", "==", improvementWorkId)); + constraints.push(where("isResponsibleFor", "==", true)); + const q = query(userImprovementWorkCollection, ...constraints); + const querySnapshot = yield getDocs(q); + if (querySnapshot.empty) { + console.log("Improvement work ", improvementWorkId, " has no responsible"); + return null; + } + else { + const responsibleId = querySnapshot.docs[0].data().userHsaId; + const responsible = yield getObjectById("users", responsibleId); + return responsible; + } + } + catch (error) { + console.log(error); + } + }); } // TODO getUsersForTask! /** @@ -980,44 +831,38 @@ function getImprovementWorkResponsible(improvementWorkId) { * * @throws Will throw an error if there is an issue during the retrieval process. */ -function getUsers({ - hsaId, - name, - unitId, - ascendingFirstNames = false, // Descending names by default - uid, -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "users"); - let constraints = []; - if (hsaId) { - constraints.push(where("id", "==", hsaId)); - } - if (unitId) { - constraints.push(where("unitId", "==", unitId)); - } - if (uid) { - constraints.push(where("uid", "==", uid)); - } - if (name) { - constraints.push(where("name", "==", name)); - } - constraints.push( - orderBy("firstName", ascendingFirstNames ? "asc" : "desc") - ); - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - const users = []; - querySnapshot.forEach((doc) => { - users.push(Object.assign({ id: doc.id }, doc.data())); - }); - return users; - } catch (error) { - console.log("Error retrieving users by department: ", error); - throw error; - } - }); +function getUsers({ hsaId, name, unitId, ascendingFirstNames = false, // Descending names by default +uid, }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "users"); + let constraints = []; + if (hsaId) { + constraints.push(where("id", "==", hsaId)); + } + if (unitId) { + constraints.push(where("unitId", "==", unitId)); + } + if (uid) { + constraints.push(where("uid", "==", uid)); + } + if (name) { + constraints.push(where("name", "==", name)); + } + constraints.push(orderBy("firstName", ascendingFirstNames ? "asc" : "desc")); + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + const users = []; + querySnapshot.forEach((doc) => { + users.push(Object.assign({ id: doc.id }, doc.data())); + }); + return users; + } + catch (error) { + console.log("Error retrieving users by department: ", error); + throw error; + } + }); } // TODO getTasksForUser! /** @@ -1035,36 +880,35 @@ function getUsers({ * * @throws Will throw an error if there is an issue during the retrieval process. */ -function getTasks({ - // userHsaId, - // isResponsibleFor, - improvementWorkId, - stage, - ascendingDates = false, // Descending dates by default -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "task"); - let constraints = []; - if (stage) { - constraints.push(where("stage", "==", stage)); - } - if (improvementWorkId != undefined) { - constraints.push(where("improvementWorkId", "==", improvementWorkId)); - constraints.push(orderBy("startDate", ascendingDates ? "asc" : "desc")); - } - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - let tasks = []; - querySnapshot.forEach((doc) => { - tasks.push(Object.assign({ id: doc.id }, doc.data())); - }); - return tasks; - } catch (error) { - console.log("Error retrieving task by department: ", error); - throw error; - } - }); +function getTasks({ +// userHsaId, +// isResponsibleFor, +improvementWorkId, stage, ascendingDates = false, // Descending dates by default + }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "task"); + let constraints = []; + if (stage) { + constraints.push(where("stage", "==", stage)); + } + if (improvementWorkId != undefined) { + constraints.push(where("improvementWorkId", "==", improvementWorkId)); + constraints.push(orderBy("startDate", ascendingDates ? "asc" : "desc")); + } + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + let tasks = []; + querySnapshot.forEach((doc) => { + tasks.push(Object.assign({ id: doc.id }, doc.data())); + }); + return tasks; + } + catch (error) { + console.log("Error retrieving task by department: ", error); + throw error; + } + }); } /** * Asynchronously retrieves an array of unit documents from the database based on various filter criteria. @@ -1080,305 +924,246 @@ function getTasks({ * * @throws Will throw an error if there is an issue during the retrieval process. */ -function getUnits({ - unitId, - hospitalId, - name, - ascendingUnitNames = false, // Sort descending names by default -}) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, "unit"); - let constraints = []; - if (unitId) { - constraints.push(where("id", "==", unitId)); - } - if (name) { - constraints.push(where("name", "==", name)); - } - if (hospitalId) { - constraints.push(where("hospitalId", "==", hospitalId)); - constraints.push(orderBy("name", ascendingUnitNames ? "asc" : "desc")); - } - const q = query(collectionRef, ...constraints); - const querySnapshot = yield getDocs(q); - let units = []; - querySnapshot.forEach((doc) => { - units.push(Object.assign({ id: doc.id }, doc.data())); - }); - return units; - } catch (error) { - console.log("Error retrieving units by hospitalId: ", error); - throw error; - } - }); +function getUnits({ unitId, hospitalId, name, ascendingUnitNames = false, // Sort descending names by default + }) { + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, "unit"); + let constraints = []; + if (unitId) { + constraints.push(where("id", "==", unitId)); + } + if (name) { + constraints.push(where("name", "==", name)); + } + if (hospitalId) { + constraints.push(where("hospitalId", "==", hospitalId)); + constraints.push(orderBy("name", ascendingUnitNames ? "asc" : "desc")); + } + const q = query(collectionRef, ...constraints); + const querySnapshot = yield getDocs(q); + let units = []; + querySnapshot.forEach((doc) => { + units.push(Object.assign({ id: doc.id }, doc.data())); + }); + return units; + } + catch (error) { + console.log("Error retrieving units by hospitalId: ", error); + throw error; + } + }); } function getImprovementWorksForUser(userHsaId) { - return __awaiter(this, void 0, void 0, function* () { - try { - console.log("Getting improvementworks for user: ", userHsaId); - // Query the userImprovementWork collection for relations involving this user - const q = query( - userImprovementWorkCollection, - where("userHsaId", "==", userHsaId) - ); - const querySnapshot = yield getDocs(q); - // Fetch each related improvementWork document - const improvementWorks = []; - for (const doc of querySnapshot.docs) { - const improvementWorkId = doc.data().improvementWorkId; - const improvementWorkDoc = yield getObjectById( - "improvementWork", - improvementWorkId - ); - improvementWorks.push(improvementWorkDoc); - } - return improvementWorks; - } catch (error) { - console.error("Error getting improvement works for user: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + console.log("Getting improvementworks for user: ", userHsaId); + // Query the userImprovementWork collection for relations involving this user + const q = query(userImprovementWorkCollection, where("userHsaId", "==", userHsaId)); + const querySnapshot = yield getDocs(q); + // Fetch each related improvementWork document + const improvementWorks = []; + for (const doc of querySnapshot.docs) { + const improvementWorkId = doc.data().improvementWorkId; + const improvementWorkDoc = yield getObjectById("improvementWork", improvementWorkId); + improvementWorks.push(improvementWorkDoc); + } + return improvementWorks; + } + catch (error) { + console.error("Error getting improvement works for user: ", error); + throw error; + } + }); } function getUsersForImprovementWork(improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - // Query the userImprovementWork collection for relations involving this improvementWork - const q = query( - userImprovementWorkCollection, - where("improvementWorkId", "==", improvementWorkId) - ); - const querySnapshot = yield getDocs(q); - // Fetch each related user document - const users = []; - for (const doc of querySnapshot.docs) { - const userHsaId = doc.data().userHsaId; - const userDoc = yield getObjectById("users", userHsaId); - users.push(userDoc); - } - return users; - } catch (error) { - console.error("Error getting users for improvementWork: ", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + // Query the userImprovementWork collection for relations involving this improvementWork + const q = query(userImprovementWorkCollection, where("improvementWorkId", "==", improvementWorkId)); + const querySnapshot = yield getDocs(q); + // Fetch each related user document + const users = []; + for (const doc of querySnapshot.docs) { + const userHsaId = doc.data().userHsaId; + const userDoc = yield getObjectById("users", userHsaId); + users.push(userDoc); + } + return users; + } + catch (error) { + console.error("Error getting users for improvementWork: ", error); + throw error; + } + }); } // export getters to be able to use in other files -export { - getObject, - getObjectById, - getSuggestions, - getImprovementWorks, - getUsers, - getTasks, - getUnits, - getComments, - getHospitals, - getImprovementWorksForUser, - getUsersForImprovementWork, - getImprovementWorkOwner, - getImprovementWorkResponsible, - getFilteredImprovementWorks, - getDocumentsByImprovementWork, -}; +export { getObject, getObjectById, getSuggestions, getImprovementWorks, getUsers, getTasks, getUnits, getComments, getHospitals, getImprovementWorksForUser, getUsersForImprovementWork, getImprovementWorkOwner, getImprovementWorkResponsible, getFilteredImprovementWorks, getDocumentsByImprovementWork, }; ////////////////////////////////////DELETING///////////////////////////////////////////// // delete an instance of a type function deleteInstance(docType, docId) { - return __awaiter(this, void 0, void 0, function* () { - try { - const docRef = doc(db, docType, docId); - yield deleteDoc(docRef); - console.log(`${docType} deleted successfully.`); - } catch (error) { - console.error(`Error deleting ${docType}:`, error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const docRef = doc(db, docType, docId); + yield deleteDoc(docRef); + console.log(`${docType} deleted successfully.`); + } + catch (error) { + console.error(`Error deleting ${docType}:`, error); + throw error; + } + }); } // delete all instances of a type function deleteAllDocumentsInCollection(collectionName) { - return __awaiter(this, void 0, void 0, function* () { - try { - const collectionRef = collection(db, collectionName); - const snapshot = yield getDocs(collectionRef); - // Delete all documents in the collection - const deletePromises = snapshot.docs.map((doc) => - __awaiter(this, void 0, void 0, function* () { - yield deleteDoc(doc.ref); - }) - ); - yield Promise.all(deletePromises); - console.log( - `All documents in the ${collectionName} collection deleted successfully.` - ); - } catch (error) { - console.error( - `Error deleting all documents in ${collectionName}:`, - error - ); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const collectionRef = collection(db, collectionName); + const snapshot = yield getDocs(collectionRef); + // Delete all documents in the collection + const deletePromises = snapshot.docs.map((doc) => __awaiter(this, void 0, void 0, function* () { + yield deleteDoc(doc.ref); + })); + yield Promise.all(deletePromises); + console.log(`All documents in the ${collectionName} collection deleted successfully.`); + } + catch (error) { + console.error(`Error deleting all documents in ${collectionName}:`, error); + throw error; + } + }); } ////////////////////////////////////UPDATING///////////////////////////////////////////// // update a field in an instance function updateInstance(docType, docId, updates) { - return __awaiter(this, void 0, void 0, function* () { - try { - const docRef = doc(db, docType, docId); - yield updateDoc(docRef, updates); - console.log(`${docType} updated successfully.`); - } catch (error) { - console.error(`Error updating ${docType}:`, error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + const docRef = doc(db, docType, docId); + yield updateDoc(docRef, updates); + console.log(`${docType} updated successfully.`); + } + catch (error) { + console.error(`Error updating ${docType}:`, error); + throw error; + } + }); } // changes the ongoing status of an improvement work. if ongoing it is paused, if if paused onging. // user must be a manager function startOrPauseImprovementWork(userId, improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - let user = yield getObjectById("users", userId); - let improvementWork = yield getObjectById( - "improvementWork", - improvementWorkId - ); - if (!user || !user.manager) { - throw new Error("User can't change improvementWork status"); - } else { - if (improvementWork) { - let update = { ongoing: !improvementWork.ongoing }; - yield updateInstance("improvementWork", improvementWorkId, update); - console.log(`Improvement work ${improvementWorkId} status updated.`); - return true; - } else { - console.error( - `Improvement work with ID ${improvementWorkId} not found.` - ); - return false; - } - } - } catch (error) { - console.error("Error starting/pausing improvement work:", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let user = yield getObjectById("users", userId); + let improvementWork = yield getObjectById("improvementWork", improvementWorkId); + if (!user || !user.manager) { + throw new Error("User can't change improvementWork status"); + } + else { + if (improvementWork) { + let update = { ongoing: !improvementWork.ongoing }; + yield updateInstance("improvementWork", improvementWorkId, update); + console.log(`Improvement work ${improvementWorkId} status updated.`); + return true; + } + else { + console.error(`Improvement work with ID ${improvementWorkId} not found.`); + return false; + } + } + } + catch (error) { + console.error("Error starting/pausing improvement work:", error); + throw error; + } + }); } function changePatientRiskLevel(userId, improvementWorkId, patientRiskLevel) { - return __awaiter(this, void 0, void 0, function* () { - try { - let user = yield getObjectById("users", userId); - let improvementWork = yield getObjectById( - "improvementWork", - improvementWorkId - ); - if (!user || !user.manager) { - throw new Error( - "User can't change patientRiskLevel in improvement work" - ); - } else { - if (improvementWork) { - let update = { patientRiskLevel: patientRiskLevel }; - yield updateInstance("improvementWork", improvementWorkId, update); - console.log(`Improvement work ${improvementWorkId} status updated.`); - } else { - console.error( - `Improvement work with ID ${improvementWorkId} not found.` - ); - } - } - } catch (error) { - console.error("Error starting/pausing improvement work:", error); - throw error; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let user = yield getObjectById("users", userId); + let improvementWork = yield getObjectById("improvementWork", improvementWorkId); + if (!user || !user.manager) { + throw new Error("User can't change patientRiskLevel in improvement work"); + } + else { + if (improvementWork) { + let update = { patientRiskLevel: patientRiskLevel }; + yield updateInstance("improvementWork", improvementWorkId, update); + console.log(`Improvement work ${improvementWorkId} status updated.`); + } + else { + console.error(`Improvement work with ID ${improvementWorkId} not found.`); + } + } + } + catch (error) { + console.error("Error starting/pausing improvement work:", error); + throw error; + } + }); } // finalizes the improvement work. ongoing is set to false. // user must be a manager function finalizeImprovementWork(userId, improvementWorkId) { - return __awaiter(this, void 0, void 0, function* () { - try { - let user = yield getObjectById("users", userId); - if (!user || !user.manager) { - return false; - } else { - let update = { completed: true, ongoing: false, endDate: new Date() }; - yield updateInstance("improvementWork", improvementWorkId, update); - return true; - } - } catch (error) { - return false; - } - }); + return __awaiter(this, void 0, void 0, function* () { + try { + let user = yield getObjectById("users", userId); + if (!user || !user.manager) { + return false; + } + else { + let update = { completed: true, ongoing: false, endDate: new Date() }; + yield updateInstance("improvementWork", improvementWorkId, update); + return true; + } + } + catch (error) { + return false; + } + }); } function getAddAndDeleteMembersLists(listA, listB) { - const deleteList = listA.filter((element) => !listB.includes(element)); - const addList = listB.filter((element) => !listA.includes(element)); - return { - delete: deleteList, - add: addList, - }; + const deleteList = listA.filter((element) => !listB.includes(element)); + const addList = listB.filter((element) => !listA.includes(element)); + return { + delete: deleteList, + add: addList, + }; } -export function updateImprovementWorkMembers( - improvementWorkId, - projectLeaderId, - membersIdList -) { - return __awaiter(this, void 0, void 0, function* () { - const currentProjectLeader = yield getImprovementWorkResponsible( - improvementWorkId - ); - if (currentProjectLeader.id === projectLeaderId) { - // Do nothing if the project leader is the same - } else { - // Remove the current project leader and add the new one - yield removeMemberFromImprovementWork( - improvementWorkId, - currentProjectLeader.id - ); - yield addMemberToImprovementWork( - projectLeaderId, - improvementWorkId, - false, - true - ); - console.log("ledare"); - } - const currentMembers = yield getUsersForImprovementWork(improvementWorkId); - const currentMembersId = []; - currentMembers.forEach((member) => { - currentMembersId.push(member.id); - }); - const differenceList = getAddAndDeleteMembersLists( - currentMembersId, - membersIdList - ); - console.log("delete " + differenceList.delete); - console.log("add " + differenceList.add); - const indexOfProjectLeader = differenceList.delete.indexOf(projectLeaderId); - if (indexOfProjectLeader !== -1) { - alert( - "Du kan inte ta bort projektledaren från ditt förbättringsarbete. För att göra detta byt projektledare först. Alla andra ändringar kommer genomföras." - ); - differenceList.delete.splice(indexOfProjectLeader, 1); - } - differenceList.delete.forEach((deleteId) => { - removeMemberFromImprovementWork(deleteId, improvementWorkId); - }); - differenceList.add.forEach((addId) => { - addMemberToImprovementWork(addId, improvementWorkId, false, false); +export function updateImprovementWorkMembers(improvementWorkId, projectLeaderId, membersIdList) { + return __awaiter(this, void 0, void 0, function* () { + const currentProjectLeader = yield getImprovementWorkResponsible(improvementWorkId); + if (currentProjectLeader.id === projectLeaderId) { + // Do nothing if the project leader is the same + } + else { + // Remove the current project leader and add the new one + yield removeMemberFromImprovementWork(improvementWorkId, currentProjectLeader.id); + yield addMemberToImprovementWork(projectLeaderId, improvementWorkId, false, true); + console.log("ledare"); + } + const currentMembers = yield getUsersForImprovementWork(improvementWorkId); + const currentMembersId = []; + currentMembers.forEach((member) => { + currentMembersId.push(member.id); + }); + const differenceList = getAddAndDeleteMembersLists(currentMembersId, membersIdList); + console.log("delete " + differenceList.delete); + console.log("add " + differenceList.add); + const indexOfProjectLeader = differenceList.delete.indexOf(projectLeaderId); + if (indexOfProjectLeader !== -1) { + alert("Du kan inte ta bort projektledaren från ditt förbättringsarbete. För att göra detta byt projektledare först. Alla andra ändringar kommer genomföras."); + differenceList.delete.splice(indexOfProjectLeader, 1); + } + differenceList.delete.forEach((deleteId) => { + removeMemberFromImprovementWork(deleteId, improvementWorkId); + }); + differenceList.add.forEach((addId) => { + addMemberToImprovementWork(addId, improvementWorkId, false, false); + }); }); - }); } -export { - deleteInstance, - updateInstance, - finalizeImprovementWork, - deleteAllDocumentsInCollection, - startOrPauseImprovementWork, - changePatientRiskLevel, -}; +export { deleteInstance, updateInstance, finalizeImprovementWork, deleteAllDocumentsInCollection, startOrPauseImprovementWork, changePatientRiskLevel, }; //////////////////////////////// for later sprint //function add_upvotes //function add_notes -- GitLab