@chenchaolong/plugin-trade-compliance-workbench 1.0.234 → 1.0.236
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/customs-document-scope.d.ts +8 -0
- package/dist/lib/customs-document-scope.d.ts.map +1 -0
- package/dist/lib/customs-document-scope.js +29 -0
- package/dist/lib/customs-document-scope.js.map +1 -0
- package/dist/lib/domain/default-settings.d.ts +1 -0
- package/dist/lib/domain/default-settings.d.ts.map +1 -1
- package/dist/lib/domain/default-settings.js +1 -0
- package/dist/lib/domain/default-settings.js.map +1 -1
- package/dist/lib/entities/settings.entity.d.ts +2 -0
- package/dist/lib/entities/settings.entity.d.ts.map +1 -1
- package/dist/lib/entities/settings.entity.js +4 -0
- package/dist/lib/entities/settings.entity.js.map +1 -1
- package/dist/lib/packing/packing-complete-rows.d.ts +1 -1
- package/dist/lib/packing/packing-complete-rows.d.ts.map +1 -1
- package/dist/lib/packing/packing-complete-rows.js +16 -12
- package/dist/lib/packing/packing-complete-rows.js.map +1 -1
- package/dist/lib/packing/packing-full-text.d.ts.map +1 -1
- package/dist/lib/packing/packing-full-text.js +69 -8
- package/dist/lib/packing/packing-full-text.js.map +1 -1
- package/dist/lib/packing/packing-render.d.ts.map +1 -1
- package/dist/lib/packing/packing-render.js +2 -19
- package/dist/lib/packing/packing-render.js.map +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.js +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +61 -1
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +141 -127
- package/dist/lib/remote-ui/components/packing-generation-actions.js +1 -1
- package/dist/lib/remote-ui/components/packing-generation-actions.js.map +1 -1
- package/dist/lib/remote-ui/components/supplier-materials.d.ts +1 -0
- package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -1
- package/dist/lib/remote-ui/components/supplier-materials.js +2 -2
- package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -1
- package/dist/lib/remote-ui/pages/settings.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/settings.js +1 -1
- package/dist/lib/remote-ui/pages/settings.js.map +1 -1
- package/dist/lib/remote-ui/settings-contracts.d.ts +1 -0
- package/dist/lib/remote-ui/settings-contracts.d.ts.map +1 -1
- package/dist/lib/sales-file.service.d.ts +1 -1
- package/dist/lib/sales-file.service.d.ts.map +1 -1
- package/dist/lib/sales-file.service.js +68 -29
- package/dist/lib/sales-file.service.js.map +1 -1
- package/dist/lib/schema-maintenance.d.ts.map +1 -1
- package/dist/lib/schema-maintenance.js +2 -0
- package/dist/lib/schema-maintenance.js.map +1 -1
- package/dist/lib/supplier-materials/customs-coverage.js +1 -1
- package/dist/lib/supplier-materials/customs-coverage.js.map +1 -1
- package/dist/lib/supplier-materials/customs-packaging-recovery.d.ts +14 -0
- package/dist/lib/supplier-materials/customs-packaging-recovery.d.ts.map +1 -0
- package/dist/lib/supplier-materials/customs-packaging-recovery.js +29 -0
- package/dist/lib/supplier-materials/customs-packaging-recovery.js.map +1 -0
- package/dist/lib/supplier-materials/customs-source-fields.d.ts.map +1 -1
- package/dist/lib/supplier-materials/customs-source-fields.js +39 -1
- package/dist/lib/supplier-materials/customs-source-fields.js.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.d.ts +7 -0
- package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.js +29 -4
- package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.d.ts +2 -1
- package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.js +5 -2
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
- package/dist/lib/types.d.ts +1 -0
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +2 -0
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +7 -0
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +1 -1
- package/dist/lib/workbench.middleware.js.map +1 -1
- package/dist/lib/workbench.service.d.ts +1 -0
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +13 -4
- 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 { scopeCustomsDocument, isPlaceholderCustomerName } from './customs-document-scope.js';
|
|
2
3
|
import { recoverPurchaseSourceCities, extractCityName } from './import-jobs/purchase-source-city.js';
|
|
3
4
|
import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
|
|
4
5
|
import { generationMaterials } from './supplier-materials/generation-materials.js';
|
|
@@ -39,8 +40,8 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
|
|
|
39
40
|
export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
|
|
40
41
|
export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
|
|
41
42
|
export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
|
|
42
|
-
export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-
|
|
43
|
-
const PACKING_LAYOUT_VERSION = '
|
|
43
|
+
export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-11.customs-material-scope';
|
|
44
|
+
const PACKING_LAYOUT_VERSION = 'v16';
|
|
44
45
|
const COMPANY_LOGO_PLACEMENTS = {
|
|
45
46
|
PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
46
47
|
CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
|
|
@@ -65,12 +66,14 @@ let SalesFileService = class SalesFileService {
|
|
|
65
66
|
const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
|
|
66
67
|
const materialData = generationMaterials(evaluated.purchaseLines, materialDocs);
|
|
67
68
|
if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType))
|
|
68
|
-
result.customsCoverage = materialData.
|
|
69
|
+
result.customsCoverage = materialData.customsDocumentCoverage;
|
|
69
70
|
const materialWarnings = materialData.warnings.filter(warning => (!warning.code.startsWith('CUSTOMS_') || ['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType)) && (!warning.code.startsWith('ENGLISH_') || input.fileType !== 'CUSTOMS_DECLARATION'));
|
|
70
71
|
const priceWarnings = evaluated.warnings.filter(warning => warning.code === 'PURCHASE_NET_PRICE_CONFLICT');
|
|
71
72
|
if (materialWarnings.length || priceWarnings.length)
|
|
72
73
|
result.materialWarnings = [...materialWarnings, ...priceWarnings];
|
|
73
|
-
|
|
74
|
+
if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType) && isPlaceholderCustomerName(evaluated.customer.name))
|
|
75
|
+
result.materialWarnings = [...(result.materialWarnings ?? []), { code: 'CUSTOMS_CUSTOMER_PLACEHOLDER_MISSING', message: '收货人名称为占位内容,报关单保留原值并标色,请核对真实名称。' }];
|
|
76
|
+
result.documentPricing = input.fileType === 'CUSTOMS_DECLARATION' ? scopeCustomsDocument({ derived: evaluated.derived, purchaseLines: materialData.customsLines, customsScope: materialData.customsScope, snapshot: { documentPricing: evaluated.documentPricing } }).snapshot.documentPricing : evaluated.documentPricing;
|
|
74
77
|
result.packingWarnings = packingData?.warnings ?? [];
|
|
75
78
|
result.packingMode = input.packingMode ?? 'DRAFT';
|
|
76
79
|
if (needsPacking && this.packingService)
|
|
@@ -109,12 +112,14 @@ let SalesFileService = class SalesFileService {
|
|
|
109
112
|
const materialData = generationMaterials(purchaseLines, materialDocuments);
|
|
110
113
|
const customsSourceCities = requestedTypes.includes('CUSTOMS_DECLARATION') ? await recoverPurchaseSourceCities(evaluated.purchaseOrderEntities, id => this.storage.read(id)) : {};
|
|
111
114
|
if (requestedTypes.includes('CUSTOMS_DECLARATION'))
|
|
112
|
-
for (const line of materialData.customsLines) {
|
|
115
|
+
for (const line of materialData.customsLines.filter(line => !materialData.customsScope || materialData.customsScope.purchaseOrderLineIds.includes(line.id))) {
|
|
113
116
|
line.domesticSourceLocation = customsSourceCities[line.purchaseOrderId]?.city;
|
|
114
117
|
if (!line.domesticSourceLocation)
|
|
115
118
|
generationWarnings.push({ code: 'CUSTOMS_SOURCE_CITY_MISSING', purchaseOrderLineId: line.id, message: `商品“${line.productName}”对应采购合同未找到可确定的卖方城市,货源地留空。` });
|
|
116
119
|
}
|
|
117
120
|
generationWarnings.push(...materialData.warnings);
|
|
121
|
+
if (isPlaceholderCustomerName(customer.name))
|
|
122
|
+
generationWarnings.push({ code: 'CUSTOMS_CUSTOMER_PLACEHOLDER_MISSING', field: 'customer.name', message: '收货人名称为占位内容,报关单保留原值并标色,请核对真实名称。' });
|
|
118
123
|
const materialsFingerprint = materialSelectionFingerprint(materialDocuments);
|
|
119
124
|
await hooks?.progress('TRANSLATING', 0);
|
|
120
125
|
const translated = await this.translateDynamicFields(scope, customer, materialData.englishLines, clauses, generationWarnings, input.fileType, packing, new Set(materialData.sources.filter(source => source.documentType === 'ENGLISH_QUOTATION' && source.fields.includes('description')).map(source => source.purchaseOrderLineId)));
|
|
@@ -131,7 +136,7 @@ let SalesFileService = class SalesFileService {
|
|
|
131
136
|
const repo = source.getRepository(GeneratedSalesFile);
|
|
132
137
|
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' } } : {}) }) : [];
|
|
133
138
|
// Local-only historical results must not keep a new workspace generation pinned to a missing container file.
|
|
134
|
-
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 }));
|
|
139
|
+
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: item.fileType === 'CUSTOMS_DECLARATION' && materialData.customsScope ? materialData.customsScope.purchaseOrderLineIds : derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey, currencyCode: documentPricing.currencyCode }));
|
|
135
140
|
const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
|
|
136
141
|
return new Map(existing.map(item => [item.fileType, item]));
|
|
137
142
|
};
|
|
@@ -143,9 +148,12 @@ let SalesFileService = class SalesFileService {
|
|
|
143
148
|
await hooks?.progress('RENDERING', initialExisting.size);
|
|
144
149
|
for (const fileType of missingTypes) {
|
|
145
150
|
const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
|
|
146
|
-
const
|
|
151
|
+
const customsData = fileType === 'CUSTOMS_DECLARATION' ? scopeCustomsDocument({ derived, purchaseLines: materialData.customsLines, customsScope: materialData.customsScope, snapshot: { documentPricing } }) : null;
|
|
152
|
+
const fileCustomsCoverage = fileType === 'CUSTOMS_DECLARATION' ? materialData.customsDocumentCoverage : materialData.customsCoverage;
|
|
153
|
+
const fileDocumentPricing = customsData?.snapshot.documentPricing ?? documentPricing;
|
|
154
|
+
const sourceDerived = fileType === 'CUSTOMS_DECLARATION' ? { ...customsData.derived, lines: customsData.derived.lines.map((line) => ({ ...line, hsCode: materialData.customsLines.find(product => product.id === line.purchaseOrderLineId)?.hsCode ?? line.hsCode })) } : derived;
|
|
147
155
|
const fileDerived = shipmentDerived(sourceDerived, packing, fileType);
|
|
148
|
-
const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ?
|
|
156
|
+
const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? customsData.purchaseLines : purchaseLines;
|
|
149
157
|
const fileWarnings = generationWarnings.filter(warning => {
|
|
150
158
|
const field = String(warning.field ?? '');
|
|
151
159
|
if (String(warning.code ?? '').startsWith('CUSTOMS_') && fileType !== 'CUSTOMS_DECLARATION')
|
|
@@ -165,9 +173,9 @@ let SalesFileService = class SalesFileService {
|
|
|
165
173
|
if (fileType === 'CUSTOMS_DECLARATION')
|
|
166
174
|
fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
|
|
167
175
|
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: PACKING_LAYOUT_VERSION } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
|
|
168
|
-
const snapshot = { customsSourceCities, customsCoverage:
|
|
176
|
+
const snapshot = { customsScope: fileType === 'CUSTOMS_DECLARATION' ? materialData.customsScope : null, customsSourceCities, customsCoverage: fileCustomsCoverage, materials: materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing: fileDocumentPricing, 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: fileDerived.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 } };
|
|
169
177
|
const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
|
|
170
|
-
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, customsCoverage:
|
|
178
|
+
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, customsCoverage: fileCustomsCoverage, generationWarnings: fileWarnings }, logo);
|
|
171
179
|
await validateWorkbook(buffer);
|
|
172
180
|
const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
|
|
173
181
|
const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
|
|
@@ -838,6 +846,8 @@ function fillInvoiceSheet(sheet, type, data) {
|
|
|
838
846
|
fillIntermediaryChannelBankRows(sheet, { labelEnd: 'B', valueStart: 'C', valueEnd: 'J', lastColumn: 10 }, bankStart, type, bank, derived, translated, company);
|
|
839
847
|
}
|
|
840
848
|
export async function renderSalesWorkbook(type, data, logo) {
|
|
849
|
+
if (type === 'CUSTOMS_DECLARATION')
|
|
850
|
+
data = scopeCustomsDocument(data);
|
|
841
851
|
data = { ...data, derived: shipmentDerived(data.derived, data.packing, type) };
|
|
842
852
|
const workbook = new ExcelJS.Workbook();
|
|
843
853
|
await workbook.xlsx.load(await templateBuffer(type));
|
|
@@ -919,6 +929,8 @@ export async function renderSalesWorkbook(type, data, logo) {
|
|
|
919
929
|
markReview(cell);
|
|
920
930
|
}
|
|
921
931
|
}));
|
|
932
|
+
if (type === 'CUSTOMS_DECLARATION' && isPlaceholderCustomerName(data.customer?.name))
|
|
933
|
+
markReview(sheet.getCell('B5'));
|
|
922
934
|
applySingleSheetReview(sheet, type, data, fieldLocations);
|
|
923
935
|
if (type === 'PL')
|
|
924
936
|
for (const packingSheet of [sheet, workbook.getWorksheet('Packaging Details')].filter((value) => Boolean(value))) {
|
|
@@ -1154,7 +1166,7 @@ function fillPackingSheet(sheet, data) {
|
|
|
1154
1166
|
set(sheet, 'F5', orderDateValue === '' ? '—' : orderDateValue);
|
|
1155
1167
|
if (orderDateValue !== '')
|
|
1156
1168
|
sheet.getCell('F5').numFmt = 'yyyy/m/d';
|
|
1157
|
-
set(sheet, 'F6',
|
|
1169
|
+
set(sheet, 'F6', company?.contactName?.trim() || '—');
|
|
1158
1170
|
set(sheet, 'F7', company?.email || '—');
|
|
1159
1171
|
set(sheet, 'F8', company?.phone || '—');
|
|
1160
1172
|
rows.forEach((line, index) => {
|
|
@@ -1340,13 +1352,17 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1340
1352
|
set(sheet, 'C9', packing?.totals.cartons > 0 ? packing.totals.cartons : '待确认');
|
|
1341
1353
|
set(sheet, 'D9', packing?.totals.grossKg > 0 ? packing.totals.grossKg : '待确认');
|
|
1342
1354
|
set(sheet, 'E9', data.customsCoverage?.acceptedNetWeightKg != null ? Number(data.customsCoverage.acceptedNetWeightKg) : '待确认');
|
|
1355
|
+
set(sheet, 'L8', pricing.currencyCode === 'USD' ? '美元' : '人民币');
|
|
1343
1356
|
const terms = [...new Set(((deliveryClauseText(data.clauses ?? []) || '').toUpperCase().match(/\b(?:EXW|FCA|FAS|FOB|CFR|CIF|CPT|CIP|DAP|DPU|DDP)\b/g) ?? []))];
|
|
1344
1357
|
set(sheet, 'F9', terms.length === 1 ? terms[0] : '待确认');
|
|
1345
1358
|
for (const address of ['F6', 'H6']) {
|
|
1346
1359
|
set(sheet, address, null);
|
|
1347
1360
|
markReview(sheet.getCell(address));
|
|
1348
1361
|
}
|
|
1349
|
-
|
|
1362
|
+
const packagingTypes = [...new Set(purchaseLines.map((line) => String(line.packagingType ?? '').trim()).filter(Boolean))];
|
|
1363
|
+
set(sheet, 'A9', packagingTypes.join('、') || '待确认');
|
|
1364
|
+
if (packagingTypes.length > 1)
|
|
1365
|
+
markReview(sheet.getCell('A9'), 'FFFFE0B2');
|
|
1350
1366
|
set(sheet, 'G9', '待确认');
|
|
1351
1367
|
set(sheet, 'I9', '待确认');
|
|
1352
1368
|
set(sheet, 'K9', '待确认');
|
|
@@ -1358,7 +1374,8 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1358
1374
|
for (const offset of [0, 1])
|
|
1359
1375
|
for (const column of [6, 7, 8])
|
|
1360
1376
|
sheet.getCell(row + offset, column).value = null;
|
|
1361
|
-
|
|
1377
|
+
const fallbackDescription = [product.productDescription, product.modelSpecification && !String(product.productDescription ?? '').includes(product.modelSpecification) ? product.modelSpecification : null].filter(Boolean).join('\n');
|
|
1378
|
+
set(sheet, `C${row + 1}`, product.declarationElements || fallbackDescription || null);
|
|
1362
1379
|
if (!String(product.declarationElements ?? '').trim())
|
|
1363
1380
|
markReview(sheet.getCell(`C${row + 1}`));
|
|
1364
1381
|
safeMerge(sheet, `A${row}:A${row + 1}`);
|
|
@@ -1374,8 +1391,15 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1374
1391
|
const quantities = customsQuantityRows(product, derived.lines[index]);
|
|
1375
1392
|
// Price belongs to the commercial quantity row, never the statutory kg row
|
|
1376
1393
|
// merely because it is first in the declaration template.
|
|
1377
|
-
const
|
|
1378
|
-
const priceRow = row +
|
|
1394
|
+
const tradeRow = quantities.findIndex(entry => entry.quantity != null && customsUnitsCompatible(product.unit, entry.unit));
|
|
1395
|
+
const priceRow = row + Math.max(0, tradeRow);
|
|
1396
|
+
if (tradeRow < 0) {
|
|
1397
|
+
// Two statutory slots can be occupied by sets and kg. Keep commercial
|
|
1398
|
+
// pieces separately in the goods cell instead of silently equating units.
|
|
1399
|
+
set(sheet, `C${row}`, `${product.productName || ''}\n成交数量:${new Decimal(derived.lines[index].quantity).toString()} ${String(product.unit || '').trim()}`.trim());
|
|
1400
|
+
markReview(sheet.getCell(`C${row}`), 'FFFFE0B2');
|
|
1401
|
+
markReview(sheet.getCell(`F${priceRow}`), 'FFFFE0B2');
|
|
1402
|
+
}
|
|
1379
1403
|
set(sheet, `F${priceRow}`, Number(pricing.lines[index].unitPrice));
|
|
1380
1404
|
set(sheet, `G${priceRow}`, Number(pricing.lines[index].lineAmount));
|
|
1381
1405
|
set(sheet, `H${priceRow}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
|
|
@@ -1384,11 +1408,15 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1384
1408
|
set(sheet, `E${row + offset}`, entry.unit);
|
|
1385
1409
|
if (entry.review)
|
|
1386
1410
|
markReview(sheet.getCell(`D${row + offset}`));
|
|
1411
|
+
if (entry.inferred)
|
|
1412
|
+
for (const column of ['D', 'E'])
|
|
1413
|
+
markReview(sheet.getCell(`${column}${row + offset}`), 'FFFFE0B2');
|
|
1387
1414
|
}
|
|
1388
1415
|
for (const warning of data.generationWarnings ?? [])
|
|
1389
1416
|
if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
|
|
1390
1417
|
markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
|
|
1391
|
-
|
|
1418
|
+
const priceFormat = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
|
|
1419
|
+
sheet.getCell(`F${priceRow}`).numFmt = priceFormat + (tradeRow < 0 && product.unit ? `" / ${String(product.unit).replace(/["\\]/g, '')}"` : '');
|
|
1392
1420
|
sheet.getCell(`G${priceRow}`).numFmt = '0.00';
|
|
1393
1421
|
}
|
|
1394
1422
|
const tail = 14 + derived.lines.length * 2;
|
|
@@ -1396,27 +1424,38 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1396
1424
|
set(sheet, `B${tail + 3}`, companyText);
|
|
1397
1425
|
}
|
|
1398
1426
|
/** Quantity order follows explicit statutory units; trade quantity and sale pricing remain independent. */
|
|
1427
|
+
function customsUnitsCompatible(source, target) {
|
|
1428
|
+
const normalize = (value) => String(value ?? '').normalize('NFKC').trim().toLowerCase().replace(/\.$/, '');
|
|
1429
|
+
const a = normalize(source), b = normalize(target);
|
|
1430
|
+
const count = /^(?:pcs?|pieces?|个|件|台)$/;
|
|
1431
|
+
const set = /^(?:sets?|套)$/;
|
|
1432
|
+
const kg = /^(?:千克|公斤|kg|kgs|kilograms?)$/;
|
|
1433
|
+
return Boolean(a && b) && (a === b || count.test(a) && count.test(b) || set.test(a) && set.test(b) || kg.test(a) && kg.test(b));
|
|
1434
|
+
}
|
|
1399
1435
|
function customsQuantityRows(product, commercial) {
|
|
1400
|
-
const
|
|
1436
|
+
const explicitPrimary = String(product.statutoryUnitPrimary || '').trim();
|
|
1401
1437
|
const isKg = (unit) => /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(unit);
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1438
|
+
const tradeUnit = String(product.unit || '').trim();
|
|
1439
|
+
// Commercial quantities must remain visible. A purchase unit is traceable
|
|
1440
|
+
// evidence, not a confirmed statutory unit: mark the fallback for review.
|
|
1441
|
+
const primary = explicitPrimary || tradeUnit;
|
|
1442
|
+
const explicitSecondary = String(product.statutoryUnitSecondary || '').trim();
|
|
1443
|
+
const secondary = explicitSecondary || (isKg(primary) && tradeUnit && !isKg(tradeUnit) ? tradeUnit : '');
|
|
1444
|
+
return [primary, secondary].map((unit, index) => {
|
|
1445
|
+
const inferred = Boolean(unit && (index === 0 ? !explicitPrimary : !explicitSecondary));
|
|
1405
1446
|
if (!unit)
|
|
1406
1447
|
return { unit, quantity: null, review: false };
|
|
1407
1448
|
if (isKg(unit)) {
|
|
1408
1449
|
const weight = product.netWeightKg;
|
|
1409
|
-
const valid = typeof weight === 'number' && Number.isFinite(weight) && weight
|
|
1410
|
-
|
|
1450
|
+
const valid = typeof weight === 'number' && Number.isFinite(weight) && weight > 0;
|
|
1451
|
+
// If the commercial unit itself is kg, its quantity remains authoritative.
|
|
1452
|
+
const quantity = isKg(tradeUnit) && Number.isFinite(Number(commercial.quantity)) && commercial.quantity != null ? Number(commercial.quantity) : valid ? weight : null;
|
|
1453
|
+
return { unit, quantity, review: quantity == null, inferred };
|
|
1411
1454
|
}
|
|
1412
|
-
const
|
|
1413
|
-
const
|
|
1414
|
-
const setUnit = (value) => /^(?:sets?|套)$/.test(value);
|
|
1415
|
-
const sourceUnit = normalizedUnit(product.unit);
|
|
1416
|
-
const targetUnit = normalizedUnit(unit);
|
|
1417
|
-
const compatible = Boolean(sourceUnit) && (sourceUnit === targetUnit || (countUnit(sourceUnit) && countUnit(targetUnit)) || (setUnit(sourceUnit) && setUnit(targetUnit)));
|
|
1455
|
+
const compatible = customsUnitsCompatible(product.unit, unit);
|
|
1456
|
+
const sourceQuantity = (index === (isKg(primary) ? 1 : 0)) && product.customsSourceQuantity != null && Number.isFinite(Number(product.customsSourceQuantity)) && Number(product.customsSourceQuantity) > 0 ? Number(product.customsSourceQuantity) : null;
|
|
1418
1457
|
const valid = compatible && commercial.quantity != null && Number.isFinite(Number(commercial.quantity));
|
|
1419
|
-
return { unit, quantity: valid ? Number(commercial.quantity) :
|
|
1458
|
+
return { unit, quantity: valid ? Number(commercial.quantity) : sourceQuantity, review: !valid, inferred };
|
|
1420
1459
|
});
|
|
1421
1460
|
}
|
|
1422
1461
|
function normalizeCustomsConfirmationRow(sheet, row) {
|