@chenchaolong/plugin-trade-compliance-workbench 1.0.211 → 1.0.212

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 (131) hide show
  1. package/dist/lib/analytics-query.d.ts.map +1 -1
  2. package/dist/lib/analytics-query.js +3 -1
  3. package/dist/lib/analytics-query.js.map +1 -1
  4. package/dist/lib/domain/purchase-pricing.d.ts +5 -0
  5. package/dist/lib/domain/purchase-pricing.d.ts.map +1 -0
  6. package/dist/lib/domain/purchase-pricing.js +27 -0
  7. package/dist/lib/domain/purchase-pricing.js.map +1 -0
  8. package/dist/lib/entities/index.d.ts +3 -1
  9. package/dist/lib/entities/index.d.ts.map +1 -1
  10. package/dist/lib/entities/index.js +3 -1
  11. package/dist/lib/entities/index.js.map +1 -1
  12. package/dist/lib/entities/procurement.entity.d.ts +2 -0
  13. package/dist/lib/entities/procurement.entity.d.ts.map +1 -1
  14. package/dist/lib/entities/procurement.entity.js +8 -0
  15. package/dist/lib/entities/procurement.entity.js.map +1 -1
  16. package/dist/lib/entities/sales-file-generation-task.entity.d.ts +23 -0
  17. package/dist/lib/entities/sales-file-generation-task.entity.d.ts.map +1 -0
  18. package/dist/lib/entities/sales-file-generation-task.entity.js +75 -0
  19. package/dist/lib/entities/sales-file-generation-task.entity.js.map +1 -0
  20. package/dist/lib/import-jobs/import-command.builder.js +2 -2
  21. package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
  22. package/dist/lib/import-jobs/purchase-spreadsheet-review.d.ts.map +1 -1
  23. package/dist/lib/import-jobs/purchase-spreadsheet-review.js +11 -3
  24. package/dist/lib/import-jobs/purchase-spreadsheet-review.js.map +1 -1
  25. package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts +15 -0
  26. package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
  27. package/dist/lib/import-jobs/spreadsheet-contract-facts.js +68 -2
  28. package/dist/lib/import-jobs/spreadsheet-contract-facts.js.map +1 -1
  29. package/dist/lib/packing/packing-spreadsheet.d.ts.map +1 -1
  30. package/dist/lib/packing/packing-spreadsheet.js +4 -0
  31. package/dist/lib/packing/packing-spreadsheet.js.map +1 -1
  32. package/dist/lib/packing/supplier-packing.service.d.ts +3 -0
  33. package/dist/lib/packing/supplier-packing.service.d.ts.map +1 -1
  34. package/dist/lib/packing/supplier-packing.service.js +57 -5
  35. package/dist/lib/packing/supplier-packing.service.js.map +1 -1
  36. package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
  37. package/dist/lib/remote-components/trade-compliance-workbench/app.js +11 -11
  38. package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +4 -2
  39. package/dist/lib/remote-components/trade-compliance-workbench/editor.js +1 -1
  40. package/dist/lib/remote-components/trade-compliance-workbench/preview-source.mjs +1 -1
  41. package/dist/lib/remote-components/trade-compliance-workbench/preview.js +1 -1
  42. package/dist/lib/remote-ui/action-execution.d.ts.map +1 -1
  43. package/dist/lib/remote-ui/action-execution.js +4 -0
  44. package/dist/lib/remote-ui/action-execution.js.map +1 -1
  45. package/dist/lib/remote-ui/app-source.d.ts.map +1 -1
  46. package/dist/lib/remote-ui/app-source.js +26 -5
  47. package/dist/lib/remote-ui/app-source.js.map +1 -1
  48. package/dist/lib/remote-ui/components/generation-task-panel.d.ts +7 -0
  49. package/dist/lib/remote-ui/components/generation-task-panel.d.ts.map +1 -0
  50. package/dist/lib/remote-ui/components/generation-task-panel.js +64 -0
  51. package/dist/lib/remote-ui/components/generation-task-panel.js.map +1 -0
  52. package/dist/lib/remote-ui/components/source-file-preview.d.ts +11 -1
  53. package/dist/lib/remote-ui/components/source-file-preview.d.ts.map +1 -1
  54. package/dist/lib/remote-ui/components/source-file-preview.js +36 -6
  55. package/dist/lib/remote-ui/components/source-file-preview.js.map +1 -1
  56. package/dist/lib/remote-ui/generation-tasks.d.ts +40 -0
  57. package/dist/lib/remote-ui/generation-tasks.d.ts.map +1 -0
  58. package/dist/lib/remote-ui/generation-tasks.js +28 -0
  59. package/dist/lib/remote-ui/generation-tasks.js.map +1 -0
  60. package/dist/lib/remote-ui/pages/analytics-dashboard.d.ts.map +1 -1
  61. package/dist/lib/remote-ui/pages/analytics-dashboard.js +1 -1
  62. package/dist/lib/remote-ui/pages/analytics-dashboard.js.map +1 -1
  63. package/dist/lib/remote-ui/pages/files.d.ts +1 -1
  64. package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
  65. package/dist/lib/remote-ui/pages/files.js +6 -12
  66. package/dist/lib/remote-ui/pages/files.js.map +1 -1
  67. package/dist/lib/remote-ui/pages/procurement-contracts.css +3 -0
  68. package/dist/lib/remote-ui/pages/procurement.d.ts +2 -0
  69. package/dist/lib/remote-ui/pages/procurement.d.ts.map +1 -1
  70. package/dist/lib/remote-ui/pages/procurement.js +62 -16
  71. package/dist/lib/remote-ui/pages/procurement.js.map +1 -1
  72. package/dist/lib/remote-ui/pages/sales.d.ts +3 -1
  73. package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
  74. package/dist/lib/remote-ui/pages/sales.js +27 -13
  75. package/dist/lib/remote-ui/pages/sales.js.map +1 -1
  76. package/dist/lib/remote-ui/procurement-contracts.d.ts +7 -0
  77. package/dist/lib/remote-ui/procurement-contracts.d.ts.map +1 -1
  78. package/dist/lib/remote-ui/procurement-contracts.js.map +1 -1
  79. package/dist/lib/remote-ui/purchase-review-adapter.d.ts.map +1 -1
  80. package/dist/lib/remote-ui/purchase-review-adapter.js +4 -3
  81. package/dist/lib/remote-ui/purchase-review-adapter.js.map +1 -1
  82. package/dist/lib/remote-ui/sales-contracts.d.ts +1 -1
  83. package/dist/lib/remote-ui/sales-contracts.d.ts.map +1 -1
  84. package/dist/lib/remote-ui/styles.css +6 -0
  85. package/dist/lib/sales-file-generation-lifecycle.d.ts +11 -0
  86. package/dist/lib/sales-file-generation-lifecycle.d.ts.map +1 -0
  87. package/dist/lib/sales-file-generation-lifecycle.js +42 -0
  88. package/dist/lib/sales-file-generation-lifecycle.js.map +1 -0
  89. package/dist/lib/sales-file-generation-task.d.ts +46 -0
  90. package/dist/lib/sales-file-generation-task.d.ts.map +1 -0
  91. package/dist/lib/sales-file-generation-task.js +207 -0
  92. package/dist/lib/sales-file-generation-task.js.map +1 -0
  93. package/dist/lib/sales-file.service.d.ts +15 -6
  94. package/dist/lib/sales-file.service.d.ts.map +1 -1
  95. package/dist/lib/sales-file.service.js +134 -82
  96. package/dist/lib/sales-file.service.js.map +1 -1
  97. package/dist/lib/schema-maintenance.d.ts +1 -0
  98. package/dist/lib/schema-maintenance.d.ts.map +1 -1
  99. package/dist/lib/schema-maintenance.js +28 -0
  100. package/dist/lib/schema-maintenance.js.map +1 -1
  101. package/dist/lib/supplier-materials/generation-materials.d.ts +1 -0
  102. package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
  103. package/dist/lib/supplier-materials/generation-materials.js +1 -1
  104. package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
  105. package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
  106. package/dist/lib/supplier-materials/supplier-materials.js +15 -2
  107. package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
  108. package/dist/lib/types.d.ts +28 -1
  109. package/dist/lib/types.d.ts.map +1 -1
  110. package/dist/lib/types.js.map +1 -1
  111. package/dist/lib/workbench-action-contract.d.ts +1 -1
  112. package/dist/lib/workbench-action-contract.d.ts.map +1 -1
  113. package/dist/lib/workbench-action-contract.js +4 -0
  114. package/dist/lib/workbench-action-contract.js.map +1 -1
  115. package/dist/lib/workbench-view.provider.d.ts +18 -13
  116. package/dist/lib/workbench-view.provider.d.ts.map +1 -1
  117. package/dist/lib/workbench-view.provider.js +32 -5
  118. package/dist/lib/workbench-view.provider.js.map +1 -1
  119. package/dist/lib/workbench.middleware.d.ts +78 -64
  120. package/dist/lib/workbench.middleware.d.ts.map +1 -1
  121. package/dist/lib/workbench.middleware.js +2 -0
  122. package/dist/lib/workbench.middleware.js.map +1 -1
  123. package/dist/lib/workbench.plugin.d.ts +3 -1
  124. package/dist/lib/workbench.plugin.d.ts.map +1 -1
  125. package/dist/lib/workbench.plugin.js +11 -5
  126. package/dist/lib/workbench.plugin.js.map +1 -1
  127. package/dist/lib/workbench.service.d.ts +8 -3
  128. package/dist/lib/workbench.service.d.ts.map +1 -1
  129. package/dist/lib/workbench.service.js +88 -23
  130. package/dist/lib/workbench.service.js.map +1 -1
  131. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { __decorate, __metadata, __param } from "tslib";
