Compare commits
11 Commits
main
...
fb1551a3a4
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb1551a3a4 | ||
|
|
4c1ff2d5b8 | ||
|
|
3e4269729c | ||
|
|
bca524417e | ||
|
|
d01281fba9 | ||
|
|
b243562e60 | ||
|
|
ca3810a3d0 | ||
|
|
6e590e3b08 | ||
|
|
b83a6a53c9 | ||
|
|
7f6c0e0983 | ||
|
|
a6f5a5fd4a |
@@ -50,6 +50,17 @@ WECOM_AGENT_ID=
|
||||
WECOM_SECRET=
|
||||
WECOM_NOTIFY_DUE_DAYS=3
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
# 数据回流通知(可选):KOC 提交链接/截图、每日采集摘要推运营群机器人,默认关闭。
|
||||
WECOM_FEEDBACK_ENABLED=false
|
||||
# 超期升级催办(可选):超期任务升级运营群机器人 + 项目总群交互卡片,默认关闭。
|
||||
WECOM_ESCALATION_ENABLED=false
|
||||
# 超期 N 天自动释放(可选):从 due_at 起算,超期内容自动回到可领取池,0 = 关闭(默认),最大 90。
|
||||
WECOM_AUTO_RELEASE_DAYS=0
|
||||
# 企微回调(可选):交互卡片「已处理」回执落库。需在企微后台「接收消息」配置回调 URL
|
||||
# https://<APP_ORIGIN>/api/wecom-callback + 下方 Token / EncodingAESKey,默认关闭。
|
||||
WECOM_CALLBACK_ENABLED=false
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_CALLBACK_ENCODING_AES_KEY=
|
||||
|
||||
# ── 调度与入口 ────────────────────────────────────────────
|
||||
# 每天北京时间 09:00 自动执行采集计划,生产保持 true。
|
||||
|
||||
@@ -93,6 +93,11 @@ WECOM_SECRET — 企业微信自建应用 Secret(可选)
|
||||
WECOM_ROBOT_WEBHOOK — 企业微信群机器人 webhook(当日催办汇总,可选)
|
||||
WECOM_NOTIFY_DUE_DAYS — 临期阈值,默认 3,取值 1–30(可选)
|
||||
WECOM_NOTIFY_ENABLED — 企业微信通知总开关,默认 true(可选)
|
||||
WECOM_FEEDBACK_ENABLED — 数据回流通知(提交/采集摘要推运营群),默认 false(可选)
|
||||
WECOM_ESCALATION_ENABLED — 超期升级催办(运营群+交互卡片),默认 false(可选)
|
||||
WECOM_AUTO_RELEASE_DAYS — 超期 N 天自动释放,从 due_at 起算,0=关闭(可选)
|
||||
WECOM_CALLBACK_ENABLED — 企微回调开关(交互卡片回执),默认 false(可选)
|
||||
WECOM_CALLBACK_TOKEN / WECOM_CALLBACK_ENCODING_AES_KEY — 企微回调密钥(/api/wecom-callback)
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
1638
app/admin-app.tsx
1638
app/admin-app.tsx
File diff suppressed because it is too large
Load Diff
@@ -10,6 +10,7 @@ import {
|
||||
ensureSchema,
|
||||
getDashboardData,
|
||||
getRawDb,
|
||||
getTaskReportData,
|
||||
uid,
|
||||
} from "../../../lib/mvp-db";
|
||||
import {
|
||||
@@ -45,7 +46,11 @@ import {
|
||||
WecomClientError,
|
||||
type WecomBindings,
|
||||
} from "../../../lib/wecom-client";
|
||||
import { runDueSoonWecomNotifications } from "../../../lib/wecom-notifier-service";
|
||||
import {
|
||||
runDueSoonWecomNotifications,
|
||||
runOverdueAutoRelease,
|
||||
runOverdueEscalation,
|
||||
} from "../../../lib/wecom-notifier-service";
|
||||
import {
|
||||
listGroupChatRows,
|
||||
listGroupPushes,
|
||||
@@ -58,6 +63,24 @@ import {
|
||||
getAccountFieldRefreshStatus,
|
||||
startAccountFieldRefresh,
|
||||
} from "../../../lib/account-field-refresh-service";
|
||||
import {
|
||||
deleteProject,
|
||||
getProjectDetail,
|
||||
listGroupOwnerPartners,
|
||||
listProjects,
|
||||
ProjectError,
|
||||
saveGroupOwnerPartner,
|
||||
saveProject,
|
||||
setProjectGroupChats,
|
||||
} from "../../../lib/project-service";
|
||||
import { pushProjectTask } from "../../../lib/project-push-service";
|
||||
import {
|
||||
findTodayTaskPushLog,
|
||||
listBoundWecomPartners,
|
||||
listTaskPushLogs,
|
||||
OneClickPushError,
|
||||
oneClickPushTask,
|
||||
} from "../../../lib/task-one-click-push-service";
|
||||
|
||||
type ActionBody = {
|
||||
action?: string;
|
||||
@@ -119,6 +142,7 @@ export async function POST(request: Request) {
|
||||
dueAt,
|
||||
platform,
|
||||
contentFormat,
|
||||
projectId: String(body.projectId ?? "").trim(),
|
||||
},
|
||||
env as unknown as FeishuBindings,
|
||||
);
|
||||
@@ -131,6 +155,7 @@ export async function POST(request: Request) {
|
||||
instructions: String(body.instructions ?? "").trim(),
|
||||
quantity: numberValue(body.quantity),
|
||||
exampleImageKey: String(body.exampleImageKey ?? "").trim(),
|
||||
projectId: String(body.projectId ?? "").trim(),
|
||||
});
|
||||
} else if (body.action === "claim") {
|
||||
const partnerId = String(body.partnerId ?? "");
|
||||
@@ -644,6 +669,14 @@ export async function POST(request: Request) {
|
||||
wecomConfig,
|
||||
);
|
||||
return Response.json(summary);
|
||||
} else if (body.action === "trigger_wecom_overdue_escalation") {
|
||||
if (!isManagerRequest(request)) return adminForbidden();
|
||||
const wecomConfig = resolveWecomConfig(
|
||||
env as unknown as WecomBindings,
|
||||
);
|
||||
const escalation = await runOverdueEscalation(db, wecomConfig);
|
||||
const autoRelease = await runOverdueAutoRelease(db, wecomConfig);
|
||||
return Response.json({ escalation, autoRelease });
|
||||
} else if (body.action === "wecom_list_external_contacts") {
|
||||
const wecomConfig = resolveWecomConfig(
|
||||
env as unknown as WecomBindings,
|
||||
@@ -687,6 +720,91 @@ export async function POST(request: Request) {
|
||||
const taskId = String(body.taskId ?? "").trim();
|
||||
const pushes = await listGroupPushes(db, taskId || undefined);
|
||||
return Response.json({ pushes });
|
||||
} else if (body.action === "project_list") {
|
||||
return Response.json({ projects: await listProjects(db) });
|
||||
} else if (body.action === "project_detail") {
|
||||
return Response.json(await getProjectDetail(db, String(body.projectId ?? "")));
|
||||
} else if (body.action === "project_save") {
|
||||
return Response.json({
|
||||
project: await saveProject(db, {
|
||||
id: body.id,
|
||||
name: body.name,
|
||||
brand: body.brand,
|
||||
mainGroupMemberIds: body.mainGroupMemberIds,
|
||||
note: body.note,
|
||||
}),
|
||||
});
|
||||
} else if (body.action === "project_delete") {
|
||||
await deleteProject(db, String(body.projectId ?? ""));
|
||||
return Response.json({ ok: true });
|
||||
} else if (body.action === "project_set_group_chats") {
|
||||
const detail = await setProjectGroupChats(
|
||||
db,
|
||||
String(body.projectId ?? ""),
|
||||
Array.isArray(body.items) ? body.items : [],
|
||||
);
|
||||
return Response.json(detail);
|
||||
} else if (body.action === "partner_save") {
|
||||
return Response.json({
|
||||
partner: await saveGroupOwnerPartner(db, {
|
||||
id: body.id,
|
||||
name: body.name,
|
||||
wecomUserid: body.wecomUserid,
|
||||
}),
|
||||
});
|
||||
} else if (body.action === "partner_group_owners") {
|
||||
return Response.json({ partners: await listGroupOwnerPartners(db) });
|
||||
} else if (body.action === "project_push_task") {
|
||||
const wecomConfig = resolveWecomConfig(env as unknown as WecomBindings);
|
||||
const outcome = await pushProjectTask(
|
||||
db,
|
||||
{
|
||||
taskId: body.taskId,
|
||||
sendMainGroup: body.sendMainGroup,
|
||||
sendGroupChats: body.sendGroupChats,
|
||||
text: body.text,
|
||||
},
|
||||
wecomConfig,
|
||||
);
|
||||
const appFailed = outcome.appResults.filter((item) => !item.ok);
|
||||
return Response.json({
|
||||
...outcome,
|
||||
appSent: outcome.appResults.length - appFailed.length,
|
||||
appFailedCount: appFailed.length,
|
||||
hint: "任务群走企业群发,群主需在企微客户端「群发助手」点击发送后,消息才会送达客户群",
|
||||
});
|
||||
} else if (body.action === "wecom_bound_partners") {
|
||||
const partners = await listBoundWecomPartners(db);
|
||||
const taskId = String(body.taskId ?? "").trim();
|
||||
const pushedToday = taskId
|
||||
? await findTodayTaskPushLog(db, taskId, "task_open")
|
||||
: null;
|
||||
return Response.json({ partners, pushedToday });
|
||||
} else if (body.action === "task_one_click_push") {
|
||||
const wecomConfig = resolveWecomConfig(env as unknown as WecomBindings);
|
||||
const outcome = await oneClickPushTask(
|
||||
db,
|
||||
{
|
||||
taskId: body.taskId,
|
||||
sendMainGroup: body.sendMainGroup,
|
||||
sendKoc: body.sendKoc,
|
||||
createGroupTemplate: body.createGroupTemplate,
|
||||
selectedKocPartnerIds: body.selectedKocPartnerIds,
|
||||
force: body.force,
|
||||
text: body.text,
|
||||
},
|
||||
wecomConfig,
|
||||
);
|
||||
return Response.json({
|
||||
...outcome,
|
||||
hint: "KOC 直达消息已即时送达;任务群走企业群发,群主需在企微客户端「群发助手」点击发送后才会送达客户群",
|
||||
});
|
||||
} else if (body.action === "task_push_logs") {
|
||||
const logs = await listTaskPushLogs(db, String(body.taskId ?? "").trim());
|
||||
return Response.json({ logs });
|
||||
} else if (body.action === "task_report_list") {
|
||||
if (!isManagerRequest(request)) return adminForbidden();
|
||||
return Response.json({ reports: await getTaskReportData(db) });
|
||||
} else if (body.action === "refresh_account_fields") {
|
||||
const status = startAccountFieldRefresh(
|
||||
db,
|
||||
@@ -711,7 +829,9 @@ export async function POST(request: Request) {
|
||||
status:
|
||||
error instanceof FeishuSourceError ||
|
||||
error instanceof DistributionReleaseError ||
|
||||
error instanceof WecomClientError
|
||||
error instanceof WecomClientError ||
|
||||
error instanceof ProjectError ||
|
||||
error instanceof OneClickPushError
|
||||
? error.status
|
||||
: 500,
|
||||
},
|
||||
|
||||
@@ -23,6 +23,19 @@ import {
|
||||
} from "../../../lib/partner-utils";
|
||||
import { extractPublishUrl } from "../../../lib/publish-url";
|
||||
import { parseClaimantIdentifier } from "../../../lib/claimant-identifier";
|
||||
import {
|
||||
resolveWecomClaimant,
|
||||
verifyWecomIdentityTicket,
|
||||
type WecomIdentity,
|
||||
} from "../../../lib/wecom-oauth-service";
|
||||
import {
|
||||
isWecomFeedbackEnabled,
|
||||
notifyPartnerSubmitted,
|
||||
} from "../../../lib/wecom-feedback-service";
|
||||
import {
|
||||
resolveWecomConfig,
|
||||
type WecomBindings,
|
||||
} from "../../../lib/wecom-client";
|
||||
import {
|
||||
partnerOptions,
|
||||
withPartnerCors,
|
||||
@@ -39,6 +52,7 @@ type PartnerBody = {
|
||||
delegationBundleId?: string;
|
||||
claimantIdentifier?: string;
|
||||
claimantName?: string;
|
||||
identityTicket?: string;
|
||||
quantity?: number;
|
||||
publishUrl?: string;
|
||||
exposure?: number | string;
|
||||
@@ -446,13 +460,27 @@ async function handlePost(request: Request) {
|
||||
}
|
||||
const db = getRawDb();
|
||||
|
||||
let wecomIdentity: WecomIdentity | null = null;
|
||||
if (body.identityTicket) {
|
||||
try {
|
||||
wecomIdentity = await verifyWecomIdentityTicket(
|
||||
textValue(body.identityTicket, 512),
|
||||
);
|
||||
} catch {
|
||||
wecomIdentity = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (body.action === "recover") {
|
||||
const identifierInput = textValue(
|
||||
body.claimantIdentifier ?? body.claimantName,
|
||||
64,
|
||||
);
|
||||
const claimantIdentifier = parseClaimantIdentifier(identifierInput);
|
||||
if (!claimantIdentifier && identifierInput.length < 2) {
|
||||
const wecomPartnerId = wecomIdentity
|
||||
? (await resolveWecomClaimant(db, wecomIdentity.externalUserId)).partnerId
|
||||
: null;
|
||||
if (!claimantIdentifier && identifierInput.length < 2 && !wecomPartnerId) {
|
||||
return Response.json(
|
||||
{ error: "请输入领取时使用的正确微信号或手机号" },
|
||||
{ status: 400 },
|
||||
@@ -466,6 +494,11 @@ async function handlePost(request: Request) {
|
||||
`claimant:${claimantIdentifier.canonical}`,
|
||||
)}`
|
||||
: legacyPartnerId;
|
||||
const partnerCandidates = [
|
||||
...new Set(
|
||||
wecomPartnerId ? [wecomPartnerId] : [partnerId, legacyPartnerId],
|
||||
),
|
||||
];
|
||||
const recovered = await db
|
||||
.prepare(
|
||||
`SELECT
|
||||
@@ -481,12 +514,14 @@ async function handlePost(request: Request) {
|
||||
FROM claims c
|
||||
LEFT JOIN distributions d ON d.claim_id = c.id
|
||||
LEFT JOIN contents co ON co.id = d.content_id
|
||||
WHERE c.task_id = ? AND c.partner_id IN (?, ?)
|
||||
WHERE c.task_id = ? AND c.partner_id IN (${partnerCandidates
|
||||
.map(() => "?")
|
||||
.join(", ")})
|
||||
GROUP BY c.id, c.claim_token, c.quantity, c.created_at
|
||||
ORDER BY c.created_at DESC, c.id DESC
|
||||
LIMIT 20`,
|
||||
)
|
||||
.bind(task.task_type, task.task_type, task.id, partnerId, legacyPartnerId)
|
||||
.bind(task.task_type, task.task_type, task.id, ...partnerCandidates)
|
||||
.all<{
|
||||
claim_token: string;
|
||||
quantity: number;
|
||||
@@ -522,7 +557,7 @@ async function handlePost(request: Request) {
|
||||
);
|
||||
const claimantIdentifier = parseClaimantIdentifier(identifierInput);
|
||||
const quantity = quantityValue(body.quantity);
|
||||
if (!claimantIdentifier) {
|
||||
if (!claimantIdentifier && !wecomIdentity) {
|
||||
return Response.json(
|
||||
{ error: "请输入正确的微信号或手机号" },
|
||||
{ status: 400 },
|
||||
@@ -540,23 +575,45 @@ async function handlePost(request: Request) {
|
||||
if (available.results.length === 0) {
|
||||
return Response.json({ error: "当前任务已领完" }, { status: 409 });
|
||||
}
|
||||
const partnerId = `partner-ext-${hashText(
|
||||
`claimant:${claimantIdentifier.canonical}`,
|
||||
)}`;
|
||||
const claimantName = claimantIdentifier.display;
|
||||
const partnerId = wecomIdentity
|
||||
? (await resolveWecomClaimant(db, wecomIdentity.externalUserId)).partnerId
|
||||
: `partner-ext-${hashText(
|
||||
`claimant:${claimantIdentifier?.canonical}`,
|
||||
)}`;
|
||||
const claimantName = wecomIdentity
|
||||
? wecomIdentity.displayName
|
||||
: (claimantIdentifier?.display ?? "");
|
||||
const claimId = uid("claim");
|
||||
const claimToken = crypto.randomUUID().replaceAll("-", "");
|
||||
const statements: DatabaseStatement[] = [
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO partners
|
||||
(id, name, wecom_name, owner, claimed_total, completed_total)
|
||||
VALUES (?, ?, ?, '外部KOC', 0, 0)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
wecom_name = excluded.wecom_name`,
|
||||
)
|
||||
.bind(partnerId, claimantName, claimantName),
|
||||
wecomIdentity
|
||||
? db
|
||||
.prepare(
|
||||
`INSERT INTO partners
|
||||
(id, name, wecom_name, owner, claimed_total, completed_total,
|
||||
wecom_external_user_id)
|
||||
VALUES (?, ?, ?, '外部KOC', 0, 0, ?)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
wecom_name = excluded.wecom_name,
|
||||
wecom_external_user_id = excluded.wecom_external_user_id`,
|
||||
)
|
||||
.bind(
|
||||
partnerId,
|
||||
claimantName,
|
||||
claimantName,
|
||||
wecomIdentity.externalUserId,
|
||||
)
|
||||
: db
|
||||
.prepare(
|
||||
`INSERT INTO partners
|
||||
(id, name, wecom_name, owner, claimed_total, completed_total)
|
||||
VALUES (?, ?, ?, '外部KOC', 0, 0)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
name = excluded.name,
|
||||
wecom_name = excluded.wecom_name`,
|
||||
)
|
||||
.bind(partnerId, claimantName, claimantName),
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO claims
|
||||
@@ -1014,6 +1071,14 @@ async function handlePost(request: Request) {
|
||||
),
|
||||
).catch(() => undefined);
|
||||
runInBackground(enrichment, "distribution account enrichment");
|
||||
if (isWecomFeedbackEnabled()) {
|
||||
const feedback = notifyPartnerSubmitted(
|
||||
db,
|
||||
{ distributionId: assignment.id, kind: "publish" },
|
||||
resolveWecomConfig(env as unknown as WecomBindings),
|
||||
).catch(() => undefined);
|
||||
runInBackground(feedback, "wecom publish feedback");
|
||||
}
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
@@ -1107,6 +1172,14 @@ async function handlePost(request: Request) {
|
||||
);
|
||||
}
|
||||
await db.batch(statements);
|
||||
if (isWecomFeedbackEnabled()) {
|
||||
const feedback = notifyPartnerSubmitted(
|
||||
db,
|
||||
{ distributionId: assignment.id, kind: "screenshot" },
|
||||
resolveWecomConfig(env as unknown as WecomBindings),
|
||||
).catch(() => undefined);
|
||||
runInBackground(feedback, "wecom screenshot feedback");
|
||||
}
|
||||
return Response.json({ submitted: true });
|
||||
}
|
||||
|
||||
|
||||
29
app/api/task-report-export/route.ts
Normal file
29
app/api/task-report-export/route.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
|
||||
import { buildTaskReportCsv } from "../../../lib/task-report-csv";
|
||||
import {
|
||||
ensureSchema,
|
||||
getRawDb,
|
||||
getTaskReportData,
|
||||
} from "../../../lib/mvp-db";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
if (!(await isAdminRequest(request))) return adminForbidden();
|
||||
await ensureSchema();
|
||||
const rows = await getTaskReportData(getRawDb());
|
||||
const fileName = `任务复盘报表.csv`;
|
||||
return new Response(buildTaskReportCsv(rows), {
|
||||
headers: {
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Type": "text/csv; charset=utf-8",
|
||||
"Content-Disposition": `attachment; filename="koc-task-report.csv"; filename*=UTF-8''${encodeURIComponent(fileName)}`,
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return Response.json(
|
||||
{ error: error instanceof Error ? error.message : "导出失败" },
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
131
app/api/wecom-callback/route.ts
Normal file
131
app/api/wecom-callback/route.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
decryptWecomCallback,
|
||||
verifyWecomCallbackSignature,
|
||||
wecomSignaturesMatch,
|
||||
WecomCallbackCryptoError,
|
||||
} from "../../../lib/wecom-callback-crypto";
|
||||
import {
|
||||
extractWecomEncryptField,
|
||||
handleWecomCallbackEvent,
|
||||
parseWecomCallbackXml,
|
||||
} from "../../../lib/wecom-callback-events";
|
||||
import { ensureSchema, getRawDb } from "../../../lib/mvp-db";
|
||||
import { isEnabled, getRuntimeEnv } from "../../../lib/runtime-env";
|
||||
|
||||
type CallbackConfig = {
|
||||
token: string;
|
||||
encodingAesKey: string;
|
||||
corpId: string;
|
||||
};
|
||||
|
||||
function resolveCallbackConfig(): CallbackConfig | null {
|
||||
const env = getRuntimeEnv();
|
||||
if (!isEnabled(env.WECOM_CALLBACK_ENABLED, false)) return null;
|
||||
const token = String(env.WECOM_CALLBACK_TOKEN ?? "").trim();
|
||||
const encodingAesKey = String(
|
||||
env.WECOM_CALLBACK_ENCODING_AES_KEY ?? "",
|
||||
).trim();
|
||||
if (!token || !encodingAesKey) return null;
|
||||
return {
|
||||
token,
|
||||
encodingAesKey,
|
||||
corpId: String(env.WECOM_CORP_ID ?? "").trim(),
|
||||
};
|
||||
}
|
||||
|
||||
function readCallbackQuery(request: Request) {
|
||||
const url = new URL(request.url);
|
||||
return {
|
||||
msgSignature: url.searchParams.get("msg_signature") ?? "",
|
||||
timestamp: url.searchParams.get("timestamp") ?? "",
|
||||
nonce: url.searchParams.get("nonce") ?? "",
|
||||
echostr: url.searchParams.get("echostr") ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const config = resolveCallbackConfig();
|
||||
if (!config) {
|
||||
return new Response("企业微信回调未启用", { status: 403 });
|
||||
}
|
||||
const { msgSignature, timestamp, nonce, echostr } =
|
||||
readCallbackQuery(request);
|
||||
if (!msgSignature || !timestamp || !nonce || !echostr) {
|
||||
return new Response("缺少回调校验参数", { status: 400 });
|
||||
}
|
||||
const expected = verifyWecomCallbackSignature(
|
||||
config.token,
|
||||
timestamp,
|
||||
nonce,
|
||||
echostr,
|
||||
);
|
||||
if (!wecomSignaturesMatch(expected, msgSignature)) {
|
||||
return new Response("签名校验失败", { status: 403 });
|
||||
}
|
||||
try {
|
||||
const { message } = decryptWecomCallback(echostr, config.encodingAesKey);
|
||||
return new Response(message, {
|
||||
status: 200,
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof WecomCallbackCryptoError) {
|
||||
console.warn("[KOC LOOP] wecom callback echostr decrypt failed", error);
|
||||
return new Response(error.message, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const config = resolveCallbackConfig();
|
||||
if (!config) {
|
||||
return new Response("企业微信回调未启用", { status: 403 });
|
||||
}
|
||||
const { msgSignature, timestamp, nonce } = readCallbackQuery(request);
|
||||
try {
|
||||
const body = await request.text();
|
||||
const encrypt = extractWecomEncryptField(body);
|
||||
if (!encrypt) {
|
||||
return new Response("回调报文缺少 Encrypt 字段", { status: 400 });
|
||||
}
|
||||
if (!msgSignature || !timestamp || !nonce) {
|
||||
return new Response("缺少回调校验参数", { status: 400 });
|
||||
}
|
||||
const expected = verifyWecomCallbackSignature(
|
||||
config.token,
|
||||
timestamp,
|
||||
nonce,
|
||||
encrypt,
|
||||
);
|
||||
if (!wecomSignaturesMatch(expected, msgSignature)) {
|
||||
return new Response("签名校验失败", { status: 403 });
|
||||
}
|
||||
const { message, receiveId } = decryptWecomCallback(
|
||||
encrypt,
|
||||
config.encodingAesKey,
|
||||
);
|
||||
if (config.corpId && receiveId !== config.corpId) {
|
||||
console.warn(
|
||||
"[KOC LOOP] wecom callback receiveid mismatch",
|
||||
{ expected: config.corpId },
|
||||
);
|
||||
return new Response("receiveid 校验失败", { status: 403 });
|
||||
}
|
||||
const fields = parseWecomCallbackXml(message);
|
||||
try {
|
||||
await ensureSchema();
|
||||
await handleWecomCallbackEvent(getRawDb(), fields);
|
||||
} catch (eventError) {
|
||||
console.error("[KOC LOOP] wecom callback event handling failed", eventError);
|
||||
}
|
||||
return new Response("", { status: 200 });
|
||||
} catch (error) {
|
||||
if (error instanceof WecomCallbackCryptoError) {
|
||||
console.warn("[KOC LOOP] wecom callback decrypt failed", error);
|
||||
return new Response(error.message, { status: 400 });
|
||||
}
|
||||
console.error("[KOC LOOP] wecom callback failed", error);
|
||||
return new Response("", { status: 200 });
|
||||
}
|
||||
}
|
||||
65
app/api/wecom-oauth/route.ts
Normal file
65
app/api/wecom-oauth/route.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { getRuntimeEnv } from "../../../lib/runtime-env";
|
||||
import {
|
||||
exchangeWecomOAuthCode,
|
||||
fetchWecomExternalContactName,
|
||||
resolveWecomConfig,
|
||||
WecomClientError,
|
||||
type WecomBindings,
|
||||
} from "../../../lib/wecom-client";
|
||||
import { signWecomIdentityTicket } from "../../../lib/wecom-oauth-service";
|
||||
import { partnerOptions, withPartnerCors } from "../../../lib/partner-cors";
|
||||
|
||||
const env = getRuntimeEnv();
|
||||
|
||||
export function OPTIONS(request: Request) {
|
||||
return partnerOptions(request);
|
||||
}
|
||||
|
||||
async function handlePost(request: Request) {
|
||||
try {
|
||||
const body = (await request.json().catch(() => ({}))) as { code?: string };
|
||||
const code = String(body.code ?? "").trim();
|
||||
const config = resolveWecomConfig(env as unknown as WecomBindings);
|
||||
if (!config.corpId || !config.agentId || !config.secret) {
|
||||
return Response.json(
|
||||
{ error: "未配置企业微信授权(WECOM_CORP_ID / WECOM_AGENT_ID / WECOM_SECRET)" },
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
if (!code) {
|
||||
return Response.json({ error: "缺少授权 code" }, { status: 400 });
|
||||
}
|
||||
const identity = await exchangeWecomOAuthCode(config, code);
|
||||
if (identity.externalUserId) {
|
||||
const displayName =
|
||||
(await fetchWecomExternalContactName(config, identity.externalUserId)) ??
|
||||
"企微客户";
|
||||
const { ticket, expiresIn } = await signWecomIdentityTicket(
|
||||
identity.externalUserId,
|
||||
displayName,
|
||||
);
|
||||
return Response.json({
|
||||
userType: "external",
|
||||
identityTicket: ticket,
|
||||
displayName,
|
||||
expiresIn,
|
||||
});
|
||||
}
|
||||
return Response.json({
|
||||
userType: "internal",
|
||||
userId: identity.userId ?? "",
|
||||
});
|
||||
} catch (error) {
|
||||
const status = error instanceof WecomClientError ? error.status : 500;
|
||||
return Response.json(
|
||||
{ error: error instanceof Error ? error.message : "授权失败" },
|
||||
{ status },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const response = await handlePost(request);
|
||||
response.headers.set("Cache-Control", "private, no-store");
|
||||
return withPartnerCors(request, response);
|
||||
}
|
||||
314
app/globals.css
314
app/globals.css
@@ -5372,3 +5372,317 @@ label small {
|
||||
animation-iteration-count: 1 !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── 项目中心 ─────────────────────────────────────────── */
|
||||
|
||||
.project-hero-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.project-panel {
|
||||
padding: 18px 20px;
|
||||
}
|
||||
|
||||
.project-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.project-card-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.project-card-title h3 {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.project-card-title small {
|
||||
display: block;
|
||||
margin-top: 3px;
|
||||
color: #8a968f;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-card-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.project-note {
|
||||
margin: 10px 0 0;
|
||||
color: #7d8a83;
|
||||
font-size: 11px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.share-link-button.danger {
|
||||
color: #c0453e;
|
||||
}
|
||||
|
||||
.project-detail {
|
||||
margin-top: 14px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px dashed #dfe6e1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.project-detail-grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(240px, 0.9fr) 1.4fr;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.project-detail-block {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.project-detail-block-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.project-detail-block-head h4 {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.project-detail-block-head small {
|
||||
color: #97a29c;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.project-member-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.project-member-list code {
|
||||
padding: 3px 8px;
|
||||
border-radius: 6px;
|
||||
background: #eef2ef;
|
||||
color: #556861;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-empty-line {
|
||||
color: #9aa39f;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-chat-table,
|
||||
.project-task-table {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-chat-missing td {
|
||||
color: #b0685f;
|
||||
background: #fdf6f5;
|
||||
}
|
||||
|
||||
.project-chat-missing td:first-child {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.project-push-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.project-push-bar small {
|
||||
color: #97a29c;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-chat-hint {
|
||||
margin: 0 0 10px;
|
||||
color: #7d8a83;
|
||||
font-size: 11px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.project-chat-edit-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.project-chat-edit-row .group-push-row {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.project-chat-edit-row select {
|
||||
max-width: 220px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.project-delete-warning {
|
||||
margin: 0;
|
||||
padding: 10px 12px;
|
||||
border-radius: 9px;
|
||||
background: #fdf6f5;
|
||||
color: #a2564e;
|
||||
font-size: 11px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.project-push-targets {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.project-push-target {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid #e2e8e4;
|
||||
border-radius: 9px;
|
||||
background: #fbfcfb;
|
||||
}
|
||||
|
||||
.project-push-target b {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.project-push-target small {
|
||||
display: block;
|
||||
margin-top: 2px;
|
||||
color: #8a968f;
|
||||
font-size: 10px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.koc-picker {
|
||||
margin: 10px 0;
|
||||
}
|
||||
|
||||
.koc-picker-toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.koc-picker-toolbar input[type="text"],
|
||||
.koc-picker-toolbar input:not([type]) {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.koc-picker-toolbar label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
color: #4b5563;
|
||||
}
|
||||
|
||||
.koc-picker-list {
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
border: 1px solid #e2e8e4;
|
||||
border-radius: 9px;
|
||||
background: #fbfcfb;
|
||||
}
|
||||
|
||||
.koc-picker-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 7px 12px;
|
||||
border-bottom: 1px solid #eef2ee;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.koc-picker-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.koc-picker-item span {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.koc-picker-item small {
|
||||
margin-left: auto;
|
||||
color: #8a968f;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
/* ── 合作方类型 ───────────────────────────────────────── */
|
||||
|
||||
.partner-type-tabs {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.partner-type-tabs button {
|
||||
padding: 5px 12px;
|
||||
border: 1px solid #dfe6e1;
|
||||
border-radius: 999px;
|
||||
background: #fbfcfb;
|
||||
color: #687773;
|
||||
font-size: 11px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.partner-type-tabs button.active {
|
||||
border-color: #205843;
|
||||
background: #205843;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.partner-type-badge {
|
||||
display: inline-block;
|
||||
margin-left: 6px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
font-size: 10px;
|
||||
font-style: normal;
|
||||
vertical-align: 1px;
|
||||
}
|
||||
|
||||
.partner-type-badge.group-owner {
|
||||
background: #e7f2ec;
|
||||
color: #1f6b4a;
|
||||
}
|
||||
|
||||
.partner-type-badge.external-koc {
|
||||
background: #eef1f6;
|
||||
color: #4c5f85;
|
||||
}
|
||||
|
||||
.partner-owner-hint {
|
||||
color: #9aa39f;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.project-detail-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.project-hero-actions {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
48
db/schema.ts
48
db/schema.ts
@@ -22,6 +22,10 @@ export const partners = mysqlTable("partners", {
|
||||
claimedTotal: int("claimed_total").notNull().default(0),
|
||||
completedTotal: int("completed_total").notNull().default(0),
|
||||
wecomExternalUserId: varchar("wecom_external_user_id", { length: 128 }),
|
||||
partnerType: varchar("partner_type", { length: 32 })
|
||||
.notNull()
|
||||
.default("external_koc"),
|
||||
wecomUserid: varchar("wecom_userid", { length: 128 }).notNull().default(""),
|
||||
createdAt: timestamp("created_at"),
|
||||
});
|
||||
|
||||
@@ -53,6 +57,7 @@ export const tasks = mysqlTable(
|
||||
mode: "string",
|
||||
fsp: 3,
|
||||
}),
|
||||
projectId: varchar("project_id", { length: 64 }).notNull().default(""),
|
||||
createdAt: timestamp("created_at"),
|
||||
},
|
||||
(table) => [uniqueIndex("tasks_share_token_idx").on(table.shareToken)],
|
||||
@@ -282,6 +287,49 @@ export const wecomGroupPushes = mysqlTable(
|
||||
(table) => [index("wecom_group_pushes_task_idx").on(table.taskId)],
|
||||
);
|
||||
|
||||
export const wecomPushLogs = mysqlTable(
|
||||
"wecom_push_logs",
|
||||
{
|
||||
id: varchar("id", { length: 64 }).primaryKey(),
|
||||
taskId: varchar("task_id", { length: 64 }).notNull(),
|
||||
projectId: varchar("project_id", { length: 64 }).notNull().default(""),
|
||||
pushKind: varchar("push_kind", { length: 32 }).notNull().default("task_open"),
|
||||
mainGroupCount: int("main_group_count").notNull().default(0),
|
||||
kocUserids: text("koc_userids").notNull(),
|
||||
kocOkCount: int("koc_ok_count").notNull().default(0),
|
||||
kocFailList: text("koc_fail_list").notNull(),
|
||||
groupPushId: varchar("group_push_id", { length: 128 }).notNull().default(""),
|
||||
detail: text("detail").notNull(),
|
||||
createdAt: timestamp("created_at"),
|
||||
},
|
||||
(table) => [index("wecom_push_logs_task_idx").on(table.taskId, table.pushKind)],
|
||||
);
|
||||
|
||||
export const projects = mysqlTable("projects", {
|
||||
id: varchar("id", { length: 64 }).primaryKey(),
|
||||
name: varchar("name", { length: 255 }).notNull(),
|
||||
brand: varchar("brand", { length: 255 }).notNull().default(""),
|
||||
mainGroupMemberIds: text("main_group_member_ids").notNull(),
|
||||
status: varchar("status", { length: 32 }).notNull().default("active"),
|
||||
note: text("note").notNull(),
|
||||
createdAt: timestamp("created_at"),
|
||||
});
|
||||
|
||||
export const projectGroupChats = mysqlTable(
|
||||
"project_group_chats",
|
||||
{
|
||||
id: varchar("id", { length: 64 }).primaryKey(),
|
||||
projectId: varchar("project_id", { length: 64 }).notNull(),
|
||||
chatId: varchar("chat_id", { length: 128 }).notNull(),
|
||||
partnerId: varchar("partner_id", { length: 64 }).notNull().default(""),
|
||||
createdAt: timestamp("created_at"),
|
||||
},
|
||||
(table) => [
|
||||
uniqueIndex("project_group_chats_uniq").on(table.projectId, table.chatId),
|
||||
index("project_group_chats_project_idx").on(table.projectId),
|
||||
],
|
||||
);
|
||||
|
||||
export const backgroundJobs = mysqlTable(
|
||||
"background_jobs",
|
||||
{
|
||||
|
||||
12
dev.vars_exp
12
dev.vars_exp
@@ -26,7 +26,17 @@ WECOM_ROBOT_WEBHOOK=
|
||||
WECOM_NOTIFY_DUE_DAYS=3
|
||||
# 企业微信通知总开关,默认 true;临时关闭设为 false
|
||||
WECOM_NOTIFY_ENABLED=true
|
||||
# 数据回流通知(可选):KOC 提交链接/截图、采集摘要推运营群机器人,默认关闭
|
||||
WECOM_FEEDBACK_ENABLED=false
|
||||
# 超期升级催办(可选):超期任务升级运营群 + 项目总群交互卡片,默认关闭
|
||||
WECOM_ESCALATION_ENABLED=false
|
||||
# 超期 N 天自动释放(可选):从 due_at 起算,0 = 关闭(默认),最大 90
|
||||
WECOM_AUTO_RELEASE_DAYS=0
|
||||
# 企微回调(可选):交互卡片「已处理」回执落库;回调 URL 为 /api/wecom-callback,默认关闭
|
||||
WECOM_CALLBACK_ENABLED=false
|
||||
WECOM_CALLBACK_TOKEN=
|
||||
WECOM_CALLBACK_ENCODING_AES_KEY=
|
||||
|
||||
# 本地测试:让 /api/bootstrap 自动 seed 3 个测试 partner + 5 条待发布 distribution
|
||||
# 上线后改为 false
|
||||
SEED_DEMO_DATA=true
|
||||
SEED_DEMO_DATA=false
|
||||
|
||||
@@ -65,6 +65,11 @@ cp .env.app.example .env.app
|
||||
| `WECOM_ROBOT_WEBHOOK` | 企业微信群机器人 webhook,用于当日催办汇总 |
|
||||
| `WECOM_NOTIFY_DUE_DAYS` | 临期阈值,默认 3,超过则不在催办;可填 1–30 |
|
||||
| `WECOM_NOTIFY_ENABLED` | 企业微信通知总开关,默认 `true`;临时关闭设为 `false` |
|
||||
| `WECOM_FEEDBACK_ENABLED` | 数据回流通知,默认 `false`;开启后 KOC 提交链接/截图与每日采集摘要推送运营群机器人 |
|
||||
| `WECOM_ESCALATION_ENABLED` | 超期升级催办,默认 `false`;开启后超期任务升级运营群机器人 + 项目总群交互卡片 |
|
||||
| `WECOM_AUTO_RELEASE_DAYS` | 超期 N 天自动释放内容回可领取池,从 `due_at` 起算,`0` = 关闭(默认),最大 90 |
|
||||
| `WECOM_CALLBACK_ENABLED` | 企微回调开关,默认 `false`;开启后支持交互卡片「已处理」回执落库,需配置回调 URL 与密钥 |
|
||||
| `WECOM_CALLBACK_TOKEN` / `WECOM_CALLBACK_ENCODING_AES_KEY` | 企微后台「接收消息」里生成的回调 Token 与 EncodingAESKey |
|
||||
|
||||
企业微信变量全部选填:不填则临期催办与汇总都跳过,不影响其他功能。所有变量都可以在「合作方」页面顶部「企业微信连通性」面板查看就绪状态,并用「测试群机器人」「测试发送」按钮验证。
|
||||
|
||||
@@ -229,7 +234,7 @@ docker compose --env-file .env.app \
|
||||
|
||||
## 11. 企业微信自建应用与群机器人配置
|
||||
|
||||
KOC LOOP 的企业微信通知是**单向外发**:每天 09:00 与定时采集一同触发,给合作方绑定的外部联系人推送临期催办,再向群机器人发送当日汇总。不需要 OAuth 回调,也不需要拉通讯录。
|
||||
KOC LOOP 的企业微信通知默认是**单向外发**:每天 09:00 与定时采集一同触发,给合作方绑定的外部联系人推送临期催办,再向群机器人发送当日汇总。基础催办不需要回调,也不需要拉通讯录;交互卡片回执等进阶能力见第 12 章。
|
||||
|
||||
### 11.1 群机器人(用于当日催办汇总)
|
||||
|
||||
@@ -280,3 +285,36 @@ KOC LOOP 的企业微信通知是**单向外发**:每天 09:00 与定时采集
|
||||
使用流程:后台「任务中心」→ 任务行「发布到企微群」→ 弹窗内「同步群列表」(拉取客户联系下的正常状态客户群)→ 勾选目标群、确认文案 → 「创建群发」。创建成功后平台返回 msgid 并落库 `wecom_group_pushes`,各群主在企微客户端收到群发助手提醒,**点击发送后**消息(含 KOC 领取链接)才出现在群里。
|
||||
|
||||
限制与注意:每个客户群每月最多接收「当月天数」条企业群发;群主使用的企业微信客户端需 ≥4.1.10 才能免选群直接发送;无效的 chat_id 会进入失败列表但不影响其他群。
|
||||
|
||||
## 12. 以企微为中心的业务流程(一键推送 / 回流通知 / 分层催办 / 回调卡片 / 复盘报表)
|
||||
|
||||
在 11.2 自建应用与 11.5 企业群发的基础上,以下能力全部由环境变量独立控制,默认关闭,不配置则对现有流程零影响。推送记录统一落库 `wecom_push_logs`(迁移 `mysql/0011_wecom_push_logs.sql`,`npm run db:migrate` 自动执行)。
|
||||
|
||||
### 12.1 任务一键推送
|
||||
|
||||
后台「任务中心」→ 任务行「一键推送」:一次把任务送达三类对象 —— ①项目总群成员应用消息(复用项目推送)②已绑定企微的 KOC 个人直达(弹层默认全选,可搜索/取消勾选)③可选创建任务群企业群发。同一任务当日重复推送会先提示,确认后可强制再推。KOC 消息里的领取链接在企微内置浏览器打开时自动完成 OAuth 静默登录,KOC 无需输任何身份。
|
||||
|
||||
### 12.2 数据回流通知(`WECOM_FEEDBACK_ENABLED`)
|
||||
|
||||
开启后:KOC 提交发布链接 / 截图 → 运营群机器人收到提醒(合作方 / 任务 / 标题 / 链接);每天 09:00 定时采集结束后推送批次摘要,采集失败会附告警清单。通知失败不影响提交与采集主流程。
|
||||
|
||||
### 12.3 超期升级与自动释放(`WECOM_ESCALATION_ENABLED` / `WECOM_AUTO_RELEASE_DAYS`)
|
||||
|
||||
催办分三层:临期(默认 3 天内)直达合作方本人(原有逻辑不变)→ 超期(`due_at` 已过)升级运营群机器人汇总 + 项目总群成员收到 template_card 交互卡片(按钮「查看任务」跳转、「已处理」回执落库)→ 超期 N 天(`WECOM_AUTO_RELEASE_DAYS`,从 `due_at` 起算)自动把仍未发布的 distribution 释放回可领取池,已提交截图或已回填链接的不释放。两层开关独立;也可在「合作方」页点「跑一次超期升级」手动触发。
|
||||
|
||||
### 12.4 企微回调配置(`WECOM_CALLBACK_ENABLED`)
|
||||
|
||||
交互卡片「已处理」按钮需要公网回调才能回执。步骤:
|
||||
|
||||
1. 登录企业微信管理后台 → 应用管理 → 自建 → 打开 11.2 的应用;
|
||||
2. 「接收消息」→ 设置 API 接收 → 回调 URL 填 `https://<APP_ORIGIN>/api/wecom-callback`(必须公网 80/443 可达,与 APP_ORIGIN 一致);
|
||||
3. Token 与 EncodingAESKey 随机生成后,分别填入 `WECOM_CALLBACK_TOKEN`、`WECOM_CALLBACK_ENCODING_AES_KEY`,保存时企微会向该 URL 发 GET 验证,服务端自动应答;
|
||||
4. 「企业可信 IP」(开发者接口)加入服务器出口 IP,否则 access_token 类接口全部返回 `60020`;
|
||||
5. 应用「可见范围」包含接收卡片的运营成员;
|
||||
6. `WECOM_CALLBACK_ENABLED=true` 并重启服务;关闭时回调路由直接 403,可随时回退。
|
||||
|
||||
回执写入 `wecom_push_logs`(`push_kind = card_ack`),在任务推送记录里可见「卡片确认」条目。回调地址、Token 或密钥配错时企微保存验证不通过,逐项核对第 2、3 步。
|
||||
|
||||
### 12.5 复盘报表
|
||||
|
||||
后台「复盘报表」(管理员可见):按任务汇总领取 / 发布 / 完成数、完成率、曝光阅读与 D2/D5/D7/最新互动数据,支持状态、类型、关键词筛选,一键导出带 BOM 的 CSV(Excel 直接打开不乱码)。无需环境变量。
|
||||
|
||||
@@ -547,6 +547,40 @@ input:focus {
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.wecom-identity-chip {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: var(--green-soft);
|
||||
}
|
||||
|
||||
.wecom-identity-chip b {
|
||||
color: var(--green-deep);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.wecom-identity-chip span {
|
||||
color: var(--ink);
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wecom-identity-chip button {
|
||||
margin-left: auto;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--muted);
|
||||
font-size: 10px;
|
||||
text-decoration: underline;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.recovery-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -107,11 +107,135 @@ function partnerApi(
|
||||
path:
|
||||
| "/api/partner"
|
||||
| "/api/partner-upload"
|
||||
| "/api/partner-batch-workbook",
|
||||
| "/api/partner-batch-workbook"
|
||||
| "/api/wecom-oauth",
|
||||
) {
|
||||
return `${resolveAdminOrigin()}${path}`;
|
||||
}
|
||||
|
||||
const WECOM_CORP_ID = process.env.NEXT_PUBLIC_WECOM_CORP_ID ?? "";
|
||||
const WECOM_AGENT_ID = process.env.NEXT_PUBLIC_WECOM_AGENT_ID ?? "";
|
||||
const WECOM_OAUTH_ENABLED = Boolean(WECOM_CORP_ID && WECOM_AGENT_ID);
|
||||
const WECOM_PORTAL_BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH ?? "/koc";
|
||||
const WECOM_IDENTITY_SESSION_KEY = "koc-wecom-identity";
|
||||
const WECOM_AUTH_FAILED_KEY = "koc-wecom-auth-failed";
|
||||
const WECOM_OAUTH_SID_PREFIX = "koc-wecom-oauth-sid";
|
||||
const WECOM_OAUTH_STATE_LIMIT = 120;
|
||||
|
||||
type WecomPortalIdentity = {
|
||||
ticket: string;
|
||||
name: string;
|
||||
expiresAt: number;
|
||||
};
|
||||
|
||||
type PortalParams = {
|
||||
task: string;
|
||||
claim: string;
|
||||
share: string;
|
||||
note: string;
|
||||
};
|
||||
|
||||
function readSessionValue<T>(key: string): T | null {
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(key);
|
||||
return raw ? (JSON.parse(raw) as T) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeSessionValue(key: string, value: unknown): boolean {
|
||||
try {
|
||||
window.sessionStorage.setItem(key, JSON.stringify(value));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function markSessionFlag(key: string) {
|
||||
try {
|
||||
window.sessionStorage.setItem(key, "1");
|
||||
} catch {
|
||||
// 隐私模式等场景下忽略,最多少一次自动授权
|
||||
}
|
||||
}
|
||||
|
||||
function hasSessionFlag(key: string) {
|
||||
try {
|
||||
return window.sessionStorage.getItem(key) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function loadWecomIdentity(): WecomPortalIdentity | null {
|
||||
const identity = readSessionValue<WecomPortalIdentity>(
|
||||
WECOM_IDENTITY_SESSION_KEY,
|
||||
);
|
||||
if (!identity?.ticket || typeof identity.expiresAt !== "number") return null;
|
||||
if (Date.now() > identity.expiresAt) return null;
|
||||
return identity;
|
||||
}
|
||||
|
||||
function isWecomEmbeddedBrowser() {
|
||||
const userAgent = window.navigator.userAgent;
|
||||
return /wxwork/i.test(userAgent) || /MicroMessenger/i.test(userAgent);
|
||||
}
|
||||
|
||||
function buildWecomAuthorizeUrl(state: string) {
|
||||
const query = new URLSearchParams({
|
||||
appid: WECOM_CORP_ID,
|
||||
redirect_uri: `${window.location.origin}${WECOM_PORTAL_BASE_PATH}/`,
|
||||
response_type: "code",
|
||||
scope: "snsapi_base",
|
||||
state,
|
||||
agentid: WECOM_AGENT_ID,
|
||||
});
|
||||
return `https://open.weixin.qq.com/connect/oauth2/authorize?${query}#wechat_redirect`;
|
||||
}
|
||||
|
||||
function buildWecomOAuthState(params: PortalParams): string {
|
||||
const compact = new URLSearchParams();
|
||||
if (params.task) compact.set("t", params.task);
|
||||
if (params.claim) compact.set("c", params.claim);
|
||||
if (params.share) compact.set("s", params.share);
|
||||
if (params.note) compact.set("n", params.note);
|
||||
if (compact.toString().length <= WECOM_OAUTH_STATE_LIMIT) {
|
||||
return compact.toString();
|
||||
}
|
||||
const sid = crypto.randomUUID().replaceAll("-", "").slice(0, 12);
|
||||
if (writeSessionValue(`${WECOM_OAUTH_SID_PREFIX}:${sid}`, params)) {
|
||||
return `sid=${sid}`;
|
||||
}
|
||||
const fallback = new URLSearchParams();
|
||||
if (params.task) fallback.set("t", params.task);
|
||||
if (params.share) fallback.set("s", params.share);
|
||||
return fallback.toString();
|
||||
}
|
||||
|
||||
function restoreParamsFromWecomState(state: string): PortalParams {
|
||||
const parsed = new URLSearchParams(state);
|
||||
const sid = parsed.get("sid");
|
||||
if (sid) {
|
||||
const key = `${WECOM_OAUTH_SID_PREFIX}:${sid}`;
|
||||
const stored = readSessionValue<PortalParams>(key);
|
||||
try {
|
||||
window.sessionStorage.removeItem(key);
|
||||
} catch {
|
||||
// 忽略清理失败
|
||||
}
|
||||
if (stored?.task || stored?.share) return stored;
|
||||
return { task: "", claim: "", share: "", note: "" };
|
||||
}
|
||||
return {
|
||||
task: parsed.get("t") ?? "",
|
||||
claim: parsed.get("c") ?? "",
|
||||
share: parsed.get("s") ?? "",
|
||||
note: parsed.get("n") ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function isMobilePortalViewport() {
|
||||
return (
|
||||
typeof window !== "undefined" &&
|
||||
@@ -325,6 +449,10 @@ export default function Home() {
|
||||
const [creatorViews, setCreatorViews] = useState("");
|
||||
const [entryMode, setEntryMode] = useState<"claim" | "recover">("claim");
|
||||
const [recoveredClaims, setRecoveredClaims] = useState<RecoveredClaim[]>([]);
|
||||
const [wecomIdentity, setWecomIdentity] = useState<WecomPortalIdentity | null>(
|
||||
null,
|
||||
);
|
||||
const [manualEntry, setManualEntry] = useState(false);
|
||||
const [adminOrigin, setAdminOrigin] = useState("");
|
||||
const [downloadingImage, setDownloadingImage] = useState<number | null>(null);
|
||||
const [batchDownloading, setBatchDownloading] = useState(false);
|
||||
@@ -401,10 +529,79 @@ export default function Home() {
|
||||
}
|
||||
}, []);
|
||||
|
||||
const exchangeWecomIdentity = useCallback(
|
||||
async (code: string, restored: PortalParams) => {
|
||||
try {
|
||||
const response = await fetch(partnerApi("/api/wecom-oauth"), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code }),
|
||||
});
|
||||
const result = (await response.json()) as {
|
||||
userType?: string;
|
||||
identityTicket?: string;
|
||||
displayName?: string;
|
||||
expiresIn?: number;
|
||||
error?: string;
|
||||
};
|
||||
if (
|
||||
response.ok &&
|
||||
result.userType === "external" &&
|
||||
result.identityTicket
|
||||
) {
|
||||
const identity: WecomPortalIdentity = {
|
||||
ticket: result.identityTicket,
|
||||
name: result.displayName || "企微客户",
|
||||
expiresAt:
|
||||
Date.now() +
|
||||
Math.max(60, (result.expiresIn ?? 1800) - 60) * 1_000,
|
||||
};
|
||||
writeSessionValue(WECOM_IDENTITY_SESSION_KEY, identity);
|
||||
setWecomIdentity(identity);
|
||||
setManualEntry(false);
|
||||
setToast(`企微身份已确认:${identity.name}`);
|
||||
} else {
|
||||
markSessionFlag(WECOM_AUTH_FAILED_KEY);
|
||||
setToast(
|
||||
result.userType === "internal"
|
||||
? "当前为企业内部成员身份,请手动输入微信号领取"
|
||||
: result.error || "企微授权失败,请手动输入微信号",
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
markSessionFlag(WECOM_AUTH_FAILED_KEY);
|
||||
setToast("企微授权失败,请手动输入微信号");
|
||||
}
|
||||
setTaskToken(restored.task);
|
||||
setClaimToken(restored.claim);
|
||||
setDelegationToken(restored.share);
|
||||
setSelectedId(restored.note);
|
||||
if (!restored.task && !restored.share) {
|
||||
setLoading(false);
|
||||
setError("任务链接不完整,请向运营重新获取");
|
||||
return;
|
||||
}
|
||||
await loadTask(restored.task, restored.claim, restored.share);
|
||||
},
|
||||
[loadTask],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = window.setTimeout(() => {
|
||||
setAdminOrigin(resolveAdminOrigin());
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const oauthCode = params.get("code") ?? "";
|
||||
if (oauthCode) {
|
||||
const restored = restoreParamsFromWecomState(params.get("state") ?? "");
|
||||
const cleaned = new URL(window.location.href);
|
||||
cleaned.searchParams.delete("code");
|
||||
cleaned.searchParams.delete("state");
|
||||
window.history.replaceState({}, "", cleaned);
|
||||
void exchangeWecomIdentity(oauthCode, restored);
|
||||
return;
|
||||
}
|
||||
const cachedIdentity = loadWecomIdentity();
|
||||
if (cachedIdentity) setWecomIdentity(cachedIdentity);
|
||||
const task = params.get("task") ?? "";
|
||||
const claim = params.get("claim") ?? "";
|
||||
const delegation = params.get("share") ?? "";
|
||||
@@ -418,10 +615,28 @@ export default function Home() {
|
||||
setError("任务链接不完整,请向运营重新获取");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
WECOM_OAUTH_ENABLED &&
|
||||
!cachedIdentity &&
|
||||
!hasSessionFlag(WECOM_AUTH_FAILED_KEY) &&
|
||||
isWecomEmbeddedBrowser()
|
||||
) {
|
||||
window.location.replace(
|
||||
buildWecomAuthorizeUrl(
|
||||
buildWecomOAuthState({
|
||||
task,
|
||||
claim,
|
||||
share: delegation,
|
||||
note,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
void loadTask(task, claim, delegation);
|
||||
}, 0);
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [loadTask]);
|
||||
}, [loadTask, exchangeWecomIdentity]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!toast) return;
|
||||
@@ -464,6 +679,9 @@ export default function Home() {
|
||||
action: "claim",
|
||||
taskToken,
|
||||
claimantIdentifier: claimantName,
|
||||
...(wecomIdentity && !manualEntry
|
||||
? { identityTicket: wecomIdentity.ticket }
|
||||
: {}),
|
||||
quantity,
|
||||
}),
|
||||
});
|
||||
@@ -512,6 +730,9 @@ export default function Home() {
|
||||
action: "recover",
|
||||
taskToken,
|
||||
claimantIdentifier: claimantName,
|
||||
...(wecomIdentity && !manualEntry
|
||||
? { identityTicket: wecomIdentity.ticket }
|
||||
: {}),
|
||||
}),
|
||||
});
|
||||
const result = (await response.json()) as {
|
||||
@@ -2031,25 +2252,36 @@ export default function Home() {
|
||||
找回领取记录
|
||||
</button>
|
||||
</div>
|
||||
{wecomIdentity && !manualEntry && (
|
||||
<div className="wecom-identity-chip">
|
||||
<b>企微身份已确认</b>
|
||||
<span>{wecomIdentity.name}</span>
|
||||
<button type="button" onClick={() => setManualEntry(true)}>
|
||||
切换为手动输入
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
{entryMode === "claim" ? (
|
||||
<form onSubmit={claimNotes}>
|
||||
<div>
|
||||
<p className="micro">01 · 确认领取</p>
|
||||
<h2>你要领取多少{payload.task.type === "screenshot_collect" ? "份" : "篇"}?</h2>
|
||||
</div>
|
||||
<label>
|
||||
<span>微信号 / 手机号</span>
|
||||
<input
|
||||
value={claimantName}
|
||||
onChange={(event) => setClaimantName(event.target.value)}
|
||||
placeholder="请输入微信号或手机号"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
maxLength={64}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
{(!wecomIdentity || manualEntry) && (
|
||||
<label>
|
||||
<span>微信号 / 手机号</span>
|
||||
<input
|
||||
value={claimantName}
|
||||
onChange={(event) => setClaimantName(event.target.value)}
|
||||
placeholder="请输入微信号或手机号"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
maxLength={64}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<div className="quantity-control">
|
||||
<button type="button" onClick={() => setQuantity(Math.max(1, quantity - 1))}>−</button>
|
||||
<div><strong>{quantity}</strong><span>{payload.task.type === "screenshot_collect" ? "份" : "篇"}</span></div>
|
||||
@@ -2080,22 +2312,26 @@ export default function Home() {
|
||||
<p className="micro">找回历史记录</p>
|
||||
<h2>继续之前领取的{payload.task.type === "screenshot_collect" ? "任务" : "笔记"}</h2>
|
||||
<p className="recover-intro">
|
||||
输入领取时使用的微信号或手机号;同一任务多次领取会分批展示。
|
||||
{wecomIdentity && !manualEntry
|
||||
? "已用企微身份查找,同一任务多次领取会分批展示。"
|
||||
: "输入领取时使用的微信号或手机号;同一任务多次领取会分批展示。"}
|
||||
</p>
|
||||
</div>
|
||||
<label>
|
||||
<span>领取时的微信号 / 手机号</span>
|
||||
<input
|
||||
value={claimantName}
|
||||
onChange={(event) => setClaimantName(event.target.value)}
|
||||
placeholder="需与领取时完全一致"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
maxLength={64}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
{(!wecomIdentity || manualEntry) && (
|
||||
<label>
|
||||
<span>领取时的微信号 / 手机号</span>
|
||||
<input
|
||||
value={claimantName}
|
||||
onChange={(event) => setClaimantName(event.target.value)}
|
||||
placeholder="需与领取时完全一致"
|
||||
autoCapitalize="none"
|
||||
autoCorrect="off"
|
||||
spellCheck={false}
|
||||
maxLength={64}
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
)}
|
||||
<button className="claim-primary" disabled={working}>
|
||||
{working ? "正在查找…" : "查找我的领取记录"}
|
||||
</button>
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
"dev": "next dev -p 3001",
|
||||
"build": "next build",
|
||||
"start": "npx serve out -l 3001",
|
||||
"test": "npm run build && node --test tests/rendered-html.test.mjs",
|
||||
"test": "npm run build && node --import tsx --test tests/rendered-html.test.mjs",
|
||||
"lint": "eslint . --ignore-pattern dist --ignore-pattern .next --ignore-pattern out"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
@@ -170,3 +170,29 @@ test("creates anonymous delegation bundles and reuses one-to-one backfill", asyn
|
||||
assert.match(styles, /\.share-checkbox/);
|
||||
assert.match(styles, /\.delegation-history/);
|
||||
});
|
||||
|
||||
test("wires silent wecom oauth with full manual fallback", async () => {
|
||||
const [page, styles] = await Promise.all([
|
||||
readFile(new URL("../app/page.tsx", import.meta.url), "utf8"),
|
||||
readFile(new URL("../app/globals.css", import.meta.url), "utf8"),
|
||||
]);
|
||||
|
||||
assert.match(page, /NEXT_PUBLIC_WECOM_CORP_ID/);
|
||||
assert.match(page, /NEXT_PUBLIC_WECOM_AGENT_ID/);
|
||||
assert.match(page, /snsapi_base/);
|
||||
assert.match(page, /connect\/oauth2\/authorize/);
|
||||
assert.match(page, /wxwork\/i\.test\(userAgent\)/);
|
||||
assert.match(page, /MicroMessenger\/i\.test\(userAgent\)/);
|
||||
assert.match(page, /"koc-wecom-identity"/);
|
||||
assert.match(page, /"koc-wecom-auth-failed"/);
|
||||
assert.match(page, /\/api\/wecom-oauth/);
|
||||
assert.match(page, /restoreParamsFromWecomState/);
|
||||
assert.match(page, /buildWecomOAuthState/);
|
||||
assert.match(page, /identityTicket: wecomIdentity\.ticket/);
|
||||
assert.match(page, /企微身份已确认/);
|
||||
assert.match(page, /切换为手动输入/);
|
||||
assert.match(page, /window\.location\.replace\(/);
|
||||
assert.match(styles, /\.wecom-identity-chip/);
|
||||
assert.match(page, /\(!wecomIdentity \|\| manualEntry\)/);
|
||||
assert.match(page, /claimantIdentifier:\s*claimantName/);
|
||||
});
|
||||
|
||||
@@ -872,6 +872,79 @@ export async function getDashboardData() {
|
||||
};
|
||||
}
|
||||
|
||||
export type TaskReportRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
task_type: string;
|
||||
brand: string;
|
||||
platform: string;
|
||||
status: string;
|
||||
due_at: string;
|
||||
created_at: string;
|
||||
quantity: number;
|
||||
project_name: string | null;
|
||||
claimed_count: number;
|
||||
published_count: number;
|
||||
completed_count: number;
|
||||
exposure_total: number | null;
|
||||
views_total: number | null;
|
||||
d2_likes: number | null;
|
||||
d2_comments: number | null;
|
||||
d2_collects: number | null;
|
||||
d5_likes: number | null;
|
||||
d5_comments: number | null;
|
||||
d5_collects: number | null;
|
||||
d7_likes: number | null;
|
||||
d7_comments: number | null;
|
||||
d7_collects: number | null;
|
||||
latest_likes: number | null;
|
||||
latest_comments: number | null;
|
||||
latest_collects: number | null;
|
||||
latest_shares: number | null;
|
||||
};
|
||||
|
||||
export async function getTaskReportData(db: DatabaseClient) {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT
|
||||
t.id,
|
||||
t.name,
|
||||
t.task_type,
|
||||
t.brand,
|
||||
t.platform,
|
||||
t.status,
|
||||
t.due_at,
|
||||
t.created_at,
|
||||
t.quantity,
|
||||
p.name AS project_name,
|
||||
COUNT(d.id) AS claimed_count,
|
||||
SUM(CASE WHEN TRIM(COALESCE(d.publish_url, '')) != '' THEN 1 ELSE 0 END) AS published_count,
|
||||
SUM(CASE WHEN d.status = 'complete' THEN 1 ELSE 0 END) AS completed_count,
|
||||
SUM(d.exposure) AS exposure_total,
|
||||
SUM(d.views) AS views_total,
|
||||
SUM(d.d2_likes) AS d2_likes,
|
||||
SUM(d.d2_comments) AS d2_comments,
|
||||
SUM(d.d2_collects) AS d2_collects,
|
||||
SUM(d.d5_likes) AS d5_likes,
|
||||
SUM(d.d5_comments) AS d5_comments,
|
||||
SUM(d.d5_collects) AS d5_collects,
|
||||
SUM(d.d7_likes) AS d7_likes,
|
||||
SUM(d.d7_comments) AS d7_comments,
|
||||
SUM(d.d7_collects) AS d7_collects,
|
||||
SUM(d.latest_likes) AS latest_likes,
|
||||
SUM(d.latest_comments) AS latest_comments,
|
||||
SUM(d.latest_collects) AS latest_collects,
|
||||
SUM(d.latest_shares) AS latest_shares
|
||||
FROM tasks t
|
||||
LEFT JOIN distributions d ON d.task_id = t.id
|
||||
LEFT JOIN projects p ON p.id = t.project_id
|
||||
GROUP BY t.id
|
||||
ORDER BY t.created_at DESC`,
|
||||
)
|
||||
.all<TaskReportRow>();
|
||||
return result.results;
|
||||
}
|
||||
|
||||
export function uid(prefix: string) {
|
||||
return `${prefix}-${crypto.randomUUID().slice(0, 8)}`;
|
||||
}
|
||||
|
||||
160
lib/project-push-service.ts
Normal file
160
lib/project-push-service.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
import { getRuntimeEnv } from "./runtime-env";
|
||||
import {
|
||||
sendWecomAppMessage,
|
||||
WecomClientError,
|
||||
type WecomConfig,
|
||||
} from "./wecom-client";
|
||||
import {
|
||||
pushTaskToGroupChats,
|
||||
type GroupPushResult,
|
||||
type TaskPushRow,
|
||||
} from "./wecom-group-push-service";
|
||||
import { getProjectDetail, ProjectError } from "./project-service";
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
export type AppMessageResult = {
|
||||
userid: string;
|
||||
ok: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type ProjectPushOutcome = {
|
||||
appResults: AppMessageResult[];
|
||||
groupResults: GroupPushResult[];
|
||||
groupChatCount: number;
|
||||
skippedReasons: string[];
|
||||
linkUrl: string;
|
||||
};
|
||||
|
||||
function text(value: unknown) {
|
||||
return String(value ?? "").trim();
|
||||
}
|
||||
|
||||
export function buildProjectAppMessage(
|
||||
task: Pick<
|
||||
TaskPushRow,
|
||||
| "name"
|
||||
| "brand"
|
||||
| "quantity"
|
||||
| "due_at"
|
||||
| "task_type"
|
||||
| "platform"
|
||||
| "content_format"
|
||||
| "share_token"
|
||||
>,
|
||||
portalUrl: string,
|
||||
): string {
|
||||
const portal = text(portalUrl).replace(/\/$/, "");
|
||||
const claimUrl =
|
||||
portal && task.share_token ? `${portal}/?task=${task.share_token}` : "";
|
||||
const formatLabel =
|
||||
task.task_type === "screenshot_collect"
|
||||
? "截图回收"
|
||||
: task.content_format === "video"
|
||||
? "视频"
|
||||
: "图文";
|
||||
return [
|
||||
`【项目任务】${task.name}`,
|
||||
`品牌:${task.brand}|数量:${task.quantity} 份|截止:${task.due_at}`,
|
||||
`平台:${task.platform}|形式:${formatLabel}`,
|
||||
"请把任务转发到你负责的项目任务群,并跟进群内成员领取与发布。",
|
||||
claimUrl ? `领取链接:${claimUrl}` : "领取链接生成失败,请联系管理员",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export async function pushProjectTask(
|
||||
db: DatabaseClient,
|
||||
params: {
|
||||
taskId: unknown;
|
||||
sendMainGroup?: unknown;
|
||||
sendGroupChats?: unknown;
|
||||
text?: unknown;
|
||||
},
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<ProjectPushOutcome> {
|
||||
const taskId = text(params.taskId);
|
||||
if (!taskId) throw new ProjectError("缺少 taskId");
|
||||
const sendMainGroup = params.sendMainGroup !== false;
|
||||
const sendGroupChats = params.sendGroupChats !== false;
|
||||
if (!sendMainGroup && !sendGroupChats) {
|
||||
throw new ProjectError("请至少选择一个发送目标(项目总群或任务群)");
|
||||
}
|
||||
|
||||
const task = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, quantity, due_at, task_type, platform,
|
||||
content_format, share_token
|
||||
FROM tasks WHERE id = ?`,
|
||||
)
|
||||
.bind(taskId)
|
||||
.first<TaskPushRow & { project_id: string }>();
|
||||
if (!task) throw new ProjectError("任务不存在", 404);
|
||||
if (!text(task.project_id)) {
|
||||
throw new ProjectError("该任务未挂项目,请先在任务中心关联项目");
|
||||
}
|
||||
|
||||
const detail = await getProjectDetail(db, task.project_id);
|
||||
const portalUrl = text(getRuntimeEnv().KOC_PORTAL_URL);
|
||||
const fallback = buildProjectAppMessage(task, portalUrl);
|
||||
const message = text(params.text) || fallback;
|
||||
|
||||
const skippedReasons: string[] = [];
|
||||
const appResults: AppMessageResult[] = [];
|
||||
if (sendMainGroup) {
|
||||
const members = detail.project.mainGroupMemberIds;
|
||||
if (members.length === 0) {
|
||||
skippedReasons.push("项目总群未配置成员");
|
||||
} else {
|
||||
for (const userid of members) {
|
||||
try {
|
||||
await sendWecomAppMessage([userid], message, config, fetchImpl);
|
||||
appResults.push({ userid, ok: true, error: "" });
|
||||
} catch (error) {
|
||||
appResults.push({
|
||||
userid,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : "发送失败",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let groupResults: GroupPushResult[] = [];
|
||||
let groupChatCount = 0;
|
||||
let linkUrl =
|
||||
task.share_token && portalUrl
|
||||
? `${portalUrl.replace(/\/$/, "")}/?task=${task.share_token}`
|
||||
: "";
|
||||
if (sendGroupChats) {
|
||||
const chatIds = detail.groupChats
|
||||
.filter((chat) => !chat.missing)
|
||||
.map((chat) => chat.chatId);
|
||||
if (chatIds.length === 0) {
|
||||
skippedReasons.push("项目没有可用的任务群");
|
||||
} else {
|
||||
const summary = await pushTaskToGroupChats(
|
||||
db,
|
||||
{ taskId, chatIds, text: message },
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
groupResults = summary.results;
|
||||
groupChatCount = chatIds.length;
|
||||
linkUrl = summary.linkUrl;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
appResults,
|
||||
groupResults,
|
||||
groupChatCount,
|
||||
skippedReasons,
|
||||
linkUrl,
|
||||
};
|
||||
}
|
||||
|
||||
export { WecomClientError };
|
||||
385
lib/project-service.ts
Normal file
385
lib/project-service.ts
Normal file
@@ -0,0 +1,385 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
|
||||
export type ProjectRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
main_group_member_ids: string;
|
||||
status: string;
|
||||
note: string;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type ProjectSummary = {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
status: string;
|
||||
note: string;
|
||||
createdAt: string;
|
||||
mainGroupMemberIds: string[];
|
||||
taskCount: number;
|
||||
groupChatCount: number;
|
||||
};
|
||||
|
||||
export type ProjectTaskRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
brand: string;
|
||||
quantity: number;
|
||||
claimed_quantity: number;
|
||||
due_at: string;
|
||||
status: string;
|
||||
task_type: string;
|
||||
platform: string;
|
||||
content_format: string;
|
||||
share_token: string | null;
|
||||
};
|
||||
|
||||
export type ProjectGroupChat = {
|
||||
chatId: string;
|
||||
name: string;
|
||||
ownerUserId: string;
|
||||
memberCount: number;
|
||||
status: number;
|
||||
partnerId: string;
|
||||
partnerName: string;
|
||||
missing: boolean;
|
||||
};
|
||||
|
||||
export type ProjectDetail = {
|
||||
project: ProjectSummary;
|
||||
tasks: ProjectTaskRow[];
|
||||
groupChats: ProjectGroupChat[];
|
||||
};
|
||||
|
||||
export type GroupOwnerPartnerRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
wecom_userid: string;
|
||||
partner_type: string;
|
||||
};
|
||||
|
||||
function text(value: unknown) {
|
||||
return String(value ?? "").trim();
|
||||
}
|
||||
|
||||
export class ProjectError extends Error {
|
||||
status: number;
|
||||
constructor(message: string, status = 400) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export function parseMemberIds(value: unknown): string[] {
|
||||
const raw = Array.isArray(value)
|
||||
? value.map((item) => text(item))
|
||||
: text(value).split(/[\s,;,;]+/);
|
||||
const seen = new Set<string>();
|
||||
for (const item of raw) {
|
||||
if (item) seen.add(item);
|
||||
}
|
||||
return [...seen];
|
||||
}
|
||||
|
||||
function parseJsonArray(value: string): string[] {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return Array.isArray(parsed) ? parsed.map((item) => String(item)) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function listProjects(db: DatabaseClient): Promise<ProjectSummary[]> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT p.id, p.name, p.brand, p.main_group_member_ids, p.status, p.note, p.created_at,
|
||||
(SELECT COUNT(*) FROM tasks t WHERE t.project_id = p.id) AS task_count,
|
||||
(SELECT COUNT(*) FROM project_group_chats g WHERE g.project_id = p.id) AS group_chat_count
|
||||
FROM projects p
|
||||
ORDER BY p.created_at DESC`,
|
||||
)
|
||||
.all<ProjectRow & { task_count: number; group_chat_count: number }>();
|
||||
return result.results.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
brand: row.brand,
|
||||
status: row.status,
|
||||
note: row.note,
|
||||
createdAt: row.created_at,
|
||||
mainGroupMemberIds: parseJsonArray(row.main_group_member_ids),
|
||||
taskCount: Number(row.task_count),
|
||||
groupChatCount: Number(row.group_chat_count),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getProjectDetail(
|
||||
db: DatabaseClient,
|
||||
projectId: string,
|
||||
): Promise<ProjectDetail> {
|
||||
const id = text(projectId);
|
||||
const project = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, main_group_member_ids, status, note, created_at
|
||||
FROM projects WHERE id = ?`,
|
||||
)
|
||||
.bind(id)
|
||||
.first<ProjectRow>();
|
||||
if (!project) throw new ProjectError("项目不存在", 404);
|
||||
|
||||
const tasks = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, quantity, claimed_quantity, due_at, status,
|
||||
task_type, platform, content_format, share_token
|
||||
FROM tasks WHERE project_id = ?
|
||||
ORDER BY created_at DESC`,
|
||||
)
|
||||
.bind(id)
|
||||
.all<ProjectTaskRow>();
|
||||
|
||||
const chats = await db
|
||||
.prepare(
|
||||
`SELECT g.chat_id, g.partner_id,
|
||||
c.name AS chat_name, c.owner_user_id, c.member_count, c.status AS chat_status,
|
||||
p.name AS partner_name
|
||||
FROM project_group_chats g
|
||||
LEFT JOIN wecom_group_chats c ON c.chat_id = g.chat_id
|
||||
LEFT JOIN partners p ON p.id = g.partner_id
|
||||
WHERE g.project_id = ?
|
||||
ORDER BY g.created_at`,
|
||||
)
|
||||
.bind(id)
|
||||
.all<{
|
||||
chat_id: string;
|
||||
partner_id: string;
|
||||
chat_name: string | null;
|
||||
owner_user_id: string | null;
|
||||
member_count: number | null;
|
||||
chat_status: number | null;
|
||||
partner_name: string | null;
|
||||
}>();
|
||||
|
||||
return {
|
||||
project: {
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
brand: project.brand,
|
||||
status: project.status,
|
||||
note: project.note,
|
||||
createdAt: project.created_at,
|
||||
mainGroupMemberIds: parseJsonArray(project.main_group_member_ids),
|
||||
taskCount: tasks.results.length,
|
||||
groupChatCount: chats.results.length,
|
||||
},
|
||||
tasks: tasks.results,
|
||||
groupChats: chats.results.map((row) => ({
|
||||
chatId: row.chat_id,
|
||||
name: row.chat_name ?? "",
|
||||
ownerUserId: row.owner_user_id ?? "",
|
||||
memberCount: Number(row.member_count ?? 0),
|
||||
status: Number(row.chat_status ?? 0),
|
||||
partnerId: row.partner_id,
|
||||
partnerName: row.partner_name ?? "",
|
||||
missing: row.chat_name === null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export type SaveProjectInput = {
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
brand?: unknown;
|
||||
mainGroupMemberIds?: unknown;
|
||||
note?: unknown;
|
||||
};
|
||||
|
||||
export async function saveProject(
|
||||
db: DatabaseClient,
|
||||
input: SaveProjectInput,
|
||||
): Promise<ProjectSummary> {
|
||||
const id = text(input.id);
|
||||
const name = text(input.name);
|
||||
const brand = text(input.brand);
|
||||
const note = text(input.note ?? "");
|
||||
const memberIds = parseMemberIds(input.mainGroupMemberIds);
|
||||
if (!name) throw new ProjectError("请填写项目名称");
|
||||
|
||||
const now = new Date().toISOString();
|
||||
let projectId = id;
|
||||
if (id) {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`UPDATE projects
|
||||
SET name = ?, brand = ?, main_group_member_ids = ?, note = ?
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.bind(name, brand, JSON.stringify(memberIds), note, id)
|
||||
.run();
|
||||
if (result.meta.changes === 0) throw new ProjectError("项目不存在", 404);
|
||||
} else {
|
||||
projectId = `proj-${crypto.randomUUID().slice(0, 12)}`;
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO projects
|
||||
(id, name, brand, main_group_member_ids, status, note, created_at)
|
||||
VALUES (?, ?, ?, ?, 'active', ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
projectId,
|
||||
name,
|
||||
brand,
|
||||
JSON.stringify(memberIds),
|
||||
note,
|
||||
now,
|
||||
)
|
||||
.run();
|
||||
}
|
||||
const detail = await getProjectDetail(db, projectId);
|
||||
return detail.project;
|
||||
}
|
||||
|
||||
export async function deleteProject(
|
||||
db: DatabaseClient,
|
||||
projectId: string,
|
||||
): Promise<void> {
|
||||
const id = text(projectId);
|
||||
if (!id) throw new ProjectError("缺少项目 ID");
|
||||
const result = await db
|
||||
.prepare("DELETE FROM projects WHERE id = ?")
|
||||
.bind(id)
|
||||
.run();
|
||||
if (result.meta.changes === 0) throw new ProjectError("项目不存在", 404);
|
||||
await db.batch([
|
||||
db.prepare("DELETE FROM project_group_chats WHERE project_id = ?").bind(id),
|
||||
db
|
||||
.prepare("UPDATE tasks SET project_id = '' WHERE project_id = ?")
|
||||
.bind(id),
|
||||
]);
|
||||
}
|
||||
|
||||
export type ProjectGroupChatInput = {
|
||||
chatId: string;
|
||||
partnerId?: string;
|
||||
};
|
||||
|
||||
export async function setProjectGroupChats(
|
||||
db: DatabaseClient,
|
||||
projectId: string,
|
||||
items: ProjectGroupChatInput[],
|
||||
): Promise<ProjectDetail> {
|
||||
const id = text(projectId);
|
||||
await getProjectDetail(db, id);
|
||||
const seen = new Set<string>();
|
||||
const rows: ProjectGroupChatInput[] = [];
|
||||
for (const item of Array.isArray(items) ? items : []) {
|
||||
const chatId = text(item?.chatId);
|
||||
if (!chatId || seen.has(chatId)) continue;
|
||||
seen.add(chatId);
|
||||
rows.push({ chatId, partnerId: text(item?.partnerId) });
|
||||
}
|
||||
const statements = [
|
||||
db.prepare("DELETE FROM project_group_chats WHERE project_id = ?").bind(id),
|
||||
...rows.map((row) =>
|
||||
db
|
||||
.prepare(
|
||||
`INSERT INTO project_group_chats
|
||||
(id, project_id, chat_id, partner_id, created_at)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
`pgc-${crypto.randomUUID().slice(0, 12)}`,
|
||||
id,
|
||||
row.chatId,
|
||||
row.partnerId ?? "",
|
||||
new Date().toISOString(),
|
||||
),
|
||||
),
|
||||
];
|
||||
await db.batch(statements);
|
||||
return getProjectDetail(db, id);
|
||||
}
|
||||
|
||||
export type ProjectPushTargets = {
|
||||
project: { id: string; name: string; mainGroupMemberIds: string[] };
|
||||
chatIds: string[];
|
||||
};
|
||||
|
||||
export async function getProjectPushTargets(
|
||||
db: DatabaseClient,
|
||||
projectId: string,
|
||||
): Promise<ProjectPushTargets> {
|
||||
const detail = await getProjectDetail(db, projectId);
|
||||
return {
|
||||
project: {
|
||||
id: detail.project.id,
|
||||
name: detail.project.name,
|
||||
mainGroupMemberIds: detail.project.mainGroupMemberIds,
|
||||
},
|
||||
chatIds: detail.groupChats.filter((chat) => !chat.missing).map((chat) => chat.chatId),
|
||||
};
|
||||
}
|
||||
|
||||
export async function listGroupOwnerPartners(
|
||||
db: DatabaseClient,
|
||||
): Promise<GroupOwnerPartnerRow[]> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT id, name, wecom_userid, partner_type
|
||||
FROM partners
|
||||
WHERE partner_type = 'group_owner'
|
||||
ORDER BY created_at DESC`,
|
||||
)
|
||||
.all<GroupOwnerPartnerRow>();
|
||||
return result.results;
|
||||
}
|
||||
|
||||
export type SavePartnerInput = {
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
wecomUserid?: unknown;
|
||||
};
|
||||
|
||||
export async function saveGroupOwnerPartner(
|
||||
db: DatabaseClient,
|
||||
input: SavePartnerInput,
|
||||
): Promise<GroupOwnerPartnerRow> {
|
||||
const id = text(input.id);
|
||||
const name = text(input.name);
|
||||
const wecomUserid = text(input.wecomUserid);
|
||||
if (!name) throw new ProjectError("请填写合作方名称");
|
||||
if (!wecomUserid) throw new ProjectError("请填写企业微信 userid");
|
||||
|
||||
let partnerId = id;
|
||||
if (id) {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`UPDATE partners
|
||||
SET name = ?, wecom_userid = ?, partner_type = 'group_owner'
|
||||
WHERE id = ?`,
|
||||
)
|
||||
.bind(name, wecomUserid, id)
|
||||
.run();
|
||||
if (result.meta.changes === 0) throw new ProjectError("合作方不存在", 404);
|
||||
} else {
|
||||
partnerId = `partner-go-${crypto.randomUUID().slice(0, 12)}`;
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO partners
|
||||
(id, name, wecom_name, owner, claimed_total, completed_total,
|
||||
partner_type, wecom_userid, created_at)
|
||||
VALUES (?, ?, '', '运营组', 0, 0, 'group_owner', ?, ?)`,
|
||||
)
|
||||
.bind(partnerId, name, wecomUserid, new Date().toISOString())
|
||||
.run();
|
||||
}
|
||||
const row = await db
|
||||
.prepare(
|
||||
"SELECT id, name, wecom_userid, partner_type FROM partners WHERE id = ?",
|
||||
)
|
||||
.bind(partnerId)
|
||||
.first<GroupOwnerPartnerRow>();
|
||||
if (!row) throw new ProjectError("合作方保存失败", 500);
|
||||
return row;
|
||||
}
|
||||
@@ -24,6 +24,12 @@ export type RuntimeEnv = {
|
||||
WECOM_ROBOT_WEBHOOK?: string;
|
||||
WECOM_NOTIFY_DUE_DAYS?: string;
|
||||
WECOM_NOTIFY_ENABLED?: string;
|
||||
WECOM_CALLBACK_TOKEN?: string;
|
||||
WECOM_CALLBACK_ENCODING_AES_KEY?: string;
|
||||
WECOM_CALLBACK_ENABLED?: string;
|
||||
WECOM_FEEDBACK_ENABLED?: string;
|
||||
WECOM_ESCALATION_ENABLED?: string;
|
||||
WECOM_AUTO_RELEASE_DAYS?: string;
|
||||
SEED_DEMO_DATA?: string;
|
||||
ENABLE_SCHEDULER?: string;
|
||||
};
|
||||
|
||||
@@ -12,7 +12,15 @@ import {
|
||||
resolveWecomConfig,
|
||||
type WecomBindings,
|
||||
} from "./wecom-client";
|
||||
import { runDueSoonWecomNotifications } from "./wecom-notifier-service";
|
||||
import {
|
||||
runDueSoonWecomNotifications,
|
||||
runOverdueAutoRelease,
|
||||
runOverdueEscalation,
|
||||
} from "./wecom-notifier-service";
|
||||
import {
|
||||
isWecomFeedbackEnabled,
|
||||
notifyCollectionFinished,
|
||||
} from "./wecom-feedback-service";
|
||||
|
||||
declare global {
|
||||
var __kocLoopScheduler: ScheduledTask | undefined;
|
||||
@@ -28,25 +36,49 @@ async function runDailyJob() {
|
||||
);
|
||||
const collections = await runScheduledCollections(db, Date.now(), config);
|
||||
const accounts = await backfillAccountProfiles(db, config, 10);
|
||||
const wecomConfig = resolveWecomConfig(env as unknown as WecomBindings);
|
||||
let wecom: Awaited<ReturnType<typeof runDueSoonWecomNotifications>> | null =
|
||||
null;
|
||||
if (isEnabled(env.WECOM_NOTIFY_ENABLED, true)) {
|
||||
const wecomConfig = resolveWecomConfig(env as unknown as WecomBindings);
|
||||
if (
|
||||
wecomConfig.robotWebhook ||
|
||||
(wecomConfig.corpId && wecomConfig.agentId && wecomConfig.secret)
|
||||
) {
|
||||
try {
|
||||
wecom = await runDueSoonWecomNotifications(db, wecomConfig);
|
||||
} catch (error) {
|
||||
console.error("[KOC LOOP] wecom notify failed", error);
|
||||
}
|
||||
let escalation: Awaited<ReturnType<typeof runOverdueEscalation>> | null =
|
||||
null;
|
||||
let autoRelease: Awaited<ReturnType<typeof runOverdueAutoRelease>> | null =
|
||||
null;
|
||||
if (
|
||||
isEnabled(env.WECOM_NOTIFY_ENABLED, true) &&
|
||||
(wecomConfig.robotWebhook ||
|
||||
(wecomConfig.corpId && wecomConfig.agentId && wecomConfig.secret))
|
||||
) {
|
||||
try {
|
||||
wecom = await runDueSoonWecomNotifications(db, wecomConfig);
|
||||
} catch (error) {
|
||||
console.error("[KOC LOOP] wecom notify failed", error);
|
||||
}
|
||||
}
|
||||
if (isEnabled(env.WECOM_ESCALATION_ENABLED, false)) {
|
||||
try {
|
||||
escalation = await runOverdueEscalation(db, wecomConfig);
|
||||
} catch (error) {
|
||||
console.error("[KOC LOOP] wecom overdue escalation failed", error);
|
||||
}
|
||||
}
|
||||
try {
|
||||
autoRelease = await runOverdueAutoRelease(db, wecomConfig);
|
||||
} catch (error) {
|
||||
console.error("[KOC LOOP] wecom overdue auto release failed", error);
|
||||
}
|
||||
if (isWecomFeedbackEnabled()) {
|
||||
try {
|
||||
await notifyCollectionFinished(collections, wecomConfig);
|
||||
} catch (error) {
|
||||
console.error("[KOC LOOP] wecom collection feedback failed", error);
|
||||
}
|
||||
}
|
||||
console.info("[KOC LOOP] daily scheduler completed", {
|
||||
collections,
|
||||
accounts,
|
||||
wecom,
|
||||
escalation,
|
||||
autoRelease,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
355
lib/task-one-click-push-service.ts
Normal file
355
lib/task-one-click-push-service.ts
Normal file
@@ -0,0 +1,355 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
import { getRuntimeEnv } from "./runtime-env";
|
||||
import {
|
||||
sendWecomAppMessage,
|
||||
type WecomConfig,
|
||||
} from "./wecom-client";
|
||||
import { pushProjectTask, type ProjectPushOutcome } from "./project-push-service";
|
||||
import type { TaskPushRow } from "./wecom-group-push-service";
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
export class OneClickPushError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(message: string, status = 400) {
|
||||
super(message);
|
||||
this.name = "OneClickPushError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export type BoundWecomPartner = {
|
||||
id: string;
|
||||
name: string;
|
||||
wecomExternalUserId: string;
|
||||
};
|
||||
|
||||
export type KocPushResult = {
|
||||
partnerId: string;
|
||||
partnerName: string;
|
||||
externalUserId: string;
|
||||
ok: boolean;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type TaskPushLogRow = {
|
||||
id: string;
|
||||
task_id: string;
|
||||
project_id: string;
|
||||
push_kind: string;
|
||||
main_group_count: number;
|
||||
koc_userids: string;
|
||||
koc_ok_count: number;
|
||||
koc_fail_list: string;
|
||||
group_push_id: string;
|
||||
detail: string;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type OneClickPushOutcome = {
|
||||
linkUrl: string;
|
||||
projectOutcome: ProjectPushOutcome | null;
|
||||
kocResults: KocPushResult[];
|
||||
kocSent: number;
|
||||
kocFailed: number;
|
||||
skippedReasons: string[];
|
||||
logId: string;
|
||||
};
|
||||
|
||||
function text(value: unknown) {
|
||||
return String(value ?? "").trim();
|
||||
}
|
||||
|
||||
export function buildKocDirectMessage(
|
||||
task: Pick<
|
||||
TaskPushRow,
|
||||
| "name"
|
||||
| "brand"
|
||||
| "quantity"
|
||||
| "due_at"
|
||||
| "task_type"
|
||||
| "platform"
|
||||
| "content_format"
|
||||
| "share_token"
|
||||
>,
|
||||
portalUrl: string,
|
||||
): string {
|
||||
const portal = text(portalUrl).replace(/\/$/, "");
|
||||
const claimUrl =
|
||||
portal && task.share_token ? `${portal}/?task=${task.share_token}` : "";
|
||||
const formatLabel =
|
||||
task.task_type === "screenshot_collect"
|
||||
? "截图回收"
|
||||
: task.content_format === "video"
|
||||
? "视频"
|
||||
: "图文";
|
||||
return [
|
||||
`【新任务】${task.name}`,
|
||||
`品牌:${task.brand}|数量:${task.quantity} 份|截止:${task.due_at}`,
|
||||
`平台:${task.platform}|形式:${formatLabel}`,
|
||||
"数量有限,先到先得,点击链接直接领取(企微内打开免输身份):",
|
||||
claimUrl || "领取链接生成失败,请联系管理员",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export async function listBoundWecomPartners(
|
||||
db: DatabaseClient,
|
||||
): Promise<BoundWecomPartner[]> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT id, name, wecom_external_user_id
|
||||
FROM partners
|
||||
WHERE wecom_external_user_id IS NOT NULL
|
||||
AND wecom_external_user_id != ''
|
||||
ORDER BY name ASC`,
|
||||
)
|
||||
.all<{
|
||||
id: string;
|
||||
name: string;
|
||||
wecom_external_user_id: string;
|
||||
}>();
|
||||
return result.results.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
wecomExternalUserId: row.wecom_external_user_id,
|
||||
}));
|
||||
}
|
||||
|
||||
export async function findTodayTaskPushLog(
|
||||
db: DatabaseClient,
|
||||
taskId: string,
|
||||
pushKind = "task_open",
|
||||
): Promise<TaskPushLogRow | null> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT id, task_id, project_id, push_kind, main_group_count,
|
||||
koc_userids, koc_ok_count, koc_fail_list, group_push_id,
|
||||
detail, created_at
|
||||
FROM wecom_push_logs
|
||||
WHERE task_id = ? AND push_kind = ?
|
||||
AND DATE(created_at) = CURDATE()
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 1`,
|
||||
)
|
||||
.bind(taskId, pushKind)
|
||||
.first<TaskPushLogRow>();
|
||||
return result ?? null;
|
||||
}
|
||||
|
||||
export async function listTaskPushLogs(
|
||||
db: DatabaseClient,
|
||||
taskId: string,
|
||||
): Promise<TaskPushLogRow[]> {
|
||||
const filter = taskId ? "WHERE task_id = ?" : "";
|
||||
const statement = db
|
||||
.prepare(
|
||||
`SELECT id, task_id, project_id, push_kind, main_group_count,
|
||||
koc_userids, koc_ok_count, koc_fail_list, group_push_id,
|
||||
detail, created_at
|
||||
FROM wecom_push_logs
|
||||
${filter}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 50`,
|
||||
)
|
||||
.bind(...(taskId ? [taskId] : []));
|
||||
const result = await statement.all<TaskPushLogRow>();
|
||||
return result.results;
|
||||
}
|
||||
|
||||
export async function recordCardAck(
|
||||
db: DatabaseClient,
|
||||
params: { cardTaskId: string; btnKey: string; operator: string },
|
||||
) {
|
||||
const taskId = /^task:([^:]+):/.exec(params.cardTaskId)?.[1] ?? "";
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO wecom_push_logs
|
||||
(id, task_id, project_id, push_kind, main_group_count,
|
||||
koc_userids, koc_ok_count, koc_fail_list, group_push_id, detail)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
`wpl-${crypto.randomUUID().slice(0, 12)}`,
|
||||
taskId || params.cardTaskId,
|
||||
"",
|
||||
"card_ack",
|
||||
0,
|
||||
"[]",
|
||||
0,
|
||||
"[]",
|
||||
"",
|
||||
JSON.stringify({
|
||||
cardTaskId: params.cardTaskId,
|
||||
btnKey: params.btnKey,
|
||||
operator: params.operator,
|
||||
}),
|
||||
)
|
||||
.run();
|
||||
}
|
||||
|
||||
export async function oneClickPushTask(
|
||||
db: DatabaseClient,
|
||||
params: {
|
||||
taskId: unknown;
|
||||
sendMainGroup?: unknown;
|
||||
sendKoc?: unknown;
|
||||
createGroupTemplate?: unknown;
|
||||
selectedKocPartnerIds?: unknown;
|
||||
force?: unknown;
|
||||
text?: unknown;
|
||||
},
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<OneClickPushOutcome> {
|
||||
const taskId = text(params.taskId);
|
||||
if (!taskId) throw new OneClickPushError("缺少 taskId");
|
||||
|
||||
const sendMainGroup = params.sendMainGroup !== false;
|
||||
const sendKoc = params.sendKoc !== false;
|
||||
const createGroupTemplate = params.createGroupTemplate === true;
|
||||
if (!sendMainGroup && !sendKoc && !createGroupTemplate) {
|
||||
throw new OneClickPushError("请至少选择一个推送目标");
|
||||
}
|
||||
|
||||
const task = await db
|
||||
.prepare(
|
||||
`SELECT id, name, brand, quantity, due_at, task_type, platform,
|
||||
content_format, share_token, project_id
|
||||
FROM tasks WHERE id = ?`,
|
||||
)
|
||||
.bind(taskId)
|
||||
.first<TaskPushRow & { project_id: string }>();
|
||||
if (!task) throw new OneClickPushError("任务不存在", 404);
|
||||
if (!text(task.share_token)) {
|
||||
throw new OneClickPushError("任务尚未生成领取链接,请先开放领取", 400);
|
||||
}
|
||||
|
||||
if (params.force !== true) {
|
||||
const existing = await findTodayTaskPushLog(db, taskId, "task_open");
|
||||
if (existing) {
|
||||
throw new OneClickPushError(
|
||||
"今天已推送过该任务;如确需再次推送,请勾选「仍要推送」",
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const skippedReasons: string[] = [];
|
||||
const wantsProjectTargets = sendMainGroup || createGroupTemplate;
|
||||
let projectOutcome: ProjectPushOutcome | null = null;
|
||||
if (wantsProjectTargets) {
|
||||
if (!text(task.project_id)) {
|
||||
skippedReasons.push("任务未挂项目,已跳过项目总群与任务群");
|
||||
} else {
|
||||
projectOutcome = await pushProjectTask(
|
||||
db,
|
||||
{
|
||||
taskId,
|
||||
sendMainGroup,
|
||||
sendGroupChats: createGroupTemplate,
|
||||
text: params.text,
|
||||
},
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
skippedReasons.push(...projectOutcome.skippedReasons);
|
||||
}
|
||||
}
|
||||
|
||||
const portalUrl = text(getRuntimeEnv().KOC_PORTAL_URL);
|
||||
const linkUrl = task.share_token
|
||||
? `${portalUrl.replace(/\/$/, "")}/?task=${task.share_token}`
|
||||
: "";
|
||||
|
||||
const kocResults: KocPushResult[] = [];
|
||||
if (sendKoc) {
|
||||
const bound = await listBoundWecomPartners(db);
|
||||
const selected = Array.isArray(params.selectedKocPartnerIds)
|
||||
? params.selectedKocPartnerIds.map((id) => text(id)).filter(Boolean)
|
||||
: null;
|
||||
const targets = selected
|
||||
? bound.filter((partner) => selected.includes(partner.id))
|
||||
: bound;
|
||||
if (targets.length === 0) {
|
||||
skippedReasons.push("没有可直达的合作方(未勾选或均未绑定企微身份)");
|
||||
} else {
|
||||
const message = buildKocDirectMessage(task, portalUrl);
|
||||
for (const partner of targets) {
|
||||
try {
|
||||
const sent = await sendWecomAppMessage(
|
||||
[partner.wecomExternalUserId],
|
||||
message,
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
const failed = sent.sent === 0;
|
||||
kocResults.push({
|
||||
partnerId: partner.id,
|
||||
partnerName: partner.name,
|
||||
externalUserId: partner.wecomExternalUserId,
|
||||
ok: !failed,
|
||||
error: failed ? "企业微信未送达(invaliduser)" : "",
|
||||
});
|
||||
} catch (error) {
|
||||
kocResults.push({
|
||||
partnerId: partner.id,
|
||||
partnerName: partner.name,
|
||||
externalUserId: partner.wecomExternalUserId,
|
||||
ok: false,
|
||||
error: error instanceof Error ? error.message : "发送失败",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const kocSent = kocResults.filter((item) => item.ok).length;
|
||||
const kocFailed = kocResults.length - kocSent;
|
||||
const logId = `wpl-${crypto.randomUUID().slice(0, 12)}`;
|
||||
const groupPushId =
|
||||
projectOutcome?.groupResults.map((item) => item.msgid).join(",") ?? "";
|
||||
|
||||
await db
|
||||
.prepare(
|
||||
`INSERT INTO wecom_push_logs
|
||||
(id, task_id, project_id, push_kind, main_group_count,
|
||||
koc_userids, koc_ok_count, koc_fail_list, group_push_id, detail)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
logId,
|
||||
taskId,
|
||||
text(task.project_id),
|
||||
"task_open",
|
||||
projectOutcome ? projectOutcome.appResults.length : 0,
|
||||
JSON.stringify(
|
||||
kocResults.map((item) => ({
|
||||
partnerId: item.partnerId,
|
||||
name: item.partnerName,
|
||||
externalUserId: item.externalUserId,
|
||||
ok: item.ok,
|
||||
error: item.error,
|
||||
})),
|
||||
),
|
||||
kocSent,
|
||||
JSON.stringify(kocResults.filter((item) => !item.ok)),
|
||||
groupPushId,
|
||||
JSON.stringify({
|
||||
skippedReasons,
|
||||
createGroupTemplate,
|
||||
linkUrl,
|
||||
}),
|
||||
)
|
||||
.run();
|
||||
|
||||
return {
|
||||
linkUrl,
|
||||
projectOutcome,
|
||||
kocResults,
|
||||
kocSent,
|
||||
kocFailed,
|
||||
skippedReasons,
|
||||
logId,
|
||||
};
|
||||
}
|
||||
94
lib/task-report-csv.ts
Normal file
94
lib/task-report-csv.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import type { TaskReportRow } from "./mvp-db";
|
||||
|
||||
const CSV_HEADERS = [
|
||||
"任务ID",
|
||||
"任务名称",
|
||||
"任务类型",
|
||||
"品牌",
|
||||
"平台",
|
||||
"所属项目",
|
||||
"任务状态",
|
||||
"计划数量",
|
||||
"领取数",
|
||||
"发布数",
|
||||
"完成数",
|
||||
"完成率",
|
||||
"截止日期",
|
||||
"创建时间",
|
||||
"曝光量合计",
|
||||
"阅读量合计",
|
||||
"D2点赞",
|
||||
"D2评论",
|
||||
"D2收藏",
|
||||
"D5点赞",
|
||||
"D5评论",
|
||||
"D5收藏",
|
||||
"D7点赞",
|
||||
"D7评论",
|
||||
"D7收藏",
|
||||
"最新点赞",
|
||||
"最新评论",
|
||||
"最新收藏",
|
||||
"最新转发",
|
||||
];
|
||||
|
||||
function taskTypeLabel(value: string) {
|
||||
return value === "screenshot_collect" ? "截图采集" : "内容发布";
|
||||
}
|
||||
|
||||
function taskStatusLabel(value: string) {
|
||||
return value === "active" ? "进行中" : value === "completed" ? "已完结" : value;
|
||||
}
|
||||
|
||||
function completionRate(row: TaskReportRow) {
|
||||
if (!row.claimed_count) return "";
|
||||
return `${Math.round((row.completed_count / row.claimed_count) * 100)}%`;
|
||||
}
|
||||
|
||||
function csvCell(value: string | number | null | undefined) {
|
||||
const text = value === null || value === undefined ? "" : String(value);
|
||||
if (/[",\r\n]/.test(text)) return `"${text.replaceAll('"', '""')}"`;
|
||||
return text;
|
||||
}
|
||||
|
||||
export function buildTaskReportCsv(rows: TaskReportRow[]) {
|
||||
const lines = [CSV_HEADERS.join(",")];
|
||||
for (const row of rows) {
|
||||
lines.push(
|
||||
[
|
||||
row.id,
|
||||
row.name,
|
||||
taskTypeLabel(row.task_type),
|
||||
row.brand,
|
||||
row.platform,
|
||||
row.project_name ?? "",
|
||||
taskStatusLabel(row.status),
|
||||
row.quantity,
|
||||
row.claimed_count,
|
||||
row.published_count,
|
||||
row.completed_count,
|
||||
completionRate(row),
|
||||
row.due_at,
|
||||
row.created_at,
|
||||
row.exposure_total,
|
||||
row.views_total,
|
||||
row.d2_likes,
|
||||
row.d2_comments,
|
||||
row.d2_collects,
|
||||
row.d5_likes,
|
||||
row.d5_comments,
|
||||
row.d5_collects,
|
||||
row.d7_likes,
|
||||
row.d7_comments,
|
||||
row.d7_collects,
|
||||
row.latest_likes,
|
||||
row.latest_comments,
|
||||
row.latest_collects,
|
||||
row.latest_shares,
|
||||
]
|
||||
.map(csvCell)
|
||||
.join(","),
|
||||
);
|
||||
}
|
||||
return `\uFEFF${lines.join("\r\n")}`;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export type CreateDistributionTaskInput = {
|
||||
dueAt: string;
|
||||
platform?: "小红书" | "抖音";
|
||||
contentFormat?: "image_text" | "video";
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
export type CreateScreenshotTaskInput = {
|
||||
@@ -22,6 +23,7 @@ export type CreateScreenshotTaskInput = {
|
||||
instructions: string;
|
||||
quantity: number;
|
||||
exampleImageKey?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
export type DistributionTaskCreation = {
|
||||
@@ -140,10 +142,10 @@ async function insertTaskFromSource(
|
||||
.prepare(
|
||||
`INSERT INTO tasks
|
||||
(id, name, brand, quantity, claimed_quantity, due_at, status,
|
||||
platform, content_format,
|
||||
platform, content_format, project_id,
|
||||
source_url, source_sheet_id, source_sheet_name, source_synced_at,
|
||||
share_token)
|
||||
VALUES (?, ?, ?, ?, 0, ?, 'importing', ?, ?, ?, ?, ?, ?, ?)`,
|
||||
VALUES (?, ?, ?, ?, 0, ?, 'importing', ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
)
|
||||
.bind(
|
||||
taskId,
|
||||
@@ -153,6 +155,7 @@ async function insertTaskFromSource(
|
||||
input.dueAt,
|
||||
input.platform ?? "小红书",
|
||||
input.contentFormat ?? "image_text",
|
||||
input.projectId,
|
||||
source.url,
|
||||
source.sheetId,
|
||||
source.sheetName,
|
||||
@@ -220,6 +223,7 @@ export async function createDistributionTask(
|
||||
dueAt: normalizedDueDate(rawInput.dueAt),
|
||||
platform: rawInput.platform === "抖音" ? "抖音" : "小红书",
|
||||
contentFormat: rawInput.contentFormat === "video" ? "video" : "image_text",
|
||||
projectId: normalizedValue(rawInput.projectId ?? ""),
|
||||
};
|
||||
if (!input.feishuUrl || !input.name || !input.brand) {
|
||||
throw new Error("请补全飞书链接、任务名称和品牌/项目");
|
||||
@@ -281,6 +285,7 @@ export async function createScreenshotTask(
|
||||
instructions: normalizedValue(rawInput.instructions),
|
||||
quantity: Math.floor(Number(rawInput.quantity)),
|
||||
exampleImageKey: normalizedValue(rawInput.exampleImageKey ?? ""),
|
||||
projectId: normalizedValue(rawInput.projectId ?? ""),
|
||||
};
|
||||
if (!input.name || !input.brand || !input.keyword || !input.instructions) {
|
||||
throw new Error("请补全任务名称、品牌/项目、搜索关键词和任务说明");
|
||||
@@ -304,9 +309,9 @@ export async function createScreenshotTask(
|
||||
.prepare(
|
||||
`INSERT INTO tasks
|
||||
(id, name, brand, quantity, claimed_quantity, due_at, status,
|
||||
task_type, source_url, source_sheet_id, source_sheet_name,
|
||||
task_type, project_id, source_url, source_sheet_id, source_sheet_name,
|
||||
share_token, collection_days)
|
||||
VALUES (?, ?, ?, ?, 0, ?, 'active', 'screenshot_collect', '', '', '', ?, '[]')`,
|
||||
VALUES (?, ?, ?, ?, 0, ?, 'active', 'screenshot_collect', ?, '', '', '', ?, '[]')`,
|
||||
)
|
||||
.bind(
|
||||
taskId,
|
||||
@@ -314,6 +319,7 @@ export async function createScreenshotTask(
|
||||
input.brand,
|
||||
input.quantity,
|
||||
input.dueAt,
|
||||
input.projectId,
|
||||
shareToken,
|
||||
)
|
||||
.run();
|
||||
|
||||
97
lib/wecom-callback-crypto.ts
Normal file
97
lib/wecom-callback-crypto.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHash,
|
||||
randomBytes,
|
||||
timingSafeEqual,
|
||||
} from "node:crypto";
|
||||
|
||||
export class WecomCallbackCryptoError extends Error {
|
||||
status: number;
|
||||
|
||||
constructor(message: string, status = 400) {
|
||||
super(message);
|
||||
this.name = "WecomCallbackCryptoError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveWecomCallbackAesKey(encodingAesKey: string): Buffer {
|
||||
const key = String(encodingAesKey ?? "").trim();
|
||||
if (!/^[A-Za-z0-9]{43}$/.test(key)) {
|
||||
throw new WecomCallbackCryptoError(
|
||||
"企业微信回调 EncodingAESKey 非法(需 43 位字母数字)",
|
||||
500,
|
||||
);
|
||||
}
|
||||
return Buffer.from(`${key}=`, "base64");
|
||||
}
|
||||
|
||||
export function verifyWecomCallbackSignature(
|
||||
token: string,
|
||||
timestamp: string,
|
||||
nonce: string,
|
||||
encrypt: string,
|
||||
): string {
|
||||
return createHash("sha1")
|
||||
.update([token, timestamp, nonce, encrypt].sort().join(""))
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export function wecomSignaturesMatch(
|
||||
expected: string,
|
||||
received: string,
|
||||
): boolean {
|
||||
const a = Buffer.from(String(expected ?? ""));
|
||||
const b = Buffer.from(String(received ?? ""));
|
||||
if (a.length !== b.length || a.length === 0) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
export function encryptWecomCallback(
|
||||
plainMessage: string,
|
||||
receiveId: string,
|
||||
encodingAesKey: string,
|
||||
): string {
|
||||
const key = resolveWecomCallbackAesKey(encodingAesKey);
|
||||
const random = randomBytes(16);
|
||||
const message = Buffer.from(String(plainMessage ?? ""), "utf8");
|
||||
const receive = Buffer.from(String(receiveId ?? ""), "utf8");
|
||||
const length = Buffer.alloc(4);
|
||||
length.writeUInt32BE(message.length, 0);
|
||||
const cipher = createCipheriv("aes-256-cbc", key, key.subarray(0, 16));
|
||||
const encrypted = Buffer.concat([
|
||||
cipher.update(Buffer.concat([random, length, message, receive])),
|
||||
cipher.final(),
|
||||
]);
|
||||
return encrypted.toString("base64");
|
||||
}
|
||||
|
||||
export function decryptWecomCallback(
|
||||
encrypted: string,
|
||||
encodingAesKey: string,
|
||||
): { message: string; receiveId: string } {
|
||||
const key = resolveWecomCallbackAesKey(encodingAesKey);
|
||||
const data = Buffer.from(String(encrypted ?? "").trim(), "base64");
|
||||
if (data.length === 0 || data.length % 16 !== 0) {
|
||||
throw new WecomCallbackCryptoError("企业微信回调密文长度非法");
|
||||
}
|
||||
let raw: Buffer;
|
||||
try {
|
||||
const decipher = createDecipheriv("aes-256-cbc", key, key.subarray(0, 16));
|
||||
raw = Buffer.concat([decipher.update(data), decipher.final()]);
|
||||
} catch {
|
||||
throw new WecomCallbackCryptoError("企业微信回调密文解密失败");
|
||||
}
|
||||
if (raw.length < 20) {
|
||||
throw new WecomCallbackCryptoError("企业微信回调明文长度非法");
|
||||
}
|
||||
const messageLength = raw.readUInt32BE(16);
|
||||
if (messageLength <= 0 || 20 + messageLength > raw.length) {
|
||||
throw new WecomCallbackCryptoError("企业微信回调消息长度字段非法");
|
||||
}
|
||||
return {
|
||||
message: raw.subarray(20, 20 + messageLength).toString("utf8"),
|
||||
receiveId: raw.subarray(20 + messageLength).toString("utf8"),
|
||||
};
|
||||
}
|
||||
56
lib/wecom-callback-events.ts
Normal file
56
lib/wecom-callback-events.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
import { recordCardAck } from "./task-one-click-push-service";
|
||||
|
||||
export type WecomCallbackFields = Record<string, string>;
|
||||
|
||||
export type WecomCallbackEventResult = {
|
||||
recognized: boolean;
|
||||
action: string;
|
||||
taskId: string;
|
||||
btnKey: string;
|
||||
operator: string;
|
||||
};
|
||||
|
||||
export function parseWecomCallbackXml(xml: string): WecomCallbackFields {
|
||||
const fields: WecomCallbackFields = {};
|
||||
const source = String(xml ?? "");
|
||||
const pattern =
|
||||
/<([A-Za-z][A-Za-z0-9_]*)>(?:<!\[CDATA\[([\s\S]*?)\]\]>|([^<]*))<\/\1>/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = pattern.exec(source)) !== null) {
|
||||
const tag = match[1];
|
||||
const value = match[2] ?? match[3] ?? "";
|
||||
if (!(tag in fields)) fields[tag] = value.trim();
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
export function extractWecomEncryptField(body: string): string {
|
||||
const fields = parseWecomCallbackXml(body);
|
||||
return fields.Encrypt ?? "";
|
||||
}
|
||||
|
||||
export async function handleWecomCallbackEvent(
|
||||
db: DatabaseClient,
|
||||
fields: WecomCallbackFields,
|
||||
): Promise<WecomCallbackEventResult> {
|
||||
const event = fields.Event ?? "";
|
||||
const taskId = fields.TaskId ?? "";
|
||||
const btnKey = fields.BtnKey ?? "";
|
||||
const operator = fields.FromUserName ?? "";
|
||||
|
||||
if (fields.MsgType === "event" && event === "template_card_event") {
|
||||
if (btnKey === "mark_handled") {
|
||||
await recordCardAck(db, { cardTaskId: taskId, btnKey, operator });
|
||||
console.info("[KOC LOOP] wecom card ack recorded", { taskId, operator });
|
||||
return { recognized: true, action: "card_ack", taskId, btnKey, operator };
|
||||
}
|
||||
return { recognized: true, action: "ignored", taskId, btnKey, operator };
|
||||
}
|
||||
|
||||
console.info("[KOC LOOP] wecom callback event ignored", {
|
||||
msgType: fields.MsgType ?? "",
|
||||
event,
|
||||
});
|
||||
return { recognized: false, action: "ignored", taskId, btnKey, operator };
|
||||
}
|
||||
@@ -25,6 +25,7 @@ type WecomEnvelope = {
|
||||
access_token?: string;
|
||||
expires_in?: number;
|
||||
invaliduser?: string;
|
||||
userid?: string;
|
||||
follow_user?: Array<{ userid: string }>;
|
||||
external_userid?: string[];
|
||||
external_contact?: {
|
||||
@@ -243,6 +244,87 @@ export function clearWecomAccessTokenCacheForTests() {
|
||||
cachedAccessToken = null;
|
||||
}
|
||||
|
||||
export type WecomTemplateCardButton = {
|
||||
key: string;
|
||||
name: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
export async function sendWecomTemplateCard(
|
||||
config: WecomConfig,
|
||||
params: {
|
||||
touser: string[];
|
||||
taskId: string;
|
||||
title: string;
|
||||
description: string;
|
||||
url: string;
|
||||
buttons: WecomTemplateCardButton[];
|
||||
},
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<{ sent: number; failed: number; skipped: boolean }> {
|
||||
const normalized = params.touser
|
||||
.map((id) => bindingValue(id))
|
||||
.filter((id) => id.length > 0);
|
||||
if (normalized.length === 0) {
|
||||
return { sent: 0, failed: 0, skipped: true };
|
||||
}
|
||||
if (!hasAppCredentials(config)) {
|
||||
return { sent: 0, failed: 0, skipped: true };
|
||||
}
|
||||
const taskId = bindingValue(params.taskId);
|
||||
if (!taskId) {
|
||||
throw new WecomClientError("模板卡片缺少 task_id(回调识别用)", 400);
|
||||
}
|
||||
const token = await fetchAccessToken(config, fetchImpl);
|
||||
const url = `${WECOM_API_ORIGIN}/cgi-bin/message/send?access_token=${encodeURIComponent(token)}`;
|
||||
const response = await fetchImpl(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify({
|
||||
touser: normalized.join("|"),
|
||||
msgtype: "template_card",
|
||||
agentid: Number(config.agentId),
|
||||
template_card: {
|
||||
card_type: "text_notice",
|
||||
source: {
|
||||
desc: "KOC LOOP",
|
||||
desc_color: 0,
|
||||
},
|
||||
main_title: {
|
||||
title: safeMessage(params.title),
|
||||
desc: safeMessage(params.description).slice(0, 120),
|
||||
},
|
||||
card_action: {
|
||||
type: 1,
|
||||
url: bindingValue(params.url),
|
||||
},
|
||||
button_list: params.buttons.map((button) => ({
|
||||
type: button.url ? 1 : 0,
|
||||
text: safeMessage(button.name),
|
||||
key: bindingValue(button.key),
|
||||
...(button.url ? { url: button.url } : {}),
|
||||
})),
|
||||
task_id: taskId,
|
||||
},
|
||||
}),
|
||||
signal: AbortSignal.timeout(12_000),
|
||||
});
|
||||
const payload = await readEnvelope(response, "企业微信模板卡片推送失败");
|
||||
if (!response.ok) {
|
||||
throw new WecomClientError(
|
||||
`企业微信模板卡片推送失败(HTTP ${response.status})`,
|
||||
502,
|
||||
);
|
||||
}
|
||||
ensureOk(payload, "企业微信模板卡片推送失败");
|
||||
const invalid = bindingValue(payload.invaliduser).split("|").filter(Boolean);
|
||||
return {
|
||||
sent: Math.max(0, normalized.length - invalid.length),
|
||||
failed: invalid.length,
|
||||
skipped: false,
|
||||
};
|
||||
}
|
||||
|
||||
export type WecomGroupChat = {
|
||||
chatId: string;
|
||||
name: string;
|
||||
@@ -458,3 +540,98 @@ export async function listExternalContacts(
|
||||
}
|
||||
return contacts;
|
||||
}
|
||||
|
||||
export function buildWecomOAuthUrl(params: {
|
||||
corpId: string;
|
||||
agentId: string;
|
||||
redirectUri: string;
|
||||
state: string;
|
||||
}): string {
|
||||
const query = new URLSearchParams({
|
||||
appid: params.corpId,
|
||||
redirect_uri: params.redirectUri,
|
||||
response_type: "code",
|
||||
scope: "snsapi_base",
|
||||
state: params.state,
|
||||
agentid: params.agentId,
|
||||
});
|
||||
return `https://open.weixin.qq.com/connect/oauth2/authorize?${query.toString()}#wechat_redirect`;
|
||||
}
|
||||
|
||||
export type WecomOAuthIdentity = {
|
||||
userId?: string;
|
||||
externalUserId?: string;
|
||||
};
|
||||
|
||||
export async function exchangeWecomOAuthCode(
|
||||
config: WecomConfig,
|
||||
code: string,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<WecomOAuthIdentity> {
|
||||
if (!hasAppCredentials(config)) {
|
||||
throw new WecomClientError(
|
||||
"企业微信自建应用未配置(WECOM_CORP_ID / WECOM_AGENT_ID / WECOM_SECRET)",
|
||||
400,
|
||||
);
|
||||
}
|
||||
const authorizationCode = bindingValue(code);
|
||||
if (!authorizationCode) {
|
||||
throw new WecomClientError("缺少企业微信授权 code", 400);
|
||||
}
|
||||
const token = await fetchAccessToken(config, fetchImpl);
|
||||
const url = `${WECOM_API_ORIGIN}/cgi-bin/auth/getuserinfo?access_token=${encodeURIComponent(token)}`;
|
||||
const response = await fetchImpl(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json; charset=utf-8" },
|
||||
body: JSON.stringify({ code: authorizationCode }),
|
||||
signal: AbortSignal.timeout(12_000),
|
||||
});
|
||||
const payload = await readEnvelope(response, "企业微信授权身份换取失败");
|
||||
if (!response.ok) {
|
||||
throw new WecomClientError(
|
||||
`企业微信授权身份换取失败(HTTP ${response.status})`,
|
||||
502,
|
||||
);
|
||||
}
|
||||
if (Number(payload.errcode ?? 0) === 40029) {
|
||||
throw new WecomClientError("企业微信授权 code 无效或已过期", 400);
|
||||
}
|
||||
ensureOk(payload, "企业微信授权身份换取失败");
|
||||
const userId = bindingValue(payload.userid);
|
||||
const externalUserId =
|
||||
typeof payload.external_userid === "string"
|
||||
? bindingValue(payload.external_userid)
|
||||
: "";
|
||||
if (!userId && !externalUserId) {
|
||||
throw new WecomClientError("企业微信未返回有效身份", 400);
|
||||
}
|
||||
return {
|
||||
...(userId ? { userId } : {}),
|
||||
...(externalUserId ? { externalUserId } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchWecomExternalContactName(
|
||||
config: WecomConfig,
|
||||
externalUserId: string,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<string | null> {
|
||||
if (!hasAppCredentials(config)) return null;
|
||||
const externalId = bindingValue(externalUserId);
|
||||
if (!externalId) return null;
|
||||
try {
|
||||
const token = await fetchAccessToken(config, fetchImpl);
|
||||
const url = `${WECOM_API_ORIGIN}/cgi-bin/externalcontact/get?access_token=${encodeURIComponent(token)}&external_userid=${encodeURIComponent(externalId)}`;
|
||||
const response = await fetchImpl(url, {
|
||||
method: "GET",
|
||||
signal: AbortSignal.timeout(12_000),
|
||||
});
|
||||
const payload = await readEnvelope(response, "获取外部联系人详情失败");
|
||||
if (!response.ok) return null;
|
||||
if (Number(payload.errcode ?? 0) !== 0) return null;
|
||||
const name = bindingValue(payload.external_contact?.name);
|
||||
return name || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
107
lib/wecom-feedback-service.ts
Normal file
107
lib/wecom-feedback-service.ts
Normal file
@@ -0,0 +1,107 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
import { getRuntimeEnv, isEnabled } from "./runtime-env";
|
||||
import { sendWecomRobotMessage, type WecomConfig } from "./wecom-client";
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
export function isWecomFeedbackEnabled() {
|
||||
return isEnabled(getRuntimeEnv().WECOM_FEEDBACK_ENABLED, false);
|
||||
}
|
||||
|
||||
type SubmittedRow = {
|
||||
claimant_name: string | null;
|
||||
partner_name: string | null;
|
||||
task_name: string;
|
||||
content_title: string | null;
|
||||
publish_url: string | null;
|
||||
};
|
||||
|
||||
function truncate(value: string, max: number) {
|
||||
return value.length > max ? `${value.slice(0, max)}…` : value;
|
||||
}
|
||||
|
||||
export function buildPublishSubmittedMessage(
|
||||
row: SubmittedRow,
|
||||
kind: "publish" | "screenshot",
|
||||
): string {
|
||||
const partner = row.partner_name || row.claimant_name || "未知合作方";
|
||||
if (kind === "screenshot") {
|
||||
return [
|
||||
"【KOC 已提交截图】",
|
||||
`合作方:${partner}`,
|
||||
`任务:${truncate(row.task_name, 24)}`,
|
||||
`内容:${truncate(row.content_title ?? "", 24)}`,
|
||||
"请到后台「数据回收」页查看与审核。",
|
||||
].join("\n");
|
||||
}
|
||||
return [
|
||||
"【KOC 已提交发布】",
|
||||
`合作方:${partner}`,
|
||||
`任务:${truncate(row.task_name, 24)}`,
|
||||
`内容:${truncate(row.content_title ?? "", 24)}`,
|
||||
`链接:${row.publish_url ?? ""}`,
|
||||
"链接已入库,采集计划将按日自动执行。",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export async function notifyPartnerSubmitted(
|
||||
db: DatabaseClient,
|
||||
params: { distributionId: string; kind: "publish" | "screenshot" },
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<boolean> {
|
||||
if (!config.robotWebhook) return false;
|
||||
const distributionId = String(params.distributionId ?? "").trim();
|
||||
if (!distributionId) return false;
|
||||
const row = await db
|
||||
.prepare(
|
||||
`SELECT d.claimant_name, d.publish_url, t.name AS task_name,
|
||||
c.title AS content_title, p.name AS partner_name
|
||||
FROM distributions d
|
||||
JOIN tasks t ON t.id = d.task_id
|
||||
LEFT JOIN contents c ON c.id = d.content_id
|
||||
LEFT JOIN partners p ON p.id = d.partner_id
|
||||
WHERE d.id = ?`,
|
||||
)
|
||||
.bind(distributionId)
|
||||
.first<SubmittedRow>();
|
||||
if (!row) return false;
|
||||
const message = buildPublishSubmittedMessage(row, params.kind);
|
||||
await sendWecomRobotMessage(message, config, fetchImpl);
|
||||
return true;
|
||||
}
|
||||
|
||||
export function buildCollectionFinishedMessage(summary: {
|
||||
currentDate: string;
|
||||
dueTasks: number;
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
}): string {
|
||||
const lines = [
|
||||
`【数据采集日报】${summary.currentDate}`,
|
||||
`应采集任务 ${summary.dueTasks} 个,执行 ${summary.attempted} 条:成功 ${summary.succeeded}、失败 ${summary.failed}。`,
|
||||
];
|
||||
if (summary.failed > 0) {
|
||||
lines.push("有采集失败,请到后台「数据回收」页查看并重试。");
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export async function notifyCollectionFinished(
|
||||
summary: {
|
||||
currentDate: string;
|
||||
dueTasks: number;
|
||||
attempted: number;
|
||||
succeeded: number;
|
||||
failed: number;
|
||||
},
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
): Promise<boolean> {
|
||||
if (!config.robotWebhook) return false;
|
||||
if (summary.attempted <= 0 && summary.failed <= 0) return false;
|
||||
const message = buildCollectionFinishedMessage(summary);
|
||||
await sendWecomRobotMessage(message, config, fetchImpl);
|
||||
return true;
|
||||
}
|
||||
@@ -3,9 +3,11 @@ import { shanghaiDateFromTimestamp } from "./collection-service";
|
||||
import {
|
||||
sendWecomAppMessage,
|
||||
sendWecomRobotMessage,
|
||||
sendWecomTemplateCard,
|
||||
type WecomConfig,
|
||||
} from "./wecom-client";
|
||||
import { getRuntimeEnv } from "./runtime-env";
|
||||
import { releaseUnfinishedDistribution } from "./distribution-release-service";
|
||||
|
||||
type FetchLike = typeof fetch;
|
||||
|
||||
@@ -162,6 +164,227 @@ function bindingValue(value: unknown) {
|
||||
return String(value ?? "").trim();
|
||||
}
|
||||
|
||||
export function resolveAutoReleaseDays(value: string | undefined) {
|
||||
const parsed = Number(String(value ?? "").trim());
|
||||
if (!Number.isFinite(parsed) || parsed < 1) return 0;
|
||||
return Math.min(90, Math.floor(parsed));
|
||||
}
|
||||
|
||||
type OverdueRow = {
|
||||
id: string;
|
||||
task_id: string;
|
||||
task_name: string;
|
||||
due_at: string;
|
||||
project_id: string;
|
||||
partner_id: string;
|
||||
partner_name: string;
|
||||
};
|
||||
|
||||
export type OverdueEscalationSummary = {
|
||||
overdueTasks: number;
|
||||
overdueDistributions: number;
|
||||
robotSent: boolean;
|
||||
cardSent: number;
|
||||
cardFailed: number;
|
||||
};
|
||||
|
||||
async function queryOverdueUnpublished(
|
||||
db: DatabaseClient,
|
||||
cutoff: string,
|
||||
): Promise<OverdueRow[]> {
|
||||
const result = await db
|
||||
.prepare(
|
||||
`SELECT d.id, t.id AS task_id, t.name AS task_name, t.due_at,
|
||||
t.project_id, p.id AS partner_id, p.name AS partner_name
|
||||
FROM distributions d
|
||||
JOIN tasks t ON t.id = d.task_id
|
||||
JOIN partners p ON p.id = d.partner_id
|
||||
WHERE (d.publish_url IS NULL OR d.publish_url = '')
|
||||
AND t.due_at IS NOT NULL AND t.due_at != ''
|
||||
AND t.due_at < ?
|
||||
ORDER BY t.due_at ASC, t.name ASC`,
|
||||
)
|
||||
.bind(cutoff)
|
||||
.all<OverdueRow>();
|
||||
return result.results;
|
||||
}
|
||||
|
||||
export async function runOverdueEscalation(
|
||||
db: DatabaseClient,
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
now: number = Date.now(),
|
||||
): Promise<OverdueEscalationSummary> {
|
||||
const today = shanghaiDateFromTimestamp(now);
|
||||
const rows = await queryOverdueUnpublished(db, today);
|
||||
|
||||
const byTask = new Map<
|
||||
string,
|
||||
{ taskName: string; dueAt: string; projectId: string; count: number; partners: Set<string> }
|
||||
>();
|
||||
for (const row of rows) {
|
||||
const entry = byTask.get(row.task_id) ?? {
|
||||
taskName: row.task_name,
|
||||
dueAt: row.due_at,
|
||||
projectId: bindingValue(row.project_id),
|
||||
count: 0,
|
||||
partners: new Set<string>(),
|
||||
};
|
||||
entry.count += 1;
|
||||
entry.partners.add(row.partner_name || row.partner_id);
|
||||
byTask.set(row.task_id, entry);
|
||||
}
|
||||
|
||||
const summary: OverdueEscalationSummary = {
|
||||
overdueTasks: byTask.size,
|
||||
overdueDistributions: rows.length,
|
||||
robotSent: false,
|
||||
cardSent: 0,
|
||||
cardFailed: 0,
|
||||
};
|
||||
|
||||
if (rows.length === 0) return summary;
|
||||
|
||||
if (config.robotWebhook) {
|
||||
const lines = [...byTask.values()].map((entry) => {
|
||||
const partners = [...entry.partners].slice(0, 5).join("、");
|
||||
const overflow = entry.partners.size > 5 ? ` 等 ${entry.partners.size} 位` : "";
|
||||
return `· ${truncate(entry.taskName, 24)}(截止 ${entry.dueAt}):${entry.count} 条超期未发布 — ${partners}${overflow}`;
|
||||
});
|
||||
try {
|
||||
await sendWecomRobotMessage(
|
||||
`【超期未发布升级】${today}\n${lines.join("\n")}\n请运营跟进催办或释放。`,
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
summary.robotSent = true;
|
||||
} catch (error) {
|
||||
console.warn("[KOC LOOP] overdue escalation robot failed", {
|
||||
error: safeError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const env = getRuntimeEnv();
|
||||
const cardUrl = bindingValue(env.APP_ORIGIN) || bindingValue(env.KOC_PORTAL_URL);
|
||||
for (const [taskId, entry] of byTask) {
|
||||
if (!entry.projectId) continue;
|
||||
try {
|
||||
const project = await db
|
||||
.prepare("SELECT main_group_member_ids FROM projects WHERE id = ?")
|
||||
.bind(entry.projectId)
|
||||
.first<{ main_group_member_ids: string }>();
|
||||
const members = safeParseIdList(project?.main_group_member_ids);
|
||||
if (members.length === 0) continue;
|
||||
const sent = await sendWecomTemplateCard(
|
||||
config,
|
||||
{
|
||||
touser: members,
|
||||
taskId: `task:${taskId}:due`,
|
||||
title: `超期催办:${truncate(entry.taskName, 20)}`,
|
||||
description: `${entry.count} 条内容超期未发布(截止 ${entry.dueAt}),请跟进催办或释放`,
|
||||
url: cardUrl,
|
||||
buttons: [
|
||||
{ key: "view_task", name: "查看任务", url: cardUrl },
|
||||
{ key: "mark_handled", name: "已处理" },
|
||||
],
|
||||
},
|
||||
fetchImpl,
|
||||
);
|
||||
if (!sent.skipped) {
|
||||
summary.cardSent += sent.sent;
|
||||
summary.cardFailed += sent.failed;
|
||||
}
|
||||
} catch (error) {
|
||||
summary.cardFailed += 1;
|
||||
console.warn("[KOC LOOP] overdue escalation card failed", {
|
||||
taskId,
|
||||
error: safeError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
export type AutoReleaseSummary = {
|
||||
enabled: boolean;
|
||||
days: number;
|
||||
cutoff: string;
|
||||
released: number;
|
||||
blocked: number;
|
||||
failed: number;
|
||||
robotSent: boolean;
|
||||
};
|
||||
|
||||
export async function runOverdueAutoRelease(
|
||||
db: DatabaseClient,
|
||||
config: WecomConfig,
|
||||
fetchImpl: FetchLike = fetch,
|
||||
now: number = Date.now(),
|
||||
): Promise<AutoReleaseSummary> {
|
||||
const days = resolveAutoReleaseDays(getRuntimeEnv().WECOM_AUTO_RELEASE_DAYS);
|
||||
const summary: AutoReleaseSummary = {
|
||||
enabled: days > 0,
|
||||
days,
|
||||
cutoff: "",
|
||||
released: 0,
|
||||
blocked: 0,
|
||||
failed: 0,
|
||||
robotSent: false,
|
||||
};
|
||||
if (days <= 0) return summary;
|
||||
|
||||
const today = shanghaiDateFromTimestamp(now);
|
||||
summary.cutoff = computeDueCutoff(today, -days);
|
||||
const rows = await queryOverdueUnpublished(db, summary.cutoff);
|
||||
|
||||
for (const row of rows) {
|
||||
try {
|
||||
await releaseUnfinishedDistribution(db, row.id);
|
||||
summary.released += 1;
|
||||
} catch (error) {
|
||||
const status = (error as { status?: number }).status;
|
||||
if (status === 409) {
|
||||
summary.blocked += 1;
|
||||
} else {
|
||||
summary.failed += 1;
|
||||
console.warn("[KOC LOOP] auto release failed", {
|
||||
distributionId: row.id,
|
||||
error: safeError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (summary.released > 0 && config.robotWebhook) {
|
||||
try {
|
||||
await sendWecomRobotMessage(
|
||||
`【超期自动释放】截止 ${summary.cutoff} 前仍未发布的内容已释放 ${summary.released} 条回库存(跳过 ${summary.blocked} 条已提交、失败 ${summary.failed} 条),可重新领取。`,
|
||||
config,
|
||||
fetchImpl,
|
||||
);
|
||||
summary.robotSent = true;
|
||||
} catch (error) {
|
||||
console.warn("[KOC LOOP] auto release robot failed", {
|
||||
error: safeError(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
function safeParseIdList(value: string | null | undefined) {
|
||||
try {
|
||||
const parsed = JSON.parse(String(value ?? "[]"));
|
||||
if (!Array.isArray(parsed)) return [];
|
||||
return parsed.map((item) => String(item)).filter(Boolean);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(value: string, max: number) {
|
||||
return value.length > max ? `${value.slice(0, max)}…` : value;
|
||||
}
|
||||
|
||||
160
lib/wecom-oauth-service.ts
Normal file
160
lib/wecom-oauth-service.ts
Normal file
@@ -0,0 +1,160 @@
|
||||
import type { DatabaseClient } from "./database";
|
||||
import { getRuntimeEnv } from "./runtime-env";
|
||||
import { hashText } from "./mvp-db";
|
||||
|
||||
export const WECOM_IDENTITY_TTL_MS = 30 * 60 * 1_000;
|
||||
const WECOM_IDENTITY_GRACE_MS = 60 * 1_000;
|
||||
|
||||
type WecomIdentityPayload = {
|
||||
v: 1;
|
||||
ext: string;
|
||||
name: string;
|
||||
iat: number;
|
||||
exp: number;
|
||||
jti: string;
|
||||
};
|
||||
|
||||
export type WecomIdentity = {
|
||||
externalUserId: string;
|
||||
displayName: string;
|
||||
};
|
||||
|
||||
export function getWecomOAuthSecret(): string {
|
||||
const secret = String(getRuntimeEnv().ADMIN_INTERNAL_TOKEN ?? "").trim();
|
||||
if (!secret) {
|
||||
throw new Error("ADMIN_INTERNAL_TOKEN 未配置,无法签发企微身份票据");
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
function toBase64Url(bytes: Uint8Array): string {
|
||||
let binary = "";
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||||
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
||||
}
|
||||
|
||||
function fromBase64Url(value: string): Uint8Array {
|
||||
const padded = value
|
||||
.replace(/-/g, "+")
|
||||
.replace(/_/g, "/")
|
||||
.padEnd(Math.ceil(value.length / 4) * 4, "=");
|
||||
const binary = atob(padded);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
async function hmacSha256(secret: string, data: string): Promise<Uint8Array> {
|
||||
const key = await crypto.subtle.importKey(
|
||||
"raw",
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: "HMAC", hash: "SHA-256" },
|
||||
false,
|
||||
["sign"],
|
||||
);
|
||||
const signature = await crypto.subtle.sign(
|
||||
"HMAC",
|
||||
key,
|
||||
new TextEncoder().encode(data),
|
||||
);
|
||||
return new Uint8Array(signature);
|
||||
}
|
||||
|
||||
function constantTimeEquals(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
let diff = 0;
|
||||
for (let index = 0; index < a.length; index += 1) {
|
||||
diff |= a[index] ^ b[index];
|
||||
}
|
||||
return diff === 0;
|
||||
}
|
||||
|
||||
export async function signWecomIdentityTicket(
|
||||
externalUserId: string,
|
||||
displayName: string,
|
||||
options: { secret?: string; nowMs?: number; ttlMs?: number } = {},
|
||||
): Promise<{ ticket: string; expiresIn: number }> {
|
||||
const secret = options.secret ?? getWecomOAuthSecret();
|
||||
const issuedAt = options.nowMs ?? Date.now();
|
||||
const ttl = options.ttlMs ?? WECOM_IDENTITY_TTL_MS;
|
||||
const ext = String(externalUserId ?? "").trim();
|
||||
if (!ext) throw new Error("缺少企微外部联系人 ID");
|
||||
const payload: WecomIdentityPayload = {
|
||||
v: 1,
|
||||
ext,
|
||||
name: String(displayName ?? "").trim().slice(0, 120),
|
||||
iat: issuedAt,
|
||||
exp: issuedAt + ttl,
|
||||
jti: toBase64Url(crypto.getRandomValues(new Uint8Array(12))),
|
||||
};
|
||||
const payloadSegment = toBase64Url(
|
||||
new TextEncoder().encode(JSON.stringify(payload)),
|
||||
);
|
||||
const signature = await hmacSha256(secret, payloadSegment);
|
||||
return {
|
||||
ticket: `${payloadSegment}.${toBase64Url(signature)}`,
|
||||
expiresIn: Math.floor(ttl / 1_000),
|
||||
};
|
||||
}
|
||||
|
||||
export async function verifyWecomIdentityTicket(
|
||||
ticket: string,
|
||||
options: { secret?: string; nowMs?: number } = {},
|
||||
): Promise<WecomIdentity | null> {
|
||||
const raw = String(ticket ?? "").trim();
|
||||
const dotIndex = raw.indexOf(".");
|
||||
if (dotIndex <= 0 || dotIndex === raw.length - 1) return null;
|
||||
const payloadSegment = raw.slice(0, dotIndex);
|
||||
const signatureSegment = raw.slice(dotIndex + 1);
|
||||
if (/[^A-Za-z0-9_-]/.test(payloadSegment) || /[^A-Za-z0-9_-]/.test(signatureSegment)) {
|
||||
return null;
|
||||
}
|
||||
let payload: WecomIdentityPayload;
|
||||
try {
|
||||
payload = JSON.parse(
|
||||
new TextDecoder().decode(fromBase64Url(payloadSegment)),
|
||||
) as WecomIdentityPayload;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
payload?.v !== 1 ||
|
||||
typeof payload.ext !== "string" ||
|
||||
!payload.ext.trim() ||
|
||||
typeof payload.exp !== "number"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
const secret = options.secret ?? getWecomOAuthSecret();
|
||||
const expected = await hmacSha256(secret, payloadSegment);
|
||||
const provided = fromBase64Url(signatureSegment);
|
||||
if (!constantTimeEquals(expected, provided)) return null;
|
||||
const now = options.nowMs ?? Date.now();
|
||||
if (now > payload.exp + WECOM_IDENTITY_GRACE_MS) return null;
|
||||
return {
|
||||
externalUserId: payload.ext.trim(),
|
||||
displayName: payload.name || "企微客户",
|
||||
};
|
||||
}
|
||||
|
||||
export function wecomClaimantPartnerId(externalUserId: string): string {
|
||||
return `partner-ext-${hashText(`claimant:wecom:${externalUserId}`)}`;
|
||||
}
|
||||
|
||||
export async function resolveWecomClaimant(
|
||||
db: DatabaseClient,
|
||||
externalUserId: string,
|
||||
): Promise<{ partnerId: string; matchedExisting: boolean }> {
|
||||
const ext = String(externalUserId ?? "").trim();
|
||||
if (!ext) throw new Error("缺少企微外部联系人 ID");
|
||||
const existing = await db
|
||||
.prepare("SELECT id FROM partners WHERE wecom_external_user_id = ?")
|
||||
.bind(ext)
|
||||
.first<{ id: string }>();
|
||||
if (existing?.id) {
|
||||
return { partnerId: existing.id, matchedExisting: true };
|
||||
}
|
||||
return { partnerId: wecomClaimantPartnerId(ext), matchedExisting: false };
|
||||
}
|
||||
27
mysql/0010_projects_and_partner_type.sql
Normal file
27
mysql/0010_projects_and_partner_type.sql
Normal file
@@ -0,0 +1,27 @@
|
||||
CREATE TABLE IF NOT EXISTS `projects` (
|
||||
`id` VARCHAR(64) NOT NULL,
|
||||
`name` VARCHAR(255) NOT NULL,
|
||||
`brand` VARCHAR(255) NOT NULL DEFAULT '',
|
||||
`main_group_member_ids` TEXT NOT NULL,
|
||||
`status` VARCHAR(32) NOT NULL DEFAULT 'active',
|
||||
`note` TEXT NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
-- statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS `project_group_chats` (
|
||||
`id` VARCHAR(64) NOT NULL,
|
||||
`project_id` VARCHAR(64) NOT NULL,
|
||||
`chat_id` VARCHAR(128) NOT NULL,
|
||||
`partner_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `project_group_chats_uniq` (`project_id`,`chat_id`),
|
||||
KEY `project_group_chats_project_idx` (`project_id`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
-- statement-breakpoint
|
||||
ALTER TABLE `partners` ADD COLUMN `partner_type` VARCHAR(32) NOT NULL DEFAULT 'external_koc';
|
||||
-- statement-breakpoint
|
||||
ALTER TABLE `partners` ADD COLUMN `wecom_userid` VARCHAR(128) NOT NULL DEFAULT '';
|
||||
-- statement-breakpoint
|
||||
ALTER TABLE `tasks` ADD COLUMN `project_id` VARCHAR(64) NOT NULL DEFAULT '';
|
||||
15
mysql/0011_wecom_push_logs.sql
Normal file
15
mysql/0011_wecom_push_logs.sql
Normal file
@@ -0,0 +1,15 @@
|
||||
CREATE TABLE IF NOT EXISTS `wecom_push_logs` (
|
||||
`id` VARCHAR(64) NOT NULL,
|
||||
`task_id` VARCHAR(64) NOT NULL,
|
||||
`project_id` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
`push_kind` VARCHAR(32) NOT NULL DEFAULT 'task_open',
|
||||
`main_group_count` INT NOT NULL DEFAULT 0,
|
||||
`koc_userids` TEXT NOT NULL,
|
||||
`koc_ok_count` INT NOT NULL DEFAULT 0,
|
||||
`koc_fail_list` TEXT NOT NULL,
|
||||
`group_push_id` VARCHAR(128) NOT NULL DEFAULT '',
|
||||
`detail` TEXT NOT NULL,
|
||||
`created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `wecom_push_logs_task_idx` (`task_id`,`push_kind`)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
|
||||
42
tests/partner-wecom-claim.test.mjs
Normal file
42
tests/partner-wecom-claim.test.mjs
Normal file
@@ -0,0 +1,42 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
const routeSource = readFileSync(
|
||||
new URL("../app/api/partner/route.ts", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
test("partner route accepts identityTicket for wecom-backed claim", () => {
|
||||
assert.match(routeSource, /identityTicket\?: string/);
|
||||
assert.match(routeSource, /verifyWecomIdentityTicket/);
|
||||
assert.match(routeSource, /resolveWecomClaimant/);
|
||||
});
|
||||
|
||||
test("claim keeps manual wechat/phone path untouched when no ticket", () => {
|
||||
assert.match(
|
||||
routeSource,
|
||||
/请输入正确的微信号或手机号/,
|
||||
"manual validation message preserved",
|
||||
);
|
||||
assert.match(
|
||||
routeSource,
|
||||
/VALUES \(\?, \?, \?, '外部KOC', 0, 0\)\s*\n\s*ON CONFLICT\(id\) DO UPDATE SET\s*\n\s*name = excluded\.name,\s*\n\s*wecom_name = excluded\.wecom_name`/,
|
||||
"manual partner upsert statement preserved",
|
||||
);
|
||||
});
|
||||
|
||||
test("claim with ticket upserts wecom_external_user_id for reminders", () => {
|
||||
assert.match(
|
||||
routeSource,
|
||||
/wecom_external_user_id = excluded\.wecom_external_user_id/,
|
||||
);
|
||||
});
|
||||
|
||||
test("recover builds dynamic partner candidates including wecom identity", () => {
|
||||
assert.match(
|
||||
routeSource,
|
||||
/wecomPartnerId \? \[wecomPartnerId\] : \[partnerId, legacyPartnerId\]/,
|
||||
);
|
||||
assert.match(routeSource, /\.bind\(task\.task_type, task\.task_type, task\.id, \.\.\.partnerCandidates\)/);
|
||||
});
|
||||
264
tests/project-push.test.mjs
Normal file
264
tests/project-push.test.mjs
Normal file
@@ -0,0 +1,264 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildProjectAppMessage,
|
||||
pushProjectTask,
|
||||
} from "../lib/project-push-service.ts";
|
||||
import { ProjectError } from "../lib/project-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-01",
|
||||
task_type: "content_publish",
|
||||
platform: "小红书",
|
||||
content_format: "image_text",
|
||||
share_token: "tok-123",
|
||||
project_id: "proj-1",
|
||||
claimed_quantity: 0,
|
||||
status: "active",
|
||||
};
|
||||
|
||||
const projectRow = {
|
||||
id: "proj-1",
|
||||
name: "项目一",
|
||||
brand: "品牌A",
|
||||
main_group_member_ids: JSON.stringify(["zhangsan", "lisi"]),
|
||||
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 },
|
||||
],
|
||||
} = {}) {
|
||||
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 projects WHERE id = \?/.test(sql)) return project;
|
||||
return null;
|
||||
},
|
||||
async all() {
|
||||
executed.push({ sql, params });
|
||||
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,
|
||||
prepare(sql) {
|
||||
return makeStatement(sql);
|
||||
},
|
||||
async batch(statements) {
|
||||
for (const statement of statements) await statement.run();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeWecomFetch(calls, { failAppFor = [] } = {}) {
|
||||
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 (failAppFor.includes(body.touser)) {
|
||||
return Response.json({ errcode: 60111, errmsg: "userid not found" });
|
||||
}
|
||||
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: [] });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
test.beforeEach(() => {
|
||||
clearWecomAccessTokenCacheForTests();
|
||||
});
|
||||
|
||||
test("buildProjectAppMessage targets internal members with claim url", () => {
|
||||
const message = buildProjectAppMessage(taskRow, "https://portal.example.com/");
|
||||
assert.match(message, /【项目任务】测试任务/);
|
||||
assert.match(message, /请把任务转发到你负责的项目任务群/);
|
||||
assert.match(message, /领取链接:https:\/\/portal\.example\.com\/\?task=tok-123/);
|
||||
});
|
||||
|
||||
test("pushProjectTask sends per-member app messages and group templates", async () => {
|
||||
process.env.KOC_PORTAL_URL = "https://portal.example.com";
|
||||
try {
|
||||
const db = fakePushDb();
|
||||
const calls = [];
|
||||
const outcome = await pushProjectTask(
|
||||
db,
|
||||
{ taskId: "task-1", sendMainGroup: true, sendGroupChats: true },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeWecomFetch(calls),
|
||||
);
|
||||
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),
|
||||
["zhangsan", "lisi"],
|
||||
"one message/send per main group member",
|
||||
);
|
||||
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.deepEqual(outcome.skippedReasons, []);
|
||||
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 () => {
|
||||
process.env.KOC_PORTAL_URL = "https://portal.example.com";
|
||||
try {
|
||||
const db = fakePushDb();
|
||||
const calls = [];
|
||||
const outcome = await pushProjectTask(
|
||||
db,
|
||||
{ taskId: "task-1" },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeWecomFetch(calls, { failAppFor: ["zhangsan"] }),
|
||||
);
|
||||
assert.deepEqual(
|
||||
outcome.appResults.map((item) => [item.userid, item.ok]),
|
||||
[
|
||||
["zhangsan", false],
|
||||
["lisi", true],
|
||||
],
|
||||
);
|
||||
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");
|
||||
} finally {
|
||||
delete process.env.KOC_PORTAL_URL;
|
||||
}
|
||||
});
|
||||
|
||||
test("pushProjectTask skips empty targets instead of failing", async () => {
|
||||
const db = fakePushDb({
|
||||
project: { ...projectRow, main_group_member_ids: "[]" },
|
||||
links: [{ project_id: "proj-1", chat_id: "wr-gone", partner_id: "" }],
|
||||
groupChats: [],
|
||||
});
|
||||
const calls = [];
|
||||
const outcome = await pushProjectTask(
|
||||
db,
|
||||
{ taskId: "task-1" },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeWecomFetch(calls),
|
||||
);
|
||||
assert.deepEqual(outcome.skippedReasons, ["项目总群未配置成员", "项目没有可用的任务群"]);
|
||||
assert.equal(calls.length, 0, "no wecom api calls expected");
|
||||
});
|
||||
|
||||
test("pushProjectTask rejects task without project or unknown task", async () => {
|
||||
const unlinked = fakePushDb({ task: { ...taskRow, project_id: "" } });
|
||||
await assert.rejects(
|
||||
() =>
|
||||
pushProjectTask(
|
||||
unlinked,
|
||||
{ taskId: "task-1" },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeWecomFetch([]),
|
||||
),
|
||||
(error) => error instanceof ProjectError && /未挂项目/.test(error.message),
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
() => pushProjectTask(fakePushDb(), { taskId: "" }, resolveWecomConfig(baseBindings)),
|
||||
(error) => error instanceof ProjectError,
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
() =>
|
||||
pushProjectTask(
|
||||
fakePushDb(),
|
||||
{ taskId: "task-1", sendMainGroup: false, sendGroupChats: false },
|
||||
resolveWecomConfig(baseBindings),
|
||||
fakeWecomFetch([]),
|
||||
),
|
||||
(error) => error instanceof ProjectError && /至少选择一个发送目标/.test(error.message),
|
||||
);
|
||||
});
|
||||
378
tests/project-service.test.mjs
Normal file
378
tests/project-service.test.mjs
Normal file
@@ -0,0 +1,378 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
deleteProject,
|
||||
getProjectDetail,
|
||||
listProjects,
|
||||
parseMemberIds,
|
||||
ProjectError,
|
||||
saveGroupOwnerPartner,
|
||||
saveProject,
|
||||
setProjectGroupChats,
|
||||
} from "../lib/project-service.ts";
|
||||
|
||||
function fakeProjectDb({
|
||||
projects = [],
|
||||
links = [],
|
||||
tasks = [],
|
||||
groupChats = [],
|
||||
partners = [],
|
||||
} = {}) {
|
||||
const executed = [];
|
||||
const applyWrite = (sql, params) => {
|
||||
const normalized = sql.trim();
|
||||
if (/^INSERT INTO projects/.test(normalized)) {
|
||||
projects.push({
|
||||
id: params[0],
|
||||
name: params[1],
|
||||
brand: params[2],
|
||||
main_group_member_ids: params[3],
|
||||
status: "active",
|
||||
note: params[4],
|
||||
created_at: params[5],
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
if (/^UPDATE projects/.test(normalized)) {
|
||||
const row = projects.find((item) => item.id === params[4]);
|
||||
if (!row) return 0;
|
||||
Object.assign(row, {
|
||||
name: params[0],
|
||||
brand: params[1],
|
||||
main_group_member_ids: params[2],
|
||||
note: params[3],
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
if (/^DELETE FROM projects/.test(normalized)) {
|
||||
const index = projects.findIndex((item) => item.id === params[0]);
|
||||
if (index < 0) return 0;
|
||||
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 = "";
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
if (/^INSERT INTO partners/.test(normalized)) {
|
||||
partners.push({
|
||||
id: params[0],
|
||||
name: params[1],
|
||||
wecom_userid: params[2],
|
||||
partner_type: "group_owner",
|
||||
});
|
||||
return 1;
|
||||
}
|
||||
if (/^UPDATE partners/.test(normalized)) {
|
||||
const row = partners.find((item) => item.id === params[2]);
|
||||
if (!row) return 0;
|
||||
Object.assign(row, { name: params[0], wecom_userid: params[1] });
|
||||
return 1;
|
||||
}
|
||||
return 1;
|
||||
};
|
||||
const makeStatement = (sql, params = []) => ({
|
||||
sql,
|
||||
params,
|
||||
bind(...args) {
|
||||
return makeStatement(sql, args);
|
||||
},
|
||||
async run() {
|
||||
executed.push({ sql, params });
|
||||
return { meta: { changes: applyWrite(sql, params) } };
|
||||
},
|
||||
async first() {
|
||||
executed.push({ sql, params });
|
||||
if (/FROM projects WHERE id = \?/.test(sql)) {
|
||||
return projects.find((item) => item.id === params[0]) ?? null;
|
||||
}
|
||||
if (/FROM partners WHERE id = \?/.test(sql)) {
|
||||
return partners.find((item) => item.id === params[0]) ?? null;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
async all() {
|
||||
executed.push({ sql, params });
|
||||
if (/FROM projects p/.test(sql)) {
|
||||
return {
|
||||
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,
|
||||
})),
|
||||
};
|
||||
}
|
||||
if (/FROM tasks WHERE project_id/.test(sql)) {
|
||||
return {
|
||||
results: tasks
|
||||
.filter((task) => task.project_id === params[0])
|
||||
.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 })) };
|
||||
}
|
||||
return { results: [] };
|
||||
},
|
||||
});
|
||||
return {
|
||||
projects,
|
||||
links,
|
||||
tasks,
|
||||
groupChats,
|
||||
partners,
|
||||
executed,
|
||||
prepare(sql) {
|
||||
return makeStatement(sql);
|
||||
},
|
||||
async batch(statements) {
|
||||
const output = [];
|
||||
for (const statement of statements) output.push(await statement.run());
|
||||
return output;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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"]);
|
||||
assert.deepEqual(parseMemberIds("a,b;c,d"), ["a", "b", "c", "d"]);
|
||||
assert.deepEqual(parseMemberIds(" \n "), []);
|
||||
});
|
||||
|
||||
test("saveProject inserts with proj- prefixed id and JSON members", async () => {
|
||||
const db = fakeProjectDb();
|
||||
const project = await saveProject(db, {
|
||||
name: "暑期焕新",
|
||||
brand: "青柠实验室",
|
||||
mainGroupMemberIds: "zhangsan\nlisi\nzhangsan",
|
||||
note: "备注",
|
||||
});
|
||||
assert.match(project.id, /^proj-/);
|
||||
assert.equal(project.name, "暑期焕新");
|
||||
assert.deepEqual(project.mainGroupMemberIds, ["zhangsan", "lisi"]);
|
||||
assert.equal(db.projects.length, 1);
|
||||
assert.equal(db.projects[0].status, "active");
|
||||
});
|
||||
|
||||
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",
|
||||
},
|
||||
],
|
||||
});
|
||||
await saveProject(db, {
|
||||
id: "proj-1",
|
||||
name: "新名",
|
||||
brand: "品牌",
|
||||
mainGroupMemberIds: ["wangwu"],
|
||||
});
|
||||
assert.equal(db.projects[0].name, "新名");
|
||||
assert.equal(db.projects[0].brand, "品牌");
|
||||
assert.deepEqual(JSON.parse(db.projects[0].main_group_member_ids), ["wangwu"]);
|
||||
assert.equal(db.projects.length, 1, "update must not insert");
|
||||
|
||||
await assert.rejects(
|
||||
() => saveProject(db, { id: "proj-1", name: " " }),
|
||||
(error) => error instanceof ProjectError && error.status === 400,
|
||||
);
|
||||
});
|
||||
|
||||
test("saveProject rejects unknown id on update", async () => {
|
||||
const db = fakeProjectDb();
|
||||
await assert.rejects(
|
||||
() => saveProject(db, { id: "proj-404", name: "x" }),
|
||||
(error) => error instanceof ProjectError && error.status === 404,
|
||||
);
|
||||
});
|
||||
|
||||
test("listProjects aggregates task and group chat counts", async () => {
|
||||
const db = fakeProjectDb({
|
||||
projects: [
|
||||
{
|
||||
id: "proj-1",
|
||||
name: "A",
|
||||
brand: "",
|
||||
main_group_member_ids: "[\"u1\",\"u2\"]",
|
||||
status: "active",
|
||||
note: "",
|
||||
created_at: "2026-08-01",
|
||||
},
|
||||
],
|
||||
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.deepEqual(projects[0].mainGroupMemberIds, ["u1", "u2"]);
|
||||
});
|
||||
|
||||
test("getProjectDetail marks missing chats and dangling partners", 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: "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, "");
|
||||
});
|
||||
|
||||
test("getProjectDetail throws 404 for unknown project", async () => {
|
||||
const db = fakeProjectDb();
|
||||
await assert.rejects(
|
||||
() => getProjectDetail(db, "proj-404"),
|
||||
(error) => error instanceof ProjectError && error.status === 404,
|
||||
);
|
||||
});
|
||||
|
||||
test("setProjectGroupChats replaces links and dedupes chat ids", 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: "" }],
|
||||
tasks: [
|
||||
{ id: "t1", project_id: "proj-1" },
|
||||
{ id: "t2", project_id: "proj-2" },
|
||||
],
|
||||
});
|
||||
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");
|
||||
|
||||
await assert.rejects(
|
||||
() => deleteProject(db, "proj-404"),
|
||||
(error) => error instanceof ProjectError && error.status === 404,
|
||||
);
|
||||
});
|
||||
|
||||
test("saveGroupOwnerPartner inserts and updates group_owner partners", async () => {
|
||||
const db = fakeProjectDb();
|
||||
const created = await saveGroupOwnerPartner(db, {
|
||||
name: "张三",
|
||||
wecomUserid: "zhangsan",
|
||||
});
|
||||
assert.match(created.id, /^partner-go-/);
|
||||
assert.equal(db.partners[0].partner_type, "group_owner");
|
||||
|
||||
const updated = await saveGroupOwnerPartner(db, {
|
||||
id: created.id,
|
||||
name: "张三丰",
|
||||
wecomUserid: "zhangsanfeng",
|
||||
});
|
||||
assert.equal(updated.name, "张三丰");
|
||||
assert.equal(db.partners.length, 1);
|
||||
|
||||
await assert.rejects(
|
||||
() => saveGroupOwnerPartner(db, { name: "李四", wecomUserid: "" }),
|
||||
(error) => error instanceof ProjectError,
|
||||
);
|
||||
});
|
||||
250
tests/task-one-click-push.test.mjs
Normal file
250
tests/task-one-click-push.test.mjs
Normal file
@@ -0,0 +1,250 @@
|
||||
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),
|
||||
);
|
||||
});
|
||||
164
tests/task-report.test.mjs
Normal file
164
tests/task-report.test.mjs
Normal file
@@ -0,0 +1,164 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { buildTaskReportCsv } from "../lib/task-report-csv.ts";
|
||||
import { getTaskReportData } from "../lib/mvp-db.ts";
|
||||
|
||||
const reportRow = {
|
||||
id: "task-A",
|
||||
name: "夏日种草计划",
|
||||
task_type: "content_publish",
|
||||
brand: "轻食品牌",
|
||||
platform: "小红书",
|
||||
status: "active",
|
||||
due_at: "2026-08-20",
|
||||
created_at: "2026-08-01 10:00:00",
|
||||
quantity: 20,
|
||||
project_name: "八月投放",
|
||||
claimed_count: 10,
|
||||
published_count: 8,
|
||||
completed_count: 5,
|
||||
exposure_total: 12000,
|
||||
views_total: 9000,
|
||||
d2_likes: 100,
|
||||
d2_comments: 20,
|
||||
d2_collects: 30,
|
||||
d5_likes: 150,
|
||||
d5_comments: 25,
|
||||
d5_collects: 40,
|
||||
d7_likes: 180,
|
||||
d7_comments: 30,
|
||||
d7_collects: 50,
|
||||
latest_likes: 200,
|
||||
latest_comments: 40,
|
||||
latest_collects: 60,
|
||||
latest_shares: 10,
|
||||
};
|
||||
|
||||
test("buildTaskReportCsv writes BOM, headers and mapped rows", () => {
|
||||
const csv = buildTaskReportCsv([reportRow]);
|
||||
assert.ok(csv.startsWith(""), "starts with UTF-8 BOM");
|
||||
const lines = csv.slice(1).split("\r\n");
|
||||
assert.equal(lines.length, 2);
|
||||
assert.equal(
|
||||
lines[0],
|
||||
[
|
||||
"任务ID",
|
||||
"任务名称",
|
||||
"任务类型",
|
||||
"品牌",
|
||||
"平台",
|
||||
"所属项目",
|
||||
"任务状态",
|
||||
"计划数量",
|
||||
"领取数",
|
||||
"发布数",
|
||||
"完成数",
|
||||
"完成率",
|
||||
"截止日期",
|
||||
"创建时间",
|
||||
"曝光量合计",
|
||||
"阅读量合计",
|
||||
"D2点赞",
|
||||
"D2评论",
|
||||
"D2收藏",
|
||||
"D5点赞",
|
||||
"D5评论",
|
||||
"D5收藏",
|
||||
"D7点赞",
|
||||
"D7评论",
|
||||
"D7收藏",
|
||||
"最新点赞",
|
||||
"最新评论",
|
||||
"最新收藏",
|
||||
"最新转发",
|
||||
].join(","),
|
||||
);
|
||||
assert.equal(
|
||||
lines[1],
|
||||
[
|
||||
"task-A",
|
||||
"夏日种草计划",
|
||||
"内容发布",
|
||||
"轻食品牌",
|
||||
"小红书",
|
||||
"八月投放",
|
||||
"进行中",
|
||||
20,
|
||||
10,
|
||||
8,
|
||||
5,
|
||||
"50%",
|
||||
"2026-08-20",
|
||||
"2026-08-01 10:00:00",
|
||||
12000,
|
||||
9000,
|
||||
100,
|
||||
20,
|
||||
30,
|
||||
150,
|
||||
25,
|
||||
40,
|
||||
180,
|
||||
30,
|
||||
50,
|
||||
200,
|
||||
40,
|
||||
60,
|
||||
10,
|
||||
].join(","),
|
||||
);
|
||||
});
|
||||
|
||||
test("buildTaskReportCsv escapes commas and quotes, blanks null metrics", () => {
|
||||
const csv = buildTaskReportCsv([
|
||||
{
|
||||
...reportRow,
|
||||
name: '含,逗号"引号"任务',
|
||||
project_name: null,
|
||||
claimed_count: 0,
|
||||
exposure_total: null,
|
||||
views_total: null,
|
||||
d2_likes: null,
|
||||
d2_comments: null,
|
||||
d2_collects: null,
|
||||
d5_likes: null,
|
||||
d5_comments: null,
|
||||
d5_collects: null,
|
||||
d7_likes: null,
|
||||
d7_comments: null,
|
||||
d7_collects: null,
|
||||
latest_likes: null,
|
||||
latest_comments: null,
|
||||
latest_collects: null,
|
||||
latest_shares: null,
|
||||
},
|
||||
]);
|
||||
const rowLine = csv.slice(1).split("\r\n")[1];
|
||||
assert.ok(rowLine.includes('"含,逗号""引号""任务"'));
|
||||
const cells = rowLine.split(",");
|
||||
assert.equal(cells.at(-1), "", "null latest_shares becomes empty");
|
||||
assert.equal(cells.at(-18), "", "no claims means empty completion rate");
|
||||
assert.equal(cells.at(-16), "2026-08-01 10:00:00");
|
||||
});
|
||||
|
||||
test("getTaskReportData aggregates per task via distributions join", async () => {
|
||||
let capturedSql = "";
|
||||
const db = {
|
||||
prepare(sql) {
|
||||
capturedSql = sql;
|
||||
return {
|
||||
async all() {
|
||||
return { results: [reportRow] };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const rows = await getTaskReportData(db);
|
||||
assert.deepEqual(rows, [reportRow]);
|
||||
assert.match(capturedSql, /FROM tasks t/);
|
||||
assert.match(capturedSql, /LEFT JOIN distributions d ON d\.task_id = t\.id/);
|
||||
assert.match(capturedSql, /LEFT JOIN projects p ON p\.id = t\.project_id/);
|
||||
assert.match(capturedSql, /GROUP BY t\.id/);
|
||||
assert.match(capturedSql, /publish_url/);
|
||||
assert.match(capturedSql, /latest_shares/);
|
||||
});
|
||||
133
tests/wecom-callback-crypto.test.mjs
Normal file
133
tests/wecom-callback-crypto.test.mjs
Normal file
@@ -0,0 +1,133 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import test from "node:test";
|
||||
import {
|
||||
decryptWecomCallback,
|
||||
encryptWecomCallback,
|
||||
resolveWecomCallbackAesKey,
|
||||
verifyWecomCallbackSignature,
|
||||
wecomSignaturesMatch,
|
||||
WecomCallbackCryptoError,
|
||||
} from "../lib/wecom-callback-crypto.ts";
|
||||
import {
|
||||
extractWecomEncryptField,
|
||||
handleWecomCallbackEvent,
|
||||
parseWecomCallbackXml,
|
||||
} from "../lib/wecom-callback-events.ts";
|
||||
|
||||
const AES_KEY = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQ";
|
||||
const CORP_ID = "wwCallbackCorp01";
|
||||
const TOKEN = "callback-token-test";
|
||||
|
||||
test("aes key resolution accepts 43-char key and rejects invalid input", () => {
|
||||
const key = resolveWecomCallbackAesKey(AES_KEY);
|
||||
assert.equal(key.length, 32);
|
||||
assert.throws(
|
||||
() => resolveWecomCallbackAesKey("short"),
|
||||
WecomCallbackCryptoError,
|
||||
);
|
||||
assert.throws(
|
||||
() => resolveWecomCallbackAesKey("abcdefghij;klmnopqrstuvwxyzABCDEFGHIJKLMNOP"),
|
||||
WecomCallbackCryptoError,
|
||||
);
|
||||
});
|
||||
|
||||
test("encrypt → decrypt roundtrip preserves chinese message and receiveId", () => {
|
||||
const plain =
|
||||
'<xml><ToUserName><![CDATA[wwCallbackCorp01]]></ToUserName><Event><![CDATA[模板卡片]]></Event></xml>';
|
||||
const encrypted = encryptWecomCallback(plain, CORP_ID, AES_KEY);
|
||||
const decrypted = decryptWecomCallback(encrypted, AES_KEY);
|
||||
assert.equal(decrypted.message, plain);
|
||||
assert.equal(decrypted.receiveId, CORP_ID);
|
||||
});
|
||||
|
||||
test("decrypt rejects tampered ciphertext", () => {
|
||||
const encrypted = encryptWecomCallback("hello", CORP_ID, AES_KEY);
|
||||
const corrupted = `${encrypted.slice(0, -4)}AAAA`;
|
||||
assert.throws(
|
||||
() => decryptWecomCallback(corrupted, AES_KEY),
|
||||
WecomCallbackCryptoError,
|
||||
);
|
||||
});
|
||||
|
||||
test("decrypt rejects non-block-aligned ciphertext", () => {
|
||||
assert.throws(
|
||||
() => decryptWecomCallback("AAAAAAAA", AES_KEY),
|
||||
WecomCallbackCryptoError,
|
||||
);
|
||||
});
|
||||
|
||||
test("signature = sha1 of sorted join, order independent", () => {
|
||||
const encrypted = encryptWecomCallback("hello", CORP_ID, AES_KEY);
|
||||
const expected = createHash("sha1")
|
||||
.update([TOKEN, "1756700000", "nonce-abc", encrypted].sort().join(""))
|
||||
.digest("hex");
|
||||
const actual = verifyWecomCallbackSignature(
|
||||
TOKEN,
|
||||
"1756700000",
|
||||
"nonce-abc",
|
||||
encrypted,
|
||||
);
|
||||
assert.equal(actual, expected);
|
||||
assert.ok(wecomSignaturesMatch(actual, expected));
|
||||
assert.ok(!wecomSignaturesMatch(actual, `${expected}x`));
|
||||
assert.ok(!wecomSignaturesMatch(actual, ""));
|
||||
});
|
||||
|
||||
test("parse callback xml handles CDATA and plain fields", () => {
|
||||
const body =
|
||||
"<xml><ToUserName><![CDATA[wwCorp]]></ToUserName><Encrypt><![CDATA[RW5jcnlwdGVkQmFzZTY0PT0=]]></Encrypt><CreateTime>1756700000</CreateTime></xml>";
|
||||
const fields = parseWecomCallbackXml(body);
|
||||
assert.equal(fields.ToUserName, "wwCorp");
|
||||
assert.equal(fields.Encrypt, "RW5jcnlwdGVkQmFzZTY0PT0=");
|
||||
assert.equal(fields.CreateTime, "1756700000");
|
||||
assert.equal(extractWecomEncryptField(body), "RW5jcnlwdGVkQmFzZTY0PT0=");
|
||||
});
|
||||
|
||||
test("event dispatcher classifies template_card mark_handled and ignores others", async () => {
|
||||
const inserts = [];
|
||||
const fakeDb = {
|
||||
prepare(sql) {
|
||||
return {
|
||||
bind(...params) {
|
||||
return {
|
||||
async run() {
|
||||
inserts.push({ sql, params });
|
||||
return { success: true };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
const ack = await handleWecomCallbackEvent(fakeDb, {
|
||||
MsgType: "event",
|
||||
Event: "template_card_event",
|
||||
TaskId: "task:t123:due",
|
||||
BtnKey: "mark_handled",
|
||||
FromUserName: "opsUser01",
|
||||
});
|
||||
assert.equal(ack.recognized, true);
|
||||
assert.equal(ack.action, "card_ack");
|
||||
assert.equal(ack.taskId, "task:t123:due");
|
||||
assert.equal(ack.operator, "opsUser01");
|
||||
assert.equal(inserts.length, 1);
|
||||
assert.match(inserts[0].sql, /INSERT INTO wecom_push_logs/);
|
||||
assert.equal(inserts[0].params[0].startsWith("wpl-"), true);
|
||||
assert.equal(inserts[0].params[1], "t123");
|
||||
|
||||
const view = await handleWecomCallbackEvent(fakeDb, {
|
||||
MsgType: "event",
|
||||
Event: "template_card_event",
|
||||
TaskId: "task:t123:due",
|
||||
BtnKey: "view_task",
|
||||
});
|
||||
assert.equal(view.recognized, true);
|
||||
assert.equal(view.action, "ignored");
|
||||
|
||||
const other = await handleWecomCallbackEvent(fakeDb, {
|
||||
MsgType: "event",
|
||||
Event: "change_contact",
|
||||
});
|
||||
assert.equal(other.recognized, false);
|
||||
});
|
||||
@@ -1,8 +1,11 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildWecomOAuthUrl,
|
||||
clearWecomAccessTokenCacheForTests,
|
||||
createGroupMsgTemplate,
|
||||
exchangeWecomOAuthCode,
|
||||
fetchWecomExternalContactName,
|
||||
listCustomerGroupChats,
|
||||
listExternalContacts,
|
||||
resolveWecomConfig,
|
||||
@@ -605,3 +608,166 @@ test("createGroupMsgTemplate rejects missing sender or empty chat list", async (
|
||||
/客户群列表为空/,
|
||||
);
|
||||
});
|
||||
|
||||
function fakeWecomOAuth(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/auth/getuserinfo")) {
|
||||
return Response.json({
|
||||
errcode: options.oauthErrcode ?? 0,
|
||||
errmsg: options.oauthErrmsg ?? "ok",
|
||||
...(options.userId ? { userid: options.userId } : {}),
|
||||
...(options.externalUserId ? { external_userid: options.externalUserId } : {}),
|
||||
});
|
||||
}
|
||||
if (url.pathname.endsWith("/cgi-bin/externalcontact/get")) {
|
||||
const eid = url.searchParams.get("external_userid");
|
||||
if (options.contactNames && options.contactNames[eid]) {
|
||||
return Response.json({
|
||||
errcode: 0,
|
||||
errmsg: "ok",
|
||||
external_contact: { external_userid: eid, name: options.contactNames[eid] },
|
||||
});
|
||||
}
|
||||
return Response.json({ errcode: 60111, errmsg: "not found" });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
return { calls, fetchImpl };
|
||||
}
|
||||
|
||||
test("buildWecomOAuthUrl assembles authorize URL with encoded params", () => {
|
||||
const url = new URL(
|
||||
buildWecomOAuthUrl({
|
||||
corpId: "corp-test",
|
||||
agentId: "1000001",
|
||||
redirectUri: "https://portal.example.com/koc/?task=abc",
|
||||
state: "t=abc",
|
||||
}),
|
||||
);
|
||||
assert.equal(url.origin, "https://open.weixin.qq.com");
|
||||
assert.equal(url.pathname, "/connect/oauth2/authorize");
|
||||
assert.equal(url.hash, "#wechat_redirect");
|
||||
assert.equal(url.searchParams.get("appid"), "corp-test");
|
||||
assert.equal(url.searchParams.get("agentid"), "1000001");
|
||||
assert.equal(url.searchParams.get("response_type"), "code");
|
||||
assert.equal(url.searchParams.get("scope"), "snsapi_base");
|
||||
assert.equal(url.searchParams.get("state"), "t=abc");
|
||||
assert.equal(
|
||||
url.searchParams.get("redirect_uri"),
|
||||
"https://portal.example.com/koc/?task=abc",
|
||||
);
|
||||
});
|
||||
|
||||
test("exchangeWecomOAuthCode returns external identity and posts code", async () => {
|
||||
const { calls, fetchImpl } = fakeWecomOAuth({ externalUserId: "wmExt123" });
|
||||
const identity = await exchangeWecomOAuthCode(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"code-abc",
|
||||
fetchImpl,
|
||||
);
|
||||
assert.deepEqual(identity, { externalUserId: "wmExt123" });
|
||||
const call = calls.find((c) =>
|
||||
c.url.pathname.endsWith("/cgi-bin/auth/getuserinfo"),
|
||||
);
|
||||
assert.ok(call, "getuserinfo was called");
|
||||
assert.equal(call.url.searchParams.get("access_token"), "token-test");
|
||||
assert.equal(JSON.parse(String(call.init.body)).code, "code-abc");
|
||||
});
|
||||
|
||||
test("exchangeWecomOAuthCode returns internal member userid", async () => {
|
||||
const { fetchImpl } = fakeWecomOAuth({ userId: "zhangsan" });
|
||||
const identity = await exchangeWecomOAuthCode(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"code-abc",
|
||||
fetchImpl,
|
||||
);
|
||||
assert.deepEqual(identity, { userId: "zhangsan" });
|
||||
});
|
||||
|
||||
test("exchangeWecomOAuthCode throws 400 on invalid code (errcode 40029)", async () => {
|
||||
const { fetchImpl } = fakeWecomOAuth({
|
||||
oauthErrcode: 40029,
|
||||
oauthErrmsg: "invalid code",
|
||||
});
|
||||
await assert.rejects(
|
||||
() =>
|
||||
exchangeWecomOAuthCode(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"code-expired",
|
||||
fetchImpl,
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 400);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("exchangeWecomOAuthCode throws when provider returns no identity", async () => {
|
||||
const { fetchImpl } = fakeWecomOAuth();
|
||||
await assert.rejects(
|
||||
() =>
|
||||
exchangeWecomOAuthCode(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"code-abc",
|
||||
fetchImpl,
|
||||
),
|
||||
(error) => {
|
||||
assert.ok(error instanceof WecomClientError);
|
||||
assert.equal(error.status, 400);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("exchangeWecomOAuthCode reuses cached access_token", async () => {
|
||||
const { calls, fetchImpl } = fakeWecomOAuth({ externalUserId: "wmExt123" });
|
||||
const config = resolveWecomConfig(baseBindings);
|
||||
await exchangeWecomOAuthCode(config, "code-1", fetchImpl);
|
||||
await exchangeWecomOAuthCode(config, "code-2", fetchImpl);
|
||||
assert.equal(
|
||||
calls.filter((c) => c.url.pathname.endsWith("/cgi-bin/gettoken")).length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test("fetchWecomExternalContactName resolves name and falls back to null", async () => {
|
||||
const okImpl = fakeWecomOAuth({ contactNames: { wmExt123: "张三" } });
|
||||
assert.equal(
|
||||
await fetchWecomExternalContactName(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"wmExt123",
|
||||
okImpl.fetchImpl,
|
||||
),
|
||||
"张三",
|
||||
);
|
||||
const failImpl = fakeWecomOAuth();
|
||||
assert.equal(
|
||||
await fetchWecomExternalContactName(
|
||||
resolveWecomConfig(baseBindings),
|
||||
"wmMissing",
|
||||
failImpl.fetchImpl,
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
await fetchWecomExternalContactName(
|
||||
resolveWecomConfig({ ...baseBindings, WECOM_SECRET: "" }),
|
||||
"wmExt123",
|
||||
failImpl.fetchImpl,
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
268
tests/wecom-escalation.test.mjs
Normal file
268
tests/wecom-escalation.test.mjs
Normal file
@@ -0,0 +1,268 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
resolveAutoReleaseDays,
|
||||
runOverdueAutoRelease,
|
||||
runOverdueEscalation,
|
||||
} from "../lib/wecom-notifier-service.ts";
|
||||
import {
|
||||
clearWecomAccessTokenCacheForTests,
|
||||
resolveWecomConfig,
|
||||
} from "../lib/wecom-client.ts";
|
||||
|
||||
const config = resolveWecomConfig({
|
||||
WECOM_CORP_ID: "corp-test",
|
||||
WECOM_AGENT_ID: "1000001",
|
||||
WECOM_SECRET: "secret-test",
|
||||
WECOM_ROBOT_WEBHOOK: "https://qyapi.example.com/webhook/send?key=abc",
|
||||
});
|
||||
|
||||
const TODAY = "2026-09-01";
|
||||
const NOW = new Date(`${TODAY}T02:00:00Z`).getTime();
|
||||
|
||||
const overdueRows = [
|
||||
{
|
||||
id: "d-1",
|
||||
task_id: "task-A",
|
||||
task_name: "超期任务A",
|
||||
due_at: "2026-08-20",
|
||||
project_id: "proj-1",
|
||||
partner_id: "p-1",
|
||||
partner_name: "合作方甲",
|
||||
},
|
||||
{
|
||||
id: "d-2",
|
||||
task_id: "task-A",
|
||||
task_name: "超期任务A",
|
||||
due_at: "2026-08-20",
|
||||
project_id: "proj-1",
|
||||
partner_id: "p-2",
|
||||
partner_name: "合作方乙",
|
||||
},
|
||||
{
|
||||
id: "d-3",
|
||||
task_id: "task-B",
|
||||
task_name: "无项目任务B",
|
||||
due_at: "2026-08-25",
|
||||
project_id: "",
|
||||
partner_id: "p-3",
|
||||
partner_name: "合作方丙",
|
||||
},
|
||||
];
|
||||
|
||||
const releasableDistribution = {
|
||||
id: "d-1",
|
||||
task_id: "task-A",
|
||||
task_type: "content_publish",
|
||||
content_id: "c-1",
|
||||
content_title: "超期内容",
|
||||
partner_id: "p-1",
|
||||
partner_name: "合作方甲",
|
||||
claim_id: null,
|
||||
delegation_bundle_id: null,
|
||||
publish_url: null,
|
||||
result_submitted_at: null,
|
||||
};
|
||||
|
||||
function fakeEscalationDb({ rows = overdueRows } = {}) {
|
||||
return {
|
||||
prepare(sql) {
|
||||
return {
|
||||
bind(...params) {
|
||||
return {
|
||||
async first() {
|
||||
if (/FROM projects WHERE id = \?/.test(sql)) {
|
||||
return { main_group_member_ids: JSON.stringify(["opsZhang", "opsLi"]) };
|
||||
}
|
||||
return null;
|
||||
},
|
||||
async all() {
|
||||
if (/FROM distributions d/.test(sql) && /publish_url IS NULL/.test(sql)) {
|
||||
return { results: rows.filter((row) => row.due_at < params[0]) };
|
||||
}
|
||||
return { results: [] };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeReleaseDb({ rows = overdueRows, blockedIds = [] } = {}) {
|
||||
const executed = [];
|
||||
const inner = {
|
||||
prepare(sql) {
|
||||
return {
|
||||
bind(...params) {
|
||||
return {
|
||||
async first() {
|
||||
if (/FROM projects WHERE id = \?/.test(sql)) {
|
||||
return { main_group_member_ids: JSON.stringify(["opsZhang"]) };
|
||||
}
|
||||
if (/FOR UPDATE/.test(sql)) {
|
||||
const row = rows.find((item) => item.id === params[0]);
|
||||
if (!row) return null;
|
||||
return {
|
||||
...releasableDistribution,
|
||||
id: row.id,
|
||||
task_id: row.task_id,
|
||||
partner_id: row.partner_id,
|
||||
partner_name: row.partner_name,
|
||||
result_submitted_at: blockedIds.includes(row.id)
|
||||
? "2026-08-30 10:00:00"
|
||||
: null,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
async all() {
|
||||
if (/FROM distributions d/.test(sql) && /publish_url IS NULL/.test(sql)) {
|
||||
return { results: rows.filter((row) => row.due_at < params[0]) };
|
||||
}
|
||||
return { results: [] };
|
||||
},
|
||||
async run() {
|
||||
executed.push({ sql, params });
|
||||
return { meta: { changes: 1 } };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
return {
|
||||
executed,
|
||||
...inner,
|
||||
async transaction(fn) {
|
||||
return fn(inner);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function wecomFetch(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/message/send") ||
|
||||
url.host === "qyapi.example.com"
|
||||
) {
|
||||
return Response.json({ errcode: 0, errmsg: "ok" });
|
||||
}
|
||||
return new Response("not found", { status: 404 });
|
||||
};
|
||||
}
|
||||
|
||||
test.beforeEach(() => {
|
||||
clearWecomAccessTokenCacheForTests();
|
||||
delete process.env.WECOM_AUTO_RELEASE_DAYS;
|
||||
delete process.env.APP_ORIGIN;
|
||||
});
|
||||
|
||||
test("resolveAutoReleaseDays parses bounds and defaults to disabled", () => {
|
||||
assert.equal(resolveAutoReleaseDays(undefined), 0);
|
||||
assert.equal(resolveAutoReleaseDays(""), 0);
|
||||
assert.equal(resolveAutoReleaseDays("0"), 0);
|
||||
assert.equal(resolveAutoReleaseDays("-5"), 0);
|
||||
assert.equal(resolveAutoReleaseDays("abc"), 0);
|
||||
assert.equal(resolveAutoReleaseDays("7"), 7);
|
||||
assert.equal(resolveAutoReleaseDays("120"), 90);
|
||||
});
|
||||
|
||||
test("runOverdueEscalation posts robot digest and template cards per project", async () => {
|
||||
const calls = [];
|
||||
const summary = await runOverdueEscalation(
|
||||
fakeEscalationDb(),
|
||||
config,
|
||||
wecomFetch(calls),
|
||||
NOW,
|
||||
);
|
||||
assert.equal(summary.overdueTasks, 2);
|
||||
assert.equal(summary.overdueDistributions, 3);
|
||||
assert.equal(summary.robotSent, true);
|
||||
|
||||
const robotBodies = calls
|
||||
.filter((call) => call.url.host === "qyapi.example.com")
|
||||
.map((call) => JSON.parse(String(call.init.body)));
|
||||
assert.equal(robotBodies.length, 1);
|
||||
assert.match(robotBodies[0].text.content, /【超期未发布升级】/);
|
||||
assert.match(robotBodies[0].text.content, /超期任务A/);
|
||||
assert.match(robotBodies[0].text.content, /无项目任务B/);
|
||||
|
||||
const cardCalls = calls.filter((call) =>
|
||||
call.url.pathname.endsWith("/cgi-bin/message/send"),
|
||||
);
|
||||
assert.equal(cardCalls.length, 1, "only the project task gets a card");
|
||||
const body = JSON.parse(String(cardCalls[0].init.body));
|
||||
assert.equal(body.msgtype, "template_card");
|
||||
assert.equal(body.template_card.task_id, "task:task-A:due");
|
||||
assert.equal(body.touser, "opsZhang|opsLi");
|
||||
const buttons = body.template_card.button_list;
|
||||
assert.equal(buttons.length, 2);
|
||||
assert.ok(buttons.some((button) => button.type === 0 && button.key === "mark_handled"));
|
||||
assert.equal(summary.cardSent, 2);
|
||||
assert.equal(summary.cardFailed, 0);
|
||||
});
|
||||
|
||||
test("runOverdueEscalation no-ops without overdue rows", async () => {
|
||||
const calls = [];
|
||||
const summary = await runOverdueEscalation(
|
||||
fakeEscalationDb({ rows: [] }),
|
||||
config,
|
||||
wecomFetch(calls),
|
||||
NOW,
|
||||
);
|
||||
assert.equal(summary.overdueDistributions, 0);
|
||||
assert.equal(summary.robotSent, false);
|
||||
assert.equal(calls.length, 0);
|
||||
});
|
||||
|
||||
test("runOverdueAutoRelease is disabled without env switch", async () => {
|
||||
const calls = [];
|
||||
const db = fakeReleaseDb();
|
||||
const summary = await runOverdueAutoRelease(db, config, wecomFetch(calls), NOW);
|
||||
assert.equal(summary.enabled, false);
|
||||
assert.equal(summary.released, 0);
|
||||
assert.equal(calls.length, 0);
|
||||
assert.equal(db.executed.length, 0);
|
||||
});
|
||||
|
||||
test("runOverdueAutoRelease releases overdue rows and skips blocked ones", async () => {
|
||||
process.env.WECOM_AUTO_RELEASE_DAYS = "10";
|
||||
const calls = [];
|
||||
const db = fakeReleaseDb({ blockedIds: ["d-3"] });
|
||||
const summary = await runOverdueAutoRelease(db, config, wecomFetch(calls), NOW);
|
||||
// cutoff = 2026-08-22:d-1/d-2(08-20)命中,d-3(08-25)不在窗口内
|
||||
assert.equal(summary.enabled, true);
|
||||
assert.equal(summary.cutoff, "2026-08-22");
|
||||
assert.equal(summary.released, 2);
|
||||
assert.equal(summary.blocked, 0);
|
||||
assert.ok(
|
||||
db.executed.some((item) => /UPDATE contents SET status = 'available'/.test(item.sql)),
|
||||
"released content returns to pool",
|
||||
);
|
||||
const robotBodies = calls
|
||||
.filter((call) => call.url.host === "qyapi.example.com")
|
||||
.map((call) => JSON.parse(String(call.init.body)));
|
||||
assert.equal(robotBodies.length, 1);
|
||||
assert.match(robotBodies[0].text.content, /已释放 2 条/);
|
||||
});
|
||||
|
||||
test("runOverdueAutoRelease counts blocked rows as skipped", async () => {
|
||||
process.env.WECOM_AUTO_RELEASE_DAYS = "3";
|
||||
const db = fakeReleaseDb({ blockedIds: ["d-1", "d-2", "d-3"] });
|
||||
const summary = await runOverdueAutoRelease(db, config, wecomFetch([]), NOW);
|
||||
assert.equal(summary.cutoff, "2026-08-29");
|
||||
assert.equal(summary.released, 0);
|
||||
assert.equal(summary.blocked, 3);
|
||||
assert.equal(summary.failed, 0);
|
||||
});
|
||||
123
tests/wecom-feedback.test.mjs
Normal file
123
tests/wecom-feedback.test.mjs
Normal file
@@ -0,0 +1,123 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
buildCollectionFinishedMessage,
|
||||
buildPublishSubmittedMessage,
|
||||
notifyCollectionFinished,
|
||||
notifyPartnerSubmitted,
|
||||
} from "../lib/wecom-feedback-service.ts";
|
||||
import { resolveWecomConfig } from "../lib/wecom-client.ts";
|
||||
|
||||
const config = resolveWecomConfig({
|
||||
WECOM_CORP_ID: "corp-test",
|
||||
WECOM_AGENT_ID: "1000001",
|
||||
WECOM_SECRET: "secret-test",
|
||||
WECOM_ROBOT_WEBHOOK: "https://qyapi.example.com/webhook/send?key=abc",
|
||||
});
|
||||
|
||||
const submittedRow = {
|
||||
claimant_name: "小王",
|
||||
partner_name: "合作方甲",
|
||||
task_name: "夏日轻盈计划",
|
||||
content_title: "好物分享笔记",
|
||||
publish_url: "https://www.xiaohongshu.com/explore/abc",
|
||||
};
|
||||
|
||||
function robotFetch(calls) {
|
||||
return async (input, init = {}) => {
|
||||
const url = new URL(String(input));
|
||||
calls.push({ url, init });
|
||||
return Response.json({ errcode: 0, errmsg: "ok" });
|
||||
};
|
||||
}
|
||||
|
||||
function fakeSubmittedDb(row = submittedRow) {
|
||||
return {
|
||||
prepare(sql) {
|
||||
return {
|
||||
bind() {
|
||||
return {
|
||||
async first() {
|
||||
if (/FROM distributions d/.test(sql)) return row;
|
||||
return null;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("publish submitted message covers partner, task and link", () => {
|
||||
const message = buildPublishSubmittedMessage(submittedRow, "publish");
|
||||
assert.match(message, /【KOC 已提交发布】/);
|
||||
assert.match(message, /合作方:合作方甲/);
|
||||
assert.match(message, /夏日轻盈计划/);
|
||||
assert.match(message, /xiaohongshu\.com\/explore\/abc/);
|
||||
const screenshot = buildPublishSubmittedMessage(submittedRow, "screenshot");
|
||||
assert.match(screenshot, /【KOC 已提交截图】/);
|
||||
assert.doesNotMatch(screenshot, /链接:/);
|
||||
});
|
||||
|
||||
test("collection digest includes failure hint only when failed", () => {
|
||||
const ok = buildCollectionFinishedMessage({
|
||||
currentDate: "2026-09-01",
|
||||
dueTasks: 3,
|
||||
attempted: 10,
|
||||
succeeded: 10,
|
||||
failed: 0,
|
||||
});
|
||||
assert.match(ok, /成功 10、失败 0/);
|
||||
assert.doesNotMatch(ok, /重试/);
|
||||
const bad = buildCollectionFinishedMessage({
|
||||
currentDate: "2026-09-01",
|
||||
dueTasks: 3,
|
||||
attempted: 10,
|
||||
succeeded: 7,
|
||||
failed: 3,
|
||||
});
|
||||
assert.match(bad, /重试/);
|
||||
});
|
||||
|
||||
test("notifyPartnerSubmitted posts robot message and skips without webhook", async () => {
|
||||
const calls = [];
|
||||
const sent = await notifyPartnerSubmitted(
|
||||
fakeSubmittedDb(),
|
||||
{ distributionId: "d-1", kind: "publish" },
|
||||
config,
|
||||
robotFetch(calls),
|
||||
);
|
||||
assert.equal(sent, true);
|
||||
assert.equal(calls.length, 1);
|
||||
const body = JSON.parse(String(calls[0].init.body));
|
||||
assert.equal(body.msgtype, "text");
|
||||
assert.match(body.text.content, /【KOC 已提交发布】/);
|
||||
|
||||
const noWebhook = await notifyPartnerSubmitted(
|
||||
fakeSubmittedDb(),
|
||||
{ distributionId: "d-1", kind: "publish" },
|
||||
resolveWecomConfig({}),
|
||||
robotFetch([]),
|
||||
);
|
||||
assert.equal(noWebhook, false);
|
||||
});
|
||||
|
||||
test("notifyCollectionFinished skips empty batches and posts on activity", async () => {
|
||||
const calls = [];
|
||||
const idle = await notifyCollectionFinished(
|
||||
{ currentDate: "2026-09-01", dueTasks: 0, attempted: 0, succeeded: 0, failed: 0 },
|
||||
config,
|
||||
robotFetch(calls),
|
||||
);
|
||||
assert.equal(idle, false);
|
||||
assert.equal(calls.length, 0);
|
||||
|
||||
const active = await notifyCollectionFinished(
|
||||
{ currentDate: "2026-09-01", dueTasks: 2, attempted: 5, succeeded: 4, failed: 1 },
|
||||
config,
|
||||
robotFetch(calls),
|
||||
);
|
||||
assert.equal(active, true);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.match(JSON.parse(String(calls[0].init.body)).text.content, /成功 4、失败 1/);
|
||||
});
|
||||
158
tests/wecom-oauth-service.test.mjs
Normal file
158
tests/wecom-oauth-service.test.mjs
Normal file
@@ -0,0 +1,158 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import {
|
||||
getWecomOAuthSecret,
|
||||
resolveWecomClaimant,
|
||||
signWecomIdentityTicket,
|
||||
verifyWecomIdentityTicket,
|
||||
wecomClaimantPartnerId,
|
||||
WECOM_IDENTITY_TTL_MS,
|
||||
} from "../lib/wecom-oauth-service.ts";
|
||||
|
||||
const SECRET = "internal-token-test";
|
||||
|
||||
function fakePartnerDb(partners = []) {
|
||||
return {
|
||||
prepare(sql) {
|
||||
return {
|
||||
bind(...params) {
|
||||
return {
|
||||
async first() {
|
||||
if (/WHERE wecom_external_user_id = \?/.test(sql)) {
|
||||
const row = partners.find(
|
||||
(item) => item.wecom_external_user_id === params[0],
|
||||
);
|
||||
return row ? { id: row.id } : null;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("identity ticket sign → verify roundtrip", async () => {
|
||||
const { ticket } = await signWecomIdentityTicket("wmExt123", "张三", {
|
||||
secret: SECRET,
|
||||
});
|
||||
const identity = await verifyWecomIdentityTicket(ticket, { secret: SECRET });
|
||||
assert.deepEqual(identity, { externalUserId: "wmExt123", displayName: "张三" });
|
||||
});
|
||||
|
||||
test("identity ticket falls back to default display name when empty", async () => {
|
||||
const { ticket } = await signWecomIdentityTicket("wmExt123", " ", {
|
||||
secret: SECRET,
|
||||
});
|
||||
const identity = await verifyWecomIdentityTicket(ticket, { secret: SECRET });
|
||||
assert.equal(identity.displayName, "企微客户");
|
||||
});
|
||||
|
||||
test("identity ticket default TTL is 30 minutes and expiresIn matches", async () => {
|
||||
const now = Date.now();
|
||||
const { ticket, expiresIn } = await signWecomIdentityTicket("wmExt123", "张三", {
|
||||
secret: SECRET,
|
||||
nowMs: now,
|
||||
});
|
||||
assert.equal(expiresIn, 30 * 60);
|
||||
const identity = await verifyWecomIdentityTicket(ticket, {
|
||||
secret: SECRET,
|
||||
nowMs: now + WECOM_IDENTITY_TTL_MS - 1,
|
||||
});
|
||||
assert.ok(identity, "still valid just before expiry");
|
||||
const expired = await verifyWecomIdentityTicket(ticket, {
|
||||
secret: SECRET,
|
||||
nowMs: now + WECOM_IDENTITY_TTL_MS + 61_000,
|
||||
});
|
||||
assert.equal(expired, null, "expired beyond grace window");
|
||||
});
|
||||
|
||||
test("identity ticket passes within 60s grace window", async () => {
|
||||
const now = Date.now();
|
||||
const { ticket } = await signWecomIdentityTicket("wmExt123", "张三", {
|
||||
secret: SECRET,
|
||||
nowMs: now,
|
||||
});
|
||||
const identity = await verifyWecomIdentityTicket(ticket, {
|
||||
secret: SECRET,
|
||||
nowMs: now + WECOM_IDENTITY_TTL_MS + 30_000,
|
||||
});
|
||||
assert.deepEqual(identity?.externalUserId, "wmExt123");
|
||||
});
|
||||
|
||||
test("identity ticket verification fails on wrong secret", async () => {
|
||||
const { ticket } = await signWecomIdentityTicket("wmExt123", "张三", {
|
||||
secret: SECRET,
|
||||
});
|
||||
assert.equal(
|
||||
await verifyWecomIdentityTicket(ticket, { secret: "other-secret" }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("identity ticket verification fails on tampered payload", async () => {
|
||||
const { ticket } = await signWecomIdentityTicket("wmExt123", "张三", {
|
||||
secret: SECRET,
|
||||
});
|
||||
const [payload, signature] = ticket.split(".");
|
||||
const decoded = JSON.parse(
|
||||
Buffer.from(payload.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString(
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
decoded.ext = "wmVictim";
|
||||
const forgedPayload = Buffer.from(JSON.stringify(decoded))
|
||||
.toString("base64")
|
||||
.replace(/\+/g, "-")
|
||||
.replace(/\//g, "_")
|
||||
.replace(/=+$/, "");
|
||||
assert.equal(
|
||||
await verifyWecomIdentityTicket(`${forgedPayload}.${signature}`, {
|
||||
secret: SECRET,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("identity ticket verification fails on malformed input", async () => {
|
||||
for (const bad of ["", "no-dot", ".abc", "abc.", "a b.c d", "xxx.yyy"]) {
|
||||
assert.equal(
|
||||
await verifyWecomIdentityTicket(bad, { secret: SECRET }),
|
||||
null,
|
||||
`rejects ${JSON.stringify(bad)}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("getWecomOAuthSecret throws when ADMIN_INTERNAL_TOKEN missing", () => {
|
||||
const previous = process.env.ADMIN_INTERNAL_TOKEN;
|
||||
delete process.env.ADMIN_INTERNAL_TOKEN;
|
||||
try {
|
||||
assert.throws(() => getWecomOAuthSecret(), /ADMIN_INTERNAL_TOKEN/);
|
||||
} finally {
|
||||
if (previous !== undefined) process.env.ADMIN_INTERNAL_TOKEN = previous;
|
||||
}
|
||||
});
|
||||
|
||||
test("wecomClaimantPartnerId derives stable partner-ext id", () => {
|
||||
const first = wecomClaimantPartnerId("wmExt123");
|
||||
assert.match(first, /^partner-ext-[a-z0-9]+$/);
|
||||
assert.equal(first, wecomClaimantPartnerId("wmExt123"));
|
||||
assert.notEqual(first, wecomClaimantPartnerId("wmExt456"));
|
||||
});
|
||||
|
||||
test("resolveWecomClaimant reuses partner bound by operator", async () => {
|
||||
const db = fakePartnerDb([
|
||||
{ id: "partner-9", wecom_external_user_id: "wmExt123" },
|
||||
]);
|
||||
const resolved = await resolveWecomClaimant(db, "wmExt123");
|
||||
assert.deepEqual(resolved, { partnerId: "partner-9", matchedExisting: true });
|
||||
});
|
||||
|
||||
test("resolveWecomClaimant derives new id when unbound", async () => {
|
||||
const db = fakePartnerDb();
|
||||
const resolved = await resolveWecomClaimant(db, "wmExt123");
|
||||
assert.equal(resolved.matchedExisting, false);
|
||||
assert.equal(resolved.partnerId, wecomClaimantPartnerId("wmExt123"));
|
||||
});
|
||||
Reference in New Issue
Block a user