@chenchaolong/plugin-trade-compliance-workbench 1.0.211 → 1.0.213
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/dist/lib/analytics-query.d.ts.map +1 -1
- package/dist/lib/analytics-query.js +39 -16
- package/dist/lib/analytics-query.js.map +1 -1
- 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/import-command.builder.js +2 -2
- package/dist/lib/import-jobs/import-command.builder.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/source-field-recovery.d.ts +5 -0
- package/dist/lib/import-jobs/source-field-recovery.d.ts.map +1 -0
- package/dist/lib/import-jobs/source-field-recovery.js +52 -0
- package/dist/lib/import-jobs/source-field-recovery.js.map +1 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts +23 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js +74 -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 +7 -2
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +87 -87
- 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 +4 -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 +26 -5
- package/dist/lib/remote-ui/app-source.js.map +1 -1
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts +8 -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 +67 -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/generation-tasks.d.ts +42 -0
- package/dist/lib/remote-ui/generation-tasks.d.ts.map +1 -0
- package/dist/lib/remote-ui/generation-tasks.js +32 -0
- package/dist/lib/remote-ui/generation-tasks.js.map +1 -0
- 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 +1 -1
- package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/files.js +6 -12
- 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 +3 -1
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +27 -13
- package/dist/lib/remote-ui/pages/sales.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 +1 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts.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 +142 -83
- 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 +1 -0
- package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.js +1 -1
- package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.js +17 -2
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
- package/dist/lib/types.d.ts +28 -1
- package/dist/lib/types.d.ts.map +1 -1
- 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 +4 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +18 -13
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +32 -5
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +84 -70
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +2 -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 +8 -3
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +107 -24
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
|
|
2
3
|
import { generationMaterials } from './supplier-materials/generation-materials.js';
|
|
3
4
|
import { Injectable, Optional } from '@nestjs/common';
|
|
4
5
|
import { InjectDataSource } from '@nestjs/typeorm';
|
|
@@ -7,6 +8,7 @@ import { createHash, randomUUID } from 'node:crypto';
|
|
|
7
8
|
import { dirname, join } from 'node:path';
|
|
8
9
|
import { fileURLToPath } from 'node:url';
|
|
9
10
|
import ExcelJS from 'exceljs';
|
|
11
|
+
import JSZip from 'jszip';
|
|
10
12
|
import { aggregatePackingBatches } from './packing/packing-render.js';
|
|
11
13
|
import { PACKING_IMPORT_ACTIVE_STATUSES } from './packing/packing-import-task.contract.js';
|
|
12
14
|
import { applySharedPackageLayout, packingGoodsOrder } from './packing/shared-package-layout.js';
|
|
@@ -35,6 +37,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
|
|
|
35
37
|
export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
|
|
36
38
|
export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
|
|
37
39
|
export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
|
|
40
|
+
export const SALES_EXPORT_INTEGRITY_VERSION = '2026-10-21.1';
|
|
38
41
|
const COMPANY_LOGO_PLACEMENTS = {
|
|
39
42
|
PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
40
43
|
CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
@@ -74,7 +77,8 @@ let SalesFileService = class SalesFileService {
|
|
|
74
77
|
return preflightResult(input, metrics?.complianceProfitRate ?? null, metrics?.exchangeCost ?? null, metrics?.warnings ?? [], undefined, error);
|
|
75
78
|
}
|
|
76
79
|
}
|
|
77
|
-
async generate(scope, input, context) {
|
|
80
|
+
async generate(scope, input, context, hooks) {
|
|
81
|
+
await hooks?.progress('VALIDATING', 0);
|
|
78
82
|
const evaluated = await this.evaluate(scope, input);
|
|
79
83
|
const { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing } = evaluated;
|
|
80
84
|
const generationWarnings = [...warnings];
|
|
@@ -82,6 +86,7 @@ let SalesFileService = class SalesFileService {
|
|
|
82
86
|
generationWarnings.push({ code: 'PAYMENT_TERMS_VARY', message: `各订单付款条款不一致,已使用订单 ${orders[0].salesOrderNo} 的付款条款(${paymentTermsVariants[0]}),其余为:${paymentTermsVariants.slice(1).join(';')},请人工核对文件条款` });
|
|
83
87
|
const company = await this.dataSource.getRepository(CompanySettings).findOne({ where: scoped(scope) });
|
|
84
88
|
const clauses = await this.dataSource.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: customerContract.id, deletedAt: IsNull() } });
|
|
89
|
+
const evaluatedFingerprint = generationSourceFingerprint(evaluated, company, clauses);
|
|
85
90
|
const generatedAt = new Date();
|
|
86
91
|
const requestedTypes = generationFileTypes(input.fileType);
|
|
87
92
|
const templateVersion = input.templateVersion ?? TEMPLATE_VERSION;
|
|
@@ -97,96 +102,113 @@ let SalesFileService = class SalesFileService {
|
|
|
97
102
|
const materialData = generationMaterials(purchaseLines, materialDocuments);
|
|
98
103
|
generationWarnings.push(...materialData.warnings);
|
|
99
104
|
const materialsFingerprint = createHash('sha256').update(JSON.stringify(materialDocuments)).digest('hex');
|
|
105
|
+
await hooks?.progress('TRANSLATING', 0);
|
|
100
106
|
const translated = await this.translateDynamicFields(scope, customer, materialData.englishLines, clauses, generationWarnings, input.fileType, packing);
|
|
101
107
|
const packingTranslated = translated;
|
|
102
108
|
if (packing)
|
|
103
109
|
generationWarnings.push(...this.packingWarningsForPl(derived, packing));
|
|
104
110
|
const mergedOrderRefs = orders.length > 1 ? orders.map(order => ({ customerContractId: order.customerContractId, purchaseOrderId: order.purchaseOrderId, salesOrderNo: order.salesOrderNo })) : null;
|
|
105
|
-
const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint })).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');
|
|
106
112
|
const shipmentReference = `SHIP-${createHash('sha256').update(`${ordersKey}:${packing?.fingerprint ?? ''}:${orderDataFingerprint}`).digest('hex').slice(0, 16)}`;
|
|
107
113
|
const batchGenerationId = input.fileType === 'ALL' ? randomUUID() : undefined;
|
|
108
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
|
+
};
|
|
109
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
|
+
}
|
|
110
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, '历史销售文件已变化,请重新生成文件');
|
|
111
190
|
const repo = manager.getRepository(GeneratedSalesFile);
|
|
112
|
-
|
|
113
|
-
// Serialize with uploads, import persistence and packing edits. Translation may
|
|
114
|
-
// have taken time since preflight: never commit a stale shipment snapshot.
|
|
115
|
-
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
116
|
-
const currentMaterials = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds, manager) ?? [];
|
|
117
|
-
if (createHash('sha256').update(JSON.stringify(currentMaterials)).digest('hex') !== materialsFingerprint)
|
|
118
|
-
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商资料已变化,请重新生成文件');
|
|
119
|
-
const currentPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input, manager) : null;
|
|
120
|
-
for (const warning of currentPacking?.warnings ?? [])
|
|
121
|
-
if (!generationWarnings.some(existing => existing.code === warning.code && existing.message === warning.message))
|
|
122
|
-
generationWarnings.push(warning);
|
|
123
|
-
if ((currentPacking?.fingerprint ?? '') !== (packing?.fingerprint ?? ''))
|
|
124
|
-
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '装箱数据已变化,请重新生成文件');
|
|
125
|
-
}
|
|
126
|
-
if (['PI_CI_PL', 'ALL'].includes(input.fileType)) {
|
|
127
|
-
const lockedPurchaseOrder = await manager.getRepository(PurchaseOrder).findOne({
|
|
128
|
-
where: { ...scoped(scope), id: purchaseOrder.id, deletedAt: IsNull() },
|
|
129
|
-
lock: { mode: 'pessimistic_write' }
|
|
130
|
-
});
|
|
131
|
-
if (!lockedPurchaseOrder)
|
|
132
|
-
throw new DomainError(DomainErrorCodes.NOT_FOUND, '采购订单不存在');
|
|
133
|
-
}
|
|
134
|
-
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' } }) : [];
|
|
135
|
-
// Local-only historical results must not keep a new workspace generation pinned to a missing container file.
|
|
136
|
-
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 }));
|
|
137
|
-
const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
|
|
138
|
-
const existingByType = new Map(existing.map(item => [item.fileType, item]));
|
|
139
|
-
const missingTypes = requestedTypes.filter(fileType => !existingByType.has(fileType));
|
|
140
|
-
const created = [];
|
|
141
|
-
for (const fileType of missingTypes) {
|
|
142
|
-
const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
|
|
143
|
-
const sourceDerived = fileType === 'CUSTOMS_DECLARATION' ? { ...derived, lines: derived.lines.map((line, index) => ({ ...line, hsCode: materialData.customsLines[index].hsCode })) } : derived;
|
|
144
|
-
const fileDerived = shipmentDerived(sourceDerived, packing, fileType);
|
|
145
|
-
const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? materialData.customsLines : purchaseLines;
|
|
146
|
-
const fileWarnings = generationWarnings.filter(warning => {
|
|
147
|
-
const field = String(warning.field ?? '');
|
|
148
|
-
if (String(warning.code ?? '').startsWith('CUSTOMS_') && fileType !== 'CUSTOMS_DECLARATION')
|
|
149
|
-
return false;
|
|
150
|
-
if (fileType === 'CUSTOMS_DECLARATION' && (String(warning.code ?? '').startsWith('TRANSLATION_') || warning.code === 'SOURCE_FIELD_REVIEW'))
|
|
151
|
-
return false;
|
|
152
|
-
if (field.startsWith('packing.'))
|
|
153
|
-
return fileType === 'PL';
|
|
154
|
-
if (fileType === 'PL' && (field.startsWith('clause.') || /^line\..+\.(description|unit)$/.test(field)))
|
|
155
|
-
return false;
|
|
156
|
-
return true;
|
|
157
|
-
});
|
|
158
|
-
if (fileType === 'CUSTOMS_DECLARATION')
|
|
159
|
-
fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述仅使用已知信息,申报要素、法定计量单位等请人工补全;本文件尚未提交海关。' });
|
|
160
|
-
const request = { currencyCode: documentPricing.currencyCode, ...(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 };
|
|
161
|
-
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 } };
|
|
162
|
-
const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
|
|
163
|
-
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, generationWarnings: fileWarnings }, logo);
|
|
164
|
-
await validateWorkbook(buffer);
|
|
165
|
-
const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
|
|
166
|
-
const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
|
|
167
|
-
const checksum = createHash('sha256').update(await templateBuffer(fileType)).digest('hex');
|
|
168
|
-
const storageFileId = await this.fileStorage.save(scope, buffer, fileName, context);
|
|
169
|
-
newStorageFileIds.push(storageFileId);
|
|
170
|
-
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 }));
|
|
171
|
-
}
|
|
172
|
-
const saved = created.length ? await repo.save(created) : [];
|
|
191
|
+
const saved = remainingTypes.length ? await repo.save(remainingTypes.map(type => stagedByType.get(type))) : [];
|
|
173
192
|
const savedByType = new Map(saved.map(item => [item.fileType, item]));
|
|
174
|
-
|
|
193
|
+
const results = requestedTypes.map(fileType => generationResult(existingByType.get(fileType) ?? savedByType.get(fileType)));
|
|
194
|
+
await hooks?.beforeCommit(manager, results);
|
|
195
|
+
return results;
|
|
175
196
|
});
|
|
197
|
+
files.forEach(file => retainedStorageIds.add(file.storageFileId));
|
|
176
198
|
return ['PI_CI_PL', 'ALL'].includes(input.fileType) ? { files } : files[0];
|
|
177
199
|
}
|
|
178
|
-
|
|
179
|
-
await Promise.allSettled(newStorageFileIds.map(storageFileId => this.fileStorage.remove(scope, storageFileId)));
|
|
180
|
-
throw error;
|
|
200
|
+
finally {
|
|
201
|
+
await Promise.allSettled(newStorageFileIds.filter(id => !retainedStorageIds.has(id)).map(storageFileId => this.fileStorage.remove(scope, storageFileId)));
|
|
181
202
|
}
|
|
182
203
|
}
|
|
183
|
-
async evaluate(scope, input) {
|
|
204
|
+
async evaluate(scope, input, manager) {
|
|
205
|
+
const source = manager ?? this.dataSource;
|
|
184
206
|
// 合并生成:orders 指定同客户的多个销售订单(合同+采购单);缺省退化为单订单生成
|
|
185
207
|
const currencyCode = input.currencyCode ?? 'CNY';
|
|
186
208
|
if (currencyCode !== 'CNY' && currencyCode !== 'USD')
|
|
187
209
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '文件币种仅支持 CNY 或 USD');
|
|
188
210
|
const orderRefs = normalizeGenerationOrders(input);
|
|
189
|
-
const allDerived = await this.workbench.listDerivedSalesOrders(scope);
|
|
211
|
+
const allDerived = await (manager ? this.workbench.listDerivedSalesOrders(scope, undefined, undefined, manager) : this.workbench.listDerivedSalesOrders(scope));
|
|
190
212
|
const orderEntries = orderRefs.map(ref => {
|
|
191
213
|
const derived = allDerived.find(item => item.customerContractId === ref.customerContractId && item.purchaseOrderId === ref.purchaseOrderId);
|
|
192
214
|
if (!derived)
|
|
@@ -196,9 +218,9 @@ let SalesFileService = class SalesFileService {
|
|
|
196
218
|
return { ref, derived };
|
|
197
219
|
}).sort((a, b) => a.derived.salesOrderNo.localeCompare(b.derived.salesOrderNo));
|
|
198
220
|
const primary = orderEntries[0];
|
|
199
|
-
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)));
|
|
200
222
|
const customerContract = contracts[0];
|
|
201
|
-
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)));
|
|
202
224
|
const customer = customers[0];
|
|
203
225
|
if (customers.some(item => item.id !== customer.id))
|
|
204
226
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '合并生成的销售订单必须属于同一客户');
|
|
@@ -207,7 +229,7 @@ let SalesFileService = class SalesFileService {
|
|
|
207
229
|
// 逐字比对会误伤语义相同的条款;均未提取到条款的合同不参与比对(缺失 ≠ 不一致)。
|
|
208
230
|
let paymentTermsVariants = null;
|
|
209
231
|
if (orderEntries.length > 1) {
|
|
210
|
-
const clauseRows = await
|
|
232
|
+
const clauseRows = await source.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: In(orderEntries.map(entry => entry.ref.customerContractId)), deletedAt: IsNull() } });
|
|
211
233
|
const termsByContract = new Map();
|
|
212
234
|
for (const clause of clauseRows) {
|
|
213
235
|
if (clause.clauseType !== 'PAYMENT_TERMS')
|
|
@@ -222,7 +244,7 @@ let SalesFileService = class SalesFileService {
|
|
|
222
244
|
}
|
|
223
245
|
// 信用额度硬拦截:客户未收款总额超出信用额度(剩余额度为负)时,禁止生成任何销售文件。
|
|
224
246
|
if (customer.creditLimit != null) {
|
|
225
|
-
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]));
|
|
226
248
|
const unreceivedAmountCny = unreceivedByCustomer.get(customer.id) ?? '0.00';
|
|
227
249
|
const remainingCreditCny = new Decimal(customer.creditLimit).minus(unreceivedAmountCny);
|
|
228
250
|
if (remainingCreditCny.isNegative()) {
|
|
@@ -230,10 +252,10 @@ let SalesFileService = class SalesFileService {
|
|
|
230
252
|
}
|
|
231
253
|
}
|
|
232
254
|
const purchaseIds = [...new Set(orderEntries.flatMap(entry => entry.derived.purchaseOrderIds?.length ? entry.derived.purchaseOrderIds : [entry.ref.purchaseOrderId]))];
|
|
233
|
-
const purchaseOrderEntities = await Promise.all(purchaseIds.map(id => this.required(PurchaseOrder, scope, id, '采购订单不存在')));
|
|
255
|
+
const purchaseOrderEntities = await Promise.all(purchaseIds.map(id => this.required(PurchaseOrder, scope, id, '采购订单不存在', source)));
|
|
234
256
|
const purchaseOrder = purchaseOrderEntities.find(item => item.id === primary.ref.purchaseOrderId);
|
|
235
257
|
const purchaseOrderDates = new Map(purchaseOrderEntities.map(item => [item.id, item.orderDate]));
|
|
236
|
-
const sourcePurchaseLines = await
|
|
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' } });
|
|
237
259
|
const purchaseLinesById = new Map(sourcePurchaseLines.map(line => [line.id, line]));
|
|
238
260
|
const lineIds = orderEntries.flatMap(entry => entry.derived.lines.map(line => line.purchaseOrderLineId));
|
|
239
261
|
if (sourcePurchaseLines.length !== lineIds.length || purchaseLinesById.size !== sourcePurchaseLines.length || new Set(lineIds).size !== lineIds.length || lineIds.some(id => !purchaseLinesById.has(id))) {
|
|
@@ -241,7 +263,7 @@ let SalesFileService = class SalesFileService {
|
|
|
241
263
|
}
|
|
242
264
|
// All downstream arrays share the final sales order, including translations and snapshots.
|
|
243
265
|
const purchaseLines = lineIds.map(id => purchaseLinesById.get(id));
|
|
244
|
-
const rule = await
|
|
266
|
+
const rule = await source.getRepository(ProfitRuleSettings).findOne({ where: scoped(scope), ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
245
267
|
if (!rule)
|
|
246
268
|
throw new DomainError(DomainErrorCodes.PROFIT_RULE_UNCONFIGURED, '利润率规则未配置');
|
|
247
269
|
if (parseProfitRuleStatus(rule.status) !== 'ACTIVE')
|
|
@@ -284,7 +306,7 @@ let SalesFileService = class SalesFileService {
|
|
|
284
306
|
let rate = monthlyRates.get(month);
|
|
285
307
|
if (!rate) {
|
|
286
308
|
const [year, monthNumber] = month.split('-').map(Number);
|
|
287
|
-
const found = await
|
|
309
|
+
const found = await source.getRepository(MonthlySafeExchangeRate).findOne({ where: { ...scoped(scope), year, month: monthNumber, currencyCode: 'USD', deletedAt: IsNull() }, ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
288
310
|
if (!found)
|
|
289
311
|
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `缺少 ${month} 月外汇管理局首日美元汇率(1 USD = X CNY)`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
290
312
|
try {
|
|
@@ -293,6 +315,8 @@ let SalesFileService = class SalesFileService {
|
|
|
293
315
|
catch {
|
|
294
316
|
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `${month} 月美元汇率无效,请维护有效的月度美元汇率`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
295
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}),请在正式交易前维护并核实有效汇率。` });
|
|
296
320
|
rate = found;
|
|
297
321
|
monthlyRates.set(month, rate);
|
|
298
322
|
}
|
|
@@ -328,7 +352,7 @@ let SalesFileService = class SalesFileService {
|
|
|
328
352
|
if (!input.bankType)
|
|
329
353
|
throw new SalesFileEvaluationError(DomainErrorCodes.BANK_ACCOUNT_REQUIRED, '生成 PI 或 CI 前必须选择银行信息', {}, compliance.complianceProfitRate.toString(), exchangeCost?.toString() ?? null, warnings);
|
|
330
354
|
const bankType = parseBankAccountType(input.bankType);
|
|
331
|
-
bank = await
|
|
355
|
+
bank = await source.getRepository(BankAccountSettings).findOne({ where: { ...scoped(scope), bankType }, ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
|
|
332
356
|
if (!bank)
|
|
333
357
|
throw new SalesFileEvaluationError(DomainErrorCodes.BANK_ACCOUNT_REQUIRED, '所选银行信息尚未维护', { bankType: input.bankType }, compliance.complianceProfitRate.toString(), exchangeCost?.toString() ?? null, warnings);
|
|
334
358
|
parseBankAccountType(bank.bankType);
|
|
@@ -363,6 +387,31 @@ let SalesFileService = class SalesFileService {
|
|
|
363
387
|
const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
|
|
364
388
|
return { item, buffer: await this.fileStorage.read(scope, item.storageFileId) };
|
|
365
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
|
+
}
|
|
366
415
|
async saveEditedWorkbook(scope, id, buffer, expected, context) {
|
|
367
416
|
const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
|
|
368
417
|
const limits = editedWorkbookLimits();
|
|
@@ -483,8 +532,8 @@ let SalesFileService = class SalesFileService {
|
|
|
483
532
|
return undefined;
|
|
484
533
|
return this.workbench.readCompanyLogo(scope, logoFileId);
|
|
485
534
|
}
|
|
486
|
-
async required(entity, scope, id, message) {
|
|
487
|
-
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() } });
|
|
488
537
|
if (!item)
|
|
489
538
|
throw new DomainError(DomainErrorCodes.NOT_FOUND, message);
|
|
490
539
|
return item;
|
|
@@ -652,7 +701,7 @@ function generationRequestMatches(item, expected) {
|
|
|
652
701
|
return Boolean(request &&
|
|
653
702
|
typeof request === 'object' &&
|
|
654
703
|
!Array.isArray(request) &&
|
|
655
|
-
request.exportIntegrityVersion ===
|
|
704
|
+
request.exportIntegrityVersion === SALES_EXPORT_INTEGRITY_VERSION &&
|
|
656
705
|
request.currencyCode === expected.currencyCode &&
|
|
657
706
|
request.fileNumber === expected.fileNumber &&
|
|
658
707
|
request.templateVersion === expected.templateVersion &&
|
|
@@ -1168,7 +1217,12 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1168
1217
|
set(sheet, 'C9', packing?.totals.cartons > 0 ? packing.totals.cartons : '待确认');
|
|
1169
1218
|
set(sheet, 'D9', packing?.totals.grossKg > 0 ? packing.totals.grossKg : '待确认');
|
|
1170
1219
|
set(sheet, 'E9', '待确认');
|
|
1171
|
-
|
|
1220
|
+
const terms = [...new Set(((deliveryClauseText(data.clauses ?? []) || '').toUpperCase().match(/\b(?:EXW|FCA|FAS|FOB|CFR|CIF|CPT|CIP|DAP|DPU|DDP)\b/g) ?? []))];
|
|
1221
|
+
set(sheet, 'F9', terms.length === 1 ? terms[0] : '待确认');
|
|
1222
|
+
for (const address of ['F6', 'H6']) {
|
|
1223
|
+
set(sheet, address, null);
|
|
1224
|
+
markReview(sheet.getCell(address));
|
|
1225
|
+
}
|
|
1172
1226
|
set(sheet, 'A9', '待确认');
|
|
1173
1227
|
set(sheet, 'G9', '待确认');
|
|
1174
1228
|
set(sheet, 'I9', '待确认');
|
|
@@ -1206,6 +1260,8 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1206
1260
|
function normalizeCustomsConfirmationRow(sheet, row) {
|
|
1207
1261
|
safeMerge(sheet, `A${row}:L${row}`);
|
|
1208
1262
|
const cell = sheet.getCell(row, 1);
|
|
1263
|
+
cell.value = '特殊关系确认: 价格影响确认: 特许权使用费确认: 自报自缴:';
|
|
1264
|
+
markReview(cell);
|
|
1209
1265
|
cell.alignment = { ...cell.alignment, horizontal: 'center', vertical: 'middle', shrinkToFit: true, wrapText: false };
|
|
1210
1266
|
}
|
|
1211
1267
|
/** PL v2 布局:数据区 20 行原型整体伸缩;合计区(标签+合并+边框)显式快照重建,避免 ExcelJS 行平移丢失内容。 */
|
|
@@ -1379,7 +1435,7 @@ function deterministicEnglish(value, field) {
|
|
|
1379
1435
|
const normalized = normalizeKnownBusinessTerms(text);
|
|
1380
1436
|
if (normalized !== text && !/\p{Script=Han}/u.test(normalized))
|
|
1381
1437
|
return normalized;
|
|
1382
|
-
if (/^[\
|
|
1438
|
+
if (/^[\p{Script=Latin}\p{N}\p{P}\p{S}\p{Z}\s]+$/u.test(text) && /[A-Za-z0-9]/.test(text))
|
|
1383
1439
|
return text;
|
|
1384
1440
|
return null;
|
|
1385
1441
|
}
|
|
@@ -1437,4 +1493,7 @@ function unitFallback(value) {
|
|
|
1437
1493
|
const dictionary = { 台: 'pcs', 块: 'pcs', 个: 'pcs', 件: 'pcs', 只: 'pcs', 支: 'pcs', 套: 'set', 千克: 'kg', 公斤: 'kg', 米: 'm', PCS: 'PCS', pcs: 'pcs', SET: 'set', set: 'set' };
|
|
1438
1494
|
return dictionary[value.trim()] ?? null;
|
|
1439
1495
|
}
|
|
1496
|
+
function generationSourceFingerprint(evaluated, company, clauses) {
|
|
1497
|
+
return createHash('sha256').update(JSON.stringify({ evaluated, company, clauses })).digest('hex');
|
|
1498
|
+
}
|
|
1440
1499
|
//# sourceMappingURL=sales-file.service.js.map
|