2
+ import { cancelSalesFileGenerationTasks } from './sales-file-generation-lifecycle.js';
2
3
  import { loadSupplierMaterials, listSupplierMaterials, mutateSupplierMaterial, validateMaterialTargets } from './supplier-materials/supplier-materials.js';
3
4
  import { contractResultRecoveryCommand, importTaskHandoffId } from './import-jobs/contract-result-recovery.js';
4
5
  import { Inject, Injectable, Optional } from '@nestjs/common';
@@ -12,7 +13,7 @@ import { tmpdir } from 'node:os';
12
13
  import { join } from 'node:path';
13
14
  import { finished } from 'node:stream/promises';
14
15
  import { createHash, randomUUID } from 'node:crypto';
15
- import { BankAccountSettings, CatalogReviewBlock, CompanySanctionMatch, CompanySettings, ControlledCatalogBatch, ControlledCatalogImportIssue, ControlledGoodsRecord, Customer, CustomerContract, CustomerContractAnalysisRun, CustomerContractClause, CustomerContractClauseAnalysis, DerivedSalesOrderManualData, GeneratedSalesFile, HsCodeReferenceSnapshot, ImportTask, ManagedAsset, MonthlySafeExchangeRate, ProductComplianceMatch, ProfitRuleSettings, PurchaseOrder, PurchaseOrderLine, SanctionCatalogBatch, SanctionCatalogImportIssue, SanctionedCompanyAlias, SanctionedCompanyRecord, SettingsHistory, Supplier, SupplierPacking, SupplierPackingLine } from './entities/index.js';
16
+ import { BankAccountSettings, CatalogReviewBlock, CompanySanctionMatch, CompanySettings, ControlledCatalogBatch, ControlledCatalogImportIssue, ControlledGoodsRecord, Customer, CustomerContract, CustomerContractAnalysisRun, CustomerContractClause, CustomerContractClauseAnalysis, DerivedSalesOrderManualData, GeneratedSalesFile, SalesFileGenerationTask, HsCodeReferenceSnapshot, ImportTask, ManagedAsset, MonthlySafeExchangeRate, ProductComplianceMatch, ProfitRuleSettings, PurchaseOrder, PurchaseOrderLine, SanctionCatalogBatch, SanctionCatalogImportIssue, SanctionedCompanyAlias, SanctionedCompanyRecord, SettingsHistory, Supplier, SupplierPacking, SupplierPackingLine } from './entities/index.js';
16
17
  import { CATALOG_REVIEW_BATCH_LIMIT, CATALOG_REVIEW_LEASE_MS, CATALOG_TRANSLATION_REVIEW_LEASE_MS } from './constants.js';
