@chenchaolong/plugin-trade-compliance-workbench 1.0.249 → 1.0.250

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,7 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
2
  import { balanceDocumentPricing, documentUnitPriceFormat } from './document-pricing.js';
3
+ import { PackingWeightAnalysisProvider } from './adapters/packing-weight-analysis.provider.js';
4
+ import { withCategoryWeightEstimates } from './packing/packing-product-weight.js';
3
5
  import { clearExportReviewColors } from './export-formatting.js';
4
6
  import { resolvePackingItemWeights } from './packing/packing-item-weights.js';
5
7
  import { customsDocumentWeights as customsPackingWeights } from './customs-packing-weight.js';
@@ -46,7 +48,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
46
48
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
47
49
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
48
50
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
49
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-17.precise-rmb-pricing-v2';
51
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-17.precise-rmb-v2.product-aware-weights';
50
52
  const PACKING_LAYOUT_VERSION = 'v21';
51
53
  const COMPANY_LOGO_PLACEMENTS = {
52
54
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -54,12 +56,13 @@ const COMPANY_LOGO_PLACEMENTS = {
54
56
  PL: { tl: { col: 0, row: 0.05 }, br: { col: 0.9999, row: 1.9999 } }
55
57
  };
56
58
  let SalesFileService = class SalesFileService {
57
- constructor(dataSource, workbench, storage, translator, packingService, workspaceFiles) {
59
+ constructor(dataSource, workbench, storage, translator, packingService, workspaceFiles, weightAnalyzer) {
58
60
  this.dataSource = dataSource;
59
61
  this.workbench = workbench;
60
62
  this.storage = storage;
61
63
  this.translator = translator;
62
64
  this.packingService = packingService;
65
+ this.weightAnalyzer = weightAnalyzer;
63
66
  this.fileStorage = new SalesFileStorage(storage, workspaceFiles);
64
67
  }
65
68
  async preflight(scope, input) {
@@ -67,7 +70,8 @@ let SalesFileService = class SalesFileService {
67
70
  const evaluated = await this.evaluate(scope, input);
68
71
  const packing = await this.packingStatusForOrders(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId]);
69
72
  const needsPacking = ['CI', 'PL', 'PI_CI_PL', 'ALL', 'CUSTOMS_DECLARATION'].includes(input.fileType);
70
- const packingData = needsPacking ? await this.loadPackingData(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId], input) : null;
73
+ const rawPacking = needsPacking ? await this.loadPackingData(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId], input) : null;
74
+ const packingData = this.weightAnalyzer ? await this.weightAnalyzer.analyze(rawPacking, evaluated.purchaseLines, scope.organizationId) : withCategoryWeightEstimates(rawPacking, evaluated.purchaseLines);
71
75
  const result = preflightResult(input, evaluated.compliance.complianceProfitRate.toString(), evaluated.exchangeCost?.toString() ?? null, evaluated.warnings, packing);
72
76
  const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
73
77
  const materialData = generationMaterials(evaluated.purchaseLines, materialDocs);
@@ -114,7 +118,8 @@ let SalesFileService = class SalesFileService {
114
118
  const bankType = input.bankType ?? null;
115
119
  const needsPacking = input.fileType !== 'PI';
116
120
  const purchaseIds = derived.purchaseOrderIds?.length ? derived.purchaseOrderIds : [purchaseOrder.id];
117
- const packing = needsPacking ? await this.loadPackingData(scope, purchaseIds, input) : null;
121
+ const rawPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input) : null;
122
+ const packing = (this.weightAnalyzer ? await this.weightAnalyzer.analyze(rawPacking, purchaseLines, scope.organizationId) : withCategoryWeightEstimates(rawPacking, purchaseLines)) ?? null;
118
123
  if (needsPacking && !packing?.shipmentOnly)
119
124
  generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
120
125
  const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
@@ -139,7 +144,8 @@ let SalesFileService = class SalesFileService {
139
144
  if (packing)
140
145
  generationWarnings.push(...this.packingWarningsForPl(derived, packing));
141
146
  const mergedOrderRefs = orders.length > 1 ? orders.map(order => ({ customerContractId: order.customerContractId, purchaseOrderId: order.purchaseOrderId, salesOrderNo: order.salesOrderNo })) : null;
142
- const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint, materialData, exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION })).digest('hex');
147
+ const commercialOrderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint, materialData, exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION })).digest('hex');
148
+ const orderDataFingerprint = packing?.weightEstimates && Object.keys(packing.weightEstimates).length ? createHash('sha256').update(JSON.stringify({ commercialOrderDataFingerprint, packingWeightAnalysis: packing.weightEstimates })).digest('hex') : commercialOrderDataFingerprint;
143
149
  const shipmentReference = `SHIP-${createHash('sha256').update(`${ordersKey}:${packing?.fingerprint ?? ''}:${orderDataFingerprint}`).digest('hex').slice(0, 16)}`;
