@chenchaolong/plugin-trade-compliance-workbench 1.0.210 → 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.
- package/README.md +13 -1
- package/dist/lib/analytics-query.d.ts.map +1 -1
- package/dist/lib/analytics-query.js +4 -2
- package/dist/lib/analytics-query.js.map +1 -1
- package/dist/lib/constants.d.ts +1 -0
- package/dist/lib/constants.d.ts.map +1 -1
- package/dist/lib/constants.js +1 -0
- package/dist/lib/constants.js.map +1 -1
- package/dist/lib/domain/finance.js +6 -6
- 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/contract-result-recovery.js +1 -1
- package/dist/lib/import-jobs/contract-result-recovery.js.map +1 -1
- package/dist/lib/import-jobs/import-command.builder.d.ts +1 -0
- package/dist/lib/import-jobs/import-command.builder.d.ts.map +1 -1
- package/dist/lib/import-jobs/import-command.builder.js +11 -2
- package/dist/lib/import-jobs/import-command.builder.js.map +1 -1
- package/dist/lib/import-jobs/import-job.processor.js +1 -1
- package/dist/lib/import-jobs/import-job.processor.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/spreadsheet-contract-facts.d.ts +15 -0
- package/dist/lib/import-jobs/spreadsheet-contract-facts.d.ts.map +1 -1
- package/dist/lib/import-jobs/spreadsheet-contract-facts.js +68 -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 +4 -2
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +1 -1
- 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 +9 -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 +40 -13
- package/dist/lib/remote-ui/app-source.js.map +1 -1
- package/dist/lib/remote-ui/components/generation-task-panel.d.ts +7 -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 +64 -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/components/supplier-materials.css +19 -0
- package/dist/lib/remote-ui/components/supplier-materials.d.ts +61 -0
- package/dist/lib/remote-ui/components/supplier-materials.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/supplier-materials.js +165 -0
- package/dist/lib/remote-ui/components/supplier-materials.js.map +1 -0
- package/dist/lib/remote-ui/contract-import.d.ts +1 -1
- package/dist/lib/remote-ui/contract-import.d.ts.map +1 -1
- package/dist/lib/remote-ui/contract-import.js +1 -1
- package/dist/lib/remote-ui/contract-import.js.map +1 -1
- package/dist/lib/remote-ui/generation-tasks.d.ts +40 -0
- package/dist/lib/remote-ui/generation-tasks.d.ts.map +1 -0
- package/dist/lib/remote-ui/generation-tasks.js +28 -0
- package/dist/lib/remote-ui/generation-tasks.js.map +1 -0
- package/dist/lib/remote-ui/import-task-status.d.ts +2 -2
- package/dist/lib/remote-ui/import-task-status.d.ts.map +1 -1
- package/dist/lib/remote-ui/import-task-status.js +3 -1
- package/dist/lib/remote-ui/import-task-status.js.map +1 -1
- 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 +8 -3
- package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/files.js +40 -22
- 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 +21 -6
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +75 -22
- package/dist/lib/remote-ui/pages/sales.js.map +1 -1
- package/dist/lib/remote-ui/pages/settings.js +2 -2
- package/dist/lib/remote-ui/pages/settings.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 +45 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts.map +1 -1
- package/dist/lib/remote-ui/sales-contracts.js.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 +234 -96
- 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 +50 -0
- package/dist/lib/supplier-materials/generation-materials.d.ts.map +1 -0
- package/dist/lib/supplier-materials/generation-materials.js +67 -0
- package/dist/lib/supplier-materials/generation-materials.js.map +1 -0
- package/dist/lib/supplier-materials/supplier-materials.d.ts +83 -0
- package/dist/lib/supplier-materials/supplier-materials.d.ts.map +1 -0
- package/dist/lib/supplier-materials/supplier-materials.js +138 -0
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -0
- package/dist/lib/types.d.ts +50 -4
- package/dist/lib/types.d.ts.map +1 -1
- package/dist/lib/types.js +5 -3
- 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 +9 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +20 -13
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +48 -8
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +196 -64
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +3 -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 +103 -3
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +114 -40
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { cancelSalesFileGenerationTasks } from './sales-file-generation-lifecycle.js';
|
|
3
|
+
import { loadSupplierMaterials, listSupplierMaterials, mutateSupplierMaterial, validateMaterialTargets } from './supplier-materials/supplier-materials.js';
|
|
2
4
|
import { contractResultRecoveryCommand, importTaskHandoffId } from './import-jobs/contract-result-recovery.js';
|
|
3
5
|
import { Inject, Injectable, Optional } from '@nestjs/common';
|
|
4
6
|
import { InjectDataSource } from '@nestjs/typeorm';
|
|
@@ -11,7 +13,7 @@ import { tmpdir } from 'node:os';
|
|
|
11
13
|
import { join } from 'node:path';
|
|
12
14
|
import { finished } from 'node:stream/promises';
|
|
13
15
|
import { createHash, randomUUID } from 'node:crypto';
|
|
14
|
-
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';
|
|
15
17
|
import { CATALOG_REVIEW_BATCH_LIMIT, CATALOG_REVIEW_LEASE_MS, CATALOG_TRANSLATION_REVIEW_LEASE_MS } from './constants.js';
|
|
16
18
|
import { CatalogTypes, ClauseTypes, CustomerProfitRateStatuses, DomainError, DomainErrorCodes, RefundValidationMethods, RiskLevels, SalesPaymentStatuses, SanctionHitStatuses, StalledCatalogImportDecisions } from './types.js';
|
|
17
19
|
import { resolveSalesLineOrder } from './domain/sales-line-order.js';
|
|
@@ -36,6 +38,7 @@ import { PACKING_IMPORT_ACTIVE_STATUSES, packingImportTaskDto, packingImportTarg
|
|
|
36
38
|
import { DemoDataSeedMarker } from './demo-data.entity.js';
|
|
37
39
|
import { extractSpreadsheetContractFacts, applyCustomerSpreadsheetFacts } from './import-jobs/spreadsheet-contract-facts.js';
|
|
38
40
|
import { preparePurchaseSpreadsheetDraft } from './import-jobs/purchase-spreadsheet-review.js';
|
|
41
|
+
import { normalizePurchaseLinePricing, purchaseAmountMismatch } from './domain/purchase-pricing.js';
|
|
39
42
|
import { cleanPurchaseDraftPayload } from './domain/purchase-draft-cleanup.js';
|
|
40
43
|
const DEFAULT_IMPORT_ISSUE_EXPORT_MAX_ROWS = 50_000;
|
|
41
44
|
const HARD_IMPORT_ISSUE_EXPORT_MAX_ROWS = 100_000;
|
|
@@ -2265,6 +2268,12 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2265
2268
|
await this.failCatalogDraft(manager, scope, task);
|
|
2266
2269
|
}
|
|
2267
2270
|
}
|
|
2271
|
+
async loadSupplierMaterials(scope, ids, manager) { return loadSupplierMaterials(manager ?? this.dataSource, scope, ids); }
|
|
2272
|
+
async validateSupplierMaterialTargets(scope, ids) { await validateMaterialTargets(this.dataSource.manager, scope, ids); }
|
|
2273
|
+
async listSupplierMaterials(scope, ids) { return { documents: await listSupplierMaterials(this.dataSource, scope, ids) }; }
|
|
2274
|
+
async importSupplierMaterials(scope, id, rows, claimAttemptToken) { return mutateSupplierMaterial(this.dataSource, scope, id, 'IMPORT', rows, claimAttemptToken); }
|
|
2275
|
+
async saveSupplierMaterialReview(scope, id, rows) { return mutateSupplierMaterial(this.dataSource, scope, id, 'REVIEW', rows); }
|
|
2276
|
+
async deleteSupplierMaterial(scope, id) { return mutateSupplierMaterial(this.dataSource, scope, id, 'DELETE'); }
|
|
2268
2277
|
async createImportTask(scope, input) {
|
|
2269
2278
|
const repo = this.dataSource.getRepository(ImportTask);
|
|
2270
2279
|
const targetAssistantId = requiredId(input.targetAssistantId, '目标智能体标识');
|
|
@@ -2275,8 +2284,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2275
2284
|
await lockOrganizationTaskClaim(manager, scope);
|
|
2276
2285
|
const taskRepo = manager.getRepository(ImportTask);
|
|
2277
2286
|
if (input.executionInput?.sourceContentHash) {
|
|
2278
|
-
const candidates = await taskRepo.find({ where: { ...activeScope(scope), documentType: input.documentType, status: In(['QUEUED', 'EXTRACTING', 'AI_PARSING', 'VALIDATING', 'AWAITING_REVIEW', 'PERSISTING']), deletedAt: IsNull() } });
|
|
2279
|
-
const existing = candidates.find(candidate => ['QUEUED', 'EXTRACTING', 'AI_PARSING', 'VALIDATING', 'AWAITING_REVIEW', 'PERSISTING'].includes(candidate.status) && candidate.executionInput?.sourceContentHash === input.executionInput?.sourceContentHash);
|
|
2287
|
+
const candidates = await taskRepo.find({ where: { ...activeScope(scope), documentType: input.documentType, status: In(['QUEUED', 'EXTRACTING', 'AI_PARSING', 'VALIDATING', 'AWAITING_REVIEW', 'PERSISTING', ...(['ENGLISH_QUOTATION', 'CUSTOMS_INFO'].includes(input.documentType) ? ['SUCCEEDED'] : [])]), deletedAt: IsNull() } });
|
|
2288
|
+
const existing = candidates.find(candidate => ['QUEUED', 'EXTRACTING', 'AI_PARSING', 'VALIDATING', 'AWAITING_REVIEW', 'PERSISTING', ...(['ENGLISH_QUOTATION', 'CUSTOMS_INFO'].includes(input.documentType) ? ['SUCCEEDED'] : [])].includes(candidate.status) && candidate.executionInput?.sourceContentHash === input.executionInput?.sourceContentHash);
|
|
2280
2289
|
if (existing)
|
|
2281
2290
|
return existing;
|
|
2282
2291
|
}
|
|
@@ -2667,7 +2676,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2667
2676
|
await lockOrganizationTaskClaim(manager, scope);
|
|
2668
2677
|
const repo = manager.getRepository(ImportTask);
|
|
2669
2678
|
const source = await required(repo.findOne({ where: { ...activeScope(scope), id: sourceTaskId, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } }), '解析任务不存在');
|
|
2670
|
-
if (!['CONTROLLED_CATALOG', 'SANCTION_CATALOG', 'PURCHASE_CONTRACT', 'CUSTOMER_CONTRACT', 'SUPPLIER_PACKING'].includes(source.documentType))
|
|
2679
|
+
if (!['CONTROLLED_CATALOG', 'SANCTION_CATALOG', 'PURCHASE_CONTRACT', 'CUSTOMER_CONTRACT', 'SUPPLIER_PACKING', 'ENGLISH_QUOTATION', 'CUSTOMS_INFO'].includes(source.documentType))
|
|
2671
2680
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '仅目录、合同和装箱单任务支持重新解析');
|
|
2672
2681
|
if (!source.executionInput)
|
|
2673
2682
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '原任务缺少可恢复执行参数');
|
|
@@ -2766,7 +2775,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2766
2775
|
}
|
|
2767
2776
|
async savePurchaseDraft(scope, importTaskId, draft) {
|
|
2768
2777
|
await this.ensureProcurementSchema();
|
|
2769
|
-
const normalizedDraft = normalizePurchaseDraftDates(cleanPurchaseDraftPayload(draft));
|
|
2778
|
+
const normalizedDraft = normalizePurchaseDraftDates(normalizePurchaseDraftMoney(cleanPurchaseDraftPayload(draft)));
|
|
2770
2779
|
assertPurchaseDraft(normalizedDraft);
|
|
2771
2780
|
const confirmedById = requiredId(scope.userId, '当前用户标识');
|
|
2772
2781
|
const confirmedAt = new Date();
|
|
@@ -2787,7 +2796,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
2787
2796
|
const lineRepo = manager.getRepository(PurchaseOrderLine);
|
|
2788
2797
|
for (let index = 0; index < normalizedDraft.lines.length; index += 1) {
|
|
2789
2798
|
const line = normalizedDraft.lines[index];
|
|
2790
|
-
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 }));
|
|
2791
2800
|
}
|
|
2792
2801
|
task.status = 'SUCCEEDED';
|
|
2793
2802
|
task.resultEntityId = entity.id;
|
|
@@ -3016,13 +3025,14 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3016
3025
|
await this.ensureProcurementSchema();
|
|
3017
3026
|
validatePurchaseLineDiscriminators(input);
|
|
3018
3027
|
const existing = await required(this.dataSource.getRepository(PurchaseOrderLine).findOne({ where: { ...activeScope(scope), id, deletedAt: IsNull() } }), '采购商品不存在');
|
|
3019
|
-
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']) };
|
|
3020
3029
|
validatePurchaseTaxRates(candidate, { purchaseOrderLineId: existing.id, lineNumber: existing.lineNumber, productName: candidate.productName });
|
|
3021
3030
|
if (new Decimal(candidate.quantity).lte(0))
|
|
3022
3031
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
|
|
3023
3032
|
const saved = await this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
|
|
3024
3033
|
const item = await required(Promise.resolve(lines.find(line => line.id === id) ?? null), '采购商品不存在');
|
|
3025
|
-
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);
|
|
3026
3036
|
item.lineAmountTaxIncluded = purchaseLineAmountText(item);
|
|
3027
3037
|
validatePurchaseLineDiscriminators(item);
|
|
3028
3038
|
const rates = validatePurchaseTaxRates(item, { purchaseOrderLineId: item.id, lineNumber: item.lineNumber, productName: item.productName });
|
|
@@ -3041,6 +3051,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3041
3051
|
}
|
|
3042
3052
|
async addPurchaseLine(scope, purchaseOrderId, input) {
|
|
3043
3053
|
await this.ensureProcurementSchema();
|
|
3054
|
+
input = normalizePurchaseLinePricing({ ...input });
|
|
3044
3055
|
validatePurchaseLineDiscriminators(input);
|
|
3045
3056
|
const discriminators = validatePurchaseLineDiscriminators({ ...input, sourceType: 'MANUAL_ENTRY', vatRateSource: input.vatRateSource ?? 'MANUAL' });
|
|
3046
3057
|
const rates = validatePurchaseTaxRates(input, { productName: input.productName });
|
|
@@ -3048,7 +3059,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3048
3059
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '采购商品数量必须大于 0');
|
|
3049
3060
|
const saved = await this.withLockedPurchaseLines(scope, purchaseOrderId, async ({ lineRepo, lines, contracts, customers, manuals }) => {
|
|
3050
3061
|
const lineNumber = lines.reduce((maximum, line) => Math.max(maximum, line.lineNumber), 0) + 1;
|
|
3051
|
-
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);
|
|
3052
3064
|
this.assertLockedPurchaseReceipts([...lines, item], contracts, customers, manuals);
|
|
3053
3065
|
return lineRepo.save(item);
|
|
3054
3066
|
});
|
|
@@ -3135,7 +3147,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3135
3147
|
* 客户级未收款总额(CNY):派生销售订单(客户合同组)各自 clamp 后汇总,超收不抵扣其他订单欠款。
|
|
3136
3148
|
* 口径与销售订单列表、分析看板一致:订单总额 = 人工覆盖值或商品行汇总,未收款 = max(总额 - 已收款, 0)。
|
|
3137
3149
|
*/
|
|
3138
|
-
async customerUnreceivedAmounts(scope, customerIds) {
|
|
3150
|
+
async customerUnreceivedAmounts(scope, customerIds, manager) {
|
|
3139
3151
|
const map = new Map();
|
|
3140
3152
|
const ids = [...new Set(customerIds)].filter(Boolean);
|
|
3141
3153
|
if (!ids.length)
|
|
@@ -3174,7 +3186,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3174
3186
|
SUM(GREATEST(sales_contract_totals."salesTotalCny" - sales_contract_totals."receivedCny", 0))::text AS "unreceivedCny"
|
|
3175
3187
|
FROM sales_contract_totals
|
|
3176
3188
|
GROUP BY sales_contract_totals."customerId"`;
|
|
3177
|
-
const rows = await this.dataSource.query(sql, parameters);
|
|
3189
|
+
const rows = await (manager ?? this.dataSource).query(sql, parameters);
|
|
3178
3190
|
for (const row of rows)
|
|
3179
3191
|
if (row?.customerId)
|
|
3180
3192
|
map.set(row.customerId, new Decimal(row.unreceivedCny ?? 0).toFixed(2));
|
|
@@ -3763,29 +3775,30 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3763
3775
|
await this.recalculateCompanyRisks(scope, 'SOURCE_CHANGED');
|
|
3764
3776
|
return saved;
|
|
3765
3777
|
}
|
|
3766
|
-
async listDerivedSalesOrders(scope, customerId, selectedIdentities) {
|
|
3767
|
-
const
|
|
3778
|
+
async listDerivedSalesOrders(scope, customerId, selectedIdentities, manager) {
|
|
3779
|
+
const source = manager ?? this.dataSource;
|
|
3780
|
+
const identities = selectedIdentities ?? await this.selectAllDerivedSalesOrderIdentities(scope, customerId, {}, false, manager);
|
|
3768
3781
|
if (!identities.length)
|
|
3769
3782
|
return [];
|
|
3770
3783
|
const contractIds = [...new Set(identities.map(identity => identity.customerContractId))];
|
|
3771
3784
|
const selectedContracts = new Set(identities.map(identity => identity.customerContractId));
|
|
3772
3785
|
const [customers, contracts, purchases, lines] = await Promise.all([
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
|
|
3776
|
-
|
|
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' } })
|
|
3777
3790
|
]);
|
|
3778
3791
|
const associatedPurchaseIds = purchases.filter(purchase => {
|
|
3779
3792
|
const baseCode = parsePurchaseContractNo(purchase.contractNo).baseCode;
|
|
3780
3793
|
return contracts.some(contract => selectedContracts.has(contract.id) && parseCustomerContractNo(contract.contractNo).baseCode === baseCode);
|
|
3781
3794
|
}).map(purchase => purchase.id);
|
|
3782
|
-
const manuals = associatedPurchaseIds.length ? await
|
|
3795
|
+
const manuals = associatedPurchaseIds.length ? await source.getRepository(DerivedSalesOrderManualData).find({ where: { ...activeScope(scope), customerContractId: In(contractIds), purchaseOrderId: In(associatedPurchaseIds), deletedAt: IsNull() } }) : [];
|
|
3783
3796
|
const customerMap = new Map(customers.map(customer => [customer.id, customer]));
|
|
3784
3797
|
const manualMap = new Map(manuals.map(manual => [derivedOrderKey(manual.customerContractId, manual.purchaseOrderId), manual]));
|
|
3785
3798
|
const linesByPurchase = groupBy(lines, line => line.purchaseOrderId);
|
|
3786
|
-
const riskRows = lines.length ? await
|
|
3799
|
+
const riskRows = lines.length ? await source.getRepository(ProductComplianceMatch).find({ where: { ...activeScope(scope), purchaseOrderLineId: In(lines.map(line => line.id)), deletedAt: IsNull() } }) : [];
|
|
3787
3800
|
const controlledGoodsIds = [...new Set(riskRows.map(match => match.controlledGoodsId))];
|
|
3788
|
-
const controlledGoods = controlledGoodsIds.length ? await
|
|
3801
|
+
const controlledGoods = controlledGoodsIds.length ? await source.getRepository(ControlledGoodsRecord).find({ where: { ...activeScope(scope), id: In(controlledGoodsIds), lifecycleStatus: 'ACTIVE', deletedAt: IsNull() } }) : [];
|
|
3789
3802
|
const controlledGoodsById = new Map(controlledGoods.map(item => [item.id, item]));
|
|
3790
3803
|
const risksByLine = groupBy(riskRows, match => match.purchaseOrderLineId);
|
|
3791
3804
|
const purchasesByBaseCode = groupBy(purchases, purchase => parsePurchaseContractNo(purchase.contractNo).baseCode);
|
|
@@ -3826,7 +3839,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3826
3839
|
const pricedLines = derivedLines.filter(line => line.pricingStatus === 'PRICED' && line.salesLineAmountCny != null);
|
|
3827
3840
|
const amount = manual?.orderAmountCnyOverride != null ? new Decimal(manual.orderAmountCnyOverride) : pricedLines.reduce((sum, line) => sum.plus(line.salesLineAmountCny ?? 0), new Decimal(0));
|
|
3828
3841
|
const received = new Decimal(manual?.receivedAmountCny ?? 0);
|
|
3829
|
-
results.push({ customerContractId: contract.id, purchaseOrderId: purchase.id, purchaseOrderIds: [purchase.id], purchaseContractNos: [purchase.contractNo], customerId: customer.id, salesOrderNo: contract.contractNo, customerContractNo: contract.contractNo, purchaseContractNo: purchase.contractNo, orderDate: purchase.orderDate, currencyCode: 'CNY', pricingProfitRateSource: orderPricingSource(derivedLines, manual?.pricingProfitRateOverride, customer.pricingProfitRateStatus === 'CONFIGURED' ? customer.defaultPricingProfitRate : null), effectivePricingProfitRate: effectiveRate, pricingStatus: orderPricingStatus(derivedLines), missingPricingFields: orderMissingPricingFields(derivedLines), orderAmountCny: amount.toFixed(manual?.orderAmountCnyOverride != null ? 4 :
|
|
3842
|
+
results.push({ customerContractId: contract.id, purchaseOrderId: purchase.id, purchaseOrderIds: [purchase.id], purchaseContractNos: [purchase.contractNo], customerId: customer.id, salesOrderNo: contract.contractNo, customerContractNo: contract.contractNo, purchaseContractNo: purchase.contractNo, orderDate: purchase.orderDate, currencyCode: 'CNY', hasManualOrderAmount: manual?.orderAmountCnyOverride != null, pricingProfitRateSource: orderPricingSource(derivedLines, manual?.pricingProfitRateOverride, customer.pricingProfitRateStatus === 'CONFIGURED' ? customer.defaultPricingProfitRate : null), effectivePricingProfitRate: effectiveRate, pricingStatus: orderPricingStatus(derivedLines), missingPricingFields: orderMissingPricingFields(derivedLines), orderAmountCny: amount.toFixed(manual?.orderAmountCnyOverride != null ? 4 : 2), receivedAmountCny: received.toFixed(2), unreceivedAmountCny: Decimal.max(amount.minus(received), 0).toFixed(2), lines: derivedLines });
|
|
3830
3843
|
}
|
|
3831
3844
|
}
|
|
3832
3845
|
const grouped = new Map();
|
|
@@ -3839,7 +3852,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3839
3852
|
existing.purchaseOrderIds = [...(existing.purchaseOrderIds ?? [existing.purchaseOrderId]), item.purchaseOrderId];
|
|
3840
3853
|
existing.purchaseContractNos = [...new Set([...(existing.purchaseContractNos ?? [existing.purchaseContractNo]), item.purchaseContractNo])];
|
|
3841
3854
|
existing.lines.push(...item.lines);
|
|
3842
|
-
existing.
|
|
3855
|
+
existing.hasManualOrderAmount = existing.hasManualOrderAmount || item.hasManualOrderAmount;
|
|
3856
|
+
existing.orderAmountCny = new Decimal(existing.orderAmountCny).plus(item.orderAmountCny).toFixed(2);
|
|
3843
3857
|
existing.receivedAmountCny = new Decimal(existing.receivedAmountCny).plus(item.receivedAmountCny).toFixed(2);
|
|
3844
3858
|
existing.unreceivedAmountCny = Decimal.max(new Decimal(existing.orderAmountCny).minus(existing.receivedAmountCny), 0).toFixed(2);
|
|
3845
3859
|
if (item.orderDate && (!existing.orderDate || item.orderDate < existing.orderDate))
|
|
@@ -3864,8 +3878,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3864
3878
|
}
|
|
3865
3879
|
return [...grouped.values()].sort(compareDerivedSalesOrders);
|
|
3866
3880
|
}
|
|
3867
|
-
derivedSalesIdentityQuery(scope, customerId, parameters, includeParties) {
|
|
3868
|
-
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')
|
|
3869
3883
|
.innerJoin(Customer, 'customer', 'customer.id = contract."customerId" AND customer."tenantId" = contract."tenantId" AND customer."organizationId" = contract."organizationId" AND customer."deletedAt" IS NULL')
|
|
3870
3884
|
.innerJoin(PurchaseOrder, 'purchase', `purchase."tenantId" = contract."tenantId" AND purchase."organizationId" = contract."organizationId" AND purchase."deletedAt" IS NULL AND ${derivedSalesContractLinkSql('contract', 'purchase')}`)
|
|
3871
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')
|
|
@@ -3900,8 +3914,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
3900
3914
|
qb.andWhere(`${received} >= ${amount}`);
|
|
3901
3915
|
return qb;
|
|
3902
3916
|
}
|
|
3903
|
-
async selectAllDerivedSalesOrderIdentities(scope, customerId, parameters, includeParties) {
|
|
3904
|
-
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();
|
|
3905
3919
|
const seen = new Set();
|
|
3906
3920
|
return rows.filter(row => { if (seen.has(row.customerContractId))
|
|
3907
3921
|
return false; seen.add(row.customerContractId); return true; });
|
|
@@ -4054,6 +4068,8 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4054
4068
|
if (entity === PurchaseOrderLine)
|
|
4055
4069
|
return this.deletePurchaseLine(scope, id);
|
|
4056
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]);
|
|
4057
4073
|
if (entity === Customer) {
|
|
4058
4074
|
const count = await manager.getRepository(CustomerContract).count({ where: { ...activeScope(scope), customerId: id, deletedAt: IsNull() } });
|
|
4059
4075
|
if (count)
|
|
@@ -4067,6 +4083,10 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4067
4083
|
const repo = manager.getRepository(entity);
|
|
4068
4084
|
const lifecycle = entity === ControlledGoodsRecord || entity === SanctionedCompanyRecord ? { lifecycleStatus: 'ACTIVE' } : {};
|
|
4069
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 });
|
|
4070
4090
|
const now = new Date();
|
|
4071
4091
|
target.deletedAt = now;
|
|
4072
4092
|
target.deletedById = scope.userId ?? null;
|
|
@@ -4135,7 +4155,15 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4135
4155
|
const scoped = activeScope(scope);
|
|
4136
4156
|
const company = await manager.getRepository(CompanySettings).findOne({ where: scoped });
|
|
4137
4157
|
const assets = await manager.getRepository(ManagedAsset).find({ where: scoped });
|
|
4138
|
-
const
|
|
4158
|
+
const catalogTypes = ['CONTROLLED_CATALOG', 'SANCTION_CATALOG'];
|
|
4159
|
+
// Keep the entire catalog provenance chain, including active imports and
|
|
4160
|
+
// historical source files, when resetting transactional business data.
|
|
4161
|
+
const catalogSources = [
|
|
4162
|
+
...await manager.getRepository(ControlledCatalogBatch).find({ where: scoped }),
|
|
4163
|
+
...await manager.getRepository(SanctionCatalogBatch).find({ where: scoped }),
|
|
4164
|
+
...await manager.getRepository(ImportTask).find({ where: { ...scoped, documentType: In([...catalogTypes]) } })
|
|
4165
|
+
];
|
|
4166
|
+
const preservedStorageIds = new Set([BUILTIN_COMPANY_LOGO_STORAGE_ID, company?.logoFileId, ...catalogSources.map(item => item.sourceFileId)].filter((id) => Boolean(id)));
|
|
4139
4167
|
const removableAssets = assets.filter(asset => !preservedStorageIds.has(asset.storageFileId));
|
|
4140
4168
|
const deleted = {};
|
|
4141
4169
|
const remove = async (name, entity) => {
|
|
@@ -4146,6 +4174,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4146
4174
|
await remove('customerContractAnalysisRun', CustomerContractAnalysisRun);
|
|
4147
4175
|
await remove('customerContractClause', CustomerContractClause);
|
|
4148
4176
|
await remove('derivedSalesOrderManualData', DerivedSalesOrderManualData);
|
|
4177
|
+
await remove('salesFileGenerationTask', SalesFileGenerationTask);
|
|
4149
4178
|
await remove('generatedSalesFile', GeneratedSalesFile);
|
|
4150
4179
|
await remove('customerContract', CustomerContract);
|
|
4151
4180
|
await remove('customer', Customer);
|
|
@@ -4156,16 +4185,9 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4156
4185
|
await remove('purchaseOrder', PurchaseOrder);
|
|
4157
4186
|
await remove('supplier', Supplier);
|
|
4158
4187
|
await remove('companySanctionMatch', CompanySanctionMatch);
|
|
4159
|
-
await remove('sanctionedCompanyAlias', SanctionedCompanyAlias);
|
|
4160
|
-
await remove('sanctionCatalogImportIssue', SanctionCatalogImportIssue);
|
|
4161
|
-
await remove('sanctionedCompanyRecord', SanctionedCompanyRecord);
|
|
4162
|
-
await remove('sanctionCatalogBatch', SanctionCatalogBatch);
|
|
4163
|
-
await remove('controlledCatalogImportIssue', ControlledCatalogImportIssue);
|
|
4164
|
-
await remove('catalogReviewBlock', CatalogReviewBlock);
|
|
4165
|
-
await remove('controlledGoodsRecord', ControlledGoodsRecord);
|
|
4166
|
-
await remove('controlledCatalogBatch', ControlledCatalogBatch);
|
|
4167
4188
|
await remove('hsCodeReferenceSnapshot', HsCodeReferenceSnapshot);
|
|
4168
|
-
await
|
|
4189
|
+
const tasks = await manager.getRepository(ImportTask).delete({ ...scoped, documentType: Not(In([...catalogTypes])) });
|
|
4190
|
+
deleted.importTask = tasks.affected ?? 0;
|
|
4169
4191
|
await remove('demoDataSeedMarker', DemoDataSeedMarker);
|
|
4170
4192
|
for (const asset of removableAssets)
|
|
4171
4193
|
await manager.getRepository(ManagedAsset).delete({ ...scoped, id: asset.id });
|
|
@@ -4825,6 +4847,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4825
4847
|
}
|
|
4826
4848
|
async withLockedPurchaseLines(scope, purchaseOrderId, callback) {
|
|
4827
4849
|
return this.dataSource.transaction(async (manager) => {
|
|
4850
|
+
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
4828
4851
|
const purchaseRepo = manager.getRepository(PurchaseOrder);
|
|
4829
4852
|
const preview = await required(purchaseRepo.findOne({ where: { ...activeScope(scope), id: purchaseOrderId, deletedAt: IsNull() } }), '采购订单不存在');
|
|
4830
4853
|
const baseCode = parsePurchaseContractNo(preview.contractNo).baseCode;
|
|
@@ -4862,6 +4885,7 @@ let TradeComplianceWorkbenchService = class TradeComplianceWorkbenchService {
|
|
|
4862
4885
|
return this.withLockedPurchaseLines(scope, existing.purchaseOrderId, async ({ manager, lineRepo, lines, contracts, customers, manuals }) => {
|
|
4863
4886
|
const row = await required(Promise.resolve(lines.find(line => line.id === id) ?? null), '记录不存在');
|
|
4864
4887
|
this.assertLockedPurchaseReceipts(lines.filter(line => line.id !== id), contracts, customers, manuals);
|
|
4888
|
+
await cancelSalesFileGenerationTasks(manager, scope, { purchaseOrderId: existing.purchaseOrderId });
|
|
4865
4889
|
row.deletedAt = new Date();
|
|
4866
4890
|
row.deletedById = scope.userId ?? null;
|
|
4867
4891
|
row.deleteOperation = 'USER_DELETE';
|
|
@@ -5309,11 +5333,11 @@ function beijingDateOf(value) {
|
|
|
5309
5333
|
return null;
|
|
5310
5334
|
return new Intl.DateTimeFormat('en-CA', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit' }).format(date);
|
|
5311
5335
|
}
|
|
5312
|
-
function derivedOrderAmount(lines, rate) { return lines.reduce((total, line) => total.plus(deriveSalesLine({ purchaseUnitPriceCny: line.unitPriceTaxIncluded, quantity: line.quantity }, rate).salesLineAmountCny), new Decimal(0)).toFixed(
|
|
5336
|
+
function derivedOrderAmount(lines, rate) { return lines.reduce((total, line) => total.plus(deriveSalesLine({ purchaseUnitPriceCny: line.unitPriceTaxIncluded, quantity: line.quantity }, rate).salesLineAmountCny), new Decimal(0)).toFixed(2); }
|
|
5313
5337
|
function derivedSalesOrderAmountSql(lineAlias, overridesExpression, effectiveRateExpression) {
|
|
5314
5338
|
const override = `${overridesExpression} -> ${lineAlias}.id::text`;
|
|
5315
5339
|
const lineRate = `COALESCE(NULLIF(BTRIM(${override}->>'pricingProfitRate'), '')::numeric, ${effectiveRateExpression})`;
|
|
5316
|
-
const lineAmount = `COALESCE(NULLIF(BTRIM(${override}->>'salesLineAmountCny'), '')::numeric, NULLIF(BTRIM(${override}->>'salesUnitPriceCny'), '')::numeric * ${lineAlias}.quantity, CASE WHEN COALESCE(${override}->>'pricingMethod', 'TAX_INCLUDED_MARKUP') = 'TAX_INCLUDED_MARKUP' AND ${lineAlias}."unitPriceTaxIncluded" IS NOT NULL AND ${lineRate} IS NOT NULL THEN ROUND(ROUND(${lineAlias}."unitPriceTaxIncluded" * (1 + ${lineRate}),
|
|
5340
|
+
const lineAmount = `COALESCE(NULLIF(BTRIM(${override}->>'salesLineAmountCny'), '')::numeric, NULLIF(BTRIM(${override}->>'salesUnitPriceCny'), '')::numeric * ${lineAlias}.quantity, CASE WHEN COALESCE(${override}->>'pricingMethod', 'TAX_INCLUDED_MARKUP') = 'TAX_INCLUDED_MARKUP' AND ${lineAlias}."unitPriceTaxIncluded" IS NOT NULL AND ${lineRate} IS NOT NULL THEN ROUND(ROUND(${lineAlias}."unitPriceTaxIncluded" * (1 + ${lineRate}), 2) * ${lineAlias}.quantity, 2) ELSE NULL END, 0)`;
|
|
5317
5341
|
return `COALESCE(manual."orderAmountCnyOverride", (SELECT COALESCE(SUM(${lineAmount}), 0) FROM plugin_trade_compliance_purchase_order_line ${lineAlias} WHERE ${lineAlias}."purchaseOrderId" = purchase.id AND ${lineAlias}."tenantId" = purchase."tenantId" AND ${lineAlias}."organizationId" = purchase."organizationId" AND ${lineAlias}."deletedAt" IS NULL))`;
|
|
5318
5342
|
}
|
|
5319
5343
|
function linePricingOverrides(value) {
|
|
@@ -5503,6 +5527,22 @@ async function required(promise, message) { const value = await promise; if (!va
|
|
|
5503
5527
|
throw new DomainError(DomainErrorCodes.NOT_FOUND, message); return value; }
|
|
5504
5528
|
function pick(input, keys) { return Object.fromEntries(keys.filter(key => key in input).map(key => [key, input[key]])); }
|
|
5505
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
|
+
}
|
|
5506
5546
|
function normalizePurchaseDraftDates(draft) {
|
|
5507
5547
|
return {
|
|
5508
5548
|
...draft,
|
|
@@ -5520,7 +5560,7 @@ function normalizeOptionalDateString(value, label) {
|
|
|
5520
5560
|
if (!hasQueryValue(value))
|
|
5521
5561
|
return null;
|
|
5522
5562
|
const text = String(value).trim();
|
|
5523
|
-
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*(?:日)?$/);
|
|
5524
5564
|
if (!matched)
|
|
5525
5565
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${label}格式无效,请使用 YYYY-MM-DD`);
|
|
5526
5566
|
const [, rawYear, rawMonth, rawDay] = matched;
|
|
@@ -5533,6 +5573,35 @@ function normalizeOptionalDateString(value, label) {
|
|
|
5533
5573
|
}
|
|
5534
5574
|
return `${rawYear}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
|
|
5535
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
|
+
}
|
|
5536
5605
|
function assertPurchaseDraft(draft) {
|
|
5537
5606
|
if (!hasQueryValue(draft.supplier?.name))
|
|
5538
5607
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商名称为必填项');
|
|
@@ -5569,6 +5638,11 @@ function assertPurchaseDraft(draft) {
|
|
|
5569
5638
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}退税政策日期不得晚于下单日期`);
|
|
5570
5639
|
if (hasQueryValue(line.refundValidationMethod) && !RefundValidationMethods.some(method => method === line.refundValidationMethod))
|
|
5571
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}参考单价不能为负数`);
|
|
5572
5646
|
validatePurchaseLineDiscriminators({ ...line, sourceType: line.sourceType ?? 'CONTRACT_EXTRACTED' });
|
|
5573
5647
|
if (line.amountMismatch === true && line.amountMismatchConfirmed !== true)
|
|
5574
5648
|
throw new DomainError(DomainErrorCodes.INVALID_INPUT, `${prefix}金额差异必须确认`);
|
|
@@ -5614,7 +5688,7 @@ function purchaseLineAmountText(line) {
|
|
|
5614
5688
|
}
|
|
5615
5689
|
function purchaseLineMetricAmount(line) {
|
|
5616
5690
|
const lineAmount = optionalDecimalInput(line.lineAmountTaxIncluded, '采购商品含税金额必须为有效金额') ?? new Decimal(0);
|
|
5617
|
-
if (
|
|
5691
|
+
if (hasQueryValue(line.lineAmountTaxIncluded))
|
|
5618
5692
|
return lineAmount;
|
|
5619
5693
|
const quantity = optionalDecimalInput(line.quantity, '采购商品数量必须为有效数值');
|
|
5620
5694
|
const unitPrice = optionalDecimalInput(line.unitPriceTaxIncluded, '采购商品含税单价必须为有效金额');
|