17
18
  import { CatalogTypes, ClauseTypes, CustomerProfitRateStatuses, DomainError, DomainErrorCodes, RefundValidationMethods, RiskLevels, SalesPaymentStatuses, SanctionHitStatuses, StalledCatalogImportDecisions } from './types.js';
18
19
  import { resolveSalesLineOrder } from './domain/sales-line-order.js';
@@ -37,6 +38,7 @@ import { PACKING_IMPORT_ACTIVE_STATUSES, packingImportTaskDto, packingImportTarg
37
38
  import { DemoDataSeedMarker } from './demo-data.entity.js';
38
39
  import { extractSpreadsheetContractFacts, applyCustomerSpreadsheetFacts } from './import-jobs/spreadsheet-contract-facts.js';
39
40
  import { preparePurchaseSpreadsheetDraft } from './import-jobs/purchase-spreadsheet-review.js';
41
+ import { normalizePurchaseLinePricing, purchaseAmountMismatch } from './domain/purchase-pricing.js';
40
42
  import { cleanPurchaseDraftPayload } from './domain/purchase-draft-cleanup.js';
41
43
  const DEFAULT_IMPORT_ISSUE_EXPORT_MAX_ROWS = 50_000;
42
44
  const HARD_IMPORT_ISSUE_EXPORT_MAX_ROWS = 100_000;
@@ -2773,7 +2775,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
2773
2775
  }
