@chenchaolong/plugin-trade-compliance-workbench 1.0.259 → 1.0.261

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/invoice/source-layout.d.ts +8 -0
  2. package/dist/lib/invoice/source-layout.d.ts.map +1 -1
  3. package/dist/lib/invoice/source-layout.js +63 -11
  4. package/dist/lib/invoice/source-layout.js.map +1 -1
  5. package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
  6. package/dist/lib/remote-components/trade-compliance-workbench/app.js +4 -4
  7. package/dist/lib/remote-ui/app-source.js +3 -3
  8. package/dist/lib/remote-ui/app-source.js.map +1 -1
  9. package/dist/lib/remote-ui/components/layout.d.ts +6 -1
  10. package/dist/lib/remote-ui/components/layout.d.ts.map +1 -1
  11. package/dist/lib/remote-ui/components/layout.js +4 -1
  12. package/dist/lib/remote-ui/components/layout.js.map +1 -1
  13. package/dist/lib/remote-ui/components/supplier-materials.css +6 -0
  14. package/dist/lib/remote-ui/components/supplier-materials.d.ts +3 -1
  15. package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -1
  16. package/dist/lib/remote-ui/components/supplier-materials.js +34 -7
  17. package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -1
  18. package/dist/lib/remote-ui/customer-contract-contracts.d.ts +2 -0
  19. package/dist/lib/remote-ui/customer-contract-contracts.d.ts.map +1 -1
  20. package/dist/lib/remote-ui/customer-contract-contracts.js.map +1 -1
  21. package/dist/lib/remote-ui/pages/contracts.css +17 -4
  22. package/dist/lib/remote-ui/pages/contracts.d.ts +4 -0
  23. package/dist/lib/remote-ui/pages/contracts.d.ts.map +1 -1
  24. package/dist/lib/remote-ui/pages/contracts.js +3 -1
  25. package/dist/lib/remote-ui/pages/contracts.js.map +1 -1
  26. package/dist/lib/remote-ui/pages/sales.d.ts +2 -0
  27. package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
  28. package/dist/lib/remote-ui/pages/sales.js +1 -1
  29. package/dist/lib/remote-ui/pages/sales.js.map +1 -1
  30. package/dist/lib/sales-file.service.d.ts +1 -1
  31. package/dist/lib/sales-file.service.d.ts.map +1 -1
  32. package/dist/lib/sales-file.service.js +74 -33
  33. package/dist/lib/sales-file.service.js.map +1 -1
  34. package/dist/lib/supplier-materials/english-shipment.d.ts +20 -0
  35. package/dist/lib/supplier-materials/english-shipment.d.ts.map +1 -0
  36. package/dist/lib/supplier-materials/english-shipment.js +80 -0
  37. package/dist/lib/supplier-materials/english-shipment.js.map +1 -0
  38. package/dist/lib/supplier-materials/generation-materials.d.ts +3 -1
  39. package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
  40. package/dist/lib/supplier-materials/generation-materials.js +5 -5
  41. package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
  42. package/dist/lib/supplier-materials/supplier-materials.d.ts +1 -1
  43. package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
  44. package/dist/lib/supplier-materials/supplier-materials.js +6 -3
  45. package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
  46. package/dist/lib/types.d.ts +1 -0
  47. package/dist/lib/types.d.ts.map +1 -1
  48. package/dist/lib/workbench-view.provider.js +1 -1
  49. package/dist/lib/workbench-view.provider.js.map +1 -1
  50. package/dist/lib/workbench.service.d.ts +3 -1
  51. package/dist/lib/workbench.service.d.ts.map +1 -1
  52. package/dist/lib/workbench.service.js +2 -2
  53. package/dist/lib/workbench.service.js.map +1 -1
  54. package/package.json +1 -1
@@ -20,6 +20,7 @@ import { recoverPurchaseSourceCities, extractCityName } from './import-jobs/purc
20
20
  import { assertSalesGenerationSources } from './sales-file-generation-lifecycle.js';
