import { initialBillLines, initialStatements, lastClosedDemoMonth, type DemoBillLine, type DemoStatementRow } from "./settlement-demo.ts"; import { commitCustomerBundle } from "./customer-records.ts"; import { customerAudit, readCustomerAudit } from "./customer-delivery-store.ts"; import type { DemoIdentity } from "./demo-identities"; const key = "oss-demo-settlement-retries-v2"; type Retry = { partyId: string; from?: string; month?: string; to: string; by: string; at: string }; function readRetries(): Retry[] { try { const value: unknown = JSON.parse(localStorage.getItem(key) ?? "[]"); return Array.isArray(value) ? value : []; } catch { return []; } } function uncoveredLines(statements: DemoStatementRow[], lines: DemoBillLine[], partyId: string, month: string) { const covered = new Set(statements .filter((row) => row.partyId === partyId && row.month === month && (row.status === "已执行" || row.status === "待执行")) .flatMap((row) => row.lines)); return lines.filter((line) => line.party.id === partyId && line.row.month === month && !covered.has(line)); } export function readSettlementLedger() { const statements = [...initialStatements]; const lines = [...initialBillLines]; for (const retry of readRetries()) { const source = statements.find((row) => row.no === retry.from && row.partyId === retry.partyId && row.status === "执行失败"); const month = retry.month ?? source?.month; if (!month || statements.some((row) => row.no === retry.to)) continue; // 兼容旧版只保存原批次编号的补跑记录。 const candidates = retry.month ? uncoveredLines(statements, lines, retry.partyId, month) : source?.lines ?? []; if (!candidates.length) continue; const party = candidates[0].party; const reassigned = candidates.map((line): DemoBillLine => { const next = { ...line, row: { ...line.row, statementNo: retry.to, statementStatus: "已执行" as const } }; const position = lines.indexOf(line); if (position >= 0) lines[position] = next; return next; }); const failed = statements.filter((row) => row.partyId === retry.partyId && row.month === month && row.status === "执行失败"); for (const row of failed) { statements[statements.indexOf(row)] = { ...row, status: "已作废", replacementNo: retry.to, lines: [], lineCount: 0 }; } const bases = new Map(candidates.map((line) => [JSON.stringify([line.row.customer, line.row.order]), line.row.base])); statements.push({ no: retry.to, partyId: party.id, partyName: party.name, partyType: party.type, month, base: [...bases.values()].reduce((sum, value) => sum + value, 0), amount: reassigned.reduce((sum, line) => sum + line.row.amount, 0), dayText: source?.dayText ?? failed[0]?.dayText ?? retry.at.slice(0, 10), by: retry.by, trigger: "人工", status: "已执行", sourceNo: source?.no ?? failed[0]?.no, lines: reassigned, lineCount: reassigned.length, executedAt: retry.at, warning: "按该账期冻结的金额和分成口径补跑。", }); } const executed = new Set(statements.filter((row) => row.status === "已执行").flatMap((row) => row.lines)); return { statements, lines, executed }; } export function retryStatement(partyId: string, no: string, identity: DemoIdentity | null) { if (identity && identity.role !== "admin") throw new Error("仅总运营可补跑对账批次。"); const { statements } = readSettlementLedger(); const row = statements.find((item) => item.partyId === partyId && item.no === no); if (!row || row.status !== "执行失败") throw new Error("当前批次已处理或不可补跑。"); return runStatementMonth(partyId, row.month, identity, no); } export function runStatementMonth(partyId: string, month: string, identity: DemoIdentity | null, from?: string) { if (identity && identity.role !== "admin") throw new Error("仅总运营可补跑对账批次。"); if (!/^\d{4}-(0[1-9]|1[0-2])$/.test(month) || month > lastClosedDemoMonth) throw new Error("请选择已结束的自然月。"); const { statements, lines } = readSettlementLedger(); const candidates = uncoveredLines(statements, lines, partyId, month); if (!candidates.length) throw new Error("该分成方本月没有可补跑的明细。请核对应收记录和已有批次。"); const failed = statements.filter((row) => row.partyId === partyId && row.month === month && row.status === "执行失败"); const prefix = from ?? failed[0]?.no; const base = prefix ? `${prefix}-R` : `DZD-${lastClosedDemoMonth.replaceAll("-", "")}-RG`; let to = base; for (let suffix = 2; statements.some((item) => item.no === to); suffix++) to = `${base}${suffix}`; const replaced = failed.length ? `,原失败批次 ${failed.map((row) => row.no).join("、")} 作废` : ""; const audit = customerAudit(identity, "新增", `对账清单 / ${to}`, `人工补跑 ${candidates[0].party.name} ${month},生成 ${candidates.length} 条明细${replaced}。`); const retries = [...readRetries(), { partyId, month, from: prefix, to, by: audit.actor, at: audit.at }]; commitCustomerBundle(null, {}, [audit, ...readCustomerAudit()], [[key, JSON.stringify(retries)]]); return to; }