@chenchaolong/plugin-trade-compliance-workbench 1.0.211 → 1.0.213
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.
- package/dist/lib/analytics-query.d.ts.map +1 -1
- package/dist/lib/analytics-query.js +39 -16
- package/dist/lib/analytics-query.js.map +1 -1
- package/dist/lib/domain/purchase-pricing.d.ts +5 -0
- package/dist/lib/domain/purchase-pricing.d.ts.map +1 -0
- package/dist/lib/domain/purchase-pricing.js +27 -0
- package/dist/lib/domain/purchase-pricing.js.map +1 -0
- package/dist/lib/entities/index.d.ts +3 -1
- package/dist/lib/entities/index.d.ts.map +1 -1
- package/dist/lib/entities/index.js +3 -1
- package/dist/lib/entities/index.js.map +1 -1
- package/dist/lib/entities/procurement.entity.d.ts +2 -0
- package/dist/lib/entities/procurement.entity.d.ts.map +1 -1
- package/dist/lib/entities/procurement.entity.js +8 -0
- package/dist/lib/entities/procurement.entity.js.map +1 -1
- package/dist/lib/entities/sales-file-generation-task.entity.d.ts +23 -0
- package/dist/lib/entities/sales-file-generation-task.entity.d.ts.map +1 -0
- package/dist/lib/entities/sales-file-generation-task.entity.js +75 -0
- package/dist/lib/entities/sales-file-generation-task.entity.js.map +1 -0
- package/dist/lib/import-jobs/import-command.builder.js +2 -2
- package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
- package/dist/lib/import-jobs/purchase-spreadsheet-review.d.ts.map +1 -1
- package/dist/lib/import-jobs/purchase-spreadsheet-review.js +11 -3
- package/dist/lib/import-jobs/purchase-spreadsheet-review.js.map +1 -1
- package/dist/lib/import-jobs/source-field-recovery.d.ts +5 -0
- package/dist/lib/import-jobs/source-field-recovery.d.ts.map +1 -0
- package/dist/lib/import-jobs/source-field-recovery.js +52 -0
- package/dist/lib/import-jobs/source-field-recovery.js.map +1 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts +23 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js +74 -2
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js.map +1 -1
- package/dist/lib/packing/packing-spreadsheet.d.ts.map +1 -1
- package/dist/lib/packing/packing-spreadsheet.js +4 -0
- package/dist/lib/packing/packing-spreadsheet.js.map +1 -1
- package/dist/lib/packing/supplier-packing.service.d.ts +3 -0
- package/dist/lib/packing/supplier-packing.service.d.ts.map +1 -1
- package/dist/lib/packing/supplier-packing.service.js +57 -5
- package/dist/lib/packing/supplier-packing.service.js.map +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.css +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.js +11 -11
- package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +7 -2
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +87 -87
- package/dist/lib/remote-components/trade-compliance-workbench/preview-source.mjs +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/preview.js +1 -1
- package/dist/lib/remote-ui/action-execution.d.ts.map +1 -1
- package/dist/lib/remote-ui/action-execution.js +4 -0
- package/dist/lib/remote-ui/action-execution.js.map +1 -1
- package/dist/lib/remote-ui/app-source.d.ts.map +1 -1
- package/dist/lib/remote-ui/app-source.js +26 -5
- package/dist/lib/remote-ui/app-source.js.map +1 -1
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts +8 -0
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/generation-task-panel.js +67 -0
- package/dist/lib/remote-ui/components/generation-task-panel.js.map +1 -0
- package/dist/lib/remote-ui/components/source-file-preview.d.ts +11 -1
- package/dist/lib/remote-ui/components/source-file-preview.d.ts.map +1 -1
- package/dist/lib/remote-ui/components/source-file-preview.js +36 -6
- package/dist/lib/remote-ui/components/source-file-preview.js.map +1 -1
- package/dist/lib/remote-ui/generation-tasks.d.ts +42 -0
- package/dist/lib/remote-ui/generation-tasks.d.ts.map +1 -0
- package/dist/lib/remote-ui/generation-tasks.js +32 -0
- package/dist/lib/remote-ui/generation-tasks.js.map +1 -0
- package/dist/lib/remote-ui/pages/analytics-dashboard.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/analytics-dashboard.js +1 -1
- package/dist/lib/remote-ui/pages/analytics-dashboard.js.map +1 -1
- package/dist/lib/remote-ui/pages/files.d.ts +1 -1
- package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/files.js +6 -12
- package/dist/lib/remote-ui/pages/files.js.map +1 -1
- package/dist/lib/remote-ui/pages/procurement-contracts.css +3 -0
- package/dist/lib/remote-ui/pages/procurement.d.ts +2 -0
- package/dist/lib/remote-ui/pages/procurement.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/procurement.js +62 -16
- package/dist/lib/remote-ui/pages/procurement.js.map +1 -1
- package/dist/lib/remote-ui/pages/sales.d.ts +3 -1
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +27 -13
- package/dist/lib/remote-ui/pages/sales.js.map +1 -1
- package/dist/lib/remote-ui/procurement-contracts.d.ts +7 -0
- package/dist/lib/remote-ui/procurement-contracts.d.ts.map +1 -1
- package/dist/lib/remote-ui/procurement-contracts.js.map +1 -1
- package/dist/lib/remote-ui/purchase-review-adapter.d.ts.map +1 -1
- package/dist/lib/remote-ui/purchase-review-adapter.js +4 -3
- package/dist/lib/remote-ui/purchase-review-adapter.js.map +1 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts +1 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts.map +1 -1
- package/dist/lib/remote-ui/styles.css +6 -0
- package/dist/lib/sales-file-generation-lifecycle.d.ts +11 -0
- package/dist/lib/sales-file-generation-lifecycle.d.ts.map +1 -0
- package/dist/lib/sales-file-generation-lifecycle.js +42 -0
- package/dist/lib/sales-file-generation-lifecycle.js.map +1 -0
- package/dist/lib/sales-file-generation-task.d.ts +46 -0
- package/dist/lib/sales-file-generation-task.d.ts.map +1 -0
- package/dist/lib/sales-file-generation-task.js +207 -0
- package/dist/lib/sales-file-generation-task.js.map +1 -0
- package/dist/lib/sales-file.service.d.ts +15 -6
- package/dist/lib/sales-file.service.d.ts.map +1 -1
- package/dist/lib/sales-file.service.js +142 -83
- package/dist/lib/sales-file.service.js.map +1 -1
- package/dist/lib/schema-maintenance.d.ts +1 -0
- package/dist/lib/schema-maintenance.d.ts.map +1 -1
- package/dist/lib/schema-maintenance.js +28 -0
- package/dist/lib/schema-maintenance.js.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.d.ts +1 -0
- package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.js +1 -1
- package/dist/lib/supplier-materials/generation-materials.js.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -1
- package/dist/lib/supplier-materials/supplier-materials.js +17 -2
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -1
- package/dist/lib/types.d.ts +28 -1
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/types.js.map +1 -1
- package/dist/lib/workbench-action-contract.d.ts +1 -1
- package/dist/lib/workbench-action-contract.d.ts.map +1 -1
- package/dist/lib/workbench-action-contract.js +4 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +18 -13
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +32 -5
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +84 -70
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +2 -0
- package/dist/lib/workbench.middleware.js.map +1 -1
- package/dist/lib/workbench.plugin.d.ts +3 -1
- package/dist/lib/workbench.plugin.d.ts.map +1 -1
- package/dist/lib/workbench.plugin.js +11 -5
- package/dist/lib/workbench.plugin.js.map +1 -1
- package/dist/lib/workbench.service.d.ts +8 -3
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +107 -24
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { recoverEnglishMaterialFields, recoverSourcePartyName } from './import-jobs/source-field-recovery.js';
|
|
3
|
+
import { extractDocumentText } from './adapters/document-text-extractor.js';
|
|
4
|
+
import { cancelSalesFileGenerationTasks } from './sales-file-generation-lifecycle.js';
|
|
2
5
|
import { loadSupplierMaterials, listSupplierMaterials, mutateSupplierMaterial, validateMaterialTargets } from './supplier-materials/supplier-materials.js';
|
|
3
6
|
import { contractResultRecoveryCommand, importTaskHandoffId } from './import-jobs/contract-result-recovery.js';
|
|
4
7
|
import { Inject, Injectable, Optional } from '@nestjs/common';
|
|
@@ -12,7 +15,7 @@ import { tmpdir } from 'node:os';
|
|
|
12
15
|
import { join } from 'node:path';
|
|
13
16
|
import { finished } from 'node:stream/promises';
|
|
14
17
|
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';
|
|
18
|
+
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
19
|
import { CATALOG_REVIEW_BATCH_LIMIT, CATALOG_REVIEW_LEASE_MS, CATALOG_TRANSLATION_REVIEW_LEASE_MS } from './constants.js';
|
|
17
20
|
import { CatalogTypes, ClauseTypes, CustomerProfitRateStatuses, DomainError, DomainErrorCodes, RefundValidationMethods, RiskLevels, SalesPaymentStatuses, SanctionHitStatuses, StalledCatalogImportDecisions } from './types.js';
|
|
18
21
|
import { resolveSalesLineOrder } from './domain/sales-line-order.js';
|
|
@@ -37,6 +40,7 @@ import { PACKING_IMPORT_ACTIVE_STATUSES, packingImportTaskDto, packingImportTarg
|
|
|
37
40
|
import { DemoDataSeedMarker } from './demo-data.entity.js';
|
|
38
41
|
import { extractSpreadsheetContractFacts, applyCustomerSpreadsheetFacts } from './import-jobs/spreadsheet-contract-facts.js';
|
|
39
42
|
import { preparePurchaseSpreadsheetDraft } from './import-jobs/purchase-spreadsheet-review.js';
|
|
43
|
+
import { normalizePurchaseLinePricing, purchaseAmountMismatch } from './domain/purchase-pricing.js';
|
|
40
44
|
import { cleanPurchaseDraftPayload } from './domain/purchase-draft-cleanup.js';
|
|
41
45
|
const DEFAULT_IMPORT_ISSUE_EXPORT_MAX_ROWS = 50_000;
|
|
42
46
|
const HARD_IMPORT_ISSUE_EXPORT_MAX_ROWS = 100_000;
|
|
@@ -2269,7 +2273,15 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2269
2273
|
async loadSupplierMaterials(scope, ids, manager) { return loadSupplierMaterials(manager ?? this.dataSource, scope, ids); }
|
|
2270
2274
|
async validateSupplierMaterialTargets(scope, ids) { await validateMaterialTargets(this.dataSource.manager, scope, ids); }
|
|
2271
2275
|
async listSupplierMaterials(scope, ids) { return { documents: await listSupplierMaterials(this.dataSource, scope, ids) }; }
|
|
2272
|
-
async importSupplierMaterials(scope, id, rows, claimAttemptToken) {
|
|
2276
|
+
async importSupplierMaterials(scope, id, rows, claimAttemptToken) {
|
|
2277
|
+
const task = await this.dataSource.getRepository(ImportTask).findOne({ where: { ...activeScope(scope), id, deletedAt: IsNull() } });
|
|
2278
|
+
if (task?.documentType === 'ENGLISH_QUOTATION' && ['XLS', 'XLSX'].includes(task.sourceFileFormat) && this.storage && task.status !== 'SUCCEEDED') {
|
|
2279
|
+
const source = await this.storage.read(task.sourceFileId).catch(() => null);
|
|
2280
|
+
if (source)
|
|
2281
|
+
rows = recoverEnglishMaterialFields(rows, source);
|
|
2282
|
+
}
|
|
2283
|
+
return mutateSupplierMaterial(this.dataSource, scope, id, 'IMPORT', rows, claimAttemptToken);
|
|
2284
|
+
}
|
|
2273
2285
|
async saveSupplierMaterialReview(scope, id, rows) { return mutateSupplierMaterial(this.dataSource, scope, id, 'REVIEW', rows); }
|
|
2274
2286
|
async deleteSupplierMaterial(scope, id) { return mutateSupplierMaterial(this.dataSource, scope, id, 'DELETE'); }
|
|
2275
2287
|
async createImportTask(scope, input) {
|
|
@@ -2734,6 +2746,14 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2734
2746
|
effectivePayload = { ...effectivePayload, contract: applyCustomerSpreadsheetFacts(effectivePayload.contract, facts) };
|
|
2735
2747
|
}
|
|
2736
2748
|
}
|
|
2749
|
+
if (version === 'CUSTOMER_CONTRACT_DRAFT_V1' && task.sourceFileFormat === 'DOCX' && this.storage) {
|
|
2750
|
+
const source = await this.storage.read(task.sourceFileId).catch(() => null);
|
|
2751
|
+
const customer = effectivePayload.customer;
|
|
2752
|
+
if (source && typeof customer?.name === 'string') {
|
|
2753
|
+
const text = await extractDocumentText({ buffer: source, fileName: task.sourceFileName });
|
|
2754
|
+
effectivePayload = { ...effectivePayload, customer: { ...customer, name: recoverSourcePartyName(customer.name, text.text) } };
|
|
2755
|
+
}
|
|
2756
|
+
}
|
|
2737
2757
|
if (version === 'CUSTOMER_CONTRACT_DRAFT_V1')
|
|
2738
2758
|
effectivePayload = normalizeCustomerContractDraftPayload(effectivePayload);
|
|
2739
2759
|
if (version === 'PURCHASE_DRAFT_V1')
|
|
@@ -2773,7 +2793,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2773
2793
|
}
|
|
2774
2794
|
async savePurchaseDraft(scope, importTaskId, draft) {
|
|
2775
2795
|
await this.ensureProcurementSchema();
|
|
2776
|
-
const normalizedDraft = normalizePurchaseDraftDates(cleanPurchaseDraftPayload(draft));
|
|
2796
|
+
const normalizedDraft = normalizePurchaseDraftDates(normalizePurchaseDraftMoney(cleanPurchaseDraftPayload(draft)));
|
|
2777
2797
|
assertPurchaseDraft(normalizedDraft);
|
|
2778
2798
|
const confirmedById = requiredId(scope.userId, '当前用户标识');
|
|
2779
2799
|
const confirmedAt = new Date();
|
|
@@ -2794,7 +2814,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2794
2814
|
const lineRepo = manager.getRepository(PurchaseOrderLine);
|
|
2795
2815
|
for (let index = 0; index < normalizedDraft.lines.length; index += 1) {
|
|
2796
2816
|
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 }));
|
|
2817
|
+
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
2818
|
}
|
|
2799
2819
|
task.status = 'SUCCEEDED';
|
|
2800
2820
|
task.resultEntityId = entity.id;
|
|
@@ -3023,13 +3043,14 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3023
3043
|
await this.ensureProcurementSchema();
|
|
3024
3044
|
validatePurchaseLineDiscriminators(input);
|
|
3025
3045
|
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']) };
|
|
3046
|
+
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
3047
|
validatePurchaseTaxRates(candidate, { purchaseOrderLineId: existing.id, lineNumber: existing.lineNumber, productName: candidate.productName });
|
|
3028
3048
|
if (new Decimal(candidate.quantity).lte(0))
|
|
3029
3049
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
|
|
3030
3050
|
const saved = await this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
|
|
3031
3051
|
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']));
|
|
3052
|
+
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']));
|
|
3053
|
+
applyManualPurchasePricing(item, input, scope);
|
|
3033
3054
|
item.lineAmountTaxIncluded = purchaseLineAmountText(item);
|
|
3034
3055
|
validatePurchaseLineDiscriminators(item);
|
|
3035
3056
|
const rates = validatePurchaseTaxRates(item, { purchaseOrderLineId: item.id, lineNumber: item.lineNumber, productName: item.productName });
|
|
@@ -3048,6 +3069,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3048
3069
|
}
|
|
3049
3070
|
async addPurchaseLine(scope, purchaseOrderId, input) {
|
|
3050
3071
|
await this.ensureProcurementSchema();
|
|
3072
|
+
input = normalizePurchaseLinePricing({ ...input });
|
|
3051
3073
|
validatePurchaseLineDiscriminators(input);
|
|
3052
3074
|
const discriminators = validatePurchaseLineDiscriminators({ ...input, sourceType: 'MANUAL_ENTRY', vatRateSource: input.vatRateSource ?? 'MANUAL' });
|
|
3053
3075
|
const rates = validatePurchaseTaxRates(input, { productName: input.productName });
|
|
@@ -3055,7 +3077,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3055
3077
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
|
|
3056
3078
|
const saved = await this.withLockedPurchaseLines(scope, purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
|
|
3057
3079
|
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 });
|
|
3080
|
+
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 });
|
|
3081
|
+
applyManualPurchasePricing(item, input, scope);
|
|
3059
3082
|
this.assertLockedPurchaseReceipts([...lines, item], contracts, customers, manuals);
|
|
3060
3083
|
return lineRepo.save(item);
|
|
3061
3084
|
});
|
|
@@ -3142,7 +3165,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3142
3165
|
* 客户级未收款总额(CNY):派生销售订单(客户合同组)各自 clamp 后汇总,超收不抵扣其他订单欠款。
|
|
3143
3166
|
* 口径与销售订单列表、分析看板一致:订单总额 = 人工覆盖值或商品行汇总,未收款 = max(总额 - 已收款, 0)。
|
|
3144
3167
|
*/
|
|
3145
|
-
async customerUnreceivedAmounts(scope, customerIds) {
|
|
3168
|
+
async customerUnreceivedAmounts(scope, customerIds, manager) {
|
|
3146
3169
|
const map = new Map();
|
|
3147
3170
|
const ids = [...new Set(customerIds)].filter(Boolean);
|
|
3148
3171
|
if (!ids.length)
|
|
@@ -3181,7 +3204,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3181
3204
|
SUM(GREATEST(sales_contract_totals."salesTotalCny" - sales_contract_totals."receivedCny", 0))::text AS "unreceivedCny"
|
|
3182
3205
|
FROM sales_contract_totals
|
|
3183
3206
|
GROUP BY sales_contract_totals."customerId"`;
|
|
3184
|
-
const rows = await this.dataSource.query(sql, parameters);
|
|
3207
|
+
const rows = await (manager ?? this.dataSource).query(sql, parameters);
|
|
3185
3208
|
for (const row of rows)
|
|
3186
3209
|
if (row?.customerId)
|
|
3187
3210
|
map.set(row.customerId, new Decimal(row.unreceivedCny ?? 0).toFixed(2));
|
|
@@ -3770,29 +3793,30 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3770
3793
|
await this.recalculateCompanyRisks(scope, 'SOURCE_CHANGED');
|
|
3771
3794
|
return saved;
|
|
3772
3795
|
}
|
|
3773
|
-
async listDerivedSalesOrders(scope, customerId, selectedIdentities) {
|
|
3774
|
-
const
|
|
3796
|
+
async listDerivedSalesOrders(scope, customerId, selectedIdentities, manager) {
|
|
3797
|
+
const source = manager ?? this.dataSource;
|
|
3798
|
+
const identities = selectedIdentities ?? await this.selectAllDerivedSalesOrderIdentities(scope, customerId, {}, false, manager);
|
|
3775
3799
|
if (!identities.length)
|
|
3776
3800
|
return [];
|
|
3777
3801
|
const contractIds = [...new Set(identities.map(identity => identity.customerContractId))];
|
|
3778
3802
|
const selectedContracts = new Set(identities.map(identity => identity.customerContractId));
|
|
3779
3803
|
const [customers, contracts, purchases, lines] = await Promise.all([
|
|
3780
|
-
|
|
3781
|
-
|
|
3782
|
-
|
|
3783
|
-
|
|
3804
|
+
source.getRepository(Customer).find({ where: { ...activeScope(scope), ...(customerId ? { id: customerId } : {}), deletedAt: IsNull() } }),
|
|
3805
|
+
source.getRepository(CustomerContract).find({ where: { ...activeScope(scope), id: In(contractIds), ...(customerId ? { customerId } : {}), deletedAt: IsNull() } }),
|
|
3806
|
+
source.getRepository(PurchaseOrder).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { id: 'ASC' } }),
|
|
3807
|
+
source.getRepository(PurchaseOrderLine).find({ where: { ...activeScope(scope), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } })
|
|
3784
3808
|
]);
|
|
3785
3809
|
const associatedPurchaseIds = purchases.filter(purchase => {
|
|
3786
3810
|
const baseCode = parsePurchaseContractNo(purchase.contractNo).baseCode;
|
|
3787
3811
|
return contracts.some(contract => selectedContracts.has(contract.id) && parseCustomerContractNo(contract.contractNo).baseCode === baseCode);
|
|
3788
3812
|
}).map(purchase => purchase.id);
|
|
3789
|
-
const manuals = associatedPurchaseIds.length ? await
|
|
3813
|
+
const manuals = associatedPurchaseIds.length ? await source.getRepository(DerivedSalesOrderManualData).find({ where: { ...activeScope(scope), customerContractId: In(contractIds), purchaseOrderId: In(associatedPurchaseIds), deletedAt: IsNull() } }) : [];
|
|
3790
3814
|
const customerMap = new Map(customers.map(customer => [customer.id, customer]));
|
|
3791
3815
|
const manualMap = new Map(manuals.map(manual => [derivedOrderKey(manual.customerContractId, manual.purchaseOrderId), manual]));
|
|
3792
3816
|
const linesByPurchase = groupBy(lines, line => line.purchaseOrderId);
|
|
3793
|
-
const riskRows = lines.length ? await
|
|
3817
|
+
const riskRows = lines.length ? await source.getRepository(ProductComplianceMatch).find({ where: { ...activeScope(scope), purchaseOrderLineId: In(lines.map(line => line.id)), deletedAt: IsNull() } }) : [];
|
|
3794
3818
|
const controlledGoodsIds = [...new Set(riskRows.map(match => match.controlledGoodsId))];
|
|
3795
|
-
const controlledGoods = controlledGoodsIds.length ? await
|
|
3819
|
+
const controlledGoods = controlledGoodsIds.length ? await source.getRepository(ControlledGoodsRecord).find({ where: { ...activeScope(scope), id: In(controlledGoodsIds), lifecycleStatus: 'ACTIVE', deletedAt: IsNull() } }) : [];
|
|
3796
3820
|
const controlledGoodsById = new Map(controlledGoods.map(item => [item.id, item]));
|
|
3797
3821
|
const risksByLine = groupBy(riskRows, match => match.purchaseOrderLineId);
|
|
3798
3822
|
const purchasesByBaseCode = groupBy(purchases, purchase => parsePurchaseContractNo(purchase.contractNo).baseCode);
|
|
@@ -3872,8 +3896,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3872
3896
|
}
|
|
3873
3897
|
return [...grouped.values()].sort(compareDerivedSalesOrders);
|
|
3874
3898
|
}
|
|
3875
|
-
derivedSalesIdentityQuery(scope, customerId, parameters, includeParties) {
|
|
3876
|
-
const qb = this.dataSource.getRepository(CustomerContract).createQueryBuilder('contract')
|
|
3899
|
+
derivedSalesIdentityQuery(scope, customerId, parameters, includeParties, manager) {
|
|
3900
|
+
const qb = (manager ?? this.dataSource).getRepository(CustomerContract).createQueryBuilder('contract')
|
|
3877
3901
|
.innerJoin(Customer, 'customer', 'customer.id = contract."customerId" AND customer."tenantId" = contract."tenantId" AND customer."organizationId" = contract."organizationId" AND customer."deletedAt" IS NULL')
|
|
3878
3902
|
.innerJoin(PurchaseOrder, 'purchase', `purchase."tenantId" = contract."tenantId" AND purchase."organizationId" = contract."organizationId" AND purchase."deletedAt" IS NULL AND ${derivedSalesContractLinkSql('contract', 'purchase')}`)
|
|
3879
3903
|
.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 +3932,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3908
3932
|
qb.andWhere(`${received} >= ${amount}`);
|
|
3909
3933
|
return qb;
|
|
3910
3934
|
}
|
|
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();
|
|
3935
|
+
async selectAllDerivedSalesOrderIdentities(scope, customerId, parameters, includeParties, manager) {
|
|
3936
|
+
const rows = await this.derivedSalesIdentityQuery(scope, customerId, parameters, includeParties, manager).orderBy('contract.id', 'ASC').addOrderBy('purchase.id', 'ASC').getRawMany();
|
|
3913
3937
|
const seen = new Set();
|
|
3914
3938
|
return rows.filter(row => { if (seen.has(row.customerContractId))
|
|
3915
3939
|
return false; seen.add(row.customerContractId); return true; });
|
|
@@ -4062,6 +4086,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4062
4086
|
if (entity === PurchaseOrderLine)
|
|
4063
4087
|
return this.deletePurchaseLine(scope, id);
|
|
4064
4088
|
const row = await this.dataSource.transaction(async (manager) => {
|
|
4089
|
+
if (entity === PurchaseOrder || entity === CustomerContract)
|
|
4090
|
+
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
4065
4091
|
if (entity === Customer) {
|
|
4066
4092
|
const count = await manager.getRepository(CustomerContract).count({ where: { ...activeScope(scope), customerId: id, deletedAt: IsNull() } });
|
|
4067
4093
|
if (count)
|
|
@@ -4075,6 +4101,10 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4075
4101
|
const repo = manager.getRepository(entity);
|
|
4076
4102
|
const lifecycle = entity === ControlledGoodsRecord || entity === SanctionedCompanyRecord ? { lifecycleStatus: 'ACTIVE' } : {};
|
|
4077
4103
|
const target = await required(repo.findOne({ where: { ...activeScope(scope), id, ...lifecycle, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } }), '记录不存在');
|
|
4104
|
+
if (entity === PurchaseOrder)
|
|
4105
|
+
await cancelSalesFileGenerationTasks(manager, scope, { purchaseOrderId: id });
|
|
4106
|
+
if (entity === CustomerContract)
|
|
4107
|
+
await cancelSalesFileGenerationTasks(manager, scope, { customerContractId: id });
|
|
4078
4108
|
const now = new Date();
|
|
4079
4109
|
target.deletedAt = now;
|
|
4080
4110
|
target.deletedById = scope.userId ?? null;
|
|
@@ -4162,6 +4192,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4162
4192
|
await remove('customerContractAnalysisRun', CustomerContractAnalysisRun);
|
|
4163
4193
|
await remove('customerContractClause', CustomerContractClause);
|
|
4164
4194
|
await remove('derivedSalesOrderManualData', DerivedSalesOrderManualData);
|
|
4195
|
+
await remove('salesFileGenerationTask', SalesFileGenerationTask);
|
|
4165
4196
|
await remove('generatedSalesFile', GeneratedSalesFile);
|
|
4166
4197
|
await remove('customerContract', CustomerContract);
|
|
4167
4198
|
await remove('customer', Customer);
|
|
@@ -4834,6 +4865,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4834
4865
|
}
|
|
4835
4866
|
async withLockedPurchaseLines(scope, purchaseOrderId, callback) {
|
|
4836
4867
|
return this.dataSource.transaction(async (manager) => {
|
|
4868
|
+
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
4837
4869
|
const purchaseRepo = manager.getRepository(PurchaseOrder);
|
|
4838
4870
|
const preview = await required(purchaseRepo.findOne({ where: { ...activeScope(scope), id: purchaseOrderId, deletedAt: IsNull() } }), '采购订单不存在');
|
|
4839
4871
|
const baseCode = parsePurchaseContractNo(preview.contractNo).baseCode;
|
|
@@ -4871,6 +4903,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4871
4903
|
return this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ manager, lineRepo, lines, contracts, customers, manuals }) => {
|
|
4872
4904
|
const row = await required(Promise.resolve(lines.find(line => line.id === id) ?? null), '记录不存在');
|
|
4873
4905
|
this.assertLockedPurchaseReceipts(lines.filter(line => line.id !== id), contracts, customers, manuals);
|
|
4906
|
+
await cancelSalesFileGenerationTasks(manager, scope, { purchaseOrderId: existing.purchaseOrderId });
|
|
4874
4907
|
row.deletedAt = new Date();
|
|
4875
4908
|
row.deletedById = scope.userId ?? null;
|
|
4876
4909
|
row.deleteOperation = 'USER_DELETE';
|
|
@@ -5512,6 +5545,22 @@ async function required(promise, message) { const value = await promise; if (!va
|
|
|
5512
5545
|
throw new DomainError(DomainErrorCodes.NOT_FOUND, message); return value; }
|
|
5513
5546
|
function pick(input, keys) { return Object.fromEntries(keys.filter(key => key in input).map(key => [key, input[key]])); }
|
|
5514
5547
|
function maxRisk(levels) { return levels.includes('HIGH') ? 'HIGH' : levels.includes('MEDIUM') ? 'MEDIUM' : levels.includes('LOW') ? 'LOW' : null; }
|
|
5548
|
+
function normalizePurchaseDraftMoney(draft) {
|
|
5549
|
+
const lines = draft.lines.map(line => {
|
|
5550
|
+
const normalized = normalizePurchaseLinePricing(line);
|
|
5551
|
+
return { ...normalized, amountMismatch: normalized.amountMismatch === true || purchaseAmountMismatch(normalized.quantity, normalized.unitPriceTaxIncluded, normalized.lineAmountTaxIncluded) };
|
|
5552
|
+
});
|
|
5553
|
+
const complete = lines.every(line => hasQueryValue(line.lineAmountTaxIncluded) || (hasQueryValue(line.quantity) && hasQueryValue(line.unitPriceTaxIncluded)));
|
|
5554
|
+
let mismatch = false;
|
|
5555
|
+
if (complete && hasQueryValue(draft.order.contractAmountCny)) {
|
|
5556
|
+
// Invalid decimals are reported by field validation below; they must not hide its precise message.
|
|
5557
|
+
try {
|
|
5558
|
+
mismatch = !new Decimal(draft.order.contractAmountCny).toDecimalPlaces(2).equals(lines.reduce((sum, line) => sum.plus(purchaseLineAmountText(line)), new Decimal(0)).toDecimalPlaces(2));
|
|
5559
|
+
}
|
|
5560
|
+
catch { }
|
|
5561
|
+
}
|
|
5562
|
+
return { ...draft, lines, order: { ...draft.order, amountMismatch: draft.order.amountMismatch === true || mismatch } };
|
|
5563
|
+
}
|
|
5515
5564
|
function normalizePurchaseDraftDates(draft) {
|
|
5516
5565
|
return {
|
|
5517
5566
|
...draft,
|
|
@@ -5529,7 +5578,7 @@ function normalizeOptionalDateString(value, label) {
|
|
|
5529
5578
|
if (!hasQueryValue(value))
|
|
5530
5579
|
return null;
|
|
5531
5580
|
const text = String(value).trim();
|
|
5532
|
-
const matched = text.match(/^(\d{4})\s*(?:[-/.年])\s*(\d{1,2})\s*(?:[-/.月])\s*(\d{1,2})\s*(?:日)?$/);
|
|
5581
|
+
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
5582
|
if (!matched)
|
|
5534
5583
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${label}格式无效,请使用 YYYY-MM-DD`);
|
|
5535
5584
|
const [, rawYear, rawMonth, rawDay] = matched;
|
|
@@ -5542,6 +5591,35 @@ function normalizeOptionalDateString(value, label) {
|
|
|
5542
5591
|
}
|
|
5543
5592
|
return `${rawYear}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
|
5544
5593
|
}
|
|
5594
|
+
function applyManualPurchasePricing(item, input, scope) {
|
|
5595
|
+
const pricingChanged = ['quantity', 'unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'freeOfCharge', 'referenceUnitPriceTaxIncluded'].some(key => Object.prototype.hasOwnProperty.call(input, key));
|
|
5596
|
+
if (!pricingChanged)
|
|
5597
|
+
return;
|
|
5598
|
+
if (!Object.prototype.hasOwnProperty.call(input, 'lineAmountTaxIncluded') && (input.quantity !== undefined || input.unitPriceTaxIncluded !== undefined)) {
|
|
5599
|
+
item.lineAmountTaxIncluded = new Decimal(item.quantity).mul(item.unitPriceTaxIncluded).toFixed(2);
|
|
5600
|
+
}
|
|
5601
|
+
Object.assign(item, normalizePurchaseLinePricing({ ...item }));
|
|
5602
|
+
for (const key of ['unitPriceTaxIncluded', 'lineAmountTaxIncluded', 'referenceUnitPriceTaxIncluded']) {
|
|
5603
|
+
if (!hasQueryValue(item[key]))
|
|
5604
|
+
continue;
|
|
5605
|
+
let value;
|
|
5606
|
+
try {
|
|
5607
|
+
value = new Decimal(String(item[key]));
|
|
5608
|
+
}
|
|
5609
|
+
catch {
|
|
5610
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品金额格式无效');
|
|
5611
|
+
}
|
|
5612
|
+
if (!value.isFinite() || value.lt(0))
|
|
5613
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品金额必须为非负数');
|
|
5614
|
+
}
|
|
5615
|
+
if (item.freeOfCharge != null && typeof item.freeOfCharge !== 'boolean')
|
|
5616
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '赠品标记无效');
|
|
5617
|
+
const mismatch = purchaseAmountMismatch(item.quantity, item.unitPriceTaxIncluded, item.lineAmountTaxIncluded);
|
|
5618
|
+
if (mismatch && input.amountMismatchConfirmed !== true)
|
|
5619
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '商品金额差异必须确认');
|
|
5620
|
+
item.amountMismatchConfirmedAt = mismatch ? new Date() : null;
|
|
5621
|
+
item.amountMismatchConfirmedById = mismatch ? scope.userId ?? null : null;
|
|
5622
|
+
}
|
|
5545
5623
|
function assertPurchaseDraft(draft) {
|
|
5546
5624
|
if (!hasQueryValue(draft.supplier?.name))
|
|
5547
5625
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商名称为必填项');
|
|
@@ -5578,6 +5656,11 @@ function assertPurchaseDraft(draft) {
|
|
|
5578
5656
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}退税政策日期不得晚于下单日期`);
|
|
5579
5657
|
if (hasQueryValue(line.refundValidationMethod) && !RefundValidationMethods.some(method => method === line.refundValidationMethod))
|
|
5580
5658
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}退税校验方式无效`);
|
|
5659
|
+
if (line.freeOfCharge != null && typeof line.freeOfCharge !== 'boolean')
|
|
5660
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}免费标记必须为布尔值`);
|
|
5661
|
+
const referencePrice = optionalDecimalInput(line.referenceUnitPriceTaxIncluded, `${prefix}参考单价必须为有效金额`);
|
|
5662
|
+
if (referencePrice?.isNegative())
|
|
5663
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}参考单价不能为负数`);
|
|
5581
5664
|
validatePurchaseLineDiscriminators({ ...line, sourceType: line.sourceType ?? 'CONTRACT_EXTRACTED' });
|
|
5582
5665
|
if (line.amountMismatch === true && line.amountMismatchConfirmed !== true)
|
|
5583
5666
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}金额差异必须确认`);
|
|
@@ -5623,7 +5706,7 @@ function purchaseLineAmountText(line) {
|
|
|
5623
5706
|
}
|
|
5624
5707
|
function purchaseLineMetricAmount(line) {
|
|
5625
5708
|
const lineAmount = optionalDecimalInput(line.lineAmountTaxIncluded, '采购商品含税金额必须为有效金额') ?? new Decimal(0);
|
|
5626
|
-
if (
|
|
5709
|
+
if (hasQueryValue(line.lineAmountTaxIncluded))
|
|
5627
5710
|
return lineAmount;
|
|
5628
5711
|
const quantity = optionalDecimalInput(line.quantity, '采购商品数量必须为有效数值');
|
|
5629
5712
|
const unitPrice = optionalDecimalInput(line.unitPriceTaxIncluded, '采购商品含税单价必须为有效金额');
|