--
-- workflow_case__cancel/4
--
create or replace function workflow_case__cancel(
  integer,
  integer,
  character varying,
  character varying
) returns int4 as $$

declare
  cancel__case_id                alias for $1;  
  cancel__user_id                alias for $2;  -- default null  
  cancel__ip_address             alias for $3;  -- default null
  cancel__msg                    alias for $4;  -- default null
  v_state                        varchar;   
  v_journal_id                   integer;        
begin
        select state into v_state
        from   wf_cases
        where  case_id = cancel__case_id;

        if v_state != 'active' and v_state != 'suspended' then
            raise EXCEPTION '-20000: Only active or suspended cases can be canceled';
        end if;

        /* Add an entry to the journal */
        v_journal_id := journal_entry__new(
            null,
            cancel__case_id,
            'case cancel',
            'Case canceled',
            now(),
            cancel__user_id,
            cancel__ip_address,
            cancel__msg
        );

        update wf_cases
        set    state = 'canceled'
        where  case_id = cancel__case_id;

        return 0; 
end;$$ language plpgsql;