import { pool } from '../db'; import type { QuerySpec } from './queryExecutor'; const LOCKED_PREP_FIELDS = new Set([ 'prepare_qty', 'purchase_price', 'supplier_code', 'sku_code', 'order_code', 'item_name', 'category_code', ]); /** 完成后仍允许单独改采购价(管理员纠错);数量等其它锁定字段仍禁止 */ const PRICE_ONLY_UNLOCK_FIELDS = new Set(['purchase_price', 'updated_at']); function isPurchasePriceOnlyUpdate(record: Record): boolean { const keys = Object.keys(record).filter((key) => record[key] !== undefined); if (!keys.includes('purchase_price')) return false; return keys.every((key) => PRICE_ONLY_UNLOCK_FIELDS.has(key) || key === 'prepare_status'); } export async function validateTableWrite(spec: QuerySpec) { if (spec.table !== 'supplier_preparations' || spec.action !== 'update') return; const record = (spec.updateData || {}) as Record; const changingLockedFields = Object.keys(record).some( (key) => record[key] !== undefined && LOCKED_PREP_FIELDS.has(key) ); const nextStatus = record.prepare_status !== undefined ? Number(record.prepare_status) : null; const ids: string[] = []; for (const filter of spec.filters || []) { if (filter.op === 'eq' && filter.column === 'id' && filter.value) { ids.push(String(filter.value)); } if (filter.op === 'in' && filter.column === 'id' && Array.isArray(filter.value)) { ids.push(...filter.value.map(String)); } } if (!ids.length) return; const existing = await pool.query( `SELECT id, prepare_status, is_stockout FROM supplier_preparations WHERE id = ANY($1::uuid[])`, [ids] ); for (const row of existing.rows) { const currentStatus = Number(row.prepare_status) || 0; if (currentStatus >= 30 && nextStatus !== 40) { const priceOnly = isPurchasePriceOnlyUpdate(record); if ( (changingLockedFields && !priceOnly) || (nextStatus !== null && nextStatus !== currentStatus && nextStatus < 30) ) { throw new Error('备货已确认锁定,不可修改数量等字段(采购价可由管理员单独纠正)'); } } if (currentStatus >= 30 && nextStatus !== null && nextStatus < 30) { throw new Error('备货已完成,不可回退状态'); } } }