<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>


<NODE name="INIT" label="INITIALISATIONS">
	<NODE label="Corrections">
		<sqlcmd><![CDATA[
				-- Longueur de la colonne LFAC_LET_CLE forcée à 16 au lieu de 5
				-- Car on assigne LFAC_CODE(16) à LFAC_LET_CLE(5)
				ALTER TABLE prod_hm.FAC_LIGNE_FACTURE
				ALTER COLUMN LFAC_LET_CLE TYPE varchar(16)
				;

				-- Traitement si plusieurs medecins responsables
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'HM_MULTIMED',
					'Medecin responsable si plusieurs declares',
					'0',
					'0=Medecin de l''enveloppe séjour, 1=Medecin a l''entree'
				WHERE 'HM_MULTIMED' NOT IN (SELECT code FROM activite.t_divers);
				;

				-- Correction medecin responsable si plusieurs medecins
				UPDATE PROD_HM.IDE_SEJOUR
				SET SEJO_ID_MEDE_COURANT = subview.MESE_ID_MEDE
				FROM
				(
				SELECT MESE_ID_SEJO, (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint AS MESE_ID_MEDE, MAX(SEJO_ID_MEDE_COURANT) AS SEJO_ID_MEDE_COURANT
				FROM prod_hm.IDE_MED_VENUE
				JOIN PROD_HM.IDE_SEJOUR ON MESE_ID_SEJO = SEJO_ID_SEJO
				JOIN prod_hm.BAS_CATALOGUE_PERS ON MESE_ID_CAPE = CAPE_ID_CAPE
				JOIN prod_hm.IDE_MEDECIN  ON MESE_ID_MEDE = MEDE_ID_MEDE
				JOIN activite.t_divers ON t_divers.code = 'HM_MULTIMED' AND t_divers.valeur = '1'
				WHERE CAPE_CODE = '1'
				GROUP BY 1
				HAVING (MIN(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint <> MAX(SEJO_ID_MEDE_COURANT)
				) subview
				WHERE SEJO_ID_SEJO = MESE_ID_SEJO
				;



                -- Séjours bébés avec ind bgh différents de la mère
				UPDATE prod_hm.IDE_SEJOUR
                    SET SEJO_IND_BGH = IDE_SEJOUR_MERE.SEJO_IND_BGH
                    FROM prod_hm.IDE_SEJOUR IDE_SEJOUR_MERE
                WHERE IDE_SEJOUR.SEJO_ID_SEJO_MER_ENF = IDE_SEJOUR_MERE.SEJO_ID_SEJO AND
                    IDE_SEJOUR_MERE.SEJO_IND_BGH IS DISTINCT FROM IDE_SEJOUR.SEJO_IND_BGH AND
                    IDE_SEJOUR.SEJO_ID_SEJO_MER_ENF <> 0
                ;

				-- Forcage prestation
				UPDATE prod_hm.PAD_PRESTATION_SEJOUR
				SET PRSE_CODE = code_force
				FROM activite[PX].t_rubriques_facturation
				WHERE t_rubriques_facturation.code_original = PRSE_ID_PRSE AND
					t_rubriques_facturation.code_force <> ''
				;

				UPDATE prod_hm.PAD_PRESTATION_HONORAIRE
				SET PRHO_CODE = code_force
				FROM activite[PX].t_rubriques_facturation
				WHERE t_rubriques_facturation.code_original = PRHO_ID_PRHO AND
					t_rubriques_facturation.code_force <> ''
				;

				UPDATE prod_hm.PAD_PRESTATION_SEJOUR
				SET PRSE_LET_CLE = t_prestations.code
				FROM activite[PX].t_rubriques_facturation
					JOIN activite.t_prestations ON prestation_forcee_id = t_prestations.oid
				WHERE t_rubriques_facturation.code_original = PRSE_ID_PRSE AND
					t_rubriques_facturation.prestation_forcee_id > 0
				;


				UPDATE prod_hm.FAC_LIGNE_FACTURE
				SET LFAC_LET_CLE = t_prestations.code
				FROM activite[PX].t_rubriques_facturation
					JOIN activite.t_prestations ON prestation_forcee_id = t_prestations.oid
				WHERE t_rubriques_facturation.code_original = LFAC_ID_PRSE AND
					t_rubriques_facturation.prestation_forcee_id > 0
				;


				-- Prestation vide dans lignes de facture
				UPDATE prod_hm.FAC_LIGNE_FACTURE
				SET LFAC_LET_CLE = LFAC_CODE
				WHERE LFAC_LET_CLE = ''
				;

				-- Externes, mettre une date de fin cohérente
				UPDATE prod_hm.IDE_SEJOUR
				SET SEJO_DAT_FIN = SEJO_DAT_DEB + interval '2 hours'
				FROM prod_hm.BAS_UF
				JOIN prod_hm.BAS_CATEGORIE_UFM ON UNFO_ID_CUFM = CUFM_ID_CUFM
				JOIN prod_hm.BAS_CATALOGUE_GEN BAS_CATALOGUE_GEN_MT ON CUFM_ID_CAGE_MT = BAS_CATALOGUE_GEN_MT.CAGE_ID_CAGE
				WHERE SEJO_STATUT IN ('E','S') AND
					(
					SEJO_DAT_FIN IS NULL OR
					(date(SEJO_DAT_FIN) - date(SEJO_DAT_DEB)) > 1
					) AND
					SEJO_ID_UNFO = UNFO_ID_UNFO AND
					BAS_CATALOGUE_GEN_MT.CAGE_CODE = '07'
				;

				-- Le code 'M' est aussi médecin salarié
				UPDATE prod_hm.FAC_LIGNE_FACTURE
				SET LFAC_CDT_EXC = 'S'
				WHERE LFAC_CDT_EXC = 'M'
				;
				
				-- Conserver les encours HM 		
				INSERT INTO activite.t_divers (code, texte, valeur, description, show_info_module)
				SELECT
					'ENCOURSHM'
					,'Conservation des encours du prestataire HM'
					,'0'
					,'1=Conserver les encours HM 0=Ne pas conserver',
					false
				WHERE NOT EXISTS (SELECT 1 FROM activite.t_divers WHERE code = 'ENCOURSHM')
				;
		
			]]></sqlcmd>
	</NODE>



	<NODE label="Identification des séjours">
		<sqlcmd><![CDATA[

                    -- Les types de prestations exclues veant du PMSI MCO sont paramétrés
                    INSERT INTO activite.t_divers (code, texte, valeur, description)
                    SELECT
                        'EXCLUSIONPRESTATIONPMSI',
                        'Par défaut sont exclues les prestations suivant du PMSI MCO : BHN, PHN, ELMA, HYP, PB, PB  F, PHH, PNDL, SAP, SCOL, SIND',
                        'BHN, PHN, ELMA, HYP, PB, PB  F, PHH, PNDL, SAP, SCOL, SIND ',
                        'Type prestations exclues'
                    WHERE 'EXCLUSIONPRESTATIONPMSI' NOT IN (SELECT code FROM activite.t_divers);
                    ;

					-- Les types de journaux de ventes sont paramétrés
					INSERT INTO activite.t_divers (code, texte, valeur, description)
					SELECT
						'HM_TYPJVT',
						'HM. Types des journaux des ventes',
						'FACAV',
						'Types journaux de ventes HM'
					WHERE 'HM_TYPJVT' NOT IN (SELECT code FROM activite.t_divers);
					;

					-- Les forcages par type de sejours sont paramétrés (anciennement, le type B était bébé)
					INSERT INTO activite.t_divers (code, texte, valeur, description)
					SELECT 'HM_TYPSEJ_' || CAPE_CODE,
						'HM. Forcage type séjour ' || CAPE_LIBELLE || ' (' || CAPE_CODE || ')',
						CASE WHEN CAPE_CODE = 'B' THEN '6' ELSE '' END,
						'HM. Forcage type séjour ' || CAPE_LIBELLE || ' (' || CAPE_CODE || ')'
					FROM
					(
					SELECT CAPE_CODE, MAX(CAPE_LIBELLE) AS CAPE_LIBELLE
					FROM PROD_HM.IDE_SEJOUR
					JOIN prod_hm.BAS_CATALOGUE_PERS ON (SEJO_ID_CAPE_VEN = CAPE_ID_CAPE)
					GROUP BY 1
					) subview
					LEFT JOIN activite.t_divers ON t_divers.code = ('HM_TYPSEJ_' || CAPE_CODE)
					WHERE t_divers.code IS NULL
					ORDER BY 1
					;

					DROP TABLE IF EXISTS w_CCL_JOURNAL;
					CREATE TEMP TABLE w_CCL_JOURNAL AS
					SELECT JOUR_ID_JOUR, JOUR_CODE, CAGE_CODE AS JOUR_CAGE_CODE,
						CASE WHEN CAGE_CODE = ANY(string_to_array(replace(t_divers.valeur,' ',''),',')) THEN '1' ELSE '0' END AS JOUR_ISJVT
					FROM prod_hm.CCL_JOURNAL
						JOIN prod_hm.BAS_CATALOGUE_GEN ON JOUR_ID_CAGE = CAGE_ID_CAGE
						JOIN activite.t_divers ON t_divers.code = 'HM_TYPJVT';

					ALTER TABLE w_CCL_JOURNAL ADD CONSTRAINT w_CCL_JOURNAL_pkey PRIMARY KEY(JOUR_ID_JOUR);


					DROP TABLE IF EXISTS w_CCL_COMPTE;
					CREATE TEMP TABLE w_CCL_COMPTE AS
					SELECT CPTE_ID_CPTE, CPTE_CODE, CAGE_CODE AS CPTE_CAGE_CODE
					FROM prod_hm.CCL_COMPTE
						JOIN prod_hm.BAS_CATALOGUE_GEN ON CPTE_ID_CAGE = CAGE_ID_CAGE
					WHERE CAGE_CODE IN ('CLIENT' , 'ACO85', 'ACO', 'CLIRMB');

					ALTER TABLE w_CCL_COMPTE ADD CONSTRAINT w_CCL_COMPTE_pkey PRIMARY KEY(CPTE_ID_CPTE);


					DROP TABLE IF EXISTS w_periode;
					CREATE TEMP TABLE w_periode AS
					SELECT GREATEST(date_trunc('month',date(MIN(ECRI_DAT_ECRITURE))),'[ENV_ADM_ANNEEDEBUT]0101'::date) AS date_debut_periode,
						'00010101'::timestamp without time zone AS date_extraction
					FROM
						prod_hm.CCL_ECRITURE
							JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
					WHERE
							ECRI_DAT_SUP IS NULL
							AND JOUR_ISJVT = '1'
							AND ECRI_ID_ETAB IN ([ID_ETAB]);


					UPDATE w_periode
					SET date_extraction = DAT_MOD
					FROM (
						SELECT max(GREATEST(PATI_DAT_MOD,PATI_DAT_CRE)) AS DAT_MOD FROM prod_hm.IDE_PATIENT WHERE GREATEST(PATI_DAT_MOD,PATI_DAT_CRE) < now()
						) subview
					WHERE DAT_MOD > date_extraction;

					UPDATE w_periode
					SET date_extraction = DAT_MOD
					FROM (
						SELECT max(GREATEST(SEJO_DAT_MOD,SEJO_DAT_CRE)) AS DAT_MOD FROM prod_hm.IDE_SEJOUR WHERE GREATEST(SEJO_DAT_MOD,SEJO_DAT_CRE) < now()
						) subview
					WHERE DAT_MOD > date_extraction;

					DROP TABLE IF EXISTS w_SEJOUR_compta;
					CREATE TEMP TABLE w_SEJOUR_compta AS
					SELECT
						FACT_ID_SEJO
					FROM prod_hm.CCL_LIGNE_ECRITURE,
						prod_hm.CCL_ECRITURE,
						w_CCL_JOURNAL,
						w_CCL_COMPTE,
						prod_hm.FAC_FACTURE_DEBITEUR,
						prod_hm.FAC_FACTURE
					WHERE
						LECR_ID_ECRI = ECRI_ID_ECRI
						AND LECR_ID_FACD = FACD_ID_FACD
						AND FACD_ID_FACT = FACT_ID_FACT
						AND ECRI_ID_JOUR = JOUR_ID_JOUR
						AND LECR_ID_CPTE = CPTE_ID_CPTE
						AND ECRI_DAT_SUP IS NULL
						AND CPTE_CAGE_CODE IN ('CLIENT' , 'ACO85', 'ACO', 'CLIRMB')
						AND ECRI_ID_ETAB IN ([ID_ETAB])
						AND ECRI_DAT_ECRITURE >= '[ENV_ADM_ANNEEDEBUT]0101'
					GROUP BY 1
					ORDER BY 1;

					DROP TABLE IF EXISTS w_IDE_SEJOUR;
					CREATE TEMP TABLE w_IDE_SEJOUR AS
					SELECT
						date_extraction,
						SEJO_ID_SEJO AS w_SEJO_ID_SEJO,
						MAX(CASE WHEN COALESCE(SEJO_NUM_SEJ,'') = '' THEN 'W' || SEJO_ID_SEJO::bigint ELSE SEJO_NUM_SEJ END) AS w_SEJO_NUM_SEJ
					FROM w_periode , prod_hm.IDE_SEJOUR
					WHERE SEJO_ID_ETAB_CON IN ([ID_ETAB])
						AND ((SEJO_DAT_SUP IS NULL AND SEJO_IND_INCOMPLET IS DISTINCT FROM '1'))
						AND (SEJO_DAT_DEB BETWEEN date_debut_periode AND now() + interval '2 day' OR SEJO_DAT_FIN >= date_debut_periode OR SEJO_DAT_FIN IS NULL)
						AND (SEJO_DAT_FIN IS NOT NULL AND SEJO_DAT_FIN <= date_extraction + interval '1 year' OR SEJO_DAT_FIN IS NULL)
						AND (SEJO_STATUT NOT IN ('A', 'P') OR (SEJO_STATUT IN ('A', 'P') AND (SEJO_DAT_DEB >= date_extraction AND (SEJO_DAT_FIN IS NULL OR SEJO_DAT_FIN >= date_extraction))))
					GROUP BY 1,2;

					ALTER TABLE w_IDE_SEJOUR ADD CONSTRAINT w_IDE_SEJOUR_pk PRIMARY KEY(w_SEJO_ID_SEJO);

					INSERT INTO w_IDE_SEJOUR
					SELECT date_extraction,
						SEJO_ID_SEJO AS w_SEJO_ID_SEJO,
						MAX(CASE WHEN COALESCE(SEJO_NUM_SEJ,'') = '' THEN 'W' || SEJO_ID_SEJO::bigint ELSE SEJO_NUM_SEJ END) AS w_SEJO_NUM_SEJ
					FROM w_periode, prod_hm.FAC_FACTURE
					JOIN prod_hm.IDE_SEJOUR ON FACT_ID_SEJO = SEJO_ID_SEJO
					WHERE FACT_DAT_SUP IS NULL AND
						SEJO_ID_ETAB_CON IN ([ID_ETAB]) AND
						FACT_DAT_CRE >= '[ENV_ADM_ANNEEDEBUT]0101' AND
						FACT_ID_SEJO NOT IN (SELECT w_SEJO_ID_SEJO FROM w_IDE_SEJOUR)
					GROUP BY 1,2
					;

					INSERT INTO w_IDE_SEJOUR
					SELECT
						date_extraction,
						SEJO_ID_SEJO AS w_SEJO_ID_SEJO,
						MAX(CASE WHEN COALESCE(SEJO_NUM_SEJ,'') = '' THEN 'W' || SEJO_ID_SEJO::bigint ELSE SEJO_NUM_SEJ END) AS w_SEJO_NUM_SEJ
					FROM w_periode , prod_hm.IDE_SEJOUR
					WHERE SEJO_ID_ETAB_CON IN ([ID_ETAB])
						AND SEJO_ID_SEJO IN (SELECT FACT_ID_SEJO FROM w_SEJOUR_compta)
						AND SEJO_ID_SEJO NOT IN (SELECT w_SEJO_ID_SEJO FROM w_IDE_SEJOUR)
					GROUP BY 1,2;


					DROP TABLE IF EXISTS w_IDE_SEJOUR_complet;
					CREATE TEMP TABLE w_IDE_SEJOUR_complet AS
					SELECT
						w_SEJO_NUM_SEJ,
						w_SEJO_ID_SEJO,
						date_extraction,
						IDE_SEJOUR.*
					FROM w_IDE_SEJOUR
						JOIN prod_hm.IDE_SEJOUR ON SEJO_ID_SEJO = w_SEJO_ID_SEJO;

					ALTER TABLE w_IDE_SEJOUR_complet ADD CONSTRAINT w_IDE_SEJOUR_complet_pk PRIMARY KEY(SEJO_ID_SEJO);


					UPDATE w_IDE_SEJOUR_complet SET
					w_SEJO_NUM_SEJ = w_IDE_SEJOUR_complet.w_SEJO_NUM_SEJ || '_2'
					FROM
						(SELECT w_SEJO_NUM_SEJ, MAX(w_SEJO_ID_SEJO) AS w_SEJO_ID_SEJO
						FROM w_IDE_SEJOUR_complet
						GROUP BY 1
						HAVING count(*) > 1) subview
					WHERE subview.w_SEJO_ID_SEJO = w_IDE_SEJOUR_complet.w_SEJO_ID_SEJO;

					UPDATE w_IDE_SEJOUR_complet SET
					w_SEJO_NUM_SEJ = w_IDE_SEJOUR_complet.w_SEJO_NUM_SEJ || '_3'
					FROM
						(SELECT w_SEJO_NUM_SEJ, MAX(w_SEJO_ID_SEJO) AS w_SEJO_ID_SEJO
						FROM w_IDE_SEJOUR_complet
						GROUP BY 1
						HAVING count(*) > 1) subview
					WHERE subview.w_SEJO_ID_SEJO = w_IDE_SEJOUR_complet.w_SEJO_ID_SEJO;

					UPDATE w_IDE_SEJOUR_complet SET
					w_SEJO_NUM_SEJ = w_IDE_SEJOUR_complet.w_SEJO_NUM_SEJ || '_4'
					FROM
						(SELECT w_SEJO_NUM_SEJ, MAX(w_SEJO_ID_SEJO) AS w_SEJO_ID_SEJO
						FROM w_IDE_SEJOUR_complet
						GROUP BY 1
						HAVING count(*) > 1) subview
					WHERE subview.w_SEJO_ID_SEJO = w_IDE_SEJOUR_complet.w_SEJO_ID_SEJO;

					UPDATE w_IDE_SEJOUR_complet SET
					w_SEJO_NUM_SEJ = w_IDE_SEJOUR_complet.w_SEJO_NUM_SEJ || '_5'
					FROM
						(SELECT w_SEJO_NUM_SEJ, MAX(w_SEJO_ID_SEJO) AS w_SEJO_ID_SEJO
						FROM w_IDE_SEJOUR_complet
						GROUP BY 1
						HAVING count(*) > 1) subview
					WHERE subview.w_SEJO_ID_SEJO = w_IDE_SEJOUR_complet.w_SEJO_ID_SEJO;

					UPDATE w_IDE_SEJOUR_complet SET
					w_SEJO_NUM_SEJ = w_IDE_SEJOUR_complet.w_SEJO_NUM_SEJ || '_6'
					FROM
						(SELECT w_SEJO_NUM_SEJ, MAX(w_SEJO_ID_SEJO) AS w_SEJO_ID_SEJO
						FROM w_IDE_SEJOUR_complet
						GROUP BY 1
						HAVING count(*) > 1) subview
					WHERE subview.w_SEJO_ID_SEJO = w_IDE_SEJOUR_complet.w_SEJO_ID_SEJO;

					UPDATE w_IDE_SEJOUR_complet
					SET SEJO_NUM_SEJ = w_SEJO_NUM_SEJ
					WHERE w_SEJO_NUM_SEJ <> SEJO_NUM_SEJ;


					CREATE INDEX w_IDE_SEJOUR_complet_i1
					ON w_IDE_SEJOUR_complet
					USING btree
					(w_SEJO_NUM_SEJ);

					ANALYSE w_IDE_SEJOUR_complet
					;


					-- Correction HM suppression anciennes factures provisoires
					UPDATE prod_hm.FAC_FACTURE
					SET FACT_DAT_SUP = subview.FACT_DAT_DER_CALCUL
					FROM
					(
					SELECT FACT_ID_SEJO, FACT_DAT_DEB_FAC, count(*),
						(MAX(ARRAY[FACT_DAT_DER_CALCUL::text, FACT_ID_FACT::text]))[2]::bigint AS FACT_ID_DER_CALCUL,
						MAX(FACT_DAT_DER_CALCUL) AS FACT_DAT_DER_CALCUL
					FROM prod_hm.FAC_FACTURE
					WHERE FACT_TYPE = 'P' AND FACT_DAT_SUP IS NULL
					GROUP BY 1,2
					HAVING count(*) > 1
					) subview
					WHERE FAC_FACTURE.FACT_ID_SEJO = subview.FACT_ID_SEJO AND
						FAC_FACTURE.FACT_DAT_DEB_FAC = subview.FACT_DAT_DEB_FAC AND
						FAC_FACTURE.FACT_TYPE = 'P' AND
						FAC_FACTURE.FACT_DAT_SUP IS NULL AND
						FAC_FACTURE.FACT_ID_FACT <> FACT_ID_DER_CALCUL
					;

					-- Corrections base HM : Factures annulées comptabilisées

					UPDATE prod_hm.FAC_FACTURE
					SET FACT_DAT_SUP = NULL
					WHERE FACT_DAT_SUP IS NOT NULL AND
						FACT_ID_FACT IN
							(
							SELECT
								FACT_ID_FACT
							FROM prod_hm.CCL_LIGNE_ECRITURE,
								prod_hm.CCL_ECRITURE,
								w_CCL_JOURNAL,
								w_CCL_COMPTE,
								prod_hm.FAC_FACTURE_DEBITEUR,
								prod_hm.FAC_FACTURE
							WHERE
								LECR_ID_ECRI = ECRI_ID_ECRI
								AND LECR_ID_FACD = FACD_ID_FACD
								AND FACD_ID_FACT = FACT_ID_FACT
								AND ECRI_ID_JOUR = JOUR_ID_JOUR
								AND LECR_ID_CPTE = CPTE_ID_CPTE
								AND ECRI_DAT_SUP IS NULL
								AND CPTE_CAGE_CODE IN ('CLIENT' , 'ACO85', 'ACO', 'CLIRMB')
								AND ECRI_ID_ETAB IN ([ID_ETAB])
								AND ECRI_DAT_ECRITURE >= '[ENV_ADM_ANNEEDEBUT]0101'
								AND FACT_TYPE <> 'P'
								AND FACT_DAT_SUP IS NOT NULL
								AND JOUR_CAGE_CODE= 'FACAV'
							GROUP BY 1
							ORDER BY 1
							);

					-- Numéros de factures en double

					ALTER TABLE prod_hm.fac_facture ALTER fact_num_fac TYPE text;

					SELECT base.cti_execute('
					UPDATE prod_hm.FAC_FACTURE
					SET FACT_NUM_FAC = FAC_FACTURE.FACT_NUM_FAC || ''.'' || count
					FROM (
					SELECT FACT_NUM_FAC, MAX(FACT_ID_FACT) AS FACT_ID_FACT, count(*) AS count
					FROM prod_hm.FAC_FACTURE
					WHERE
						FACT_NUM_FAC <> '''' AND
						FACT_TYPE <> ''E'' AND
						(FACT_TYPE = ''P'' OR FACT_DAT_SUP IS NULL)
					GROUP BY 1
					HAVING COUNT(*) > 1
					) subview
					WHERE FAC_FACTURE.FACT_ID_FACT = subview.FACT_ID_FACT',1000);


			]]></sqlcmd>
	</NODE>

	<NODE label="Détection modifications">
		<sqlcmd><![CDATA[



			]]></sqlcmd>
	</NODE>

</NODE>

<NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">

	<NODE label="Patients">
		<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_patients;

				CREATE TEMP TABLE w_patients AS
				SELECT CASE WHEN PATI_NIP = '' OR PATI_NIP IS NULL THEN 'W' || PATI_ID_PATI::bigint ELSE PATI_NIP END AS w_PATI_NIP,
						MAX(PATI_ID_PATI) AS w_PATI_ID_PATI
				FROM w_IDE_SEJOUR_complet JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
				GROUP BY 1;

				INSERT INTO activite[PX].p_patients(finess, no_patient, nom, nom_naissance, prenom, date_naissance, code_sexe)
				SELECT '', w_PATI_NIP, PATI_NOM_USU, PATI_NOM_NAI, PATI_PRENOM, date(PATI_DAT_NAI), CASE WHEN PATI_SEXE = 'F' THEN '2' ELSE '1' END
				FROM w_patients
					JOIN prod_hm.IDE_PATIENT ON PATI_ID_PATI = w_PATI_ID_PATI
					LEFT JOIN activite[PX].p_patients ON (w_PATI_NIP = p_patients.no_patient)
				WHERE p_patients.no_patient IS NULL;

				UPDATE activite[PX].p_patients
				SET nom = PATI_NOM_USU,
					nom_naissance = PATI_NOM_NAI,
					prenom = PATI_PRENOM,
					date_naissance = date(PATI_DAT_NAI),
					code_sexe = CASE WHEN PATI_SEXE = 'F' THEN '2' ELSE '1' END
				FROM prod_hm.IDE_PATIENT JOIN w_patients ON PATI_ID_PATI = w_PATI_ID_PATI
				WHERE p_patients.no_patient = w_PATI_NIP
					AND (
						p_patients.nom IS DISTINCT FROM PATI_NOM_USU OR
						p_patients.nom_naissance IS DISTINCT FROM PATI_NOM_NAI OR
						p_patients.prenom IS DISTINCT FROM PATI_PRENOM OR
						p_patients.date_naissance IS DISTINCT FROM date(PATI_DAT_NAI) OR
						p_patients.code_sexe IS DISTINCT FROM CASE WHEN PATI_SEXE = 'F' THEN '2' ELSE '1' END
					);

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_patients;


			]]></sqlcmd>
	</NODE>

	<NODE label="Séjours">
		<sqlcmd><![CDATA[

					DROP TABLE IF EXISTS w_IDE_PEC;
					CREATE TEMP TABLE w_IDE_PEC AS
					SELECT SEJO_ID_SEJO AS PECH_ID_SEJO,
						COALESCE(MAX(t_tiers_payant_0.oid),0)::bigint AS tiers_payant_0_id,
						COALESCE(MAX(t_tiers_payant_1.oid),0)::bigint AS tiers_payant_1_id,
						COALESCE(MIN(t_tiers_payant_2.oid),0)::bigint AS tiers_payant_2_id,
						COALESCE(MAX(t_tiers_payant_2.oid),0)::bigint AS tiers_payant_22_id,
						COALESCE(MAX(ASSU_NUM_SEC_SOC)) AS matricule_1,
						COALESCE(MAX(SEAM_NUM_ADHERENT)) AS matricule_2
					FROM w_IDE_SEJOUR_complet
						LEFT JOIN prod_hm.IDE_PEC
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON (PECH_ID_ORGA_AMO::bigint = t_tiers_payant_1.code_original AND PECH_ID_ORGA_AMO <> 0) ON (SEJO_ID_SEJO = PECH_ID_SEJO)
						LEFT JOIN prod_hm.IDE_ASSURE ON ASSU_ID_ASSU = PECH_ID_ASSU
						LEFT JOIN prod_hm.IDE_SEJOUR_AMC
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON (SEAM_ID_ORGA_AMC::bigint = t_tiers_payant_2.code_original AND SEAM_ID_ORGA_AMC <> 0) ON (SEJO_ID_SEJO = SEAM_ID_SEJO)
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON (t_tiers_payant_0.type_tiers_payant = '0' AND t_tiers_payant_0.oid <> 0)
					GROUP BY 1;

					ALTER TABLE w_IDE_PEC ADD CONSTRAINT w_IDE_PEC_pkey PRIMARY KEY(PECH_ID_SEJO);

					DROP TABLE IF EXISTS w_IDE_MOUVEMENT_S;
					CREATE TEMP TABLE w_IDE_MOUVEMENT_S AS
					SELECT MOUV_ID_SEJO, 'S'::text AS MOUV_STATUT
					FROM prod_hm.IDE_MOUVEMENT
						JOIN w_IDE_SEJOUR ON MOUV_ID_SEJO = w_SEJO_ID_SEJO
						JOIN prod_hm.BAS_CATALOGUE_GEN ON (MOUV_ID_CAGE = CAGE_ID_CAGE AND CAGE_CODE IN ('S'))
					WHERE date(MOUV_DAT_MOU) <= date(now())
					GROUP BY 1;

					CREATE INDEX w_IDE_MOUVEMENT_S_i1
					ON w_IDE_MOUVEMENT_S
					USING btree
					(MOUV_ID_SEJO);


					DROP TABLE IF EXISTS w_sejours;
					CREATE TEMP TABLE w_sejours AS
					SELECT
						CASE WHEN SEJO_NUM_SEJ IS NULL OR SEJO_NUM_SEJ = '' THEN 'W' || SEJO_ID_SEJO ELSE SEJO_NUM_SEJ END as no_sejour,
						w_SEJO_ID_SEJO::bigint as code_original,
                        CASE WHEN PATI_NIP = '' OR PATI_NIP IS NULL THEN 'W' || PATI_ID_PATI::bigint ELSE PATI_NIP END AS no_patient,
						date(SEJO_DAT_DEB) as date_entree,
						extract('hour' FROM SEJO_DAT_DEB) * 10000 + extract('minute' FROM SEJO_DAT_DEB) * 100 + extract('second' FROM SEJO_DAT_DEB) as heure_entree,
						CASE WHEN SEJO_DAT_FIN IS NOT NULL AND (SEJO_STATUT IN ('S', 'M') OR MOUV_STATUT IN ('S')) THEN date(SEJO_DAT_FIN) ELSE '20991231' END::date as date_sortie,
						CASE WHEN SEJO_DAT_FIN IS NOT NULL THEN extract('hour' FROM SEJO_DAT_FIN) * 10000 + extract('minute' FROM SEJO_DAT_FIN) * 100 + extract('second' FROM SEJO_DAT_FIN) ELSE 0 END as heure_sortie,
						CASE WHEN PATI_SEXE = 'F' THEN '2' ELSE '1' END as code_sexe,
						0 AS age,
						CASE WHEN SEJO_STATUT IN ('S', 'M') AND SEJO_DAT_FIN <= date(now()) OR MOUV_STATUT IN ('S') THEN 1 ELSE 0 END as code_sorti,
						CASE WHEN SEJO_STATUT IN ('A', 'P') OR date(SEJO_DAT_DEB) > date(date_extraction) THEN 1 ELSE 0 END as code_prevu,
						CASE
							WHEN SEJO_DAT_SUP IS NOT NULL THEN '9'
							WHEN SEJO_IND_INCOMPLET = '1' THEN '9'
							WHEN SEJO_STATUT = 'Z' THEN '9'

							WHEN t_divers.valeur IN ('1', '2', '3', '4', '5', '6', '9') THEN t_divers.valeur
							WHEN t_services_facturation.type_sejour IN ('1', '2', '3', '4', '5') THEN t_services_facturation.type_sejour
							WHEN t_modes_traitement.code IN ('07') OR t_dmt.code In ('958') THEN '3'
							WHEN t_modes_traitement.code IN ('19', '23') AND date(SEJO_DAT_FIN) = date(SEJO_DAT_DEB) THEN '2'
							WHEN t_modes_traitement.code IN ('04') AND date(SEJO_DAT_FIN) = date(SEJO_DAT_DEB) THEN '2'
							WHEN t_modes_traitement.code IN ('03') AND date(SEJO_DAT_FIN) = date(SEJO_DAT_DEB) THEN '2'
							WHEN t_modes_traitement.code IN ('10') AND date(SEJO_DAT_FIN) <= date(SEJO_DAT_DEB) + interval '1 day' THEN '3'
							ELSE '1' END as type_sejour,
						t_medecins_administratifs.oid as medecin_sejour_id,
						0 as ghs_id,
						'20991231'::date as date_groupage,
						SEJO_IND_CHB_PAR as code_cp_demandee,
						t_services_facturation.mode_traitement_id as mode_traitement_id,
						'8'::character(1) as mode_entree,
						'0'::character(1) as provenance,
						'8'::character(1) as mode_sortie,
						'0'::character(1) as destination,
						COALESCE(tiers_payant_0_id,0) AS tiers_payant_0_id,
						COALESCE(tiers_payant_1_id,0) AS tiers_payant_1_id,
						COALESCE(tiers_payant_2_id,0) AS tiers_payant_2_id,
						CASE WHEN COALESCE(tiers_payant_22_id,0) <> COALESCE(tiers_payant_2_id,0) THEN COALESCE(tiers_payant_22_id,0) ELSE 0 END AS tiers_payant_22_id,
						CASE WHEN COALESCE(SEJO_IND_BGH,'0') = '1' THEN 1 ELSE 0 END AS est_budget_global,
						COALESCE(t_divers.valeur,'') AS type_sejour_force_hm

					FROM w_IDE_SEJOUR_complet
							LEFT JOIN w_IDE_PEC ON (PECH_ID_SEJO = SEJO_ID_SEJO)
							JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
							JOIN prod_hm.BAS_CATALOGUE_PERS ON (SEJO_ID_CAPE_VEN = CAPE_ID_CAPE)
							LEFT JOIN activite.t_divers ON t_divers.code = ('HM_TYPSEJ_' || CAPE_CODE)
							JOIN activite[PX].t_services_facturation ON SEJO_ID_UNFO::bigint = t_services_facturation.code_original
							JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
							JOIN base.t_dmt ON t_services_facturation.dmt_id = t_dmt.oid
							JOIN activite[PX].t_medecins_administratifs ON SEJO_ID_MEDE_COURANT::bigint = t_medecins_administratifs.code_original
							LEFT JOIN w_IDE_MOUVEMENT_S ON w_SEJO_ID_SEJO = MOUV_ID_SEJO
						;

					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_2');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_3');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_4');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_5');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_6');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_7');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_8');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_9');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_10');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_11');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_12');
					SELECT base.cti_disable_index('activite[PX]', 'i_sejours_13');

					-- Forcage type selon séjour
					UPDATE w_sejours
					SET type_sejour = t_sejour.type_sejour
					FROM activite.t_sejour
					WHERE t_sejour.no_sejour = w_sejours.no_sejour AND
						t_sejour.type_sejour IN ('1','2','3','4','5','6','9');

					UPDATE activite[PX].p_sejours SET
						code_original = w_sejours.code_original,
						no_patient = w_sejours.no_patient,
						date_entree = w_sejours.date_entree,
						heure_entree = w_sejours.heure_entree,
						date_sortie = w_sejours.date_sortie,
						heure_sortie = w_sejours.heure_sortie,
						code_sexe = w_sejours.code_sexe,
						age = w_sejours.age,
						code_sorti = w_sejours.code_sorti,
						code_prevu = w_sejours.code_prevu,
						type_sejour = w_sejours.type_sejour,
						medecin_sejour_id = w_sejours.medecin_sejour_id,
						code_cp_demandee = w_sejours.code_cp_demandee,
						mode_traitement_id = w_sejours.mode_traitement_id,
						mode_entree = w_sejours.mode_entree,
						provenance = w_sejours.provenance,
						mode_sortie = w_sejours.mode_sortie,
						destination = w_sejours.destination,
						tiers_payant_0_id = w_sejours.tiers_payant_0_id,
						tiers_payant_1_id = w_sejours.tiers_payant_1_id,
						tiers_payant_2_id = w_sejours.tiers_payant_2_id,
						tiers_payant_22_id = w_sejours.tiers_payant_22_id,
						est_budget_global = w_sejours.est_budget_global
					FROM w_sejours
					WHERE w_sejours.no_sejour = p_sejours.no_sejour
					AND (
						w_sejours.code_original IS DISTINCT FROM p_sejours.code_original OR
						w_sejours.no_patient IS DISTINCT FROM p_sejours.no_patient OR
						w_sejours.date_entree IS DISTINCT FROM p_sejours.date_entree OR
						w_sejours.heure_entree IS DISTINCT FROM p_sejours.heure_entree OR
						w_sejours.date_sortie IS DISTINCT FROM p_sejours.date_sortie OR
						w_sejours.heure_sortie IS DISTINCT FROM p_sejours.heure_sortie OR
						w_sejours.code_sexe IS DISTINCT FROM p_sejours.code_sexe OR
						w_sejours.age IS DISTINCT FROM p_sejours.age OR
						w_sejours.code_sorti IS DISTINCT FROM p_sejours.code_sorti OR
						w_sejours.code_prevu IS DISTINCT FROM p_sejours.code_prevu OR
						w_sejours.type_sejour IS DISTINCT FROM p_sejours.type_sejour OR
						w_sejours.medecin_sejour_id IS DISTINCT FROM p_sejours.medecin_sejour_id OR
						w_sejours.code_cp_demandee IS DISTINCT FROM p_sejours.code_cp_demandee OR
						w_sejours.mode_traitement_id IS DISTINCT FROM p_sejours.mode_traitement_id OR
						w_sejours.mode_entree IS DISTINCT FROM p_sejours.mode_entree OR
						w_sejours.provenance IS DISTINCT FROM p_sejours.provenance OR
						w_sejours.mode_sortie IS DISTINCT FROM p_sejours.mode_sortie OR
						w_sejours.destination IS DISTINCT FROM p_sejours.destination OR
						w_sejours.tiers_payant_0_id IS DISTINCT FROM p_sejours.tiers_payant_0_id OR
						w_sejours.tiers_payant_1_id IS DISTINCT FROM p_sejours.tiers_payant_1_id OR
						w_sejours.tiers_payant_2_id IS DISTINCT FROM p_sejours.tiers_payant_2_id OR
						w_sejours.tiers_payant_22_id IS DISTINCT FROM p_sejours.tiers_payant_22_id OR
						w_sejours.est_budget_global IS DISTINCT FROM p_sejours.est_budget_global
					);

				INSERT INTO activite[PX].p_sejours (
					no_sejour,
					code_original,
					no_patient,
					date_entree,
					heure_entree,
					date_sortie,
					heure_sortie,
					code_sexe,
					age,
					code_sorti,
					code_prevu,
					type_sejour,
					medecin_sejour_id,
					ghs_id,
					date_groupage,
					code_cp_demandee,
					mode_traitement_id,
					mode_entree,
					provenance,
					mode_sortie,
					destination,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					est_budget_global
				)
				SELECT
					w_sejours.no_sejour,
					w_sejours.code_original,
					w_sejours.no_patient,
					w_sejours.date_entree,
					w_sejours.heure_entree,
					w_sejours.date_sortie,
					w_sejours.heure_sortie,
					w_sejours.code_sexe,
					w_sejours.age,
					w_sejours.code_sorti,
					w_sejours.code_prevu,
					w_sejours.type_sejour,
					w_sejours.medecin_sejour_id,
					w_sejours.ghs_id,
					w_sejours.date_groupage,
					w_sejours.code_cp_demandee,
					w_sejours.mode_traitement_id,
					w_sejours.mode_entree,
					w_sejours.provenance,
					w_sejours.mode_sortie,
					w_sejours.destination,
					w_sejours.tiers_payant_0_id,
					w_sejours.tiers_payant_1_id,
					w_sejours.tiers_payant_2_id,
					w_sejours.tiers_payant_22_id,
					w_sejours.est_budget_global

				FROM w_sejours LEFT JOIN activite[PX].p_sejours ON (w_sejours.no_sejour = p_sejours.no_sejour)
				WHERE p_sejours.no_sejour IS NULL;


				DELETE FROM activite[PX].p_sejours
				USING activite[PX].p_sejours AS p_sejours_i LEFT JOIN w_sejours ON (w_sejours.no_sejour = p_sejours_i.no_sejour)
				WHERE
					p_sejours.no_sejour = p_sejours_i.no_sejour AND
					w_sejours.no_sejour IS NULL;

				-- Modes entrée sortie selon mouvements
				DROP TABLE IF EXISTS w_MOUV_MOD_SOR;
				CREATE TEMP TABLE w_MOUV_MOD_SOR AS
				SELECT MOUV_ID_SEJO,
					(MAX(ARRAY[MOUV_DAT_MOU::text, CAPE_CODE]))[2]::text AS MOD_SOR
				FROM prod_hm.IDE_MOUVEMENT
					JOIN activite[PX].p_sejours ON MOUV_ID_SEJO::bigint = p_sejours.code_original
					JOIN prod_hm.BAS_CATALOGUE_GEN ON (MOUV_ID_CAGE = CAGE_ID_CAGE AND CAGE_CODE IN ('E', 'D', 'M', 'S'))
					JOIN prod_hm.BAS_CATALOGUE_PERS ON (MOUV_ID_CAPE_SOR = CAPE_ID_CAPE)
				GROUP BY 1;

				UPDATE w_MOUV_MOD_SOR
				SET MOD_SOR = '80' WHERE MOD_SOR = '8';

				UPDATE activite[PX].p_sejours
				SET mode_sortie = substr(MOD_SOR,1,1)
				FROM w_MOUV_MOD_SOR
				WHERE code_original = MOUV_ID_SEJO AND
					substr(MOD_SOR,1,1) IS DISTINCT FROM mode_sortie AND
					substr(MOD_SOR,1,1) IN (SELECT code FROM base.t_modes_sortie);

				UPDATE activite[PX].p_sejours
				SET destination = substr(MOD_SOR,2,1)
				FROM w_MOUV_MOD_SOR
				WHERE code_original = MOUV_ID_SEJO AND
					length(MOD_SOR) = 2 AND
					substr(MOD_SOR,2,1) IS DISTINCT FROM destination AND
					substr(MOD_SOR,2,1) IN (SELECT code FROM base.t_destinations_sortie);




				DROP TABLE IF EXISTS w_MOUV_MOD_ENT;
				CREATE TEMP TABLE w_MOUV_MOD_ENT AS
				SELECT MOUV_ID_SEJO,
					(MIN(ARRAY[MOUV_DAT_MOU::text, CAPE_CODE]))[2]::text AS MOD_ENT
				FROM prod_hm.IDE_MOUVEMENT
					JOIN activite[PX].p_sejours ON MOUV_ID_SEJO::bigint = p_sejours.code_original
					JOIN prod_hm.BAS_CATALOGUE_GEN ON (MOUV_ID_CAGE = CAGE_ID_CAGE AND CAGE_CODE IN ('E', 'D', 'M', 'S'))
					JOIN prod_hm.BAS_CATALOGUE_PERS ON (MOUV_ID_CAPE_ENT = CAPE_ID_CAPE)
				GROUP BY 1;

				UPDATE w_MOUV_MOD_ENT
				SET MOD_ENT = '80' WHERE MOD_ENT = '8';

				UPDATE activite[PX].p_sejours
				SET mode_entree = substr(MOD_ENT,1,1)
				FROM w_MOUV_MOD_ENT
				WHERE code_original = MOUV_ID_SEJO AND
					substr(MOD_ENT,1,1) IS DISTINCT FROM mode_entree AND
					substr(MOD_ENT,1,1) IN (SELECT code FROM base.t_modes_entree);

				UPDATE activite[PX].p_sejours
				SET provenance = substr(MOD_ENT,2,1)
				FROM w_MOUV_MOD_ENT
				WHERE code_original = MOUV_ID_SEJO AND
					length(MOD_ENT) = 2 AND
					substr(MOD_ENT,2,1) IS DISTINCT FROM provenance AND
					substr(MOD_ENT,2,1) IN (SELECT code FROM base.t_provenances_entree);


				-- Modes entrée sortie selon PMSI MCO
				UPDATE activite[PX].p_sejours
				SET mode_entree = CASE WHEN TRUM_MOD_ENT < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_ENT::bigint * 10,1,1) END,
					provenance = CASE WHEN TRUM_MOD_ENT < 8 THEN TRUM_MOD_ENT::text ELSE SUBSTR(TRUM_MOD_ENT::bigint * 10,2,1) END
				FROM w_IDE_SEJOUR_complet JOIN
					(SELECT
						TRUM_ID_SEJO,
						MIN(TRUM_DAT_ENT_RUM) AS TRUM_DAT_ENT_RUM,
						(MIN(ARRAY[TRUM_DAT_ENT_RUM::text,TRUM_MOD_ENT::text]))[2]::bigint AS TRUM_MOD_ENT
					FROM
						prod_hm.PMS_RUM
					GROUP BY 1) sub ON SEJO_ID_SEJO = TRUM_ID_SEJO AND date(TRUM_DAT_ENT_RUM) = date(SEJO_DAT_DEB)
				WHERE
					no_sejour = w_SEJO_NUM_SEJ AND
					(
					mode_entree <> CASE WHEN TRUM_MOD_ENT < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_ENT::bigint * 10,1,1) END OR
					provenance <> CASE WHEN TRUM_MOD_ENT < 8 THEN TRUM_MOD_ENT::text ELSE SUBSTR(TRUM_MOD_ENT::bigint * 10,2,1) END
					)
					;

				UPDATE activite[PX].p_sejours
					SET mode_sortie = CASE WHEN TRUM_MOD_SOR < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_SOR::bigint * 10,1,1) END,
					destination = CASE WHEN TRUM_MOD_SOR < 8 THEN TRUM_MOD_SOR::text ELSE SUBSTR(TRUM_MOD_SOR::bigint * 10,2,1) END
				FROM w_IDE_SEJOUR_complet JOIN
					(SELECT
						TRUM_ID_SEJO,
						MAX(TRUM_DAT_SOR_RUM) AS TRUM_DAT_SOR_RUM,
						(MAX(ARRAY[TRUM_DAT_SOR_RUM::text,TRUM_MOD_SOR::text]))[2]::bigint AS TRUM_MOD_SOR
					FROM
						prod_hm.PMS_RUM
					GROUP BY 1) sub ON SEJO_ID_SEJO = TRUM_ID_SEJO AND date(TRUM_DAT_SOR_RUM) = date(SEJO_DAT_FIN)
				WHERE
					no_sejour = w_SEJO_NUM_SEJ AND
					(
					mode_sortie <> CASE WHEN TRUM_MOD_SOR < 8 THEN '0'::text ELSE SUBSTR(TRUM_MOD_SOR::bigint * 10,1,1) END OR
					destination <> CASE WHEN TRUM_MOD_SOR < 8 THEN TRUM_MOD_SOR::text ELSE SUBSTR(TRUM_MOD_SOR::bigint * 10,2,1) END
					);

				-- Etablissements de provenance et destination
				-- insertion nouveaux etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT * FROM prod_hm.IDE_ETABLISSEMENT_EXTERIEUR LEFT JOIN base.t_etablissements ON ETEX_CODE = code
					WHERE ETEX_ID_ETEX = ANY(array(SELECT SEJO_ID_ETEX_PRO FROM prod_hm.IDE_SEJOUR)::bigint[])
						OR ETEX_ID_ETEX = ANY(array(SELECT SEJO_ID_ETEX_DES FROM prod_hm.IDE_SEJOUR)::bigint[]);

				INSERT INTO base.t_etablissements
					(
						code,
						texte,
						texte_court
					)
					SELECT
						ETEX_CODE,
						ETEX_NOM,
						ETEX_NOM
					FROM w_ETAB
					WHERE code IS NULL;

				-- rechargements des etablissements
				DROP TABLE IF EXISTS w_ETAB;
				CREATE TEMP TABLE w_ETAB AS
					SELECT * FROM prod_hm.IDE_ETABLISSEMENT_EXTERIEUR LEFT JOIN base.t_etablissements ON ETEX_CODE = code;

                -- insertion des données de correspondances (pas d'update car les tables sont vidées avant import)
                DROP TABLE IF EXISTS w_TRANS;
				CREATE TEMP TABLE w_TRANS AS
					SELECT
						CASE WHEN SEJO_NUM_SEJ IS NULL OR SEJO_NUM_SEJ = '' THEN 'W' || SEJO_ID_SEJO ELSE SEJO_NUM_SEJ END as no_sejour,
						etex_pro.oid as oid_pro,
						etex_des.oid as oid_des
					FROM w_IDE_SEJOUR_complet
						LEFT JOIN w_ETAB as etex_pro ON w_IDE_SEJOUR_complet.SEJO_ID_ETEX_PRO = etex_pro.ETEX_ID_ETEX
						LEFT JOIN w_ETAB as etex_des ON w_IDE_SEJOUR_complet.SEJO_ID_ETEX_DES = etex_des.ETEX_ID_ETEX
					WHERE SEJO_ID_ETEX_PRO <> 0 OR SEJO_ID_ETEX_DES <> 0;

				INSERT INTO activite[PX].p_sejours_transferts(
					sejour_id,
					provenance_id,
					destination_id
					)
					SELECT
						p_sejours.oid,
						MAX(COALESCE(oid_pro,0)),
						MAX(COALESCE(oid_des,0))
					FROM activite[PX].p_sejours
						JOIN w_TRANS ON w_TRANS.no_sejour = p_sejours.no_sejour
					GROUP BY 1
					;

				-- ghm et ghs
				UPDATE activite[PX].p_sejours SET
					ghs_id = COALESCE(t_ghs.oid,0),
					ghm_id = COALESCE(t_ghm.oid,0),
					date_groupage = CASE WHEN TGHM_NUMERO <> '' AND TGHM_NUMERO NOT LIKE '90%' THEN COALESCE(date(TRUM_DAT_DER_GROUPAGE),'20991231)') ELSE '20991231' END
				FROM prod_hm.PMS_RSS
					LEFT JOIN
						(
						SELECT TRUM_ID_TRSS, MAX(TRUM_DAT_DER_GROUPAGE) AS TRUM_DAT_DER_GROUPAGE FROM prod_hm.PMS_RUM GROUP BY 1
						) subview ON TRUM_ID_TRSS = TRSS_ID_TRSS
					LEFT JOIN prod_hm.PMS_GHM ON (TRSS_ID_TGHM = TGHM_ID_TGHM)
					LEFT JOIN base.t_ghs ON TRSS_SARGH_NUM_GHS = t_ghs.code
					LEFT JOIN base.t_ghm ON TGHM_NUMERO = t_ghm.code AND t_ghm.code NOT LIKE '90%'
				WHERE
					p_sejours.code_original = TRSS_ID_SEJO_D AND
					TGHM_NUMERO <> '' AND
					(
						p_sejours.ghs_id IS DISTINCT FROM COALESCE(t_ghs.oid,0) OR
						p_sejours.ghm_id IS DISTINCT FROM COALESCE(t_ghm.oid,0) OR
						p_sejours.date_groupage IS DISTINCT FROM CASE WHEN TGHM_NUMERO <> '' AND TGHM_NUMERO NOT LIKE '90%' THEN COALESCE(date(TRUM_DAT_DER_GROUPAGE),'20991231)') ELSE '20991231' END
					)
				;

				-- Code postal ?
				DROP TABLE IF EXISTS w_SEJO_COD_POS;
				CREATE TEMP TABLE w_SEJO_COD_POS AS
				SELECT SEJO_ID_SEJO,
					(MAX(ARRAY[ADRE_DAT_MOD::text, ADRE_COD_POS]))[2]::text AS ADRE_COD_POS,
					(MAX(ARRAY[ADRE_DAT_MOD::text, ADRE_VILLE]))[2]::text AS ADRE_VILLE,
					(MAX(ARRAY[ADRE_DAT_MOD::text, COALESCE(t_codes_postaux.oid,0)::text]))[2]::bigint AS code_postal_id
				FROM prod_hm.IDE_PATIENT
				JOIN prod_hm.IDE_SEJOUR ON SEJO_ID_PATI = PATI_ID_PATI
				JOIN prod_hm.IDE_ADRESSE ON PATI_ID_PATI = ADRE_ID_OBJ
				JOIN base.t_codes_postaux ON ADRE_COD_POS = t_codes_postaux.code
				JOIN prod_hm.BAS_CATALOGUE_GEN ON IDE_ADRESSE.ADRE_ID_CAGE = BAS_CATALOGUE_GEN.CAGE_ID_CAGE AND CAGE_CODE = 'ADR_PERSO'
				WHERE ADRE_COD_POS <> '' AND LENGTH(ADRE_COD_POS) = 5
				GROUP BY 1;

				UPDATE activite[PX].p_sejours
				SET code_postal_id = w_SEJO_COD_POS.code_postal_id
				FROM w_SEJO_COD_POS
				WHERE code_original = SEJO_ID_SEJO AND
					p_sejours.code_postal_id IS DISTINCT FROM w_SEJO_COD_POS.code_postal_id;

				-- Type séance d'après GHM
				UPDATE activite[PX].p_sejours
				SET type_sejour = '5'
				FROM base.t_ghm,
					activite[PX].t_lieux
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.type_sejour <> '5' AND
					p_sejours.type_sejour <> '9' AND
					ghm_id = t_ghm.oid AND
					lieu_sortie_id = t_lieux.oid AND
					t_services_facturation.type_sejour <> '0sauf5' AND
					t_ghm.code LIKE '28%' AND
					no_sejour NOT IN (SELECT no_sejour FROM w_sejours WHERE type_sejour_force_hm <> '');


				-- Séjours ignorés
				UPDATE activite[PX].p_sejours
				SET etat = 'I'
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					est_ignore = '1' AND
					etat <> 'I' AND
					'[PX]' = '';

				UPDATE activite[PX].p_sejours
				SET etat = ''
				WHERE etat = 'I' AND
					no_sejour NOT IN (SELECT no_sejour FROM activite.t_sejour WHERE est_ignore = '1') AND
					'[PX]' = '';

				-- Médecin séjour forcé
				UPDATE activite[PX].p_sejours
				SET medecin_sejour_id = t_sejour.medecin_sejour_id
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					t_sejour.medecin_sejour_id <> 0 AND
					p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
					'[PX]' = '';


				-- recréation index
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_13');


				-- assurance
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_4');

				INSERT INTO activite[PX].p_sejours_assurance(
					sejour_id,
					tiers_payant_0_id,
					tiers_payant_1_id,
					matricule_1,
					tiers_payant_2_id,
					matricule_2,
					tiers_payant_22_id,
					matricule_22)
				SELECT
					oid AS sejour_id,
					p_sejours.tiers_payant_0_id,
					p_sejours.tiers_payant_1_id,
					substr(w_IDE_PEC.matricule_1,1,30),
					p_sejours.tiers_payant_2_id,
					substr(w_IDE_PEC.matricule_2,1,30),
					p_sejours.tiers_payant_22_id,
					''::text AS matricule_22
				FROM w_IDE_PEC
					JOIN activite[PX].p_sejours ON code_original = PECH_ID_SEJO AND p_sejours.etat = '';



				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_4');

				
				-- SMR 
				-- Compléments d'informations
				DROP TABLE IF EXISTS w_sejours_smr_groupes;
				CREATE TEMP TABLE w_sejours_smr_groupes AS
				WITH dernier_gme_valide_par_sejour AS (
					SELECT DISTINCT ON (trhs_id_sejo)
						trhs_id_sejo AS sejour_id
						, PMS_GME.TGME_CODE AS gme_code
						, t_gme.oid AS gme_id
						, trhs_dat_der_groupage AS date_groupage
					FROM prod_hm.pms_rhs
						JOIN prod_hm.PMS_GME ON PMS_GME.TGME_ID_TGME = PMS_RHS.TRHS_ID_TGME
						JOIN base.t_gme ON PMS_GME.TGME_CODE = t_gme.code
					ORDER BY trhs_id_sejo, trhs_dat_ent DESC, trhs_dat_der_groupage DESC
				)
				SELECT
					IDE_SEJOUR.SEJO_NUM_SEJ AS no_sejour
					, IDE_SEJOUR.sejo_dat_deb AS date_entree
					, IDE_SEJOUR.sejo_dat_fin AS date_sortie
					, COALESCE(TRHS_DAT_DER_GROUPAGE, dernier_gme_valide_par_sejour.date_groupage) AS date_groupage 
					, dernier_gme_valide_par_sejour.gme_code AS gme_code
					, dernier_gme_valide_par_sejour.gme_id AS gme_id
					, PMS_RHS.TRHS_COD_GMT AS gmt_code
					, 0 AS gmt_id
					, PMS_RHS.TRHS_DAT_ENT AS date_debut_rhs
					, PMS_RHS.TRHS_DAT_SOR AS date_fin_rhs
					, PMS_RHS.TRHS_NBJ_PRES_HWE AS nb_jours_presence_semaine
					, DATE_PART('day', pms_rhs.TRHS_DAT_SOR - sejo_dat_deb) + 1 AS nb_jours_presence_total
					, CASE
						WHEN DATE_PART('day', pms_rhs.TRHS_DAT_SOR - sejo_dat_deb) <= 90 THEN 'periode_1'
						ELSE 'periode_2'
					END AS periode
					, ''::text AS types_gmt_code
				FROM prod_hm.pms_rhs
					JOIN prod_hm.ide_sejour ON ide_sejour.sejo_id_sejo = pms_rhs.trhs_id_sejo
					JOIN dernier_gme_valide_par_sejour ON dernier_gme_valide_par_sejour.sejour_id = pms_rhs.trhs_id_sejo
					JOIN activite[PX].p_sejours ON p_sejours.no_sejour = IDE_SEJOUR.SEJO_NUM_SEJ
				WHERE 1 = 1
					AND SEJO_STATUT NOT IN ('A', 'P')
					AND TRHS_DAT_SOR <= now()
					ORDER BY SEJO_NUM_SEJ, TRHS_DAT_ENT
				;
				
				ANALYZE w_sejours_smr_groupes;
				
				WITH sejours_avec_gmt_9999 AS (
					SELECT DISTINCT(no_sejour)
					FROM w_sejours_smr_groupes
					WHERE gmt_code = '9999'
				),
				gmt_hc_reconstitues_par_sejour AS (
					SELECT
						w_sejours_smr_groupes.no_sejour
						, gmt1.code AS code_gmt_90_premiers_jours
						, gmt2.code AS gmt_post_90_jours
					FROM w_sejours_smr_groupes
						JOIN sejours_avec_gmt_9999 ON sejours_avec_gmt_9999.no_sejour = w_sejours_smr_groupes.no_sejour
						JOIN base.v_tarifs_prive_gmt_hc_pre_90_jours gmt1 ON w_sejours_smr_groupes.gme_code = gmt1.gme_code
							AND w_sejours_smr_groupes.date_debut_rhs BETWEEN gmt1.date_debut AND gmt1.date_fin
						JOIN base.v_tarifs_prive_gmt_en_7 gmt2 ON w_sejours_smr_groupes.gme_code = gmt2.gme_code
							AND w_sejours_smr_groupes.date_debut_rhs BETWEEN gmt2.date_debut AND gmt2.date_fin
				)
				UPDATE w_sejours_smr_groupes
				SET gmt_code = 
					CASE 
						WHEN periode = 'periode_1' THEN code_gmt_90_premiers_jours
						ELSE gmt_post_90_jours
					END
				FROM gmt_hc_reconstitues_par_sejour
				WHERE w_sejours_smr_groupes.no_sejour = gmt_hc_reconstitues_par_sejour.no_sejour
				;
				
				WITH dernier_gmt_valide_par_sejour AS (
					SELECT DISTINCT ON (no_sejour)
						no_sejour
						, gmt_code
					FROM w_sejours_smr_groupes
					WHERE gmt_code <> ''
					ORDER BY no_sejour, date_fin_rhs DESC, date_groupage DESC
				)
				UPDATE w_sejours_smr_groupes
				SET gmt_code = dernier_gmt_valide_par_sejour.gmt_code
				FROM dernier_gmt_valide_par_sejour
				WHERE dernier_gmt_valide_par_sejour.no_sejour = w_sejours_smr_groupes.no_sejour
					AND w_sejours_smr_groupes.gmt_code = ''
				;
				
				WITH affectation_dates_gmt AS (
					SELECT DISTINCT ON (periode, no_sejour)
						periode
						, no_sejour
						, MIN(date_debut_rhs) AS date_debut_rhs
						, MAX(date_fin_rhs) AS date_fin_rhs
					FROM w_sejours_smr_groupes
					GROUP BY 
						periode
						, no_sejour
				)
				UPDATE w_sejours_smr_groupes
				SET 
					date_debut_rhs = affectation_dates_gmt.date_debut_rhs
					, date_fin_rhs = affectation_dates_gmt.date_fin_rhs
				FROM affectation_dates_gmt
				WHERE affectation_dates_gmt.no_sejour = w_sejours_smr_groupes.no_sejour
					AND w_sejours_smr_groupes.periode = affectation_dates_gmt.periode
				;
			
				WITH presence_moyenne_hebdomadaire AS (
					SELECT 
						no_sejour
						, SUM(nb_jours_presence_semaine) AS total_presence_hebdomadaire
						, GREATEST(COUNT(*), 1) AS nombre_semaines
					FROM w_sejours_smr_groupes
					WHERE nb_jours_presence_semaine <> 0
					GROUP BY no_sejour
				)
				UPDATE w_sejours_smr_groupes
				SET nb_jours_presence_semaine = (total_presence_hebdomadaire / nombre_semaines)::numeric
				FROM presence_moyenne_hebdomadaire
				WHERE presence_moyenne_hebdomadaire.no_sejour = w_sejours_smr_groupes.no_sejour 
					AND nb_jours_presence_semaine = 0
				;
				
				WITH presence_hors_weekend_par_sejour AS (
					SELECT 
						no_sejour
						, SUM(nb_jours_presence_semaine) AS total_jours_presence
					FROM w_sejours_smr_groupes
					GROUP BY 1
				)
				UPDATE w_sejours_smr_groupes
				SET nb_jours_presence_semaine = total_jours_presence
				FROM presence_hors_weekend_par_sejour
				WHERE presence_hors_weekend_par_sejour.no_sejour = w_sejours_smr_groupes.no_sejour
				;
				
				UPDATE w_sejours_smr_groupes
				SET nb_jours_presence_total = nb_jours_presence_total - 90 
				WHERE 
					EXISTS (SELECT 1 FROM base.v_tarifs_prive_gmt_en_7 WHERE v_tarifs_prive_gmt_en_7.code = w_sejours_smr_groupes.gmt_code)
					AND periode = 'periode_2'
				;
				
				UPDATE w_sejours_smr_groupes
				SET types_gmt_code = 
					CASE
						WHEN EXISTS (SELECT 1 FROM base.v_tarifs_prive_gmt_forfaitisables WHERE w_sejours_smr_groupes.gmt_code = v_tarifs_prive_gmt_forfaitisables.code) THEN 'hc_forfaitisable'
						WHEN EXISTS (SELECT 1 FROM base.v_tarifs_prive_gmt_non_forfaitisables WHERE w_sejours_smr_groupes.gmt_code = v_tarifs_prive_gmt_non_forfaitisables.code) THEN 'hc_non_forfaitisable'
						WHEN EXISTS (SELECT 1 FROM base.v_tarifs_prive_gmt_hospitalisation_partielle WHERE w_sejours_smr_groupes.gmt_code = v_tarifs_prive_gmt_hospitalisation_partielle.code) THEN 'hp_hebdomadaire'
						ELSE 'hc_sans_zf'
					END
				;
				
				DROP TABLE IF EXISTS w_codes_pour_sejours_avec_deux_gmt;
				
				CREATE TEMP TABLE w_codes_pour_sejours_avec_deux_gmt AS
				SELECT code, gme_code, date_debut, date_fin FROM base.v_tarifs_prive_gmt_dzf_90
				UNION
				SELECT code, gme_code, date_debut, date_fin FROM base.v_tarifs_prive_gmt_forfaitisables
				UNION
				SELECT code, gme_code, date_debut, date_fin FROM base.v_tarifs_prive_gmt_non_forfaitisables
				UNION 
				SELECT code, gme_code, date_debut, date_fin FROM base.v_tarifs_prive_gmt_en_7
				;
				
				-- Mise à jour des dates de début de rhs pour hospitalisations partielles de + 90jrs						
				WITH sejours_hp AS (
					SELECT
						no_sejour
						, MIN(date_debut_rhs) AS date_debut_rhs
					FROM w_sejours_smr_groupes
					WHERE types_gmt_code = 'hp_hebdomadaire'
					GROUP BY no_sejour
				)
				UPDATE w_sejours_smr_groupes
				SET date_debut_rhs = sejours_hp.date_debut_rhs
				FROM sejours_hp
				WHERE sejours_hp.no_sejour = w_sejours_smr_groupes.no_sejour
				;
				
				-- Mise à jour des dates de fin de rhs en HC pour les patients encore présents
				WITH sejours_hc_patients_presents AS (
					SELECT DISTINCT ON (no_sejour)
						no_sejour
						, periode
						, date_sortie
					FROM w_sejours_smr_groupes
					WHERE 
						types_gmt_code ILIKE 'hc%'
						AND (
							w_sejours_smr_groupes.date_sortie IS NULL
							OR w_sejours_smr_groupes.date_sortie > now()
						)
					ORDER BY 
						no_sejour
						, periode DESC	
				)
				UPDATE w_sejours_smr_groupes
				SET date_fin_rhs = now()
				FROM sejours_hc_patients_presents
				WHERE 
					sejours_hc_patients_presents.no_sejour = w_sejours_smr_groupes.no_sejour
					AND sejours_hc_patients_presents.periode = w_sejours_smr_groupes.periode
				;
							
				WITH sejours_gmt_hospit_partielle AS (
					SELECT DISTINCT ON (no_sejour)
						no_sejour
						, date_entree
						, date_sortie
						, date_groupage
						, gmt_code
						, gmt_id
						, gme_code
						, gme_id
						, date_debut_rhs
						, date_fin_rhs
						, nb_jours_presence_semaine
						, types_gmt_code
					FROM w_sejours_smr_groupes
					WHERE types_gmt_code = 'hp_hebdomadaire'
					ORDER BY 
						no_sejour
						, date_fin_rhs DESC			
				),
				sejours_gmt_en_8 AS (
					SELECT DISTINCT ON (no_sejour)
						no_sejour
						, date_entree
						, date_sortie
						, date_groupage
						, gmt_code
						, gmt_id
						, gme_code
						, gme_id
						, date_debut_rhs
						, date_fin_rhs
						, nb_jours_presence_total
						, types_gmt_code
					FROM w_sejours_smr_groupes
					WHERE gmt_code LIKE '8%'
					ORDER BY 
						no_sejour
						, date_fin_rhs DESC
				),
				sejours_gmt_multiples AS (
					SELECT DISTINCT ON (no_sejour, gmt_code, periode)
						no_sejour
						, date_entree
						, date_sortie
						, date_groupage
						, gmt_code
						, gmt_id
						, gme_code
						, gme_id
						, date_debut_rhs
						, date_fin_rhs
						, nb_jours_presence_total
						, types_gmt_code
					FROM w_sejours_smr_groupes
					WHERE EXISTS (
						SELECT 1 FROM w_codes_pour_sejours_avec_deux_gmt 
						WHERE w_sejours_smr_groupes.gmt_code = w_codes_pour_sejours_avec_deux_gmt.code
							AND w_sejours_smr_groupes.gme_code = w_codes_pour_sejours_avec_deux_gmt.gme_code
							AND w_sejours_smr_groupes.date_fin_rhs BETWEEN w_codes_pour_sejours_avec_deux_gmt.date_debut AND w_codes_pour_sejours_avec_deux_gmt.date_fin
					) 
					ORDER BY 
						no_sejour
						, gmt_code, periode
						, nb_jours_presence_total DESC
				)
				INSERT INTO activite[PX].p_sejours_groupes_smr (no_sejour, date_entree, date_sortie, date_groupage, gmt_code, gmt_id, gme_code, gme_id, date_debut_gmt, date_fin_gmt, nb_jours_presence, types_gmt_code)
				SELECT *
				FROM sejours_gmt_multiples
				UNION ALL
				SELECT * FROM sejours_gmt_hospit_partielle
				UNION ALL 
				SELECT * FROM sejours_gmt_en_8
				ON CONFLICT (no_sejour, gmt_code)
				DO NOTHING 
				; 
	
				-- MAJ des séjours groupés dans la table des séjours
				WITH dernier_groupage_par_sejour AS (				
					SELECT DISTINCT ON (no_sejour)
						p_sejours_groupes_smr.date_groupage::date
						, t_gmt.oid AS gmt_id
						, t_gmt.code AS gmt_code
						, no_sejour
						, p_sejours_groupes_smr.gme_id
					FROM activite[PX].p_sejours_groupes_smr
 					JOIN base.t_gmt ON p_sejours_groupes_smr.gmt_code = t_gmt.code
					ORDER BY 
						no_sejour
						, date_debut_gmt DESC
				)
				UPDATE activite[PX].p_sejours
					SET 
						date_groupage = dernier_groupage_par_sejour.date_groupage
						, gmt_id = dernier_groupage_par_sejour.gmt_id
						, gme_id = dernier_groupage_par_sejour.gme_id
						, delai_groupage = dernier_groupage_par_sejour.date_groupage - p_sejours.date_sortie
					FROM dernier_groupage_par_sejour
					WHERE dernier_groupage_par_sejour.no_sejour = p_sejours.no_sejour
				;
				
				
				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_IDE_PEC;
				DROP TABLE IF EXISTS w_sejours;
				DROP TABLE IF EXISTS w_IDE_MOUVEMENT_S;
				DROP TABLE IF EXISTS w_sejours_smr_groupes;		
				DROP TABLE IF EXISTS w_codes_pour_sejours_avec_deux_gmt;		
			]]></sqlcmd>
	</NODE>

	<NODE label="Mouvements">
		<sqlcmd><![CDATA[

				-- Recherche UM principale
				DROP TABLE IF EXISTS w_PMS_RUM_principal;
				CREATE TEMP TABLE w_PMS_RUM_principal AS
				SELECT TRUM_ID_SEJO,
					COALESCE(
						(MIN(Array[CASE WHEN TRUM_IND_PRINCIPAL = '1' THEN TRUM_DAT_ENT_RUM ELSE NULL END::text, CASE WHEN TRUM_IND_PRINCIPAL = '1' THEN TRUM_ID_UNME ELSE NULL END::text]))[2],
						(MIN(Array[TRUM_DAT_ENT_RUM::text,TRUM_ID_UNME::text]))[2]
						)::bigint AS TRUM_ID_UNME_principale
				FROM prod_hm.PMS_RUM
				JOIN activite[PX].p_sejours ON p_sejours.code_original = TRUM_ID_SEJO
				GROUP BY 1;

				CREATE INDEX w_PMS_RUM_principal_i1
					ON w_PMS_RUM_principal
					USING btree
					(TRUM_ID_SEJO);

				ANALYSE w_PMS_RUM_principal
				;


				-- Séjours hors PMSi = derniere UM
				INSERT INTO w_PMS_RUM_principal
				SELECT MOUV_ID_SEJO,
					(MAX(Array[MOUV_DAT_MOU::text, UNFO_ID_UNME::text]))[2]::bigint
				FROM prod_hm.IDE_MOUVEMENT
				JOIN activite[PX].p_sejours ON MOUV_ID_SEJO::bigint = p_sejours.code_original
				JOIN prod_hm.BAS_UF ON UNFO_ID_UNFO = MOUV_ID_UNFO
				LEFT JOIN w_PMS_RUM_principal ON TRUM_ID_SEJO = MOUV_ID_SEJO
				WHERE TRUM_ID_SEJO IS NULL
				GROUP BY 1;


				-- Traitement des mouvements
				DROP SEQUENCE IF EXISTS w_IDE_MOUVEMENT_seq;
				CREATE TEMP SEQUENCE w_IDE_MOUVEMENT_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;

				UPDATE prod_hm.IDE_MOUVEMENT
				SET MOUV_DAT_MOU = MOUV_DAT_MOU + '2 second'
				FROM prod_hm.BAS_CATALOGUE_GEN
				WHERE 1=1
					AND MOUV_ID_CAGE = CAGE_ID_CAGE
					AND CAGE_CODE IN ('D','M')
					AND extract('hour' FROM MOUV_DAT_MOU) * 10000 + extract('minute' FROM MOUV_DAT_MOU) * 100 + extract('second' FROM MOUV_DAT_MOU) = 0
					;

				DROP TABLE IF EXISTS w_IDE_MOUVEMENT;

				CREATE TEMP TABLE w_IDE_MOUVEMENT AS
				SELECT nextval('w_IDE_MOUVEMENT_seq'::regclass) AS sequence,
					subview.MOUV_ID_SEJO,
					subview.SEJO_NUM_SEJ,
					subview.SEJO_CODE_CAPE_VEN,
					subview.SEJO_ID_SEJO_MER_ENF,
					subview.MOUV_DAT_MOU,
					date(subview.MOUV_DAT_MOU) AS MOUV_DAT_MOU_DAT,
					extract('hour' FROM MOUV_DAT_MOU) * 10000 + extract('minute' FROM MOUV_DAT_MOU) * 100 + extract('second' FROM MOUV_DAT_MOU)  AS MOUV_DAT_MOU_TIM,
					'2099/12/31'::timestamp without time zone AS MOUV_DAT_FIN,
					date('2099/12/31')::date AS MOUV_DAT_FIN_DAT,
					000000::numeric(6, 0) AS MOUV_DAT_FIN_TIM,
					subview.CAGE_CODE,
					subview.TRUM_ID_UNME_principale,
					subview.MOUV_ID_UNFO,
					subview.MOUV_ID_UNFO_MED,
					CASE
						WHEN subview.MOUV_ID_LIPO = 0 THEN subview.MOUV_ID_UNFO::text || '-0'
						WHEN subview.MOUV_ID_UNFO <> subview.CHAS_ID_UNFO THEN subview.MOUV_ID_UNFO::text || '-0'
						ELSE subview.MOUV_ID_LIPO::text END AS MOUV_ID_LIPO,
					''::character(1) AS CAGE_CODE_before,
					'0'::text AS MOUV_ID_UNFO_before,
					'0'::text AS MOUV_ID_UNFO_MED_before,
					0::text AS MOUV_ID_LIPO_before,
					''::character(1) AS CAGE_CODE_next,
					'0'::text AS MOUV_ID_UNFO_next,
					'0'::text AS MOUV_ID_UNFO_MED_next,
					0::text AS MOUV_ID_LIPO_next

				FROM
				(
				SELECT
					CASE WHEN SEJO_NUM_SEJ IS NULL OR SEJO_NUM_SEJ = '' THEN 'W' || SEJO_ID_SEJO ELSE SEJO_NUM_SEJ END AS SEJO_NUM_SEJ,
					MOUV_ID_SEJO,
					CASE WHEN CAGE_CODE = 'E' THEN SEJO_DAT_DEB WHEN CAGE_CODE = 'S' THEN SEJO_DAT_FIN ELSE MOUV_DAT_MOU END AS MOUV_DAT_MOU,
					CAGE_CODE,
					COALESCE(TRUM_ID_UNME_principale,0) AS TRUM_ID_UNME_principale,
					MOUV_ID_UNFO::text,
					MOUV_ID_UNFO_MED::text,
					MOUV_ID_LIPO,
					COALESCE(CHAS_ID_UNFO,0) AS CHAS_ID_UNFO,
					CAPE_CODE AS SEJO_CODE_CAPE_VEN,
					SEJO_ID_SEJO_MER_ENF
				FROM prod_hm.IDE_MOUVEMENT
					JOIN activite[PX].p_sejours ON MOUV_ID_SEJO::bigint = p_sejours.code_original
					JOIN w_IDE_SEJOUR_complet ON MOUV_ID_SEJO = SEJO_ID_SEJO
					LEFT JOIN prod_hm.PAD_LIT_POSTE ON MOUV_ID_LIPO = LIPO_ID_LIPO
					LEFT JOIN prod_hm.PAD_CHAMBRE_SALLE ON LIPO_ID_CHAS = CHAS_ID_CHAS
					LEFT JOIN w_PMS_RUM_principal ON TRUM_ID_SEJO = MOUV_ID_SEJO
					JOIN prod_hm.BAS_CATALOGUE_GEN ON (MOUV_ID_CAGE = CAGE_ID_CAGE AND CAGE_CODE IN ('E', 'D', 'M', 'S', 'C','P', 'F','T', 'A', 'R'))
					JOIN prod_hm.BAS_CATALOGUE_PERS ON (SEJO_ID_CAPE_VEN = CAPE_ID_CAPE)

				ORDER BY CASE WHEN SEJO_NUM_SEJ IS NULL OR SEJO_NUM_SEJ = '' THEN 'W' || SEJO_ID_SEJO ELSE SEJO_NUM_SEJ END, MOUV_DAT_MOU, CAGE_CODE
				) subview;


				-- calcul date fin

				UPDATE w_IDE_MOUVEMENT
				SET MOUV_DAT_FIN = CASE WHEN w_IDE_MOUVEMENT_next.CAGE_CODE <> 'S' THEN w_IDE_MOUVEMENT_next.MOUV_DAT_MOU - interval '1 second' ELSE w_IDE_MOUVEMENT_next.MOUV_DAT_MOU END,
					MOUV_DAT_FIN_DAT = date(CASE WHEN w_IDE_MOUVEMENT_next.CAGE_CODE <> 'S' THEN w_IDE_MOUVEMENT_next.MOUV_DAT_MOU - interval '1 second' ELSE w_IDE_MOUVEMENT_next.MOUV_DAT_MOU END),
					MOUV_DAT_FIN_TIM = extract('hour' FROM CASE WHEN w_IDE_MOUVEMENT_next.CAGE_CODE <> 'S' THEN w_IDE_MOUVEMENT_next.MOUV_DAT_MOU - interval '1 second' ELSE w_IDE_MOUVEMENT_next.MOUV_DAT_MOU END) * 10000 +
							extract('minute' FROM CASE WHEN w_IDE_MOUVEMENT_next.CAGE_CODE <> 'S' THEN w_IDE_MOUVEMENT_next.MOUV_DAT_MOU - interval '1 second' ELSE w_IDE_MOUVEMENT_next.MOUV_DAT_MOU END) * 100 +
							extract('second' FROM CASE WHEN w_IDE_MOUVEMENT_next.CAGE_CODE <> 'S' THEN w_IDE_MOUVEMENT_next.MOUV_DAT_MOU - interval '1 second' ELSE w_IDE_MOUVEMENT_next.MOUV_DAT_MOU END),
					CAGE_CODE_next = w_IDE_MOUVEMENT_next.CAGE_CODE,
					MOUV_ID_UNFO_next = w_IDE_MOUVEMENT_next.MOUV_ID_UNFO,
					MOUV_ID_UNFO_MED_next = w_IDE_MOUVEMENT_next.MOUV_ID_UNFO_MED,
					MOUV_ID_LIPO_next = w_IDE_MOUVEMENT_next.MOUV_ID_LIPO
				FROM w_IDE_MOUVEMENT w_IDE_MOUVEMENT_next
				WHERE w_IDE_MOUVEMENT.SEJO_NUM_SEJ = w_IDE_MOUVEMENT_next.SEJO_NUM_SEJ
					AND w_IDE_MOUVEMENT.sequence = w_IDE_MOUVEMENT_next.sequence - 1;


				-- Si hopital de jour sans journée,
				UPDATE w_IDE_MOUVEMENT
				SET CAGE_CODE_next = 'C'
				FROM activite[PX].p_sejours,
					activite[PX].t_services_facturation
					JOIN base.t_modes_traitement on t_services_facturation.mode_traitement_id = t_modes_traitement.oid
				WHERE MOUV_ID_SEJO::bigint = p_sejours.code_original AND
					code_prevu <> '1' AND
					CAGE_CODE = 'E' AND
					MOUV_ID_UNFO_MED = t_services_facturation.code_original AND
					(CAGE_CODE_NEXT = '' OR CAGE_CODE_NEXT = 'S' AND date_entree <> date_sortie) AND
					t_modes_traitement.code = '04' AND
					t_services_facturation.type_t2a = '2';




				-- calcul mvt avant

				UPDATE w_IDE_MOUVEMENT
				SET
					CAGE_CODE_before = w_IDE_MOUVEMENT_before.CAGE_CODE,
					MOUV_ID_UNFO_before = w_IDE_MOUVEMENT_before.MOUV_ID_UNFO,
					MOUV_ID_UNFO_MED_before = w_IDE_MOUVEMENT_before.MOUV_ID_UNFO_MED,
					MOUV_ID_LIPO_before = w_IDE_MOUVEMENT_before.MOUV_ID_LIPO
				FROM w_IDE_MOUVEMENT w_IDE_MOUVEMENT_before
				WHERE w_IDE_MOUVEMENT.SEJO_NUM_SEJ = w_IDE_MOUVEMENT_before.SEJO_NUM_SEJ
					AND w_IDE_MOUVEMENT.sequence = w_IDE_MOUVEMENT_before.sequence + 1
					AND w_IDE_MOUVEMENT.CAGE_CODE <> 'S';

				-- Absences
				UPDATE w_IDE_MOUVEMENT
				SET MOUV_ID_UNFO_MED = '*ABS'
				WHERE CAGE_CODE = 'A';

				-- Hopital de jour Dernière séance avant dans sortie
				UPDATE w_IDE_MOUVEMENT SET
					MOUV_DAT_MOU = MOUV_DAT_FIN,
					MOUV_DAT_MOU_DAT = MOUV_DAT_FIN_DAT,
					MOUV_DAT_MOU_TIM = MOUV_DAT_FIN_TIM
				WHERE CAGE_CODE = 'P' AND CAGE_CODE_next = 'S' AND
					MOUV_DAT_FIN <> MOUV_DAT_MOU;

				-- Hopital de jour Première séance après date entree
				UPDATE w_IDE_MOUVEMENT SET
					MOUV_DAT_FIN = MOUV_DAT_MOU,
					MOUV_DAT_FIN_DAT = MOUV_DAT_MOU_DAT,
					MOUV_DAT_FIN_TIM = MOUV_DAT_MOU_TIM
				WHERE CAGE_CODE = 'E' AND CAGE_CODE_next = 'C' AND
					MOUV_DAT_MOU <> MOUV_DAT_FIN;


				-- creation mouvements par jour

				DROP TABLE IF EXISTS w_mouvements_sejour;
				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT
					w_IDE_MOUVEMENT.MOUV_ID_SEJO,
					w_IDE_MOUVEMENT.SEJO_NUM_SEJ AS no_sejour,
					p_sejours.oid AS sejour_id,
					sequence,
					p_calendrier.date,
					p_calendrier.jour_semaine,
					p_calendrier.is_weekend,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT THEN MOUV_DAT_MOU_TIM ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date = MOUV_DAT_FIN_DAT THEN MOUV_DAT_FIN_TIM ELSE 240000 END AS heure_fin,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN p_calendrier.date = MOUV_DAT_FIN_DAT AND CAGE_CODE_next = 'S' AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN p_calendrier.date = MOUV_DAT_FIN_DAT AND CAGE_CODE_next = 'S' AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
					CASE WHEN p_sejours.type_sejour = '1' AND CAGE_CODE_next <> 'C' AND CAGE_CODE <> 'P' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND p_sejours.type_sejour <> '9' AND t_dmt.code IN ('303', '307', '308', '401', '402', '403', '404', '405', '406', '407', '408', '409') THEN 1 ELSE 0 END AS nb_urgences,
					0 as nb_seances,

					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE IN ('D', 'M') AND p_sejours.type_sejour = '1' AND mouv_id_unfo_med <> mouv_id_unfo_med_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = MOUV_DAT_FIN_DAT AND CAGE_CODE_next IN ('D', 'M') AND p_sejours.type_sejour = '1' AND mouv_id_unfo_med <> mouv_id_unfo_med_next THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE IN ('D', 'M') AND p_sejours.type_sejour = '1' AND mouv_id_unfo <> mouv_id_unfo_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = MOUV_DAT_FIN_DAT AND CAGE_CODE_next IN ('D', 'M') AND p_sejours.type_sejour = '1' AND mouv_id_unfo <> mouv_id_unfo_next THEN 1 ELSE 0 END AS nb_sorties_mutation_etage,
					0 AS nb_entrees_mutation_activite,
					0 AS nb_sorties_mutation_activite,
					0 AS nb_entrees_mutation_unite_medicale,
					0 AS nb_sorties_mutation_unite_medicale,

					CASE WHEN p_sejours.type_sejour = '1' AND CAGE_CODE_next <> 'C' AND CAGE_CODE <> 'P' AND (p_calendrier.date <> MOUV_DAT_FIN_DAT OR CAGE_CODE_next = 'S') THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND CAGE_CODE_next <> 'C' AND CAGE_CODE <> 'P' AND p_calendrier.date <> MOUV_DAT_FIN_DAT THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE WHEN p_sejours.type_sejour = '1' AND CAGE_CODE_next <> 'C' AND CAGE_CODE <> 'P' AND t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN p_sejours.type_sejour = '1' AND CAGE_CODE_next <> 'C' AND CAGE_CODE <> 'P' AND t_lits.chambre_particuliere = 'O' AND (p_calendrier.date <> MOUV_DAT_FIN_DAT OR CAGE_CODE_next = 'S') THEN 1 ELSE 0 END AS nb_chambres_particulieres,

					CASE WHEN p_calendrier.date = MOUV_DAT_MOU_DAT AND CAGE_CODE = 'E' AND (p_sejours.type_sejour = '6' OR COALESCE(w_IDE_MOUVEMENT.SEJO_ID_SEJO_MER_ENF) > 0) THEN 1 ELSE 0 END AS nb_bebes,

					TRUM_ID_UNME_principale,
					MOUV_ID_UNFO_MED,
					MOUV_ID_LIPO,

					COALESCE(t_lieux.oid,0) AS lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id,

					CASE WHEN p_sejours.code_prevu = '1' OR p_calendrier.date > date(date_extraction) THEN '1' ELSE '0' END AS est_mouvement_previsionnel,

					''::text AS est_premier_mouvement_jour,
					''::text AS est_dernier_mouvement_jour


				FROM w_IDE_MOUVEMENT
					LEFT JOIN activite[PX].t_lieux ON
						(t_lieux.code_original_1 = MOUV_ID_UNFO_MED::text AND
						t_lieux.code_original_2 = TRUM_ID_UNME_principale AND
						t_lieux.code_original_4 = MOUV_ID_LIPO AND
						t_lieux.code_original_6 = MOUV_ID_UNFO_MED::text  )
					JOIN w_IDE_SEJOUR_complet ON SEJO_ID_SEJO = MOUV_ID_SEJO
					JOIN activite[PX].p_sejours ON w_IDE_MOUVEMENT.SEJO_NUM_SEJ = p_sejours.no_sejour AND p_sejours.etat = ''
					JOIN activite[PX].t_lits ON MOUV_ID_LIPO = t_lits.code_original
					JOIN activite[PX].t_services_facturation ON MOUV_ID_UNFO_MED::text = t_services_facturation.code_original
					JOIN base.t_dmt ON t_services_facturation.dmt_id = t_dmt.oid
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN MOUV_DAT_MOU_DAT AND MOUV_DAT_FIN_DAT AND p_calendrier.date <= date(date_extraction) + interval '1 month'
				WHERE CAGE_CODE <> 'S' AND
					(CAGE_CODE <> 'P' OR CAGE_CODE_next = 'S') AND
					(p_sejours.type_sejour NOT IN ('3') OR (p_sejours.type_sejour IN ('3') AND CAGE_CODE = 'E' AND p_calendrier.date = MOUV_DAT_MOU_DAT)) AND
					(p_sejours.code_prevu <> '1' AND p_calendrier.date <= date(date_extraction) OR p_calendrier.date >= date(date_extraction))
				ORDER BY sequence, p_calendrier.date;


				DELETE FROM w_mouvements_sejour WHERE heure_fin < heure_debut;



				-- Actualisation lieux
				UPDATE activite[PX].t_lieux SET
					service_facturation_id = t_services_facturation.oid,
					mode_traitement_id = t_services_facturation.mode_traitement_id
				FROM activite[PX].t_services_facturation
				WHERE
					code_original_1 = t_services_facturation.code_original;

				UPDATE activite[PX].t_lieux SET
					activite_id = t_activites.oid
				FROM activite[PX].t_activites
				WHERE
					code_original_2 = t_activites.code_original;

				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				FROM activite[PX].t_unites_fonctionnelles
				WHERE
					code_original_6 = t_unites_fonctionnelles.code_original;

				UPDATE activite[PX].t_lieux SET
					lit_id = t_lits.oid
				FROM activite[PX].t_lits
				WHERE
					code_original_4 = t_lits.code_original;



				-- creation nouveaux lieux

				INSERT INTO activite[PX].t_lieux(
					code_original_1,
					code_original_2,
					code_original_3,
					code_original_4,
					code_original_5,
					code_original_6,
					code_original_7,
					service_facturation_id,
					activite_id,
					lit_id,
					unite_medicale_id,
					unite_fonctionnelle_id,
					mode_traitement_id)
				SELECT DISTINCT
					MOUV_ID_UNFO_MED,
					TRUM_ID_UNME_principale,
					'',
					MOUV_ID_LIPO,
					'',
					MOUV_ID_UNFO_MED,
					'',
					t_services_facturation.oid,
					COALESCE(t_activites.oid,0),
					t_lits.oid,
					0,
					t_unites_fonctionnelles.oid,
					t_services_facturation.mode_traitement_id
				FROM w_mouvements_sejour
					LEFT JOIN activite[PX].t_lieux ON
						(t_lieux.code_original_1 = MOUV_ID_UNFO_MED::text AND
						t_lieux.code_original_2 = TRUM_ID_UNME_principale::bigint AND
						t_lieux.code_original_4 = MOUV_ID_LIPO AND
						t_lieux.code_original_6 = MOUV_ID_UNFO_MED::text  )
					JOIN activite[PX].t_services_facturation ON MOUV_ID_UNFO_MED::text = t_services_facturation.code_original
					LEFT JOIN activite[PX].t_activites ON TRUM_ID_UNME_principale::bigint = t_activites.code_original
					JOIN activite[PX].t_lits ON MOUV_ID_LIPO = t_lits.code_original
					JOIN activite[PX].t_unites_fonctionnelles ON MOUV_ID_UNFO_MED::text = t_unites_fonctionnelles.code_original
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13;




				-- Mise à jour lieux dans futurs mouvements
				UPDATE w_mouvements_sejour SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE t_lieux.code_original_1 = MOUV_ID_UNFO_MED::text
					AND t_lieux.code_original_2 = TRUM_ID_UNME_principale::bigint
					AND t_lieux.code_original_4 = MOUV_ID_LIPO
					AND t_lieux.code_original_6 = MOUV_ID_UNFO_MED::text
					AND w_mouvements_sejour.lieu_id = 0;



				-- Médecin séjour (fonctionnalitée non supportée pour le moment)

				--UPDATE w_mouvements_sejour SET medecin_sejour_id = t_medecins_administratifs.oid
				--FROM prod_hm.IDE_MED_VENUE, prod_hm.BAS_CATALOGUE_PERS, activite[PX].t_medecins_administratifs
				--WHERE MOUV_ID_SEJO = MESE_ID_SEJO
					--AND MESE_ID_CAPE = CAPE_ID_CAPE
					--AND MESE_ID_MEDE::bigint = t_medecins_administratifs.code_original
					--AND date BETWEEN date(MESE_DAT_DEB) AND date(MESE_DAT_FIN)
					--AND CAPE_CODE IN ('1')
					--AND w_mouvements_sejour.medecin_sejour_id <> t_medecins_administratifs.oid
					--AND t_medecins_administratifs.oid <> 0;


				-- Unité médicale selon UF
				UPDATE activite[PX].t_lieux
				SET unite_medicale_id = t_unites_medicales.oid,
					code_original_5 = UNFO_ID_UNME
				FROM prod_hm.BAS_UF
					JOIN prod_hm.SAD_UM ON UNFO_ID_UNME = UNME_ID_UNME
					JOIN activite[PX].t_unites_medicales ON UNME_ID_UNME =t_unites_medicales.code_original
				WHERE UNFO_ID_UNFO = code_original_6 AND
					(unite_medicale_id IS DISTINCT FROM t_unites_medicales.oid OR
					code_original_5 IS DISTINCT FROM UNFO_ID_UNME);

				UPDATE activite[PX].t_lieux
				SET unite_medicale_id = t_unites_medicales.oid,
					code_original_5 = '*ABS'
				FROM activite[PX].t_unites_medicales
				WHERE code_original_6 = '*ABS' AND t_unites_medicales.code_original = '*ABS';

				-- Unité médicale principale selon UF
				UPDATE activite[PX].t_lieux SET
					activite_id = t_activites.oid,
					code_original_2 = UNFO_ID_UNME
				FROM prod_hm.BAS_UF
					JOIN prod_hm.SAD_UM ON UNFO_ID_UNME = UNME_ID_UNME
					JOIN activite[PX].t_activites ON UNME_ID_UNME = t_activites.code_original
				WHERE UNFO_ID_UNFO = code_original_6 AND
					activite_id = 0;


				-- Prise en compte mutations ambulatoire
                INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'MUTATIONAMBU',
					'Traitement des mutations / ambulatoire',
					'0',
					'0=Prendre en compte mouvement d''entrée, 1=Prendre en compte mouvement de sortie'
				WHERE 'MUTATIONAMBU' NOT IN (SELECT code FROM activite.t_divers);
                ;

                DROP TABLE IF EXISTS w_correction_ambu;
                CREATE TEMP TABLE  w_correction_ambu AS
                SELECT p_mouvements_sejour.no_sejour,
                    (MAX(Array[to_char(heure_debut,'FM000000'),lieu_id::text]))[2]::bigint AS lieu_id,
                    MIN(heure_entree) AS heure_entree,
                    MAX(heure_sortie) AS heure_sortie
                FROM w_mouvements_sejour p_mouvements_sejour
                JOIN activite[PX].p_sejours ON p_mouvements_sejour.no_sejour = p_sejours.no_sejour
                JOIN activite.t_divers ON t_divers.code = 'MUTATIONAMBU' ANd t_divers.valeur = '1'
                WHERE type_sejour = '2' AND code_sorti = '1' AND date_sortie = date_entree
                GROUP BY 1
                HAVING count(*) > 1 AND count(DISTINCT date) = 1
                ;

                DELETE FROM w_mouvements_sejour p_mouvements_sejour
                WHERE nb_ambulatoires = '0' AND
                    no_sejour IN (SELECT no_sejour FROM w_correction_ambu)
                ;

                UPDATE w_mouvements_sejour p_mouvements_sejour
                SET lieu_id = w_correction_ambu.lieu_id,
                    heure_debut = heure_entree,
                    heure_fin = heure_sortie
                FROM w_correction_ambu
                WHERE p_mouvements_sejour.no_sejour = w_correction_ambu.no_sejour AND
                    p_mouvements_sejour.nb_ambulatoires = '1'
                    ;


				-- Seances selon GHS pmsi
				DROP TABLE IF EXISTS w_ghs_seances;
				CREATE TEMP TABLE w_ghs_seances AS
				SELECT ghs_id AS oid
				FROM activite[PX].p_sejours
				JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid AND t_ghm.code LIKE '28%'
				JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid AND t_ghs.code <> 9999 AND t_ghs.code > 0
				WHERE ghs_id <> 0
				GROUP BY 1;

				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date_entree AS date,
					1 AS nb_seances
				FROM activite[PX].p_sejours
					JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
					JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
				WHERE date_entree = date_sortie AND
					(ghs_id IN (SELECT oid FROM w_ghs_seances) OR t_ghm.code LIKE '28%');

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);

				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;



				-- seances selon GHS facturé
				DROP TABLE IF EXISTS w_FAC_LIGNE_FACTURE_seances;
				CREATE TEMP TABLE  w_FAC_LIGNE_FACTURE_seances AS
				SELECT
					p_sejours.no_sejour,
					date(LFAC_DAT_EXE_DEB) AS date,
					SUM(LFAC_QTE_COEFFICIENT) AS nb_seances
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT AND FACT_TYPE <> 'P' AND FACT_TYPE <> 'E' AND FACT_DAT_SUP IS NULL
					JOIN activite[PX].p_sejours ON LFAC_ID_SEJO_D::bigint = p_sejours.code_original
					JOIN base.t_ghs ON to_number('0' || LFAC_NUM_GHS,'00000') = t_ghs.code
				WHERE LFAC_LET_CLE = 'GHS' AND LFAC_ID_PRSE <> 0 AND
					t_ghs.oid IN (SELECT oid FROM w_ghs_seances)
				GROUP BY 1,2
				HAVING SUM(LFAC_QTE_COEFFICIENT) > 0;

				CREATE INDEX  w_FAC_LIGNE_FACTURE_seances_i1
				  ON  w_FAC_LIGNE_FACTURE_seances
				  USING btree
				  (no_sejour);

				UPDATE w_mouvements_sejour
				SET nb_seances = w_FAC_LIGNE_FACTURE_seances.nb_seances
				FROM w_FAC_LIGNE_FACTURE_seances
				WHERE w_FAC_LIGNE_FACTURE_seances.no_sejour = w_mouvements_sejour.no_sejour AND
					w_FAC_LIGNE_FACTURE_seances.date = w_mouvements_sejour.date;




				-- seances selon D09, D11 facturé
				DROP TABLE IF EXISTS w_FAC_LIGNE_FACTURE_seances;
				CREATE TEMP TABLE  w_FAC_LIGNE_FACTURE_seances AS
				SELECT
					p_sejours.no_sejour,
					date(LFAC_DAT_EXE_DEB) AS date,
					SUM(LFAC_QTE_COEFFICIENT) AS nb_seances
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT AND FACT_TYPE <> 'P' AND FACT_TYPE <> 'E' AND FACT_DAT_SUP IS NULL
					JOIN activite[PX].p_sejours ON LFAC_ID_SEJO_D::bigint = p_sejours.code_original
				WHERE LFAC_LET_CLE IN ('D09', 'D11') AND LFAC_ID_PRSE <> 0
				GROUP BY 1,2
				HAVING SUM(LFAC_QTE_COEFFICIENT) > 0;

				CREATE INDEX  w_FAC_LIGNE_FACTURE_seances_i1
				  ON  w_FAC_LIGNE_FACTURE_seances
				  USING btree
				  (no_sejour);

				UPDATE w_mouvements_sejour
				SET nb_seances = w_FAC_LIGNE_FACTURE_seances.nb_seances
				FROM w_FAC_LIGNE_FACTURE_seances
				WHERE w_FAC_LIGNE_FACTURE_seances.no_sejour = w_mouvements_sejour.no_sejour AND
					w_FAC_LIGNE_FACTURE_seances.date = w_mouvements_sejour.date;


				-- seances selon Actes
				DROP TABLE IF EXISTS w_SAD_ACTIVITE_SAISIES_seances;
				CREATE TEMP TABLE  w_SAD_ACTIVITE_SAISIES_seances AS
				SELECT
					p_sejours.no_sejour,
					date(ACSA_DAT_EXE_DEB) AS date,
					1 AS nb_seances
				FROM prod_hm.SAD_ACTIVITE_SAISIES
					JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original
				WHERE
					ACSA_LET_CLE = 'K' AND
					ACSA_QTE_COEFFICIENT =	(SELECT
									ACSA_QTE_COEFFICIENT
								FROM prod_hm.SAD_ACTIVITE_SAISIES
									JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original
									JOIN w_FAC_LIGNE_FACTURE_seances ON p_sejours.no_sejour = w_FAC_LIGNE_FACTURE_seances.no_sejour AND w_FAC_LIGNE_FACTURE_seances.date = date(ACSA_DAT_EXE_DEB)
								WHERE ACSA_LET_CLE = 'K'
								GROUP BY 1
								ORDER BY 1
								LIMIT 1)
				GROUP BY 1,2;

				UPDATE w_mouvements_sejour
				SET nb_seances = w_SAD_ACTIVITE_SAISIES_seances.nb_seances
				FROM w_SAD_ACTIVITE_SAISIES_seances
				WHERE w_SAD_ACTIVITE_SAISIES_seances.no_sejour = w_mouvements_sejour.no_sejour AND
					w_SAD_ACTIVITE_SAISIES_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances = 0;

			-- Séances d'après acte PMSI (ESPIC)
				SELECT base.cti_execute('DROP TABLE IF EXISTS w_PMSI_seances',1)
				WHERE 'p_rss_actes' IN (
					SELECT table_name 
					FROM information_schema.tables
					WHERE table_schema = 'pmsi'
				)
				;

				SELECT base.cti_execute('CREATE TEMP TABLE w_PMSI_seances AS
					SELECT
						p_sejours.no_sejour,
						date(p_rss_actes.date_acte) AS date,
						1 AS nb_seances
					FROM pmsi.p_rss_actes
					JOIN pmsi.t_actes ON acte_id = t_actes.oid
					JOIN pmsi.p_rss ON rss_id = p_rss.oid
					JOIN activite[PX].p_sejours ON p_sejours.no_sejour = p_rss.no_sejour_administratif
					WHERE p_sejours.date_sortie > p_sejours.date_entree 
						AND est_budget_global = ''1''
						AND t_actes.code IN (''ZZLF900'',''JVJF004'')
					GROUP BY 
						p_sejours.no_sejour,
						date(p_rss_actes.date_acte)'
				,1)
				WHERE 'p_rss_actes' IN (
					SELECT table_name 
					FROM information_schema.tables
					WHERE table_schema = 'pmsi'
				)
				;

				SELECT base.cti_execute('ANALYSE w_PMSI_seances',1)
				WHERE 'p_rss_actes' IN (
					SELECT table_name 
					FROM information_schema.tables
					WHERE table_schema = 'pmsi'
				)
				;

				SELECT base.cti_execute('UPDATE w_mouvements_sejour
					SET nb_seances = w_PMSI_seances.nb_seances
					FROM w_PMSI_seances
					WHERE w_PMSI_seances.no_sejour = w_mouvements_sejour.no_sejour 
						AND w_PMSI_seances.date = w_mouvements_sejour.date 
						AND w_mouvements_sejour.nb_seances = 0'
				,1)
				WHERE 'p_rss_actes' IN (
					SELECT table_name 
					FROM information_schema.tables 
					WHERE table_schema = 'pmsi'
				)
				;

				-- seances selon D09
				DROP TABLE IF EXISTS w_SAD_ACTIVITE_SAISIES_seances;
				CREATE TEMP TABLE  w_SAD_ACTIVITE_SAISIES_seances AS
				SELECT
					p_sejours.no_sejour,
					date(ACSA_DAT_EXE_DEB) AS date,
					COUNT(*) AS nb_seances
				FROM prod_hm.SAD_ACTIVITE_SAISIES
					JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original
				WHERE
					ACSA_LET_CLE IN ('D09', 'D11')
				GROUP BY 1,2;

				UPDATE w_mouvements_sejour
				SET nb_seances = w_SAD_ACTIVITE_SAISIES_seances.nb_seances
				FROM w_SAD_ACTIVITE_SAISIES_seances
				WHERE w_SAD_ACTIVITE_SAISIES_seances.no_sejour = w_mouvements_sejour.no_sejour AND
					w_SAD_ACTIVITE_SAISIES_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances = 0;



				-- Seances selon type sejour DE = DS
				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM activite[PX].p_sejours
				WHERE p_sejours.no_sejour = w_mouvements_sejour.no_sejour AND
					p_sejours.type_sejour = '5' AND
					p_sejours.date_entree = p_sejours.date_sortie AND
					p_sejours.date_entree = w_mouvements_sejour.date AND
					w_mouvements_sejour.heure_debut > 0 AND
					w_mouvements_sejour.nb_seances = 0 AND
					w_mouvements_sejour.no_sejour NOT IN (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0);

				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM activite[PX].p_sejours
				JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid AND t_ghm.code LIKE '28%'
				WHERE p_sejours.no_sejour = w_mouvements_sejour.no_sejour AND
					p_sejours.type_sejour = '5' AND
					p_sejours.date_entree = w_mouvements_sejour.date AND
					w_mouvements_sejour.heure_debut > 0 AND
					w_mouvements_sejour.nb_seances = 0 AND
					w_mouvements_sejour.no_sejour NOT IN (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0)
				;

				-- plusieurs séances le même jour

				DROP TABLE IF EXISTS w_seances;
				CREATE TEMP TABLE w_seances as
				SELECT no_sejour, date, MAX(heure_debut) AS heure_debut
				FROM w_mouvements_sejour
				WHERE nb_seances > 0
				GROUP BY 1,2
				HAVING count(DISTINCT heure_debut) > 1;


				UPDATE w_mouvements_sejour
				SET nb_seances = 0
				FROM w_seances
				WHERE w_mouvements_sejour.no_sejour = w_seances.no_sejour and
					w_mouvements_sejour.date = w_seances.date and
					w_mouvements_sejour.heure_debut <> w_seances.heure_debut;

				-- Lignes inutiles
				DELETE FROM w_mouvements_sejour
				WHERE
					nb_entrees_directes = 0 AND
					nb_sorties_directes = 0 AND
					est_jour_hospitalisation <> '1' AND
					nb_ambulatoires = 0 AND
					nb_externes = 0 AND
					nb_urgences = 0 AND
					nb_seances = 0 AND
					nb_entrees_mutation_service = 0 AND
					nb_sorties_mutation_service = 0 AND
					nb_entrees_mutation_etage = 0 AND
					nb_sorties_mutation_etage = 0 AND
					nb_entrees_mutation_activite = 0 AND
					nb_sorties_mutation_activite = 0 AND
					nb_entrees_mutation_unite_medicale = 0 AND
					nb_sorties_mutation_unite_medicale = 0 AND
					nb_jours_js_inclus = 0 AND
					nb_jours_js_non_inclus = 0 AND
					est_chambre_particuliere <> '1' AND
					nb_chambres_particulieres = 0 AND
					nb_bebes = 0
				;


				-- Doublons potentiels
				DELETE FROM w_mouvements_sejour
				USING (
				SELECT
					no_sejour, date, heure_debut, MIN(CTID) AS keepCTID
				FROM w_mouvements_sejour
                WHERE heure_fin >= heure_debut
				GROUP BY 1,2,3
				HAVING count(*) > 1) subview
				WHERE w_mouvements_sejour.no_sejour = subview.no_sejour AND
					w_mouvements_sejour.date = subview.date AND
					w_mouvements_sejour.heure_debut = subview.heure_debut AND
					subview.keepCTID <> w_mouvements_sejour.CTID;




				-- Mise en production des mouvements
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_5');

				INSERT INTO activite[PX].p_mouvements_sejour(
							sejour_id, no_sejour, date, est_mouvement_previsionnel, nb_jours_js_non_inclus,
							lieu_id, nb_entrees_directes, nb_sorties_directes,
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id,
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service,
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite,
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres,
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation,
							est_chambre_particuliere,
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend)
				SELECT sejour_id, no_sejour, date, est_mouvement_previsionnel ,nb_jours_js_non_inclus,
							lieu_id, nb_entrees_directes, nb_sorties_directes,
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id,
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service,
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite,
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres,
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation,
							est_chambre_particuliere,
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend
				FROM w_mouvements_sejour
				WHERE heure_fin >= heure_debut
				ORDER BY no_sejour, sequence;

				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_5');

				-- Lieux de sortie

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id
					FROM activite[PX].p_mouvements_sejour
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour
						AND p_mouvements_sejour.date = p_sejours.date_sortie
						AND (lieu_sortie_id <> p_mouvements_sejour.lieu_id OR lieu_sortie_id IS NULL);

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id
					FROM activite[PX].p_mouvements_sejour
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour
						AND p_mouvements_sejour.date = p_sejours.date_sortie  AND p_mouvements_sejour.nb_sorties_directes = 1
						AND (lieu_sortie_id <> p_mouvements_sejour.lieu_id OR lieu_sortie_id IS NULL);

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id
					FROM activite[PX].p_mouvements_sejour
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour
						AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL) ;

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE lieu_sortie_id IS NULL ;


				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE p_sejours.code_prevu = '1' AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL);


				UPDATE activite[PX].p_sejours
				SET code_sorti = '1'
				FROM activite[PX].p_mouvements_sejour
				WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
					code_sorti = '0' AND
					(nb_ambulatoires > 0 OR nb_externes > 0) AND
					date_sortie <= now();

				UPDATE activite[PX].p_sejours
				SET type_sejour = '5'
				WHERE type_sejour <> '5' AND
					type_sejour <> '1' AND
					type_sejour <> '9' AND
					no_sejour IN (
						SELECT no_sejour
						FROM activite[PX].p_mouvements_sejour
						WHERE nb_seances > 0);


				UPDATE activite[PX].p_mouvements_sejour
				SET nb_externes = 0, nb_ambulatoires = 0
				FROM activite[PX].p_sejours
				WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour AND
					p_sejours.type_sejour = '5' AND
					(
						nb_externes <> 0 OR
						nb_ambulatoires <> 0
					);



				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_IDE_MOUVEMENT;
				DROP TABLE IF EXISTS w_mouvements_sejour;
				DROP TABLE IF EXISTS w_seances;
				DROP TABLE IF EXISTS w_SAD_ACTIVITE_SAISIES_seances;
				DROP TABLE IF EXISTS w_FAC_LIGNE_FACTURE_seances;


			]]></sqlcmd>
	</NODE>

</NODE>

<NODE name="FACTURE" label="RECUPERATION DES FACTURES">

	<NODE label="Entêtes">

		<sqlcmd><![CDATA[


				DROP TABLE IF EXISTS w_sejours_orga CASCADE
				;
				CREATE TEMP TABLE w_sejours_orga AS
				SELECT
					no_sejour
					,p_sejours.oid AS sejour_id
					,p_sejours.code_original
					,p_sejours.date_sortie
					,p_sejours.ghs_id
					,p_sejours.lieu_sortie_id
					,p_sejours.tiers_payant_0_id
					,p_sejours.tiers_payant_1_id
					,p_sejours.tiers_payant_2_id
					,p_sejours.tiers_payant_22_id
					,t_tiers_payant_1.code_original as tiers_payant_1_orga_id
					,t_tiers_payant_2.code_original as tiers_payant_2_orga_id
					,t_tiers_payant_22.code_original as tiers_payant_22_orga_id
				FROM activite[PX].p_sejours
					JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON tiers_payant_1_id = t_tiers_payant_1.oid
					JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON tiers_payant_2_id = t_tiers_payant_2.oid
					JOIN activite[PX].t_tiers_payant t_tiers_payant_22 ON tiers_payant_22_id = t_tiers_payant_22.oid
				WHERE p_sejours.etat = ''
				;


				CREATE INDEX w_sejours_orga_i1
				ON w_sejours_orga
				USING btree
				(code_original)
				;



				-- factures à traiter

                -- Identification des factures qui sont comptabilisées en honoraires (pour les PSPH multi type Jules Vernes)
                DROP TABLE IF EXISTS w_FACTURE_HON;
				CREATE TEMP TABLE w_FACTURE_HON AS
				SELECT
					FACD_ID_FACT AS FACT_ID_FACT_HON
				FROM prod_hm.CCL_LIGNE_ECRITURE
					JOIN prod_hm.CCL_ECRITURE ON LECR_ID_ECRI = ECRI_ID_ECRI
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LECR_ID_FACD = FACD_ID_FACD
					JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
				WHERE ECRI_DAT_SUP IS NULL AND
					JOUR_ISJVT = '1' AND
					LECR_PART = 'HON'
				GROUP BY 1
				;


				DROP TABLE IF EXISTS w_FAC_FACTURE;
				CREATE TEMP TABLE w_FAC_FACTURE AS
				SELECT FAC_FACTURE.*,
					w_sejours_orga.*,
					ETAB_TYP_ETAB,
					CASE
                        WHEN FACT_ID_FACT IN (SELECT FACT_ID_FACT_HON FROM w_FACTURE_HON) THEN '0'::text
                        WHEN SEJO_IND_BGH IS NOT DISTINCT FROM '1' OR ETAB_TYP_ETAB = 'PSPH' THEN '1'::text
                        ELSE '0'::text END AS CRN_HON_TO_SEJ,
					'1'::text AS FAC_HON,
					0::bigint AS FACT_ID_FACT_SEJ,
					''::text AS FACT_NUM_FAC_SEJ,
					SEJO_IND_BGH
				FROM prod_hm.FAC_FACTURE
					JOIN w_IDE_SEJOUR_complet ON FACT_ID_SEJO = SEJO_ID_SEJO
					JOIN prod_hm.BAS_ETABLISSEMENT ON SEJO_ID_ETAB_CON = ETAB_ID_ETAB
					JOIN w_sejours_orga ON (FACT_ID_SEJO::bigint = w_sejours_orga.code_original)
				WHERE FACT_TYPE <> 'E' AND
					(FACT_TYPE = 'P' OR FACT_DAT_SUP IS NULL);


				CREATE INDEX w_FAC_FACTURE_i1
				ON w_FAC_FACTURE
				USING btree
				(FACT_ID_FACT);

				-- En budget global, tous les honoraires ne sont pas facturés (inclus dans GHS)

				-- Honoraires comptabilisés -> Donc pas inclus
				DROP TABLE IF EXISTS w_FAC_LIGNE_FACTURE_DEBITEUR_noninclus;
				CREATE TEMP TABLE w_FAC_LIGNE_FACTURE_DEBITEUR_noninclus AS
				SELECT LFAC_ID_FACT AS LFAC_ID_FACT_noninclus
				FROM prod_hm.FAC_LIGNE_FACTURE_DEBITEUR
				JOIN prod_hm.FAC_LIGNE_FACTURE ON LFAC_ID_LFAC = LFAD_ID_LFAC
				WHERE '[ENV_TYPEETS]' IN ('2','3') AND
					LFAC_ID_PRHO <> 0 AND LFAD_MTT_CRN <> 0
				GROUP BY 1
				;

				UPDATE w_FAC_FACTURE SET
					FAC_HON = '0',
					FACT_ID_FACT_SEJ = FACT_ID_FACT,
					FACT_NUM_FAC_SEJ = FACT_NUM_FAC
				FROM prod_hm.FAC_LIGNE_FACTURE
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					FACT_ID_FACT = LFAC_ID_FACT AND
					CRN_HON_TO_SEJ = '1' AND
					(
						LFAC_LET_CLE IN ('GHS', 'PJ', 'AMP5', 'AMD', 'AMF', 'IPD') OR
						LFAC_ID_PRSE::bigint IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE actes_inclus_public = '1')
					);



				UPDATE w_FAC_FACTURE SET
					FAC_HON = '0',
					FACT_ID_FACT_SEJ = FAC_FACTURE.FACT_ID_FACT,
					FACT_NUM_FAC_SEJ = FAC_FACTURE.FACT_NUM_FAC
				FROM prod_hm.FAC_LIGNE_FACTURE
				JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					w_FAC_FACTURE.FACT_ID_SEJO = FAC_FACTURE.FACT_ID_SEJO AND
					CRN_HON_TO_SEJ = '1' AND
					(
						LFAC_LET_CLE IN ('GHS', 'PJ', 'AMP5', 'AMD', 'AMF', 'IPD') OR
						LFAC_ID_PRSE::bigint IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE actes_inclus_public = '1')
					) AND
					FAC_FACTURE.FACT_TYPE <> 'P'  AND
					FAC_FACTURE.FACT_TYPE <> 'E' AND
					FAC_FACTURE.FACT_DAT_SUP IS NULL AND
					FAC_HON = '1' AND
					LFAC_ID_FACT NOT IN (SELECT LFAC_ID_FACT_noninclus FROM w_FAC_LIGNE_FACTURE_DEBITEUR_noninclus)
				;


				-- Informations montants factures et regles

				DROP TABLE IF EXISTS w_FAC_MONTANTS;
				CREATE TEMP TABLE w_FAC_MONTANTS AS
				SELECT FACD_ID_FACT::bigint,
					SUM(CASE WHEN FACT_TYPE <> 'P' THEN FACD_MTT_SEJOUR ELSE 0 END) AS montant_facture_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_SEJOUR ELSE 0 END) AS montant_facture_0_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_SEJOUR ELSE 0 END) AS montant_facture_1_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_SEJOUR ELSE 0 END) AS montant_facture_2_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_SEJOUR ELSE 0 END) AS montant_facture_22_c,

					SUM(CASE WHEN FACT_TYPE <> 'P' THEN FACD_MTT_CRN_SEJ ELSE 0 END)
						+ SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ = '1' THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_CRN_SEJ ELSE 0 END)
						+ SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ = '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_0_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_CRN_SEJ ELSE 0 END)
						+ SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ = '1' AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_1_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_CRN_SEJ ELSE 0 END)
						+ SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_2_c,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_CRN_SEJ ELSE 0 END)
						+ SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_22_c,

					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) THEN FACD_MTT_VEN_SEJ + FACD_MTT_A85_SEJ + FACD_MTT_ACO_SEJ + FACD_MTT_CAR_SEJ + FACD_MTT_PER_SEJ ELSE 0 END) AS montant_regle_c,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_VEN_SEJ + FACD_MTT_A85_SEJ + FACD_MTT_ACO_SEJ + FACD_MTT_CAR_SEJ + FACD_MTT_PER_SEJ ELSE 0 END) AS montant_regle_0_c,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_VEN_SEJ + FACD_MTT_A85_SEJ + FACD_MTT_ACO_SEJ + FACD_MTT_CAR_SEJ + FACD_MTT_PER_SEJ ELSE 0 END) AS montant_regle_1_c,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_VEN_SEJ + FACD_MTT_A85_SEJ + FACD_MTT_ACO_SEJ + FACD_MTT_CAR_SEJ + FACD_MTT_PER_SEJ ELSE 0 END) AS montant_regle_2_c,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_VEN_SEJ + FACD_MTT_A85_SEJ + FACD_MTT_ACO_SEJ + FACD_MTT_CAR_SEJ + FACD_MTT_PER_SEJ ELSE 0 END) AS montant_regle_22_c,

					SUM(CASE WHEN FACT_TYPE <> 'P' THEN FACD_MTT_HON_HOR_DEH + FACD_MTT_DEH ELSE 0 END) AS montant_facture_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_HON_HOR_DEH + FACD_MTT_DEH ELSE 0 END) AS montant_facture_0_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_HON_HOR_DEH + FACD_MTT_DEH ELSE 0 END) AS montant_facture_1_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_HON_HOR_DEH + FACD_MTT_DEH ELSE 0 END) AS montant_facture_2_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_HON_HOR_DEH + FACD_MTT_DEH ELSE 0 END) AS montant_facture_22_h,

					SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ <> '1' THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ <> '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_0_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ <> '1' AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_1_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_2_h,
					SUM(CASE WHEN FACT_TYPE <> 'P' AND CRN_HON_TO_SEJ <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_CRN_HON ELSE 0 END) AS montant_comptabilise_22_h,

					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) THEN FACD_MTT_VEN_HON + FACD_MTT_ACO_HON + FACD_MTT_PER_HON ELSE 0 END) AS montant_regle_h,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN FACD_MTT_VEN_HON + FACD_MTT_ACO_HON + FACD_MTT_PER_HON ELSE 0 END) AS montant_regle_0_h,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMO > 0 THEN FACD_MTT_VEN_HON + FACD_MTT_ACO_HON + FACD_MTT_PER_HON ELSE 0 END) AS montant_regle_1_h,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FACD_MTT_VEN_HON + FACD_MTT_ACO_HON + FACD_MTT_PER_HON ELSE 0 END) AS montant_regle_2_h,
					SUM(CASE WHEN (FACT_TYPE <> 'P' OR FACT_DAT_ARCHIVE IS NULL) AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FACD_MTT_VEN_HON + FACD_MTT_ACO_HON + FACD_MTT_PER_HON ELSE 0 END) AS montant_regle_22_h

				FROM prod_hm.FAC_FACTURE_DEBITEUR, w_FAC_FACTURE
				WHERE  FACD_ID_FACT = FACT_ID_FACT
				GROUP BY FACD_ID_FACT;


				CREATE INDEX w_FAC_MONTANTS_i1
				ON w_FAC_MONTANTS
				USING btree
				(FACD_ID_FACT);


				-- Informations date dernier reglement

				DROP TABLE IF EXISTS w_FAC_REGLEMENT;
				CREATE TEMP TABLE w_FAC_REGLEMENT AS
				SELECT FACD_ID_FACT AS LECR_ID_FACT,
					FACT_NUM_FAC AS LECR_NUM_FAC,
					MAX(CASE WHEN LECR_PART <> 'HON' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_0_c,
					MAX(CASE WHEN LECR_PART <> 'HON' AND FACD_ID_ORGA_AMO > 0 THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_1_c,
					MAX(CASE WHEN LECR_PART <> 'HON' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_2_c,
					MAX(CASE WHEN LECR_PART <> 'HON' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_22_c,
					MAX(CASE WHEN LECR_PART = 'HON' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_0_h,
					MAX(CASE WHEN LECR_PART = 'HON' AND FACD_ID_ORGA_AMO > 0 THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_1_h,
					MAX(CASE WHEN LECR_PART = 'HON' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_2_h,
					MAX(CASE WHEN LECR_PART = 'HON' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN ECRI_DAT_ECRITURE ELSE NULL END) AS date_dernier_reglement_22_h,
					count(DISTINCT date_part('month',ECRI_DAT_ECRITURE)) AS nb_mois_reglement
				FROM prod_hm.CCL_LIGNE_ECRITURE,
					prod_hm.CCL_ECRITURE,
					prod_hm.FAC_FACTURE_DEBITEUR,
					w_CCL_JOURNAL,
					w_CCL_COMPTE,
					w_FAC_FACTURE
				WHERE
				LECR_ID_ECRI = ECRI_ID_ECRI
					AND LECR_ID_FACD = FACD_ID_FACD
					AND LECR_ID_CPTE = CPTE_ID_CPTE
					AND ECRI_ID_JOUR = JOUR_ID_JOUR
					AND FACD_ID_FACT = FACT_ID_FACT
					AND JOUR_ISJVT = '0'
					AND CPTE_CAGE_CODE = 'CLIENT'
					AND ECRI_DAT_SUP IS NULL
				GROUP BY 1,2;

				CREATE INDEX w_FAC_REGLEMENT_i1
				ON w_FAC_REGLEMENT
				USING btree
				(LECR_ID_FACT);


				-- Informations date vente

				DROP TABLE IF EXISTS w_FAC_DATEVENTE;
				CREATE TEMP TABLE w_FAC_DATEVENTE AS
				SELECT FACD_ID_FACT AS LECR_ID_FACT_VENT,
					MAX(date(ECRI_DAT_ECRITURE)) AS date_vente
				FROM prod_hm.CCL_LIGNE_ECRITURE,
					prod_hm.CCL_ECRITURE,
					prod_hm.FAC_FACTURE_DEBITEUR,
					w_CCL_JOURNAL,
					w_CCL_COMPTE,
					w_FAC_FACTURE
				WHERE
					LECR_ID_ECRI = ECRI_ID_ECRI
					AND LECR_ID_FACD = FACD_ID_FACD
					AND ECRI_ID_JOUR = JOUR_ID_JOUR
					AND LECR_ID_CPTE = CPTE_ID_CPTE
					AND FACD_ID_FACT = FACT_ID_FACT
					AND ECRI_DAT_SUP IS NULL
					AND CPTE_CAGE_CODE = 'CLIENT'
					AND JOUR_ISJVT = '1'
				GROUP BY 1;

				CREATE INDEX w_FAC_DATEVENTE_i1
				ON w_FAC_DATEVENTE
				USING btree
				(LECR_ID_FACT_VENT);

				-- Informations expedition

				-- L'organisme AMC n'est pas toujours renseigné dans la ligne de bordereau pour les CMU, on le retrouve dans les factures débuteur

				UPDATE prod_hm.FAC_BORDEREAU
                SET FBOR_ID_ORGA_AMC = FACD_ID_ORGA_AMC
                FROM
                (
                    SELECT FBOR_ID_FBOR,
                        MAX(FACD_ID_ORGA_AMC) AS FACD_ID_ORGA_AMC
                    FROM
                    (
                        SELECT FBOR_ID_FBOR,
                            FACT_ID_FACT,
                            MAX(FBOR_ID_ORGA_AMO) AS FBOR_ID_ORGA_AMO,
                            MAX(FBOR_ID_ORGA_AMC) AS FBOR_ID_ORGA_AMC,
                            MAX(FACD_ID_ORGA_AMC) AS FACD_ID_ORGA_AMC
                        FROM prod_hm.FAC_BORDEREAU
                        JOIN prod_hm.FAC_LIGNE_BORDEREAU ON LBOR_ID_FBOR = FBOR_ID_FBOR
                        JOIN prod_hm.FAC_FACTURE ON LBOR_ID_FACT = FACT_ID_FACT
                        JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LBOR_ID_FACT = FACD_ID_FACT
                        JOIN prod_hm.IDE_ORGANISME ON FACD_ID_ORGA_AMC = ORGA_ID_ORGA
                        WHERE LBOR_MTT_MUT_SEJ <> 0 AND
                            FBOR_ID_ORGA_AMO <> 0 AND
                            FBOR_ID_ORGA_AMC = 0 AND
                            ORGA_NOM LIKE 'CMU %'
                        GROUP BY 1,2
                        HAVING MAX(FBOR_ID_ORGA_AMC) = 0
                    ) subview
                    GROUP BY 1
                ) subview
                WHERE FAC_BORDEREAU.FBOR_ID_FBOR = subview.FBOR_ID_FBOR
                ;


				-- L'organisme AMC n'est pas toujours renseigné dans la ligne de bordereau, on le retrouve dans les factures débuteur
				UPDATE prod_hm.FAC_BORDEREAU
				SET FBOR_ID_ORGA_AMC = FACD_ID_ORGA_AMC
				FROM
				(
					SELECT FBOR_ID_FBOR, FACD_ID_ORGA_AMC
					FROM prod_hm.FAC_LIGNE_BORDEREAU
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LBOR_ID_FACD = FACD_ID_FACD
					JOIN prod_hm.FAC_BORDEREAU ON LBOR_ID_FBOR = FBOR_ID_FBOR
					WHERE FBOR_ID_ORGA_AMC = 0 AND FACD_ID_ORGA_AMC <> 0 AND
					FACD_MTT_SEJOUR = LBOR_MTT_MUT_SEJ
				) subview
				WHERE FAC_BORDEREAU.FBOR_ID_FBOR = subview.FBOR_ID_FBOR
				;

				DROP TABLE IF EXISTS w_FAC_BORDEREAU;
				CREATE TEMP TABLE w_FAC_BORDEREAU AS
				SELECT LBOR_ID_FACT::bigint,
					'0'::text  AS code_expedie_0,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMO > 0 THEN '1'
						ELSE '0'
						END) AS code_expedie_1,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN '1'
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN '1'
						ELSE '0' END) AS code_expedie_2,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC = tiers_payant_22_orga_id THEN '1'
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN '1'
						ELSE '0' END) AS code_expedie_22,
					''::text AS no_bordereau_0,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMO > 0 THEN FBOR_NUM_LOT
						ELSE 0 END) AS no_bordereau_1,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FBOR_NUM_LOT
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN FBOR_NUM_LOT
						ELSE 0 END) AS no_bordereau_2,
					MAX(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FBOR_NUM_LOT
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN FBOR_NUM_LOT
						ELSE 0 END) AS no_bordereau_22,
					'20991231'::date AS date_expedition_0,
					MIN(CASE
						WHEN FBOR_ID_ORGA_AMO > 0 THEN GREATEST(FBOR_DAT_EXPEDITION, FBOR_DAT_CONSTITUTION)
						ELSE '20991231' END) AS date_expedition_1,
					MIN(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN GREATEST(FBOR_DAT_EXPEDITION, FBOR_DAT_CONSTITUTION)
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN GREATEST(FBOR_DAT_EXPEDITION, FBOR_DAT_CONSTITUTION)
						ELSE '20991231' END) AS date_expedition_2,
					MIN(CASE
						WHEN FBOR_ID_ORGA_AMC > 0 AND FBOR_ID_ORGA_AMC = tiers_payant_22_orga_id THEN GREATEST(FBOR_DAT_EXPEDITION, FBOR_DAT_CONSTITUTION)
						WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN GREATEST(FBOR_DAT_EXPEDITION, FBOR_DAT_CONSTITUTION)
						ELSE '20991231' END) AS date_expedition_22
				FROM prod_hm.FAC_BORDEREAU
				JOIN prod_hm.FAC_LIGNE_BORDEREAU ON LBOR_ID_FBOR = FBOR_ID_FBOR
				JOIN w_FAC_FACTURE ON LBOR_ID_FACT = FACT_ID_FACT
				LEFT JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LBOR_ID_FACD = FACD_ID_FACD
				WHERE FBOR_DAT_SUPPRESSION IS NULL
				GROUP BY LBOR_ID_FACT;

				CREATE INDEX w_FAC_BORDEREAU_i1
				ON w_FAC_BORDEREAU
				USING btree
				(LBOR_ID_FACT);

				-- Informations rejets

				DROP TABLE IF EXISTS w_FAC_REJET;
				CREATE TEMP TABLE w_FAC_REJET AS
				SELECT NOER_ID_FACT::bigint,
					COUNT(*) as nb_rejets
				FROM prod_hm.CCL_NOEMIE_REJET, w_FAC_FACTURE
				WHERE NOER_ID_FACT = FACT_ID_FACT AND TRIM(NOER_CDF_REJET) <> '0001'
				GROUP BY NOER_ID_FACT;

				CREATE INDEX w_FAC_REJET_i1
				ON w_FAC_REJET
				USING btree
				(NOER_ID_FACT);


				-- Ajout des factures

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_14');

				INSERT INTO activite[PX].p_factures(
					sejour_id,
					no_sejour,
					no_facture,
					date_debut,
					date_fin,
					type_facture,
					code_facture,
					date_facture,
					code_vente,
					date_vente,
					mois_vente,
					date_solde,
					montant_facture_c,
					montant_facture_h,
					montant_regle_c,
					montant_regle_h,
					delai_facture,
					delai_solde,
					date_expedition,
					delai_expedition,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					date_solde_0_c,
					date_solde_0_h,
					date_solde_1_c,
					date_solde_1_h,
					date_solde_2_c,
					date_solde_2_h,
					date_solde_22_c,
					date_solde_22_h,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					date_expedition_22,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					code_expedie_22,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					no_bordereau_22,
					montant_facture_0_c,
					montant_facture_0_h,
					montant_facture_1_c,
					montant_facture_1_h,
					montant_facture_2_c,
					montant_facture_2_h,
					montant_facture_22_c,
					montant_facture_22_h,
					montant_regle_0_c,
					montant_regle_0_h,
					montant_regle_1_c,
					montant_regle_1_h,
					montant_regle_2_c,
					montant_regle_2_h,
					montant_regle_22_c,
					montant_regle_22_h,
					delai_expedition_0,
					delai_expedition_1,
					delai_expedition_2,
					delai_expedition_22,
					delai_solde_0_c,
					delai_solde_0_h,
					delai_solde_1_c,
					delai_solde_1_h,
					delai_solde_2_c,
					delai_solde_2_h,
					delai_solde_22_c,
					delai_solde_22_h,
					ghs_id,
					particularite_t2a,
					code_cloture,
					code_cp_demandee,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,

					montant_comptabilise_c,
					montant_comptabilise_h,
					montant_comptabilise_0_c,
					montant_comptabilise_0_h,
					montant_comptabilise_1_c,
					montant_comptabilise_1_h,
					montant_comptabilise_2_c,
					montant_comptabilise_2_h,
					montant_comptabilise_22_c,
					montant_comptabilise_22_h,

					nb_rejets,

					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour
					)
				SELECT
					sejour_id,
					no_sejour,
					FACT_NUM_FAC AS no_facture,
					date(FACT_DAT_DEB_FAC) AS date_debut,
					date(FACT_DAT_FIN_FAC) AS date_fin,
					CASE
						WHEN FACT_TYPE IN ('P') THEN 'P'
						WHEN FACT_TYPE IN ('F', 'P') AND FACT_TYP_FAC = 0 THEN '0'
						WHEN FACT_TYPE = 'X' THEN 'X'
						WHEN FACT_TYPE = 'F' AND FACT_TYP_FAC <> 0 THEN '2'
						WHEN FACT_TYPE = 'A' THEN '1'
						ELSE '0' END AS type_facture,
					CASE WHEN FACT_TYPE = 'P' THEN '0' ELSE '1' END AS code_facture,
					date(FACT_DAT_DER_CALCUL) AS date_facture,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN '1' ELSE '0' END AS code_vente,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN w_FAC_DATEVENTE.date_vente ELSE '20991231'::date END AS date_vente,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN extract('year' FROM w_FAC_DATEVENTE.date_vente) * 100 + extract('month' FROM w_FAC_DATEVENTE.date_vente) ELSE extract('year' FROM '20991231'::date) * 100 + extract('month' FROM '20991231'::date) END AS mois_vente,

					COALESCE(
					GREATEST(
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_c = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_0_c END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_h = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_0_h END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_c = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_1_c END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_h = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_1_h END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_c = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_2_c END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_h = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_2_h END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_c = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_22_c END,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_h = 0 THEN date(FACT_DAT_FIN_FAC) ELSE date_dernier_reglement_22_h END)
					, '20991231') as date_solde,


					w_FAC_MONTANTS.montant_facture_c AS montant_facture_c,
					w_FAC_MONTANTS.montant_facture_h AS montant_facture_h,
					w_FAC_MONTANTS.montant_regle_c AS montant_regle_c,
					w_FAC_MONTANTS.montant_regle_h AS montant_regle_h,
					date(FACT_DAT_DER_CALCUL) - date_sortie as delai_facture,
					0 as delai_solde,
					LEAST(w_FAC_BORDEREAU.date_expedition_1, w_FAC_BORDEREAU.date_expedition_2) as date_expedition,
					0 as delai_expedition,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_c = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_0_c IS NOT NULL THEN date_dernier_reglement_0_c ELSE '20991231' END  as date_solde_0_c,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_0_h = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_0_h IS NOT NULL THEN date_dernier_reglement_0_h ELSE '20991231' END  as date_solde_0_h,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_c = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_1_c IS NOT NULL THEN date_dernier_reglement_1_c ELSE '20991231' END  as date_solde_1_c,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_1_h = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_1_h IS NOT NULL THEN date_dernier_reglement_1_h ELSE '20991231' END  as date_solde_1_h,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_c = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_2_c IS NOT NULL THEN date_dernier_reglement_2_c ELSE '20991231' END  as date_solde_2_c,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_2_h = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_2_h IS NOT NULL THEN date_dernier_reglement_2_h ELSE '20991231' END  as date_solde_2_h,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_c = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_22_c IS NOT NULL THEN date_dernier_reglement_22_c ELSE '20991231' END  as date_solde_22_c,
					CASE
						WHEN w_FAC_MONTANTS.montant_comptabilise_22_h = 0 THEN date(FACT_DAT_FIN_FAC)
						WHEN date_dernier_reglement_22_h IS NOT NULL THEN date_dernier_reglement_22_h ELSE '20991231' END  as date_solde_22_h,

					w_FAC_BORDEREAU.date_expedition_0,
					w_FAC_BORDEREAU.date_expedition_1,
					w_FAC_BORDEREAU.date_expedition_2,
					w_FAC_BORDEREAU.date_expedition_22,
					w_FAC_BORDEREAU.code_expedie_0,
					w_FAC_BORDEREAU.code_expedie_1,
					w_FAC_BORDEREAU.code_expedie_2,
					w_FAC_BORDEREAU.code_expedie_22,
					w_FAC_BORDEREAU.no_bordereau_0,
					w_FAC_BORDEREAU.no_bordereau_1,
					w_FAC_BORDEREAU.no_bordereau_2,
					w_FAC_BORDEREAU.no_bordereau_22,

					w_FAC_MONTANTS.montant_facture_0_c AS montant_facture_0_c,
					w_FAC_MONTANTS.montant_facture_0_h AS montant_facture_0_h,
					w_FAC_MONTANTS.montant_facture_1_c AS montant_facture_1_c,
					w_FAC_MONTANTS.montant_facture_1_h AS montant_facture_1_h,
					w_FAC_MONTANTS.montant_facture_2_c AS montant_facture_2_c,
					w_FAC_MONTANTS.montant_facture_2_h AS montant_facture_2_h,
					w_FAC_MONTANTS.montant_facture_22_c AS montant_facture_22_c,
					w_FAC_MONTANTS.montant_facture_22_h AS montant_facture_22_h,

					w_FAC_MONTANTS.montant_regle_0_c AS montant_regle_0_c,
					w_FAC_MONTANTS.montant_regle_0_h AS montant_regle_0_h,
					w_FAC_MONTANTS.montant_regle_1_c AS montant_regle_1_c,
					w_FAC_MONTANTS.montant_regle_1_h AS montant_regle_1_h,
					w_FAC_MONTANTS.montant_regle_2_c AS montant_regle_2_c,
					w_FAC_MONTANTS.montant_regle_2_h AS montant_regle_2_h,
					w_FAC_MONTANTS.montant_regle_22_c AS montant_regle_22_c,
					w_FAC_MONTANTS.montant_regle_22_h AS montant_regle_22_h,


					0 AS delai_expedition_0,
					0 AS delai_expedition_1,
					0 AS delai_expedition_2,
					0 AS delai_expedition_22,
					0 AS delai_solde_0_c,
					0 AS delai_solde_0_h,
					0 AS delai_solde_1_c,
					0 AS delai_solde_1_h,
					0 AS delai_solde_2_c,
					0 AS delai_solde_2_h,
					0 AS delai_solde_22_c,
					0 AS delai_solde_22_h,

					ghs_id,
					'' as particularite_t2a,

					'0' as code_cloture,
					'0' as code_cp_demandee,
					0 AS ghs_bebe1_id,
					0 AS ghs_bebe2_id,
					0 AS ghs_bebe3_id,

					w_FAC_MONTANTS.montant_comptabilise_c,
					w_FAC_MONTANTS.montant_comptabilise_h,
					w_FAC_MONTANTS.montant_comptabilise_0_c,
					w_FAC_MONTANTS.montant_comptabilise_0_h,
					w_FAC_MONTANTS.montant_comptabilise_1_c,
					w_FAC_MONTANTS.montant_comptabilise_1_h,
					w_FAC_MONTANTS.montant_comptabilise_2_c,
					w_FAC_MONTANTS.montant_comptabilise_2_h,
					w_FAC_MONTANTS.montant_comptabilise_22_c,
					w_FAC_MONTANTS.montant_comptabilise_22_h,

					COALESCE(w_FAC_REJET.nb_rejets,0),

					0,
					0


				FROM w_FAC_FACTURE
					LEFT JOIN w_FAC_BORDEREAU ON (LBOR_ID_FACT = FACT_ID_FACT)
					LEFT JOIN w_FAC_MONTANTS ON (FACD_ID_FACT = FACT_ID_FACT)
					LEFT JOIN w_FAC_REGLEMENT ON (LECR_ID_FACT = FACT_ID_FACT)
					LEFT JOIN w_FAC_DATEVENTE ON (LECR_ID_FACT_VENT = FACT_ID_FACT)
					LEFT JOIN w_FAC_REJET ON (NOER_ID_FACT = FACT_ID_FACT)
				ORDER BY 1,2;


				-- Avoirs qui annulent des factures

				UPDATE activite[PX].p_factures SET no_facture_od_avoir = fac_facture_avoir.FACT_NUM_FAC
				FROM prod_hm.FAC_FACTURE
				JOIN prod_hm.FAC_FACTURE FAC_FACTURE_AVOIR ON FAC_FACTURE.FACT_ID_FACT_AVOIR = FAC_FACTURE_AVOIR.FACT_ID_FACT AND FAC_FACTURE.FACT_ID_FACT_AVOIR <> 0
				WHERE p_factures.no_facture = FAC_FACTURE.FACT_NUM_FAC
					AND no_facture_od_avoir IS DISTINCT FROM fac_facture_avoir.FACT_NUM_FAC;


				DROP TABLE IF EXISTS w_ods_avoir;
				CREATE TEMP TABLE w_ods_avoir AS

				SELECT p_factures.no_facture, p_factures.no_facture_od_avoir, p_factures_avoir.date_facture AS date_od_avoir,
				SUM(p_factures.montant_comptabilise_c + p_factures.montant_comptabilise_h) AS montant_comptabilise,
				SUM(p_factures.montant_regle_c + p_factures.montant_regle_h) AS montant_regle,
				SUM(p_factures_avoir.montant_comptabilise_c + p_factures_avoir.montant_comptabilise_h) AS montant_facture_avoir,
				SUM(p_factures_avoir.montant_regle_c + p_factures_avoir.montant_regle_h) AS montant_regle_avoir
				FROM activite[PX].p_factures
				JOIN activite[PX].p_factures p_factures_avoir ON p_factures.no_facture = p_factures_avoir.no_facture_od_avoir
				WHERE p_factures.type_facture = 'X' AND p_factures_avoir.type_facture = '1'
				GROUP BY 1,2,3
				HAVING SUM(p_factures.montant_comptabilise_c + p_factures.montant_comptabilise_h) = 0 - SUM(p_factures_avoir.montant_comptabilise_c + p_factures_avoir.montant_comptabilise_h) AND
					SUM(p_factures.montant_regle_c + p_factures.montant_regle_h) = 0 AND
					SUM(p_factures_avoir.montant_regle_c + p_factures_avoir.montant_regle_h) = 0;


				UPDATE activite[PX].p_factures SET
					date_solde_c = date_od_avoir,
					date_solde_0_c = date_od_avoir,
					date_solde_1_c = date_od_avoir,
					date_solde_2_c = date_od_avoir,
					date_solde_22_c = date_od_avoir,
					date_solde_h = date_od_avoir,
					date_solde_0_h = date_od_avoir,
					date_solde_1_h = date_od_avoir,
					date_solde_2_h = date_od_avoir,
					date_solde_22_h = date_od_avoir,
					montant_regle_c = montant_comptabilise_c,
					montant_regle_0_c = montant_comptabilise_0_c,
					montant_regle_1_c = montant_comptabilise_1_c,
					montant_regle_2_c = montant_comptabilise_2_c,
					montant_regle_22_c = montant_comptabilise_22_c,
					montant_regle_h = montant_comptabilise_h,
					montant_regle_0_h = montant_comptabilise_0_h,
					montant_regle_1_h = montant_comptabilise_1_h,
					montant_regle_2_h = montant_comptabilise_2_h,
					montant_regle_22_h = montant_comptabilise_22_h
				FROM w_ods_avoir
				WHERE p_factures.no_facture = w_ods_avoir.no_facture;

				UPDATE activite[PX].p_factures SET
					date_solde_c = date_od_avoir,
					date_solde_0_c = date_od_avoir,
					date_solde_1_c = date_od_avoir,
					date_solde_2_c = date_od_avoir,
					date_solde_22_c = date_od_avoir,
					date_solde_h = date_od_avoir,
					date_solde_0_h = date_od_avoir,
					date_solde_1_h = date_od_avoir,
					date_solde_2_h = date_od_avoir,
					date_solde_22_h = date_od_avoir,
					montant_regle_c = montant_comptabilise_c,
					montant_regle_0_c = montant_comptabilise_0_c,
					montant_regle_1_c = montant_comptabilise_1_c,
					montant_regle_2_c = montant_comptabilise_2_c,
					montant_regle_22_c = montant_comptabilise_22_c,
					montant_regle_h = montant_comptabilise_h,
					montant_regle_0_h = montant_comptabilise_0_h,
					montant_regle_1_h = montant_comptabilise_1_h,
					montant_regle_2_h = montant_comptabilise_2_h,
					montant_regle_22_h = montant_comptabilise_22_h
				FROM w_ods_avoir
				WHERE p_factures.no_facture = w_ods_avoir.no_facture_od_avoir;


				SELECT base.cti_enable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_14');





				-- Séjours sans facture

				DROP TABLE IF EXISTS w_factures_trous;
				CREATE TEMP TABLE w_factures_trous AS
				SELECT
					p_sejours.finess,
					p_sejours.no_sejour,
					p_sejours.date_entree,
					p_sejours.tiers_payant_0_id,
					p_sejours.tiers_payant_1_id,
					p_sejours.tiers_payant_2_id,
					p_sejours.tiers_payant_22_id,
					p_sejours.code_cp_demandee,
					p_sejours.ghs_id,
					COALESCE(t_services_facturation.avec_facturation_intermediaire,'') AS avec_facturation_intermediaire,
					p_sejours.code_sorti,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_sortie,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_encours,
					MAX(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture,
					date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours
				FROM activite[PX].p_sejours
					LEFT JOIN activite[PX].p_factures ON
						p_sejours.no_sejour = p_factures.no_sejour AND
						no_facture NOT LIKE 'E%' AND
						type_facture IS DISTINCT FROM 'P' AND
						no_facture_od_avoir = ''
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				WHERE p_sejours.etat = '' AND p_sejours.code_prevu <> 1 AND p_sejours.est_sans_facturation IS DISTINCT FROM '1' AND date_entree <= now() AND p_sejours.type_sejour <> '6' AND p_sejours.type_sejour <> '9'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13;


				INSERT INTO activite[PX].p_factures(
					finess,
					no_sejour,
					no_facture,
					no_facture_reference,
					type_facture,
					code_facture,
					date_facture,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					code_cp_demandee,
					ghs_id,
					date_debut,
					date_fin)
				SELECT finess,
					no_sejour,
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END,
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END,
					'E',
					'0',
					'20991231'::date,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					code_cp_demandee ,
					ghs_id,
					MIN(GREATEST(date_debut_encours, p_calendrier.date)),
					MAX(LEAST(date_fin_encours, p_calendrier.date))
				FROM w_factures_trous
					JOIN base.p_calendrier ON p_calendrier.date  BETWEEN date_debut_encours AND date_fin_encours
				WHERE (date_debut_encours <= date_fin_encours or date_fin_facture is null)
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13;



				UPDATE activite[PX].p_factures SET
					date_debut = date_entree,
					date_fin = CASE WHEN code_sorti = '1' THEN date_sortie ELSE date_fin END
				FROM activite[PX].p_sejours
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid AND
						avec_facturation_intermediaire IS DISTINCT FROM '1'
				WHERE p_factures.no_sejour = p_sejours.no_sejour AND
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END - date_entree < 30 AND
					(
					p_factures.date_debut <> date_entree OR
					p_factures.date_fin <> CASE WHEN code_sorti = '1' THEN date_sortie ELSE date_fin END
					);




				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_sejours_orga CASCADE;
				DROP TABLE IF EXISTS w_FAC_MONTANTS CASCADE;
				DROP TABLE IF EXISTS w_FAC_REGLEMENT CASCADE;
				DROP TABLE IF EXISTS w_FAC_BORDEREAU CASCADE;
				DROP TABLE IF EXISTS w_factures_trous CASCADE;


			]]></sqlcmd>
	</NODE>

	<NODE label="Rejets">
		<sqlcmd><![CDATA[

				INSERT INTO activite[PX].p_factures_rejets(
					no_facture, date_rejet, rejet_id, rejet_code, rejet_texte)
				SELECT
					FACT_NUM_FAC ,
					date(NOER_DAT_CRE) ,
					0,
					TRIM(NOER_CDF_REJET) ,
					TRIM(NOER_LIB_REJET)
				FROM prod_hm.CCL_NOEMIE_REJET, w_FAC_FACTURE
				WHERE NOER_ID_FACT = FACT_ID_FACT
					AND TRIM(NOER_CDF_REJET) <> '0001' AND TRIM(NOER_LIB_REJET) <> '';

				INSERT INTO activite.t_rejets_noemie (texte, code)
				SELECT rejet_texte, MAX(rejet_code)
				FROM activite[PX].p_factures_rejets
				LEFT JOIN activite.t_rejets_noemie ON (rejet_texte = t_rejets_noemie.texte)
				WHERE t_rejets_noemie.oid IS NULL
				GROUP BY 1;

				UPDATE activite[PX].p_factures_rejets
				SET rejet_id = t_rejets_noemie.oid
				FROM activite.t_rejets_noemie
				WHERE rejet_texte = t_rejets_noemie.texte;

			]]></sqlcmd>
	</NODE>

	<NODE label="Date fin multi-séances">
		<sqlcmd><![CDATA[

				-- Séjours sortis dont la dernière séance est antérieure à la date de sortie

				DROP TABLE IF EXISTS w_seances_sortie_mvt;
				CREATE TEMP TABLE w_seances_sortie_mvt AS
				SELECT p_sejours.no_sejour,  MAX(CASE WHEN nb_seances > 0 THEN p_mouvements_sejour.date ELSE p_sejours.date_entree END) AS date_mvt_max
				FROM activite[PX].p_sejours
				JOIN activite[PX].p_mouvements_sejour On p_sejours.no_sejour = p_mouvements_sejour.no_sejour
				JOIN activite[PX].t_lieux ON p_mouvements_sejour.lieu_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
				WHERE code_sorti = '1' AND code_prevu = '0' AND p_sejours.type_sejour = '5' AND
					avec_facturation_intermediaire = '1'
				GROUP BY 1
				HAVING MAX(date_sortie) > MAX(CASE WHEN nb_seances > 0 THEN p_mouvements_sejour.date ELSE p_sejours.date_entree END) AND
					SUM(nb_seances) > 0
				;


				DROP TABLE IF EXISTS w_seances_sortie_fac;
				CREATE TEMP TABLE w_seances_sortie_fac AS
				SELECT p_sejours.no_sejour,  MAX(p_factures.date_fin) AS date_fac_max
				FROM activite[PX].p_sejours
				JOIN w_seances_sortie_mvt ON p_sejours.no_sejour = w_seances_sortie_mvt.no_sejour
				JOIN activite[PX].p_factures On p_sejours.no_sejour = p_factures.no_sejour
				WHERE code_sorti = '1' AND code_prevu = '0' AND type_sejour = '5' AND
					p_factures.code_facture >= '1'
				GROUP BY 1
				;


				DROP TABLE IF EXISTS w_seances_sortie_maj;
				CREATE TEMP TABLE w_seances_sortie_maj AS
				SELECT p_sejours.no_sejour, p_sejours.date_sortie, date_mvt_max, date_fac_max,
					GREATEST(date_mvt_max, date_fac_max) AS date_sortie_reelle
				FROM activite[PX].p_sejours
				JOIN w_seances_sortie_mvt ON p_sejours.no_sejour = w_seances_sortie_mvt.no_sejour
				LEFT JOIN w_seances_sortie_fac ON p_sejours.no_sejour = w_seances_sortie_fac.no_sejour
				WHERE date_sortie > GREATEST(date_mvt_max, date_fac_max)
				ORDER BY 1
				;



				UPDATE activite[PX].p_sejours
				SET date_sortie = date_sortie_reelle
				FROM w_seances_sortie_maj
				WHERE p_sejours.no_sejour = w_seances_sortie_maj.no_sejour AND
					p_sejours.date_sortie > date_sortie_reelle;


				DELETE FROM activite[PX].p_factures
				USING w_seances_sortie_maj
				WHERE p_factures.no_sejour = w_seances_sortie_maj.no_sejour AND
					p_factures.date_fin > date_sortie_reelle AND
					p_factures.code_facture = '0' AND
					montant_regle_c = 0 AND montant_facture_c = 0 AND
					montant_regle_h = 0 AND montant_facture_h = 0
					;



				DELETE FROM activite[PX].p_mouvements_sejour
				USING w_seances_sortie_maj
				WHERE p_mouvements_sejour.no_sejour = w_seances_sortie_maj.no_sejour AND
					p_mouvements_sejour.date > date_sortie_reelle
					;

			]]></sqlcmd>
	</NODE>

	<NODE label="Lignes non facturées Clinique">
		<sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;

				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					rubrique_facturation_id,
					prestation_id,
					prix_unitaire,
					lieu_id,
					ucd_id,
					lpp_id)
				SELECT
					p_factures.no_facture,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(COALESCE(LFAC_DAT_EXE_FIN, LFAC_DAT_EXE_DEB)) AS date_fin,
					MAX(LFAC_QTE_COEFFICIENT) AS nb_rubrique,
					1 AS coefficient,
					MAX(t_rubriques_facturation.oid) AS rubrique_facturation_id,
					MAX(t_prestations.oid) AS prestation_id,
					CASE
						WHEN MAX(LFAD_IND_BGH) <> '1' THEN MAX(LFAC_PRI_UNITAIRE)
						ELSE base.cti_division(SUM(CASE WHEN LFAD_IND_BGH <> '1' THEN LFAD_MTT_HOR_DEH ELSE 0 END) , MAX(LFAC_QTE_COEFFICIENT)) END
							AS prix_unitaire,
					MAX(p_sejours.lieu_sortie_id) AS lieu_id,
					MAX(COALESCE(t_ucd.oid)) AS ucd_id,
					MAX(COALESCE(t_lpp.oid)) AS lpp_id
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT AND FACT_TYPE = 'P'
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
					JOIN activite[PX].p_sejours ON LFAC_ID_SEJO_D::bigint = p_sejours.code_original AND p_sejours.etat = ''
					JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture = 'E' AND p_factures.no_facture NOT LIKE '%BG'
					JOIN activite[PX].t_rubriques_facturation ON LFAC_ID_PRSE::bigint = t_rubriques_facturation.code_original
					JOIN activite.t_prestations ON LFAC_LET_CLE = t_prestations.code
					LEFT JOIN base.t_lpp ON LFAC_COD_LPP <> '' AND LFAC_COD_LPP = t_lpp.code
					LEFT JOIN prod_hm.FAC_LIGNE_FACTURE_UCD ON LFAC_ID_LFAC = LFUC_ID_LFAC
					LEFT JOIN base.t_ucd ON LFUC_COD_UCD <> '' AND LFUC_COD_UCD = t_ucd.code
				WHERE LFAC_LET_CLE NOT IN ('GHS', 'GMT') AND LFAC_ID_PRSE <> 0 AND
					FACT_DAT_SUP IS NULL AND
					date(LFAC_DAT_EXE_DEB) BETWEEN p_factures.date_debut AND p_factures.date_fin
				GROUP BY 1,2,3, LFAC_ID_LFAC
				HAVING MIN(LFAD_IND_BGH) <> '1'
					;

				DROP TABLE IF EXISTS w_deja_non_factures;
				CREATE TEMP TABLE w_deja_non_factures AS
				SELECT LFAC_ID_ACSA
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT AND FACT_TYPE = 'P'
					JOIN activite[PX].p_sejours ON LFAC_ID_SEJO_D::bigint = p_sejours.code_original
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
				WHERE LFAC_ID_PRSE <> 0 AND
					FACT_DAT_SUP IS NULL AND
					LFAC_ID_ACSA <> 0
				GROUP BY 1
				HAVING MIN(LFAD_IND_BGH) <> '1';

				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture
					, date_debut
					, date_fin
					, nb_rubrique
					, coefficient
					, rubrique_facturation_id
					, prestation_id
					, prix_unitaire
					, lieu_id
				)
				SELECT
					p_factures.no_facture
					, date(ACSA_DAT_EXE_DEB) AS date_debut
					, date(COALESCE(ACSA_DAT_EXE_FIN, ACSA_DAT_EXE_DEB)) AS date_fin
					, ACSA_QTE_COEFFICIENT AS nb_rubrique
					, 1 AS coefficient
					, t_rubriques_facturation.oid AS rubrique_facturation_id
					, t_prestations.oid AS prestation_id
					, CASE 
						WHEN acsa_qte_coefficient > 1 AND base.cti_division(acsa_qte_coefficient * acsa_pri_unitaire, acsa_mon_tot) > 2 THEN base.cti_division(acsa_pri_unitaire , acsa_qte_coefficient)
						ELSE acsa_pri_unitaire END AS prix_unitaire
					, p_sejours.lieu_sortie_id AS lieu_id
                FROM prod_hm.SAD_ACTIVITE_SAISIES
                    JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original AND p_sejours.etat = ''
                    JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture = 'E'
                    JOIN activite[PX].t_rubriques_facturation ON ACSA_ID_PRSE::bigint = t_rubriques_facturation.code_original
                    JOIN activite.t_prestations ON ACSA_LET_CLE = t_prestations.code
                    LEFT JOIN w_deja_non_factures ON ACSA_ID_ACSA = LFAC_ID_ACSA
                WHERE 1 = 1
                	AND ACSA_LET_CLE NOT IN ('GHS', 'GMT', 'SZH')  
                	AND ACSA_ID_PRSE <> 0  
                	AND LFAC_ID_ACSA IS NULL 
                    AND date(ACSA_DAT_EXE_DEB) BETWEEN p_factures.date_debut AND p_factures.date_fin
                ;

                -- Prestations pointées sur le dossier sans ligne générée
                DROP TABLE IF EXISTS w_lignes_deja_non_facturees_sejour;
				CREATE TEMP TABLE w_lignes_deja_non_facturees_sejour AS
				SELECT no_sejour, prestation_id, rubrique_facturation_id
				FROM activite[PX].p_factures_lignes_non_facturees_c
				JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
				GROUP BY 1,2,3
				;

				ANALYSE w_lignes_deja_non_facturees_sejour
				;

                INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					rubrique_facturation_id,
					prestation_id,
					prix_unitaire,
					lieu_id)
                SELECT p_factures.no_facture,
                    GREATEST(date(SEPR_DAT_DEB), p_factures.date_debut) AS date_debut,
                    LEAST(date(COALESCE(SEPR_DAT_FIN,'20991231')),p_factures.date_fin, date(now()+interval '1 day')) AS date_fin,
                    GREATEST(LEAST(date(COALESCE(SEPR_DAT_FIN,'20991231')),p_factures.date_fin, date(now()+interval '1 day')) - GREATEST(date(SEPR_DAT_DEB), p_factures.date_debut),1) AS nb_rubrique,
                    1 AS coefficient,
                    t_rubriques_facturation.oid AS rubrique_facturation_id,
                    t_prestations.oid AS prestation_id,
                    LFAC_PRI_UNITAIRE AS prix_unitaire,
                    p_sejours.lieu_sortie_id AS lieu_id
                FROM prod_hm.IDE_SEJOUR_PRESTATION
                JOIN prod_hm.PAD_PRESTATION_SEJOUR ON SEPR_ID_PRSE = PRSE_ID_PRSE
                JOIN activite[PX].p_sejours ON SEPR_ID_SEJO = code_original AND type_sejour IN ('1','2')
                JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN activite[PX].t_rubriques_facturation ON SEPR_ID_PRSE::bigint = t_rubriques_facturation.code_original
                JOIN activite.t_prestations ON PRSE_LET_CLE = t_prestations.code
                JOIN
                (
                    SELECT LFAC_ID_PRSE, (MAX(ARRAY[LFAC_DAT_EXE_DEB::text,LFAC_PRI_UNITAIRE::text]))[2]::numeric AS LFAC_PRI_UNITAIRE
                    FROM prod_hm.FAC_LIGNE_FACTURE
                    WHERE LFAC_ID_PRSE = ANY (SELECT SEPR_ID_PRSE FROM prod_hm.IDE_SEJOUR_PRESTATION GROUP BY 1)
                    GROUP BY 1
                ) subview ON SEPR_ID_PRSE = subview.LFAC_ID_PRSE
                LEFT JOIN w_lignes_deja_non_facturees_sejour ON
                    w_lignes_deja_non_facturees_sejour.no_sejour = p_sejours.no_sejour AND
                    (
						w_lignes_deja_non_facturees_sejour.prestation_id = t_prestations.oid OR
						w_lignes_deja_non_facturees_sejour.rubrique_facturation_id = t_rubriques_facturation.oid
                    )
                WHERE SEPR_IND_ACTIF = '1' 
                    AND SEPR_ID_PRSE <> 0 
                    AND p_factures.type_facture = 'E' 
                    AND date(SEPR_DAT_DEB) <= p_factures.date_fin 
                    AND (date(SEPR_DAT_FIN) >= p_factures.date_debut OR SEPR_DAT_FIN IS NULL) 
                    AND w_lignes_deja_non_facturees_sejour.no_sejour IS NULL
					-- evite les problèmes avec CPC
					AND t_prestations.code != ''  
					AND PRSE_LET_CLE NOT IN ('GMT')
                ;


			]]></sqlcmd>
	</NODE>

	<NODE label="Lignes facturées Clinique">
		<sqlcmd><![CDATA[

				-- comptes associés
				DROP TABLE IF EXISTS w_FAC_LIGNE_FACTURE_DEBITEUR_compte;
				CREATE TEMP TABLE w_FAC_LIGNE_FACTURE_DEBITEUR_compte AS
				SELECT LECR_ID_LFAD, MAX(LECR_NUM_COMPTE) AS LECR_NUM_COMPTE
				FROM prod_hm.CCL_LIGNE_ECRITURE
				JOIN prod_hm.CCL_ECRITURE ON LECR_ID_ECRI = ECRI_ID_ECRI
				JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
				JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR on LECR_ID_LFAD = LFAD_ID_LFAD
				WHERE LECR_PART = 'SFT' AND
					ECRI_DAT_SUP IS NULL
				GROUP BY 1;

				ANALYSE w_FAC_LIGNE_FACTURE_DEBITEUR_compte
				;

				ALTER TABLE w_FAC_LIGNE_FACTURE_DEBITEUR_compte ADD CONSTRAINT w_FAC_LIGNE_FACTURE_DEBITEUR_compte_pkey PRIMARY KEY(LECR_ID_LFAD);
				CREATE INDEX w_FAC_LIGNE_FACTURE_DEBITEUR_compte_i1 ON w_FAC_LIGNE_FACTURE_DEBITEUR_compte USING btree (LECR_NUM_COMPTE);


				-- Extraction lignes

				DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_C;
				CREATE TEMP TABLE w_FAC_FACTURE_LIGNE_C AS
				SELECT
					1::integer AS origine_facturation_id,
					LFAC_ID_LFAC,
					FACT_NUM_FAC AS no_facture,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(LFAC_DAT_EXE_FIN) AS date_fin,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN w_FAC_DATEVENTE.date_vente ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					LFAC_QTE_COEFFICIENT AS nb_rubrique,
					LFAC_QTE_COEFFICIENT AS nb_prestations,
					1::numeric as coefficient,
					LFAC_COE_MCO_HAD AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
					LFAC_PRI_UNITAIRE AS prix_unitaire,

					MAX(LFAC_COD_LPP) AS LFAC_COD_LPP,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id,

					SUM(LFAD_MTT_HOR_DEH + LFAD_MTT_DEH) AS montant_facture,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) as montant_facture_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_2,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_22,

					0 AS montant_facture_actes_inclus_dans_sejour,
					0 as montant_facture_0_actes_inclus_dans_sejour,
					0 as montant_facture_1_actes_inclus_dans_sejour,
					0 as montant_facture_2_actes_inclus_dans_sejour,
					0 as montant_facture_22_actes_inclus_dans_sejour,

					MAX(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN 100-LFAD_TAUX ELSE 0 END) as taux_0,
					MAX(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_TAUX ELSE 0 END) as taux_1,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_2,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_22,


					SUM(LFAD_MTT_CRN) AS montant_comptabilise,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_2,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_22,

					0::bigint AS rubrique_facture_id

				FROM prod_hm.FAC_LIGNE_FACTURE
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRSE::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
					JOIN w_FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
					LEFT JOIN w_FAC_DATEVENTE ON (LECR_ID_FACT_VENT = FACT_ID_FACT)
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
					LEFT JOIN w_FAC_LIGNE_FACTURE_DEBITEUR_compte ON LECR_ID_LFAD = LFAD_ID_LFAD
					LEFT JOIN activite[PX].t_compte ON (LECR_NUM_COMPTE = t_compte.code_original)
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				WHERE
					FACT_TYPE <> 'P' AND
					LFAC_ID_PRSE <> 0
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,15,16;



				-- Médecin Salarié ?

				INSERT INTO w_FAC_FACTURE_LIGNE_C
				SELECT
					1::integer AS origine_facturation_id,
					LFAC_ID_LFAC,
					FACT_NUM_FAC AS no_facture,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(LFAC_DAT_EXE_FIN) AS date_fin,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN w_FAC_DATEVENTE.date_vente ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					LFAC_QTE_COEFFICIENT AS nb_rubrique,
					LFAC_QTE_COEFFICIENT AS nb_prestations,
					1::numeric as coefficient,
					LFAC_COE_MCO_HAD AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
					LFAC_PRI_UNITAIRE AS prix_unitaire,

					MAX(LFAC_COD_LPP) AS LFAC_COD_LPP,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id,

					0 AS montant_facture,
					0 as montant_facture_0,
					0 as montant_facture_1,
					0 as montant_facture_2,
					0 as montant_facture_22,

					0 AS montant_facture_actes_inclus_dans_sejour,
					0 as montant_facture_0_actes_inclus_dans_sejour,
					0 as montant_facture_1_actes_inclus_dans_sejour,
					0 as montant_facture_2_actes_inclus_dans_sejour,
					0 as montant_facture_22_actes_inclus_dans_sejour,

					MAX(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN 100-LFAD_TAUX ELSE 0 END) as taux_0,
					MAX(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_TAUX ELSE 0 END) as taux_1,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_2,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_22,

					SUM(LFAD_MTT_CRN) AS montant_comptabilise,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_2,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_22,

					0::bigint AS rubrique_facture_id

				FROM prod_hm.FAC_LIGNE_FACTURE
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRHO::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
					JOIN w_FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
					LEFT JOIN w_FAC_DATEVENTE ON (LECR_ID_FACT_VENT = FACT_ID_FACT)
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
					LEFT JOIN w_FAC_LIGNE_FACTURE_DEBITEUR_compte ON LECR_ID_LFAD = LFAD_ID_LFAD
					LEFT JOIN activite[PX].t_compte ON (LECR_NUM_COMPTE = t_compte.code_original)
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				WHERE
					SEJO_IND_BGH <> '1' AND
					FACT_TYPE <> 'P' AND
					LFAC_ID_PRHO <> 0 AND
					LFAC_CDT_EXC = 'S' AND
					CRN_HON_TO_SEJ <> '1' AND
					LFAD_MTT_CRN <> 0
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,15,16;

				-- Public Honoraires -> Clinique

				INSERT INTO w_FAC_FACTURE_LIGNE_C
				SELECT
					CASE WHEN FAC_HON = '1' THEN 2::integer ELSE 3::integer END AS origine_facturation_id,
					LFAC_ID_LFAC,
					FACT_NUM_FAC AS no_facture,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(LFAC_DAT_EXE_FIN) AS date_fin,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN w_FAC_DATEVENTE.date_vente ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					LFAC_QTE_COEFFICIENT AS nb_rubrique,
					LFAC_QTE_COEFFICIENT AS nb_prestation,
					1 as coefficient,
					LFAC_COE_MCO_HAD AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
					LFAC_PRI_UNITAIRE AS prix_unitaire,

					MAX(LFAC_COD_LPP) AS LFAC_COD_LPP,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id,

					SUM(CASE WHEN FAC_HON = '1' THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_facture,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) as montant_facture_0,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_1,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_2,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_22,

					SUM(CASE WHEN FAC_HON <> '1' THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_facture_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) as montant_facture_0_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_1_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_2_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END)  as montant_facture_22_actes_inclus_dans_sejour,

					MAX(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN 100-LFAD_TAUX ELSE 0 END) as taux_0,
					MAX(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_TAUX ELSE 0 END) as taux_1,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_2,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_22,


					SUM(LFAD_MTT_CRN) AS montant_comptabilise,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_2,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_22,

					0::bigint AS rubrique_facture_id

				FROM prod_hm.FAC_LIGNE_FACTURE
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRHO::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
					JOIN w_FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
					LEFT JOIN w_FAC_DATEVENTE ON (LECR_ID_FACT_VENT = FACT_ID_FACT)
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
					LEFT JOIN w_FAC_LIGNE_FACTURE_DEBITEUR_compte ON LECR_ID_LFAD = LFAD_ID_LFAD
					LEFT JOIN activite[PX].t_compte ON (LECR_NUM_COMPTE = t_compte.code_original)
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					FACT_TYPE <> 'P' AND
					LFAC_ID_PRHO <> 0 AND
					CRN_HON_TO_SEJ = '1'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,15,16;

				UPDATE w_FAC_FACTURE_LIGNE_C
				SET lpp_id = t_lpp.oid
				FROM base.t_lpp
				WHERE LFAC_COD_LPP = t_lpp.code
				;

				UPDATE w_FAC_FACTURE_LIGNE_C
				SET ucd_id = t_ucd.oid
				FROM prod_hm.FAC_LIGNE_FACTURE_UCD
				JOIN base.t_ucd ON LFUC_COD_UCD = t_ucd.code
				WHERE LFAC_ID_LFAC = LFUC_ID_LFAC
				;

				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_FAC_FACTURE_LIGNE_C');

				-- lignes clinique
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_8');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,

					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,

					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour)

				SELECT
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestations,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_sortie_id,

					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,

					0,
					0,
					0,
					0,
					0,

					origine_facturation_id,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour

				FROM w_FAC_FACTURE_LIGNE_C;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_8');




				UPDATE activite[PX].p_factures_lignes_c
				SET nb_prestation = coefficient * nb_prestation,
					nb_rubrique = coefficient * nb_prestation,
					coefficient = 1
                FROM activite.t_prestations
				WHERE prestation_id = t_prestations.oid AND
                    coefficient > 1 AND
                    (
					prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'PHJ', 'SSM', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO'))
                    OR
                    type_ventilation_jour = '1'
                    );


				-- Eclatement des supplements par jour
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					p_factures_lignes_c.CTID AS from_CTID,
					t_prestations.code AS prestation_code,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_entree) ELSE p_factures_lignes_c.date_debut END AS date_debut_ghs,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_sortie - interval '1 day') ELSE p_factures_lignes_c.date_fin END AS date_fin_ghs,
					(date(date_sortie) - date(date_entree)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_debut WHEN t_prestations.code = 'GHS' THEN date(date_entree + interval '1 day') ELSE date(p_factures_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_fin WHEN t_prestations.code = 'GHS' THEN date(p_sejours.date_sortie - interval '1 day') ELSE date(p_factures_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
					ABS(CASE WHEN type_sejour <> '5' AND t_prestations.code = 'GHS' THEN date(date_sortie) - date(date_entree) ELSE nb_prestation END) AS nb_det,
					p_factures_lignes_c.*
				FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND
						(
						code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						t_prestations.type_ventilation_jour = '1'
						)
				WHERE (nb_prestation > 1 or nb_prestation < -1 OR (type_sejour <> '5' AND t_prestations.code = 'GHS' AND date(date_sortie) - date(date_entree) > 1)) ;



				UPDATE w_factures_lignes_sup_c SET
					date_fin_ghs = date(date_debut_exh - interval '1 day'),
					date_fin_det = date(date_debut_exh - interval '1 day'),
					nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1,
					nb_det = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
				FROM (
					SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
					FROM activite[PX].p_factures_lignes_c
						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
					GROUP BY 1) subview
				WHERE w_factures_lignes_sup_c.no_facture = subview.no_facture AND
					prestation_code = 'GHS';

				CREATE INDEX w_factures_lignes_sup_c_i1
				  ON w_factures_lignes_sup_c
				  USING btree
				  (date_debut);

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup AS
				SELECT
					from_CTID,
					no_facture,
					date AS date_debut,
					date AS date_fin,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					round(montant_facture / ABS(nb_det),2) AS montant_facture,
					round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
					round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
					round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
					round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					round(montant_comptabilise / ABS(nb_det),2) AS montant_comptabilise,
					round(montant_comptabilise_0 / ABS(nb_det),2) AS montant_comptabilise_0,
					round(montant_comptabilise_1 / ABS(nb_det),2) AS montant_comptabilise_1,
					round(montant_comptabilise_2 / ABS(nb_det),2) AS montant_comptabilise_2,
					round(montant_comptabilise_22 / ABS(nb_det),2) AS montant_comptabilise_22,
					round(montant_encours / ABS(nb_det),2) AS montant_encours,
					round(montant_encours_0 / ABS(nb_det),2) AS montant_encours_0,
					round(montant_encours_1 / ABS(nb_det),2) AS montant_encours_1,
					round(montant_encours_2 / ABS(nb_det),2) AS montant_encours_2,
					round(montant_encours_22 / ABS(nb_det),2) AS montant_encours_22,
					round(montant_facture_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_actes_inclus_dans_sejour,
					round(montant_facture_0_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_0_actes_inclus_dans_sejour,
					round(montant_facture_1_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_1_actes_inclus_dans_sejour,
					round(montant_facture_2_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_2_actes_inclus_dans_sejour,
					round(montant_facture_22_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					round(montant_comptabilise_budget_global_1 / ABS(nb_det),2) AS montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_det AND date_fin_det
				;

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

				SELECT from_CTID,
					SUM(nb_rubrique) AS nb_rubrique,
					SUM(nb_prestation) AS nb_prestation,
					SUM(montant_facture) AS montant_facture,
					SUM(montant_facture_0) AS montant_facture_0,
					SUM(montant_facture_1) AS montant_facture_1,
					SUM(montant_facture_2) AS montant_facture_2,
					SUM(montant_facture_22) AS montant_facture_22,
					SUM(montant_comptabilise) AS montant_comptabilise,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22,
					SUM(montant_encours) AS montant_encours,
					SUM(montant_encours_0) AS montant_encours_0,
					SUM(montant_encours_1) AS montant_encours_1,
					SUM(montant_encours_2) AS montant_encours_2,
					SUM(montant_encours_22) AS montant_encours_22,
					SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
					SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
					SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
					SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
					SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup
				GROUP BY 1;


				UPDATE activite[PX].p_factures_lignes_c
				SET
					date_fin = p_factures_lignes_c.date_debut,
					nb_rubrique = p_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_sup_tot.nb_rubrique,
					nb_prestation = p_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_sup_tot.nb_prestation,
					montant_facture = p_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_sup_tot.montant_facture,
					montant_facture_0 = p_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = p_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = p_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = p_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = p_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = p_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = p_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = p_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = p_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_22,
					montant_encours = p_factures_lignes_c.montant_encours - w_factures_lignes_sup_c_sup_tot.montant_encours,
					montant_encours_0 = p_factures_lignes_c.montant_encours_0 - w_factures_lignes_sup_c_sup_tot.montant_encours_0,
					montant_encours_1 = p_factures_lignes_c.montant_encours_1 - w_factures_lignes_sup_c_sup_tot.montant_encours_1,
					montant_encours_2 = p_factures_lignes_c.montant_encours_2 - w_factures_lignes_sup_c_sup_tot.montant_encours_2,
					montant_encours_22 = p_factures_lignes_c.montant_encours_22 - w_factures_lignes_sup_c_sup_tot.montant_encours_22,
					montant_facture_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_0_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_1_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_2_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_22_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_22_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_1 = p_factures_lignes_c.montant_comptabilise_budget_global_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup_tot
				WHERE p_factures_lignes_c.CTID = from_CTID;

				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_sup_c_sup');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id)
				SELECT
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c_sup;



				UPDATE activite[PX].p_factures_lignes_c
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_factures, activite[PX].p_mouvements_sejour
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
					activite[PX].p_factures_lignes_c.date_debut = p_mouvements_sejour.date AND
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					p_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id;










				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour;
				CREATE TEMP TABLE w_actes_inclus_dans_sejour AS
				SELECT FACT_NUM_FAC_SEJ AS no_facture,
					SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
					SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
					SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
					SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
					SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour
				FROM activite[PX].p_factures_lignes_c JOIN w_FAC_FACTURE ON no_facture = FACT_NUM_FAC
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					montant_facture_actes_inclus_dans_sejour <> 0 AND
					origine_facturation_id = 3
				GROUP BY 1;

				DROP TABLE IF EXISTS w_ghs_pj;
				CREATE TEMP TABLE w_ghs_pj AS
				SELECT p_factures_lignes_c.no_facture,
					p_sejours.no_sejour,
					p_sejours.est_budget_global,
					MIN(p_factures_lignes_c.ctid) AS ctid_min
				FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					origine_facturation_id = 1 AND
					(
						prestation_id IN (SELECT oid FROM activite.t_prestations where code IN ('PJ', 'PJ1', 'PJ2', 'GHS', 'AMP5')) OR
						rubrique_facturation_id IN (SELECT oid FROM activite[PX].t_rubriques_facturation where actes_inclus_public = '1')
					)
				GROUP BY 1,2,3;



				UPDATE activite[PX].p_factures_lignes_c
				SET
					montant_facture_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = 0 - w_actes_inclus_dans_sejour.montant_facture_22_actes_inclus_dans_sejour
				FROM w_actes_inclus_dans_sejour, w_ghs_pj
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					p_factures_lignes_c.no_facture = w_ghs_pj.no_facture AND p_factures_lignes_c.ctid = w_ghs_pj.ctid_min AND
					w_actes_inclus_dans_sejour.no_facture = p_factures_lignes_c.no_facture AND
					(
						prestation_id IN (SELECT oid FROM activite.t_prestations where code IN ('PJ', 'GHS', 'AMP5')) OR
						rubrique_facturation_id IN (SELECT oid FROM activite[PX].t_rubriques_facturation where actes_inclus_public = '1')
					);



				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour_t;
				CREATE TEMP TABLE w_actes_inclus_dans_sejour_t AS
				SELECT no_facture,
					SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_actes_inclus_dans_sejour ELSE 0 END) AS montant_facture_c_actes_inclus_dans_sejour,
					SUM(CASE WHEN origine_facturation_id = 3 THEN montant_facture_actes_inclus_dans_sejour ELSE 0 END) AS montant_facture_h_actes_inclus_dans_sejour
				FROM activite[PX].p_factures_lignes_c
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					montant_facture_actes_inclus_dans_sejour <> 0
				GROUP BY 1;


				UPDATE activite[PX].p_factures SET
					montant_facture_c_actes_inclus_dans_sejour = w_actes_inclus_dans_sejour_t.montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour = w_actes_inclus_dans_sejour_t.montant_facture_h_actes_inclus_dans_sejour
				FROM w_actes_inclus_dans_sejour_t
				WHERE
					'[ENV_TYPEETS]' IN ('2','3') AND
					w_actes_inclus_dans_sejour_t.no_facture = p_factures.no_facture;





				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_factures_lignes_sup_c CASCADE;
				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot CASCADE;
				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup CASCADE;
				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour CASCADE;
				DROP TABLE IF EXISTS w_ghs_pj CASCADE;
				DROP TABLE IF EXISTS w_actes_inclus_dans_sejour_t CASCADE;



			]]></sqlcmd>
	</NODE>


	<NODE label="Budget global MCO">
		<condition><![CDATA[
				"[ENV_TYPEETS]" != "1" && "[ENV_WITHPMSI]" == "1"
			]]></condition>
		<sqlcmd><![CDATA[

				SELECT activite[PX].cti_reorganize_sejour_pmsi()
				;

                -- Montants depuis PMSI

				-- Mise à jour date début PMSI pour EXH
				UPDATE pmsi.p_rsf_detail
				SET date_debut = date_debut_new
				FROM
				(
				SELECT rss_id, prestation_id, date_debut, date_fin, nombre, date(date_sortie - (nombre||' days')::interval) AS date_debut_new
				FROM pmsi.p_rsf_detail
				JOIN pmsi.t_prestations on prestation_id = t_prestations.oid
				JOIN pmsi.p_rss ON rss_id = p_rss.oid
				WHERE t_prestations.code = 'EXH' AND
					date_debut = date_entree AND
					date(date_sortie - (nombre||' days')::interval) > date_entree
				) subview
				WHERE p_rsf_detail.rss_id = subview.rss_id AND
					p_rsf_detail.prestation_id = subview.prestation_id AND
					p_rsf_detail.date_debut = subview.date_debut AND
					p_rsf_detail.date_fin = subview.date_fin AND
					p_rsf_detail.nombre = subview.nombre
				;

                UPDATE pmsi.p_rss
                SET no_sejour_administratif =
                    CASE WHEN SEJO_DAT_SUP IS NULL AND
                        SEJO_IND_INCOMPLET IS DISTINCT FROM '1' AND
                        p_rss.date_sortie = date(SEJO_DAT_FIN)
                    THEN sejo_num_sej ELSE no_sejour_administratif END
                FROM prod_hm.pms_rss
                JOIN w_IDE_SEJOUR_complet ON trss_id_sejo_d = sejo_id_sejo
                WHERE p_rss.no_rss = TRSS_NUMERO AND ghm_id <> 0 AND
                    no_sejour_administratif IS DISTINCT FROM
                    CASE WHEN SEJO_DAT_SUP IS NULL AND
                        SEJO_IND_INCOMPLET IS DISTINCT FROM '1' AND
                        p_rss.date_sortie = date(SEJO_DAT_FIN)
                    THEN sejo_num_sej ELSE no_sejour_administratif END
                ;



                UPDATE pmsi.p_rss
                SET no_sejour_administratif = SEJO_NUM_SEJ
                FROM w_IDE_SEJOUR_complet
                WHERE p_rss.date_entree = date(SEJO_DAT_DEB) AND p_rss.date_sortie = date(SEJO_DAT_FIN) AND
                    SEJO_NUM_SEJ LIKE '%' || no_sejour_administratif AND SEJO_DAT_SUP IS NULL AND SEJO_IND_INCOMPLET IS DISTINCT FROM '1' AND
                    no_sejour_administratif IS DISTINCT FROM SEJO_NUM_SEJ
                ;



                DROP TABLE IF EXISTS w_factures_lignes_bg;

                CREATE TEMP TABLE w_factures_lignes_bg AS
                SELECT
					trim(p_rss.no_sejour_administratif) AS no_sejour_administratif,
					p_rss.date_sortie AS date_sortie_pmsi,
					p_rss.date_entree AS date_entree_pmsi,
					p_rss.date_naissance AS date_naissance_pmsi,
                    NULL::text AS no_sejour,
                    NULL::text AS no_facture,
                    NULL::bigint AS lieu_id,
                    NULL::date AS date_debut_facture,
                    NULL::date AS date_fin_facture,
                    NULL::date AS date_sortie,
                    NULL::bigint AS tiers_payant_0_id,
                    NULL::bigint AS tiers_payant_1_id,
                    0 AS tiers_payant_2_id,
                    0 AS tiers_payant_22_id,
                    NULL::bigint AS ghs_id,
                    NULL::bigint AS ghs_bebe1_id,
                    NULL::bigint AS ghs_bebe2_id,
                    NULL::bigint AS ghs_bebe3_id,

                    p_rsf_detail.date_debut AS date_debut,
                    p_rsf_detail.date_fin AS date_fin,

                    trim(replace(replace(t_prestations_pmsi.code, ' F', ''), ' N', '')) AS prestation_code,

                    p_rsf_detail.nombre,
                    p_rsf_detail.coefficient,
                    p_rsf_detail.coefficient_mco,
                    p_rsf_detail.prix_unitaire,
                    p_rsf_detail.taux_remboursement,

                    round(p_rsf_detail.sejour_remboursable,2) AS montant_comptabilise_budget_global_c
				FROM pmsi.p_rss
				JOIN pmsi.p_rsf_detail ON p_rss.oid = p_rsf_detail.rss_id
					JOIN activite.t_divers ON t_divers.code = 'EXCLUSIONPRESTATIONPMSI'
					JOIN pmsi.t_prestations t_prestations_pmsi ON prestation_id = t_prestations_pmsi.oid AND t_prestations_pmsi.code != ALL(string_to_array(replace(replace(t_divers.valeur,' ',''), '-', ' '),','))
					JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement IN ('2','3')
				WHERE p_rss.traitement_epmsi IN ('30','31','32','33') AND
					en_cours = '0' AND
					p_rss.etat = ''AND
					p_rss.date_sortie >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					fides_detail <> 1 AND
					p_rsf_detail.est_ligne_rss = '1'
				;

				ANALYSE w_factures_lignes_bg
				;

				CREATE INDEX i_w_factures_lignes_bg_1
					ON w_factures_lignes_bg
					USING btree
					(no_sejour_administratif);

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
				WHERE no_sejour_administratif = p_sejours.no_sejour AND
					date_trunc('month',date_sortie_pmsi) = date_trunc('month',p_sejours.date_sortie)AND
					date_naissance_pmsi = p_patients.date_naissance
				;

				CREATE INDEX i_w_factures_lignes_bg_2
					ON w_factures_lignes_bg
					USING btree
					(no_sejour);

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = p_sejours.no_sejour AND
					date_trunc('month',date_sortie_pmsi) = date_trunc('month',p_sejours.date_sortie) AND
					w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = substr(p_sejours.no_sejour,2) AND
					date_trunc('month',date_sortie_pmsi) = date_trunc('month',p_sejours.date_sortie) AND
					w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = p_sejours.no_sejour AND
					date_entree_pmsi = date_entree AND
					w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = substr(p_sejours.no_sejour,2) AND
					date_entree_pmsi= date_entree AND
					w_factures_lignes_bg.no_sejour IS NULL
				;


				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
				WHERE no_sejour_administratif = substr(p_sejours.no_sejour,2) AND
					date_naissance_pmsi = p_patients.date_naissance AND
					w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg SET
					no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = substr(p_sejours.no_sejour,2) AND
					w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg 
				SET no_sejour = p_sejours.no_sejour
				FROM activite[PX].p_sejours
				WHERE no_sejour_administratif = p_sejours.no_sejour
					AND w_factures_lignes_bg.no_sejour IS NULL
				;

				UPDATE w_factures_lignes_bg SET
					no_facture = w_factures_lignes_bg.no_sejour || '.BG',
					lieu_id = p_sejours.lieu_sortie_id,
					date_debut_facture = p_sejours.date_entree,
					date_fin_facture = p_sejours.date_sortie,
					date_sortie = p_sejours.date_sortie,
					tiers_payant_0_id = p_sejours.tiers_payant_0_id,
					tiers_payant_1_id = p_sejours.tiers_payant_1_id,
					ghs_id = p_sejours.ghs_id,
					ghs_bebe1_id = p_sejours.ghs_bebe1_id,
					ghs_bebe2_id = p_sejours.ghs_bebe2_id,
					ghs_bebe3_id = p_sejours.ghs_bebe3_id
				FROM activite[PX].p_sejours
				WHERE w_factures_lignes_bg.no_sejour = p_sejours.no_sejour
				;

				DELETE FROM w_factures_lignes_bg
				WHERE no_sejour IS NULL
				;

				ANALYSE w_factures_lignes_bg
				;


            UPDATE w_factures_lignes_bg
            SET lieu_id = p_mouvements_sejour.lieu_id
            FROM activite[PX].p_mouvements_sejour
            WHERE
                w_factures_lignes_bg.no_sejour = p_mouvements_sejour.no_sejour AND
                w_factures_lignes_bg.date_debut = p_mouvements_sejour.date AND
                (p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
                w_factures_lignes_bg.lieu_id <> p_mouvements_sejour.lieu_id
            ;


            INSERT INTO activite[PX].p_factures(
                no_sejour,
                no_facture,
                no_facture_reference,
                date_debut,
                date_fin,
                type_facture,
                code_facture,
                date_facture,
                code_vente,
                date_vente,
                mois_vente,
                date_solde,
                montant_facture_c,
                montant_facture_h,
                montant_regle_c,
                montant_regle_h,
                delai_facture,
                delai_solde,
                date_expedition,
                delai_expedition,
                tiers_payant_0_id,
                tiers_payant_1_id,
                tiers_payant_2_id,
                tiers_payant_22_id,
                date_solde_0_c,
                date_solde_0_h,
                date_solde_1_c,
                date_solde_1_h,
                date_solde_2_c,
                date_solde_2_h,
                date_solde_22_c,
                date_solde_22_h,
                date_expedition_0,
                date_expedition_1,
                date_expedition_2,
                date_expedition_22,
                code_expedie_0,
                code_expedie_1,
                code_expedie_2,
                code_expedie_22,
                no_bordereau_0,
                no_bordereau_1,
                no_bordereau_2,
                no_bordereau_22,
                montant_facture_0_c,
                montant_facture_0_h,
                montant_facture_1_c,
                montant_facture_1_h,
                montant_facture_2_c,
                montant_facture_2_h,
                montant_facture_22_c,
                montant_facture_22_h,
                montant_regle_0_c,
                montant_regle_0_h,
                montant_regle_1_c,
                montant_regle_1_h,
                montant_regle_2_c,
                montant_regle_2_h,
                montant_regle_22_c,
                montant_regle_22_h,
                delai_expedition_0,
                delai_expedition_1,
                delai_expedition_2,
                delai_expedition_22,
                delai_solde_0_c,
                delai_solde_0_h,
                delai_solde_1_c,
                delai_solde_1_h,
                delai_solde_2_c,
                delai_solde_2_h,
                delai_solde_22_c,
                delai_solde_22_h,
                ghs_id,
                particularite_t2a,
                code_cloture,
                code_cp_demandee,
                ghs_bebe1_id,
                ghs_bebe2_id,
                ghs_bebe3_id,

                montant_comptabilise_c,
                montant_comptabilise_h,
                montant_comptabilise_0_c,
                montant_comptabilise_0_h,
                montant_comptabilise_1_c,
                montant_comptabilise_1_h,
                montant_comptabilise_2_c,
                montant_comptabilise_2_h,
                montant_comptabilise_22_c,
                montant_comptabilise_22_h,

                nb_rejets,

                montant_facture_c_actes_inclus_dans_sejour,
                montant_facture_h_actes_inclus_dans_sejour,

                montant_comptabilise_budget_global_c
                )

            SELECT
                no_sejour,
                no_facture,
                no_facture,
                date_debut_facture AS date_debut,
                date_fin_facture AS date_fin,
                'G' AS type_facture,
                '1' AS code_facture,
                date_sortie AS date_facture,
                '1' AS code_vente,
                date_sortie AS date_vente,
                extract('year' FROM date_sortie) * 100 + extract('month' FROM date_sortie),
                date_sortie AS date_solde,
                SUM(montant_comptabilise_budget_global_c) AS montant_facture_c,
                0 AS montant_facture_h,
                0 AS montant_regle_c,
                0 AS montant_regle_h,
                0 AS delai_facture,
                0 AS delai_solde,
                date_sortie AS date_expedition,
                0 AS delai_expedition,
                tiers_payant_0_id,
                tiers_payant_1_id,
                tiers_payant_2_id,
                tiers_payant_22_id,
                date_sortie AS date_solde_0_c,
                date_sortie AS date_solde_0_h,
                date_sortie AS date_solde_1_c,
                date_sortie AS date_solde_1_h,
                date_sortie AS date_solde_2_c,
                date_sortie AS date_solde_2_h,
                date_sortie AS date_solde_22_c,
                date_sortie AS date_solde_22_h,
                date_sortie AS date_expedition_0,
                date_sortie AS date_expedition_1,
                date_sortie AS date_expedition_2,
                date_sortie AS date_expedition_22,
                '1' AS code_expedie_0,
                '1' AS code_expedie_1,
                '1' AS code_expedie_2,
                '1' AS code_expedie_22,
                '' AS no_bordereau_0,
                '' AS no_bordereau_1,
                '' AS no_bordereau_2,
                '' AS no_bordereau_22,
                0 AS montant_facture_0_c,
                0 AS montant_facture_0_h,
                SUM(montant_comptabilise_budget_global_c) AS montant_facture_1_c,
                0 AS montant_facture_1_h,
                0 AS montant_facture_2_c,
                0 AS montant_facture_2_h,
                0 AS montant_facture_22_c,
                0 AS montant_facture_22_h,
                0 AS montant_regle_0_c,
                0 AS montant_regle_0_h,
                0 AS montant_regle_1_c,
                0 AS montant_regle_1_h,
                0 AS montant_regle_2_c,
                0 AS montant_regle_2_h,
                0 AS montant_regle_22_c,
                0 AS montant_regle_22_h,
                0 AS delai_expedition_0,
                0 AS delai_expedition_1,
                0 AS delai_expedition_2,
                0 AS delai_expedition_22,
                0 AS delai_solde_0_c,
                0 AS delai_solde_0_h,
                0 AS delai_solde_1_c,
                0 AS delai_solde_1_h,
                0 AS delai_solde_2_c,
                0 AS delai_solde_2_h,
                0 AS delai_solde_22_c,
                0 AS delai_solde_22_h,
                ghs_id AS ghs_id,
                '' AS particularite_t2a,
                '' AS code_cloture,
                '0' AS code_cp_demandee,
                ghs_bebe1_id,
                ghs_bebe2_id,
                ghs_bebe3_id,

                0 AS montant_comptabilise_c,
                0 AS montant_comptabilise_h,
                0 AS montant_comptabilise_0_c,
                0 AS montant_comptabilise_0_h,
                0 AS montant_comptabilise_1_c,
                0 AS montant_comptabilise_1_h,
                0 AS montant_comptabilise_2_c,
                0 AS montant_comptabilise_2_h,
                0 AS montant_comptabilise_22_c,
                0 AS montant_comptabilise_22_h,

                0 AS nb_rejets,

                0 AS montant_facture_c_actes_inclus_dans_sejour,
                0 AS montant_facture_h_actes_inclus_dans_sejour,

                SUM(montant_comptabilise_budget_global_c)

                FROM w_factures_lignes_bg
                GROUP BY no_sejour,
                    no_facture,
                    date_debut_facture,
                    date_fin_facture,
                    date_sortie,
                    tiers_payant_0_id,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id
                ;



                INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
                SELECT prestation_code, prestation_code, prestation_code, prestation_code
                FROM w_factures_lignes_bg
                    LEFT JOIN activite.t_prestations ON prestation_code = t_prestations.code
                WHERE t_prestations.code IS NULL
                GROUP BY prestation_code
                ;

				UPDATE activite[PX].t_rubriques_facturation
				SET code = PRSE_CODE,
					texte = PRSE_LIBELLE,
					texte_court = PRSE_LIBELLE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE PRSE_ID_PRSE::bigint = code_original
				;

                INSERT INTO activite[PX].t_rubriques_facturation(code, code_original, texte, texte_court)
                SELECT prestation_code, prestation_code, prestation_code, prestation_code
                FROM w_factures_lignes_bg
                    LEFT JOIN activite[PX].t_rubriques_facturation ON prestation_code = t_rubriques_facturation.code
                WHERE t_rubriques_facturation.code IS NULL
                GROUP BY prestation_code
                ;

                DROP TABLE IF EXISTS w_rubriques_bg;
				CREATE TEMP TABLE w_rubriques_bg AS
				SELECT code, (MIN(ARRAY[CASE WHEN code <> code_original THEN 0 ELSE 1 END, oid]))[2]::bigint AS oid
				FROM activite.t_rubriques_facturation
				WHERE EXISTS (SELECT prestation_code FROM w_factures_lignes_bg WHERE w_factures_lignes_bg.prestation_code = t_rubriques_facturation.code)
				GROUP BY 1
				;

				ANALYSE w_rubriques_bg
				;


                INSERT INTO activite[PX].p_factures_lignes_c(
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    nb_prestation,
                    coefficient,
                    coefficient_mco,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    compte_produit_id,
                    prestation_id,
                    montant_facture,
                    montant_facture_0,
                    montant_facture_1,
                    montant_facture_2,
                    montant_facture_22,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    prix_unitaire,
                    lieu_id,

                    montant_comptabilise,
                    montant_comptabilise_0,
                    montant_comptabilise_1,
                    montant_comptabilise_2,
                    montant_comptabilise_22,

                    montant_encours,
                    montant_encours_0,
                    montant_encours_1,
                    montant_encours_2,
                    montant_encours_22,

                    origine_facturation_id,
                    montant_facture_actes_inclus_dans_sejour,
                    montant_facture_0_actes_inclus_dans_sejour,
                    montant_facture_1_actes_inclus_dans_sejour,
                    montant_facture_2_actes_inclus_dans_sejour,
                    montant_facture_22_actes_inclus_dans_sejour,
                    montant_comptabilise_budget_global_1)

                SELECT

                    no_facture,
                    date_debut,
                    date_fin,
                    nombre AS nb_rubrique,
                    nombre AS nb_prestation,
                    coefficient AS coefficient,
                    coefficient_mco AS coefficient_mco,
                    COALESCE(w_rubriques_bg.oid,0) AS rubrique_facturation_id,
                    COALESCE(w_rubriques_bg.oid,0) AS rubrique_comptabilisation_id,
                    0::bigint AS compte_produit_id,
                    COALESCE(t_prestations.oid,0) AS prestation_id,
                    montant_comptabilise_budget_global_c AS montant_facture,
                    0 AS montant_facture_0,
                    montant_comptabilise_budget_global_c AS montant_facture_1,
                    0 AS montant_facture_2,
                    0 AS montant_facture_22,

                    0 AS taux_0,
                    taux_remboursement AS taux_1,
                    0 AS taux_2,
                    0 AS taux_22,
                    prix_unitaire,
                    lieu_id,

                    0 AS montant_comptabilise,
                    0 AS montant_comptabilise_0,
                    0 AS montant_comptabilise_1,
                    0 AS montant_comptabilise_2,
                    0 AS montant_comptabilise_22,

                    0 AS montant_encours,
                    0 AS montant_encours_0,
                    0 AS montant_encours_1,
                    0 AS montant_encours_2,
                    0 AS montant_encours_22,

                    1 AS origine_facturation_id,
                    0 AS montant_facture_actes_inclus_dans_sejour,
                    0 AS montant_facture_0_actes_inclus_dans_sejour,
                    0 AS montant_facture_1_actes_inclus_dans_sejour,
                    0 AS montant_facture_2_actes_inclus_dans_sejour,
                    0 AS montant_facture_22_actes_inclus_dans_sejour,

                    montant_comptabilise_budget_global_c AS montant_comptabilise_budget_global_1

                FROM w_factures_lignes_bg
                    LEFT JOIN activite.t_prestations ON prestation_code = t_prestations.code
                    LEFT JOIN w_rubriques_bg ON prestation_code = w_rubriques_bg.code
                ;



                DROP TABLE IF EXISTS w_factures_ventes_bg;
                CREATE TEMP TABLE w_factures_ventes_bg AS
                SELECT no_sejour, date_debut, date_fin, MAX(date_vente) AS date_vente
                FROM activite[PX].p_factures
                WHERE montant_comptabilise_budget_global_c <> 0
                GROUP BY 1,2,3;

                CREATE INDEX i_factures_ventes_bg_1
                    ON w_factures_ventes_bg
                    USING btree
                    (no_sejour);

                UPDATE activite[PX].p_factures
                SET date_vente= w_factures_ventes_bg.date_vente
                FROM w_factures_ventes_bg
                WHERE p_factures.date_vente = '20991231' AND
                    p_factures.code_facture = '1' AND
                    p_factures.no_sejour = w_factures_ventes_bg.no_sejour AND
                    p_factures.date_fin BETWEEN w_factures_ventes_bg.date_debut AND w_factures_ventes_bg.date_fin
                ;

                DROP TABLE IF EXISTS w_factures_ventes_bg CASCADE
                ;
                DROP TABLE IF EXISTS w_factures_lignes_bg CASCADE
                ;


                -- RAZ montants facturé TP1 sur budget global (générés à tord par HM)
                UPDATE activite[PX].p_factures_lignes_c
                SET montant_facture = montant_facture - montant_facture_1,
                    montant_facture_1 = 0,
                    taux_1 = 0
                FROM prod_hm.FAC_FACTURE
                WHERE p_factures_lignes_c.no_facture = FACT_NUM_FAC AND
                    montant_facture_1 <> 0 AND
                    montant_comptabilise_1 = 0 AND
                    p_factures_lignes_c.no_facture NOT LIKE '%BG%' AND
                    FACT_TYP_BGH = 'B'
                ;

                UPDATE activite[PX].p_factures
                SET montant_facture_c = p_factures.montant_facture_c - p_factures.montant_facture_1_c,
                    montant_facture_1_c = 0
                FROM prod_hm.FAC_FACTURE
                WHERE p_factures.no_facture = FACT_NUM_FAC AND
                    p_factures.montant_facture_1_c <> 0 AND
                    p_factures.montant_comptabilise_1_c = 0 AND
                    p_factures.no_facture NOT LIKE '%BG%' AND
                    FACT_TYP_BGH = 'B'
                ;




                -- En cours PMSI public
                INSERT INTO activite[PX].p_factures(
                    sejour_id,
                    no_sejour,
                    no_facture,
                    no_facture_reference,
                    date_debut,
                    date_fin,
                    type_facture,
                    code_facture,
                    date_facture,
                    tiers_payant_0_id,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id)
                SELECT
                    p_sejours.oid,
                    p_sejours.no_sejour,
                    MAX(p_sejours.no_sejour || '.BG'),
                    MAX(p_sejours.no_sejour || '.BG'),
                    MAX(p_sejours.date_entree),
                    MAX(p_sejours.date_sortie),
                    '0',
                    '0',
                    '20991231'::date,
                    MAX(p_sejours.tiers_payant_0_id),
                    MAX(p_sejours.tiers_payant_1_id),
                    MAX(p_sejours.tiers_payant_2_id),
                    MAX(p_sejours.tiers_payant_22_id),
                    MAX(p_sejours.ghs_id),
                    MAX(p_sejours.ghs_bebe1_id),
                    MAX(p_sejours.ghs_bebe2_id),
                    MAX(p_sejours.ghs_bebe3_id)
                FROM pmsi.p_rss
                JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
                JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
                LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND p_factures.no_facture LIKE '%BG'
                WHERE p_rss.en_cours = '1' AND p_factures.no_facture IS NULL AND
                    p_sejours.type_sejour IN ('1','2','5','6')
                GROUP BY 1,2;

				-- Encours Externes BG avec facturation partielle SE, FFM, ATU
				INSERT INTO activite[PX].p_factures(
                    sejour_id,
                    no_sejour,
                    no_facture,
                    no_facture_reference,
                    date_debut,
                    date_fin,
                    type_facture,
                    code_facture,
                    date_facture,
                    tiers_payant_0_id,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id)
				SELECT p_sejours.oid,
                    p_sejours.no_sejour,
                    p_sejours.no_sejour || '.BG',
                    p_sejours.no_sejour || '.BG',
                    p_sejours.date_entree,
                    p_sejours.date_sortie,
                    '0',
                    '0',
                    '20991231'::date,
                    p_sejours.tiers_payant_0_id,
                    p_sejours.tiers_payant_1_id,
                    p_sejours.tiers_payant_2_id,
                    p_sejours.tiers_payant_22_id,
                    p_sejours.ghs_id,
                    p_sejours.ghs_bebe1_id,
                    p_sejours.ghs_bebe2_id,
                    p_sejours.ghs_bebe3_id
                FROM activite[PX].p_sejours
                JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
                WHERE p_sejours.est_budget_global = '1' AND
                    p_sejours.type_sejour IN ('3') AND
					p_sejours.etat = '' AND
                    date_sortie between date(date_trunc('year',now() - interval '1 year')) AND  now() AND
                    code_sorti = '1' AND
                    no_sejour NOT IN (SELECt no_sejour FROM activite[PX].p_factures where no_facture like '%BG') AND
                    no_sejour IN (
                        SELECT p_factures.no_sejour
                        FROM activite[PX].p_factures_lignes_c
                        JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                        JOIN activite[PX].t_prestations ON prestation_id = t_prestations.oid
                        WHERE p_sejours.est_budget_global = '1' AND
                            code_facture = '1' AND
                            t_prestations.code IN ('SE1','SE2','SE3','SE4','ATU', 'FPU','FFM')
                        GROUP BY 1
                        HAVING SUM(nb_prestation) > 0 AND
							round(base.cti_division(SUM(montant_facture_0+montant_facture_2),SUM(prix_unitaire*nb_prestation*coefficient*coefficient_mco)),2)<=0.21
                    )
				;
				-- Récupération des lignes SE,FFM,ATU facturées à 0 au patient et à la mutuelle pour encours BG
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    rubrique_facturation_id,
                    prestation_id,
                    prix_unitaire,
                    lieu_id,
					coefficient_mco)
				SELECT p_factures_bg.no_facture,
                    p_factures_bg.date_debut,
                    p_factures_bg.date_fin,
                    SUM(p_factures_lignes_c.nb_rubrique),
                    p_factures_lignes_c.coefficient,
                    p_factures_lignes_c.rubrique_facturation_id,
                    p_factures_lignes_c.prestation_id,
                    MAX(p_factures_lignes_c.prix_unitaire),
                    p_factures_lignes_c.lieu_id,
					MAX(p_factures_lignes_c.coefficient_mco)
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				JOIN activite[PX].p_factures p_factures_bg ON
					p_factures_bg.no_facture = p_factures.no_sejour || '.BG' AND
					p_factures_bg.code_facture = '0'
				JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				LEFT JOIN activite[PX].p_factures_lignes_non_facturees_c ON
					p_factures_lignes_non_facturees_c.no_facture = p_factures_bg.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = t_prestations.oid
				WHERE p_sejours.est_budget_global = '1' AND
					p_factures.code_facture = '1' AND
					t_prestations.code IN ('SE1','SE2','SE3','SE4','ATU', 'FPU','FFM') AND
					p_factures_lignes_non_facturees_c.no_facture IS NULL
				GROUP BY 1,2,3,5,6,7,9
				HAVING SUM(nb_prestation) > 0
				;

                -- Sejours BG PMSi qui ne sont pas dans les RSS
                INSERT INTO activite[PX].p_factures(
                    sejour_id,
                    no_sejour,
                    no_facture,
                    no_facture_reference,
                    date_debut,
                    date_fin,
                    type_facture,
                    code_facture,
                    date_facture,
                    tiers_payant_0_id,
                    tiers_payant_1_id,
                    tiers_payant_2_id,
                    tiers_payant_22_id,
                    ghs_id,
                    ghs_bebe1_id,
                    ghs_bebe2_id,
                    ghs_bebe3_id)
                SELECT p_sejours.oid,
                    p_sejours.no_sejour,
                    p_sejours.no_sejour || '.BG',
                    p_sejours.no_sejour || '.BG',
                    p_sejours.date_entree,
                    p_sejours.date_sortie,
                    '0',
                    '0',
                    '20991231'::date,
                    p_sejours.tiers_payant_0_id,
                    p_sejours.tiers_payant_1_id,
                    p_sejours.tiers_payant_2_id,
                    p_sejours.tiers_payant_22_id,
                    p_sejours.ghs_id,
                    p_sejours.ghs_bebe1_id,
                    p_sejours.ghs_bebe2_id,
                    p_sejours.ghs_bebe3_id
                FROM activite[PX].p_sejours
                JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
                WHERE p_sejours.est_budget_global = '1' AND
                    p_sejours.type_sejour IN ('1','2','5') AND
                    type_t2a = '1' AND
                    date_sortie between date(date_trunc('year',now() - interval '1 year')) AND  now() AND
                    code_sorti = '1' AND
                    no_sejour NOT IN (SELECt no_sejour FROm activite[PX].p_factures where no_facture like '%BG') AND
                    no_sejour NOT IN (
                        SELECT p_factures.no_sejour
                        FROM activite[PX].p_factures_lignes_c
                        JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                        JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                        JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                        WHERE p_sejours.est_budget_global = '1' AND
                            code_facture = '1' AND
                            t_prestations.code = 'PJ' AND
                            (taux_2 = 100 OR taux_0 = 100)
                        GROUP BY 1
                        HAVING SUM(montant_facture_0+montant_facture_2) > 0
                    );




				-- Récupération lignes non facturées pour les factures BG
                INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                    no_facture,
                    date_debut,
                    date_fin,
                    nb_rubrique,
                    coefficient,
                    rubrique_facturation_id,
                    prestation_id,
                    prix_unitaire,
                    lieu_id)
                SELECT
                        p_factures.no_facture,
                        date(LFAC_DAT_EXE_DEB) AS date_debut,
                        date(COALESCE(LFAC_DAT_EXE_FIN, LFAC_DAT_EXE_DEB)) AS date_fin,
                        MAX(LFAC_QTE_COEFFICIENT) AS nb_rubrique,
                        1 AS coefficient,
                        MAX(t_rubriques_facturation.oid) AS rubrique_facturation_id,
                        MAX(t_prestations.oid) AS prestation_id,
                        CASE
                            WHEN MIN(LFAD_IND_BGH) = '1' THEN MAX(LFAC_PRI_UNITAIRE)
                            ELSE base.cti_division(SUM(CASE WHEN LFAD_IND_BGH = '1' THEN LFAD_MTT_HOR_DEH ELSE 0 END) , MAX(LFAC_QTE_COEFFICIENT)) END
                                AS prix_unitaire,
                        MAX(p_sejours.lieu_sortie_id) AS lieu_id
                    FROM prod_hm.FAC_LIGNE_FACTURE
                        JOIN prod_hm.FAC_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT AND FACT_TYPE = 'P'
                        JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
                        JOIN activite[PX].p_sejours ON LFAC_ID_SEJO_D::bigint = p_sejours.code_original AND p_sejours.etat = ''
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND code_facture = '0' AND p_factures.no_facture LIKE '%BG'
                        JOIN activite[PX].t_rubriques_facturation ON LFAC_ID_PRSE::bigint = t_rubriques_facturation.code_original
                        JOIN activite.t_prestations ON LFAC_LET_CLE = t_prestations.code
						LEFT JOIN activite[PX].p_factures_lignes_non_facturees_c ON
							p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture AND
							p_factures_lignes_non_facturees_c.prestation_id = t_prestations.oid
                    WHERE LFAC_LET_CLE NOT IN ('GHS','PJ') AND LFAC_ID_PRSE <> 0 AND
                        FACT_DAT_SUP IS NULL AND
                        date(LFAC_DAT_EXE_DEB) BETWEEN p_factures.date_debut AND p_factures.date_fin AND
					p_factures_lignes_non_facturees_c.no_facture IS NULL
                    GROUP BY 1,2,3, LFAC_ID_LFAC
					HAVING MIN(LFAD_IND_BGH) = '1'
                ;

				-- Il peut y avoir des lignes en double avec la récupération standard
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
				USING
				(
					SELECT no_sejour, prestation_id,
						p_factures_lignes_non_facturees_c.date_debut,
						p_factures_lignes_non_facturees_c.date_fin,
						p_factures_lignes_non_facturees_c.prix_unitaire,
						MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.BG' THEN p_factures_lignes_non_facturees_c.no_facture ELSE NULL END) AS no_facture
					FROm activite[PX].p_factures_lignes_non_facturees_c
					JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5
					HAVING count(DISTINCT p_factures.no_facture) > 1 AND
						MAX(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 1 AND
						MIN(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 0
				) subview
				WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id AND
					p_factures_lignes_non_facturees_c.date_debut = subview.date_debut AND
					p_factures_lignes_non_facturees_c.date_fin = subview.date_fin AND
					p_factures_lignes_non_facturees_c.prix_unitaire = subview.prix_unitaire
				;

				-- Il peut y avoir des lignes en double avec la récupération standard
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
				USING
				(
					SELECT no_sejour, prestation_id,
						p_factures_lignes_non_facturees_c.date_debut,
						p_factures_lignes_non_facturees_c.date_fin,
						p_factures_lignes_non_facturees_c.prix_unitaire,
						MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.BG' THEN p_factures_lignes_non_facturees_c.no_facture ELSE NULL END) AS no_facture
					FROm activite[PX].p_factures_lignes_non_facturees_c
					JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5
					HAVING count(DISTINCT p_factures.no_facture) > 1 AND
						MAX(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 1 AND
						MIN(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 0
				) subview
				WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id AND
					p_factures_lignes_non_facturees_c.date_debut = subview.date_debut AND
					p_factures_lignes_non_facturees_c.date_fin = subview.date_fin AND
					p_factures_lignes_non_facturees_c.prix_unitaire = subview.prix_unitaire
				;

				-- Ou des lignes en double avec la facturation
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
				USING
				(
					SELECT no_sejour, prestation_id,
						p_factures_lignes_non_facturees_c.date_debut,
						p_factures_lignes_non_facturees_c.date_fin,
						MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.BG' THEN p_factures_lignes_non_facturees_c.no_facture ELSE NULL END) AS no_facture
					FROm activite[PX].p_factures_lignes_non_facturees_c
					JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4
				) subview
				JOIN
				(
					SELECT no_sejour, prestation_id,
						p_factures_lignes_c.date_debut,
						p_factures_lignes_c.date_fin,
						p_factures.no_facture
					FROm activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5
				) subview2
				ON  subview2.no_sejour = subview.no_sejour AND
					subview2.prestation_id = subview.prestation_id AND
					subview2.date_debut = subview.date_debut AND
					subview2.date_fin = subview.date_fin
				WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id AND
					p_factures_lignes_non_facturees_c.date_debut = subview.date_debut AND
					p_factures_lignes_non_facturees_c.date_fin = subview.date_fin
				;

                -- Factures non assurés ajoutées à tord (on trouve un 100% dans patient ou tp1
                DROP TABLE IF EXISTS w_sejours_bg_24;
                CREATE TEMP TABLE w_sejours_bg_24 AS
                SELECT 
                	p_factures.no_sejour, 
                	SUM(montant_facture_0+montant_facture_1+montant_facture_2) AS montant_facture_100
                FROM activite[PX].p_factures_lignes_c
                JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN activite.t_prestations ON prestation_id = t_prestations.oid
                LEFT JOIN pmsi.p_rss ON p_factures.no_sejour = p_rss.no_sejour_administratif 
					AND p_rss.traitement_epmsi IN ('30','31','32','33') 
					AND p_rss.etat = ''
                WHERE p_sejours.est_budget_global = '1' 
                    AND code_facture = '1' 
                    AND t_prestations.code = 'PJ' 
                    AND (taux_1 + taux_2 + taux_0 = 100 
                    	OR taux_0+taux_1+taux_2=0 AND (montant_facture_1+montant_facture_2+montant_facture_0) = montant_facture
                    ) 
                    AND p_rss.oid IS NULL 
					AND montant_facture <> 0
					AND p_factures.no_facture NOT LIKE '%BG'
                GROUP BY p_factures.no_sejour
                HAVING SUM(montant_facture_0+montant_facture_1+montant_facture_2) > 0
                ORDER BY p_factures.no_sejour
                ;

                DELETE FROM activite[PX].p_factures_lignes_c
                USING activite[PX].p_factures
                WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
                    p_factures.no_sejour IN (SELECT no_sejour FROM w_sejours_bg_24) AND
                    p_factures_lignes_c.no_facture LIKE '%BG' AND
                    origine_facturation_id = 1;

                UPDATE activite[PX].p_factures SET
                    code_facture = '1',
                    montant_facture_c = 0,
                    montant_facture_1_c = 0,
                    montant_comptabilise_1_c =0,
                    montant_comptabilise_budget_global_c = 0
                WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_bg_24) AND
                    no_facture LIKE '%BG' AND
                    montant_comptabilise_budget_global_c = 0;



				-- Eclatement des supplements par jour des lignes BG
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					p_factures_lignes_c.CTID AS from_CTID,
					t_prestations.code AS prestation_code,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_entree) ELSE p_factures_lignes_c.date_debut END AS date_debut_ghs,
					CASE WHEN p_sejours.type_sejour <> '5' THEN date(p_sejours.date_sortie - interval '1 day') ELSE p_factures_lignes_c.date_fin END AS date_fin_ghs,
					(date(date_sortie) - date(date_entree)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_debut WHEN t_prestations.code = 'GHS' THEN date(date_entree + interval '1 day') ELSE date(p_factures_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN type_sejour = '5' THEN p_factures_lignes_c.date_fin WHEN t_prestations.code = 'GHS' THEN date(p_sejours.date_sortie - interval '1 day') ELSE date(p_factures_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
					ABS(CASE WHEN type_sejour <> '5' AND t_prestations.code = 'GHS' THEN date(date_sortie) - date(date_entree) ELSE nb_prestation END) AS nb_det,
					p_factures_lignes_c.*
				FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND
						(
						code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						t_prestations.type_ventilation_jour = '1'
						)
				WHERE p_factures_lignes_c.no_facture LIKE '%BG' AND
					(nb_prestation > 1 or nb_prestation < -1 OR (type_sejour <> '5' AND t_prestations.code = 'GHS' AND date(date_sortie) - date(date_entree) > 1)) ;



				UPDATE w_factures_lignes_sup_c SET
					date_fin_ghs = date(date_debut_exh - interval '1 day'),
					date_fin_det = date(date_debut_exh - interval '1 day'),
					nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1,
					nb_det = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
				FROM (
					SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
					FROM activite[PX].p_factures_lignes_c
						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
					GROUP BY 1) subview
				WHERE w_factures_lignes_sup_c.no_facture = subview.no_facture AND
					prestation_code = 'GHS';

				CREATE INDEX w_factures_lignes_sup_c_i1
				  ON w_factures_lignes_sup_c
				  USING btree
				  (date_debut);

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup AS
				SELECT
					from_CTID,
					no_facture,
					date AS date_debut,
					date AS date_fin,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					round(montant_facture / ABS(nb_det),2) AS montant_facture,
					round(montant_facture_0 / ABS(nb_det),2) AS montant_facture_0,
					round(montant_facture_1 / ABS(nb_det),2) AS montant_facture_1,
					round(montant_facture_2 / ABS(nb_det),2) AS montant_facture_2,
					round(montant_facture_22 / ABS(nb_det),2) AS montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					round(montant_comptabilise / ABS(nb_det),2) AS montant_comptabilise,
					round(montant_comptabilise_0 / ABS(nb_det),2) AS montant_comptabilise_0,
					round(montant_comptabilise_1 / ABS(nb_det),2) AS montant_comptabilise_1,
					round(montant_comptabilise_2 / ABS(nb_det),2) AS montant_comptabilise_2,
					round(montant_comptabilise_22 / ABS(nb_det),2) AS montant_comptabilise_22,
					round(montant_encours / ABS(nb_det),2) AS montant_encours,
					round(montant_encours_0 / ABS(nb_det),2) AS montant_encours_0,
					round(montant_encours_1 / ABS(nb_det),2) AS montant_encours_1,
					round(montant_encours_2 / ABS(nb_det),2) AS montant_encours_2,
					round(montant_encours_22 / ABS(nb_det),2) AS montant_encours_22,
					round(montant_facture_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_actes_inclus_dans_sejour,
					round(montant_facture_0_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_0_actes_inclus_dans_sejour,
					round(montant_facture_1_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_1_actes_inclus_dans_sejour,
					round(montant_facture_2_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_2_actes_inclus_dans_sejour,
					round(montant_facture_22_actes_inclus_dans_sejour / ABS(nb_det),2) AS montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					round(montant_comptabilise_budget_global_1 / ABS(nb_det),2) AS montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_det AND date_fin_det
				;

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

				SELECT from_CTID,
					SUM(nb_rubrique) AS nb_rubrique,
					SUM(nb_prestation) AS nb_prestation,
					SUM(montant_facture) AS montant_facture,
					SUM(montant_facture_0) AS montant_facture_0,
					SUM(montant_facture_1) AS montant_facture_1,
					SUM(montant_facture_2) AS montant_facture_2,
					SUM(montant_facture_22) AS montant_facture_22,
					SUM(montant_comptabilise) AS montant_comptabilise,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22,
					SUM(montant_encours) AS montant_encours,
					SUM(montant_encours_0) AS montant_encours_0,
					SUM(montant_encours_1) AS montant_encours_1,
					SUM(montant_encours_2) AS montant_encours_2,
					SUM(montant_encours_22) AS montant_encours_22,
					SUM(montant_facture_actes_inclus_dans_sejour) AS montant_facture_actes_inclus_dans_sejour,
					SUM(montant_facture_0_actes_inclus_dans_sejour) AS montant_facture_0_actes_inclus_dans_sejour,
					SUM(montant_facture_1_actes_inclus_dans_sejour) AS montant_facture_1_actes_inclus_dans_sejour,
					SUM(montant_facture_2_actes_inclus_dans_sejour) AS montant_facture_2_actes_inclus_dans_sejour,
					SUM(montant_facture_22_actes_inclus_dans_sejour) AS montant_facture_22_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup
				GROUP BY 1;


				UPDATE activite[PX].p_factures_lignes_c
				SET
					date_fin = p_factures_lignes_c.date_debut,
					nb_rubrique = p_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_sup_tot.nb_rubrique,
					nb_prestation = p_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_sup_tot.nb_prestation,
					montant_facture = p_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_sup_tot.montant_facture,
					montant_facture_0 = p_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = p_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = p_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = p_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = p_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = p_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = p_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = p_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = p_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_22,
					montant_encours = p_factures_lignes_c.montant_encours - w_factures_lignes_sup_c_sup_tot.montant_encours,
					montant_encours_0 = p_factures_lignes_c.montant_encours_0 - w_factures_lignes_sup_c_sup_tot.montant_encours_0,
					montant_encours_1 = p_factures_lignes_c.montant_encours_1 - w_factures_lignes_sup_c_sup_tot.montant_encours_1,
					montant_encours_2 = p_factures_lignes_c.montant_encours_2 - w_factures_lignes_sup_c_sup_tot.montant_encours_2,
					montant_encours_22 = p_factures_lignes_c.montant_encours_22 - w_factures_lignes_sup_c_sup_tot.montant_encours_22,
					montant_facture_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_0_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_1_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_2_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour = p_factures_lignes_c.montant_facture_22_actes_inclus_dans_sejour - w_factures_lignes_sup_c_sup_tot.montant_facture_22_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_1 = p_factures_lignes_c.montant_comptabilise_budget_global_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup_tot
				WHERE p_factures_lignes_c.CTID = from_CTID;

				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_sup_c_sup');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id)
				SELECT
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c_sup;



				UPDATE activite[PX].p_factures_lignes_c
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_factures, activite[PX].p_mouvements_sejour
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures_lignes_c.no_facture LIKE '%BG' AND
					p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
					activite[PX].p_factures_lignes_c.date_debut = p_mouvements_sejour.date AND
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					p_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id;


            ]]></sqlcmd>
	</NODE>


	<NODE label="Compte client Clinique">
		<sqlcmd><![CDATA[

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_8');

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture,
					date_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_regle,
					montant_regle_0,
					montant_regle_1,
					montant_regle_2,
					montant_regle_22
				)
				SELECT
					no_facture,
					date_vente,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM w_FAC_FACTURE_LIGNE_C
				WHERE date_vente IS NOT NULL  AND
					(montant_comptabilise <> 0 OR
					montant_comptabilise_0 <> 0 OR
					montant_comptabilise_1 <> 0 OR
					montant_comptabilise_2 <> 0 OR
					montant_comptabilise_22 <> 0
					)
				GROUP BY 1,2,3,4;

				DROP TABLE IF EXISTS w_FAC_REG;
				CREATE TEMP TABLE w_FAC_REG AS
				SELECT
					FACT_NUM_FAC,
					ECRI_DAT_ECRITURE,
					VENT_MONTANT AS montant_regle,
					CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN VENT_MONTANT ELSE 0 END AS montant_regle_0,
					CASE WHEN FACD_ID_ORGA_AMO > 0 THEN VENT_MONTANT ELSE 0 END AS montant_regle_1,
					CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN VENT_MONTANT ELSE 0 END AS montant_regle_2,
					CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN VENT_MONTANT ELSE 0 END AS montant_regle_22,
					LFAC_ID_PRSE,
					LFAC_LET_CLE,
					ECRI_DAT_SUP,
					CPTE_CAGE_CODE,
					CRN_HON_TO_SEJ,
					LFAC_CDT_EXC,
					LFAC_ID_PRHO,
					LFAC_ID_MEDE_EXE
				FROM w_FAC_FACTURE
					JOIN prod_hm.FAC_LIGNE_FACTURE ON LFAC_ID_FACT = FACT_ID_FACT
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
					JOIN prod_hm.CCL_VENTILATION ON VENT_ID_LFAD = LFAD_ID_LFAD
					JOIN prod_hm.CCL_LIGNE_ECRITURE ON VENT_ID_LECR = LECR_ID_LECR
					JOIN prod_hm.CCL_ECRITURE ON LECR_ID_ECRI = ECRI_ID_ECRI
					JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
					JOIN w_CCL_COMPTE ON LECR_ID_CPTE = CPTE_ID_CPTE
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				WHERE ECRI_DAT_SUP IS NULL
					AND JOUR_ISJVT = '0'
				;


				DROP TABLE IF EXISTS w_FAC_REG_DEB;
				CREATE TEMP TABLE w_FAC_REG_DEB AS
				SELECT
					FACT_NUM_FAC,
					ECRI_DAT_ECRITURE,
					CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END AS montant_regle,
					CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END AS montant_regle_0,
					CASE WHEN FACD_ID_ORGA_AMO > 0 THEN CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END AS montant_regle_1,
					CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END AS montant_regle_2,
					CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END AS montant_regle_22,
					LECR_ID_LECR,
					CPTE_CAGE_CODE,
					LECR_PART
				FROM prod_hm.FAC_FACTURE_DEBITEUR
				, w_FAC_FACTURE,
				prod_hm.CCL_LIGNE_ECRITURE,
				prod_hm.CCL_ECRITURE,
				w_CCL_JOURNAL,
				w_CCL_COMPTE
				WHERE LECR_ID_FACD = FACD_ID_FACD
					AND FACD_ID_FACT = FACT_ID_FACT
					AND LECR_ID_ECRI = ECRI_ID_ECRI
					AND ECRI_ID_JOUR = JOUR_ID_JOUR
					AND LECR_ID_CPTE = CPTE_ID_CPTE
					AND ECRI_DAT_SUP IS NULL
					AND JOUR_ISJVT = '0'
					--AND LECR_PART = 'SFT'
				;

				-- Comptes clients (REG)

				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_C;
				CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_C AS
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRSE::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
				WHERE 1=1
					AND LFAC_ID_PRSE <> 0
					AND CPTE_CAGE_CODE = 'CLIENT'
				GROUP BY 1,2,3,4;

				-- Médecins salariés

				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRHO = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
				WHERE 1=1
					AND LFAC_ID_PRHO <> 0
					AND CRN_HON_TO_SEJ <> '1'
					AND LFAC_CDT_EXC = 'S'
					AND CPTE_CAGE_CODE = 'CLIENT'
				GROUP BY 1,2,3,4;


				-- Règlements
				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRHO = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
				WHERE 1=1
					AND LFAC_ID_PRHO <> 0
					AND CRN_HON_TO_SEJ = '1'
					AND CPTE_CAGE_CODE = 'CLIENT'
				GROUP BY 1,2,3,4;

				-- Acomptes 85%
				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG_DEB
					LEFT JOIN activite[PX].t_rubriques_facturation ON (t_rubriques_facturation.code_original = '*CTI_ACO85')
					LEFT JOIN activite.t_prestations ON (t_prestations.code_original = '*CTI_ACO85')
				WHERE 1=1
					AND CPTE_CAGE_CODE = 'ACO85'
					AND LECR_PART = 'SFT'
				GROUP BY 1,2,3,4
				;

				-- Acomptes
				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG_DEB
					LEFT JOIN activite[PX].t_rubriques_facturation ON (t_rubriques_facturation.code_original = '*CTI_ACO')
					LEFT JOIN activite.t_prestations ON (t_prestations.code_original = '*CTI_ACO')
				WHERE 1=1
					AND CPTE_CAGE_CODE IN ('ACO', 'CLIRMB')
					AND LECR_PART = 'SFT'
				GROUP BY 1,2,3,4
				;

				-- Ecritures clients non ventilees (solde centimes)
				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_C_non_ventilees;
				CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_C_non_ventilees AS
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					0 AS rubrique_comptabilisation_id,
					0 AS prestation_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG_DEB
				LEFT JOIN prod_hm.CCL_VENTILATION ON CCL_VENTILATION.VENT_ID_LECR = w_FAC_REG_DEB.LECR_ID_LECR
				WHERE 1=1
					AND CPTE_CAGE_CODE IN ('CLIENT')
					AND LECR_PART = 'SFT'
					AND CCL_VENTILATION.VENT_ID_LECR IS NULL
				GROUP BY 1,2,3
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_c = montant_regle + subview.montant_regle,
					montant_regle_0_c = montant_regle_0_c + subview.montant_regle_0,
					montant_regle_1_c = montant_regle_1_c + subview.montant_regle_1,
					montant_regle_2_c = montant_regle_2_c + subview.montant_regle_2,
					montant_regle_22_c = montant_regle_22_c + subview.montant_regle_22
				FROM
					(
					SELECT no_facture,
						SUM(montant_regle) AS montant_regle,
						SUM(montant_regle_0) AS montant_regle_0,
						SUM(montant_regle_1) AS montant_regle_1,
						SUM(montant_regle_2) AS montant_regle_2,
						SUM(montant_regle_22) AS montant_regle_22
					FROM w_FAC_REGLEMENT_LIGNE_C_non_ventilees
					GROUP BY 1
					) subview
				WHERE subview.no_facture = p_factures.no_facture
				;

				INSERT INTO w_FAC_REGLEMENT_LIGNE_C
				SELECT *
				FROM w_FAC_REGLEMENT_LIGNE_C_non_ventilees
				;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');



				UPDATE activite[PX].p_factures_soldes_c
				SET
					montant_regle = w_FAC_REGLEMENT_LIGNE_C.montant_regle,
					montant_regle_0 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_0,
					montant_regle_1 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_1,
					montant_regle_2 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_2,
					montant_regle_22 = w_FAC_REGLEMENT_LIGNE_C.montant_regle_22
				FROM w_FAC_REGLEMENT_LIGNE_C
				WHERE p_factures_soldes_c.no_facture = w_FAC_REGLEMENT_LIGNE_C.no_facture AND
					p_factures_soldes_c.date_comptable = w_FAC_REGLEMENT_LIGNE_C.date_reglement AND
					p_factures_soldes_c.rubrique_comptabilisee_id = w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id AND
					p_factures_soldes_c.prestation_id = w_FAC_REGLEMENT_LIGNE_C.prestation_id;


				INSERT INTO activite[PX].p_factures_soldes_c(
						no_facture,
						date_comptable,
						rubrique_comptabilisee_id,
						prestation_id,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						montant_regle,
						montant_regle_0,
						montant_regle_1,
						montant_regle_2,
						montant_regle_22
					)
				SELECT
					w_FAC_REGLEMENT_LIGNE_C.no_facture,
					w_FAC_REGLEMENT_LIGNE_C.date_reglement,
					w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id,
					w_FAC_REGLEMENT_LIGNE_C.prestation_id,
					0,
					0,
					0,
					0,
					0,
					w_FAC_REGLEMENT_LIGNE_C.montant_regle,
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_0,
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_1,
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_2,
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_22
				FROM w_FAC_REGLEMENT_LIGNE_C
					LEFT JOIN activite[PX].p_factures_soldes_c
					ON (p_factures_soldes_c.no_facture = w_FAC_REGLEMENT_LIGNE_C.no_facture
						AND p_factures_soldes_c.date_comptable = w_FAC_REGLEMENT_LIGNE_C.date_reglement
						AND p_factures_soldes_c.rubrique_comptabilisee_id = w_FAC_REGLEMENT_LIGNE_C.rubrique_comptabilisation_id
						AND p_factures_soldes_c.prestation_id = w_FAC_REGLEMENT_LIGNE_C.prestation_id)
				WHERE date_reglement IS NOT NULL AND p_factures_soldes_c.no_facture IS NULL AND
					(
					w_FAC_REGLEMENT_LIGNE_C.montant_regle <> 0   OR
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_0 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_1 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_2 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_C.montant_regle_22 <> 0
					)
					;



				-- Annulations par avoirs

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture,
					date_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_regle,
					montant_regle_0,
					montant_regle_1,
					montant_regle_2,
					montant_regle_22,
					od_avoir)
				SELECT
					p_factures_soldes_c.no_facture,
					date_od_avoir,
					rubrique_comptabilisee_id,
					prestation_id,
					0,
					0,
					0,
					0,
					0,
					p_factures_soldes_c.montant_comptabilise,
					p_factures_soldes_c.montant_comptabilise_0,
					p_factures_soldes_c.montant_comptabilise_1,
					p_factures_soldes_c.montant_comptabilise_2,
					p_factures_soldes_c.montant_comptabilise_22,
					'1'
				FROM activite[PX].p_factures_soldes_c JOIN w_ods_avoir ON p_factures_soldes_c.no_facture = w_ods_avoir.no_facture
				WHERE p_factures_soldes_c.montant_comptabilise <> 0;


				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture,
					date_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_regle,
					montant_regle_0,
					montant_regle_1,
					montant_regle_2,
					montant_regle_22,
					od_avoir)
				SELECT
					p_factures_soldes_c.no_facture,
					date_od_avoir,
					rubrique_comptabilisee_id,
					prestation_id,
					0,
					0,
					0,
					0,
					0,
					p_factures_soldes_c.montant_comptabilise,
					p_factures_soldes_c.montant_comptabilise_0,
					p_factures_soldes_c.montant_comptabilise_1,
					p_factures_soldes_c.montant_comptabilise_2,
					p_factures_soldes_c.montant_comptabilise_22,
					'1'
				FROM activite[PX].p_factures_soldes_c JOIN w_ods_avoir ON p_factures_soldes_c.no_facture = w_ods_avoir.no_facture_od_avoir
				WHERE p_factures_soldes_c.montant_comptabilise <> 0;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_8');


				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_C CASCADE;
				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_C CASCADE;



			]]></sqlcmd>
	</NODE>

	<NODE label="Lignes non facturées Honoraires">
		<sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;

				INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
					no_facture,
					date_debut,
					date_fin,
					heure_debut,
					nb_rubrique,
					coefficient,
					medecin_facture_id,
					prestation_id,
					prix_unitaire,
					montant_depassement,
					lieu_id,
					acte_id,
					phase_ccam,
					activite_ccam,
					extension_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4)
				SELECT
					p_factures.no_facture,
					date(ACSA_DAT_EXE_DEB) AS date_debut,
					date(COALESCE(ACSA_DAT_EXE_FIN, ACSA_DAT_EXE_DEB)) AS date_fin,
					CASE WHEN ACSA_HEU_MEDICALE IS NOT NULL
						THEN extract('hour' FROM ACSA_HEU_MEDICALE)
						ELSE
							extract('hour' FROM ACSA_DAT_EXE_DEB)
						END AS heure_debut,
					1 AS nb_rubrique,
					ACSA_QTE_COEFFICIENT AS coefficient,
					t_medecins_administratifs.oid AS medecin_facture_id,
					t_prestations.oid AS prestation_id,
					CASE WHEN ACSA_MON_TOT <> 0 AND ACSA_QTE_COEFFICIENT = 1 THEN ACSA_MON_TOT ELSE ACSA_PRI_UNITAIRE END AS prix_unitaire,
					ACSA_MON_DEP_HON AS montant_depassement,
					p_sejours.lieu_sortie_id AS lieu_id,
					COALESCE(t_actes.oid::bigint, 0) AS acte_id,
					COALESCE(floor(ASAI_NUM_PHAS),0) AS phase_ccam,
					COALESCE(floor(ACSA_COD_ACT_D),0) AS activite_ccam,
					substr(ACSA_EXT_DOC,1,1) AS extension_ccam,
					substr(ACSA_MODIF1,1,1) AS modificateur_ccam_1,
					substr(ACSA_MODIF2,1,1) AS modificateur_ccam_2,
					substr(ACSA_MODIF3,1,1) AS modificateur_ccam_3,
					substr(ACSA_MODIF4,1,1) AS modificateur_ccam_4

					FROM prod_hm.SAD_ACTIVITE_SAISIES
						LEFT JOIN prod_hm.SAD_ACTES_SAISIS ON ACSA_ID_ASAI = ASAI_ID_ASAI
						JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original AND p_sejours.etat = ''
						JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture = 'E'
						JOIN activite[PX].t_medecins_administratifs ON ACSA_ID_MEDE::bigint = t_medecins_administratifs.code_original
						JOIN activite.t_prestations ON ACSA_LET_CLE = t_prestations.code
						JOIN base.t_actes ON (substring(ACSA_CODE_D, 1, 7) = t_actes.code)
					WHERE ACSA_ID_PRHO <> 0
						AND date(COALESCE(ACSA_DAT_EXE_FIN, ACSA_DAT_EXE_DEB)) BETWEEN p_factures.date_debut AND p_factures.date_fin

				ORDER BY p_sejours.no_sejour;


			]]></sqlcmd>
	</NODE>

	<NODE label="Lignes factures Honoraires">
		<sqlcmd><![CDATA[

				INSERT INTO base.t_actes(
					code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4,
					geste_marqueur_id)
				SELECT
					substring(LFAC_CODE, 1, 7),
					substring(LFAC_CODE, 1, 7),
					substring(LFAC_CODE, 1, 7),
					MIN(CASE WHEN length(trim(LFAC_CODE)) >= 7 THEN 'CCAM' ELSE 'NGAP' END),
					MIN(CASE WHEN length(trim(LFAC_CODE)) >= 7 THEN 0 ELSE t_ccam_regroupements.oid END),
					MIN(CASE WHEN length(trim(LFAC_CODE)) >= 7 THEN 0 ELSE t_ccam_regroupements.oid END),
					0
				FROM w_FAC_FACTURE, prod_hm.FAC_LIGNE_FACTURE
				LEFT JOIN base.t_actes ON (trim(substring(LFAC_CODE, 1, 7)) = trim(t_actes.code)), base.t_ccam_regroupements
				WHERE
					LFAC_ID_FACT = FACT_ID_FACT
					AND LFAC_ID_PRHO  <> 0 AND t_actes.oid is  NULL
					AND t_ccam_regroupements.code = 'NGAP'
				GROUP BY 1,2,3;



				DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_H;

				CREATE TEMP TABLE w_FAC_FACTURE_LIGNE_H AS
				SELECT
					LFAC_ID_LFAC,
					FACT_NUM_FAC AS no_facture,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(LFAC_DAT_EXE_FIN) AS date_fin,
					CASE WHEN FACT_TYPE <> 'P' AND w_FAC_DATEVENTE.date_vente IS NOT NULL THEN w_FAC_DATEVENTE.date_vente ELSE '20991231'::date END AS date_vente,
					lieu_sortie_id,
					CASE WHEN LFAC_QTE_COEFFICIENT >= 0 THEN 1 ELSE -1 END AS nb_rubrique,
					CASE WHEN LFAC_QTE_COEFFICIENT >= 0 THEN 1 ELSE -1 END AS nb_prestations,
					ABS(LFAC_QTE_COEFFICIENT) as coefficient,
					LFAC_COE_MCO_HAD AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
					COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_facture_id,
					COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_comptabilise_id,
					LFAC_PRI_UNITAIRE AS prix_unitaire,

					COALESCE(t_actes.oid::bigint, 0) AS acte_id,
					COALESCE(t_protocoles.oid::bigint, 0) AS protocole_id,
					to_char(COALESCE(LFAC_HEU_MEDICALE, LFAC_DAT_EXE_DEB, '0001-01-01 00:00:00'),'HH24MISS')::numeric AS heure_debut,
					'1' AS phase_ccam,
					LFAC_COD_ACTIVITE::integer AS activite_ccam,
					LFAC_EXT_DOC AS extension_ccam,
					LFAC_MODIF1 AS modificateur_ccam_1,
					LFAC_MODIF2 AS modificateur_ccam_2,
					LFAC_MODIF3 AS modificateur_ccam_3,
					LFAC_MODIF4 AS modificateur_ccam_4,

					SUM(CASE WHEN FAC_HON = '1' THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END) AS montant_facture,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END) as montant_facture_0,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMO > 0 THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_1,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_2,
					SUM(CASE WHEN FAC_HON = '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_22,
					SUM(coalesce(LFAD_MTT_DEH, 0)) as montant_depassement,

					SUM(CASE WHEN FAC_HON <> '1' THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END) AS montant_facture_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END) as montant_facture_0_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMO > 0 THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_1_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_2_actes_inclus_dans_sejour,
					SUM(CASE WHEN FAC_HON <> '1' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN coalesce(LFAD_MTT_HOR_DEH, 0) + coalesce(LFAD_MTT_DEH, 0) ELSE 0 END)  as montant_facture_22_actes_inclus_dans_sejour,

					MAX(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN 100-LFAD_TAUX ELSE 0 END) as taux_0,
					MAX(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_TAUX ELSE 0 END) as taux_1,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_2,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN 100-LFAD_TAUX ELSE 0 END) as taux_22,

					SUM(CASE WHEN LFAD_IND_DIRECT <> 1 AND CRN_HON_TO_SEJ <> '1' AND LFAC_CDT_EXC <> 'S' THEN LFAD_MTT_CRN ELSE 0 END) AS montant_comptabilise,
					SUM(CASE WHEN LFAD_IND_DIRECT <> 1 AND CRN_HON_TO_SEJ <> '1' AND LFAC_CDT_EXC <> 'S' AND FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_0,
					SUM(CASE WHEN LFAD_IND_DIRECT <> 1 AND CRN_HON_TO_SEJ <> '1' AND LFAC_CDT_EXC <> 'S' AND FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_CRN ELSE 0 END)  as montant_comptabilise_1,
					SUM(CASE WHEN LFAD_IND_DIRECT <> 1 AND CRN_HON_TO_SEJ <> '1' AND LFAC_CDT_EXC <> 'S' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC <> tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_2,
					SUM(CASE WHEN LFAD_IND_DIRECT <> 1 AND CRN_HON_TO_SEJ <> '1' AND LFAC_CDT_EXC <> 'S' AND FACD_ID_ORGA_AMC > 0 AND FACD_ID_ORGA_AMC = tiers_payant_22_orga_id THEN LFAD_MTT_CRN ELSE 0 END) as montant_comptabilise_22

				FROM prod_hm.FAC_LIGNE_FACTURE
					LEFT JOIN activite[PX].t_rubriques_facturation ON (LFAC_ID_PRHO::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite.t_prestations ON (LFAC_LET_CLE = t_prestations.code)
					LEFT JOIN activite[PX].t_medecins_administratifs ON (LFAC_ID_MEDE_EXE::bigint = t_medecins_administratifs.code_original)
					LEFT JOIN base.t_actes ON (substring(LFAC_CODE, 1, 7) = t_actes.code)
					LEFT JOIN activite[PX].t_protocoles ON (LFAC_ID_FAVO::bigint = t_protocoles.code_original)
					LEFT JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAC_ID_LFAC = LFAD_ID_LFAC
                    LEFT JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				, w_FAC_FACTURE
					LEFT JOIN w_FAC_DATEVENTE ON (LECR_ID_FACT_VENT = FACT_ID_FACT)
				WHERE LFAC_ID_FACT = FACT_ID_FACT
					AND FACT_TYPE <> 'P'
					AND LFAC_ID_PRHO  <> 0

				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26;


				-- Ajout des lignes ESPIC non valorisées
				DROP TABLE IF EXISTS w_FAC_FACTURE_last;
				CREATE TEMP TABLE w_FAC_FACTURE_last AS
				SELECT FACT_ID_SEJO,
					(MAX(ARRAY[FACT_DAT_CRE::text, FACT_TYPE, FACT_NUM_FAC::text]))[3]::text AS FACT_NUM_FAC_last,
					(MAX(ARRAY[FACT_DAT_CRE::text, FACT_TYPE, lieu_sortie_id::text]))[3]::bigint AS lieu_sortie_id
				FROM w_FAC_FACTURE
				WHERE FACT_TYPE IN ('A','F') AND
					SEJO_IND_BGH = '1'
				GROUP BY 1
				HAVING (MAX(ARRAY[FACT_DAT_CRE::text, FACT_TYPE]))[2] = 'F'
				;

				ANALYSE w_FAC_FACTURE_last
				;

				CREATE INDEX w_FAC_FACTURE_last_i1
				ON w_FAC_FACTURE_last
				USING btree
				(FACT_ID_SEJO);

				INSERT INTO w_FAC_FACTURE_LIGNE_H
				SELECT
					0::bigint AS FACT_ID_LFAC,
					FACT_NUM_FAC_last AS no_facture,
					date(ACSA_DAT_EXE_DEB) AS date_debut,
					date(ACSA_DAT_EXE_DEB) AS date_fin,
					'20991231'::date AS date_vente,
					lieu_sortie_id,
					CASE WHEN ACSA_QTE_COEFFICIENT >= 0 THEN 1 ELSE -1 END AS nb_rubrique,
					CASE WHEN ACSA_QTE_COEFFICIENT >= 0 THEN 1 ELSE -1 END AS nb_prestations,
					ABS(ACSA_QTE_COEFFICIENT) as coefficient,
					1::numeric AS coefficient_mco,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid::bigint, 0) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,
					COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_facture_id,
					COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_comptabilise_id,
					CASE WHEN ACSA_PRI_UNITAIRE > 0 THEN ACSA_PRI_UNITAIRE ELSE 0.0001 END AS prix_unitaire,

					COALESCE(t_actes.oid::bigint, 0) AS acte_id,
					COALESCE(t_protocoles.oid::bigint, 0) AS protocole_id,
					to_char(ACSA_DAT_EXE_DEB,'HH24MISS')::numeric AS heure_debut,
					'1' AS phase_ccam,
					ACSA_COD_ACT_D::integer AS activite_ccam,
					ACSA_EXT_DOC AS extension_ccam,
					ACSA_MODIF1 AS modificateur_ccam_1,
					ACSA_MODIF2 AS modificateur_ccam_2,
					ACSA_MODIF3 AS modificateur_ccam_3,
					ACSA_MODIF4 AS modificateur_ccam_4,

					0::numeric AS montant_facture,
					0::numeric AS montant_facture_0,
					0::numeric AS montant_facture_1,
					0::numeric AS montant_facture_2,
					0::numeric AS montant_facture_22,
					0::numeric AS montant_depassement,

					0::numeric AS montant_facture_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour,

					0::numeric AS taux_0,
					0::numeric AS taux_1,
					0::numeric AS taux_2,
					0::numeric AS taux_22,


					0::numeric AS montant_comptabilise,
					0::numeric AS montant_comptabilise_0,
					0::numeric AS montant_comptabilise_1,
					0::numeric AS montant_comptabilise_2,
					0::numeric AS montant_comptabilise_22

				FROM prod_hm.SAD_ACTES_SAISIS
					JOIN prod_hm.SAD_ACTIVITE_SAISIES ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN prod_hm.IDE_SEJOUR ON ASAI_ID_SEJO = SEJO_ID_SEJO
					JOIN w_FAC_FACTURE_last ON SEJO_ID_SEJO = w_FAC_FACTURE_last.FACT_ID_SEJO
					LEFT JOIN activite[PX].t_medecins_administratifs ON (ACSA_ID_MEDE::bigint = t_medecins_administratifs.code_original)
					LEFT JOIN base.t_actes ON (substring(ASAI_CODE_D, 1, 7) = t_actes.code)
					LEFT JOIN activite.t_prestations ON (ACSA_LET_CLE = t_prestations.code)
					LEFT JOIN activite[PX].t_rubriques_facturation ON (ACSA_ID_PRHO::bigint = t_rubriques_facturation.code_original)
					LEFT JOIN activite[PX].t_protocoles ON (ACSA_ID_FAVO::bigint = t_protocoles.code_original)
				WHERE ACSA_ID_PRHO  <> 0 AND
					ACSA_ASS_NON_PREV = '99'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26
				;

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_9');

				INSERT INTO activite[PX].p_factures_lignes_h(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,

					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,

					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,

					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,

					acte_id,
					protocole_id
					)

				SELECT
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestations,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_sortie_id,

					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,

					0,
					0,
					0,
					0,
					0,

					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,

					acte_id,
					protocole_id

				FROM w_FAC_FACTURE_LIGNE_H;


				UPDATE activite[PX].p_factures_lignes_h
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_factures, activite[PX].p_mouvements_sejour
				WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = p_mouvements_sejour.no_sejour AND
					activite[PX].p_factures_lignes_h.date_debut = p_mouvements_sejour.date AND
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					p_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id;

				-- ajout des lignes non facturées mais dont la prestations doit remonter quand même

				-- Les types de prestations exclues venant du PMSI MCO sont paramétrés
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
				'HM_ACTES_NON_FAC',
				'Actes avec tarif à 0 à rajouter en cas de non facturation mais présence d''un autre actes effectué par le même médecin',
				'',
				'Actes non facturés devant être rajoutés'
				WHERE 'HM_ACTES_NON_FAC' NOT IN (SELECT code FROM activite.t_divers);
				;

				DROP TABLE IF EXISTS w_SAD_ACTIVITE_SAISIES_to_add;
				CREATE TEMP TABLE w_SAD_ACTIVITE_SAISIES_to_add AS
				SELECT
					ACSA_ID_SEJO,
					ACSA_ID_FAVO,
					ACSA_ID_MEDE,
					SUM(CASE WHEN ACSA_CODE_D = ANY(string_to_array(valeur,',')) THEN 1 ELSE 0 END),
					base.cti_array_accum(distinct CASE WHEN ACSA_CODE_D = ANY(string_to_array(valeur,',')) THEN ACSA_ID_ACSA ELSE null END) AS ids,
					base.cti_array_accum(distinct CASE WHEN ACSA_CODE_D = ANY(string_to_array(valeur,',')) THEN ACSA_CODE_D ELSE null END) AS codes,
					base.cti_array_accum(distinct CASE WHEN ACSA_CODE_D != ALL(string_to_array(valeur,',')) THEN ACSA_CODE_D ELSE null END) AS assocs
				FROM prod_hm.SAD_ACTIVITE_SAISIES
				JOIN activite.t_divers ON code = 'HM_ACTES_NON_FAC'
				WHERE ACSA_ID_PRHO != 0
				GROUP BY 1,2,3
				HAVING
					-- present dans les actes à ajouter
					SUM(CASE WHEN ACSA_CODE_D = ANY(string_to_array(valeur,',')) THEN 1 ELSE 0 END) > 0
					-- avec au moins un autre acte saisi par le même médecin pour le même protocole (meme 0)
					--AND cardinality(base.cti_array_accum(distinct CASE WHEN ACSA_CODE_D != ALL(string_to_array(valeur,',')) THEN ACSA_CODE_D ELSE null END)) > 1
				;

				INSERT INTO activite[PX].p_factures_lignes_h(
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,

					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,

					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,

					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,

					acte_id,
					protocole_id
				)
				SELECT
					p_factures.no_facture,
					date(ACSA_DAT_EXE_DEB) AS date_debut,
					date(COALESCE(ACSA_DAT_EXE_FIN, ACSA_DAT_EXE_DEB)) AS date_fin,
					COALESCE(p_factures_lignes_h.nb_rubrique,1),
					COALESCE(p_factures_lignes_h.nb_prestation,1),
					ACSA_QTE_COEFFICIENT AS coefficient,
					COALESCE(p_factures_lignes_h.coefficient_mco,1),
					t_medecins_administratifs.oid AS medecin_facture_id,
					t_medecins_administratifs.oid AS medecin_comptabilise_id,

					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					0 AS montant_facture,
					0 as montant_facture_0,
					0 as montant_facture_1,
					0 as montant_facture_2,
					0 as montant_facture_22,
					0 as montant_depassement,

					0 as taux_0,
					0 as taux_1,
					0 as taux_2,
					0 as taux_22,

					ACSA_PRI_UNITAIRE AS prix_unitaire,
					COALESCE(p_factures_lignes_h.lieu_id,0) AS lieu_sortie_id,

					0 AS montant_comptabilise,
					0 as montant_comptabilise_0,
					0 as montant_comptabilise_1,
					0 as montant_comptabilise_2,
					0 as montant_comptabilise_22,

					0 AS montant_encours,
					0 AS montant_encours_0,
					0 AS montant_encours_1,
					0 AS montant_encours_2,
					0 AS montant_encours_22,

					0 AS montant_facture_actes_inclus_dans_sejour,
					0 as montant_facture_0_actes_inclus_dans_sejour,
					0 as montant_facture_1_actes_inclus_dans_sejour,
					0 as montant_facture_2_actes_inclus_dans_sejour,
					0 as montant_facture_22_actes_inclus_dans_sejour,

					COALESCE(t_actes.oid::bigint, 0) AS acte_id,
					COALESCE(p_factures_lignes_h.protocole_id, t_protocoles.oid,0)
				FROM (
					SELECT id, MAX(assoc) AS assoc FROM
						(SELECT
						unnest(ids) AS id,
						unnest(assocs) AS assoc
						FROM w_SAD_ACTIVITE_SAISIES_to_add )
						sub
						GROUP BY 1
					) sub
				JOIN prod_hm.SAD_ACTIVITE_SAISIES ON id = ACSA_ID_ACSA
					LEFT JOIN prod_hm.SAD_ACTES_SAISIS ON ACSA_ID_ASAI = ASAI_ID_ASAI
					JOIN activite[PX].p_sejours ON ACSA_ID_SEJO::bigint = p_sejours.code_original AND p_sejours.etat = ''
					JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture != 'E'
					JOIN activite[PX].t_medecins_administratifs ON ACSA_ID_MEDE::bigint = t_medecins_administratifs.code_original
					JOIN activite.t_prestations ON ACSA_LET_CLE = t_prestations.code
					JOIN base.t_actes ON (substring(ACSA_CODE_D, 1, 7) = t_actes.code)
					LEFT JOIN activite[PX].p_factures_lignes_h verif ON p_factures.no_facture = verif.no_facture AND t_actes.oid = verif.acte_id
					LEFT JOIN base.t_actes acte_associe ON (substring(assoc, 1, 7) = acte_associe.code)
					LEFT JOIN activite[PX].p_factures_lignes_h ON p_factures.no_facture = p_factures_lignes_h.no_facture AND acte_associe.oid = p_factures_lignes_h.acte_id
					LEFT JOIN activite[PX].t_protocoles ON (ACSA_ID_FAVO::bigint = t_protocoles.code_original)
				WHERE verif.no_facture IS NULL
				;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_9');


				-- Suppression des tables de travail non utilisées après

			]]></sqlcmd>
	</NODE>

	<NODE label="Compte client Honoraires">
		<sqlcmd><![CDATA[

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');

				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture,
					date_comptable,
					medecin_comptabilise_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_regle,
					montant_regle_0,
					montant_regle_1,
					montant_regle_2,
					montant_regle_22
				)
				SELECT
					no_facture,
					date_vente,
					medecin_comptabilise_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM w_FAC_FACTURE_LIGNE_H
				WHERE date_vente IS NOT NULL AND
					(montant_comptabilise <> 0 OR
					montant_comptabilise_0 <> 0 OR
					montant_comptabilise_1 <> 0 OR
					montant_comptabilise_2 <> 0 OR
					montant_comptabilise_22 <> 0
					)
				GROUP BY 1,2,3;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');




				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_H;

				CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_H AS
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					COALESCE(t_medecins_administratifs.oid::bigint, 0) AS medecin_comptabilise_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22

				FROM w_FAC_REG
					LEFT JOIN activite[PX].t_medecins_administratifs ON (LFAC_ID_MEDE_EXE::bigint = t_medecins_administratifs.code_original)
				WHERE 1=1
					AND LFAC_ID_PRHO  <> 0
					AND CRN_HON_TO_SEJ <> '1'
					AND LFAC_CDT_EXC <> 'S'
					AND CPTE_CAGE_CODE = 'CLIENT'
				GROUP BY 1,2,3;

				-- Acomptes
				INSERT INTO w_FAC_REGLEMENT_LIGNE_H
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					0 AS medecin_comptabilise_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22
				FROM w_FAC_REG_DEB
				WHERE 1=1
					AND CPTE_CAGE_CODE IN ('ACO', 'CLIRMB')
					AND LECR_PART = 'HON'
				GROUP BY 1,2,3
				;


				-- Ecritures clients non ventilees (solde centimes)
				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_H_non_ventilees;
				CREATE TEMP TABLE w_FAC_REGLEMENT_LIGNE_H_non_ventilees AS
				SELECT
					FACT_NUM_FAC AS no_facture,
					date(ECRI_DAT_ECRITURE) AS date_reglement,

					0 AS medecin_comptabilise_id,

					SUM(montant_regle) AS montant_regle,
					SUM(montant_regle_0) AS montant_regle_0,
					SUM(montant_regle_1) AS montant_regle_1,
					SUM(montant_regle_2) AS montant_regle_2,
					SUM(montant_regle_22) AS montant_regle_22

				FROM w_FAC_REG_DEB
				LEFT JOIN prod_hm.CCL_VENTILATION ON CCL_VENTILATION.VENT_ID_LECR = w_FAC_REG_DEB.LECR_ID_LECR
				WHERE 1=1
					AND CPTE_CAGE_CODE IN ('CLIENT')
					AND LECR_PART = 'HON'
					AND CCL_VENTILATION.VENT_ID_LECR IS NULL

				GROUP BY 1,2,3
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_h = montant_regle + subview.montant_regle,
					montant_regle_0_h = montant_regle_0_h + subview.montant_regle_0,
					montant_regle_1_h = montant_regle_1_h + subview.montant_regle_1,
					montant_regle_2_h = montant_regle_2_h + subview.montant_regle_2,
					montant_regle_22_h = montant_regle_22_h + subview.montant_regle_22
				FROM
					(
					SELECT no_facture,
						SUM(montant_regle) AS montant_regle,
						SUM(montant_regle_0) AS montant_regle_0,
						SUM(montant_regle_1) AS montant_regle_1,
						SUM(montant_regle_2) AS montant_regle_2,
						SUM(montant_regle_22) AS montant_regle_22
					FROM w_FAC_REGLEMENT_LIGNE_H_non_ventilees
					GROUP BY 1
					) subview
				WHERE subview.no_facture = p_factures.no_facture
				;

				INSERT INTO w_FAC_REGLEMENT_LIGNE_H
				SELECT *
				FROM w_FAC_REGLEMENT_LIGNE_H_non_ventilees
				;

				-- Comptes clients (REG)

				UPDATE activite[PX].p_factures_soldes_h
				SET
				montant_regle = w_FAC_REGLEMENT_LIGNE_H.montant_regle,
				montant_regle_0 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_0,
				montant_regle_1 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_1,
				montant_regle_2 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_2,
				montant_regle_22 = w_FAC_REGLEMENT_LIGNE_H.montant_regle_22
				FROM w_FAC_REGLEMENT_LIGNE_H
				WHERE p_factures_soldes_h.no_facture = w_FAC_REGLEMENT_LIGNE_H.no_facture
					AND p_factures_soldes_h.date_comptable = w_FAC_REGLEMENT_LIGNE_H.date_reglement
					AND p_factures_soldes_h.medecin_comptabilise_id = w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id;


				INSERT INTO activite[PX].p_factures_soldes_h(
						no_facture,
						date_comptable,
						medecin_comptabilise_id,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						montant_regle,
						montant_regle_0,
						montant_regle_1,
						montant_regle_2,
						montant_regle_22
					)
				SELECT
					w_FAC_REGLEMENT_LIGNE_H.no_facture,
					w_FAC_REGLEMENT_LIGNE_H.date_reglement,
					w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id,
					0,
					0,
					0,
					0,
					0,
					w_FAC_REGLEMENT_LIGNE_H.montant_regle,
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_0,
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_1,
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_2,
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_22
				FROM w_FAC_REGLEMENT_LIGNE_H
					LEFT JOIN activite[PX].p_factures_soldes_h
					ON (p_factures_soldes_h.no_facture = w_FAC_REGLEMENT_LIGNE_H.no_facture
						AND p_factures_soldes_h.date_comptable = w_FAC_REGLEMENT_LIGNE_H.date_reglement
						AND p_factures_soldes_h.medecin_comptabilise_id = w_FAC_REGLEMENT_LIGNE_H.medecin_comptabilise_id)
				WHERE date_reglement IS NOT NULL AND p_factures_soldes_h.no_facture IS NULL AND
					(
					w_FAC_REGLEMENT_LIGNE_H.montant_regle <> 0   OR
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_0 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_1 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_2 <> 0 OR
					w_FAC_REGLEMENT_LIGNE_H.montant_regle_22 <> 0
					)
					;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_8');

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_FAC_REGLEMENT_LIGNE_H CASCADE;
				DROP TABLE IF EXISTS w_FAC_FACTURE_LIGNE_H CASCADE;


			]]></sqlcmd>
	</NODE>

	<NODE label="Post traitement entetes">
		<sqlcmd><![CDATA[

				-- Préfactures inutiles
				DROP TABLE IF EXISTS w_factures_soldes_c_h
				;
				CREATE TEMP TABLE w_factures_soldes_c_h AS
				SELECT
					p_factures.no_facture AS no_facture
				FROM activite[PX].p_factures
				LEFT JOIN activite[PX].p_factures_soldes_c ON p_factures_soldes_c.no_facture = p_factures.no_facture AND p_factures_soldes_c IS NULL
				LEFT JOIN activite[PX].p_factures_soldes_h ON p_factures_soldes_h.no_facture = p_factures.no_facture AND p_factures_soldes_h IS NULL
				;
				CREATE INDEX w_factures_soldes_c_h_i1
					ON w_factures_soldes_c_h
					USING btree
					(no_facture)
				;
				ANALYSE w_factures_soldes_c_h
				;

				DELETE
				FROM activite[PX].p_factures
				USING w_factures_soldes_c_h
				WHERE w_factures_soldes_c_h.no_facture = p_factures.no_facture AND
					type_facture = 'P' AND
					coalesce(montant_facture_c,0) = 0 AND
					coalesce(montant_facture_h,0) = 0 AND
					coalesce(montant_comptabilise_c,0) = 0 AND
					coalesce(montant_comptabilise_h,0) = 0 AND
					coalesce(montant_regle_c,0) = 0 AND
					coalesce(montant_regle_h,0) = 0
				;

				-- Il reste parfois des encaissements sans facture sur des préfactures
				DELETE
				FROM activite[PX].p_factures_soldes_h
				WHERE no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures) AND
					no_facture LIKE 'P%'
				;

				-- Facture reference

				DROP TABLE IF EXISTS w_sejours_facture_reference;
				CREATE TEMP TABLE w_sejours_facture_reference AS
				SELECT
					no_sejour,
					date_debut,
					MAX(date_fin) AS date_fin,
					MAX(p_factures.no_facture) AS no_facture_last,
					MAX(CASE WHEN type_facture = '0' AND type_facture <> 'P' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_last,
					MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'P' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_last_2,
					MAX(p_factures.oid) AS facture_id_last,
					MAX(CASE WHEN type_facture = '0' AND type_facture <> 'P' THEN p_factures.oid ELSE null END) AS facture_id_reference_last,
					MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'P' THEN p_factures.oid ELSE null END) AS facture_id_reference_last_2
				FROM activite[PX].p_factures
				WHERE type_facture <> 'P'
				GROUP BY 1,2;

				CREATE INDEX w_sejours_facture_reference_i1
					ON w_sejours_facture_reference
					USING btree
					(no_sejour);

				UPDATE w_sejours_facture_reference
				SET facture_id_last = p_factures_references.oid
				FROM activite[PX].p_factures p_factures_references
				WHERE w_sejours_facture_reference.no_facture_last = p_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_last <> p_factures_references.oid;


				UPDATE w_sejours_facture_reference
				SET facture_id_reference_last = p_factures_references.oid
				FROM activite[PX].p_factures p_factures_references
				WHERE w_sejours_facture_reference.no_facture_reference_last = p_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_reference_last <> p_factures_references.oid;

				UPDATE w_sejours_facture_reference
				SET facture_id_reference_last_2 = p_factures_references.oid
				FROM activite[PX].p_factures p_factures_references
				WHERE w_sejours_facture_reference.no_facture_reference_last_2 = p_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_reference_last_2 <> p_factures_references.oid;



				UPDATE activite[PX].p_factures
				SET
					no_facture_reference = COALESCE(no_facture_reference_last, no_facture_reference_last_2, no_facture_last),
					facture_reference_id = COALESCE(facture_id_reference_last, facture_id_reference_last_2, facture_id_last)
				FROM w_sejours_facture_reference
				WHERE p_factures.no_sejour = w_sejours_facture_reference.no_sejour AND
					p_factures.date_debut BETWEEN w_sejours_facture_reference.date_debut AND w_sejours_facture_reference.date_fin AND
					(
						no_facture_reference IS DISTINCT FROM COALESCE(no_facture_reference_last, no_facture_reference_last_2, no_facture_last) OR
						facture_reference_id IS DISTINCT FROM COALESCE(facture_id_reference_last, facture_id_reference_last_2, facture_id_last)
					);




				UPDATE activite[PX].p_factures
				SET no_facture_reference = no_facture
				WHERE (no_facture_reference IS NULL OR no_facture_reference = '');


				UPDATE activite[PX].p_factures
				SET type_facture = '0'
				WHERE p_factures.type_facture = '2' AND
					p_factures.no_facture = p_factures.no_facture_reference;

				UPDATE activite[PX].p_factures
				SET type_facture = '2'
				WHERE p_factures.type_facture = '0' AND
					p_factures.no_facture <> p_factures.no_facture_reference;

				UPDATE activite[PX].p_factures
				SET facture_reference_id = p_factures_references.oid
				FROM activite[PX].p_factures p_factures_references
				WHERE p_factures.no_facture_reference = p_factures_references.no_facture
					AND p_factures.facture_reference_id <> p_factures_references.oid;


				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_sejours_facture_reference CASCADE;


                -- Pour le budget global, il peut y avoir des lignes de factures facturées non comptabilisées avec montant aussi issu du pmsi
                -- Il faut les enlever
                DROP TABLE IF EXISTS w_factures_lignes_c_factord;
                CREATE TEMP TABLE w_factures_lignes_c_factord AS
                SELECT no_sejour, prestation_id
                FROM activite[PX].p_factures_lignes_c
                JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                JOIN activite[PX].t_prestations ON prestation_id = t_prestations.oid
                 GROUP BY 1,2
                HAVING SUM(CASE WHEN p_factures_lignes_c.no_facture LIKE '%BG' THEN montant_facture_1 ELSE 0 END) <> 0 AND
                    SUM(CASE WHEN p_factures_lignes_c.no_facture NOT LIKE '%BG' AND montant_comptabilise_1 = 0 THEN montant_facture_1 ELSE 0 END) <> 0
                ORDER BY 1,2
                ;

                UPDATE activite[PX].p_factures_lignes_c
                SET montant_facture_1 = 0, montant_facture = p_factures_lignes_c.montant_facture - p_factures_lignes_c.montant_facture_1
                FROM activite[PX].p_factures,
                    w_factures_lignes_c_factord
                WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
                    w_factures_lignes_c_factord.no_sejour = p_factures.no_sejour AND
                    p_factures_lignes_c.prestation_id = w_factures_lignes_c_factord.prestation_id AND
                    p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
                    p_factures_lignes_c.montant_facture_1 <> 0 AND
                    p_factures_lignes_c.montant_comptabilise_1 = 0
                ;

                DELETE FROM activite[PX].p_factures_lignes_c
                USING activite[PX].p_factures,
                    w_factures_lignes_c_factord
                WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
                    w_factures_lignes_c_factord.no_sejour = p_factures.no_sejour AND
                    p_factures_lignes_c.prestation_id = w_factures_lignes_c_factord.prestation_id AND
                    p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
                    p_factures_lignes_c.montant_facture = 0 AND
                    p_factures_lignes_c.montant_comptabilise = 0
                ;


				-- BG. Lignes PJ non comptabilisées avec GHS a supprimer
				DROP TABLE IF EXISTS w_PJ_trop;
				CREATE TEMP TABLE w_PJ_trop AS
				SELECT p_factures.no_sejour,
					MAX(CASE WHEN t_prestations.code = 'PJ' THEN prestation_id ELSE 0 END) AS pj_prestation_id,
					SUM(CASE WHEN t_prestations.code = 'PJ' THEN montant_facture ELSE 0 END) AS pj_fac,
					SUM(CASE WHEN t_prestations.code = 'PJ' THEN montant_comptabilise ELSE 0 END) AS pj_cpt,
					SUM(CASE WHEN t_prestations.code = 'GHS' THEN montant_facture ELSE 0 END) AS ghs_fac
				FROm activite[PX].p_factures_lignes_c
				JOIN activite[PX].p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE '[ENV_TYPEETS]' IN ('2','3') AND
					t_prestations.code IN ('GHS','PJ')
				GROUP BY 1
				HAVING
					MAX(CASE WHEN p_factures.no_facture LIKE '%BG' THEN '1' ELSE '0' END) = '1' AND
					SUM(CASE WHEN t_prestations.code = 'PJ' THEN montant_facture ELSE 0 END) <>
						SUM(CASE WHEN t_prestations.code = 'PJ' THEN montant_comptabilise ELSE 0 END) AND
					SUM(CASE WHEN t_prestations.code = 'GHS' THEN montant_facture ELSE 0 END) > 0
				;

				ANALYSE w_PJ_trop
				;

				DELETE FROM activite[PX].p_factures_lignes_c
				USING activite[PX].p_factures,
					w_PJ_trop
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = w_PJ_trop.no_sejour AND
					p_factures_lignes_c.prestation_id = pj_prestation_id AND
					p_factures.no_facture NOT LIKE '%BG'
				;

				UPDATE activite[PX].p_factures SET
					montant_facture_c = subview.montant_facture,
					montant_facture_0_c = subview.montant_facture_0,
					montant_facture_1_c = subview.montant_facture_1,
					montant_facture_2_c = subview.montant_facture_2,
					montant_facture_22_c = subview.montant_facture_22
				FROM
					(
					SELECT p_factures.no_facture,
						COALESCE(SUM(montant_facture),0) AS montant_facture,
						COALESCE(SUM(montant_facture_0),0) AS montant_facture_0,
						COALESCE(SUM(montant_facture_1),0) AS montant_facture_1,
						COALESCE(SUM(montant_facture_2),0) AS montant_facture_2,
						COALESCE(SUM(montant_facture_22),0) AS montant_facture_22
					FROM activite[PX].p_factures
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture
					WHERE p_factures.no_sejour IN (SELECT no_sejour FROM w_PJ_trop) AND
						p_factures.no_facture NOT LIKE '%BG'
					GROUP BY 1
					) subview
				WHERE p_factures.no_sejour IN (SELECT no_sejour FROM w_PJ_trop)  AND
					subview.no_facture = p_factures.no_facture
				;


			]]></sqlcmd>
	</NODE>

</NODE>

<NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">

	<NODE label="Ecritures comptables">
		<sqlcmd><![CDATA[


				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT JOUR_ID_JOUR::text,
					MAX(JOUR_CODE),
					MAX(JOUR_LIBELLE)
				FROM prod_hm.CCL_JOURNAL
				WHERE JOUR_ID_JOUR::text NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 2
				;

				UPDATE activite[PX].t_journal
				SET type_journal = 'VE'
				FROM prod_hm.CCL_JOURNAL
				JOIN prod_hm.BAS_CATALOGUE_GEN ON JOUR_ID_CAGE = CAGE_ID_CAGE
				WHERE JOUR_ID_JOUR = code_original AND
					type_journal = '' AND
					CAGE_CODE = 'FACAV'
				;



				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT CPTE_CODE, CPTE_CODE, MAX(CPTE_LIBELLE), MAX(CPTE_LIBELLE)
				FROM prod_hm.CCL_COMPTE
				WHERE CPTE_CODE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				;

				-- Initialisation CLI/NON (cas des comptes de liaison et des valeurs à blanc)
				UPDATE prod_hm.CCL_LIGNE_ECRITURE SET
					LECR_PART =
						CASE
						WHEN LECR_PART = 'SFT' AND CPTE_ABREVIATION = 'LIAIHONO' THEN 'HOL'
						WHEN LECR_PART = 'HON' AND CPTE_ABREVIATION = 'LIAICLI' THEN 'SFL'
						ELSE LECR_PART END
				FROM prod_hm.CCL_COMPTE
				WHERE LECR_ID_CPTE = CPTE_ID_CPTE AND
					CPTE_ABREVIATION IN ('LIAIHONO','LIAICLI')
				;

				UPDATE prod_hm.CCL_LIGNE_ECRITURE
				SET LECR_PART = subview.LECR_PART
				FROM
				(
				SELECT LECR_ID_ECRI, MAX(CASE WHEN LECR_PART IN ('HON','HOL') THEN 'HON' WHEN LECR_PART IN ('SFT','SFL') THEN 'SFT' ELSE '' END) AS LECR_PART
				FROM prod_hm.CCL_LIGNE_ECRITURE
				GROUP BY 1
				HAVING MIN(LECR_PART) = '' AND
					MAX(CASE WHEN LECR_PART IN ('HON','HOL') THEN 'HOD' WHEN LECR_PART IN ('SFT','SFL') THEN 'SFD' ELSE '' END) <> ''
				) subview
				WHERE CCL_LIGNE_ECRITURE.LECR_ID_ECRI = subview.LECR_ID_ECRI AND
					CCL_LIGNE_ECRITURE.LECR_PART = ''
				;





				DROP TABLE IF EXISTS w_ecriture_comptable;
				CREATE TEMP TABLE w_ecriture_comptable AS
				SELECT
					LECR_ID_LECR,
					LECR_ID_LECR::text AS code_original,
					date(ECRI_DAT_ECRITURE) AS date_comptable,
					CASE
					WHEN t_journal.type_journal = 'VE' AND CPTE_CODE LIKE '411%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND CPTE_CODE LIKE '412%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND CPTE_CODE LIKE '445%' THEN 'VTVA'
					WHEN t_journal.type_journal = 'VE' AND LECR_PART NOT IN ('HON','HOD','HOL') THEN 'VPRD'
					WHEN t_journal.type_journal = 'VE' AND LECR_PART IN ('HON','HOD','HOL') THEN 'VHON'
					WHEN CPTE_CODE LIKE '758%' THEN 'PEPR'
					WHEN CPTE_CODE LIKE '658%' THEN 'PEPR'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '468%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '471%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '411%' AND ECRI_LIBELLE NOT ILIKE '%NOEMIE%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '412%' AND ECRI_LIBELLE NOT ILIKE '%NOEMIE%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '411%' AND ECRI_LIBELLE ILIKE '%NOEMIE%' THEN 'RNOE'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '412%' AND ECRI_LIBELLE ILIKE '%NOEMIE%' THEN 'RNOE'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '419%' THEN 'ACPT'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '51%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '531%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND CPTE_CODE LIKE '466%' THEN 'PHON'
					ELSE LIBE_CODE END AS type_ecriture,
					ECRI_ID_ECRI::text AS piece,
					CASE WHEN LECR_PART IN ('HON','HOD','HOL') THEN 'H' ELSE 'C' END AS clinique_honoraire,
					COALESCE(t_compte.oid,0) AS compte_id,
					COALESCE(t_journal.oid,0) AS journal_id,
					COALESCE(p_sejours.oid,0::bigint) AS sejour_id,
					COALESCE(p_sejours.no_sejour,''::text) AS no_sejour,
					COALESCE(p_factures.oid,0::bigint) AS facture_id,
					COALESCE(FACT_NUM_FAC::text,'')::text AS no_facture,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_id,
					0::bigint AS tiers_payant_id,
					ECRI_LIBELLE AS texte,
					CASE WHEN LECR_SENS = 'C' THEN LECR_MONTANT ELSE 0 END AS montant_credit,
					CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 END AS montant_debit,
					CASE
						WHEN t_journal.type_journal = 'VE' THEN 'VENTE'
						WHEN t_journal.code LIKE 'OD%' THEN 'OD'
						ELSE '?'||t_journal.code END AS type_piece,
					CASE
					WHEN LIBE_CODE = 'ESP' THEN 'ESP'
					WHEN LIBE_CODE = 'RCE' THEN 'ESP'
					WHEN LIBE_CODE = 'CH' THEN 'CHQ'
					WHEN LIBE_CODE = 'RCH' THEN 'CHQ'
					WHEN LIBE_CODE = 'CB' THEN 'CB'
					WHEN LIBE_CODE = 'RCB' THEN 'CB'
					WHEN LIBE_CODE = 'VRT' THEN 'VIR'
					WHEN LIBE_CODE = 'VRTP' THEN 'VIR'
					ELSE ''::text END AS mode_reglement_code,
					t_compte.taux_tva
				FROM prod_hm.CCL_ECRITURE
				JOIN prod_hm.CCL_LIGNE_ECRITURE ON ECRI_ID_ECRI = LECR_ID_ECRI
				JOIN prod_hm.CCL_COMPTE ON LECR_ID_CPTE = CPTE_ID_CPTE
				LEFT JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LECR_ID_FACD = FACD_ID_FACD
				LEFT JOIN prod_hm.FAC_FACTURE ON FACD_ID_FACT = FACT_ID_FACT
				LEFT JOIN prod_hm.CCL_LIBELLE ON ECRI_ID_LIBE = LIBE_ID_LIBE
				JOIN activite[PX].t_journal ON ECRI_ID_JOUR = t_journal.code_original
				LEFT JOIN activite[PX].t_compte ON CPTE_CODE = t_compte.code
				LEFT JOIN activite[PX].p_sejours ON LECR_ID_SEJO = p_sejours.code_original
				LEFT JOIN activite[PX].p_factures ON FACT_NUM_FAC = p_factures.no_facture
				LEFT JOIN activite[PX].t_medecins_administratifs ON LECR_ID_MEDE::text = t_medecins_administratifs.code_original
				WHERE ECRI_DAT_SUP IS NULL AND
					ECRI_ID_ETAB IN ([ID_ETAB]) AND
					ECRI_DAT_ECRITURE >= '[ENV_ADM_ANNEEDEBUT]0101'
				;

				ANALYSE w_ecriture_comptable
				;


				TRUNCATE activite[PX].p_ecriture_comptable;
				INSERT INTO activite[PX].p_ecriture_comptable(
					code_original,
					date_comptable,
					type_ecriture,
					type_piece,
					piece,
					clinique_honoraire,
					compte_id,
					journal_id,
					sejour_id,
					no_sejour,
					facture_id,
					no_facture,
					medecin_id,
					tiers_payant_id,
					texte,
					montant_credit,
					montant_debit,
					est_comptabilise,
					mode_reglement_code,
					taux_tva)
				SELECT
					code_original,
					date_comptable,
					type_ecriture,
					type_piece,
					piece,
					clinique_honoraire,
					compte_id,
					journal_id,
					sejour_id,
					no_sejour,
					facture_id,
					no_facture,
					medecin_id,
					tiers_payant_id,
					texte,
					montant_credit,
					montant_debit,
					'1'::text AS est_comptabilise,
					mode_reglement_code,
					taux_tva
				FROM w_ecriture_comptable
				;



				ANALYSE activite[PX].p_ecriture_comptable
				;

				UPDATE activite[PX].p_ecriture_comptable
				SET code_erreur = 'EQP'
				FROM
				(
				SELECT provider_id, clinique_honoraire, piece
				FROM activite[PX].p_ecriture_comptable
				GROUP BY 1,2,3
				HAVING SUM(montant_debit-montant_credit) <> 0
				) subview
				WHERE p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.piece = subview.piece AND
					p_ecriture_comptable.clinique_honoraire = subview.clinique_honoraire
				;



				UPDATE activite[PX].p_ecriture_comptable
				SET code_erreur = 'FAC'
				FROM
				(
				SELECT p_ecriture_comptable.provider_id AS provider_id,
					p_ecriture_comptable.piece AS piece,
					p_ecriture_comptable.clinique_honoraire AS clinique_honoraire
				FROM activite[PX].p_ecriture_comptable
				JOIN
				(
				SELECT p_ecriture_comptable.provider_id,
					p_ecriture_comptable.no_facture,
					CASE WHEN round(SUM(CASE WHEN type_ecriture IN ('VPRD','VTVA') THEN montant_credit-montant_debit ELSE 0 END),2) IS DISTINCT FROM round(MAX(montant_comptabilise_c),2) THEN '1' ELSE '0' END AS erreur_vente_c,
					CASE WHEN round(SUM(CASE WHEN type_ecriture IN ('VHON','VHOI') THEN montant_credit-montant_debit ELSE 0 END),2) IS DISTINCT FROM round(MAX(montant_comptabilise_h),2) THEN '1' ELSE '0' END AS erreur_vente_h
				FROM activite[PX].p_ecriture_comptable
				LEFT JOIN activite[PX].p_factures ON p_factures.no_facture = p_ecriture_comptable.no_facture
				WHERE type_ecriture IN ('VPRD','VTVA','VHON','VHOI')
				GROUP BY 1,2
				) subview ON
					p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.no_facture = subview.no_facture
				WHERE p_ecriture_comptable.type_ecriture IN ('VPRD','VTVA','VHON','VHOI','VCLI') AND
					(
					p_ecriture_comptable.clinique_honoraire = 'C' AND erreur_vente_c = '1' OR
					p_ecriture_comptable.clinique_honoraire = 'H' AND erreur_vente_h = '1'
					)
				GROUP BY 1,2,3
				) subview
				WHERE p_ecriture_comptable.provider_id = subview.provider_id AND
					p_ecriture_comptable.piece = subview.piece AND
					p_ecriture_comptable.clinique_honoraire = subview.clinique_honoraire
				;

				-- Il y a des pièces sans TVA
				UPDATE activite[PX].p_ecriture_comptable
				SET taux_tva = 0
				WHERE piece IN (
				SELECT piece
				FROM activite[PX].p_ecriture_comptable
				JOIN activite[PX].t_compte on compte_id = t_compte.oid
				GROUP BY 1
				HAVING MAX(CASE WHEN t_compte.code LIKE '445%' THEN '1' ELSE '0' END) = '0' AND
					MAX(CASE WHEN t_compte.code NOT LIKE '445%' THEN p_ecriture_comptable.taux_tva ELSE 0 END) > 0
					)
				;


			]]></sqlcmd>
	</NODE>

	<NODE label="Récupération chiffrier">
		<sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_chiffrier_comptable;

				INSERT INTO activite[PX].p_chiffrier_comptable(
					date_comptable,
					montant_ventes_c,
					montant_reglements_c,
					montant_solde_client_c,
					montant_ventes_h,
					montant_reglements_h,
					montant_solde_client_h
				)
				SELECT
					date(ECRI_DAT_ECRITURE) AS date_comptable,
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_reglements_c,
					SUM(CASE WHEN LECR_PART = 'SFT' THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_solde_client_c,
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) AS montant_ventes_h,
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_reglements_h,
					SUM(CASE WHEN LECR_PART = 'HON' THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_solde_client_h
				FROM prod_hm.CCL_LIGNE_ECRITURE
					JOIN prod_hm.CCL_ECRITURE ON LECR_ID_ECRI = ECRI_ID_ECRI
					JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
					JOIN w_CCL_COMPTE ON LECR_ID_CPTE = CPTE_ID_CPTE
				WHERE
					ECRI_DAT_SUP IS NULL AND
					ECRI_ID_ETAB IN ([ID_ETAB]) AND
					CPTE_CAGE_CODE IN ('CLIENT' , 'ACO85', 'ACO', 'CLIRMB') AND
					ECRI_DAT_ECRITURE >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1
				ORDER BY 1;


				TRUNCATE activite[PX].p_factures_comptables;

				INSERT INTO activite[PX].p_factures_comptables(
					no_facture,
					date_comptable,
					montant_ventes_c,
					montant_reglements_c,
					montant_ventes_h,
					montant_reglements_h
				)
				SELECT
					COALESCE(FACT_NUM_FAC,'00000000'),
					date(ECRI_DAT_ECRITURE) AS date_comptable,
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_reglements_c,
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) AS montant_ventes_h,
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) AS montant_reglements_h
				FROM prod_hm.CCL_LIGNE_ECRITURE
					JOIN prod_hm.CCL_ECRITURE ON LECR_ID_ECRI = ECRI_ID_ECRI
					JOIN w_CCL_JOURNAL ON ECRI_ID_JOUR = JOUR_ID_JOUR
					JOIN w_CCL_COMPTE ON LECR_ID_CPTE = CPTE_ID_CPTE
					LEFT JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LECR_ID_FACD = FACD_ID_FACD
					LEFT JOIN prod_hm.FAC_FACTURE ON FACD_ID_FACT = FACT_ID_FACT
				WHERE ECRI_DAT_SUP IS NULL AND
					ECRI_ID_ETAB IN ([ID_ETAB]) AND
					CPTE_CAGE_CODE IN ('CLIENT' , 'ACO85', 'ACO', 'CLIRMB') AND
					ECRI_DAT_ECRITURE >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2
				HAVING
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) <> 0 OR
					SUM(CASE WHEN LECR_PART = 'SFT' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) <> 0 OR
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '1' THEN CASE WHEN LECR_SENS = 'D' THEN LECR_MONTANT ELSE 0 - LECR_MONTANT END ELSE 0 END) <> 0 OR
					SUM(CASE WHEN LECR_PART = 'HON' AND JOUR_ISJVT = '0' AND (LECR_ID_FACD <> 0 OR LECR_ID_LFAD <> 0) THEN CASE WHEN LECR_SENS = 'D' THEN 0 - LECR_MONTANT ELSE LECR_MONTANT END ELSE 0 END) <> 0
				ORDER BY 1,2;



			]]></sqlcmd>
	</NODE>
</NODE>

<NODE name="PARAM" label="RECUPERATION DES PARAMETRES">

	<NODE label="Type d'environnement">
		<sqlcmd><![CDATA[
				CTISELECT_PROPERTY_READ 'ENV_WITHPMSI', MAX(CASE WHEN schemaname = 'pmsi' AND tablename = 'p_rss' THEN 1 ELSE 0 END)
				FROM pg_tables
				WHERE schemaname = 'pmsi' AND tablename = 'p_rss'
			]]></sqlcmd>
	</NODE>

	<NODE label="Tiers payant">
		<sqlcmd><![CDATA[

				INSERT INTO activite[PX].t_types_tiers_payant(code, texte, texte_court)
				SELECT code, texte, texte FROM
				(
				SELECT '0' AS code, 'Patients' AS texte
				UNION ALL
				SELECT '1','Régime général'
				UNION ALL
				SELECT '2','Mutuelles'
				) subview
				WHERE code NOT IN (SELECT code FROM activite[PX].t_types_tiers_payant);


				INSERT INTO base.t_grands_regimes(code, code_original, texte, texte_court)
				SELECT GREG_CODE, GREG_CODE, GREG_LIBELLE, GREG_LIBELLE
				FROM prod_hm.IDE_ORGANISME
				JOIN prod_hm.pad_grand_regime ON ORGA_ID_GREG = GREG_ID_GREG
				LEFT JOIN base.t_grands_regimes ON GREG_CODE = code
				WHERE t_grands_regimes.code IS NULL
				GROUP BY 1,2,3,4;



				INSERT INTO activite[PX].t_tiers_payant(oid, code, code_original, type_tiers_payant, texte, texte_court)
				SELECT 0, '', '', '0', 'Non saisi', 'Non saisi'
				WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_tiers_payant);

				INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court)
				SELECT 'PATIENTS', '0', '0', 'Patients', 'Patients'
				WHERE '0' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);

				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court)
				SELECT ORGA_ID_ORGA::bigint, ORGA_CODE, CASE WHEN ORGA_TYPE = 'AMO' THEN '1' WHEN ORGA_TYPE = 'AMC' THEN '2' ELSE '0' END, ORGA_NOM, ORGA_NOM
				FROM prod_hm.IDE_ORGANISME
				WHERE ORGA_ID_ORGA IN (
							SELECT DISTINCT PECH_ID_ORGA_AMO
							FROM  prod_hm.IDE_SEJOUR, prod_hm.IDE_PEC
							WHERE SEJO_ID_ETAB_CON IN ([ID_ETAB])
							AND SEJO_ID_SEJO = PECH_ID_SEJO)
					AND ORGA_ID_ORGA::bigint NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);

				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court)
				SELECT ORGA_ID_ORGA::bigint, ORGA_CODE, CASE WHEN ORGA_TYPE = 'AMO' THEN '1' WHEN ORGA_TYPE = 'AMC' THEN '2' ELSE '0' END, ORGA_NOM, ORGA_NOM
				FROM prod_hm.IDE_ORGANISME
				WHERE ORGA_ID_ORGA IN (
							SELECT DISTINCT SEAM_ID_ORGA_AMC
							FROM  prod_hm.IDE_SEJOUR, prod_hm.IDE_SEJOUR_AMC
							WHERE SEJO_ID_ETAB_CON IN ([ID_ETAB])
							AND SEJO_ID_SEJO = SEAM_ID_SEJO)
					AND ORGA_ID_ORGA::bigint NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);

				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM prod_hm.IDE_ORGANISME
					JOIN prod_hm.pad_grand_regime ON ORGA_ID_GREG = GREG_ID_GREG
					JOIN base.t_grands_regimes ON GREG_CODE = code
				WHERE t_tiers_payant.code_original = ORGA_ID_ORGA AND
					grand_regime_id IS DISTINCT FROM t_grands_regimes.oid AND
					GREG_CODE <> '00';

				UPDATE activite[PX].t_tiers_payant SET
					code = ORGA_CODE,
					texte = ORGA_NOM,
					texte_court = ORGA_NOM
				FROM prod_hm.IDE_ORGANISME
				WHERE t_tiers_payant.code_original = ORGA_ID_ORGA::bigint AND
					(
					code IS DISTINCT FROM ORGA_CODE OR
					texte IS DISTINCT FROM ORGA_NOM OR
					texte_court IS DISTINCT FROM ORGA_NOM
					)
				;

			]]></sqlcmd>
	</NODE>

	<NODE label="Médecins">
		<sqlcmd><![CDATA[

				INSERT INTO base.t_specialites_medecin(oid, code, code_original, texte, texte_court)
				SELECT 0, '', '0', 'Non saisie', 'Non saisie'
				WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin);

				UPDATE base.t_specialites_medecin SET
				code_original = code where code_original is null and oid != 0;

				INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
				SELECT
                    CAGE_CODE,
                    CAGE_CODE,
                    CAGE_LIBELLE,
                    CAGE_LIBELLE
				FROM
                    prod_hm.BAS_CATALOGUE_GEN
                    JOIN prod_hm.BAS_TYPE_INFO ON CAGE_ID_TYIN = TYIN_ID_TYIN AND TYIN_CODE = 'SPEC_MED'
                    LEFT JOIN base.t_specialites_medecin ON t_specialites_medecin.code = CAGE_CODE
				WHERE
					t_specialites_medecin.code IS NULL
				ORDER BY CAGE_CODE;

				INSERT INTO activite[PX].t_specialites_medecin(oid, code, code_original, texte, texte_court)
				SELECT 0, '', '0', 'Non saisie', 'Non saisie'
				WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_specialites_medecin);

				INSERT INTO base.t_medecins(oid, nom, prenom, numero_ordre, specialite_id )
				SELECT 0, 'Non renseigné', '', '', 0 WHERE 0 NOT IN (SELECT oid FROM base.t_medecins);

				INSERT INTO activite[PX].t_medecins_administratifs(oid, code_original, code, nom, prenom, specialite_id, medecin_id)
				SELECT 0, '0', '****', 'Non renseigné', '', 0, 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_medecins_administratifs);

				DROP TABLE IF EXISTS w_medecins_USED;
				CREATE TEMP TABLE w_medecins_USED AS
				SELECT MESE_ID_MEDE AS MEDE_ID_USED
				FROM prod_hm.IDE_MED_VENUE
				JOIN prod_hm.BAS_CATALOGUE_PERS ON MESE_ID_CAPE = CAPE_ID_CAPE
				WHERE MESE_ID_ETAB_D IN ([ID_ETAB]) AND
				CAPE_CODE IN ('1', '15', '8')
				GROUP BY 1
				;
				INSERT INTO w_medecins_USED
				SELECT SEJO_ID_MEDE_COURANT AS MEDE_ID_USED
				FROM prod_hm.IDE_SEJOUR
				WHERE SEJO_ID_ETAB_CON IN ([ID_ETAB])
				GROUP BY 1
				;
				INSERT INTO w_medecins_USED
				SELECT LFAC_ID_MEDE_EXE AS MEDE_ID_USED
				FROM prod_hm.FAC_LIGNE_FACTURE
				WHERE LFAC_ID_ETAB_D IN ([ID_ETAB]) AND
					LFAC_ID_MEDE_EXE > 0
				GROUP BY 1
				;

				DROP TABLE IF EXISTS w_medecins;
				CREATE TEMP TABLE w_medecins AS
					SELECT MEDE_ID_MEDE::bigint,
						CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
						base.cti_soundex_nom(MEDE_NOM_USU) AS MEDE_NOM_USU_SOUNDEX,
						base.cti_soundex_nom(COALESCE(MEDE_PRENOM,'')) AS MEDE_PRENOM_SOUNDEX,
						MEDE_NOM_USU,
						COALESCE(MEDE_PRENOM,'') AS MEDE_PRENOM,
						COALESCE(MEDI_ADELI,'') AS MEDI_ADELI,
						MEDE_ID_CAGE::bigint,
						COALESCE(CAGE_CODE,'') AS CAGE_CODE,
						COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
					FROM prod_hm.IDE_MEDECIN
						LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI, MAX(MEDI_ID_CAGE) AS MEDI_ID_CAGE FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB IN ([ID_ETAB]) GROUP BY 1) subview
							ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
						LEFT JOIN activite[PX].t_medecins_administratifs ON MEDE_ID_MEDE = t_medecins_administratifs.code_original
						LEFT JOIN prod_hm.BAS_CATALOGUE_GEN ON MEDI_ID_CAGE = CAGE_ID_CAGE
					WHERE MEDE_ID_MEDE = ANY(SELECT MEDE_ID_USED FROM w_medecins_USED);

				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
				SELECT w_medecins.MEDE_NOM_USU, w_medecins.MEDE_PRENOM, w_medecins.MEDI_ADELI, 0 FROM
				(SELECT SUBSTR(MEDE_NOM_USU_SOUNDEX, 1, 8) AS MEDE_NOM_USU_SOUNDEX, SUBSTR(MEDE_PRENOM_SOUNDEX, 1, 8) AS MEDE_PRENOM_SOUNDEX, MEDI_ADELI, MIN(MEDE_ID_MEDE) AS MEDE_ID_MEDE
				FROM w_medecins
				GROUP BY 1,2,3) subview, w_medecins
				WHERE w_medecins.MEDE_ID_MEDE = subview.MEDE_ID_MEDE
					AND subview.MEDE_NOM_USU_SOUNDEX || ',' || subview.MEDE_PRENOM_SOUNDEX || ',' ||  subview.MEDI_ADELI NOT IN
					(SELECT substr(base.cti_soundex_nom(nom),1,8)  || ',' || substr(base.cti_soundex_nom(prenom),1,8) || ',' || numero_ordre FROM base.t_medecins);


				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
				SELECT w_medecins.MEDE_NOM_USU, w_medecins.MEDE_PRENOM, w_medecins.MEDI_ADELI, 0 FROM
				(SELECT MEDE_NOM_USU_SOUNDEX, MEDE_PRENOM_SOUNDEX, MIN(MEDE_ID_MEDE) AS MEDE_ID_MEDE
				FROM w_medecins
				GROUP BY 1,2) subview, w_medecins
				WHERE w_medecins.MEDE_ID_MEDE = subview.MEDE_ID_MEDE
					AND subview.MEDE_NOM_USU_SOUNDEX || ',' || subview.MEDE_PRENOM_SOUNDEX NOT IN
					(SELECT base.cti_soundex_nom(nom)  || ',' || base.cti_soundex_nom(prenom) FROM base.t_medecins);


				UPDATE w_medecins SET medecin_id = subview.medecin_id
				FROM
				(SELECT substr(base.cti_soundex_nom(nom),1,8) as nom , substr(base.cti_soundex_nom(prenom),1,8) as prenom, numero_ordre, MIN(oid) AS medecin_id FROM base.t_medecins GROUP BY 1,2,3) subview
				WHERE SUBSTR(MEDE_NOM_USU_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(MEDE_PRENOM_SOUNDEX, 1, 8) = subview.prenom
				AND MEDI_ADELI = subview.numero_ordre
				AND w_medecins.medecin_id = 0;

				UPDATE w_medecins SET medecin_id = subview.medecin_id
				FROM
				(SELECT base.cti_soundex_nom(nom) as nom , base.cti_soundex_nom(prenom) as prenom, MIN(oid) AS medecin_id FROM base.t_medecins GROUP BY 1,2) subview
				WHERE SUBSTR(MEDE_NOM_USU_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(MEDE_PRENOM_SOUNDEX, 1, 8) = subview.prenom
				AND w_medecins.medecin_id = 0;

				INSERT INTO activite[PX].t_medecins_administratifs(code_original, code, nom, prenom, specialite_id,  medecin_id)
				SELECT DISTINCT MEDE_ID_MEDE, MEDE_CODE, MEDE_NOM_USU, MEDE_PRENOM, COALESCE(t_specialites_medecin.oid,0), medecin_id
				FROM w_medecins
					LEFT JOIN base.t_specialites_medecin ON (MEDE_ID_CAGE::bigint = t_specialites_medecin.code_original)
				WHERE MEDE_ID_MEDE NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

				UPDATE activite[PX].t_medecins_administratifs
				SET nom = MEDE_NOM_USU,
					prenom = MEDE_PRENOM,
					specialite_id = COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0),
					medecin_id = w_medecins.medecin_id
				FROM w_medecins
				LEFT JOIN base.t_specialites_medecin ON (CAGE_CODE || '..' = t_specialites_medecin.code)
				LEFT JOIN base.t_specialites_medecin t_specialites_medecin_2 ON (CAGE_CODE = t_specialites_medecin_2.code)
				WHERE w_medecins.MEDE_ID_MEDE = t_medecins_administratifs.code_original
					AND (
					t_medecins_administratifs.nom <> MEDE_NOM_USU OR
					t_medecins_administratifs.prenom <> MEDE_PRENOM OR
					t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0) OR
					t_medecins_administratifs.medecin_id <> w_medecins.medecin_id
				);



				UPDATE activite[PX].t_medecins_administratifs
				SET specialite_id = subview.specialite_medecin_id
				FROM
					(
					SELECT t_medecins_administratifs.oid,t_specialites_medecin.oid AS specialite_medecin_id
					FROM activite[PX].t_medecins_administratifs
					JOIN base.t_specialites_medecin t_specialites_medecin_2 ON specialite_id = t_specialites_medecin_2.oid
					JOIN base.t_specialites_medecin ON t_specialites_medecin_2.code || '..'  = t_specialites_medecin.code
					) subview
				WHERE t_medecins_administratifs.oid = subview.oid;

				UPDATE base.t_medecins SET specialite_id = subview.specialite_id FROM
				(SELECT t_medecins.oid, MIN(t_medecins_administratifs.specialite_id) as specialite_id
				FROM base.t_medecins, activite[PX].t_medecins_administratifs , base.t_specialites_medecin
				WHERE t_medecins.oid = t_medecins_administratifs.medecin_id
				AND t_medecins_administratifs.specialite_id = t_specialites_medecin.oid
				GROUP BY t_medecins.oid) subview
				WHERE t_medecins.oid = subview.oid AND t_medecins.oid <> 0 AND t_medecins.specialite_id = 0;

				-- ADELI
				UPDATE activite[PX].t_medecins_administratifs
				SET no_adeli = MEDI_ADELI
				FROM prod_hm.IDE_MEDECIN
				JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI FROM prod_hm.IDE_MEDECIN_IMMAT GROUP BY 1) subview
					ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
				WHERE t_medecins_administratifs.code_original = MEDE_ID_MEDE AND
					no_adeli IS DISTINCT FROM MEDI_ADELI
				;

                -- Code RPPS
                UPDATE base.t_medecins
                SET code_rpps = subview.RPPS
                FROM
                (
                SELECT medecin_id, count(DISTINCT MEIN_IDE_NATIONALE), MAX(MEIN_IDE_NATIONALE) AS RPPS
                FROM activite[PX].t_medecins_administratifs
                JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
                JOIN prod_hm.IDE_MEDECIN_IDENT_NATIONALE ON code_original = IDE_MEDECIN_IDENT_NATIONALE.MEIN_ID_MEDE
                WHERE MEIN_IDE_NATIONALE <> '' AND
                    length(MEIN_IDE_NATIONALE) = 11 AND
                    t_medecins.code_rpps = '' AND
                    medecin_id <> 0
                GROUP BY 1
                HAVING count(DISTINCT MEIN_IDE_NATIONALE) = 1
                ) subview
                WHERE t_medecins.oid = subview.medecin_id
                ;

				-- Adresse
				DROP TABLE IF EXISTS w_IDE_MEDECIN_ADRESSE;
				CREATE TEMP TABLE w_IDE_MEDECIN_ADRESSE AS
				SELECT MEDE_ID_MEDE,
					MAX(CASE WHEN BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_ADRE.CAGE_CODE = 'ADR_PROF' THEN ADRE_LIGNE1 ELSE '' END) AS ADRE_LIGNE1,
					MAX(CASE WHEN BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_ADRE.CAGE_CODE = 'ADR_PROF' THEN ADRE_LIGNE2 ELSE '' END) AS ADRE_LIGNE2,
					MAX(CASE WHEN BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_ADRE.CAGE_CODE = 'ADR_PROF' THEN ADRE_LIGNE3 ELSE '' END) AS ADRE_LIGNE3,
					MAX(CASE WHEN BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_ADRE.CAGE_CODE = 'ADR_PROF' THEN ADRE_COD_POS ELSE '' END) AS ADRE_COD_POS,
					MAX(CASE WHEN BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_ADRE.CAGE_CODE = 'ADR_PROF' THEN ADRE_VILLE ELSE '' END) AS ADRE_VILLE,
					MAX(CASE WHEN BAS_TYP_INFO_TELE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_TELE.CAGE_CODE = 'TEL_PERS' THEN TELE_NUM_TEL ELSE '' END) AS TELE_NULM_TEL_FIXE,
					MAX(CASE WHEN BAS_TYP_INFO_TELE.TYIN_CODE = 'MEDECIN' AND BAS_CATALOGUE_GEN_TELE.CAGE_CODE = 'TEL_PORT' THEN TELE_NUM_TEL ELSE '' END) AS TELE_NULM_TEL_PORT
				FROM prod_hm.IDE_MEDECIN
				LEFT JOIN prod_hm.IDE_ADRESSE ON MEDE_ID_MEDE = ADRE_ID_OBJ
				LEFT JOIN prod_hm.BAS_TYPE_INFO BAS_TYP_INFO_ADRE ON ADRE_ID_TYIN = BAS_TYP_INFO_ADRE.TYIN_ID_TYIN AND BAS_TYP_INFO_ADRE.TYIN_CODE = 'MEDECIN'
				LEFT JOIN prod_hm.BAS_CATALOGUE_GEN BAS_CATALOGUE_GEN_ADRE ON ADRE_ID_CAGE = BAS_CATALOGUE_GEN_ADRE.CAGE_ID_CAGE
				LEFT JOIN prod_hm.IDE_TELEPHONE ON MEDE_ID_MEDE = TELE_ID_OBJ
				LEFT JOIN prod_hm.BAS_TYPE_INFO BAS_TYP_INFO_TELE ON TELE_ID_TYIN = BAS_TYP_INFO_TELE.TYIN_ID_TYIN AND BAS_TYP_INFO_TELE.TYIN_CODE = 'MEDECIN'
				LEFT JOIN prod_hm.BAS_CATALOGUE_GEN BAS_CATALOGUE_GEN_TELE ON TELE_ID_CAGE = BAS_CATALOGUE_GEN_TELE.CAGE_ID_CAGE
				GROUP BY 1
				;

				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT ADRE_COD_POS, MAX(ADRE_VILLE), MAX(ADRE_VILLE), MAX(t_departements.oid)
				FROM w_IDE_MEDECIN_ADRESSE
				LEFT JOIN base.t_codes_postaux ON ADRE_COD_POS = t_codes_postaux.code
				JOIN base.t_departements ON
					ADRE_COD_POS NOT LIKE '97%' AND substr(ADRE_COD_POS,1,2) = t_departements.code OR
					ADRE_COD_POS LIKE '97%' AND substr(ADRE_COD_POS,1,3) = t_departements.code
				WHERE t_codes_postaux.oid IS NULL AND
					ADRE_COD_POS <> '' AND
					length(ADRE_COD_POS) = 5
				GROUP BY 1
				;

				UPDATE activite[PX].t_medecins_administratifs SET
					adresse = ADRE_LIGNE1 || ' ' ||  ADRE_LIGNE2 || ' ' || ADRE_LIGNE3,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = ADRE_VILLE,
					telephone = trim(TELE_NULM_TEL_FIXE || ' ' || TELE_NULM_TEL_PORT)
				FROM w_IDE_MEDECIN_ADRESSE
					LEFT JOIN base.t_codes_postaux ON ADRE_COD_POS = t_codes_postaux.code
				WHERE t_medecins_administratifs.code_original = MEDE_ID_MEDE::text AND
					(
					adresse IS DISTINCT FROM (ADRE_LIGNE1 || ' ' ||  ADRE_LIGNE2 || ' ' || ADRE_LIGNE3) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM ADRE_VILLE OR
					telephone IS DISTINCT FROM trim(TELE_NULM_TEL_FIXE || ' ' || TELE_NULM_TEL_PORT)
					)
				;

			]]></sqlcmd>
	</NODE>

	<NODE label="Hébergement">
		<sqlcmd><![CDATA[


				-- Modes de traitement

				INSERT INTO base.t_modes_traitement(code, texte, texte_court)
				SELECT CAGE_CODE, CAGE_LIBELLE, CAGE_LIBELLE
				FROM prod_hm.BAS_CATALOGUE_GEN, prod_hm.BAS_TYPE_INFO
				WHERE CAGE_ID_TYIN = TYIN_ID_TYIN AND TYIN_CODE = 'ACTIVITE'
					AND CAGE_CODE NOT IN (SELECt code FROM base.t_modes_traitement)
				ORDER BY CAGE_CODE;

				-- DMT

				INSERT INTO base.t_dmt(code, texte, texte_court)
				SELECT CAGE_CODE, CAGE_LIBELLE, CAGE_LIBELLE
				FROM prod_hm.BAS_CATALOGUE_GEN, prod_hm.BAS_TYPE_INFO
				WHERE CAGE_ID_TYIN = TYIN_ID_TYIN AND TYIN_CODE = 'CAT_DMT'
					AND CAGE_CODE NOT IN (SELECt code FROM base.t_dmt)
				ORDER BY CAGE_CODE;

				-- Services

				INSERT INTO activite[PX].t_services_facturation(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '****', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_services_facturation);

				UPDATE activite[PX].t_services_facturation SET
					code = substr(translate(UNFO_CODE,' ',''),1,10),
					texte = UNFO_LIBELLE,
					texte_court = UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE UNFO_ID_UNFO::text = code_original AND
					(
					code IS DISTINCT FROM substr(translate(UNFO_CODE,' ',''),1,10) OR
					texte IS DISTINCT FROM UNFO_LIBELLE OR
					texte_court IS DISTINCT FROM UNFO_LIBELLE
					)
				;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, type_t2a)
				SELECT UNFO_ID_UNFO::bigint, substr(translate(UNFO_CODE,' ',''),1,10) AS UNFO_CODE, UNFO_LIBELLE, UNFO_LIBELLE, CASE WHEN UNFO_TYP_PMS = 1 THEN '1' ELSE '0' END
				FROM prod_hm.BAS_UF
				WHERE
					UNFO_ID_ETAB IN ([ID_ETAB]) AND
					(
					UNFO_IND_MED = 1 OR
					UNFO_ID_UNFO IN (
						SELECT SEJO_ID_UNFO_MED_COURANT
						FROM prod_hm.IDE_SEJOUR
						WHERE SEJO_DAT_SUP IS NULL AND
							SEJO_IND_INCOMPLET <> 1 AND
							SEJO_STATUT NOT IN ('A','P') AND
							SEJO_ID_ETAB_CON IN ([ID_ETAB])
							)
					) AND
					UNFO_ID_UNFO::bigint NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
				ORDER BY UNFO_ID_UNFO;

				UPDATE activite[PX].t_services_facturation
				SET mode_traitement_id = subview.mode_traitement_id, dmt_id = subview.dmt_id
				FROM (
					SELECT UNFO_ID_UNFO::bigint, COALESCE(t_modes_traitement.oid,0) as mode_traitement_id, COALESCE(t_dmt.oid,0) as dmt_id
					FROM prod_hm.BAS_UF
						LEFT JOIN prod_hm.BAS_CATEGORIE_UFM ON UNFO_ID_CUFM = CUFM_ID_CUFM
						LEFT JOIN prod_hm.BAS_CATALOGUE_GEN BAS_CATALOGUE_GEN_MT ON CUFM_ID_CAGE_MT = BAS_CATALOGUE_GEN_MT.CAGE_ID_CAGE
						LEFT JOIN prod_hm.BAS_CATALOGUE_GEN BAS_CATALOGUE_GEN_DMT ON CUFM_ID_CAGE_DMT = BAS_CATALOGUE_GEN_DMT.CAGE_ID_CAGE
						LEFT JOIN base.t_modes_traitement ON BAS_CATALOGUE_GEN_MT.CAGE_CODE = t_modes_traitement.code
						LEFT JOIN base.t_dmt ON BAS_CATALOGUE_GEN_DMT.CAGE_CODE = t_dmt.code
					WHERE
						UNFO_ID_ETAB IN ([ID_ETAB]) AND
						UNFO_IND_MED = 1 AND
						(t_modes_traitement.oid IS NOT NULL OR t_dmt.oid IS NOT NULL)
					) subview
				WHERE code_original = UNFO_ID_UNFO AND (t_services_facturation.mode_traitement_id = 0 OR t_services_facturation.dmt_id = 0);

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, est_absence)
				SELECT '*ABS', '*ABS', 'Absence', 'Absence', '1' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_services_facturation);

				UPDATE activite[PX].t_services_facturation SET
					code = substr(translate(UNFO_CODE,' ',''),1,10),
					texte = UNFO_LIBELLE,
					texte_court = UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE UNFO_ID_UNFO::text = code_original AND
					(
					code IS DISTINCT FROM substr(translate(UNFO_CODE,' ',''),1,10) OR
					texte IS DISTINCT FROM UNFO_LIBELLE OR
					texte_court IS DISTINCT FROM UNFO_LIBELLE
					)
				;

				-- Unités fonctionnelles

				INSERT INTO activite[PX].t_unites_fonctionnelles(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_unites_fonctionnelles);

				INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT UNFO_ID_UNFO::bigint, substr(translate(UNFO_CODE,' ',''),1,10) AS UNFO_CODE, UNFO_LIBELLE, UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE
					UNFO_ID_ETAB IN ([ID_ETAB]) AND
					UNFO_IND_MED = 1 AND
					UNFO_ID_UNFO::bigint NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles)
				ORDER BY UNFO_ID_UNFO;

				INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT '*ABS', '*ABS', 'Absence', 'Absence' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles);

				UPDATE activite[PX].t_unites_fonctionnelles SET
					code = substr(translate(UNFO_CODE,' ',''),1,10),
					texte = UNFO_LIBELLE,
					texte_court = UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE UNFO_ID_UNFO::bigint = code_original AND
					(
					code IS DISTINCT FROM substr(translate(UNFO_CODE,' ',''),1,10) OR
					texte IS DISTINCT FROM UNFO_LIBELLE OR
					texte_court IS DISTINCT FROM UNFO_LIBELLE
					)
				;

				-- Unités médicales

				INSERT INTO activite[PX].t_unites_medicales(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_unites_medicales);

				INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court)
				SELECT UNME_ID_UNME::bigint, UNME_CODE, UNME_LIBELLE, UNME_LIBELLE
				FROM prod_hm.SAD_UM
				WHERE
					UNME_ID_ETAB IN ([ID_ETAB]) AND
					UNME_ID_UNME::bigint NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
				ORDER BY UNME_ID_UNME;

				INSERT INTO activite[PX].t_unites_medicales(code_original, code, texte, texte_court)
				SELECT '*ABS', '*ABS', 'Absence', 'Absence' WHERE '*ABS' NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales);

				UPDATE activite[PX].t_unites_medicales SET
					code = UNME_CODE,
					texte = UNME_LIBELLE,
					texte_court = UNME_LIBELLE
				FROM prod_hm.SAD_UM
				WHERE UNME_ID_UNME::bigint = code_original AND
					(
					code IS DISTINCT FROM UNME_CODE OR
					texte IS DISTINCT FROM UNME_LIBELLE OR
					texte_court IS DISTINCT FROM UNME_LIBELLE
					)
				;

				-- Activités (um principale)

				INSERT INTO activite[PX].t_activites(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_activites);

				DROP TABLE IF EXISTS w_SAD_UM;
				CREATE TEMP TABLE w_SAD_UM as
				SELECT UNME_ID_UNME::BIGINT as UNME_ID_UNME
					,UNME_CODE
					,UNME_LIBELLE
				FROM prod_hm.SAD_UM
				WHERE UNME_ID_ETAB IN ([ID_ETAB]);

				-- suffixage des codes um en doublon dans la table HM
				UPDATE w_SAD_UM SET
					UNME_CODE = substr(w_SAD_UM.UNME_CODE, 1, 3) || '#'::text
				FROM
					(SELECT	UNME_CODE FROM w_SAD_UM GROUP BY UNME_CODE HAVING count(*) > 1) w_doub,
					activite[PX].t_activites
				WHERE 1=1
					AND w_SAD_UM.UNME_CODE = w_doub.UNME_CODE
					AND w_doub.UNME_CODE = t_activites.code
					AND t_activites.code_original = w_SAD_UM.UNME_ID_UNME;

				-- Mise à jour du code suffixé dans la table CTI
				UPDATE activite[PX].t_activites SET
					code = w_SAD_UM.UNME_CODE
				FROM w_SAD_UM
				WHERE 1=1
					AND t_activites.code_original = w_SAD_UM.UNME_ID_UNME
					AND t_activites.code IS DISTINCT FROM w_SAD_UM.UNME_CODE;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
				SELECT UNME_ID_UNME::bigint, UNME_CODE, UNME_LIBELLE, UNME_LIBELLE
				FROM w_SAD_UM
				WHERE
					UNME_ID_UNME::bigint != ALL(ARRAY(SELECT code_original FROM activite[PX].t_activites WHERE code_original IS NOT NULL)::text[])
				ORDER BY UNME_ID_UNME;

				UPDATE activite[PX].t_activites SET
					code = UNME_CODE,
					texte = UNME_LIBELLE,
					texte_court = UNME_LIBELLE
				FROM w_SAD_UM
				WHERE UNME_ID_UNME::bigint = code_original AND
					(
					code IS DISTINCT FROM UNME_CODE OR
					texte IS DISTINCT FROM UNME_LIBELLE OR
					texte_court IS DISTINCT FROM UNME_LIBELLE
					)
				;

				-- Etages et lits

				INSERT INTO activite[PX].t_etages(oid, code_original, code, texte, texte_court, nb_lits)
				SELECT 0, 0, '', 'Non renseigné', 'Non renseigné', 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_etages);

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court)
				SELECT UNFO_ID_UNFO::bigint, substr(translate(UNFO_CODE,' ',''),1,10) AS UNFO_CODE, UNFO_LIBELLE, UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE
					UNFO_ID_ETAB IN ([ID_ETAB]) AND
					UNFO_IND_HEB = 1 AND
					UNFO_ID_UNFO::bigint NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL )
				ORDER BY UNFO_ID_UNFO;

				UPDATE activite[PX].t_etages SET
					code = substr(translate(UNFO_CODE,' ',''),1,10),
					texte = UNFO_LIBELLE,
					texte_court = UNFO_LIBELLE
				FROM prod_hm.BAS_UF
				WHERE UNFO_ID_UNFO::bigint = code_original AND
					(
					code IS DISTINCT FROM substr(translate(UNFO_CODE,' ',''),1,10) OR
					texte IS DISTINCT FROM UNFO_LIBELLE OR
					texte_court IS DISTINCT FROM UNFO_LIBELLE
					)
				;

                -- Cas de changement de code lit
				UPDATE activite[PX].t_lits
				SET code = t_lits.code || '(2)'
				FROM
				(
				SELECT etage_id, CASE WHEN code_original LIKE '%-%' THEN split_part(code_original,'-',2) ELSE code_original END AS code_original,
					MAX(CASE WHEN code_original NOT LIKE '%-%' THEN oid ELSE 0 END) AS keepoid,
					MAX(CASE WHEN code_original NOT LIKE '%-%' THEN t_lits.code ELSE '' END) AS code,
					count(*)
				FROM activite[PX].t_lits
				WHERE trim(code_original) NOT LIKE '%-0'
				GROUP BY 1,2
				HAVING count(*) > 1
				ORDER BY 1,2
				) subview
				WHERE t_lits.code_original LIKE '%-%' AND
					t_lits.code NOT LIKE '%(2)' AND
					split_part(t_lits.code_original,'-',2) = subview.code_original AND
					t_lits.etage_id = subview.etage_id AND
					t_lits.oid <> subview.keepoid
				;

				UPDATE activite[PX].t_lits	SET
					code = LIPO_CODE || 'BAK',
					texte = LIPO_LIBELLE,
					texte_court = LIPO_LIBELLE,
					etage_id = t_etages.oid
				FROM prod_hm.PAD_LIT_POSTE, prod_hm.PAD_CHAMBRE_SALLE, activite[PX].t_etages
				WHERE LIPO_ID_LIPO::bigint = t_lits.code_original
					AND LIPO_ID_CHAS = CHAS_ID_CHAS
					AND CHAS_ID_ETAB IN ([ID_ETAB])
					AND CHAS_ID_UNFO::bigint = t_etages.code_original AND
					(
					t_lits.code IS DISTINCT FROM LIPO_CODE OR
					t_lits.texte IS DISTINCT FROM LIPO_LIBELLE OR
					t_lits.texte_court IS DISTINCT FROM LIPO_LIBELLE OR
					t_lits.etage_id IS DISTINCT FROM t_etages.oid
					);

				UPDATE activite[PX].t_lits	SET
					code = LIPO_CODE,
					texte = LIPO_LIBELLE,
					texte_court = LIPO_LIBELLE,
					etage_id = t_etages.oid
				FROM prod_hm.PAD_LIT_POSTE, prod_hm.PAD_CHAMBRE_SALLE, activite[PX].t_etages
				WHERE LIPO_ID_LIPO::bigint = t_lits.code_original
					AND LIPO_ID_CHAS = CHAS_ID_CHAS
					AND CHAS_ID_ETAB IN ([ID_ETAB])
					AND CHAS_ID_UNFO::bigint = t_etages.code_original AND
					(
					t_lits.code IS DISTINCT FROM LIPO_CODE OR
					t_lits.texte IS DISTINCT FROM LIPO_LIBELLE OR
					t_lits.texte_court IS DISTINCT FROM LIPO_LIBELLE OR
					t_lits.etage_id IS DISTINCT FROM t_etages.oid
					);


				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
							SELECT LIPO_ID_LIPO::bigint, LIPO_CODE, LIPO_LIBELLE, LIPO_LIBELLE, t_etages.oid, CASE WHEN CHAS_CODE = LIPO_CODE THEN 'O' ELSE 'N' END AS CHAS_IND_CP
									FROM prod_hm.PAD_LIT_POSTE, prod_hm.PAD_CHAMBRE_SALLE, activite[PX].t_etages
									WHERE LIPO_ID_CHAS = CHAS_ID_CHAS
										AND CHAS_ID_ETAB IN ([ID_ETAB])
										AND CHAS_ID_UNFO::bigint = t_etages.code_original
										AND LIPO_ID_LIPO::bigint NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL  );

				-- Anciennes versions d'étages par lit
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
							SELECT MOUV_ID_UNFO || '-' || LIPO_ID_LIPO, LIPO_CODE, LIPO_LIBELLE, LIPO_LIBELLE, t_etages.oid, CASE WHEN CHAS_CODE = LIPO_CODE THEN 'O' ELSE 'N' END AS CHAS_IND_CP
							FROM prod_hm.IDE_MOUVEMENT
									JOIN prod_hm.IDE_SEJOUR ON MOUV_ID_SEJO = SEJO_ID_SEJO AND SEJO_ID_ETAB_CON IN ([ID_ETAB])
									JOIN prod_hm.PAD_LIT_POSTE ON MOUV_ID_LIPO = LIPO_ID_LIPO
									JOIN prod_hm.PAD_CHAMBRE_SALLE ON LIPO_ID_CHAS = CHAS_ID_CHAS
									JOIN activite[PX].t_etages ON MOUV_ID_UNFO = t_etages.code_original
									WHERE MOUV_ID_UNFO <> CHAS_ID_UNFO AND
										(MOUV_ID_UNFO || '-' || LIPO_ID_LIPO) NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL  )
									GROUP BY 1,2,3,4,5,6;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
							SELECT code_original || '-0' , '', 'Non renseigné', 'Non renseigné', oid, 'O'
									FROM activite[PX].t_etages
									WHERE oid > 0 AND
										code_original || '-0' NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL );

				UPDATE activite[PX].t_lits SET code = '*****' WHERE code = '';
			]]></sqlcmd>
	</NODE>

	<NODE label="Facturation">
		<sqlcmd><![CDATA[

				-- Comptes
				INSERT INTO activite[PX].t_compte(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_compte);


				-- Changement d'identification du code original, le numéro devient le code original
				DELETE FROM activite[PX].t_compte
				USING
				(
				SELECT code, min(oid) AS keep_oid
				FROM activite[PX].t_compte
				WHERE oid <> 0
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE t_compte.code = subview.code AND
					oid <> keep_oid
				;

				UPDATE activite[PX].t_compte
				SET code_original = code
				WHERE oid <> 0 AND
					code <> code_original
				;


				DROP TABLE IF EXISTS w_LECR_COMPTE;
				CREATE TEMP TABLE w_LECR_COMPTE AS
				SELECT CASE
					WHEN LECR_NUM_COMPTE <> '' THEN LECR_NUM_COMPTE
					WHEN CPTE_NUM_COMPTE <> '' THEN CPTE_NUM_COMPTE
					ELSE CPTE_CODE END AS LECR_NUM_COMPTE,
					MAX(LECR_ID_CPTE) AS LECR_ID_CPTE, ''::text AS CPTE_LIBELLE
				FROM prod_hm.CCL_LIGNE_ECRITURE
				JOIN prod_hm.CCL_COMPTE ON LECR_ID_CPTE = CPTE_ID_CPTE
				GROUP BY 1
				;

				ANALYSE w_LECR_COMPTE
				;

				UPDATE w_LECR_COMPTE
				SET CPTE_LIBELLE = CCL_COMPTE.CPTE_LIBELLE
				FROM prod_hm.CCL_COMPTE
				WHERE LECR_NUM_COMPTE = CPTE_NUM_COMPTE
				;
				UPDATE w_LECR_COMPTE
				SET CPTE_LIBELLE = CCL_COMPTE.CPTE_LIBELLE
				FROM prod_hm.CCL_COMPTE
				WHERE w_LECR_COMPTE.CPTE_LIBELLE = '' AND
					LECR_NUM_COMPTE = CPTE_CODE
				;
				UPDATE w_LECR_COMPTE
				SET CPTE_LIBELLE = CCL_COMPTE.CPTE_LIBELLE
				FROM prod_hm.CCL_COMPTE
				WHERE w_LECR_COMPTE.CPTE_LIBELLE = '' AND
					LECR_ID_CPTE = CPTE_ID_CPTE
				;
				UPDATE w_LECR_COMPTE
				SET CPTE_LIBELLE = LECR_NUM_COMPTE
				WHERE CPTE_LIBELLE = ''
				;

				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT LECR_NUM_COMPTE,
					LECR_NUM_COMPTE,
					CPTE_LIBELLE,
					CPTE_LIBELLE
				FROM w_LECR_COMPTE
				WHERE LECR_NUM_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				;

				UPDATE activite[PX].t_compte SET
					code = LECR_NUM_COMPTE,
					texte = CPTE_LIBELLE,
					texte_court = CPTE_LIBELLE
				FROM w_LECR_COMPTE
				WHERE t_compte.code_original = LECR_NUM_COMPTE AND
					(
					code IS DISTINCT FROM LECR_NUM_COMPTE OR
					texte IS DISTINCT FROM CPTE_LIBELLE OR
					texte_court IS DISTINCT FROM CPTE_LIBELLE
					)
				;

				-- Rubriques et prestations

				INSERT INTO activite[PX].t_rubriques_facturation(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_rubriques_facturation);

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO', 'ACOMPTE', 'Acomptes', 'Acomptes'
				WHERE '*CTI_ACO' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

				UPDATE activite[PX].t_rubriques_facturation
				SET code = '#'||PRSE_CODE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE code_original = PRSE_ID_PRSE AND
					code IS DISTINCT FROM PRSE_CODE;

				UPDATE activite[PX].t_rubriques_facturation
				SET code = PRSE_CODE,
					texte = PRSE_LIBELLE,
					texte_court = PRSE_LIBELLE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE code_original = PRSE_ID_PRSE AND
				(
					code IS DISTINCT FROM PRSE_CODE OR
					texte IS DISTINCT FROM PRSE_LIBELLE OR
					texte_court IS DISTINCT FROM PRSE_LIBELLE
				);

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRSE_ID_PRSE::bigint, PRSE_CODE, PRSE_LIBELLE, PRSE_LIBELLE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE PRSE_ID_ETAB IN ([ID_ETAB])
					AND PRSE_ID_PRSE::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRSE_ID_PRSE IN (SELECT LFAC_ID_PRSE FROM prod_hm.FAC_LIGNE_FACTURE)
				ORDER BY PRSE_CODE;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRSE_ID_PRSE::bigint, PRSE_CODE, PRSE_LIBELLE, PRSE_LIBELLE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE
					PRSE_ID_PRSE::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRSE_ID_PRSE IN (SELECT LFAC_ID_PRSE FROM prod_hm.FAC_LIGNE_FACTURE WHERE LFAC_ID_ETAB_D IN ([ID_ETAB]) )
				ORDER BY PRSE_CODE;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRSE_ID_PRSE::bigint, PRSE_CODE, PRSE_LIBELLE, PRSE_LIBELLE
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE PRSE_ID_ETAB IN ([ID_ETAB])
					AND PRSE_ID_PRSE::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRSE_ID_PRSE IN (SELECT ACSA_ID_PRSE FROM prod_hm.SAD_ACTIVITE_SAISIES)
				ORDER BY PRSE_CODE;

				UPDATE activite[PX].t_rubriques_facturation
				SET code = '#' || PRHO_CODE || '_H'
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				WHERE code_original = PRHO_ID_PRHO AND
					code IS DISTINCT FROM PRHO_CODE AND
					code IS DISTINCT FROM (PRHO_CODE || '_H');

				UPDATE activite[PX].t_rubriques_facturation
				SET code = PRHO_CODE || '_H',
					texte = PRHO_LIBELLE,
					texte_court = PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				WHERE code_original = PRHO_ID_PRHO AND
					code IS DISTINCT FROM PRHO_CODE AND
				(
					code IS DISTINCT FROM  PRHO_CODE || '_H' OR
					texte IS DISTINCT FROM PRHO_LIBELLE OR
					texte_court IS DISTINCT FROM PRHO_LIBELLE
				);

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRHO_ID_PRHO::bigint, PRHO_CODE, PRHO_LIBELLE, PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE JOIN prod_hm.BAS_ETABLISSEMENT ON PRHO_ID_ETAB = ETAB_ID_ETAB AND ETAB_TYP_ETAB = 'PSPH'
				WHERE PRHO_ID_ETAB IN ([ID_ETAB])
					AND PRHO_ID_PRHO::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_ID_PRHO IN (SELECT LFAC_ID_PRHO FROM prod_hm.FAC_LIGNE_FACTURE)
				ORDER BY PRHO_CODE;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRHO_ID_PRHO::bigint, PRHO_CODE || '_H', PRHO_LIBELLE, PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE JOIN prod_hm.BAS_ETABLISSEMENT ON PRHO_ID_ETAB = ETAB_ID_ETAB AND ETAB_TYP_ETAB = 'PSPH'
				WHERE PRHO_ID_ETAB IN ([ID_ETAB])
					AND PRHO_ID_PRHO::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE || '_H' NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_ID_PRHO IN (SELECT LFAC_ID_PRHO FROM prod_hm.FAC_LIGNE_FACTURE)
				ORDER BY PRHO_CODE;

                INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRHO_ID_PRHO::bigint, PRHO_CODE, PRHO_LIBELLE, PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE JOIN prod_hm.BAS_ETABLISSEMENT ON PRHO_ID_ETAB = ETAB_ID_ETAB AND ETAB_TYP_ETAB <> 'PSPH'
				WHERE PRHO_ID_ETAB IN ([ID_ETAB])
					AND PRHO_ID_PRHO::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_ID_PRHO IN (SELECT LFAC_ID_PRHO FROM prod_hm.FAC_LIGNE_FACTURE WHERE LFAC_CDT_EXC = 'S')
				ORDER BY PRHO_CODE;

                -- Rubriques pour médecins salariés
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRHO_ID_PRHO::bigint, PRHO_CODE, PRHO_LIBELLE, PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				WHERE PRHO_ID_ETAB IN ([ID_ETAB])
					AND PRHO_ID_PRHO::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_ID_PRHO IN (SELECT LFAC_ID_PRHO FROM prod_hm.FAC_LIGNE_FACTURE WHERE LFAC_CDT_EXC = 'S')
				ORDER BY PRHO_CODE;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT PRHO_ID_PRHO::bigint, PRHO_CODE, PRHO_LIBELLE, PRHO_LIBELLE
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				WHERE PRHO_ID_PRHO::bigint NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
					AND PRHO_CODE NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation)
					AND PRHO_ID_PRHO IN (SELECT LFAC_ID_PRHO FROM prod_hm.FAC_LIGNE_FACTURE WHERE LFAC_ID_ETAB_D IN ([ID_ETAB]) AND LFAC_CDT_EXC = 'S')
				ORDER BY PRHO_CODE;

				INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
				SELECT CASE WHEN TRIM(PRSE_LET_CLE) <> '' THEN PRSE_LET_CLE ELSE PRSE_CODE END, CASE WHEN TRIM(PRSE_LET_CLE) <> '' THEN PRSE_LET_CLE ELSE PRSE_CODE END, MIN(PRSE_LIBELLE) , MIN(PRSE_LIBELLE)
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				WHERE PRSE_ID_ETAB IN ([ID_ETAB])
					AND CASE WHEN TRIM(PRSE_LET_CLE) <> '' THEN PRSE_LET_CLE ELSE PRSE_CODE END NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO', 'ACOMPTE', 'Acomptes', 'Acomptes'
				WHERE '*CTI_ACO' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);

				INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
				SELECT CASE WHEN TRIM(PRHO_LET_CLE) <> ''  THEN PRHO_LET_CLE ELSE PRHO_CODE END, CASE WHEN TRIM(PRHO_LET_CLE) <> '' THEN PRHO_LET_CLE ELSE PRHO_CODE END, MIN(PRHO_LIBELLE) , MIN(PRHO_LIBELLE)
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				WHERE PRHO_ID_ETAB IN ([ID_ETAB])
					AND CASE WHEN TRIM(PRHO_LET_CLE) <> '' THEN PRHO_LET_CLE ELSE PRHO_CODE END NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1,2
				ORDER BY 1;

				INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
				SELECT DISTINCT LFAC_LET_CLE, LFAC_LET_CLE, LFAC_LET_CLE , LFAC_LET_CLE
				FROM prod_hm.FAC_LIGNE_FACTURE
				WHERE LFAC_LET_CLE NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL) AND
					LFAC_LET_CLE <> ''
				ORDER BY 1;



				UPDATE activite[PX].t_protocoles SET
					code = FAVO_CODE::text,
					texte = FAVO_LIBELLE::text,
					texte_court = FAVO_LIBELLE::text
				FROM
					prod_hm.SAD_FAVORIS
				WHERE 1=1
					AND FAVO_ID_FAVO = t_protocoles.code_original
					AND (FAVO_CODE <> t_protocoles.code OR FAVO_LIBELLE <> t_protocoles.texte);


				INSERT INTO activite[PX].t_protocoles(oid, code_original, code, texte, texte_court)
				SELECT 0, 0, '***', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_protocoles);

				INSERT INTO activite[PX].t_protocoles(code_original, code, texte, texte_court)
				SELECT FAVO_ID_FAVO::bigint, FAVO_CODE, FAVO_LIBELLE, FAVO_LIBELLE
				FROM prod_hm.SAD_FAVORIS
				WHERE FAVO_ID_FAVO IN (SELECT LFAC_ID_FAVO FROM prod_hm.FAC_LIGNE_FACTURE GROUP BY 1) AND
					FAVO_ID_FAVO::bigint NOT IN (SELECT code_original FROM activite[PX].t_protocoles)
				ORDER BY FAVO_CODE;




			]]></sqlcmd>
	</NODE>

</NODE>

<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">

	<NODE label="Calcul -10% SSR">
		<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_moins10;
				CREATE TEMP TABLE w_moins10 AS
				SELECT p_factures_lignes_c.*,
					p_factures_lignes_c.CTID AS CTID_orig,
					CASE
						WHEN (t_prestations.code = 'PJ' OR type_valorisation_non_facture = 'PJ') AND
							montant_comptabilise_0=0 AND
							montant_comptabilise_2=0 AND
							montant_comptabilise_22=0 AND
							ABS(round(((prix_unitaire*nb_prestation*0.9)-montant_comptabilise_1)/nb_prestation,0)) BETWEEN 17 AND 37
						THEN round(((prix_unitaire*nb_prestation*0.9)-montant_comptabilise_1)/ABS(nb_prestation),2)
						ELSE 0::numeric END AS montant_fj,
						t_prestations.code AS prestation_code,
						type_valorisation_non_facture,
						'M'::text || CASE WHEN t_prestations.code <> 'PJ' THEN t_prestations.code ELSE 'PJS' END AS prestation_mcode
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation ON t_services_facturation.oid = service_facturation_id
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE date_fin >= '20170701' AND
					date_debut >= '20170701' AND
					type_t2a = '2' AND
					prestation_id = ANY (SELECT to_id FROM activite.t_listes_contenu JOIN activite.t_listes ON liste_id = t_listes.oid AND t_listes.code = 'DMAP_MFS') AND
					montant_comptabilise <> 0 AND
					montant_comptabilise_1 <> 0 AND
					round(prix_unitaire * nb_prestation,2) <> montant_comptabilise AND
					abs(round(prix_unitaire * nb_prestation,2)) <> abs(montant_comptabilise)+(nb_prestation*18)
				ORDER BY no_facture, prestation_id
				;

				-- Calcul tarif plein
				UPDATE w_moins10 SET
					montant_facture_1 =
						CASE WHEN prestation_code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN round(prix_unitaire * nb_prestation * taux_1 / 100,2) - montant_fj
						ELSE round(prix_unitaire * nb_prestation * taux_1 / 100,2) END,
					montant_facture =
						CASE WHEN prestation_code = 'PJ' OR type_valorisation_non_facture = 'PJ' THEN round(prix_unitaire * nb_prestation * taux_1 / 100,2) - montant_fj
						ELSE round(prix_unitaire * nb_prestation * taux_1 / 100,2) END +
							(montant_facture_2+montant_facture_22+montant_facture_0)
				;

				-- Génération prestations spécifiques
				INSERT INTO activite.t_prestations (code, texte, texte_court)
				SELECT prestation_mcode, t_prestations.texte || ' (-10%)', t_prestations.texte || ' (-10%)'
				FROM w_moins10
				JOIN activite.t_prestations on prestation_id = t_prestations.oid
				WHERE prestation_mcode NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1,2,3
				;

				-- Maj tarif plein
				UPDATE activite[PX].p_factures_lignes_c
				SET montant_facture = w_moins10.montant_facture, montant_facture_1 = w_moins10.montant_facture_1
				FROM w_moins10
				WHERE p_factures_lignes_c.CTID = w_moins10.CTID_orig;
				;

				-- Génération -10%
				UPDATE w_moins10 SET
					montant_facture = montant_comptabilise - montant_facture,
					montant_facture_1 = montant_comptabilise_1 - montant_facture_1,
					montant_facture_2 = montant_comptabilise_2 - montant_facture_2,
					montant_facture_22 = montant_comptabilise_22 - montant_facture_22,
					montant_facture_0 = montant_comptabilise_0 - montant_facture_0,
					montant_comptabilise = 0,
					montant_comptabilise_1 = 0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_22 = 0,
					montant_comptabilise_0 = 0,
					prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE t_prestations.code = prestation_mcode
				;

				ALTER TABLE w_moins10 DROP COLUMN CTID_orig;
				ALTER TABLE w_moins10 DROP COLUMN montant_fj;
				ALTER TABLE w_moins10 DROP COLUMN prestation_code;
				ALTER TABLE w_moins10 DROP COLUMN prestation_mcode;
                ALTER TABLE w_moins10 DROP COLUMN type_valorisation_non_facture;

				INSERT INTO activite[PX].p_factures_lignes_c
				SELECT *
				FROM w_moins10
				WHERE montant_facture <> 0
				;


				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_lignes_c');
			]]></sqlcmd>
	</NODE>

	<NODE label="compléments patients">
		<sqlcmd><![CDATA[

				-- Medecin par patient HM
				DROP TABLE IF EXISTS w_PATI_MED_TRT;
				CREATE TEMP TABLE w_PATI_MED_TRT AS
				SELECT
					PATI_NIP,
					(MAX(ARRAY[MESE_DAT_DEB::text,MESE_ID_MEDE::text]))[2]::bigint AS MESE_ID_MEDE
				FROM prod_hm.IDE_MED_VENUE
				JOIN prod_hm.IDE_SEJOUR ON MESE_ID_SEJO = SEJO_ID_SEJO
				JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
				JOIN prod_hm.BAS_CATALOGUE_PERS ON MESE_ID_CAPE = CAPE_ID_CAPE
				WHERE CAPE_CODE = '2'
				GROUP BY 1;

				CREATE INDEX w_PATI_MED_TRT_i1 ON w_PATI_MED_TRT USING btree (PATI_NIP);


				-- Médecins traitants
				INSERT INTO activite[PX].t_medecins_traitants_administratifs(code_original, code, nom, prenom, specialite_id, no_rpps)
				SELECT MEDE_ID_MEDE::bigint,
					CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE ELSE MEDE_ID_MEDE::text END AS MEDE_CODE,
					MEDE_NOM_USU,
					COALESCE(MEDE_PRENOM,'') AS MEDE_PRENOM,
					0,
					''
				FROM prod_hm.IDE_MEDECIN
					LEFT JOIN (SELECT MEDI_ID_MEDE, MAX(MEDI_ADELI) AS MEDI_ADELI FROM prod_hm.IDE_MEDECIN_IMMAT WHERE MEDI_ID_ETAB IN ([ID_ETAB]) GROUP BY 1) subview
						ON (MEDE_ID_MEDE = MEDI_ID_MEDE)
				WHERE MEDE_ID_MEDE IN (SELECT MESE_ID_MEDE FROM w_PATI_MED_TRT) AND
					MEDE_ID_MEDE NOT IN (SELECT code_original FROM activite[PX].t_medecins_traitants_administratifs)
					;


				UPDATE activite[PX].t_medecins_traitants_administratifs SET
					code = CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE ELSE MEDE_ID_MEDE::text END,
					nom = MEDE_NOM_USU,
					prenom = COALESCE(MEDE_PRENOM,'')
				FROM prod_hm.IDE_MEDECIN
				WHERE t_medecins_traitants_administratifs.code_original = MEDE_ID_MEDE::bigint AND
					(
					code IS DISTINCT FROM CASE WHEN MEDE_CODE <> '' AND MEDE_CODE IS NOT NULL THEN MEDE_CODE ELSE MEDE_ID_MEDE::text END OR
					nom IS DISTINCT FROM MEDE_NOM_USU OR
					prenom IS DISTINCT FROM COALESCE(MEDE_PRENOM,'')
					)
				;

				--  maj code rpps
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET no_rpps = MEIN_IDE_NATIONALE
				FROM prod_hm.IDE_MEDECIN_IDENT_NATIONALE
				WHERE code_original = MEIN_ID_MEDE AND
					t_medecins_traitants_administratifs.no_rpps IS DISTINCT FROM MEIN_IDE_NATIONALE;


				-- maj id médecin_traitant dans séjours
				UPDATE activite[PX].p_sejours
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM w_PATI_MED_TRT
				JOIN activite[PX].t_medecins_traitants_administratifs ON t_medecins_traitants_administratifs.code_original = MESE_ID_MEDE
				WHERE no_patient = PATI_NIP AND
					medecin_traitant_id IS DISTINCT FROM t_medecins_traitants_administratifs.oid;
				;

				-- ajout des coordonnées par séjour
				INSERT INTO activite[PX].p_coordonnees_patient (
					sejour_id,
					adresse,
					code_postal_id,
					commune,
					telephone_fixe,
					telephone_portable,
					email
				)
				WITH
					w_TEL AS ( 	SELECT TELE_ID_OBJ, regexp_replace(TELE_NUM_TEL,'[^0-9]','','g') as TELE_NUM_TEL FROM prod_hm.IDE_TELEPHONE),
					w_ADR AS ( 	SELECT DISTINCT ADRE_ID_OBJ,
									last_value(ADRE_LIGNE1) OVER (PARTITION BY ADRE_ID_OBJ ORDER BY ADRE_DAT_MOD rows between unbounded preceding and unbounded following) AS ADRE_LIGNE1,
									last_value(ADRE_LIGNE2) OVER (PARTITION BY ADRE_ID_OBJ ORDER BY ADRE_DAT_MOD rows between unbounded preceding and unbounded following) AS ADRE_LIGNE2,
									last_value(ADRE_LIGNE3) OVER (PARTITION BY ADRE_ID_OBJ ORDER BY ADRE_DAT_MOD rows between unbounded preceding and unbounded following) AS ADRE_LIGNE3,
									last_value(ADRE_COD_POS) OVER (PARTITION BY ADRE_ID_OBJ ORDER BY ADRE_DAT_MOD rows between unbounded preceding and unbounded following) AS ADRE_COD_POS,
									last_value(ADRE_VILLE) OVER (PARTITION BY ADRE_ID_OBJ ORDER BY ADRE_DAT_MOD rows between unbounded preceding and unbounded following) AS ADRE_VILLE
								FROM prod_hm.IDE_ADRESSE
								WHERE ADRE_LIGNE1 != ''
							)
				SELECT
					p_sejours.oid,
					ADRE_LIGNE1 || CASE WHEN ADRE_LIGNE2 != '' THEN ' - ' || ADRE_LIGNE2 ELSE '' END || CASE WHEN ADRE_LIGNE3 != '' THEN ' - ' || ADRE_LIGNE3 ELSE '' END,
					COALESCE(t_codes_postaux.oid,0),
					ADRE_VILLE,
					STRING_AGG(CASE WHEN SUBSTR(TELE_NUM_TEL,2,1) IN (1,2,3,4,5,9) THEN TELE_NUM_TEL ELSE null END,','),
					STRING_AGG(CASE WHEN SUBSTR(TELE_NUM_TEL,2,1) NOT IN (1,2,3,4,5,9) THEN TELE_NUM_TEL ELSE null END,','),
					PATI_EMAIL
				FROM activite[PX].p_sejours
					JOIN prod_hm.IDE_SEJOUR ON SEJO_ID_SEJO = code_original
					JOIN prod_hm.IDE_PATIENT ON SEJO_ID_PATI = PATI_ID_PATI
					JOIN w_ADR ON PATI_ID_PATI = ADRE_ID_OBJ
					LEFT JOIN base.t_codes_postaux ON ADRE_COD_POS = t_codes_postaux.code
					LEFT JOIN w_TEL ON PATI_ID_PATI = TELE_ID_OBJ
				GROUP BY 1,2,3,4,7
				]]></sqlcmd>
	</NODE>
	<NODE label="Compléments facture">
		<sqlcmd><![CDATA[
				ANALYSE activite[PX].p_factures;
				ANALYSE activite[PX].p_factures_lignes_h;


				DROP TABLE IF EXISTS w_factures;
				CREATE TEMP TABLE w_factures AS
				SELECT
					no_facture,
					no_facture_reference,
					CASE WHEN date_expedition_0 < date_facture AND date_facture <> '2099-12-31' THEN date_facture ELSE date_expedition_0 END AS date_expedition_0,

					CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde,
					CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde_c,
					CASE WHEN montant_comptabilise_1_h = 0 THEN '00010101' WHEN montant_comptabilise_1_h = montant_regle_1_h THEN date_solde_1_h ELSE '20991231' END AS date_solde_h,
					CASE WHEN montant_comptabilise_0_c = 0 THEN '00010101' WHEN montant_comptabilise_0_c = montant_regle_0_c THEN date_solde_0_c ELSE '20991231' END AS date_solde_0_c,
					CASE WHEN montant_comptabilise_0_h = 0 THEN '00010101' WHEN montant_comptabilise_0_h = montant_regle_0_h THEN date_solde_0_h ELSE '20991231' END AS date_solde_0_h,
					CASE WHEN montant_comptabilise_1_c = 0 THEN '00010101' WHEN montant_comptabilise_1_c = montant_regle_1_c THEN date_solde_1_c ELSE '20991231' END AS date_solde_1_c,
					CASE WHEN montant_comptabilise_1_h = 0 THEN '00010101' WHEN montant_comptabilise_1_h = montant_regle_1_h THEN date_solde_1_h ELSE '20991231' END AS date_solde_1_h,
					CASE WHEN montant_comptabilise_2_c = 0 THEN '00010101' WHEN montant_comptabilise_2_c = montant_regle_2_c THEN date_solde_2_c ELSE '20991231' END AS date_solde_2_c,
					CASE WHEN montant_comptabilise_2_h = 0 THEN '00010101' WHEN montant_comptabilise_2_h = montant_regle_2_h THEN date_solde_2_h ELSE '20991231' END AS date_solde_2_h,
					CASE WHEN montant_comptabilise_22_c = 0 THEN '00010101' WHEN montant_comptabilise_22_c = montant_regle_22_c THEN date_solde_22_c ELSE '20991231' END AS date_solde_22_c,
					CASE WHEN montant_comptabilise_22_h = 0 THEN '00010101' WHEN montant_comptabilise_22_h = montant_regle_22_h THEN date_solde_22_h ELSE '20991231' END AS date_solde_22_h
				FROM activite[PX].p_factures;

				UPDATE w_factures SET
					date_solde = GREATEST(date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h),
					date_solde_c = GREATEST(date_solde_0_c, date_solde_1_c, date_solde_2_c, date_solde_22_c),
					date_solde_h = GREATEST(date_solde_0_h, date_solde_1_h, date_solde_2_h, date_solde_22_h)
				WHERE
					date_solde IS DISTINCT FROM GREATEST(date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h) OR
					date_solde_c IS DISTINCT FROM GREATEST(date_solde_0_c, date_solde_1_c, date_solde_2_c, date_solde_22_c) OR
					date_solde_h IS DISTINCT FROM GREATEST(date_solde_0_h, date_solde_1_h, date_solde_2_h, date_solde_22_h) ;

				CREATE INDEX w_factures_i1
					ON w_factures
					USING btree
					(no_facture);

				CREATE INDEX w_factures_i2
					ON w_factures
					USING btree
					(no_facture_reference);



				DROP TABLE IF EXISTS w_factures_references_soldes;

				CREATE TEMP TABLE w_factures_references_soldes AS
				SELECT
					no_facture_reference,
					MAX(date_solde) AS date_solde_reference,
					MAX(date_solde_c) AS date_solde_reference_c,
					MAX(date_solde_h) AS date_solde_reference_h,
					MAX(date_solde_0_c) AS date_solde_reference_0_c,
					MAX(date_solde_0_h) AS date_solde_reference_0_h,
					MAX(date_solde_1_c) AS date_solde_reference_1_c,
					MAX(date_solde_1_h) AS date_solde_reference_1_h,
					MAX(date_solde_2_c) AS date_solde_reference_2_c,
					MAX(date_solde_2_h) AS date_solde_reference_2_h,
					MAX(date_solde_22_c) AS date_solde_reference_22_c,
					MAX(date_solde_22_h) AS date_solde_reference_22_h
				FROM w_factures
				GROUP BY no_facture_reference;


				CREATE INDEX w_factures_references_soldes_i1
				ON w_factures_references_soldes
				USING btree
				(no_facture_reference);




				UPDATE activite[PX].p_factures
				SET
					date_expedition_0 = w_factures.date_expedition_0,
					date_solde = w_factures.date_solde,
					date_solde_c = w_factures.date_solde_c,
					date_solde_h = w_factures.date_solde_h,
					date_solde_0_c = w_factures.date_solde_0_c,
					date_solde_0_h = w_factures.date_solde_0_h,
					date_solde_1_c = w_factures.date_solde_1_c,
					date_solde_1_h = w_factures.date_solde_1_h,
					date_solde_2_c = w_factures.date_solde_2_c,
					date_solde_2_h = w_factures.date_solde_2_h,
					date_solde_22_c = w_factures.date_solde_22_c,
					date_solde_22_h = w_factures.date_solde_22_h,
					date_solde_reference = w_factures_references_soldes.date_solde_reference,
					date_solde_reference_c = w_factures_references_soldes.date_solde_reference_c,
					date_solde_reference_h = w_factures_references_soldes.date_solde_reference_h,
					date_solde_reference_0_c = w_factures_references_soldes.date_solde_reference_0_c,
					date_solde_reference_0_h = w_factures_references_soldes.date_solde_reference_0_h,
					date_solde_reference_1_c = w_factures_references_soldes.date_solde_reference_1_c,
					date_solde_reference_1_h = w_factures_references_soldes.date_solde_reference_1_h,
					date_solde_reference_2_c = w_factures_references_soldes.date_solde_reference_2_c,
					date_solde_reference_2_h = w_factures_references_soldes.date_solde_reference_2_h,
					date_solde_reference_22_c = w_factures_references_soldes.date_solde_reference_22_c,
					date_solde_reference_22_h = w_factures_references_soldes.date_solde_reference_22_h
				FROM w_factures
					JOIN w_factures_references_soldes ON w_factures_references_soldes.no_facture_reference = w_factures.no_facture_reference
				WHERE p_factures.no_facture = w_factures.no_facture
				AND (
					p_factures.date_expedition_0 IS DISTINCT FROM w_factures.date_expedition_0 OR
					p_factures.date_solde IS DISTINCT FROM w_factures.date_solde OR
					p_factures.date_solde_c IS DISTINCT FROM w_factures.date_solde_c OR
					p_factures.date_solde_h IS DISTINCT FROM w_factures.date_solde_h OR
					p_factures.date_solde_0_c IS DISTINCT FROM w_factures.date_solde_0_c OR
					p_factures.date_solde_0_h IS DISTINCT FROM w_factures.date_solde_0_h OR
					p_factures.date_solde_1_c IS DISTINCT FROM w_factures.date_solde_1_c OR
					p_factures.date_solde_1_h IS DISTINCT FROM w_factures.date_solde_1_h OR
					p_factures.date_solde_2_c IS DISTINCT FROM w_factures.date_solde_2_c OR
					p_factures.date_solde_2_h IS DISTINCT FROM w_factures.date_solde_2_h OR
					p_factures.date_solde_22_c IS DISTINCT FROM w_factures.date_solde_22_c OR
					p_factures.date_solde_22_h IS DISTINCT FROM w_factures.date_solde_22_h OR
					p_factures.date_solde_reference IS DISTINCT FROM w_factures_references_soldes.date_solde_reference OR
					p_factures.date_solde_reference_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_c OR
					p_factures.date_solde_reference_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_h OR
					p_factures.date_solde_reference_0_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_0_c OR
					p_factures.date_solde_reference_0_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_0_h OR
					p_factures.date_solde_reference_1_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_1_c OR
					p_factures.date_solde_reference_1_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_1_h OR
					p_factures.date_solde_reference_2_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_2_c OR
					p_factures.date_solde_reference_2_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_2_h OR
					p_factures.date_solde_reference_22_c IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_22_c OR
					p_factures.date_solde_reference_22_h IS DISTINCT FROM w_factures_references_soldes.date_solde_reference_22_h
				);

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_factures CASCADE;
				DROP TABLE IF EXISTS w_factures_references_soldes CASCADE;

                -- Elimination des protocoles sur avoirs et factures annulées pour comptage correct
                DROP TABLE IF EXISTS w_correction_protocole
				;
                CREATE TEMP TABLE w_correction_protocole AS
                SELECT no_facture_reference,
                    (MAX(ARRAY[CASE WHEN p_factures_lignes_h.nb_prestation >= 0 THEN '1' ELSE '0' END, date_facture::text,p_factures.no_facture]))[3] AS no_facture_ok,
                    base.cti_array_accum(DISTINCT p_factures.no_facture) AS facture_array
                FROM activite[PX].p_factures
                JOIN activite[PX].p_factures_lignes_h ON p_factures.no_facture = p_factures_lignes_h.no_facture
                WHERE p_factures.no_facture NOT LIKE '%BG' AND
                    protocole_id IS NOT NULL AND
                    protocole_id <> 0
                GROUP BY 1
                HAVING MIN(p_factures_lignes_h.montant_facture) < 0
                ;
				ANALYSE w_correction_protocole
				;

				-- Etape internmédiaire pour avoir la colonne facture_array ligne par ligne (pour performance)
				DROP TABLE IF EXISTS w_correction_protocole_factures_lignes;
				CREATE TEMP TABLE w_correction_protocole_factures_lignes AS
				SELECT no_facture_reference,
					no_facture_ok,
					UNNEST(facture_array::text[]) no_facture_par_ligne
				FROM w_correction_protocole
				;
				ANALYSE w_correction_protocole_factures_lignes
				;

                UPDATE activite[PX].p_factures_lignes_h
                SET protocole_id = 0
                FROM w_correction_protocole_factures_lignes
                WHERE p_factures_lignes_h.no_facture = no_facture_par_ligne AND
					p_factures_lignes_h.no_facture <> no_facture_ok
                ;

				-- Taux pour le budget global (actes inclus)
				DROP TABLE IF EXISTS w_sejour_taux1;
				CREATE TEMP TABLE w_sejour_taux1 AS
				SELECT no_sejour, (MAX(ARRAY[p_factures.date_facture::text, taux_1::text]))[2]::numeric AS taux_1
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE '[ENV_TYPEETS]' <> '1' AND
					t_prestations.code = 'GHS' AND
					code_facture = '1' AND
					p_factures_lignes_c.montant_facture <> 0
				GROUP BY 1
				;

				ANALYSE w_sejour_taux1
				;

				INSERT INTO w_sejour_taux1
				SELECT p_factures.no_sejour, (MAX(ARRAY[p_factures.date_facture::text, p_factures_lignes_c.taux_1::text]))[2]::numeric AS taux_1
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				LEFT JOIN w_sejour_taux1 ON p_factures.no_sejour = w_sejour_taux1.no_sejour
				WHERE '[ENV_TYPEETS]' <> '1' AND
					t_prestations.code = 'PJ' AND
					code_facture = '1' AND
					p_factures_lignes_c.montant_facture <> 0 AND
					w_sejour_taux1.no_sejour IS NULL
				GROUP BY 1
				;

				UPDATE activite[PX].p_factures_lignes_h SET
					taux_1 = w_sejour_taux1.taux_1
				FROM activite[PX].p_factures
					JOIN w_sejour_taux1 ON p_factures.no_sejour = w_sejour_taux1.no_sejour
				WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
					montant_facture_actes_inclus_dans_sejour <> 0 AND
					p_factures_lignes_h.taux_1 <> w_sejour_taux1.taux_1
				;


				DROP TABLE IF EXISTS w_sejour_taux1_div;
				CREATE TEMP TABLE w_sejour_taux1_div AS
				SELECT no_sejour, acte_id, p_factures_lignes_h.date_debut, medecin_facture_id, MAX(taux_1) AS taux_1
				FROM activite[PX].p_factures_lignes_h
				JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture
				WHERE '[ENV_TYPEETS]' <> '1' AND
					montant_facture_actes_inclus_dans_sejour <> 0
				GROUP BY 1,2,3,4
				HAVING count(DISTINCT taux_1) > 1
				;

				ANALYSE w_sejour_taux1_div
				;

				UPDATE activite[PX].p_factures_lignes_h SET
					taux_1 = w_sejour_taux1_div.taux_1
				FROM activite[PX].p_factures
					JOIN w_sejour_taux1_div ON p_factures.no_sejour = w_sejour_taux1_div.no_sejour
				WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
					montant_facture_actes_inclus_dans_sejour <> 0 AND
					p_factures.no_sejour = w_sejour_taux1_div.no_sejour AND
					p_factures_lignes_h.acte_id = w_sejour_taux1_div.acte_id AND
					p_factures_lignes_h.date_debut = w_sejour_taux1_div.date_debut AND
					p_factures_lignes_h.medecin_facture_id = w_sejour_taux1_div.medecin_facture_id AND
					p_factures_lignes_h.taux_1 <> w_sejour_taux1_div.taux_1
				;

			]]></sqlcmd>
	</NODE>

	<NODE label="Compléments séjours">
		<sqlcmd><![CDATA[

				UPDATE activite[PX].p_sejours
				SET date_groupage = date_facture
				WHERE (date_groupage IS null OR date_groupage = '20991231') AND
					date_facture <> '2099-12-31';


				DROP TABLE IF EXISTS w_sejours_total;
				CREATE TEMP TABLE w_sejours_total AS
				SELECT
					p_sejours.no_sejour AS no_sejour,
					p_sejours.code_sorti,
					p_sejours.date_sortie,
					p_sejours.date_groupage,
					p_sejours.ghs_id,

					MAX(COALESCE(p_factures.date_facture,'20991231')) AS date_facture,
					MAX(COALESCE(p_factures.date_expedition,'20991231')) AS date_expedition,
					MAX(COALESCE(p_factures.date_solde,'20991231')) AS date_solde,
					SUM(COALESCE(p_factures.montant_facture_c,0)) AS montant_facture_c,
					SUM(COALESCE(p_factures.montant_facture_h,0)) AS montant_facture_h,
					SUM(COALESCE(p_factures.montant_regle_c,0)) AS montant_regle_c,
					SUM(COALESCE(p_factures.montant_regle_h,0)) AS montant_regle_h,
					SUM(COALESCE(CASE WHEN p_factures.type_facture <> 'P' AND p_factures.type_facture <> 'E' AND p_factures.type_facture <> 'G' THEN 1 ELSE 0 END,0)) AS nb_factures,
					SUM(COALESCE(CASE WHEN p_factures.type_facture = '0' THEN 0 ELSE 1 END,0)) AS nb_factures_regularisation,
					SUM(COALESCE(p_factures.nb_rejets,0)) AS nb_rejets,

					SUM(COALESCE(p_factures.montant_facture_0_c,0)) AS montant_facture_0_c,
					SUM(COALESCE(p_factures.montant_facture_0_h,0)) AS montant_facture_0_h,
					SUM(COALESCE(p_factures.montant_regle_0_c,0)) AS montant_regle_0_c,
					SUM(COALESCE(p_factures.montant_regle_0_h,0)) AS montant_regle_0_h,
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_0_c <> 0 OR p_factures.montant_facture_0_h <> 0)  THEN p_factures.date_expedition_0 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_0,
					MAX(COALESCE(CASE WHEN p_factures.date_solde_0_c < '2099-12-31' AND p_factures.date_solde_0_c > p_factures.date_solde_0_h THEN p_factures.date_solde_0_c ELSE p_factures.date_solde_0_h END,'20991231' )) AS date_solde_0,


					SUM(COALESCE(p_factures.montant_facture_1_c,0)) AS montant_facture_1_c,
					SUM(COALESCE(p_factures.montant_facture_1_h,0)) AS montant_facture_1_h,
					SUM(COALESCE(p_factures.montant_regle_1_c,0)) AS montant_regle_1_c,
					SUM(COALESCE(p_factures.montant_regle_1_h,0)) AS montant_regle_1_h,
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_1_c <> 0 OR p_factures.montant_facture_1_h <> 0)  THEN p_factures.date_expedition_1 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_1,
					MAX(COALESCE(CASE WHEN p_factures.date_solde_1_c < '2099-12-31' AND p_factures.date_solde_1_c > p_factures.date_solde_1_h THEN p_factures.date_solde_1_c ELSE p_factures.date_solde_1_h END,'20991231' )) AS date_solde_1,

					SUM(COALESCE(p_factures.montant_facture_2_c,0)) AS montant_facture_2_c,
					SUM(COALESCE(p_factures.montant_facture_2_h,0)) AS montant_facture_2_h,
					SUM(COALESCE(p_factures.montant_regle_2_c,0)) AS montant_regle_2_c,
					SUM(COALESCE(p_factures.montant_regle_2_h,0)) AS montant_regle_2_h,
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_2_c <> 0 OR p_factures.montant_facture_2_h <> 0)  THEN p_factures.date_expedition_2 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_2,
					MAX(COALESCE(CASE WHEN p_factures.date_solde_2_c < '2099-12-31' AND p_factures.date_solde_2_c > p_factures.date_solde_2_h THEN p_factures.date_solde_2_c ELSE p_factures.date_solde_2_h END,'20991231' )) AS date_solde_2,

					SUM(COALESCE(p_factures.montant_facture_22_c,0)) AS montant_facture_22_c,
					SUM(COALESCE(p_factures.montant_facture_22_h,0)) AS montant_facture_22_h,
					SUM(COALESCE(p_factures.montant_regle_22_c,0)) AS montant_regle_22_c,
					SUM(COALESCE(p_factures.montant_regle_22_h,0)) AS montant_regle_22_h,
					MAX(COALESCE(CASE WHEN (p_factures.montant_facture_22_c <> 0 OR p_factures.montant_facture_22_h <> 0)  THEN p_factures.date_expedition_22 ELSE '0001-01-01' END,'20991231' )) AS date_expedition_22,
					MAX(COALESCE(CASE WHEN p_factures.date_solde_22_c < '2099-12-31' AND p_factures.date_solde_22_c > p_factures.date_solde_22_h THEN p_factures.date_solde_22_c ELSE p_factures.date_solde_22_h END,'20991231' )) AS date_solde_22 ,


					SUM(COALESCE(p_factures.montant_comptabilise_c,0)) AS montant_comptabilise_c,
					SUM(COALESCE(p_factures.montant_comptabilise_h,0)) AS montant_comptabilise_h,
					SUM(COALESCE(p_factures.montant_comptabilise_0_c,0)) AS montant_comptabilise_0_c,
					SUM(COALESCE(p_factures.montant_comptabilise_0_h,0)) AS montant_comptabilise_0_h,
					SUM(COALESCE(p_factures.montant_comptabilise_1_c,0)) AS montant_comptabilise_1_c,
					SUM(COALESCE(p_factures.montant_comptabilise_1_h,0)) AS montant_comptabilise_1_h,
					SUM(COALESCE(p_factures.montant_comptabilise_2_c,0)) AS montant_comptabilise_2_c,
					SUM(COALESCE(p_factures.montant_comptabilise_2_h,0)) AS montant_comptabilise_2_h,
					SUM(COALESCE(p_factures.montant_comptabilise_22_c,0)) AS montant_comptabilise_22_c,
					SUM(COALESCE(p_factures.montant_comptabilise_22_h,0)) AS montant_comptabilise_22_h,

					SUM(COALESCE(p_factures.montant_comptabilise_budget_global_c,0)) AS montant_comptabilise_budget_global_c,

					SUM(COALESCE(p_factures.montant_facture_c_actes_inclus_dans_sejour,0)) AS montant_facture_c_actes_inclus_dans_sejour,
					SUM(COALESCE(p_factures.montant_facture_h_actes_inclus_dans_sejour,0)) AS montant_facture_h_actes_inclus_dans_sejour,

					0::numeric AS delai_groupage,
					0::numeric AS delai_facture,
					0::numeric AS delai_expedition,
					0::numeric AS delai_solde,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_solde_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_solde_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_solde_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_22

				FROM activite[PX].p_sejours LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture <> 'P'
				GROUP BY 
					p_sejours.no_sejour,
					p_sejours.code_sorti,
					p_sejours.date_sortie,
					p_sejours.date_groupage,
					p_sejours.ghs_id
				;


				UPDATE activite[PX].p_sejours
				SET date_groupage = date_facture
				WHERE (date_groupage IS null OR date_groupage = '20991231' OR date_groupage = '00010101') AND
					date_facture <> '2099-12-31';


				UPDATE w_sejours_total SET
					date_groupage = CASE WHEN date_groupage > '00010101' THEN date_groupage ELSE '20991231' END,
					date_facture = CASE WHEN date_facture> '00010101' THEN date_facture ELSE '20991231' END,
					date_expedition = CASE WHEN date_expedition > '00010101' THEN date_expedition ELSE '20991231' END,
					date_solde = CASE WHEN date_solde > '00010101' THEN date_solde ELSE '20991231' END,
					date_expedition_0 = CASE WHEN date_expedition_0 > '00010101' THEN date_expedition_0 ELSE '20991231' END,
					date_solde_0 = CASE WHEN date_solde_0 > '00010101' THEN date_solde_0 ELSE '20991231' END,
					date_expedition_1 = CASE WHEN date_expedition_1 > '00010101' THEN date_expedition_1 ELSE '20991231' END,
					date_solde_1 = CASE WHEN date_solde_1 > '00010101' THEN date_solde_1 ELSE '20991231' END,
					date_expedition_2 = CASE WHEN date_expedition_2 > '00010101' THEN date_expedition_2 ELSE '20991231' END,
					date_solde_2 = CASE WHEN date_solde_2 > '00010101' THEN date_solde_2 ELSE '20991231' END,
					date_expedition_22 = CASE WHEN date_expedition_22 > '00010101' THEN date_expedition_22 ELSE '20991231' END,
					date_solde_22 = CASE WHEN date_solde_22 > '00010101' THEN date_solde_22 ELSE '20991231' END;


				UPDATE w_sejours_total SET
					delai_groupage = CASE WHEN code_sorti = '1' AND date_groupage > date_sortie AND date_groupage < '2099-12-31' AND ghs_id <> 0
								THEN date_groupage  - date_sortie ELSE 0 END,
					delai_facture = CASE WHEN code_sorti = '1' AND date_facture  > date_sortie AND date_facture < '2099-12-31' AND date_facture > date_sortie
								THEN date_facture  - date_sortie ELSE 0 END,
					delai_expedition = CASE WHEN code_sorti = '1' AND date_expedition  > date_sortie AND date_facture < '2099-12-31' AND date_expedition < '2099-12-31'
								THEN date_expedition  - date_sortie ELSE 0 END,
					delai_solde = CASE WHEN code_sorti = '1' AND date_solde > date_sortie AND date_facture < '2099-12-31' AND date_solde < '2099-12-31'
								THEN date_solde - date_sortie ELSE 0 END,
					delai_expedition_0 = CASE WHEN code_sorti = '1' AND date_expedition_0 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_0 < '2099-12-31'
								THEN date_expedition_0  - date_sortie ELSE 0 END,
					delai_solde_0 = CASE WHEN code_sorti = '1'AND date_solde_0 > date_sortie AND date_facture < '2099-12-31' AND date_solde_0 < '2099-12-31'
								THEN date_solde_0 - date_sortie ELSE 0 END,
					delai_expedition_1 = CASE WHEN code_sorti = '1' AND date_expedition_1 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_1 < '2099-12-31'
								THEN date_expedition_1  - date_sortie ELSE 0 END,
					delai_solde_1 = CASE WHEN code_sorti = '1' AND date_solde_1 > date_sortie AND date_facture < '2099-12-31' AND date_solde_1 < '2099-12-31'
								THEN date_solde_1 - date_sortie ELSE 0 END,
					delai_expedition_2 = CASE WHEN code_sorti = '1' AND date_expedition_2 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_2 < '2099-12-31'
								THEN date_expedition_2  - date_sortie ELSE 0 END,
					delai_solde_2 = CASE WHEN code_sorti = '1' AND date_solde_2 > date_sortie AND date_facture < '2099-12-31' AND date_solde_2 < '2099-12-31'
								THEN date_solde_2 - date_sortie ELSE 0 END,
					delai_expedition_22 = CASE WHEN code_sorti = '1' AND date_expedition_22 > date_sortie AND date_facture < '2099-12-31' AND date_expedition_22 < '2099-12-31'
								THEN date_expedition_22  - date_sortie ELSE 0 END,
					delai_solde_22 = CASE WHEN code_sorti = '1' AND date_solde_22 > date_sortie AND date_facture < '2099-12-31' AND date_solde_22 < '2099-12-31'
								THEN date_solde_22 - date_sortie ELSE 0 END;

				ALTER TABLE w_sejours_total  ADD CONSTRAINT w_sejours_total_pkey PRIMARY KEY(no_sejour);



				UPDATE activite[PX].p_sejours SET

					date_facture = w_sejours_total.date_facture,
					date_expedition = w_sejours_total.date_expedition,
					date_solde = w_sejours_total.date_solde,
					montant_facture_c = w_sejours_total.montant_facture_c,
					montant_facture_h = w_sejours_total.montant_facture_h,
					montant_regle_c = w_sejours_total.montant_regle_c,
					montant_regle_h = w_sejours_total.montant_regle_h,
					nb_factures = w_sejours_total.nb_factures,
					nb_factures_regularisation = w_sejours_total.nb_factures_regularisation,
					nb_factures_rejet = w_sejours_total.nb_rejets,

					montant_facture_0_c = w_sejours_total.montant_facture_0_c,
					montant_facture_0_h = w_sejours_total.montant_facture_0_h,
					montant_regle_0_c = w_sejours_total.montant_regle_0_c,
					montant_regle_0_h = w_sejours_total.montant_regle_0_h,
					date_expedition_0 = w_sejours_total.date_expedition_0,
					date_solde_0 = w_sejours_total.date_solde_0,

					montant_facture_1_c = w_sejours_total.montant_facture_1_c,
					montant_facture_1_h = w_sejours_total.montant_facture_1_h,
					montant_regle_1_c = w_sejours_total.montant_regle_1_c,
					montant_regle_1_h = w_sejours_total.montant_regle_1_h,
					date_expedition_1 = w_sejours_total.date_expedition_1,
					date_solde_1 = w_sejours_total.date_solde_1,

					montant_facture_2_c = w_sejours_total.montant_facture_2_c,
					montant_facture_2_h = w_sejours_total.montant_facture_2_h,
					montant_regle_2_c = w_sejours_total.montant_regle_2_c,
					montant_regle_2_h = w_sejours_total.montant_regle_2_h,
					date_expedition_2 = w_sejours_total.date_expedition_2,
					date_solde_2 = w_sejours_total.date_solde_2,

					montant_facture_22_c = w_sejours_total.montant_facture_22_c,
					montant_facture_22_h = w_sejours_total.montant_facture_22_h,
					montant_regle_22_c = w_sejours_total.montant_regle_22_c,
					montant_regle_22_h = w_sejours_total.montant_regle_22_h,
					date_expedition_22 = w_sejours_total.date_expedition_22,
					date_solde_22 = w_sejours_total.date_solde_22,

					montant_comptabilise_c = w_sejours_total.montant_comptabilise_c,
					montant_comptabilise_h = w_sejours_total.montant_comptabilise_h,
					montant_comptabilise_0_c = w_sejours_total.montant_comptabilise_0_c,
					montant_comptabilise_0_h = w_sejours_total.montant_comptabilise_0_h,
					montant_comptabilise_1_c = w_sejours_total.montant_comptabilise_1_c,
					montant_comptabilise_1_h = w_sejours_total.montant_comptabilise_1_h,
					montant_comptabilise_2_c = w_sejours_total.montant_comptabilise_2_c,
					montant_comptabilise_2_h = w_sejours_total.montant_comptabilise_2_h,
					montant_comptabilise_22_c = w_sejours_total.montant_comptabilise_22_c,
					montant_comptabilise_22_h = w_sejours_total.montant_comptabilise_22_h,

					montant_comptabilise_budget_global_c = w_sejours_total.montant_comptabilise_budget_global_c,

					montant_facture_c_actes_inclus_dans_sejour = w_sejours_total.montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour = w_sejours_total.montant_facture_h_actes_inclus_dans_sejour,


					delai_groupage = w_sejours_total.delai_groupage,
					delai_facture = w_sejours_total.delai_facture,
					delai_expedition = w_sejours_total.delai_expedition,
					delai_solde = w_sejours_total.delai_solde,
					delai_expedition_0 = w_sejours_total.delai_expedition_0,
					delai_solde_0 = w_sejours_total.delai_solde_0,
					delai_expedition_1 = w_sejours_total.delai_expedition_1,
					delai_solde_1 = w_sejours_total.delai_solde_1,
					delai_expedition_2 = w_sejours_total.delai_expedition_2,
					delai_solde_2 = w_sejours_total.delai_solde_2,
					delai_expedition_22 = w_sejours_total.delai_expedition_22,
					delai_solde_22 = w_sejours_total.delai_solde_22

				FROM w_sejours_total
				WHERE w_sejours_total.no_sejour =  p_sejours.no_sejour

				AND (
					p_sejours.date_facture IS DISTINCT FROM w_sejours_total.date_facture OR
					p_sejours.date_expedition IS DISTINCT FROM w_sejours_total.date_expedition OR
					p_sejours.date_solde IS DISTINCT FROM w_sejours_total.date_solde OR
					p_sejours.montant_facture_c IS DISTINCT FROM w_sejours_total.montant_facture_c OR
					p_sejours.montant_facture_h IS DISTINCT FROM w_sejours_total.montant_facture_h OR
					p_sejours.montant_regle_c IS DISTINCT FROM w_sejours_total.montant_regle_c OR
					p_sejours.montant_regle_h IS DISTINCT FROM w_sejours_total.montant_regle_h OR
					p_sejours.nb_factures IS DISTINCT FROM w_sejours_total.nb_factures OR
					p_sejours.nb_factures_regularisation IS DISTINCT FROM w_sejours_total.nb_factures_regularisation OR
					p_sejours.nb_factures_rejet IS DISTINCT FROM w_sejours_total.nb_rejets OR

					p_sejours.montant_facture_0_c IS DISTINCT FROM w_sejours_total.montant_facture_0_c OR
					p_sejours.montant_facture_0_h IS DISTINCT FROM w_sejours_total.montant_facture_0_h OR
					p_sejours.montant_regle_0_c IS DISTINCT FROM w_sejours_total.montant_regle_0_c OR
					p_sejours.montant_regle_0_h IS DISTINCT FROM w_sejours_total.montant_regle_0_h OR
					p_sejours.date_expedition_0 IS DISTINCT FROM w_sejours_total.date_expedition_0 OR
					p_sejours.date_solde_0 IS DISTINCT FROM w_sejours_total.date_solde_0 OR

					p_sejours.montant_facture_1_c IS DISTINCT FROM w_sejours_total.montant_facture_1_c OR
					p_sejours.montant_facture_1_h IS DISTINCT FROM w_sejours_total.montant_facture_1_h OR
					p_sejours.montant_regle_1_c IS DISTINCT FROM w_sejours_total.montant_regle_1_c OR
					p_sejours.montant_regle_1_h IS DISTINCT FROM w_sejours_total.montant_regle_1_h OR
					p_sejours.date_expedition_1 IS DISTINCT FROM w_sejours_total.date_expedition_1 OR
					p_sejours.date_solde_1 IS DISTINCT FROM w_sejours_total.date_solde_1 OR

					p_sejours.montant_facture_2_c IS DISTINCT FROM w_sejours_total.montant_facture_2_c OR
					p_sejours.montant_facture_2_h IS DISTINCT FROM w_sejours_total.montant_facture_2_h OR
					p_sejours.montant_regle_2_c IS DISTINCT FROM w_sejours_total.montant_regle_2_c OR
					p_sejours.montant_regle_2_h IS DISTINCT FROM w_sejours_total.montant_regle_2_h OR
					p_sejours.date_expedition_2 IS DISTINCT FROM w_sejours_total.date_expedition_2 OR
					p_sejours.date_solde_2 IS DISTINCT FROM w_sejours_total.date_solde_2 OR

					p_sejours.montant_facture_22_c IS DISTINCT FROM w_sejours_total.montant_facture_22_c OR
					p_sejours.montant_facture_22_h IS DISTINCT FROM w_sejours_total.montant_facture_22_h OR
					p_sejours.montant_regle_22_c IS DISTINCT FROM w_sejours_total.montant_regle_22_c OR
					p_sejours.montant_regle_22_h IS DISTINCT FROM w_sejours_total.montant_regle_22_h OR
					p_sejours.date_expedition_22 IS DISTINCT FROM w_sejours_total.date_expedition_22 OR
					p_sejours.date_solde_22 IS DISTINCT FROM w_sejours_total.date_solde_22 OR

					p_sejours.montant_comptabilise_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_c OR
					p_sejours.montant_comptabilise_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_h OR
					p_sejours.montant_comptabilise_0_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_c OR
					p_sejours.montant_comptabilise_0_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_h OR
					p_sejours.montant_comptabilise_1_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_c OR
					p_sejours.montant_comptabilise_1_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_h OR
					p_sejours.montant_comptabilise_2_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_c OR
					p_sejours.montant_comptabilise_2_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_h OR
					p_sejours.montant_comptabilise_22_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_c OR
					p_sejours.montant_comptabilise_22_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_h OR

					p_sejours.montant_comptabilise_budget_global_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_budget_global_c OR

					p_sejours.montant_facture_c_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_c_actes_inclus_dans_sejour OR
					p_sejours.montant_facture_h_actes_inclus_dans_sejour IS DISTINCT FROM w_sejours_total.montant_facture_h_actes_inclus_dans_sejour OR

					p_sejours.delai_groupage IS DISTINCT FROM w_sejours_total.delai_groupage OR
					p_sejours.delai_facture IS DISTINCT FROM w_sejours_total.delai_facture OR
					p_sejours.delai_expedition IS DISTINCT FROM w_sejours_total.delai_expedition OR
					p_sejours.delai_solde IS DISTINCT FROM w_sejours_total.delai_solde OR
					p_sejours.delai_expedition_0 IS DISTINCT FROM w_sejours_total.delai_expedition_0 OR
					p_sejours.delai_solde_0 IS DISTINCT FROM w_sejours_total.delai_solde_0 OR
					p_sejours.delai_expedition_1 IS DISTINCT FROM w_sejours_total.delai_expedition_1 OR
					p_sejours.delai_solde_1 IS DISTINCT FROM w_sejours_total.delai_solde_1 OR
					p_sejours.delai_expedition_2 IS DISTINCT FROM w_sejours_total.delai_expedition_2 OR
					p_sejours.delai_solde_2 IS DISTINCT FROM w_sejours_total.delai_solde_2 OR
					p_sejours.delai_expedition_22 IS DISTINCT FROM w_sejours_total.delai_expedition_22 OR
					p_sejours.delai_solde_22 IS DISTINCT FROM w_sejours_total.delai_solde_22

				);

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_sejours_total CASCADE;


			]]></sqlcmd>
	</NODE>


	<NODE label="Tables répliquées">

		<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

		<sqlcmd><![CDATA[



			]]></sqlcmd>
	</NODE>
</NODE>

<NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">

	<NODE label="Encours HM">
		<condition><![CDATA[
				SELECT 
					count(*) = 1
				FROM activite.t_divers
				WHERE code = 'ENCOURSHM' 
					AND valeur = 1
				;
				]]></condition>
		<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_FACT_DAT_DER_CALCUL;
				CREATE TEMP TABLE w_FACT_DAT_DER_CALCUL AS
				SELECT
					date(date_trunc('month', fact_dat_fac) + interval '1 month' - interval '1 day') AS date_encours,
					MAX(date(FACT_DAT_DER_CALCUL)) AS FACT_DAT_DER_CALCUL
				FROM prod_hm.FAC_FACTURE
				WHERE FACT_TYPE = 'E' AND
					FACT_DAT_FAC >= '[ENV_ADM_ANNEEDEBUT]1201' AND
					FACT_DAT_SUP IS NULL
				GROUP BY 1
				ORDER BY 1;

				CREATE INDEX w_FACT_DAT_DER_CALCUL_i1 ON w_FACT_DAT_DER_CALCUL USING btree (date_encours);

				-- encours sur medecins salaries
				DROP TABLE IF EXISTS w_factures_encours_salaries;
				CREATE TEMP TABLE w_factures_encours_salaries AS
				SELECT
					LFAC_ID_FACT,
					SUM(LFAD_MTT_HOR_DEH + LFAD_MTT_DEH) AS montant_encours_salaries,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_salaries_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_salaries_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_salaries_2,
					0::numeric AS montant_encours_22
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAD_ID_LFAC = LFAC_ID_LFAC
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
				WHERE LFAC_ID_PRHO <> 0 AND LFAC_CDT_EXC = 'S'
				GROUP BY 1
				ORDER BY 1;

				CREATE INDEX w_factures_encours_salaries_i1 ON w_factures_encours_salaries USING btree (LFAC_ID_FACT);


				-- entetes factures encours

				DROP TABLE IF EXISTS w_factures_references;
				CREATE TEMP TABLE w_factures_references AS
				SELECT
					no_sejour,
					date_fin,
					MIN(date_debut) AS date_debut,
					MAX(no_facture) AS no_facture
				FROM activite[PX].p_factures
				WHERE no_facture_reference = no_facture AND code_facture >= '1'
				GROUP BY 1,2;

				CREATE INDEX w_factures_references_i1 ON w_factures_references USING btree (no_sejour);


				DROP TABLE IF EXISTS w_factures_encours;
				CREATE TEMP TABLE w_factures_encours AS
				SELECT
						0::bigint AS oid,
						FACT_ID_FACT,
						p_sejours.finess,
						p_sejours.no_sejour,
						p_sejours.date_entree,
						p_sejours.date_sortie,
						p_sejours.oid AS sejour_id,
						p_sejours.lieu_sortie_id,
						COALESCE(w_factures_references.no_facture,'ID' || FACT_ID_FACT)  || '.EP' || substr(to_char(date_part('year', w_FACT_DAT_DER_CALCUL.date_encours),'FM0000'),3,2) || to_char(date_part('month', w_FACT_DAT_DER_CALCUL.date_encours),'FM00') AS no_facture,
						w_factures_references.no_facture AS no_facture_reference,
						date(FACT_DAT_DEB_FAC) AS date_debut,
						date(FACT_DAT_FIN_FAC) AS date_fin,
						w_FACT_DAT_DER_CALCUL.date_encours,
						'P'::text AS code_origine,
						CASE WHEN date(FACT_DAT_FIN_FAC) > date_encours OR SEJO_STATUT NOT IN ('S', 'M') OR date(SEJO_DAT_FIN) > date_encours THEN '0' ELSE '1' END AS code_sorti,
						p_sejours.tiers_payant_1_id,
						p_sejours.tiers_payant_2_id,
						p_sejours.tiers_payant_22_id,
						p_sejours.tiers_payant_0_id,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id,
						p_sejours.code_cp_demandee,
						FACT_MTT_CAI_SEJ + FACT_MTT_MUT_SEJ + FACT_MTT_PAT_SEJ + COALESCE(montant_encours_salaries,0) AS montant_encours_c,
						FACT_MTT_PAT_SEJ + COALESCE(montant_encours_salaries_0,0)  AS montant_encours_0_c,
						FACT_MTT_CAI_SEJ + COALESCE(montant_encours_salaries_1,0)  AS montant_encours_1_c,
						FACT_MTT_MUT_SEJ + COALESCE(montant_encours_salaries_2,0)  AS montant_encours_2_c,
						0::numeric AS montant_encours_22_c,
						0::numeric AS montant_encours_h,
						0::numeric AS montant_encours_0_h,
						0::numeric AS montant_encours_1_h,
						0::numeric AS montant_encours_2_h,
						0::numeric AS montant_encours_22_h,
						p_sejours.type_sejour
				FROM prod_hm.FAC_FACTURE
					JOIN w_FACT_DAT_DER_CALCUL ON date(FAC_FACTURE.FACT_DAT_DER_CALCUL) = w_FACT_DAT_DER_CALCUL.FACT_DAT_DER_CALCUL AND
						date(date_trunc('month', fact_dat_fac) + interval '1 month' - interval '1 day') = date_encours
					JOIN prod_hm.IDE_SEJOUR ON FACT_ID_SEJO = SEJO_ID_SEJO
					JOIN activite[PX].p_sejours ON code_original = FACT_ID_SEJO
					LEFT JOIN w_factures_references ON p_sejours.no_sejour = w_factures_references.no_sejour AND
						date(FACT_DAT_FIN_FAC) BETWEEN w_factures_references.date_debut AND w_factures_references.date_fin
					LEFT JOIN w_factures_encours_salaries ON w_factures_encours_salaries.LFAC_ID_FACT = FACT_ID_FACT
				WHERE FACT_TYPE = 'E' AND
					FACT_ID_ECRI_ENC <> 0
				;

				CREATE INDEX w_factures_encours_i1 ON w_factures_encours USING btree (FACT_ID_FACT);


				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_11');

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_8');

				DELETE FROM activite[PX].p_factures_encours WHERE code_origine = 'P';
				DELETE FROM activite[PX].p_factures_encours_lignes_c
					WHERE NOT EXISTS (
						SELECT no_facture FROM activite[PX].p_factures_encours
						WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture
					)
				;

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_encours_lignes_c_1');

				INSERT INTO activite[PX].p_factures_encours(
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					date_debut,
					date_fin,
					date_encours,
					code_origine,
					code_sorti,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					tiers_payant_0_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					montant_encours_c,
					montant_encours_0_c,
					montant_encours_1_c,
					montant_encours_2_c,
					montant_encours_22_c,
					montant_encours_h,
					montant_encours_0_h,
					montant_encours_1_h,
					montant_encours_2_h,
					montant_encours_22_h,
					type_sejour
					)
				SELECT
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					date_debut,
					date_fin,
					date_encours,
					code_origine,
					code_sorti,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					tiers_payant_0_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					montant_encours_c,
					montant_encours_0_c,
					montant_encours_1_c,
					montant_encours_2_c,
					montant_encours_22_c,
					montant_encours_h,
					montant_encours_0_h,
					montant_encours_1_h,
					montant_encours_2_h,
					montant_encours_22_h,
					type_sejour
				FROM w_factures_encours;

				UPDATE w_factures_encours SET oid = p_factures_encours.oid
				FROM activite[PX].p_factures_encours
				WHERE w_factures_encours.no_facture = p_factures_encours.no_facture;

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_1');

				DROP SEQUENCE IF EXISTS w_factures_encours_lignes_c_sequence;
				CREATE TEMP SEQUENCE w_factures_encours_lignes_c_sequence;

				DROP TABLE IF EXISTS w_factures_encours_lignes_c;
				CREATE TEMP TABLE w_factures_encours_lignes_c AS
				SELECT
					nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
					no_sejour,
					LFAC_ID_LFAC,
					w_factures_encours.oid AS facture_id,
					w_factures_encours.no_facture,
					w_factures_encours.date_entree,
					w_factures_encours.date_sortie,
					date(LFAC_DAT_EXE_DEB) AS date_debut,
					date(LFAC_DAT_EXE_FIN) AS date_fin,
					LFAC_QTE_COEFFICIENT AS nb_rubrique,
					1::numeric AS coefficient,
					LFAC_COE_MCO_HAD AS coefficient_mco,
					COALESCE(t_rubriques_facturation_PRSE.oid,t_rubriques_facturation_PRHO.oid, 0) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation_PRSE.oid,t_rubriques_facturation_PRHO.oid, 0) AS rubrique_comptabilisation_id,
					MAX(COALESCE(t_compte.oid::bigint, 0)) AS compte_produit_id,
					COALESCE(t_prestations.oid::bigint, 0) AS prestation_id,

					0::numeric AS taux_22,
					LFAC_PRI_UNITAIRE AS prix_unitaire,
					w_factures_encours.lieu_sortie_id AS lieu_id,
					LFAC_QTE_COEFFICIENT AS nb_prestation,

					MAX(LFAC_ID_PRSE) AS LFAC_ID_PRSE,
					MAX(LFAC_ID_PRHO) AS LFAC_ID_PRHO,

					MAX(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN 100-LFAD_TAUX ELSE 0 END) AS taux_0,
					MAX(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_TAUX ELSE 0 END) AS taux_1,
					MAX(CASE WHEN FACD_ID_ORGA_AMC > 0 THEN 100-LFAD_TAUX ELSE 0 END) AS taux_2,
					SUM(LFAD_MTT_HOR_DEH + LFAD_MTT_DEH) AS montant_encours,
					SUM(CASE WHEN FACD_ID_ORGA_AMO = 0 AND FACD_ID_ORGA_AMC = 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_0,
					SUM(CASE WHEN FACD_ID_ORGA_AMO > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_1,
					SUM(CASE WHEN FACD_ID_ORGA_AMC > 0 THEN LFAD_MTT_HOR_DEH + LFAD_MTT_DEH ELSE 0 END) AS montant_encours_2,
					0::numeric AS montant_encours_22
				FROM prod_hm.FAC_LIGNE_FACTURE
					JOIN w_factures_encours ON FACT_ID_FACT = LFAC_ID_FACT
					JOIN prod_hm.FAC_LIGNE_FACTURE_DEBITEUR ON LFAD_ID_LFAC = LFAC_ID_LFAC
					JOIN prod_hm.FAC_FACTURE_DEBITEUR ON LFAD_ID_FACD = FACD_ID_FACD
					LEFT JOIN activite[PX].t_rubriques_facturation t_rubriques_facturation_PRSE ON LFAC_ID_PRSE::bigint = t_rubriques_facturation_PRSE.code_original AND LFAC_ID_PRSE <> 0
					LEFT JOIN activite[PX].t_rubriques_facturation t_rubriques_facturation_PRHO ON LFAC_ID_PRHO::bigint = t_rubriques_facturation_PRHO.code_original AND LFAC_ID_PRHO <> 0
					LEFT JOIN activite.t_prestations ON LFAC_LET_CLE = t_prestations.code
					LEFT JOIN w_FAC_LIGNE_FACTURE_DEBITEUR_compte ON LECR_ID_LFAD = LFAD_ID_LFAD
					LEFT JOIN activite[PX].t_compte ON (LECR_NUM_COMPTE = t_compte.code_original)
				WHERE (LFAC_ID_PRSE <> 0 OR (LFAC_ID_PRHO <> 0 AND LFAC_CDT_EXC = 'S')) AND
					LFAD_IND_BGH <> '1' AND
					(LFAD_MTT_HOR_DEH + LFAD_MTT_DEH) <> 0
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,17,18,19,20
				ORDER BY 1;

				-- Compte par défaut si pas trouvé en compta
				DROP TABLE IF EXISTS w_PAD_PRESTATION_SEJOUR;
				CREATE TEMP TABLE w_PAD_PRESTATION_SEJOUR AS
				SELECT *,
					''::text AS CPTE_NUM_COMPTE_defaut,
					0::bigint AS compte_id
				FROM prod_hm.PAD_PRESTATION_SEJOUR
				;

				UPDATE w_PAD_PRESTATION_SEJOUR
				SET CPTE_NUM_COMPTE_defaut = CPTE_NUM_COMPTE
				FROM (SELECT
					CPTP_ID_PRSE, (MAX(ARRAY[CPTP_DAT_CRE::text,CPTE_NUM_COMPTE]))[2] AS CPTE_NUM_COMPTE
					FROM prod_hm.CCL_COMPTE_PRESTATION
					JOIN prod_hm.CCL_COMPTE ON CPTP_ID_CPTE = CPTE_ID_CPTE
					WHERE CPTP_ID_PRSE <> 0
					GROUP BY 1
					) subview
				WHERE PRSE_ID_PRSE = CPTP_ID_PRSE
				;

				UPDATE w_PAD_PRESTATION_SEJOUR
				SET CPTE_NUM_COMPTE_defaut = CPTE_NUM_COMPTE
				FROM (SELECT
					CPTP_ID_CAPR, (MAX(ARRAY[CPTP_DAT_CRE::text,CPTE_NUM_COMPTE]))[2] AS CPTE_NUM_COMPTE
					FROM prod_hm.CCL_COMPTE_PRESTATION
					JOIN prod_hm.CCL_COMPTE ON CPTP_ID_CPTE = CPTE_ID_CPTE
					WHERE CPTP_ID_CAPR <> 0
					GROUP BY 1
					) subview
				WHERE CPTE_NUM_COMPTE_defaut = '' AND
					PRSE_ID_CAPR = CPTP_ID_CAPR
				;

				UPDATE w_PAD_PRESTATION_SEJOUR
				SET compte_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE CPTE_NUM_COMPTE_defaut = code_original
				;

				DROP TABLE IF EXISTS w_PAD_PRESTATION_HONORAIRE;
				CREATE TEMP TABLE w_PAD_PRESTATION_HONORAIRE AS
				SELECT *,
					''::text AS CPTE_NUM_COMPTE_defaut,
					0::bigint AS compte_id
				FROM prod_hm.PAD_PRESTATION_HONORAIRE
				;

				UPDATE w_PAD_PRESTATION_HONORAIRE
				SET CPTE_NUM_COMPTE_defaut = CPTE_NUM_COMPTE
				FROM (SELECT
					CPTP_ID_PRHO, (MAX(ARRAY[CPTP_DAT_CRE::text,CPTE_NUM_COMPTE]))[2] AS CPTE_NUM_COMPTE
					FROM prod_hm.CCL_COMPTE_PRESTATION
					JOIN prod_hm.CCL_COMPTE ON CPTP_ID_CPTE = CPTE_ID_CPTE
					WHERE CPTP_ID_PRHO <> 0
					GROUP BY 1
					) subview
				WHERE PRHO_ID_PRHO = CPTP_ID_PRHO
				;

				UPDATE w_PAD_PRESTATION_HONORAIRE
				SET CPTE_NUM_COMPTE_defaut = CPTE_NUM_COMPTE
				FROM (SELECT
					CPTP_ID_CAPR, (MAX(ARRAY[CPTP_DAT_CRE::text,CPTE_NUM_COMPTE]))[2] AS CPTE_NUM_COMPTE
					FROM prod_hm.CCL_COMPTE_PRESTATION
					JOIN prod_hm.CCL_COMPTE ON CPTP_ID_CPTE = CPTE_ID_CPTE
					WHERE CPTP_ID_CAPR <> 0
					GROUP BY 1
					) subview
				WHERE CPTE_NUM_COMPTE_defaut = '' AND
					PRHO_ID_CAPR = CPTP_ID_CAPR
				;

				UPDATE w_PAD_PRESTATION_honoraire
				SET compte_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE CPTE_NUM_COMPTE_defaut = code_original
				;

				UPDATE w_factures_encours_lignes_c
				SET compte_produit_id = compte_id
				FROM w_PAD_PRESTATION_SEJOUR
				WHERE LFAC_ID_PRSE <> 0 AND
					compte_produit_id = 0 AND
					LFAC_ID_PRSE = PRSE_ID_PRSE
				;
				UPDATE w_factures_encours_lignes_c
				SET compte_produit_id = compte_id
				FROM w_PAD_PRESTATION_HONORAIRE
				WHERE LFAC_ID_PRHO <> 0 AND
					compte_produit_id = 0 AND
					LFAC_ID_PRHO = PRHO_ID_PRHO
				;




				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c;
				CREATE TEMP TABLE w_factures_encours_lignes_sup_c AS
				SELECT
					w_factures_encours_lignes_c.oid AS from_oid,
					t_prestations.code AS prestation_code,
					date(date_debut) AS date_debut_ghs,
					date(date_fin - interval '1 day') AS date_fin_ghs,
					(date(date_fin) - date(date_debut)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_entree + interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie - interval '1 day') ELSE date(w_factures_encours_lignes_c.date_debut + ((ABS(nb_prestation)-1) || ' day')::interval)  END AS date_fin_det,
					ABS(CASE WHEN t_prestations.code = 'GHS' THEN date(w_factures_encours_lignes_c.date_sortie) - date(w_factures_encours_lignes_c.date_entree) ELSE nb_prestation END) AS nb_det,
					w_factures_encours_lignes_c.*
				FROM w_factures_encours_lignes_c
					JOIN activite[PX].p_sejours ON w_factures_encours_lignes_c.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND
						(
						code IN ('PJ', 'PJ1', 'PJ2', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						t_prestations.type_ventilation_jour = '1'
						)
				WHERE (nb_prestation > 1 or nb_prestation < -1 OR (t_prestations.code = 'GHS' AND date(date_fin) - date(date_debut) > 1)) ;


				UPDATE w_factures_encours_lignes_sup_c SET
					date_fin_ghs = date(date_debut_exh - interval '1 day'),
					date_fin_det = date(date_debut_exh - interval '1 day'),
					nb_prestation_ghs = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1,
					nb_det = date(date_debut_exh - interval '1 day') - date_debut_ghs + 1
				FROM (
					SELECT no_facture, date(MIN(date_debut)) AS date_debut_exh
					FROM w_factures_encours_lignes_c
						JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND code = 'EXH'
					GROUP BY 1) subview
				WHERE w_factures_encours_lignes_sup_c.no_facture = subview.no_facture;

				CREATE INDEX w_factures_encours_lignes_sup_c_i1
				  ON w_factures_encours_lignes_sup_c
				  USING btree
				  (date_debut);

				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen;
				CREATE TEMP TABLE w_factures_encours_lignes_sup_c_gen AS
				SELECT
					from_oid,
					''::text AS finess,
					no_sejour,
					no_facture,
					facture_id,
					date AS date_debut,
					date AS date_fin,
					lieu_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					CASE WHEN prestation_code = 'GHS' AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					coefficient,
					coefficient_mco,
					prix_unitaire,
					oid,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					round(montant_encours / ABS(nb_det),2) AS montant_encours,
					round(montant_encours_0 / ABS(nb_det),2) AS montant_encours_0,
					round(montant_encours_1 / ABS(nb_det),2) AS montant_encours_1,
					round(montant_encours_2 / ABS(nb_det),2) AS montant_encours_2,
					round(montant_encours_22 / ABS(nb_det),2) AS montant_encours_22
				FROM w_factures_encours_lignes_sup_c
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date_debut_det AND date_fin_det ;


				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen_tot;
				CREATE TEMP TABLE w_factures_encours_lignes_sup_c_gen_tot AS
				SELECT from_oid,
					SUM(nb_rubrique) AS nb_rubrique,
					SUM(nb_prestation) AS nb_prestation,
					SUM(montant_encours) AS montant_encours,
					SUM(montant_encours_0) AS montant_encours_0,
					SUM(montant_encours_1) AS montant_encours_1,
					SUM(montant_encours_2) AS montant_encours_2,
					SUM(montant_encours_22) AS montant_encours_22
				FROM w_factures_encours_lignes_sup_c_gen
				GROUP BY 1;


				UPDATE w_factures_encours_lignes_c
				SET
					date_fin = w_factures_encours_lignes_c.date_debut,
					nb_rubrique = w_factures_encours_lignes_c.nb_rubrique - w_factures_encours_lignes_sup_c_gen_tot.nb_rubrique,
					nb_prestation = w_factures_encours_lignes_c.nb_prestation - w_factures_encours_lignes_sup_c_gen_tot.nb_prestation,
					montant_encours = w_factures_encours_lignes_c.montant_encours - w_factures_encours_lignes_sup_c_gen_tot.montant_encours,
					montant_encours_0 = w_factures_encours_lignes_c.montant_encours_0 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_0,
					montant_encours_1 = w_factures_encours_lignes_c.montant_encours_1 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_1,
					montant_encours_2 = w_factures_encours_lignes_c.montant_encours_2 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_2,
					montant_encours_22 = w_factures_encours_lignes_c.montant_encours_22 - w_factures_encours_lignes_sup_c_gen_tot.montant_encours_22
				FROM w_factures_encours_lignes_sup_c_gen_tot
				WHERE w_factures_encours_lignes_c.oid = from_oid;


				INSERT INTO w_factures_encours_lignes_c(
					oid,
					no_sejour,
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22)
				SELECT
					nextval('w_factures_encours_lignes_c_sequence'::regclass) AS oid,
					no_sejour,
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_encours_lignes_sup_c_gen;



				UPDATE w_factures_encours_lignes_c
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_mouvements_sejour
				WHERE w_factures_encours_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_encours_lignes_c.date_debut = p_mouvements_sejour.date AND
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					w_factures_encours_lignes_c.lieu_id IS DISTINCT FROM p_mouvements_sejour.lieu_id;



				INSERT INTO activite[PX].p_factures_encours_lignes_c(
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_encours_lignes_c;


				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours');
				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours_lignes_c');

				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_lignes_c_8');


				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_encours_11');

				-- Correction pour factures encours HM en double
				UPDATE activite[PX].p_factures_encours
				SET no_facture = p_factures_encours.no_facture ||'('||nb::text||')'
				FROM
				(
				SELECT no_facture, count(*) AS nb, MAX(oid) AS oid_dup
				FROM activite[PX].p_factures_encours
				WHERE p_factures_encours.code_origine = 'P'
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE p_factures_encours.no_facture = subview.no_facture AND
					p_factures_encours.oid = subview.oid_dup
					;

				UPDATE activite[PX].p_factures_encours_lignes_c
				SET facture_id = p_factures_encours.oid
				FROM activite[PX].p_factures_encours
				WHERE p_factures_encours.no_facture = p_factures_encours_lignes_c.no_facture AND
					p_factures_encours.code_origine = 'P' AND
					facture_id <> p_factures_encours.oid
				;

				-- Suppression des tables de travail non utilisées après
				DROP TABLE IF EXISTS w_factures_encours_salaries CASCADE;
				DROP TABLE IF EXISTS w_factures_references CASCADE;
				DROP TABLE IF EXISTS w_FAC_FACTURE_DAT_CRE CASCADE;
				DROP TABLE IF EXISTS w_factures_encours CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_c CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen CASCADE;
				DROP TABLE IF EXISTS w_factures_encours_lignes_sup_c_gen_tot CASCADE;

			]]></sqlcmd>
	</NODE>

</NODE>


</ROOT>
