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


-- 修复 plan_process_steps 的 RLS 策略
-- 删除旧的策略
DROP POLICY IF EXISTS users_select_process_steps ON public.plan_process_steps;
DROP POLICY IF EXISTS users_insert_process_steps ON public.plan_process_steps;
DROP POLICY IF EXISTS users_update_process_steps ON public.plan_process_steps;
DROP POLICY IF EXISTS users_delete_process_steps ON public.plan_process_steps;

-- 创建新的策略：允许查看（用于流程跟踪）
CREATE POLICY users_select_process_steps ON public.plan_process_steps
FOR SELECT USING (true);

-- 插入：允许关联计划的采购商或工厂
CREATE POLICY users_insert_process_steps ON public.plan_process_steps
FOR INSERT WITH CHECK (
 EXISTS (
 SELECT 1 FROM public.production_plans p
 LEFT JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = plan_process_steps.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
 LEFT JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = plan_process_steps.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_delete_process_steps ON public.plan_process_steps
FOR DELETE USING (
 EXISTS (
 SELECT 1 FROM public.production_plans
 WHERE id = plan_process_steps.plan_id 
 AND purchaser_id = public.get_user_master_company_id()
 )
);

