263 lines
7.5 KiB
JavaScript
Raw Normal View History

2026-07-27 11:28:33 +08:00
const dayjs = require("dayjs");
const utils = require("../utils.js");
const appFunction = require("../app-function");
const api = require("../../api.js");
const common = require("../../common.js");
let db = null;
exports.main = async (event, DB) => {
db = DB;
switch (event.type) {
case "pushtoDoCountToCorpApp":
return await pushtoDoCountToCorpApp(event);
case "updatExpireStatus":
return await updatExpireStatus(event);
case "batchCreateGroupMsgTaskByTodo":
return await batchCreateGroupMsgTaskByTodo(event);
}
};
// 更新过期状态
async function updatExpireStatus({ corpId }) {
let todayStartTime = dayjs().startOf("day").valueOf();
let todayEndTime = dayjs().endOf("day").valueOf();
let params = {
expireTime: { $gte: todayStartTime, $lte: todayEndTime },
eventStatus: "untreated",
};
if (corpId) params["corpId"] = corpId;
const fetchData = async (page, pageSize, db) => {
let data = await db
.collection("to-do-events")
.find(params)
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();
return data;
};
let events = await utils.getAllData(fetchData, db);
let expireListIds = Array.isArray(events)
? events.map((item) => item._id)
: [];
await db.collection("to-do-events").updateMany(
{ _id: { $in: expireListIds } },
{
$set: {
eventStatus: "expire",
result: "已过期",
endTime: new Date().getTime(),
},
}
);
// 任务过期 更新sop任务状态
await toDoEventCompleteUpdateSopTask(events);
return {
success: true,
message: "更新成功",
};
}
// 待办完成 更新sop任务状态
async function toDoEventCompleteUpdateSopTask(events) {
if (!events || events.length === 0) return;
// 筛选出sop任务
let sopTaskEvents = events.filter((item) => item.customerSopTaskId);
// 对sop任务根据corpId进行分组
const groupedEvents = groupByCorpId(sopTaskEvents);
for (const corpId in groupedEvents) {
const list = groupedEvents[corpId];
const customerSopTaskIds = list.map((item) => item.customerSopTaskId);
await appFunction.updateCustomerSopTaskStatus({
corpId,
customerSopTaskIds,
executeStatus: "failed",
});
}
}
function groupByCorpId(tasks) {
return tasks.reduce((acc, task) => {
const { corpId } = task;
if (!acc[corpId]) {
acc[corpId] = [];
}
acc[corpId].push(task);
return acc;
}, {});
}
async function pushtoDoCountToCorpApp({ corpId }) {
let currentTime = dayjs().startOf("day").valueOf();
let params = {
eventStatus: "untreated",
expireTime: { $gte: currentTime },
};
if (corpId) params["corpId"] = corpId;
const fetchData = async (page, pageSize, db) => {
let { data } = await db
.collection("to-do-events")
.find(params)
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();
return data;
};
let events = await utils.getAllData(fetchData, db);
if (events.length > 0) {
const list = events.reduce((result, current) => {
const executorUserId = current.executorUserId;
const existingCategory = result.find(
(item) => item[0].executorUserId === executorUserId
);
if (!existingCategory) {
result.push([current]);
} else {
existingCategory.push(current);
}
return result;
}, []);
if (list.length === 0) return;
let tasks = [];
for (const item of list) {
if (item.length === 0) continue;
const touser = item[0].executorUserId;
const corpId = item[0].corpId;
// 异步创建内容
const content = await createContext(item, touser, corpId);
if (!content) continue;
// 保存异步任务
tasks.push(pushAppToToMessage(touser, corpId, content));
}
// 每次执行最多 10 个任务
for (let i = 0; i < tasks.length; i += 10) {
const batch = tasks.slice(i, i + 10);
await Promise.all(batch);
}
}
return {
success: true,
message: "推送成功",
};
}
async function createContext(todoList, executorUserId, corpId) {
let startDay = dayjs().startOf("day").valueOf();
let endDay = dayjs().endOf("day").valueOf();
let teamList = await getTeamList(executorUserId, corpId);
let teamContext = "";
let incompleteCount = todoList.filter((item) => {
return (
item.plannedExecutionTime < endDay &&
teamList.some((i) => i.teamId === item.executeTeamId)
);
}).length;
teamList.forEach((i) => {
let teamTodoList = todoList.filter(
(item) => item.executeTeamId === i.teamId
);
if (teamTodoList.length > 0) {
teamContext += getTeamContext(teamTodoList, i);
}
});
if (!incompleteCount) return false;
let incompleteContext =
incompleteCount > 0 ? `未完成待办总数:${incompleteCount}\n` : "";
return `截止当前,${incompleteContext}${teamContext}请及时处理! <a href=\"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwc1c7baebf62eab4a&redirect_uri=https%3A%2F%2Fwww.youcan365.com%2Fdist%2F%23%2FWORK&response_type=code&scope=snsapi_privateinfo&state=STATE#wechat_redirect\">立即查看</a>`;
}
function getTeamContext(teamTodoList, team) {
return `${team.name}:${teamTodoList.length}\n`;
}
async function getTeamList(executorUserId, corpId) {
const result = await api.getCorpApi({
type: "getTeamBymember",
corpUserId: executorUserId,
corpId,
});
if (result && Array.isArray(result.data) && result.data.length > 0)
return result.data;
else return [];
}
async function pushAppToToMessage(touser, corpId, content) {
if (!corpId) return;
let result = await api.getCorpApi({
type: "getCorpInfo",
corpId,
});
let corp = result.data[0];
let agentid = corp.auth_info.agent[0].agentid;
console.log("agentid", agentid, content, touser);
let res = await api.getWecomApi({
type: "pushAppMessage",
corpid: corpId,
touser,
agentid,
content,
});
console.log(res);
}
// 生成群发消息任务
async function batchCreateGroupMsgTaskByTodo() {
let todayStartTime = dayjs().startOf("day").valueOf();
let todayEndTime = dayjs().endOf("day").valueOf();
let params = {
plannedExecutionTime: { $gte: todayStartTime, $lte: todayEndTime },
executeMethod: "groupTask",
};
const fetchData = async (page, pageSize, db) => {
let data = await db
.collection("to-do-events")
.find(params)
.skip((page - 1) * pageSize)
.limit(pageSize)
.toArray();
return data;
};
let events = await utils.getAllData(fetchData, db);
if (events.length === 0) return;
let groupMsgTasks = events.map(createGroupMsgTask).filter(Boolean);
if (groupMsgTasks.length > 0) {
for (let i = 0; i < groupMsgTasks.length; i += 10) {
const batch = groupMsgTasks.slice(i, i + 10);
await Promise.all(batch);
}
}
}
function createGroupMsgTask(item) {
const {
taskId,
customerId,
customerUserId,
sendContent,
fileList,
executorUserId,
corpId,
} = item;
const params = {
sendType: "MESSAGE",
executor: executorUserId,
customers: [customerId],
content: sendContent,
attachments: common.getAttachments(fileList, taskId, executorUserId),
startTaskDate: dayjs().valueOf(),
endTaskDate: dayjs().add(3, "day").endOf("day").valueOf(),
sendSource: "MINE",
teamIds: [],
creator: "system",
createSource: "MINE",
executeStatus: "doing",
corpId,
taskId,
externalUserIds: [customerUserId],
};
return appFunction.createGroupmsgTask({ params });
}