
-- renforce intégrité des détails
delete from detailbien_t where ndetail not in (select ndetail from detail) ;


DROP VIEW IF EXISTS w_am6_detail CASCADE;

CREATE OR REPLACE FUNCTION public.f_set_nnummandat()
  RETURNS trigger AS
$BODY$
  DECLARE
    ll_nnummandat integer ;
 BEGIN

   SELECT INTO ll_nnummandat max(mandat.nnummandat) FROM mandat WHERE mandat.cagence = (select cagencemandat from agence where agence.cagence = new.cagence) ;

   IF ll_nnummandat IS NULL THEN
      --SELECT max(nnummandat) INTO ll_nnummandat FROM mandat WHERE cagence = (select cagencemandat from agence where agence = new.cagence) ;
      select INTO ll_nnummandat nnummandatdebut
      from agence
      where agence.cagence = (select agence.cagencemandat from agence where agence.cagence = new.cagence);

        IF ll_nnummandat IS NULL THEN
		--raise exception error
		RAISE EXCEPTION  'Le nouveau numéro de mandat ne peut être déterminé. Veuillez vérifier les paramètres de numérotaiton du registre des mandats'   ;

        ELSE
		NEW.nnummandat = ll_nnummandat + 1;
	END IF ;

   ELSE
       NEW.nnummandat = ll_nnummandat + 1;
   END IF ;

  RETURN NEW;

END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.f_set_nnummandat()
  OWNER TO admin;


  CREATE OR REPLACE FUNCTION public.f_update_bien_mandat()
  RETURNS trigger AS
$BODY$
DECLARE
 --cpays   character varying(3);
BEGIN
        IF (NEW.nbien IS NOT NULL AND NEW.nbien > 0) THEN

		 UPDATE bien SET (cmandat , dmandat, dexpmandat, nnatmandat) =
		 (select nmandat::varchar , ddebmandat , dfinmandat , nnatmandat
		 from mandat
		 where mandat.nbien = NEW.nbien order by ddebmandat DESC limit 1);

        END IF ;

        RETURN NEW;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.f_update_bien_mandat()
  OWNER TO admin;




CREATE OR REPLACE FUNCTION add_column_if_not_exists(
    p_table_name text, 
    p_column_name text, 
    p_column_type text, 
    p_is_not_null boolean DEFAULT false, 
    p_default_value text DEFAULT NULL
)
RETURNS void AS $$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_name = p_table_name 
        AND column_name = p_column_name
    ) THEN
        EXECUTE format(
            'ALTER TABLE %I ADD COLUMN %I %s%s%s', 
            p_table_name, 
            p_column_name, 
            p_column_type,
            CASE WHEN p_is_not_null THEN ' NOT NULL' ELSE '' END,
            CASE WHEN p_default_value IS NOT NULL THEN ' DEFAULT ' || p_default_value ELSE '' END
        );
    END IF;
END;
$$ LANGUAGE plpgsql;

DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'mandat') THEN
        -- Vérifier que 'mandat_t' n'existe pas déjà
        IF NOT EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'mandat_t') THEN
            EXECUTE 'ALTER TABLE mandat RENAME TO mandat_t';
        END IF;
    END IF;
END
$$;


-- Create sequence if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'mandat_nmandat_seq') THEN
    CREATE SEQUENCE mandat_nmandat_seq;
  END IF;
END $do$;



DO $do$ 
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace 
                   WHERE c.relkind = 'S' AND c.relname = 'mandat_nmandat_seq') THEN
        CREATE SEQUENCE mandat_nmandat_seq;
    END IF;
END $do$;






-- Create table if it does not exist
CREATE TABLE IF NOT EXISTS public.mandat_t (
  nmandat INTEGER DEFAULT nextval('mandat_nmandat_seq'::regclass) NOT NULL,
  nbien INTEGER,
  ddebmandat TIMESTAMP WITH TIME ZONE,
  dfinmandat TIMESTAMP WITH TIME ZONE,
  ltypmandat VARCHAR(100),
  lnatmandat VARCHAR(100),
  cstatutmandat VARCHAR(1) DEFAULT 'r'::character varying,
  ltypxx VARCHAR(50),
  ladrbien VARCHAR(200),
  lcpbien VARCHAR(20),
  llocalitebien VARCHAR(100),
  cagence VARCHAR(10),
  lusername VARCHAR(250),
  lstatutmandat VARCHAR(250),
  lmandants TEXT,
  cisopaysbien VARCHAR(3),
  nnummandat INTEGER NOT NULL,
  ltypbien VARCHAR(100),
  nnumrepertoire INTEGER,
  dcre TIMESTAMP WITH TIME ZONE DEFAULT now(),
  cusercre VARCHAR(10) DEFAULT current_user,
  cusermod VARCHAR(10) DEFAULT current_user,
  dmod TIMESTAMP WITH TIME ZONE DEFAULT now(),
  lobservations TEXT,
  CONSTRAINT pk_mandat_nmandat PRIMARY KEY(nmandat),
  CONSTRAINT unique_index_mandat UNIQUE(nnummandat, cagence)
);

-- Create index if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'fki_mandat_cagence' AND relkind = 'i') THEN
    CREATE INDEX fki_mandat_cagence ON public.mandat_t
    USING btree (cagence COLLATE pg_catalog."default");
  END IF;
END $do$;

-- Create trigger if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_trigger
    WHERE tgname = 'tbi_mandat_nnumandat'
  ) THEN
    CREATE TRIGGER tbi_mandat_nnumandat
    BEFORE INSERT 
    ON public.mandat_t
    FOR EACH ROW 
    EXECUTE PROCEDURE public.f_set_nnummandat();
  END IF;
END $do$;


-- Replace or create the `tbiud_mandat_denorm` trigger
DO $do$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM pg_trigger
    WHERE tgname = 'tbiud_mandat_denorm'
  ) THEN
    DROP TRIGGER tbiud_mandat_denorm ON public.mandat_t;
  END IF;

  CREATE TRIGGER tbiud_mandat_denorm
  BEFORE INSERT OR UPDATE OR DELETE 
  ON public.mandat_t
  FOR EACH ROW 
  EXECUTE PROCEDURE public.f_update_bien_mandat();
END $do$;

-- Replace or create the `tbui_mandat_audit` trigger
DO $do$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM pg_trigger
    WHERE tgname = 'tbui_mandat_audit'
  ) THEN
    DROP TRIGGER tbui_mandat_audit ON public.mandat_t;
  END IF;

  CREATE TRIGGER tbui_mandat_audit
  BEFORE INSERT OR UPDATE 
  ON public.mandat_t
  FOR EACH ROW 
  EXECUTE PROCEDURE public.f_set_audit();
END $do$;

-- Set table owner if it is not already set
DO $do$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM pg_tables
    WHERE schemaname = 'public'
      AND tablename = 'mandat_t'
  ) THEN
    ALTER TABLE public.mandat_t OWNER TO admin;
  END IF;
END $do$;



-- Create sequence if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'mandat_observation_nobservation_seq') THEN
    CREATE SEQUENCE mandat_observation_nobservation_seq;
  END IF;
END $do$;

-- Create table if it does not exist
CREATE TABLE IF NOT EXISTS public.mandat_observation_t (
  nobservation INTEGER DEFAULT nextval('mandat_observation_nobservation_seq'::regclass) NOT NULL,
  lobservation TEXT NOT NULL,
  nmandat INTEGER NOT NULL,
  lusername VARCHAR(10),
  dobservation TIMESTAMP WITHOUT TIME ZONE,
  dcre TIMESTAMP WITHOUT TIME ZONE,
  cusercre VARCHAR(50),
  cusermod VARCHAR(50),
  dmod TIMESTAMP WITHOUT TIME ZONE,
  CONSTRAINT pk_nobservation PRIMARY KEY(nobservation)
);

-- Create index if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'fki_mandat_observation_nmandat' AND relkind = 'i') THEN
    CREATE INDEX fki_mandat_observation_nmandat ON public.mandat_observation_t
    USING btree (nmandat);
  END IF;
END $do$;

-- Create trigger if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_trigger
    WHERE tgname = 'tbui_mandat_observation_audit'
  ) THEN
    CREATE TRIGGER tbui_mandat_observation_audit
    BEFORE INSERT OR UPDATE 
    ON public.mandat_observation_t
    FOR EACH ROW 
    EXECUTE PROCEDURE public.f_set_audit();
  END IF;
END $do$;

-- Set table owner if it is not already set
DO $do$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM pg_tables
    WHERE schemaname = 'public'
      AND tablename = 'mandat_observation_t'
  ) THEN
    ALTER TABLE public.mandat_observation_t OWNER TO admin;
  END IF;
END $do$;




-- Create table if it does not exist
CREATE TABLE IF NOT EXISTS public.mandat_mandant (
  nmandant SERIAL,
  lmandant TEXT NOT NULL,
  ladr TEXT NOT NULL,
  nmandat INTEGER NOT NULL,
  cusercre VARCHAR(50),
  cusermod VARCHAR(50),
  dcre TIMESTAMP WITHOUT TIME ZONE,
  dmod TIMESTAMP WITHOUT TIME ZONE,
  CONSTRAINT pk_mandat_mandants PRIMARY KEY(nmandant)
);

-- Create trigger if it does not exist
DO $do$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_trigger
    WHERE tgname = 'tbui_mandat_mandant_audit'
  ) THEN
    CREATE TRIGGER tbui_mandat_mandant_audit
    BEFORE INSERT OR UPDATE 
    ON public.mandat_mandant
    FOR EACH ROW 
    EXECUTE PROCEDURE public.f_set_audit();
  END IF;
END $do$;

-- Set table owner if it is not already set
DO $do$
BEGIN
  IF EXISTS (
    SELECT 1
    FROM pg_tables
    WHERE schemaname = 'public'
      AND tablename = 'mandat_mandant'
  ) THEN
    ALTER TABLE public.mandat_mandant OWNER TO admin;
  END IF;
END $do$;





CREATE TABLE IF NOT EXISTS params (
    id integer NOT NULL DEFAULT 0,
    lftpserver character varying(50),
    lftpusername character varying(50),
    lftppasswd character varying(50),
    lftpsubdir character varying(255),
    bftppassive integer DEFAULT 1,
    bftpssl integer DEFAULT 0,
    nftpport integer default 21,
    bftpssh integer DEFAULT 0,
    nprospectnotaire integer,
    nprospectprio integer,
    nprospectagence integer,
    nprospectprospect integer,
    ntyprelationssp integer,
    ntyprelationacte integer,
    ntyprelationactivite integer,
    lintraneturl character varying(250),
    nprospectlead integer,
    ntyprelationemail integer,
    ntyprelationvisite integer,
    ntyprelationrelance   integer,
    ndetailtodoreminder integer,
    dcre timestamp without time zone DEFAULT ('now'::text)::date,
    cusercre character varying(50) DEFAULT 'current_user'::text,
    cusermod character varying(50) DEFAULT 'current_user'::text,
    dmod timestamp without time zone DEFAULT now()
) ;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    --PERFORM add_column_if_not_exists('cat', 'bisaprospect', 'integer' );
PERFORM  add_column_if_not_exists('agence', 'bstandardwebsite', 'integer DEFAULT 1');

--//busepg2mysql4web on portailagence
PERFORM  add_column_if_not_exists('portailagence', 'busepg2mysql4web', 'integer DEFAULT 0');


PERFORM  add_column_if_not_exists('offre_t', 'mcommissionvendeur', 'integer');
PERFORM  add_column_if_not_exists('portailagence', 'cspecialtypformat', 'character varying(100)');
PERFORM  add_column_if_not_exists('detail', 'breport', 'integer');

PERFORM  add_column_if_not_exists('agence', 'bdisporeminder', 'integer DEFAULT 0');
PERFORM  add_column_if_not_exists('agence', 'btodoreminder', 'integer DEFAULT 0');
PERFORM  add_column_if_not_exists('agence', 'cagencemandat', 'character varying(10)');
PERFORM  add_column_if_not_exists('bien_t', 'lsearchfr', 'text');
PERFORM  add_column_if_not_exists('biencrit_t', 'bqsurfjardin', 'int DEFAULT 1');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion16', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion17', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion18', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion19', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion20', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion21', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion22', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion23', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion24', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'cregion25', 'character varying(8)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ldetailsen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ldetailsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ldetailssen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ldetailssfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lenvironnementsen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lenvironnementsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lenvironnementsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lprogrammesen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lprogrammesfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lprogrammesfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregionmetas', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregionmetasen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregionmetasfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregions', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregionsen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lregionsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lsearchen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lsearchfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lstylesen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lstylesfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'lstylesfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmandats', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmandatsen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmandatsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmetas', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmetasen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypmetasfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypsen', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'ltypsfr', 'character varying(1000)');
PERFORM  add_column_if_not_exists('biencrit_t', 'qsurfjardinmax', 'int');
PERFORM  add_column_if_not_exists('offre_t', 'noffre', 'int');
PERFORM  add_column_if_not_exists('biencrit_t', 'qsurfjardinmin', 'int');
PERFORM  add_column_if_not_exists('biencrit_t', 'lusername', 'character varying(10)');

PERFORM  add_column_if_not_exists('deletebienlog', 'bien_cusercre', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'bien_cusermod', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'bien_dcre', 'TIMESTAMP WITHOUT TIME ZONE');
PERFORM  add_column_if_not_exists('deletebienlog', 'bien_dmod', 'TIMESTAMP WITHOUT TIME ZONE');
PERFORM  add_column_if_not_exists('deletebienlog', 'cbien', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'cisopays', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'ctyp', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'ladr', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'lcp', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'llocalite', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'lusername', 'VARCHAR');
PERFORM  add_column_if_not_exists('deletebienlog', 'mprix', 'INT');

PERFORM  add_column_if_not_exists('prospectbien_t', 'ninteret', 'INT DEFAULT 0');

PERFORM  add_column_if_not_exists('offre_t', 'cdevise', 'character varying(3)');

PERFORM  add_column_if_not_exists('deleteprospectlog', 'coperation', 'VARCHAR');

PERFORM  add_column_if_not_exists('typdetail', 'cicon', 'VARCHAR');
PERFORM  add_column_if_not_exists('typdetail', 'breport', 'INT');
PERFORM  add_column_if_not_exists('typdetail', 'ntypdetailmeta', 'INT');




PERFORM  add_column_if_not_exists('biencrit_t', 'nbiencrit', 'INTEGER');

PERFORM  add_column_if_not_exists('deleteprospectlog', 'cisopays', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'ladr', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lcp', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lemail', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lgsm', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'llocalite', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lnom', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lprenom', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'ltel', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'lusername', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'prospect_cusercre', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'prospect_cusermod', 'VARCHAR');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'prospect_dcre', 'TIMESTAMP WITHOUT TIME ZONE');
PERFORM  add_column_if_not_exists('deleteprospectlog', 'prospect_dmod', 'TIMESTAMP WITHOUT TIME ZONE');
PERFORM  add_column_if_not_exists('portailagence', 'lcustomname', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('preference_t', 'ntyprelationemail', 'integer');
PERFORM  add_column_if_not_exists('preference_t', 'ntyprelationvisite', 'integer');
PERFORM  add_column_if_not_exists('preference_t', 'ntyprelationvisite', 'integer');
PERFORM  add_column_if_not_exists('prospect_t', 'ballownews', 'integer',true , '0');
PERFORM  add_column_if_not_exists('prospect_t', 'ballowsms', 'integer',true , '0');
PERFORM  add_column_if_not_exists('prospect_t', 'lsearch', 'text');
PERFORM  add_column_if_not_exists('prospectbien_t', 'cavisclient', 'character varying(10)');
PERFORM  add_column_if_not_exists('prospectbien_t', 'cidannonceportail', 'character varying(255)');
PERFORM  add_column_if_not_exists('prospectbien_t', 'dlastpcidannonceurubannonceur', 'timestamp without time zone');
PERFORM  add_column_if_not_exists('prospectbien_t', 'dlastpubannonceur', 'timestamp without time zone');
PERFORM  add_column_if_not_exists('prospectbien_t', 'mmontant', 'integer');
PERFORM  add_column_if_not_exists('statutoffre', 'cstatutoffre', 'timestamp without time zone');
PERFORM  add_column_if_not_exists('statutoffre', 'ncouleur', 'INTEGER');
PERFORM  add_column_if_not_exists('statutoffre', 'ncouleurtexte', 'INTEGER');
PERFORM  add_column_if_not_exists('typrelation', 'brelance', 'int DEFAULT 1');
PERFORM  add_column_if_not_exists('typrelation', 'ndetailtrigger', 'integer');
PERFORM  add_column_if_not_exists('utilisateur', 'bautopubsiteweb', 'integer');
PERFORM  add_column_if_not_exists('utilisateur', 'bexportenabled', 'int DEFAULT 0');
PERFORM  add_column_if_not_exists('utilisateur', 'clangue', 'varchar(2) DEFAULT ''fr'' ');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionfr', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctioncs', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionde', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionen', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctiones', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionit', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionnl', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionru', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionsk', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'lfonctionzh', 'VARCHAR(50)');
PERFORM  add_column_if_not_exists('utilisateur', 'bstatreportenabled', 'INT DEFAULT 0');
PERFORM  add_column_if_not_exists('typrelation', 'brenseignement',  'int DEFAULT 0');
PERFORM  add_column_if_not_exists('prospectbien_t', 'bconfirmmailsent',  'int DEFAULT 0');
PERFORM  add_column_if_not_exists('prospectbien_t', 'blvisitemailsent',  'int DEFAULT 0');
PERFORM  add_column_if_not_exists('portailagence', 'bincvideos',  'int DEFAULT 1');
PERFORM  add_column_if_not_exists('statutbien', 'cbgcolor',  'VARCHAR(7) DEFAULT ''#FFAE1A''');
PERFORM  add_column_if_not_exists('agence', 'bstandardwebsite',  'int DEFAULT 1');
PERFORM  add_column_if_not_exists('doc_t', 'lonlyofficeid',  'VARCHAR(1000)');
PERFORM  add_column_if_not_exists('statutoffre', 'ccouleur',  'VARCHAR(7)');
PERFORM  add_column_if_not_exists('statutoffre', 'ccouleurtexte',  'VARCHAR(7)');
PERFORM  add_column_if_not_exists('prospect_t', 'ndetailsuivi',  'INT DEFAULT 0');
PERFORM  add_column_if_not_exists('prospect_t', 'bfollowup',  'INT DEFAULT 0');
PERFORM  add_column_if_not_exists('prospect_t', 'ndetailsuiviprec',  'INT DEFAULT 0');
PERFORM  add_column_if_not_exists('prospect_t', 'nrisklevel',  'INT DEFAULT 0');
PERFORM  add_column_if_not_exists('prospect_t', 'ddetailsuivi',  'TIMESTAMP WITHOUT TIME ZONE');
PERFORM  add_column_if_not_exists('prospect_t', 'cpassport',  'VARCHAR(50)');
PERFORM  add_column_if_not_exists('prospect_t', 'cisopaysnat',  'VARCHAR(3)');
PERFORM  add_column_if_not_exists('prospect_t', 'cid',  'VARCHAR(50)');
PERFORM  add_column_if_not_exists('agence', 'lyoutube',  'VARCHAR(255)');
PERFORM  add_column_if_not_exists('agence', 'lfacebook',  'VARCHAR(255)');
PERFORM  add_column_if_not_exists('agence', 'linstragram',  'VARCHAR(255)');
PERFORM  add_column_if_not_exists('agence', 'ltwitter',  'VARCHAR(255)');
PERFORM  add_column_if_not_exists('agence', 'limmosignkeyv1',  'VARCHAR(255)');
PERFORM  add_column_if_not_exists('agence', 'limmosignaccount',  'VARCHAR(255)');

PERFORM  add_column_if_not_exists('portailagence', 'nemailscenario',  'INT NOT NULL DEFAULT 0');
PERFORM  add_column_if_not_exists('portailagence', 'nphonescenario',  'INT NOT NULL DEFAULT 0');

PERFORM  add_column_if_not_exists('portailagence', 'ballowotheragencies',  'INT NOT NULL DEFAULT 0');

PERFORM  add_column_if_not_exists('agence', 'lemail4leads',  'VARCHAR(250) DEFAULT NULL');

PERFORM  add_column_if_not_exists('biencrit_t', 'lusername', 'VARCHAR(10)');

PERFORM  add_column_if_not_exists('typrelation', 'cclasse', 'VARCHAR(10)');

 
PERFORM add_column_if_not_exists('portailagence', 'busepg2mysql4web', 'INT NOT NULL DEFAULT 0');

PERFORM add_column_if_not_exists('typrelation', 'nordreoffre', 'smallint');

PERFORM add_column_if_not_exists('prospectbien_t', 'noffre', 'int');



PERFORM add_column_if_not_exists('prospect_t', 'ncategories', 'integer[]');
PERFORM add_column_if_not_exists('offre_t', 'noffre', 'integer');
PERFORM add_column_if_not_exists('offre_t', 'lsearchfr', 'text');
PERFORM add_column_if_not_exists('offre_t', 'lsearchen', 'text');

PERFORM add_column_if_not_exists('statutbien', 'cbgcolor', 'varchar(7)');




PERFORM add_column_if_not_exists('portailagence', 'busepg2mysql4web', 'INT NOT NULL DEFAULT 0');
	
PERFORM add_column_if_not_exists('typrelation', 'nordreoffre', 'smallint');

PERFORM add_column_if_not_exists('typrelation', 'nordreoffre', 'smallint');


PERFORM add_column_if_not_exists('utilisateur', 'lzeptomailkey', 'VARCHAR(2000)');

PERFORM add_column_if_not_exists('utilisateur', 'copenonstart', 'VARCHAR(100)');

PERFORM add_column_if_not_exists('htmlbien_t', 'lannonceseo', 'TEXT');


PERFORM add_column_if_not_exists('mandat_t', 'lstatutmandat', 'VARCHAR(255)');


PERFORM add_column_if_not_exists('mandat_t', 'lmandants', 'text');

PERFORM add_column_if_not_exists('mandat_t', 'cisopaysbien', 'VARCHAR(3)');

PERFORM add_column_if_not_exists('mandat_t', 'nnummandat', 'integer NOT NULL');

PERFORM add_column_if_not_exists('mandat_t', 'ltypbien', 'VARCHAR(100)');

PERFORM add_column_if_not_exists('mandat_t', 'nnumrepertoire', 'integer');

PERFORM add_column_if_not_exists('params', 'nbmoismandat', 'integer DEFAULT 12');

PERFORM add_column_if_not_exists('params', 'nbjoursagenda', 'integer DEFAULT 6');

PERFORM add_column_if_not_exists('params', 'nheuredebutagenda', 'integer DEFAULT 9');

PERFORM add_column_if_not_exists('params', 'nheurefinagenda', 'integer DEFAULT 20');

PERFORM add_column_if_not_exists('params', 'bregmandat', 'integer');

PERFORM add_column_if_not_exists('params', 'nnummandat', 'integer');

PERFORM add_column_if_not_exists('prospectbien_t', 'bconfirmmailsent', 'integer DEFAULT 0');

PERFORM add_column_if_not_exists('prospectbien_t', 'blvisitemailsent', 'integer DEFAULT 0');


    
END
$do$;


update bien_t set nprospectpropr = null where nprospectpropr not in (select nprospect from prospect_t);


CREATE OR REPLACE FUNCTION public.f_validateupdateprospect (
)
RETURNS trigger AS
$body$
    -- Trigger permettant de valider le droit pour modifier un prospect
    
    declare
	isentitled integer ;
	ll_nprospectprio integer ;
    begin
     /*-- Vérifier s'il s'agit d'un propriétaire : SELECT count(*) FROM bien WHERE nbienpropr = nprospect
    -- Selon qu'il est proprio ou non on vérifie l'état de bdeleteprospect ou de bdeleteproprio pour savoir si on peut continuer
    */

	IF OLD.lusername = current_user THEN
	-- accepte une modification par son auteur 
	     return NEW;
	ELSE

	  SELECT INTO ll_nprospectprio nprospectprio FROM preference_t WHERE cagence = (SELECT cagence FROM utilisateur WHERE lusername = current_user) ;

		IF OLD.ncategorie = ll_nprospectprio THEN
			SELECT INTO isentitled bupdateproprio FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

		  if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin' OR current_user = 'unsubscribe_usr' then
		    return NEW;
		  Else
		    RAISE EXCEPTION  'Droits insuffisants pour modifier un propriétaire (cagence:%)',  NEW.cagence   ;
		  End if;

		ELSE
			SELECT INTO isentitled bupdateprospect FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

		  if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin' OR current_user = 'unsubscribe_usr'  then
		    return NEW;
		  Else
		    RAISE EXCEPTION  'Droits insuffisants pour modifier un contact (cagence:%)',  NEW.cagence   ;
		  End if;



		END IF;
	END IF;

    end;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT

COST 100;





CREATE OR REPLACE FUNCTION public.f_tbi_statutoffre()
  RETURNS trigger AS
$BODY$
--DECLARE
--    myvar varchar(25);
BEGIN

IF (NEW.cstatut IS NULL) THEN
    NEW.cstatut := f_random_string (10) ;
END IF;
IF (NEW.dmod IS NULL) THEN
    NEW.dmod := current_timestamp ;
END IF;
IF (NEW.dcre IS NULL) THEN
    NEW.dcre := current_timestamp ;
END IF;

IF (NEW.cusercre IS NULL) THEN
    NEW.cusercre := current_user ;
END IF;

IF (NEW.cusermod IS NULL) THEN
    NEW.cusercre := current_user ;
END IF;

Return NEW ;
END;$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.f_tbi_statutoffre()
  OWNER TO postgres;


-- utiliser des sequences interne pour nphoto pluttot que tables seuqneces
-- utiliser des sequences interne pour nphoto pluttot que tables seuqneces
-- terreimmo
DROP VIEW IF EXISTS prospect CASCADE;
drop view IF EXISTS prospectbien cascade ;
drop view IF EXISTS bien cascade ;
drop view IF EXISTS preference cascade ;
drop view IF EXISTS htmlbien cascade ;
drop view IF EXISTS biencrit cascade ;
drop view IF EXISTS photo cascade ;
drop view IF EXISTS agenda cascade ;

-- agrandir 
ALTER TABLE public.bien_t ALTER COLUMN lcomment TYPE TEXT COLLATE pg_catalog."default";


--drop view IF EXISTS mandat cascade ;
--drop view IF EXISTS mandat_observation cascade ;
drop view IF EXISTS offre cascade ;
drop view IF EXISTS doc cascade ;






--ALTER TABLE prospect_t ADD COLUMN ballownews integer;
--ALTER TABLE prospect_t ADD COLUMN ballowsms integer;



--ALTER TABLE prospectbien_t ADD COLUMN cidannonceportail character varying(255);
--ALTER TABLE prospectbien_t ADD COLUMN mmontant integer;

DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM pg_class 
        WHERE relkind = 'S' 
        AND relname = 'nphoto'
    ) THEN
        EXECUTE 'CREATE SEQUENCE nphoto';
    END IF;
END $do$;


CREATE EXTENSION IF NOT EXISTS unaccent;

UPDATE photo_t
SET nphoto = nextval('nphoto')
WHERE nphoto IS NULL;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM setval(
        'public.nphoto',
        (SELECT COALESCE(MAX(nphoto), 0) + 100000 FROM photo_t),
        true
    );

END
$do$;

CREATE OR REPLACE FUNCTION f_set_nextval_photo_t()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.nphoto IS NULL) THEN NEW.nphoto = nextval ('nphoto'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

-- o.lemail pour utilisateur
CREATE OR REPLACE FUNCTION f_getrepo(
    IN clangue character varying,
    IN dfrom timestamp without time zone)
  RETURNS TABLE(l text, v character varying, t character varying, p text, o character varying, c integer) AS
$BODY$

    DECLARE
      clangue ALIAS FOR $1;
      ends_with ALIAS FOR $2;
      sql VARCHAR;
    BEGIN

    sql := 'SELECT ''etat'' as l ,
        etat.cetat as v,
        etat.letat' || clangue || ' as t,
        '''' as p ,
        letatfr as o,
        1 as c
       from etat where exists (select null from etat b where b.dmod >= ''2000-01-01'') group by 3,2,5
    UNION
        SELECT ''agence'' ,
        agence.cagence ,
        agence.lnomagence ,
        '''' as p ,
        agence.lnomagence,
        0 as c
        from agence
        where exists (select null from agence b where b.dmod >= ''2000-01-01'')
        group by 3,2,5
    UNION
     SELECT ''environnement'' ,
     environnement.cenvironnement as v,
     environnement.lenvironnement' || clangue || ' as t,
     '''' as p ,
     environnement.lenvironnement' || clangue || ' as o,
     1 as c
       from environnement where exists (select null from environnement b where b.dmod >= '''|| dfrom ||''') group by 3,2,5
    UNION
     SELECT ''langue'' ,  langue.clangue as v, langue.llangue' || clangue || ' as t,'''' as p ,llangue as o, bweb from langue
    UNION
     SELECT ''naturebien'' ,  naturebien.cnaturebien as v, naturebien.lnaturebien' || clangue || ' as t,'''' as p ,lnaturebien' || clangue || ' as o, 1 as c from naturebien group by 3,2,5
    UNION
     SELECT ''originebien'' ,  originebien.coriginebien as v, originebien.loriginebien' || clangue || ' as t,'''' as p ,originebien.loriginebien' || clangue || ' as o,  1 as c from originebien group by 3,2,5
    UNION
     SELECT ''origineprospect'' ,  origineprospect.corigineprospect as v, origineprospect.lorigineprospect' || clangue || ' as t,'''' as p ,origineprospect.lorigineprospect' || clangue || ' as o,  1 from origineprospect  group by 3,2,5
    UNION
     SELECT ''pays'' ,  pays.cisopays as v, pays.lpays' || clangue || ' as t,'''' as p ,pays.ciso2pays as o,  1 as c from pays group by 3,2,5
    UNION
     SELECT ''polit'' ,  polit.cpolit as v, polit.lpolit' || clangue || ' as t,'''' as p ,polit.lpolit' || clangue || ' as o,  1 as c from polit group by 3,2,5
    UNION
     SELECT ''regionmeta'' ,  regionmeta.cregionmeta as v, regionmeta.lregionmeta' || clangue || ' as t,null as p ,regionmeta.lregionmeta' || clangue || ' as o,  1 as c from regionmeta group by 3,2,5
    UNION
     SELECT ''statutoffre'' ,  statutoffre.cstatut as v, statutoffre.lstatut' || clangue || ' as t,'''' as p ,statutoffre.lstatut' || clangue || ' as o, nordre as c  from statutoffre LEFT JOIN offre ON statutoffre.cstatut = offre.cstatut group by 3,2,5
    UNION
     SELECT ''statutmandat'' ,  statutmandat.cstatut as v, statutmandat.lstatut' || clangue || ' as t,'''' as p ,statutmandat.lstatut' || clangue || ' as o, 0 as c from statutmandat group by 3,2,5
    UNION
     SELECT ''typ'' ,  typ.ctyp as v, typ.ltyp' || clangue || ' as t, CAST (typ.ctypmeta AS text) as p ,typ.ltyp' || clangue || ' as o, typ.binclure  from typ,typmeta where typ.ctypmeta = typmeta.ctypmeta and typ.binclure <> 0 group by 3,2,4,5
    UNION
     SELECT ''taux'' ,  taux.cdevise as v, taux.cdevise as t,null as p ,taux.cdevise as o, 1  from taux  group by 3,2,5
    UNION
     SELECT ''typmandat'' ,  typmandat.ctypmandat as v, typmandat.ltypmandat' || clangue || ' as t ,CAST (typmandat.ctypmandatmeta AS text) as p ,typmandat.ltypmandat' || clangue || ' as o,  max(typmandatmeta.mprixmax) from typmandat LEFT JOIN typmandatmeta ON typmandat.ctypmandatmeta = typmandatmeta.ctypmandatmeta group by 3,2,5
    UNION
     SELECT ''typmandatmeta'' ,  typmandatmeta.ctypmandatmeta as v, typmandatmeta.ltypmandatmeta' || clangue || ' as t ,null as p ,CAST (typmandatmeta.mprixmax AS character varying) as o,  mprixmax from typmandatmeta group by 3,2,5
    UNION
     SELECT ''typmeta'' ,  typmeta.ctypmeta as v, typmeta.ltypmeta' || clangue || ' as t,typmeta.ctypmetameta as p ,typmeta.ltypmeta' || clangue || ' as o,  1  from typmeta group by 3,2,5
    UNION
     SELECT ''typorientation'' ,  typorientation.corientation as v, typorientation.lorientation' || clangue || ' as t,null as p ,typorientation.lorientation' || clangue || ' as o,  1  from typorientation group by 3,2,5
    UNION
     SELECT ''style'' ,  style.cstyle as v, style.lstyle' || clangue || ' as t,null as p ,style.lstyle' || clangue || ' as o, 1 from style group by 3,2,5
    UNION
     SELECT ''region'' ,region.cregion as v, region.lregion' || clangue || ' as t,CAST (cregionmeta AS text) as p ,region.lregion' || clangue || ' as o, 1 from region group by 3,2,4,5
    UNION
     SELECT ''typchauf'' ,  typchauf.cchauf as v, typchauf.lchauf' || clangue || ' as t,null as p ,typchauf.lchauf as o, 1  from typchauf group by 3,2,5
    UNION
     SELECT ''typcivilite'' ,  typcivilite.ccivilite as v, typcivilite.lcivilite' || clangue || ' as t,null as p ,typcivilite.lcivilite' || clangue || ' as o, 1 from typcivilite
    UNION
     SELECT ''typsexe'' ,   typsexe.csexe as v,  typsexe.lsexe as t,null as p , typsexe.lsexe as o, 1 from typsexe
    UNION
     SELECT ''notaire'' , CAST (prospect.nprospect AS character varying) , concat (upper(lnom), '' '', initcap(lprenom) )  as t,null as p ,prospect.lnom as o, 1 from preference,prospect where preference.nprospectnotaire = prospect.ncategorie group by 3,2,4,5
    UNION
    SELECT ''utilisateur'' , utilisateur.lusername , ARRAY_TO_STRING(ARRAY[initcap (lprenom) , upper(lnom)], '' ''),CAST (utilisateur.cagence AS text) as p ,utilisateur.lprenom, 1 from utilisateur where lusername <> ''admin''
    UNION
    SELECT ''typdetail'',CAST (typdetail.ntypdetail AS character varying), typdetail.ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1  from typdetail where binclure = 1
    UNION
    SELECT ''typdetailmeta'',CAST (ntypdetailmeta AS character varying), ltypdetailmeta' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1  from typdetailmeta
    UNION
    SELECT ''typdetailbien'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1   from typdetail where btache = 0 and binclure = 1 and blinkid = 0
    UNION
    SELECT ''typdetailprospect'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1   from typdetail where btache = 0 and binclure = 1  and blinkid = 1
    UNION
    SELECT ''typdetailoffre'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1  from typdetail where binclure = 1 and  btache = 0 and blinkid = 2
    UNION
    SELECT ''typtachebien'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1  from typdetail where binclure = 1 and  btache = 1 and blinkid = 0
    UNION
    SELECT ''typtacheprospect'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1 from typdetail where binclure = 1  and btache = 1 and blinkid = 1
    UNION
    SELECT ''typtacheoffre'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1 as e  from typdetail where binclure = 1  and btache = 1 and blinkid = 2
    UNION
    SELECT ''typtache'',CAST (ntypdetail AS character varying), ltypdetail' || clangue || ' as t,TO_CHAR(typdetail.blinkid,''9'') as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1 as e  from typdetail where binclure = 1  and btache = 1
    UNION
    SELECT ''detail'', CAST (ndetail AS character varying), ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(nordre,''fm0000000000'') as o, detail.bcritere from detail
    UNION
    SELECT ''regmat'' ,  CAST (nregmat AS character varying), lregmat' || clangue || ' as t,null as p ,lregmat' || clangue || ' as o, 1 from regmat group by 3,2,5
    UNION
    SELECT ''cat'' ,CAST (cat.ncategorie AS character varying), lcategorie' || clangue || ' as t,null as p ,ccouleur as o, null  from cat where cat.binclure <> 0 group by 3,2,5
    UNION
    SELECT ''disponibilite'' ,  CAST (disponibilite.ndisponibilite AS character varying), ldisponibilite' || clangue || ' as t,null as p ,ldisponibilite' || clangue || ' as o, 1  from disponibilite group by 3,2,5
    UNION
    SELECT ''etat2'' ,  CAST (nordre AS character varying), letat' || clangue || ' as t,null as p ,TO_CHAR(nordre,''fm0000000000'') as o, 1  from etat group by 3,2,5
    UNION
    SELECT ''natmandat'' ,  CAST (natmandat.nnatmandat AS character varying), lnatmandat' || clangue || ' as t,null as p ,lnatmandat' || clangue || ' as o, 1  from natmandat group by 3,2,5
    UNION
    SELECT ''privilege'' , CAST (nprivilege AS character varying), lprivilege as t,null as p ,lprivilege as o, 1 from privilege
    UNION
    SELECT ''role'' ,  CAST (nrole AS character varying), lrole' || clangue || ' as t,null as p ,lrole' || clangue || ' as o, 1 from role
    UNION
    SELECT ''typcuisine'' ,  CAST (typcuisine.ntypcuisine AS character varying), ltypcuisine' || clangue || ' as t,null as p ,ltypcuisine' || clangue || ' as o, 1  from typcuisine group by 3,2,5
    UNION
    SELECT ''typpiscine'' ,  CAST (typpiscine.ntyppiscine AS character varying), ltyppiscine' || clangue || ' as t,null as p ,ltyppiscine' || clangue || ' as o, 1  from typpiscine group by 3,2,5
    UNION
    SELECT ''typrelation'' , CAST (ntyprelation AS character varying), ltyprelation' || clangue || ' as t,null as p ,ltyprelation' || clangue || ', 1 from typrelation group by 3,2,5
    UNION
    SELECT ''typrelationrv'' , CAST (ntyprelation AS character varying), ltyprelation' || clangue || ' as t,null as p ,ltyprelation' || clangue || ' as o, 1 as e  from typrelation where brendezvous = 1  group by 3,2,5
    UNION
    SELECT ''typrelationbien'' , CAST (ntyprelation AS character varying), ltyprelation' || clangue || ' as t,null as p ,TO_CHAR(nordrebien,''fm0000000000'')  as o, 1 as e  from typrelation where nordrebien > 0  group by 3,2,5
    UNION
    SELECT ''typrelationprospect'' , CAST (ntyprelation AS character varying), ltyprelation' || clangue || ' as t,null as p ,TO_CHAR(nordrepro,''fm0000000000'') as o, 1  as e  from typrelation where nordrepro > 0  group by 3,2,5
    UNION
    SELECT ''typrelationoffre'' , CAST (ntyprelation AS character varying), ltyprelation' || clangue || ' as t,null as p ,TO_CHAR(nordrepro,''fm0000000000'') as o, 1  as e  from typrelation where nordreoffre > 0  group by 3,2,5
    UNION
    SELECT ''statutbien'' ,  cast( statutbien.bactif as character varying ) as v, lstatutbien' || clangue || ' as t,  CAST (statutbien.bisactive AS text) as p ,cbgcolor as o, 1  from statutbien group by 3,2,4,5
    UNION
    SELECT ''trancheprix'' , cast(  mmin as character varying )||''|''||cast(  mmax as character varying ) as v, ltrancheprix as t,CAST (ctypmandat AS character varying) as p ,ltrancheprix as o, 1  from trancheprix
    UNION
    SELECT distinct ''cp'' , lcp as v, lcp as t,null as p ,null as o, 1 from ville where bcommon = 1  group by 3,2,5
    UNION
    SELECT ''ndetailcritprospect'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying)as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1 from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and detail.bcritere >= 1 and typdetail.blinkid = 1 and typdetail.btache = 0 and (detail.dmod >='''|| dfrom ||''' or exists (select null from typdetail b where b.dmod >='''|| dfrom ||'''))
    UNION
    SELECT ''mitoyennete'' ,  CAST (mitoyennete.nmitoyennete AS character varying) as v, mitoyennete.lmitoyennete' || clangue || ' as t,null as p ,mitoyennete.lmitoyenneteen as o, 1 from mitoyennete group by 3,2,5
    UNION
    SELECT ''detailtache'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying)as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1  as e  from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and typdetail.btache = 1
    UNION
    SELECT ''detailtachebien'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1  as e  from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and typdetail.btache = 1 and typdetail.blinkid = 0
    UNION
    SELECT ''detailtacheprospect'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1  as e  from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and typdetail.btache = 1 and typdetail.blinkid = 1
    UNION
    SELECT ''detailtacheoffre'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1  as e  from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and typdetail.btache = 1 and typdetail.blinkid = 2
    UNION
    SELECT ''detail2typdetail'', CAST (ndetail AS character varying), typdetail.ltypdetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1  as e  from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail
    UNION
    SELECT ''ndetailcritbien'', CAST (ndetail AS character varying), detail.ldetail' || clangue || ' as t,CAST (detail.ntypdetail AS character varying) as p ,TO_CHAR(detail.nordre,''fm0000000000'') as o, 1 from detail,typdetail where detail.ntypdetail = typdetail.ntypdetail and detail.bcritere > 0 and typdetail.blinkid = 0 and typdetail.btache = 0
    UNION
    SELECT ''programme'' ,  CAST (bien.nbien AS character varying), CAST (bien.cbien AS character varying) as t,null as p ,bien.cbien as o, bien.bactif from bien where bneuf=1
    UNION
    SELECT ''projet'' ,  CAST (bien.nbien AS character varying), CAST (bien.cbien AS character varying) as t,null as p ,bien.cbien as o, 1 from bien WHERE bneuf = 1
        ';
        RETURN QUERY EXECUTE sql;
    END;
    $BODY$
  LANGUAGE plpgsql VOLATILE ;


-- insérer un typrelation standard 'suivi' qui permet de suivre la relation entre un acquéreur et un bien

insert into typrelation ( ntyprelation , ltyprelationfr, ltyprelationen ) values ( 70 , 'Suivi commercial', 'Commercial follow up') ON CONFLICT (ntyprelation) DO NOTHING;;


DO $do$
BEGIN
    -- Create unique index indx_suivi_prospectbien on prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'indx_suivi_prospectbien' AND relkind = 'i') THEN
        CREATE UNIQUE INDEX indx_suivi_prospectbien ON prospectbien_t (nprospect, nbien, cagence, ntyprelation) WHERE ntyprelation = 70;
    END IF;

    -- Add column ninteret to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'ninteret') THEN
        ALTER TABLE prospectbien_t ADD COLUMN ninteret int DEFAULT 0;
    END IF;

    -- Drop trigger t_prospectbien_audit on prospectbien_t if it exists
    IF EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 't_prospectbien_audit' AND tgrelid = 'prospectbien_t'::regclass) THEN
        DROP TRIGGER t_prospectbien_audit ON prospectbien_t;
    END IF;

    -- Add column cicone to typrelation if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typrelation' AND column_name = 'cicone') THEN
        ALTER TABLE typrelation ADD COLUMN cicone character varying(25) DEFAULT 'event';
    END IF;

    -- Create sequence ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'ncategorie') THEN
        CREATE SEQUENCE ncategorie START WITH 100000;
    END IF;

    -- Create sequence nnatmandat if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'nnatmandat') THEN
        CREATE SEQUENCE nnatmandat START WITH 100000;
    END IF;

    -- Create sequence nregmat if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'nregmat') THEN
        CREATE SEQUENCE nregmat START WITH 100000;
    END IF;

    -- Create sequence ntypcuisine if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'ntypcuisine') THEN
        CREATE SEQUENCE ntypcuisine START WITH 100000;
    END IF;

    -- Create sequence ntyppiscine if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'ntyppiscine') THEN
        CREATE SEQUENCE ntyppiscine START WITH 100000;
    END IF;
END $do$;


CREATE OR REPLACE FUNCTION f_set_nextval_cat()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.ncategorie IS NULL) THEN NEW.ncategorie = nextval ('ncategorie'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

-- Supprimer le trigger tbui_cat_t_nextval s'il existe
DROP TRIGGER IF EXISTS tbui_cat_t_nextval ON cat;


-- Supprimer le trigger tbui_deleteprospectlog_audit s'il existe
DROP TRIGGER IF EXISTS tbui_deleteprospectlog_audit ON deleteprospectlog;


-- Supprimer le trigger tbui_typcuisine_t_nextval s'il existe
DROP TRIGGER IF EXISTS tbui_typcuisine_t_nextval ON typcuisine;



DROP TRIGGER IF EXISTS tbui_cat_t_nextval ON cat;
CREATE TRIGGER tbui_cat_t_nextval
  BEFORE INSERT OR UPDATE
  ON cat
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_cat();


--
DROP TRIGGER IF EXISTS tbui_deleteprospectlog_audit ON deleteprospectlog;
CREATE TRIGGER tbui_deleteprospectlog_audit
  BEFORE INSERT OR UPDATE
  ON deleteprospectlog
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();
--


CREATE OR REPLACE FUNCTION f_set_nextval_typcuisine()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.ntypcuisine IS NULL) THEN NEW.ntypcuisine = nextval ('ntypcuisine'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;


DROP TRIGGER IF EXISTS tbui_typcuisine_t_nextval ON typcuisine;
CREATE TRIGGER tbui_typcuisine_t_nextval
  BEFORE INSERT OR UPDATE
  ON typcuisine
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_typcuisine();

---
CREATE OR REPLACE FUNCTION f_set_nextval_natmandat()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.nnatmandat IS NULL) THEN NEW.nnatmandat = nextval ('nnatmandat'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

-- Supprimer le trigger s'il existe
DROP TRIGGER IF EXISTS tbui_natmandat_t_nextval ON natmandat;

CREATE TRIGGER tbui_natmandat_t_nextval
  BEFORE INSERT OR UPDATE
  ON natmandat
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_natmandat();

--


CREATE OR REPLACE FUNCTION f_set_nextval_regmat()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.nregmat IS NULL) THEN NEW.nregmat = nextval ('nregmat'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;


DROP TRIGGER IF EXISTS tbui_regmat_t_nextval ON regmat;
CREATE TRIGGER tbui_regmat_t_nextval
  BEFORE INSERT OR UPDATE
  ON regmat
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_regmat();

--

CREATE OR REPLACE FUNCTION f_set_nextval_typpiscine()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.ntyppiscine IS NULL) THEN NEW.ntyppiscine = nextval ('ntyppiscine'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;


DROP TRIGGER IF EXISTS tbui_typpiscine_t_nextval ON typpiscine;

CREATE TRIGGER tbui_typpiscine_t_nextval
  BEFORE INSERT OR UPDATE
  ON typpiscine
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_typpiscine();

---
CREATE OR REPLACE FUNCTION f_set_nextval_role()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.nrole IS NULL) THEN NEW.nrole = nextval ('nrole'); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

DROP TRIGGER IF EXISTS tbui_role_t_nextval ON role;

CREATE TRIGGER tbui_role_t_nextval
  BEFORE INSERT OR UPDATE
  ON role
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_role();

--alter table cat alter column bisaprospect set default 0 ;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM add_column_if_not_exists('cat', 'bisaprospect', 'integer' );
END
$do$;

update cat set bisaprospect = 1 where ncategorie in ( 1, 16,101) and bisaprospect is null ;
update cat set bisaprospect = 0 where bisaprospect is null ;
alter table cat alter column bisaprospect set not null ;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentcs','text');    
END
$do$;



DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentde','text');
END
$do$;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontenten','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentes','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentfr','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentit','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentnl','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentru','text');
END
$do$;

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentsk','text');
END
$do$;


DO $do$

BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM  add_column_if_not_exists('tpl', 'lcontentzh','text');
END
$do$;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM add_column_if_not_exists('tpl', 'lcontentre','text');
END $do$;


DO $do$
BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjectcs','text');
END $do$;


DO $do$

BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjectde','text');
END $do$;

DO $do$
BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjecten','text');
END $do$;

DO $do$
BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjectes','text');
END $do$;

DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('tpl', 'lsubjectfr','text');
END $do$;

DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('tpl', 'lsubjectit','text');
END $do$;

DO $do$
BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjectnl','text');
END $do$;

DO $do$
BEGIN
PERFORM  add_column_if_not_exists('tpl', 'lsubjectru','text');
END $do$;



DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('tpl', 'lsubjectsk','text');
END $do$;

DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('tpl', 'lsubjectzh','text');
END $do$;

DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('tpl', 'lsubjectre','text');
END $do$;

-- ALTER TABLE tpl ADD COLUMN lsubjectcs varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectde varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjecten varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectes varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectfr varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectit varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectnl varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectru varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectsk varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectzh varchar(250);
-- ALTER TABLE tpl ADD COLUMN lsubjectre varchar(250);

---

DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('todo', 'nordrebien','integer');
END $do$;


DO $do$
BEGIN
PERFORM     
 add_column_if_not_exists('todo', 'nordreprospect','integer');
END $do$;




CREATE OR REPLACE FUNCTION f_cdetail(
    nombre integer,
    unite character varying,
    detail character varying,
    comment character varying)
  RETURNS character varying AS
$BODY$

    DECLARE
    detail text ;
    unite text ;
    unite_prefix text ;
    --formatted_number integer ;

    BEGIN

 --   IF $1 > 0 THEN
--	formatted_number = to_char($1,'9,999') ;
 --   END IF ;


    IF $2 IS NULL OR $2 = ''  THEN

	   IF $1 > 1 THEN
			detail = replace($3, '(s)', 's');
			detail = replace(detail, '(x)', '');
	   ELSE
			detail = replace($3, '(s)', '');
			detail = replace(detail, '(x)', '');
	   END IF ;


         RETURN concat (  $1, ' ' , detail , ' ' , $4);

    ELSEIF $2 = '-' THEN
           RETURN concat (   $3 , ' ' , $1, ' ',  $4);
    ELSE
         RETURN concat (   $3 , ' ' , $1, ' ', $2 , ' ' , $4);
    END IF;

    END;

    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;



DO $do$
BEGIN
PERFORM     
  add_column_if_not_exists('typdetail', 'cicon', 'text');
END $do$;



ALTER TABLE typdetail ALTER COLUMN cicon SET DEFAULT 'fact_check';


CREATE OR REPLACE FUNCTION f_propag_bien_cagence()
  RETURNS trigger AS
$BODY$
declare
    cagence2   VARCHAR;
BEGIN

    IF (NEW.nbien IS NOT NULL ) THEN
             SELECT bien.cagence INTO cagence2 FROM bien WHERE bien.nbien = NEW.nbien  ;
             IF cagence2 IS NOT NULL THEN
                    NEW.cagence = cagence2 ;
             END IF;
   END IF;

    RETURN NEW;

END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION f_propag_bien_cagence()
  OWNER TO admin;

--ALTER TABLE typrelation ADD COLUMN ctyprelationmeta character varying(10);

DO $do$
BEGIN
PERFORM     
  add_column_if_not_exists('typrelation', 'ctyprelationmeta','character varying(10)');
END $do$;



CREATE TABLE IF NOT EXISTS typrelationmeta (
    ctyprelationmeta character varying(10) NOT NULL,
    ltyprelationmetafr character varying(50),
    ltyprelationmetaen character varying(50),
    ltyprelationmetanl character varying(50),
    ltyprelationmetade character varying(50),
    ltyprelationmetaes character varying(50),
    ltyprelationmetait character varying(50),
    ltyprelationmetask character varying(50),
    ltyprelationmetacs character varying(50),
    ltyprelationmetaru character varying(50),
    ltyprelationmetazh character varying(50),
    cicone character varying(25) DEFAULT 'event'::character varying,
    cusercre character varying(50),
    dcre timestamp without time zone,
    cusermod character varying(50),
    dmod timestamp without time zone,
    CONSTRAINT pk_typrelationmeta PRIMARY KEY (ctyprelationmeta)
)
WITH (
    OIDS=FALSE
);



CREATE TABLE IF NOT EXISTS typdetailmeta
(
  ntypdetailmeta integer NOT NULL,
  nordre smallint,
  cusercre character varying(50),
  dcre timestamp without time zone,
  cusermod character varying(50),
  dmod timestamp without time zone,
  cunite character varying(10),
  binternet integer,
  ltypdetailmetaen character varying(50),
  ltypdetailmetanl character varying(50),
  ltypdetailmetafr character varying(50),
  ltypdetailmetade character varying(50),
  binclure smallint DEFAULT 1,
  bprotect smallint,
  ctypdetailmeta character varying(20),
  btache smallint,
  blinkid integer,
  ltypdetailmetaes character varying(50),
  ltypdetailmetait character varying(255),
  ltypdetailmetask character varying(255),
  ltypdetailmetacs character varying(255),
  ltypdetailmetaru character varying(255),
  ltypdetailmetazh character varying(255),
  cicon character varying(25) DEFAULT 'fact_check'::character varying,
  CONSTRAINT pk_typdetailmeta PRIMARY KEY (ntypdetailmeta)
)
WITH (
  OIDS=FALSE
);

DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM add_column_if_not_exists('typrelation', 'ntyprelationactivite', 'integer' );
END
$do$;

insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('suivi','Suivi', 'Follow-up', 'Follow-up', 'send' ) ON CONFLICT (ctyprelationmeta) DO NOTHING;
insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('chat','Chat', 'Chat', 'Chat', 'chat' ) ON CONFLICT (ctyprelationmeta) DO NOTHING;
insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('rdv','Rendez-vous', 'Appointments', 'Appointments', 'event' )ON CONFLICT (ctyprelationmeta) DO NOTHING;
insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('change','Changements', 'Changes', 'Changes', 'trending_up' ) ON CONFLICT (ctyprelationmeta) DO NOTHING;
insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('perso','Perso', 'Private', 'Private', 'privacy_tip' ) ON CONFLICT (ctyprelationmeta) DO NOTHING;
insert into typrelationmeta (ctyprelationmeta, ltyprelationmetafr, ltyprelationmetaen, ltyprelationmetanl,cicone ) values ('autre','Autre', 'Other', 'Other', 'more_horiz' ) ON CONFLICT (ctyprelationmeta) DO NOTHING;


DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM add_column_if_not_exists('typdetail', 'ntypdetailmeta', 'integer' );
END
$do$;


DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ntypdetailmeta'
    ) THEN
        EXECUTE 'ALTER TABLE typdetail 
                 ADD CONSTRAINT fk_ntypdetailmeta 
                 FOREIGN KEY (ntypdetailmeta) 
                 REFERENCES typdetailmeta (ntypdetailmeta)';
    END IF;
END $do$;


DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.table_constraints 
        WHERE constraint_name = 'fk_ntyprelationactivite'
    ) THEN
        EXECUTE 'ALTER TABLE preference_t 
                 ADD CONSTRAINT fk_ntyprelationactivite 
                 FOREIGN KEY (ntyprelationactivite) 
                 REFERENCES typrelation (ntyprelation)';
    END IF;
END $do$;



insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 100, 1, 1,0,0,'Pièces', 'Rooms') ON CONFLICT (ntypdetailmeta) DO NOTHING;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 101, 2, 1,0,0,'Extérieurs', 'Ouside')ON CONFLICT (ntypdetailmeta) DO NOTHING;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 102, 3, 1,0,0,'Equipement', 'Equipment')ON CONFLICT (ntypdetailmeta) DO NOTHING;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 103, 4, 1,0,0,'Services', 'Services') ON CONFLICT (ntypdetailmeta) DO NOTHING; 
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 105, 6, 1,0,0,'Financier', 'Financial') ON CONFLICT (ntypdetailmeta) DO NOTHING;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 106, 7, 1,0,0,'Matériaux', 'Material') ON CONFLICT (ntypdetailmeta) DO NOTHING;
update  typdetailmeta set  ltypdetailmetafr = 'Matériaux' where ltypdetailmetafr ilike 'Matéri%' ;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 107, 8, 1,0,0,'Légal', 'Legal') ON CONFLICT (ntypdetailmeta) DO NOTHING;;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 108, 9, 1,0,0,'Pub', 'Pub') ON CONFLICT (ntypdetailmeta) DO NOTHING;
insert into typdetailmeta (ntypdetailmeta,nordre,bprotect, btache, blinkid , ltypdetailmetafr, ltypdetailmetaen ) values ( 110, 10, 1,0,0,'Autres', 'Other') ON CONFLICT (ntypdetailmeta) DO NOTHING;




DO $do$
BEGIN
    -- Ajuster la séquence à partir du maximum existant dans la table photo_t
    PERFORM add_column_if_not_exists('typdetail', 'ntypdetailmeta', 'integer default 110' );
END
$do$;





--ALTER TABLE typdetail ALTER COLUMN brendezvous set default 1;
--update typdetail set brendezvous = 0 where brendezvous <> 1;

update  typdetail set ntypdetailmeta = 100 where ntypdetail = 10056;
update  typdetail set ntypdetailmeta = 106 where ntypdetail = 66;
update  typdetail set ntypdetailmeta = 107 where ntypdetail = 114;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 1;
update  typdetail set ntypdetailmeta = 106 where ntypdetail = 68;
update  typdetail set ntypdetailmeta = 106 where ntypdetail = 125;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 122;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 10047;
update  typdetail set ntypdetailmeta = 105 where ntypdetail = 10044;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 69;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 3;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 127;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 4;
update  typdetail set ntypdetailmeta = 106 where ntypdetail = 53;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 75;
update  typdetail set ntypdetailmeta = 110 where ntypdetail = 155;
update  typdetail set ntypdetailmeta = 110 where ntypdetail = 119;
update  typdetail set ntypdetailmeta = 108 where ntypdetail = 128;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 132;
update  typdetail set ntypdetailmeta = 108 where ntypdetail = 153;
update  typdetail set ntypdetailmeta = 105 where ntypdetail = 151;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 111;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 126;
update  typdetail set ntypdetailmeta = 107 where ntypdetail = 120;
update  typdetail set ntypdetailmeta = 107 where ntypdetail = 117;
update  typdetail set ntypdetailmeta = 105 where ntypdetail = 14;
update  typdetail set ntypdetailmeta = 107 where ntypdetail = 124;
update  typdetail set ntypdetailmeta = 102 where ntypdetail = 115;
update  typdetail set ntypdetailmeta = 110 where ntypdetail = 10058;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 200;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 61;
update  typdetail set ntypdetailmeta = 105 where ntypdetail = 157;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 70;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 71;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 10045;
update  typdetail set ntypdetailmeta = 102 where ntypdetail = 20;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 10042;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 10053;
update  typdetail set ntypdetailmeta = 108 where ntypdetail = 100;
update  typdetail set ntypdetailmeta = 102 where ntypdetail = 116;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 73;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 72;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 123;
update  typdetail set ntypdetailmeta = 107 where ntypdetail = 118;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 121;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 2;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 74;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 76;
update  typdetail set ntypdetailmeta = 106 where ntypdetail = 58;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 62;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 54;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 63;
update  typdetail set ntypdetailmeta = 102 where ntypdetail = 51;
update  typdetail set ntypdetailmeta = 102 where ntypdetail = 55;
update  typdetail set ntypdetailmeta = 101 where ntypdetail = 201;
update  typdetail set ntypdetailmeta = 103 where ntypdetail = 203;
update  typdetail set ntypdetailmeta = 108 where ntypdetail = 110;
update  typdetail set ntypdetailmeta = 100 where ntypdetail = 202;
update  typdetail set ntypdetailmeta = 110 where ntypdetailmeta is null;

--



update preference_t set  ntyprelationvisite = 14 where ntyprelationvisite is null ;

--     DROP VIEW preference CASCADE ;

DO $do$
BEGIN
    PERFORM add_column_if_not_exists('prospectbien_t', 'llieurdv','varchar(200)');
END $do$;




--alter table prospectbien_t add column llieurdv varchar(200) ;

-- ajouter régénération de biencrits
--DROP TABLE params ;


/* Data for the 'public.typrelation' table  (Records 1 - 1) */

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (24, E'Signature acte', 0, 80, 10, 0, E'activimmo', E'10/06/2008 14:06:27', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Signature acte', E'Signature acte', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'teal', E'event', E'autre', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;


INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (1, E'Offre', 0, 0, 0, 0, NULL, NULL, E'admin', E'06/04/2018 13:46:03.68', NULL, E'Offre', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'red', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (5, E'Propriétaire', 0, 0, 0, 0, NULL, NULL, E'admin', E'06/04/2018 13:46:03.68', NULL, E'Propriétaire', E'Propriétaire', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'rdv', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (10, E'Annonce', 0, 0, 4, NULL, NULL, E'05/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Annonce', E'Annonce', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'blue', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (12, E'Renseignement', 1, 20, 1, NULL, NULL, E'01/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Renseignement', E'Renseignement', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'yellow', E'event', E'autre', 1)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (14, E'Visite', 1, 30, 2, NULL, NULL, E'01/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Visite', E'Visite', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 1, 1, E'#ffffff', E'#000000', E'blue', E'event', E'rdv', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (15, E'Téléphone', 1, 10, 2, NULL, NULL, E'01/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Téléphone', E'Téléphone', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'teal', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (16, E'Expertise', 0, 50, 6, NULL, NULL, E'01/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Expertise', E'Expertise', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'red', E'event', E'autre', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (17, E'Relance', 0, 40, 5, NULL, NULL, E'05/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Relance', E'Relance', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (18, E'Biens exclus', 0, 60, 6, 0, NULL, E'05/02/2005 22:48:52', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Biens exclus', E'Biens exclus', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'autre', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (20, E'Variation prix', 0, 0, 10, NULL, E'system', E'08/04/2009 00:00:10', E'admin', E'06/04/2018 13:46:03.68', E'Prijs verandering', E'Changement de Prix', E'Variation prix', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Price changes', 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (21, E'Variation de statut', 0, 0, 10, NULL, E'system', E'08/04/2009 00:00:10', E'admin', E'06/04/2018 13:46:03.68', E'Status verandering', E'Changement de statut', E'Variation Statut', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Status change', 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (22, E'Message interne', 1, 0, 10, NULL, E'system', E'08/04/2009 00:00:06', E'admin', E'06/04/2018 13:46:03.68', E'Message interne', E'Message interne', E'Message interne', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 1, E'#ffffff', E'#000000', E'black', E'event', E'chat', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (23, E'Signature compromis', 1, 70, 10, 0, E'activimmo', E'10/06/2008 14:06:27', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Signature compromis', E'Signature compromis', 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 1, 1, E'#ffffff', E'#000000', E'teal', E'event', E'autre', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (30, E'Changement de négo.', 0, 5, 5, NULL, E'admin', E'06/04/2018 13:44:40.321', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Changement de négociateur', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Salesman change', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (31, E'Changement pub. Web.', 0, 5, 5, NULL, E'admin', E'06/04/2018 13:44:40.555', E'admin', E'06/04/2018 13:46:03.68', NULL, E'Chang. statut pub. Web', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Publication status change', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (40, E'Changement de profil de réception de mails', 0, 100, 0, NULL, E'admin', E'01/06/2018 17:14:57.168', E'admin', E'01/06/2018 17:14:57.168', NULL, E'Changement de profil de réception de mails', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Mail profile change', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (41, E'Envoi d''un rapport d''activité', 0, 100, 0, NULL, E'admin', E'06/06/2018 10:09:50.872', E'admin', E'06/06/2018 10:09:50.872', NULL, E'Envoi de rapports d''activité', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Activity report sent by email', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (42, E'Envoi de voeux d''anniversaire', 0, 100, 0, NULL, E'admin', E'06/06/2018 10:09:50.919', E'admin', E'06/06/2018 10:09:50.919', NULL, E'Envoi de voeux d''anniversaire', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Happy birthday', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (50, E'Publication d''annonces', 0, 100, 0, NULL, E'admin', E'06/06/2018 10:09:50.95', E'admin', E'06/06/2018 10:09:50.95', NULL, E'Publication d''annonces', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Adverts publishing', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'suivi', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (60, E'Changement de mandat', 0, 100, 0, NULL, E'admin', E'07/07/2018 23:13:47.937', E'admin', E'07/07/2018 23:13:47.937', NULL, E'Changement de mandat', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Mandate change', 0, 1, E'#FFFFFF', E'#000000', E'black', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (70, NULL, 0, NULL, NULL, NULL, E'admin', E'09/11/2022 08:01:31.674812', E'admin', E'09/11/2022 08:01:31.674812', NULL, E'Suivi commercial', NULL, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, 0, E'Commercial follow up', 0, 1, E'#000000', E'#000000', E'blue', E'event', E'autre', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;


INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (80, 'Envoi de message WhatsApp', 0, 100, 100, NULL, 'system', '08/04/2009 00:00:10', 'admin', '06/04/2018 13:46:03.68', 'WhatsApp-bericht verzonden', 'Envoi de message WhatsApp', 'WhatsApp-Nachricht gesendet', 16777215, 0, 'Mensaje de WhatsApp enviado', 'Messaggio WhatsApp inviato', 'Správa WhatsApp odoslaná', 'Zpráva WhatsApp odeslána', 'Сообщение WhatsApp отправлено', 'WhatsApp消息已发送', 0, 'WhatsApp message sent', 0, 1, '#ffffff', '#000000', 'black', 'event', 'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;




INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (109, E'Email envoyé', 0, 5, 5, NULL, E'admin', E'09/01/2022 08:41:33.068036', E'admin', E'09/11/2022 08:41:33.068036', NULL, E'Email envoyé', NULL, 16777215, 0, NULL, NULL, NULL, NULL, NULL, NULL, 1, E'Mail sent', 0, 1, E'#FFFFFF', E'#000000', E'blue', E'event', E'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;



update params set lftpserver =(select lftpserver from preference_t limit 1) where lftpserver is null ;
update params set lftpusername =(select lftpusername from preference_t limit 1) where lftpusername is null ;
update params set lftppasswd   =(select lftppasswd from preference_t limit 1) where lftppasswd is null ;
update params set lftpsubdir  =(select lftpsubdir from preference_t limit 1) where lftpsubdir is null ;
update params set bftppassive = (select bftppassive from preference_t limit 1) where bftppassive is null ;
update params set bftpssl     = (select bftpssl from preference_t limit 1) where bftpssl is null ;
update params set nftpport    = (select nftpport from preference_t limit 1) where nftpport is null ;
update params set bftpssh     =  (select bftpssh from preference_t limit 1) where bftpssh is null ;

update params set nprospectnotaire   =  (select nprospectnotaire from preference_t limit 1) where nprospectnotaire is null ;
update params set nprospectprio   = (select nprospectprio from preference_t limit 1) where nprospectprio is null ;
update params set nprospectagence     = (select nprospectagence from preference_t limit 1) where nprospectagence is null ;
update params set nprospectprospect    =(select nprospectprospect from preference_t limit 1) where nprospectprospect is null ;

update params set ntyprelationssp      = (select ntyprelationssp from preference_t limit 1) where ntyprelationssp is null ;
update params set ntyprelationacte      =(select ntyprelationacte from preference_t limit 1) where ntyprelationacte is null ;
update params set ntyprelationactivite  = (select ntyprelationactivite from preference_t limit 1) where ntyprelationactivite is null ;
update params set ntyprelationrelance  = (select ntyprelationrelance from preference_t limit 1) where ntyprelationrelance is null ;
update params set ntyprelationemail      =  (select ntyprelationemail from preference_t limit 1) where ntyprelationemail is null ;
update params set ntyprelationvisite     =  (select ntyprelationvisite from preference_t limit 1) where ntyprelationvisite is null ;

update params set lintraneturl          =  (select lintraneturl from agence order by nagence limit 1) where lintraneturl is null ;

update params set nprospectlead         =  (select nprospectlead from preference_t limit 1) where nprospectlead is null ;

DO $do$
BEGIN
    IF EXISTS (
        SELECT 1
        FROM detail
        WHERE ndetail = 2642
    ) THEN
        UPDATE params
        SET ndetailtodoreminder = 2642
        WHERE ndetailtodoreminder IS NULL;
    ELSE
        RAISE NOTICE 'Value 2642 does not exist in the referenced table. Update not performed.';
    END IF;
END
$do$;



DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'pk_params'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT pk_params PRIMARY KEY(id);
    END IF;
END
$$;


insert into params (id) values (0) ON CONFLICT (id) DO NOTHING;;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_nprospectnotaire'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_nprospectnotaire 
            FOREIGN KEY (nprospectnotaire) REFERENCES cat (ncategorie) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_nprospectprio'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_nprospectprio 
            FOREIGN KEY (nprospectprio) REFERENCES cat (ncategorie) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_nprospectagence'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_nprospectagence 
            FOREIGN KEY (nprospectagence) REFERENCES cat (ncategorie) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_nprospectprospect'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_nprospectprospect 
            FOREIGN KEY (nprospectprospect) REFERENCES cat (ncategorie) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_nprospectlead'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_nprospectlead 
            FOREIGN KEY (nprospectlead) REFERENCES cat (ncategorie) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationssp'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationssp 
            FOREIGN KEY (ntyprelationssp) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationacte'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationacte 
            FOREIGN KEY (ntyprelationacte) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationactivite'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationactivite 
            FOREIGN KEY (ntyprelationactivite) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationrelance'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationrelance 
            FOREIGN KEY (ntyprelationrelance) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationemail'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationemail 
            FOREIGN KEY (ntyprelationemail) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ntyprelationvisite'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ntyprelationvisite 
            FOREIGN KEY (ntyprelationvisite) REFERENCES typrelation (ntyprelation) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'fk_params_ndetailtodoreminder'
    ) THEN
        ALTER TABLE params ADD CONSTRAINT fk_params_ndetailtodoreminder 
            FOREIGN KEY (ndetailtodoreminder) REFERENCES detail (ndetail) ON UPDATE CASCADE ON DELETE SET NULL;
    END IF;
END
$$;


--drop table statutlead ;
CREATE TABLE IF NOT EXISTS statutlead
(
  nstatutlead serial NOT NULL,
  lstatutleadfr character varying(50),
  lstatutleaden character varying(50),
  lstatutleadnl character varying(50),
  lstatutleadde character varying(50),
  lstatutleades character varying(50),
  lstatutleadit character varying(50),
  lstatutleadsk character varying(50),
  lstatutleadcs character varying(50),
  lstatutleadru character varying(50),
  lstatutleadzh character varying(50),
  nordre integer,
  binclure smallint DEFAULT 1,
  cusercre character varying(10),
  dcre date,
  cusermod character varying(10),
  dmod date,
  CONSTRAINT pk_statutlead PRIMARY KEY (nstatutlead)
)
WITH (
  OIDS=FALSE
);


CREATE OR REPLACE FUNCTION f_set_nextval_statutlead()
  RETURNS trigger AS
$BODY$ BEGIN IF (NEW.nstatutlead  IS NULL) THEN NEW.nstatutlead  = f_nextval('nstatutlead '); END IF; RETURN NEW; END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;



-- Trigger: tbui_statutlead_audit on statutlead
-- DROP TRIGGER tbui_statutlead_audit ON statutlead;

DROP TRIGGER IF EXISTS tbui_statutlead_audit ON statutlead;

CREATE TRIGGER tbui_statutlead_audit
  BEFORE INSERT OR UPDATE
  ON statutlead
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();



-- Trigger: tbui_statutlead_nextval on statutlead

-- DROP TRIGGER tbui_statutlead_nextval ON statutlead;
DROP TRIGGER IF EXISTS tbui_statutlead_nextval ON statutlead;
CREATE TRIGGER tbui_statutlead_nextval
  BEFORE INSERT OR UPDATE
  ON statutlead
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_nextval_statutlead();

insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (1, 1 , 'Non assigné', 'Raw', 'Raw') ON CONFLICT (nstatutlead) DO NOTHING;
insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (2, 2 , 'Assigné', 'Assigned', 'Assigned') ON CONFLICT (nstatutlead) DO NOTHING;
insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (3, 3 , 'En traitement', 'Working', 'Working') ON CONFLICT (nstatutlead) DO NOTHING ;
insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (4, 4 , 'Qualifié', 'Qualified', 'Qualified') ON CONFLICT (nstatutlead) DO NOTHING ;
insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (5, 5 , 'Reporté', 'Nurture', 'Nurture') ON CONFLICT (nstatutlead) DO NOTHING ;
insert into statutlead (nstatutlead , nordre, lstatutleadfr, lstatutleaden, lstatutleadnl ) VALUES (6, 6 , 'Pas intéressé', 'Unqualified', 'Unqualified') ON CONFLICT (nstatutlead) DO NOTHING ;

-- 1. Raw
-- 2. Assigned
-- 3. Working
-- 4. Qualified (now)
-- 5. Nurture (not now)
-- 6. Unqualified (never)
DO $do$
BEGIN
    -- Vérifier si la colonne n'existe pas déjà
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'prospect_t' AND column_name = 'nstatutlead'
    ) THEN
        -- Ajouter la colonne si elle n'existe pas
        ALTER TABLE prospect_t ADD COLUMN nstatutlead integer ;
    END IF;
END $do$;


update offre_t set bpaye = 0 where bpaye is null ;
DO $do$
BEGIN
    
        -- Vérifier si la colonne n'existe pas déjà
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'offre_t' AND column_name = 'bpaye'
    ) THEN
        -- Ajouter la colonne si elle n'existe pas
        ALTER TABLE offre_t ADD COLUMN bpaye integer DEFAULT 0;
    END IF;

    
    -- Vérifier et modifier la valeur par défaut si nécessaire
    IF (SELECT column_default FROM information_schema.columns 
        WHERE table_name = 'offre_t' AND column_name = 'bpaye') IS DISTINCT FROM '0' THEN
        ALTER TABLE offre_t ALTER COLUMN bpaye SET DEFAULT 0;
    END IF;

    -- Vérifier et modifier la contrainte NOT NULL si nécessaire
    IF EXISTS (SELECT 1 FROM information_schema.columns 
               WHERE table_name = 'offre_t' AND column_name = 'bpaye' AND is_nullable = 'YES') THEN
        ALTER TABLE offre_t ALTER COLUMN bpaye SET NOT NULL;
    END IF;
END $do$;




CREATE OR REPLACE FUNCTION strip_nulls(    IN array_in ANYARRAY)  RETURNS anyarray AS 'SELECT    array_agg(a) FROM unnest(array_in) a WHERE a IS NOT NULL;' LANGUAGE sql;

DO $do$
BEGIN
    -- Vérifier si la colonne n'existe pas déjà
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'todo' AND column_name = 'nordreoffre'
    ) THEN
        -- Ajouter la colonne si elle n'existe pas
        ALTER TABLE todo ADD COLUMN nordreoffre integer DEFAULT 0;
    END IF;
END $do$;


DO $do$
BEGIN
    -- Vérifier si la colonne n'existe pas déjà
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'todo' AND column_name = 'nordrenego'
    ) THEN
        -- Ajouter la colonne si elle n'existe pas
        ALTER TABLE todo ADD COLUMN nordrenego integer DEFAULT 0;
    END IF;
END $do$;



update todo set nordrenego = 0 where nordrenego is null ;
update todo set nordrebien = 0 where nordrebien is null ;
update todo set nordreprospect = 0 where nordreprospect is null ;



DROP INDEX IF EXISTS indx_pub_prospectbien;


CREATE OR REPLACE FUNCTION calculate_distance(lat1 float, lon1 float, lat2 float, lon2 float, units varchar)
-- exemple SELECT calculate_distance(32.9697, -96.80322, 29.46786, -98.53506, 'K'); -> distance en km ( 'M' pour miles)
RETURNS float AS $dist$
    DECLARE
        dist float = 0;
        radlat1 float;
        radlat2 float;
        theta float;
        radtheta float;
    BEGIN
        IF lat1 = lat2 OR lon1 = lon2
            THEN RETURN dist;
        ELSE
            radlat1 = pi() * lat1 / 180;
            radlat2 = pi() * lat2 / 180;
            theta = lon1 - lon2;
            radtheta = pi() * theta / 180;
            dist = sin(radlat1) * sin(radlat2) + cos(radlat1) * cos(radlat2) * cos(radtheta);

            IF dist > 1 THEN dist = 1; END IF;

            dist = acos(dist);
            dist = dist * 180 / pi();
            dist = dist * 60 * 1.1515;

            IF upper(units) = 'K' THEN dist = dist * 1.609344; END IF;
            IF upper(units) = 'N' THEN dist = dist * 0.8684; END IF;

            RETURN dist;
        END IF;
    END;
$dist$ LANGUAGE plpgsql;

--
--
--( utilisateur.bselectprospectagence = 0 and utilisateur.cagence = p.cagence and nprospect in (select nprospect from prospectbien_t where ntyprelation = 5) )
--)
update prospect_t set lnom = '-' where lnom is null ;

ALTER TABLE prospect_t ALTER COLUMN lnom SET NOT NULL;



update bien_t set tcommissionvendeur = 0 where tcommissionvendeur is null ;

DO $do$
BEGIN
    -- Vérifier et modifier la contrainte NOT NULL si nécessaire
    IF EXISTS (SELECT 1 FROM information_schema.columns 
               WHERE table_name = 'bien_t' AND column_name = 'tcommissionvendeur' AND is_nullable = 'YES') THEN
        ALTER TABLE bien_t ALTER COLUMN tcommissionvendeur SET NOT NULL;
    END IF;

    -- Vérifier et modifier la valeur par défaut si nécessaire
    IF (SELECT column_default FROM information_schema.columns 
        WHERE table_name = 'bien_t' AND column_name = 'tcommissionvendeur') IS DISTINCT FROM '0' THEN
        ALTER TABLE bien_t ALTER COLUMN tcommissionvendeur SET DEFAULT 0;
    END IF;
    IF (SELECT column_default FROM information_schema.columns 
        WHERE table_name = 'photo_t' AND column_name = 'bexportweb') IS DISTINCT FROM '0' THEN
        ALTER TABLE photo_t ALTER COLUMN bexportweb SET DEFAULT 0;
    END IF;


END $do$;

CREATE INDEX IF NOT EXISTS indx_prospect_ltelecom ON prospect_t USING btree (ltelecom);

update cat set ccouleur = '#286ab3' where ccouleur is null or ccouleur = '#000000';

DO $do$
BEGIN
    -- Vérifier si la colonne n'existe pas déjà
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'typrelation' AND column_name = 'cclasse'
    ) THEN
        -- Ajouter la colonne si elle n'existe pas
        ALTER TABLE typrelation ADD COLUMN cclasse character varying(10) DEFAULT 'blue';
    ELSE
        -- Si la colonne existe déjà, on peut optionnellement mettre à jour la valeur par défaut
        ALTER TABLE typrelation ALTER COLUMN cclasse SET DEFAULT 'blue';
    END IF;
END $do$;


update typrelation set cclasse = 'red' where ntyprelation = 1 ;
update typrelation set cclasse = 'black' where ntyprelation = 5 ;
update typrelation set cclasse = 'yellow' where ntyprelation = 12 ;
update typrelation set cclasse = 'blue' where ntyprelation = 14 ;
update typrelation set cclasse = 'teal' where ntyprelation = 15 ;
update typrelation set cclasse = 'red' where ntyprelation = 16 ;
update typrelation set cclasse = 'black' where ntyprelation = 17 ;
update typrelation set cclasse = 'black' where ntyprelation = 18 ;
update typrelation set cclasse = 'black' where ntyprelation = 20 ;
update typrelation set cclasse = 'black' where ntyprelation = 21 ;
update typrelation set cclasse = 'black' where ntyprelation = 22 ;
update typrelation set cclasse = 'teal' where ntyprelation = 23 ;
update typrelation set cclasse = 'teal' where ntyprelation = 24 ;
update typrelation set cclasse = 'black' where ntyprelation = 25 ;
update typrelation set cclasse = 'black' where ntyprelation = 26 ;
update typrelation set cclasse = 'black' where ntyprelation = 30 ;
update typrelation set cclasse = 'black' where ntyprelation = 31 ;
update typrelation set cclasse = 'black' where ntyprelation = 40 ;
update typrelation set cclasse = 'black' where ntyprelation = 41 ;
update typrelation set cclasse = 'black' where ntyprelation = 42 ;
update typrelation set cclasse = 'black' where ntyprelation = 50 ;
update typrelation set cclasse = 'black' where ntyprelation = 60 ;
update typrelation set cclasse = 'blue' where ntyprelation = 101 ;
update typrelation set cclasse = 'teal' where ntyprelation = 102 ;
update typrelation set cclasse = 'black' where ntyprelation = 107 ;
update typrelation set cclasse = 'black' where ntyprelation = 108 ;

update typrelation set cclasse = 'WhiteSmoke' where cclasse is null ;

DO $do$
BEGIN
    -- Update prospectdef only if ncategorie 101 exists in the referenced table
    IF EXISTS (SELECT 1 FROM cat WHERE ncategorie = 101) THEN
        UPDATE prospectdef SET ncategorie = 101 WHERE ncategorie IS NULL;
    END IF;
    
    -- Update prospect_t only if ncategorie 101 exists in the referenced table
    IF EXISTS (SELECT 1 FROM cat WHERE ncategorie = 101) THEN
        UPDATE prospect_t SET ncategorie = 101 WHERE ncategorie IS NULL;
    END IF;
EXCEPTION
    WHEN foreign_key_violation THEN
        RAISE NOTICE 'Foreign key constraint violation prevented. Category 101 may not exist.';
    WHEN OTHERS THEN
        RAISE NOTICE 'Error updating ncategorie: %', SQLERRM;

    IF EXISTS (SELECT 1 FROM cat WHERE ncategorie = 101) THEN
        ALTER TABLE cat ALTER COLUMN ncategorie set default 101;

        ELSE
            IF EXISTS (SELECT 1 FROM cat WHERE ncategorie = 1) THEN
                ALTER TABLE cat ALTER COLUMN ncategorie set default 1;
                UPDATE prospect_t SET ncategorie = 1 WHERE ncategorie IS NULL;
            END IF;
    END IF;
    
END $do$;



--ALTER TABLE biencrit_t ADD COLUMN ltypsfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmetasfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregionsfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregionmetasfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmandatsfr character varying(1000);

--ALTER TABLE biencrit_t ADD COLUMN cregion16 character varying(1000);



CREATE OR REPLACE FUNCTION f_set_biencrit_lmulti()
    RETURNS trigger AS
$BODY$
DECLARE
         ltypsfr VARCHAR(1000);
         ltypmetasfr VARCHAR(1000);
         lregionsfr VARCHAR(1000);
         lregionmetasfr VARCHAR(1000);
         ltypmandatsfr VARCHAR(1000);
         lenvironnementsfr VARCHAR(1000);
         lstylesfr VARCHAR(1000);
         lprogrammesfr VARCHAR(1000);
         ldetailsfr VARCHAR(1000);
         lsearchfr TEXT;
         lsearchen TEXT;
         ltypsen VARCHAR(1000);
         ltypmetasen VARCHAR(1000);
         lregionsen VARCHAR(1000);
         lregionmetasen VARCHAR(1000);
         ltypmandatsen VARCHAR(1000);
         lenvironnementsen VARCHAR(1000);
         lstylesen VARCHAR(1000);
         lprogrammesen VARCHAR(1000);
         ldetailsen VARCHAR(1000);
         ltypmandatmetasfr  VARCHAR(1000);
         ltypmandatmetasen  VARCHAR(1000);
         ltempfr  VARCHAR(1000);
         ltempen  VARCHAR(1000);
         ballowforeigners  integer ;
BEGIN


--ALTER TABLE biencrit_t ADD COLUMN ltypsfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmetas character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregions character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregionmetas character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmandats character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmandats character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lenvironnementsfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lstylesfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lprogrammesfr character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ldetailsfr character varying(1000);

--ALTER TABLE biencrit_t ADD COLUMN ltypsen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmetasen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregionsen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lregionmetasen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ltypmandatsen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lenvironnementsen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lstylesen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN lprogrammesen character varying(1000);
--ALTER TABLE biencrit_t ADD COLUMN ldetailsen character varying(1000);

-- lenvironnementsfr
SELECT INTO ltypmandatsfr array_to_string (array_agg(DISTINCT ltypmandatfr),', ','') FROM typmandat WHERE typmandat.ctypmandat = ANY (array [NEW.ctypmandat1, NEW.ctypmandat2])  ;
SELECT INTO ltypmandatsen array_to_string (array_agg(DISTINCT ltypmandaten),', ','') FROM typmandat WHERE typmandat.ctypmandat = ANY (array [NEW.ctypmandat1, NEW.ctypmandat2])  ;

SELECT INTO ltypmandatmetasfr array_to_string (array_agg(DISTINCT typmandatmeta.ltypmandatmetafr),', ','') FROM typmandat JOIN typmandatmeta ON typmandat.ctypmandatmeta = typmandatmeta.ctypmandatmeta WHERE typmandat.ctypmandat = ANY (array [NEW.ctypmandat1, NEW.ctypmandat2])  ;
SELECT INTO ltypmandatmetasen array_to_string (array_agg(DISTINCT typmandatmeta.ltypmandatmetaen),', ','') FROM typmandat JOIN typmandatmeta ON typmandat.ctypmandatmeta = typmandatmeta.ctypmandatmeta  WHERE typmandat.ctypmandat = ANY (array [NEW.ctypmandat1, NEW.ctypmandat2])  ;

SELECT INTO ltypsfr      array_to_string (array_agg(DISTINCT typ.ltypfr),', ','')        FROM typ WHERE typ.ctyp         = ANY (array [NEW.ctyp1, NEW.ctyp2, NEW.ctyp3, NEW.ctyp4, NEW.ctyp5, NEW.ctyp6, NEW.ctyp7, NEW.ctyp8, NEW.ctyp9, NEW.ctyp10, NEW.ctyp11, NEW.ctyp12, NEW.ctyp13, NEW.ctyp14, NEW.ctyp15])  ;

--SELECT INTO ballowforeigners       typ.ballowforeigners        FROM typ WHERE typ.ctyp         = ANY (array [NEW.ctyp1, NEW.ctyp2, NEW.ctyp3, NEW.ctyp4, NEW.ctyp5, NEW.ctyp6, NEW.ctyp7, NEW.ctyp8, NEW.ctyp9, NEW.ctyp10, NEW.ctyp11, NEW.ctyp12, NEW.ctyp13, NEW.ctyp14, NEW.ctyp15])  ;

SELECT INTO ltypmetasfr array_to_string (array_agg(DISTINCT typmeta.ltypmetafr),', ','') FROM typmeta WHERE typmeta.ctypmeta = ANY (array [NEW.ctypmeta1, NEW.ctypmeta2, NEW.ctypmeta3, NEW.ctypmeta4, NEW.ctypmeta5, NEW.ctypmeta6, NEW.ctypmeta7, NEW.ctypmeta8, NEW.ctypmeta9, NEW.ctypmeta10, NEW.ctypmeta11, NEW.ctypmeta12, NEW.ctypmeta13, NEW.ctypmeta14, NEW.ctypmeta15])  ;
SELECT INTO lregionsfr array_to_string (array_agg(DISTINCT region.lregionfr),', ','') FROM region WHERE region.cregion = ANY (array [NEW.cregion1, NEW.cregion2, NEW.cregion3, NEW.cregion4, NEW.cregion5, NEW.cregion6, NEW.cregion7, NEW.cregion8, NEW.cregion9, NEW.cregion10, NEW.cregion11, NEW.cregion12, NEW.cregion13, NEW.cregion14, NEW.cregion15 , NEW.cregion16,NEW.cregion17, NEW.cregion18,NEW.cregion19,NEW.cregion20,NEW.cregion21,NEW.cregion22,NEW.cregion23,NEW.cregion24,NEW.cregion25])  ;
SELECT INTO lregionmetasfr array_to_string (array_agg(DISTINCT regionmeta.lregionmetafr),', ','') FROM regionmeta WHERE regionmeta.cregionmeta = ANY (array [NEW.cregionmeta1, NEW.cregionmeta2, NEW.cregionmeta3, NEW.cregionmeta4, NEW.cregionmeta5, NEW.cregionmeta6, NEW.cregionmeta7, NEW.cregionmeta8, NEW.cregionmeta9, NEW.cregionmeta10, NEW.cregionmeta11, NEW.cregionmeta12, NEW.cregionmeta13, NEW.cregionmeta14, NEW.cregionmeta15])  ;
SELECT INTO lenvironnementsfr array_to_string (array_agg(DISTINCT environnement.lenvironnementfr),', ','') FROM environnement WHERE environnement.cenvironnement = ANY (array [NEW.cenvironnement1, NEW.cenvironnement2, NEW.cenvironnement3, NEW.cenvironnement4, NEW.cenvironnement5, NEW.cenvironnement6, NEW.cenvironnement7, NEW.cenvironnement8, NEW.cenvironnement9, NEW.cenvironnement10, NEW.cenvironnement11, NEW.cenvironnement12, NEW.cenvironnement13, NEW.cenvironnement14, NEW.cenvironnement15 ])  ;
SELECT INTO lstylesfr array_to_string (array_agg(DISTINCT style.lstylefr),', ','') FROM style WHERE style.cstyle = ANY (array [NEW.cstyle1, NEW.cstyle2, NEW.cstyle3, NEW.cstyle4, NEW.cstyle5, NEW.cstyle6, NEW.cstyle7, NEW.cstyle8, NEW.cstyle9, NEW.cstyle10, NEW.cstyle11, NEW.cstyle12, NEW.cstyle13, NEW.cstyle14, NEW.cstyle15 ])  ;
SELECT INTO lprogrammesfr array_to_string (array_agg(DISTINCT bien.cbien),', ','') FROM bien WHERE bien.nbien = ANY (array [NEW.nprogramme1, NEW.nprogramme2, NEW.nprogramme3, NEW.nprogramme4, NEW.nprogramme5, NEW.nprogramme6, NEW.nprogramme7, NEW.nprogramme8, NEW.nprogramme9, NEW.nprogramme10, NEW.nprogramme11, NEW.nprogramme12, NEW.nprogramme13, NEW.nprogramme14, NEW.nprogramme15 ])  ;
SELECT INTO ldetailsfr array_to_string (array_agg(DISTINCT detail.ldetailfr),', ','') FROM detail WHERE detail.ndetail = ANY (array [NEW.ndetail1, NEW.ndetail2, NEW.ndetail3, NEW.ndetail4, NEW.ndetail5, NEW.ndetail6, NEW.ndetail7, NEW.ndetail8, NEW.ndetail9, NEW.ndetail10, NEW.ndetail11, NEW.ndetail12, NEW.ndetail13, NEW.ndetail14, NEW.ndetail15 ])  ;

--english
SELECT INTO ltypsen      array_to_string (array_agg(DISTINCT typ.ltypen),', ','')        FROM typ     WHERE typ.ctyp         = ANY (array [NEW.ctyp1, NEW.ctyp2, NEW.ctyp3, NEW.ctyp4, NEW.ctyp5, NEW.ctyp6, NEW.ctyp7, NEW.ctyp8, NEW.ctyp9, NEW.ctyp10, NEW.ctyp11, NEW.ctyp12, NEW.ctyp13, NEW.ctyp14, NEW.ctyp15])  ;
SELECT INTO ltypmetasen array_to_string (array_agg(DISTINCT typmeta.ltypmetaen),', ','') FROM typmeta WHERE typmeta.ctypmeta = ANY (array [NEW.ctypmeta1, NEW.ctypmeta2, NEW.ctypmeta3, NEW.ctypmeta4, NEW.ctypmeta5, NEW.ctypmeta6, NEW.ctypmeta7, NEW.ctypmeta8, NEW.ctypmeta9, NEW.ctypmeta10, NEW.ctypmeta11, NEW.ctypmeta12, NEW.ctypmeta13, NEW.ctypmeta14, NEW.ctypmeta15])  ;
SELECT INTO lregionsen array_to_string (array_agg(DISTINCT region.lregionen),', ','') FROM region WHERE region.cregion = ANY (array [NEW.cregion1, NEW.cregion2, NEW.cregion3, NEW.cregion4, NEW.cregion5, NEW.cregion6, NEW.cregion7, NEW.cregion8, NEW.cregion9, NEW.cregion10, NEW.cregion11, NEW.cregion12, NEW.cregion13, NEW.cregion14, NEW.cregion15 , NEW.cregion16,NEW.cregion17, NEW.cregion18,NEW.cregion19,NEW.cregion20,NEW.cregion21,NEW.cregion22,NEW.cregion23,NEW.cregion24,NEW.cregion25])  ;
SELECT INTO lregionmetasen array_to_string (array_agg(DISTINCT regionmeta.lregionmetaen),', ','') FROM regionmeta WHERE regionmeta.cregionmeta = ANY (array [NEW.cregionmeta1, NEW.cregionmeta2, NEW.cregionmeta3, NEW.cregionmeta4, NEW.cregionmeta5, NEW.cregionmeta6, NEW.cregionmeta7, NEW.cregionmeta8, NEW.cregionmeta9, NEW.cregionmeta10, NEW.cregionmeta11, NEW.cregionmeta12, NEW.cregionmeta13, NEW.cregionmeta14, NEW.cregionmeta15])  ;
SELECT INTO lenvironnementsen array_to_string (array_agg(DISTINCT environnement.lenvironnementen),', ','') FROM environnement WHERE environnement.cenvironnement = ANY (array [NEW.cenvironnement1, NEW.cenvironnement2, NEW.cenvironnement3, NEW.cenvironnement4, NEW.cenvironnement5, NEW.cenvironnement6, NEW.cenvironnement7, NEW.cenvironnement8, NEW.cenvironnement9, NEW.cenvironnement10, NEW.cenvironnement11, NEW.cenvironnement12, NEW.cenvironnement13, NEW.cenvironnement14, NEW.cenvironnement15 ])  ;
SELECT INTO lstylesen array_to_string (array_agg(DISTINCT style.lstyleen),', ','') FROM style WHERE style.cstyle = ANY (array [NEW.cstyle1, NEW.cstyle2, NEW.cstyle3, NEW.cstyle4, NEW.cstyle5, NEW.cstyle6, NEW.cstyle7, NEW.cstyle8, NEW.cstyle9, NEW.cstyle10, NEW.cstyle11, NEW.cstyle12, NEW.cstyle13, NEW.cstyle14, NEW.cstyle15 ])  ;
SELECT INTO lprogrammesen array_to_string (array_agg(DISTINCT bien.cbien),', ','') FROM bien WHERE bien.nbien = ANY (array [NEW.nprogramme1, NEW.nprogramme2, NEW.nprogramme3, NEW.nprogramme4, NEW.nprogramme5, NEW.nprogramme6, NEW.nprogramme7, NEW.nprogramme8, NEW.nprogramme9, NEW.nprogramme10, NEW.nprogramme11, NEW.nprogramme12, NEW.nprogramme13, NEW.nprogramme14, NEW.nprogramme15 ])  ;
SELECT INTO ldetailsen array_to_string (array_agg(DISTINCT detail.ldetailen),', ','') FROM detail WHERE detail.ndetail = ANY (array [NEW.ndetail1, NEW.ndetail2, NEW.ndetail3, NEW.ndetail4, NEW.ndetail5, NEW.ndetail6, NEW.ndetail7, NEW.ndetail8, NEW.ndetail9, NEW.ndetail10, NEW.ndetail11, NEW.ndetail12, NEW.ndetail13, NEW.ndetail14, NEW.ndetail15 ])  ;

NEW.ltypsfr = ltypsfr ;
NEW.ltypmetasfr = ltypmetasfr;
NEW.lregionsfr = lregionsfr ;
NEW.lregionmetasfr = lregionmetasfr ;
NEW.ltypmandatsfr = ltypmandatsfr ;
NEW.lenvironnementsfr = lenvironnementsfr;
NEW.lstylesfr = lstylesfr ;
NEW.lprogrammesfr = lprogrammesfr ;
NEW.ldetailsfr = ldetailsfr;

IF (NEW.bpiscinemin > 0 ) THEN
      ltempfr := concat ( ltempfr ,  ' piscine') ;
      ltempen := concat ( ltempfr ,  ' swimming pool swimmingpool') ;
END IF;

IF (NEW.ballowforeigners > 0 ) THEN
      ltempfr := concat (ltempfr , ' accessible etrangers') ;
      ltempen := concat (ltempen , ' accessible foreigners') ;
END IF;

NEW.lsearchfr = trim(lower (unaccent (concat ( ltempfr, ' ' , NEW.qchambresmin , 'chambres ' ,NEW.qpiecesmin , 'pieces ' , ltypmandatmetasfr , ' ' , ltypsfr , ' ' ,  ltypmetasfr ,  ' ' ,  lregionsfr ,  ' ' ,  lregionmetasfr ,  ' ' ,  ltypmandatsfr , ' ', lenvironnementsfr , ' ' ,lstylesfr, ' ' , lprogrammesfr , ' ' , ldetailsfr)  ))) ;

-- english
NEW.ltypsen = ltypsen ;
NEW.ltypmetasen = ltypmetasen;
NEW.lregionsen = lregionsen ;
NEW.lregionmetasen = lregionmetasen ;
NEW.ltypmandatsen = ltypmandatsen ;
NEW.lenvironnementsen = lenvironnementsen;
NEW.lstylesen = lstylesen ;
NEW.lprogrammesen = lprogrammesen ;
NEW.ldetailsen = ldetailsen;
NEW.lsearchen = trim(lower (unaccent (concat (  ltempfr, ' ' , NEW.qchambresmin , 'bedrooms ' ,NEW.qpiecesmin , 'rooms ' , ltypmandatmetasen , ' ' ,ltypsen , ' ' ,  ltypmetasen ,  ' ' ,  lregionsen ,  ' ' ,  lregionmetasen ,  ' ' ,  ltypmandatsen , ' ', lenvironnementsen , ' ' ,lstylesen, ' ' , lprogrammesen , ' ' , ldetailsen)  ))) ;


RETURN NEW;
        END; $BODY$
    LANGUAGE plpgsql VOLATILE
    COST 100;

DROP TRIGGER IF EXISTS tbui_biencrit_t_lmulti ON biencrit_t;
CREATE TRIGGER tbui_biencrit_t_lmulti
  BEFORE INSERT OR UPDATE
  ON biencrit_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_biencrit_lmulti();


--drop view biencrit ;
----------------------- table prospect:

CREATE OR REPLACE FUNCTION f_set_prospect_search()
RETURNS trigger AS
$BODY$
DECLARE
BEGIN
    NEW.lsearch = lower(unaccent(concat(
                        NEW.lnom, ' ',
                        NEW.lprenom, ' ',
                        NEW.lnomsociete, ' ',
                        NEW.ltel, ' ',
                        NEW.lfax, ' ',
                        NEW.ltel2, ' ',
                        NEW.lgsm, ' ',
                        NEW.lemail, ' ',
                        NEW.lnomjf  -- removed comma here
    )));
    RETURN NEW;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;


DROP TRIGGER IF EXISTS tbui_prospect_t_lsearch ON prospect_t;

CREATE TRIGGER tbui_prospect_t_lsearch
  BEFORE INSERT OR UPDATE
  ON prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_prospect_search();

DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM pg_ts_config 
        WHERE cfgname = 'mydict'
    ) THEN
        CREATE TEXT SEARCH CONFIGURATION mydict ( COPY = simple );
    END IF;
END
$do$;



ALTER TEXT SEARCH CONFIGURATION mydict
  ALTER MAPPING FOR hword, hword_part, word
  WITH unaccent, simple;

DROP VIEW IF EXISTS biencrit CASCADE;
DROP VIEW IF EXISTS prospect CASCADE;


DO $do$
BEGIN
    -- Add bfollowup column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='bfollowup') THEN
        ALTER TABLE prospect_t ADD COLUMN bfollowup INT DEFAULT 0;
    END IF;

    -- Add ndetailsuivi column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='ndetailsuivi') THEN
        ALTER TABLE prospect_t ADD COLUMN ndetailsuivi INT DEFAULT 0;
    END IF;

    -- Add ndetailsuiviprec column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='ndetailsuiviprec') THEN
        ALTER TABLE prospect_t ADD COLUMN ndetailsuiviprec INT DEFAULT 0;
    END IF;

    -- Add nrisklevel column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='nrisklevel') THEN
        ALTER TABLE prospect_t ADD COLUMN nrisklevel INT;
    END IF;

    -- Add ddetailsuivi column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='ddetailsuivi') THEN
        ALTER TABLE prospect_t ADD COLUMN ddetailsuivi TIMESTAMP WITHOUT TIME ZONE;
    END IF;

    -- Add cpassport column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='cpassport') THEN
        ALTER TABLE prospect_t ADD COLUMN cpassport VARCHAR(50);
    END IF;

    -- Add cisopaysnat column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='cisopaysnat') THEN
        ALTER TABLE prospect_t ADD COLUMN cisopaysnat VARCHAR(3);
    END IF;

    -- Add cid column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='prospect_t' AND column_name='cid') THEN
        ALTER TABLE prospect_t ADD COLUMN cid VARCHAR(50);
    END IF;

END $do$;






      
--SELECT * FROM prospect_t WHERE to_tsvector('mydict', lsearch) @@ 'villers & guillaume';

------------------ index / bien

--ALTER TABLE bien_t ADD COLUMN lsearchfr text;



DO $do$
BEGIN
    IF (SELECT current_setting('server_version_num')::int) > 100000 THEN
        CREATE INDEX IF NOT EXISTS idx_bien_t_lsearchfr ON bien_t USING GIST (to_tsvector('mydict', lsearchfr));
    END IF;
END $do$;


CREATE OR REPLACE FUNCTION f_set_bien_search()
        RETURNS trigger AS
$BODY$

DECLARE

    ls_cagence VARCHAR(1000);
    ls_ldept VARCHAR(1000);
    ls_ltyp VARCHAR(1000);
    ls_bactif VARCHAR(1000);
    ls_lusername VARCHAR(1000);
    ls_letatfr VARCHAR(1000);
    ls_proprio VARCHAR(1000);
    ls_lregion VARCHAR(1000);
    ls_lenvironnement VARCHAR(1000);
    ls_ltypmandat VARCHAR(1000);
    ls_ldisponibilite VARCHAR(1000);
    ls_ladr VARCHAR(1000);
    ls_lcp VARCHAR(1000);
    ls_llocalite VARCHAR(1000);
    ls_lpays VARCHAR(1000);
    ls_bexportweb VARCHAR(1000);
    ls_lnatmandat VARCHAR(1000);
    ls_lcontactvisite VARCHAR(1000);
    ls_lnaturebien VARCHAR(1000);
    ls_netageappart VARCHAR(1000);
    ls_lplan VARCHAR(1000);
    ls_lvue_fr VARCHAR(1000);
    ls_lusercre VARCHAR(1000);
    ls_lusermod VARCHAR(1000);
    ls_qsdb VARCHAR(1000);
    ls_qgarages VARCHAR(1000);
    ls_lpiscine VARCHAR(1000);
    ls_ldetails  TEXT;
    ls_nomagence    VARCHAR(1000);
    ls_lchauff     VARCHAR(1000);
    ls_lvue        VARCHAR(1000);
    ls_lactif      VARCHAR(1000);
    ls_lnego        VARCHAR(1000);
    ls_lbiendepend     VARCHAR(1000);
    ls_nanneerenov VARCHAR(1000);
    ls_lchauf VARCHAR(1000);
    ls_lcomment VARCHAR(1000);
    ls_ltypcuisine VARCHAR(1000);
    ls_loriginebien VARCHAR(1000);
    --//detail ?
    --//htmlbien ?
    ls_nbiendepend VARCHAR(1000);
    ls_ndureemandat VARCHAR(1000);
    ls_netagetot VARCHAR(1000);
    ls_mrevcad VARCHAR(1000);
    ls_mcharge VARCHAR(1000);
    ls_mprecimmo VARCHAR(1000);
    ls_lstyle VARCHAR(1000);
    ls_cusercre VARCHAR(1000);
    ls_dcre VARCHAR(1000);
    ls_cusermod VARCHAR(1000);
    ls_dmod VARCHAR(1000);
    ls_cmandat VARCHAR(1000);
    ls_temp VARCHAR(1000);
    ls_lregion_meta VARCHAR(1000);

   ls_lannonceweb TEXT;

    li_bexclusivite integer ;

BEGIN

SELECT INTO ls_nomagence lnomagence FROM agence x WHERE NEW.cagence = x.cagence ;
SELECT INTO ls_ldept ldeptfr FROM dept x WHERE NEW.ndept = x.ndept ;
SELECT INTO ls_ltyp ltypfr FROM typ x WHERE NEW.ctyp = x.ctyp ;
SELECT INTO ls_letatfr letatfr FROM etat x WHERE NEW.cetat = x.cetat ;
SELECT INTO ls_proprio concat (lnom, ' ' , lprenom) FROM prospect WHERE NEW.nprospectpropr = prospect.nprospect ;
SELECT INTO ls_lregion lregionfr FROM region x WHERE NEW.cregion = x.cregion ;
SELECT INTO ls_lregion_meta regionmeta.lregionmetafr FROM region x JOIN regionmeta on x.cregionmeta = regionmeta.cregionmeta WHERE NEW.cregion = x.cregion ;
SELECT INTO ls_lenvironnement x.lenvironnementfr FROM environnement x WHERE NEW.cenvironnement = x.cenvironnement ;

SELECT INTO ls_ltypmandat x.ltypmandatfr FROM typmandat x WHERE NEW.ctypmandat = x.ctypmandat ;

SELECT INTO ls_ldisponibilite x.ldisponibilitefr FROM disponibilite x WHERE NEW.ndisponibilite = x.ndisponibilite ;
SELECT INTO ls_lpays x.lpaysfr FROM pays x WHERE NEW.cisopays = x.cisopays ;

SELECT INTO ls_lnatmandat x.lnatmandatfr FROM natmandat x WHERE NEW.nnatmandat = x.nnatmandat ;
SELECT INTO li_bexclusivite bexclusivite FROM natmandat x WHERE NEW.nnatmandat = x.nnatmandat ;


SELECT INTO ls_lnaturebien x.lnaturebienfr FROM naturebien x WHERE NEW.cnaturebien = x.cnaturebien ;
SELECT INTO ls_lvue x.lorientationfr FROM typorientation x WHERE NEW.lvue = x.corientation ;
SELECT INTO ls_lchauff x.lchauffr FROM typchauf x WHERE NEW.cchauf = x.cchauf ;
SELECT INTO ls_ltypcuisine x.ltypcuisinefr FROM typcuisine x WHERE NEW.ntypcuisine = x.ntypcuisine ;

SELECT INTO ls_loriginebien x.loriginebienfr FROM originebien x WHERE NEW.coriginebien = x.coriginebien ;

SELECT INTO ls_lactif x.lstatutbienfr FROM statutbien x WHERE NEW.bactif = x.bactif ;
SELECT INTO ls_lnego concat (lnom, ' ' , lprenom) FROM utilisateur WHERE NEW.lusername = utilisateur.lusername ;
SELECT INTO ls_lstyle lstylefr FROM style WHERE NEW.cstyle = style.cstyle ;
SELECT INTO ls_lusercre concat (lnom, ' ' , lprenom) FROM utilisateur WHERE NEW.cusercre = utilisateur.lusername ;
SELECT INTO ls_lusermod concat (lnom, ' ' , lprenom) FROM utilisateur WHERE NEW.cusermod = utilisateur.lusername ;
select into ls_ldetails string_agg (detail.ldetailfr, ', ') from detailbien join detail on detailbien.nbien = NEW.nbien ;
SELECT INTO ls_lpiscine ltyppiscinefr FROM typpiscine WHERE NEW.bpiscine = typpiscine.ntyppiscine ;
SELECT INTO ls_lbiendepend cbien FROM bien WHERE NEW.nbiendepend = bien.nbien ;

--SELECT INTO ls_lannonceweb lannonceweb FROM htmlbien x WHERE NEW.nbien = x.nbien and clangue = 'fr' limit 1 ;


IF li_bexclusivite = 1 THEN
    ls_temp = concat ( ls_temp , ' exclusivité exclusivite exclu' ) ;
END IF ;

--IF new.bexportweb = 1 THEN
--    ls_temp = concat ( ls_temp , ' publié site web' ) ;
--END IF ;
if new.qbureau = 1 Then
    ls_temp = concat ( ls_temp , ' bureau' ) ;
end if ;
if new.qbureau > 1 Then
    ls_temp = concat ( ls_temp , ' bureaux' ) ;
end if ;
if new.qsurfterrasse > 0 Then
    ls_temp = concat ( ls_temp , ' terrasse' ) ;
end if ;
--IF new.qsdd > 0 Then
--    ls_temp = concat ( ls_temp , ' douche salle eau' ) ;
--END IF ;
IF new.dtransaction IS NOT NULL THEN
    ls_temp = concat ( ls_temp , ' vendu' ) ;
END IF ;
if new.ddisponibilite < current_timestamp THEN
    ls_temp = concat ( ls_temp , ' disponible' ) ;
END IF ;
if new.bcle = 1 THEN
    ls_temp = concat ( ls_temp , ' clé agence' ) ;
END IF ;
if new.qparking >= 1 THEN
    ls_temp = concat ( ls_temp , ' ' , 'parking' ) ;
END IF ;
--IF new.qmurmitoy > 1 THEN
--    ls_temp = concat ( ls_temp , ' façades' ) ;
--END IF ;
if new.bneuf = 1 THEN
    ls_temp = concat ( ls_temp , ' projet neuf programme promotion' ) ;
END IF ;
if new.nbiendepend is not null THEN
    ls_temp = concat ( ls_temp , ' lot projet neuf programme promotion' ) ;
END IF ;
--if new.qchambres > 0 THEN
--    ls_temp = concat ( ls_temp , ' parking' ) ;
--END IF ;
IF new.qgarages = 1 THEN
    ls_temp = concat ( ls_temp , ' ', new.qgarages , ' garage' ) ;
END IF ;
if new.qgarages > 1 THEN
    ls_temp = concat ( ls_temp , ' ',  new.qgarages , 'garages' ) ;
END IF ;

IF new.qchambres = 1 THEN
    ls_temp = concat ( ls_temp , ' ', new.qchambres , ' chambre' ) ;
END IF ;
if new.qchambres > 1 THEN
    ls_temp = concat ( ls_temp , ' ',  new.qchambres , 'chambres' ) ;
END IF ;

if new.qpieces = 1 THEN
    ls_temp = concat ( ls_temp ,  ' ', new.qpieces, 'pièce' ) ;
END IF ;
if new.qpieces > 1 THEN
    ls_temp = concat ( ls_temp ,  ' ', new.qpieces, 'pièces' ) ;
END IF ;


IF new.netageappart= '0' THEN
    ls_temp = concat ( ls_temp ,  ' ', 'rez de chaussée' ) ;
END IF;

--new.chambres + 'chambres'
--new.qpieces   + 'chambres'

NEW.lsearchfr = unaccent (concat (
ls_temp ,
NEW.nbien      , ' ' ,
NEW.cagence      , ' ' ,
ls_nomagence , ' ' ,
NEW.cbien   , ' ' ,
NEW.mprix  , ' ' ,
NEW.ndept  , ' ' ,
ls_ldept  , ' ' ,
ls_ltyp    , ' ' ,
new.nannee , ' ' ,
ls_letatfr  , ' ' ,
ls_proprio  , ' ' ,
ls_lregion   , ' ' ,
ls_lregion_meta   , ' ' ,
ls_lenvironnement   , ' ' ,
ls_ltypmandat   , ' ' ,
ls_ldisponibilite  , ' ' ,
new.ladr     , ' ' ,
new.lcp            , ' ' ,
new.llocalite     , ' ' ,
ls_lpays    , ' ' ,
new.lcontactvisite , ' ' ,
new.cmandat , ' ' ,
ls_lnaturebien , ' ' ,
ls_lnatmandat      , ' ' ,
new.lcontactvisite   , ' ' ,
ls_lnaturebien     , ' ' ,
ls_lvue              , ' ' ,
ls_lchauff    , ' ' ,
ls_lcomment    , ' ' ,
ls_ltypcuisine    , ' ' ,
ls_lactif    , ' ' ,
ls_lusername      , ' ' ,
ls_lstyle          , ' ' ,
ls_lusercre        , ' ' ,
ls_lusermod      , ' ' ,
new.cmandat         , ' ' ,
new.mprixnet       , ' ' ,
ls_loriginebien          , ' ' ,
ls_lbiendepend           , ' ' ,
ls_lpiscine         , ' ' ,
ls_nbiendepend     , ' ' ,
new.cdevise      , ' ' ,
ls_lannonceweb
)) ;

--NEW.lsearch = 'lklklklk' ;

RETURN NEW;
                END; $BODY$
        LANGUAGE plpgsql VOLATILE
        COST 100;


DROP TRIGGER IF EXISTS tbui_bien_t_lsearch ON bien_t;
CREATE TRIGGER tbui_bien_t_lsearch
  BEFORE INSERT OR UPDATE
  ON bien_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_bien_search();


DO $do$
BEGIN
    -- Add lsearchfr column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='offre_t' AND column_name='lsearchfr') THEN
        ALTER TABLE offre_t ADD COLUMN lsearchfr TEXT;
    END IF;

    -- Add lsearchen column if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='offre_t' AND column_name='lsearchen') THEN
        ALTER TABLE offre_t ADD COLUMN lsearchen TEXT;
    END IF;

END $do$;


CREATE INDEX ON offre_t USING GIST (to_tsvector('mydict', lsearchfr));
CREATE INDEX ON offre_t USING GIST (to_tsvector('mydict', lsearchen));


CREATE OR REPLACE FUNCTION f_set_offre_search()
        RETURNS trigger AS
$BODY$

DECLARE

ls_lstatut_fr VARCHAR(1000);
ls_lstatut_en VARCHAR(1000);
ls_lnego VARCHAR(1000);
ls_lnotairevendeur VARCHAR(1000);
ls_lnotaireacquereur VARCHAR(1000);
ls_bien VARCHAR(1000);
ls_proprio VARCHAR(1000);
ls_nomagence VARCHAR(1000);
ls_acquereur VARCHAR(1000);


BEGIN

SELECT INTO ls_lstatut_fr lstatutfr FROM statutoffre x WHERE NEW.cstatut = x.cstatut ;
SELECT INTO ls_lstatut_en lstatuten FROM statutoffre x WHERE NEW.cstatut = x.cstatut ;
SELECT INTO ls_lnego concat (lnom, ' ' , lprenom) FROM utilisateur WHERE NEW.lusername = utilisateur.lusername ;

SELECT INTO ls_acquereur concat (lnom, ' ' , lprenom) FROM prospect WHERE NEW.nprospect = prospect.nprospect ;
SELECT INTO ls_proprio concat (lnom, ' ' , lprenom) FROM bien , prospect WHERE bien.nbien = NEW.nbien AND bien.nprospectpropr = prospect.nprospect ;

--SELECT INTO ls_lnotairevendeur concat (lnom, ' ' , lprenom) FROM prospect WHERE NEW.nnotairevendeur = prospect.nprospect ;
--SELECT INTO ls_lnotaireacquereur concat (lnom, ' ' , lprenom) FROM prospect WHERE NEW.nnotaireacquereur = prospect.nprospect ;
SELECT INTO ls_bien concat (cbien, ' ' , ladr, ' ' , llocalite, ' ', typ.ltypfr) FROM bien JOIN typ ON typ.ctyp = bien.ctyp WHERE NEW.nbien = bien.nbien ;
SELECT INTO ls_nomagence lnomagence FROM agence x WHERE NEW.cagence = x.cagence ;


--IF li_bexclusivite = 1 THEN
--   ls_temp = concat ( ls_temp , ' exclusivité exclusivite exclu' ) ;
--END IF ;

NEW.lsearchfr = concat (
    NEW.coffre, ' '      ,
     ls_lstatut_fr, ' ' ,
    NEW.cfacture      , ' ' ,
    NEW.lusername, ' ' ,
    ls_lnego , ' ' ,
    ls_lnotairevendeur, ' ' ,
    ls_lnotaireacquereur, ' ' ,
    NEW.lcomment   , ' ' ,
    ls_bien  , ' ' ,
    ls_proprio    , ' ' ,
    ls_acquereur    , ' ' ,
    ls_nomagence  , ' ' ,
    NEW.cdevise   , ' '
    ) ;

NEW.lsearchen = unaccent (concat (
    NEW.coffre, ' '      ,
     ls_lstatut_en, ' ' ,
    NEW.cfacture      , ' ' ,
    ls_lnego , ' ' ,
    ls_lnotairevendeur, ' ' ,
    ls_lnotaireacquereur, ' ' ,
    NEW.lcomment   , ' ' ,
    ls_bien  , ' ' ,
    ls_proprio    , ' ' ,
    ls_nomagence  , ' ' ,
    NEW.cdevise   , ' '
    ) ) ;

RETURN NEW;
        END; $BODY$
LANGUAGE plpgsql VOLATILE
COST 100;


DROP TRIGGER IF EXISTS tbui_offre_t_lsearch ON offre_t;

CREATE TRIGGER tbui_offre_t_lsearch
  BEFORE INSERT OR UPDATE
  ON offre_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_offre_search();




CREATE OR REPLACE FUNCTION f_set_nnummandat()
  RETURNS trigger AS
$BODY$
  DECLARE
    ll_nnummandat integer ;
 BEGIN

   SELECT INTO ll_nnummandat max(mandat_t.nnummandat) FROM mandat_t WHERE mandat_t.cagence = (select cagencemandat from agence where agence.cagence = new.cagence) ;

   IF ll_nnummandat IS NULL THEN
      --SELECT max(nnummandat) INTO ll_nnummandat FROM mandat_t WHERE cagence = (select cagencemandat from agence where agence = new.cagence) ;
      select INTO ll_nnummandat nnummandatdebut
      from agence
      where agence.cagence = (select agence.cagencemandat from agence where agence.cagence = new.cagence);

        IF ll_nnummandat IS NULL THEN
		--raise exception error
		RAISE EXCEPTION  'Le nouveau numéro de mandat_t ne peut être déterminé. Veuillez vérifier les paramètres de numérotaiton du registre des mandats'   ;

        ELSE
		NEW.nnummandat = ll_nnummandat + 1;
	END IF ;

   ELSE
       NEW.nnummandat = ll_nnummandat + 1;
   END IF ;

  RETURN NEW;

END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

ALTER FUNCTION f_set_nnummandat()
  OWNER TO admin;




CREATE OR REPLACE FUNCTION f_update_bien_mandat()
  RETURNS trigger AS
$BODY$
DECLARE
 --cpays   character varying(3);
BEGIN
        IF (NEW.nbien IS NOT NULL AND NEW.nbien > 0) THEN

		 UPDATE bien SET (cmandat , dmandat, dexpmandat, nnatmandat) =
		 (select nmandat::varchar , ddebmandat , dfinmandat , nnatmandat
		 from mandat_t
		 where mandat_t.nbien = NEW.nbien order by ddebmandat DESC limit 1);

        END IF ;

        RETURN NEW;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION f_update_bien_mandat()
  OWNER TO admin;




DROP VIEW IF EXISTS preference CASCADE;
CREATE OR REPLACE VIEW preference AS
     SELECT preference_t.id,
        preference_t.cagence,
        preference_t.cinternetsite,
        preference_t.ndelairelance,
        preference_t.nemailntemplate,
        preference_t.ncourrierntemplate,
        preference_t.ncatprospectnotaire,
        preference_t.dlastsend,
        preference_t.lftpserver,
        preference_t.lftpusername,
        preference_t.lftppasswd,
        preference_t.njpgquality,
        preference_t.njpgprogressive,
        preference_t.nphotomaxh,
        preference_t.nphotomaxw,
        preference_t.ntyprelationrelance,
        preference_t.nshadowlevel,
        preference_t.nphotomedmaxh,
        preference_t.nphotomedmaxw,
        preference_t.nthumbmaxh,
        preference_t.nthumbmaxw,
        preference_t.lftpsubdir,
        preference_t.nprospectnotaire,
        preference_t.nprospectproprio,
        preference_t.nprospectprio,
        preference_t.nprospectagence,
        preference_t.cinternetsiteactivimmo,
        preference_t.nprospectprospect,
        preference_t.nallowusershare,
        preference_t.qnbjourhisto,
        preference_t.ndbversion,
        preference_t.nsilentupload,
        preference_t.bprixtoprixnet,
        preference_t.bwebupdatesingle,
        preference_t.qcss,
        preference_t.limportexportdir,
        preference_t.dlastrunbackup,
        preference_t.ntyprelationssp,
        preference_t.ntyprelationacte,
        preference_t.ntyprelationactivite,
        preference_t.nprospectlead,
        preference_t.ntyprelationemail,
        preference_t.ntyprelationvisite
      FROM preference_t
      WHERE (EXISTS ( SELECT NULL::unknown AS unknown
               FROM utilisateuragence
              WHERE utilisateuragence.bprincipale = 1 AND utilisateuragence.lusername::name = "current_user"() AND (preference_t.cagence::text = utilisateuragence.cagence::text OR preference_t.cagence::text = ''::text OR preference_t.cagence IS NULL)));







DO $do$
BEGIN
	update prospectbien_t set bconfirmmailsent = 0 where bconfirmmailsent is null ;
	update prospectbien_t set blvisitemailsent = 0 where blvisitemailsent is null ;

    -- Check and add columns for prospectbien_t bnewsauto bconfirmmailsent bconfirmmailsent 
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'bconfirmmailsent') THEN
		
        ALTER TABLE prospectbien_t ADD COLUMN bconfirmmailsent integer DEFAULT 0 NOT NULL;
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'dconfirmmailsmssent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN dconfirmmailsmssent timestamp without time zone;
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'blvisitemailsent') THEN
		
        ALTER TABLE prospectbien_t ADD COLUMN blvisitemailsent integer DEFAULT 0 NOT NULL;
    END IF;

    -- Check and add columns for biendef
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'nprogramme') THEN
        ALTER TABLE biendef ADD COLUMN nprogramme int;
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'bpiscine') THEN
        ALTER TABLE biendef ADD COLUMN bpiscine int DEFAULT 0;
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'qmurmitoy') THEN
        ALTER TABLE biendef ADD COLUMN qmurmitoy int;
    END IF;

    -- Handling multiple identical operations
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'portailagence' AND column_name = 'busepic') THEN
        ALTER TABLE portailagence ADD COLUMN busepic integer DEFAULT 0;
    END IF;

    -- Check and add indices
    IF (SELECT current_setting('server_version_num')::int) > 100000 THEN
        CREATE INDEX IF NOT EXISTS idx_biencrit_lsearchfr ON biencrit_t USING GIST (to_tsvector('mydict', lsearchfr));
    END IF;

    IF (SELECT current_setting('server_version_num')::int) > 100000 THEN
        CREATE INDEX IF NOT EXISTS idx_biencrit_lsearchen ON biencrit_t USING GIST (to_tsvector('mydict', lsearchen));
    END IF;

    -- Set default and NOT NULL constraints where needed
    --ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET DEFAULT 0;
   -- ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET NOT NULL;

    -- More conditional checks and operations for other tables
    -- Due to the length, you would repeat similar blocks for each operation from your list
    -- Make sure to check the existence of indexes, columns, and constraints as shown in previous examples
    -- Use additional IF NOT EXISTS and SELECT FROM information_schema or pg_catalog as needed

    -- Note: Some operations, like 'ALTER COLUMN ... SET COMPRESSION' might not require condition checks if they are safe to rerun

   -- Add column bconfirmmailsent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'bconfirmmailsent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN bconfirmmailsent integer;
        ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET DEFAULT 0;
        ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET NOT NULL;
    END IF;

    -- If the column exists but does not have the default value or NOT NULL constraint, update it
    IF EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'bconfirmmailsent') THEN
        ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET DEFAULT 0;
        ALTER TABLE prospectbien_t ALTER COLUMN bconfirmmailsent SET NOT NULL;
    END IF;

    -- Add column dconfirmmailsmssent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'dconfirmmailsmssent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN dconfirmmailsmssent timestamp without time zone;
    END IF;

    -- Add column dconfirmmailsent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'dconfirmmailsent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN dconfirmmailsent timestamp without time zone;
    END IF;

    -- Add column nprogramme to biendef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'nprogramme') THEN
        ALTER TABLE biendef ADD COLUMN nprogramme int;
    END IF;

    -- Add column bpiscine to biendef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'bpiscine') THEN
        ALTER TABLE biendef ADD COLUMN bpiscine int DEFAULT 0;
    END IF;

    -- Add column qmurmitoy to biendef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'qmurmitoy') THEN
        ALTER TABLE biendef ADD COLUMN qmurmitoy int;
    END IF;

    -- Add column coriginebien to biendef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'coriginebien') THEN
        ALTER TABLE biendef ADD COLUMN coriginebien varchar(10);
    END IF;

    -- Add column tcommissionvendeur to biendef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biendef' AND column_name = 'tcommissionvendeur') THEN
        ALTER TABLE biendef ADD COLUMN tcommissionvendeur int;
    END IF;

    -- Add column corigineprospect to prospectdef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectdef' AND column_name = 'corigineprospect') THEN
        ALTER TABLE prospectdef ADD COLUMN corigineprospect varchar(10);
    END IF;

    -- Add column lusername to prospectdef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectdef' AND column_name = 'lusername') THEN
        ALTER TABLE prospectdef ADD COLUMN lusername varchar(10);
    END IF;

    -- Add column bnewsauto to prospectdef if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectdef' AND column_name = 'bnewsauto') THEN
        ALTER TABLE prospectdef ADD COLUMN bnewsauto int DEFAULT 1;
    END IF;

    -- Add column bsmsauto to prospectdef if it does not exist:
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectdef' AND column_name = 'bsmsauto') THEN
        ALTER TABLE prospectdef ADD COLUMN bsmsauto int DEFAULT 0;
    END IF;
    UPDATE prospectdef SET bsmsauto = 0 WHERE bsmsauto IS NULL;

    -- Add column blvisitemailsent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'blvisitemailsent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN blvisitemailsent integer DEFAULT 0;
    END IF;


    -- Add column cdevise to typmandatmeta if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typmandatmeta' AND column_name = 'cdevise') THEN
        ALTER TABLE typmandatmeta ADD COLUMN cdevise character varying(3) DEFAULT 'EUR';
    END IF;

    -- Add column busepic to portailagence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'portailagence' AND column_name = 'busepic') THEN
        ALTER TABLE portailagence ADD COLUMN busepic integer DEFAULT 0;
    END IF;
    UPDATE portailagence SET busepic = 0 WHERE busepic IS NULL;

    -- Add column cisopaysnat to prospect_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospect_t' AND column_name = 'cisopaysnat') THEN
        ALTER TABLE prospect_t ADD COLUMN cisopaysnat character varying(3);
    END IF;

    -- Add column cid to prospect_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospect_t' AND column_name = 'cid') THEN
        ALTER TABLE prospect_t ADD COLUMN cid character varying(50);
    END IF;

    -- Add column cpassport to prospect_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospect_t' AND column_name = 'cpassport') THEN
        ALTER TABLE prospect_t ADD COLUMN cpassport character varying(50);
    END IF;

    -- Add column nrisklevel to prospect_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospect_t' AND column_name = 'nrisklevel') THEN
        ALTER TABLE prospect_t ADD COLUMN nrisklevel integer;
    END IF;

    -- Alter column brendezvous in typrelation to set default if it does not exist
    ALTER TABLE typrelation ALTER COLUMN brendezvous SET DEFAULT 0;

    -- Add column dmandat to bien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'bien_t' AND column_name = 'dmandat') THEN
        ALTER TABLE bien_t ADD COLUMN dmandat date;
    END IF;

    -- Add column lstatutmandat to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'lstatutmandat') THEN
        ALTER TABLE mandat_t ADD COLUMN lstatutmandat character varying(250);
    END IF;

    -- Add column lmandants to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'lmandants') THEN
        ALTER TABLE mandat_t ADD COLUMN lmandants text;
    END IF;

    -- Add column cisopaysbien to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'cisopaysbien') THEN
        ALTER TABLE mandat_t ADD COLUMN cisopaysbien character varying(3);
    END IF;

    -- Add column nnummandat to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'nnummandat') THEN
        ALTER TABLE mandat_t ADD COLUMN nnummandat integer NOT NULL;
    END IF;

    -- Add column ltypbien to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'ltypbien') THEN
        ALTER TABLE mandat_t ADD COLUMN ltypbien character varying(100);
    END IF;

    -- Add column nnumrepertoire to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'nnumrepertoire') THEN
        ALTER TABLE mandat_t ADD COLUMN nnumrepertoire integer;
    END IF;

    -- Add column nbmoismandat to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'nbmoismandat') THEN
        ALTER TABLE params ADD COLUMN nbmoismandat integer DEFAULT 12;
    END IF;

    -- Add column nbjoursagenda to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'nbjoursagenda') THEN
        ALTER TABLE params ADD COLUMN nbjoursagenda integer DEFAULT 6;
    END IF;


    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'nheuredebutagenda') THEN
        ALTER TABLE params ADD COLUMN nheuredebutagenda integer DEFAULT 9;
    END IF;

    -- Add column nheurefinagenda to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'nheurefinagenda') THEN
        ALTER TABLE params ADD COLUMN nheurefinagenda integer DEFAULT 20;
    END IF;

    -- Add column bregmandat to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'bregmandat') THEN
        ALTER TABLE params ADD COLUMN bregmandat integer;
    END IF;

    -- Set default for column bregmandat in params
    ALTER TABLE params ALTER COLUMN bregmandat SET DEFAULT 0;

    -- Add column nnummandat to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'nnummandat') THEN
        ALTER TABLE params ADD COLUMN nnummandat integer;
    END IF;

    -- Set default for column nnummandat in params
    ALTER TABLE params ALTER COLUMN nnummandat SET DEFAULT 0;

    -- Add column clangue_std to langue if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'langue' AND column_name = 'clangue_std') THEN
        ALTER TABLE langue ADD COLUMN clangue_std character varying(2);
    END IF;

    -- Set default for column clangue_std in langue
    ALTER TABLE langue ALTER COLUMN clangue_std SET DEFAULT 'en';

    -- Add column nportailagence to portailagence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'portailagence' AND column_name = 'nportailagence') THEN
        ALTER TABLE portailagence ADD COLUMN nportailagence SERIAL;
    END IF;

    -- Drop existing primary key constraint pk_portailagence in portailagence
    ALTER TABLE portailagence DROP CONSTRAINT IF EXISTS pk_portailagence;

    -- Add primary key constraint pk_portailagence in portailagence
    ALTER TABLE portailagence ADD CONSTRAINT pk_portailagence PRIMARY KEY(nportailagence);

    -- Add column bcommonlogo to params if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'params' AND column_name = 'bcommonlogo') THEN
        ALTER TABLE params ADD COLUMN bcommonlogo integer DEFAULT 1;
    END IF;

    -- Add column bisactive to statutbien if it does not exist 
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'statutbien' AND column_name = 'bisactive') THEN
        ALTER TABLE statutbien ADD COLUMN bisactive smallint DEFAULT 1 NOT NULL;
    END IF;


    -- Add column cdevisecharge to bien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'bien_t' AND column_name = 'cdevisecharge') THEN
        ALTER TABLE bien_t ADD COLUMN cdevisecharge character varying(3);
    END IF;

    -- Add column llieurdv to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'llieurdv') THEN
        ALTER TABLE prospectbien_t ADD COLUMN llieurdv character varying(200);
    END IF;

    -- Add column bconfirmmailsent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'bconfirmmailsent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN bconfirmmailsent integer;
    END IF;

    -- Add column dconfirmmailsmssent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'dconfirmmailsmssent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN dconfirmmailsmssent timestamp without time zone;
    END IF;

    -- Add column blvisitemailsent to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'blvisitemailsent') THEN
        ALTER TABLE prospectbien_t ADD COLUMN blvisitemailsent integer;
        ALTER TABLE prospectbien_t ALTER COLUMN blvisitemailsent SET NOT NULL;
        ALTER TABLE prospectbien_t ALTER COLUMN blvisitemailsent SET DEFAULT 0;
    END IF;


    -- Check if the table mandat_t does not exist, then create it
    

            IF NOT EXISTS (SELECT FROM pg_catalog.pg_tables WHERE schemaname = 'public' AND tablename  = 'mandat_t') THEN
                CREATE TABLE public.mandat_t
                (
                  nmandat integer NOT NULL DEFAULT nextval('mandat_nmandat_seq'::regclass),
                  nbien integer,
                  ddebmandat timestamp with time zone,
                  dfinmandat timestamp with time zone,
                  ltypmandat character varying(100),
                  lnatmandat character varying(100),
                  cstatutmandat character varying(1) DEFAULT 'r'::character varying,
                  ltypxx character varying(50),
                  ladrbien character varying(200),
                  lcpbien character varying(20),
                  llocalitebien character varying(100),
                  cagence character varying(10),
                  lusername character varying(250),
                  lstatutmandat character varying(250),
                  lmandants text,
                  cisopaysbien character varying(3),
                  nnummandat integer NOT NULL,
                  ltypbien character varying(100),
                  nnumrepertoire integer,
                  ndureemois integer,
                  ndureetrmois integer,
                  dcre timestamp with time zone DEFAULT now(),
                  cusercre character varying(10) DEFAULT current_user,
                  cusermod character varying(10) DEFAULT current_user,
                  dmod timestamp with time zone DEFAULT now(),
                  CONSTRAINT pk_nmandat_t PRIMARY KEY (nmandat),
                  CONSTRAINT fk_mandat_t_cagence FOREIGN KEY (cagence)
                      REFERENCES agence (cagence) MATCH SIMPLE
                      ON UPDATE CASCADE ON DELETE RESTRICT,
                  CONSTRAINT unique_index_mandat UNIQUE (nnummandat, cagence)
                )
                WITH (
                  OIDS=FALSE
                );
            END IF;
 

    -- Add column lobservations to mandat_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'mandat_t' AND column_name = 'lobservations') THEN
        ALTER TABLE mandat_t ADD COLUMN lobservations text;
    END IF;

    -- Add column lsiren to agence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agence' AND column_name = 'lsiren') THEN
        ALTER TABLE agence ADD COLUMN lsiren character varying(50);
    END IF;

    -- Add column ldisplayname to tpl if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'tpl' AND column_name = 'ldisplayname') THEN
        ALTER TABLE tpl ADD COLUMN ldisplayname character varying(250);
    END IF;

    -- Add column bsendmail_alert to todo if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'todo' AND column_name = 'bsendmail_alert') THEN
        ALTER TABLE todo ADD COLUMN bsendmail_alert integer DEFAULT 0;
    END IF;

    -- Add column dsendmail_alert to todo if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'todo' AND column_name = 'dsendmail_alert') THEN
        ALTER TABLE todo ADD COLUMN dsendmail_alert timestamp;
    END IF;

    -- Add column breport to detail if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'detail' AND column_name = 'breport') THEN
        ALTER TABLE detail ADD COLUMN breport smallint DEFAULT 0;
        ALTER TABLE detail ALTER COLUMN breport SET NOT NULL;
        ALTER TABLE detail ALTER COLUMN breport SET DEFAULT 0;
    END IF;

    -- Add column breport to typdetail if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typdetail' AND column_name = 'breport') THEN
        ALTER TABLE typdetail ADD COLUMN breport smallint DEFAULT 0;
        ALTER TABLE typdetail ALTER COLUMN breport SET NOT NULL;
    END IF;


-- Add column lannonceseo to htmlbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'htmlbien_t' AND column_name = 'lannonceseo') THEN
        ALTER TABLE htmlbien_t ADD COLUMN lannonceseo text;
    END IF;

    -- Set default and not null for column nrating in prospect_t
    ALTER TABLE prospect_t ALTER COLUMN nrating SET DEFAULT 0;
    UPDATE prospect_t set nrating = 0 where nrating is null;
    ALTER TABLE prospect_t ALTER COLUMN nrating SET NOT NULL;

    -- Set default and not null for columns bsmsauto and bnewsauto in prospect_t
    ALTER TABLE prospect_t ALTER COLUMN bsmsauto SET DEFAULT 0;
    ALTER TABLE prospect_t ALTER COLUMN bnewsauto SET DEFAULT 0;
    UPDATE prospect_t set bsmsauto = 0 where bsmsauto is null;
    UPDATE prospect_t set bnewsauto = 0 where bnewsauto is null;
    ALTER TABLE prospect_t ALTER COLUMN bsmsauto SET NOT NULL;
    ALTER TABLE prospect_t ALTER COLUMN bnewsauto SET NOT NULL;

    -- Add column cdevise to comnego if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'comnego' AND column_name = 'cdevise') THEN
        ALTER TABLE comnego ADD COLUMN cdevise character varying(3) DEFAULT 'EUR';
    END IF;

    -- Add column breport to typdetail if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typdetail' AND column_name = 'breport') THEN
        ALTER TABLE typdetail ADD COLUMN breport smallint DEFAULT 0;
    END IF;

    -- Add column nprospectdepend to prospect_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospect_t' AND column_name = 'nprospectdepend') THEN
        ALTER TABLE prospect_t ADD COLUMN nprospectdepend integer;
    END IF;

    -- Drop not null constraint for column nprospectdepend in prospect_t
    ALTER TABLE prospect_t ALTER COLUMN nprospectdepend DROP NOT NULL;

    -- Add primary keys

        IF NOT EXISTS (SELECT FROM pg_constraint WHERE conrelid = 'commoffre'::regclass AND contype = 'p') THEN
            ALTER TABLE commoffre ADD PRIMARY KEY (ncommission);
        END IF;

    IF NOT EXISTS (SELECT FROM pg_constraint WHERE conrelid = 'pige'::regclass AND contype = 'p') THEN
        ALTER TABLE pige ADD PRIMARY KEY (npige);
    END IF;

    -- Drop default for column ncategorie in cat
    ALTER TABLE cat ALTER COLUMN ncategorie DROP DEFAULT;


    -- Add column l_gmail_token to utilisateur if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'l_gmail_token') THEN
        ALTER TABLE utilisateur ADD COLUMN l_gmail_token text;
    END IF;

    -- Add column l_gmail_rtoken to utilisateur if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'l_gmail_rtoken') THEN
        ALTER TABLE utilisateur ADD COLUMN l_gmail_rtoken text;
    END IF;

    -- Set default and not null for column bactif in prospectdef
    ALTER TABLE prospectdef ALTER COLUMN bactif SET DEFAULT 1;
    ALTER TABLE prospectdef ALTER COLUMN bactif SET NOT NULL;

    -- Add column dreiteration to offre_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'offre_t' AND column_name = 'dreiteration') THEN
        ALTER TABLE offre_t ADD COLUMN dreiteration date;
    END IF;

    -- Add columns for SMTP settings to utilisateur if they do not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'lsmtp_host') THEN
        ALTER TABLE utilisateur ADD COLUMN lsmtp_host character varying(100);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'bsmtp_auth') THEN
        ALTER TABLE utilisateur ADD COLUMN bsmtp_auth character varying(10);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'bsmtp_autotls') THEN
        ALTER TABLE utilisateur ADD COLUMN bsmtp_autotls character varying(10);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'lsmtp_user') THEN
        ALTER TABLE utilisateur ADD COLUMN lsmtp_user character varying(200);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'lsmtp_pass') THEN
        ALTER TABLE utilisateur ADD COLUMN lsmtp_pass character varying(200);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'lsmtp_encryption_type') THEN
        ALTER TABLE utilisateur ADD COLUMN lsmtp_encryption_type character varying(10);
    END IF;

    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'nsmtp_port') THEN
        ALTER TABLE utilisateur ADD COLUMN nsmtp_port integer;
    END IF;

    -- Drop not null constraint for column mprix1max in biencrit_t
  
        IF EXISTS (
            SELECT 1
            FROM information_schema.columns
            WHERE table_name = 'biencrit_t'
            AND column_name = 'mprix1max'
            AND is_nullable = 'NO'
        ) THEN
            ALTER TABLE public.biencrit_t ALTER COLUMN mprix1max DROP NOT NULL;
        END IF;
  

    -- Add column badderpinadverts to agence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agence' AND column_name = 'badderpinadverts') THEN
        ALTER TABLE agence ADD COLUMN badderpinadverts integer DEFAULT 0;
    END IF;

    -- Add column nhtmlpageref and foreign key constraint to htmlpage if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'htmlpage' AND column_name = 'nhtmlpageref') THEN
        ALTER TABLE htmlpage ADD COLUMN nhtmlpageref INT DEFAULT NULL;
        ALTER TABLE htmlpage ADD CONSTRAINT htmlpage_unique_nhtmlpageref UNIQUE (nhtmlpageref);
        -- a du être dsactivée suite a message d'erreur
        --
        --ALTER TABLE htmlpage ADD CONSTRAINT fk_htmlpage_nhtmlpageref FOREIGN KEY (nhtmlpageref) REFERENCES htmlpage(nhtmlpage) ON DELETE SET NULL ON UPDATE CASCADE;
    END IF;


    -- Create indices on biencrit_t if they do not exist
    IF (SELECT current_setting('server_version_num')::int) > 100000 THEN
        IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'idx_biencrit_lsearchfr' AND relkind = 'i') THEN
            CREATE INDEX idx_biencrit_lsearchfr ON biencrit_t USING GIST (to_tsvector('mydict', lsearchfr));
        END IF;

        IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'idx_biencrit_lsearchen' AND relkind = 'i') THEN
            CREATE INDEX idx_biencrit_lsearchen ON biencrit_t USING GIST (to_tsvector('mydict', lsearchen));
        END IF;
    END IF;

END $do$;

update typrelation set brendezvous=0 where brendezvous is null ;
UPDATE typmandatmeta set cdevise ='MUR' where ctypmandatmeta in ('l','v');
UPDATE typmandatmeta set cdevise ='EUR' where ctypmandatmeta not in ('l','v');
update typmeta set ctypmetameta = 'A' where ltypmetafr ilike '%appartement%' ;
update typmeta set ctypmetameta = 'M' where ltypmetafr ilike '%maison%' ;
update typmeta set ctypmetameta = 'M' where ltypmetafr ilike '%demeure%' ;
update typmeta set ctypmetameta = 'M' where ltypmetafr ilike '%château%' ;
update typmeta set ctypmetameta = 'C' where ltypmetafr ilike '%commerce%' ;
update typmeta set ctypmetameta = 'C' where ltypmetafr ilike '%bureau%' ;
update typmeta set ctypmetameta = 'T' where ltypmetafr ilike '%terrain%' ;


--alter table detail add ltypmetametas varchar (10) default 'M,A,C,T' ;
--alter table detail add ltypmetametas varchar (10) default 'M,A,C,T' ;

--alter table detail add ctypmandatmetas integer default 1 ;
--alter table detail add ctypmetametas integer default 1 ;
--alter table detail add bcommerce integer default 1 ;
--alter table detail add bterrain integer default 1 ;

INSERT INTO statutoffre (cstatut, lstatutfr, lstatuten, lstatutnl, lstatutde, ncouleurtexte, nordre, cusercre, dcre, cusermod, dmod, lstatutes, lstatutit, lstatutsk, lstatutcs, lstatutru, lstatutzh, bactif, ccouleurtexte, binclure, ccouleur, bsignature, ncouleur) VALUES ('acceptee', 'Offre acceptée', 'Accepted', NULL, NULL, 0, 3, NULL, NULL, 'admin', '2018-03-21', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '#000000', 1, NULL, 1, NULL) ON CONFLICT (cstatut) DO NOTHING;;
INSERT INTO statutoffre (cstatut, lstatutfr, lstatuten, lstatutnl, lstatutde, ncouleurtexte, nordre, cusercre, dcre, cusermod, dmod, lstatutes, lstatutit, lstatutsk, lstatutcs, lstatutru, lstatutzh, bactif, ccouleurtexte, binclure, ccouleur, bsignature, ncouleur) VALUES ('acte', 'Acte signé', 'Act Signed', NULL, NULL, 0, 5, NULL, NULL, 'admin', '2018-03-21', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '#000000', 1, NULL, 1, NULL)ON CONFLICT (cstatut) DO NOTHING;;
INSERT INTO statutoffre (cstatut, lstatutfr, lstatuten, lstatutnl, lstatutde, ncouleurtexte, nordre, cusercre, dcre, cusermod, dmod, lstatutes, lstatutit, lstatutsk, lstatutcs, lstatutru, lstatutzh, bactif, ccouleurtexte, binclure, ccouleur, bsignature, ncouleur) VALUES ('ssp', 'Compromis signé', 'Compromise signed', NULL, NULL, 0, 4, NULL, NULL, 'admin', '2018-03-21', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '#000000', 1, NULL, 1, NULL)ON CONFLICT (cstatut) DO NOTHING;;
INSERT INTO statutoffre (cstatut, lstatutfr, lstatuten, lstatutnl, lstatutde, ncouleurtexte, nordre, cusercre, dcre, cusermod, dmod, lstatutes, lstatutit, lstatutsk, lstatutcs, lstatutru, lstatutzh, bactif, ccouleurtexte, binclure, ccouleur, bsignature, ncouleur) VALUES ('offre', 'Sous offre', 'Under offer', NULL, NULL, 0, 1, NULL, NULL, 'admin', '2018-03-21', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '#000000', 1, NULL, 0, NULL) ON CONFLICT (cstatut) DO NOTHING;;
INSERT INTO statutoffre (cstatut, lstatutfr, lstatuten, lstatutnl, lstatutde, ncouleurtexte, nordre, cusercre, dcre, cusermod, dmod, lstatutes, lstatutit, lstatutsk, lstatutcs, lstatutru, lstatutzh, bactif, ccouleurtexte, binclure, ccouleur, bsignature, ncouleur) VALUES ('refusee', 'Offre refusée', 'Refused', NULL, NULL, 0, 2, NULL, NULL, 'admin', '2018-03-21', NULL, NULL, NULL, NULL, NULL, NULL, NULL, '#000000', 1, NULL, 0, NULL) ON CONFLICT (cstatut) DO NOTHING;;


--DROP VIEW prospect CASCADE ;
--CREATE OR REPLACE VIEW prospect AS
--     SELECT prospect_t.*
--       FROM prospect_t
--      WHERE (prospect_t.ncategorie = ANY (ARRAY[0, 10])) OR
--            (prospect_t.ncategorie = 2 and prospect_t.cagence in (select cagence from utilisateuragence where utilisateuragence.bselectproprio = 1 and utilisateuragence.lusername = current_user)) OR
--            (prospect_t.ncategorie <> 2 and prospect_t.cagence in (select cagence from utilisateuragence where utilisateuragence.bselectprospect = 1 and utilisateuragence.lusername = current_user)) OR
--             prospect_t.lusername = current_user  ;



--DROP VIEW prospect CASCADE ;
--CREATE OR REPLACE VIEW prospect AS
--
 --    SELECT prospect_t.*
--       FROM prospect_t
--  WHERE (prospect_t.ncategorie = ANY (ARRAY[0, 10])) OR prospect_t.ncategorie = 2 AND (prospect_t.cagence::text IN ( SELECT utilisateuragence.cagence
--           FROM utilisateuragence
--          WHERE utilisateuragence.bselectproprio = 1 AND utilisateuragence.lusername::name = "current_user"())) OR prospect_t.ncategorie <> 2 AND (prospect_t.cagence::text IN ( SELECT utilisateuragence.cagence
--           FROM utilisateuragence
--          WHERE utilisateuragence.bselectprospect = 1 AND utilisateuragence.lusername::name = "current_user"())) OR prospect_t.lusername::name = "current_user"();



CREATE OR REPLACE FUNCTION f_cdetail(
    nombre real,
    unite character varying,
    detail character varying,
    comment character varying)
  RETURNS character varying AS
$BODY$

    DECLARE
    detail text ;
    unite text ;
    unite_prefix text ;

    BEGIN

    IF $2 IS NULL OR $2 = ''  THEN

	   IF $1 > 1 THEN
			detail = replace($3, '(s)', 's');
			detail = replace(detail, '(x)', '');
	   ELSE
			detail = replace($3, '(s)', '');
			detail = replace(detail, '(x)', '');
	   END IF ;


         RETURN concat (  $1, ' ' , detail , ' ' , $4);

    ELSEIF $2 = '-' THEN
           RETURN concat (   $3 , ' ' , $1, ' ',  $4);
    ELSE
         RETURN concat (   $3 , ' ' , $1, ' ', $2 , ' ' , $4);
    END IF;

    END;

    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;



CREATE OR REPLACE FUNCTION f_unaccent_wild(items text[])
  RETURNS text[] AS
$BODY$
DECLARE
 conditions_arr  text[] ;
 expression  text ;
 item  text ;
-- Permet de retirer les accent des éléments d'une matrice et lui ajoute les '%' afin de permettre des recherche comme
-- lnom ilike all(f_unaccent_wild (ARRAY[ 'my','name','is','bond' ] ))
BEGIN
	FOREACH item IN ARRAY $1
	LOOP
		-- Prend chaque élément de la matrice et lui retire les accents
		expression = '%' || unaccent(item) || '%' ;
		conditions_arr = array_append( conditions_arr,expression );
	END LOOP;

    --  renvoi la matrice des éléments sans accents
    RETURN conditions_arr;

END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;



CREATE TABLE IF NOT EXISTS mandat_observation_t
(
  nobservation SERIAL,
  lobservation text NOT NULL,
  nmandat integer NOT NULL,
  lusername character varying(10),
  dobservation timestamp without time zone,
  dcre timestamp without time zone,
  cusercre character varying(50),
  cusermod character varying(50),
  dmod timestamp without time zone,
  CONSTRAINT pk_nobservation PRIMARY KEY (nobservation),
  CONSTRAINT fk_mandat_observation_nmandat FOREIGN KEY (nmandat)
      REFERENCES mandat_t (nmandat) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE CASCADE
)
WITH (
  OIDS=FALSE
);
ALTER TABLE mandat_observation_t
  OWNER TO admin;

-- Index: fki_mandat_observation_nmandat

-- DROP INDEX fki_mandat_observation_nmandat;
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_indexes
        WHERE schemaname = 'public'
          AND tablename = 'mandat_observation_t'
          AND indexname = 'fki_mandat_observation_nmandat'
    ) THEN
        CREATE INDEX fki_mandat_observation_nmandat
        ON mandat_observation_t
        USING btree (nmandat);
    END IF;
END
$$;



-- Trigger: tbui_mandat_observation_audit on mandat_observation_t

-- DROP TRIGGER tbui_mandat_observation_audit ON mandat_observation_t;
DROP TRIGGER IF EXISTS tbui_mandat_observation_audit ON mandat_observation_t;
CREATE TRIGGER tbui_mandat_observation_audit
  BEFORE INSERT OR UPDATE
  ON mandat_observation_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();



update params set nbmoismandat = 12 where nbmoismandat is null ;
update params set nbjoursagenda = 6 where nbjoursagenda is null ;
update params set nheuredebutagenda = 9 where nheuredebutagenda is null ;
update params set nheurefinagenda = 20 where nheurefinagenda is null ;
update params set bregmandat = 0 where bregmandat is null ;
UPDATE params SET nnummandat = 0 WHERE nnummandat is null ;

update langue set clangue_std = 'fr' where clangue = 'fr' and clangue_std is null ;
update langue set clangue_std = 'en' where clangue = 'en' and clangue_std is null ;
update langue set clangue_std = 'nl' where clangue = 'nl' and clangue_std is null ;
update langue set clangue_std = 'en' where clangue in ('zh', 'ru', 'sl', 'cs') and clangue_std is null ;
update langue set clangue_std = 'fr' where clangue is null ;


CREATE UNIQUE INDEX IF NOT EXISTS indx_cagence_ctargetsys_portailagence 
ON portailagence (cagence ASC NULLS LAST, ctargetsys ASC NULLS LAST);


update statutbien set  bisactive = 1 where bactif > 0;


DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'detailbien_ndetail_fk'
    ) THEN
        ALTER TABLE detailbien_t
        ADD CONSTRAINT detailbien_ndetail_fk 
        FOREIGN KEY (ndetail)
        REFERENCES detail (ndetail) MATCH SIMPLE
        ON UPDATE NO ACTION ON DELETE CASCADE;
    END IF;
END
$do$;


CREATE TABLE IF NOT EXISTS statutlead
(
  nstatutlead integer NOT NULL DEFAULT nextval('statutlead_nstatutlead_seq'::regclass),
  lstatutleadfr character varying(50),
  lstatutleaden character varying(50),
  lstatutleadnl character varying(50),
  lstatutleadde character varying(50),
  lstatutleades character varying(50),
  lstatutleadit character varying(50),
  lstatutleadsk character varying(50),
  lstatutleadcs character varying(50),
  lstatutleadru character varying(50),
  lstatutleadzh character varying(50),
  nordre integer,
  binclure smallint DEFAULT 1,
  cusercre character varying(10),
  dcre date,
  cusermod character varying(10),
  dmod date,
  CONSTRAINT pk_statutlead PRIMARY KEY (nstatutlead)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE statutlead OWNER TO admin;

--drop view biencrit cascade ;
--drop view prospectbien cascade ;

CREATE OR REPLACE FUNCTION f_recordbienchange()
  RETURNS trigger AS
$BODY$
    BEGIN
    -- Variation de mandat_t
    IF (OLD.cmandat <> NEW.cmandat AND OLD.cmandat IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 60, current_timestamp, current_timestamp, concat (OLD.cmandat , ' -> ' , NEW.cmandat )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

    -- Variation de prix
    -- Variation de prix
    IF (OLD.mprix <> NEW.mprix AND OLD.mprix IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 20, current_timestamp, current_timestamp, concat ( replace (trim(to_char (OLD.mprix, '999G999G999G999')),',','.'), ' -> ' , replace (trim(to_char (NEW.mprix, '999G999G999G999')),',','.') )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

     -- Variation de statut

    IF (OLD.bactif <> NEW.bactif AND OLD.bactif IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 21, current_timestamp, current_timestamp, (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = OLD.bactif) || ' -> '  || (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = NEW.bactif) ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

     -- Changement de négociateur (ntyprelation = 30)
    IF (OLD.lusername <> NEW.lusername AND OLD.lusername IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 30, current_timestamp, current_timestamp,
              concat ((SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = OLD.lusername)  , ' ('  , OLD.lusername  , ') -> '  , (SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = NEW.lusername ) , ' (' , NEW.lusername , ') '),
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;



    -- Changement de statut de publication Web (ntyprelation = 31)
    IF (OLD.bexportweb <> NEW.bexportweb AND OLD.bexportweb IS NOT NULL) THEN


      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 31, current_timestamp, current_timestamp, case when NEW.bexportweb=1 then 'Publication web activée' else 'Publication web suspendue' end ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;


     RETURN OLD;
    -- RETURN NULL;

    END;

    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;



CREATE OR REPLACE FUNCTION f_validateinserthisto()
  RETURNS trigger AS
$BODY$
-- Trigger permettant de valider le droit d'insérer un histo avec d'accepter
declare
 isentitled utilisateuragence.binserthisto%TYPE ;

begin

 if NEW.lusername = '' OR NEW.lusername IS NULL then
    NEW.lusername = current_user ;
End if;

 if NEW.cagence = '' OR NEW.cagence IS NULL then
    RAISE EXCEPTION 'Le code agence est manquant (utilisateur agence)';
else
  /* New function body */
  SELECT INTO isentitled binserthisto FROM utilisateuragence WHERE lusername = current_user and cagence = NEW.cagence ;

  if isentitled = 1 OR current_user = ',' OR current_user = 'admin'  then
    return NEW;
  Else
    RAISE EXCEPTION  'Droits insuffisants pour ajouter un évènement (cagence:%  utilisateur:%)' , NEW.cagence  , current_user      ;
  End if;
End if;

end;
$BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;
ALTER FUNCTION f_validateinserthisto()
  OWNER TO admin;



DO $do$
BEGIN
    -- Drop trigger tbu_histo_nprospectpropr if it exists
    IF EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'tbu_histo_nprospectpropr' AND tgrelid = 'prospectbien_t'::regclass) THEN
        DROP TRIGGER tbu_histo_nprospectpropr ON prospectbien_t;
    END IF;

    -- Drop trigger tbi_histo_nprospectpropr if it exists
    IF EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = 'tbi_histo_nprospectpropr' AND tgrelid = 'prospectbien_t'::regclass) THEN
        DROP TRIGGER tbi_histo_nprospectpropr ON prospectbien_t;
    END IF;
END $do$;




CREATE OR REPLACE FUNCTION public.f_set_nprospectpropr (
)
RETURNS trigger AS
$body$
BEGIN

    IF (TG_OP = 'DELETE') THEN

        IF (OLD.ntyprelation = 5 AND OLD.nbien IS NOT NULL AND OLD.nbien > 0) THEN
 
           -- Si aucun enregistrement correspondant dans prospectbien, mettre nprospectpropr à NULL
            UPDATE bien 
            SET nprospectpropr = NULL 
            WHERE nbien = OLD.nbien 
              AND NOT EXISTS (
                  SELECT 1 
                  FROM prospectbien 
                  WHERE ntyprelation = 5 
                    AND nbien = OLD.nbien
              );

            -- Sinon, prendre le premier nprospectpropr disponible pour ntyprelation = 5 et OLD.nbien
            UPDATE bien 
            SET nprospectpropr = (
                SELECT nprospect 
                FROM prospectbien 
                WHERE ntyprelation = 5 
                  AND nbien = OLD.nbien 
                LIMIT 1
            )
            WHERE nbien = OLD.nbien 
              AND EXISTS (
                  SELECT 1 
                  FROM prospectbien 
                  WHERE ntyprelation = 5 
                    AND nbien = OLD.nbien
              );        
        
        END IF; RETURN OLD;

    ELSE

        IF (NEW.ntyprelation = 5 AND NEW.nbien IS NOT NULL AND NEW.nprospect IS NOT NULL AND NEW.nbien > 0) THEN
        UPDATE bien SET nprospectpropr = NEW.nprospect WHERE nbien = NEW.nbien AND bien.nprospectpropr IS NULL ;
        END IF; RETURN NEW;

    END IF ;

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;
--cagencemandat 

ALTER FUNCTION f_set_nprospectpropr()
    OWNER TO admin;

DROP TRIGGER IF EXISTS tauid_histo_nprospectpropr ON prospectbien_t;
CREATE TRIGGER tauid_histo_nprospectpropr
    AFTER INSERT OR UPDATE OR DELETE
    ON prospectbien_t
    FOR EACH ROW
    EXECUTE PROCEDURE f_set_nprospectpropr();



  CREATE TABLE IF NOT EXISTS mandat_mandant
  (
    nmandant serial NOT NULL,
    lmandant text NOT NULL,
    ladr text NOT NULL,
    nmandat integer NOT NULL,
    cusercre character varying(50),
    cusermod character varying(50),
    dcre timestamp without time zone,
    dmod timestamp without time zone,
    CONSTRAINT pk_mandat_mandants PRIMARY KEY (nmandant)
  )
  WITH (
    OIDS=FALSE
  );

DROP TRIGGER IF EXISTS tbui_mandat_mandant_audit ON mandat_mandant;
CREATE TRIGGER tbui_mandat_mandant_audit
  BEFORE INSERT OR UPDATE
  ON mandat_mandant
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();


UPDATE agence SET cagencemandat = cagence WHERE cagencemandat is null ;



-- clean
-- Mettre à NULL les valeurs orphelines pour toutes les colonnes de référence vers typrelation
UPDATE preference_t p
SET 
    ntyprelationacte = CASE 
        WHEN ntyprelationacte IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationacte)
        THEN NULL 
        ELSE ntyprelationacte 
    END,
    ntyprelationactivite = CASE 
        WHEN ntyprelationactivite IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationactivite)
        THEN NULL 
        ELSE ntyprelationactivite 
    END,
    ntyprelationemail = CASE 
        WHEN ntyprelationemail IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationemail)
        THEN NULL 
        ELSE ntyprelationemail 
    END,
    ntyprelationrelance = CASE 
        WHEN ntyprelationrelance IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationrelance)
        THEN NULL 
        ELSE ntyprelationrelance 
    END,
    ntyprelationssp = CASE 
        WHEN ntyprelationssp IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationssp)
        THEN NULL 
        ELSE ntyprelationssp 
    END,
    ntyprelationvisite = CASE 
        WHEN ntyprelationvisite IS NOT NULL AND 
             NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationvisite)
        THEN NULL 
        ELSE ntyprelationvisite 
    END
WHERE 
    (ntyprelationacte IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationacte)) OR
    (ntyprelationactivite IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationactivite)) OR
    (ntyprelationemail IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationemail)) OR
    (ntyprelationrelance IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationrelance)) OR
    (ntyprelationssp IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationssp)) OR
    (ntyprelationvisite IS NOT NULL AND NOT EXISTS (SELECT 1 FROM typrelation t WHERE t.ntyprelation = p.ntyprelationvisite));
	
	

DO $do$
BEGIN
    -- Add foreign key constraint fk_ntyprelationacte_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationacte_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationacte_preference FOREIGN KEY (ntyprelationacte) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;

    -- Add foreign key constraint fk_ntyprelationactivite_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationactivite_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationactivite_preference FOREIGN KEY (ntyprelationactivite) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;

    -- Add foreign key constraint fk_ntyprelationemail_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationemail_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationemail_preference FOREIGN KEY (ntyprelationemail) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;

    -- Add foreign key constraint fk_ntyprelationrelance_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationrelance_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationrelance_preference FOREIGN KEY (ntyprelationrelance) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;

    -- Add foreign key constraint fk_ntyprelationssp_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationssp_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationssp_preference FOREIGN KEY (ntyprelationssp) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;

    -- Add foreign key constraint fk_ntyprelationvisite_preference if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_ntyprelationvisite_preference') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_ntyprelationvisite_preference FOREIGN KEY (ntyprelationvisite) REFERENCES typrelation (ntyprelation) MATCH SIMPLE ON UPDATE CASCADE ON DELETE CASCADE;
    END IF;
END $do$;


CREATE OR REPLACE FUNCTION f_dfinpublication() RETURNS trigger AS
$BODY$
declare
  --  cagence2   VARCHAR;
BEGIN
  IF (TG_OP = 'UPDATE') THEN
    IF (NEW.bexportweb <> OLD.bexportweb AND NEW.bexportweb = 0 ) THEN
		-- mettre fin à toutes les publications des biens sans export web ( a tester d'abord sur une agence)
		UPDATE prospectbien
		SET dfinpublication = current_timestamp
		WHERE nbien = NEW.nbien and ntyprelation = 10 and dfinpublication is null and ddebut is not null  ;
   END IF;
-- ELSIF (TG_OP = 'INSERT' ) THEN

 END IF;

 RETURN NEW;

END; $BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;

--drop view prospectbien ;

DO $do$
BEGIN
    -- Add column cagencemandat to agence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agence' AND column_name = 'cagencemandat') THEN
        ALTER TABLE agence ADD COLUMN cagencemandat character varying(10);
    END IF;

    -- Add column nnummandatdebut to agence if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agence' AND column_name = 'nnummandatdebut') THEN
        ALTER TABLE agence ADD COLUMN nnummandatdebut integer;
    END IF;
END $do$;


UPDATE agence SET cagencemandat = cagence WHERE cagencemandat is null ;


CREATE OR REPLACE FUNCTION f_set_nnummandat()
  RETURNS trigger AS
$BODY$
  DECLARE
    ll_nnummandat integer ;
 BEGIN

   SELECT INTO ll_nnummandat max(mandat_t.nnummandat) FROM mandat_t WHERE mandat_t.cagence = (select cagencemandat from agence where agence.cagence = new.cagence) ;

   IF ll_nnummandat IS NULL THEN
      --SELECT max(nnummandat) INTO ll_nnummandat FROM mandat_t WHERE cagence = (select cagencemandat from agence where agence = new.cagence) ;
      select INTO ll_nnummandat nnummandatdebut
      from agence
      where agence.cagence = (select agence.cagencemandat from agence where agence.cagence = new.cagence);

        IF ll_nnummandat IS NULL THEN
		--raise exception error
		RAISE EXCEPTION  'Le nouveau numéro de mandat_t ne peut être déterminé. Veuillez vérifier les paramètres de numérotaiton du registre des mandats'   ;

        ELSE
		NEW.nnummandat = ll_nnummandat + 1;
	END IF ;

   ELSE
       NEW.nnummandat = ll_nnummandat + 1;
   END IF ;

  RETURN NEW;

END; $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

ALTER FUNCTION f_set_nnummandat()
  OWNER TO admin;


------------------
--module des mandats
-------------------

DO $do$
BEGIN
    -- Create sequence mandat_observation_nobservation_seq if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'mandat_observation_nobservation_seq') THEN
        CREATE SEQUENCE mandat_observation_nobservation_seq
          INCREMENT 1
          MINVALUE 1
          MAXVALUE 9223372036854775807
          START 1
          CACHE 1;
        ALTER TABLE mandat_observation_nobservation_seq OWNER TO admin;
    END IF;

    -- Create sequence mandat_nmandat_seq if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'mandat_nmandat_seq') THEN
        CREATE SEQUENCE mandat_nmandat_seq
          INCREMENT 1
          MINVALUE 1
          MAXVALUE 9223372036854775807
          START 1
          CACHE 1;
        ALTER TABLE mandat_nmandat_seq OWNER TO admin;
    END IF;
END $do$;




DO $do$
BEGIN
    -- Create index fki_mandat_cagence on mandat_t if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relname = 'fki_mandat_cagence' AND relkind = 'i') THEN
        CREATE INDEX fki_mandat_cagence
          ON mandat_t
          USING btree
          (cagence COLLATE pg_catalog."default");
    END IF;

    -- Create TRIGGER tbi_mandat_nnumandat on mandat_t if it does not exist
    drop trigger if exists tbi_mandat_nnumandat on mandat_t;
        CREATE TRIGGER tbi_mandat_nnumandat
          BEFORE INSERT
          ON mandat_t
          FOR EACH ROW
          EXECUTE PROCEDURE f_set_nnummandat();
    

    -- Create TRIGGER tbui_mandat_audit on mandat_t if it does not exist
        DROP TRIGGER IF EXISTS tbui_mandat_audit ON mandat_t;
        CREATE TRIGGER tbui_mandat_audit
          BEFORE INSERT OR UPDATE
          ON mandat_t
          FOR EACH ROW
          EXECUTE PROCEDURE f_set_audit();


    -- Create table mandat_observation_t if it does not exist
    
        CREATE TABLE IF NOT EXISTS mandat_observation_t
        (
          nobservation integer NOT NULL DEFAULT nextval('mandat_observation_nobservation_seq'::regclass),
          lobservation text NOT NULL,
          nmandat integer NOT NULL,
          lusername character varying(10),
          dobservation timestamp without time zone,
          dcre timestamp without time zone,
          cusercre character varying(50),
          cusermod character varying(50),
          dmod timestamp without time zone,
          CONSTRAINT pk_nobservation PRIMARY KEY (nobservation),
          CONSTRAINT fk_mandat_observation_nmandat FOREIGN KEY (nmandat)
              REFERENCES mandat_t (nmandat) MATCH SIMPLE
              ON UPDATE CASCADE ON DELETE CASCADE
        )
        WITH (
          OIDS=FALSE
        );
    

    -- Create index fki_mandat_observation_nmandat on mandat_observation_t if it does not exist
      drop index if exists fki_mandat_observation_nmandat;
        CREATE INDEX fki_mandat_observation_nmandat
          ON mandat_observation_t
          USING btree
          (nmandat);
   

    -- CREATE TRIGGER tbui_mandat_observation_audit on mandat_observation_t if it does not exist

      DROP TRIGGER IF EXISTS tbui_mandat_observation_audit ON mandat_observation_t;

      CREATE TRIGGER tbui_mandat_observation_audit
          BEFORE INSERT OR UPDATE
          ON mandat_observation_t
          FOR EACH ROW
          EXECUTE PROCEDURE f_set_audit();
    
END $do$;




CREATE OR REPLACE FUNCTION f_propag_changes_on_duplicates()
RETURNS trigger AS
$BODY$
BEGIN
    IF (TG_OP = 'UPDATE') THEN
        IF (NEW.lemail > '') THEN
            IF (OLD.ladr <> NEW.ladr AND NEW.ladr > '') THEN
                UPDATE prospect
                SET ladr = NEW.ladr
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.lcp <> NEW.lcp AND NEW.lcp > '') THEN
                UPDATE prospect
                SET lcp = NEW.lcp
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.llocalite <> NEW.llocalite AND NEW.llocalite > '') THEN
                UPDATE prospect
                SET llocalite = NEW.llocalite
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.cisopays <> NEW.cisopays AND NEW.cisopays > '') THEN
                UPDATE prospect
                SET cisopays = NEW.cisopays
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.ltel <> NEW.ltel AND NEW.ltel > '') THEN
                UPDATE prospect
                SET ltel = NEW.ltel
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.lgsm <> NEW.lgsm AND NEW.lgsm > '') THEN
                UPDATE prospect
                SET lgsm = NEW.lgsm
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.ltel2 <> NEW.ltel2 AND NEW.ltel2 > '') THEN
                UPDATE prospect
                SET ltel2 = NEW.ltel2
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;

            IF (OLD.lfax <> NEW.lfax AND NEW.lfax > '') THEN
                UPDATE prospect
                SET lfax = NEW.lfax
                WHERE lemail = NEW.lemail
                  AND cagence = NEW.cagence
                  AND NEW.nprospect <> prospect.nprospect;
            END IF;
        END IF;
    END IF;
    RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS tau_propag_changes_on_duplicates ON prospect_t;
  CREATE TRIGGER tau_propag_changes_on_duplicates
  AFTER UPDATE
  ON prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_propag_changes_on_duplicates();


CREATE OR REPLACE FUNCTION f_get_prospect_detail(
    as_clangue text,
    an_nprospect integer,
    an_ndetail integer)
  RETURNS text AS
$BODY$
      DECLARE
         ret text;
     BEGIN

	IF as_clangue = 'en' THEN

		 SELECT INTO ret concat ( qnombre , ' ' , lcommenten )  FROM detailprospect WHERE nprospect = an_nprospect and ndetail = an_ndetail limit 1 ;
		 IF ret IS NULL THEN
		  Return 'No';
		ELSE
		  IF trim(ret) > '' THEN
			RETURN trim(ret);
		  ELSE
		    RETURN 'Yes';
		  END IF;
		END IF ;

	 ELSE

		 SELECT INTO ret concat ( qnombre , ' ' , lcommentfr  )  FROM detailprospect WHERE nprospect = an_nprospect and ndetail = an_ndetail limit 1 ;
		 IF ret IS NULL THEN
		  Return 'Non';
		ELSE
		  IF trim(ret) > '' THEN
			RETURN trim(ret);
		  ELSE
		    RETURN 'Oui';
		  END IF;
		END IF ;

	 END IF ;

     END;
     $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;




CREATE OR REPLACE FUNCTION f_get_bien_detail(
    as_clangue text,
    an_nbien integer,
    an_ndetail integer)
  RETURNS text AS
$BODY$
      DECLARE
         ret text;
     BEGIN

	IF as_clangue = 'en' THEN

		 SELECT INTO ret concat ( qnombre , ' ' , lcommenten )  FROM detailbien WHERE nbien = an_nbien and ndetail = an_ndetail limit 1 ;
		 IF ret IS NULL THEN
		  Return 'No';
		ELSE
		  IF trim(ret) > '' THEN
			RETURN trim(ret);
		  ELSE
		    RETURN 'Yes';
		  END IF;
		END IF ;

	 ELSE

		 SELECT INTO ret concat ( qnombre , ' ' , lcommentfr  )  FROM detailbien WHERE nbien = an_nbien and ndetail = an_ndetail limit 1 ;
		 IF ret IS NULL THEN
		  Return 'Non';
		ELSE
		  IF trim(ret) > '' THEN
			RETURN trim(ret);
		  ELSE
		    RETURN 'Oui';
		  END IF;
		END IF ;

	 END IF ;

     END;
     $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;




CREATE OR REPLACE FUNCTION public.f_format_currency (
  amount numeric,
  currency_code text
)
RETURNS text AS
$body$
DECLARE
    formatted_amount TEXT;
    currency_symbol TEXT;
    symbol_position TEXT DEFAULT 'before'; -- Default position is before the amount
BEGIN
    -- Define currency symbols for known currencies and their position
    CASE currency_code
        WHEN 'USD' THEN currency_symbol := '$';
        WHEN 'GBP' THEN currency_symbol := '£';
        WHEN 'JPY' THEN currency_symbol := '¥';
        WHEN 'EUR' THEN 
            BEGIN
                currency_symbol := '€';
                symbol_position := 'after'; -- For EUR, place the symbol after the amount
            END;
        WHEN 'MUR' THEN currency_symbol := '₨'; -- Mauritian Rupee symbol before the amount
        -- Add more currencies and adjust positions as needed
        ELSE 
            BEGIN
                currency_symbol := currency_symbol; -- Default case if currency is not recognized
                symbol_position := 'after';
            END;
    END CASE;

    -- Format the amount with two decimal places TO_CHAR(6565455456565, 'FM999 999 999 999 990') 
    formatted_amount := TO_CHAR(amount, 'FM999 999 999 999 990');

    -- Return the formatted amount with the currency symbol in the correct position
    IF symbol_position = 'before' THEN
        RETURN currency_symbol || formatted_amount;
    ELSE
        RETURN formatted_amount || ' ' || currency_symbol; -- Note the space before the currency symbol for readability
    END IF;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;

ALTER FUNCTION public.f_format_currency (amount numeric, currency_code text)
  OWNER TO admin;

  
-- renouvellement de toutes les vues :
--drop view prospect cascade ;
--drop view prospectbien cascade ;
--drop view bien cascade ;
--drop view preference cascade ;
--drop view htmlbien cascade ;
--drop view biencrit cascade ;
--drop view photo cascade ;
--drop view agenda cascade ;
--drop view mandat_t cascade ;
--drop view mandat_observation cascade ;
--drop view offre cascade ;
--drop view doc cascade ;
DO $do$
BEGIN
    -- Drop view prospect if it exists
    IF EXISTS (SELECT 1 FROM information_schema.views WHERE table_name = 'prospect') THEN
        DROP VIEW IF EXISTS prospect CASCADE;
    END IF;
END $do$;


DROP VIEW IF EXISTS prospect CASCADE;
CREATE OR REPLACE VIEW prospect AS
 SELECT prospect_t.nprospect,
    prospect_t.ccivilite,
    prospect_t.cpolit,
    prospect_t.lnom,
    prospect_t.lprenom,
    prospect_t.lnomsociete,
    prospect_t.ladr,
    prospect_t.lcp,
    prospect_t.llocalite,
    prospect_t.cisopays,
    prospect_t.ltel,
    prospect_t.lfax,
    prospect_t.ltel2,
    prospect_t.lgsm,
    prospect_t.lemail,
    prospect_t.ncategorie,
    prospect_t.bactif,
    prospect_t.csexe,
    prospect_t.dnaissance,
    prospect_t.nregmat,
    prospect_t.lnomjf,
    prospect_t.nprospectdepend,
    prospect_t.llieunaissance,
    prospect_t.dregmatdepuis,
    prospect_t.lcomment,
    prospect_t.cusercre,
    prospect_t.dcre,
    prospect_t.dmod,
    prospect_t.cusermod,
    prospect_t.clangue,
    prospect_t.brelanceauto,
    prospect_t.lccp,
    prospect_t.nprospectnotaire,
    prospect_t.lusername,
    prospect_t.cagence,
    prospect_t.nprospectagence,
    prospect_t.corigineprospect,
    prospect_t.ltelecom,
    prospect_t.mlongitude,
    prospect_t.mlatitude,
    prospect_t.lpassword,
    prospect_t.ddoubleoptin,
    prospect_t.bsmsauto,
    prospect_t.bnewsauto,
    prospect_t.llpassword,
    prospect_t.benqueteauto,
    prospect_t.lurlenquete,
    prospect_t.nrating,
    prospect_t.ballownews,
    prospect_t.ballowsms,
    prospect_t.nstatutlead,
    prospect_t.lsearch,
    prospect_t.cisopaysnat,
    prospect_t.cid,
    prospect_t.cpassport,
    prospect_t.nrisklevel
   FROM prospect_t
  WHERE (prospect_t.ncategorie = ANY (ARRAY[0, 10])) OR prospect_t.ncategorie = 2 AND (prospect_t.cagence::text IN ( SELECT utilisateuragence.cagence
           FROM utilisateuragence
          WHERE utilisateuragence.bselectproprio = 1 AND utilisateuragence.lusername::name = "current_user"())) OR prospect_t.ncategorie <> 2 AND (prospect_t.cagence::text IN ( SELECT utilisateuragence.cagence
           FROM utilisateuragence
          WHERE utilisateuragence.bselectprospect = 1 AND utilisateuragence.lusername::name = "current_user"())) OR prospect_t.lusername::name = "current_user"();




DROP VIEW IF EXISTS biencrit CASCADE;
CREATE OR REPLACE VIEW biencrit AS
 SELECT biencrit_t.*
   FROM biencrit_t
  WHERE (biencrit_t.nprospect IN ( SELECT prospect.nprospect
           FROM prospect));



DROP VIEW IF EXISTS photo CASCADE;
CREATE OR REPLACE VIEW photo AS
 SELECT photo_t.*
   FROM photo_t
  WHERE (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE photo_t.nbien = bien_t.nbien AND utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));




--grant all on agence to remax_admin, remax_normal ;
-- si la table mandat existe il faut la supprimer avec cascade (vérfier qu'elle est vide)
-- DROP TABLE public.mandat  CASCADE ;

--DROP VIEW IF EXISTS mandat CASCADE;


DROP VIEW IF EXISTS mandat CASCADE;
CREATE OR REPLACE VIEW mandat AS
 SELECT mandat_t.nmandat,
    mandat_t.nbien,
    mandat_t.ddebmandat,
    mandat_t.dfinmandat,
    mandat_t.ltypmandat,
    mandat_t.lnatmandat,
    mandat_t.cstatutmandat,
    mandat_t.ltypxx,
    mandat_t.ladrbien,
    mandat_t.lcpbien,
    mandat_t.llocalitebien,
    mandat_t.cagence,
    mandat_t.lusername,
    mandat_t.lstatutmandat,
    mandat_t.lmandants,
    mandat_t.cisopaysbien,
    mandat_t.nnummandat,
    mandat_t.ltypbien,
    mandat_t.nnumrepertoire,
    mandat_t.dcre,
    mandat_t.cusercre,
    mandat_t.cusermod,
    mandat_t.dmod
   FROM mandat_t
  WHERE (mandat_t.cagence::text IN ( SELECT agence.cagencemandat
           FROM agence
          WHERE (agence.cagence::text IN ( SELECT utilisateur.cagence
                   FROM utilisateur
                  WHERE utilisateur.lusername::name = "current_user"()))));



DROP VIEW IF EXISTS mandat_observation;


CREATE OR REPLACE VIEW mandat_observation AS
 SELECT mandat_observation_t.nobservation,
    mandat_observation_t.lobservation,
    mandat_observation_t.nmandat,
    mandat_observation_t.lusername,
    mandat_observation_t.dobservation,
    mandat_observation_t.dcre,
    mandat_observation_t.cusercre,
    mandat_observation_t.cusermod,
    mandat_observation_t.dmod
   FROM mandat_observation_t
  WHERE (mandat_observation_t.nmandat IN ( SELECT mandat.nmandat
           FROM mandat));



DROP VIEW IF EXISTS prospectbien CASCADE;


CREATE OR REPLACE VIEW prospectbien AS
 SELECT prospectbien_t.*
   FROM prospectbien_t
  WHERE prospectbien_t.ntyprelation = 5 OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            typrelation
          WHERE prospectbien_t.ntyprelation = typrelation.ntyprelation AND (utilisateuragence.bselecthisto = 1 OR utilisateuragence.bselectrv = 1 AND typrelation.brendezvous = 1) AND utilisateuragence.lusername::name = "current_user"() AND (prospectbien_t.cagence::text = utilisateuragence.cagence::text OR prospectbien_t.cagence::text = ''::text OR prospectbien_t.cagence IS NULL)));

DROP VIEW IF EXISTS bien CASCADE;

CREATE OR REPLACE VIEW bien AS
 SELECT bien_t.*
   FROM bien_t
  WHERE (bien_t.lusername::text = "current_user"() OR 
        EXISTS ( SELECT NULL::unknown AS unknown
         FROM utilisateuragence
         WHERE utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));


    



DROP VIEW IF EXISTS htmlbien CASCADE;
CREATE OR REPLACE VIEW htmlbien AS
 SELECT htmlbien_t.clangue,
    htmlbien_t.nbien,
    htmlbien_t.lhtml,
    htmlbien_t.lascii,
    htmlbien_t.cusercre,
    htmlbien_t.cusermod,
    htmlbien_t.dcre,
    htmlbien_t.dmod,
    htmlbien_t.ltitre,
    htmlbien_t.lannonce,
    htmlbien_t.cagence,
    htmlbien_t.lannonceweb,
    htmlbien_t.lannonceseo
   FROM htmlbien_t
  WHERE (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE bien_t.nbien = htmlbien_t.nbien AND utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));


-- assurer que l'on peut voir les doc que l'on a créé
DROP VIEW IF EXISTS doc CASCADE;
CREATE OR REPLACE VIEW doc AS
 SELECT doc_t.ndoc,
    doc_t.ltitre,
    doc_t.nbien,
    doc_t.nprospect,
    doc_t.lcontent,
    doc_t.lheader,
    doc_t.lfooter,
    doc_t.dcre,
    doc_t.cusercre,
    doc_t.dmod,
    doc_t.cusermod,
    doc_t.denvoi,
    doc_t.ntxformatid,
    doc_t.cagence,
    doc_t.cagencedoc,
    doc_t.lfilename,
    doc_t.bexportweb,
    doc_t.nrelation
   FROM doc_t
  WHERE
doc_t.cagence = (select cagence from utilisateur where lusername = current_user)
OR
  (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE doc_t.nbien = bien_t.nbien AND utilisateuragence.bselectdoc = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL))) OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            prospect_t
          WHERE doc_t.nprospect = prospect_t.nprospect AND utilisateuragence.bselectdoc = 1 AND utilisateuragence.lusername::name = "current_user"() AND (prospect_t.cagence::text = utilisateuragence.cagence::text OR prospect_t.cagence::text = ''::text OR prospect_t.cagence IS NULL)));


DROP VIEW IF EXISTS prospectbien CASCADE;
CREATE OR REPLACE VIEW prospectbien AS
 SELECT prospectbien_t.*
   FROM prospectbien_t
  WHERE prospectbien_t.ntyprelation = 5 OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            typrelation
          WHERE prospectbien_t.ntyprelation = typrelation.ntyprelation AND (utilisateuragence.bselecthisto = 1 OR utilisateuragence.bselectrv = 1 AND typrelation.brendezvous = 1) AND utilisateuragence.lusername::name = "current_user"() AND (prospectbien_t.cagence::text = utilisateuragence.cagence::text OR prospectbien_t.cagence::text = ''::text OR prospectbien_t.cagence IS NULL)));



DROP VIEW IF EXISTS agenda CASCADE;
CREATE OR REPLACE VIEW agenda AS
 SELECT bien_t.cbien,
    bien_t.bcle,
    bien_t.lcontactvisite,
    bien_t.llocalite,
    prospectbien.nrelation,
    prospectbien.nprospect,
    prospectbien.nbien,
    prospectbien.ntyprelation,
    prospectbien.ddebut,
    prospectbien.dfin,
    prospectbien.lrem,
    typrelation.ltyprelation,
    prospect_t.lnom,
    prospect_t.lprenom,
    prospect_t.cpolit,
    prospectbien.dalarm,
    prospectbien.lusername,
    typrelation.ncouleur,
    typrelation.ncouleurtexte,
    bien_t.ladr,
    prospectbien.bconfirmed
   FROM prospectbien
     LEFT JOIN typrelation USING (ntyprelation)
     LEFT JOIN bien_t USING (nbien)
     LEFT JOIN prospect_t USING (nprospect)
  WHERE typrelation.brendezvous = 1 AND prospectbien.ddebut IS NOT NULL;


-- update qui requiert l'existence des vues
UPDATE prospectbien_t set blvisitemailsent = 0 WHERE blvisitemailsent IS NULL ;
ALTER TABLE prospectbien_t ALTER COLUMN blvisitemailsent SET NOT NULL;


UPDATE offre_t set dmod =  dmod ;
update prospectbien_t set bconfirmmailsent = 0 WHERE bconfirmmailsent IS NULL ;





--mettre à jour les champs dénormalisés
update biencrit_t set dmod = dmod ;







--mettre à jour les champs dénormalisés
update biencrit_t set dmod = dmod ;


update prospect_t set nrating = 0 where nrating is null ;

update prospect_t set bsmsauto = 0 where bsmsauto is null ;
update prospect_t set bnewsauto = 0 where bnewsauto is null ;

DROP TRIGGER IF EXISTS tbui_mandat_audit ON mandat_t;
CREATE TRIGGER tbui_mandat_audit
  BEFORE INSERT OR UPDATE
  ON mandat_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();



DROP TRIGGER IF EXISTS tbiud_mandat_denorm ON mandat_t;

CREATE TRIGGER tbiud_mandat_denorm
  BEFORE INSERT OR UPDATE OR DELETE
  ON mandat_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_update_bien_mandat();



CREATE TABLE IF NOT EXISTS prospectrel
(
  nprospectrel SERIAL,
  nprospect1 integer,
  nprospect2 integer,
  ntyprel integer default 1,
  dcre timestamp without time zone,
  cusercre character varying(15),
  dmod timestamp without time zone,
  cusermod character varying(15),
  CONSTRAINT pk_nprospectrel PRIMARY KEY (nprospectrel),

  CONSTRAINT fk_prospectrel_nprospect1_t FOREIGN KEY (nprospect1)
      REFERENCES prospect_t (nprospect) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE SET NULL,

  CONSTRAINT fk_prospectrel_nprospect2_t FOREIGN KEY (nprospect2)
      REFERENCES prospect_t (nprospect) MATCH SIMPLE
      ON UPDATE CASCADE ON DELETE SET NULL
)
WITH (
  OIDS=FALSE
);



-- mettre des message clair sur l'insertion de bien
CREATE OR REPLACE FUNCTION f_tbi_bien_check()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.cregion IS NULL THEN
    RAISE EXCEPTION 'Le champ "secteur" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.lusername IS NULL THEN
    RAISE EXCEPTION 'Le champ "négociateur" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.cbien IS NULL THEN
    RAISE EXCEPTION 'Le champ "référence" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.ctyp IS NULL THEN
    RAISE EXCEPTION 'Le champ "type de bien" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- mettre des message clair sur l'insertion de bien
CREATE OR REPLACE FUNCTION f_tbi_bien_check()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.cregion IS NULL THEN
    RAISE EXCEPTION 'Le champ "secteur" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.lusername IS NULL THEN
    RAISE EXCEPTION 'Le champ "négociateur" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.cbien IS NULL THEN
    RAISE EXCEPTION 'Le champ "référence" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  IF NEW.ctyp IS NULL THEN
    RAISE EXCEPTION 'Le champ "type de bien" doit avoir une valeur. Merci de la spécifier.';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS tbi_bien_check ON bien_t;

CREATE TRIGGER tbi_bien_check
BEFORE INSERT OR UPDATE ON bien_t
FOR EACH ROW EXECUTE PROCEDURE f_tbi_bien_check();



CREATE OR REPLACE FUNCTION f_propagate_nprospectdepend()
  RETURNS trigger AS
$BODY$
-- Trigger permettant de propager la relation de mariage exprimée par nprospectdepend
begin

         IF (TG_OP = 'UPDATE') THEN

            IF NEW.nprospectdepend <> OLD.nprospectdepend THEN
                UPDATE prospect SET nprospectdepend = NEW.nprospect WHERE nprospect = NEW.nprospectdepend::integer ;
            END IF ;

            RETURN NEW ;

         ELSIF (TG_OP = 'INSERT') THEN

            IF NEW.nprospectdepend > 0 AND NEW.nprospectdepend IS NOT NULL THEN
                     UPDATE prospect SET nprospectdepend = NEW.nprospect WHERE nprospect = NEW.nprospectdepend::integer ;
            END IF ;

            RETURN NEW ;

         ELSIF (TG_OP = 'DELETE') THEN

            IF OLD.nprospectdepend > 0 AND OLD.nprospectdepend IS NOT NULL THEN
                UPDATE prospect SET nprospectdepend = NULL WHERE nprospect = OLD.nprospectdepend::integer ;
            END IF ;
            RETURN OLD ;

         END IF;


end;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

DROP TRIGGER IF EXISTS tbiud_nprospectdepend ON prospect_t;
CREATE TRIGGER tbiud_nprospectdepend
  AFTER INSERT OR UPDATE OR DELETE
  ON prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_propagate_nprospectdepend();



CREATE OR REPLACE FUNCTION check_ntyprelation()
RETURNS trigger AS
$$
BEGIN
    IF OLD.ntyprelation < 108 OR OLD.ntyprelation = 1000 THEN
        RAISE EXCEPTION 'Cette valeur est protégée, vous ne pouvez pas la supprimer';
    END IF;
    RETURN OLD;
END;
$$
LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS prevent_delete_typrelation ON typrelation;
CREATE TRIGGER prevent_delete_typrelation
BEFORE DELETE ON typrelation
FOR EACH ROW
EXECUTE PROCEDURE check_ntyprelation();




CREATE OR REPLACE FUNCTION check_detail_bprotect()
RETURNS trigger AS
$$
BEGIN
    IF OLD.bprotect = 1 THEN
        RAISE EXCEPTION 'Cette valeur est protégée, vous ne pouvez pas la supprimer';
    END IF;
    RETURN OLD;
END;
$$
LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS prevent_delete_detail_bprotect ON detail;
CREATE TRIGGER prevent_delete_detail_bprotect
BEFORE DELETE ON detail
FOR EACH ROW
EXECUTE PROCEDURE check_detail_bprotect();


DROP TRIGGER IF EXISTS prevent_delete_typdetail_bprotect ON typdetail;
CREATE TRIGGER prevent_delete_typdetail_bprotect
BEFORE DELETE ON typdetail
FOR EACH ROW
EXECUTE PROCEDURE check_detail_bprotect();




update typ set ballowforeigners = 0 where ballowforeigners is null ;
alter table typ ALTER COLUMN ballowforeigners SET DEFAULT 0;
alter table typ ALTER COLUMN ballowforeigners SET NOT NULL;



CREATE OR REPLACE FUNCTION f_set_audit()
  RETURNS trigger AS
$BODY$BEGIN
       IF TG_OP = 'INSERT' THEN
		NEW.cusercre := current_user ;
		NEW.dcre := current_timestamp  ;
		NEW.cusermod := current_user ;
		NEW.dmod := current_timestamp  ;
       ELSE
         IF current_user <> 'admin' THEN
             NEW.cusermod := current_user ;
             NEW.dmod :=  current_timestamp  ;
         END IF;
       END IF;

     RETURN NEW;
     END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

DROP TRIGGER IF EXISTS tbui_prospect_t_audit ON prospect_t;
CREATE TRIGGER tbui_prospect_t_audit
  BEFORE INSERT OR UPDATE
  ON prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();


DO $do$
BEGIN
    -- Add column copenonstart to utilisateur if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'copenonstart') THEN
        ALTER TABLE utilisateur ADD COLUMN copenonstart varchar(10) DEFAULT '/biens';
    END IF;

    -- Drop foreign key constraint offre_fk_cagence on offre_t if it exists
    IF EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'offre_t' AND constraint_name = 'offre_fk_cagence') THEN
        ALTER TABLE offre_t DROP CONSTRAINT offre_fk_cagence;
    END IF;

    -- Add foreign key constraint offre_fk_cagence on offre_t
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'offre_t' AND constraint_name = 'offre_fk_cagence') THEN
        ALTER TABLE offre_t
          ADD CONSTRAINT offre_fk_cagence FOREIGN KEY (cagence)
          REFERENCES agence (cagence) MATCH SIMPLE
          ON UPDATE CASCADE ON DELETE NO ACTION;
    END IF;

    -- Add primary key constraint pk_statutoffre on statutoffre if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'statutoffre' AND constraint_name = 'pk_statutoffre') THEN
        ALTER TABLE statutoffre
          ADD CONSTRAINT pk_statutoffre PRIMARY KEY (cstatut);
    END IF;

    -- Create table agencereport if it does not exist
    
        CREATE TABLE IF NOT EXISTS agencereport
        (
          nagencereport SERIAL NOT NULL,
          cagence character varying(10) NOT NULL,
          lname character varying(150),
          lcomment character varying(1000),
          ldata text,
          bsharelevel integer NOT NULL DEFAULT 1,
          cstoragekey character varying(20),
          dcre timestamp without time zone,
          cusercre character varying(50),
          dmod timestamp without time zone,
          cusermod character varying(50),
          lusername character varying(10),
          CONSTRAINT pk_agencereport PRIMARY KEY (nagencereport)
        )
        WITH (
          OIDS=FALSE
        );
        ALTER TABLE agencereport OWNER TO admin;


    -- Add column cstoragekey to agencereport if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agencereport' AND column_name = 'cstoragekey') THEN
        ALTER TABLE agencereport ADD COLUMN cstoragekey varchar(20);
    END IF;

END $do$;




DROP TRIGGER IF EXISTS tbui_agencereport_audit ON agencereport;
CREATE TRIGGER tbui_agencereport_audit    BEFORE INSERT OR UPDATE  ON agencereport     FOR EACH ROW     EXECUTE PROCEDURE f_set_audit();


-- Trigger: tbui_agencereport_audit on agencereport

--activimmo ADM
--DROP TABLE news;

DO $do$
BEGIN
    -- Create table news if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'news') THEN
        CREATE TABLE IF NOT EXISTS news
        (
          nnews SERIAL NOT NULL,
          dnews timestamp without time zone DEFAULT NOW(),
          clangue character varying(2),
          ccountry character varying(3),
          ctype character varying(10) DEFAULT 'wait'::character varying,
          ltitle character varying(100),
          lbody character varying(1000),
          lbodyhtml character varying(1000),
          qtimeoutmms integer,
          balwaysshown integer,
          bshowclose integer,
          href character varying(1000),
          nversion_from integer,
          nversion_to integer,
          CONSTRAINT nnews_pkey PRIMARY KEY (nnews)
        )
        WITH (
          OIDS=FALSE
        );
        ALTER TABLE news OWNER TO admin;
    END IF;
END $do$;



DO $do$
BEGIN
    -- Add column lname to agencereport if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'agencereport' AND column_name = 'lname') THEN
        ALTER TABLE agencereport ADD COLUMN lname character varying(150);
    END IF;

    -- Create sequence agencereport_nagencereport_seq if it does not exist
    IF NOT EXISTS (SELECT 1 FROM pg_class WHERE relkind = 'S' AND relname = 'agencereport_nagencereport_seq') THEN
        CREATE SEQUENCE agencereport_nagencereport_seq
          INCREMENT 1
          MINVALUE 1
          MAXVALUE 9223372036854775807
          START 64
          CACHE 1;
    END IF;
END $do$;




-- Trigger: tbui_agence_audit on agence

-- DROP TRIGGER tbui_agence_audit ON agence;
DROP TRIGGER IF EXISTS tbui_agencereport_audit ON agencereport;
CREATE TRIGGER tbui_agencereport_audit
  BEFORE INSERT OR UPDATE
  ON agencereport
  FOR EACH ROW
  EXECUTE PROCEDURE f_set_audit();


CREATE OR REPLACE FUNCTION f_validatedeletedoc()
  RETURNS trigger AS
$BODY$
    -- Trigger permettant de valider le droit de supprimer un document avec d'accepter
    declare
     isentitled utilisateuragence.bdeletedoc%TYPE ;

    begin
      /* New function body */
      SELECT INTO isentitled bdeletedoc FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

      if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin'  then
        return OLD;
      Else
        RAISE EXCEPTION  'Droits insuffisants pour supprimer un document (cagence:%)',  OLD.cagence   ;
      End if;
    end;
    $BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;


ALTER TABLE agencereport_nagencereport_seq OWNER TO admin;


DROP TRIGGER IF EXISTS tbui_agencereport_audit ON agencereport;
CREATE TRIGGER tbui_agencereport_audit BEFORE INSERT OR UPDATE ON agencereport     FOR EACH ROW     EXECUTE PROCEDURE f_set_audit();

-- ne fonctionne pas en pg 9.6
--CREATE EXTENSION IF NOT EXISTS pg_trgm;


CREATE OR REPLACE FUNCTION f_nextval(as_csequence text) RETURNS integer AS
$BODY$
      DECLARE
         ret integer;
     BEGIN

         SELECT INTO ret max(nvaleur) FROM sequences WHERE  csequence = as_csequence ;

         IF ret IS NULL THEN
    	INSERT INTO sequences (csequence, nvaleur) VALUES (as_csequence, 1) ;
            ret := 1 ;
         ELSE
    	ret := ret + 1 ;
    	UPDATE sequences SET nvaleur = ret WHERE csequence = as_csequence ;
        END IF ;


         RETURN ret;

     END;
     $BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;



CREATE OR REPLACE FUNCTION timestamp_to_rfc3339(t TIMESTAMP WITHOUT TIME ZONE)
RETURNS TEXT
LANGUAGE plpgsql
AS $$
BEGIN
    RETURN to_char(t, 'YYYY-MM-DD"T"HH24:MI:SS') ||
           (CASE
               WHEN EXTRACT(TIMEZONE FROM CURRENT_TIMESTAMP) / 3600 >= 0 THEN '+'
               ELSE '-'
            END) ||
            to_char(ABS(EXTRACT(TIMEZONE_HOUR FROM CURRENT_TIMESTAMP)), 'FM00') || ':' ||
            to_char(ABS(EXTRACT(TIMEZONE_MINUTE FROM CURRENT_TIMESTAMP)), 'FM00');
END;
$$;

-- erreur avec pg 9.6 :
--CREATE EXTENSION IF NOT EXISTS pg_trgm;



-- init de coffre si nécessaire par le biais d'un trigger
CREATE OR REPLACE FUNCTION public.f_set_nextval_offre_t() RETURNS trigger AS
$BODY$ BEGIN
 IF (NEW.nrelation IS NULL) THEN NEW.nrelation = f_nextval('nrelation'); END IF;
 IF (NEW.coffre IS NULL OR trim(NEW.coffre) = '') THEN NEW.coffre = NEW.nrelation::text ; END IF;
 RETURN NEW;
 END; $BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;



update prospectdef set bactif = 1 WHERE bactif <> 0 or bactif is null ;



update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 10 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 15 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 31 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 60 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 30 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 20 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 40 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 21 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'change' where ntyprelation = 109 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 108 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 41 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 42 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'autre' where ntyprelation = 16 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'chat' where ntyprelation = 22 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 1 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 107 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'rdv' where ntyprelation = 5 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 50 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'rdv' where ntyprelation = 102 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'rdv' where ntyprelation = 101 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'suivi' where ntyprelation = 17 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'autre' where ntyprelation = 12 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'autre' where ntyprelation = 24 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'autre' where ntyprelation = 23 and (ctyprelationmeta is null or ctyprelationmeta = '') ;
update typrelation set ctyprelationmeta = 'rdv' where ntyprelation = 14 and (ctyprelationmeta is null or ctyprelationmeta = '') ;

update typrelation set ctyprelationmeta = 'autre' where ctyprelationmeta is null or ctyprelationmeta = '' ;








CREATE OR REPLACE VIEW typdetail_bien AS SELECT * FROM typdetail WHERE blinkid = 0 AND btache = 0 ORDER BY nordre ;
CREATE OR REPLACE VIEW typdetail_prospect AS SELECT * FROM  typdetail WHERE blinkid = 1 AND btache = 0 ORDER BY nordre ;
CREATE OR REPLACE VIEW typdetail_offre AS SELECT * FROM  typdetail WHERE blinkid = 2 AND btache = 0 ORDER BY nordre  ;
CREATE OR REPLACE VIEW typdetail_tache_bien AS SELECT * FROM  typdetail WHERE blinkid = 0 AND btache = 1 ORDER BY nordre  ;
CREATE OR REPLACE VIEW typdetail_tache_prospect AS SELECT * FROM  typdetail WHERE blinkid = 1 AND btache = 1 ORDER BY nordre  ;
CREATE OR REPLACE VIEW typdetail_tache_offre AS SELECT * FROM  typdetail WHERE blinkid = 2 AND btache = 1 ORDER BY nordre  ;


--grant sur les vues


-- 


-- ajout de la colonne mcommissionvendeur dans la vue offre

DO $do$
BEGIN
    -- Add column mcommissionvendeur to offre_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'offre_t' AND column_name = 'mcommissionvendeur') THEN
        ALTER TABLE public.offre_t ADD COLUMN mcommissionvendeur integer;
    END IF;
END $do$;





DO $do$
BEGIN
    -- Create table ids if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'ids') THEN
        CREATE TABLE IF NOT EXISTS ids
        (
          nids SERIAL NOT NULL,
          lgateway character varying(20) NOT NULL,
          ctype character varying(20) NOT NULL,
          nexternalid integer,
          ninternalid integer NOT NULL,
          cexternalid character varying(20),
          cinternalid character varying(20),
          CONSTRAINT pk_ids PRIMARY KEY (nids)
        )
        WITH (
          OIDS=FALSE
        );
    END IF;
END $do$;




-- Function: public.update_mariage_relation()

-- DROP FUNCTION public.update_mariage_relation();

CREATE OR REPLACE FUNCTION public.f_handle_nprospectdepend_update() RETURNS trigger AS
$BODY$
BEGIN
  -- Si nprospectdepend est modifié
  IF TG_OP = 'UPDATE' THEN
    IF NEW.nprospectdepend IS DISTINCT FROM OLD.nprospectdepend THEN
        -- Mettre à jour l'épouse pour indiquer que son mari est le contact mis à jour
        UPDATE prospect
        SET nprospectdepend = NEW.nprospect
        WHERE nprospect = NEW.nprospectdepend;
    END IF;
    RETURN NEW;

   ELSE
	IF TG_OP = 'UPDATE' THEN
	    IF NEW.nprospectdepend > 0 THEN
		-- Mettre à jour l'épouse pour indiquer que son mari est le contact mis à jour
		UPDATE prospect
		SET nprospectdepend = NEW.nprospect
		WHERE nprospect = NEW.nprospectdepend;
	    END IF;
	END IF;
	RETURN NEW;
   END IF;
  
END;
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;




CREATE OR REPLACE FUNCTION public.f_handle_nprospectdepend_deletion()
  RETURNS trigger AS
$BODY$
BEGIN
    -- Si un contact est supprimé, mettre à NULL toutes les références dans nprospectdepend
    UPDATE prospect
    SET nprospectdepend = NULL
    WHERE nprospectdepend = OLD.nprospect;

    RETURN OLD;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.f_handle_nprospectdepend_deletion()
  OWNER TO admin;


DROP TRIGGER IF EXISTS tad_prospect_nprospectdepend ON prospect_t;
CREATE TRIGGER tad_prospect_nprospectdepend
  AFTER DELETE
  ON public.prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE public.f_handle_nprospectdepend_deletion();


DROP TRIGGER IF EXISTS taiu_prospect_nprospectdepend ON prospect_t;
CREATE TRIGGER taiu_prospect_nprospectdepend
  AFTER INSERT OR UPDATE
  ON public.prospect_t
  FOR EACH ROW
  EXECUTE PROCEDURE public.f_handle_nprospectdepend_update();




CREATE OR REPLACE FUNCTION public.check_ntyprelation() RETURNS trigger AS
$BODY$
BEGIN
 IF TG_OP = 'UPDATE' THEN
    IF OLD.ntyprelation IN (0, 5, 10) THEN
        RAISE EXCEPTION 'Cette valeur de ntyprelation est protégée et ne peut pas être modifiée';
    END IF;
    RETURN NEW;

  ELSIF TG_OP = 'DELETE' THEN
    IF OLD.ntyprelation IN (0, 5, 10) THEN
        RAISE EXCEPTION 'Cette valeur de ntyprelation est protégée et ne peut pas être modifiée';
    END IF;
    RETURN OLD;

  ELSIF TG_OP = 'INSERT' THEN
    --IF NEW.ntyprelation IN (0, 5, 10) THEN
    --    RAISE EXCEPTION 'Cette valeur de ntyprelation est protégée et ne peut pas être modifiée';
    --END IF;
    RETURN NEW;
  
  END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE NOT LEAKPROOF
COST 100;


CREATE OR REPLACE FUNCTION public.f_set_biencrit_lsql (
)
RETURNS trigger AS
$body$
 BEGIN
      -- trigger function for getting and storing lsql when called from biencrit at insertion or update
      --IF (NEW.ntyprelation IS NULL) THEN
      IF (NEW.ctypmandat1 IS NULL) THEN
		NEW.ctypmandat1 = 'v' ;
      END IF;

      NEW.lsql = f_build_select(NEW);

      RETURN NEW;

    END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;



CREATE OR REPLACE FUNCTION f_insert_erp()
  RETURNS trigger AS
$BODY$
    -- Trigger permettant de valider le droit d'insérer un bien avec d'accepter
    declare
     badderp integer ;
     text_erp varchar(250) ;
     text_erp_html varchar(250) ;

    begin

      IF NEW.clangue = 'fr' then

          /* Rechercher l'agence donc dépend le nbien */
          SELECT INTO badderp badderpinadverts
          FROM agence
          WHERE NEW.cagence = agence.cagence ;

          IF badderp IS NOT NULL AND badderp = 1 then

            text_erp = 'Les informations sur les risques auxquels ce bien est exposé sont disponibles sur le site Géorisques : www.georisques.gouv.fr';
            text_erp_html = '<p>Les informations sur les risques auxquels ce bien est exposé sont disponibles sur le site Géorisques <a target="_blank" href="https://www.georisques.gouv.fr/">www.georisques.gouv.fr</a></p>';
            IF NEW.lannonce not ilike '%' || 'georisques.gouv.fr' || '%' THEN
                NEW.lannonce = NEW.lannonce || ' ' || chr(10) || text_erp;
            END IF ;

            IF NEW.lannonceweb not ilike '%' || 'georisques.gouv.fr' || '%' THEN
                NEW.lannonceweb = NEW.lannonceweb || ' ' || chr(10) || text_erp;
            END IF ;

            IF NEW.lascii not ilike '%' || 'georisques.gouv.fr' || '%' THEN
                NEW.lascii = NEW.lascii || ' ' ||  chr(10) || text_erp;
            END IF ;

            IF NEW.lhtml not ilike '%' || 'georisques.gouv.fr' || '%' THEN
                NEW.lhtml = NEW.lhtml || text_erp_html;
            END IF ;

          END IF;
      END IF;

    return NEW ;

    end;
    $BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;


DROP TRIGGER IF EXISTS tbi_htmlbien_erp ON htmlbien_t;
  CREATE TRIGGER tbi_htmlbien_erp
  BEFORE INSERT OR UPDATE
  ON htmlbien_t
  FOR EACH ROW
  EXECUTE PROCEDURE f_insert_erp();


DO $do$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_constraint
    WHERE conname = 'pk_typdetail'
      AND conrelid = 'public.typdetail'::regclass
  ) THEN
    ALTER TABLE public.typdetail
      ADD CONSTRAINT pk_typdetail 
        PRIMARY KEY (ntypdetail) NOT DEFERRABLE;
  END IF;
END $do$;

    
  DO $do$
  BEGIN
    IF NOT EXISTS (
      SELECT 1
      FROM pg_constraint
      WHERE conname = 'pk_detail'
        AND conrelid = 'public.detail'::regclass
    ) THEN
      ALTER TABLE public.detail
    ADD CONSTRAINT pk_detail 
      PRIMARY KEY (ndetail) NOT DEFERRABLE;
  END IF;
END $do$;

--update agence set badderpinadverts = 1  ;
--create table htmlbien_sav as select * from htmbien_t ;

INSERT INTO typdetail (
  ntypdetail,
  nordre,
  binternet,
  ltypdetailen,
  ltypdetailnl,
  ltypdetailfr,
  ltypdetailde,
  binclure,
  bprotect,
  ctypdetail,
  btache,
  blinkid,
  ltypdetailes,
  ltypdetailit,
  ltypdetailsk,
  ltypdetailcs,
  ltypdetailru,
  ltypdetailzh,
  cicon,
  ntypdetailmeta,
  breport
)
VALUES (
  300,
  0,
  0,
  'Lead Management',
  'Leadbeheer',
  'Suivi commercial',
  'Lead-Management',
  1,
  1,
  'lead',
  0,
  1,
  'Gestión de leads',
  'Gestione dei lead',
  'Manažment leadov',
  'Správa leadů',
  'Управление лидами',
  '潜在客户管理',
  'contact_mail',
  NULL,
  1
) ON CONFLICT (ntypdetail) DO NOTHING; 


INSERT INTO detail (
  ndetail,
  ntypdetail,
  binternet,
  ldetailnl,
  ldetailen,
  ldetailfr,
  bdescriptif,
  binclure,
  bprotect,
  nordre,
  bcritere,
  ldetailde,
  ldetailes,
  ldetailit,
  ldetailsk,
  ldetailcs,
  ldetailru,
  ldetailzh,
  bimportant,
  bdefault,
  breport
)
VALUES (
  4001,
  300,
  0,
  'Commerciële tracking geactiveerd',
  'Lead follow-up enabled',
  'Suivi commercial activé',
  0,
  1,
  1,
  0,
  1,
  'Verkaufstracking aktiviert',
  'Seguimiento comercial activado',
  'Monitoraggio commerciale attivato',
  'Obchodné sledovanie aktivované',
  'Obchodní sledování aktivováno',
  'Торговый мониторинг активирован',
  '商业跟踪已激活',
  1,
  0,
  1
) ON CONFLICT (ndetail) DO NOTHING;


INSERT INTO detail (
  ndetail,
  ntypdetail,
  binternet,
  ldetailnl,
  ldetailen,
  ldetailfr,
  bdescriptif,
  binclure,
  bprotect,
  nordre,
  bcritere,
  ldetailde,
  ldetailes,
  ldetailit,
  ldetailsk,
  ldetailcs,
  ldetailru,
  ldetailzh,
  bimportant,
  bdefault,
  breport
)
VALUES (
  4002,
  300,
  0,
  'Leadkwalificatie',
  'Criteria entered (Lead Qualification)',
  'Définition des critères',
  0,
  1,
  1,
  2,
  1,
  'Lead-Qualifizierung',
  'Calificación de Leads',
  'Qualificazione del Lead',
  'Kvalifikácia Leadov',
  'Kvalifikace leadů',
  'Квалификация Лидов',
  '潜在客户资格审核',
  1,
  0,
  1
) 
ON CONFLICT (ndetail) DO NOTHING;


INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport)
VALUES (4003, 300, 0, 'Engagement en Nurturing', 'Engagement and Nurturing', 'Echanges (emails ou appels,etc)', 0, 1, 1, 3, 1, 'Engagement und Nurturing', 'Compromiso y Nutrición', 'Impegno e Nurturing', 'Angažovanosť a Nurturing', 'Angažovanost a Nurturing', 'Вовлечение и Воспитание', '顾客参与和培养', 1, 0, 1)
ON CONFLICT (ndetail) DO NOTHING;

INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport)
VALUES (4004, 300, 0, 'Presentatie van Eigendommen', 'Property Presentation', 'Visites de propriétés', 0, 1, 1, 4, 1, 'Präsentation von Immobilien', 'Presentación de Propiedades', 'Presentazione di Proprietà', 'Prezentácia Nehnuteľností', 'Prezentace nemovitostí', 'Предложение Недвижимости', '展示房产', 1, 0, 1)
ON CONFLICT (ndetail) DO NOTHING;

INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport)
VALUES (4005, 300, 0, 'Onderhandeling en Aanbiedingen', 'Negotiation and Offers', 'Offres et négociation', 0, 1, 1, 5, 1, 'Verhandlung und Angebote', 'Negociación y Ofertas', 'Negoziazione e Offerte', 'Vyjednávanie a Ponuky', 'Vyjednávání a nabídky', 'Переговоры и Предложения', '谈判和报价', 1, 0, 1)
ON CONFLICT (ndetail) DO NOTHING;

INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport)
VALUES (4006, 300, 0, 'Afsluiting (Succes)', 'Closure (Success)', 'Clôture avec succès :-)', 0, 1, 1, 6, 1, 'Abschluss (Erfolg)', 'Cierre (Éxito)', 'Chiusura (Successo)', 'Uzatvorenie (Úspech)', 'Uzavření (Úspěch)', 'Закрытие Сделки (Успех)', '成交（成功）', 1, 0, 1)
ON CONFLICT (ndetail) DO NOTHING;

INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport)
VALUES (4007, 300, 0, 'Afsluiting (Mislukking)', 'Closure (Failure)', 'Clôture (Échec)', 0, 1, 1, 7, 1, 'Abschluss (Misserfolg)', 'Cierre (Fracaso)', 'Chiusura (Fallimento)', 'Uzatvorenie (Neúspech)', 'Uzavření (Neúspěch)', 'Закрытие Сделки (Провал)', '成交（失败）', 1, 0, 1)
ON CONFLICT (ndetail) DO NOTHING;

--INSERT INTO detail (ndetail, ntypdetail, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, breport) VALUES (4008, 300, 0, 'In afwachting', 'Pending', 'En attente', 0, 1, 1, 7, 1, 'In Erwartung', 'En espera', 'In attesa', 'V očakávaní', 'V očekávání', 'В ожидании', '待定', 1, 0, 1);


-- ajoute le lead qualification dès qu'un critère de prospect est ajouté nbien
CREATE OR REPLACE FUNCTION f_manage_detailprospect_qualification()
RETURNS TRIGGER AS $$
BEGIN
    IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN

      -- Si une entrée avec ndetail=4000 et nprospect correspondant existe déjà
      IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4002 AND nprospect = NEW.nprospect) THEN
          -- Mise à jour du champ dmod
          UPDATE detailprospect
          SET dmod = CURRENT_TIMESTAMP
          WHERE ndetail = 4002 AND nprospect = NEW.nprospect;
      ELSE
          -- Insertion d'une nouvelle entrée
          INSERT INTO detailprospect(ndetail, nprospect)
          VALUES (4002, NEW.nprospect);
      END IF;
    END IF;

    -- Retourner NEW pour permettre la continuation des opérations
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS taiu_biencrit_detailprospect ON biencrit_t;
CREATE TRIGGER taiu_biencrit_detailprospect
AFTER INSERT OR UPDATE OF nprospect
ON biencrit_t
FOR EACH ROW
EXECUTE PROCEDURE f_manage_detailprospect_qualification();


-- Trigger permettant de gérer le suivi de lead en fonction des actions menées
CREATE OR REPLACE FUNCTION public.f_manage_detailprospect_nurturing()
  RETURNS trigger AS
$BODY$
DECLARE
    v_detail INTEGER;
BEGIN
    -- Determine le ndetail à utiliser
    IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN
      SELECT INTO v_detail
          CASE 
              WHEN brendezvous = 1 THEN 4004
              WHEN brelance = 1 THEN 4003
              ELSE NULL
          END
      FROM typrelation 
      WHERE ntyprelation = NEW.ntyprelation AND (brelance = 1 OR brendezvous = 1);

      -- Si aucun ndetail valide n'est trouvé, retourner NEW sans effectuer d'autres actions
      IF v_detail IS NULL THEN
          RETURN NEW;
      END IF;

      -- Si une entrée avec ndetail calculé et nprospect correspondant existe déjà
      IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = v_detail AND nprospect = NEW.nprospect) THEN
          -- Mise à jour du champ dmod
          UPDATE detailprospect
          SET dmod = CURRENT_TIMESTAMP
          WHERE ndetail = v_detail AND nprospect = NEW.nprospect;
      ELSE
          -- Insertion d'une nouvelle entrée
          INSERT INTO detailprospect(ndetail, nprospect)
          VALUES (v_detail, NEW.nprospect);
      END IF;
    END IF;

    -- Retourner NEW pour permettre la continuation des opérations
    RETURN NEW;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION public.f_manage_detailprospect_nurturing()
  OWNER TO admin;


DROP TRIGGER IF EXISTS taiu_biencrit_detailprospect ON prospectbien_t;

CREATE TRIGGER taiu_biencrit_detailprospect
AFTER INSERT OR UPDATE OF nprospect
ON prospectbien_t
FOR EACH ROW
EXECUTE PROCEDURE f_manage_detailprospect_nurturing();



-- si une offre est faite il faut mettre dans le suivi de lead qu'il y a une négociation en cours
CREATE OR REPLACE FUNCTION public.f_manage_offer_detailprospect()
RETURNS TRIGGER AS $$
BEGIN
    IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN

      -- Si une entrée avec ndetail = 4005 et nprospect correspondant existe déjà
      IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4005 AND nprospect = NEW.nprospect) THEN
          -- Mise à jour du champ dmod
          UPDATE detailprospect
          SET dmod = CURRENT_TIMESTAMP
          WHERE ndetail = 4005 AND nprospect = NEW.nprospect;
      ELSE
          -- Insertion d'une nouvelle entrée
          INSERT INTO detailprospect(ndetail, nprospect, dmod)
          VALUES (4005, NEW.nprospect, CURRENT_TIMESTAMP);
      END IF;
    END IF;

    -- Retourner NEW pour permettre la continuation des opérations
    RETURN NEW;
END;
$$ LANGUAGE plpgsql VOLATILE;

DROP TRIGGER IF EXISTS manage_offer_insert_trigger ON offre_t;
CREATE TRIGGER manage_offer_insert_trigger
AFTER INSERT ON offre_t
FOR EACH ROW EXECUTE PROCEDURE f_manage_offer_detailprospect();

-- si une offre est faite il faut mettre dans le suivi de lead qu'il y a une négociation en cours
DROP TRIGGER IF EXISTS manage_offer_trigger ON offre_t;
CREATE TRIGGER manage_offer_trigger
AFTER INSERT OR UPDATE ON offre_t
FOR EACH ROW EXECUTE PROCEDURE f_manage_offer_detailprospect();


-- enchencher le lead management:nbien
CREATE OR REPLACE FUNCTION f_enable_lead_management()
RETURNS TRIGGER AS $$

DECLARE
    count_exists INTEGER;
BEGIN
  IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN
    IF NEW.ndetail IN ( 4002, 4003) THEN
        SELECT COUNT(*)
        INTO count_exists
        FROM detailprospect
        WHERE ndetail = 4001 AND nprospect = NEW.nprospect;
        
        IF count_exists = 0 THEN
            INSERT INTO detailprospect (ndetail, nprospect)
            VALUES (4001, NEW.nprospect);
        END IF;
    END IF;
  END IF;
    RETURN NEW;
END;

$$ LANGUAGE plpgsql;


--DROP FUNCTION f_denormalize_lead_management() CASCADE;
CREATE OR REPLACE FUNCTION public.f_denormalize_lead_management (
)
RETURNS trigger AS
$body$
DECLARE
  current_nprospect BIGINT;
BEGIN
  IF TG_OP = 'DELETE' THEN
    current_nprospect := OLD.nprospect;
  ELSE
    current_nprospect := NEW.nprospect;
  END IF;

  -- Mise à jour de ndetaillast ddebut:
  IF EXISTS (SELECT 1 FROM detailprospect, detail WHERE detailprospect.ndetail = detail.ndetail and detail.ntypdetail = 300 and nprospect = current_nprospect) AND
     NOT EXISTS (SELECT 1 FROM detailprospect WHERE ndetail IN (4006, 4007) AND nprospect = current_nprospect) THEN
    UPDATE prospect
    SET ddetailsuivi = current_timestamp, ndetailsuivi = (
      SELECT dp.ndetail
      FROM detailprospect dp
      JOIN detail d ON dp.ndetail = d.ndetail
      WHERE dp.nprospect = current_nprospect
      ORDER BY d.nordre DESC
      LIMIT 1
    )
    WHERE nprospect = current_nprospect;
  ELSE
    UPDATE prospect
    SET ddetailsuivi = null, ndetailsuivi = NULL
    WHERE nprospect = current_nprospect;
  END IF;

  -- Mise à jour de ndetailprec
  UPDATE prospect
  SET ndetailsuiviprec = (
    SELECT dp.ndetail
    FROM detailprospect dp
    JOIN detail d ON dp.ndetail = d.ndetail
    WHERE dp.nprospect = current_nprospect AND dp.dcre <= current_date - interval '1 week'
    ORDER BY d.nordre DESC
    LIMIT 1
  )
  WHERE nprospect = current_nprospect;

  IF TG_OP = 'DELETE' THEN
    RETURN NULL;
  ELSE
    RETURN NEW;
  END IF;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;
















DROP TRIGGER IF EXISTS taid_detailprospect ON detailprospect;
CREATE TRIGGER taid_detailprospect AFTER INSERT OR UPDATE OR DELETE ON detailprospect FOR EACH ROW EXECUTE PROCEDURE f_denormalize_lead_management();




DROP TRIGGER IF EXISTS tbid_detailprospect ON detailprospect;
CREATE TRIGGER tbid_detailprospect
  BEFORE INSERT OR DELETE 
  ON public.detailprospect
FOR EACH ROW  
  EXECUTE PROCEDURE f_denormalize_lead_management();

--DROP TRIGGER tai_detailprospect_trigger ON detailbien_t;

DROP TRIGGER IF EXISTS tai_detailprospect_trigger ON detailprospect;
CREATE TRIGGER tai_detailprospect_trigger
AFTER INSERT ON detailprospect
FOR EACH ROW EXECUTE PROCEDURE f_enable_lead_management();

-- CREATE TRIGGER trigger_update_prospect_detail
-- AFTER INSERT OR UPDATE OR DELETE ON detailprospect
-- FOR EACH ROW EXECUTE FUNCTION update_prospect_detail();

-- suppression du lead management lors d'une cloture de lead:
CREATE OR REPLACE FUNCTION f_remove_leadmanagement()
RETURNS TRIGGER AS $$
BEGIN
    IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN
      IF OLD.ndetail IN (4006, 4007) THEN
          DELETE FROM detailprospect
          WHERE ndetail = 4001 AND nbien = NEW.nprospect;
      END IF;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS tai_detailbien_remove_detailbien_trigger ON detailbien_t;
DROP TRIGGER IF EXISTS tai_detailbien_remove_detailbien_trigger ON detailprospect;
CREATE TRIGGER tai_detailbien_remove_detailbien_trigger
AFTER INSERT ON detailprospect
FOR EACH ROW EXECUTE PROCEDURE f_remove_leadmanagement();



-- ajouter le detail 4001 enable lead management lors de la création d'un prospect
DROP TRIGGER IF EXISTS tai_add_leadmanagement ON prospect_t;
CREATE OR REPLACE FUNCTION f_activate_leadmanagement()
RETURNS TRIGGER AS $$
DECLARE
    v_islead BOOLEAN;
BEGIN
  -- ajouter le detail 4001 enable lead management lors de la création d'un prospect
 
    -- Vérification si la catégorie correspondante a bislead égal à 1
    SELECT c.bislead INTO v_islead
    FROM cat c
    WHERE c.ncategorie = NEW.ncategorie;
    
    IF v_islead THEN

            -- Insertion d'une nouvelle entrée
            INSERT INTO detailprospect (ndetail, nprospect)
            VALUES (4001, NEW.nprospect);
        
    END IF;

    -- Retourner NEW pour permettre la continuation des opérations
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS tai_add_leadmanagement ON prospect_t;
CREATE TRIGGER tai_add_leadmanagement
AFTER INSERT ON prospect_t
FOR EACH ROW EXECUTE PROCEDURE f_activate_leadmanagement();


DO $do$
BEGIN
    -- Add column brelance to typrelation if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typrelation' AND column_name = 'brelance') THEN
        ALTER TABLE typrelation ADD COLUMN brelance smallint;
        ALTER TABLE typrelation ALTER COLUMN brelance SET DEFAULT 0;
    END IF;

    -- If the column exists but does not have the default value set, update it
    IF EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typrelation' AND column_name = 'brelance') THEN
        ALTER TABLE typrelation ALTER COLUMN brelance SET DEFAULT 0;
    END IF;


    -- Add column brenseignement to typrelation if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'typrelation' AND column_name = 'brenseignement') THEN
        ALTER TABLE typrelation ADD COLUMN brenseignement smallint;
    END IF;

    -- Set default value for column brenseignement in typrelation
    ALTER TABLE typrelation ALTER COLUMN brenseignement SET DEFAULT 0;

END $do$;



UPDATE typrelation 
SET brelance = 1 
WHERE ntyprelation IN (17, 101, 109, 114, 115)
OR ltyprelationfr ILIKE '%relance%'
OR ltyprelationfr ILIKE '%appel%'
OR ltyprelationfr ILIKE '%téléph%'
OR ltyprelationfr ILIKE '%téléphone%'
OR ltyprelationfr ILIKE '%phoning%'
OR ltyprelationfr ILIKE '%telephonique%'
OR ltyprelationfr ILIKE '%mail%';


UPDATE typrelation 
SET brenseignement = 1 
WHERE ntyprelation IN (12)
OR ltyprelationfr ILIKE '%rensei%'
OR ltyprelationfr ILIKE '%premier%';


DO $do$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'cat'
          AND column_name = 'bislead'
    ) THEN
        ALTER TABLE cat ADD COLUMN bislead smallint DEFAULT 0;
    END IF;
END
$do$;



UPDATE cat 
SET bislead = 1 
WHERE 
   lcategoriefr ILIKE '%prospect%'
OR lcategoriefr ILIKE '%acquéreur%'
OR lcategoriefr ILIKE '%acquereur%'
OR lcategoriefr ILIKE '%acqere%'
OR lcategoriefr ILIKE '%acqu%'
OR lcategoriefr ILIKE '%acqére%'
OR lcategoriefr ILIKE '%investisseur%'
OR lcategoriefr ILIKE '%demandeur%'
OR lcategoriefr ILIKE '%amateur%';



CREATE OR REPLACE FUNCTION public.check_detail_bprotect (
)
RETURNS trigger AS
$body$
BEGIN
    IF OLD.bprotect = 1 and current_user <> 'admin' THEN
        RAISE EXCEPTION 'Cette valeur est protégée, vous ne pouvez pas la supprimer';
    END IF;
    RETURN OLD;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;



--INSERT INTO  regionmeta (    cregionmeta,  lregionmetafr,  lregionmetaen,  lregionmetanl,  binclure) VALUES ( 'nc',  'Non communiqué',  'Undefined',  'Ongedefinieerd',1);
--INSERT INTO   region(  cregion,  cregionmeta,  lregionfr,  lregionen,  lregionnl,  binclure) VALUES (  'nc',  'nc',  'Non communiqué',  'Undefined',  'Ongedefinieerd',1);
--INSERT INTO   typmeta(   ctypmeta,  ltypmetafr,  ltypmetaen,  ltypmetanl,  binclure) VALUES (  'nc', 'Non communiqué',  'Undefined',  'Ongedefinieerd',1);
--INSERT INTO   typ(  ctyp,  ctypmeta,  ltypfr,  ltypen,  ltypnl,  binclure) VALUES (  'nc',  'nc',  'Non communiqué',  'Undefined',  'Ongedefinieerd',1);

--INSERT INTO public.converter(    cactivtable,    cactivcode,    ctargetsys,    ctargetval,    lactivvalue,    nconverter) VALUES (    'typ',    'nc',    'generic',    'ma',    'Maison',    966521);
--INSERT INTO public.converter(    cactivtable,    cactivcode,    ctargetsys,    ctargetval,    lactivvalue,    nconverter) VALUES (    'typmeta',    'nc',    'generic',    'mai',    'Maisons',    966522);

--INSERT INTO public.converter(    cactivtable,    cactivcode,    ctargetsys,    ctargetval,    lactivvalue,    nconverter)SELECT    'region',    'nc',    'generic',    cregion,    'Maisons',    966523FROM biendef where cregion > '' and cregion is not null LIMIT 1;

-- nextval qui prend 11000 par défaut au lieu de 1
CREATE OR REPLACE FUNCTION public.f_nextval (
  as_csequence text
)
RETURNS integer AS
$body$
      DECLARE
         ret integer;
     BEGIN

         SELECT INTO ret max(nvaleur) FROM sequences WHERE  csequence = as_csequence ;

         IF ret IS NULL THEN
    	INSERT INTO sequences (csequence, nvaleur) VALUES (as_csequence, 11000) ;
            ret := 11000 ;
         ELSE
    	ret := ret + 1 ;
    	UPDATE sequences SET nvaleur = ret WHERE csequence = as_csequence ;
        END IF ;


         RETURN ret;

     END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;





DO $do$
BEGIN
    -- Add column cintprefix to pays if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'pays' AND column_name = 'cintprefix') THEN
        ALTER TABLE pays ADD COLUMN cintprefix VARCHAR(10);
    END IF;
END $do$;



UPDATE pays SET cintprefix = '93' WHERE cisopays = 'AFG'; -- Afghanistan
UPDATE pays SET cintprefix = '355' WHERE cisopays = 'ALB'; -- Albanie
UPDATE pays SET cintprefix = '213' WHERE cisopays = 'DZA'; -- Algérie
UPDATE pays SET cintprefix = '376' WHERE cisopays = 'AND'; -- Andorre
UPDATE pays SET cintprefix = '244' WHERE cisopays = 'AGO'; -- Angola
UPDATE pays SET cintprefix = '54' WHERE cisopays = 'ARG'; -- Argentine
UPDATE pays SET cintprefix = '374' WHERE cisopays = 'ARM'; -- Arménie
UPDATE pays SET cintprefix = '61' WHERE cisopays = 'AUS'; -- Australie
UPDATE pays SET cintprefix = '43' WHERE cisopays = 'AUT'; -- Autriche
UPDATE pays SET cintprefix = '994' WHERE cisopays = 'AZE'; -- Azerbaïdjan
UPDATE pays SET cintprefix = '973' WHERE cisopays = 'BHR'; -- Bahreïn
UPDATE pays SET cintprefix = '880' WHERE cisopays = 'BGD'; -- Bangladesh
UPDATE pays SET cintprefix = '375' WHERE cisopays = 'BLR'; -- Bélarus
UPDATE pays SET cintprefix = '32' WHERE cisopays = 'BEL'; -- Belgique
UPDATE pays SET cintprefix = '501' WHERE cisopays = 'BLZ'; -- Belize
UPDATE pays SET cintprefix = '229' WHERE cisopays = 'BEN'; -- Bénin
UPDATE pays SET cintprefix = '975' WHERE cisopays = 'BTN'; -- Bhoutan
UPDATE pays SET cintprefix = '591' WHERE cisopays = 'BOL'; -- Bolivie
UPDATE pays SET cintprefix = '387' WHERE cisopays = 'BIH'; -- Bosnie-Herzégovine
UPDATE pays SET cintprefix = '267' WHERE cisopays = 'BWA'; -- Botswana
UPDATE pays SET cintprefix = '55' WHERE cisopays = 'BRA'; -- Brésil
UPDATE pays SET cintprefix = '673' WHERE cisopays = 'BRN'; -- Brunei
UPDATE pays SET cintprefix = '359' WHERE cisopays = 'BGR'; -- Bulgarie
UPDATE pays SET cintprefix = '226' WHERE cisopays = 'BFA'; -- Burkina Faso
UPDATE pays SET cintprefix = '257' WHERE cisopays = 'BDI'; -- Burundi
UPDATE pays SET cintprefix = '855' WHERE cisopays = 'KHM'; -- Cambodge
UPDATE pays SET cintprefix = '237' WHERE cisopays = 'CMR'; -- Cameroun
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'CAN'; -- Canada
UPDATE pays SET cintprefix = '238' WHERE cisopays = 'CPV'; -- Cap-Vert
UPDATE pays SET cintprefix = '236' WHERE cisopays = 'CAF'; -- République centrafricaine
UPDATE pays SET cintprefix = '56' WHERE cisopays = 'CHL'; -- Chili
UPDATE pays SET cintprefix = '86' WHERE cisopays = 'CHN'; -- Chine
UPDATE pays SET cintprefix = '57' WHERE cisopays = 'COL'; -- Colombie
UPDATE pays SET cintprefix = '269' WHERE cisopays = 'COM'; -- Comores
UPDATE pays SET cintprefix = '242' WHERE cisopays = 'COG'; -- Congo (Brazzaville)
UPDATE pays SET cintprefix = '243' WHERE cisopays = 'COD'; -- Congo (Kinshasa)
UPDATE pays SET cintprefix = '506' WHERE cisopays = 'CRI'; -- Costa Rica
UPDATE pays SET cintprefix = '225' WHERE cisopays = 'CIV'; -- Côte d'Ivoire
UPDATE pays SET cintprefix = '385' WHERE cisopays = 'HRV'; -- Croatie
UPDATE pays SET cintprefix = '53' WHERE cisopays = 'CUB'; -- Cuba
UPDATE pays SET cintprefix = '357' WHERE cisopays = 'CYP'; -- Chypre
UPDATE pays SET cintprefix = '420' WHERE cisopays = 'CZE'; -- République tchèque
UPDATE pays SET cintprefix = '45' WHERE cisopays = 'DNK'; -- Danemark
UPDATE pays SET cintprefix = '253' WHERE cisopays = 'DJI'; -- Djibouti
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'DMA'; -- Dominique

UPDATE pays SET cintprefix = '236' WHERE cisopays = 'CAF'; -- République centrafricaine
UPDATE pays SET cintprefix = '56' WHERE cisopays = 'CHL'; -- Chili
UPDATE pays SET cintprefix = '86' WHERE cisopays = 'CHN'; -- Chine
UPDATE pays SET cintprefix = '57' WHERE cisopays = 'COL'; -- Colombie
UPDATE pays SET cintprefix = '269' WHERE cisopays = 'COM'; -- Comores
UPDATE pays SET cintprefix = '242' WHERE cisopays = 'COG'; -- Congo (Brazzaville)
UPDATE pays SET cintprefix = '243' WHERE cisopays = 'COD'; -- Congo (Kinshasa)
UPDATE pays SET cintprefix = '506' WHERE cisopays = 'CRI'; -- Costa Rica
UPDATE pays SET cintprefix = '225' WHERE cisopays = 'CIV'; -- Côte d'Ivoire
UPDATE pays SET cintprefix = '385' WHERE cisopays = 'HRV'; -- Croatie
UPDATE pays SET cintprefix = '53' WHERE cisopays = 'CUB'; -- Cuba
UPDATE pays SET cintprefix = '357' WHERE cisopays = 'CYP'; -- Chypre
UPDATE pays SET cintprefix = '420' WHERE cisopays = 'CZE'; -- République tchèque
UPDATE pays SET cintprefix = '45' WHERE cisopays = 'DNK'; -- Danemark
UPDATE pays SET cintprefix = '253' WHERE cisopays = 'DJI'; -- Djibouti
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'DMA'; -- Dominique
UPDATE pays SET cintprefix = '1809' WHERE cisopays = 'DOM'; -- République Dominicaine
UPDATE pays SET cintprefix = '593' WHERE cisopays = 'ECU'; -- Équateur
UPDATE pays SET cintprefix = '20' WHERE cisopays = 'EGY'; -- Égypte
UPDATE pays SET cintprefix = '503' WHERE cisopays = 'SLV'; -- El Salvador
UPDATE pays SET cintprefix = '240' WHERE cisopays = 'GNQ'; -- Guinée équatoriale
UPDATE pays SET cintprefix = '291' WHERE cisopays = 'ERI'; -- Érythrée
UPDATE pays SET cintprefix = '372' WHERE cisopays = 'EST'; -- Estonie
UPDATE pays SET cintprefix = '251' WHERE cisopays = 'ETH'; -- Éthiopie
UPDATE pays SET cintprefix = '679' WHERE cisopays = 'FJI'; -- Fidji
UPDATE pays SET cintprefix = '358' WHERE cisopays = 'FIN'; -- Finlande
UPDATE pays SET cintprefix = '33' WHERE cisopays = 'FRA'; -- France
UPDATE pays SET cintprefix = '241' WHERE cisopays = 'GAB'; -- Gabon
UPDATE pays SET cintprefix = '220' WHERE cisopays = 'GMB'; -- Gambie
UPDATE pays SET cintprefix = '995' WHERE cisopays = 'GEO'; -- Géorgie
UPDATE pays SET cintprefix = '49' WHERE cisopays = 'DEU'; -- Allemagne
UPDATE pays SET cintprefix = '233' WHERE cisopays = 'GHA'; -- Ghana
UPDATE pays SET cintprefix = '30' WHERE cisopays = 'GRC'; -- Grèce
UPDATE pays SET cintprefix = '1473' WHERE cisopays = 'GRD'; -- Grenade
UPDATE pays SET cintprefix = '502' WHERE cisopays = 'GTM'; -- Guatemala
UPDATE pays SET cintprefix = '224' WHERE cisopays = 'GIN'; -- Guinée
UPDATE pays SET cintprefix = '245' WHERE cisopays = 'GNB'; -- Guinée-Bissau
UPDATE pays SET cintprefix = '592' WHERE cisopays = 'GUY'; -- Guyana
UPDATE pays SET cintprefix = '509' WHERE cisopays = 'HTI'; -- Haïti
UPDATE pays SET cintprefix = '504' WHERE cisopays = 'HND'; -- Honduras
UPDATE pays SET cintprefix = '36' WHERE cisopays = 'HUN'; -- Hongrie
UPDATE pays SET cintprefix = '354' WHERE cisopays = 'ISL'; -- aidbe
UPDATE pays SET cintprefix = '91' WHERE cisopays = 'IND'; -- Inde
UPDATE pays SET cintprefix = '62' WHERE cisopays = 'IDN'; -- Indonésie
UPDATE pays SET cintprefix = '98' WHERE cisopays = 'IRN'; -- Iran
UPDATE pays SET cintprefix = '964' WHERE cisopays = 'IRQ'; -- Irak
UPDATE pays SET cintprefix = '353' WHERE cisopays = 'IRL'; -- Irlande
UPDATE pays SET cintprefix = '972' WHERE cisopays = 'ISR'; -- Israël
UPDATE pays SET cintprefix = '39' WHERE cisopays = 'ITA'; -- Italie
UPDATE pays SET cintprefix = '1876' WHERE cisopays = 'JAM'; -- Jamaïque
UPDATE pays SET cintprefix = '81' WHERE cisopays = 'JPN'; -- Japon
UPDATE pays SET cintprefix = '962' WHERE cisopays = 'JOR'; -- Jordanie
UPDATE pays SET cintprefix = '7' WHERE cisopays = 'KAZ'; -- Kazakhstan
UPDATE pays SET cintprefix = '254' WHERE cisopays = 'KEN'; -- Kenya
UPDATE pays SET cintprefix = '686' WHERE cisopays = 'KIR'; -- Kiribati
UPDATE pays SET cintprefix = '965' WHERE cisopays = 'KWT'; -- Koweït
UPDATE pays SET cintprefix = '996' WHERE cisopays = 'KGZ'; -- Kirghizistan
UPDATE pays SET cintprefix = '856' WHERE cisopays = 'LAO'; -- Laos
UPDATE pays SET cintprefix = '371' WHERE cisopays = 'LVA'; -- Lettonie
UPDATE pays SET cintprefix = '961' WHERE cisopays = 'LBN'; -- Liban
UPDATE pays SET cintprefix = '266' WHERE cisopays = 'LSO'; -- Lesotho
UPDATE pays SET cintprefix = '231' WHERE cisopays = 'LBR'; -- Libéria
UPDATE pays SET cintprefix = '218' WHERE cisopays = 'LBY'; -- Libye
UPDATE pays SET cintprefix = '423' WHERE cisopays = 'LIE'; -- Liechtenstein
UPDATE pays SET cintprefix = '370' WHERE cisopays = 'LTU'; -- Lituanie
UPDATE pays SET cintprefix = '352' WHERE cisopays = 'LUX'; -- Luxembourg
UPDATE pays SET cintprefix = '389' WHERE cisopays = 'MKD'; -- Macédoine du Nord
UPDATE pays SET cintprefix = '261' WHERE cisopays = 'MDG'; -- Madagascar
UPDATE pays SET cintprefix = '265' WHERE cisopays = 'MWI'; -- Malawi
UPDATE pays SET cintprefix = '60' WHERE cisopays = 'MYS'; -- Malaisie
UPDATE pays SET cintprefix = '960' WHERE cisopays = 'MDV'; -- Maldives
UPDATE pays SET cintprefix = '223' WHERE cisopays = 'MLI'; -- Mali
UPDATE pays SET cintprefix = '356' WHERE cisopays = 'MLT'; -- Malte
UPDATE pays SET cintprefix = '692' WHERE cisopays = 'MHL'; -- Îles Marshall
UPDATE pays SET cintprefix = '222' WHERE cisopays = 'MRT'; -- Mauritanie
UPDATE pays SET cintprefix = '230' WHERE cisopays = 'MUS'; -- Maurice
UPDATE pays SET cintprefix = '52' WHERE cisopays = 'MEX'; -- Mexique
UPDATE pays SET cintprefix = '691' WHERE cisopays = 'FSM'; -- États fédérés de Micronésie
UPDATE pays SET cintprefix = '373' WHERE cisopays = 'MDA'; -- Moldavie
UPDATE pays SET cintprefix = '377' WHERE cisopays = 'MCO'; -- Monaco
UPDATE pays SET cintprefix = '976' WHERE cisopays = 'MNG'; -- Mongolie
UPDATE pays SET cintprefix = '382' WHERE cisopays = 'MNE'; -- Monténégro
UPDATE pays SET cintprefix = '212' WHERE cisopays = 'MAR'; -- Maroc
UPDATE pays SET cintprefix = '258' WHERE cisopays = 'MOZ'; -- Mozambique
UPDATE pays SET cintprefix = '95' WHERE cisopays = 'MMR'; -- Myanmar (Birmanie)
UPDATE pays SET cintprefix = '264' WHERE cisopays = 'NAM'; -- Namibie
UPDATE pays SET cintprefix = '674' WHERE cisopays = 'NRU'; -- Nauru
UPDATE pays SET cintprefix = '977' WHERE cisopays = 'NPL'; -- Népal
UPDATE pays SET cintprefix = '31' WHERE cisopays = 'NLD'; -- Pays-Bas
UPDATE pays SET cintprefix = '687' WHERE cisopays = 'NCL'; -- Nouvelle-Calédonie
UPDATE pays SET cintprefix = '64' WHERE cisopays = 'NZL'; -- Nouvelle-Zélande
UPDATE pays SET cintprefix = '505' WHERE cisopays = 'NIC'; -- Nicaragua
UPDATE pays SET cintprefix = '227' WHERE cisopays = 'NER'; -- Niger
UPDATE pays SET cintprefix = '234' WHERE cisopays = 'NGA'; -- Nigéria
UPDATE pays SET cintprefix = '683' WHERE cisopays = 'NIU'; -- Niue
UPDATE pays SET cintprefix = '850' WHERE cisopays = 'PRK'; -- Corée du Nord
UPDATE pays SET cintprefix = '47' WHERE cisopays = 'NOR'; -- Norvège
UPDATE pays SET cintprefix = '968' WHERE cisopays = 'OMN'; -- Oman
UPDATE pays SET cintprefix = '92' WHERE cisopays = 'PAK'; -- Pakistan
UPDATE pays SET cintprefix = '680' WHERE cisopays = 'PLW'; -- Palaos
UPDATE pays SET cintprefix = '970' WHERE cisopays = 'PSE'; -- Palestine
UPDATE pays SET cintprefix = '507' WHERE cisopays = 'PAN'; -- Panama
UPDATE pays SET cintprefix = '675' WHERE cisopays = 'PNG'; -- Papouasie-Nouvelle-Guinée
UPDATE pays SET cintprefix = '595' WHERE cisopays = 'PRY'; -- Paraguay
UPDATE pays SET cintprefix = '51' WHERE cisopays = 'PER'; -- Pérou
UPDATE pays SET cintprefix = '63' WHERE cisopays = 'PHL'; -- Philippines
UPDATE pays SET cintprefix = '48' WHERE cisopays = 'POL'; -- Pologne
UPDATE pays SET cintprefix = '351' WHERE cisopays = 'PRT'; -- Portugal
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'PRI'; -- Porto Rico
UPDATE pays SET cintprefix = '974' WHERE cisopays = 'QAT'; -- Qatar
UPDATE pays SET cintprefix = '40' WHERE cisopays = 'ROU'; -- Roumanie
UPDATE pays SET cintprefix = '7' WHERE cisopays = 'RUS'; -- Russie
UPDATE pays SET cintprefix = '250' WHERE cisopays = 'RWA'; -- Rwanda
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'KNA'; -- Saint-Christophe-et-Niévès
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'LCA'; -- Sainte-Lucie
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'VCT'; -- Saint-Vincent-et-les-Grenadines
UPDATE pays SET cintprefix = '685' WHERE cisopays = 'WSM'; -- Samoa
UPDATE pays SET cintprefix = '378' WHERE cisopays = 'SMR'; -- Saint-Marin
UPDATE pays SET cintprefix = '239' WHERE cisopays = 'STP'; -- Sao Tomé-et-Principe
UPDATE pays SET cintprefix = '966' WHERE cisopays = 'SAU'; -- Arabie saoudite
UPDATE pays SET cintprefix = '221' WHERE cisopays = 'SEN'; -- Sénégal
UPDATE pays SET cintprefix = '381' WHERE cisopays = 'SRB'; -- Serbie
UPDATE pays SET cintprefix = '248' WHERE cisopays = 'SYC'; -- Seychelles
UPDATE pays SET cintprefix = '232' WHERE cisopays = 'SLE'; -- Sierra Leone
UPDATE pays SET cintprefix = '65' WHERE cisopays = 'SGP'; -- Singapour
UPDATE pays SET cintprefix = '421' WHERE cisopays = 'SVK'; -- Slovaquie
UPDATE pays SET cintprefix = '386' WHERE cisopays = 'SVN'; -- Slovénie
UPDATE pays SET cintprefix = '252' WHERE cisopays = 'SOM'; -- Somalie
UPDATE pays SET cintprefix = '27' WHERE cisopays = 'ZAF'; -- Afrique du Sud
UPDATE pays SET cintprefix = '82' WHERE cisopays = 'KOR'; -- Corée du Sud
UPDATE pays SET cintprefix = '34' WHERE cisopays = 'ESP'; -- Espagne
UPDATE pays SET cintprefix = '94' WHERE cisopays = 'LKA'; -- Sri Lanka

UPDATE pays SET cintprefix = '249' WHERE cisopays = 'SDN'; -- Soudan
UPDATE pays SET cintprefix = '597' WHERE cisopays = 'SUR'; -- Suriname
UPDATE pays SET cintprefix = '268' WHERE cisopays = 'SWZ'; -- Eswatini
UPDATE pays SET cintprefix = '46' WHERE cisopays = 'SWE'; -- Suède
UPDATE pays SET cintprefix = '41' WHERE cisopays = 'CHE'; -- Suisse
UPDATE pays SET cintprefix = '963' WHERE cisopays = 'SYR'; -- Syrie
UPDATE pays SET cintprefix = '886' WHERE cisopays = 'TWN'; -- Taïwan
UPDATE pays SET cintprefix = '992' WHERE cisopays = 'TJK'; -- Tadjikistan
UPDATE pays SET cintprefix = '255' WHERE cisopays = 'TZA'; -- Tanzanie
UPDATE pays SET cintprefix = '66' WHERE cisopays = 'THA'; -- Thaïlande
UPDATE pays SET cintprefix = '228' WHERE cisopays = 'TGO'; -- Togo
UPDATE pays SET cintprefix = '676' WHERE cisopays = 'TON'; -- Tonga
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'TTO'; -- Trinité-et-Tobago
UPDATE pays SET cintprefix = '216' WHERE cisopays = 'TUN'; -- Tunisie
UPDATE pays SET cintprefix = '993' WHERE cisopays = 'TKM'; -- Turkménistan
UPDATE pays SET cintprefix = '90' WHERE cisopays = 'TUR'; -- Turquie
UPDATE pays SET cintprefix = '256' WHERE cisopays = 'UGA'; -- Ouganda
UPDATE pays SET cintprefix = '380' WHERE cisopays = 'UKR'; -- Ukraine
UPDATE pays SET cintprefix = '971' WHERE cisopays = 'ARE'; -- Émirats arabes unis
UPDATE pays SET cintprefix = '44' WHERE cisopays = 'GBR'; -- Royaume-Uni

UPDATE pays SET cintprefix = '598' WHERE cisopays = 'URY'; -- Uruguay
UPDATE pays SET cintprefix = '998' WHERE cisopays = 'UZB'; -- Ouzbékistan
UPDATE pays SET cintprefix = '678' WHERE cisopays = 'VUT'; -- Vanuatu
UPDATE pays SET cintprefix = '58' WHERE cisopays = 'VEN'; -- Venezuela
UPDATE pays SET cintprefix = '84' WHERE cisopays = 'VNM'; -- Vietnam
UPDATE pays SET cintprefix = '967' WHERE cisopays = 'YEM'; -- Yémen
UPDATE pays SET cintprefix = '260' WHERE cisopays = 'ZMB'; -- Zambie
UPDATE pays SET cintprefix = '263' WHERE cisopays = 'ZWE'; -- Zimbabwe
UPDATE pays SET cintprefix = '383' WHERE cisopays = 'XKX'; -- Kosovo
UPDATE pays SET cintprefix = '1' WHERE cisopays = 'USA'; -- États-Unis
UPDATE pays SET cintprefix = '39' WHERE cisopays = 'ITA'; -- Italie
UPDATE pays SET cintprefix = '33' WHERE cisopays = 'FRA'; -- France
UPDATE pays SET cintprefix = '49' WHERE cisopays = 'DEU'; -- Allemagne
UPDATE pays SET cintprefix = '7' WHERE cisopays = 'RUS'; -- Russie
UPDATE pays SET cintprefix = '81' WHERE cisopays = 'JPN'; -- Japon

UPDATE pays SET cintprefix = '34' WHERE cisopays = 'ESP'; -- Espagne
UPDATE pays SET cintprefix = '44' WHERE cisopays = 'GBR'; -- Royaume-Uni
UPDATE pays SET cintprefix = '61' WHERE cisopays = 'AUS'; -- Australie
UPDATE pays SET cintprefix = '55' WHERE cisopays = 'BRA'; -- Brésil
UPDATE pays SET cintprefix = '82' WHERE cisopays = 'KOR'; -- Corée du Sud
UPDATE pays SET cintprefix = '90' WHERE cisopays = 'TUR'; -- Turquie
UPDATE pays SET cintprefix = '91' WHERE cisopays = 'IND'; -- Inde
UPDATE pays SET cintprefix = '62' WHERE cisopays = 'IDN'; -- Indonésie
UPDATE pays SET cintprefix = '60' WHERE cisopays = 'MYS'; -- Malaisie
UPDATE pays SET cintprefix = '63' WHERE cisopays = 'PHL'; -- Philippines
UPDATE pays SET cintprefix = '27' WHERE cisopays = 'ZAF'; -- Afrique du Sud
UPDATE pays SET cintprefix = '52' WHERE cisopays = 'MEX'; -- Mexique
UPDATE pays SET cintprefix = '51' WHERE cisopays = 'PER'; -- Pérou
UPDATE pays SET cintprefix = '32' WHERE cisopays = 'BEL'; -- Belgique
UPDATE pays SET cintprefix = '31' WHERE cisopays = 'NLD'; -- Pays-Bas

UPDATE pays SET cintprefix = '64' WHERE cisopays = 'NZL'; -- Nouvelle-Zélande
UPDATE pays SET cintprefix = '39' WHERE cisopays = 'ITA'; -- Italie
UPDATE pays SET cintprefix = '49' WHERE cisopays = 'DEU'; -- Allemagne
UPDATE pays SET cintprefix = '81' WHERE cisopays = 'JPN'; -- Japon
UPDATE pays SET cintprefix = '46' WHERE cisopays = 'SWE'; -- Suède
UPDATE pays SET cintprefix = '47' WHERE cisopays = 'NOR'; -- Norvège
UPDATE pays SET cintprefix = '45' WHERE cisopays = 'DNK'; -- Danemark
UPDATE pays SET cintprefix = '358' WHERE cisopays = 'FIN'; -- Finlande
UPDATE pays SET cintprefix = '353' WHERE cisopays = 'IRL'; -- Irlande
UPDATE pays SET cintprefix = '43' WHERE cisopays = 'AUT'; -- Autriche
UPDATE pays SET cintprefix = '48' WHERE cisopays = 'POL'; -- Pologne
UPDATE pays SET cintprefix = '420' WHERE cisopays = 'CZE'; -- République Tchèque
UPDATE pays SET cintprefix = '36' WHERE cisopays = 'HUN'; -- Hongrie
UPDATE pays SET cintprefix = '40' WHERE cisopays = 'ROU'; -- Roumanie
UPDATE pays SET cintprefix = '381' WHERE cisopays = 'SRB'; -- Serbie

UPDATE pays SET cintprefix = '65' WHERE cisopays = 'SGP'; -- Singapour
UPDATE pays SET cintprefix = '66' WHERE cisopays = 'THA'; -- Thaïlande
UPDATE pays SET cintprefix = '91' WHERE cisopays = 'IND'; -- Inde
UPDATE pays SET cintprefix = '92' WHERE cisopays = 'PAK'; -- Pakistan
UPDATE pays SET cintprefix = '972' WHERE cisopays = 'ISR'; -- Israël
UPDATE pays SET cintprefix = '966' WHERE cisopays = 'SAU'; -- Arabie Saoudite
UPDATE pays SET cintprefix = '98' WHERE cisopays = 'IRN'; -- Iran
UPDATE pays SET cintprefix = '20' WHERE cisopays = 'EGY'; -- Égypte
UPDATE pays SET cintprefix = '84' WHERE cisopays = 'VNM'; -- Viêt Nam
UPDATE pays SET cintprefix = '7' WHERE cisopays = 'RUS'; -- Russie
UPDATE pays SET cintprefix = '55' WHERE cisopays = 'BRA'; -- Brésil
UPDATE pays SET cintprefix = '54' WHERE cisopays = 'ARG'; -- Argentine
UPDATE pays SET cintprefix = '52' WHERE cisopays = 'MEX'; -- Mexique
UPDATE pays SET cintprefix = '27' WHERE cisopays = 'ZAF'; -- Afrique du Sud
UPDATE pays SET cintprefix = '234' WHERE cisopays = 'NGA'; -- Nigeria
UPDATE pays SET cintprefix = '61' WHERE cisopays = 'AUS'; -- Australie
UPDATE pays SET cintprefix = '64' WHERE cisopays = 'NZL'; -- Nouvelle-Zélande
UPDATE pays SET cintprefix = '62' WHERE cisopays = 'IDN'; -- Indonésie
UPDATE pays SET cintprefix = '60' WHERE cisopays = 'MYS'; -- Malaisie
UPDATE pays SET cintprefix = '63' WHERE cisopays = 'PHL'; -- Philippines
UPDATE pays SET cintprefix = '81' WHERE cisopays = 'JPN'; -- Japon
UPDATE pays SET cintprefix = '82' WHERE cisopays = 'KOR'; -- Corée du Sud
UPDATE pays SET cintprefix = '880' WHERE cisopays = 'BGD'; -- Bangladesh
UPDATE pays SET cintprefix = '93' WHERE cisopays = 'AFG'; -- Afghanistan
UPDATE pays SET cintprefix = '94' WHERE cisopays = 'LKA'; -- Sri Lanka
UPDATE pays SET cintprefix = '95' WHERE cisopays = 'MMR'; -- Myanmar (Birmanie)
UPDATE pays SET cintprefix = '971' WHERE cisopays = 'ARE'; -- Émirats arabes unis
UPDATE pays SET cintprefix = '967' WHERE cisopays = 'YEM'; -- Yémen
UPDATE pays SET cintprefix = '968' WHERE cisopays = 'OMN'; -- Oman
UPDATE pays SET cintprefix = '974' WHERE cisopays = 'QAT'; -- Qatar

UPDATE pays SET cintprefix = '973' WHERE cisopays = 'BHR'; -- Bahreïn
UPDATE pays SET cintprefix = '965' WHERE cisopays = 'KWT'; -- Koweït
UPDATE pays SET cintprefix = '961' WHERE cisopays = 'LBN'; -- Liban
UPDATE pays SET cintprefix = '962' WHERE cisopays = 'JOR'; -- Jordanie
UPDATE pays SET cintprefix = '90' WHERE cisopays = 'TUR'; -- Turquie
UPDATE pays SET cintprefix = '964' WHERE cisopays = 'IRQ'; -- Irak
UPDATE pays SET cintprefix = '966' WHERE cisopays = 'SAU'; -- Arabie saoudite
UPDATE pays SET cintprefix = '91' WHERE cisopays = 'IND'; -- Inde
UPDATE pays SET cintprefix = '92' WHERE cisopays = 'PAK'; -- Pakistan
UPDATE pays SET cintprefix = '977' WHERE cisopays = 'NPL'; -- Népal
UPDATE pays SET cintprefix = '975' WHERE cisopays = 'BTN'; -- Bhoutan
UPDATE pays SET cintprefix = '960' WHERE cisopays = 'MDV'; -- Maldives
UPDATE pays SET cintprefix = '993' WHERE cisopays = 'TKM'; -- Turkménistan
UPDATE pays SET cintprefix = '998' WHERE cisopays = 'UZB'; -- Ouzbékistan
UPDATE pays SET cintprefix = '996' WHERE cisopays = 'KGZ'; -- Kirghizistan
UPDATE pays SET cintprefix = '992' WHERE cisopays = 'TJK'; -- Tadjikistan
UPDATE pays SET cintprefix = '968' WHERE cisopays = 'OMN'; -- Oman
UPDATE pays SET cintprefix = '970' WHERE cisopays = 'PSE'; -- Palestine
UPDATE pays SET cintprefix = '972' WHERE cisopays = 'ISR'; -- Israël
UPDATE pays SET cintprefix = '357' WHERE cisopays = 'CYP'; -- Chypre
UPDATE pays SET cintprefix = '358' WHERE cisopays = 'FIN'; -- Finlande
UPDATE pays SET cintprefix = '354' WHERE cisopays = 'ISL'; -- aidbe
UPDATE pays SET cintprefix = '372' WHERE cisopays = 'EST'; -- Estonie
UPDATE pays SET cintprefix = '370' WHERE cisopays = 'LTU'; -- Lituanie
UPDATE pays SET cintprefix = '371' WHERE cisopays = 'LVA'; -- Lettonie
UPDATE pays SET cintprefix = '373' WHERE cisopays = 'MDA'; -- Moldavie
UPDATE pays SET cintprefix = '375' WHERE cisopays = 'BLR'; -- Biélorussie
UPDATE pays SET cintprefix = '359' WHERE cisopays = 'BGR'; -- Bulgarie
UPDATE pays SET cintprefix = '356' WHERE cisopays = 'MLT'; -- Malte
UPDATE pays SET cintprefix = '355' WHERE cisopays = 'ALB'; -- Albanie
UPDATE pays SET cintprefix = '385' WHERE cisopays = 'HRV'; -- Croatie
UPDATE pays SET cintprefix = '387' WHERE cisopays = 'BIH'; -- Bosnie-Herzégovine
UPDATE pays SET cintprefix = '382' WHERE cisopays = 'MNE'; -- Monténégro
UPDATE pays SET cintprefix = '381' WHERE cisopays = 'SRB'; -- Serbie
UPDATE pays SET cintprefix = '389' WHERE cisopays = 'MKD'; -- Macédoine du Nord
UPDATE pays SET cintprefix = '386' WHERE cisopays = 'SVN'; -- Slovénie
UPDATE pays SET cintprefix = '43' WHERE cisopays = 'AUT'; -- Autriche
UPDATE pays SET cintprefix = '48' WHERE cisopays = 'POL'; -- Pologne
UPDATE pays SET cintprefix = '420' WHERE cisopays = 'CZE'; -- République tchèque
UPDATE pays SET cintprefix = '421' WHERE cisopays = 'SVK'; -- Slovaquie
UPDATE pays SET cintprefix = '36' WHERE cisopays = 'HUN'; -- Hongrie
UPDATE pays SET cintprefix = '40' WHERE cisopays = 'ROU'; -- Roumanie
UPDATE pays SET cintprefix = '373' WHERE cisopays = 'MDA'; -- Moldavie
UPDATE pays SET cintprefix = '995' WHERE cisopays = 'GEO'; -- Géorgie
UPDATE pays SET cintprefix = '374' WHERE cisopays = 'ARM'; -- Arménie
UPDATE pays SET cintprefix = '994' WHERE cisopays = 'AZE'; -- Azerbaïdjan
UPDATE pays SET cintprefix = '39' WHERE cisopays = 'ITA'; -- Italie
UPDATE pays SET cintprefix = '357' WHERE cisopays = 'CYP'; -- Chypre
UPDATE pays SET cintprefix = '34' WHERE cisopays = 'ESP'; -- Espagne
UPDATE pays SET cintprefix = '351' WHERE cisopays = 'PRT'; -- Portugal
UPDATE pays SET cintprefix = '350' WHERE cisopays = 'GIB'; -- Gibraltar
UPDATE pays SET cintprefix = '377' WHERE cisopays = 'MCO'; -- Monaco
UPDATE pays SET cintprefix = '41' WHERE cisopays = 'CHE'; -- Suisse
UPDATE pays SET cintprefix = '33' WHERE cisopays = 'FRA'; -- France
UPDATE pays SET cintprefix = '32' WHERE cisopays = 'BEL'; -- Belgique
UPDATE pays SET cintprefix = '31' WHERE cisopays = 'NLD'; -- Pays-Bas
UPDATE pays SET cintprefix = '352' WHERE cisopays = 'LUX'; -- Luxembourg
UPDATE pays SET cintprefix = '49' WHERE cisopays = 'DEU'; -- Allemagne
UPDATE pays SET cintprefix = '44' WHERE cisopays = 'GBR'; -- Royaume-Uni
UPDATE pays SET cintprefix = '45' WHERE cisopays = 'DNK'; -- Danemark
UPDATE pays SET cintprefix = '46' WHERE cisopays = 'SWE'; -- Suède
UPDATE pays SET cintprefix = '47' WHERE cisopays = 'NOR'; -- Norvège
UPDATE pays SET cintprefix = '298' WHERE cisopays = 'FRO'; -- Îles Féroé
UPDATE pays SET cintprefix = '354' WHERE cisopays = 'ISL'; -- aidbe
UPDATE pays SET cintprefix = '353' WHERE cisopays = 'IRL'; -- Irlande

UPDATE pays SET cintprefix = '358' WHERE cisopays = 'FIN'; -- Finlande
UPDATE pays SET cintprefix = '370' WHERE cisopays = 'LTU'; -- Lituanie
UPDATE pays SET cintprefix = '371' WHERE cisopays = 'LVA'; -- Lettonie
UPDATE pays SET cintprefix = '372' WHERE cisopays = 'EST'; -- Estonie
UPDATE pays SET cintprefix = '375' WHERE cisopays = 'BLR'; -- Bélarus
UPDATE pays SET cintprefix = '380' WHERE cisopays = 'UKR'; -- Ukraine
UPDATE pays SET cintprefix = '90' WHERE cisopays = 'TUR'; -- Turquie
UPDATE pays SET cintprefix = '30' WHERE cisopays = 'GRC'; -- Grèce
UPDATE pays SET cintprefix = '356' WHERE cisopays = 'MLT'; -- Malte
UPDATE pays SET cintprefix = '212' WHERE cisopays = 'MAR'; -- Maroc
UPDATE pays SET cintprefix = '213' WHERE cisopays = 'DZA'; -- Algérie
UPDATE pays SET cintprefix = '216' WHERE cisopays = 'TUN'; -- Tunisie
UPDATE pays SET cintprefix = '218' WHERE cisopays = 'LBY'; -- Libye
UPDATE pays SET cintprefix = '220' WHERE cisopays = 'GMB'; -- Gambie
UPDATE pays SET cintprefix = '221' WHERE cisopays = 'SEN'; -- Sénégal
UPDATE pays SET cintprefix = '222' WHERE cisopays = 'MRT'; -- Mauritanie
UPDATE pays SET cintprefix = '223' WHERE cisopays = 'MLI'; -- Mali

UPDATE pays SET cintprefix = '386' WHERE cisopays = 'SVN'; -- Slovénie
UPDATE pays SET cintprefix = '387' WHERE cisopays = 'BIH'; -- Bosnie-Herzégovine
UPDATE pays SET cintprefix = '389' WHERE cisopays = 'MKD'; -- Macédoine du Nord
UPDATE pays SET cintprefix = '385' WHERE cisopays = 'HRV'; -- Croatie
UPDATE pays SET cintprefix = '423' WHERE cisopays = 'LIE'; -- Liechtenstein
UPDATE pays SET cintprefix = '352' WHERE cisopays = 'LUX'; -- Luxembourg
UPDATE pays SET cintprefix = '350' WHERE cisopays = 'GIB'; -- Gibraltar
UPDATE pays SET cintprefix = '373' WHERE cisopays = 'MDA'; -- Moldavie
UPDATE pays SET cintprefix = '377' WHERE cisopays = 'MCO'; -- Monaco
UPDATE pays SET cintprefix = '354' WHERE cisopays = 'ISL'; -- aidbe
UPDATE pays SET cintprefix = '382' WHERE cisopays = 'MNE'; -- Monténégro
UPDATE pays SET cintprefix = '976' WHERE cisopays = 'MNG'; -- Mongolie
UPDATE pays SET cintprefix = '855' WHERE cisopays = 'KHM'; -- Cambodge
UPDATE pays SET cintprefix = '856' WHERE cisopays = 'LAO'; -- Laos
UPDATE pays SET cintprefix = '960' WHERE cisopays = 'MDV'; -- Maldives
UPDATE pays SET cintprefix = '961' WHERE cisopays = 'LBN'; -- Liban



-- ... et ainsi de suite pour les autres pays.






CREATE OR REPLACE FUNCTION public.f_validateupdatehisto (
)
RETURNS trigger AS
$body$
    -- Trigger permettant de valider le droit pour modifierun historique
    declare
     isentitled utilisateuragence.bupdatehisto%TYPE ;

    begin
      IF NEW.lusername = current_user THEN
      -- accepte une modification par son auteur 
          return NEW;
      ELSE
            SELECT INTO isentitled bupdatehisto FROM utilisateuragence WHERE lusername = current_user and cagence = OLD.cagence ;

            if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin'  OR (OLD.lusername = current_user and OLD.ntyprelation = 22) then
              return NEW;
            Else
              RAISE EXCEPTION 'Privilèges insuffisants pour modifier un historique !';
            End if;
      END IF;    
    end;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT
COST 100;


  
CREATE OR REPLACE FUNCTION public.f_validateupdateproprio()
  RETURNS trigger AS
$BODY$
    -- Trigger permettant de valider le droit pour modifier un propriétaire
    declare
     isentitled utilisateuragence.bupdateproprio%TYPE ;

    begin
      
	IF NEW.lusername = current_user THEN
		-- accepte une modification par son auteur 
		     return NEW;
	ELSE

	      SELECT INTO isentitled bupdateproprio FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

	      if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin' then
		return NEW;
	      Else
		RAISE EXCEPTION  'Droits insuffisants pour modifier un propriétaire (cagence:%)',  NEW.cagence   ;
	      End if;
	END IF;

    end;

    $BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 100;




CREATE OR REPLACE FUNCTION public.f_validateupdatebien()
RETURNS trigger AS
$BODY$
DECLARE
    isentitled utilisateuragence.bupdatebien%TYPE;
BEGIN
    -- Vérifier d'abord si la table est 'bien'
    IF TG_TABLE_NAME = 'bien' THEN
        -- Si la table est 'bien', vérifier ensuite l'utilisateur
        IF OLD.lusername = current_user AND NEW.lusername = current_user  THEN
            -- Accepter une modification par son auteur
            RETURN NEW;
        END IF;
    END IF;

    -- Le code suivant s'exécutera seulement si la table n'est pas 'bien' ou si NEW.lusername n'est pas current_user
    SELECT INTO isentitled bupdatebien FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL);

    IF isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin' THEN
        RETURN NEW;
    ELSE
        RAISE EXCEPTION 'Droits insuffisants pour modifier un bien (cagence:%)', NEW.cagence;
    END IF;

    RETURN NULL; -- Ajouté pour la clarté, bien que facultatif
END;
$BODY$
LANGUAGE plpgsql IMMUTABLE
COST 100;



CREATE OR REPLACE FUNCTION public.f_validateupdatedoc (
)
RETURNS trigger AS
$body$
    -- Trigger permettant de valider le droit de modifier un document avec d'accepter
    declare
     isentitled utilisateuragence.bupdatedoc%TYPE ;

    begin

      IF NEW.cusercre = current_user OR NEW.cusermod = current_user THEN
        -- accepte une modification par son auteur 
            return NEW;
      ELSE
            SELECT INTO isentitled bupdatedoc FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

            if isentitled = 1 OR current_user =  'postgres'  OR current_user =  'admin' then
              return NEW;
            Else
              RAISE EXCEPTION  'Droits insuffisants pour modifier un document (cagence:%)',  NEW.cagence   ;
            End if;
        END IF;
        
    end;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT
COST 100;




CREATE OR REPLACE FUNCTION  f_todo_detailtrigger()
RETURNS TRIGGER AS $$
DECLARE
    v_blinkid INT;
    v_cnt INT;
    v_ndetailtrigger INT;
    v_cagence TEXT;
   --v_table_name TEXT;
BEGIN
    -- Vérifier l'existence du ndetail dans la table 'detail'
    SELECT ndetailtrigger INTO v_ndetailtrigger FROM detail WHERE ndetail = NEW.ndetail ; 

    IF v_ndetailtrigger IS NULL THEN
        RETURN NEW;
    END IF;


    -- Obtenir blinkid et btache du typdetail correspondant
    SELECT blinkid INTO v_blinkid
    FROM typdetail
    JOIN detail ON detail.ntypdetail = typdetail.ntypdetail
    WHERE detail.ndetail = NEW.ndetail;

    -- Obtenir blinkid et btache du typdetail correspondant
    SELECT ndetailtrigger INTO v_ndetailtrigger
    FROM detail
    WHERE detail.ndetail = NEW.ndetail;

    -- Obtenir cagence de l'utilisateur courant
    SELECT cagence INTO v_cagence
    FROM utilisateur
    WHERE lusername = current_user
    LIMIT 1;




    IF v_blinkid = 0 THEN

	IF NEW.nbien > 0 THEN 
		SELECT count(*) INTO v_cnt
		FROM detailbien
		WHERE nbien = NEW.nbien and ndetail = NEW.ndetail;
	    
		IF v_cnt = 0 THEN
			INSERT INTO detailbien (ndetail, cagence, nbien)
			VALUES (NEW.ndetail, v_cagence, NEW.nbien);
		END IF ;
	END IF ;

	
    ELSIF v_blinkid = 1 THEN
	IF NEW.nprospect > 0 THEN 
		SELECT count(*) INTO v_cnt
		FROM detailprospect
		WHERE nprospect = NEW.nprospect and ndetail = NEW.ndetail;

		IF v_cnt = 0 THEN
			INSERT INTO detailprospect (ndetail, cagence, nprospect)
			VALUES (NEW.ndetail, v_cagence, NEW.nprospect);
		END IF;

	END IF ;
    ELSE
        RETURN NEW;
    END IF;

    -- Exécuter l'insertion dynamique
    --EXECUTE format('INSERT INTO %I (ndetail, cagence,nbien,nprospect) VALUES ($1, $2)', v_table_name)
   -- USING NEW.ndetail, v_cagence;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS tai_todo_ndetailtrigger ON todo;
CREATE TRIGGER tai_todo_ndetailtrigger
AFTER INSERT ON todo
FOR EACH ROW
EXECUTE PROCEDURE f_todo_detailtrigger();

--ALTER TABLE typrelation ADD COLUMN ndetailtrigger int;

CREATE OR REPLACE FUNCTION  f_prospectbien_detailtrigger()
RETURNS TRIGGER AS $$
DECLARE
    v_blinkid INT;
    v_cnt INT;
    v_ndetailtrigger INT;
    v_cagence TEXT;
   --v_table_name TEXT;
BEGIN
    -- Vérifier l'existence du ndetail dans la table 'detail'
    SELECT ndetailtrigger INTO v_ndetailtrigger FROM typrelation WHERE ntyprelation = NEW.ntyprelation ; 

    IF v_ndetailtrigger IS NULL THEN
        RETURN NEW;
    END IF;


    -- Obtenir blinkid et btache du typdetail correspondant
    SELECT blinkid INTO v_blinkid
    FROM typdetail
    JOIN detail ON detail.ntypdetail = typdetail.ntypdetail
    WHERE detail.ndetail = v_ndetailtrigger;


    -- Obtenir cagence de l'utilisateur courant
    SELECT cagence INTO v_cagence
    FROM utilisateur
    WHERE lusername = current_user
    LIMIT 1;

   
    IF v_blinkid = 0 THEN

      IF NEW.nbien > 0 THEN 
        SELECT count(*) INTO v_cnt
        FROM detailbien
        WHERE nbien = NEW.nbien AND ndetail = v_ndetailtrigger;
          
        IF v_cnt = 0 THEN
          INSERT INTO detailbien (ndetail, cagence, nbien)
          VALUES (v_ndetailtrigger, v_cagence, NEW.nbien);
        END IF ;
      END IF ;
	
    ELSIF v_blinkid = 1 THEN

      IF NEW.nprospect > 0 THEN 

        SELECT count(*) INTO v_cnt
        FROM detailprospect
        WHERE nprospect = NEW.nprospect AND ndetail = v_ndetailtrigger;

        IF v_cnt = 0 THEN


--RAISE EXCEPTION 'Message d''erreur2 : blinkid%, ndetailtrigger% nprospect% cagence%', v_blinkid, v_ndetailtrigger , NEW.nprospect, v_cagence;

          INSERT INTO detailprospect (ndetail, cagence, nprospect)
          VALUES (v_ndetailtrigger, v_cagence, NEW.nprospect);
        END IF;

	END IF ;
    ELSE
        RETURN NEW;
    END IF;

    -- Exécuter l'insertion dynamique
    --EXECUTE format('INSERT INTO %I (ndetail, cagence,nbien,nprospect) VALUES ($1, $2)', v_table_name)
   -- USING NEW.ndetail, v_cagence;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;


DROP TRIGGER IF EXISTS tai_prospectbien_ndetailtrigger ON prospectbien_t;
CREATE TRIGGER tai_prospectbien_ndetailtrigger
AFTER INSERT ON prospectbien_t
FOR EACH ROW
EXECUTE PROCEDURE f_prospectbien_detailtrigger();





--dénormalisation de la table prospectbien (perme)

CREATE OR REPLACE FUNCTION f_prospectbien_bienexclu()
RETURNS TRIGGER AS $$
BEGIN
  -- Vérifier si ninteret = -1, ntyprelation = 70 et s'il n'existe pas déjà un enregistrement pour le même nbien et nprospect
  IF (NEW.ninteret = -1 AND NEW.ntyprelation = 70) THEN
    IF NOT EXISTS (
      SELECT 1
      FROM prospectbien
      WHERE nbien = NEW.nbien AND nprospect = NEW.nprospect
    ) THEN
      -- Insérer un nouvel enregistrement avec les valeurs spécifiées
      INSERT INTO prospectbien (ntyprelation, nbien, nprospect, cagence, lusername)
      VALUES (18, NEW.nbien, NEW.nprospect, NEW.cagence, current_user);
    END IF;
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;




DROP TRIGGER IF EXISTS tai_prospectbien_bienexclu ON prospectbien_t; 
CREATE TRIGGER tai_prospectbien_bienexclu
AFTER INSERT ON prospectbien_t
FOR EACH ROW
EXECUTE PROCEDURE f_prospectbien_bienexclu();


INSERT INTO typrelation (ntyprelation, ltyprelationfr, ltyprelationen)
VALUES (18, 'Bien à exclure du rapprochement', 'Property to be excluded')
ON CONFLICT (ntyprelation) DO NOTHING;


CREATE OR REPLACE FUNCTION f_format_currency(amount NUMERIC, currency_code TEXT)
RETURNS TEXT AS $$
DECLARE
    formatted_amount TEXT;
    currency_symbol TEXT;
    symbol_position TEXT DEFAULT 'before'; -- Default position is before the amount
BEGIN
    -- Define currency symbols for known currencies and their position
    CASE currency_code
        WHEN 'USD' THEN currency_symbol := '$';
        WHEN 'GBP' THEN currency_symbol := '£';
        WHEN 'JPY' THEN currency_symbol := '¥';
        WHEN 'EUR' THEN 
            BEGIN
                currency_symbol := '€';
                symbol_position := 'after'; -- For EUR, place the symbol after the amount
            END;
        WHEN 'MUR' THEN currency_symbol := '₨'; -- Mauritian Rupee symbol before the amount
        -- Add more currencies and adjust positions as needed
        ELSE 
            BEGIN
                currency_symbol := currency_symbol; -- Default case if currency is not recognized
                symbol_position := 'after';
            END;
    END CASE;

    -- Format the amount with two decimal places TO_CHAR(6565455456565, 'FM999 999 999 999 990') 
    formatted_amount := TO_CHAR(amount, 'FM999 999 999 999 990');

    -- Return the formatted amount with the currency symbol in the correct position
    IF symbol_position = 'before' THEN
        RETURN currency_symbol || formatted_amount;
    ELSE
        RETURN formatted_amount || ' ' || currency_symbol; -- Note the space before the currency symbol for readability
    END IF;
END;
$$ LANGUAGE plpgsql;


DO $do$
BEGIN
    -- Create table testimonials if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'testimonials') THEN
        CREATE TABLE IF NOT EXISTS testimonials (
          ntestimonials SERIAL PRIMARY KEY,
          ltitre TEXT DEFAULT NULL,
          lcontent TEXT DEFAULT NULL,
          lprenom VARCHAR(30) DEFAULT NULL,
          lnom VARCHAR(30) DEFAULT NULL,
          dpub DATE DEFAULT NULL,
          clangue VARCHAR(2) DEFAULT 'fr',
          bpub SMALLINT DEFAULT NULL
        );
    END IF;
END $do$;



DO $do$
BEGIN
    -- Create table htmlpage if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'htmlpage') THEN
        CREATE TABLE IF NOT EXISTS htmlpage (
          clangue CHAR(2) NOT NULL DEFAULT 'fr',
          ltitre VARCHAR(100) DEFAULT NULL,
          cusermod VARCHAR(10) DEFAULT NULL,
          cusercre VARCHAR(10) DEFAULT NULL,
          nhtmlpage SERIAL PRIMARY KEY,
          nordre INT DEFAULT NULL,
          dcre DATE DEFAULT NULL,
          dmod DATE DEFAULT NULL,
          lcontent TEXT DEFAULT NULL,
          nhtmlpageparent INT DEFAULT NULL,
          lurl VARCHAR(200) DEFAULT NULL,
          ctypmenu VARCHAR(25) DEFAULT NULL,
          lsection VARCHAR(200) DEFAULT NULL,
          lurlv4 VARCHAR(200) DEFAULT NULL,
          lfriendlyurl VARCHAR(250) DEFAULT NULL,
          cagence VARCHAR(10) DEFAULT NULL,
          lmetatitle VARCHAR(255) DEFAULT NULL,
          lmetakey TEXT DEFAULT NULL,
          lmetadesc TEXT DEFAULT NULL,
          bpub SMALLINT DEFAULT NULL,
          dpub TIMESTAMP DEFAULT current_timestamp
        );
    END IF;

    -- Add columns to htmlpage if they do not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'htmlpage' AND column_name = 'lurlv4') THEN
        ALTER TABLE public.htmlpage ADD COLUMN lurlv4 VARCHAR(200) DEFAULT NULL;
    END IF;
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'htmlpage' AND column_name = 'lfriendlyurl') THEN
        ALTER TABLE public.htmlpage ADD COLUMN lfriendlyurl VARCHAR(250) DEFAULT NULL;
    END IF;
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_schema = 'public' AND table_name = 'htmlpage' AND column_name = 'dpub') THEN
        ALTER TABLE public.htmlpage ADD COLUMN dpub TIMESTAMP DEFAULT current_timestamp;
    END IF;

    -- Create table news if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_name = 'news') THEN
        CREATE TABLE IF NOT EXISTS news (
          nnews SERIAL PRIMARY KEY,
          ltitre TEXT DEFAULT NULL,
          lcontent TEXT DEFAULT NULL,
          lprenom VARCHAR(30) DEFAULT NULL,
          lnom VARCHAR(30) DEFAULT NULL,
          dpub DATE DEFAULT NULL,
          clangue VARCHAR(2) DEFAULT 'fr',
          bpub SMALLINT DEFAULT NULL
        );
    END IF;

    -- Add column licskey to utilisateur if it does not exist and add unique constraint
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'utilisateur' AND column_name = 'licskey') THEN
        ALTER TABLE utilisateur ADD COLUMN licskey VARCHAR(255);
        ALTER TABLE utilisateur ADD CONSTRAINT licskey_unique UNIQUE (licskey);
    END IF;

    -- Add column qupdatecnt to prospectbien_t if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'qupdatecnt') THEN
        ALTER TABLE prospectbien_t ADD COLUMN qupdatecnt integer DEFAULT 0;
    END IF;
END $do$;



CREATE OR REPLACE FUNCTION public.fn_increment_updatecnt (
)
RETURNS trigger AS
$body$
BEGIN
    -- Vérifie si des modifications ont été apportées aux colonnes spécifiées
    IF OLD.lrem IS DISTINCT FROM NEW.lrem
       OR OLD.nprospect IS DISTINCT FROM NEW.nprospect
       OR OLD.nbien IS DISTINCT FROM NEW.nbien
       OR OLD.ddebut IS DISTINCT FROM NEW.ddebut
       OR OLD.dfin IS DISTINCT FROM NEW.dfin
       OR OLD.lvisite IS DISTINCT FROM NEW.lvisite
       OR OLD.lusername IS DISTINCT FROM NEW.lusername
    THEN
        -- Incrémente qupdatecnt si une modification a été détectée
        NEW.qupdatecnt := NEW.qupdatecnt + 1;
    END IF;
    
    -- Renvoie le nouvel enregistrement modifié pour mise à jour
    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;

ALTER FUNCTION public.fn_increment_updatecnt ()
  OWNER TO admin;

DROP TRIGGER IF EXISTS tbu_prospectbien_updatecnt_t ON prospectbien_t;
CREATE TRIGGER tbu_prospectbien_updatecnt_t
  BEFORE UPDATE 
  ON public.prospectbien_t
  
FOR EACH ROW 
  EXECUTE PROCEDURE public.fn_increment_updatecnt();






CREATE OR REPLACE FUNCTION public.f_validateinserthisto (
)
RETURNS trigger AS
$body$
-- Trigger permettant de valider le droit d'insérer un histo avec d'accepter
declare
 isentitled utilisateuragence.binserthisto%TYPE ;

begin

 if NEW.lusername = '' OR NEW.lusername IS NULL then
    NEW.lusername = current_user ;
End if;

 if NEW.cagence = '' OR NEW.cagence IS NULL then
    RAISE EXCEPTION 'Le code agence est manquant (utilisateur agence)';
else
  /* New function body */
  SELECT INTO isentitled binserthisto FROM utilisateuragence WHERE lusername = current_user and cagence = NEW.cagence ;

  if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin'  OR current_user = 'unsubscribe_usr' then
    return NEW;
  Else
    RAISE EXCEPTION  'Droits insuffisants pour ajouter un évènement (cagence:%  utilisateur:%)' , NEW.cagence  , current_user      ;
  End if;
End if;

end;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT

COST 100;




CREATE OR REPLACE FUNCTION public.f_validateupdateproprio (
)
RETURNS trigger AS
$body$
    -- Trigger permettant de valider le droit pour modifier un propriétaire
    declare
     isentitled utilisateuragence.bupdateproprio%TYPE ;

    begin
      
	IF NEW.lusername = current_user THEN
		-- accepte une modification par son auteur 
		     return NEW;
	ELSE

	      SELECT INTO isentitled bupdateproprio FROM utilisateuragence WHERE lusername = current_user and (cagence = OLD.cagence OR OLD.cagence IS NULL) ;

	      if isentitled = 1 OR current_user = 'postgres' OR current_user = 'admin' OR current_user = 'unsubscribe_usr' then
		return NEW;
	      Else
		RAISE EXCEPTION  'Droits insuffisants pour modifier un propriétaire (cagence:%)',  NEW.cagence   ;
	      End if;
	END IF;

    end;
$body$
LANGUAGE 'plpgsql'
IMMUTABLE
CALLED ON NULL INPUT

COST 100;





CREATE OR REPLACE FUNCTION public.f_build_select (
  t_row public.biencrit_t
)
RETURNS text AS
$body$
-- TBD chauffage, typmndat avec tranche prix liée
DECLARE
 critsql text ;
 ctyps text ;
 ctypmetas text ;
 cregions text ;
 cregionmetas text ;
 cenvironnements text ;
 cstyles text ;
 cnaturebiens text ;
 lcps text ;
 cchaufs text ;
 ndetails int ;
 ndetailsql text ;
 nprogrammesql text ;

 ctyps_arr      text[] ;
 ctypmetas_arr      text[] ;
 cregions_arr       text[] ;
 cregionmetas_arr      text[] ;
 cenvironnements_arr    text[] ;
 cstyles_arr     text[] ;
 lcps_arr        text[] ;
 ndetails_arr     int[] ;
 nprogrammes_arr     int[] ;

 cnaturebiens_arr     text[] ;

 ctyps_arr2      text[] ;
 ctypmetas_arr2      text[] ;
 cregions_arr2       text[] ;
 cregionmetas_arr2      text[] ;
 cenvironnements_arr2    text[] ;
 cstyles_arr2     text[] ;
 lcps_arr2        text[] ;
 lcpcond_arr  text[] ;
 lcpcond  text ;
 all_regions_or text ;
 lcp text ;
 ndetails_arr2     int[] ;
 cnaturebiens_arr2     text[] ;
 cchauf_arr2 text[] ;

 conditions_arr     text[] ;
 conditions1_arr     text[] ;
 conditions2_arr     text[] ;
 conditions1and2_arr text[] ;
 conditionsprix1_arr     text[] ;
 conditionsprix2_arr     text[] ;
 combined_ctyps_or_ctypmetas text;


 condition_itemprix1 text ;
 condition_itemprix2 text ;
 cchauf_arr text[];
 condition_item  text ;
 i int ;
 nrequesteddetail int;

BEGIN

-- Contruite des arrays avec toutes les séries de valeurs (ctyp&, ctyp2, cregion1, etc
ctyps_arr = ARRAY[t_row.ctyp1 ,t_row.ctyp2 ,t_row.ctyp3 ,t_row.ctyp4 ,t_row.ctyp5 ,t_row.ctyp6 ,t_row.ctyp7 ,t_row.ctyp8 ,t_row.ctyp9,t_row.ctyp10,t_row.ctyp11,t_row.ctyp12,t_row.ctyp13,t_row.ctyp14,t_row.ctyp15] ;

ctypmetas_arr = ARRAY[t_row.ctypmeta1 ,t_row.ctypmeta2 ,t_row.ctypmeta3 ,t_row.ctypmeta4 ,t_row.ctypmeta5 ,t_row.ctypmeta6 ,t_row.ctypmeta7 ,t_row.ctypmeta8 ,t_row.ctypmeta9,t_row.ctypmeta10,t_row.ctypmeta11,t_row.ctypmeta12,t_row.ctypmeta13,t_row.ctypmeta14,t_row.ctypmeta15] ;

cregions_arr = ARRAY[t_row.cregion1 ,t_row.cregion2 ,t_row.cregion3 ,t_row.cregion4 ,t_row.cregion5 ,t_row.cregion6 ,t_row.cregion7 ,t_row.cregion8 ,t_row.cregion9 ,t_row.cregion10,t_row.cregion11,t_row.cregion12,t_row.cregion13,t_row.cregion14,t_row.cregion15] ;

cregionmetas_arr = ARRAY[t_row.cregionmeta1 ,t_row.cregionmeta2 ,t_row.cregionmeta3 ,t_row.cregionmeta4 ,t_row.cregionmeta5 ,t_row.cregionmeta6 ,t_row.cregionmeta7 ,t_row.cregionmeta8 ,t_row.cregionmeta9 ,t_row.cregionmeta10,t_row.cregionmeta11,t_row.cregionmeta12,t_row.cregionmeta13,t_row.cregionmeta14,t_row.cregionmeta15] ;

cenvironnements_arr = ARRAY[t_row.cenvironnement1 ,t_row.cenvironnement2 ,t_row.cenvironnement3 ,t_row.cenvironnement4 ,t_row.cenvironnement5 ,t_row.cenvironnement6 ,t_row.cenvironnement7 ,t_row.cenvironnement8 ,t_row.cenvironnement9 ,t_row.cenvironnement10,t_row.cenvironnement11,t_row.cenvironnement12,t_row.cenvironnement13,t_row.cenvironnement14,t_row.cenvironnement15] ;

cstyles_arr = ARRAY[t_row.cstyle1 ,t_row.cstyle2 ,t_row.cstyle3 ,t_row.cstyle4 ,t_row.cstyle5 ,t_row.cstyle6 ,t_row.cstyle7 ,t_row.cstyle8 ,t_row.cstyle9 ,t_row.cstyle10,t_row.cstyle11,t_row.cstyle12,t_row.cstyle13,t_row.cstyle14,t_row.cstyle15] ;

lcps_arr = ARRAY[t_row.lcp1 ,t_row.lcp2 ,t_row.lcp3 ,t_row.lcp4 ,t_row.lcp5 ,t_row.lcp6 ,t_row.lcp7 ,t_row.lcp8 ,t_row.lcp9 ,t_row.lcp10,t_row.lcp11,t_row.lcp12,t_row.lcp13,t_row.lcp14,t_row.lcp15] ;

ndetails_arr = ARRAY[t_row.ndetail1 ,t_row.ndetail2 ,t_row.ndetail3 ,t_row.ndetail4 ,t_row.ndetail5 ,t_row.ndetail6 ,t_row.ndetail7 ,t_row.ndetail8 ,t_row.ndetail9 ,t_row.ndetail10,t_row.ndetail11,t_row.ndetail12,t_row.ndetail13,t_row.ndetail14,t_row.ndetail15] ;

nprogrammes_arr = ARRAY[t_row.nprogramme1 ,t_row.nprogramme2 ,t_row.nprogramme3 ,t_row.nprogramme4 ,t_row.nprogramme5 ,t_row.nprogramme6 ,t_row.nprogramme7 ,t_row.nprogramme8 ,t_row.nprogramme9 ,t_row.nprogramme10,t_row.nprogramme11,t_row.nprogramme12,t_row.nprogramme13,t_row.nprogramme14,t_row.nprogramme15] ;


cnaturebiens_arr = ARRAY[t_row.cnaturebien1 ,t_row.cnaturebien2 ,t_row.cnaturebien3 ,t_row.cnaturebien4  ] ;

cchauf_arr = ARRAY[t_row.cchauf1 ,t_row.cchauf2 ,t_row.cchauf3 ,t_row.cchauf4  ] ;

-- array_append(ctyps_arr, 3)

-- Protège toutes les valeurs des erreurs des effets indésirables des quotes _literals ( se prémunir contre de single quotes dans les data
FOR i IN 0 .. array_upper(ctyps_arr, 1) LOOP  if ctyps_arr[i]>'' and ctyps_arr[i] is not null then ctyps_arr2 = ctyps_arr2 || quote_literal(ctyps_arr[i]) ;   end if;  END LOOP;
FOR i IN 0 .. array_upper(ctypmetas_arr, 1) LOOP  if ctypmetas_arr[i]>'' and ctypmetas_arr[i] is not null then ctypmetas_arr2 = ctypmetas_arr2 || quote_literal(ctypmetas_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cregions_arr, 1) LOOP  if cregions_arr[i]>'' and cregions_arr[i] is not null then  cregions_arr2 = cregions_arr2 || quote_literal(cregions_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cregionmetas_arr, 1) LOOP  if cregionmetas_arr[i]>'' and cregionmetas_arr[i] is not null then  cregionmetas_arr2 = cregionmetas_arr2 || quote_literal(cregionmetas_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cenvironnements_arr, 1) LOOP  if cenvironnements_arr[i]>'' and cenvironnements_arr[i] is not null then cenvironnements_arr2 = cenvironnements_arr2 || quote_literal(cenvironnements_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cstyles_arr, 1) LOOP  if cstyles_arr[i]>'' and cstyles_arr[i] is not null then  cstyles_arr2 = cstyles_arr2 ||  quote_literal(cstyles_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(lcps_arr, 1) LOOP  if lcps_arr[i]>'' and lcps_arr[i] is not null then  lcps_arr2 = lcps_arr2 || quote_literal(lcps_arr[i] || '%' ) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cnaturebiens_arr, 1) LOOP  if cnaturebiens_arr[i]>'' and cnaturebiens_arr[i] is not null then cnaturebiens_arr2 = cnaturebiens_arr2 || quote_literal(cnaturebiens_arr[i]) ;   end if;  END LOOP;
FOR i IN 1 .. array_upper(cchauf_arr, 1) LOOP  if cchauf_arr[i]>'' and cchauf_arr[i] is not null then cchauf_arr2 = cchauf_arr2 || quote_literal(cchauf_arr[i]) ;   end if;  END LOOP;


-- Piscine
IF t_row.bpiscine=1 THEN
  IF t_row.bpiscinemin = 0 THEN
	conditions_arr = array_append(conditions_arr, 'bien.bpiscine = 0');
  ELSIF t_row.bpiscinemin = 1 THEN
	conditions_arr = array_append(conditions_arr, 'bien.bpiscine = 1');
  ELSIF t_row.bpiscinemin = 2 THEN
	conditions_arr = array_append(conditions_arr, 'bien.bpiscine = 2');
  ELSIF t_row.bpiscinemin = 3 THEN
	conditions_arr = array_append(conditions_arr, 'bien.bpiscine > 0');
 END IF ;

END IF ;

--IF t_row.bpiscine=1 AND t_row.bpiscinemin>0 THEN
--	conditions_arr = array_append(conditions_arr, 'bien.bpiscine = 0');
--END IF ;


--ALTER TABLE biencrit_t ADD COLUMN ballowforeigners integer ;
--ALTER TABLE biencrit_t ADD COLUMN ballowforeignersmin integer ;
IF t_row.ballowforeigners=1 THEN
	conditions_arr = array_append(conditions_arr, 'typ.ballowforeigners = 1');
END IF ;


-- Construite tous les éléments dans une matrice qui les reliera ensuite par des 'AND' ou 'OR'
IF t_row.bctyp=1 AND array_to_string(ctyps_arr2, ',') <> '' AND ctyps_arr IS NOT NULL THEN
	ctyps = 'bien.ctyp in (' || array_to_string(ctyps_arr2, ',') || ')';
END IF;

IF t_row.bctypmeta=1 AND array_to_string(ctypmetas_arr2, ',') <> '' AND ctypmetas_arr IS NOT NULL THEN
	ctypmetas = 'typ.ctypmeta in (' || array_to_string(ctypmetas_arr2, ',') || ')';
END IF;


-- Combine ctyps and ctypmetas with an OR if both are specified, and add the combined condition to the global conditions array
IF ctyps <> '' THEN
	IF ctypmetas <> '' THEN
		combined_ctyps_or_ctypmetas = '(' || ctyps || ' OR ' || ctypmetas || ')';
		conditions_arr = array_append(conditions_arr, combined_ctyps_or_ctypmetas);
	ELSE
		conditions_arr = array_append(conditions_arr, ctyps);
	END IF;
ELSIF ctypmetas <> '' THEN
	conditions_arr = array_append(conditions_arr, ctypmetas);
END IF;





IF t_row.bcregion=1 AND array_to_string( cregions_arr2  ,',')>'' AND cregions_arr IS NOT NULL THEN
	cregions = 'bien.cregion in (' || array_to_string(cregions_arr2 , ',') || ')' ;
	--conditions_arr = array_append(conditions_arr, cregions);
END IF ;

IF t_row.bcregionmeta=1 AND array_to_string( cregionmetas_arr2  ,',')>'' AND cregionmetas_arr IS NOT NULL THEN
	cregionmetas = 'region.cregionmeta in (' || array_to_string(cregionmetas_arr2 , ',') || ')' ;
	--conditions_arr = array_append(conditions_arr, cregionmetas);
 END IF ;

IF cregions > '' THEN
	IF cregionmetas > '' THEN
	   all_regions_or = '(' || cregions || ' OR ' || cregionmetas || ')' ;
	ELSE
	   all_regions_or = cregions ;
	END IF ;
ELSE
	IF cregionmetas > '' THEN
	   all_regions_or = cregionmetas ;
	END IF ;
END IF ;
IF all_regions_or > '' THEN
	conditions_arr = array_append(conditions_arr, all_regions_or);
END IF ;

-- mis en commentaire 15 04 2023 GDB (redondac
--IF t_row.bcregionmeta=1 AND array_to_string( cregionmetas_arr2  ,',')>'' AND cregionmetas_arr IS NOT NULL THEN
--	cregionmetas = 'region.cregionmeta in (' || array_to_string(cregionmetas_arr2 , ',') || ')' ;
	--conditions_arr = array_append(conditions_arr, cregionmetas);
-- END IF ;

IF t_row.bcenvironnement=1 AND array_to_string( cenvironnements_arr2  ,',')>'' AND cenvironnements_arr IS NOT NULL THEN
	cenvironnements = 'bien.cenvironnement in (' || array_to_string( cenvironnements_arr2, ',') || ')' ;
	conditions_arr = array_append(conditions_arr, cenvironnements);
 END IF ;

IF t_row.bcstyle=1 AND array_to_string( cstyles_arr2 ,',' )>'' AND cstyles_arr IS NOT NULL THEN
	cstyles = 'bien.cstyle in (' || array_to_string( cstyles_arr2, ',') || ')' ;
	conditions_arr = array_append(conditions_arr, cstyles);
 END IF ;

IF t_row.blcp=1 AND array_to_string( lcps_arr2  ,',')>'' AND lcps_arr IS NOT NULL THEN

	FOREACH lcp IN ARRAY lcps_arr2
	LOOP
	 -- can do some processing here
	 lcpcond = 'bien.lcp like ' || lcp    ;
	 lcpcond_arr = array_append(lcpcond_arr, lcpcond);
	END LOOP;

	lcps = '(' || array_to_string( lcpcond_arr, ' OR ') || ')' ;
	conditions_arr = array_append(conditions_arr, lcps);
 END IF ;

IF t_row.bcnaturebien=1 AND array_to_string( cnaturebiens_arr2  ,',')>'' AND cnaturebiens_arr IS NOT NULL THEN
	cnaturebiens = 'bien.cnaturebien in (' || array_to_string( cnaturebiens_arr2, ',') || ')' ;
	conditions_arr = array_append(conditions_arr, cnaturebiens);
 END IF ;

--IF t_row.bcchauf=1 AND array_to_string( cchauf_arr  ,',')>'' AND cchauf_arr IS NOT NULL THEN
--	cchaufs = 'bien.cchauf in (' || array_to_string( cchauf_arr, ',') || ')' ;
--	conditions_arr = array_append(conditions_arr, cchaufs);
-- END IF ;



-- IF condition detail is OR THEN
--     conditions_arr =	 'exists (select null from detailbien d where bien.nbien = d.nbien and d.ndetail IN (' ||  explode (ndetails_arr, "," ) '))' ;
IF t_row.bdetail=1 AND array_to_string( ndetails_arr  ,'')>'' AND ndetails_arr IS NOT NULL THEN
--    IF t_row.bmatchalldetails = 1 THEN
    -- lorsque tous les détails doivent etre satisfaits en meme temps
    	FOREACH nrequesteddetail IN ARRAY ndetails_arr
    	LOOP
    	 ndetailsql = 'exists (select null from detailbien d where bien.nbien = d.nbien and d.ndetail = (' ||  nrequesteddetail || '))' ;
    	 conditions_arr = array_append(conditions_arr, ndetailsql);
    	END LOOP;

--    ELSE      -- Match at least one
        --	ndetailsql = 'exists (select null from detailbien d where bien.nbien = d.nbien and d.ndetail IN (' || array_to_string( ndetails_arr, ',') || '))' ;
        --	conditions_arr = array_append(conditions_arr, ndetailsql);
--    END IF ;
END IF ;

-- programme
IF t_row.bprogramme=1 AND array_to_string( nprogrammes_arr  ,'')>'' AND nprogrammes_arr IS NOT NULL THEN


  --  const conditions = [
 --          { v: 1, t: this.$t("Uniquement les lots neufs") },
----   { v: -2, t: this.$t("Uniquement les programmes neufs") },
--  { v: -4, t: this.$t("Uniquement les lots et programmes neufs") },
--           { v: -1, t: this.$t("Exclure les lots neufs") },
 --  { v: -3, t: this.$t("Exclure les programmes neufs") },
 --     { v: 0, t: "---------------------------------------" }
--    ];


	IF 1 = ANY(nprogrammes_arr) THEN
  --Uniquement les lots neufs
		nprogrammesql = 'bien.nbiendepend is not null';

	ELSIF -2 = ANY(nprogrammes_arr) THEN
  --Uniquement les programmes neufs
		nprogrammesql = 'bien.bneuf = 1';
  	conditions_arr = array_append(conditions_arr, nprogrammesql);
	ELSIF -4 = ANY(nprogrammes_arr) THEN
  --Uniquement les lots et programmes neufs
		nprogrammesql = 'bien.nbiendepend is not null OR bien.bneuf = 1';
  	conditions_arr = array_append(conditions_arr, nprogrammesql);

	ELSIF -1 = ANY(nprogrammes_arr) THEN
    --Exclure les lots neufs
      nprogrammesql = 'bien.nbiendepend is null';
      conditions_arr = array_append(conditions_arr, nprogrammesql);  
    
    ELSIF -3 = ANY(nprogrammes_arr) THEN
  --Exclure les programmes neufs
		nprogrammesql = 'bien.bneuf <> 1';
  	conditions_arr = array_append(conditions_arr, nprogrammesql);

    ELSIF -5 = ANY(nprogrammes_arr) THEN
  --Exclure les programmes neufs et les lots
		nprogrammesql = 'bien.bneuf <> 1 and bien.nbiendepend is null';
	  	conditions_arr = array_append(conditions_arr, nprogrammesql);
      
ELSE
		nprogrammesql = 'bien.nbiendepend in (' || array_to_string(nprogrammes_arr, ',') || ')';
	END IF;
	conditions_arr = array_append(conditions_arr, nprogrammesql);




END IF ;



--bctypmandat1 smallint,
IF (t_row.bctypmandat1 = 1) THEN
	condition_item = 'bien.ctypmandat = ' || quote_literal(t_row.ctypmandat1) ;
	conditionsprix1_arr = array_append(conditionsprix1_arr, condition_item);
	IF (t_row.mprix1min IS NOT NULL) THEN
		condition_item = 'f_toeuro(bien.mprix,bien.cdevise) >= f_toeuro(' || t_row.mprix1min || ',''' || t_row.cdevise || ''')' ;
		conditionsprix1_arr = array_append(conditionsprix1_arr, condition_item);
	END IF ;
	IF (t_row.mprix1max IS NOT NULL) THEN
		condition_item = 'f_toeuro(bien.mprix,bien.cdevise) <= f_toeuro(' || t_row.mprix1max || ',''' || t_row.cdevise || ''')' ;
		conditionsprix1_arr = array_append(conditionsprix1_arr, condition_item);
	END IF ;
	IF array_to_string( conditionsprix1_arr  ,'') > '' THEN
		condition_itemprix1 = '(' || array_to_string( conditionsprix1_arr  ,' AND ') || ')';
	END IF ;

END IF ;


--bctypmandat2 smallint,
IF (t_row.ctypmandat2 IS NOT NULL ) THEN
	condition_item = 'bien.ctypmandat = ' || quote_literal(t_row.ctypmandat2) ;
	conditionsprix2_arr = array_append(conditionsprix2_arr, condition_item);
	IF (t_row.mprix2min IS NOT NULL) THEN
		condition_item = 'f_toeuro(bien.mprix,bien.cdevise) >= f_toeuro(' || t_row.mprix2min || ',''' || t_row.cdevise || ''')' ;
		conditionsprix2_arr = array_append(conditionsprix2_arr, condition_item);
	END IF ;
	IF (t_row.mprix2max IS NOT NULL) THEN
		condition_item = 'f_toeuro(bien.mprix,bien.cdevise) <= f_toeuro(' || t_row.mprix2max || ',''' || t_row.cdevise || ''')' ;
		conditionsprix2_arr = array_append(conditionsprix2_arr, condition_item);
	END IF ;

	--condition_itemprix2 = '(' || array_to_string( conditionsprix2_arr  ,' AND ') || ')';

	IF array_to_string( conditionsprix2_arr  ,'') > '' THEN
		condition_itemprix2 = '(' || array_to_string( conditionsprix2_arr  ,' AND ') || ')';
	END IF ;

END IF ;

IF (condition_itemprix1 > '' AND condition_itemprix1 IS NOT NULL) THEN
	conditions1and2_arr = array_append ( conditions1and2_arr , condition_itemprix1 ) ;
END IF ;

IF (condition_itemprix2 > '' AND condition_itemprix2 IS NOT NULL) THEN
	conditions1and2_arr = array_append ( conditions1and2_arr , condition_itemprix2 ) ;
END IF ;

-- Constitue une matrice avec les deux tranche de prix et budget
-- conditions1and2_arr = ARRAY[condition_itemprix1,condition_itemprix2];

-- Fusionne ces éléments en une condition de type OR

IF (array_upper(conditions1and2_arr, 1)>0) THEN
	condition_item = '(' || array_to_string( conditions1and2_arr  ,' OR ') || ')';
	--
	-- Ajoute cette condition tel quel dans la liste des conditions existantes
	conditions_arr = array_append(conditions_arr, condition_item);
END IF  ;

--bmchargemax smallint,
--bmprecimmomax smallint,
--bmrevcadmax smallint,
--bnannee smallint,

IF (t_row.bnannee=1 AND t_row.bnannee > 0 and t_row.bnannee IS NOT NULL AND t_row.nanneemin > 0 and t_row.nanneemin IS NOT NULL) THEN
	condition_item = 'bien.nannee >= ' || t_row.nanneemin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


IF (t_row.bnannee=1 AND t_row.bnannee > 0 and t_row.bnannee IS NOT NULL AND t_row.nanneemax > 0 and t_row.nanneemax IS NOT NULL) THEN
	condition_item = 'bien.nannee <= ' || t_row.nanneemax || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;



--bnanneerenov smallint,   qsurfjardin
--bndept smallint,
--bndisponibilite smallint,
--IF (t_row.bndisponibilite=1 AND t_row.ndisponibilite > 0 and t_row.ndisponibilite IS NOT NULL ) THEN
--	condition_item = 'bien.ndisponibilite = ' || t_row.ndisponibilite || ' ' ;
--	conditions_arr = array_append(conditions_arr, condition_item);
--END IF ;


--bnetat smallint,
IF (t_row.bnetat=1 AND t_row.netatmin > 0 and t_row.netatmin IS NOT NULL ) THEN
	condition_item = 'etat.nordre >= ' || t_row.netatmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bntypcuisine smallint,
IF (t_row.bntypcuisine=1 AND t_row.ntypcuisinemin > 0 and t_row.ntypcuisinemin IS NOT NULL ) THEN
	condition_item = 'bien.ntypcuisine = ' || t_row.ntypcuisinemin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bpiscine smallint,
--bpiscinemin smallint,   bpiscine
--IF (t_row.bpiscine=1 AND t_row.bpiscinemin >= 0 and t_row.bpiscinemin IS NOT NULL ) THEN
--	condition_item = 'bien.bpiscine = 0' || t_row.bpiscinemin || ' ' ;
--	conditions_arr = array_append(conditions_arr, condition_item);
--END IF ;

--bqbureau smallint,
IF (t_row.bqbureau=1 AND t_row.qbureaumin > 0 and t_row.qbureaumin IS NOT NULL ) THEN
	condition_item = 'bien.qbureau >= 0' || t_row.qbureaumin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqchambres smallint,
IF (t_row.bqchambres=1 AND t_row.qchambresmin > 0 and t_row.qchambresmin IS NOT NULL ) THEN
	condition_item = 'bien.qchambres >= ' || t_row.qchambresmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqchambres smallint,
IF (t_row.bqchambres=1 AND t_row.qchambresmax > 0 and t_row.qchambresmax IS NOT NULL ) THEN
	condition_item = 'bien.qchambres <= ' || t_row.qchambresmax || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqgarages smallint,
IF (t_row.bqgarages=1 AND t_row.qgaragesmin > 0 and t_row.qgaragesmin IS NOT NULL ) THEN
	condition_item = 'bien.qgarages >= 0' || t_row.qgaragesmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;



--bqpieces smallint,
IF (t_row.bqpieces=1 AND t_row.qpiecesmin > 0 and t_row.qpiecesmin IS NOT NULL ) THEN
	condition_item = 'bien.qpieces >= ' || t_row.qpiecesmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqpieces smallint,
IF (t_row.bqpieces=1 AND t_row.qpiecesmax > 0 and t_row.qpiecesmax IS NOT NULL ) THEN
	condition_item = 'bien.qpieces <= ' || t_row.qpiecesmax || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


--bqsdb smallint,
IF (t_row.bqsdb=1 AND t_row.qsdbmin > 0 and t_row.qsdbmin IS NOT NULL ) THEN
	condition_item = 'bien.qsdb >= ' || t_row.qsdbmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqsdd smallint,
IF (t_row.bqsdd=1 AND t_row.qsddmin > 0 and t_row.qsddmin IS NOT NULL ) THEN
	condition_item = 'bien.qsdd >= ' || t_row.qsddmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


--bqsurfhab smallint,
IF (t_row.bqsurfhab=1 AND t_row.qsurfhabmin > 0 and t_row.qsurfhabmin IS NOT NULL ) THEN
	condition_item = 'bien.qsurfhab >= ' || t_row.qsurfhabmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


--bqsurfhabmax smallint,
IF (t_row.bqsurfhab=1 AND t_row.qsurfhabmax > 0 and t_row.qsurfhabmax IS NOT NULL ) THEN
	condition_item = 'bien.qsurfhab <= ' || t_row.qsurfhabmax || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


--bqsurfsejour smallint,  qsurfjardinmin
IF (t_row.bqsurfsejour=1 AND t_row.qsurfsejourmin > 0 and t_row.qsurfsejourmin IS NOT NULL ) THEN
	condition_item = 'bien.qsurfsejour >= ' || t_row.qsurfsejourmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;


--bqsurfterrain smallint,
IF (t_row.bqsurfterrain=1 AND t_row.qsurfterrainmin > 0 AND t_row.qsurfterrainmin IS NOT NULL ) THEN
	condition_item = 'bien.qsurfterrain >= ' || t_row.qsurfterrainmin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqsurfterrain smallint,
IF (t_row.bqsurfterrain=1 AND t_row.qsurfterrainmax > 0 AND t_row.qsurfterrainmax IS NOT NULL ) THEN
	condition_item = 'bien.qsurfterrain <= ' || t_row.qsurfterrainmax || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;



--bqsurfjardin smallint,
IF (t_row.bqsurfjardin=1 AND t_row.qsurfjardinmin > 0 AND t_row.qsurfjardinmin IS NOT NULL ) THEN
    condition_item = 'bien.qsurfjardin >= ' || t_row.qsurfjardinmin || ' ' ;
    conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--bqsurfjardin smallint,
IF (t_row.bqsurfjardin=1 AND t_row.qsurfjardinmax > 0 AND t_row.qsurfjardinmax IS NOT NULL ) THEN
    condition_item = 'bien.qsurfjardin <= ' || t_row.qsurfjardinmax || ' ' ;
    conditions_arr = array_append(conditions_arr, condition_item);
END IF ;



--bqsurfterrasse smallint,
IF (t_row.bqsurfterrasse=1 AND t_row.qsurfterrassemin > 0 and t_row.qsurfterrassemin IS NOT NULL ) THEN
	condition_item = 'bien.qsurfterrasse >= ' || t_row.qsurfterrassemin || ' ' ;
	conditions_arr = array_append(conditions_arr, condition_item);
END IF ;

--condition_item = 'bien.bneuf <> 1'  ;
--conditions_arr = array_append(conditions_arr, condition_item);


   IF array_upper(conditions_arr, 1) > 0 THEN
        critsql = array_to_string( conditions_arr  ,' AND ');


	-- lbienssup (ajout des biens hors critères)
	IF (t_row.lbienssup IS NOT NULL AND trim(t_row.lbienssup) > ''  ) THEN
		critsql = '(('  || critsql ||  ') OR '  || 'bien.nbien IN ( ' || t_row.lbienssup || '))' ;
	END IF ;


        IF char_length(trim(critsql)) > 4 THEN
		critsql = ' AND (' || critsql || ')';
	ELSE
		critsql = '';
	END IF;
    ELSE
	critsql = '';

    END IF;


    RETURN critsql;
    --RETURN '';

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
COST 100;


DO $do$
BEGIN
    -- Alter column bctypmandat1 in biencrit_t to set default value if it exists
    IF EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'biencrit_t' AND column_name = 'bctypmandat1') THEN
        ALTER TABLE biencrit_t ALTER COLUMN bctypmandat1 SET DEFAULT 1;
    END IF;
END $do$;


update pays set ciso2pays = 'af' WHERE cisopays = 'AFG';
update pays set ciso2pays = 'al' WHERE cisopays = 'ALB';
update pays set ciso2pays = 'dz' WHERE cisopays = 'DZA';
update pays set ciso2pays = 'as' WHERE cisopays = 'ASM';
update pays set ciso2pays = 'ad' WHERE cisopays = 'AND';
update pays set ciso2pays = 'ao' WHERE cisopays = 'AGO';
update pays set ciso2pays = 'ai' WHERE cisopays = 'AIA';
update pays set ciso2pays = 'aq' WHERE cisopays = 'ATA';
update pays set ciso2pays = 'ag' WHERE cisopays = 'ATG';
update pays set ciso2pays = 'ar' WHERE cisopays = 'ARG';
update pays set ciso2pays = 'am' WHERE cisopays = 'ARM';
update pays set ciso2pays = 'aw' WHERE cisopays = 'ABW';
update pays set ciso2pays = 'au' WHERE cisopays = 'AUS';
update pays set ciso2pays = 'at' WHERE cisopays = 'AUT';
update pays set ciso2pays = 'az' WHERE cisopays = 'AZE';
update pays set ciso2pays = 'bs' WHERE cisopays = 'BHS';
update pays set ciso2pays = 'bh' WHERE cisopays = 'BHR';
update pays set ciso2pays = 'bd' WHERE cisopays = 'BGD';
update pays set ciso2pays = 'bb' WHERE cisopays = 'BRB';
update pays set ciso2pays = 'by' WHERE cisopays = 'BLR';
update pays set ciso2pays = 'be' WHERE cisopays = 'BEL';
update pays set ciso2pays = 'bz' WHERE cisopays = 'BLZ';
update pays set ciso2pays = 'bj' WHERE cisopays = 'BEN';
update pays set ciso2pays = 'bm' WHERE cisopays = 'BMU';
update pays set ciso2pays = 'bt' WHERE cisopays = 'BTN';
update pays set ciso2pays = 'bo' WHERE cisopays = 'BOL';
update pays set ciso2pays = 'ba' WHERE cisopays = 'BIH';
update pays set ciso2pays = 'bw' WHERE cisopays = 'BWA';
update pays set ciso2pays = 'bv' WHERE cisopays = 'BVT';
update pays set ciso2pays = 'br' WHERE cisopays = 'BRA';
update pays set ciso2pays = 'io' WHERE cisopays = 'IOT';
update pays set ciso2pays = 'bn' WHERE cisopays = 'BRN';
update pays set ciso2pays = 'bg' WHERE cisopays = 'BGR';
update pays set ciso2pays = 'bf' WHERE cisopays = 'BFA';
update pays set ciso2pays = 'bi' WHERE cisopays = 'BDI';
update pays set ciso2pays = 'cv' WHERE cisopays = 'CPV';
update pays set ciso2pays = 'kh' WHERE cisopays = 'KHM';
update pays set ciso2pays = 'cm' WHERE cisopays = 'CMR';
update pays set ciso2pays = 'ca' WHERE cisopays = 'CAN';
update pays set ciso2pays = 'ky' WHERE cisopays = 'CYM';
update pays set ciso2pays = 'cf' WHERE cisopays = 'CAF';
update pays set ciso2pays = 'td' WHERE cisopays = 'TCD';
update pays set ciso2pays = 'cl' WHERE cisopays = 'CHL';
update pays set ciso2pays = 'cn' WHERE cisopays = 'CHN';
update pays set ciso2pays = 'cx' WHERE cisopays = 'CXR';
update pays set ciso2pays = 'cc' WHERE cisopays = 'CCK';
update pays set ciso2pays = 'co' WHERE cisopays = 'COL';
update pays set ciso2pays = 'km' WHERE cisopays = 'COM';
update pays set ciso2pays = 'cg' WHERE cisopays = 'COG';
update pays set ciso2pays = 'cd' WHERE cisopays = 'COD';
update pays set ciso2pays = 'ck' WHERE cisopays = 'COK';
update pays set ciso2pays = 'cr' WHERE cisopays = 'CRI';
update pays set ciso2pays = 'ci' WHERE cisopays = 'CIV';
update pays set ciso2pays = 'hr' WHERE cisopays = 'HRV';
update pays set ciso2pays = 'cu' WHERE cisopays = 'CUB';
update pays set ciso2pays = 'cy' WHERE cisopays = 'CYP';
update pays set ciso2pays = 'cz' WHERE cisopays = 'CZE';
update pays set ciso2pays = 'dk' WHERE cisopays = 'DNK';
update pays set ciso2pays = 'dj' WHERE cisopays = 'DJI';
update pays set ciso2pays = 'dm' WHERE cisopays = 'DMA';
update pays set ciso2pays = 'do' WHERE cisopays = 'DOM';
update pays set ciso2pays = 'ec' WHERE cisopays = 'ECU';
update pays set ciso2pays = 'eg' WHERE cisopays = 'EGY';
update pays set ciso2pays = 'sv' WHERE cisopays = 'SLV';
update pays set ciso2pays = 'gq' WHERE cisopays = 'GNQ';
update pays set ciso2pays = 'er' WHERE cisopays = 'ERI';
update pays set ciso2pays = 'ee' WHERE cisopays = 'EST';
update pays set ciso2pays = 'et' WHERE cisopays = 'ETH';
update pays set ciso2pays = 'fk' WHERE cisopays = 'FLK';
update pays set ciso2pays = 'fo' WHERE cisopays = 'FRO';
update pays set ciso2pays = 'fj' WHERE cisopays = 'FJI';
update pays set ciso2pays = 'fi' WHERE cisopays = 'FIN';
update pays set ciso2pays = 'fr' WHERE cisopays = 'FRA';
update pays set ciso2pays = 'gf' WHERE cisopays = 'GUF';
update pays set ciso2pays = 'pf' WHERE cisopays = 'PYF';
update pays set ciso2pays = 'tf' WHERE cisopays = 'ATF';
update pays set ciso2pays = 'ga' WHERE cisopays = 'GAB';
update pays set ciso2pays = 'gm' WHERE cisopays = 'GMB';
update pays set ciso2pays = 'ge' WHERE cisopays = 'GEO';
update pays set ciso2pays = 'de' WHERE cisopays = 'DEU';
update pays set ciso2pays = 'gh' WHERE cisopays = 'GHA';
update pays set ciso2pays = 'gi' WHERE cisopays = 'GIB';
update pays set ciso2pays = 'gr' WHERE cisopays = 'GRC';
update pays set ciso2pays = 'gl' WHERE cisopays = 'GRL';
update pays set ciso2pays = 'gd' WHERE cisopays = 'GRD';
update pays set ciso2pays = 'gp' WHERE cisopays = 'GLP';
update pays set ciso2pays = 'gu' WHERE cisopays = 'GUM';
update pays set ciso2pays = 'gt' WHERE cisopays = 'GTM';
update pays set ciso2pays = 'gn' WHERE cisopays = 'GIN';
update pays set ciso2pays = 'gw' WHERE cisopays = 'GNB';
update pays set ciso2pays = 'gy' WHERE cisopays = 'GUY';
update pays set ciso2pays = 'ht' WHERE cisopays = 'HTI';
update pays set ciso2pays = 'hm' WHERE cisopays = 'HMD';
update pays set ciso2pays = 'hn' WHERE cisopays = 'HND';
update pays set ciso2pays = 'hk' WHERE cisopays = 'HKG';
update pays set ciso2pays = 'hu' WHERE cisopays = 'HUN';
update pays set ciso2pays = 'is' WHERE cisopays = 'ISL';
update pays set ciso2pays = 'in' WHERE cisopays = 'IND';
update pays set ciso2pays = 'id' WHERE cisopays = 'IDN';
update pays set ciso2pays = 'ir' WHERE cisopays = 'IRN';
update pays set ciso2pays = 'iq' WHERE cisopays = 'IRQ';
update pays set ciso2pays = 'ie' WHERE cisopays = 'IRL';
update pays set ciso2pays = 'il' WHERE cisopays = 'ISR';
update pays set ciso2pays = 'it' WHERE cisopays = 'ITA';
update pays set ciso2pays = 'jm' WHERE cisopays = 'JAM';
update pays set ciso2pays = 'jp' WHERE cisopays = 'JPN';
update pays set ciso2pays = 'jo' WHERE cisopays = 'JOR';
update pays set ciso2pays = 'kz' WHERE cisopays = 'KAZ';
update pays set ciso2pays = 'ke' WHERE cisopays = 'KEN';
update pays set ciso2pays = 'ki' WHERE cisopays = 'KIR';
update pays set ciso2pays = 'kp' WHERE cisopays = 'PRK';
update pays set ciso2pays = 'kr' WHERE cisopays = 'KOR';
update pays set ciso2pays = 'kw' WHERE cisopays = 'KWT';
update pays set ciso2pays = 'kg' WHERE cisopays = 'KGZ';
update pays set ciso2pays = 'la' WHERE cisopays = 'LAO';
update pays set ciso2pays = 'lv' WHERE cisopays = 'LVA';
update pays set ciso2pays = 'lb' WHERE cisopays = 'LBN';
update pays set ciso2pays = 'ls' WHERE cisopays = 'LSO';
update pays set ciso2pays = 'lr' WHERE cisopays = 'LBR';
update pays set ciso2pays = 'ly' WHERE cisopays = 'LBY';
update pays set ciso2pays = 'li' WHERE cisopays = 'LIE';
update pays set ciso2pays = 'lt' WHERE cisopays = 'LTU';
update pays set ciso2pays = 'lu' WHERE cisopays = 'LUX';
update pays set ciso2pays = 'mo' WHERE cisopays = 'MAC';
update pays set ciso2pays = 'mk' WHERE cisopays = 'MKD';
update pays set ciso2pays = 'mg' WHERE cisopays = 'MDG';
update pays set ciso2pays = 'mw' WHERE cisopays = 'MWI';
update pays set ciso2pays = 'my' WHERE cisopays = 'MYS';
update pays set ciso2pays = 'mv' WHERE cisopays = 'MDV';
update pays set ciso2pays = 'ml' WHERE cisopays = 'MLI';
update pays set ciso2pays = 'mt' WHERE cisopays = 'MLT';
update pays set ciso2pays = 'mh' WHERE cisopays = 'MHL';
update pays set ciso2pays = 'mq' WHERE cisopays = 'MTQ';
update pays set ciso2pays = 'mr' WHERE cisopays = 'MRT';
update pays set ciso2pays = 'mu' WHERE cisopays = 'MUS';
update pays set ciso2pays = 'yt' WHERE cisopays = 'MYT';
update pays set ciso2pays = 'mx' WHERE cisopays = 'MEX';
update pays set ciso2pays = 'fm' WHERE cisopays = 'FSM';
update pays set ciso2pays = 'md' WHERE cisopays = 'MDA';
update pays set ciso2pays = 'mc' WHERE cisopays = 'MCO';
update pays set ciso2pays = 'mn' WHERE cisopays = 'MNG';
update pays set ciso2pays = 'me' WHERE cisopays = 'MNE';
update pays set ciso2pays = 'ms' WHERE cisopays = 'MSR';
update pays set ciso2pays = 'ma' WHERE cisopays = 'MAR';
update pays set ciso2pays = 'mz' WHERE cisopays = 'MOZ';
update pays set ciso2pays = 'mm' WHERE cisopays = 'MMR';
update pays set ciso2pays = 'na' WHERE cisopays = 'NAM';
update pays set ciso2pays = 'nr' WHERE cisopays = 'NRU';
update pays set ciso2pays = 'np' WHERE cisopays = 'NPL';
update pays set ciso2pays = 'nl' WHERE cisopays = 'NLD';
update pays set ciso2pays = 'nc' WHERE cisopays = 'NCL';
update pays set ciso2pays = 'nz' WHERE cisopays = 'NZL';
update pays set ciso2pays = 'ni' WHERE cisopays = 'NIC';
update pays set ciso2pays = 'ne' WHERE cisopays = 'NER';
update pays set ciso2pays = 'ng' WHERE cisopays = 'NGA';
update pays set ciso2pays = 'nu' WHERE cisopays = 'NIU';
update pays set ciso2pays = 'nf' WHERE cisopays = 'NFK';
update pays set ciso2pays = 'mp' WHERE cisopays = 'MNP';
update pays set ciso2pays = 'no' WHERE cisopays = 'NOR';
update pays set ciso2pays = 'om' WHERE cisopays = 'OMN';
update pays set ciso2pays = 'pk' WHERE cisopays = 'PAK';
update pays set ciso2pays = 'pw' WHERE cisopays = 'PLW';
update pays set ciso2pays = 'ps' WHERE cisopays = 'PSE';
update pays set ciso2pays = 'pa' WHERE cisopays = 'PAN';
update pays set ciso2pays = 'pg' WHERE cisopays = 'PNG';
update pays set ciso2pays = 'py' WHERE cisopays = 'PRY';
update pays set ciso2pays = 'pe' WHERE cisopays = 'PER';
update pays set ciso2pays = 'ph' WHERE cisopays = 'PHL';
update pays set ciso2pays = 'pn' WHERE cisopays = 'PCN';
update pays set ciso2pays = 'pl' WHERE cisopays = 'POL';
update pays set ciso2pays = 'pt' WHERE cisopays = 'PRT';
update pays set ciso2pays = 'pr' WHERE cisopays = 'PRI';
update pays set ciso2pays = 'qa' WHERE cisopays = 'QAT';
update pays set ciso2pays = 're' WHERE cisopays = 'REU';
update pays set ciso2pays = 'ro' WHERE cisopays = 'ROU';
update pays set ciso2pays = 'ru' WHERE cisopays = 'RUS';
update pays set ciso2pays = 'rw' WHERE cisopays = 'RWA';
update pays set ciso2pays = 'bl' WHERE cisopays = 'BLM';
update pays set ciso2pays = 'sh' WHERE cisopays = 'SHN';
update pays set ciso2pays = 'kn' WHERE cisopays = 'KNA';
update pays set ciso2pays = 'lc' WHERE cisopays = 'LCA';
update pays set ciso2pays = 'mf' WHERE cisopays = 'MAF';
update pays set ciso2pays = 'pm' WHERE cisopays = 'SPM';
update pays set ciso2pays = 'vc' WHERE cisopays = 'VCT';
update pays set ciso2pays = 'ws' WHERE cisopays = 'WSM';
update pays set ciso2pays = 'sm' WHERE cisopays = 'SMR';
update pays set ciso2pays = 'st' WHERE cisopays = 'STP';
update pays set ciso2pays = 'sa' WHERE cisopays = 'SAU';
update pays set ciso2pays = 'sn' WHERE cisopays = 'SEN';
update pays set ciso2pays = 'rs' WHERE cisopays = 'SRB';
update pays set ciso2pays = 'sc' WHERE cisopays = 'SYC';
update pays set ciso2pays = 'sl' WHERE cisopays = 'SLE';
update pays set ciso2pays = 'sg' WHERE cisopays = 'SGP';
update pays set ciso2pays = 'sx' WHERE cisopays = 'SXM';
update pays set ciso2pays = 'sk' WHERE cisopays = 'SVK';
update pays set ciso2pays = 'si' WHERE cisopays = 'SVN';
update pays set ciso2pays = 'sb' WHERE cisopays = 'SLB';
update pays set ciso2pays = 'so' WHERE cisopays = 'SOM';
update pays set ciso2pays = 'za' WHERE cisopays = 'ZAF';
update pays set ciso2pays = 'gs' WHERE cisopays = 'SGS';
update pays set ciso2pays = 'ss' WHERE cisopays = 'SSD';
update pays set ciso2pays = 'es' WHERE cisopays = 'ESP';
update pays set ciso2pays = 'lk' WHERE cisopays = 'LKA';
update pays set ciso2pays = 'sd' WHERE cisopays = 'SDN';
update pays set ciso2pays = 'sr' WHERE cisopays = 'SUR';
update pays set ciso2pays = 'sj' WHERE cisopays = 'SJM';
update pays set ciso2pays = 'sz' WHERE cisopays = 'SWZ';
update pays set ciso2pays = 'se' WHERE cisopays = 'SWE';
update pays set ciso2pays = 'ch' WHERE cisopays = 'CHE';
update pays set ciso2pays = 'sy' WHERE cisopays = 'SYR';
update pays set ciso2pays = 'tw' WHERE cisopays = 'TWN';
update pays set ciso2pays = 'tj' WHERE cisopays = 'TJK';
update pays set ciso2pays = 'tz' WHERE cisopays = 'TZA';
update pays set ciso2pays = 'th' WHERE cisopays = 'THA';
update pays set ciso2pays = 'tl' WHERE cisopays = 'TLS';
update pays set ciso2pays = 'tg' WHERE cisopays = 'TGO';
update pays set ciso2pays = 'tk' WHERE cisopays = 'TKL';
update pays set ciso2pays = 'to' WHERE cisopays = 'TON';
update pays set ciso2pays = 'tt' WHERE cisopays = 'TTO';
update pays set ciso2pays = 'tn' WHERE cisopays = 'TUN';
update pays set ciso2pays = 'tr' WHERE cisopays = 'TUR';
update pays set ciso2pays = 'tm' WHERE cisopays = 'TKM';
update pays set ciso2pays = 'tc' WHERE cisopays = 'TCA';
update pays set ciso2pays = 'tv' WHERE cisopays = 'TUV';
update pays set ciso2pays = 'ug' WHERE cisopays = 'UGA';
update pays set ciso2pays = 'ua' WHERE cisopays = 'UKR';
update pays set ciso2pays = 'ae' WHERE cisopays = 'ARE';
update pays set ciso2pays = 'gb' WHERE cisopays = 'GBR';
update pays set ciso2pays = 'us' WHERE cisopays = 'USA';
update pays set ciso2pays = 'um' WHERE cisopays = 'UMI';
update pays set ciso2pays = 'uy' WHERE cisopays = 'URY';
update pays set ciso2pays = 'uz' WHERE cisopays = 'UZB';
update pays set ciso2pays = 'vu' WHERE cisopays = 'VUT';
update pays set ciso2pays = 've' WHERE cisopays = 'VEN';
update pays set ciso2pays = 'vn' WHERE cisopays = 'VNM';
update pays set ciso2pays = 'vg' WHERE cisopays = 'VGB';
update pays set ciso2pays = 'vi' WHERE cisopays = 'VIR';
update pays set ciso2pays = 'wf' WHERE cisopays = 'WLF';
update pays set ciso2pays = 'eh' WHERE cisopays = 'ESH';
update pays set ciso2pays = 'ye' WHERE cisopays = 'YEM';
update pays set ciso2pays = 'zm' WHERE cisopays = 'ZMB';
update pays set ciso2pays = 'zw' WHERE cisopays = 'ZWE';




-- Ajout de la clé étrangère pour nprospectnotaire

update preference_t set nprospectprospect = null where nprospectprospect not in (select ncategorie from cat);
update preference_t set nprospectagence = null where nprospectagence not in (select ncategorie from cat);
update preference_t set nprospectprio = null where nprospectprio not in (select ncategorie from cat);
update preference_t set nprospectproprio = null where nprospectproprio not in (select ncategorie from cat);
update preference_t set nprospectnotaire = null where nprospectnotaire not in (select ncategorie from cat);



DO $do$
BEGIN
    -- Add foreign key constraint fk_nprospectnotaire_ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_nprospectnotaire_ncategorie') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_nprospectnotaire_ncategorie FOREIGN KEY (nprospectnotaire) REFERENCES cat (ncategorie);
    END IF;

    -- Add foreign key constraint fk_nprospectproprio_ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_nprospectproprio_ncategorie') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_nprospectproprio_ncategorie FOREIGN KEY (nprospectproprio) REFERENCES cat (ncategorie);
    END IF;

    -- Add foreign key constraint fk_nprospectprio_ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_nprospectprio_ncategorie') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_nprospectprio_ncategorie FOREIGN KEY (nprospectprio) REFERENCES cat (ncategorie);
    END IF;

    -- Add foreign key constraint fk_nprospectagence_ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_nprospectagence_ncategorie') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_nprospectagence_ncategorie FOREIGN KEY (nprospectagence) REFERENCES cat (ncategorie);
    END IF;

    -- Add foreign key constraint fk_nprospectprospect_ncategorie if it does not exist
    IF NOT EXISTS (SELECT 1 FROM information_schema.table_constraints WHERE table_name = 'preference_t' AND constraint_name = 'fk_nprospectprospect_ncategorie') THEN
        ALTER TABLE preference_t ADD CONSTRAINT fk_nprospectprospect_ncategorie FOREIGN KEY (nprospectprospect) REFERENCES cat (ncategorie);
    END IF;
END $do$;



DO $do$
BEGIN
    -- Create table webcontents if it does not exist
    IF NOT EXISTS (SELECT FROM information_schema.tables WHERE table_schema = 'public' AND table_name = 'webcontents') THEN
        CREATE TABLE IF NOT EXISTS webcontents
        (
          id serial,
          ctypmenu character varying(10),
          clangue character varying(2),
          cagence character varying(10),
          lcontent text,
          cusercre character varying(50),
          dcre timestamp without time zone,
          cusermod character varying(50),
          dmod timestamp without time zone, 
          CONSTRAINT pk_webcontent_id PRIMARY KEY (id),
          CONSTRAINT fk_webcontent_cagence FOREIGN KEY (cagence)
              REFERENCES public.agence (cagence) MATCH SIMPLE
              ON UPDATE CASCADE ON DELETE SET NULL
        )
        WITH (
          OIDS=FALSE
        );
    END IF;
END $do$;




CREATE OR REPLACE FUNCTION public.f_check_unique_cbien (
)
RETURNS trigger AS
$body$
BEGIN
    -- Vérifier si la valeur de 'cbien' existe déjà
    IF EXISTS (SELECT 1 FROM bien WHERE cbien = NEW.cbien) THEN
        -- Déclencher une exception si la valeur existe déjà
        RAISE EXCEPTION 'La référence de ce bien (%) a déjà été attribuée à un bien existant, veuillez en utiliser une autre', NEW.cbien;
    END IF;
    -- Si la valeur n'existe pas, permettre l'insertion
    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT

COST 100;

ALTER FUNCTION public.f_check_unique_cbien ()
  OWNER TO admin;


DROP TRIGGER IF EXISTS tbi_bien_cbien_unique ON bien_t;
CREATE TRIGGER tbi_bien_cbien_unique
  BEFORE INSERT 
  ON public.bien_t
  
FOR EACH ROW 
  EXECUTE PROCEDURE public.f_check_unique_cbien();

--mettre à jour les champs dénormalisés
UPDATE prospect_t set dmod = dmod ;
UPDATE bien_t set dmod = dmod ;
UPDATE biencrit_t set dmod = dmod ;
UPDATE prospect_t set dmod = dmod ;
UPDATE bien_t set dmod = dmod ;
UPDATE prospect_t set dcre = dmod where dcre is null ;
UPDATE biencrit set bctypmandat1 = 1 ;



DO $$
BEGIN
    -- Check if the column clangue exists
    IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'utilisateur'
          AND column_name = 'clangue'
    ) THEN
        -- Add the column with a default value
        ALTER TABLE utilisateur ADD COLUMN clangue character(2) DEFAULT 'fr';

        -- Set the default explicitly
        ALTER TABLE utilisateur ALTER COLUMN clangue SET DEFAULT 'fr';
    END IF;
END
$$;

UPDATE utilisateur set clangue = (select clangue from agence where utilisateur.cagence = agence.cagence ) ;


--UPDATE utilisateur set bexportenabled = 1 where nprivilege = 1 ;


DO $do$ 
BEGIN
    IF NOT EXISTS (
        SELECT 1 
        FROM information_schema.columns 
        WHERE table_name='portailagence' 
        AND column_name='lcustomname'
    ) THEN
        ALTER TABLE portailagence ADD COLUMN lcustomname VARCHAR(50);
    END IF;
END $do$;



-- Ajouter les colonnes 'lfonction<langue>' pour chaque langue

-- ALTER TABLE utilisateur ADD COLUMN lfonctionen VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionnl VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionde VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctiones VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionit VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionsk VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctioncs VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionru VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionzh VARCHAR(50);
-- ALTER TABLE utilisateur ADD COLUMN lfonctionfr VARCHAR(50);




CREATE OR REPLACE FUNCTION update_lfonction_trigger()
RETURNS TRIGGER AS $$
BEGIN
    -- Vérifier si la valeur de 'lfonctionfr' a changé
    IF NEW.lfonctionfr IS DISTINCT FROM OLD.lfonctionfr THEN
        -- Mettre à jour 'lfonction' avec la nouvelle valeur de 'lfonctionfr'
        NEW.lfonction := NEW.lfonctionfr;
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;




-- Créer le trigger
DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_trigger
        WHERE tgname = 'update_lfonction_on_change'
    ) THEN
        CREATE TRIGGER update_lfonction_on_change
        BEFORE UPDATE OF lfonctionfr ON utilisateur
        FOR EACH ROW
        EXECUTE PROCEDURE update_lfonction_trigger();
    END IF;
END
$$;



CREATE OR REPLACE FUNCTION public.f_insertdeletebienlog (
)
RETURNS trigger AS
$body$
BEGIN
    -- Tentative d'insertion dans la table deletebienlog
    BEGIN
        INSERT INTO deletebienlog (
            nbien, cbien, ladr, lcp, llocalite, cisopays, mprix, lusername, 
            ctyp, bien_dmod, bien_dcre, bien_cusercre, bien_cusermod
        ) VALUES (
            OLD.nbien, OLD.cbien, OLD.ladr, OLD.lcp, OLD.llocalite, OLD.cisopays, 
            OLD.mprix, OLD.lusername, OLD.ctyp, OLD.dmod, OLD.dcre, 
            OLD.cusercre, OLD.cusermod
        );
    EXCEPTION
        -- En cas d'erreur, levée d'une exception pour annuler la suppression
        WHEN OTHERS THEN
            RAISE EXCEPTION 'Erreur lors de l''insertion dans le log des suppressions (deletebienlog) : %', SQLERRM;
    END;

    -- Retourner la ligne OLD pour permettre la suppression
    RETURN OLD;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT

COST 100;



CREATE OR REPLACE FUNCTION public.f_insertdeleteprospectlog (
)
RETURNS trigger AS
$body$
DECLARE
    coperation VARCHAR(10);
BEGIN
    -- Tentative d'insertion dans la table deleteprospectlog
    BEGIN
      --Detect trigger operation then set coperation
        IF TG_OP = 'DELETE' THEN
            coperation = 'DELETE';
        ELSIF TG_OP = 'UPDATE' THEN
            coperation = 'UPDATE';

		-- check if lnom or lprenom has changed
        IF NEW.lnom IS NOT DISTINCT FROM OLD.lnom AND NEW.lprenom IS NOT DISTINCT FROM OLD.lprenom AND NEW.lusername IS NOT DISTINCT FROM OLD.lusername THEN
            -- nothing to do because name and firstname didn't change
            RETURN NEW;
        END IF;

        ELSIF TG_OP = 'INSERT' THEN
            coperation = 'INSERT';
        END IF;

        INSERT INTO deleteprospectlog (
            nprospect, 
            coperation,
            lnom, lprenom, lgsm, ltel, lemail, ladr, lcp, llocalite, 
            cisopays, lusername, prospect_dmod, prospect_dcre, 
            prospect_cusercre, prospect_cusermod
        ) VALUES (
            OLD.nprospect, 
            coperation,
            OLD.lnom, OLD.lprenom, OLD.lgsm, OLD.ltel, OLD.lemail, 
            OLD.ladr, OLD.lcp, OLD.llocalite, OLD.cisopays, OLD.lusername, 
            OLD.dmod, OLD.dcre, OLD.cusercre, OLD.cusermod
        );
    EXCEPTION
        -- En cas d'erreur, levée d'une exception pour annuler la suppression
        WHEN OTHERS THEN
            RAISE EXCEPTION 'Erreur lors de l''insertion dans deleteprospectlog. Suppression annulée.';
    END;

    -- Retourner la ligne OLD pour permettre la suppression
    RETURN OLD;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

ALTER FUNCTION public.f_insertdeleteprospectlog ()
  OWNER TO postgres;
  


--DROP TRIGGER IF EXISTS tbd_deleteprospectlog ON public.prospect_t;

--CREATE TRIGGER tbd_deleteprospectlog
  --BEFORE UPDATE OF lnom, lprenom,lusername OR DELETE 
 -- ON public.prospect_t
 -- FOR EACH ROW 
 -- EXECUTE PROCEDURE public.f_insertdeleteprospectlog();

DROP TRIGGER IF EXISTS tbu_deleteprospectlog ON public.prospect_t;

CREATE TRIGGER tbu_deleteprospectlog
  BEFORE DELETE ON
  public.prospect_t
  FOR EACH ROW 
  EXECUTE PROCEDURE public.f_insertdeleteprospectlog();


-- Ajout des chjamps pour gérer l'envoi des leads dans les flux des portails

--ALTER TABLE portailagence ADD COLUMN nemailscenario INT NOT NULL DEFAULT 0;
--ALTER TABLE portailagence ADD COLUMN nphonescenario INT NOT NULL DEFAULT 0;
--ALTER TABLE agence ADD COLUMN lemail4leads VARCHAR(250) DEFAULT NULL;


--ALTER TABLE portailagence ADD COLUMN ballowotheragencies INT NOT NULL DEFAULT 0;

-- Création de la fonction du trigger
CREATE OR REPLACE FUNCTION f_update_dtransaction()
RETURNS TRIGGER AS $$
DECLARE
    current_cisopays VARCHAR; -- Variable pour stocker la valeur de cpaysiso
BEGIN
    -- Si nbien est NULL, ne rien faire
    IF NEW.nbien IS NULL THEN
        RETURN NEW;
    END IF;

   
    -- Vérifie si le champ dssp est non nul et si cpaysiso est différent de 'BEL'
    IF NEW.dssp IS NOT NULL THEN
        -- Met à jour le champ dtransaction avec la valeur de dssp
        UPDATE bien
        SET dtransaction = NEW.dssp
        WHERE bien.cisopays <> 'BEL' AND nbien = NEW.nbien; -- Associe avec une clé primaire ou unique
    END IF;

    IF NEW.dacte IS NOT NULL THEN
        -- Met à jour le champ dtransaction avec la valeur de dssp
        UPDATE bien
        SET dtransaction = NEW.dacte
        WHERE bien.cisopays <> 'BEL' AND nbien = NEW.nbien; -- Associe avec une clé primaire ou unique
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Création du trigger
DROP TRIGGER IF EXISTS tbiu_update_dtransaction ON offre_t;
CREATE TRIGGER tbiu_update_dtransaction
AFTER INSERT OR UPDATE OF dssp ON offre_t
FOR EACH ROW
EXECUTE PROCEDURE f_update_dtransaction();


DROP VIEW IF EXISTS offre;


ALTER TABLE offre_t ALTER COLUMN cfacture TYPE VARCHAR(25);

ALTER TABLE offre_t ALTER COLUMN noffre TYPE INT ;


DO $do$
BEGIN
    -- Drop the view if it exists
    IF EXISTS (SELECT 1 FROM information_schema.views WHERE table_name = 'offre') THEN
        DROP VIEW IF EXISTS offre;
    END IF;

    -- Create or replace the view offre
    CREATE OR REPLACE VIEW offre AS
    SELECT offre_t.nrelation,
        offre_t.coffre,
        offre_t.cstatut,
        offre_t.mcommission,
        offre_t.cfacture,
        offre_t.dacte,
        offre_t.bpaye,
        offre_t.cusercre,
        offre_t.cusermod,
        offre_t.dmod,
        offre_t.dcre,
        offre_t.lusername,
        offre_t.dssp,
        offre_t.dactebutoir,
        offre_t.mmontant,
        offre_t.nrelationrvacte,
        offre_t.nrelationrvssp,
        offre_t.nnotairevendeur,
        offre_t.nnotaireacquereur,
        offre_t.doffre,
        offre_t.lcomment,
        offre_t.nbien,
        offre_t.nprospect,
        offre_t.cagence,
        offre_t.denvoi_sru,
        offre_t.dfin_csop,
        offre_t.lcondsusp,
        offre_t.lcondpart,
        offre_t.cdevise,
        offre_t.lsearchfr,
        offre_t.lsearchen,
        offre_t.dreiteration,
        offre_t.mcommissionvendeur,
        offre_t.noffre
    FROM offre_t
    WHERE (EXISTS ( 
        SELECT NULL::unknown AS unknown
        FROM utilisateuragence
        WHERE utilisateuragence.bselectoffre = 1 
        AND utilisateuragence.lusername::name = current_user
        AND (utilisateuragence.cagence::text = utilisateuragence.cagence::text 
            OR utilisateuragence.cagence::text = ''::text 
            OR utilisateuragence.cagence IS NULL)
    ));
END $do$;




--ALTER TABLE statutbien ADD COLUMN cbgcolor VARCHAR(7) DEFAULT '#FFAE1A'; 
UPDATE statutbien SET cbgcolor = '#00a300' WHERE bactif = 1 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#6C757D' WHERE bactif = 0 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#6610F2' WHERE bactif = 9 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#FD7E14' WHERE bactif = 7 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#FFC107' WHERE bactif = 6 AND cbgcolor IS NULL;

UPDATE statutbien SET cbgcolor = '#6C757D' WHERE bactif = -4 AND cbgcolor IS NULL;

UPDATE statutbien SET cbgcolor = '#007BFF' WHERE bactif = -2 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#6C757D' WHERE bactif = -9 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#6C757D' WHERE bactif = -6 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#A133FF' WHERE bactif = 5 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#6C757D' WHERE bactif = 2 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#b80606' WHERE bactif = 8 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#0056B3' WHERE bactif = 4 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#A133FF' WHERE bactif = 3 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#17A2B8' WHERE bactif = -3 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#007BFF' WHERE bactif = -1 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#17A2B8' WHERE bactif = -8 AND cbgcolor IS NULL;
UPDATE statutbien SET cbgcolor = '#17A2B8' WHERE bactif = -7 AND cbgcolor IS NULL;



CREATE OR REPLACE FUNCTION public.f_update_bactif (
)
RETURNS trigger AS
$body$
    -- Trigger permettant de valider le droit d'insérer des tâches à chaque création de bien
    declare
	ll_bactif integer ;

    begin

	SELECT bactif INTO ll_bactif FROM statutoffre WHERE cstatut = NEW.cstatut ;

	IF ll_bactif > 0 AND ll_bactif IS NOT NULL AND NEW.nbien IS NOT NULL THEN

		UPDATE bien SET bactif = ll_bactif WHERE nbien = NEW.nbien ;

	END IF;

	RETURN NEW;

    end;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

ALTER FUNCTION public.f_update_bactif ()
  OWNER TO admin;
  
-- Drop the trigger if it already exists, then create it
DROP TRIGGER IF EXISTS tbui_offre_t ON offre_t;
CREATE TRIGGER tbui_offre_t BEFORE INSERT OR UPDATE ON offre_t FOR EACH ROW EXECUTE PROCEDURE f_update_bactif();

INSERT INTO public.detail (
  ndetail,
  ntypdetail,
  cunite,
  binternet,
  ldetailnl,
  ldetailen,
  ldetailfr,
  bdescriptif,
  cusercre,
  dcre,
  cusermod,
  dmod,
  binclure,
  bprotect,
  nordre,
  bcritere,
  ldetailde,
  ldetailes,
  ldetailit,
  ldetailsk,
  ldetailcs,
  ldetailru,
  ldetailzh,
  bimportant,
  bdefault,
  ndetailtrigger,
  breport
)
SELECT
  4100,
  133,
  NULL,
  0,
  'Herinneren na afloop van het contract', -- Traduction en néerlandais (NL) requise
  'Recall after contract expiration', -- Traduction en anglais (EN)
  'Rappeler suite à expiration contrat', -- Français (FR)
  0,
  'admin',
  CURRENT_TIMESTAMP,
  'admin',
  CURRENT_TIMESTAMP,
  1,
  1,
  2,
  0,
  'Nach Vertragsablauf erinnern', -- Allemand (DE)
  'Recordar después del vencimiento del contrato', -- Espagnol (ES)
  'Richiamare dopo la scadenza del contratto', -- Italien (IT)
  'Pripomenúť po uplynutí zmluvy', -- Slovaque (SK)
  'Připomenout po vypršení smlouvy', -- Tchèque (CS)
  'Напомнить после истечения срока действия договора', -- Russe (RU)
  '合同到期后提醒', -- Chinois (ZH)
  0,
  0,
  NULL,
  0
WHERE NOT EXISTS (
  SELECT 1 FROM public.detail WHERE ndetail = 4100
);


--ALTER TABLE agence ADD COLUMN bstandardwebsite  TYPE INT DEFAULT 1;


CREATE OR REPLACE VIEW prospectbien AS
 SELECT prospectbien_t.*
   FROM prospectbien_t
  WHERE prospectbien_t.ntyprelation = 5 OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            typrelation
          WHERE prospectbien_t.ntyprelation = typrelation.ntyprelation AND (utilisateuragence.bselecthisto = 1 OR utilisateuragence.bselectrv = 1 AND typrelation.brendezvous = 1) AND utilisateuragence.lusername::name = "current_user"() AND (prospectbien_t.cagence::text = utilisateuragence.cagence::text OR prospectbien_t.cagence::text = ''::text OR prospectbien_t.cagence IS NULL)));




CREATE OR REPLACE VIEW public.prospectbien_lastpub (
    nrelation,
    nprospect,
    nbien,
    ntyprelation,
    ddebut,
    dfin,
    lrem,
    lusername,
    dcre,
    cusercre,
    dmod,
    cusermod,
    mcout,
    dalarm,
    ndoc,
    nrubrique,
    bannulation,
    cagence,
    bphoto,
    ldocfilename,
    bconfirmed,
    dfinpublication,
    dderpublication,
    lvisite,
    cavisclient,
    cidannonceportail,
    mmontant,
    lemailcontent,
    dlastpubannonceur)
AS
SELECT b.nrelation,
    b.nprospect,
    b.nbien,
    b.ntyprelation,
    b.ddebut,
    b.dfin,
    b.lrem,
    b.lusername,
    b.dcre,
    b.cusercre,
    b.dmod,
    b.cusermod,
    b.mcout,
    b.dalarm,
    b.ndoc,
    b.nrubrique,
    b.bannulation,
    b.cagence,
    b.bphoto,
    b.ldocfilename,
    b.bconfirmed,
    b.dfinpublication,
    b.dderpublication,
    b.lvisite,
    b.cavisclient,
    b.cidannonceportail,
    b.mmontant,
    b.lemailcontent,
    b.dlastpubannonceur
FROM prospectbien b
WHERE (b.nrelation IN (
    SELECT max(c.nrelation) AS max
    FROM prospectbien c
    WHERE c.ntyprelation = 10
    GROUP BY c.nprospect, c.nbien
    ));
    


CREATE OR REPLACE FUNCTION public.f_recordbienchange (
)
RETURNS trigger AS
$body$
    BEGIN


    -- Variation de mandat
    IF (OLD.cmandat <> NEW.cmandat AND OLD.cmandat IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 60, current_timestamp, current_timestamp, concat (OLD.cmandat , ' -> ' , NEW.cmandat )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

--

    -- Variation de prix
    -- Variation de prix
IF ((OLD.mprix IS NOT NULL OR NEW.mprix IS NOT NULL) AND OLD.mprix <> NEW.mprix ) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 20, current_timestamp, current_timestamp, concat ( replace (trim(to_char (OLD.mprix, '999G999G999G999')),',','.'), ' -> ' , replace (trim(to_char (NEW.mprix, '999G999G999G999')),',','.') )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;



     -- Variation de statut

    IF (OLD.bactif <> NEW.bactif AND OLD.bactif IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 21, current_timestamp, current_timestamp, (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = OLD.bactif) || ' -> '  || (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = NEW.bactif) ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

     -- Changement de négociateur (ntyprelation = 30)
    IF (OLD.lusername <> NEW.lusername AND OLD.lusername IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 30, current_timestamp, current_timestamp,
              concat ((SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = OLD.lusername)  , ' ('  , OLD.lusername  , ') -> '  , (SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = NEW.lusername ) , ' (' , NEW.lusername , ') '),
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;



    -- Changement de statut de publication Web (ntyprelation = 31)
    IF (OLD.bexportweb <> NEW.bexportweb AND OLD.bexportweb IS NOT NULL) THEN


      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (null, null, OLD.nbien, 31, current_timestamp, current_timestamp, case when NEW.bexportweb=1 then 'Publication web activée' else 'Publication web suspendue' end ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;


     RETURN OLD;
    -- RETURN NULL;

    END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

update prospect_t set ncategorie = 2 where ncategorie is null ;
update prospect_t set ncategorie = 101 where ncategorie is null ;
ALTER TABLE prospect_t ALTER COLUMN ncategorie SET NOT NULL;
UPDATE prospect_t SET ncategories = ARRAY[ncategorie] WHERE ncategories IS NULL ;


CREATE OR REPLACE FUNCTION public.f_sync_ncategorie_fields (
)
RETURNS trigger AS
$body$
BEGIN
    -- Cas 1 : si ncategorie est NULL mais ncategories[1] est défini
    IF NEW.ncategorie IS NULL 
       AND NEW.ncategories IS NOT NULL 
       AND array_length(NEW.ncategories, 1) >= 1 THEN
        NEW.ncategorie := NEW.ncategories[1];

    -- Cas 1' : si ncategories est spécifé lors d'une insertion il prend le dessus sur le reste
    ELSIF ( TG_OP = 'INSERT' AND NEW.ncategories IS NOT NULL AND array_length(NEW.ncategories, 1) > 0) THEN
        NEW.ncategorie := NEW.ncategories[1];

    ELSIF ( TG_OP = 'UPDATE' AND NEW.ncategories <> OLD.ncategories AND array_length(NEW.ncategories, 1) > 0) THEN
        NEW.ncategorie := NEW.ncategories[1];
 
    -- Cas 2 : si ncategories est NULL ou vide mais ncategorie est défini
    ELSIF (NEW.ncategories IS NULL OR array_length(NEW.ncategories, 1) = 0)
          AND NEW.ncategorie IS NOT NULL THEN
        NEW.ncategories := ARRAY[NEW.ncategorie];

    -- Cas 2' : si ncategories est un array vide {} mais ncategorie est défini
    ELSIF NEW.ncategories = '{}'::integer[]
          AND NEW.ncategorie IS NOT NULL THEN
        NEW.ncategories := ARRAY[NEW.ncategorie];

    -- Cas 3 : les deux sont définis et différents
    ELSIF NEW.ncategorie IS NOT NULL 
       AND NEW.ncategories IS NOT NULL 
       AND array_length(NEW.ncategories, 1) > 0
       AND NEW.ncategories[1] IS DISTINCT FROM NEW.ncategorie THEN

        -- Insérer ncategorie en première position si non présent, et décaler les autres sans doublon
        NEW.ncategories := ARRAY[
            NEW.ncategorie
        ] || (
            SELECT array_agg(val)
            FROM unnest(NEW.ncategories) AS val
            WHERE val IS DISTINCT FROM NEW.ncategorie
        );
    END IF;

    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

ALTER FUNCTION public.f_sync_ncategorie_fields ()
  OWNER TO admin;
  

DROP TRIGGER IF EXISTS trg_sync_ncategorie ON prospect_t;
CREATE TRIGGER trg_sync_ncategorie
  BEFORE INSERT OR UPDATE 
  ON public.prospect_t
FOR EACH ROW 
  EXECUTE PROCEDURE public.f_sync_ncategorie_fields();


--drop view prospect CASCADE ;
DROP VIEW IF EXISTS prospect CASCADE;
-- intégratopn des multi catégories 
CREATE OR REPLACE VIEW public.prospect (
    nprospect,
    ccivilite,
    cpolit,
    lnom,
    lprenom,
    lnomsociete,
    ladr,
    lcp,
    llocalite,
    cisopays,
    ltel,
    lfax,
    ltel2,
    lgsm,
    lemail,
    ncategorie,
    bactif,
    csexe,
    dnaissance,
    nregmat,
    lnomjf,
    nprospectdepend,
    llieunaissance,
    dregmatdepuis,
    lcomment,
    cusercre,
    dcre,
    dmod,
    cusermod,
    clangue,
    brelanceauto,
    lccp,
    nprospectnotaire,
    lusername,
    cagence,
    nprospectagence,
    corigineprospect,
    ltelecom,
    mlongitude,
    mlatitude,
    lpassword,
    nrating,
    benqueteauto,
    lurlenquete,
    ddoubleoptin,
    bsmsauto,
    bnewsauto,
    llpassword,
    nstatutlead,
    lsearch,
    ballownews,
    ballowsms,
    bfollowup,
    cpassport,
    cisopaysnat,
    cid,
    ndetailsuivi,
    ndetailsuiviprec,
    ddetailsuivi,
    nrisklevel,
    ncategories)
AS
SELECT prospect_t.nprospect,
    prospect_t.ccivilite,
    prospect_t.cpolit,
    prospect_t.lnom,
    prospect_t.lprenom,
    prospect_t.lnomsociete,
    prospect_t.ladr,
    prospect_t.lcp,
    prospect_t.llocalite,
    prospect_t.cisopays,
    prospect_t.ltel,
    prospect_t.lfax,
    prospect_t.ltel2,
    prospect_t.lgsm,
    prospect_t.lemail,
    prospect_t.ncategorie,
    prospect_t.bactif,
    prospect_t.csexe,
    prospect_t.dnaissance,
    prospect_t.nregmat,
    prospect_t.lnomjf,
    prospect_t.nprospectdepend,
    prospect_t.llieunaissance,
    prospect_t.dregmatdepuis,
    prospect_t.lcomment,
    prospect_t.cusercre,
    prospect_t.dcre,
    prospect_t.dmod,
    prospect_t.cusermod,
    prospect_t.clangue,
    prospect_t.brelanceauto,
    prospect_t.lccp,
    prospect_t.nprospectnotaire,
    prospect_t.lusername,
    prospect_t.cagence,
    prospect_t.nprospectagence,
    prospect_t.corigineprospect,
    prospect_t.ltelecom,
    prospect_t.mlongitude,
    prospect_t.mlatitude,
    prospect_t.lpassword,
    prospect_t.nrating,
    prospect_t.benqueteauto,
    prospect_t.lurlenquete,
    prospect_t.ddoubleoptin,
    prospect_t.bsmsauto,
    prospect_t.bnewsauto,
    prospect_t.llpassword,
    prospect_t.nstatutlead,
    prospect_t.lsearch,
    prospect_t.ballownews,
    prospect_t.ballowsms,
    prospect_t.bfollowup,
    prospect_t.cpassport,
    prospect_t.cisopaysnat,
    prospect_t.cid,
    prospect_t.ndetailsuivi,
    prospect_t.ndetailsuiviprec,
    prospect_t.ddetailsuivi,
    prospect_t.nrisklevel,
    prospect_t.ncategories
FROM prospect_t
WHERE (prospect_t.ncategorie = ANY (ARRAY[0, 10])) OR prospect_t.ncategorie = 2 AND (prospect_t.cagence::text IN (
    SELECT utilisateuragence.cagence
    FROM utilisateuragence
    WHERE utilisateuragence.bselectproprio = 1 AND utilisateuragence.lusername::name = "current_user"()
    )) OR prospect_t.ncategorie <> 2 AND (prospect_t.cagence::text IN (
    SELECT utilisateuragence.cagence
    FROM utilisateuragence
    WHERE utilisateuragence.bselectprospect = 1 AND utilisateuragence.lusername::name = "current_user"()
    )) OR prospect_t.lusername::name = "current_user"();

ALTER VIEW public.prospect
  OWNER TO admin;

--grant all on prospect to bgoimmo_admin, bgoimmo_normal ;

 
 -- DPE prise en charge des logement de petite surface
 
-- DPE prise en charge des logement de petite surface - uniquement pour la France
DO $do$
BEGIN
    IF EXISTS (SELECT 1 FROM agence WHERE cisopays = 'FRA') THEN
        INSERT INTO detail (ndetail, ntypdetail, cunite, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, cusercre, dcre, cusermod, dmod, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, ndetailtrigger, ltitredoctrigger, ltyprelationtrigger, ltplsms, breport)
        VALUES 
          (3661, 155, 'm²', 1, 'Referentieoppervlakte voor DPE-berekening', 'Reference surface for DPE calculation', 'Surface de référence pour le calcul DPE', 1, 'admin', '2025-05-01', 'admin', '2025-05-01', 1, 1, 11, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, NULL, 0)
        ON CONFLICT (ndetail) DO NOTHING;
    END IF;
END $do$;


-- DPE prise en charge des logement de petite surface - uniquement pour la France
DO $do$
BEGIN
    IF EXISTS (SELECT 1 FROM agence WHERE cisopays = 'FRA') THEN
        INSERT INTO detail (ndetail, ntypdetail, cunite, binternet, ldetailnl, ldetailen, ldetailfr, bdescriptif, cusercre, dcre, cusermod, dmod, binclure, bprotect, nordre, bcritere, ldetailde, ldetailes, ldetailit, ldetailsk, ldetailcs, ldetailru, ldetailzh, bimportant, bdefault, ndetailtrigger, ltitredoctrigger, ltyprelationtrigger, ltplsms, breport)
        VALUES 
          (3662, 155, null, 1, 'Energieaudit uitgevoerd conform de geldende regelgeving', 'Energy audit carried out in accordance with current regulations', 'Audit énergétique réalisé conformément à la réglementation en vigueur', 1, 'admin', '2025-05-01', 'admin', '2025-05-01', 1, 1, 11, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, NULL, NULL, NULL, NULL, 0)
        ON CONFLICT (ndetail) DO NOTHING;
    END IF;
END $do$;





-- multi bien crit 

-- 1. Add the column (initially nullable)
--PERFORM add_column_if_not_exists('biencrit_t', 'nbiencrit', 'INTEGER');

-- 2. Create the sequence

CREATE SEQUENCE IF NOT EXISTS biencrit_t_nbiencrit_seq;

-- 3. Populate existing rows with unique values
UPDATE public.biencrit_t SET nbiencrit = nextval('biencrit_t_nbiencrit_seq') WHERE nbiencrit IS NULL;

-- 4. Set the default value for future inserts
ALTER TABLE public.biencrit_t ALTER COLUMN nbiencrit SET DEFAULT nextval('biencrit_t_nbiencrit_seq');

-- 5. Set NOT NULL constraint
ALTER TABLE public.biencrit_t ALTER COLUMN nbiencrit SET NOT NULL;

-- 6. Align the sequence with the current max value
SELECT setval('biencrit_t_nbiencrit_seq', (SELECT MAX(nbiencrit) FROM public.biencrit_t));

-- 7. Drop the old primary key constraint named 'pk_biencrit'
DO $do$
BEGIN
    IF EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'pk_biencrit' AND conrelid = 'public.biencrit_t'::regclass) THEN
        ALTER TABLE public.biencrit_t DROP CONSTRAINT pk_biencrit;
    END IF;
END $do$;

-- 8. Add a new primary key on 'nbiencrit'
DO $do$
BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'pk_biencrit' AND conrelid = 'public.biencrit_t'::regclass) THEN
        ALTER TABLE public.biencrit_t ADD CONSTRAINT pk_biencrit PRIMARY KEY (nbiencrit);
    END IF;
END $do$;

--PERFORM add_column_if_not_exists('biencrit_t', 'lusername', 'VARCHAR(10)');
	   



CREATE OR REPLACE VIEW public.biencrit(
    nprospect,
    ctypmandat1,
    mprix1max,
    ctypmandat2,
    mprix2max,
    ctyp1,
    ctyp2,
    ctyp3,
    ctyp4,
    nanneemin,
    nanneemax,
    nanneerenovmin,
    cregion1,
    cregion2,
    cregion3,
    cregion4,
    lcp1,
    lcp2,
    lcp3,
    lcp4,
    qpiecesmin,
    qpiecesmax,
    qchambresmin,
    qchambresmax,
    qsurfhabmin,
    qsurfhabmax,
    ndept1,
    ndept2,
    ndept3,
    ndept4,
    qsurfterrainmin,
    qsurfterrainmax,
    cenvironnement1,
    cenvironnement2,
    cenvironnement3,
    cenvironnement4,
    cnaturebien1,
    cnaturebien3,
    cnaturebien4,
    cnaturebien2,
    qsdbmin,
    qsdbmax,
    qgaragesmin,
    cchauf1,
    cchauf2,
    cchauf3,
    cchauf4,
    ntypcuisinemin,
    ndisponibilitemin,
    cstyle1,
    cstyle2,
    cstyle3,
    cstyle4,
    netagetot,
    mrevcadmax,
    mchargemax,
    mprecimmomax,
    nbureaumin,
    nordreetatmin,
    netatmin,
    qsddmin,
    qsurfterrassemin,
    qbureaumin,
    lsql,
    cusercre,
    dcre,
    cusermod,
    dmod,
    bctypmandat1,
    bmprix1max,
    bctypmandat2,
    bmprix2max,
    bctyp,
    bnannee,
    bnanneerenov,
    bcregion,
    blcp,
    bqpieces,
    bqchambres,
    bqsurfhab,
    bndept,
    bqsurfterrain,
    bcenvironnement,
    bcnaturebien,
    bqsdb,
    bqgarages,
    bcchauf,
    bntypcuisine,
    bndisponibilite,
    bcstyle,
    bmrevcadmax,
    bmchargemax,
    bmprecimmomax,
    bnetat,
    bqsdd,
    bqsurfterrasse,
    bqbureau,
    lcomment,
    mprix1min,
    mprix2min,
    bctypmeta,
    ctypmeta1,
    ctypmeta2,
    lbienssup,
    lprofilprive,
    lprofilpro,
    limplogement,
    limphoraires,
    bpiscine,
    bpiscinemin,
    bdetail,
    ndetail1,
    ndetail2,
    ndetail3,
    ndetail4,
    cregionmeta1,
    cregionmeta2,
    bcregionmeta,
    qsurfsejourmin,
    bqsurfsejour,
    lcp,
    cregionmeta3,
    cregionmeta4,
    cenvironnement10,
    cenvironnement11,
    cenvironnement12,
    cenvironnement13,
    cenvironnement14,
    cenvironnement15,
    cenvironnement5,
    cenvironnement6,
    cenvironnement7,
    cenvironnement8,
    cenvironnement9,
    cregion10,
    cregion11,
    cregion12,
    cregion13,
    cregion14,
    cregion15,
    cregion16,
    cregion17,
    cregion18,
    cregion19,
    cregion20,
    cregion21,
    cregion22,
    cregion23,
    cregion24,
    cregion25,
    cregion5,
    cregion6,
    cregion7,
    cregion8,
    cregion9,
    cregionmeta10,
    cregionmeta11,
    cregionmeta12,
    cregionmeta13,
    cregionmeta14,
    cregionmeta15,
    cregionmeta5,
    cregionmeta6,
    cregionmeta7,
    cregionmeta8,
    cregionmeta9,
    cstyle10,
    cstyle11,
    cstyle12,
    cstyle13,
    cstyle14,
    cstyle15,
    cstyle5,
    cstyle6,
    cstyle7,
    cstyle8,
    cstyle9,
    ctyp10,
    ctyp11,
    ctyp12,
    ctyp13,
    ctyp14,
    ctyp15,
    ctyp5,
    ctyp6,
    ctyp7,
    ctyp8,
    ctyp9,
    ctypmeta10,
    ctypmeta11,
    ctypmeta12,
    ctypmeta13,
    ctypmeta14,
    ctypmeta15,
    ctypmeta3,
    ctypmeta4,
    ctypmeta5,
    ctypmeta6,
    ctypmeta7,
    ctypmeta8,
    ctypmeta9,
    lcp10,
    lcp11,
    lcp12,
    lcp13,
    lcp14,
    lcp15,
    lcp5,
    lcp6,
    lcp7,
    lcp8,
    lcp9,
    ndetail10,
    ndetail11,
    ndetail12,
    ndetail13,
    ndetail14,
    ndetail15,
    ndetail5,
    ndetail6,
    ndetail7,
    ndetail8,
    ndetail9,
    cdevise,
    ballowforeigners,
    ballowforeignersmin,
    bprogramme,
    nprogramme1,
    nprogramme2,
    nprogramme3,
    nprogramme4,
    nprogramme5,
    nprogramme6,
    nprogramme7,
    nprogramme8,
    nprogramme9,
    nprogramme10,
    nprogramme11,
    nprogramme12,
    nprogramme13,
    nprogramme14,
    nprogramme15,
    qsurfjardinmin,
    qsurfjardinmax,
    bqsurfjardin,
    ltypsfr,
    ltypmetasfr,
    lregionsfr,
    lregionmetasfr,
    ltypmandatsfr,
    lenvironnementsfr,
    lstylesfr,
    lprogrammesfr,
    ldetailsfr,
    ltypsen,
    ltypmetasen,
    lregionsen,
    lregionmetasen,
    ltypmandatsen,
    lenvironnementsen,
    lstylesen,
    lprogrammesen,
    ldetailsen,
    lsearchen,
    lsearchfr,
    nbiencrit,
	lusername)
AS
  SELECT biencrit_t.nprospect,
         biencrit_t.ctypmandat1,
         biencrit_t.mprix1max,
         biencrit_t.ctypmandat2,
         biencrit_t.mprix2max,
         biencrit_t.ctyp1,
         biencrit_t.ctyp2,
         biencrit_t.ctyp3,
         biencrit_t.ctyp4,
         biencrit_t.nanneemin,
         biencrit_t.nanneemax,
         biencrit_t.nanneerenovmin,
         biencrit_t.cregion1,
         biencrit_t.cregion2,
         biencrit_t.cregion3,
         biencrit_t.cregion4,
         biencrit_t.lcp1,
         biencrit_t.lcp2,
         biencrit_t.lcp3,
         biencrit_t.lcp4,
         biencrit_t.qpiecesmin,
         biencrit_t.qpiecesmax,
         biencrit_t.qchambresmin,
         biencrit_t.qchambresmax,
         biencrit_t.qsurfhabmin,
         biencrit_t.qsurfhabmax,
         biencrit_t.ndept1,
         biencrit_t.ndept2,
         biencrit_t.ndept3,
         biencrit_t.ndept4,
         biencrit_t.qsurfterrainmin,
         biencrit_t.qsurfterrainmax,
         biencrit_t.cenvironnement1,
         biencrit_t.cenvironnement2,
         biencrit_t.cenvironnement3,
         biencrit_t.cenvironnement4,
         biencrit_t.cnaturebien1,
         biencrit_t.cnaturebien3,
         biencrit_t.cnaturebien4,
         biencrit_t.cnaturebien2,
         biencrit_t.qsdbmin,
         biencrit_t.qsdbmax,
         biencrit_t.qgaragesmin,
         biencrit_t.cchauf1,
         biencrit_t.cchauf2,
         biencrit_t.cchauf3,
         biencrit_t.cchauf4,
         biencrit_t.ntypcuisinemin,
         biencrit_t.ndisponibilitemin,
         biencrit_t.cstyle1,
         biencrit_t.cstyle2,
         biencrit_t.cstyle3,
         biencrit_t.cstyle4,
         biencrit_t.netagetot,
         biencrit_t.mrevcadmax,
         biencrit_t.mchargemax,
         biencrit_t.mprecimmomax,
         biencrit_t.nbureaumin,
         biencrit_t.nordreetatmin,
         biencrit_t.netatmin,
         biencrit_t.qsddmin,
         biencrit_t.qsurfterrassemin,
         biencrit_t.qbureaumin,
         biencrit_t.lsql,
         biencrit_t.cusercre,
         biencrit_t.dcre,
         biencrit_t.cusermod,
         biencrit_t.dmod,
         biencrit_t.bctypmandat1,
         biencrit_t.bmprix1max,
         biencrit_t.bctypmandat2,
         biencrit_t.bmprix2max,
         biencrit_t.bctyp,
         biencrit_t.bnannee,
         biencrit_t.bnanneerenov,
         biencrit_t.bcregion,
         biencrit_t.blcp,
         biencrit_t.bqpieces,
         biencrit_t.bqchambres,
         biencrit_t.bqsurfhab,
         biencrit_t.bndept,
         biencrit_t.bqsurfterrain,
         biencrit_t.bcenvironnement,
         biencrit_t.bcnaturebien,
         biencrit_t.bqsdb,
         biencrit_t.bqgarages,
         biencrit_t.bcchauf,
         biencrit_t.bntypcuisine,
         biencrit_t.bndisponibilite,
         biencrit_t.bcstyle,
         biencrit_t.bmrevcadmax,
         biencrit_t.bmchargemax,
         biencrit_t.bmprecimmomax,
         biencrit_t.bnetat,
         biencrit_t.bqsdd,
         biencrit_t.bqsurfterrasse,
         biencrit_t.bqbureau,
         biencrit_t.lcomment,
         biencrit_t.mprix1min,
         biencrit_t.mprix2min,
         biencrit_t.bctypmeta,
         biencrit_t.ctypmeta1,
         biencrit_t.ctypmeta2,
         biencrit_t.lbienssup,
         biencrit_t.lprofilprive,
         biencrit_t.lprofilpro,
         biencrit_t.limplogement,
         biencrit_t.limphoraires,
         biencrit_t.bpiscine,
         biencrit_t.bpiscinemin,
         biencrit_t.bdetail,
         biencrit_t.ndetail1,
         biencrit_t.ndetail2,
         biencrit_t.ndetail3,
         biencrit_t.ndetail4,
         biencrit_t.cregionmeta1,
         biencrit_t.cregionmeta2,
         biencrit_t.bcregionmeta,
         biencrit_t.qsurfsejourmin,
         biencrit_t.bqsurfsejour,
         biencrit_t.lcp,
         biencrit_t.cregionmeta3,
         biencrit_t.cregionmeta4,
         biencrit_t.cenvironnement10,
         biencrit_t.cenvironnement11,
         biencrit_t.cenvironnement12,
         biencrit_t.cenvironnement13,
         biencrit_t.cenvironnement14,
         biencrit_t.cenvironnement15,
         biencrit_t.cenvironnement5,
         biencrit_t.cenvironnement6,
         biencrit_t.cenvironnement7,
         biencrit_t.cenvironnement8,
         biencrit_t.cenvironnement9,
         biencrit_t.cregion10,
         biencrit_t.cregion11,
         biencrit_t.cregion12,
         biencrit_t.cregion13,
         biencrit_t.cregion14,
         biencrit_t.cregion15,
         biencrit_t.cregion16,
         biencrit_t.cregion17,
         biencrit_t.cregion18,
         biencrit_t.cregion19,
         biencrit_t.cregion20,
         biencrit_t.cregion21,
         biencrit_t.cregion22,
         biencrit_t.cregion23,
         biencrit_t.cregion24,
         biencrit_t.cregion25,
         biencrit_t.cregion5,
         biencrit_t.cregion6,
         biencrit_t.cregion7,
         biencrit_t.cregion8,
         biencrit_t.cregion9,
         biencrit_t.cregionmeta10,
         biencrit_t.cregionmeta11,
         biencrit_t.cregionmeta12,
         biencrit_t.cregionmeta13,
         biencrit_t.cregionmeta14,
         biencrit_t.cregionmeta15,
         biencrit_t.cregionmeta5,
         biencrit_t.cregionmeta6,
         biencrit_t.cregionmeta7,
         biencrit_t.cregionmeta8,
         biencrit_t.cregionmeta9,
         biencrit_t.cstyle10,
         biencrit_t.cstyle11,
         biencrit_t.cstyle12,
         biencrit_t.cstyle13,
         biencrit_t.cstyle14,
         biencrit_t.cstyle15,
         biencrit_t.cstyle5,
         biencrit_t.cstyle6,
         biencrit_t.cstyle7,
         biencrit_t.cstyle8,
         biencrit_t.cstyle9,
         biencrit_t.ctyp10,
         biencrit_t.ctyp11,
         biencrit_t.ctyp12,
         biencrit_t.ctyp13,
         biencrit_t.ctyp14,
         biencrit_t.ctyp15,
         biencrit_t.ctyp5,
         biencrit_t.ctyp6,
         biencrit_t.ctyp7,
         biencrit_t.ctyp8,
         biencrit_t.ctyp9,
         biencrit_t.ctypmeta10,
         biencrit_t.ctypmeta11,
         biencrit_t.ctypmeta12,
         biencrit_t.ctypmeta13,
         biencrit_t.ctypmeta14,
         biencrit_t.ctypmeta15,
         biencrit_t.ctypmeta3,
         biencrit_t.ctypmeta4,
         biencrit_t.ctypmeta5,
         biencrit_t.ctypmeta6,
         biencrit_t.ctypmeta7,
         biencrit_t.ctypmeta8,
         biencrit_t.ctypmeta9,
         biencrit_t.lcp10,
         biencrit_t.lcp11,
         biencrit_t.lcp12,
         biencrit_t.lcp13,
         biencrit_t.lcp14,
         biencrit_t.lcp15,
         biencrit_t.lcp5,
         biencrit_t.lcp6,
         biencrit_t.lcp7,
         biencrit_t.lcp8,
         biencrit_t.lcp9,
         biencrit_t.ndetail10,
         biencrit_t.ndetail11,
         biencrit_t.ndetail12,
         biencrit_t.ndetail13,
         biencrit_t.ndetail14,
         biencrit_t.ndetail15,
         biencrit_t.ndetail5,
         biencrit_t.ndetail6,
         biencrit_t.ndetail7,
         biencrit_t.ndetail8,
         biencrit_t.ndetail9,
         biencrit_t.cdevise,
         biencrit_t.ballowforeigners,
         biencrit_t.ballowforeignersmin,
         biencrit_t.bprogramme,
         biencrit_t.nprogramme1,
         biencrit_t.nprogramme2,
         biencrit_t.nprogramme3,
         biencrit_t.nprogramme4,
         biencrit_t.nprogramme5,
         biencrit_t.nprogramme6,
         biencrit_t.nprogramme7,
         biencrit_t.nprogramme8,
         biencrit_t.nprogramme9,
         biencrit_t.nprogramme10,
         biencrit_t.nprogramme11,
         biencrit_t.nprogramme12,
         biencrit_t.nprogramme13,
         biencrit_t.nprogramme14,
         biencrit_t.nprogramme15,
         biencrit_t.qsurfjardinmin,
         biencrit_t.qsurfjardinmax,
         biencrit_t.bqsurfjardin,
         biencrit_t.ltypsfr,
         biencrit_t.ltypmetasfr,
         biencrit_t.lregionsfr,
         biencrit_t.lregionmetasfr,
         biencrit_t.ltypmandatsfr,
         biencrit_t.lenvironnementsfr,
         biencrit_t.lstylesfr,
         biencrit_t.lprogrammesfr,
         biencrit_t.ldetailsfr,
         biencrit_t.ltypsen,
         biencrit_t.ltypmetasen,
         biencrit_t.lregionsen,
         biencrit_t.lregionmetasen,
         biencrit_t.ltypmandatsen,
         biencrit_t.lenvironnementsen,
         biencrit_t.lstylesen,
         biencrit_t.lprogrammesen,
         biencrit_t.ldetailsen,
         biencrit_t.lsearchen,
         biencrit_t.lsearchfr,
         biencrit_t.nbiencrit,
         biencrit_t.lusername
  FROM biencrit_t
  WHERE (biencrit_t.nprospect IN (
                                   SELECT prospect.nprospect
                                   FROM prospect
        ));
		

		


-- 14/07/2025 fonction pour logger les changements de nom ou prénom
CREATE OR REPLACE FUNCTION public.f_insertdeleteprospectlog (
)
RETURNS trigger AS
$body$
DECLARE
    coperation VARCHAR(10);
BEGIN
    -- Tentative d'insertion dans la table deleteprospectlog
    BEGIN
      --Detect trigger operation then set coperation
        IF TG_OP = 'DELETE' THEN
            coperation = 'DELETE';
            RETURN OLD;
            
        ELSIF TG_OP = 'UPDATE' THEN
            coperation = 'UPDATE';

		-- check if lnom or lprenom has changed
        IF NEW.lnom IS NOT DISTINCT FROM OLD.lnom AND NEW.lprenom IS NOT DISTINCT FROM OLD.lprenom AND NEW.lusername IS NOT DISTINCT FROM OLD.lusername THEN
            -- nothing to do because name and firstname didn't change
            RETURN NEW;
        END IF;

        ELSIF TG_OP = 'INSERT' THEN
            coperation = 'INSERT';
        END IF;

        INSERT INTO deleteprospectlog (
            nprospect, 
            coperation,
            lnom, lprenom, lgsm, ltel, lemail, ladr, lcp, llocalite, 
            cisopays, lusername, prospect_dmod, prospect_dcre, 
            prospect_cusercre, prospect_cusermod
        ) VALUES (
            OLD.nprospect, 
            coperation,
            OLD.lnom, OLD.lprenom, OLD.lgsm, OLD.ltel, OLD.lemail, 
            OLD.ladr, OLD.lcp, OLD.llocalite, OLD.cisopays, OLD.lusername, 
            OLD.dmod, OLD.dcre, OLD.cusercre, OLD.cusermod
        );
    EXCEPTION
        -- En cas d'erreur, levée d'une exception pour annuler la suppression
        WHEN OTHERS THEN
            RAISE EXCEPTION 'Erreur lors de l''insertion dans deleteprospectlog. Suppression annulée.';
    END;

    -- Retourner la ligne OLD pour permettre la suppression
    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;

ALTER FUNCTION public.f_insertdeleteprospectlog ()
  OWNER TO postgres;


--DROP TRIGGER tbd_deleteprospectlog ON public.prospect_t;


--DROP TRIGGER IF EXISTS tbud_prospectlog ON public.prospect_t;
--CREATE TRIGGER tbud_prospectlog
  --BEFORE UPDATE OF lnom, lprenom OR DELETE 
  --ON public.prospect_t
  
--FOR EACH ROW 
  --EXECUTE PROCEDURE public.f_insertdeleteprospectlog();



--Create signature_procedure table if it doesn't exist
        
CREATE TABLE IF NOT EXISTS signatures (
id SERIAL PRIMARY KEY,
cforeignid VARCHAR(255),
ndoc INTEGER,
cagence VARCHAR(50),
ctype VARCHAR(50),
cstatus VARCHAR(50),
lname TEXT,
ldescription TEXT,
lstatus VARCHAR(50),
nsigners INTEGER[] DEFAULT '{}',
nfollowers INTEGER[] DEFAULT '{}',
dcre TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
cusercre VARCHAR(50),
dmod TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
cusermod VARCHAR(50));
       
DROP TRIGGER IF EXISTS tbui_signature_audit ON public.signatures;
CREATE TRIGGER tbui_signature_audit
  BEFORE INSERT OR UPDATE 
  ON public.signatures
  
FOR EACH ROW 
  EXECUTE PROCEDURE public.f_set_audit();


--PERFORM add_column_if_not_exists('biencrit_t', 'lusername', 'VARCHAR(10)');
	   
DROP VIEW IF EXISTS public.biencritfirst ;	   

CREATE OR REPLACE VIEW biencritfirst AS
SELECT DISTINCT ON (nprospect)
    nprospect,
    ctypmandat1,
    mprix1max,
    ctypmandat2,
    mprix2max,
    ctyp1,
    ctyp2,
    ctyp3,
    ctyp4,
    nanneemin,
    nanneemax,
    nanneerenovmin,
    cregion1,
    cregion2,
    cregion3,
    cregion4,
    lcp1,
    lcp2,
    lcp3,
    lcp4,
    qpiecesmin,
    qpiecesmax,
    qchambresmin,
    qchambresmax,
    qsurfhabmin,
    qsurfhabmax,
    ndept1,
    ndept2,
    ndept3,
    ndept4,
    qsurfterrainmin,
    qsurfterrainmax,
    cenvironnement1,
    cenvironnement2,
    cenvironnement3,
    cenvironnement4,
    cnaturebien1,
    cnaturebien3,
    cnaturebien4,
    cnaturebien2,
    qsdbmin,
    qsdbmax,
    qgaragesmin,
    cchauf1,
    cchauf2,
    cchauf3,
    cchauf4,
    ntypcuisinemin,
    ndisponibilitemin,
    cstyle1,
    cstyle2,
    cstyle3,
    cstyle4,
    netagetot,
    mrevcadmax,
    mchargemax,
    mprecimmomax,
    nbureaumin,
    nordreetatmin,
    netatmin,
    qsddmin,
    qsurfterrassemin,
    qbureaumin,
    lsql,
    cusercre,
    dcre,
    cusermod,
    dmod,
    bctypmandat1,
    bmprix1max,
    bctypmandat2,
    bmprix2max,
    bctyp,
    bnannee,
    bnanneerenov,
    bcregion,
    blcp,
    bqpieces,
    bqchambres,
    bqsurfhab,
    bndept,
    bqsurfterrain,
    bcenvironnement,
    bcnaturebien,
    bqsdb,
    bqgarages,
    bcchauf,
    bntypcuisine,
    bndisponibilite,
    bcstyle,
    bmrevcadmax,
    bmchargemax,
    bmprecimmomax,
    bnetat,
    bqsdd,
    bqsurfterrasse,
    bqbureau,
    lcomment,
    mprix1min,
    mprix2min,
    bctypmeta,
    ctypmeta1,
    ctypmeta2,
    lbienssup,
    lprofilprive,
    lprofilpro,
    limplogement,
    limphoraires,
    bpiscine,
    bpiscinemin,
    bdetail,
    ndetail1,
    ndetail2,
    ndetail3,
    ndetail4,
    cregionmeta1,
    cregionmeta2,
    bcregionmeta,
    qsurfsejourmin,
    bqsurfsejour,
    lcp,
    cregionmeta3,
    cregionmeta4,
    cenvironnement11,
    cenvironnement12,
    cenvironnement13,
    cenvironnement14,
    cenvironnement15,
    cenvironnement5,
    cenvironnement6,
    cenvironnement7,
    cenvironnement8,
    cenvironnement9,
    cregion10,
    cregion11,
    cregion12,
    cregion13,
    cregion14,
    cregion15,
    cregion5,
    cregion6,
    cregion7,
    cregion8,
    cregion9,
    cregionmeta10,
    cregionmeta11,
    cregionmeta12,
    cregionmeta13,
    cregionmeta14,
    cregionmeta15,
    cregionmeta5,
    cregionmeta6,
    cregionmeta7,
    cregionmeta8,
    cregionmeta9,
    cstyle10,
    cstyle11,
    cstyle12,
    cstyle13,
    cstyle14,
    cstyle15,
    cstyle5,
    cstyle6,
    cstyle7,
    cstyle8,
    cstyle9,
    ctyp10,
    ctyp11,
    ctyp12,
    ctyp13,
    ctyp14,
    ctyp15,
    ctyp5,
    ctyp6,
    ctyp7,
    ctyp8,
    ctyp9,
    ctypmeta10,
    ctypmeta11,
    ctypmeta12,
    ctypmeta13,
    ctypmeta14,
    ctypmeta15,
    ctypmeta3,
    ctypmeta4,
    ctypmeta5,
    ctypmeta6,
    ctypmeta7,
    ctypmeta8,
    ctypmeta9,
    lcp10,
    lcp11,
    lcp12,
    lcp13,
    lcp14,
    lcp15,
    lcp5,
    lcp6,
    lcp7,
    lcp8,
    lcp9,
    ndetail10,
    ndetail11,
    ndetail12,
    ndetail13,
    ndetail14,
    ndetail15,
    ndetail5,
    ndetail6,
    ndetail7,
    ndetail8,
    ndetail9,
    cenvironnement10,
    ctyps,
    ctypmetas,
    cregions,
    cregionmetas,
    cstyles,
    cenvironnements,
    cdevise,
    ballowforeigners,
    ballowforeignersmin,
    bprogramme,
    nprogramme1,
    nprogramme2,
    nprogramme3,
    nprogramme4,
    nprogramme5,
    nprogramme6,
    nprogramme7,
    nprogramme8,
    nprogramme9,
    nprogramme10,
    nprogramme11,
    nprogramme12,
    nprogramme13,
    nprogramme14,
    nprogramme15,
    qsurfjardinmin,
    qsurfjardinmax,
    bqsurfjardin,
    cregion16,
    cregion17,
    cregion18,
    cregion19,
    cregion20,
    cregion21,
    cregion22,
    cregion23,
    cregion24,
    cregion25,
    ltypsfr,
    ltypmetas,
    lregions,
    lregionmetas,
    ltypmandats,
    lenvironnementsfr,
    lstylesfr,
    lprogrammesfr,
    ldetailsfr,
    ltypsen,
    ltypmetasen,
    lregionsen,
    lregionmetasen,
    ltypmandatsen,
    lenvironnementsen,
    lstylesen,
    lprogrammesen,
    ldetailssen,
    lsearchen,
    lsearchfr,
    ltypmetasfr,
    lregionsfr,
    lregionmetasfr,
    ltypmandatsfr,
    ldetailssfr,
    ldetailsen,
    nbiencrit
FROM biencrit_t
WHERE nprospect in (select nprospect from prospect)
ORDER BY nprospect, nbiencrit ;

--grant all on biencritfirst to bgoimmo_normal, bgoimmo_admin ;

-- biencrit supprimer l'index unique sur nprospect  
DROP INDEX IF EXISTS new_index;


DROP FUNCTION IF EXISTS set_limit(real);
DROP FUNCTION IF EXISTS set_limit(float4);
DROP FUNCTION IF EXISTS similarity(text, text);
DROP FUNCTION IF EXISTS show_limit();
DROP FUNCTION IF EXISTS set_limit(real);
DROP FUNCTION IF EXISTS show_trgm ();

--CREATE EXTENSION IF NOT EXISTS pg_trgm;
  
DO $do$
BEGIN
    -- Create GIST index on prospect_t only if PostgreSQL version >= 10
    IF current_setting('server_version_num')::int > 100000 THEN
        CREATE INDEX IF NOT EXISTS idx_prospect_t_lsearch_gist ON prospect_t USING GIST (to_tsvector('mydict', lsearch));
    END IF;
EXCEPTION
    WHEN OTHERS THEN
        -- Silently ignore errors if the index creation fails
        NULL;
END $do$;



CREATE INDEX IF NOT EXISTS idx_biencrit_nprospect_nbiencrit
ON biencrit_t (nprospect, nbiencrit);

	




CREATE OR REPLACE FUNCTION trg_set_qnombre_from_comment()
RETURNS trigger
LANGUAGE plpgsql
AS $$
DECLARE
  leading_num_text text;
BEGIN

-- Fonction de trigger qui evite toute confusion lors de la saisie des montants haut et bas de la consommation d'énergie , ges et conso energétique
-- const NDETAIL_DPE_ENERGIE = 3480;
--  const NDETAIL_DPE_GES = 3481;
--const NDETAIL_DPE_MMONTANTBASDEPENERGIE = 3488;
--const NDETAIL_DPE_MMONTANTHAUTDEPENERGIE = 3489;

  IF NEW.ndetail IN (3488, 3489,3480,3481)
     AND (NEW.qnombre IS NULL OR NEW.qnombre = 0)
     AND NEW.lcommentfr IS NOT NULL
     AND NEW.lcommentfr ~ '^\s*\d+'  -- commence par un nombre (espaces initiaux permis)
  THEN
    -- N'extrait que le nombre de tête (ignore tout texte qui suit)
    leading_num_text := (regexp_match(NEW.lcommentfr, '^\s*(\d+)'))[1];

    IF leading_num_text IS NOT NULL THEN
      NEW.qnombre := leading_num_text::int;
      NEW.lcommentfr := '';  -- met à blanc
    END IF;
  END IF;

  RETURN NEW;
END;
$$;


CREATE OR REPLACE FUNCTION public.trg_set_qnombre_from_comment (
)
RETURNS trigger AS
$body$
DECLARE
  leading_num_text text;
BEGIN

-- Fonction de trigger qui evite toute confusion lors de la saisie des montants haut et bas de la consommation d'énergie , ges et conso energétique
--	const NDETAIL_DPE_ENERGIE = 3480;
--    const NDETAIL_DPE_GES = 3481;

  IF NEW.ndetail IN (3488, 3489,3480,3481)
     AND (NEW.qnombre IS NULL OR NEW.qnombre = 0)
     AND NEW.lcommentfr IS NOT NULL
     AND NEW.lcommentfr ~ '^\s*\d+'  -- commence par un nombre (espaces initiaux permis)
  THEN
    -- N'extrait que le nombre de tête (ignore tout texte qui suit)
    leading_num_text := (regexp_match(NEW.lcommentfr, '^\s*(\d+)'))[1];

    IF leading_num_text IS NOT NULL THEN
      NEW.qnombre := leading_num_text::int;
      NEW.lcommentfr := '';  -- met à blanc
    END IF;
  END IF;

  RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;




-- 2) Trigger avant INSERT ou UPDATE sur detailbien
DROP TRIGGER IF EXISTS set_qnombre_from_comment_biub ON detailbien_t;
CREATE TRIGGER set_qnombre_from_comment_biub
BEFORE INSERT OR UPDATE ON detailbien_t
FOR EACH ROW
EXECUTE PROCEDURE trg_set_qnombre_from_comment();



CREATE OR REPLACE VIEW bien AS
 SELECT bien_t.*
   FROM bien_t
  WHERE (bien_t.lusername::text = "current_user"() OR 
        EXISTS ( SELECT NULL::unknown AS unknown
         FROM utilisateuragence
         WHERE utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));




CREATE OR REPLACE FUNCTION f_cbien_csv_from_lbienssup(p_lbienssup text)
RETURNS text
LANGUAGE sql
STABLE
AS $$
-- fonciton pour exlater lbienssup en liste des références des  biens 
  SELECT NULLIF(
           string_agg(
             replace(trim(b.cbien::text), '"', ''),  -- supprime d’éventuels "
             ',' ORDER BY t.ord
           ),
           ''  -- renvoie NULL si rien trouvé
         )
  FROM regexp_split_to_table(COALESCE(p_lbienssup, ''), '\s*,\s*') WITH ORDINALITY AS t(nb_txt, ord)
  JOIN bien AS b
    ON (t.nb_txt ~ '^\d+$') AND b.nbien = t.nb_txt::int;
$$;
	
	
	
update typrelation set 	nordreoffre = nordrepro ;

INSERT INTO public.typrelation ("ntyprelation", "ltyprelation", "brendezvous", "nordrepro", "nordrebien", "ntemplate", "cusercre", "dcre", "cusermod", "dmod", "ltyprelationnl", "ltyprelationfr", "ltyprelationde", "ncouleur", "ncouleurtexte", "ltyprelationes", "ltyprelationit", "ltyprelationsk", "ltyprelationcs", "ltyprelationru", "ltyprelationzh", "bactivite", "ltyprelationen", "bautoconf", "binclure", "ccouleur", "ccouleurtexte", "cclasse", "cicone", "ctyprelationmeta", "brenseignement")
VALUES (80, 'Envoi de message WhatsApp', 0, 100, 100, NULL, 'system', '08/04/2009 00:00:10', 'admin', '06/04/2018 13:46:03.68', 'WhatsApp-bericht verzonden', 'Envoi de message WhatsApp', 'WhatsApp-Nachricht gesendet', 16777215, 0, 'Mensaje de WhatsApp enviado', 'Messaggio WhatsApp inviato', 'Správa WhatsApp odoslaná', 'Zpráva WhatsApp odeslána', 'Сообщение WhatsApp отправлено', 'WhatsApp消息已发送', 0, 'WhatsApp message sent', 0, 1, '#ffffff', '#000000', 'black', 'event', 'change', NULL)
ON CONFLICT (ntyprelation) DO NOTHING;

-- ?
--alter table offre_t add noffre int ;

--
--alter table prospectbien_t add noffre int ;
	
CREATE OR REPLACE VIEW prospectbien AS
 SELECT prospectbien_t.*
   FROM prospectbien_t
  WHERE prospectbien_t.ntyprelation = 5 OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            typrelation
          WHERE prospectbien_t.ntyprelation = typrelation.ntyprelation AND (utilisateuragence.bselecthisto = 1 OR utilisateuragence.bselectrv = 1 AND typrelation.brendezvous = 1) AND utilisateuragence.lusername::name = "current_user"() AND (prospectbien_t.cagence::text = utilisateuragence.cagence::text OR prospectbien_t.cagence::text = ''::text OR prospectbien_t.cagence IS NULL)));






	
	
	-- suppreesion du default 0 pour budget min
CREATE OR REPLACE FUNCTION public.f_set_biencrit_cdevise (
)
RETURNS trigger AS
$body$
  DECLARE
    ls_cdevise character varying(3);
 BEGIN

IF NEW.cdevise IS NULL THEN

   SELECT INTO ls_cdevise max(cdeviseref) FROM agence ;

   IF ls_cdevise IS NULL OR ls_cdevise = '' THEN
      NEW.cdevise = 'EUR';
   ELSE
       NEW.cdevise = ls_cdevise;
   END IF ;
END IF;


IF NEW.mprix1min IS NULL THEN

 --  NEW.mprix1min = 0 ;

END IF;


  RETURN NEW;

END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;	
	
	

-- pour que l'historique mette à jour bien.dmod (openhouse)
--CREATE OR REPLACE FUNCTION f_update_biendmod() 
--RETURNS TRIGGER AS $$
--BEGIN
--  -- Mise à jour de la colonne dmod dans la table bien et prospectbien lors d'un INSERT ou UPDATE
--  IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
--    UPDATE bien
--    SET dmod = CURRENT_DATE
--   WHERE nbien = NEW.nbien;
--    
--
   -- Si l'opération est DELETE, on met à jour aussi la table 'bien' et 'prospectbien'
--    UPDATE bien
--    SET dmod = CURRENT_DATE
--    WHERE nbien = OLD.nbien;
--
--
--  END IF;
--
--  RETURN NEW;
--END;
--$$ LANGUAGE plpgsql;
--
--
--CREATE TRIGGER tauid_bien_dmod
--AFTER INSERT OR UPDATE OR DELETE ON prospectbien_t
--FOR EACH ROW
--EXECUTE FUNCTION f_update_biendmod();



CREATE OR REPLACE VIEW public.prospectbien_lastpub(
    nrelation,
    nprospect,
    nbien,
    ntyprelation,
    ddebut,
    dfin,
    lrem,
    lusername,
    dcre,
    cusercre,
    dmod,
    cusermod,
    mcout,
    dalarm,
    ndoc,
    nrubrique,
    bannulation,
    cagence,
    bphoto,
    ldocfilename,
    bconfirmed,
    dfinpublication,
    dderpublication,
    lvisite,
    cavisclient,
    cidannonceportail,
    mmontant,
    lemailcontent,
    dlastpubannonceur)
AS
  SELECT b.nrelation,
         b.nprospect,
         b.nbien,
         b.ntyprelation,
         b.ddebut,
         b.dfin,
         b.lrem,
         b.lusername,
         b.dcre,
         b.cusercre,
         b.dmod,
         b.cusermod,
         b.mcout,
         b.dalarm,
         b.ndoc,
         b.nrubrique,
         b.bannulation,
         b.cagence,
         b.bphoto,
         b.ldocfilename,
         b.bconfirmed,
         b.dfinpublication,
         b.dderpublication,
         b.lvisite,
         b.cavisclient,
         b.cidannonceportail,
         b.mmontant,
         b.lemailcontent,
         b.dlastpubannonceur
  FROM prospectbien b
  WHERE (b.nrelation IN (
                          SELECT max(c.nrelation) AS max
                          FROM prospectbien c
                          WHERE c.ntyprelation = 10
                          GROUP BY c.nprospect,
                                   c.nbien
        ));




DROP VIEW IF EXISTS biencritfirst CASCADE;

CREATE OR REPLACE VIEW public.biencritfirst (
    nprospect,
    ctypmandat1,
    mprix1max,
    ctypmandat2,
    mprix2max,
    ctyp1,
    ctyp2,
    ctyp3,
    ctyp4,
    nanneemin,
    nanneemax,
    nanneerenovmin,
    cregion1,
    cregion2,
    cregion3,
    cregion4,
    lcp1,
    lcp2,
    lcp3,
    lcp4,
    qpiecesmin,
    qpiecesmax,
    qchambresmin,
    qchambresmax,
    qsurfhabmin,
    qsurfhabmax,
    ndept1,
    ndept2,
    ndept3,
    ndept4,
    qsurfterrainmin,
    qsurfterrainmax,
    cenvironnement1,
    cenvironnement2,
    cenvironnement3,
    cenvironnement4,
    cnaturebien1,
    cnaturebien3,
    cnaturebien4,
    cnaturebien2,
    qsdbmin,
    qsdbmax,
    qgaragesmin,
    cchauf1,
    cchauf2,
    cchauf3,
    cchauf4,
    ntypcuisinemin,
    ndisponibilitemin,
    cstyle1,
    cstyle2,
    cstyle3,
    cstyle4,
    netagetot,
    mrevcadmax,
    mchargemax,
    mprecimmomax,
    nbureaumin,
    nordreetatmin,
    netatmin,
    qsddmin,
    qsurfterrassemin,
    qbureaumin,
    lsql,
    cusercre,
    dcre,
    cusermod,
    dmod,
    bctypmandat1,
    bmprix1max,
    bctypmandat2,
    bmprix2max,
    bctyp,
    bnannee,
    bnanneerenov,
    bcregion,
    blcp,
    bqpieces,
    bqchambres,
    bqsurfhab,
    bndept,
    bqsurfterrain,
    bcenvironnement,
    bcnaturebien,
    bqsdb,
    bqgarages,
    bcchauf,
    bntypcuisine,
    bndisponibilite,
    bcstyle,
    bmrevcadmax,
    bmchargemax,
    bmprecimmomax,
    bnetat,
    bqsdd,
    bqsurfterrasse,
    bqbureau,
    lcomment,
    mprix1min,
    mprix2min,
    bctypmeta,
    ctypmeta1,
    ctypmeta2,
    lbienssup,
    lprofilprive,
    lprofilpro,
    limplogement,
    limphoraires,
    bpiscine,
    bpiscinemin,
    bdetail,
    ndetail1,
    ndetail2,
    ndetail3,
    ndetail4,
    cregionmeta1,
    cregionmeta2,
    bcregionmeta,
    qsurfsejourmin,
    bqsurfsejour,
    lcp,
    cregionmeta3,
    cregionmeta4,
    cenvironnement10,
    cenvironnement11,
    cenvironnement12,
    cenvironnement13,
    cenvironnement14,
    cenvironnement15,
    cenvironnement5,
    cenvironnement6,
    cenvironnement7,
    cenvironnement8,
    cenvironnement9,
    cregion10,
    cregion11,
    cregion12,
    cregion13,
    cregion14,
    cregion15,
    cregion5,
    cregion6,
    cregion7,
    cregion8,
    cregion9,
    cregionmeta10,
    cregionmeta11,
    cregionmeta12,
    cregionmeta13,
    cregionmeta14,
    cregionmeta15,
    cregionmeta5,
    cregionmeta6,
    cregionmeta7,
    cregionmeta8,
    cregionmeta9,
    cstyle10,
    cstyle11,
    cstyle12,
    cstyle13,
    cstyle14,
    cstyle15,
    cstyle5,
    cstyle6,
    cstyle7,
    cstyle8,
    cstyle9,
    ctyp10,
    ctyp11,
    ctyp12,
    ctyp13,
    ctyp14,
    ctyp15,
    ctyp5,
    ctyp6,
    ctyp7,
    ctyp8,
    ctyp9,
    ctypmeta10,
    ctypmeta11,
    ctypmeta12,
    ctypmeta13,
    ctypmeta14,
    ctypmeta15,
    ctypmeta3,
    ctypmeta4,
    ctypmeta5,
    ctypmeta6,
    ctypmeta7,
    ctypmeta8,
    ctypmeta9,
    lcp10,
    lcp11,
    lcp12,
    lcp13,
    lcp14,
    lcp15,
    lcp5,
    lcp6,
    lcp7,
    lcp8,
    lcp9,
    ndetail10,
    ndetail11,
    ndetail12,
    ndetail13,
    ndetail14,
    ndetail15,
    ndetail5,
    ndetail6,
    ndetail7,
    ndetail8,
    ndetail9,
    cdevise,
    ballowforeigners,
    ballowforeignersmin,
    bprogramme,
    nprogramme1,
    nprogramme2,
    nprogramme3,
    nprogramme4,
    nprogramme5,
    nprogramme6,
    nprogramme7,
    nprogramme8,
    nprogramme9,
    nprogramme10,
    nprogramme11,
    nprogramme12,
    nprogramme13,
    nprogramme14,
    nprogramme15,
    qsurfjardinmax,
    bqsurfjardin,
    cregion16,
    cregion17,
    cregion18,
    cregion19,
    cregion20,
    cregion21,
    cregion22,
    cregion23,
    cregion24,
    cregion25,
    ctyps,
    ctypmetas,
    cregions,
    cregionmetas,
    cstyles,
    cenvironnements,
    ltypsfr,
    ltypmetas,
    lregions,
    lregionmetas,
    ltypmandats,
    lenvironnementsfr,
    lstylesfr,
    lprogrammesfr,
    ldetailsfr,
    ltypsen,
    ltypmetasen,
    lregionsen,
    lregionmetasen,
    ltypmandatsen,
    lenvironnementsen,
    lstylesen,
    lprogrammesen,
    ldetailssen,
    lsearchen,
    lsearchfr,
    ltypmetasfr,
    lregionsfr,
    lregionmetasfr,
    ltypmandatsfr,
    ldetailssfr,
    ldetailsen,
    qsurfjardinmin,
    nbiencrit,
	lusername)
AS
SELECT DISTINCT ON (biencrit_t.nprospect) biencrit_t.nprospect,
    biencrit_t.ctypmandat1,
    biencrit_t.mprix1max,
    biencrit_t.ctypmandat2,
    biencrit_t.mprix2max,
    biencrit_t.ctyp1,
    biencrit_t.ctyp2,
    biencrit_t.ctyp3,
    biencrit_t.ctyp4,
    biencrit_t.nanneemin,
    biencrit_t.nanneemax,
    biencrit_t.nanneerenovmin,
    biencrit_t.cregion1,
    biencrit_t.cregion2,
    biencrit_t.cregion3,
    biencrit_t.cregion4,
    biencrit_t.lcp1,
    biencrit_t.lcp2,
    biencrit_t.lcp3,
    biencrit_t.lcp4,
    biencrit_t.qpiecesmin,
    biencrit_t.qpiecesmax,
    biencrit_t.qchambresmin,
    biencrit_t.qchambresmax,
    biencrit_t.qsurfhabmin,
    biencrit_t.qsurfhabmax,
    biencrit_t.ndept1,
    biencrit_t.ndept2,
    biencrit_t.ndept3,
    biencrit_t.ndept4,
    biencrit_t.qsurfterrainmin,
    biencrit_t.qsurfterrainmax,
    biencrit_t.cenvironnement1,
    biencrit_t.cenvironnement2,
    biencrit_t.cenvironnement3,
    biencrit_t.cenvironnement4,
    biencrit_t.cnaturebien1,
    biencrit_t.cnaturebien3,
    biencrit_t.cnaturebien4,
    biencrit_t.cnaturebien2,
    biencrit_t.qsdbmin,
    biencrit_t.qsdbmax,
    biencrit_t.qgaragesmin,
    biencrit_t.cchauf1,
    biencrit_t.cchauf2,
    biencrit_t.cchauf3,
    biencrit_t.cchauf4,
    biencrit_t.ntypcuisinemin,
    biencrit_t.ndisponibilitemin,
    biencrit_t.cstyle1,
    biencrit_t.cstyle2,
    biencrit_t.cstyle3,
    biencrit_t.cstyle4,
    biencrit_t.netagetot,
    biencrit_t.mrevcadmax,
    biencrit_t.mchargemax,
    biencrit_t.mprecimmomax,
    biencrit_t.nbureaumin,
    biencrit_t.nordreetatmin,
    biencrit_t.netatmin,
    biencrit_t.qsddmin,
    biencrit_t.qsurfterrassemin,
    biencrit_t.qbureaumin,
    biencrit_t.lsql,
    biencrit_t.cusercre,
    biencrit_t.dcre,
    biencrit_t.cusermod,
    biencrit_t.dmod,
    biencrit_t.bctypmandat1,
    biencrit_t.bmprix1max,
    biencrit_t.bctypmandat2,
    biencrit_t.bmprix2max,
    biencrit_t.bctyp,
    biencrit_t.bnannee,
    biencrit_t.bnanneerenov,
    biencrit_t.bcregion,
    biencrit_t.blcp,
    biencrit_t.bqpieces,
    biencrit_t.bqchambres,
    biencrit_t.bqsurfhab,
    biencrit_t.bndept,
    biencrit_t.bqsurfterrain,
    biencrit_t.bcenvironnement,
    biencrit_t.bcnaturebien,
    biencrit_t.bqsdb,
    biencrit_t.bqgarages,
    biencrit_t.bcchauf,
    biencrit_t.bntypcuisine,
    biencrit_t.bndisponibilite,
    biencrit_t.bcstyle,
    biencrit_t.bmrevcadmax,
    biencrit_t.bmchargemax,
    biencrit_t.bmprecimmomax,
    biencrit_t.bnetat,
    biencrit_t.bqsdd,
    biencrit_t.bqsurfterrasse,
    biencrit_t.bqbureau,
    biencrit_t.lcomment,
    biencrit_t.mprix1min,
    biencrit_t.mprix2min,
    biencrit_t.bctypmeta,
    biencrit_t.ctypmeta1,
    biencrit_t.ctypmeta2,
    biencrit_t.lbienssup,
    biencrit_t.lprofilprive,
    biencrit_t.lprofilpro,
    biencrit_t.limplogement,
    biencrit_t.limphoraires,
    biencrit_t.bpiscine,
    biencrit_t.bpiscinemin,
    biencrit_t.bdetail,
    biencrit_t.ndetail1,
    biencrit_t.ndetail2,
    biencrit_t.ndetail3,
    biencrit_t.ndetail4,
    biencrit_t.cregionmeta1,
    biencrit_t.cregionmeta2,
    biencrit_t.bcregionmeta,
    biencrit_t.qsurfsejourmin,
    biencrit_t.bqsurfsejour,
    biencrit_t.lcp,
    biencrit_t.cregionmeta3,
    biencrit_t.cregionmeta4,
    biencrit_t.cenvironnement10,
    biencrit_t.cenvironnement11,
    biencrit_t.cenvironnement12,
    biencrit_t.cenvironnement13,
    biencrit_t.cenvironnement14,
    biencrit_t.cenvironnement15,
    biencrit_t.cenvironnement5,
    biencrit_t.cenvironnement6,
    biencrit_t.cenvironnement7,
    biencrit_t.cenvironnement8,
    biencrit_t.cenvironnement9,
    biencrit_t.cregion10,
    biencrit_t.cregion11,
    biencrit_t.cregion12,
    biencrit_t.cregion13,
    biencrit_t.cregion14,
    biencrit_t.cregion15,
    biencrit_t.cregion5,
    biencrit_t.cregion6,
    biencrit_t.cregion7,
    biencrit_t.cregion8,
    biencrit_t.cregion9,
    biencrit_t.cregionmeta10,
    biencrit_t.cregionmeta11,
    biencrit_t.cregionmeta12,
    biencrit_t.cregionmeta13,
    biencrit_t.cregionmeta14,
    biencrit_t.cregionmeta15,
    biencrit_t.cregionmeta5,
    biencrit_t.cregionmeta6,
    biencrit_t.cregionmeta7,
    biencrit_t.cregionmeta8,
    biencrit_t.cregionmeta9,
    biencrit_t.cstyle10,
    biencrit_t.cstyle11,
    biencrit_t.cstyle12,
    biencrit_t.cstyle13,
    biencrit_t.cstyle14,
    biencrit_t.cstyle15,
    biencrit_t.cstyle5,
    biencrit_t.cstyle6,
    biencrit_t.cstyle7,
    biencrit_t.cstyle8,
    biencrit_t.cstyle9,
    biencrit_t.ctyp10,
    biencrit_t.ctyp11,
    biencrit_t.ctyp12,
    biencrit_t.ctyp13,
    biencrit_t.ctyp14,
    biencrit_t.ctyp15,
    biencrit_t.ctyp5,
    biencrit_t.ctyp6,
    biencrit_t.ctyp7,
    biencrit_t.ctyp8,
    biencrit_t.ctyp9,
    biencrit_t.ctypmeta10,
    biencrit_t.ctypmeta11,
    biencrit_t.ctypmeta12,
    biencrit_t.ctypmeta13,
    biencrit_t.ctypmeta14,
    biencrit_t.ctypmeta15,
    biencrit_t.ctypmeta3,
    biencrit_t.ctypmeta4,
    biencrit_t.ctypmeta5,
    biencrit_t.ctypmeta6,
    biencrit_t.ctypmeta7,
    biencrit_t.ctypmeta8,
    biencrit_t.ctypmeta9,
    biencrit_t.lcp10,
    biencrit_t.lcp11,
    biencrit_t.lcp12,
    biencrit_t.lcp13,
    biencrit_t.lcp14,
    biencrit_t.lcp15,
    biencrit_t.lcp5,
    biencrit_t.lcp6,
    biencrit_t.lcp7,
    biencrit_t.lcp8,
    biencrit_t.lcp9,
    biencrit_t.ndetail10,
    biencrit_t.ndetail11,
    biencrit_t.ndetail12,
    biencrit_t.ndetail13,
    biencrit_t.ndetail14,
    biencrit_t.ndetail15,
    biencrit_t.ndetail5,
    biencrit_t.ndetail6,
    biencrit_t.ndetail7,
    biencrit_t.ndetail8,
    biencrit_t.ndetail9,
    biencrit_t.cdevise,
    biencrit_t.ballowforeigners,
    biencrit_t.ballowforeignersmin,
    biencrit_t.bprogramme,
    biencrit_t.nprogramme1,
    biencrit_t.nprogramme2,
    biencrit_t.nprogramme3,
    biencrit_t.nprogramme4,
    biencrit_t.nprogramme5,
    biencrit_t.nprogramme6,
    biencrit_t.nprogramme7,
    biencrit_t.nprogramme8,
    biencrit_t.nprogramme9,
    biencrit_t.nprogramme10,
    biencrit_t.nprogramme11,
    biencrit_t.nprogramme12,
    biencrit_t.nprogramme13,
    biencrit_t.nprogramme14,
    biencrit_t.nprogramme15,
    biencrit_t.qsurfjardinmax,
    biencrit_t.bqsurfjardin,
    biencrit_t.cregion16,
    biencrit_t.cregion17,
    biencrit_t.cregion18,
    biencrit_t.cregion19,
    biencrit_t.cregion20,
    biencrit_t.cregion21,
    biencrit_t.cregion22,
    biencrit_t.cregion23,
    biencrit_t.cregion24,
    biencrit_t.cregion25,
    biencrit_t.ctyps,
    biencrit_t.ctypmetas,
    biencrit_t.cregions,
    biencrit_t.cregionmetas,
    biencrit_t.cstyles,
    biencrit_t.cenvironnements,
    biencrit_t.ltypsfr,
    biencrit_t.ltypmetas,
    biencrit_t.lregions,
    biencrit_t.lregionmetas,
    biencrit_t.ltypmandats,
    biencrit_t.lenvironnementsfr,
    biencrit_t.lstylesfr,
    biencrit_t.lprogrammesfr,
    biencrit_t.ldetailsfr,
    biencrit_t.ltypsen,
    biencrit_t.ltypmetasen,
    biencrit_t.lregionsen,
    biencrit_t.lregionmetasen,
    biencrit_t.ltypmandatsen,
    biencrit_t.lenvironnementsen,
    biencrit_t.lstylesen,
    biencrit_t.lprogrammesen,
    biencrit_t.ldetailssen,
    biencrit_t.lsearchen,
    biencrit_t.lsearchfr,
    biencrit_t.ltypmetasfr,
    biencrit_t.lregionsfr,
    biencrit_t.lregionmetasfr,
    biencrit_t.ltypmandatsfr,
    biencrit_t.ldetailssfr,
    biencrit_t.ldetailsen,
    biencrit_t.qsurfjardinmin,
    biencrit_t.nbiencrit,
    biencrit_t.lusername
FROM biencrit_t
WHERE (biencrit_t.nprospect IN (
    SELECT prospect.nprospect
    FROM prospect
    ));










-- marc focqune 4 bornes
-- 6.5 
-- 70-75% -> 
-- postgres >13

-- 19
-- 19
-- 19
-- ceb 30

--DO $do$

--BEGIN
  -- Set compression for column lemailcontent in prospectbien_t if it exists
    --IF EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'prospectbien_t' AND column_name = 'lemailcontent') THEN
  --      ALTER TABLE prospectbien_t ALTER COLUMN lemailcontent SET COMPRESSION pglz;
 --END IF;

 -- Set compression for column lresponsepage in gatewayupload if it exists
 --   IF EXISTS (SELECT FROM information_schema.columns WHERE table_name = 'gatewayupload' AND column_name = 'lresponsepage') THEN
 --       ALTER TABLE gatewayupload ALTER COLUMN lresponsepage SET COMPRESSION pglz;
 --   END IF;

--END $do$;


-- ne fonctionne pas en pg 9.6
--CREATE EXTENSION IF NOT EXISTS pg_trgm;

--CREATE TEXT SEARCH CONFIGURATION unaccented_english ( COPY = english );
--ALTER TEXT SEARCH CONFIGURATION unaccented_english   ALTER MAPPING FOR hword, hword_part, word      WITH unaccent, english_stem;


-- Créez une configuration de recherche en texte intégral pour ignorer les accents
--CREATE TEXT SEARCH CONFIGURATION unaccented_english ( COPY = english );
--ALTER TEXT SEARCH CONFIGURATION unaccented_english   ALTER MAPPING FOR hword, hword_part, word      WITH unaccent, english_stem;




-- DROP TRIGGER IF EXISTS tau_updatedfinpublication ON public.bien_t;
-- CREATE OR REPLACE TRIGGER tau_updatedfinpublication
--   AFTER UPDATE 
--   ON public.bien_t
-- FOR EACH ROW 
--   EXECUTE PROCEDURE public.f_dfinpublication();



CREATE TABLE IF NOT EXISTS public.signatures
(
  id SERIAL PRIMARY KEY,
  cforeignid character varying(255),
  ndoc integer,
  cagence character varying(50),
  ctype character varying(50),
  cstatus character varying(50),
  lname text,
  ldescription text,
  lstatus character varying(50),
  nsigners integer[] DEFAULT '{}'::integer[],
  nfollowers integer[] DEFAULT '{}'::integer[],
  dcre timestamp without time zone DEFAULT now(),
  cusercre character varying(50),
  dmod timestamp without time zone DEFAULT now(),
  cusermod character varying(50)
);










CREATE OR REPLACE FUNCTION public.f_recordbienchange()
  RETURNS trigger AS
$BODY$
    BEGIN


    -- Variation de mandat
    IF (OLD.cmandat <> NEW.cmandat AND OLD.cmandat IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (f_nextval('nrelation'), null, OLD.nbien, 60, current_timestamp, current_timestamp, concat (OLD.cmandat , ' -> ' , NEW.cmandat )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

--

    -- Variation de prix
    -- Variation de prix
IF ((OLD.mprix IS NOT NULL OR NEW.mprix IS NOT NULL) AND OLD.mprix <> NEW.mprix ) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (f_nextval('nrelation'), null, OLD.nbien, 20, current_timestamp, current_timestamp, concat ( replace (trim(to_char (OLD.mprix, '999G999G999G999')),',','.'), ' -> ' , replace (trim(to_char (NEW.mprix, '999G999G999G999')),',','.') )  ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, NEW.mprix, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;



     -- Variation de statut

    IF (OLD.bactif <> NEW.bactif AND OLD.bactif IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (f_nextval('nrelation'), null, OLD.nbien, 21, current_timestamp, current_timestamp, (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = OLD.bactif) || ' -> '  || (SELECT lstatutbienfr FROM statutbien WHERE statutbien.bactif = NEW.bactif) ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);

    END IF;

     -- Changement de négociateur (ntyprelation = 30)
    IF (OLD.lusername <> NEW.lusername AND OLD.lusername IS NOT NULL) THEN
      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (f_nextval('nrelation'), null, OLD.nbien, 30, current_timestamp, current_timestamp,
              concat ((SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = OLD.lusername)  , ' ('  , OLD.lusername  , ') -> '  , (SELECT concat (upper(lnom), ' ', lprenom ) FROM utilisateur WHERE lusername = NEW.lusername ) , ' (' , NEW.lusername , ') '),
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;



    -- Changement de statut de publication Web (ntyprelation = 31)
    IF (OLD.bexportweb <> NEW.bexportweb AND OLD.bexportweb IS NOT NULL) THEN


      INSERT INTO prospectbien (
                nrelation, nprospect, nbien, ntyprelation, ddebut, dfin, lrem,
                lusername, dcre, cusercre, dmod, cusermod, mcout, dalarm, ndoc,
                nrubrique, bannulation, cagence, bphoto, ldocfilename, bconfirmed,
                dfinpublication)
        VALUES (f_nextval('nrelation'), null, OLD.nbien, 31, current_timestamp, current_timestamp, case when NEW.bexportweb=1 then 'Publication web activée' else 'Publication web suspendue' end ,
                current_user, current_timestamp, current_user, current_timestamp, current_user, null, current_timestamp, null,
                null, 0, new.cagence, 0, null, 1,
                current_timestamp);
    END IF;


     RETURN OLD;
    -- RETURN NULL;

    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
  
  
  CREATE OR REPLACE FUNCTION public.f_remove_leadmanagement (
)
RETURNS trigger AS
$body$
BEGIN
    IF EXISTS(SELECT 1 FROM detailprospect WHERE ndetail = 4001 AND nprospect = NEW.nprospect) THEN
      IF NEW.ndetail IN (4006, 4007) THEN
          DELETE FROM detailprospect
          WHERE ndetail = 4001 AND nbien = NEW.nprospect;
      END IF;
    END IF;
    RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql'
VOLATILE
CALLED ON NULL INPUT
SECURITY INVOKER
COST 100;
  
  
CREATE OR REPLACE VIEW agenda AS
 SELECT bien_t.cbien,
    bien_t.bcle,
    bien_t.lcontactvisite,
    bien_t.llocalite,
    prospectbien.nrelation,
    prospectbien.nprospect,
    prospectbien.nbien,
    prospectbien.ntyprelation,
    prospectbien.ddebut,
    prospectbien.dfin,
    prospectbien.lrem,
    typrelation.ltyprelation,
    prospect_t.lnom,
    prospect_t.lprenom,
    prospect_t.cpolit,
    prospectbien.dalarm,
    prospectbien.lusername,
    typrelation.ncouleur,
    typrelation.ncouleurtexte,
    bien_t.ladr,
    prospectbien.bconfirmed
   FROM prospectbien
     LEFT JOIN typrelation USING (ntyprelation)
     LEFT JOIN bien_t USING (nbien)
     LEFT JOIN prospect_t USING (nprospect)
  WHERE typrelation.brendezvous = 1 AND prospectbien.ddebut IS NOT NULL;  


CREATE OR REPLACE VIEW doc AS
 SELECT doc_t.ndoc,
    doc_t.ltitre,
    doc_t.nbien,
    doc_t.nprospect,
    doc_t.lcontent,
    doc_t.lheader,
    doc_t.lfooter,
    doc_t.dcre,
    doc_t.cusercre,
    doc_t.dmod,
    doc_t.cusermod,
    doc_t.denvoi,
    doc_t.ntxformatid,
    doc_t.cagence,
    doc_t.cagencedoc,
    doc_t.lfilename,
    doc_t.bexportweb,
    doc_t.nrelation
   FROM doc_t
  WHERE
doc_t.cagence = (select cagence from utilisateur where lusername = current_user)
OR
  (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE doc_t.nbien = bien_t.nbien AND utilisateuragence.bselectdoc = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL))) OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            prospect_t
          WHERE doc_t.nprospect = prospect_t.nprospect AND utilisateuragence.bselectdoc = 1 AND utilisateuragence.lusername::name = "current_user"() AND (prospect_t.cagence::text = utilisateuragence.cagence::text OR prospect_t.cagence::text = ''::text OR prospect_t.cagence IS NULL)));



CREATE OR REPLACE VIEW htmlbien AS
 SELECT htmlbien_t.clangue,
    htmlbien_t.nbien,
    htmlbien_t.lhtml,
    htmlbien_t.lascii,
    htmlbien_t.cusercre,
    htmlbien_t.cusermod,
    htmlbien_t.dcre,
    htmlbien_t.dmod,
    htmlbien_t.ltitre,
    htmlbien_t.lannonce,
    htmlbien_t.cagence,
    htmlbien_t.lannonceweb,
    htmlbien_t.lannonceseo
   FROM htmlbien_t
  WHERE (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE bien_t.nbien = htmlbien_t.nbien AND utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));


    CREATE OR REPLACE VIEW offre AS
    SELECT offre_t.nrelation,
        offre_t.coffre,
        offre_t.cstatut,
        offre_t.mcommission,
        offre_t.cfacture,
        offre_t.dacte,
        offre_t.bpaye,
        offre_t.cusercre,
        offre_t.cusermod,
        offre_t.dmod,
        offre_t.dcre,
        offre_t.lusername,
        offre_t.dssp,
        offre_t.dactebutoir,
        offre_t.mmontant,
        offre_t.nrelationrvacte,
        offre_t.nrelationrvssp,
        offre_t.nnotairevendeur,
        offre_t.nnotaireacquereur,
        offre_t.doffre,
        offre_t.lcomment,
        offre_t.nbien,
        offre_t.nprospect,
        offre_t.cagence,
        offre_t.denvoi_sru,
        offre_t.dfin_csop,
        offre_t.lcondsusp,
        offre_t.lcondpart,
        offre_t.cdevise,
        offre_t.lsearchfr,
        offre_t.lsearchen,
        offre_t.dreiteration,
        offre_t.mcommissionvendeur,
        offre_t.noffre
    FROM offre_t
    WHERE (EXISTS ( 
        SELECT NULL::unknown AS unknown
        FROM utilisateuragence
        WHERE utilisateuragence.bselectoffre = 1 
        AND utilisateuragence.lusername::name = current_user
        AND (utilisateuragence.cagence::text = utilisateuragence.cagence::text 
            OR utilisateuragence.cagence::text = ''::text 
            OR utilisateuragence.cagence IS NULL)
    ));


CREATE OR REPLACE VIEW photo AS
 SELECT photo_t.*
   FROM photo_t
  WHERE (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            bien_t
          WHERE photo_t.nbien = bien_t.nbien AND utilisateuragence.bselectbien = 1 AND utilisateuragence.lusername::name = "current_user"() AND (bien_t.cagence::text = utilisateuragence.cagence::text OR bien_t.cagence::text = ''::text OR bien_t.cagence IS NULL)));


CREATE OR REPLACE VIEW mandat AS
 SELECT mandat_t.nmandat,
    mandat_t.nbien,
    mandat_t.ddebmandat,
    mandat_t.dfinmandat,
    mandat_t.ltypmandat,
    mandat_t.lnatmandat,
    mandat_t.cstatutmandat,
    mandat_t.ltypxx,
    mandat_t.ladrbien,
    mandat_t.lcpbien,
    mandat_t.llocalitebien,
    mandat_t.cagence,
    mandat_t.lusername,
    mandat_t.lstatutmandat,
    mandat_t.lmandants,
    mandat_t.cisopaysbien,
    mandat_t.nnummandat,
    mandat_t.ltypbien,
    mandat_t.nnumrepertoire,
    mandat_t.dcre,
    mandat_t.cusercre,
    mandat_t.cusermod,
    mandat_t.dmod
   FROM mandat_t
  WHERE (mandat_t.cagence::text IN ( SELECT agence.cagencemandat
           FROM agence
          WHERE (agence.cagence::text IN ( SELECT utilisateur.cagence
                   FROM utilisateur
                  WHERE utilisateur.lusername::name = "current_user"()))));




CREATE OR REPLACE VIEW mandat_observation AS
 SELECT mandat_observation_t.nobservation,
    mandat_observation_t.lobservation,
    mandat_observation_t.nmandat,
    mandat_observation_t.lusername,
    mandat_observation_t.dobservation,
    mandat_observation_t.dcre,
    mandat_observation_t.cusercre,
    mandat_observation_t.cusermod,
    mandat_observation_t.dmod
   FROM mandat_observation_t
  WHERE (mandat_observation_t.nmandat IN ( SELECT mandat.nmandat
           FROM mandat));



CREATE OR REPLACE VIEW prospectbien AS
 SELECT prospectbien_t.*
   FROM prospectbien_t
  WHERE prospectbien_t.ntyprelation = 5 OR (EXISTS ( SELECT NULL::unknown AS unknown
           FROM utilisateuragence,
            typrelation
          WHERE prospectbien_t.ntyprelation = typrelation.ntyprelation AND (utilisateuragence.bselecthisto = 1 OR utilisateuragence.bselectrv = 1 AND typrelation.brendezvous = 1) AND utilisateuragence.lusername::name = "current_user"() AND (prospectbien_t.cagence::text = utilisateuragence.cagence::text OR prospectbien_t.cagence::text = ''::text OR prospectbien_t.cagence IS NULL)));



CREATE OR REPLACE VIEW preference AS
     SELECT preference_t.id,
        preference_t.cagence,
        preference_t.cinternetsite,
        preference_t.ndelairelance,
        preference_t.nemailntemplate,
        preference_t.ncourrierntemplate,
        preference_t.ncatprospectnotaire,
        preference_t.dlastsend,
        preference_t.lftpserver,
        preference_t.lftpusername,
        preference_t.lftppasswd,
        preference_t.njpgquality,
        preference_t.njpgprogressive,
        preference_t.nphotomaxh,
        preference_t.nphotomaxw,
        preference_t.ntyprelationrelance,
        preference_t.nshadowlevel,
        preference_t.nphotomedmaxh,
        preference_t.nphotomedmaxw,
        preference_t.nthumbmaxh,
        preference_t.nthumbmaxw,
        preference_t.lftpsubdir,
        preference_t.nprospectnotaire,
        preference_t.nprospectproprio,
        preference_t.nprospectprio,
        preference_t.nprospectagence,
        preference_t.cinternetsiteactivimmo,
        preference_t.nprospectprospect,
        preference_t.nallowusershare,
        preference_t.qnbjourhisto,
        preference_t.ndbversion,
        preference_t.nsilentupload,
        preference_t.bprixtoprixnet,
        preference_t.bwebupdatesingle,
        preference_t.qcss,
        preference_t.limportexportdir,
        preference_t.dlastrunbackup,
        preference_t.ntyprelationssp,
        preference_t.ntyprelationacte,
        preference_t.ntyprelationactivite,
        preference_t.nprospectlead,
        preference_t.ntyprelationemail,
        preference_t.ntyprelationvisite
      FROM preference_t
      WHERE (EXISTS ( SELECT NULL::unknown AS unknown
               FROM utilisateuragence
              WHERE utilisateuragence.bprincipale = 1 AND utilisateuragence.lusername::name = "current_user"() AND (preference_t.cagence::text = utilisateuragence.cagence::text OR preference_t.cagence::text = ''::text OR preference_t.cagence IS NULL)));


CREATE OR REPLACE VIEW biencritfirst AS
SELECT DISTINCT ON (nprospect)
    nprospect,
    ctypmandat1,
    mprix1max,
    ctypmandat2,
    mprix2max,
    ctyp1,
    ctyp2,
    ctyp3,
    ctyp4,
    nanneemin,
    nanneemax,
    nanneerenovmin,
    cregion1,
    cregion2,
    cregion3,
    cregion4,
    lcp1,
    lcp2,
    lcp3,
    lcp4,
    qpiecesmin,
    qpiecesmax,
    qchambresmin,
    qchambresmax,
    qsurfhabmin,
    qsurfhabmax,
    ndept1,
    ndept2,
    ndept3,
    ndept4,
    qsurfterrainmin,
    qsurfterrainmax,
    cenvironnement1,
    cenvironnement2,
    cenvironnement3,
    cenvironnement4,
    cnaturebien1,
    cnaturebien3,
    cnaturebien4,
    cnaturebien2,
    qsdbmin,
    qsdbmax,
    qgaragesmin,
    cchauf1,
    cchauf2,
    cchauf3,
    cchauf4,
    ntypcuisinemin,
    ndisponibilitemin,
    cstyle1,
    cstyle2,
    cstyle3,
    cstyle4,
    netagetot,
    mrevcadmax,
    mchargemax,
    mprecimmomax,
    nbureaumin,
    nordreetatmin,
    netatmin,
    qsddmin,
    qsurfterrassemin,
    qbureaumin,
    lsql,
    cusercre,
    dcre,
    cusermod,
    dmod,
    bctypmandat1,
    bmprix1max,
    bctypmandat2,
    bmprix2max,
    bctyp,
    bnannee,
    bnanneerenov,
    bcregion,
    blcp,
    bqpieces,
    bqchambres,
    bqsurfhab,
    bndept,
    bqsurfterrain,
    bcenvironnement,
    bcnaturebien,
    bqsdb,
    bqgarages,
    bcchauf,
    bntypcuisine,
    bndisponibilite,
    bcstyle,
    bmrevcadmax,
    bmchargemax,
    bmprecimmomax,
    bnetat,
    bqsdd,
    bqsurfterrasse,
    bqbureau,
    lcomment,
    mprix1min,
    mprix2min,
    bctypmeta,
    ctypmeta1,
    ctypmeta2,
    lbienssup,
    lprofilprive,
    lprofilpro,
    limplogement,
    limphoraires,
    bpiscine,
    bpiscinemin,
    bdetail,
    ndetail1,
    ndetail2,
    ndetail3,
    ndetail4,
    cregionmeta1,
    cregionmeta2,
    bcregionmeta,
    qsurfsejourmin,
    bqsurfsejour,
    lcp,
    cregionmeta3,
    cregionmeta4,
    cenvironnement11,
    cenvironnement12,
    cenvironnement13,
    cenvironnement14,
    cenvironnement15,
    cenvironnement5,
    cenvironnement6,
    cenvironnement7,
    cenvironnement8,
    cenvironnement9,
    cregion10,
    cregion11,
    cregion12,
    cregion13,
    cregion14,
    cregion15,
    cregion5,
    cregion6,
    cregion7,
    cregion8,
    cregion9,
    cregionmeta10,
    cregionmeta11,
    cregionmeta12,
    cregionmeta13,
    cregionmeta14,
    cregionmeta15,
    cregionmeta5,
    cregionmeta6,
    cregionmeta7,
    cregionmeta8,
    cregionmeta9,
    cstyle10,
    cstyle11,
    cstyle12,
    cstyle13,
    cstyle14,
    cstyle15,
    cstyle5,
    cstyle6,
    cstyle7,
    cstyle8,
    cstyle9,
    ctyp10,
    ctyp11,
    ctyp12,
    ctyp13,
    ctyp14,
    ctyp15,
    ctyp5,
    ctyp6,
    ctyp7,
    ctyp8,
    ctyp9,
    ctypmeta10,
    ctypmeta11,
    ctypmeta12,
    ctypmeta13,
    ctypmeta14,
    ctypmeta15,
    ctypmeta3,
    ctypmeta4,
    ctypmeta5,
    ctypmeta6,
    ctypmeta7,
    ctypmeta8,
    ctypmeta9,
    lcp10,
    lcp11,
    lcp12,
    lcp13,
    lcp14,
    lcp15,
    lcp5,
    lcp6,
    lcp7,
    lcp8,
    lcp9,
    ndetail10,
    ndetail11,
    ndetail12,
    ndetail13,
    ndetail14,
    ndetail15,
    ndetail5,
    ndetail6,
    ndetail7,
    ndetail8,
    ndetail9,
    cenvironnement10,
    ctyps,
    ctypmetas,
    cregions,
    cregionmetas,
    cstyles,
    cenvironnements,
    cdevise,
    ballowforeigners,
    ballowforeignersmin,
    bprogramme,
    nprogramme1,
    nprogramme2,
    nprogramme3,
    nprogramme4,
    nprogramme5,
    nprogramme6,
    nprogramme7,
    nprogramme8,
    nprogramme9,
    nprogramme10,
    nprogramme11,
    nprogramme12,
    nprogramme13,
    nprogramme14,
    nprogramme15,
    qsurfjardinmin,
    qsurfjardinmax,
    bqsurfjardin,
    cregion16,
    cregion17,
    cregion18,
    cregion19,
    cregion20,
    cregion21,
    cregion22,
    cregion23,
    cregion24,
    cregion25,
    ltypsfr,
    ltypmetas,
    lregions,
    lregionmetas,
    ltypmandats,
    lenvironnementsfr,
    lstylesfr,
    lprogrammesfr,
    ldetailsfr,
    ltypsen,
    ltypmetasen,
    lregionsen,
    lregionmetasen,
    ltypmandatsen,
    lenvironnementsen,
    lstylesen,
    lprogrammesen,
    ldetailssen,
    lsearchen,
    lsearchfr,
    ltypmetasfr,
    lregionsfr,
    lregionmetasfr,
    ltypmandatsfr,
    ldetailssfr,
    ldetailsen,
    nbiencrit
FROM biencrit_t
WHERE nprospect in (select nprospect from prospect)
ORDER BY nprospect, nbiencrit ;