fix(分拣/核货): 保护分拣数量证据与核货照片
- loaded_qty 仍可改且保留审计 - picked_qty/weight 变更写 picking_qty_edit 审计 - 核货补录不覆盖已有分拣/核货/照片证据 - loading_photos 追加去重,不再覆盖旧照片
This commit is contained in:
@@ -283,6 +283,8 @@ export function mountPickingWorkflowRoutes(router: Router): void {
|
||||
const data = await updatePickingItemProgress({
|
||||
pickCode: String(req.body?.pick_code || ''),
|
||||
rows: Array.isArray(req.body?.items) ? req.body.items : [],
|
||||
operatorId: ctx?.userId || null,
|
||||
source: 'web_picking_progress',
|
||||
});
|
||||
return res.json({ data });
|
||||
} catch (error: any) {
|
||||
|
||||
@@ -821,7 +821,12 @@ router.post('/picking/progress', authMiddleware, async (req: AuthRequest, res: R
|
||||
if (!pickCode || !rows.length) {
|
||||
return res.status(400).json({ error: 'invalid_request', error_description: '缺少分拣明细' });
|
||||
}
|
||||
const data = await updatePickingItemProgress({ pickCode, rows });
|
||||
const data = await updatePickingItemProgress({
|
||||
pickCode,
|
||||
rows,
|
||||
operatorId: (req as any).user?.id || null,
|
||||
source: 'mobile_picking_progress',
|
||||
});
|
||||
return res.json({ success: true, data });
|
||||
} catch (error: any) {
|
||||
return res.status(error?.status || 500).json({ error: error?.code || 'server_error', error_description: error?.message || '保存分拣进度失败' });
|
||||
|
||||
@@ -877,20 +877,55 @@ export async function backfillLoadingItemUpstream(input: LoadingBackfillInput):
|
||||
);
|
||||
const settlement = resolvePickingSettlementQty(measures.picked_qty, measures.picked_weight, unit);
|
||||
const { updatePickingItemProgress, confirmPickingComplete } = await import('./pickingService');
|
||||
await updatePickingItemProgress({
|
||||
pickCode,
|
||||
rows: [
|
||||
{
|
||||
id: String(item.pick_item_id),
|
||||
required_qty: requiredQty,
|
||||
picked_qty: settlement || confirmedQty,
|
||||
picked_weight: measures.picked_weight,
|
||||
unit,
|
||||
diff_reason: '',
|
||||
},
|
||||
],
|
||||
});
|
||||
pickingQty = settlement || confirmedQty;
|
||||
const evidence = await pool.query(
|
||||
`SELECT COALESCE(picked_qty, 0)::float AS picked_qty,
|
||||
COALESCE(picked_weight, 0)::float AS picked_weight,
|
||||
COALESCE(loaded_qty, 0)::float AS loaded_qty,
|
||||
COALESCE(array_length(loading_photos, 1), 0)::int AS photo_count
|
||||
FROM picking_items WHERE id = $1 LIMIT 1`,
|
||||
[String(item.pick_item_id)]
|
||||
);
|
||||
const evidenceRow = evidence.rows[0] || {};
|
||||
const hasPickingEvidence =
|
||||
Number(evidenceRow.picked_qty) > 0 ||
|
||||
Number(evidenceRow.picked_weight) > 0 ||
|
||||
Number(evidenceRow.loaded_qty) > 0 ||
|
||||
Number(evidenceRow.photo_count) > 0;
|
||||
if (hasPickingEvidence) {
|
||||
// 已有实拣/实收/照片:不覆盖分拣数量,保留证据;只记录跳过。
|
||||
console.warn('[delivery-backfill] 已存在拣货/核货/照片证据,跳过覆盖分拣数量', {
|
||||
orderCode,
|
||||
pickCode,
|
||||
itemId: item.pick_item_id,
|
||||
pickedQty: evidenceRow.picked_qty,
|
||||
pickedWeight: evidenceRow.picked_weight,
|
||||
loadedQty: evidenceRow.loaded_qty,
|
||||
photoCount: evidenceRow.photo_count,
|
||||
});
|
||||
pickingQty =
|
||||
resolvePickingSettlementQty(
|
||||
evidenceRow.picked_qty,
|
||||
evidenceRow.picked_weight,
|
||||
unit
|
||||
) || confirmedQty;
|
||||
} else {
|
||||
await updatePickingItemProgress({
|
||||
pickCode,
|
||||
rows: [
|
||||
{
|
||||
id: String(item.pick_item_id),
|
||||
required_qty: requiredQty,
|
||||
picked_qty: settlement || confirmedQty,
|
||||
picked_weight: measures.picked_weight,
|
||||
unit,
|
||||
diff_reason: '',
|
||||
},
|
||||
],
|
||||
operatorId: input.operatorId || null,
|
||||
source: 'delivery_loading_backfill',
|
||||
});
|
||||
pickingQty = settlement || confirmedQty;
|
||||
}
|
||||
let taskItems = await pool.query(
|
||||
`SELECT id, required_qty, picked_qty, picked_weight, unit, review_status
|
||||
FROM picking_items WHERE pick_code = $1`,
|
||||
@@ -913,7 +948,12 @@ export async function backfillLoadingItemUpstream(input: LoadingBackfillInput):
|
||||
diff_reason: '',
|
||||
}));
|
||||
if (weightRows.length) {
|
||||
await updatePickingItemProgress({ pickCode, rows: weightRows });
|
||||
await updatePickingItemProgress({
|
||||
pickCode,
|
||||
rows: weightRows,
|
||||
operatorId: input.operatorId || null,
|
||||
source: 'delivery_loading_backfill',
|
||||
});
|
||||
taskItems = await pool.query(
|
||||
`SELECT id, required_qty, picked_qty, picked_weight, unit, review_status
|
||||
FROM picking_items WHERE pick_code = $1`,
|
||||
|
||||
@@ -1150,7 +1150,7 @@ export async function confirmDeliveryLoadingItem(input: {
|
||||
};
|
||||
}
|
||||
|
||||
export const MAX_LOADING_PHOTOS = 1;
|
||||
export const MAX_LOADING_PHOTOS = 2;
|
||||
|
||||
export async function uploadDeliveryLoadingPhoto(input: {
|
||||
taskCode: string;
|
||||
@@ -1212,7 +1212,10 @@ export async function uploadDeliveryLoadingPhoto(input: {
|
||||
});
|
||||
const updated = await pool.query(
|
||||
`UPDATE picking_items
|
||||
SET loading_photos = ARRAY[$2]::text[]
|
||||
SET loading_photos = CASE
|
||||
WHEN $2 = ANY(COALESCE(loading_photos, '{}'::text[])) THEN loading_photos
|
||||
ELSE array_append(COALESCE(loading_photos, '{}'::text[]), $2)
|
||||
END
|
||||
WHERE id = $1
|
||||
RETURNING COALESCE(array_length(loading_photos, 1), 0)::int AS loading_photo_count`,
|
||||
[item.id, filename]
|
||||
|
||||
@@ -1086,10 +1086,21 @@ export async function savePickingReview(input: {
|
||||
export async function updatePickingItemProgress(input: {
|
||||
pickCode: string;
|
||||
rows: PickingProgressRow[];
|
||||
operatorId?: string | null;
|
||||
source?: string | null;
|
||||
}) {
|
||||
const client = await pool.connect();
|
||||
/** 分拣保存可能写入"实际消耗的批次计划" ⇒ 报告候选在这一刻才成立,提交后入队(2026-10-24 核查项 1) */
|
||||
let queueTarget: { branchCode: string; orderCode: string } | null = null;
|
||||
const qtyChanges: Array<{
|
||||
id: string;
|
||||
orderCode: string | null;
|
||||
oldPickedQty: number;
|
||||
oldPickedWeight: number;
|
||||
newPickedQty: number;
|
||||
newPickedWeight: number;
|
||||
branchCode: string | null;
|
||||
}> = [];
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const taskResult = await client.query(
|
||||
@@ -1112,14 +1123,13 @@ export async function updatePickingItemProgress(input: {
|
||||
const requiredQty = Number(row.required_qty) || 0;
|
||||
const pickedQty = Number(row.picked_qty) || 0;
|
||||
const pickedWeight = Number(row.picked_weight) || 0;
|
||||
let unit = String(row.unit || '').trim() || null;
|
||||
if (!unit) {
|
||||
const existing = await client.query(
|
||||
`SELECT unit FROM picking_items WHERE id = $1 AND pick_code = $2`,
|
||||
[row.id, input.pickCode]
|
||||
);
|
||||
unit = existing.rows[0]?.unit ? String(existing.rows[0].unit).trim() : null;
|
||||
}
|
||||
const existing = await client.query(
|
||||
`SELECT unit, picked_qty, picked_weight, order_code
|
||||
FROM picking_items WHERE id = $1 AND pick_code = $2`,
|
||||
[row.id, input.pickCode]
|
||||
);
|
||||
const existingRow = existing.rows[0];
|
||||
let unit = String(row.unit || existingRow?.unit || '').trim() || null;
|
||||
const saved = normalizePickingSavedMeasures(pickedQty, pickedWeight, unit);
|
||||
const settlement = resolvePickingSettlementQty(saved.picked_qty, saved.picked_weight, unit);
|
||||
if (settlement <= 0) {
|
||||
@@ -1130,6 +1140,22 @@ export async function updatePickingItemProgress(input: {
|
||||
}
|
||||
if (Math.abs(requiredQty - settlement) > 0.0001) hasDiff = true;
|
||||
const itemStatus = pickingItemReviewStatus(requiredQty, saved.picked_qty, saved.picked_weight, unit);
|
||||
const oldPickedQty = Number(existingRow?.picked_qty) || 0;
|
||||
const oldPickedWeight = Number(existingRow?.picked_weight) || 0;
|
||||
if (
|
||||
Math.abs(oldPickedQty - saved.picked_qty) > 1e-9 ||
|
||||
Math.abs(oldPickedWeight - saved.picked_weight) > 1e-9
|
||||
) {
|
||||
qtyChanges.push({
|
||||
id: String(row.id),
|
||||
orderCode: existingRow?.order_code ? String(existingRow.order_code) : null,
|
||||
oldPickedQty,
|
||||
oldPickedWeight,
|
||||
newPickedQty: saved.picked_qty,
|
||||
newPickedWeight: saved.picked_weight,
|
||||
branchCode: task.branch_code ? String(task.branch_code) : null,
|
||||
});
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE picking_items
|
||||
SET picked_qty = $1, picked_weight = $2, review_status = $3, diff_reason = $4,
|
||||
@@ -1173,6 +1199,32 @@ export async function updatePickingItemProgress(input: {
|
||||
);
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
// 分拣改量审计:失败只告警,不阻断正常分拣保存。
|
||||
for (const change of qtyChanges) {
|
||||
try {
|
||||
await writeAuditLog({
|
||||
operatorId: input.operatorId || null,
|
||||
operationType: 'picking_qty_edit',
|
||||
targetTable: 'picking_items',
|
||||
targetId: change.id,
|
||||
oldValue: {
|
||||
picked_qty: change.oldPickedQty,
|
||||
picked_weight: change.oldPickedWeight,
|
||||
},
|
||||
newValue: {
|
||||
picked_qty: change.newPickedQty,
|
||||
picked_weight: change.newPickedWeight,
|
||||
order_code: change.orderCode,
|
||||
pick_code: input.pickCode,
|
||||
source: input.source || 'picking_progress',
|
||||
},
|
||||
branchCode: change.branchCode,
|
||||
actionCategory: 'picking',
|
||||
});
|
||||
} catch (auditError) {
|
||||
console.warn('[picking] 分拣改量审计失败', change.id, auditError);
|
||||
}
|
||||
}
|
||||
/** 提交后入队(尽力而为,失败不影响分拣保存):本单消耗的批次可能刚被确定 ⇒ 报告候选成立了 */
|
||||
if (queueTarget) {
|
||||
try {
|
||||
|
||||
@@ -27,8 +27,8 @@ describe('配送核货补拍不混入库照', () => {
|
||||
expect(sql).toContain('pi.order_item_id');
|
||||
expect(src).toContain('needs_loading_photo');
|
||||
expect(src).toContain('attachCategoryPhotoInspectionRequirements');
|
||||
expect(src).toContain('loading_photos = ARRAY[$2]::text[]');
|
||||
expect(src).toContain('MAX_LOADING_PHOTOS = 1');
|
||||
expect(src).toContain('array_append(COALESCE(loading_photos, \'{}\'::text[])');
|
||||
expect(src).toContain('MAX_LOADING_PHOTOS = 2');
|
||||
expect(src).not.toMatch(/UPDATE inspections[\s\S]*inspection_photos/);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const read = (rel: string) => readFileSync(new URL(`../${rel}`, import.meta.url), 'utf8');
|
||||
const picking = read('src/services/pickingService.ts');
|
||||
const backfill = read('src/services/deliveryLoadingBackfillService.ts');
|
||||
const loading = read('src/services/deliveryLoadingService.ts');
|
||||
|
||||
describe('分拣改量审计与证据保护', () => {
|
||||
it('updatePickingItemProgress 对 picked 实际变更写 operation_logs,失败只告警', () => {
|
||||
expect(picking).toContain("operationType: 'picking_qty_edit'");
|
||||
expect(picking).toContain('oldValue:');
|
||||
expect(picking).toContain('newValue:');
|
||||
expect(picking).toContain('pick_code: input.pickCode');
|
||||
expect(picking).toContain('分拣改量审计失败');
|
||||
});
|
||||
|
||||
it('补录已有 picked/loaded/照片时不覆盖分拣数量', () => {
|
||||
const start = backfill.indexOf('const evidence = await pool.query(');
|
||||
const end = backfill.indexOf('pickingQty = settlement', start);
|
||||
const fn = backfill.slice(start, end);
|
||||
expect(fn).toContain('picked_qty');
|
||||
expect(fn).toContain('loaded_qty');
|
||||
expect(fn).toContain('photo_count');
|
||||
expect(fn).toContain('hasPickingEvidence');
|
||||
expect(fn).toContain('跳过覆盖分拣数量');
|
||||
});
|
||||
|
||||
it('核货照片追加去重,不再覆盖旧照片', () => {
|
||||
expect(loading).toContain('array_append(COALESCE(loading_photos');
|
||||
expect(loading).toContain('WHEN $2 = ANY(COALESCE(loading_photos');
|
||||
expect(loading).not.toContain('loading_photos = ARRAY[$2]::text[]');
|
||||
});
|
||||
|
||||
it('loaded_qty 改量与既有 delivery_loading_qty_edit 审计保留', () => {
|
||||
expect(loading).toContain("operationType: 'delivery_loading_qty_edit'");
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user