const utils = require("../utils"); const dayjs = require("dayjs"); const common = require("../../common"); const appFunction = require("../app-function"); const api = require("../../api"); let db = null; exports.main = async (content, DB) => { db = DB; switch (content.type) { case "getGroups": return await exports.getGroups(content); case "createGroup": return await exports.createGroup(content); case "updateGroup": return await exports.updateGroup(content); case "getGroupsByCorpGroupId": return await exports.getGroupsByCorpGroupId(content); case "orderTeamGroups": return await exports.orderTeamGroups(content); case "removeGroup": return await exports.removeGroup(content); case "addGroupIdForMember": return await exports.addGroupIdForMember(content); case "customerEnterGroup": return await exports.customerEnterGroup(content); case "getGroupByIds": return await exports.getGroupByIds(content); default: return { success: false, message: "未找到对应的操作类型", }; } }; exports.createGroup = async (context) => { const { corpId, params } = context; const { groupName, managementPlan = {}, teamId, groupType, description, creator, relatePlan, executorUserId, } = params; if (!corpId) { return { success: false, message: "机构ID未输入", }; } if (!groupName) { return { success: false, message: "分组名称未输入", }; } const countQuery = { corpId, groupName, }; if (groupType === "corp") { countQuery.groupType = "corp"; } else { countQuery.teamId = teamId; } const count = await db.collection("group").find(countQuery).count(); if (count > 0) { return { success: false, message: "分组名称重复!", }; } let query = { _id: common.generateRandomString(24), corpId, teamId, groupName, managementPlan, creator, description, createTime: dayjs().valueOf(), }; if (groupType === "corp") { query["groupType"] = "corp"; } else { query["groupType"] = "team"; query["relatePlan"] = typeof relatePlan === "boolean" ? relatePlan : false; query["executorUserId"] = typeof executorUserId == "string" && executorUserId.trim() ? executorUserId.trim() : ""; } try { const result = await db.collection("group").insertOne(query); const id = result.insertedId; if (groupType === "corp") await distributeGroupToTeam(id, query); return { success: true, data: id, message: "新增分组成功", }; } catch (error) { return { success: false, message: "新增分组失败", }; } }; // 分发机构分组到团队 async function distributeGroupToTeam(parentGroupId, group) { const { corpId, groupName, managementPlan, description } = group; try { const { list = [] } = await api.getCorpApi({ type: "getCorpTeams", corpId, pageSize: 10000, page: 1, fields: { teamId: 1 }, showCustomerCount: false, }); const teams = Array.isArray(list) ? list.filter((i) => Boolean(i.teamId)) : []; const bulkOps = teams.map((team) => { const { teamId } = team; const query = { _id: common.generateRandomString(24), parentGroupId, corpId, teamId, groupName, managementPlan, description, createTime: dayjs().valueOf(), }; return { insertOne: { document: query, }, }; }); if (bulkOps.length > 0) { await db.collection("group").bulkWrite(bulkOps); } return { success: true, message: "分发成功", }; } catch (error) { return { success: false, message: "分发失败", }; } } exports.updateGroup = async (context) => { const { id, params, corpId } = context; if (!id) { return { success: false, message: "分组id未传", }; } const { groupName, managementPlan, description, relatePlan, executorUserId } = params; let query = { updateTime: dayjs().valueOf() }; if (typeof groupName === "string") { query["groupName"] = groupName.trim(); } if (typeof description === "string") { query["description"] = description.trim(); } if (typeof managementPlan === "object" && managementPlan) { query["managementPlan"] = managementPlan; } if (typeof relatePlan === "boolean") { query["relatePlan"] = relatePlan; } if (typeof executorUserId === "string") { query["executorUserId"] = executorUserId.trim(); } try { await db.collection("group").updateMany( { corpId, $or: [{ _id: id }, { parentGroupId: id }], }, { $set: query } ); return { success: true, message: "修改成功", }; } catch (error) { return { success: false, message: error.message || "修改失败", }; } }; exports.removeGroup = async (context) => { const { corpId, id, groupType, teamId } = context; if (!corpId) { return { success: false, message: "机构ID未输入", }; } if (!id) { return { success: false, message: "机构ID未输入", }; } try { let memberCount = 0; // 判断是否存在客户 if (groupType === "corp") { // 机构分组 const groups = await db .collection("group") .find({ corpId, parentGroupId: id }) .toArray(); const groupIds = groups.map((e) => e._id); memberCount = await db .collection("member") .find({ corpId, groupIds: { $in: groupIds } }) .count(); } else { memberCount = await db .collection("member") .find({ corpId, groupIds: id, teamId }) .count(); } if (memberCount !== 0) { return { success: false, message: "此分组下还存在客户,请将客户转组后再删除本分组!", }; } // 删除分组 await db.collection("group").deleteMany({ corpId, $or: [{ _id: id }, { parentGroupId: id }], }); return { success: true, message: "删除成功", }; } catch (error) { return { success: false, message: "删除失败", }; } }; exports.getGroupByIds = async (context) => { const { ids, corpId } = context; if (!ids) { return { success: false, message: "分组ID未输入", }; } try { const data = await db .collection("group") .find({ _id: { $in: ids }, corpId }) .toArray(); return { success: true, data, message: "获取成功", }; } catch (error) { return { success: false, message: "获取失败", }; } }; exports.getGroups = async (context) => { const { corpId, teamId, page, pageSize, groupName, groupType } = context; if (!corpId) { return { success: false, message: "机构ID未输入", }; } let query = { corpId }; if (groupType === "corp") { query.groupType = "corp"; } else { query["teamId"] = teamId; } if (groupName && typeof groupName === "string" && groupName.trim()) { query.groupName = new RegExp(".*" + groupName.trim() + ".*", "i"); } const total = await db.collection("group").find(query).count(); const pages = Math.ceil(total / pageSize); const data = await db .collection("group") .find(query) .sort({ createTime: -1 }) .skip((page - 1) * pageSize) .limit(pageSize) .toArray(); const handler = async (item) => { let count = await db .collection("member") .find({ corpId, groupIds: item._id, teamId: teamId, }) .count(); item.memberCount = count; return item; }; let list = await utils.processInBatches(data, handler, 10); return { success: true, data: list, message: "获取成功", total: total, pages: pages, size: pageSize, }; }; exports.addGroupIdForMember = async (context) => { const { memberId, toGroupId, fromGroupId } = context; if (!memberId) { return { success: false, message: "客户Id未输入!", }; } try { const member = await db.collection("member").findOne({ _id: memberId }); let { groupIds = [] } = member; if (fromGroupId && Array.isArray(groupIds)) { const index = groupIds.findIndex((e) => e == fromGroupId); groupIds.splice(index, 1); } if (toGroupId && Array.isArray(groupIds)) { const index = groupIds.findIndex((e) => e == toGroupId); if (index < 0) groupIds.push(toGroupId); } await db.collection("member").updateOne( { _id: memberId }, { $set: { groupIds }, } ); return { success: true, groupIds, message: "更新成功!", }; } catch (error) { return { success: true, message: "更新失败!", }; } }; exports.orderTeamGroups = async (ctx) => { const { teamId, corpId, order } = ctx; if ( !corpId || !teamId || Object.prototype.toString.call(order) !== "[object Object]" ) { return { success: false, message: "参数错误", }; } const ids = Object.keys(order); if (ids.length === 0) { return { success: true, message: "参数错误" }; } try { const list = await db .collection("group") .find({ corpId, teamId, _id: { $in: ids }, }) .toArray(); const bulkOps = list .map((i) => ({ id: i._id, order: order[i._id] })) .filter((i) => typeof i.order === "number" && i.order >= 0) .map((item) => ({ updateOne: { filter: { _id: item.id }, update: { $set: { order: item.order } }, }, })); if (bulkOps.length > 0) { await db.collection("group").bulkWrite(bulkOps); } return { success: true, message: "更新成功", }; } catch (e) { return { success: false, message: e.message || "更新失败", }; } }; exports.getGroupsByCorpGroupId = async (ctx) => { const { id, corpId } = ctx; if (!id || !corpId) { return { success: false, message: "参数错误" }; } try { const data = await db .collection("group") .find({ parentGroupId: id, corpId }) .toArray(); return { success: true, data, message: "获取成功" }; } catch (e) { return { success: false, message: e.message || "获取失败", }; } }; exports.customerEnterGroup = async (context) => { let { corpId, customerId, targetGroupId, executeTeamId, executeTeamName, executeUserId, planExecutionTime, } = context; if (!corpId || !customerId || !targetGroupId) { return { success: false, message: "必须字段为传!", }; } const customer = await db.collection("member").findOne({ _id: customerId }); if (!customer) { return { success: false, message: "患者不存在", }; } const { groupIds = [] } = customer; // //先判断目标分组是否是机构分组, 若不是机构分组, 则可以直接使用 const group = await db.collection("group").findOne({ _id: targetGroupId, corpId, }); if (!group) { return { success: false, message: "未获取到目标分组", }; } // 若此分组是是机构分组, 则去除在侧团队的子分组 if (!group.parentGroupId) { const temaGroups = await db .collection("group") .find({ corpId, teamId: executeTeamId, }) .toArray(); const teamGroup = temaGroups.find((i) => i.parentGroupId === targetGroupId); if (!teamGroup) { return { success: false, message: "未获取到目标分组", }; } targetGroupId = teamGroup._id; } // 如果是机构分组, 在拿到执行团队的所有机构分组, 找到目标分组在当前团队的子分组 console.log("groupIds", groupIds); console.log("targetGroupId", targetGroupId); if (Array.isArray(groupIds) && groupIds.some((i) => i === targetGroupId)) { return { success: false, message: "患者已进入相同分组", }; } const allGroupId = [...groupIds, targetGroupId]; const groups = await db .collection("group") .find({ _id: { $in: allGroupId }, corpId, }) .toArray(); if (groups.length === 0 || !Array.isArray(groups)) { return { success: false, message: "未获取到分组", }; } const targetGroup = groups.find((i) => i._id === targetGroupId); // 获取目标分组 if (!targetGroup) { return { success: false, message: "未获取到目标分组", }; } const { managementPlan } = targetGroup; let customerGroupIds = []; if (groupIds.length === 0) { customerGroupIds = [targetGroupId]; } else { // 获取客户分组 const customerGroups = groups.filter((i) => groupIds.some((j) => j === i._id) ); let res = groupRules({ customerGroups, targetGroup }); if (!res.success) return res; customerGroupIds = allGroupId; } await updateGroupIdForMember({ customerGroupIds, customer, managementPlan, executeTeamId, executeTeamName, corpId, executeUserId, planExecutionTime, }); return { success: true, message: "进组成功", }; }; function groupRules({ customerGroups, targetGroup }) { const { parentGroupId: targetParentGroupId, teamId: targetTeamId } = targetGroup; // 如果存在targetParentGroupId 则此分组为机构分组 if (targetParentGroupId && customerGroups.some((i) => i.parentGroupId)) { return { success: false, message: "患者已进入其他机构分组", }; } else if (customerGroups.some((i) => i.teamId === targetTeamId)) { return { success: false, message: "患者已入团队下其他分组", }; } return { success: true, customerGroupIds: [], }; } async function updateGroupIdForMember(context) { const { customerGroupIds, customer, executeTeamId, executeTeamName, managementPlan = {}, executeUserId, corpId, } = context; // 更新患者信息分组信息 await db.collection("member").updateOne( { _id: customer._id }, { $set: { groupIds: customerGroupIds }, } ); let { taskList, planId, planName } = managementPlan; taskList = taskList.map((item) => { const { timeType, taskTime } = item; if (timeType) { item["planExecutionTime"] = dayjs().add(taskTime, timeType).valueOf(); } else { item["planExecutionTime"] = dayjs().add(taskTime, "day").valueOf(); } return item; }); if (planId) { const params = { corpId, customerId: customer._id || "", customerName: customer.name || "", customerUserId: customer.externalUserId || "", executeTeamId, executeTeamName, taskList, planId, planName, userId: executeUserId, }; const res = await appFunction.executeManagementPlanTodo(params); console.log("res", res); } }