Files
SupplierSystem/src/utils/statements.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

278 lines
11 KiB
TypeScript

import { supabase, executeBatch, type BatchOperation } from '../supabase/client';
import { isStatementInvoiced } from './statementInvoiceStatus';
export { isStatementInvoiced };
/**
* 结算单工具:按自然月周期汇总已履约业务,生成客户/供应商结算单。
* statement_status: 10 待确认 / 20 已确认 / 30 已收款(客户)、已付款(供应商)
*/
export interface CycleRange {
cycle: string;
startIso: string;
endIso: string;
dueDate: string;
}
const DEFAULT_SETTLEMENT_DAYS = 15;
function addDaysYmd(ymd: string, days: number): string {
const [y, m, d] = ymd.split('-').map(Number);
const dt = new Date(y, m - 1, d);
dt.setDate(dt.getDate() + days);
return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')}`;
}
function dueDateFromSettlementDays(periodEndYmd: string, settlementDays?: number | null): string {
const n = Math.floor(Number(settlementDays));
const days = Number.isFinite(n) && n > 0 ? Math.min(n, 366) : DEFAULT_SETTLEMENT_DAYS;
return addDaysYmd(periodEndYmd, days);
}
/** 解析 'YYYY-MM' 或 'YYYYMM' 为周期范围;默认到期日=月末+15(具体客户账期在生成时覆盖) */
export function resolveCycleRange(input: string): CycleRange {
const normalized = input.replace('-', '');
const year = Number(normalized.slice(0, 4));
const month = Number(normalized.slice(4, 6));
const start = new Date(year, month - 1, 1);
const end = new Date(year, month, 1);
const periodEnd = new Date(year, month, 0);
const periodEndYmd = `${periodEnd.getFullYear()}-${String(periodEnd.getMonth() + 1).padStart(2, '0')}-${String(periodEnd.getDate()).padStart(2, '0')}`;
return {
cycle: normalized,
startIso: start.toISOString(),
endIso: end.toISOString(),
dueDate: dueDateFromSettlementDays(periodEndYmd, DEFAULT_SETTLEMENT_DAYS),
};
}
export interface StatementGenerateResult {
created: number;
skipped: number;
}
/** 生成客户结算单:按签收/完成时间汇总周期内已履约订单 */
export async function generateCustomerStatements(cycleInput: string): Promise<StatementGenerateResult> {
const range = resolveCycleRange(cycleInput);
const [{ data: orders }, { data: existing }] = await Promise.all([
supabase
.from('orders')
.select('order_code, customer_code, total_amount, order_status, updated_at')
.gte('order_status', 90)
.gte('updated_at', range.startIso)
.lt('updated_at', range.endIso),
supabase.from('customer_statements').select('statement_no, customer_code').eq('cycle_code', range.cycle),
]);
const existingCustomers = new Set((existing || []).map((s: any) => s.customer_code));
const totals = new Map<string, number>();
for (const order of orders || []) {
if (!order.customer_code) continue;
totals.set(
order.customer_code,
(totals.get(order.customer_code) || 0) + Number(order.total_amount || 0)
);
}
const customerCodes = [...totals.keys()];
const { data: customerRows } = customerCodes.length
? await supabase.from('customers').select('customer_code, settlement_days').in('customer_code', customerCodes)
: { data: [] as Array<{ customer_code: string; settlement_days: number }> };
const daysByCustomer = new Map<string, number>(
(customerRows || []).map(
(r: { customer_code?: string; settlement_days?: unknown }) =>
[String(r.customer_code), Number(r.settlement_days)] as [string, number]
)
);
const periodEndYmd = new Date(range.endIso);
periodEndYmd.setDate(periodEndYmd.getDate() - 1);
const periodEndStr = periodEndYmd.toISOString().slice(0, 10);
let seq = (existing || []).length;
let skipped = 0;
const operations: BatchOperation[] = [];
for (const [customerCode, total] of totals) {
if (existingCustomers.has(customerCode)) {
skipped += 1;
continue;
}
if (total <= 0) continue;
seq += 1;
operations.push({
table: 'customer_statements',
action: 'insert',
insertData: {
statement_no: `CS${range.cycle}${String(seq).padStart(3, '0')}`,
cycle_code: range.cycle,
customer_code: customerCode,
total_amount: Math.round(total * 100) / 100,
paid_amount: 0,
unpaid_amount: Math.round(total * 100) / 100,
due_date: dueDateFromSettlementDays(periodEndStr, daysByCustomer.get(customerCode)),
statement_status: 10,
},
});
}
if (operations.length) {
await executeBatch(operations);
}
return { created: operations.length, skipped };
}
/** 生成供应商结算单:仅汇总周期内已完成备货(不含自采/采购入库) */
export async function generateSupplierStatements(cycleInput: string): Promise<StatementGenerateResult> {
const range = resolveCycleRange(cycleInput);
const [{ data: preps }, { data: existing }] = await Promise.all([
supabase
.from('supplier_preparations')
.select('supplier_code, prepare_qty, purchase_price, prepare_status, transferred_to_purchase, prepare_time')
.eq('prepare_status', 30)
.gte('prepare_time', range.startIso)
.lt('prepare_time', range.endIso),
supabase.from('supplier_statements').select('statement_no, supplier_code').eq('cycle_code', range.cycle),
]);
const existingSuppliers = new Set((existing || []).map((s: any) => s.supplier_code));
const totals = new Map<string, number>();
for (const prep of preps || []) {
if (!prep.supplier_code || prep.transferred_to_purchase) continue;
const amount = Number(prep.prepare_qty || 0) * Number(prep.purchase_price || 0);
totals.set(prep.supplier_code, (totals.get(prep.supplier_code) || 0) + amount);
}
const supplierCodes = [...totals.keys()];
const { data: supplierRows } = supplierCodes.length
? await supabase.from('suppliers').select('supplier_code, settlement_days').in('supplier_code', supplierCodes)
: { data: [] as Array<{ supplier_code: string; settlement_days: number }> };
const daysBySupplier = new Map<string, number>(
(supplierRows || []).map(
(r: { supplier_code?: string; settlement_days?: unknown }) =>
[String(r.supplier_code), Number(r.settlement_days)] as [string, number]
)
);
const periodEndYmd = new Date(range.endIso);
periodEndYmd.setDate(periodEndYmd.getDate() - 1);
const periodEndStr = periodEndYmd.toISOString().slice(0, 10);
let seq = (existing || []).length;
let skipped = 0;
const operations: BatchOperation[] = [];
for (const [supplierCode, total] of totals) {
if (existingSuppliers.has(supplierCode)) {
skipped += 1;
continue;
}
if (total <= 0) continue;
seq += 1;
const rounded = Math.round(total * 100) / 100;
operations.push({
table: 'supplier_statements',
action: 'insert',
insertData: {
statement_no: `SS${range.cycle}${String(seq).padStart(3, '0')}`,
cycle_code: range.cycle,
supplier_code: supplierCode,
total_amount: rounded,
deduction_amount: 0,
payable_amount: rounded,
due_date: dueDateFromSettlementDays(periodEndStr, daysBySupplier.get(supplierCode)),
statement_status: 10,
},
});
}
if (operations.length) {
await executeBatch(operations);
}
return { created: operations.length, skipped };
}
export const STATEMENT_STATUS: Record<number, { text: string; color: string }> = {
10: { text: '待确认', color: 'bg-amber-100 text-amber-700' },
15: { text: '争议复核', color: 'bg-red-100 text-red-700' },
20: { text: '已确认', color: 'bg-blue-100 text-blue-700' },
30: { text: '已结清', color: 'bg-emerald-100 text-emerald-700' },
};
export function getStatementStatus(status: number | null) {
return STATEMENT_STATUS[status || 10] || { text: '未知', color: 'bg-gray-100 text-gray-600' };
}
/** 未结清:status < 30(与客户/供应商结算页原公式逐字相同) */
export function isStatementOpen(status: number | null | undefined): boolean {
return Number(status || 10) < 30;
}
/** 待确认:status === 10(与两页勾选口径相同) */
export function isStatementAwaitingConfirm(status: number | null | undefined): boolean {
return (status || 10) === 10;
}
export function filterStatementsByStatusGroup<
T extends { statement_status?: number | null; invoice_status?: string | null },
>(rows: T[], statusGroup: string): T[] {
if (statusGroup === 'pending') return rows.filter((s) => isStatementOpen(s.statement_status));
if (statusGroup === 'uninvoiced') return rows.filter((s) => !isStatementInvoiced(s.invoice_status));
if (statusGroup === 'invoiced') return rows.filter((s) => isStatementInvoiced(s.invoice_status));
return rows;
}
/** 默认结算周期:上一个自然月 */
export function defaultCycleMonth(): string {
const d = new Date();
d.setMonth(d.getMonth() - 1);
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
/** 当前自然月(供应商结算常用:按当月已供货预览) */
export function currentCycleMonth(): string {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
}
/** 默认账期:就近 15 天(含今天),即 今天-14 ~ 今天 */
export function defaultStatementDateRange(): { date_from: string; date_to: string } {
const fmt = (d: Date) =>
`${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
const end = new Date();
const start = new Date();
start.setDate(start.getDate() - 14);
return { date_from: fmt(start), date_to: fmt(end) };
}
/**
* 从 URL 读取初始账期(概览卡片下钻联动)。
* 仅当 date_from/date_to 齐全、为 YYYY-MM-DD 且 from<=to 时采用;否则回退默认近15天。
*/
export function initialStatementDateRangeFromUrl(
searchParams: Pick<URLSearchParams, 'get'>
): { date_from: string; date_to: string } {
const isYmd = (s: string) => /^\d{4}-\d{2}-\d{2}$/.test(s);
const from = String(searchParams.get('date_from') || '').trim();
const to = String(searchParams.get('date_to') || '').trim();
if (isYmd(from) && isYmd(to) && from <= to) {
return { date_from: from, date_to: to };
}
return defaultStatementDateRange();
}
export type StatementDateField = 'delivery_date' | 'created_at' | 'inbound';
export function normalizeStatementDateField(raw?: string | null): StatementDateField {
const v = String(raw || '').trim();
if (v === 'created_at') return 'created_at';
if (v === 'inbound') return 'inbound';
return 'delivery_date';
}
export function statementDateFieldLabel(field: StatementDateField): string {
if (field === 'created_at') return '下单日';
if (field === 'inbound') return '入库日';
return '配送日';
}