CREATE SCHEMA timewarp;


CREATE OR REPLACE FUNCTION timewarp.trialbaltrigger() RETURNS trigger 
AS $BODY$
DECLARE
     v_tmp_id INT;
BEGIN
    
    SELECT period_id INTO v_tmp_id  FROM timewarp.period LIMIT 1;
    IF NOT FOUND THEN
        RETURN NEW;
    END IF;
    
    -- if there is no change in the trailbalance values, do not update the
    IF (
        (TG_OP = 'UPDATE')
        AND
        (OLD IS NOT NULL)
        AND
        (OLD.trialbal_beginning = NEW.trialbal_beginning)
        AND
        (OLD.trialbal_ending = NEW.trialbal_ending)
        AND
        (OLD.trialbal_credits = NEW.trialbal_credits)
        AND
        (OLD.trialbal_debits = NEW.trialbal_debits)
    ) THEN
        RETURN NEW;
    END IF;
        
    
    PERFORM timewarp.trialbal_fill(NEW.trialbal_id);
      
    RETURN NEW;   
        
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
ALTER FUNCTION  timewarp.trialbaltrigger()
  OWNER TO admin;

GRANT ALL ON FUNCTION timewarp.trialbaltrigger() TO xtrole;

CREATE TRIGGER _trialbaltrigger 
    AFTER INSERT OR UPDATE ON public.trialbal
        FOR EACH ROW EXECUTE PROCEDURE timewarp.trialbaltrigger();


-------- yearperiod----------------




CREATE OR REPLACE FUNCTION timewarp.yearperiodtrigger() RETURNS trigger 
AS $BODY$
DECLARE
     v_tmp_id INT;
BEGIN
    
      SELECT period_id INTO v_tmp_id  FROM timewarp.period LIMIT 1;
    IF NOT FOUND THEN
        RETURN NEW;
    END IF;
    
    
    PERFORM timewarp.yearperiod_fill(NEW.yearperiod_id);
      
    RETURN NEW;   
        
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
ALTER FUNCTION  timewarp.yearperiodtrigger()
  OWNER TO admin;


GRANT ALL ON FUNCTION timewarp.yearperiodtrigger() TO xtrole;

CREATE TRIGGER _yearperiodtrigger 
    AFTER INSERT OR UPDATE ON public.yearperiod
        FOR EACH ROW EXECUTE PROCEDURE timewarp.yearperiodtrigger();
        

---------------------- period--------------------------------------



CREATE OR REPLACE FUNCTION timewarp.periodtrigger() RETURNS trigger 
AS $BODY$
DECLARE
     v_tmp_id INT;
BEGIN
     SELECT period_id INTO v_tmp_id FROM timewarp.period LIMIT 1;
    IF NOT FOUND THEN
        RETURN NEW;
    END IF;
    
    PERFORM timewarp.period_fill(NEW.period_id);
      
    RETURN NEW;   
        
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
ALTER FUNCTION  timewarp.periodtrigger()
  OWNER TO admin;
GRANT ALL ON FUNCTION timewarp.periodtrigger() TO xtrole;

CREATE TRIGGER _periodtrigger 
    AFTER INSERT OR UPDATE ON public.period
        FOR EACH ROW EXECUTE PROCEDURE timewarp.periodtrigger();