Files
SupplierSystem/src/utils/statementInvoiceStatus.ts
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

330 lines
12 KiB
TypeScript

export type StatementInvoiceStatus = 'pending' | 'partial' | 'invoiced';
const COVER_EPS = 0.005;
export function isStatementInvoiced(status?: string | null): boolean {
return String(status || '').toLowerCase() === 'invoiced';
}
export function isStatementInvoicePartial(status?: string | null): boolean {
return String(status || '').toLowerCase() === 'partial';
}
export type SupplierInvoiceMatchInput = {
statement_no?: string | null;
supplier_code?: string | null;
invoice_no?: string | null;
amount?: number | null;
invoice_date?: string | null;
created_at?: string | null;
};
function invoiceDay(inv: SupplierInvoiceMatchInput): string {
return String(inv.invoice_date || inv.created_at || '').slice(0, 10);
}
export function invoicesInDateRange<T extends SupplierInvoiceMatchInput>(
invoices: T[],
dateFrom: string,
dateTo: string
): T[] {
const from = String(dateFrom || '').slice(0, 10);
const to = String(dateTo || '').slice(0, 10);
if (!from || !to) return invoices;
return invoices.filter((inv) => {
const day = invoiceDay(inv);
return day >= from && day <= to;
});
}
export type SupplierStatementInvoiceFields = {
invoice_status: StatementInvoiceStatus;
invoice_no: string | null;
invoice_amount: number;
invoice_remaining: number;
};
function payableOf(row: { payable_amount?: number | null; total_amount?: number | null }): number {
return Number(row.payable_amount ?? row.total_amount ?? 0);
}
function coverStatus(cover: number, payable: number): StatementInvoiceStatus {
if (cover <= COVER_EPS) return 'pending';
if (cover + COVER_EPS < payable) return 'partial';
return 'invoiced';
}
export function supplierInvoiceDayKey(row: {
supplier_code?: string | null;
cycle_code?: string | null;
statement_no?: string;
}): string {
const supplier = String(row.supplier_code || '').trim();
const cycle = String(row.cycle_code || '').trim();
if (supplier && cycle) return `${supplier}\t${cycle}`;
return `${supplier}\t${String(row.statement_no || '')}`;
}
/** KPI 按供应商+日去重,避免当天多张结算单把当日已盖/还差加重复。 */
export function sumSupplierInvoicePoolKpis<
T extends {
supplier_code?: string | null;
cycle_code?: string | null;
statement_no?: string;
invoice_amount?: number | null;
invoice_remaining?: number | null;
},
>(rows: T[]): { invoiced: number; uninvoiced: number } {
const seen = new Set<string>();
let invoiced = 0;
let uninvoiced = 0;
for (const row of rows) {
const key = supplierInvoiceDayKey(row);
if (seen.has(key)) continue;
seen.add(key);
invoiced += Number(row.invoice_amount || 0);
uninvoiced += Number(row.invoice_remaining || 0);
}
return { invoiced, uninvoiced };
}
/**
* 按供应商发票金额池、按日应付合计从早到晚盖。
* 同一供应商同一 cycle_code(当天)多张结算单先加总再占用;当天所有行同一开票态。
* `allocateStatements` 用于占用(可含筛选窗口之前的天);返回值只对应 `statements`。
*
* `boundCoverByStatement`(设计 20260923):上传即绑定到具体结算单的票额,先按单占掉应付,
* 池(`invoices`)只吃剩余额。不传时行为与旧版逐字一致(历史票仍走池)。
*/
export function attachSupplierInvoiceStatus<
T extends {
statement_no: string;
supplier_code?: string | null;
cycle_code?: string | null;
payable_amount?: number | null;
total_amount?: number | null;
},
>(
statements: T[],
invoices: SupplierInvoiceMatchInput[],
allocateStatements: T[] = statements,
boundCoverByStatement: Map<string, number> = new Map()
): Array<T & SupplierStatementInvoiceFields> {
const poolBySupplier = new Map<string, number>();
for (const inv of invoices) {
const supplierCode = String(inv.supplier_code || '').trim();
if (!supplierCode) continue;
poolBySupplier.set(supplierCode, (poolBySupplier.get(supplierCode) || 0) + (Number(inv.amount) || 0));
}
const remainingBySupplier = new Map(poolBySupplier);
const dayPayable = new Map<string, number>();
const dayBound = new Map<string, number>();
const dayOrder: string[] = [];
const seenStmt = new Set<string>();
const alloc = [...allocateStatements].sort((a, b) =>
supplierInvoiceDayKey(a).localeCompare(supplierInvoiceDayKey(b))
);
for (const row of alloc) {
if (seenStmt.has(row.statement_no)) continue;
seenStmt.add(row.statement_no);
const key = supplierInvoiceDayKey(row);
if (!dayPayable.has(key)) {
dayOrder.push(key);
dayPayable.set(key, 0);
dayBound.set(key, 0);
}
const payable = Math.max(0, payableOf(row));
const bound = Math.max(0, Number(boundCoverByStatement.get(row.statement_no)) || 0);
dayPayable.set(key, (dayPayable.get(key) || 0) + payable);
dayBound.set(key, (dayBound.get(key) || 0) + Math.min(payable, bound));
}
const dayCover = new Map<string, { cover: number; payable: number }>();
for (const key of dayOrder) {
const supplierCode = key.split('\t')[0] || '';
const payable = dayPayable.get(key) || 0;
const bound = Math.min(payable, dayBound.get(key) || 0);
const residual = Math.max(0, payable - bound);
const leftover = remainingBySupplier.get(supplierCode) || 0;
const legacyCover = Math.min(leftover, residual);
remainingBySupplier.set(supplierCode, leftover - legacyCover);
dayCover.set(key, { cover: bound + legacyCover, payable });
}
return statements.map((row) => {
const key = supplierInvoiceDayKey(row);
const day = dayCover.get(key) || { cover: 0, payable: Math.max(0, payableOf(row)) };
const remaining = Math.max(0, day.payable - day.cover);
return {
...row,
invoice_status: coverStatus(day.cover, day.payable),
invoice_no: null,
invoice_amount: day.cover,
invoice_remaining: remaining,
};
});
}
export type CustomerInvoiceMatchInput = {
customer_code?: string | null;
amount?: number | null;
};
export type CustomerStatementInvoiceFields = SupplierStatementInvoiceFields;
export function isCustomerInvoicePoolStatement(row: {
statement_no?: string;
cycle_code?: string | null;
}): boolean {
const no = String(row.statement_no || '');
if (no.startsWith('CS')) return false;
return /^\d{8}$/.test(String(row.cycle_code || '').trim());
}
export function customerInvoiceDayKey(row: {
customer_code?: string | null;
cycle_code?: string | null;
statement_no?: string;
}): string {
const customer = String(row.customer_code || '').trim();
const cycle = String(row.cycle_code || '').trim();
if (customer && cycle) return `${customer}\t${cycle}`;
return `${customer}\t${String(row.statement_no || '')}`;
}
/** KPI 按客户+日去重,避免当天多张结算单把当日已盖/还差加重复。 */
export function sumCustomerInvoicePoolKpis<
T extends {
customer_code?: string | null;
cycle_code?: string | null;
statement_no?: string;
invoice_amount?: number | null;
invoice_remaining?: number | null;
},
>(rows: T[]): { invoiced: number; uninvoiced: number } {
const seen = new Set<string>();
let invoiced = 0;
let uninvoiced = 0;
for (const row of rows) {
const key = customerInvoiceDayKey(row);
if (seen.has(key)) continue;
seen.add(key);
invoiced += Number(row.invoice_amount || 0);
uninvoiced += Number(row.invoice_remaining || 0);
}
return { invoiced, uninvoiced };
}
/**
* 结算页卡片口径(2026-09-22 开发者决定,供应商/客户同口径):
*
* 已开发票 = min(本分公司已上传票额合计, 应付合计)
* 未开发票 = 应付合计 − 已开发票(恒 ≥ 0)
*
* 与「行内开票态」相互独立:行内仍按发票池水位逐日盖(`attachXxxInvoiceStatus`),
* 卡片回答的是「我一共上传了多少票面金额」,因此当票额超过该期应付时取应付为上限,
* 保证「已开 + 未开 = 应付」且「已开 ≤ 应付」两条不变量恒成立。
*/
export function sumStatementInvoiceKpiCards(input: {
payableTotal: number;
invoicePoolTotal: number;
}): { invoiced: number; uninvoiced: number } {
// 先把应付归整到分,保证「已开 + 未开 = 应付」在分位精确成立
const payable = Math.round(Math.max(0, Number(input.payableTotal) || 0) * 100) / 100;
const pool = Math.max(0, Number(input.invoicePoolTotal) || 0);
const invoiced = Math.round(Math.min(payable, pool) * 100) / 100;
const uninvoiced = Math.round(Math.max(0, payable - invoiced) * 100) / 100;
return { invoiced, uninvoiced };
}
/**
* 客户开票水位:只认实际上传的客户票额(有解析金额),与供应商同一套 FIFO。
* 历史「标记已开票」不进池。CS* / 非 8 位日 cycle 不参与水位。
*
* `boundCoverByStatement`(设计 20260923):上传即绑定到具体结算单的票额,先按单占掉应付,
* 池(`invoices`,只放无绑定的历史票)只吃剩余额。不传时行为与旧版逐字一致。
*/
export function attachCustomerInvoiceStatus<
T extends {
statement_no: string;
customer_code?: string | null;
cycle_code?: string | null;
payable_amount?: number | null;
total_amount?: number | null;
},
>(
statements: T[],
invoices: CustomerInvoiceMatchInput[],
allocateStatements: T[] = statements,
boundCoverByStatement: Map<string, number> = new Map()
): Array<T & CustomerStatementInvoiceFields> {
const poolByCustomer = new Map<string, number>();
for (const inv of invoices) {
const customerCode = String(inv.customer_code || '').trim();
const amount = Number(inv.amount) || 0;
if (!customerCode || amount <= 0) continue;
poolByCustomer.set(customerCode, (poolByCustomer.get(customerCode) || 0) + amount);
}
const remainingByCustomer = new Map(poolByCustomer);
const dayPayable = new Map<string, number>();
const dayBound = new Map<string, number>();
const dayOrder: string[] = [];
const seenStmt = new Set<string>();
const alloc = [...allocateStatements]
.filter(isCustomerInvoicePoolStatement)
.sort((a, b) => customerInvoiceDayKey(a).localeCompare(customerInvoiceDayKey(b)));
for (const row of alloc) {
if (seenStmt.has(row.statement_no)) continue;
seenStmt.add(row.statement_no);
const key = customerInvoiceDayKey(row);
if (!dayPayable.has(key)) {
dayOrder.push(key);
dayPayable.set(key, 0);
dayBound.set(key, 0);
}
const payable = Math.max(0, payableOf(row));
const bound = Math.max(0, Number(boundCoverByStatement.get(row.statement_no)) || 0);
dayPayable.set(key, (dayPayable.get(key) || 0) + payable);
dayBound.set(key, (dayBound.get(key) || 0) + Math.min(payable, bound));
}
const dayCover = new Map<string, { cover: number; payable: number }>();
for (const key of dayOrder) {
const customerCode = key.split('\t')[0] || '';
const payable = dayPayable.get(key) || 0;
const bound = Math.min(payable, dayBound.get(key) || 0);
const residual = Math.max(0, payable - bound);
const leftover = remainingByCustomer.get(customerCode) || 0;
const legacyCover = Math.min(leftover, residual);
remainingByCustomer.set(customerCode, leftover - legacyCover);
dayCover.set(key, { cover: bound + legacyCover, payable });
}
return statements.map((row) => {
if (!isCustomerInvoicePoolStatement(row)) {
const payable = Math.max(0, payableOf(row));
return {
...row,
invoice_status: 'pending' as StatementInvoiceStatus,
invoice_no: null,
invoice_amount: 0,
invoice_remaining: payable,
};
}
const key = customerInvoiceDayKey(row);
const day = dayCover.get(key) || { cover: 0, payable: Math.max(0, payableOf(row)) };
const remaining = Math.max(0, day.payable - day.cover);
return {
...row,
invoice_status: coverStatus(day.cover, day.payable),
invoice_no: null,
invoice_amount: day.cover,
invoice_remaining: remaining,
};
});
}