21
21
  import { generationMaterials } from './supplier-materials/generation-materials.js';
22
22
  import { purchasePriceEvidenceWarning } from './domain/purchase-price-evidence.js';
23
+ import { englishShipment, shipmentPackingDifferences } from './supplier-materials/english-shipment.js';
23
24
  import { recoverPurchasePriceEvidence } from './import-jobs/purchase-price-evidence-recovery.js';
24
25
  import { Injectable, Optional } from '@nestjs/common';
25
26
  import { InjectDataSource } from '@nestjs/typeorm';
@@ -56,7 +57,7 @@ export const MAX_EDITED_WORKBOOK_BYTES = 20 * 1024 * 1024;
56
57
  export const MAX_EDITED_WORKBOOK_ZIP_ENTRIES = 2048;
57
58
  export const MAX_EDITED_WORKBOOK_ZIP_UNCOMPRESSED_BYTES = 100 * 1024 * 1024;
58
59
  export const OLD_SALES_FILE_CLEANUP_DELAY_MS = 30_000;
59
- export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-18.customs-form-borders';
60
+ export const SALES_EXPORT_INTEGRITY_VERSION = '2026-11-23.customs-commercial-units';
60
61
  const PACKING_LAYOUT_VERSION = 'v22-boom-marker';
61
62
  const COMPANY_LOGO_PLACEMENTS = {
62
63
  PI: { tl: { col: 0, row: 0.02925 }, br: { col: 2, row: 0.999996875 } },
@@ -82,8 +83,9 @@ let SalesFileService = class SalesFileService {
82
83
  const rawPacking = needsPacking ? await this.loadPackingData(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId], input) : null;
83
84
  const packingData = this.weightAnalyzer ? await this.weightAnalyzer.analyze(rawPacking, evaluated.purchaseLines, scope.organizationId) : withCategoryWeightEstimates(rawPacking, evaluated.purchaseLines);
84
85
  const result = preflightResult(input, evaluated.compliance.complianceProfitRate.toString(), evaluated.exchangeCost?.toString() ?? null, evaluated.warnings, packing);
85
- const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
86
- const materialData = generationMaterials(evaluated.purchaseLines, materialDocs);
86
+ validateEnglishShipmentPacking(evaluated.shipment, packingData);
87
+ const materialDocs = evaluated.materialDocuments;
88
+ const materialData = generationMaterials(evaluated.purchaseLines, materialDocs, Boolean(evaluated.shipment));
87
89
  const customsWeights = customsPackingWeights(packingData, materialData.customsLines.filter(line => !materialData.customsScope || materialData.customsScope.purchaseOrderLineIds.includes(line.id)));
88
90
  if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType))
89
91
  result.customsCoverage = { ...materialData.customsDocumentCoverage, sourceNetWeightKg: null, acceptedNetWeightKg: customsWeights.totalNetWeightKg == null ? null : String(customsWeights.totalNetWeightKg) };
