| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194 |
- import type { AccountListRow, ExportCodeItem, ExportResult } from "./api/types";
- import type { CustomerRecord, CustomerMasterAccount } from "./customer-records";
- import { claimMatches, claimState, customerRegionId, deliveredClaim, onboardingCustomers, type ClaimFilter } from "./customer-onboarding.ts";
- import type { OrganizationData } from "./organization-demo";
- import type { DemoIdentity } from "./demo-identities";
- import { textWorkbook } from "./xlsx-export.ts";
- export type ClaimExportScope = { mode: "region"; regionIds: string[] } | { mode: "batch"; rows: { ok: boolean; customerNo?: string }[] };
- export function claimExportCustomers(records: CustomerRecord[], data: OrganizationData, identity: DemoIdentity | null, scope: ClaimExportScope) {
- const nos = new Set(scope.mode === "batch" ? scope.rows.filter((row) => row.ok && row.customerNo).map((row) => row.customerNo) : []);
- return onboardingCustomers(records, data, identity).filter((customer) => scope.mode === "region" ? scope.regionIds.includes(customerRegionId(customer, data) || "") : nos.has(customer.no));
- }
- /**
- * `/account/get_list@v1` 的账号行 → 本轮导出用的 `user_ids`(`/account/export_codes` 的必填入参)。
- *
- * 只取主体=customer 且 `subject_id` 命中本轮客户主体号的账号,去重后返回;
- * ⛔ 把整页账号原样交给导出接口=越界导出。
- */
- export function claimExportUserIds(accounts: AccountListRow[], customerIds: Iterable<string>) {
- const scoped = new Set(customerIds);
- return [...new Set(accounts
- .filter((account) => account.subject_type === "customer" && scoped.has(account.subject_id))
- .map((account) => account.user_id))];
- }
- /** `plaintext_note` 缺失时的兜底话术(语义=明文只回显一次,须立即分发或安全保存)。 */
- export const CODE_EXPORT_ONCE_NOTE = "明文只随本次应答出现一次,平台侧不落库 ⇒ 请立即分发或安全保存";
- /**
- * 交付设置(状态筛选)→ 平台 `validity` 的选项口径(D-66:标签逐字=手册用词,标签自陈是否写操作)。
- * 底层映射⛔ 改:`both→all`/`pending→valid`/`expired→expired`(映射本身是对的,错在旧标签)。
- */
- export const CLAIM_VALIDITY_OPTIONS: { value: ClaimFilter; label: string; hint: string; write: boolean }[] = [
- { value: "both", label: "未激活(含凭证已过期)(默认)", hint: "写操作:其中凭证已过期的,平台侧先作废旧码再发新码", write: true },
- { value: "pending", label: "只导凭证仍有效", hint: "只读:不作废旧码、不延长截止日", write: false },
- { value: "expired", label: "只导凭证已过期", hint: "写操作:旧码立即作废并发新码", write: true },
- ];
- /** 交付设置各选项生效后的说明话术(含 `validity` 真值,⛔ 让标签与生效语义错位)。 */
- export function claimValidityNote(filter: ClaimFilter): string {
- if (filter === "pending") return "「只导凭证仍有效」按 validity=valid 只读导出:仍有效的码原样回显,不作废旧码、不延长截止日。";
- return filter === "expired"
- ? "「只导凭证已过期」按 validity=expired 导出=写操作:平台侧先作废旧码再发新码,下列明文=换新后的码,只随本次应答回显一次。"
- : "「未激活(含凭证已过期)」按 validity=all 导出=写操作:其中凭证已过期的,平台侧先作废旧码再发新码;仍有效的沿用原码与原截止日。是否真的发生换新以本次应答 write_capability/reissued 为准。";
- }
- /** 一客户多账号时的激活态汇总(D-62:⛔ 只看首行、⛔ 把「后端未回激活态」猜成未激活)。 */
- export type CustomerActivation = {
- accounts: AccountListRow[];
- /** 任一账号 `activation_status === "activated"` ⇒ 该客户按已激活计(⛔ 计入未激活家数)。 */
- activated: boolean;
- /** 后端回了激活态的账号(去重、原值),供状态列如实展示。 */
- knownStatuses: string[];
- /** 后端未回激活态(无 `bos_account_ext` 档)的账号数。 */
- unknownCount: number;
- /** 未激活(无任何账号 activated)且存在已过截止日的账号。 */
- expired: boolean;
- };
- /** 同一客户的账号行 → 激活态汇总:已激活优先,状态未知单独计数,⛔ 取首行定生死。 */
- export function activationOfCustomer(accounts: AccountListRow[], today: string): CustomerActivation {
- return {
- accounts,
- activated: accounts.some((account) => account.activation_status === "activated"),
- knownStatuses: [...new Set(accounts.map((account) => account.activation_status).filter((status): status is string => Boolean(status)))],
- unknownCount: accounts.filter((account) => !account.activation_status).length,
- expired: accounts.some((account) => account.activation_status !== "activated" && account.expire_date && account.expire_date < today),
- };
- }
- /** 账号行 → 客户主体号 → 激活态汇总(只统计主体=customer 的成员账号)。 */
- export function activationByCustomer(accounts: AccountListRow[], today: string): Map<string, CustomerActivation> {
- const grouped = new Map<string, AccountListRow[]>();
- for (const account of accounts) {
- if (account.subject_type !== "customer") continue;
- const list = grouped.get(account.subject_id);
- if (list) list.push(account); else grouped.set(account.subject_id, [account]);
- }
- return new Map([...grouped].map(([id, list]) => [id, activationOfCustomer(list, today)]));
- }
- /**
- * 客户主体维度的激活态家数口径(D-62/D-63:家数=客户主体去重,账号数另算)。
- * * `inactive`:无任何账号 activated 且至少有一个账号回了激活态(有证据的未激活);
- * * `unknownState`:一个账号的激活态都没回 ⇒ 状态整体未知,⛔ 计入 `inactive`,单独如实报数;
- * * `noAccount`:该客户在 `/account/get_list` 没取到成员账号 ⇒ ⛔ 进入导出请求;
- * * `deliverable`:真正进入本次导出请求的家数=有账号且未确认已激活(含状态未知)。
- */
- export function activationHouseholds(customers: { id: string }[], byCustomer: Map<string, CustomerActivation>) {
- let inactive = 0, expired = 0, unknownState = 0, noAccount = 0, deliverable = 0;
- for (const customer of customers) {
- const state = byCustomer.get(customer.id);
- if (!state) { noAccount += 1; continue; }
- if (state.activated) continue;
- deliverable += 1;
- if (!state.knownStatuses.length) { unknownState += 1; continue; }
- inactive += 1;
- if (state.expired) expired += 1;
- }
- return { inactive, expired, unknownState, noAccount, deliverable };
- }
- /** 明文清单单元格取值:后端未回字段一律「—」,⛔ 猜值。 */
- export function codeExportCell(value: unknown): string {
- if (value === null || value === undefined || value === "") return "—";
- return typeof value === "object" ? JSON.stringify(value) : String(value);
- }
- export type CodeExportView = {
- items: ExportCodeItem[];
- total: number;
- /** 空态=后端成功但一条明文都没回(⛔ 当成「导出成功有数据」)。 */
- empty: boolean;
- /** 「明文只回显一次」提示;后端明确 `plaintext_once=false` 时不宣称只回显一次。 */
- onceNote: string;
- /** 如实提示:写操作、未写审计留痕。 */
- warnings: string[];
- };
- /**
- * 明文导出成功出参 → 页面展示口径(`account/export_codes` 与 `import_batch/export_codes` 共用)。
- *
- * 审计留痕按**严格口径**呈现:只有 `audit_written===true` 才不提;`false`=明确未留痕,
- * `undefined`/`null`(后端漏字段)=留痕**未确认**——两者都如实提示,⛔ 拿不到证据就当已留痕。
- */
- export function codeExportView(result: ExportResult | null): CodeExportView {
- const items = result?.items ?? [];
- const warnings: string[] = [];
- if (result?.write_capability) warnings.push(`本次是写操作(validity=${codeExportCell(result.validity)}):平台侧先作废旧码再发新码,下列明文=换新后的码。`);
- if (result && result.audit_written !== true) {
- warnings.push(result.audit_written === false
- ? "本次未写入审计留痕(后端 audit_written=false),请自行留存本次分发记录。"
- : "本次应答未回 audit_written ⇒ 审计是否留痕未确认,请自行留存本次分发记录。");
- }
- return {
- items,
- total: typeof result?.total === "number" ? result.total : items.length,
- empty: items.length === 0,
- onceNote: items.length && result?.plaintext_once !== false ? (result?.plaintext_note?.trim() || CODE_EXPORT_ONCE_NOTE) : "",
- warnings,
- };
- }
- /** 复制到剪贴板:浏览器不支持或未授权时回 false(⛔ 谎称已复制)。 */
- export async function copyPlainText(text: string): Promise<boolean> {
- try {
- await navigator.clipboard.writeText(text);
- return true;
- } catch {
- return false;
- }
- }
- /**
- * 激活码明文清单 → `.xlsx` 字节(D-64:交付形态=文件下载,手册 01 册 §导出与导入动作/09 册 §16.1)。
- *
- * 口径:
- * * 文件内容=**本次应答**的 `items[]` 明文,字段与在线表格同一真源(`codeExportCell`,缺失=`—`);
- * * 首行写状态与写口径提示(含 `audit_written !== true` 的留痕告警),使离线文件自解释;
- * * ⛔ 写 localStorage/IndexedDB/任何前端存储——只有用户点「下载」才落盘,落盘后由使用者自行保管;
- * * 文件名带时间戳(`激活码清单_YYYYMMDD-HHmmss.xlsx`),与在线清单同属一次性会话产物。
- */
- export function codeExportWorkbook(result: ExportResult, owners?: Map<string, string>, generatedAt: Date = new Date()) {
- const view = codeExportView(result);
- const hint = `激活码明文只随本次导出应答回显一次;写入文件后请自行妥善保管,本系统不保留副本。状态 ${codeExportCell(result.status)}${view.warnings.length ? `;${view.warnings.join(";")}` : ""}`;
- const rows: string[][] = [
- [hint],
- ["账号 / 客户", "user_id", "用途", "截止日", "激活码明文", "本条性质"],
- ...view.items.map((item) => [
- owners?.get(item.user_id ?? "") ?? codeExportCell(item.user_id),
- codeExportCell(item.user_id),
- codeExportCell(item.purpose),
- codeExportCell(item.expires_at),
- codeExportCell(item.plaintext),
- item.reissued ? "换新码" : "在用的码",
- ]),
- ];
- return { bytes: textWorkbook(rows, "激活码清单"), filename: `激活码清单_${fileStamp(generatedAt)}.xlsx`, count: view.total };
- }
- function fileStamp(d: Date) {
- const p = (n: number) => String(n).padStart(2, "0");
- return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
- }
- /** 只准备文件与交付结果,不持久化。确认导出后,调用方将账号与审计一次提交。 */
- export function prepareClaimExport(customers: CustomerRecord[], readAccount: (no: string) => CustomerMasterAccount | undefined, today: string, filter: ClaimFilter) {
- const eligible = customers.flatMap((customer) => { const account = readAccount(customer.no); return account && claimMatches(claimState(account, today), filter) ? [{ customer, account }] : []; });
- if (!eligible.length) throw new Error("当前范围没有可导出的激活码");
- const masters = Object.fromEntries(eligible.map(({ customer, account }) => [customer.no, deliveredClaim(account, today)]));
- 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]; });
- const bytes = textWorkbook([["激活码仅供线下交付。发码时起算 7 天;有效期内重导沿用原码与截止日,过期后导出换码。"], ["客户主体号", "客户名称", "所属区域", "登录名", "绑定手机号", "激活码", "有效期截止日", "激活状态", "开通时间"], ...rows]);
- const expired = eligible.filter(({ account }) => claimState(account, today) === "已过期").length;
- const initial = eligible.filter(({ account }) => !account.claimExpireOn).length;
- return { bytes, masters, count: eligible.length, expired, initial, carried: eligible.length - expired - initial };
- }
|