@chenchaolong/plugin-trade-compliance-workbench 1.0.253 → 1.0.255

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 (54) hide show
  1. package/dist/lib/customs-packing-weight.d.ts +7 -8
  2. package/dist/lib/customs-packing-weight.d.ts.map +1 -1
  3. package/dist/lib/customs-packing-weight.js +4 -7
  4. package/dist/lib/customs-packing-weight.js.map +1 -1
  5. package/dist/lib/document-pricing.d.ts +1 -2
  6. package/dist/lib/document-pricing.d.ts.map +1 -1
  7. package/dist/lib/document-pricing.js +1 -4
  8. package/dist/lib/document-pricing.js.map +1 -1
  9. package/dist/lib/invoice/dynamic-render.d.ts +1 -0
  10. package/dist/lib/invoice/dynamic-render.d.ts.map +1 -1
  11. package/dist/lib/invoice/dynamic-render.js +38 -19
  12. package/dist/lib/invoice/dynamic-render.js.map +1 -1
  13. package/dist/lib/invoice/values.js +1 -1
  14. package/dist/lib/invoice/values.js.map +1 -1
  15. package/dist/lib/invoice-formatting.d.ts +3 -0
  16. package/dist/lib/invoice-formatting.d.ts.map +1 -1
  17. package/dist/lib/invoice-formatting.js +24 -1
  18. package/dist/lib/invoice-formatting.js.map +1 -1
  19. package/dist/lib/packing/packing-document-weights.d.ts +1 -2
  20. package/dist/lib/packing/packing-document-weights.d.ts.map +1 -1
  21. package/dist/lib/packing/packing-document-weights.js +8 -52
  22. package/dist/lib/packing/packing-document-weights.js.map +1 -1
  23. package/dist/lib/packing/packing-layout.js +2 -2
  24. package/dist/lib/packing/packing-layout.js.map +1 -1
  25. package/dist/lib/packing/packing-render.d.ts.map +1 -1
  26. package/dist/lib/packing/packing-render.js +13 -9
  27. package/dist/lib/packing/packing-render.js.map +1 -1
  28. package/dist/lib/packing/supplier-packing.service.js +4 -4
  29. package/dist/lib/packing/supplier-packing.service.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-ui/app-source.js +1 -1
  33. package/dist/lib/remote-ui/app-source.js.map +1 -1
  34. package/dist/lib/remote-ui/components/generation-progress.js +2 -2
  35. package/dist/lib/remote-ui/components/generation-progress.js.map +1 -1
  36. package/dist/lib/remote-ui/components/packing-generation-actions.js +1 -1
  37. package/dist/lib/remote-ui/components/packing-generation-actions.js.map +1 -1
  38. package/dist/lib/remote-ui/pages/procurement-contracts.css +0 -5
  39. package/dist/lib/remote-ui/pages/procurement.d.ts.map +1 -1
  40. package/dist/lib/remote-ui/pages/procurement.js +9 -9
  41. package/dist/lib/remote-ui/pages/procurement.js.map +1 -1
  42. package/dist/lib/remote-ui/pages/sales.js +1 -1
  43. package/dist/lib/remote-ui/pages/sales.js.map +1 -1
  44. package/dist/lib/sales-batch-workbook.d.ts +17 -0
  45. package/dist/lib/sales-batch-workbook.d.ts.map +1 -0
  46. package/dist/lib/sales-batch-workbook.js +96 -0
  47. package/dist/lib/sales-batch-workbook.js.map +1 -0
  48. package/dist/lib/sales-file.service.d.ts +1 -1
  49. package/dist/lib/sales-file.service.d.ts.map +1 -1
  50. package/dist/lib/sales-file.service.js +62 -30
  51. package/dist/lib/sales-file.service.js.map +1 -1
  52. package/dist/lib/workbench-view.provider.js +1 -1
  53. package/dist/lib/workbench-view.provider.js.map +1 -1
  54. package/package.json +1 -1
@@ -1,9 +1,10 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
- import { applyDynamicInvoiceLayout } from './invoice/dynamic-render.js';
2
+ import { combineSalesWorkbooks, CUSTOMS_MISC_FEE_RATE } from './sales-batch-workbook.js';
3
+ import { applyDynamicInvoiceLayout, DYNAMIC_INVOICE_LAYOUT_VERSION } from './invoice/dynamic-render.js';
3
4
  import { mergeInvoiceLayouts } from './invoice/source-layout.js';
4
5
  import { InvoiceLayoutAnalysisProvider } from './adapters/invoice-layout-analysis.provider.js';
