@chenchaolong/plugin-trade-compliance-workbench 1.0.236 → 1.0.238

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.
@@ -1,4 +1,6 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
+ import { customsPackingWeights } from './customs-packing-weight.js';
3
+ import { addPackingPiModelColumn } from './packing/packing-pi-model-column.js';
2
4
  import { scopeCustomsDocument, isPlaceholderCustomerName } from './customs-document-scope.js';
3
5
  import { recoverPurchaseSourceCities, extractCityName } from './import-jobs/purchase-source-city.js';
4
6
  import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
@@ -40,8 +42,8 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
40
42
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
41
43
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
42
44
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
43
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-11.customs-material-scope';
44
- const PACKING_LAYOUT_VERSION = 'v16';
45
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-11.customs-pl-net-estimate-80';
46
+ const PACKING_LAYOUT_VERSION = 'v19';
45
47
  const COMPANY_LOGO_PLACEMENTS = {
46
48
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
47
49
  CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -65,9 +67,12 @@ let SalesFileService = class SalesFileService {
65
67
  const result = preflightResult(input, evaluated.compliance.complianceProfitRate.toString(), evaluated.exchangeCost?.toString() ?? null, evaluated.warnings, packing);
66
68
  const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
67
69
  const materialData = generationMaterials(evaluated.purchaseLines, materialDocs);
70
+ const customsWeights = customsPackingWeights(packingData, materialData.customsLines.filter(line => !materialData.customsScope || materialData.customsScope.purchaseOrderLineIds.includes(line.id)));
68
71
  if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType))
