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


-- payments 表 RLS 策略
-- 付款方或收款方可以查看相关结款记录
CREATE POLICY users_select_payments ON public.payments
FOR SELECT USING (
 from_company_id = public.get_user_master_company_id()
 OR to_company_id = public.get_user_master_company_id()
);

CREATE POLICY users_insert_payments ON public.payments
FOR INSERT WITH CHECK (
 from_company_id = public.get_user_master_company_id()
 OR to_company_id = public.get_user_master_company_id()
);

CREATE POLICY users_update_payments ON public.payments
FOR UPDATE USING (
 from_company_id = public.get_user_master_company_id()
 OR to_company_id = public.get_user_master_company_id()
);

-- plan_process_steps 表 RLS 策略
-- 关联计划的采购商或工厂可以查看流程步骤
CREATE POLICY users_select_process_steps ON public.plan_process_steps
FOR SELECT USING (
 EXISTS (
 SELECT 1 FROM public.production_plans p
 JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = plan_id 
 AND (p.purchaser_id = public.get_user_master_company_id() 
 OR pf.factory_id = public.get_user_master_company_id())
 )
);

CREATE POLICY users_insert_process_steps ON public.plan_process_steps
FOR INSERT WITH CHECK (
 EXISTS (
 SELECT 1 FROM public.production_plans p
 JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = plan_id 
 AND (p.purchaser_id = public.get_user_master_company_id() 
 OR pf.factory_id = public.get_user_master_company_id())
 )
);

CREATE POLICY users_update_process_steps ON public.plan_process_steps
FOR UPDATE USING (
 EXISTS (
 SELECT 1 FROM public.production_plans p
 JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = plan_id 
 AND (p.purchaser_id = public.get_user_master_company_id() 
 OR pf.factory_id = public.get_user_master_company_id())
 )
);

-- company_members 表 RLS 策略
CREATE POLICY users_select_company_members ON public.company_members
FOR SELECT USING (
 company_id = public.get_user_master_company_id()
);

CREATE POLICY users_insert_company_members ON public.company_members
FOR INSERT WITH CHECK (
 company_id = public.get_user_master_company_id()
);

CREATE POLICY users_delete_company_members ON public.company_members
FOR DELETE USING (
 company_id = public.get_user_master_company_id()
);