5
6
  import { invoicePaymentTerms } from './invoice-payment-terms.js';
6
- import { balanceDocumentPricing, documentUnitPriceFormat } from './document-pricing.js';
7
+ import { balanceDocumentPricing, DOCUMENT_UNIT_PRICE_FORMAT } from './document-pricing.js';
7
8
  import { compactExportLayout } from './compact-export-layout.js';
8
9
  import { refreshPackingTotalsPagination } from './packing/packing-full-text.js';
9
10
  import { PackingWeightAnalysisProvider } from './adapters/packing-weight-analysis.provider.js';
@@ -31,7 +32,7 @@ import { aggregatePackingBatches } from './packing/packing-render.js';
31
32
  import { PACKING_IMPORT_ACTIVE_STATUSES } from './packing/packing-import-task.contract.js';
32
33
  import { completePackingRows } from './packing/packing-complete-rows.js';
33
34
  import { shipmentDerived, markReview } from './packing/shipment-documents.js';
34
- import { formatInvoiceSheet, removeInvoiceExchangeRateColumn } from './invoice-formatting.js';
35
+ import { styleInvoiceGrid, formatInvoiceSheet, removeInvoiceExchangeRateColumn } from './invoice-formatting.js';
35
36
  import { formatCustomsSheet } from './customs-formatting.js';
36
37
  import { stylePackingSheet, expandPackingTextRows } from './packing/packing-layout.js';
37
38
  import * as yauzl from 'yauzl';
@@ -54,7 +55,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
54
55
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
55
56
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
56
57
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
57
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-18.dynamic-invoice.payment-conditions.product-aware-weights';
58
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-18.invoice-grid-customs-misc-fee';
58
59
  const PACKING_LAYOUT_VERSION = 'v22-boom-marker';
59
60
  const COMPANY_LOGO_PLACEMENTS = {
60
61
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -199,10 +200,12 @@ let SalesFileService = class SalesFileService {
199
200
  });
200
201
  if (fileType === 'CUSTOMS_DECLARATION')
201
202
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
202
- const request = { currencyCode: documentPricing.currencyCode, ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION, shipmentDocumentsVersion: 'v2', orderDataFingerprint: fileType === 'PI' ? commercialOrderDataFingerprint : orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: PACKING_LAYOUT_VERSION } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
203
- const snapshot = { ...((fileType === 'PI' || fileType === 'CI') && invoiceLayout ? { invoiceLayout } : {}), ...(fileType === 'CUSTOMS_DECLARATION' ? { customsWeightSource: { type: 'SUPPLIER_PACKING', packingIds: packing?.batchIds ?? [], grossWeightKg: packing?.totals.grossKg ?? null, netWeightKg: customsWeights.totalNetWeightKg, method: 'PL_GROSS_80_PERCENT', ratio: 0.8, byLine: customsWeights.byLine } } : {}), customsScope: fileType === 'CUSTOMS_DECLARATION' ? materialData.customsScope : null, customsSourceCities, customsCoverage: fileCustomsCoverage, materials: fileType === 'CUSTOMS_DECLARATION' ? materialData.sources.map(source => source.documentType === 'CUSTOMS_INFO' ? { ...source, fields: source.fields.filter(field => field !== 'netWeightKg' || customsWeights.byLine[source.purchaseOrderLineId]?.source === 'REVIEWED_SHARED_ITEM_NET') } : source) : materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing: fileDocumentPricing, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: filePurchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: fileDerived.lines.filter((line) => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
203
+ const dynamicInvoice = (fileType === 'PI' || fileType === 'CI') && invoiceLayout;
204
+ const request = { currencyCode: documentPricing.currencyCode, ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION, shipmentDocumentsVersion: 'v2', orderDataFingerprint: fileType === 'PI' ? commercialOrderDataFingerprint : orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(dynamicInvoice ? { dynamicInvoiceLayoutVersion: DYNAMIC_INVOICE_LAYOUT_VERSION } : {}), ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: PACKING_LAYOUT_VERSION } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
205
+ const snapshot = { ...((fileType === 'PI' || fileType === 'CI') && invoiceLayout ? { invoiceLayout } : {}), ...(fileType === 'CUSTOMS_DECLARATION' ? { piTotalAmount: documentPricing.orderAmount, customsWeightSource: { type: 'SUPPLIER_PACKING', packingIds: packing?.batchIds ?? [], grossWeightKg: packing?.totals.grossKg ?? null, netWeightKg: customsWeights.totalNetWeightKg, method: 'PL_GROSS_80_PERCENT', ratio: 0.8, byLine: customsWeights.byLine } } : {}), customsScope: fileType === 'CUSTOMS_DECLARATION' ? materialData.customsScope : null, customsSourceCities, customsCoverage: fileCustomsCoverage, materials: fileType === 'CUSTOMS_DECLARATION' ? materialData.sources.map(source => source.documentType === 'CUSTOMS_INFO' ? { ...source, fields: source.fields.filter(field => field !== 'netWeightKg' || customsWeights.byLine[source.purchaseOrderLineId]?.source === 'REVIEWED_SHARED_ITEM_NET') } : source) : materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing: fileDocumentPricing, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: filePurchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: fileDerived.lines.filter((line) => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
206
+ const sheetSources = { itemNetByProduct: {} };
204
207
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
205
- const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, customsCoverage: fileCustomsCoverage, generationWarnings: fileWarnings }, logo);
208
+ const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, customsCoverage: fileCustomsCoverage, generationWarnings: fileWarnings, sheetSources }, logo);
206
209
  await validateWorkbook(buffer);
