customer-claim-export.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. import type { AccountListRow, ExportCodeItem, ExportResult } from "./api/types";
  2. import type { CustomerRecord, CustomerMasterAccount } from "./customer-records";
  3. import { claimMatches, claimState, customerRegionId, deliveredClaim, onboardingCustomers, type ClaimFilter } from "./customer-onboarding.ts";
  4. import type { OrganizationData } from "./organization-demo";
  5. import type { DemoIdentity } from "./demo-identities";
  6. import { textWorkbook } from "./xlsx-export.ts";
  7. export type ClaimExportScope = { mode: "region"; regionIds: string[] } | { mode: "batch"; rows: { ok: boolean; customerNo?: string }[] };
  8. export function claimExportCustomers(records: CustomerRecord[], data: OrganizationData, identity: DemoIdentity | null, scope: ClaimExportScope) {
  9. const nos = new Set(scope.mode === "batch" ? scope.rows.filter((row) => row.ok && row.customerNo).map((row) => row.customerNo) : []);
  10. return onboardingCustomers(records, data, identity).filter((customer) => scope.mode === "region" ? scope.regionIds.includes(customerRegionId(customer, data) || "") : nos.has(customer.no));
  11. }
  12. /**
  13. * `/account/get_list@v1` 的账号行 → 本轮导出用的 `user_ids`(`/account/export_codes` 的必填入参)。
  14. *
  15. * 只取主体=customer 且 `subject_id` 命中本轮客户主体号的账号,去重后返回;
  16. * ⛔ 把整页账号原样交给导出接口=越界导出。
  17. */
  18. export function claimExportUserIds(accounts: AccountListRow[], customerIds: Iterable<string>) {
  19. const scoped = new Set(customerIds);
  20. return [...new Set(accounts
  21. .filter((account) => account.subject_type === "customer" && scoped.has(account.subject_id))
  22. .map((account) => account.user_id))];
  23. }
  24. /** `plaintext_note` 缺失时的兜底话术(语义=明文只回显一次,须立即分发或安全保存)。 */
  25. export const CODE_EXPORT_ONCE_NOTE = "明文只随本次应答出现一次,平台侧不落库 ⇒ 请立即分发或安全保存";
  26. /**
  27. * 交付设置(状态筛选)→ 平台 `validity` 的选项口径(D-66:标签逐字=手册用词,标签自陈是否写操作)。
  28. * 底层映射⛔ 改:`both→all`/`pending→valid`/`expired→expired`(映射本身是对的,错在旧标签)。
  29. */
  30. export const CLAIM_VALIDITY_OPTIONS: { value: ClaimFilter; label: string; hint: string; write: boolean }[] = [
  31. { value: "both", label: "未激活(含凭证已过期)(默认)", hint: "写操作:其中凭证已过期的,平台侧先作废旧码再发新码", write: true },
  32. { value: "pending", label: "只导凭证仍有效", hint: "只读:不作废旧码、不延长截止日", write: false },
  33. { value: "expired", label: "只导凭证已过期", hint: "写操作:旧码立即作废并发新码", write: true },
  34. ];
  35. /** 交付设置各选项生效后的说明话术(含 `validity` 真值,⛔ 让标签与生效语义错位)。 */
  36. export function claimValidityNote(filter: ClaimFilter): string {
  37. if (filter === "pending") return "「只导凭证仍有效」按 validity=valid 只读导出:仍有效的码原样回显,不作废旧码、不延长截止日。";
  38. return filter === "expired"
  39. ? "「只导凭证已过期」按 validity=expired 导出=写操作:平台侧先作废旧码再发新码,下列明文=换新后的码,只随本次应答回显一次。"
  40. : "「未激活(含凭证已过期)」按 validity=all 导出=写操作:其中凭证已过期的,平台侧先作废旧码再发新码;仍有效的沿用原码与原截止日。是否真的发生换新以本次应答 write_capability/reissued 为准。";
  41. }
  42. /** 一客户多账号时的激活态汇总(D-62:⛔ 只看首行、⛔ 把「后端未回激活态」猜成未激活)。 */
  43. export type CustomerActivation = {
  44. accounts: AccountListRow[];
  45. /** 任一账号 `activation_status === "activated"` ⇒ 该客户按已激活计(⛔ 计入未激活家数)。 */
  46. activated: boolean;
  47. /** 后端回了激活态的账号(去重、原值),供状态列如实展示。 */
  48. knownStatuses: string[];
  49. /** 后端未回激活态(无 `bos_account_ext` 档)的账号数。 */
  50. unknownCount: number;
  51. /** 未激活(无任何账号 activated)且存在已过截止日的账号。 */
  52. expired: boolean;
  53. };
  54. /** 同一客户的账号行 → 激活态汇总:已激活优先,状态未知单独计数,⛔ 取首行定生死。 */
  55. export function activationOfCustomer(accounts: AccountListRow[], today: string): CustomerActivation {
  56. return {
  57. accounts,
  58. activated: accounts.some((account) => account.activation_status === "activated"),
  59. knownStatuses: [...new Set(accounts.map((account) => account.activation_status).filter((status): status is string => Boolean(status)))],
  60. unknownCount: accounts.filter((account) => !account.activation_status).length,
  61. expired: accounts.some((account) => account.activation_status !== "activated" && account.expire_date && account.expire_date < today),
  62. };
  63. }
  64. /** 账号行 → 客户主体号 → 激活态汇总(只统计主体=customer 的成员账号)。 */
  65. export function activationByCustomer(accounts: AccountListRow[], today: string): Map<string, CustomerActivation> {
  66. const grouped = new Map<string, AccountListRow[]>();
  67. for (const account of accounts) {
  68. if (account.subject_type !== "customer") continue;
  69. const list = grouped.get(account.subject_id);
  70. if (list) list.push(account); else grouped.set(account.subject_id, [account]);
  71. }
  72. return new Map([...grouped].map(([id, list]) => [id, activationOfCustomer(list, today)]));
  73. }
  74. /**
  75. * 客户主体维度的激活态家数口径(D-62/D-63:家数=客户主体去重,账号数另算)。
  76. * * `inactive`:无任何账号 activated 且至少有一个账号回了激活态(有证据的未激活);
  77. * * `unknownState`:一个账号的激活态都没回 ⇒ 状态整体未知,⛔ 计入 `inactive`,单独如实报数;
  78. * * `noAccount`:该客户在 `/account/get_list` 没取到成员账号 ⇒ ⛔ 进入导出请求;
  79. * * `deliverable`:真正进入本次导出请求的家数=有账号且未确认已激活(含状态未知)。
  80. */
  81. export function activationHouseholds(customers: { id: string }[], byCustomer: Map<string, CustomerActivation>) {
  82. let inactive = 0, expired = 0, unknownState = 0, noAccount = 0, deliverable = 0;
  83. for (const customer of customers) {
  84. const state = byCustomer.get(customer.id);
  85. if (!state) { noAccount += 1; continue; }
  86. if (state.activated) continue;
  87. deliverable += 1;
  88. if (!state.knownStatuses.length) { unknownState += 1; continue; }
  89. inactive += 1;
  90. if (state.expired) expired += 1;
  91. }
  92. return { inactive, expired, unknownState, noAccount, deliverable };
  93. }
  94. /** 明文清单单元格取值:后端未回字段一律「—」,⛔ 猜值。 */
  95. export function codeExportCell(value: unknown): string {
  96. if (value === null || value === undefined || value === "") return "—";
  97. return typeof value === "object" ? JSON.stringify(value) : String(value);
  98. }
  99. export type CodeExportView = {
  100. items: ExportCodeItem[];
  101. total: number;
  102. /** 空态=后端成功但一条明文都没回(⛔ 当成「导出成功有数据」)。 */
  103. empty: boolean;
  104. /** 「明文只回显一次」提示;后端明确 `plaintext_once=false` 时不宣称只回显一次。 */
  105. onceNote: string;
  106. /** 如实提示:写操作、未写审计留痕。 */
  107. warnings: string[];
  108. };
  109. /**
  110. * 明文导出成功出参 → 页面展示口径(`account/export_codes` 与 `import_batch/export_codes` 共用)。
  111. *
  112. * 审计留痕按**严格口径**呈现:只有 `audit_written===true` 才不提;`false`=明确未留痕,
  113. * `undefined`/`null`(后端漏字段)=留痕**未确认**——两者都如实提示,⛔ 拿不到证据就当已留痕。
  114. */
  115. export function codeExportView(result: ExportResult | null): CodeExportView {
  116. const items = result?.items ?? [];
  117. const warnings: string[] = [];
  118. if (result?.write_capability) warnings.push(`本次是写操作(validity=${codeExportCell(result.validity)}):平台侧先作废旧码再发新码,下列明文=换新后的码。`);
  119. if (result && result.audit_written !== true) {
  120. warnings.push(result.audit_written === false
  121. ? "本次未写入审计留痕(后端 audit_written=false),请自行留存本次分发记录。"
  122. : "本次应答未回 audit_written ⇒ 审计是否留痕未确认,请自行留存本次分发记录。");
  123. }
  124. return {
  125. items,
  126. total: typeof result?.total === "number" ? result.total : items.length,
  127. empty: items.length === 0,
  128. onceNote: items.length && result?.plaintext_once !== false ? (result?.plaintext_note?.trim() || CODE_EXPORT_ONCE_NOTE) : "",
  129. warnings,
  130. };
  131. }
  132. /** 复制到剪贴板:浏览器不支持或未授权时回 false(⛔ 谎称已复制)。 */
  133. export async function copyPlainText(text: string): Promise<boolean> {
  134. try {
  135. await navigator.clipboard.writeText(text);
  136. return true;
  137. } catch {
  138. return false;
  139. }
  140. }
  141. /**
  142. * 激活码明文清单 → `.xlsx` 字节(D-64:交付形态=文件下载,手册 01 册 §导出与导入动作/09 册 §16.1)。
  143. *
  144. * 口径:
  145. * * 文件内容=**本次应答**的 `items[]` 明文,字段与在线表格同一真源(`codeExportCell`,缺失=`—`);
  146. * * 首行写状态与写口径提示(含 `audit_written !== true` 的留痕告警),使离线文件自解释;
  147. * * ⛔ 写 localStorage/IndexedDB/任何前端存储——只有用户点「下载」才落盘,落盘后由使用者自行保管;
  148. * * 文件名带时间戳(`激活码清单_YYYYMMDD-HHmmss.xlsx`),与在线清单同属一次性会话产物。
  149. */
  150. export function codeExportWorkbook(result: ExportResult, owners?: Map<string, string>, generatedAt: Date = new Date()) {
  151. const view = codeExportView(result);
  152. const hint = `激活码明文只随本次导出应答回显一次;写入文件后请自行妥善保管,本系统不保留副本。状态 ${codeExportCell(result.status)}${view.warnings.length ? `;${view.warnings.join(";")}` : ""}`;
  153. const rows: string[][] = [
  154. [hint],
  155. ["账号 / 客户", "user_id", "用途", "截止日", "激活码明文", "本条性质"],
  156. ...view.items.map((item) => [
  157. owners?.get(item.user_id ?? "") ?? codeExportCell(item.user_id),
  158. codeExportCell(item.user_id),
  159. codeExportCell(item.purpose),
  160. codeExportCell(item.expires_at),
  161. codeExportCell(item.plaintext),
  162. item.reissued ? "换新码" : "在用的码",
  163. ]),
  164. ];
  165. return { bytes: textWorkbook(rows, "激活码清单"), filename: `激活码清单_${fileStamp(generatedAt)}.xlsx`, count: view.total };
  166. }
  167. function fileStamp(d: Date) {
  168. const p = (n: number) => String(n).padStart(2, "0");
  169. return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
  170. }
  171. /** 只准备文件与交付结果,不持久化。确认导出后,调用方将账号与审计一次提交。 */
  172. export function prepareClaimExport(customers: CustomerRecord[], readAccount: (no: string) => CustomerMasterAccount | undefined, today: string, filter: ClaimFilter) {
  173. const eligible = customers.flatMap((customer) => { const account = readAccount(customer.no); return account && claimMatches(claimState(account, today), filter) ? [{ customer, account }] : []; });
  174. if (!eligible.length) throw new Error("当前范围没有可导出的激活码");
  175. const masters = Object.fromEntries(eligible.map(({ customer, account }) => [customer.no, deliveredClaim(account, today)]));
  176. const rows = eligible.map(({ customer }) => { const account = masters[customer.no]; return [customer.no, customer.name, customer.regionPath, account.login, account.phone || "", account.claimCode!, account.claimExpireOn!, "未激活", account.createdOn]; });
  177. const bytes = textWorkbook([["激活码仅供线下交付。发码时起算 7 天;有效期内重导沿用原码与截止日,过期后导出换码。"], ["客户主体号", "客户名称", "所属区域", "登录名", "绑定手机号", "激活码", "有效期截止日", "激活状态", "开通时间"], ...rows]);
  178. const expired = eligible.filter(({ account }) => claimState(account, today) === "已过期").length;
  179. const initial = eligible.filter(({ account }) => !account.claimExpireOn).length;
  180. return { bytes, masters, count: eligible.length, expired, initial, carried: eligible.length - expired - initial };
  181. }