<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
		
	<NODE name="INIT" label="INITIALISATIONS">
	
		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
			
					UPDATE prod_shs.[PMSISCHEMA]_L0P01
					SET L0NGHS = ''
					WHERE L0NGHS = '9999';

					DROP TABLE IF EXISTS w_L0P01;

					CREATE TEMP TABLE w_L0P01 AS
					SELECT L0NDOS, 
						MAX(L0DTGR) AS L0DTGR, 
						MAX(L0NGHS) AS L0NGHS, 
						MAX(L0GHM9) AS L0GHM9, 
						'0000'::text AS L0NGHS_BEBE_1, 
						NULL::TID AS L0NGHS_BEBE_CTID_1, 
						'0000'::text AS L0NGHS_BEBE_2, 
						NULL::TID AS L0NGHS_BEBE_CTID_2, 
						'0000'::text AS L0NGHS_BEBE_3,
						NULL::TID AS L0NGHS_BEBE_CTID_3
					FROM prod_shs.[PMSISCHEMA]_L0P01 WHERE L0GHM9 <> '' AND L0COMP = 0
					GROUP BY 1;
					
					ALTER TABLE w_L0P01 ADD CONSTRAINT w_L0P01_pkey PRIMARY KEY(L0NDOS);


					UPDATE w_L0P01 
					SET L0NGHS = L0P01.L0NGHS
					FROM prod_shs.[PMSISCHEMA]_L0P01 L0P01
					WHERE w_L0P01.L0NDOS = L0P01.L0NDOS AND w_L0P01.L0DTGR = L0P01.L0DTGR AND L0P01.L0COMP = 0 AND w_L0P01.L0NGHS <> L0P01.L0NGHS;
					
					
					UPDATE w_L0P01 
					SET L0GHM9 = L0P01.L0GHM9
					FROM prod_shs.[PMSISCHEMA]_L0P01 L0P01
					WHERE w_L0P01.L0NDOS = L0P01.L0NDOS AND w_L0P01.L0DTGR = L0P01.L0DTGR AND L0P01.L0COMP = 0 AND w_L0P01.L0GHM9 <> L0P01.L0GHM9 ;


					UPDATE w_L0P01 
					SET L0NGHS_BEBE_1 = L0P01.L0NGHS
					FROM prod_shs.[PMSISCHEMA]_L0P01 L0P01
					WHERE w_L0P01.L0NDOS = L0P01.L0NDME AND w_L0P01.L0DTGR = L0P01.L0DTGR AND L0P01.L0COMP = 0 AND L0P01.L0NDCO = 0;
					
					-- Code facture incohérent avec code ventes
					UPDATE prod_shs.[ACTIVITESCHEMA]_ADP01 
					SET ADCFAC = '1' 
					WHERE ADCFAC <> '1' AND ADCJVT = '1'
					;


					DROP TABLE IF EXISTS w_ADP01;

					CREATE TEMP TABLE w_ADP01 AS
					SELECT 'H'::text AS w_CODENV, 
						ADDOSS AS w_ADDOSS, 
						ADDCPL AS w_ADDCPL, 
						to_char(ADDOSS,'FM00000000') AS w_ADDOSS_a,
						to_char(ADDCPL,'FM00') AS w_ADDCPL_a,
						to_char(CASE WHEN ADDOL1 <> 0 AND COALESCE(SFQSEJ,'1') NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'FM00000000') AS w_ADDOL1, 
						to_char(ADDOSS,'FM00000000') || '.' || to_char(ADDCPL,'FM00') AS w_ADDOSSDCPL,
						ADCSER || '|' || ADACTI || '|' || ADETAG || '|' || ADCHLT || '|' || ADMEDR || '|' || COALESCE(w_L0P01.L0GHM9,'') || '|' || COALESCE(w_L0P01.L0NGHS,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_1,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_2,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_3,'0000') || '|' || ADCFSS || '|' || ADCFMC || '|' || ADCFMM || '|' || ADCODM || '|' || ADCRIS AS key,
						ADCSER AS w_ADCSER,
						ADACTI AS w_ADACTI,
						ADETAG AS w_ADETAG,
						ADCHLT AS w_ADCHLT,
						CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_ADDTE1,
						COALESCE(CASE WHEN ADCPRP = '1' THEN to_date(to_char(ADDTE1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTE1_date,
						ADHREN AS w_ADHREN,
						CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN ADDTS1 ELSE '20991231' END AS w_ADDTS1,
						COALESCE(CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN to_date(to_char(ADDTS1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTS1_date,
						ADHRSO AS w_ADHRSO,
						to_timestamp(
							CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHREN BETWEEN 0 AND 240000 THEN ADHREN ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHREN,
						to_timestamp(
							CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN ADDTS1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHRSO BETWEEN 0 AND 240000 THEN ADHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHRSO,
						AD$$$6 AS w_AD$$$6,
						CASE WHEN substr(AD$$$6, 1, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 1, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 1, 1) = '4' THEN '0'
							ELSE '8' END as w_AD$$$6_ME,
						CASE WHEN substr(AD$$$6, 2, 1) = '1' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 2, 1) = '5' THEN '9'
							WHEN substr(AD$$$6, 2, 1) = '6' THEN '7'
							ELSE '8' END as w_AD$$$6_MS,
						COALESCE(SFQSEJ,'1') AS w_SFQSEJ,
						to_char(CASE WHEN ADDOL1 <> 0 AND COALESCE(SFQSEJ,'1') NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'00000000') || CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_DTE1DOL1,
						(CASE WHEN ADDCPL = 0 THEN '1' ELSE '0' END)::text AS w_DOL1UN,
						ADSEXM AS w_ADSEXM,
						ADDMED AS w_ADDMED,
						to_char(ADMEDR,'FM0000') AS w_ADMEDR,
						ADCPRP AS w_ADCPRP,
						ADCSOR AS w_ADCSOR,
						ADQURG AS w_ADQURG,
						ADSPL1 AS w_ADSPL1,
						COALESCE(w_L0P01.L0DTGR,0) AS L0DTGR,
						COALESCE(to_date(to_char(w_L0P01.L0DTGR,'FM00000000'),'YYYYMMDD'),'20991231') AS L0DTGR_date,
						COALESCE(L0NGHS,'0000') AS L0NGHS,
						COALESCE(w_L0P01.L0GHM9,'') AS L0GHM9,
						COALESCE(L0NGHS_BEBE_1,'0000') AS L0NGHS_BEBE_1,
						COALESCE(L0NGHS_BEBE_2,'0000') AS L0NGHS_BEBE_2,
						COALESCE(L0NGHS_BEBE_3,'0000') AS L0NGHS_BEBE_3,
						ADCFSS AS w_ADCFSS,
						ADCFMC AS w_ADCFMC,
						ADCFMM AS w_ADCFMM,
						ADCANN AS w_ADCANN,
						ADADAV AS w_ADADAV,
						ADCFAC AS w_ADCFAC,
						ADPAD5 AS w_ADPAD5,
						ADDTFA AS w_ADDTFA,
						COALESCE(to_date(to_char(ADDTFA,'FM00000000'),'YYYYMMDD'), '20991231') AS w_ADDTFA_date,
						ADCJVT AS w_ADCJVT,
						ADAAJV AS w_ADAAJV,
						ADMMJV AS w_ADMMJV,
						COALESCE(to_date(to_char(ADAAJV * 10000 + ADMMJV * 100 + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_ADDTJV_date,
						CASE WHEN ADAAJV >= [ENV_ADM_ANNEEDEBUT] AND ADAAJV < 2100 THEN '1' WHEN ADDTS1 >= [ENV_ADM_ANNEEDEBUT]0101 THEN  '1' WHEN ADCJVT <> '1' THEN '1' ELSE '0' END AS CTIOK,
						ADCODM AS w_ADCODM,
						ADAD1M AS w_ADAD1M,
						ADAD2M AS w_ADAD2M,
                        ADVILM AS w_ADVILM,
                        ADTELM AS w_ADTELM,
                        ADCRIS AS w_ADCRIS,
						case when length(ADNMDT) > 3 AND ADMEDT IN ('0000', '9999') THEN ADNMDT ELSE to_char(ADMEDT,'FM0000') END AS w_ADMEDT,
						ADNOM1 AS w_ADNOM1, 
						ADPREM AS w_ADPREM,
						ADMTSS AS w_ADMTSS,
						ADMTMc AS w_ADMTMC,
						DMNOMM as nom
					FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H 
						LEFT JOIN prod_shs.[ACTIVITESCHEMA]_SFP01 ON ADCSER = SFCSER
						LEFT JOIN w_L0P01 ON ADDOSS = L0NDOS
						LEFT JOIN prod_shs.[ACTIVITESCHEMA]_DMP01 ON DMDMED = ADDMED;

					CREATE INDEX w_ADP01_i1 ON w_ADP01 USING btree (w_ADDOSS);

					INSERT INTO w_ADP01
					SELECT 'P' AS w_CODENV, 
						ADDOSS, 
						ADDCPL,
						to_char(ADDOSS,'FM00000000') AS w_ADDOSS_a,
						to_char(ADDCPL,'FM00') AS w_ADDCPL_a,
						to_char(CASE WHEN ADDOL1 <> 0 AND COALESCE(SFQSEJ,'1') NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'FM00000000') AS w_ADDOL1, 
						to_char(ADDOSS,'FM00000000') || '.' || to_char(ADDCPL,'FM00') AS w_ADDOSSDCPL,
						ADCSER || '|' || ADACTI || '|' || ADETAG || '|' || ADCHLT || '|' || ADMEDR || '|' || COALESCE(w_L0P01.L0GHM9,'') || '|' || COALESCE(w_L0P01.L0NGHS,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_1,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_2,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_3,'0000') || '|' || ADCFSS || '|' || ADCFMC || '|' || ADCFMM || '|' || ADCODM || '|' || ADCRIS AS key,
						ADCSER AS w_ADCSER,
						ADACTI AS w_ADACTI,
						ADETAG AS w_ADETAG,
						ADCHLT AS w_ADCHLT,
						CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_ADDTE1,
						COALESCE(CASE WHEN ADCPRP = '1' THEN to_date(to_char(ADDTE1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTE1_date,
						ADHREN AS w_ADHREN,
						CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN ADDTS1 ELSE '20991231' END AS w_ADDTS1,
						COALESCE(CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN to_date(to_char(ADDTS1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTS1_date,
						ADHRSO AS w_ADHRSO,
						to_timestamp(
							CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHREN BETWEEN 0 AND 240000 THEN ADHREN ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHREN,
						to_timestamp(
							CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN ADDTS1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHRSO BETWEEN 0 AND 240000 THEN ADHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHRSO,
						AD$$$6,
						CASE WHEN substr(AD$$$6, 1, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 1, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 1, 1) = '4' THEN '0'
							ELSE '8' END as w_AD$$$6_ME,
						CASE WHEN substr(AD$$$6, 2, 1) = '1' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 2, 1) = '5' THEN '9'
							WHEN substr(AD$$$6, 2, 1) = '6' THEN '7'
							ELSE '8' END as w_AD$$$6_MS,
						COALESCE(SFQSEJ,'1') AS w_SFQSEJ,
						to_char(CASE WHEN ADDOL1 <> 0 AND COALESCE(SFQSEJ,'1') NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'00000000') || CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_DTE1DOL1,
						(CASE WHEN ADDCPL = 0 THEN '1' ELSE '0' END)::text AS w_DOL1UN,
						ADSEXM AS w_ADSEXM,
						ADDMED AS w_ADDMED,
						to_char(ADMEDR,'FM0000') AS w_ADMEDR,
						ADCPRP AS w_ADCPRP,
						ADCSOR AS w_ADCSOR,
						ADQURG AS w_ADQURG,
						ADSPL1 AS w_ADSPL1,
						COALESCE(w_L0P01.L0DTGR,0) AS L0DTGR,
						COALESCE(to_date(to_char(w_L0P01.L0DTGR,'FM00000000'),'YYYYMMDD'),'20991231') AS L0DTGR_date,
						COALESCE(w_L0P01.L0NGHS,'0000') AS L0NGHS,
						COALESCE(w_L0P01.L0GHM9,'') AS L0GHM9,
						COALESCE(w_L0P01.L0NGHS_BEBE_1,'0000') AS L0NGHS_BEBE_1,
						COALESCE(w_L0P01.L0NGHS_BEBE_2,'0000') AS L0NGHS_BEBE_2,
						COALESCE(w_L0P01.L0NGHS_BEBE_3,'0000') AS L0NGHS_BEBE_3,
						ADCFSS AS w_ADCFSS,
						ADCFMC AS w_ADCFMC,
						ADCFMM AS w_ADCFMM,
						ADCANN AS w_ADCANN,
						ADADAV AS w_ADADAV,
						ADCFAC AS w_ADCFAC,
						ADPAD5 AS w_ADPAD5,
						ADDTFA AS w_ADDTFA,
						COALESCE(to_date(to_char(ADDTFA,'FM00000000'),'YYYYMMDD'), '20991231') AS w_ADDTFA_date,
						ADCJVT AS w_ADCJVT,
						ADAAJV AS w_ADAAJV,
						ADMMJV AS w_ADMMJV,
						COALESCE(to_date(to_char(ADAAJV * 10000 + ADMMJV * 100 + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_ADDTJV_date,
						CASE WHEN ADAAJV >= [ENV_ADM_ANNEEDEBUT] AND ADAAJV < 2100 THEN '1' WHEN ADDTS1 >= [ENV_ADM_ANNEEDEBUT]0101 THEN  '1' WHEN ADCJVT <> '1' THEN '1' ELSE '0' END AS CTIOK,
						ADCODM AS w_ADCODM,
						ADAD1M AS w_ADAD1M,
						ADAD2M AS w_ADAD2M,
                        ADVILM AS w_ADVILM,
                        ADTELM AS w_ADTELM,
                        ADCRIS AS w_ADCRIS,
						case when length(ADNMDT) > 3 AND ADMEDT IN ('0000', '9999') THEN ADNMDT ELSE to_char(ADMEDT,'FM0000') END AS w_ADMEDT,
						ADNOM1 AS w_ADNOM1, 
						ADPREM AS w_ADPREM,
						ADMTSS AS w_ADMTSS,
						ADMTMc AS w_ADMTMC
					FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P 
						LEFT JOIN prod_shs.[ACTIVITESCHEMA]_SFP01 ON ADCSER = SFCSER
						LEFT JOIN w_ADP01 ON ADDOSS = w_ADDOSS AND ADDCPL = w_ADDCPL
						LEFT JOIN w_L0P01 ON ADDOSS = L0NDOS
					WHERE w_ADDOSS IS NULL;
						


					INSERT INTO w_ADP01 
					SELECT '' AS w_CODENV, 
						ADDOSS, 
						ADDCPL, 
						to_char(ADDOSS,'FM00000000') AS w_ADDOSS_a,
						to_char(ADDCPL,'FM00') AS w_ADDCPL_a,
						to_char(CASE WHEN ADDOL1 <> 0 AND COALESCE(SFQSEJ,'1') NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'FM00000000') AS w_ADDOL1, 
						to_char(ADDOSS,'FM00000000') || '.' || to_char(ADDCPL,'FM00') AS w_ADDOSSDCPL,
						ADCSER || '|' || ADACTI || '|' || ADETAG || '|' || ADCHLT || '|' || ADMEDR || '|' || COALESCE(w_L0P01.L0GHM9,'') || '|' || COALESCE(w_L0P01.L0NGHS,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_1,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_2,'0000') || '|' || COALESCE(w_L0P01.L0NGHS_BEBE_3,'0000') || '|' || ADCFSS || '|' || ADCFMC || '|' || ADCFMM || '|' || ADCODM || '|' || ADCRIS AS key,
						ADCSER AS w_ADCSER,
						ADACTI AS w_ADACTI,
						ADETAG AS w_ADETAG,
						ADCHLT AS w_ADCHLT,
						CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_ADDTE1,
						COALESCE(CASE WHEN ADCPRP = '1' THEN to_date(to_char(ADDTE1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTE1_date,
						ADHREN AS w_ADHREN,
						CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN ADDTS1 ELSE '20991231' END AS w_ADDTS1,
						COALESCE(CASE WHEN ADCPRP = '1' AND ADCSOR = '1' THEN to_date(to_char(ADDTS1,'FM00000000'),'YYYYMMDD') ELSE '20991231' END,'20991231') AS w_ADDTS1_date,
						ADHRSO AS w_ADHRSO,
						to_timestamp(
							CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHREN BETWEEN 0 AND 240000 THEN ADHREN ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHREN,
						to_timestamp(
							CASE WHEN ADCPRP = '1' AND ADCSOR = '1' AND ADDTS1 != 0 THEN ADDTS1 ELSE '20991231' END || 
							to_char(CASE WHEN ADHRSO BETWEEN 0 AND 240000 THEN ADHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI'
						)::timestamp without time zone AS w_ADDTHRSO,
						AD$$$6,
						CASE WHEN substr(AD$$$6, 1, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 1, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 1, 1) = '4' THEN '0'
							ELSE '8' END as w_AD$$$6_ME,
						CASE WHEN substr(AD$$$6, 2, 1) = '1' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '2' THEN '6'
							WHEN substr(AD$$$6, 2, 1) = '3' THEN '7'
							WHEN substr(AD$$$6, 2, 1) = '5' THEN '9'
							WHEN substr(AD$$$6, 2, 1) = '6' THEN '7'
							ELSE '8' END as w_AD$$$6_MS,
						COALESCE(SFQSEJ,'1') AS w_SFQSEJ,
						to_char(CASE WHEN ADDOL1 <> 0 AND SFQSEJ NOT IN ('0','5') AND ADCPRP = '1' AND to_char(ADDOL1,'FM00000000') NOT LIKE '50%' THEN ADDOL1 ELSE ADDOSS END,'00000000') || CASE WHEN ADCPRP = '1' THEN ADDTE1 ELSE '20991231' END AS w_DTE1DOL1,
						(CASE WHEN ADDCPL = 0 THEN '1' ELSE '0' END)::text AS w_DOL1UN,
						ADSEXM AS w_ADSEXM,
						ADDMED AS w_ADDMED,
						to_char(ADMEDR,'FM0000') AS w_ADMEDR,
						ADCPRP AS w_ADCPRP,
						ADCSOR AS w_ADCSOR,
						ADQURG AS w_ADQURG,
						ADSPL1 AS w_ADSPL1,
						COALESCE(w_L0P01.L0DTGR,0) AS L0DTGR,
						COALESCE(to_date(to_char(w_L0P01.L0DTGR,'FM00000000'),'YYYYMMDD'),'20991231') AS L0DTGR_date,
						COALESCE(w_L0P01.L0NGHS,'0000') AS L0NGHS,
						COALESCE(w_L0P01.L0GHM9,'') AS L0GHM9,
						COALESCE(w_L0P01.L0NGHS_BEBE_1,'0000') AS L0NGHS_BEBE_1,
						COALESCE(w_L0P01.L0NGHS_BEBE_2,'0000') AS L0NGHS_BEBE_2,
						COALESCE(w_L0P01.L0NGHS_BEBE_3,'0000') AS L0NGHS_BEBE_3,
						ADCFSS AS w_ADCFSS,
						ADCFMC AS w_ADCFMC,
						ADCFMM AS w_ADCFMM,
						ADCANN AS w_ADCANN,
						ADADAV AS w_ADADAV,
						ADCFAC AS w_ADCFAC,
						ADPAD5 AS w_ADPAD5,
						ADDTFA AS w_ADDTFA,
						COALESCE(to_date(to_char(ADDTFA,'FM00000000'),'YYYYMMDD'), '20991231') AS w_ADDTFA_date,
						ADCJVT AS w_ADCJVT,
						ADAAJV AS w_ADAAJV,
						ADMMJV AS w_ADMMJV,
						COALESCE(to_date(to_char(ADAAJV * 10000 + ADMMJV * 100 + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_ADDTJV_date,
						CASE WHEN ADAAJV >= [ENV_ADM_ANNEEDEBUT] AND ADAAJV < 2100 THEN '1' WHEN ADDTS1 >= [ENV_ADM_ANNEEDEBUT]0101 THEN  '1' WHEN ADCJVT <> '1' THEN '1' ELSE '0' END AS CTIOK,
						ADCODM AS w_ADCODM,
						ADAD1M AS w_ADAD1M,
						ADAD2M AS w_ADAD2M,
                        ADVILM AS w_ADVILM,
                        ADTELM AS w_ADTELM,
                        ADCRIS AS w_ADCRIS,
						case when length(ADNMDT) > 3 AND ADMEDT IN ('0000', '9999') THEN ADNMDT ELSE to_char(ADMEDT,'FM0000') END AS w_ADMEDT,
						ADNOM1 AS w_ADNOM1, 
						ADPREM AS w_ADPREM,
						ADMTSS AS w_ADMTSS,
						ADMTMc AS w_ADMTMC
					FROM prod_shs.[ACTIVITESCHEMA]_ADP01
						LEFT JOIN prod_shs.[ACTIVITESCHEMA]_SFP01 ON ADCSER = SFCSER
						LEFT JOIN w_ADP01 ON ADDOSS = w_ADDOSS AND ADDCPL = w_ADDCPL
						LEFT JOIN w_L0P01 ON ADDOSS = L0NDOS
					WHERE w_ADDOSS IS NULL AND ADCPRP = '1';
					
				-- Médecin de référence modifié sur les additifs, il faut modifier les additifs antérieus
				UPDATE w_ADP01 SET
					w_ADMEDR = subview.w_ADMEDR_last,
					key = key || '|' || subview.w_ADMEDR_last
				FROM
				(
				SELECT w_ADDOSS,					 
					(MAX(ARRAY[to_char(w_ADDCPL,'FM00'),w_ADMEDR]))[2] AS w_ADMEDR_last
				FROM w_ADP01
				GROUP BY 1
				HAVING  count(DISTINCT w_ADMEDR) > 1
				) subview
				WHERE w_ADP01.w_ADDOSS = subview.w_ADDOSS AND
					w_ADP01.w_ADMEDR <> subview.w_ADMEDR_last
				;
					
				-- Dossiers séances ouverts à tord (services forcés séance)
				UPDATE w_adp01 
				SET w_ADCANN = 'A'
				WHERE w_ADCSER IN (SELECT code_original FROM activite[PX].t_services_facturation WHERE type_sejour = '5') AND 
					w_ADCSOR = '0' AND 
					w_ADDTE1_date <= (now() - interval '7 days') AND 
					w_ADCANN <> 'A' AND
					w_ADDOSS NOT IN (SELECT ACDOSS FROM prod_shs.[ACTIVITESCHEMA]_ACP01 WHERE ACCANN = '1');
					
				-- Dossiers séances ouverts à tord (19-302)
				UPDATE w_adp01 
				SET w_ADCANN = 'A'
				WHERE w_ADCSER IN (
					SELECT t_services_facturation.code_original 
					FROM activite[PX].t_services_facturation 
					JOIN base.t_modes_traitement ON mode_traitement_id = t_modes_traitement.oid
					JOIN base.t_dmt ON dmt_id = t_dmt.oid
					WHERE t_modes_traitement.code = '19' AND t_dmt.code = '302') AND 
					w_ADCSOR = '0' AND 
					w_ADDTE1_date <= (now() - interval '7 days') AND 
					w_ADCANN <> 'A' AND
					w_ADDOSS NOT IN (SELECT ACDOSS FROM prod_shs.[ACTIVITESCHEMA]_ACP01 WHERE ACCANN = '1');

				DELETE FROM w_ADP01 WHERE w_ADCANN <> '';
				
				
				
				DROP TABLE IF EXISTS w_CCP01_next_jvt;
				CREATE TEMP TABLE w_CCP01_next_jvt AS
				SELECT 
					COALESCE(to_date(MAX(CCANEE * 10000 + CCMOIS * 100 + 01),'YYYYMMDD') + interval '2 month' - interval '1 day', '20991231') AS CCDTJV_date
				FROM prod_shs.[ACTIVITESCHEMA]_CCP01 
				WHERE CCCMON = 'E' AND CCMOIS <= 12 AND CCNOR3 IN (105) ;

				
				UPDATE w_ADP01 
					SET w_ADDTJV_date = CASE WHEN w_ADCSOR <> '1' THEN '20991231' WHEN w_ADDTS1_date <= CCDTJV_date THEN CCDTJV_date ELSE date_trunc('month', w_ADDTS1_date) + interval '1 month' - interval '1 day'  END
				FROM w_CCP01_next_jvt
				WHERE w_ADCJVT <> '1';
				
				UPDATE w_ADP01 
					SET w_ADAAJV = date_part('year',  w_ADDTJV_date), w_ADMMJV = date_part('month',  w_ADDTJV_date)
				WHERE w_ADCJVT <> '1';

				DROP TABLE IF EXISTS w_ADP01_keys;
				CREATE TEMP TABLE w_ADP01_keys AS
				SELECT 
					key,
					w_ADCSER,
					w_ADACTI,
					w_ADETAG,
					w_ADCHLT,
					w_ADMEDR,
					L0NGHS,
					L0GHM9,
					L0NGHS_BEBE_1,
					L0NGHS_BEBE_2,
					L0NGHS_BEBE_3,
					w_ADCFSS,
					w_ADCFMC,
					w_ADCFMM,
					w_ADCODM,
					w_ADCRIS,
					''::text AS mode_traitement_code,
					''::text AS dmt_code,
					'0'::text AS type_sejour_force,
					0::bigint AS lieu_id,
					0::bigint AS 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,
					0::bigint AS tiers_payant_0_id,
					0::bigint AS tiers_payant_1_id,
					0::bigint AS tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id,
					0::bigint AS code_postal_id,
                    0::bigint AS risque_id
				FROM w_ADP01
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16;


				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT w_ADCSER, w_ADACTI, w_ADETAG, w_ADETAG || '|' || w_ADCHLT
				FROM w_ADP01_keys 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = w_ADCSER AND
						code_original_2 = w_ADACTI AND
						code_original_3 = w_ADETAG AND
						code_original_4 = w_ADETAG || '|' || w_ADCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;



				UPDATE w_ADP01_keys
					set lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = w_ADCSER AND
					code_original_2 = w_ADACTI AND
					code_original_3 = w_ADETAG AND
					code_original_4 = w_ADETAG || '|' || w_ADCHLT;

				UPDATE w_ADP01_keys SET
					mode_traitement_code = t_modes_traitement.code,
					dmt_code = t_dmt.code,
					type_sejour_force = CASE WHEN t_services_facturation.type_sejour IN ('1', '2', '3', '31', '4', '5') THEN t_services_facturation.type_sejour ELSE '0' END
				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 = w_ADCSER ;


				UPDATE w_ADP01_keys
					set medecin_sejour_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE code_original = w_ADMEDR;

				UPDATE w_ADP01_keys
					set ghs_id = t_ghs.oid
				FROM base.t_ghs
				WHERE L0NGHS <> '0000' AND to_char(t_ghs.code,'FM0000') = L0NGHS;
				
				UPDATE w_ADP01_keys
					set ghm_id = t_ghm.oid
				FROM base.t_ghm
				WHERE t_ghm.code = L0GHM9 AND t_ghm.code NOT LIKE '90%';

				UPDATE w_ADP01_keys
					set ghs_bebe1_id = t_ghs.oid
				FROM base.t_ghs
				WHERE L0NGHS_BEBE_1 <> '0000' AND to_char(t_ghs.code,'FM0000') = L0NGHS_BEBE_1;

				UPDATE w_ADP01_keys
					set ghs_bebe2_id = t_ghs.oid
				FROM base.t_ghs
				WHERE L0NGHS_BEBE_2 <> '0000' AND to_char(t_ghs.code,'FM0000') = L0NGHS_BEBE_2;
	
				UPDATE w_ADP01_keys
					set ghs_bebe3_id = t_ghs.oid
				FROM base.t_ghs
				WHERE L0NGHS_BEBE_3 <> '0000' AND to_char(t_ghs.code,'FM0000') = L0NGHS_BEBE_3;

				ALTER TABLE w_ADP01_keys ADD CONSTRAINT w_ADP01_keys_pkey PRIMARY KEY(key);

				
				UPDATE w_ADP01_keys
					set tiers_payant_0_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE code_original = '0000';

				UPDATE w_ADP01_keys
					set tiers_payant_1_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE w_ADCFSS <> 0 AND w_ADCFSS <> 9999 AND code_original = w_ADCFSS;

				UPDATE w_ADP01_keys
					set tiers_payant_2_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE w_ADCFMC <> 0 AND w_ADCFMC <> 9999 AND code_original = w_ADCFMC;

				UPDATE w_ADP01_keys
					set tiers_payant_22_id = t_tiers_payant.oid
				FROM activite[PX].t_tiers_payant
				WHERE w_ADCFMM <> 0 AND w_ADCFMM <> 9999 AND code_original = w_ADCFMM;

				UPDATE w_ADP01_keys
					set code_postal_id = t_codes_postaux.oid
				FROM base.t_codes_postaux
				WHERE w_ADCODM = t_codes_postaux.code;

				UPDATE w_ADP01_keys
					set risque_id = t_risque.oid
				FROM activite[PX].t_risque
				WHERE w_ADCRIS = t_risque.code;





				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
					t_lieux.activite_id <> COALESCE(t_activites.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)
					;


				DROP TABLE IF EXISTS w_ADP01_SEJOUR;
				CREATE TEMP TABLE w_ADP01_SEJOUR AS
				SELECT w_ADDOL1, 
					COUNT(CASE WHEN w_DOL1UN = '1' THEN w_ADDOSS ELSE NULl END) AS count, 
					MIN(w_ADDTE1) AS w_ADDTE1,
					MIN(w_ADHREN) AS w_ADHREN,
					MAX(w_ADDTS1) AS w_ADDTS1,
					MAX(w_ADHRSO) AS w_ADHRSO,
					MIN(w_AD$$$6_ME) AS w_AD$$$6_ME,
					MIN(w_AD$$$6_MS) AS w_AD$$$6_MS,
					MIN(w_DTE1DOL1) AS w_DTE1DOL1_1,
					MAX(w_DTE1DOL1) AS w_DTE1DOL1_9
				FROM w_ADP01
				GROUP BY 1;

				UPDATE w_ADP01_SEJOUR
				SET w_ADDTE1 = w_ADP01.w_ADDTE1,
					w_ADHREN = w_ADP01.w_ADHREN,
					w_AD$$$6_ME = w_ADP01.w_AD$$$6_ME
				FROM w_ADP01
				WHERE w_ADP01_SEJOUR.w_ADDOL1 = w_ADP01.w_ADDOL1 AND w_ADP01_SEJOUR.w_DTE1DOL1_1 = w_ADP01.w_DTE1DOL1
					AND (w_ADP01_SEJOUR.w_ADDTE1 <> w_ADP01.w_ADDTE1 OR 
						w_ADP01_SEJOUR.w_ADHREN <> w_ADP01.w_ADHREN OR
						w_ADP01_SEJOUR.w_AD$$$6_ME <> w_ADP01.w_AD$$$6_ME);

				UPDATE w_ADP01_SEJOUR
				SET w_ADDTS1 = w_ADP01.w_ADDTS1,
					w_ADHRSO = w_ADP01.w_ADHRSO,
					w_AD$$$6_MS = w_ADP01.w_AD$$$6_MS
				FROM w_ADP01
				WHERE w_ADP01_SEJOUR.w_ADDOL1 = w_ADP01.w_ADDOL1 AND w_ADP01_SEJOUR.w_DTE1DOL1_9 = w_ADP01.w_DTE1DOL1
					AND (w_ADP01_SEJOUR.w_ADDTS1 <> w_ADP01.w_ADDTS1 OR 
						w_ADP01_SEJOUR.w_ADHRSO <> w_ADP01.w_ADHRSO OR
						w_ADP01_SEJOUR.w_AD$$$6_MS <> w_ADP01.w_AD$$$6_MS
					);




				UPDATE w_ADP01
				SET w_DOL1UN = '0'
				FROM w_ADP01_SEJOUR
				WHERE w_ADP01.w_ADDOL1 = w_ADP01_SEJOUR.w_ADDOL1 AND COUNT > 1 AND w_DOL1UN = '1' AND w_ADP01.w_DTE1DOL1 <> w_ADP01_SEJOUR.w_DTE1DOL1_1;

				UPDATE w_ADP01
				SET w_DOL1UN = '0'
				FROM
				(
				SELECT w_ADDOL1, MIN(w_ADDOSS) AS first_ADDOSS
				FROM w_ADP01
				GROUP BY 1
				HAVING count(CASE WHEN w_DOL1UN = '1' THEN 1 ELSE NULL END) > 1
				) subview
				WHERE w_ADP01.w_ADDOL1 = subview.w_ADDOL1 AND
					w_ADDOSS <> first_ADDOSS AND
					w_DOL1UN = '1';

				

				CREATE INDEX w_ADP01_i2
				  ON w_ADP01
				  USING btree
				  (w_ADDOL1);

				CREATE INDEX w_ADP01_i5
				  ON w_ADP01
				  USING btree
				  (key);

				CREATE INDEX w_ADP01_i4
				  ON w_ADP01
				  USING btree
				  (w_CODENV);
				  
				CREATE INDEX w_ADP01_i9
					ON w_ADP01
					USING btree
					(w_ADDOSS_a);
				
				ALTER TABLE w_ADP01 ADD CONSTRAINT w_ADP01_pkey PRIMARY KEY(w_ADDOSSDCPL);

				ALTER TABLE w_ADP01_SEJOUR ADD CONSTRAINT w_ADP01_SEJOUR_pkey PRIMARY KEY(w_ADDOL1);
				
				
				DROP TABLE IF EXISTS w_ADP01_autres;
				CREATE TEMP TABLE w_ADP01_autres AS
				SELECT FTDOSS AS ADDOSS FROM prod_shs.[ACTIVITESCHEMA]_FTP01 WHERE FTMTFA <> (FTMTRG + FTMTOD) GROUP BY 1
				UNION
				SELECT FDDOSS AS ADDOSS FROM prod_shs.[ACTIVITESCHEMA]_FDP03 WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01 GROUP BY 1
				UNION
				SELECT FDDOSS AS ADDOSS FROM prod_shs.[ACTIVITESCHEMA]p_FDP03P WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01 GROUP BY 1
				UNION
				SELECT FDDOSS AS ADDOSS FROM prod_shs.[ACTIVITESCHEMA]h_FDP03H WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01 GROUP BY 1;

				UPDATE w_ADP01 SET CTIOK = '1'
				WHERE CTIOK <> '1' AND w_ADDOSS IN 
					(SELECT ADDOSS FROM w_ADP01_autres);
				  

				

				UPDATE w_ADP01 SET CTIOK = '1'
				WHERE CTIOK <> '1' AND
					w_ADDOL1 IN (SELECT w_ADDOL1 FROM w_ADP01 WHERE CTIOK = '1');


				DELETE FROM w_ADP01 WHERE CTIOK <> '1';
				
				UPDATE w_ADP01
				SET L0NGHS_BEBE_1 = '0000'
				WHERE L0NGHS_BEBE_1 NOT BETWEEN '0000' AND '9999';
				
				
				
				-- Suppression des tables de travail
				
				DROP TABLE IF EXISTS w_L0P01;
				DROP TABLE IF EXISTS w_CCP01_next_jvt;
					
			]]></sqlcmd>
		</NODE>
					
		<NODE label="Détection modifications">
			<sqlcmd><![CDATA[
				
				
				
				DROP TABLE IF EXISTS w_ADP01_sejours_modifies;
				CREATE TEMP TABLE w_ADP01_sejours_modifies AS
				SELECT * 
				FROM w_ADP01;
				
				CREATE INDEX w_ADP01_sejours_modifies_i1
				  ON w_ADP01_sejours_modifies
				  USING btree
				  (w_ADDOSS);


				DROP TABLE IF EXISTS w_ADP01_factures_modifiees;
				CREATE TEMP TABLE w_ADP01_factures_modifiees AS
				SELECT * 
				FROM w_ADP01; 
				
				CREATE INDEX w_ADP01_factures_modifiees_i1
				  ON w_ADP01_factures_modifiees
				  USING btree
				  (w_ADDOSS);
				  
				CREATE INDEX w_ADP01_factures_modifiees_i2
				  ON w_ADP01_factures_modifiees
				  USING btree
				  (w_ADDOL1);

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

	<NODE name="SEJOUR" label="RECUPERATION DES SEJOURS">
	
		<NODE label="Patients">
			<sqlcmd><![CDATA[

				INSERT INTO activite[PX].p_patients(no_patient, nom, nom_naissance, prenom, date_naissance, code_sexe)
				SELECT DMDMED, 
					MAX(DMNOMM), 
					MAX(DMNJFM), 
					MAX(DMPREM), 
					MAX(base.cti_to_date(DMAANM, DMMMNM, DMJJNM)),
					MAX(CASE WHEN DMSEXM IN ('2','3', '5') THEN '2' ELSE '1' END) as code_sexe
				FROM prod_shs.[ACTIVITESCHEMA]_DMP01 LEFT JOIN activite[PX].p_patients ON (DMDMED = p_patients.no_patient)
				WHERE (DMDMED IN (SELECT w_ADDMED FROM w_ADP01) OR DMDMED IN (SELECT ltrim(trim(split_part(w_ADP01.nom, 'VOIR IDENTITE', 2)), '0') FROM w_ADP01)) AND
					p_patients.no_patient IS NULL
				GROUP BY 1;

				UPDATE activite[PX].p_patients
				SET nom = DMNOMM, 
					nom_naissance = DMNJFM, 
					prenom = DMPREM, 
					date_naissance = base.cti_to_date(DMAANM, DMMMNM, DMJJNM),
					code_sexe = CASE WHEN DMSEXM IN ('2','3', '5') THEN '2' ELSE '1' END
				FROM prod_shs.[ACTIVITESCHEMA]_DMP01
				WHERE p_patients.no_patient = DMDMED
					AND (
						p_patients.nom <> DMNOMM OR 
						p_patients.prenom <> DMPREM OR
						p_patients.date_naissance <> base.cti_to_date(DMAANM, DMMMNM, DMJJNM) OR
						code_sexe <> CASE WHEN DMSEXM IN ('2','3', '5') THEN '2' ELSE '1' END
					);
										
										
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Séjours">
			<sqlcmd><![CDATA[
			
					-- ATU ou SEx factures ou GHS ou CP 
					
					DROP TABLE IF EXISTS w_MFP01_atuse;
					
					CREATE TEMP TABLE w_MFP01_atuse AS
					SELECT
						to_char(MFDOSS, 'FM00000000') AS w_MFDOSS,
						CASE WHEN MFCCLE NOT IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_FOR,
						CASE WHEN MFCCLE IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_GHS
					FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
						JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
					WHERE MFCSER || MFRUPR IN (
						SELECT TRCSER || TRCRUB 
						FROM prod_shs.[ACTIVITESCHEMA]_TRP01
						WHERE TRCENR = 'A51' AND
							(
							TRPRSA IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6') OR
							TRPRST IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6')
							)
						) OR
						MFCCLE IN ('GHS','PJ');
							
					INSERT INTO w_MFP01_atuse	
					SELECT
						to_char(MFDOSS, 'FM00000000') AS w_MFDOSS,
						CASE WHEN MFCCLE NOT IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_FOR,
						CASE WHEN MFCCLE IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_GHS
					FROM prod_shs.[ACTIVITESCHEMA]P_MFP01CLIP
						JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'P')
					WHERE MFCSER || MFRUPR IN (
						SELECT TRCSER || TRCRUB 
						FROM prod_shs.[ACTIVITESCHEMA]_TRP01
						WHERE TRCENR = 'A51' AND
							(
							TRPRSA IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6') OR
							TRPRST IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6')
							)
						) OR
						MFCCLE IN ('GHS','PJ');
							
					INSERT INTO w_MFP01_atuse	
					SELECT
						to_char(MFDOSS, 'FM00000000') AS w_MFDOSS,
						CASE WHEN MFCCLE NOT IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_FOR,
						CASE WHEN MFCCLE IN ('GHS','PJ') THEN CASE WHEN MFMTFA < 0 THEN 0 - MFNBRE ELSE MFNBRE END ELSE 0 END AS MFNBRE_GHS
					FROM prod_shs.[ACTIVITESCHEMA]H_MFP01CLIH
						JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'H')
					WHERE MFCSER || MFRUPR IN (
						SELECT TRCSER || TRCRUB 
						FROM prod_shs.[ACTIVITESCHEMA]_TRP01
						WHERE TRCENR = 'A51' AND
							(
							TRPRSA IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6') OR
							TRPRST IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6')
							)
						) OR
						MFCCLE IN ('GHS','PJ');
						
					INSERT INTO w_MFP01_atuse	
					SELECT
						to_char(ACDOSS, 'FM00000000') AS w_MFDOSS,
						ACNBRE AS ACNBRE_FOR,
						0 AS ACNBRE_GHS
					FROM prod_shs.[ACTIVITESCHEMA]_ACP01
					JOIN prod_shs.[ACTIVITESCHEMA]_ADP01 ON ACDOSS = ADDOSS AND ACDCPL = ADDCPL
					WHERE ACCCLH = '1' AND
						ADCSER||to_char(ACRUPR,'FM000') IN (
						SELECT TRCSER || TRCRUB 
						FROM prod_shs.[ACTIVITESCHEMA]_TRP01
						WHERE TRCENR = 'A51' AND
							(
							TRPRSA IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6') OR
							TRPRST IN ('ATU', 'FPU', 'SE1', 'SE2', 'SE3', 'SE4','SE5', 'SE6')
							)
						) ;
							
			
					
					DROP TABLE IF EXISTS w_MFP01_ext;
					CREATE TEMP TABLE w_MFP01_ext AS
					SELECT
						w_MFDOSS,
						'07':: text AS w_MFMT
					FROM w_MFP01_atuse
					GROUP BY 1,2
					HAVING SUM(MFNBRE_FOR) > 0 OR (MAX(MFNBRE_FOR) > 0 AND SUM(MFNBRE_GHS) = 0);
					
					CREATE INDEX w_MFP01_ext_i1
					ON w_MFP01_ext
					USING btree
					(w_MFDOSS);
					
					
					
					

					DROP TABLE IF EXISTS w_sejours;

					CREATE TEMP TABLE w_sejours AS
					SELECT 
						''::text AS finess,
						w_ADP01.w_ADDOL1 as no_sejour, 
						w_ADDOSSDCPL as code_original, 
						w_ADDMED as no_patient, 
						COALESCE(to_date(to_char(w_ADP01_SEJOUR.w_ADDTE1,'FM00000000'),'YYYYMMDD'),'20991231') as date_entree, 
						w_ADP01_SEJOUR.w_ADHREN * 100 as heure_entree, 
						COALESCE(to_date(to_char(w_ADP01_SEJOUR.w_ADDTS1,'FM00000000'),'YYYYMMDD'),'20991231') as date_sortie, 
						w_ADP01_SEJOUR.w_ADHRSO * 100 as heure_sortie, 
						CASE WHEN w_ADSEXM IN ('2','3', '5') THEN '2' ELSE '1' END as code_sexe, 
						0 AS age, 
						CASE WHEN w_ADCSOR = '1' THEN 1 ELSE 0 END as code_sorti, 
						CASE WHEN w_ADCPRP <> '1' THEN 1 ELSE 0 END as code_prevu,
						CASE 
							WHEN type_sejour_force <> '0' AND type_sejour_force <> '31' THEN type_sejour_force
							WHEN type_sejour_force = 31 AND to_date(to_char(w_ADP01.w_ADDTS1,'FM00000000'),'YYYYMMDD')::date - to_date(to_char(w_ADP01.w_ADDTE1,'FM00000000'),'YYYYMMDD')::date <= 1 THEN '3'
							WHEN type_sejour_force = 31 THEN '1'
							WHEN mode_traitement_code IN ('07') OR dmt_code IN ('958') THEN '3' 
							WHEN mode_traitement_code IN ('19') AND dmt_code IN ('302') THEN '5' 
							WHEN mode_traitement_code IN ('19', '23') THEN '2' 
							WHEN mode_traitement_code IN ('04') AND to_date(to_char(w_ADP01.w_ADDTS1,'FM00000000'),'YYYYMMDD') = to_date(to_char(w_ADP01.w_ADDTE1,'FM00000000'),'YYYYMMDD') THEN '2' 
							WHEN mode_traitement_code IN ('04') THEN '1' 
							WHEN mode_traitement_code IN ('03') AND to_date(to_char(w_ADP01.w_ADDTS1,'FM00000000'),'YYYYMMDD') = to_date(to_char(w_ADP01.w_ADDTE1,'FM00000000'),'YYYYMMDD') THEN '2' 
							WHEN mode_traitement_code IN ('10') AND w_SFQSEJ NOT IN ('0', '5') AND to_date(to_char(w_ADP01.w_ADDTS1,'FM00000000'),'YYYYMMDD') = to_date(to_char(w_ADP01.w_ADDTE1,'FM00000000'),'YYYYMMDD') THEN '2' 
							WHEN mode_traitement_code IN ('03') THEN '1' 
							WHEN w_SFQSEJ IN ('0', '5') THEN '3' 
							ELSE '1' END as type_sejour,
						w_ADP01_keys.lieu_id AS lieu_sortie_id,
						w_ADP01_keys.medecin_sejour_id,
						w_ADP01_keys.ghs_id,
						w_ADP01_keys.ghm_id,
						w_ADP01_keys.ghs_bebe1_id,
						w_ADP01_keys.ghs_bebe2_id,
						w_ADP01_keys.ghs_bebe3_id,
						L0DTGR_date as date_groupage,
						CASE WHEN w_ADSPL1 = '' OR w_ADSPL1 = '0' THEN '0' ELSE '1' END as code_cp_demandee,
						t_services_facturation.mode_traitement_id as mode_traitement_id,
						w_ADP01_SEJOUR.w_AD$$$6_ME as mode_entree,
						'0'::character(1) as provenance,
						w_ADP01_SEJOUR.w_AD$$$6_MS as mode_sortie,
						'0'::character(1) as destination,
						w_ADP01_keys.tiers_payant_0_id,
						w_ADP01_keys.tiers_payant_1_id,
						w_ADP01_keys.tiers_payant_2_id,
						w_ADP01_keys.tiers_payant_22_id,
						CASE WHEN substr(w_AD$$$6, 3, 2) = 'BG' THEN 1 ELSE 0 END AS est_budget_global,
						w_ADP01_keys.code_postal_id,
						w_ADP01_keys.risque_id

					FROM w_ADP01_sejours_modifies w_ADP01
						JOIN w_ADP01_SEJOUR ON w_ADP01.w_ADDOL1 = w_ADP01_SEJOUR.w_ADDOL1
						JOIN w_ADP01_keys ON w_ADP01.key = w_ADP01_keys.key
						JOIN activite[PX].t_services_facturation ON w_ADP01.w_ADCSER = t_services_facturation.code_original
					WHERE w_DOL1UN = '1'  AND w_ADCANN = '';
					
					UPDATE w_sejours
					SET type_sejour = '3'
					WHERE type_sejour <> '3' AND
						no_sejour IN (SELECT w_MFDOSS FROM w_MFP01_ext);
						
					-- 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;
					
					UPDATE w_sejours
					SET finess = '000000000'
					WHERE finess = '';
					
					
					

					UPDATE activite[PX].p_sejours SET
						code_original = w_sejours.code_original, 
						finess = w_sejours.finess, 
						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,
						risque_id = w_sejours.risque_id
					FROM w_sejours
					WHERE w_sejours.no_sejour = p_sejours.no_sejour
					AND (
						w_sejours.code_original IS DISTINCT FROM p_sejours.code_original OR
						w_sejours.finess IS DISTINCT FROM p_sejours.finess 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 OR
						w_sejours.risque_id IS DISTINCT FROM p_sejours.risque_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,
						risque_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,
						w_sejours.risque_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 w_ADDOL1 FROM w_ADP01 WHERE w_DOL1UN = '1'  AND w_ADCANN = '');
				
				-- Séjours ignorés
				UPDATE activite[PX].p_sejours
				SET etat = 'I'
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					est_ignore = '1' AND
					etat <> 'I' AND
					'[PX]' = '';

				UPDATE activite[PX].p_sejours
				SET etat = ''
				WHERE etat = 'I' AND 
					no_sejour NOT IN (SELECT no_sejour FROM activite.t_sejour WHERE est_ignore = '1') AND
					'[PX]' = '';
				
				-- Médecin séjour forcé
				UPDATE activite[PX].p_sejours
				SET medecin_sejour_id = t_sejour.medecin_sejour_id
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					t_sejour.medecin_sejour_id <> 0 AND
					p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
					'[PX]' = '';
				
				
					-- recréation index
				
				-- Suppression tables de travail
				DROP TABLE IF EXISTS w_ADP01_keys;
				DROP TABLE IF EXISTS w_ADP01_SEJOUR;
				DROP TABLE IF EXISTS w_sejours;
									
					

				-- transferts d'établissements
				INSERT INTO base.t_etablissements(code, texte, texte_court)
				SELECT 
					DDNDOP,
					DDNDOP,
					DDNDOP
				FROM prod_shs.[ACTIVITESCHEMA]_DDP01
				WHERE DDNDOP NOT IN (SELECT code FROM base.t_etablissements)
				GROUP BY 1,2,3
				;

				-- transferts d'établissements
				INSERT INTO base.t_etablissements(code, texte, texte_court)
				SELECT 
					DDNDOD,
					DDNDOD,
					DDNDOD
				FROM prod_shs.[ACTIVITESCHEMA]_DDP01
				WHERE DDNDOD NOT IN (SELECT code FROM base.t_etablissements)
				GROUP BY 1,2,3
				;

				INSERT INTO activite[PX].p_sejours_transferts (sejour_id, provenance_id, destination_id)
				SELECT 
					p_sejours.oid,
					(MAX(ARRAY[DDDCPL::text,provenance.oid::text]))[2]::bigint AS provenance_id,
					(MAX(ARRAY[DDDCPL::text,destination.oid::text]))[2]::bigint AS destination_id
				FROM
					activite[PX].p_sejours
					JOIN prod_shs.[ACTIVITESCHEMA]_DDP01 ON DDDOSS = no_sejour
				    LEFT JOIN base.t_etablissements provenance ON DDNDOP = provenance.code AND DDNDOP != ''
					LEFT JOIN base.t_etablissements destination ON DDNDOD = destination.code AND DDNDOD != ''
				WHERE 1!=1 OR
					DDNDOD != '' OR
					DDNDOP != ''
				GROUP BY 1
				;

				-- Assurance
				INSERT INTO activite[PX].p_sejours_assurance(
						sejour_id, 
						nom_assure, 
						prenom_assure, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						matricule_1, 
						tiers_payant_2_id, 
						matricule_2, 
						tiers_payant_22_id, 
						matricule_22
						)
					SELECT 
						p_sejours.oid AS sejour_id,
						MAX(w_ADNOM1) AS nom_assure, 
						MAX(w_ADPREM) prenom_assure,
						MAX(p_sejours.tiers_payant_0_id),
						MAX(p_sejours.tiers_payant_1_id),
						MAX(substr(w_ADMTSS,1,13)),
						MAX(p_sejours.tiers_payant_2_id),
						MAX(CASE WHEN w_ADMTMC <> '' THEN w_ADMTMC ELSE substr(w_ADMTSS,1,13) END) AS matricule_2,
						MAX(p_sejours.tiers_payant_22_id),
						MAX(''::text) AS matricule_2
					FROM w_ADP01
						  JOIN activite[PX].p_sejours ON code_original = w_ADDOSSDCPL
					GROUP BY 1
					;
				
					
			]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Mouvements">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_SOP01;
				CREATE TEMP TABLE w_SOP01 AS
				SELECT 	
					w_ADDOL1,
					w_ADDTHREN,
					w_ADDTHRSO,
					w_ADQURG,
					SODOSS AS w_SODOSS,
					SODCPL AS w_SODCPL,
					SOCSER AS w_SOCSER,
					SOACTI AS w_SOACTI,
					SOETAG AS w_SOETAG,
					SOCHLT AS w_SOCHLT,
					to_char(SOMEDS,'FM0000') AS w_SOMEDS,
					SODTSS AS w_SODTSS,
					SOHRSO AS w_SOHRSO,
					SODTE1 AS w_SODTE1,
					SOHREN AS w_SOHREN,
					w_ADDTHREN AS w_SODTHREN,
					to_timestamp(SODTSS || to_char(CASE WHEN SOHRSO BETWEEN 0 AND 240000 THEN SOHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI')::timestamp without time zone AS w_SODTHRSO
				FROM prod_shs.[ACTIVITESCHEMA]_SOP01 
					JOIN w_ADP01_sejours_modifies w_ADP01 ON w_ADDOSS = SODOSS AND w_ADDCPL = SODCPL AND w_CODENV = '' AND SODCPL = 0 AND w_ADDCPL = 0
				WHERE SOTYMV = '0' 
				ORDER BY w_ADDOL1, SODTSS
				; 

				INSERT INTO w_SOP01
				SELECT 	
					w_ADDOL1,
					w_ADDTHREN,
					w_ADDTHRSO,
					w_ADQURG,
					SODOSS AS w_SODOSS,
					SODCPL AS w_SODCPL,
					SOCSER AS w_SOCSER,
					SOACTI AS w_SOACTI,
					SOETAG AS w_SOETAG,
					SOCHLT AS w_SOCHLT,
					to_char(SOMEDS,'FM0000') AS w_SOMEDS,
					SODTSS AS w_SODTSS,
					SOHRSO AS w_SOHRSO,
					SODTE1 AS w_SODTE1,
					SOHREN AS w_SOHREN,
					w_ADDTHREN AS w_SODTHREN,
					to_timestamp(SODTSS || to_char(CASE WHEN SOHRSO BETWEEN 0 AND 240000 THEN SOHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI')::timestamp without time zone AS w_SODTHRSO
				FROM prod_shs.[ACTIVITESCHEMA]p_SOP01P 
					JOIN w_ADP01_sejours_modifies w_ADP01 ON w_ADDOSS = SODOSS AND w_ADDCPl = SODCPL AND w_CODENV = 'P'
				WHERE SOTYMV = '0' AND SODCPL = 0
				ORDER BY w_ADDOL1, SODTSS;


				INSERT INTO w_SOP01
				SELECT 	
					w_ADDOL1,
					w_ADDTHREN,
					w_ADDTHRSO,
					w_ADQURG,
					SODOSS AS w_SODOSS,
					SODCPL AS w_SODCPL,
					SOCSER AS w_SOCSER,
					SOACTI AS w_SOACTI,
					SOETAG AS w_SOETAG,
					SOCHLT AS w_SOCHLT,
					to_char(SOMEDS,'FM0000') AS w_SOMEDS,
					SODTSS AS w_SODTSS,
					SOHRSO AS w_SOHRSO,
					SODTE1 AS w_SODTE1,
					SOHREN AS w_SOHREN,
					w_ADDTHREN AS w_SODTHREN,
					to_timestamp(SODTSS || to_char(CASE WHEN SOHRSO BETWEEN 0 AND 240000 THEN SOHRSO ELSE 0 END,'0000'),'YYYYMMDD HH24MI')::timestamp without time zone AS w_SODTHRSO
				FROM prod_shs.[ACTIVITESCHEMA]h_SOP01H 
					JOIN w_ADP01_sejours_modifies w_ADP01 ON w_ADDOSS = SODOSS AND w_ADDCPl = SODCPL AND w_CODENV = 'H'
				WHERE SOTYMV = '0' AND SODCPL = 0
				ORDER BY w_ADDOL1, SODTSS;




				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT w_SOCSER, w_SOACTI, w_SOETAG, w_SOETAG || '|' || w_SOCHLT
				FROM w_SOP01 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = w_SOCSER AND
						code_original_2 = w_SOACTI AND
						code_original_3 = w_SOETAG AND
						code_original_4 = w_SOETAG || '|' || w_SOCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;




				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
					t_lieux.activite_id <> COALESCE(t_activites.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)
					;


				DROP TABLE IF EXISTS w_SOP01_2;
				CREATE TEMP TABLE w_SOP01_2 AS
				SELECT 
					w_ADDOL1,
					w_ADDTHREN,
					w_ADDTHRSO,
					w_ADQURG,
					w_SODOSS,
					w_SODCPL,
					w_SOCSER,
					w_SOACTI,
					w_SOETAG,
					w_SOCHLT,
					w_SOMEDS,
					w_SODTSS,
					w_SOHRSO,
					w_SODTE1,
					w_SOHREN,
					'1'::text AS w_QENTREE,
					w_SODTHREN,
					'1'::text AS w_QSORTIE,
					w_SODTHRSO,
					''::text AS w_SOCSER_before,
					''::text AS w_SOETAG_before,
					''::text AS w_SOCSER_next,
					''::text AS w_SOETAG_next,
					COALESCE(t_lieux.oid,0) AS lieu_id
				FROM w_SOP01 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = w_SOCSER AND
						code_original_2 = w_SOACTI AND
						code_original_3 = w_SOETAG AND
						code_original_4 = w_SOETAG || '|' || w_SOCHLT
					)
				ORDER BY w_ADDOL1, w_SODTHRSO;


				DROP SEQUENCE IF EXISTS w_SOP01_seq;
				CREATE TEMP SEQUENCE w_SOP01_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;

				DROP TABLE IF EXISTS w_SOP01;
				CREATE TEMP TABLE w_SOP01 AS
				SELECT 
					nextval('w_SOP01_seq'::regclass) AS sequence, 
					w_ADDOL1,
					w_ADDTHREN,
					w_ADDTHRSO,
					w_ADQURG,
					w_SODOSS,
					w_SODCPL,
					w_SOCSER,
					w_SOACTI,
					w_SOETAG,
					w_SOCHLT,
					w_SOMEDS,
					w_SODTSS,
					w_SOHRSO,
					w_SODTE1,
					w_SOHREN,
					w_QENTREE,
					w_SODTHREN,
					w_QSORTIE,
					w_SODTHRSO,
					w_SOCSER_before,
					w_SOETAG_before,
					w_SOCSER_next,
					w_SOETAG_next,
					lieu_id
				FROM w_SOP01_2 
				ORDER BY w_ADDOL1, w_SODTHRSO;
				
				-- Correction mouvements erronés
				UPDATE w_SOP01
				SET 
					w_SODTHREN = w_SOP01_before.w_SODTHRSO + interval '1 SECOND'
				FROM w_SOP01 w_SOP01_before
				WHERE w_SOP01.w_ADDOL1 = w_SOP01_before.w_ADDOL1
					AND w_SOP01.sequence = w_SOP01_before.sequence + 1;

				DROP TABLE IF EXISTS w_SOP01_SEJOUR;
				CREATE TEMP TABLE w_SOP01_SEJOUR AS
				SELECT 
					w_ADDOL1
				FROM w_SOP01
				GROUP BY 1
				HAVING count(*) > 1;

				DELETE FROM w_SOP01 
				USING w_SOP01_SEJOUR 
				WHERE w_SOP01_SEJOUR.w_ADDOL1 = w_SOP01.w_ADDOL1 AND w_SODTHREN > w_ADDTHRSO;

				DELETE FROM w_SOP01 
				USING w_SOP01_SEJOUR 
				WHERE w_SOP01_SEJOUR.w_ADDOL1 = w_SOP01.w_ADDOL1 AND w_SODTHRSO < w_ADDTHREN ;


				-- 
				
				DROP TABLE IF EXISTS w_SOP01_SEJOUR;
				CREATE TEMP TABLE w_SOP01_SEJOUR AS
				SELECT 
					w_ADDOL1,
					MIN(sequence) AS sequence_1,
					MAX(sequence) AS sequence_9
				FROM w_SOP01
				GROUP BY 1;



				UPDATE w_SOP01
				SET w_SODTHRSO = w_ADDTHRSO
				FROM w_SOP01_SEJOUR 
				WHERE w_SOP01.w_ADDOL1 = w_SOP01_SEJOUR.w_ADDOL1 AND w_SOP01.sequence = w_SOP01_SEJOUR.sequence_9 AND
					w_SODTHRSO <> w_ADDTHRSO
                    AND (w_SOP01_SEJOUR.sequence_1 <> w_SOP01_SEJOUR.sequence_9 OR (w_SOP01_SEJOUR.sequence_1 = w_SOP01_SEJOUR.sequence_9 AND w_SODTHRSO < w_ADDTHRSO));


				UPDATE w_SOP01
				SET w_SODTHREN = w_ADDTHREN
				FROM w_SOP01_SEJOUR 
				WHERE w_SOP01.w_ADDOL1 = w_SOP01_SEJOUR.w_ADDOL1 AND w_SOP01.sequence = w_SOP01_SEJOUR.sequence_1 AND
					w_SODTHREN <> w_ADDTHREN;




				UPDATE w_SOP01
					SET 
						w_QSORTIE = '0',
						w_SOCSER_next = w_SOP01_next.w_SOCSER,
						w_SOETAG_next = w_SOP01_next.w_SOETAG
					FROM w_SOP01 w_SOP01_next
					WHERE w_SOP01.w_ADDOL1 = w_SOP01_next.w_ADDOL1
						AND w_SOP01.sequence = w_SOP01_next.sequence - 1;



				UPDATE w_SOP01
					SET 
						w_QENTREE = '0',
						w_SODTHREN = w_SOP01_before.w_SODTHRSO + interval '1 SECOND',
						w_SOCSER_before = w_SOP01_before.w_SOCSER,
						w_SOETAG_before = w_SOP01_before.w_SOETAG
					FROM w_SOP01 w_SOP01_before
					WHERE w_SOP01.w_ADDOL1 = w_SOP01_before.w_ADDOL1
						AND w_SOP01.sequence = w_SOP01_before.sequence + 1;
						
						
				--
				
				
				-- Génération fichier de base



				DROP TABLE IF EXISTS w_mouvements_sejour;

				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_SOP01.w_ADDOL1,
					w_SOP01.w_ADDOL1 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 =  date(w_SODTHREN) THEN extract('hour' from w_SODTHREN) * 10000 + extract('minute' from w_SODTHREN) * 100 + extract('second' from w_SODTHREN) ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date =  date(w_SODTHRSO) THEN extract('hour' from w_SODTHRSO) * 10000 + extract('minute' from w_SODTHRSO) * 100 + extract('second' from w_SODTHRSO) ELSE 240000 END AS heure_fin,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_SODTHREN) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN w_QSORTIE = '1' AND p_calendrier.date =  date(w_SODTHRSO) AND p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_SODTHREN) AND p_sejours.type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN w_QSORTIE = '1' AND p_calendrier.date =  date(w_SODTHRSO) 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 w_QENTREE = '1' AND p_calendrier.date =  date(w_SODTHREN) AND p_sejours.type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN w_QENTREE = '1' AND p_calendrier.date =  date(w_SODTHREN) AND p_sejours.type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN w_ADQURG = '1' AND p_calendrier.date =  date(w_SODTHREN) AND w_QENTREE = '1' THEN 1 ELSE 0 END AS nb_urgences,
					0 as nb_seances,

					CASE WHEN p_calendrier.date = date(w_SODTHREN) AND p_sejours.type_sejour = '1' AND w_QENTREE <> '1' AND w_SOCSER <> w_SOCSER_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = date(w_SODTHRSO) AND p_sejours.type_sejour = '1' AND w_QSORTIE <> '1' AND w_SOCSER <> w_SOCSER_next THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = date(w_SODTHREN) AND p_sejours.type_sejour = '1' AND w_QENTREE <> '1' AND w_SOETAG <> w_SOETAG_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = date(w_SODTHRSO) AND p_sejours.type_sejour = '1' AND w_QSORTIE <> '1' AND w_SOETAG <> w_SOETAG_next THEN 1 ELSE 0 END AS nb_sorties_mutation_etage,
					0 AS nb_entrees_mutation_activite,
					0 AS nb_sorties_mutation_activite,
					0 AS nb_entrees_mutation_unite_medicale,
					0 AS nb_sorties_mutation_unite_medicale,

					CASE WHEN p_sejours.type_sejour = '1' THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN p_sejours.type_sejour = '1' AND (p_calendrier.date <> date(p_sejours.date_sortie) OR p_sejours.code_sorti <> '1') THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE 
						WHEN p_sejours.type_sejour = '1' AND t_lits.chambre_particuliere = 'O' THEN '1' 
						WHEN p_sejours.type_sejour = '2' AND t_lits.chambre_particuliere = 'O' AND w_QENTREE = '1' AND p_calendrier.date = date(w_SODTHREN) THEN '1' 
						ELSE '0' END AS est_chambre_particuliere,
					CASE 
						WHEN p_sejours.type_sejour = '1' AND t_lits.chambre_particuliere = 'O' THEN 1 
						WHEN p_sejours.type_sejour = '2' AND t_lits.chambre_particuliere = 'O' AND w_QENTREE = '1' AND p_calendrier.date = date(w_SODTHREN) THEN 1
						ELSE 0 END AS nb_chambres_particulieres,

					0 AS nb_bebes,

					lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id

				FROM w_SOP01 
					JOIN activite[PX].p_sejours ON w_SOP01.w_ADDOL1 = p_sejours.no_sejour AND p_sejours.etat = ''
					JOIN activite[PX].t_lits ON w_SOETAG || '|' || w_SOCHLT = t_lits.code_original
					JOIN base.p_calendrier ON (p_calendrier.date BETWEEN date(w_SODTHREN) AND date(w_SODTHRSO) AND p_calendrier.date <= now() )
				WHERE p_sejours.code_prevu <> '1' 
				ORDER BY sequence, p_calendrier.date;
				
				
				DELETE FROM w_mouvements_sejour WHERE heure_fin < heure_debut ;
				
				CREATE INDEX  w_mouvements_sejour_i1
				ON  w_mouvements_sejour
				USING btree
				(no_sejour);
				
				-- Séances d'après actes
				DROP TABLE IF EXISTS w_MFP01_seances;
				CREATE TEMP TABLE w_MFP01_seances AS
				SELECT 
					w_ADDOL1,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					SUM(CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END) AS MFNBRE
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
				WHERE 
					(MFRUPR = 189 OR 
					MFCCLE IN ('D01', 'D02', 'D03', 'D04', 'D05', 'D06', 'D07', 'D08', 'D09', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', 'D16', 'D17', 'D18', 'D19'))
				GROUP BY 1,2;

				INSERT INTO w_MFP01_seances
				SELECT 
					w_ADDOL1,
					
					COALESCE(to_date(to_char(ACDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					SUM(CASE WHEN w_ADADAV IN ('2', '4', '6') AND ACNBRE > 0 THEN 0 - ACNBRE ELSE ACNBRE END) AS ACNBRE
				FROM prod_shs.[ACTIVITESCHEMA]_ACP01
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (ACDOSS = w_ADDOSS AND ACDCPL = w_ADDCPL AND W_ADCFAC <> '1' AND w_CODENV = '')
				WHERE W_ADCFAC <> '1' AND ACCCLE IN ('K', 'ATM')  AND ACCNAT ='DIA' AND ACCCLH = '2' AND ACCANN = '1'
				GROUP BY 1,2;



				
				INSERT INTO w_MFP01_seances
				SELECT 
					w_ADDOL1,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					SUM(CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END) AS MFNBRE
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'P')
				WHERE 
					(MFRUPR = 189 OR 
					MFCCLE IN ('D01', 'D02', 'D03', 'D04', 'D05', 'D06', 'D07', 'D08', 'D09', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', 'D16', 'D17', 'D18', 'D19'))
				GROUP BY 1,2;

				INSERT INTO w_MFP01_seances
				SELECT 
					w_ADDOL1,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					SUM(CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END) AS MFNBRE
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'H')
				WHERE 
					(MFRUPR = 189 OR 
					MFCCLE IN ('D01', 'D02', 'D03', 'D04', 'D05', 'D06', 'D07', 'D08', 'D09', 'D10', 'D11', 'D12', 'D13', 'D14', 'D15', 'D16', 'D17', 'D18', 'D19'))
				GROUP BY 1,2;

				CREATE INDEX w_MFP01_seances_i1
				  ON w_MFP01_seances
				  USING btree
				  (w_ADDOL1);
				  
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = MFNBRE
				FROM w_MFP01_seances,
					activite[PX].t_lieux
					JOIN activite[PX].t_services_facturation ON t_lieux.service_facturation_id = t_services_facturation.oid
				WHERE w_MFP01_seances.w_ADDOL1 = w_mouvements_sejour.no_sejour AND 
					date(MFDTA1_date) = w_mouvements_sejour.date AND
					lieu_id = t_lieux.oid AND t_services_facturation.type_t2a NOT IN ('2','3');
				
				
				-- seances selon GHS pmsi
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date_entree AS date,
					1 AS nb_seances
				FROM activite[PX].p_sejours
					JOIN 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
					JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
					JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
				WHERE (date_sortie - date_entree) <= 1 AND p_sejours.type_sejour <> '5' AND
					t_services_facturation.type_sejour NOT IN ('2','0sauf5') AND
					(t_ghs.texte ilike '%séance%' OR
					t_ghm.code LIKE '28%');

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;			

				-- Séances non trouvées sur séjours forcés
				DROP TABLE IF EXISTS w_sejours_sans_seance;
				CREATE TEMP TABLE w_sejours_sans_seance AS
				SELECT w_mouvements_sejour.no_sejour, p_sejours.date_entree, MIN(CASE WHEN w_mouvements_sejour.date = date_entree THEN heure_debut ELSE 999999 END) AS heure_debut
					FROM w_mouvements_sejour
					JOIN activite[PX].p_sejours ON w_mouvements_sejour.no_sejour = p_sejours.no_sejour
					JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
					WHERE type_sejour = '5'
					GROUP BY 1,2
					HAVING SUM(nb_seances) = 0;

				CREATE INDEX  w_sejours_sans_seance_i1
				  ON  w_sejours_sans_seance
				  USING btree
				  (no_sejour);

				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM w_sejours_sans_seance
				WHERE w_mouvements_sejour.no_sejour = w_sejours_sans_seance.no_sejour AND 
					w_mouvements_sejour.date = w_sejours_sans_seance.date_entree AND
					w_mouvements_sejour.heure_debut = w_sejours_sans_seance.heure_debut;

				-- Bébés
				DROP TABLE IF EXISTS w_MFP01_bebes;
				CREATE TEMP TABLE w_MFP01_bebes AS
				SELECT 
					w_ADDOL1,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CCAM
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
					JOIN base.t_actes ON substring(MFCCAM, 1, 7) = t_actes.code AND 
						MFCCAM LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
				WHERE MFDCPL = 0 AND MFCCAC = '1'
				GROUP BY 1;


				INSERT INTO w_MFP01_bebes
				SELECT 
					w_ADDOL1,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_shs.[ACTIVITESCHEMA]_ACP01
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (ACDOSS = w_ADDOSS AND ACDCPL = w_ADDCPL AND W_ADCFAC <> '1' AND w_CODENV = '')
					JOIN base.t_actes ON substring(ACCCAM, 1, 7) = t_actes.code AND 
						ACCCAM LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
				WHERE ACCCLH = '2' AND ACDCPL = 0 AND ACCCAC = '1'
				GROUP BY 1;

				INSERT INTO w_MFP01_bebes
				SELECT 
					w_ADDOL1,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CCAMP
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
					JOIN base.t_actes ON substring(MFCCAM, 1, 7) = t_actes.code AND 
						MFCCAM LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
				WHERE MFDCPL = 0 AND MFCCAC = '1'
				GROUP BY 1;

				INSERT INTO w_MFP01_bebes
				SELECT 
					w_ADDOL1,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CCAMH
					JOIN w_ADP01_sejours_modifies w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
					JOIN base.t_actes ON substring(MFCCAM, 1, 7) = t_actes.code AND 
						MFCCAM LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
				WHERE MFDCPL = 0 AND MFCCAC = '1'
				GROUP BY 1;

				CREATE INDEX w_MFP01_bebes_i1
				  ON w_MFP01_bebes
				  USING btree
				  (w_ADDOL1);


				UPDATE w_mouvements_sejour 
				SET nb_bebes = w_MFP01_bebes.nb_bebes
				FROM w_MFP01_bebes 
				WHERE w_MFP01_bebes.w_ADDOL1 = w_mouvements_sejour.no_sejour AND
					(nb_entrees_directes = 1 OR nb_externes = 1 OR nb_ambulatoires = 1);


				

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

				DELETE FROM activite[PX].p_mouvements_sejour WHERE no_sejour NOT IN (SELECT w_ADDOL1 FROM w_ADP01 WHERE w_DOL1UN = '1'  AND w_ADCANN = '');
				DELETE FROM activite[PX].p_mouvements_sejour WHERE no_sejour IN (SELECT w_ADDOL1 FROM w_ADP01_sejours_modifies WHERE w_DOL1UN = '1'  AND w_ADCANN = '');

				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_5');
				
				INSERT INTO activite[PX].p_mouvements_sejour(
							sejour_id, no_sejour, date, nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale,
							nb_bebes, jour_semaine, is_weekend)
				SELECT sejour_id, no_sejour, date,nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale,
							nb_bebes, jour_semaine, is_weekend
				FROM w_mouvements_sejour 
				ORDER BY no_sejour, sequence;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_5');
				
				
				-- Suppression tables de travail
				DROP TABLE IF EXISTS w_SOP01;
				DROP TABLE IF EXISTS w_SOP01_2;
				DROP TABLE IF EXISTS w_mouvements_sejour;
				DROP TABLE IF EXISTS w_MFP01_seances;
				DROP TABLE IF EXISTS w_MFP01_bebes;
				
				
				
				UPDATE activite[PX].p_sejours
				SET type_sejour = '5'
				FROM activite[PX].t_lieux
					JOIN activite[PX].t_services_facturation ON t_services_facturation.oid = service_facturation_id
				WHERE lieu_sortie_id = t_lieux.oid AND
					p_sejours.type_sejour <> '5' AND 
					p_sejours.type_sejour <> '1' AND
					t_services_facturation.type_sejour NOT IN ('2','0sauf5') 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>

	<NODE name="FACTURE" label="RECUPERATION DES FACTURES">
	
		<NODE label="Entêtes">
			<sqlcmd><![CDATA[

				
				DROP TABLE IF EXISTS w_FTP01_GROUP;
				CREATE TEMP TABLE w_FTP01_GROUP AS
				SELECT 
					w_ADDOSSDCPL,

					MAX(CASE WHEN FTTYPC = '0' AND (FTCEXP = '1' OR FTDTEX <> 0) THEN '1' ELSE '0' END) AS FTCEXP_0,
					MAX(CASE WHEN FTTYPC = '0' THEN GREATEST(FTDTEX, w_ADDTFA) ELSE 0 END) AS FTDTEX_0,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '0' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_0_date,
					MAX(CASE WHEN FTTYPC = '0' THEN FTNBOR ELSE 0 END) AS FTNBOR_0,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_H,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_H,
					
					MAX(CASE WHEN FTTYPC = '1' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTCEXP ELSE '' END) AS FTCEXP_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 0 END) AS FTDTEX_1,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_1_date,
					MAX(CASE WHEN FTTYPC = '1' THEN FTNBOR ELSE 0 END) AS FTNBOR_1,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_H,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_H,
					
					MAX(CASE WHEN FTTYPC = '2' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTCEXP ELSE '' END) AS FTCEXP_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 0 END) AS FTDTEX_2,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_2_date,
					MAX(CASE WHEN FTTYPC = '2' THEN FTNBOR ELSE 0 END) AS FTNBOR_2,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_H,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_H,
					
					MAX(CASE WHEN FTTYPC = '3' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTCEXP ELSE '' END) AS FTCEXP_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 0 END) AS FTDTEX_22,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_22_date,
					MAX(CASE WHEN FTTYPC = '3' THEN FTNBOR ELSE 0 END) AS FTNBOR_22,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_H,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_H
					
				FROM prod_shs.[ACTIVITESCHEMA]_FTP01
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FTDOSS = w_ADDOSS AND FTDCPL = w_ADDCPL AND w_CODENV = '')

				GROUP BY 1;




				INSERT INTO w_FTP01_GROUP 
				SELECT 
					w_ADDOSSDCPL,

					MAX(CASE WHEN FTTYPC = '0' AND (FTCEXP = '1' OR FTDTEX <> 0) THEN '1' ELSE '0' END) AS FTCEXP_0,
					MAX(CASE WHEN FTTYPC = '0' THEN GREATEST(FTDTEX, w_ADDTFA) ELSE 0 END) AS FTDTEX_0,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '0' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_0_date,
					MAX(CASE WHEN FTTYPC = '0' THEN FTNBOR ELSE 0 END) AS FTNBOR_0,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_H,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_H,
					
					MAX(CASE WHEN FTTYPC = '1' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTCEXP ELSE '' END) AS FTCEXP_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 0 END) AS FTDTEX_1,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_1_date,
					MAX(CASE WHEN FTTYPC = '1' THEN FTNBOR ELSE 0 END) AS FTNBOR_1,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_H,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_H,
					
					MAX(CASE WHEN FTTYPC = '2' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTCEXP ELSE '' END) AS FTCEXP_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 0 END) AS FTDTEX_2,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_2_date,
					MAX(CASE WHEN FTTYPC = '2' THEN FTNBOR ELSE 0 END) AS FTNBOR_2,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_H,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_H,
					
					MAX(CASE WHEN FTTYPC = '3' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTCEXP ELSE '' END) AS FTCEXP_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 0 END) AS FTDTEX_22,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_22_date,
					MAX(CASE WHEN FTTYPC = '3' THEN FTNBOR ELSE 0 END) AS FTNBOR_22,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_H,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_H
					
				FROM prod_shs.[ACTIVITESCHEMA]p_FTP01P
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FTDOSS = w_ADDOSS AND FTDCPL = w_ADDCPL AND w_CODENV = 'P')

				GROUP BY 1;




				INSERT INTO w_FTP01_GROUP
				SELECT 
					w_ADDOSSDCPL,
					
					MAX(CASE WHEN FTTYPC = '0' AND (FTCEXP = '1' OR FTDTEX <> 0) THEN '1' ELSE '0' END) AS FTCEXP_0,
					MAX(CASE WHEN FTTYPC = '0' THEN GREATEST(FTDTEX, w_ADDTFA) ELSE 0 END) AS FTDTEX_0,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '0' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_0_date,
					MAX(CASE WHEN FTTYPC = '0' THEN FTNBOR ELSE 0 END) AS FTNBOR_0,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_0_H,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_C,
					SUM(CASE WHEN FTTYPC = '0' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_0_H,
					
					MAX(CASE WHEN FTTYPC = '1' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTCEXP ELSE '' END) AS FTCEXP_1,
					MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 0 END) AS FTDTEX_1,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '1' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_1_date,
					MAX(CASE WHEN FTTYPC = '1' THEN FTNBOR ELSE 0 END) AS FTNBOR_1,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_1_H,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_C,
					SUM(CASE WHEN FTTYPC = '1' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_1_H,
					
					MAX(CASE WHEN FTTYPC = '2' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTCEXP ELSE '' END) AS FTCEXP_2,
					MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 0 END) AS FTDTEX_2,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '2' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_2_date,
					MAX(CASE WHEN FTTYPC = '2' THEN FTNBOR ELSE 0 END) AS FTNBOR_2,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_2_H,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_C,
					SUM(CASE WHEN FTTYPC = '2' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_2_H,
					
					MAX(CASE WHEN FTTYPC = '3' THEN to_char(FTCCAI,'FM0000') ELSE NULL END) AS FTCCAI_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTCEXP ELSE '' END) AS FTCEXP_22,
					MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 0 END) AS FTDTEX_22,
					COALESCE(to_date(to_char(MAX(CASE WHEN FTTYPC = '3' THEN FTDTEX ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS FTDTEX_22_date,
					MAX(CASE WHEN FTTYPC = '3' THEN FTNBOR ELSE 0 END) AS FTNBOR_22,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS FTMTFA_22_H,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '1' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_C,
					SUM(CASE WHEN FTTYPC = '3' AND FTCCLH = '2' THEN FTMTRG + FTMTRM + FTMTOD ELSE 0 END) AS FTMTRG_22_H
					
				FROM prod_shs.[ACTIVITESCHEMA]h_FTP01H
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FTDOSS = w_ADDOSS AND FTDCPL = w_ADDCPL AND w_CODENV = 'H')

				GROUP BY 1;


				ALTER TABLE w_FTP01_GROUP ADD CONSTRAINT w_FTP01_GROUP_pkey PRIMARY KEY(w_ADDOSSDCPL);


				DROP TABLE IF EXISTS w_MCP01_GROUP;
				CREATE TEMP TABLE w_MCP01_GROUP AS
				SELECT 
					w_ADDOSSDCPL,
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41110000 OR MCCPTE = 41910000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_C_date,  
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41210000 OR MCCPTE = 41920000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_H_date, 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41110001 AND 41111999) OR (MCCPTE BETWEEN 41113000 AND 41114999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41210001 AND 41211999) OR (MCCPTE BETWEEN 41213000 AND 41214999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_H_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41112001 AND 41112999) OR (MCCPTE BETWEEN 41115000 AND 41119999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41212001 AND 41212999) OR (MCCPTE BETWEEN 41215000 AND 41219999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_H_date 
				FROM prod_shs.[ACTIVITESCHEMA]_MCP01ACTI
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MCDOSA = w_ADDOSS_A AND MCDCPA = w_ADDCPL_A AND w_CODENV = '')
				WHERE ((MCCPTE BETWEEN 41110000 AND 41119999) OR (MCCPTE BETWEEN 41210000 AND 41219999) OR (MCCPTE BETWEEN 41910000 AND 41920000)) AND MCDOSA != '' AND MCDOSA <> '00000000' AND MCCJAL >= 100 
				
				GROUP BY 1;



				INSERT INTO w_MCP01_GROUP 
				SELECT 
					w_ADDOSSDCPL,
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41110000 OR MCCPTE = 41910000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_C_date,  
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41210000 OR MCCPTE = 41920000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_H_date, 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41110001 AND 41111999) OR (MCCPTE BETWEEN 41113000 AND 41114999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41210001 AND 41211999) OR (MCCPTE BETWEEN 41213000 AND 41214999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_H_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41112001 AND 41112999) OR (MCCPTE BETWEEN 41115000 AND 41119999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41212001 AND 41212999) OR (MCCPTE BETWEEN 41215000 AND 41219999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_H_date 
				FROM prod_shs.[ACTIVITESCHEMA]p_MCP01ACTIP
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MCDOSA = w_ADDOSS_A AND MCDCPA = w_ADDCPL_A AND w_CODENV = 'P')
				WHERE ((MCCPTE BETWEEN 41110000 AND 41119999) OR (MCCPTE BETWEEN 41210000 AND 41219999) OR (MCCPTE BETWEEN 41910000 AND 41920000)) AND MCDOSA != '' AND MCDOSA <> '00000000' AND MCCJAL >= 100 
				
				GROUP BY 1;




				INSERT INTO w_MCP01_GROUP
				SELECT 
					w_ADDOSSDCPL,
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41110000 OR MCCPTE = 41910000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_C_date,  
					COALESCE(to_date(to_char(MAX(CASE WHEN MCCPTE = 41210000 OR MCCPTE = 41920000 THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_0_H_date, 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41110001 AND 41111999) OR (MCCPTE BETWEEN 41113000 AND 41114999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41210001 AND 41211999) OR (MCCPTE BETWEEN 41213000 AND 41214999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_1_H_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41112001 AND 41112999) OR (MCCPTE BETWEEN 41115000 AND 41119999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_C_date , 
					COALESCE(to_date(to_char(MAX(CASE WHEN (MCCPTE BETWEEN 41212001 AND 41212999) OR (MCCPTE BETWEEN 41215000 AND 41219999) THEN MCDTEC ELSE 00010101 END),'FM00000000'),'YYYYMMDD'),'00010101') AS MCDTEC_2_H_date 
				FROM prod_shs.[ACTIVITESCHEMA]h_MCP01ACTIH
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MCDOSA = w_ADDOSS_A AND MCDCPA = w_ADDCPL_A AND w_CODENV = 'H')
				WHERE ((MCCPTE BETWEEN 41110000 AND 41119999) OR (MCCPTE BETWEEN 41210000 AND 41219999) OR (MCCPTE BETWEEN 41910000 AND 41920000)) AND MCDOSA != '' AND MCDOSA <> '00000000' AND MCCJAL >= 100 
				
				GROUP BY 1;



				ALTER TABLE w_MCP01_GROUP ADD CONSTRAINT w_MCP01_GROUP_pkey PRIMARY KEY(w_ADDOSSDCPL);

				
				DROP TABLE IF EXISTS w_factures;
				CREATE TEMP TABLE w_factures AS
				SELECT 
					COALESCE(p_factures.oid,nextval('activite[PX].s_factures'::regclass)) AS oid,
					p_sejours.oid AS sejour_id,
					w_ADDOL1 AS no_sejour,
					w_ADP01.w_ADDOSS,
					w_ADP01.w_ADDCPL,
					w_ADP01.w_ADDOSSDCPL AS no_facture,
					CASE WHEN w_ADADAV = '0' THEN w_ADP01.w_ADDOSSDCPL ELSE substr(w_ADP01.w_ADDOSSDCPL,1,9) || '00' END AS no_facture_reference,
					CASE WHEN w_ADADAV = '0' THEN COALESCE(p_factures.oid,0) ELSE 0 END AS facture_reference_id,
					''::text AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id,
					w_ADP01.w_ADDTE1_date AS date_debut,
					w_ADP01.w_ADDTS1_date 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 AS code_cp_demandee,
					CASE WHEN w_ADADAV IN ('2', '4', '6') THEN '1' WHEN w_ADADAV IN ('1', '3') THEN '2' WHEN w_ADADAV IN ('5') THEN '3' ELSE '0' END AS type_facture,
					CASE WHEN w_ADADAV IN ('2', '4', '6') THEN 1::numeric ELSE 0::numeric END AS nb_rejets,
					CASE WHEN w_ADPAD5 = '1' THEN '1' WHEN w_ADCFAC = '1' THEN '1' ELSE '0' END AS code_facture,
					CASE WHEN w_ADPAD5 = '1' OR w_ADCFAC = '1' THEN CASE WHEN w_ADDTFA_date <> '20991231' THEN w_ADDTFA_date ELSE w_ADDTS1_date END ELSE '20991231' END AS date_facture,
					w_ADCJVT AS code_vente,
					w_ADAAJV * 100 + w_ADMMJV AS mois_vente,
					w_ADDTJV_date AS date_vente,
					w_CODENV AS code_cloture,

					CASE WHEN p_sejours.ghs_id > 0 THEN 'GHS' ELSE '' END AS particularite_t2a,
					
					COALESCE(t_tiers_payant_0.oid,0) AS tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid,0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid,0) AS tiers_payant_2_id,
					COALESCE(t_tiers_payant_22.oid,0) AS tiers_payant_22_id,
					COALESCE(FTMTFA_0_C + FTMTFA_1_C + FTMTFA_2_C + FTMTFA_22_C,0) AS montant_facture_c,
					COALESCE(FTMTFA_0_H + FTMTFA_1_H + FTMTFA_2_H + FTMTFA_22_H,0) AS montant_facture_h,
					COALESCE(FTMTFA_0_C,0) AS montant_facture_0_c,
					COALESCE(FTMTFA_0_H,0) AS montant_facture_0_h,
					COALESCE(FTMTFA_1_C,0) AS montant_facture_1_c,
					COALESCE(FTMTFA_1_H,0) AS montant_facture_1_h,
					COALESCE(FTMTFA_2_C,0) AS montant_facture_2_c,
					COALESCE(FTMTFA_2_H,0) AS montant_facture_2_h,
					COALESCE(FTMTFA_22_C,0) AS montant_facture_22_c,
					COALESCE(FTMTFA_22_H,0) AS montant_facture_22_h,
					COALESCE(FTMTFA_0_C + FTMTFA_1_C + FTMTFA_2_C + FTMTFA_22_C,0) AS montant_comptabilise_c,
					COALESCE(FTMTFA_0_H + FTMTFA_1_H + FTMTFA_2_H + FTMTFA_22_H,0) AS montant_comptabilise_h,
					COALESCE(FTMTFA_0_C,0) AS montant_comptabilise_0_c,
					COALESCE(FTMTFA_0_H,0) AS montant_comptabilise_0_h,
					COALESCE(FTMTFA_1_C,0) AS montant_comptabilise_1_c,
					COALESCE(FTMTFA_1_H,0) AS montant_comptabilise_1_h,
					COALESCE(FTMTFA_2_C,0) AS montant_comptabilise_2_c,
					COALESCE(FTMTFA_2_H,0) AS montant_comptabilise_2_h,
					COALESCE(FTMTFA_22_C,0) AS montant_comptabilise_22_c,
					COALESCE(FTMTFA_22_H,0) AS montant_comptabilise_22_h,
					COALESCE(FTMTRG_0_C + FTMTRG_1_C + FTMTRG_2_C + FTMTRG_22_C,0) AS montant_regle_c,
					COALESCE(FTMTRG_0_H + FTMTRG_1_H + FTMTRG_2_H + FTMTRG_22_H,0) AS montant_regle_h,
					COALESCE(FTMTRG_0_C,0) AS montant_regle_0_c,
					COALESCE(FTMTRG_0_H,0) AS montant_regle_0_h,
					COALESCE(FTMTRG_1_C,0) AS montant_regle_1_c,
					COALESCE(FTMTRG_1_H,0) AS montant_regle_1_h,
					COALESCE(FTMTRG_2_C,0) AS montant_regle_2_c,
					COALESCE(FTMTRG_2_H,0) AS montant_regle_2_h,
					COALESCE(FTMTRG_22_C,0) AS montant_regle_22_c,
					COALESCE(FTMTRG_22_H,0) AS montant_regle_22_h,
					COALESCE(FTCEXP_0,'0') AS code_expedie_0,
					COALESCE(FTCEXP_1,'0') AS code_expedie_1,
					COALESCE(FTCEXP_2,'0') AS code_expedie_2,
					COALESCE(FTCEXP_22,'0') AS code_expedie_22,
					COALESCE(CASE WHEN FTDTEX_1_date > '00010101' THEN FTDTEX_1_date
								  WHEN FTDTEX_2_date > '00010101' THEN FTDTEX_2_date
								  WHEN FTDTEX_0_date > '00010101' THEN FTDTEX_0_date
								  ELSE FTDTEX_2_date END, '00010101') AS date_expedition,
					CASE WHEN w_ADDTFA_date <> '20991231' AND COALESCE(FTDTEX_0_date,'20991231') < w_ADDTFA_date THEN w_ADDTFA_date ELSE COALESCE(FTDTEX_0_date,'00010101') END AS date_expedition_0,
					COALESCE(FTDTEX_1_date,'00010101') AS date_expedition_1,
					COALESCE(FTDTEX_2_date,'00010101') AS date_expedition_2,
					COALESCE(FTDTEX_22_date,'00010101') AS date_expedition_22,
					COALESCE(FTNBOR_0,0) AS no_bordereau_0,
					COALESCE(FTNBOR_1,0) AS no_bordereau_1,
					COALESCE(FTNBOR_2,0) AS no_bordereau_2,
					COALESCE(FTNBOR_22,0) AS no_bordereau_22,

					COALESCE(GREATEST(MCDTEC_0_C_date, MCDTEC_1_C_date, MCDTEC_2_C_date, MCDTEC_0_H_date, MCDTEC_1_H_date, MCDTEC_2_H_date),'20991231') AS date_solde,
					COALESCE(GREATEST(MCDTEC_0_C_date, MCDTEC_1_C_date, MCDTEC_2_C_date),'20991231') AS date_solde_c,
					COALESCE(GREATEST(MCDTEC_0_H_date, MCDTEC_1_H_date, MCDTEC_2_H_date),'20991231') AS date_solde_h,
					COALESCE(MCDTEC_0_C_date,'20991231') AS date_solde_0_c,
					COALESCE(MCDTEC_0_H_date,'20991231') AS date_solde_0_h,
					COALESCE(MCDTEC_1_C_date,'20991231') AS date_solde_1_c,
					COALESCE(MCDTEC_1_H_date,'20991231') AS date_solde_1_h,
					COALESCE(MCDTEC_2_C_date,'20991231') AS date_solde_2_c,
					COALESCE(MCDTEC_2_H_date,'20991231') AS date_solde_2_h,
					COALESCE(MCDTEC_2_C_date,'20991231') AS date_solde_22_c,
					COALESCE(MCDTEC_2_H_date,'20991231') AS date_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,

					'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,

					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					0::numeric AS delai_expedition,
					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,


					'20991231'::date AS date_encours,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					0::numeric AS montant_comptabilise_budget_global_c

					FROM w_ADP01_factures_modifiees w_ADP01
						JOIN activite[PX].p_sejours ON w_ADP01.w_ADDOL1 = p_sejours.no_sejour
						LEFT JOIN w_FTP01_GROUP ON (w_FTP01_GROUP.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL)
						LEFt JOIN w_MCP01_GROUP ON (w_MCP01_GROUP.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL)
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_0 ON '0000' = t_tiers_payant_0.code_original
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON FTCCAI_1 = t_tiers_payant_1.code_original
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON FTCCAI_2 = t_tiers_payant_2.code_original
						LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_22 ON FTCCAI_22 = t_tiers_payant_22.code_original
						LEFT JOIN activite[PX].p_factures ON w_ADP01.w_ADDOSSDCPL = p_factures.no_facture;

				ALTER TABLE w_factures ADD CONSTRAINT w_factures_pkey PRIMARY KEY(no_facture);

				CREATE INDEX w_factures_i1
				  ON w_factures
				  USING btree
				  (w_ADDOSS);

				CREATE INDEX w_factures_i2
				  ON w_factures
				  USING btree
				  (no_facture_reference);
				
				DROP TABLE IF EXISTS w_factures_od_avoir;
				CREATE TEMP TABLE w_factures_od_avoir AS
				SELECT
					oid AS facture_od_avoir_id,
					no_facture AS no_facture_od_avoir,
					''::text AS no_facture,
					0::bigint AS facture_id,
					w_ADDOSS,
					w_ADDCPL,
					montant_facture_c,
					montant_facture_0_c,
					montant_facture_1_c,
					montant_facture_2_c,
					montant_facture_22_c,
					montant_facture_h,
					montant_facture_0_h,
					montant_facture_1_h,
					montant_facture_2_h,
					montant_facture_22_h
				FROM w_factures
				WHERE type_facture = '1';

				ALTER TABLE w_factures_od_avoir ADD CONSTRAINT w_factures_od_avoir_od_pkey PRIMARY KEY(no_facture_od_avoir);

				CREATE INDEX w_factures_od_avoir_i1
				  ON w_factures_od_avoir
				  USING btree
				  (w_ADDOSS);

				UPDATE w_factures_od_avoir SET no_facture = w_factures.no_facture, facture_id = w_factures.oid
				FROM w_factures   
				WHERE 
					w_factures_od_avoir.w_ADDOSS = w_factures.w_ADDOSS AND w_factures_od_avoir.w_ADDCPL = w_factures.w_ADDCPL + 1 AND
					w_factures_od_avoir.montant_facture_c = 0 - w_factures.montant_facture_c AND
					w_factures_od_avoir.montant_facture_0_c = 0 - w_factures.montant_facture_0_c AND
					w_factures_od_avoir.montant_facture_1_c = 0 - w_factures.montant_facture_1_c AND
					w_factures_od_avoir.montant_facture_2_c = 0 - w_factures.montant_facture_2_c AND
					w_factures_od_avoir.montant_facture_22_c = 0 - w_factures.montant_facture_22_c AND
					w_factures_od_avoir.montant_facture_h = 0 - w_factures.montant_facture_h AND
					w_factures_od_avoir.montant_facture_0_h = 0 - w_factures.montant_facture_0_h AND
					w_factures_od_avoir.montant_facture_1_h = 0 - w_factures.montant_facture_1_h AND
					w_factures_od_avoir.montant_facture_2_h = 0 - w_factures.montant_facture_2_h AND
					w_factures_od_avoir.montant_facture_22_h = 0 - w_factures.montant_facture_22_h;

				UPDATE w_factures SET 
					type_facture = 'X' ,
					no_facture_od_avoir = w_factures_od_avoir.no_facture_od_avoir,
					facture_od_avoir_id = w_factures_od_avoir.facture_od_avoir_id 
				FROM w_factures_od_avoir
				WHERE w_factures.no_facture = w_factures_od_avoir.no_facture AND w_factures_od_avoir.no_facture <> '' AND w_factures_od_avoir.no_facture_od_avoir <> '';

				UPDATE w_factures SET 
					no_facture_od_avoir = w_factures_od_avoir.no_facture,
					facture_od_avoir_id = w_factures_od_avoir.facture_id
				FROM w_factures_od_avoir
				WHERE w_factures.no_facture = w_factures_od_avoir.no_facture_od_avoir AND w_factures_od_avoir.no_facture <> '' AND w_factures_od_avoir.no_facture_od_avoir <> '';

					
				DROP TABLE IF EXISTS w_factures_references;
				CREATE TEMP TABLE w_factures_references AS
				SELECT w_ADDOSS, COALESCE(MIN(CASE WHEN type_facture NOT IN ('X', '1') THEN no_facture ELSE NULL END), MIN(no_facture)) AS no_facture_reference
				FROM w_factures
				GROUP BY 1;


				UPDATE w_factures SET 
					no_facture_reference = w_factures_references.no_facture_reference,
					facture_reference_id = 0
				FROM w_factures_references
				WHERE w_factures.w_ADDOSS = w_factures_references.w_ADDOSS AND
					w_factures.no_facture_reference <> w_factures_references.no_facture_reference;
					
				UPDATE w_factures SET 
					type_facture = '0'
				WHERE type_facture <> '0' AND no_facture = no_facture_reference;

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

				ALTER TABLE w_factures_references_soldes ADD CONSTRAINT w_factures_references_soldes_pkey PRIMARY KEY(no_facture_reference);
				
				
				UPDATE w_factures
				SET facture_reference_id = w_factures_references.oid
				FROM w_factures w_factures_references
				WHERE w_factures.no_facture_reference = w_factures_references.no_facture
					AND w_factures.facture_reference_id <> w_factures_references.oid;

				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
					AND w_factures.facture_od_avoir_id <> w_factures_od_avoir.oid;

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

				DELETE FROM activite[PX].p_factures WHERE no_facture IN (SELECT w_ADDOSSDCPL FROM w_ADP01_factures_modifiees);

				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_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,


					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,

					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,

					delai_facture,
					delai_solde,
					delai_expedition,
					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,


					date_encours,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_c

					)

				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_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,


					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,

					CASE WHEN w_factures_references_soldes.date_solde_reference <> '00010101' THEN w_factures_references_soldes.date_solde_reference ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_0_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_0_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_1_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_1_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_2_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_2_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_22_c <> '00010101' THEN w_factures_references_soldes.date_solde_reference_22_c ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_0_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_0_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_1_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_1_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_2_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_2_h ELSE '20991231' END,
					CASE WHEN w_factures_references_soldes.date_solde_reference_22_h <> '00010101' THEN w_factures_references_soldes.date_solde_reference_22_h ELSE '20991231' END,

					delai_facture,
					delai_solde,
					delai_expedition,
					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,

					date_encours,
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour,
					montant_comptabilise_budget_global_c

				FROM w_factures 
					JOIN w_factures_references_soldes ON w_factures.no_facture_reference = w_factures_references_soldes.no_facture_reference
				WHERE oid NOT IN (SELECT oid FROM activite[PX].p_factures);
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_13');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_14');


				
										
								
								
								
				-- Suppression tables de travail
				
				DROP TABLE IF EXISTS w_FTP01_GROUP;
				DROP TABLE IF EXISTS w_MCP01_GROUP;
				DROP TABLE IF EXISTS w_factures;
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_TRP01;
				CREATE TEMP TABLE w_TRP01 AS 
				SELECT                                     
					0::bigint AS TRSEQU,
					TRCSER, 
					TRCRUB, 
					TRDTTR AS TRDTT1,
					20991231::numeric AS TRDTT9, 
					TRPRUE   
				FROM prod_shs.[ACTIVITESCHEMA]_TRP02                       
				WHERE TRCENR = 'A51' AND TRSUJT = ''       
				ORDER BY TRCSER, TRCRUB, TRDTTR;

				DROP SEQUENCE IF EXISTS w_TRP01_seq;
				CREATE TEMP SEQUENCE w_TRP01_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;

				UPDATE w_TRP01 SET TRSEQU = nextval('w_TRP01_seq'::regclass);


				UPDATE w_TRP01
				SET TRDTT9 = w_TRP01_next.TRDTT1 -1
				FROM w_TRP01 w_TRP01_next
				WHERE w_TRP01.TRCSER = w_TRP01_next.TRCSER AND
					w_TRP01.TRCRUB = w_TRP01_next.TRCRUB AND
					w_TRP01.TRSEQU = w_TRP01_next.TRSEQU - 1;
					
					
				-- Modification quantité si détail dans ACP08
				UPDATE prod_shs.[ACTIVITESCHEMA]_ACP01 ACP01
				SET ACNBRE = ACQUAN
				FROM prod_shs.[ACTIVITESCHEMA]_ACP08 ACP08
				WHERE ACP08.ACDOSS = ACP01.ACDOSS AND
					ACP08.ACDCPL = ACP01.ACDCPL AND
					ACP08.ACNOR3 = ACP01.ACNOR3 AND
					ACCCLH = '1' AND
					ACQUAN <> ACNBRE
				;

				-- 
				DROP TABLE IF EXISTS w_ACP01;
				CREATE TEMP TABLE w_ACP01 AS
				SELECT 
					w_ADDOSSDCPL,
					ACDTA1,
					COALESCE(to_date(to_char(ACDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS ACDTA1_date,
					COALESCE(to_date(to_char(CASE WHEN ACDTA9 >= ACDTA1 THEN ACDTA9 ELSE ACDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS ACDTA9_date,
					w_ADCSER AS ACCSER,
					w_ADACTI AS ACACTI,
					w_ADETAG AS ACETAG,
					w_ADCHLT AS ACCHLT,
					substr(to_char(ACRUPR,'0000'),3,3) AS ACRUPR,
					ACCCLE,
					ACCLPP,
					w_ADCSER || '|' || w_ADACTI || '|' || w_ADETAG || '|' || w_ADCHLT || '|' || ACCLPP || '|' || ACCCLE || '|' || substr(to_char(ACRUPR,'0000'),3,3) AS key,
					CASE WHEN w_ADADAV IN ('2', '4', '6') AND ACNBRE > 0 THEN 0 - ACNBRE ELSE ACNBRE END AS ACNBRE,
					CASE WHEN ACCOE1 <> 0 THEN ACCOE1 ELSE 1 END AS ACCOE1,
					ACPRUA	
				FROM prod_shs.[ACTIVITESCHEMA]_ACP01
					JOIN w_ADP01 ON (ACDOSS = w_ADDOSS AND ACDCPL = w_ADDCPL AND W_ADCFAC <> '1' AND w_CODENV = '')
				WHERE ACCCLH = '1' AND ACCANN = '1';


				UPDATE w_ACP01 SET ACPRUA = TRPRUE
				FROM w_TRP01
				WHERE ACCSER = TRCSER AND ACRUPR = TRCRUB AND ACPRUA = 0 AND ACDTA1 BETWEEN TRDTT1 AND TRDTT9;


				DROP TABLE IF EXISTS w_ACP01_keys;
				CREATE TEMP TABLE w_ACP01_keys AS
				SELECT 
					key,
					ACCSER,
					ACACTI,
					ACETAG,
					ACCHLT,
					ACCCLE, 
					ACCLPP,
					ACRUPR,
					0::bigint AS rubrique_facturation_id,
					''::text AS prestation_code, 
					0::bigint AS prestation_id, 
					0::bigint AS lieu_id, 
					0::bigint AS ucd_id, 
					0::bigint AS lpp_id 
				FROM w_ACP01
				GROUP BY 1,2,3,4,5,6,7,8;

				UPDATE w_ACP01_keys	SET prestation_code = 'GHS'	WHERE ACCCLE = 'GHS';

				UPDATE w_ACP01_keys	SET prestation_code = 'EXH'	WHERE ACCCLE = 'EXH';


				UPDATE w_ACP01_keys
				SET prestation_code = CASE WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END 
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE prestation_code = '' AND TRCENR = 'A51' AND TRSUJT = '' AND ACCSER = TRCSER AND ACRUPR = TRCRUB ;


				DROP TABLE IF EXISTS w_TRP01;
				CREATE TEMP TABLE w_TRP01 AS
				SELECT TRCRUB, 
					CASE WHEN MAX(TRPRST) <> '' THEN MAX(TRPRST) ELSE MAX(TRPRSA) END AS TRPRST
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01
				WHERE TRCENR = 'A51' AND TRSUJT = '' AND (TRPRST <> '' OR TRPRSA <> '')
				GROUP BY 1;

				UPDATE w_ACP01_keys
				SET prestation_code = TRPRST
				FROM w_TRP01
				WHERE prestation_code = '' AND ACRUPR = TRCRUB ;

				UPDATE w_ACP01_keys	SET prestation_code = 'NOEMIE'	WHERE prestation_code = '' AND ACRUPR = '998';

				UPDATE w_ACP01_keys	SET prestation_code = 'DIV'	WHERE prestation_code = '';

				ALTER TABLE w_ACP01_keys  ADD CONSTRAINT w_ACP01_keys_pkey PRIMARY KEY(key);

				INSERT INTO activite[PX].t_lieux(code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT ACCSER, ACACTI, ACETAG, ACETAG || '|' || ACCHLT
				FROM w_ACP01_keys 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = ACCSER AND
						code_original_2 = ACACTI AND
						code_original_3 = ACETAG AND
						code_original_4 = ACETAG || '|' || ACCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
								SELECT prestation_code, prestation_code, prestation_code, prestation_code, ''
								FROM w_ACP01_keys
								WHERE prestation_code NOT IN (SELECT code FROM activite.t_prestations)
								GROUP BY prestation_code
								ORDER BY prestation_code;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
								SELECT ACRUPR, ACRUPR, ACRUPR, ACRUPR
								FROM w_ACP01_keys
								WHERE ACRUPR NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
								GROUP BY ACRUPR
								ORDER BY ACRUPR;

				UPDATE w_ACP01_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE prestation_code = t_prestations.code;

				UPDATE w_ACP01_keys SET rubrique_facturation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE ACRUPR = t_rubriques_facturation.code_original;
				
				UPDATE w_ACP01_keys
					set ucd_id = t_ucd.oid
				FROM base.t_ucd
				WHERE ACCLPP <> '' AND t_ucd.code = ACCLPP;
				
				UPDATE w_ACP01_keys
					set lpp_id = t_lpp.oid
				FROM base.t_lpp
				WHERE ACCLPP <> '' AND t_lpp.code = ACCLPP;


				UPDATE w_ACP01_keys SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = ACCSER AND
					code_original_2 = ACACTI AND
					code_original_3 = ACETAG AND
					code_original_4 = ACETAG || '|' || ACCHLT;


				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_c AS 
				SELECT
						p_factures.oid AS facture_id,
						w_ADDOSSDCPL AS no_facture,
						ACDTA1_date AS date_debut,
						ACDTA9_date AS date_fin,
						ACNBRE AS nb_rubrique,
						ACCOE1 AS coefficient,
						w_ACP01_keys.rubrique_facturation_id AS rubrique_facturation_id,
						w_ACP01_keys.prestation_id AS prestation_id,
						ACPRUA AS prix_unitaire,
						w_ACP01_keys.lieu_id AS lieu_id,
						w_ACP01_keys.ucd_id,
						w_ACP01_keys.lpp_id
				FROM w_ACP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_ACP01_keys ON w_ACP01.key = w_ACP01_keys.key;
					
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c WHERE no_facture IN (SELECT no_facture FROM w_factures_lignes_non_facturees_c GROUP BY 1);
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c WHERE no_facture IN (SELECT no_facture FROM activite[PX].p_factures WHERE code_facture >= '1' GROUP BY 1);

				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,
					ucd_id,
					lpp_id
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					rubrique_facturation_id,
					prestation_id,
					prix_unitaire,
					lieu_id,
					ucd_id,
					lpp_id
				FROM w_factures_lignes_non_facturees_c;
				
				
				-- Suppression tables de travail
				
				DROP TABLE IF EXISTS w_TRP01;
				DROP TABLE IF EXISTS w_ACP01;
				DROP TABLE IF EXISTS w_ACP01_keys;
				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_c;
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Clinique">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_MFP01;
				CREATE TEMP TABLE w_MFP01 AS
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					substr(to_char(MFRUPR,'0000'),3,3) AS MFRUPR,
					substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS MFCPRC,
					MFCCLE,
					MFCGHS,
					MFCLPP,
					MFCGHS || '|' || MFCLPP || '|' || MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || substr(to_char(MFRUPR,'0000'),3,3) || '|' || substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
					JOIN w_ADP01_factures_modifiees ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
				;

				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					substr(to_char(MFRUPR,'0000'),3,3) AS MFRUPR,
					substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS MFCPRC,
					MFCCLE,
					MFCGHS,
					MFCLPP,
					MFCGHS || '|' || MFCLPP || '|' || MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || substr(to_char(MFRUPR,'0000'),3,3) || '|' || substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP
					JOIN w_ADP01_factures_modifiees ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'P')
				;


				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					substr(to_char(MFRUPR,'0000'),3,3) AS MFRUPR,
					substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS MFCPRC,
					MFCCLE,
					MFCGHS,
					MFCLPP,
					MFCGHS || '|' || MFCLPP || '|' || MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || substr(to_char(MFRUPR,'0000'),3,3) || '|' || substr(to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'0000'),3,3) AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH
					JOIN w_ADP01_factures_modifiees ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'H')
				;


				CREATE INDEX w_MFP01_i1 ON w_MFP01 USING btree (w_ADDOSSDCPL);

				CREATE INDEX w_MFP01_i2 ON w_MFP01 USING btree (key);

				DROP TABLE IF EXISTS w_MFP01_keys;
				CREATE TEMP TABLE w_MFP01_keys AS
				SELECT 
					key,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					MFCCLE, 
					MFRUPR,
					MFCPRC,
					MFCGHS,
					MFCLPP,
					0::bigint AS rubrique_facturation_id,
					0::bigint AS rubrique_comptabilisation_id,
					''::text AS prestation_code, 
					0::bigint AS prestation_id, 
					0::bigint AS lieu_id,
					0::bigint AS ghs_id,
					''::text AS compte_produit,
					0::bigint AS compte_produit_id,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id
				FROM w_MFP01
				GROUP BY 1,2,3,4,5,6,7,8,9,10;

				UPDATE w_MFP01_keys	SET prestation_code = 'GHS'	WHERE MFCCLE = 'GHS';

				UPDATE w_MFP01_keys	SET prestation_code = 'EXH'	WHERE MFCCLE = 'EXH';

				
				UPDATE w_MFP01_keys
					set ghs_id = t_ghs.oid
				FROM base.t_ghs
				WHERE MFCGHS <> '0000' AND to_char(t_ghs.code,'FM0000') = MFCGHS;
				
				UPDATE w_MFP01_keys
					set ucd_id = t_ucd.oid
				FROM base.t_ucd
				WHERE MFCLPP <> '' AND t_ucd.code = MFCLPP;
				
				UPDATE w_MFP01_keys
					set lpp_id = t_lpp.oid
				FROM base.t_lpp
				WHERE MFCLPP <> '' AND t_lpp.code = MFCLPP;

				UPDATE w_MFP01_keys
				SET prestation_code = CASE WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE prestation_code = '' AND TRCENR = 'A51' AND TRSUJT = '' AND MFCSER = TRCSER AND MFRUPR = TRCRUB ;
				
				
				UPDATE w_MFP01_keys
				SET compte_produit = TRCPTE
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE TRCENR = 'A51' AND TRSUJT = '' AND MFCSER = TRCSER AND MFRUPR = TRCRUB ;

				UPDATE w_MFP01_keys	SET prestation_code = 'NOEMIE'	WHERE prestation_code = '' AND MFRUPR = '998';


				UPDATE w_MFP01_keys	SET prestation_code = 'DIV'	WHERE prestation_code = '';

				ALTER TABLE w_MFP01_keys  ADD CONSTRAINT w_MFP01_keys_pkey PRIMARY KEY(key);

				INSERT INTO activite[PX].t_lieux(code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT MFCSER, MFACTI, MFETAG, MFETAG || '|' || MFCHLT
				FROM w_MFP01_keys 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = MFCSER AND
						code_original_2 = MFACTI AND
						code_original_3 = MFETAG AND
						code_original_4 = MFETAG || '|' || MFCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
								SELECT prestation_code, prestation_code, prestation_code, prestation_code, ''
								FROM w_MFP01_keys
								WHERE prestation_code NOT IN (SELECT code FROM activite.t_prestations)
								GROUP BY prestation_code
								ORDER BY prestation_code;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
								SELECT MFRUPR, MFRUPR, MFRUPR, MFRUPR
								FROM w_MFP01_keys
								WHERE MFRUPR NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
								GROUP BY MFRUPR
								ORDER BY MFRUPR;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
								SELECT MFCPRC, MFCPRC, MFCPRC, MFCPRC
								FROM w_MFP01_keys
								WHERE MFCPRC NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
								GROUP BY MFCPRC
								ORDER BY MFCPRC;

				UPDATE w_MFP01_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE prestation_code = t_prestations.code;

				UPDATE w_MFP01_keys SET rubrique_facturation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE MFRUPR = t_rubriques_facturation.code_original;

				UPDATE w_MFP01_keys SET rubrique_comptabilisation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE MFCPRC = t_rubriques_facturation.code_original;

				UPDATE w_MFP01_keys SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = MFCSER AND
					code_original_2 = MFACTI AND
					code_original_3 = MFETAG AND
					code_original_4 = MFETAG || '|' || MFCHLT;
					
					
					
				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 compte_produit, compte_produit, MAX(COALESCE(PEINT3,compte_produit)), MAX(COALESCE(PEINT3,compte_produit))
				FROM w_MFP01_keys
					LEFT JOIN prod_shs.[ACTIVITESCHEMA]_PEP01 ON compte_produit = PECPTE
				WHERE compte_produit NOT IN (SELECT code_original FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;
				
				
				UPDATE w_MFP01_keys SET compte_produit_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE compte_produit = t_compte.code_original;
					
				-- Remplacement des codes dialyse
                INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'TRANSGHSDXX',
					'Transformation des GHS en Dxx',
					'',
					'Transformation des prestations GHS en Dxx selong GHS, la rubrique de facturation prend la valeur du GHS'
				WHERE 'TRANSGHSDXX' NOT IN (SELECT code FROM activite.t_divers);
                ;
                
                INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
                SELECT t_ghs.code::text, t_ghs.code::text, t_ghs.texte, t_ghs.texte
                FROM base.t_ghs
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE t_ghs.code IN (9602,9603,9604,9605,9617) AND
                    t_ghs.code::text NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
                    ;
                    
                INSERT INTO activite[PX].t_rubriques_facturation (code_original, code, texte, texte_court)
                SELECT t_prestations.code::text, t_prestations.code::text, t_prestations.texte, t_prestations.texte
                FROM activite.t_prestations
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE (t_prestations.code LIKE 'D1%' OR t_prestations.code LIKE 'D2%') AND
                    t_prestations.code::text NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
                    ;
					
                UPDATE w_MFP01_keys	
                SET prestation_code = 'D09', rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFCCLE = 'GHS' AND MFCGHS = 9605 AND t_rubriques_facturation.code = '9605';
                
                UPDATE w_MFP01_keys	
                SET prestation_code = 'D10', rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation 
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFCCLE = 'GHS' AND MFCGHS = 9617 AND t_rubriques_facturation.code = '9617';
                
                UPDATE w_MFP01_keys	
                SET prestation_code = 'D17', rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation 
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFCCLE = 'GHS' AND MFCGHS = 9604 AND t_rubriques_facturation.code = '9604';
                
                UPDATE w_MFP01_keys	
                SET prestation_code = 'D18', rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFCCLE = 'GHS' AND MFCGHS = 9602 AND t_rubriques_facturation.code = '9602';
                
                UPDATE w_MFP01_keys	
                SET prestation_code = 'D19', rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation 
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFCCLE = 'GHS' AND MFCGHS = 9603 AND t_rubriques_facturation.code = '9603';
                
                UPDATE w_MFP01_keys	
                SET rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite[PX].t_rubriques_facturation
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE MFRUPR IN (188,189) AND prestation_code IN ('D11','D13','D14','D15','D16','D20','D22') AND 
                    t_rubriques_facturation.code_original = prestation_code AND
                    rubrique_facturation_id <> t_rubriques_facturation.oid;
                    
                    
                UPDATE activite[PX].p_factures_lignes_non_facturees_c
                SET rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite.t_prestations
                    JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = t_prestations.code
                    JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE prestation_id = t_prestations.oid AND
                    t_prestations.code IN ('D11','D13','D14','D15','D16','D20','D22') AND 
                    rubrique_facturation_id <> t_rubriques_facturation.oid
                ;
                   
                UPDATE w_MFP01_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE prestation_code = t_prestations.code AND
                    w_MFP01_keys.prestation_id IS DISTINCT FROM t_prestations.oid;


				DROP TABLE IF EXISTS w_factures_lignes_c;
				CREATE TEMP TABLE w_factures_lignes_c AS 
				SELECT
					p_factures.oid AS facture_id,
					w_MFP01.w_ADDOSSDCPL AS no_facture,
					
					MFCOE1 AS coefficient,
					MFCOET AS coefficient_mco,
					w_MFP01.MFCGHS,
					w_MFP01_keys.ghs_id,
					w_MFP01_keys.rubrique_facturation_id AS rubrique_facturation_id,
					w_MFP01_keys.rubrique_comptabilisation_id AS rubrique_comptabilisation_id,
					w_MFP01_keys.compte_produit_id AS compte_produit_id,
					w_MFP01_keys.prestation_id AS prestation_id,
					w_MFP01_keys.lieu_id AS lieu_id,
					1::bigint AS origine_facturation_id,
					w_MFP01_keys.ucd_id,
					w_MFP01_keys.lpp_id,

					date_trunc('month', MFDTA9_date) AS MFDTA9_month,
					MFPRUA AS prix_unitaire,
					MFTFAM AS taux_0,
					MFTFA1 AS taux_1,
					MFTFA2 AS taux_2,
					MFTFA3 AS taux_22,

					w_MFP01.MFDTA1_date AS date_debut,
					w_MFP01.MFDTA9_date AS date_fin,
					w_MFP01.MFNBRE AS nb_rubrique,
					CASE WHEN w_MFP01.MFCCLE = 'GHS' AND w_MFP01.MFRUPR = 111 THEN 0 ELSE w_MFP01.MFNBRE END AS nb_prestation,
					MFMFAM + MFMFA1 + MFMFA2 + MFMFA3 AS montant_facture,
					MFMFAM AS montant_facture_0,
					MFMFA1 AS montant_facture_1,
					MFMFA2 AS montant_facture_2,
					MFMFA3 AS montant_facture_22,
					MFMCAM + MFMCA1 + MFMCA2 + MFMCA3 AS montant_comptabilise,
					MFMCAM AS montant_comptabilise_0,
					MFMCA1 AS montant_comptabilise_1,
					MFMCA2 AS montant_comptabilise_2,
					MFMCA3 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,
					0::numeric AS montant_comptabilise_budget_global_1,
					0::numeric AS rubrique_facture_id
				FROM w_MFP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key;
					
					
				UPDATE w_factures_lignes_c
				SET nb_prestation = CASE WHEN nb_rubrique >=0 THEN 1 ELSE -1 END
				FROM 
					(SELECT no_facture, ghs_id, prestation_id, rubrique_facturation_id, MAX(date_debut) AS date_debut 
					FROM w_factures_lignes_c 
					WHERE prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code = 'GHS') AND
						rubrique_facturation_id IN (SELECT oid FROM activite[PX].t_rubriques_facturation WHERE code = '111')
					GROUP BY 1,2,3,4
					) subview
				WHERE w_factures_lignes_c.no_facture = subview.no_facture AND
					w_factures_lignes_c.ghs_id = subview.ghs_id AND
					w_factures_lignes_c.prestation_id = subview.prestation_id AND
					w_factures_lignes_c.rubrique_facturation_id = subview.rubrique_facturation_id AND
					w_factures_lignes_c.date_debut = subview.date_debut ;
					
				
				
				-- Supprimer les montants GHS qui chevauchent les EXH
					
				DROP TABLE IF EXISTS w_factures_exh;
				CREATE TEMP TABLE w_factures_exh AS
				SELECT no_facture, MIN(w_factures_lignes_c.date_debut) AS date_debut_exh
				FROM w_factures_lignes_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND t_prestations.code IN ('EXH')
				GROUP BY 1;


				DROP TABLE IF EXISTS w_factures_ghs;
				CREATE TEMP TABLE w_factures_ghs AS
				SELECT w_factures_lignes_c.no_facture, 
					MIN(date_debut_exh) AS date_debut_exh, 
					MAX(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN date_fin ELSE NULL END) AS date_fin_ghs,
					NULL::TID AS ctid_fin_ghs,
					SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END) AS nb_rubrique_ghs_ok,
					SUM(CASE WHEN w_factures_lignes_c.date_fin >= date_debut_exh THEN 1 ELSE 0 END) AS nb_rubrique_ghs_ko,
					SUM(prix_unitaire) AS prix_unitaire_total_ghs,
					round(base.cti_division(SUM(montant_facture), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END * CASE WHEN montant_facture < 0 THEN -1 ELSE 1 END)),2) AS prix_unitaire_ghs,
					0::numeric AS prix_unitaire_ghs_last,
					SUM(montant_facture) AS montant_facture_total_ghs,
					round(base.cti_division(SUM(montant_facture), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_facture_ghs,
					0::numeric AS montant_facture_ghs_last,
					SUM(montant_facture_0) AS montant_facture_0_total_ghs,
					round(base.cti_division(SUM(montant_facture_0), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_facture_0_ghs,
					0::numeric AS montant_facture_0_ghs_last,
					SUM(montant_facture_1) AS montant_facture_1_total_ghs,
					round(base.cti_division(SUM(montant_facture_1), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_facture_1_ghs,
					0::numeric AS montant_facture_1_ghs_last,
					SUM(montant_facture_2) AS montant_facture_2_total_ghs,
					round(base.cti_division(SUM(montant_facture_2), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_facture_2_ghs,
					0::numeric AS montant_facture_2_ghs_last,
					SUM(montant_facture_22) AS montant_facture_22_total_ghs,
					round(base.cti_division(SUM(montant_facture_22), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_facture_22_ghs,
					0::numeric AS montant_facture_22_ghs_last,
					SUM(montant_comptabilise) AS montant_comptabilise_total_ghs,
					round(base.cti_division(SUM(montant_comptabilise), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_comptabilise_ghs,
					0::numeric AS montant_comptabilise_ghs_last,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0_total_ghs,
					round(base.cti_division(SUM(montant_comptabilise_0), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_comptabilise_0_ghs,
					0::numeric AS montant_comptabilise_0_ghs_last,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1_total_ghs,
					round(base.cti_division(SUM(montant_comptabilise_1), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_comptabilise_1_ghs,
					0::numeric AS montant_comptabilise_1_ghs_last,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2_total_ghs,
					round(base.cti_division(SUM(montant_comptabilise_2), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_comptabilise_2_ghs,
					0::numeric AS montant_comptabilise_2_ghs_last,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22_total_ghs,
					round(base.cti_division(SUM(montant_comptabilise_22), SUM(CASE WHEN w_factures_lignes_c.date_fin < date_debut_exh THEN 1 ELSE 0 END )),2) AS montant_comptabilise_22_ghs,
					0::numeric AS montant_comptabilise_22_ghs_last
				FROM w_factures_lignes_c
				JOIN w_factures_exh ON w_factures_exh.no_facture = w_factures_lignes_c.no_facture
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid AND t_rubriques_facturation.code = '111'
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS')
				WHERE montant_encours = 0
				GROUP BY 1
				HAVING SUM(CASE WHEN w_factures_lignes_c.date_fin >= date_debut_exh THEN nb_rubrique ELSE 0 END) <> 0;


				UPDATE w_factures_ghs
				SET ctid_fin_ghs = w_factures_lignes_c.CTID
				FROM w_factures_lignes_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS')
				JOIN activite[PX].t_rubriques_facturation ON rubrique_facturation_id = t_rubriques_facturation.oid AND t_rubriques_facturation.code = '111'
				WHERE w_factures_lignes_c.no_facture = w_factures_ghs.no_facture AND w_factures_lignes_c.date_fin = w_factures_ghs.date_fin_ghs;




				UPDATE w_factures_ghs SET
					montant_facture_ghs_last = montant_facture_total_ghs + montant_facture_ghs - nb_rubrique_ghs_ok * montant_facture_ghs,
					montant_facture_0_ghs_last = montant_facture_0_total_ghs + montant_facture_0_ghs - nb_rubrique_ghs_ok * montant_facture_0_ghs,
					montant_facture_1_ghs_last = montant_facture_1_total_ghs + montant_facture_1_ghs - nb_rubrique_ghs_ok * montant_facture_1_ghs,
					montant_facture_2_ghs_last = montant_facture_2_total_ghs + montant_facture_2_ghs - nb_rubrique_ghs_ok * montant_facture_2_ghs,
					montant_facture_22_ghs_last = montant_facture_22_total_ghs + montant_facture_22_ghs - nb_rubrique_ghs_ok * montant_facture_22_ghs,
					montant_comptabilise_ghs_last = montant_comptabilise_total_ghs + montant_comptabilise_ghs - nb_rubrique_ghs_ok * montant_comptabilise_ghs,
					montant_comptabilise_0_ghs_last = montant_comptabilise_0_total_ghs + montant_comptabilise_0_ghs - nb_rubrique_ghs_ok * montant_comptabilise_0_ghs,
					montant_comptabilise_1_ghs_last = montant_comptabilise_1_total_ghs + montant_comptabilise_1_ghs - nb_rubrique_ghs_ok * montant_comptabilise_1_ghs,
					montant_comptabilise_2_ghs_last = montant_comptabilise_2_total_ghs + montant_comptabilise_2_ghs - nb_rubrique_ghs_ok * montant_comptabilise_2_ghs,
					montant_comptabilise_22_ghs_last = montant_comptabilise_22_total_ghs + montant_comptabilise_22_ghs - nb_rubrique_ghs_ok * montant_comptabilise_22_ghs;


				UPDATE w_factures_lignes_c SET
					nb_prestation = CASE WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN 1 ELSE 0 END,
					prix_unitaire = CASE WHEN date_fin > date_fin_ghs THEN 0 ELSE prix_unitaire_total_ghs END,
					montant_facture = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_facture_ghs_last ELSE montant_facture_ghs END,
					montant_facture_0 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_facture_0_ghs_last ELSE montant_facture_0_ghs END,
					montant_facture_1 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_facture_1_ghs_last ELSE montant_facture_1_ghs END,
					montant_facture_2 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_facture_2_ghs_last ELSE montant_facture_2_ghs END,
					montant_facture_22 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_facture_22_ghs_last ELSE montant_facture_22_ghs END,
					montant_comptabilise = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_comptabilise_ghs_last ELSE montant_comptabilise_ghs END,
					montant_comptabilise_0 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_comptabilise_0_ghs_last ELSE montant_comptabilise_0_ghs END,
					montant_comptabilise_1 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_comptabilise_1_ghs_last ELSE montant_comptabilise_1_ghs END,
					montant_comptabilise_2 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_comptabilise_2_ghs_last ELSE montant_comptabilise_2_ghs END,
					montant_comptabilise_22 = CASE WHEN date_fin > date_fin_ghs THEN 0 WHEN w_factures_lignes_c.CTID = ctid_fin_ghs THEN montant_comptabilise_22_ghs_last ELSE montant_comptabilise_22_ghs END
				FROM w_factures_ghs, activite.t_prestations, activite[PX].t_rubriques_facturation
				WHERE w_factures_ghs.no_facture = w_factures_lignes_c.no_facture AND
					prestation_id = t_prestations.oid AND t_prestations.code IN ('GHS') AND
					rubrique_facturation_id = t_rubriques_facturation.oid AND t_rubriques_facturation.code = '111';

				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_c');	 
					 
				-- Valider les lignes
				
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_8');
				
				DELETE FROM activite[PX].p_factures_lignes_c WHERE no_facture IN (SELECT w_ADDOSSDCPL FROM w_ADP01_factures_modifiees);

				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,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					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,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					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
				FROM w_factures_lignes_c;
				
				
				
				
				-- Mise à jour factures et séjour (GHS selon facturation)
				DROP TABLE IF EXISTS w_MFP01_ghs;
				CREATE TEMP TABLE w_MFP01_ghs AS
				SELECT
						p_factures.oid AS facture_id,
						w_MFP01.w_ADDOSSDCPL AS no_facture,
						MAX(CASE WHEN w_MFP01.MFCGHS < '5800' OR w_MFP01.MFCGHS > '5836' THEN w_MFP01_keys.ghs_id ELSE 0 END) AS ghs_id
				FROM w_MFP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture AND p_factures.ghs_id = 0
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key
				WHERE w_MFP01.MFCCLE = 'GHS' 
				GROUP BY 1,2;
				
				CREATE INDEX w_MFP01_ghs_i1 ON w_MFP01_ghs USING btree (no_facture);
				
				UPDATE activite[PX].p_factures
				SET ghs_id = w_MFP01_ghs.ghs_id
				FROM w_MFP01_ghs
				WHERE p_factures.ghs_id = 0 AND
					w_MFP01_ghs.no_facture = p_factures.no_facture AND
					w_MFP01_ghs.ghs_id <> 0;
				
				UPDATE activite[PX].p_sejours
				SET ghs_id = p_factures.ghs_id
				FROM activite[PX].p_factures 
				WHERE p_sejours.ghs_id = 0 AND
					p_factures.no_sejour = p_sejours.no_sejour AND 
					p_factures.type_facture = '0' AND 
					p_factures.ghs_id <> 0;
					
					
					
					
					
				-- Eclatement des supplements par jour
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_2');
				
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;

				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					CTID AS from_CTID, *
				FROM activite[PX].p_factures_lignes_c
				WHERE prestation_id IN (SELECT oid FROM activite.t_prestations 
									WHERE code IN ('PJ', 'FJ', 'PHJ', 'SSM', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
										t_prestations.type_ventilation_jour = '1'
										)						 
				AND (nb_prestation > 1 or nb_prestation < -1);


				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 nb_rubrique < 0 THEN -1 ELSE 1 END AS nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					round(montant_facture / ABS(nb_prestation),2) AS montant_facture,
					round(montant_facture_0 / ABS(nb_prestation),2) AS montant_facture_0,
					round(montant_facture_1 / ABS(nb_prestation),2) AS montant_facture_1,
					round(montant_facture_2 / ABS(nb_prestation),2) AS montant_facture_2,
					round(montant_facture_22 / ABS(nb_prestation),2) AS montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation,
					round(montant_comptabilise / ABS(nb_prestation),2) AS montant_comptabilise,
					round(montant_comptabilise_0 / ABS(nb_prestation),2) AS montant_comptabilise_0,
					round(montant_comptabilise_1 / ABS(nb_prestation),2) AS montant_comptabilise_1,
					round(montant_comptabilise_2 / ABS(nb_prestation),2) AS montant_comptabilise_2,
					round(montant_comptabilise_22 / ABS(nb_prestation),2) AS montant_comptabilise_22,
					round(montant_encours / ABS(nb_prestation),2) AS montant_encours,
					round(montant_encours_0 / ABS(nb_prestation),2) AS montant_encours_0,
					round(montant_encours_1 / ABS(nb_prestation),2) AS montant_encours_1,
					round(montant_encours_2 / ABS(nb_prestation),2) AS montant_encours_2,
					round(montant_encours_22 / ABS(nb_prestation),2) AS montant_encours_22,
					round(montant_facture_actes_inclus_dans_sejour / ABS(nb_prestation),2) AS montant_facture_actes_inclus_dans_sejour,
					round(montant_facture_0_actes_inclus_dans_sejour / ABS(nb_prestation),2) AS montant_facture_0_actes_inclus_dans_sejour,
					round(montant_facture_1_actes_inclus_dans_sejour / ABS(nb_prestation),2) AS montant_facture_1_actes_inclus_dans_sejour,
					round(montant_facture_2_actes_inclus_dans_sejour / ABS(nb_prestation),2) AS montant_facture_2_actes_inclus_dans_sejour,
					round(montant_facture_22_actes_inclus_dans_sejour / ABS(nb_prestation),2) AS montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					round(montant_comptabilise_budget_global_1 / ABS(nb_prestation),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_prestation)::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(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 = CASE WHEN p_factures_lignes_c.nb_rubrique < 0 THEN -1 ELSE 1 END ,
					nb_prestation = CASE WHEN p_factures_lignes_c.nb_prestation < 0 THEN -1 ELSE 1 END ,
					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,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id)
				SELECT 
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					compte_produit_id,
					prestation_id,
					ucd_id,
					lpp_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					finess,
					prix_unitaire,
					lieu_id,
					nb_prestation,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour,
					origine_facturation_id,
					montant_comptabilise_budget_global_1,
					facture_id
				FROM w_factures_lignes_sup_c_sup;
				
				
				-- Lieu exécution
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_c_4');
				
				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;

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


				-- Pour les chambres particulières, regroupement des lignes si même rubrique
				DROP TABLE IF EXISTS w_fact_cp;
				CREATE TEMP TABLE w_fact_cp AS
				SELECT
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(prix_unitaire) AS prix_unitaire,
					SUM(montant_facture) AS montant_facture,
					SUM(montant_comptabilise) AS montant_comptabilise,
					MAX(taux_1) AS taux_1,
					SUM(montant_facture_1) AS montant_facture_1,
					SUM(montant_comptabilise_1) AS montant_comptabilise_1,
					MAX(taux_2) AS taux_2,
					SUM(montant_facture_2) AS montant_facture_2,
					SUM(montant_comptabilise_2) AS montant_comptabilise_2,
					MAX(taux_22) AS taux_22,
					SUM(montant_facture_22) AS montant_facture_22,
					SUM(montant_comptabilise_22) AS montant_comptabilise_22,
					MAX(taux_0) AS taux_0,
					SUM(montant_facture_0) AS montant_facture_0,
					SUM(montant_comptabilise_0) AS montant_comptabilise_0,
					count(*) AS nb,
					MIN(CTID) AS keep_CTID
				FROM activite[PX].p_factures_lignes_c
				WHERE montant_facture <> 0 AND
					date_debut = date_fin AND
					rubrique_facturation_id IN 
					(SELECT to_id 
					FROM activite[PX].t_listes
					JOIN activite[PX].t_listes_contenu ON liste_id = t_listes.oid
					WHERE t_listes.code = 'CTI_SHO_R') 
				GROUP BY 1,2,3,4,5,6,7,8
				HAVING count(*) > 1
				ORDER BY 1,2,3,4,5,6,7,8;

				UPDATE w_fact_cp SET
					taux_1 = round(base.cti_division(montant_facture_1 * 100.00 , montant_facture),0),
					taux_2 = round(base.cti_division(montant_facture_2 * 100.00 , montant_facture),0),
					taux_22 = round(base.cti_division(montant_facture_22 * 100.00 , montant_facture),0);

				UPDATE w_fact_cp SET
					taux_0 = 100 - taux_1 - taux_2 - taux_22;
				
				
				UPDATE activite[PX].p_factures_lignes_c SET
					rubrique_facturation_id = CASE WHEN p_factures_lignes_c.CTID = keep_CTID THEN p_factures_lignes_c.rubrique_facturation_id ELSE -123456789 END,
					prix_unitaire = w_fact_cp.prix_unitaire,
					montant_facture = w_fact_cp.montant_facture,
					montant_comptabilise = w_fact_cp.montant_comptabilise,
					taux_1 = w_fact_cp.taux_1,
					montant_facture_1 = w_fact_cp.montant_facture_1,
					montant_comptabilise_1 = w_fact_cp.montant_comptabilise_1,
					taux_2 = w_fact_cp.taux_2,
					montant_facture_2 = w_fact_cp.montant_facture_2,
					montant_comptabilise_2 = w_fact_cp.montant_comptabilise_2,
					taux_0 = w_fact_cp.taux_0,
					montant_facture_0 = w_fact_cp.montant_facture_0,
					montant_comptabilise_0 = w_fact_cp.montant_comptabilise_0
				FROM w_fact_cp
				WHERE p_factures_lignes_c.no_facture = w_fact_cp.no_facture AND
					p_factures_lignes_c.date_debut = w_fact_cp.date_debut AND
					p_factures_lignes_c.date_fin = w_fact_cp.date_fin AND
					p_factures_lignes_c.nb_rubrique = w_fact_cp.nb_rubrique AND
					p_factures_lignes_c.nb_prestation = w_fact_cp.nb_prestation AND
					p_factures_lignes_c.rubrique_facturation_id = w_fact_cp.rubrique_facturation_id AND
					p_factures_lignes_c.rubrique_comptabilisation_id = w_fact_cp.rubrique_comptabilisation_id AND
					p_factures_lignes_c.prestation_id = w_fact_cp.prestation_id;

				DELETE FROM activite[PX].p_factures_lignes_c WHERE rubrique_facturation_id = -123456789;
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Compte client Clinique">
			<sqlcmd><![CDATA[

				-- Associations prestations par dossier et rubrique
				DROP TABLE IF EXISTS w_MFP01_rubriques;
				CREATE TEMP TABLE w_MFP01_rubriques AS 
				SELECT
					w_ADDOSSDCPL,
					w_MFP01.MFCPRC,
					MAX(prestation_code) AS MFCCLE
				FROM w_MFP01
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key
				GROUP BY 1,2;

				CREATE INDEX w_MFP01_rubriques_i1 ON w_MFP01_rubriques USING btree (w_ADDOSSDCPL);

				-- Montants réglés par mois
				
				DROP TABLE IF EXISTS w_FDP03;
				CREATE TEMP TABLE w_FDP03 AS
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char((FDAMRG * 100) + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					w_ADCSER,
					substr(to_char(FDRUPR,'0000'),3,3) AS FDRUPR,
					COALESCE(MFCCLE,'') AS MFCCLE,
					w_ADCSER || '|' || COALESCE(MFCCLE,'') || '|' || substr(to_char(FDRUPR,'0000'),3,3)  AS key,
					FDMPRM + FDMPOD AS FDMTRG,
					CASE WHEN FDTYPC = '0' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDTYPC = '1' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDTYPC = '2' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDTYPC = '3' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]_FDP03
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = '')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDRUPR,'0000'),3,3) = MFCPRC)
				WHERE FDCCLH = '1';

				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char((FDAMRG * 100) + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					w_ADCSER,
					substr(to_char(FDRUPR,'0000'),3,3) AS FDRUPR,
					COALESCE(MFCCLE,'') AS MFCCLE,
					w_ADCSER || '|' || COALESCE(MFCCLE,'') || '|' || substr(to_char(FDRUPR,'0000'),3,3)  AS key,
					FDMPRM + FDMPOD AS FDMTRG,
					CASE WHEN FDTYPC = '0' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDTYPC = '1' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDTYPC = '2' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDTYPC = '3' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]p_FDP03P
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = 'P')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDRUPR,'0000'),3,3) = MFCPRC)
				WHERE FDCCLH = '1';

				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char((FDAMRG * 100) + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					w_ADCSER,
					substr(to_char(FDRUPR,'0000'),3,3) AS FDRUPR,
					COALESCE(MFCCLE,'') AS MFCCLE,
					w_ADCSER || '|' || COALESCE(MFCCLE,'') || '|' || substr(to_char(FDRUPR,'0000'),3,3)  AS key,
					FDMPRM + FDMPOD AS FDMTRG,
					CASE WHEN FDTYPC = '0' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDTYPC = '1' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDTYPC = '2' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDTYPC = '3' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]h_FDP03H
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = 'H')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDRUPR,'0000'),3,3) = MFCPRC)
				WHERE FDCCLH = '1';
				
				-- Ajout des règlements / factures historique remises dans le circuit
				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char((FDP03.FDAMRG * 100) + 01,'FM00000000'),'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					w_ADCSER,
					substr(to_char(FDP03.FDRUPR,'0000'),3,3) AS FDRUPR,
					COALESCE(MFCCLE,'') AS MFCCLE,
					w_ADCSER || '|' || COALESCE(MFCCLE,'') || '|' || substr(to_char(FDP03.FDRUPR,'0000'),3,3)  AS key,
					FDP03.FDMPRM + FDP03.FDMPOD AS FDMTRG,
					CASE WHEN FDP03.FDTYPC = '0' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDP03.FDTYPC = '1' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDP03.FDTYPC = '2' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDP03.FDTYPC = '3' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]_FDP03 FDP03
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDP03.FDDOSS = w_ADDOSS AND FDP03.FDDCPL = w_ADDCPL AND w_CODENV = 'H')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDP03.FDRUPR,'0000'),3,3) = MFCPRC)
					LEFT JOIN prod_shs.[ACTIVITESCHEMA]H_FDP03H FDP03H ON
						FDP03.FDDOSS = FDP03H.FDDOSS AND
						FDP03.FDDCPL = FDP03H.FDDCPL AND
						FDP03.FDTYPC = FDP03H.FDTYPC AND
						FDP03.FDCCLH = FDP03H.FDCCLH AND
						FDP03.FDAMRG = FDP03H.FDAMRG
				WHERE FDP03.FDCCLH = '1' AND
					FDP03H.FDDOSS IS NULL
				;

				-- Clés pour calcul des oid
				
				DROP TABLE IF EXISTS w_FDP03_keys;
				CREATE TEMP TABLE w_FDP03_keys AS
				SELECT 
					key,
					w_ADCSER,
					MFCCLE, 
					FDRUPR,
					0::bigint AS rubrique_comptabilisee_id,
					0::bigint AS prestation_id
				FROM w_FDP03
				GROUP BY 1,2,3,4;

				UPDATE w_FDP03_keys
				SET MFCCLE = CASE WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END 
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE MFCCLE = '' AND TRCENR = 'A51' AND TRSUJT = '' AND w_ADCSER = TRCSER AND FDRUPR = TRCRUB ;

				UPDATE w_FDP03_keys	SET MFCCLE = 'NOEMIE'	WHERE MFCCLE = '' AND FDRUPR = '998';

				UPDATE w_FDP03_keys	SET MFCCLE = 'DIV'	WHERE MFCCLE = '' ;

				ALTER TABLE w_FDP03_keys  ADD CONSTRAINT w_FDP03_keys_pkey PRIMARY KEY(key);

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
								SELECT MFCCLE, MFCCLE, MFCCLE, MFCCLE, ''
								FROM w_FDP03_keys
								WHERE MFCCLE NOT IN (SELECT code FROM activite.t_prestations)
								GROUP BY MFCCLE
								ORDER BY MFCCLE;

				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
								SELECT FDRUPR, FDRUPR, FDRUPR, FDRUPR
								FROM w_FDP03_keys
								WHERE FDRUPR NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
								GROUP BY FDRUPR
								ORDER BY FDRUPR;

				UPDATE w_FDP03_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE MFCCLE = t_prestations.code;

				UPDATE w_FDP03_keys SET rubrique_comptabilisee_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE FDRUPR = t_rubriques_facturation.code_original;

				

				-- Montants ventes
				DROP TABLE IF EXISTS w_factures_soldes_c;
				CREATE TEMP TABLE w_factures_soldes_c AS 
				SELECT
					p_factures.oid AS facture_id,
					w_ADDOSSDCPL AS no_facture,
					date_vente AS date_comptable,
					w_MFP01_keys.rubrique_comptabilisation_id AS rubrique_comptabilisee_id,
					w_MFP01_keys.prestation_id AS prestation_id,
					SUM(MFMCAM + MFMCA1 + MFMCA2 + MFMCA3) AS montant_comptabilise,
					SUM(MFMCAM) AS montant_comptabilise_0,
					SUM(MFMCA1) AS montant_comptabilise_1,
					SUM(MFMCA2) AS montant_comptabilise_2,
					SUM(MFMCA3) AS montant_comptabilise_22,
					0::numeric AS montant_regle,
					0::numeric AS montant_regle_0,
					0::numeric AS montant_regle_1,
					0::numeric AS montant_regle_2,
					0::numeric AS montant_regle_22,
					'0'::text AS od_avoir
				FROM w_MFP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key
				GROUP BY 1,2,3,4,5
				;

				-- Montants réglés
				INSERT INTO w_factures_soldes_c
				SELECT
					p_factures.oid AS facture_id,
					w_ADDOSSDCPL AS no_facture,
					w_FDDTRG_date AS date_comptable,
					w_FDP03_keys.rubrique_comptabilisee_id AS rubrique_comptabilisee_id,
					w_FDP03_keys.prestation_id 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(FDMTRG) AS montant_regle,
					SUM(FDMTRG_0) AS montant_montant_regle_0,
					SUM(FDMTRG_1) AS montant_montant_regle_1,
					SUM(FDMTRG_2) AS montant_montant_regle_2,
					SUM(FDMTRG_22) AS montant_montant_regle_22,
					'0'::text AS od_avoir
				FROM w_FDP03
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_FDP03_keys ON w_FDP03.key = w_FDP03_keys.key
				GROUP BY 1,2,3,4,5;


				-- Alimentation tables
				
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_8');
				
				DELETE FROM activite[PX].p_factures_soldes_c WHERE no_facture IN (SELECT w_ADDOSSDCPL FROM w_ADP01_factures_modifiees);

				INSERT INTO activite[PX].p_factures_soldes_c (
					facture_id,
					no_facture,
					date_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					od_avoir,
					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_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					od_avoir,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					SUM(montant_regle),
					SUM(montant_regle_0),
					SUM(montant_regle_1),
					SUM(montant_regle_2),
					SUM(montant_regle_22)
				FROM w_factures_soldes_c
				GROUP BY 1,2,3,4,5,6;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_c_8');

				-- Suppression tables de travail
				
				DROP TABLE IF EXISTS w_MFP01;		
				DROP TABLE IF EXISTS w_FDP03;
				DROP TABLE IF EXISTS w_factures_lignes_c;	
				DROP TABLE IF EXISTS w_factures_soldes_c;					
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Lignes non facturées Honoraires">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_TRP01;
				CREATE TEMP TABLE w_TRP01 AS 
				SELECT                                     
					0::bigint AS TRSEQU,
					TRSUJT, 
					TRDTTR AS TRDTT1,
					20991231::numeric AS TRDTT9, 
					TRPRUE   
				FROM prod_shs.[ACTIVITESCHEMA]_TRP02                       
				WHERE TRCENR = 'A59' AND TRSUJT <> ''       
				ORDER BY TRSUJT, TRDTTR;

				DROP SEQUENCE IF EXISTS w_TRP01_seq;
				CREATE TEMP SEQUENCE w_TRP01_seq
					INCREMENT 1
					MINVALUE 1
					MAXVALUE 9223372036854775807
					START 1
					CACHE 1;

				UPDATE w_TRP01 SET TRSEQU = nextval('w_TRP01_seq'::regclass);


				UPDATE w_TRP01
				SET TRDTT9 = w_TRP01_next.TRDTT1 -1
				FROM w_TRP01 w_TRP01_next
				WHERE w_TRP01.TRSUJT = w_TRP01_next.TRSUJT AND
					w_TRP01.TRSEQU = w_TRP01_next.TRSEQU - 1;


				DROP TABLE IF EXISTS w_ACP01;
				CREATE TEMP TABLE w_ACP01 AS
				SELECT 
					w_ADDOSSDCPL,
					
					ACDTA1,
					COALESCE(to_date(to_char(ACDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS ACDTA1_date,
					ACHRA1,
					COALESCE(to_date(to_char(CASE WHEN ACDTA9 >= ACDTA1 THEN ACDTA9 ELSE ACDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS ACDTA9_date,
					w_ADCSER AS ACCSER,
					w_ADACTI AS ACACTI,
					w_ADETAG AS ACETAG,
					w_ADCHLT AS ACCHLT,
					to_char(ACRUPR,'FM0000') AS ACRUPR,
					ACCCLE,
					CASE WHEN ACCCAM <> '' THEN ACCCAM ELSE ACCCLE END AS ACCCAM,
					ACCCAC,
					ACCCXD,
					ACCCPT,
					ACCCM1,
					ACCCM2,
					ACCCM3,
					ACCCM4,
					w_ADCSER || '|' || w_ADACTI || '|' || w_ADETAG || '|' || w_ADCHLT || '|' || ACCCLE || '|' || ACCCAM || '|' || to_char(ACRUPR,'FM0000')  AS key,
					CASE WHEN w_ADADAV IN ('2', '4', '6') AND ACNBRE > 0 THEN 0 - ACNBRE ELSE ACNBRE END AS ACNBRE,
					CASE WHEN ACCOE1 <> 0 THEN ACCOE1 ELSE 1 END AS ACCOE1,
					ACPRUA,
					ACMTDP
				FROM prod_shs.[ACTIVITESCHEMA]_ACP01
					JOIN w_ADP01 ON (ACDOSS = w_ADDOSS AND ACDCPL = w_ADDCPL AND W_ADCFAC <> '1' AND w_CODENV = '')
				WHERE ACCCLH = '2' AND ACCANN = '1';

				

				UPDATE w_ACP01 SET ACPRUA = TRPRUE
				FROM w_TRP01
				WHERE ACCCLE = TRSUJT AND ACPRUA = 0 AND ACDTA1 BETWEEN TRDTT1 AND TRDTT9;




				DROP TABLE IF EXISTS w_ACP01_keys;
				CREATE TEMP TABLE w_ACP01_keys AS
				SELECT 
					key,
					ACCSER,
					ACACTI,
					ACETAG,
					ACCHLT,
					ACCCLE, 
					ACRUPR,
					ACCCAM,	
					0::bigint AS medecin_facture_id,
					''::text AS prestation_code, 
					0::bigint AS prestation_id, 
					0::bigint AS acte_id,
					0::bigint AS lieu_id 
				FROM w_ACP01
				GROUP BY 1,2,3,4,5,6,7,8;

				

				UPDATE w_ACP01_keys
				SET prestation_code = CASE WHEN TRPRST <> '' THEN TRPRST WHEN TRPRSA <> '' THEN TRPRSA ELSE ACCCLE END 
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE prestation_code = '' AND TRCENR = 'A59' AND TRSUJT = ACCCLE ;

				UPDATE w_ACP01_keys SET prestation_code = 'DIV' WHERE prestation_code = '';

				ALTER TABLE w_ACP01_keys  ADD CONSTRAINT w_ACP01_keys_pkey PRIMARY KEY(key);

				INSERT INTO activite[PX].t_lieux(code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT ACCSER, ACACTI, ACETAG, ACETAG || '|' || ACCHLT
				FROM w_ACP01_keys 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = ACCSER AND
						code_original_2 = ACACTI AND
						code_original_3 = ACETAG AND
						code_original_4 = ACETAG || '|' || ACCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;



				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
								SELECT prestation_code, prestation_code, prestation_code, prestation_code, ''
								FROM w_ACP01_keys
								WHERE prestation_code NOT IN (SELECT code FROM activite.t_prestations)
								GROUP BY prestation_code
								ORDER BY prestation_code;

				DROP TABLE IF EXISTS w_new_actes;
				CREATE TEMP TABLE w_new_actes AS 
				SELECT 
					substring(ACCCAM, 1, 7) as acte_code, 
					substring(ACCCAM, 1, 7) as acte_texte, 
					substring(ACCCAM, 1, 7) as acte_texte_court, 
					CASE WHEN length(ACCCAM) >= 7 THEN 'CCAM' ELSE 'NGAP' END as nomenclature, 
					t_ccam_regroupements.oid as ccam_1_id, 
					t_ccam_regroupements.oid as ccam_4_id
				FROM w_ACP01_keys
					LEFT JOIN base.t_actes ON t_actes.code = substring(ACCCAM, 1, 7), 
					base.t_ccam_regroupements
				WHERE 1=1
					AND t_ccam_regroupements.code = 'NGAP'
					AND t_actes.code IS NULL;
				
				INSERT INTO base.t_actes(code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4)
								SELECT acte_code, acte_texte, acte_texte_court, nomenclature, ccam_1_id, ccam_4_id FROM w_new_actes
								GROUP BY acte_code, acte_texte, acte_texte_court, nomenclature, ccam_1_id, ccam_4_id;

				UPDATE w_ACP01_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE prestation_code = t_prestations.code;


				UPDATE w_ACP01_keys SET medecin_facture_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE ACRUPR = t_medecins_administratifs.code_original;

				UPDATE w_ACP01_keys SET acte_id = t_actes.oid
				FROM base.t_actes
				WHERE substring(ACCCAM, 1, 7) = t_actes.code;

				UPDATE w_ACP01_keys SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = ACCSER AND
					code_original_2 = ACACTI AND
					code_original_3 = ACETAG AND
					code_original_4 = ACETAG || '|' || ACCHLT;


				DROP TABLE IF EXISTS w_factures_lignes_non_facturees_h;
				CREATE TEMP TABLE w_factures_lignes_non_facturees_h AS 
				SELECT
						p_factures.oid AS facture_id,
						w_ADDOSSDCPL AS no_facture,
						ACDTA1_date AS date_debut,
						ACHRA1 * 10000 AS heure_debut,
						ACDTA9_date AS date_fin,
						ACNBRE AS nb_rubrique,
						ACCOE1 AS coefficient,
						w_ACP01_keys.medecin_facture_id AS medecin_facture_id,
						w_ACP01_keys.prestation_id AS prestation_id,
						ACPRUA AS prix_unitaire,
						ACMTDP AS montant_depassement,
						w_ACP01_keys.lieu_id AS lieu_id,
						w_ACP01_keys.acte_id AS acte_id,	
						ACCCAC AS activite_ccam,
						ACCCXD AS extension_ccam,
						ACCCPT AS phase_ccam,
						ACCCM1 AS modificateur_ccam_1,
						ACCCM2 AS modificateur_ccam_2,
						ACCCM3 AS modificateur_ccam_3,
						ACCCM4 AS modificateur_ccam_4
				FROM w_ACP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_ACP01_keys ON w_ACP01.key = w_ACP01_keys.key
					
				;
				
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_h WHERE no_facture IN (SELECT no_facture FROM w_factures_lignes_non_facturees_h GROUP BY 1);
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_h WHERE no_facture IN (SELECT no_facture FROM activite[PX].p_factures WHERE code_facture >= '1' GROUP BY 1);


				INSERT INTO activite[PX].p_factures_lignes_non_facturees_h (
					facture_id,
					no_facture,
					date_debut,
					heure_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					medecin_facture_id,
					prestation_id,
					prix_unitaire,
					montant_depassement,
					lieu_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4
				
				)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					heure_debut,
					date_fin,
					nb_rubrique,
					coefficient,
					medecin_facture_id,
					prestation_id,
					prix_unitaire,
					montant_depassement,
					lieu_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4
				FROM w_factures_lignes_non_facturees_h;
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Lignes factures Honoraires">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_MFP01;
				CREATE TEMP TABLE w_MFP01 AS
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					CASE WHEN MFCCAM <> '' THEN SUBSTR(MFCCAM,1,7) ELSE MFCCLE END AS MFCCAM,
					MFCCAC,
					MFCCXD,
					MFCCPT,
					MFCCM1,
					MFCCM2,
					MFCCM3,
					MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || SUBSTR(MFCCAM,1,7) || '|' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CCAM
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
				;
				
				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					MFCCLE AS MFCCAM,
					''::text AS MFCCAC,
					''::text AS MFCCXD,
					''::text AS MFCCPT,
					''::text AS MFCCM1,
					''::text AS MFCCM2,
					''::text AS MFCCM3,
					''::text AS MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '||' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01HON
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = '')
				;

				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					MFCCLE AS MFCCAM,
					''::text AS MFCCAC,
					''::text AS MFCCXD,
					''::text AS MFCCPT,
					''::text AS MFCCM1,
					''::text AS MFCCM2,
					''::text AS MFCCM3,
					''::text AS MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '||' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01HONP
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'P')
				;
				
				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					CASE WHEN MFCCAM <> '' THEN SUBSTR(MFCCAM,1,7) ELSE MFCCLE END AS MFCCAM,
					MFCCAC,
					MFCCXD,
					MFCCPT,
					MFCCM1,
					MFCCM2,
					MFCCM3,
					MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || SUBSTR(MFCCAM,1,7) || '|' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CCAMP
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'P')
				;

				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					MFCCLE AS MFCCAM,
					''::text AS MFCCAC,
					''::text AS MFCCXD,
					''::text AS MFCCPT,
					''::text AS MFCCM1,
					''::text AS MFCCM2,
					''::text AS MFCCM3,
					''::text AS MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '||' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01HONH
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'H')
				;
				
				INSERT INTO w_MFP01
				SELECT 
					w_ADDOSSDCPL,
					
					COALESCE(to_date(to_char(MFDTA1,'FM00000000'),'YYYYMMDD'), w_ADDTE1_date) AS MFDTA1_date,
					MFHRA1,
					COALESCE(to_date(to_char(CASE WHEN MFDTA9 >= MFDTA1 THEN MFDTA9 ELSE MFDTA1 END,'FM00000000'),'YYYYMMDD'), w_ADDTS1_date) AS MFDTA9_date,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					to_char(MFRUPR,'FM0000') AS MFRUPR,
					to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS MFCPRC,
					MFCCLE,
					CASE WHEN MFCCAM <> '' THEN SUBSTR(MFCCAM,1,7) ELSE MFCCLE END AS MFCCAM,
					MFCCAC,
					MFCCXD,
					MFCCPT,
					MFCCM1,
					MFCCM2,
					MFCCM3,
					MFCCM4,
					MFCSER || '|' || MFACTI || '|' || MFETAG || '|' || MFCHLT || '|' || MFCCLE || '|' || SUBSTR(MFCCAM,1,7) || '|' || to_char(MFRUPR,'FM0000') || '|' || to_char(CASE WHEN MFCPRC <> 0 THEN MFCPRC ELSE MFRUPR END,'FM0000') AS key,
					CASE WHEN MFMFA1 + MFMFA2 + MFMFA3 + MFMFAM < 0 AND MFNBRE > 0 THEN 0 - MFNBRE ELSE MFNBRE END AS MFNBRE,
					CASE WHEN MFCOE1 <> 0 THEN MFCOE1 ELSE 1 END AS MFCOE1,
					CASE WHEN MFCOET <> 0 THEN MFCOET ELSE 1 END AS MFCOET,
					ABS(MFPRUA) AS MFPRUA,
					MFTFAM,
					MFTFA1,
					MFTFA2,
					MFTFA3,
					MFMFAM,
					MFMFA1,
					MFMFA2,
					MFMFA3,
					MFMTDP,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCAM ELSE MFMFAM END AS MFMCAM,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA1 ELSE MFMFA1 END AS MFMCA1,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA2 ELSE MFMFA2 END AS MFMCA2,
					CASE WHEN w_ADPAD5 = '1' THEN MFMCA3 ELSE MFMFA3 END AS MFMCA3
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CCAMH
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (MFDOSS = w_ADDOSS AND MFDCPL = w_ADDCPL AND W_ADCFAC = '1' AND w_CODENV = 'H')
				;

				CREATE INDEX w_MFP01_i1 ON w_MFP01 USING btree (w_ADDOSSDCPL);

				CREATE INDEX w_MFP01_i2 ON w_MFP01 USING btree (key);

				DROP TABLE IF EXISTS w_MFP01_keys;
				CREATE TEMP TABLE w_MFP01_keys AS
				SELECT 
					key,
					MFCSER,
					MFACTI,
					MFETAG,
					MFCHLT,
					MFCCLE, 
					MFRUPR,
					MFCPRC,
					MFCCAM,	
					0::bigint AS medecin_facture_id,
					0::bigint AS medecin_comptabilise_id,
					''::text AS prestation_code, 
					0::bigint AS prestation_id, 
					0::bigint AS acte_id,
					0::bigint AS lieu_id 
				FROM w_MFP01
				GROUP BY 1,2,3,4,5,6,7,8,9;



				UPDATE w_MFP01_keys
				SET prestation_code = CASE WHEN TRPRST <> '' THEN TRPRST WHEN TRPRSA <> '' THEN TRPRSA ELSE MFCCLE END 
				FROM prod_shs.[ACTIVITESCHEMA]_TRP01 
				WHERE prestation_code = '' AND TRCENR = 'A59' AND TRSUJT = MFCCLE ;

				UPDATE w_MFP01_keys SET prestation_code = 'DIV' WHERE prestation_code = '';

				ALTER TABLE w_MFP01_keys  ADD CONSTRAINT w_MFP01_keys_pkey PRIMARY KEY(key);

				INSERT INTO activite[PX].t_lieux(code_original_1, code_original_2, code_original_3, code_original_4)
				SELECT MFCSER, MFACTI, MFETAG, MFETAG || '|' || MFCHLT
				FROM w_MFP01_keys 
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = MFCSER AND
						code_original_2 = MFACTI AND
						code_original_3 = MFETAG AND
						code_original_4 = MFETAG || '|' || MFCHLT
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4;



				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
				SELECT prestation_code, prestation_code, prestation_code, prestation_code, ''
				FROM w_MFP01_keys
				WHERE prestation_code NOT IN (SELECT code FROM activite.t_prestations)
				GROUP BY prestation_code
				ORDER BY prestation_code;

				DROP TABLE IF EXISTS w_actes;
				CREATE TEMP TABLE w_actes AS 
				SELECT 
					substring(MFCCAM, 1, 7) as acte_code, 
					substring(MFCCAM, 1, 7) as acte_texte,
					substring(MFCCAM, 1, 7) as acte_texte_court, 
					CASE WHEN length(MFCCAM) >= 7 THEN 'CCAM' ELSE 'NGAP' END as nomenclature, 
					t_ccam_regroupements .oid as ccam_id_1, 
					t_ccam_regroupements.oid as ccam_id_4
				FROM w_MFP01_keys
					LEFT JOIN base.t_actes ON t_actes.code = substring(MFCCAM, 1, 7),
					base.t_ccam_regroupements
				WHERE 1=1
					AND t_actes.code IS NULL
					AND t_ccam_regroupements.code = 'NGAP';
				
				INSERT INTO base.t_actes(code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4)
				SELECT 
					acte_code, 
					acte_texte,
					acte_texte_court, 
					nomenclature, 
					ccam_id_1, 
					ccam_id_4
				FROM w_actes
				GROUP BY acte_code,acte_texte,acte_texte_court, nomenclature, ccam_id_1,ccam_id_4;

				UPDATE w_MFP01_keys SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE prestation_code = t_prestations.code;

				UPDATE w_MFP01_keys SET medecin_facture_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE MFRUPR = t_medecins_administratifs.code_original;

				UPDATE w_MFP01_keys SET medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE MFCPRC = t_medecins_administratifs.code_original;

				UPDATE w_MFP01_keys SET acte_id = t_actes.oid
				FROM base.t_actes
				WHERE substring(MFCCAM, 1, 7) = t_actes.code;

				UPDATE w_MFP01_keys SET lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = MFCSER AND
					code_original_2 = MFACTI AND
					code_original_3 = MFETAG AND
					code_original_4 = MFETAG || '|' || MFCHLT;


				DROP TABLE IF EXISTS w_factures_lignes_h;
				CREATE TEMP TABLE w_factures_lignes_h AS 
				SELECT
						p_factures.oid AS facture_id,
						w_ADDOSSDCPL AS no_facture,
						MFDTA1_date AS date_debut,
						MFHRA1 * 10000 AS heure_debut,
						MFDTA9_date AS date_fin,
						MFNBRE AS nb_rubrique,
						MFNBRE AS nb_prestation,
						MFCOE1 AS coefficient,
						MFCOET AS coefficient_mco,
						w_MFP01_keys.medecin_facture_id AS medecin_facture_id,
						w_MFP01_keys.medecin_comptabilise_id AS medecin_comptabilise_id,
						w_MFP01_keys.prestation_id AS prestation_id,
						w_MFP01_keys.acte_id AS acte_id,	
						MFCCAC AS activite_ccam,
						MFCCXD AS extension_ccam,
						MFCCPT AS phase_ccam,
						MFCCM1 AS modificateur_ccam_1,
						MFCCM2 AS modificateur_ccam_2,
						MFCCM3 AS modificateur_ccam_3,
						MFCCM4 AS modificateur_ccam_4,
						MFMFAM + MFMFA1 + MFMFA2 + MFMFA3 AS montant_facture,
						MFMFAM AS montant_facture_0,
						MFMFA1 AS montant_facture_1,
						MFMFA2 AS montant_facture_2,
						MFMFA3 AS montant_facture_22,
						MFMTDP AS montant_depassement,
						MFTFAM AS taux_0,
						MFTFA1 AS taux_1,
						MFTFA2 AS taux_2,
						MFTFA3 AS taux_22,
						MFPRUA AS prix_unitaire,
						w_MFP01_keys.lieu_id AS lieu_id,
						MFMCAM + MFMCA1 + MFMCA2 + MFMCA3 AS montant_comptabilise,
						MFMCAM AS montant_comptabilise_0,
						MFMCA1 AS montant_comptabilise_1,
						MFMCA2 AS montant_comptabilise_2,
						MFMCA3 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
				FROM w_MFP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key
					
				;

				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_h_9');
				
				DELETE FROM activite[PX].p_factures_lignes_h WHERE no_facture IN (SELECT w_ADDOSSDCPL FROM w_ADP01_factures_modifiees);

				INSERT INTO activite[PX].p_factures_lignes_h (
					facture_id,
					no_facture,
					date_debut,
					heure_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour
					)
				SELECT
					facture_id,
					no_facture,
					date_debut,
					heure_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour
				FROM w_factures_lignes_h;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_lignes_h_9');
										
										
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Compte client Honoraires">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_FDP03;
				CREATE TEMP TABLE w_FDP03 AS
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char(FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					to_char(FDRUPR,'FM0000') AS FDRUPR,
					to_char(FDRUPR,'FM0000') AS key,
					FDMPRM + FDMPOD AS FDMTRG,
					CASE WHEN FDTYPC = '0' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDTYPC = '1' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDTYPC = '2' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDTYPC = '3' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]_FDP03
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = '')
				WHERE FDCCLH = '2';

				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char(FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					to_char(FDRUPR,'FM0000') AS FDRUPR,
					to_char(FDRUPR,'FM0000') AS key,
					FDMPRM + FDMPOD AS FDMTRG,
					CASE WHEN FDTYPC = '0' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDTYPC = '1' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDTYPC = '2' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDTYPC = '3' THEN FDMPRM + FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]p_FDP03P
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = 'P')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDRUPR,'0000'),3,3) = MFCPRC)
				WHERE FDCCLH = '2';

				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char(FDP03.FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					to_char(FDP03.FDRUPR,'FM0000') AS FDRUPR,
					to_char(FDP03.FDRUPR,'FM0000') AS key,
					FDP03.FDMPRM + FDP03.FDMPOD AS FDMTRG,
					CASE WHEN FDP03.FDTYPC = '0' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDP03.FDTYPC = '1' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDP03.FDTYPC = '2' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDP03.FDTYPC = '3' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]h_FDP03H AS FDP03
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDDOSS = w_ADDOSS AND FDDCPL = w_ADDCPL AND w_CODENV = 'H')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDP03.FDRUPR,'0000'),3,3) = MFCPRC)
				WHERE FDCCLH = '2';
				
				-- Ajout des règlements / factures historique remises dans le circuit
				INSERT INTO w_FDP03
				SELECT 
					w_ADP01.w_ADDOSSDCPL,

					COALESCE(to_date(to_char(FDP03.FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS w_FDDTRG_date,
					to_char(FDP03.FDRUPR,'FM0000') AS FDRUPR,
					to_char(FDP03.FDRUPR,'FM0000') AS key,
					FDP03.FDMPRM + FDP03.FDMPOD AS FDMTRG,
					CASE WHEN FDP03.FDTYPC = '0' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_0,
					CASE WHEN FDP03.FDTYPC = '1' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_1,
					CASE WHEN FDP03.FDTYPC = '2' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_2,
					CASE WHEN FDP03.FDTYPC = '3' THEN FDP03.FDMPRM + FDP03.FDMPOD ELSE 0 END AS FDMTRG_22
				FROM prod_shs.[ACTIVITESCHEMA]_FDP03 AS FDP03
					JOIN w_ADP01_factures_modifiees w_ADP01 ON (FDP03.FDDOSS = w_ADDOSS AND FDP03.FDDCPL = w_ADDCPL AND w_CODENV = 'H')
					LEFT JOIN w_MFP01_rubriques ON (w_MFP01_rubriques.w_ADDOSSDCPL = w_ADP01.w_ADDOSSDCPL AND substr(to_char(FDP03.FDRUPR,'0000'),3,3) = MFCPRC)
					LEFT JOIN prod_shs.[ACTIVITESCHEMA]H_FDP03H FDP03H ON
						FDP03.FDDOSS = FDP03H.FDDOSS AND
						FDP03.FDDCPL = FDP03H.FDDCPL AND
						FDP03.FDTYPC = FDP03H.FDTYPC AND
						FDP03.FDCCLH = FDP03H.FDCCLH AND
						FDP03.FDAMRG = FDP03H.FDAMRG
				WHERE FDP03.FDCCLH = '2' AND
					FDP03H.FDDOSS IS NULL
				;


				DROP TABLE IF EXISTS w_FDP03_keys;
				CREATE TEMP TABLE w_FDP03_keys AS
				SELECT 
					key,
					FDRUPR,
					0::bigint AS medecin_comptabilise_id
				FROM w_FDP03
				GROUP BY 1,2;

								
				ALTER TABLE w_FDP03_keys  ADD CONSTRAINT w_FDP03_keys_pkey PRIMARY KEY(key);



				UPDATE w_FDP03_keys SET medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM activite[PX].t_medecins_administratifs
				WHERE FDRUPR = t_medecins_administratifs.code_original;

				
				
				DROP TABLE IF EXISTS w_factures_soldes_h;
				CREATE TEMP TABLE w_factures_soldes_h AS 
				SELECT
					p_factures.oid AS facture_id,
					w_ADDOSSDCPL AS no_facture,
					date_vente AS date_comptable,
					w_MFP01_keys.medecin_comptabilise_id AS medecin_comptabilise_id,
					SUM(MFMCAM + MFMCA1 + MFMCA2 + MFMCA3) AS montant_comptabilise,
					SUM(MFMCAM) AS montant_comptabilise_0,
					SUM(MFMCA1) AS montant_comptabilise_1,
					SUM(MFMCA2) AS montant_comptabilise_2,
					SUM(MFMCA3) AS montant_comptabilise_22,
					0::numeric AS montant_regle,
					0::numeric AS montant_regle_0,
					0::numeric AS montant_regle_1,
					0::numeric AS montant_regle_2,
					0::numeric AS montant_regle_22,
					'0'::text AS od_avoir
				FROM w_MFP01
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_MFP01_keys ON w_MFP01.key = w_MFP01_keys.key
				GROUP BY 1,2,3,4
				;

				INSERT INTO w_factures_soldes_h
				SELECT
					p_factures.oid AS facture_id,
					w_ADDOSSDCPL AS no_facture,
					w_FDDTRG_date AS date_comptable,
					w_FDP03_keys.medecin_comptabilise_id AS medecin_comptabilise_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(FDMTRG) AS montant_regle,
					SUM(FDMTRG_0) AS montant_montant_regle_0,
					SUM(FDMTRG_1) AS montant_montant_regle_1,
					SUM(FDMTRG_2) AS montant_montant_regle_2,
					SUM(FDMTRG_22) AS montant_montant_regle_22,
					'0'::text AS od_avoir
				FROM w_FDP03
					JOIN activite[PX].p_factures ON w_ADDOSSDCPL = p_factures.no_facture
					JOIN w_FDP03_keys ON w_FDP03.key = w_FDP03_keys.key
				GROUP BY 1,2,3,4;

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

				DELETE FROM activite[PX].p_factures_soldes_h WHERE no_facture IN (SELECT w_ADDOSSDCPL FROM w_ADP01_factures_modifiees);

				INSERT INTO activite[PX].p_factures_soldes_h (
					facture_id,
					no_facture,
					date_comptable,
					medecin_comptabilise_id,
					od_avoir,
					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_comptable,
					medecin_comptabilise_id,
					od_avoir,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					SUM(montant_regle),
					SUM(montant_regle_0),
					SUM(montant_regle_1),
					SUM(montant_regle_2),
					SUM(montant_regle_22)
				FROM w_factures_soldes_h
				GROUP BY 1,2,3,4,5;
				
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_8');
				
				-- Suppression tables de travail
				
				DROP TABLE IF EXISTS w_MFP01;		
				DROP TABLE IF EXISTS w_FDP03;
				DROP TABLE IF EXISTS w_factures_lignes_h;	
				DROP TABLE IF EXISTS w_factures_soldes_h;	
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Validation">
			<sqlcmd><![CDATA[

				
										
			]]></sqlcmd>
		</NODE>

	</NODE>
	
	<NODE name="FACTURES_PMSI_BG" label="RECUPERATION DES FACTURES PMSI BG">
		
		<NODE label="RAZ">
			<sqlcmd><![CDATA[

				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.type_facture = 'G';

				DELETE FROM activite[PX].p_factures WHERE p_factures.type_facture = 'G';

										
			]]></sqlcmd>
		</NODE>
		
		
		
		<NODE label="Identification RSS">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_rss;

				CREATE TEMP TABLE w_rss AS
				SELECT substr(no_sejour_administratif,1,8) AS no_sejour_administratif, 
				MIN(date_entree) AS date_entree, 
				MAX(date_sortie) AS date_sortie,
				MAX(date_naissance) AS date_naissance,
				MAX(oid) AS rss_id,
                MAX(valorise_fides) as valorise_fides
				FROM pmsi.p_rss
                JOIN pmsi.p_rsf_total ON p_rsf_total.rss_id = p_rss.oid
				WHERE etat = '' AND traitement_epmsi = '30' AND en_cours = '0'
				GROUP BY 1
				HAVING count(*) = 1;


				CREATE INDEX w_rss_i1
				  ON w_rss
				  USING btree
				  (no_sejour_administratif);

				CREATE INDEX w_rss_i2
				  ON w_rss
				  USING btree
				  (rss_id);
										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Génération prestations PMSI">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_factures_c;

				CREATE TEMP TABLE w_factures_c AS
				SELECT no_facture,
					SUM(montant_facture) AS montant_facture_c,
					SUM(montant_facture_0) AS montant_facture_0_c,
					SUM(montant_facture_1) AS montant_facture_1_c,
					SUM(montant_facture_2) AS montant_facture_2_c,
					SUM(montant_facture_22) AS montant_facture_22_c
				FROM activite[PX].p_factures_lignes_c
				GROUP BY 1
				ORDER BY 1;

				CREATE INDEX w_factures_c_i1
				  ON w_factures_c
				  USING btree
				  (no_facture);


				UPDATE activite[PX].p_factures SET 
					montant_facture_c = w_factures_c.montant_facture_c,
					montant_facture_0_c = w_factures_c.montant_facture_0_c,
					montant_facture_1_c = w_factures_c.montant_facture_1_c,
					montant_facture_2_c = w_factures_c.montant_facture_2_c,
					montant_facture_22_c = w_factures_c.montant_facture_22_c
				FROM w_factures_c
				WHERE p_factures.no_facture = w_factures_c.no_facture AND
					(p_factures.montant_facture_c IS DISTINCT FROM w_factures_c.montant_facture_c OR
					p_factures.montant_facture_0_c IS DISTINCT FROM w_factures_c.montant_facture_0_c OR
					p_factures.montant_facture_1_c IS DISTINCT FROM w_factures_c.montant_facture_1_c OR
					p_factures.montant_facture_2_c IS DISTINCT FROM w_factures_c.montant_facture_2_c OR
					p_factures.montant_facture_22_c IS DISTINCT FROM w_factures_c.montant_facture_22_c);
				
				DROP TABLE IF EXISTS w_factures_lignes_bg;

				CREATE TEMP TABLE w_factures_lignes_bg AS
				SELECT 
					w_rss.no_sejour_administratif AS no_sejour, 
					w_rss.no_sejour_administratif || '.BG' AS no_facture, 
					p_sejours.lieu_sortie_id AS lieu_id, 
					p_sejours.date_entree AS date_debut_facture, 
					p_sejours.date_sortie AS date_fin_facture, 
					p_sejours.date_sortie AS date_sortie, 
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					0 AS tiers_payant_2_id, 
					0 AS tiers_payant_22_id, 
					p_sejours.ghs_id AS ghs_id, 
					p_sejours.ghs_bebe1_id, 
					p_sejours.ghs_bebe2_id, 
					p_sejours.ghs_bebe3_id,

					p_rsf_detail.date_debut AS date_debut, 
					p_rsf_detail.date_fin AS date_fin, 
					
					trim(replace(replace(t_prestations_pmsi.code, ' F', ''), ' N', '')) AS prestation_code,
					trim(replace(replace(t_prestations_pmsi.code, ' F', ''), ' N', '')) AS rubrique_code,

					p_rsf_detail.nombre,
					p_rsf_detail.coefficient,
					p_rsf_detail.coefficient_mco,
					p_rsf_detail.prix_unitaire,
					p_rsf_detail.taux_remboursement,
					
					round(p_rsf_detail.sejour_remboursable,2) AS montant_comptabilise_budget_global_c
			FROM  activite[PX].p_sejours 
				JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
				JOIN w_rss ON w_rss.no_sejour_administratif = p_sejours.no_sejour AND p_sejours.date_sortie = w_rss.date_sortie  AND w_rss.date_naissance = p_patients.date_naissance
                    AND w_rss.valorise_fides IS DISTINCT FROM 1
				JOIN pmsi.p_rsf_detail ON w_rss.rss_id = p_rsf_detail.rss_id
				JOIN pmsi.t_prestations t_prestations_pmsi ON prestation_id = t_prestations_pmsi.oid  AND t_prestations_pmsi.code NOT IN ('BHN', 'PHN', 'ELMA', 'HYP', 'PB', 'PB  F', 'PHH', 'PNDL', 'SAP', 'SCOL', 'SIND')
			;


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

				montant_comptabilise_budget_global_c
				)

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

				SUM(montant_comptabilise_budget_global_c)

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

				UPDATE w_factures_lignes_bg SET rubrique_code = '111' WHERE rubrique_code IN ('GHS', 'EXH');

				DROP TABLE IF EXISTS w_prestations;
				CREATE TEMP TABLE w_prestations AS
				SELECT
				CASE WHEN TRPRST <> '' THEN TRPRST ELSE TRPRSA END AS prestation_code, 
				MAX(TRCRUB) AS rubrique_code 
				FROM prod_shs.[ACTIVITESCHEMA]_trp01 WHERE TRCENR = 'A51' 
				GROUP BY 1
				ORDER BY 1;


				UPDATE w_factures_lignes_bg SET rubrique_code = w_prestations.rubrique_code 
				FROM w_prestations 
				WHERE w_factures_lignes_bg.rubrique_code = w_prestations.prestation_code ;



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

	

				INSERT INTO activite[PX].t_rubriques_facturation(code, code_original, texte, texte_court)
				SELECT rubrique_code, rubrique_code, rubrique_code, rubrique_code
				FROM w_factures_lignes_bg 
					LEFT JOIN activite[PX].t_rubriques_facturation ON rubrique_code = t_rubriques_facturation.code
				WHERE t_rubriques_facturation.code IS NULL
				GROUP BY rubrique_code;
	
				
				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

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

				SELECT 

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

					0 AS taux_0, 
					taux_remboursement AS taux_1, 
					0 AS taux_2, 
					0 AS taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					0 AS montant_comptabilise, 
					0 AS montant_comptabilise_0, 
					0 AS montant_comptabilise_1, 
					0 AS montant_comptabilise_2,
					0 AS montant_comptabilise_22, 
					
					0 AS montant_encours, 
					0 AS montant_encours_0, 
					0 AS montant_encours_1, 
					0 AS montant_encours_2, 
					0 AS montant_encours_22,

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

					montant_comptabilise_budget_global_c AS montant_comptabilise_budget_global_1

				FROM w_factures_lignes_bg
					LEFT JOIN activite.t_prestations ON prestation_code = t_prestations.code			
					LEFT JOIN activite[PX].t_rubriques_facturation ON rubrique_code = t_rubriques_facturation.code
				;
										
										
			]]></sqlcmd>
		</NODE>
	
	</NODE>
	
	<NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
		
		<NODE label="Ecritures comptables">
			<sqlcmd><![CDATA[
	
				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT JLCJAL::text,
					to_char(JLCJAL,'FM000'),
					MAX(JLINT7)
				FROM prod_shs.[ACTIVITESCHEMA]_JLP01
				WHERE JLCJAL::text NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				ORDER BY 2
				;

				UPDATE activite[PX].t_journal
				SET type_journal = 'VE'
				WHERE type_journal = '' AND
					code IN ('071','072')
				;

				UPDATE activite[PX].t_journal
				SET type_journal = 'IGNORE'
				WHERE type_journal = '' AND
					code IN ('001','002','100')
				;

				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT to_char(PECPTE,'FM00000000'), to_char(PECPTE,'FM00000000'), MAX(PEINT3), MAX(PEINT3)
				FROM prod_shs.[ACTIVITESCHEMA]_PEP01
				WHERE PETYPE IN (95,96) AND
					to_char(PECPTE,'FM00000000') NOT IN (SELECT code FROM activite[PX].t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				;
				
				DROP TABLE IF EXISTS w_MCP01;
				CREATE TEMP TABLE w_MCP01 AS
				SELECT *,
					to_date(CASE WHEN MCAMTC > 0 THEN MCAMTC::text||'01' ELSE NULL END,'YYYYMMDD') AS date_comptable, 
					''::text AS no_sejour,
					0::bigint AS sejour_id,
					''::text AS no_facture,
					0::bigint AS facture_id,
					0::bigint AS medecin_administratif_id,
					0::bigint AS tiers_payant_id,
					''::text AS mode_reglement_code,
					'':: text AS type_ecriture, 
					'':: text AS type_piece,
					CASE WHEN MCCCLH = '1' THEN 'C' ELSE 'H' END AS clinique_honoraire
				FROM prod_shs.[ACTIVITESCHEMA]_MCP01
				WHERE MCTYMV = 0 AND MCCANN <> 'A' AND
					MCCJAL NOT IN (1,2)
				;
				
				UPDATE w_MCP01 SET
					no_sejour = p_factures.no_sejour,
					sejour_id = p_factures.sejour_id,
					no_facture = p_factures.no_facture,
					facture_id = p_factures.oid
				FROM activite[PX].p_factures
				WHERE (MCDOSA||'.'||MCDCPA) = p_factures.no_facture
				;

				DROP TABLE IF EXISTS w_CCP01_next;
				CREATE TEMP TABLE w_CCP01_next AS
				SELECT MAX(CCANEE*100+CCMOIS + CASE WHEN CCMOIS <> 12 THEN 1 ELSE 89 END) AS CCAMTC
				FROM prod_shs.[ACTIVITESCHEMA]_CCP01 
				WHERE CCMOIS <= 12 AND CCMLTT <> 0 AND
					CCNOR3 IN (320) ;


				UPDATE w_MCP01 SET
					MCAMTC = CASE 
							WHEN to_number(substr(MCDTEC,1,6),'FM999999') < CCAMTC THEN CCAMTC
							ELSE to_number(substr(MCDTEC,1,6),'FM999999') END,
					date_comptable = to_date(CASE 
							WHEN to_number(substr(MCDTEC,1,6),'FM999999') < CCAMTC THEN CCAMTC
							ELSE to_number(substr(MCDTEC,1,6),'FM999999') END || '01','YYYYMMDD')
				FROM w_CCP01_next
				WHERE MCPOIC <> '1' AND
					MCAMTC <> CASE 
					WHEN to_number(substr(MCDTEC,1,6),'FM999999') < CCAMTC THEN CCAMTC
					ELSE to_number(substr(MCDTEC,1,6),'FM999999') END AND
					MCTYMV = 0 AND MCCANN <> 'A'
				;

				UPDATE w_MCP01
				SET MCCPTE = CLCPTE, MCTYPE = CLTYPG
				FROM  prod_shs.[ACTIVITESCHEMA]_CLP01
				WHERE  MCTYPE = CLTYPE AND MCSANA = CLCCOL AND
					(
					MCCPTE <> CLCPTE OR 
					MCTYPE <> CLTYPG
					)
				;

				
				
				DELETE FROM activite[PX].p_ecriture_comptable
				USING (SELECT COALESCE(MIN(date_comptable),'0001-01-01') AS date_comptable_min FROM w_MCP01) subview
				WHERE p_ecriture_comptable.date_comptable >= date_comptable_min
				;
				
				INSERT INTO activite[PX].p_ecriture_comptable(
					code_original, 
					date_comptable, 
					type_ecriture, 
					type_piece, 
					piece, 
					mode_reglement_code,
					clinique_honoraire, 
					compte_id, 
					journal_id, 
					sejour_id, 
					no_sejour, 
					facture_id, 
					no_facture, 
					medecin_id, 
					tiers_payant_id, 
					texte, 
					montant_credit, 
					montant_debit,
					est_comptabilise,
					taux_tva)
				SELECT 
					to_char(MCFOLI,'FM00000')||'.'||to_char(MCLIGN,'FM00') AS code_original, 
					w_MCP01.date_comptable,
					CASE 
					WHEN t_journal.type_journal = 'VE' AND MCCPTE LIKE '411%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND MCCPTE LIKE '412%' THEN 'VCLI'
					WHEN t_journal.type_journal = 'VE' AND MCCPTE LIKE '445%' THEN 'VTVA'
					WHEN t_journal.type_journal = 'VE' AND w_MCP01.clinique_honoraire = 'C' THEN 'VPRD'
					WHEN t_journal.type_journal = 'VE' AND w_MCP01.clinique_honoraire = 'H' THEN 'VHON'
					WHEN MCCPTE LIKE '758%' THEN 'PEPR'
					WHEN MCCPTE LIKE '658%' THEN 'PEPR'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '468%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '471%' THEN 'ATT'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '411%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '412%' THEN 'RCLI'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '419%' THEN 'ACPT'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '51%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '531%' THEN 'BANQ'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '466%' THEN 'PHON'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '7%' THEN 'XPRD'
					WHEN t_journal.type_journal <> 'VE' AND MCCPTE LIKE '445%' THEN 'XTVA'
					ELSE '?'||to_char(MCCJAL,'FM000') END AS type_ecriture,
					CASE 
					WHEN t_journal.type_journal = 'VE' THEN 'VENTE'
					ELSE t_journal.type_journal END AS type_piece,
					MCAMTC::text || to_char(MCCJAL,'FM000') AS piece, 
					w_MCP01.mode_reglement_code,
					w_MCP01.clinique_honoraire, 
					COALESCE(t_compte.oid,0) AS compte_id, 
					COALESCE(t_journal.oid,0) AS journal_id, 
					w_MCP01.sejour_id, 
					w_MCP01.no_sejour, 
					w_MCP01.facture_id, 
					w_MCP01.no_facture, 
					w_MCP01.medecin_administratif_id, 
					w_MCP01.tiers_payant_id, 
					MCINT3 AS texte, 
					CASE WHEN MCSENS = 'C' THEN MCMONT ELSE 0.00 END AS CREDIT,
					CASE WHEN MCSENS = 'D' THEN MCMONT ELSE 0.00 END AS DEBIT, 
	
					CASE WHEN MCPOIC = '1' THEN '1'::text ELSE '0'::text END AS est_comptabilise,
					COALESCE(t_compte.taux_tva,0) AS taux_tva
				FROM w_MCP01
				LEFT JOIN activite[PX].t_compte ON MCCPTE = t_compte.code
				LEFT JOIN activite[PX].t_journal ON w_MCP01.MCCJAL = t_journal.code_original
				WHERE t_journal.type_journal IS DISTINCT FROM 'IGNORE'
				;
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Récupération chiffrier SHS">
			<sqlcmd><![CDATA[

				TRUNCATE activite[PX].p_chiffrier_shs;

				INSERT INTO activite[PX].p_chiffrier_shs(
					date_comptable, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_solde_client_c, 
					montant_ventes_h, 
					montant_reglements_h, 
					montant_solde_client_h) 
				SELECT 
					COALESCE(to_date(CCANEE * 10000 + CCMOIS * 100 + 01, 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS date_comptable, 
					SUM(CASE WHEN CCNOR3 = 105 THEN CCMLCL ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN CCNOR3 = 230 THEN CCMLCL ELSE 0 END) AS montant_reglements_c,
					SUM(CASE WHEN CCNOR3 = 235 THEN CCMLCL ELSE 0 END) AS montant_solde_client_c,
					SUM(CASE WHEN CCNOR3 = 105 THEN CCMLHO ELSE 0 END) AS montant_ventes_h,
					SUM(CASE WHEN CCNOR3 = 230 THEN CCMLHO ELSE 0 END) AS montant_reglements_h,
					SUM(CASE WHEN CCNOR3 = 235 THEN CCMLHO ELSE 0 END) AS montant_solde_client_h
				FROM prod_shs.[ACTIVITESCHEMA]_CCP01 
				WHERE CCCMON = 'E' AND CCMOIS <= 12 AND CCNOR3 IN (105, 230, 235) AND
					CCANEE >= [ENV_ADM_ANNEEDEBUT]
				GROUP BY 1
				HAVING SUM(CASE WHEN CCNOR3 = 235 THEN CCMLCL ELSE 0 END) <> 0
				ORDER BY 1;
				
				
				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 
					COALESCE(to_date(CCANEE * 10000 + CCMOIS * 100 + 01, 'YYYYMMDD') + interval '1 month' - interval '1 day', '20991231') AS date_comptable, 
					SUM(CASE WHEN CCNOR3 = 105 THEN CCMLCL ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN CCNOR3 = 230 THEN CCMLCL ELSE 0 END) AS montant_reglements_c,
					SUM(CASE WHEN CCNOR3 = 235 THEN CCMLCL ELSE 0 END) AS montant_solde_client_c,
					SUM(CASE WHEN CCNOR3 = 105 THEN CCMLHO ELSE 0 END) AS montant_ventes_h,
					SUM(CASE WHEN CCNOR3 = 230 THEN CCMLHO ELSE 0 END) AS montant_reglements_h,
					SUM(CASE WHEN CCNOR3 = 235 THEN CCMLHO ELSE 0 END) AS montant_solde_client_h
				FROM prod_shs.[ACTIVITESCHEMA]_CCP01 
				WHERE CCCMON = 'E' AND CCMOIS <= 12 AND CCNOR3 IN (105, 230, 235) AND
					CCANEE >= [ENV_ADM_ANNEEDEBUT]
				GROUP BY 1
				ORDER BY 1;
				
				
				
				TRUNCATE activite[PX].p_factures_comptables;

				DROP TABLE IF EXISTS w_factures_comptables;
				
				CREATE TEMP TABLE w_factures_comptables AS
				SELECT 
					'H'::text AS historique,
					FTDOSS,
					FTDCPL,
					0 AS facture_id,
					to_char(FTDOSS,'FM00000000') || '.' || to_char(FTDCPL,'FM00') AS no_facture,
					to_date(to_char(FTDTJV,'FM00000000'),'YYYYMMDD') AS date_comptable,
					SUM(CASE WHEN FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					SUM(CASE WHEN FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]h_FTP01H
				GROUP BY 1,2,3,4,5,6;

				CREATE INDEX w_factures_comptables_i1
				  ON w_factures_comptables
				  USING btree
				  (FTDOSS);

				INSERT INTO w_factures_comptables
				SELECT 
					'P'::text AS historique,
					FTP01.FTDOSS,
					FTP01.FTDCPL,
					0 AS facture_id,
					to_char(FTP01.FTDOSS,'FM00000000') || '.' || to_char(FTP01.FTDCPL,'FM00') AS no_facture,
					to_date(to_char(FTDTJV,'FM00000000'),'YYYYMMDD') AS date_comptable,
					SUM(CASE WHEN FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					SUM(CASE WHEN FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]p_FTP01P FTP01
					LEFT JOIN w_factures_comptables ON FTP01.FTDOSS = w_factures_comptables.FTDOSS AND
									FTP01.FTDCPL = w_factures_comptables.FTDCPL
				WHERE w_factures_comptables.FTDOSS IS NULL
				GROUP BY 1,2,3,4,5,6;


				INSERT INTO w_factures_comptables
				SELECT 
					''::text AS historique,
					FTP01.FTDOSS,
					FTP01.FTDCPL,
					0 AS facture_id,
					to_char(FTP01.FTDOSS,'FM00000000') || '.' || to_char(FTP01.FTDCPL,'FM00') AS no_facture,
					to_date(to_char(FTDTJV,'FM00000000'),'YYYYMMDD') AS date_comptable,
					SUM(CASE WHEN FTCCLH = '1' THEN FTMTFA ELSE 0 END) AS montant_ventes_c, 
					0::numeric AS montant_reglements_c, 
					SUM(CASE WHEN FTCCLH = '2' THEN FTMTFA ELSE 0 END) AS montant_ventes_h, 
					0::numeric AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]_FTP01 FTP01
					LEFT JOIN w_factures_comptables ON FTP01.FTDOSS = w_factures_comptables.FTDOSS AND
									FTP01.FTDCPL = w_factures_comptables.FTDCPL
				WHERE w_factures_comptables.FTDOSS IS NULL
				GROUP BY 1,2,3,4,5,6;


				INSERT INTO w_factures_comptables
				SELECT 
					'H'::text AS historique,
					FDDOSS,
					FDDCPL,
					0 AS facture_id,
					to_char(FDDOSS,'FM00000000') || '.' || to_char(FDDCPL,'FM00') AS no_facture,
					to_date(to_char(FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day' AS date_comptable,
					0::numeric AS montant_ventes_c, 
					SUM(CASE WHEN FDCCLH = '1' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					SUM(CASE WHEN FDCCLH = '2' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]h_FDP03H
					JOIN w_factures_comptables ON FDDOSS = w_factures_comptables.FTDOSS AND
									FDDCPL = w_factures_comptables.FTDCPL AND
									historique = 'H'
				WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01
				GROUP BY 1,2,3,4,5,6;

				INSERT INTO w_factures_comptables
				SELECT 
					'P'::text AS historique,
					FDDOSS,
					FDDCPL,
					0 AS facture_id,
					to_char(FDDOSS,'FM00000000') || '.' || to_char(FDDCPL,'FM00') AS no_facture,
					to_date(to_char(FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day' AS date_comptable,
					0::numeric AS montant_ventes_c, 
					SUM(CASE WHEN FDCCLH = '1' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					SUM(CASE WHEN FDCCLH = '2' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]p_FDP03P
					JOIN w_factures_comptables ON FDDOSS = w_factures_comptables.FTDOSS AND
									FDDCPL = w_factures_comptables.FTDCPL AND
									historique = 'P'
				WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01
				GROUP BY 1,2,3,4,5,6;


				INSERT INTO w_factures_comptables
				SELECT 
					''::text AS historique,
					FDDOSS,
					FDDCPL,
					0 AS facture_id,
					to_char(FDDOSS,'FM00000000') || '.' || to_char(FDDCPL,'FM00') AS no_facture,
					to_date(to_char(FDAMRG * 100 + 01,'FM00000000'), 'YYYYMMDD') + interval '1 month' - interval '1 day' AS date_comptable,
					0::numeric AS montant_ventes_c, 
					SUM(CASE WHEN FDCCLH = '1' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_c, 
					0::numeric AS montant_ventes_h, 
					SUM(CASE WHEN FDCCLH = '2' THEN FDMPRM + FDMPOD ELSE 0 END) AS montant_reglements_h
				FROM prod_shs.[ACTIVITESCHEMA]_FDP03
					JOIN w_factures_comptables ON FDDOSS = w_factures_comptables.FTDOSS AND
									FDDCPL = w_factures_comptables.FTDCPL AND
									historique = ''
				WHERE FDAMRG >= [ENV_ADM_ANNEEDEBUT]01
				GROUP BY 1,2,3,4,5,6;





				INSERT INTO activite[PX].p_factures_comptables(
					facture_id,
					no_facture,
					date_comptable, 
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h)

				SELECT 
					facture_id,
					no_facture,
					date_comptable, 
					SUM(montant_ventes_c), 
					SUM(montant_reglements_c), 
					SUM(montant_ventes_h), 
					SUM(montant_reglements_h)
				FROM w_factures_comptables
				WHERE date_comptable >= '[ENV_ADM_ANNEEDEBUT]0101'
				GROUP BY 1,2,3;
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>
	
	<NODE name="PARAM" label="RECUPERATION DES PARAMETRES">
	
		<NODE label="Comptabibilité prod_shs">
			<sqlcmd><![CDATA[
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN cacodp text default ''''',1)
				WHERE 'cacodp' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN caadre text default ''''',1)
				WHERE 'caadre' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN caadrs text default ''''',1)
				WHERE 'caadrs' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN cavile text default ''''',1)
				WHERE 'cavile' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN catlph text default ''''',1)
				WHERE 'catlph' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_cap01 ADD COLUMN cafaxc text default ''''',1)
				WHERE 'cafaxc' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_cap01' )
				;
				
					
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_acp01 ADD COLUMN acclpp character varying(20) default ''''',1)
				WHERE 'acclpp' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_acp01' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]_mfp01cli ADD COLUMN mfclpp character varying(20) default ''''',1)
				WHERE 'mfclpp' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]_mfp01cli' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]p_mfp01clip ADD COLUMN mfclpp character varying(20) default ''''',1)
				WHERE 'mfclpp' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]p_mfp01clip' )
				;
				SELECT base.cti_execute('ALTER TABLE prod_shs.[ACTIVITESCHEMA]h_mfp01clih ADD COLUMN mfclpp character varying(20) default ''''',1)
				WHERE 'mfclpp' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name ILIKE '[ACTIVITESCHEMA]h_mfp01clih' )
				;
			]]></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 '0000', '0000', '0', 'PATIENTS', 'PATIENTS'
				WHERE '0000' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);

				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT CACCAI, CACCAI, CASE WHEN SUBSTR(CACCAI,1,1) IN ('1', '3', '4')  THEN '1' ELSE '2' END, CARSO1, CARSO1
							FROM prod_shs.[ACTIVITESCHEMA]_CAP01
							WHERE CACCAI NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);
							
				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid
				FROM prod_shs.[ACTIVITESCHEMA]_CFP01
					JOIN base.t_grands_regimes ON to_char(CFRGP2,'FM00') = t_grands_regimes.code AND 
						CFRGP2 <> 0
				WHERE t_tiers_payant.code_original = CFCCAI AND
					COALESCE(t_tiers_payant.grand_regime_id,0) = 0 AND
					t_grands_regimes.oid <> 0;
										
				-- Adresses des tiers
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT CACODP, MAX(CAVILE), MAX(CAVILE), MAX(t_departements.oid)
				FROM prod_shs.[ACTIVITESCHEMA]_CAP01
				LEFT JOIN base.t_codes_postaux ON CACODP = t_codes_postaux.code
				JOIN base.t_departements ON 
					CACODP NOT LIKE '97%' AND substr(CACODP,1,2) = t_departements.code OR
					CACODP LIKE '97%' AND substr(CACODP,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL 
				GROUP BY 1
				;

			
				UPDATE activite[PX].t_tiers_payant SET
					adresse = CAADRE || ' ' || CAADRS,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = CAVILE,
					telephone = CATLPH,
					fax = CAFAXC
				FROM prod_shs.[ACTIVITESCHEMA]_CAP01
					LEFT JOIN base.t_codes_postaux ON CACODP = t_codes_postaux.code
				WHERE t_tiers_payant.code_original = CACCAI AND
					(
					adresse IS DISTINCT FROM (CAADRE || ' ' || CAADRS) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM CAVILE OR
					telephone IS DISTINCT FROM CATLPH OR
					fax IS DISTINCT FROM CAFAXC
					)
				;
				
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Médecins">
			<sqlcmd><![CDATA[
			
				-- Mise à jour du code original si absent et si matching sur le code
				UPDATE base.t_specialites_medecin SET
					code_original = SPCSPE
				FROM
					prod_shs.[ACTIVITESCHEMA]_SPP01
				where 1=1
					AND SPCSPE = t_specialites_medecin.code
					AND t_specialites_medecin.code_original IS NULL;
				
				-- Ajout des nouvelles spécialités
				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_specialites_medecin(code_original, code, texte, texte_court)
				SELECT 
					SPCSPE, SPCSPE, SPINTS, SPINTS 
				FROM 
					prod_shs.[ACTIVITESCHEMA]_SPP01
					LEFT JOIN base.t_specialites_medecin spe ON spe.code_original::text = SPCSPE::text
				WHERE 1=1
					AND SPCSPE <> '' 
					AND spe.code_original IS NULL
				ORDER BY SPCSPE;
				
				INSERT INTO activite[PX].t_specialites_medecin(oid, code, code_original, texte, texte_court) 
				SELECT 0, '', '0', 'Non saisie', 'Non saisie'
				WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_specialites_medecin);
				
				


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

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

				DROP TABLE IF EXISTS w_medecins;
				CREATE TEMP TABLE w_medecins AS
				SELECT 
					to_char(MDPRAT,'FM0000') AS MDPRAT,
					base.cti_soundex_nom(MDNOMS) AS MDNOMS_SOUNDEX, 
					base.cti_soundex_nom(COALESCE(MDPRES,'')) AS MDPRES_SOUNDEX, 
					MDNOMS, 
					COALESCE(MDPRES,'') AS MDPRES, 
					COALESCE(MDNIOM,'') AS MDNIOM, 
					MDCSPE, 
					COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
				FROM prod_shs.[ACTIVITESCHEMA]_MDP01 
					LEFT JOIN activite[PX].t_medecins_administratifs ON to_char(MDPRAT,'FM0000') = t_medecins_administratifs.code_original;

				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
				SELECT w_medecins.MDNOMS, w_medecins.MDPRES, w_medecins.MDNIOM, 0 FROM
				(SELECT SUBSTR(MDNOMS_SOUNDEX, 1, 8) AS MDNOMS_SOUNDEX, SUBSTR(MDPRES_SOUNDEX, 1, 8) AS MDPRES_SOUNDEX, MDNIOM, MIN(MDPRAT) AS MDPRAT
				FROM w_medecins
				GROUP BY 1,2,3) subview, w_medecins
				WHERE w_medecins.MDPRAT = subview.MDPRAT
					AND subview.MDNOMS_SOUNDEX || ',' || subview.MDPRES_SOUNDEX || ',' ||  subview.MDNIOM 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.MDNOMS, w_medecins.MDPRES, w_medecins.MDNIOM, 0 FROM
				(SELECT MDNOMS_SOUNDEX, MDPRES_SOUNDEX, MIN(MDPRAT) AS MDPRAT
				FROM w_medecins
				GROUP BY 1,2) subview, w_medecins
				WHERE w_medecins.MDPRAT = subview.MDPRAT
					AND subview.MDNOMS_SOUNDEX || ',' || subview.MDPRES_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(MDNOMS_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(MDPRES_SOUNDEX, 1, 8) = subview.prenom
				AND MDNIOM = 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(MDNOMS_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(MDPRES_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 MDPRAT, MDPRAT, MDNOMS, MDPRES, COALESCE(t_specialites_medecin.oid,0), medecin_id
				FROM w_medecins
					LEFT JOIN base.t_specialites_medecin ON (MDCSPE = t_specialites_medecin.code_original)
				WHERE MDPRAT NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

				UPDATE activite[PX].t_medecins_administratifs
				SET nom = MDNOMS,
					prenom = MDPRES,
					specialite_id = COALESCE(t_specialites_medecin.oid,0),
					medecin_id = w_medecins.medecin_id
				FROM w_medecins LEFT JOIN base.t_specialites_medecin ON (MDCSPE = t_specialites_medecin.code_original)
				WHERE w_medecins.MDPRAT = t_medecins_administratifs.code_original
					AND (
					t_medecins_administratifs.nom <> MDNOMS OR
					t_medecins_administratifs.prenom <> MDPRES OR
					t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0) OR
					t_medecins_administratifs.medecin_id <> w_medecins.medecin_id
				);

				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;
                
                -- Code rpps
                UPDATE base.t_medecins
                SET code_rpps = subview.RPPS
                FROM
                (
                SELECT medecin_id, count(DISTINCT MDRPPS), MAX(MDRPPS::text) AS RPPS
                FROM activite[PX].t_medecins_administratifs
                JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
                JOIN prod_shs.[ACTIVITESCHEMA]_MDP03 ON code_original = to_char(MDPRAT,'FM0000')
                WHERE MDRPPS <> 0 AND 
                    t_medecins.code_rpps = '' AND 
                    medecin_id <> 0
                GROUP BY 1
                HAVING count(DISTINCT MDRPPS) = 1
                ) subview
                WHERE t_medecins.oid = subview.medecin_id
                ;
				
				-- Adresse	
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT MDCODP, MAX(MDVIL1), MAX(MDVIL1), MAX(t_departements.oid)
				FROM prod_shs.[ACTIVITESCHEMA]_MDP01
				LEFT JOIN base.t_codes_postaux ON MDCODP = t_codes_postaux.code
				JOIN base.t_departements ON 
					MDCODP NOT LIKE '97%' AND substr(MDCODP,1,2) = t_departements.code OR
					MDCODP LIKE '97%' AND substr(MDCODP,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL 
				GROUP BY 1
				;

			
				UPDATE activite[PX].t_medecins_administratifs SET
					adresse = MDADRE || ' ' || MDADS1,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = MDVIL1,
					telephone = MDTLPH,
					fax = MDTLPF,
					no_adeli = MDNIOM
				FROM prod_shs.[ACTIVITESCHEMA]_MDP01
					LEFT JOIN base.t_codes_postaux ON MDCODP = t_codes_postaux.code
				WHERE t_medecins_administratifs.code_original = to_char(MDPRAT,'FM0000') AND
					(
					adresse IS DISTINCT FROM (MDADRE || ' ' || MDADS1) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM MDVIL1 OR
					telephone IS DISTINCT FROM MDTLPH OR
					fax IS DISTINCT FROM MDTLPF OR
					no_adeli IS DISTINCT FROM MDNIOM
					)
				;

										
										
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Codes Postaux">
			<sqlcmd><![CDATA[ 
				
				-- Ajout des codes postaux inconnus
				
				INSERT INTO base.t_codes_postaux (code, texte, texte_court)
				SELECT ADCODM, max(ADVILM), max(ADVILM) FROM prod_SHS.[ACTIVITESCHEMA]_ADP01
				LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = prod_SHS.[ACTIVITESCHEMA]_ADP01.ADCODM
				WHERE 1=1
					AND t_codes_postaux.code IS NULL
					AND base.cti_is_num(ADCODM::text)
					AND char_length(ADCODM::text) = 5
				GROUP BY ADCODM
				ORDER BY ADCODM;

			
				INSERT INTO base.t_codes_postaux (code, texte, texte_court)
				SELECT ADCODM, max(ADVILM), max(ADVILM) FROM prod_SHS.[ACTIVITESCHEMA]p_ADP01p
				LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = prod_SHS.[ACTIVITESCHEMA]p_ADP01p.ADCODM
				WHERE 1=1
					AND t_codes_postaux.code IS NULL
					AND base.cti_is_num(ADCODM::text)
					AND char_length(ADCODM::text) = 5
				GROUP BY ADCODM
				ORDER BY ADCODM;

			
				INSERT INTO base.t_codes_postaux (code, texte, texte_court)
				SELECT ADCODM, max(ADVILM), max(ADVILM) FROM prod_SHS.[ACTIVITESCHEMA]h_ADP01h
				LEFT JOIN base.t_codes_postaux ON t_codes_postaux.code = prod_SHS.[ACTIVITESCHEMA]h_ADP01h.ADCODM
				WHERE 1=1
					AND t_codes_postaux.code IS NULL
					AND base.cti_is_num(ADCODM::text)
					AND char_length(ADCODM::text) = 5
				GROUP BY ADCODM
				ORDER BY ADCODM;
				
				
				-- Mise à jour des départements
				
				UPDATE base.t_codes_postaux SET
					departement_id = t_departements.oid
				FROM base.t_departements
				WHERE 1=1
					AND substring(t_codes_postaux.code, 1, 2) NOT IN ('97', '98')
					AND t_codes_postaux.oid <> 0
					AND t_codes_postaux.departement_id = 0
					AND t_departements.code = substring(t_codes_postaux.code, 1, 2);

				UPDATE base.t_codes_postaux SET
					departement_id = t_departements.oid
				FROM base.t_departements
				WHERE 1=1
					AND substring(t_codes_postaux.code, 1, 2) IN ('97', '98')
					AND t_codes_postaux.oid <> 0
					AND t_codes_postaux.departement_id = 0
					AND t_departements.code = substring(t_codes_postaux.code, 1, 3);

				
				SELECT base.cti_reorganize_codes_postaux_c('activite');
				
			]]></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 SFCSER, SFCSER, SFINT5, SFINT5, SFNLIT, CASE WHEN SFGGHS = '1' THEN '1' ELSE '0' END 
								FROM prod_shs.[ACTIVITESCHEMA]_SFP01
								WHERE SFCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								ORDER BY SFCSER;
								
				
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT SOCSER, SOCSER,SOCSER, SOCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]_SOP01
								WHERE SOCSER <> '' AND
									SOCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY SOCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT SOCSER, SOCSER,SOCSER, SOCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]p_SOP01P
								WHERE SOCSER <> '' AND
									SOCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY SOCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT SOCSER, SOCSER,SOCSER, SOCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]h_SOP01H
								WHERE SOCSER <> '' AND
									SOCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY SOCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT ADCSER, ADCSER,ADCSER, ADCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]_ADP01
								WHERE ADCSER <> '' AND
									ADCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY ADCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT ADCSER, ADCSER,ADCSER, ADCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P
								WHERE ADCSER <> '' AND
									ADCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY ADCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT ADCSER, ADCSER,ADCSER, ADCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H
								WHERE ADCSER <> '' AND
									ADCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY ADCSER
								ORDER BY 1;
								
				
				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT MFCSER, MFCSER,MFCSER, MFCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
								WHERE MFCSER <> '' AND
									MFCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY MFCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT MFCSER, MFCSER,MFCSER, MFCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP
								WHERE MFCSER <> '' AND
									MFCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY MFCSER
								ORDER BY 1;

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, nb_lits)
								SELECT MFCSER, MFCSER,MFCSER, MFCSER, 0
								FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH
								WHERE MFCSER <> '' AND
									MFCSER NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
								GROUP BY MFCSER
								ORDER BY 1;


				UPDATE activite[PX].t_services_facturation
				SET mode_traitement_id = COALESCE(t_modes_traitement.oid,0)
				FROM prod_shs.[ACTIVITESCHEMA]_SFP01
					LEFT JOIN base.t_modes_traitement ON substr(SFCDMT,1,2) = t_modes_traitement.code
				WHERE t_services_facturation.code_original = SFCSER AND 
					COALESCE(mode_traitement_id,0) = 0 AND
					COALESCE(mode_traitement_id,0) <> COALESCE(t_modes_traitement.oid,0);

				UPDATE activite[PX].t_services_facturation
				SET dmt_id = COALESCE(t_dmt.oid,0)
				FROM prod_shs.[ACTIVITESCHEMA]_SFP01
					LEFT JOIN base.t_dmt ON substr(SFCDMT,3,3) = t_dmt.code
				WHERE t_services_facturation.code_original = SFCSER AND 
					COALESCE(dmt_id,0) = 0 AND
					COALESCE(dmt_id,0) <> COALESCE(t_dmt.oid,0);

					
				-- 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 L3CDUM, L3CDUM, L3LBUM, L3LBUM
								FROM prod_shs.[PMSISCHEMA]_L3P01
								WHERE L3CDUM NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
								ORDER BY L3CDUM;


				-- 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 ASACTI, ASACTI, ASINTS, ASINTS
								FROM prod_shs.[ACTIVITESCHEMA]_ASP01
								WHERE ASACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								ORDER BY ASACTI;
								
				
				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT SOACTI, SOACTI,SOACTI, SOACTI
								FROM prod_shs.[ACTIVITESCHEMA]_SOP01
								WHERE SOACTI <> '' AND
									SOACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY SOACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT SOACTI, SOACTI,SOACTI, SOACTI
								FROM prod_shs.[ACTIVITESCHEMA]p_SOP01P
								WHERE SOACTI <> '' AND
									SOACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY SOACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT SOACTI, SOACTI,SOACTI, SOACTI
								FROM prod_shs.[ACTIVITESCHEMA]h_SOP01H
								WHERE SOACTI <> '' AND
									SOACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY SOACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT ADACTI, ADACTI,ADACTI, ADACTI
								FROM prod_shs.[ACTIVITESCHEMA]_ADP01
								WHERE ADACTI <> '' AND
									ADACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY ADACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT ADACTI, ADACTI,ADACTI, ADACTI
								FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P
								WHERE ADACTI <> '' AND
									ADACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY ADACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT ADACTI, ADACTI,ADACTI, ADACTI
								FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H
								WHERE ADACTI <> '' AND
									ADACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY ADACTI
								ORDER BY 1;
							
				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT MFACTI, MFACTI,MFACTI, MFACTI
								FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
								WHERE MFACTI <> '' AND
									MFACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY MFACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT MFACTI, MFACTI,MFACTI, MFACTI
								FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP
								WHERE MFACTI <> '' AND
									MFACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY MFACTI
								ORDER BY 1;

				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court)
								SELECT MFACTI, MFACTI,MFACTI, MFACTI
								FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH
								WHERE MFACTI <> '' AND
									MFACTI NOT IN (SELECT code_original FROM activite[PX].t_activites)
								GROUP BY MFACTI
								ORDER BY 1;

				-- 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 CHETAG, CHETAG, MAX(CASE WHEN CHINTS <> '' THEN CHINTS ELSE CHETAG END),MAX( CASE WHEN CHINTS <> '' THEN CHINTS ELSE CHETAG END), MAX(CHNLIT)
				FROM prod_shs.[ACTIVITESCHEMA]_CHP01
				WHERE CHACTI = '' AND CHCHLT = ''  AND
					CHETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY 1,2
				ORDER BY 1;
								
				
				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT SOETAG, SOETAG,SOETAG, SOETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]_SOP01
				WHERE SOETAG <> '' AND
					SOETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY SOETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT SOETAG, SOETAG,SOETAG, SOETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]p_SOP01P
				WHERE SOETAG <> '' AND
					SOETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY SOETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT SOETAG, SOETAG,SOETAG, SOETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]h_SOP01H
				WHERE SOETAG <> '' AND
					SOETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY SOETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT ADETAG, ADETAG, ADETAG, ADETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]_ADP01
				WHERE ADETAG <> '' AND
					ADETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY ADETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT ADETAG, ADETAG, ADETAG, ADETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P
				WHERE ADETAG <> '' AND
					ADETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY ADETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT ADETAG, ADETAG, ADETAG, ADETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H
				WHERE ADETAG <> '' AND
					ADETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY ADETAG
				ORDER BY 1;
								
				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT MFETAG, MFETAG, MFETAG, MFETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI
				WHERE MFETAG <> '' AND
					MFETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY MFETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT MFETAG, MFETAG, MFETAG, MFETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP
				WHERE MFETAG <> '' AND
					MFETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY MFETAG
				ORDER BY 1;

				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court, nb_lits)
				SELECT MFETAG, MFETAG, MFETAG, MFETAG, 0
				FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH
				WHERE MFETAG <> '' AND
					MFETAG NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY MFETAG
				ORDER BY 1;

				UPDATE activite[PX].t_lits
				SET code_original = t_etages.code_original || '|' || t_lits.code_original
				FROM activite[PX].t_etages 
				WHERE t_lits.etage_id = t_etages.oid AND t_lits.code_original NOT LIKE '%|%';
				
				UPDATE activite[PX].t_lits
				SET code_original = '|'
				WHERE oid = 0;

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

				INSERT INTO activite[PX].t_lits(code, code_original, texte, texte_court, etage_id)
				SELECT '****', t_etages.code_original || '|' , 'Non renseigné', 'Non renseigné', t_etages.oid
				FROM activite[PX].t_etages LEFT JOIN activite[PX].t_lits ON t_etages.oid = t_lits.etage_id AND t_lits.code_original = t_etages.code_original || '|'
				WHERE t_etages.code_original <> '' AND t_lits.oid IS NULL;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT CHETAG || '|' || CHCHLT, CHCHLT, CASE WHEN CHINTS <> '' THEN CHINTS ELSE CHCHLT END, CASE WHEN CHINTS <> '' THEN CHINTS ELSE CHCHLT END, 
					t_etages.oid, CASE WHEN CHCHLT <> '' AND SUBSTR(CHCHLT,5,1) = '' THEN 'O' ELSE 'N' END
				FROM prod_shs.[ACTIVITESCHEMA]_CHP01 JOIN activite[PX].t_etages ON CHETAG = t_etages.code_original
				WHERE CHACTI = '' AND CHCHLT <> '' AND
					CHETAG || '|' || CHCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
				ORDER BY 1;
				
				
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT SOETAG || '|' || SOCHLT, SOCHLT, SOCHLT, SOCHLT, 
									t_etages.oid, CASE WHEN SOCHLT <> '' AND SUBSTR(SOCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]_SOP01 JOIN activite[PX].t_etages ON SOETAG = t_etages.code_original
								WHERE SOETAG <> '' AND SOCHLT <> '' AND
									SOETAG || '|' || SOCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY SOETAG, SOCHLT, t_etages.oid
								ORDER BY SOETAG, SOCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT SOETAG || '|' || SOCHLT, SOCHLT, SOCHLT, SOCHLT, 
									t_etages.oid, CASE WHEN SOCHLT <> '' AND SUBSTR(SOCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]p_SOP01P JOIN activite[PX].t_etages ON SOETAG = t_etages.code_original
								WHERE SOETAG <> '' AND SOCHLT <> '' AND
									SOETAG || '|' || SOCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY SOETAG, SOCHLT, t_etages.oid
								ORDER BY SOETAG, SOCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT SOETAG || '|' || SOCHLT, SOCHLT, SOCHLT, SOCHLT, 
									t_etages.oid, CASE WHEN SOCHLT <> '' AND SUBSTR(SOCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]h_SOP01H JOIN activite[PX].t_etages ON SOETAG = t_etages.code_original
								WHERE SOETAG <> '' AND SOCHLT <> '' AND
									SOETAG || '|' || SOCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY SOETAG, SOCHLT, t_etages.oid
								ORDER BY SOETAG, SOCHLT;
								
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT ADETAG || '|' || ADCHLT, ADCHLT, ADCHLT, ADCHLT, 
									t_etages.oid, CASE WHEN ADCHLT <> '' AND SUBSTR(ADCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]_ADP01 JOIN activite[PX].t_etages ON ADETAG = t_etages.code_original
								WHERE ADETAG <> '' AND ADCHLT <> '' AND
									ADETAG || '|' || ADCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY ADETAG, ADCHLT, t_etages.oid
								ORDER BY ADETAG, ADCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT ADETAG || '|' || ADCHLT, ADCHLT, ADCHLT, ADCHLT, 
									t_etages.oid, CASE WHEN ADCHLT <> '' AND SUBSTR(ADCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]p_ADP01P JOIN activite[PX].t_etages ON ADETAG = t_etages.code_original
								WHERE ADETAG <> '' AND ADCHLT <> '' AND
									ADETAG || '|' || ADCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY ADETAG, ADCHLT, t_etages.oid
								ORDER BY ADETAG, ADCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT ADETAG || '|' || ADCHLT, ADCHLT, ADCHLT, ADCHLT, 
									t_etages.oid, CASE WHEN ADCHLT <> '' AND SUBSTR(ADCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]h_ADP01H JOIN activite[PX].t_etages ON ADETAG = t_etages.code_original
								WHERE ADETAG <> '' AND ADCHLT <> '' AND
									ADETAG || '|' || ADCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY ADETAG, ADCHLT, t_etages.oid
								ORDER BY ADETAG, ADCHLT;
							
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT MFETAG || '|' || MFCHLT, MFCHLT, MFCHLT, MFCHLT, 
									t_etages.oid, CASE WHEN MFCHLT <> '' AND SUBSTR(MFCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]_MFP01CLI JOIN activite[PX].t_etages ON MFETAG = t_etages.code_original
								WHERE MFETAG <> '' AND MFCHLT <> '' AND
									MFETAG || '|' || MFCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY MFETAG, MFCHLT, t_etages.oid
								ORDER BY MFETAG, MFCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT MFETAG || '|' || MFCHLT, MFCHLT, MFCHLT, MFCHLT, 
									t_etages.oid, CASE WHEN MFCHLT <> '' AND SUBSTR(MFCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]p_MFP01CLIP JOIN activite[PX].t_etages ON MFETAG = t_etages.code_original
								WHERE MFETAG <> '' AND MFCHLT <> '' AND
									MFETAG || '|' || MFCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY MFETAG, MFCHLT, t_etages.oid
								ORDER BY MFETAG, MFCHLT;

				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
								SELECT MFETAG || '|' || MFCHLT, MFCHLT, MFCHLT, MFCHLT, 
									t_etages.oid, CASE WHEN MFCHLT <> '' AND SUBSTR(MFCHLT,5,1) = '' THEN 'O' ELSE 'N' END
								FROM prod_shs.[ACTIVITESCHEMA]h_MFP01CLIH JOIN activite[PX].t_etages ON MFETAG = t_etages.code_original
								WHERE MFETAG <> '' AND MFCHLT <> '' AND
									MFETAG || '|' || MFCHLT NOT IN (SELECT code_original FROM activite[PX].t_lits)
								GROUP BY MFETAG, MFCHLT, t_etages.oid
								ORDER BY MFETAG, MFCHLT;
								
				UPDATE activite[PX].t_lits 
				SET chambre_particuliere = CASE WHEN split_part(code_original, '|', 2) <> '' AND SUBSTR(split_part(code_original, '|', 2),5,1) = '' THEN 'O' ELSE 'N' END
				WHERE chambre_particuliere <> CASE WHEN split_part(code_original, '|', 2) <> '' AND SUBSTR(split_part(code_original, '|', 2),5,1) = '' THEN 'O' ELSE 'N' END AND
					chambre_particuliere = '';
										
			]]></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 NACRUB, NACRUB, NAINTS, NAINTS
				FROM prod_shs.[ACTIVITESCHEMA]_NAP01
				WHERE NACRUB NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation)
				ORDER BY NACRUB;


				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, clinique_honoraire)
				SELECT SXCACA, SXCACA, SXINTS, SXINTS, CASE WHEN SXCCLH = '1' THEN 'C' WHEN SXCCLH = '2' THEN 'H' ELSE '' END
				FROM prod_shs.[ACTIVITESCHEMA]_SXP01
				WHERE SXCCAI = 0 AND SUBSTR(SXCACA, 5 , 1) <> 'F' AND SUBSTR(SXCACA, 5 , 1) <> 'N' AND
					SXCACA NOT IN (SELECT code FROM activite.t_prestations)
				ORDER BY SXCACA;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court, clinique_honoraire)
				SELECT SXCACA, SXCACA, SXINTS, SXINTS, CASE WHEN SXCCLH = '1' THEN 'C' WHEN SXCCLH = '2' THEN 'H' ELSE '' END
				FROM 
					(
					SELECT 'FJ' AS SXCACA, 'FORFAIT JOURNALIER' AS SXINTS, '1' AS SXCCLH 
					UNION
					SELECT 'N' AS SXCACA, 'SUPPLEMENT NUIT' AS SXINTS, '2' AS SXCCLH 
					UNION
					SELECT 'F' AS SXCACA, 'SUPPLEMENT FERIE' AS SXINTS, '2' AS SXCCLH 
					UNION
					SELECT 'DIV' AS SXCACA, 'DIVERS' AS SXINTS, '' AS SXCCLH 
					UNION
					SELECT 'NOEMIE' AS SXCACA, 'ACOMPTES NOEMIE' AS SXINTS, '1' AS SXCCLH 
					) SXP01
				WHERE SXCACA NOT IN (SELECT code FROM activite.t_prestations)
				ORDER BY SXCACA;
                
                INSERT INTO activite[PX].t_risque(code, texte)
                SELECT
                    ADCRIS, ADCRIS
                FROM
                    prod_shs.[ACTIVITESCHEMA]_ADP01
                    LEFT JOIN activite[PX].t_risque ON t_risque.code = ADCRIS
                WHERE 1=1
                    AND ADCRIS IS DISTINCT FROM NULL
                    AND t_risque.code IS NULL
                GROUP BY 1,2;
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>
		
	<NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
    
        <NODE label="Calcul -10% SSR">
			<sqlcmd><![CDATA[
				DROP TABLE IF EXISTS w_moins10;
				CREATE TEMP TABLE w_moins10 AS  
				SELECT p_factures_lignes_c.*, 
					p_factures_lignes_c.CTID AS CTID_orig,
					CASE 
						WHEN t_prestations.code = 'PJ' AND
							montant_comptabilise_0=0 AND 
							montant_comptabilise_2=0 AND 
							montant_comptabilise_22=0 AND
							abs(round(((prix_unitaire*nb_prestation*0.9)-montant_comptabilise_1)/nb_prestation,0)) = 18
						THEN 18*nb_prestation 
						WHEN t_prestations.code = 'PJ' AND
							(abs(montant_comptabilise_0)=18 OR abs(montant_comptabilise_2) = 18 OR abs(montant_comptabilise_2) = 36 OR abs(montant_comptabilise_2) = 36)
						THEN montant_comptabilise_0+montant_comptabilise_2
						ELSE 0::numeric END AS montant_fj,
						t_prestations.code AS prestation_code,
						'M'::text || CASE WHEN t_prestations.code <> 'PJ' THEN t_prestations.code ELSE 'PJS' END AS prestation_mcode
				FROM activite[PX].p_factures_lignes_c
				JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
				JOIN activite[PX].t_services_facturation ON t_services_facturation.oid = service_facturation_id
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE date_fin >= '20170701' AND
					date_debut >= '20170701' AND
					type_t2a = '2' AND
					prestation_id = ANY (SELECT to_id FROM activite.t_listes_contenu JOIN activite.t_listes ON liste_id = t_listes.oid AND t_listes.code = 'DMAP_MFS') AND
					montant_comptabilise <> 0 AND
					montant_comptabilise_1 <> 0 AND
					round(prix_unitaire * nb_prestation,2) <> montant_comptabilise AND
					abs(round(prix_unitaire * nb_prestation,2)) <> abs(montant_comptabilise)+(nb_prestation*18)
				ORDER BY no_facture, prestation_id
				;

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

				-- Génération prestations spécifiques 
				INSERT INTO activite.t_prestations (code, texte, texte_court)
				SELECT prestation_mcode, t_prestations.texte || ' (-10%)', t_prestations.texte || ' (-10%)'
				FROM w_moins10
				JOIN activite.t_prestations on prestation_id = t_prestations.oid
				WHERE prestation_mcode NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY 1,2,3
				;
			
				-- Maj tarif plein
				UPDATE activite[PX].p_factures_lignes_c
				SET montant_facture = w_moins10.montant_facture, montant_facture_1 = w_moins10.montant_facture_1
				FROM w_moins10
				WHERE p_factures_lignes_c.CTID = w_moins10.CTID_orig;
				;
				
				-- Génération -10%
				UPDATE w_moins10 SET
					montant_facture = montant_comptabilise - montant_facture,
					montant_facture_1 = montant_comptabilise_1 - montant_facture_1,
					montant_facture_2 = montant_comptabilise_2 - montant_facture_2,
					montant_facture_22 = montant_comptabilise_22 - montant_facture_22,
					montant_facture_0 = montant_comptabilise_0 - montant_facture_0,
					montant_comptabilise = 0,
					montant_comptabilise_1 = 0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_22 = 0,
					montant_comptabilise_0 = 0,
					prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE t_prestations.code = prestation_mcode
				;
			
				ALTER TABLE w_moins10 DROP COLUMN CTID_orig;
				ALTER TABLE w_moins10 DROP COLUMN montant_fj;
				ALTER TABLE w_moins10 DROP COLUMN prestation_code;
				ALTER TABLE w_moins10 DROP COLUMN prestation_mcode;
			
				INSERT INTO activite[PX].p_factures_lignes_c
				SELECT *
				FROM w_moins10
				WHERE montant_facture <> 0
				;
			
			
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite[PX].p_factures_lignes_c');
			]]></sqlcmd>
		</NODE>
	
				
		<NODE label="Mouvements des factures très anciennes">
			<sqlcmd><![CDATA[
			
				UPDATE activite[PX].p_factures SET date_facture = '20991231' WHERE code_facture = '2';
				UPDATE activite[PX].p_factures SET date_facture = date_fin WHERE code_facture = '1' AND date_facture < date_fin;
				
			
				DROP TABLE IF EXISTS w_factures_anciennes;
				CREATE TEMP TABLE w_factures_anciennes AS
				SELECT p_factures.*, lieu_sortie_id 
				FROM activite[PX].p_factures 
				JOIN activite[PX].p_sejours ON sejour_id = p_sejours.oid
				WHERE p_factures.date_vente < '20110101' AND
					(p_factures.montant_comptabilise_c <> 0 OR p_factures.montant_comptabilise_h <> 0) AND 
					p_factures.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_lignes_c WHERE date_fin < '20110101' ) AND 
					p_factures.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_lignes_h WHERE date_fin < '20110101' );


				INSERT INTO activite[PX].p_factures_lignes_c (
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					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
					oid AS facture_id,
					no_facture,
					date_debut,
					date_fin,
					0 AS nb_rubrique,
					0 AS nb_prestation,
					1 AS coefficient,
					1 AS coefficient_mco,
					0 AS rubrique_facturation_id,
					0 AS rubrique_comptabilisation_id,
					0 AS prestation_id,
					montant_facture_c,
					montant_facture_0_c,
					montant_facture_1_c,
					montant_facture_2_c,
					montant_facture_22_c,
					0 AS taux_0,
					0 AS taux_1,
					0 AS taux_2,
					0 AS taux_22,
					montant_facture_c AS prix_unitaire,
					lieu_sortie_id AS lieu_id,
					montant_comptabilise_c,
					montant_comptabilise_0_c,
					montant_comptabilise_1_c,
					montant_comptabilise_2_c,
					montant_comptabilise_22_c,
					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,
					0 AS montant_comptabilise_budget_global_1,
					1 AS origine_facturation_id
				FROM w_factures_anciennes
				WHERE montant_comptabilise_c <> 0;
					
					
				INSERT INTO activite[PX].p_factures_soldes_c (
					facture_id,
					no_facture,
					date_comptable,
					rubrique_comptabilisee_id,
					prestation_id,
					od_avoir,
					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
					oid AS facture_id,
					no_facture,
					date_vente AS date_comptable,
					0 AS rubrique_comptabilisee_id,
					0 AS prestation_id,
					'0' AS od_avoir,
					montant_comptabilise_c,
					montant_comptabilise_0_c,
					montant_comptabilise_1_c,
					montant_comptabilise_2_c,
					montant_comptabilise_22_c,
					0 AS montant_regle,
					0 AS montant_regle_0,
					0 AS montant_regle_1,
					0 AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_factures_anciennes
				WHERE montant_comptabilise_c <> 0;
				
				
				
				INSERT INTO activite[PX].p_factures_lignes_h (
					facture_id,
					no_facture,
					date_debut,
					date_fin,
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					medecin_facture_id,
					medecin_comptabilise_id,
					prestation_id,
					acte_id,	
					activite_ccam,
					extension_ccam,
					phase_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_22,
					montant_depassement,
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					prix_unitaire,
					lieu_id,
					montant_comptabilise,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					montant_facture_actes_inclus_dans_sejour,
					montant_facture_0_actes_inclus_dans_sejour,
					montant_facture_1_actes_inclus_dans_sejour,
					montant_facture_2_actes_inclus_dans_sejour,
					montant_facture_22_actes_inclus_dans_sejour
					)
				SELECT
					oid AS facture_id,
					no_facture,
					date_debut,
					date_fin,
					0 AS nb_rubrique,
					0 AS nb_prestation,
					1 AS coefficient,
					1 AS coefficient_mco,
					0 AS medecin_facture_id,
					0 AS medecin_comptabilise_id,
					0 AS prestation_id,
					0 AS acte_id,	
					'' AS activite_ccam,
					'' AS aextension_ccam,
					'' AS aphase_ccam,
					'' AS amodificateur_ccam_1,
					'' AS amodificateur_ccam_2,
					'' AS amodificateur_ccam_3,
					'' AS amodificateur_ccam_4,
					montant_facture_h,
					montant_facture_0_h,
					montant_facture_1_h,
					montant_facture_2_h,
					montant_facture_22_h,
					0 AS montant_depassement,
					0 AS taux_0,
					0 AS taux_1,
					0 AS taux_2,
					0 AS taux_22,
					montant_facture_h AS prix_unitaire,
					lieu_sortie_id AS lieu_id,
					montant_comptabilise_h,
					montant_comptabilise_0_h,
					montant_comptabilise_1_h,
					montant_comptabilise_2_h,
					montant_comptabilise_22_h,
					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
				FROM w_factures_anciennes
				WHERE montant_comptabilise_h <> 0;


				INSERT INTO activite[PX].p_factures_soldes_h (
					facture_id,
					no_facture,
					date_comptable,
					medecin_comptabilise_id,
					od_avoir,
					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
					oid AS facture_id,
					no_facture,
					date_vente AS date_comptable,
					0 AS medecin_comptabilise_id,
					'0' AS od_avoir,
					montant_comptabilise_h,
					montant_comptabilise_0_h,
					montant_comptabilise_1_h,
					montant_comptabilise_2_h,
					montant_comptabilise_22_h,
					0 AS montant_regle,
					0 AS montant_regle_0,
					0 AS montant_regle_1,
					0 AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_factures_anciennes
				WHERE montant_comptabilise_h <> 0;

				
			]]></sqlcmd>
		</NODE>
		
		<NODE name ="Compléments patients">
			<sqlcmd><![CDATA[
         
				 
				-- Ajout codes postaux inexistants
				INSERT INTO base.t_codes_postaux(code, texte, texte_court)
				SELECT w_ADCODM, w_ADCODM, w_ADCODM
				FROM w_ADP01
				WHERE w_ADCODM NOT IN (SELECT code FROM base.t_codes_postaux) AND w_ADCODM IS NOT NULL AND w_ADCODM <> ''
				GROUP BY 1,2,3
				ORDER BY 1;
				
				-- Maj code postal sur séjours
				UPDATE activite[PX].p_sejours
				SET code_postal_id = t_codes_postaux.oid
				FROM base.t_codes_postaux, w_ADP01
				WHERE w_ADP01.w_ADCODM = t_codes_postaux.code AND
					p_sejours.no_sejour = '[CPX]' || w_ADP01.w_ADDOSS_a AND
					w_ADP01.w_ADCODM IS NOT NULL AND  w_ADP01.w_ADCODM <> '' AND
					p_sejours.code_postal_id = 0;
							  
				--  Maj table OID
				INSERT INTO activite[PX].p_oids (code_table, oid) 
				SELECT 'c_postaux', code_postal_id 
				FROM activite[PX].p_sejours 
				WHERE code_postal_id NOT IN (SELECT oid FROM activite[PX].p_oids WHERE code_table = 'c_postaux')
				GROUP BY 2;

				-- 	Ajout médecins traitants dans ACTIVITE (Ajouter dans BASE)
				INSERT INTO activite[PX].t_medecins_traitants_administratifs(code_original, code, nom, prenom, specialite_id, no_rpps)
				SELECT DISTINCT w_ADP01.w_ADMEDT, w_ADP01.w_ADMEDT, w_ADP01.w_ADMEDT, '', 0, ''
				FROM w_ADP01
				WHERE w_ADMEDT NOT IN (SELECT code FROM activite[PX].t_medecins_traitants_administratifs);
				
							
				--  maj code rpps
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET no_rpps = MDRPPS
				FROM prod_shs.[ACTIVITESCHEMA]_MDP03 
				WHERE MDPRAT = t_medecins_traitants_administratifs.code
					AND (t_medecins_traitants_administratifs.no_rpps IS NULL OR t_medecins_traitants_administratifs.no_rpps = '' OR t_medecins_traitants_administratifs.no_rpps <> MDRPPS
					AND MDRPPS IS not NULL AND MDRPPS <> 0 );

			
				--  maj nom prenom spe medecin de référence
				UPDATE activite[PX].t_medecins_traitants_administratifs
				SET nom = MDNOMS,
					prenom = MDPRES,
					specialite_id = COALESCE(t_specialites_medecin.oid,0)
				FROM prod_shs.[ACTIVITESCHEMA]_MDP03
					JOIN prod_shs.[ACTIVITESCHEMA]_MDP01 ON [ACTIVITESCHEMA]_MDP03.MDPRAT = [ACTIVITESCHEMA]_MDP01.MDPRAT
					LEFT JOIN base.t_specialites_medecin ON (MDCSPE = t_specialites_medecin.code_original)
				WHERE [ACTIVITESCHEMA]_MDP03.MDPRAT = t_medecins_traitants_administratifs.code_original
					AND (
					t_medecins_traitants_administratifs.nom <> MDNOMS OR
					t_medecins_traitants_administratifs.prenom <> MDPRES OR
					t_medecins_traitants_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,0)
				);
					
				-- maj id médecin_traitant dans séjours
							
				UPDATE activite[PX].p_sejours
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM w_ADP01
				JOIN activite[PX].t_medecins_traitants_administratifs ON w_ADP01.w_ADMEDT = t_medecins_traitants_administratifs.code 
				WHERE w_ADP01.w_ADDOSS_a = p_sejours.no_sejour AND
					w_ADP01.w_ADMEDT IS NOT NULL AND 
					w_ADP01.w_ADMEDT <> '0000' AND
					medecin_traitant_id IS DISTINCT FROM t_medecins_traitants_administratifs.oid
				;
								


                -- ajout des coordonnees par sejour

                DROP TABLE IF EXISTS w_ADP09
                ;

                CREATE TEMP TABLE w_ADP09 AS 
                    SELECT * FROM ( 
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]h_ADP09H
                            UNION 
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]p_ADP09p 
                            UNION
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]_ADP09 
                    ) subq
                    GROUP BY 1,2,3
                ;

				-- ajout des coordonnees par sejour

                DROP TABLE IF EXISTS w_ADP09
                ;

                CREATE TEMP TABLE w_ADP09 AS 
                    SELECT * FROM ( 
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]h_ADP09H
                            UNION 
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]p_ADP09p 
                            UNION
                        SELECT * FROM prod_shs.[ACTIVITESCHEMA]_ADP09 
                    ) subq
                    GROUP BY 1,2,3
                ;

                -- ajout des coordonnees par sejour
                INSERT INTO activite[PX].p_coordonnees_patient (
                    sejour_id,
                    adresse,
                    code_postal_id,
					commune,
                    telephone_fixe,
                    telephone_portable,
                    email 
                )
                SELECT
                    p_sejours.oid,
                    MAX(w_ADAD1M || CASE WHEN w_ADAD2M != '' THEN ' - ' || w_ADAD2M ELSE '' END),
                    MAX(COALESCE(t_codes_postaux.oid,0)),
                    MAX(w_ADVILM),
                    MAX(w_ADTELM),
                    MAX(ADPORM),
                    MAX(ADMAIL)
                FROM w_ADP01
                    LEFT JOIN w_ADP09 ON w_ADDOSS = ADDOSS
                    LEFT JOIN base.t_codes_postaux ON w_ADCODM = t_codes_postaux.code
                    JOIN activite[PX].p_sejours ON code_original = w_ADDOSSDCPL
                GROUP BY 1
                ;
			]]></sqlcmd>
		</NODE>
		
		<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';
				
				-- Montants facturés pour calculées non passées en fin de journée
				UPDATE activite[PX].p_factures SET
					montant_facture_c = subview.montant_facture_c,
					montant_facture_0_c = subview.montant_facture_0_c,
					montant_facture_1_c = subview.montant_facture_1_c,
					montant_facture_2_c = subview.montant_facture_2_c,
					montant_facture_22_c = subview.montant_facture_22_c
				FROM
				(
				SELECT p_factures.no_facture,  
					SUM(p_factures_lignes_c.montant_facture) AS montant_facture_c,  
					SUM(p_factures_lignes_c.montant_facture_0) AS montant_facture_0_c,  
					SUM(p_factures_lignes_c.montant_facture_1) AS montant_facture_1_c,  
					SUM(p_factures_lignes_c.montant_facture_2) AS montant_facture_2_c,  
					SUM(p_factures_lignes_c.montant_facture_22) AS montant_facture_22_c
				from activite[PX].p_factures
				join activite[PX].p_factures_lignes_c on p_factures.no_facture = p_factures_lignes_c.no_facture
				WHERE p_factures.code_facture = '2'
				GROUP BY 1
				) subview
				WHERE p_factures.no_facture = subview.no_facture AND
					(
					p_factures.montant_facture_c IS DISTINCT FROM subview.montant_facture_c OR
					p_factures.montant_facture_0_c IS DISTINCT FROM subview.montant_facture_0_c OR
					p_factures.montant_facture_1_c IS DISTINCT FROM subview.montant_facture_1_c OR
					p_factures.montant_facture_2_c IS DISTINCT FROM subview.montant_facture_2_c OR
					p_factures.montant_facture_22_c IS DISTINCT FROM subview.montant_facture_22_c
					);

				UPDATE activite[PX].p_factures SET
					montant_facture_h = subview.montant_facture_h,
					montant_facture_0_h = subview.montant_facture_0_h,
					montant_facture_1_h = subview.montant_facture_1_h,
					montant_facture_2_h = subview.montant_facture_2_h,
					montant_facture_22_h = subview.montant_facture_22_h
				FROM
				(
				SELECT p_factures.no_facture,  
					SUM(p_factures_lignes_h.montant_facture) AS montant_facture_h,  
					SUM(p_factures_lignes_h.montant_facture_0) AS montant_facture_0_h,  
					SUM(p_factures_lignes_h.montant_facture_1) AS montant_facture_1_h,  
					SUM(p_factures_lignes_h.montant_facture_2) AS montant_facture_2_h,  
					SUM(p_factures_lignes_h.montant_facture_22) AS montant_facture_22_h
				from activite[PX].p_factures
				join activite[PX].p_factures_lignes_h on p_factures.no_facture = p_factures_lignes_h.no_facture
				WHERE p_factures.code_facture = '2'
				GROUP BY 1
				) subview
				WHERE p_factures.no_facture = subview.no_facture AND
					(
					p_factures.montant_facture_h IS DISTINCT FROM subview.montant_facture_h OR
					p_factures.montant_facture_0_h IS DISTINCT FROM subview.montant_facture_0_h OR
					p_factures.montant_facture_1_h IS DISTINCT FROM subview.montant_facture_1_h OR
					p_factures.montant_facture_2_h IS DISTINCT FROM subview.montant_facture_2_h OR
					p_factures.montant_facture_22_h IS DISTINCT FROM subview.montant_facture_22_h
					);
				

				
			]]></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,  
					
					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
				
				FROM activite[PX].p_sejours LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture <> 'P'
				GROUP BY p_sejours.no_sejour;

				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 = CASE WHEN w_sejours_total.date_expedition_0 <> '0001-01-01' THEN w_sejours_total.date_expedition_0 ELSE '2099-12-31' END,  
					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 = CASE WHEN w_sejours_total.date_expedition_1 <> '0001-01-01' THEN w_sejours_total.date_expedition_1 ELSE '2099-12-31' END,   
					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 = CASE WHEN w_sejours_total.date_expedition_2 <> '0001-01-01' THEN w_sejours_total.date_expedition_2 ELSE '2099-12-31' END, 
					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 = CASE WHEN w_sejours_total.date_expedition_22 <> '0001-01-01' THEN w_sejours_total.date_expedition_22 ELSE '2099-12-31' END, 
					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
					
				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 CASE WHEN w_sejours_total.date_expedition_0 <> '0001-01-01' THEN w_sejours_total.date_expedition_0 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_1 <> '0001-01-01' THEN w_sejours_total.date_expedition_1 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_2 <> '0001-01-01' THEN w_sejours_total.date_expedition_2 ELSE '2099-12-31' END 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 CASE WHEN w_sejours_total.date_expedition_22 <> '0001-01-01' THEN w_sejours_total.date_expedition_22 ELSE '2099-12-31' END 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

				);
				
				
				UPDATE activite[PX].p_sejours 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
				
				WHERE
					
					delai_groupage IS DISTINCT FROM 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 
						OR
					delai_facture IS DISTINCT FROM 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
						OR
					delai_expedition IS DISTINCT FROM 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
						OR
					delai_solde IS DISTINCT FROM 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
						OR

					delai_expedition_0 IS DISTINCT FROM 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
						OR
					delai_solde_0 IS DISTINCT FROM 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
						OR

					delai_expedition_1 IS DISTINCT FROM 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
						OR
					delai_solde_1 IS DISTINCT FROM 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
						OR

					delai_expedition_2 IS DISTINCT FROM 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
						OR
					delai_solde_2 IS DISTINCT FROM 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
						OR

					delai_expedition_22 IS DISTINCT FROM 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
						OR
					delai_solde_22 IS DISTINCT FROM 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;
														
					-- SHS a la possibilité de fusionner des patients en double
					-- Le lien se fait au travers du nom du patient dans lequel on retrouver la référence vers le "nouveau" patient / patient "maitre"
					WITH lien_fusion_patient AS (
						SELECT p_sejours.no_sejour, ltrim(trim(split_part(p_patients.nom, 'VOIR IDENTITE', 2)), 0) as new_no_patient
						FROM activite[PX].p_sejours
						JOIN activite[PX].p_patients ON p_patients.no_patient = p_sejours.no_patient
						WHERE p_patients.nom ilike '%VOIR IDENTITE%'
					)
					UPDATE activite[PX].p_sejours
					SET no_patient = lien_fusion_patient.new_no_patient
					FROM lien_fusion_patient
					WHERE 1=1
						AND p_sejours.no_sejour = lien_fusion_patient.no_sejour
						AND p_sejours.no_patient IS DISTINCT FROM lien_fusion_patient.new_no_patient
					;					
			]]></sqlcmd>
		</NODE>
		
        <NODE name ="Compléments mouvements">
			<sqlcmd><![CDATA[
				-- unite_fonctionnelle = service
				INSERT INTO activite[PX].t_unites_fonctionnelles (oid, code, code_original, texte, texte_court)
                SELECT oid, code, code_original, texte, texte_court
                FROM activite[PX].t_services_facturation
                WHERE oid <> 0 AND
                    oid NOT IN (SELECT oid FROM activite[PX].t_unites_fonctionnelles);
                ;
                UPDATE activite[PX].t_lieux
                SET unite_fonctionnelle_id = service_facturation_id
				;
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Tables répliquées">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>
			
			<sqlcmd><![CDATA[

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

	
</ROOT>
