feat: 项目总群自动建群+任务负责人后台视角+客户群活码进群+任务编辑

- 项目总群:≥3 人 appchat/create 自动建群(chatid=pgc+projectId),成员 diff 增删同步;DROP project_group_chats;推送改 appchat/send 群发、无群降级逐人
- 任务负责人:tasks.owner_userid(新建/编辑任务通讯录选人),task_set_owner 分配即预建 tgc 任务群发介绍,群主链接只归属负责人
- 任务编辑 task_update:基础字段+截图任务数量/关键词/说明,contents 调平只删 available 尾行
- 删除「一键推送」:task-one-click-push-service 整体移除(recordCardAck 移入 wecom-callback-events)
- 负责人后台视角:users.wecom_userid 绑定,lib/owner-scope 行级过滤(undefined=全量/""=空范围/非空=过滤),~30 action 补 managerGate/taskOwnerGate,owner 登录仅见工作台/任务中心/数据回收/复盘报表
- 任务绑定客户群+进群活码:tasks 增 customer_chat_id/name、join_config_id、join_qr_code 4 列,join_way add/update/get/del(换绑走 update 保 config_id 活码不变),后台「客户群」弹窗,portal 认领后扫码自助进群(满员自动开新群)
- 迁移 0013/0014/0015;催办支持按任务;企微可信域名 IP 验证文件
- 288 测试全绿;真机全链路验收通过(列群/活码四端点/portal 渲染/解绑清空)
This commit is contained in:
ABAPPLO
2026-09-04 18:03:46 +08:00
parent 5430624a43
commit dd5b603149
44 changed files with 4655 additions and 2039 deletions

View File

