-- Allow client revision returns to clear stale assignments while keeping -- assignment fields protected for normal client updates. create or replace function public.guard_task_update() returns trigger as $$ declare caller_role text; begin select role into caller_role from public.profiles where id = auth.uid(); if caller_role = 'client' then new.project_id := old.project_id; new.invoiced := old.invoiced; if not ( new.status = 'not_started' and coalesce(new.current_version, 0) > coalesce(old.current_version, 0) and new.assigned_to is null and new.assigned_name is null ) then new.assigned_to := old.assigned_to; new.assigned_name := old.assigned_name; end if; elsif caller_role = 'external' then new.project_id := old.project_id; new.invoiced := old.invoiced; end if; return new; end; $$ language plpgsql security definer;