207
210
  const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
208
211
  const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
@@ -210,7 +213,7 @@ let SalesFileService = class SalesFileService {
210
213
  await hooks?.progress('SAVING', initialExisting.size + created.length);
211
214
  const storageFileId = await this.fileStorage.save(scope, buffer, fileName, context);
212
215
  newStorageFileIds.push(storageFileId);
213
- created.push(stagingRepo.create({ tenantId: scope.tenantId, organizationId: scope.organizationId, createdById: scope.userId ?? null, updatedById: scope.userId ?? null, deletedAt: null, deletedById: null, deleteOperation: null, customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, salesOrderNoSnapshot: derived.salesOrderNo, fileType, documentNo, fileName, storageFileId, templateVersion, templateChecksum: checksum, generationSnapshotVersion: 'v1', generationSnapshot: snapshot, mergedOrderRefs, generationWarnings: fileWarnings, pricingProfitRate: derived.effectivePricingProfitRate, complianceProfitRate: compliance.complianceProfitRate.toString(), exchangeCost: exchangeCost?.toString() ?? null, profitRuleSnapshot: { ...rule }, bankType: bank?.bankType ?? null, bankSnapshot: bank ? { ...bank } : null, generatedById: scope.userId ?? null, generatedAt, lastEditedById: null, lastEditedAt: null }));
216
+ created.push(stagingRepo.create({ tenantId: scope.tenantId, organizationId: scope.organizationId, createdById: scope.userId ?? null, updatedById: scope.userId ?? null, deletedAt: null, deletedById: null, deleteOperation: null, customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, salesOrderNoSnapshot: derived.salesOrderNo, fileType, documentNo, fileName, storageFileId, templateVersion, templateChecksum: checksum, generationSnapshotVersion: 'v1', generationSnapshot: { ...snapshot, sheetSources }, mergedOrderRefs, generationWarnings: fileWarnings, pricingProfitRate: derived.effectivePricingProfitRate, complianceProfitRate: compliance.complianceProfitRate.toString(), exchangeCost: exchangeCost?.toString() ?? null, profitRuleSnapshot: { ...rule }, bankType: bank?.bankType ?? null, bankSnapshot: bank ? { ...bank } : null, generatedById: scope.userId ?? null, generatedAt, lastEditedById: null, lastEditedAt: null }));
214
217
  await hooks?.progress('RENDERING', initialExisting.size + created.length);
215
218
  }
