@chenchaolong/plugin-trade-compliance-workbench 1.0.224 → 1.0.226

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.
Files changed (85) hide show
  1. package/dist/lib/analytics-export.js +2 -2
  2. package/dist/lib/analytics-export.js.map +1 -1
  3. package/dist/lib/customs-formatting.d.ts.map +1 -1
  4. package/dist/lib/customs-formatting.js +3 -0
  5. package/dist/lib/customs-formatting.js.map +1 -1
  6. package/dist/lib/import-jobs/customer-country.d.ts +3 -0
  7. package/dist/lib/import-jobs/customer-country.d.ts.map +1 -0
  8. package/dist/lib/import-jobs/customer-country.js +28 -0
  9. package/dist/lib/import-jobs/customer-country.js.map +1 -0
  10. package/dist/lib/import-jobs/import-command.builder.js +1 -1
  11. package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
  12. package/dist/lib/import-jobs/source-field-recovery.d.ts.map +1 -1
  13. package/dist/lib/import-jobs/source-field-recovery.js +10 -0
  14. package/dist/lib/import-jobs/source-field-recovery.js.map +1 -1
  15. package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts +1 -0
  16. package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
  17. package/dist/lib/import-jobs/spreadsheet-contract-facts.js +2 -2
  18. package/dist/lib/import-jobs/spreadsheet-contract-facts.js.map +1 -1
  19. package/dist/lib/invoice-formatting.d.ts.map +1 -1
  20. package/dist/lib/invoice-formatting.js +3 -0
  21. package/dist/lib/invoice-formatting.js.map +1 -1
  22. package/dist/lib/packing/packing-commercial-rows.d.ts +33 -0
  23. package/dist/lib/packing/packing-commercial-rows.d.ts.map +1 -0
  24. package/dist/lib/packing/packing-commercial-rows.js +93 -0
  25. package/dist/lib/packing/packing-commercial-rows.js.map +1 -0
  26. package/dist/lib/packing/packing-layout.d.ts +2 -0
  27. package/dist/lib/packing/packing-layout.d.ts.map +1 -1
  28. package/dist/lib/packing/packing-layout.js +58 -4
  29. package/dist/lib/packing/packing-layout.js.map +1 -1
  30. package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
  31. package/dist/lib/remote-components/trade-compliance-workbench/app.js +4 -4
  32. package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +8 -0
  33. package/dist/lib/remote-components/trade-compliance-workbench/editor.js +1 -1
  34. package/dist/lib/remote-ui/bridge.d.ts.map +1 -1
  35. package/dist/lib/remote-ui/bridge.js +5 -2
  36. package/dist/lib/remote-ui/bridge.js.map +1 -1
  37. package/dist/lib/remote-ui/components/generation-progress.js +1 -1
  38. package/dist/lib/remote-ui/components/generation-progress.js.map +1 -1
  39. package/dist/lib/remote-ui/components/packing-generation-actions.d.ts +2 -1
  40. package/dist/lib/remote-ui/components/packing-generation-actions.d.ts.map +1 -1
  41. package/dist/lib/remote-ui/components/packing-generation-actions.js +2 -2
  42. package/dist/lib/remote-ui/components/packing-generation-actions.js.map +1 -1
  43. package/dist/lib/remote-ui/components/supplier-materials.css +3 -1
  44. package/dist/lib/remote-ui/components/supplier-materials.d.ts +13 -0
  45. package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -1
  46. package/dist/lib/remote-ui/components/supplier-materials.js +9 -3
  47. package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -1
  48. package/dist/lib/remote-ui/customer-contract-contracts.d.ts +5 -0
  49. package/dist/lib/remote-ui/customer-contract-contracts.d.ts.map +1 -1
  50. package/dist/lib/remote-ui/pages/analytics-dashboard.js +1 -1
  51. package/dist/lib/remote-ui/pages/analytics-dashboard.js.map +1 -1
  52. package/dist/lib/remote-ui/pages/contracts.d.ts.map +1 -1
  53. package/dist/lib/remote-ui/pages/contracts.js +3 -2
  54. package/dist/lib/remote-ui/pages/contracts.js.map +1 -1
  55. package/dist/lib/remote-ui/pages/files.js +1 -1
  56. package/dist/lib/remote-ui/pages/files.js.map +1 -1
  57. package/dist/lib/remote-ui/pages/procurement.d.ts.map +1 -1
  58. package/dist/lib/remote-ui/pages/procurement.js +5 -3
  59. package/dist/lib/remote-ui/pages/procurement.js.map +1 -1
  60. package/dist/lib/remote-ui/pages/sales.js +1 -1
  61. package/dist/lib/remote-ui/pages/sales.js.map +1 -1
  62. package/dist/lib/sales-file.service.d.ts +1 -1
  63. package/dist/lib/sales-file.service.d.ts.map +1 -1
  64. package/dist/lib/sales-file.service.js +162 -113
  65. package/dist/lib/sales-file.service.js.map +1 -1
  66. package/dist/lib/supplier-materials/customs-source-fields.d.ts +3 -0
  67. package/dist/lib/supplier-materials/customs-source-fields.d.ts.map +1 -0
  68. package/dist/lib/supplier-materials/customs-source-fields.js +67 -0
  69. package/dist/lib/supplier-materials/customs-source-fields.js.map +1 -0
  70. package/dist/lib/supplier-materials/generation-materials.d.ts +6 -0
  71. package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
  72. package/dist/lib/supplier-materials/generation-materials.js +6 -4
  73. package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
  74. package/dist/lib/supplier-materials/supplier-materials.d.ts +7 -0
  75. package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
  76. package/dist/lib/supplier-materials/supplier-materials.js +10 -0
  77. package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
  78. package/dist/lib/workbench.middleware.d.ts +39 -4
  79. package/dist/lib/workbench.middleware.d.ts.map +1 -1
  80. package/dist/lib/workbench.middleware.js +1 -1
  81. package/dist/lib/workbench.middleware.js.map +1 -1
  82. package/dist/lib/workbench.service.d.ts.map +1 -1
  83. package/dist/lib/workbench.service.js +8 -3
  84. package/dist/lib/workbench.service.js.map +1 -1
  85. package/package.json +1 -1
