import { ApprovalWorkflow } from "@/interfaces/approval.workflow"; import client from "@/lib/mongodb"; import { ObjectId } from "mongodb"; const db = client.db(process.env.MONGODB_DB); export const getApprovalWorkflows = async (collection: string, ids?: string[]) => { return await db .collection(collection) .find(ids ? { _id: { $in: ids.map((id) => new ObjectId(id)) } } : {}) .toArray(); }; export const getApprovalWorkflow = async (collection: string, id: string) => { return await db.collection(collection).findOne({ _id: new ObjectId(id) }); }; export const getApprovalWorkflowsByEntities = async (collection: string, ids: string[]) => { return await db .collection(collection) .find({ entityId: { $in: ids } }) .toArray(); }; export const createApprovalWorkflow = async (collection: string, workflow: ApprovalWorkflow) => { const { _id, ...workflowWithoutId } = workflow as ApprovalWorkflow; return await db.collection(collection).insertOne(workflowWithoutId); }; export const createApprovalWorkflows = async (collection: string, workflows: ApprovalWorkflow[]) => { if (workflows.length === 0) return; const workflowsWithoutIds: ApprovalWorkflow[] = workflows.map(({ _id, ...wfs }) => wfs); return await db.collection(collection).insertMany(workflowsWithoutIds); }; export const updateApprovalWorkflow = async (collection: string, workflow: ApprovalWorkflow) => { const { _id, ...workflowWithoutId } = workflow as ApprovalWorkflow; return await db.collection(collection).replaceOne({ _id: _id }, workflowWithoutId); }; export const updateApprovalWorkflows = async (collection: string, workflows: ApprovalWorkflow[]) => { const bulkOperations = workflows.map((workflow) => { const { _id, ...workflowWithoutId } = workflow; return { replaceOne: { filter: { _id: new ObjectId(_id) }, replacement: workflowWithoutId, }, }; }); return await db.collection(collection).bulkWrite(bulkOperations); }; export const deleteApprovalWorkflow = async (collection: string, id: string) => { return await db.collection(collection).deleteOne({ _id: new ObjectId(id) }); }; export const replaceApprovalWorkflowsByEntities = async (collection: string, workflows: ApprovalWorkflow[], entityIds: string[]) => { // 1. Keep track of the _id values of all workflows we want to end up with const finalIds = new Set(); // 2. Process incoming workflows for (const workflow of workflows) { if (workflow._id) { // Replace the existing ones await updateApprovalWorkflow(collection, workflow); finalIds.add(workflow._id.toString()); } else { // Insert if no _id const insertResult = await createApprovalWorkflow(collection, workflow); finalIds.add(insertResult.insertedId.toString()); } } // 3. Delete any existing workflow (within these entityIds) that wasn't in the final list await db.collection(collection).deleteMany({ _id: { $nin: Array.from(finalIds).map((id) => new ObjectId(id)), }, entityId: { $in: entityIds }, }); };