<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	
	
	<NODE name="INIT" label="INITIALISATIONS">

		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_PERIODE;
				CREATE TEMP TABLE w_PERIODE AS 
				SELECT date(MAX(HO_DDEB)) AS now_cerner
				FROM prod_cerner.HOSPITALISATION;

				DROP TABLE IF EXISTS w_DEFAULT;
				CREATE TEMP TABLE w_DEFAULT AS 
				SELECT 
					(SELECT oid FROM activite[PX].t_tiers_payant WHERE code_original = '*PATIENT') AS tiers_payant_0_id,
					(SELECT oid FROM activite[PX].t_tiers_payant WHERE code_original = '*MUTDIV') AS tiers_payant_2_id
				;

				DROP TABLE IF EXISTS w_PASSAGE_ACTES;
				
				CREATE TEMP TABLE w_PASSAGE_ACTES AS
				SELECT NGAP_HONUM AS ACTE_HONUM, 
					NGAP_SEANCE AS ACTE_SEANCE, 
					SEA_ID AS ACTE_SEAID,
					date(NGAP_DATE) AS ACTE_DATE,
					date(NGAP_DATE) + (NGAP_HEURE - date(NGAP_HEURE)) AS ACTE_HEURE,
					NGAP_UFXCODE AS ACTE_UFXCODE
				FROM prod_cerner.PASSAGE_NGAP
				JOIN prod_cerner.HOSPITALISATION ON NGAP_HONUM = HO_NUM
				JOIN prod_cerner.REGROUPEMENT ON HO_RECODE = RE_CODE AND RE_TYPE NOT IN ('H')
				;

				INSERT INTO w_PASSAGE_ACTES
				SELECT CDAM_HONUM AS ACTE_HONUM, 
					CDAM_SEANCE AS ACTE_SEANCE, 
					CDAM_SEAID AS ACTE_SEAID,
					date(CDAM_DATE) AS ACTE_DATE,
					date(CDAM_DATE) + (CDAM_HEURE - date(CDAM_HEURE)) AS ACTE_HEURE,
					CDAM_UFXCODE AS ACTE_UFXCODE
				FROM prod_cerner.PASSAGE_CDAM
				JOIN prod_cerner.HOSPITALISATION ON CDAM_HONUM = HO_NUM
				JOIN prod_cerner.REGROUPEMENT ON HO_RECODE = RE_CODE AND RE_TYPE NOT IN ('H')
				;
				
				UPDATE w_PASSAGE_ACTES
				SET ACTE_UFXCODE = SEA_UFCODE
				FROM prod_cerner.PASSAGE
				WHERE ACTE_HONUM = SEA_HONUM AND SEA_ID = ACTE_SEAID AND
					SEA_UFCODE = 'CS21' AND ACTE_UFXCODE = 'UR21'
				;

				UPDATE w_PASSAGE_ACTES
				SET ACTE_UFXCODE = SEA_UFCODE
				FROM prod_cerner.PASSAGE
				WHERE ACTE_HONUM = SEA_HONUM AND SEA_ID = ACTE_SEAID AND
					SEA_UFCODE = 'UR21' AND ACTE_UFXCODE = 'CS21'
				;
					
				DROP TABLE IF EXISTS w_PASSAGE_ACTES_SEANCE;
				CREATE TEMP TABLE w_PASSAGE_ACTES_SEANCE AS
				SELECT ACTE_HONUM,
					ACTE_SEAID,
					(MAX(ARRAY[ACTE_HEURE::text,ACTE_UFXCODE]))[2] AS ACTE_UFXCODE,
					MIN(ACTE_HEURE) AS ACTE_HEURE_DEB,
					MAX(ACTE_HEURE)+ interval '59 seconds' AS ACTE_HEURE_FIN
				FROM w_PASSAGE_ACTES
				GROUP BY 1,2
				;

				CREATE INDEX w_PASSAGE_ACTES_SEANCE_i2
					ON w_PASSAGE_ACTES_SEANCE
					USING btree
					(ACTE_SEAID);
				

				DROP TABLE IF EXISTS w_PASSAGE;
				CREATE TEMP TABLE w_PASSAGE AS
				SELECT 
					SEA_HONUM,
					SEA_SEANCE,
					MIN(SEA_ID) AS SEA_ID,
					date(MIN(SEA_DATE)) AS SEA_DATE,
					date(MIN(SEA_DATE)) AS SEA_DATE_FIN,
					MIN(SEA_DATE + (SEA_HEURE - date(SEA_HEURE))) AS SEA_HEURE,
					MIN(SEA_DATE + (SEA_HEURE - date(SEA_HEURE))) +interval '59 seconds' AS SEA_HEURE_FIN,
					MIN(SEA_INCODE) AS SEA_INCODE,
					MIN(SEA_UFCODE) AS SEA_UFCODE,
					MIN(SEA_UFCODE) AS SEA_UMCODE,
					MIN(SEA_UFCODE) AS SEA_UFCODE_REA
				FROM prod_cerner.HOSPITALISATION
				JOIN prod_cerner.REGROUPEMENT ON HO_RECODE = RE_CODE
				JOIN prod_cerner.PASSAGE ON SEA_HONUM = HO_NUM AND RE_TYPE NOT IN ('H')
				GROUP BY 1,2;



				CREATE INDEX w_PASSAGE_i1
					ON w_PASSAGE
					USING btree
					(SEA_HONUM);

				CREATE INDEX w_PASSAGE_i2
					ON w_PASSAGE
					USING btree
					(SEA_ID);


				UPDATE w_PASSAGE
				SET SEA_UFCODE_REA = ACTE_UFXCODE,
					SEA_DATE_FIN = date(ACTE_HEURE_FIN),
					SEA_HEURE_FIN = ACTE_HEURE_FIN
				FROM w_PASSAGE_ACTES_SEANCE
				WHERE ACTE_SEAID = w_PASSAGE.SEA_ID AND
					(
					ACTE_UFXCODE <> SEA_UFCODE_REA OR
					SEA_HEURE_FIN <> ACTE_HEURE_FIN
					)
				;

				ANALYSE w_PASSAGE;

				
				DROP TABLE IF EXISTS w_HOSPITALISATION_SELECT;

				CREATE TEMP TABLE w_HOSPITALISATION_SELECT AS
				SELECT HO_NUM,
					HO_MANUMDOS,
					MA_SEXE,
					''::text AS HO_VNCODE,
					
					HO_RECODE,
					
					date(COALESCE(SEA_DATE,HO_DDEB)) AS HO_DDEB,
					date(COALESCE(SEA_DATE,HO_DFIN)) AS HO_DFIN,
					RE_TYPE,

					CASE
						WHEN RE_TYPE IN ('H') AND HO_DDEB >= '[ENV_ADM_ANNEEDEBUT]0101' THEN '1'
						WHEN RE_TYPE IN ('H') AND HO_DFIN >= '[ENV_ADM_ANNEEDEBUT]0101' THEN '1'
						WHEN RE_TYPE IN ('H') AND HO_DFIN IS NULL THEN '1'
						WHEN RE_TYPE NOT IN ('H') AND SEA_DATE >= '[ENV_ADM_ANNEEDEBUT]0101' THEN '1'
						ELSE '0' END AS HO_OK,
					
					
					COALESCE(trim(SEA_SEANCE),'') AS HO_SEANCE,
					date(CASE WHEN RE_TYPE IN ('H') THEN HO_DDEB ELSE COALESCE(SEA_DATE,HO_DDEB) END) AS HO_DDEBS,
					(SEA_HEURE - date(SEA_HEURE))::time without time zone AS HO_HDEBS,
					date(CASE WHEN RE_TYPE IN ('H') THEN HO_DFIN ELSE COALESCE(SEA_DATE,HO_DFIN) END) AS HO_DFINS,
					(SEA_HEURE - date(SEA_HEURE))::time without time zone AS HO_HFINS,

					HO_NUM::text AS HO_NUMSEJ,
					'1'::text AS sejour_a_creer,
					
					HO_PREENT,

					'8'::text AS mode_entree,
					''::text AS provenance,
					'0'::text AS urgence,
					'8'::text AS mode_sortie,
					''::text AS destination,

					COALESCE(SEA_INCODE,'') AS HO_INCODE,
					COALESCE(SEA_UFCODE_REA,'') AS HO_UFCODE_REA,
					COALESCE(SEA_UFCODE,'') AS HO_UFCODE,
					COALESCE(SEA_UMCODE,'') AS HO_UMCODE,
					''::text AS HO_UFHEBER,
					''::text AS HO_SACODE,
					''::text AS HO_LICODE,
					''::text AS HO_ETCODE_CTI,
					''::text AS HO_LICODE_CTI,
					''::text AS HO_ELCODE_CTI,
					
					''::text AS mode_traitement_code,
					''::text AS dmt_code,
					
					0::bigint AS mode_traitement_id,
					0::bigint AS tiers_payant_1_id,
					w_DEFAULT.tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id,
					w_DEFAULT.tiers_payant_0_id,
					0::bigint AS code_postal_id,
					0::bigint AS medecin_sejour_id,
					0::bigint AS lieu_sortie_id,
					CASE WHEN HO_VALID IS DISTINCT FROM 'X' AND HO_VALID IS DISTINCT FROM 'U' THEN '0' ELSE '9' END::text AS type_sejour_force,

					0::bigint AS sejour_id,
					'0'::text AS sans_sejour
				FROM prod_cerner.HOSPITALISATION
				JOIN prod_cerner.MALADE ON HO_MANUMDOS = MA_NUMDOS
				JOIN prod_cerner.REGROUPEMENT ON HO_RECODE = RE_CODE
				LEFT JOIN w_PASSAGE ON SEA_HONUM = HO_NUM AND RE_TYPE NOT IN ('H')
				JOIN w_DEFAULT ON 1=1
				WHERE (RE_TYPE IN ('H') OR SEA_HONUM IS NOT NULL) AND
					COALESCE(HO_PREENT,'') = ''
				;

				UPDATE w_HOSPITALISATION_SELECT SET
					HO_DFIN = HO_DDEB,
					HO_DFINS = HO_DDEBS,
					HO_HFINS = HO_HDEBS
				WHERE RE_TYPE NOT IN ('H') AND HO_DFIN IS NULL;

				CREATE INDEX w_HOSPITALISATION_SELECT_i1
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_NUM);

				CREATE INDEX w_HOSPITALISATION_SELECT_i2
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_MANUMDOS);
					
				CREATE INDEX w_HOSPITALISATION_SELECT_i_HO_NUMSEJ
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_NUMSEJ);


				UPDATE w_HOSPITALISATION_SELECT
				SET HO_OK = '0'
				WHERE HO_OK = '1' AND
					HO_DDEB > (SELECT now_cerner FROM w_PERIODE)
				;

				UPDATE w_HOSPITALISATION_SELECT
				SET HO_OK = '0'
				WHERE HO_OK = '1' AND
					RE_TYPE = 'H' AND
					HO_NUM NOT IN (SELECT MH_HONUM FROM w_MOUV_HOSPI_source)
				;
				
				UPDATE w_HOSPITALISATION_SELECT
				SET HO_OK = '1' 
				WHERE HO_OK <> '1' AND
					HO_NUM IN (SELECT FAC_HONUM FROM prod_cerner.FACTURE WHERE FAC_DATE >= '[ENV_ADM_ANNEEDEBUT]0101' OR FAC_EXER >= [ENV_ADM_ANNEEDEBUT])
				;
				
				UPDATE w_HOSPITALISATION_SELECT
				SET HO_OK = '1' 
				WHERE HO_OK <> '1' AND
					HO_NUM IN (SELECT MC_HONUM FROM prod_cerner.MOUV_COMPTA WHERE MC_DATECR >= '[ENV_ADM_ANNEEDEBUT]0101' OR MC_EXER >= [ENV_ADM_ANNEEDEBUT])
				;

				UPDATE w_HOSPITALISATION_SELECT
				SET HO_OK = '1' 
				WHERE HO_OK <> '1' AND
					HO_NUM IN (SELECT HO_NUM FROM w_HOSPITALISATION_SELECT WHERE HO_OK = '1')
				;

				
				-- Factures et règlements sans référence de séjour
				DROP TABLE IF EXISTS w_FACTURE_sans_sejour;
				CREATE TEMP TABLE w_FACTURE_sans_sejour AS
				SELECT FAC_NUM, 
					FAC_HONUM,
					FAD_SEANCE AS FAC_SEANCE,
					MIN(FAD_DEB) AS FAC_DDEB,
					MAX(FAD_FIN) AS FAC_DFIN,
					0::numeric AS FAC_MANUMDOS
				FROM prod_cerner.FACTURE_DET
				JOIN prod_cerner.FACTURE ON FAD_NUM = FAC_NUM
				LEFT JOIN w_HOSPITALISATION_SELECT ON
					FAC_HONUM = HO_NUM AND
					FAD_SEANCE = HO_SEANCE
				WHERE (FAC_DATE >= '[ENV_ADM_ANNEEDEBUT]0101' OR FAC_EXER >= [ENV_ADM_ANNEEDEBUT]) AND
					HO_NUM IS NULL
				GROUP BY 1,2,3
				;


				UPDATE prod_cerner.MOUV_COMPTA
				SET MC_HONUM = 999999999
				WHERE MC_HONUM = 0 AND MC_MANUMDOS = 0 AND
					(MC_COMPTE LIKE '411%' OR MC_COMPTE LIKE '412%' OR MC_COMPTE LIKE '413%' OR MC_COMPTE LIKE '414%' OR MC_COMPTE LIKE '452%' OR MC_COMPTE LIKE '467%')
				;

				INSERT INTO w_FACTURE_sans_sejour
				SELECT MC_NUMFAC_LET AS FAC_NUM,
					MC_HONUM AS FAC_HONUM, 
					''::text AS FAD_SEANCE,
					MIN(MC_DATECR) AS FAC_DDEB,
					MAX(MC_DATECR) AS FAC_DFIN,
					0::numeric AS FAC_MANUMDOS
				FROM prod_cerner.MOUV_COMPTA
				LEFT JOIN w_HOSPITALISATION_SELECT ON MC_HONUM = HO_NUM
				WHERE (MC_DATECR >= '[ENV_ADM_ANNEEDEBUT]0101' OR MC_EXER >= [ENV_ADM_ANNEEDEBUT]) AND
					(MC_COMPTE LIKE '411%' OR MC_COMPTE LIKE '412%' OR MC_COMPTE LIKE '413%' OR MC_COMPTE LIKE '414%' OR MC_COMPTE LIKE '452%' OR MC_COMPTE LIKE '467%') AND
					HO_NUM IS NULL
				GROUP BY 1,2
				HAVING SUM(CASE WHEN MC_SENS = 'C' THEN MC_MON ELSE 0-MC_MON END) <> 0
				;

				

				UPDATE w_FACTURE_sans_sejour
				SET FAC_MANUMDOS = MC_MANUMDOS
				FROM prod_cerner.MOUV_COMPTA
				WHERE MC_NUMV = FAC_NUM AND
					MC_HONUM = FAC_HONUM AND
					FAC_MANUMDOS = 0
				;

				INSERT INTO w_HOSPITALISATION_SELECT 
				SELECT FAC_HONUM,
					MAX(FAC_MANUMDOS),
					MAX(COALESCE(MA_SEXE,'1')),
					''::text AS HO_VNCODE,
					
					MIN(COALESCE(HOSPITALISATION.HO_RECODE,''::text)) AS HO_RECODE,
					
					MIN(date(FAC_DDEB)) AS HO_DDEB,
					MAX(date(FAC_DFIN)) AS HO_DFIN,
					MAX(COALESCE(REGROUPEMENT.RE_TYPE,''::text)) AS RE_TYPE,

					'1'::text AS HO_OK,
					
					
					FAC_SEANCE AS HO_SEANCE,
					MIN(date(FAC_DDEB)) AS HO_DDEBS,
					'11:00:00' AS HO_HDEBS,
					MAX(date(FAC_DFIN)) AS HO_DFINS,
					'11:00:00' AS HO_HFINS,

					MAX(FAC_HONUM) AS HO_NUMSEJ,
					'1'::text AS sejour_a_creer,
					
					''::text AS HO_PREENT,

					'8'::text AS mode_entree,
					''::text AS provenance,
					'0'::text AS urgence,
					'8'::text AS mode_sortie,
					''::text AS destination,

					''::text AS HO_INCODE,
					''::text AS HO_UFCODE_REA,
					''::text AS HO_UFCODE,
					''::text AS HO_UMCODE,
					''::text AS HO_UFHEBER,
					''::text AS HO_SACODE,
					''::text AS HO_LICODE,
					''::text AS HO_ETCODE_CTI,
					''::text AS HO_LICODE_CTI,
					''::text AS HO_ELCODE_CTI,
					
					''::text AS mode_traitement_code,
					''::text AS dmt_code,
					
					0::bigint AS mode_traitement_id,
					0::bigint AS tiers_payant_1_id,
					MAX(w_DEFAULT.tiers_payant_2_id),
					0::bigint AS tiers_payant_22_id,
					MAX(w_DEFAULT.tiers_payant_0_id),
					0::bigint AS code_postal_id,
					0::bigint AS medecin_sejour_id,
					0::bigint AS lieu_sortie_id,
					MAX(CASE WHEN FAC_SEANCE = '' OR FAC_HONUM IN (SELECT HO_NUM FROM w_HOSPITALISATION_SELECT ) THEN '0' ELSE '9' END) AS type_sejour_force,

					0::bigint AS sejour_id,
					'1'::text AS sans_sejour
				FROM w_FACTURE_sans_sejour
				LEFT JOIN prod_cerner.MALADE ON FAC_MANUMDOS = MA_NUMDOS
                LEFT JOIN prod_cerner.HOSPITALISATION ON FAC_HONUM = HOSPITALISATION.HO_NUM
                LEFT JOIN prod_cerner.REGROUPEMENT ON HO_RECODE = RE_CODE 
				JOIN w_DEFAULT ON 1=1
				GROUP BY 
					FAC_HONUM,
					FAC_SEANCE
				;
				
				
				
				-- Supprimer les dossiers à ne pas récupérer

				DELETE FROM w_HOSPITALISATION_SELECT
				WHERE HO_OK <> '1'
				;
				
				
				-- Numéro de séjour avec séance si séances multiples
				
				UPDATE w_HOSPITALISATION_SELECT
				SET HO_NUMSEJ = HO_NUMSEJ::text || '.' || to_char(HO_DFINS,'YYMMDD')
				WHERE HO_NUMSEJ IN
					(
					SELECT HO_NUMSEJ
					FROM w_HOSPITALISATION_SELECT
					WHERE RE_TYPE NOT IN ('H')
					GROUP BY 1
					HAVING count(DISTINCT HO_DFINS) > 1
					)
				;
				
				UPDATE w_HOSPITALISATION_SELECT SET
					sejour_a_creer = CASE WHEN w_HOSPITALISATION_SELECT.HO_SEANCE = subview.HO_SEANCE THEN '1' ELSE '0' END,
					HO_HDEBS = subview.HO_HDEBS,
					HO_HFINS = subview.HO_HFINS
				FROM
					(
					SELECT HO_NUMSEJ, (MIN(Array[sans_sejour,HO_SEANCE::text]))[2] AS HO_SEANCE,
						MIN(HO_HDEBS) AS HO_HDEBS,
						MAX(HO_HFINS) AS HO_HFINS
					FROM w_HOSPITALISATION_SELECT
					GROUP BY 1
					HAVING count(*) > 1
					) subview
				WHERE w_HOSPITALISATION_SELECT.HO_NUMSEJ = subview.HO_NUMSEJ 
				;
	

				ANALYSE w_HOSPITALISATION_SELECT;

				UPDATE w_HOSPITALISATION_SELECT
				SET HO_NUMSEJ = w_HOSPITALISATION_SELECT.HO_NUMSEJ || '.' || nb
				FROM
				(
				SELECT HO_NUMSEJ, count(*) AS nb, MAX(CTID) AS from_CTID
				FROM w_HOSPITALISATION_SELECT
				WHERE sejour_a_creer = '1'
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_HOSPITALISATION_SELECT.HO_NUMSEJ = subview.HO_NUMSEJ AND
					w_HOSPITALISATION_SELECT.CTID = from_CTID
				;
				
				DELETE FROM w_HOSPITALISATION_SELECT WHERE HO_NUMSEJ IS NULL
				;


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

	<NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
	
		<NODE label="Patients">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_PATIENT;
				CREATE TEMP TABLE w_PATIENT AS
				SELECT 
					MA_NUMDOS, 
					to_char(MA_NUMDOS,'FM0000000000') AS no_patient,
					MAX(MA_NOM1) AS MA_NOM1, 
					MAX(MA_PRENOM) AS MA_PRENOM, 
					MAX(MA_NOM2) AS MA_NOM2, 
					MAX(MA_DATENAI) AS MA_DATENAI,
					MAX(MA_SEXE) AS MA_SEXE
				FROM prod_cerner.MALADE
				WHERE MA_NUMDOS IN (SELECT HO_MANUMDOS FROM w_HOSPITALISATION_SELECT WHERE HO_OK = '1')
				GROUP BY 1,2;
				
				CREATE INDEX w_PATIENT_i1
				  ON w_PATIENT 
				  USING btree
				  (MA_NUMDOS);
				
				INSERT INTO w_PATIENT 
				SELECT HO_MANUMDOS,
					to_char(HO_MANUMDOS,'FM0000000000') AS no_patient,
					'Patient ' || HO_MANUMDOS AS MA_NOM1, 
					'' AS MA_PRENOM, 
					'' AS MA_NOM2, 
					'19620418' AS MA_DATENAI,
					'1' AS MA_SEXE
				FROM w_HOSPITALISATION_SELECT 
				LEFT JOIN w_PATIENT ON HO_MANUMDOS = MA_NUMDOS
				WHERE MA_NUMDOS IS NULL
				GROUP BY HO_MANUMDOS
				;


				CREATE INDEX w_PATIENT_i2
				  ON w_PATIENT 
				  USING btree
				  (no_patient);
				  
				UPDATE activite[PX].p_patients
				SET nom = MA_NOM1, 
					nom_naissance = MA_NOM2, 
					prenom = MA_PRENOM, 
					date_naissance = MA_DATENAI, 
					code_sexe = MA_SEXE
				FROM w_PATIENT 
				WHERE p_patients.no_patient = w_PATIENT.no_patient
					AND (
						p_patients.nom IS DISTINCT FROM MA_NOM1 OR 
						p_patients.prenom IS DISTINCT FROM MA_PRENOM OR
						nom_naissance IS DISTINCT FROM MA_NOM2 OR
						p_patients.date_naissance IS DISTINCT FROM MA_DATENAI OR
						p_patients.code_sexe IS DISTINCT FROM MA_SEXE
					);

				INSERT INTO activite[PX].p_patients(finess, no_patient, nom, prenom, nom_naissance, date_naissance, code_sexe)
				SELECT '', w_PATIENT.no_patient, MA_NOM1, MA_PRENOM, MA_NOM2, MA_DATENAI, MA_SEXE
				FROM w_PATIENT 
					LEFT JOIN activite[PX].p_patients ON (w_PATIENT.no_patient = p_patients.no_patient)
				WHERE p_patients.no_patient IS NULL;
				
				
				
				
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Séjours">
			<sqlcmd><![CDATA[
			
				-- Tiers payant
				DROP SEQUENCE IF EXISTS w_ADRESSE_tiers_seq;
				CREATE TEMP SEQUENCE w_ADRESSE_tiers_seq;

				DROP TABLE IF EXISTS w_ADRESSE_tiers;
				CREATE TEMP TABLE w_ADRESSE_tiers AS
				SELECT
					nextval('w_ADRESSE_tiers_seq'::regclass) AS sequence, 
					subview.*
				FROM
					(
					SELECT
						AD_MANUMDOS,
						CASE WHEN AD_PYTYPE IN ('1','2') THEN '1' ELSE '2' END AS AD_PYTYPE_CTI,
						AD_PYTYPE,
						AD_PYCODE,
						('C'||AD_PYTYPE||AD_PYCODE) AD_PYCODE_CTI,
						date(COALESCE(AD_HDEB,'00010101')) AS AD_HDEB,
						'20991231'::date AS AD_DFIN,
						AD_CPT
					FROM prod_cerner.ADRESSE
					WHERE AD_TYP = 'T' 
					ORDER BY 1,2,6,8
					) subview
				;

				UPDATE w_ADRESSE_tiers
				SET AD_DFIN = w_ADRESSE_tiers_a.AD_HDEB - interval '1 day'
				FROM w_ADRESSE_tiers w_ADRESSE_tiers_a
				WHERE w_ADRESSE_tiers.AD_MANUMDOS = w_ADRESSE_tiers_a.AD_MANUMDOS AND 
					w_ADRESSE_tiers.AD_PYTYPE_CTI = w_ADRESSE_tiers_a.AD_PYTYPE_CTI AND
					w_ADRESSE_tiers.sequence = w_ADRESSE_tiers_a.sequence - 1
				;

				UPDATE w_ADRESSE_tiers
				SET AD_HDEB = '00010101'
				WHERE sequence = 1 AND
					w_ADRESSE_tiers.AD_HDEB <> '00010101';

				UPDATE w_ADRESSE_tiers
				SET AD_HDEB = '00010101'
				FROM w_ADRESSE_tiers w_ADRESSE_tiers_b
				WHERE w_ADRESSE_tiers.sequence = w_ADRESSE_tiers_b.sequence + 1 AND
					(
					w_ADRESSE_tiers.AD_MANUMDOS <> w_ADRESSE_tiers_b.AD_MANUMDOS OR
					w_ADRESSE_tiers.AD_PYTYPE_CTI <> w_ADRESSE_tiers_b.AD_PYTYPE_CTI
					) AND
					w_ADRESSE_tiers.AD_HDEB <> '00010101'
					
				;

				CREATE INDEX w_ADRESSE_tiers_i1
					ON w_ADRESSE_tiers
					USING btree
					(AD_MANUMDOS);

				CREATE INDEX w_ADRESSE_tiers_i2
					ON w_ADRESSE_tiers
					USING btree
					(AD_PYCODE_CTI);


					
				UPDATE w_HOSPITALISATION_SELECT
				SET tiers_payant_1_id = t_tiers_payant.oid
				FROM w_ADRESSE_tiers 
				JOIN activite[PX].t_tiers_payant ON AD_PYCODE_CTI = t_tiers_payant.code_original
				WHERE w_HOSPITALISATION_SELECT.HO_MANUMDOS = w_ADRESSE_tiers.AD_MANUMDOS AND
					AD_PYTYPE_CTI = '1' AND
					HO_DDEB BETWEEN AD_HDEB AND AD_DFIN 
				;


				UPDATE w_HOSPITALISATION_SELECT
				SET tiers_payant_2_id = t_tiers_payant.oid
				FROM w_ADRESSE_tiers 
				JOIN activite[PX].t_tiers_payant ON AD_PYCODE_CTI = t_tiers_payant.code_original
				WHERE w_HOSPITALISATION_SELECT.HO_MANUMDOS = w_ADRESSE_tiers.AD_MANUMDOS AND
					AD_PYTYPE_CTI = '2' AND
					HO_DDEB BETWEEN AD_HDEB AND AD_DFIN 
				;
				
			
			
				-- Mouvement de sortie
				DROP TABLE IF EXISTS w_HOSPITALISATION_MOUV_SORTIE;
				CREATE TEMP TABLE w_HOSPITALISATION_MOUV_SORTIE AS
				SELECT MH_HONUM, 
					(MIN(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, (MH_HDEB - date(MH_HDEB))::text]))[2]::time without time zone AS MH_HDEB, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, (MH_HFIN - date(MH_HFIN))::text]))[2]::time without time zone AS MH_HFIN, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_INCODE]))[2] AS MH_INCODE, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_UFCODE]))[2] AS MH_UFCODE, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_UMCODE]))[2] AS MH_UMCODE, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_UFHEBER]))[2] AS MH_UFHEBER, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_SACODE]))[2] AS MH_SACODE, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_LICODE]))[2] AS MH_LICODE,
					(MIN(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_RSCODENT]))[2] AS MH_RSCODENT,
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_RSCODSOR]))[2] AS MH_RSCODSOR,
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_ETCODE_CTI]))[2] AS MH_ETCODE_CTI, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_LICODE_CTI]))[2] AS MH_LICODE_CTI, 
					(MAX(ARRAY[lpad(MH_DER,1,' ')||(MH_DDEB + (MH_HDEB - date(MH_HDEB)))::text, MH_ELCODE_CTI]))[2] AS MH_ELCODE_CTI, 
					'8'::text AS mode_entree,
					''::text AS provenance,
					'0'::text AS urgence,
					'8'::text AS mode_sortie,
					''::text AS destination
				FROM w_MOUV_HOSPI_source
				JOIN w_HOSPITALISATION_SELECT ON HO_NUM = MH_HONUM 
				GROUP BY 1
				;

				-- Modif CLA du 15-09-2017
				-- RAISON.RS_TYPESORT peut prendre des valeurs non aurotisées de mode d'entrée. On force donc à 8/0 si la valeur n'est pas standard
				UPDATE w_HOSPITALISATION_MOUV_SORTIE SET
					mode_entree = CASE WHEN t_modes_entree.code IS NULL THEN '8'::text ELSE RS_TYPESORT::text END,
					provenance = CASE WHEN t_modes_entree.code IS NULL THEN '0'::text ELSE RS_PROVDEST::text END,
					urgence = CASE WHEN RS_CODE = ANY(string_to_array(t_divers.valeur,',')) THEN '1' ELSE '0' END
				FROM prod_cerner.RAISON
				JOIN activite.t_divers ON t_divers.code = 'CERNER_RAISONURGENCE'
					LEFT JOIN base.t_modes_entree ON t_modes_entree.code = RS_TYPESORT
				WHERE MH_RSCODENT = RS_CODE AND
					(mode_entree <> CASE WHEN t_modes_entree.code IS NULL THEN '8'::text ELSE RS_TYPESORT::text END OR
					provenance <> CASE WHEN t_modes_entree.code IS NULL THEN '0'::text ELSE RS_PROVDEST::text END OR
					urgence <> CASE WHEN RS_CODE = ANY(string_to_array(t_divers.valeur,',')) THEN '1' ELSE '0' END)
				;

				-- Modif CLA du 15-09-2017
				-- RAISON.RS_TYPESORT peut prendre des valeurs non aurotisées de mode de sortie. On force donc à 8/0 si la valeur n'est pas standard
				UPDATE w_HOSPITALISATION_MOUV_SORTIE SET
					mode_sortie = CASE WHEN t_modes_sortie.code IS NULL THEN '8'::text ELSE RS_TYPESORT::text END,
					destination = CASE WHEN t_modes_sortie.code IS NULL THEN '0'::text ELSE RS_PROVDEST::text END
				FROM prod_cerner.RAISON
					LEFT JOIN base.t_modes_sortie ON t_modes_sortie.code = RS_TYPESORT
				WHERE MH_RSCODSOR = RS_CODE AND
					(mode_sortie <> CASE WHEN t_modes_sortie.code IS NULL THEN '8'::text ELSE RS_TYPESORT::text END OR
					destination <> CASE WHEN t_modes_sortie.code IS NULL THEN '0'::text ELSE RS_PROVDEST::text END)
				;


				CREATE INDEX w_HOSPITALISATION_MOUV_SORTIE_i1
					ON w_HOSPITALISATION_MOUV_SORTIE
					USING btree
					(MH_HONUM);


				UPDATE w_HOSPITALISATION_select SET
					HO_HDEBS = COALESCE(w_HOSPITALISATION_select.HO_HDEBS,MH_HDEB),
					HO_HFINS = COALESCE(w_HOSPITALISATION_select.HO_HFINS,MH_HFIN),
					HO_INCODE = CASE 
						WHEN w_HOSPITALISATION_select.HO_INCODE <> '' THEN w_HOSPITALISATION_select.HO_INCODE
						ELSE MH_INCODE END,
					HO_UFCODE = CASE 
						WHEN w_HOSPITALISATION_select.HO_UFCODE <> '' THEN w_HOSPITALISATION_select.HO_UFCODE
						ELSE MH_UFCODE END,
					HO_UMCODE = CASE 
						WHEN w_HOSPITALISATION_select.HO_UMCODE <> '' THEN w_HOSPITALISATION_select.HO_UMCODE
						ELSE MH_UMCODE END,
					HO_UFCODE_REA = CASE 
						WHEN w_HOSPITALISATION_select.HO_UFCODE_REA <> '' THEN w_HOSPITALISATION_select.HO_UFCODE_REA
						ELSE MH_UFCODE END,
					HO_UFHEBER = CASE 
						WHEN w_HOSPITALISATION_select.HO_UFHEBER <> '' THEN w_HOSPITALISATION_select.HO_UFHEBER
						WHEN MH_UFHEBER <> '' THEN MH_UFHEBER 
						WHEN w_HOSPITALISATION_select.HO_UFCODE <> '' THEN w_HOSPITALISATION_select.HO_UFCODE
						ELSE MH_UFCODE END,
					HO_SACODE = CASE 
						WHEN w_HOSPITALISATION_select.HO_SACODE <> '' THEN w_HOSPITALISATION_select.HO_SACODE  
						ELSE MH_SACODE END,
					HO_LICODE = CASE 
						WHEN w_HOSPITALISATION_select.HO_LICODE <> '' THEN w_HOSPITALISATION_select.HO_LICODE 
						WHEN MH_LICODE <> '' AND MH_LICODE <> MH_UFCODE AND MH_LICODE <> MH_UFHEBER THEN MH_LICODE 
						WHEN MH_SACODE <> '' AND MH_SACODE <> MH_UFCODE AND MH_SACODE <> MH_UFHEBER THEN MH_SACODE
						ELSE '0' END,
					HO_ETCODE_CTI = CASE 
						WHEN w_HOSPITALISATION_select.HO_ETCODE_CTI <> '' THEN w_HOSPITALISATION_select.HO_ETCODE_CTI
						ELSE MH_ETCODE_CTI END,
					HO_LICODE_CTI = CASE 
						WHEN w_HOSPITALISATION_select.HO_LICODE_CTI <> '' THEN w_HOSPITALISATION_select.HO_LICODE_CTI
						ELSE MH_LICODE_CTI END,
					HO_ELCODE_CTI = CASE 
						WHEN w_HOSPITALISATION_select.HO_ELCODE_CTI <> '' THEN w_HOSPITALISATION_select.HO_ELCODE_CTI
						ELSE MH_ELCODE_CTI END,
						mode_entree = w_HOSPITALISATION_MOUV_SORTIE.mode_entree,
						provenance = w_HOSPITALISATION_MOUV_SORTIE.provenance,
						urgence = w_HOSPITALISATION_MOUV_SORTIE.urgence,
						mode_sortie = w_HOSPITALISATION_MOUV_SORTIE.mode_sortie,
						destination = w_HOSPITALISATION_MOUV_SORTIE.destination
				FROM w_HOSPITALISATION_MOUV_SORTIE
				WHERE HO_NUM = MH_HONUM AND
					(
					HO_HDEBS IS NULL OR
					HO_HFINS IS NULL OR
					HO_INCODE = '' OR
					HO_UFCODE = '' OR
					HO_UMCODE = '' OR
					HO_UFHEBER = '' OR
					HO_SACODE = '' OR
					HO_LICODE = '' OR
					HO_ETCODE_CTI = '' OR
					HO_LICODE_CTI = '' OR
					HO_ELCODE_CTI = '' OR
					w_HOSPITALISATION_MOUV_SORTIE.mode_entree <> '8' OR
					w_HOSPITALISATION_MOUV_SORTIE.mode_sortie <> '8' OR
					w_HOSPITALISATION_MOUV_SORTIE.urgence <> '0'
					)
				;

				

				DROP TABLE IF EXISTS w_MALADE_code_postal;
				CREATE TEMP TABLE w_MALADE_code_postal AS
				SELECT AD_MANUMDOS, (MAX(ARRAY[to_char(AD_CPT,'FM000'),t_codes_postaux.oid::text]))[2]::bigint AS code_postal_id
				FROM prod_cerner.ADRESSE
				JOIN base.t_codes_postaux ON AD_VNCODE = t_codes_postaux.code
				WHERE AD_TYP = 'M'
				GROUP BY 1
				;
				
				
				UPDATE w_HOSPITALISATION_select SET
					code_postal_id = w_MALADE_code_postal.code_postal_id
				FROM w_MALADE_code_postal
				WHERE HO_MANUMDOS = AD_MANUMDOS
				;

				UPDATE w_HOSPITALISATION_select SET
					mode_traitement_id = t_services_facturation.mode_traitement_id,
					mode_traitement_code = t_modes_traitement.code,
					dmt_code = t_dmt.code
				FROM activite[PX].t_services_facturation
					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
				WHERE t_services_facturation.code_original = HO_UFCODE
				;

				UPDATE w_HOSPITALISATION_select SET
					medecin_sejour_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE t_medecins_administratifs.code_original = HO_INCODE
				;

				CREATE INDEX w_HOSPITALISATION_SELECT_i3
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_UFHEBER);

				CREATE INDEX w_HOSPITALISATION_SELECT_i4
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_LICODE_CTI);

				CREATE INDEX w_HOSPITALISATION_SELECT_i5
					ON w_HOSPITALISATION_SELECT
					USING btree
					(HO_UFCODE);

				ANALYSE w_HOSPITALISATION_SELECT;

				

				


				-- Id des Tiers payant
				--UPDATE w_HOSPITALISATION_SELECT
				--SET tiers_payant_1_id = t_tiers_payant.oid
				--FROM activite[PX].t_tiers_payant
				--WHERE t_tiers_payant.code_original = ('C'||NOCAIS)
				;

				



				


				


				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
				SELECT HO_UFCODE, 
					HO_RECODE, 
					HO_ETCODE_CTI, 
					HO_ELCODE_CTI,
					HO_UMCODE, 
					HO_UFCODE_REA
				FROM w_HOSPITALISATION_SELECT
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = HO_UFCODE AND
						code_original_2 = HO_RECODE AND
						code_original_3 = HO_ETCODE_CTI AND
						code_original_4 = HO_ELCODE_CTI AND
						code_original_5 = HO_UMCODE AND
						code_original_6 = HO_UFCODE_REA
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5,6;

				

				UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0)
				FROM
					activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original AND
					(t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
					;

				UPDATE activite[PX].t_lieux SET
					activite_id = COALESCE(t_activites.oid,0)
				FROM
					activite[PX].t_activites
				WHERE code_original_2 = t_activites.code_original
					AND activite_id <> COALESCE(t_activites.oid,0);


				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);

				UPDATE activite[PX].t_lieux SET
					unite_medicale_id = COALESCE(t_unites_medicales.oid,0)
				FROM
					activite[PX].t_unites_medicales
				WHERE code_original_5 = t_unites_medicales.code_original
					AND unite_medicale_id <> COALESCE(t_unites_medicales.oid,0);
				

				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM
					activite[PX].t_lits
				WHERE code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;

				UPDATE w_HOSPITALISATION_SELECT SET
					lieu_sortie_id = t_lieux.oid,
					type_sejour_force = CASE WHEN w_HOSPITALISATION_SELECT.type_sejour_force <> '9' AND t_services_facturation.type_sejour IN ('1', '2', '3', '4', '5', '6') THEN t_services_facturation.type_sejour ELSE w_HOSPITALISATION_SELECT.type_sejour_force END
				FROM activite[PX].t_lieux
				JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE code_original_1 = HO_UFCODE AND
					code_original_2 = HO_RECODE AND
					code_original_3 = HO_ETCODE_CTI AND
					code_original_4 = HO_ELCODE_CTI AND
					code_original_5 = HO_UMCODE AND
					code_original_6 = HO_UFCODE_REA
				;



				DROP TABLE IF EXISTS w_sejours;
				CREATE TEMP TABLE w_sejours AS
				SELECT 
					'000000000'::text AS finess,
					w_HOSPITALISATION_SELECT.HO_NUMSEJ as no_sejour, 
					w_HOSPITALISATION_SELECT.HO_NUMSEJ as code_original, 
					to_char(HO_MANUMDOS,'FM0000000000') as no_patient, 
					HO_DDEBS as date_entree, 
					to_char(HO_HDEBS,'HH24MISS')::numeric as heure_entree, 
					COALESCE(HO_DFINS,'20991231') as date_sortie, 
					to_char(HO_HFINS,'HH24MISS')::numeric as heure_sortie, 
					MA_SEXE as code_sexe, 
					0 AS age, 
					CASE WHEN HO_DFINS IS NULL THEN 0 ELSE 1 END::numeric as code_sorti, 
					CASE WHEN HO_DDEBS > now() THEN 1::numeric ELSE 0::numeric END AS code_prevu,
					CASE 
						WHEN type_sejour_force <> '0' THEN type_sejour_force
						WHEN RE_TYPE = 'C' THEN '3'
						WHEN RE_TYPE = 'H' AND HO_DFINS = HO_DDEBS THEN '2' 
						WHEN RE_TYPE = 'H' THEN '1' 
						WHEN mode_traitement_code IN ('07') OR dmt_code IN ('958') THEN '3' 
						WHEN mode_traitement_code IN ('03') AND HO_DFINS = HO_DDEBS THEN '2' 
						WHEN mode_traitement_code IN ('04') AND HO_DFINS = HO_DDEBS THEN '2' 
						WHEN mode_traitement_code IN ('19', '23') AND HO_DFINS = HO_DDEBS THEN '2' 
						WHEN mode_traitement_code IN ('03') THEN '1' 
						WHEN HO_DFINS = HO_DDEBS THEN '2' 
						ELSE '1' END as type_sejour,
					w_HOSPITALISATION_SELECT.lieu_sortie_id AS lieu_sortie_id,
					w_HOSPITALISATION_SELECT.medecin_sejour_id,
					0::bigint AS ghs_id,
					0::bigint AS ghm_id,
					0::bigint AS ghs_bebe1_id,
					0::bigint AS ghs_bebe2_id,
					0::bigint AS ghs_bebe3_id,
					'20991231'::date AS DATE_GROUPAGE,
					'0'::text AS code_cp_demandee,
					w_HOSPITALISATION_SELECT.mode_traitement_id,
					w_HOSPITALISATION_SELECT.mode_entree,
					w_HOSPITALISATION_SELECT.provenance,
					w_HOSPITALISATION_SELECT.mode_sortie,
					w_HOSPITALISATION_SELECT.destination,
					w_HOSPITALISATION_SELECT.tiers_payant_0_id,
					w_HOSPITALISATION_SELECT.tiers_payant_1_id,
					w_HOSPITALISATION_SELECT.tiers_payant_2_id,
					w_HOSPITALISATION_SELECT.tiers_payant_22_id,
					1 AS est_budget_global,
					w_HOSPITALISATION_SELECT.code_postal_id
				FROM w_HOSPITALISATION_SELECT
				WHERE sejour_a_creer = '1'
				;

				

				-- 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');


				-- FINESS
				UPDATE w_sejours
				SET finess = t_finess.code
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_services_facturation on  service_facturation_id = t_services_facturation.oid
				JOIN base.t_finess ON finess_id = t_finess.oid
				WHERE lieu_sortie_id = t_lieux.oid;

                -- GHM et GHS depuis PMSI
                UPDATE w_sejours p_sejours
                SET ghm_id = subview.ghm_id, ghs_id = subview.ghs_id
                FROM
                (
                    SELECT no_sejour, t_ghm_a.oid AS ghm_id, t_ghs_a.oid AS ghs_id
                    FROM w_sejours p_sejours
                    JOIN pmsi.p_rss ON p_sejours.no_sejour = p_rss.no_sejour_administratif AND
                        date_trunc('month',p_sejours.date_sortie) = date_trunc('month',p_rss.date_sortie)
                    JOIN pmsi.t_ghm t_ghm_p ON p_rss.ghm_id = t_ghm_p.oid
                    JOIN base.t_ghs t_ghs_p ON p_rss.ghs_id = t_ghs_p.oid
                    JOIN base.t_ghm t_ghm_a ON t_ghm_p.code = t_ghm_a.code
                    JOIN base.t_ghs t_ghs_a ON t_ghs_p.code = t_ghs_a.code
                    WHERE type_sejour IN ('1','2','5') AND
                        p_rss.ghm_id > 0 AND
                        p_sejours.ghm_id <> t_ghm_a.oid AND
                        t_ghm_p.code NOT LIKE '90%' AND t_ghm_p.code NOT LIKE '99%' 
                ) subview
                WHERE p_sejours.no_sejour = subview.no_sejour
                ;

				-- Validation des séjours

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

				UPDATE activite[PX].p_sejours SET
					finess = w_sejours.finess, 
					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, 
					lieu_sortie_id = w_sejours.lieu_sortie_id,
					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,
					date_groupage = w_sejours.date_groupage,
					ghs_id = w_sejours.ghs_id,
					ghm_id = w_sejours.ghm_id,
					ghs_bebe1_id = w_sejours.ghs_bebe1_id,
					ghs_bebe2_id = w_sejours.ghs_bebe2_id,
					ghs_bebe3_id = w_sejours.ghs_bebe3_id,
					code_postal_id = w_sejours.code_postal_id
				FROM w_sejours
				WHERE w_sejours.no_sejour = p_sejours.no_sejour
				AND (
					w_sejours.finess IS DISTINCT FROM p_sejours.finess OR
					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.lieu_sortie_id IS DISTINCT FROM p_sejours.lieu_sortie_id 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 OR
					w_sejours.date_groupage IS DISTINCT FROM p_sejours.date_groupage OR
					w_sejours.ghs_id IS DISTINCT FROM p_sejours.ghs_id OR
					w_sejours.ghm_id IS DISTINCT FROM p_sejours.ghm_id OR
					w_sejours.ghs_bebe1_id IS DISTINCT FROM p_sejours.ghs_bebe1_id OR
					w_sejours.ghs_bebe2_id IS DISTINCT FROM p_sejours.ghs_bebe2_id OR
					w_sejours.ghs_bebe3_id IS DISTINCT FROM p_sejours.ghs_bebe3_id OR
					w_sejours.code_postal_id IS DISTINCT FROM p_sejours.code_postal_id
				);		


				INSERT INTO activite[PX].p_sejours (
					finess,
					no_sejour, 
					code_original, 
					no_patient, 
					date_entree, 
					heure_entree, 
					date_sortie, 
					heure_sortie, 
					code_sexe, 
					age, 
					code_sorti, 
					code_prevu, 
					type_sejour, 
					lieu_sortie_id,
					medecin_sejour_id,
					ghs_id,
					ghm_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_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,
					code_postal_id
				) 
				SELECT 
					w_sejours.finess, 
					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.lieu_sortie_id,
					w_sejours.medecin_sejour_id,
					w_sejours.ghs_id,
					w_sejours.ghm_id,
					w_sejours.ghs_bebe1_id,
					w_sejours.ghs_bebe2_id,
					w_sejours.ghs_bebe3_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,
					w_sejours.code_postal_id
				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 WHERE no_sejour NOT IN (SELECT no_sejour FROM w_sejours );
				
				DELETE FROM activite[PX].p_sejours USING
				(
				SELECT no_sejour, min(CTID) AS koctid 
				FROM activite[PX].p_sejours
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE CTID = koctid;
				
				-- 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
					'' = '';

				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
					'' = '';
				
				-- 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
					'' = '';
			
			
				-- recréation index
				
				SELECT base.cti_enable_index('activite', 'i_sejours_2');
				SELECT base.cti_enable_index('activite', 'i_sejours_3');
				SELECT base.cti_enable_index('activite', 'i_sejours_4');
				SELECT base.cti_enable_index('activite', 'i_sejours_5');
				SELECT base.cti_enable_index('activite', 'i_sejours_6');
				SELECT base.cti_enable_index('activite', 'i_sejours_7');
				SELECT base.cti_enable_index('activite', 'i_sejours_8');
				SELECT base.cti_enable_index('activite', 'i_sejours_9');
				SELECT base.cti_enable_index('activite', 'i_sejours_10');
				SELECT base.cti_enable_index('activite', 'i_sejours_11');
				SELECT base.cti_enable_index('activite', 'i_sejours_12');
				SELECT base.cti_enable_index('activite', 'i_sejours_13');	
				
				
				UPDATE w_HOSPITALISATION_SELECT
				SET sejour_id = p_sejours.oid
				FROM activite[PX].p_sejours
				WHERE HO_NUMSEJ = p_sejours.code_original
				;
									
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Mouvements">
			<sqlcmd><![CDATA[

				DROP SEQUENCE IF EXISTS w_MOUV_HOSPI_seq;
				CREATE TEMP SEQUENCE w_MOUV_HOSPI_seq;

				DROP TABLE IF EXISTS w_MOUV_HOSPI;
				CREATE TEMP TABLE w_MOUV_HOSPI AS
				SELECT 
					nextval('w_MOUV_HOSPI_seq'::regclass) AS sequence, 
					subview.*
				FROM
					(
					SELECT
						w_HOSPITALISATION_SELECT.HO_NUMSEJ,
						w_HOSPITALISATION_SELECT.HO_NUM,
						HO_DDEBS,
						HO_HDEBS,
						HO_DDEBS + HO_HDEBS AS HO_DHDEBS,
						HO_DFINS,
						HO_HFINS,
						HO_DFINS + HO_HFINS AS HO_DHFINS,

						date(MH_DDEB) AS MH_DDEB,
						(MH_HDEB - date(MH_HDEB))::time without time zone AS MH_HDEB,
						MH_DDEB + ((MH_HDEB - date(MH_HDEB))) AS MH_DHDEB,
						date(MH_DFIN) AS MH_DFIN,
						(MH_HFIN - date(MH_HFIN))::time without time zone AS MH_HFIN,
						MH_DFIN + ((MH_HFIN - date(MH_HFIN))) AS MH_DHFIN,
						0::bigint AS lieu_id,
						'0'::text AS est_chambre_particuliere,
						w_HOSPITALISATION_SELECT.urgence,
						
						MH_UFCODE AS lieu_service_facturation_code_original,
						HO_RECODE AS lieu_activite_code_original,
						MH_ETCODE_CTI AS lieu_etage_code_original,
						MH_LICODE_CTI AS lieu_lit_code,
						MH_ELCODE_CTI AS lieu_lit_code_original,
						MH_UFCODE AS lieu_unite_fonctionnelle_code_original,
						MH_UMCODE AS lieu_unite_medicale_code_original,

						''::text AS lieu_service_facturation_before,
						''::text AS lieu_activite_before,
						''::text AS lieu_etage_before,
						''::text AS lieu_lit_before,
						''::text AS lieu_unite_fonctionnelle_before,
						''::text AS lieu_unite_medicale_before,
						''::text AS lieu_service_facturation_after,
						''::text AS lieu_activite_after,
						''::text AS lieu_etage_after,
						''::text AS lieu_lit_after,
						''::text AS lieu_unite_fonctionnelle_after,
						''::text AS lieu_unite_medicale_after
					FROM w_HOSPITALISATION_SELECT
					JOIN w_MOUV_HOSPI_source ON w_HOSPITALISATION_SELECT.HO_NUM = w_MOUV_HOSPI_source.MH_HONUM
					WHERE RE_TYPE = 'H'
					ORDER BY 1,9,10
					) subview
				;


				CREATE INDEX w_MOUV_HOSPI_i1
					ON w_MOUV_HOSPI
					USING btree
					(HO_NUMSEJ);

				CREATE INDEX w_MOUV_HOSPI_i2
					ON w_MOUV_HOSPI
					USING btree
					(sequence);

					

				-- Correction des mouvements en désaccord avec séjour (date entrée)
				UPDATE w_MOUV_HOSPI SET
					MH_DDEB = w_MOUV_HOSPI.HO_DDEBS,
					MH_HDEB = w_MOUV_HOSPI.HO_HDEBS,
					MH_DHDEB = w_MOUV_HOSPI.HO_DHDEBS
				FROM
					(
					SELECT HO_NUMSEJ, 
						MIN(sequence) AS sequence_first,
						MAX(HO_DDEBS) AS HO_DDEBS,
						MAX(HO_HDEBS) AS HO_HDEBS,
						MAX(HO_DHDEBS) AS HO_DHDEBS,
						(MIN(ARRAY[to_char(sequence,'FM00000000'),MH_DDEB::text]))[2]::date AS MH_DDEB_first,
						(MIN(ARRAY[to_char(sequence,'FM00000000'),MH_HDEB::text]))[2]::time without time zone AS MH_HDEB_first,
						(MIN(ARRAY[to_char(sequence,'FM00000000'),MH_DHDEB::text]))[2]::timestamp without time zone AS MH_DHDEB_first
					FROM w_MOUV_HOSPI
					GROUP BY 1
					HAVING MAX(HO_DHDEBS) <>
						(MIN(ARRAY[to_char(sequence,'FM00000000'),MH_DHDEB::text]))[2]::timestamp without time zone
					) subview
				WHERE w_MOUV_HOSPI.HO_NUMSEJ = subview.HO_NUMSEJ AND
					w_MOUV_HOSPI.sequence = subview.sequence_first
				;

				

				-- Correction des mouvements en désaccord avec séjour (date sortie)
				UPDATE w_MOUV_HOSPI SET
					MH_DFIN = w_MOUV_HOSPI.HO_DFINS,
					MH_HFIN = w_MOUV_HOSPI.HO_HFINS,
					MH_DHFIN = w_MOUV_HOSPI.HO_DHFINS
				FROM
					(
					SELECT HO_NUMSEJ, 
						MAX(sequence) AS sequence_last,
						MAX(HO_DFINS) AS HO_DFINS,
						MAX(HO_HFINS) AS HO_HFINS,
						MAX(HO_DHFINS) AS HO_DHFINS,
						(MAX(ARRAY[to_char(sequence,'FM00000000'),MH_DFIN::text]))[2]::date AS MH_DFIN_last,
						(MAX(ARRAY[to_char(sequence,'FM00000000'),MH_HFIN::text]))[2]::time without time zone AS MH_HFIN_last,
						(MAX(ARRAY[to_char(sequence,'FM00000000'),MH_DHFIN::text]))[2]::timestamp without time zone AS MH_DHFIN_last
					FROM w_MOUV_HOSPI
					GROUP BY 1
					HAVING MAX(HO_DHFINS) <>
						(MAX(ARRAY[to_char(sequence,'FM00000000'),MH_DHFIN::text]))[2]::timestamp without time zone
					) subview
				WHERE w_MOUV_HOSPI.HO_NUMSEJ = subview.HO_NUMSEJ AND
					w_MOUV_HOSPI.sequence = subview.sequence_last
				;

				UPDATE w_MOUV_HOSPI SET
					MH_DHDEB = MH_DHFIN - interval '1 second',
					MH_DDEB = date(MH_DHFIN - interval '1 second'),
					MH_HDEB = (MH_DHFIN - interval '1 second')::time without time zone
				WHERE MH_DHDEB > MH_DHFIN
				;


				UPDATE w_MOUV_HOSPI SET
					MH_DHFIN = w_MOUV_HOSPI_after.MH_DHDEB - interval '1 second',
					MH_DFIN = date(w_MOUV_HOSPI_after.MH_DHDEB - interval '1 second'),
					MH_HFIN = (w_MOUV_HOSPI_after.MH_DHDEB - interval '1 second')::time without time zone
				FROM w_MOUV_HOSPI w_MOUV_HOSPI_after 
				WHERE w_MOUV_HOSPI.HO_NUMSEJ = w_MOUV_HOSPI_after.HO_NUMSEJ AND
					w_MOUV_HOSPI.sequence = w_MOUV_HOSPI_after.sequence -1
				;

				DELETE FROM w_MOUV_HOSPI
				WHERE MH_DHFIN < HO_DHDEBS
				;


				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
				SELECT lieu_service_facturation_code_original, 
					lieu_activite_code_original, 
					lieu_etage_code_original, 
					lieu_lit_code_original,
					lieu_unite_medicale_code_original,
					lieu_unite_fonctionnelle_code_original
				FROM w_MOUV_HOSPI
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = lieu_service_facturation_code_original AND
						code_original_2 = lieu_activite_code_original AND
						code_original_3 = lieu_etage_code_original AND
						code_original_4 = lieu_lit_code_original AND
						code_original_5 = lieu_unite_medicale_code_original AND
						code_original_6 = lieu_unite_fonctionnelle_code_original
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5,6;

				

				UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0)
				FROM
					activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original AND
					(t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
					;

				UPDATE activite[PX].t_lieux SET
					activite_id = COALESCE(t_activites.oid,0)
				FROM
					activite[PX].t_activites
				WHERE code_original_2 = t_activites.code_original
					AND activite_id <> COALESCE(t_activites.oid,0);


				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);

				UPDATE activite[PX].t_lieux SET
					unite_medicale_id = COALESCE(t_unites_medicales.oid,0)
				FROM
					activite[PX].t_unites_medicales
				WHERE code_original_5 = t_unites_medicales.code_original
					AND unite_medicale_id <> COALESCE(t_unites_medicales.oid,0);
				

				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM
					activite[PX].t_lits
				WHERE code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;

				UPDATE w_MOUV_HOSPI SET
					lieu_id = t_lieux.oid,
					est_chambre_particuliere = CASE WHEN t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END
				FROM activite[PX].t_lieux
				JOIN activite[PX].t_lits ON lit_id = t_lits.oid
				WHERE 
					code_original_1 = lieu_service_facturation_code_original AND
					code_original_2 = lieu_activite_code_original AND
					code_original_3 = lieu_etage_code_original AND
					code_original_4 = lieu_lit_code_original AND
					code_original_5 = lieu_unite_medicale_code_original AND
					code_original_6 = lieu_unite_fonctionnelle_code_original
				;



				-- Etat avant
				UPDATE w_MOUV_HOSPI SET
					lieu_service_facturation_before = w_MOUV_HOSPI_before.lieu_service_facturation_code_original,
					lieu_activite_before = w_MOUV_HOSPI_before.lieu_activite_code_original,
					lieu_etage_before = w_MOUV_HOSPI_before.lieu_etage_code_original,
					lieu_lit_before = w_MOUV_HOSPI_before.lieu_lit_code_original,
					lieu_unite_fonctionnelle_before = w_MOUV_HOSPI_before.lieu_unite_fonctionnelle_code_original,
					lieu_unite_medicale_before = w_MOUV_HOSPI_before.lieu_unite_medicale_code_original
				FROM w_MOUV_HOSPI w_MOUV_HOSPI_before 
				WHERE w_MOUV_HOSPI.HO_NUMSEJ = w_MOUV_HOSPI_before.HO_NUMSEJ AND
					w_MOUV_HOSPI.sequence = w_MOUV_HOSPI_before.sequence +1
				;

				-- Etat apres
				UPDATE w_MOUV_HOSPI SET
					lieu_service_facturation_after = w_MOUV_HOSPI_after.lieu_service_facturation_code_original,
					lieu_activite_after = w_MOUV_HOSPI_after.lieu_activite_code_original,
					lieu_etage_after = w_MOUV_HOSPI_after.lieu_etage_code_original,
					lieu_lit_after = w_MOUV_HOSPI_after.lieu_lit_code_original,
					lieu_unite_fonctionnelle_after = w_MOUV_HOSPI_after.lieu_unite_fonctionnelle_code_original,
					lieu_unite_medicale_after = w_MOUV_HOSPI_after.lieu_unite_medicale_code_original
				FROM w_MOUV_HOSPI w_MOUV_HOSPI_after 
				WHERE w_MOUV_HOSPI.HO_NUMSEJ = w_MOUV_HOSPI_after.HO_NUMSEJ AND
					w_MOUV_HOSPI.sequence = w_MOUV_HOSPI_after.sequence -1
				;

				


				DROP TABLE IF EXISTS w_mouvements_sejour;

				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_MOUV_HOSPI.HO_NUM,
					w_MOUV_HOSPI.HO_NUMSEJ 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 = MH_DDEB THEN to_char(MH_HDEB,'HH24MISS')::numeric ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date = MH_DFIN THEN to_char(MH_HFIN,'HH24MISS')::numeric ELSE 240000 END AS heure_fin,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN MH_DHFIN = HO_DHFINS AND p_calendrier.date = MH_DFIN AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN MH_DHFIN = HO_DHFINS AND p_calendrier.date = MH_DFIN AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
					CASE WHEN p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_passage_externe,
					CASE WHEN w_MOUV_HOSPI.urgence = '1' AND p_calendrier.date = MH_DDEB AND MH_DHDEB = HO_DHDEBS THEN 1 ELSE 0 END AS nb_urgences,
					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '5' THEN 1 ELSE 0 END AS nb_seances,

					CASE WHEN p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '1' AND MH_DHDEB <> HO_DHDEBS AND lieu_service_facturation_code_original <> lieu_service_facturation_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = MH_DFIN AND p_sejours.type_sejour = '1' AND MH_DHFIN <> HO_DHFINS AND lieu_service_facturation_code_original <> lieu_service_facturation_after THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '1' AND MH_DHDEB <> HO_DHDEBS AND lieu_etage_code_original <> lieu_etage_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = MH_DFIN AND p_sejours.type_sejour = '1' AND MH_DHFIN <> HO_DHFINS AND lieu_etage_code_original <> lieu_etage_after 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' THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND p_calendrier.date <> MH_DFIN THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE WHEN p_sejours.type_sejour IN ('1','2') THEN est_chambre_particuliere ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN p_sejours.type_sejour IN ('1','2') AND est_chambre_particuliere = 1 THEN 1 ELSE 0 END AS nb_chambres_particulieres,

					CASE WHEN MH_DHDEB = HO_DHDEBS AND p_calendrier.date = MH_DDEB AND p_sejours.type_sejour = '6' THEN 1 ELSE 0 END AS nb_bebes,

					lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id,
					
					CASE WHEN p_sejours.code_prevu = '1' OR p_calendrier.date > date(now_cerner) THEN '1' ELSE '0' END AS est_mouvement_previsionnel
				FROM w_MOUV_HOSPI 
					JOIN w_PERIODE ON 1=1
					JOIN activite[PX].p_sejours ON w_MOUV_HOSPI.HO_NUMSEJ = p_sejours.no_sejour AND p_sejours.etat = ''
					JOIN base.p_calendrier ON (p_calendrier.date BETWEEN MH_DDEB AND MH_DFIN AND p_calendrier.date <= now() + interval '1 month' )
				ORDER BY sequence, p_calendrier.date;

				
				-- Externes (avec passages donc possibilité d'avoir plusieurs externes pour un séjour)
				DROP TABLE IF EXISTS w_mouvements_externes;
				CREATE TEMP TABLE w_mouvements_externes AS
				SELECT 
					HO_NUMSEJ,
					COALESCE(SEA_DATE,HO_DDEBS) AS HO_DDEBS,
					COALESCE((SEA_HEURE - date(SEA_HEURE))::time without time zone,HO_HDEBS) AS HO_HDEBS,
					SEA_ID,
					COALESCE(ACTE_UFXCODE,SEA_UFCODE_REA,HO_UFCODE_REA) AS ACTE_UFXCODE,
					to_char(SEA_ID,'FM000000000000')||COALESCE(ACTE_UFXCODE,SEA_UFCODE_REA,HO_UFCODE_REA) AS ACTE_KEY,
					MAX(HO_NUM) AS HO_NUM,
					MAX(COALESCE(SEA_DATE_FIN,HO_DFINS)) AS HO_DFINS,
					MAX(COALESCE((SEA_HEURE_FIN - date(SEA_HEURE_FIN))::time without time zone,HO_HFINS)) AS HO_HFINS,
					MAX(w_HOSPITALISATION_SELECT.medecin_sejour_id) AS medecin_sejour_id,
					MAX(w_HOSPITALISATION_SELECT.lieu_sortie_id) AS lieu_id,
					MAX(COALESCE(SEA_UFCODE,HO_UFCODE)) AS lieu_service_facturation_code_original,
					MAX(HO_RECODE) AS lieu_activite_code_original,
					MAX(HO_ETCODE_CTI) AS lieu_etage_code_original,
					MAX(HO_ELCODE_CTI) AS lieu_lit_code_original,
					''::text AS lieu_unite_medicale_code_original,
					MAX(COALESCE(ACTE_UFXCODE,SEA_UFCODE_REA,HO_UFCODE_REA)) AS lieu_unite_fonctionnelle_code_original,
					'0'::text AS est_chambre_particuliere,
					'1'::text AS est_premier_passage_jour
				FROM w_HOSPITALISATION_SELECT
				LEFT JOIN w_PASSAGE ON HO_NUM = SEA_HONUM AND HO_SEANCE = SEA_SEANCE
				LEFT JOIN w_PASSAGE_ACTES ON HO_NUM = ACTE_HONUM AND
					w_PASSAGE.SEA_ID = ACTE_SEAID
				JOIN activite[PX].p_sejours ON w_HOSPITALISATION_SELECT.HO_NUMSEJ = p_sejours.no_sejour AND p_sejours.etat = ''
				WHERE RE_TYPE <> 'H' AND sejour_a_creer = '1' 
				GROUP BY 1,2,3,4,5,6
				ORDER BY 1,2,3,4
				;
				
				CREATE INDEX w_mouvements_externes_i1
					ON w_mouvements_externes
					USING btree
					(HO_NUMSEJ);
					
				SELECT base.cti_execute(
				'UPDATE w_mouvements_externes
				SET HO_HDEBS = w_mouvements_externes.HO_HDEBS + interval ''1 second''
				FROM
				(
				SELECT HO_NUMSEJ, HO_DDEBS, HO_HDEBS, MIN(ACTE_KEY) AS ACTE_KEY_first
				FROM w_mouvements_externes
				GROUP BY 1,2,3
				HAVING count(*) > 1
				) subview
				WHERE w_mouvements_externes.HO_NUMSEJ = subview.HO_NUMSEJ AND
					w_mouvements_externes.HO_DDEBS = subview.HO_DDEBS AND
					w_mouvements_externes.HO_HDEBS = subview.HO_HDEBS AND
					w_mouvements_externes.ACTE_KEY <> subview.ACTE_KEY_first
				',100)
				;
				
				UPDATE w_mouvements_externes
				SET est_premier_passage_jour = '0'
				FROM 
				(
					SELECT HO_NUMSEJ, HO_DDEBS, (MIN(ARRAY[HO_HDEBS::text,ACTE_KEY::text]))[2]::text AS ACTE_KEY_first
					FROM w_mouvements_externes
					GROUP BY 1,2
					HAVING COUNT(*) > 1
				) subview
				WHERE w_mouvements_externes.HO_NUMSEJ = subview.HO_NUMSEJ AND
					w_mouvements_externes.HO_DDEBS = subview.HO_DDEBS AND
					w_mouvements_externes.ACTE_KEY <> subview.ACTE_KEY_first
				;



				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
				SELECT lieu_service_facturation_code_original, 
					lieu_activite_code_original, 
					lieu_etage_code_original, 
					lieu_lit_code_original,
					lieu_unite_medicale_code_original,
					lieu_unite_fonctionnelle_code_original
				FROM w_mouvements_externes
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = lieu_service_facturation_code_original AND
						code_original_2 = lieu_activite_code_original AND
						code_original_3 = lieu_etage_code_original AND
						code_original_4 = lieu_lit_code_original AND
						code_original_5 = lieu_unite_medicale_code_original AND
						code_original_6 = lieu_unite_fonctionnelle_code_original
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5,6;

				

				UPDATE activite[PX].t_lieux SET
					service_facturation_id = COALESCE(t_services_facturation.oid,0),
					mode_traitement_id = COALESCE(t_services_facturation.mode_traitement_id,0)
				FROM
					activite[PX].t_services_facturation 
				WHERE code_original_1 = t_services_facturation.code_original AND
					(t_lieux.service_facturation_id <> COALESCE(t_services_facturation.oid,0) OR
						t_lieux.mode_traitement_id <> COALESCE(t_services_facturation.mode_traitement_id,0)
					)
					;

				UPDATE activite[PX].t_lieux SET
					activite_id = COALESCE(t_activites.oid,0)
				FROM
					activite[PX].t_activites
				WHERE code_original_2 = t_activites.code_original
					AND activite_id <> COALESCE(t_activites.oid,0);


				UPDATE activite[PX].t_lieux SET
					unite_fonctionnelle_id = COALESCE(t_unites_fonctionnelles.oid,0)
				FROM
					activite[PX].t_unites_fonctionnelles
				WHERE code_original_6 = t_unites_fonctionnelles.code_original
					AND unite_fonctionnelle_id <> COALESCE(t_unites_fonctionnelles.oid,0);

				UPDATE activite[PX].t_lieux SET
					unite_medicale_id = COALESCE(t_unites_medicales.oid,0)
				FROM
					activite[PX].t_unites_medicales
				WHERE code_original_5 = t_unites_medicales.code_original
					AND unite_medicale_id <> COALESCE(t_unites_medicales.oid,0);
				

				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM
					activite[PX].t_lits
				WHERE code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;

				UPDATE w_mouvements_externes SET
					lieu_id = t_lieux.oid,
					est_chambre_particuliere = CASE WHEN t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END
				FROM activite[PX].t_lieux
				JOIN activite[PX].t_lits ON lit_id = t_lits.oid
				WHERE 
					code_original_1 = lieu_service_facturation_code_original AND
					code_original_2 = lieu_activite_code_original AND
					code_original_3 = lieu_etage_code_original AND
					code_original_4 = lieu_lit_code_original AND
					code_original_5 = lieu_unite_medicale_code_original AND
					code_original_6 = lieu_unite_fonctionnelle_code_original AND
					(
						w_mouvements_externes.lieu_id <> t_lieux.oid OR 
						w_mouvements_externes.est_chambre_particuliere <> CASE WHEN t_lits.chambre_particuliere = 'O' THEN '1' ELSE '0' END
					)
				;
				
				DELETE FROM w_mouvements_sejour
				USING
				(
				SELECT no_sejour, date, heure_debut, min(CTID) AS keep_ctid
				FROM w_mouvements_sejour
				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
					w_mouvements_sejour.CTID <> keep_ctid
				;
				


				INSERT INTO w_mouvements_sejour
					(
					HO_NUM,
					no_sejour,
					sejour_id,
					sequence,
					date, 
					jour_semaine,
					is_weekend,
					heure_debut,
					heure_fin,
					nb_entrees_directes,
					nb_sorties_directes,
					est_jour_entree,
					est_jour_sortie,
					est_jour_hospitalisation,
					nb_ambulatoires,
					nb_externes,
					nb_passage_externe,
					nb_urgences,
					nb_seances,

					nb_entrees_mutation_service,
					nb_sorties_mutation_service,
					nb_entrees_mutation_etage,
					nb_sorties_mutation_etage,
					nb_entrees_mutation_activite,
					nb_sorties_mutation_activite,
					nb_entrees_mutation_unite_medicale,
					nb_sorties_mutation_unite_medicale,

					nb_jours_js_inclus,
					nb_jours_js_non_inclus,

					est_chambre_particuliere,
					nb_chambres_particulieres,

					nb_bebes,
					lieu_id,
					medecin_sejour_id,
					est_mouvement_previsionnel
					)
				SELECT 
					w_mouvements_externes.HO_NUM,
					w_mouvements_externes.HO_NUMSEJ AS no_sejour,
					p_sejours.oid AS sejour_id,
					0::numeric,
					p_calendrier.date, 
					p_calendrier.jour_semaine,
					p_calendrier.is_weekend,
					CASE WHEN p_calendrier.date = HO_DDEBS THEN to_char(HO_HDEBS,'HH24MISS')::numeric ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date = HO_DFINS THEN to_char(HO_HFINS,'HH24MISS')::numeric ELSE 240000 END AS heure_fin,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN p_calendrier.date = HO_DFINS AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN p_calendrier.date = HO_DFINS AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
					CASE WHEN p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '3' AND est_premier_passage_jour = '1' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_passage_externe,
					CASE WHEN '1' <> '1' AND p_calendrier.date = HO_DDEBS THEN 1 ELSE 0 END AS nb_urgences,
					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '5' THEN 1 ELSE 0 END AS nb_seances,

					0 AS nb_entrees_mutation_service,
					0 AS nb_sorties_mutation_service,
					0 AS nb_entrees_mutation_etage,
					0 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' THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND p_calendrier.date <> HO_DFINS THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					'0'::text AS est_chambre_particuliere,
					0::numeric AS nb_chambres_particulieres,

					CASE WHEN p_calendrier.date = HO_DDEBS AND p_sejours.type_sejour = '6' THEN 1 ELSE 0 END AS nb_bebes,

					w_mouvements_externes.lieu_id AS lieu_id,

					w_mouvements_externes.medecin_sejour_id as medecin_sejour_id,
					
					CASE WHEN p_sejours.code_prevu = '1' OR p_calendrier.date > date(now_cerner) THEN '1' ELSE '0' END AS est_mouvement_previsionnel
				FROM w_mouvements_externes
					JOIN w_PERIODE ON 1=1
					JOIN activite[PX].p_sejours ON w_mouvements_externes.HO_NUMSEJ = p_sejours.no_sejour AND p_sejours.etat = ''
					JOIN base.p_calendrier ON (p_calendrier.date BETWEEN HO_DDEBS AND HO_DFINS AND p_calendrier.date <= now() + interval '1 month' )
				ORDER BY w_mouvements_externes.HO_NUMSEJ, p_calendrier.date;



				-- Séances
				
				DROP TABLE IF EXISTS w_MOUV_HOSPI_seances;
				CREATE TEMP TABLE w_MOUV_HOSPI_seances AS
				SELECT HO_NUMSEJ, date(mh_ddeb) AS date_seance, to_char(MH_HDEB,'HH24MISS')::numeric AS heure_seance
				FROM w_HOSPITALISATION_SELECT
				JOIN w_MOUV_HOSPI_source ON w_HOSPITALISATION_SELECT.HO_NUM = w_MOUV_HOSPI_source.MH_HONUM
				JOIN activite.t_divers On t_divers.code = 'CERNER_RAISONSEANCE'
				WHERE MH_RSCODENT = ANY(string_to_array(t_divers.valeur,',')) 
				;

				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM w_MOUV_HOSPI_seances
				WHERE w_mouvements_sejour.no_sejour = HO_NUMSEJ AND
					w_mouvements_sejour.date = date_seance AND
					heure_seance BETWEEN heure_debut AND heure_fin
				;
				
				UPDATE activite[PX].p_mouvements_sejour
				SET nb_seances = 1, nb_ambulatoires = 0
				FROM activite[PX].p_sejours
					JOIN base.t_ghs  ON ghs_id = t_ghs.oid
				WHERE p_mouvements_sejour.no_sejour = p_sejours.no_sejour
					AND trim(t_ghs.code) IN (9606,9616,9613,9614)
					AND (p_mouvements_sejour.nb_seances = 0 OR nb_ambulatoires = 1)
				;
				
				UPDATE activite[PX].p_sejours
				SET type_sejour = 5
				FROM base.t_ghs
				WHERE ghs_id = t_ghs.oid 
					AND trim(t_ghs.code) IN (9606,9616,9613,9614)
					AND type_sejour != 5
				;
			
				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_passage_externe = 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;

				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_5');

				



				INSERT INTO activite[PX].p_mouvements_sejour(
							no_sejour, date, nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_passage_externe, 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,est_mouvement_previsionnel, jour_semaine, is_weekend)
				SELECT no_sejour, date,nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_passage_externe, 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,est_mouvement_previsionnel, jour_semaine, is_weekend
				FROM w_mouvements_sejour 
				ORDER BY no_sejour, sequence;



				
				
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_5');
				
				
				
				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 IS DISTINCT FROM p_mouvements_sejour.lieu_id);
						
				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 type_sejour = '5'
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
				WHERE lieu_sortie_id = t_lieux.oid AND
					t_services_facturation.type_sejour <> '0sauf5' AND
					p_sejours.type_sejour <> '5' AND 
					p_sejours.type_sejour <> '1' 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
					)

				;
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lien PMSI">

			<sqlcmd><![CDATA[
			
					SELECT activite[PX].cti_reorganize_sejour_pmsi();
					
					UPDATE activite[PX].p_sejours SET
						ghs_id = subview.ghs_id,
						ghm_id = subview.ghm_id
					FROM
					(
						SELECT sejour_id, 
							 t_ghs_pmsi.code,
							 t_ghm_pmsi.code,
							 COALESCE(t_ghs.oid,0) AS ghs_id,
							 COALESCE(t_ghm.oid,0) AS ghm_id
						FROM activite[PX].p_sejour_pmsi
						JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
						LEFT JOIN pmsi.t_ghs t_ghs_pmsi ON t_ghs_pmsi.oid = p_rss.ghs_id
						LEFT JOIN pmsi.t_ghm t_ghm_pmsi ON t_ghm_pmsi.oid = p_rss.ghm_id
						LEFT JOIN base.t_ghs ON t_ghs_pmsi.code = t_ghs.code AND t_ghm_pmsi.code NOT LIKE '99%'
						LEFT JOIN base.t_ghm ON t_ghm_pmsi.code = t_ghm.code AND t_ghm_pmsi.code NOT LIKE '99%'
					) subview
					WHERE p_sejours.oid = subview.sejour_id AND
						(
						p_sejours.ghs_id <> subview.ghs_id OR
						p_sejours.ghm_id <> subview.ghm_id
						);

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

	<NODE name="FACTURE" label="RECUPERATION DES FACTURES">
	
	
	
		<NODE label="Entêtes">
			<sqlcmd><![CDATA[
			
			
				DROP TABLE IF EXISTS w_FACTURE;
				CREATE TEMP TABLE w_FACTURE AS 
				SELECT FAC_NUM::text AS FAC_NUM_CTI,
					FAC_NUM,
					FAC_HONUM,
					HO_MANUMDOS AS FAC_MANUMDOS,
					0::numeric AS FAC_ADCPT_BG,
					''::text AS FAC_PYTYPE_CTI_BG,
					''::text AS FAC_PYCODE_CTI_BG,
					FAC_ADCPT AS FAC_ADCPT_HB,
					''::text AS FAC_PYTYPE_CTI_HB,
					''::text AS FAC_PYCODE_CTI_HB,
					FAC_DATE,
					FAC_EXER,
					FAC_DATE AS FAC_DATE_VENT,
					NULL::date AS FAC_DDEB,
					NULL::date AS FAC_DFIN,
					FAC_MONT,
					0::numeric AS FAC_MONT_0,
					0::numeric AS FAC_MONT_1,
					0::numeric AS FAC_MONT_2,
					0::numeric AS FAC_MONT_BG_1,
					FAC_REGL,
					0::numeric AS FAC_REGL_0,
					0::numeric AS FAC_REGL_1,
					0::numeric AS FAC_REGL_2,
					FAC_ETAT,
					FAC_COMM,
					FAC_INV,
					FAC_ETAB,
					FAC_BORD,
					FAC_DATE_LOT,
					''::text AS FAC_SEANCE,
					NULL::text[] AS FAC_SEANCE_array,
					1::numeric AS sequence_index
				FROM prod_cerner.FACTURE
				LEFT JOIN prod_cerner.HOSPITALISATION ON FAC_HONUM = HO_NUM
				WHERE FAC_HONUM IN (SELECT HO_NUM FROM w_HOSPITALISATION_SELECT);
				
				

				UPDATE w_FACTURE
				SET FAC_MANUMDOS = w_HOSPITALISATION_SELECT.HO_MANUMDOS
				FROM w_HOSPITALISATION_SELECT
				WHERE FAC_HONUM = HO_NUM AND
					FAC_MANUMDOS IS NULL
				;
				
				-- date de vente selon exercice précédent
				UPDATE w_FACTURE
				SET FAC_DATE_VENT = to_date(FAC_EXER||'-12-31','YYYY-MM-DD')
				WHERE date_part('year',FAC_DATE) <> FAC_EXER
				;

				ANALYSE w_FACTURE;

				CREATE INDEX w_FACTURE_i1
					ON w_FACTURE
					USING btree
					(FAC_NUM);

				CREATE INDEX w_FACTURE_i2
					ON w_FACTURE
					USING btree
					(FAC_HONUM);

				CREATE INDEX w_FACTURE_i_FAC_SEANCE
					ON w_FACTURE
					USING btree
					(FAC_SEANCE);

				CREATE INDEX w_FACTURE_FAC_MANUMDOS
					ON w_FACTURE
					USING btree
					(FAC_MANUMDOS);


				UPDATE w_FACTURE SET
					FAC_PYTYPE_CTI_HB = 
						CASE 
						WHEN AD_TYP = 'T' AND AD_PYTYPE IN ('1','2') THEN '1' 
						WHEN AD_TYP = 'T' AND AD_PYTYPE NOT IN ('1','2') THEN '2' 
						ELSE '0' END,
					FAC_PYCODE_CTI_HB = 
						CASE 
						WHEN AD_TYP = 'T' THEN ('C'||AD_PYTYPE||AD_PYCODE)
						ELSE '*PATIENT' END
				FROM prod_cerner.ADRESSE
				WHERE FAC_MANUMDOS = AD_MANUMDOS AND
					FAC_ADCPT_HB = AD_CPT
				;

				

				DROP TABLE IF EXISTS w_FACTURE_DET;
				CREATE TEMP TABLE w_FACTURE_DET AS
				SELECT
					'FAD'::text AS FAD_SOURCE,
					FAD_NUM,
					FAD_UFCODE,
					FAD_TYPE,
					FAD_DEB,
					FAD_FIN,
					FAD_HEU,
					FAD_INCODE,
					CASE 
						WHEN trim(FAD_CCAMREGR) <> '' THEN trim(FAD_CCAMREGR) 
						ELSE trim(FAD_CTCODE) END AS FAD_CTCODE,
					CASE 
						WHEN trim(FAD_CCAMREGR) <> '' THEN trim(FAD_CCAMREGR) 
						WHEN trim(FAD_CTNB2) <> '' THEN trim(FAD_CTNB2) 
						ELSE trim(FAD_CTCODE) END AS FAD_CTNB2,
					CASE 
						WHEN trim(FAD_CCAMREGR) <> '' THEN trim(FAD_CCAMREGR)
						ELSE '' END AS FAD_CTACTE,
					FAD_UFEXE,
					FAD_INEXE,
					FAD_COMPTE,
					FAD_SEANCE,
					FAC_ADCPT_HB AS FAD_CPT,
					FAD_TAUDG,
					FAD_PUFAC,
					CASE WHEN FAD_MON < 0 AND FAD_NBR > 0 THEN 0 - FAD_NBR ELSE FAD_NBR END AS FAD_NBR,
					FAD_MON,
					CASE WHEN FAC_PYTYPE_CTI_HB NOT IN ('1','2') THEN FAD_MON ELSE 0 END AS FAD_MON_0,
					CASE WHEN FAC_PYTYPE_CTI_HB = '1' THEN FAD_MON ELSE 0 END AS FAD_MON_1,
					CASE WHEN FAC_PYTYPE_CTI_HB = '2' THEN FAD_MON ELSE 0 END AS FAD_MON_2,
					0::numeric AS FAD_MON_BG_1
				FROM prod_cerner.FACTURE_DET
				JOIN w_FACTURE ON FAC_NUM = FAD_NUM;


				INSERT INTO w_FACTURE_DET
				SELECT
					'FDG'::text AS FAD_SOURCE,
					FDG_NUM,
					FDG_UFCODE,
					FDG_TYPE,
					FDG_DEB,
					FDG_FIN,
					FDG_DEB AS FDG_HEU,
					''::text AS FDG_INCODE,
					trim(FDG_CTCODE) AS FDG_CTCODE,
					trim(FDG_CTCODE) AS FDG_CTNB2,
					''::text AS FDG_CTACTE,
					''::text AS FDG_UFEXE,
					''::text AS FDG_INEXE,
					trim(FDG_COMPTE) AS FGD_COMPTE,
					''::text AS FDG_SEANCE,
					FDG_CPT,
					FDG_TAUDG,
					FDG_PU AS FDG_PUFAC,
					FDG_NBR,
					FDG_MON,
					0::numeric AS FAD_MON_0,
					0::numeric AS FAD_MON_1,
					0::numeric AS FAD_MON_2,
					FDG_MON AS FAD_MON_BG_1
				FROM prod_cerner.FACTURE_DG
				JOIN w_FACTURE ON FAC_NUM = FDG_NUM
				;
				
				UPDATE w_FACTURE_DET
				SET FAD_CTNB2 = CT_LET
				FROM prod_cerner.CODE_TARIF
				WHERE FAD_CTCODE = CT_CODE AND
					FAD_CTNB2 <> CT_LET AND
					CT_LET <> ''
				;

				ANALYSE w_FACTURE_DET;

				CREATE INDEX w_FACTURE_DET_i_FAD_NUM
					ON w_FACTURE_DET
					USING btree
					(FAD_NUM);

				


				DROP TABLE IF EXISTS w_FACTURE_DET_seance;
				CREATE TEMP TABLE w_FACTURE_DET_seance AS
				SELECT 	
					FAD_NUM,
					base.cti_array_accum(DISTINCT trim(FAD_SEANCE)) AS FAD_SEANCE_array
				FROM w_FACTURE_DET
				WHERE FAD_SEANCE <> ''
				GROUP BY 1
				;

				ANALYSE w_FACTURE_DET_seance;

				CREATE INDEX w_FACTURE_DET_seance_i1
					ON w_FACTURE_DET_seance
					USING btree
					(FAD_NUM);

					
				UPDATE w_FACTURE
				SET FAC_SEANCE_array = FAD_SEANCE_array, FAC_SEANCE = COALESCE(FAD_SEANCE_array[1],'')
				FROM w_FACTURE_DET_seance
				WHERE w_FACTURE.FAC_NUM = w_FACTURE_DET_seance.FAD_NUM
				;

				SELECT base.cti_execute('
				INSERT INTO w_FACTURE
				SELECT
					FAC_NUM_CTI,
					FAC_NUM,
					FAC_HONUM,
					FAC_MANUMDOS,
					FAC_ADCPT_BG,
					FAC_PYTYPE_CTI_BG,
					FAC_PYCODE_CTI_BG,
					FAC_ADCPT_HB,
					FAC_PYTYPE_CTI_HB,
					FAC_PYCODE_CTI_HB,
					FAC_DATE,
					FAC_EXER,
					FAC_DATE_VENT,
					FAC_DDEB,
					FAC_DFIN,
					FAC_MONT,
					FAC_MONT_0,
					FAC_MONT_1,
					FAC_MONT_2,
					FAC_MONT_BG_1,
					FAC_REGL,
					FAC_REGL_0,
					FAC_REGL_1,
					FAC_REGL_2,
					FAC_ETAT,
					FAC_COMM,
					FAC_INV,
					FAC_ETAB,
					FAC_BORD,
					FAC_DATE_LOT,
					FAC_SEANCE_array[subview.sequence_index] AS FAC_SEANCE,
					NULL::text[] AS FAC_SEANCE_array,
					subview.sequence_index
				FROM w_FACTURE
				JOIN (SELECT MAX(sequence_index)+1 AS sequence_index FROM w_FACTURE) subview ON 1=1
				WHERE FAC_SEANCE_array[subview.sequence_index] IS NOT NULL
				',50)
				;

				



				
				DROP TABLE IF EXISTS w_FACTURE_DET_fac;
				CREATE TEMP TABLE w_FACTURE_DET_fac AS
				SELECT 	
					FAD_NUM,
					trim(FAD_SEANCE) AS FAD_SEANCE,
					SUM(FAD_MON) AS FAD_MON,
					SUM(FAD_MON_0) AS FAD_MON_0,
					SUM(FAD_MON_1) AS FAD_MON_1,
					SUM(FAD_MON_2) AS FAD_MON_2,
					SUM(FAD_MON_BG_1) AS FAD_MON_BG_1,
					date(MIN(FAD_DEB)) AS FAD_DDEB,
					date(MAX(FAD_FIN)) AS FAD_DFIN,
					MAX(CASE WHEN FAD_SOURCE = 'FDG' THEN FAD_CPT ELSE 0 END) AS FAD_ADCPT_BG
				FROM w_FACTURE_DET
				GROUP BY 1,2
				;

				ANALYSE w_FACTURE_DET_fac;

				CREATE INDEX w_FACTURE_DET_fac_i1
					ON w_FACTURE_DET_fac
					USING btree
					(FAD_NUM);


					
				UPDATE w_FACTURE SET
					FAC_ADCPT_BG = FAD_ADCPT_BG,
					FAC_MONT = w_FACTURE_DET_fac.FAD_MON,
					FAC_MONT_0 = w_FACTURE_DET_fac.FAD_MON_0,
					FAC_MONT_1 = w_FACTURE_DET_fac.FAD_MON_1,
					FAC_MONT_2 = w_FACTURE_DET_fac.FAD_MON_2,
					FAC_MONT_BG_1 = w_FACTURE_DET_fac.FAD_MON_BG_1,
					FAC_DDEB = w_FACTURE_DET_fac.FAD_DDEB,
					FAC_DFIN = w_FACTURE_DET_fac.FAD_DFIN
				FROM w_FACTURE_DET_fac
				WHERE w_FACTURE.FAC_NUM = w_FACTURE_DET_fac.FAD_NUM AND
					w_FACTURE.FAC_SEANCE = w_FACTURE_DET_fac.FAD_SEANCE
					
				;

				
				

				UPDATE w_FACTURE SET
					FAC_PYTYPE_CTI_BG = 
						CASE 
						WHEN AD_TYP = 'T' AND AD_PYTYPE IN ('1','2') THEN '1' 
						WHEN AD_TYP = 'T' AND AD_PYTYPE NOT IN ('1','2') THEN '2' 
						ELSE '0' END,
					FAC_PYCODE_CTI_BG = 
						CASE 
						WHEN AD_TYP = 'T' THEN ('C'||AD_PYTYPE||AD_PYCODE)
						ELSE '*PATIENT' END
				FROM prod_cerner.ADRESSE
				WHERE FAC_MANUMDOS = AD_MANUMDOS AND
					FAC_ADCPT_BG = AD_CPT
				;

				


				UPDATE w_FACTURE
				SET FAC_NUM_CTI = FAC_NUM || '.' || FAC_SEANCE
				WHERE FAC_SEANCE <> '' AND
					FAC_NUM IN
					(
						SELECT FAC_NUM
						FROM w_FACTURE
						GROUP BY 1
						HAVING COUNT(*) > 1
					)
				;
				
				
				-- Récupération des règlements et affectation aux factures
				
				
				DROP TABLE IF EXISTS w_MOUV_COMPTA_REG;
				CREATE TEMP TABLE w_MOUV_COMPTA_REG AS
				SELECT MC_EXER,
					MC_NUM,
					MC_NUMT,
					MC_LIGNE,
					MC_COMPTE,
					CASE 
					WHEN AD_TYP IS NULL THEN ''
					WHEN AD_TYP = 'T' AND AD_PYTYPE IN ('1','2') THEN '1' 
					WHEN AD_TYP = 'T' AND AD_PYTYPE NOT IN ('1','2') THEN '2' 
					ELSE '0' END AS MC_PYTYPE_CTI_HB,
					MC_DATECR,
					MC_HONUM,
					MC_MANUMDOS,
					''::text AS MC_SEANCE,
					MC_NUMFAC_LET,
					MC_TYPE,
					CASE WHEN MC_SENS = 'C' THEN MC_MON ELSE 0-MC_MON END AS MC_MON_REG,
					MC_EXER*100000000000000+MC_NUM*10000000+MC_LIGNE AS MC_KEY,
					''::text AS MC_FACNUM_CTI,
					'0'::text AS MC_OK
				FROM prod_cerner.MOUV_COMPTA
				LEFT JOIN prod_cerner.FACTURE ON MC_NUMFAC_LET = FAC_NUM
				LEFT JOIN prod_cerner.ADRESSE ON MC_MANUMDOS = AD_MANUMDOS AND
					FAC_ADCPT = AD_CPT
				WHERE MC_JRN <> 'JV' AND
					MC_HONUM <> 0 AND
					(MC_COMPTE LIKE '411%' OR MC_COMPTE LIKE '412%' OR MC_COMPTE LIKE '413%' OR MC_COMPTE LIKE '414%' OR MC_COMPTE LIKE '452%' OR MC_COMPTE LIKE '467%') AND
					MC_HONUM IN (SELECT HO_NUM FROM w_HOSPITALISATION_SELECT)
				;
				
				UPDATE w_MOUV_COMPTA_REG
				SET MC_PYTYPE_CTI_HB = subview.MC_PYTYPE_CTI_HB
				FROM
				(
					SELECT MC_COMPTE_racine,
						(MAX(ARRAY[to_char(nb,'FM000000000000'),MC_PYTYPE_CTI_HB]))[2] AS MC_PYTYPE_CTI_HB
					FROM 
					(
						SELECT 
							substr(MC_COMPTE,1,4) AS MC_COMPTE_racine, MC_PYTYPE_CTI_HB, count(*) AS nb
						FROM w_MOUV_COMPTA_REG
						WHERE MC_PYTYPE_CTI_HB <> ''
						GROUP BY 1,2
						ORDER BY 1,2
					) subview
					GROUP BY 1
				) subview
				WHERE substr(w_MOUV_COMPTA_REG.MC_COMPTE,1,4) = MC_COMPTE_racine AND
					w_MOUV_COMPTA_REG.MC_PYTYPE_CTI_HB = ''
				;

				-- Ne pas tenir compte des règlements qui s'annulent
				DELETE FROM w_MOUV_COMPTA_REG
				USING
				(
				SELECT MC_HONUM, MC_NUMT, MC_DATECR, SUM(MC_MON_REG)
				FROM w_MOUV_COMPTA_REG
				GROUP BY 1,2,3
				HAVING SUM(MC_MON_REG) = 0
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_HONUM = subview.MC_HONUM AND
					w_MOUV_COMPTA_REG.MC_NUMT = subview.MC_NUMT AND
					w_MOUV_COMPTA_REG.MC_DATECR = subview.MC_DATECR
				;


				-- Ne pas tenir compte des règlements qui s'annulent (n° facture)
				DELETE FROM w_MOUV_COMPTA_REG
				USING
				(
				SELECT MC_HONUM, MC_NUMFAC_LET, MC_DATECR, SUM(MC_MON_REG)
				FROM w_MOUV_COMPTA_REG
				GROUP BY 1,2,3
				HAVING SUM(MC_MON_REG) = 0
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_HONUM = subview.MC_HONUM AND
					w_MOUV_COMPTA_REG.MC_NUMFAC_LET = subview.MC_NUMFAC_LET AND
					w_MOUV_COMPTA_REG.MC_DATECR = subview.MC_DATECR
				;

				
				-- Lettrage des factures. Cas d'une seule facture réglée par séjour
				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.MC_NUMFAC_LET
				FROM
				(
				SELECT MC_HONUM, MAX(MC_NUMFAC_LET) AS MC_NUMFAC_LET
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMT <> 0
				GROUP BY 1
				HAVING count(DISTINCT CASE WHEN MC_NUMFAC_LET > 0 THEN MC_NUMFAC_LET ELSE NULL END) = 1 AND
					MAX(MC_NUMFAC_LET) > 0 AND MIN(MC_NUMFAC_LET) = 0
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_HONUM = subview.MC_HONUM AND
					w_MOUV_COMPTA_REG.MC_NUMFAC_LET = 0
				;

				-- Lettrage des factures. Cas d'une seule facture réglée par pièce
				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.MC_NUMFAC_LET
				FROM
				(
				SELECT MC_HONUM, MC_NUMT, MAX(MC_NUMFAC_LET) AS MC_NUMFAC_LET
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMT <> 0
				GROUP BY 1,2
				HAVING count(DISTINCT CASE WHEN MC_NUMFAC_LET > 0 THEN MC_NUMFAC_LET ELSE NULL END) = 1 AND
					MAX(MC_NUMFAC_LET) > 0 AND MIN(MC_NUMFAC_LET) = 0
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_HONUM = subview.MC_HONUM AND
					w_MOUV_COMPTA_REG.MC_NUMFAC_LET = 0
				;

				
				-- Lettrage des factures. Cas d'une facture seule pour un montant réglé (plusieurs passages)
				DROP TABLE IF EXISTS w_FACTURE_LET;
				CREATE TEMP TABLE w_FACTURE_LET (
					FAC_HONUM numeric,
					FAC_REGL numeric,
					FAC_DATE date,
					FAC_NUM numeric,
					FAC_nb numeric
					)
				;

				DROP TABLE IF EXISTS w_MOUV_COMPTA_LET;
				CREATE TEMP TABLE w_MOUV_COMPTA_LET (
					MC_HONUM numeric,
					MC_MON_REG numeric,
					MC_DATECR date,
					MC_nb numeric,
					MC_KEY numeric
				)
				;


				SELECT base.cti_execute(
				'TRUNCATE w_FACTURE_LET
				.,
				INSERT INTO w_FACTURE_LET 
				SELECT FAC_HONUM, FAC_REGL, MIN(date(FAC_DATE)) AS FAC_DATE, (MIN(ARRAY[FAC_DATE::text,FAC_NUM::text]))[2]::numeric AS FAC_NUM, count(*) AS FAC_nb
				FROM prod_cerner.FACTURE
				WHERE FAC_INV = 0 AND
					FAC_HONUM IN
					(SELECT MC_HONUM FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET = 0) AND
					FAC_NUM NOT IN (SELECT MC_NUMFAC_LET FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET <> 0)
				GROUP BY 1,2
				.,
				
				TRUNCATE w_MOUV_COMPTA_LET
				.,
				INSERT INTO w_MOUV_COMPTA_LET 
				SELECT MC_HONUM, MC_MON_REG, DATE(min(MC_DATECR)) AS MC_DATECR, count(*) AS MC_nb,
					MIN(MC_KEY) AS MC_KEY
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMFAC_LET = 0
				GROUP BY 1,2
				.,

				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.FAC_NUM
				FROM 
				(
					SELECT w_MOUV_COMPTA_LET.MC_KEY, w_FACTURE_LET.FAC_NUM
					FROM w_MOUV_COMPTA_LET
					JOIN w_FACTURE_LET ON w_MOUV_COMPTA_LET.MC_HONUM = w_FACTURE_LET.FAC_HONUM AND
						w_MOUV_COMPTA_LET.MC_MON_REG = w_FACTURE_LET.FAC_REGL AND
						(FAC_DATE <= MC_DATECR OR FAC_nb = MC_nb)
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_KEY = subview.MC_KEY
				',100)
				;


				DROP TABLE IF EXISTS w_MOUV_COMPTA_LET;
				CREATE TEMP TABLE w_MOUV_COMPTA_LET AS
				SELECT MC_HONUM, MC_NUMFAC_LET, SUM(MC_MON_REG) AS MC_MON_REG
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMFAC_LET <> 0
				GROUP BY 1,2
				;


				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.MC_NUMFAC_LET
				FROM
				(
				SELECT w_MOUV_COMPTA_LET.MC_HONUM, w_MOUV_COMPTA_LET.MC_NUMFAC_LET, FAC_REGL, 
					w_MOUV_COMPTA_LET.MC_MON_REG, 
					w_MOUV_COMPTA_REG.MC_MON_REG,
					w_MOUV_COMPTA_REG.MC_KEY
				FROM w_MOUV_COMPTA_LET
				JOIN prod_cerner.FACTURE ON FAC_HONUM = MC_HONUM AND
					FAC_NUM = MC_NUMFAC_LET
				JOIN w_MOUV_COMPTA_REG ON w_MOUV_COMPTA_REG.MC_HONUM = w_MOUV_COMPTA_LET.MC_HONUM AND w_MOUV_COMPTA_REG.MC_NUMFAC_LET = 0
				WHERE FAC_REGL <> w_MOUV_COMPTA_LET.MC_MON_REG AND
					w_MOUV_COMPTA_LET.MC_MON_REG + w_MOUV_COMPTA_REG.MC_MON_REG = FAC_REGL
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_KEY = subview.MC_KEY
				;


				-- Lettrage des factures. Cas d'une facture seule pour un montant réglé (plusieurs passages)
				DROP TABLE IF EXISTS w_FACTURE_LET;
				CREATE TEMP TABLE w_FACTURE_LET (
					FAC_HONUM numeric,
					FAC_REGL numeric,
					FAC_DATE date,
					FAC_NUM numeric,
					FAC_nb numeric
					)
				;

				DROP TABLE IF EXISTS w_MOUV_COMPTA_LET;
				CREATE TEMP TABLE w_MOUV_COMPTA_LET (
					MC_HONUM numeric,
					MC_MON_REG numeric,
					MC_DATECR date,
					MC_nb numeric,
					MC_KEY numeric
				)
				;


				SELECT base.cti_execute(
				'TRUNCATE w_FACTURE_LET
				.,
				INSERT INTO w_FACTURE_LET 
				SELECT FAC_HONUM, FAC_REGL, MIN(date(FAC_DATE)) AS FAC_DATE, (MIN(ARRAY[FAC_DATE::text,FAC_NUM::text]))[2]::numeric AS FAC_NUM, count(*) AS FAC_nb
				FROM prod_cerner.FACTURE
				WHERE FAC_INV = 0 AND
					FAC_HONUM IN
					(SELECT MC_HONUM FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET = 0) AND
					FAC_NUM NOT IN (SELECT MC_NUMFAC_LET FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET <> 0)
				GROUP BY 1,2
				.,
				
				TRUNCATE w_MOUV_COMPTA_LET
				.,
				INSERT INTO w_MOUV_COMPTA_LET 
				SELECT MC_HONUM, MC_MON_REG, DATE(min(MC_DATECR)) AS MC_DATECR, count(*) AS MC_nb,
					MIN(MC_KEY) AS MC_KEY
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMFAC_LET = 0
				GROUP BY 1,2
				.,

				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.FAC_NUM
				FROM 
				(
					SELECT w_MOUV_COMPTA_LET.MC_KEY, w_FACTURE_LET.FAC_NUM
					FROM w_MOUV_COMPTA_LET
					JOIN w_FACTURE_LET ON w_MOUV_COMPTA_LET.MC_HONUM = w_FACTURE_LET.FAC_HONUM AND
						w_MOUV_COMPTA_LET.MC_MON_REG = w_FACTURE_LET.FAC_REGL 
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_KEY = subview.MC_KEY
				',100)
				;


				SELECT base.cti_execute(
				'TRUNCATE w_FACTURE_LET
				.,
				INSERT INTO w_FACTURE_LET 
				SELECT FAC_HONUM, FAC_MONT AS FAC_REGL, MIN(date(FAC_DATE)) AS FAC_DATE, (MIN(ARRAY[FAC_DATE::text,FAC_NUM::text]))[2]::numeric AS FAC_NUM, count(*) AS FAC_nb
				FROM prod_cerner.FACTURE
				WHERE FAC_INV = 0 AND
					FAC_REGL = 0 AND
					FAC_HONUM IN
					(SELECT MC_HONUM FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET = 0) AND
					FAC_NUM NOT IN (SELECT MC_NUMFAC_LET FROM w_MOUV_COMPTA_REG WHERE MC_NUMFAC_LET <> 0)
				GROUP BY 1,2
				.,
				
				TRUNCATE w_MOUV_COMPTA_LET
				.,
				INSERT INTO w_MOUV_COMPTA_LET 
				SELECT MC_HONUM, MC_MON_REG, DATE(min(MC_DATECR)) AS MC_DATECR, count(*) AS MC_nb,
					MIN(MC_KEY) AS MC_KEY
				FROM w_MOUV_COMPTA_REG
				WHERE MC_NUMFAC_LET = 0
				GROUP BY 1,2
				.,

				UPDATE w_MOUV_COMPTA_REG
				SET MC_NUMFAC_LET = subview.FAC_NUM
				FROM 
				(
					SELECT w_MOUV_COMPTA_LET.MC_KEY, w_FACTURE_LET.FAC_NUM
					FROM w_MOUV_COMPTA_LET
					JOIN w_FACTURE_LET ON w_MOUV_COMPTA_LET.MC_HONUM = w_FACTURE_LET.FAC_HONUM AND
						w_MOUV_COMPTA_LET.MC_MON_REG = w_FACTURE_LET.FAC_REGL AND
						(FAC_DATE <= MC_DATECR OR FAC_nb = MC_nb)
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_KEY = subview.MC_KEY
				',100)
				;

				
				-- Lettrage des factures. Affectation facture CTI (facture + passage) mono facture
				DROP TABLE IF EXISTS w_FACTURE_reg;
				CREATE TEMP TABLE w_FACTURE_reg AS
				SELECT FAC_NUM,
					COUNT(DISTINCT FAC_NUM_CTI),
					COUNT(DISTINCT FAC_NUM_CTI) AS nb,
					(MAX(ARRAY[FAC_DATE::text,FAC_NUM_CTI]))[2] AS FAC_NUM_CTI_LAST,
					SUM(FAC_MONT_0 + FAC_MONT_1 + FAC_MONT_2) AS FAC_MONT_HBG
				FROM w_FACTURE
				GROUP BY 1
				;


				UPDATE w_MOUV_COMPTA_REG
				SET MC_FACNUM_CTI = FAC_NUM_CTI_LAST, 
					MC_OK = '1'
				FROM w_FACTURE_reg
				WHERE w_MOUV_COMPTA_REG.MC_NUMFAC_LET = w_FACTURE_reg.FAC_NUM AND
					nb = 1
				;

				-- Lettrage des factures. Affectation facture CTI (facture + passage) plusieurs factures sur total identique
				INSERT INTO w_MOUV_COMPTA_REG
				SELECT 
					MC_EXER,
					MC_NUM,
					MC_NUMT,
					MC_LIGNE,
					MC_COMPTE,
					MC_PYTYPE_CTI_HB,
					MC_DATECR,
					MC_HONUM,
					MC_MANUMDOS,
					MC_SEANCE,
					MC_NUMFAC_LET,
					MC_TYPE,
					FAC_MONT_0 + FAC_MONT_1 + FAC_MONT_2 AS MC_MON_REG,
					MC_KEY,
					w_FACTURE.FAC_NUM_CTI AS MC_FACNUM_CTI,
					'1'::text AS MC_OK
				FROM w_MOUV_COMPTA_REG
				JOIN w_FACTURE_reg ON w_MOUV_COMPTA_REG.MC_NUMFAC_LET = w_FACTURE_reg.FAC_NUM
				JOIN w_FACTURE ON w_MOUV_COMPTA_REG.MC_NUMFAC_LET = w_FACTURE.FAC_NUM
				WHERE
					MC_OK = '0' AND
					nb > 1 AND
					MC_MON_REG = FAC_MONT_HBG
				;

				DELETE FROM w_MOUV_COMPTA_REG
				WHERE MC_OK = '0' AND
					MC_KEY IN (SELECT MC_KEY FROM w_MOUV_COMPTA_REG WHERE MC_OK = '1')
				;

				-- Lettrage des factures. Affectation facture CTI (facture + passage) plusieurs factures sur total identique inversé (remboursement)
				INSERT INTO w_MOUV_COMPTA_REG
				SELECT 
					MC_EXER,
					MC_NUM,
					MC_NUMT,
					MC_LIGNE,
					MC_COMPTE,
					MC_PYTYPE_CTI_HB,
					MC_DATECR,
					MC_HONUM,
					MC_MANUMDOS,
					MC_SEANCE,
					MC_NUMFAC_LET,
					MC_TYPE,
					0 - (FAC_MONT_0 + FAC_MONT_1 + FAC_MONT_2) AS MC_MON_REG,
					MC_KEY,
					w_FACTURE.FAC_NUM_CTI AS MC_FACNUM_CTI,
					'1'::text AS MC_OK
				FROM w_MOUV_COMPTA_REG
				JOIN w_FACTURE_reg ON w_MOUV_COMPTA_REG.MC_NUMFAC_LET = w_FACTURE_reg.FAC_NUM
				JOIN w_FACTURE ON w_MOUV_COMPTA_REG.MC_NUMFAC_LET = w_FACTURE.FAC_NUM
				WHERE
					MC_OK = '0' AND
					nb > 1 AND
					MC_MON_REG = 0-FAC_MONT_HBG
				;

				DELETE FROM w_MOUV_COMPTA_REG
				WHERE MC_OK = '0' AND
					MC_KEY IN (SELECT MC_KEY FROM w_MOUV_COMPTA_REG WHERE MC_OK = '1')
				;
				
				-- Création des factures fictives CTI sur règlements non lettrés
				UPDATE w_MOUV_COMPTA_REG
				SET MC_FACNUM_CTI = 
					CASE WHEN MC_NUMFAC_LET <> 0 THEN MC_NUMFAC_LET ELSE MC_HONUM END::text || '.' || 'RG', 
					MC_OK = '1'
				WHERE MC_OK = '0'
				;
				
				UPDATE w_MOUV_COMPTA_REG
				SET MC_SEANCE = subview.HO_SEANCE
				FROM
				(
					SELECT MC_KEY, MAX(w_HOSPITALISATION_SELECT_HONUM.HO_SEANCE) AS HO_SEANCE
					FROM w_MOUV_COMPTA_REG
					LEFT JOIN w_HOSPITALISATION_SELECT ON MC_HONUM = w_HOSPITALISATION_SELECT.HO_NUM AND
						MC_SEANCE = w_HOSPITALISATION_SELECT.HO_SEANCE
					JOIN w_HOSPITALISATION_SELECT w_HOSPITALISATION_SELECT_HONUM ON MC_HONUM = w_HOSPITALISATION_SELECT_HONUM.HO_NUM
					WHERE MC_FACNUM_CTI LIKE '%.RG' AND
						w_HOSPITALISATION_SELECT.HO_NUM IS NULL
					GROUP BY 1
				) subview
				WHERE w_MOUV_COMPTA_REG.MC_KEY = subview.MC_KEY
				;


				INSERT INTO w_FACTURE
				SELECT
					MC_FACNUM_CTI,
					MC_NUMFAC_LET AS FAC_NUM,
					MC_HONUM AS HONUM,
					COALESCE(HO_MANUMDOS,MC_MANUMDOS,0),
					0::numeric AS FAC_ADCPT_BG,
					'' AS FAC_PYTYPE_CTI_BG,
					'' AS FAC_PYCODE_CTI_BG,
					0::numeric AS FAC_ADCPT_HB,
					MAX(MC_PYTYPE_CTI_HB) AS FAC_PYTYPE_CTI_HB,
					'' AS FAC_PYCODE_CTI_HB,
					MIN(MC_DATECR) AS FAC_DATE,
					MIN(MC_EXER) AS FAC_EXER,
					MIN(MC_DATECR) AS FAC_DATE_VENT,
					MIN(HO_DDEB) AS FAC_DDEB,
					MAX(HO_DFIN) AS FAC_DFIN,
					0::numeric AS FAC_MONT,
					0::numeric AS FAC_MONT_0,
					0::numeric AS FAC_MONT_1,
					0::numeric AS FAC_MONT_2,
					0::numeric AS FAC_MONT_BG_1,
					0::numeric AS FAC_REGL,
					0::numeric AS FAC_REGL_0,
					0::numeric AS FAC_REGL_1,
					0::numeric AS FAC_REGL_2,
					0::numeric AS FAC_ETAT,
					0::numeric AS FAC_COMM,
					0::numeric AS FAC_INV,
					''::text AS FAC_ETAB,
					0::numeric AS FAC_BORD,
					'20991231' AS FAC_DATE_LOT,
					MAX(MC_SEANCE) AS FAC_SEANCE,
					NULL::text[] AS FAC_SEANCE_array,
					0
				FROM w_MOUV_COMPTA_REG
				LEFT JOIN prod_cerner.HOSPITALISATION ON MC_HONUM = HO_NUM
				WHERE MC_FACNUM_CTI LIKE '%.RG'
				GROUP BY 1,2,3,4
				;


				UPDATE w_FACTURE SET
					FAC_REGL = MC_MON_REG,
					FAC_REGL_0 = CASE WHEN FAC_PYTYPE_CTI_HB = '0' THEN MC_MON_REG ELSE 0 END,
					FAC_REGL_1 = CASE WHEN FAC_PYTYPE_CTI_HB = '1' THEN MC_MON_REG ELSE 0 END,
					FAC_REGL_2 = CASE WHEN FAC_PYTYPE_CTI_HB = '2' THEN MC_MON_REG ELSE 0 END
				FROM
				(
				SELECT MC_FACNUM_CTI, SUM(MC_MON_REG) AS MC_MON_REG
				FROM w_MOUV_COMPTA_REG
				GROUP BY 1
				) subview
				WHERE w_FACTURE.FAC_NUM_CTI = MC_FACNUM_CTI AND
					(
						FAC_REGL <> MC_MON_REG OR
						FAC_REGL_0 <> CASE WHEN FAC_PYTYPE_CTI_HB = '0' THEN MC_MON_REG ELSE 0 END OR
						FAC_REGL_1 <> CASE WHEN FAC_PYTYPE_CTI_HB = '1' THEN MC_MON_REG ELSE 0 END OR
						FAC_REGL_2 <> CASE WHEN FAC_PYTYPE_CTI_HB = '2' THEN MC_MON_REG ELSE 0 END
					)
				;


				UPDATE w_FACTURE
				SET FAC_REGL = FAC_REGL_0+FAC_REGL_1+FAC_REGL_2
				WHERE FAC_REGL <> FAC_REGL_0+FAC_REGL_1+FAC_REGL_2
				;
					
				




				-- Préparation factures CTI
				DROP TABLE IF EXISTS w_factures;
				CREATE TEMP TABLE w_factures AS 
				SELECT
					FAC_NUM,
					FAC_SEANCE,
					nextval('activite[PX].s_factures'::regclass) AS oid,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					FAC_NUM_CTI AS no_facture,
					FAC_NUM_CTI AS no_facture_reference,
					0::bigint AS facture_reference_id,
					''::text AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id,
					FAC_DDEB AS date_debut,
					FAC_DFIN AS date_fin,
					p_sejours.ghs_id,
					p_sejours.ghs_bebe1_id,
					p_sejours.ghs_bebe2_id,
					p_sejours.ghs_bebe3_id,
					p_sejours.code_cp_demandee,
					CASE WHEN FAC_NUM_CTI LIKE '%.RG' THEN '9' WHEN FAC_MONT < 0 THEN '1' ELSE '0' END AS type_facture,
					CASE WHEN FAC_MONT < 0 THEN 1 ELSE 0 END AS nb_rejets,
					'1' AS code_facture,
					date(FAC_DATE) AS date_facture,
					'1' AS code_vente,
					to_char(FAC_DATE_VENT,'YYYYMM')::numeric AS mois_vente,
					date(FAC_DATE_VENT) AS date_vente,
					'' AS code_cloture,

					'' AS particularite_t2a,

					
					p_sejours.tiers_payant_0_id,
					p_sejours.tiers_payant_1_id,
					p_sejours.tiers_payant_2_id,
					p_sejours.tiers_payant_22_id,
					FAC_MONT AS montant_facture_c,
					0::numeric AS montant_facture_h,
					FAC_MONT_0 AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					FAC_MONT_1 + FAC_MONT_BG_1 AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					FAC_MONT_2 AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					FAC_MONT_0 + FAC_MONT_1 + FAC_MONT_2 AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					FAC_MONT_0 AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					FAC_MONT_1 AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					FAC_MONT_2 AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					FAC_MONT_BG_1 AS montant_comptabilise_budget_global_c,
					FAC_REGL AS montant_regle_c,
					0::numeric AS montant_regle_h,
					FAC_REGL_0 AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					FAC_REGL_1 AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					FAC_REGL_2 AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					CASE WHEN FAC_PYTYPE_CTI_HB = '0' AND FAC_BORD > 0 THEN '1' ELSE '0' END AS code_expedie_0,
					CASE WHEN (FAC_PYTYPE_CTI_HB = '1' OR FAC_PYTYPE_CTI_HB = '1') AND FAC_BORD > 0 THEN '1' ELSE '0' END AS code_expedie_1,
					CASE WHEN FAC_PYTYPE_CTI_HB = '2' AND FAC_BORD > 0 THEN '1' ELSE '0' END AS code_expedie_2,
					'0' AS code_expedie_22,
					CASE WHEN FAC_DATE_LOT IS NOT NULL THEN date(FAC_DATE_LOT) ELSE '20991231' END date_expedition,
					CASE WHEN FAC_PYTYPE_CTI_HB = '0' AND FAC_DATE_LOT IS NOT NULL THEN date(FAC_DATE_LOT) ELSE '20991231' END AS date_expedition_0,
					CASE WHEN (FAC_PYTYPE_CTI_HB = '1' OR FAC_PYTYPE_CTI_HB = '1') AND FAC_DATE_LOT IS NOT NULL THEN date(FAC_DATE_LOT) ELSE '20991231' END AS date_expedition_1,
					CASE WHEN FAC_PYTYPE_CTI_HB = '2' AND FAC_DATE_LOT IS NOT NULL THEN date(FAC_DATE_LOT) ELSE '20991231' END AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					CASE WHEN FAC_PYTYPE_CTI_HB = '0' AND FAC_BORD > 0 THEN FAC_BORD::text ELSE '' END AS no_bordereau_0,
					CASE WHEN (FAC_PYTYPE_CTI_HB = '1' OR FAC_PYTYPE_CTI_HB = '1') AND FAC_BORD > 0 THEN FAC_BORD::text ELSE '' END AS no_bordereau_1,
					CASE WHEN FAC_PYTYPE_CTI_HB = '2' AND FAC_BORD > 0 THEN FAC_BORD::text ELSE '' END AS no_bordereau_2,
					''::text AS no_bordereau_22,
					'0001-01-01'::date AS date_solde,
					'0001-01-01'::date AS date_solde_c,
					'0001-01-01'::date AS date_solde_h,
					'0001-01-01'::date AS date_solde_0_c,
					'0001-01-01'::date AS date_solde_0_h,
					'0001-01-01'::date AS date_solde_1_c,
					'0001-01-01'::date AS date_solde_1_h,
					'0001-01-01'::date AS date_solde_2_c,
					'0001-01-01'::date AS date_solde_2_h,
					'0001-01-01'::date AS date_solde_22_c,
					'0001-01-01'::date AS date_solde_22_h

				FROM w_FACTURE
				JOIN w_HOSPITALISATION_SELECT ON
					FAC_HONUM = HO_NUM AND
					FAC_SEANCE = HO_SEANCE
				JOIN activite[PX].p_sejours ON w_HOSPITALISATION_SELECT.sejour_id = p_sejours.oid
				
				;

				CREATE INDEX w_factures_i1
					ON w_factures
					USING btree
					(no_facture);

				CREATE INDEX w_factures_FAC_NUM
					ON w_factures
					USING btree
					(FAC_NUM);

				CREATE INDEX w_factures_FAC_SEANCE
					ON w_factures
					USING btree
					(FAC_SEANCE);

			

				UPDATE w_factures
				SET facture_od_avoir_id = w_factures_od_avoir.oid
				FROM w_factures w_factures_od_avoir
				WHERE w_factures.no_facture_od_avoir = w_factures_od_avoir.no_facture
				;

				UPDATE w_factures
				SET type_facture = 'X'
				WHERE w_factures.no_facture_od_avoir <> '0' AND
                    w_factures.no_facture_od_avoir <> '' AND
					w_factures.type_facture = '0'
				;

				UPDATE w_factures
				SET no_facture_reference = subview.no_facture_reference
				FROM
					(SELECT sejour_id,
						(MAX(ARRAY[date_facture::text,no_facture]))[2] AS no_facture_reference
						FROM w_factures
						WHERE type_facture = '0'
						GROUP BY 1
					) subview
				WHERE w_factures.sejour_id = subview.sejour_id AND
					w_factures.no_facture_reference <> subview.no_facture_reference
				;

				UPDATE w_factures
				SET facture_reference_id = w_factures_reference.oid
				FROM w_factures w_factures_reference
				WHERE w_factures.no_facture_reference = w_factures_reference.no_facture
				;

truncate activite[PX].p_factures;

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

				INSERT INTO activite[PX].p_factures (
					oid,
					sejour_id,
					no_sejour,
					no_facture,
					no_facture_reference,
					facture_reference_id,
					no_facture_od_avoir,
					facture_od_avoir_id,
					date_debut,
					date_fin,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					type_facture,
					nb_rejets,
					code_facture,
					date_facture,
					code_vente,
					mois_vente,
					date_vente,
					code_cloture,

					particularite_t2a,
					
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					montant_facture_c,
					montant_facture_h,
					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_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,
					montant_comptabilise_budget_global_c,
					montant_regle_c,
					montant_regle_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,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					code_expedie_22,
					date_expedition,
					date_expedition_0,
					date_expedition_1,
					date_expedition_2,
					date_expedition_22,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					no_bordereau_22,

					date_solde,
					date_solde_c,
					date_solde_h,
					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


					)

				SELECT
					oid,
					sejour_id,
					no_sejour,
					no_facture,
					w_factures.no_facture_reference,
					facture_reference_id,
					no_facture_od_avoir,
					facture_od_avoir_id,
					date_debut,
					date_fin,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					code_cp_demandee,
					type_facture,
					nb_rejets,
					code_facture,
					date_facture,
					code_vente,
					mois_vente,
					date_vente,
					code_cloture,

					particularite_t2a,
					
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					montant_facture_c,
					montant_facture_h,
					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_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,
					montant_comptabilise_budget_global_c,
					montant_regle_c,
					montant_regle_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,
					code_expedie_0,
					code_expedie_1,
					code_expedie_2,
					code_expedie_22,
					CASE WHEN date_expedition <> '00010101' THEN date_expedition ELSE '20991231' END,
					CASE WHEN date_expedition_0 <> '00010101' THEN date_expedition_0 ELSE '20991231' END,
					CASE WHEN date_expedition_1 <> '00010101' THEN date_expedition_1 ELSE '20991231' END,
					CASE WHEN date_expedition_2 <> '00010101' THEN date_expedition_2 ELSE '20991231' END,
					CASE WHEN date_expedition_22 <> '00010101' THEN date_expedition_22 ELSE '20991231' END,
					no_bordereau_0,
					no_bordereau_1,
					no_bordereau_2,
					no_bordereau_22,

					CASE WHEN date_solde <> '00010101' THEN date_solde ELSE '20991231' END,
					CASE WHEN date_solde_c <> '00010101' THEN date_solde_c ELSE '20991231' END,
					CASE WHEN date_solde_h <> '00010101' THEN date_solde_h ELSE '20991231' END,
					CASE WHEN date_solde_0_c <> '00010101' THEN date_solde_0_c ELSE '20991231' END,
					CASE WHEN date_solde_0_h <> '00010101' THEN date_solde_0_h ELSE '20991231' END,
					CASE WHEN date_solde_1_c <> '00010101' THEN date_solde_1_c ELSE '20991231' END,
					CASE WHEN date_solde_1_h <> '00010101' THEN date_solde_1_h ELSE '20991231' END,
					CASE WHEN date_solde_2_c <> '00010101' THEN date_solde_2_c ELSE '20991231' END,
					CASE WHEN date_solde_2_h <> '00010101' THEN date_solde_2_h ELSE '20991231' END,
					CASE WHEN date_solde_22_c <> '00010101' THEN date_solde_22_c ELSE '20991231' END,
					CASE WHEN date_solde_22_h <> '00010101' THEN date_solde_22_h ELSE '20991231' END

				FROM w_factures 
				;

				SELECT base.cti_enable_index('activite', 'i_factures_3');
				SELECT base.cti_enable_index('activite', 'i_factures_4');
				SELECT base.cti_enable_index('activite', 'i_factures_5');
				SELECT base.cti_enable_index('activite', 'i_factures_6');
				SELECT base.cti_enable_index('activite', 'i_factures_7');
				SELECT base.cti_enable_index('activite', 'i_factures_8');
				SELECT base.cti_enable_index('activite', 'i_factures_9');
				SELECT base.cti_enable_index('activite', 'i_factures_10');
				SELECT base.cti_enable_index('activite', 'i_factures_11');
				SELECT base.cti_enable_index('activite', 'i_factures_12');
				SELECT base.cti_enable_index('activite', 'i_factures_13');
				SELECT base.cti_enable_index('activite', '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,
					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,
					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,
					CASE WHEN code_sorti = '1' THEN date_sortie ELSE date(now()) END AS date_fin_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%'
					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.est_sans_facturation IS DISTINCT FROM '1' AND date_entree <= now() AND p_sejours.type_sejour <> '6' AND p_sejours.type_sejour <> '9' AND code_prevu <> 1
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11;
				
				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, 
					date_debut, 
					date_fin)
				SELECT finess, 
					no_sejour, 
					no_sejour || '.00' || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois ELSE '' END, 
					no_sejour || '.00' || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || p_calendrier.mois 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 , 
					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;

					
				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
					);
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[

				
				
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Clinique">
			<sqlcmd><![CDATA[
			
				
				DROP SEQUENCE IF EXISTS w_factures_lignes_c_seq;
				CREATE TEMP SEQUENCE w_factures_lignes_c_seq;
			
				DROP TABLE IF EXISTS w_factures_lignes_c;
				CREATE TEMP TABLE w_factures_lignes_c AS 
				SELECT
					nextval('w_factures_lignes_c_seq'::regclass) AS sequence, 
					w_factures.no_sejour,
					w_factures.oid AS facture_id,
					w_factures.no_facture AS no_facture,
					w_factures.date_vente,
					
					1::numeric AS coefficient,
					1::numeric AS coefficient_mco,
					t_rubriques_facturation.oid AS rubrique_facturation_id,
					t_rubriques_facturation.oid AS rubrique_comptabilisation_id,
					t_prestations.oid AS prestation_id,
					t_prestations.code AS prestation_code,
					t_prestations.type_ventilation_jour AS prestation_type_ventilation_jour,
					COALESCE(t_compte.oid,0) AS compte_produit_id,
					p_sejours.lieu_sortie_id AS lieu_id,
					1::bigint AS origine_facturation_id,

					FAD_PUFAC AS prix_unitaire,
					0::numeric AS taux_0,
					FAD_TAUDG AS taux_1,
					0::numeric  AS taux_2,
					0::numeric AS taux_22,

					date(FAD_DEB) AS date_debut,
					date(FAD_FIN) AS date_fin,
					FAD_NBR AS nb_rubrique,
					FAD_NBR AS nb_prestation,
					FAD_MON AS montant_facture,
					FAD_MON_0 AS montant_facture_0,
					FAD_MON_1+FAD_MON_BG_1 AS  montant_facture_1,
					FAD_MON_2 AS montant_facture_2,
					0::numeric AS montant_facture_22,
					FAD_MON_0+FAD_MON_1+FAD_MON_2 AS montant_comptabilise,
					FAD_MON_0 AS montant_comptabilise_0,
					FAD_MON_1 AS montant_comptabilise_1,
					FAD_MON_2 AS montant_comptabilise_2,
					0::numeric AS montant_comptabilise_22,
					FAD_MON_BG_1 AS montant_comptabilise_budget_global_1,
					
					0::numeric AS rubrique_facture_id
				FROM w_FACTURE_DET
					JOIN w_factures ON w_factures.FAC_NUM = w_FACTURE_DET.FAD_NUM AND
						w_factures.FAC_SEANCE = w_FACTURE_DET.FAD_SEANCE AND
						w_factures.no_facture NOT LIKE '%.RG'
					JOIN activite[PX].p_sejours ON w_factures.no_sejour = p_sejours.no_sejour
					LEFT JOIN activite[PX].t_rubriques_facturation ON FAD_CTCODE = t_rubriques_facturation.code_original 
					LEFT JOIN activite.t_prestations ON FAD_CTNB2 = t_prestations.code
					LEFT JOIN activite[PX].t_compte ON FAD_COMPTE = t_compte.code
				;


				  
				CREATE INDEX w_factures_lignes_c_i1
				  ON w_factures_lignes_c
				  USING btree
				  (sequence);
				  
				CREATE INDEX w_factures_lignes_c_i2
				  ON w_factures_lignes_c
				  USING btree
				  (prestation_id);


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

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					date(p_sejours.date_entree) AS date_debut_ghs,
					date(p_sejours.date_sortie - interval '1 day') 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 prestation_code = 'GHS' THEN date(date_entree + interval '1 day') ELSE date(date_debut + interval '1 day') END AS date_debut_det,
					CASE WHEN prestation_code = 'GHS' THEN date(p_sejours.date_sortie - interval '1 day') ELSE date(date_debut + ((ABS(nb_prestation)-1)|| ' days')::interval)  END AS date_fin_det,
					ABS(CASE WHEN prestation_code = 'GHS' THEN date(date_sortie) - date(date_entree) ELSE nb_prestation END) AS nb_det,
					w_factures_lignes_c.*
				FROM w_factures_lignes_c
					JOIN activite[PX].p_sejours ON w_factures_lignes_c.no_sejour = p_sejours.no_sejour
				WHERE 
					(
						prestation_code IN ('PJ', 'FJ', 'SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						prestation_type_ventilation_jour = '1'
					)
						AND
					(
					(nb_prestation > 1 or nb_prestation < -1 OR 
					(prestation_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 w_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
					w_factures_lignes_sup_c.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
					sequence, 
					no_sejour,
					facture_id,
					no_facture,
					date_vente,

					
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					prestation_code,
					prestation_type_ventilation_jour,
					compte_produit_id,
					lieu_id,
					origine_facturation_id,

					prix_unitaire,
					taux_0,
					taux_1,
					taux_2,
					taux_22,

					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,
					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,
					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_comptabilise_budget_global_1 / ABS(nb_det),2) AS montant_comptabilise_budget_global_1,
					rubrique_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 sequence,
					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_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_1
				FROM w_factures_lignes_sup_c_sup
				GROUP BY 1;


				UPDATE w_factures_lignes_c
				SET
					date_fin = w_factures_lignes_c.date_debut,
					nb_rubrique = w_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_sup_tot.nb_rubrique,
					nb_prestation = w_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_sup_tot.nb_prestation,
					montant_facture = w_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_sup_tot.montant_facture,
					montant_facture_0 = w_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_sup_tot.montant_facture_0,
					montant_facture_1 = w_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_sup_tot.montant_facture_1,
					montant_facture_2 = w_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_sup_tot.montant_facture_2,
					montant_facture_22 = w_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_sup_tot.montant_facture_22,
					montant_comptabilise = w_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_sup_tot.montant_comptabilise,
					montant_comptabilise_0 = w_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_0,
					montant_comptabilise_1 = w_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_1,
					montant_comptabilise_2 = w_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_2,
					montant_comptabilise_22 = w_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_sup_tot.montant_comptabilise_22,
					montant_comptabilise_budget_global_1 = w_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 w_factures_lignes_c.sequence = w_factures_lignes_sup_c_sup_tot.sequence;
				
				
		
				-- Ajout des lignes
				INSERT INTO w_factures_lignes_c(
					sequence, 
					no_sejour,
					facture_id,
					no_facture,
					date_vente,

					
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					prestation_code,
					prestation_type_ventilation_jour,
					compte_produit_id,
					lieu_id,
					origine_facturation_id,

					prix_unitaire,
					taux_0,
					taux_1,
					taux_2,
					taux_22,

					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					rubrique_facture_id)
				SELECT 
					sequence, 
					no_sejour,
					facture_id,
					no_facture,
					date_vente,

					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					prestation_code,
					prestation_type_ventilation_jour,
					compte_produit_id,
					lieu_id,
					origine_facturation_id,

					prix_unitaire,
					taux_0,
					taux_1,
					taux_2,
					taux_22,

					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					rubrique_facture_id
				FROM w_factures_lignes_sup_c_sup;
				
				
				
				-- Lieu exécution
				
				
				UPDATE w_factures_lignes_c
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM 
					activite[PX].p_mouvements_sejour
				WHERE
					w_factures_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_lignes_c.date_fin = p_mouvements_sejour.date AND
					(230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
					nb_entrees_directes = 1 AND heure_fin = 240000 OR 
					nb_sorties_directes = 1 ) AND
					w_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id AND
					nb_externes <> 1;
					
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_c');	
				  



				-- Validation des lignes de facture  
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_c_8');

				INSERT INTO activite[PX].p_factures_lignes_c (
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					compte_produit_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,
					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,
					origine_facturation_id
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					compte_produit_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,
					0::numeric AS montant_encours,
					0::numeric AS montant_encours_0,
					0::numeric AS montant_encours_1,
					0::numeric AS montant_encours_2,
					0::numeric AS montant_encours_22,
					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,
					montant_comptabilise_budget_global_1,
					origine_facturation_id
				FROM w_factures_lignes_c
				WHERE montant_facture <> 0;
				
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_1');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_2');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_3');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_4');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_5');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_6');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_7');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_c_8');

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

				-- Ajout des prestations PMSI aux prestations activité
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT
					t_prestations_pmsi.code,
					t_prestations_pmsi.code,
					t_prestations_pmsi.texte,
					t_prestations_pmsi.texte
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND
					t_rubriques_facturation.oid IS NULL
				GROUP BY 1,2,3,4;

				-- Ajout des prestations PMSI aux rubriques activité
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT
					t_prestations_pmsi.code,
					t_prestations_pmsi.code,
					t_prestations_pmsi.texte,
					t_prestations_pmsi.texte
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND 
					t_prestations_activite.oid IS NULL
				GROUP BY 1,2,3,4;

				-- Lignes PMSI à ajouter
				DROP TABLE IF EXISTS w_sejours_budget_global;
				CREATE TEMP TABLE w_sejours_budget_global AS
				SELECT 
					p_sejour_pmsi.rss_id,
					MAX(p_sejour_pmsi.sejour_id) AS sejour_id,
					(MAX(Array[to_char(p_sejour_pmsi.sejour_id,'FM000000000000'),p_sejours.no_sejour]))[2]::text AS no_sejour,
					(MAX(CASE WHEN p_factures.montant_comptabilise_budget_global_c > 0 AND date_part('year',p_factures.date_facture) =  date_part('year',p_sejours.date_sortie) THEN Array[to_char(p_sejour_pmsi.sejour_id,'FM000000000000'),p_factures.no_facture] ELSE NULL END))[2]::text AS no_facture_budget_global,
					(MAX(CASE WHEN p_factures.montant_facture_c > 0 AND date_part('year',p_factures.date_facture) =  date_part('year',p_sejours.date_sortie) THEN Array[to_char(p_sejour_pmsi.sejour_id,'FM000000000000'),p_factures.no_facture] ELSE NULL END))[2]::text AS no_facture_hors_budget_global,
					(MAX(Array[p_sejour_pmsi.sejour_id,p_sejours.lieu_sortie_id]))[2] AS lieu_sortie_id
				FROM activite[PX].p_sejour_pmsi
				JOIN activite[PX].p_sejours ON p_sejour_pmsi.sejour_id = p_sejours.oid
				LEFT JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour 
				WHERE 
					p_sejour_pmsi.sejour_id IS NOT NULL AND 
					p_sejour_pmsi.sejour_id <> 0 AND
					p_sejour_pmsi.rss_id <> 0
				GROUP BY 1;
				
				-- Suppression des lignes issues de la facturation
				DELETE FROM activite[PX].p_factures_lignes_c
				WHERE montant_comptabilise_budget_global_1 <> 0 AND
					no_facture IN
					(SELECT no_facture
					FROM activite[PX].p_factures
					JOIN w_sejours_budget_global ON p_factures.no_sejour = w_sejours_budget_global.no_sejour AND w_sejours_budget_global.rss_id <> 0
					)
				;
				
				DELETE FROM activite[PX].p_factures_lignes_c
				WHERE montant_comptabilise_budget_global_1 <> 0 AND
					no_facture IN
					(SELECT no_facture
					FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON  p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite[PX].t_lieux On lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON t_services_facturation.oid = service_facturation_id AND type_t2a = '1'
					)
				;

				-- Génération des lignes venant du pmsi
				DROP TABLE IF EXISTS w_factures_lignes_pmsi;
				CREATE TEMP TABLE w_factures_lignes_pmsi AS
				SELECT
					w_sejours_budget_global.no_sejour,
					w_sejours_budget_global.sejour_id,
					COALESCE(w_sejours_budget_global.no_facture_budget_global,w_sejours_budget_global.no_facture_hors_budget_global,w_sejours_budget_global.no_sejour || '.BG') AS no_facture,
					0::bigint AS facture_id,
					CASE WHEN p_rsf_detail.type = 'C' THEN 'H' ELSE 'C' END AS clinique_honoraire,
					p_rsf_detail.date_debut,
					p_rsf_detail.date_fin,
					p_rsf_detail.nombre AS nb_rubrique,
					p_rsf_detail.nombre AS nb_prestation,
					p_rsf_detail.coefficient AS coefficient,
					p_rsf_detail.coefficient_mco,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations_activite.oid,0::bigint) AS prestation_id,
					p_rsf_detail.sejour_remboursable AS montant_facture,
					0::numeric AS montant_facture_0,
					p_rsf_detail.sejour_remboursable AS montant_facture_1,
					0::numeric AS montant_facture_2,
					0::numeric AS montant_facture_22,
					0::numeric AS taux_0,
					p_rsf_detail.taux_remboursement AS taux_1,
					0::numeric AS taux_2,
					0::numeric AS taux_22,
					p_rsf_detail.prix_unitaire,
					w_sejours_budget_global.lieu_sortie_id AS lieu_id,
					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,
					0::numeric AS montant_encours,
					0::numeric AS montant_encours_0,
					0::numeric AS montant_encours_1,
					0::numeric AS montant_encours_2,
					0::numeric AS montant_encours_22,
					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,
					1::bigint AS origine_facturation_id,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_comptabilise_budget_global_1,
					0::numeric AS protocole_id,
					0::numeric AS compte_produit_id,
					t_prestations_pmsi.code AS prestation_code,
					''::text AS uf_code,
					''::text AS dmt_code,
					''::text AS mt_code
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0' 
				JOIN pmsi.p_rsf_total ON p_rss.oid = p_rsf_total.rss_id AND p_rsf_total.valorise_fides IS DISTINCT FROM 1
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN w_sejours_budget_global ON p_rss.oid = w_sejours_budget_global.rss_id
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND
					p_rss.date_sortie >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					p_rss.traitement_epmsi IN ('30','31','32','33') ;


				

				-- Factures à créer
				DROP TABLE IF EXISTS w_factures_pmsi;
				CREATE TEMP TABLE w_factures_pmsi AS
				SELECT
					w_factures_lignes_pmsi.no_sejour,
					w_factures_lignes_pmsi.sejour_id,
					w_factures_lignes_pmsi.no_facture,
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					MAX(p_sejours.date_sortie) AS date_facture,
					MAX('1') AS code_vente,
					MAX(to_char(p_sejours.date_sortie,'YYYYMM')::numeric) AS mois_vente,
					MAX(p_sejours.date_sortie) AS date_solde,
					'0'::text AS particularite_t2a,
					MAX(p_sejours.date_sortie) AS date_vente,
					''::text AS code_cloture,
					MAX(p_sejours.code_cp_demandee) AS code_cp_demandee,
					'20991231'::date AS date_encours,
					MAX(p_sejours.ghs_id) AS ghs_id,
					MAX(p_sejours.ghs_bebe1_id) AS ghs_bebe1_id,
					MAX(p_sejours.ghs_bebe2_id) AS ghs_bebe2_id,
					MAX(p_sejours.ghs_bebe3_id) AS ghs_bebe3_id,
					MAX(p_sejours.ghm_id) AS ghm_id,
					SUM(montant_facture) AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					'20991231'::date AS date_expedition,
					0::numeric AS delai_expedition,
					MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
					MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
					MAX(p_sejours.tiers_payant_22_id) AS tiers_payant_22_id,
					MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,
					'20991231'::date AS date_expedition_0,
					'20991231'::date AS date_expedition_1,
					'20991231'::date AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					'0'::text AS code_expedie_0,
					'0'::text AS code_expedie_1,
					'0'::text AS code_expedie_2,
					'0'::text AS code_expedie_22,
					''::text AS no_bordereau_0,
					''::text AS no_bordereau_1,
					''::text AS no_bordereau_2,
					''::text AS no_bordereau_22,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					SUM(montant_facture) AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,
					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric 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,
					0::numeric AS nb_rejets,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					w_factures_lignes_pmsi.no_facture AS no_facture_reference,
					0::bigint AS facture_reference_id,
					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_c,
					''::text AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id
				FROM w_factures_lignes_pmsi
				JOIN activite[PX].p_sejours ON w_factures_lignes_pmsi.no_sejour = p_sejours.no_sejour
				WHERE w_factures_lignes_pmsi.no_facture LIKE '%BG'
				GROUP BY 1,2,3,4,5;
				
				

				
				
				-- Ajout des factures
				INSERT INTO activite[PX].p_factures
					(no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_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_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_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, date_vente, code_cloture, 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, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, 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, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id)
				  SELECt no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_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_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_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, 'PMSIMCO' AS 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, date_vente, code_cloture, 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, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, 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, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id
				   FROM w_factures_pmsi;



					-- Ajout des lignes
				   INSERT INTO activite[PX].p_factures_lignes_c(
						no_facture, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
						rubrique_facturation_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, finess, prix_unitaire, lieu_id, nb_prestation, 
						montant_comptabilise, montant_comptabilise_0, montant_comptabilise_1, 
						montant_comptabilise_2, montant_comptabilise_22, rubrique_comptabilisation_id, 
						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, protocole_id, compte_produit_id)
					SELECT 
						p_factures.no_facture, w_factures_lignes_pmsi.date_debut, w_factures_lignes_pmsi.date_fin, nb_rubrique, coefficient, coefficient_mco, 
							rubrique_facturation_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, finess, prix_unitaire, lieu_id, nb_prestation, 
							montant_comptabilise, montant_comptabilise_0, montant_comptabilise_1, 
							montant_comptabilise_2, montant_comptabilise_22, rubrique_comptabilisation_id, 
							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, 
							p_factures.oid AS facture_id, protocole_id, compte_produit_id
					FROM w_factures_lignes_pmsi
					JOIN activite[PX].p_factures ON w_factures_lignes_pmsi.no_facture = p_factures.no_facture ;
                    
                    
                    
                    -- 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,
                        date(p_sejours.date_entree) AS date_debut_ghs,
                        date(p_sejours.date_sortie - interval '1 day') 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 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 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 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 AND p_sejours.etat = ''
                        JOIN activite.t_prestations ON prestation_id = t_prestations.oid  AND 
                            (
                            code IN ('PJ', '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_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
                        w_factures_lignes_sup_c.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,
                        prestation_id,
                        compte_produit_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,
                        rubrique_comptabilisation_id,
                        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 date_debut BETWEEN p_calendrier.date - ABS(nb_det)::integer + 1 AND p_calendrier.date AND 
                                    p_calendrier.date <> date_debut ;
                    ;


                    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;
                    
                    

                    INSERT INTO activite[PX].p_factures_lignes_c(
                        no_facture,
                        date_debut,
                        date_fin,
                        nb_rubrique,
                        coefficient,
                        coefficient_mco,
                        rubrique_facturation_id,
                        prestation_id,
                        compte_produit_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,
                        rubrique_comptabilisation_id,
                        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_facturation_id,
                        prestation_id,
                        compte_produit_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,
                        rubrique_comptabilisation_id,
                        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;


                    -- Lieu exécution
                    
                    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
                        p_factures_lignes_c.date_fin = p_mouvements_sejour.date AND
                        (230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
                        nb_entrees_directes = 1 AND heure_fin = 240000 OR 
                        nb_sorties_directes = 1 ) AND
                        p_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id
                    ;
                            


					
					-- 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, 
						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 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
					GROUP BY 1,2,3,4,5,6,10,11,12,13,14,15,16,17;
					
					-- 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
						type_t2a = '1' AND
						date_entree between 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
                            JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture
                            JOIN activite[PX].t_prestations ON prestation_id = t_prestations.oid 
                            WHERE t_prestations.code = 'GHS' AND montant_facture > 0
                        ) 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
						);
						
					
					
					-- 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
					JOIN activite[PX].p_sejour_pmsi ON p_sejour_pmsi.sejour_id = p_sejours.oid
					JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
					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
						) AND
						p_rss.traitement_epmsi NOT IN ('30','31','32','33')
					GROUP BY 1
					HAVING SUM(montant_facture_0+montant_facture_1+montant_facture_2) > 0
					ORDER BY 1;

					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;
                        
                        
                    -- Suppression des factures encours externes ajoutées à tord
                    DROP TABLE IF EXISTS w_factures_externes_double_bg;
                    CREATE TEMP TABLE w_factures_externes_double_bg AS
                    SELECT p_factures.no_sejour, 
                        MAX(CASE WHEN code_facture = '0' AND p_factures.montant_facture_c = 0 THEN no_facture ELSE '' END) AS no_facture_encours,
                        MAX(CASE WHEN code_facture = '1' AND no_facture LIKE '%BG%' THEN no_facture ELSE '' END) AS no_facture_bg
                        FROM activite[PX].p_factures
                        JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                    WHERE p_sejours.type_sejour = '3' 
                    GROUP BY 1
                    HAVING MAX(CASE WHEN code_facture = '0' THEN no_facture ELSE '' END) <> '' AND MAX(CASE WHEN code_facture = '1' AND no_facture LIKE '%BG%' THEN no_facture ELSE '' END) <> ''
                    ;
                    
                    DELETE FROM activite[PX].p_factures
                    WHERE code_facture = '0' AND
                        montant_facture_c = 0 AND
                        no_facture IN (SELECT no_facture_encours FROM w_factures_externes_double_bg)
                    ;
                    
                    DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
                    WHERE no_facture IN (SELECT no_facture_encours FROM w_factures_externes_double_bg)
                    ;
                     
                    -- Ajout des prestations NGAP non facturées
                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        facture_id,
                        no_facture, 
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id)
                    SELECT 
                        p_factures.oid AS facture_id,
                        p_factures.no_facture AS no_facture,
                        date(NGAP_DATE) AS date_debut,
                        date(NGAP_DATE) AS date_fin,
                        NGAP_NB AS nb_rubrique,
                        NGAP_COEF AS coefficient,
                        t_rubriques_facturation.oid AS rubrique_facturation_id,
                        t_prestations.oid AS prestation_id,
                        LC_PRIX AS prix_unitaire,
                        p_sejours.lieu_sortie_id AS lieu_id
                    FROM prod_cerner.PASSAGE_NGAP
                    JOIN prod_cerner.CODE_TARIF ON NGAP_CTCODE = CT_CODE
                    JOIN prod_cerner.LETTRE_CLE ON CT_LET = LC_CODE AND NGAP_DATE BETWEEN LC_DDEB AND COALESCE(LC_DFIN,'20991231')
                    JOIN activite[PX].p_sejours ON NGAP_HONUM = p_sejours.code_original AND p_sejours.etat = '' AND
                            NGAP_DATE BETWEEN p_sejours.date_entree AND p_sejours.date_sortie
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour
                        JOIN activite.t_prestations ON t_prestations.code = CT_LET
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = NGAP_CTCODE
                    WHERE p_factures.code_facture <> '1' AND p_sejours.type_sejour = '3' AND NGAP_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'
                    ;
                    
                    INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
                        facture_id,
                        no_facture, 
                        date_debut, 
                        date_fin, 
                        nb_rubrique, 
                        coefficient, 
                        rubrique_facturation_id, 
                        prestation_id, 
                        prix_unitaire, 
                        lieu_id)
                    SELECT 
                        p_factures.oid AS facture_id,
                        p_factures.no_facture AS no_facture,
                        date(CDAM_DATE) AS date_debut,
                        date(CDAM_DATE) AS date_fin,
                        1 AS nb_rubrique,
                        1 AS coefficient,
                        t_rubriques_facturation.oid AS rubrique_facturation_id,
                        t_prestations.oid AS prestation_id,
                        PRIX_ACTE * CASE CDAM_CCAM_ASSNOPREV WHEN '2' THEN 0.5 WHEN '3' THEN 0.75 ELSE 1 END AS prix_unitaire,
                        p_sejours.lieu_sortie_id AS lieu_id
                    FROM prod_cerner.PASSAGE_CDAM
                    JOIN activite[PX].p_sejours ON CDAM_HONUM = p_sejours.code_original AND p_sejours.etat = '' AND
                            CDAM_DATE BETWEEN p_sejours.date_entree AND p_sejours.date_sortie
                        JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour
                        JOIN base.t_actes ON CDAM_CODEACTE = t_actes.code
                        JOIN base.t_ccam_regroupements ON 
                            (t_actes.ccam_regroupement_id_1 = t_ccam_regroupements.oid AND CDAM_CCAM_ACTIVITE <> '4' OR
                            t_actes.ccam_regroupement_id_4 = t_ccam_regroupements.oid AND CDAM_CCAM_ACTIVITE = '4'
                            )
                        JOIN activite.t_prestations ON t_prestations.code = t_ccam_regroupements.code
                        JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = t_ccam_regroupements.code
                    WHERE p_factures.code_facture <> '1' AND p_sejours.type_sejour = '3' AND CDAM_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'
                    ;
					
					
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Compte client Clinique">
			<sqlcmd><![CDATA[
			
				

			
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_c_8');
				
				
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					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
					facture_id,
					no_facture,
					date_trunc('month',date_vente) + interval '1 month' - interval '1 day',
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS 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_factures_lignes_c
				WHERE date_vente >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					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,5;
				
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					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
					p_factures.oid AS facture_id,
					no_facture,
					date_trunc('month',MC_DATECR) + interval '1 month' - interval '1 day',
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
					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, 
					SUM(MC_MON_REG) AS montant_regle, 
					SUM(CASE WHEN FAC_PYTYPE_CTI_HB = '0' THEN MC_MON_REG ELSE 0 END) AS montant_regle_0, 
					SUM(CASE WHEN FAC_PYTYPE_CTI_HB = '1' THEN MC_MON_REG ELSE 0 END) AS montant_regle_1, 
					SUM(CASE WHEN FAC_PYTYPE_CTI_HB = '2' THEN MC_MON_REG ELSE 0 END) AS montant_regle_2, 
					0::numeric AS montant_regle_22
				FROM w_MOUV_COMPTA_REG
				JOIN w_FACTURE ON w_FACTURE.FAC_NUM_CTI = MC_FACNUM_CTI
				JOIN activite[PX].p_factures ON w_MOUV_COMPTA_REG.MC_FACNUM_CTI = p_factures.no_facture
				WHERE MC_DATECR >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					MC_MON_REG <> 0
				GROUP BY 1,2,3,4,5;

				
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_c_1');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_c_2');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_c_3');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_c_4');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_c_8');
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Lignes non facturées Honoraires">
			<sqlcmd><![CDATA[

						
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Honoraires">
			<sqlcmd><![CDATA[
		
				-- Recalculer facture de référence (pour attribuer l'acte à la bonne facture)
				DROP TABLE IF EXISTS w_sejours_facture_reference;

				CREATE TEMP TABLE w_sejours_facture_reference AS
				SELECT 
					p_sejours.no_sejour,
					CASE WHEN avec_facturation_intermediaire IS DISTINCT FROM '1' THEN p_sejours.date_sortie ELSE p_factures.date_fin END AS date_fin,
					MIN(CASE WHEN avec_facturation_intermediaire IS DISTINCT FROM '1' THEN p_sejours.date_entree ELSE p_factures.date_debut END) AS date_debut,
					MAX(p_factures.no_facture) AS no_facture_last,
					MAX(CASE WHEN type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' THEN p_factures.no_facture ELSE null END) AS no_facture_reference_last,
					(MAX(ARRAY[to_char(
						CASE
							WHEN type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' AND (t_prestations.code IN ('GHS','PJ') OR (p_factures.no_facture LIKE '%BG' AND p_sejours.type_sejour IN ('1','2','5','6'))) THEN p_factures_lignes_c.taux_1
							ELSE 0 END
							,'FM00000'),
						CASE 
							WHEN type_facture <> '1' AND type_facture <> 'X' AND type_facture <> 'P' AND (t_prestations.code IN ('GHS','PJ') OR (p_factures.no_facture LIKE '%BG' AND p_sejours.type_sejour IN ('1','2','5','6'))) THEN p_factures.no_facture 
							ELSE NULL END
							]
					))[2] AS no_facture_reference_sejour_last,
					COUNT(DISTINCT p_factures.no_facture) AS nb_factures,
					MAX(avec_facturation_intermediaire) AS avec_facturation_intermediaire
				FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite[PX].t_lieux ON p_sejours.lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures.no_facture = p_factures_lignes_c.no_facture
					LEFT JOIN activite.t_prestations ON p_factures_lignes_c.prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS','PJ')
				GROUP BY 1,2;


				CREATE INDEX w_sejours_facture_reference_i1
								  ON w_sejours_facture_reference
								  USING btree
								  (no_sejour);

				UPDATE activite[PX].p_factures
				SET no_facture_reference = COALESCE(no_facture_reference_sejour_last, no_facture_reference_last, no_facture_last)
				FROM w_sejours_facture_reference
				JOIN activite[PX].p_sejours ON p_sejours.no_sejour = w_sejours_facture_reference.no_sejour
				WHERE p_factures.no_sejour = w_sejours_facture_reference.no_sejour AND
					(
						p_factures.date_fin = w_sejours_facture_reference.date_fin OR
						p_factures.date_fin = p_sejours.date_sortie AND avec_facturation_intermediaire IS DISTINCT FROM '1'

					) AND
					p_factures.no_facture_reference <> COALESCE(no_facture_reference_sejour_last, no_facture_reference_last, no_facture_last);
						
				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
				;
				
				UPDATE activite[PX].p_factures
				SET date_fin = date_fin_facture
				FROM activite[PX].p_factures_reference 
				WHERE p_factures.no_facture_reference = p_factures_reference.no_facture_reference AND
					p_factures.date_fin <> p_factures_reference.date_fin_facture
				;
				UPDATE activite[PX].p_factures
				SET date_debut = date_debut_facture
				FROM activite[PX].p_factures_reference 
				WHERE p_factures.no_facture_reference = p_factures_reference.no_facture_reference AND
					p_factures.date_debut <> p_factures_reference.date_debut_facture
				;
				
				
                
                INSERT INTO base.t_actes (code, texte, texte_court, nomenclature, ccam_regroupement_id_1)
                SELECT CT_LET, MAX(CT_LIB), MAX(CT_LIB), 'NGAP', MAX(t_ccam_regroupements.oid)
                FROM prod_cerner.PASSAGE_NGAP
                    JOIN prod_cerner.CODE_TARIF ON NGAP_CTCODE = CT_CODE
                    JOIN base.t_ccam_regroupements ON t_ccam_regroupements.Code = 'NGAP'
                    LEFT JOIN base.t_actes ON t_actes.code = CT_LET
                WHERE CT_LET NOT IN ('SE1','SE2','SE3','SE4','SE5', 'SE6', 'SE7','ATU', 'FPU','FFM') AND
                    t_actes.oid IS NULL
                GROUP BY 1
                ORDER BY 1
                ;

					SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_1');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_2');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_3');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_4');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_5');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_6');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_7');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_8');
				SELECT base.cti_disable_index('activite', 'i_factures_lignes_h_9');
				
				DROP TABLE IF EXISTS w_PASSAGE_NGAP;
				CREATE TEMP TABLE w_PASSAGE_NGAP AS
				SELECT row_number() OVER () AS oid,
					0 as lieu_id,
					code_original_1,
					code_original_2,
					code_original_3,
					code_original_4,
					code_original_5,
					PASSAGE_NGAP.*,
					CODE_TARIF.*,
					LETTRE_CLE.*
				FROM prod_cerner.PASSAGE_NGAP
				JOIN prod_cerner.CODE_TARIF ON NGAP_CTCODE = CT_CODE
						JOIN prod_cerner.LETTRE_CLE ON CT_LET = LC_CODE AND NGAP_DATE BETWEEN LC_DDEB AND COALESCE(LC_DFIN,'20991231')
				JOIN activite[PX].p_sejours ON no_sejour = NGAP_HONUM
				JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
                ;

				ANALYSE w_PASSAGE_NGAP
				;

				CREATE INDEX w_PASSAGE_NGAP_oid
							ON w_PASSAGE_NGAP
							USING btree
							(oid);

				DROP TABLE IF EXISTS w_PASSAGE_NGAP_facture;
				CREATE TEMP TABLE w_PASSAGE_NGAP_facture AS
				SELECT PASSAGE_NGAP.oid,
					NGAP_HONUM AS HONUM,
					MAX(no_facture) AS no_facture,
					(MAX(ARRAY[no_facture,p_factures.oid::text]))[2]::bigint AS facture_id,
					MAX(p_sejours.lieu_sortie_id) AS lieu_sortie_id
				FROM w_PASSAGE_NGAP PASSAGE_NGAP
				JOIN activite[PX].p_sejours ON NGAP_HONUM = p_sejours.no_sejour AND p_sejours.etat = ''
                JOIN activite[PX].p_factures ON NGAP_HONUM = p_factures.no_sejour AND
                        p_factures.no_facture = p_factures.no_facture_reference AND
                        NGAP_DATE BETWEEN p_factures.date_debut AND p_factures.date_fin
                GROUP BY 1,2
                ;

                ANALYSE w_PASSAGE_NGAP_facture
                ;
                
                
                CREATE INDEX w_PASSAGE_NGAP_facture_oid
					ON w_PASSAGE_NGAP_facture
					USING btree
					(oid)
				;

                INSERT INTO activite[PX].t_lieux(
                    code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
                    SELECT
                    w_PASSAGE_NGAP.code_original_1,
                    w_PASSAGE_NGAP.code_original_2,
                    w_PASSAGE_NGAP.code_original_3,
                    w_PASSAGE_NGAP.code_original_4,
                    w_PASSAGE_NGAP.code_original_5,
                    NGAP_UFXCODE
                FROM w_PASSAGE_NGAP
                    LEFT JOIN activite[PX].t_lieux ON (
                        t_lieux.code_original_1 = w_PASSAGE_NGAP.code_original_1 AND
                        t_lieux.code_original_2 = w_PASSAGE_NGAP.code_original_2 AND
                        t_lieux.code_original_3 = w_PASSAGE_NGAP.code_original_3 AND
                        t_lieux.code_original_4 = w_PASSAGE_NGAP.code_original_4 AND
                        t_lieux.code_original_5 = w_PASSAGE_NGAP.code_original_5 AND
                        t_lieux.code_original_6 = NGAP_UFXCODE
                        )
                WHERE t_lieux.oid IS NULL
                GROUP BY 1,2,3,4,5,6
                ;

                UPDATE w_PASSAGE_NGAP
                SET lieu_id = t_lieux.oid
                FROM activite[PX].t_lieux
                WHERE t_lieux.code_original_1 = w_PASSAGE_NGAP.code_original_1 AND
                t_lieux.code_original_2 = w_PASSAGE_NGAP.code_original_2 AND
                t_lieux.code_original_3 = w_PASSAGE_NGAP.code_original_3 AND
                t_lieux.code_original_4 = w_PASSAGE_NGAP.code_original_4 AND
                t_lieux.code_original_5 = w_PASSAGE_NGAP.code_original_5 AND
                t_lieux.code_original_6 = NGAP_UFXCODE
                ;

                INSERT INTO activite[PX].p_factures_lignes_h(
                    no_facture,
                    date_debut,
                    date_fin,
                    coefficient,
                    coefficient_mco,
                    prestation_id,
                    nb_rubrique,
                    nb_prestation,
                    prix_unitaire,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    montant_facture,
                    montant_facture_0,
                    montant_facture_1,
                    montant_facture_2,
                    montant_facture_22,
                    montant_comptabilise,
                    montant_comptabilise_0,
                    montant_comptabilise_1,
                    montant_comptabilise_2,
                    montant_comptabilise_22,
                    lieu_id,
                    montant_depassement,
                    acte_id,
                    medecin_facture_id,
                    medecin_comptabilise_id,
                    heure_debut,
                    phase_ccam,
                    activite_ccam,
                    extension_ccam,
                    modificateur_ccam_1,
                    modificateur_ccam_2,
                    modificateur_ccam_3,
                    modificateur_ccam_4,
                    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,
                    facture_id,
                    protocole_id,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    montant_non_facture
                )
                SELECT
                    w_PASSAGE_NGAP_facture.no_facture,
                    date(NGAP_DATE) AS date_debut,
                    date(NGAP_DATE) AS date_fin,
                    CASE WHEN CT_COEF = NGAP_COEF THEN CT_COEF ELSE CT_COEF * NGAP_COEF END AS coefficient,
                    1 AS coefficient_mco,
                    COALESCE(t_prestations.oid, 0) AS prestation_id,
                    NGAP_NB AS nb_rubrique,
                    NGAP_NB AS nb_prestation,
                    LC_PRIX AS prix_unitaire,
                    0 AS taux_0,
                    0 AS taux_1,
                    0 AS taux_2,
                    0 AS taux_22,
                    NGAP_NB * (CASE WHEN CT_COEF = NGAP_COEF THEN CT_COEF ELSE CT_COEF * NGAP_COEF END ) * LC_PRIX AS montant_facture,
                    0 AS montant_facture_0,
                    NGAP_NB * (CASE WHEN CT_COEF = NGAP_COEF THEN CT_COEF ELSE CT_COEF * NGAP_COEF END ) * LC_PRIX AS montant_facture_1,
                    0 AS montant_facture_2,
                    0 AS montant_facture_22,
                    0 AS montant_comptabilise,
                    0 AS montant_comptabilise_0,
                    0 AS montant_comptabilise_1,
                    0 AS montant_comptabilise_2,
                    0 AS montant_comptabilise_22,
                    PASSAGE_NGAP.lieu_id AS lieu_id,
                    0 AS montant_depassement,
					COALESCE(t_actes.oid,0) AS acte_id,
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,
                    to_char(NGAP_HEURE,'HH24MISS')::numeric AS heure_debut,
                    '' AS phase_ccam,
                    '' AS activite_ccam,
                    '' AS extension_ccam,
                    '' AS modificateur_ccam_1,
                    '' AS modificateur_ccam_2,
                    '' AS modificateur_ccam_3,
                    '' AS modificateur_ccam_4,
                    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,
                    w_PASSAGE_NGAP_facture.facture_id,
                    0 AS protocole_id,
                    COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
                    COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
                    0 AS montant_non_facture
                FROM w_PASSAGE_NGAP PASSAGE_NGAP
				JOIN w_PASSAGE_NGAP_facture ON PASSAGE_NGAP.oid = w_PASSAGE_NGAP_facture.oid
				LEFT JOIN activite.t_prestations ON t_prestations.code = CT_LET
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = NGAP_CTCODE
				LEFT JOIN base.t_actes ON t_actes.code = CT_LET
				LEFT JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original = NGAP_INXCODE
                WHERE CT_LET NOT IN ('SE1','SE2','SE3','SE4','SE5','SE6', 'SE7','ATU', 'FPU','FFM') 
                ;




                DROP TABLE IF EXISTS w_PASSAGE_CDAM;
				CREATE TEMP TABLE w_PASSAGE_CDAM AS
				SELECT row_number() OVER () AS oid,
					0 as lieu_id,
                    code_original_1,
                    code_original_2,
                    code_original_3,
                    code_original_4,
                    code_original_5,
                    PASSAGE_CDAM.*
				FROM prod_cerner.PASSAGE_CDAM
				JOIN activite[PX].p_sejours ON no_sejour = CDAM_HONUM
				JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
				;

				ANALYSE w_PASSAGE_CDAM
				;

				CREATE INDEX w_PASSAGE_CDAM_oid
							ON w_PASSAGE_CDAM
							USING btree
							(oid);

                INSERT INTO activite[PX].t_lieux(
                    code_original_1, code_original_2, code_original_3, code_original_4, code_original_5, code_original_6)
                SELECT
                    w_PASSAGE_CDAM.code_original_1,
                    w_PASSAGE_CDAM.code_original_2,
                    w_PASSAGE_CDAM.code_original_3,
                    w_PASSAGE_CDAM.code_original_4,
                    w_PASSAGE_CDAM.code_original_5,
                    CDAM_UFXCODE
                FROM w_PASSAGE_CDAM
                    LEFT JOIN activite[PX].t_lieux ON (
                        t_lieux.code_original_1 = w_PASSAGE_CDAM.code_original_1 AND
                        t_lieux.code_original_2 = w_PASSAGE_CDAM.code_original_2 AND
                        t_lieux.code_original_3 = w_PASSAGE_CDAM.code_original_3 AND
                        t_lieux.code_original_4 = w_PASSAGE_CDAM.code_original_4 AND
                        t_lieux.code_original_5 = w_PASSAGE_CDAM.code_original_5 AND
                        t_lieux.code_original_6 = CDAM_UFXCODE
                        )
                WHERE t_lieux.oid IS NULL
                GROUP BY 1,2,3,4,5,6
                ;

                UPDATE w_PASSAGE_CDAM
                SET lieu_id = t_lieux.oid
                FROM activite[PX].t_lieux
                WHERE t_lieux.code_original_1 = w_PASSAGE_CDAM.code_original_1 AND
                    t_lieux.code_original_2 = w_PASSAGE_CDAM.code_original_2 AND
                    t_lieux.code_original_3 = w_PASSAGE_CDAM.code_original_3 AND
                    t_lieux.code_original_4 = w_PASSAGE_CDAM.code_original_4 AND
                    t_lieux.code_original_5 = w_PASSAGE_CDAM.code_original_5 AND
                    t_lieux.code_original_6 = CDAM_UFXCODE
                ;
                
				DROP TABLE IF EXISTS w_PASSAGE_CDAM_facture;
				CREATE TEMP TABLE w_PASSAGE_CDAM_facture AS
				SELECT PASSAGE_CDAM.oid,
					CDAM_HONUM AS HONUM,
					MAX(no_facture) AS no_facture,
					(MAX(ARRAY[no_facture,p_factures.oid::text]))[2]::bigint AS facture_id,
					MAX(p_sejours.lieu_sortie_id) AS lieu_sortie_id
				FROM w_PASSAGE_CDAM PASSAGE_CDAM
				JOIN activite[PX].p_sejours ON CDAM_HONUM = p_sejours.no_sejour AND p_sejours.etat = ''
                JOIN activite[PX].p_factures ON CDAM_HONUM = p_factures.no_sejour AND
                        p_factures.no_facture = p_factures.no_facture_reference AND
                        CDAM_DATE BETWEEN p_factures.date_debut AND p_factures.date_fin
                GROUP BY 1,2
                ;

                ANALYSE w_PASSAGE_CDAM_facture
                ;

                CREATE INDEX w_PASSAGE_CDAM_facture_HONUM
					ON w_PASSAGE_CDAM_facture
					USING btree
					(HONUM);


                INSERT INTO activite[PX].p_factures_lignes_h(
                    no_facture,
                    date_debut,
                    date_fin,
                    coefficient,
                    coefficient_mco,
                    prestation_id,
                    nb_rubrique,
                    nb_prestation,
                    prix_unitaire,
                    taux_0,
                    taux_1,
                    taux_2,
                    taux_22,
                    montant_facture,
                    montant_facture_0,
                    montant_facture_1,
                    montant_facture_2,
                    montant_facture_22,
                    montant_comptabilise,
                    montant_comptabilise_0,
                    montant_comptabilise_1,
                    montant_comptabilise_2,
                    montant_comptabilise_22,
                    lieu_id,
                    montant_depassement,
                    acte_id,
                    medecin_facture_id,
                    medecin_comptabilise_id,
                    heure_debut,
                    phase_ccam,
                    activite_ccam,
                    extension_ccam,
                    modificateur_ccam_1,
                    modificateur_ccam_2,
                    modificateur_ccam_3,
                    modificateur_ccam_4,
                    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,
                    facture_id,
                    protocole_id,
                    rubrique_facturation_id,
                    rubrique_comptabilisation_id,
                    montant_non_facture
                )
                SELECT
                    w_PASSAGE_CDAM_facture.no_facture,
                    date(CDAM_DATE) AS date_debut,
                    date(CDAM_DATE) AS date_fin,
                    1 AS coefficient,
                    1 AS coefficient_mco,
                    t_prestations.oid AS prestation_id,
                    1 AS nb_rubrique,
                    1 AS nb_prestation,
                    PRIX_ACTE * CASE CDAM_CCAM_ASSNOPREV WHEN '2' THEN 0.5 WHEN '3' THEN 0.75 ELSE 1 END AS prix_unitaire,
                    0 AS taux_0,
                    0 AS taux_1,
                    0 AS taux_2,
                    0 AS taux_22,
                    PRIX_ACTE * CASE CDAM_CCAM_ASSNOPREV WHEN '2' THEN 0.5 WHEN '3' THEN 0.75 ELSE 1 END AS montant_facture,
                    0 AS montant_facture_0,
                    PRIX_ACTE * CASE CDAM_CCAM_ASSNOPREV WHEN '2' THEN 0.5 WHEN '3' THEN 0.75 ELSE 1 END AS montant_facture_1,
                    0 AS montant_facture_2,
                    0 AS montant_facture_22,
                    0 AS montant_comptabilise,
                    0 AS montant_comptabilise_0,
                    0 AS montant_comptabilise_1,
                    0 AS montant_comptabilise_2,
                    0 AS montant_comptabilise_22,
                    PASSAGE_CDAM.lieu_id AS lieu_id,
                    0 AS montant_depassement,
					COALESCE(t_actes.oid,0) AS acte_id,
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,
                    to_char(CDAM_HEURE,'HH24MISS')::numeric AS heure_debut,
                    CDAM_CCAM_PHASTRAIT::text AS phase_ccam,
                    CDAM_CCAM_ACTIVITE AS activite_ccam,
                    CDAM_CCAM_EXTDOC AS extension_ccam,
                    CDAM_CCAM_MODIF1 AS modificateur_ccam_1,
                    CDAM_CCAM_MODIF2 AS modificateur_ccam_2,
                    CDAM_CCAM_MODIF3 AS modificateur_ccam_3,
                    CDAM_CCAM_MODIF4 AS modificateur_ccam_4,
                    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,
                    w_PASSAGE_CDAM_facture.facture_id,
                    0 AS protocole_id,
                    COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
                    COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
                    0 AS montant_non_facture
                FROM w_PASSAGE_CDAM PASSAGE_CDAM
				JOIN activite[PX].p_sejours ON CDAM_HONUM = p_sejours.code_original AND p_sejours.etat = ''
				JOIN w_PASSAGE_CDAM_facture ON PASSAGE_CDAM.oid = w_PASSAGE_CDAM_facture.oid
				JOIN base.t_actes ON CDAM_CODEACTE = t_actes.code
				JOIN base.t_ccam_regroupements ON 
					(t_actes.ccam_regroupement_id_1 = t_ccam_regroupements.oid AND CDAM_CCAM_ACTIVITE <> '4' OR
					t_actes.ccam_regroupement_id_4 = t_ccam_regroupements.oid AND CDAM_CCAM_ACTIVITE = '4'
					)
				LEFT JOIN activite.t_prestations ON t_prestations.code = t_ccam_regroupements.code
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = t_ccam_regroupements.code
				LEFT JOIN activite[PX].t_medecins_administratifs ON t_medecins_administratifs.code_original = CDAM_INXCODE
                ;
				
				ANALYSE activite[PX].p_factures_lignes_h
				;				
				
				
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_1');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_2');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_3');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_4');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_5');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_6');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_7');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_8');
				SELECT base.cti_enable_index('activite', 'i_factures_lignes_h_9');
				
				-- Supplément F
				UPDATE activite[PX].p_factures_lignes_h SET
					prix_unitaire = prix_unitaire + 19.06,
					montant_facture = montant_facture + 19.06,
					montant_facture_1 = montant_facture_1 + 19.06
				WHERE montant_facture > 0 AND
					(
					modificateur_ccam_1 = 'F' OR
					modificateur_ccam_2 = 'F' OR
					modificateur_ccam_3 = 'F' OR
					modificateur_ccam_4 = 'F'
					)
				;
				
				-- Supplément M
				UPDATE activite[PX].p_factures_lignes_h SET
					prix_unitaire = prix_unitaire + 26.88,
					montant_facture = montant_facture + 26.88,
					montant_facture_1 = montant_facture_1 + 26.88
				WHERE montant_facture > 0 AND
					(
					modificateur_ccam_1 = 'M' OR
					modificateur_ccam_2 = 'M' OR
					modificateur_ccam_3 = 'M' OR
					modificateur_ccam_4 = 'M'
					)
				;
				
				-- Supplément P
				UPDATE activite[PX].p_factures_lignes_h SET
					prix_unitaire = prix_unitaire + 35,
					montant_facture = montant_facture + 35,
					montant_facture_1 = montant_facture_1 + 35
				WHERE montant_facture > 0 AND
					(
					modificateur_ccam_1 = 'P' OR
					modificateur_ccam_2 = 'P' OR
					modificateur_ccam_3 = 'P' OR
					modificateur_ccam_4 = 'P'
					)
				;
				
				-- Comptabilbilité lettre clé G uniquement avec ECG
				UPDATE activite[PX].p_factures_lignes_h SET
					montant_facture = 0,
					montant_facture_1 = 0
				FROM
				(
				SELECT p_factures_lignes_h.no_facture,
					p_factures_lignes_h.date_debut,
					p_factures_lignes_h.medecin_facture_id,
					subview.prestation_id
				FROM activite[PX].p_factures_lignes_h
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				JOIN base.t_actes ON acte_id = t_actes.oid
				JOIN
				(
				SELECT p_factures_lignes_h.no_facture,
					p_factures_lignes_h.date_debut,
					p_factures_lignes_h.medecin_facture_id,
					p_factures_lignes_h.prestation_id
				FROM activite[PX].p_factures_lignes_h
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE t_prestations.code IN ('G','GS') AND
					montant_facture <> 0
				GROUP BY 1,2,3,4
				) subview ON
					p_factures_lignes_h.no_facture = subview.no_facture AND
					p_factures_lignes_h.date_debut = subview.date_debut AND
					p_factures_lignes_h.medecin_facture_id = subview.medecin_facture_id
				WHERE t_prestations.code = 'ATM' AND
					t_actes.code NOT LIKE 'DEQP%'
				GROUP BY 1,2,3,4
				) subview
				WHERE p_factures_lignes_h.no_facture = subview.no_facture AND
					p_factures_lignes_h.date_debut = subview.date_debut AND
					p_factures_lignes_h.medecin_facture_id = subview.medecin_facture_id AND
					p_factures_lignes_h.prestation_id = subview.prestation_id
				;
                
                UPDATE activite[PX].p_factures_lignes_h
                SET lieu_id = p_sejours.lieu_sortie_id
                FROM 
                    activite[PX].p_factures
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                WHERE
                    p_factures_lignes_h.no_facture = p_factures.no_facture AND
                    (p_factures_lignes_h.lieu_id = 0 OR
                       (SELECT count(*) FROM activite.t_divers WHERE code = 'CERNER_LIEU_H' AND valeur = '1') = 0)
                ;
                
                -- UPDATE activite[PX].p_factures_lignes_h
                -- SET lieu_id = p_mouvements_sejour.lieu_id
                -- FROM 
                --     activite[PX].p_factures , 
                --     activite[PX].p_sejours , 
                --     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
                --     p_factures.no_sejour = p_sejours.no_sejour AND
                --     p_factures_lignes_h.date_fin = p_mouvements_sejour.date AND
                --     (230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
                --     nb_entrees_directes = 1 AND heure_fin = 240000 OR 
                --     nb_sorties_directes = 1 ) AND
                --     (p_factures_lignes_h.lieu_id = 0 OR 
                --     (p_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id AND
                --        (SELECT count(*) FROM activite.t_divers WHERE code = 'CERNER_LIEU_H' AND valeur = '1') = 0) OR
                --      (p_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id AND
                --       p_factures_lignes_h.lieu_id <> lieu_sortie_id AND
                --        (SELECT count(*) FROM activite.t_divers WHERE code = 'CERNER_LIEU_H' AND valeur = '1') = 1))
                -- ;
                
                UPDATE activite[PX].p_factures_lignes_h
                SET lieu_id = p_mouvements_sejour.lieu_id
                FROM 
                    activite[PX].p_factures , 
                    activite[PX].p_sejours , 
                    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
                    p_factures.no_sejour = p_sejours.no_sejour AND
                    p_factures_lignes_h.date_fin = p_mouvements_sejour.date AND
                    (230000 BETWEEN p_mouvements_sejour.heure_debut AND p_mouvements_sejour.heure_fin OR 
                    nb_entrees_directes = 1 AND heure_fin = 240000 OR 
                    nb_sorties_directes = 1 ) AND
                    (p_factures_lignes_h.lieu_id = 0 OR 
                    (p_factures_lignes_h.lieu_id <> p_mouvements_sejour.lieu_id AND
                       (SELECT count(*) FROM activite.t_divers WHERE code = 'CERNER_LIEU_H' AND valeur = '1') = 0)
                      )
                ;
               
			]]></sqlcmd>
		</NODE>

	
		<NODEx label="Compte client Honoraires">
			<sqlcmd><![CDATA[
			
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_h_1');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_h_3');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_h_4');
				SELECT base.cti_disable_index('activite', 'i_factures_soldes_h_8');
			
				INSERT INTO activite[PX].p_factures_soldes_h(
					facture_id,
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_comptabilisee_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
					facture_id,
					no_facture,
					date_trunc('month',date_vente) + interval '1 month' - interval '1 day',
					medecin_comptabilise_id,
					prestation_id,
					rubrique_facturation_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_factures_lignes_h
				WHERE date_vente >= '[ENV_ADM_ANNEEDEBUT]0101' 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,5,6;

				DROP TABLE IF EXISTS w_medecins_3;
				CREATE TEMP TABLE w_medecins_3 AS
				SELECT
					base.cti_to_number(right(code_original,3)) AS code_3,
					MAX(oid) AS medecin_administratif_id
				FROM activite[PX].t_medecins_administratifs
				GROUP BY 1;


				INSERT INTO activite[PX].p_factures_soldes_h(
					facture_id,
					no_facture, 
					date_comptable, 
					medecin_comptabilise_id, 
					prestation_id,
					rubrique_comptabilisee_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_factures.oid AS facture_id,
					no_facture,
					(to_char(ACSDTF,'FM00')||to_char(ACADTF,'FM00')||to_char(ACMDTF,'FM00')||'01')::date,
					COALESCE(w_medecins_3.medecin_administratif_id,0) AS medecin_comptabilise_id, 
					0::bigint AS rubrique_comptabilisation_id,
					0::bigint AS prestation_id,
					0,
					0,
					0,
					0,
					0,
					SUM(0-ACMTFC) AS montant_regle,
					SUM(CASE WHEN ACINDI = 3 THEN 0-ACMTFC ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN ACINDI = 1 THEN 0-ACMTFC ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN ACINDI = 2 THEN 0-ACMTFC ELSE 0 END) AS montant_regle_2,
					0 AS montant_regle_22
				FROM prod_chataigneraie_as400.NXXXFAC_FACTURES FACTURES
				JOIN w_NDOADM_SELECT ON w_NDOADM_SELECT.NONUMA = FACTURES.NONUMA
				JOIN prod_chataigneraie_as400.XXXFICH_REGLI REGLI ON FACTURES.FAID = REGLI.ACNFAC
				JOIN w_factures ON REGLI.ACNFAC = w_factures.FAID
				LEFT JOIN w_medecins_3 ON w_medecins_3.code_3 = ACMED
				WHERE ACSDTF*100+ACADTF >= [ENV_ADM_ANNEEDEBUT] AND
					ACID > 100
				GROUP BY 1,2,3,4,5,6
				;
				
				
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_h_1');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_h_3');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_h_4');
				SELECT base.cti_enable_index('activite', 'i_factures_soldes_h_8');
						
										
			]]></sqlcmd>
		</NODEx>
		
		<NODE label="Rejets">
			<sqlcmd><![CDATA[
	
				INSERT INTO activite[PX].p_factures_rejets(
					no_facture, date_rejet, rejet_id, rejet_code, rejet_texte)
				SELECT 
					NOE_DET_FAC_NUM,
					date(NOE_DET_DATE_LOT) , 
					0,
					TRIM(NOE_290_CODIF) ,
					TRIM(NOE_290_LIBELLE)
				FROM prod_cerner.NOEMIE_DETAIL
				JOIN prod_cerner.NOEMIE_290 ON NOE_DET_ID = NOE_290_DET_ID
				JOIN activite[PX].p_factures ON split_part(no_facture,'.',1) = NOE_DET_FAC_NUM 
				WHERE NOE_DET_FAC_NUM <> 0
				;
					
				INSERT INTO activite[PX].t_rejets_noemie (texte, code)
				SELECT rejet_texte, MAX(rejet_code) 
				FROM activite[PX].p_factures_rejets
				LEFT JOIN activite[PX].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[PX].t_rejets_noemie
				WHERE rejet_texte = t_rejets_noemie.texte;
	
		
			]]></sqlcmd>
		</NODE>
		
		
		
		
	</NODE>
	
	<NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
		
		<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(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN date_trunc('month',MC_DATECR) ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) AS date_comptable,
					SUM(
						CASE WHEN MC_NUMV <> 0 AND
							MC_TYPE <> 'IRR' AND
							MC_OD <> 'X' AND
							MC_JRN = 'JV' THEN
							CASE WHEN MC_SENS = 'D' THEN MC_MON ELSE 0-MC_MON END
						ELSE 0 END
					) AS montant_ventes_c,
					SUM(
						CASE WHEN MC_JRN <> 'JV' THEN
							CASE WHEN MC_SENS = 'C' THEN MC_MON ELSE 0-MC_MON END
						ELSE 0 END::numeric
					) AS montant_reglements_c, 
					0::numeric AS montant_solde_client_c,
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h,
					0::numeric AS montant_solde_client_h
				FROM prod_cerner.MOUV_COMPTA
				WHERE (MC_COMPTE LIKE '411%' OR MC_COMPTE LIKE '412%' OR MC_COMPTE LIKE '413%' OR MC_COMPTE LIKE '414%' OR MC_COMPTE LIKE '452%' OR MC_COMPTE LIKE '467%') AND
					date(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN MC_DATECR ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) >= '[ENV_ADM_ANNEEDEBUT]0101' 
				GROUP BY 1;
				
				
				-- Justificatif par facture
				

				DROP TABLE IF EXISTS w_factures_comptables;
				CREATE TEMP TABLE w_factures_comptables AS
				SELECT 
					MC_NUMV::text AS no_facture,
					date(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN MC_DATECR ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) AS date_comptable,
					SUM(CASE WHEN MC_SENS = 'D' THEN MC_MON ELSE 0-MC_MON END) AS montant_ventes_c,
					0::numeric AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_cerner.MOUV_COMPTA
				WHERE MC_NUMV <> 0 AND
					(MC_COMPTE LIKE '411%' OR MC_COMPTE LIKE '412%' OR MC_COMPTE LIKE '413%' OR MC_COMPTE LIKE '414%' OR MC_COMPTE LIKE '452%' OR MC_COMPTE LIKE '467%') AND
					MC_TYPE <> 'IRR' AND
					MC_OD <> 'X' AND
					MC_JRN = 'JV' AND
					date(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN MC_DATECR ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2
				;

				
				-- Ajustement des factures trouvées dans les ecritures pour ajouter les séances
				
				DROP TABLE IF EXISTS w_factures_eclatees;
				CREATE TEMP TABLE w_factures_eclatees AS 
				SELECT
					split_part(no_facture,'.',1)::numeric AS no_facture,
					MAX(date_vente) AS date_vente,
					SUM(montant_comptabilise_c) AS montant_comptabilise_c,
					MIN(no_facture) AS no_facture_1,
					base.cti_array_accum(no_facture) AS no_factures_array,
					count(*) AS nb
				FROM activite[PX].p_factures
				WHERE date_vente >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1
				;
				
				-- Attribuer le bon n° de facture si une seule
				UPDATE w_factures_comptables
				SET no_facture = no_facture_1
				FROM w_factures_eclatees
				WHERE w_factures_comptables.no_facture = w_factures_eclatees.no_facture AND
					w_factures_comptables.date_comptable = w_factures_eclatees.date_vente AND
					w_factures_eclatees.nb = 1 AND
					w_factures_comptables.no_facture <> no_facture_1
				;


				

				-- Eclater si plusieurs
				DELETE FROM w_factures_eclatees WHERE nb = 1;

				INSERT INTO w_factures_comptables(
					no_facture,
					date_comptable, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h)
				SELECT p_factures.no_facture, 
					p_factures.date_vente, 
					p_factures.montant_comptabilise_c, 
					0,
					0,
					0
				FROM w_factures_comptables
				JOIN w_factures_eclatees ON 
					w_factures_comptables.no_facture = w_factures_eclatees.no_facture AND
					w_factures_comptables.date_comptable = w_factures_eclatees.date_vente AND
					w_factures_comptables.montant_ventes_c = w_factures_eclatees.montant_comptabilise_c
				JOIN activite[PX].p_factures ON p_factures.no_facture = ANY(no_factures_array) AND
					p_factures.no_facture <> w_factures_eclatees.no_facture_1
				;

				UPDATE w_factures_comptables
				SET no_facture = no_facture_1, 
					montant_ventes_c = p_factures.montant_comptabilise_c
				FROM w_factures_eclatees
				JOIN activite[PX].p_factures ON p_factures.no_facture = no_facture_1
				WHERE w_factures_comptables.no_facture = w_factures_eclatees.no_facture AND
					w_factures_comptables.date_comptable = w_factures_eclatees.date_vente 
				;

				-- Ajout des règlements (déjà éclatés)
				INSERT INTO w_factures_comptables
				SELECT 
					MC_FACNUM_CTI::text AS no_facture,
					date(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN MC_DATECR ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) AS date_comptable,
					0 AS montant_ventes_c,
					SUM(MC_MON_REG) AS montant_reglements_c, 
					0 AS montant_ventes_h, 
					0 AS montant_reglements_h
				FROM w_MOUV_COMPTA_REG
				WHERE date(CASE WHEN date_part('year',MC_DATECR) = MC_EXER THEN MC_DATECR ELSE to_date(MC_EXER||'-12-31','YYYY-MM-DD') END) >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2
				;

				-- Validation
				
				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 no_facture,
					date_comptable,
					SUM(montant_ventes_c),
					SUM(montant_reglements_c),
					0 AS montant_ventes_h, 
					0 AS montant_reglements_h
				FROM w_factures_comptables
				GROUP 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="Initialisation paramétres divers">
			<sqlcmd><![CDATA[
			
				INSERT INTO activite.t_divers(code, texte, valeur, description)
				SELECT 
					'CERNER_SALLE=ETAGE',
					'1=La salle est l''étage',
					'0',
					'1=La salle est l''étage'
				WHERE 'CERNER_SALLE=ETAGE' NOT IN (SELECT code FROM activite.t_divers);
				
				INSERT INTO activite.t_divers(code, texte, valeur, description)
				SELECT 
					'CERNER_RAISONURGENCE',
					'Codes raison pour séjour en urgence',
					'',
					'Codes séparés par une virgule'
				WHERE 'CERNER_RAISONURGENCE' NOT IN (SELECT code FROM activite.t_divers);
				
				INSERT INTO activite.t_divers(code, texte, valeur, description)
				SELECT 
					'CERNER_RAISONSEANCE',
					'Codes raison pour les séances',
					'',
					'Codes séparés par une virgule'
				WHERE 'CERNER_RAISONSEANCE' NOT IN (SELECT code FROM activite.t_divers);
				
                INSERT INTO activite.t_divers(code, texte, valeur, description)
				SELECT 
					'CERNER_LIEU_H',
					'1=récupérer lieu exécution acte',
					'0',
					'0=ne pas récupérer, prendre celui du séjour ou du mouvement si différent 1=récupérer lieu exécution acte en priorité'
				WHERE 'CERNER_LIEU_H' NOT IN (SELECT code FROM activite.t_divers);
				
			]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Préparation mouvements">
			<sqlcmd><![CDATA[
			
		
				-- Selon utilisation l'étage est dans MH_UFHEBER ou dans MH_SACODE
				-- Donc préparation d'un fichier qui contient les bon champs selon paramétrage
				
				

				DROP TABLE IF EXISTS w_MOUV_HOSPI_source;
				CREATE TEMP TABLE w_MOUV_HOSPI_source AS
				SELECT MOUV_HOSPI.*,
					MH_UFCODE AS MH_UMCODE,
					HO_MANUMDOS AS MH_MANUMDOS,
					CASE 
						WHEN t_divers.valeur = '2' AND SA_CODE IS NOT NULL AND SA_UFHEBERG <> '' THEN SA_UFHEBERG
                        WHEN t_divers.valeur = '1' THEN MH_SACODE
						WHEN MH_UFHEBER <> '' THEN MH_UFHEBER
                        WHEN SA_CODE IS NOT NULL AND SA_UFHEBERG <> '' THEN SA_UFHEBERG
						ELSE MH_UFCODE
						END AS MH_ETCODE_CTI,
					CASE 
						WHEN t_divers.valeur = '1' THEN CASE WHEN MH_SACODE <> '' THEN CASE WHEN MH_LICODE <> '' THEN MH_LICODE ELSE '0' END ELSE '' END
						ELSE CASE WHEN MH_LICODE <> '' AND MH_LICODE <> MH_UFCODE AND MH_LICODE <> MH_UFHEBER THEN MH_LICODE WHEN MH_SACODE <> '' AND MH_SACODE <> MH_UFCODE AND MH_SACODE <> MH_UFHEBER THEN MH_SACODE ELSE '0' END
						END AS MH_LICODE_CTI,
					''::text AS MH_ELCODE_CTI
				FROM prod_cerner.MOUV_HOSPI
				JOIN prod_cerner.HOSPITALISATION ON HO_NUM = MH_HONUM
                LEFT JOIN prod_cerner.SALLE ON MH_SACODE = SA_CODE
				JOIN activite.t_divers ON t_divers.code = 'CERNER_SALLE=ETAGE'

				;
				
				UPDATE w_MOUV_HOSPI_source
				SET MH_DFIN = '20991231', MH_HFIN = now()
				WHERE MH_DFIN IS NULL
				;


				-- Modification Spécifique SJSL pour les urgences (nouvelle version CERNER)
				UPDATE w_MOUV_HOSPI_source
				SET MH_UFCODE = 'UR21', MH_COMM = '*URG*'
				WHERE MH_URGORG = 'UR21'  AND MH_UFCODE <> 'CS21' AND MH_UFCODE <> 'UR21' AND MH_DDEB >= '[ENV_ADM_ANNEEDEBUT]0101' 
				;
				
				UPDATE w_MOUV_HOSPI_source
				SET MH_UFHEBER = 'UR00', MH_COMM = '*URG*'
				WHERE MH_SACODE = 'UR00' AND MH_UFHEBER <> 'UR00' AND MH_DDEB >= '[ENV_ADM_ANNEEDEBUT]0101' 
				;


				CREATE INDEX w_MOUV_HOSPI_source_MH_MANUMDOS
					ON w_MOUV_HOSPI_source
					USING btree
					(MH_MANUMDOS);
				

				-- Spécifique Saint Joseph St Luc
				-- Le premier mouveement transfert urgence sur hospit = Etage = UR00
				UPDATE w_MOUV_HOSPI_source SET
					MH_ETCODE_CTI = 'UR00',  MH_LICODE_CTI = '0'
				WHERE MH_ID IN
				(
					SELECT w_MOUV_HOSPI_source_HOS.MH_ID
					FROM w_MOUV_HOSPI_source w_MOUV_HOSPI_source_URG
					JOIN w_MOUV_HOSPI_source w_MOUV_HOSPI_source_HOS ON
						w_MOUV_HOSPI_source_URG.MH_MANUMDOS = w_MOUV_HOSPI_source_HOS.MH_MANUMDOS AND
						w_MOUV_HOSPI_source_URG.MH_DDEB = w_MOUV_HOSPI_source_HOS.MH_DDEB AND
						to_char(w_MOUV_HOSPI_source_URG.MH_HDEB,'HH24MISS') = to_char(w_MOUV_HOSPI_source_HOS.MH_HDEB,'HH24MISS') AND
						w_MOUV_HOSPI_source_URG.MH_DFIN = w_MOUV_HOSPI_source_HOS.MH_DFIN AND
						to_char(w_MOUV_HOSPI_source_URG.MH_HFIN,'HH24MISS') = to_char(w_MOUV_HOSPI_source_HOS.MH_HFIN,'HH24MISS') AND
						w_MOUV_HOSPI_source_URG.MH_UFSOR =  w_MOUV_HOSPI_source_HOS.MH_UFCODE AND
						w_MOUV_HOSPI_source_URG.MH_HONUM <> w_MOUV_HOSPI_source_HOS.MH_HONUM
					JOIN base.t_finess ON t_finess.Code = '690805361'
					WHERE w_MOUV_HOSPI_source_URG.MH_RSCODSOR = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_RSCODENT = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_ETCODE_CTI <> 'UR00'
				)
				;

				UPDATE w_MOUV_HOSPI_source SET
					MH_ETCODE_CTI = 'UR00',  MH_LICODE_CTI = '0'
				WHERE MH_ID IN
				(
					SELECT w_MOUV_HOSPI_source_HOS.MH_ID
					FROM w_MOUV_HOSPI_source w_MOUV_HOSPI_source_URG
					JOIN w_MOUV_HOSPI_source w_MOUV_HOSPI_source_HOS ON
						w_MOUV_HOSPI_source_URG.MH_MANUMDOS = w_MOUV_HOSPI_source_HOS.MH_MANUMDOS AND
						w_MOUV_HOSPI_source_URG.MH_DDEB = w_MOUV_HOSPI_source_HOS.MH_DDEB AND
						to_char(w_MOUV_HOSPI_source_URG.MH_HDEB,'HH24MISS') = to_char(w_MOUV_HOSPI_source_HOS.MH_HDEB,'HH24MISS') AND
						w_MOUV_HOSPI_source_URG.MH_DFIN = w_MOUV_HOSPI_source_HOS.MH_DFIN AND
						to_char(w_MOUV_HOSPI_source_URG.MH_HFIN,'HH24MISS') = to_char(w_MOUV_HOSPI_source_HOS.MH_HFIN,'HH24MISS') AND
						w_MOUV_HOSPI_source_URG.MH_HONUM <> w_MOUV_HOSPI_source_HOS.MH_HONUM
					JOIN base.t_finess ON t_finess.Code = '690805361'
					WHERE w_MOUV_HOSPI_source_URG.MH_RSCODSOR = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_RSCODENT = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_ETCODE_CTI <> 'UR00'
				)
				;

				UPDATE w_MOUV_HOSPI_source SET
					MH_ETCODE_CTI = 'UR00',  MH_LICODE_CTI = '0'
				WHERE MH_ID IN
				(
					SELECT w_MOUV_HOSPI_source_HOS.MH_ID
					FROM w_MOUV_HOSPI_source w_MOUV_HOSPI_source_URG
					JOIN w_MOUV_HOSPI_source w_MOUV_HOSPI_source_HOS ON
						w_MOUV_HOSPI_source_URG.MH_MANUMDOS = w_MOUV_HOSPI_source_HOS.MH_MANUMDOS AND
						w_MOUV_HOSPI_source_URG.MH_DDEB = w_MOUV_HOSPI_source_HOS.MH_DDEB AND
						to_char(w_MOUV_HOSPI_source_URG.MH_HDEB,'HH24MISS') = to_char(w_MOUV_HOSPI_source_HOS.MH_HDEB,'HH24MISS') AND
						w_MOUV_HOSPI_source_URG.MH_HONUM <> w_MOUV_HOSPI_source_HOS.MH_HONUM
					JOIN base.t_finess ON t_finess.Code = '690805361'
					WHERE w_MOUV_HOSPI_source_URG.MH_RSCODSOR = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_RSCODENT = 'UH' AND
						w_MOUV_HOSPI_source_HOS.MH_ETCODE_CTI <> 'UR00'
				)
				;
				
				UPDATE w_MOUV_HOSPI_source
				SET MH_ELCODE_CTI = MH_ETCODE_CTI || '|' || MH_LICODE_CTI
				WHERE MH_LICODE_CTI <> ''
				;
				
				
				ANALYSE w_MOUV_HOSPI_source;
				
				CREATE INDEX w_MOUV_HOSPI_source_i1
					ON w_MOUV_HOSPI_source
					USING btree
					(MH_HONUM);
					
				CREATE INDEX w_MOUV_HOSPI_source_i2
					ON w_MOUV_HOSPI_source
					USING btree
					(MH_INCODE);
					
				CREATE INDEX w_MOUV_HOSPI_source_i3
					ON w_MOUV_HOSPI_source
					USING btree
					(MH_UFCODE);
					
					-- Fusion des urgences hospitalisés (SJSL < [ENV_ADM_ANNEEDEBUT]0630)
				DROP TABLE IF EXISTS w_FUSION_UR21;
				CREATE TEMP TABLE w_FUSION_UR21 AS
				SELECT MH_MANUMDOS, MH_DDEB, MH_HDEB, 
					MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_HONUM ELSE 0 END) AS MH_HONUM_urg,
					MAX(CASE WHEN MH_UFCODE <> 'UR21' THEN MH_HONUM ELSE 0 END) AS MH_HONUM_hos,
					MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_UFCODE ELSE '' END) AS MH_UFHEBER_urg,
					MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_ETCODE_CTI ELSE '' END) AS MH_ETCODE_CTI_urg,
					MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_LICODE_CTI ELSE '' END) AS MH_LICODE_CTI_urg,
					MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_ELCODE_CTI ELSE '' END) AS MH_ELCODE_CTI_urg
				FROM w_MOUV_HOSPI_source
				JOIN prod_cerner.HOSPITALISATION ON 
					HO_NUM = MH_HONUM AND
					MH_DDEB = HO_DDEB AND
					HO_VALID <> 'X'
				WHERE MH_UFCODE <> 'CS21'
				GROUP BY 1,2,3
				HAVING count(*) > 1 AND
				MAX(CASE WHEN MH_UFCODE = 'UR21' THEN MH_HONUM ELSE 0 END) > 0 AND
				MAX(CASE WHEN MH_UFCODE <> 'UR21' THEN MH_HONUM ELSE 0 END) > 0
				;

				UPDATE w_MOUV_HOSPI_source SET
					MH_UFCODE = 'UR21',
					MH_UFHEBER = MH_UFHEBER_urg,
					MH_ETCODE_CTI = MH_ETCODE_CTI_urg,
					MH_LICODE_CTI = MH_LICODE_CTI_urg,
					MH_ELCODE_CTI = MH_ELCODE_CTI_urg
				FROM w_FUSION_UR21
				WHERE w_MOUV_HOSPI_source.MH_HONUM = w_FUSION_UR21.MH_HONUM_hos AND
					w_MOUV_HOSPI_source.MH_DDEB = w_FUSION_UR21.MH_DDEB AND
					w_MOUV_HOSPI_source.MH_HDEB = w_FUSION_UR21.MH_HDEB
				;

				UPDATE prod_cerner.HOSPITALISATION
				SET HO_VALID = 'U'
				FROM w_FUSION_UR21
				WHERE HOSPITALISATION.HO_NUM = MH_HONUM_urg 
				;
					
			]]></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 activite[PX].t_tiers_payant(oid, code, code_original, type_tiers_payant, texte, texte_court) 
				SELECT 0, '', '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 'PATIENT', '*PATIENT', '0', 'PATIENTS', 'PATIENTS'
				WHERE '*PATIENT' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);

				DROP TABLE IF EXISTS w_PAYEUR;
				CREATE TEMP TABLE w_PAYEUR AS
				SELECT PY_TYPE, PY_CODE, 
				('C'||PY_TYPE||PY_CODE) AS tiers_payant_code_original, 
					CASE WHEN PY_TYPE IN ('1','2') THEN '1' ELSE '2' END AS PY_TYPE_CTI,
					(MAX(ARRAY[PY_DATCRE::text,PY_LIB]))[2] AS PY_LIB, 
					0::bigint AS tiers_payant_id
				FROM prod_cerner.PAYEUR
				GROUP BY 1,2
				ORDER BY 1,2
				;
			
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT tiers_payant_code_original,
					PY_CODE,
					PY_TYPE_CTI, 
					PY_LIB, 
					PY_LIB
				FROM w_PAYEUR
				WHERE tiers_payant_code_original NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL)
				ORDER BY 1;

				UPDATE activite[PX].t_tiers_payant SET
					code = PY_CODE,
					type_tiers_payant = PY_TYPE_CTI,
					texte = PY_LIB,
					texte_court = PY_LIB
				FROM w_PAYEUR
				WHERE tiers_payant_code_original = t_tiers_payant.code_original AND
					(
						PY_CODE IS DISTINCT FROM PY_CODE OR
						type_tiers_payant IS DISTINCT FROM PY_TYPE_CTI OR
						texte IS DISTINCT FROM PY_LIB OR
						texte_court IS DISTINCT FROM PY_LIB
					)
				;
				
				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM base.t_grands_regimes
				WHERE t_tiers_payant.code_original LIKE 'C%' AND
					length(t_tiers_payant.code_original) = 10 AND
					grand_regime_id = 0 AND
					t_grands_regimes.code = substr(t_tiers_payant.code_original,3,2);

				INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court) 
				SELECT 'MUTDIV', '*MUTDIV', '2', 'MUTUELLE DIVERSE', 'MUTUELLE DIVERSE'
				WHERE '*MUTDIV' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant WHERE code_original IS NOT NULL);


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

				INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
				SELECT 
					SP_CODE,
					SP_CODE,
					SP_LIB,
					SP_LIB
				FROM prod_cerner.SPECIALITE
					LEFT JOIN base.t_specialites_medecin on t_specialites_medecin.code = SP_CODE
				WHERE t_specialites_medecin.code IS NULL 
				ORDER BY 1;

				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_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);


				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;
				CREATE TEMP TABLE w_medecins AS
				SELECT 
					IN_CODE,
					base.cti_soundex_nom(IN_NOM) AS IN_NOM_SOUNDEX, 
					base.cti_soundex_nom(IN_PRENOM) AS IN_PRENOM_SOUNDEX, 
					IN_NOM, 
					IN_PRENOM AS IN_PRENOM, 
					SUBSTR(COALESCE(IN_IDNATIONAL,''),1,9) AS IN_IDNATIONAL, 
					IN_SPCODE,
					COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
				FROM prod_cerner.INTERVENANT
					LEFT JOIN activite[PX].t_medecins_administratifs ON IN_CODE = t_medecins_administratifs.code_original
				WHERE IN_CODE IN (SELECT IN_CODE FROM w_MOUV_HOSPI_source) OR
					IN_CODE IN (SELECT NGAP_INXCODE FROM prod_cerner.PASSAGE_NGAP)
				ORDER BY 2
				;
				
				

				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
				SELECT w_medecins.IN_NOM, w_medecins.IN_PRENOM, w_medecins.IN_IDNATIONAL, 0 FROM
				(SELECT SUBSTR(IN_NOM_SOUNDEX, 1, 8) AS IN_NOM_SOUNDEX, SUBSTR(IN_PRENOM_SOUNDEX, 1, 8) AS IN_PRENOM_SOUNDEX, IN_IDNATIONAL, MIN(IN_CODE) AS IN_CODE
				FROM w_medecins
				GROUP BY 1,2,3) subview, w_medecins
				WHERE w_medecins.IN_CODE = subview.IN_CODE
					AND subview.IN_NOM_SOUNDEX || ',' || subview.IN_PRENOM_SOUNDEX || ',' ||  subview.IN_IDNATIONAL 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.IN_NOM, w_medecins.IN_PRENOM, w_medecins.IN_IDNATIONAL, 0 FROM
				(SELECT IN_NOM_SOUNDEX, IN_PRENOM_SOUNDEX, MIN(IN_CODE) AS IN_CODE
				FROM w_medecins
				GROUP BY 1,2) subview, w_medecins
				WHERE w_medecins.IN_CODE = subview.IN_CODE
					AND subview.IN_NOM_SOUNDEX || ',' || subview.IN_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(IN_NOM_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(IN_PRENOM_SOUNDEX, 1, 8) = subview.prenom
				AND IN_IDNATIONAL = 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(IN_NOM_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(IN_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 IN_CODE, substr(translate(IN_NOM,' -=()''',''),1,5) || substr(translate(IN_PRENOM,' -=()''',''),1,2), IN_NOM, IN_PRENOM, COALESCE(t_specialites_medecin.oid,0), medecin_id
				FROM w_medecins
					LEFT JOIN base.t_specialites_medecin ON IN_SPCODE = t_specialites_medecin.code_original
				WHERE IN_CODE NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

				UPDATE activite[PX].t_medecins_administratifs
				SET code = substr(translate(IN_NOM,' -=()''',''),1,5) || substr(translate(IN_PRENOM,' -=()''',''),1,2),
					nom = IN_NOM,
					prenom = IN_PRENOM,
					specialite_id = COALESCE(t_specialites_medecin.oid,0),
					medecin_id = w_medecins.medecin_id,
					no_adeli = IN_IDNATIONAL
				FROM w_medecins LEFT JOIN base.t_specialites_medecin ON IN_SPCODE = t_specialites_medecin.code_original
				WHERE w_medecins.IN_CODE = t_medecins_administratifs.code_original
					AND 
				(
					t_medecins_administratifs.code <> substr(translate(IN_NOM,' -=()''',''),1,5) || substr(translate(IN_PRENOM,' -=()''',''),1,2) OR
					t_medecins_administratifs.nom <> IN_NOM OR
					t_medecins_administratifs.nom <> IN_NOM OR
					t_medecins_administratifs.prenom <> IN_PRENOM OR
					t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0) OR
					t_medecins_administratifs.medecin_id <> w_medecins.medecin_id OR 
					t_medecins_administratifs.no_adeli <> w_medecins.IN_IDNATIONAL
				);

				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;
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Hébergement">
			<sqlcmd><![CDATA[
				
				-- 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);

								
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
				SELECT UF_CODE, UF_CODE, UF_LIB, UF_LIB, 0 AS nb_lits, '0' AS type_t2a
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_services_facturation WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT MH_UFCODE FROM w_MOUV_HOSPI_source)
				ORDER BY UF_CODE;
				
				UPDATE activite[PX].t_services_facturation SET
					code = UF_CODE,
					texte = UF_LIB,
					texte_court = CASE WHEN texte_court = texte THEN UF_LIB ELSE texte_court END
				FROM prod_cerner.UF
				WHERE UF_CODE = code_original AND
					(
						code IS DISTINCT FROM UF_CODE OR
						texte IS DISTINCT FROM UF_LIB OR
						texte_court IS DISTINCT FROM CASE WHEN texte_court = texte THEN UF_LIB ELSE texte_court END
					)
				;

				INSERT INTO base.t_modes_traitement(code_original, code, texte, texte_court)
				SELECT UF_ACTIVITE, UF_ACTIVITE, UF_ACTIVITE, UF_ACTIVITE
				FROM prod_cerner.UF
				WHERE UF_ACTIVITE NOT IN (SELECT code FROM base.t_modes_traitement WHERE code IS NOT NULL) AND
					UF_ACTIVITE <> '' 
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
				SELECT UF_CODE, UF_CODE, UF_LIB, UF_LIB, 0 AS nb_lits, '0' AS type_t2a
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_services_facturation WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT NGAP_UFXCODE FROM prod_cerner.PASSAGE_NGAP)
				ORDER BY UF_CODE;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits, type_t2a)
				SELECT UF_CODE, UF_CODE, UF_LIB, UF_LIB, 0 AS nb_lits, '0' AS type_t2a
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_services_facturation WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT CDAM_UFXCODE FROM prod_cerner.PASSAGE_CDAM)
				ORDER BY UF_CODE;
				
				UPDATE activite[PX].t_services_facturation
				SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
				FROM prod_cerner.UF
					LEFT JOIN base.t_modes_traitement ON UF_ACTIVITE = t_modes_traitement.code
				WHERE t_services_facturation.code_original = UF_CODE AND 
					COALESCE(mode_traitement_id,0) = 0 AND
					COALESCE(mode_traitement_id,0) <> COALESCE(t_modes_traitement.oid,0);

				INSERT INTO base.t_dmt(code_original, code, texte, texte_court)
				SELECT DP_CODE, DP_CODE, DP_LIB, DP_LIB
				FROM prod_cerner.DISP_PRES
				WHERE DP_CODE NOT IN (SELECT code FROM base.t_dmt WHERE code IS NOT NULL) AND
					DP_CODE <> '' 
				GROUP BY 1,2,3,4
				ORDER BY 1;
				
				UPDATE activite[PX].t_services_facturation
				SET dmt_id = COALESCE(t_dmt.oid,0)
				FROM prod_cerner.UF
					LEFT JOIN base.t_dmt ON UF_DPCODE = t_dmt.code
				WHERE t_services_facturation.code_original = UF_CODE AND 
					COALESCE(dmt_id,0) = 0 AND
					COALESCE(dmt_id,0) <> COALESCE(t_dmt.oid,0);

				UPDATE activite[PX].t_services_facturation
				SET dmt_id = COALESCE(t_dmt.oid,0)
				FROM prod_cerner.UF
					LEFT JOIN base.t_dmt ON UF_DECODE = t_dmt.code
				WHERE t_services_facturation.code_original = UF_CODE AND 
					COALESCE(dmt_id,0) = 0 AND
					COALESCE(dmt_id,0) <> COALESCE(t_dmt.oid,0);

				-- 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 UF_CODE, UF_CODE, UF_LIB, UF_LIB
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT MH_UFCODE FROM w_MOUV_HOSPI_source)
				ORDER BY UF_CODE;
				
				INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT UF_CODE, UF_CODE, UF_LIB, UF_LIB
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT NGAP_UFXCODE FROM prod_cerner.PASSAGE_NGAP)
				ORDER BY UF_CODE;

				
				INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT UF_CODE, UF_CODE, UF_LIB, UF_LIB
				FROM prod_cerner.UF
				WHERE UF_CODE NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles WHERE code_original IS NOT NULL) AND
					UF_CODE IN (SELECT CDAM_UFXCODE FROM prod_cerner.PASSAGE_CDAM)
				ORDER BY UF_CODE;
				
				UPDATE activite[PX].t_unites_fonctionnelles SET
					code = UF_CODE,
					texte = UF_LIB,
					texte_court = CASE WHEN texte_court = texte THEN UF_LIB ELSE texte_court END
				FROM prod_cerner.UF
				WHERE UF_CODE = code_original AND
					(
						code IS DISTINCT FROM UF_CODE OR
						texte IS DISTINCT FROM UF_LIB OR
						texte_court IS DISTINCT FROM CASE WHEN texte_court = texte THEN UF_LIB ELSE texte_court END
					);
					
				-- 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 code_original, code, texte, texte_court
				FROM activite[PX].t_unites_fonctionnelles
				WHERE t_unites_fonctionnelles.oid <> 0 AND
					t_unites_fonctionnelles.code_original NOT IN (SELECT t_unites_medicales.code_original FROM activite[PX].t_unites_medicales WHERE code_original IS NOT NULL)
				ORDER BY code;

				
				UPDATE activite[PX].t_unites_medicales SET
					code = t_unites_fonctionnelles.code,
					texte = t_unites_fonctionnelles.texte,
					texte_court = t_unites_fonctionnelles.texte_court
				FROM activite[PX].t_unites_fonctionnelles
				WHERE t_unites_medicales.code_original = t_unites_fonctionnelles.code_original AND
					t_unites_medicales.oid <> 0 AND
					(
						t_unites_medicales.code IS DISTINCT FROM t_unites_fonctionnelles.code OR
						t_unites_medicales.texte IS DISTINCT FROM t_unites_fonctionnelles.texte OR
						t_unites_medicales.texte_court IS DISTINCT FROM t_unites_fonctionnelles.texte_court
					);

				-- Activités

				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);
				
				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
				SELECT RE_CODE, RE_CODE, RE_LIB, RE_LIB
				FROM prod_cerner.REGROUPEMENT
				WHERE RE_CODE NOT IN (SELECT code_original FROM activite[PX].t_activites WHERE code_original IS NOT NULL) AND
					RE_CODE IN (SELECT HO_RECODE FROM prod_cerner.HOSPITALISATION)
				ORDER BY RE_CODE;

				
				UPDATE activite[PX].t_activites SET
					code = RE_CODE,
					texte = RE_LIB,
					texte_court = RE_LIB
				FROM prod_cerner.REGROUPEMENT
				WHERE RE_CODE = code_original AND
					(
						t_activites.code IS DISTINCT FROM RE_CODE OR
						t_activites.texte IS DISTINCT FROM RE_LIB OR
						t_activites.texte_court IS DISTINCT FROM RE_LIB
					)
				;
				-- 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, nb_lits)
				SELECT MH_ETCODE_CTI, MH_ETCODE_CTI, MH_ETCODE_CTI, MH_ETCODE_CTI, 0
				FROM w_MOUV_HOSPI_source
				WHERE MH_ETCODE_CTI <> '' AND
					MH_ETCODE_CTI NOT IN (SELECT code_original FROM activite[PX].t_etages WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY MH_ETCODE_CTI;

				
				UPDATE activite[PX].t_etages SET
					code = UF_CODE,
					texte = UF_LIB,
					texte_court = CASE WHEN texte_court = t_etages.texte THEN UF_LIB ELSE t_etages.texte_court END
				FROM prod_cerner.UF
				JOIN activite.t_divers ON t_divers.code = 'CERNER_SALLE=ETAGE' AND t_divers.valeur IS DISTINCT FROM '1' 
				WHERE UF_CODE = code_original AND
					(
						t_etages.code IS DISTINCT FROM UF_CODE OR
						t_etages.texte IS DISTINCT FROM UF_LIB OR
						t_etages.texte_court IS DISTINCT FROM CASE WHEN texte_court = t_etages.texte THEN UF_LIB ELSE t_etages.texte_court END
					);

				UPDATE activite[PX].t_etages SET
					code = SA_CODE,
					texte = SA_LIB,
					texte_court = CASE WHEN texte_court = t_etages.texte THEN SA_LIB ELSE t_etages.texte_court END
				FROM prod_cerner.SALLE
				JOIN activite.t_divers ON t_divers.code = 'CERNER_SALLE=ETAGE' AND t_divers.valeur = '1'
				WHERE SA_CODE = code_original AND
					(
						t_etages.code IS DISTINCT FROM SA_CODE OR
						t_etages.texte IS DISTINCT FROM SA_LIB OR
						t_etages.texte_court IS DISTINCT FROM CASE WHEN texte_court = t_etages.texte THEN SA_LIB ELSE t_etages.texte_court END
					);

					

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

				DROP TABLE IF EXISTS w_lits;
				CREATE TEMP TABLE w_lits AS
				SELECT 
					MH_ETCODE_CTI AS etage_code,
					''::text AS etage_texte,
					MH_LICODE_CTI AS lit_code,
					''::text AS lit_texte,
					MH_ELCODE_CTI AS lit_code_original,
					0::bigint AS lit_id
				FROM w_MOUV_HOSPI_source
				WHERE MH_ELCODE_CTI <> ''
				GROUP BY 1,2,3,4,5,6
				ORDER BY 1,2,3,4,5,6;

				

				UPDATE w_lits
				SET lit_texte = LI_LIB
				FROM prod_cerner.LIT
				WHERE LI_CODE = lit_code
				;

				UPDATE w_lits
				SET lit_texte = SA_LIB
				FROM prod_cerner.SALLE
				WHERE SA_CODE = lit_code AND
					lit_texte = ''
				;


				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT lit_code_original, lit_code, lit_texte, lit_texte,
					t_etages.oid, CASE WHEN lit_texte ilike '%individuel%' THEN 'O' ELSE 'N' END AS chambre_particuliere
				FROM w_lits
					JOIN activite[PX].t_etages ON etage_code = t_etages.code_original
				WHERE lit_code_original <> '' AND
					lit_code_original NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4,5,6
				ORDER BY 1;

				UPDATE w_lits
				SET lit_id = t_lits.oid
				FROM activite[PX].t_lits 
				WHERE lit_code_original = t_lits.code_original
				;

				UPDATE activite[PX].t_lits SET
					code = lit_code,
					texte = lit_texte,
					texte_court = lit_texte
				FROM w_lits
				WHERE lit_code_original = code_original AND
					(
						t_lits.code IS DISTINCT FROM lit_code OR
						t_lits.texte IS DISTINCT FROM lit_texte OR
						t_lits.texte_court IS DISTINCT FROM lit_texte
					)
				;

				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 );
									
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Facturation">
			<sqlcmd><![CDATA[
				
				-- 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 CT_CODE, CT_CODE, MAX(CT_LIB), MAX(CT_LIB)
				FROM prod_cerner.CODE_TARIF
				WHERE CT_CODE <> '' AND
					CT_CODE NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;	

				UPDATE activite[PX].t_rubriques_facturation SET
					code = CT_CODE,
					texte = CT_LIB,
					texte_court = CT_LIB
				FROM 
					(
						SELECT 
							CT_CODE, 
							MAX(CT_LIB) AS CT_LIB
						FROM prod_cerner.CODE_TARIF
						WHERE CT_CODE <> ''
						GROUP BY 1
					) subview
				WHERE CT_CODE = code_original AND
					(
						t_rubriques_facturation.code IS DISTINCT FROM CT_CODE OR
						t_rubriques_facturation.texte IS DISTINCT FROM CT_LIB OR
						t_rubriques_facturation.texte_court IS DISTINCT FROM CT_LIB
					)
				;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT LC_CODE, LC_CODE, (MAX(ARRAY[LC_DDEB::text,LC_LIB]))[2], (MAX(ARRAY[LC_DDEB::text,LC_LIB]))[2]
				FROM prod_cerner.LETTRE_CLE
				WHERE LC_LIB <> '' AND
					LC_CODE NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT LC_CODE, LC_CODE, LC_CODE, LC_CODE
				FROM prod_cerner.LETTRE_CLE
				WHERE LC_LIB = '' AND
					LC_CODE NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;

				UPDATE activite[PX].t_rubriques_facturation SET
					code = LC_CODE,
					texte = LC_DDEB,
					texte_court = LC_DDEB
				FROM 
					(
						SELECT 
							LC_CODE,
							(MAX(ARRAY[LC_DDEB::text,LC_LIB]))[2] AS LC_DDEB
						FROM prod_cerner.LETTRE_CLE
						WHERE LC_CODE <> ''
						GROUP BY 1
					) subview
				WHERE LC_CODE = code_original AND
					(
						t_rubriques_facturation.code IS DISTINCT FROM LC_CODE OR
						t_rubriques_facturation.texte IS DISTINCT FROM LC_DDEB OR
						t_rubriques_facturation.texte_court IS DISTINCT FROM LC_DDEB
					)
				;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT CT_LET, CT_LET, MAX(CT_LIB), MAX(CT_LIB)
				FROM prod_cerner.CODE_TARIF
				WHERE CT_LET <> '' AND
					CT_LET NOT IN (SELECT LC_CODE FROM prod_cerner.LETTRE_CLE) AND
					CT_LET NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;	

				
				UPDATE activite[PX].t_rubriques_facturation
				SET texte = CT_LIB, texte_court = CT_LIB
				FROM
				(
					SELECT CT_LET, MAX(CT_LIB) AS CT_LIB
					FROM prod_cerner.CODE_TARIF
					JOIN activite[PX].t_rubriques_facturation ON CT_LET = code_original
					WHERE t_rubriques_facturation.code = t_rubriques_facturation.texte
					GROUP BY 1
					HAVING count(DISTINCT CT_LIB) = 1 AND
						MAX(CT_LIB) <> CT_LET
				) subview
				WHERE subview.CT_LET = t_rubriques_facturation.code_original
				;
				
				
				

				INSERT INTO activite.t_prestations(oid, code_original, code, texte, texte_court, clinique_honoraire) 
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée', '' WHERE 0 NOT IN (SELECT oid FROM activite.t_prestations);
				
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT CT_LET, CT_LET, MAX(CT_LIB), MAX(CT_LIB)
				FROM prod_cerner.CODE_TARIF
				WHERE CT_LET <> '' AND
					CT_LET 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 LC_CODEB2, LC_CODEB2, MAX(LC_CODEB2), MAX(LC_CODEB2)
				FROM prod_cerner.LETTRE_CLE
				WHERE LC_CODEB2 <> '' AND
					LC_CODEB2 NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1
				;
				

				
				
				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);
				
				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court) 
				SELECT MC_COMPTE,MC_COMPTE,MC_COMPTE,MC_COMPTE
				FROM prod_cerner.MOUV_COMPTA
				WHERE MC_COMPTE <> '' AND
					MC_COMPTE <> '0' AND
					MC_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1
				;

				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court) 
				SELECT FAD_COMPTE,FAD_COMPTE,FAD_COMPTE,FAD_COMPTE
				FROM prod_cerner.FACTURE_DET
				WHERE FAD_COMPTE <> '' AND
					FAD_COMPTE <> '0' AND
					FAD_COMPTE NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1
				;
										
				UPDATE activite[PX].t_compte SET
					code = MC_COMPTE,
					texte = MC_COMPTE,
					texte_court = MC_COMPTE
				FROM prod_cerner.MOUV_COMPTA
				WHERE MC_COMPTE = code_original AND
					(
						t_compte.code IS DISTINCT FROM MC_COMPTE OR
						t_compte.texte IS DISTINCT FROM MC_COMPTE OR
						t_compte.texte_court IS DISTINCT FROM MC_COMPTE
					)
				;

				UPDATE activite[PX].t_compte SET
					code = FAD_COMPTE,
					texte = FAD_COMPTE,
					texte_court = FAD_COMPTE
				FROM prod_cerner.FACTURE_DET
				WHERE FAD_COMPTE = code_original AND
					(
						t_compte.code IS DISTINCT FROM FAD_COMPTE OR
						t_compte.texte IS DISTINCT FROM FAD_COMPTE OR
						t_compte.texte_court IS DISTINCT FROM FAD_COMPTE
					)
				;

			]]></sqlcmd>
		</NODE>
		
	</NODE>
		
	<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
	
		
	
		<NODE label="Compléments facture">
			<sqlcmd><![CDATA[
							
				
			
				UPDATE activite[PX].p_factures SET date_expedition_0 = date_facture WHERE date_expedition_0 < date_facture AND date_facture <> '2099-12-31';
				
				-- Si deux factures (une pour tp1 et une pour patient, il ne faut pas la quantité sur cette du patient
				DROP TABLE IF EXISTS w_factures_lignes_quantite_0;
				CREATE TEMP TABLE w_factures_lignes_quantite_0 AS
				SELECT p_factures.no_sejour, p_factures_lignes_c.date_debut, prestation_id, rubrique_facturation_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].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				WHERE p_sejours.type_sejour = '3' AND
					nb_prestation <> 0 
				GROUP BY 1,2,3,4
				HAVING count(*) > 1 AND
					MAX(CASE WHEN montant_facture_1 <> 0 THEN 1 ELSE 0 END) = 1 AND
					MAX(CASE WHEN montant_facture_1 = 0 AND (montant_facture_2 <> 0 OR montant_facture_0 <> 0) THEN 1 ELSE 0 END) = 1
				;

				ANALYSE w_factures_lignes_quantite_0
				;

				UPDATE activite[PX].p_factures_lignes_c SET
					nb_prestation = 0,
					nb_rubrique = 0
				FROM activite[PX].p_factures,
					w_factures_lignes_quantite_0
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = w_factures_lignes_quantite_0.no_sejour AND
					p_factures_lignes_c.date_debut = w_factures_lignes_quantite_0.date_debut AND
					p_factures_lignes_c.prestation_id = w_factures_lignes_quantite_0.prestation_id AND
					p_factures_lignes_c.rubrique_facturation_id = w_factures_lignes_quantite_0.rubrique_facturation_id AND
					montant_facture_1 = 0 AND (montant_facture_2 <> 0 OR montant_facture_0 <> 0)

				
			]]></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 1,2,3,4,5;
				
				
				UPDATE w_sejours_total
				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

				);
                
                
                -- Sejours qui n'existe plus dans CERNER
                UPDATE activite[PX].p_sejours
                SET type_sejour = '9'
                WHERE split_part(no_sejour,'.',1) NOT IN (SELECT HO_NUM FROM prod_cerner.HOSPITALISATION) AND type_sejour <> '9'
                ;

                DELETE FROM activite[PX].p_mouvements_sejour
                WHERE no_sejour IN (SELECT no_sejour FROM activite[PX].p_sejours WHERE type_sejour = '9')
                ;
														
										
			]]></sqlcmd>
		</NODE>
		
	
	</NODE>
	
	<NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">
	
		<NODE label="Encours et valorisation non facturés">
			<sqlcmd><![CDATA[

				
				--SELECT activite[PX].calcul_encours(NULL,'');
				
				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours');
				SELECT base.cti_vacuum_table('activite[PX]','p_factures_encours_lignes_c');
				
			
				
			]]></sqlcmd>
		</NODE>
		
	</NODE>
</ROOT>