@@ -11,12 +11,12 @@ import ExcelJS from 'exceljs';
11
11
  import JSZip from 'jszip';
12
12
  import { aggregatePackingBatches } from './packing/packing-render.js';
13
13
  import { PACKING_IMPORT_ACTIVE_STATUSES } from './packing/packing-import-task.contract.js';
14
- import { applySharedPackageLayout, packingGoodsOrder } from './packing/shared-package-layout.js';
15
- import { packingSourceDisplay } from './packing/packing-source-display.js';
14
+ import { buildPackingCommercialRows, supplierCartonNo } from './packing/packing-commercial-rows.js';
15
+ import { packingRoleLabels } from './packing/packing-source-display.js';
16
16
  import { shipmentDerived, appendShipmentReview, markReview } from './packing/shipment-documents.js';
17
17
  import { formatInvoiceSheet } from './invoice-formatting.js';
18
18
  import { formatCustomsSheet } from './customs-formatting.js';
19
- import { stylePackingSheet } from './packing/packing-layout.js';
19
+ import { stylePackingSheet, appendPackingSpecifications } from './packing/packing-layout.js';
20
20
  import * as yauzl from 'yauzl';
21
21
  import { Decimal } from 'decimal.js';
22
22
  import { BankAccountSettings, CompanySettings, Customer, CustomerContract, CustomerContractClause, GeneratedSalesFile, MonthlySafeExchangeRate, ProfitRuleSettings, PurchaseOrder, PurchaseOrderLine, SupplierPacking, SupplierPackingLine } from './entities/index.js';
@@ -37,7 +37,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
37
37
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
38
38
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
39
39
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
40
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-10-22.2';
40
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-10-27.1';
41
41
  const COMPANY_LOGO_PLACEMENTS = {
42
42
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
43
43
  CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -106,7 +106,7 @@ let SalesFileService = class SalesFileService {
106
106
  generationWarnings.push(...materialData.warnings);
107
107
  const materialsFingerprint = createHash('sha256').update(JSON.stringify(materialDocuments)).digest('hex');
108
108
  await hooks?.progress('TRANSLATING', 0);
109
- const translated = await this.translateDynamicFields(scope, customer, materialData.englishLines, clauses, generationWarnings, input.fileType, packing);
109
+ 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)));
110
110
  const packingTranslated = translated;
111
111
  if (packing)
112
112
  generationWarnings.push(...this.packingWarningsForPl(derived, packing));
@@ -145,13 +145,13 @@ let SalesFileService = class SalesFileService {
145
145
  return fileType === 'PL';
146
146
  if (field.startsWith('packing.'))
147
147
  return fileType === 'PL';
148
- if (fileType === 'PL' && (field.startsWith('clause.') || /^line\..+\.(description|unit)$/.test(field)))
148
+ if (fileType === 'PL' && (field.startsWith('clause.') || /^line\..+\.unit$/.test(field)))
149
149
  return false;
150
150
  return true;
151
151
  });
152
152
  if (fileType === 'CUSTOMS_DECLARATION')
153
153
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述仅使用已知信息,申报要素、法定计量单位等请人工补全;本文件尚未提交海关。' });
154
- 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 };
154
+ 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: 'v11' } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
155
155
  const snapshot = { customsCoverage: materialData.customsCoverage, 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 } };
156
156
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
157
157
  const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, customsCoverage: materialData.customsCoverage, generationWarnings: fileWarnings }, logo);
@@ -457,7 +457,7 @@ let SalesFileService = class SalesFileService {
457
457
  const timer = setTimeout(() => { void this.fileStorage.remove(scope, storageFileId).catch(() => undefined); }, OLD_SALES_FILE_CLEANUP_DELAY_MS);
458
458
  timer.unref?.();
459
459
  }
