--
-- workflow_case__sweep_hold_timeout/0
--
create or replace function workflow_case__sweep_hold_timeout(
  
) returns int4 as $$

declare
        v_journal_id    integer;
        task_rec        record;
begin
        for task_rec in select t.task_id, t.case_id, tr.transition_name
            from   wf_tasks t, wf_transitions tr
            where  hold_timeout <= now()
            and    state = 'started'
            and    tr.workflow_key = t.workflow_key
            and    tr.transition_key = t.transition_key
        LOOP
 
            /* Insert an entry to the journal so people will know it was canceled */

            v_journal_id := journal_entry__new (
                null,
                task_rec.case_id, 
                'task ' || task_rec.task_id || ' cancel timeout',
                task_rec.transition_name || ' timed out', 
                now(),
                null,
                null,
                'The user''s hold on the task timed out and the task was automatically canceled'
            );


            /* Cancel the task */

            PERFORM workflow_case__cancel_task (
                task_rec.task_id,
                v_journal_id
            );

        end loop;

        return 0;
end;$$ language plpgsql;