| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267 |
- import test from "node:test";
- import assert from "node:assert/strict";
- import { nextCustomerNo, normalizedIdNo, generatedCustomerLogin, validateCustomerDraft, onboardingCustomers, onboardingRegions, provinceId, claimState, addClaimDays, deliveredClaim, createClaimCode } from "../src/lib/customer-onboarding.ts";
- import { commitCustomerBundle, readCustomers, readCustomerMasterAccount } from "../src/lib/customer-records.ts";
- import { textWorkbook } from "../src/lib/xlsx-export.ts";
- import { claimExportCustomers, claimExportUserIds, codeExportCell, codeExportView, codeExportWorkbook, copyPlainText, prepareClaimExport } from "../src/lib/customer-claim-export.ts";
- import { downloadBlob } from "../src/lib/customer-delivery-store.ts";
- import { writeFileSync } from "node:fs";
- const data = { regions: [{ id: "root", name: "上海市", parent: null }, { id: "child", name: "浦东", parent: "root" }, { id: "other", name: "广东", parent: null }], operationsTeams: [{ id: "team", scope: { regions: ["root"], enterprises: [] } }], enterprises: [], operators: [{ id: "op", region: "root" }], maintenanceTeams: [{ id: "mt", region: "root", ticketTypes: ["开户"] }], partners: [] };
- const regional = { role: "regAdmin", operationsTeamId: "team" };
- const draft = () => ({ name: "同名客户", subject: "企业", idNo: "91310115MA1K3XE71T", contact: "联系人", phone: "021-00000000", address: "演示地址", regionId: "child", operatorId: "op", teamIds: ["mt"], partnerId: "", login: "new-client", masterPhone: "", initialPassword: "", idNoBasis: "" });
- test("自动主体号递增、规范化识别号;同名客户可建档,识别号重复拒绝", () => {
- assert.equal(nextCustomerNo([{ no: "KL-2026-0008" }, { no: "KL-2026-0036" }, { no: "KL-2025-9999" }], 2026), "KL-2026-000037");
- assert.equal(normalizedIdNo(" 91310115 ma1k3xe71t "), "91310115MA1K3XE71T");
- assert.deepEqual(validateCustomerDraft(draft(), [{ no: "old", name: "同名客户", idNo: "91310115MA1K3XE72T" }], data, regional, []), {});
- assert.match(validateCustomerDraft(draft(), [{ no: "old", idNo: "91310115 ma1k3xe71t" }], data, regional, []).idNo, /已登记/);
- });
- test("联系人、电话、地址、运维团队必填;个人识别号与更正依据校验", () => {
- for (const field of ["name", "contact", "phone", "address", "regionId"]) assert.ok(validateCustomerDraft({ ...draft(), [field]: "" }, [], data, regional, [])[field]);
- assert.ok(validateCustomerDraft({ ...draft(), teamIds: [] }, [], data, regional, []).teamIds);
- assert.ok(validateCustomerDraft({ ...draft(), subject: "个人" }, [], data, regional, []).idNo);
- assert.equal(validateCustomerDraft({ ...draft(), subject: "个人", idNo: "31011519920817302x" }, [], data, regional, []).idNo, undefined);
- assert.ok(validateCustomerDraft(draft(), [], data, regional, [], { no: "old", idNo: "91310115MA1K3XE72T" }).idNoBasis);
- });
- test("登录名自动避重且可覆盖;手填账号、绑定手机号全站查重", () => {
- assert.equal(generatedCustomerLogin("澄澜科技有限公司", "KL-2026-000037", []), "clkj");
- assert.equal(generatedCustomerLogin("澄澜科技有限公司", "KL-2026-000037", [{ login: "CLKJ" }, { login: "clkj2" }]), "clkj3");
- assert.ok(validateCustomerDraft(draft(), [], data, regional, [{ login: "NEW-CLIENT" }]).login);
- assert.ok(validateCustomerDraft({ ...draft(), masterPhone: "123" }, [], data, regional, []).masterPhone);
- assert.ok(validateCustomerDraft({ ...draft(), masterPhone: "13900000200" }, [], data, regional, [{ phone: "13900000200" }]).masterPhone);
- });
- test("客户运营商须同省,运维团队恰好 1 支,人工初始密码限 8–32 位", () => {
- // 业主 2026-11-12 裁定「单支定案」:0 支/>1 支一律整笔拒绝(后端 customer.rs 同步校验)。
- assert.equal(validateCustomerDraft(draft(), [], data, regional, []).teamIds, undefined);
- assert.match(validateCustomerDraft({ ...draft(), teamIds: ["mt", "mt"] }, [], data, regional, []).teamIds, /1 支/);
- assert.match(validateCustomerDraft({ ...draft(), teamIds: [] }, [], data, regional, []).teamIds, /1 支/);
- assert.match(validateCustomerDraft({ ...draft(), regionId: "other" }, [], data, null, []).operatorId, /省份/);
- assert.ok(validateCustomerDraft({ ...draft(), initialPassword: "short" }, [], data, regional, []).initialPassword);
- assert.equal(validateCustomerDraft({ ...draft(), initialPassword: "welcome-123" }, [], data, regional, []).initialPassword, undefined);
- });
- test("区域运营只能挂载、导出本人范围及下级;其他角色不获得建档范围", () => {
- assert.deepEqual(onboardingRegions(data, regional), ["root", "child"]);
- assert.ok(validateCustomerDraft({ ...draft(), regionId: "other" }, [], data, regional, []).regionId);
- assert.deepEqual(onboardingCustomers([{ no: "a", regionPath: "上海市 / 浦东" }, { no: "b", regionPath: "广东" }], data, regional).map((item) => item.no), ["a"]);
- assert.deepEqual(onboardingCustomers([{ no: "moved", regionId: "child", regionPath: "广东" }], data, regional), []);
- assert.deepEqual(onboardingRegions(data, { role: "partner" }), []);
- });
- /*
- * 2026-11-15 实测缺陷:dev 区域树=「全网(level 为空)› 上海市/江苏省/广东省 › 市 › 区县」。
- * 旧的 `provinceId` 一路沿 `parent` 走到根 ⇒ 每个区域都归到「全网」,成本管理的省份下拉只剩
- * 一个「全网」选项、「运营商建档省份须与客户所在省份一致」校验恒真。
- */
- test("省份归属按层级取最近「省」祖先,⛔ 一路走到「全网」根", () => {
- const tree = {
- ...data,
- regions: [
- { id: "all", name: "全网", parent: null, level: null },
- { id: "sh", name: "上海市", parent: "all", level: 0 },
- { id: "sh_city", name: "市辖区", parent: "sh", level: 1 },
- { id: "sh_lg", name: "临港", parent: "sh_city", level: 2 },
- { id: "js", name: "江苏省", parent: "all", level: 0 },
- ],
- };
- assert.equal(provinceId(tree, "sh"), "sh");
- assert.equal(provinceId(tree, "sh_city"), "sh");
- assert.equal(provinceId(tree, "sh_lg"), "sh");
- assert.equal(provinceId(tree, "js"), "js");
- // 层级未下发的历史档案:退回区域直属口径(旧行为),⛔ 变成 undefined
- assert.equal(provinceId(data, "child"), "root");
- assert.equal(provinceId(data, "missing"), undefined);
- });
- test("发码起算 7 天;预览不改账号;有效期内重导不延期", () => {
- const account = { login: "a", claimStatus: "未激活", claimCode: "ORIGINAL", claimOn: "2026-10-27", claimExpireOn: "2026-11-03", createdOn: "2026-10-01" }, before = structuredClone(account);
- assert.equal(claimState(account, "2026-10-27"), "未激活");
- const exported = deliveredClaim(account, "2026-10-27", () => "NEW");
- assert.deepEqual(account, before);
- assert.equal(exported.claimCode, "ORIGINAL"); assert.equal(exported.claimExpireOn, "2026-11-03");
- const repeated = deliveredClaim(exported, "2026-10-28", () => "UNUSED");
- assert.equal(repeated.claimCode, "ORIGINAL"); assert.equal(repeated.claimExpireOn, exported.claimExpireOn);
- assert.equal(claimState(exported, "2026-11-03"), "未激活");
- });
- test("过期交付作废原码;已激活不能导出;有效期 1–90 天", () => {
- const old = { login: "b", claimStatus: "未激活", claimCode: "OLD", claimExpireOn: "2026-10-26" };
- assert.equal(claimState(old, "2026-10-27"), "已过期");
- const replaced = deliveredClaim(old, "2026-10-27", () => "NEW");
- assert.equal(replaced.claimCode, "NEW"); assert.equal(replaced.claimExpireOn, "2026-11-03"); assert.equal(old.claimCode, "OLD");
- assert.throws(() => deliveredClaim({ ...old, claimStatus: "已激活" }, "2026-10-27"));
- for (const days of [0, 91, 1.5, NaN]) assert.throws(() => addClaimDays("2026-10-27", days));
- assert.equal(addClaimDays("2026-12-31", 1), "2027-01-01"); assert.match(createClaimCode(), /^[A-HJ-NP-Z2-9]{10}$/);
- });
- test("档案、账号、审计原子保存;存储失败回滚且不污染内存账号", () => {
- const values = new Map(); let fail = true;
- globalThis.window = { localStorage: { getItem: (key) => values.get(key) ?? null, removeItem: (key) => values.delete(key), setItem: (key, value) => { if (key === "oss-customer-audit-v1" && fail) throw new Error("quota"); values.set(key, value); } } };
- assert.throws(() => commitCustomerBundle([{ no: "new" }], { new: { login: "new" } }, []));
- assert.equal(values.size, 0); assert.equal(readCustomerMasterAccount("new"), undefined);
- fail = false; commitCustomerBundle([{ no: "new" }], { new: { login: "new" } }, []);
- assert.equal(readCustomers()[0].no, "new"); assert.equal(readCustomerMasterAccount("new").login, "new");
- });
- test("生成真实 XLSX,号码与类公式字符串都写为文本", () => {
- const bytes = textWorkbook([["交付说明"], ["主体号", "手机号", "名称"], ["KL-2026-000037", "13900009999", "=SUM(1,2)<&"]]);
- assert.equal(new DataView(bytes.buffer).getUint32(0, true), 0x04034b50);
- const content = new TextDecoder().decode(bytes);
- assert.ok(content.includes('t="inlineStr"')); assert.ok(content.includes("=SUM(1,2)<&")); assert.ok(!content.includes("<f>"));
- if (process.env.CUSTOMER_XLSX_FIXTURE) writeFileSync(process.env.CUSTOMER_XLSX_FIXTURE, bytes);
- });
- test("导入批次仅取成功且已关联的客户,去重并与区域范围取交集", () => {
- const records = [{ no: "a", regionId: "child" }, { no: "b", regionId: "other" }, { no: "c", regionId: "child" }];
- const rows = [{ ok: true, customerNo: "a" }, { ok: true, customerNo: "a" }, { ok: false, customerNo: "c" }, { ok: true, customerNo: "missing" }, { ok: true, customerNo: "b" }, { ok: true }];
- assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "batch", rows }).map((row) => row.no), ["a"]);
- assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "region", regionIds: ["other"] }), []);
- assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "region", regionIds: ["child"] }).map((row) => row.no), ["a", "c"]);
- });
- test("账号列表收窄导出范围:只取主体为客户且命中本轮主体号的账号,去重且⛔ 越界", () => {
- const account = (userId, subjectType, subjectId) => ({ user_id: userId, display_name: null, username: `登录${userId}`, mobile: "138****0000", role_code: "customer_admin", subject_type: subjectType, subject_id: subjectId, account_kind: "primary", status: "active", activation_status: "issued", delivered_at: null, activated_at: null, pwd_set_at: null, expire_date: null, created_at: null });
- const accounts = [account("u-a", "customer", "a"), account("u-a2", "customer", "a"), account("u-b", "customer", "b"), account("u-t", "ent_team", "a"), account("u-c", "customer", "out-of-scope")];
- assert.deepEqual(claimExportUserIds(accounts, ["a", "b"]), ["u-a", "u-a2", "u-b"]);
- assert.deepEqual(claimExportUserIds(accounts, ["a"]), ["u-a", "u-a2"]);
- assert.deepEqual(claimExportUserIds(accounts, []), []);
- assert.deepEqual(claimExportUserIds([], ["a"]), []);
- });
- test("交付文件、持久化账号保持一致,已激活与无主账号排除;重导保留截止日", () => {
- const customer = (no) => ({ no, name: `演示客户${no}`, regionPath: "演示区域" });
- const records = ["new", "expired", "valid", "active", "missing"].map(customer);
- const base = { login: "fixture", createdOn: "2026-10-27", claimStatus: "未激活" };
- const accounts = { new: { ...base, claimCode: "FIRST-CODE" }, expired: { ...base, claimCode: "EXPIRED-CODE", claimExpireOn: "2026-10-26" }, valid: { ...base, claimCode: "VALID-CODE", claimExpireOn: "2026-11-01" }, active: { ...base, claimStatus: "已激活" } };
- const before = structuredClone(accounts);
- const exported = prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "both");
- assert.deepEqual(accounts, before); assert.equal(exported.count, 3); assert.equal(exported.initial, 1); assert.equal(exported.expired, 1); assert.equal(exported.carried, 1);
- assert.notEqual(exported.masters.expired.claimCode, "EXPIRED-CODE");
- assert.equal(exported.masters.valid.claimExpireOn, "2026-11-01");
- assert.equal(exported.masters.new.claimExpireOn, "2026-11-03");
- const xml = new TextDecoder().decode(exported.bytes);
- for (const account of Object.values(exported.masters)) assert.ok(xml.includes(account.claimCode));
- assert.ok(!xml.includes("EXPIRED-CODE")); assert.ok(!xml.includes("演示客户active")); assert.ok(!xml.includes("演示客户missing"));
- assert.equal(prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "expired").count, 1);
- assert.equal(prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "pending").count, 2);
- const repeated = prepareClaimExport(records, (no) => exported.masters[no], "2026-10-28", "both");
- for (const no of Object.keys(exported.masters)) { assert.equal(repeated.masters[no].claimCode, exported.masters[no].claimCode); assert.equal(repeated.masters[no].claimExpireOn, exported.masters[no].claimExpireOn); }
- assert.throws(() => prepareClaimExport([customer("active")], (no) => accounts[no], "2026-10-27", "both"));
- if (process.env.CUSTOMER_CLAIM_FIXTURE) writeFileSync(process.env.CUSTOMER_CLAIM_FIXTURE, exported.bytes);
- });
- test("D-64:激活码交付文件=本次应答明文,字段缺失回「—」,未留痕告警写进首行", () => {
- const result = {
- status: "ok",
- validity: "all",
- write_capability: true,
- total: 2,
- items: [
- { user_id: "u-1", plaintext: "PLAIN-038XK9F2Q", purpose: "activate", expires_at: "2026-11-22T09:03:23Z", reissued: false },
- { user_id: "u-2", plaintext: "SECOND-CODE" },
- ],
- };
- const owners = new Map([["u-1", "klt_cust_a · 演示客户A"]]);
- const file = codeExportWorkbook(result, owners, new Date(2026, 10, 15, 9, 3, 7));
- assert.match(file.filename, /^激活码清单_20261115-090307\.xlsx$/);
- assert.equal(file.count, 2);
- const xml = new TextDecoder().decode(file.bytes);
- assert.ok(xml.includes("PLAIN-038XK9F2Q") && xml.includes("SECOND-CODE"));
- assert.ok(xml.includes("klt_cust_a · 演示客户A"));
- assert.ok(xml.includes("激活码明文"));
- assert.ok(xml.includes("作废旧码再发新码"));
- const missing = codeExportWorkbook({ status: "ok", total: 0, items: [] });
- assert.ok(new TextDecoder().decode(missing.bytes).includes("audit_written"));
- });
- test("下载入口使用真实文件 Blob 与 XLSX 文件名,点击后释放链接", async () => {
- const originalDocument = globalThis.document, originalWindow = globalThis.window;
- const create = URL.createObjectURL, revoke = URL.revokeObjectURL;
- let capturedBlob, url, clicked = 0, removed = 0, revokeUrl, cleanup;
- const anchor = { href: "", download: "", click() { clicked++; }, remove() { removed++; } };
- globalThis.document = { createElement: () => anchor, body: { append: (element) => assert.equal(element, anchor) } };
- globalThis.window = { setTimeout: (callback) => { cleanup = callback; } };
- URL.createObjectURL = (blob) => { capturedBlob = blob; return url = "blob:test-file"; };
- URL.revokeObjectURL = (value) => { revokeUrl = value; };
- try {
- const bytes = textWorkbook([["交付说明"], ["客户主体号"], ["KL-2026-000037"]]);
- downloadBlob(new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), "客户激活码.xlsx");
- assert.equal(anchor.href, url); assert.equal(anchor.download, "客户激活码.xlsx"); assert.equal(clicked, 1); assert.equal(removed, 1);
- assert.equal(capturedBlob.type, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
- assert.deepEqual(new Uint8Array(await capturedBlob.arrayBuffer()), bytes); cleanup(); assert.equal(revokeUrl, url);
- } finally { globalThis.document = originalDocument; globalThis.window = originalWindow; URL.createObjectURL = create; URL.revokeObjectURL = revoke; }
- });
- // 导出激活码新契约(`account/export_codes@v1`/`import_batch/export_codes@v1` 已接平台 bootstrap_credential/export@v1):
- // 应答回 items[] 明文清单,明文只随本次应答回显一次;后端不再回 capability_pending。
- const codesPayload = (overrides = {}) => ({
- status: "ok", scope_type: "end_user", scope_id: "376985101906509824", validity: "valid",
- user_count: 2, user_ids: ["u-1", "u-2"], total: 2,
- items: [
- { id: "c-1", user_id: "u-1", purpose: "activate", plaintext: "KLT-AAAA-1111", expires_at: "2026-11-22T00:00:00Z", reissued: false },
- { id: "c-2", user_id: "u-2", purpose: "activate", plaintext: "KLT-BBBB-2222", expires_at: "2026-12-01T00:00:00Z", reissued: true, channel: "app" },
- ],
- chunks: 1, pages: 1, reissued: 0, kept: 2, revoked: 0,
- write_capability: false, export_mode: "read", plaintext_once: true,
- plaintext_note: "明文只随本次应答出现一次,平台侧不落库 ⇒ 请立即分发或安全保存",
- audit_written: true,
- audit_note: "已写 bos_audit_log(bos.*.export_codes:validity=valid/user_count=2/items=2/export_mode=read)",
- ...overrides,
- });
- test("明文清单渲染口径:明文取 items.plaintext 原样,只回显一次提示用后端 plaintext_note", () => {
- const view = codeExportView(codesPayload());
- assert.deepEqual(view.items.map((item) => item.plaintext), ["KLT-AAAA-1111", "KLT-BBBB-2222"]);
- assert.equal(view.total, 2);
- assert.equal(view.empty, false);
- assert.match(view.onceNote, /只随本次应答出现一次/);
- assert.deepEqual(view.warnings, []);
- // 平台原样转发的附加字段保留可用,⛔ 前端裁剪
- assert.equal(view.items[1].channel, "app");
- });
- test("只回显一次提示:plaintext_note 缺失时兜底,plaintext_once=false 时不宣称只回显一次", () => {
- const { plaintext_note: _note, ...withoutNote } = codesPayload();
- assert.match(codeExportView(withoutNote).onceNote, /请立即分发或安全保存/);
- assert.equal(codeExportView(codesPayload({ plaintext_once: false })).onceNote, "");
- });
- test("写操作与审计留痕如实提示:write_capability/export_mode=write 说明换新,audit_written=false 只说未留痕", () => {
- const view = codeExportView(codesPayload({
- validity: "expired", write_capability: true, export_mode: "write",
- reissued: 1, kept: 0, revoked: 1, audit_written: false,
- audit_note: "本次未写入审计留痕(audit_written=false),请自行留存本次分发记录",
- }));
- assert.equal(view.warnings.length, 2);
- assert.match(view.warnings[0], /写操作/);
- assert.match(view.warnings[0], /validity=expired/);
- assert.match(view.warnings[0], /export_mode=write/);
- assert.match(view.warnings[0], /revoked=1/);
- assert.match(view.warnings[1], /未写入审计留痕/);
- assert.ok(!view.warnings.some((text) => /已写 bos_audit_log|已留痕/.test(text)), "⛔ 未留痕时声称已留痕");
- });
- test("审计留痕严格口径:后端漏回 audit_written 也按「留痕未确认」提示,⛔ 当成已留痕", () => {
- const { audit_written: _audit, audit_note: _note, ...withoutAudit } = codesPayload();
- const missing = codeExportView(withoutAudit);
- assert.equal(missing.warnings.length, 1);
- assert.match(missing.warnings[0], /未回 audit_written/);
- assert.match(missing.warnings[0], /未确认/);
- assert.ok(!missing.warnings.some((text) => /已写 bos_audit_log|已留痕/.test(text)), "⛔ 拿不到证据就当已留痕");
- // null 同样按未确认处理(后端整段漏字段)
- assert.match(codeExportView(codesPayload({ audit_written: null, audit_note: undefined })).warnings[0], /未回 audit_written/);
- // 显式 true 才不提(读路径无写操作告警)
- assert.deepEqual(codeExportView(codesPayload({ audit_written: true })).warnings, []);
- });
- test("空 items=本次无可导出明文(空态),⛔ 当成导出成功有数据", () => {
- const view = codeExportView(codesPayload({ total: 0, items: [], kept: 0, user_count: 0 }));
- assert.equal(view.empty, true);
- assert.equal(view.total, 0);
- assert.equal(view.onceNote, "");
- assert.equal(codeExportView(null).empty, true);
- });
- test("平台未回字段显示「—」⛔ 猜值;剪贴板不可用时复制如实失败", async () => {
- assert.equal(codeExportCell(undefined), "—");
- assert.equal(codeExportCell(null), "—");
- assert.equal(codeExportCell(""), "—");
- assert.equal(codeExportCell("valid"), "valid");
- assert.equal(await copyPlainText("KLT-AAAA-1111"), false);
- });
|