diff --git a/server/src/modules/workflow/routes/pickingRoutes.ts b/server/src/modules/workflow/routes/pickingRoutes.ts index fee29eb..399502c 100644 --- a/server/src/modules/workflow/routes/pickingRoutes.ts +++ b/server/src/modules/workflow/routes/pickingRoutes.ts @@ -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) { diff --git a/server/src/routes/mobile/mobileWarehouseRoutes.ts b/server/src/routes/mobile/mobileWarehouseRoutes.ts index e74152d..d18b027 100644 --- a/server/src/routes/mobile/mobileWarehouseRoutes.ts +++ b/server/src/routes/mobile/mobileWarehouseRoutes.ts @@ -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 || '保存分拣进度失败' }); diff --git a/server/src/services/deliveryLoadingBackfillService.ts b/server/src/services/deliveryLoadingBackfillService.ts index b5b8036..cd0180a 100644 --- a/server/src/services/deliveryLoadingBackfillService.ts +++ b/server/src/services/deliveryLoadingBackfillService.ts @@ -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`, diff --git a/server/src/services/deliveryLoadingService.ts b/server/src/services/deliveryLoadingService.ts index d76bea4..6e1ab8a 100644 --- a/server/src/services/deliveryLoadingService.ts +++ b/server/src/services/deliveryLoadingService.ts @@ -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] diff --git a/server/src/services/pickingService.ts b/server/src/services/pickingService.ts index ec30ef9..7de9faf 100644 --- a/server/src/services/pickingService.ts +++ b/server/src/services/pickingService.ts @@ -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 { diff --git a/server/tests/deliveryLoadingPhotos.test.ts b/server/tests/deliveryLoadingPhotos.test.ts index acaa190..6f92304 100644 --- a/server/tests/deliveryLoadingPhotos.test.ts +++ b/server/tests/deliveryLoadingPhotos.test.ts @@ -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/); }); diff --git a/server/tests/pickingQtyEvidenceAudit.test.ts b/server/tests/pickingQtyEvidenceAudit.test.ts new file mode 100644 index 0000000..61f4d2d --- /dev/null +++ b/server/tests/pickingQtyEvidenceAudit.test.ts @@ -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'"); + }); +});