@chenchaolong/plugin-trade-compliance-workbench 1.0.188 → 1.0.190
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 +8 -0
- package/dist/assets/templates/PL.xlsx +0 -0
- package/dist/lib/entities/supplier-packing.entity.d.ts +7 -1
- package/dist/lib/entities/supplier-packing.entity.d.ts.map +1 -1
- package/dist/lib/entities/supplier-packing.entity.js +22 -2
- package/dist/lib/entities/supplier-packing.entity.js.map +1 -1
- package/dist/lib/import-jobs/import-command.builder.d.ts +2 -0
- package/dist/lib/import-jobs/import-command.builder.d.ts.map +1 -1
- 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/import-job.processor.js +1 -1
- package/dist/lib/import-jobs/import-job.processor.js.map +1 -1
- package/dist/lib/packing/packing-batch.contract.d.ts +66 -0
- package/dist/lib/packing/packing-batch.contract.d.ts.map +1 -0
- package/dist/lib/packing/packing-batch.contract.js +2 -0
- package/dist/lib/packing/packing-batch.contract.js.map +1 -0
- package/dist/lib/packing/packing-layout.d.ts +4 -0
- package/dist/lib/packing/packing-layout.d.ts.map +1 -0
- package/dist/lib/packing/packing-layout.js +70 -0
- package/dist/lib/packing/packing-layout.js.map +1 -0
- package/dist/lib/packing/packing-render.d.ts +66 -0
- package/dist/lib/packing/packing-render.d.ts.map +1 -0
- package/dist/lib/packing/packing-render.js +102 -0
- package/dist/lib/packing/packing-render.js.map +1 -0
- package/dist/lib/packing/supplier-packing.service.d.ts +45 -49
- package/dist/lib/packing/supplier-packing.service.d.ts.map +1 -1
- package/dist/lib/packing/supplier-packing.service.js +473 -91
- 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 +5 -5
- package/dist/lib/remote-components/trade-compliance-workbench/editor-source.mjs +3 -2
- package/dist/lib/remote-components/trade-compliance-workbench/editor.js +1 -1
- package/dist/lib/remote-ui/action-execution.d.ts.map +1 -1
- package/dist/lib/remote-ui/action-execution.js +6 -0
- package/dist/lib/remote-ui/action-execution.js.map +1 -1
- package/dist/lib/remote-ui/app-source.js +1 -1
- package/dist/lib/remote-ui/app-source.js.map +1 -1
- package/dist/lib/remote-ui/components/packing-batches.css +5 -0
- package/dist/lib/remote-ui/components/packing-batches.d.ts +35 -0
- package/dist/lib/remote-ui/components/packing-batches.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/packing-batches.js +101 -0
- package/dist/lib/remote-ui/components/packing-batches.js.map +1 -0
- package/dist/lib/remote-ui/components/packing-import.css +1 -0
- package/dist/lib/remote-ui/components/packing-import.d.ts +30 -0
- package/dist/lib/remote-ui/components/packing-import.d.ts.map +1 -0
- package/dist/lib/remote-ui/components/packing-import.js +61 -0
- package/dist/lib/remote-ui/components/packing-import.js.map +1 -0
- package/dist/lib/remote-ui/pages/files.d.ts +8 -5
- package/dist/lib/remote-ui/pages/files.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/files.js +9 -6
- package/dist/lib/remote-ui/pages/files.js.map +1 -1
- package/dist/lib/remote-ui/pages/sales-files.css +38 -0
- package/dist/lib/remote-ui/pages/sales.d.ts +12 -4
- package/dist/lib/remote-ui/pages/sales.d.ts.map +1 -1
- package/dist/lib/remote-ui/pages/sales.js +25 -30
- package/dist/lib/remote-ui/pages/sales.js.map +1 -1
- package/dist/lib/remote-ui/sales-contracts.d.ts +5 -2
- package/dist/lib/remote-ui/sales-contracts.d.ts.map +1 -1
- package/dist/lib/sales-file.service.d.ts +4 -2
- package/dist/lib/sales-file.service.d.ts.map +1 -1
- package/dist/lib/sales-file.service.js +48 -47
- 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 +61 -0
- package/dist/lib/schema-maintenance.js.map +1 -1
- package/dist/lib/types.d.ts +10 -0
- 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 +6 -0
- package/dist/lib/workbench-action-contract.js.map +1 -1
- package/dist/lib/workbench-view.provider.d.ts.map +1 -1
- package/dist/lib/workbench-view.provider.js +36 -6
- package/dist/lib/workbench-view.provider.js.map +1 -1
- package/dist/lib/workbench.middleware.d.ts +15 -5
- package/dist/lib/workbench.middleware.d.ts.map +1 -1
- package/dist/lib/workbench.middleware.js +2 -2
- package/dist/lib/workbench.middleware.js.map +1 -1
- package/dist/lib/workbench.service.js +2 -2
- package/dist/lib/workbench.service.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,107 +1,408 @@
|
|
|
1
1
|
import { __decorate, __metadata, __param } from "tslib";
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
2
3
|
import { Injectable } from '@nestjs/common';
|
|
3
4
|
import { InjectDataSource } from '@nestjs/typeorm';
|
|
4
|
-
import { DataSource, IsNull } from 'typeorm';
|
|
5
|
-
import {
|
|
5
|
+
import { DataSource, In, IsNull } from 'typeorm';
|
|
6
|
+
import { Decimal } from 'decimal.js';
|
|
7
|
+
import { PACKING_BATCH_SCHEMA_MAINTENANCE_SQL } from '../schema-maintenance.js';
|
|
8
|
+
import { CustomerContract, ImportTask, PurchaseOrder, PurchaseOrderLine, SupplierPacking, SupplierPackingLine } from '../entities/index.js';
|
|
6
9
|
import { DomainError, DomainErrorCodes } from '../types.js';
|
|
7
|
-
/** 供应商装箱单:1 个采购合同 1 份。行数据由 Xpert 平台专家识别后经工具保存,本服务负责校验、合同内匹配采购行、整份覆盖(revision 递增)并完结导入任务。 */
|
|
8
10
|
let SupplierPackingService = class SupplierPackingService {
|
|
9
11
|
constructor(dataSource) {
|
|
10
12
|
this.dataSource = dataSource;
|
|
11
13
|
}
|
|
12
14
|
async importSupplierPackingDraft(scope, input) {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
throw new DomainError(DomainErrorCodes.NOT_FOUND, '采购合同不存在', { purchaseOrderId: input.purchaseOrderId });
|
|
16
|
-
const warnings = [];
|
|
17
|
-
const rows = input.rows
|
|
18
|
-
.map((row, index) => prepareDraftRow(row, index, warnings))
|
|
19
|
-
.filter((row) => row != null);
|
|
20
|
-
if (!rows.length)
|
|
21
|
-
throw new DomainError(DomainErrorCodes.INVALID_INPUT, '装箱数据为空:每一行至少需要型号或数量,请核对提取结果');
|
|
22
|
-
const purchaseLines = await this.dataSource.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), purchaseOrderId: input.purchaseOrderId, deletedAt: IsNull() }, order: { lineNumber: 'ASC' } });
|
|
23
|
-
const { bindings, matchWarnings } = bindRowsToPurchaseLines(rows, purchaseLines);
|
|
24
|
-
warnings.push(...matchWarnings);
|
|
25
|
-
const matchedCount = bindings.filter(binding => binding.purchaseOrderLineId).length;
|
|
26
|
-
const unmatchedCount = bindings.length - matchedCount;
|
|
27
|
-
const result = await this.dataSource.transaction(async (manager) => {
|
|
15
|
+
await this.ensurePackingSchema();
|
|
16
|
+
return this.dataSource.transaction(async (manager) => {
|
|
28
17
|
const taskRepo = manager.getRepository(ImportTask);
|
|
29
18
|
const task = await taskRepo.findOne({ where: { ...scoped(scope), id: input.importTaskId }, lock: { mode: 'pessimistic_write' } });
|
|
30
19
|
if (!task)
|
|
31
|
-
throw new DomainError(DomainErrorCodes.NOT_FOUND, '解析任务不存在'
|
|
20
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '解析任务不存在');
|
|
32
21
|
if (task.documentType !== 'SUPPLIER_PACKING')
|
|
33
|
-
|
|
22
|
+
invalid('解析任务类型与装箱数据不匹配');
|
|
23
|
+
const target = (task.executionInput ?? {});
|
|
24
|
+
const explicitIds = input.purchaseOrderIds ?? (input.purchaseOrderId ? [input.purchaseOrderId] : undefined);
|
|
25
|
+
const trustedIds = target.purchaseOrderIds ?? (target.purchaseOrderId ? [target.purchaseOrderId] : undefined);
|
|
26
|
+
if (explicitIds && trustedIds && !sameIds(explicitIds, trustedIds))
|
|
27
|
+
invalid('装箱采购合同与解析任务目标不一致');
|
|
28
|
+
if (input.packingId && (target.purchaseOrderIds || target.purchaseOrderId || target.packingId) && input.packingId !== target.packingId)
|
|
29
|
+
invalid('装箱批次与解析任务目标不一致');
|
|
30
|
+
const packingId = target.packingId ?? input.packingId;
|
|
34
31
|
const packingRepo = manager.getRepository(SupplierPacking);
|
|
32
|
+
let existing = packingId ? await this.requirePacking(manager, scope, packingId, true) : null;
|
|
33
|
+
const ids = uniqueIds(trustedIds ?? explicitIds ?? (existing ? associationIds(existing) : []));
|
|
34
|
+
if (!ids.length)
|
|
35
|
+
invalid('请指定装箱批次关联的采购合同');
|
|
36
|
+
const orders = await this.validateOrders(manager, scope, ids);
|
|
37
|
+
// Legacy direct single-PO calls retain whole-document replacement behavior.
|
|
38
|
+
const legacy = !packingId && !input.purchaseOrderIds && !target.purchaseOrderIds && !!input.purchaseOrderId;
|
|
39
|
+
if (legacy)
|
|
40
|
+
existing = await packingRepo.findOne({ where: { ...scoped(scope), purchaseOrderId: ids[0], deletedAt: IsNull() }, order: { createdAt: 'DESC' }, lock: { mode: 'pessimistic_write' } });
|
|
41
|
+
const warnings = [];
|
|
42
|
+
const rows = input.rows.map((row, i) => prepareDraftRow(row, i, warnings)).filter((row) => !!row);
|
|
43
|
+
if (!rows.length)
|
|
44
|
+
invalid('装箱数据为空:每一行至少需要型号或数量,请核对提取结果');
|
|
45
|
+
const purchaseLines = await manager.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), purchaseOrderId: In(ids), deletedAt: IsNull() }, order: { lineNumber: 'ASC' } });
|
|
46
|
+
const { bindings, matchWarnings } = bindRowsToPurchaseLines(rows, purchaseLines);
|
|
47
|
+
warnings.push(...matchWarnings);
|
|
35
48
|
const lineRepo = manager.getRepository(SupplierPackingLine);
|
|
36
|
-
const existing = await packingRepo.findOne({ where: { ...scoped(scope), purchaseOrderId: input.purchaseOrderId, deletedAt: IsNull() } });
|
|
37
|
-
const revision = existing ? existing.revision + 1 : 1;
|
|
38
49
|
const now = new Date();
|
|
39
50
|
if (existing) {
|
|
40
51
|
const mark = { deletedAt: now, deletedById: scope.userId ?? null, deleteOperation: 'PACKING_REPLACE' };
|
|
41
|
-
await lineRepo.update({ packingId: existing.id }, mark);
|
|
42
|
-
|
|
52
|
+
await lineRepo.update({ ...scoped(scope), packingId: existing.id, deletedAt: IsNull() }, mark);
|
|
53
|
+
if (legacy)
|
|
54
|
+
await packingRepo.update(existing.id, mark);
|
|
43
55
|
}
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
purchaseOrderId:
|
|
47
|
-
|
|
56
|
+
const value = {
|
|
57
|
+
...scoped(scope), createdById: scope.userId ?? null, updatedById: scope.userId ?? null,
|
|
58
|
+
purchaseOrderId: ids[0], purchaseOrderIds: ids, supplierId: orders[0].supplierId ?? null,
|
|
59
|
+
revision: existing ? existing.revision + 1 : 1, status: 'DRAFT',
|
|
60
|
+
fileName: task.sourceFileName, sourceFileId: task.sourceFileId, importedById: scope.userId ?? null,
|
|
61
|
+
contentFingerprint: null, deletedAt: null, deletedById: null, deleteOperation: null
|
|
62
|
+
};
|
|
63
|
+
const packing = await packingRepo.save(existing && !legacy ? Object.assign(existing, value) : packingRepo.create(value));
|
|
64
|
+
const lines = await lineRepo.save(bindings.map((binding, index) => {
|
|
65
|
+
const purchaseLine = purchaseLines.find(line => line.id === binding.purchaseOrderLineId);
|
|
66
|
+
const counts = purchaseLine ? countsAsGoods(binding.row.role, purchaseLine, bindings.some(other => other.purchaseOrderLineId === purchaseLine.id && other.row.role !== 'BOOM' && other.row.role !== 'PART')) : true;
|
|
67
|
+
return lineRepo.create({
|
|
68
|
+
...scoped(scope), createdById: scope.userId ?? null, updatedById: scope.userId ?? null,
|
|
69
|
+
packingId: packing.id, purchaseOrderId: purchaseLine?.purchaseOrderId ?? ids[0], purchaseOrderLineId: binding.purchaseOrderLineId,
|
|
70
|
+
allocations: binding.purchaseOrderLineId ? [allocation(binding.purchaseOrderLineId, numberToString(binding.row.qty) ?? '0', counts)] : [],
|
|
71
|
+
lineIndex: index, model: binding.row.model, normalizedModel: normalizeModelKey(binding.row.model), description: binding.row.description, role: binding.row.role,
|
|
72
|
+
qty: numberToString(binding.row.qty), cartons: numberToString(binding.row.cartons), dimensionCm: binding.row.dimensionCm,
|
|
73
|
+
grossWeightPerCtnKg: numberToString(binding.row.grossWeightPerCtnKg), battery: binding.row.battery,
|
|
74
|
+
boxVolumeCbm: numberToString(binding.row.boxVolumeCbm), totalVolumeCbm: numberToString(binding.row.totalVolumeCbm), totalGrossWeightKg: numberToString(binding.row.totalGrossWeightKg),
|
|
75
|
+
deletedAt: null, deletedById: null, deleteOperation: null
|
|
76
|
+
});
|
|
48
77
|
}));
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
model: binding.row.model, normalizedModel: normalizeModelKey(binding.row.model), description: binding.row.description, role: binding.row.role,
|
|
53
|
-
qty: numberToString(binding.row.qty), cartons: numberToString(binding.row.cartons), dimensionCm: binding.row.dimensionCm,
|
|
54
|
-
grossWeightPerCtnKg: numberToString(binding.row.grossWeightPerCtnKg), battery: binding.row.battery,
|
|
55
|
-
boxVolumeCbm: numberToString(binding.row.boxVolumeCbm), totalVolumeCbm: numberToString(binding.row.totalVolumeCbm), totalGrossWeightKg: numberToString(binding.row.totalGrossWeightKg),
|
|
56
|
-
deletedAt: null, deletedById: null, deleteOperation: null
|
|
57
|
-
})));
|
|
78
|
+
packing.contentFingerprint = fingerprint(packing, lines);
|
|
79
|
+
await packingRepo.save(packing);
|
|
80
|
+
const matchedCount = bindings.filter(binding => binding.purchaseOrderLineId).length;
|
|
58
81
|
task.status = 'SUCCEEDED';
|
|
59
|
-
task.resultPayload = {
|
|
82
|
+
task.resultPayload = { packingId: packing.id, purchaseOrderId: ids[0], purchaseOrderIds: ids, revision: packing.revision, rowCount: rows.length, matchedCount, unmatchedCount: rows.length - matchedCount, warnings };
|
|
60
83
|
task.resultPayloadVersion = 'SUPPLIER_PACKING_RESULT_V1';
|
|
61
84
|
task.completedAt = now;
|
|
62
|
-
|
|
63
|
-
|
|
85
|
+
await taskRepo.save(task);
|
|
86
|
+
const detail = this.detail(packing, lines, purchaseLines, orders);
|
|
87
|
+
return { packing: detail.packing, task: { id: task.id, status: task.status }, rows: detail.lines, warnings: [...warnings, ...detail.warnings], matchedCount, unmatchedCount: rows.length - matchedCount };
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
async validateBatchTargets(scope, purchaseOrderIds, packingId) {
|
|
91
|
+
await this.ensurePackingSchema();
|
|
92
|
+
await this.dataSource.transaction(async (manager) => {
|
|
93
|
+
if (packingId)
|
|
94
|
+
await this.requirePacking(manager, scope, packingId, true);
|
|
95
|
+
const ids = uniqueIds(purchaseOrderIds);
|
|
96
|
+
if (!ids.length)
|
|
97
|
+
invalid('装箱批次至少关联一张采购合同');
|
|
98
|
+
await this.validateOrders(manager, scope, ids);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
async listPackingBatches(scope, purchaseOrderIds = []) {
|
|
102
|
+
await this.ensurePackingSchema();
|
|
103
|
+
const packs = await this.dataSource.getRepository(SupplierPacking).find({ where: { ...scoped(scope), deletedAt: IsNull() }, order: { createdAt: 'DESC' } });
|
|
104
|
+
const selected = packs.filter(pack => !purchaseOrderIds.length || associationIds(pack).some(id => purchaseOrderIds.includes(id)));
|
|
105
|
+
return Promise.all(selected.map(async (pack) => (await this.getPackingBatch(scope, pack.id)).packing));
|
|
106
|
+
}
|
|
107
|
+
async getPackingBatch(scope, packingId) {
|
|
108
|
+
await this.ensurePackingSchema();
|
|
109
|
+
return this.readDetail(this.dataSource.manager, scope, await this.requirePacking(this.dataSource.manager, scope, packingId));
|
|
110
|
+
}
|
|
111
|
+
async linkPackingBatch(scope, input) {
|
|
112
|
+
await this.ensurePackingSchema();
|
|
113
|
+
return this.dataSource.transaction(async (manager) => {
|
|
114
|
+
const pack = await this.requirePacking(manager, scope, input.packingId, true);
|
|
115
|
+
const ids = uniqueIds(input.purchaseOrderIds);
|
|
116
|
+
if (!ids.length)
|
|
117
|
+
invalid('装箱批次至少关联一张采购合同');
|
|
118
|
+
const orders = await this.validateOrders(manager, scope, ids);
|
|
119
|
+
const lines = await manager.getRepository(SupplierPackingLine).find({ where: { ...scoped(scope), packingId: pack.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } });
|
|
120
|
+
const referenced = [...new Set(lines.flatMap(line => effectiveAllocations(line).map(a => a.purchaseOrderLineId)))];
|
|
121
|
+
const refs = referenced.length ? await manager.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), id: In(referenced), deletedAt: IsNull() } }) : [];
|
|
122
|
+
if (refs.length !== referenced.length || refs.some(line => !ids.includes(line.purchaseOrderId)))
|
|
123
|
+
invalid('不能移除已分配包装行所属的采购合同,请先解除分配');
|
|
124
|
+
const purchaseLines = await manager.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), purchaseOrderId: In(ids), deletedAt: IsNull() }, order: { lineNumber: 'ASC' } });
|
|
125
|
+
const byModel = bindingsByModel(purchaseLines);
|
|
126
|
+
for (const line of lines) {
|
|
127
|
+
if (effectiveAllocations(line).length)
|
|
128
|
+
continue;
|
|
129
|
+
const candidates = byModel.get(normalizeModelKey(line.model) ?? '') ?? [];
|
|
130
|
+
if (candidates.length !== 1 || specificationConflict(line.model, candidates[0]))
|
|
131
|
+
continue;
|
|
132
|
+
line.purchaseOrderLineId = candidates[0].id;
|
|
133
|
+
line.purchaseOrderId = candidates[0].purchaseOrderId;
|
|
134
|
+
line.allocations = [allocation(candidates[0].id, line.qty ?? '0', countsAsGoods(line.role, candidates[0], lines.some(other => other.id !== line.id && other.purchaseOrderLineId === candidates[0].id && other.role !== 'BOOM' && other.role !== 'PART')))];
|
|
135
|
+
line.updatedById = scope.userId ?? null;
|
|
136
|
+
}
|
|
137
|
+
await manager.getRepository(SupplierPackingLine).save(lines);
|
|
138
|
+
pack.purchaseOrderId = ids[0];
|
|
139
|
+
pack.purchaseOrderIds = ids;
|
|
140
|
+
pack.supplierId = orders[0].supplierId;
|
|
141
|
+
await this.touch(manager, scope, pack, lines);
|
|
142
|
+
return this.detail(pack, lines, purchaseLines, orders);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
async allocatePackingLine(scope, input) {
|
|
146
|
+
await this.ensurePackingSchema();
|
|
147
|
+
return this.dataSource.transaction(async (manager) => {
|
|
148
|
+
const lineRepo = manager.getRepository(SupplierPackingLine);
|
|
149
|
+
const found = await lineRepo.findOne({ where: { ...scoped(scope), id: input.lineId, deletedAt: IsNull() } });
|
|
150
|
+
if (!found)
|
|
151
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行不存在');
|
|
152
|
+
const pack = await this.requirePacking(manager, scope, found.packingId, true);
|
|
153
|
+
await this.validateOrders(manager, scope, associationIds(pack));
|
|
154
|
+
const detail = await this.readDetail(manager, scope, pack);
|
|
155
|
+
const current = await lineRepo.findOne({ where: { ...scoped(scope), id: input.lineId, packingId: pack.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } });
|
|
156
|
+
if (!current)
|
|
157
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行已被替换');
|
|
158
|
+
const previousAllocations = effectiveAllocations(current).map(a => ({ ...a }));
|
|
159
|
+
const allocations = validateAllocations(current, input.allocations, detail.purchaseLines);
|
|
160
|
+
current.allocations = allocations;
|
|
161
|
+
current.purchaseOrderLineId = allocations.length === 1 ? allocations[0].purchaseOrderLineId : null;
|
|
162
|
+
current.purchaseOrderId = detail.purchaseLines.find(line => line.id === current.purchaseOrderLineId)?.purchaseOrderId ?? pack.purchaseOrderId;
|
|
163
|
+
current.updatedById = scope.userId ?? null;
|
|
164
|
+
const lines = await lineRepo.find({ where: { ...scoped(scope), packingId: pack.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } });
|
|
165
|
+
const changed = lines.map(line => line.id === current.id ? current : line);
|
|
166
|
+
await this.validateQuantities(manager, scope, pack, changed, detail.purchaseLines, { lineId: current.id, previousAllocations });
|
|
167
|
+
await lineRepo.save(current);
|
|
168
|
+
await this.touch(manager, scope, pack, changed);
|
|
169
|
+
return this.readDetail(manager, scope, pack);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async updatePackingLine(scope, input) {
|
|
173
|
+
await this.ensurePackingSchema();
|
|
174
|
+
return this.dataSource.transaction(async (manager) => {
|
|
175
|
+
const repo = manager.getRepository(SupplierPackingLine);
|
|
176
|
+
const initial = await repo.findOne({ where: { ...scoped(scope), id: input.lineId, deletedAt: IsNull() } });
|
|
177
|
+
if (!initial)
|
|
178
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行不存在');
|
|
179
|
+
const pack = await this.requirePacking(manager, scope, initial.packingId, true);
|
|
180
|
+
await this.validateOrders(manager, scope, associationIds(pack));
|
|
181
|
+
const line = await repo.findOne({ where: { ...scoped(scope), id: input.lineId, packingId: pack.id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } });
|
|
182
|
+
if (!line)
|
|
183
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行已被替换');
|
|
184
|
+
const previousAllocations = effectiveAllocations(line).map(a => ({ ...a }));
|
|
185
|
+
const toNumber = (value) => {
|
|
186
|
+
if (value == null)
|
|
187
|
+
return null;
|
|
188
|
+
if (!value.trim() || !Number.isFinite(Number(value)) || Number(value) < 0)
|
|
189
|
+
invalid('包装数值必须为有效非负数字');
|
|
190
|
+
return Number(value);
|
|
191
|
+
};
|
|
192
|
+
for (const field of ['qty', 'cartons', 'grossWeightPerCtnKg'])
|
|
193
|
+
if (input[field] !== undefined)
|
|
194
|
+
line[field] = numberToString(toNumber(input[field]));
|
|
195
|
+
if (input.role !== undefined) {
|
|
196
|
+
if (input.role != null && !['MAIN', 'BOOM', 'PART'].includes(input.role))
|
|
197
|
+
invalid('包装角色无效');
|
|
198
|
+
line.role = input.role;
|
|
199
|
+
}
|
|
200
|
+
if (input.dimensionCm !== undefined)
|
|
201
|
+
line.dimensionCm = input.dimensionCm;
|
|
202
|
+
const dimension = parseDimensionCm(line.dimensionCm);
|
|
203
|
+
line.dimensionCm = dimension?.text ?? null;
|
|
204
|
+
line.boxVolumeCbm = numberToString(dimension?.volumeCbm ?? null);
|
|
205
|
+
line.totalVolumeCbm = line.cartons != null && Number(line.cartons) === 0 ? '0' : line.boxVolumeCbm != null && line.cartons != null ? numberToString(Number(line.boxVolumeCbm) * Number(line.cartons)) : null;
|
|
206
|
+
line.totalGrossWeightKg = line.cartons != null && Number(line.cartons) === 0 ? '0' : line.grossWeightPerCtnKg != null && line.cartons != null ? numberToString(Number(line.grossWeightPerCtnKg) * Number(line.cartons)) : null;
|
|
207
|
+
line.allocations = effectiveAllocations(line);
|
|
208
|
+
if (input.qty !== undefined && line.allocations.length === 1)
|
|
209
|
+
line.allocations[0].quantity = line.qty ?? '0';
|
|
210
|
+
const lines = (await repo.find({ where: { ...scoped(scope), packingId: pack.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } })).map(row => row.id === line.id ? line : row);
|
|
211
|
+
const detail = await this.readDetail(manager, scope, pack);
|
|
212
|
+
if (line.cartons != null && Number(line.cartons) === 0 && !isCompanion(line, lines))
|
|
213
|
+
invalid('零箱数仅用于明确与同商品主包装共箱且不计商品数量的闸杆或配件行');
|
|
214
|
+
if (line.allocations.length)
|
|
215
|
+
validateAllocations(line, line.allocations, detail.purchaseLines);
|
|
216
|
+
await this.validateQuantities(manager, scope, pack, lines, detail.purchaseLines, { lineId: line.id, previousAllocations });
|
|
217
|
+
line.updatedById = scope.userId ?? null;
|
|
218
|
+
await repo.save(line);
|
|
219
|
+
await this.touch(manager, scope, pack, lines);
|
|
220
|
+
return this.readDetail(manager, scope, pack);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
async confirmPackingBatch(scope, input) {
|
|
224
|
+
await this.ensurePackingSchema();
|
|
225
|
+
return this.dataSource.transaction(async (manager) => {
|
|
226
|
+
const pack = await this.requirePacking(manager, scope, input.packingId, true);
|
|
227
|
+
await this.validateOrders(manager, scope, associationIds(pack));
|
|
228
|
+
const detail = await this.readDetail(manager, scope, pack);
|
|
229
|
+
const lines = await manager.getRepository(SupplierPackingLine).find({ where: { ...scoped(scope), packingId: pack.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } });
|
|
230
|
+
if (!lines.length)
|
|
231
|
+
invalid('装箱批次没有包装行');
|
|
232
|
+
for (const line of lines) {
|
|
233
|
+
const allocations = effectiveAllocations(line);
|
|
234
|
+
if (!allocations.length)
|
|
235
|
+
invalid(`第 ${line.lineIndex + 1} 行尚未分配商品`);
|
|
236
|
+
validateAllocations(line, allocations, detail.purchaseLines);
|
|
237
|
+
if (!positive(line.qty))
|
|
238
|
+
invalid(`第 ${line.lineIndex + 1} 行缺少有效数量`);
|
|
239
|
+
if (!isCompanion(line, lines) && (!positive(line.cartons) || !positive(line.grossWeightPerCtnKg) || !positive(line.boxVolumeCbm) || !parseDimensionCm(line.dimensionCm)?.volumeCbm))
|
|
240
|
+
invalid(`第 ${line.lineIndex + 1} 行缺少有效箱数、尺寸或毛重`);
|
|
241
|
+
}
|
|
242
|
+
await this.validateQuantities(manager, scope, pack, lines, detail.purchaseLines);
|
|
243
|
+
pack.status = 'CONFIRMED';
|
|
244
|
+
pack.updatedById = scope.userId ?? null;
|
|
245
|
+
pack.contentFingerprint = fingerprint(pack, lines);
|
|
246
|
+
await manager.getRepository(SupplierPacking).save(pack);
|
|
247
|
+
return this.readDetail(manager, scope, pack);
|
|
64
248
|
});
|
|
65
|
-
return {
|
|
66
|
-
packing: { id: result.packing.id, purchaseOrderId: input.purchaseOrderId, revision: result.packing.revision, fileName: result.packing.fileName, importedAt: result.packing.createdAt.toISOString() },
|
|
67
|
-
task: { id: result.task.id, status: result.task.status },
|
|
68
|
-
rows: result.lines.map((line, index) => packingLineDto(line, bindings[index]?.row.sourceRow ?? index + 1)),
|
|
69
|
-
warnings,
|
|
70
|
-
matchedCount,
|
|
71
|
-
unmatchedCount
|
|
72
|
-
};
|
|
73
249
|
}
|
|
74
250
|
async getPurchasePacking(scope, purchaseOrderId) {
|
|
75
|
-
|
|
251
|
+
await this.ensurePackingSchema();
|
|
252
|
+
// Keep the legacy latest-document view, including its return contract.
|
|
253
|
+
const packing = await this.dataSource.getRepository(SupplierPacking).findOne({ where: { ...scoped(scope), purchaseOrderId, deletedAt: IsNull() }, order: { createdAt: 'DESC' } });
|
|
76
254
|
const lines = packing ? await this.dataSource.getRepository(SupplierPackingLine).find({ where: { ...scoped(scope), packingId: packing.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } }) : [];
|
|
77
255
|
const purchaseLines = await this.dataSource.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), purchaseOrderId, deletedAt: IsNull() }, order: { lineNumber: 'ASC' } });
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
purchaseLines: purchaseLines.map(line => ({ id: line.id, lineNumber: line.lineNumber, productName: line.productName, englishName: line.englishName, modelSpecification: line.modelSpecification, quantity: line.quantity }))
|
|
82
|
-
};
|
|
256
|
+
const orders = [{ id: purchaseOrderId, contractNo: '' }];
|
|
257
|
+
const detail = packing ? this.detail(packing, lines, purchaseLines, orders) : null;
|
|
258
|
+
return { packing: detail?.packing ?? null, lines: detail?.lines ?? [], purchaseLines: purchaseLines.map(line => purchaseLineDto(line, orders)) };
|
|
83
259
|
}
|
|
84
260
|
async bindSupplierPackingLine(scope, input) {
|
|
261
|
+
await this.ensurePackingSchema();
|
|
85
262
|
const line = await this.dataSource.getRepository(SupplierPackingLine).findOne({ where: { ...scoped(scope), id: input.lineId, deletedAt: IsNull() } });
|
|
86
263
|
if (!line)
|
|
87
|
-
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行不存在'
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
line.updatedById = scope.userId ?? null;
|
|
95
|
-
const saved = await this.dataSource.getRepository(SupplierPackingLine).save(line);
|
|
96
|
-
return packingLineDto(saved);
|
|
264
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱行不存在');
|
|
265
|
+
const detail = await this.getPackingBatch(scope, line.packingId);
|
|
266
|
+
const purchase = detail.purchaseLines.find(row => row.id === input.purchaseOrderLineId);
|
|
267
|
+
if (input.purchaseOrderLineId && !purchase)
|
|
268
|
+
invalid('只能绑定批次关联采购合同下的商品行');
|
|
269
|
+
const result = await this.allocatePackingLine(scope, { lineId: line.id, allocations: purchase ? [allocation(purchase.id, line.qty ?? '0', countsAsGoods(line.role, purchase, detail.lines.some(other => other.id !== line.id && other.purchaseOrderLineId === purchase.id && other.role !== 'BOOM' && other.role !== 'PART')))] : [] });
|
|
270
|
+
return result.lines.find(row => row.id === line.id);
|
|
97
271
|
}
|
|
98
|
-
/** 生成销售文件前判断装箱数据是否可用:存在且至少一行绑定到采购行。 */
|
|
99
272
|
async hasUsablePacking(scope, purchaseOrderId) {
|
|
100
|
-
|
|
273
|
+
await this.ensurePackingSchema();
|
|
274
|
+
return (await this.listPackingBatches(scope, [purchaseOrderId])).some(pack => pack.boundRowCount > 0);
|
|
275
|
+
}
|
|
276
|
+
/** Hot plugin refresh may skip application bootstrap, so guard every public entry. */
|
|
277
|
+
ensurePackingSchema() {
|
|
278
|
+
if (this.packingSchemaPromise)
|
|
279
|
+
return this.packingSchemaPromise;
|
|
280
|
+
const schema = this.dataSource.options?.schema ?? 'public';
|
|
281
|
+
const promise = this.dataSource.transaction(async (manager) => {
|
|
282
|
+
// The transaction-local path targets the configured schema without polluting pooled connections.
|
|
283
|
+
await manager.query("SELECT set_config('search_path', quote_ident($1), true)", [schema]);
|
|
284
|
+
await manager.query(PACKING_BATCH_SCHEMA_MAINTENANCE_SQL);
|
|
285
|
+
});
|
|
286
|
+
this.packingSchemaPromise = promise;
|
|
287
|
+
void promise.catch(() => { if (this.packingSchemaPromise === promise)
|
|
288
|
+
this.packingSchemaPromise = undefined; });
|
|
289
|
+
return promise;
|
|
290
|
+
}
|
|
291
|
+
async requirePacking(manager, scope, id, lock = false) {
|
|
292
|
+
const packing = await manager.getRepository(SupplierPacking).findOne({ where: { ...scoped(scope), id, deletedAt: IsNull() }, ...(lock ? { lock: { mode: 'pessimistic_write' } } : {}) });
|
|
101
293
|
if (!packing)
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
294
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '装箱批次不存在');
|
|
295
|
+
return packing;
|
|
296
|
+
}
|
|
297
|
+
async validateOrders(manager, scope, ids) {
|
|
298
|
+
const orders = [];
|
|
299
|
+
for (const id of [...ids].sort()) {
|
|
300
|
+
const order = await manager.getRepository(PurchaseOrder).findOne({ where: { ...scoped(scope), id, deletedAt: IsNull() }, lock: { mode: 'pessimistic_write' } });
|
|
301
|
+
if (!order)
|
|
302
|
+
throw new DomainError(DomainErrorCodes.NOT_FOUND, '采购合同不存在', { purchaseOrderId: id });
|
|
303
|
+
orders.push(order);
|
|
304
|
+
}
|
|
305
|
+
if (new Set(orders.map(order => order.supplierId)).size > 1)
|
|
306
|
+
invalid('同一装箱批次只能关联同一供应商的采购合同');
|
|
307
|
+
if (ids.length > 1) {
|
|
308
|
+
const contracts = await manager.getRepository(CustomerContract).find({ where: { ...scoped(scope), deletedAt: IsNull() } });
|
|
309
|
+
const customers = orders.map(order => {
|
|
310
|
+
const base = order.normalizedContractNo.replace(/(-[0-9]+)?C$/, '');
|
|
311
|
+
const matches = contracts.filter(contract => contract.normalizedContractNo === base || contract.normalizedContractNo === `${base}X`);
|
|
312
|
+
const unique = [...new Set(matches.map(contract => contract.customerId))];
|
|
313
|
+
if (unique.length !== 1)
|
|
314
|
+
invalid('采购合同无法确定唯一客户销售链路');
|
|
315
|
+
return unique[0];
|
|
316
|
+
});
|
|
317
|
+
if (new Set(customers).size !== 1)
|
|
318
|
+
invalid('同一装箱批次只能关联同一客户的采购合同');
|
|
319
|
+
}
|
|
320
|
+
return ids.map(id => orders.find(order => order.id === id));
|
|
321
|
+
}
|
|
322
|
+
async readDetail(manager, scope, pack) {
|
|
323
|
+
const ids = associationIds(pack);
|
|
324
|
+
const lines = await manager.getRepository(SupplierPackingLine).find({ where: { ...scoped(scope), packingId: pack.id, deletedAt: IsNull() }, order: { lineIndex: 'ASC' } });
|
|
325
|
+
const purchaseLines = await manager.getRepository(PurchaseOrderLine).find({ where: { ...scoped(scope), purchaseOrderId: In(ids), deletedAt: IsNull() }, order: { lineNumber: 'ASC' } });
|
|
326
|
+
const orders = await manager.getRepository(PurchaseOrder).find({ where: { ...scoped(scope), id: In(ids), deletedAt: IsNull() } });
|
|
327
|
+
return this.detail(pack, lines, purchaseLines, orders);
|
|
328
|
+
}
|
|
329
|
+
detail(pack, lines, purchaseLines, orders) {
|
|
330
|
+
const purchaseOrders = orders.map(order => ({ id: order.id, contractNo: order.contractNo }));
|
|
331
|
+
const purchases = purchaseLines.map(line => purchaseLineDto(line, purchaseOrders));
|
|
332
|
+
const byModel = bindingsByModel(purchaseLines);
|
|
333
|
+
const goodsTotals = new Map();
|
|
334
|
+
for (const line of lines)
|
|
335
|
+
for (const a of effectiveAllocations(line)) {
|
|
336
|
+
if (a.countsAsGoods)
|
|
337
|
+
goodsTotals.set(a.purchaseOrderLineId, (goodsTotals.get(a.purchaseOrderLineId) ?? new Decimal(0)).plus(a.quantity));
|
|
338
|
+
}
|
|
339
|
+
const overcounts = new Map(purchases.filter(purchase => (goodsTotals.get(purchase.id) ?? new Decimal(0)).gt(purchase.quantity)).map(purchase => [purchase.id, `采购合同 ${purchase.contractNo || purchase.purchaseOrderId} 采购行 ${purchase.lineNumber} 出货数量 ${goodsTotals.get(purchase.id).toFixed()} 超量(采购数量 ${purchase.quantity})`]));
|
|
340
|
+
const dtos = lines.map(line => {
|
|
341
|
+
const dto = packingLineDto(line);
|
|
342
|
+
dto.candidates = (byModel.get(normalizeModelKey(line.model) ?? '') ?? []).map(candidate => purchases.find(p => p.id === candidate.id));
|
|
343
|
+
const review = [];
|
|
344
|
+
if (!dto.allocations.length)
|
|
345
|
+
review.push(dto.candidates.length > 1 ? '型号对应多个采购商品,请人工分配' : '尚未匹配采购商品');
|
|
346
|
+
for (const a of dto.allocations)
|
|
347
|
+
if (a.countsAsGoods && overcounts.has(a.purchaseOrderLineId))
|
|
348
|
+
review.push(overcounts.get(a.purchaseOrderLineId));
|
|
349
|
+
if (!positive(line.qty))
|
|
350
|
+
review.push('缺少有效数量');
|
|
351
|
+
if (!isCompanion(line, lines)) {
|
|
352
|
+
if (!positive(line.cartons))
|
|
353
|
+
review.push('缺少有效箱数');
|
|
354
|
+
if (!positive(line.boxVolumeCbm))
|
|
355
|
+
review.push('缺少有效尺寸');
|
|
356
|
+
if (!positive(line.grossWeightPerCtnKg))
|
|
357
|
+
review.push('缺少有效毛重');
|
|
358
|
+
}
|
|
359
|
+
if (!dto.allocations.length && dto.candidates.some(candidate => specificationConflict(line.model, candidate)))
|
|
360
|
+
review.push('型号英文名称与明确规格冲突,请人工核对');
|
|
361
|
+
dto.needsReview = review.length ? review.join(';') : null;
|
|
362
|
+
return dto;
|
|
363
|
+
});
|
|
364
|
+
const warnings = dtos.filter(line => line.needsReview).map(line => `第 ${line.row} 行${line.needsReview}`);
|
|
365
|
+
const boundRowCount = dtos.filter(line => line.allocations.length).length;
|
|
366
|
+
return {
|
|
367
|
+
packing: { id: pack.id, purchaseOrderId: pack.purchaseOrderId, purchaseOrderIds: associationIds(pack), purchaseOrders, supplierId: pack.supplierId ?? null, revision: pack.revision, fileName: pack.fileName, status: pack.status ?? 'DRAFT', importedAt: pack.createdAt.toISOString(), importedById: pack.importedById ?? null, rowCount: lines.length, boundRowCount, unmatchedCount: lines.length - boundRowCount, warnings },
|
|
368
|
+
lines: dtos, purchaseLines: purchases, purchaseOrders, warnings
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
async touch(manager, scope, pack, lines) {
|
|
372
|
+
pack.status = 'DRAFT';
|
|
373
|
+
pack.revision += 1;
|
|
374
|
+
pack.updatedById = scope.userId ?? null;
|
|
375
|
+
pack.contentFingerprint = fingerprint(pack, lines);
|
|
376
|
+
await manager.getRepository(SupplierPacking).save(pack);
|
|
377
|
+
}
|
|
378
|
+
async validateQuantities(manager, scope, pack, lines, purchases, repair) {
|
|
379
|
+
const confirmed = await manager.getRepository(SupplierPacking).find({ where: { ...scoped(scope), status: 'CONFIRMED', deletedAt: IsNull() } });
|
|
380
|
+
const otherIds = confirmed.filter(other => other.id !== pack.id).map(other => other.id);
|
|
381
|
+
const others = otherIds.length ? await manager.getRepository(SupplierPackingLine).find({ where: { ...scoped(scope), packingId: In(otherIds), deletedAt: IsNull() } }) : [];
|
|
382
|
+
const totals = new Map();
|
|
383
|
+
for (const line of [...others, ...lines])
|
|
384
|
+
for (const a of effectiveAllocations(line)) {
|
|
385
|
+
if (!a.countsAsGoods)
|
|
386
|
+
continue;
|
|
387
|
+
totals.set(a.purchaseOrderLineId, (totals.get(a.purchaseOrderLineId) ?? new Decimal(0)).plus(a.quantity));
|
|
388
|
+
}
|
|
389
|
+
const changedAllocations = repair ? effectiveAllocations(lines.find(line => line.id === repair.lineId)) : [];
|
|
390
|
+
const affected = repair ? new Set([...repair.previousAllocations, ...changedAllocations].map(a => a.purchaseOrderLineId)) : null;
|
|
391
|
+
for (const purchase of purchases) {
|
|
392
|
+
if (affected && !affected.has(purchase.id))
|
|
393
|
+
continue;
|
|
394
|
+
const total = totals.get(purchase.id) ?? new Decimal(0);
|
|
395
|
+
if (!total.gt(purchase.quantity))
|
|
396
|
+
continue;
|
|
397
|
+
if (repair) {
|
|
398
|
+
const sumFor = (allocations) => allocations.filter(a => a.purchaseOrderLineId === purchase.id && a.countsAsGoods).reduce((sum, a) => sum.plus(a.quantity), new Decimal(0));
|
|
399
|
+
const previousTotal = total.minus(sumFor(changedAllocations)).plus(sumFor(repair.previousAllocations));
|
|
400
|
+
// Draft corrections may reduce an existing overcount in steps; confirmation still checks all goods.
|
|
401
|
+
if (total.lte(previousTotal))
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
invalid(`采购行 ${purchase.lineNumber} 累计出货数量超过采购数量 ${purchase.quantity}`);
|
|
405
|
+
}
|
|
105
406
|
}
|
|
106
407
|
};
|
|
107
408
|
SupplierPackingService = __decorate([
|
|
@@ -116,6 +417,9 @@ function prepareDraftRow(row, index, warnings) {
|
|
|
116
417
|
const qty = finiteOrNull(row.qty);
|
|
117
418
|
const cartons = finiteOrNull(row.cartons);
|
|
118
419
|
const weight = finiteOrNull(row.grossWeightPerCtnKg);
|
|
420
|
+
for (const value of [row.qty, row.cartons, row.grossWeightPerCtnKg])
|
|
421
|
+
if (value != null && (typeof value !== 'number' || !Number.isFinite(value) || value < 0))
|
|
422
|
+
invalid(`第 ${index + 1} 行数值必须为有限非负数`);
|
|
119
423
|
if (!model && qty == null && !description && cartons == null)
|
|
120
424
|
return null;
|
|
121
425
|
if (!model && qty == null) {
|
|
@@ -132,39 +436,44 @@ function prepareDraftRow(row, index, warnings) {
|
|
|
132
436
|
model, description, role: normalizeRole(row.role, description),
|
|
133
437
|
qty, cartons, dimensionCm: dimension?.text ?? null, grossWeightPerCtnKg: weight,
|
|
134
438
|
battery: textOrNull(row.battery), boxVolumeCbm,
|
|
135
|
-
totalVolumeCbm: boxVolumeCbm != null && cartons != null ? round6(boxVolumeCbm * cartons) : null,
|
|
136
|
-
totalGrossWeightKg: weight != null && cartons != null ? round6(weight * cartons) : null,
|
|
439
|
+
totalVolumeCbm: cartons === 0 ? 0 : boxVolumeCbm != null && cartons != null ? round6(boxVolumeCbm * cartons) : null,
|
|
440
|
+
totalGrossWeightKg: cartons === 0 ? 0 : weight != null && cartons != null ? round6(weight * cartons) : null,
|
|
137
441
|
sourceRow: index + 1
|
|
138
442
|
};
|
|
139
443
|
}
|
|
140
|
-
|
|
141
|
-
function bindRowsToPurchaseLines(rows, purchaseLines) {
|
|
444
|
+
function bindingsByModel(purchaseLines) {
|
|
142
445
|
const byKey = new Map();
|
|
143
446
|
for (const line of purchaseLines) {
|
|
144
|
-
const key
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
447
|
+
for (const key of new Set([normalizeModelKey(line.modelSpecification), normalizeModelKey(line.englishName)])) {
|
|
448
|
+
if (!key)
|
|
449
|
+
continue;
|
|
450
|
+
byKey.set(key, [...(byKey.get(key) ?? []), line]);
|
|
451
|
+
}
|
|
148
452
|
}
|
|
453
|
+
return byKey;
|
|
454
|
+
}
|
|
455
|
+
function bindRowsToPurchaseLines(rows, purchaseLines) {
|
|
456
|
+
const byKey = bindingsByModel(purchaseLines);
|
|
149
457
|
const matchWarnings = [];
|
|
150
458
|
const bindings = rows.map(row => {
|
|
151
|
-
const
|
|
152
|
-
const candidates = key ? byKey.get(key) ?? [] : [];
|
|
153
|
-
if (!candidates.length)
|
|
154
|
-
return { row, purchaseOrderLineId: null };
|
|
459
|
+
const candidates = byKey.get(normalizeModelKey(row.model) ?? '') ?? [];
|
|
155
460
|
if (candidates.length > 1)
|
|
156
|
-
matchWarnings.push(`第 ${row.sourceRow} 行型号对应 ${candidates.length}
|
|
157
|
-
return { row, purchaseOrderLineId: candidates[0].id };
|
|
461
|
+
matchWarnings.push(`第 ${row.sourceRow} 行型号对应 ${candidates.length} 条采购行,请人工分配`);
|
|
462
|
+
return { row, purchaseOrderLineId: candidates.length === 1 && !specificationConflict(row.model, candidates[0]) ? candidates[0].id : null };
|
|
158
463
|
});
|
|
159
464
|
const qtyByLine = new Map();
|
|
160
465
|
for (const binding of bindings) {
|
|
161
466
|
if (!binding.purchaseOrderLineId || binding.row.qty == null)
|
|
162
467
|
continue;
|
|
163
|
-
|
|
468
|
+
const purchase = purchaseLines.find(line => line.id === binding.purchaseOrderLineId);
|
|
469
|
+
const hasMain = bindings.some(other => other.purchaseOrderLineId === purchase.id && other.row.role !== 'BOOM' && other.row.role !== 'PART');
|
|
470
|
+
if (!countsAsGoods(binding.row.role, purchase, hasMain))
|
|
471
|
+
continue;
|
|
472
|
+
qtyByLine.set(purchase.id, (qtyByLine.get(purchase.id) ?? 0) + binding.row.qty);
|
|
164
473
|
}
|
|
165
|
-
for (const [
|
|
166
|
-
const line = purchaseLines.find(item => item.id ===
|
|
167
|
-
if (
|
|
474
|
+
for (const [id, total] of qtyByLine) {
|
|
475
|
+
const line = purchaseLines.find(item => item.id === id);
|
|
476
|
+
if (Math.abs(Number(line.quantity) - total) > 0.0001)
|
|
168
477
|
matchWarnings.push(`采购行 ${line.lineNumber}(${line.englishName ?? line.productName})装箱数量合计 ${trimNumber(total)} 与采购数量 ${trimNumber(Number(line.quantity))} 不一致,请核对`);
|
|
169
478
|
}
|
|
170
479
|
return { bindings, matchWarnings };
|
|
@@ -193,10 +502,12 @@ function parseDimensionCm(value) {
|
|
|
193
502
|
return { text, volumeCbm: round6((numbers[0] * numbers[1] * numbers[2]) / 1_000_000) };
|
|
194
503
|
}
|
|
195
504
|
export function normalizeModelKey(value) {
|
|
196
|
-
|
|
197
|
-
if (!text)
|
|
505
|
+
let text = String(value ?? '').trim().toLowerCase();
|
|
506
|
+
if (!text || /\*/.test(text))
|
|
198
507
|
return null;
|
|
199
|
-
|
|
508
|
+
// Only documented identity suffixes are removable; numeric specification decimals remain significant.
|
|
509
|
+
text = text.replace(/\s*\(zam230\)\s*$/i, '').replace(/\/(?:id|battery)\s*$/i, '');
|
|
510
|
+
return text.replace(/\s+/g, '').replace(/[/\\\-_·()()]/g, '') || null;
|
|
200
511
|
}
|
|
201
512
|
function packingLineDto(line, row) {
|
|
202
513
|
return {
|
|
@@ -204,7 +515,7 @@ function packingLineDto(line, row) {
|
|
|
204
515
|
model: line.model, normalizedModel: line.normalizedModel, description: line.description, role: line.role,
|
|
205
516
|
qty: line.qty, cartons: line.cartons, dimensionCm: line.dimensionCm, grossWeightPerCtnKg: line.grossWeightPerCtnKg,
|
|
206
517
|
battery: line.battery, boxVolumeCbm: line.boxVolumeCbm, totalVolumeCbm: line.totalVolumeCbm, totalGrossWeightKg: line.totalGrossWeightKg,
|
|
207
|
-
purchaseOrderLineId: line.purchaseOrderLineId
|
|
518
|
+
purchaseOrderLineId: line.purchaseOrderLineId, allocations: effectiveAllocations(line), candidates: [], needsReview: null
|
|
208
519
|
};
|
|
209
520
|
}
|
|
210
521
|
function textOrNull(value) {
|
|
@@ -226,4 +537,75 @@ function round6(value) {
|
|
|
226
537
|
function scoped(scope) {
|
|
227
538
|
return { tenantId: scope.tenantId, organizationId: scope.organizationId };
|
|
228
539
|
}
|
|
540
|
+
function invalid(message) { throw new DomainError(DomainErrorCodes.INVALID_INPUT, message); }
|
|
541
|
+
function associationIds(pack) { return pack.purchaseOrderIds?.length ? pack.purchaseOrderIds : [pack.purchaseOrderId]; }
|
|
542
|
+
function uniqueIds(ids) { return [...new Set(ids.filter(Boolean))]; }
|
|
543
|
+
function sameIds(a, b) { return JSON.stringify(uniqueIds(a).sort()) === JSON.stringify(uniqueIds(b).sort()); }
|
|
544
|
+
function allocation(purchaseOrderLineId, quantity, countsAsGoods) { return { purchaseOrderLineId, quantity, countsAsGoods, cartons: null, grossKg: null, volumeCbm: null }; }
|
|
545
|
+
function effectiveAllocations(line) {
|
|
546
|
+
return line.allocations?.length ? line.allocations : line.purchaseOrderLineId ? [allocation(line.purchaseOrderLineId, line.qty ?? '0', line.role !== 'BOOM' && line.role !== 'PART')] : [];
|
|
547
|
+
}
|
|
548
|
+
function countsAsGoods(role, line, hasMain) {
|
|
549
|
+
const orderedPart = /配件|备件|闸杆|boom|spare|(?:^|\s)parts?(?:\s|$)/i.test(`${line.productName} ${line.englishName ?? ''} ${line.modelSpecification ?? ''}`);
|
|
550
|
+
return role !== 'BOOM' && role !== 'PART' || orderedPart;
|
|
551
|
+
}
|
|
552
|
+
function positive(value) { return value != null && Number.isFinite(Number(value)) && Number(value) > 0; }
|
|
553
|
+
function purchaseLineDto(line, orders) {
|
|
554
|
+
return { id: line.id, purchaseOrderId: line.purchaseOrderId, contractNo: orders.find(order => order.id === line.purchaseOrderId)?.contractNo ?? '', lineNumber: line.lineNumber, productName: line.productName, englishName: line.englishName, modelSpecification: line.modelSpecification, quantity: line.quantity };
|
|
555
|
+
}
|
|
556
|
+
function validateAllocations(line, input, purchases) {
|
|
557
|
+
if (!Array.isArray(input))
|
|
558
|
+
invalid('装箱分配必须为数组');
|
|
559
|
+
if (new Set(input.map(a => a.purchaseOrderLineId)).size !== input.length)
|
|
560
|
+
invalid('同一包装行不能重复分配同一商品');
|
|
561
|
+
const allocations = input.map(a => {
|
|
562
|
+
if (!purchases.some(p => p.id === a.purchaseOrderLineId))
|
|
563
|
+
invalid('分配商品不属于批次关联采购合同');
|
|
564
|
+
if (typeof a.countsAsGoods !== 'boolean')
|
|
565
|
+
invalid('请指定是否计入商品出货数量');
|
|
566
|
+
const numeric = (value, nullable) => {
|
|
567
|
+
if (value == null && nullable)
|
|
568
|
+
return null;
|
|
569
|
+
if (typeof value !== 'string' || !value.trim())
|
|
570
|
+
invalid('分配数值必须为有效非负数字字符串');
|
|
571
|
+
let number;
|
|
572
|
+
try {
|
|
573
|
+
number = new Decimal(value);
|
|
574
|
+
}
|
|
575
|
+
catch {
|
|
576
|
+
invalid('分配数值必须为有效非负数字字符串');
|
|
577
|
+
}
|
|
578
|
+
if (!number.isFinite() || number.isNegative())
|
|
579
|
+
invalid('分配数值必须为有效非负数字字符串');
|
|
580
|
+
return number.toFixed();
|
|
581
|
+
};
|
|
582
|
+
return { purchaseOrderLineId: a.purchaseOrderLineId, quantity: numeric(a.quantity, false), countsAsGoods: a.countsAsGoods, cartons: numeric(a.cartons, true), grossKg: numeric(a.grossKg, true), volumeCbm: numeric(a.volumeCbm, true) };
|
|
583
|
+
});
|
|
584
|
+
if (!allocations.length)
|
|
585
|
+
return allocations;
|
|
586
|
+
const qty = allocations.reduce((total, a) => total.plus(a.quantity), new Decimal(0));
|
|
587
|
+
if (line.qty == null || !qty.eq(line.qty))
|
|
588
|
+
invalid('分配数量合计必须等于包装行数量');
|
|
589
|
+
for (const [field, original] of [['cartons', line.cartons], ['grossKg', line.totalGrossWeightKg], ['volumeCbm', line.totalVolumeCbm]]) {
|
|
590
|
+
if (!allocations.some(a => a[field] != null))
|
|
591
|
+
continue;
|
|
592
|
+
if (original == null || allocations.some(a => a[field] == null))
|
|
593
|
+
invalid('包装指标分配必须完整且原始指标存在');
|
|
594
|
+
const total = allocations.reduce((sum, a) => sum.plus(a[field]), new Decimal(0));
|
|
595
|
+
if (total.minus(original).abs().gt('0.000001'))
|
|
596
|
+
invalid('包装指标分配合计必须等于原包装行');
|
|
597
|
+
}
|
|
598
|
+
return allocations;
|
|
599
|
+
}
|
|
600
|
+
function fingerprint(pack, lines) {
|
|
601
|
+
return createHash('sha256').update(JSON.stringify({ purchaseOrderIds: associationIds(pack), revision: pack.revision, status: pack.status, lines: lines.map(line => ({ model: line.model, role: line.role, qty: line.qty, cartons: line.cartons, dimensionCm: line.dimensionCm, grossWeightPerCtnKg: line.grossWeightPerCtnKg, allocations: effectiveAllocations(line) })) })).digest('hex');
|
|
602
|
+
}
|
|
603
|
+
function specificationConflict(model, line) {
|
|
604
|
+
const key = normalizeModelKey(model), spec = normalizeModelKey(line.modelSpecification);
|
|
605
|
+
return !!key && !!spec && key !== spec && key === normalizeModelKey(line.englishName);
|
|
606
|
+
}
|
|
607
|
+
function isCompanion(line, lines) {
|
|
608
|
+
const allocations = effectiveAllocations(line);
|
|
609
|
+
return line.cartons != null && Number(line.cartons) === 0 && (line.role === 'BOOM' || line.role === 'PART') && allocations.length > 0 && allocations.every(a => !a.countsAsGoods && lines.some(other => other.id !== line.id && positive(other.cartons) && effectiveAllocations(other).some(b => b.purchaseOrderLineId === a.purchaseOrderLineId)));
|
|
610
|
+
}
|
|
229
611
|
//# sourceMappingURL=supplier-packing.service.js.map
|