```sql -- Enable Row Level Security on all tables ALTER TABLE organizations ENABLE ROW LEVEL SECURITY; ALTER TABLE user_profiles ENABLE ROW LEVEL SECURITY; ALTER TABLE departments ENABLE ROW LEVEL SECURITY; ALTER TABLE crm_leads ENABLE ROW LEVEL SECURITY; ALTER TABLE hr_employees ENABLE ROW LEVEL SECURITY; ALTER TABLE hr_attendance ENABLE ROW LEVEL SECURITY; ALTER TABLE hr_leaves ENABLE ROW LEVEL SECURITY; ALTER TABLE finance_invoices ENABLE ROW LEVEL SECURITY; ALTER TABLE inventory_products ENABLE ROW LEVEL SECURITY; ALTER TABLE inventory_stock_movements ENABLE ROW LEVEL SECURITY; ALTER TABLE workflows ENABLE ROW LEVEL SECURITY; ALTER TABLE audit_logs ENABLE ROW LEVEL SECURITY; -- Superadmin can access everything CREATE POLICY superadmin_all_access ON ALL TABLES TO authenticated USING (auth.uid() IN (SELECT id FROM user_profiles WHERE role = 'superadmin')); -- Organization admin can access their org's data CREATE POLICY org_admin_access ON organizations TO authenticated USING (id IN (SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND role = 'org_admin')); CREATE POLICY org_admin_user_profiles ON user_profiles TO authenticated USING (organization_id IN (SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND role = 'org_admin')); -- Department-based access for HR managers CREATE POLICY hr_manager_employee_access ON hr_employees TO authenticated USING ( organization_id IN ( SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND (role = 'hr_manager' OR role = 'org_admin') AND organization_id = hr_employees.organization_id ) ); -- CRM lead access policies CREATE POLICY crm_lead_manager_access ON crm_leads TO authenticated USING ( organization_id IN ( SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND (role IN ('crm_lead_manager', 'org_admin')) AND organization_id = crm_leads.organization_id ) ); -- Finance manager access CREATE POLICY finance_manager_access ON finance_invoices TO authenticated USING ( organization_id IN ( SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND (role IN ('finance_manager', 'org_admin')) AND organization_id = finance_invoices.organization_id ) ); -- Inventory manager access CREATE POLICY inventory_manager_access ON inventory_products TO authenticated USING ( organization_id IN ( SELECT organization_id FROM user_profiles WHERE id = auth.uid() AND (role IN ('inventory_manager', 'org_admin')) AND organization_id = inventory_products.organization_id ) ); -- Regular employees can view their own records CREATE POLICY employee_self_access ON user_profiles TO authenticated USING (id = auth.uid()); CREATE POLICY employee_own_attendance ON hr_attendance TO authenticated USING ( employee_id IN ( SELECT id FROM hr_employees WHERE user_id = auth.uid() ) ); ```