216
219
  const files = await this.dataSource.transaction(async (manager) => {
@@ -475,19 +478,23 @@ let SalesFileService = class SalesFileService {
475
478
  if (current.storageFileId !== item.storageFileId || current.editVersion !== item.editVersion || current.fileName !== item.fileName)
476
479
  throw new DomainError(DomainErrorCodes.SALES_FILE_EDIT_CONFLICT, '销售文件已变化,请重新下载');
477
480
  }
478
- const zip = new JSZip();
479
- snapshots.forEach(({ item, buffer }, index) => {
480
- const name = item.fileName.split(/[\\/]/).pop().replace(/[\x00-\x1f\x7f]/g, '_').slice(0, 200) || 'sales-file.xlsx';
481
- zip.file(`${index + 1}-${name}`, buffer);
482
- });
481
+ if (snapshots.length === 1)
482
+ return { fileName: snapshots[0].item.fileName, buffer: snapshots[0].buffer };
483
483
  const first = snapshots[0].item;
484
484
  const request = first.generationSnapshot?.request;
485
485
  const prefix = typeof request?.fileNumber === 'string' ? request.fileNumber : first.salesOrderNoSnapshot || 'sales-files';
486
486
  const currency = request?.currencyCode === 'USD' ? 'USD' : request?.currencyCode === 'CNY' ? 'CNY' : '';
487
- const sameBatch = snapshots.every(({ item }) => { const other = item.generationSnapshot?.request; return other?.fileNumber === request?.fileNumber && other?.currencyCode === request?.currencyCode && String(item.generatedAt) === String(first.generatedAt); });
487
+ const sameBatch = snapshots.every(({ item }) => {
488
+ const other = item.generationSnapshot?.request;
489
+ if (request?.batchGenerationId)
490
+ return request.batchGenerationId === other?.batchGenerationId;
491
+ return item.customerContractId === first.customerContractId && item.purchaseOrderId === first.purchaseOrderId &&
492
+ other?.ordersKey === request?.ordersKey && other?.fileNumber === request?.fileNumber &&
493
+ other?.currencyCode === request?.currencyCode && String(item.generatedAt) === String(first.generatedAt);
494
+ });
488
495
  const stamp = first.generatedAt && Number.isFinite(new Date(first.generatedAt).getTime()) ? beijingFileTimestamp(new Date(first.generatedAt)) : first.id.slice(0, 8);
489
- const fileName = [sameBatch ? prefix : 'sales-files-multiple-batches', sameBatch ? currency : '', stamp].filter(Boolean).join('-').replace(/[\\/\x00-\x1f\x7f]/g, '_').slice(0, 180) + '.zip';
490
- return { fileName, buffer: await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' }) };
496
+ const fileName = [sameBatch ? prefix : 'sales-files-multiple-batches', sameBatch ? currency : '', stamp].filter(Boolean).join('-').replace(/[\\/\x00-\x1f\x7f]/g, '_').slice(0, 180) + '.xlsx';
497
+ return { fileName, buffer: await combineSalesWorkbooks(snapshots, sameBatch) };
491
498
  }
492
499
  async saveEditedWorkbook(scope, id, buffer, expected, context) {
493
500
  const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
@@ -780,10 +787,13 @@ function workbookDocumentPricing(data) {
780
787
  const ids = data.derived.lines.map((line) => line.purchaseOrderLineId);
781
788
  if (byId.size !== pricing.lines.length || new Set(ids).size !== ids.length || ids.length !== pricing.lines.length || ids.some(id => !byId.has(id)))
782
789
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '商品与定价明细不一致,请重新生成整批文件');
783
- return { ...pricing, lines: ids.map(id => byId.get(id)) };
790
+ return { ...pricing, lines: ids.map(id => {
791
+ const line = byId.get(id);
792
+ return { ...line, unitPrice: line.unroundedUnitPrice ?? line.unitPrice };
793
+ }) };
784
794
  }
785
795
  // Older rendering callers and saved snapshots are denominated in CNY.
786
- return { currencyCode: 'CNY', orderAmount: data.derived.orderAmountCny, lines: data.derived.lines.map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, purchaseOrderId: '', exchangeRateMonth: null, usdToCnyRate: null, unitPrice: line.salesUnitPriceCny, lineAmount: line.salesLineAmountCny })) };
796
+ return { currencyCode: 'CNY', orderAmount: data.derived.orderAmountCny, lines: data.derived.lines.map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, purchaseOrderId: '', exchangeRateMonth: null, usdToCnyRate: null, unitPrice: line.salesUnitPriceCnyExact ?? line.salesUnitPriceCny, lineAmount: line.salesLineAmountCny })) };
787
797
  }