2774
2776
  async savePurchaseDraft(scope, importTaskId, draft) {
2775
2777
  await this.ensureProcurementSchema();
2776
- const normalizedDraft = normalizePurchaseDraftDates(cleanPurchaseDraftPayload(draft));
2778
+ const normalizedDraft = normalizePurchaseDraftDates(normalizePurchaseDraftMoney(cleanPurchaseDraftPayload(draft)));
2777
2779
  assertPurchaseDraft(normalizedDraft);
2778
2780
  const confirmedById = requiredId(scope.userId, '当前用户标识');
2779
2781
  const confirmedAt = new Date();
@@ -2794,7 +2796,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
2794
2796
  const lineRepo = manager.getRepository(PurchaseOrderLine);
2795
2797
  for (let index = 0; index < normalizedDraft.lines.length; index += 1) {
2796
2798
  const line = normalizedDraft.lines[index];
2797
- await lineRepo.save(lineRepo.create({ ...auditScope(scope), purchaseOrderId: entity.id, lineNumber: line.lineNumber ?? index + 1, sourceType: line.sourceType ?? 'CONTRACT_EXTRACTED', reviewStatus: 'REVIEWED', productName: line.productName.trim(), normalizedProductName: normalizeForProductMatch(line.productName), englishName: line.englishName ?? null, englishNameSource: line.englishNameSource ?? null, productDescription: line.productDescription ?? null, modelSpecification: line.modelSpecification ?? null, unit: line.unit ?? null, quantity: defaultDecimalText(line.quantity), unitPriceTaxIncluded: defaultDecimalText(line.unitPriceTaxIncluded), lineAmountTaxIncluded: purchaseLineAmountText(line), vatRate: optionalString(line.vatRate), vatRateSource: line.vatRateSource ?? null, hsCode: line.hsCode ?? null, hsCodeSource: line.hsCodeSource ?? null, hsCodeReferenceSnapshotId: line.hsCodeReferenceSnapshotId ?? null, originCountry: line.originCountry ?? null, domesticSourceLocation: line.domesticSourceLocation ?? null, refundRate: optionalString(line.refundRate), refundRateSource: line.refundRateSource ?? null, refundPolicyReference: line.refundPolicyReference ?? null, refundPolicyDate: optionalString(line.refundPolicyDate), refundValidationMethod: line.refundValidationMethod ?? null, refundConfirmedAt: confirmedAt, refundConfirmedById: confirmedById, amountMismatchConfirmedAt: line.amountMismatch === true ? confirmedAt : null, amountMismatchConfirmedById: line.amountMismatch === true ? confirmedById : null, sourceLocation: line.sourceLocation ?? null, sourceContent: line.sourceContent ?? null }));
2799
+ await lineRepo.save(lineRepo.create({ ...auditScope(scope), purchaseOrderId: entity.id, lineNumber: line.lineNumber ?? index + 1, sourceType: line.sourceType ?? 'CONTRACT_EXTRACTED', reviewStatus: 'REVIEWED', productName: line.productName.trim(), normalizedProductName: normalizeForProductMatch(line.productName), englishName: line.englishName ?? null, englishNameSource: line.englishNameSource ?? null, productDescription: line.productDescription ?? null, modelSpecification: line.modelSpecification ?? null, unit: line.unit ?? null, quantity: defaultDecimalText(line.quantity), unitPriceTaxIncluded: defaultDecimalText(line.unitPriceTaxIncluded), lineAmountTaxIncluded: purchaseLineAmountText(line), freeOfCharge: line.freeOfCharge === true, referenceUnitPriceTaxIncluded: optionalString(line.referenceUnitPriceTaxIncluded), vatRate: optionalString(line.vatRate), vatRateSource: line.vatRateSource ?? null, hsCode: line.hsCode ?? null, hsCodeSource: line.hsCodeSource ?? null, hsCodeReferenceSnapshotId: line.hsCodeReferenceSnapshotId ?? null, originCountry: line.originCountry ?? null, domesticSourceLocation: line.domesticSourceLocation ?? null, refundRate: optionalString(line.refundRate), refundRateSource: line.refundRateSource ?? null, refundPolicyReference: line.refundPolicyReference ?? null, refundPolicyDate: optionalString(line.refundPolicyDate), refundValidationMethod: line.refundValidationMethod ?? null, refundConfirmedAt: confirmedAt, refundConfirmedById: confirmedById, amountMismatchConfirmedAt: line.amountMismatch === true ? confirmedAt : null, amountMismatchConfirmedById: line.amountMismatch === true ? confirmedById : null, sourceLocation: line.sourceLocation ?? null, sourceContent: line.sourceContent ?? null }));
2798
2800
  }
2799
2801
  task.status = 'SUCCEEDED';
2800
2802
  task.resultEntityId = entity.id;
@@ -3023,13 +3025,14 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3023
3025
  await this.ensureProcurementSchema();
3024
3026
  validatePurchaseLineDiscriminators(input);
3025
3027
  const existing = await required(this.dataSource.getRepository(PurchaseOrderLine).findOne({ where: { ...activeScope(scope), id, deletedAt: IsNull() } }), '采购商品不存在');
3026
- const candidate = { ...existing, ...pick(input, ['productName', 'englishName', 'englishNameSource', 'productDescription', 'modelSpecification', 'unit', 'quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'vatRate', 'vatRateSource', 'hsCode', 'hsCodeSource', 'originCountry', 'domesticSourceLocation', 'refundRate', 'refundRateSource', 'refundPolicyReference', 'refundPolicyDate', 'refundValidationMethod']) };
3028
+ const candidate = { ...existing, ...pick(input, ['productName', 'englishName', 'englishNameSource', 'productDescription', 'modelSpecification', 'unit', 'quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'freeOfCharge', 'referenceUnitPriceTaxIncluded', 'vatRate', 'vatRateSource', 'hsCode', 'hsCodeSource', 'originCountry', 'domesticSourceLocation', 'refundRate', 'refundRateSource', 'refundPolicyReference', 'refundPolicyDate', 'refundValidationMethod']) };
3027
3029
  validatePurchaseTaxRates(candidate, { purchaseOrderLineId: existing.id, lineNumber: existing.lineNumber, productName: candidate.productName });
3028
3030
  if (new Decimal(candidate.quantity).lte(0))
3029
3031
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
3030
3032
  const saved = await this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
3031
3033
  const item = await required(Promise.resolve(lines.find(line => line.id === id) ?? null), '采购商品不存在');
3032
- Object.assign(item, pick(input, ['productName', 'englishName', 'englishNameSource', 'productDescription', 'modelSpecification', 'unit', 'quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'vatRate', 'vatRateSource', 'hsCode', 'hsCodeSource', 'originCountry', 'domesticSourceLocation', 'refundRate', 'refundRateSource', 'refundPolicyReference', 'refundPolicyDate', 'refundValidationMethod']));
3034
+ Object.assign(item, pick(input, ['productName', 'englishName', 'englishNameSource', 'productDescription', 'modelSpecification', 'unit', 'quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'freeOfCharge', 'referenceUnitPriceTaxIncluded', 'vatRate', 'vatRateSource', 'hsCode', 'hsCodeSource', 'originCountry', 'domesticSourceLocation', 'refundRate', 'refundRateSource', 'refundPolicyReference', 'refundPolicyDate', 'refundValidationMethod']));
3035
+ applyManualPurchasePricing(item, input, scope);
3033
3036
  item.lineAmountTaxIncluded = purchaseLineAmountText(item);
3034
3037
  validatePurchaseLineDiscriminators(item);
3035
3038
  const rates = validatePurchaseTaxRates(item, { purchaseOrderLineId: item.id, lineNumber: item.lineNumber, productName: item.productName });
@@ -3048,6 +3051,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3048
3051
  }
3049
3052
  async addPurchaseLine(scope, purchaseOrderId, input) {
3050
3053
  await this.ensureProcurementSchema();
3054
+ input = normalizePurchaseLinePricing({ ...input });
3051
3055
  validatePurchaseLineDiscriminators(input);
3052
3056
  const discriminators = validatePurchaseLineDiscriminators({ ...input, sourceType: 'MANUAL_ENTRY', vatRateSource: input.vatRateSource ?? 'MANUAL' });
3053
3057
  const rates = validatePurchaseTaxRates(input, { productName: input.productName });
@@ -3055,7 +3059,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3055
3059
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
3056
3060
  const saved = await this.withLockedPurchaseLines(scope, purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
3057
3061
  const lineNumber = lines.reduce((maximum, line) => Math.max(maximum, line.lineNumber), 0) + 1;
3058
- const item = lineRepo.create({ ...auditScope(scope), purchaseOrderId, lineNumber, sourceType: discriminators.sourceType ?? 'MANUAL_ENTRY', reviewStatus: 'PENDING', productName: input.productName.trim(), normalizedProductName: normalizeForProductMatch(input.productName), englishName: input.englishName ?? null, englishNameSource: discriminators.englishNameSource ?? null, productDescription: input.productDescription ?? null, modelSpecification: input.modelSpecification ?? null, unit: input.unit ?? null, quantity: input.quantity, unitPriceTaxIncluded: input.unitPriceTaxIncluded, lineAmountTaxIncluded: purchaseLineAmountText(input), vatRate: rates.vatRate, vatRateSource: discriminators.vatRateSource ?? 'MANUAL', hsCode: input.hsCode ?? null, hsCodeSource: discriminators.hsCodeSource ?? null, hsCodeReferenceSnapshotId: null, originCountry: input.originCountry ?? null, domesticSourceLocation: input.domesticSourceLocation ?? null, refundRate: rates.refundRate, refundRateSource: discriminators.refundRateSource ?? null, refundPolicyReference: input.refundPolicyReference ?? null, refundPolicyDate: input.refundPolicyDate ?? null, refundValidationMethod: discriminators.refundValidationMethod ?? null, refundConfirmedAt: null, refundConfirmedById: null, amountMismatchConfirmedAt: null, amountMismatchConfirmedById: null, sourceLocation: null, sourceContent: null });
3062
+ const item = lineRepo.create({ ...auditScope(scope), purchaseOrderId, lineNumber, sourceType: discriminators.sourceType ?? 'MANUAL_ENTRY', reviewStatus: 'PENDING', productName: input.productName.trim(), normalizedProductName: normalizeForProductMatch(input.productName), englishName: input.englishName ?? null, englishNameSource: discriminators.englishNameSource ?? null, productDescription: input.productDescription ?? null, modelSpecification: input.modelSpecification ?? null, unit: input.unit ?? null, quantity: input.quantity, unitPriceTaxIncluded: input.unitPriceTaxIncluded, lineAmountTaxIncluded: purchaseLineAmountText(input), freeOfCharge: input.freeOfCharge === true, referenceUnitPriceTaxIncluded: input.referenceUnitPriceTaxIncluded ?? null, vatRate: rates.vatRate, vatRateSource: discriminators.vatRateSource ?? 'MANUAL', hsCode: input.hsCode ?? null, hsCodeSource: discriminators.hsCodeSource ?? null, hsCodeReferenceSnapshotId: null, originCountry: input.originCountry ?? null, domesticSourceLocation: input.domesticSourceLocation ?? null, refundRate: rates.refundRate, refundRateSource: discriminators.refundRateSource ?? null, refundPolicyReference: input.refundPolicyReference ?? null, refundPolicyDate: input.refundPolicyDate ?? null, refundValidationMethod: discriminators.refundValidationMethod ?? null, refundConfirmedAt: null, refundConfirmedById: null, amountMismatchConfirmedAt: null, amountMismatchConfirmedById: null, sourceLocation: null, sourceContent: null });
3063
+ applyManualPurchasePricing(item, input, scope);
3059
3064
  this.assertLockedPurchaseReceipts([...lines, item], contracts, customers, manuals);
3060
3065
  return lineRepo.save(item);
3061
3066
  });
@@ -3142,7 +3147,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3142
3147
  * 客户级未收款总额(CNY):派生销售订单(客户合同组)各自 clamp 后汇总,超收不抵扣其他订单欠款。
3143
3148
  * 口径与销售订单列表、分析看板一致:订单总额 = 人工覆盖值或商品行汇总,未收款 = max(总额 - 已收款, 0)。
3144
3149
  */
3145
- async customerUnreceivedAmounts(scope, customerIds) {
3150
+ async customerUnreceivedAmounts(scope, customerIds, manager) {
3146
3151
  const map = new Map();
3147
3152
  const ids = [...new Set(customerIds)].filter(Boolean);
3148
3153
  if (!ids.length)
@@ -3181,7 +3186,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3181
3186
  SUM(GREATEST(sales_contract_totals."salesTotalCny" - sales_contract_totals."receivedCny", 0))::text AS "unreceivedCny"
3182
3187
  FROM sales_contract_totals
3183
3188
  GROUP BY sales_contract_totals."customerId"`;
3184
- const rows = await this.dataSource.query(sql, parameters);
3189
+ const rows = await (manager ?? this.dataSource).query(sql, parameters);
3185
3190
  for (const row of rows)
3186
3191
  if (row?.customerId)
3187
3192
  map.set(row.customerId, new Decimal(row.unreceivedCny ?? 0).toFixed(2));
@@ -3770,29 +3775,30 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3770
3775
  await this.recalculateCompanyRisks(scope, 'SOURCE_CHANGED');
3771
3776
  return saved;
3772
3777
  }
3773
- async listDerivedSalesOrders(scope, customerId, selectedIdentities) {
3774
- const identities = selectedIdentities ?? await this.selectAllDerivedSalesOrderIdentities(scope, customerId, {}, false);
3778
+ async listDerivedSalesOrders(scope, customerId, selectedIdentities, manager) {
3779
+ const source = manager ?? this.dataSource;
3780
+ const identities = selectedIdentities ?? await this.selectAllDerivedSalesOrderIdentities(scope, customerId, {}, false, manager);
3775
3781
  if (!identities.length)
3776
3782
  return [];
3777
3783
  const contractIds = [...new Set(identities.map(identity => identity.customerContractId))];
3778
3784
  const selectedContracts = new Set(identities.map(identity => identity.customerContractId));
3779
3785
  const [customers, contracts, purchases, lines] = await Promise.all([
3780
- this.dataSource.getRepository(Customer).find({ where: { ...activeScope(scope), ...(customerId ? { id: customerId } : {}), deletedAt: IsNull() } }),
3781
- this.dataSource.getRepository(CustomerContract).find({ where: { ...activeScope(scope), id: In(contractIds), ...(customerId ? { customerId } : {}), deletedAt: IsNull() } }),
3782
- this.dataSource.getRepository(PurchaseOrder).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { id: 'ASC' } }),
3783
- this.dataSource.getRepository(PurchaseOrderLine).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } })
3786
+ source.getRepository(Customer).find({ where: { ...activeScope(scope), ...(customerId ? { id: customerId } : {}), deletedAt: IsNull() } }),
3787
+ source.getRepository(CustomerContract).find({ where: { ...activeScope(scope), id: In(contractIds), ...(customerId ? { customerId } : {}), deletedAt: IsNull() } }),
3788
+ source.getRepository(PurchaseOrder).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { id: 'ASC' } }),
3789
+ source.getRepository(PurchaseOrderLine).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } })
3784
3790
  ]);
3785
3791
  const associatedPurchaseIds = purchases.filter(purchase => {
3786
3792
  const baseCode = parsePurchaseContractNo(purchase.contractNo).baseCode;
3787
3793
  return contracts.some(contract => selectedContracts.has(contract.id) && parseCustomerContractNo(contract.contractNo).baseCode === baseCode);
3788
3794
  }).map(purchase => purchase.id);
3789
- const manuals = associatedPurchaseIds.length ? await this.dataSource.getRepository(DerivedSalesOrderManualData).find({ where: { ...activeScope(scope), customerContractId: In(contractIds), purchaseOrderId: In(associatedPurchaseIds), deletedAt: IsNull() } }) : [];
3795
+ const manuals = associatedPurchaseIds.length ? await source.getRepository(DerivedSalesOrderManualData).find({ where: { ...activeScope(scope), customerContractId: In(contractIds), purchaseOrderId: In(associatedPurchaseIds), deletedAt: IsNull() } }) : [];
3790
3796
  const customerMap = new Map(customers.map(customer => [customer.id, customer]));
3791
3797
  const manualMap = new Map(manuals.map(manual => [derivedOrderKey(manual.customerContractId, manual.purchaseOrderId), manual]));
3792
3798
  const linesByPurchase = groupBy(lines, line => line.purchaseOrderId);
3793
- const riskRows = lines.length ? await this.dataSource.getRepository(ProductComplianceMatch).find({ where: { ...activeScope(scope), purchaseOrderLineId: In(lines.map(line => line.id)), deletedAt: IsNull() } }) : [];
3799
+ const riskRows = lines.length ? await source.getRepository(ProductComplianceMatch).find({ where: { ...activeScope(scope), purchaseOrderLineId: In(lines.map(line => line.id)), deletedAt: IsNull() } }) : [];
3794
3800
  const controlledGoodsIds = [...new Set(riskRows.map(match => match.controlledGoodsId))];
3795
- const controlledGoods = controlledGoodsIds.length ? await this.dataSource.getRepository(ControlledGoodsRecord).find({ where: { ...activeScope(scope), id: In(controlledGoodsIds), lifecycleStatus: 'ACTIVE', deletedAt: IsNull() } }) : [];
3801
+ const controlledGoods = controlledGoodsIds.length ? await source.getRepository(ControlledGoodsRecord).find({ where: { ...activeScope(scope), id: In(controlledGoodsIds), lifecycleStatus: 'ACTIVE', deletedAt: IsNull() } }) : [];
3796
3802
  const controlledGoodsById = new Map(controlledGoods.map(item => [item.id, item]));
3797
3803
  const risksByLine = groupBy(riskRows, match => match.purchaseOrderLineId);
3798
3804
  const purchasesByBaseCode = groupBy(purchases, purchase => parsePurchaseContractNo(purchase.contractNo).baseCode);
@@ -3872,8 +3878,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3872
3878
  }
3873
3879
  return [...grouped.values()].sort(compareDerivedSalesOrders);
3874
3880
  }
3875
- derivedSalesIdentityQuery(scope, customerId, parameters, includeParties) {
3876
- const qb = this.dataSource.getRepository(CustomerContract).createQueryBuilder('contract')
3881
+ derivedSalesIdentityQuery(scope, customerId, parameters, includeParties, manager) {
3882
+ const qb = (manager ?? this.dataSource).getRepository(CustomerContract).createQueryBuilder('contract')
3877
3883
  .innerJoin(Customer, 'customer', 'customer.id = contract."customerId" AND customer."tenantId" = contract."tenantId" AND customer."organizationId" = contract."organizationId" AND customer."deletedAt" IS NULL')
3878
3884
  .innerJoin(PurchaseOrder, 'purchase', `purchase."tenantId" = contract."tenantId" AND purchase."organizationId" = contract."organizationId" AND purchase."deletedAt" IS NULL AND ${derivedSalesContractLinkSql('contract', 'purchase')}`)
3879
3885
  .leftJoin(DerivedSalesOrderManualData, 'manual', 'manual."customerContractId" = contract.id AND manual."purchaseOrderId" = purchase.id AND manual."tenantId" = contract."tenantId" AND manual."organizationId" = contract."organizationId" AND manual."deletedAt" IS NULL')
@@ -3908,8 +3914,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
3908
3914
  qb.andWhere(`${received} >= ${amount}`);
3909
3915
  return qb;
3910
3916
  }
3911
- async selectAllDerivedSalesOrderIdentities(scope, customerId, parameters, includeParties) {
3912
- const rows = await this.derivedSalesIdentityQuery(scope, customerId, parameters, includeParties).orderBy('contract.id', 'ASC').addOrderBy('purchase.id', 'ASC').getRawMany();
3917
+ async selectAllDerivedSalesOrderIdentities(scope, customerId, parameters, includeParties, manager) {
3918
+ const rows = await this.derivedSalesIdentityQuery(scope, customerId, parameters, includeParties, manager).orderBy('contract.id', 'ASC').addOrderBy('purchase.id', 'ASC').getRawMany();
3913
3919
  const seen = new Set();
3914
3920
  return rows.filter(row => { if (seen.has(row.customerContractId))
3915
3921
  return false; seen.add(row.customerContractId); return true; });
@@ -4062,6 +4068,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
4062
4068
  if (entity === PurchaseOrderLine)
4063
4069
  return this.deletePurchaseLine(scope, id);
4064
4070
  const row = await this.dataSource.transaction(async (manager) => {
4071
+ if (entity === PurchaseOrder || entity === CustomerContract)
4072
+ await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
4065
4073
  if (entity === Customer) {
4066
4074
  const count = await manager.getRepository(CustomerContract).count({ where: { ...activeScope(scope), customerId: id, deletedAt: IsNull() } });
4067
4075
  if (count)
@@ -4075,6 +4083,10 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
4075
4083
  const repo = manager.getRepository(entity);
4076
4084
  const lifecycle = entity === ControlledGoodsRecord || entity === SanctionedCompanyRecord ? { lifecycleStatus: 'ACTIVE' } : {};
4077
4085
  const target = await required(repo.findOne({ where: { ...activeScope(scope), id, ...lifecycle, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } }), '记录不存在');
4086
+ if (entity === PurchaseOrder)
4087
+ await cancelSalesFileGenerationTasks(manager, scope, { purchaseOrderId: id });
4088
+ if (entity === CustomerContract)
4089
+ await cancelSalesFileGenerationTasks(manager, scope, { customerContractId: id });
4078
4090
  const now = new Date();
4079
4091
  target.deletedAt = now;
4080
4092
  target.deletedById = scope.userId ?? null;
@@ -4162,6 +4174,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
4162
4174
  await remove('customerContractAnalysisRun', CustomerContractAnalysisRun);
4163
4175
  await remove('customerContractClause', CustomerContractClause);
4164
4176
  await remove('derivedSalesOrderManualData', DerivedSalesOrderManualData);
4177
+ await remove('salesFileGenerationTask', SalesFileGenerationTask);
4165
4178
  await remove('generatedSalesFile', GeneratedSalesFile);
4166
4179
  await remove('customerContract', CustomerContract);
4167
4180
  await remove('customer', Customer);
@@ -4834,6 +4847,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
4834
4847
  }
4835
4848
  async withLockedPurchaseLines(scope, purchaseOrderId, callback) {
4836
4849
  return this.dataSource.transaction(async (manager) => {
4850
+ await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
4837
4851
  const purchaseRepo = manager.getRepository(PurchaseOrder);
4838
4852
  const preview = await required(purchaseRepo.findOne({ where: { ...activeScope(scope), id: purchaseOrderId, deletedAt: IsNull() } }), '采购订单不存在');
4839
4853
  const baseCode = parsePurchaseContractNo(preview.contractNo).baseCode;
@@ -4871,6 +4885,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
4871
4885
  return this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ manager, lineRepo, lines, contracts, customers, manuals }) => {
4872
4886
  const row = await required(Promise.resolve(lines.find(line => line.id === id) ?? null), '记录不存在');
4873
4887
  this.assertLockedPurchaseReceipts(lines.filter(line => line.id !== id), contracts, customers, manuals);
4888
+ await cancelSalesFileGenerationTasks(manager, scope, { purchaseOrderId: existing.purchaseOrderId });
4874
4889
  row.deletedAt = new Date();
4875
4890
  row.deletedById = scope.userId ?? null;
4876
4891
  row.deleteOperation = 'USER_DELETE';
@@ -5512,6 +5527,22 @@ async function required(promise, message) { const value = await promise; if (!va
5512
5527
  throw new DomainError(DomainErrorCodes.NOT_FOUND, message); return value; }
5513
5528
  function pick(input, keys) { return Object.fromEntries(keys.filter(key => key in input).map(key => [key, input[key]])); }
5514
5529
  function maxRisk(levels) { return levels.includes('HIGH') ? 'HIGH' : levels.includes('MEDIUM') ? 'MEDIUM' : levels.includes('LOW') ? 'LOW' : null; }
5530
+ function normalizePurchaseDraftMoney(draft) {
5531
+ const lines = draft.lines.map(line => {
5532
+ const normalized = normalizePurchaseLinePricing(line);
5533
+ return { ...normalized, amountMismatch: normalized.amountMismatch === true || purchaseAmountMismatch(normalized.quantity, normalized.unitPriceTaxIncluded, normalized.lineAmountTaxIncluded) };
5534
+ });
5535
+ const complete = lines.every(line => hasQueryValue(line.lineAmountTaxIncluded) || (hasQueryValue(line.quantity) && hasQueryValue(line.unitPriceTaxIncluded)));
5536
+ let mismatch = false;
5537
+ if (complete && hasQueryValue(draft.order.contractAmountCny)) {
5538
+ // Invalid decimals are reported by field validation below; they must not hide its precise message.
5539
+ try {
5540
+ mismatch = !new Decimal(draft.order.contractAmountCny).toDecimalPlaces(2).equals(lines.reduce((sum, line) => sum.plus(purchaseLineAmountText(line)), new Decimal(0)).toDecimalPlaces(2));
5541
+ }
5542
+ catch { }
5543
+ }
5544
+ return { ...draft, lines, order: { ...draft.order, amountMismatch: draft.order.amountMismatch === true || mismatch } };
5545
+ }
5515
5546
  function normalizePurchaseDraftDates(draft) {
5516
5547
  return {
5517
5548
  ...draft,
@@ -5529,7 +5560,7 @@ function normalizeOptionalDateString(value, label) {
5529
5560
  if (!hasQueryValue(value))
5530
5561
  return null;
5531
5562
  const text = String(value).trim();
5532
- const matched = text.match(/^(\d{4})\s*(?:[-/.年])\s*(\d{1,2})\s*(?:[-/.月])\s*(\d{1,2})\s*(?:日)?$/);
5563
+ const matched = text.match(/^(\d{4})(\d{2})(\d{2})$/) ?? text.match(/^(\d{4})\s*(?:[-/.年])\s*(\d{1,2})\s*(?:[-/.月])\s*(\d{1,2})\s*(?:日)?$/);
5533
5564
  if (!matched)
5534
5565
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${label}格式无效,请使用 YYYY-MM-DD`);
5535
5566
  const [, rawYear, rawMonth, rawDay] = matched;
@@ -5542,6 +5573,35 @@ function normalizeOptionalDateString(value, label) {
5542
5573
  }
5543
5574
  return `${rawYear}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
5544
5575
  }
5576
+ function applyManualPurchasePricing(item, input, scope) {
5577
+ const pricingChanged = ['quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'freeOfCharge', 'referenceUnitPriceTaxIncluded'].some(key => Object.prototype.hasOwnProperty.call(input, key));
5578
+ if (!pricingChanged)
5579
+ return;
5580
+ if (!Object.prototype.hasOwnProperty.call(input, 'lineAmountTaxIncluded') && (input.quantity !== undefined || input.unitPriceTaxIncluded !== undefined)) {
5581
+ item.lineAmountTaxIncluded = new Decimal(item.quantity).mul(item.unitPriceTaxIncluded).toFixed(2);
5582
+ }
5583
+ Object.assign(item, normalizePurchaseLinePricing({ ...item }));
5584
+ for (const key of ['unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'referenceUnitPriceTaxIncluded']) {
5585
+ if (!hasQueryValue(item[key]))
5586
+ continue;
5587
+ let value;
5588
+ try {
5589
+ value = new Decimal(String(item[key]));
5590
+ }
5591
+ catch {
5592
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品金额格式无效');
5593
+ }
5594
+ if (!value.isFinite() || value.lt(0))
5595
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品金额必须为非负数');
5596
+ }
5597
+ if (item.freeOfCharge != null && typeof item.freeOfCharge !== 'boolean')
5598
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, '赠品标记无效');
5599
+ const mismatch = purchaseAmountMismatch(item.quantity, item.unitPriceTaxIncluded, item.lineAmountTaxIncluded);
5600
+ if (mismatch && input.amountMismatchConfirmed !== true)
5601
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, '商品金额差异必须确认');
5602
+ item.amountMismatchConfirmedAt = mismatch ? new Date() : null;
5603
+ item.amountMismatchConfirmedById = mismatch ? scope.userId ?? null : null;
5604
+ }
5545
5605
  function assertPurchaseDraft(draft) {
5546
5606
  if (!hasQueryValue(draft.supplier?.name))
5547
5607
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商名称为必填项');
@@ -5578,6 +5638,11 @@ function assertPurchaseDraft(draft) {
5578
5638
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}退税政策日期不得晚于下单日期`);
5579
5639
  if (hasQueryValue(line.refundValidationMethod) && !RefundValidationMethods.some(method => method === line.refundValidationMethod))
5580
5640
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}退税校验方式无效`);
5641
+ if (line.freeOfCharge != null && typeof line.freeOfCharge !== 'boolean')
5642
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}免费标记必须为布尔值`);
5643
+ const referencePrice = optionalDecimalInput(line.referenceUnitPriceTaxIncluded, `${prefix}参考单价必须为有效金额`);
5644
+ if (referencePrice?.isNegative())
5645
+ throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}参考单价不能为负数`);
5581
5646
  validatePurchaseLineDiscriminators({ ...line, sourceType: line.sourceType ?? 'CONTRACT_EXTRACTED' });
5582
5647
  if (line.amountMismatch === true && line.amountMismatchConfirmed !== true)
5583
5648
  throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}金额差异必须确认`);
@@ -5623,7 +5688,7 @@ function purchaseLineAmountText(line) {
5623
5688
  }
5624
5689
  function purchaseLineMetricAmount(line) {
5625
5690
  const lineAmount = optionalDecimalInput(line.lineAmountTaxIncluded, '采购商品含税金额必须为有效金额') ?? new Decimal(0);
5626
- if (lineAmount.gt(0))
5691
+ if (hasQueryValue(line.lineAmountTaxIncluded))
5627
5692
  return lineAmount;
5628
5693
  const quantity = optionalDecimalInput(line.quantity, '采购商品数量必须为有效数值');
5629
5694
  const unitPrice = optionalDecimalInput(line.unitPriceTaxIncluded, '采购商品含税单价必须为有效金额');