settlement-retries.ts 5.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import { initialBillLines, initialStatements, lastClosedDemoMonth, type DemoBillLine, type DemoStatementRow } from "./settlement-demo.ts";
  2. import { commitCustomerBundle } from "./customer-records.ts";
  3. import { customerAudit, readCustomerAudit } from "./customer-delivery-store.ts";
  4. import type { DemoIdentity } from "./demo-identities";
  5. const key = "oss-demo-settlement-retries-v2";
  6. type Retry = { partyId: string; from?: string; month?: string; to: string; by: string; at: string };
  7. function readRetries(): Retry[] {
  8. try {
  9. const value: unknown = JSON.parse(localStorage.getItem(key) ?? "[]");
  10. return Array.isArray(value) ? value : [];
  11. } catch { return []; }
  12. }
  13. function uncoveredLines(statements: DemoStatementRow[], lines: DemoBillLine[], partyId: string, month: string) {
  14. const covered = new Set(statements
  15. .filter((row) => row.partyId === partyId && row.month === month && (row.status === "已执行" || row.status === "待执行"))
  16. .flatMap((row) => row.lines));
  17. return lines.filter((line) => line.party.id === partyId && line.row.month === month && !covered.has(line));
  18. }
  19. export function readSettlementLedger() {
  20. const statements = [...initialStatements];
  21. const lines = [...initialBillLines];
  22. for (const retry of readRetries()) {
  23. const source = statements.find((row) => row.no === retry.from && row.partyId === retry.partyId && row.status === "执行失败");
  24. const month = retry.month ?? source?.month;
  25. if (!month || statements.some((row) => row.no === retry.to)) continue;
  26. // 兼容旧版只保存原批次编号的补跑记录。
  27. const candidates = retry.month ? uncoveredLines(statements, lines, retry.partyId, month) : source?.lines ?? [];
  28. if (!candidates.length) continue;
  29. const party = candidates[0].party;
  30. const reassigned = candidates.map((line): DemoBillLine => {
  31. const next = { ...line, row: { ...line.row, statementNo: retry.to, statementStatus: "已执行" as const } };
  32. const position = lines.indexOf(line);
  33. if (position >= 0) lines[position] = next;
  34. return next;
  35. });
  36. const failed = statements.filter((row) => row.partyId === retry.partyId && row.month === month && row.status === "执行失败");
  37. for (const row of failed) {
  38. statements[statements.indexOf(row)] = { ...row, status: "已作废", replacementNo: retry.to, lines: [], lineCount: 0 };
  39. }
  40. const bases = new Map(candidates.map((line) => [JSON.stringify([line.row.customer, line.row.order]), line.row.base]));
  41. statements.push({
  42. no: retry.to, partyId: party.id, partyName: party.name, partyType: party.type, month,
  43. base: [...bases.values()].reduce((sum, value) => sum + value, 0),
  44. amount: reassigned.reduce((sum, line) => sum + line.row.amount, 0),
  45. dayText: source?.dayText ?? failed[0]?.dayText ?? retry.at.slice(0, 10),
  46. by: retry.by, trigger: "人工", status: "已执行", sourceNo: source?.no ?? failed[0]?.no,
  47. lines: reassigned, lineCount: reassigned.length, executedAt: retry.at,
  48. warning: "按该账期冻结的金额和分成口径补跑。",
  49. });
  50. }
  51. const executed = new Set(statements.filter((row) => row.status === "已执行").flatMap((row) => row.lines));
  52. return { statements, lines, executed };
  53. }
  54. export function retryStatement(partyId: string, no: string, identity: DemoIdentity | null) {
  55. if (identity && identity.role !== "admin") throw new Error("仅总运营可补跑对账批次。");
  56. const { statements } = readSettlementLedger();
  57. const row = statements.find((item) => item.partyId === partyId && item.no === no);
  58. if (!row || row.status !== "执行失败") throw new Error("当前批次已处理或不可补跑。");
  59. return runStatementMonth(partyId, row.month, identity, no);
  60. }
  61. export function runStatementMonth(partyId: string, month: string, identity: DemoIdentity | null, from?: string) {
  62. if (identity && identity.role !== "admin") throw new Error("仅总运营可补跑对账批次。");
  63. if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month) || month > lastClosedDemoMonth) throw new Error("请选择已结束的自然月。");
  64. const { statements, lines } = readSettlementLedger();
  65. const candidates = uncoveredLines(statements, lines, partyId, month);
  66. if (!candidates.length) throw new Error("该分成方本月没有可补跑的明细。请核对应收记录和已有批次。");
  67. const failed = statements.filter((row) => row.partyId === partyId && row.month === month && row.status === "执行失败");
  68. const prefix = from ?? failed[0]?.no;
  69. const base = prefix ? `${prefix}-R` : `DZD-${lastClosedDemoMonth.replaceAll("-", "")}-RG`;
  70. let to = base;
  71. for (let suffix = 2; statements.some((item) => item.no === to); suffix++) to = `${base}${suffix}`;
  72. const replaced = failed.length ? `,原失败批次 ${failed.map((row) => row.no).join("、")} 作废` : "";
  73. const audit = customerAudit(identity, "新增", `对账清单 / ${to}`, `人工补跑 ${candidates[0].party.name} ${month},生成 ${candidates.length} 条明细${replaced}。`);
  74. const retries = [...readRetries(), { partyId, month, from: prefix, to, by: audit.actor, at: audit.at }];
  75. commitCustomerBundle(null, {}, [audit, ...readCustomerAudit()], [[key, JSON.stringify(retries)]]);
  76. return to;
  77. }