import { orgModel } from "./organization/organization.schema"; import { userModel } from "./user/user.schema"; import { AuthenticatedUser } from "./auth"; import { modelMap } from "./utils/tags"; import { listUsers } from "./user/user.service"; type Collection = | "users" | "permits" | "orgs" | "processed" | "notifications" | "rts" | "tasks" | "ctasks" | "payments"; export async function getUniqueFields( field: string, collection: Collection, user: AuthenticatedUser ) { const model = modelMap[collection]; if (!model) throw new Error("invalid collection"); if (collection === "notifications" && field === "changes") { const changeKeys = await model.aggregate([ { $project: { changesKeys: { $objectToArray: "$changes" } } }, { $unwind: "$changesKeys" }, { $group: { _id: "$changesKeys.k" } }, ]); return changeKeys.map((item) => item._id); } if (field === "taggedUsers") { const users = await listUsers(user); const usersObj = {}; for (const user of users) { usersObj[user.id] = user.name; } return usersObj; } let values = await model.distinct(field, { tenantId: user.tenantId }); let matchedValues = []; if (field === "county.name") { matchedValues = await orgModel.find().where("name").in(values).exec(); } else if (field === "county") { matchedValues = await orgModel.find().where("_id").in(values).exec(); } else if (field === "client") { if (user.role == "client") { values = [user.orgId]; } matchedValues = await orgModel.find().where("_id").in(values).exec(); } else if (field === "createdBy") { matchedValues = await userModel.find().where("_id").in(values).exec(); } else if (field === "assignedTo") { matchedValues = await userModel.find().where("_id").in(values).exec(); } if (matchedValues.length > 0) { const newValues = {}; for (const item of matchedValues) { newValues[item.id] = item.name; } return newValues; } return values; }