144
150
  const batchGenerationId = input.fileType === 'ALL' ? randomUUID() : undefined;
145
151
  const newStorageFileIds = [];
@@ -148,7 +154,7 @@ let SalesFileService = class SalesFileService {
148
154
  const repo = source.getRepository(GeneratedSalesFile);
149
155
  const candidates = ['PI_CI_PL', 'ALL'].includes(input.fileType) ? await repo.find({ where: { ...scoped(scope), customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, fileType: In(requestedTypes), deletedAt: IsNull() }, order: { generatedAt: 'DESC' }, ...(lock ? { lock: { mode: 'pessimistic_write' } } : {}) }) : [];
150
156
  // Local-only historical results must not keep a new workspace generation pinned to a missing container file.
151
- const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: item.fileType === 'CUSTOMS_DECLARATION' && materialData.customsScope ? materialData.customsScope.purchaseOrderLineIds : derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey, currencyCode: documentPricing.currencyCode }));
157
+ const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: item.fileType === 'CUSTOMS_DECLARATION' && materialData.customsScope ? materialData.customsScope.purchaseOrderLineIds : derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint: item.fileType === 'PI' ? commercialOrderDataFingerprint : orderDataFingerprint, ordersKey, currencyCode: documentPricing.currencyCode }));
152
158
  const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
153
159
  return new Map(existing.map(item => [item.fileType, item]));
154
160
  };
@@ -184,7 +190,7 @@ let SalesFileService = class SalesFileService {
184
190
  });
185
191
  if (fileType === 'CUSTOMS_DECLARATION')
186
192
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
187
- 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 };
193
+ 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 };
188
194
  const snapshot = { ...(fileType === 'CUSTOMS_DECLARATION' ? { customsWeightSource: { type: 'SUPPLIER_PACKING', packingIds: packing?.batchIds ?? [], grossWeightKg: packing?.totals.grossKg ?? null, netWeightKg: customsWeights.totalNetWeightKg, method: 'PL_GROSS_80_PERCENT', ratio: 0.8, byLine: customsWeights.byLine } } : {}), customsScope: fileType === 'CUSTOMS_DECLARATION' ? materialData.customsScope : null, customsSourceCities, customsCoverage: fileCustomsCoverage, materials: fileType === 'CUSTOMS_DECLARATION' ? materialData.sources.map(source => source.documentType === 'CUSTOMS_INFO' ? { ...source, fields: source.fields.filter(field => field !== 'netWeightKg' || customsWeights.byLine[source.purchaseOrderLineId]?.source === 'REVIEWED_SHARED_ITEM_NET') } : source) : materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing: fileDocumentPricing, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: filePurchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: fileDerived.lines.filter((line) => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
189
195
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
190
196
  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);
@@ -655,12 +661,14 @@ SalesFileService = __decorate([
655
661
  __param(0, InjectDataSource()),
656
662
  __param(4, Optional()),
657
663
  __param(5, Optional()),
664
+ __param(6, Optional()),
658
665
  __metadata("design:paramtypes", [DataSource,
659
666
  TradeComplianceWorkbenchService,
660
667
  TradeComplianceFileStorage,
661
668
  TranslationProvider,
662
669
  SupplierPackingService,
663
- TradeComplianceWorkspaceFiles])
670
+ TradeComplianceWorkspaceFiles,
671
+ PackingWeightAnalysisProvider])
664
672
  ], SalesFileService);
665
673
  export { SalesFileService };
666
674
  function materialSelectionFingerprint(documents) {