@chenchaolong/plugin-trade-compliance-workbench 1.0.210 → 1.0.212
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -1
- package/dist/lib/analytics-query.d.ts.map +1 -1
- package/dist/lib/analytics-query.js +4 -2
- package/dist/lib/analytics-query.js.map +1 -1
- package/dist/lib/constants.d.ts +1 -0
- package/dist/lib/constants.d.ts.map +1 -1
- package/dist/lib/constants.js +1 -0
- package/dist/lib/constants.js.map +1 -1
- package/dist/lib/domain/finance.js +6 -6
- package/dist/lib/domain/purchase-pricing.d.ts +5 -0
- package/dist/lib/domain/purchase-pricing.d.ts.map +1 -0
- package/dist/lib/domain/purchase-pricing.js +27 -0
- package/dist/lib/domain/purchase-pricing.js.map +1 -0
- package/dist/lib/entities/index.d.ts +3 -1
- package/dist/lib/entities/index.d.ts.map +1 -1
- package/dist/lib/entities/index.js +3 -1
- package/dist/lib/entities/index.js.map +1 -1
- package/dist/lib/entities/procurement.entity.d.ts +2 -0
- package/dist/lib/entities/procurement.entity.d.ts.map +1 -1
- package/dist/lib/entities/procurement.entity.js +8 -0
- package/dist/lib/entities/procurement.entity.js.map +1 -1
- package/dist/lib/entities/sales-file-generation-task.entity.d.ts +23 -0
- package/dist/lib/entities/sales-file-generation-task.entity.d.ts.map +1 -0
- package/dist/lib/entities/sales-file-generation-task.entity.js +75 -0
- package/dist/lib/entities/sales-file-generation-task.entity.js.map +1 -0
- package/dist/lib/import-jobs/contract-result-recovery.js +1 -1
- package/dist/lib/import-jobs/contract-result-recovery.js.map +1 -1
- package/dist/lib/import-jobs/import-command.builder.d.ts +1 -0
- package/dist/lib/import-jobs/import-command.builder.d.ts.map +1 -1
- package/dist/lib/import-jobs/import-command.builder.js +11 -2
- package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
- package/dist/lib/import-jobs/import-job.processor.js +1 -1
- package/dist/lib/import-jobs/import-job.processor.js.map +1 -1
- package/dist/lib/import-jobs/purchase-spreadsheet-review.d.ts.map +1 -1
- package/dist/lib/import-jobs/purchase-spreadsheet-review.js +11 -3
- package/dist/lib/import-jobs/purchase-spreadsheet-review.js.map +1 -1
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts +15 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js +68 -2
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js.map +1 -1
- package/dist/lib/packing/packing-spreadsheet.d.ts.map +1 -1
- package/dist/lib/packing/packing-spreadsheet.js +4 -0
- package/dist/lib/packing/packing-spreadsheet.js.map +1 -1
- package/dist/lib/packing/supplier-packing.service.d.ts +3 -0
- package/dist/lib/packing/supplier-packing.service.d.ts.map +1 -1
- package/dist/lib/packing/supplier-packing.service.js +57 -5
- package/dist/lib/packing/supplier-packing.service.js.map +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.js +11 -11
- package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +4 -2
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/preview-source.mjs +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/preview.js +1 -1
- package/dist/lib/remote-ui/action-execution.d.ts.map +1 -1
- package/dist/lib/remote-ui/action-execution.js +9 -0
- package/dist/lib/remote-ui/action-execution.js.map +1 -1
- package/dist/lib/remote-ui/app-source.d.ts.map +1 -1
- package/dist/lib/remote-ui/app-source.js +40 -13
- package/dist/lib/remote-ui/app-source.js.map +1 -1
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts +7 -0
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/generation-task-panel.js +64 -0
- package/dist/lib/remote-ui/components/generation-task-panel.js.map +1 -0
- package/dist/lib/remote-ui/components/source-file-preview.d.ts +11 -1
- package/dist/lib/remote-ui/components/source-file-preview.d.ts.map +1 -1
- package/dist/lib/remote-ui/components/source-file-preview.js +36 -6
- package/dist/lib/remote-ui/components/source-file-preview.js.map +1 -1
- package/dist/lib/remote-ui/components/supplier-materials.css +19 -0
- package/dist/lib/remote-ui/components/supplier-materials.d.ts +61 -0
- package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/supplier-materials.js +165 -0
- package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -0
- package/dist/lib/remote-ui/contract-import.d.ts +1 -1
- package/dist/lib/remote-ui/contract-import.d.ts.map +1 -1
- package/dist/lib/remote-ui/contract-import.js +1 -1
- package/dist/lib/remote-ui/contract-import.js.map +1 -1
- package/dist/lib/remote-ui/generation-tasks.d.ts +40 -0
- package/dist/lib/remote-ui/generation-tasks.d.ts.map +1 -0
- package/dist/lib/remote-ui/generation-tasks.js +28 -0
- package/dist/lib/remote-ui/generation-tasks.js.map +1 -0
- package/dist/lib/remote-ui/import-task-status.d.ts +2 -2
- package/dist/lib/remote-ui/import-task-status.d.ts.map +1 -1
- package/dist/lib/remote-ui/import-task-status.js +3 -1
- package/dist/lib/remote-ui/import-task-status.js.map +1 -1
- package/dist/lib/remote-ui/pages/analytics-dashboard.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/analytics-dashboard.js +1 -1
- package/dist/lib/remote-ui/pages/analytics-dashboard.js.map +1 -1
- package/dist/lib/remote-ui/pages/files.d.ts +8 -3
- package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/files.js +40 -22
- package/dist/lib/remote-ui/pages/files.js.map +1 -1
- package/dist/lib/remote-ui/pages/procurement-contracts.css +3 -0
- package/dist/lib/remote-ui/pages/procurement.d.ts +2 -0
- package/dist/lib/remote-ui/pages/procurement.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/procurement.js +62 -16
- package/dist/lib/remote-ui/pages/procurement.js.map +1 -1
- package/dist/lib/remote-ui/pages/sales.d.ts +21 -6
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +75 -22
- package/dist/lib/remote-ui/pages/sales.js.map +1 -1
- package/dist/lib/remote-ui/pages/settings.js +2 -2
- package/dist/lib/remote-ui/pages/settings.js.map +1 -1
- package/dist/lib/remote-ui/procurement-contracts.d.ts +7 -0
- package/dist/lib/remote-ui/procurement-contracts.d.ts.map +1 -1
- package/dist/lib/remote-ui/procurement-contracts.js.map +1 -1
- package/dist/lib/remote-ui/purchase-review-adapter.d.ts.map +1 -1
- package/dist/lib/remote-ui/purchase-review-adapter.js +4 -3
- package/dist/lib/remote-ui/purchase-review-adapter.js.map +1 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts +45 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts.map +1 -1
- package/dist/lib/remote-ui/sales-contracts.js.map +1 -1
- package/dist/lib/remote-ui/styles.css +6 -0
- package/dist/lib/sales-file-generation-lifecycle.d.ts +11 -0
- package/dist/lib/sales-file-generation-lifecycle.d.ts.map +1 -0
- package/dist/lib/sales-file-generation-lifecycle.js +42 -0
- package/dist/lib/sales-file-generation-lifecycle.js.map +1 -0
- package/dist/lib/sales-file-generation-task.d.ts +46 -0
- package/dist/lib/sales-file-generation-task.d.ts.map +1 -0
- package/dist/lib/sales-file-generation-task.js +207 -0
- package/dist/lib/sales-file-generation-task.js.map +1 -0
- package/dist/lib/sales-file.service.d.ts +15 -6
- package/dist/lib/sales-file.service.d.ts.map +1 -1
- package/dist/lib/sales-file.service.js +234 -96
- package/dist/lib/sales-file.service.js.map +1 -1
- package/dist/lib/schema-maintenance.d.ts +1 -0
- package/dist/lib/schema-maintenance.d.ts.map +1 -1
- package/dist/lib/schema-maintenance.js +28 -0
- package/dist/lib/schema-maintenance.js.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.d.ts +50 -0
- package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -0
- package/dist/lib/supplier-materials/generation-materials.js +67 -0
- package/dist/lib/supplier-materials/generation-materials.js.map +1 -0
- package/dist/lib/supplier-materials/supplier-materials.d.ts +83 -0
- package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -0
- package/dist/lib/supplier-materials/supplier-materials.js +138 -0
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -0
- package/dist/lib/types.d.ts +50 -4
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/types.js +5 -3
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/workbench-action-contract.d.ts +1 -1
- package/dist/lib/workbench-action-contract.d.ts.map +1 -1
- package/dist/lib/workbench-action-contract.js +9 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +20 -13
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +48 -8
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +196 -64
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +3 -0
- package/dist/lib/workbench.middleware.js.map +1 -1
- package/dist/lib/workbench.plugin.d.ts +3 -1
- package/dist/lib/workbench.plugin.d.ts.map +1 -1
- package/dist/lib/workbench.plugin.js +11 -5
- package/dist/lib/workbench.plugin.js.map +1 -1
- package/dist/lib/workbench.service.d.ts +103 -3
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +114 -40
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
|
|
3
|
+
import { generationMaterials } from './supplier-materials/generation-materials.js';
|
|
2
4
|
import { Injectable, Optional } from '@nestjs/common';
|
|
3
5
|
import { InjectDataSource } from '@nestjs/typeorm';
|
|
4
6
|
import { DataSource, In, IsNull } from 'typeorm';
|
|
@@ -6,6 +8,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
6
8
|
import { dirname, join } from 'node:path';
|
|
7
9
|
import { fileURLToPath } from 'node:url';
|
|
8
10
|
import ExcelJS from 'exceljs';
|
|
11
|
+
import JSZip from 'jszip';
|
|
9
12
|
import { aggregatePackingBatches } from './packing/packing-render.js';
|
|
10
13
|
import { PACKING_IMPORT_ACTIVE_STATUSES } from './packing/packing-import-task.contract.js';
|
|
11
14
|
import { applySharedPackageLayout, packingGoodsOrder } from './packing/shared-package-layout.js';
|
|
@@ -34,6 +37,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
|
|
|
34
37
|
export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
|
|
35
38
|
export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
|
|
36
39
|
export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
|
|
40
|
+
export const SALES_EXPORT_INTEGRITY_VERSION = '2026-10-20.1';
|
|
37
41
|
const COMPANY_LOGO_PLACEMENTS = {
|
|
38
42
|
PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
39
43
|
CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
@@ -55,6 +59,11 @@ let SalesFileService = class SalesFileService {
|
|
|
55
59
|
const needsPacking = ['CI', 'PL', 'PI_CI_PL', 'ALL', 'CUSTOMS_DECLARATION'].includes(input.fileType);
|
|
56
60
|
const packingData = needsPacking ? await this.loadPackingData(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId], input) : null;
|
|
57
61
|
const result = preflightResult(input, evaluated.compliance.complianceProfitRate.toString(), evaluated.exchangeCost?.toString() ?? null, evaluated.warnings, packing);
|
|
62
|
+
const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
|
|
63
|
+
const materialWarnings = generationMaterials(evaluated.purchaseLines, materialDocs).warnings.filter(warning => !warning.code.startsWith('CUSTOMS_') || ['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType));
|
|
64
|
+
if (materialWarnings.length)
|
|
65
|
+
result.materialWarnings = materialWarnings;
|
|
66
|
+
result.documentPricing = evaluated.documentPricing;
|
|
58
67
|
result.packingWarnings = packingData?.warnings ?? [];
|
|
59
68
|
result.packingMode = input.packingMode ?? 'DRAFT';
|
|
60
69
|
if (needsPacking && this.packingService)
|
|
@@ -68,14 +77,16 @@ let SalesFileService = class SalesFileService {
|
|
|
68
77
|
return preflightResult(input, metrics?.complianceProfitRate ?? null, metrics?.exchangeCost ?? null, metrics?.warnings ?? [], undefined, error);
|
|
69
78
|
}
|
|
70
79
|
}
|
|
71
|
-
async generate(scope, input, context) {
|
|
80
|
+
async generate(scope, input, context, hooks) {
|
|
81
|
+
await hooks?.progress('VALIDATING', 0);
|
|
72
82
|
const evaluated = await this.evaluate(scope, input);
|
|
73
|
-
const { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants } = evaluated;
|
|
83
|
+
const { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing } = evaluated;
|
|
74
84
|
const generationWarnings = [...warnings];
|
|
75
85
|
if (['PI', 'CI', 'PI_CI_PL', 'ALL'].includes(input.fileType) && paymentTermsVariants && paymentTermsVariants.length > 1)
|
|
76
86
|
generationWarnings.push({ code: 'PAYMENT_TERMS_VARY', message: `各订单付款条款不一致,已使用订单 ${orders[0].salesOrderNo} 的付款条款(${paymentTermsVariants[0]}),其余为:${paymentTermsVariants.slice(1).join(';')},请人工核对文件条款` });
|
|
77
87
|
const company = await this.dataSource.getRepository(CompanySettings).findOne({ where: scoped(scope) });
|
|
78
88
|
const clauses = await this.dataSource.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: customerContract.id, deletedAt: IsNull() } });
|
|
89
|
+
const evaluatedFingerprint = generationSourceFingerprint(evaluated, company, clauses);
|
|
79
90
|
const generatedAt = new Date();
|
|
80
91
|
const requestedTypes = generationFileTypes(input.fileType);
|
|
81
92
|
const templateVersion = input.templateVersion ?? TEMPLATE_VERSION;
|
|
@@ -87,86 +98,117 @@ let SalesFileService = class SalesFileService {
|
|
|
87
98
|
const packing = needsPacking ? await this.loadPackingData(scope, purchaseIds, input) : null;
|
|
88
99
|
if (needsPacking && !packing?.shipmentOnly)
|
|
89
100
|
generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
|
|
90
|
-
const
|
|
101
|
+
const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
|
|
102
|
+
const materialData = generationMaterials(purchaseLines, materialDocuments);
|
|
103
|
+
generationWarnings.push(...materialData.warnings);
|
|
104
|
+
const materialsFingerprint = createHash('sha256').update(JSON.stringify(materialDocuments)).digest('hex');
|
|
105
|
+
await hooks?.progress('TRANSLATING', 0);
|
|
106
|
+
const translated = await this.translateDynamicFields(scope, customer, materialData.englishLines, clauses, generationWarnings, input.fileType, packing);
|
|
91
107
|
const packingTranslated = translated;
|
|
92
108
|
if (packing)
|
|
93
109
|
generationWarnings.push(...this.packingWarningsForPl(derived, packing));
|
|
94
110
|
const mergedOrderRefs = orders.length > 1 ? orders.map(order => ({ customerContractId: order.customerContractId, purchaseOrderId: order.purchaseOrderId, salesOrderNo: order.salesOrderNo })) : null;
|
|
95
|
-
const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses })).digest('hex');
|
|
111
|
+
const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint, materialData, exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION })).digest('hex');
|
|
96
112
|
const shipmentReference = `SHIP-${createHash('sha256').update(`${ordersKey}:${packing?.fingerprint ?? ''}:${orderDataFingerprint}`).digest('hex').slice(0, 16)}`;
|
|
97
113
|
const batchGenerationId = input.fileType === 'ALL' ? randomUUID() : undefined;
|
|
98
114
|
const newStorageFileIds = [];
|
|
115
|
+
const retainedStorageIds = new Set();
|
|
116
|
+
const selectCached = async (source, lock = false) => {
|
|
117
|
+
const repo = source.getRepository(GeneratedSalesFile);
|
|
118
|
+
const candidates = ['PI_CI_PL', 'ALL'].includes(input.fileType) ? await repo.find({ where: { ...scoped(scope), customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, fileType: In(requestedTypes), deletedAt: IsNull() }, order: { generatedAt: 'DESC' }, ...(lock ? { lock: { mode: 'pessimistic_write' } } : {}) }) : [];
|
|
119
|
+
// Local-only historical results must not keep a new workspace generation pinned to a missing container file.
|
|
120
|
+
const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey, currencyCode: documentPricing.currencyCode }));
|
|
121
|
+
const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
|
|
122
|
+
return new Map(existing.map(item => [item.fileType, item]));
|
|
123
|
+
};
|
|
99
124
|
try {
|
|
125
|
+
const stagingRepo = this.dataSource.getRepository(GeneratedSalesFile);
|
|
126
|
+
const initialExisting = await selectCached(this.dataSource);
|
|
127
|
+
const missingTypes = requestedTypes.filter(type => !initialExisting.has(type));
|
|
128
|
+
const created = [];
|
|
129
|
+
await hooks?.progress('RENDERING', initialExisting.size);
|
|
130
|
+
for (const fileType of missingTypes) {
|
|
131
|
+
const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
|
|
132
|
+
const sourceDerived = fileType === 'CUSTOMS_DECLARATION' ? { ...derived, lines: derived.lines.map((line, index) => ({ ...line, hsCode: materialData.customsLines[index].hsCode })) } : derived;
|
|
133
|
+
const fileDerived = shipmentDerived(sourceDerived, packing, fileType);
|
|
134
|
+
const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? materialData.customsLines : purchaseLines;
|
|
135
|
+
const fileWarnings = generationWarnings.filter(warning => {
|
|
136
|
+
const field = String(warning.field ?? '');
|
|
137
|
+
if (String(warning.code ?? '').startsWith('CUSTOMS_') && fileType !== 'CUSTOMS_DECLARATION')
|
|
138
|
+
return false;
|
|
139
|
+
if (fileType === 'CUSTOMS_DECLARATION' && (String(warning.code ?? '').startsWith('TRANSLATION_') || warning.code === 'SOURCE_FIELD_REVIEW'))
|
|
140
|
+
return false;
|
|
141
|
+
if (field.startsWith('packing.'))
|
|
142
|
+
return fileType === 'PL';
|
|
143
|
+
if (fileType === 'PL' && (field.startsWith('clause.') || /^line\..+\.(description|unit)$/.test(field)))
|
|
144
|
+
return false;
|
|
145
|
+
return true;
|
|
146
|
+
});
|
|
147
|
+
if (fileType === 'CUSTOMS_DECLARATION')
|
|
148
|
+
fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述仅使用已知信息,申报要素、法定计量单位等请人工补全;本文件尚未提交海关。' });
|
|
149
|
+
const request = { currencyCode: documentPricing.currencyCode, ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION, shipmentDocumentsVersion: 'v2', orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: 'v10' } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
|
|
150
|
+
const snapshot = { materials: materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: filePurchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: derived.lines.filter(line => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map(line => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
|
|
151
|
+
const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
|
|
152
|
+
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, generationWarnings: fileWarnings }, logo);
|
|
153
|
+
await validateWorkbook(buffer);
|
|
154
|
+
const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
|
|
155
|
+
const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
|
|
156
|
+
const checksum = createHash('sha256').update(await templateBuffer(fileType)).digest('hex');
|
|
157
|
+
await hooks?.progress('SAVING', initialExisting.size + created.length);
|
|
158
|
+
const storageFileId = await this.fileStorage.save(scope, buffer, fileName, context);
|
|
159
|
+
newStorageFileIds.push(storageFileId);
|
|
160
|
+
created.push(stagingRepo.create({ tenantId: scope.tenantId, organizationId: scope.organizationId, createdById: scope.userId ?? null, updatedById: scope.userId ?? null, deletedAt: null, deletedById: null, deleteOperation: null, customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, salesOrderNoSnapshot: derived.salesOrderNo, fileType, documentNo, fileName, storageFileId, templateVersion, templateChecksum: checksum, generationSnapshotVersion: 'v1', generationSnapshot: snapshot, mergedOrderRefs, generationWarnings: fileWarnings, pricingProfitRate: derived.effectivePricingProfitRate, complianceProfitRate: compliance.complianceProfitRate.toString(), exchangeCost: exchangeCost?.toString() ?? null, profitRuleSnapshot: { ...rule }, bankType: bank?.bankType ?? null, bankSnapshot: bank ? { ...bank } : null, generatedById: scope.userId ?? null, generatedAt, lastEditedById: null, lastEditedAt: null }));
|
|
161
|
+
await hooks?.progress('RENDERING', initialExisting.size + created.length);
|
|
162
|
+
}
|
|
100
163
|
const files = await this.dataSource.transaction(async (manager) => {
|
|
164
|
+
// The commit lock contains database reads/writes only. Rendering, logo reads,
|
|
165
|
+
// and workspace network I/O must never prevent watchdogs or source edits.
|
|
166
|
+
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
167
|
+
await assertSalesGenerationSources(manager, scope, input);
|
|
168
|
+
if (['PI_CI_PL', 'ALL'].includes(input.fileType))
|
|
169
|
+
await manager.getRepository(PurchaseOrder).findOne({ where: { ...scoped(scope), id: purchaseOrder.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } });
|
|
170
|
+
const currentMaterials = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds, manager) ?? [];
|
|
171
|
+
if (createHash('sha256').update(JSON.stringify(currentMaterials)).digest('hex') !== materialsFingerprint)
|
|
172
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商资料已变化,请重新生成文件');
|
|
173
|
+
const currentPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input, manager) : null;
|
|
174
|
+
if ((currentPacking?.fingerprint ?? '') !== (packing?.fingerprint ?? ''))
|
|
175
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '装箱数据已变化,请重新生成文件');
|
|
176
|
+
for (const warning of currentPacking?.warnings ?? [])
|
|
177
|
+
for (const file of created)
|
|
178
|
+
if (!file.generationWarnings?.some(existing => existing.code === warning.code && existing.message === warning.message))
|
|
179
|
+
file.generationWarnings = [...(file.generationWarnings ?? []), warning];
|
|
180
|
+
const current = await this.evaluate(scope, input, manager);
|
|
181
|
+
const currentCompany = await manager.getRepository(CompanySettings).findOne({ where: scoped(scope), lock: { mode: 'pessimistic_read' } });
|
|
182
|
+
const currentClauses = await manager.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: customerContract.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_read' } });
|
|
183
|
+
if (generationSourceFingerprint(current, currentCompany, currentClauses) !== evaluatedFingerprint)
|
|
184
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '销售订单或设置已变化,请重新生成文件');
|
|
185
|
+
const existingByType = await selectCached(manager, true);
|
|
186
|
+
const stagedByType = new Map(created.map(item => [item.fileType, item]));
|
|
187
|
+
const remainingTypes = requestedTypes.filter(type => !existingByType.has(type));
|
|
188
|
+
if (remainingTypes.some(type => !stagedByType.has(type)))
|
|
189
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '历史销售文件已变化,请重新生成文件');
|
|
101
190
|
const repo = manager.getRepository(GeneratedSalesFile);
|
|
102
|
-
|
|
103
|
-
// Serialize with uploads, import persistence and packing edits. Translation may
|
|
104
|
-
// have taken time since preflight: never commit a stale shipment snapshot.
|
|
105
|
-
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
106
|
-
const currentPacking = await this.loadPackingData(scope, purchaseIds, input, manager);
|
|
107
|
-
for (const warning of currentPacking?.warnings ?? [])
|
|
108
|
-
if (!generationWarnings.some(existing => existing.code === warning.code && existing.message === warning.message))
|
|
109
|
-
generationWarnings.push(warning);
|
|
110
|
-
if ((currentPacking?.fingerprint ?? '') !== (packing?.fingerprint ?? ''))
|
|
111
|
-
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '装箱数据已变化,请重新生成文件');
|
|
112
|
-
}
|
|
113
|
-
if (['PI_CI_PL', 'ALL'].includes(input.fileType)) {
|
|
114
|
-
const lockedPurchaseOrder = await manager.getRepository(PurchaseOrder).findOne({
|
|
115
|
-
where: { ...scoped(scope), id: purchaseOrder.id, deletedAt: IsNull() },
|
|
116
|
-
lock: { mode: 'pessimistic_write' }
|
|
117
|
-
});
|
|
118
|
-
if (!lockedPurchaseOrder)
|
|
119
|
-
throw new DomainError(DomainErrorCodes.NOT_FOUND, '采购订单不存在');
|
|
120
|
-
}
|
|
121
|
-
const candidates = ['PI_CI_PL', 'ALL'].includes(input.fileType) ? await repo.find({ where: { ...scoped(scope), customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, fileType: In(requestedTypes), deletedAt: IsNull() }, order: { generatedAt: 'DESC' }, lock: { mode: 'pessimistic_write' } }) : [];
|
|
122
|
-
// Local-only historical results must not keep a new workspace generation pinned to a missing container file.
|
|
123
|
-
const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey }));
|
|
124
|
-
const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
|
|
125
|
-
const existingByType = new Map(existing.map(item => [item.fileType, item]));
|
|
126
|
-
const missingTypes = requestedTypes.filter(fileType => !existingByType.has(fileType));
|
|
127
|
-
const created = [];
|
|
128
|
-
for (const fileType of missingTypes) {
|
|
129
|
-
const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
|
|
130
|
-
const fileDerived = shipmentDerived(derived, packing, fileType);
|
|
131
|
-
const fileWarnings = generationWarnings.filter(warning => {
|
|
132
|
-
const field = String(warning.field ?? '');
|
|
133
|
-
if (fileType === 'CUSTOMS_DECLARATION' && (String(warning.code ?? '').startsWith('TRANSLATION_') || warning.code === 'SOURCE_FIELD_REVIEW'))
|
|
134
|
-
return false;
|
|
135
|
-
if (field.startsWith('packing.'))
|
|
136
|
-
return fileType === 'PL';
|
|
137
|
-
if (fileType === 'PL' && (field.startsWith('clause.') || /^line\..+\.(description|unit)$/.test(field)))
|
|
138
|
-
return false;
|
|
139
|
-
return true;
|
|
140
|
-
});
|
|
141
|
-
if (fileType === 'CUSTOMS_DECLARATION')
|
|
142
|
-
fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述仅使用已知信息,申报要素、法定计量单位等请人工补全;本文件尚未提交海关。' });
|
|
143
|
-
const request = { ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: '2026-10-19.1', shipmentDocumentsVersion: 'v2', orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: 'v10' } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
|
|
144
|
-
const snapshot = { version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: purchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: derived.lines.filter(line => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map(line => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
|
|
145
|
-
const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
|
|
146
|
-
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, generationWarnings: fileWarnings }, logo);
|
|
147
|
-
await validateWorkbook(buffer);
|
|
148
|
-
const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
|
|
149
|
-
const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
|
|
150
|
-
const checksum = createHash('sha256').update(await templateBuffer(fileType)).digest('hex');
|
|
151
|
-
const storageFileId = await this.fileStorage.save(scope, buffer, fileName, context);
|
|
152
|
-
newStorageFileIds.push(storageFileId);
|
|
153
|
-
created.push(repo.create({ tenantId: scope.tenantId, organizationId: scope.organizationId, createdById: scope.userId ?? null, updatedById: scope.userId ?? null, deletedAt: null, deletedById: null, deleteOperation: null, customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, salesOrderNoSnapshot: derived.salesOrderNo, fileType, documentNo, fileName, storageFileId, templateVersion, templateChecksum: checksum, generationSnapshotVersion: 'v1', generationSnapshot: snapshot, mergedOrderRefs, generationWarnings: fileWarnings, pricingProfitRate: derived.effectivePricingProfitRate, complianceProfitRate: compliance.complianceProfitRate.toString(), exchangeCost: exchangeCost?.toString() ?? null, profitRuleSnapshot: { ...rule }, bankType: bank?.bankType ?? null, bankSnapshot: bank ? { ...bank } : null, generatedById: scope.userId ?? null, generatedAt, lastEditedById: null, lastEditedAt: null }));
|
|
154
|
-
}
|
|
155
|
-
const saved = created.length ? await repo.save(created) : [];
|
|
191
|
+
const saved = remainingTypes.length ? await repo.save(remainingTypes.map(type => stagedByType.get(type))) : [];
|
|
156
192
|
const savedByType = new Map(saved.map(item => [item.fileType, item]));
|
|
157
|
-
|
|
193
|
+
const results = requestedTypes.map(fileType => generationResult(existingByType.get(fileType) ?? savedByType.get(fileType)));
|
|
194
|
+
await hooks?.beforeCommit(manager, results);
|
|
195
|
+
return results;
|
|
158
196
|
});
|
|
197
|
+
files.forEach(file => retainedStorageIds.add(file.storageFileId));
|
|
159
198
|
return ['PI_CI_PL', 'ALL'].includes(input.fileType) ? { files } : files[0];
|
|
160
199
|
}
|
|
161
|
-
|
|
162
|
-
await Promise.allSettled(newStorageFileIds.map(storageFileId => this.fileStorage.remove(scope, storageFileId)));
|
|
163
|
-
throw error;
|
|
200
|
+
finally {
|
|
201
|
+
await Promise.allSettled(newStorageFileIds.filter(id => !retainedStorageIds.has(id)).map(storageFileId => this.fileStorage.remove(scope, storageFileId)));
|
|
164
202
|
}
|
|
165
203
|
}
|
|
166
|
-
async evaluate(scope, input) {
|
|
204
|
+
async evaluate(scope, input, manager) {
|
|
205
|
+
const source = manager ?? this.dataSource;
|
|
167
206
|
// 合并生成:orders 指定同客户的多个销售订单(合同+采购单);缺省退化为单订单生成
|
|
207
|
+
const currencyCode = input.currencyCode ?? 'CNY';
|
|
208
|
+
if (currencyCode !== 'CNY' && currencyCode !== 'USD')
|
|
209
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '文件币种仅支持 CNY 或 USD');
|
|
168
210
|
const orderRefs = normalizeGenerationOrders(input);
|
|
169
|
-
const allDerived = await this.workbench.listDerivedSalesOrders(scope);
|
|
211
|
+
const allDerived = await (manager ? this.workbench.listDerivedSalesOrders(scope, undefined, undefined, manager) : this.workbench.listDerivedSalesOrders(scope));
|
|
170
212
|
const orderEntries = orderRefs.map(ref => {
|
|
171
213
|
const derived = allDerived.find(item => item.customerContractId === ref.customerContractId && item.purchaseOrderId === ref.purchaseOrderId);
|
|
172
214
|
if (!derived)
|
|
@@ -176,9 +218,9 @@ let SalesFileService = class SalesFileService {
|
|
|
176
218
|
return { ref, derived };
|
|
177
219
|
}).sort((a, b) => a.derived.salesOrderNo.localeCompare(b.derived.salesOrderNo));
|
|
178
220
|
const primary = orderEntries[0];
|
|
179
|
-
const contracts = await Promise.all(orderEntries.map(entry => this.required(CustomerContract, scope, entry.ref.customerContractId, '客户合同不存在')));
|
|
221
|
+
const contracts = await Promise.all(orderEntries.map(entry => this.required(CustomerContract, scope, entry.ref.customerContractId, '客户合同不存在', source)));
|
|
180
222
|
const customerContract = contracts[0];
|
|
181
|
-
const customers = await Promise.all(orderEntries.map(entry => this.required(Customer, scope, entry.derived.customerId, '客户不存在')));
|
|
223
|
+
const customers = await Promise.all(orderEntries.map(entry => this.required(Customer, scope, entry.derived.customerId, '客户不存在', source)));
|
|
182
224
|
const customer = customers[0];
|
|
183
225
|
if (customers.some(item => item.id !== customer.id))
|
|
184
226
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '合并生成的销售订单必须属于同一客户');
|
|
@@ -187,7 +229,7 @@ let SalesFileService = class SalesFileService {
|
|
|
187
229
|
// 逐字比对会误伤语义相同的条款;均未提取到条款的合同不参与比对(缺失 ≠ 不一致)。
|
|
188
230
|
let paymentTermsVariants = null;
|
|
189
231
|
if (orderEntries.length > 1) {
|
|
190
|
-
const clauseRows = await
|
|
232
|
+
const clauseRows = await source.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: In(orderEntries.map(entry => entry.ref.customerContractId)), deletedAt: IsNull() } });
|
|
191
233
|
const termsByContract = new Map();
|
|
192
234
|
for (const clause of clauseRows) {
|
|
193
235
|
if (clause.clauseType !== 'PAYMENT_TERMS')
|
|
@@ -202,18 +244,18 @@ let SalesFileService = class SalesFileService {
|
|
|
202
244
|
}
|
|
203
245
|
// 信用额度硬拦截:客户未收款总额超出信用额度(剩余额度为负)时,禁止生成任何销售文件。
|
|
204
246
|
if (customer.creditLimit != null) {
|
|
205
|
-
const unreceivedByCustomer = await this.workbench.customerUnreceivedAmounts(scope, [customer.id]);
|
|
247
|
+
const unreceivedByCustomer = await (manager ? this.workbench.customerUnreceivedAmounts(scope, [customer.id], manager) : this.workbench.customerUnreceivedAmounts(scope, [customer.id]));
|
|
206
248
|
const unreceivedAmountCny = unreceivedByCustomer.get(customer.id) ?? '0.00';
|
|
207
249
|
const remainingCreditCny = new Decimal(customer.creditLimit).minus(unreceivedAmountCny);
|
|
208
250
|
if (remainingCreditCny.isNegative()) {
|
|
209
251
|
throw new DomainError(DomainErrorCodes.CREDIT_LIMIT_EXCEEDED, `客户「${customer.name}」已超出信用额度,无法生成销售文件:信用额度 ${new Decimal(customer.creditLimit).toFixed(2)} CNY,未收款总额 ${unreceivedAmountCny} CNY,剩余 ${remainingCreditCny.toFixed(2)} CNY。请先回收货款或上调信用额度`, { customerId: customer.id, customerName: customer.name, creditLimit: customer.creditLimit, unreceivedAmountCny, remainingCreditCny: remainingCreditCny.toFixed(2) });
|
|
210
252
|
}
|
|
211
253
|
}
|
|
212
|
-
const
|
|
254
|
+
const purchaseIds = [...new Set(orderEntries.flatMap(entry => entry.derived.purchaseOrderIds?.length ? entry.derived.purchaseOrderIds : [entry.ref.purchaseOrderId]))];
|
|
255
|
+
const purchaseOrderEntities = await Promise.all(purchaseIds.map(id => this.required(PurchaseOrder, scope, id, '采购订单不存在', source)));
|
|
213
256
|
const purchaseOrder = purchaseOrderEntities.find(item => item.id === primary.ref.purchaseOrderId);
|
|
214
257
|
const purchaseOrderDates = new Map(purchaseOrderEntities.map(item => [item.id, item.orderDate]));
|
|
215
|
-
const
|
|
216
|
-
const sourcePurchaseLines = await this.dataSource.getRepository(PurchaseOrderLine).find({ where: { tenantId: scope.tenantId, organizationId: scope.organizationId, purchaseOrderId: In(purchaseIds), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } });
|
|
258
|
+
const sourcePurchaseLines = await source.getRepository(PurchaseOrderLine).find({ where: { tenantId: scope.tenantId, organizationId: scope.organizationId, purchaseOrderId: In(purchaseIds), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } });
|
|
217
259
|
const purchaseLinesById = new Map(sourcePurchaseLines.map(line => [line.id, line]));
|
|
218
260
|
const lineIds = orderEntries.flatMap(entry => entry.derived.lines.map(line => line.purchaseOrderLineId));
|
|
219
261
|
if (sourcePurchaseLines.length !== lineIds.length || purchaseLinesById.size !== sourcePurchaseLines.length || new Set(lineIds).size !== lineIds.length || lineIds.some(id => !purchaseLinesById.has(id))) {
|
|
@@ -221,7 +263,7 @@ let SalesFileService = class SalesFileService {
|
|
|
221
263
|
}
|
|
222
264
|
// All downstream arrays share the final sales order, including translations and snapshots.
|
|
223
265
|
const purchaseLines = lineIds.map(id => purchaseLinesById.get(id));
|
|
224
|
-
const rule = await
|
|
266
|
+
const rule = await source.getRepository(ProfitRuleSettings).findOne({ where: scoped(scope), ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
225
267
|
if (!rule)
|
|
226
268
|
throw new DomainError(DomainErrorCodes.PROFIT_RULE_UNCONFIGURED, '利润率规则未配置');
|
|
227
269
|
if (parseProfitRuleStatus(rule.status) !== 'ACTIVE')
|
|
@@ -251,20 +293,53 @@ let SalesFileService = class SalesFileService {
|
|
|
251
293
|
const compliance = summarizeCompliance(complianceInputs);
|
|
252
294
|
const orderedDerivedLines = purchaseLines.map(line => derivedLines.get(line.id) ?? { purchaseOrderLineId: line.id, productName: line.productName });
|
|
253
295
|
const warnings = negativeProfitWarnings(compliance.lines, orderedDerivedLines);
|
|
296
|
+
for (const entry of orderEntries)
|
|
297
|
+
if (entry.derived.hasManualOrderAmount) {
|
|
298
|
+
const lineTotal = entry.derived.lines.reduce((sum, line) => sum.plus(line.salesLineAmountCny ?? 0), new Decimal(0));
|
|
299
|
+
if (!lineTotal.toDecimalPlaces(2).eq(new Decimal(entry.derived.orderAmountCny).toDecimalPlaces(2)))
|
|
300
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.SALES_PRICING_REQUIRED, `手工维护的订单总额 ${entry.derived.orderAmountCny} CNY 与商品明细合计 ${lineTotal.toFixed(2)} CNY 不一致,请调整商品定价或清除总额覆盖后重新生成`, { orderAmountCny: entry.derived.orderAmountCny, lineTotalCny: lineTotal.toFixed(2) }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
301
|
+
}
|
|
302
|
+
// Document pricing is separate from the internal CNY accounting and compliance basis.
|
|
303
|
+
const monthlyRates = new Map();
|
|
304
|
+
const requireRate = async (orderDate, purchaseOrderId) => {
|
|
305
|
+
const month = strictOrderMonth(orderDate, purchaseOrderId);
|
|
306
|
+
let rate = monthlyRates.get(month);
|
|
307
|
+
if (!rate) {
|
|
308
|
+
const [year, monthNumber] = month.split('-').map(Number);
|
|
309
|
+
const found = await source.getRepository(MonthlySafeExchangeRate).findOne({ where: { ...scoped(scope), year, month: monthNumber, currencyCode: 'USD', deletedAt: IsNull() }, ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
310
|
+
if (!found)
|
|
311
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `缺少 ${month} 月外汇管理局首日美元汇率(1 USD = X CNY)`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
312
|
+
try {
|
|
313
|
+
parseExchangeRateInput(found);
|
|
314
|
+
}
|
|
315
|
+
catch {
|
|
316
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `${month} 月美元汇率无效,请维护有效的月度美元汇率`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
317
|
+
}
|
|
318
|
+
if (/\bdemo\b/i.test(found.sourceReference ?? ''))
|
|
319
|
+
warnings.push({ code: 'EXCHANGE_RATE_DEMO', month, sourceReference: found.sourceReference, usdToCnyRate: found.usdToCnyRate, message: `${month} 月当前使用演示预设汇率(1 USD = ${found.usdToCnyRate} CNY,来源:${found.sourceReference}),请在正式交易前维护并核实有效汇率。` });
|
|
320
|
+
rate = found;
|
|
321
|
+
monthlyRates.set(month, rate);
|
|
322
|
+
}
|
|
323
|
+
return { month, rate };
|
|
324
|
+
};
|
|
325
|
+
const documentLines = [];
|
|
326
|
+
for (const line of purchaseLines) {
|
|
327
|
+
const pricing = derivedLines.get(line.id);
|
|
328
|
+
const fx = currencyCode === 'USD' ? await requireRate(purchaseOrderDates.get(line.purchaseOrderId), line.purchaseOrderId) : null;
|
|
329
|
+
const unitPrice = new Decimal(pricing.salesUnitPriceCny ?? 0).div(fx?.rate.usdToCnyRate ?? 1).toDecimalPlaces(currencyCode === 'USD' ? 2 : 4, Decimal.ROUND_HALF_UP);
|
|
330
|
+
const lineAmount = currencyCode === 'CNY' ? new Decimal(pricing.salesLineAmountCny ?? 0).toDecimalPlaces(2, Decimal.ROUND_HALF_UP) : unitPrice.times(pricing.quantity).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
|
|
331
|
+
documentLines.push({ purchaseOrderLineId: line.id, purchaseOrderId: line.purchaseOrderId, exchangeRateMonth: fx?.month ?? null, usdToCnyRate: fx?.rate.usdToCnyRate ?? null, unitPrice: unitPrice.toFixed(currencyCode === 'CNY' && unitPrice.decimalPlaces() > 2 ? 4 : 2), lineAmount: lineAmount.toFixed(2) });
|
|
332
|
+
}
|
|
333
|
+
const documentPricing = { currencyCode, lines: documentLines, orderAmount: documentLines.reduce((sum, line) => sum.plus(line.lineAmount), new Decimal(0)).toFixed(2) };
|
|
254
334
|
if (!compliance.purchaseAmountTaxInclusiveCny.isZero() && compliance.complianceProfitRate.lt(rule.minimumOrderProfitRate))
|
|
255
335
|
throw new SalesFileEvaluationError(DomainErrorCodes.PROFIT_RATE_BELOW_MINIMUM, '整单合规利润率低于系统设置的最低值', { actual: compliance.complianceProfitRate.toString(), minimum: rule.minimumOrderProfitRate }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
256
336
|
const refundable = complianceInputs.map((line, index) => ({ line, calculated: compliance.lines[index] })).filter(item => new Decimal(item.line.refundRate).gt(0) && new Decimal(item.line.purchaseAmountTaxInclusiveCny).gt(0));
|
|
257
337
|
let exchangeCost = null;
|
|
258
338
|
let exchangeRate = null;
|
|
259
339
|
if (refundable.length) {
|
|
260
|
-
//
|
|
261
|
-
const orderDate =
|
|
262
|
-
|
|
263
|
-
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, '采购订单下单日期为空,无法确定月度美元汇率', {}, compliance.complianceProfitRate.toString(), null, warnings);
|
|
264
|
-
const date = new Date(`${orderDate}T00:00:00Z`);
|
|
265
|
-
exchangeRate = await this.dataSource.getRepository(MonthlySafeExchangeRate).findOne({ where: { ...scoped(scope), year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, currencyCode: 'USD', deletedAt: IsNull() } });
|
|
266
|
-
if (!exchangeRate)
|
|
267
|
-
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, '缺少订单月份的外汇管理局首日美元汇率', { orderDate }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
340
|
+
// Keep the established CNY compliance gate; resolve its month strictly from purchase dates.
|
|
341
|
+
const orderDate = [...purchaseOrderDates.values()].filter(Boolean).sort()[0] ?? null;
|
|
342
|
+
exchangeRate = (await requireRate(orderDate)).rate;
|
|
268
343
|
const validatedExchangeRate = parseExchangeRateInput(exchangeRate);
|
|
269
344
|
const purchaseNet = refundable.reduce((sum, item) => sum.plus(item.calculated.purchaseNetCny), new Decimal(0));
|
|
270
345
|
const sales = refundable.reduce((sum, item) => sum.plus(item.line.salesAmountCny), new Decimal(0));
|
|
@@ -277,7 +352,7 @@ let SalesFileService = class SalesFileService {
|
|
|
277
352
|
if (!input.bankType)
|
|
278
353
|
throw new SalesFileEvaluationError(DomainErrorCodes.BANK_ACCOUNT_REQUIRED, '生成 PI 或 CI 前必须选择银行信息', {}, compliance.complianceProfitRate.toString(), exchangeCost?.toString() ?? null, warnings);
|
|
279
354
|
const bankType = parseBankAccountType(input.bankType);
|
|
280
|
-
bank = await
|
|
355
|
+
bank = await source.getRepository(BankAccountSettings).findOne({ where: { ...scoped(scope), bankType }, ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
281
356
|
if (!bank)
|
|
282
357
|
throw new SalesFileEvaluationError(DomainErrorCodes.BANK_ACCOUNT_REQUIRED, '所选银行信息尚未维护', { bankType: input.bankType }, compliance.complianceProfitRate.toString(), exchangeCost?.toString() ?? null, warnings);
|
|
283
358
|
parseBankAccountType(bank.bankType);
|
|
@@ -306,12 +381,37 @@ let SalesFileService = class SalesFileService {
|
|
|
306
381
|
orderAmountCny: orders.reduce((sum, order) => sum.plus(order.orderAmountCny ?? 0), new Decimal(0)).toFixed(2),
|
|
307
382
|
lines: orderEntries.flatMap(entry => entry.derived.lines)
|
|
308
383
|
};
|
|
309
|
-
return { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants };
|
|
384
|
+
return { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing };
|
|
310
385
|
}
|
|
311
386
|
async download(scope, id) {
|
|
312
387
|
const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
|
|
313
388
|
return { item, buffer: await this.fileStorage.read(scope, item.storageFileId) };
|
|
314
389
|
}
|
|
390
|
+
async downloadMany(scope, ids) {
|
|
391
|
+
if (!Array.isArray(ids) || !ids.length || ids.length > 20 || ids.some(id => typeof id !== 'string' || !id.trim()) || new Set(ids).size !== ids.length)
|
|
392
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '请选择 1 至 20 个不同的销售文件');
|
|
393
|
+
const snapshots = [];
|
|
394
|
+
let totalBytes = 0;
|
|
395
|
+
for (const id of ids) {
|
|
396
|
+
const downloaded = await this.download(scope, id);
|
|
397
|
+
totalBytes += downloaded.buffer.length;
|
|
398
|
+
if (downloaded.buffer.length > MAX_EDITED_WORKBOOK_BYTES || totalBytes > 100 * 1024 * 1024)
|
|
399
|
+
throw new DomainError(DomainErrorCodes.FILE_TOO_LARGE, '所选销售文件过大,请分批下载');
|
|
400
|
+
snapshots.push({ item: { ...downloaded.item }, buffer: downloaded.buffer });
|
|
401
|
+
}
|
|
402
|
+
// All immutable blob reads must belong to a single unchanged metadata snapshot.
|
|
403
|
+
for (const { item } of snapshots) {
|
|
404
|
+
const current = await this.required(GeneratedSalesFile, scope, item.id, '历史销售文件不存在');
|
|
405
|
+
if (current.storageFileId !== item.storageFileId || current.editVersion !== item.editVersion || current.fileName !== item.fileName)
|
|
406
|
+
throw new DomainError(DomainErrorCodes.SALES_FILE_EDIT_CONFLICT, '销售文件已变化,请重新下载');
|
|
407
|
+
}
|
|
408
|
+
const zip = new JSZip();
|
|
409
|
+
snapshots.forEach(({ item, buffer }, index) => {
|
|
410
|
+
const name = item.fileName.split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f]/g, '_').slice(0, 200) || 'sales-file.xlsx';
|
|
411
|
+
zip.file(`${index + 1}-${name}`, buffer);
|
|
412
|
+
});
|
|
413
|
+
return { fileName: 'sales-files.zip', buffer: await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) };
|
|
414
|
+
}
|
|
315
415
|
async saveEditedWorkbook(scope, id, buffer, expected, context) {
|
|
316
416
|
const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
|
|
317
417
|
const limits = editedWorkbookLimits();
|
|
@@ -432,8 +532,8 @@ let SalesFileService = class SalesFileService {
|
|
|
432
532
|
return undefined;
|
|
433
533
|
return this.workbench.readCompanyLogo(scope, logoFileId);
|
|
434
534
|
}
|
|
435
|
-
async required(entity, scope, id, message) {
|
|
436
|
-
const item = await
|
|
535
|
+
async required(entity, scope, id, message, source = this.dataSource) {
|
|
536
|
+
const item = await source.getRepository(entity).findOne({ where: { ...scoped(scope), id, deletedAt: IsNull() } });
|
|
437
537
|
if (!item)
|
|
438
538
|
throw new DomainError(DomainErrorCodes.NOT_FOUND, message);
|
|
439
539
|
return item;
|
|
@@ -574,6 +674,21 @@ function normalizeGenerationOrders(input) {
|
|
|
574
674
|
}
|
|
575
675
|
return result;
|
|
576
676
|
}
|
|
677
|
+
function strictOrderMonth(value, purchaseOrderId) {
|
|
678
|
+
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
679
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
680
|
+
if (Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value)
|
|
681
|
+
return value.slice(0, 7);
|
|
682
|
+
}
|
|
683
|
+
const month = typeof value === 'string' && /^\d{4}-\d{2}/.test(value) ? value.slice(0, 7) : null;
|
|
684
|
+
throw new DomainError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `采购订单下单日期为空或无效${month ? `(${month})` : ''},无法确定月度美元汇率,请维护真实的 YYYY-MM-DD 日期`, { orderDate: value ?? null, month, purchaseOrderId });
|
|
685
|
+
}
|
|
686
|
+
function workbookDocumentPricing(data) {
|
|
687
|
+
if (data.snapshot?.documentPricing)
|
|
688
|
+
return data.snapshot.documentPricing;
|
|
689
|
+
// Older rendering callers and saved snapshots are denominated in CNY.
|
|
690
|
+
return { currencyCode: 'CNY', orderAmount: data.derived.orderAmountCny, lines: data.derived.lines.map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, purchaseOrderId: '', exchangeRateMonth: null, usdToCnyRate: null, unitPrice: line.salesUnitPriceCny, lineAmount: line.salesLineAmountCny })) };
|
|
691
|
+
}
|
|
577
692
|
function generationRequestMatches(item, expected) {
|
|
578
693
|
const request = item.generationSnapshot?.request;
|
|
579
694
|
const snapshotDerived = item.generationSnapshot?.derived;
|
|
@@ -586,7 +701,8 @@ function generationRequestMatches(item, expected) {
|
|
|
586
701
|
return Boolean(request &&
|
|
587
702
|
typeof request === 'object' &&
|
|
588
703
|
!Array.isArray(request) &&
|
|
589
|
-
request.exportIntegrityVersion ===
|
|
704
|
+
request.exportIntegrityVersion === SALES_EXPORT_INTEGRITY_VERSION &&
|
|
705
|
+
request.currencyCode === expected.currencyCode &&
|
|
590
706
|
request.fileNumber === expected.fileNumber &&
|
|
591
707
|
request.templateVersion === expected.templateVersion &&
|
|
592
708
|
request.remarks === expected.remarks &&
|
|
@@ -610,7 +726,7 @@ function preflightResult(input, complianceProfitRate, exchangeCost, warnings, pa
|
|
|
610
726
|
allowed: !error,
|
|
611
727
|
fileType: input.fileType,
|
|
612
728
|
bankType: input.fileType === 'CUSTOMS_DECLARATION' || input.fileType === 'PL' ? null : input.bankType ?? null,
|
|
613
|
-
currencyCode: 'CNY',
|
|
729
|
+
currencyCode: input.currencyCode ?? 'CNY',
|
|
614
730
|
complianceProfitRate,
|
|
615
731
|
exchangeCost,
|
|
616
732
|
warnings,
|
|
@@ -639,19 +755,32 @@ function fillInvoiceSheet(sheet, type, data) {
|
|
|
639
755
|
set(sheet, 'E9', type === 'PI' ? 'Remark: The quotation is valid for one week.' : '');
|
|
640
756
|
// "To:" 目的国:写客户国别;为空时覆盖模板默认值(MOSCOW),留空即可
|
|
641
757
|
set(sheet, 'B9', translated.customerCountry);
|
|
642
|
-
|
|
758
|
+
const pricing = workbookDocumentPricing(data);
|
|
759
|
+
const currency = pricing.currencyCode;
|
|
760
|
+
set(sheet, 'E11', `Unit Price (${currency})`);
|
|
761
|
+
set(sheet, 'I11', `Amount (${currency})`);
|
|
762
|
+
set(sheet, 'G11', currency === 'USD' ? '1 USD = CNY' : 'CNY to RMB');
|
|
643
763
|
for (let index = 0; index < derived.lines.length; index += 1) {
|
|
644
764
|
const row = 12 + index;
|
|
645
|
-
|
|
765
|
+
const englishProduct = translated.lines[index]?.productName ?? '';
|
|
766
|
+
const englishModel = translated.lines[index]?.model ?? '';
|
|
767
|
+
const fromQuotation = data.snapshot?.materials?.some((source) => source.documentType === 'ENGLISH_QUOTATION' && source.purchaseOrderLineId === derived.lines[index].purchaseOrderLineId && (source.fields.includes('productName') || source.fields.includes('model')));
|
|
768
|
+
const productLabel = fromQuotation && englishModel && !englishProduct.toLocaleUpperCase().includes(englishModel.toLocaleUpperCase()) ? `${englishProduct}\n${englishModel}` : englishProduct;
|
|
769
|
+
[index + 1, productLabel, translated.lines[index]?.description ?? '', derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity), Number(pricing.lines[index].unitPrice), translated.lines[index]?.unit ?? '', Number(pricing.lines[index].usdToCnyRate ?? 1), derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount), derived.lines[index].hsCode ?? ''].forEach((value, offset) => sheet.getCell(row, offset < 7 ? offset + 1 : offset + 2).value = value);
|
|
646
770
|
safeMerge(sheet, `G${row}:H${row}`);
|
|
771
|
+
sheet.getCell(`E${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
|
|
772
|
+
sheet.getCell(`I${row}`).numFmt = '0.00';
|
|
773
|
+
if (pricing.lines[index].exchangeRateMonth)
|
|
774
|
+
sheet.getCell(`G${row}`).note = `${pricing.lines[index].exchangeRateMonth}: 1 USD = ${pricing.lines[index].usdToCnyRate} CNY`;
|
|
647
775
|
}
|
|
648
776
|
const total = 12 + derived.lines.length;
|
|
649
777
|
safeMerge(sheet, `A${total}:F${total}`);
|
|
650
778
|
safeMerge(sheet, `G${total}:J${total}`);
|
|
651
|
-
set(sheet, `A${total}`, derived.shipmentIncomplete ?
|
|
652
|
-
set(sheet, `G${total}`, Number(
|
|
779
|
+
set(sheet, `A${total}`, derived.shipmentIncomplete ? `Known Amount (${currency}) — Pending review` : `Total Amount(${currency})`);
|
|
780
|
+
set(sheet, `G${total}`, Number(pricing.orderAmount));
|
|
781
|
+
sheet.getCell(`G${total}`).numFmt = '0.00';
|
|
653
782
|
set(sheet, `A${total + 1}`, 'Price');
|
|
654
|
-
set(sheet, `C${total + 1}`,
|
|
783
|
+
set(sheet, `C${total + 1}`, `Remark: All prices are in ${currency}`);
|
|
655
784
|
set(sheet, `C${total + 2}`, translated.deliveryTerms || deliveryClauseText(data.clauses ?? []) || 'To confirm');
|
|
656
785
|
const bankStart = total + 4;
|
|
657
786
|
set(sheet, `C${bankStart}`, bank.beneficiary ?? '');
|
|
@@ -1072,6 +1201,7 @@ export function remittanceInformation(cnapsCode, goodsName, derived, civilUse) {
|
|
|
1072
1201
|
}
|
|
1073
1202
|
function fillCustomsSheet(sheet, data) {
|
|
1074
1203
|
const { customer, purchaseOrder, purchaseLines, derived, company, packing } = data;
|
|
1204
|
+
const pricing = workbookDocumentPricing(data);
|
|
1075
1205
|
resizeTwoRowSection(sheet, 14, 2, derived.lines.length, 12);
|
|
1076
1206
|
const companyText = [company?.companyNameZh, company?.unifiedSocialCreditCode ? `(${company.unifiedSocialCreditCode})` : ''].join('');
|
|
1077
1207
|
set(sheet, 'K3', '1/1');
|
|
@@ -1096,7 +1226,7 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1096
1226
|
const row = 14 + index * 2;
|
|
1097
1227
|
for (let col = 2; col <= 10; col++)
|
|
1098
1228
|
sheet.getCell(row + 1, col).value = null;
|
|
1099
|
-
set(sheet, `C${row + 1}`, purchaseLines[index].productDescription
|
|
1229
|
+
set(sheet, `C${row + 1}`, [purchaseLines[index].productDescription, purchaseLines[index].brand ? `品牌:${purchaseLines[index].brand}` : '', purchaseLines[index].material ? `材质:${purchaseLines[index].material}` : '', purchaseLines[index].usage ? `用途:${purchaseLines[index].usage}` : '', purchaseLines[index].declarationElements].filter(Boolean).join(';'));
|
|
1100
1230
|
safeMerge(sheet, `A${row}:A${row + 1}`);
|
|
1101
1231
|
safeMerge(sheet, `K${row}:K${row + 1}`);
|
|
1102
1232
|
safeMerge(sheet, `L${row}:L${row + 1}`);
|
|
@@ -1105,13 +1235,18 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1105
1235
|
set(sheet, `C${row}`, [purchaseLines[index].productName, purchaseLines[index].modelSpecification].filter(Boolean).join(' '));
|
|
1106
1236
|
set(sheet, `D${row}`, derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity));
|
|
1107
1237
|
set(sheet, `E${row}`, purchaseLines[index].unit ?? '');
|
|
1108
|
-
set(sheet, `F${row}`, Number(
|
|
1109
|
-
set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(
|
|
1110
|
-
set(sheet, `H${row}`, '人民币');
|
|
1238
|
+
set(sheet, `F${row}`, Number(pricing.lines[index].unitPrice));
|
|
1239
|
+
set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount));
|
|
1240
|
+
set(sheet, `H${row}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
|
|
1111
1241
|
set(sheet, `I${row}`, purchaseLines[index].originCountry || '待确认');
|
|
1112
1242
|
set(sheet, `J${row}`, customer.country || '待确认');
|
|
1113
1243
|
set(sheet, `K${row}`, purchaseLines[index].domesticSourceLocation || '待确认');
|
|
1114
1244
|
set(sheet, `L${row}`, '待确认');
|
|
1245
|
+
for (const warning of data.generationWarnings ?? [])
|
|
1246
|
+
if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
|
|
1247
|
+
markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
|
|
1248
|
+
sheet.getCell(`F${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
|
|
1249
|
+
sheet.getCell(`G${row}`).numFmt = '0.00';
|
|
1115
1250
|
}
|
|
1116
1251
|
const tail = 14 + derived.lines.length * 2;
|
|
1117
1252
|
normalizeCustomsConfirmationRow(sheet, tail);
|
|
@@ -1293,7 +1428,7 @@ function deterministicEnglish(value, field) {
|
|
|
1293
1428
|
const normalized = normalizeKnownBusinessTerms(text);
|
|
1294
1429
|
if (normalized !== text && !/\p{Script=Han}/u.test(normalized))
|
|
1295
1430
|
return normalized;
|
|
1296
|
-
if (/^[\
|
|
1431
|
+
if (/^[\p{Script=Latin}\p{N}\p{P}\p{S}\p{Z}\s]+$/u.test(text) && /[A-Za-z0-9]/.test(text))
|
|
1297
1432
|
return text;
|
|
1298
1433
|
return null;
|
|
1299
1434
|
}
|
|
@@ -1351,4 +1486,7 @@ function unitFallback(value) {
|
|
|
1351
1486
|
const dictionary = { 台: 'pcs', 块: 'pcs', 个: 'pcs', 件: 'pcs', 只: 'pcs', 支: 'pcs', 套: 'set', 千克: 'kg', 公斤: 'kg', 米: 'm', PCS: 'PCS', pcs: 'pcs', SET: 'set', set: 'set' };
|
|
1352
1487
|
return dictionary[value.trim()] ?? null;
|
|
1353
1488
|
}
|
|
1489
|
+
function generationSourceFingerprint(evaluated, company, clauses) {
|
|
1490
|
+
return createHash('sha256').update(JSON.stringify({ evaluated, company, clauses })).digest('hex');
|
|
1491
|
+
}
|
|
1354
1492
|
//# sourceMappingURL=sales-file.service.js.map
|