feat: 任务发布到企微客户群(企业群发)与资源库单条新增
- 任务中心新增「发布到企微群」:同步客户群清单(wecom_group_chats)、 按群主分组创建企业群发任务(add_msg_template)、发送记录落库 wecom_group_pushes,迁移 mysql/0009;lib/wecom-client.ts 补 listCustomerGroupChats/createGroupMsgTemplate - KOC 资源库支持单条新增:app/api/resources-insert + lib/resource-write, 拆出资源写入公共逻辑供导入复用;0008 补合作方外部联系人字段 - 环境变量示例补企微凭证与 SEED_DEMO_DATA;next.config 增加 allowedDevOrigins;CLAUDE.md 补充项目说明 - .gitignore 排除 .codegraph/ 与 .ipynb_checkpoints/
This commit is contained in:
@@ -510,11 +510,12 @@ test("filters and exports the current KOC resource result set", async () => {
|
||||
});
|
||||
|
||||
test("imports existing KOC resources through a validated spreadsheet preview", async () => {
|
||||
const [adminApp, globalCss, importRoute, resourceParser, accountMigration, profileMigration, contactMigration] = await Promise.all([
|
||||
const [adminApp, globalCss, importRoute, resourceParser, resourceWrite, accountMigration, profileMigration, contactMigration] = await Promise.all([
|
||||
readFile(new URL("../app/admin-app.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../app/globals.css", import.meta.url), "utf8"),
|
||||
readFile(new URL("../app/api/resources-import/route.ts", import.meta.url), "utf8"),
|
||||
readFile(new URL("../lib/resource-import.ts", import.meta.url), "utf8"),
|
||||
readFile(new URL("../lib/resource-write.ts", import.meta.url), "utf8"),
|
||||
readFile(new URL("../mysql/0002_resource_import.sql", import.meta.url), "utf8"),
|
||||
readFile(new URL("../mysql/0006_account_profile_tags.sql", import.meta.url), "utf8"),
|
||||
readFile(new URL("../mysql/0007_account_current_contact.sql", import.meta.url), "utf8"),
|
||||
@@ -527,7 +528,7 @@ test("imports existing KOC resources through a validated spreadsheet preview", a
|
||||
assert.match(resourceParser, /RESOURCE_IMPORT_MAX_ROWS = 10_000/);
|
||||
assert.match(resourceParser, /RESOURCE_IMPORT_MAX_BYTES = 20 \* 1024 \* 1024/);
|
||||
assert.match(adminApp, /单次最多 10,000 个账号,文件不超过 20MB/);
|
||||
assert.match(importRoute, /RESOURCE_IMPORT_DB_BATCH_SIZE = 100/);
|
||||
assert.match(resourceWrite, /RESOURCE_IMPORT_DB_BATCH_SIZE = 100/);
|
||||
assert.match(importRoute, /bulk resource profile enrichment/);
|
||||
assert.match(adminApp, /异常数据将自动跳过,不会导入/);
|
||||
assert.match(
|
||||
@@ -542,7 +543,7 @@ test("imports existing KOC resources through a validated spreadsheet preview", a
|
||||
assert.match(importRoute, /跳过 \$\{summary\.error\} 条异常数据/);
|
||||
assert.match(importRoute, /previewAnalyzedRows\(analyzed\)/);
|
||||
assert.match(resourceParser, /当前自动解析仅支持小红书或抖音账号主页/);
|
||||
assert.match(importRoute, /resolveProfileDetailsFromMcp/);
|
||||
assert.match(resourceWrite, /resolveProfileDetailsFromMcp/);
|
||||
assert.match(accountMigration, /cooperation_source/);
|
||||
assert.match(profileMigration, /ADD COLUMN gender/);
|
||||
assert.match(profileMigration, /ADD COLUMN bio/);
|
||||
|
||||
@@ -2,6 +2,9 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
clearWecomAccessTokenCacheForTests,
|
||||
createGroupMsgTemplate,
|
||||
listCustomerGroupChats,
|
||||
listExternalContacts,
|
||||
resolveWecomConfig,
|
||||
sendWecomAppMessage,
|
||||
sendWecomRobotMessage,
|
||||
@@ -215,3 +218,390 @@ test("access_token is cached across calls", async () => {
|
||||
);
|
||||
assert.equal(tokenCalls.length, 1, "access_token cached for second call");
|
||||
});
|
||||
|
||||
function fakeExternalContacts() {
|
||||
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/get_follow_user_list")) {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
follow_user: [{ userid: "owner-a" }, { userid: "owner-b" }],
|
||||
});
|
||||
}
|
||||
if (url.pathname.endsWith("/cgi-bin/externalcontact/list")) {
|
||||
const userid = url.searchParams.get("userid");
|
||||
if (userid === "owner-a") {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_userid: ["ext-1", "ext-2"],
|
||||
});
|
||||
}
|
||||
if (userid === "owner-b") {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_userid: ["ext-3"],
|
||||
});
|
||||
}
|
||||
return Response.json({ errcode: 60020, errmsg: "user not found" });
|
||||
}
|
||||
if (url.pathname.endsWith("/cgi-bin/externalcontact/get")) {
|
||||
const eid = url.searchParams.get("external_userid");
|
||||
if (eid === "ext-1") {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_contact: {
|
||||
external_userid: "ext-1",
|
||||
name: "张三",
|
||||
avatar: "https://example.com/a.png",
|
||||
corp_fullname: "ACME 公司",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (eid === "ext-2") {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_contact: {
|
||||
external_userid: "ext-2",
|
||||
name: "李四",
|
||||
avatar: "",
|
||||
corp_fullname: "",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (eid === "ext-3") {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_contact: {
|
||||
external_userid: "ext-3",
|
||||
name: "王五",
|
||||
avatar: "https://example.com/c.png",
|
||||
corp_fullname: "Other 公司",
|
||||
},
|
||||
});
|
||||
}
|
||||
return Response.json({ errcode: 60111, errmsg: "not found" });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
return { calls, fetchImpl };
|
||||
}
|
||||
|
||||
test("listExternalContacts flattens follow_user → list → get into a single array", async () => {
|
||||
const { fetchImpl } = fakeExternalContacts();
|
||||
const contacts = await listExternalContacts(
|
||||
resolveWecomConfig(baseBindings),
|
||||
fetchImpl,
|
||||
);
|
||||
assert.equal(contacts.length, 3);
|
||||
const first = contacts.find((c) => c.externalUserId === "ext-1");
|
||||
assert.ok(first);
|
||||
assert.equal(first.name, "张三");
|
||||
assert.equal(first.avatar, "https://example.com/a.png");
|
||||
assert.equal(first.corpName, "ACME 公司");
|
||||
assert.equal(first.ownerUserId, "owner-a");
|
||||
const second = contacts.find((c) => c.externalUserId === "ext-2");
|
||||
assert.ok(second);
|
||||
assert.equal(second.corpName, "李四");
|
||||
const third = contacts.find((c) => c.externalUserId === "ext-3");
|
||||
assert.ok(third);
|
||||
assert.equal(third.ownerUserId, "owner-b");
|
||||
});
|
||||
|
||||
test("listExternalContacts skips members with non-zero errcode", async () => {
|
||||
const { fetchImpl } = fakeExternalContacts();
|
||||
const contacts = await listExternalContacts(
|
||||
resolveWecomConfig(baseBindings),
|
||||
fetchImpl,
|
||||
);
|
||||
const ownerBIds = contacts
|
||||
.filter((c) => c.ownerUserId === "owner-b")
|
||||
.map((c) => c.externalUserId);
|
||||
assert.deepEqual(ownerBIds, ["ext-3"]);
|
||||
});
|
||||
|
||||
test("listExternalContacts returns empty array when app credentials missing", async () => {
|
||||
const { calls, fetchImpl } = fakeExternalContacts();
|
||||
const contacts = await listExternalContacts(
|
||||
resolveWecomConfig({
|
||||
...baseBindings,
|
||||
WECOM_CORP_ID: "",
|
||||
WECOM_AGENT_ID: "",
|
||||
WECOM_SECRET: "",
|
||||
}),
|
||||
fetchImpl,
|
||||
);
|
||||
assert.deepEqual(contacts, []);
|
||||
assert.equal(calls.length, 0, "no API calls without credentials");
|
||||
});
|
||||
|
||||
function fakeGroupPush(options = {}) {
|
||||
const calls = [];
|
||||
const pages =
|
||||
options.pages ??
|
||||
[
|
||||
{
|
||||
next_cursor: "page-2",
|
||||
group_chat_list: [
|
||||
{ chat_id: "wr-normal-1", status: 0 },
|
||||
{ chat_id: "wr-dissolved", status: 1 },
|
||||
],
|
||||
},
|
||||
{ next_cursor: "", group_chat_list: [{ chat_id: "wr-normal-2", status: 0 }] },
|
||||
];
|
||||
const details =
|
||||
options.details ??
|
||||
{
|
||||
"wr-normal-1": { name: "KOC 一群", owner: "zhangsan", member_count: 42 },
|
||||
"wr-normal-2": { name: "KOC 二群", owner: "lisi", member_count: 7 },
|
||||
};
|
||||
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/list")) {
|
||||
const body = JSON.parse(String(init.body ?? "{}"));
|
||||
const index = body.cursor ? Number(body.cursor.replace("page-", "")) - 1 : 0;
|
||||
const page = pages[index] ?? { next_cursor: "", group_chat_list: [] };
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
next_cursor: page.next_cursor,
|
||||
group_chat_list: page.group_chat_list,
|
||||
});
|
||||
}
|
||||
if (url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/get")) {
|
||||
const body = JSON.parse(String(init.body ?? "{}"));
|
||||
const detail = details[body.chat_id];
|
||||
if (!detail) {
|
||||
return Response.json({ errcode: 60111, errmsg: "not found" });
|
||||
}
|
||||
return Response.json({ errcode: 0, errmsg: "ok", group_chat: detail });
|
||||
}
|
||||
if (url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template")) {
|
||||
return Response.json({
|
||||
errcode: options.templateErrcode ?? 0,
|
||||
errmsg: options.templateErrmsg ?? "ok",
|
||||
msgid: options.msgid ?? "msgGTEST",
|
||||
fail_list: options.failList ?? [],
|
||||
});
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
return { calls, fetchImpl };
|
||||
}
|
||||
|
||||
test("listCustomerGroupChats paginates groupchat/list and keeps only normal groups", async () => {
|
||||
const { calls, fetchImpl } = fakeGroupPush();
|
||||
const groups = await listCustomerGroupChats(
|
||||
resolveWecomConfig(baseBindings),
|
||||
fetchImpl,
|
||||
);
|
||||
assert.equal(groups.length, 2);
|
||||
const first = groups.find((g) => g.chatId === "wr-normal-1");
|
||||
assert.ok(first);
|
||||
assert.equal(first.name, "KOC 一群");
|
||||
assert.equal(first.ownerUserId, "zhangsan");
|
||||
assert.equal(first.memberCount, 42);
|
||||
const second = groups.find((g) => g.chatId === "wr-normal-2");
|
||||
assert.ok(second);
|
||||
assert.equal(second.ownerUserId, "lisi");
|
||||
assert.equal(
|
||||
groups.some((g) => g.chatId === "wr-dissolved"),
|
||||
false,
|
||||
"non-normal status groups are filtered",
|
||||
);
|
||||
const listCalls = calls.filter((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/groupchat/list"),
|
||||
);
|
||||
assert.equal(listCalls.length, 2, "cursor pagination followed");
|
||||
const secondBody = JSON.parse(String(listCalls[1].init.body));
|
||||
assert.equal(secondBody.cursor, "page-2");
|
||||
});
|
||||
|
||||
test("listCustomerGroupChats skips groups whose detail lookup fails", async () => {
|
||||
const { fetchImpl } = fakeGroupPush({
|
||||
pages: [
|
||||
{
|
||||
next_cursor: "",
|
||||
group_chat_list: [
|
||||
{ chat_id: "wr-normal-1", status: 0 },
|
||||
{ chat_id: "wr-gone", status: 0 },
|
||||
],
|
||||
},
|
||||
],
|
||||
details: {
|
||||
"wr-normal-1": { name: "KOC 一群", owner: "zhangsan", member_count: 42 },
|
||||
},
|
||||
});
|
||||
const groups = await listCustomerGroupChats(
|
||||
resolveWecomConfig(baseBindings),
|
||||
fetchImpl,
|
||||
);
|
||||
assert.deepEqual(
|
||||
groups.map((g) => g.chatId),
|
||||
["wr-normal-1"],
|
||||
);
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate posts group payload with text and link attachment", async () => {
|
||||
const { calls, fetchImpl } = fakeGroupPush();
|
||||
const result = await createGroupMsgTemplate(
|
||||
resolveWecomConfig(baseBindings),
|
||||
{
|
||||
sender: "zhangsan",
|
||||
chatIdList: ["wr-normal-1", "wr-normal-2"],
|
||||
text: "【新任务】测试任务",
|
||||
link: {
|
||||
title: "测试任务",
|
||||
desc: "品牌 A · 3 份",
|
||||
url: "https://portal.example.com/?task=tok-1",
|
||||
},
|
||||
},
|
||||
fetchImpl,
|
||||
);
|
||||
assert.equal(result.msgid, "msgGTEST");
|
||||
assert.deepEqual(result.failList, []);
|
||||
const sendCall = calls.find((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
|
||||
);
|
||||
assert.ok(sendCall, "add_msg_template was called");
|
||||
assert.equal(sendCall.url.searchParams.get("access_token"), "token-test");
|
||||
const body = JSON.parse(String(sendCall.init.body));
|
||||
assert.equal(body.chat_type, "group");
|
||||
assert.equal(body.sender, "zhangsan");
|
||||
assert.deepEqual(body.chat_id_list, ["wr-normal-1", "wr-normal-2"]);
|
||||
assert.equal(body.text.content, "【新任务】测试任务");
|
||||
assert.equal(body.attachments.length, 1);
|
||||
assert.equal(body.attachments[0].msgtype, "link");
|
||||
assert.equal(body.attachments[0].link.url, "https://portal.example.com/?task=tok-1");
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate omits text and attachments keys when absent", async () => {
|
||||
const { calls, fetchImpl } = fakeGroupPush();
|
||||
await createGroupMsgTemplate(
|
||||
resolveWecomConfig(baseBindings),
|
||||
{
|
||||
sender: "zhangsan",
|
||||
chatIdList: ["wr-normal-1"],
|
||||
link: { title: "只有图文", url: "https://portal.example.com/?task=tok-1" },
|
||||
},
|
||||
fetchImpl,
|
||||
);
|
||||
const sendCall = calls.find((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
|
||||
);
|
||||
assert.ok(sendCall, "add_msg_template was called");
|
||||
const body = JSON.parse(String(sendCall.init.body));
|
||||
assert.equal("text" in body, false);
|
||||
assert.equal(body.attachments[0].link.title, "只有图文");
|
||||
assert.equal(body.attachments[0].link.desc, "");
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate passes through fail_list from provider", async () => {
|
||||
const { fetchImpl } = fakeGroupPush({
|
||||
msgid: "msgFAIL",
|
||||
failList: ["wr-normal-2"],
|
||||
});
|
||||
const result = await createGroupMsgTemplate(
|
||||
resolveWecomConfig(baseBindings),
|
||||
{
|
||||
sender: "zhangsan",
|
||||
chatIdList: ["wr-normal-1", "wr-normal-2"],
|
||||
text: "内容",
|
||||
},
|
||||
fetchImpl,
|
||||
);
|
||||
assert.equal(result.msgid, "msgFAIL");
|
||||
assert.deepEqual(result.failList, ["wr-normal-2"]);
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate throws WecomClientError on provider error", async () => {
|
||||
const { fetchImpl } = fakeGroupPush({
|
||||
templateErrcode: 81053,
|
||||
templateErrmsg: "user not in visible scope",
|
||||
});
|
||||
await assert.rejects(
|
||||
() =>
|
||||
createGroupMsgTemplate(
|
||||
resolveWecomConfig(baseBindings),
|
||||
{ sender: "zhangsan", chatIdList: ["wr-normal-1"], text: "内容" },
|
||||
fetchImpl,
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 502);
|
||||
assert.match(error.message, /user not in visible scope/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate rejects empty text and link before calling API", async () => {
|
||||
const { calls, fetchImpl } = fakeGroupPush();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
createGroupMsgTemplate(
|
||||
resolveWecomConfig(baseBindings),
|
||||
{ sender: "zhangsan", chatIdList: ["wr-normal-1"] },
|
||||
fetchImpl,
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 400);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
assert.equal(
|
||||
calls.filter((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
|
||||
).length,
|
||||
0,
|
||||
"no API call for invalid payload",
|
||||
);
|
||||
});
|
||||
|
||||
test("createGroupMsgTemplate rejects missing sender or empty chat list", async () => {
|
||||
const { fetchImpl } = fakeGroupPush();
|
||||
const config = resolveWecomConfig(baseBindings);
|
||||
await assert.rejects(
|
||||
() =>
|
||||
createGroupMsgTemplate(config, {
|
||||
sender: "",
|
||||
chatIdList: ["wr-normal-1"],
|
||||
text: "内容",
|
||||
}, fetchImpl),
|
||||
/群主/,
|
||||
);
|
||||
await assert.rejects(
|
||||
() =>
|
||||
createGroupMsgTemplate(config, {
|
||||
sender: "zhangsan",
|
||||
chatIdList: [],
|
||||
text: "内容",
|
||||
}, fetchImpl),
|
||||
/客户群列表为空/,
|
||||
);
|
||||
});
|
||||
|
||||
262
tests/wecom-group-push.test.mjs
Normal file
262
tests/wecom-group-push.test.mjs
Normal file
@@ -0,0 +1,262 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildTaskGroupPushMessage,
|
||||
groupChatsByOwner,
|
||||
pushTaskToGroupChats,
|
||||
trimToBytes,
|
||||
} from "../lib/wecom-group-push-service.ts";
|
||||
import {
|
||||
clearWecomAccessTokenCacheForTests,
|
||||
resolveWecomConfig,
|
||||
WecomClientError,
|
||||
} from "../lib/wecom-client.ts";
|
||||
|
||||
const baseBindings = {
|
||||
WECOM_CORP_ID: "corp-test",
|
||||
WECOM_AGENT_ID: "1000001",
|
||||
WECOM_SECRET: "secret-test",
|
||||
};
|
||||
|
||||
const baseTask = {
|
||||
id: "task-1",
|
||||
name: "测试任务",
|
||||
brand: "品牌A",
|
||||
quantity: 3,
|
||||
due_at: "2026-09-01",
|
||||
task_type: "content_publish",
|
||||
platform: "小红书",
|
||||
content_format: "image_text",
|
||||
share_token: "tok-123",
|
||||
};
|
||||
|
||||
test.beforeEach(() => {
|
||||
clearWecomAccessTokenCacheForTests();
|
||||
});
|
||||
|
||||
test("trimToBytes cuts on UTF-8 boundaries", () => {
|
||||
assert.equal(trimToBytes("abc", 10), "abc");
|
||||
assert.equal(trimToBytes("abcdef", 3), "abc");
|
||||
// 「汉」占 3 字节
|
||||
assert.equal(trimToBytes("a汉b", 4), "a汉");
|
||||
assert.equal(trimToBytes("汉汉汉", 7), "汉汉");
|
||||
});
|
||||
|
||||
test("buildTaskGroupPushMessage composes text and link with claim url", () => {
|
||||
const message = buildTaskGroupPushMessage(baseTask, "https://portal.example.com/");
|
||||
assert.match(message.text, /【新任务】测试任务/);
|
||||
assert.match(message.text, /品牌:品牌A|数量:3 份|截止:2026-09-01/);
|
||||
assert.match(message.text, /平台:小红书|形式:图文/);
|
||||
assert.match(message.text, /领取链接:https:\/\/portal\.example\.com\/\?task=tok-123/);
|
||||
assert.ok(message.link);
|
||||
assert.equal(message.link.title, "测试任务");
|
||||
assert.equal(message.link.url, "https://portal.example.com/?task=tok-123");
|
||||
assert.match(message.link.desc, /品牌A · 3 份 · 截止 2026-09-01/);
|
||||
});
|
||||
|
||||
test("buildTaskGroupPushMessage marks video and screenshot tasks", () => {
|
||||
const video = buildTaskGroupPushMessage(
|
||||
{ ...baseTask, content_format: "video" },
|
||||
"https://portal.example.com",
|
||||
);
|
||||
assert.match(video.text, /形式:视频/);
|
||||
const screenshot = buildTaskGroupPushMessage(
|
||||
{ ...baseTask, task_type: "screenshot_collect" },
|
||||
"https://portal.example.com",
|
||||
);
|
||||
assert.match(screenshot.text, /形式:截图回收/);
|
||||
});
|
||||
|
||||
test("buildTaskGroupPushMessage drops link when share_token missing", () => {
|
||||
const message = buildTaskGroupPushMessage(
|
||||
{ ...baseTask, share_token: null },
|
||||
"https://portal.example.com",
|
||||
);
|
||||
assert.equal(message.link, null);
|
||||
assert.match(message.text, /领取链接生成失败/);
|
||||
});
|
||||
|
||||
test("buildTaskGroupPushMessage trims long content to byte limits", () => {
|
||||
const longName = "长".repeat(200);
|
||||
const longBrand = "牌".repeat(400);
|
||||
const message = buildTaskGroupPushMessage(
|
||||
{ ...baseTask, name: longName, brand: longBrand },
|
||||
"https://portal.example.com",
|
||||
);
|
||||
assert.ok(Buffer.byteLength(message.text, "utf8") <= 4000);
|
||||
assert.ok(Buffer.byteLength(message.link.title, "utf8") <= 128);
|
||||
assert.ok(Buffer.byteLength(message.link.desc, "utf8") <= 512);
|
||||
});
|
||||
|
||||
test("groupChatsByOwner groups chat ids by owner and skips empty owners", () => {
|
||||
const grouped = groupChatsByOwner([
|
||||
{ chat_id: "wr-1", name: "一", owner_user_id: "zhangsan", member_count: 1, status: 0 },
|
||||
{ chat_id: "wr-2", name: "二", owner_user_id: "lisi", member_count: 2, status: 0 },
|
||||
{ chat_id: "wr-3", name: "三", owner_user_id: "zhangsan", member_count: 3, status: 0 },
|
||||
{ chat_id: "wr-4", name: "四", owner_user_id: " ", member_count: 4, status: 0 },
|
||||
]);
|
||||
assert.deepEqual(grouped, [
|
||||
{ ownerUserId: "zhangsan", chatIds: ["wr-1", "wr-3"] },
|
||||
{ ownerUserId: "lisi", chatIds: ["wr-2"] },
|
||||
]);
|
||||
});
|
||||
|
||||
function fakeGroupPushDb(taskRow) {
|
||||
const executed = [];
|
||||
const groupRows = [
|
||||
{ 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 },
|
||||
];
|
||||
const makeStatement = (sql, params = []) => ({
|
||||
sql,
|
||||
params,
|
||||
bind(...args) {
|
||||
return makeStatement(sql, args);
|
||||
},
|
||||
async run() {
|
||||
executed.push({ sql, params });
|
||||
return {};
|
||||
},
|
||||
async first() {
|
||||
executed.push({ sql, params });
|
||||
if (/FROM tasks WHERE id = \?/.test(sql)) {
|
||||
return params[0] === taskRow.id ? taskRow : null;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
async all() {
|
||||
executed.push({ sql, params });
|
||||
if (/FROM wecom_group_chats/.test(sql)) {
|
||||
return {
|
||||
results: sql.includes(" IN (")
|
||||
? groupRows.filter((row) => params.includes(row.chat_id))
|
||||
: groupRows,
|
||||
};
|
||||
}
|
||||
return { results: [] };
|
||||
},
|
||||
});
|
||||
return {
|
||||
executed,
|
||||
prepare(sql) {
|
||||
return makeStatement(sql);
|
||||
},
|
||||
async batch(statements) {
|
||||
for (const statement of statements) await statement.run();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeTemplateFetch(calls) {
|
||||
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/externalcontact/add_msg_template")) {
|
||||
return Response.json({ errcode: 0, errmsg: "ok", msgid: "msg-1", fail_list: [] });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
test("pushTaskToGroupChats batches per owner and records each send", async () => {
|
||||
process.env.KOC_PORTAL_URL = "https://portal.example.com";
|
||||
try {
|
||||
const db = fakeGroupPushDb(baseTask);
|
||||
const calls = [];
|
||||
const summary = await pushTaskToGroupChats(
|
||||
db,
|
||||
{ taskId: "task-1", chatIds: ["wr-2", "wr-1"] },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeTemplateFetch(calls),
|
||||
);
|
||||
assert.equal(summary.results.length, 2);
|
||||
const senders = summary.results.map((item) => item.sender).sort();
|
||||
assert.deepEqual(senders, ["lisi", "zhangsan"]);
|
||||
const templateCalls = calls.filter((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
|
||||
);
|
||||
assert.equal(templateCalls.length, 2, "one call per owner");
|
||||
const bodies = templateCalls.map((c) => JSON.parse(String(c.init.body)));
|
||||
const bySender = new Map(bodies.map((body) => [body.sender, body]));
|
||||
assert.deepEqual(bySender.get("zhangsan").chat_id_list, ["wr-1"]);
|
||||
assert.deepEqual(bySender.get("lisi").chat_id_list, ["wr-2"]);
|
||||
assert.match(bySender.get("zhangsan").text.content, /【新任务】测试任务/);
|
||||
assert.equal(
|
||||
bySender.get("zhangsan").attachments[0].link.url,
|
||||
"https://portal.example.com/?task=tok-123",
|
||||
);
|
||||
const inserts = db.executed.filter((item) =>
|
||||
item.sql.includes("INSERT INTO wecom_group_pushes"),
|
||||
);
|
||||
assert.equal(inserts.length, 2);
|
||||
} finally {
|
||||
delete process.env.KOC_PORTAL_URL;
|
||||
}
|
||||
});
|
||||
|
||||
test("pushTaskToGroupChats rejects unknown chat ids", async () => {
|
||||
const db = fakeGroupPushDb(baseTask);
|
||||
const calls = [];
|
||||
await assert.rejects(
|
||||
() =>
|
||||
pushTaskToGroupChats(
|
||||
db,
|
||||
{ taskId: "task-1", chatIds: ["wr-404"] },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeTemplateFetch(calls),
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 400);
|
||||
assert.match(error.message, /未同步/);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("pushTaskToGroupChats rejects missing task", async () => {
|
||||
const db = fakeGroupPushDb(baseTask);
|
||||
await assert.rejects(
|
||||
() =>
|
||||
pushTaskToGroupChats(
|
||||
db,
|
||||
{ taskId: "task-404", chatIds: ["wr-1"] },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeTemplateFetch([]),
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 404);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("pushTaskToGroupChats prefers explicit text over template", async () => {
|
||||
process.env.KOC_PORTAL_URL = "https://portal.example.com";
|
||||
try {
|
||||
const db = fakeGroupPushDb(baseTask);
|
||||
const calls = [];
|
||||
await pushTaskToGroupChats(
|
||||
db,
|
||||
{ taskId: "task-1", chatIds: ["wr-1"], text: "运营手动编辑的文案" },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeTemplateFetch(calls),
|
||||
);
|
||||
const templateCall = calls.find((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/externalcontact/add_msg_template"),
|
||||
);
|
||||
const body = JSON.parse(String(templateCall.init.body));
|
||||
assert.equal(body.text.content, "运营手动编辑的文案");
|
||||
} finally {
|
||||
delete process.env.KOC_PORTAL_URL;
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user