customer-onboarding.test.mjs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. import test from "node:test";
  2. import assert from "node:assert/strict";
  3. import { nextCustomerNo, normalizedIdNo, generatedCustomerLogin, validateCustomerDraft, onboardingCustomers, onboardingRegions, provinceId, claimState, addClaimDays, deliveredClaim, createClaimCode } from "../src/lib/customer-onboarding.ts";
  4. import { commitCustomerBundle, readCustomers, readCustomerMasterAccount } from "../src/lib/customer-records.ts";
  5. import { textWorkbook } from "../src/lib/xlsx-export.ts";
  6. import { claimExportCustomers, claimExportUserIds, codeExportCell, codeExportView, codeExportWorkbook, copyPlainText, prepareClaimExport } from "../src/lib/customer-claim-export.ts";
  7. import { downloadBlob } from "../src/lib/customer-delivery-store.ts";
  8. import { writeFileSync } from "node:fs";
  9. 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: [] };
  10. const regional = { role: "regAdmin", operationsTeamId: "team" };
  11. const draft = () => ({ name: "同名客户", subject: "企业", idNo: "91310115MA1K3XE71T", contact: "联系人", phone: "021-00000000", address: "演示地址", regionId: "child", operatorId: "op", teamIds: ["mt"], partnerId: "", login: "new-client", masterPhone: "", initialPassword: "", idNoBasis: "" });
  12. test("自动主体号递增、规范化识别号;同名客户可建档,识别号重复拒绝", () => {
  13. assert.equal(nextCustomerNo([{ no: "KL-2026-0008" }, { no: "KL-2026-0036" }, { no: "KL-2025-9999" }], 2026), "KL-2026-000037");
  14. assert.equal(normalizedIdNo(" 91310115 ma1k3xe71t "), "91310115MA1K3XE71T");
  15. assert.deepEqual(validateCustomerDraft(draft(), [{ no: "old", name: "同名客户", idNo: "91310115MA1K3XE72T" }], data, regional, []), {});
  16. assert.match(validateCustomerDraft(draft(), [{ no: "old", idNo: "91310115 ma1k3xe71t" }], data, regional, []).idNo, /已登记/);
  17. });
  18. test("联系人、电话、地址、运维团队必填;个人识别号与更正依据校验", () => {
  19. for (const field of ["name", "contact", "phone", "address", "regionId"]) assert.ok(validateCustomerDraft({ ...draft(), [field]: "" }, [], data, regional, [])[field]);
  20. assert.ok(validateCustomerDraft({ ...draft(), teamIds: [] }, [], data, regional, []).teamIds);
  21. assert.ok(validateCustomerDraft({ ...draft(), subject: "个人" }, [], data, regional, []).idNo);
  22. assert.equal(validateCustomerDraft({ ...draft(), subject: "个人", idNo: "31011519920817302x" }, [], data, regional, []).idNo, undefined);
  23. assert.ok(validateCustomerDraft(draft(), [], data, regional, [], { no: "old", idNo: "91310115MA1K3XE72T" }).idNoBasis);
  24. });
  25. test("登录名自动避重且可覆盖;手填账号、绑定手机号全站查重", () => {
  26. assert.equal(generatedCustomerLogin("澄澜科技有限公司", "KL-2026-000037", []), "clkj");
  27. assert.equal(generatedCustomerLogin("澄澜科技有限公司", "KL-2026-000037", [{ login: "CLKJ" }, { login: "clkj2" }]), "clkj3");
  28. assert.ok(validateCustomerDraft(draft(), [], data, regional, [{ login: "NEW-CLIENT" }]).login);
  29. assert.ok(validateCustomerDraft({ ...draft(), masterPhone: "123" }, [], data, regional, []).masterPhone);
  30. assert.ok(validateCustomerDraft({ ...draft(), masterPhone: "13900000200" }, [], data, regional, [{ phone: "13900000200" }]).masterPhone);
  31. });
  32. test("客户运营商须同省,运维团队恰好 1 支,人工初始密码限 8–32 位", () => {
  33. // 业主 2026-11-12 裁定「单支定案」:0 支/>1 支一律整笔拒绝(后端 customer.rs 同步校验)。
  34. assert.equal(validateCustomerDraft(draft(), [], data, regional, []).teamIds, undefined);
  35. assert.match(validateCustomerDraft({ ...draft(), teamIds: ["mt", "mt"] }, [], data, regional, []).teamIds, /1 支/);
  36. assert.match(validateCustomerDraft({ ...draft(), teamIds: [] }, [], data, regional, []).teamIds, /1 支/);
  37. assert.match(validateCustomerDraft({ ...draft(), regionId: "other" }, [], data, null, []).operatorId, /省份/);
  38. assert.ok(validateCustomerDraft({ ...draft(), initialPassword: "short" }, [], data, regional, []).initialPassword);
  39. assert.equal(validateCustomerDraft({ ...draft(), initialPassword: "welcome-123" }, [], data, regional, []).initialPassword, undefined);
  40. });
  41. test("区域运营只能挂载、导出本人范围及下级;其他角色不获得建档范围", () => {
  42. assert.deepEqual(onboardingRegions(data, regional), ["root", "child"]);
  43. assert.ok(validateCustomerDraft({ ...draft(), regionId: "other" }, [], data, regional, []).regionId);
  44. assert.deepEqual(onboardingCustomers([{ no: "a", regionPath: "上海市 / 浦东" }, { no: "b", regionPath: "广东" }], data, regional).map((item) => item.no), ["a"]);
  45. assert.deepEqual(onboardingCustomers([{ no: "moved", regionId: "child", regionPath: "广东" }], data, regional), []);
  46. assert.deepEqual(onboardingRegions(data, { role: "partner" }), []);
  47. });
  48. /*
  49. * 2026-11-15 实测缺陷:dev 区域树=「全网(level 为空)› 上海市/江苏省/广东省 › 市 › 区县」。
  50. * 旧的 `provinceId` 一路沿 `parent` 走到根 ⇒ 每个区域都归到「全网」,成本管理的省份下拉只剩
  51. * 一个「全网」选项、「运营商建档省份须与客户所在省份一致」校验恒真。
  52. */
  53. test("省份归属按层级取最近「省」祖先,⛔ 一路走到「全网」根", () => {
  54. const tree = {
  55. ...data,
  56. regions: [
  57. { id: "all", name: "全网", parent: null, level: null },
  58. { id: "sh", name: "上海市", parent: "all", level: 0 },
  59. { id: "sh_city", name: "市辖区", parent: "sh", level: 1 },
  60. { id: "sh_lg", name: "临港", parent: "sh_city", level: 2 },
  61. { id: "js", name: "江苏省", parent: "all", level: 0 },
  62. ],
  63. };
  64. assert.equal(provinceId(tree, "sh"), "sh");
  65. assert.equal(provinceId(tree, "sh_city"), "sh");
  66. assert.equal(provinceId(tree, "sh_lg"), "sh");
  67. assert.equal(provinceId(tree, "js"), "js");
  68. // 层级未下发的历史档案:退回区域直属口径(旧行为),⛔ 变成 undefined
  69. assert.equal(provinceId(data, "child"), "root");
  70. assert.equal(provinceId(data, "missing"), undefined);
  71. });
  72. test("发码起算 7 天;预览不改账号;有效期内重导不延期", () => {
  73. const account = { login: "a", claimStatus: "未激活", claimCode: "ORIGINAL", claimOn: "2026-10-27", claimExpireOn: "2026-11-03", createdOn: "2026-10-01" }, before = structuredClone(account);
  74. assert.equal(claimState(account, "2026-10-27"), "未激活");
  75. const exported = deliveredClaim(account, "2026-10-27", () => "NEW");
  76. assert.deepEqual(account, before);
  77. assert.equal(exported.claimCode, "ORIGINAL"); assert.equal(exported.claimExpireOn, "2026-11-03");
  78. const repeated = deliveredClaim(exported, "2026-10-28", () => "UNUSED");
  79. assert.equal(repeated.claimCode, "ORIGINAL"); assert.equal(repeated.claimExpireOn, exported.claimExpireOn);
  80. assert.equal(claimState(exported, "2026-11-03"), "未激活");
  81. });
  82. test("过期交付作废原码;已激活不能导出;有效期 1–90 天", () => {
  83. const old = { login: "b", claimStatus: "未激活", claimCode: "OLD", claimExpireOn: "2026-10-26" };
  84. assert.equal(claimState(old, "2026-10-27"), "已过期");
  85. const replaced = deliveredClaim(old, "2026-10-27", () => "NEW");
  86. assert.equal(replaced.claimCode, "NEW"); assert.equal(replaced.claimExpireOn, "2026-11-03"); assert.equal(old.claimCode, "OLD");
  87. assert.throws(() => deliveredClaim({ ...old, claimStatus: "已激活" }, "2026-10-27"));
  88. for (const days of [0, 91, 1.5, NaN]) assert.throws(() => addClaimDays("2026-10-27", days));
  89. assert.equal(addClaimDays("2026-12-31", 1), "2027-01-01"); assert.match(createClaimCode(), /^[A-HJ-NP-Z2-9]{10}$/);
  90. });
  91. test("档案、账号、审计原子保存;存储失败回滚且不污染内存账号", () => {
  92. const values = new Map(); let fail = true;
  93. 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); } } };
  94. assert.throws(() => commitCustomerBundle([{ no: "new" }], { new: { login: "new" } }, []));
  95. assert.equal(values.size, 0); assert.equal(readCustomerMasterAccount("new"), undefined);
  96. fail = false; commitCustomerBundle([{ no: "new" }], { new: { login: "new" } }, []);
  97. assert.equal(readCustomers()[0].no, "new"); assert.equal(readCustomerMasterAccount("new").login, "new");
  98. });
  99. test("生成真实 XLSX,号码与类公式字符串都写为文本", () => {
  100. const bytes = textWorkbook([["交付说明"], ["主体号", "手机号", "名称"], ["KL-2026-000037", "13900009999", "=SUM(1,2)<&"]]);
  101. assert.equal(new DataView(bytes.buffer).getUint32(0, true), 0x04034b50);
  102. const content = new TextDecoder().decode(bytes);
  103. assert.ok(content.includes('t="inlineStr"')); assert.ok(content.includes("=SUM(1,2)&lt;&amp;")); assert.ok(!content.includes("<f>"));
  104. if (process.env.CUSTOMER_XLSX_FIXTURE) writeFileSync(process.env.CUSTOMER_XLSX_FIXTURE, bytes);
  105. });
  106. test("导入批次仅取成功且已关联的客户,去重并与区域范围取交集", () => {
  107. const records = [{ no: "a", regionId: "child" }, { no: "b", regionId: "other" }, { no: "c", regionId: "child" }];
  108. const rows = [{ ok: true, customerNo: "a" }, { ok: true, customerNo: "a" }, { ok: false, customerNo: "c" }, { ok: true, customerNo: "missing" }, { ok: true, customerNo: "b" }, { ok: true }];
  109. assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "batch", rows }).map((row) => row.no), ["a"]);
  110. assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "region", regionIds: ["other"] }), []);
  111. assert.deepEqual(claimExportCustomers(records, data, regional, { mode: "region", regionIds: ["child"] }).map((row) => row.no), ["a", "c"]);
  112. });
  113. test("账号列表收窄导出范围:只取主体为客户且命中本轮主体号的账号,去重且⛔ 越界", () => {
  114. 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 });
  115. 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")];
  116. assert.deepEqual(claimExportUserIds(accounts, ["a", "b"]), ["u-a", "u-a2", "u-b"]);
  117. assert.deepEqual(claimExportUserIds(accounts, ["a"]), ["u-a", "u-a2"]);
  118. assert.deepEqual(claimExportUserIds(accounts, []), []);
  119. assert.deepEqual(claimExportUserIds([], ["a"]), []);
  120. });
  121. test("交付文件、持久化账号保持一致,已激活与无主账号排除;重导保留截止日", () => {
  122. const customer = (no) => ({ no, name: `演示客户${no}`, regionPath: "演示区域" });
  123. const records = ["new", "expired", "valid", "active", "missing"].map(customer);
  124. const base = { login: "fixture", createdOn: "2026-10-27", claimStatus: "未激活" };
  125. 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: "已激活" } };
  126. const before = structuredClone(accounts);
  127. const exported = prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "both");
  128. assert.deepEqual(accounts, before); assert.equal(exported.count, 3); assert.equal(exported.initial, 1); assert.equal(exported.expired, 1); assert.equal(exported.carried, 1);
  129. assert.notEqual(exported.masters.expired.claimCode, "EXPIRED-CODE");
  130. assert.equal(exported.masters.valid.claimExpireOn, "2026-11-01");
  131. assert.equal(exported.masters.new.claimExpireOn, "2026-11-03");
  132. const xml = new TextDecoder().decode(exported.bytes);
  133. for (const account of Object.values(exported.masters)) assert.ok(xml.includes(account.claimCode));
  134. assert.ok(!xml.includes("EXPIRED-CODE")); assert.ok(!xml.includes("演示客户active")); assert.ok(!xml.includes("演示客户missing"));
  135. assert.equal(prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "expired").count, 1);
  136. assert.equal(prepareClaimExport(records, (no) => accounts[no], "2026-10-27", "pending").count, 2);
  137. const repeated = prepareClaimExport(records, (no) => exported.masters[no], "2026-10-28", "both");
  138. 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); }
  139. assert.throws(() => prepareClaimExport([customer("active")], (no) => accounts[no], "2026-10-27", "both"));
  140. if (process.env.CUSTOMER_CLAIM_FIXTURE) writeFileSync(process.env.CUSTOMER_CLAIM_FIXTURE, exported.bytes);
  141. });
  142. test("D-64:激活码交付文件=本次应答明文,字段缺失回「—」,未留痕告警写进首行", () => {
  143. const result = {
  144. status: "ok",
  145. validity: "all",
  146. write_capability: true,
  147. total: 2,
  148. items: [
  149. { user_id: "u-1", plaintext: "PLAIN-038XK9F2Q", purpose: "activate", expires_at: "2026-11-22T09:03:23Z", reissued: false },
  150. { user_id: "u-2", plaintext: "SECOND-CODE" },
  151. ],
  152. };
  153. const owners = new Map([["u-1", "klt_cust_a · 演示客户A"]]);
  154. const file = codeExportWorkbook(result, owners, new Date(2026, 10, 15, 9, 3, 7));
  155. assert.match(file.filename, /^激活码清单_20261115-090307\.xlsx$/);
  156. assert.equal(file.count, 2);
  157. const xml = new TextDecoder().decode(file.bytes);
  158. assert.ok(xml.includes("PLAIN-038XK9F2Q") && xml.includes("SECOND-CODE"));
  159. assert.ok(xml.includes("klt_cust_a · 演示客户A"));
  160. assert.ok(xml.includes("激活码明文"));
  161. assert.ok(xml.includes("作废旧码再发新码"));
  162. const missing = codeExportWorkbook({ status: "ok", total: 0, items: [] });
  163. assert.ok(new TextDecoder().decode(missing.bytes).includes("audit_written"));
  164. });
  165. test("下载入口使用真实文件 Blob 与 XLSX 文件名,点击后释放链接", async () => {
  166. const originalDocument = globalThis.document, originalWindow = globalThis.window;
  167. const create = URL.createObjectURL, revoke = URL.revokeObjectURL;
  168. let capturedBlob, url, clicked = 0, removed = 0, revokeUrl, cleanup;
  169. const anchor = { href: "", download: "", click() { clicked++; }, remove() { removed++; } };
  170. globalThis.document = { createElement: () => anchor, body: { append: (element) => assert.equal(element, anchor) } };
  171. globalThis.window = { setTimeout: (callback) => { cleanup = callback; } };
  172. URL.createObjectURL = (blob) => { capturedBlob = blob; return url = "blob:test-file"; };
  173. URL.revokeObjectURL = (value) => { revokeUrl = value; };
  174. try {
  175. const bytes = textWorkbook([["交付说明"], ["客户主体号"], ["KL-2026-000037"]]);
  176. downloadBlob(new Blob([bytes], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }), "客户激活码.xlsx");
  177. assert.equal(anchor.href, url); assert.equal(anchor.download, "客户激活码.xlsx"); assert.equal(clicked, 1); assert.equal(removed, 1);
  178. assert.equal(capturedBlob.type, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  179. assert.deepEqual(new Uint8Array(await capturedBlob.arrayBuffer()), bytes); cleanup(); assert.equal(revokeUrl, url);
  180. } finally { globalThis.document = originalDocument; globalThis.window = originalWindow; URL.createObjectURL = create; URL.revokeObjectURL = revoke; }
  181. });
  182. // 导出激活码新契约(`account/export_codes@v1`/`import_batch/export_codes@v1` 已接平台 bootstrap_credential/export@v1):
  183. // 应答回 items[] 明文清单,明文只随本次应答回显一次;后端不再回 capability_pending。
  184. const codesPayload = (overrides = {}) => ({
  185. status: "ok", scope_type: "end_user", scope_id: "376985101906509824", validity: "valid",
  186. user_count: 2, user_ids: ["u-1", "u-2"], total: 2,
  187. items: [
  188. { id: "c-1", user_id: "u-1", purpose: "activate", plaintext: "KLT-AAAA-1111", expires_at: "2026-11-22T00:00:00Z", reissued: false },
  189. { id: "c-2", user_id: "u-2", purpose: "activate", plaintext: "KLT-BBBB-2222", expires_at: "2026-12-01T00:00:00Z", reissued: true, channel: "app" },
  190. ],
  191. chunks: 1, pages: 1, reissued: 0, kept: 2, write_capability: false, plaintext_once: true,
  192. plaintext_note: "明文只随本次应答出现一次,平台侧不落库 ⇒ 请立即分发或安全保存", audit_written: true,
  193. ...overrides,
  194. });
  195. test("明文清单渲染口径:明文取 items.plaintext 原样,只回显一次提示用后端 plaintext_note", () => {
  196. const view = codeExportView(codesPayload());
  197. assert.deepEqual(view.items.map((item) => item.plaintext), ["KLT-AAAA-1111", "KLT-BBBB-2222"]);
  198. assert.equal(view.total, 2);
  199. assert.equal(view.empty, false);
  200. assert.match(view.onceNote, /只随本次应答出现一次/);
  201. assert.deepEqual(view.warnings, []);
  202. // 平台原样转发的附加字段保留可用,⛔ 前端裁剪
  203. assert.equal(view.items[1].channel, "app");
  204. });
  205. test("只回显一次提示:plaintext_note 缺失时兜底,plaintext_once=false 时不宣称只回显一次", () => {
  206. const { plaintext_note: _note, ...withoutNote } = codesPayload();
  207. assert.match(codeExportView(withoutNote).onceNote, /请立即分发或安全保存/);
  208. assert.equal(codeExportView(codesPayload({ plaintext_once: false })).onceNote, "");
  209. });
  210. test("写操作与审计留痕如实提示:write_capability=true 说明先作废再换新码,audit_written=false 只说未留痕", () => {
  211. const view = codeExportView(codesPayload({ validity: "expired", write_capability: true, audit_written: false }));
  212. assert.deepEqual(view.warnings.map((text) => Boolean(/写操作/.test(text))), [true, false]);
  213. assert.match(view.warnings[0], /先作废旧码再发新码/);
  214. assert.match(view.warnings[0], /validity=expired/);
  215. assert.match(view.warnings[1], /未写入审计留痕/);
  216. assert.ok(!view.warnings.some((text) => /已写入审计|已留痕/.test(text)), "⛔ 未留痕时声称已留痕");
  217. });
  218. test("审计留痕严格口径:后端漏回 audit_written 也按「留痕未确认」提示,⛔ 当成已留痕", () => {
  219. const { audit_written: _audit, ...withoutAudit } = codesPayload();
  220. const missing = codeExportView(withoutAudit);
  221. assert.equal(missing.warnings.length, 1);
  222. assert.match(missing.warnings[0], /未回 audit_written/);
  223. assert.match(missing.warnings[0], /未确认/);
  224. assert.ok(!missing.warnings.some((text) => /已写入审计|已留痕/.test(text)), "⛔ 拿不到证据就当已留痕");
  225. // null 同样按未确认处理(后端整段漏字段)
  226. assert.match(codeExportView(codesPayload({ audit_written: null })).warnings[0], /未回 audit_written/);
  227. // 显式 true 才不提
  228. assert.deepEqual(codeExportView(codesPayload({ audit_written: true })).warnings, []);
  229. });
  230. test("空 items=本次无可导出明文(空态),⛔ 当成导出成功有数据", () => {
  231. const view = codeExportView(codesPayload({ total: 0, items: [], kept: 0, user_count: 0 }));
  232. assert.equal(view.empty, true);
  233. assert.equal(view.total, 0);
  234. assert.equal(view.onceNote, "");
  235. assert.equal(codeExportView(null).empty, true);
  236. });
  237. test("平台未回字段显示「—」⛔ 猜值;剪贴板不可用时复制如实失败", async () => {
  238. assert.equal(codeExportCell(undefined), "—");
  239. assert.equal(codeExportCell(null), "—");
  240. assert.equal(codeExportCell(""), "—");
  241. assert.equal(codeExportCell("valid"), "valid");
  242. assert.equal(await copyPlainText("KLT-AAAA-1111"), false);
  243. });