@chenchaolong/plugin-trade-compliance-workbench 1.0.232 → 1.0.234

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 (59) hide show
  1. package/dist/lib/entities/supplier-packing.entity.d.ts +6 -0
  2. package/dist/lib/entities/supplier-packing.entity.d.ts.map +1 -1
  3. package/dist/lib/entities/supplier-packing.entity.js +4 -0
  4. package/dist/lib/entities/supplier-packing.entity.js.map +1 -1
  5. package/dist/lib/import-jobs/purchase-source-city.d.ts +17 -0
  6. package/dist/lib/import-jobs/purchase-source-city.d.ts.map +1 -0
  7. package/dist/lib/import-jobs/purchase-source-city.js +50 -0
  8. package/dist/lib/import-jobs/purchase-source-city.js.map +1 -0
  9. package/dist/lib/invoice-formatting.d.ts +1 -1
  10. package/dist/lib/invoice-formatting.d.ts.map +1 -1
  11. package/dist/lib/invoice-formatting.js +12 -6
  12. package/dist/lib/invoice-formatting.js.map +1 -1
  13. package/dist/lib/packing/packing-complete-rows.d.ts +18 -0
  14. package/dist/lib/packing/packing-complete-rows.d.ts.map +1 -0
  15. package/dist/lib/packing/packing-complete-rows.js +98 -0
  16. package/dist/lib/packing/packing-complete-rows.js.map +1 -0
  17. package/dist/lib/packing/packing-full-text.d.ts +6 -0
  18. package/dist/lib/packing/packing-full-text.d.ts.map +1 -0
  19. package/dist/lib/packing/packing-full-text.js +101 -0
  20. package/dist/lib/packing/packing-full-text.js.map +1 -0
  21. package/dist/lib/packing/packing-layout.d.ts +1 -0
  22. package/dist/lib/packing/packing-layout.d.ts.map +1 -1
  23. package/dist/lib/packing/packing-layout.js +5 -5
  24. package/dist/lib/packing/packing-layout.js.map +1 -1
  25. package/dist/lib/packing/packing-render.d.ts +5 -0
  26. package/dist/lib/packing/packing-render.d.ts.map +1 -1
  27. package/dist/lib/packing/packing-render.js +15 -3
  28. package/dist/lib/packing/packing-render.js.map +1 -1
  29. package/dist/lib/packing/packing-role.d.ts +4 -0
  30. package/dist/lib/packing/packing-role.d.ts.map +1 -0
  31. package/dist/lib/packing/packing-role.js +26 -0
  32. package/dist/lib/packing/packing-role.js.map +1 -0
  33. package/dist/lib/packing/packing-spreadsheet.d.ts.map +1 -1
  34. package/dist/lib/packing/packing-spreadsheet.js +2 -8
  35. package/dist/lib/packing/packing-spreadsheet.js.map +1 -1
  36. package/dist/lib/packing/shipment-documents.d.ts +1 -1
  37. package/dist/lib/packing/shipment-documents.d.ts.map +1 -1
  38. package/dist/lib/packing/shipment-documents.js +6 -2
  39. package/dist/lib/packing/shipment-documents.js.map +1 -1
  40. package/dist/lib/packing/supplier-packing.service.d.ts.map +1 -1
  41. package/dist/lib/packing/supplier-packing.service.js +33 -35
  42. package/dist/lib/packing/supplier-packing.service.js.map +1 -1
  43. package/dist/lib/remote-components/trade-compliance-workbench/app.js +1 -1
  44. package/dist/lib/remote-ui/components/supplier-materials.js +1 -1
  45. package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -1
  46. package/dist/lib/sales-file.service.d.ts +1 -1
  47. package/dist/lib/sales-file.service.d.ts.map +1 -1
  48. package/dist/lib/sales-file.service.js +124 -89
  49. package/dist/lib/sales-file.service.js.map +1 -1
  50. package/dist/lib/schema-maintenance.d.ts.map +1 -1
  51. package/dist/lib/schema-maintenance.js +2 -1
  52. package/dist/lib/schema-maintenance.js.map +1 -1
  53. package/dist/lib/supplier-materials/product-matching.d.ts.map +1 -1
  54. package/dist/lib/supplier-materials/product-matching.js +24 -19
  55. package/dist/lib/supplier-materials/product-matching.js.map +1 -1
  56. package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
  57. package/dist/lib/supplier-materials/supplier-materials.js +27 -45
  58. package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
  59. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
+ import { recoverPurchaseSourceCities, extractCityName } from './import-jobs/purchase-source-city.js';
2
3
  import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
3
4
  import { generationMaterials } from './supplier-materials/generation-materials.js';
4
5
  import { purchasePriceEvidenceWarning } from './domain/purchase-price-evidence.js';
