-- 迁移：DWS 层 ratio/margin/multiplier 字段精度扩展
-- 原因：numeric(5,4) 只能存 ±0.9999，当比率 ≥ 1 或 < -1 时溢出（P1 已爆 gross_margin）
-- 日期：2026-03-01
-- 注意：需先 DROP 依赖视图，ALTER 后重建

BEGIN;

-- 1. DROP 依赖视图（app schema 的 RLS 视图）
DROP VIEW IF EXISTS app.v_cfg_performance_tier CASCADE;
DROP VIEW IF EXISTS app.v_dws_assistant_finance_analysis CASCADE;
DROP VIEW IF EXISTS app.v_dws_assistant_recharge_commission CASCADE;
DROP VIEW IF EXISTS app.v_dws_assistant_salary_calc CASCADE;
DROP VIEW IF EXISTS app.v_dws_finance_discount_detail CASCADE;
DROP VIEW IF EXISTS app.v_dws_finance_income_structure CASCADE;
DROP VIEW IF EXISTS app.v_dws_member_assistant_intimacy CASCADE;

-- 2. ALTER 列类型：numeric(5,4)/numeric(6,4) → numeric(7,4)
ALTER TABLE dws.cfg_performance_tier
    ALTER COLUMN bonus_deduction_ratio TYPE numeric(7,4);
ALTER TABLE dws.dws_assistant_finance_analysis
    ALTER COLUMN gross_margin TYPE numeric(7,4);
ALTER TABLE dws.dws_assistant_recharge_commission
    ALTER COLUMN commission_ratio TYPE numeric(7,4);
ALTER TABLE dws.dws_assistant_salary_calc
    ALTER COLUMN bonus_deduction_ratio TYPE numeric(7,4);
ALTER TABLE dws.dws_finance_discount_detail
    ALTER COLUMN discount_ratio TYPE numeric(7,4);
ALTER TABLE dws.dws_finance_income_structure
    ALTER COLUMN income_ratio TYPE numeric(7,4);
ALTER TABLE dws.dws_member_assistant_intimacy
    ALTER COLUMN burst_multiplier TYPE numeric(7,4);

-- 3. 重建视图（使用 pg_get_viewdef 保存的原始定义）
-- 注意：实际执行时应从 _p1_migrate_with_views.py 自动保存/重建
-- 以下为手动重建模板，视图定义为 SELECT * FROM dws.xxx WHERE site_id = ...
CREATE OR REPLACE VIEW app.v_cfg_performance_tier AS
    SELECT * FROM dws.cfg_performance_tier
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_assistant_finance_analysis AS
    SELECT * FROM dws.dws_assistant_finance_analysis
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_assistant_recharge_commission AS
    SELECT * FROM dws.dws_assistant_recharge_commission
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_assistant_salary_calc AS
    SELECT * FROM dws.dws_assistant_salary_calc
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_finance_discount_detail AS
    SELECT * FROM dws.dws_finance_discount_detail
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_finance_income_structure AS
    SELECT * FROM dws.dws_finance_income_structure
    WHERE site_id = current_setting('app.current_site_id')::bigint;
CREATE OR REPLACE VIEW app.v_dws_member_assistant_intimacy AS
    SELECT * FROM dws.dws_member_assistant_intimacy
    WHERE site_id = current_setting('app.current_site_id')::bigint;

COMMIT;
