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


-- 修复高风险表的 SELECT 策略

-- 1. production_plans: 只允许采购商查看自己的计划，工厂查看关联的计划
DROP POLICY IF EXISTS users_select_plans ON public.production_plans;

CREATE POLICY users_select_plans ON public.production_plans
FOR SELECT USING (
 -- 采购商可以查看自己的计划
 purchaser_id = public.get_user_master_company_id()
 OR
 -- 工厂可以查看关联的计划
 EXISTS (
 SELECT 1 FROM public.plan_factories
 WHERE plan_id = production_plans.id
 AND factory_id = public.get_user_master_company_id()
 )
);

-- 2. products: 只允许公司自己查看（产品管理）
DROP POLICY IF EXISTS users_select_products ON public.products;

CREATE POLICY users_select_products ON public.products
FOR SELECT USING (
 company_id = public.get_user_master_company_id()
);

-- 3. inventory_records: 只允许相关方查看
DROP POLICY IF EXISTS users_select_inventory ON public.inventory_records;

CREATE POLICY users_select_inventory ON public.inventory_records
FOR SELECT USING (
 -- 公司可以查看自己的入库记录
 company_id = public.get_user_master_company_id()
 OR
 -- 采购商可以查看关联计划的入库记录
 EXISTS (
 SELECT 1 FROM public.production_plans p
 JOIN public.plan_factories pf ON p.id = pf.plan_id
 WHERE p.id = inventory_records.plan_id
 AND (p.purchaser_id = public.get_user_master_company_id()
 OR pf.factory_id = public.get_user_master_company_id())
 )
);