@@ -97,7 +99,7 @@ let SalesFileService = class SalesFileService {
97
99
  if (['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType) && isPlaceholderCustomerName(evaluated.customer.name))
98
100
  result.materialWarnings = [...(result.materialWarnings ?? []), { code: 'CUSTOMS_CUSTOMER_PLACEHOLDER_MISSING', message: '收货人名称为占位内容,报关单保留原值并标色,请核对真实名称。' }];
99
101
  result.documentPricing = input.fileType === 'CUSTOMS_DECLARATION' ? scopeCustomsDocument({ derived: evaluated.derived, purchaseLines: materialData.customsLines, customsScope: materialData.customsScope, snapshot: { documentPricing: evaluated.documentPricing } }).snapshot.documentPricing : evaluated.documentPricing;
100
- result.packingWarnings = packingData?.warnings ?? [];
102
+ result.packingWarnings = applicablePackingWarnings(packingData, Boolean(evaluated.shipment));
101
103
  result.packingMode = input.packingMode ?? 'DRAFT';
102
104
  if (needsPacking && this.packingService)
103
105
  result.packingBatches = (await this.packingService.listPackingBatches(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId])).filter(batch => input.packingIds == null || input.packingIds.includes(batch.id));
@@ -130,12 +132,13 @@ let SalesFileService = class SalesFileService {
130
132
  const purchaseIds = derived.purchaseOrderIds?.length ? derived.purchaseOrderIds : [purchaseOrder.id];
131
133
  const rawPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input) : null;
132
134
  const packing = (this.weightAnalyzer ? await this.weightAnalyzer.analyze(rawPacking, purchaseLines, scope.organizationId) : withCategoryWeightEstimates(rawPacking, purchaseLines)) ?? null;
135
+ const { shipment, materialDocuments } = evaluated;
136
+ validateEnglishShipmentPacking(shipment, packing);
133
137
  if (needsPacking && !packing?.shipmentOnly)
134
- generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
135
- const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
136
- const materialData = generationMaterials(purchaseLines, materialDocuments);
138
+ generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: `尚无已选定的装箱数据,商品数量按${shipment ? '本批英文 PI' : '订单'}生成,请核对实际包装信息。` });
139
+ const materialData = generationMaterials(purchaseLines, materialDocuments, Boolean(shipment));
137
140
  const contact = buyerContactFromInvoices(evaluated.customer, materialDocuments.flatMap(doc => doc.buyerContacts ?? []));
138
- const customer = { ...evaluated.customer, address: contact.address, phone: contact.phone };
141
+ const customer = { ...evaluated.customer, address: contact.address, phone: contact.phone, contactName: contact.contactName };
139
142
  generationWarnings.push(...buyerContactWarnings(input.fileType, contact));
140
143
  const sourceInvoiceLayout = mergeInvoiceLayouts(materialDocuments.filter(doc => doc.documentType === 'ENGLISH_QUOTATION' && doc.rows.some(row => row.reviewed && row.purchaseOrderLineId)).map(doc => 'invoiceLayout' in doc ? doc.invoiceLayout : undefined));
141
144
  const invoiceLayout = requestedTypes.some(type => type === 'PI' || type === 'CI') ? this.invoiceLayoutAnalyzer ? await this.invoiceLayoutAnalyzer.analyze(sourceInvoiceLayout, scope.organizationId) : sourceInvoiceLayout : undefined;
@@ -157,7 +160,7 @@ let SalesFileService = class SalesFileService {
157
160
  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)));
158
161
  const packingTranslated = translated;
159
162
  if (packing)
160
- generationWarnings.push(...this.packingWarningsForPl(derived, packing));
163
+ generationWarnings.push(...this.packingWarningsForPl(derived, packing, Boolean(shipment)));
161
164
  const mergedOrderRefs = orders.length > 1 ? orders.map(order => ({ customerContractId: order.customerContractId, purchaseOrderId: order.purchaseOrderId, salesOrderNo: order.salesOrderNo })) : null;
162
165
  const commercialOrderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint, materialData, invoiceLayout, exportIntegrityVersion: SALES_EXPORT_INTEGRITY_VERSION })).digest('hex');
163
166
  const orderDataFingerprint = packing?.weightEstimates && Object.keys(packing.weightEstimates).length ? createHash('sha256').update(JSON.stringify({ commercialOrderDataFingerprint, packingWeightAnalysis: packing.weightEstimates })).digest('hex') : commercialOrderDataFingerprint;
@@ -207,7 +210,7 @@ let SalesFileService = class SalesFileService {
207
210
  fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述采用报关资料申报要素,数量及单位按第一、第二法定单位列示;黄色空缺字段请核对补全,本文件尚未提交海关。' });
208
211
  const dynamicInvoice = (fileType === 'PI' || fileType === 'CI') && invoiceLayout;
209
212
  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 };
