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


-- 创建辅助函数：获取用户主账号公司ID（用于子账号）
CREATE OR REPLACE FUNCTION public.get_user_master_company_id()
RETURNS UUID
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
 user_company_id UUID;
 user_master_id UUID;
BEGIN
 SELECT company_id, master_id INTO user_company_id, user_master_id
 FROM public.profiles
 WHERE id = auth.uid();
 
 -- 如果是子账号，返回主账号的公司ID
 IF user_master_id IS NOT NULL THEN
 SELECT company_id INTO user_company_id
 FROM public.profiles
 WHERE id = user_master_id;
 END IF;
 
 RETURN user_company_id;
END;
$$;

