import { executeQuery, type QuerySpec } from './queryExecutor'; import { writeAuditLog } from './auditService'; import type { TenantContext } from './tenantScope'; export const DATA_AUDIT_BULK_THRESHOLD = 10; /** 批量写保留的明细样本条数:超过部分只记数量,避免一次批量操作刷出成千上万条日志 */ export const DATA_AUDIT_BULK_DETAIL_LIMIT = 10; /** 写前快照只取样本行;命中总数由 count 单独返回,不随命中行数增长(不吃内存) */ const DATA_AUDIT_SNAPSHOT_LIMIT = DATA_AUDIT_BULK_DETAIL_LIMIT; const SENSITIVE_FIELD = /password|passwd|secret|token|private_key|access_key|image_data/i; const SKIP_FIELDS = new Set(['updated_at', 'created_at', 'image_data']); const ROW_KEY_COLUMNS = [ 'sku_code', 'code', 'order_code', 'customer_code', 'supplier_code', 'purchase_code', 'id', ]; const NAME_COLUMNS = ['sku_name', 'name', 'item_name', 'full_name', 'title']; export type DataWriteChange = { field: string; before: unknown; after: unknown }; export type DataWriteRowSample = { key?: string | null; name?: string | null; customer_code?: string | null; price?: unknown; unit?: string | null; source_type?: string | null; }; export type DataWriteAuditPayload = { kind: 'data_write'; bulk: boolean; bulk_count?: number; bulk_detail_limit?: number; row_key?: string | null; row_name?: string | null; changes?: DataWriteChange[]; inserted?: DataWriteRowSample[]; updated?: DataWriteRowSample[]; deleted?: DataWriteRowSample[]; }; type DbLike = { query: (sql: string, params?: unknown[]) => Promise<{ rows: unknown[]; rowCount?: number | null }> }; function asRows(data: unknown): Record[] { if (!data) return []; return Array.isArray(data) ? (data as Record[]) : [data as Record]; } function insertRowCount(spec: QuerySpec): number { if (!spec.insertData) return 0; return Array.isArray(spec.insertData) ? spec.insertData.length : 1; } export function pickRowKey(row: Record | null | undefined, spec?: QuerySpec): string | null { if (spec?.filters) { for (const col of ROW_KEY_COLUMNS) { const hit = spec.filters.find((f) => f.op === 'eq' && f.column === col && f.value != null && f.value !== ''); if (hit) return String(hit.value); } } if (!row) return null; for (const col of ROW_KEY_COLUMNS) { if (row[col] != null && String(row[col]).trim() !== '') return String(row[col]); } return null; } export function pickRowName(row: Record | null | undefined): string | null { if (!row) return null; for (const col of NAME_COLUMNS) { if (row[col] != null && String(row[col]).trim() !== '') return String(row[col]); } return null; } function valuesEqual(a: unknown, b: unknown): boolean { if (a === b) return true; if (a == null && b == null) return true; try { return JSON.stringify(a) === JSON.stringify(b); } catch { return String(a) === String(b); } } export function diffPatch( before: Record | null | undefined, patch: Record ): DataWriteChange[] { const changes: DataWriteChange[] = []; for (const [field, after] of Object.entries(patch)) { if (after === undefined) continue; if (SKIP_FIELDS.has(field) || SENSITIVE_FIELD.test(field)) continue; const prev = before ? before[field] : undefined; if (valuesEqual(prev, after)) continue; changes.push({ field, before: prev ?? null, after }); } return changes.slice(0, 20); } export function buildDataWritePayload(input: { spec: QuerySpec; beforeRows: Record[]; beforeCount: number; resultCount: number; resultData: unknown; }): DataWriteAuditPayload | null { const { spec, beforeRows, beforeCount, resultCount, resultData } = input; const action = spec.action; if (action === 'select') return null; const detailLimit = DATA_AUDIT_BULK_DETAIL_LIMIT; /** 批量:保留前 N 条明细样本 + 命中总数,不再一行一条 */ const bulkPayload = ( count: number, key: 'inserted' | 'updated' | 'deleted', samples: DataWriteRowSample[] ): DataWriteAuditPayload => ({ kind: 'data_write', bulk: true, bulk_count: count, bulk_detail_limit: detailLimit, [key]: samples.slice(0, detailLimit), }); if (action === 'insert') { const n = insertRowCount(spec) || resultCount; const rows = asRows(resultData); const insertRows = asRows(spec.insertData); const sources = rows.length ? rows : insertRows; const toEntry = (row: Record, index: number): DataWriteRowSample => { const extra = spec.table === 'customer_quote_versions' ? insertRows[index] || row : row; const entry: DataWriteRowSample = { key: pickRowKey(row), name: pickRowName(row) || pickRowName(extra), }; if (spec.table !== 'customer_quote_versions') return entry; const src = { ...extra, ...row }; return { ...entry, customer_code: src.customer_code != null && String(src.customer_code).trim() ? String(src.customer_code) : null, price: src.price ?? null, unit: src.unit != null && String(src.unit).trim() ? String(src.unit) : null, source_type: src.source_type != null && String(src.source_type).trim() ? String(src.source_type) : null, }; }; if (n > DATA_AUDIT_BULK_THRESHOLD) { return bulkPayload(n, 'inserted', sources.map(toEntry)); } return { kind: 'data_write', bulk: false, inserted: sources.slice(0, detailLimit).map(toEntry), }; } if (action === 'update') { if (beforeCount > DATA_AUDIT_BULK_THRESHOLD || resultCount > DATA_AUDIT_BULK_THRESHOLD) { // 命中多行:只记前 N 条明细 + 总数(同一 patch 作用于全部命中行) return bulkPayload( Math.max(beforeCount, resultCount), 'updated', beforeRows.map((row) => ({ key: pickRowKey(row, spec), name: pickRowName(row) })) ); } const patch = (spec.updateData || {}) as Record; const before = beforeRows[0] || null; const changes = diffPatch(before, patch); if (!changes.length) return null; return { kind: 'data_write', bulk: false, row_key: pickRowKey(before, spec), row_name: pickRowName(before), changes, }; } if (action === 'delete') { const rows = beforeRows.length ? beforeRows : asRows(resultData); const toEntry = (row: Record) => ({ key: pickRowKey(row, spec), name: pickRowName(row), }); if (beforeCount > DATA_AUDIT_BULK_THRESHOLD || resultCount > DATA_AUDIT_BULK_THRESHOLD) { return bulkPayload(Math.max(beforeCount, resultCount), 'deleted', rows.map(toEntry)); } return { kind: 'data_write', bulk: false, deleted: rows.slice(0, detailLimit).map(toEntry), }; } return null; } function auditSelectColumns(spec: QuerySpec): string { if (spec.table === 'skus') { return 'sku_code, sku_name, category_code, unit, spec, barcode, brand, status, stock_mode, default_loss_threshold'; } if (spec.table === 'product_catalog') { return 'code, name, item_type, status, parent_code, unit'; } return '*'; } export async function snapshotRowsBeforeWrite( spec: QuerySpec, db: DbLike ): Promise<{ rows: Record[]; count: number }> { if (spec.action !== 'update' && spec.action !== 'delete') { return { rows: [], count: 0 }; } const result = await executeQuery( { table: spec.table, action: 'select', select: auditSelectColumns(spec), filters: spec.filters, count: 'exact', limit: DATA_AUDIT_SNAPSHOT_LIMIT, }, db ); const rows = asRows(result.data); return { rows, count: Number(result.count ?? rows.length) }; } export async function writeDataSpecAudit(input: { spec: QuerySpec; beforeRows: Record[]; beforeCount: number; result: { data?: unknown; error?: unknown; count?: number | null }; ctx: TenantContext | null; branchCode?: string | null; }): Promise { const { spec, result } = input; if (result.error) return; if (spec.table === 'orders' && spec.action === 'delete') return; const payload = buildDataWritePayload({ spec, beforeRows: input.beforeRows, beforeCount: input.beforeCount, resultCount: Number(result.count ?? 0), resultData: result.data, }); if (!payload) return; const targetId = payload.row_key || payload.inserted?.[0]?.key || payload.updated?.[0]?.key || payload.deleted?.[0]?.key || (payload.bulk ? `bulk:${payload.bulk_count}` : null); await writeAuditLog({ operatorId: input.ctx?.userId || null, operatorRole: input.ctx?.roles?.join(',') || null, operationType: `data_${spec.action}`, actionCategory: 'data', targetTable: spec.table, targetId: targetId ?? undefined, branchCode: input.branchCode || input.ctx?.branchCode || null, newValue: payload, }); } export async function writeDataBatchAudit(input: { specs: QuerySpec[]; results: Array<{ data?: unknown; error?: unknown; count?: number | null }>; snapshots?: Array<{ rows: Record[]; count: number }>; ctx: TenantContext | null; branchCode?: string | null; }): Promise { const { specs, results, ctx, branchCode, snapshots = [] } = input; const total = results.reduce((sum, row, i) => { if (row.error) return sum; const spec = specs[i]; if (spec?.action === 'insert') return sum + insertRowCount(spec); return sum + Number(row.count ?? 0); }, 0); if (total <= 0) return; if (total > DATA_AUDIT_BULK_THRESHOLD || specs.length > DATA_AUDIT_BULK_THRESHOLD) { const tables = [...new Set(specs.map((s) => s.table).filter(Boolean))]; await writeAuditLog({ operatorId: ctx?.userId || null, operatorRole: ctx?.roles?.join(',') || null, operationType: 'data_batch', actionCategory: 'data', targetTable: tables[0] || 'batch', targetId: `bulk:${total}`, branchCode: branchCode || ctx?.branchCode || null, newValue: { kind: 'data_write', bulk: true, bulk_count: total, tables, }, }); return; } for (let i = 0; i < specs.length; i += 1) { const spec = specs[i]; const result = results[i]; if (!spec || !result || result.error) continue; const snap = snapshots[i] || { rows: [], count: 0 }; await writeDataSpecAudit({ spec, beforeRows: snap.rows, beforeCount: snap.count, result, ctx, branchCode, }); } }