460
- async translateDynamicFields(scope, customer, lines, clauses, warnings, fileType = 'PI', packing = null) {
460
+ async translateDynamicFields(scope, customer, lines, clauses, warnings, fileType = 'PI', packing = null, reviewedDescriptionIds = new Set()) {
461
461
  const options = { organizationId: scope.organizationId };
462
462
  const customsOnly = fileType === 'CUSTOMS_DECLARATION';
463
463
  const packingOnly = fileType === 'PL';
@@ -485,7 +485,7 @@ let SalesFileService = class SalesFileService {
485
485
  return result.trim();
486
486
  }
487
487
  }
488
- if (field.startsWith('clause.') || field.endsWith('.unit')) {
488
+ if (field.endsWith('.unit')) {
489
489
  warnings.push({ code: 'SOURCE_FIELD_REVIEW', field, sourceValue: value, message: `字段 ${field} 保留原文“${value}”,英文待确认` });
490
490
  return value;
491
491
  }
@@ -500,7 +500,7 @@ let SalesFileService = class SalesFileService {
500
500
  ...(!packingOnly ? [['clause.PAYMENT_TERMS', clauseText(clauses, 'PAYMENT_TERMS')], ['clause.TRANSPORT', deliveryClauseText(clauses)]] : []),
501
501
  ...lines.flatMap(line => [
502
502
  [`line.${line.id}.productName`, line.englishName || [line.productName, line.modelSpecification].filter(Boolean).join(' ')],
503
- ...(!packingOnly ? [[`line.${line.id}.description`, line.productDescription], [`line.${line.id}.unit`, line.unit]] : [])
503
+ ...(!reviewedDescriptionIds.has(line.id) || /\p{Script=Han}/u.test(line.productDescription ?? '') ? [[`line.${line.id}.description`, line.productDescription]] : []), ...(!packingOnly ? [[`line.${line.id}.unit`, line.unit]] : [])
504
504
  ]),
505
505
  ...(['PL', 'PI_CI_PL', 'ALL'].includes(fileType) ? (packing?.sourceLines ?? []).flatMap(line => [[`packing.${line.id}.description`, line.description], [`packing.${line.id}.battery`, line.battery === '无' ? '' : line.battery]]) : [])
506
506
  ];
@@ -519,7 +519,7 @@ let SalesFileService = class SalesFileService {
519
519
  deliveryTerms: packingOnly || customsOnly ? '' : await translate('clause.TRANSPORT', deliveryClauseText(clauses)),
520
520
  lines: await Promise.all(lines.map(async (line) => {
521
521
  return { productName: customsOnly ? '' : line.englishName && !/\p{Script=Han}/u.test(line.englishName) ? line.englishName : await translate(`line.${line.id}.productName`, line.englishName || [line.productName, line.modelSpecification].filter(Boolean).join(' ')),
522
- description: packingOnly ? '' : await translate(`line.${line.id}.description`, line.productDescription),
522
+ description: reviewedDescriptionIds.has(line.id) && !/\p{Script=Han}/u.test(line.productDescription ?? '') ? line.productDescription ?? '' : await translate(`line.${line.id}.description`, line.productDescription),
523
523
  model: line.modelSpecification ?? '', unit: packingOnly ? '' : await translate(`line.${line.id}.unit`, line.unit) };
524
524
  }))
525
525
  };
@@ -722,7 +722,7 @@ function generationRequestMatches(item, expected) {
722
722
  bankType === expected.bankType &&
723
723
  lineOrderMatches && (request.shipmentDocumentsVersion !== 'v2' || request.orderDataFingerprint === expected.orderDataFingerprint) &&
724
724
  !item.generationWarnings?.some(warning => warning.code === DomainErrorCodes.TRANSLATION_FAILED || warning.code === 'TRANSLATION_NOT_CONFIGURED' || warning.code === 'TRANSLATION_SERVICE_UNAVAILABLE') &&
725
- (item.fileType === 'PI' || request.shipmentDocumentsVersion === 'v2') && (item.fileType !== 'PL' || request.packingLayoutVersion === 'v10') &&
725
+ (item.fileType === 'PI' || request.shipmentDocumentsVersion === 'v2') && (item.fileType !== 'PL' || request.packingLayoutVersion === 'v11') &&
726
726
  packingMatches &&
727
727
  ordersKeyMatches);
728
728
  }
@@ -776,9 +776,7 @@ function fillInvoiceSheet(sheet, type, data) {
776
776
  for (let index = 0; index < derived.lines.length; index += 1) {
777
777
  const row = 12 + index;
778
778
  const englishProduct = translated.lines[index]?.productName ?? '';
779
- const englishModel = translated.lines[index]?.model ?? '';
780
- const fromQuotation = data.snapshot?.materials?.some((source) => source.documentType === 'ENGLISH_QUOTATION' && source.purchaseOrderLineId === derived.lines[index].purchaseOrderLineId && (source.fields.includes('productName') || source.fields.includes('model')));
781
- const productLabel = fromQuotation && englishModel && !englishProduct.toLocaleUpperCase().includes(englishModel.toLocaleUpperCase()) ? `${englishProduct}\n${englishModel}` : englishProduct;
779
+ const productLabel = englishProduct;
782
780
  [index + 1, productLabel, translated.lines[index]?.description ?? '', derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity), Number(pricing.lines[index].unitPrice), translated.lines[index]?.unit ?? '', Number(pricing.lines[index].usdToCnyRate ?? 1), derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount), derived.lines[index].hsCode ?? ''].forEach((value, offset) => sheet.getCell(row, offset < 7 ? offset + 1 : offset + 2).value = value);
783
781
  safeMerge(sheet, `G${row}:H${row}`);
784
782
  sheet.getCell(`E${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
@@ -809,11 +807,6 @@ function fillInvoiceSheet(sheet, type, data) {
809
807
  }
810
808
  export async function renderSalesWorkbook(type, data, logo) {
811
809
  data = { ...data, derived: shipmentDerived(data.derived, data.packing, type) };
812
- if (type === 'PL') {
813
- const order = packingGoodsOrder(data.packing?.sourceLines ?? [], data.derived.lines.map((line) => line.purchaseOrderLineId));
814
- if (order.some((index, position) => index !== position))
815
- data = { ...data, derived: { ...data.derived, lines: order.map(index => data.derived.lines[index]) }, translated: { ...data.translated, lines: order.map(index => data.translated.lines[index]) }, purchaseLines: order.map(index => data.purchaseLines[index]) };
816
- }
817
810
  const workbook = new ExcelJS.Workbook();
818
811
  await workbook.xlsx.load(await templateBuffer(type));
819
812
  const sheet = workbook.getWorksheet(sheetName(type));
@@ -839,6 +832,7 @@ export async function renderSalesWorkbook(type, data, logo) {
839
832
  set(detail, 'A3', 'PACKAGING DETAILS');
840
833
  }
841
834
  fillPackingSheet(sheet, data);
835
+ appendPackingSpecifications(workbook, sheet);
842
836
  }
843
837
  else
844
838
  fillCustomsSheet(sheet, data);
@@ -864,24 +858,36 @@ export async function renderSalesWorkbook(type, data, logo) {
864
858
  }
865
859
  if (type === 'PL') {
866
860
  Object.assign(fieldLocations, { 'customer.address': { location: 'PL!B5' }, 'customer.contactName': { location: 'PL!B7' }, 'customer.country': { location: 'PL!B6' } });
867
- data.purchaseLines.forEach((line, index) => { fieldLocations[`line.${line.id}.productName`] = { location: `PL!A${12 + index}`, productName: line.productName }; });
861
+ const plRows = buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []);
862
+ data.purchaseLines.forEach((line, orderIndex) => {
863
+ const index = plRows.findIndex(row => row.orderIndex === orderIndex);
864
+ if (index >= 0)
865
+ for (const [field, column] of Object.entries({ productName: 'A', description: 'B' }))
866
+ fieldLocations[`line.${line.id}.${field}`] = { location: `PL!${column}${12 + index}`, productName: line.productName };
867
+ });
868
868
  (data.packing?.sourceLines ?? []).forEach((line, index) => {
869
869
  for (const field of ['description', 'battery'])
870
- fieldLocations[`packing.${line.id}.${field}`] = { location: `Packaging Details!A${12 + index}` };
870
+ fieldLocations[`packing.${line.id}.${field}`] = { location: `Packaging Details!B${12 + index}` };
871
871
  });
872
872
  }
873
873
  for (const line of data.derived.lines) {
874
874
  const index = data.derived.lines.indexOf(line);
875
- if ((type !== 'PI' && line.quantityReview) || line.quantityPending)
875
+ if (type !== 'PL' && ((type !== 'PI' && line.quantityReview) || line.quantityPending))
876
876
  markReview(sheet.getCell(type === 'CUSTOMS_DECLARATION' ? 14 + index * 2 : 12 + index, 4));
877
877
  if (line.amountPending && (type === 'PI' || type === 'CI'))
878
878
  markReview(sheet.getCell(12 + index, 9));
879
879
  }
880
- if (type === 'CUSTOMS_DECLARATION')
881
- for (let index = 0; index < data.derived.lines.length; index++)
882
- markReview(sheet.getCell(15 + index * 2, 3));
880
+ const plWarningRows = type === 'PL' ? buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []) : [];
883
881
  for (const warning of data.generationWarnings ?? []) {
884
- const target = fieldLocations[String(warning.field ?? '')];
882
+ const field = String(warning.field ?? '');
883
+ const commercialField = type === 'PL' ? /^line\.(.+)\.(productName|description)$/.exec(field) : null;
884
+ if (commercialField) {
885
+ const orderIndex = data.purchaseLines.findIndex((line) => line.id === commercialField[1]);
886
+ const column = commercialField[2] === 'description' ? 2 : 1;
887
+ plWarningRows.forEach((row, index) => { if (row.orderIndex === orderIndex)
888
+ markReview(sheet.getCell(index + 12, column)); });
889
+ }
890
+ const target = fieldLocations[field];
885
891
  if (target) {
886
892
  const [name, address] = target.location.split('!');
887
893
  const targetSheet = workbook.getWorksheet(name);
@@ -989,27 +995,82 @@ function imageDimensions(buffer) {
989
995
  }
990
996
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '公司 Logo 图片尺寸无法识别');
991
997
  }
992
- function fillPackingSheet(sheet, data) {
993
- const { customer, purchaseOrder, company, packing } = data;
994
- const sourceGroups = new Set();
995
- const sourceLines = data.packagingDetails && packing?.sourceLines?.length ? packing.sourceLines : null;
996
- const sourceDisplay = sourceLines?.map((line) => {
997
- const english = data.translated.packingLines?.find((item) => item.id === line.id);
998
- const description = english?.description ?? (line.description && !/\p{Script=Han}/u.test(line.description) ? line.description : '');
999
- const battery = english?.battery ?? (line.battery && !/\p{Script=Han}/u.test(line.battery) ? line.battery : '');
1000
- const display = packingSourceDisplay({ ...line, description, battery }, sourceGroups);
1001
- const index = data.derived.lines.findIndex((item) => line.allocations?.some(a => a.purchaseOrderLineId === item.purchaseOrderLineId));
1002
- return { ...display, productName: display.productName || data.translated.lines[index]?.productName || '', model: display.model || data.translated.lines[index]?.model || '' };
998
+ const packingPhysicalColumns = [5, 6, 7, 8, 9, 12];
999
+ const packingPhysicalFields = ['dimensionCm', 'grossWeightPerCtnKg', 'cartons', 'boxVolumeCbm', 'totalVolumeCbm', 'totalGrossWeightKg'];
1000
+ const packingPhysicalKey = (row) => JSON.stringify([row.packingId, row.packageGroup ?? row.id]);
1001
+ function packingSheetRows(data) {
1002
+ const source = data.packing?.sourceLines ?? [];
1003
+ if (data.packagingDetails)
1004
+ return source.map(line => {
1005
+ const english = data.translated.packingLines?.find((item) => item.id === line.id);
1006
+ const description = english?.description ?? (line.description && !/\p{Script=Han}/u.test(line.description) ? line.description : '');
1007
+ const battery = english?.battery ?? (line.battery && !/\p{Script=Han}/u.test(line.battery) ? line.battery : '');
1008
+ return {
1009
+ productName: line.model ?? '', description: [description, line.role && line.role !== 'PART' ? packingRoleLabels[line.role] ?? line.role : '', battery && battery !== '无' ? `Battery: ${battery}` : ''].filter(Boolean).join('\n'),
1010
+ quantity: line.qty == null ? null : Number(line.qty), cartonNo: supplierCartonNo(line), sourceLineId: line.id, packageKey: packingPhysicalKey(line), metrics: line,
1011
+ pending: (!line.allocations?.length && line.role !== 'CONFIG') || line.role === 'SLAVE' && Boolean(line.allocations?.some(a => !a.quantityBasisConfirmed)) || Boolean(/\p{Script=Han}/u.test(line.description ?? '') && !english?.description)
1012
+ };
1013
+ });
1014
+ return buildPackingCommercialRows(data.derived.lines, source).map(row => {
1015
+ const aggregate = !source.length ? data.packing?.byPurchaseLine?.[row.purchaseOrderLineId] : null;
1016
+ const legacyMetrics = aggregate && aggregate.statisticsComplete !== false ? {
1017
+ dimensionCm: aggregate.dimensions?.join(' / '), grossWeightPerCtnKg: aggregate.weightsPerCtn?.length > 1 ? aggregate.weightsPerCtn.join(' / ') : aggregate.weightPerCtn == null ? null : String(aggregate.weightPerCtn),
1018
+ cartons: String(aggregate.cartons), boxVolumeCbm: aggregate.boxVolumesCbm?.length > 1 ? aggregate.boxVolumesCbm.join(' / ') : aggregate.boxVolumeCbm == null ? null : String(aggregate.boxVolumeCbm), totalVolumeCbm: String(aggregate.totalVolumeCbm), totalGrossWeightKg: String(aggregate.grossKg)
1019
+ } : undefined;
1020
+ return { ...row, metrics: row.metrics ?? legacyMetrics, productName: data.translated.lines[row.orderIndex]?.productName ?? '', description: data.translated.lines[row.orderIndex]?.description ?? '', quantity: data.derived.lines[row.orderIndex].quantityPending ? null : Number(row.quantity) };
1003
1021
  });
1004
- const indices = data.derived.lines.map((_, i) => i);
1005
- const derived = { ...data.derived, lines: sourceDisplay ?? indices.map((i) => data.derived.lines[i]) };
1006
- const translated = { ...data.translated, lines: sourceDisplay ?? indices.map((i) => data.translated.lines[i]) };
1007
- resizePackingLayout(sheet, derived.lines.length);
1022
+ }
1023
+ /** Resolve the supplier's physical group once, independently of commercial quantities. */
1024
+ function fillPackingPhysicalRows(sheet, rows, data) {
1025
+ const source = data.packing?.sourceLines ?? [];
1026
+ const selected = new Set(data.derived.lines.map((line) => line.purchaseOrderLineId));
1027
+ const seen = new Set();
1028
+ for (const [index, row] of rows.entries()) {
1029
+ const excelRow = index + 12;
1030
+ const members = row.packageKey ? source.filter(line => packingPhysicalKey(line) === row.packageKey) : [];
1031
+ const unresolvedSubset = data.packing?.warnings?.some((warning) => warning.code === 'PACKING_SHARED_UNALLOCATED' && (!warning.packingLineId || members.some(member => member.id === warning.packingLineId)));
1032
+ const completeScope = data.packagingDetails || !unresolvedSubset && members.every(member => member.allocations?.length && member.allocations.every(a => selected.has(a.purchaseOrderLineId) && (!a.countsAsGoods || rows.some(rendered => rendered.packageKey === row.packageKey && rendered.sourceLineId === member.id && rendered.purchaseOrderLineId === a.purchaseOrderLineId))));
1033
+ const facts = packingPhysicalFields.map(field => [...new Set(members.map(member => member[field]).filter(value => value != null && value !== '').map(value => field === 'dimensionCm' ? String(value) : Number(value)))]);
1034
+ const conflict = facts.some(values => values.length > 1);
1035
+ const repeated = row.packageKey ? seen.has(row.packageKey) : false;
1036
+ if (row.packageKey)
1037
+ seen.add(row.packageKey);
1038
+ packingPhysicalColumns.forEach((column, offset) => {
1039
+ const cell = sheet.getCell(excelRow, column);
1040
+ const field = packingPhysicalFields[offset];
1041
+ const raw = row.metrics?.[field];
1042
+ let value = raw == null || raw === '' ? null : offset === 0 || !Number.isFinite(Number(raw)) ? String(raw) : Number(raw);
1043
+ if (members.length)
1044
+ value = conflict ? data.packagingDetails ? value : null : completeScope && !repeated ? facts[offset][0] ?? null : null;
1045
+ cell.value = value;
1046
+ if (conflict || !completeScope || !repeated && (value == null || typeof value === 'number' && (!Number.isFinite(value) || value <= 0)))
1047
+ markReview(cell);
1048
+ });
1049
+ if (conflict || !completeScope) {
1050
+ markReview(sheet.getCell(excelRow, 3));
1051
+ sheet.getCell(excelRow, 3).note = 'Shared carton data conflict or incomplete commercial scope. Verify supplier package allocation.';
1052
+ }
1053
+ }
1054
+ for (let start = 0; start < rows.length;) {
1055
+ const first = rows[start];
1056
+ let end = start;
1057
+ while (first.packageKey && end + 1 < rows.length && rows[end + 1].packageKey === first.packageKey && rows[end + 1].cartonNo === first.cartonNo)
1058
+ end++;
1059
+ if (end > start && !sheet.getCell(start + 12, 3).note)
1060
+ for (const col of [3, ...packingPhysicalColumns]) {
1061
+ sheet.mergeCells(start + 12, col, end + 12, col);
1062
+ sheet.getCell(start + 12, col).alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
1063
+ }
1064
+ start = end + 1;
1065
+ }
1066
+ }
1067
+ function fillPackingSheet(sheet, data) {
1068
+ const { customer, purchaseOrder, company, packing, translated, derived } = data;
1069
+ const rows = packingSheetRows(data);
1070
+ resizePackingLayout(sheet, rows.length);
1008
1071
  set(sheet, 'B1', company?.addressEn, true);
1009
1072
  set(sheet, 'B2', company?.phone || company?.email ? `Tel:${company?.phone ?? ''} Email:${company?.email ?? ''}` : undefined, true);
1010
1073
  set(sheet, 'A3', data.snapshot?.request?.packingMode === 'DRAFT' ? 'PACKING LIST — DRAFT' : 'PACKING LIST');
1011
- // 收货信息(左)与卖家信息(右):标签为模板静态内容,值由生成数据填充
1012
- // 信息块缺失值显示 —,避免大片空白;日期写入后保持模板的 yyyy/m/d 格式
1013
1074
  set(sheet, 'B4', translated.customerName || '—');
1014
1075
  set(sheet, 'B5', translated.customerAddress || '—');
1015
1076
  set(sheet, 'B6', translated.customerCountry || '—');
@@ -1023,41 +1084,11 @@ function fillPackingSheet(sheet, data) {
1023
1084
  set(sheet, 'F6', translated.customerContact || '—');
1024
1085
  set(sheet, 'F7', company?.email || '—');
1025
1086
  set(sheet, 'F8', company?.phone || '—');
1026
- for (let index = 0; index < derived.lines.length; index += 1) {
1027
- const row = 12 + index;
1028
- const linePacking = packing?.byPurchaseLine?.[derived.lines[index].purchaseOrderLineId];
1029
- let packingValues = null;
1030
- if (sourceDisplay)
1031
- packingValues = sourceDisplay[index].metrics;
1032
- else if (linePacking && linePacking.statisticsComplete !== false) {
1033
- // 列序(E 起):尺寸(cm)/单箱毛重/箱数/单箱体积/总体积/单件净重(缺)/总净重(缺)/总毛重
1034
- const round6 = (value) => Math.round(value * 1_000_000) / 1_000_000;
1035
- packingValues = [
1036
- linePacking.dimensions.join(' / '),
1037
- linePacking.weightsPerCtn?.length > 1 ? linePacking.weightsPerCtn.join(' / ') : linePacking.weightPerCtn ?? '',
1038
- linePacking.cartons > 0 ? linePacking.cartons : '',
1039
- linePacking.boxVolumesCbm?.length > 1 ? linePacking.boxVolumesCbm.map(round6).join(' / ') : linePacking.boxVolumeCbm == null ? '' : round6(linePacking.boxVolumeCbm),
1040
- linePacking.totalVolumeCbm == null ? '' : round6(linePacking.totalVolumeCbm),
1041
- '',
1042
- '',
1043
- linePacking.grossKg ? Math.round(linePacking.grossKg * 100) / 100 : ''
1044
- ];
1045
- }
1046
- else if (packing) {
1047
- // 订单已有装箱数据但该行未匹配到:清空(该行已触发 PACKING_LINE_MISSING 告警)
1048
- packingValues = [null, null, null, null, null, null, null, null];
1049
- }
1050
- const values = [
1051
- translated.lines[index]?.productName ?? '',
1052
- translated.lines[index]?.model ?? '',
1053
- null,
1054
- sourceDisplay ? sourceDisplay[index].quantity : derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity),
1055
- ...(packingValues ?? [null, null, null, null, null, null, null, null])
1056
- ];
1057
- values.forEach((value, offset) => { sheet.getCell(row, offset + 1).value = value; });
1058
- }
1059
- // Show known physical data in drafts; incomplete totals must not masquerade as final totals.
1060
- const totalsRow = 12 + derived.lines.length;
1087
+ rows.forEach((line, index) => {
1088
+ const row = index + 12;
1089
+ [line.productName, line.description, line.cartonNo, line.quantity].forEach((value, offset) => { sheet.getCell(row, offset + 1).value = value; });
1090
+ });
1091
+ const totalsRow = 12 + rows.length;
1061
1092
  const incomplete = packing?.totalsComplete === false;
1062
1093
  const labels = ['Total Gross weight (KG)', 'Total Net weight (KG)', 'Volume (CBM)', 'Total Carton (CTN)'];
1063
1094
  const totals = [packing?.totals.grossKg, null, packing?.totals.volumeCbm, packing?.totals.cartons];
@@ -1068,42 +1099,29 @@ function fillPackingSheet(sheet, data) {
1068
1099
  if (incomplete && offset !== 1)
1069
1100
  sheet.getCell(totalsRow + offset, 6).note = 'Known packaging data only. Missing or unallocated packaging quantities are excluded; verify before use.';
1070
1101
  });
1071
- stylePackingSheet(sheet, derived.lines.length);
1072
- for (const address of ['B4', 'B5', 'B6', 'B7', 'B8', 'F4', 'F5', 'F6', 'F7', 'F8']) {
1102
+ stylePackingSheet(sheet, rows.length);
1103
+ fillPackingPhysicalRows(sheet, rows, data);
1104
+ for (const address of ['B4', 'B5', 'B6', 'B7', 'B8', 'F4', 'F5', 'F6', 'F7', 'F8'])
1073
1105
  if (sheet.getCell(address).value === '—')
1074
1106
  markReview(sheet.getCell(address));
1075
- }
1076
- for (let index = 0; index < derived.lines.length; index++) {
1107
+ rows.forEach((line, index) => {
1077
1108
  const row = index + 12;
1078
1109
  for (const column of [10, 11])
1079
1110
  markReview(sheet.getCell(row, column));
1080
- if (sourceDisplay) {
1081
- const line = sourceLines[index];
1082
- const translatedSource = data.translated.packingLines?.find((item) => item.id === line.id);
1083
- if ((!line.allocations?.length && line.role !== 'CONFIG') || line.role === 'SLAVE' && line.allocations?.some((a) => !a.quantityBasisConfirmed) || /\p{Script=Han}/u.test(line.description ?? '') && !translatedSource?.description)
1084
- markReview(sheet.getCell(row, 1));
1085
- if (line.qty == null && line.role !== 'CONFIG')
1086
- markReview(sheet.getCell(row, 4));
1087
- }
1088
- else if (packing) {
1089
- const metrics = packing.byPurchaseLine[derived.lines[index].purchaseOrderLineId];
1090
- if (!metrics || metrics.quantityNeedsReview || Math.abs(metrics.shippedQty - Number(derived.lines[index].quantity)) > .000001)
1091
- markReview(sheet.getCell(row, 4));
1092
- if (!metrics || metrics.statisticsComplete === false)
1093
- for (const col of [5, 6, 7, 8, 9, 12])
1094
- markReview(sheet.getCell(row, col));
1111
+ if (!line.cartonNo)
1112
+ markReview(sheet.getCell(row, 3));
1113
+ if (line.pending && (packing || data.packagingDetails)) {
1114
+ markReview(sheet.getCell(row, 4));
1115
+ if (data.packagingDetails)
1116
+ markReview(sheet.getCell(row, 2));
1095
1117
  }
1096
- else {
1097
- // Order quantities are known; without a supplier batch the physical metrics are not.
1098
- for (const col of [5, 6, 7, 8, 9, 12])
1099
- markReview(sheet.getCell(row, col));
1100
- }
1101
- }
1118
+ if (line.quantity == null)
1119
+ markReview(sheet.getCell(row, 4));
1120
+ });
1102
1121
  if (incomplete || packing?.warnings?.some((warning) => warning.code === 'PACKING_SOURCE_TOTAL_DIFF'))
1103
1122
  for (const offset of [0, 2, 3])
1104
1123
  markReview(sheet.getCell(totalsRow + offset, 6));
1105
1124
  markReview(sheet.getCell(totalsRow + 1, 6));
1106
- applySharedPackageLayout(sheet, packing?.sourceLines ?? [], sourceDisplay ? undefined : derived.lines.map((line) => line.purchaseOrderLineId));
1107
1125
  }
1108
1126
  /**
1109
1127
  * 银行信息区块按通道分两种布局:
@@ -1249,22 +1267,28 @@ function fillCustomsSheet(sheet, data) {
1249
1267
  const row = 14 + index * 2;
1250
1268
  for (let col = 2; col <= 10; col++)
1251
1269
  sheet.getCell(row + 1, col).value = null;
1252
- set(sheet, `C${row + 1}`, [purchaseLines[index].productDescription, purchaseLines[index].brand ? `品牌:${purchaseLines[index].brand}` : '', purchaseLines[index].material ? `材质:${purchaseLines[index].material}` : '', purchaseLines[index].usage ? `用途:${purchaseLines[index].usage}` : '', purchaseLines[index].declarationElements].filter(Boolean).join(';'));
1270
+ const product = purchaseLines[index];
1271
+ set(sheet, `C${row + 1}`, product.declarationElements || product.productDescription || '');
1253
1272
  safeMerge(sheet, `A${row}:A${row + 1}`);
1254
1273
  safeMerge(sheet, `K${row}:K${row + 1}`);
1255
1274
  safeMerge(sheet, `L${row}:L${row + 1}`);
1256
1275
  set(sheet, `A${row}`, index + 1);
1257
1276
  set(sheet, `B${row}`, derived.lines[index].hsCode ?? '');
1258
- set(sheet, `C${row}`, [purchaseLines[index].productName, purchaseLines[index].modelSpecification].filter(Boolean).join(' '));
1259
- set(sheet, `D${row}`, derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity));
1260
- set(sheet, `E${row}`, purchaseLines[index].unit ?? '');
1277
+ set(sheet, `C${row}`, product.productName || '');
1261
1278
  set(sheet, `F${row}`, Number(pricing.lines[index].unitPrice));
1262
1279
  set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount));
1263
1280
  set(sheet, `H${row}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
1264
1281
  set(sheet, `I${row}`, purchaseLines[index].originCountry || '待确认');
1265
1282
  set(sheet, `J${row}`, customer.country || '待确认');
1266
1283
  set(sheet, `K${row}`, purchaseLines[index].domesticSourceLocation || '待确认');
1267
- set(sheet, `L${row}`, '待确认');
1284
+ set(sheet, `L${row}`, product.taxMode || '待确认');
1285
+ const quantities = customsQuantityRows(product, derived.lines[index]);
1286
+ for (const [offset, entry] of quantities.entries()) {
1287
+ set(sheet, `D${row + offset}`, entry.quantity);
1288
+ set(sheet, `E${row + offset}`, entry.unit);
1289
+ if (entry.review)
1290
+ markReview(sheet.getCell(`D${row + offset}`));
1291
+ }
1268
1292
  for (const warning of data.generationWarnings ?? [])
1269
1293
  if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
1270
1294
  markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
@@ -1275,6 +1299,30 @@ function fillCustomsSheet(sheet, data) {
1275
1299
  normalizeCustomsConfirmationRow(sheet, tail);
1276
1300
  set(sheet, `B${tail + 3}`, companyText);
1277
1301
  }
1302
+ /** Quantity order follows explicit statutory units; trade quantity and sale pricing remain independent. */
1303
+ function customsQuantityRows(product, commercial) {
1304
+ const primary = String(product.statutoryUnitPrimary || product.unit || '').trim();
1305
+ const isKg = (unit) => /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(unit);
1306
+ // A kg-first declaration still needs the independently recorded commercial quantity.
1307
+ const secondary = String(product.statutoryUnitSecondary || (isKg(primary) && product.unit && !isKg(product.unit) ? product.unit : '')).trim();
1308
+ return [primary, secondary].map(unit => {
1309
+ if (!unit)
1310
+ return { unit, quantity: null, review: false };
1311
+ if (isKg(unit)) {
1312
+ const weight = product.netWeightKg;
1313
+ const valid = typeof weight === 'number' && Number.isFinite(weight) && weight >= 0;
1314
+ return { unit, quantity: valid ? weight : null, review: !valid || weight === 0 };
1315
+ }
1316
+ const normalizedUnit = (value) => String(value ?? '').normalize('NFKC').trim().toLowerCase().replace(/\.$/, '');
1317
+ const countUnit = (value) => /^(?:pcs?|pieces?|个|件|台)$/.test(value);
1318
+ const setUnit = (value) => /^(?:sets?|套)$/.test(value);
1319
+ const sourceUnit = normalizedUnit(product.unit);
1320
+ const targetUnit = normalizedUnit(unit);
1321
+ const compatible = Boolean(sourceUnit) && (sourceUnit === targetUnit || (countUnit(sourceUnit) && countUnit(targetUnit)) || (setUnit(sourceUnit) && setUnit(targetUnit)));
1322
+ const valid = compatible && !commercial.quantityPending && commercial.quantity != null && Number.isFinite(Number(commercial.quantity));
1323
+ return { unit, quantity: valid ? Number(commercial.quantity) : null, review: !valid };
1324
+ });
1325
+ }
1278
1326
  function normalizeCustomsConfirmationRow(sheet, row) {
1279
1327
  safeMerge(sheet, `A${row}:L${row}`);
1280
1328
  const cell = sheet.getCell(row, 1);
@@ -1453,16 +1501,17 @@ const salesFileNameTypeLabels = { PI: 'PI', CI: 'CI', PL: 'PL', CUSTOMS_DECLARAT
1453
1501
  function isTranslationFailure(value) { return value.code === DomainErrorCodes.TRANSLATION_FAILED && typeof value.field === 'string' && typeof value.sourceValue === 'string' && typeof value.message === 'string'; }
1454
1502
  function scoped(scope) { return { tenantId: scope.tenantId, organizationId: scope.organizationId }; }
1455
1503
  function deterministicEnglish(value, field) {
1456
- const text = value.trim().replace(/\s+/g, ' ');
1504
+ const text = value.trim();
1457
1505
  if (!text)
1458
1506
  return '';
1459
1507
  if (field.endsWith('.unit') && unitFallback(text) != null)
1460
1508
  return unitFallback(text);
1509
+ // Reviewed English specifications retain supplier line breaks and spacing.
1510
+ if (/^[\p{Script=Latin}\p{N}\p{P}\p{S}\p{Z}\s]+$/u.test(text) && /[A-Za-z0-9]/.test(text))
1511
+ return text;
1461
1512
  const normalized = normalizeKnownBusinessTerms(text);
1462
1513
  if (normalized !== text && !/\p{Script=Han}/u.test(normalized))
1463
1514
  return normalized;
1464
- if (/^[\p{Script=Latin}\p{N}\p{P}\p{S}\p{Z}\s]+$/u.test(text) && /[A-Za-z0-9]/.test(text))
1465
- return text;
1466
1515
  return null;
1467
1516
  }
1468
1517
  function normalizeKnownBusinessTerms(value) {