@@ -13,12 +14,11 @@ import ExcelJS from 'exceljs';
13
14
  import JSZip from 'jszip';
14
15
  import { aggregatePackingBatches } from './packing/packing-render.js';
15
16
  import { PACKING_IMPORT_ACTIVE_STATUSES } from './packing/packing-import-task.contract.js';
16
- import { buildPackingCommercialRows, supplierCartonNo } from './packing/packing-commercial-rows.js';
17
- import { packingRoleLabels } from './packing/packing-source-display.js';
18
- import { shipmentDerived, appendShipmentReview, markReview } from './packing/shipment-documents.js';
17
+ import { completePackingRows } from './packing/packing-complete-rows.js';
18
+ import { shipmentDerived, markReview } from './packing/shipment-documents.js';
19
19
  import { formatInvoiceSheet } from './invoice-formatting.js';
20
20
  import { formatCustomsSheet } from './customs-formatting.js';
21
- import { stylePackingSheet, appendPackingSpecifications } from './packing/packing-layout.js';
21
+ import { stylePackingSheet, expandPackingTextRows } from './packing/packing-layout.js';
22
22
  import * as yauzl from 'yauzl';
23
23
  import { Decimal } from 'decimal.js';
24
24
  import { BankAccountSettings, CompanySettings, Customer, CustomerContract, CustomerContractClause, GeneratedSalesFile, MonthlySafeExchangeRate, ProfitRuleSettings, PurchaseOrder, PurchaseOrderLine, SupplierPacking, SupplierPackingLine } from './entities/index.js';
@@ -39,7 +39,8 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
39
39
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
40
40
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
41
41
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
42
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-05.customs-source-order';
42
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-10.single-sheet-complete';
43
+ const PACKING_LAYOUT_VERSION = 'v14';
43
44
  const COMPANY_LOGO_PLACEMENTS = {
44
45
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
45
46
  CI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -106,6 +107,13 @@ let SalesFileService = class SalesFileService {
106
107
  generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
107
108
  const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
108
109
  const materialData = generationMaterials(purchaseLines, materialDocuments);
110
+ const customsSourceCities = requestedTypes.includes('CUSTOMS_DECLARATION') ? await recoverPurchaseSourceCities(evaluated.purchaseOrderEntities, id => this.storage.read(id)) : {};
111
+ if (requestedTypes.includes('CUSTOMS_DECLARATION'))
112
+ for (const line of materialData.customsLines) {
113
+ line.domesticSourceLocation = customsSourceCities[line.purchaseOrderId]?.city;
114
+ if (!line.domesticSourceLocation)
115
+ generationWarnings.push({ code: 'CUSTOMS_SOURCE_CITY_MISSING', purchaseOrderLineId: line.id, message: `商品“${line.productName}”对应采购合同未找到可确定的卖方城市,货源地留空。` });
116
+ }
109
117
  generationWarnings.push(...materialData.warnings);
110
118
  const materialsFingerprint = materialSelectionFingerprint(materialDocuments);
111
119
  await hooks?.progress('TRANSLATING', 0);
@@ -146,7 +154,7 @@ let SalesFileService = class SalesFileService {
146
154
  return false;
147
155
  if (fileType === 'CUSTOMS_DECLARATION' && (String(warning.code ?? '').startsWith('TRANSLATION_') || warning.code === 'SOURCE_FIELD_REVIEW'))
148
156
  return false;
149
- if (warning.code === 'PACKING_NET_WEIGHT_CALCULATED')
157
+ if (warning.code === 'PACKING_NET_WEIGHT_SOURCE')
150
158
  return fileType === 'PL';
151
159
  if (field.startsWith('packing.'))
152
160
  return fileType === 'PL';
@@ -156,8 +164,8 @@ let SalesFileService = class SalesFileService {
156
164
  });
157
165
  if (fileType === 'CUSTOMS_DECLARATION')
158
166
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
159
- 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 };
160
- 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 } };
167
+ const request = { currencyCode: documentPricing.currencyCode, ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION, shipmentDocumentsVersion: 'v2', orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: PACKING_LAYOUT_VERSION } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
168
+ const snapshot = { customsSourceCities, customsCoverage: 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 } };
161
169
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
162
170
  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);
163
171
  await validateWorkbook(buffer);
@@ -400,7 +408,7 @@ let SalesFileService = class SalesFileService {
400
408
  orderAmountCny: orders.reduce((sum, order) => sum.plus(order.orderAmountCny ?? 0), new Decimal(0)).toFixed(2),
401
409
  lines: orderEntries.flatMap(entry => entry.derived.lines)
402
410
  };
403
- return { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing };
411
+ return { derived, customerContract, customer, purchaseOrder, purchaseOrderEntities, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing };
404
412
  }