788
798
  function generationRequestMatches(item, expected) {
789
799
  const request = item.generationSnapshot?.request;
@@ -798,6 +808,7 @@ function generationRequestMatches(item, expected) {
798
808
  typeof request === 'object' &&
799
809
  !Array.isArray(request) &&
800
810
  request.exportIntegrityVersion === SALES_EXPORT_INTEGRITY_VERSION &&
811
+ (!item.generationSnapshot?.invoiceLayout || request.dynamicInvoiceLayoutVersion === DYNAMIC_INVOICE_LAYOUT_VERSION) &&
801
812
  request.currencyCode === expected.currencyCode &&
802
813
  request.fileNumber === expected.fileNumber &&
803
814
  request.templateVersion === expected.templateVersion &&
@@ -862,7 +873,7 @@ function fillInvoiceSheet(sheet, type, data) {
862
873
  const productLabel = englishProduct;
863
874
  [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);
864
875
  safeMerge(sheet, `G${row}:H${row}`);
865
- sheet.getCell(`E${row}`).numFmt = documentUnitPriceFormat(pricing.lines[index].unitPrice);
876
+ sheet.getCell(`E${row}`).numFmt = DOCUMENT_UNIT_PRICE_FORMAT;
866
877
  sheet.getCell(`I${row}`).numFmt = '0.00';
867
878
  if (pricing.lines[index].exchangeRateMonth)
868
879
  sheet.getCell(`G${row}`).note = `${pricing.lines[index].exchangeRateMonth}: 1 USD = ${pricing.lines[index].usdToCnyRate} CNY`;
@@ -889,8 +900,10 @@ function fillInvoiceSheet(sheet, type, data) {
889
900
  fillIntermediaryChannelBankRows(sheet, { labelEnd: 'B', valueStart: 'C', valueEnd: 'J', lastColumn: 10 }, bankStart, type, bank, derived, translated, company);
890
901
  }
891
902
  export async function renderSalesWorkbook(type, data, logo) {
892
- if (type === 'CUSTOMS_DECLARATION')
893
- data = scopeCustomsDocument(data);
903
+ if (type === 'CUSTOMS_DECLARATION') {
904
+ const piTotalAmount = data.snapshot?.piTotalAmount ?? data.snapshot?.documentPricing?.orderAmount ?? data.derived.orderAmountCny;
905
+ data = { ...scopeCustomsDocument(data), piTotalAmount };
906
+ }
894
907
  data = { ...data, derived: shipmentDerived(data.derived, data.packing, type) };
895
908
  const workbook = new ExcelJS.Workbook();
896
909
  await workbook.xlsx.load(await templateBuffer(type));
@@ -979,7 +992,15 @@ export async function renderSalesWorkbook(type, data, logo) {
979
992
  if (type === 'PL')
980
993
  for (const packingSheet of [sheet, workbook.getWorksheet('Packaging Details')].filter((value) => Boolean(value))) {
981
994
  const rows = expandPackingTextRows(packingSheet);
982
- addPackingPiModelColumn(packingSheet, completePackingRows(data).map((row, index) => ({ row: rows.get(index + 12) ?? index + 12, endRow: (rows.get(index + 13) ?? index + 13) - 1, model: row.piModel ?? '' })));
995
+ const packingRows = completePackingRows(data);
996
+ addPackingPiModelColumn(packingSheet, packingRows.map((row, index) => ({ row: rows.get(index + 12) ?? index + 12, endRow: (rows.get(index + 13) ?? index + 13) - 1, model: row.piModel ?? '' })));
997
+ if (packingSheet === sheet && data.sheetSources)
998
+ packingRows.forEach((row, index) => {
999
+ const cell = sheet.getCell(rows.get(index + 12) ?? index + 12, 12);
1000
+ if (row.purchaseOrderLineId && typeof cell.value === 'number' && cell.master.address === cell.address) {
1001
+ (data.sheetSources.itemNetByProduct[row.purchaseOrderLineId] ??= []).push(cell.address);
1002
+ }
1003
+ });
983
1004
  for (const target of Object.values(fieldLocations)) {
984
1005
  const [name, address] = target.location.split('!');
985
1006
  const match = /^([A-Z]+)(\d+)$/.exec(address ?? '');
@@ -1001,6 +1022,8 @@ export async function renderSalesWorkbook(type, data, logo) {
1001
1022
  if (logo)
1002
1023
  addCompanyLogo(type, workbook, sheet, logo);
1003
1024
  }
1025
+ if ((type === 'PI' || type === 'CI') && sheet === templateSheet)
1026
+ styleInvoiceGrid(sheet, 11, data.derived.lines.length, 8, new Set([1, 4]));
1004
1027
  clearExportReviewColors(sheet, type);
1005
1028
  return removeExportComments(Buffer.from(await workbook.xlsx.writeBuffer()));
1006
1029
  }
@@ -1211,15 +1234,15 @@ function fillPackingPhysicalRows(sheet, rows, data) {
1211
1234
  }
1212
1235
  const itemSource = source.find(member => member.id === row.sourceLineId && packingPhysicalKey(member) === row.packageKey);
1213
1236
  const weight = itemSource && row.purchaseOrderLineId ? documentWeights.byAllocation[packingWeightAllocationKey(itemSource, row.purchaseOrderLineId)] : undefined;
1214
- const balanced = weight ?? (!repeated && row.packageKey ? documentWeights.byGroup[row.packageKey] : !row.packageKey && row.purchaseOrderLineId ? documentWeights.byLine[row.purchaseOrderLineId] : undefined);
1215
- if (balanced && typeof sheet.getCell(excelRow, 12).value === 'number') {
1237
+ const exactWeight = weight ?? (!repeated && row.packageKey ? documentWeights.byGroup[row.packageKey] : !row.packageKey && row.purchaseOrderLineId ? documentWeights.byLine[row.purchaseOrderLineId] : undefined);
1238
+ if (exactWeight && typeof sheet.getCell(excelRow, 12).value === 'number') {
1216
1239
  const allocation = itemSource?.allocations?.find(a => a.purchaseOrderLineId === row.purchaseOrderLineId);
1217
1240
  const count = Number(allocation?.cartons) > 0 ? Number(allocation.cartons) : Number(row.metrics?.cartons);
1218
- sheet.getCell(excelRow, 12).value = balanced.grossKg;
1219
- sheet.getCell(excelRow, 11).value = balanced.netKg;
1241
+ sheet.getCell(excelRow, 12).value = exactWeight.grossKg;
1242
+ sheet.getCell(excelRow, 11).value = exactWeight.netKg;
1220
1243
  if (count > 0) {
1221
- sheet.getCell(excelRow, 6).value = new Decimal(balanced.grossKg).div(count).toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
1222
- sheet.getCell(excelRow, 10).value = new Decimal(balanced.netKg).div(count).toDecimalPlaces(2, Decimal.ROUND_HALF_UP).toNumber();
1244
+ sheet.getCell(excelRow, 6).value = new Decimal(exactWeight.grossKg).div(count).toNumber();
1245
+ sheet.getCell(excelRow, 10).value = new Decimal(exactWeight.netKg).div(count).toNumber();
1223
1246
  }
1224
1247
  }
1225
1248
  if (conflict || !completeScope) {
@@ -1472,7 +1495,13 @@ function fillCustomsSheet(sheet, data) {
1472
1495
  markReview(sheet.getCell('A9'), 'FFFFE0B2');
1473
1496
  set(sheet, 'G9', '待确认');
1474
1497
  set(sheet, 'I9', '待确认');
1475
- set(sheet, 'K9', '待确认');
1498
+ const piTotal = data.piTotalAmount;
1499
+ if (piTotal != null && String(piTotal).trim() && Number.isFinite(Number(piTotal))) {
1500
+ set(sheet, 'K9', new Decimal(piTotal).mul(CUSTOMS_MISC_FEE_RATE).toNumber());
1501
+ sheet.getCell('K9').numFmt = '0.00';
1502
+ }
1503
+ else
1504
+ set(sheet, 'K9', null);
1476
1505
  for (let index = 0; index < derived.lines.length; index += 1) {
1477
1506
  const row = 14 + index * 2;
1478
1507
  for (let col = 2; col <= 10; col++)
@@ -1515,6 +1544,9 @@ function fillCustomsSheet(sheet, data) {
1515
1544
  set(sheet, `D${row + offset}`, entry.quantity);
1516
1545
  set(sheet, `E${row + offset}`, entry.unit);
1517
1546
  sheet.getCell(`D${row + offset}`).numFmt = kgUnit(entry.unit) ? '0.00' : 'General';
1547
+ if (data.sheetSources && kgUnit(entry.unit) && typeof entry.quantity === 'number') {
1548
+ (data.sheetSources.itemNetByProduct[product.id] ??= []).push(`D${row + offset}`);
1549
+ }
1518
1550
  if (entry.review)
1519
1551
  markReview(sheet.getCell(`D${row + offset}`));
1520
1552
  if (weights.byLine[product.id]?.estimated && /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(entry.unit) && entry.quantity != null)
@@ -1523,7 +1555,7 @@ function fillCustomsSheet(sheet, data) {
1523
1555
  for (const warning of data.generationWarnings ?? [])
1524
1556
  if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
1525
1557
  markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
1526
- const priceFormat = documentUnitPriceFormat(pricing.lines[index].unitPrice);
1558
+ const priceFormat = DOCUMENT_UNIT_PRICE_FORMAT;
1527
1559
  sheet.getCell(`F${priceRow}`).numFmt = priceFormat;
1528
1560
  sheet.getCell(`G${priceRow}`).numFmt = '0.00';
1529
1561
  }