Files
SupplierSystem/server/src/services/invoiceStatementLinkService.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

135 lines
5.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { pool } from '../db';
/**
* 结算发票「上传即绑定」的分配链接。
* 设计:docs/design/20260923-invoice-statement-binding.md
*
* - 写入:发票金额按页面算好的 FIFO 切分落到 `invoice_statement_links`。
* - 读取:结算页按 `statement_no` 反查「绑定到该单的票额」。
*/
export type InvoiceStatementType = 'customer' | 'supplier';
export interface InvoiceAllocationInput {
statement_no: string;
amount: number;
}
export interface InvoiceStatementLink {
invoice_id: string;
statement_no: string;
amount: number;
}
const ALLOCATION_EPS = 0.005;
function badRequest(message: string) {
return Object.assign(new Error(message), { status: 400, code: 'invalid_request' });
}
/** 汇总多行分配,容忍字符串金额;非法项直接 400。 */
export function normalizeInvoiceAllocations(raw: unknown): InvoiceAllocationInput[] {
if (raw == null) return [];
if (!Array.isArray(raw)) throw badRequest('分配明细格式无效');
const merged = new Map<string, number>();
for (const item of raw) {
if (!item || typeof item !== 'object') throw badRequest('分配明细格式无效');
const record = item as Record<string, unknown>;
const statementNo = String(record.statement_no || '').trim();
if (!statementNo || statementNo.length > 64) throw badRequest('分配明细结算单号无效');
const amount = Number(record.amount);
if (!Number.isFinite(amount) || amount <= 0) throw badRequest('分配金额必须大于 0');
merged.set(statementNo, (merged.get(statementNo) || 0) + amount);
}
return [...merged.entries()].map(([statement_no, amount]) => ({
statement_no,
amount: Math.round(amount * 100) / 100,
}));
}
/** 分配合计不得超过票面金额(分位容差)。 */
export function assertAllocationsWithinInvoiceAmount(
allocations: InvoiceAllocationInput[],
invoiceAmount: number
): void {
const total = allocations.reduce((sum, item) => sum + item.amount, 0);
if (total > Number(invoiceAmount) + ALLOCATION_EPS) {
throw badRequest('分配金额合计不能大于发票金额');
}
}
/**
* 校验每个结算单号确实属于该主体(防止跨主体/跨表乱绑)。
* 走请求作用域的 `pool.query`,search_path 已由租户上下文切好。
*/
export async function assertInvoiceAllocationsOwned(input: {
statementType: InvoiceStatementType;
partyCode: string;
allocations: InvoiceAllocationInput[];
}): Promise<void> {
if (!input.allocations.length) return;
const table = input.statementType === 'customer' ? 'customer_statements' : 'supplier_statements';
const partyColumn = input.statementType === 'customer' ? 'customer_code' : 'supplier_code';
const nos = input.allocations.map((item) => item.statement_no);
const result = await pool.query(
`SELECT statement_no FROM ${table}
WHERE ${partyColumn} = $1 AND statement_no = ANY($2::text[])`,
[input.partyCode, nos]
);
const found = new Set(result.rows.map((row: { statement_no?: unknown }) => String(row.statement_no || '')));
const missing = nos.filter((no) => !found.has(no));
if (missing.length) {
throw badRequest(`结算单不属于当前客户/供应商:${missing.slice(0, 3).join('、')}`);
}
}
/** 结算页读取绑定:按租户 + 分公司作用域返回全部链接(量级与发票数同阶)。 */
export async function listInvoiceStatementLinks(input: {
statementType: InvoiceStatementType;
branchCode: string | null;
}): Promise<InvoiceStatementLink[]> {
const params: unknown[] = [input.statementType];
let branchSql = '';
if (input.branchCode) {
params.push(input.branchCode);
branchSql = ` AND branch_code = $${params.length}`;
}
const result = await pool.query(
`SELECT invoice_id, statement_no, amount
FROM invoice_statement_links
WHERE statement_type = $1
${branchSql}
ORDER BY created_at DESC`,
params
);
return result.rows.map((row: { invoice_id?: unknown; statement_no?: unknown; amount?: unknown }) => ({
invoice_id: String(row.invoice_id || ''),
statement_no: String(row.statement_no || ''),
amount: Number(row.amount) || 0,
}));
}
/** 单语句写发票 + 绑定链接:数据修改 CTE,天然原子,无需在共享请求连接上开事务。 */
export function invoiceWithLinksCteSql(partyColumn: 'customer_code' | 'supplier_code'): string {
return `
WITH inv AS (
INSERT INTO invoices (
invoice_no, invoice_type, ${partyColumn}, statement_no,
amount, tax_rate, tax_amount, invoice_url, invoice_date,
ocr_data, verify_status, branch_code
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, $12)
RETURNING id, invoice_no, invoice_type, ${partyColumn}, statement_no,
amount, tax_rate, tax_amount, invoice_url, invoice_date,
ocr_data, verify_status, created_at
), links AS (
INSERT INTO invoice_statement_links (
invoice_id, statement_type, statement_no, amount, branch_code
)
SELECT inv.id, $2, a.statement_no, a.amount, $12
FROM inv, unnest($13::text[], $14::numeric[]) AS a(statement_no, amount)
ON CONFLICT (invoice_id, statement_no) DO NOTHING
RETURNING invoice_id
)
SELECT * FROM inv`;
}