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

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 (45) hide show
  1. package/dist/lib/customs-formatting.d.ts.map +1 -1
  2. package/dist/lib/customs-formatting.js +3 -0
  3. package/dist/lib/customs-formatting.js.map +1 -1
  4. package/dist/lib/import-jobs/import-command.builder.js +1 -1
  5. package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
  6. package/dist/lib/invoice-formatting.d.ts.map +1 -1
  7. package/dist/lib/invoice-formatting.js +3 -0
  8. package/dist/lib/invoice-formatting.js.map +1 -1
  9. package/dist/lib/packing/packing-commercial-rows.d.ts +33 -0
  10. package/dist/lib/packing/packing-commercial-rows.d.ts.map +1 -0
  11. package/dist/lib/packing/packing-commercial-rows.js +93 -0
  12. package/dist/lib/packing/packing-commercial-rows.js.map +1 -0
  13. package/dist/lib/packing/packing-layout.js +3 -3
  14. package/dist/lib/packing/packing-layout.js.map +1 -1
  15. package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
  16. package/dist/lib/remote-components/trade-compliance-workbench/app.js +2 -2
  17. package/dist/lib/remote-ui/components/supplier-materials.css +3 -1
  18. package/dist/lib/remote-ui/components/supplier-materials.d.ts +13 -0
  19. package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -1
  20. package/dist/lib/remote-ui/components/supplier-materials.js +9 -3
  21. package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -1
  22. package/dist/lib/sales-file.service.d.ts +1 -1
  23. package/dist/lib/sales-file.service.d.ts.map +1 -1
  24. package/dist/lib/sales-file.service.js +159 -111
  25. package/dist/lib/sales-file.service.js.map +1 -1
  26. package/dist/lib/supplier-materials/customs-source-fields.d.ts +3 -0
  27. package/dist/lib/supplier-materials/customs-source-fields.d.ts.map +1 -0
  28. package/dist/lib/supplier-materials/customs-source-fields.js +67 -0
  29. package/dist/lib/supplier-materials/customs-source-fields.js.map +1 -0
  30. package/dist/lib/supplier-materials/generation-materials.d.ts +6 -0
  31. package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
  32. package/dist/lib/supplier-materials/generation-materials.js +6 -4
  33. package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
  34. package/dist/lib/supplier-materials/supplier-materials.d.ts +7 -0
  35. package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
  36. package/dist/lib/supplier-materials/supplier-materials.js +10 -0
  37. package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
  38. package/dist/lib/workbench.middleware.d.ts +35 -0
  39. package/dist/lib/workbench.middleware.d.ts.map +1 -1
  40. package/dist/lib/workbench.middleware.js +1 -1
  41. package/dist/lib/workbench.middleware.js.map +1 -1
  42. package/dist/lib/workbench.service.d.ts.map +1 -1
  43. package/dist/lib/workbench.service.js +3 -2
  44. package/dist/lib/workbench.service.js.map +1 -1
  45. package/package.json +1 -1
@@ -11,8 +11,8 @@ 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';
@@ -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-26.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';
@@ -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));
@@ -864,24 +857,36 @@ export async function renderSalesWorkbook(type, data, logo) {
864
857
  }
865
858
  if (type === 'PL') {
866
859
  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 }; });
860
+ const plRows = buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []);
861
+ data.purchaseLines.forEach((line, orderIndex) => {
862
+ const index = plRows.findIndex(row => row.orderIndex === orderIndex);
863
+ if (index >= 0)
864
+ for (const [field, column] of Object.entries({ productName: 'A', description: 'B' }))
865
+ fieldLocations[`line.${line.id}.${field}`] = { location: `PL!${column}${12 + index}`, productName: line.productName };
866
+ });
868
867
  (data.packing?.sourceLines ?? []).forEach((line, index) => {
869
868
  for (const field of ['description', 'battery'])
870
- fieldLocations[`packing.${line.id}.${field}`] = { location: `Packaging Details!A${12 + index}` };
869
+ fieldLocations[`packing.${line.id}.${field}`] = { location: `Packaging Details!B${12 + index}` };
871
870
  });
872
871
  }
