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

declare
        v_journal_id    integer;
        trans_rec       record;
begin
        for trans_rec in select t.task_id, t.case_id, tr.transition_name
            from   wf_tasks t, wf_transitions tr
            where  trigger_time <= now()
            and    state = 'enabled'
            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 fired */

            v_journal_id := journal_entry__new (
                null,
                trans_rec.case_id, 
                'task ' || trans_rec.task_id || ' fire time',
                trans_rec.transition_name || ' automatically finished',
                now(),
                null,
                null,
                'Timed transition fired.'
            );
        
            /* Fire the transition */

            PERFORM workflow_case__fire_transition_internal (
                trans_rec.task_id,
                v_journal_id
            );

            /* Update the workflow internal state */

            PERFORM workflow_case__sweep_automatic_transitions(
                trans_rec.case_id,
                v_journal_id
            );

        end loop;

        return 0;
end;$$ language plpgsql;