const utils = require("../utils"); const common = require("../../common"); let db = null; exports.main = async (content, DB) => { db = DB; switch (content.type) { case "syncCustomerTag": return await syncCustomerTag(content); } }; async function syncCustomerTag(context) { try { const { env, corpId, tags, externalUserId, customterName } = context; const query = { corpId, relationship: "本人", externalUserId, }; // 获取当前客户数据 let data = await db.collection("member").find(query).toArray(); if (data.length === 0) { // 给客户自动建档 await db.collection("member").insertOne({ _id: common.generateRandomString(24), corpId, name: customterName, externalUserId, relationship: "本人", tagIds: tags, }); } else { for (let i of data) { const { _id } = i; // 更新客户标签 // 合并标签 if (i.tagIds && Array.isArray(i.tagIds)) { // 合并标签并去重 i.tagIds = Array.from(new Set([...i.tagIds, ...tags])); } else { i.tagIds = tags; } await db.collection("member").updateOne( { _id }, { $set: { tagIds: i.tagIds } } ); } } return { success: true, message: "标签同步成功", }; } catch (error) { return { success: false, message: "标签同步失败", }; } }