-- ============================================
-- 此文件由 Meoo Cloud 自动生成，请勿修改
-- This file is auto-generated by Meoo Cloud, DO NOT MODIFY
-- ============================================


CREATE OR REPLACE FUNCTION log_data_audit()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE
 v_old_values JSONB;
 v_new_values JSONB;
 v_operation TEXT;
BEGIN
 v_operation := TG_OP;
 
 IF TG_OP = 'DELETE' THEN
 v_old_values := to_jsonb(OLD);
 v_new_values := NULL;
 ELSIF TG_OP = 'UPDATE' THEN
 v_old_values := to_jsonb(OLD);
 v_new_values := to_jsonb(NEW);
 ELSE
 v_old_values := NULL;
 v_new_values := to_jsonb(NEW);
 END IF;
 
 INSERT INTO data_audit_logs (
 table_name, record_id, operation, old_values, new_values, changed_by
 ) VALUES (
 TG_TABLE_NAME,
 COALESCE(NEW.id, OLD.id),
 v_operation,
 v_old_values,
 v_new_values,
 auth.uid()
 );
 
 IF TG_OP = 'DELETE' THEN
 RETURN OLD;
 ELSE
 RETURN NEW;
 END IF;
END;
$$;

DROP TRIGGER IF EXISTS trg_audit_production_plans ON production_plans;
CREATE TRIGGER trg_audit_production_plans
 AFTER INSERT OR UPDATE OR DELETE ON production_plans
 FOR EACH ROW
 EXECUTE FUNCTION log_data_audit();

DROP TRIGGER IF EXISTS trg_audit_inventory_records ON inventory_records;
CREATE TRIGGER trg_audit_inventory_records
 AFTER INSERT OR UPDATE OR DELETE ON inventory_records
 FOR EACH ROW
 EXECUTE FUNCTION log_data_audit();

DROP TRIGGER IF EXISTS trg_audit_payments ON payments;
CREATE TRIGGER trg_audit_payments
 AFTER INSERT OR UPDATE OR DELETE ON payments
 FOR EACH ROW
 EXECUTE FUNCTION log_data_audit();

DROP TRIGGER IF EXISTS trg_audit_accounts_payable ON accounts_payable;
CREATE TRIGGER trg_audit_accounts_payable
 AFTER INSERT OR UPDATE OR DELETE ON accounts_payable
 FOR EACH ROW
 EXECUTE FUNCTION log_data_audit();

DROP TRIGGER IF EXISTS trg_audit_accounts_payable_items ON accounts_payable_items;
CREATE TRIGGER trg_audit_accounts_payable_items
 AFTER INSERT OR UPDATE OR DELETE ON accounts_payable_items
 FOR EACH ROW
 EXECUTE FUNCTION log_data_audit();