873
872
  for (const line of data.derived.lines) {
874
873
  const index = data.derived.lines.indexOf(line);
875
- if ((type !== 'PI' && line.quantityReview) || line.quantityPending)
874
+ if (type !== 'PL' && ((type !== 'PI' && line.quantityReview) || line.quantityPending))
876
875
  markReview(sheet.getCell(type === 'CUSTOMS_DECLARATION' ? 14 + index * 2 : 12 + index, 4));
877
876
  if (line.amountPending && (type === 'PI' || type === 'CI'))
878
877
  markReview(sheet.getCell(12 + index, 9));
879
878
  }
880
- if (type === 'CUSTOMS_DECLARATION')
881
- for (let index = 0; index < data.derived.lines.length; index++)
882
- markReview(sheet.getCell(15 + index * 2, 3));
879
+ const plWarningRows = type === 'PL' ? buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []) : [];
883
880
  for (const warning of data.generationWarnings ?? []) {
884
- const target = fieldLocations[String(warning.field ?? '')];
881
+ const field = String(warning.field ?? '');
882
+ const commercialField = type === 'PL' ? /^line\.(.+)\.(productName|description)$/.exec(field) : null;
883
+ if (commercialField) {
884
+ const orderIndex = data.purchaseLines.findIndex((line) => line.id === commercialField[1]);
885
+ const column = commercialField[2] === 'description' ? 2 : 1;
886
+ plWarningRows.forEach((row, index) => { if (row.orderIndex === orderIndex)
887
+ markReview(sheet.getCell(index + 12, column)); });
888
+ }
889
+ const target = fieldLocations[field];
885
890
  if (target) {
886
891
  const [name, address] = target.location.split('!');
887
892
  const targetSheet = workbook.getWorksheet(name);
@@ -989,27 +994,82 @@ function imageDimensions(buffer) {
989
994
  }
990
995
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '公司 Logo 图片尺寸无法识别');
991
996
  }
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 || '' };
997
+ const packingPhysicalColumns = [5, 6, 7, 8, 9, 12];
998
+ const packingPhysicalFields = ['dimensionCm', 'grossWeightPerCtnKg', 'cartons', 'boxVolumeCbm', 'totalVolumeCbm', 'totalGrossWeightKg'];
999
+ const packingPhysicalKey = (row) => JSON.stringify([row.packingId, row.packageGroup ?? row.id]);
1000
+ function packingSheetRows(data) {
1001
+ const source = data.packing?.sourceLines ?? [];
1002
+ if (data.packagingDetails)
1003
+ return source.map(line => {
1004
+ const english = data.translated.packingLines?.find((item) => item.id === line.id);
1005
+ const description = english?.description ?? (line.description && !/\p{Script=Han}/u.test(line.description) ? line.description : '');
1006
+ const battery = english?.battery ?? (line.battery && !/\p{Script=Han}/u.test(line.battery) ? line.battery : '');
1007
+ return {
1008
+ productName: line.model ?? '', description: [description, line.role && line.role !== 'PART' ? packingRoleLabels[line.role] ?? line.role : '', battery && battery !== '无' ? `Battery: ${battery}` : ''].filter(Boolean).join('\n'),
1009
+ quantity: line.qty == null ? null : Number(line.qty), cartonNo: supplierCartonNo(line), sourceLineId: line.id, packageKey: packingPhysicalKey(line), metrics: line,
1010
+ 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)
1011
+ };
1012
+ });
1013
+ return buildPackingCommercialRows(data.derived.lines, source).map(row => {
1014
+ const aggregate = !source.length ? data.packing?.byPurchaseLine?.[row.purchaseOrderLineId] : null;
1015
+ const legacyMetrics = aggregate && aggregate.statisticsComplete !== false ? {
1016
+ dimensionCm: aggregate.dimensions?.join(' / '), grossWeightPerCtnKg: aggregate.weightsPerCtn?.length > 1 ? aggregate.weightsPerCtn.join(' / ') : aggregate.weightPerCtn == null ? null : String(aggregate.weightPerCtn),
1017
+ 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)
1018
+ } : undefined;
1019
+ 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
1020
  });
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);
1021
+ }
1022
+ /** Resolve the supplier's physical group once, independently of commercial quantities. */
1023
+ function fillPackingPhysicalRows(sheet, rows, data) {
1024
+ const source = data.packing?.sourceLines ?? [];
1025
+ const selected = new Set(data.derived.lines.map((line) => line.purchaseOrderLineId));
1026
+ const seen = new Set();
1027
+ for (const [index, row] of rows.entries()) {
1028
+ const excelRow = index + 12;
1029
+ const members = row.packageKey ? source.filter(line => packingPhysicalKey(line) === row.packageKey) : [];
1030
+ const unresolvedSubset = data.packing?.warnings?.some((warning) => warning.code === 'PACKING_SHARED_UNALLOCATED' && (!warning.packingLineId || members.some(member => member.id === warning.packingLineId)));
1031
+ 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))));
1032
+ 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)))]);
1033
+ const conflict = facts.some(values => values.length > 1);
1034
+ const repeated = row.packageKey ? seen.has(row.packageKey) : false;
1035
+ if (row.packageKey)
1036
+ seen.add(row.packageKey);
1037
+ packingPhysicalColumns.forEach((column, offset) => {
1038
+ const cell = sheet.getCell(excelRow, column);
1039
+ const field = packingPhysicalFields[offset];
1040
+ const raw = row.metrics?.[field];
1041
+ let value = raw == null || raw === '' ? null : offset === 0 || !Number.isFinite(Number(raw)) ? String(raw) : Number(raw);
1042
+ if (members.length)
1043
+ value = conflict ? data.packagingDetails ? value : null : completeScope && !repeated ? facts[offset][0] ?? null : null;
1044
+ cell.value = value;
1045
+ if (conflict || !completeScope || !repeated && (value == null || typeof value === 'number' && (!Number.isFinite(value) || value <= 0)))
1046
+ markReview(cell);
1047
+ });
1048
+ if (conflict || !completeScope) {
1049
+ markReview(sheet.getCell(excelRow, 3));
1050
+ sheet.getCell(excelRow, 3).note = 'Shared carton data conflict or incomplete commercial scope. Verify supplier package allocation.';
1051
+ }
1052
+ }
1053
+ for (let start = 0; start < rows.length;) {
1054
+ const first = rows[start];
1055
+ let end = start;
1056
+ while (first.packageKey && end + 1 < rows.length && rows[end + 1].packageKey === first.packageKey && rows[end + 1].cartonNo === first.cartonNo)
1057
+ end++;
1058
+ if (end > start && !sheet.getCell(start + 12, 3).note)
1059
+ for (const col of [3, ...packingPhysicalColumns]) {
1060
+ sheet.mergeCells(start + 12, col, end + 12, col);
1061
+ sheet.getCell(start + 12, col).alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
1062
+ }
1063
+ start = end + 1;
1064
+ }
1065
+ }
1066
+ function fillPackingSheet(sheet, data) {
1067
+ const { customer, purchaseOrder, company, packing, translated, derived } = data;
1068
+ const rows = packingSheetRows(data);
1069
+ resizePackingLayout(sheet, rows.length);
1008
1070
  set(sheet, 'B1', company?.addressEn, true);
1009
1071
  set(sheet, 'B2', company?.phone || company?.email ? `Tel:${company?.phone ?? ''} Email:${company?.email ?? ''}` : undefined, true);
1010
1072
  set(sheet, 'A3', data.snapshot?.request?.packingMode === 'DRAFT' ? 'PACKING LIST — DRAFT' : 'PACKING LIST');
1011
- // 收货信息(左)与卖家信息(右):标签为模板静态内容,值由生成数据填充
1012
- // 信息块缺失值显示 —,避免大片空白;日期写入后保持模板的 yyyy/m/d 格式
1013
1073
  set(sheet, 'B4', translated.customerName || '—');
1014
1074
  set(sheet, 'B5', translated.customerAddress || '—');
1015
1075
  set(sheet, 'B6', translated.customerCountry || '—');
@@ -1023,41 +1083,11 @@ function fillPackingSheet(sheet, data) {
1023
1083
  set(sheet, 'F6', translated.customerContact || '—');
1024
1084
  set(sheet, 'F7', company?.email || '—');
1025
1085
  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;
1086
+ rows.forEach((line, index) => {
1087
+ const row = index + 12;
1088
+ [line.productName, line.description, line.cartonNo, line.quantity].forEach((value, offset) => { sheet.getCell(row, offset + 1).value = value; });
1089
+ });
1090
+ const totalsRow = 12 + rows.length;
1061
1091
  const incomplete = packing?.totalsComplete === false;
1062
1092
  const labels = ['Total Gross weight (KG)', 'Total Net weight (KG)', 'Volume (CBM)', 'Total Carton (CTN)'];
1063
1093
  const totals = [packing?.totals.grossKg, null, packing?.totals.volumeCbm, packing?.totals.cartons];
@@ -1068,42 +1098,29 @@ function fillPackingSheet(sheet, data) {
1068
1098
  if (incomplete && offset !== 1)
1069
1099
  sheet.getCell(totalsRow + offset, 6).note = 'Known packaging data only. Missing or unallocated packaging quantities are excluded; verify before use.';
1070
1100
  });
1071
- stylePackingSheet(sheet, derived.lines.length);
1072
- for (const address of ['B4', 'B5', 'B6', 'B7', 'B8', 'F4', 'F5', 'F6', 'F7', 'F8']) {
1101
+ stylePackingSheet(sheet, rows.length);
1102
+ fillPackingPhysicalRows(sheet, rows, data);
1103
+ for (const address of ['B4', 'B5', 'B6', 'B7', 'B8', 'F4', 'F5', 'F6', 'F7', 'F8'])
1073
1104
  if (sheet.getCell(address).value === '—')
1074
1105
  markReview(sheet.getCell(address));
1075
- }
1076
- for (let index = 0; index < derived.lines.length; index++) {
1106
+ rows.forEach((line, index) => {
1077
1107
  const row = index + 12;
1078
1108
  for (const column of [10, 11])
1079
1109
  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));
1110
+ if (!line.cartonNo)
1111
+ markReview(sheet.getCell(row, 3));
1112
+ if (line.pending && (packing || data.packagingDetails)) {
1113
+ markReview(sheet.getCell(row, 4));
1114
+ if (data.packagingDetails)
1115
+ markReview(sheet.getCell(row, 2));
1095
1116
  }
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
- }
1117
+ if (line.quantity == null)
1118
+ markReview(sheet.getCell(row, 4));
1119
+ });
1102
1120
  if (incomplete || packing?.warnings?.some((warning) => warning.code === 'PACKING_SOURCE_TOTAL_DIFF'))
