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


-- 修复 production_plans SELECT 策略：移除过于宽松的条件3，改为允许通过 share_links 查看计划
DROP POLICY IF EXISTS users_select_plans ON production_plans;

CREATE POLICY users_select_plans ON production_plans
 FOR SELECT
 USING (
 -- 采购商可以查看自己的计划
 purchaser_id = get_user_master_company_id()
 OR
 -- 工厂可以查看已关联的计划
 EXISTS (
 SELECT 1 FROM plan_factories
 WHERE plan_factories.plan_id = production_plans.id
 AND plan_factories.factory_id = get_user_master_company_id()
 )
 OR
 -- 通过有效分享链接可以查看计划（导入页面使用）
 EXISTS (
 SELECT 1 FROM share_links
 WHERE share_links.plan_id = production_plans.id
 AND share_links.factory_type = 'textile'
 AND (share_links.used_at IS NULL OR share_links.used_at > NOW() - INTERVAL '1 hour')
 AND share_links.expires_at > NOW()
 )
 );

