@chenchaolong/plugin-trade-compliance-workbench 1.0.210 → 1.0.211
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.js +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/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 +10 -1
- 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/remote-components/trade-compliance-workbench/app.css +1 -1
- package/dist/lib/remote-components/trade-compliance-workbench/app.js +5 -5
- package/dist/lib/remote-ui/action-execution.d.ts.map +1 -1
- package/dist/lib/remote-ui/action-execution.js +5 -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 +15 -9
- package/dist/lib/remote-ui/app-source.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/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/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 +36 -12
- package/dist/lib/remote-ui/pages/files.js.map +1 -1
- package/dist/lib/remote-ui/pages/sales.d.ts +18 -5
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +49 -10
- 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/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/sales-file.service.d.ts.map +1 -1
- package/dist/lib/sales-file.service.js +117 -31
- package/dist/lib/sales-file.service.js.map +1 -1
- package/dist/lib/supplier-materials/generation-materials.d.ts +49 -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 +125 -0
- package/dist/lib/supplier-materials/supplier-materials.js.map +1 -0
- package/dist/lib/types.d.ts +22 -3
- 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 +5 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts +2 -0
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +19 -6
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +118 -0
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +1 -0
- package/dist/lib/workbench.middleware.js.map +1 -1
- package/dist/lib/workbench.service.d.ts +95 -0
- package/dist/lib/workbench.service.d.ts.map +1 -1
- package/dist/lib/workbench.service.js +26 -17
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { generationMaterials } from './supplier-materials/generation-materials.js';
|
|
2
3
|
import { Injectable, Optional } from '@nestjs/common';
|
|
3
4
|
import { InjectDataSource } from '@nestjs/typeorm';
|
|
4
5
|
import { DataSource, In, IsNull } from 'typeorm';
|
|
@@ -55,6 +56,11 @@ let SalesFileService = class SalesFileService {
|
|
|
55
56
|
const needsPacking = ['CI', 'PL', 'PI_CI_PL', 'ALL', 'CUSTOMS_DECLARATION'].includes(input.fileType);
|
|
56
57
|
const packingData = needsPacking ? await this.loadPackingData(scope, evaluated.derived.purchaseOrderIds?.length ? evaluated.derived.purchaseOrderIds : [input.purchaseOrderId], input) : null;
|
|
57
58
|
const result = preflightResult(input, evaluated.compliance.complianceProfitRate.toString(), evaluated.exchangeCost?.toString() ?? null, evaluated.warnings, packing);
|
|
59
|
+
const materialDocs = await this.workbench.loadSupplierMaterials?.(scope, evaluated.derived.purchaseOrderIds ?? [input.purchaseOrderId]) ?? [];
|
|
60
|
+
const materialWarnings = generationMaterials(evaluated.purchaseLines, materialDocs).warnings.filter(warning => !warning.code.startsWith('CUSTOMS_') || ['CUSTOMS_DECLARATION', 'ALL'].includes(input.fileType));
|
|
61
|
+
if (materialWarnings.length)
|
|
62
|
+
result.materialWarnings = materialWarnings;
|
|
63
|
+
result.documentPricing = evaluated.documentPricing;
|
|
58
64
|
result.packingWarnings = packingData?.warnings ?? [];
|
|
59
65
|
result.packingMode = input.packingMode ?? 'DRAFT';
|
|
60
66
|
if (needsPacking && this.packingService)
|
|
@@ -70,7 +76,7 @@ let SalesFileService = class SalesFileService {
|
|
|
70
76
|
}
|
|
71
77
|
async generate(scope, input, context) {
|
|
72
78
|
const evaluated = await this.evaluate(scope, input);
|
|
73
|
-
const { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants } = evaluated;
|
|
79
|
+
const { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing } = evaluated;
|
|
74
80
|
const generationWarnings = [...warnings];
|
|
75
81
|
if (['PI', 'CI', 'PI_CI_PL', 'ALL'].includes(input.fileType) && paymentTermsVariants && paymentTermsVariants.length > 1)
|
|
76
82
|
generationWarnings.push({ code: 'PAYMENT_TERMS_VARY', message: `各订单付款条款不一致,已使用订单 ${orders[0].salesOrderNo} 的付款条款(${paymentTermsVariants[0]}),其余为:${paymentTermsVariants.slice(1).join(';')},请人工核对文件条款` });
|
|
@@ -87,23 +93,30 @@ let SalesFileService = class SalesFileService {
|
|
|
87
93
|
const packing = needsPacking ? await this.loadPackingData(scope, purchaseIds, input) : null;
|
|
88
94
|
if (needsPacking && !packing?.shipmentOnly)
|
|
89
95
|
generationWarnings.push({ code: 'PACKING_ORDER_BASIS', message: '尚无已选定的装箱数据,本文件暂按订单商品数量生成;请按实际发货情况人工核对数量和包装信息。' });
|
|
90
|
-
const
|
|
96
|
+
const materialDocuments = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds) ?? [];
|
|
97
|
+
const materialData = generationMaterials(purchaseLines, materialDocuments);
|
|
98
|
+
generationWarnings.push(...materialData.warnings);
|
|
99
|
+
const materialsFingerprint = createHash('sha256').update(JSON.stringify(materialDocuments)).digest('hex');
|
|
100
|
+
const translated = await this.translateDynamicFields(scope, customer, materialData.englishLines, clauses, generationWarnings, input.fileType, packing);
|
|
91
101
|
const packingTranslated = translated;
|
|
92
102
|
if (packing)
|
|
93
103
|
generationWarnings.push(...this.packingWarningsForPl(derived, packing));
|
|
94
104
|
const mergedOrderRefs = orders.length > 1 ? orders.map(order => ({ customerContractId: order.customerContractId, purchaseOrderId: order.purchaseOrderId, salesOrderNo: order.salesOrderNo })) : null;
|
|
95
|
-
const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses })).digest('hex');
|
|
105
|
+
const orderDataFingerprint = createHash('sha256').update(JSON.stringify({ derived, customer, company, bank, clauses, documentPricing, materialsFingerprint })).digest('hex');
|
|
96
106
|
const shipmentReference = `SHIP-${createHash('sha256').update(`${ordersKey}:${packing?.fingerprint ?? ''}:${orderDataFingerprint}`).digest('hex').slice(0, 16)}`;
|
|
97
107
|
const batchGenerationId = input.fileType === 'ALL' ? randomUUID() : undefined;
|
|
98
108
|
const newStorageFileIds = [];
|
|
99
109
|
try {
|
|
100
110
|
const files = await this.dataSource.transaction(async (manager) => {
|
|
101
111
|
const repo = manager.getRepository(GeneratedSalesFile);
|
|
102
|
-
if (needsPacking) {
|
|
112
|
+
if (needsPacking || typeof this.workbench.loadSupplierMaterials === 'function') {
|
|
103
113
|
// Serialize with uploads, import persistence and packing edits. Translation may
|
|
104
114
|
// have taken time since preflight: never commit a stale shipment snapshot.
|
|
105
115
|
await manager.query('SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))', [scope.tenantId, scope.organizationId]);
|
|
106
|
-
const
|
|
116
|
+
const currentMaterials = await this.workbench.loadSupplierMaterials?.(scope, purchaseIds, manager) ?? [];
|
|
117
|
+
if (createHash('sha256').update(JSON.stringify(currentMaterials)).digest('hex') !== materialsFingerprint)
|
|
118
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '供应商资料已变化,请重新生成文件');
|
|
119
|
+
const currentPacking = needsPacking ? await this.loadPackingData(scope, purchaseIds, input, manager) : null;
|
|
107
120
|
for (const warning of currentPacking?.warnings ?? [])
|
|
108
121
|
if (!generationWarnings.some(existing => existing.code === warning.code && existing.message === warning.message))
|
|
109
122
|
generationWarnings.push(warning);
|
|
@@ -120,16 +133,20 @@ let SalesFileService = class SalesFileService {
|
|
|
120
133
|
}
|
|
121
134
|
const candidates = ['PI_CI_PL', 'ALL'].includes(input.fileType) ? await repo.find({ where: { ...scoped(scope), customerContractId: customerContract.id, purchaseOrderId: purchaseOrder.id, fileType: In(requestedTypes), deletedAt: IsNull() }, order: { generatedAt: 'DESC' }, lock: { mode: 'pessimistic_write' } }) : [];
|
|
122
135
|
// Local-only historical results must not keep a new workspace generation pinned to a missing container file.
|
|
123
|
-
const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey }));
|
|
136
|
+
const matching = candidates.filter(item => (input.fileType !== 'ALL' || item.generationSnapshot?.shipment?.reference === shipmentReference) && (context === undefined || item.storageFileId.startsWith('workspace-sales:v1:')) && generationRequestMatches(item, { fileNumber, templateVersion, remarks, bankType, lineIds: derived.lines.map(line => line.purchaseOrderLineId), packingFingerprint: packing?.fingerprint ?? '', orderDataFingerprint, ordersKey, currencyCode: documentPricing.currencyCode }));
|
|
124
137
|
const existing = input.fileType === 'ALL' ? completeFileBatch(matching, requestedTypes) : matching;
|
|
125
138
|
const existingByType = new Map(existing.map(item => [item.fileType, item]));
|
|
126
139
|
const missingTypes = requestedTypes.filter(fileType => !existingByType.has(fileType));
|
|
127
140
|
const created = [];
|
|
128
141
|
for (const fileType of missingTypes) {
|
|
129
142
|
const fileTranslated = fileType === 'PL' ? packingTranslated : translated;
|
|
130
|
-
const
|
|
143
|
+
const sourceDerived = fileType === 'CUSTOMS_DECLARATION' ? { ...derived, lines: derived.lines.map((line, index) => ({ ...line, hsCode: materialData.customsLines[index].hsCode })) } : derived;
|
|
144
|
+
const fileDerived = shipmentDerived(sourceDerived, packing, fileType);
|
|
145
|
+
const filePurchaseLines = fileType === 'CUSTOMS_DECLARATION' ? materialData.customsLines : purchaseLines;
|
|
131
146
|
const fileWarnings = generationWarnings.filter(warning => {
|
|
132
147
|
const field = String(warning.field ?? '');
|
|
148
|
+
if (String(warning.code ?? '').startsWith('CUSTOMS_') && fileType !== 'CUSTOMS_DECLARATION')
|
|
149
|
+
return false;
|
|
133
150
|
if (fileType === 'CUSTOMS_DECLARATION' && (String(warning.code ?? '').startsWith('TRANSLATION_') || warning.code === 'SOURCE_FIELD_REVIEW'))
|
|
134
151
|
return false;
|
|
135
152
|
if (field.startsWith('packing.'))
|
|
@@ -140,10 +157,10 @@ let SalesFileService = class SalesFileService {
|
|
|
140
157
|
});
|
|
141
158
|
if (fileType === 'CUSTOMS_DECLARATION')
|
|
142
159
|
fileWarnings.push({ code: 'CUSTOMS_ELEMENTS_REVIEW', message: '商品描述仅使用已知信息,申报要素、法定计量单位等请人工补全;本文件尚未提交海关。' });
|
|
143
|
-
const request = { ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: '2026-10-19.1', shipmentDocumentsVersion: 'v2', orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: 'v10' } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
|
|
144
|
-
const snapshot = { version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines:
|
|
160
|
+
const request = { currencyCode: documentPricing.currencyCode, ...(batchGenerationId ? { batchGenerationId } : {}), exportIntegrityVersion: '2026-10-19.1', shipmentDocumentsVersion: 'v2', orderDataFingerprint, templateVersion, fileNumber, remarks, bankType, ...(needsPacking ? { packingMode: input.packingMode ?? 'DRAFT', packingIds: packing?.batchIds ?? [] } : {}), ...(fileType === 'PL' ? { packingLayoutVersion: 'v10' } : {}), packingFingerprint: packing?.fingerprint ?? '', ordersKey };
|
|
161
|
+
const snapshot = { materials: materialData.sources, materialsFingerprint, version: 'v1', generatedAt: generatedAt.toISOString(), fileType, request, orders, documentPricing, customer: { ...customer }, customerContract: { ...customerContract }, purchaseOrder: { ...purchaseOrder }, purchaseLines: filePurchaseLines.map(item => ({ ...item })), derived: fileDerived, shipment: { reference: shipmentReference, orders, packingIds: packing?.batchIds ?? [], status: 'PENDING_REVIEW' }, company: company ? { ...company } : null, bank: bank ? { ...bank } : null, clauses: clauses.map(item => ({ ...item })), translated: fileTranslated, packing: packing ? { ...packing, mode: input.packingMode ?? 'DRAFT', shipmentLines: derived.lines.filter(line => (packing.byPurchaseLine[line.purchaseOrderLineId]?.shippedQty ?? 0) > 0).map(line => ({ purchaseOrderLineId: line.purchaseOrderLineId, quantity: String(packing.byPurchaseLine[line.purchaseOrderLineId].shippedQty) })) } : null, compliance: { profitCny: compliance.profitCny.toString(), complianceProfitRate: compliance.complianceProfitRate.toString() }, exchangeRate: exchangeRate ? { ...exchangeRate } : null, exchangeCost: exchangeCost?.toString() ?? null, rule: { ...rule } };
|
|
145
162
|
const logo = await this.readCompanyLogo(scope, fileType, company?.logoFileId);
|
|
146
|
-
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, generationWarnings: fileWarnings }, logo);
|
|
163
|
+
const buffer = await this.fillWorkbook(fileType, { snapshot, customer, customerContract, purchaseOrder, purchaseLines: filePurchaseLines, derived: fileDerived, company, bank, clauses, translated: fileTranslated, packing, generationWarnings: fileWarnings }, logo);
|
|
147
164
|
await validateWorkbook(buffer);
|
|
148
165
|
const documentNo = fileType === 'PI' || fileType === 'CI' ? fileNumber !== derived.salesOrderNo ? fileNumber : salesDocumentNo(derived.salesOrderNo, fileType, customer.name) : null;
|
|
149
166
|
const fileName = `${fileNumber}-${salesFileNameTypeLabels[fileType]}-${beijingFileTimestamp(generatedAt)}.xlsx`;
|
|
@@ -165,6 +182,9 @@ let SalesFileService = class SalesFileService {
|
|
|
165
182
|
}
|
|
166
183
|
async evaluate(scope, input) {
|
|
167
184
|
// 合并生成:orders 指定同客户的多个销售订单(合同+采购单);缺省退化为单订单生成
|
|
185
|
+
const currencyCode = input.currencyCode ?? 'CNY';
|
|
186
|
+
if (currencyCode !== 'CNY' && currencyCode !== 'USD')
|
|
187
|
+
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '文件币种仅支持 CNY 或 USD');
|
|
168
188
|
const orderRefs = normalizeGenerationOrders(input);
|
|
169
189
|
const allDerived = await this.workbench.listDerivedSalesOrders(scope);
|
|
170
190
|
const orderEntries = orderRefs.map(ref => {
|
|
@@ -209,10 +229,10 @@ let SalesFileService = class SalesFileService {
|
|
|
209
229
|
throw new DomainError(DomainErrorCodes.CREDIT_LIMIT_EXCEEDED, `客户「${customer.name}」已超出信用额度,无法生成销售文件:信用额度 ${new Decimal(customer.creditLimit).toFixed(2)} CNY,未收款总额 ${unreceivedAmountCny} CNY,剩余 ${remainingCreditCny.toFixed(2)} CNY。请先回收货款或上调信用额度`, { customerId: customer.id, customerName: customer.name, creditLimit: customer.creditLimit, unreceivedAmountCny, remainingCreditCny: remainingCreditCny.toFixed(2) });
|
|
210
230
|
}
|
|
211
231
|
}
|
|
212
|
-
const
|
|
232
|
+
const purchaseIds = [...new Set(orderEntries.flatMap(entry => entry.derived.purchaseOrderIds?.length ? entry.derived.purchaseOrderIds : [entry.ref.purchaseOrderId]))];
|
|
233
|
+
const purchaseOrderEntities = await Promise.all(purchaseIds.map(id => this.required(PurchaseOrder, scope, id, '采购订单不存在')));
|
|
213
234
|
const purchaseOrder = purchaseOrderEntities.find(item => item.id === primary.ref.purchaseOrderId);
|
|
214
235
|
const purchaseOrderDates = new Map(purchaseOrderEntities.map(item => [item.id, item.orderDate]));
|
|
215
|
-
const purchaseIds = [...new Set(orderEntries.flatMap(entry => entry.derived.purchaseOrderIds?.length ? entry.derived.purchaseOrderIds : [entry.ref.purchaseOrderId]))];
|
|
216
236
|
const sourcePurchaseLines = await this.dataSource.getRepository(PurchaseOrderLine).find({ where: { tenantId: scope.tenantId, organizationId: scope.organizationId, purchaseOrderId: In(purchaseIds), deletedAt: IsNull() }, order: { purchaseOrderId: 'ASC', lineNumber: 'ASC' } });
|
|
217
237
|
const purchaseLinesById = new Map(sourcePurchaseLines.map(line => [line.id, line]));
|
|
218
238
|
const lineIds = orderEntries.flatMap(entry => entry.derived.lines.map(line => line.purchaseOrderLineId));
|
|
@@ -251,20 +271,51 @@ let SalesFileService = class SalesFileService {
|
|
|
251
271
|
const compliance = summarizeCompliance(complianceInputs);
|
|
252
272
|
const orderedDerivedLines = purchaseLines.map(line => derivedLines.get(line.id) ?? { purchaseOrderLineId: line.id, productName: line.productName });
|
|
253
273
|
const warnings = negativeProfitWarnings(compliance.lines, orderedDerivedLines);
|
|
274
|
+
for (const entry of orderEntries)
|
|
275
|
+
if (entry.derived.hasManualOrderAmount) {
|
|
276
|
+
const lineTotal = entry.derived.lines.reduce((sum, line) => sum.plus(line.salesLineAmountCny ?? 0), new Decimal(0));
|
|
277
|
+
if (!lineTotal.toDecimalPlaces(2).eq(new Decimal(entry.derived.orderAmountCny).toDecimalPlaces(2)))
|
|
278
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.SALES_PRICING_REQUIRED, `手工维护的订单总额 ${entry.derived.orderAmountCny} CNY 与商品明细合计 ${lineTotal.toFixed(2)} CNY 不一致,请调整商品定价或清除总额覆盖后重新生成`, { orderAmountCny: entry.derived.orderAmountCny, lineTotalCny: lineTotal.toFixed(2) }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
279
|
+
}
|
|
280
|
+
// Document pricing is separate from the internal CNY accounting and compliance basis.
|
|
281
|
+
const monthlyRates = new Map();
|
|
282
|
+
const requireRate = async (orderDate, purchaseOrderId) => {
|
|
283
|
+
const month = strictOrderMonth(orderDate, purchaseOrderId);
|
|
284
|
+
let rate = monthlyRates.get(month);
|
|
285
|
+
if (!rate) {
|
|
286
|
+
const [year, monthNumber] = month.split('-').map(Number);
|
|
287
|
+
const found = await this.dataSource.getRepository(MonthlySafeExchangeRate).findOne({ where: { ...scoped(scope), year, month: monthNumber, currencyCode: 'USD', deletedAt: IsNull() } });
|
|
288
|
+
if (!found)
|
|
289
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `缺少 ${month} 月外汇管理局首日美元汇率(1 USD = X CNY)`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
290
|
+
try {
|
|
291
|
+
parseExchangeRateInput(found);
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `${month} 月美元汇率无效,请维护有效的月度美元汇率`, { orderDate, month, purchaseOrderId }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
295
|
+
}
|
|
296
|
+
rate = found;
|
|
297
|
+
monthlyRates.set(month, rate);
|
|
298
|
+
}
|
|
299
|
+
return { month, rate };
|
|
300
|
+
};
|
|
301
|
+
const documentLines = [];
|
|
302
|
+
for (const line of purchaseLines) {
|
|
303
|
+
const pricing = derivedLines.get(line.id);
|
|
304
|
+
const fx = currencyCode === 'USD' ? await requireRate(purchaseOrderDates.get(line.purchaseOrderId), line.purchaseOrderId) : null;
|
|
305
|
+
const unitPrice = new Decimal(pricing.salesUnitPriceCny ?? 0).div(fx?.rate.usdToCnyRate ?? 1).toDecimalPlaces(currencyCode === 'USD' ? 2 : 4, Decimal.ROUND_HALF_UP);
|
|
306
|
+
const lineAmount = currencyCode === 'CNY' ? new Decimal(pricing.salesLineAmountCny ?? 0).toDecimalPlaces(2, Decimal.ROUND_HALF_UP) : unitPrice.times(pricing.quantity).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
|
|
307
|
+
documentLines.push({ purchaseOrderLineId: line.id, purchaseOrderId: line.purchaseOrderId, exchangeRateMonth: fx?.month ?? null, usdToCnyRate: fx?.rate.usdToCnyRate ?? null, unitPrice: unitPrice.toFixed(currencyCode === 'CNY' && unitPrice.decimalPlaces() > 2 ? 4 : 2), lineAmount: lineAmount.toFixed(2) });
|
|
308
|
+
}
|
|
309
|
+
const documentPricing = { currencyCode, lines: documentLines, orderAmount: documentLines.reduce((sum, line) => sum.plus(line.lineAmount), new Decimal(0)).toFixed(2) };
|
|
254
310
|
if (!compliance.purchaseAmountTaxInclusiveCny.isZero() && compliance.complianceProfitRate.lt(rule.minimumOrderProfitRate))
|
|
255
311
|
throw new SalesFileEvaluationError(DomainErrorCodes.PROFIT_RATE_BELOW_MINIMUM, '整单合规利润率低于系统设置的最低值', { actual: compliance.complianceProfitRate.toString(), minimum: rule.minimumOrderProfitRate }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
256
312
|
const refundable = complianceInputs.map((line, index) => ({ line, calculated: compliance.lines[index] })).filter(item => new Decimal(item.line.refundRate).gt(0) && new Decimal(item.line.purchaseAmountTaxInclusiveCny).gt(0));
|
|
257
313
|
let exchangeCost = null;
|
|
258
314
|
let exchangeRate = null;
|
|
259
315
|
if (refundable.length) {
|
|
260
|
-
//
|
|
261
|
-
const orderDate =
|
|
262
|
-
|
|
263
|
-
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, '采购订单下单日期为空,无法确定月度美元汇率', {}, compliance.complianceProfitRate.toString(), null, warnings);
|
|
264
|
-
const date = new Date(`${orderDate}T00:00:00Z`);
|
|
265
|
-
exchangeRate = await this.dataSource.getRepository(MonthlySafeExchangeRate).findOne({ where: { ...scoped(scope), year: date.getUTCFullYear(), month: date.getUTCMonth() + 1, currencyCode: 'USD', deletedAt: IsNull() } });
|
|
266
|
-
if (!exchangeRate)
|
|
267
|
-
throw new SalesFileEvaluationError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, '缺少订单月份的外汇管理局首日美元汇率', { orderDate }, compliance.complianceProfitRate.toString(), null, warnings);
|
|
316
|
+
// Keep the established CNY compliance gate; resolve its month strictly from purchase dates.
|
|
317
|
+
const orderDate = [...purchaseOrderDates.values()].filter(Boolean).sort()[0] ?? null;
|
|
318
|
+
exchangeRate = (await requireRate(orderDate)).rate;
|
|
268
319
|
const validatedExchangeRate = parseExchangeRateInput(exchangeRate);
|
|
269
320
|
const purchaseNet = refundable.reduce((sum, item) => sum.plus(item.calculated.purchaseNetCny), new Decimal(0));
|
|
270
321
|
const sales = refundable.reduce((sum, item) => sum.plus(item.line.salesAmountCny), new Decimal(0));
|
|
@@ -306,7 +357,7 @@ let SalesFileService = class SalesFileService {
|
|
|
306
357
|
orderAmountCny: orders.reduce((sum, order) => sum.plus(order.orderAmountCny ?? 0), new Decimal(0)).toFixed(2),
|
|
307
358
|
lines: orderEntries.flatMap(entry => entry.derived.lines)
|
|
308
359
|
};
|
|
309
|
-
return { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants };
|
|
360
|
+
return { derived, customerContract, customer, purchaseOrder, purchaseLines, rule, compliance, exchangeCost, exchangeRate, bank, warnings, orders, ordersKey, paymentTermsVariants, documentPricing };
|
|
310
361
|
}
|
|
311
362
|
async download(scope, id) {
|
|
312
363
|
const item = await this.required(GeneratedSalesFile, scope, id, '历史销售文件不存在');
|
|
@@ -574,6 +625,21 @@ function normalizeGenerationOrders(input) {
|
|
|
574
625
|
}
|
|
575
626
|
return result;
|
|
576
627
|
}
|
|
628
|
+
function strictOrderMonth(value, purchaseOrderId) {
|
|
629
|
+
if (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
|
630
|
+
const date = new Date(`${value}T00:00:00.000Z`);
|
|
631
|
+
if (Number.isFinite(date.getTime()) && date.toISOString().slice(0, 10) === value)
|
|
632
|
+
return value.slice(0, 7);
|
|
633
|
+
}
|
|
634
|
+
const month = typeof value === 'string' && /^\d{4}-\d{2}/.test(value) ? value.slice(0, 7) : null;
|
|
635
|
+
throw new DomainError(DomainErrorCodes.EXCHANGE_RATE_REQUIRED, `采购订单下单日期为空或无效${month ? `(${month})` : ''},无法确定月度美元汇率,请维护真实的 YYYY-MM-DD 日期`, { orderDate: value ?? null, month, purchaseOrderId });
|
|
636
|
+
}
|
|
637
|
+
function workbookDocumentPricing(data) {
|
|
638
|
+
if (data.snapshot?.documentPricing)
|
|
639
|
+
return data.snapshot.documentPricing;
|
|
640
|
+
// Older rendering callers and saved snapshots are denominated in CNY.
|
|
641
|
+
return { currencyCode: 'CNY', orderAmount: data.derived.orderAmountCny, lines: data.derived.lines.map((line) => ({ purchaseOrderLineId: line.purchaseOrderLineId, purchaseOrderId: '', exchangeRateMonth: null, usdToCnyRate: null, unitPrice: line.salesUnitPriceCny, lineAmount: line.salesLineAmountCny })) };
|
|
642
|
+
}
|
|
577
643
|
function generationRequestMatches(item, expected) {
|
|
578
644
|
const request = item.generationSnapshot?.request;
|
|
579
645
|
const snapshotDerived = item.generationSnapshot?.derived;
|
|
@@ -587,6 +653,7 @@ function generationRequestMatches(item, expected) {
|
|
|
587
653
|
typeof request === 'object' &&
|
|
588
654
|
!Array.isArray(request) &&
|
|
589
655
|
request.exportIntegrityVersion === '2026-10-19.1' &&
|
|
656
|
+
request.currencyCode === expected.currencyCode &&
|
|
590
657
|
request.fileNumber === expected.fileNumber &&
|
|
591
658
|
request.templateVersion === expected.templateVersion &&
|
|
592
659
|
request.remarks === expected.remarks &&
|
|
@@ -610,7 +677,7 @@ function preflightResult(input, complianceProfitRate, exchangeCost, warnings, pa
|
|
|
610
677
|
allowed: !error,
|
|
611
678
|
fileType: input.fileType,
|
|
612
679
|
bankType: input.fileType === 'CUSTOMS_DECLARATION' || input.fileType === 'PL' ? null : input.bankType ?? null,
|
|
613
|
-
currencyCode: 'CNY',
|
|
680
|
+
currencyCode: input.currencyCode ?? 'CNY',
|
|
614
681
|
complianceProfitRate,
|
|
615
682
|
exchangeCost,
|
|
616
683
|
warnings,
|
|
@@ -639,19 +706,32 @@ function fillInvoiceSheet(sheet, type, data) {
|
|
|
639
706
|
set(sheet, 'E9', type === 'PI' ? 'Remark: The quotation is valid for one week.' : '');
|
|
640
707
|
// "To:" 目的国:写客户国别;为空时覆盖模板默认值(MOSCOW),留空即可
|
|
641
708
|
set(sheet, 'B9', translated.customerCountry);
|
|
642
|
-
|
|
709
|
+
const pricing = workbookDocumentPricing(data);
|
|
710
|
+
const currency = pricing.currencyCode;
|
|
711
|
+
set(sheet, 'E11', `Unit Price (${currency})`);
|
|
712
|
+
set(sheet, 'I11', `Amount (${currency})`);
|
|
713
|
+
set(sheet, 'G11', currency === 'USD' ? '1 USD = CNY' : 'CNY to RMB');
|
|
643
714
|
for (let index = 0; index < derived.lines.length; index += 1) {
|
|
644
715
|
const row = 12 + index;
|
|
645
|
-
|
|
716
|
+
const englishProduct = translated.lines[index]?.productName ?? '';
|
|
717
|
+
const englishModel = translated.lines[index]?.model ?? '';
|
|
718
|
+
const fromQuotation = data.snapshot?.materials?.some((source) => source.documentType === 'ENGLISH_QUOTATION' && source.purchaseOrderLineId === derived.lines[index].purchaseOrderLineId && (source.fields.includes('productName') || source.fields.includes('model')));
|
|
719
|
+
const productLabel = fromQuotation && englishModel && !englishProduct.toLocaleUpperCase().includes(englishModel.toLocaleUpperCase()) ? `${englishProduct}\n${englishModel}` : englishProduct;
|
|
720
|
+
[index + 1, productLabel, translated.lines[index]?.description ?? '', derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity), Number(pricing.lines[index].unitPrice), translated.lines[index]?.unit ?? '', Number(pricing.lines[index].usdToCnyRate ?? 1), derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount), derived.lines[index].hsCode ?? ''].forEach((value, offset) => sheet.getCell(row, offset < 7 ? offset + 1 : offset + 2).value = value);
|
|
646
721
|
safeMerge(sheet, `G${row}:H${row}`);
|
|
722
|
+
sheet.getCell(`E${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
|
|
723
|
+
sheet.getCell(`I${row}`).numFmt = '0.00';
|
|
724
|
+
if (pricing.lines[index].exchangeRateMonth)
|
|
725
|
+
sheet.getCell(`G${row}`).note = `${pricing.lines[index].exchangeRateMonth}: 1 USD = ${pricing.lines[index].usdToCnyRate} CNY`;
|
|
647
726
|
}
|
|
648
727
|
const total = 12 + derived.lines.length;
|
|
649
728
|
safeMerge(sheet, `A${total}:F${total}`);
|
|
650
729
|
safeMerge(sheet, `G${total}:J${total}`);
|
|
651
|
-
set(sheet, `A${total}`, derived.shipmentIncomplete ?
|
|
652
|
-
set(sheet, `G${total}`, Number(
|
|
730
|
+
set(sheet, `A${total}`, derived.shipmentIncomplete ? `Known Amount (${currency}) — Pending review` : `Total Amount(${currency})`);
|
|
731
|
+
set(sheet, `G${total}`, Number(pricing.orderAmount));
|
|
732
|
+
sheet.getCell(`G${total}`).numFmt = '0.00';
|
|
653
733
|
set(sheet, `A${total + 1}`, 'Price');
|
|
654
|
-
set(sheet, `C${total + 1}`,
|
|
734
|
+
set(sheet, `C${total + 1}`, `Remark: All prices are in ${currency}`);
|
|
655
735
|
set(sheet, `C${total + 2}`, translated.deliveryTerms || deliveryClauseText(data.clauses ?? []) || 'To confirm');
|
|
656
736
|
const bankStart = total + 4;
|
|
657
737
|
set(sheet, `C${bankStart}`, bank.beneficiary ?? '');
|
|
@@ -1072,6 +1152,7 @@ export function remittanceInformation(cnapsCode, goodsName, derived, civilUse) {
|
|
|
1072
1152
|
}
|
|
1073
1153
|
function fillCustomsSheet(sheet, data) {
|
|
1074
1154
|
const { customer, purchaseOrder, purchaseLines, derived, company, packing } = data;
|
|
1155
|
+
const pricing = workbookDocumentPricing(data);
|
|
1075
1156
|
resizeTwoRowSection(sheet, 14, 2, derived.lines.length, 12);
|
|
1076
1157
|
const companyText = [company?.companyNameZh, company?.unifiedSocialCreditCode ? `(${company.unifiedSocialCreditCode})` : ''].join('');
|
|
1077
1158
|
set(sheet, 'K3', '1/1');
|
|
@@ -1096,7 +1177,7 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1096
1177
|
const row = 14 + index * 2;
|
|
1097
1178
|
for (let col = 2; col <= 10; col++)
|
|
1098
1179
|
sheet.getCell(row + 1, col).value = null;
|
|
1099
|
-
set(sheet, `C${row + 1}`, purchaseLines[index].productDescription
|
|
1180
|
+
set(sheet, `C${row + 1}`, [purchaseLines[index].productDescription, purchaseLines[index].brand ? `品牌:${purchaseLines[index].brand}` : '', purchaseLines[index].material ? `材质:${purchaseLines[index].material}` : '', purchaseLines[index].usage ? `用途:${purchaseLines[index].usage}` : '', purchaseLines[index].declarationElements].filter(Boolean).join(';'));
|
|
1100
1181
|
safeMerge(sheet, `A${row}:A${row + 1}`);
|
|
1101
1182
|
safeMerge(sheet, `K${row}:K${row + 1}`);
|
|
1102
1183
|
safeMerge(sheet, `L${row}:L${row + 1}`);
|
|
@@ -1105,13 +1186,18 @@ function fillCustomsSheet(sheet, data) {
|
|
|
1105
1186
|
set(sheet, `C${row}`, [purchaseLines[index].productName, purchaseLines[index].modelSpecification].filter(Boolean).join(' '));
|
|
1106
1187
|
set(sheet, `D${row}`, derived.lines[index].quantityPending ? null : Number(derived.lines[index].quantity));
|
|
1107
1188
|
set(sheet, `E${row}`, purchaseLines[index].unit ?? '');
|
|
1108
|
-
set(sheet, `F${row}`, Number(
|
|
1109
|
-
set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(
|
|
1110
|
-
set(sheet, `H${row}`, '人民币');
|
|
1189
|
+
set(sheet, `F${row}`, Number(pricing.lines[index].unitPrice));
|
|
1190
|
+
set(sheet, `G${row}`, derived.lines[index].quantityPending || derived.lines[index].amountPending ? null : Number(pricing.lines[index].lineAmount));
|
|
1191
|
+
set(sheet, `H${row}`, pricing.currencyCode === 'USD' ? '美元' : '人民币');
|
|
1111
1192
|
set(sheet, `I${row}`, purchaseLines[index].originCountry || '待确认');
|
|
1112
1193
|
set(sheet, `J${row}`, customer.country || '待确认');
|
|
1113
1194
|
set(sheet, `K${row}`, purchaseLines[index].domesticSourceLocation || '待确认');
|
|
1114
1195
|
set(sheet, `L${row}`, '待确认');
|
|
1196
|
+
for (const warning of data.generationWarnings ?? [])
|
|
1197
|
+
if (String(warning.field ?? '').startsWith(`customs.${purchaseLines[index].id}.`))
|
|
1198
|
+
markReview(sheet.getCell(String(warning.field).endsWith('.hsCode') ? `B${row}` : `C${row}`));
|
|
1199
|
+
sheet.getCell(`F${row}`).numFmt = pricing.currencyCode === 'CNY' && new Decimal(pricing.lines[index].unitPrice).decimalPlaces() > 2 ? '0.0000' : '0.00';
|
|
1200
|
+
sheet.getCell(`G${row}`).numFmt = '0.00';
|
|
1115
1201
|
}
|
|
1116
1202
|
const tail = 14 + derived.lines.length * 2;
|
|
1117
1203
|
normalizeCustomsConfirmationRow(sheet, tail);
|