import db from "../db.js"; /** * Log a field change to the history table */ export function logFieldChange(tableName, recordId, fieldName, oldValue, newValue, changedBy = null, reason = null) { // Don't log if values are the same if (oldValue === newValue) return null; const stmt = db.prepare(` INSERT INTO field_change_history (table_name, record_id, field_name, old_value, new_value, changed_by, change_reason) VALUES (?, ?, ?, ?, ?, ?, ?) `); return stmt.run( tableName, recordId, fieldName, oldValue || null, newValue || null, changedBy, reason ); } /** * Get field change history for a specific field */ export function getFieldHistory(tableName, recordId, fieldName) { const stmt = db.prepare(` SELECT fch.*, u.name as changed_by_name, u.username as changed_by_username FROM field_change_history fch LEFT JOIN users u ON fch.changed_by = u.id WHERE fch.table_name = ? AND fch.record_id = ? AND fch.field_name = ? ORDER BY fch.changed_at DESC `); return stmt.all(tableName, recordId, fieldName); } /** * Get all field changes for a specific record */ export function getAllFieldHistory(tableName, recordId) { const stmt = db.prepare(` SELECT fch.*, u.name as changed_by_name, u.username as changed_by_username FROM field_change_history fch LEFT JOIN users u ON fch.changed_by = u.id WHERE fch.table_name = ? AND fch.record_id = ? ORDER BY fch.changed_at DESC, fch.field_name ASC `); return stmt.all(tableName, recordId); } /** * Check if a field has any change history */ export function hasFieldHistory(tableName, recordId, fieldName) { const stmt = db.prepare(` SELECT COUNT(*) as count FROM field_change_history WHERE table_name = ? AND record_id = ? AND field_name = ? `); const result = stmt.get(tableName, recordId, fieldName); return result.count > 0; } /** * Get the most recent change for a field */ export function getLatestFieldChange(tableName, recordId, fieldName) { const stmt = db.prepare(` SELECT fch.*, u.name as changed_by_name, u.username as changed_by_username FROM field_change_history fch LEFT JOIN users u ON fch.changed_by = u.id WHERE fch.table_name = ? AND fch.record_id = ? AND fch.field_name = ? ORDER BY fch.changed_at DESC LIMIT 1 `); return stmt.get(tableName, recordId, fieldName); }