210
- 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, ...(Object.keys(contact.sources).length ? { buyerContactSources: contact.sources } : {}), 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 } };
213
+ 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, ...(Object.keys(contact.sources).length ? { buyerContactSources: contact.sources } : {}), 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, ...(shipment ? { basis: 'ENGLISH_PI', documentId: shipment.documentId, sourceFileName: shipment.sourceFileName } : {}), 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 } };
211
214
  const sheetSources = { itemNetByProduct: {} };
212
215
  const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
213
216
  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);
@@ -228,17 +231,16 @@ let SalesFileService = class SalesFileService {
228
231
  await assertSalesGenerationSources(manager, scope, input);
229
232
  if (['PI_CI_PL', 'ALL'].includes(input.fileType))
230
233
  await manager.getRepository(PurchaseOrder).findOne({ where: { ...scoped(scope), id: purchaseOrder.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } });
231
- const currentMaterials = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds, manager) ?? [];
232
- if (materialSelectionFingerprint(currentMaterials) !== materialsFingerprint)
233
- throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商资料已变化,请重新生成文件');
234
234
  const currentPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input, manager) : null;
235
235
  if ((currentPacking?.fingerprint ?? '') !== (packing?.fingerprint ?? ''))
236
236
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '装箱数据已变化,请重新生成文件');
237
- for (const warning of currentPacking?.warnings ?? [])
237
+ for (const warning of applicablePackingWarnings(currentPacking, Boolean(shipment)))
238
238
  for (const file of created)
239
239
  if (!file.generationWarnings?.some(existing => existing.code === warning.code && existing.message === warning.message))
240
240
  file.generationWarnings = [...(file.generationWarnings ?? []), warning];
241
241
  const current = await this.evaluate(scope, input, manager);
242
+ if (materialSelectionFingerprint(current.materialDocuments) !== materialsFingerprint)
243
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商资料已变化,请重新生成文件');
242
244
  const currentCompany = await manager.getRepository(CompanySettings).findOne({ where: scoped(scope), lock: { mode: 'pessimistic_read' } });
