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


	<NODE name="INIT" label="INITIALISATIONS">
		<NODE label="Ajout table optionnelles manquantes">
			<condition><![CDATA[
				SELECT count(*) != 6 FROM information_schema.tables WHERE table_schema = 'prod_web100t' AND table_name IN ('correspondants','mws_nmcl_correspondant','cpt_journal','def_etat_facture','noe_paiement','noe_pai_fact')
			]]></condition>
			<sqlcmd><![CDATA[
			
				CREATE TABLE IF NOT EXISTS prod_web100t.correspondants
				(
				  cor_id double precision,
				  cor_qualite double precision,
				  cor_adresse double precision,
				  cor_nom character varying(30),
				  cor_prenom character varying(30),
				  cor_profession double precision,
				  cor_specialite double precision,
				  cor_creation timestamp without time zone,
				  cor_modification timestamp without time zone,
				  cor_adeli character varying(15),
				  cor_notes character varying(1024),
				  cor_code character varying(15),
				  cor_rpps character varying(20)
				)
				WITH (
				  OIDS=FALSE
				)
				;
				
				CREATE TABLE IF NOT EXISTS prod_web100t.mws_nmcl_correspondant
				(
				  nd_code character varying(15),
				  oid double precision,
				  fld_coderpps character varying(20),
				  fld_nom character varying(30),
				  fld_prenom character varying(30),
				  fld_specialite double precision,
				  fld_codeadeli character varying(15)
				)
				WITH (
				  OIDS=FALSE
				);

				CREATE TABLE IF NOT EXISTS prod_web100t.cpt_journal
				(
				  jour_oid double precision,
				  jour_type character varying(5),
				  jour_ef double precision,
				  jour_plan double precision,
				  jour_calc_count double precision,
				  jour_err_count double precision,
				  jour_debut timestamp without time zone,
				  jour_fin timestamp without time zone,
				  jour_state double precision,
				  jour_closed_date timestamp without time zone,
				  jour_closer double precision,
				  jour_created timestamp without time zone,
				  jour_creator double precision,
				  jour_export double precision,
				  jour_lib character varying(100)
				)
				WITH (
				  OIDS=FALSE
				);
				
				
				CREATE TABLE IF NOT EXISTS prod_web100t.def_etat_facture
				(
				  ef_oid double precision,
				  ef_lib character varying(100)
				)
				WITH (
				  OIDS=FALSE
				)
				;
				
							
				CREATE TABLE IF NOT EXISTS prod_web100t.noe_paiement
				(
				  np_oid double precision,
				  np_entite double precision,
				  np_paiement_ets double precision,
				  np_num_org character varying(15),
				  np_num_destinataire character varying(15),
				  np_intervenant double precision,
				  np_ef double precision,
				  np_date_comptable timestamp without time zone,
				  np_total double precision,
				  np_montant_amo double precision,
				  np_montant_amc double precision,
				  np_acompte double precision,
				  np_mvt_financier double precision,
				  np_nbre_facture double precision,
				  np_reglement double precision,
				  np_ttt_auto double precision,
				  np_date_ttt timestamp without time zone,
				  np_user_ttt double precision,
				  np_action_ttt double precision,
				  np_to_update numeric(1,0),
				  np_plan_cpta double precision,
				  np_date_plan timestamp without time zone,
				  np_comments character varying(1024),
				  np_type_tier character varying(3),
				  np_ref_paiement character varying(100),
				  np_from_fse numeric(1,0)
				)
				WITH (
				  OIDS=FALSE
				)
				;
				

				CREATE TABLE IF NOT EXISTS prod_web100t.noe_pai_fact
				(
				  npf_oid double precision,
				  npf_paiement double precision,
				  npf_no_fact character varying(15),
				  npf_no_lot double precision,
				  npf_date_lot timestamp without time zone,
				  npf_facture double precision,
				  npf_fact_root double precision,
				  npf_fact_updated timestamp without time zone,
				  npf_fact_tier double precision,
				  npf_fact_amc double precision,
				  npf_lot double precision,
				  npf_ttt_auto double precision,
				  npf_total double precision,
				  npf_total_amo double precision,
				  npf_total_amc double precision,
				  npf_total_acompte double precision,
				  npf_total_mvt double precision,
				  npf_total_prest double precision,
				  npf_total_autre_amo double precision,
				  npf_total_autre_amc double precision,
				  npf_diff_amo double precision,
				  npf_diff_amc double precision,
				  npf_comments character varying(1024),
				  npf_rappel_tarif numeric(1,0),
				  npf_code_lot character varying(10),
				  npf_fse double precision
				)
				WITH (
				  OIDS=FALSE
				)
				;
			]]></sqlcmd>
		</NODE>

		<NODE label="Corrections des tables WEB100T">
			<sqlcmd><![CDATA[
			
				-- UF GEO selon LIT
				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				SET MVT_UF_GEO = CHA_UF
				FROM prod_web100t.LITS 
					JOIN prod_web100t.CHAMBRES ON CHA_OID = LIT_CHAMBRE
					JOIN activite.t_divers ON t_divers.code = 'WEB100T_ETAGE' AND t_divers.valeur <> '1'
				WHERE MVT_TYPE IN (1,4) AND
					LIT_OID <> 0 AND
					LIT_OID = MVT_LIT AND
					CHA_UF <> MVT_UF_GEO;
														
				-- Unité de soin non renseignée -> attribution de l'unité géo
				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				SET MVT_UF_SOIN = MVT_UF_GEO
				WHERE MVT_UF_SOIN = 0 AND MVT_UF_GEO <> 0 AND MVT_TYPE IN (1,4);
				
				-- Unité geo non renseignée -> attribution de l'unité de soin
				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				SET MVT_UF_GEO = MVT_UF_SOIN
				WHERE MVT_UF_SOIN <> 0 AND MVT_UF_GEO = 0 AND MVT_TYPE IN (1,4);
			
				-- Pointage de mouvements en double
				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_double;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_double AS
				SELECT MVT_SEJ_OID, MVT_DATE, 
					(MAX(ARRAY[MVT_INDEX,MVT_RESP]))[2] AS MVT_RESP, 
					(MAX(ARRAY[MVT_INDEX,MVT_UF_SOIN]))[2] AS MVT_UF_SOIN, 
					(MAX(ARRAY[MVT_INDEX,MVT_UF_GEO]))[2] AS MVT_UF_GEO, 
					(MAX(ARRAY[MVT_INDEX,MVT_CHAMBRE]))[2] AS MVT_CHAMBRE, 
					(MAX(ARRAY[MVT_INDEX,MVT_LIT]))[2] AS MVT_LIT, 
					MIN(MVT_OID) AS MVT_OID
				FROM w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				WHERE MVT_TYPE IN (1,4)
				GROUP BY 1,2
				HAVING count(*) > 1;

				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS SET
					MVT_RESP = w_REGUL_MOUVEMENTS_double.MVT_RESP,
					MVT_UF_SOIN = w_REGUL_MOUVEMENTS_double.MVT_UF_SOIN,
					MVT_UF_GEO = w_REGUL_MOUVEMENTS_double.MVT_UF_GEO,
					MVT_CHAMBRE = w_REGUL_MOUVEMENTS_double.MVT_CHAMBRE,
					MVT_LIT = w_REGUL_MOUVEMENTS_double.MVT_LIT 
				FROM w_REGUL_MOUVEMENTS_double
				WHERE REGUL_MOUVEMENTS.MVT_SEJ_OID = w_REGUL_MOUVEMENTS_double.MVT_SEJ_OID AND
					REGUL_MOUVEMENTS.MVT_DATE = w_REGUL_MOUVEMENTS_double.MVT_DATE AND
					REGUL_MOUVEMENTS.MVT_OID = w_REGUL_MOUVEMENTS_double.MVT_OID AND
					REGUL_MOUVEMENTS.MVT_TYPE IN (1,4);

				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS SET
					MVT_TYPE = 49
				FROM w_REGUL_MOUVEMENTS_double
				WHERE REGUL_MOUVEMENTS.MVT_SEJ_OID = w_REGUL_MOUVEMENTS_double.MVT_SEJ_OID AND
					REGUL_MOUVEMENTS.MVT_DATE = w_REGUL_MOUVEMENTS_double.MVT_DATE AND
					REGUL_MOUVEMENTS.MVT_OID <> w_REGUL_MOUVEMENTS_double.MVT_OID AND
					REGUL_MOUVEMENTS.MVT_TYPE IN (1,4);
					
				-- UF selon mode de calcul PMSI (Cas des retrocessions,FSD,FFM)
				DROP TABLE IF EXISTS w_DIM_MODE_FACT_default
				;
				CREATE TEMP TABLE w_DIM_MODE_FACT_default AS
				SELECT DA_DIM_MODE_FACT,
					MAX(NMCL_UNITEFONCTIONNELLE.OID::bigint) AS UF_OID, 
					count(*)
				FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
				JOIN w_SGN_NMCL_DATA ON ND_INVARIANT_OID = OID
				JOIN prod_web100t.DAT_DA ON
					DA_DIM_MODE_FACT IN ('FSE','FSD','FFM','RETRO') AND
					DA_DIM_MODE_FACT = ND_CODE
				WHERE NMCL_IDENT = 'UNITEFONCTIONNELLE' 
				GROUP BY 1
				;
				
				ANALYSE w_DIM_MODE_FACT_default
				;

				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				SET MVT_UF_SOIN = UF_OID
				FROM prod_web100t.DAT_SEJOUR
				JOIN prod_web100t.DAT_DA ON SEJ_DA = DA_OID
				JOIN w_DIM_MODE_FACT_default ON w_DIM_MODE_FACT_default.DA_DIM_MODE_FACT = DAT_DA.DA_DIM_MODE_FACT
					WHERE PHASE_OID = MVT_SEJ_OID AND
					MVT_TYPE IN (1,2,4) AND
					MVT_UF_SOIN = 0
				;                
                
				UPDATE w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				SET MVT_UF_SOIN = UF_OID
				FROM prod_web100t.DAT_SEJOUR
				JOIN prod_web100t.DAT_DA ON SEJ_DA = DA_OID
				JOIN w_DIM_MODE_FACT_default ON w_DIM_MODE_FACT_default.DA_DIM_MODE_FACT = DAT_DA.DA_SUGG_MODE_FACT
					WHERE PHASE_OID = MVT_SEJ_OID AND
					MVT_TYPE IN (1,2,4) AND
					MVT_UF_SOIN = 0
				; 
				
                -- Statut séjour présent alors que facturé depuis plus de 6 mois
                UPDATE prod_web100T.DAT_DA
                SET DA_STATUT = '3'
                WHERE DA_DATE_FIN <= now() - interval '2 month' AND
                    DA_DATE_FIN >= DA_DATE_DEBUT AND
                    DA_STATUT = 2 AND
                    DA_DIM_VALID <= now() - interval '2 month' AND
                    DA_OID = ANY (ARRAY(SELECT DISTINCT FACT_DA FROM prod_web100T.FAC_FACTURE WHERE FACT_DATE <= now() - interval '2 month')::double precision[])
                ;
				
				-- Sejour ambulatoire présent à convertir en sorti
				UPDATE PROD_WEB100T.DAT_DA SET
					DA_STATUT = CASE WHEN DA_STATUT < 3 THEN 3 ELSE DA_STATUT END,
					DA_DATE_FIN = DA_DATE_DEBUT,
					DA_HEURE_FIN = LEAST(DA_HEURE_DEBUT + 0.2,0.9)
				WHERE 
					DA_STATUT >= 2 AND
					DA_CLASSE IN (2,3) AND
					DA_DATE_FIN IS NULL
				;
				
				-- Forcage code prestation
				UPDATE prod_web100t.FAC_FACT_LIGNE_TIER SET
					FLT_CODE_PREST = t_prestations.code
				FROM activite[PX].t_rubriques_facturation
				JOIN activite.t_prestations ON prestation_forcee_id = t_prestations.oid AND prestation_forcee_id <> 0
				WHERE FLT_ARTICLE::text = t_rubriques_facturation.code_original
				;
                
                
                -- Placer l'heure dans les lignes d'actes 
				-- Parametre car trop long sur certains sites (CCN)
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'WEB100T_INITHEUREACTE',
					'Recuperation heures des actes',
					'1',
					'1=Les heures des actes son recuperees'
				WHERE 'WEB100T_INITHEUREACTE' NOT IN (SELECT code FROM activite.t_divers);
				;

				-- en attendant de trouver la bonnjointure
				DROP TABLE IF EXISTS w_heures_actes;
				CREATE TEMP TABLE w_heures_actes AS
				SELECT PREST_DA, 
					PREST_ARTICLE, 
					ART_CODE,
					PREST_EXECUTANT, 
					DATE(PREST_DATE_DEBUT) AS PREST_DATE,
					MAX(PREST_DATE_DEBUT-date(PREST_DATE_DEBUT)) AS PREST_HEURE,
					count(DISTINCT date_part('hour',PREST_DATE_DEBUT)) AS nb_heure
				FROM prod_web100t.DAT_PRESTATIONS_GAP
				JOIN activite.t_divers ON t_divers.code = 'WEB100T_INITHEUREACTE'
				JOIN prod_web100t.ART_ARTICLES ON PREST_ARTICLE = ART_OID
				WHERE 
					t_divers.valeur = '1' AND
					PREST_DELETED <> 1 AND
					PREST_EXECUTANT > 0 AND
					PREST_DATE_DEBUT <> date(PREST_DATE_DEBUT)
                GROUP BY 1,2,3,4,5
				;
				
				ANALYSE w_heures_actes
				;
				
				UPDATE prod_web100t.FAC_FACT_LIGNE_TIER 
				SET FLT_DATE_DEBUT = date_trunc('day',FLT_DATE_DEBUT) + PREST_HEURE
				FROM prod_web100t.FAC_FACTURE,
					w_heures_actes
				WHERE FLT_FACTURE = FAC_FACTURE.FACT_OID AND
					FACT_DA = PREST_DA AND
					FLT_ARTICLE = PREST_ARTICLE AND
					date(FLT_DATE_DEBUT) = PREST_DATE AND
					FLT_INTERVENANT = PREST_EXECUTANT
				;
				
				-- Date de règlement selon ecritures comptable
				UPDATE prod_web100t.FAC_REGLEMENTS
				SET FR_DATE_ENC = ECR_DATE
				FROM prod_web100t.FAC_RGLMT_DETAILS
				JOIN w_CPT_ECRITURE_source ON RD_COMPTA = ECR_OPERATION
				WHERE FR_OID = RD_REGLEMENT AND
					FR_DATE_ENC IS NULL AND
					FR_DATE_DEPOT_GUESS IS NOT NULL AND
					ECR_REF_TYPE = 'FACTURE' AND
					ECR_TYPE = 'CLIENT'
				;
				
				DROP TABLE IF EXISTS w_max_ECR_UPDATED;
				CREATE TEMP TABLE w_max_ECR_UPDATED AS
				SELECT MAX(ECR_UPDATED) AS ECR_UPDATED_MAX FROM w_CPT_ECRITURE_source
				;
				
				DROP TABLE IF EXISTS w_CPT_ECRITURE_source;
				
				-- Pour identification de la deuxième mutuelle
				UPDATE prod_web100t.FAC_FACT_TIER
				SET FT_TYPE_TIER = 'AMD'
				FROM
				(
				SELECT FT_FACTURE, 
					(MIN(ARRAY[abs(ft_total_ets+ft_total_ho),FT_ORGANISME]))[2]::numeric AS FT_ORGANISME_AMD
				FROM prod_web100t.FAC_FACT_TIER
				WHERE FT_TYPE_TIER = 'AMC'
				GROUP BY 1
				HAVING count(DISTINCT FT_ORGANISME) > 1
				) subview
				WHERE FAC_FACT_TIER.FT_FACTURE = subview.FT_FACTURE AND
					FAC_FACT_TIER.FT_ORGANISME = subview.FT_ORGANISME_AMD
				;
				
				-- Identification des honoraires directs selon compta
				DROP TABLE IF EXISTS w_FAC_RGLMT_DETAILS_FACT_LINE;
				CREATE TEMP TABLE w_FAC_RGLMT_DETAILS_FACT_LINE AS
				SELECT RD_FACT_LINE
				FROM prod_web100t.FAC_RGLMT_DETAILS
				WHERE RD_ETS = 0
				GROUP BY 1
				;

				ANALYSE w_FAC_RGLMT_DETAILS_FACT_LINE
				;

				DROP TABLE IF EXISTS w_FAC_FACT_LIGNE_TIER;
				CREATE TEMP TABLE w_FAC_FACT_LIGNE_TIER AS
				SELECT *,
					CASE WHEN FLT_IS_DIRECT <> 1 THEN FLT_TOTAL_TTC ELSE 0 END AS FLT_TOTAL_TTC_comptable,
					CASE WHEN RD_FACT_LINE IS NULL THEN '0' ELSE '1' END AS QRGMT
				FROM prod_web100t.FAC_FACT_LIGNE_TIER
				JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
				JOIN prod_web100t.FAC_FACTURE ON FLT_FACTURE = FACT_OID 
				LEFT JOIN w_FAC_RGLMT_DETAILS_FACT_LINE ON RD_FACT_LINE = FLT_OID
				WHERE FLT_IS_ETS = 0 AND
					(
					SELECT count(*)
					FROM w_CPT_ECRITURE_source_OP_LINK
					JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
					WHERE ECR_IS_ETS = 0 AND
						LNK_JOURNAL = 'VE' AND
						(CPT_CODE LIKE '411%' OR CPT_CODE LIKE '412%')
					) > 0
				;

				ANALYSE w_FAC_FACT_LIGNE_TIER
				;
				
				-- Ajout colonne si absente de prod_web100t
				SELECT base.cti_execute('ALTER TABLE w_FAC_FACT_LIGNE_TIER ADD COLUMN FLT_PRED_LIGNE bigint',1)
					WHERE 'flt_pred_ligne' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'w_fac_fact_ligne_tier')
				;


				-- reporter indicateur vente directe dans avoir depuis facture initiale
				UPDATE w_FAC_FACT_LIGNE_TIER FAC_FACT_LIGNE_TIER SET
					FLT_IS_DIRECT = FAC_FACT_LIGNE_TIER2.FLT_IS_DIRECT,
					FLT_TOTAL_TTC_comptable = CASE WHEN FAC_FACT_LIGNE_TIER2.FLT_IS_DIRECT <> 1 THEN FAC_FACT_LIGNE_TIER.FLT_TOTAL_TTC ELSE 0 END
				FROM w_FAC_FACT_LIGNE_TIER FAC_FACT_LIGNE_TIER2
				WHERE FAC_FACT_LIGNE_TIER.FLT_PRED_LIGNE = FAC_FACT_LIGNE_TIER2.FLT_OID AND
					FAC_FACT_LIGNE_TIER.FLT_TOTAL_TTC < 0 AND
					FAC_FACT_LIGNE_TIER.FLT_IS_ETS = 0 AND
					FAC_FACT_LIGNE_TIER.FLT_IS_DIRECT <> FAC_FACT_LIGNE_TIER2.FLT_IS_DIRECT
				;


				-- Honoraires directs comptabilisés ?
				DROP TABLE IF EXISTS w_ECR_vente_hon;
				CREATE TEMP TABLE w_ECR_vente_hon AS
				SELECT FT_OID, FACT_NUMERO, MAX(FT_TOTAL_HO) AS FT_TOTAL_HO
					
				FROM w_CPT_ECRITURE_source_OP_LINK
				JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
				JOIN prod_web100t.FAC_FACT_TIER ON ECR_REF_FTIERS = FT_OID
				JOIN prod_web100t.FAC_FACTURE ON FT_FACTURE = FACT_OID
				WHERE ECR_IS_ETS = 0 AND
					LNK_JOURNAL = 'VE' AND
					(CPT_CODE LIKE '411%' OR CPT_CODE LIKE '412%')
				GROUP BY 1,2
				HAVING MAX(FT_TOTAL_HO) = SUM(ECR_DEBIT-ECR_CREDIT)
				;
				
				UPDATE w_FAC_FACT_LIGNE_TIER FAC_FACT_LIGNE_TIER
				SET FLT_IS_DIRECT = 
					CASE 
						WHEN FLT_FACTURE IN (
							SELECT ECR_REF_FACT
							FROM w_CPT_ECRITURE_source_OP_LINK
							WHERE ECR_TYPE = 'VENTE-DIRECTE'
							) THEN -1 
						WHEN QRGMT = '0' THEN -1 
						ELSE 0 END, 
					FLT_TOTAL_TTC_comptable = FLT_TOTAL_TTC
				WHERE FLT_FACTURE_TIER = 
					ANY(
					SELECT w_ECR_vente_hon.FT_OID
					FROm w_ECR_vente_hon 
					LEFT JOIN w_FAC_FACT_LIGNE_TIER  ON
						FLT_FACTURE_TIER = w_ECR_vente_hon.FT_OID AND
						FLT_IS_ETS = 0
					GROUP BY 1
					HAVING  round(MAX(w_ECR_vente_hon.FT_TOTAL_HO)::numeric,2) = round(SUM(FLT_TOTAL_TTC)::numeric,2)
					) AND
					FLT_IS_DIRECT = 1
				;



				DROP TABLE IF EXISTS w_FLT_INTERVENANT;
				CREATE TEMP TABLE w_FLT_INTERVENANT AS
				WITH vente_directe AS (
					SELECT ECR_REF_FACT
					FROM w_CPT_ECRITURE_source_OP_LINK
					WHERE ECR_TYPE = 'VENTE-DIRECTE'
				),
				journal_vente AS (
					SELECT ECR_REF_FACT
					FROM w_CPT_ECRITURE_source_OP_LINK
					WHERE LNK_JOURNAL = 'VE'
				)
				SELECT FLT_FACTURE,
					FACT_NUMERO,
					FT_TYPE_TIER,
					FLT_INTERVENANT,
					round(SUM(FLT_TOTAL_TTC)::numeric,2) AS FLT_TOTAL_TTC,
					round(SUM(FLT_TOTAL_TTC_comptable)::numeric,2) AS FLT_TOTAL_TTC_comptable
				FROM w_FAC_FACT_LIGNE_TIER FAC_FACT_LIGNE_TIER
				LEFT JOIN vente_directe ON vente_directe.ECR_REF_FACT = FLT_FACTURE
				LEFT JOIN journal_vente ON journal_vente.ECR_REF_FACT = FLT_FACTURE
				WHERE FLT_IS_ETS = 0 AND
					FLT_IS_DIRECT >= 0 AND
					(
					journal_vente.ECR_REF_FACT IS NOT NULL
					OR date(FACT_DATE) <= (SELECT date(MAX(ECR_DATE)) FROM w_CPT_ECRITURE_source_OP_LINK WHERE ECR_LOCKED = 1) 
					) 
					AND vente_directe.ECR_REF_FACT IS NULL
					GROUP BY 1,2,3,4
				;
				
				ANALYSE w_FLT_INTERVENANT
				;

				DROP TABLE IF EXISTS w_ECR_INTERVENANT;
				CREATE TEMP TABLE w_ECR_INTERVENANT AS
				SELECT ECR_REF_FACT, 
					FACT_NUMERO,
					CASE 
						WHEN ECR_DETAILS LIKE '%AMO%' THEN 'AMO'::text
						WHEN ECR_DETAILS LIKE '%AMC%' THEN 'AMC'::text
						WHEN ECR_DETAILS LIKE '%CLI%' THEN 'CLI'::text
						WHEN ECR_DETAILS LIKE '%Part client%' THEN 'CLI'::text
						ELSE '???' END AS ECR_TYPE_TIER,
					CASE WHEN CPT_REF_TYPE = 'PRATICIEN' THEN CPT_REF ELSE -1 END AS CPT_REF,
					round(SUM(ECR_CREDIT-ECR_DEBIT)::numeric,2) AS ECR_MONTANT
				FROM w_CPT_ECRITURE_source_OP_LINK
				JOIN prod_web100t.FAC_FACTURE ON ECR_REF_FACT = FACT_OID 
				JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
				WHERE ECR_IS_ETS = 0 AND
					LNK_JOURNAL = 'VE' AND
					(CPT_REF_TYPE = 'PRATICIEN' OR CPT_CODE LIKE '466%' OR CPT_CODE LIKE '4781%' OR (CPT_REF_TYPE = '' AND CPT_CODE IN (
						SELECT CPT_CODE 
						FROM w_CPT_ECRITURE_source_OP_LINK
							JOIN prod_web100t.FAC_FACTURE ON ECR_REF_FACT = FACT_OID 
							JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
							WHERE ECR_IS_ETS = 0 AND LNK_JOURNAL = 'VE' AND CPT_REF_TYPE != ''
							GROUP BY 1
							HAVING COUNT(DISTINCT CPT_REF_TYPE) = 1
								AND MIN(CPT_REF_TYPE) = 'PRATICIEN'
								)))
				GROUP BY 1,2,3,4
				;
				
				ANALYSE w_ECR_INTERVENANT
				;
				
				DROP TABLE IF EXISTS w_FLT_INTERVENANT_compta;
				CREATE TEMP TABLE w_FLT_INTERVENANT_compta AS
				SELECT FLT_FACTURE, FT_TYPE_TIER, FLT_INTERVENANT
				FROM w_FLT_INTERVENANT
				LEFT JOIN w_ECR_INTERVENANT ON 
					FLT_FACTURE = ECR_REF_FACT AND
					FT_TYPE_TIER = ECR_TYPE_TIER AND
					FLT_INTERVENANT = CPT_REF
				WHERE FLT_TOTAL_TTC_comptable <> COALESCE(ECR_MONTANT,0) AND
					FLT_TOTAL_TTC = COALESCE(ECR_MONTANT,0)
				GROUP BY 1,2,3
				;

				ANALYSE w_FLT_INTERVENANT_compta
				;

				UPDATE w_FAC_FACT_LIGNE_TIER SET
					FLT_TOTAL_TTC_comptable = FLT_TOTAL_TTC
				FROM w_FLT_INTERVENANT_compta
				WHERE w_FAC_FACT_LIGNE_TIER.FLT_FACTURE = w_FLT_INTERVENANT_compta.FLT_FACTURE AND
					w_FAC_FACT_LIGNE_TIER.FT_TYPE_TIER = w_FLT_INTERVENANT_compta.FT_TYPE_TIER AND
					w_FAC_FACT_LIGNE_TIER.FLT_INTERVENANT = w_FLT_INTERVENANT_compta.FLT_INTERVENANT AND
					FLT_IS_DIRECT = 1
				;

				DROP TABLE IF EXISTS w_FLT_INTERVENANT_compta;
				CREATE TEMP TABLE w_FLT_INTERVENANT_compta AS
				SELECT FLT_FACTURE, FT_TYPE_TIER, FLT_INTERVENANT
				FROM w_FLT_INTERVENANT
				LEFT JOIN w_ECR_INTERVENANT ON 
					FLT_FACTURE = ECR_REF_FACT AND
					FT_TYPE_TIER = ECR_TYPE_TIER AND
					(FLT_INTERVENANT = CPT_REF OR CPT_REF = -1)
				WHERE FLT_TOTAL_TTC_comptable <> COALESCE(ECR_MONTANT,0) AND
					COALESCE(ECR_MONTANT,0) = 0
				GROUP BY 1,2,3
				ORDER BY 1,2,3
				;

				ANALYSE w_FLT_INTERVENANT_compta
				;

				UPDATE w_FAC_FACT_LIGNE_TIER SET
					FLT_TOTAL_TTC_comptable = 0
				FROM w_FLT_INTERVENANT_compta
				WHERE w_FAC_FACT_LIGNE_TIER.FLT_FACTURE = w_FLT_INTERVENANT_compta.FLT_FACTURE AND
					w_FAC_FACT_LIGNE_TIER.FT_TYPE_TIER = w_FLT_INTERVENANT_compta.FT_TYPE_TIER AND
					w_FAC_FACT_LIGNE_TIER.FLT_INTERVENANT = w_FLT_INTERVENANT_compta.FLT_INTERVENANT AND
					FLT_TOTAL_TTC_comptable <> 0
				;

				UPDATE w_FAC_FACT_LIGNE_TIER
				SET FLT_IS_DIRECT = 1
				WHERE FLT_IS_DIRECT = 0 AND FLT_TOTAL_TTC_comptable = 0
				;
				
				UPDATE w_FAC_FACT_LIGNE_TIER
				SET FLT_IS_DIRECT = CASE WHEN QRGMT = '0' THEN -1 ELSE 0 END
				WHERE FLT_IS_DIRECT = 1 AND FLT_TOTAL_TTC_comptable <> 0
				;

				UPDATE prod_web100t.FAC_FACT_LIGNE_TIER
				SET FLT_IS_DIRECT = w_FAC_FACT_LIGNE_TIER.FLT_IS_DIRECT
				FROM w_FAC_FACT_LIGNE_TIER
				WHERE w_FAC_FACT_LIGNE_TIER.FLT_OID = FAC_FACT_LIGNE_TIER.FLT_OID AND
					w_FAC_FACT_LIGNE_TIER.FLT_IS_DIRECT <> FAC_FACT_LIGNE_TIER.FLT_IS_DIRECT
				;
				
				
				-- Forçage des prestations comptabilisees clinique en facture clinique
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'WEB100T_FORCEPRESTA_ETSB24',
					'Forçage des prestations comptabilisees clinique en facture clinique',
					'0',
					'1=Les prestations établissements avec type B2 = 4 sont forcées en facturation établissement'
				WHERE 'WEB100T_FORCEPRESTA_ETSB24' NOT IN (SELECT code FROM activite.t_divers);
				;
				
				UPDATE prod_web100t.FAC_FACT_LIGNE
				SET LI_TYPE_B2 = '3'
				FROM prod_web100t.FAC_FACT_LIGNE_TIER,
					activite.t_divers
				WHERE FLT_LIGNE_FACTURE = LI_OID AND
					FLT_IS_ETS = '1' AND
					LI_TYPE_B2 = '4' AND
					t_divers.code = 'WEB100T_FORCEPRESTA_ETSB24' AND
					t_divers.valeur = '1'
				;

				
			]]></sqlcmd>
		</NODE>

		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
				-- remise a jourt des index de dat_da
				VACUUM ANALYSE  prod_web100t.DAT_DA;
				REINDEX TABLE prod_web100t.DAT_DA;
				
				
				DROP TABLE IF EXISTS w_DAT_DA;
				CREATE TEMP TABLE w_DAT_DA AS
				SELECT 
					finess,	
					DAT_DA.* ,
					DAT_SEJOUR.*,
					COALESCE(DA_DATE_FIN + DA_HEURE_FIN * interval '1 day', '20991231') AS DA_DATE_TIME_FIN,
					'N'::text AS CTI_OK,
					0::numeric AS RPH_ETAT,
					null::timestamp AS RPH_MODIFIED,
					''::text AS dup_type_sejour,
					'0'::text AS dup_code_prevu,
					0::bigint AS dup_sejour_id,
					''::text AS dup_no_sejour,
					0::bigint AS dup_medecin_sejour_id,
					''::text AS dup_etat
				FROM prod_web100t.DAT_SEJOUR 
					JOIN prod_web100t.DAT_DA ON SEJ_DA = DA_OID
					JOIN w_NMCL_ETABLISSEMENT ON ETS_OID = DA_EG_ENTREE;

				ALTER TABLE w_DAT_DA ALTER COLUMN da_numero TYPE text;

				CREATE INDEX w_DAT_DA_i1
					ON w_DAT_DA
					USING btree
					(DA_OID);
				
				UPDATE w_DAT_DA
				SET CTI_OK = 'O' 
				WHERE DA_STATUT IN (2,3,4) AND
					SEJ_NO_ENTREE <> '' AND
					(DA_DATE_FIN >= '[ENV_ADM_ANNEEDEBUT]0101' OR DA_DATE_FIN IS NULL);

				
				UPDATE w_DAT_DA
				SET CTI_OK = 'O' 
				WHERE CTI_OK <> 'O' AND
					DA_OID = ANY (ARRAY (SELECT DISTINCT FACT_DA FROM prod_web100t.FAC_FACTURE));
					
				
				-- Séjours cloturés sans facture à supprimer (fausses venues)
				UPDATE w_DAT_DA
				SET CTI_OK = 'N'
				WHERE CTI_OK = 'O' AND
					DA_STATUT = 4 AND
					DA_OID = ANY (ARRAY (SELECT DISTINCT DA_OID FROM w_DAT_DA LEFT JOIN prod_web100t.FAC_FACTURE ON FACT_DA = DA_OID WHERE FACT_DA IS NULL))
				;
                
                -- Séances (séjours avec plusieurs jour - préparés à l'avance) sans prestation saisie ni facture
                
                DROP TABLE IF EXISTS w_exclude_da;
                CREATE TEMP TABLE w_exclude_da AS
                (
                    SELECT 
                        DISTINCT PREST_DA AS exclude_da
                    FROM 
                        prod_web100t.DAT_PRESTATIONS_GAP 
                    WHERE 1=1
                        AND PREST_DELETED = 0
                        AND PREST_DATE_DEBUT >= '[ENV_ADM_ANNEEDEBUT]0101'::timestamp without time zone
                )
                UNION
                (
                    SELECT 
                        DISTINCT FACT_DA AS exclude_da
                    FROM 
                        prod_web100t.FAC_FACTURE 
                    WHERE 
                        FACT_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'::timestamp without time zone
                );

                UPDATE w_DAT_DA
				SET CTI_OK = 'N'
                WHERE CTI_OK = 'O' AND
					DA_STATUT IN ('3','4') AND
                    DA_CLASSE = '4' AND
                    date(DA_DATE_FIN) > date(DA_DATE_DEBUT) AND
                    DA_OID != ALL (ARRAY(SELECT exclude_da FROM w_exclude_da)::double precision[]) 
                ;
                UPDATE w_DAT_DA
				SET CTI_OK = 'N'
                WHERE CTI_OK = 'O' AND
					DA_STATUT NOT IN ('3','4') AND
                    DA_CLASSE = '4' AND
                    DA_OID != ALL (ARRAY(SELECT exclude_da FROM w_exclude_da)::double precision[]) AND
                    date(DA_DATE_DEBUT) < date(now() - interval '7 day')
                ;
                
                DROP TABLE w_exclude_da;
				
				-- Enlever les dossiers trop anciens
				UPDATE w_DAT_DA
				SET CTI_OK = 'N'
				FROM
				(
				SELECT FACT_DA, 
					SUM(FT_TOTAL), 
					SUM(RD_TOTAL), 
					MAX(FACT_DATE), 
					MAX(FR_DATE_ENC)
				FROM
				(
				SELECT FACT_DA, 
					FT_OID, 
					MAX(FT_TOTAL_ETS+FT_TOTAL_HO) AS FT_TOTAL, 
					SUM(RD_MONTANT) AS RD_TOTAL, 
					date(MAX(FACT_DATE)) AS FACT_DATE, 
					date(MAX(GREATEST(RD_DATE,FR_DATE_ENC))) AS FR_DATE_ENC
				FROM prod_web100t.FAC_FACTURE
				JOIN W_DAT_DA ON FACT_DA = DA_OID AND 
						CTI_OK = 'O' AND 
						DA_STATUT IN ('3','4') AND 
						DA_DATE_FIN <= '[ENV_ADM_ANNEEDEBUT]0101'
				LEFT JOIN prod_web100t.FAC_FACT_TIER ON FACT_OID = FT_FACTURE
				LEFT JOIN prod_web100t.FAC_RGLMT_DETAILS ON RD_FACT_TIER = FT_OID
				LEFT JOIN prod_web100t.FAC_REGLEMENTS ON FR_OID = RD_REGLEMENT
				GROUP BY 1,2
				) subview
				GROUP BY 1
				HAVING round(SUM(FT_TOTAL)::numeric,2) = round(SUM(RD_TOTAL)::numeric,2) AND
					MAX(FACT_DATE) < '[ENV_ADM_ANNEEDEBUT]0101' AND
					MAX(FR_DATE_ENC) < '[ENV_ADM_ANNEEDEBUT]0101'
					) subview
				WHERE FACT_DA = DA_OID
				;
				
				-- Identification séjour suspndus/annulés/refusés
				DROP TABLE IF EXISTS w_REGUL_PHASES
				;
				CREATE TEMP TABLE w_REGUL_PHASES AS
				SELECT RPH_SEJOUR_OID, 
					(MAX(ARRAY[RPH_MODIFIED::text, RPH_ETAT::text]))[2]::numeric AS RPH_ETAT,
					MAX(RPH_MODIFIED) AS RPH_MODIFIED
				FROM prod_web100T.REGUL_PHASES
				GROUP BY 1
				;
				
				ANALYSE  w_REGUL_PHASES
				;
				
				UPDATE w_DAT_DA SET
					CTI_OK = 'O',
					RPH_ETAT = w_REGUL_PHASES.RPH_ETAT,
					RPH_MODIFIED = w_REGUL_PHASES.RPH_MODIFIED
				FROM w_REGUL_PHASES
				WHERE  PHASE_OID = RPH_SEJOUR_OID AND
					w_REGUL_PHASES.RPH_ETAT IN (6,7,8) AND
					DA_DATE_DEBUT >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					CTI_OK = 'N'
				;
				

				DELETE FROM w_DAT_DA
				WHERE CTI_OK <> 'O';


				UPDATE w_DAT_DA
				SET SEJ_NO_ENTREE = 'W' || DA_OID
				WHERE SEJ_NO_ENTREE = '';
				
				
				UPDATE w_DAT_DA
				SET DA_DATE_FIN = date(MVT_DATE_DAY), DA_HEURE_FIN = MVT_DATE_HOUR
				FROM w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				WHERE DA_DATE_FIN IS NULL AND
					PHASE_OID = MVT_SEJ_OID AND 
					DA_STATUT IN (3,4) AND
					MVT_TYPE = 2;
                
                -- Sejours en double (Analyser différence entre DA_NUMERO et SEJ_NO_ENTREE)	
                SELECT base.cti_execute('
					DELETE
					FROM w_DAT_DA
					USING
					(SELECT DA_OID, (MAX(ARRAY[to_char(999-SEJ_NBRE_BB,''FM999'')::text || to_char(PHASE_OID,''FM999999999999'')::text,SEJ_NO_ENTREE::text]))[2] AS SEJ_NO_ENTREE FROM w_DAT_DA WHERE CTI_OK = ''O'' GROUP BY 1 HAVING COUNT(*) > 1) subview
					WHERE w_DAT_DA.DA_OID = subview.DA_OID AND w_DAT_DA.SEJ_NO_ENTREE = subview.SEJ_NO_ENTREE AND SEJ_NBRE_BB > 0',20);
					
				-- Sejours en double (Analyser différence entre DA_NUMERO et SEJ_NO_ENTREE)	
				SELECT base.cti_execute('
					DELETE
					FROM w_DAT_DA
					USING
					(SELECT DA_OID, (MAX(ARRAY[to_char(999-SEJ_NBRE_BB,''FM999'')::text || to_char(PHASE_OID,''FM999999999999'')::text,SEJ_NO_ENTREE::text]))[2] AS SEJ_NO_ENTREE FROM w_DAT_DA WHERE CTI_OK = ''O'' GROUP BY 1 HAVING COUNT(*) > 1) subview
					WHERE w_DAT_DA.DA_OID = subview.DA_OID AND w_DAT_DA.SEJ_NO_ENTREE = subview.SEJ_NO_ENTREE',20);
				
				-- Sejours en double (Suffixer no sejour pour le reste)
				SELECT base.cti_execute('
					UPDATE w_DAT_DA
					SET DA_NUMERO = w_DAT_DA.DA_NUMERO || ''_'' || nb::text
					FROM (
						SELECT DA_NUMERO, MAX(DA_OID) AS DA_OID, count(*) AS nb
						FROM w_DAT_DA
						WHERE DA_NUMERO IN (
						SELECT da_numero 
						FROM w_DAT_DA 
						GROUP BY 1 
						HAVING count(*) > 1) AND
						SEJ_NO_ENTREE <> DA_NUMERO
						GROUP BY 1) subview
					WHERE w_DAT_DA.DA_OID = subview.DA_OID'
					,20);
					
				
					SELECT base.cti_execute('
					UPDATE w_DAT_DA
					SET DA_NUMERO = w_DAT_DA.DA_NUMERO || ''_'' || nb::text
					FROM (
						SELECT DA_NUMERO, MAX(DA_OID) AS DA_OID, count(*) AS nb
						FROM w_DAT_DA
						WHERE DA_NUMERO IN (
						SELECT da_numero 
						FROM w_DAT_DA 
						GROUP BY 1 
						HAVING count(*) > 1) 
						GROUP BY 1) subview
					WHERE w_DAT_DA.DA_OID = subview.DA_OID'
					,20);

				VACUUM ANALYSE w_DAT_DA;
				
				
				
				-- Si mouvement d'entrée sans lit, prendre le lit suivant (si même UF)
				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_lit_entree;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_lit_entree AS
				SELECT w_REGUL_MOUVEMENTS_source.MVT_OID, MAX(w_REGUL_MOUVEMENTS_source.MVT_SEJ_OID) AS MVT_SEJ_OID, 
					(MIN(ARRAY[w_REGUL_MOUVEMENTS_source_2.MVT_INDEX, w_REGUL_MOUVEMENTS_source_2.MVT_CHAMBRE]))[2] AS MVT_CHAMBRE, 
					(MIN(ARRAY[w_REGUL_MOUVEMENTS_source_2.MVT_INDEX, w_REGUL_MOUVEMENTS_source_2.MVT_LIT]))[2] AS MVT_LIT
				FROM w_REGUL_MOUVEMENTS_source
				JOIN w_DAT_DA ON PHASE_OID = w_REGUL_MOUVEMENTS_source.MVT_SEJ_OID
				JOIN w_REGUL_MOUVEMENTS_source w_REGUL_MOUVEMENTS_source_2 ON 
					w_REGUL_MOUVEMENTS_source.MVT_SEJ_OID = w_REGUL_MOUVEMENTS_source_2.MVT_SEJ_OID AND
					w_REGUL_MOUVEMENTS_source_2.MVT_INDEX > w_REGUL_MOUVEMENTS_source.MVT_INDEX AND
					w_REGUL_MOUVEMENTS_source_2.MVT_TYPE IN (1,2,4)
				WHERE
					w_REGUL_MOUVEMENTS_source.MVT_INDEX = 1 AND
					w_REGUL_MOUVEMENTS_source.MVT_UF_GEO <> 0 AND
					w_REGUL_MOUVEMENTS_source.MVT_LIT = 0 AND
					w_REGUL_MOUVEMENTS_source.MVT_CHAMBRE = 0 
				GROUP BY 1
				HAVING (MIN(ARRAY[w_REGUL_MOUVEMENTS_source_2.MVT_INDEX, w_REGUL_MOUVEMENTS_source_2.MVT_UF_GEO]))[2] = MAX(w_REGUL_MOUVEMENTS_source.MVT_UF_GEO) AND
					(MIN(ARRAY[w_REGUL_MOUVEMENTS_source_2.MVT_INDEX, w_REGUL_MOUVEMENTS_source_2.MVT_LIT]))[2] <> 0
				;

				ANALYSE w_REGUL_MOUVEMENTS_lit_entree
				;

				UPDATE w_REGUL_MOUVEMENTS_source SET 
					MVT_CHAMBRE = w_REGUL_MOUVEMENTS_lit_entree.MVT_CHAMBRE,
					MVT_LIT = w_REGUL_MOUVEMENTS_lit_entree.MVT_LIT
				FROM w_REGUL_MOUVEMENTS_lit_entree
				WHERE w_REGUL_MOUVEMENTS_source.MVT_OID = w_REGUL_MOUVEMENTS_lit_entree.MVT_OID
				;
				

				
			]]></sqlcmd>
		</NODE>

	</NODE>

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

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

				DROP TABLE IF EXISTS w_patients;
				CREATE TEMP TABLE w_patients AS
				SELECT 
					PAT_ID AS w_PAT_ID,
					MAX(PAT_IPP) AS w_PAT_IPP
				FROM w_DAT_DA 
					JOIN prod_web100t.PATIENTS ON DA_PATIENT = PAT_ID
				GROUP BY 1
				ORDER BY 1;
				
				-- Doublons
				UPDATE w_patients
				SET w_PAT_IPP = w_patients.w_PAT_IPP || '_' || num
				FROM
				(SELECT * FROM 
					(SELECT w_pat_id, w_pat_ipp,row_number() OVER(PARTITION BY w_PAT_IPP ORDER BY w_PAT_ID ASC) AS num FROM w_patients) subview0 
					WHERE subview0.num > 1
				) subview
				WHERE w_patients.w_PAT_ID = subview.w_PAT_ID;

				
				INSERT INTO activite[PX].p_patients(
					no_patient, 
					nom, 
					prenom, 
					nom_naissance, 
					date_naissance, 
					code_sexe)
				SELECT 
					w_PAT_IPP, 
					PAT_NOM, 
					PAT_PRENOM, 
					PAT_NOMNAISS, 
					date(PAT_NAISSANCE), 
					CASE WHEN PAT_SEXE = '2' THEN '2' ELSE '1' END
				FROM w_patients 
					JOIN prod_web100t.PATIENTS ON PAT_ID = w_PAT_ID
					LEFT JOIN activite[PX].p_patients ON (w_PAT_IPP = p_patients.no_patient)
				WHERE p_patients.no_patient IS NULL;
					
				UPDATE activite[PX].p_patients
				SET 
					nom = PAT_NOM, 
					prenom = PAT_PRENOM, 
					nom_naissance = PAT_NOMNAISS, 
					date_naissance = date(PAT_NAISSANCE), 
					code_sexe = CASE WHEN PAT_SEXE = '2' THEN '2' ELSE '1' END
				FROM prod_web100t.PATIENTS
					JOIN w_patients ON PAT_ID = w_PAT_ID
				WHERE w_PAT_IPP = p_patients.no_patient
					AND (
						nom IS DISTINCT FROM PAT_NOM OR
						prenom IS DISTINCT FROM PAT_PRENOM OR
						nom_naissance IS DISTINCT FROM PAT_NOMNAISS OR
						date_naissance IS DISTINCT FROM date(PAT_NAISSANCE) OR
						code_sexe IS DISTINCT FROM CASE WHEN PAT_SEXE = '2' THEN '2' ELSE '1' END
					);
										
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Séjours">
			<sqlcmd><![CDATA[
            
                -- Corrections car rss en double !!
	            UPDATE prod_web100t.DAT_RSS
	            SET RSS_NO_HOSPIT = 0-DAT_RSS.RSS_NO_HOSPIT
	            FROM
	            (
	            SELECT RSS_NO_HOSPIT , MAX(CASE WHEN DA_NUMERO IS NOT NULL THEN RES_OID ELSE NULL END) AS RES_OID_OK
	            				FROM prod_web100t.DAT_RESUME  
	            				JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
	            				JOIN prod_web100t.DAT_GROUPAGE ON GRP_RESUME = RES_OID AND GRP_CORRECT = 1
	            				LEFT JOIN prod_web100t.DAT_DA ON RSS_NO_HOSPIT = DA_NUMERO AND 
	            					date(DA_DATE_DEBUT) = date(RES_DE_CALC) AND 
	            					date(DA_DATE_FIN)  = date(RES_DS_CALC)
	            				WHERE RSS_NO_HOSPIT > 0
	            				GROUp BY 1
	            				HAVING count(DISTINCT RSS_OID) > 1 
	            				ORDER BY 1
	            ) subview
	            WHERE DAT_RSS.RSS_NO_HOSPIT = subview.RSS_NO_HOSPIT AND
	            	RSS_OID <> RES_OID_OK
                ;
                
                -- Détection GHM
				
				DROP TABLE IF EXISTS w_DAT_GROUPAGE;
				CREATE TEMP TABLE w_DAT_GROUPAGE AS
				SELECT 
					RSS_NO_HOSPIT,
					to_number((MAX(Array[GRP_DATE::text, COALESCE(t_ghs.oid,0)::text]))[2],'00000000000000') AS ghs_id,
					to_number((MAX(Array[GRP_DATE::text, COALESCE(t_ghm.oid,0)::text]))[2],'00000000000000') AS ghm_id,
					(MAX(Array[GRP_DATE::text, w_SGN_NMCL_DATA_GHS.ND_CODE]))[2] AS ND_CODE_GHS,
					(MAX(Array[GRP_DATE::text, w_SGN_NMCL_DATA_GHM.ND_CODE]))[2] AS ND_CODE_GHM
				FROM prod_web100t.DAT_GROUPAGE
					JOIN prod_web100t.DAT_RESUME ON GRP_RESUME = RES_OID
					JOIN prod_web100t.DAT_RSS ON RES_OID = RSS_OID
					JOIN prod_web100t.DAT_HOSPIT ON RES_HOSPIT = HOSP_OID
					LEFT JOIN w_SGN_NMCL_DATA w_SGN_NMCL_DATA_GHS ON 
						GRP_CODE_GHS = w_SGN_NMCL_DATA_GHS.ND_OID
					LEFT JOIN w_SGN_NMCL_DATA w_SGN_NMCL_DATA_GHM ON 
						GRP_GHM = w_SGN_NMCL_DATA_GHM.ND_OID
					LEFT JOIN base.t_ghs ON t_ghs.code = to_number('0' || w_SGN_NMCL_DATA_GHS.ND_CODE,'00000')
					LEFT JOIN base.t_ghm ON t_ghm.code = w_SGN_NMCL_DATA_GHM.ND_CODE
				WHERE GRP_CODE_GHS <> 0 OR GRP_GHM <> 0 
				GROUP BY 1;
				
				UPDATE w_DAT_GROUPAGE SET
					ghs_id = 0, ghm_id = 0
				WHERE ND_CODE_GHM LIKE '90%' AND
					(ghs_id <> 0 OR ghm_id <> 0);

				ALTER TABLE w_DAT_GROUPAGE ADD CONSTRAINT w_DAT_GROUPAGE_pkey PRIMARY KEY(RSS_NO_HOSPIT);


				DROP TABLE IF EXISTS w_DAT_CONDITIONS_HEB;
				CREATE TEMP TABLE w_DAT_CONDITIONS_HEB AS
				SELECT
					CH_SEJOUR,
					(MAX(Array[CH_DATE_DEMANDE::text,CH_CP_DEMANDEE::text]))[2] AS CH_CP_DEMANDEE
				FROM prod_web100t.DAT_CONDITIONS_HEB 
				WHERE CH_CP_DEMANDEE <> 0
				GROUP BY 1;

				ALTER TABLE w_DAT_CONDITIONS_HEB ADD CONSTRAINT w_DAT_CONDITIONS_HEB_pkey PRIMARY KEY(CH_SEJOUR);

			
				DROP TABLE IF EXISTS w_DAT_IDENTITE;
				CREATE TEMP TABLE w_DAT_IDENTITE AS
				SELECT
					IDT_DA,
					(MAX(CASE WHEN IDT_TYPE = 'AMO' AND IDT_ORGANISME <> 0 THEN Array[IDT_CREATED::text, COALESCE(t_tiers_payant.oid,0)::text] ELSE Array['',0::text] END))[2]::bigint AS tiers_payant_1_id,
					(MAX(CASE WHEN IDT_TYPE = 'AMC' AND IDT_ORGANISME <> 0 THEN Array[IDT_CREATED::text, COALESCE(t_tiers_payant.oid,0)::text] ELSE Array['',0::text] END))[2]::bigint AS tiers_payant_2_id,
					(MAX(Array[IDT_CREATED::text, COALESCE(t_codes_postaux.oid,0)::text]))[2]::bigint AS code_postal_id
				FROM prod_web100t.DAT_IDENTITE
					LEFT JOIN activite[PX].t_tiers_payant ON IDT_ORGANISME = code_original
					LEFT JOIN base.t_codes_postaux on IDT_CP = t_codes_postaux.code
				GROUP BY 1;

				ALTER TABLE w_DAT_IDENTITE ADD CONSTRAINT w_DAT_IDENTITE_pkey PRIMARY KEY(IDT_DA);

				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_SORTIE;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_SORTIE AS
				SELECT
					DA_OID,
					SEJ_SPECIALITE,
					SEJ_RESPONSABLE,
					DA_NODE_RESP,
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_RESP::text]))[2]::bigint,0) AS MVT_RESP,
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_UF_SOIN::text]))[2]::bigint,0) AS MVT_UF_SOIN,
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_UF_GEO::text]))[2]::bigint,0) AS MVT_UF_GEO,
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_LIT::text]))[2]::bigint,0) AS MVT_LIT,

					SEJ_SPECIALITE || '|' ||
					SEJ_RESPONSABLE || '|' ||
					DA_NODE_RESP || '|' ||
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_RESP::text]))[2],'') || '|' ||
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_UF_SOIN::text]))[2],'') || '|' ||
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_UF_GEO::text]))[2],'') || '|' ||
					COALESCE((MAX(Array[MVT_DATE::text || MVT_INDEX, MVT_LIT::text]))[2],'')
					 AS key
				FROM w_DAT_DA
					LEFT JOIN w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS ON PHASE_OID = MVT_SEJ_OID AND MVT_TYPE IN (1,4)
				GROUP BY 1,2,3,4;


				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_SORTIE_keys;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_SORTIE_keys AS
				SELECT 
					key,
					SEJ_RESPONSABLE,
					DA_NODE_RESP,
					MVT_RESP,
					MVT_UF_SOIN,
					SEJ_SPECIALITE,
					MVT_UF_GEO,
					MVT_LIT,

					0 AS mode_traitement_id,
					''::text AS mode_traitement_code,
					''::text AS dmt_code,
					'0'::text AS type_sejour_force,
                    '0'::text AS type_sejour_seances_autorise,
					'0'::text AS type_t2a,
					0::bigint AS lieu_id,
					0::bigint AS medecin_sejour_id
				FROM w_REGUL_MOUVEMENTS_SORTIE
				GROUP BY 1,2,3,4,5,6,7,8;


				UPDATE w_REGUL_MOUVEMENTS_SORTIE_keys SET
					mode_traitement_id = w_NMCL_UNITEFONCTIONNELLE.mode_traitement_id,
					mode_traitement_code = w_NMCL_UNITEFONCTIONNELLE.mode_traitement_code,
					dmt_code = w_NMCL_UNITEFONCTIONNELLE.dmt_code,
					type_sejour_force = CASE WHEN w_NMCL_UNITEFONCTIONNELLE.type_sejour IN ('1', '2', '3', '31', '4', '5', '9') THEN w_NMCL_UNITEFONCTIONNELLE.type_sejour ELSE '0' END,
                    type_sejour_seances_autorise = CASE WHEN w_NMCL_UNITEFONCTIONNELLE.type_sejour IN ('1', '2', '3', '31', '4', '0sauf5') THEN '0' ELSE '1' END,
					type_t2a = w_NMCL_UNITEFONCTIONNELLE.type_t2a
				FROM w_NMCL_UNITEFONCTIONNELLE
				WHERE w_NMCL_UNITEFONCTIONNELLE.WEB100T_OID = MVT_UF_SOIN;




				UPDATE w_REGUL_MOUVEMENTS_SORTIE_keys
					set medecin_sejour_id = w_NMCL_INTERVENANT.medecin_administratif_id
				FROM w_NMCL_INTERVENANT
				WHERE MVT_RESP <> 0 AND NODE_OID = MVT_RESP;

				UPDATE w_REGUL_MOUVEMENTS_SORTIE_keys
					set medecin_sejour_id = w_NMCL_INTERVENANT.medecin_administratif_id
				FROM w_NMCL_INTERVENANT
				WHERE medecin_sejour_id = 0 AND SEJ_RESPONSABLE <> 0 AND NODE_OID = SEJ_RESPONSABLE;

				UPDATE w_REGUL_MOUVEMENTS_SORTIE_keys
					set medecin_sejour_id = w_NMCL_INTERVENANT.medecin_administratif_id
				FROM w_NMCL_INTERVENANT
				WHERE medecin_sejour_id = 0 AND DA_NODE_RESP <> 0 AND NODE_OID = DA_NODE_RESP;


				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_6)
				SELECT MVT_UF_SOIN, SEJ_SPECIALITE, MVT_UF_GEO, MVT_LIT, MVT_UF_SOIN
				FROM w_REGUL_MOUVEMENTS_SORTIE_keys
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = MVT_UF_SOIN AND
						code_original_2 = SEJ_SPECIALITE AND
						code_original_3 = MVT_UF_GEO AND
						code_original_4 = MVT_LIT AND
						code_original_6 = MVT_UF_SOIN
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5;


				



				UPDATE w_REGUL_MOUVEMENTS_SORTIE_keys
					set lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = MVT_UF_SOIN AND
						code_original_2 = SEJ_SPECIALITE AND
						code_original_3 = MVT_UF_GEO AND
						code_original_4 = MVT_LIT AND
						code_original_6 = MVT_UF_SOIN;


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

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

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

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

	

				ALTER TABLE w_REGUL_MOUVEMENTS_SORTIE ADD CONSTRAINT w_REGUL_MOUVEMENTS_SORTIE_pkey PRIMARY KEY(DA_OID);

				CREATE INDEX w_REGUL_MOUVEMENTS_SORTIE_i1
					ON w_REGUL_MOUVEMENTS_SORTIE
					USING btree
					(key);
					
					
					
				DROP TABLE IF EXISTS w_DAT_DA_type_sejour;
				CREATE TEMP TABLE w_DAT_DA_type_sejour AS
				SELECT
					DA_OID,
					CASE WHEN date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '1' ELSE '0' END AS de_ds,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC >= 0 AND FLT_CODE_PREST IN ('GHS','PJ') THEN 1 
						WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC < 0 AND FLT_CODE_PREST IN ('GHS','PJ') THEN -1 
						ELSE 0 END) AS nb_sej,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC >= 0 AND FLT_CODE_PREST IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'ATU', 'FPU', 'FFM') THEN 1 
						WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC < 0 AND FLT_CODE_PREST IN ('SE1', 'SE2', 'SE3', 'SE4', 'SE5', 'SE6', 'SE7', 'ATU', 'FPU', 'FFM') THEN -1 
						ELSE 0 END) AS nb_ext,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC >= 0 AND FLT_CODE_PREST BETWEEN 'D01' AND 'D19' THEN 1 
						WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC < 0 AND FLT_CODE_PREST BETWEEN 'D01' AND 'D19' THEN -1 
						ELSE 0 END) AS nb_dia,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC >= 0 THEN 1 
						WHEN FLT_IS_ETS = 1 AND FLT_TOTAL_TTC < 0 THEN -1 
						ELSE 0 END) AS nb_ets,
					SUM(CASE WHEN FLT_IS_ETS <> 1 AND FLT_TOTAL_TTC >= 0 THEN 1 
						WHEN FLT_IS_ETS <> 1 AND FLT_TOTAL_TTC < 0 THEN -1 
						ELSE 0 END) AS nb_hon,
					'0'::text AS type_sejour_facture
				FROM w_DAT_DA
					JOIN prod_web100t.FAC_FACT_TIER ON FT_DA = DA_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID 
				WHERE FLT_RECAP <> 0 
				GROUP BY 1,2
				ORDER BY 1
				;

				UPDATE w_DAT_DA_type_sejour SET type_sejour_facture = '1' WHERE nb_sej > 0 AND nb_ext = 0 AND de_ds = '0';
				UPDATE w_DAT_DA_type_sejour SET type_sejour_facture = '2' WHERE nb_sej > 0 AND nb_ext = 0 AND de_ds = '1';
				UPDATE w_DAT_DA_type_sejour SET type_sejour_facture = '3' WHERE nb_sej = 0 AND nb_ext > 0 AND nb_dia = 0;
				UPDATE w_DAT_DA_type_sejour SET type_sejour_facture = '5' WHERE nb_sej = 0 AND nb_ext = 0 AND nb_dia > 0;
				UPDATE w_DAT_DA_type_sejour SET type_sejour_facture = '3' WHERE type_sejour_facture = '0' AND de_ds = '1' AND nb_ets = 0 AND nb_hon = 1;
				
				ALTER TABLE w_DAT_DA_type_sejour ADD CONSTRAINT w_DAT_DA_type_sejour_pkey PRIMARY KEY(DA_OID);

				-- Table de travail pour la préadmission des séjours 

				DROP TABLE IF EXISTS w_sejours_preadmission;
				CREATE TEMP TABLE w_sejours_preadmission(
					no_sejour text PRIMARY KEY,
					date_entree timestamp,
					date_validation_preadmission timestamp,
					"preadmission_j1" smallint,
					"preadmission_j2" smallint
				)
				;

				INSERT INTO w_sejours_preadmission(
					no_sejour,
					date_entree,
					date_validation_preadmission,
					"preadmission_j1",
					"preadmission_j2"
				)
				SELECT 
					DA_NUMERO,
					DA_DATE_DEBUT,
					SEJ_VALIDATION_PREAD_LE,
					CASE WHEN (DA_DATE_DEBUT - SEJ_VALIDATION_PREAD_LE) >= '10:00:00' THEN 1 ELSE 0 END,
					CASE WHEN (DA_DATE_DEBUT - SEJ_VALIDATION_PREAD_LE) >= '1 day 06:00:00' THEN 1 ELSE 0 END
				FROM w_DAT_DA
				;

				ANALYZE w_sejours_preadmission
				;

				-- Insertion des colonnes de la table w_sejours_preadmission
				-- dans table CTI p_sejours_preadmission

				INSERT INTO activite[PX].p_sejours_preadmission(
					no_sejour,
					date_entree,
					date_validation_preadmission,
					"preadmission_j1",
					"preadmission_j2"
				)
				SELECT
					no_sejour,
					date_entree,
					date_validation_preadmission,
					"preadmission_j1",
					"preadmission_j2"
				FROM w_sejours_preadmission
				WHERE NOT EXISTS (
					SELECT no_sejour 
					FROM activite[PX].p_sejours_preadmission 
					WHERE w_sejours_preadmission.no_sejour = p_sejours_preadmission.no_sejour
				)
				;

				DROP TABLE IF EXISTS w_sejours ;
				CREATE TEMP TABLE w_sejours AS
				SELECT
					finess,
					nextval('activite[PX].s_sejours'::regclass) AS sejour_id,
					w_DAT_DA.DA_OID AS code_original,
					DA_NUMERO AS no_sejour,
					PAT_IPP AS no_patient,
					CASE WHEN PAT_SEXE = '2' THEN '2' ELSE '1' END AS code_sexe,
					DA_DATE_DEBUT + DA_HEURE_DEBUT * interval '1 day' AS date_heure_entree,
					date(DA_DATE_DEBUT) AS date_entree,
					extract('hour' FROM DA_HEURE_DEBUT * interval '1 day') * 10000 + 
						extract('minute' FROM DA_HEURE_DEBUT * interval '1 day') * 100 + 
						extract('second' FROM DA_HEURE_DEBUT * interval '1 day') AS heure_entree,
					COALESCE(substr(w_SGN_NMCL_DATA_MODEENTREE.ND_CODE,1,1),'8') AS mode_entree,
					COALESCE(substr(w_SGN_NMCL_DATA_MODEENTREE.ND_CODE,2,1),'') AS provenance,
					COALESCE(DA_DATE_FIN + DA_HEURE_FIN * interval '1 day', '20991231') AS date_heure_sortie,
					COALESCE(date(DA_DATE_FIN), '20991231') AS date_sortie,
					COALESCE(extract('hour' FROM DA_HEURE_FIN * interval '1 day') * 10000 + 
						extract('minute' FROM DA_HEURE_FIN * interval '1 day') * 100 + 
						extract('second' FROM DA_HEURE_FIN * interval '1 day'),0) AS heure_sortie,
					COALESCE(substr(w_SGN_NMCL_DATA_MODESORTIE.ND_CODE,1,1),'8') AS mode_sortie,
					COALESCE(substr(w_SGN_NMCL_DATA_MODESORTIE.ND_CODE,2,1),'') AS destination,
					CASE 
						WHEN DA_STATUT IN ('3','4') AND DA_DATE_FIN IS NOT NULL THEN 1
						ELSE 0 END AS code_sorti,
					CASE 
						WHEN DA_STATUT <= 1 THEN 1
						ELSE 0 END AS code_prevu,
					CASE 
						WHEN type_sejour_seances_autorise = '1' AND ND_CODE_GHM LIKE '28%' THEN '5'
						WHEN type_sejour_force <> '0' AND type_sejour_force <> '31' THEN type_sejour_force
						WHEN type_sejour_force = 31 AND date(DA_DATE_FIN) - date(DA_DATE_DEBUT) <= 1 THEN '3'
						WHEN type_sejour_force = 31 THEN '1'
						WHEN type_sejour_facture <> '0' THEN type_sejour_facture
						WHEN DA_CLASSE IN (1,2) AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) AND DA_SUGG_MODE_FACT IN ('ATU','FSU','HON','SEH') THEN '3'
						WHEN DA_CLASSE IN (1,2) AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2'
						WHEN DA_CLASSE IN (1,2) THEN '1'
						WHEN DA_CLASSE IN (3,5) THEN '3'
						WHEN DA_CLASSE IN (4) THEN '5'
						WHEN mode_traitement_code IN ('03') AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_code IN ('03') THEN '1' 
						WHEN mode_traitement_code IN ('07') THEN '3' 
						WHEN mode_traitement_code IN ('07') OR dmt_code IN ('958') THEN '3' 
						WHEN mode_traitement_code IN ('19', '23') AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_code IN ('04') AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_code IN ('03') AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_code IN ('03') THEN '1' 
						WHEN mode_traitement_id = 0 AND type_t2a = '1' AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_id = 0 AND ghs_id <> 0 AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '2' 
						WHEN mode_traitement_id = 0 AND type_t2a <> '1' AND date(DA_DATE_DEBUT) = date(DA_DATE_FIN) THEN '3' 
						ELSE '1' END AS type_sejour,
					mode_traitement_id,
					w_REGUL_MOUVEMENTS_SORTIE_keys.lieu_id AS lieu_sortie_id,
					medecin_sejour_id,
					COALESCE(tiers_payant_1_id,0) AS tiers_payant_1_id,
					COALESCE(tiers_payant_2_id,0) AS tiers_payant_2_id,
					(SELECT MIN(oid) FROM activite[PX].t_tiers_payant WHERE code = 'PATIENTS') AS tiers_payant_0_id,
					0::bigint AS tiers_payant_22_id,
					COALESCE(ghs_id,0) AS ghs_id,
					COALESCE(ghm_id,0) AS ghm_id,
					0::bigint AS ghs_bebe1_id,
					0::bigint AS ghs_bebe2_id,
					0::bigint AS ghs_bebe3_id,
					DATE(DA_DIM_VALID) AS date_groupage,
					CASE RPH_ETAT
						WHEN 6 THEN 'R'
						WHEN 7 THEN 'A'
						WHEN 8 THEN 'C'
						ELSE ''::text 
					END AS etat,
					CASE WHEN RPH_ETAT > 0 THEN RPH_MODIFIED ELSE NULL END AS date_etat,
					COALESCE(CH_CP_DEMANDEE,'0') AS code_cp_demandee,
					0::numeric AS est_budget_global,
					'0'::text AS est_sans_facturation,
					0::bigint AS provider_id,
					w_DAT_IDENTITE.code_postal_id
				FROM w_DAT_DA
					JOIN prod_web100t.PATIENTS ON DA_PATIENT = PAT_ID
					LEFT JOIN w_SGN_NMCL_DATA w_SGN_NMCL_DATA_MODEENTREE ON 
						SEJ_MODE_ENTREE = w_SGN_NMCL_DATA_MODEENTREE.ND_INVARIANT_OID AND 
						w_SGN_NMCL_DATA_MODEENTREE.NMCL_IDENT = 'MODEENTREE'
					LEFT JOIN w_SGN_NMCL_DATA w_SGN_NMCL_DATA_MODESORTIE ON 
						SEJ_MODE_SORTIE = w_SGN_NMCL_DATA_MODESORTIE.ND_INVARIANT_OID AND 
						w_SGN_NMCL_DATA_MODESORTIE.NMCL_IDENT = 'MODESORTIE'
					JOIN w_REGUL_MOUVEMENTS_SORTIE ON w_DAT_DA.DA_OID = w_REGUL_MOUVEMENTS_SORTIE.DA_OID
					JOIN w_REGUL_MOUVEMENTS_SORTIE_keys ON w_REGUL_MOUVEMENTS_SORTIE.key = w_REGUL_MOUVEMENTS_SORTIE_keys.key
					LEFT JOIN w_DAT_GROUPAGE ON DA_NUMERO = RSS_NO_HOSPIT
					LEFT JOIN w_DAT_CONDITIONS_HEB ON PHASE_OID = CH_SEJOUR
					LEFT JOIN w_DAT_IDENTITE ON IDT_DA = w_DAT_DA.DA_OID
					LEFT JOIN w_DAT_DA_type_sejour ON w_DAT_DA.DA_OID = w_DAT_DA_type_sejour.DA_OID;


				-- correction mode de sortie
				UPDATE w_sejours
				SET mode_sortie = ''
				WHERE mode_sortie != ALL (ARRAY(SELECT code from base.t_modes_sortie)::text[])
				;
				-- correction mode entree 
				UPDATE w_sejours
				SET mode_entree = ''
				WHERE mode_entree != ALL (ARRAY(SELECT code from base.t_modes_entree)::text[])
				;			

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

				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_13');
				
				INSERT INTO activite[PX].p_sejours (
					finess,
					oid,
					code_original,
					no_sejour,
					no_patient,
					code_sexe,
					date_entree,
					heure_entree,
					mode_entree,
					provenance,
					date_sortie,
					heure_sortie,
					mode_sortie,
					destination,
					code_sorti,
					code_prevu,
					type_sejour,
					mode_traitement_id,
					lieu_sortie_id,
					medecin_sejour_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_0_id,
					tiers_payant_22_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					date_groupage,
					ghm_id,
					etat,
					date_etat,
					code_cp_demandee,
					est_budget_global,
					est_sans_facturation,
					provider_id,
					code_postal_id
				) 
				SELECT 
					finess,
					sejour_id,
					code_original,
					no_sejour,
					no_patient,
					code_sexe,
					date_entree,
					heure_entree,
					mode_entree,
					provenance,
					date_sortie,
					heure_sortie,
					mode_sortie,
					destination,
					code_sorti,
					code_prevu,
					type_sejour,
					mode_traitement_id,
					lieu_sortie_id,
					medecin_sejour_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_0_id,
					tiers_payant_22_id,
					ghs_id,
					ghs_bebe1_id,
					ghs_bebe2_id,
					ghs_bebe3_id,
					date_groupage,
					ghm_id,
					etat,
					date_etat,
					code_cp_demandee,
					est_budget_global,
					est_sans_facturation,
					provider_id,
					code_postal_id
				FROM w_sejours ;

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

				UPDATE activite[PX].p_sejours
				SET etat = ''
				WHERE etat = 'I' AND 
					no_sejour NOT IN (SELECT no_sejour FROM activite.t_sejour WHERE est_ignore = '1') AND
					'[PX]' = '';
				
				-- Médecin séjour forcé
				UPDATE activite[PX].p_sejours
				SET medecin_sejour_id = t_sejour.medecin_sejour_id
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					t_sejour.medecin_sejour_id <> 0 AND
					p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
					'[PX]' = '';
			
				
				-- recréation index

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

				-- transferts d'établissements 
				INSERT INTO base.t_etablissements (code, texte, texte_court)
				SELECT
					ND_CODE,
					ND_LIB,
					ND_LIB
				FROM 
					w_SGN_NMCL_DATA
				WHERE 1=1 AND
					NMCL_IDENT = 'FINESS' AND
					ND_INVARIANT_OID IN (SELECT DISTINCT MVT_AUTRE_ETS FROM prod_web100t.REGUL_MOUVEMENTS) AND
					ND_CODE NOT IN (SELECT CODE FROM base.t_etablissements)
				;
				
				INSERT INTO activite[PX].p_sejours_transferts (sejour_id, provenance_id, destination_id)
				SELECT 
					p_sejours.oid,
					MIN(CASE WHEN MVT_TYPE = 1 THEN t_etablissements.oid ELSE null END) AS provenance_id,
					MIN(CASE WHEN MVT_TYPE = 2 THEN t_etablissements.oid ELSE null END) AS destination_id
				FROM
					activite[PX].p_sejours
					JOIN prod_web100t.DAT_SEJOUR ON SEJ_DA = code_original
					JOIN prod_web100t.REGUL_MOUVEMENTS ON MVT_SEJ_OID = PHASE_OID
					LEFT JOIN w_SGN_NMCL_DATA ON MVT_AUTRE_ETS = ND_INVARIANT_OID AND NMCL_IDENT = 'FINESS'
					LEFT JOIN base.t_etablissements ON ND_CODE = code
				WHERE 1!=1 OR
					MVT_AUTRE_ETS != 0 
				GROUP BY 1
				;
				
				-- Assurance
				SELECT base.cti_execute(
				'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(ARRAY[CASE WHEN IDT_TYPE = ''AMO'' THEN ''1'' ELSE ''2'' END::text,IDT_NOM]))[2] AS nom_assure, 
					(MAX(ARRAY[CASE WHEN IDT_TYPE = ''AMO'' THEN ''1'' ELSE ''2'' END::text,IDT_PRENOM]))[2] AS prenom_assure,
					MAX(p_sejours.tiers_payant_0_id),
					MAX(p_sejours.tiers_payant_1_id),
					MAX(CASE WHEN AMO_MATRICULE_BENEF <> '''' THEN AMO_MATRICULE_BENEF ELSE AMO_MATRICULE END) AS matricule_1,
					MAX(p_sejours.tiers_payant_2_id),
					MAX(CASE WHEN AMC_MATRICULE <> '''' THEN AMO_MATRICULE ELSE AMC_NUM_CONTRAT END) AS matricule_2,
					MAX(p_sejours.tiers_payant_22_id),
					''''::text AS matricule_22
				FROM prod_web100t.DAT_IDENTITE
				JOIN prod_web100t.DAT_DA ON IDT_DA = DA_OID
				JOIN prod_web100t.PATIENTS ON DA_PATIENT = PAT_ID
				LEFT JOIN prod_web100t.DAT_ASSURE_AMO ON DA_ASSURE_AMO = AMO_OID
				LEFT JOIN prod_web100t.DAT_ASSURE_AMC ON DA_ASSURE_AMC_1 = AMC_OID
				JOIN activite[PX].p_sejours ON code_original = DA_OID
				WHERE IDT_TYPE = ANY(ARRAY[''AMO'',''AMC''])
				GROUP BY 1',1)
				FROM pg_tables 
				WHERE schemaname = 'prod_web100t' AND tablename = 'dat_assure_amo'
				;
			
			]]></sqlcmd>
		</NODE>

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

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


				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS AS
				SELECT
					nextval('w_REGUL_MOUVEMENTS_seq'::regclass) AS sequence, 

					DA_OID,

					MVT_TYPE,

					MVT_DATE,
					date(MVT_DATE) AS MVT_DATE_DAT,
					extract('hour' FROM MVT_DATE) * 10000 + extract('minute' FROM MVT_DATE) * 100 + extract('second' FROM MVT_DATE)  AS MVT_DATE_TIM,
					'2099/12/31'::timestamp without time zone AS MVT_DATE_FIN,
					date('2099/12/31')::date AS MVT_DATE_FIN_DAT,
					000000::numeric(6, 0) AS MVT_DATE_FIN_TIM,


					SEJ_SPECIALITE,
					MVT_UF_SOIN,
					MVT_UF_GEO,
					MVT_LIT,

					0::bigint AS MVT_TYPE_before,
					0::bigint AS MVT_UF_SOIN_before,
					0::bigint AS MVT_UF_GEO_before,
					
					0::bigint AS MVT_TYPE_next,
					0::bigint AS MVT_UF_SOIN_next,
					0::bigint AS MVT_UF_GEO_next,

					SEJ_SPECIALITE || '|' ||
					MVT_UF_SOIN::text || '|' ||
					MVT_UF_GEO::text || '|' ||
					MVT_LIT::text
					 AS key
				FROM 
					(SELECT w_DAT_DA.*, REGUL_MOUVEMENTS.*
					FROM w_DAT_DA
						JOIN w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS ON PHASE_OID = MVT_SEJ_OID AND MVT_TYPE IN (1,2,4)
					WHERE (DA_STATUT IN (3,4) AND MVT_DATE <= DA_DATE_TIME_FIN OR
						DA_STATUT NOT IN (3,4)
						)
					ORDER BY MVT_SEJ_OID, MVT_DATE, MVT_INDEX) subview;



				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_keys;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_keys AS
				SELECT 
					key,
					MVT_UF_SOIN,
					SEJ_SPECIALITE,
					MVT_UF_GEO,
					MVT_LIT,

					0::bigint AS lieu_id,
					''::text AS dmt_code,
					''::text AS mode_traitement_code,
					''::text AS chambre_particuliere
				FROM w_REGUL_MOUVEMENTS
				WHERE MVT_TYPE <> 2
				GROUP BY 1,2,3,4,5;

				UPDATE w_REGUL_MOUVEMENTS_keys SET
					mode_traitement_code = w_NMCL_UNITEFONCTIONNELLE.mode_traitement_code,
					dmt_code = w_NMCL_UNITEFONCTIONNELLE.dmt_code
				FROM w_NMCL_UNITEFONCTIONNELLE
				WHERE w_NMCL_UNITEFONCTIONNELLE.WEB100T_OID = MVT_UF_SOIN;




				INSERT INTO activite[PX].t_lieux(
							code_original_1, code_original_2, code_original_3, code_original_4, code_original_6)
				SELECT MVT_UF_SOIN, SEJ_SPECIALITE, MVT_UF_GEO, MVT_LIT, MVT_UF_SOIN
				FROM w_REGUL_MOUVEMENTS_keys
					LEFT JOIN activite[PX].t_lieux ON (
						code_original_1 = MVT_UF_SOIN AND
						code_original_2 = SEJ_SPECIALITE AND
						code_original_3 = MVT_UF_GEO AND
						code_original_4 = MVT_LIT AND
						code_original_6 = MVT_UF_SOIN
					)
				WHERE t_lieux.oid IS NULL
				GROUP BY 1,2,3,4,5;


				



				UPDATE w_REGUL_MOUVEMENTS_keys
					set lieu_id = t_lieux.oid
				FROM activite[PX].t_lieux
				WHERE code_original_1 = MVT_UF_SOIN AND
						code_original_2 = SEJ_SPECIALITE AND
						code_original_3 = MVT_UF_GEO AND
						code_original_4 = MVT_LIT AND
						code_original_6 = MVT_UF_SOIN;


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

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

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

				UPDATE activite[PX].t_lieux SET
					lit_id = COALESCE(t_lits.oid,0)
				FROM
					activite[PX].t_lits
				WHERE code_original_3 || '-' || code_original_4 = t_lits.code_original AND
					t_lieux.lit_id <> COALESCE(t_lits.oid,0)
					;
					
				UPDATE w_REGUL_MOUVEMENTS_keys
				SET chambre_particuliere = t_lits.chambre_particuliere
				FROM activite[PX].t_lieux
				JOIN activite[PX].t_lits ON lit_id = t_lits.oid
				WHERE w_REGUL_MOUVEMENTS_keys.lieu_id = t_lieux.oid;


				CREATE INDEX w_REGUL_MOUVEMENTS_i1
					ON w_REGUL_MOUVEMENTS
					USING btree
					(key);



				-- calcul date fin

				UPDATE w_REGUL_MOUVEMENTS
				SET MVT_DATE_FIN = CASE WHEN w_REGUL_MOUVEMENTS_next.MVT_TYPE <> 2 THEN w_REGUL_MOUVEMENTS_next.MVT_DATE - interval '1 second' ELSE w_REGUL_MOUVEMENTS_next.MVT_DATE END,
					MVT_DATE_FIN_DAT = date(CASE WHEN w_REGUL_MOUVEMENTS_next.MVT_TYPE <> 2 THEN w_REGUL_MOUVEMENTS_next.MVT_DATE - interval '1 second' ELSE w_REGUL_MOUVEMENTS_next.MVT_DATE END),
					MVT_DATE_FIN_TIM = extract('hour' FROM CASE WHEN w_REGUL_MOUVEMENTS_next.MVT_TYPE <> 2 THEN w_REGUL_MOUVEMENTS_next.MVT_DATE - interval '1 second' ELSE w_REGUL_MOUVEMENTS_next.MVT_DATE END) * 10000 + 
							extract('minute' FROM CASE WHEN w_REGUL_MOUVEMENTS_next.MVT_TYPE <> 2 THEN w_REGUL_MOUVEMENTS_next.MVT_DATE - interval '1 second' ELSE w_REGUL_MOUVEMENTS_next.MVT_DATE END) * 100 + 
							extract('second' FROM CASE WHEN w_REGUL_MOUVEMENTS_next.MVT_TYPE <> 2 THEN w_REGUL_MOUVEMENTS_next.MVT_DATE - interval '1 second' ELSE w_REGUL_MOUVEMENTS_next.MVT_DATE END),
					MVT_TYPE_next = w_REGUL_MOUVEMENTS_next.MVT_TYPE,
					MVT_UF_SOIN_next = w_REGUL_MOUVEMENTS_next.MVT_UF_SOIN,
					MVT_UF_GEO_next = w_REGUL_MOUVEMENTS_next.MVT_UF_GEO
				FROM w_REGUL_MOUVEMENTS w_REGUL_MOUVEMENTS_next
				WHERE w_REGUL_MOUVEMENTS.DA_OID = w_REGUL_MOUVEMENTS_next.DA_OID
					AND w_REGUL_MOUVEMENTS.sequence = w_REGUL_MOUVEMENTS_next.sequence - 1;



				-- calcul mvt avant

				UPDATE w_REGUL_MOUVEMENTS
				SET 
					MVT_TYPE_before = w_REGUL_MOUVEMENTS_before.MVT_TYPE,
					MVT_UF_SOIN_before = w_REGUL_MOUVEMENTS_before.MVT_UF_SOIN,
					MVT_UF_GEO_before = w_REGUL_MOUVEMENTS_before.MVT_UF_GEO
				FROM w_REGUL_MOUVEMENTS w_REGUL_MOUVEMENTS_before
				WHERE w_REGUL_MOUVEMENTS.DA_OID = w_REGUL_MOUVEMENTS_before.DA_OID
					AND w_REGUL_MOUVEMENTS.sequence = w_REGUL_MOUVEMENTS_before.sequence + 1
					AND w_REGUL_MOUVEMENTS.MVT_TYPE <> 2;


				UPDATE w_DAT_DA SET
					dup_type_sejour = p_sejours.type_sejour,
					dup_code_prevu = p_sejours.code_prevu,
					dup_sejour_id = p_sejours.oid,
					dup_no_sejour = p_sejours.no_sejour,
					dup_medecin_sejour_id = p_sejours.medecin_sejour_id,
					dup_etat = p_sejours.etat
				FROM activite[PX].p_sejours
				WHERE DA_OID = p_sejours.code_original;

				-- creation mouvements par jour
				CREATE INDEX w_REGUL_MOUVEMENTS_i2
					ON w_REGUL_MOUVEMENTS
					USING btree
					(DA_OID);
					
				CREATE INDEX w_REGUL_MOUVEMENTS_i3
					ON w_REGUL_MOUVEMENTS
					USING btree
					(MVT_DATE_DAT);
					
				VACUUM ANALYSE w_REGUL_MOUVEMENTS 
				;
				VACUUM ANALYSE w_DAT_DA 
				;
				VACUUM ANALYSE w_REGUL_MOUVEMENTS_keys
				;

				DROP TABLE IF EXISTS w_mouvements_sejour;
				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_REGUL_MOUVEMENTS.DA_OID,
					w_DAT_DA.dup_no_sejour AS no_sejour,
					w_DAT_DA.dup_sejour_id AS sejour_id,
					sequence,
					p_calendrier.date, 
					p_calendrier.jour_semaine,
					p_calendrier.is_weekend,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT THEN MVT_DATE_TIM ELSE 0 END AS heure_debut,
					CASE WHEN p_calendrier.date = MVT_DATE_FIN_DAT THEN MVT_DATE_FIN_TIM ELSE 240000 END AS heure_fin,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 1 AND w_DAT_DA.dup_type_sejour = '1' THEN 1 ELSE 0 END AS nb_entrees_directes,
					CASE WHEN p_calendrier.date = MVT_DATE_FIN_DAT AND MVT_TYPE_next = 2 AND w_DAT_DA.dup_type_sejour = '1' THEN 1 ELSE 0 END AS nb_sorties_directes,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 1 AND w_DAT_DA.dup_type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_entree,
					CASE WHEN p_calendrier.date = MVT_DATE_FIN_DAT AND MVT_TYPE_next = 2 AND w_DAT_DA.dup_type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_sortie,
					CASE WHEN w_DAT_DA.dup_type_sejour = '1' THEN '1' ELSE '0' END AS est_jour_hospitalisation,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 1 AND w_DAT_DA.dup_type_sejour = '2' THEN 1 ELSE 0 END AS nb_ambulatoires,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 1 AND w_DAT_DA.dup_type_sejour = '3' THEN 1 ELSE 0 END AS nb_externes,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 1 AND w_DAT_DA.dup_type_sejour <> '9' THEN
						CASE WHEN dmt_code IN ('303', '307', '308', '401', '402', '403', '404', '405', '406', '407', '408', '409') THEN 1
							WHEN SEJ_URGENCE = 1 THEN 1
						ELSE 0 END
					ELSE 0 END AS nb_urgences,
					0 as nb_seances,

					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 4 AND w_DAT_DA.dup_type_sejour = '1' AND w_REGUL_MOUVEMENTS.MVT_UF_SOIN <> MVT_UF_SOIN_before THEN 1 ELSE 0 END AS nb_entrees_mutation_service,
					CASE WHEN p_calendrier.date = MVT_DATE_FIN_DAT AND MVT_TYPE_next = 4 AND w_DAT_DA.dup_type_sejour = '1' AND w_REGUL_MOUVEMENTS.MVT_UF_SOIN <> MVT_UF_SOIN_next THEN 1 ELSE 0 END AS nb_sorties_mutation_service,
					CASE WHEN p_calendrier.date = MVT_DATE_DAT AND MVT_TYPE = 4 AND w_DAT_DA.dup_type_sejour = '1' AND w_REGUL_MOUVEMENTS.MVT_UF_GEO <> MVT_UF_GEO_before THEN 1 ELSE 0 END AS nb_entrees_mutation_etage,
					CASE WHEN p_calendrier.date = MVT_DATE_FIN_DAT AND MVT_TYPE_next = 4 AND w_DAT_DA.dup_type_sejour = '1' AND w_REGUL_MOUVEMENTS.MVT_UF_GEO <> MVT_UF_GEO_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 w_DAT_DA.dup_type_sejour = '1' AND (p_calendrier.date <> MVT_DATE_FIN_DAT OR MVT_TYPE_next = 2) THEN 1 ELSE 0 END AS nb_jours_js_inclus,
					CASE WHEN w_DAT_DA.dup_type_sejour = '1' AND p_calendrier.date <> MVT_DATE_FIN_DAT THEN 1 ELSE 0 END AS nb_jours_js_non_inclus,

					CASE WHEN w_DAT_DA.dup_type_sejour IN ('1','2') AND chambre_particuliere = 'O' THEN '1' ELSE '0' END AS est_chambre_particuliere,
					CASE WHEN w_DAT_DA.dup_type_sejour IN ('1','2') AND chambre_particuliere = 'O' AND (p_calendrier.date <> MVT_DATE_FIN_DAT OR MVT_TYPE_next = 2) THEN 1 ELSE 0 END AS nb_chambres_particulieres,

					0::numeric AS nb_bebes,

					lieu_id,

					w_DAT_DA.dup_medecin_sejour_id as medecin_sejour_id,

					CASE WHEN w_DAT_DA.dup_code_prevu = '1' OR p_calendrier.date > date(now()) THEN '1' ELSE '0' END AS est_mouvement_previsionnel

				FROM w_REGUL_MOUVEMENTS 
					JOIN w_DAT_DA ON w_DAT_DA.DA_OID = w_REGUL_MOUVEMENTS.DA_OID
					JOIN w_REGUL_MOUVEMENTS_keys ON w_REGUL_MOUVEMENTS.key = w_REGUL_MOUVEMENTS_keys.key
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN MVT_DATE_DAT AND MVT_DATE_FIN_DAT AND p_calendrier.date <= date(now()) + interval '1 month'
				WHERE MVT_TYPE <> 2
					AND w_DAT_DA.dup_etat = ''
					AND (w_DAT_DA.dup_type_sejour NOT IN ('3') OR (w_DAT_DA.dup_type_sejour IN ('3') AND MVT_TYPE = 1 AND p_calendrier.date = MVT_DATE_DAT))
					AND (w_DAT_DA.dup_code_prevu <> '1' AND p_calendrier.date <= date(now()) OR p_calendrier.date >= date(now()))
				ORDER BY sequence, p_calendrier.date;

				-- bébés
				DROP TABLE IF EXISTS w_CCAM_bebes;
				
				CREATE TEMP TABLE w_CCAM_bebes AS
				SELECT
					p_sejours.no_sejour,
					MAX(CASE WHEN t_actes.texte ILIKE '%multiple%' THEN 2 ELSE 1 END) AS nb_bebes
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN activite[PX].p_sejours ON PREST_DA = p_sejours.code_original
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID
					JOIN base.t_actes ON t_actes.oid = acte_id AND 
						t_actes.code LIKE 'JQG%' AND 
						t_actes.texte ILIKE 'accouchement%' 
                WHERE PREST_DELETED = 0
				GROUP BY 1;

				CREATE INDEX w_CCAM_bebes_i1
				  ON w_CCAM_bebes
				  USING btree
				  (no_sejour);

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





























				-- seances selon prestation Dxx facturées


				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date(FLT_DATE_DEBUT) AS date,
					SUM(CASE WHEN FLT_TOTAL_TTC >= 0 THEN 1 ELSE -1 END) AS nb_seances
				FROM activite[PX].p_sejours
					JOIN prod_web100t.FAC_FACT_TIER ON FT_DA = code_original
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID AND FLT_CODE_PREST BETWEEN 'D01' AND 'D19'
				WHERE FLT_IS_ETS = 1 AND FLT_RECAP <> 0 
				GROUP BY 1,2
				ORDER BY 1,2
				;

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;	
					
					
				-- seances selon Actes (JV Séances Facturés)

				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date(FLT_DATE_DEBUT) AS date,
					SUM(CASE WHEN FLT_TOTAL_TTC >= 0 THEN 1 ELSE -1 END) AS nb_seances
				FROM activite[PX].p_sejours
					JOIN prod_web100t.FAC_FACT_TIER ON FT_DA = code_original
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FLT_FACTURE_TIER = FT_OID 
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID AND 
						(
							ART_CODE_ACTE LIKE 'JV%' AND (ART_LIB_ACTE ILIKE '%seance%' OR ART_LIB_ACTE ILIKE '%séance%' ) OR
							ART_CODE_ACTE LIKE 'JVJF%'
						)
				WHERE FLT_IS_ETS = 0 AND FLT_RECAP <> 0 
				GROUP BY 1,2
				ORDER BY 1,2
				;


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

					
				-- seances selon prestation Dxx saisies
				
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date(PREST_DATE_DEBUT) AS date,
					SUM(CASE WHEN PREST_QUANTITE <> 0 THEN PREST_QUANTITE ELSE 1 END) AS nb_seances
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID
				WHERE ART_CODE BETWEEN 'D01' AND 'D19' AND PREST_DELETED = 0
				GROUP BY 1,2;

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;	
					
					
				-- seances selon actes JV séance saisis
				
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date(PREST_DATE_DEBUT) AS date,
					SUM(CASE WHEN PREST_QUANTITE <> 0 THEN PREST_QUANTITE ELSE 1 END) AS nb_seances
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID AND 
						(
							ART_CODE_ACTE LIKE 'JV%' AND (ART_LIB_ACTE ILIKE '%seance%' OR ART_LIB_ACTE ILIKE '%séance%' ) OR
							ART_CODE_ACTE LIKE 'JVJF%'
						)
				WHERE PREST_DELETED = 0
				GROUP BY 1,2;


				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;	
                    
                -- seances selon K 15 ou 9606
                
                INSERT INTO activite.t_divers (code, description, texte, valeur) 
				SELECT 'K15_SEANCE',
					'Création de séances pour les actes K coefficient 15 : 0 = Jamais, 1 = Toujours, 2 = Sauf pour les séjours Hospitalisation',
					'Règle de création de séances pour les actes K coefficient 15',
					'1'
				WHERE 'K15_SEANCE' NOT IN (SELECT code FROM activite.t_divers)
                ;
				
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS
				SELECT
					p_sejours.no_sejour,
					date(PREST_DATE_DEBUT) AS date,
					1::numeric AS nb_seances
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
                    JOIN activite.t_divers ON t_divers.code = 'K15_SEANCE'
				WHERE PREST_DELETED = 0 AND
					(
                    PREST_CODE = 'K' AND PREST_COEFF = 15 AND t_divers.valeur IN ('1','2') OR
					PREST_CODE IN ('9605','9606')
                    )
				GROUP BY 1,2;

				INSERT INTO w_sejours_seances(no_sejour,date,nb_seances)
				SELECT 
					p_sejours.no_sejour,
					date(PREST_DATE_DEBUT) AS date,
					1::numeric AS nb_seances
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
					JOIN activite.t_divers ON t_divers.code = 'K15_SEANCE'
					LEFT JOIN w_sejours_seances from_ghs ON from_ghs.no_sejour = p_sejours.no_sejour
				WHERE from_ghs.no_sejour IS NULL AND
					PREST_DELETED = 0 AND
					(
                    PREST_CODE = 'K' AND PREST_COEFF = 15 AND t_divers.valeur IN ('1','2') OR
					PREST_CODE IN ('9605','9606')
                    )
				GROUP BY 1,2
				;

				CREATE INDEX  w_sejours_seances_i1
				  ON  w_sejours_seances
				  USING btree
				  (no_sejour);
				  
				UPDATE w_mouvements_sejour
				SET nb_seances = w_sejours_seances.nb_seances
				FROM w_sejours_seances
				WHERE w_sejours_seances.no_sejour = w_mouvements_sejour.no_sejour AND 
					w_sejours_seances.date = w_mouvements_sejour.date AND
					w_mouvements_sejour.nb_seances IS DISTINCT FROM w_sejours_seances.nb_seances;	
                    
                -- seances selon GHS 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 base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
					LEFT JOIN base.t_ghm ON p_sejours.ghm_id = t_ghm.oid
				WHERE date_sortie - date_entree <= 1 AND
					no_sejour != ALL (ARRAY (SELECT DISTINCT no_sejour FROM w_mouvements_sejour WHERE nb_seances > 0)::text[]) 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;	
					
					
				-- Nombre de seances pour forcage service seances
				UPDATE w_mouvements_sejour
				SET nb_seances = 1
				FROM activite[PX].p_sejours
				WHERE p_sejours.no_sejour = w_mouvements_sejour.no_sejour AND 
					p_sejours.date_entree = w_mouvements_sejour.date AND
					p_sejours.type_sejour = '5' AND
					p_sejours.no_sejour != ALL (ARRAY (SELECT no_sejour FROM w_mouvements_sejour WHERE nb_seances <> 0)::text[]);
				
				-- une seule séance par jour pour un séjour de type séance
				UPDATE w_mouvements_sejour
				SET nb_seances = 0
				FROM (
					SELECT 
						w_mouvements_sejour.no_sejour,
						date,
						MAX(w_mouvements_sejour.heure_debut) as heure_debut
					FROM w_mouvements_sejour
					JOIN activite[PX].p_sejours ON sejour_id = p_sejours.oid
					WHERE nb_seances > 0 AND type_sejour = '5'
					GROUP BY 1,2
					HAVING COUNT(*) > 1
					) ref
				WHERE 1=1
					AND ref.no_sejour = w_mouvements_sejour.no_sejour
					AND ref.date = w_mouvements_sejour.date
					AND ref.heure_debut != w_mouvements_sejour.heure_debut
				;
				
                -- Prise en compte mutations ambulatoire
                INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'MUTATIONAMBU',
					'Traitement des mutations / ambulatoire',
					'0',
					'0=Prendre en compte mouvement d''entrée, 1=Prendre en compte mouvement de sortie'
				WHERE 'MUTATIONAMBU' NOT IN (SELECT code FROM activite.t_divers);
                ;
                
                DROP TABLE IF EXISTS w_correction_ambu;
                CREATE TEMP TABLE  w_correction_ambu AS
                SELECT p_mouvements_sejour.no_sejour, 
                    (MAX(Array[COALESCE(t_lits.est_prioritaire,'0'), to_char(heure_debut,'FM000000'),lieu_id::text]))[3]::bigint AS lieu_id,
                    MIN(heure_entree) AS heure_entree, 
                    MAX(heure_sortie) AS heure_sortie
                FROM w_mouvements_sejour p_mouvements_sejour
                JOIN activite[PX].p_sejours ON p_mouvements_sejour.no_sejour = p_sejours.no_sejour 
                JOIN activite.t_divers ON t_divers.code = 'MUTATIONAMBU' ANd t_divers.valeur = '1'
				JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
                JOIN activite[PX].t_lits ON t_lieux.lit_id = t_lits.oid
                WHERE type_sejour = '2' AND code_sorti = '1' AND date_sortie = date_entree
                GROUP BY 1
                HAVING count(*) > 1 AND count(DISTINCT date) = 1 
                ;

                DELETE FROM w_mouvements_sejour p_mouvements_sejour
                WHERE nb_ambulatoires = '0' AND
                    no_sejour = ANY (ARRAY (SELECT DISTINCT no_sejour FROM w_correction_ambu)::text[])
                ;

                UPDATE w_mouvements_sejour p_mouvements_sejour
                SET lieu_id = w_correction_ambu.lieu_id,
                    heure_debut = heure_entree, 
                    heure_fin = heure_sortie
                FROM w_correction_ambu
                WHERE p_mouvements_sejour.no_sejour = w_correction_ambu.no_sejour AND
                    p_mouvements_sejour.nb_ambulatoires = '1'
                    ;
                    
				-- Lignes inutiles
				DELETE FROM w_mouvements_sejour 
				WHERE 
					nb_entrees_directes = 0 AND
					nb_sorties_directes = 0 AND
					est_jour_hospitalisation <> '1' AND
					nb_ambulatoires = 0 AND
					nb_externes = 0 AND
					nb_urgences = 0 AND
					nb_seances = 0 AND
					nb_entrees_mutation_service = 0 AND
					nb_sorties_mutation_service = 0 AND
					nb_entrees_mutation_etage = 0 AND
					nb_sorties_mutation_etage = 0 AND
					nb_entrees_mutation_activite = 0 AND
					nb_sorties_mutation_activite = 0 AND
					nb_entrees_mutation_unite_medicale = 0 AND
					nb_sorties_mutation_unite_medicale = 0 AND
					nb_jours_js_inclus = 0 AND
					nb_jours_js_non_inclus = 0 AND
					est_chambre_particuliere <> '1' AND
					nb_chambres_particulieres = 0 AND
					nb_bebes = 0;
                    
                -- Doublons potentiels
				DELETE FROM w_mouvements_sejour
				USING (
				SELECT 				
					no_sejour, date, heure_debut, MIN(CTID) AS keepCTID
				FROM w_mouvements_sejour
                WHERE heure_fin >= heure_debut
				GROUP BY 1,2,3
				HAVING count(*) > 1) subview
				WHERE w_mouvements_sejour.no_sejour = subview.no_sejour AND
					w_mouvements_sejour.date = subview.date AND
					w_mouvements_sejour.heure_debut = subview.heure_debut AND
					subview.keepCTID <> w_mouvements_sejour.CTID;


				-- Mise en production des mouvements
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_mouvements_sejour_5');
				
				INSERT INTO activite[PX].p_mouvements_sejour(
							sejour_id, no_sejour, date, est_mouvement_previsionnel, nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend)
				SELECT sejour_id, no_sejour, date, est_mouvement_previsionnel ,nb_jours_js_non_inclus, 
							lieu_id, nb_entrees_directes, nb_sorties_directes, 
							nb_urgences, nb_externes, nb_ambulatoires, medecin_sejour_id, 
							nb_jours_js_inclus, nb_seances, nb_entrees_mutation_service, 
							nb_sorties_mutation_service, nb_entrees_mutation_activite, nb_sorties_mutation_activite, 
							nb_entrees_mutation_etage, nb_sorties_mutation_etage, nb_chambres_particulieres, 
							heure_debut, heure_fin, est_jour_entree, est_jour_sortie, est_jour_hospitalisation, 
							est_chambre_particuliere, 
							nb_entrees_mutation_unite_medicale, nb_sorties_mutation_unite_medicale, nb_bebes,
							jour_semaine, is_weekend
				FROM w_mouvements_sejour
				WHERE heure_fin >= heure_debut
				ORDER BY no_sejour, sequence;
	
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_mouvements_sejour_5');

				-- Lieux de sortie

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

				UPDATE activite[PX].p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite[PX].p_mouvements_sejour 
					WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour 
						AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL) ;
				
				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE lieu_sortie_id IS NULL ;
				
				
				UPDATE activite[PX].p_sejours SET lieu_sortie_id = 0
					WHERE p_sejours.code_prevu = '1' AND (p_sejours.lieu_sortie_id = 0 OR lieu_sortie_id IS NULL);
					
					
				UPDATE activite[PX].p_sejours
				SET code_sorti = '1'
				FROM activite[PX].p_mouvements_sejour 
				WHERE p_sejours.no_sejour = p_mouvements_sejour.no_sejour AND
					code_sorti = '0' AND
					(nb_ambulatoires > 0 OR nb_externes > 0) AND 
					date_sortie <= now();
					
				UPDATE activite[PX].p_sejours
				SET type_sejour = '5'
                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
					);
					
					
					
					
					
				-- Forcage service selon etage
				UPDATE activite[PX].t_lieux
				SET service_facturation_id = t_etages.service_force_id
				FROM activite[PX].t_lits
				JOIN activite[PX].t_etages ON etage_id = t_etages.oid
				WHERE lit_id = t_lits.oid AND
					service_force_id <> 0 AND 
					service_facturation_id IS DISTINCT FROM t_etages.service_force_id;
										
										
			]]></sqlcmd>
		</NODE>

	</NODE>

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

		<NODE label="Corrections données facturation en entrée">
			<sqlcmd><![CDATA[

				-- Le numero de facture devient text
				ALTER TABLE prod_web100t.FAC_FACTURE ALTER FACT_NUMERO TYPE text;
				
                UPDATE prod_web100t.FAC_FACTURE
                SET FACT_NUMERO =  'x'||fact_oid::text
                WHERE FACT_NUMERO IS NULL OR trim(FACT_NUMERO) = '' OR FACT_NUMERO = '0' 
                ;				
                
				-- numéro de facture = 6 caractères minimum (compléter avec des 0)
				UPDATE prod_web100t.FAC_FACTURE
				SET FACT_NUMERO = lpad(FACT_NUMERO,6,'0')
				WHERE length(FACT_NUMERO) < 6;
				
				-- Suffixe AV aux avoirs
				UPDATE prod_web100t.FAC_FACTURE
				SET FACT_NUMERO = FACT_NUMERO || '-AV'
				WHERE FACT_NUMERO NOT LIKE '%AV' AND
					(FACT_TOTAL_ETS < 0 OR FACT_TOTAL_HO < 0);
			
				
				-- Correction des numéros de factures en double
				SELECT base.cti_execute(
					'UPDATE prod_web100t.FAC_FACTURE
					SET FACT_NUMERO = FAC_FACTURE.FACT_NUMERO || ''.'' || subview.count::text
					FROM (
						SELECT FACT_NUMERO,
							count(*) AS count,
							(MAX(Array[FACT_DATE::text || FACT_TYPE, FACT_OID::text]))[2]::bigint AS FACT_OID
						FROM prod_web100t.FAC_FACTURE
						JOIN w_DAT_DA ON FACT_DA = DA_OID
						GROUP BY 1
						HAVING count(*) > 1
						) subview
					WHERE FAC_FACTURE.FACT_OID = subview.FACT_OID',20);

		
			]]></sqlcmd>
		</NODE>

		<NODE label="Entêtes">

			<sqlcmd><![CDATA[

				-- Extraction réglements
				DROP TABLE IF EXISTS w_FAC_RGLMT_DETAILS;
				CREATE TEMP TABLE w_FAC_RGLMT_DETAILS AS
				SELECT RD_FACT_TIER,
					SUM(CASE WHEN RD_ETS = 1 THEN RD_MONTANT ELSE 0 END) AS RD_MONTANT_ETS,
					SUM(CASE WHEN RD_ETS <> 1 AND FLT_IS_DIRECT = 0 THEN RD_MONTANT ELSE 0 END) AS RD_MONTANT_HON,
					MAX(CASE WHEN RD_ETS = 1 THEN FR_DATE_ENC ELSE NULL END) AS FR_DATE_ENC_ETS,
					MAX(CASE WHEN RD_ETS <> 1 AND FLT_IS_DIRECT = 0 THEN FR_DATE_ENC ELSE NULL END) AS FR_DATE_ENC_HON
				FROM w_DAT_DA
					JOIN prod_web100t.FAC_RGLMT_DETAILS ON RD_DA = DA_OID
					JOIN prod_web100t.FAC_REGLEMENTS ON FR_OID = RD_REGLEMENT
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON RD_FACT_LINE = FLT_OID
				GROUP BY 1;

				ALTER TABLE w_FAC_RGLMT_DETAILS ADD CONSTRAINT w_FAC_RGLMT_DETAILS_pkey PRIMARY KEY(RD_FACT_TIER);
				
				-- Extraction règlements si paiement direct comptabilisé
				DROP TABLE IF EXISTS w_FAC_DIRECT_compta;
				CREATE TEMP TABLE w_FAC_DIRECT_compta AS
				SELECT FLT_FACTURE_TIER,
					SUM(FLT_TOTAL_TTC) AS FLT_TOTAL_TTC
				FROM prod_web100t.FAC_FACT_LIGNE_TIER
				WHERE FLT_IS_ETS = 0 AND
					FLT_IS_DIRECT = -1
				GROUP BY 1
				;

				ALTER TABLE w_FAC_DIRECT_compta ADD CONSTRAINT w_FAC_DIRECT_compta_pkey PRIMARY KEY(FLT_FACTURE_TIER);
				


				DROP TABLE IF EXISTS w_ENV_FACTURE;
				CREATE TEMP TABLE w_ENV_FACTURE AS
				SELECT FACT_OID,
					MAX(CASE WHEN ENV_TYPE_TIER = 'AMO' THEN COALESCE(ENV_TELETRANS, ENV_CREATED) ELSE NULL END) AS ENV_TELETRANS_AMO,
					MAX(CASE WHEN ENV_TYPE_TIER = 'AMC' THEN COALESCE(ENV_TELETRANS, ENV_CREATED) ELSE NULL END) AS ENV_TELETRANS_AMC,
                    MAX(CASE WHEN ENV_TYPE_TIER = 'AMD' THEN COALESCE(ENV_TELETRANS, ENV_CREATED) ELSE NULL END) AS ENV_TELETRANS_AMD,
					MAX(FACT_DATE) AS ENV_TELETRANS_CLI
				FROM prod_web100t.FAC_FACTURE
					JOIN prod_web100t.FAC_FACT_TIER ON FT_FACTURE = FACT_OID
					LEFT JOIN prod_web100t.ENV_FACTURE ON FT_OID = EF_FACTURE
					LEFT JOIN prod_web100t.ENV_ENVOI ON ENV_OID = EF_ENVOI
				GROUP BY 1;

				ALTER TABLE w_ENV_FACTURE ADD CONSTRAINT w_ENV_FACTURE_pkey PRIMARY KEY(FACT_OID);


				DROP TABLE IF EXISTS w_FAC_FACTURE_od;
				CREATE TEMP TABLE w_FAC_FACTURE_od AS
				SELECT FAC_FACTURE.FACT_OID, 
					CASE 
						WHEN FAC_FACTURE.FACT_TYPE = 2 AND FAC_FACTURE.FACT_TYPE <> FAC_FACTURE_PRED.FACT_TYPE THEN FAC_FACTURE_PRED.FACT_NUMERO
						WHEN FAC_FACTURE.FACT_TYPE <> 2 AND FAC_FACTURE.FACT_TYPE <> FAC_FACTURE_NEXT.FACT_TYPE THEN FAC_FACTURE_NEXT.FACT_NUMERO
						ELSE NULL END AS FACT_NUMERO_OD
				FROM prod_web100t.FAC_FACTURE 
					LEFT JOIN prod_web100t.FAC_FACTURE FAC_FACTURE_PRED ON FAC_FACTURE.FACT_PRED_FACTURE = FAC_FACTURE_PRED.FACT_OID
					LEFT JOIN prod_web100t.FAC_FACTURE FAC_FACTURE_NEXT ON FAC_FACTURE.FACT_NEXT_FACTURE = FAC_FACTURE_NEXT.FACT_OID
				WHERE FAC_FACTURE.FACT_PRED_FACTURE <> 0 OR FAC_FACTURE.FACT_NEXT_FACTURE <> 0;

				ALTER TABLE w_FAC_FACTURE_od ADD CONSTRAINT w_FAC_FACTURE_od_pkey PRIMARY KEY(FACT_OID);
				
				
				-- Date de comptabilisation
				DROP TABLE IF EXISTS w_FAC_FACTURE_vente;
				CREATE TEMP TABLE w_FAC_FACTURE_vente AS
				SELECT FAC_FACTURE.FACT_OID, 
					MAX(FACT_TOTAL_ETS) AS w_FACT_TOTAL_ETS,
					MAX(FACT_TOTAL_HO) AS w_FACT_TOTAL_HO,
					MAX(FACT_DATE) AS w_FACT_DATE,
					COALESCE(MIN(CASE 
						WHEN LNK_TYPE = 'FACT' THEN ECR_DATE
						ELSE NULL END)
						,'20991231') AS ECR_DATE
				FROM prod_web100t.FAC_FACTURE 
					LEFT JOIN w_CPT_ECRITURE_source_OP_LINK ON 
										FACT_OID = ECR_REF_OID AND
										ECR_REF_TYPE = 'FACTURE' AND
										LNK_TYPE IN ('FACT') AND
										(
											ECR_TYPE IN ('CLIENT','IMPAYE','VENTE-DIRECTE','VENTE-DEP','VENTE-HON') AND LNK_ERROR = '' OR
											LNK_JOURNAL = 'VE'
										)
				GROUP BY 1;

				ALTER TABLE w_FAC_FACTURE_vente ADD CONSTRAINT w_FAC_FACTURE_vente_pkey PRIMARY KEY(FACT_OID);
				
				-- Forcage date ventes pour facturés non comptabilisés (sur les factures non comptabilisées, placer la date du jour)
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'WEB100T_FORCE_DATE_VENTE',
					'Antériorité date facture (jours) pour forçage date vente si non comptabilisé',
					'3',
					'Antériorité date facture (jours) pour forçage date vente si non comptabilisé'
				WHERE 'WEB100T_FORCE_DATE_VENTE' NOT IN (SELECT code FROM activite.t_divers);
                ;
				
				
				UPDATE w_FAC_FACTURE_vente
				SET ECR_DATE = date(now())
				FROM prod_web100t.FAC_FACTURE 
				JOIN activite.t_divers ON t_divers.code = 'WEB100T_FORCE_DATE_VENTE'
				WHERE FAC_FACTURE.FACT_OID = w_FAC_FACTURE_vente.FACT_OID AND
					ECR_DATE = '20991231' AND
					date(FACT_DATE) >= date(now() - (t_divers.valeur||' day')::interval)
				;
				
				-- Cas spécial de factures additives honoraires qui ne seraient pas trouvées (cf Saint Claude)
				UPDATE w_FAC_FACTURE_vente
				SET ECR_DATE = date_trunc('month',w_FACT_DATE)+interval '1 month' - interval '1 day'
				WHERE date(ECR_DATE) = '20991231' AND
					w_FACT_TOTAL_ETS = 0 AND
					w_FACT_TOTAL_HO <> 0 
				;

				
				DROP TABLE IF EXISTS w_FAC_FACTURE_cpt;
				CREATE TEMP TABLE w_FAC_FACTURE_cpt AS
				SELECT
					FACT_OID,

					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER <> 'ETS' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_ETS,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_ETS_CLI,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_ETS_AMO,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_ETS_AMC,
                    SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_ETS_AMD,

					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER <> 'ETS' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_HON,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_HON_CLI,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_HON_AMO,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_HON_AMC,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS FLT_TOTAL_CPT_HON_AMD,
					
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER <> 'ETS' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_CLI,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMO,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMC,
                    SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMD,

					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER <> 'ETS' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_CLI,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMO,
					SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMC,
                    SUM(CASE WHEN COALESCE(ECR_DATE,'20991231') <> '20991231' AND FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN 0-FLT_IMPAYE ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMD

				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN w_FAC_FACTURE_vente ON FLT_FACTURE = FACT_OID
				WHERE FLT_RECAP <> 0 
				GROUP BY 1;

				ALTER TABLE w_FAC_FACTURE_cpt ADD CONSTRAINT w_FAC_FACTURE_cpt_pkey PRIMARY KEY(FACT_OID);




				DROP TABLE IF EXISTS w_FAC_FACTURE;
				CREATE TEMP TABLE w_FAC_FACTURE AS
				SELECT FAC_FACTURE.FACT_OID,
					FAC_FACTURE.FACT_NUMERO,
					FAC_FACTURE.FACT_DA,
					FAC_FACTURE.FACT_TYPE,
					FAC_FACTURE.FACT_PERIODE,
					FAC_FACTURE.FACT_DATE,

					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FT_ORGANISME::text ELSE '' END) AS FT_ORGANISME_AMO,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FT_ORGANISME::text ELSE '' END) AS FT_ORGANISME_AMC,
                    MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FT_ORGANISME::text ELSE '' END) AS FT_ORGANISME_AMD,

					SUM(CASE WHEN FT_TYPE_TIER <> 'ETS' THEN FT_TOTAL_ETS ELSE 0 END) AS FACT_TOTAL_ETS,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FT_TOTAL_ETS ELSE 0 END) AS FT_TOTAL_ETS_AMO,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FT_TOTAL_ETS ELSE 0 END) AS FT_TOTAL_ETS_AMC,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FT_TOTAL_ETS ELSE 0 END) AS FT_TOTAL_ETS_AMD,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FT_TOTAL_ETS ELSE 0 END) AS FT_TOTAL_ETS_CLI,
                    
					SUM(CASE WHEN FT_TYPE_TIER <> 'ETS' THEN FT_TOTAL_HO ELSE 0 END) AS FACT_TOTAL_HO,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FT_TOTAL_HO ELSE 0 END) AS FT_TOTAL_HO_AMO,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FT_TOTAL_HO ELSE 0 END) AS FT_TOTAL_HO_AMC,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FT_TOTAL_HO ELSE 0 END) AS FT_TOTAL_HO_AMD,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FT_TOTAL_HO ELSE 0 END) AS FT_TOTAL_HO_CLI,
                    					
					'20991231'::date AS ENV_TELETRANS,	
					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN COALESCE(ENV_TELETRANS_AMO,'20991231') ELSE '00010101' END) AS ENV_TELETRANS_AMO,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN COALESCE(ENV_TELETRANS_AMC,'20991231') ELSE '00010101' END) AS ENV_TELETRANS_AMC,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN COALESCE(ENV_TELETRANS_AMD,'20991231') ELSE '00010101' END) AS ENV_TELETRANS_AMD,
					MAX(CASE WHEN FT_TYPE_TIER = 'CLI' THEN COALESCE(ENV_TELETRANS_CLI,'20991231') ELSE '00010101' END) AS ENV_TELETRANS_CLI,
                    
					'1'::text AS ENV_Q_TELETRANS,
					'1'::text AS ENV_Q_TELETRANS_AMO,
					'1'::text AS ENV_Q_TELETRANS_AMC,
					'1'::text AS ENV_Q_TELETRANS_AMD,
					'1'::text AS ENV_Q_TELETRANS_CLI,
                    
					SUM(COALESCE(RD_MONTANT_ETS,0)) AS RD_MONTANT_ETS,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN COALESCE(RD_MONTANT_ETS,0) ELSE 0 END) AS RD_MONTANT_ETS_AMO,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN COALESCE(RD_MONTANT_ETS,0) ELSE 0 END) AS RD_MONTANT_ETS_AMC,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN COALESCE(RD_MONTANT_ETS,0) ELSE 0 END) AS RD_MONTANT_ETS_AMD,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN COALESCE(RD_MONTANT_ETS,0) ELSE 0 END) AS RD_MONTANT_ETS_CLI,
                    					
					SUM(COALESCE(RD_MONTANT_HON,0)+COALESCE(FLT_TOTAL_TTC,0)) AS RD_MONTANT_HON,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN COALESCE(RD_MONTANT_HON,0)+COALESCE(FLT_TOTAL_TTC,0) ELSE 0 END) AS RD_MONTANT_HON_AMO,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN COALESCE(RD_MONTANT_HON,0)+COALESCE(FLT_TOTAL_TTC,0) ELSE 0 END) AS RD_MONTANT_HON_AMC,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN COALESCE(RD_MONTANT_HON,0)+COALESCE(FLT_TOTAL_TTC,0) ELSE 0 END) AS RD_MONTANT_HON_AMD,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN COALESCE(RD_MONTANT_HON,0)+COALESCE(FLT_TOTAL_TTC,0) ELSE 0 END) AS RD_MONTANT_HON_CLI,
                    					
					MAX(GREATEST(COALESCE(FR_DATE_ENC_ETS,'00010101'), COALESCE(FR_DATE_ENC_HON,'00010101'))) AS FR_DATE_ENC,

					MAX(COALESCE(FR_DATE_ENC_ETS,'00010101')) AS FR_DATE_ENC_ETS,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN COALESCE(FR_DATE_ENC_ETS,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_ETS_AMO,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN COALESCE(FR_DATE_ENC_ETS,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_ETS_AMC,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN COALESCE(FR_DATE_ENC_ETS,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_ETS_AMD,
					MAX(CASE WHEN FT_TYPE_TIER = 'CLI' THEN COALESCE(FR_DATE_ENC_ETS,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_ETS_CLI,
                    					
					MAX(COALESCE(FR_DATE_ENC_HON,'00010101')) AS FR_DATE_ENC_HON,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN COALESCE(FR_DATE_ENC_HON,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_HON_AMO,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN COALESCE(FR_DATE_ENC_HON,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_HON_AMC,
                    MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN COALESCE(FR_DATE_ENC_HON,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_HON_AMD,
					MAX(CASE WHEN FT_TYPE_TIER = 'CLI' THEN COALESCE(FR_DATE_ENC_HON,'00010101') ELSE '00010101' END) AS FR_DATE_ENC_HON_CLI
					

				FROM w_DAT_DA
					JOIN prod_web100t.FAC_FACTURE ON FACT_DA = DA_OID
					LEFT JOIN prod_web100t.FAC_FACT_TIER ON FT_FACTURE = FAC_FACTURE.FACT_OID
					LEFT JOIN w_FAC_RGLMT_DETAILS ON FT_OID = RD_FACT_TIER
					LEFT JOIN w_FAC_DIRECT_compta ON FT_OID = FLT_FACTURE_TIER
					LEFT JOIN w_ENV_FACTURE ON FT_FACTURE = w_ENV_FACTURE.FACT_OID
				GROUP BY 1,2,3,4,5,6
				ORDER BY 1;

				ALTER TABLE w_FAC_FACTURE ADD CONSTRAINT w_FAC_FACTURE_pkey PRIMARY KEY(FACT_OID);


				UPDATE w_FAC_FACTURE 
				SET ENV_TELETRANS_AMO = FACT_DATE,
					ENV_Q_TELETRANS_AMO = '0'
				WHERE ENV_TELETRANS_AMO IN ('20991231', '00010101') AND FT_TOTAL_ETS_AMO = 0 AND FT_TOTAL_HO_AMO = 0;

				UPDATE w_FAC_FACTURE 
				SET ENV_Q_TELETRANS_AMO = '0'
				WHERE ENV_TELETRANS_AMO IN ('20991231', '00010101') ;

				UPDATE w_FAC_FACTURE 
				SET ENV_TELETRANS_AMC = FACT_DATE,
					ENV_Q_TELETRANS_AMC = '0'
				WHERE ENV_TELETRANS_AMC IN ('20991231', '00010101') AND FT_TOTAL_ETS_AMC = 0 AND FT_TOTAL_HO_AMC = 0;

				UPDATE w_FAC_FACTURE 
				SET ENV_Q_TELETRANS_AMC = '0'
				WHERE ENV_TELETRANS_AMC IN ('20991231', '00010101') ;
				
				UPDATE w_FAC_FACTURE 
				SET ENV_TELETRANS_AMD = FACT_DATE,
					ENV_Q_TELETRANS_AMD = '0'
				WHERE ENV_TELETRANS_AMD IN ('20991231', '00010101') AND FT_TOTAL_ETS_AMD = 0 AND FT_TOTAL_HO_AMD = 0;

				UPDATE w_FAC_FACTURE 
				SET ENV_Q_TELETRANS_AMD = '0'
				WHERE ENV_TELETRANS_AMD IN ('20991231', '00010101') ;
	

				UPDATE w_FAC_FACTURE 
				SET ENV_TELETRANS = GREATEST(ENV_TELETRANS_AMO,ENV_TELETRANS_AMC,ENV_TELETRANS_AMD,ENV_TELETRANS_CLI);


				UPDATE w_FAC_FACTURE 
				SET ENV_Q_TELETRANS = '0'
				WHERE ENV_TELETRANS IN ('20991231', '00010101') ;
				
				-- Montants honoraires comptabilisés en clinique
				-- Ces montants ne sont pas compté en montant facturé chez Web100T. Il faut les changer de type dans les totaux
				
				DROP TABLE IF EXISTS w_FAC_FACTURE_HON_ETS;
				CREATE TEMP TABLE w_FAC_FACTURE_HON_ETS AS
				SELECT FAC_FACTURE.FACT_OID,
				SUM(FLT_TOTAL_TTC) AS HON_ETS,
				SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS HON_ETS_AMO,
				SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS HON_ETS_AMC,
				SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS HON_ETS_AMD,
				SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS HON_ETS_CLI
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN prod_web100t.FAC_FACTURE  ON FLT_FACTURE = FACT_OID
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
				WHERE FLT_IS_ETS = 1 AND LI_TYPE_B2 = '4' AND FLT_RECAP <> 0 
				GROUP BY 1;
				
				UPDATE w_FAC_FACTURE SET
					FACT_TOTAL_ETS = FACT_TOTAL_ETS - HON_ETS,
					FT_TOTAL_ETS_AMO = FT_TOTAL_ETS_AMO - HON_ETS_AMO,
					FT_TOTAL_ETS_AMC = FT_TOTAL_ETS_AMC - HON_ETS_AMC,
					FT_TOTAL_ETS_AMD = FT_TOTAL_ETS_AMD - HON_ETS_AMD,
					FT_TOTAL_ETS_CLI = FT_TOTAL_ETS_CLI - HON_ETS_CLI,
                    FACT_TOTAL_HO = FACT_TOTAL_HO + HON_ETS,
					FT_TOTAL_HO_AMO = FT_TOTAL_HO_AMO + HON_ETS_AMO,
					FT_TOTAL_HO_AMC = FT_TOTAL_HO_AMC + HON_ETS_AMC,
                    FT_TOTAL_HO_AMD = FT_TOTAL_HO_AMD + HON_ETS_AMD,
					FT_TOTAL_HO_CLI = FT_TOTAL_HO_CLI + HON_ETS_CLI
				FROM w_FAC_FACTURE_HON_ETS
				WHERE w_FAC_FACTURE_HON_ETS.FACT_OID = w_FAC_FACTURE.FACT_OID;
			

			
				-- Traitement des impayés comptabilisés en ventes
				DROP TABLE IF EXISTS w_FAC_FACT_LIGNE_TIER_IMPAYE;
				CREATE TEMP TABLE w_FAC_FACT_LIGNE_TIER_IMPAYE AS
				SELECT 
					FI_FACTURE AS FACT_IMPAYE_OID, 
					to_char(FI_DATE,'YYMM') AS MOIS_IMPAYE,
					FIL_CREANCE AS FLT_IMPAYE_OID,
					FI_COMPTA,
					date(MAX(FI_DATE)) AS ECR_IMPAYE_DATE, 

					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_CLI,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMO,
					SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMC,
                    SUM(CASE WHEN FLT_IS_ETS = 1 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_ETS_AMD,

					SUM(CASE WHEN FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON,
					SUM(CASE WHEN FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'CLI' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_CLI,
					SUM(CASE WHEN FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMO' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMO,
					SUM(CASE WHEN FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMC' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMC,
                    SUM(CASE WHEN FLT_IS_ETS = 0 AND FLT_IS_DIRECT <= 0 AND FT_TYPE_TIER = 'AMD' THEN 0-FIL_MONTANT ELSE 0 END) AS FLT_TOTAL_IMPAYE_HON_AMD
				FROM prod_web100t.FAC_FACT_IMPAYE
				JOIN prod_web100t.FAC_FACT_IMPAYE_LINE ON FIL_IMPAYE = FAC_FACT_IMPAYE.FI_OID
				JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON FIL_CREANCE = FLT_OID
				JOIN prod_web100t.FAC_FACT_TIER ON FI_FACT_TIER = FT_OID
				JOIN w_FAC_FACTURE ON FI_FACTURE = FACT_OID
				GROUP BY 1,2,3,4
				ORDER BY 1,2,3;
				
				DROP TABLE IF EXISTS w_FAC_FACT_IMPAYE;
				CREATE Temp table w_FAC_FACT_IMPAYE AS
				SELECT
					FACT_IMPAYE_OID, 
					MOIS_IMPAYE,
					FI_COMPTA,
					MAX(ECR_IMPAYE_DATE) AS ECR_IMPAYE_DATE, 

					SUM(FLT_TOTAL_IMPAYE_ETS) AS FT_TOTAL_IMPAYE_ETS,
					SUM(FLT_TOTAL_IMPAYE_ETS_CLI) AS FT_TOTAL_IMPAYE_ETS_CLI,
					SUM(FLT_TOTAL_IMPAYE_ETS_AMO) AS FT_TOTAL_IMPAYE_ETS_AMO,
					SUM(FLT_TOTAL_IMPAYE_ETS_AMC) AS FT_TOTAL_IMPAYE_ETS_AMC,
                    SUM(FLT_TOTAL_IMPAYE_ETS_AMD) AS FT_TOTAL_IMPAYE_ETS_AMD,

					SUM(FLT_TOTAL_IMPAYE_HON) AS FT_TOTAL_IMPAYE_HON,
					SUM(FLT_TOTAL_IMPAYE_HON_CLI) AS FT_TOTAL_IMPAYE_HON_CLI,
					SUM(FLT_TOTAL_IMPAYE_HON_AMO) AS FT_TOTAL_IMPAYE_HON_AMO,
					SUM(FLT_TOTAL_IMPAYE_HON_AMC) AS FT_TOTAL_IMPAYE_HON_AMC,
					SUM(FLT_TOTAL_IMPAYE_HON_AMD) AS FT_TOTAL_IMPAYE_HON_AMD
				FROM w_FAC_FACT_LIGNE_TIER_IMPAYE
				GROUP BY 1,2,3;



				DROP TABLE IF EXISTS w_factures;
				CREATE TEMP TABLE w_factures AS
				SELECT
						w_FAC_FACTURE.FACT_OID,

						nextval('activite[PX].s_factures'::regclass) AS oid,
						no_sejour,
						p_sejours.oid AS sejour_id,
						p_sejours.lieu_sortie_id,
						FACT_NUMERO AS no_facture,
						
						FACT_NUMERO AS no_facture_reference,
						0::bigint AS facture_reference_id,
						COALESCE(FACT_NUMERO_OD,'') AS no_facture_od_avoir,
						0::bigint AS facture_od_avoir_id,
						
						0::bigint AS IMPAYE,
						
						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,
						p_sejours.tiers_payant_0_id,
						
						COALESCE(PF_DEBUT,date_entree) AS date_debut,
						COALESCE(PF_FIN,date_sortie) AS date_fin,
						CASE 
							WHEN FACT_TYPE = 1 AND FACT_NUMERO_OD IS NOT NULL THEN 'X'
							WHEN FACT_TYPE = 4 AND FACT_NUMERO_OD IS NOT NULL THEN 'X'
							WHEN FACT_TYPE = 1 THEN '0'
							WHEN FACT_TYPE = 2 THEN '1'
							WHEN FACT_TYPE = 4 THEN '2'
							ELSE '0' END AS type_facture,
						
						'1'::text AS code_facture,
						w_FAC_FACTURE.FACT_DATE AS date_facture,
						0::numeric AS delai_facture,
						
						CASE WHEN ECR_DATE <> '20991231' THEN '1'::text ELSE '0'::text END AS code_vente,
						ECR_DATE AS date_vente,
						extract('year' FROM ECR_DATE) * 100 + extract('month' FROM ECR_DATE) AS mois_vente,
						
						'0'::text AS code_cloture,

						'20991231'::date AS date_encours,
						
						''::text AS particularite_t2a,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id,
						p_sejours.code_cp_demandee,

						0::numeric AS nb_rejets,

						FACT_TOTAL_ETS AS montant_facture_c,
						FACT_TOTAL_HO AS montant_facture_h,
						FT_TOTAL_ETS_CLI AS montant_facture_0_c,
						FT_TOTAL_HO_CLI AS montant_facture_0_h,
						FT_TOTAL_ETS_AMO AS montant_facture_1_c,
						FT_TOTAL_HO_AMO AS montant_facture_1_h,
						FT_TOTAL_ETS_AMC AS montant_facture_2_c,
						FT_TOTAL_HO_AMC AS montant_facture_2_h,
                        FT_TOTAL_ETS_AMD AS montant_facture_22_c,
						FT_TOTAL_HO_AMD AS montant_facture_22_h,
						0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
						
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_ETS,0) AS montant_comptabilise_c,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_HON,0) AS montant_comptabilise_h,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_ETS_CLI,0) AS montant_comptabilise_0_c,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_HON_CLI,0) AS montant_comptabilise_0_h,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_ETS_AMO,0) AS montant_comptabilise_1_c,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_HON_AMO,0) AS montant_comptabilise_1_h,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_ETS_AMC,0) AS montant_comptabilise_2_c,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_HON_AMC,0) AS montant_comptabilise_2_h,
                        COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_ETS_AMD,0) AS montant_comptabilise_22_c,
						COALESCE(w_FAC_FACTURE_cpt.FLT_TOTAL_CPT_HON_AMD,0) AS montant_comptabilise_22_h,
						0::numeric AS montant_comptabilise_budget_global_c,
						
						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,
						
						ENV_TELETRANS AS date_expedition,
						ENV_TELETRANS_CLI AS date_expedition_0,
						ENV_TELETRANS_AMO AS date_expedition_1,
						ENV_TELETRANS_AMC AS date_expedition_2,
						ENV_TELETRANS_AMD AS date_expedition_22,
						ENV_Q_TELETRANS_CLI AS code_expedie_0,
						ENV_Q_TELETRANS_AMO AS code_expedie_1,
						ENV_Q_TELETRANS_AMC AS code_expedie_2,
						ENV_Q_TELETRANS_AMD AS code_expedie_22,
						''::text AS no_bordereau_0,
						''::text AS no_bordereau_1,
						''::text AS no_bordereau_2,
						''::text AS no_bordereau_22,
						0::numeric AS 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,
						
						RD_MONTANT_ETS AS montant_regle_c,
						RD_MONTANT_HON AS montant_regle_h,
						RD_MONTANT_ETS_CLI AS montant_regle_0_c,
						RD_MONTANT_HON_CLI AS montant_regle_0_h,
						RD_MONTANT_ETS_AMO AS montant_regle_1_c,
						RD_MONTANT_HON_AMO AS montant_regle_1_h,
						RD_MONTANT_ETS_AMC AS montant_regle_2_c,
						RD_MONTANT_HON_AMC AS montant_regle_2_h,
                        RD_MONTANT_ETS_AMD AS montant_regle_22_c,
						RD_MONTANT_HON_AMD AS montant_regle_22_h,
						
						FR_DATE_ENC AS date_solde,
						FR_DATE_ENC_ETS AS date_solde_c,
						FR_DATE_ENC_HON AS date_solde_h,
						FR_DATE_ENC_ETS_CLI AS date_solde_0_c,
						FR_DATE_ENC_HON_CLI AS date_solde_0_h,
						FR_DATE_ENC_ETS_AMO AS date_solde_1_c,
						FR_DATE_ENC_HON_AMO AS date_solde_1_h,
						FR_DATE_ENC_ETS_AMC AS date_solde_2_c,
						FR_DATE_ENC_HON_AMC AS date_solde_2_h,
						FR_DATE_ENC_ETS_AMD AS date_solde_22_c,
						FR_DATE_ENC_HON_AMD AS date_solde_22_h,
						0::numeric AS delai_solde,
						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,
						
						'00010101'::date AS date_solde_reference,
						'00010101'::date AS date_solde_reference_c,
						'00010101'::date AS date_solde_reference_h,
						'00010101'::date AS date_solde_reference_0_c,
						'00010101'::date AS date_solde_reference_1_c,
						'00010101'::date AS date_solde_reference_2_c,
						'00010101'::date AS date_solde_reference_22_c,
						'00010101'::date AS date_solde_reference_0_h,
						'00010101'::date AS date_solde_reference_1_h,
						'00010101'::date AS date_solde_reference_2_h,
						'00010101'::date AS date_solde_reference_22_h
						
				FROM w_FAC_FACTURE
					JOIN activite[PX].p_sejours ON FACT_DA = p_sejours.code_original AND p_sejours.etat = ''
					LEFT JOIN w_FAC_FACTURE_vente  ON w_FAC_FACTURE.FACT_OID = w_FAC_FACTURE_vente.FACT_OID
					LEFT JOIN w_FAC_FACTURE_cpt  ON w_FAC_FACTURE.FACT_OID = w_FAC_FACTURE_cpt.FACT_OID
					LEFT JOIN prod_web100t.FAC_PERIODE_FACTU ON FACT_PERIODE = PF_OID
					LEFT JOIN w_FAC_FACTURE_od  ON w_FAC_FACTURE.FACT_OID = w_FAC_FACTURE_od.FACT_OID
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON FT_ORGANISME_AMO = t_tiers_payant_1.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON FT_ORGANISME_AMC = t_tiers_payant_2.code_original
                    LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_22 ON FT_ORGANISME_AMD = t_tiers_payant_22.code_original;
					
				ANALYSE w_factures
				;
				
				CREATE INDEX w_factures_i1 ON w_factures USING btree (FACT_OID)
				;

					
				-- Facture fictive pour impayés
				INSERT INTo w_factures
				SELECT
						w_FAC_FACTURE.FACT_OID,

						nextval('activite[PX].s_factures'::regclass) AS oid,
						no_sejour,
						p_sejours.oid AS sejour_id,
						p_sejours.lieu_sortie_id,
						FACT_NUMERO || '-IM' || FI_COMPTA::text AS no_facture,
						
						FACT_NUMERO AS no_facture_reference,
						0::bigint AS facture_reference_id,
						FACT_NUMERO AS no_facture_od_avoir,
						0::bigint AS facture_od_avoir_id,
						
						FI_COMPTA AS IMPAYE,
						
						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,
						p_sejours.tiers_payant_0_id,
						
						COALESCE(PF_DEBUT,date_entree) AS date_debut,
						COALESCE(PF_FIN,date_sortie) AS date_fin,
						'X' AS type_facture,
						
						'1'::text AS code_facture,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_facture,
						0::numeric AS delai_facture,
						
						'1' AS code_vente,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_vente,
						extract('year' FROM w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE) * 100 + extract('month' FROM w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE) AS mois_vente,
						
						'0'::text AS code_cloture,

						'20991231'::date AS date_encours,
						
						''::text AS particularite_t2a,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id,
						p_sejours.code_cp_demandee,

						0::numeric AS nb_rejets,

						0 AS montant_facture_c,
						0 AS montant_facture_h,
						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::numeric AS montant_facture_22_c,
						0::numeric AS montant_facture_22_h,
						0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
						0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
						
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_ETS AS montant_comptabilise_c,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_HON AS montant_comptabilise_h,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_ETS_CLI AS montant_comptabilise_0_c,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_HON_CLI AS montant_comptabilise_0_h,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_ETS_AMO AS montant_comptabilise_1_c,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_HON_AMO AS montant_comptabilise_1_h,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_ETS_AMC AS montant_comptabilise_2_c,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_HON_AMC AS montant_comptabilise_2_h,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_ETS_AMD AS montant_comptabilise_22_c,
						w_FAC_FACT_IMPAYE.FT_TOTAL_IMPAYE_HON_AMD AS montant_comptabilise_22_h,
						0::numeric AS montant_comptabilise_budget_global_c,
						
						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_expedition,
						'20991231'::date AS date_expedition_0,
						'20991231'::date AS date_expedition_1,
						'20991231'::date AS date_expedition_2,
						'20991231'::date AS date_expedition_22,
						'0'::text AS code_expedie_0,
						'0'::text AS code_expedie_1,
						'0'::text AS code_expedie_2,
						'0'::text AS code_expedie_22,
						''::text AS no_bordereau_0,
						''::text AS no_bordereau_1,
						''::text AS no_bordereau_2,
						''::text AS no_bordereau_22,
						0::numeric AS 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 montant_regle_c,
						0::numeric AS montant_regle_h,
						0::numeric AS montant_regle_0_c,
						0::numeric AS montant_regle_0_h,
						0::numeric AS montant_regle_1_c,
						0::numeric AS montant_regle_1_h,
						0::numeric AS montant_regle_2_c,
						0::numeric AS montant_regle_2_h,
						0::numeric AS montant_regle_22_c,
						0::numeric AS montant_regle_22_h,
						
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_c,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_h,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_0_c,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_0_h,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_1_c,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_1_h,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_2_c,
						w_FAC_FACT_IMPAYE.ECR_IMPAYE_DATE AS date_solde_2_h,
						'00010101'::date AS date_solde_22_c,
						'00010101'::date AS date_solde_22_h,
						0::numeric AS delai_solde,
						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,
						
						'00010101'::date AS date_solde_reference,
						'00010101'::date AS date_solde_reference_c,
						'00010101'::date AS date_solde_reference_h,
						'00010101'::date AS date_solde_reference_0_c,
						'00010101'::date AS date_solde_reference_1_c,
						'00010101'::date AS date_solde_reference_2_c,
						'00010101'::date AS date_solde_reference_22_c,
						'00010101'::date AS date_solde_reference_0_h,
						'00010101'::date AS date_solde_reference_1_h,
						'00010101'::date AS date_solde_reference_2_h,
						'00010101'::date AS date_solde_reference_22_h
						
				FROM w_FAC_FACTURE
					JOIN activite[PX].p_sejours ON FACT_DA = p_sejours.code_original AND p_sejours.etat = ''
					JOIN w_FAC_FACT_IMPAYE ON w_FAC_FACTURE.FACT_OID = w_FAC_FACT_IMPAYE.FACT_IMPAYE_OID
					LEFT JOIN prod_web100t.FAC_PERIODE_FACTU ON FACT_PERIODE = PF_OID
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_1 ON FT_ORGANISME_AMO = t_tiers_payant_1.code_original
					LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_2 ON FT_ORGANISME_AMC = t_tiers_payant_2.code_original
                    LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant_22 ON FT_ORGANISME_AMD = t_tiers_payant_22.code_original;

				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.no_facture_od_avoir <> '';



				

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



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

				CREATE INDEX w_sejours_facture_reference_i1
					ON w_sejours_facture_reference
					USING btree
					(no_sejour);

				UPDATE w_sejours_facture_reference
				SET facture_id_last = w_factures_references.oid
				FROM w_factures w_factures_references
				WHERE w_sejours_facture_reference.no_facture_last = w_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_last <> w_factures_references.oid;

			
				UPDATE w_sejours_facture_reference
				SET facture_id_reference_last = w_factures_references.oid
				FROM w_factures w_factures_references
				WHERE w_sejours_facture_reference.no_facture_reference_last = w_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_reference_last <> w_factures_references.oid;

				UPDATE w_sejours_facture_reference
				SET facture_id_reference_last_2 = w_factures_references.oid
				FROM w_factures w_factures_references
				WHERE w_sejours_facture_reference.no_facture_reference_last_2 = w_factures_references.no_facture
					AND w_sejours_facture_reference.facture_id_reference_last_2 <> w_factures_references.oid;

				

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

				

				UPDATE w_factures
				SET no_facture_reference = no_facture 
				WHERE (no_facture_reference IS NULL OR no_facture_reference = '');

				
				UPDATE w_factures
				SET type_facture = '0' 
				WHERE w_factures.type_facture = '2' AND
					w_factures.no_facture = w_factures.no_facture_reference;
				
				UPDATE w_factures
				SET type_facture = '2' 
				WHERE w_factures.type_facture = '0' AND
					w_factures.no_facture <> w_factures.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;

				

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

				INSERT INTO activite[PX].p_factures(
						oid,
						no_sejour,
						sejour_id,
						no_facture,
						
						no_facture_reference,
						facture_reference_id,
						no_facture_od_avoir,
						facture_od_avoir_id,
						
						tiers_payant_1_id,
						tiers_payant_2_id,
						tiers_payant_22_id,
						tiers_payant_0_id,
						
						date_debut,
						date_fin,
						type_facture,
						
						code_facture,
						date_facture,
						delai_facture,
						
						code_vente,
						date_vente,
						mois_vente,
						
						code_cloture,

						date_encours,
						
						particularite_t2a,
						ghs_id,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id,
						code_cp_demandee,

						nb_rejets,

						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_facture_c_actes_inclus_dans_sejour,
						montant_facture_h_actes_inclus_dans_sejour,
						
						montant_comptabilise_c,
						montant_comptabilise_h,
						montant_comptabilise_0_c,
						montant_comptabilise_0_h,
						montant_comptabilise_1_c,
						montant_comptabilise_1_h,
						montant_comptabilise_2_c,
						montant_comptabilise_2_h,
						montant_comptabilise_22_c,
						montant_comptabilise_22_h,
						montant_comptabilise_budget_global_c,
						
						montant_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_expedition,
						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,
						delai_expedition,
						delai_expedition_0,
						delai_expedition_1,
						delai_expedition_2,
						delai_expedition_22,
						
						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,
						
						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,
						delai_solde,
						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_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
						
						
						
					)
				SELECT
						oid,
						no_sejour,
						sejour_id,
						no_facture,
						
						no_facture_reference,
						facture_reference_id,
						no_facture_od_avoir,
						facture_od_avoir_id,
						
						tiers_payant_1_id,
						tiers_payant_2_id,
						tiers_payant_22_id,
						tiers_payant_0_id,
						
						date_debut,
						date_fin,
						type_facture,
						
						code_facture,
						date_facture,
						delai_facture,
						
						code_vente,
						date_vente,
						mois_vente,
						
						code_cloture,

						date_encours,
						
						particularite_t2a,
						ghs_id,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id,
						code_cp_demandee,

						nb_rejets,

						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_facture_c_actes_inclus_dans_sejour,
						montant_facture_h_actes_inclus_dans_sejour,
						
						montant_comptabilise_c,
						montant_comptabilise_h,
						montant_comptabilise_0_c,
						montant_comptabilise_0_h,
						montant_comptabilise_1_c,
						montant_comptabilise_1_h,
						montant_comptabilise_2_c,
						montant_comptabilise_2_h,
						montant_comptabilise_22_c,
						montant_comptabilise_22_h,
						montant_comptabilise_budget_global_c,
						
						montant_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_expedition,
						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,
						delai_expedition,
						delai_expedition_0,
						delai_expedition_1,
						delai_expedition_2,
						delai_expedition_22,
						
						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,
						
						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,
						delai_solde,
						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_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
						
				FROM w_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');

	

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


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

			]]></sqlcmd>
		</NODE>

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

				
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[
            
                -- Tarif des UCD saisies sans prix
				SELECT base.cti_execute(
				'UPDATE prod_web100t.DAT_PRESTATIONS_GAP
				SET PREST_MFE_ETS = PREST_QUANTITE * t_ucd_tarifs.prix_unitaire_ttc
				FROM pmsi.t_ucd 
				JOIN pmsi.t_ucd_tarifs ON t_ucd.oid = t_ucd_tarifs.ucd_id
				WHERE prest_mfe_ets = 0 AND
                    PREST_DELETED = 0 AND
					t_ucd.code = PREST_CODE AND
					date(PREST_DATE_DEBUT) BETWEEN t_ucd_tarifs.date_debut AND t_ucd_tarifs.date_fin',1)
				FROM pg_tables 
				WHERE schemaname = 'pmsi' AND tablename = 't_ucd_tarifs'
				;
                
                -- Tarif des lpp saisies sans prix ou avec un prix divisé par 2
				SELECT base.cti_execute(
				'UPDATE prod_web100t.DAT_PRESTATIONS_GAP
				SET PREST_PU = t_lpp_tarifs.prix_unitaire, PREST_MFE_ETS = PREST_QUANTITE * t_lpp_tarifs.prix_unitaire
				FROM pmsi.t_lpp 
				JOIN pmsi.t_lpp_tarifs ON t_lpp.oid = t_lpp_tarifs.lpp_id
				WHERE (
					prest_mfe_ets = 0 OR
					round(base.cti_division(PREST_QUANTITE::numeric * t_lpp_tarifs.prix_unitaire::numeric,PREST_MFE_ETS::numeric),1) = 2
					) AND
                    PREST_DELETED = 0 AND
					t_lpp.code = PREST_CODE AND
					date(PREST_DATE_DEBUT) BETWEEN t_lpp_tarifs.date_debut AND t_lpp_tarifs.date_fin',1)
				FROM pg_tables 
				WHERE schemaname = 'pmsi' AND tablename = 't_lpp_tarifs'
				;

				TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;
				
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id,
					ucd_id,
					lpp_id)
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					date(PREST_DATE_DEBUT) AS date_debut,
					date(COALESCE(PREST_DATE_FIN, PREST_DATE_DEBUT)) AS date_fin,
					CASE WHEN PREST_QUANTITE <> 0 AND ART_CODE NOT IN ('TDE', 'TSE', 'ST1', 'ST2', 'ST3') THEN PREST_QUANTITE ELSE 1 END AS nb_rubrique,
					CASE WHEN PREST_COEFF <> 0 AND PREST_PU <> 0 THEN PREST_COEFF ELSE 1 END AS coefficient,
					rubrique_facturation_id,
					prestation_id,
					CASE
					WHEN PREST_PU <> 0 THEN PREST_PU
					WHEN PREST_QUANTITE <> 0 THEN PREST_MFE_ETS / CASE WHEN ART_CODE NOT IN ('TDE', 'TSE', 'ST1', 'ST2', 'ST3') THEN PREST_QUANTITE ELSE 1 END
					ELSE PREST_MFE_ETS END AS prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id,
					w_ART_ARTICLES.ucd_id,
					w_ART_ARTICLES.lpp_id
				FROM prod_web100t.DAT_PRESTATIONS_GAP
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND type_facture = 'E' AND date(PREST_DATE_DEBUT) BETWEEN date_debut AND date_fin
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID
				WHERE ART_CODE NOT IN ('GHS', 'EXH', 'I01', 'CCAM') AND PREST_MFE_ETS > 0 AND PREST_ENTENTE_DIRECTE = 0 AND PREST_DELETED = 0 AND
					PREST_QUANTITE < 99999 AND
					NOT (PREST_QUANTITE > 1 AND (date(PREST_DATE_FIN) - date(PREST_DATE_DEBUT) + 1) = PREST_QUANTITE )
					;
				
				
                -- Eclatement des prestations par jour
                INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id,
					ucd_id,
					lpp_id)
                SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					p_calendrier.date AS date_debut,
					p_calendrier.date AS date_fin,
					1 AS nb_rubrique,
					CASE WHEN PREST_COEFF <> 0 AND PREST_PU <> 0 THEN PREST_COEFF ELSE 1 END AS coefficient,
					rubrique_facturation_id,
					prestation_id,
					CASE 
						WHEN PREST_PU <> 0 THEN PREST_PU 
						WHEN PREST_QUANTITE <> 0 THEN PREST_MFE_ETS / PREST_QUANTITE
						ELSE PREST_MFE_ETS END AS prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id,
					w_ART_ARTICLES.ucd_id,
					w_ART_ARTICLES.lpp_id
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
					JOIN base.p_calendrier ON p_calendrier.date BETWEEN date(PREST_DATE_DEBUT) AND date(PREST_DATE_FIN)
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND type_facture = 'E' AND p_calendrier.date BETWEEN date_debut AND date_fin
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID
				WHERE ART_CODE NOT IN ('GHS', 'EXH', 'I01', 'CCAM') AND PREST_MFE_ETS > 0 AND PREST_ENTENTE_DIRECTE = 0 AND PREST_DELETED = 0 AND
					PREST_QUANTITE < 99999 AND
					PREST_QUANTITE > 1 AND (date(PREST_DATE_FIN) - date(PREST_DATE_DEBUT) + 1) = PREST_QUANTITE 
                ;
				
				-- Prestation I01 (innovation) venant du PMSI
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					coefficient_mco,
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id)
				SELECT
					p_factures.no_facture,
					MAX(p_factures.oid) AS facture_id,
					MAX(p_sejours.date_entree) AS date_debut,
					MAX(p_sejours.date_sortie) AS date_fin,
					1::numeric AS nb_rubrique,
					1::numeric AS coefficient,
					0.9935::numeric AS coefficient_mco, 
					MAX(t_rubriques_facturation.oid) AS rubrique_facturation_id,
					MAX(t_prestations.oid) AS prestation_id,
					6047::numeric AS prix_unitaire,
					MAX(p_sejours.lieu_sortie_id) AS lieu_id
				FROM prod_web100t.DAT_RUM
					JOIN prod_web100t.SGN_NMCL_DATA ON RUM_NUM_INNOVATION = ND_INVARIANT_OID AND ND_CODE = 'INNOV1441001H'
					JOIN prod_web100t.DAT_RESUME ON RUM_OID = RES_OID
					JOIN prod_web100t.DAT_DA ON RES_NUM = DA_NUMERO
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original  
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND code_facture <> '1'
					JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = 'I01' 
					JOIN activite.t_prestations ON t_prestations.code = 'I01'
				GROUP BY 1
                ;
                
                
                

										
			]]></sqlcmd>
		</NODE>

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

				DROP TABLE IF EXISTS w_FAC_B2_TIER;
				CREATE TEMP TABLE w_FAC_B2_TIER AS
				SELECT 
					B2T_LIGNE,
					MAX(B2T_QUANTITE) AS B2T_QUANTITE,
					base.cti_division(
						SUM(CASE WHEN B2T_QUANTITE <> 0 THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(B2T_DEPASSEMENT)::numeric,
						MAX(B2T_QUANTITE)::numeric
					) AS B2T_PU,
					SUM(B2T_TOTAL_TTC) AS B2T_TOTAL,
					SUM(B2T_DEPASSEMENT) AS B2T_DEPASSEMENT,
					round(base.cti_division(
						SUM(CASE WHEN B2T_TYPE_TIER = 'AMO' THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(CASE WHEN B2T_TYPE_TIER = 'AMO' THEN B2T_DEPASSEMENT ELSE 0 END)::numeric,
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric
					) * 100,0) AS B2T_TAUX_AMO,
					round(base.cti_division(
						SUM(CASE WHEN B2T_TYPE_TIER = 'AMC' THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(CASE WHEN B2T_TYPE_TIER = 'AMC' THEN B2T_DEPASSEMENT ELSE 0 END)::numeric,
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric
					) * 100,0) AS B2T_TAUX_AMC,
					round(base.cti_division(
						SUM(CASE WHEN B2T_TYPE_TIER = 'AMD' THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(CASE WHEN B2T_TYPE_TIER = 'AMD' THEN B2T_DEPASSEMENT ELSE 0 END)::numeric,
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric
					) * 100,0) AS B2T_TAUX_AMD,
					round(base.cti_division(
						SUM(CASE WHEN B2T_TYPE_TIER = 'CLI' THEN B2T_TOTAL_TTC ELSE 0 END)::numeric - SUM(CASE WHEN B2T_TYPE_TIER = 'CLI' THEN B2T_DEPASSEMENT ELSE 0 END)::numeric,
						SUM(B2T_TOTAL_TTC)::numeric - SUM(B2T_DEPASSEMENT)::numeric
					) * 100,0) AS B2T_TAUX_CLI,
					SUM(CASE WHEN B2T_TYPE_TIER = 'AMO' THEN B2T_TOTAL_TTC ELSE 0 END) AS B2T_TOTAL_AMO,
					SUM(CASE WHEN B2T_TYPE_TIER = 'AMC' THEN B2T_TOTAL_TTC ELSE 0 END) AS B2T_TOTAL_AMC,
                    SUM(CASE WHEN B2T_TYPE_TIER = 'AMD' THEN B2T_TOTAL_TTC ELSE 0 END) AS B2T_TOTAL_AMD,
					SUM(CASE WHEN B2T_TYPE_TIER = 'CLI' THEN B2T_TOTAL_TTC ELSE 0 END) AS B2T_TOTAL_CLI
				FROM prod_web100t.FAC_B2_TIER 
				GROUP BY 1
				ORDER BY 1;
				
				ALTER TABLE w_FAC_B2_TIER ADD CONSTRAINT w_FAC_B2_TIER_pkey PRIMARY KEY(B2T_LIGNE);


				-- Comptes par ligne
				
				DROP TABLE IF EXISTS w_LIGNE_CPT;
				CREATE TEMP TABLE w_LIGNE_CPT AS
				SELECT FLT_OID, 
					LI_OID, 
					LI_PRED_LIGNE, 
					LI_NEXT_LIGNE,
					MAX(COALESCE(CPT_OID,0)) AS ECR_COMPTE, 
					MAX(COALESCE(CPT_CODE,'')) AS CPT_CODE,
					0::bigint AS compte_produit_id
				FROM PROD_WEB100T.FAC_FACT_LIGNE_TIER 
				JOIN PROD_WEB100T.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
				LEFT JOIN w_CPT_ECRITURE_source_OP_LINK ON ECR_DATA = LI_OID AND ECR_TYPE = 'PRODUIT_ETS'
				LEFT JOIN PROD_WEB100T.CPT_COMPTES ON ECR_COMPTE = CPT_OID
				WHERE FLT_IS_ETS = 1
				GROUP BY 1,2,3,4;  

				UPDATE w_LIGNE_CPT
				SET ECR_COMPTE = w_LIGNE_CPT_NEXT.ECR_COMPTE, CPT_CODE = w_LIGNE_CPT_NEXT.CPT_CODE 
				FROM w_LIGNE_CPT w_LIGNE_CPT_NEXT
				WHERE w_LIGNE_CPT.ECR_COMPTE = 0 AND
					w_LIGNE_CPT.LI_NEXT_LIGNE = w_LIGNE_CPT_NEXT.LI_OID;

				UPDATE w_LIGNE_CPT
				SET ECR_COMPTE = w_LIGNE_CPT_PRED.ECR_COMPTE, CPT_CODE = w_LIGNE_CPT_PRED.CPT_CODE 
				FROM w_LIGNE_CPT w_LIGNE_CPT_PRED
				WHERE w_LIGNE_CPT.ECR_COMPTE = 0 AND
					w_LIGNE_CPT.LI_PRED_LIGNE = w_LIGNE_CPT_PRED.LI_OID;

				DELETE FROM w_LIGNE_CPT
				WHERE CPT_CODE LIKE '445%';

				UPDATE w_LIGNE_CPT
				SET compte_produit_id = t_compte.oid
				FROM activite[PX].t_compte
				WHERE t_compte.code = CPT_CODE;
				
				ALTER TABLE w_LIGNE_CPT ADD CONSTRAINT w_LIGNE_CPT_pkey PRIMARY KEY(FLT_OID);

		
				-- Table temporaire lignes
				DROP TABLE IF EXISTS w_factures_lignes_c;
				CREATE TEMP TABLE w_factures_lignes_c AS
				SELECT
					FLT_LIGNE_FACTURE,

					w_factures.no_sejour,
					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date_vente,
										
					lieu_sortie_id AS lieu_id,
					1::numeric AS origine_facturation_id,
					
					rubrique_facturation_id,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					0::bigint AS protocole_id,
					COALESCE(w_LIGNE_CPT.compte_produit_id,0::bigint) AS compte_produit_id,
					w_ART_ARTICLES.ucd_id,
					w_ART_ARTICLES.lpp_id,

					date(MIN(FLT_DATE_DEBUT)) AS date_debut,
					date(MAX(FLT_DATE_FIN)) AS date_fin,
					
					MAX(COALESCE(B2T_PU,FLT_TOTAL_TTC)) AS prix_unitaire,
					
					CASE WHEN SUM(FLT_TOTAL_TTC) >= 0 THEN 1 ELSE -1 END * MAX(COALESCE(B2T_QUANTITE,1)) AS nb_rubrique,
					CASE WHEN SUM(FLT_TOTAL_TTC) >= 0 THEN 1 ELSE -1 END * MAX(COALESCE(B2T_QUANTITE,1)) AS nb_prestation,
					1::numeric AS coefficient,
					1::numeric AS coefficient_mco,
					
					MAX(COALESCE(B2T_TAUX_CLI,0)) AS taux_0,
					MAX(COALESCE(B2T_TAUX_AMO,0)) AS taux_1,
					MAX(COALESCE(B2T_TAUX_AMC,0)) AS taux_2,
					MAX(COALESCE(B2T_TAUX_AMD,0)) AS taux_22,
					
					base.cti_division(SUM(FLT_TOTAL_TVA)::numeric , SUM(FLT_TOTAL_TTC)::numeric-SUM(FLT_TOTAL_TVA)::numeric)*100 AS taux_tva,
					
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture,
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' AND FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_0,
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' AND FT_TYPE_TIER IN ('AMO','ETS') THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_1,
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' AND FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_2,
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' AND FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_22,
					SUM(CASE WHEN LI_TYPE_B2 IS DISTINCT FROM '4' AND FT_TYPE_TIER = 'ETS' THEN 0-FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_dma,
					
					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,

					SUM(CASE WHEN code_vente = '1' AND FT_TYPE_TIER <> 'ETS' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise,
					SUM(CASE WHEN code_vente = '1' AND FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_0,
					SUM(CASE WHEN code_vente = '1' AND FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_1,
					SUM(CASE WHEN code_vente = '1' AND FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_2,
					SUM(CASE WHEN code_vente = '1' AND FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_22,
					0::numeric AS montant_comptabilise_budget_global_1,
					
					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::bigint AS rubrique_facture_id,
                    
                    MAX(ART_CODE) AS ART_CODE,
                    MAX(ART_CODE_2) AS ART_CODE_2
                    
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN w_factures ON FLT_FACTURE = FACT_OID AND IMPAYE = 0
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE
					LEFT JOIN w_LIGNE_CPT ON FAC_FACT_LIGNE_TIER.FLT_OID = w_LIGNE_CPT.FLT_OID
				WHERE FLT_IS_ETS = 1 AND FLT_RECAP <> 0
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
				
				
				
				-- Montants impayés
				INSERT INTO w_factures_lignes_c
				SELECT
					FLT_LIGNE_FACTURE,

					w_factures.no_sejour,
					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date_vente,
										
					lieu_sortie_id AS lieu_id,
					1::numeric AS origine_facturation_id,
					
					rubrique_facturation_id,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					0::bigint AS protocole_id,
					COALESCE(w_LIGNE_CPT.compte_produit_id,0::bigint) AS compte_produit_id,
					w_ART_ARTICLES.ucd_id,
					w_ART_ARTICLES.lpp_id,

					date(MIN(FLT_DATE_DEBUT)) AS date_debut,
					date(MAX(FLT_DATE_FIN)) AS date_fin,
					
					MAX(COALESCE(B2T_PU,FLT_TOTAL_TTC)) AS prix_unitaire,
					
					0 AS nb_rubrique,
					0 AS nb_prestation,
					1::numeric AS coefficient,
					1::numeric AS coefficient_mco,
					
					MAX(COALESCE(B2T_TAUX_CLI,0)) AS taux_0,
					MAX(COALESCE(B2T_TAUX_AMO,0)) AS taux_1,
					MAX(COALESCE(B2T_TAUX_AMC,0)) AS taux_2,
					MAX(COALESCE(B2T_TAUX_AMD,0)) AS taux_22,
					
					0::numeric AS taux_tva,
					
					0 AS montant_facture,
					0 AS montant_facture_0,
					0 AS montant_facture_1,
					0 AS montant_facture_2,
					0::numeric AS montant_facture_22,
					0::numeric AS montant_facture_dma,
					
					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,

					SUM(FLT_TOTAL_IMPAYE_ETS) AS montant_comptabilise,
					SUM(FLT_TOTAL_IMPAYE_ETS_CLI) AS montant_comptabilise_0,
					SUM(FLT_TOTAL_IMPAYE_ETS_AMO) AS montant_comptabilise_1,
					SUM(FLT_TOTAL_IMPAYE_ETS_AMC) AS montant_comptabilise_2,
					SUM(FLT_TOTAL_IMPAYE_ETS_AMD) AS montant_comptabilise_22,
					0::numeric AS montant_comptabilise_budget_global_1,
					
					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::bigint AS rubrique_facture_id,
                    
                    MAX(ART_CODE) AS ART_CODE,
                    MAX(ART_CODE_2) AS ART_CODE_2
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN w_FAC_FACT_LIGNE_TIER_IMPAYE ON FAC_FACT_LIGNE_TIER.FLT_OID = FLT_IMPAYE_OID
					JOIN w_factures ON FLT_FACTURE = FACT_OID AND IMPAYE = w_FAC_FACT_LIGNE_TIER_IMPAYE.FI_COMPTA
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE
					LEFT JOIN w_LIGNE_CPT ON FAC_FACT_LIGNE_TIER.FLT_OID = w_LIGNE_CPT.FLT_OID
				WHERE FLT_IS_ETS = 1 AND FLT_RECAP <> 0 AND FLT_TOTAL_IMPAYE_ETS <> 0
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14;
				
				
				
				-- 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 IN ('D11') AND
                    t_prestations.code::text NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL) AND
					t_prestations.code::text NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation WHERE code IS NOT NULL)
                    ;
                    
                DROP TABLE IF EXISTS w_transform_dxx;
                CREATE TEMP TABLE w_transform_dxx AS
                        SELECT p_factures_lignes_c.no_facture,
                    p_factures_lignes_c.CTID AS CTID_source,
                    t_prestations.code,
                    CASE WHEN t_ghs.code IN (9602,9603,9604,9605,9617) THEN t_ghs.code::text ELSE ART_CODE_2 END AS ghs_code,
                    CASE 
                        WHEN t_ghs.code = 9602 THEN 'D18'
                        WHEN t_ghs.code = 9603 THEN 'D19'
                        WHEN t_ghs.code = 9604 THEN 'D17'
                        WHEN t_ghs.code = 9605 THEN 'D09'
                        WHEN t_ghs.code = 9617 THEN 'D10'
                        WHEN ART_CODE_2 = '9602' THEN 'D18'
                        WHEN ART_CODE_2 = '9603' THEN 'D19'
                        WHEN ART_CODE_2 = '9604' THEN 'D17'
                        WHEN ART_CODE_2 = '9605' THEN 'D09'
                        WHEN ART_CODE_2 = '9617' THEN 'D10'
                        ELSE '' END AS dxx_prestation_code
                FROM w_factures_lignes_c p_factures_lignes_c
                JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
                JOIN base.t_ghs ON p_sejours.ghs_id = t_ghs.oid
                JOIN activite.t_prestations ON t_prestations.oid = prestation_id
                JOIN activite.t_divers ON t_divers.code = 'TRANSGHSDXX' AND t_divers.valeur = '1'
                WHERE t_prestations.code = 'GHS' AND 
                    (
                    t_ghs.code IN (9602,9603,9604,9605,9617) OR
                    ART_CODE_2 IN ('9602','9603','9604','9605','9617')
                    );

                CREATE INDEX w_transform_dxx_i1
                          ON w_transform_dxx
                          USING btree
                          (no_facture)
                ;

                UPDATE w_factures_lignes_c p_factures_lignes_c SET
                    prestation_id = t_prestations.oid,
                    rubrique_facturation_id = t_rubriques_facturation.oid
                FROM w_transform_dxx
                JOIN activite.t_prestations ON dxx_prestation_code = t_prestations.code 
                JOIN activite[PX].t_rubriques_facturation ON ghs_code = t_rubriques_facturation.code_original
                WHERE p_factures_lignes_c.no_facture = w_transform_dxx.no_facture AND
                    p_factures_lignes_c.CTID = w_transform_dxx.CTID_source
                ;


				
				-- Eclatement des GHS, GMT et suppléments par jour
				DROP TABLE IF EXISTS w_factures_lignes_sup_c;
				CREATE TEMP TABLE w_factures_lignes_sup_c AS
				SELECT
					w_factures_lignes_c.CTID AS from_CTID,
					t_prestations.code AS prestation_code,
					date(p_sejours.date_entree) AS date_debut_ghs,
					date(p_sejours.date_sortie - interval '1 day') AS date_fin_ghs,
					(date(date_sortie) - date(date_entree)) * CASE WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS nb_prestation_ghs,
					w_factures_lignes_c.*
				FROM w_factures_lignes_c
					JOIN activite[PX].p_sejours ON w_factures_lignes_c.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND 
						(
						code IN ('PJ', 'FJ', 'PHJ','SSM', 'GHS', 'EXH', 'SRC', 'REA', 'STF', 'NN1', 'NN2', 'NN3', 'CP', 'CPC', 'SHO') OR
						t_prestations.type_ventilation_jour = '1'
						)						
				WHERE (nb_prestation > 1 or nb_prestation < -1 OR (t_prestations.code IN ('GHS', 'GMT') AND p_sejours.type_sejour != '5' AND date(date_sortie) - date(date_entree) > 1)) 
				;

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

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_gen;
				CREATE TEMP TABLE w_factures_lignes_sup_c_gen AS
				SELECT
					w_factures_lignes_sup_c.*	
					,date AS new_date_debut
					,date AS new_date_fin
					,CASE WHEN prestation_code IN ('GHS', 'GMT') AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS new_nb_rubrique
					,CASE WHEN prestation_code IN ('GHS', 'GMT') AND date <> date_fin_ghs THEN 0 WHEN nb_prestation < 0 THEN -1 ELSE 1 END AS new_nb_prestation
					,round((montant_facture / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture
					,round((montant_facture_0 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture_0
					,round((montant_facture_1 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture_1
					,round((montant_facture_2 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture_2
					,round((montant_facture_22 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture_22
					,round((montant_facture_dma / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_facture_dma
					,round((montant_comptabilise / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_comptabilise
					,round((montant_comptabilise_0 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_comptabilise_0
					,round((montant_comptabilise_1 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_comptabilise_1
					,round((montant_comptabilise_2 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_comptabilise_2
					,round((montant_comptabilise_22 / ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END))::numeric,2) AS new_montant_comptabilise_22					
				FROM w_factures_lignes_sup_c
					JOIN base.p_calendrier ON date_debut BETWEEN p_calendrier.date - ABS(CASE WHEN prestation_code NOT IN ('GHS', 'GMT') THEN nb_prestation ELSE nb_prestation_ghs END)::integer + 1 
						AND p_calendrier.date 
						AND p_calendrier.date <> date_debut 
				;


				DROP TABLE IF EXISTS w_factures_lignes_sup_c_gen_tot;
				CREATE TEMP TABLE w_factures_lignes_sup_c_gen_tot AS
				SELECT from_CTID,
					SUM(new_nb_rubrique) AS nb_rubrique,
					SUM(new_nb_prestation) AS nb_prestation,
					SUM(new_montant_facture) AS montant_facture,
					SUM(new_montant_facture_0) AS montant_facture_0,
					SUM(new_montant_facture_1) AS montant_facture_1,
					SUM(new_montant_facture_2) AS montant_facture_2,
					SUM(new_montant_facture_22) AS montant_facture_22,
					SUM(new_montant_facture_dma) AS montant_facture_dma,
					SUM(new_montant_comptabilise) AS montant_comptabilise,
					SUM(new_montant_comptabilise_0) AS montant_comptabilise_0,
					SUM(new_montant_comptabilise_1) AS montant_comptabilise_1,
					SUM(new_montant_comptabilise_2) AS montant_comptabilise_2,
					SUM(new_montant_comptabilise_22) AS montant_comptabilise_22
				FROM w_factures_lignes_sup_c_gen
				GROUP BY 1;



				UPDATE w_factures_lignes_c
				SET
					date_fin = w_factures_lignes_c.date_debut,
					nb_rubrique = w_factures_lignes_c.nb_rubrique - w_factures_lignes_sup_c_gen_tot.nb_rubrique,
					nb_prestation = w_factures_lignes_c.nb_prestation - w_factures_lignes_sup_c_gen_tot.nb_prestation,
					montant_facture = w_factures_lignes_c.montant_facture - w_factures_lignes_sup_c_gen_tot.montant_facture,
					montant_facture_0 = w_factures_lignes_c.montant_facture_0 - w_factures_lignes_sup_c_gen_tot.montant_facture_0,
					montant_facture_1 = w_factures_lignes_c.montant_facture_1 - w_factures_lignes_sup_c_gen_tot.montant_facture_1,
					montant_facture_2 = w_factures_lignes_c.montant_facture_2 - w_factures_lignes_sup_c_gen_tot.montant_facture_2,
					montant_facture_22 = w_factures_lignes_c.montant_facture_22 - w_factures_lignes_sup_c_gen_tot.montant_facture_22,
					montant_facture_dma = w_factures_lignes_c.montant_facture_dma - w_factures_lignes_sup_c_gen_tot.montant_facture_dma,
					montant_comptabilise = w_factures_lignes_c.montant_comptabilise - w_factures_lignes_sup_c_gen_tot.montant_comptabilise,
					montant_comptabilise_0 = w_factures_lignes_c.montant_comptabilise_0 - w_factures_lignes_sup_c_gen_tot.montant_comptabilise_0,
					montant_comptabilise_1 = w_factures_lignes_c.montant_comptabilise_1 - w_factures_lignes_sup_c_gen_tot.montant_comptabilise_1,
					montant_comptabilise_2 = w_factures_lignes_c.montant_comptabilise_2 - w_factures_lignes_sup_c_gen_tot.montant_comptabilise_2,
					montant_comptabilise_22 = w_factures_lignes_c.montant_comptabilise_22 - w_factures_lignes_sup_c_gen_tot.montant_comptabilise_22
				FROM w_factures_lignes_sup_c_gen_tot
				WHERE w_factures_lignes_c.CTID = from_CTID;


				INSERT INTO w_factures_lignes_c
				SELECT
					FLT_LIGNE_FACTURE,

					no_sejour,
					no_facture,
					facture_id,
					date_vente,
										
					lieu_id,
					origine_facturation_id,
					
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,
					compte_produit_id,
					ucd_id,
					lpp_id,

					new_date_debut,
					new_date_fin,
					
					prix_unitaire,
					
					new_nb_rubrique,
					new_nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					taux_tva,
					
					new_montant_facture,
					new_montant_facture_0,
					new_montant_facture_1,
					new_montant_facture_2,
					new_montant_facture_22,
					new_montant_facture_dma,
					
					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,

					new_montant_comptabilise,
					new_montant_comptabilise_0,
					new_montant_comptabilise_1,
					new_montant_comptabilise_2,
					new_montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22,
					
					0::bigint AS rubrique_facture_id
				FROM w_factures_lignes_sup_c_gen;
				
				-- arrondi tva
				UPDATE w_factures_lignes_c 
				SET taux_tva = 2.1
				WHERE taux_tva BETWEEN 1.2 AND 3 AND
					taux_tva <> 2.1
				;
				
				UPDATE w_factures_lignes_c 
				SET taux_tva = 5.5
				WHERE taux_tva BETWEEN 4.6 AND 6.4 AND
					taux_tva <> 5.5
				;
				
				UPDATE w_factures_lignes_c 
				SET taux_tva = 10
				WHERE taux_tva BETWEEN 9.1 AND 10.9 AND
					taux_tva <> 10
				;

				UPDATE w_factures_lignes_c 
				SET taux_tva = 20
				WHERE taux_tva >= 15 AND
					taux_tva <> 20
				;
				
				
				-- Lieux d'exécution
				
				
				UPDATE w_factures_lignes_c 
				SET lieu_id = p_mouvements_sejour.lieu_id
				FROM activite[PX].p_mouvements_sejour
				WHERE w_factures_lignes_c.no_sejour = p_mouvements_sejour.no_sejour AND
					w_factures_lignes_c.date_debut = p_mouvements_sejour.date AND 
					(p_mouvements_sejour.heure_fin = 240000 OR p_mouvements_sejour.nb_sorties_directes = 1) AND
					w_factures_lignes_c.lieu_id <> p_mouvements_sejour.lieu_id;
				
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_c');
				
				-- Validation
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_lignes_c_8');

				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					
					lieu_id,
					origine_facturation_id,
					
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					taux_tva,
					
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22

					
				)
				SELECT
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					
					lieu_id,
					origine_facturation_id,
					
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					taux_tva,
					
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_lignes_c;
				
				
				-- DMA SSR
				DROP TABLE IF EXISTS w_factures_lignes_c_dma;
				CREATE TEMP TABLE w_factures_lignes_c_dma AS 
				SELECT *
				FROM w_factures_lignes_c
				WHERE montant_facture_dma <> 0
				;
				
				UPDATE w_factures_lignes_c_dma SET
					nb_rubrique = 0-nb_rubrique,
					nb_prestation = 0-nb_prestation,
					taux_0 = 0,
					taux_2 = 0,
					taux_22 = 0,
					montant_facture = montant_facture_dma,
					montant_facture_1 = montant_facture_dma,
					montant_facture_2 = 0,
					montant_facture_22 = 0,
					montant_facture_0 = 0,
					montant_facture_actes_inclus_dans_sejour = 0,
					montant_facture_0_actes_inclus_dans_sejour = 0,
					montant_facture_1_actes_inclus_dans_sejour = 0,
					montant_facture_2_actes_inclus_dans_sejour = 0,
					montant_facture_22_actes_inclus_dans_sejour = 0,
					montant_comptabilise = 0,
					montant_comptabilise_0 = 0,
					montant_comptabilise_1 = 0,
					montant_comptabilise_2 = 0,
					montant_comptabilise_22 = 0,
					montant_comptabilise_budget_global_1 = 0,
					montant_encours = 0,
					montant_encours_0 = 0,
					montant_encours_1 = 0,
					montant_encours_2 = 0,
					montant_encours_22 = 0
				WHERE montant_facture_dma <> 0
				;
				
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court) 
				SELECT 'DMAM'||code, 'DMAM'||code, 'Diminution SSR ' || code, 'Diminution SSR ' || code
				FROM
				(
				SELECT t_prestations.code AS code
				FROM w_factures_lignes_c_dma
				JOIN activite.t_prestations ON t_prestations.oid = prestation_id
				GROUP BY 1
				) subview
				WHERE ('DMAM'||code) NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				;


				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court) 
				SELECT '*DMAM'||code, 'DMAM'||code, 'Diminution SSR ' || code, 'Diminution SSR ' || code
				FROM
				(
				SELECT t_rubriques_facturation.code AS code
				FROM w_factures_lignes_c_dma
				JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.oid = rubrique_facturation_id
				GROUP BY 1
				) subview
				WHERE ('*DMAM'||code) NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation WHERE code_original IS NOT NULL)
				;
				
				UPDATE w_factures_lignes_c_dma SET
					rubrique_facturation_id = t_rubriques_facturation_dmam.oid,
					rubrique_comptabilisation_id = t_rubriques_facturation_dmam.oid
				FROM activite[PX].t_rubriques_facturation 
				JOIN activite[PX].t_rubriques_facturation t_rubriques_facturation_dmam ON t_rubriques_facturation_dmam.code_original = '*DMAM'||t_rubriques_facturation.code
				WHERE rubrique_facturation_id = t_rubriques_facturation.oid
				;
				UPDATE w_factures_lignes_c_dma SET
					prestation_id = t_prestations_dmam.oid
				FROM activite.t_prestations
				JOIN activite.t_prestations t_prestations_dmam ON t_prestations_dmam.code = 'DMAM'||t_prestations.code
				WHERE prestation_id = t_prestations.oid
				;
				
				INSERT INTO activite[PX].p_factures_lignes_c(
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					
					lieu_id,
					origine_facturation_id,
					
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					taux_tva,
					
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22

					
				)
				SELECT
					no_facture,
					facture_id,
					date_debut,
					date_fin,
					
					lieu_id,
					origine_facturation_id,
					
					rubrique_facture_id,
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,
					compte_produit_id,
					ucd_id,
					lpp_id,
					
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					0::numeric AS taux_tva,
					
					montant_facture,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					montant_comptabilise_0,
					montant_comptabilise_1,
					montant_comptabilise_2,
					montant_comptabilise_22,
					montant_comptabilise_budget_global_1,
					
					montant_encours,
					montant_encours_0,
					montant_encours_1,
					montant_encours_2,
					montant_encours_22
				FROM w_factures_lignes_c_dma
				WHERE montant_facture_dma <> 0
				;
				
				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');

										
			]]></sqlcmd>
		</NODE>

		<NODE label="Compte client Clinique">
			<sqlcmd><![CDATA[
			
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_c_8');

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					facture_id,
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					no_facture,
					facture_id,
					date_vente,
					rubrique_comptabilisation_id,
					prestation_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0::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
				FROM w_factures_lignes_c
				WHERE date_vente IS NOT NULL  AND
					(montant_comptabilise <> 0 OR 
					montant_comptabilise_0 <> 0 OR 
					montant_comptabilise_1 <> 0 OR 
					montant_comptabilise_2 <> 0 OR 
					montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4,5;
				
				
				DROP TABLE IF EXISTS w_CPT_OP_LINK;
				CREATE TEMP TABLE w_CPT_OP_LINK AS
				SELECT LNK_OPERATION,
					MAX(ECR_DATE) AS ECR_DATE
				FROM w_CPT_OP_LINK_source_agg
				JOIN
				(
				SELECT 
					LNK_MASTER_OP, MAX(ECR_DATE) AS ECR_DATE
				FROM w_CPT_ECRITURE_source_OP_LINK
				WHERE LNK_ERROR = '' 
				GROUP BY 1
				) subview ON w_CPT_OP_LINK_source_agg.LNK_MASTER_OP = subview.LNK_MASTER_OP
				GROUP BY 1;
				
				ALTER TABLE  w_CPT_OP_LINK ADD CONSTRAINT w_CPT_OP_LINK_pkey PRIMARY KEY(LNK_OPERATION);
				
				
				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					facture_id,
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					od_non_comptabilise,
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date(COALESCE(ECR_DATE,RD_DATE,FR_DATE_ENC)) AS date_comptable,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					CASE 
						WHEN FR_DATE_DEPOT_GUESS IS NOT NULL AND FR_DATE_ENC IS NULL THEN '1' 
						WHEN RD_CREATED > ECR_UPDATED_MAX THEN '1'
						ELSE '0' END AS od_non_comptabilise,
					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(RD_MONTANT) As montant_regle,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN RD_MONTANT ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN RD_MONTANT ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN RD_MONTANT ELSE 0 END) AS montant_regle_2,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN RD_MONTANT ELSE 0 END) AS montant_regle_22
				FROM prod_web100t.FAC_RGLMT_DETAILS 
					JOIN prod_web100t.FAC_REGLEMENTS ON FR_OID = RD_REGLEMENT
					JOIN w_factures ON RD_FACTURE = FACT_OID AND IMPAYE = 0
					JOIN prod_web100t.FAC_FACT_TIER ON RD_FACT_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON RD_FACT_LINE = FLT_OID
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID
					LEFT JOIN w_CPT_OP_LINK ON RD_COMPTA = LNK_OPERATION
					JOIN w_max_ECR_UPDATED ON 1=1
				WHERE RD_ETS = 1
				GROUP BY 1,2,3,4,5,6;
				
				
				-- Acomptes noemie 85%
				
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation);

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT '*CTI_ACO85', 'ACO85', 'Acomptes 85%', 'Acomptes 85%'
				WHERE '*CTI_ACO85' NOT IN (SELECT code_original FROM activite.t_prestations WHERE code_original IS NOT NULL);
				
				-- Correction tables noemie car quelque fois il manque la reprise d'acompte sur le règlement
				UPDATE prod_web100t.NOE_PAI_FACT
				SET NPF_TOTAL_ACOMPTE = 0-NPF_TOTAL_ACOMPTE_1
				FROM
				(
				SELECT NPF_FACT_TIER, 
					MAX(CASE WHEN NPF_TOTAL_ACOMPTE <> 0 THEN NPF_OID ELSE 0 END) AS NPF_OID_1,
					MAX(CASE WHEN NPF_TOTAL_ACOMPTE <> 0 THEN NPF_TOTAL_ACOMPTE ELSE NULL END) AS NPF_TOTAL_ACOMPTE_1,
					MAX(CASE WHEN NPF_TOTAL_ACOMPTE = 0 THEN NPF_OID ELSE 0 END) AS NPF_OID_2
				FROM prod_web100t.NOE_PAI_FACT
				JOIN prod_web100t.NOE_PAIEMENT ON NPF_PAIEMENT = NP_OID AND NP_PAIEMENT_ETS = 1
				GROUP BY 1
				HAVING count(*) = 2 AND
					SUM(NPF_TOTAL_ACOMPTE) > 0 AND
					MAX(CASE WHEN NPF_TOTAL_ACOMPTE = 0 THEN NPF_OID ELSE 0 END) <> 0
				) subview
				WHERE NPF_OID = NPF_OID_2 AND
					NPF_TOTAL_ACOMPTE = 0
				;

				-- Exploitation des tables noemie
				DROP TABLE IF EXISTS w_NOE_PAI_FACT;
				CREATE TEMP TABLE w_NOE_PAI_FACT AS
				SELECT FACT_NUMERO, 
					NPF_FACT_TIER, 
					NPF_TOTAL_AMO, 
					NPF_TOTAL_ACOMPTE, 
					NPF_PAIEMENT, 
					NP_DATE_COMPTABLE, 
					NP_REGLEMENT,
					date(COALESCE(FR_DATE_ENC,NP_DATE_COMPTABLE)) AS date_imputation, 
					'1'::text AS ok
				FROM prod_web100t.NOE_PAI_FACT
				JOIN prod_web100t.NOE_PAIEMENT ON NPF_PAIEMENT = NP_OID AND NP_PAIEMENT_ETS = 1
				LEFT JOIN prod_web100T.FAC_REGLEMENTS ON NP_REGLEMENT = FR_OID
				JOIN prod_web100t.FAC_FACT_TIER ON NPF_FACT_TIER = FT_OID
				JOIN prod_web100t.FAC_FACTURE ON FT_FACTURE = FACT_OID
				WHERE NPF_TOTAL_ACOMPTE <> 0 AND
					FACT_DA = ANY(SELECT DA_OID FROM prod_web100t.DAT_DA WHERE DA_EG_ENTREE = ANY(SELECT ets_oid FROM w_NMCL_ETABLISSEMENT))
				;

				-- Date imputation reprise acompte selon date encaissement AMO
				UPDATE w_NOE_PAI_FACT
				SET date_imputation = subview.date_imputation
				FROM
				(
				SELECT NPF_PAIEMENT, max(date_imputation) AS date_imputation 
				FROM
				(
					
				SELECT p_factures.no_facture, 
					MAX(NPF_PAIEMENT) AS npf_paiement, 
					MIN(NP_DATE_COMPTABLE), 
					MIN(p_factures_soldes_c.date_comptable) AS date_imputation, 
					date(MIN(p_factures_soldes_c.date_comptable)) - date(MIN(NP_DATE_COMPTABLE)) AS ecart
				FROM w_NOE_PAI_FACT
				JOIN activite[PX].p_factures ON FACT_NUMERO = p_factures.no_facture
				JOIN activite[PX].p_factures_soldes_c ON p_factures_soldes_c.no_facture = p_factures.no_facture
				WHERE p_factures.montant_comptabilise_1_c = p_factures_soldes_c.montant_regle_1 AND
					NPF_TOTAL_ACOMPTE < 0 AND
					NPF_TOTAL_AMO = montant_regle_1
				GROUP BY 1
				HAVING count(*) = 1
				ORDER BY 2,5 desc
				) subview
				GROUP BY 1
				HAVING count(DISTINCT ecart) = 1
				) subview
				WHERE w_NOE_PAI_FACT.NPF_PAIEMENT = subview.NPF_PAIEMENT
				;

				UPDATE w_NOE_PAI_FACT
				SET OK = '0'
				FROM
				(
				SELECT NPF_FACT_TIER, SUM(NPF_TOTAL_ACOMPTE), MAX(NP_DATE_COMPTABLE)
				FROM w_NOE_PAI_FACT
				GROUP BY 1
				HAVING (
						SUM(NPF_TOTAL_ACOMPTE) <> 0 AND MAX(NP_DATE_COMPTABLE) < (now() - interval '1 year') OR
						SUM(NPF_TOTAL_ACOMPTE) < 0 OR 
						SUM(NPF_TOTAL_ACOMPTE) > 0 AND count(*) > 1
						)
				) subview
				WHERE w_NOE_PAI_FACT.NPF_FACT_TIER = subview.NPF_FACT_TIER
				;



				-- Acompte et reprise d'acompte
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures.oid AS facture_id,
					p_factures.no_facture, 
					date_imputation AS date_comptable,
					t_rubriques_facturation.oid AS rubrique_comptabilisation_id, 
					t_prestations.oid 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, 
					NPF_TOTAL_ACOMPTE AS montant_regle, 
					0 AS montant_regle_0, 
					NPF_TOTAL_ACOMPTE AS montant_regle_1, 
					0 AS montant_regle_2,  
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM w_NOE_PAI_FACT
					JOIN activite[PX].p_factures ON FACT_NUMERO = no_facture
					JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = '*CTI_ACO85'
					JOIN activite.t_prestations ON t_prestations.code_original = '*CTI_ACO85'
				WHERE w_NOE_PAI_FACT.ok = '1'
				;
				
				-- Règlement si mouvement non comptabilisé
				INSERT INTO activite[PX].p_factures_soldes_c(
					facture_id,
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures.oid AS facture_id,
					p_factures.no_facture, 
					date_imputation AS date_comptable,
					t_rubriques_facturation.oid AS rubrique_comptabilisation_id, 
					t_prestations.oid 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, 
					NPF_TOTAL_AMO AS montant_regle, 
					0 AS montant_regle_0, 
					NPF_TOTAL_AMO AS montant_regle_1, 
					0 AS montant_regle_2,  
					0 AS montant_regle_22,
					'1' AS od_non_comptabilise
				FROM w_NOE_PAI_FACT
					JOIN activite[PX].p_factures ON FACT_NUMERO = no_facture
					JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code_original = '*CTI_ACO85'
					JOIN activite.t_prestations ON t_prestations.code_original = '*CTI_ACO85'
				WHERE w_NOE_PAI_FACT.ok = '1' AND
					NP_REGLEMENT = 0 AND
					NPF_TOTAL_ACOMPTE < 0 AND
					NPF_TOTAL_AMO > 0 AND
					date_imputation >= date(now() - interval '1 month')
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_c = montant_regle_c + montant_acompte,
					montant_regle_1_c = montant_regle_1_c + montant_acompte
				FROM
				(
				SELECT no_facture, SUM(montant_regle_1) AS montant_acompte
				FROM activite[PX].p_factures_soldes_c
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid AND
					t_prestations.code_original = '*CTI_ACO85' 
				GROUP BY 1
				HAVING SUM(montant_regle_1) <> 0
				) subview
				WHERE p_factures.no_facture = subview.no_facture
				;
				
				
				
				
				-- Solder les factures soldées par une facture d'impayé
				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					facture_id,
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_c.no_facture,
					p_factures_soldes_c.facture_id,
					p_factures_soldes_c.date_comptable,
					p_factures_soldes_c.rubrique_comptabilisee_id,
					p_factures_soldes_c.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,
					p_factures_soldes_c.montant_comptabilise AS montant_regle, 
					p_factures_soldes_c.montant_comptabilise_0 AS montant_regle_0, 
					p_factures_soldes_c.montant_comptabilise_1 AS montant_regle_1, 
					p_factures_soldes_c.montant_comptabilise_2 AS montant_regle_2, 
					p_factures_soldes_c.montant_comptabilise_22 AS montant_regle_22,
					'1'::text AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_c
				JOIN activite[PX].p_factures ON split_part(p_factures_soldes_c.no_facture,'-IM',1) = p_factures.no_facture
				WHERE p_factures_soldes_c.no_facture LIKE '%-IM%' AND p_factures_soldes_c.montant_comptabilise <> 0
				;

				INSERT INTO activite[PX].p_factures_soldes_c(
					no_facture, 
					facture_id,
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					p_factures_soldes_c.date_comptable,
					p_factures_soldes_c.rubrique_comptabilisee_id,
					p_factures_soldes_c.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,
					0-p_factures_soldes_c.montant_comptabilise AS montant_regle, 
					0-p_factures_soldes_c.montant_comptabilise_0 AS montant_regle_0, 
					0-p_factures_soldes_c.montant_comptabilise_1 AS montant_regle_1, 
					0-p_factures_soldes_c.montant_comptabilise_2 AS montant_regle_2, 
					0-p_factures_soldes_c.montant_comptabilise_22 AS montant_regle_22,
					'1'::text AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_c
				JOIN activite[PX].p_factures ON split_part(p_factures_soldes_c.no_facture,'-IM',1) = p_factures.no_facture
				WHERE p_factures_soldes_c.no_facture LIKE '%-IM%' AND montant_comptabilise <> 0
				;
				
				DROP TABLE IF EXISTS w_facture_total_impaye;
				CREATE TEMP TABLE w_facture_total_impaye AS
				SELECT split_part(p_factures.no_facture,'-IM',1) AS impaye_no_facture,
					SUM(montant_comptabilise_c) AS impaye_montant_comptabilise_c,
					SUM(montant_comptabilise_1_c) AS impaye_montant_comptabilise_1_c,
					SUM(montant_comptabilise_2_c) AS impaye_montant_comptabilise_2_c,
					SUM(montant_comptabilise_22_c) AS impaye_montant_comptabilise_22_c,
					SUM(montant_comptabilise_0_c) AS impaye_montant_comptabilise_0_c
				FROM activite[PX].p_factures
				WHERE no_facture LIKE '%-IM%' AND montant_comptabilise_c <> 0
				GROUP BY 1
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_c = montant_regle_c - impaye_montant_comptabilise_c,
					montant_regle_1_c = montant_regle_1_c - impaye_montant_comptabilise_1_c,
					montant_regle_2_c = montant_regle_2_c - impaye_montant_comptabilise_2_c,
					montant_regle_22_c = montant_regle_22_c - impaye_montant_comptabilise_22_c,
					montant_regle_0_c = montant_regle_0_c - impaye_montant_comptabilise_0_c
				FROM w_facture_total_impaye
				WHERE p_factures.no_facture = impaye_no_facture
				;

				UPDATE activite[PX].p_factures  SET
					montant_regle_c = montant_regle_c + montant_comptabilise_c,
					montant_regle_1_c = montant_regle_1_c + montant_comptabilise_1_c,
					montant_regle_2_c = montant_regle_2_c + montant_comptabilise_2_c,
					montant_regle_22_c = montant_regle_22_c + montant_comptabilise_22_c,
					montant_regle_0_c = montant_regle_0_c + montant_comptabilise_0_c
				FROM w_facture_total_impaye
				WHERE p_factures.no_facture LIKE '%-IM%' AND
					split_part(p_factures.no_facture,'-IM',1) = w_facture_total_impaye.impaye_no_facture
				;
				
				

				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');
	
										
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Lignes non facturées Honoraires">
			<sqlcmd><![CDATA[
            
                -- Retraitement PU et montant des Honoraires de Surveillance (419)
				DROP TABLE IF EXISTS w_DAT_PRESTATIONS_GAP_PU;
				CREATE TEMP TABLE w_DAT_PRESTATIONS_GAP_PU AS
				SELECT PREST_CODE, (MAX(Array[PREST_DATE_DEBUT::text,(PREST_MFE_HON / PREST_COEFF)::text]))[2]::numeric AS PU
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
				WHERE PREST_CODE = 'HS' AND
					PREST_DATE_DEBUT = PREST_DATE_FIN AND
					PREST_COEFF <> 0
				GROUP BY 1
				;

				UPDATE prod_web100t.DAT_PRESTATIONS_GAP SET
					PREST_PU = PU,
					PREST_QUANTITE = (date(prest_date_fin)-date(prest_date_debut)+1),
					PREST_MFE_HON = round(((date(prest_date_fin)-date(prest_date_debut)+1)*PU*PREST_COEFF)::numeric,2)
					FROM w_DAT_PRESTATIONS_GAP_PU
					WHERE DAT_PRESTATIONS_GAP.PREST_CODE = w_DAT_PRESTATIONS_GAP_PU.PREST_CODE AND
						PREST_DATE_DEBUT <> PREST_DATE_FIN
				;

				TRUNCATE activite[PX].p_factures_lignes_non_facturees_h;
				
				INSERT INTO activite[PX].p_factures_lignes_non_facturees_h(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					heure_debut, 
					nb_rubrique, 
					coefficient, 
					medecin_facture_id, 
					prestation_id, 
					prix_unitaire, 
					montant_depassement, 
					lieu_id, 
					acte_id, 
					phase_ccam, 
					activite_ccam, 
					extension_ccam, 
					modificateur_ccam_1, 
					modificateur_ccam_2,
					modificateur_ccam_3, 
					modificateur_ccam_4)
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					date(PREST_DATE_DEBUT) AS date_debut,
					date(COALESCE(PREST_DATE_FIN, PREST_DATE_DEBUT)) AS date_fin,
					extract('hour' FROM COALESCE(PREST_DATE_FIN, PREST_DATE_DEBUT)) AS heure_debut,
					CASE WHEN PREST_QUANTITE <> 0 AND PREST_PU <> 0 THEN PREST_QUANTITE ELSE 1 END AS nb_rubrique,
					CASE WHEN PREST_COEFF <> 0 AND PREST_PU <> 0 THEN PREST_COEFF ELSE 1 END AS coefficient,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
					prestation_id,
					CASE WHEN PREST_PU <> 0 THEN PREST_PU ELSE PREST_MFE_HON END AS prix_unitaire,
					PREST_DEPASSEMENT AS montant_depassement, 
					p_sejours.lieu_sortie_id AS lieu_id,
					acte_id,
					ART_CODE_PHASE AS phase_ccam,
					ART_CODE_ACTIVITE AS activite_ccam,
					PREST_EXTENSION_DOC AS extension_ccam, 
					substr(PREST_MODIFICATEURS,1,1) AS modificateur_ccam_1, 
					substr(PREST_MODIFICATEURS,2,1) AS modificateur_ccam_2,
					substr(PREST_MODIFICATEURS,3,1) AS modificateur_ccam_3, 
					substr(PREST_MODIFICATEURS,4,1) AS modificateur_ccam_4
					
				FROM prod_web100t.DAT_PRESTATIONS_GAP 
					JOIN prod_web100t.DAT_DA ON PREST_DA = DA_OID
					JOIN activite[PX].p_sejours ON DA_OID = p_sejours.code_original AND date(PREST_DATE_DEBUT) BETWEEN date_entree AND date_sortie 
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND type_facture = 'E' AND date(PREST_DATE_DEBUT) BETWEEN date_debut AND date_fin
					JOIN w_ART_ARTICLES ON PREST_ARTICLE = ART_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON PREST_EXECUTANT = t_medecins_administratifs.code_original
				WHERE PREST_MFE_HON > 0 AND PREST_ENTENTE_DIRECTE = 0 AND PREST_DELETED = 0


				ORDER BY p_sejours.no_sejour;
										
										
			]]></sqlcmd>
		</NODE>

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

				DROP TABLE IF EXISTS w_factures_lignes_h;
				CREATE TEMP TABLE w_factures_lignes_h AS
				SELECT
					FLT_LIGNE_FACTURE,

					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date_vente,
										
					lieu_sortie_id AS lieu_id,
					1::numeric AS origine_facturation_id,
					
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,

					acte_id,
					ART_CODE_PHASE AS phase_ccam,
					ART_CODE_ACTIVITE AS activite_ccam,
					''::text AS extension_ccam,
					''::text AS modificateur_ccam_1,
					''::text AS modificateur_ccam_2,
					''::text AS modificateur_ccam_3,
					''::text AS modificateur_ccam_4,
					
					rubrique_facturation_id,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					0::bigint AS protocole_id,
					0::bigint AS compte_produit_id,

					date(MIN(FLT_DATE_DEBUT)) AS date_debut,
					date(MAX(FLT_DATE_FIN)) AS date_fin,
					date_part('hour',FLT_DATE_DEBUT) AS heure_debut,

  
					MAX(COALESCE(B2T_PU,FLT_TOTAL_TTC)) AS prix_unitaire,
					
					CASE WHEN SUM(FLT_TOTAL_TTC) >= 0 THEN 1 ELSE -1 END AS nb_rubrique,
					CASE WHEN SUM(FLT_TOTAL_TTC) >= 0 THEN 1 ELSE -1 END AS nb_prestation,
					MAX(COALESCE(B2T_QUANTITE,1)) AS coefficient,
					1::numeric AS coefficient_mco,
					
					MAX(COALESCE(B2T_TAUX_CLI,0)) AS taux_0,
					MAX(COALESCE(B2T_TAUX_AMO,0)) AS taux_1,
					MAX(COALESCE(B2T_TAUX_AMC,0)) AS taux_2,
					MAX(COALESCE(B2T_TAUX_AMD,0)) AS taux_22,
					
					SUM(FLT_TOTAL_TTC) AS montant_facture,
					SUM(CASE WHEN FLT_IS_DEP = 1 THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_depassement,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_0,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_1,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_2,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_facture_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,

					SUM(CASE WHEN code_vente = '1' AND FLT_IS_DIRECT <= 0 AND FLT_IS_ETS = 0 AND FT_TYPE_TIER <> 'ETS' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise,
					SUM(CASE WHEN code_vente = '1' AND FLT_IS_DIRECT <= 0 AND FLT_IS_ETS = 0 AND FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_0,
					SUM(CASE WHEN code_vente = '1' AND FLT_IS_DIRECT <= 0 AND FLT_IS_ETS = 0 AND FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_1,
					SUM(CASE WHEN code_vente = '1' AND FLT_IS_DIRECT <= 0 AND FLT_IS_ETS = 0 AND FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_2,
					SUM(CASE WHEN code_vente = '1' AND FLT_IS_DIRECT <= 0 AND FLT_IS_ETS = 0 AND FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_comptabilise_22,
					0::numeric AS montant_comptabilise_budget_global_1,
					
					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,
					
					MAX(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FLT_OID ELSE 0 END) AS FLT_OID_0,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FLT_OID ELSE 0 END) AS FLT_OID_1,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FLT_OID ELSE 0 END) AS FLT_OID_2,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FLT_OID ELSE 0 END) AS FLT_OID_22
					
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN w_factures ON FLT_FACTURE = FACT_OID AND IMPAYE = 0
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE
				WHERE (FLT_IS_ETS = 0 OR LI_TYPE_B2 = '4') AND FLT_RECAP <> 0 
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,FLT_DATE_DEBUT;
				
				
				-- Impayés
				INSERT INTO w_factures_lignes_h
				SELECT
					FLT_LIGNE_FACTURE,

					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date_vente,
										
					lieu_sortie_id AS lieu_id,
					1::numeric AS origine_facturation_id,
					
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,

					acte_id,
					ART_CODE_PHASE AS phase_ccam,
					ART_CODE_ACTIVITE AS activite_ccam,
					''::text AS extension_ccam,
					''::text AS modificateur_ccam_1,
					''::text AS modificateur_ccam_2,
					''::text AS modificateur_ccam_3,
					''::text AS modificateur_ccam_4,
					
					rubrique_facturation_id,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					0::bigint AS protocole_id,
					0::bigint AS compte_produit_id,

					date(MIN(FLT_DATE_DEBUT)) AS date_debut,
					date(MAX(FLT_DATE_FIN)) AS date_fin,
					date_part('hour', FLT_DATE_DEBUT)*10000 + date_part('minute', FLT_DATE_DEBUT)*100 + date_part('second', FLT_DATE_DEBUT) AS heure_debut,

  
					MAX(COALESCE(B2T_PU,FLT_TOTAL_TTC)) AS prix_unitaire,
					
					0 AS nb_rubrique,
					0 AS nb_prestation,
					MAX(COALESCE(B2T_QUANTITE,1)) AS coefficient,
					1::numeric AS coefficient_mco,
					
					MAX(COALESCE(B2T_TAUX_CLI,0)) AS taux_0,
					MAX(COALESCE(B2T_TAUX_AMO,0)) AS taux_1,
					MAX(COALESCE(B2T_TAUX_AMC,0)) AS taux_2,
					MAX(COALESCE(B2T_TAUX_AMD,0)) AS taux_22,
					
					0 AS montant_facture,
					0 AS montant_depassement,
					0 AS montant_facture_0,
					0 AS montant_facture_1,
					0 AS montant_facture_2,
					0::numeric AS montant_facture_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,

					SUM(FLT_TOTAL_IMPAYE_HON) AS montant_comptabilise,
					SUM(FLT_TOTAL_IMPAYE_HON_CLI) AS montant_comptabilise_0,
					SUM(FLT_TOTAL_IMPAYE_HON_AMO) AS montant_comptabilise_1,
					SUM(FLT_TOTAL_IMPAYE_HON_AMC) AS montant_comptabilise_2,
					SUM(FLT_TOTAL_IMPAYE_HON_AMD) AS montant_comptabilise_22,
					0::numeric AS montant_comptabilise_budget_global_1,
					
					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,
					
					MAX(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FLT_OID ELSE 0 END) AS FLT_OID_0,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FLT_OID ELSE 0 END) AS FLT_OID_1,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FLT_OID ELSE 0 END) AS FLT_OID_2,
					MAX(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FLT_OID ELSE 0 END) AS FLT_OID_22
					
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN w_FAC_FACT_LIGNE_TIER_IMPAYE ON FLT_OID = FLT_IMPAYE_OID
					JOIN w_factures ON FLT_FACTURE = FACT_OID AND IMPAYE = w_FAC_FACT_LIGNE_TIER_IMPAYE.FI_COMPTA
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN w_ART_ARTICLES ON FLT_ARTICLE = ART_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
					LEFT JOIN w_FAC_B2_TIER ON LI_LIGNE_SOURCE = B2T_LIGNE
				WHERE (FLT_IS_ETS = 0 OR LI_TYPE_B2 = '4') AND FLT_RECAP <> 0 
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,FLT_DATE_DEBUT;
				
				
				
				
				
				-- Actes honoraires comptabilisés en clinique, recherche véritable exécutant d'après les prestations
				DROP TABLE IF EXISTS w_DAT_PRESTATIONS_GAP;
				CREATE TEMP TABLE w_DAT_PRESTATIONS_GAP AS 
				SELECT PREST_DA, PREST_DATE_DEBUT, PREST_DATE_FIN, PREST_CODE, PREST_ARTICLE, MAX(PREST_EXECUTANT) AS PREST_EXECUTANT
				FROM prod_web100t.DAT_PRESTATIONS_GAP
				WHERE PREST_EXECUTANT <> 0 AND PREST_DELETED = 0
					GROUP BY 1,2,3,4,5;
							
				DROP TABLE IF EXISTS w_FAC_FACT_LIGNE_TIER_EXEC;
				CREATE TEMP TABLE w_FAC_FACT_LIGNE_TIER_EXEC AS
				SELECT FLT_OID, 
					MAX(COALESCE(w_DAT_PRESTATIONS_GAP_1.PREST_EXECUTANT,w_DAT_PRESTATIONS_GAP_2.PREST_EXECUTANT,FLT_INTERVENANT)) AS FLT_INTERVENANT
				FROM prod_web100t.FAC_FACT_LIGNE_TIER 
					JOIN prod_web100t.FAC_FACTURE  ON FLT_FACTURE = FACT_OID
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE ON FLT_LIGNE_FACTURE = LI_OID
					JOIN prod_web100t.DAT_DA ON FT_DA = DA_OID
				LEFT JOIN w_DAT_PRESTATIONS_GAP w_DAT_PRESTATIONS_GAP_1 ON 
					w_DAT_PRESTATIONS_GAP_1.PREST_DA = FT_DA AND
					(date(FLT_DATE_DEBUT) = date(w_DAT_PRESTATIONS_GAP_1.PREST_DATE_DEBUT) OR 
					date(FLT_DATE_FIN) = date(w_DAT_PRESTATIONS_GAP_1.PREST_DATE_FIN)
					) AND
					(FLT_ARTICLE = w_DAT_PRESTATIONS_GAP_1.PREST_ARTICLE OR FLT_CODE_PREST = PREST_CODE)
				LEFT JOIN w_DAT_PRESTATIONS_GAP w_DAT_PRESTATIONS_GAP_2 ON 
					w_DAT_PRESTATIONS_GAP_2.PREST_DA = FT_DA AND
					(FLT_ARTICLE = w_DAT_PRESTATIONS_GAP_2.PREST_ARTICLE OR FLT_CODE_PREST = w_DAT_PRESTATIONS_GAP_2.PREST_CODE)
				WHERE FLT_IS_ETS = 1 AND LI_TYPE_B2 = '4' AND FLT_RECAP <> 0 
				GROUP BY 1;
				
				
				UPDATE w_factures_lignes_h SET
					medecin_facture_id = t_medecins_administratifs.oid,
					medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM w_FAC_FACT_LIGNE_TIER_EXEC
				JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
				WHERE w_factures_lignes_h.FLT_OID_0 = w_FAC_FACT_LIGNE_TIER_EXEC.FLT_OID AND
					medecin_facture_id IS DISTINCT FROM t_medecins_administratifs.oid;
					
				UPDATE w_factures_lignes_h SET
					medecin_facture_id = t_medecins_administratifs.oid,
					medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM w_FAC_FACT_LIGNE_TIER_EXEC
				JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
				WHERE w_factures_lignes_h.FLT_OID_1 = w_FAC_FACT_LIGNE_TIER_EXEC.FLT_OID AND
					medecin_facture_id IS DISTINCT FROM t_medecins_administratifs.oid;
					
				UPDATE w_factures_lignes_h SET
					medecin_facture_id = t_medecins_administratifs.oid,
					medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM w_FAC_FACT_LIGNE_TIER_EXEC
				JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
				WHERE w_factures_lignes_h.FLT_OID_2 = w_FAC_FACT_LIGNE_TIER_EXEC.FLT_OID AND
					medecin_facture_id IS DISTINCT FROM t_medecins_administratifs.oid;
                    
                UPDATE w_factures_lignes_h SET
					medecin_facture_id = t_medecins_administratifs.oid,
					medecin_comptabilise_id = t_medecins_administratifs.oid
				FROM w_FAC_FACT_LIGNE_TIER_EXEC
				JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
				WHERE w_factures_lignes_h.FLT_OID_22 = w_FAC_FACT_LIGNE_TIER_EXEC.FLT_OID AND
					medecin_facture_id IS DISTINCT FROM t_medecins_administratifs.oid;
                    
                -- Correction de taux bizarres
                UPDATE w_factures_lignes_h SET
                    taux_0 = CASE WHEN taux_0 > 100 THEN 100 WHEN taux_0 < -100 THEN -100 ELSE taux_0 END,
                    taux_1 = CASE WHEN taux_1 > 100 THEN 100 WHEN taux_1 < -100 THEN -100 ELSE taux_1 END,
                    taux_2 = CASE WHEN taux_2 > 100 THEN 100 WHEN taux_2 < -100 THEN -100 ELSE taux_2 END,
                    taux_22 = CASE WHEN taux_22 > 100 THEN 100 WHEN taux_22 < -100 THEN -100 ELSE taux_22 END
                WHERE 
                    taux_0 > 100 OR
                    taux_1 > 100 OR
                    taux_2 > 100 OR
                    taux_22 > 100 OR
                    taux_0 < -100 OR
                    taux_1 < -100 OR
                    taux_2 < -100 OR
                    taux_22 < -100
                ;

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


				INSERT INTO activite[PX].p_factures_lignes_h(
					no_facture,
					facture_id,
										
					lieu_id,
					
					medecin_facture_id,
					medecin_comptabilise_id,

					acte_id,
					phase_ccam,
					activite_ccam,
					extension_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					
					rubrique_facturation_id,
					rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,

					date_debut,
					date_fin,
					heure_debut,

  
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					montant_facture,
					montant_depassement,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					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

					
				)
				SELECT
					no_facture,
					facture_id,
										
					lieu_id,
					
					medecin_facture_id,
					medecin_comptabilise_id,

					acte_id,
					phase_ccam,
					activite_ccam,
					extension_ccam,
					modificateur_ccam_1,
					modificateur_ccam_2,
					modificateur_ccam_3,
					modificateur_ccam_4,
					
					rubrique_facturation_id,
					rubrique_facturation_id AS rubrique_comptabilisation_id,
					prestation_id,
					protocole_id,

					date_debut,
					date_fin,
					heure_debut,

  
					prix_unitaire,
					
					nb_rubrique,
					nb_prestation,
					coefficient,
					coefficient_mco,
					
					taux_0,
					taux_1,
					taux_2,
					taux_22,
					
					montant_facture,
					montant_depassement,
					montant_facture_0,
					montant_facture_1,
					montant_facture_2,
					montant_facture_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,
					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
				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[
			
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_factures_soldes_h_8');

				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					facture_id,
					date_comptable, 
					medecin_comptabilise_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					no_facture,
					facture_id,
					date_vente,
					medecin_comptabilise_id,
					SUM(montant_comptabilise),
					SUM(montant_comptabilise_0),
					SUM(montant_comptabilise_1),
					SUM(montant_comptabilise_2),
					SUM(montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM w_factures_lignes_h
				WHERE date_vente IS NOT NULL AND
					(montant_comptabilise <> 0 OR 
					montant_comptabilise_0 <> 0 OR 
					montant_comptabilise_1 <> 0 OR 
					montant_comptabilise_2 <> 0 OR 
					montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4;
				
				
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					facture_id,
					date_comptable, 
					medecin_comptabilise_id,
					od_non_comptabilise,					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					w_factures.no_facture,
					w_factures.oid AS facture_id,
					date(COALESCE(ECR_DATE,RD_DATE,FR_DATE_ENC)) AS date_comptable,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,
					CASE 
						WHEN FR_DATE_DEPOT_GUESS IS NOT NULL AND FR_DATE_ENC IS NULL THEN '1' 
						WHEN RD_CREATED > ECR_UPDATED_MAX THEN '1'
						ELSE '0' END AS od_non_comptabilise,
					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(RD_MONTANT) As montant_regle,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN RD_MONTANT ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN RD_MONTANT ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN RD_MONTANT ELSE 0 END) AS montant_regle_2,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN RD_MONTANT ELSE 0 END) AS montant_regle_22
				FROM prod_web100t.FAC_RGLMT_DETAILS 
					JOIN prod_web100t.FAC_REGLEMENTS ON FR_OID = RD_REGLEMENT
					JOIN w_factures ON RD_FACTURE = FACT_OID AND IMPAYE = 0
					JOIN prod_web100t.FAC_FACT_TIER ON RD_FACT_TIER = FT_OID
					JOIN prod_web100t.FAC_FACT_LIGNE_TIER ON RD_FACT_LINE = FLT_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
					LEFT JOIN w_CPT_OP_LINK ON RD_COMPTA = LNK_OPERATION
					JOIN w_max_ECR_UPDATED ON 1=1
				WHERE RD_ETS = 0 AND FLT_IS_DIRECT = 0
				GROUP BY 1,2,3,4,5;
				
				-- Paiements directs comptabilisés
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					facture_id,
					date_comptable, 
					medecin_comptabilise_id,
					od_non_comptabilise,					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					w_factures.no_facture,
					w_factures.oid AS facture_id,
					w_factures.date_vente AS date_comptable,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id,
					'0'::text AS od_non_comptabilise,
					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(FLT_TOTAL_TTC) As montant_regle,
					SUM(CASE WHEN FT_TYPE_TIER = 'CLI' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_regle_0,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMO' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_regle_1,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMC' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_regle_2,
					SUM(CASE WHEN FT_TYPE_TIER = 'AMD' THEN FLT_TOTAL_TTC ELSE 0 END) AS montant_regle_22
				FROM prod_web100t.FAC_FACT_LIGNE_TIER
					JOIN w_factures ON FLT_FACTURE = FACT_OID AND IMPAYE = 0
					JOIN prod_web100t.FAC_FACT_TIER ON FLT_FACTURE_TIER = FT_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON FLT_INTERVENANT = code_original
				WHERE FLT_IS_ETS = 0 AND FLT_IS_DIRECT = -1
				GROUP BY 1,2,3,4,5;
				
				-- Solder les factures soldées par une facture d'impayé
				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					facture_id,
					date_comptable, 
					medecin_comptabilise_id, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures_soldes_h.no_facture,
					p_factures_soldes_h.facture_id,
					p_factures_soldes_h.date_comptable,
					p_factures_soldes_h.medecin_comptabilise_id, 
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.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,
					p_factures_soldes_h.montant_comptabilise AS montant_regle, 
					p_factures_soldes_h.montant_comptabilise_0 AS montant_regle_0, 
					p_factures_soldes_h.montant_comptabilise_1 AS montant_regle_1, 
					p_factures_soldes_h.montant_comptabilise_2 AS montant_regle_2, 
					p_factures_soldes_h.montant_comptabilise_22 AS montant_regle_22,
					'1'::text AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].p_factures ON split_part(p_factures_soldes_h.no_facture,'-IM',1) = p_factures.no_facture
				WHERE p_factures_soldes_h.no_facture LIKE '%-IM%' AND p_factures_soldes_h.montant_comptabilise <> 0
				;

				INSERT INTO activite[PX].p_factures_soldes_h(
					no_facture, 
					facture_id,
					date_comptable, 
					medecin_comptabilise_id, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22,
					od_non_comptabilise
				)
				SELECT
					p_factures.no_facture,
					p_factures.oid AS facture_id,
					p_factures_soldes_h.date_comptable,
					p_factures_soldes_h.medecin_comptabilise_id, 
					p_factures_soldes_h.rubrique_comptabilisee_id,
					p_factures_soldes_h.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,
					0-p_factures_soldes_h.montant_comptabilise AS montant_regle, 
					0-p_factures_soldes_h.montant_comptabilise_0 AS montant_regle_0, 
					0-p_factures_soldes_h.montant_comptabilise_1 AS montant_regle_1, 
					0-p_factures_soldes_h.montant_comptabilise_2 AS montant_regle_2, 
					0-p_factures_soldes_h.montant_comptabilise_22 AS montant_regle_22,
					'1'::text AS od_non_comptabilise
				FROM activite[PX].p_factures_soldes_h
				JOIN activite[PX].p_factures ON split_part(p_factures_soldes_h.no_facture,'-IM',1) = p_factures.no_facture
				WHERE p_factures_soldes_h.no_facture LIKE '%-IM%' AND montant_comptabilise <> 0
				;
				
				DROP TABLE IF EXISTS w_facture_total_impaye;
				CREATE TEMP TABLE w_facture_total_impaye AS
				SELECT split_part(p_factures.no_facture,'-IM',1) AS impaye_no_facture,
					SUM(montant_comptabilise_h) AS impaye_montant_comptabilise_h,
					SUM(montant_comptabilise_1_h) AS impaye_montant_comptabilise_1_h,
					SUM(montant_comptabilise_2_h) AS impaye_montant_comptabilise_2_h,
					SUM(montant_comptabilise_22_h) AS impaye_montant_comptabilise_22_h,
					SUM(montant_comptabilise_0_h) AS impaye_montant_comptabilise_0_h
				FROM activite[PX].p_factures
				WHERE no_facture LIKE '%-IM%' AND montant_comptabilise_h <> 0
				GROUP BY 1
				;

				UPDATE activite[PX].p_factures SET
					montant_regle_h = montant_regle_h - impaye_montant_comptabilise_h,
					montant_regle_1_h = montant_regle_1_h - impaye_montant_comptabilise_1_h,
					montant_regle_2_h = montant_regle_2_h - impaye_montant_comptabilise_2_h,
					montant_regle_22_h = montant_regle_22_h - impaye_montant_comptabilise_22_h,
					montant_regle_0_h = montant_regle_0_h - impaye_montant_comptabilise_0_h
				FROM w_facture_total_impaye
				WHERE p_factures.no_facture = impaye_no_facture
				;

				UPDATE activite[PX].p_factures  SET
					montant_regle_h = montant_regle_h + montant_comptabilise_h,
					montant_regle_1_h = montant_regle_1_h + montant_comptabilise_1_h,
					montant_regle_2_h = montant_regle_2_h + montant_comptabilise_2_h,
					montant_regle_22_h = montant_regle_22_h + montant_comptabilise_22_h,
					montant_regle_0_h = montant_regle_0_h + montant_comptabilise_0_h
				FROM w_facture_total_impaye
				WHERE p_factures.no_facture LIKE '%-IM%' AND
					split_part(p_factures.no_facture,'-IM',1) = w_facture_total_impaye.impaye_no_facture
				;
				
				
				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');
										
										
			]]></sqlcmd>
		</NODE>

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

				
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Budget global MCO">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1" && "[ENV_WITHPMSI]" == "1"
			]]></condition>
			<sqlcmd><![CDATA[
				UPDATE activite[PX].p_sejours SET est_budget_global = '1';
			
				-- Correction des GHM/GHS activité selon PMSI
				UPDATE activite[PX].p_sejours SET
					ghm_id = t_ghm.oid,
					ghs_id = t_ghs.oid
				FROM activite[PX].p_sejour_pmsi
				JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
				JOIN pmsi.t_ghm t_ghm_pmsi ON p_rss.ghm_id = t_ghm_pmsi.oid
				JOIN pmsi.t_ghs t_ghs_pmsi ON p_rss.ghs_id = t_ghs_pmsi.oid
				JOIN base.t_ghm ON t_ghm_pmsi.code = t_ghm.code
				JOIN base.t_ghs ON t_ghs_pmsi.code = t_ghs.code
				WHERE p_sejour_pmsi.sejour_id = p_sejours.oid AND
					p_rss.ghm_id  > 0 AND 
					p_sejours.ghm_id <= 0 AND
					t_ghm_pmsi.code NOT LIKE '90%' AND
					t_ghm_pmsi.code NOT LIKE '99%' 
				;
				
				ANALYSE activite[PX].p_sejours;
				ANALYSE activite[PX].p_factures;
				ANALYSE activite[PX].p_factures_lignes_c;

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

				-- Ajout des prestations PMSI aux rubriques activité
				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT
					t_prestations_pmsi.code,
					t_prestations_pmsi.code,
					t_prestations_pmsi.texte,
					t_prestations_pmsi.texte
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND 
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					t_prestations_activite.oid IS NULL
				GROUP BY 1,2,3,4;

				-- Lignes PMSI à ajouter
				DROP TABLE IF EXISTS w_factures_lignes_pmsi;
				CREATE TEMP TABLE w_factures_lignes_pmsi AS
				SELECT
					p_sejours.no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour || '.BG' AS no_facture,
					0::bigint AS facture_id,
					CASE WHEN p_rsf_detail.type = 'C' THEN 'H' ELSE 'C' END AS clinique_honoraire,
					p_rsf_detail.date_debut,
					CASE WHEN p_sejours.type_sejour <> '5' THEN p_rsf_detail.date_fin ELSE p_rsf_detail.date_debut END AS date_fin,
					p_rsf_detail.nombre AS nb_rubrique,
					p_rsf_detail.nombre AS nb_prestation,
					p_rsf_detail.coefficient AS coefficient,
					p_rsf_detail.coefficient_mco,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_facturation_id,
					COALESCE(t_rubriques_facturation.oid,0::bigint) AS rubrique_comptabilisation_id,
					COALESCE(t_prestations_activite.oid,0::bigint) AS prestation_id,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_facture,
					0::numeric AS montant_facture_0,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_facture_1,
					0::numeric AS montant_facture_2,
					0::numeric AS montant_facture_22,
					0::numeric AS taux_0,
					p_rsf_detail.taux_remboursement AS taux_1,
					0::numeric AS taux_2,
					0::numeric AS taux_22,
					p_rsf_detail.prix_unitaire,
					p_sejours.lieu_sortie_id AS lieu_id,
					0::numeric AS montant_comptabilise,
					0::numeric AS montant_comptabilise_0,
					0::numeric AS montant_comptabilise_1,
					0::numeric AS montant_comptabilise_2,
					0::numeric AS montant_comptabilise_22,
					0::numeric AS montant_encours,
					0::numeric AS montant_encours_0,
					0::numeric AS montant_encours_1,
					0::numeric AS montant_encours_2,
					0::numeric AS montant_encours_22,
					0::numeric AS montant_facture_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour,
					CASE WHEN p_rsf_detail.type = 'C' THEN 2::bigint ELSE 1::bigint END AS origine_facturation_id,
					CASE WHEN p_rss.traitement_epmsi IN ('30','31','32','33') THEN p_rsf_detail.sejour_remboursable ELSE 0 END AS montant_comptabilise_budget_global_1,
					0::numeric AS protocole_id,
					0::numeric AS compte_produit_id,
					t_prestations_pmsi.code AS prestation_code,
					''::text AS uf_code,
					''::text AS dmt_code,
					''::text AS mt_code
				FROM pmsi.p_rsf_detail
				JOIN pmsi.p_rss ON p_rss.oid = p_rsf_detail.rss_id AND p_rss.etat = '' AND p_rss.en_cours = '0'
                JOIN pmsi.p_rsf_total ON p_rss.oid = p_rsf_total.rss_id AND p_rsf_total.valorise_fides IS DISTINCT FROM 1
				JOIN pmsi.t_prestations t_prestations_pmsi ON t_prestations_pmsi.oid = p_rsf_detail.prestation_id
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejour_pmsi ON p_rss.oid = p_sejour_pmsi.rss_id
				JOIN activite[PX].p_sejours on p_sejour_pmsi.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN activite.t_prestations t_prestations_activite ON t_prestations_activite.code = t_prestations_pmsi.code
				LEFT JOIN activite[PX].t_rubriques_facturation ON t_rubriques_facturation.code = t_prestations_pmsi.code
				WHERE est_ligne_rss = '1' AND p_rss.en_cours = '0' AND
                    p_rss.etat = '' AND
					operation_lamda IS DISTINCT FROM '1' AND
					operation_lamda IS DISTINCT FROM '2' AND
					p_rss.traitement_epmsi NOT IN ('11', '12') ;

				-- compte
				UPDATE w_factures_lignes_pmsi
				SET uf_code = t_unites_fonctionnelles.code,
					dmt_code = CASE WHEN t_dmt.oid <> 0 THEN t_dmt.code ELSE '' END,
					mt_code = CASE WHEN t_modes_traitement.oid <> 0 THEN CASE WHEN t_modes_traitement.code <> '23' THEN t_modes_traitement.code ELSE '04' END ELSE '' END
				FROM activite[PX].t_lieux 
				JOIN activite[PX].t_unites_fonctionnelles ON unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
				JOIN base.t_dmt ON dmt_id = t_dmt.oid
				JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
				WHERE lieu_id = t_lieux.oid;
				
				DROP TABLE IF EXISTS w_last_comptes_produits;
				CREATE TEMP TABLE w_last_comptes_produits AS
				SELECT t_prestations.code AS last_prestation_code,
					t_unites_fonctionnelles.code AS last_uf_code,
					t_dmt.code AS last_dmt_code,
					t_modes_traitement.code AS last_mt_code,
					(MAX(ARRAY[date_fin::text,compte_produit_id::text]))[2]::bigint AS last_compte_produit_id
				FROM activite[PX].p_factures_lignes_c
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid 
					JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid 
					JOIN activite[PX].t_unites_fonctionnelles ON unite_fonctionnelle_id = t_unites_fonctionnelles.oid
					JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
					JOIN base.t_dmt ON dmt_id = t_dmt.oid
					JOIN base.t_modes_traitement ON t_services_facturation.mode_traitement_id = t_modes_traitement.oid
				WHERE compte_produit_id != 0
				GROUP BY 1,2,3,4;

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = uf_code AND
					last_dmt_code = dmt_code AND
					last_mt_code = mt_code;

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = uf_code AND
					last_dmt_code = '' AND
					last_mt_code = mt_code;

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = uf_code AND
					last_dmt_code = dmt_code AND
					last_mt_code = '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = uf_code AND
					last_dmt_code = '' AND
					last_mt_code = '';



				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = '' AND
					last_dmt_code = dmt_code AND
					last_mt_code = mt_code;

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = '' AND
					last_dmt_code = '' AND
					last_mt_code = mt_code;

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = '' AND
					last_dmt_code = dmt_code AND
					last_mt_code = '';

				UPDATE w_factures_lignes_pmsi
				SET compte_produit_id = last_compte_produit_id
				FROM w_last_comptes_produits
				WHERE compte_produit_id = 0 AND
					last_prestation_code = prestation_code AND
					last_uf_code = '' AND
					last_dmt_code = '' AND
					last_mt_code = '';

				UPDATE w_factures_lignes_pmsi
				SET prestation_id = (SELECT oid FROM activite.t_prestations WHERE code = 'UCD')
				WHERE prestation_id IN (SELECT oid FROM activite.t_prestations WHERE code = 'PHH')
				;
					
				-- Rubriques internes cti
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('w_factures_lignes_pmsi');
				
				
				CREATE INDEX w_factures_lignes_pmsi_i1
						  ON w_factures_lignes_pmsi
						  USING btree
						  (no_sejour);
				

				-- Factures de base
				DROP TABLE IF EXISTS w_factures_pmsi_base;
				CREATE TEMP TABLE w_factures_pmsi_base AS 
				SELECT p_factures.no_sejour, 
					(MAX(Array[CASE WHEN p_factures.code_facture <> '0' THEN p_factures.date_facture ELSE '00010101' END::text,p_factures.no_facture]))[2] AS no_facture_base 
				FROM pmsi.p_rss
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejour_pmsi ON p_rss.oid = p_sejour_pmsi.rss_id
				JOIN activite[PX].p_sejours on p_sejour_pmsi.no_sejour = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour
				WHERE p_rss.etat = '' AND 
					p_rss.en_cours = '0' 
				GROUP BY 1;
				
				CREATE INDEX w_factures_pmsi_base_i1
						  ON w_factures_pmsi_base
						  USING btree
						  (no_sejour);
						  
				CREATE INDEX w_factures_pmsi_base_i2
						  ON w_factures_pmsi_base
						  USING btree
						  (no_facture_base);

				-- Factures à créer
				DROP TABLE IF EXISTS w_factures_pmsi;
				CREATE TEMP TABLE w_factures_pmsi AS
				SELECT
					w_factures_lignes_pmsi.no_sejour,
					w_factures_lignes_pmsi.sejour_id,
					w_factures_lignes_pmsi.no_facture,
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					MAX(CASE 
						WHEN p_factures_base.date_facture IS NULL THEN p_sejours.date_sortie
						WHEN p_factures_base.date_facture <> '20991231' THEN p_factures_base.date_facture 
						WHEN p_sejours.date_groupage <> '20991231' THEN p_sejours.date_groupage
						ELSE p_sejours.date_sortie END)::date AS date_facture,
					MAX(COALESCE(p_factures_base.code_vente,'1')) AS code_vente,
					MAX(COALESCE(p_factures_base.mois_vente,209912)) AS mois_vente,
					MAX(COALESCE(p_factures_base.date_facture,p_sejours.date_sortie)) AS date_solde,
					'0'::text AS particularite_t2a,
					MAX(COALESCE(p_factures_base.date_vente,p_sejours.date_sortie)) AS date_vente,
					''::text AS code_cloture,
					MAX(p_sejours.code_cp_demandee) AS code_cp_demandee,
					'20991231'::date AS date_encours,
					MAX(p_sejours.ghs_id) AS ghs_id,
					MAX(p_sejours.ghs_bebe1_id) AS ghs_bebe1_id,
					MAX(p_sejours.ghs_bebe2_id) AS ghs_bebe2_id,
					MAX(p_sejours.ghs_bebe3_id) AS ghs_bebe3_id,
					MAX(p_sejours.ghm_id) AS ghm_id,
					SUM(montant_facture) AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					'20991231'::date AS date_expedition,
					0::numeric AS delai_expedition,
					MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
					MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
					MAX(p_sejours.tiers_payant_22_id) AS tiers_payant_22_id,
					MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,
					'20991231'::date AS date_expedition_0,
					'20991231'::date AS date_expedition_1,
					'20991231'::date AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					'0'::text AS code_expedie_0,
					'0'::text AS code_expedie_1,
					'0'::text AS code_expedie_2,
					'0'::text AS code_expedie_22,
					''::text AS no_bordereau_0,
					''::text AS no_bordereau_1,
					''::text AS no_bordereau_2,
					''::text AS no_bordereau_22,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					SUM(montant_facture) AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,
					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric AS montant_encours_2_c,
					0::numeric AS montant_encours_22_c,
					0::numeric AS montant_encours_h,
					0::numeric AS montant_encours_0_h,
					0::numeric AS montant_encours_1_h,
					0::numeric AS montant_encours_2_h,
					0::numeric AS montant_encours_22_h,
					0::numeric AS nb_rejets,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					w_factures_lignes_pmsi.no_facture AS no_facture_reference,
					0::bigint AS facture_reference_id,
					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					SUM(montant_comptabilise_budget_global_1) AS montant_comptabilise_budget_global_c,
					'' AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id
				FROM w_factures_lignes_pmsi
				JOIN activite[PX].p_sejours ON w_factures_lignes_pmsi.no_sejour = p_sejours.no_sejour
				JOIN w_factures_pmsi_base ON w_factures_lignes_pmsi.no_sejour = w_factures_pmsi_base.no_sejour
				LEFT JOIN activite[PX].p_factures p_factures_base ON w_factures_pmsi_base.no_facture_base = p_factures_base.no_facture AND 1 <> 1
				GROUP BY 1,2,3,4,5;
				
				INSERT INTO w_factures_pmsi
				SELECT
					p_sejours.no_sejour,
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour || '.BG',
					p_sejours.date_entree AS date_debut,
					p_sejours.date_sortie AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					MAX(CASE 
						WHEN p_sejours.date_groupage <> '20991231' THEN p_sejours.date_groupage
						ELSE p_sejours.date_sortie END)::date AS date_facture,
					'1' AS code_vente,
					209912 AS mois_vente,
					'20991231' AS date_solde,
					'0'::text AS particularite_t2a,
					'20991231' AS date_vente,
					''::text AS code_cloture,
					MAX(p_sejours.code_cp_demandee) AS code_cp_demandee,
					'20991231'::date AS date_encours,
					MAX(p_sejours.ghs_id) AS ghs_id,
					MAX(p_sejours.ghs_bebe1_id) AS ghs_bebe1_id,
					MAX(p_sejours.ghs_bebe2_id) AS ghs_bebe2_id,
					MAX(p_sejours.ghs_bebe3_id) AS ghs_bebe3_id,
					MAX(p_sejours.ghm_id) AS ghm_id,
					0 AS montant_facture_c,
					0::numeric AS montant_facture_h,
					0::numeric AS montant_regle_c,
					0::numeric AS montant_regle_h,
					0::numeric AS delai_facture,
					0::numeric AS delai_solde,
					'20991231'::date AS date_expedition,
					0::numeric AS delai_expedition,
					MAX(p_sejours.tiers_payant_1_id) AS tiers_payant_1_id,
					MAX(p_sejours.tiers_payant_2_id) AS tiers_payant_2_id,
					MAX(p_sejours.tiers_payant_22_id) AS tiers_payant_22_id,
					MAX(p_sejours.tiers_payant_0_id) AS tiers_payant_0_id,
					'20991231'::date AS date_solde_0_c,
					'20991231'::date AS date_solde_0_h,
					'20991231'::date AS date_solde_1_c,
					'20991231'::date AS date_solde_1_h,
					'20991231'::date AS date_solde_2_c,
					'20991231'::date AS date_solde_2_h,
					'20991231'::date AS date_solde_22_c,
					'20991231'::date AS date_solde_22_h,
					'20991231'::date AS date_expedition_0,
					'20991231'::date AS date_expedition_1,
					'20991231'::date AS date_expedition_2,
					'20991231'::date AS date_expedition_22,
					'0'::text AS code_expedie_0,
					'0'::text AS code_expedie_1,
					'0'::text AS code_expedie_2,
					'0'::text AS code_expedie_22,
					''::text AS no_bordereau_0,
					''::text AS no_bordereau_1,
					''::text AS no_bordereau_2,
					''::text AS no_bordereau_22,
					0::numeric AS montant_facture_0_c,
					0::numeric AS montant_facture_0_h,
					0::numeric AS montant_facture_1_c,
					0::numeric AS montant_facture_1_h,
					0::numeric AS montant_facture_2_c,
					0::numeric AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,
					0::numeric AS montant_regle_0_c,
					0::numeric AS montant_regle_0_h,
					0::numeric AS montant_regle_1_c,
					0::numeric AS montant_regle_1_h,
					0::numeric AS montant_regle_2_c,
					0::numeric AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,
					0::numeric AS delai_expedition_0,
					0::numeric AS delai_expedition_1,
					0::numeric AS delai_expedition_2,
					0::numeric AS delai_expedition_22,
					0::numeric AS delai_solde_0_c,
					0::numeric AS delai_solde_0_h,
					0::numeric AS delai_solde_1_c,
					0::numeric AS delai_solde_1_h,
					0::numeric AS delai_solde_2_c,
					0::numeric AS delai_solde_2_h,
					0::numeric AS delai_solde_22_c,
					0::numeric AS delai_solde_22_h,
					0::numeric AS montant_encours_c,
					0::numeric AS montant_encours_0_c,
					0::numeric AS montant_encours_1_c,
					0::numeric AS montant_encours_2_c,
					0::numeric AS montant_encours_22_c,
					0::numeric AS montant_encours_h,
					0::numeric AS montant_encours_0_h,
					0::numeric AS montant_encours_1_h,
					0::numeric AS montant_encours_2_h,
					0::numeric AS montant_encours_22_h,
					0::numeric AS nb_rejets,
					0::numeric AS montant_comptabilise_c,
					0::numeric AS montant_comptabilise_h,
					0::numeric AS montant_comptabilise_0_c,
					0::numeric AS montant_comptabilise_0_h,
					0::numeric AS montant_comptabilise_1_c,
					0::numeric AS montant_comptabilise_1_h,
					0::numeric AS montant_comptabilise_2_c,
					0::numeric AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					p_sejours.no_sejour || '.BG' AS no_facture_reference,
					0::bigint AS facture_reference_id,
					'20991231'::date AS date_solde_reference,
					'20991231'::date AS date_solde_reference_c,
					'20991231'::date AS date_solde_reference_h,
					'20991231'::date AS date_solde_reference_0_c,
					'20991231'::date AS date_solde_reference_1_c,
					'20991231'::date AS date_solde_reference_2_c,
					'20991231'::date AS date_solde_reference_22_c,
					'20991231'::date AS date_solde_reference_0_h,
					'20991231'::date AS date_solde_reference_1_h,
					'20991231'::date AS date_solde_reference_2_h,
					'20991231'::date AS date_solde_reference_22_h,
					'20991231'::date AS date_solde_c,
					'20991231'::date AS date_solde_h,
					0::numeric AS montant_facture_c_actes_inclus_dans_sejour,
					0::numeric AS montant_facture_h_actes_inclus_dans_sejour,
					0::numeric AS montant_comptabilise_budget_global_c,
					'' AS no_facture_od_avoir,
					0::bigint AS facture_od_avoir_id
				FROM pmsi.p_rss
				JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
				JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
				LEFT JOIN w_factures_pmsi ON p_sejours.no_sejour = w_factures_pmsi.no_sejour 
				WHERE p_rss.en_cours = '0' AND 
                    p_rss.etat = '' AND
					p_rss.traitement_epmsi NOT IN ('11', '12') AND
					w_factures_pmsi.no_facture IS NULL AND
					p_sejours.date_sortie >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					p_sejours.no_sejour NOT IN 
						(
							SELECT p_factures.no_sejour 
							FROM activite[PX].p_factures
							WHERE montant_facture_1_c <> 0
						)
				GROUP BY 1,2,3,4,5;


				UPDATE w_factures_pmsi
				SET date_vente = date_facture, mois_vente = date_part('year',date_facture)*100 +  date_part('month',date_facture)
				WHERE date_vente = '20991231';

				UPDATE w_factures_pmsi
				SET date_solde = date_facture
				WHERE date_vente IS DISTINCT FROM date_facture;
				
				
				-- Ajout des factures
				INSERT INTO activite[PX].p_factures
					(no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_vente, mois_vente, date_solde, 
					   montant_facture_c, montant_facture_h, montant_regle_c, montant_regle_h, 
					   delai_facture, delai_solde, date_expedition, delai_expedition, 
					   tiers_payant_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_id, 
					   date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, 
					   date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h, 
					   date_expedition_0, date_expedition_1, date_expedition_2, date_expedition_22, 
					   code_expedie_0, code_expedie_1, code_expedie_2, code_expedie_22, 
					   no_bordereau_0, no_bordereau_1, no_bordereau_2, no_bordereau_22, 
					   montant_facture_0_c, montant_facture_0_h, montant_facture_1_c, 
					   montant_facture_1_h, montant_facture_2_c, montant_facture_2_h, 
					   montant_facture_22_c, montant_facture_22_h, montant_regle_0_c, 
					   montant_regle_0_h, montant_regle_1_c, montant_regle_1_h, montant_regle_2_c, 
					   montant_regle_2_h, montant_regle_22_c, montant_regle_22_h, delai_expedition_0, 
					   delai_expedition_1, delai_expedition_2, delai_expedition_22, 
					   delai_solde_0_c, delai_solde_0_h, delai_solde_1_c, delai_solde_1_h, 
					   delai_solde_2_c, delai_solde_2_h, delai_solde_22_c, delai_solde_22_h, 
					   ghs_id, particularite_t2a, date_vente, code_cloture, montant_encours_c, 
					   montant_encours_0_c, montant_encours_1_c, montant_encours_2_c, 
					   montant_encours_22_c, montant_encours_h, montant_encours_0_h, 
					   montant_encours_1_h, montant_encours_2_h, montant_encours_22_h, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, montant_comptabilise_c, montant_comptabilise_h, montant_comptabilise_0_c, 
					   montant_comptabilise_0_h, montant_comptabilise_1_c, montant_comptabilise_1_h, 
					   montant_comptabilise_2_c, montant_comptabilise_2_h, montant_comptabilise_22_c, 
					   montant_comptabilise_22_h, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id)
				  SELECt no_sejour, no_facture, date_debut, date_fin, type_facture, 
					   code_facture, date_facture, code_vente, mois_vente, date_solde, 
					   montant_facture_c, montant_facture_h, montant_regle_c, montant_regle_h, 
					   delai_facture, delai_solde, date_expedition, delai_expedition, 
					   tiers_payant_1_id, tiers_payant_2_id, tiers_payant_22_id, tiers_payant_0_id, 
					   date_solde_0_c, date_solde_0_h, date_solde_1_c, date_solde_1_h, 
					   date_solde_2_c, date_solde_2_h, date_solde_22_c, date_solde_22_h, 
					   date_expedition_0, date_expedition_1, date_expedition_2, date_expedition_22, 
					   code_expedie_0, code_expedie_1, code_expedie_2, code_expedie_22, 
					   no_bordereau_0, no_bordereau_1, no_bordereau_2, no_bordereau_22, 
					   montant_facture_0_c, montant_facture_0_h, montant_facture_1_c, 
					   montant_facture_1_h, montant_facture_2_c, montant_facture_2_h, 
					   montant_facture_22_c, montant_facture_22_h, montant_regle_0_c, 
					   montant_regle_0_h, montant_regle_1_c, montant_regle_1_h, montant_regle_2_c, 
					   montant_regle_2_h, montant_regle_22_c, montant_regle_22_h, delai_expedition_0, 
					   delai_expedition_1, delai_expedition_2, delai_expedition_22, 
					   delai_solde_0_c, delai_solde_0_h, delai_solde_1_c, delai_solde_1_h, 
					   delai_solde_2_c, delai_solde_2_h, delai_solde_22_c, delai_solde_22_h, 
					   ghs_id, particularite_t2a, date_vente, code_cloture, montant_encours_c, 
					   montant_encours_0_c, montant_encours_1_c, montant_encours_2_c, 
					   montant_encours_22_c, montant_encours_h, montant_encours_0_h, 
					   montant_encours_1_h, montant_encours_2_h, montant_encours_22_h, 
					   code_cp_demandee, date_encours, ghs_bebe1_id, ghs_bebe2_id, ghs_bebe3_id, 
					   nb_rejets, montant_comptabilise_c, montant_comptabilise_h, montant_comptabilise_0_c, 
					   montant_comptabilise_0_h, montant_comptabilise_1_c, montant_comptabilise_1_h, 
					   montant_comptabilise_2_c, montant_comptabilise_2_h, montant_comptabilise_22_c, 
					   montant_comptabilise_22_h, no_facture_reference, date_solde_reference, 
					   date_solde_reference_c, date_solde_reference_h, date_solde_reference_0_c, 
					   date_solde_reference_1_c, date_solde_reference_2_c, date_solde_reference_22_c, 
					   date_solde_reference_0_h, date_solde_reference_1_h, date_solde_reference_2_h, 
					   date_solde_reference_22_h, date_solde_c, date_solde_h, montant_facture_c_actes_inclus_dans_sejour, 
					   montant_facture_h_actes_inclus_dans_sejour, montant_comptabilise_budget_global_c, 
					   no_facture_od_avoir, sejour_id, facture_reference_id, facture_od_avoir_id, 
					   ghm_id
				   FROM w_factures_pmsi;



					-- Ajout des lignes
				   INSERT INTO activite[PX].p_factures_lignes_c(
						no_facture, date_debut, date_fin, nb_rubrique, coefficient, coefficient_mco, 
						rubrique_facturation_id, prestation_id, montant_facture, montant_facture_0, 
						montant_facture_1, montant_facture_2, montant_facture_22, taux_0, 
						taux_1, taux_2, taux_22, finess, prix_unitaire, lieu_id, nb_prestation, 
						montant_comptabilise, montant_comptabilise_0, montant_comptabilise_1, 
						montant_comptabilise_2, montant_comptabilise_22, rubrique_comptabilisation_id, 
						montant_encours, montant_encours_0, montant_encours_1, montant_encours_2, 
						montant_encours_22, montant_facture_actes_inclus_dans_sejour, 
						montant_facture_0_actes_inclus_dans_sejour, montant_facture_1_actes_inclus_dans_sejour, 
						montant_facture_2_actes_inclus_dans_sejour, montant_facture_22_actes_inclus_dans_sejour, 
						origine_facturation_id, montant_comptabilise_budget_global_1, 
						facture_id, protocole_id, compte_produit_id)
					SELECT 
						p_factures.no_facture, w_factures_lignes_pmsi.date_debut, w_factures_lignes_pmsi.date_fin, nb_rubrique, coefficient, coefficient_mco, 
							rubrique_facturation_id, prestation_id, montant_facture, montant_facture_0, 
							montant_facture_1, montant_facture_2, montant_facture_22, taux_0, 
							taux_1, taux_2, taux_22, finess, prix_unitaire, lieu_id, nb_prestation, 
							montant_comptabilise, montant_comptabilise_0, montant_comptabilise_1, 
							montant_comptabilise_2, montant_comptabilise_22, rubrique_comptabilisation_id, 
							montant_encours, montant_encours_0, montant_encours_1, montant_encours_2, 
							montant_encours_22, montant_facture_actes_inclus_dans_sejour, 
							montant_facture_0_actes_inclus_dans_sejour, montant_facture_1_actes_inclus_dans_sejour, 
							montant_facture_2_actes_inclus_dans_sejour, montant_facture_22_actes_inclus_dans_sejour, 
							origine_facturation_id, montant_comptabilise_budget_global_1, 
							p_factures.oid AS facture_id, protocole_id, compte_produit_id
					FROM w_factures_lignes_pmsi
					JOIN activite[PX].p_factures ON w_factures_lignes_pmsi.no_facture = p_factures.no_facture ;
					
					

					
					-- En cours PMSI public
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id)
					SELECT 
                        p_sejours.oid,
                        p_sejours.no_sejour, 
                        MAX(p_sejours.no_sejour || '.BG'), 
                        MAX(p_sejours.no_sejour || '.BG'), 
                        MAX(p_sejours.date_entree), 
                        MAX(p_sejours.date_sortie), 
                        '0', 
                        '0', 
                        '20991231'::date,
                        MAX(p_sejours.tiers_payant_0_id), 
                        MAX(p_sejours.tiers_payant_1_id), 
                        MAX(p_sejours.tiers_payant_2_id), 
                        MAX(p_sejours.tiers_payant_22_id),
                        MAX(p_sejours.ghs_id),
                        MAX(p_sejours.ghs_bebe1_id),
                        MAX(p_sejours.ghs_bebe2_id),
                        MAX(p_sejours.ghs_bebe3_id)
                    FROM pmsi.p_rss
                    JOIN base.t_finess ON p_rss.finess = t_finess.code AND t_finess.type_etablissement <> '1'
                    JOIN activite[PX].p_sejours on no_sejour_administratif = p_sejours.no_sejour AND p_sejours.est_budget_global = '1'
                    LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND p_factures.no_facture LIKE '%BG'
                    WHERE p_rss.en_cours = '1' AND p_factures.no_facture IS NULL AND 
                        p_sejours.type_sejour IN ('1','2','5')
                    GROUP BY 1,2;
					
					-- Sejours BG PMSi qui ne sont pas dans les RSS
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id)
					SELECT p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						p_sejours.date_sortie, 
						'0', 
						'0', 
						'20991231'::date,
						p_sejours.tiers_payant_0_id, 
						p_sejours.tiers_payant_1_id, 
						p_sejours.tiers_payant_2_id, 
						p_sejours.tiers_payant_22_id,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id
					FROM activite[PX].p_sejours
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
					WHERE p_sejours.est_budget_global = '1' AND
                        p_sejours.type_sejour IN ('1','2','5') AND
						type_t2a = '1' AND
						date_sortie between date(date_trunc('year',now() - interval '1 year')) AND  now() AND
						code_sorti = '1' AND
						no_sejour NOT IN (SELECt no_sejour FROm activite[PX].p_factures where no_facture like '%BG') AND
						no_sejour NOT IN (
							SELECT p_factures.no_sejour
							FROM activite[PX].p_factures_lignes_c
							JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
							JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
							JOIN activite.t_prestations ON prestation_id = t_prestations.oid
							WHERE p_sejours.est_budget_global = '1' AND
								p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
								code_facture = '1' AND
								(t_prestations.code = 'PJ' OR t_prestations.code LIKE 'GHS%') AND
								(taux_1 = 100 OR taux_2 = 100 OR taux_0 = 100) 
							GROUP BY 1
							HAVING SUM(montant_facture_1+montant_facture_0+montant_facture_2) > 0
						);
                        
                    -- Séances pour séjour présents	
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id,
						ghs_bebe1_id,
						ghs_bebe2_id,
						ghs_bebe3_id)
					SELECT p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						date(date_trunc('month',now()) + interval '1 month' - interval '1 day'), 
						'0', 
						'0', 
						'20991231'::date,
						p_sejours.tiers_payant_0_id, 
						p_sejours.tiers_payant_1_id, 
						p_sejours.tiers_payant_2_id, 
						p_sejours.tiers_payant_22_id,
						p_sejours.ghs_id,
						p_sejours.ghs_bebe1_id,
						p_sejours.ghs_bebe2_id,
						p_sejours.ghs_bebe3_id
					FROM activite[PX].p_sejours
					JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
					JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
					WHERE p_sejours.est_budget_global = '1' AND
						type_t2a = '1' AND
						date_entree between date(date_trunc('year',now() - interval '1 year')) AND  now() AND
						p_sejours.type_sejour IN ('5') AND
						code_sorti <> '1' AND
						no_sejour NOT IN (SELECt no_sejour FROm activite[PX].p_factures where no_facture like '%BG') AND
						no_sejour NOT IN (
							SELECT p_factures.no_sejour
							FROM activite[PX].p_factures_lignes_c
							JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
							JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
							JOIN activite.t_prestations ON prestation_id = t_prestations.oid
							WHERE p_sejours.est_budget_global = '1' AND
								code_facture = '1' AND
								t_prestations.code = 'PJ' AND
								(taux_2 = 100 OR taux_0 = 100) 
							GROUP BY 1
							HAVING SUM(montant_facture_0+montant_facture_2) > 0
						);
						
					
				-- Il peut y avoir des lignes en double avec la récupération standard
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
				USING
				(
					SELECT no_sejour, prestation_id, 
						p_factures_lignes_non_facturees_c.date_debut, 
						p_factures_lignes_non_facturees_c.date_fin,
						p_factures_lignes_non_facturees_c.prix_unitaire,
						MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.BG' THEN p_factures_lignes_non_facturees_c.no_facture ELSE NULL END) AS no_facture
					FROm activite[PX].p_factures_lignes_non_facturees_c
					JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5
					HAVING count(DISTINCT p_factures.no_facture) > 1 AND
						MAX(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 1 AND
						MIN(CASE WHEN p_factures.no_facture LIKE '%.BG' THEN 1 ELSE 0 END) = 0
				) subview
				WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id AND
					p_factures_lignes_non_facturees_c.date_debut = subview.date_debut AND
					p_factures_lignes_non_facturees_c.date_fin = subview.date_fin AND
					p_factures_lignes_non_facturees_c.prix_unitaire = subview.prix_unitaire
				;
					
				-- Ou des lignes en double avec la facturation
				DELETE FROM activite[PX].p_factures_lignes_non_facturees_c
				USING
				(
					SELECT no_sejour, prestation_id, 
						p_factures_lignes_non_facturees_c.date_debut, 
						p_factures_lignes_non_facturees_c.date_fin,
						p_factures_lignes_non_facturees_c.prix_unitaire,
						MAX(CASE WHEN p_factures.no_facture NOT LIKE '%.BG' THEN p_factures_lignes_non_facturees_c.no_facture ELSE NULL END) AS no_facture
					FROm activite[PX].p_factures_lignes_non_facturees_c
					JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5
				) subview
				JOIN 
				(
					SELECT no_sejour, prestation_id, 
						p_factures_lignes_c.date_debut, 
						p_factures_lignes_c.date_fin,
						p_factures_lignes_c.prix_unitaire,
						p_factures.no_facture
					FROm activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					GROUP BY 1,2,3,4,5,6
				) subview2
				ON  subview2.prestation_id = subview.prestation_id AND
					subview2.date_debut = subview.date_debut AND
					subview2.date_fin = subview.date_fin AND
					subview2.prix_unitaire = subview.prix_unitaire
				WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture AND
					p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id AND
					p_factures_lignes_non_facturees_c.date_debut = subview.date_debut AND
					p_factures_lignes_non_facturees_c.date_fin = subview.date_fin AND
					p_factures_lignes_non_facturees_c.prix_unitaire = subview.prix_unitaire
				;
					
					
					-- Factures non assurés ajoutées à tord (on trouve un 100% dans patient ou tp1
					DROP TABLE IF EXISTS w_sejours_bg_24;
					CREATE TEMP TABLE w_sejours_bg_24 AS
					SELECT p_factures.no_sejour, SUM(montant_facture_0+montant_facture_1+montant_facture_2) AS montant_facture_100
					FROM activite[PX].p_factures_lignes_c
					JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					JOIN activite[PX].p_sejour_pmsi ON p_sejour_pmsi.sejour_id = p_sejours.oid
					JOIN pmsi.p_rss ON p_sejour_pmsi.rss_id = p_rss.oid
					WHERE p_sejours.est_budget_global = '1' AND
						code_facture = '1' AND
						(
                        t_prestations.code = 'PJ' OR
                        t_prestations.code LIKE 'GHS%'
                        ) AND
						(taux_1 + taux_2 + taux_0 = 100 OR 
						taux_0+taux_1+taux_2=0 AND montant_facture_1 = montant_facture
						) AND
						p_rss.traitement_epmsi NOT IN ('30','31','32','33')
					GROUP BY 1
					HAVING SUM(montant_facture_0+montant_facture_1+montant_facture_2) > 0
					ORDER BY 1;

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

					UPDATE activite[PX].p_factures SET
						code_facture = '1',
                        date_facture = date_fin,
						montant_facture_c = 0,
						montant_facture_1_c = 0,
						montant_comptabilise_1_c =0,
						montant_comptabilise_budget_global_c = 0
					WHERE no_sejour IN (SELECT no_sejour FROM w_sejours_bg_24) AND
						no_facture LIKE '%BG' AND
						montant_comptabilise_budget_global_c = 0;
                        
                        
                    -- Transfert de lignes non facturées vers budget global
                    UPDATE activite[PX].p_factures_lignes_non_facturees_c
                    SET no_facture = subview.no_facture_bg
                    FROM
                    (
                    SELECT p_sejours.no_sejour, t_prestations.code, t_prestations.texte, p_factures_lignes_non_facturees_c.*,
                        p_factures_bg.code_facture,p_factures_bg.no_facture AS no_facture_bg
                    FROM activite[PX].p_factures_lignes_non_facturees_c
                    JOIN activite[PX].p_factures ON p_factures_lignes_non_facturees_c.no_facture = p_factures.no_facture
                    JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND type_sejour IN ('1','2','5')
                    JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid 
                    JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid AND type_t2a = '1'
                    JOIN activite.t_prestations ON p_factures_lignes_non_facturees_c.prestation_id = t_prestations.oid
                    JOIN activite[PX].p_factures p_factures_bg ON p_factures_bg.no_sejour = p_factures.no_sejour AND p_factures_bg.no_facture LIKE '%BG' AND
                        p_factures_lignes_non_facturees_c.date_debut BETWEEN p_factures_bg.date_debut AND p_factures_bg.date_fin
                    WHERE p_factures_lignes_non_facturees_c.no_facture NOT LIKE '%BG' AND
                        t_prestations.code IN ('EMI','ETI','PII','PME','PH8','PHU') AND
                        p_factures_bg.code_facture = '0'
                    ) subview
                    WHERE p_factures_lignes_non_facturees_c.no_facture = subview.no_facture and
                        p_factures_lignes_non_facturees_c.prestation_id = subview.prestation_id
                        ;
				




					
			]]></sqlcmd>
		</NODE>

		<NODE label="Budget global Actes">
			<condition><![CDATA[
				"[ENV_TYPEETS]" != "1"
			]]></condition>
			<sqlcmd><![CDATA[
	
							
					-- Valorisation actes	
					DROP TABLE IF EXISTS w_sejours_hospit_bg;
					CREATE TEMP TABLE w_sejours_hospit_bg AS	
					SELECT p_factures.no_sejour AS no_sejour_bg,
						MIN(CASE
							WHEN t_prestations.code IN ('GHS', 'PJ') THEN origine_facturation_id
							WHEN origine_facturation_id = 2 THEN origine_facturation_id
							WHEN type_sejour = '3' THEN 2
							ELSE 9 END) AS origine_facturation_id
					FROM activite[PX].p_sejours
					JOIN activite[PX].p_factures ON p_factures.no_sejour = p_sejours.no_sejour AND p_factures.code_facture = '1'
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture
					LEFT JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					WHERE est_budget_global = '1' 
					GROUP BY 1;

					
					-- actes inclus	dans séjour	
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_2_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_2 / 100.00,
						montant_facture_0_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_0 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0 AND
						(taux_0 <> 0 OR taux_1 <> 0 OR taux_2 <> 0 OR taux_22 <> 0);
						
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient),
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient)
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0 AND
						taux_1 = 0 AND taux_2 = 0 AND taux_0 = 0;


					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_1_actes_inclus_dans_sejour = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 1
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						montant_facture_actes_inclus_dans_sejour = 0 AND
						(montant_facture_2 + montant_facture_0) <> 0 AND montant_facture_1 = 0;
						
					
					--arrondis
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_facture_1_actes_inclus_dans_sejour = 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)
					WHERE montant_facture_1_actes_inclus_dans_sejour <> 0 AND 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);
										
								
					
					-- actes externes
					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1 = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00,
						montant_facture_2 = (prix_unitaire * nb_prestation * coefficient) * taux_2 / 100.00,
						montant_facture_0 = (prix_unitaire * nb_prestation * coefficient) * taux_0 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0 AND
						(montant_facture_1 + montant_facture_2 + montant_facture_0) = 0;

					UPDATE activite[PX].p_factures_lignes_h
					SET 
						montant_facture = prix_unitaire * nb_prestation * coefficient,
						montant_facture_1 = (prix_unitaire * nb_prestation * coefficient) * taux_1 / 100.00
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND prix_unitaire <> 0  AND
						taux_1 <> 0 AND (montant_facture_2 + montant_facture_0) <> 0 AND montant_facture_1 = 0;


					-- Arrondis
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_facture_1 = montant_facture - (montant_facture_0+montant_facture_1+montant_facture_2+montant_facture_22)
					FROM activite[PX].p_factures 
					JOIN w_sejours_hospit_bg ON p_factures.no_sejour = w_sejours_hospit_bg.no_sejour_bg AND origine_facturation_id = 2
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND 
						montant_facture_1 <> 0 AND 
						montant_facture <> (montant_facture_0+montant_facture_1+montant_facture_2+montant_facture_22);
						
						
					-- Ajout des honoraires budget global dans la partie CLINIQUE
					INSERT INTO activite[PX].p_factures_lignes_c(
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_id,
						prestation_id,
						montant_facture,
						montant_facture_0,
						montant_facture_1,
						montant_facture_2,
						montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						montant_encours,
						montant_encours_0,
						montant_encours_1,
						montant_encours_2,
						montant_encours_22,
						montant_facture_actes_inclus_dans_sejour,
						montant_facture_0_actes_inclus_dans_sejour,
						montant_facture_1_actes_inclus_dans_sejour,
						montant_facture_2_actes_inclus_dans_sejour,
						montant_facture_22_actes_inclus_dans_sejour,
						origine_facturation_id,
						montant_comptabilise_budget_global_1,
						facture_id,
						protocole_id,
						compte_produit_id)
					SELECT 
						p_factures.no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						CASE WHEN p_factures_lignes_h.rubrique_facturation_id <> 0 THEN p_factures_lignes_h.rubrique_facturation_id ELSE COALESCE(t_rubriques_facturation.oid,0) END AS rubrique_facturation_id,
						prestation_id,
						CASE WHEN montant_comptabilise_0 <> 0 THEN montant_facture_0 ELSE 0 END +
						CASE WHEN montant_comptabilise_1 <> 0 THEN montant_facture_1 ELSE 0 END +
						CASE WHEN montant_comptabilise_2 <> 0 THEN montant_facture_2 ELSE 0 END +
						CASE WHEN montant_comptabilise_22 <> 0 THEN montant_facture_22 ELSE 0 END AS montant_facture,
						CASE WHEN montant_comptabilise_0 <> 0 THEN montant_facture_0 ELSE 0 END AS montant_facture_0,
						CASE WHEN montant_comptabilise_1 <> 0 THEN montant_facture_1 ELSE 0 END AS montant_facture_1,
						CASE WHEN montant_comptabilise_2 <> 0 THEN montant_facture_2 ELSE 0 END AS montant_facture_2,
						CASE WHEN montant_comptabilise_22 <> 0 THEN montant_facture_22 ELSE 0 END AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						CASE WHEN montant_comptabilise_1 <> 0 THEN nb_prestation ELSE 0 END,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						CASE WHEN p_factures_lignes_h.rubrique_facturation_id <> 0 THEN p_factures_lignes_h.rubrique_facturation_id ELSE COALESCE(t_rubriques_facturation.oid,0) END AS rubrique_comptabilisation_id,
						montant_encours,
						montant_encours_0,
						montant_encours_1,
						montant_encours_2,
						montant_encours_22,
						montant_facture_actes_inclus_dans_sejour,
						montant_facture_0_actes_inclus_dans_sejour,
						montant_facture_1_actes_inclus_dans_sejour,
						montant_facture_2_actes_inclus_dans_sejour,
						montant_facture_22_actes_inclus_dans_sejour,
						2::bigint AS origine_facturation_id,
						0::numeric AS montant_comptabilise_budget_global_1,
						p_factures.oid AS facture_id,
						protocole_id,
						0::bigint AS compte_produit_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					LEFT JOIN activite[PX].t_rubriques_facturation ON t_prestations.code = t_rubriques_facturation.code
					JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture 
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE p_factures.code_facture = '1' AND
						((p_sejours.type_sejour = '3' AND p_factures_lignes_h.no_facture NOT LIKE '%BG') OR 
                        montant_comptabilise <> 0 OR 
                        montant_comptabilise_0 <> 0 OR 
                        montant_comptabilise_1 <> 0 OR 
                        montant_comptabilise_2 <> 0) ;

				
					UPDATE activite[PX].p_factures_lignes_h
					SET montant_comptabilise = 0, montant_comptabilise_0 = 0, montant_comptabilise_1 = 0, montant_comptabilise_2 = 0
					FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND 
						(montant_comptabilise <> 0 OR montant_comptabilise_0 <> 0 OR montant_comptabilise_1 <> 0 OR montant_comptabilise_2 <> 0) ;
						
						
					-- Ajout des actes inclus dans séjour dans la partie clinique (verrouillé)
					DROP TABLE IF EXISTS w_actes_inclus;
					CREATE TEMP TABLE w_actes_inclus AS
					SELECT 
						p_factures.no_sejour,
						p_factures.no_facture AS no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_facturation_id,
						prestation_id,
						0::numeric AS montant_facture,
						0::numeric AS montant_facture_0,
						0::numeric AS montant_facture_1,
						0::numeric AS montant_facture_2,
						0::numeric AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						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,
						COALESCE(t_rubriques_facturation.oid,0) AS rubrique_comptabilisation_id,
						montant_encours,
						montant_encours_0,
						montant_encours_1,
						montant_encours_2,
						montant_encours_22,
						montant_facture_actes_inclus_dans_sejour,
						montant_facture_0_actes_inclus_dans_sejour,
						montant_facture_1_actes_inclus_dans_sejour,
						montant_facture_2_actes_inclus_dans_sejour,
						montant_facture_22_actes_inclus_dans_sejour,
						3::bigint AS origine_facturation_id,
						0::numeric AS montant_comptabilise_budget_global_1,
						p_factures.oid AS facture_id,
						protocole_id,
						0::bigint AS compte_produit_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite.t_prestations ON prestation_id = t_prestations.oid
					LEFT JOIN activite[PX].t_rubriques_facturation ON t_prestations.code = t_rubriques_facturation.code
					JOIN activite[PX].p_factures ON p_factures_lignes_h.no_facture = p_factures.no_facture 
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					WHERE 1<>1 AND
						(montant_facture_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_0_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_1_actes_inclus_dans_sejour <> 0 OR 
						montant_facture_2_actes_inclus_dans_sejour <> 0) ;


					UPDATE w_actes_inclus
					SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
					FROM activite[PX].p_factures 
					WHERE w_actes_inclus.no_sejour = p_factures.no_sejour AND
						p_factures.no_facture LIKE '%BG' ;


					INSERT INTO activite[PX].p_factures_lignes_c	
					(
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_id,
						prestation_id,
						montant_facture,
						montant_facture_0,
						montant_facture_1,
						montant_facture_2,
						montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						montant_encours,
						montant_encours_0,
						montant_encours_1,
						montant_encours_2,
						montant_encours_22,
						montant_facture_actes_inclus_dans_sejour,
						montant_facture_0_actes_inclus_dans_sejour,
						montant_facture_1_actes_inclus_dans_sejour,
						montant_facture_2_actes_inclus_dans_sejour,
						montant_facture_22_actes_inclus_dans_sejour,
						origine_facturation_id,
						montant_comptabilise_budget_global_1,
						facture_id,
						protocole_id,
						compte_produit_id
					)	
					SELECT 
						no_facture,
						date_debut,
						date_fin,
						nb_rubrique,
						coefficient,
						coefficient_mco,
						rubrique_facturation_id,
						prestation_id,
						0::numeric AS montant_facture,
						0::numeric AS montant_facture_0,
						0::numeric AS montant_facture_1,
						0::numeric AS montant_facture_2,
						0::numeric AS montant_facture_22,
						taux_0,
						taux_1,
						taux_2,
						taux_22,
						prix_unitaire,
						lieu_id,
						nb_prestation,
						montant_comptabilise,
						montant_comptabilise_0,
						montant_comptabilise_1,
						montant_comptabilise_2,
						montant_comptabilise_22,
						rubrique_comptabilisation_id,
						montant_encours,
						montant_encours_0,
						montant_encours_1,
						montant_encours_2,
						montant_encours_22,
						montant_facture_actes_inclus_dans_sejour,
						montant_facture_0_actes_inclus_dans_sejour,
						montant_facture_1_actes_inclus_dans_sejour,
						montant_facture_2_actes_inclus_dans_sejour,
						montant_facture_22_actes_inclus_dans_sejour,
						origine_facturation_id,
						montant_comptabilise_budget_global_1,
						facture_id,
						protocole_id,
						compte_produit_id
					FROM w_actes_inclus;
					
					-- Correction n° facture
					UPDATE activite[PX].p_factures_lignes_c
						SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
						FROM activite[PX].p_factures 
						WHERE p_factures_lignes_c.montant_facture_actes_inclus_dans_sejour <> 0 AND
							split_part(p_factures_lignes_c.no_facture,'.',1) = p_factures.no_sejour AND
							p_factures.no_facture LIKE '%BG' AND
							p_factures_lignes_c.no_facture NOT LIKE '%BG' AND
							p_factures_lignes_c.montant_facture = 0 AND
							p_factures_lignes_c.montant_comptabilise = 0;

					UPDATE activite[PX].p_factures_lignes_h
						SET no_facture = p_factures.no_facture, facture_id = p_factures.oid
						FROM activite[PX].p_factures 
						WHERE p_factures_lignes_h.montant_facture_actes_inclus_dans_sejour <> 0 AND
							split_part(p_factures_lignes_h.no_facture,'.',1) = p_factures.no_sejour AND
							p_factures.no_facture LIKE '%BG' AND
							p_factures_lignes_h.no_facture NOT LIKE '%BG' AND
							p_factures_lignes_h.montant_facture = 0 AND
							p_factures_lignes_h.montant_comptabilise = 0;
						
						
					-- Cumuls factures
					DROP TABLE IF EXISTS w_factures_corrigees;
					CREATE TEMP TABLE w_factures_corrigees AS 
					SELECT
						p_factures_lignes_c.no_facture,
						
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture ELSE 0 END),0) AS ligne_facture_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_0 ELSE 0 END),0) AS ligne_facture_0_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_1 ELSE 0 END),0) AS ligne_facture_1_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_2 ELSE 0 END),0) AS ligne_facture_2_c,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_22 ELSE 0 END),0) AS ligne_facture_22_c,
						COALESCE(SUM(montant_comptabilise),0) AS ligne_comptabilise_c,
						COALESCE(SUM(montant_comptabilise_0),0) AS ligne_comptabilise_0_c,
						COALESCE(SUM(montant_comptabilise_1),0) AS ligne_comptabilise_1_c,
						COALESCE(SUM(montant_comptabilise_2),0) AS ligne_comptabilise_2_c,
						COALESCE(SUM(montant_comptabilise_22),0) AS ligne_comptabilise_22_c,
						
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture ELSE 0 END),0) AS ligne_facture_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_0 ELSE 0 END),0) AS ligne_facture_0_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_1 ELSE 0 END),0) AS ligne_facture_1_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_2 ELSE 0 END),0) AS ligne_facture_2_h,
						COALESCE(SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_22 ELSE 0 END),0) AS ligne_facture_22_h,
						0::numeric AS ligne_comptabilise_h,
						0::numeric AS ligne_comptabilise_0_h,
						0::numeric AS ligne_comptabilise_1_h,
						0::numeric AS ligne_comptabilise_2_h,
						0::numeric AS ligne_comptabilise_22_h
					FROM activite[PX].p_factures
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour AND est_budget_global = '1'
					LEFT JOIN activite[PX].p_factures_lignes_c ON p_factures_lignes_c.no_facture = p_factures.no_facture 
					GROUP BY 1
					HAVING SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_0 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_0_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_1 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_1_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_2 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_2_c) OR
						SUM(CASE WHEN origine_facturation_id = 1 THEN montant_facture_22 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_22_c) OR
						SUM(montant_comptabilise) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_c) OR
						SUM(montant_comptabilise_0) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_0_c) OR
						SUM(montant_comptabilise_1) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_1_c) OR
						SUM(montant_comptabilise_2) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_2_c) OR
						SUM(montant_comptabilise_22) IS DISTINCT FROM MAX(p_factures.montant_comptabilise_22_c) OR

						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_0 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_0_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_1 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_1_h) OR
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_2 ELSE 0 END) IS DISTINCT FROM MAX(p_factures.montant_facture_2_h) OR 
						SUM(CASE WHEN origine_facturation_id = 2 THEN montant_facture_22 ELSE 0 END) IS DISTINCT FROM  MAX(p_factures.montant_facture_22_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_0_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_1_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_2_h) OR
						0::numeric IS DISTINCT FROM MAX(p_factures.montant_comptabilise_22_h) ;

					UPDATE activite[PX].p_factures
					SET 
						montant_facture_c = w_factures_corrigees.ligne_facture_c,
						montant_facture_0_c = w_factures_corrigees.ligne_facture_0_c,
						montant_facture_1_c = w_factures_corrigees.ligne_facture_1_c,
						montant_facture_2_c = w_factures_corrigees.ligne_facture_2_c,
						montant_facture_22_c = w_factures_corrigees.ligne_facture_22_c,
						montant_comptabilise_c = w_factures_corrigees.ligne_comptabilise_c,
						montant_comptabilise_0_c = w_factures_corrigees.ligne_comptabilise_0_c,
						montant_comptabilise_1_c = w_factures_corrigees.ligne_comptabilise_1_c,
						montant_comptabilise_2_c = w_factures_corrigees.ligne_comptabilise_2_c,
						montant_comptabilise_22_c = w_factures_corrigees.ligne_comptabilise_22_c,
						montant_facture_h = w_factures_corrigees.ligne_facture_h,
						montant_facture_0_h = w_factures_corrigees.ligne_facture_0_h,
						montant_facture_1_h = w_factures_corrigees.ligne_facture_1_h,
						montant_facture_2_h = w_factures_corrigees.ligne_facture_2_h,
						montant_facture_22_h = w_factures_corrigees.ligne_facture_22_h,
						montant_comptabilise_h = w_factures_corrigees.ligne_comptabilise_h,
						montant_comptabilise_0_h = w_factures_corrigees.ligne_comptabilise_0_h,
						montant_comptabilise_1_h = w_factures_corrigees.ligne_comptabilise_1_h,
						montant_comptabilise_2_h = w_factures_corrigees.ligne_comptabilise_2_h,
						montant_comptabilise_22_h = w_factures_corrigees.ligne_comptabilise_22_h
					FROM w_factures_corrigees
					WHERE w_factures_corrigees.no_facture = p_factures.no_facture;
					
					
					-- Report des actes non facturés honoraires budget global pour encours
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
						facture_id,
						no_facture, 
						date_debut, 
						date_fin, 
						nb_rubrique, 
						coefficient, 
						rubrique_facturation_id, 
						prestation_id, 
						prix_unitaire, 
						lieu_id)
					SELECT 
						p_factures.oid AS facture_id,
						p_factures.no_facture AS no_facture,
						p_factures_lignes_h.date_debut,
						p_factures_lignes_h.date_fin,
						p_factures_lignes_h.nb_rubrique,
						p_factures_lignes_h.coefficient,
						p_factures_lignes_h.rubrique_facturation_id,
						p_factures_lignes_h.prestation_id,
						p_factures_lignes_h.prix_unitaire,
						p_factures_lignes_h.lieu_id
					FROM activite[PX].p_factures_lignes_h
					JOIN activite[PX].p_factures on p_factures_lignes_h.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_factures.code_facture = '0' AND 
						p_sejours.est_budget_global = '1' AND
						p_sejours.type_sejour = '3' AND
						p_factures.no_sejour NOT IN (SELECT no_sejour FROM activite[PX].p_factures WHERE code_facture = '1') AND
						p_factures_lignes_h.no_facture NOT IN (SELECT no_facture FROM activite[PX].p_factures_lignes_non_facturees_c)
						;
                        
					-- Report des actes non facturés honoraires budget global pour encours
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
						facture_id,
						no_facture, 
						date_debut, 
						date_fin, 
						nb_rubrique, 
						coefficient, 
						rubrique_facturation_id, 
						prestation_id, 
						prix_unitaire, 
						lieu_id)
					SELECT 
						p_factures.oid AS facture_id,
						p_factures.no_facture AS no_facture,
						p_factures_lignes_non_facturees_h.date_debut,
						p_factures_lignes_non_facturees_h.date_fin,
						p_factures_lignes_non_facturees_h.nb_rubrique,
						p_factures_lignes_non_facturees_h.coefficient,
						p_factures_lignes_non_facturees_h.rubrique_facturation_id,
						p_factures_lignes_non_facturees_h.prestation_id,
						p_factures_lignes_non_facturees_h.prix_unitaire,
						p_factures_lignes_non_facturees_h.lieu_id
					FROM activite[PX].p_factures_lignes_non_facturees_h 
					JOIN activite[PX].p_factures on p_factures_lignes_non_facturees_h.no_facture = p_factures.no_facture
					JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_factures.code_facture = '0' AND 
						p_sejours.est_budget_global = '1' AND
						p_sejours.type_sejour = '3' AND
						p_factures.no_sejour NOT IN (SELECT no_sejour FROM activite[PX].p_factures WHERE code_facture = '1') --AND
						;
					
					TRUNCATE activite[PX].p_factures_lignes_non_facturees_h
					;
                        
			]]></sqlcmd>
		</NODE>

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

	
					-- Séjours externes BG qui ne sont pas dans le PMSI
					INSERT INTO activite[PX].p_factures(
						sejour_id,
						no_sejour, 
						no_facture, 
						no_facture_reference, 
						date_debut, 
						date_fin, 
						type_facture, 
						code_facture, 
						date_facture, 
						tiers_payant_0_id, 
						tiers_payant_1_id, 
						tiers_payant_2_id, 
						tiers_payant_22_id,
						ghs_id)
					SELECT p_sejours.oid,
						p_sejours.no_sejour, 
						p_sejours.no_sejour || '.BG', 
						p_sejours.no_sejour || '.BG', 
						p_sejours.date_entree, 
						p_sejours.date_sortie, 
						'0', 
						'0', 
						'20991231'::date,
						p_sejours.tiers_payant_0_id, 
						p_sejours.tiers_payant_1_id, 
						p_sejours.tiers_payant_2_id, 
						p_sejours.tiers_payant_22_id,
						p_sejours.ghs_id
					FROM activite[PX].p_sejours
						JOIN activite[PX].t_lieux ON lieu_sortie_id = t_lieux.oid
						JOIN activite[PX].t_services_facturation ON service_facturation_id = t_services_facturation.oid
					WHERE 
						p_sejours.est_budget_global = '1' AND
						type_t2a <> '1' AND
						p_sejours.type_sejour = '3' AND
						date_entree between now() - interval '1 year' AND now() AND
						code_sorti = '1' AND
						no_sejour NOT IN (SELECT no_sejour FROM activite[PX].p_factures WHERE no_facture like '%BG') AND
						no_sejour NOT IN 
                            (
                            SELECT no_sejour
                            FROM activite[PX].p_factures_lignes_c
                            JOIN activite[PX].p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
                            WHERE p_factures_lignes_c.no_facture NOT LIKE '%BG' AND montant_comptabilise_1 <> 0
                            )  
					;
					
					-- Sur Externes, Récupérer actes facturés partiellement
					INSERT INTO activite[PX].p_factures_lignes_non_facturees_c(
						facture_id,
						no_facture, 
						date_debut,
						rubrique_facturation_id, 
						prestation_id,  
						date_fin, 
						nb_rubrique, 
						coefficient, 
						lieu_id,
						prix_unitaire
						)
					SELECT 
						p_factures_bg.oid AS facture_id,
						p_factures_bg.no_facture AS no_facture,
						p_factures_lignes_c.date_debut,
						p_factures_lignes_c.rubrique_facturation_id,
						p_factures_lignes_c.prestation_id,
						MAX(p_factures_lignes_c.date_fin),
						1,
						1,
						MAX(p_factures_lignes_c.lieu_id),
						(MAX(prix_unitaire) * MAX(coefficient) * SUM(nb_rubrique)) - SUM(montant_facture) AS prix_unitaire
					FROM activite[PX].p_factures_lignes_c
						JOIN activite[PX].p_factures on p_factures_lignes_c.no_facture = p_factures.no_facture
						JOIN activite[PX].p_factures p_factures_bg ON p_factures_bg.no_sejour = p_factures.no_sejour and p_factures_bg.no_facture LIKE '%BG'
						JOIN activite[PX].p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
					WHERE p_sejours.type_sejour = '3' AND
						p_factures_bg.code_facture = '0' AND
						p_factures_lignes_c.no_facture nOT LIKE '%BG' AND
						montant_encours = 0 AND p_factures_bg.montant_encours_c = 0
					GROUP BY 1,2,3,4,5
					HAVING
						SUM(nb_rubrique) > 0 AND
						((MAX(prix_unitaire) * MAX(coefficient) * SUM(nb_rubrique)) - SUM(montant_facture)) > 1
					;
					
					

					
			]]></sqlcmd>
		</NODE>



	</NODE>

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

		<NODE label="Ecritures comptables">
			<sqlcmd><![CDATA[
				VACUUM ANALYSE prod_web100t.FAC_FACTURE;
				
				DROP TABLE IF EXISTS w_ecriture_comptable;
				CREATE TEMP TABLE w_ecriture_comptable AS
				SELECT ECR_TYPE,
					ECR_REF_TYPE,
					ECR_OID,
					ECR_OID::text AS code_original,
					date(ECR_DATE) AS date_comptable, 
					CASE 
					WHEN LNK_JOURNAL = 'VE' AND CPT_CODE LIKE '411%' THEN 'VCLI'
					WHEN LNK_JOURNAL = 'VE' AND CPT_CODE LIKE '412%' THEN 'VCLI'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE LIKE 'PRODUIT%' THEN 'VPRD'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE = 'VENTE-HON' THEN 'VHON'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE = 'VENTE-DEP' THEN 'VHON'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE LIKE 'TVA%' THEN 'VTVA'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE LIKE 'IMPAYE' AND ECR_IS_ETS = 1 THEN 'VPRI'
					WHEN LNK_JOURNAL = 'VE' AND ECR_TYPE LIKE 'IMPAYE' AND ECR_IS_ETS = 0 THEN 'VHOI'
					WHEN CPT_CODE LIKE '758%' THEN 'PEPR'
					WHEN CPT_CODE LIKE '658%' THEN 'PEPR'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '468%' THEN 'ATT'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '471%' THEN 'ATT'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '411%' AND ECR_REF_TYPE = 'FACTURE' THEN 'RCLI'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '412%' AND ECR_REF_TYPE = 'FACTURE' THEN 'RCLI'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '411%' AND ECR_DETAILS LIKE '%NOEMIE%' THEN 'RNOE'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '412%' AND ECR_DETAILS LIKE '%NOEMIE%' THEN 'RNOE'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '419%' THEN 'ACPT'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '51%' THEN 'BANQ'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '531%' THEN 'BANQ'
					WHEN LNK_JOURNAL <> 'VE' AND CPT_CODE LIKE '466%' THEN 'PHON'
					WHEN ECR_TYPE = 'IMPAYE' THEN 'PEPR'
					WHEN LNK_JOURNAL <> 'VE' AND ECR_TYPE = 'VENTE-DIRECTE' THEN 'RDIR'
					WHEN ECR_TYPE LIKE '%PIVOT%' THEN 'PIVO'
					WHEN ECR_TYPE LIKE 'REVERS' THEN 'REVP'
					WHEN ECR_TYPE LIKE 'OD' THEN 'OD'
					ELSE '?'||ECR_TYPE END AS type_ecriture,
					ECR_OPERATION::text AS piece, 
					CASE ECR_IS_ETS WHEN 1 THEN 'C' ELSE 'H' END AS clinique_honoraire,
					COALESCE(t_compte.oid,0) AS compte_id, 
					COALESCE(t_journal.oid,0) AS journal_id, 
					COALESCE(p_sejours.oid,0::bigint) AS sejour_id, 
					COALESCE(p_sejours.no_sejour,''::text) AS no_sejour, 
					COALESCE(p_factures.oid,0::bigint) AS facture_id, 
					COALESCE(FACT_NUMERO::text,'')::text AS no_facture, 
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_id, 
					COALESCE(t_tiers_payant.oid,t_tiers_payant0.oid,0) AS tiers_payant_id, 
					ECR_DETAILS AS texte, 
					ECR_CREDIT AS montant_credit, 
					ECR_DEBIT AS montant_debit,
					ECR_OPERATION,
					CASE 
						WHEN LNK_SOURCE = 'FACTURE' THEN 'VENTE'
						WHEN LNK_SOURCE = 'IMPAYE' THEN 'VENTE'
						WHEN LNK_SOURCE = 'RGLMT' THEN 'RGLMT'
						WHEN LNK_SOURCE = 'ENC' THEN 'RGLMT'
						WHEN LNK_SOURCE = 'DEPOT' THEN 'ODBANQ'
						ELSE LNK_SOURCE END AS type_piece,
					LNK_SOURCE,
					LNK_SOURCE_OID,
					ECR_LOCKED,
					''::text AS mode_reglement_code,
					ECR_TVA_TAUX*100 AS taux_tva
				FROM w_CPT_ECRITURE_source_OP_LINK
				JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
				LEFT JOIN prod_web100t.DAT_DA ON ECR_REF_DA = DA_OID AND ECR_REF_DA > 0
				LEFT JOIN prod_web100t.FAC_FACTURE ON ECR_REF_FACT = FACT_OID AND ECR_REF_FACT > 0
				JOIN activite[PX].t_journal ON LNK_JOURNAL = t_journal.code_original
				LEFT JOIN activite[PX].t_compte ON CPT_CODE = t_compte.code
				LEFT JOIN activite[PX].p_sejours ON ECR_REF_DA = p_sejours.code_original AND ECR_REF_DA > 0
				LEFT JOIN activite[PX].p_factures ON FACT_NUMERO = p_factures.no_facture AND ECR_REF_FACT > 0
				LEFT JOIN activite[PX].t_tiers_payant ON CPT_REF = t_tiers_payant.code_original AND CPT_REF >0 AND CPT_REF_TYPE IN ('AMO','AMC')
				LEFT JOIN activite[PX].t_tiers_payant t_tiers_payant0 ON CPT_REF_TYPE IN ('DA') AND t_tiers_payant0.code = 'PATIENTS'
				LEFT JOIN activite[PX].t_medecins_administratifs ON CPT_REF = t_medecins_administratifs.code_original AND CPT_REF > 0 AND CPT_REF_TYPE IN ('PRATICIEN')
				WHERE 
					ECR_TYPE <> 'ERREUR' AND
					ECR_TYPE <> 'ENCOURS' AND
					LNK_ERROR = '' AND
					ECR_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'
				;
				
				ANALYSE w_ecriture_comptable
				;

				CREATE INDEX w_ecriture_comptable_ik_ECR_OID
					ON w_ecriture_comptable
					USING btree
					(ECR_OID);

				CREATE INDEX w_ecriture_comptable_ik_ECR_OPERATION
					ON w_ecriture_comptable
					USING btree
					(ECR_OPERATION);

				
				CREATE INDEX w_ecriture_comptable_ik_LNK_SOURCE_OID
					ON w_ecriture_comptable
					USING btree
					(LNK_SOURCE_OID);

				CREATE INDEX w_ecriture_comptable_ik_PIECE
					ON w_ecriture_comptable
					USING btree
					(PIECE);

				CREATE INDEX w_ecriture_comptable_ik_compte_id
					ON w_ecriture_comptable
					USING btree
					(compte_id);
								
				UPDATE w_ecriture_comptable SET
					no_facture = w_ecriture_comptable.no_facture || '-IM'||ECR_OPERATION::text,
					facture_id = p_factures.oid
				FROM activite[PX].p_factures
				WHERE p_factures.no_facture = w_ecriture_comptable.no_facture || '-IM'||ECR_OPERATION::text AND
					LNK_SOURCE = 'IMPAYE'
				;
				
				DROP TABLE IF EXISTS w_mode_reg;
				CREATE TEMP TABLE w_mode_reg AS
				SELECT ECR_OID,
					LNK_SOURCE,
				MAX(
					CASE FR_MODE
					WHEN 1 THEN 'CHQ'
					WHEN 2 THEN 'CB'
					WHEN 3 THEN 'ESP'
					WHEN 4 THEN 'VIR'
					ELSE 'A' END) AS mode_reglement_code 
				FROM prod_web100t.CPT_ECRITURE 
				JOIN prod_web100t.CPT_OP_LINK ON LNK_OPERATION = ECR_OPERATION
				JOIN prod_web100t.CPT_COMPTES ON ecr_compte = cpt_oid
				JOIN prod_web100t.FAC_REGLEMENTS ON LNK_SOURCE_OID = FR_OID
				WHERE LNK_SOURCE IN ('RGLMT','ENC') AND
					ECR_TYPE IN ('VALEUR_ENC','PIVOT','CAISSE')
				GROUP BY 1,2
				;
				
				CREATE INDEX w_mode_reg_i1
					ON w_mode_reg
					USING btree
					(ECR_OID);
				
				UPDATE w_ecriture_comptable
				SET mode_reglement_code = w_mode_reg.mode_reglement_code
				FROM
				w_mode_reg
				WHERE w_ecriture_comptable.ECR_OID = w_mode_reg.ECR_OID
					AND w_mode_reg.LNK_SOURCE = 'RGLMT'
				;
				
				UPDATE w_ecriture_comptable
				SET mode_reglement_code = w_mode_reg.mode_reglement_code
				FROM
				w_mode_reg
				WHERE w_ecriture_comptable.ECR_OID = w_mode_reg.ECR_OID
					AND w_mode_reg.LNK_SOURCE = 'ENC'
				;
				
				DROP TABLE IF EXISTS w_ecr_par_piece;
				CREATE TEMP TABLE w_ecr_par_piece AS
				SELECT piece, MAX(mode_reglement_code) AS mode_reglement_code
					FROM w_ecriture_comptable
					WHERE mode_reglement_code <> ''
					GROUP BY 1
					HAVING count(DISTINCT mode_reglement_code) = 1
				;
										
				CREATE INDEX w_ecr_par_piece_i1
					ON w_ecr_par_piece
					USING btree
					(PIECE);
				
				UPDATE w_ecriture_comptable
				SET mode_reglement_code = w_ecr_par_piece.mode_reglement_code
				FROM
					w_ecr_par_piece 
					, activite[PX].t_compte
				WHERE w_ecriture_comptable.compte_id = t_compte.oid AND
					(t_compte.code LIKE '4%' OR t_compte.code LIKE '5%') AND
					t_compte.code NOT LIKE '41%' AND
					t_compte.code NOT LIKE '445%' AND
					w_ecriture_comptable.piece = w_ecr_par_piece.piece AND
					w_ecriture_comptable.mode_reglement_code = ''
				;
				

				TRUNCATE activite[PX].p_ecriture_comptable;
				INSERT INTO activite[PX].p_ecriture_comptable(
					code_original, 
					date_comptable, 
					type_ecriture, 
					type_piece, 
					piece, 
					clinique_honoraire, 
					compte_id, 
					journal_id, 
					sejour_id, 
					no_sejour, 
					facture_id, 
					no_facture, 
					medecin_id, 
					tiers_payant_id, 
					texte, 
					montant_credit, 
					montant_debit,
					est_comptabilise,
					mode_reglement_code,
					taux_tva)
				SELECT 
					code_original, 
					date_comptable, 
					type_ecriture, 
					type_piece, 
					piece, 
					clinique_honoraire, 
					compte_id, 
					journal_id, 
					sejour_id, 
					no_sejour, 
					facture_id, 
					no_facture, 
					medecin_id, 
					tiers_payant_id, 
					texte, 
					montant_credit, 
					montant_debit,
					CASE WHEN ECR_LOCKED = 1 THEN '1' ELSE 0 END AS est_comptabilise,
					mode_reglement_code,
					taux_tva
				FROM w_ecriture_comptable
				;
				
				

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



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

		<NODE label="Récupération chiffrier">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_NMCL_ETS_EF;
				CREATE TEMP TABLE w_NMCL_ETS_EF AS
				SELECT 
					ETS_EF_OID
				FROM w_NMCL_ETABLISSEMENT
				GROUP 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 
					date(ECR_DATE) AS date_comptable,
					SUM(CASE WHEN LNK_JOURNAL = 'VE' AND ECR_IS_ETS = 1 THEN ECR_DEBIT - ECR_CREDIT ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN LNK_JOURNAL <> 'VE' AND ECR_IS_ETS = 1 THEN ECR_CREDIT - ECR_DEBIT ELSE 0 END) AS montant_reglements_c,
					0::numeric AS montant_solde_client_c,
					SUM(CASE 
						WHEN LNK_JOURNAL = 'VE' AND ECR_IS_ETS = 0 THEN ECR_DEBIT - ECR_CREDIT 
						ELSE 0 END
					) AS montant_ventes_h,
					SUM(CASE 
						WHEN LNK_JOURNAL <> 'VE' AND LNK_JOURNAL <> 'HONO' AND ECR_IS_ETS = 0 THEN ECR_CREDIT - ECR_DEBIT 
						WHEN LNK_JOURNAL = 'HONO' AND ECR_IS_ETS = 0 THEN ECR_CREDIT - ECR_DEBIT 
						ELSE 0 END
					) AS montant_reglements_h,
					0::numeric AS montant_solde_client_h
				FROM w_CPT_ECRITURE_source_OP_LINK
				JOIN prod_web100t.CPT_COMPTES ON ECR_COMPTE = CPT_OID AND CPT_CODE LIKE '41%'
				JOIN prod_web100t.FAC_FACTURE ON FACT_OID = ECR_REF_OID
				JOIN activite[PX].p_sejours ON code_original = FACT_DA
				WHERE LNK_ERROR = '' AND
					date(ECR_DATE) >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					ECR_TYPE IN ('CLIENT','VENTE-DIRECTE','VENTE-DEP') AND ECR_REF_TYPE = 'FACTURE'
				GROUP BY 1;
					
			

				TRUNCATE activite[PX].p_factures_comptables;

				INSERT INTO activite[PX].p_factures_comptables(
					no_facture,
					date_comptable,
					montant_ventes_c, 
					montant_reglements_c, 
					montant_ventes_h, 
					montant_reglements_h
				)
				SELECT 
					COALESCE(FACT_NUMERO, 'ID_' || LNK_SOURCE_OID),
					date(ECR_DATE) AS date_comptable,
					SUM(CASE WHEN LNK_JOURNAL = 'VE' AND ECR_IS_ETS = 1 THEN ECR_DEBIT - ECR_CREDIT ELSE 0 END) AS montant_ventes_c,
					SUM(CASE WHEN LNK_JOURNAL <> 'VE' AND ECR_IS_ETS = 1 THEN ECR_CREDIT - ECR_DEBIT ELSE 0 END) AS montant_reglements_c,
					SUM(CASE 
						WHEN LNK_JOURNAL = 'VE' AND ECR_IS_ETS = 0 THEN ECR_DEBIT - ECR_CREDIT 
						ELSE 0 END
					) AS montant_ventes_h,
					SUM(CASE 
						WHEN LNK_JOURNAL <> 'VE' AND LNK_JOURNAL <> 'HONO' AND ECR_IS_ETS = 0 THEN ECR_CREDIT - ECR_DEBIT 
						WHEN LNK_JOURNAL = 'HONO' AND ECR_IS_ETS = 0 THEN ECR_CREDIT - ECR_DEBIT 
						ELSE 0 END
					) AS montant_reglements_h
				FROM w_CPT_ECRITURE_source_OP_LINK
					JOIN prod_web100t.CPT_COMPTES ON ECR_COMPTE = CPT_OID AND CPT_CODE LIKE '41%'
					JOIN prod_web100t.FAC_FACTURE ON FACT_OID = ECR_REF_OID
					JOIN activite[PX].p_sejours ON code_original = FACT_DA
				WHERE LNK_ERROR = '' AND
					date(ECR_DATE) >= '[ENV_ADM_ANNEEDEBUT]0101' AND
					ECR_TYPE IN ('CLIENT','VENTE-DIRECTE','VENTE-DEP') AND ECR_REF_TYPE = 'FACTURE'
				GROUP BY 1,2;
				
				
				-- Attention, les ventes directes ne sont peut être pas encore générées
				
				-- Date dernière génération ventes directes
                -- Attention : Il faut que la dernière génération ne soit pas antérieure à 1 mois
				DROP TABLE IF EXISTS w_last_direct;
				CREATE TEMP TABLE w_last_direct AS
				SELECT 
					date(max(ECR_DATE)) AS LAST_ECR_DATE
				FROM w_CPT_ECRITURE_source_OP_LINK
					JOIN prod_web100t.CPT_COMPTES ON ECR_COMPTE = CPT_OID AND CPT_CODE LIKE '41%'
					JOIN prod_web100t.FAC_FACTURE ON FACT_OID = ECR_REF_OID
					JOIN activite[PX].p_sejours ON code_original = FACT_DA
				WHERE LNK_ERROR = '' AND
					ECR_TYPE IN ('VENTE-DIRECTE') AND ECR_REF_TYPE = 'FACTURE' and ECR_IS_ETS = 0
                HAVING date(max(ECR_DATE)) >= date(now() - interval '1 month');

				-- Factures comptabilisées après cette date
				DROP TABLE IF EXISTS w_factures_direct;
				CREATE TEMP TABLE w_factures_direct AS
				SELECT 
					FACT_OID,
					date(MAX(ECR_DATE)) AS ECR_DATE
				FROM w_CPT_ECRITURE_source_OP_LINK
					JOIN prod_web100t.CPT_COMPTES ON ECR_COMPTE = CPT_OID AND CPT_CODE LIKE '41%'
					JOIN prod_web100t.FAC_FACTURE ON FACT_OID = ECR_REF_OID
					JOIN w_last_direct ON ECR_DATE > LAST_ECR_DATE
					JOIN activite[PX].p_sejours ON code_original = FACT_DA
				WHERE LNK_ERROR = '' AND
					ECR_TYPE IN ('CLIENT','VENTE-DEP') AND ECR_REF_TYPE = 'FACTURE' AND 
					LNK_JOURNAL = 'VE' AND
					ECR_IS_ETS = 0
				GROUP BY 1;


				-- Mise à jour chiffrier
				DROP TABLE IF EXISTS w_factures_comptables;
				CREATE TEMP TABLE w_factures_comptables AS
				SELECT FACT_NUMERO AS no_facture, 
					date(ECR_DATE) AS date_comptable,
					SUM(0-FLT_TOTAL_TTC) AS montant_ventes_h
				FROM prod_web100t.fac_fact_ligne_tier
					JOIN prod_web100t.fac_facture on fac_facture.FACT_OID = FLT_FACTURE
					JOIN w_factures_direct ON w_factures_direct.FACT_OID = FLT_FACTURE
				WHERE FLT_IS_ETS = 0 AND FLT_IS_DIRECT = 1 
				GROUP BY 1,2
				ORDER BY 1,2;

				
				UPDATE activite[PX].p_factures_comptables
				SET montant_ventes_h = p_factures_comptables.montant_ventes_h + w_factures_comptables.montant_ventes_h
				FROM w_factures_comptables
				WHERE p_factures_comptables.no_facture = w_factures_comptables.no_facture AND
					p_factures_comptables.date_comptable = w_factures_comptables.date_comptable;


				DROP TABLE IF EXISTS w_chiffrier_comptable;
				CREATE TEMP TABLE w_chiffrier_comptable AS
				SELECT date(ECR_DATE) AS date_comptable,
					SUM(0-FLT_TOTAL_TTC) AS montant_ventes_h
				FROM prod_web100t.fac_fact_ligne_tier
					JOIN prod_web100t.fac_facture on fac_facture.FACT_OID = FLT_FACTURE
					JOIN w_factures_direct ON w_factures_direct.FACT_OID = FLT_FACTURE
				WHERE FLT_IS_ETS = 0 AND FLT_IS_DIRECT = 1 
				GROUP BY 1
				ORDER BY 1;

				
				UPDATE activite[PX].p_chiffrier_comptable
				SET montant_ventes_h = p_chiffrier_comptable.montant_ventes_h + w_chiffrier_comptable.montant_ventes_h
				FROM w_chiffrier_comptable
				WHERE p_chiffrier_comptable.date_comptable = w_chiffrier_comptable.date_comptable;
										
			]]></sqlcmd>
		</NODE>

	</NODE>

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

		<NODE label="Initialisation">
			<sqlcmd><![CDATA[
			
				DROP TABLE IF EXISTS w_SGN_NMCL_DATA;
				CREATE TEMP TABLE W_SGN_NMCL_DATA AS
				SELECT 
					NMCL_IDENT,
					ND_INVARIANT_OID,	
					CASE WHEN NMCL_IDENT IN ('GHS','GHM') THEN ND_OID ELSE NULL END AS ND_OID,
					(MAX(Array[ND_VALIDE_DE::text,ND_CODE]))[2] AS ND_CODE,
					(MAX(Array[ND_VALIDE_DE::text,ND_LIB]))[2] AS ND_LIB
				FROM prod_web100t.SGN_NMCL_DATA
					JOIN prod_web100t.SGN_NMCLS ON ND_NMCL_OID = NMCL_OID
				WHERE NMCL_IDENT IN
					(
						'REGIMEAMO',
						'REGIMEAMC',
						'AMO',
						'AMC',
						'MODETRAITEMENT',
						'DMT',
						'UNITEFONCTIONNELLE',
						'UNITEMEDICALE',
						'ETABLISSEMENT',
						'FINESS',
						'INTERVENANT',
						'MODEENTREE',
						'MODESORTIE',
						'SPECIALITEAMO',
						'GHS',
						'GHM',
						'ENTITEFACTURATION',
						'INNOVATIONS'
					)
				GROUP BY 1,2,3;


				CREATE INDEX w_SGN_NMCL_DATA_i1
					ON w_SGN_NMCL_DATA
					USING btree
					(ND_INVARIANT_OID);

				CREATE INDEX w_SGN_NMCL_DATA_i2
					ON w_SGN_NMCL_DATA
					USING btree
					(ND_OID);
					
				DROP TABLE IF EXISTS w_NMCL_ETABLISSEMENT;
				CREATE TEMP TABLE w_NMCL_ETABLISSEMENT AS
				SELECT 
					NMCL_ETABLISSEMENT.OID AS ETS_OID,
					FLD_ENTITEFACTURATION AS ETS_EF_OID,
					ND_CODE AS FINESS
				FROM
					prod_web100t.NMCL_ETABLISSEMENT
					JOIN w_SGN_NMCL_DATA ON ND_INVARIANT_OID = FLD_FINESSGEO AND NMCL_IDENT = 'FINESS'
					JOIN base.t_finess ON code = ND_CODE
				;
				
				ANALYSE w_NMCL_ETABLISSEMENT
				;				
					
				--
				
				DROP TABLE IF EXISTS w_CPT_OP_LINK_source;
				CREATE TEMP TABLE w_CPT_OP_LINK_source AS
				SELECT *
				FROM prod_web100t.CPT_OP_LINK
				WHERE LNK_EF = ANY(SELECT ETS_EF_OID FROM w_NMCL_ETABLISSEMENT)
					AND LNK_UPDATED >= '[ENV_ADM_ANNEEDEBUT]0101'
				;

				ANALYSE w_CPT_OP_LINK_source
				;

				CREATE INDEX w_CPT_OP_LINK_source_ik_lnk_operation
					ON w_CPT_OP_LINK_source
					USING btree
					(lnk_operation);

				CREATE INDEX w_CPT_OP_LINK_source_ik_lnk_master_op
					ON w_CPT_OP_LINK_source
					USING btree
					(lnk_master_op);

				DROP TABLE IF EXISTS w_CPT_ECRITURE_source;
				CREATE TEMP TABLE w_CPT_ECRITURE_source AS
				SELECT *
				FROM prod_web100t.CPT_ECRITURE
				WHERE ECR_EF = ANY(SELECT ETS_EF_OID FROM w_NMCL_ETABLISSEMENT)
					AND ECR_DATE >= '[ENV_ADM_ANNEEDEBUT]0101'
				;

				ANALYSE w_CPT_ECRITURE_source
				;
				
				CREATE INDEX w_CPT_ECRITURE_source_ik_ecr_operation
					ON w_CPT_ECRITURE_source
					USING btree
					(ecr_operation);

				DROP TABLE IF EXISTS w_CPT_ECRITURE_source_OP_LINK;
				CREATE TEMP TABLE w_CPT_ECRITURE_source_OP_LINK AS
				SELECT *,
					0::bigint AS ECR_REF_FACT
				FROM w_CPT_ECRITURE_source
				JOIN w_CPT_OP_LINK_source ON ECR_OPERATION = LNK_OPERATION
				;
				
				ANALYSE w_CPT_ECRITURE_source_OP_LINK
				;
				
				CREATE INDEX w_CPT_ECRITURE_source_OP_LINK_ik_ecr_operation
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(ecr_operation)
				;


				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_OID = LNK_SOURCE_OID
				WHERE ECR_OPERATION = LNK_OPERATION AND
					LNK_TYPE IN ('FACT') AND
					ECR_REF_TYPE = 'FACTURE' AND
					ECR_REF_OID <> LNK_SOURCE_OID
				;
				
				DROP TABLE IF EXISTS w_CPT_ECRITURE_work;
				CREATE TEMP TABLE w_CPT_ECRITURE_work AS
				SELECT ECR_OPERATION, MAX(ECR_REF_DA) AS ECR_REF_DA
				FROM w_CPT_ECRITURE_source_OP_LINK
				WHERE ECR_REF_DA > 0
				GROUP BY 1
				HAVING count(DISTINCT ECR_REF_DA) = 1
				;

				ANALYSE w_CPT_ECRITURE_work
				;
				
				CREATE INDEX w_CPT_ECRITURE_work_ik_ecr_operation
					ON w_CPT_ECRITURE_work
					USING btree
					(ECR_OPERATION)
				;
				
				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_DA = w_CPT_ECRITURE_work.ECR_REF_DA
				FROM w_CPT_ECRITURE_work
				WHERE w_CPT_ECRITURE_source_OP_LINK.ECR_OPERATION = w_CPT_ECRITURE_work.ECR_OPERATION AND
					w_CPT_ECRITURE_source_OP_LINK.ECR_REF_DA = 0
				;
				
				

				DROP TABLE IF EXISTS w_CPT_ECRITURE_work;
				CREATE TEMP TABLE w_CPT_ECRITURE_work AS
				SELECT ECR_MASTER, MAX(ECR_REF_DA) AS ECR_REF_DA
				FROM w_CPT_ECRITURE_source_OP_LINK
				WHERE ECR_REF_DA > 0
				GROUP BY 1
				HAVING count(DISTINCT ECR_REF_DA) = 1
				;

				ANALYSE w_CPT_ECRITURE_work
				;
				
				CREATE INDEX w_CPT_ECRITURE_work_ik_ecr_master
					ON w_CPT_ECRITURE_work
					USING btree
					(ECR_MASTER)
				;
				
				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_DA = w_CPT_ECRITURE_work.ECR_REF_DA
				FROM w_CPT_ECRITURE_work
				WHERE w_CPT_ECRITURE_source_OP_LINK.ECR_MASTER = w_CPT_ECRITURE_work.ECR_MASTER AND
					w_CPT_ECRITURE_source_OP_LINK.ECR_REF_DA = 0
				;

				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_FACT = LNK_SOURCE_OID
				WHERE LNK_SOURCE = 'FACTURE' AND
					ECR_REF_OID <> LNK_SOURCE_OID
				;

				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_FACT = ECR_REF_OID
				WHERE ECR_REF_TYPE = 'FACTURE' AND
					ECR_REF_FACT = 0
				;

				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_FACT = FACT_OID
				FROM prod_web100t.FAC_FACTURE
				WHERE ECR_DETAILS LIKE 'Facture n?%' AND
					substr(ECR_DETAILS,11,9) = lpad(FACT_NUMERO,9,'0') AND
					ECR_REF_FACT = 0
				;

				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_FACT = FACT_OID
				FROM prod_web100t.FAC_FACTURE
				WHERE ECR_REF_KEY LIKE 'F%' AND
					substr(ECR_REF_KEY,2) = FACT_OID::text AND
					ECR_REF_DA = FACT_DA AND
					ECR_REF_FACT = 0
				;
				
				
				DROP TABLE IF EXISTS w_CPT_ECRITURE_work;
				CREATE TEMP TABLE w_CPT_ECRITURE_work AS
				SELECT ECR_OPERATION, ECR_REF_DA, MAX(ECR_REF_FACT) AS ECR_REF_FACT
				FROM w_CPT_ECRITURE_source_OP_LINK
				WHERE ECR_REF_FACT > 0
				GROUP BY 1,2
				HAVING count(DISTINCT ECR_REF_FACT) = 1
				;
				
				ANALYSE w_CPT_ECRITURE_work
				;
				
				CREATE INDEX w_CPT_ECRITURE_work_ik_ecr_operation
					ON w_CPT_ECRITURE_work
					USING btree
					(ECR_OPERATION)
				;
				
				ANALYSE w_CPT_ECRITURE_source_OP_LINK
				;
				
				
				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_REF_FACT = w_CPT_ECRITURE_work.ECR_REF_FACT
				FROM w_CPT_ECRITURE_work
				WHERE w_CPT_ECRITURE_source_OP_LINK.ECR_OPERATION = w_CPT_ECRITURE_work.ECR_OPERATION AND
					w_CPT_ECRITURE_source_OP_LINK.ECR_REF_DA = w_CPT_ECRITURE_work.ECR_REF_DA AND
					w_CPT_ECRITURE_source_OP_LINK.ECR_REF_FACT = 0
				;
				
				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_TYPE = 'VENTE-DEP'
				WHERE ECR_TYPE = 'VENTE_DEP'
				;

				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_TYPE = 'VENTE-HON'
				WHERE ECR_TYPE = 'VENTE_HON'
				;
				
				UPDATE w_CPT_ECRITURE_source_OP_LINK
				SET ECR_TYPE = 'VENTE-DIRECTE'
				WHERE ECR_TYPE = 'VENTE_DIRECTE'
				;

				ANALYSE w_CPT_ECRITURE_source_OP_LINK
				;

				CREATE INDEX w_cpt_ecriture_op_link_ik_ecr_compte
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(ecr_compte);


			    CREATE INDEX w_cpt_ecriture_op_link_ik_ecr_ref_oid
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(ecr_ref_oid);

				CREATE INDEX w_cpt_ecriture_op_link_ik_ecr_data
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(ecr_data);
					
				CREATE INDEX w_cpt_ecriture_op_link_ik_ECR_REF_DA
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(ECR_REF_DA);
               
				CREATE INDEX w_cpt_ecriture_op_link_ik_ECR_REF_FACT
                    ON w_CPT_ECRITURE_source_OP_LINK
                    USING btree
                    (ECR_REF_FACT);
                					
				CREATE INDEX w_cpt_ecriture_op_link_ik_LNK_JOURNAL
					ON w_CPT_ECRITURE_source_OP_LINK
					USING btree
					(LNK_JOURNAL);
					
					
				
				
				-- Correction tiers dans les comptes car dans certains cas, ils ne correspondent pas aux factures
				UPDATE prod_web100t.CPT_COMPTES
				SET CPT_REF = subview.FT_ORGANISME
				FROM
				(
				SELECT ECR_COMPTE, CPT_CODE, CPT_COMPTES.CPT_REF, MAX(FT_ORGANISME) AS FT_ORGANISME
				FROM w_CPT_ECRITURE_source_OP_LINK
				JOIN prod_web100t.CPT_COMPTES ON ECR_COMPTE = CPT_OID
				JOIN prod_web100t.FAC_FACT_TIER ON ECR_REF_FTIERS = FT_OID
				WHERE CPT_COMPTES.CPT_REF_TYPE = 'AMC' 
				GROUP BY 1,2,3
				HAVING MAX(CASE WHEN CPT_COMPTES.CPT_REF <> FT_ORGANISME THEN '1' ELSE '0' END) = '1' AND
					count(DISTINCT FT_ORGANISME) = 1
				ORDER BY 1,2,3
				) subview
				WHERE CPT_COMPTES.CPT_OID = ECR_COMPTE
				;
				
				
				-- 
				
				
				DROP TABLE IF EXISTS w_REGUL_MOUVEMENTS_source;
				CREATE TEMP TABLE w_REGUL_MOUVEMENTS_source AS
				SELECT *
				FROM prod_web100t.REGUL_MOUVEMENTS
				WHERE MVT_SEJ_OID = ANY(SELECT PHASE_OID FROM prod_web100t.DAT_SEJOUR WHERE SEJ_DA = ANY(SELECT DA_OID FROM prod_web100t.DAT_DA WHERE DA_EG_ENTREE = ANY(SELECT ets_oid FROM w_NMCL_ETABLISSEMENT)))
				;
				
				ANALYSE w_REGUL_MOUVEMENTS_source
				;
				
				
				CREATE INDEX w_REGUL_MOUVEMENTS_source_ik_MVT_SEJ_OID
				  ON w_REGUL_MOUVEMENTS_source
				  USING btree
				  (MVT_SEJ_OID);

  
  
  
				--				
				INSERT INTO activite.t_divers (code, texte, valeur, description)
				SELECT
					'WEB100T_ETAGE',
					'Traitement étage WEB100T ',
					'0',
					'1 = Prendre UF GEO dans mouvements (pas dans chambres)'
				WHERE 'WEB100T_ETAGE' NOT IN (SELECT code FROM activite.t_divers);
			
				-- UF chambre selon mouvements
				UPDATE prod_web100t.CHAMBRES
				SET CHA_UF = MVT_UF_GEO
				FROM (
				SELECT MVT_CHAMBRE, (MAX(ARRAY[MVT_DATE::text,MVT_UF_GEO::text]))[2]::bigint AS MVT_UF_GEO
				FROM w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
				JOIN activite.t_divers ON t_divers.code = 'WEB100T_ETAGE' AND t_divers.valeur ='1'
				WHERE MVT_TYPE IN (1,4) AND
					MVT_CHAMBRE <> 0
				GROUP BY 1
				) subview
				WHERE CHA_OID = MVT_CHAMBRE
				;
				
				
				
										
			]]></sqlcmd>
		</NODE>

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

				INSERT INTO activite[PX].t_types_tiers_payant(code, texte, texte_court)
				SELECT code, texte, texte FROM
				(
				SELECT '0' AS code, 'Patients' AS texte
				UNION ALL
				SELECT '1','Régime général'
				UNION ALL
				SELECT '2','Mutuelles'
				) subview
				WHERE code NOT IN (SELECT code FROM activite[PX].t_types_tiers_payant);
				
				
				INSERT INTO base.t_grands_regimes(code, code_original, texte, texte_court)
				SELECT ND_CODE, ND_CODE, ND_LIB, ND_LIB
				FROM w_SGN_NMCL_DATA
				LEFT JOIN base.t_grands_regimes ON ND_CODE = code
				WHERE NMCL_IDENT = 'REGIMEAMO' AND t_grands_regimes.code IS NULL
				GROUP BY 1,2,3,4;
				
				

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

				INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court) 
				SELECT 'PATIENTS', '0', '0', 'Patients', 'Patients'
				WHERE '0' NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);
                
                INSERT INTO activite[PX].t_tiers_payant(code, code_original, type_tiers_payant, texte, texte_court) 
				SELECT 'ETS', '*CTIETS', '2', 'Etablissement', 'Etablissement'
				WHERE '*CTIETS' 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 NMCL_AMO.OID::bigint, w_SGN_NMCL_DATA.ND_CODE, '1', w_SGN_NMCL_DATA.ND_LIB, w_SGN_NMCL_DATA.ND_LIB 
				FROM prod_web100t.NMCL_AMO
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID 
				WHERE NMCL_IDENT = 'AMO' AND NMCL_AMO.OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);
				
				
				UPDATE activite[PX].t_tiers_payant
				SET grand_regime_id = t_grands_regimes.oid 
				FROM prod_web100t.NMCL_AMO
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = FLD_REGIMEAMO
					JOIN base.t_grands_regimes ON w_SGN_NMCL_DATA.ND_CODE = code
				WHERE t_tiers_payant.code_original = NMCL_AMO.OID::bigint AND
					grand_regime_id IS DISTINCT FROM t_grands_regimes.oid AND
					w_SGN_NMCL_DATA.ND_CODE <> '00';
					
					
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT NMCL_AMC.OID::bigint, w_SGN_NMCL_DATA.ND_CODE, '2', w_SGN_NMCL_DATA.ND_LIB, w_SGN_NMCL_DATA.ND_LIB 
				FROM prod_web100t.NMCL_AMC
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID
				WHERE NMCL_IDENT = 'AMC' AND NMCL_AMC.OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant);
				
				-- Dans certains cas, les tiers ne sont pas dans NMCL_DATA
				INSERT INTO activite[PX].t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
				SELECT NMCL_AMC.OID::bigint, MAX(CPT_AUXILIAIRE), '2', MAX(CPT_LIB), MAX(CPT_LIB)
				FROM prod_web100t.NMCL_AMC
					JOIN prod_web100t.CPT_COMPTES ON CPT_REF_TYPE = 'AMC' AND CPT_REF = NMCL_AMC.OID
				WHERE NMCL_AMC.OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_tiers_payant)
				GROUP BY 1;
				
				UPDATE activite[PX].t_tiers_payant SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM prod_web100t.NMCL_AMO
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID 
				WHERE NMCL_AMO.OID::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;

                UPDATE activite[PX].t_tiers_payant SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM prod_web100t.NMCL_AMC
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID
				WHERE NMCL_AMC.OID::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;

				-- Adresses des tiers payant
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT FLD_CODEPOSTAL, MAX(FLD_COMMUNE), MAX(FLD_COMMUNE), MAX(t_departements.oid)
				FROM prod_web100t.NMCL_AMO
				LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				JOIN base.t_departements ON 
					FLD_CODEPOSTAL NOT LIKE '97%' AND substr(FLD_CODEPOSTAL,1,2) = t_departements.code OR
					FLD_CODEPOSTAL LIKE '97%' AND substr(FLD_CODEPOSTAL,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL AND	
					FLD_CODEPOSTAL <> '' AND
					length(FLD_CODEPOSTAL) = 5
				GROUP BY 1
				;
			
				UPDATE activite[PX].t_tiers_payant SET
					adresse = FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = FLD_COMMUNE,
					telephone = FLD_TELEPHONE,
					fax = FLD_FAX,
					email = FLD_EMAIL
				FROM prod_web100t.NMCL_AMO
					LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				WHERE t_tiers_payant.code_original = NMCL_AMO.OID::bigint AND
					(
					adresse IS DISTINCT FROM (FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM FLD_COMMUNE OR
					telephone IS DISTINCT FROM FLD_TELEPHONE OR
					fax IS DISTINCT FROM FLD_FAX OR
					email IS DISTINCT FROM FLD_EMAIL
					)
				;
				
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT FLD_CODEPOSTAL, MAX(FLD_COMMUNE), MAX(FLD_COMMUNE), MAX(t_departements.oid)
				FROM prod_web100t.NMCL_AMC
				LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				JOIN base.t_departements ON 
					FLD_CODEPOSTAL NOT LIKE '97%' AND substr(FLD_CODEPOSTAL,1,2) = t_departements.code OR
					FLD_CODEPOSTAL LIKE '97%' AND substr(FLD_CODEPOSTAL,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL AND	
					FLD_CODEPOSTAL <> '' AND
					length(FLD_CODEPOSTAL) = 5
				GROUP BY 1
				;

				UPDATE activite[PX].t_tiers_payant SET
					adresse = FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = FLD_COMMUNE,
					telephone = FLD_TELEPHONE,
					fax = FLD_FAX,
					email = FLD_EMAIL
				FROM prod_web100t.NMCL_AMC
					LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				WHERE t_tiers_payant.code_original = NMCL_AMC.OID::bigint AND
					(
					adresse IS DISTINCT FROM (FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM FLD_COMMUNE OR
					telephone IS DISTINCT FROM FLD_TELEPHONE OR
					fax IS DISTINCT FROM FLD_FAX OR
					email IS DISTINCT FROM FLD_EMAIL
					)
				;


								
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Médecins">
			<sqlcmd><![CDATA[
			
				INSERT INTO base.t_specialites_medecin(oid, code, code_original, texte, texte_court) 
				SELECT 0, '', '0', 'Non saisie', 'Non saisie'
				WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin);

				INSERT INTO base.t_specialites_medecin(code_original, code, texte, texte_court)
				SELECT SUBSTR(ND_CODE,1,10), SUBSTR(ND_CODE,1,10), MAX(ND_LIB), MAX(ND_LIB)
				FROM w_SGN_NMCL_DATA
					LEFT JOIN base.t_specialites_medecin ON t_specialites_medecin.code = SUBSTR(ND_CODE,1,10)
				WHERE NMCL_IDENT = 'SPECIALITEAMO' AND 
					base.t_specialites_medecin.code IS NULL
				GROUP BY 1
				ORDER BY 2
                ;

				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 NMCL_INTERVENANT.OID::bigint AS NMCL_INTERVENANT_OID,
					w_SGN_NMCL_DATA.ND_CODE, 
					base.cti_soundex_nom(CASE WHEN FLD_NOM <> '' THEN FLD_NOM ELSE TRIM(REPLACE(w_SGN_NMCL_DATA.ND_LIB, FLD_PRENOM, '')) END) AS FLD_NOM_SOUNDEX,
					base.cti_soundex_nom(FLD_PRENOM) AS FLD_PRENOM_SOUNDEX,
					CASE WHEN FLD_NOM <> '' THEN FLD_NOM ELSE TRIM(REPLACE(w_SGN_NMCL_DATA.ND_LIB, FLD_PRENOM, '')) END AS FLD_NOM,
					FLD_PRENOM,
					FLD_CODEADELI,
					FLD_SPECIALITE,
					COALESCE(SUBSTR(w_SGN_NMCL_DATA_spe.ND_CODE,1,10),'') AS FLD_SPECIALITE_CODE,
					COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id,
					FLD_CODERPPS
				FROM prod_web100t.NMCL_INTERVENANT
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID AND w_SGN_NMCL_DATA.NMCL_IDENT = 'INTERVENANT'
					LEFT JOIN w_SGN_NMCL_DATA w_SGN_NMCL_DATA_spe ON FLD_SPECIALITE = w_SGN_NMCL_DATA_spe.ND_INVARIANT_OID
					LEFT JOIN activite[PX].t_medecins_administratifs ON NMCL_INTERVENANT.OID::bigint = t_medecins_administratifs.code_original;
					
				INSERT INTO w_medecins (
					NMCL_INTERVENANT_OID
					,ND_CODE
					,FLD_NOM_SOUNDEX
					,FLD_PRENOM_SOUNDEX
					,FLD_NOM
					,FLD_PRENOM
					,FLD_CODEADELI
					,FLD_SPECIALITE
					,FLD_SPECIALITE_CODE
					,medecin_id
					,FLD_CODERPPS
					)
				SELECT w_SGN_NMCL_DATA.ND_INVARIANT_OID::bigint
					,w_SGN_NMCL_DATA.ND_CODE
					,base.cti_soundex_nom(w_SGN_NMCL_DATA.ND_LIB)
					,base.cti_soundex_nom('') AS FLD_PRENOM_SOUNDEX
					,w_SGN_NMCL_DATA.ND_LIB AS FLD_NOM
					,''::text AS FLD_PRENOM
					,''::text AS FLD_CODEADELI
					,0 AS FLD_SPECIALITE
					,''
					,COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
					,NULL
				FROM w_SGN_NMCL_DATA 
					LEFT JOIN activite[PX].t_medecins_administratifs ON w_SGN_NMCL_DATA.ND_INVARIANT_OID::bigint = t_medecins_administratifs.code_original
				WHERE NMCL_IDENT IN ('ENTITEFACTURATION','ETABLISSEMENT')
				;

				INSERT INTO base.t_medecins(nom, prenom, numero_ordre, code_rpps, specialite_id)
				SELECT w_medecins.FLD_NOM, w_medecins.FLD_PRENOM, w_medecins.FLD_CODEADELI, w_medecins.FLD_CODERPPS, 0 FROM
				(SELECT SUBSTR(FLD_NOM_SOUNDEX, 1, 8) AS FLD_NOM_SOUNDEX, SUBSTR(FLD_PRENOM_SOUNDEX, 1, 8) AS FLD_PRENOM_SOUNDEX, FLD_CODEADELI, FLD_CODERPPS, MIN(NMCL_INTERVENANT_OID) AS NMCL_INTERVENANT_OID
				FROM w_medecins
				GROUP BY 1,2,3,4) subview, w_medecins
				WHERE w_medecins.NMCL_INTERVENANT_OID = subview.NMCL_INTERVENANT_OID
					AND subview.FLD_NOM_SOUNDEX || ',' || subview.FLD_PRENOM_SOUNDEX || ',' ||  subview.FLD_CODEADELI 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, code_rpps, specialite_id)
				SELECT w_medecins.FLD_NOM, w_medecins.FLD_PRENOM, w_medecins.FLD_CODEADELI, w_medecins.FLD_CODERPPS, 0 FROM
				(SELECT FLD_NOM_SOUNDEX, FLD_PRENOM_SOUNDEX, MIN(NMCL_INTERVENANT_OID) AS NMCL_INTERVENANT_OID
				FROM w_medecins
				GROUP BY 1,2) subview, w_medecins
				WHERE w_medecins.NMCL_INTERVENANT_OID = subview.NMCL_INTERVENANT_OID
					AND subview.FLD_NOM_SOUNDEX || ',' || subview.FLD_PRENOM_SOUNDEX NOT IN 
					(SELECT base.cti_soundex_nom(nom)  || ',' || base.cti_soundex_nom(prenom) FROM base.t_medecins);


				UPDATE w_medecins SET medecin_id = subview.medecin_id
				FROM 
				(SELECT substr(base.cti_soundex_nom(nom),1,8) as nom , substr(base.cti_soundex_nom(prenom),1,8) as prenom, numero_ordre, MIN(oid) AS medecin_id FROM base.t_medecins GROUP BY 1,2,3) subview
				WHERE SUBSTR(FLD_NOM_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(FLD_PRENOM_SOUNDEX, 1, 8) = subview.prenom
				AND FLD_CODEADELI = 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(FLD_NOM_SOUNDEX, 1, 8) = subview.nom
				AND SUBSTR(FLD_PRENOM_SOUNDEX, 1, 8) = subview.prenom
				AND w_medecins.medecin_id = 0;

				INSERT INTO activite[PX].t_medecins_administratifs(code_original, code, nom, prenom, specialite_id,  medecin_id)
				SELECT DISTINCT NMCL_INTERVENANT_OID, ND_CODE, FLD_NOM, FLD_PRENOM, COALESCE(t_specialites_medecin.oid,0), medecin_id
				FROM w_medecins
					LEFT JOIN base.t_specialites_medecin ON (FLD_SPECIALITE::bigint = t_specialites_medecin.code_original)
				WHERE NMCL_INTERVENANT_OID NOT IN (SELECT code_original FROM activite[PX].t_medecins_administratifs);

				UPDATE activite[PX].t_medecins_administratifs SET
					code = ND_CODE,
					nom = FLD_NOM,
					prenom = FLD_PRENOM
				FROM w_medecins
				WHERE t_medecins_administratifs.code_original = NMCL_INTERVENANT_OID AND
					(
						code IS DISTINCT FROM ND_CODE OR
						nom IS DISTINCT FROM FLD_NOM OR
						prenom IS DISTINCT FROM FLD_PRENOM
					)
				;

				UPDATE activite[PX].t_medecins_administratifs
				SET code = ND_CODE,
					nom = FLD_NOM,
					prenom = FLD_PRENOM,
					specialite_id = COALESCE(t_specialites_medecin.oid,0),
					medecin_id = w_medecins.medecin_id,
					no_adeli = FLD_CODEADELI,
					code_rpps = FLD_CODERPPS
				FROM w_medecins LEFT JOIN base.t_specialites_medecin ON (FLD_SPECIALITE_CODE = t_specialites_medecin.code)
				WHERE w_medecins.NMCL_INTERVENANT_OID = t_medecins_administratifs.code_original
					AND (
					t_medecins_administratifs.code IS DISTINCT FROM ND_CODE OR
					t_medecins_administratifs.nom IS DISTINCT FROM FLD_NOM OR
					t_medecins_administratifs.prenom IS DISTINCT FROM FLD_PRENOM OR
					t_medecins_administratifs.specialite_id IS DISTINCT FROM COALESCE(t_specialites_medecin.oid,0) OR
					t_medecins_administratifs.medecin_id IS DISTINCT FROM w_medecins.medecin_id OR
					t_medecins_administratifs.no_adeli IS DISTINCT FROM w_medecins.FLD_CODEADELI OR
					t_medecins_administratifs.code_rpps IS DISTINCT FROM w_medecins.FLD_CODERPPS
				);

				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 AND
					t_medecins_administratifs.specialite_id <> 0
				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 FLD_CODERPPS), MAX(FLD_CODERPPS) AS RPPS
                FROM activite[PX].t_medecins_administratifs
                JOIN base.t_medecins ON t_medecins_administratifs.medecin_id = t_medecins.oid
                JOIN prod_web100t.NMCL_INTERVENANT ON code_original = NMCL_INTERVENANT.OID
                WHERE FLD_CODERPPS <> '' AND
                    length(FLD_CODERPPS) = 11 AND
                    t_medecins.code_rpps = '' AND 
                    medecin_id <> 0
                GROUP BY 1
                HAVING count(DISTINCT FLD_CODERPPS) = 1
                ) subview
                WHERE t_medecins.oid = subview.medecin_id
                ;
				
				-- adresse
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT FLD_CODEPOSTAL, MAX(FLD_COMMUNE), MAX(FLD_COMMUNE), MAX(t_departements.oid)
				FROM prod_web100t.NMCL_INTERVENANT
				LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				JOIN base.t_departements ON 
					FLD_CODEPOSTAL NOT LIKE '97%' AND substr(FLD_CODEPOSTAL,1,2) = t_departements.code OR
					FLD_CODEPOSTAL LIKE '97%' AND substr(FLD_CODEPOSTAL,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL AND	
					FLD_CODEPOSTAL <> '' AND
					length(FLD_CODEPOSTAL) = 5
				GROUP BY 1
				;

				UPDATE activite[PX].t_medecins_administratifs SET
					adresse = FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3,
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = FLD_COMMUNE,
					telephone = FLD_TELEPHONE,
					fax = FLD_FAX,
					email = FLD_EMAIL
				FROM prod_web100t.NMCL_INTERVENANT
					LEFT JOIN base.t_codes_postaux ON FLD_CODEPOSTAL = t_codes_postaux.code
				WHERE t_medecins_administratifs.code_original = NMCL_INTERVENANT.OID::bigint AND
					(
					adresse IS DISTINCT FROM (FLD_ADRESSE1 || ' ' ||  FLD_ADRESSE2 || ' ' || FLD_ADRESSE3) OR
					code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					ville IS DISTINCT FROM FLD_COMMUNE OR
					telephone IS DISTINCT FROM FLD_TELEPHONE OR
					fax IS DISTINCT FROM FLD_FAX OR
					email IS DISTINCT FROM FLD_EMAIL
					)
				;


				DROP TABLE IF EXISTS w_NMCL_INTERVENANT;
				CREATE TEMP TABLE w_NMCL_INTERVENANT AS
				SELECT NODE_OID, NMCL_INTERVENANT.OID, COALESCE(t_medecins_administratifs.oid,0) AS medecin_administratif_id
				FROM prod_web100t.SGN_TREE_NODES
				JOIN prod_web100t.NMCL_INTERVENANT ON NODE_INVARIANT_OID = NMCL_INTERVENANT.OID
				JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = OID AND NMCL_IDENT = 'INTERVENANT'
				JOIN activite[PX].t_medecins_administratifs ON NMCL_INTERVENANT.OID = code_original;
					
				INSERT INTO w_NMCL_INTERVENANT
				SELECT NODE_OID, NODE_INVARIANT_OID, COALESCE(t_medecins_administratifs.oid,0) AS medecin_administratif_id
				FROM prod_web100t.SGN_TREE_NODES
				JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = NODE_INVARIANT_OID AND NMCL_IDENT IN ('ENTITEFACTURATION','ETABLISSEMENT')
				JOIN activite[PX].t_medecins_administratifs ON NODE_INVARIANT_OID = code_original;



				CREATE INDEX w_NMCL_INTERVENANT_i1
					ON w_NMCL_INTERVENANT
					USING btree
					(NODE_OID);
				
										
			]]></sqlcmd>
		</NODE>

		<NODE label="Hébergement">
			<sqlcmd><![CDATA[
				
				
				-- Modes de traitement
				
				INSERT INTO base.t_modes_traitement(code, texte, texte_court)
				SELECT ND_CODE, ND_LIB, ND_LIB
				FROM w_SGN_NMCL_DATA
				WHERE NMCL_IDENT = 'MODETRAITEMENT' AND ND_CODE NOT IN (SELECT code FROM base.t_modes_traitement)
				ORDER BY ND_CODE;

				
				-- DMT
				
				INSERT INTO base.t_dmt(code, texte, texte_court)
				SELECT ND_CODE, ND_LIB, ND_LIB
				FROM w_SGN_NMCL_DATA
				WHERE NMCL_IDENT = 'DMT' AND ND_CODE NOT IN (SELECt code FROM base.t_dmt)
				ORDER BY ND_CODE;

				
				-- Services

				INSERT INTO activite[PX].t_services_facturation(code_original, code, texte, texte_court, type_t2a)
				SELECT OID::bigint, ND_CODE, ND_LIB, ND_LIB, '0'
				FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
					JOIN w_SGN_NMCL_DATA ON ND_INVARIANT_OID = OID
				WHERE 
					NMCL_IDENT = 'UNITEFONCTIONNELLE' AND OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_services_facturation)
				ORDER BY ND_CODE;
				
				UPDATE activite[PX].t_services_facturation
				SET 
					mode_traitement_id = subview.mode_traitement_id, 
					dmt_id = subview.dmt_id
				FROM (
					SELECT NMCL_UNITEFONCTIONNELLE.OID::bigint, COALESCE(t_modes_traitement.oid,0) as mode_traitement_id, COALESCE(t_dmt.oid,0) as dmt_id
					FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
						LEFT JOIN w_SGN_NMCL_DATA SGN_NMCL_DATA_MT ON FLD_MODETTT = SGN_NMCL_DATA_MT.ND_INVARIANT_OID AND FLD_MODETTT <> 0
						LEFT JOIN w_SGN_NMCL_DATA SGN_NMCL_DATA_DMT  ON FLD_DMT = SGN_NMCL_DATA_DMT.ND_INVARIANT_OID AND FLD_DMT <> 0
						LEFT JOIN base.t_modes_traitement ON SGN_NMCL_DATA_MT.ND_CODE = t_modes_traitement.code
						LEFT JOIN base.t_dmt ON SGN_NMCL_DATA_DMT.ND_CODE = t_dmt.code
					WHERE COALESCE(t_modes_traitement.oid,0) <> 0 OR COALESCE(t_dmt.oid,0) <> 0
					) subview
				WHERE code_original = subview.OID AND (t_services_facturation.mode_traitement_id = 0 OR t_services_facturation.dmt_id = 0);

				
				UPDATE activite[PX].t_services_facturation SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = NMCL_UNITEFONCTIONNELLE.OID
				WHERE NMCL_UNITEFONCTIONNELLE.OID::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;
				
				-- Unités fonctionnelles
				
				INSERT INTO activite[PX].t_unites_fonctionnelles(oid, code_original, code, texte, texte_court) 
				SELECT 0, 0, '', 'Non renseignée', 'Non renseignée' WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_unites_fonctionnelles);
				
				INSERT INTO activite[PX].t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT OID::bigint, ND_CODE, ND_LIB, ND_LIB
				FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
					JOIN w_SGN_NMCL_DATA ON ND_INVARIANT_OID = OID
				WHERE NMCL_IDENT = 'UNITEFONCTIONNELLE' AND 
					OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_unites_fonctionnelles)
				ORDER BY ND_CODE;

				UPDATE activite[PX].t_unites_fonctionnelles SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM prod_web100t.NMCL_UNITEFONCTIONNELLE
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = NMCL_UNITEFONCTIONNELLE.OID
				WHERE NMCL_UNITEFONCTIONNELLE.OID::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;
					
				-- 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 OID::bigint, ND_CODE, ND_LIB, ND_LIB
				FROM prod_web100t.NMCL_UNITEMEDICALE
					JOIN w_SGN_NMCL_DATA ON ND_INVARIANT_OID = OID
				WHERE NMCL_IDENT = 'UNITEMEDICALE' AND
					OID::bigint NOT IN (SELECT code_original FROM activite[PX].t_unites_medicales)
				ORDER BY ND_CODE;

				UPDATE activite[PX].t_unites_medicales SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM prod_web100t.NMCL_UNITEMEDICALE
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = NMCL_UNITEMEDICALE.OID
				WHERE NMCL_UNITEMEDICALE.OID::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;

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

				--Traitements des spécialités
				INSERT INTO w_SGN_NMCL_DATA (NMCL_IDENT, ND_CODE, ND_OID, ND_INVARIANT_OID, ND_LIB)
				SELECT DISTINCT ON (ND_LIB)
				    NMCL_IDENT
				    ,ND_CODE
				    ,null
				    ,ND_INVARIANT_OID
				    ,ND_LIB
				FROM prod_web100t.SGN_NMCL_DATA
				    JOIN prod_web100t.SGN_NMCLS ON ND_NMCL_OID = NMCL_OID
				WHERE NMCL_IDENT = 'SPECIALITE'
				ORDER BY ND_LIB, ND_VALIDE_DE, ND_INVARIANT_OID DESC
				;
				
				-- Modification du code_original des spécialités déjà présentes dans CTI
				UPDATE activite[PX].t_activites
				SET code_original = ND_INVARIANT_OID
				    FROM w_SGN_NMCL_DATA
				WHERE
				    NMCL_IDENT = 'SPECIALITE' 
				    AND activite[PX].t_activites.code = substr(ND_CODE,1,10) 
				    AND activite[PX].t_activites.code_original <> ND_INVARIANT_OID
				;
				
				-- Insertion des nouvelles spécialités
				INSERT INTO activite[PX].t_activites(code_original, code, texte, texte_court) 
				SELECT ND_INVARIANT_OID, substr(ND_CODE,1,10), ND_LIB, ND_LIB
				FROM w_SGN_NMCL_DATA
					LEFT JOIN activite[PX].t_activites ON t_activites.code_original = ND_INVARIANT_OID
				WHERE NMCL_IDENT = 'SPECIALITE' 
					AND t_activites.code_original IS NULL
					AND NOT EXISTS (SELECT 1 FROM activite[PX].t_activites WHERE t_activites.code = substr(w_SGN_NMCL_DATA.ND_CODE,1,10))
				ORDER BY ND_CODE;
				
				-- Correction car avant, le code_original pouvait être doublé.
				DELETE FROM activite[PX].t_activites
				USING(
					SELECT code_original, MIN(oid) AS keep_oid
					FROM activite[PX].t_activites
					GROUP BY 1
					HAVING count(*) > 1 
				) subview
				WHERE t_activites.code_original = subview.code_original AND
					t_activites.oid <> keep_oid
				;
				
				UPDATE activite[PX].t_activites SET
					code = substr(ND_CODE,1,10),
					texte = ND_LIB,
					texte_court = ND_LIB
				FROM w_SGN_NMCL_DATA
				WHERE ND_INVARIANT_OID = t_activites.code_original AND
					(
						t_activites.code IS DISTINCT FROM substr(w_SGN_NMCL_DATA.ND_CODE,1,10) OR
						t_activites.texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						t_activites.texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;
				
				-- Etages et lits

				INSERT INTO activite[PX].t_etages(oid, code_original, code, texte, texte_court, nb_lits) 
				SELECT 0, 0, '', 'Non renseigné', 'Non renseigné', 0 WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_etages);
				
				UPDATE prod_web100t.CHAMBRES
				SET CHA_UF = NODE_INVARIANT_OID
				FROM prod_web100t.SGN_TREE_NODES
				WHERE CHA_UF = 0 AND
					CHA_LIEU = NODE_OID;

				-- Avec lit
				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court)
				SELECT CHA_UF::bigint,ND_CODE, ND_LIB , ND_LIB 
				FROM prod_web100t.CHAMBRES
					JOIN w_SGN_NMCL_DATA ON CHA_UF = ND_INVARIANT_OID
				WHERE NMCL_IDENT = 'UNITEFONCTIONNELLE' AND
					CHA_UF::bigint NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY 1,2,3,4
				ORDER BY ND_CODE;
				
				-- Sans lit
				INSERT INTO activite[PX].t_etages(code_original, code, texte, texte_court)
				SELECT MVT_UF_GEO::bigint,ND_CODE, ND_LIB , ND_LIB 
				FROM w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
					JOIN w_SGN_NMCL_DATA ON MVT_UF_GEO = ND_INVARIANT_OID
				WHERE NMCL_IDENT = 'UNITEFONCTIONNELLE' AND
					MVT_LIT = 0 AND 
					MVT_UF_GEO::bigint NOT IN (SELECT code_original FROM activite[PX].t_etages)
				GROUP BY 1,2,3,4
				ORDER BY ND_CODE;

				UPDATE activite[PX].t_etages SET
					code = w_SGN_NMCL_DATA.ND_CODE,
					texte = w_SGN_NMCL_DATA.ND_LIB,
					texte_court = w_SGN_NMCL_DATA.ND_LIB
				FROM w_REGUL_MOUVEMENTS_source REGUL_MOUVEMENTS
					JOIN w_SGN_NMCL_DATA ON w_SGN_NMCL_DATA.ND_INVARIANT_OID = REGUL_MOUVEMENTS.MVT_UF_GEO
				WHERE REGUL_MOUVEMENTS.MVT_UF_GEO::bigint = code_original AND
					(
						code IS DISTINCT FROM w_SGN_NMCL_DATA.ND_CODE OR
						texte IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB OR
						texte_court IS DISTINCT FROM w_SGN_NMCL_DATA.ND_LIB
					)
				;

                -- Les codes lits peuvent changer
				UPDATE activite[PX].t_lits SET
						code = LIT_CODE,
						texte = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END,
						texte_court = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
					FROM prod_web100t.CHAMBRES
					JOIN prod_web100t.LITS ON CHA_OID = LIT_CHAMBRE
					JOIN activite[PX].t_etages ON CHA_UF::bigint = t_etages.code_original
					WHERE t_lits.code_original = (CHA_UF || '-' || LIT_OID) AND
						(t_lits.code <> LIT_CODE OR
						t_lits.texte <> CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END OR
						t_lits.texte_court <> CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
						)
                ;
				
				UPDATE activite[PX].t_lits	SET 
					code = LIT_CODE, 
					texte = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END, 
					texte_court = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END, 
					etage_id = t_etages.oid
				FROM 
                    prod_web100t.CHAMBRES
					JOIN prod_web100t.LITS ON CHA_OID = LIT_CHAMBRE
					JOIN activite[PX].t_etages ON CHA_UF::bigint = t_etages.code_original
				WHERE 1=1
                    AND CHA_UF::text || '-'::text || LIT_OID::text = t_lits.code_original
                    AND (1!=1
                        OR t_lits.code != LIT_CODE
                        OR t_lits.texte != CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
                        OR t_lits.texte_court != CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
                        OR t_lits.etage_id != t_etages.oid
                    );
					
				-- Mise à jour par rapport au code du lit et à l'étage si l'oid a changé
                UPDATE activite[PX].t_lits SET 
                    code_original = (CHA_UF::text || '-'::text || LIT_OID::text)
                FROM 
                    prod_web100t.CHAMBRES
                    JOIN prod_web100t.LITS ON CHA_OID = LIT_CHAMBRE
                    ,activite[PX].t_etages
                WHERE 1=1
                    AND t_lits.etage_id = t_etages.oid
                    AND t_lits.code = LITS.LIT_CODE
                    AND t_etages.code_original = CHAMBRES.CHA_UF
                    AND t_lits.code_original IS DISTINCT FROM (CHA_UF::text || '-'::text || LIT_OID::text)
				;
                    
                INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT CHA_UF || '-' || MAX(LIT_OID),
					LIT_CODE, 
					CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END, 
					CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END, 
					t_etages.oid,
					CASE WHEN CHA_COMMUNE = '1' THEN 'N' ELSE 'O' END AS chambre_particuliere
				FROM prod_web100t.CHAMBRES
					JOIN prod_web100t.LITS ON CHA_OID = LIT_CHAMBRE
					JOIN activite[PX].t_etages ON CHA_UF::bigint = t_etages.code_original
				GROUP BY CHA_UF,2,3,4,5,6
				HAVING 
					CHA_UF || '-' || MAX(LIT_OID) NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL)
				ORDER BY LIT_CODE;
										
				INSERT INTO activite[PX].t_lits(code_original, code, texte, texte_court, etage_id, chambre_particuliere)
				SELECT code_original || '-0' , '', 'Non renseigné', 'Non renseigné', oid, 'N' 
				FROM activite[PX].t_etages
				WHERE oid > 0 AND
					code_original || '-0' NOT IN (SELECT code_original FROM activite[PX].t_lits WHERE code_original IS NOT NULL);

				UPDATE activite[PX].t_lits SET code = '*****' WHERE code = '';

				UPDATE activite[PX].t_lits SET
					code = LIT_CODE,
					texte = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END,
					texte_court = CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
				FROM 
					(
						with max_lit_oid AS (
							SELECT CHAMBRES.CHA_OID, CHAMBRES.CHA_UF, MAX(LITS.LIT_OID) AS MAX_LIT_OID
							FROM prod_web100t.CHAMBRES
							JOIN prod_web100t.LITS ON CHA_OID = LIT_CHAMBRE
							GROUP BY 1,2
						)
						SELECT 
							CHAMBRES.CHA_UF,
							CHAMBRES.CHA_CODE,
							max_lit_oid.MAX_LIT_OID,
							LITS.LIT_CODE,
							LITS.LIT_DESCR
						FROM max_lit_oid
						JOIN prod_web100t.CHAMBRES ON CHAMBRES.CHA_OID = max_lit_oid.CHA_OID
						JOIN prod_web100t.LITS ON LIT_OID = max_lit_oid.MAX_LIT_OID
						JOIN activite[PX].t_etages ON t_etages.code_original = CHAMBRES.CHA_UF::bigint
					) AS subview
				WHERE subview.CHA_UF || '-' || subview.MAX_LIT_OID = code_original AND
					(
						code IS DISTINCT FROM LIT_CODE OR
						texte IS DISTINCT FROM CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END OR
						texte_court IS DISTINCT FROM CASE WHEN LIT_DESCR <> '' THEN LIT_DESCR ELSE CHA_CODE || CASE WHEN LIT_CODE <> CHA_CODE THEN '. ' || LIT_CODE ELSE '' END END
					)
				;

				
				DROP TABLE IF EXISTS w_NMCL_UNITEFONCTIONNELLE;
				CREATE TEMP TABLE w_NMCL_UNITEFONCTIONNELLE AS
				SELECT 
					ND_INVARIANT_OID AS WEB100T_OID,
					COALESCE(t_services_facturation.oid,0) AS service_facturation_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(mode_traitement_id,0) AS mode_traitement_id,
					COALESCE(t_modes_traitement.code,'') AS mode_traitement_code,
					COALESCE(dmt_id,0) AS dmt_id,
					COALESCE(t_dmt.code,'') AS dmt_code,
					COALESCE(t_services_facturation.type_sejour,'') AS type_sejour,
					COALESCE(t_services_facturation.type_t2a,'0') AS type_t2a
				FROM w_SGN_NMCL_DATA
					LEFT JOIN activite[PX].t_services_facturation ON ND_INVARIANT_OID::bigint = t_services_facturation.code_original
					LEFT JOIN activite[PX].t_unites_fonctionnelles ON ND_INVARIANT_OID::bigint = t_unites_fonctionnelles.code_original
					LEFT JOIN base.t_modes_traitement ON mode_traitement_id = t_modes_traitement.oid
					LEFT JOIN base.t_dmt ON mode_traitement_id = t_dmt.oid
				WHERE NMCL_IDENT = 'UNITEFONCTIONNELLE';

				
			]]></sqlcmd>
		</NODE>

		<NODE label="Facturation">
			<sqlcmd><![CDATA[
				
				-- Rubriques et prestations

				DROP TABLE IF EXISTS w_ART_ARTICLES;
				CREATE TEMP TABLE w_ART_ARTICLES AS
				SELECT 
					ART_ARTICLES.ART_OID, 
					CASE WHEN ART_ARTICLES.ART_CLASS NOT IN ('GRP', 'CCAM', 'UCD', 'LPP', 'GHS', 'GHT') THEN ART_ARTICLES.ART_OID ELSE ART_ARTICLES.ART_PARENT END AS ART_OID_rub,
					CASE WHEN ART_ARTICLES.ART_CLASS NOT IN ('GRP', 'CCAM', 'UCD', 'LPP', 'GHS', 'GHT') THEN ART_ARTICLES.ART_CODE ELSE ART_ARTICLES.ART_CLASS END AS ART_CODE,
					CASE WHEN ART_ARTICLES.ART_CLASS NOT IN ('GRP', 'CCAM', 'UCD', 'LPP', 'GHS', 'GHT') THEN ART_ARTICLES.ART_LIB ELSE ART_ARTICLES_CLASS.ART_LIB END AS ART_LIB,
					CASE WHEN ART_ARTICLES.ART_CLASS IN ('CCAM') THEN substring(ART_ARTICLES.ART_CODE,1,7) ELSE ART_ARTICLES.ART_CODE_B2 END AS ART_CODE_ACTE,
                    ART_ARTICLES.ART_CODE AS ART_CODE_2,
					ART_ARTICLES.ART_LIB AS ART_LIB_ACTE,
					ART_ARTICLES.ART_CODE_B2::text,
					ART_ARTICLES.ART_DEBUT_VALIDITE,
					CASE WHEN ART_ARTICLES.ART_CLASS IN ('CCAM') THEN substring(ART_ARTICLES.ART_CODE,9,1) ELSE '' END AS ART_CODE_ACTIVITE,
					CASE WHEN ART_ARTICLES.ART_CLASS IN ('CCAM') THEN substring(ART_ARTICLES.ART_CODE,11,1) ELSE '' END AS ART_CODE_PHASE,
					0::bigint AS rubrique_facturation_id,
					0::bigint AS prestation_id,
					0::bigint AS acte_id,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id
				FROM prod_web100t.ART_ARTICLES
					JOIN prod_web100t.ART_ARTICLES ART_ARTICLES_CLASS ON ART_ARTICLES.ART_PARENT = ART_ARTICLES_CLASS.ART_OID;

				-- Forcage prestation
				UPDATE w_ART_ARTICLES SET
					ART_CODE_B2 = t_prestations.code
				FROM activite[PX].t_rubriques_facturation
				JOIN activite.t_prestations ON prestation_forcee_id = t_prestations.oid AND prestation_forcee_id <> 0
				WHERE ART_OID::text = t_rubriques_facturation.code_original
				;
	
				UPDATE w_ART_ARTICLES SET ART_CODE_B2 = ART_CODE WHERE ART_CODE_B2 = '' AND ART_CODE <> '';
                
                -- Codes ou texte modifiés
				UPDATE activite[PX].t_rubriques_facturation SET
					code = ART_CODE,
					texte = ART_LIB,
					texte_court = ART_LIB
				FROM prod_web100T.ART_ARTICLES
				WHERE code_original = ART_OID AND
					ART_ARTICLES.ART_CLASS NOT IN ('GRP', 'CCAM', 'UCD', 'LPP', 'GHS', 'GHT') AND
					(
					t_rubriques_facturation.code <> ART_CODE OR
					t_rubriques_facturation.texte <> ART_LIB OR
					t_rubriques_facturation.texte_court <> ART_LIB
					)
				;
                
                -- code changé avec code original inchangé
                UPDATE activite[PX].t_rubriques_facturation SET
                    code = ART_CODE
                FROM 
                    ( 
                    SELECT 
                        (MAX(Array[ART_DEBUT_VALIDITE::text,ART_OID_rub::text]))[2]::bigint AS ART_OID_rub,
                        ART_CODE,
                        (MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB]))[2] AS ART_LIB,
                        (MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB]))[2] AS ART_LIB
                    FROM w_ART_ARTICLES
                    GROUP BY ART_CODE
                    ) as subq
                WHERE code_original = ART_OID_rub
                AND code != ART_CODE
                ;                  
				
				INSERT INTO activite[PX].t_rubriques_facturation(code_original, code, texte, texte_court)
				SELECT 
					(MAX(Array[ART_DEBUT_VALIDITE::text,ART_OID_rub::text]))[2]::bigint AS ART_OID_rub,
					ART_CODE,
					(MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB]))[2] AS ART_LIB,
					(MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB]))[2] AS ART_LIB
				FROM w_ART_ARTICLES
				GROUP BY ART_CODE
				HAVING (MAX(Array[ART_DEBUT_VALIDITE::text,ART_OID_rub::text]))[2] NOT IN (SELECT code_original FROM activite[PX].t_rubriques_facturation) AND
					ART_CODE NOT IN (SELECT code FROM activite[PX].t_rubriques_facturation WHERE t_rubriques_facturation.code IS NOT NULL)
                ;

				INSERT INTO activite.t_prestations(code_original, code, texte, texte_court)
				SELECT 
					ART_CODE_B2,
					ART_CODE_B2,
					ART_CODE_B2,
					ART_CODE_B2
				FROM w_ART_ARTICLES
				WHERE ART_CODE_B2 NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
				GROUP BY ART_CODE_B2
				ORDER BY ART_CODE_B2;
				
				INSERT INTO base.t_actes(
					code, texte, texte_court, nomenclature, ccam_regroupement_id_1, ccam_regroupement_id_4, 
					geste_marqueur_id)
				SELECT 
					substring(ART_CODE_ACTE, 1, 7), 
					(MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB_ACTE]))[2] AS ART_LIB_ACTE, 
					(MAX(Array[ART_DEBUT_VALIDITE::text,ART_LIB_ACTE]))[2] AS ART_LIB_ACTE, 
					MIN(CASE WHEN length(trim(ART_CODE_ACTE)) >= 7 THEN 'CCAM' ELSE 'NGAP' END),
					MIN(COALESCE(t_ccam_regroupements_1.oid,0)),
					MIN(COALESCE(t_ccam_regroupements_4.oid,0)),
					0
				FROM w_ART_ARTICLES 
					LEFT JOIN base.t_ccam_regroupements t_ccam_regroupements_1 ON t_ccam_regroupements_1.code = CASE WHEN length(trim(ART_CODE_ACTE)) >= 7 THEN ART_CODE_B2 ELSE 'NGAP' END
					LEFT JOIN base.t_ccam_regroupements t_ccam_regroupements_4 ON t_ccam_regroupements_4.code = CASE WHEN length(trim(ART_CODE_ACTE)) >= 7 THEN 'ADA' ELSE 'NGAP' END
				WHERE 
					substring(ART_CODE_ACTE, 1, 7) NOT IN (SELECT code FROM base.t_actes) AND 
					ART_OID = ANY (ARRAY (SELECT DISTINCT FLT_ARTICLE FROM prod_web100t.FAC_FACT_LIGNE_TIER WHERE FLT_IS_ETS = 0 AND FLT_DATE_DEBUT >= '[ENV_ADM_ANNEEDEBUT]0101'::timestamp without time zone)::double precision[])
				GROUP BY 1;


				

				UPDATE w_ART_ARTICLES
				SET prestation_id = t_prestations.oid
				FROM activite.t_prestations
				WHERE ART_CODE_B2 = code;


				UPDATE w_ART_ARTICLES
				SET rubrique_facturation_id = t_rubriques_facturation.oid
				FROM activite[PX].t_rubriques_facturation
				WHERE ART_CODE = code;
				
				
				UPDATE w_ART_ARTICLES
				SET acte_id = t_actes.oid
				FROM base.t_actes
				WHERE substring(ART_CODE_ACTE, 1, 7) = code;
				
				UPDATE w_ART_ARTICLES
				SET ucd_id = t_ucd.oid
				FROM base.t_ucd
				WHERE ART_CODE_2 = t_ucd.code;

				UPDATE w_ART_ARTICLES
				SET lpp_id = t_lpp.oid
				FROM base.t_lpp
				WHERE ART_CODE_2 = t_lpp.code;


				ALTER TABLE w_ART_ARTICLES ADD CONSTRAINT w_ART_ARTICLES_pkey PRIMARY KEY(ART_OID);
				
				-- Journal
				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT JOUR_TYPE,
					JOUR_TYPE,
					SPLIT_PART(JOUR_LIB,' ',1)
				FROM prod_web100t.CPT_JOURNAL
				WHERE JOUR_TYPE NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3
				;

				INSERT INTO activite[PX].t_journal (code_original, code, texte)
				SELECT LNK_JOURNAL, LNK_JOURNAL, 
				    CASE LNK_JOURNAL
			            WHEN 'VE' THEN 'Ventes'
			            WHEN 'HONO' THEN 'Honoraires'
			            WHEN 'RGLMT' THEN 'Règlements'
			            WHEN 'ENCRS' THEN 'En cours'
			            ELSE LNK_JOURNAL END
				FROM w_CPT_OP_LINK_source
				WHERE LNK_JOURNAL NOT IN (SELECT code_original FROM activite[PX].t_journal WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3
				;
				
				-- Comptes
                INSERT INTO activite[PX].t_compte(oid, code_original, code, texte, texte_court) 
				SELECT 0, 0, '', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_compte);
                
				INSERT INTO activite[PX].t_compte(code_original, code, texte, texte_court)
				SELECT
					CPT_CODE,
					CPT_CODE,
					(max(DISTINCT ARRAY[cpt_created::text, CPT_LIB]))[2],
					(max(DISTINCT ARRAY[cpt_created::text, CPT_LIB]))[2]
				FROM PROD_WEB100T.CPT_COMPTES				
				WHERE CPT_CODE <> '' AND 
					CPT_OID = ANY(SELECT ECR_COMPTE FROM w_CPT_ECRITURE_source) AND
					CPT_CODE NOT IN (SELECT code FROM activite[PX].t_compte) AND
					CPT_CODE NOT IN (SELECT code_original FROM activite[PX].t_compte)
				GROUP BY 1
				ORDER BY 1;

				UPDATE activite[PX].t_compte SET
					code = subview.CPT_CODE,
					texte = subview.MAX_CPT_LIB,
					texte_court = subview.MAX_CPT_LIB
				FROM 
				(
					SELECT CPT_CODE, (max(DISTINCT ARRAY[cpt_created::text, CPT_LIB]))[2] AS MAX_CPT_LIB
					FROM PROD_WEB100T.CPT_COMPTES	
					GROUP BY 1
				) AS subview 
				WHERE subview.CPT_CODE = code_original AND
					(
						code IS DISTINCT FROM subview.CPT_CODE OR
						texte IS DISTINCT FROM subview.MAX_CPT_LIB OR
						texte_court IS DISTINCT FROM subview.MAX_CPT_LIB
					)
				;

				with last_libelle as (
					select
						CPT_CODE,
						(max(DISTINCT ARRAY[cpt_created::text, CPT_LIB]))[2] as CPT_LIB
					from PROD_WEB100T.CPT_COMPTES
					where CPT_TYPE = '1'
					group by 1
				)
				UPDATE activite[PX].t_compte SET
					texte       = last_libelle.CPT_LIB,
					texte_court = last_libelle.CPT_LIB
				FROM last_libelle
				WHERE 1=1
					AND t_compte.code = last_libelle.CPT_CODE
					AND (1!=1
						OR texte IS DISTINCT FROM CPT_LIB
						OR texte_court IS DISTINCT FROM CPT_LIB)
				;
						
				UPDATE activite[PX].t_compte
				SET taux_tva = subview.taux_tva*100
				FROM
				(
				SELECT CPT_CODE, (MAX(ARRAY[nb,ECR_TVA_TAUX]))[2]::numeric AS taux_tva
				FROM
				(
				SELECT CPT_CODE, ECR_TVA_TAUX, count(*) AS nb
								FROM prod_web100t.CPT_ECRITURE
								JOIN prod_web100t.CPT_COMPTES ON CPT_OID = ECR_COMPTE
								WHERE ECR_TYPE LIKE 'PRODUIT%'
								GROUP BY 1,2
				) subview
				GROUP BY 1
				ORDER BY 1
				) subview
				WHERE t_compte.code = CPT_CODE AND 
					subview.taux_tva <> 0 AND
					subview.taux_tva <> 0 AND
					t_compte.taux_tva = 0
				;

				DROP TABLE IF EXISTS w_CPT_OP_LINK_source_agg;
				CREATE TEMP TABLE w_CPT_OP_LINK_source_agg AS
				SELECT LNK_OPERATION,
					LNK_MASTER_OP
				FROM w_CPT_OP_LINK_source
				;
				
				CREATE INDEX w_CPT_OP_LINK_source_agg_ik_LNK_MASTER_OP
					ON w_CPT_OP_LINK_source_agg
					USING btree
					(LNK_MASTER_OP)
				;
				
				
				DROP TABLE IF EXISTS w_CPT_OP_LINK_source;
										
			]]></sqlcmd>
		</NODE>

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

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

		<NODE label="Compléments patients">
			<sqlcmd><![CDATA[
				
				-- Refonte médecins correspondants par ELA le 21/10/2021
				-- Il y a deux tables prod_web100t.MWS_NMCL_CORRESPONDANT et prod_web100t.NMCL_CORRESPONDANTS (ancienne)
				DROP TABLE IF EXISTS w_CORRESPONDANT;
				CREATE TEMP TABLE w_CORRESPONDANT AS
				SELECT MWS_NMCL_CORRESPONDANT.OID::text AS NMCL_CORRESPONDANT_OID,
					CASE WHEN FLD_NOM <> '' THEN FLD_NOM ELSE TRIM(REPLACE(SGN_NMCL_DATA_COR.ND_LIB, FLD_PRENOM, '')) END || ' '|| FLD_PRENOM AS NMCL_CORRESPONDANT_OID2,
					NULL::bigint[] AS COR_ID_array,
					SGN_NMCL_DATA_COR.ND_CODE::text, 
					CASE WHEN FLD_NOM <> '' THEN trim(FLD_NOM) ELSE TRIM(REPLACE(SGN_NMCL_DATA_COR.ND_LIB, FLD_PRENOM, ''))::text END AS FLD_NOM,
					FLD_PRENOM::text,
					FLD_CODEADELI::text,
					FLD_SPECIALITE,
					FLD_CODERPPS,
					COALESCE(SUBSTR(SGN_NMCL_DATA_SPE.ND_CODE,1,10),'')::text AS FLD_SPECIALITE_CODE,
					row_number() OVER (PARTITION BY UPPER(CASE WHEN FLD_NOM <> '' THEN trim(FLD_NOM) ELSE TRIM(REPLACE(SGN_NMCL_DATA_COR.ND_LIB, FLD_PRENOM, '')) END), UPPER(trim(FLD_PRENOM)) ORDER BY MWS_NMCL_CORRESPONDANT.OID) AS rang,
					0::bigint AS specialite_id,
					0::bigint AS medecin_traitant_id
				FROM prod_web100t.MWS_NMCL_CORRESPONDANT
					JOIN prod_web100t.SGN_NMCL_DATA SGN_NMCL_DATA_COR ON SGN_NMCL_DATA_COR.ND_INVARIANT_OID = MWS_NMCL_CORRESPONDANT.OID 
					JOIN prod_web100t.SGN_NMCLS SGN_NMCLS_COR ON SGN_NMCL_DATA_COR.ND_NMCL_OID = SGN_NMCLS_COR.NMCL_OID AND SGN_NMCLS_COR.NMCL_IDENT = 'CORRESPONDANT'
					LEFT JOIN prod_web100t.SGN_NMCL_DATA SGN_NMCL_DATA_SPE ON SGN_NMCL_DATA_SPE.ND_INVARIANT_OID = MWS_NMCL_CORRESPONDANT.FLD_SPECIALITE 
					LEFT JOIN prod_web100t.SGN_NMCLS SGN_NMCLS_SPE ON SGN_NMCL_DATA_SPE.ND_NMCL_OID = SGN_NMCLS_SPE.NMCL_OID AND SGN_NMCLS_SPE.NMCL_IDENT = 'SPECIALITE'
				WHERE FLD_NOM <> '' OR SGN_NMCL_DATA_COR.ND_LIB <> ''
				;
				
				ANALYSE w_CORRESPONDANT
				;

				UPDATE w_CORRESPONDANT
				SET COR_ID_array = subview.COR_ID_array
				FROM 
					(
					SELECT UPPER(trim(COR_NOM)) AS COR_NOM, UPPER(trim(COR_PRENOM)) AS COR_PRENOM, base.cti_array_accum(COR_ID) AS COR_ID_array
					FROM prod_web100t.CORRESPONDANTS
					GROUP BY 1,2
					) subview
				WHERE COR_NOM ILIKE FLD_NOM AND
					COR_PRENOM ILIKE FLD_PRENOM AND
					rang = 1
					;

				DROP TABLE IF EXISTS w_CORRESPONDANTS_ok;
				CREATE TEMP TABLE w_CORRESPONDANTS_ok AS
				SELECT unnest(COR_ID_array) AS COR_ID_ok 
				FROM w_CORRESPONDANT
				WHERE rang = 1
				GROUP BY 1
				;

				INSERT INTO w_CORRESPONDANT
				SELECT 
					MAX('OLDCOR'::text || COR_ID) AS NMCL_CORRESPONDANT_OID,
					MAX(CASE WHEN COR_CODE <> '' THEN COR_CODE ELSE COR_NOM || ' '|| COR_PRENOM END) AS NMCL_CORRESPONDANT_OID2,
					base.cti_array_accum(COR_ID) AS COR_ID_array,
					MAX(CASE WHEN COR_CODE <> '' THEN COR_CODE ELSE COR_NOM || ' '|| COR_PRENOM END) AS ND_CODE, 
					trim(COR_NOM) AS FLD_NOM,
					trim(COR_PRENOM) AS FLD_PRENOM,
					MAX(COR_ADELI) AS COR_ADELI,
					0::numeric AS FLD_SPECIALITE,
					MAX(COR_RPPS) AS FLD_CODERPPS,
					''::text AS FLD_SPECIALITE_CODE,
					1::numeric AS rang,
					0::bigint AS specialite_id,
					0::bigint AS medecin_traitant_id
				FROM prod_web100t.CORRESPONDANTS
				LEFT JOIN w_CORRESPONDANTS_ok ON COR_ID = COR_ID_ok
				WHERE COR_NOM <> '' AND
					COR_ID_ok IS NULL
				GROUP BY 5,6
				;
				
				UPDATE w_CORRESPONDANT
				SET specialite_id = t_specialites_medecin.oid
				FROM base.t_specialites_medecin
				WHERE FLD_SPECIALITE_CODE <> '' AND
					t_specialites_medecin.code = (FLD_SPECIALITE_CODE||'..') AND
					rang = 1
				;
				UPDATE w_CORRESPONDANT
				SET specialite_id = t_specialites_medecin.oid
				FROM base.t_specialites_medecin
				WHERE FLD_SPECIALITE_CODE <> '' AND
					specialite_id = 0 AND
					t_specialites_medecin.code = (FLD_SPECIALITE_CODE)AND
					rang = 1
				;

				UPDATE activite[PX].t_medecins_traitants_administratifs SET
					code_original = w_CORRESPONDANT.NMCL_CORRESPONDANT_OID
				FROM w_CORRESPONDANT
				LEFT JOIN activite[PX].t_medecins_traitants_administratifs t_medecins_traitants_administratifs_2 ON t_medecins_traitants_administratifs_2.code_original = NMCL_CORRESPONDANT_OID
				WHERE t_medecins_traitants_administratifs_2.code_original IS NULL AND
					t_medecins_traitants_administratifs.code_original = NMCL_CORRESPONDANT_OID2 AND
					t_medecins_traitants_administratifs.code_original <> w_CORRESPONDANT.NMCL_CORRESPONDANT_OID
				;

				UPDATE activite[PX].t_medecins_traitants_administratifs SET
					code = w_CORRESPONDANT.ND_CODE,
					nom = w_CORRESPONDANT.FLD_NOM,
					prenom = w_CORRESPONDANT.FLD_PRENOM,
					no_rpps = CASE WHEN FLD_CODERPPS <> '' AND length(w_CORRESPONDANT.FLD_CODERPPS) = 11 THEN FLD_CODERPPS ELSE no_rpps END
				FROM w_CORRESPONDANT
				WHERE code_original = NMCL_CORRESPONDANT_OID AND
					(
					code IS DISTINCT FROM w_CORRESPONDANT.ND_CODE OR
					nom IS DISTINCT FROM w_CORRESPONDANT.FLD_NOM OR
					prenom IS DISTINCT FROM w_CORRESPONDANT.FLD_PRENOM OR
					no_rpps IS DISTINCT FROM w_CORRESPONDANT.FLD_CODERPPS AND w_CORRESPONDANT.FLD_CODERPPS <> '' AND length(w_CORRESPONDANT.FLD_CODERPPS) = 11
					)
				;

				INSERT INTO activite[PX].t_medecins_traitants_administratifs(code_original, code, nom, prenom, specialite_id,  medecin_id)
				SELECT NMCL_CORRESPONDANT_OID, NMCL_CORRESPONDANT_OID, min(FLD_NOM), min(FLD_PRENOM),min(COALESCE(t_specialites_medecin.oid,0)), 0
				FROM w_CORRESPONDANT
				    LEFT JOIN base.t_specialites_medecin ON (FLD_SPECIALITE::bigint = t_specialites_medecin.code_original)
				WHERE rang = 1 AND
					NMCL_CORRESPONDANT_OID NOT IN (SELECT code_original FROM activite[PX].t_medecins_traitants_administratifs)
				GROUP BY 1, 2
				;
				
				UPDATE w_CORRESPONDANT
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM activite[PX].t_medecins_traitants_administratifs
				WHERE t_medecins_traitants_administratifs.code_original = NMCL_CORRESPONDANT_OID
				;

				UPDATE w_CORRESPONDANT
				SET medecin_traitant_id = t_medecins_traitants_administratifs.oid
				FROM w_CORRESPONDANT w_CORRESPONDANT1 
				JOIN activite[PX].t_medecins_traitants_administratifs ON 
					w_CORRESPONDANT1.rang = 1 AND
					t_medecins_traitants_administratifs.code_original = w_CORRESPONDANT1.NMCL_CORRESPONDANT_OID
				WHERE upper(w_CORRESPONDANT.FLD_NOM) = upper(w_CORRESPONDANT1.FLD_NOM) AND
					upper(w_CORRESPONDANT.FLD_PRENOM) = upper(w_CORRESPONDANT1.FLD_PRENOM) AND
					w_CORRESPONDANT.rang > 1
				;

				
				DROP TABLE IF EXISTS w_sejours;
				CREATE TEMP TABLE w_sejours AS
				SELECT no_sejour,
					date_entree,
					p_sejours.no_patient, 
					p_patients.nom,
					''::text AS no_patient_web100t,
					''::text AS nom_web100t,
					0::numeric AS PAT_MED_TRAITANT,
					0::bigint AS medecin_traitant_id
				FROM activite[PX].p_sejours
				JOIN activite[PX].p_patients ON p_sejours.no_patient = p_patients.no_patient
				;


				
				ANALYSE w_sejours
				;

				UPDATE w_sejours
				SET no_patient_web100t = PAT_IPP, nom_web100T = PAT_NOM, PAT_MED_TRAITANT = PATIENTS.PAT_MED_TRAITANT
				FROM prod_web100T.PATIENTS
				WHERE lpad(no_patient,10,'0') = lpad(PAT_IPP,10,'0') AND PATIENTS.PAT_MED_TRAITANT <> 0
				;

				ANALYSE w_sejours
				;
				
				UPDATE w_sejours
				SET medecin_traitant_id = w_CORRESPONDANT.medecin_traitant_id
				FROM w_CORRESPONDANT
				WHERE PAT_MED_TRAITANT = NMCL_CORRESPONDANT_OID
				;

				DROP TABLE IF EXISTS w_CORRESPONDANTS_ok;
				CREATE TEMP TABLE w_CORRESPONDANTS_ok AS
				SELECT unnest(COR_ID_array) AS COR_ID_ok, MAX(medecin_traitant_id) AS medecin_traitant_id
				FROM w_CORRESPONDANT
				WHERE rang = 1 AND 
					medecin_traitant_id <> 0
				GROUP BY 1
				;

				UPDATE w_sejours
				SET medecin_traitant_id = w_CORRESPONDANTS_ok.medecin_traitant_id
				FROM w_CORRESPONDANTS_ok
				WHERE w_sejours.medecin_traitant_id = 0 AND
					PAT_MED_TRAITANT = COR_ID_ok
				;
				
				
				UPDATE activite[PX].p_sejours
				SET medecin_traitant_id = w_sejours.medecin_traitant_id
				FROM w_sejours
				WHERE p_sejours.no_sejour = w_sejours.no_sejour AND
					w_sejours.medecin_traitant_id <> 0 AND
					p_sejours.medecin_traitant_id <> w_sejours.medecin_traitant_id
				;
				
					
				-- ajout des coordonnées par séjour
				INSERT INTO activite[PX].p_coordonnees_patient (
					sejour_id,
					adresse,
					code_postal_id,
					commune,
					telephone_fixe,
					telephone_portable,
					email						
					)
                SELECT
					p_sejours.oid,
					ADR_ADRESSE,
					COALESCE(t_codes_postaux.oid,0),
					ADR_COMMUNE,
					ADR_TEL_1,
					ADR_TEL_2,
					ADR_EMAIL
				FROM activite[PX].p_sejours
					LEFT JOIN prod_web100t.DAT_DA w_DAT_DA ON code_original = DA_OID
					LEFT JOIN prod_web100t.PATIENTS ON w_DAT_DA.DA_PATIENT = PATIENTS.PAT_ID
					LEFT JOIN prod_web100t.ADRESSES ON PAT_ADRESSE = ADR_ID
					LEFT JOIN base.t_codes_postaux ON ADR_CODE_POSTAL = t_codes_postaux.code
					
					;	
			]]></sqlcmd>
		</NODE>
		<NODE label="Compléments facture">
			<sqlcmd><![CDATA[

				-- Les factures sans montant comptabilisé n'ont pas de date de vente
				UPDATE activite[PX].p_factures SET
					code_vente = '1',
					date_vente = date_facture,
					mois_vente = to_char(date_facture,'YYYYMM')::numeric
				WHERE date_facture <= date(now()) AND
					code_facture = '1' AND
					montant_comptabilise_c = 0 AND
					montant_comptabilise_h = 0 AND
					code_vente = '0'
				;

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

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

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

				CREATE INDEX w_factures_i1
					ON w_factures
					USING btree
					(no_facture);
				
				CREATE INDEX w_factures_i2
					ON w_factures
					USING btree
					(no_facture_reference);



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


				CREATE INDEX w_factures_references_soldes_i1
				ON w_factures_references_soldes
				USING btree
				(no_facture_reference);

				


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

				
			]]></sqlcmd>
		</NODE>

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

				UPDATE activite[PX].p_sejours 
				SET date_groupage = date_facture 
				WHERE (date_groupage IS null OR date_groupage = '20991231') AND 
					date_facture <> '2099-12-31';
				
				
				DROP TABLE IF EXISTS w_sejours_total;
				CREATE TEMP TABLE w_sejours_total AS
				SELECT   
					p_sejours.no_sejour AS no_sejour, 
					p_sejours.code_sorti,
					p_sejours.date_sortie,
					p_sejours.date_groupage,   
					p_sejours.ghs_id,
	
					MAX(COALESCE(p_factures.date_facture,'20991231')) AS date_facture,     
					MAX(COALESCE(p_factures.date_expedition,'20991231')) AS date_expedition,  
					MAX(COALESCE(p_factures.date_solde,'20991231')) AS date_solde,  
					SUM(COALESCE(p_factures.montant_facture_c,0)) AS montant_facture_c,  
					SUM(COALESCE(p_factures.montant_facture_h,0)) AS montant_facture_h,  
					SUM(COALESCE(p_factures.montant_regle_c,0)) AS montant_regle_c,  
					SUM(COALESCE(p_factures.montant_regle_h,0)) AS montant_regle_h,  
					SUM(COALESCE(CASE WHEN p_factures.type_facture <> 'P' AND p_factures.type_facture <> 'E' AND p_factures.type_facture <> 'G' THEN 1 ELSE 0 END,0)) AS nb_factures,  
					SUM(COALESCE(CASE WHEN p_factures.type_facture = '0' THEN 0 ELSE 1 END,0)) AS nb_factures_regularisation,  
					SUM(COALESCE(p_factures.nb_rejets,0)) AS nb_rejets,  

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

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

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

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

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

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

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

					0::numeric AS delai_groupage, 
					0::numeric AS delai_facture, 
					0::numeric AS delai_expedition, 
					0::numeric AS delai_solde, 
					0::numeric AS delai_expedition_0, 
					0::numeric AS delai_solde_0, 
					0::numeric AS delai_expedition_1, 
					0::numeric AS delai_solde_1, 
					0::numeric AS delai_expedition_2, 
					0::numeric AS delai_solde_2, 
					0::numeric AS delai_expedition_22, 
					0::numeric AS delai_solde_22
				
				FROM activite[PX].p_sejours LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND type_facture <> 'P'
				GROUP BY 1,2,3,4,5;
				
				
				UPDATE activite[PX].p_sejours 
				SET date_groupage = date_facture 
				WHERE (date_groupage IS null OR date_groupage = '20991231' OR date_groupage = '00010101') AND 
					date_facture <> '2099-12-31';


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

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

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



				UPDATE activite[PX].p_sejours SET

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

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

					montant_facture_1_c = w_sejours_total.montant_facture_1_c,  
					montant_facture_1_h = w_sejours_total.montant_facture_1_h,  
					montant_regle_1_c = w_sejours_total.montant_regle_1_c,  
					montant_regle_1_h = w_sejours_total.montant_regle_1_h,  
					date_expedition_1 = w_sejours_total.date_expedition_1,   
					date_solde_1 = w_sejours_total.date_solde_1,  
		 
					montant_facture_2_c = w_sejours_total.montant_facture_2_c,  
					montant_facture_2_h = w_sejours_total.montant_facture_2_h,  
					montant_regle_2_c = w_sejours_total.montant_regle_2_c,  
					montant_regle_2_h = w_sejours_total.montant_regle_2_h,  
					date_expedition_2 = w_sejours_total.date_expedition_2, 
					date_solde_2 = w_sejours_total.date_solde_2,  
		 
					montant_facture_22_c = w_sejours_total.montant_facture_22_c,  
					montant_facture_22_h = w_sejours_total.montant_facture_22_h,  
					montant_regle_22_c = w_sejours_total.montant_regle_22_c,  
					montant_regle_22_h = w_sejours_total.montant_regle_22_h,  
					date_expedition_22 = w_sejours_total.date_expedition_22, 
					date_solde_22 = w_sejours_total.date_solde_22,
					
					montant_comptabilise_c = w_sejours_total.montant_comptabilise_c,  
					montant_comptabilise_h = w_sejours_total.montant_comptabilise_h,  
					montant_comptabilise_0_c = w_sejours_total.montant_comptabilise_0_c,  
					montant_comptabilise_0_h = w_sejours_total.montant_comptabilise_0_h,  
					montant_comptabilise_1_c = w_sejours_total.montant_comptabilise_1_c,  
					montant_comptabilise_1_h = w_sejours_total.montant_comptabilise_1_h,  
					montant_comptabilise_2_c = w_sejours_total.montant_comptabilise_2_c,  
					montant_comptabilise_2_h = w_sejours_total.montant_comptabilise_2_h,  
					montant_comptabilise_22_c = w_sejours_total.montant_comptabilise_22_c,  
					montant_comptabilise_22_h = w_sejours_total.montant_comptabilise_22_h,

					montant_comptabilise_budget_global_c = w_sejours_total.montant_comptabilise_budget_global_c,

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


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

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

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

					p_sejours.montant_facture_1_c IS DISTINCT FROM w_sejours_total.montant_facture_1_c OR   
					p_sejours.montant_facture_1_h IS DISTINCT FROM w_sejours_total.montant_facture_1_h OR   
					p_sejours.montant_regle_1_c IS DISTINCT FROM w_sejours_total.montant_regle_1_c OR   
					p_sejours.montant_regle_1_h IS DISTINCT FROM w_sejours_total.montant_regle_1_h OR   
					p_sejours.date_expedition_1 IS DISTINCT FROM w_sejours_total.date_expedition_1 OR    
					p_sejours.date_solde_1 IS DISTINCT FROM w_sejours_total.date_solde_1 OR   
		 
					p_sejours.montant_facture_2_c IS DISTINCT FROM w_sejours_total.montant_facture_2_c OR   
					p_sejours.montant_facture_2_h IS DISTINCT FROM w_sejours_total.montant_facture_2_h OR   
					p_sejours.montant_regle_2_c IS DISTINCT FROM w_sejours_total.montant_regle_2_c OR   
					p_sejours.montant_regle_2_h IS DISTINCT FROM w_sejours_total.montant_regle_2_h OR   
					p_sejours.date_expedition_2 IS DISTINCT FROM w_sejours_total.date_expedition_2 OR  
					p_sejours.date_solde_2 IS DISTINCT FROM w_sejours_total.date_solde_2 OR   
		 
					p_sejours.montant_facture_22_c IS DISTINCT FROM w_sejours_total.montant_facture_22_c OR   
					p_sejours.montant_facture_22_h IS DISTINCT FROM w_sejours_total.montant_facture_22_h OR   
					p_sejours.montant_regle_22_c IS DISTINCT FROM w_sejours_total.montant_regle_22_c OR   
					p_sejours.montant_regle_22_h IS DISTINCT FROM w_sejours_total.montant_regle_22_h OR   
					p_sejours.date_expedition_22 IS DISTINCT FROM w_sejours_total.date_expedition_22 OR  
					p_sejours.date_solde_22 IS DISTINCT FROM w_sejours_total.date_solde_22 OR 
					
					p_sejours.montant_comptabilise_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_c OR   
					p_sejours.montant_comptabilise_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_h OR   
					p_sejours.montant_comptabilise_0_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_c OR   
					p_sejours.montant_comptabilise_0_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_0_h OR   
					p_sejours.montant_comptabilise_1_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_c OR   
					p_sejours.montant_comptabilise_1_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_1_h OR   
					p_sejours.montant_comptabilise_2_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_c OR   
					p_sejours.montant_comptabilise_2_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_2_h OR   
					p_sejours.montant_comptabilise_22_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_c OR   
					p_sejours.montant_comptabilise_22_h IS DISTINCT FROM w_sejours_total.montant_comptabilise_22_h OR   

					p_sejours.montant_comptabilise_budget_global_c IS DISTINCT FROM w_sejours_total.montant_comptabilise_budget_global_c OR   

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

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

				);
														
										
			]]></sqlcmd>
		</NODE>


		<NODE label="Tables répliquées">
			<condition><![CDATA[
				"[PX]" == ""
			]]></condition>

			<sqlcmd><![CDATA[

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




</ROOT>