69
- result.customsCoverage = materialData.customsDocumentCoverage;
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'));
72
+ result.customsCoverage = { ...materialData.customsDocumentCoverage, sourceNetWeightKg: null, acceptedNetWeightKg: customsWeights.totalNetWeightKg == null ? null : String(customsWeights.totalNetWeightKg) };
73
+ const materialWarnings = materialData.warnings.filter(warning => !warning.code.startsWith('CUSTOMS_NET_WEIGHT_') && (!warning.code.startsWith('CUSTOMS_') || ['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType)) && (!warning.code.startsWith('ENGLISH_') || input.fileType !== 'CUSTOMS_DECLARATION'));
74
+ if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType))
75
+ materialWarnings.push({ code: 'CUSTOMS_PACKING_NET_WEIGHT_ESTIMATED', message: '净重暂按PL毛重×80%估算并标色;共箱仅在单品净重完整且能与整箱核对时采用,无法确认的商品净重留空。' });
71
76
  const priceWarnings = evaluated.warnings.filter(warning => warning.code === 'PURCHASE_NET_PRICE_CONFLICT');
72
77
  if (materialWarnings.length || priceWarnings.length)
73
78
  result.materialWarnings = [...materialWarnings, ...priceWarnings];
@@ -110,6 +115,7 @@ let SalesFileService = class SalesFileService {
110
115
  generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
111
116
  const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
112
117
  const materialData = generationMaterials(purchaseLines, materialDocuments);
118
+ const customsWeights = customsPackingWeights(packing, materialData.customsLines.filter(line => !materialData.customsScope || materialData.customsScope.purchaseOrderLineIds.includes(line.id)));
113
119
  const customsSourceCities = requestedTypes.includes('CUSTOMS_DECLARATION') ? await recoverPurchaseSourceCities(evaluated.purchaseOrderEntities, id => this.storage.read(id)) : {};
114
120
  if (requestedTypes.includes('CUSTOMS_DECLARATION'))
115
121
  for (const line of materialData.customsLines.filter(line => !materialData.customsScope || materialData.customsScope.purchaseOrderLineIds.includes(line.id))) {
@@ -117,7 +123,9 @@ let SalesFileService = class SalesFileService {
117
123
  if (!line.domesticSourceLocation)
118
124
  generationWarnings.push({ code: 'CUSTOMS_SOURCE_CITY_MISSING', purchaseOrderLineId: line.id, message: `商品“${line.productName}”对应采购合同未找到可确定的卖方城市,货源地留空。` });
119
125
  }
120
- generationWarnings.push(...materialData.warnings);
126
+ generationWarnings.push(...materialData.warnings.filter(warning => !warning.code.startsWith('CUSTOMS_NET_WEIGHT_')));
127
+ if (requestedTypes.includes('CUSTOMS_DECLARATION'))
128
+ generationWarnings.push({ code: 'CUSTOMS_PACKING_NET_WEIGHT_ESTIMATED', message: '净重暂按PL毛重×80%估算并标色;共箱仅在单品净重完整且能与整箱核对时采用,无法确认的商品净重留空。' });
121
129
  if (isPlaceholderCustomerName(customer.name))
122
130
  generationWarnings.push({ code: 'CUSTOMS_CUSTOMER_PLACEHOLDER_MISSING', field: 'customer.name', message: '收货人名称为占位内容,报关单保留原值并标色,请核对真实名称。' });
123
131
  const materialsFingerprint = materialSelectionFingerprint(materialDocuments);
@@ -149,11 +157,11 @@ let SalesFileService = class SalesFileService {
149
157
  for (const fileType of missingTypes) {
150
158
  const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
151
159
  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;
160
+ const fileCustomsCoverage = fileType === 'CUSTOMS_DECLARATION' ? { ...materialData.customsDocumentCoverage, sourceNetWeightKg: null, acceptedNetWeightKg: customsWeights.totalNetWeightKg == null ? null : String(customsWeights.totalNetWeightKg) } : materialData.customsCoverage;
153
161
  const fileDocumentPricing = customsData?.snapshot.documentPricing ?? documentPricing;
154
162
  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;
155
163
  const fileDerived = shipmentDerived(sourceDerived, packing, fileType);
156
- const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? customsData.purchaseLines : purchaseLines;
164
+ const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? customsData.purchaseLines.map((line) => ({ ...line, netWeightKg: customsWeights.byLine[line.id]?.netWeightKg })) : purchaseLines;
157
165
  const fileWarnings = generationWarnings.filter(warning => {
158
166
  const field = String(warning.field ?? '');
159
167
  if (String(warning.code ?? '').startsWith('CUSTOMS_') && fileType !== 'CUSTOMS_DECLARATION')
@@ -173,7 +181,7 @@ let SalesFileService = class SalesFileService {
173
181
  if (fileType === 'CUSTOMS_DECLARATION')
174
182
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
175
183
  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 };
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 } };
184
+ const snapshot = { ...(fileType === 'CUSTOMS_DECLARATION' ? { customsWeightSource: { type: 'SUPPLIER_PACKING', packingIds: packing?.batchIds ?? [], grossWeightKg: packing?.totals.grossKg ?? null, netWeightKg: customsWeights.totalNetWeightKg, method: 'PL_GROSS_80_PERCENT', ratio: 0.8, byLine: customsWeights.byLine } } : {}), customsScope: fileType === 'CUSTOMS_DECLARATION' ? materialData.customsScope : null, customsSourceCities, customsCoverage: fileCustomsCoverage, materials: fileType === 'CUSTOMS_DECLARATION' ? materialData.sources.map(source => source.documentType === 'CUSTOMS_INFO' ? { ...source, fields: source.fields.filter(field => field !== 'netWeightKg' || customsWeights.byLine[source.purchaseOrderLineId]?.source === 'REVIEWED_SHARED_ITEM_NET') } : source) : 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 } };
177
185
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
178
186
  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);
179
187
  await validateWorkbook(buffer);
@@ -935,6 +943,7 @@ export async function renderSalesWorkbook(type, data, logo) {
935
943
  if (type === 'PL')
936
944
  for (const packingSheet of [sheet, workbook.getWorksheet('Packaging Details')].filter((value) => Boolean(value))) {
937
945
  const rows = expandPackingTextRows(packingSheet);
946
+ addPackingPiModelColumn(packingSheet, completePackingRows(data).map((row, index) => ({ row: rows.get(index + 12) ?? index + 12, endRow: (rows.get(index + 13) ?? index + 13) - 1, model: row.piModel ?? '' })));
938
947
  for (const target of Object.values(fieldLocations)) {
939
948
  const [name, address] = target.location.split('!');
940
949
  const match = /^([A-Z]+)(\d+)$/.exec(address ?? '');
@@ -973,6 +982,9 @@ function applySingleSheetReview(sheet, type, data, locations) {
973
982
  const plRows = type === 'PL' ? completePackingRows(data) : [];
974
983
  for (const warning of [...(data.generationWarnings ?? []), ...(data.packing?.warnings ?? [])]) {
975
984
  const field = String(warning.field ?? ''), code = String(warning.code ?? '');
985
+ // PL has no prices: a purchase pricing conflict must not imply incorrect goods or quantities.
986
+ if (type === 'PL' && code === 'PURCHASE_NET_PRICE_CONFLICT')
987
+ continue;
976
988
  const color = /CONFLICT|EXCEEDED|TOTAL_DIFF/.test(code) ? 'FFFFC7CE' : /MISSING|NOT_PROVIDED/.test(code) ? 'FFFFF2CC' : 'FFFFE0B2';
977
989
  const target = locations[field];
978
990
  if (target?.location.startsWith(sheet.name + '!')) {
@@ -990,8 +1002,10 @@ function applySingleSheetReview(sheet, type, data, locations) {
990
1002
  });
991
1003
  if (/TOTAL_DIFF/.test(code)) {
992
1004
  const total = 12 + plRows.length;
993
- for (const offset of [0, 2, 3])
994
- markReview(sheet.getCell(total + offset, 6), color);
1005
+ const offset = { grossKg: 0, volumeCbm: 2, cartons: 3 }[warning.packingTotalField];
1006
+ // Old snapshots have no metric metadata; retain their conservative warning.
1007
+ for (const affected of offset == null ? [0, 2, 3] : [offset])
1008
+ markReview(sheet.getCell(total + affected, 6), color);
995
1009
  }
996
1010
  }
997
1011
  else if (purchaseId) {
@@ -1188,6 +1202,12 @@ function fillPackingSheet(sheet, data) {
1188
1202
  });
1189
1203
  stylePackingSheet(sheet, rows.length);
1190
1204
  fillPackingPhysicalRows(sheet, rows, data);
1205
+ // Choose after physical values/merges are filled; template formats can otherwise leak a trailing dot.
1206
+ for (let row = 12; row < totalsRow; row++)
1207
+ for (const column of [4, 7]) {
1208
+ const cell = sheet.getCell(row, column);
1209
+ cell.numFmt = typeof cell.value === 'number' && !Number.isInteger(cell.value) ? '0.######' : '0';
1210
+ }
1191
1211
  for (const address of ['B4', 'B5', 'B6', 'B7', 'B8', 'F4', 'F5', 'F6', 'F7', 'F8'])
1192
1212
  if (sheet.getCell(address).value === '—')
1193
1213
  markReview(sheet.getCell(address));
@@ -1207,7 +1227,7 @@ function fillPackingSheet(sheet, data) {
1207
1227
  if (line.quantity == null && !line.companion)
1208
1228
  markReview(sheet.getCell(row, 4));
1209
1229
  });
1210
- if (incomplete || packing?.warnings?.some((warning) => warning.code === 'PACKING_SOURCE_TOTAL_DIFF'))
1230
+ if (incomplete)
1211
1231
  for (const offset of [0, 1, 2, 3])
1212
1232
  markReview(sheet.getCell(totalsRow + offset, 6));
1213
1233
  if (totals[1] == null)
@@ -1330,11 +1350,12 @@ export function remittanceInformation(cnapsCode, goodsName, derived, civilUse) {
1330
1350
  }
1331
1351
  function fillCustomsSheet(sheet, data) {
1332
1352
  const { customer, purchaseOrder, derived, company, packing } = data;
1353
+ const weights = customsPackingWeights(packing, data.purchaseLines);
1333
1354
  const purchaseLines = derived.lines.map((line, index) => {
1334
1355
  const product = line.purchaseOrderLineId ? data.purchaseLines.find((item) => item.id === line.purchaseOrderLineId) : data.purchaseLines[index];
1335
1356
  if (!product)
1336
1357
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '报关商品缺少对应采购商品');
1337
- return product;
1358
+ return { ...product, netWeightKg: weights.byLine[product.id]?.netWeightKg };
1338
1359
  });
1339
1360
  const pricing = workbookDocumentPricing(data);
1340
1361
  resizeTwoRowSection(sheet, 14, 2, derived.lines.length, 12);
@@ -1351,7 +1372,9 @@ function fillCustomsSheet(sheet, data) {
1351
1372
  // Template row 9 contains packaging values; H8/J8 belong to freight/insurance.
1352
1373
  set(sheet, 'C9', packing?.totals.cartons > 0 ? packing.totals.cartons : '待确认');
1353
1374
  set(sheet, 'D9', packing?.totals.grossKg > 0 ? packing.totals.grossKg : '待确认');
1354
- set(sheet, 'E9', data.customsCoverage?.acceptedNetWeightKg != null ? Number(data.customsCoverage.acceptedNetWeightKg) : '待确认');
1375
+ set(sheet, 'E9', weights.totalNetWeightKg ?? '待确认');
1376
+ if (weights.totalNetWeightKg != null)
1377
+ markReview(sheet.getCell('E9'), 'FFFFE0B2');
1355
1378
  set(sheet, 'L8', pricing.currencyCode === 'USD' ? '美元' : '人民币');
1356
1379
  const terms = [...new Set(((deliveryClauseText(data.clauses ?? []) || '').toUpperCase().match(/\b(?:EXW|FCA|FAS|FOB|CFR|CIF|CPT|CIP|DAP|DPU|DDP)\b/g) ?? []))];
1357
1380
  set(sheet, 'F9', terms.length === 1 ? terms[0] : '待确认');
@@ -1391,12 +1414,10 @@ function fillCustomsSheet(sheet, data) {
1391
1414
  const quantities = customsQuantityRows(product, derived.lines[index]);
1392
1415
  // Price belongs to the commercial quantity row, never the statutory kg row
1393
1416
  // merely because it is first in the declaration template.
1394
- const tradeRow = quantities.findIndex(entry => entry.quantity != null && customsUnitsCompatible(product.unit, entry.unit));
1417
+ const tradeRow = quantities.findIndex(entry => customsUnitsCompatible(product.unit, entry.unit));
1395
1418
  const priceRow = row + Math.max(0, tradeRow);
1396
1419
  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());
1420
+ // Retain source text and financial values; communicate unit conflicts by color only.
1400
1421
  markReview(sheet.getCell(`C${row}`), 'FFFFE0B2');
1401
1422
  markReview(sheet.getCell(`F${priceRow}`), 'FFFFE0B2');
1402
1423
  }
@@ -1408,6 +1429,8 @@ function fillCustomsSheet(sheet, data) {
1408
1429
  set(sheet, `E${row + offset}`, entry.unit);
1409
1430
  if (entry.review)
1410
1431
  markReview(sheet.getCell(`D${row + offset}`));
1432
+ if (weights.byLine[product.id]?.estimated && /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(entry.unit) && entry.quantity != null)
1433
+ markReview(sheet.getCell(`D${row + offset}`), 'FFFFE0B2');
1411
1434
  if (entry.inferred)
1412
1435
  for (const column of ['D', 'E'])
1413
1436
  markReview(sheet.getCell(`${column}${row + offset}`), 'FFFFE0B2');
@@ -1416,7 +1439,7 @@ function fillCustomsSheet(sheet, data) {
1416
1439
  if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
1417
1440
  markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
1418
1441
  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, '')}"` : '');
1442
+ sheet.getCell(`F${priceRow}`).numFmt = priceFormat;
1420
1443
  sheet.getCell(`G${priceRow}`).numFmt = '0.00';
1421
1444
  }
1422
1445
  const tail = 14 + derived.lines.length * 2;
@@ -1448,8 +1471,8 @@ function customsQuantityRows(product, commercial) {
1448
1471
  if (isKg(unit)) {
1449
1472
  const weight = product.netWeightKg;
1450
1473
  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;
1474
+ // A commercial kg quantity cannot substitute for missing PL net weight.
1475
+ const quantity = valid ? weight : null;
1453
1476
  return { unit, quantity, review: quantity == null, inferred };
1454
1477
  }
1455
1478
  const compatible = customsUnitsCompatible(product.unit, unit);