405
413
  async download(scope, id) {
406
414
  const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
@@ -502,8 +510,8 @@ let SalesFileService = class SalesFileService {
502
510
  warnings.push({ code: 'SOURCE_FIELD_REVIEW', field, sourceValue: value, message: `字段 ${field} 保留原文“${value}”,英文待确认` });
503
511
  return value;
504
512
  }
505
- failures.push({ code: DomainErrorCodes.TRANSLATION_FAILED, field, sourceValue: value, message: configured ? 'AI翻译失败,目标单元格已留空' : '未配置翻译服务,英文信息待补充,目标单元格已留空' });
506
- return '';
513
+ failures.push({ code: DomainErrorCodes.TRANSLATION_FAILED, field, sourceValue: value, message: configured ? 'AI翻译失败,已采用来源原文并标色' : '未配置翻译服务,已采用来源原文并标色' });
514
+ return value;
507
515
  };
508
516
  // Pack all unknown text once. No serial per-row requests and no duplicate
509
517
  // invoice/packing translation passes for a combined export.
@@ -605,7 +613,7 @@ let SalesFileService = class SalesFileService {
605
613
  const warnings = derived.lines
606
614
  .filter(line => !packing.byPurchaseLine[line.purchaseOrderLineId])
607
615
  .map(line => ({ code: 'PACKING_LINE_MISSING', purchaseOrderLineId: line.purchaseOrderLineId, productName: line.productName, message: `商品“${line.productName}”尚未匹配供应商装箱行;主表采用订单数量,请核对包装明细中的商品归属。` }));
608
- warnings.push({ code: 'PACKING_NET_WEIGHT_CALCULATED', message: 'PL 净重按毛重 × 0.8 计算;共箱净重按整箱展示并只统计一次,不代表各商品独立净重。缺少有效毛重时留空。' });
616
+ warnings.push({ code: 'PACKING_NET_WEIGHT_SOURCE', message: 'PL 整票净重仅采用已确认完整来源;来源未提供的单箱或逐箱净重留空,不按毛重比例推算。' });
609
617
  warnings.push(...packing.warnings);
610
618
  return warnings;
611
619
  }
@@ -746,7 +754,7 @@ function generationRequestMatches(item, expected) {
746
754
  bankType === expected.bankType &&
747
755
  lineOrderMatches && (request.shipmentDocumentsVersion !== 'v2' || request.orderDataFingerprint === expected.orderDataFingerprint) &&
748
756
  !item.generationWarnings?.some(warning => warning.code === DomainErrorCodes.TRANSLATION_FAILED || warning.code === 'TRANSLATION_NOT_CONFIGURED' || warning.code === 'TRANSLATION_SERVICE_UNAVAILABLE') &&
749
- (item.fileType === 'PI' || request.shipmentDocumentsVersion === 'v2') && (item.fileType !== 'PL' || request.packingLayoutVersion === 'v11') &&
757
+ (item.fileType === 'PI' || request.shipmentDocumentsVersion === 'v2') && (item.fileType !== 'PL' || request.packingLayoutVersion === PACKING_LAYOUT_VERSION) &&
750
758
  packingMatches &&
751
759
  ordersKeyMatches);
752
760
  }
