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


ALTER TABLE inventory_records 
 DROP CONSTRAINT IF EXISTS chk_inventory_positive;
ALTER TABLE inventory_records 
 ADD CONSTRAINT chk_inventory_positive 
 CHECK (quantity >= 0 AND rolls >= 0 AND (price_per_meter IS NULL OR price_per_meter >= 0));

ALTER TABLE payments 
 DROP CONSTRAINT IF EXISTS chk_payment_positive;
ALTER TABLE payments 
 ADD CONSTRAINT chk_payment_positive 
 CHECK (amount >= 0 AND quantity >= 0 AND price_per_meter >= 0);

ALTER TABLE accounts_payable 
 DROP CONSTRAINT IF EXISTS chk_ap_amounts;
ALTER TABLE accounts_payable 
 ADD CONSTRAINT chk_ap_amounts 
 CHECK (
 total_amount >= 0 AND 
 paid_amount >= 0 AND 
 unpaid_amount >= 0 AND
 paid_amount <= total_amount AND
 unpaid_amount <= total_amount
 );

CREATE OR REPLACE VIEW v_error_rate_monitor AS
SELECT 
 DATE_TRUNC('day', changed_at) as check_date,
 table_name,
 COUNT(*) as total_operations,
 SUM(CASE WHEN validation_passed = FALSE THEN 1 ELSE 0 END) as failed_operations,
 ROUND(
 SUM(CASE WHEN validation_passed = FALSE THEN 1 ELSE 0 END)::NUMERIC / 
 NULLIF(COUNT(*), 0) * 10000, 2
 ) as error_rate_per_10k,
 CASE 
 WHEN SUM(CASE WHEN validation_passed = FALSE THEN 1 ELSE 0 END)::NUMERIC / 
 NULLIF(COUNT(*), 0) * 10000 <= 1 THEN '✓ 达标 (≤1/万)'
 ELSE '✗ 超标 (>1/万)'
 END as target_status
FROM data_audit_logs
WHERE changed_at >= NOW() - INTERVAL '30 days'
GROUP BY DATE_TRUNC('day', changed_at), table_name
ORDER BY check_date DESC, table_name;