243
245
  const currentClauses = await manager.getRepository(CustomerContractClause).find({ where: { ...scoped(scope), customerContractId: customerContract.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_read' } });
244
246
  if (generationSourceFingerprint(current, currentCompany, currentClauses) !== evaluatedFingerprint)
@@ -322,8 +324,15 @@ let SalesFileService = class SalesFileService {
322
324
  if (sourcePurchaseLines.length !== lineIds.length || purchaseLinesById.size !== sourcePurchaseLines.length || new Set(lineIds).size !== lineIds.length || lineIds.some(id => !purchaseLinesById.has(id))) {
323
325
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '销售商品与采购商品明细不一致,请刷新后重试');
324
326
  }
325
- // All downstream arrays share the final sales order, including translations and snapshots.
326
- const purchaseLines = await recoverPurchasePriceEvidence(lineIds.map(id => purchaseLinesById.get(id)), purchaseOrderEntities, id => this.storage.read(id));
327
+ const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds, manager, input.shipmentMaterialId) ?? [];
328
+ const shipment = englishShipment(materialDocuments, sourcePurchaseLines, input.shipmentMaterialId);
329
+ const shipmentLineIds = shipment ? [...shipment.quantities.keys()] : lineIds;
330
+ const pricedPurchases = await recoverPurchasePriceEvidence(shipmentLineIds.map(id => purchaseLinesById.get(id)), purchaseOrderEntities, id => this.storage.read(id));
331
+ const purchaseLines = shipment ? pricedPurchases.map(line => {
332
+ const quantity = shipment.quantities.get(line.id);
333
+ return quantity === line.quantity ? line : { ...line, quantity,
334
+ lineAmountTaxIncluded: new Decimal(line.lineAmountTaxIncluded).mul(quantity).div(line.quantity).toString() };
335
+ }) : pricedPurchases;
327
336
  const rule = await source.getRepository(ProfitRuleSettings).findOne({ where: scoped(scope), ...(manager ? { lock: { mode: 'pessimistic_read' } } : {}) });
328
337
  if (!rule)
329
338
  throw new DomainError(DomainErrorCodes.PROFIT_RULE_UNCONFIGURED, '利润率规则未配置');
@@ -351,9 +360,19 @@ let SalesFileService = class SalesFileService {
351
360
  const examples = unpricedLines.slice(0, 3).map(line => `第${line.lineNumber}行「${line.productName}」${line.missingFields.length ? `缺少${line.missingFields.map(field => labels[field] ?? field).join('、')}` : '定价数据无效'}`).join(';');
352
361
  throw new SalesFileEvaluationError(DomainErrorCodes.SALES_PRICING_REQUIRED, `销售商品存在未完成定价:${examples}${unpricedLines.length > 3 ? `等${unpricedLines.length}项` : ''}。维护订单利润率后,仍需补齐这些商品的采购数量、采购价格及税率,或维护商品销售定价。`, { lines: unpricedLines }, null, null, []);
353
362
  }
363
+ if (shipment)
364
+ for (const line of purchaseLines) {
365
+ const pricing = derivedLines.get(line.id);
366
+ if (new Decimal(pricing.quantity).eq(line.quantity))
367
+ continue;
368
+ const shippedAmount = pricing.pricingSource !== 'MANUAL_AMOUNT' && pricing.salesUnitPriceCnyExact != null
369
+ ? new Decimal(pricing.salesUnitPriceCnyExact).mul(line.quantity)
370
+ : new Decimal(pricing.salesLineAmountCnyExact ?? pricing.salesLineAmountCny).mul(line.quantity).div(pricing.quantity);
371
+ derivedLines.set(line.id, { ...pricing, quantity: line.quantity, salesLineAmountCnyExact: shippedAmount.toString(), salesLineAmountCny: shippedAmount.toFixed(2) });
372
+ }
354
373
  const complianceInputs = purchaseLines.map(line => {
355
374
  const rates = validateTaxRates(line, { purchaseOrderLineId: line.id, lineNumber: line.lineNumber, productName: line.productName });
356
- return { purchaseAmountTaxInclusiveCny: line.lineAmountTaxIncluded, salesAmountCny: derivedLines.get(line.id)?.salesLineAmountCny ?? 0, ...rates };
375
+ return { purchaseAmountTaxInclusiveCny: line.lineAmountTaxIncluded, salesAmountCny: (shipment ? derivedLines.get(line.id)?.salesLineAmountCnyExact : null) ?? derivedLines.get(line.id)?.salesLineAmountCny ?? 0, ...rates };
357
376
  });
358
377
  const compliance = summarizeCompliance(complianceInputs);
359
378
  const orderedDerivedLines = purchaseLines.map(line => derivedLines.get(line.id) ?? { purchaseOrderLineId: line.id, productName: line.productName });
@@ -456,10 +475,10 @@ let SalesFileService = class SalesFileService {
456
475
  ...primary.derived,
457
476
  purchaseOrderIds: purchaseIds,
458
477
  orderDate: earliestOrderDate,
459
- orderAmountCny: orders.reduce((sum, order) => sum.plus(order.orderAmountCny ?? 0), new Decimal(0)).toFixed(2),
460
- lines: orderEntries.flatMap(entry => entry.derived.lines)
478
+ orderAmountCny: shipment ? shipmentLineIds.reduce((sum, id) => sum.plus(derivedLines.get(id).salesLineAmountCnyExact ?? derivedLines.get(id).salesLineAmountCny ?? 0), new Decimal(0)).toFixed(2) : orders.reduce((sum, order) => sum.plus(order.orderAmountCny ?? 0), new Decimal(0)).toFixed(2),
479
+ lines: shipmentLineIds.map(id => derivedLines.get(id))
461
480
  };
462
- return { derived, customerContract, customer, purchaseOrder, purchaseOrderEntities, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing };
481
+ return { derived, customerContract, customer, purchaseOrder, purchaseOrderEntities, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing, shipment, materialDocuments };
463
482
  }
464
483
  async download(scope, id) {
465
484
  const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
@@ -668,12 +687,12 @@ let SalesFileService = class SalesFileService {
668
687
  return status.sort((a, b) => a.revision - b.revision || a.contractNo.localeCompare(b.contractNo));
669
688
  }
670
689
  /** PL 专属告警:装箱数据存在时的行缺失与净重提示。 */
671
- packingWarningsForPl(derived, packing) {
690
+ packingWarningsForPl(derived, packing, scopeFromEnglishPi) {
672
691
  const warnings = derived.lines
673
692
  .filter(line => !packing.byPurchaseLine[line.purchaseOrderLineId])
674
- .map(line => ({ code: 'PACKING_LINE_MISSING', purchaseOrderLineId: line.purchaseOrderLineId, productName: line.productName, message: `商品“${line.productName}”尚未匹配供应商装箱行;主表采用订单数量,请核对包装明细中的商品归属。` }));
693
+ .map(line => ({ code: 'PACKING_LINE_MISSING', purchaseOrderLineId: line.purchaseOrderLineId, productName: line.productName, message: `商品“${line.productName}”尚未匹配供应商装箱行;主表采用${scopeFromEnglishPi ? '英文 PI' : '订单'}数量,请核对包装明细中的商品归属。` }));
675
694
  warnings.push({ code: 'PACKING_NET_WEIGHT_SOURCE', message: 'PL 整票净重仅采用已确认完整来源;来源未提供的单箱或逐箱净重留空,不按毛重比例推算。' });
676
- warnings.push(...packing.warnings);
695
+ warnings.push(...applicablePackingWarnings(packing, scopeFromEnglishPi));
677
696
  return warnings;
678
697
  }
679
698
  };
@@ -700,18 +719,32 @@ function customsMissingItemWeights(lines, scope, weights) {
700
719
  .map(line => ({ code: 'CUSTOMS_ITEM_WEIGHT_MISSING', purchaseOrderLineId: line.id, field: `customs.${line.id}.netWeightKg`,
701
720
  message: `商品“${line.modelSpecification || line.productName}”法定单位包含千克,但没有可对应的商品净重,请核对装箱关联。` }));
702
721
  }
722
+ function applicablePackingWarnings(packing, scopeFromEnglishPi) {
723
+ return (packing?.warnings ?? []).filter(warning => !scopeFromEnglishPi || warning.code !== 'PACKING_QUANTITY_DIFFERENCE');
724
+ }
725
+ function validateEnglishShipmentPacking(shipment, packing) {
726
+ if (!shipment || !packing?.batchIds?.length)
727
+ return;
728
+ const differences = shipmentPackingDifferences(shipment, packing.byPurchaseLine);
729
+ for (const row of packing.sourceLines ?? [])
730
+ if (!['CONFIG', 'BOOM', 'PART', 'SLAVE', 'EXTRA'].includes(row.role ?? '') && !row.purchaseOrderLineId && !row.allocations?.length) {
731
+ differences.push(`装箱单第 ${(row.lineIndex ?? 0) + 1} 行 ${row.model || '商品'}(数量 ${row.qty ?? '未确认'})未关联采购明细`);
732
+ }
733
+ if (differences.length)
734
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, `英文 PI「${shipment.sourceFileName}」与所选装箱单数量不一致:${differences.join(';')}`, { differences });
735
+ }
703
736
  function buyerContactWarnings(fileType, contact) {
704
737
  if (fileType === 'CUSTOMS_DECLARATION')
705
738
  return [];
706
- return ['address', 'phone'].flatMap(field => contact[field] ? [] : [{
739
+ return ['address', 'phone', 'contactName'].flatMap(field => contact[field] ? [] : [{
707
740
  code: 'BUYER_CONTACT_MISSING', field: `customer.${field}`,
708
- message: `客户档案及本次可核验的英文资料未提供唯一的买方${field === 'address' ? '地址' : '电话'},文件留空。`
741
+ message: `客户档案及本次可核验的英文资料未提供唯一的买方${{ address: '地址', phone: '电话', contactName: '联系人' }[field]},文件留空。`
709
742
  }]);
710
743
  }
711
744
  function materialSelectionFingerprint(documents) {
712
745
  // Upload progress is not a change to the adopted generation facts. Approval,
713
746
  // binding, source revision and adoption state still invalidate a running batch.
714
- return createHash('sha256').update(JSON.stringify(documents.map(({ id, documentType, sourceFileName, revision, rows, sourceRows, adoption, buyerContacts }) => ({ id, documentType, sourceFileName, revision, rows, sourceRows, adoption, buyerContacts })))).digest('hex');
747
+ return createHash('sha256').update(JSON.stringify(documents.map(({ id, documentType, sourceFileName, revision, rows, sourceRows, shipmentRows, shipmentWarnings, adoption, buyerContacts }) => ({ id, documentType, sourceFileName, revision, rows, sourceRows, shipmentRows, shipmentWarnings, adoption, buyerContacts })))).digest('hex');
715
748
  }
716
749
  function editedWorkbookLimits() {
717
750
  return {
@@ -933,12 +966,13 @@ export async function renderSalesWorkbook(type, data, logo) {
933
966
  if (sheet.getImages().length !== 0)
934
967
  throw new DomainError(DomainErrorCodes.TEMPLATE_INVALID, '模板不应包含预置图片', { type });
935
968
  cleanBrokenFormulas(sheet);
969
+ let commercialUnitRows;
936
970
  if (type === 'PI' || type === 'CI')
937
971
  fillInvoiceSheet(sheet, type, data);
938
972
  else if (type === 'PL')
939
973
  fillPackingSheet(sheet, data);
940
974
  else
941
- fillCustomsSheet(sheet, data);
975
+ commercialUnitRows = fillCustomsSheet(sheet, data);
942
976
  normalizeDisplayValues(sheet);
943
977
  if (type !== 'CUSTOMS_DECLARATION')
944
978
  normalizeEnglishLabels(sheet);
@@ -1056,7 +1090,7 @@ export async function renderSalesWorkbook(type, data, logo) {
1056
1090
  if (type === 'CUSTOMS_DECLARATION') {
1057
1091
  for (let row = 14; row < 14 + data.derived.lines.length * 2; row++) {
1058
1092
  const unit = sheet.getCell(row, 5);
1059
- if (unit.value == null || !unit.text.trim()) {
1093
+ if (unit.value == null || !unit.text.trim() || commercialUnitRows?.has(row)) {
1060
1094
  unit.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFFE5A0' } };
1061
1095
  }
1062
1096
  }
@@ -1490,6 +1524,7 @@ export function remittanceInformation(cnapsCode, goodsName, derived, civilUse) {
1490
1524
  return parts.join(',');
1491
1525
  }
1492
1526
  function fillCustomsSheet(sheet, data) {
1527
+ const commercialUnitRows = new Set();
1493
1528
  const { customer, purchaseOrder, derived, company, packing } = data;
1494
1529
  const weights = customsPackingWeights(packing, data.purchaseLines);
1495
1530
  const purchaseLines = derived.lines.map((line, index) => {
@@ -1563,7 +1598,7 @@ function fillCustomsSheet(sheet, data) {
1563
1598
  const quantities = customsQuantityRows(product, derived.lines[index]);
1564
1599
  // Price belongs to the commercial quantity row, never the statutory kg row
1565
1600
  // merely because it is first in the declaration template.
1566
- const tradeRow = quantities.findIndex(entry => customsUnitsCompatible(product.unit, entry.unit));
1601
+ const tradeRow = quantities.findIndex(entry => entry.commercialUnit || customsUnitsCompatible(product.unit, entry.unit));
1567
1602
  // Missing statutory units stay blank; keep commercial prices off a kg row
1568
1603
  // when the sale itself is counted in pieces, even without a secondary unit.
1569
1604
  const kgUnit = (unit) => /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(String(unit ?? '').trim());
@@ -1578,11 +1613,13 @@ function fillCustomsSheet(sheet, data) {
1578
1613
  set(sheet, `H${priceRow}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
1579
1614
  for (const [offset, entry] of quantities.entries()) {
1580
1615
  set(sheet, `D${row + offset}`, entry.quantity);
1581
- set(sheet, `E${row + offset}`, entry.unit);
1616
+ set(sheet, `E${row + offset}`, entry.commercialUnit ?? entry.unit);
1582
1617
  sheet.getCell(`D${row + offset}`).numFmt = kgUnit(entry.unit) ? '0.00' : 'General';
1583
1618
  if (data.sheetSources && kgUnit(entry.unit) && typeof entry.quantity === 'number') {
1584
1619
  (data.sheetSources.itemNetByProduct[product.id] ??= []).push(`D${row + offset}`);
1585
1620
  }
1621
+ if (entry.commercialUnit)
1622
+ commercialUnitRows.add(row + offset);
1586
1623
  if (entry.review)
1587
1624
  markReview(sheet.getCell(`D${row + offset}`));
1588
1625
  if (weights.byLine[product.id]?.estimated && /^(?:千克|公斤|kg|kgs|kilograms?)$/i.test(entry.unit) && entry.quantity != null)
@@ -1598,6 +1635,7 @@ function fillCustomsSheet(sheet, data) {
1598
1635
  const tail = 14 + derived.lines.length * 2;
1599
1636
  normalizeCustomsConfirmationRow(sheet, tail);
1600
1637
  set(sheet, `B${tail + 3}`, companyText);
1638
+ return commercialUnitRows;
1601
1639
  }
1602
1640
  /** Quantity order follows explicit statutory units; trade quantity and sale pricing remain independent. */
1603
1641
  function customsUnitsCompatible(source, target) {
@@ -1624,8 +1662,11 @@ function customsQuantityRows(product, commercial) {
1624
1662
  const commercialQuantity = commercial.quantity;
1625
1663
  const validCount = commercialQuantity != null && String(commercialQuantity).trim() !== '' && Number.isFinite(Number(commercialQuantity)) && Number(commercialQuantity) >= 0;
1626
1664
  return units.map((unit, index) => {
1627
- if (!unit)
1628
- return { unit, quantity: index === missingCountRow && validCount ? Number(commercialQuantity) : null, review: false };
1665
+ if (!unit) {
1666
+ const hasCount = index === missingCountRow && validCount;
1667
+ const commercialUnit = hasCount && units.some(isKg) ? String(product.unit).trim() : undefined;
1668
+ return { unit, quantity: hasCount ? Number(commercialQuantity) : null, review: false, commercialUnit };
1669
+ }
1629
1670
  if (isKg(unit)) {
1630
1671
  const weight = product.netWeightKg;
1631
1672
  const valid = typeof weight === 'number' && Number.isFinite(weight) && weight >= 0;
@@ -1884,7 +1925,7 @@ function unitFallback(value) {
1884
1925
  const dictionary = { 台: 'pcs', 块: 'pcs', 个: 'pcs', 件: 'pcs', 只: 'pcs', 支: 'pcs', 套: 'set', 千克: 'kg', 公斤: 'kg', 米: 'm', PCS: 'PCS', pcs: 'pcs', SET: 'set', set: 'set' };
1885
1926
  return dictionary[value.trim()] ?? null;
1886
1927
  }
1887
- function generationSourceFingerprint(evaluated, company, clauses) {
1928
+ function generationSourceFingerprint({ materialDocuments: _materials, ...evaluated }, company, clauses) {
1888
1929
  return createHash('sha256').update(JSON.stringify({ evaluated, company, clauses })).digest('hex');
1889
1930
  }
1890
1931
  //# sourceMappingURL=sales-file.service.js.map