1103
1121
  for (const offset of [0, 2, 3])
1104
1122
  markReview(sheet.getCell(totalsRow + offset, 6));
1105
1123
  markReview(sheet.getCell(totalsRow + 1, 6));
1106
- applySharedPackageLayout(sheet, packing?.sourceLines ?? [], sourceDisplay ? undefined : derived.lines.map((line) => line.purchaseOrderLineId));
1107
1124
  }
1108
1125
  /**
1109
1126
  * 银行信息区块按通道分两种布局:
@@ -1249,22 +1266,28 @@ function fillCustomsSheet(sheet, data) {
1249
1266
  const row = 14 + index * 2;
1250
1267
  for (let col = 2; col <= 10; col++)
1251
1268
  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(';'));
1269
+ const product = purchaseLines[index];
1270
+ set(sheet, `C${row + 1}`, product.declarationElements || product.productDescription || '');
1253
1271
  safeMerge(sheet, `A${row}:A${row + 1}`);
1254
1272
  safeMerge(sheet, `K${row}:K${row + 1}`);
1255
1273
  safeMerge(sheet, `L${row}:L${row + 1}`);
1256
1274
  set(sheet, `A${row}`, index + 1);
1257
1275
  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 ?? '');
1276
+ set(sheet, `C${row}`, product.productName || '');
1261
1277
  set(sheet, `F${row}`, Number(pricing.lines[index].unitPrice));
1262
1278
  set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount));
1263
1279
  set(sheet, `H${row}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
1264
1280
  set(sheet, `I${row}`, purchaseLines[index].originCountry || '待确认');
1265
1281
  set(sheet, `J${row}`, customer.country || '待确认');
1266
1282
  set(sheet, `K${row}`, purchaseLines[index].domesticSourceLocation || '待确认');
1267
- set(sheet, `L${row}`, '待确认');
1283
+ set(sheet, `L${row}`, product.taxMode || '待确认');
1284
+ const quantities = customsQuantityRows(product, derived.lines[index]);
1285
+ for (const [offset, entry] of quantities.entries()) {
1286
+ set(sheet, `D${row + offset}`, entry.quantity);
1287
+ set(sheet, `E${row + offset}`, entry.unit);
1288
+ if (entry.review)
1289
+ markReview(sheet.getCell(`D${row + offset}`));
1290
+ }
1268
1291
  for (const warning of data.generationWarnings ?? [])
1269
1292
  if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
1270
1293
  markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
@@ -1275,6 +1298,30 @@ function fillCustomsSheet(sheet, data) {
1275
1298
  normalizeCustomsConfirmationRow(sheet, tail);
1276
1299
  set(sheet, `B${tail + 3}`, companyText);
1277
1300
  }
1301
+ /** Quantity order follows explicit statutory units; trade quantity and sale pricing remain independent. */
1302
+ function customsQuantityRows(product, commercial) {
1303
+ const primary = String(product.statutoryUnitPrimary || product.unit || '').trim();
1304
+ const isKg = (unit) => /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(unit);
1305
+ // A kg-first declaration still needs the independently recorded commercial quantity.
1306
+ const secondary = String(product.statutoryUnitSecondary || (isKg(primary) && product.unit && !isKg(product.unit) ? product.unit : '')).trim();
1307
+ return [primary, secondary].map(unit => {
1308
+ if (!unit)
1309
+ return { unit, quantity: null, review: false };
1310
+ if (isKg(unit)) {
1311
+ const weight = product.netWeightKg;
1312
+ const valid = typeof weight === 'number' && Number.isFinite(weight) && weight >= 0;
1313
+ return { unit, quantity: valid ? weight : null, review: !valid || weight === 0 };
1314
+ }
1315
+ const normalizedUnit = (value) => String(value ?? '').normalize('NFKC').trim().toLowerCase().replace(/\.$/, '');
1316
+ const countUnit = (value) => /^(?:pcs?|pieces?|个|件|台)$/.test(value);
1317
+ const setUnit = (value) => /^(?:sets?|套)$/.test(value);
1318
+ const sourceUnit = normalizedUnit(product.unit);
1319
+ const targetUnit = normalizedUnit(unit);
1320
+ const compatible = Boolean(sourceUnit) && (sourceUnit === targetUnit || (countUnit(sourceUnit) && countUnit(targetUnit)) || (setUnit(sourceUnit) && setUnit(targetUnit)));
1321
+ const valid = compatible && !commercial.quantityPending && commercial.quantity != null && Number.isFinite(Number(commercial.quantity));
1322
+ return { unit, quantity: valid ? Number(commercial.quantity) : null, review: !valid };
1323
+ });
1324
+ }
1278
1325
  function normalizeCustomsConfirmationRow(sheet, row) {
1279
1326
  safeMerge(sheet, `A${row}:L${row}`);
1280
1327
  const cell = sheet.getCell(row, 1);
@@ -1453,16 +1500,17 @@ const salesFileNameTypeLabels = { PI: 'PI', CI: 'CI', PL: 'PL', CUSTOMS_DECLARAT
1453
1500
  function isTranslationFailure(value) { return value.code === DomainErrorCodes.TRANSLATION_FAILED && typeof value.field === 'string' && typeof value.sourceValue === 'string' && typeof value.message === 'string'; }
1454
1501
  function scoped(scope) { return { tenantId: scope.tenantId, organizationId: scope.organizationId }; }
1455
1502
  function deterministicEnglish(value, field) {
1456
- const text = value.trim().replace(/\s+/g, ' ');
1503
+ const text = value.trim();
1457
1504
  if (!text)
1458
1505
  return '';
1459
1506
  if (field.endsWith('.unit') && unitFallback(text) != null)
1460
1507
  return unitFallback(text);
1508
+ // Reviewed English specifications retain supplier line breaks and spacing.
1509
+ if (/^[\p{Script=Latin}\p{N}\p{P}\p{S}\p{Z}\s]+$/u.test(text) && /[A-Za-z0-9]/.test(text))
1510
+ return text;
1461
1511
  const normalized = normalizeKnownBusinessTerms(text);
1462
1512
  if (normalized !== text && !/\p{Script=Han}/u.test(normalized))
1463
1513
  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
1514
  return null;
1467
1515
  }
1468
1516
  function normalizeKnownBusinessTerms(value) {