return: date
lang: plpgsql
parameters:
  p0:
    type: text
    name: i_code
  p1:
    type: text
    name: i_option
src: |
  DECLARE	
  	_code text;
  	_option text;
  	_now date;
  BEGIN
  	_code = i_code;
  	IF _code NOT IN ('NOW', 'NOWCLOTURE') THEN
  		_code = 'NOW';
  	END IF;
  	_option = i_option;
  	IF NOT EXISTS (SELECT * FROM eco.t_divers WHERE code = _code) THEN
  		_option = 'FORCE';
  	END IF; 
  	IF _option = 'FORCE' THEN
  		_now =
  		CASE _code
  		WHEN 'NOW' THEN
  			(SELECT MAX(date) FROM eco.p_mouvements_articles WHERE date <= date(now()) )
  		WHEN 'NOWCLOTURE' THEN
  			(SELECT date(date_trunc('month',MAX(date_commande)) - interval '1 day') FROM eco.p_commandes WHERE date_commande <= date(now()))
  		ELSE date(now())
  		END;
  		UPDATE eco.t_divers SET
  			texte = CASE _code 
  				WHEN 'NOW' THEN 'Date dernier mouvement'
  				WHEN 'NOWCLOTURE' THEN 'Date clôture'
  				ELSE 'Date dernier mouvement'
  				END,
  			valeur = _now::text,
  			valeur_date = _now,
  			show_info_module = true
  		WHERE code = _code;
  		INSERT INTO eco.t_divers (code, texte, valeur, valeur_date, description, show_info_module)
  		SELECT
  			_code,
  			CASE _code 
  			WHEN 'NOW' THEN 'Date dernier mouvement'
  			WHEN 'NOWCLOTURE' THEN 'Date clôture'
  			ELSE 'Date dernier mouvement'
  			END,
  			_now::text,
  			_now,	
  			'Date non modifiable',
  			true
  		WHERE _code NOT IN (SELECT code FROM eco.t_divers);
  	ELSE
  		_now = (SELECT valeur_date FROM eco.t_divers WHERE code = _code);
  	END IF;
  	
  	RETURN _now;
  END;