@@ -801,7 +809,7 @@ function fillInvoiceSheet(sheet, type, data) {
801
809
  const row = 12 + index;
802
810
  const englishProduct = translated.lines[index]?.productName ?? '';
803
811
  const productLabel = englishProduct;
804
- [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);
812
+ [index + 1, productLabel, translated.lines[index]?.description ?? '', Number(derived.lines[index].quantity), Number(pricing.lines[index].unitPrice), translated.lines[index]?.unit ?? '', Number(pricing.lines[index].usdToCnyRate ?? 1), Number(pricing.lines[index].lineAmount), derived.lines[index].hsCode ?? ''].forEach((value, offset) => sheet.getCell(row, offset < 7 ? offset + 1 : offset + 2).value = value);
805
813
  safeMerge(sheet, `G${row}:H${row}`);
806
814
  sheet.getCell(`E${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
807
815
  sheet.getCell(`I${row}`).numFmt = '0.00';
@@ -841,36 +849,19 @@ export async function renderSalesWorkbook(type, data, logo) {
841
849
  cleanBrokenFormulas(sheet);
842
850
  if (type === 'PI' || type === 'CI')
843
851
  fillInvoiceSheet(sheet, type, data);
844
- else if (type === 'PL') {
845
- // Commercial goods and supplier physical packages use different units.
846
- // Retain both without appending companion quantities to the goods total.
847
- if (data.packing?.sourceLines?.length) {
848
- const detail = workbook.addWorksheet('Packaging Details');
849
- const templateMerges = [...(sheet.model.merges ?? [])];
850
- detail.model = { ...structuredClone(sheet.model), id: detail.id, name: 'Packaging Details' };
851
- // ExcelJS's model setter expects mergeCells while its getter exposes
852
- // merges; reconstruct these explicitly when cloning the template.
853
- for (const range of templateMerges)
854
- safeMerge(detail, range);
855
- fillPackingSheet(detail, { ...data, packagingDetails: true });
856
- set(detail, 'A3', 'PACKAGING DETAILS');
857
- }
852
+ else if (type === 'PL')
858
853
  fillPackingSheet(sheet, data);
859
- appendPackingSpecifications(workbook, sheet, ...[workbook.getWorksheet('Packaging Details')].filter((detail) => Boolean(detail)));
860
- }
861
854
  else
862
855
  fillCustomsSheet(sheet, data);
863
856
  normalizeDisplayValues(sheet);
864
857
  if (type !== 'CUSTOMS_DECLARATION')
865
858
  normalizeEnglishLabels(sheet);
866
859
  if (type === 'PI' || type === 'CI')
867
- formatInvoiceSheet(sheet, data.derived.lines.length);
860
+ formatInvoiceSheet(sheet, data.derived.lines.length, true);
868
861
  if (type === 'CUSTOMS_DECLARATION')
869
862
  formatCustomsSheet(sheet, data.derived.lines.length);
870
863
  if (type !== 'CUSTOMS_DECLARATION' && logo)
871
864
  addCompanyLogo(type, workbook, sheet, logo);
872
- if (type === 'PL' && logo && workbook.getWorksheet('Packaging Details'))
873
- addCompanyLogo('PL', workbook, workbook.getWorksheet('Packaging Details'), logo);
874
865
  const fieldLocations = {};
875
866
  if (type === 'PI' || type === 'CI') {
876
867
  for (const [field, cell] of Object.entries({ 'customer.address': 'B5', 'customer.contactName': 'B6', 'customer.country': 'B9', 'clause.PAYMENT_TERMS': 'F8', 'clause.TRANSPORT': `C${14 + data.derived.lines.length}` }))
@@ -882,16 +873,18 @@ export async function renderSalesWorkbook(type, data, logo) {
882
873
  }
883
874
  if (type === 'PL') {
884
875
  Object.assign(fieldLocations, { 'customer.address': { location: 'PL!B5' }, 'customer.contactName': { location: 'PL!B7' }, 'customer.country': { location: 'PL!B6' } });
885
- const plRows = buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []);
876
+ const plRows = completePackingRows(data);
886
877
  data.purchaseLines.forEach((line, orderIndex) => {
887
- const index = plRows.findIndex(row => !row.companion && row.orderIndex === orderIndex);
878
+ const index = plRows.findIndex(row => row.orderIndex === orderIndex);
888
879
  if (index >= 0)
889
880
  for (const [field, column] of Object.entries({ productName: 'A', description: 'B' }))
890
881
  fieldLocations[`line.${line.id}.${field}`] = { location: `PL!${column}${12 + index}`, productName: line.productName };
891
882
  });
892
883
  (data.packing?.sourceLines ?? []).forEach((line, index) => {
893
- for (const field of ['description', 'battery'])
894
- fieldLocations[`packing.${line.id}.${field}`] = { location: `Packaging Details!B${12 + index}` };
884
+ const displayIndex = plRows.findIndex(row => row.sourceLineId === line.id);
885
+ if (displayIndex >= 0)
886
+ for (const field of ['description', 'battery'])
887
+ fieldLocations[`packing.${line.id}.${field}`] = { location: `PL!B${12 + displayIndex}` };
895
888
  });
896
889
  }
897
890
  for (const line of data.derived.lines) {
@@ -901,14 +894,14 @@ export async function renderSalesWorkbook(type, data, logo) {
901
894
  if (line.amountPending && (type === 'PI' || type === 'CI'))
902
895
  markReview(sheet.getCell(12 + index, 9));
903
896
  }
904
- const plWarningRows = type === 'PL' ? buildPackingCommercialRows(data.derived.lines, data.packing?.sourceLines ?? []) : [];
897
+ const plWarningRows = type === 'PL' ? completePackingRows(data) : [];
905
898
  for (const warning of data.generationWarnings ?? []) {
906
899
  const field = String(warning.field ?? '');
907
900
  const commercialField = type === 'PL' ? /^line\.(.+)\.(productName|description)$/.exec(field) : null;
908
901
  if (commercialField) {
909
902
  const orderIndex = data.purchaseLines.findIndex((line) => line.id === commercialField[1]);
910
903
  const column = commercialField[2] === 'description' ? 2 : 1;
911
- plWarningRows.forEach((row, index) => { if (!row.companion && row.orderIndex === orderIndex)
904
+ plWarningRows.forEach((row, index) => { if (row.orderIndex === orderIndex)
912
905
  markReview(sheet.getCell(index + 12, column)); });
913
906
  }
914
907
  const target = fieldLocations[field];
@@ -926,8 +919,76 @@ export async function renderSalesWorkbook(type, data, logo) {
926
919
  markReview(cell);
927
920
  }
928
921
  }));
929
- appendShipmentReview(workbook, data.generationWarnings ?? data.packing?.warnings ?? [], data.packing, fieldLocations);
930
- return Buffer.from(await workbook.xlsx.writeBuffer());
922
+ applySingleSheetReview(sheet, type, data, fieldLocations);
923
+ if (type === 'PL')
924
+ for (const packingSheet of [sheet, workbook.getWorksheet('Packaging Details')].filter((value) => Boolean(value))) {
925
+ const rows = expandPackingTextRows(packingSheet);
926
+ for (const target of Object.values(fieldLocations)) {
927
+ const [name, address] = target.location.split('!');
928
+ const match = /^([A-Z]+)(\d+)$/.exec(address ?? '');
929
+ if (name === packingSheet.name && match && rows.has(Number(match[2])))
930
+ target.location = `${name}!${match[1]}${rows.get(Number(match[2]))}`;
931
+ }
932
+ }
933
+ for (const other of [...workbook.worksheets])
934
+ if (other.id !== sheet.id)
935
+ workbook.removeWorksheet(other.id);
936
+ return removeExportComments(Buffer.from(await workbook.xlsx.writeBuffer()));
937
+ }
938
+ /** Remove comment parts and their relationships without changing drawings or business cells. */
939
+ async function removeExportComments(buffer) {
940
+ const zip = await JSZip.loadAsync(buffer);
941
+ for (const name of Object.keys(zip.files)) {
942
+ if (/^xl\/(?:comments[^/]*\.xml|comments\/|drawings\/vmlDrawing[^/]*\.vml)/i.test(name))
943
+ zip.remove(name);
944
+ else if (/\.rels$/.test(name)) {
945
+ const xml = await zip.file(name).async('string');
946
+ zip.file(name, xml.replace(/<Relationship\b[^>]*Type="[^"]*\/(?:comments|vmlDrawing)"[^>]*\/?\s*>/g, ''));
947
+ }
948
+ else if (/^xl\/worksheets\/sheet\d+\.xml$/.test(name)) {
949
+ const xml = await zip.file(name).async('string');
950
+ zip.file(name, xml.replace(/<legacyDrawing\b[^>]*\/?\s*>/g, ''));
951
+ }
952
+ else if (name === '[Content_Types].xml') {
953
+ const xml = await zip.file(name).async('string');
954
+ zip.file(name, xml.replace(/<Override\b[^>]*ContentType="[^"]*comments[^"]*"[^>]*\/?\s*>/g, ''));
955
+ }
956
+ }
957
+ return zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });
958
+ }
959
+ /** Keep review metadata in the application; exported workbooks communicate through color only. */
960
+ function applySingleSheetReview(sheet, type, data, locations) {
961
+ const plRows = type === 'PL' ? completePackingRows(data) : [];
962
+ for (const warning of [...(data.generationWarnings ?? []), ...(data.packing?.warnings ?? [])]) {
963
+ const field = String(warning.field ?? ''), code = String(warning.code ?? '');
964
+ const color = /CONFLICT|EXCEEDED|TOTAL_DIFF/.test(code) ? 'FFFFC7CE' : /MISSING|NOT_PROVIDED/.test(code) ? 'FFFFF2CC' : 'FFFFE0B2';
965
+ const target = locations[field];
966
+ if (target?.location.startsWith(sheet.name + '!')) {
967
+ const cell = sheet.getCell(target.location.slice(sheet.name.length + 1));
968
+ if (!cell.value && warning.sourceValue != null)
969
+ cell.value = String(warning.sourceValue);
970
+ markReview(cell, color);
971
+ }
972
+ const purchaseId = warning.purchaseOrderLineId || data.purchaseLines.find((line) => field.startsWith(`purchase.${line.id}.`) || field.startsWith(`customs.${line.id}.`) || field.startsWith(`line.${line.id}.`))?.id;
973
+ if (type === 'PL') {
974
+ plRows.forEach((row, index) => {
975
+ if (purchaseId && row.purchaseOrderLineId === purchaseId || warning.packingLineId && row.sourceLineId === warning.packingLineId)
976
+ for (const col of [1, 2, 4])
977
+ markReview(sheet.getCell(index + 12, col), color);
978
+ });
979
+ if (/TOTAL_DIFF/.test(code)) {
980
+ const total = 12 + plRows.length;
981
+ for (const offset of [0, 2, 3])
982
+ markReview(sheet.getCell(total + offset, 6), color);
983
+ }
984
+ }
985
+ else if (purchaseId) {
986
+ const index = data.derived.lines.findIndex((line) => line.purchaseOrderLineId === purchaseId);
987
+ if (index >= 0)
988
+ for (const col of type === 'CUSTOMS_DECLARATION' ? [2, 3, 4, 6, 7] : [2, 3, 4, 5, 9])
989
+ markReview(sheet.getCell(type === 'CUSTOMS_DECLARATION' ? 14 + index * 2 : 12 + index, col), color);
990
+ }
991
+ }
931
992
  }
932
993
  function addCompanyLogo(type, workbook, sheet, logo) {
933
994
  const bounds = imagePlacementBounds(sheet, COMPANY_LOGO_PLACEMENTS[type]);
@@ -1023,32 +1084,7 @@ const packingPhysicalColumns = [5, 6, 7, 8, 9, 12];
1023
1084
  const packingPhysicalFields = ['dimensionCm', 'grossWeightPerCtnKg', 'cartons', 'boxVolumeCbm', 'totalVolumeCbm', 'totalGrossWeightKg'];
1024
1085
  const packingPhysicalKey = (row) => JSON.stringify([row.packingId, row.packageGroup ?? row.id]);
1025
1086
  function packingSheetRows(data) {
1026
- const source = data.packing?.sourceLines ?? [];
1027
- if (data.packagingDetails)
1028
- return source.map(line => {
1029
- const english = data.translated.packingLines?.find((item) => item.id === line.id);
1030
- const description = english?.description ?? (line.description && !/\p{Script=Han}/u.test(line.description) ? line.description : '');
1031
- const battery = english?.battery ?? (line.battery && !/\p{Script=Han}/u.test(line.battery) ? line.battery : '');
1032
- return {
1033
- productName: line.model ?? '', description: [description, line.role && line.role !== 'PART' ? packingRoleLabels[line.role] ?? line.role : '', battery && battery !== '无' ? `Battery: ${battery}` : ''].filter(Boolean).join('\n'),
1034
- quantity: line.qty == null ? null : Number(line.qty), cartonNo: supplierCartonNo(line), sourceLineId: line.id, packageKey: packingPhysicalKey(line), metrics: line,
1035
- 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)
1036
- };
1037
- });
1038
- return buildPackingCommercialRows(data.derived.lines, source).map(row => {
1039
- if (row.companion) {
1040
- const physical = source.find(line => line.id === row.sourceLineId && packingPhysicalKey(line) === row.packageKey);
1041
- const english = data.translated.packingLines?.find((line) => line.id === row.sourceLineId);
1042
- const description = english?.description ?? (physical?.description && !/\p{Script=Han}/u.test(physical.description) ? physical.description : '');
1043
- return { ...row, productName: physical?.model || 'Companion packaging', description: ['Companion packaging / not additional goods', description].filter(Boolean).join('\n'), quantity: null, pending: row.pending || Boolean(/\p{Script=Han}/u.test(physical?.description ?? '') && !english?.description) };
1044
- }
1045
- const aggregate = !source.length ? data.packing?.byPurchaseLine?.[row.purchaseOrderLineId] : null;
1046
- const legacyMetrics = aggregate && aggregate.statisticsComplete !== false ? {
1047
- dimensionCm: aggregate.dimensions?.join(' / '), grossWeightPerCtnKg: aggregate.weightsPerCtn?.length > 1 ? aggregate.weightsPerCtn.join(' / ') : aggregate.weightPerCtn == null ? null : String(aggregate.weightPerCtn),
1048
- 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)
1049
- } : undefined;
1050
- 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) };
1051
- });
1087
+ return completePackingRows(data);
1052
1088
  }
1053
1089
  /** Resolve the supplier's physical group once, independently of commercial quantities. */
1054
1090
  function fillPackingPhysicalRows(sheet, rows, data) {
@@ -1071,20 +1107,15 @@ function fillPackingPhysicalRows(sheet, rows, data) {
1071
1107
  const raw = row.metrics?.[field];
1072
1108
  let value = raw == null || raw === '' ? null : offset === 0 || !Number.isFinite(Number(raw)) ? String(raw) : Number(raw);
1073
1109
  if (members.length)
1074
- value = conflict ? data.packagingDetails ? value : null : completeScope && !repeated ? facts[offset][0] ?? null : null;
1110
+ value = repeated ? null : row.metricsScoped || !completeScope ? value : conflict ? value : facts[offset][0] ?? value;
1075
1111
  cell.value = value;
1076
1112
  if (conflict || !completeScope || !repeated && (value == null || typeof value === 'number' && (!Number.isFinite(value) || value <= 0)))
1077
- markReview(cell);
1113
+ markReview(cell, conflict ? 'FFFFC7CE' : !completeScope ? 'FFFFE0B2' : undefined);
1078
1114
  });
1079
- for (const [column, grossColumn] of [[10, 6], [11, 12]]) {
1080
- const cell = sheet.getCell(excelRow, column);
1081
- const gross = sheet.getCell(excelRow, grossColumn).value;
1082
- cell.value = typeof gross === 'number' && Number.isFinite(gross) && gross > 0 ? new Decimal(gross).times('0.8').toDecimalPlaces(6).toNumber() : null;
1083
- cell.numFmt = '0.######';
1084
- if (cell.value != null)
1085
- cell.note = 'Net weight = gross weight × 0.8. Shared carton weight is counted once; no per-product weight allocation.';
1086
- else if (!repeated || conflict || !completeScope)
1087
- markReview(cell);
1115
+ // The source packing format does not provide per-carton net weight.
1116
+ for (const column of [10, 11]) {
1117
+ sheet.getCell(excelRow, column).value = null;
1118
+ sheet.getCell(excelRow, column).numFmt = '0.######';
1088
1119
  }
1089
1120
  if (conflict || !completeScope) {
1090
1121
  markReview(sheet.getCell(excelRow, 3));
@@ -1098,7 +1129,7 @@ function fillPackingPhysicalRows(sheet, rows, data) {
1098
1129
  let end = start;
1099
1130
  while (first.packageKey && end + 1 < rows.length && rows[end + 1].packageKey === first.packageKey && rows[end + 1].cartonNo === first.cartonNo)
1100
1131
  end++;
1101
- if (end > start && !sheet.getCell(start + 12, 3).note)
1132
+ if (end > start)
1102
1133
  for (const col of [3, ...packingPhysicalColumns, 10, 11]) {
1103
1134
  sheet.mergeCells(start + 12, col, end + 12, col);
1104
1135
  sheet.getCell(start + 12, col).alignment = { vertical: 'middle', horizontal: 'center', wrapText: true };
@@ -1112,7 +1143,7 @@ function fillPackingSheet(sheet, data) {
1112
1143
  resizePackingLayout(sheet, rows.length);
1113
1144
  set(sheet, 'B1', company?.addressEn, true);
1114
1145
  set(sheet, 'B2', company?.phone || company?.email ? `Tel:${company?.phone ?? ''} Email:${company?.email ?? ''}` : undefined, true);
1115
- set(sheet, 'A3', data.snapshot?.request?.packingMode === 'DRAFT' ? 'PACKING LIST — DRAFT' : 'PACKING LIST');
1146
+ set(sheet, 'A3', 'PACKING LIST');
1116
1147
  set(sheet, 'B4', translated.customerName || '—');
1117
1148
  set(sheet, 'B5', translated.customerAddress || '—');
1118
1149
  set(sheet, 'B6', translated.customerCountry || '—');
@@ -1134,7 +1165,8 @@ function fillPackingSheet(sheet, data) {
1134
1165
  const incomplete = packing?.totalsComplete === false;
1135
1166
  const labels = ['Total Gross weight (KG)', 'Total Net weight (KG)', 'Volume (CBM)', 'Total Carton (CTN)'];
1136
1167
  const grossKg = packing?.totals.grossKg;
1137
- const totals = [grossKg, typeof grossKg === 'number' && Number.isFinite(grossKg) && grossKg > 0 ? new Decimal(grossKg).times('0.8').toDecimalPlaces(6).toNumber() : null, packing?.totals.volumeCbm, packing?.totals.cartons];
1168
+ const sourceNet = data.customsCoverage?.acceptedNetWeightKg;
1169
+ const totals = [grossKg, sourceNet != null ? Number(sourceNet) : null, packing?.totals.volumeCbm, packing?.totals.cartons];
1138
1170
  labels.forEach((label, offset) => {
1139
1171
  set(sheet, `A${totalsRow + offset}`, label);
1140
1172
  const total = totals[offset];
@@ -1149,6 +1181,9 @@ function fillPackingSheet(sheet, data) {
1149
1181
  markReview(sheet.getCell(address));
1150
1182
  rows.forEach((line, index) => {
1151
1183
  const row = index + 12;
1184
+ if (line.reviewColor)
1185
+ for (const col of [1, 2, 4])
1186
+ markReview(sheet.getCell(row, col), line.reviewColor);
1152
1187
  if (!line.cartonNo)
1153
1188
  markReview(sheet.getCell(row, 3));
1154
1189
  if (line.pending && (packing || data.packagingDetails)) {
@@ -1166,7 +1201,7 @@ function fillPackingSheet(sheet, data) {
1166
1201
  if (totals[1] == null)
1167
1202
  markReview(sheet.getCell(totalsRow + 1, 6));
1168
1203
  else
1169
- sheet.getCell(totalsRow + 1, 6).note = 'Net weight = gross weight × 0.8; shared cartons counted once.';
1204
+ sheet.getCell(totalsRow + 1, 6).note = 'Net weight from confirmed source documents; no proportional estimation.';
1170
1205
  sheet.getCell(totalsRow + 1, 6).numFmt = '0.######';
1171
1206
  }
1172
1207
  /**
@@ -1323,7 +1358,7 @@ function fillCustomsSheet(sheet, data) {
1323
1358
  for (const offset of [0, 1])
1324
1359
  for (const column of [6, 7, 8])
1325
1360
  sheet.getCell(row + offset, column).value = null;
1326
- set(sheet, `C${row + 1}`, product.declarationElements || null);
1361
+ set(sheet, `C${row + 1}`, product.declarationElements || product.productDescription || product.modelSpecification || null);
1327
1362
  if (!String(product.declarationElements ?? '').trim())
1328
1363
  markReview(sheet.getCell(`C${row + 1}`));
1329
1364
  safeMerge(sheet, `A${row}:A${row + 1}`);
@@ -1332,17 +1367,17 @@ function fillCustomsSheet(sheet, data) {
1332
1367
  set(sheet, `A${row}`, index + 1);
1333
1368
  set(sheet, `B${row}`, derived.lines[index].hsCode ?? '');
1334
1369
  set(sheet, `C${row}`, product.productName || '');
1335
- set(sheet, `I${row}`, purchaseLines[index].originCountry || '待确认');
1370
+ set(sheet, `I${row}`, '中国');
1336
1371
  set(sheet, `J${row}`, customer.country || '待确认');
1337
- set(sheet, `K${row}`, purchaseLines[index].domesticSourceLocation || '待确认');
1338
- set(sheet, `L${row}`, product.taxMode || '待确认');
1372
+ set(sheet, `K${row}`, extractCityName(purchaseLines[index].domesticSourceLocation) || '待确认');
1373
+ set(sheet, `L${row}`, '照章征免(1)');
1339
1374
  const quantities = customsQuantityRows(product, derived.lines[index]);
1340
1375
  // Price belongs to the commercial quantity row, never the statutory kg row
1341
1376
  // merely because it is first in the declaration template.
1342
1377
  const kg = /^(?:千克|公斤|kg|kgs|kilograms?)$/i;
1343
1378
  const priceRow = row + (!kg.test(String(product.unit ?? '').trim()) && kg.test(quantities[0].unit) && quantities[1].unit && !kg.test(quantities[1].unit) ? 1 : 0);
1344
1379
  set(sheet, `F${priceRow}`, Number(pricing.lines[index].unitPrice));
1345
- set(sheet, `G${priceRow}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount));
1380
+ set(sheet, `G${priceRow}`, Number(pricing.lines[index].lineAmount));
1346
1381
  set(sheet, `H${priceRow}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
1347
1382
  for (const [offset, entry] of quantities.entries()) {
1348
1383
  set(sheet, `D${row + offset}`, entry.quantity);
@@ -1362,7 +1397,7 @@ function fillCustomsSheet(sheet, data) {
1362
1397
  }
1363
1398
  /** Quantity order follows explicit statutory units; trade quantity and sale pricing remain independent. */
1364
1399
  function customsQuantityRows(product, commercial) {
1365
- const primary = String(product.statutoryUnitPrimary || product.unit || '').trim();
1400
+ const primary = String(product.statutoryUnitPrimary || '').trim();
1366
1401
  const isKg = (unit) => /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(unit);
1367
1402
  // A blank second statutory unit in the source is meaningful; do not invent one from the trade unit.
1368
1403
  const secondary = String(product.statutoryUnitSecondary || '').trim();
@@ -1380,7 +1415,7 @@ function customsQuantityRows(product, commercial) {
1380
1415
  const sourceUnit = normalizedUnit(product.unit);
1381
1416
  const targetUnit = normalizedUnit(unit);
1382
1417
  const compatible = Boolean(sourceUnit) && (sourceUnit === targetUnit || (countUnit(sourceUnit) && countUnit(targetUnit)) || (setUnit(sourceUnit) && setUnit(targetUnit)));
1383
- const valid = compatible && !commercial.quantityPending && commercial.quantity != null && Number.isFinite(Number(commercial.quantity));
1418
+ const valid = compatible && commercial.quantity != null && Number.isFinite(Number(commercial.quantity));
1384
1419
  return { unit, quantity: valid ? Number(commercial.quantity) : null, review: !valid };
1385
1420
  });
1386
1421
  }