来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
244 lines
8.3 KiB
TypeScript
244 lines
8.3 KiB
TypeScript
import { pool } from '../db';
|
|
import { buildSignedStoragePath } from './storageSignedUrl';
|
|
import type { TenantContext } from './tenantScope';
|
|
import {
|
|
assertAllocationsWithinInvoiceAmount,
|
|
assertInvoiceAllocationsOwned,
|
|
invoiceWithLinksCteSql,
|
|
normalizeInvoiceAllocations,
|
|
} from './invoiceStatementLinkService';
|
|
|
|
const INVOICE_NO_MAX = 50;
|
|
|
|
function badRequest(message: string) {
|
|
return Object.assign(new Error(message), { status: 400, code: 'invalid_request' });
|
|
}
|
|
|
|
function optionalNumber(value: unknown): number | null {
|
|
if (value == null || value === '') return null;
|
|
const n = Number(value);
|
|
if (!Number.isFinite(n)) return null;
|
|
return n;
|
|
}
|
|
|
|
function optionalDate(value: unknown): string | null {
|
|
const text = String(value || '').trim();
|
|
if (!text) return null;
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(text)) {
|
|
throw badRequest('开票日期格式无效');
|
|
}
|
|
return text;
|
|
}
|
|
|
|
function sanitizeOcrData(raw: unknown): Record<string, unknown> | null {
|
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
const { items: _items, ...rest } = raw as Record<string, unknown>;
|
|
return rest;
|
|
}
|
|
|
|
export function normalizeSupplierInvoiceWrite(input: {
|
|
invoice_no?: unknown;
|
|
supplier_code?: unknown;
|
|
amount?: unknown;
|
|
tax_rate?: unknown;
|
|
tax_amount?: unknown;
|
|
invoice_url?: unknown;
|
|
invoice_date?: unknown;
|
|
ocr_data?: unknown;
|
|
branch_code?: string | null;
|
|
}) {
|
|
const invoiceNo = String(input.invoice_no || '').trim();
|
|
if (!invoiceNo) throw badRequest('发票号码不能为空');
|
|
if (invoiceNo.length > INVOICE_NO_MAX) throw badRequest('发票号码过长');
|
|
|
|
const supplierCode = String(input.supplier_code || '').trim();
|
|
if (!supplierCode) throw badRequest('请选择供应商');
|
|
|
|
const amount = Number(input.amount);
|
|
if (!Number.isFinite(amount) || amount <= 0) throw badRequest('金额必须大于 0');
|
|
|
|
const invoiceUrl = String(input.invoice_url || '').trim() || null;
|
|
const branchCode = String(input.branch_code || '').trim() || null;
|
|
|
|
return {
|
|
invoice_no: invoiceNo,
|
|
invoice_type: 'supplier' as const,
|
|
supplier_code: supplierCode,
|
|
statement_no: null,
|
|
amount,
|
|
tax_rate: optionalNumber(input.tax_rate),
|
|
tax_amount: optionalNumber(input.tax_amount),
|
|
invoice_url: invoiceUrl,
|
|
invoice_date: optionalDate(input.invoice_date),
|
|
ocr_data: sanitizeOcrData(input.ocr_data),
|
|
verify_status: 10,
|
|
branch_code: branchCode,
|
|
};
|
|
}
|
|
|
|
export async function insertSupplierInvoice(
|
|
input: Parameters<typeof normalizeSupplierInvoiceWrite>[0] & { allocations?: unknown },
|
|
_ctx: TenantContext
|
|
) {
|
|
const row = normalizeSupplierInvoiceWrite(input);
|
|
const allocations = normalizeInvoiceAllocations(input.allocations);
|
|
assertAllocationsWithinInvoiceAmount(allocations, row.amount);
|
|
await assertInvoiceAllocationsOwned({
|
|
statementType: 'supplier',
|
|
partyCode: row.supplier_code,
|
|
allocations,
|
|
});
|
|
|
|
const baseParams = [
|
|
row.invoice_no,
|
|
row.invoice_type,
|
|
row.supplier_code,
|
|
row.statement_no,
|
|
row.amount,
|
|
row.tax_rate,
|
|
row.tax_amount,
|
|
row.invoice_url,
|
|
row.invoice_date,
|
|
row.ocr_data == null ? null : JSON.stringify(row.ocr_data),
|
|
row.verify_status,
|
|
row.branch_code,
|
|
];
|
|
|
|
if (!allocations.length) {
|
|
const result = await pool.query(
|
|
`INSERT INTO invoices (
|
|
invoice_no, invoice_type, supplier_code, 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, supplier_code, statement_no,
|
|
amount, tax_rate, tax_amount, invoice_url, invoice_date,
|
|
ocr_data, verify_status, created_at`,
|
|
baseParams
|
|
);
|
|
return { ...result.rows[0], allocations: [] };
|
|
}
|
|
|
|
const result = await pool.query(invoiceWithLinksCteSql('supplier_code'), [
|
|
...baseParams,
|
|
allocations.map((item) => item.statement_no),
|
|
allocations.map((item) => item.amount),
|
|
]);
|
|
return { ...result.rows[0], allocations };
|
|
}
|
|
|
|
function toInvoiceDate(value: unknown): string | null {
|
|
if (value == null || value === '') return null;
|
|
if (value instanceof Date && Number.isFinite(value.getTime())) {
|
|
return value.toISOString().slice(0, 10);
|
|
}
|
|
const text = String(value);
|
|
const match = text.match(/^(\d{4}-\d{2}-\d{2})/);
|
|
return match ? match[1] : null;
|
|
}
|
|
|
|
function dropOcrItems(raw: unknown): Record<string, unknown> | null {
|
|
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
const { items: _items, ...rest } = raw as Record<string, unknown>;
|
|
return rest;
|
|
}
|
|
|
|
export function mapSupplierInvoiceListRow(row: {
|
|
id?: unknown;
|
|
invoice_no?: unknown;
|
|
invoice_type?: unknown;
|
|
supplier_code?: unknown;
|
|
amount?: unknown;
|
|
tax_rate?: unknown;
|
|
tax_amount?: unknown;
|
|
invoice_url?: unknown;
|
|
invoice_date?: unknown;
|
|
ocr_data?: unknown;
|
|
verify_status?: unknown;
|
|
created_at?: unknown;
|
|
}) {
|
|
const invoiceUrl = String(row.invoice_url || '').trim();
|
|
return {
|
|
id: String(row.id || ''),
|
|
invoice_no: String(row.invoice_no || ''),
|
|
invoice_type: String(row.invoice_type || 'supplier'),
|
|
supplier_code: String(row.supplier_code || ''),
|
|
amount: Number(row.amount) || 0,
|
|
tax_rate: row.tax_rate == null ? null : Number(row.tax_rate),
|
|
tax_amount: row.tax_amount == null ? null : Number(row.tax_amount),
|
|
invoice_url: invoiceUrl || null,
|
|
invoice_date: toInvoiceDate(row.invoice_date),
|
|
ocr_data: dropOcrItems(row.ocr_data),
|
|
verify_status: row.verify_status == null ? null : Number(row.verify_status),
|
|
created_at: row.created_at ? String(row.created_at) : null,
|
|
signed_url: invoiceUrl ? buildSignedStoragePath('invoices', invoiceUrl) : null,
|
|
};
|
|
}
|
|
|
|
export const SUPPLIER_INVOICE_LIST_LIMIT_DEFAULT = 30;
|
|
export const SUPPLIER_INVOICE_LIST_LIMIT_MAX = 50;
|
|
|
|
export function normalizeSupplierInvoiceListQuery(input: {
|
|
supplierCode?: unknown;
|
|
dateFrom?: unknown;
|
|
dateTo?: unknown;
|
|
branchCode?: string | null;
|
|
offset?: unknown;
|
|
limit?: unknown;
|
|
}) {
|
|
const supplierCode = String(input.supplierCode || '').trim() || null;
|
|
const dateFrom = String(input.dateFrom || '').trim();
|
|
const dateTo = String(input.dateTo || '').trim();
|
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(dateFrom) || !/^\d{4}-\d{2}-\d{2}$/.test(dateTo)) {
|
|
throw badRequest('请选择起止日期');
|
|
}
|
|
if (dateFrom > dateTo) throw badRequest('请选择起止日期');
|
|
const branchCode = String(input.branchCode || '').trim() || null;
|
|
const offsetRaw = Number(input.offset);
|
|
const offset = Number.isFinite(offsetRaw) && offsetRaw > 0 ? Math.floor(offsetRaw) : 0;
|
|
const limitRaw = Number(input.limit);
|
|
const limit = Number.isFinite(limitRaw)
|
|
? Math.min(SUPPLIER_INVOICE_LIST_LIMIT_MAX, Math.max(1, Math.floor(limitRaw)))
|
|
: SUPPLIER_INVOICE_LIST_LIMIT_DEFAULT;
|
|
return { supplierCode, dateFrom, dateTo, branchCode, offset, limit };
|
|
}
|
|
|
|
export async function listSupplierInvoices(input: {
|
|
supplierCode?: string;
|
|
dateFrom?: string;
|
|
dateTo?: string;
|
|
branchCode: string | null;
|
|
offset?: number;
|
|
limit?: number;
|
|
}) {
|
|
const query = normalizeSupplierInvoiceListQuery(input);
|
|
const params: unknown[] = [query.dateFrom, query.dateTo];
|
|
let supplierSql = '';
|
|
if (query.supplierCode) {
|
|
params.push(query.supplierCode);
|
|
supplierSql = ` AND supplier_code = $${params.length}`;
|
|
}
|
|
let branchSql = '';
|
|
if (query.branchCode) {
|
|
params.push(query.branchCode);
|
|
branchSql = ` AND branch_code = $${params.length}`;
|
|
}
|
|
params.push(query.limit + 1, query.offset);
|
|
const result = await pool.query(
|
|
`SELECT id, invoice_no, invoice_type, supplier_code, amount, tax_rate, tax_amount,
|
|
invoice_url, invoice_date, ocr_data, verify_status, created_at
|
|
FROM invoices
|
|
WHERE invoice_type = 'supplier'
|
|
AND (created_at AT TIME ZONE 'Asia/Shanghai')::date >= $1::date
|
|
AND (created_at AT TIME ZONE 'Asia/Shanghai')::date <= $2::date
|
|
${supplierSql}
|
|
${branchSql}
|
|
ORDER BY created_at DESC, id DESC
|
|
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
|
params
|
|
);
|
|
const hasMore = result.rows.length > query.limit;
|
|
const rows = (hasMore ? result.rows.slice(0, query.limit) : result.rows).map(mapSupplierInvoiceListRow);
|
|
return { rows, has_more: hasMore, offset: query.offset, limit: query.limit };
|
|
}
|