@@ -0,0 +1,204 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
const actionRoute = readFileSync(
new URL("../app/api/action/route.ts", import.meta.url),
"utf8",
);
const bootstrapRoute = readFileSync(
new URL("../app/api/bootstrap/route.ts", import.meta.url),
"utf8",
);
const taskReportExportRoute = readFileSync(
new URL("../app/api/task-report-export/route.ts", import.meta.url),
"utf8",
);
const recoveryExportRoute = readFileSync(
new URL("../app/api/recovery-export/route.ts", import.meta.url),
"utf8",
);
const screenshotTaskExportRoute = readFileSync(
new URL("../app/api/screenshot-task-export/route.ts", import.meta.url),
"utf8",
);
const taskResultImageRoute = readFileSync(
new URL("../app/api/task-result-image/route.ts", import.meta.url),
"utf8",
);
const usersRoute = readFileSync(
new URL("../app/api/users/route.ts", import.meta.url),
"utf8",
);
const mvpDb = readFileSync(
new URL("../lib/mvp-db.ts", import.meta.url),
"utf8",
);
function section(source, action) {
const start = source.indexOf(`"${action}"`);
assert.ok(start >= 0, `action ${action} 不存在于路由源码`);
const next = source.indexOf("} else if (body.action ===", start);
return source.slice(start, next === -1 ? undefined : next);
}
test("manager-only actions gate on owner scope", () => {
const managerOnly = [
"inspect_feishu",
"create_task",
"create_screenshot_task",
"claim",
"save_collection_schedule",
"run_due_collections",
"retry_failed_collections",
"backfill_account_profiles",
"set_public_account_ids",
"bind_wecom_external_id",
"send_test_wecom",
"trigger_wecom_overdue_escalation",
"wecom_list_external_contacts",
"wecom_list_internal_contacts",
"wecom_sync_group_chats",
"project_list",
"project_detail",
"project_save",
"project_delete",
"project_ensure_main_chat",
"task_set_owner",
"task_update",
"partner_save",
"partner_group_owners",
"project_push_task",
"refresh_account_fields",
"account_field_refresh_status",
];
for (const action of managerOnly) {
const body = section(actionRoute, action);
assert.match(
body,
/managerGate\(\)/,
`${action} 必须 managerGate() 拒绝任务负责人`,
);
}
});
test("collect actions stay manager-only", () => {
const body = section(actionRoute, "collect_now");
assert.match(body, /managerGate\(\)/);
});
test("task-scoped actions verify ownership for task owners", () => {
for (const action of [
"wecom_push_task_to_groups",
"task_group_links",
"task_group_push",
"task_customer_chats",
"task_bind_customer_chat",
]) {
const body = section(actionRoute, action);
assert.match(
body,
/taskOwnerGate\(/,
`${action} 必须校验任务归属`,
);
}
const dueSoon = section(actionRoute, "trigger_wecom_due_soon");
assert.match(dueSoon, /taskOwnerGate\(/);
assert.match(dueSoon, /runDueSoonWecomNotifications\(\s*db,\s*wecomConfig,\s*undefined,\s*undefined,\s*taskId \|\| undefined,/);
const pushes = section(actionRoute, "wecom_task_group_pushes");
assert.match(pushes, /taskOwnerGate\(/);
const manual = section(actionRoute, "manual_metrics");
assert.match(manual, /distributionOwnerGate\(/);
});
test("task_report_list scopes reports by owner and drops the broken gate", () => {
const body = section(actionRoute, "task_report_list");
assert.match(body, /getTaskReportData\(db, ownerScopeUserid\(scope\)\)/);
assert.ok(
!/isManagerRequest/.test(body),
"task_report_list 不再是管理员专属(负责人按 scope 过滤)",
);
});
test("no unawaited isManagerRequest gates remain", () => {
assert.ok(
!actionRoute.includes("if (!isManagerRequest(request))"),
"isManagerRequest 返回 Promise,缺 await 的门形同虚设",
);
});
test("action fallthrough dashboard is owner-scoped", () => {
assert.match(
actionRoute,
/getDashboardData\(ownerScopeUserid\(scope\)\)/,
);
});
test("customer chat actions require a task owner before binding", () => {
for (const action of ["task_customer_chats", "task_bind_customer_chat"]) {
const body = section(actionRoute, action);
assert.match(
body,
/请先设置任务负责人/,
`${action} 必须在无负责人时明确报错`,
);
assert.match(body, /Response\.json\(/);
assert.ok(
!/getDashboardData/.test(body),
`${action} 显式返回,不能落兜底 dashboard`,
);
}
const bind = section(actionRoute, "task_bind_customer_chat");
assert.match(bind, /bindTaskCustomerChat\(/);
assert.match(bind, /unbindTaskCustomerChat\(/);
});
test("partner claim detail exposes join qr only for claimed tasks", () => {
const partnerRoute = readFileSync(
new URL("../app/api/partner/route.ts", import.meta.url),
"utf8",
);
assert.match(partnerRoute, /join_qr_code FROM tasks/);
assert.match(partnerRoute, /joinQrCode,/);
const portalPage = readFileSync(
new URL("../koc-portal/app/page.tsx", import.meta.url),
"utf8",
);
assert.match(portalPage, /joinQrCode\?: string/);
assert.match(portalPage, /join-qr-card/);
assert.match(portalPage, /isClaimOwner && payload\.claim\?\.joinQrCode/);
});
test("bootstrap scopes dashboard data by owner scope", () => {
assert.match(bootstrapRoute, /getOwnerScope\(request\)/);
assert.match(bootstrapRoute, /getDashboardData\(ownerScopeUserid\(scope\)\)/);
});
test("getDashboardData filters tasks and distributions by owner", () => {
const dashboard = mvpDb.slice(
mvpDb.indexOf("export async function getDashboardData"),
mvpDb.indexOf("export type TaskReportRow"),
);
const occurrences = dashboard.match(/WHERE t\.owner_userid = \?/g) ?? [];
assert.equal(
occurrences.length,
2,
"tasks 与 distributions 两条查询都要按 owner 过滤",
);
});
test("export routes enforce owner scope", () => {
assert.match(taskReportExportRoute, /getOwnerScope\(request\)/);
assert.match(taskReportExportRoute, /ownerScopeUserid\(await getOwnerScope\(request\)\)/);
assert.match(recoveryExportRoute, /isTaskOwner\(/);
assert.match(screenshotTaskExportRoute, /isTaskOwner\(/);
assert.match(taskResultImageRoute, /isDistributionOwner\(/);
});
test("users route supports wecom binding lifecycle", () => {
assert.match(usersRoute, /action === "set_wecom"/);
assert.match(usersRoute, /INSERT INTO users[\s\S]*?wecom_userid/);
assert.match(usersRoute, /SELECT id, username, role, wecom_userid, created_at/);
});

108
tests/owner-scope.test.mjs Normal file
View File

@@ -0,0 +1,108 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
isDistributionOwner,
isTaskOwner,
ownerScopeUserid,
} from "../lib/owner-scope.ts";
import { getTaskReportData } from "../lib/mvp-db.ts";
function captureDb(rowsByPattern) {
const captured = [];
const makeStatement = (sql, values) => ({
async first() {
captured.push({ sql, values });
for (const [pattern, rows] of rowsByPattern) {
if (pattern.test(sql)) return rows(values) ?? null;
}
return null;
},
async all() {
captured.push({ sql, values });
for (const [pattern, rows] of rowsByPattern) {
if (pattern.test(sql)) return { results: rows(values) ?? [] };
}
return { results: [] };
},
});
const db = {
prepare(sql) {
const unbound = makeStatement(sql, []);
return {
bind(...values) {
return makeStatement(sql, values);
},
first: unbound.first,
all: unbound.all,
};
},
};
return { db, captured };
}
test("isTaskOwner matches task owner_userid binding", async () => {
const { db, captured } = captureDb([
[
/FROM tasks WHERE id = \? AND owner_userid = \?/,
(values) =>
values[0] === "task-1" && values[1] === "zhangsan"
? { id: "task-1" }
: null,
],
]);
assert.equal(await isTaskOwner(db, "task-1", "zhangsan"), true);
assert.equal(await isTaskOwner(db, "task-2", "zhangsan"), false);
assert.equal(captured.length, 2);
});
test("isTaskOwner guards empty taskId / wecomUserId without querying", async () => {
const { db, captured } = captureDb([]);
assert.equal(await isTaskOwner(db, "task-1", ""), false);
assert.equal(await isTaskOwner(db, "", "zhangsan"), false);
assert.equal(await isTaskOwner(db, " ", "zhangsan"), false);
assert.equal(captured.length, 0);
});
test("isDistributionOwner resolves distribution → task owner", async () => {
const { db } = captureDb([
[
/FROM distributions d\s+JOIN tasks t ON t\.id = d\.task_id/,
(values) =>
values[0] === "dist-1" && values[1] === "zhangsan"
? { id: "dist-1" }
: null,
],
]);
assert.equal(await isDistributionOwner(db, "dist-1", "zhangsan"), true);
assert.equal(await isDistributionOwner(db, "dist-9", "zhangsan"), false);
assert.equal(await isDistributionOwner(db, "dist-1", ""), false);
});
test("ownerScopeUserid maps scope kinds to filter value", () => {
assert.equal(ownerScopeUserid({ kind: "full" }), undefined);
assert.equal(ownerScopeUserid({ kind: "owner", wecomUserId: "zhangsan" }), "zhangsan");
assert.equal(ownerScopeUserid({ kind: "owner", wecomUserId: "" }), "");
});
test("getTaskReportData filters by owner when ownerUserid given", async () => {
const { db, captured } = captureDb([[/FROM tasks t/, () => []]]);
await getTaskReportData(db, "zhangsan");
assert.equal(captured.length, 1);
assert.match(captured[0].sql, /WHERE t\.owner_userid = \?/);
assert.deepEqual(captured[0].values, ["zhangsan"]);
});
test("getTaskReportData keeps global aggregation without ownerUserid", async () => {
const { db, captured } = captureDb([[/FROM tasks t/, () => []]]);
await getTaskReportData(db);
assert.equal(captured.length, 1);
assert.ok(!/owner_userid = \?/.test(captured[0].sql));
assert.ok(!captured[0].values?.length);
});
test("getTaskReportData returns empty list for unbound owner (empty string scope)", async () => {
const { db, captured } = captureDb([[/FROM tasks t/, () => [{ id: "task-x" }]]]);
const rows = await getTaskReportData(db, "");
assert.deepEqual(rows, []);
assert.equal(captured.length, 0, "空范围不应执行查询(绑定 '' 会误配 owner_userid='' 的任务)");
});

View File

@@ -27,32 +27,23 @@ const taskRow = {
content_format: "image_text",
share_token: "tok-123",
project_id: "proj-1",
claimed_quantity: 0,
status: "active",
owner_userid: "owner-task",
task_chat_id: null,
};
const projectRow = {
id: "proj-1",
name: "项目一",
brand: "品牌A",
main_group_member_ids: JSON.stringify(["zhangsan", "lisi"]),
main_group_member_ids: JSON.stringify(["zhangsan", "lisi", "owner-proj"]),
owner_userid: "owner-proj",
main_chat_id: "",
status: "active",
note: "",
created_at: "2026-08-01",
};
function fakePushDb({
task = taskRow,
project = projectRow,
links = [
{ project_id: "proj-1", chat_id: "wr-1", partner_id: "p-1" },
{ project_id: "proj-1", chat_id: "wr-2", partner_id: "" },
],
groupChats = [
{ chat_id: "wr-1", name: "一群", owner_user_id: "zhangsan", member_count: 10, status: 0 },
{ chat_id: "wr-2", name: "二群", owner_user_id: "lisi", member_count: 5, status: 0 },
],
} = {}) {
function fakePushDb({ task = { ...taskRow }, project = { ...projectRow } } = {}) {
const executed = [];
const makeStatement = (sql, params = []) => ({
sql,
@@ -62,10 +53,25 @@ function fakePushDb({
},
async run() {
executed.push({ sql, params });
if (/UPDATE tasks SET task_chat_id/.test(sql)) {
task.task_chat_id = params[0];
}
return { meta: { changes: 1 } };
},
async first() {
executed.push({ sql, params });
if (/FROM tasks t\s+LEFT JOIN projects p/.test(sql)) {
return {
id: task.id,
name: task.name,
task_chat_id: task.task_chat_id ?? null,
task_owner_userid: task.owner_userid ?? null,
project_owner_userid: project ? (project.owner_userid ?? null) : null,
};
}
if (/SELECT task_chat_id FROM tasks/.test(sql)) {
return { task_chat_id: task.task_chat_id ?? null };
}
if (/FROM tasks WHERE id = \?/.test(sql)) return task;
if (/FROM projects WHERE id = \?/.test(sql)) return project;
return null;
@@ -75,36 +81,12 @@ function fakePushDb({
if (/FROM tasks WHERE project_id/.test(sql)) {
return { results: task ? [{ ...task }] : [] };
}
if (/FROM project_group_chats g/.test(sql)) {
return {
results: links
.filter((link) => link.project_id === params[0])
.map((link) => {
const chat = groupChats.find((item) => item.chat_id === link.chat_id);
return {
chat_id: link.chat_id,
partner_id: link.partner_id,
chat_name: chat ? chat.name : null,
owner_user_id: chat ? chat.owner_user_id : null,
member_count: chat ? chat.member_count : null,
chat_status: chat ? chat.status : null,
partner_name: null,
};
}),
};
}
if (/FROM wecom_group_chats/.test(sql)) {
return {
results: sql.includes(" IN (")
? groupChats.filter((row) => params.includes(row.chat_id))
: groupChats,
};
}
return { results: [] };
},
});
return {
executed,
task,
prepare(sql) {
return makeStatement(sql);
},
@@ -114,7 +96,7 @@ function fakePushDb({
};
}
function fakeWecomFetch(calls, { failAppFor = [] } = {}) {
function fakeWecomFetch(calls, chats, { failAppFor = [], failChatSend = [] } = {}) {
return async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
@@ -133,8 +115,40 @@ function fakeWecomFetch(calls, { failAppFor = [] } = {}) {
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template")) {
return Response.json({ errcode: 0, errmsg: "ok", msgid: "msg-1", fail_list: [] });
if (url.pathname.endsWith("/cgi-bin/appchat/create")) {
const body = JSON.parse(String(init.body ?? "{}"));
chats.set(body.chatid, { name: body.name, userlist: body.userlist });
return Response.json({ errcode: 0, errmsg: "ok", chatid: body.chatid });
}
if (url.pathname.endsWith("/cgi-bin/appchat/get")) {
const body = JSON.parse(String(init.body ?? "{}"));
const chat = chats.get(body.chatid);
if (!chat) {
return Response.json({ errcode: 60111, errmsg: "chat not found" });
}
return Response.json({
errcode: 0,
errmsg: "ok",
chat_info: { chatid: body.chatid, name: chat.name, userlist: chat.userlist },
});
}
if (url.pathname.endsWith("/cgi-bin/appchat/update")) {
const body = JSON.parse(String(init.body ?? "{}"));
const chat = chats.get(body.chatid);
if (!chat) {
return Response.json({ errcode: 60111, errmsg: "chat not found" });
}
for (const userid of body.add_user_list ?? []) {
if (!chat.userlist.includes(userid)) chat.userlist.push(userid);
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/appchat/send")) {
const body = JSON.parse(String(init.body ?? "{}"));
if (failChatSend.includes(body.chatid) || !chats.has(body.chatid)) {
return Response.json({ errcode: 60111, errmsg: "chat not found" });
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
return new Response("not found", { status: 404 });
};
@@ -151,86 +165,150 @@ test("buildProjectAppMessage targets internal members with claim url", () => {
assert.match(message, /领取链接:https:\/\/portal\.example\.com\/\?task=tok-123/);
});
test("pushProjectTask sends per-member app messages and group templates", async () => {
test("pushProjectTask broadcasts once into the main chat and sends the task chat", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb();
const db = fakePushDb({
project: { ...projectRow, main_chat_id: "pgcproj1" },
});
const chats = new Map([
["pgcproj1", { name: "【总群】项目一", userlist: ["zhangsan", "lisi", "owner-proj"] }],
]);
const calls = [];
const outcome = await pushProjectTask(
db,
{ taskId: "task-1", sendMainGroup: true, sendGroupChats: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls),
fakeWecomFetch(calls, chats),
);
const appCalls = calls.filter((call) =>
call.url.pathname.endsWith("/cgi-bin/message/send"),
assert.equal(outcome.mainChatMode, "group");
assert.deepEqual(outcome.appResults, [], "no per-member sends when chat exists");
const chatSends = calls.filter((call) =>
call.url.pathname.endsWith("/cgi-bin/appchat/send"),
);
assert.deepEqual(
appCalls.map((call) => JSON.parse(String(call.init.body)).touser),
["zhangsan", "lisi"],
"one message/send per main group member",
chatSends.map((call) => JSON.parse(String(call.init.body)).chatid).sort(),
["pgcproj1", "tgctask1"],
"one send into main chat and one into task chat",
);
for (const call of appCalls) {
assert.match(JSON.parse(String(call.init.body)).text.content, /【项目任务】测试任务/);
}
assert.equal(outcome.appResults.length, 2);
assert.ok(outcome.appResults.every((item) => item.ok));
const templateCalls = calls.filter((call) =>
call.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
);
assert.equal(templateCalls.length, 2, "one template per owner");
assert.equal(outcome.groupResults.length, 2);
assert.equal(outcome.groupChatCount, 2);
assert.equal(calls.filter((call) => call.url.pathname.endsWith("/cgi-bin/message/send")).length, 0);
assert.deepEqual(outcome.skippedReasons, []);
assert.equal(outcome.taskChat.sent, true);
assert.equal(outcome.taskChat.chatId, "tgctask1");
assert.equal(outcome.linkUrl, "https://portal.example.com/?task=tok-123");
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("single member failure does not block the rest of the push", async () => {
test("pushProjectTask falls back to per-member messages when main chat missing", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb();
const db = fakePushDb({ project: { ...projectRow, main_chat_id: "" } });
const chats = new Map();
const calls = [];
const outcome = await pushProjectTask(
db,
{ taskId: "task-1" },
{ taskId: "task-1", sendMainGroup: true, sendGroupChats: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls, { failAppFor: ["zhangsan"] }),
fakeWecomFetch(calls, chats),
);
assert.equal(outcome.mainChatMode, "per_member");
assert.deepEqual(
outcome.appResults.map((item) => [item.userid, item.ok]),
[
["zhangsan", false],
["lisi", true],
],
outcome.appResults.map((item) => item.userid).sort(),
["lisi", "owner-proj", "zhangsan"],
);
assert.match(outcome.appResults[0].error, /userid not found/);
const templateCalls = calls.filter((call) =>
call.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
);
assert.equal(templateCalls.length, 2, "group push still runs");
assert.ok(outcome.appResults.every((item) => item.ok));
assert.ok(outcome.skippedReasons.includes("项目总群未建,已逐人私信"));
assert.equal(outcome.taskChat.sent, true);
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("pushProjectTask skips empty targets instead of failing", async () => {
test("single member failure does not block the rest of the per-member push", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb({ project: { ...projectRow, main_chat_id: "" } });
const calls = [];
const outcome = await pushProjectTask(
db,
{ taskId: "task-1", sendMainGroup: true, sendGroupChats: false },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls, new Map(), { failAppFor: ["zhangsan"] }),
);
const byUserid = Object.fromEntries(
outcome.appResults.map((item) => [item.userid, item.ok]),
);
assert.equal(byUserid.zhangsan, false, "failed member recorded");
assert.equal(byUserid.lisi, true, "other members still sent");
assert.equal(byUserid["owner-proj"], true, "project owner also notified");
assert.match(
outcome.appResults.find((item) => !item.ok).error,
/userid not found/,
);
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("main chat send failure degrades to per-member push", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb({
project: { ...projectRow, main_chat_id: "pgcproj1" },
});
const chats = new Map([
["pgcproj1", { name: "【总群】项目一", userlist: ["zhangsan"] }],
]);
const calls = [];
const outcome = await pushProjectTask(
db,
{ taskId: "task-1", sendMainGroup: true, sendGroupChats: false },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls, chats, { failChatSend: ["pgcproj1"] }),
);
assert.equal(outcome.mainChatMode, "per_member");
assert.ok(
outcome.skippedReasons.some((reason) => /降级逐人私信/.test(reason)),
);
assert.equal(outcome.appResults.length, 3);
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("task chat is skipped with reason when no owner at all", async () => {
const db = fakePushDb({
project: { ...projectRow, main_group_member_ids: "[]" },
links: [{ project_id: "proj-1", chat_id: "wr-gone", partner_id: "" }],
groupChats: [],
task: { ...taskRow, owner_userid: "" },
project: { ...projectRow, owner_userid: "", main_group_member_ids: "[]" },
});
const calls = [];
const outcome = await pushProjectTask(
db,
{ taskId: "task-1" },
{ taskId: "task-1", sendMainGroup: false, sendGroupChats: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls),
fakeWecomFetch(calls, new Map()),
);
assert.deepEqual(outcome.skippedReasons, ["项目总群未配置成员", "项目没有可用的任务群"]);
assert.equal(calls.length, 0, "no wecom api calls expected");
assert.equal(outcome.taskChat.sent, false);
assert.equal(outcome.taskChat.chatId, "");
assert.equal(outcome.taskChat.reason, "任务与项目都未填负责人");
assert.ok(outcome.skippedReasons.includes("任务群未发送:任务与项目都未填负责人"));
assert.equal(calls.length, 0);
});
test("task chat is skipped when fewer than 2 members", async () => {
const db = fakePushDb({
task: { ...taskRow, owner_userid: "" },
project: { ...projectRow, owner_userid: "owner-proj", main_group_member_ids: "[]" },
});
const outcome = await pushProjectTask(
db,
{ taskId: "task-1", sendMainGroup: false, sendGroupChats: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch([], new Map()),
);
assert.equal(outcome.taskChat.reason, "任务群成员不足 2 人");
});
test("pushProjectTask rejects task without project or unknown task", async () => {
@@ -241,7 +319,7 @@ test("pushProjectTask rejects task without project or unknown task", async () =>
unlinked,
{ taskId: "task-1" },
resolveWecomConfig(baseBindings),
fakeWecomFetch([]),
fakeWecomFetch([], new Map()),
),
(error) => error instanceof ProjectError && /未挂项目/.test(error.message),
);
@@ -257,7 +335,7 @@ test("pushProjectTask rejects task without project or unknown task", async () =>
fakePushDb(),
{ taskId: "task-1", sendMainGroup: false, sendGroupChats: false },
resolveWecomConfig(baseBindings),
fakeWecomFetch([]),
fakeWecomFetch([], new Map()),
),
(error) => error instanceof ProjectError && /至少选择一个发送目标/.test(error.message),
);

View File

@@ -1,23 +1,100 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
projectMainChatId,
deleteProject,
ensureProjectMainChat,
effectiveProjectMembers,
findOrCreateGroupOwnerPartner,
getProjectDetail,
listProjects,
parseMemberIds,
ProjectError,
saveGroupOwnerPartner,
saveProject,
setProjectGroupChats,
} from "../lib/project-service.ts";
import {
clearWecomAccessTokenCacheForTests,
resolveWecomConfig,
} from "../lib/wecom-client.ts";
function fakeProjectDb({
projects = [],
links = [],
tasks = [],
groupChats = [],
partners = [],
} = {}) {
const baseBindings = {
WECOM_CORP_ID: "corp-test",
WECOM_AGENT_ID: "1000001",
WECOM_SECRET: "secret-test",
};
test.beforeEach(() => {
clearWecomAccessTokenCacheForTests();
});
function fakeWecom(options = {}) {
const calls = [];
const chats = new Map(options.chats ?? []);
const failCreate = options.failCreate ?? false;
const failGet = options.failGet ?? false;
const createExisted = options.createExisted ?? false;
const fetchImpl = async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
if (url.pathname.endsWith("/cgi-bin/gettoken")) {
return Response.json({
errcode: 0,
errmsg: "ok",
access_token: "token-test",
expires_in: 7200,
});
}
if (url.pathname.endsWith("/cgi-bin/appchat/create")) {
if (createExisted) {
return Response.json({ errcode: 86215, errmsg: "chatid existed" });
}
if (failCreate) {
return Response.json({ errcode: 60111, errmsg: "user not in scope" });
}
const body = JSON.parse(String(init.body ?? "{}"));
chats.set(body.chatid, { name: body.name, userlist: body.userlist });
return Response.json({ errcode: 0, errmsg: "ok", chatid: body.chatid });
}
if (url.pathname.endsWith("/cgi-bin/appchat/update")) {
const body = JSON.parse(String(init.body ?? "{}"));
const chat = chats.get(body.chatid);
if (!chat) {
return Response.json({ errcode: 60111, errmsg: "chat not found" });
}
for (const userid of body.add_user_list ?? []) {
if (!chat.userlist.includes(userid)) chat.userlist.push(userid);
}
for (const userid of body.del_user_list ?? []) {
chat.userlist = chat.userlist.filter((id) => id !== userid);
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/appchat/get")) {
if (failGet) {
return Response.json({ errcode: 86001, errmsg: "chatid invalid" });
}
const body = JSON.parse(String(init.body ?? "{}"));
const chat = chats.get(body.chatid);
if (!chat) {
return Response.json({ errcode: 60111, errmsg: "chat not found" });
}
return Response.json({
errcode: 0,
errmsg: "ok",
chat_info: {
chatid: body.chatid,
name: chat.name,
userlist: chat.userlist,
},
});
}
return new Response("not found", { status: 404 });
};
return { calls, fetchImpl, chats };
}
function fakeProjectDb({ projects = [], tasks = [], partners = [] } = {}) {
const executed = [];
const applyWrite = (sql, params) => {
const normalized = sql.trim();
@@ -28,12 +105,18 @@ function fakeProjectDb({
brand: params[2],
main_group_member_ids: params[3],
owner_userid: params[4],
main_chat_id: "",
status: "active",
note: params[5],
created_at: params[6],
});
return 1;
}
if (/^UPDATE projects SET main_chat_id/.test(normalized)) {
const row = projects.find((item) => item.id === params[1]);
if (row) row.main_chat_id = params[0];
return row ? 1 : 0;
}
if (/^UPDATE projects/.test(normalized)) {
const row = projects.find((item) => item.id === params[5]);
if (!row) return 0;
@@ -52,16 +135,6 @@ function fakeProjectDb({
projects.splice(index, 1);
return 1;
}
if (/^INSERT INTO project_group_chats/.test(normalized)) {
links.push({ project_id: params[1], chat_id: params[2], partner_id: params[3] });
return 1;
}
if (/^DELETE FROM project_group_chats/.test(normalized)) {
for (let index = links.length - 1; index >= 0; index -= 1) {
if (links[index].project_id === params[0]) links.splice(index, 1);
}
return 1;
}
if (/^UPDATE tasks SET project_id = ''/.test(normalized)) {
for (const task of tasks) {
if (task.project_id === params[0]) task.project_id = "";
@@ -103,6 +176,15 @@ function fakeProjectDb({
if (/FROM partners WHERE id = \?/.test(sql)) {
return partners.find((item) => item.id === params[0]) ?? null;
}
if (/partner_type = 'group_owner' AND wecom_userid = \?/.test(sql)) {
return (
partners.find(
(item) =>
item.partner_type === "group_owner" &&
item.wecom_userid === params[0],
) ?? null
);
}
return null;
},
async all() {
@@ -112,7 +194,6 @@ function fakeProjectDb({
results: projects.map((item) => ({
...item,
task_count: tasks.filter((task) => task.project_id === item.id).length,
group_chat_count: links.filter((link) => link.project_id === item.id).length,
})),
};
}
@@ -123,25 +204,6 @@ function fakeProjectDb({
.map((task) => ({ ...task })),
};
}
if (/FROM project_group_chats g/.test(sql)) {
return {
results: links
.filter((link) => link.project_id === params[0])
.map((link) => {
const chat = groupChats.find((item) => item.chat_id === link.chat_id);
return {
chat_id: link.chat_id,
partner_id: link.partner_id,
chat_name: chat ? chat.name : null,
owner_user_id: chat ? chat.owner_user_id : null,
member_count: chat ? chat.member_count : null,
chat_status: chat ? chat.status : null,
partner_name:
partners.find((item) => item.id === link.partner_id)?.name ?? null,
};
}),
};
}
if (/FROM partners/.test(sql)) {
return { results: partners.map((item) => ({ ...item })) };
}
@@ -150,9 +212,7 @@ function fakeProjectDb({
});
return {
projects,
links,
tasks,
groupChats,
partners,
executed,
prepare(sql) {
@@ -166,6 +226,19 @@ function fakeProjectDb({
};
}
const projectRow = (overrides = {}) => ({
id: "proj-1",
name: "A",
brand: "",
main_group_member_ids: "[]",
owner_userid: "",
main_chat_id: "",
status: "active",
note: "",
created_at: "2026-08-01",
...overrides,
});
test("parseMemberIds accepts lines, arrays and mixed separators, dedupes", () => {
assert.deepEqual(parseMemberIds("zhangsan\nlisi zhangsan"), ["zhangsan", "lisi"]);
assert.deepEqual(parseMemberIds(["a", " b ", "a"]), ["a", "b"]);
@@ -173,9 +246,18 @@ test("parseMemberIds accepts lines, arrays and mixed separators, dedupes", () =>
assert.deepEqual(parseMemberIds(" \n "), []);
});
test("saveProject inserts with proj- prefixed id and JSON members", async () => {
test("effectiveProjectMembers parses stored JSON and merges owner", () => {
assert.deepEqual(
effectiveProjectMembers('["u1","u2"]', "owner-a"),
["u1", "u2", "owner-a"],
);
assert.deepEqual(effectiveProjectMembers("u1\nu1,u2", ""), ["u1", "u2"]);
assert.deepEqual(effectiveProjectMembers('["u1"]', "u1"), ["u1"]);
});
test("saveProject inserts with proj- prefixed id and JSON members incl owner", async () => {
const db = fakeProjectDb();
const project = await saveProject(db, {
const { project, mainChat } = await saveProject(db, {
name: "暑期焕新",
brand: "青柠实验室",
mainGroupMemberIds: "zhangsan\nlisi\nzhangsan",
@@ -185,24 +267,20 @@ test("saveProject inserts with proj- prefixed id and JSON members", async () =>
assert.match(project.id, /^proj-/);
assert.equal(project.name, "暑期焕新");
assert.equal(project.ownerUserid, "owner-zhang");
assert.deepEqual(project.mainGroupMemberIds, ["zhangsan", "lisi"]);
assert.deepEqual(project.mainGroupMemberIds, ["zhangsan", "lisi", "owner-zhang"]);
assert.equal(db.projects.length, 1);
assert.equal(db.projects[0].status, "active");
assert.deepEqual(JSON.parse(db.projects[0].main_group_member_ids), [
"zhangsan",
"lisi",
"owner-zhang",
]);
assert.equal(mainChat.reason, "no_credentials", "no config → lazy chat");
});
test("saveProject updates existing row and rejects blank name", async () => {
const db = fakeProjectDb({
projects: [
{
id: "proj-1",
name: "旧名",
brand: "",
main_group_member_ids: "[]",
status: "active",
note: "",
created_at: "2026-08-01",
},
],
projects: [projectRow({ id: "proj-1", name: "旧名" })],
});
await saveProject(db, {
id: "proj-1",
@@ -214,7 +292,10 @@ test("saveProject updates existing row and rejects blank name", async () => {
assert.equal(db.projects[0].name, "新名");
assert.equal(db.projects[0].brand, "品牌");
assert.equal(db.projects[0].owner_userid, "owner-li");
assert.deepEqual(JSON.parse(db.projects[0].main_group_member_ids), ["wangwu"]);
assert.deepEqual(JSON.parse(db.projects[0].main_group_member_ids), [
"wangwu",
"owner-li",
]);
assert.equal(db.projects.length, 1, "update must not insert");
await assert.rejects(
@@ -231,63 +312,81 @@ test("saveProject rejects unknown id on update", async () => {
);
});
test("listProjects aggregates task and group chat counts", async () => {
test("saveProject with config creates main chat once members reach 3", async () => {
const db = fakeProjectDb();
const wecom = fakeWecom();
const { project, mainChat } = await saveProject(
db,
{
name: "满三人群",
mainGroupMemberIds: "u1\nu2",
ownerUserid: "owner-a",
},
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(mainChat.chatId, projectMainChatId(project.id));
assert.equal(mainChat.reason, undefined);
assert.equal(db.projects[0].main_chat_id, projectMainChatId(project.id));
const createBody = JSON.parse(
String(
wecom.calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/create"))
.init.body,
),
);
assert.equal(createBody.chatid, projectMainChatId(project.id));
assert.deepEqual(createBody.userlist.sort(), ["owner-a", "u1", "u2"]);
});
test("listProjects aggregates task counts and exposes mainChatId", async () => {
const db = fakeProjectDb({
projects: [
{
projectRow({
id: "proj-1",
name: "A",
brand: "",
main_group_member_ids: "[\"u1\",\"u2\"]",
status: "active",
note: "",
created_at: "2026-08-01",
},
main_group_member_ids: '["u1","u2"]',
main_chat_id: "pgcproj1",
}),
],
tasks: [
{ id: "t1", project_id: "proj-1" },
{ id: "t2", project_id: "proj-1" },
{ id: "t3", project_id: "" },
],
links: [{ project_id: "proj-1", chat_id: "wr-1", partner_id: "" }],
});
const projects = await listProjects(db);
assert.equal(projects.length, 1);
assert.equal(projects[0].taskCount, 2);
assert.equal(projects[0].groupChatCount, 1);
assert.equal(projects[0].mainChatId, "pgcproj1");
assert.deepEqual(projects[0].mainGroupMemberIds, ["u1", "u2"]);
});
test("getProjectDetail marks missing chats and dangling partners", async () => {
test("getProjectDetail returns tasks with owner and mainChat members", async () => {
const db = fakeProjectDb({
projects: [
{
projectRow({
id: "proj-1",
name: "A",
brand: "",
main_group_member_ids: "[]",
status: "active",
note: "",
created_at: "2026-08-01",
main_group_member_ids: '["u1"]',
owner_userid: "owner-a",
main_chat_id: "pgcproj1",
}),
],
tasks: [
{
id: "t1",
name: "任务一",
project_id: "proj-1",
owner_userid: "owner-a",
task_chat_id: "tgc_t1",
},
],
links: [
{ project_id: "proj-1", chat_id: "wr-1", partner_id: "p-1" },
{ project_id: "proj-1", chat_id: "wr-gone", partner_id: "" },
],
groupChats: [
{ chat_id: "wr-1", name: "一群", owner_user_id: "zhangsan", member_count: 12, status: 0 },
],
partners: [],
});
const detail = await getProjectDetail(db, "proj-1");
assert.equal(detail.groupChats.length, 2);
const alive = detail.groupChats.find((chat) => chat.chatId === "wr-1");
assert.equal(alive.missing, false);
assert.equal(alive.partnerName, "", "dangling partner shows blank name");
const gone = detail.groupChats.find((chat) => chat.chatId === "wr-gone");
assert.equal(gone.missing, true);
assert.equal(gone.name, "");
assert.equal(detail.project.taskCount, 1);
assert.equal(detail.project.mainChatId, "pgcproj1");
assert.equal(detail.tasks[0].owner_userid, "owner-a");
assert.equal(detail.tasks[0].task_chat_id, "tgc_t1");
assert.equal(detail.mainChat.chatId, "pgcproj1");
assert.deepEqual(detail.mainChat.members, ["u1", "owner-a"]);
});
test("getProjectDetail throws 404 for unknown project", async () => {
@@ -298,51 +397,9 @@ test("getProjectDetail throws 404 for unknown project", async () => {
);
});
test("setProjectGroupChats replaces links and dedupes chat ids", async () => {
test("deleteProject unlinks tasks", async () => {
const db = fakeProjectDb({
projects: [
{
id: "proj-1",
name: "A",
brand: "",
main_group_member_ids: "[]",
status: "active",
note: "",
created_at: "2026-08-01",
},
],
links: [{ project_id: "proj-1", chat_id: "wr-old", partner_id: "" }],
groupChats: [
{ chat_id: "wr-1", name: "一群", owner_user_id: "zhangsan", member_count: 12, status: 0 },
],
partners: [{ id: "p-1", name: "张三", wecom_userid: "zhangsan" }],
});
const detail = await setProjectGroupChats(db, "proj-1", [
{ chatId: "wr-1", partnerId: "p-1" },
{ chatId: "wr-1", partnerId: "p-1" },
{ chatId: " ", partnerId: "" },
]);
assert.equal(detail.groupChats.length, 1);
assert.equal(detail.groupChats[0].chatId, "wr-1");
assert.equal(detail.groupChats[0].partnerName, "张三");
assert.equal(db.links.length, 1);
assert.equal(db.links[0].chat_id, "wr-1");
});
test("deleteProject removes links and unlinks tasks", async () => {
const db = fakeProjectDb({
projects: [
{
id: "proj-1",
name: "A",
brand: "",
main_group_member_ids: "[]",
status: "active",
note: "",
created_at: "2026-08-01",
},
],
links: [{ project_id: "proj-1", chat_id: "wr-1", partner_id: "" }],
projects: [projectRow({ id: "proj-1" })],
tasks: [
{ id: "t1", project_id: "proj-1" },
{ id: "t2", project_id: "proj-2" },
@@ -350,7 +407,6 @@ test("deleteProject removes links and unlinks tasks", async () => {
});
await deleteProject(db, "proj-1");
assert.equal(db.projects.length, 0);
assert.equal(db.links.length, 0);
assert.equal(db.tasks[0].project_id, "");
assert.equal(db.tasks[1].project_id, "proj-2");
@@ -360,6 +416,216 @@ test("deleteProject removes links and unlinks tasks", async () => {
);
});
test("ensureProjectMainChat returns no_project for unknown ids", async () => {
const wecom = fakeWecom();
const db = fakeProjectDb();
const result = await ensureProjectMainChat(
db,
"proj-404",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.reason, "no_project");
assert.equal(result.chatId, null);
});
test("ensureProjectMainChat skips without app credentials", async () => {
const wecom = fakeWecom();
const db = fakeProjectDb({
projects: [projectRow({ main_group_member_ids: '["u1","u2","u3"]' })],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig({ ...baseBindings, WECOM_SECRET: "" }),
wecom.fetchImpl,
);
assert.equal(result.reason, "no_credentials");
assert.equal(result.chatId, null);
assert.equal(wecom.calls.length, 0);
});
test("ensureProjectMainChat skips creation when fewer than 3 members", async () => {
const wecom = fakeWecom();
const db = fakeProjectDb({
projects: [projectRow({ main_group_member_ids: '["u1","u2"]' })],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.reason, "not_enough_members");
assert.equal(result.chatId, null);
assert.equal(db.projects[0].main_chat_id, "");
assert.equal(
wecom.calls.filter((c) => c.url.pathname.endsWith("/cgi-bin/appchat/create"))
.length,
0,
);
});
test("ensureProjectMainChat probes before creating and persists chat id", async () => {
const wecom = fakeWecom();
const db = fakeProjectDb({
projects: [
projectRow({
name: "项目一",
main_group_member_ids: '["u1","u2"]',
owner_userid: "owner-a",
}),
],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "pgcproj1");
assert.deepEqual(result.members.sort(), ["owner-a", "u1", "u2"]);
assert.equal(db.projects[0].main_chat_id, "pgcproj1");
const paths = wecom.calls.map((c) => c.url.pathname);
assert.ok(paths.some((p) => p.endsWith("/cgi-bin/appchat/get")), "probe first");
assert.ok(paths.some((p) => p.endsWith("/cgi-bin/appchat/create")));
assert.ok(
paths.indexOf(paths.find((p) => p.endsWith("/cgi-bin/appchat/get"))) <
paths.indexOf(paths.find((p) => p.endsWith("/cgi-bin/appchat/create"))),
"probe precedes create",
);
});
test("ensureProjectMainChat is idempotent when chat already exists remotely", async () => {
const wecom = fakeWecom({
chats: [["pgcproj1", { name: "【总群】项目一", userlist: ["u1", "u2", "owner-a"] }]],
});
const db = fakeProjectDb({
projects: [
projectRow({
name: "项目一",
main_group_member_ids: '["u1","u2"]',
owner_userid: "owner-a",
}),
],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "pgcproj1");
assert.equal(db.projects[0].main_chat_id, "pgcproj1", "id persisted on recovery");
assert.equal(
wecom.calls.filter((c) => c.url.pathname.endsWith("/cgi-bin/appchat/create"))
.length,
0,
"no duplicate create",
);
});
test("ensureProjectMainChat diffs members add and del on existing chat", async () => {
const wecom = fakeWecom({
chats: [["pgcproj1", { name: "【总群】项目一", userlist: ["u1", "gone-user"] }]],
});
const db = fakeProjectDb({
projects: [
projectRow({
main_group_member_ids: '["u1","u2"]',
owner_userid: "owner-a",
main_chat_id: "pgcproj1",
}),
],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "pgcproj1");
const updateBody = JSON.parse(
String(
wecom.calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/update"))
.init.body,
),
);
assert.deepEqual(updateBody.add_user_list.sort(), ["owner-a", "u2"]);
assert.deepEqual(updateBody.del_user_list, ["gone-user"]);
});
test("ensureProjectMainChat reports warning and keeps main_chat_id empty on create failure", async () => {
const wecom = fakeWecom({ failCreate: true });
const db = fakeProjectDb({
projects: [projectRow({ main_group_member_ids: '["u1","u2","u3"]' })],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, null);
assert.match(result.warning, /创建失败/);
assert.equal(db.projects[0].main_chat_id, "", "chat id not persisted on failure");
});
test("ensureProjectMainChat adopts chat when create reports chatid existed", async () => {
// 可见范围非根部门时 appchat/get 永远 86001,但群实际已建过(create 返回 86215)
const wecom = fakeWecom({ failGet: true, createExisted: true });
const db = fakeProjectDb({
projects: [
projectRow({
name: "项目一",
main_group_member_ids: '["u1","u2"]',
owner_userid: "owner-a",
}),
],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "pgcproj1");
assert.equal(result.warning, undefined);
assert.equal(db.projects[0].main_chat_id, "pgcproj1", "existing chat id adopted");
});
test("ensureProjectMainChat falls back to add-only sync when get is unavailable", async () => {
const wecom = fakeWecom({
failGet: true,
chats: [["pgcproj1", { name: "【总群】项目一", userlist: ["u1", "gone-user"] }]],
});
const db = fakeProjectDb({
projects: [
projectRow({
main_group_member_ids: '["u1","u2"]',
owner_userid: "owner-a",
main_chat_id: "pgcproj1",
}),
],
});
const result = await ensureProjectMainChat(
db,
"proj-1",
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "pgcproj1");
assert.equal(result.warning, undefined);
const updateBody = JSON.parse(
String(
wecom.calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/update"))
.init.body,
),
);
assert.deepEqual(updateBody.add_user_list.sort(), ["owner-a", "u1", "u2"]);
assert.equal(updateBody.del_user_list, undefined, "no removals without member list");
});
test("saveGroupOwnerPartner inserts and updates group_owner partners", async () => {
const db = fakeProjectDb();
const created = await saveGroupOwnerPartner(db, {
@@ -382,3 +648,23 @@ test("saveGroupOwnerPartner inserts and updates group_owner partners", async ()
(error) => error instanceof ProjectError,
);
});
test("findOrCreateGroupOwnerPartner returns existing row without duplicating", async () => {
const db = fakeProjectDb({
partners: [
{ id: "partner-go-old", name: "负责人", wecom_userid: "owner-a", partner_type: "group_owner" },
],
});
const found = await findOrCreateGroupOwnerPartner(db, "owner-a");
assert.equal(found.id, "partner-go-old");
assert.equal(db.partners.length, 1);
});
test("findOrCreateGroupOwnerPartner creates partner with userid fallback name", async () => {
const db = fakeProjectDb();
const created = await findOrCreateGroupOwnerPartner(db, "owner-b");
assert.match(created.id, /^partner-go-/);
assert.equal(created.name, "owner-b");
assert.equal(created.wecom_userid, "owner-b");
assert.equal(db.partners.length, 1);
});

View File

@@ -462,10 +462,13 @@ test("provides simple username-password login and three server-enforced roles",
assert.match(usersPage, /不开放注册和个人改密/);
assert.match(usersPage, /普通用户/);
assert.match(usersPage, /管理员/);
assert.match(adminApp, /item\.key === "resources" && currentUser\.role === "user"/);
assert.match(
adminApp,
/isTaskOwnerView && \["resources", "partners"\]\.includes\(item\.key\)/,
);
assert.match(adminApp, /item\.key === "users" && !isManager/);
assert.match(bootstrapRoute, /principal\.user\.role === "user"/);
assert.match(bootstrapRoute, /accounts: \[\]/);
assert.match(bootstrapRoute, /getOwnerScope\(request\)/);
assert.match(bootstrapRoute, /getDashboardData\(ownerScopeUserid\(scope\)\)/);
assert.match(resourceExportRoute, /isManagerRequest/);
assert.match(schema, /authSessions/);
assert.match(schema, /backgroundJobs/);

View File

@@ -0,0 +1,219 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
bindTaskCustomerChat,
listOwnerCustomerChats,
unbindTaskCustomerChat,
} from "../lib/task-customer-chat-service.ts";
import { resolveWecomConfig } from "../lib/wecom-client.ts";
const baseBindings = {
WECOM_CORP_ID: "corp-test",
WECOM_AGENT_ID: "1000001",
WECOM_SECRET: "secret-test",
};
function fakeWecom(options = {}) {
const calls = [];
const fetchImpl = async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
if (url.pathname.endsWith("/cgi-bin/gettoken")) {
return Response.json({
errcode: 0,
errmsg: "ok",
access_token: "token-test",
expires_in: 7200,
});
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/add_join_way")) {
if (options.addErrcode) {
return Response.json({ errcode: options.addErrcode, errmsg: "add failed" });
}
return Response.json({ errcode: 0, errmsg: "ok", config_id: options.configId ?? "cfg-new" });
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/update_join_way")) {
if (options.updateErrcode) {
return Response.json({ errcode: options.updateErrcode, errmsg: "update failed" });
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/get_join_way")) {
if (options.getErrcode) {
return Response.json({ errcode: options.getErrcode, errmsg: "get failed" });
}
return Response.json({
errcode: 0,
errmsg: "ok",
join_way: { qr_code: options.qrCode ?? "https://p.qpic.cn/qr-live.png" },
});
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/del_join_way")) {
if (options.delErrcode) {
return Response.json({ errcode: options.delErrcode, errmsg: "del failed" });
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
return new Response("not found", { status: 404 });
};
return { calls, fetchImpl };
}
function captureDb(taskRow) {
const captured = [];
const makeStatement = (sql, values) => ({
async first() {
captured.push({ sql, values });
if (/FROM tasks WHERE id = \?/.test(sql)) return taskRow ?? null;
return null;
},
async run() {
captured.push({ sql, values });
return { changes: 1 };
},
});
const db = {
prepare(sql) {
const unbound = makeStatement(sql, []);
return {
bind(...values) {
return makeStatement(sql, values);
},
first: unbound.first,
run: unbound.run,
};
},
};
return { db, captured };
}
function callsTo(calls, suffix) {
return calls.filter((c) => c.url.pathname.endsWith(suffix));
}
test("listOwnerCustomerChats rejects without app credentials and ignores empty owner", async () => {
const config = resolveWecomConfig({ ...baseBindings, WECOM_SECRET: "" });
await assert.rejects(() => listOwnerCustomerChats(config, "zhangsan"), /未配置/);
const { calls, fetchImpl } = fakeWecom();
assert.deepEqual(await listOwnerCustomerChats(resolveWecomConfig(baseBindings), " ", fetchImpl), []);
assert.equal(calls.length, 0, "empty owner short-circuits without API calls");
});
test("bindTaskCustomerChat creates join way when task has no config", async () => {
const { db, captured } = captureDb({
id: "task-1",
name: "美团探店任务",
join_config_id: null,
});
const { calls, fetchImpl } = fakeWecom();
const result = await bindTaskCustomerChat(
db,
{ taskId: "task-1", chatId: "wr-normal-1", chatName: "KOC 一群" },
resolveWecomConfig(baseBindings),
fetchImpl,
);
assert.equal(callsTo(calls, "/cgi-bin/externalcontact/groupchat/add_join_way").length, 1);
assert.equal(callsTo(calls, "/cgi-bin/externalcontact/groupchat/update_join_way").length, 0);
const addBody = JSON.parse(String(callsTo(calls, "/add_join_way")[0].init.body));
assert.deepEqual(addBody.chat_id_list, ["wr-normal-1"]);
assert.equal(addBody.room_base_name, "美团探店任务");
assert.equal(addBody.state, "task-task-1");
assert.equal(result.joinConfigId, "cfg-new");
assert.equal(result.joinQrCode, "https://p.qpic.cn/qr-live.png");
assert.equal(result.qrError, undefined);
const update = captured.find((c) => /UPDATE tasks/.test(c.sql));
assert.ok(update, "tasks row updated");
assert.match(update.sql, /customer_chat_id = \?/);
assert.deepEqual(update.values, ["wr-normal-1", "KOC 一群", "cfg-new", "https://p.qpic.cn/qr-live.png", "task-1"]);
});
test("bindTaskCustomerChat reuses update_join_way on rebind and falls back to add", async () => {
const { db } = captureDb({ id: "task-1", name: "任务", join_config_id: "cfg-old" });
const { calls, fetchImpl } = fakeWecom();
const result = await bindTaskCustomerChat(
db,
{ taskId: "task-1", chatId: "wr-normal-2", chatName: "KOC 二群" },
resolveWecomConfig(baseBindings),
fetchImpl,
);
assert.equal(callsTo(calls, "/cgi-bin/externalcontact/groupchat/update_join_way").length, 1);
assert.equal(callsTo(calls, "/cgi-bin/externalcontact/groupchat/add_join_way").length, 0);
assert.equal(result.joinConfigId, "cfg-old", "config id preserved so qr stays valid");
const { db: db2 } = captureDb({ id: "task-1", name: "任务", join_config_id: "cfg-old" });
const { calls: calls2, fetchImpl: fetch2 } = fakeWecom({
updateErrcode: 40068,
configId: "cfg-rebuilt",
});
const result2 = await bindTaskCustomerChat(
db2,
{ taskId: "task-1", chatId: "wr-normal-2", chatName: "KOC 二群" },
resolveWecomConfig(baseBindings),
fetch2,
);
assert.equal(callsTo(calls2, "/cgi-bin/externalcontact/groupchat/update_join_way").length, 1);
assert.equal(callsTo(calls2, "/cgi-bin/externalcontact/groupchat/add_join_way").length, 1);
assert.equal(result2.joinConfigId, "cfg-rebuilt");
});
test("bindTaskCustomerChat tolerates qr fetch failure and records qrError", async () => {
const { db } = captureDb({ id: "task-1", name: "任务", join_config_id: null });
const { fetchImpl } = fakeWecom({ getErrcode: 40068 });
const result = await bindTaskCustomerChat(
db,
{ taskId: "task-1", chatId: "wr-normal-1", chatName: "KOC 一群" },
resolveWecomConfig(baseBindings),
fetchImpl,
);
assert.equal(result.joinQrCode, "");
assert.match(result.qrError, /活码二维码获取失败/);
});
test("bindTaskCustomerChat validates missing task / chat", async () => {
const { db: missingTask } = captureDb(null);
await assert.rejects(
() =>
bindTaskCustomerChat(
missingTask,
{ taskId: "task-x", chatId: "wr-1", chatName: "群" },
resolveWecomConfig(baseBindings),
fakeWecom().fetchImpl,
),
/任务不存在/,
);
const { db } = captureDb({ id: "task-1", name: "任务", join_config_id: null });
await assert.rejects(
() =>
bindTaskCustomerChat(
db,
{ taskId: "task-1", chatId: "", chatName: "" },
resolveWecomConfig(baseBindings),
fakeWecom().fetchImpl,
),
/请选择要绑定的客户群/,
);
});
test("unbindTaskCustomerChat deletes join way (tolerating failure) and clears columns", async () => {
const { db, captured } = captureDb({ id: "task-1", join_config_id: "cfg-old" });
const { calls, fetchImpl } = fakeWecom();
await unbindTaskCustomerChat(db, "task-1", resolveWecomConfig(baseBindings), fetchImpl);
assert.equal(callsTo(calls, "/cgi-bin/externalcontact/groupchat/del_join_way").length, 1);
const update = captured.find((c) => /UPDATE tasks/.test(c.sql));
assert.ok(update);
assert.match(update.sql, /customer_chat_id = ''/);
const { db: db2, captured: captured2 } = captureDb({ id: "task-1", join_config_id: "cfg-old" });
const { fetchImpl: fetch2 } = fakeWecom({ delErrcode: 40068 });
await unbindTaskCustomerChat(db2, "task-1", resolveWecomConfig(baseBindings), fetch2);
assert.ok(
captured2.some((c) => /UPDATE tasks/.test(c.sql)),
"local columns still cleared when del_join_way fails",
);
const { db: db3, captured: captured3 } = captureDb({ id: "task-1", join_config_id: "" });
const { calls: calls3, fetchImpl: fetch3 } = fakeWecom();
await unbindTaskCustomerChat(db3, "task-1", resolveWecomConfig(baseBindings), fetch3);
assert.equal(calls3.length, 0, "no wecom calls when nothing bound");
assert.ok(captured3.some((c) => /UPDATE tasks/.test(c.sql)));
});

View File

@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
assignTaskOwner,
ensureTaskChatForMembers,
sendTaskChatMessage,
taskChatId,
@@ -26,9 +27,10 @@ function fakeWecom(options = {}) {
const calls = [];
const chats = new Map(
options.chats ?? [
["tgc_task-existing", { name: "【任务】已有群", userlist: ["owner-a"] }],
["tgctaskexisting", { name: "【任务】已有群", userlist: ["owner-a"] }],
],
);
const failGet = options.failGet ?? false;
const fetchImpl = async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
@@ -57,6 +59,9 @@ function fakeWecom(options = {}) {
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/appchat/get")) {
if (failGet) {
return Response.json({ errcode: 86001, errmsg: "chatid invalid" });
}
const body = JSON.parse(String(init.body ?? "{}"));
const chat = chats.get(body.chatid);
if (!chat) {
@@ -118,7 +123,8 @@ function fakeDb({ task }) {
test("taskChatId derives a deterministic chatid within 32 chars", () => {
const taskId = "task-1a2b3c4d";
const chatid = taskChatId(taskId);
assert.equal(chatid, `tgc_${taskId}`);
assert.equal(chatid, "tgctask1a2b3c4d");
assert.ok(!/-/.test(chatid), "hyphens rejected by wecom chatid rules");
assert.ok(chatid.length <= 32);
});
@@ -129,7 +135,8 @@ test("ensureTaskChatForMembers skips when project has no owner", async () => {
id: "task-1",
name: "任务一",
task_chat_id: null,
owner_userid: null,
task_owner_userid: null,
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -150,7 +157,8 @@ test("ensureTaskChatForMembers skips creation when fewer than 2 members", async
id: "task-1",
name: "任务一",
task_chat_id: null,
owner_userid: "owner-a",
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -175,7 +183,8 @@ test("ensureTaskChatForMembers creates the chat lazily and stores chat id", asyn
id: "task-1a2b3c4d",
name: "任务一",
task_chat_id: null,
owner_userid: "owner-a",
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -184,7 +193,7 @@ test("ensureTaskChatForMembers creates the chat lazily and stores chat id", asyn
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "tgc_task-1a2b3c4d");
assert.equal(result.chatId, "tgctask1a2b3c4d");
assert.equal(result.created, true);
const createBody = JSON.parse(
String(
@@ -197,20 +206,48 @@ test("ensureTaskChatForMembers creates the chat lazily and stores chat id", asyn
statements.some(
(statement) =>
/UPDATE tasks SET task_chat_id/.test(statement.sql) &&
statement.values[0] === "tgc_task-1a2b3c4d",
statement.values[0] === "tgctask1a2b3c4d",
),
"chat id persisted to tasks",
);
});
test("ensureTaskChatForMembers dedupes project owner, task owner and claimants", async () => {
const wecom = fakeWecom({ chats: [] });
const { db } = fakeDb({
task: {
id: "task-1",
name: "任务一",
task_chat_id: null,
task_owner_userid: "owner-a",
project_owner_userid: "owner-a",
},
});
const result = await ensureTaskChatForMembers(
db,
{ taskId: "task-1", addUserids: ["owner-a", "zhangsan"] },
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "tgctask1");
const createBody = JSON.parse(
String(
wecom.calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/create"))
.init.body,
),
);
assert.deepEqual(createBody.userlist.sort(), ["owner-a", "zhangsan"]);
});
test("ensureTaskChatForMembers reuses stored chat and diffs members", async () => {
const wecom = fakeWecom();
const { db, statements } = fakeDb({
task: {
id: "task-existing",
name: "已有任务",
task_chat_id: "tgc_task-existing",
owner_userid: "owner-a",
task_chat_id: "tgctaskexisting",
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -219,7 +256,7 @@ test("ensureTaskChatForMembers reuses stored chat and diffs members", async () =
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "tgc_task-existing");
assert.equal(result.chatId, "tgctaskexisting");
assert.equal(result.created, false);
assert.equal(
statements.filter((s) => /UPDATE tasks/.test(s.sql)).length,
@@ -235,14 +272,19 @@ test("ensureTaskChatForMembers reuses stored chat and diffs members", async () =
assert.deepEqual(updateBody.add_user_list, ["zhangsan"]);
});
test("ensureTaskChatForMembers recovers when chat exists remotely but not in db", async () => {
const wecom = fakeWecom();
const { db, statements } = fakeDb({
test("ensureTaskChatForMembers syncs add-only when get is unavailable", async () => {
// 可见范围非根部门时 appchat/get 拿不到群成员,降级为全量只增同步
const wecom = fakeWecom({
failGet: true,
chats: [["tgctaskexisting", { name: "【任务】已有群", userlist: ["owner-a"] }]],
});
const { db } = fakeDb({
task: {
id: "task-existing",
name: "已有任务",
task_chat_id: null,
owner_userid: "owner-a",
task_chat_id: "tgctaskexisting",
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -251,7 +293,35 @@ test("ensureTaskChatForMembers recovers when chat exists remotely but not in db"
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "tgc_task-existing");
assert.equal(result.chatId, "tgctaskexisting");
const updateBody = JSON.parse(
String(
wecom.calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/update"))
.init.body,
),
);
assert.deepEqual(updateBody.add_user_list.sort(), ["owner-a", "zhangsan"]);
assert.equal(updateBody.del_user_list, undefined, "add-only fallback");
});
test("ensureTaskChatForMembers recovers when chat exists remotely but not in db", async () => {
const wecom = fakeWecom();
const { db, statements } = fakeDb({
task: {
id: "task-existing",
name: "已有任务",
task_chat_id: null,
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
db,
{ taskId: "task-existing", addUserids: ["zhangsan"] },
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.chatId, "tgctaskexisting");
assert.equal(result.created, false);
assert.ok(statements.some((s) => /UPDATE tasks SET task_chat_id/.test(s.sql)));
});
@@ -263,7 +333,8 @@ test("ensureTaskChatForMembers skips without app credentials", async () => {
id: "task-1",
name: "任务一",
task_chat_id: null,
owner_userid: "owner-a",
task_owner_userid: "owner-a",
project_owner_userid: null,
},
});
const result = await ensureTaskChatForMembers(
@@ -295,7 +366,7 @@ test("sendTaskChatMessage no-ops without chat id and swallows errors", async ()
const failing = fakeWecom({ chats: [] });
const withChat = fakeDb({
task: { id: "task-existing", task_chat_id: "tgc_task-existing" },
task: { id: "task-existing", task_chat_id: "tgctaskexisting" },
});
assert.equal(
await sendTaskChatMessage(
@@ -313,7 +384,7 @@ test("sendTaskChatMessage no-ops without chat id and swallows errors", async ()
test("sendTaskChatMessage sends text into the task chat", async () => {
const wecom = fakeWecom();
const { db } = fakeDb({
task: { id: "task-existing", task_chat_id: "tgc_task-existing" },
task: { id: "task-existing", task_chat_id: "tgctaskexisting" },
});
assert.equal(
await sendTaskChatMessage(
@@ -331,7 +402,7 @@ test("sendTaskChatMessage sends text into the task chat", async () => {
.init.body,
),
);
assert.equal(sendBody.chatid, "tgc_task-existing");
assert.equal(sendBody.chatid, "tgctaskexisting");
assert.equal(sendBody.text.content, "【领取】张三 认领 5 份");
});
@@ -350,3 +421,219 @@ test("broadcast and intro text builders format messages", () => {
assert.match(intro, /品牌:品牌A/);
assert.match(intro, /截止:2026-09-30/);
});
function assignDb({ task, project, partners = [] }) {
const store = {
task: { ...task },
project: project ? { ...project } : null,
partners: partners.map((item) => ({ ...item })),
};
const statements = [];
const db = {
prepare(sql) {
return {
bind(...values) {
return {
async first() {
statements.push({ sql, values });
if (/FROM tasks t\s+LEFT JOIN projects p/.test(sql)) {
return {
id: store.task.id,
name: store.task.name,
task_chat_id: store.task.task_chat_id ?? null,
task_owner_userid: store.task.owner_userid ?? null,
project_owner_userid: store.project?.owner_userid ?? null,
};
}
if (/SELECT task_chat_id FROM tasks/.test(sql)) {
return { task_chat_id: store.task.task_chat_id ?? null };
}
if (/SELECT id, name, brand, quantity, due_at, project_id FROM tasks/.test(sql)) {
return { ...store.task };
}
if (/SELECT main_group_member_ids, owner_userid FROM projects/.test(sql)) {
return store.project
? {
main_group_member_ids: store.project.main_group_member_ids,
owner_userid: store.project.owner_userid ?? "",
}
: null;
}
if (/SELECT id, name, main_group_member_ids, owner_userid, main_chat_id FROM projects/.test(sql)) {
return store.project
? {
id: store.project.id,
name: store.project.name,
main_group_member_ids: store.project.main_group_member_ids,
owner_userid: store.project.owner_userid ?? "",
main_chat_id: store.project.main_chat_id ?? "",
}
: null;
}
if (/partner_type = 'group_owner' AND wecom_userid = \?/.test(sql)) {
return (
store.partners.find(
(item) =>
item.partner_type === "group_owner" &&
item.wecom_userid === values[0],
) ?? null
);
}
if (/FROM partners WHERE id = \?/.test(sql)) {
return store.partners.find((item) => item.id === values[0]) ?? null;
}
return null;
},
async run() {
statements.push({ sql, values });
if (/UPDATE tasks SET owner_userid/.test(sql)) {
store.task.owner_userid = values[0];
} else if (/UPDATE tasks SET task_chat_id/.test(sql)) {
store.task.task_chat_id = values[0];
} else if (/UPDATE projects SET main_group_member_ids/.test(sql)) {
if (store.project) store.project.main_group_member_ids = values[0];
} else if (/UPDATE projects SET main_chat_id/.test(sql)) {
if (store.project) store.project.main_chat_id = values[0];
} else if (/INSERT INTO partners/.test(sql)) {
store.partners.push({
id: values[0],
name: values[1],
wecom_userid: values[2],
partner_type: "group_owner",
});
}
return { meta: { changes: 1, last_row_id: 0 } };
},
async all() {
statements.push({ sql, values });
return { results: [] };
},
};
},
};
},
};
return { db, statements, store };
}
test("assignTaskOwner provisions partner, main chat and task chat with intro", async () => {
const wecom = fakeWecom({ chats: [] });
const { db, statements, store } = assignDb({
task: {
id: "task-1",
name: "任务一",
brand: "品牌A",
quantity: 10,
due_at: "2026-09-30",
project_id: "proj-1",
owner_userid: "",
task_chat_id: null,
},
project: {
id: "proj-1",
name: "项目一",
owner_userid: "proj-owner",
main_group_member_ids: JSON.stringify(["proj-owner", "u1", "u2"]),
main_chat_id: "",
},
});
const result = await assignTaskOwner(
db,
{ taskId: "task-1", ownerUserid: "owner-a" },
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.ownerUserid, "owner-a");
assert.equal(result.chatCreated, true);
assert.equal(result.chatId, "tgctask1");
assert.match(result.partnerId, /^partner-go-/);
assert.equal(store.task.owner_userid, "owner-a");
assert.deepEqual(
JSON.parse(store.project.main_group_member_ids).sort(),
["proj-owner", "u1", "u2", "owner-a"].sort(),
"task owner merged into main group members",
);
assert.equal(store.project.main_chat_id, "pgcproj1", "main chat created lazily");
assert.ok(wecom.chats.has("pgcproj1"));
assert.ok(wecom.chats.has("tgctask1"));
const sendBodies = wecom.calls
.filter((c) => c.url.pathname.endsWith("/cgi-bin/appchat/send"))
.map((c) => JSON.parse(String(c.init.body)));
assert.equal(sendBodies.length, 1, "intro message sent once to task chat");
assert.equal(sendBodies[0].chatid, "tgctask1");
assert.match(sendBodies[0].text.content, /【新任务】任务一/);
assert.ok(
statements.some((s) => /INSERT INTO partners/.test(s.sql)),
"partner insert recorded",
);
});
test("assignTaskOwner reuses the existing group_owner partner", async () => {
const wecom = fakeWecom({ chats: [] });
const { db, statements, store } = assignDb({
task: {
id: "task-1",
name: "任务一",
brand: "品牌A",
quantity: 10,
due_at: "2026-09-30",
project_id: "",
owner_userid: "",
task_chat_id: null,
},
partners: [
{ id: "partner-go-existing", name: "老负责人", wecom_userid: "owner-a", partner_type: "group_owner" },
],
});
const result = await assignTaskOwner(
db,
{ taskId: "task-1", ownerUserid: "owner-a" },
resolveWecomConfig(baseBindings),
wecom.fetchImpl,
);
assert.equal(result.partnerId, "partner-go-existing");
assert.equal(
statements.filter((s) => /INSERT INTO partners/.test(s.sql)).length,
0,
"no duplicate partner insert",
);
assert.equal(store.partners.length, 1);
});
test("assignTaskOwner collects wecom failure as warning instead of throwing", async () => {
const fetchImpl = async (input) => {
const url = new URL(String(input));
if (url.pathname.endsWith("/cgi-bin/gettoken")) {
return Response.json({ errcode: 0, errmsg: "ok", access_token: "t", expires_in: 7200 });
}
return Response.json({ errcode: 60111, errmsg: "chat not found" });
};
const { db, store } = assignDb({
task: {
id: "task-1",
name: "任务一",
brand: "品牌A",
quantity: 10,
due_at: "2026-09-30",
project_id: "proj-1",
owner_userid: "",
task_chat_id: null,
},
project: {
id: "proj-1",
name: "项目一",
owner_userid: "proj-owner",
main_group_member_ids: JSON.stringify(["u1", "u2"]),
main_chat_id: "",
},
});
const result = await assignTaskOwner(
db,
{ taskId: "task-1", ownerUserid: "owner-a" },
resolveWecomConfig(baseBindings),
fetchImpl,
);
assert.equal(result.ownerUserid, "owner-a");
assert.ok(result.warning, "wecom failure surfaced as warning");
assert.equal(store.task.owner_userid, "owner-a", "owner still persisted");
});

View File

@@ -1,250 +0,0 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
buildKocDirectMessage,
oneClickPushTask,
OneClickPushError,
} from "../lib/task-one-click-push-service.ts";
import {
clearWecomAccessTokenCacheForTests,
resolveWecomConfig,
} from "../lib/wecom-client.ts";
const baseBindings = {
WECOM_CORP_ID: "corp-test",
WECOM_AGENT_ID: "1000001",
WECOM_SECRET: "secret-test",
};
const taskRow = {
id: "task-1",
name: "测试任务",
brand: "品牌A",
quantity: 3,
due_at: "2026-09-05",
task_type: "content_publish",
platform: "小红书",
content_format: "image_text",
share_token: "tok-123",
project_id: "",
};
const boundPartners = [
{ id: "p-1", name: "合作方甲", wecom_external_user_id: "wmOK1" },
{ id: "p-2", name: "合作方乙", wecom_external_user_id: "wmOK2" },
{ id: "p-3", name: "合作方丙", wecom_external_user_id: "wmFAIL" },
];
function fakePushDb({
task = taskRow,
partners = boundPartners,
todayLog = null,
} = {}) {
const executed = [];
const makeStatement = (sql, params = []) => ({
sql,
params,
bind(...args) {
return makeStatement(sql, args);
},
async run() {
executed.push({ sql, params });
return { meta: { changes: 1 } };
},
async first() {
executed.push({ sql, params });
if (/FROM tasks WHERE id = \?/.test(sql)) return task;
if (/FROM wecom_push_logs/.test(sql) && /DATE\(created_at\) = CURDATE\(\)/.test(sql)) {
return todayLog;
}
return null;
},
async all() {
executed.push({ sql, params });
if (/FROM partners/.test(sql) && /wecom_external_user_id/.test(sql)) {
return { results: partners };
}
return { results: [] };
},
});
return {
executed,
prepare(sql) {
return makeStatement(sql);
},
};
}
function fakeWecomFetch(calls, { invalidUsers = [] } = {}) {
return async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
if (url.pathname.endsWith("/cgi-bin/gettoken")) {
return Response.json({
errcode: 0,
errmsg: "ok",
access_token: "token-test",
expires_in: 7200,
});
}
if (url.pathname.endsWith("/cgi-bin/message/send")) {
const body = JSON.parse(String(init.body));
if (invalidUsers.includes(body.touser)) {
return Response.json({
errcode: 0,
errmsg: "ok",
invaliduser: body.touser,
});
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
return new Response("not found", { status: 404 });
};
}
test.beforeEach(() => {
clearWecomAccessTokenCacheForTests();
});
test("buildKocDirectMessage targets KOC with claim url and OAuth hint", () => {
const message = buildKocDirectMessage(taskRow, "https://portal.example.com/");
assert.match(message, /【新任务】测试任务/);
assert.match(message, /先到先得/);
assert.match(message, /免输身份/);
assert.match(message, /https:\/\/portal\.example\.com\/\?task=tok-123/);
});
test("oneClickPushTask sends only to selected partners and logs the push", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb();
const calls = [];
const outcome = await oneClickPushTask(
db,
{
taskId: "task-1",
sendMainGroup: false,
sendKoc: true,
createGroupTemplate: false,
selectedKocPartnerIds: ["p-1", "p-3"],
},
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls, { invalidUsers: ["wmFAIL"] }),
);
const appCalls = calls.filter((call) =>
call.url.pathname.endsWith("/cgi-bin/message/send"),
);
assert.deepEqual(
appCalls.map((call) => JSON.parse(String(call.init.body)).touser),
["wmOK1", "wmFAIL"],
);
for (const call of appCalls) {
assert.match(JSON.parse(String(call.init.body)).text.content, /【新任务】测试任务/);
}
assert.equal(outcome.kocSent, 1);
assert.equal(outcome.kocFailed, 1);
assert.equal(outcome.kocResults[1].partnerName, "合作方丙");
assert.match(outcome.kocResults[1].error, /invaliduser/);
assert.equal(outcome.linkUrl, "https://portal.example.com/?task=tok-123");
const insert = db.executed.find((item) => /INSERT INTO wecom_push_logs/.test(item.sql));
assert.ok(insert, "push log should be written");
assert.equal(insert.params[1], "task-1");
assert.equal(insert.params[3], "task_open");
assert.equal(insert.params[6], 1);
const kocUserids = JSON.parse(insert.params[5]);
assert.equal(kocUserids.length, 2);
assert.equal(kocUserids[0].externalUserId, "wmOK1");
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("oneClickPushTask blocks duplicate same-day push unless forced", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb({
todayLog: { id: "wpl-old", task_id: "task-1", push_kind: "task_open" },
});
const calls = [];
await assert.rejects(
() =>
oneClickPushTask(
db,
{ taskId: "task-1", sendMainGroup: false, sendKoc: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls),
),
(error) =>
error instanceof OneClickPushError && /仍要推送/.test(error.message) && error.status === 409,
);
assert.equal(calls.length, 0, "no wecom api calls on duplicate block");
const outcome = await oneClickPushTask(
db,
{
taskId: "task-1",
sendMainGroup: false,
sendKoc: true,
selectedKocPartnerIds: ["p-2"],
force: true,
},
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls),
);
assert.equal(outcome.kocSent, 1);
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("oneClickPushTask without project skips project targets and still reaches KOC", async () => {
process.env.KOC_PORTAL_URL = "https://portal.example.com";
try {
const db = fakePushDb({ task: { ...taskRow, project_id: "" } });
const calls = [];
const outcome = await oneClickPushTask(
db,
{ taskId: "task-1", sendMainGroup: true, sendKoc: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch(calls),
);
assert.ok(
outcome.skippedReasons.some((reason) => /未挂项目/.test(reason)),
"should explain project skip",
);
assert.equal(outcome.projectOutcome, null);
assert.equal(outcome.kocSent, 3);
assert.equal(
calls.filter((call) => call.url.pathname.includes("/cgi-bin/externalcontact/")).length,
0,
"no group template calls expected",
);
} finally {
delete process.env.KOC_PORTAL_URL;
}
});
test("oneClickPushTask requires share token and at least one target", async () => {
await assert.rejects(
() =>
oneClickPushTask(
fakePushDb({ task: { ...taskRow, share_token: "" } }),
{ taskId: "task-1", sendMainGroup: false, sendKoc: true },
resolveWecomConfig(baseBindings),
fakeWecomFetch([]),
),
(error) => error instanceof OneClickPushError && /领取链接/.test(error.message),
);
await assert.rejects(
() =>
oneClickPushTask(
fakePushDb(),
{ taskId: "task-1", sendMainGroup: false, sendKoc: false, createGroupTemplate: false },
resolveWecomConfig(baseBindings),
fakeWecomFetch([]),
),
(error) => error instanceof OneClickPushError && /至少选择一个推送目标/.test(error.message),
);
});

366
tests/task-update.test.mjs Normal file
View File

@@ -0,0 +1,366 @@
import test from "node:test";
import assert from "node:assert/strict";
import { updateTask } from "../lib/task-service.ts";
function fakeDb({ task, contents = [] }) {
const tasks = task ? [task] : [];
const rows = contents.map((row) => ({ ...row }));
const db = {
prepare(sql) {
return {
bind(...values) {
return {
async first() {
if (/FROM tasks WHERE id = \?/.test(sql)) {
return tasks.find((row) => row.id === values[0]) ?? null;
}
if (/SELECT image_assets FROM contents/.test(sql)) {
const sorted = rows
.filter((row) => row.task_id === values[0])
.sort((a, b) => a.source_row - b.source_row);
return sorted[0] ? { image_assets: sorted[0].image_assets } : null;
}
return null;
},
async run() {
const normalized = sql.trim();
if (/^UPDATE tasks/.test(normalized)) {
const [name, brand, due_at, project_id, platform, content_format, quantity, id] =
values;
const row = tasks.find((item) => item.id === id);
if (!row) return { meta: { changes: 0 } };
Object.assign(row, {
name,
brand,
due_at,
project_id,
platform,
content_format,
quantity,
});
return { meta: { changes: 1 } };
}
if (/^INSERT INTO contents/.test(normalized)) {
const [id, task_id, title, body, image_assets, source_row] = values;
rows.push({
id,
task_id,
title,
body,
image_assets,
status: "available",
source_row,
});
return { meta: { changes: 1 } };
}
if (/^DELETE FROM contents/.test(normalized)) {
const [taskId, limit] = values;
const available = rows
.filter((row) => row.task_id === taskId && row.status === "available")
.sort((a, b) => b.source_row - a.source_row);
const doomed = new Set(available.slice(0, limit).map((row) => row.id));
for (let index = rows.length - 1; index >= 0; index -= 1) {
if (doomed.has(rows[index].id)) rows.splice(index, 1);
}
return { meta: { changes: doomed.size } };
}
if (/^UPDATE contents SET title/.test(normalized)) {
const [title, body, taskId] = values;
for (const row of rows) {
if (row.task_id === taskId) {
row.title = title;
row.body = body;
}
}
return { meta: { changes: rows.length } };
}
if (/^UPDATE contents SET image_assets/.test(normalized)) {
const [image_assets, taskId] = values;
for (const row of rows) {
if (row.task_id === taskId) row.image_assets = image_assets;
}
return { meta: { changes: rows.length } };
}
return { meta: { changes: 0 } };
},
async all() {
return { results: [] };
},
};
},
};
},
async batch(statements) {
const results = [];
for (const statement of statements) {
results.push(await statement.run());
}
return results;
},
};
return { db, tasks, contents: rows };
}
function screenshotTask(overrides = {}) {
return {
id: "task-shot-1",
task_type: "screenshot_collect",
quantity: 3,
claimed_quantity: 0,
platform: "小红书",
content_format: "image_text",
name: "旧名称",
brand: "旧品牌",
due_at: "2026-08-01",
project_id: "",
...overrides,
};
}
function screenshotContents(quantity, overrides = {}) {
return Array.from({ length: quantity }, (_, index) => ({
id: `content-${index + 1}`,
task_id: "task-shot-1",
title: overrides.title ?? "旧关键词",
body: overrides.body ?? "旧说明",
image_assets: overrides.imageAssets ?? "[]",
status: index < (overrides.claimed ?? 0) ? "claimed" : "available",
source_row: index + 1,
}));
}
test("updateTask rewrites basic fields and syncs keyword/instructions on all rows", async () => {
const { db, tasks, contents } = fakeDb({
task: screenshotTask(),
contents: screenshotContents(3),
});
const result = await updateTask(
{
taskId: "task-shot-1",
name: "新名称",
brand: "新品牌",
dueAt: "2026-09-30",
projectId: "proj-1",
keyword: "新关键词",
instructions: "新说明",
quantity: 3,
},
db,
);
assert.equal(result.quantity, 3);
assert.equal(tasks[0].name, "新名称");
assert.equal(tasks[0].brand, "新品牌");
assert.equal(tasks[0].due_at, "2026-09-30");
assert.equal(tasks[0].project_id, "proj-1");
assert.equal(contents.length, 3);
for (const row of contents) {
assert.equal(row.title, "新关键词");
assert.equal(row.body, "新说明");
}
});
test("updateTask grows placeholder contents when quantity increases", async () => {
const imageAssets = JSON.stringify([{ index: 1, key: "task-assets/a.png", width: null, height: null }]);
const { db, tasks, contents } = fakeDb({
task: screenshotTask(),
contents: screenshotContents(3, { imageAssets }),
});
await updateTask(
{
taskId: "task-shot-1",
name: "n",
brand: "b",
dueAt: "2026-09-30",
keyword: "k",
instructions: "i",
quantity: 5,
},
db,
);
assert.equal(tasks[0].quantity, 5);
assert.equal(contents.length, 5);
const added = contents.filter((row) => row.source_row > 3);
assert.equal(added.length, 2);
for (const row of added) {
assert.equal(row.status, "available");
assert.equal(row.image_assets, imageAssets, "new rows copy example image");
assert.equal(row.title, "k");
}
});
test("updateTask shrinks only available tail rows when quantity decreases", async () => {
const { db, tasks, contents } = fakeDb({
task: screenshotTask({ quantity: 5, claimed_quantity: 2 }),
contents: screenshotContents(5, { claimed: 2 }),
});
await updateTask(
{
taskId: "task-shot-1",
name: "n",
brand: "b",
dueAt: "2026-09-30",
keyword: "k",
instructions: "i",
quantity: 3,
},
db,
);
assert.equal(tasks[0].quantity, 3);
assert.equal(contents.length, 3);
const claimedRows = contents.filter((row) => row.status === "claimed");
assert.equal(claimedRows.length, 2, "claimed rows preserved");
assert.ok(
contents.every((row) => row.source_row <= 3),
"tail rows removed",
);
});
test("updateTask rejects quantity below claimed_quantity", async () => {
const { db } = fakeDb({
task: screenshotTask({ quantity: 5, claimed_quantity: 2 }),
contents: screenshotContents(5, { claimed: 2 }),
});
await assert.rejects(
() =>
updateTask(
{
taskId: "task-shot-1",
name: "n",
brand: "b",
dueAt: "2026-09-30",
keyword: "k",
instructions: "i",
quantity: 1,
},
db,
),
/不能低于已领取的 2 份/,
);
});
test("updateTask validates screenshot quantity and keyword", async () => {
const { db } = fakeDb({ task: screenshotTask(), contents: screenshotContents(3) });
await assert.rejects(
() =>
updateTask(
{ taskId: "task-shot-1", name: "n", brand: "b", dueAt: "2026-09-30", keyword: "k", instructions: "i", quantity: 0 },
db,
),
/1—500/,
);
await assert.rejects(
() =>
updateTask(
{ taskId: "task-shot-1", name: "n", brand: "b", dueAt: "2026-09-30", keyword: " ", instructions: "i", quantity: 3 },
db,
),
/请补全搜索关键词和任务说明/,
);
});
test("updateTask replaces example image across contents when re-uploaded", async () => {
const { db, contents } = fakeDb({
task: screenshotTask(),
contents: screenshotContents(3),
});
await updateTask(
{
taskId: "task-shot-1",
name: "n",
brand: "b",
dueAt: "2026-09-30",
keyword: "k",
instructions: "i",
quantity: 3,
exampleImageKey: "task-assets/new.png",
},
db,
);
for (const row of contents) {
assert.equal(JSON.parse(row.image_assets)[0].key, "task-assets/new.png");
}
});
test("updateTask ignores quantity and keyword for content_publish tasks", async () => {
const { db, tasks, contents } = fakeDb({
task: screenshotTask({
id: "task-pub-1",
task_type: "content_publish",
quantity: 18,
platform: "抖音",
content_format: "video",
}),
contents: [
{
id: "content-pub-1",
task_id: "task-pub-1",
title: "笔记标题",
body: "笔记正文",
image_assets: "[]",
status: "available",
source_row: 1,
},
],
});
await updateTask(
{
taskId: "task-pub-1",
name: "新名称",
brand: "新品牌",
dueAt: "2026-09-30",
projectId: "proj-2",
quantity: 99,
keyword: "ignored",
instructions: "ignored",
},
db,
);
assert.equal(tasks[0].quantity, 18, "feishu row count untouched");
assert.equal(tasks[0].platform, "抖音", "platform kept when not provided");
assert.equal(tasks[0].content_format, "video");
assert.equal(contents[0].title, "笔记标题", "contents untouched");
});
test("updateTask applies provided platform/contentFormat for content_publish", async () => {
const { db, tasks } = fakeDb({
task: screenshotTask({
id: "task-pub-1",
task_type: "content_publish",
platform: "小红书",
content_format: "image_text",
}),
});
await updateTask(
{
taskId: "task-pub-1",
name: "n",
brand: "b",
dueAt: "2026-09-30",
platform: "抖音",
contentFormat: "video",
},
db,
);
assert.equal(tasks[0].platform, "抖音");
assert.equal(tasks[0].content_format, "video");
});
test("updateTask rejects unknown tasks and invalid dates", async () => {
const { db } = fakeDb({ task: screenshotTask() });
await assert.rejects(
() =>
updateTask(
{ taskId: "missing", name: "n", brand: "b", dueAt: "2026-09-30" },
db,
),
/任务不存在/,
);
await assert.rejects(
() =>
updateTask(
{ taskId: "task-shot-1", name: "n", brand: "b", dueAt: "2026-13-01" },
db,
),
/截止日期/,
);
});

View File

@@ -1,13 +1,16 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
addTaskJoinWay,
buildWecomOAuthUrl,
clearWecomAccessTokenCacheForTests,
createAppChat,
createGroupMsgTemplate,
deleteJoinWay,
exchangeWecomOAuthCode,
fetchWecomExternalContactName,
getAppChat,
getJoinWayQrCode,
listCustomerGroupChats,
listExternalContacts,
listInternalContacts,
@@ -16,6 +19,7 @@ import {
sendWecomAppMessage,
sendWecomRobotMessage,
updateAppChat,
updateTaskJoinWay,
WecomClientError,
} from "../lib/wecom-client.ts";
@@ -428,6 +432,14 @@ function fakeGroupPush(options = {}) {
"wr-normal-1": { name: "KOC 一群", owner: "zhangsan", member_count: 42 },
"wr-normal-2": { name: "KOC 二群", owner: "lisi", member_count: 7 },
};
const joinWay = {
addErrcode: options.joinAddErrcode ?? 0,
updateErrcode: options.joinUpdateErrcode ?? 0,
getErrcode: options.joinGetErrcode ?? 0,
delErrcode: options.joinDelErrcode ?? 0,
qrCode: options.joinQrCode ?? "https://p.qpic.cn/qr-test.png",
configId: options.joinConfigId ?? "cfgtest123",
};
const fetchImpl = async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
@@ -466,6 +478,34 @@ function fakeGroupPush(options = {}) {
fail_list: options.failList ?? [],
});
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/add_join_way")) {
if (joinWay.addErrcode !== 0) {
return Response.json({ errcode: joinWay.addErrcode, errmsg: "add failed" });
}
return Response.json({ errcode: 0, errmsg: "ok", config_id: joinWay.configId });
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/get_join_way")) {
if (joinWay.getErrcode !== 0) {
return Response.json({ errcode: joinWay.getErrcode, errmsg: "get failed" });
}
return Response.json({
errcode: 0,
errmsg: "ok",
join_way: { qr_code: joinWay.qrCode, scene: 2 },
});
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/update_join_way")) {
if (joinWay.updateErrcode !== 0) {
return Response.json({ errcode: joinWay.updateErrcode, errmsg: "update failed" });
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/del_join_way")) {
if (joinWay.delErrcode !== 0) {
return Response.json({ errcode: joinWay.delErrcode, errmsg: "del failed" });
}
return Response.json({ errcode: 0, errmsg: "ok" });
}
return new Response("not found", { status: 404 });
};
return { calls, fetchImpl };
@@ -524,6 +564,118 @@ test("listCustomerGroupChats skips groups whose detail lookup fails", async () =
);
});
test("listCustomerGroupChats sends owner_filter when ownerUserids given", async () => {
const { calls, fetchImpl } = fakeGroupPush({
pages: [{ next_cursor: "", group_chat_list: [{ chat_id: "wr-normal-1", status: 0 }] }],
details: {
"wr-normal-1": { name: "KOC 一群", owner: "zhangsan", member_count: 42 },
},
});
const groups = await listCustomerGroupChats(
resolveWecomConfig(baseBindings),
fetchImpl,
["zhangsan", ""],
);
assert.equal(groups.length, 1);
const listCall = calls.find((c) =>
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/list"),
);
const body = JSON.parse(String(listCall.init.body));
assert.deepEqual(body.owner_filter, { userid_list: ["zhangsan"] });
});
test("addTaskJoinWay posts scene/auto_create_room/payload and returns configId", async () => {
const { calls, fetchImpl } = fakeGroupPush();
const result = await addTaskJoinWay(
resolveWecomConfig(baseBindings),
{
chatIdList: ["wr-normal-1"],
roomBaseName: "每".repeat(50),
state: "task-task-baf7fd59",
},
fetchImpl,
);
assert.equal(result.configId, "cfgtest123");
const call = calls.find((c) =>
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/add_join_way"),
);
assert.ok(call, "add_join_way was called");
assert.equal(call.url.searchParams.get("access_token"), "token-test");
const body = JSON.parse(String(call.init.body));
assert.equal(body.scene, 2);
assert.equal(body.auto_create_room, 1);
assert.deepEqual(body.chat_id_list, ["wr-normal-1"]);
assert.equal(body.room_base_name.length, 40, "room_base_name truncated to 40 code points");
assert.equal(body.state, "task-task-baf7fd59");
});
test("addTaskJoinWay surfaces upstream errcode as WecomClientError", async () => {
const { fetchImpl } = fakeGroupPush({ joinAddErrcode: 60011 });
await assert.rejects(
() =>
addTaskJoinWay(
resolveWecomConfig(baseBindings),
{ chatIdList: ["wr-normal-1"], roomBaseName: "群", state: "task-t1" },
fetchImpl,
),
(error) =>
error instanceof WecomClientError && /创建企业微信进群活码失败/.test(error.message),
);
});
test("getJoinWayQrCode returns qr_code url from join_way", async () => {
const { calls, fetchImpl } = fakeGroupPush({ joinQrCode: "https://p.qpic.cn/qr-x.png" });
const result = await getJoinWayQrCode(
resolveWecomConfig(baseBindings),
"cfgtest123",
fetchImpl,
);
assert.equal(result.qrCode, "https://p.qpic.cn/qr-x.png");
const call = calls.find((c) =>
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/get_join_way"),
);
assert.deepEqual(JSON.parse(String(call.init.body)), { config_id: "cfgtest123" });
});
test("updateTaskJoinWay re-sends full body including scene for overwrite semantics", async () => {
const { calls, fetchImpl } = fakeGroupPush();
await updateTaskJoinWay(
resolveWecomConfig(baseBindings),
{
configId: "cfgtest123",
chatIdList: ["wr-normal-2"],
roomBaseName: "新群名",
state: "task-t2",
},
fetchImpl,
);
const call = calls.find((c) =>
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/update_join_way"),
);
const body = JSON.parse(String(call.init.body));
assert.equal(body.config_id, "cfgtest123");
assert.equal(body.scene, 2);
assert.equal(body.auto_create_room, 1);
assert.deepEqual(body.chat_id_list, ["wr-normal-2"]);
assert.equal(body.room_base_name, "新群名");
});
test("deleteJoinWay tolerates upstream rejection but still calls del endpoint", async () => {
const { calls, fetchImpl } = fakeGroupPush({ joinDelErrcode: 40068 });
await deleteJoinWay(resolveWecomConfig(baseBindings), "cfgtest123", fetchImpl);
const call = calls.find((c) =>
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/del_join_way"),
);
assert.ok(call, "del_join_way was called");
assert.deepEqual(JSON.parse(String(call.init.body)), { config_id: "cfgtest123" });
});
test("deleteJoinWay skips empty configId", async () => {
const { calls, fetchImpl } = fakeGroupPush();
await deleteJoinWay(resolveWecomConfig(baseBindings), " ", fetchImpl);
assert.equal(calls.length, 0, "no API calls for empty config id");
});
test("createGroupMsgTemplate posts group payload with text and link attachment", async () => {
const { calls, fetchImpl } = fakeGroupPush();
const result = await createGroupMsgTemplate(
@@ -834,6 +986,7 @@ function fakeAppChat(options = {}) {
["tgc_task-existing", { name: "【任务】已有群", userlist: ["owner-a"] }],
],
);
const createExisted = options.createExisted ?? false;
const fetchImpl = async (input, init = {}) => {
const url = new URL(String(input));
calls.push({ url, init });
@@ -846,6 +999,9 @@ function fakeAppChat(options = {}) {
});
}
if (url.pathname.endsWith("/cgi-bin/appchat/create")) {
if (createExisted) {
return Response.json({ errcode: 86215, errmsg: "chatid existed" });
}
const body = JSON.parse(String(init.body ?? "{}"));
chats.set(body.chatid, { name: body.name, userlist: body.userlist });
return Response.json({ errcode: 0, errmsg: "ok", chatid: body.chatid });
@@ -893,15 +1049,15 @@ test("createAppChat posts name/userlist/chatid and returns chatid", async () =>
const { calls, fetchImpl } = fakeAppChat();
const result = await createAppChat(
resolveWecomConfig(baseBindings),
{ name: "【任务】任务名超长会被截断到二十个字符", userlist: ["owner-a", "owner-b"], chatid: "tgc_task-new" },
{ name: "【任务】任务名超长会被截断到二十个字符", userlist: ["owner-a", "owner-b"], chatid: "tgcnewchat" },
fetchImpl,
);
assert.equal(result.chatid, "tgc_task-new");
assert.equal(result.chatid, "tgcnewchat");
const call = calls.find((c) => c.url.pathname.endsWith("/cgi-bin/appchat/create"));
assert.ok(call, "appchat/create was called");
assert.equal(call.url.searchParams.get("access_token"), "token-test");
const body = JSON.parse(String(call.init.body));
assert.equal(body.chatid, "tgc_task-new");
assert.equal(body.chatid, "tgcnewchat");
assert.equal(body.userlist.length, 2);
assert.ok(body.name.length <= 20, "chat name truncated to 20 chars");
});
@@ -925,6 +1081,16 @@ test("createAppChat rejects fewer than 2 members and oversized chatid", async ()
assert.equal(calls.length, 0, "no API calls for invalid payload");
});
test("createAppChat treats chatid existed (86215) as success", async () => {
const { fetchImpl } = fakeAppChat({ createExisted: true });
const result = await createAppChat(
resolveWecomConfig(baseBindings),
{ name: "【总群】项目一", userlist: ["a", "b"], chatid: "pgcproj1" },
fetchImpl,
);
assert.equal(result.chatid, "pgcproj1");
});
test("updateAppChat adds and removes members", async () => {
const { calls, fetchImpl, chats } = fakeAppChat();
await updateAppChat(
@@ -962,7 +1128,7 @@ test("getAppChat returns member list or null on error", async () => {
assert.equal(info.chatId, "tgc_task-existing");
assert.deepEqual(info.userlist, ["owner-a"]);
assert.equal(
await getAppChat(resolveWecomConfig(baseBindings), "tgc_task-missing", fetchImpl),
await getAppChat(resolveWecomConfig(baseBindings), "tgcmissingchat", fetchImpl),
null,
);
});
@@ -988,7 +1154,7 @@ test("sendAppChatMessage throws WecomClientError when provider errors", async ()
() =>
sendAppChatMessage(
resolveWecomConfig(baseBindings),
{ chatid: "tgc_task-missing", text: "hello" },
{ chatid: "tgcmissingchat", text: "hello" },
fetchImpl,
),
(error) => {

View File

@@ -1,6 +1,9 @@
import assert from "node:assert/strict";
import test from "node:test";
import { computeDueCutoff } from "../lib/wecom-notifier-service.ts";
import {
computeDueCutoff,
runDueSoonWecomNotifications,
} from "../lib/wecom-notifier-service.ts";
test("computeDueCutoff advances by dueDays and crosses month/year", () => {
assert.equal(computeDueCutoff("2026-08-18", 3), "2026-08-21");
@@ -13,3 +16,62 @@ test("computeDueCutoff advances by dueDays and crosses month/year", () => {
test("computeDueCutoff returns input unchanged when malformed", () => {
assert.equal(computeDueCutoff("not-a-date", 3), "not-a-date");
});
function captureDb() {
const executed = [];
const db = {
prepare(sql) {
const statement = (values) => ({
async all() {
executed.push({ sql, values });
return { results: [] };
},
async first() {
executed.push({ sql, values });
return null;
},
});
return {
bind(...values) {
return statement(values);
},
...statement([]),
};
},
};
return { db, executed };
}
const NOTIFY_CONFIG = {
corpId: "",
agentId: "",
secret: "",
robotWebhook: "",
dueDays: 3,
};
test("runDueSoonWecomNotifications filters by taskId when given", async () => {
const { db, executed } = captureDb();
const now = Date.UTC(2026, 7, 18, 2, 0, 0);
const summary = await runDueSoonWecomNotifications(
db,
NOTIFY_CONFIG,
undefined,
now,
"task-9",
);
assert.equal(executed.length, 1);
assert.match(executed[0].sql, /AND t\.id = \?/);
assert.deepEqual(executed[0].values, ["2026-08-21", "task-9"]);
assert.equal(summary.dueSoonAttempted, 0);
assert.equal(summary.digestSent, false);
});
test("runDueSoonWecomNotifications keeps global scan without taskId", async () => {
const { db, executed } = captureDb();
const now = Date.UTC(2026, 7, 18, 2, 0, 0);
await runDueSoonWecomNotifications(db, NOTIFY_CONFIG, undefined, now);
assert.equal(executed.length, 1);
assert.ok(!/AND t\.id = \?/.test(executed[0].sql));
assert.deepEqual(executed[0].values, ["2026-08-21"]);
});