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

		<NODE label="Tests initiaux">
			<sqlcmd><![CDATA[
		
			]]></sqlcmd>
		</NODE>
	
		<NODE label="Identification des séjours">
			<sqlcmd><![CDATA[
            
                
				

				
			]]></sqlcmd>
		</NODE>
					
		<NODE label="Correstions">
			<sqlcmd><![CDATA[
				
				
				
		
			]]></sqlcmd>
		</NODE>
		
	</NODE>

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

			
				INSERT INTO activite.p_patients(finess, no_patient, nom, prenom, date_naissance, code_sexe)
				SELECT '', w_ASSURES.NUM_PAT, w_ASSURES.NOM, w_ASSURES.PRENOM, date(w_ASSURES.DATE_NAISS), CASE WHEN w_ASSURES.SEXE ILIKE 'M%' THEN '1' ELSE '2' END AS sexe			
				FROM w_ASSURES
					LEFT JOIN activite.p_patients ON NUM_PAT = p_patients.no_patient
				WHERE w_ASSURES.OK = 'O' AND
					p_patients.no_patient IS NULL 
				;
				
				
				
					
				UPDATE activite.p_patients SET
					nom = w_ASSURES.NOM, 
					prenom = w_ASSURES.PRENOM, 
					date_naissance = date(w_ASSURES.DATE_NAISS), 
					code_sexe = CASE WHEN w_ASSURES.SEXE ILIKE 'M%' THEN '1' ELSE '2' END
				FROM w_ASSURES
				WHERE p_patients.no_patient = NUM_PAT
					AND (
						p_patients.nom IS DISTINCT FROM w_ASSURES.NOM OR
						p_patients.prenom IS DISTINCT FROM w_ASSURES.PRENOM OR
						p_patients.date_naissance IS DISTINCT FROM date(w_ASSURES.DATE_NAISS) OR 
						p_patients.code_sexe IS DISTINCT FROM CASE WHEN w_ASSURES.SEXE ILIKE 'M%' THEN '1' ELSE '2' END
					);	
							
										
			]]></sqlcmd>
		</NODE>
				
		<NODE label="Séjours">
			<sqlcmd><![CDATA[

				DROP TABLE IF EXISTS w_sejours;
				CREATE TEMP TABLE w_sejours AS
				SELECT 
					w_ASSURES.NUM_PAT AS no_sejour, 
					w_ASSURES.NUM_PAT AS code_original, 
					NUM_PAT AS no_patient, 
					date_entree, 
					080000::numeric AS heure_entree, 
					CASE WHEN date_sortie IS NOT NULL THEN date_sortie ELSE '20991231'::date END AS date_sortie, 
					180000::numeric  AS heure_sortie, 
					CASE WHEN w_ASSURES.SEXE ILIKE 'M%' THEN '1' ELSE '2' END AS code_sexe, 
					0 AS age, 
					code_sorti, 
					0 AS code_prevu,
					'5'::text AS type_sejour,
					COALESCE(t_codes_postaux.oid,0) AS code_postal_id,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_sejour_id,
					COALESCE(t_ghm.oid,0) AS ghm_id,
					COALESCE(t_ghs.oid,0) AS ghs_id,
					'20991231'::date AS date_groupage,
					0::numeric AS code_cp_demandee,
					0 AS mode_traitement_id,
					'8'::character(1) AS mode_entree,
					'0'::character(1) AS provenance,
					'8'::character(1) AS mode_sortie,
					'0'::character(1) AS destination,
					COALESCE(t_tiers_payant_0.oid,0) AS tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid,0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid,0) AS tiers_payant_2_id,
					0 AS tiers_payant_22_id,
					0 AS est_budget_global, -- seulement pour privé pour l'instant
					''::text AS finess
				FROM w_ASSURES
				LEFT JOIN activite.t_medecins_administratifs ON w_ASSURES.medecin_sejour_code_original = t_medecins_administratifs.code_original
				LEFT JOIN activite.t_tiers_payant t_tiers_payant_1 ON w_ASSURES.CAISSE_NUM::text = t_tiers_payant_1.code_original
				LEFT JOIN activite.t_tiers_payant t_tiers_payant_2 ON w_ASSURES.MUT_NUM::text||'M' = t_tiers_payant_2.code_original
				LEFT JOIN activite.t_tiers_payant t_tiers_payant_0 ON t_tiers_payant_0.type_tiers_payant = '0' AND t_tiers_payant_0.oid <> 0
				LEFT JOIN base.t_ghm ON ghm_code = t_ghm.code
				LEFT JOIN base.t_ghs ON ghs_code = t_ghs.code
				LEFT JOIN base.t_codes_postaux ON w_ASSURES.CP = t_codes_postaux.code
				WHERE OK = 'O'
				;
					
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_13');
				
				-- Forcage type selon séjour
				UPDATE w_sejours
				SET type_sejour = t_sejour.type_sejour::int
				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')
					AND t_sejour.type_sejour is not NULL ;
						
				INSERT INTO activite[PX].p_sejours (
					no_sejour, 
					code_original, 
					no_patient, 
					date_entree, 
					heure_entree, 
					date_sortie, 
					heure_sortie, 
					code_sexe, 
					age, 
					code_sorti, 
					code_prevu, 
					type_sejour, 
					code_postal_id,
					medecin_sejour_id,
					date_groupage,
					code_cp_demandee,
					mode_traitement_id,
					mode_entree,
					provenance,
					mode_sortie,
					destination,
					ghm_id,
					ghs_id,
					tiers_payant_0_id,
					tiers_payant_1_id,
					tiers_payant_2_id,
					tiers_payant_22_id,
					est_budget_global,
                    finess
				) 
				SELECT 
					
					w_sejours.no_sejour, 
					w_sejours.code_original,
					w_sejours.no_patient, 
					w_sejours.date_entree, 
					w_sejours.heure_entree, 
					w_sejours.date_sortie, 
					w_sejours.heure_sortie, 
				    w_sejours.code_sexe::char(1),
					w_sejours.age, 
					w_sejours.code_sorti, 
					w_sejours.code_prevu, 
                    w_sejours.type_sejour::char(1), 
					w_sejours.code_postal_id,
					w_sejours.medecin_sejour_id,
					w_sejours.date_groupage,
                    w_sejours.type_sejour::char(1), 
					w_sejours.mode_traitement_id,
					w_sejours.mode_entree::char(1),
					w_sejours.provenance::char(1),
					w_sejours.mode_sortie::char(1),
					w_sejours.destination::char(1),
					w_sejours.ghm_id,
					w_sejours.ghs_id,
					w_sejours.tiers_payant_0_id,
					w_sejours.tiers_payant_1_id,
					w_sejours.tiers_payant_2_id,
					w_sejours.tiers_payant_22_id,
					w_sejours.est_budget_global,
                    w_sejours.finess
				FROM w_sejours
				;
				
				ANALYSE activite.p_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]' = '';
					
				-- GHM selon ghs dialyse
				UPDATE activite.p_sejours
				SET ghm_id = t_ghm.oid
				FROM base.t_ghs, base.t_ghm
				WHERE ghs_id = t_ghs.oid AND
					t_ghm.code = '28Z04Z' AND
					p_sejours.ghm_id = 0
				;

				
				-- Médecin séjour forcé
				UPDATE activite[PX].p_sejours
				SET medecin_sejour_id = t_sejour.medecin_sejour_id
				FROM activite.t_sejour
				WHERE t_sejour.no_sejour = p_sejours.no_sejour AND
					t_sejour.medecin_sejour_id <> 0 AND
					p_sejours.medecin_sejour_id IS DISTINCT FROM t_sejour.medecin_sejour_id AND
					'[PX]' = '';
			
			
				-- recréation index
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_4');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_5');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_6');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_7');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_8');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_9');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_10');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_11');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_12');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_13');
				
				
				-- assurance
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_disable_index('activite[PX]', 'i_sejours_assurance_4');
				
				INSERT INTO activite.p_sejours_assurance(
					sejour_id, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					matricule_1, 
					tiers_payant_2_id, 
					matricule_2, 
					tiers_payant_22_id, 
					matricule_22)
				SELECT
					oid AS sejour_id,
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					NUM_SECU,
					p_sejours.tiers_payant_2_id, 
					'',
					p_sejours.tiers_payant_22_id, 
					''::text AS matricule_22
				FROM w_ASSURES
					JOIN activite.p_sejours ON code_original = NUM_PAT AND p_sejours.etat = '';
					
				
				
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_1');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_2');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_3');
				SELECT base.cti_enable_index('activite[PX]', 'i_sejours_assurance_4');
				
				
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Mouvements">
			<sqlcmd><![CDATA[
		
				DROP TABLE IF EXISTS w_mouvements_sejour;
				CREATE TEMP TABLE w_mouvements_sejour AS
				SELECT 
					w_ASSURES.NUM_PAT AS no_sejour,
					p_sejours.oid AS sejour_id,
					p_calendrier.date, 
					p_calendrier.jour_semaine,
					p_calendrier.is_weekend,
					080000::numeric AS heure_debut,
					180000::numeric AS heure_fin,
					0::numeric AS nb_entrees_directes,
					0::numeric AS nb_sorties_directes,
					0::numeric AS est_jour_entree,
					0::numeric AS est_jour_sortie,
					'0'::text AS est_jour_hospitalisation,
					0::numeric AS nb_ambulatoires,
					0::numeric AS nb_externes,
					0::numeric AS nb_urgences,
					1::numeric AS nb_seances,

					0::numeric AS nb_entrees_mutation_service,
					0::numeric AS nb_sorties_mutation_service,
					0::numeric AS nb_entrees_mutation_etage,
					0::numeric AS nb_sorties_mutation_etage,
					0::numeric AS nb_entrees_mutation_activite,
					0::numeric AS nb_sorties_mutation_activite,
					0::numeric AS nb_entrees_mutation_unite_medicale,
					0::numeric AS nb_sorties_mutation_unite_medicale,

					0::numeric AS nb_jours_js_inclus,
					0::numeric AS nb_jours_js_non_inclus,

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

					0::numeric AS nb_bebes,
                    
					w_LIGNES_FACTURES.service_facturation_code_original,
					w_LIGNES_FACTURES.unite_fonctionnelle_code_original,
					w_LIGNES_FACTURES.unite_fonctionnelle_code_original AS unite_medicale_code_original,
                    
					COALESCE(t_lieux.oid,0) AS lieu_id,

					p_sejours.medecin_sejour_id as medecin_sejour_id,

					'0'::text AS est_mouvement_previsionnel,

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

					
				FROM w_ASSURES
				JOIN w_FACTURES ON w_FACTURES.NUM_PAT = w_ASSURES.NUM_PAT
				JOIN w_LIGNES_FACTURES ON w_LIGNES_FACTURES.NUM_FACT = w_FACTURES.NUM_FACT
				LEFT JOIN activite.t_lieux ON 
					t_lieux.code_original_1 = w_LIGNES_FACTURES.service_facturation_code_original AND 
					t_lieux.code_original_2 = '' AND
					t_lieux.code_original_4 = '' AND
					t_lieux.code_original_5 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original AND
					t_lieux.code_original_6 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original
				JOIN activite.p_sejours ON w_ASSURES.NUM_PAT = p_sejours.no_sejour AND p_sejours.etat = ''
				JOIN base.p_calendrier ON p_calendrier.date BETWEEN date(w_LIGNES_FACTURES.SEJOUR_DU) AND date(w_LIGNES_FACTURES.SEJOUR_AU)  AND p_calendrier.date <= date(now())
				WHERE w_ASSURES.OK = 'O' AND
					w_FACTURES.AVOIR = 'false' AND
					w_LIGNES_FACTURES.HONO_SEJ = 'false' AND
					w_LIGNES_FACTURES.PRESTATION LIKE 'D%' AND
					w_LIGNES_FACTURES.PRESTATION NOT LIKE 'DTP'
				ORDER BY w_ASSURES.NUM_PAT, p_calendrier.date
				;



				-- Actualisation lieux
				UPDATE activite.t_lieux SET
					service_facturation_id = t_services_facturation.oid,
					mode_traitement_id = t_services_facturation.mode_traitement_id
				FROM activite.t_services_facturation
				WHERE 
					code_original_1 = t_services_facturation.code_original;
	
				UPDATE activite.t_lieux SET
					unite_medicale_id = t_unites_medicales.oid
				FROM activite.t_unites_medicales
				WHERE 
					code_original_5 = t_unites_medicales.code_original;
					
				UPDATE activite.t_lieux SET
					unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				FROM activite.t_unites_fonctionnelles
				WHERE 
					code_original_6 = t_unites_fonctionnelles.code_original;
					
				
	


				-- creation nouveaux lieux

				INSERT INTO activite.t_lieux(
					code_original_1, 
					code_original_2, 
					code_original_3, 
					code_original_4, 
					code_original_5, 
					code_original_6, 
					code_original_7,
					service_facturation_id, 
					activite_id, 
					lit_id, 
					unite_medicale_id, 
					unite_fonctionnelle_id, 
					mode_traitement_id)
				SELECT DISTINCT 
					service_facturation_code_original, 
					'',
					'',
					'',
					unite_fonctionnelle_code_original,
					unite_fonctionnelle_code_original,
					'',
					t_services_facturation.oid,
					0,
					0,
					COALESCE(t_unites_medicales.oid,0),
					COALESCE(t_unites_fonctionnelles.oid,0),
					t_services_facturation.mode_traitement_id
				FROM w_mouvements_sejour 
                   LEFT JOIN activite.t_lieux ON 
						t_lieux.code_original_1 = service_facturation_code_original AND 
						t_lieux.code_original_2 = ''::text AND 
						t_lieux.code_original_4 = ''::text AND
						t_lieux.code_original_5 = unite_fonctionnelle_code_original AND
						t_lieux.code_original_6 = unite_fonctionnelle_code_original
					JOIN activite.t_services_facturation ON service_facturation_code_original::text = t_services_facturation.code_original
                    LEFT JOIN activite.t_unites_medicales ON unite_fonctionnelle_code_original = t_unites_medicales.code_original
                   
					LEFT JOIN activite.t_unites_fonctionnelles ON unite_fonctionnelle_code_original = t_unites_fonctionnelles.code_original
				WHERE t_lieux.oid IS NULL;



				UPDATE w_mouvements_sejour SET lieu_id = t_lieux.oid
				FROM activite.t_lieux
				WHERE
                        t_lieux.code_original_1 = service_facturation_code_original AND 
						t_lieux.code_original_2 = ''::text AND 
						t_lieux.code_original_4 = ''::text AND
						t_lieux.code_original_5 = unite_fonctionnelle_code_original AND
						t_lieux.code_original_6 = unite_fonctionnelle_code_original
					AND w_mouvements_sejour.lieu_id = 0;

				-- plusieurs séances le même jour
				UPDATE w_mouvements_sejour SET
					heure_debut = CASE WHEN w_mouvements_sejour.CTID = fromCTID2 THEN 140000 ELSE w_mouvements_sejour.heure_debut END,
					heure_fin = CASE WHEN w_mouvements_sejour.CTID = fromCTID1 THEN 135959 ELSE w_mouvements_sejour.heure_fin END
				FROM
				(
				SELECT 				
					no_sejour, date, heure_debut, 
						MIN(CTID) AS fromCTID1,
						MAX(CTID) AS fromCTID2, count(*)
				FROM w_mouvements_sejour
				GROUP BY 1,2,3
				HAVING count(*) > 1
				) subview
				WHERE w_mouvements_sejour.no_sejour = subview.no_sejour AND
					w_mouvements_sejour.date = subview.date AND
					w_mouvements_sejour.heure_debut = subview.heure_debut
				;
				
				DELETE FROM w_mouvements_sejour
				USING (
				SELECT 				
					no_sejour, date, heure_debut, MAX(CTID) AS fromCTID
				FROM w_mouvements_sejour
				GROUP BY 1,2,3
				HAVING count(*) > 1) subview
				WHERE 1=1
					AND subview.no_sejour = w_mouvements_sejour.no_sejour
					AND subview.date = w_mouvements_sejour.date
					AND subview.heure_debut = w_mouvements_sejour.heure_debut
					AND subview.fromCTID != w_mouvements_sejour.CTID;



				-- Mise en production des mouvements
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_1');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_2');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_3');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_4');
				SELECT base.cti_disable_index('activite', 'i_mouvements_sejour_5');
				
                
				INSERT INTO activite.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;
				
				
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_1');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_2');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_3');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_4');
				SELECT base.cti_enable_index('activite', 'i_mouvements_sejour_5');
				
				ANALYSE activite.p_mouvements_sejour
				;
				
				-- Ajout des séances non rapportées par la facturation selon la présence par jour des 28 derniers jours
				DROP TABLE IF EXISTS w_sejours_seances;
				CREATE TEMP TABLE w_sejours_seances AS 
				SELECT p_mouvements_sejour.no_sejour,
					date_part('dow',date) AS jour_semaine,
					(MAX(ARRAY[date::text,lieu_id::text]))[2]::bigint AS lieu_id,
					date(MAX(date_max + interval '1 day')) AS date_first, count(*), max(date_max)
				FROM activite.p_mouvements_sejour
				JOIN (
				SELECT p_mouvements_sejour.no_sejour, MAX(date) AS date_max
				FROM activite.p_mouvements_sejour
				JOIN activite.p_sejours ON p_mouvements_sejour.no_sejour = p_sejours.no_sejour
				WHERE nb_seances > 0 AND code_sorti = 0
				GROUP BY 1
				) subview ON
					p_mouvements_sejour.no_sejour = subview.no_sejour AND
					p_mouvements_sejour.date > date(date_max - interval '28 days')
				WHERE nb_seances > 0
				GROUP BY 1,2
				HAVING count(*) >= 3
				ORDER BY 1,2,3
				;

				ANALYSE w_sejours_seances
				; 

				UPDATE w_sejours_seances
				SET jour_semaine = 7
				WHERE jour_semaine = 0
				;
				
				INSERT INTO activite.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 p_sejours.oid AS sejour_id, 
					w_sejours_seances.no_sejour, 
					p_calendrier.date, 
					'0' AS est_mouvement_previsionnel ,
					0 AS nb_jours_js_non_inclus, 
					w_sejours_seances.lieu_id, 
					0 AS nb_entrees_directes, 
					0 AS nb_sorties_directes, 
					0 AS nb_urgences, 
					0 AS nb_externes, 
					0 AS nb_ambulatoires, 
					p_sejours.medecin_sejour_id, 
					0 AS nb_jours_js_inclus, 
					1 AS nb_seances, 
					0 AS nb_entrees_mutation_service, 
					0 AS nb_sorties_mutation_service, 
					0 AS nb_entrees_mutation_activite, 
					0 AS nb_sorties_mutation_activite, 
					0 AS nb_entrees_mutation_etage, 
					0 AS nb_sorties_mutation_etage, 
					0 AS nb_chambres_particulieres, 
					080000 AS heure_debut, 
					180000 AS heure_fin, 
					'0' AS est_jour_entree, 
					'0' AS est_jour_sortie, 
					'0' AS est_jour_hospitalisation, 
					'0' AS est_chambre_particuliere, 
					0 AS nb_entrees_mutation_unite_medicale, 
					0 AS nb_sorties_mutation_unite_medicale, 
					0 AS nb_bebes,
					p_calendrier.jour_semaine, 
					p_calendrier.is_weekend
				FROM w_sejours_seances
				JOIN activite.p_sejours ON w_sejours_seances.no_sejour = p_sejours.no_sejour
				JOIN base.p_calendrier ON 
					p_calendrier.date BETWEEN date_first AND date(now()) AND
					p_calendrier.jour_semaine = w_sejours_seances.jour_semaine
				;
	
				-- Lieux de sortie

				UPDATE activite.p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite.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.p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite.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.p_sejours SET lieu_sortie_id = p_mouvements_sejour.lieu_id  
					FROM activite.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.p_sejours SET lieu_sortie_id = 0
					WHERE lieu_sortie_id IS NULL ;
				
				
				UPDATE activite.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);
					
										
										
			]]></sqlcmd>
		</NODE>
		
	</NODE>

	<NODE name="FACTURE" label="RECUPERATION DES FACTURES">
	
		<NODE label="Entêtes">

			<sqlcmd><![CDATA[

                
				-- 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.p_factures(
					sejour_id,
					no_sejour, 
					no_facture, 
					date_debut, 
					date_fin, 
					type_facture, 
					code_facture, 
					date_facture, 
					code_vente, 
					date_vente, 
					mois_vente, 
					date_solde, 
					montant_facture_c, 
					montant_facture_h, 
					montant_regle_c, 
					montant_regle_h, 
					delai_facture, 
					delai_solde, 
					date_expedition, 
					delai_expedition, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					date_solde_0_c, 
					date_solde_0_h, 
					date_solde_1_c, 
					date_solde_1_h, 
					date_solde_2_c, 
					date_solde_2_h, 
					date_solde_22_c, 
					date_solde_22_h, 
					date_expedition_0, 
					date_expedition_1, 
					date_expedition_2, 
					date_expedition_22, 
					code_expedie_0, 
					code_expedie_1, 
					code_expedie_2, 
					code_expedie_22, 
					no_bordereau_0, 
					no_bordereau_1, 
					no_bordereau_2, 
					no_bordereau_22, 
					montant_facture_0_c,
					montant_facture_0_h, 
					montant_facture_1_c, 
					montant_facture_1_h, 
					montant_facture_2_c, 
					montant_facture_2_h, 
					montant_facture_22_c, 
					montant_facture_22_h, 
					montant_regle_0_c, 
					montant_regle_0_h, 
					montant_regle_1_c, 
					montant_regle_1_h, 
					montant_regle_2_c, 
					montant_regle_2_h, 
					montant_regle_22_c, 
					montant_regle_22_h, 
					delai_expedition_0, 
					delai_expedition_1, 
					delai_expedition_2, 
					delai_expedition_22, 
					delai_solde_0_c, 
					delai_solde_0_h, 
					delai_solde_1_c, 
					delai_solde_1_h, 
					delai_solde_2_c, 
					delai_solde_2_h, 
					delai_solde_22_c, 
					delai_solde_22_h, 
					ghs_id, 
					particularite_t2a, 
					code_cloture, 
					code_cp_demandee, 
					ghs_bebe1_id, 
					ghs_bebe2_id, 
					ghs_bebe3_id,
					
					montant_comptabilise_c, 
					montant_comptabilise_h, 
					montant_comptabilise_0_c,
					montant_comptabilise_0_h, 
					montant_comptabilise_1_c, 
					montant_comptabilise_1_h, 
					montant_comptabilise_2_c, 
					montant_comptabilise_2_h, 
					montant_comptabilise_22_c, 
					montant_comptabilise_22_h, 
					
					nb_rejets,
					
					montant_facture_c_actes_inclus_dans_sejour,
					montant_facture_h_actes_inclus_dans_sejour
					)
				SELECT
					p_sejours.oid AS sejour_id,
					p_sejours.no_sejour,
					w_FACTURES.NUM_FACT AS no_facture,
					SEJOUR_DU_D AS date_debut,
					SEJOUR_AU_D AS date_fin,
					'0'::text AS type_facture,
					'1'::text AS code_facture,
					w_FACTURES.date_vente AS date_facture,
					'1'::text AS code_vente,
					w_FACTURES.date_vente,
					to_char(w_FACTURES.date_vente,'YYYYMM')::numeric AS mois_vente,

					DATE_REGLE AS date_solde,

						
					TT_SEJ AS montant_facture_c,
					TT_HONO AS montant_facture_h,
					TR_SEJ AS montant_regle_c,
					TR_HON AS montant_regle_h,
					0::numeric AS delai_facture, 
					0::numeric AS delai_solde, 
					date(DATE_TRANSMIS) as date_expedition, 
					0::numeric AS delai_expedition, 
					p_sejours.tiers_payant_0_id,
					COALESCE(t_tiers_payant_1.oid,p_sejours.tiers_payant_1_id,0) AS tiers_payant_1_id,
					COALESCE(t_tiers_payant_2.oid,p_sejours.tiers_payant_2_id,0) AS tiers_payant_2_id,
					0::bigint AS tiers_payant_22_id,	
					DATE_REGLE AS date_solde_0_c,
					DATE_REGLE AS date_solde_0_h,
					DATE_REGLE AS date_solde_1_c,
					DATE_REGLE AS date_solde_1_h,	
					DATE_REGLE AS date_solde_2_c,
					DATE_REGLE AS date_solde_2_h,	
					DATE_REGLE AS date_solde_22_c,
					DATE_REGLE AS date_solde_22_h,	

					date(DATE_TRANSMIS) AS date_expedition_0,
					date(DATE_TRANSMIS) AS date_expedition_1,
					date(DATE_TRANSMIS) AS date_expedition_2,
					date(DATE_TRANSMIS) AS date_expedition_22,
					'1'::text AS code_expedie_0,
					'1'::text AS code_expedie_1,
					'1'::text AS code_expedie_2,
					'1'::text AS code_expedie_22,
					NUM_BORDEREAU AS no_bordereau_0,
					NUM_BORDEREAU AS no_bordereau_1,
					NUM_BORDEREAU AS no_bordereau_2,
					NUM_BORDEREAU AS no_bordereau_22,

					TT_SEJ_PAT AS montant_facture_0_c,
					TT_HON_PAT AS montant_facture_0_h,
					TT_SEJ_AMO AS montant_facture_1_c,
					TT_HON_AMO AS montant_facture_1_h,
					TT_SEJ_AMC AS montant_facture_2_c,
					TT_HON_AMC AS montant_facture_2_h,
					0::numeric AS montant_facture_22_c,
					0::numeric AS montant_facture_22_h,

					TR_SEJ_PAT AS montant_regle_0_c,
					TR_HON_PAT AS montant_regle_0_h,
					TR_SEJ_AMO AS montant_regle_1_c,
					TR_HON_AMO AS montant_regle_1_h,
					TR_SEJ_AMC AS montant_regle_2_c,
					TR_HON_AMC AS montant_regle_2_h,
					0::numeric AS montant_regle_22_c,
					0::numeric AS montant_regle_22_h,


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

					p_sejours.ghs_id,
					'' as particularite_t2a, 

					'0' as code_cloture,
					'0' as code_cp_demandee, 
					0 AS ghs_bebe1_id, 
					0 AS ghs_bebe2_id, 
					0 AS ghs_bebe3_id,
					
					TT_SEJ AS montant_comptabilise_c, 
					TC_HON AS montant_comptabilise_h, 
					TT_SEJ_PAT AS montant_comptabilise_0_c,
					TC_HON_PAT AS montant_comptabilise_0_h,
					TT_SEJ_AMO AS montant_comptabilise_1_c,
					TC_HON_AMO AS montant_comptabilise_1_h,
					TT_SEJ_AMC AS montant_comptabilise_2_c,
					TC_HON_AMC AS montant_comptabilise_2_h,
					0::numeric AS montant_comptabilise_22_c,
					0::numeric AS montant_comptabilise_22_h,
					
					0::numeric AS nb_rejets,
					
					0,
					0


				FROM w_FACTURES
				JOIN activite.p_sejours ON NUM_PAT = no_sejour
					LEFT JOIN activite.t_tiers_payant t_tiers_payant_1 ON NUM_CAISSE = t_tiers_payant_1.code_original
					LEFT JOIN activite.t_tiers_payant t_tiers_payant_2 ON NUM_MUTUELLE::text || 'M' = t_tiers_payant_2.code_original
				ORDER BY 1,2
				;
				
				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');
				
				ANALYSE activite.p_factures
				;
				
				-- Séjours sans facture
				
				DROP TABLE IF EXISTS w_factures_trous;
				CREATE TEMP TABLE w_factures_trous AS
				SELECT
					p_sejours.finess,
					p_sejours.no_sejour,
					p_sejours.date_entree,
					p_sejours.tiers_payant_0_id, 
					p_sejours.tiers_payant_1_id, 
					p_sejours.tiers_payant_2_id, 
					p_sejours.tiers_payant_22_id,
					p_sejours.code_cp_demandee,
					p_sejours.ghs_id,
					COALESCE(t_services_facturation.avec_facturation_intermediaire,'') AS avec_facturation_intermediaire,
					p_sejours.code_sorti,
					CASE WHEN code_sorti = 1 THEN date_sortie ELSE date(now()) END AS date_sortie,
					CASE WHEN code_sorti = 1 THEN date_sortie ELSE date(now()) END AS date_fin_encours,
					MAX(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END) AS date_fin_facture,
					date(MAX(COALESCE(CASE WHEN p_factures.date_fin IS NOT NULL AND date_sortie - date_entree < 30 THEN date_sortie ELSE p_factures.date_fin END + interval '1 day', p_sejours.date_entree))) AS date_debut_encours
				FROM activite[PX].p_sejours
					LEFT JOIN activite[PX].p_factures ON p_sejours.no_sejour = p_factures.no_sejour AND no_facture NOT LIKE 'E%' AND type_facture IS DISTINCT FROM 'P'
					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,13;


				INSERT INTO activite[PX].p_factures(
					finess, 
					no_sejour, 
					no_facture, 
					no_facture_reference, 
					type_facture, 
					code_facture, 
					date_facture, 
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id,
					code_cp_demandee, 
					ghs_id,
					date_debut, 
					date_fin)
				SELECT finess, 
					no_sejour, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E' || no_sejour || CASE WHEN avec_facturation_intermediaire = '1' THEN '_' || substr(p_calendrier.mois,3,4) ELSE '' END, 
					'E', 
					'0', 
					'20991231'::date,
					tiers_payant_0_id, 
					tiers_payant_1_id, 
					tiers_payant_2_id, 
					tiers_payant_22_id, 
					code_cp_demandee , 
					ghs_id,
					MIN(GREATEST(date_debut_encours, p_calendrier.date)), 
					MAX(LEAST(date_fin_encours, p_calendrier.date, CASE WHEN avec_facturation_intermediaire = '1' THEN date(date_trunc('month',p_calendrier.date) + interval '1 month' - interval '1 day') ELSE NULL END))
				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
                HAVING MIN(GREATEST(date_debut_encours, p_calendrier.date)) >= '[ENV_ADM_ANNEEDEBUT]0101'
                ;

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

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

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

				INSERT INTO activite.p_factures_lignes_c(
					no_facture, 
					facture_id,
					date_debut, 
					date_fin, 
					nb_rubrique, 
					nb_prestation, 
					coefficient, 
					coefficient_mco, 
					rubrique_facturation_id, 
					rubrique_comptabilisation_id, 
					compte_produit_id, 
					prestation_id, 
					montant_facture, 
					montant_facture_0, 
					montant_facture_1, 
					montant_facture_2, 
					montant_facture_22, 
					taux_0, 
					taux_1, 
					taux_2, 
					taux_22, 
					prix_unitaire, 
					lieu_id, 
					
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2,
					montant_comptabilise_22, 
					
					montant_encours, 
					montant_encours_0, 
					montant_encours_1, 
					montant_encours_2, 
					montant_encours_22,

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

				SELECT 
					NUM_FACT::text AS no_facture, 
					p_factures.oid AS facture_id,
					w_LIGNES_FACTURES.SEJOUR_DU AS date_debut, 
					w_LIGNES_FACTURES.SEJOUR_AU AS date_fin, 
					w_LIGNES_FACTURES.QUANTITE * w_LIGNES_FACTURES.COEF AS nb_rubrique, 
					w_LIGNES_FACTURES.QUANTITE * w_LIGNES_FACTURES.COEF AS nb_prestations, 
					1::numeric AS coefficient, 
					CASE WHEN PRIX_UNIT_NATIONAL > 0 THEN PRIX_UNIT / PRIX_UNIT_NATIONAL ELSE 1 END AS coefficient_mco, 
					COALESCE(W_RUBRIQUE_FACTUR_source.rubrique_facturation_id,0) AS rubrique_facturation_id, 
					COALESCE(W_RUBRIQUE_FACTUR_source.rubrique_facturation_id,0) AS rubrique_comptabilisation_id, 
					COALESCE(W_RUBRIQUE_FACTUR_source.compte_produit_id,0) AS compte_produit_id, 
					COALESCE(W_RUBRIQUE_FACTUR_source.prestation_id,0) AS prestation_id, 
					MT_FACT AS montant_facture, 
					PART_ASS AS montant_facture_0, 
					PART_CAISSE AS montant_facture_1, 
					PART_MUT AS montant_facture_2, 
					0::numeric AS montant_facture_22, 
					round(base.cti_division(PART_ASS,MT_FACT)*100.0,0) AS taux_0, 
					round(base.cti_division(PART_CAISSE,MT_FACT)*100.0,0) AS taux_1, 
					round(base.cti_division(PART_MUT,MT_FACT)*100.0,0) AS taux_2, 
					0::numeric AS taux_22, 
					CASE WHEN PRIX_UNIT_NATIONAL > 0 THEN PRIX_UNIT_NATIONAL ELSE PRIX_UNIT END AS prix_unitaire, 
					COALESCE(t_lieux.oid,0) AS lieu_id,
					
					MT_FACT AS montant_comptabilise, 
					PART_ASS AS montant_comptabilise_0, 
					PART_CAISSE AS montant_comptabilise_1, 
					PART_MUT AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
					
					0, 
					0, 
					0, 
					0, 
					0,

					1::integer AS origine_facturation_id,
					0::numeric AS montant_facture_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_0_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_1_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_2_actes_inclus_dans_sejour, 
					0::numeric AS montant_facture_22_actes_inclus_dans_sejour

				FROM w_LIGNES_FACTURES
				JOIN activite.p_factures ON w_LIGNES_FACTURES.NUM_FACT = p_factures.no_facture
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN w_RUBRIQUE_FACTUR_source ON w_RUBRIQUE_FACTUR_source.NUM_ACTE = w_LIGNES_FACTURES.NUM_ACTE
				LEFT JOIN activite.t_lieux ON 
					t_lieux.code_original_1 = w_LIGNES_FACTURES.service_facturation_code_original AND 
					t_lieux.code_original_2 = '' AND
					t_lieux.code_original_4 = '' AND
					t_lieux.code_original_5 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original AND
					t_lieux.code_original_6 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original
				WHERE w_LIGNES_FACTURES.HONO_SEJ = 'false'
				;
				
				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');
				
				ANALYSE activite.p_factures_lignes_c
				;
	
				
				SELECT activite[PX].cti_reorganize_rubrique_facture_c('activite.p_factures_lignes_c');

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

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

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

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup;

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

				DROP TABLE IF EXISTS w_factures_lignes_sup_c_sup_tot;

				CREATE TEMP TABLE w_factures_lignes_sup_c_sup_tot AS

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


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

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

	
				DROP TABLE IF EXISTS w_mouvements_sejour_lieu_jour;
                CREATE TEMP TABLE w_mouvements_sejour_lieu_jour AS
                SELECT no_sejour, 
                    date,
                    (MAX(CASE WHEN est_absence <> '1' THEN Array[heure_fin, lieu_id] ELSE NULL END))[2] AS lieu_id,
                    (MAX(Array[heure_fin, lieu_id]))[2] AS lieu_id_avec_absence
                FROM activite[PX].p_mouvements_sejour
                JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
                GROUP BY 1,2
                ;

                UPDATE activite[PX].p_factures_lignes_c 
				SET lieu_id = COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
				FROM activite[PX].p_factures, w_mouvements_sejour_lieu_jour
				WHERE p_factures_lignes_c.no_facture = p_factures.no_facture AND
					p_factures.no_sejour = w_mouvements_sejour_lieu_jour.no_sejour AND
					p_factures_lignes_c.date_debut = w_mouvements_sejour_lieu_jour.date AND
					p_factures_lignes_c.lieu_id = 0
                ;

                
		

				
			]]></sqlcmd>
		</NODE>	
		
		<NODE label="Lignes non facturées Clinique">
			<sqlcmd><![CDATA[
			
				TRUNCATE activite[PX].p_factures_lignes_non_facturees_c;
				
                DROP TABLE IF EXISTS w_prestations_jour;
				CREATE TEMP TABLE w_prestations_jour AS 
				SELECT p_factures.no_sejour,
					rubrique_facturation_id, 
					prestation_id, 
					t_prestations.code AS prestation_code,
					date_part('dow',p_factures_lignes_c.date_fin) AS jour_semaine,
					(MAX(ARRAY[p_factures_lignes_c.date_fin::text,lieu_id::text]))[2]::bigint AS lieu_id,
					date(MAX(date_max + interval '1 day')) AS date_first, 
					(MAX(ARRAY[p_factures_lignes_c.date_fin::text,prix_unitaire::text]))[2]::numeric AS prix_unitaire
				FROM w_periode, activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				JOIN (
				SELECT p_factures.no_sejour, MAX(p_factures_lignes_c.date_fin) AS date_max
				FROM w_periode, activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures.no_facture = p_factures_lignes_c.no_facture
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE montant_facture > 0 AND code_sorti = 0 AND
					t_prestations.code <> 'GHS' AND
					t_prestations.code NOT LIKE 'D%' AND
					p_factures_lignes_c.date_fin > date(date_extraction - interval '56 days')
				GROUP BY 1
				) subview ON
					p_factures.no_sejour = subview.no_sejour AND
					p_factures_lignes_c.date_fin > date(date_max - interval '28 days')
				WHERE montant_facture > 0 AND
					t_prestations.code <> 'GHS' AND
					t_prestations.code NOT LIKE 'D%'
				GROUP BY 1,2,3,4,5
				HAVING count(*) >= 3
				ORDER BY 6,1,2,3
				;

				ANALYSE w_prestations_jour
				; 


				INSERT INTO activite.p_factures_lignes_non_facturees_c(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id)
				SELECT
					p_factures.no_facture,
					p_calendrier.date AS date_debut,
					p_calendrier.date AS date_fin,
					1::numeric AS nb_rubrique,
					1::numeric AS coefficient,
					w_prestations_jour.rubrique_facturation_id,
					w_prestations_jour.prestation_id,
					w_prestations_jour.prix_unitaire,
					w_prestations_jour.lieu_id
				FROM w_prestations_jour
				JOIN base.p_calendrier ON 
					p_calendrier.date BETWEEN date_first AND date(now()) AND
					p_calendrier.jour_semaine = w_prestations_jour.jour_semaine
				JOIN activite.p_factures ON
					p_factures.no_sejour = w_prestations_jour.no_sejour AND
					p_factures.type_facture = 'E' AND
					p_calendrier.date BETWEEN p_factures.date_debut AND p_factures.date_fin
				;
				
										
										
			]]></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.p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					p_factures.date_vente,
					p_factures_lignes_c.rubrique_comptabilisation_id,
					p_factures_lignes_c.prestation_id,
					SUM(p_factures_lignes_c.montant_comptabilise),
					SUM(p_factures_lignes_c.montant_comptabilise_0),
					SUM(p_factures_lignes_c.montant_comptabilise_1),
					SUM(p_factures_lignes_c.montant_comptabilise_2),
					SUM(p_factures_lignes_c.montant_comptabilise_22),
					0,
					0,
					0,
					0,
					0
				FROM activite.p_factures_lignes_c
				JOIN activite.p_factures ON p_factures_lignes_c.no_facture = p_factures.no_facture
				WHERE p_factures.date_vente <> '20991231' AND 
					(
					p_factures_lignes_c.montant_comptabilise <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_0 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_1 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_2 <> 0 OR 
					p_factures_lignes_c.montant_comptabilise_22 <> 0 
					)
				GROUP BY 1,2,3,4
				;
	
	
	
				-- Comptes clients (REG)
				INSERT INTO activite.p_factures_soldes_c(
					no_facture, 
					date_comptable, 
					rubrique_comptabilisee_id, 
					prestation_id, 
					montant_comptabilise, 
					montant_comptabilise_0, 
					montant_comptabilise_1, 
					montant_comptabilise_2, 
					montant_comptabilise_22, 
					montant_regle, 
					montant_regle_0, 
					montant_regle_1, 
					montant_regle_2, 
					montant_regle_22
				)
				SELECT
					p_factures.no_facture,
					w_REGLEMENTS.DATE_REGLE,
					COALESCE(w_RUBRIQUE_FACTUR_source.rubrique_facturation_id,0),
					COALESCE(w_RUBRIQUE_FACTUR_source.prestation_id,0),
					0,
					0,
					0,
					0,
					0,
					SUM(w_REGLEMENTS.MTTOTAL) AS montant_regle,
					SUM(w_REGLEMENTS.MTASS) AS montant_regle_0,
					SUM(w_REGLEMENTS.MTCAISS) AS montant_regle_1,
					SUM(w_REGLEMENTS.MTMUT) AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_REGLEMENTS
				JOIN activite.p_factures ON w_REGLEMENTS.NUMFACT = p_factures.no_facture
				LEFT JOIN w_RUBRIQUE_FACTUR_source ON w_REGLEMENTS.NUM_ACTE = w_RUBRIQUE_FACTUR_source.NUM_ACTE
				WHERE DATE_REGLE IS NOT NULL AND 
					w_REGLEMENTS.HONO_SEJ = 'false'
				GROUP BY 1,2,3,4
				;

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

				ANALYSE activite.p_factures_soldes_c
				;				
                                        
            ]]></sqlcmd>
        </NODE>
    
        
        <NODE label="Lignes factures Honoraires">
            <sqlcmd><![CDATA[
     
                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.p_factures_lignes_h(
                    no_facture, 
                    facture_id,
                    date_debut, 
                    date_fin, 
                    nb_rubrique, 
                    nb_prestation, 
                    coefficient, 
                    coefficient_mco, 
                    medecin_facture_id, 
                    medecin_comptabilise_id, 
                    rubrique_facturation_id,
                    prestation_id, 
                    montant_facture, 
                    montant_facture_0, 
                    montant_facture_1, 
                    montant_facture_2, 
                    montant_facture_22, 
                    montant_depassement,
                    taux_0, 
                    taux_1, 
                    taux_2, 
                    taux_22, 
                    prix_unitaire, 
                    lieu_id, 
                    
                    montant_comptabilise, 
                    montant_comptabilise_0, 
                    montant_comptabilise_1, 
                    montant_comptabilise_2,
                    montant_comptabilise_22, 
                    
                    montant_encours, 
                    montant_encours_0, 
                    montant_encours_1, 
                    montant_encours_2, 
                    montant_encours_22,

                    montant_facture_actes_inclus_dans_sejour, 
                    montant_facture_0_actes_inclus_dans_sejour, 
                    montant_facture_1_actes_inclus_dans_sejour, 
                    montant_facture_2_actes_inclus_dans_sejour, 
                    montant_facture_22_actes_inclus_dans_sejour,

                    acte_id
                    )

                SELECT 
                    NUM_FACT::text AS no_facture, 
					p_factures.oid AS facture_id,
                    w_LIGNES_FACTURES.SEJOUR_DU AS date_debut, 
					w_LIGNES_FACTURES.SEJOUR_AU AS date_fin, 
                    w_LIGNES_FACTURES.QUANTITE AS nb_rubrique, 
                    w_LIGNES_FACTURES.QUANTITE AS nb_prestations, 
                    w_LIGNES_FACTURES.COEF AS coefficient, 
                    CASE WHEN PRIX_UNIT_NATIONAL > 0 THEN PRIX_UNIT / PRIX_UNIT_NATIONAL ELSE 1 END AS coefficient_mco, 
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_facture_id, 
                    COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id, 
                    COALESCE(W_RUBRIQUE_FACTUR_source.rubrique_facturation_id,0) AS rubrique_facturation_id, 
                    COALESCE(W_RUBRIQUE_FACTUR_source.prestation_id,0) AS prestation_id,
                    MT_FACT AS montant_facture, 
					PART_ASS AS montant_facture_0, 
					PART_CAISSE AS montant_facture_1, 
					PART_MUT AS montant_facture_2, 
					0::numeric AS montant_facture_22,
                    CASE WHEN MT_FACT = (PRIX_UNIT*COEF) + DEPASS THEN DEPASS ELSE 0 END AS montant_depassement,
                    round(base.cti_division(PART_ASS,MT_FACT)*100.0,0) AS taux_0, 
					round(base.cti_division(PART_CAISSE,MT_FACT)*100.0,0) AS taux_1, 
					round(base.cti_division(PART_MUT,MT_FACT)*100.0,0) AS taux_2, 
					0::numeric AS taux_22,
                    CASE WHEN PRIX_UNIT_NATIONAL > 0 THEN PRIX_UNIT_NATIONAL ELSE PRIX_UNIT END AS prix_unitaire, 
                    COALESCE(t_lieux.oid,0) AS lieu_id,
                    
                    LC_HON AS montant_comptabilise, 
					LC_HON_PAT AS montant_comptabilise_0, 
					LC_HON_AMO AS montant_comptabilise_1, 
					LC_HON_AMC AS montant_comptabilise_2, 
					0::numeric AS montant_comptabilise_22, 
                    
                    0, 
                    0, 
                    0, 
                    0, 
                    0,

                    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,

                    COALESCE(w_RUBRIQUE_FACTUR_source.acte_id,0) AS acte_id

                FROM w_LIGNES_FACTURES
				JOIN activite.p_factures ON w_LIGNES_FACTURES.NUM_FACT = p_factures.no_facture
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				LEFT JOIN w_RUBRIQUE_FACTUR_source ON w_RUBRIQUE_FACTUR_source.NUM_ACTE = w_LIGNES_FACTURES.NUM_ACTE
				LEFT JOIN activite.t_medecins_administratifs ON medecin_executant_code_original = t_medecins_administratifs.code_original
				LEFT JOIN activite.t_lieux ON 
					t_lieux.code_original_1 = w_LIGNES_FACTURES.service_facturation_code_original AND 
					t_lieux.code_original_2 = '' AND
					t_lieux.code_original_4 = '' AND
					t_lieux.code_original_5 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original AND
					t_lieux.code_original_6 = w_LIGNES_FACTURES.unite_fonctionnelle_code_original
				WHERE w_LIGNES_FACTURES.HONO_SEJ = 'true'
				;

    
                DROP TABLE IF EXISTS w_mouvements_sejour_lieu_jour;
                CREATE TEMP TABLE w_mouvements_sejour_lieu_jour AS
                SELECT no_sejour, 
                    date,
                    (MAX(CASE WHEN est_absence <> '1' THEN Array[heure_fin, lieu_id] ELSE NULL END))[2] AS lieu_id,
                    (MAX(Array[heure_fin, lieu_id]))[2] AS lieu_id_avec_absence
                FROM activite[PX].p_mouvements_sejour
                JOIN activite[PX].t_lieux ON lieu_id = t_lieux.oid
                JOIN activite[PX].t_services_facturation On service_facturation_id = t_services_facturation.oid
                GROUP BY 1,2;


                UPDATE activite[PX].p_factures_lignes_h 
                SET lieu_id = COALESCE(w_mouvements_sejour_lieu_jour.lieu_id,w_mouvements_sejour_lieu_jour.lieu_id_avec_absence)
                FROM activite[PX].p_factures, w_mouvements_sejour_lieu_jour
                WHERE p_factures_lignes_h.no_facture = p_factures.no_facture AND
                    p_factures.no_sejour = w_mouvements_sejour_lieu_jour.no_sejour AND
                    p_factures_lignes_h.date_debut = w_mouvements_sejour_lieu_jour.date AND
                    p_factures_lignes_h.lieu_id = 0;


                
                    
                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');
				
				ANALYSE activite.p_factures_lignes_h
				;
                
                                        
            ]]></sqlcmd>
        </NODE>
		
		<NODE label="Lignes non facturées Honoraires">
            <sqlcmd><![CDATA[
			
				TRUNCATE activite.p_factures_lignes_non_facturees_h
				;

                DROP TABLE IF EXISTS w_actes_jour;
				CREATE TEMP TABLE w_actes_jour AS 
				SELECT p_factures.no_sejour,
					medecin_facture_id,
					acte_id,
					rubrique_facturation_id, 
					prestation_id, 
					t_prestations.code AS prestation_code,
					date_part('dow',p_factures_lignes_h.date_fin) AS jour_semaine,
					(MAX(ARRAY[p_factures_lignes_h.date_fin::text,lieu_id::text]))[2]::bigint AS lieu_id,
					date(MAX(date_max + interval '1 day')) AS date_first, 
					(MAX(ARRAY[p_factures_lignes_h.date_fin::text,coefficient::text]))[2]::numeric AS coefficient,
					(MAX(ARRAY[p_factures_lignes_h.date_fin::text,prix_unitaire::text]))[2]::numeric AS prix_unitaire
				FROM w_periode, activite.p_factures_lignes_h
				JOIN activite.p_factures ON p_factures.no_facture = p_factures_lignes_h.no_facture
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				JOIN (
				SELECT p_factures.no_sejour, MAX(p_factures_lignes_h.date_fin) AS date_max
				FROM w_periode, activite.p_factures_lignes_h
				JOIn activite.p_factures ON p_factures.no_facture = p_factures_lignes_h.no_facture
				JOIN activite.p_sejours ON p_factures.no_sejour = p_sejours.no_sejour
				JOIN activite.t_prestations ON prestation_id = t_prestations.oid
				WHERE montant_facture > 0 AND code_sorti = 0 AND
					p_factures_lignes_h.date_fin > date(date_extraction - interval '56 days')
				GROUP BY 1
				) subview ON
					p_factures.no_sejour = subview.no_sejour AND
					p_factures_lignes_h.date_fin > date(date_max - interval '28 days')
				WHERE montant_facture > 0
				GROUP BY 1,2,3,4,5,6,7
				HAVING count(*) >= 3
				 
				;

				ANALYSE w_actes_jour
				; 


				INSERT INTO activite.p_factures_lignes_non_facturees_h(
					no_facture, 
					date_debut, 
					date_fin, 
					nb_rubrique, 
					coefficient, 
					rubrique_facturation_id, 
					prestation_id, 
					prix_unitaire, 
					lieu_id,
					medecin_facture_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_calendrier.date AS date_debut,
					p_calendrier.date AS date_fin,
					1::numeric AS nb_rubrique,
					w_actes_jour.coefficient,
					w_actes_jour.rubrique_facturation_id,
					w_actes_jour.prestation_id,
					w_actes_jour.prix_unitaire,
					w_actes_jour.lieu_id,
					w_actes_jour.medecin_facture_id,
					w_actes_jour.acte_id,
					''::text AS phase_ccam,
					'1'::text 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
				FROM w_actes_jour
				JOIN base.p_calendrier ON 
					p_calendrier.date BETWEEN date_first AND date(now()) AND
					p_calendrier.jour_semaine = w_actes_jour.jour_semaine
				JOIN activite.p_factures ON
					p_factures.no_sejour = w_actes_jour.no_sejour AND
					p_factures.type_facture = 'E' AND
					p_calendrier.date BETWEEN p_factures.date_debut AND p_factures.date_fin
					order by 1,2
				;
                                        
            ]]></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.p_factures_soldes_h(
                    no_facture, 
                    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
                )
                SELECT
                    p_factures.no_facture,
                    p_factures.date_vente,
                    medecin_comptabilise_id,
					rubrique_comptabilisation_id,
					prestation_id,
                    SUM(montant_comptabilise),
                    SUM(montant_comptabilise_0),
                    SUM(montant_comptabilise_1),
                    SUM(montant_comptabilise_2),
                    SUM(montant_comptabilise_22),
                    0,
                    0,
                    0,
                    0,
                    0
                FROM activite.p_factures_lignes_h
                JOIN activite.p_factures On p_factures_lignes_h.no_facture = p_factures.no_facture
                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
				;
				
				-- Réglements
				INSERT INTO activite.p_factures_soldes_h(
					no_facture, 
					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
				)
				SELECT
					p_factures.no_facture,
					w_REGLEMENTS.DATE_REGLE,
					COALESCE(t_medecins_administratifs.oid,0) AS medecin_comptabilise_id, 
					COALESCE(w_RUBRIQUE_FACTUR_source.rubrique_facturation_id,0),
					COALESCE(w_RUBRIQUE_FACTUR_source.prestation_id,0),
					0,
					0,
					0,
					0,
					0,
					SUM(w_REGLEMENTS.MTTOTAL) AS montant_regle,
					SUM(w_REGLEMENTS.MTASS) AS montant_regle_0,
					SUM(w_REGLEMENTS.MTCAISS) AS montant_regle_1,
					SUM(w_REGLEMENTS.MTMUT) AS montant_regle_2,
					0 AS montant_regle_22
				FROM w_REGLEMENTS
				JOIN activite.p_factures ON w_REGLEMENTS.NUMFACT = p_factures.no_facture
				LEFT JOIN w_RUBRIQUE_FACTUR_source ON w_REGLEMENTS.NUM_ACTE = w_RUBRIQUE_FACTUR_source.NUM_ACTE
				LEFT JOIN activite.t_medecins_administratifs On medecin_executant_code_original = t_medecins_administratifs.code_original
				WHERE DATE_REGLE IS NOT NULL AND 
					w_REGLEMENTS.HONO_SEJ = 'true'
				GROUP BY 1,2,3,4,5
				;  
                
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_1');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_3');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_4');
                SELECT base.cti_enable_index('activite[PX]', 'i_factures_soldes_h_8');
				
				ANALYSE activite.p_factures_soldes_h
				;
                
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Post traitement entetes">
            <sqlcmd><![CDATA[
                 
                            
            ]]></sqlcmd>
        </NODE>

    </NODE>
    
    <NODE name="CHIFFRIER" label="CREATION DU CHIFFRIER">
        
        <NODE label="Récupération chiffrier">
            <sqlcmd><![CDATA[

                TRUNCATE activite.p_chiffrier_comptable;

                INSERT INTO activite.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(date_trunc('month',DATE_EDITION)) AS date_comptable,
                    0::numeric AS montant_ventes_c,
                    0::numeric AS montant_reglements_c,
                    0::numeric AS montant_solde_client_c,
                    0::numeric AS montant_ventes_h,
                    0::numeric AS montant_reglements_h,
                    0::numeric AS monatnt_solde_client_h
                FROM w_FACTURES
                WHERE date(DATE_EDITION) >= '20190101'
                GROUP BY 1;
                
                
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>
    
    <NODE name="PARAM" label="RECUPERATION DES PARAMETRES">
        <NODE label="Préparation des tables">
            <sqlcmd><![CDATA[

               	DROP TABLE IF EXISTS w_periode;
				CREATE TEMP TABLE w_periode AS
				SELECT
					date(MAX(GREATEST(DATE_EDITION,DATE_TRANSMIS,SEJOUR_AU))) AS date_extraction
                FROM prod_hemat2A.FACTURES
                WHERE DATE_EDITION <= date(now()) AND
					DATE_TRANSMIS <= date(now()) AND
					SEJOUR_AU <= date(now())
                ;

                UPDATE w_periode
                SET date_extraction = subview.date_extraction
                FROM
                (
					SELECT date(MAX(GREATEST(DATE_EDIT,DATE_TRANSMI,SEJOUR_AU))) AS date_extraction
					FROM prod_hemat2A.arch_fact
					WHERE DATE_EDIT <= date(now()) AND
					DATE_TRANSMI <= date(now()) AND
					SEJOUR_AU <= date(now())
                ) subview
                WHERE w_periode.date_extraction IS NULL
				;

                DROP TABLE IF EXISTS w_FACTURES;
                CREATE TEMP TABLE w_FACTURES AS
                SELECT
					NUM_PAT,
					NUM_FACT::text,
					VALID,
					TT_SEJ,
					TT_HONO,
					MT_CAISSE,
					MT_MUT,
					MT_ASS,
					DATE_EDITION,
					DATE_TRANSMIS,
					EDITE,
					TRANSMIS,
					NUM_BORDEREAU,
					DATE_GENE_CPT,
					GENE_CPT,
					NUM_JNL,
					RAPPEL,
					COMPLET,
					AVOIR,
					SEJOUR_DU,
					SEJOUR_AU,
					MT_TT,
					NUM_CAISSE,
					NUM_SOC,
					TELETRANS,
					NUMLOT,
					GENAUTO,
					REGUL_POSITIVE,
					REGUL_NEGATIVE,
					CPT_ANA,
					NBR_ACT_DIAL,
					MUTUELLE,
					NUM_MUTUELLE,
					AVOIR_FACTINITIALE::text,
					FORCER_ARCHIVAGE,
					AVOIR_NUMFACT,
					'1'::text AS FACT_last,
					date(SEJOUR_DU) AS SEJOUR_DU_D,
					date(SEJOUR_AU) AS SEJOUR_AU_D,
					'1'::text AS gen_sejour,
					CASE 
					WHEN substr(num_fact,5,2) <> '00' THEN date((LEFT(NUM_FACT,6)||'01')::date + interval '1 month' - interval '1 day')
					ELSE date((LEFT(NUM_FACT,4)||'1231')::date) 
					END AS date_vente,
					TT_SEJ AS TT_SEJ_AMO,
					0::numeric AS TT_SEJ_AMC,
					0::numeric AS TT_SEJ_PAT,
					TT_HONO AS TT_HON_AMO,
					0::numeric AS TT_HON_AMC,
					0::numeric AS TT_HON_PAT,
					TT_HONO AS TC_HON,
					TT_HONO AS TC_HON_AMO,
					0::numeric AS TC_HON_AMC,
					0::numeric AS TC_HON_PAT,
					'20991231'::date AS DATE_REGLE,
					0::numeric AS TR_SEJ,
					0::numeric AS TR_SEJ_AMO,
					0::numeric AS TR_SEJ_AMC,
					0::numeric AS TR_SEJ_PAT,
					0::numeric AS TR_HON,
					0::numeric AS TR_HON_AMO,
					0::numeric AS TR_HON_AMC,
					0::numeric AS TR_HON_PAT
				FROM prod_hemat2a.FACTURES
				;

				INSERT INTO w_FACTURES
				SELECT
					NUM_PAT,
					NUM_FACT::text,
					VALID,
					TT_SEJOUR,
					TT_HONO,
					MT_CAISS,
					MT_MUT,
					MT_ASS,
					DATE_EDIT,
					DATE_TRANSMI,
					EDITE,
					TRANSMIS,
					NUM_BORDEREAU,
					DATE_GENE_COMPT,
					GENE_CPT,
					NUM_JNL,
					RAPPEL,
					COMPLET,
					AVOIR,
					SEJOUR_DU,
					SEJOUR_AU,
					MT_TT,
					NUM_CAISS,
					NUM_SOC,
					TELETRANS,
					NUMLOT,
					GENAUTO,
					REGUL_POSITIVE,
					REGUL_NEGATIVE,
					CPT_ANA,
					NBR_ACT_DIAL,
					MUTUELLE,
					NUM_MUTUELLE,
					AVOIR_FACTINITIALE::text,
					FORCER_ARCHIVAGE,
					AVOIR_NUMFACT,
					'1'::text AS FACT_last,
					date(SEJOUR_DU) AS SEJOUR_DU_D,
					date(SEJOUR_AU) AS SEJOUR_AU_D,
					'1'::text AS gen_sejour,
					CASE 
						WHEN substr(num_fact,5,2) BETWEEN '01' AND '12' THEN date((LEFT(NUM_FACT,6)||'01')::date + interval '1 month' - interval '1 day')
						ELSE date((LEFT(NUM_FACT,4)||'1231')::date) 
					END AS date_vente,
					TT_SEJOUR AS TT_SEJ_AMO,
					0::numeric AS TT_SEJ_AMC,
					0::numeric AS TT_SEJ_PAT,
					TT_HONO AS TT_HON_AMO,
					0::numeric AS TT_HON_AMC,
					0::numeric AS TT_HON_PAT,
					TT_HONO AS TC_HON,
					TT_HONO AS TC_HON_AMO,
					0::numeric AS TC_HON_AMC,
					0::numeric AS TC_HON_PAT,
					'20991231'::date AS DATE_REGLE,
					0::numeric AS TR_SEJ,
					0::numeric AS TR_SEJ_AMO,
					0::numeric AS TR_SEJ_AMC,
					0::numeric AS TR_SEJ_PAT,
					0::numeric AS TR_HON,
					0::numeric AS TR_HON_AMO,
					0::numeric AS TR_HON_AMC,
					0::numeric AS TR_HON_PAT
				FROM prod_hemat2a.ARCH_FACT
				WHERE SEJOUR_AU >= '20100101'
				;

				ANALYSE w_FACTURES
				;



				DROP TABLE IF EXISTS w_LIGNES_FACTURES;
				CREATE TEMP TABLE w_LIGNES_FACTURES AS
				SELECT 
					NUM_FACT::text,
					PRESTATION,
					NUM_ACTE,
					SEJOUR_DU,
					SEJOUR_AU,
					QUANTITE,
					COEF,
					PRIX_UNIT,
					MAJORATION,
					MT_FACT,
					BASE_REMB,
					DEPASS,
					PART_CAISSE,
					PART_MUT,
					PART_ASS,
					EXECUTANT,
					DENOMBREMENT,
					RMO,
					NUM_PAT,
					NUM_EXE,
					CPT_COMPTA,
					DMT,
					CODE_TVA,
					NUM_LIG,
					HONO_SEJ,
					CT_EPO,
					XMT_EPO,
					CODIF_AFF,
					NUM_SOC,
					TIERPERS,
					FELEC,
					TYPE_PRODUIT,
					DATE_PRESCRIPTION_PRODUIT,
					PRIX_UNIT_NATIONAL,
					COEF_NATIONAL,
					COEF_REGIONAL,
					ACTE_PMSI,
					CODE_PRODUIT,
					TYPE_ETI,
					CODE_ASSOCIATION,
					NUM_PRODUIT,
					ID_CLEFPRIMAIRE,
					FINESS_ETAB_DESTINATAIRE,
					''::text AS medecin_executant_code_original,
					NUM_SOC::text||'_'||LEFT(DMT,2) AS service_facturation_code_original,
					CASE WHEN HONO_SEJ = 'false' AND PRESTATION LIKE 'D%' THEN NUM_SOC::text||'_'||PRESTATION ELSE '' END AS unite_fonctionnelle_code_original,
					0::numeric AS LC_HON,
					0::numeric AS LC_HON_AMO,
					0::numeric AS LC_HON_AMC,
					0::numeric AS LC_HON_PAT
				FROM prod_hemat2a.LIGNES_FACTURES
				; 


				INSERT INTO w_LIGNES_FACTURES
				SELECT 
					NUM_FACT::text,
					PRESTATION,
					NUM_ACTE,
					SEJOUR_DU,
					SEJOUR_AU,
					QUANTITE,
					COEF,
					PRIX_UNIT,
					MAJORATION,
					MT_FACT,
					BASE_REMB,
					DEPASS,
					PART_CAISS,
					PART_MUT,
					PART_ASS,
					EXECUTANT,
					DENOMBREMENT,
					RMO,
					NUM_PAT,
					NUM_EXE,
					CPT_COMPTA,
					DMT,
					CODE_TVA,
					NUM_LIGG,
					HONO_SEJ,
					CPTEPO,
					XMT_EPO,
					CODIF_AFF,
					NUM_SOC,
					TIERPERS,
					FELEC,
					TYPE_PRODUIT,
					DATE_PRESCRIPTION_PRODUIT,
					PRIX_UNIT_NATIONAL,
					COEF_NATIONAL,
					COEF_REGIONAL,
					ACTE_PMSI,
					CODE_PRODUIT,
					TYPE_ETI,
					CODE_ASSOCIATION,
					NUM_PRODUIT,
					ID_CLEFPRIMAIRE,
					FINESS_ETAB_DESTINATAIRE,
					''::text AS medecin_executant_code_original,
					NUM_SOC::text||'_'||LEFT(DMT,2) AS service_facturation_code_original,
					CASE WHEN HONO_SEJ = 'false' AND PRESTATION LIKE 'D%' THEN NUM_SOC::text||'_'||PRESTATION ELSE '' END AS unite_fonctionnelle_code_original,
					0::numeric AS LC_HON,
					0::numeric AS LC_HON_AMO,
					0::numeric AS LC_HON_AMC,
					0::numeric AS LC_HON_PAT
				FROM prod_hemat2a.ARCH_LIG_FACT
				;  
				
				ANALYSE w_LIGNES_FACTURES
				;
				
				UPDATE w_LIGNES_FACTURES
				SET medecin_executant_code_original = MEDECINS.NUM_MED::text
				FROM prod_hemat2a.MEDECINS
				WHERE HONO_SEJ = 'true' AND
					NUM_EXE = MEDECINS.FINESS AND
					EXECUTANT = MEDECINS.NOM
				;

				UPDATE w_LIGNES_FACTURES
				SET medecin_executant_code_original = MEDECINS.NUM_MED::text
				FROM prod_hemat2a.MEDECINS
				WHERE HONO_SEJ = 'true' AND
					EXECUTANT = MEDECINS.NOM AND
					medecin_executant_code_original = ''
				;
				
				UPDATE w_LIGNES_FACTURES SET
					LC_HON = MT_FACT,
					LC_HON_AMO = PART_CAISSE,
					LC_HON_AMC = PART_MUT,
					LC_HON_PAT = PART_ASS
				FROM prod_hemat2a.MEDECINS 
				WHERE HONO_SEJ = 'true' AND
					medecin_executant_code_original = NUM_MED::text AND
					REGLEMENT_HONO = 'false'
				;
				
				
				UPDATE w_FACTURES SET
					SEJOUR_DU_D = subview.SEJOUR_DU_D,
					SEJOUR_AU_D = subview.SEJOUR_AU_D
				FROM
				(
				SELECT NUM_FACT,
					MIN(SEJOUR_DU) AS SEJOUR_DU_D,
					MAX(SEJOUR_AU) AS SEJOUR_AU_D
				FROM w_LIGNES_FACTURES
				WHERE HONO_SEJ = 'false' AND
					PRESTATION LIKE 'D%' AND
					PRESTATION NOT LIKE 'DTP'
				GROUP BY 1
				) subview
				WHERE subview.NUM_FACT = w_FACTURES.NUM_FACT AND
					(
					w_FACTURES.SEJOUR_DU_D IS DISTINCT FROM subview.SEJOUR_DU_D OR
					w_FACTURES.SEJOUR_AU_D IS DISTINCT FROM subview.SEJOUR_AU_D
					)
				;
				
				UPDATE w_FACTURES SET
					TT_SEJ = subview.TT_SEJ,
					TT_SEJ_AMO = subview.TT_SEJ_AMO,
					TT_SEJ_AMC = subview.TT_SEJ_AMC,
					TT_SEJ_PAT = subview.TT_SEJ_PAT,
					TC_HON = subview.TC_HON,
					TC_HON_AMO = subview.TC_HON_AMO,
					TC_HON_AMC = subview.TC_HON_AMC,
					TC_HON_PAT = subview.TC_HON_PAT,
					TT_HONO = subview.TT_HON,
					TT_HON_AMO = subview.TT_HON_AMO,
					TT_HON_AMC = subview.TT_HON_AMC,
					TT_HON_PAT = subview.TT_HON_PAT
				FROM
				(
				SELECT NUM_FACT,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN MT_FACT ELSE 0 END) AS TT_SEJ,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN PART_CAISSE ELSE 0 END) AS TT_SEJ_AMO,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN PART_MUT ELSE 0 END) AS TT_SEJ_AMC,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN PART_ASS ELSE 0 END) AS TT_SEJ_PAT,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN MT_FACT ELSE 0 END) AS TT_HON,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN PART_CAISSE ELSE 0 END) AS TT_HON_AMO,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN PART_MUT ELSE 0 END) AS TT_HON_AMC,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN PART_ASS ELSE 0 END) AS TT_HON_PAT,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN LC_HON ELSE 0 END) AS TC_HON,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN LC_HON_AMO ELSE 0 END) AS TC_HON_AMO,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN LC_HON_AMC ELSE 0 END) AS TC_HON_AMC,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN LC_HON_PAT ELSE 0 END) AS TC_HON_PAT
				FROM w_LIGNES_FACTURES
				GROUP BY 1
				) subview
				WHERE subview.NUM_FACT = w_FACTURES.NUM_FACT AND
					(
					w_FACTURES.TT_SEJ IS DISTINCT FROM subview.TT_SEJ OR
					w_FACTURES.TT_SEJ_AMO IS DISTINCT FROM subview.TT_SEJ_AMO OR
					w_FACTURES.TT_SEJ_AMC IS DISTINCT FROM subview.TT_SEJ_AMC OR
					w_FACTURES.TT_SEJ_PAT IS DISTINCT FROM subview.TT_SEJ_PAT OR
					w_FACTURES.TC_HON IS DISTINCT FROM subview.TC_HON OR
					w_FACTURES.TC_HON_AMO IS DISTINCT FROM subview.TC_HON_AMO OR
					w_FACTURES.TC_HON_AMC IS DISTINCT FROM subview.TC_HON_AMC OR
					w_FACTURES.TC_HON_PAT IS DISTINCT FROM subview.TC_HON_PAT OR
					w_FACTURES.TT_HONO IS DISTINCT FROM subview.TT_HON OR
					w_FACTURES.TT_HON_AMO IS DISTINCT FROM subview.TT_HON_AMO OR
					w_FACTURES.TT_HON_AMC IS DISTINCT FROM subview.TT_HON_AMC OR
					w_FACTURES.TT_HON_PAT IS DISTINCT FROM subview.TT_HON_PAT
					)
				;
							
				
				DROP TABLE IF EXISTS w_REGLEMENTS;
				CREATE TEMP TABLE w_REGLEMENTS AS
				SELECT REGLEMENTS.NUMFACT::text,
					REGLEMENTS.DATE_REGLE,
					REGLEMENTS.MTCAISS,
					REGLEMENTS.MTMUT,
					REGLEMENTS.MTASS,
					REGLEMENTS.MTTOTAL,
					REGLEMENTS.NUMPAT,
					REGLEMENTS.MEDECIN,
					REGLEMENTS.NUMBORD,
					REGLEMENTS.PRESTATION,
					REGLEMENTS.NUMCAISS,
					REGLEMENTS.NUM_SOC,
					CASE WHEN MEDECIN = 'SEJOUR' THEN 'false'::text ELSE 'true' END AS HONO_SEJ,
					0::bigint AS NUM_ACTE,
					''::text AS medecin_executant_code_original
				FROM prod_hemat2a.REGLEMENTS
				JOIN w_FACTURES ON w_FACTURES.NUM_FACT = REGLEMENTS.NUMFACT
				;

				ANALYSE w_REGLEMENTS
				;

				UPDATE w_REGLEMENTS
				SET HONO_SEJ = subview.HONO_SEJ
				FROM
				(
				SELECT PRESTATION, MAX(HONO_SEJ) AS HONO_SEJ
				FROM w_LIGNES_FACTURES
				GROUP BY 1
				) subview
				WHERE w_REGLEMENTS.PRESTATION = subview.PRESTATION AND
					w_REGLEMENTS.HONO_SEJ IS DISTINCT FROM subview.HONO_SEJ
				;
				
				UPDATE w_REGLEMENTS
				SET NUM_ACTE = subview.NUM_ACTE
				FROM
				(
				SELECT NUM_FACT, PRESTATION, MAX(NUM_ACTE) AS NUM_ACTE
				FROM w_LIGNES_FACTURES
				GROUP BY 1,2
				) subview
				WHERE w_REGLEMENTS.NUMFACT = subview.NUM_FACT AND
					w_REGLEMENTS.PRESTATION = subview.PRESTATION
				;
				
				UPDATE w_REGLEMENTS
				SET medecin_executant_code_original = MEDECINS.NUM_MED::text
				FROM prod_hemat2a.MEDECINS
				WHERE HONO_SEJ = 'true' AND
					MEDECIN = MEDECINS.NOM AND
					medecin_executant_code_original = ''
				;
				
				UPDATE w_FACTURES SET
					DATE_REGLE = subview.DATE_REGLE,
					TR_SEJ = subview.TR_SEJ,
					TR_SEJ_AMO = subview.TR_SEJ_AMO,
					TR_SEJ_AMC = subview.TR_SEJ_AMC,
					TR_SEJ_PAT = subview.TR_SEJ_PAT,
					TR_HON = subview.TR_HON,
					TR_HON_AMO = subview.TR_HON_AMO,
					TR_HON_AMC = subview.TR_HON_AMC,
					TR_HON_PAT = subview.TR_HON_PAT
				FROM
				(
				SELECT NUMFACT AS NUM_FACT,
					MAX(DATE_REGLE) AS DATE_REGLE,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN MTTOTAL ELSE 0 END) AS TR_SEJ,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN MTCAISS ELSE 0 END) AS TR_SEJ_AMO,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN MTMUT ELSE 0 END) AS TR_SEJ_AMC,
					SUM(CASE WHEN HONO_SEJ = 'false' THEN MTASS ELSE 0 END) AS TR_SEJ_PAT,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN MTTOTAL ELSE 0 END) AS TR_HON,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN MTCAISS ELSE 0 END) AS TR_HON_AMO,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN MTMUT ELSE 0 END) AS TR_HON_AMC,
					SUM(CASE WHEN HONO_SEJ = 'true' THEN MTASS ELSE 0 END) AS TR_HON_PAT
				FROM w_REGLEMENTS
				GROUP BY 1
				) subview
				WHERE subview.NUM_FACT = w_FACTURES.NUM_FACT
				;
				
				-- Ménage dans les factures anciennes
				DELETE FROM w_factures
				WHERE date(SEJOUR_AU) < '20150101'  
				;

				DELETE FROM w_FACTURES
				USING
				(
				SELECT NUM_PAT, 
					date(COALESCE(MAX(CASE WHEN SEJOUR_DU <= '20190101' AND TT_SEJ <> TR_SEJ THEN SEJOUR_DU ELSE NULL END),'20190101')) AS SEJOUR_DU
				FROM w_FACTURES
				GROUP BY 1  
				) subview
				WHERE w_FACTURES.NUM_PAT = subview.NUM_PAT AND
					w_FACTURES.SEJOUR_DU < subview.SEJOUR_DU
				;

				-- Traitement des avoirs
				
				-- Regul sans avoir précisé, il faut tenter de le retrouver
				UPDATE w_FACTURES
				SET AVOIR_FACTINITIALE = subview.AVOIR_FACTINITIALE
				FROM
				(
				SELECT w_FACTURES.NUM_FACT, MIN(w_FACTURES_avoir.NUM_FACT) AS AVOIR_FACTINITIALE
				FROM w_FACTURES
				JOIN w_FACTURES w_FACTURES_avoir ON
					w_FACTURES.NUM_PAT = w_FACTURES_avoir.NUM_PAT AND
					w_FACTURES.SEJOUR_DU_D = w_FACTURES_avoir.SEJOUR_DU_D AND
					w_FACTURES.SEJOUR_AU_D = w_FACTURES_avoir.SEJOUR_AU_D AND
					w_FACTURES.NUM_FACT > w_FACTURES_avoir.NUM_FACT
				WHERE w_FACTURES.REGUL_POSITIVE = 'true' AND 
					w_FACTURES.AVOIR_FACTINITIALE = '0'
				GROUP BY 1
				) subview
				WHERE w_FACTURES.NUM_FACT = subview.NUM_FACT
				;
				
				-- Ajout des avoirs
				INSERT INTO w_FACTURES
				SELECT 
					w_FACTURES.NUM_PAT,
					w_FACTURES.NUM_FACT || 'A'::text AS NUM_FACT,
					w_FACTURES_regul.VALID,
					0-w_FACTURES.TT_SEJ,
					0-w_FACTURES.TT_HONO,
					0-w_FACTURES.MT_CAISSE,
					0-w_FACTURES.MT_MUT,
					0-w_FACTURES.MT_ASS,
					w_FACTURES_regul.DATE_EDITION,
					w_FACTURES_regul.DATE_TRANSMIS,
					w_FACTURES_regul.EDITE,
					w_FACTURES_regul.TRANSMIS,
					w_FACTURES_regul.NUM_BORDEREAU,
					w_FACTURES_regul.DATE_GENE_CPT,
					w_FACTURES_regul.GENE_CPT,
					w_FACTURES_regul.NUM_JNL,
					w_FACTURES_regul.RAPPEL,
					w_FACTURES_regul.COMPLET,
					'autocti'::text AS AVOIR,
					w_FACTURES.SEJOUR_DU,
					w_FACTURES.SEJOUR_AU,
					0-w_FACTURES.MT_TT,
					w_FACTURES.NUM_CAISSE,
					w_FACTURES.NUM_SOC,
					w_FACTURES_regul.TELETRANS,
					w_FACTURES_regul.NUMLOT,
					w_FACTURES.GENAUTO,
					'false'::text AS REGUL_POSITIVE,
					'true'::text AS REGUL_NEGATIVE,
					w_FACTURES.CPT_ANA,
					w_FACTURES.NBR_ACT_DIAL,
					w_FACTURES.MUTUELLE,
					w_FACTURES.NUM_MUTUELLE,
					w_FACTURES.NUM_FACT AS AVOIR_FACTINITIALE,
					w_FACTURES.FORCER_ARCHIVAGE,
					0::numeric AS AVOIR_NUMFACT,
					'0'::text AS FACT_last,
					w_FACTURES.SEJOUR_DU_D,
					w_FACTURES.SEJOUR_AU_D,
					'0'::text AS gen_sejour,
					w_FACTURES_regul.date_vente,
					0-w_FACTURES.TT_SEJ_AMO,
					0-w_FACTURES.TT_SEJ_AMC,
					0-w_FACTURES.TT_SEJ_PAT,
					0-w_FACTURES.TT_HON_AMO,
					0-w_FACTURES.TT_HON_AMC,
					0-w_FACTURES.TT_HON_PAT,
					0-w_FACTURES.TC_HON,
					0-w_FACTURES.TC_HON_AMO,
					0-w_FACTURES.TC_HON_AMC,
					0-w_FACTURES.TC_HON_PAT,
					w_FACTURES_regul.DATE_REGLE,
					0-w_FACTURES.TR_SEJ,
					0-w_FACTURES.TR_SEJ_AMO,
					0-w_FACTURES.TR_SEJ_AMC,
					0-w_FACTURES.TR_SEJ_PAT,
					0-w_FACTURES.TR_HON,
					0-w_FACTURES.TR_HON_AMO,
					0-w_FACTURES.TR_HON_AMC,
					0-w_FACTURES.TR_HON_PAT
				FROM w_FACTURES
				JOIN w_FACTURES w_FACTURES_regul ON w_FACTURES.NUM_FACT = w_FACTURES_regul.AVOIR_FACTINITIALE
				;


				INSERT INTO w_LIGNES_FACTURES
				SELECT
					w_FACTURES.NUM_FACT::text,
					w_LIGNES_FACTURES.PRESTATION,
					w_LIGNES_FACTURES.NUM_ACTE,
					w_LIGNES_FACTURES.SEJOUR_DU,
					w_LIGNES_FACTURES.SEJOUR_AU,
					0-w_LIGNES_FACTURES.QUANTITE,
					w_LIGNES_FACTURES.COEF,
					w_LIGNES_FACTURES.PRIX_UNIT,
					w_LIGNES_FACTURES.MAJORATION,
					0-w_LIGNES_FACTURES.MT_FACT,
					0-w_LIGNES_FACTURES.BASE_REMB,
					0-w_LIGNES_FACTURES.DEPASS,
					0-w_LIGNES_FACTURES.PART_CAISSE,
					0-w_LIGNES_FACTURES.PART_MUT,
					0-w_LIGNES_FACTURES.PART_ASS,
					w_LIGNES_FACTURES.EXECUTANT,
					w_LIGNES_FACTURES.DENOMBREMENT,
					w_LIGNES_FACTURES.RMO,
					w_LIGNES_FACTURES.NUM_PAT,
					w_LIGNES_FACTURES.NUM_EXE,
					w_LIGNES_FACTURES.CPT_COMPTA,
					w_LIGNES_FACTURES.DMT,
					w_LIGNES_FACTURES.CODE_TVA,
					w_LIGNES_FACTURES.NUM_LIG,
					w_LIGNES_FACTURES.HONO_SEJ,
					w_LIGNES_FACTURES.CT_EPO,
					w_LIGNES_FACTURES.XMT_EPO,
					w_LIGNES_FACTURES.CODIF_AFF,
					w_LIGNES_FACTURES.NUM_SOC,
					w_LIGNES_FACTURES.TIERPERS,
					w_LIGNES_FACTURES.FELEC,
					w_LIGNES_FACTURES.TYPE_PRODUIT,
					w_LIGNES_FACTURES.DATE_PRESCRIPTION_PRODUIT,
					w_LIGNES_FACTURES.PRIX_UNIT_NATIONAL,
					w_LIGNES_FACTURES.COEF_NATIONAL,
					w_LIGNES_FACTURES.COEF_REGIONAL,
					w_LIGNES_FACTURES.ACTE_PMSI,
					w_LIGNES_FACTURES.CODE_PRODUIT,
					w_LIGNES_FACTURES.TYPE_ETI,
					w_LIGNES_FACTURES.CODE_ASSOCIATION,
					w_LIGNES_FACTURES.NUM_PRODUIT,
					w_LIGNES_FACTURES.ID_CLEFPRIMAIRE,
					w_LIGNES_FACTURES.FINESS_ETAB_DESTINATAIRE,
					w_LIGNES_FACTURES.medecin_executant_code_original,
					w_LIGNES_FACTURES.service_facturation_code_original,
					w_LIGNES_FACTURES.unite_fonctionnelle_code_original,
					0-w_LIGNES_FACTURES.LC_HON,
					0-w_LIGNES_FACTURES.LC_HON_AMO,
					0-w_LIGNES_FACTURES.LC_HON_AMC,
					0-w_LIGNES_FACTURES.LC_HON_PAT
				FROM w_LIGNES_FACTURES
				JOIN w_FACTURES ON w_LIGNES_FACTURES.NUM_FACT || 'A'::text = w_FACTURES.NUM_FACT
				;

				INSERT INTO w_REGLEMENTS
				SELECT 
					w_FACTURES.NUM_FACT,
					w_FACTURES.date_vente AS DATE_REGLE,
					0-w_REGLEMENTS.MTCAISS,
					0-w_REGLEMENTS.MTMUT,
					0-w_REGLEMENTS.MTASS,
					0-w_REGLEMENTS.MTTOTAL,
					w_REGLEMENTS.NUMPAT,
					w_REGLEMENTS.MEDECIN,
					w_REGLEMENTS.NUMBORD,
					w_REGLEMENTS.PRESTATION,
					w_REGLEMENTS.NUMCAISS,
					w_REGLEMENTS.NUM_SOC,
					w_REGLEMENTS.HONO_SEJ,
					w_REGLEMENTS.NUM_ACTE,
					w_REGLEMENTS.medecin_executant_code_original
				FROM w_REGLEMENTS
				JOIN w_FACTURES ON w_REGLEMENTS.NUMFACT || 'A'::text = w_FACTURES.NUM_FACT
				;
				
				
				UPDATE w_FACTURES
				SET AVOIR = 'autocti'
				WHERE NUM_FACT IN (SELECT AVOIR_FACTINITIALE FROM w_FACTURES) AND
					AVOIR = 'false'
				;


				DROP TABLE IF EXISTS w_ASSURES;
				CREATE TEMP TABLE w_ASSURES AS
				SELECT
					NUM_PAT
					, NOM
					, PRENOM
					, NOM_JF
					, CP
					, DATE_NAISS
					, SEXE
					, CAISSE_NUM
					, MUT_NUM
					, NUM_SOCIETE::text AS service_facturation_code_original
					, NUM_SECU
					, 'N'::text AS OK
					, NULL::date AS date_entree
					, NULL::date AS date_sortie
					, 0::numeric AS code_sorti
					, ''::text AS medecin_sejour_code_original
					, ''::text AS unite_fonctionnelle_code_original
					, ''::text AS ghm_code
					, 0::numeric AS ghs_code
				FROM prod_hemat2a.ASSURES
				WHERE NUM_PAT IN (SELECT NUM_PAT FROM w_FACTURES)
				;

				ANALYSE w_ASSURES
				;


				UPDATE w_ASSURES
				SET OK = 'O'
				WHERE NUM_PAT IN (
					SELECT NUM_PAT FROM w_FACTURES 
					WHERE SEJOUR_DU >= '20190101' OR 
						DATE_EDITION >= '20190101' OR 
						DATE_TRANSMIS >= '20190101' 
					)
				;

				UPDATE w_ASSURES
				SET OK = 'O'
				WHERE OK = 'N' AND
					NUM_PAT IN (
						SELECT NUM_PAT 
						FROM w_FACTURES 
						JOIN prod_hemat2a.REGLEMENTS ON w_FACTURES.NUM_FACT = REGLEMENTS.NUMFACT
						WHERE REGLEMENTS.DATE_REGLE >= '20190101' 
					)
				;
				
				UPDATE w_ASSURES SET
					date_entree = subview.date_entree,
					date_sortie = subview.date_sortie,
					code_sorti = subview.code_sorti,
					CAISSE_NUM = subview.NUM_CAISSE,
					MUT_NUM = subview.NUM_MUTUELLE
				FROM
				(
				SELECT w_FACTURES.NUM_PAT,
					date(MIN(SEJOUR_DU)) AS date_entree,
					CASE WHEN MAX(date_extraction) - date(MAX(LEAST(now(),SEJOUR_AU))) > 30 THEN date(MAX(LEAST(now(),SEJOUR_AU))) ELSE '20991231' END AS date_sortie,
					CASE WHEN MAX(date_extraction) - date(MAX(LEAST(now(),SEJOUR_AU))) > 30 THEN 1 ELSE 0 END AS code_sorti,
					(MAX(ARRAY[SEJOUR_AU::text,NUM_CAISSE::text]))[2]::numeric AS NUM_CAISSE,
					(MAX(ARRAY[SEJOUR_AU::text,NUM_MUTUELLE::text]))[2]::numeric AS NUM_MUTUELLE
				FROM w_FACTURES
				JOIN w_ASSURES ON w_FACTURES.NUM_PAT = w_ASSURES.NUM_PAT
				JOIN w_periode ON 1=1
				WHERE OK = 'O'
				GROUP BY 1
				) subview
				WHERE w_ASSURES.NUM_PAT = subview.NUM_PAT
				;
				
				UPDATE w_ASSURES SET
					service_facturation_code_original = subview.service_facturation_code_original,
					unite_fonctionnelle_code_original = subview.unite_fonctionnelle_code_original,
					ghm_code = CASE WHEN subview.ghm_code <> '' THEN '28'::text||subview.ghm_code ELSE '' END,
					ghs_code = CASE WHEN subview.ghm_code <> '' THEN CASE WHEN subview.ghs_code <> '0' THEN subview.ghs_code::numeric ELSE 9999 END ELSE 0 END
				FROM
				(
					SELECT w_FACTURES.NUM_PAT, 
						(MAX(ARRAY[w_LIGNES_FACTURES.SEJOUR_AU::text,w_LIGNES_FACTURES.service_facturation_code_original]))[2] AS service_facturation_code_original, 
						(MAX(ARRAY[w_LIGNES_FACTURES.SEJOUR_AU::text,w_LIGNES_FACTURES.unite_fonctionnelle_code_original]))[2] AS unite_fonctionnelle_code_original,
						(MAX(ARRAY[w_LIGNES_FACTURES.SEJOUR_AU::text,RUBRIQUE_FACTUR.PMSI_GHM_ASSOCIE]))[2] AS ghm_code,
						(MAX(ARRAY[w_LIGNES_FACTURES.SEJOUR_AU::text,COALESCE(RUBRIQUE_FACTUR.NUMEROGHS,'0')::text]))[2]::numeric AS ghs_code
					FROM w_FACTURES 
					JOIN w_ASSURES ON w_FACTURES.NUM_PAT = w_ASSURES.NUM_PAT
					JOIN w_LIGNES_FACTURES ON w_FACTURES.NUM_FACT = w_LIGNES_FACTURES.NUM_FACT
					LEFT JOIN prod_hemat2a.RUBRIQUE_FACTUR ON w_LIGNES_FACTURES.NUM_ACTE = RUBRIQUE_FACTUR.NUM_ACTE
					WHERE OK = 'O' AND
						w_LIGNES_FACTURES.HONO_SEJ = 'false' AND
						w_LIGNES_FACTURES.PRESTATION LIKE 'D%' AND
						w_LIGNES_FACTURES.PRESTATION NOT LIKE 'DTP' 
					GROUP BY 1
				) subview
				WHERE w_ASSURES.NUM_PAT = subview.NUM_PAT
				;
				
				UPDATE w_ASSURES
				SET medecin_sejour_code_original = subview.medecin_sejour_code_original
				FROM
					(
					SELECT NUM_PAT, (MAX(ARRAY[SEJOUR_AU::text, medecin_executant_code_original]))[2] AS medecin_sejour_code_original
					FROM w_LIGNES_FACTURES
					JOIN prod_hemat2a.MEDECINS ON medecin_executant_code_original = NUM_MED::text
					WHERE HONO_SEJ = 'true' AND
						specialite <> 30
					GROUP BY 1
					) subview
				WHERE w_ASSURES.NUM_PAT = subview.NUM_PAT
				;

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

                INSERT INTO activite.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.t_types_tiers_payant);
				
				
				INSERT INTO base.t_grands_regimes(code, code_original, texte, texte_court)
				SELECT CODEGR, CODEGR, CODEGR, CODEGR
				FROM prod_hemat2a.CAISSES
				LEFT JOIN base.t_grands_regimes ON CODEGR = code
				WHERE t_grands_regimes.code IS NULL AND
					CODEGR <> ''
				GROUP BY 1;
                
                

                INSERT INTO activite.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.t_tiers_payant);

                INSERT INTO activite.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.t_tiers_payant);

                INSERT INTO activite.t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
                SELECT NUMERO::text, to_char(NUMERO,'FM9990000'), '1'::text, NOM, NOM
                FROM prod_hemat2a.CAISSES
                WHERE NUMERO IN (SELECT NUM_CAISSE FROM w_FACTURES) AND
					NUMERO::text NOT IN (SELECT code_original FROM activite.t_tiers_payant WHERE code_original IS NOT NULL)
						;

                INSERT INTO activite.t_tiers_payant(code_original, code, type_tiers_payant, texte, texte_court) 
                SELECT NUMERO::text||'M', to_char(NUMERO,'FM9990000')||'M', '2'::text, NOM, NOM
                FROM prod_hemat2a.CAISSES
                WHERE NUMERO IN (SELECT NUM_MUTUELLE FROM w_FACTURES) AND
					NUMERO::text||'M' NOT IN (SELECT code_original FROM activite.t_tiers_payant WHERE code_original IS NOT NULL)
						;
                    
                UPDATE activite.t_tiers_payant
                SET grand_regime_id = t_grands_regimes.oid 
                FROM prod_hemat2a.CAISSES
                    JOIN base.t_grands_regimes ON CODEGR = code
                WHERE t_tiers_payant.code_original = NUMERO AND
                    grand_regime_id IS DISTINCT FROM t_grands_regimes.oid AND
                    CODEGR <> '';

                UPDATE activite.t_tiers_payant
                SET grand_regime_id = t_grands_regimes.oid 
                FROM prod_hemat2a.CAISSES
                    JOIN base.t_grands_regimes ON CODEGR = code
                WHERE t_tiers_payant.code_original = NUMERO::text||'M' AND
                    grand_regime_id IS DISTINCT FROM t_grands_regimes.oid AND
                    CODEGR <> '';
                                        
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Médecins">
            <sqlcmd><![CDATA[
            
                INSERT INTO base.t_specialites_medecin(oid, code, code_original, texte, texte_court) 
                SELECT 0, '', '0', 'Non saisie', 'Non saisie'
                WHERE 0 NOT IN (SELECT oid FROM base.t_specialites_medecin);
                
                UPDATE base.t_specialites_medecin SET
					code_original = code 
				WHERE code_original is null and oid != 0;

               

                INSERT INTO activite.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.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_source
                ;
                
                CREATE TEMP TABLE W_MEDECINS_source AS
                SELECT * 
                FROM  prod_hemat2a.MEDECINS
                WHERE NUM_MED::text IN (SELECT medecin_executant_code_original FROM w_LIGNES_FACTURES)
                ;
                
				-- Médecins d'après la nomenclature classique
                DROP TABLE IF EXISTS w_medecins;
                CREATE TEMP TABLE w_medecins AS
                SELECT NUM_MED::text, 
                    NUM_MED::text AS MEDE_CODE,
                    base.cti_soundex_nom(W_MEDECINS_source.NOM) AS NOM_SOUNDEX, 
                    base.cti_soundex_nom(COALESCE(W_MEDECINS_source.PRENOM,'')) AS PRENOM_SOUNDEX, 
                    W_MEDECINS_source.NOM, 
                    COALESCE(W_MEDECINS_source.PRENOM,'') AS PRENOM, 
                    COALESCE(W_MEDECINS_source.RPPS,'') AS RPPS,
                    COALESCE(to_char(W_MEDECINS_source.SPECIALITE,'FM00'),'') aS SPECIALITE,
                    COALESCE(t_medecins_administratifs.medecin_id,0) as medecin_id
                FROM W_MEDECINS_source 
                    LEFT JOIN activite.t_medecins_administratifs ON NUM_MED::text = t_medecins_administratifs.code_original
                ;
					
				
                                        
                INSERT INTO base.t_medecins(nom, prenom, numero_ordre, specialite_id)
                SELECT w_medecins.NOM, w_medecins.PRENOM, w_medecins.RPPS, 0 FROM
                (SELECT SUBSTR(NOM_SOUNDEX, 1, 8) AS NOM_SOUNDEX, SUBSTR(PRENOM_SOUNDEX, 1, 8) AS PRENOM_SOUNDEX, RPPS, NUM_MED::text
                FROM w_medecins
                GROUP BY 1,2,3,4) subview, w_medecins
                WHERE w_medecins.NUM_MED::text = subview.NUM_MED::text
					AND w_medecins.NUM_MED::text != ALL (ARRAY(SELECT code FROM base.t_medecins)::text[])
                    AND subview.NOM_SOUNDEX || ',' || subview.PRENOM_SOUNDEX || ',' ||  subview.RPPS 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, specialite_id)
                SELECT w_medecins.NOM, w_medecins.PRENOM, 0 FROM
                (SELECT SUBSTR(NOM_SOUNDEX, 1, 8) AS NOM_SOUNDEX, SUBSTR(PRENOM_SOUNDEX, 1, 8) AS PRENOM_SOUNDEX, NUM_MED::text
                FROM w_medecins
                GROUP BY 1,2,3) subview, w_medecins
                WHERE w_medecins.NUM_MED::text = subview.NUM_MED::text
					AND w_medecins.NUM_MED::text != ALL (ARRAY(SELECT code FROM base.t_medecins)::text[])
                    AND subview.NOM_SOUNDEX || ',' || subview.PRENOM_SOUNDEX NOT IN 
                    (SELECT substr(base.cti_soundex_nom(nom),1,8)  || ',' || substr(base.cti_soundex_nom(prenom),1,8)  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(NOM_SOUNDEX, 1, 8) = subview.nom
                AND SUBSTR(PRENOM_SOUNDEX, 1, 8) = subview.prenom
                AND RPPS = 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(NOM_SOUNDEX, 1, 8) = subview.nom
                AND SUBSTR(PRENOM_SOUNDEX, 1, 8) = subview.prenom
                AND w_medecins.medecin_id = 0;

                INSERT INTO activite.t_medecins_administratifs(code_original, code, nom, prenom, specialite_id,  medecin_id)
                SELECT DISTINCT NUM_MED::text, NUM_MED::text, NOM, PRENOM, COALESCE(t_specialites_medecin.oid::bigint,0), medecin_id
                FROM w_medecins
                    LEFT JOIN base.t_specialites_medecin ON (SPECIALITE = t_specialites_medecin.code_original)
                WHERE NUM_MED::text NOT IN (SELECT code_original FROM activite.t_medecins_administratifs);

                UPDATE activite.t_medecins_administratifs
                SET nom = w_medecins.NOM,
                    prenom = w_medecins.PRENOM,
                    specialite_id = COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0),
                    medecin_id = w_medecins.medecin_id
                FROM w_medecins 
                LEFT JOIN base.t_specialites_medecin ON (SPECIALITE || '..' = t_specialites_medecin.code)
                LEFT JOIN base.t_specialites_medecin t_specialites_medecin_2 ON (SPECIALITE = t_specialites_medecin_2.code)
                WHERE w_medecins.NUM_MED::text = t_medecins_administratifs.code_original
                    AND (
                    t_medecins_administratifs.nom <> w_medecins.NOM OR
                    t_medecins_administratifs.prenom <> w_medecins.PRENOM OR
                    t_medecins_administratifs.specialite_id <> COALESCE(t_specialites_medecin.oid,t_specialites_medecin_2.oid,0) OR
                    t_medecins_administratifs.medecin_id <> w_medecins.medecin_id
                );

                

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

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


                -- no_adeli
				UPDATE activite.t_medecins_administratifs
				SET no_adeli = ADELIE
				FROM prod_hemat2a.MEDECINS
				WHERE t_medecins_administratifs.code_original = NUM_MED::text AND
					t_medecins_administratifs.NO_ADELI IS DISTINCT FROM ADELIE
				;                                    
                                        
            ]]></sqlcmd>
        </NODE>
        
        <NODE label="Hébergement">
            <sqlcmd><![CDATA[
                
                
                -- Modes de traitement
                
              
                
                -- DMT
                
               
                
                -- Services
                
                INSERT INTO activite[PX].t_services_facturation(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '****', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECt oid FROM activite[PX].t_services_facturation);

                DROP TABLE IF EXISTS w_services_facturation;
				CREATE TEMP TABLE w_services_facturation AS
				SELECT 
					service_facturation_code_original AS code_original, 
					MAX(to_char(NUM_SOC,'FM900')||'-'||LEFT(w_LIGNES_FACTURES.DMT,2)) AS code,
					MAX(SOCIETES.NOM || ' - ' || t_modes_traitement.texte) AS texte,
					MAX(t_modes_traitement.oid) AS mode_traitement_id
				FROM w_LIGNES_FACTURES
				JOIN prod_hemat2a.SOCIETES ON NUM_SOC = SOCIETES.NUMERO
				LEFT JOIN base.t_modes_traitement ON left(w_LIGNES_FACTURES.DMT,2) = t_modes_traitement.code
				WHERE HONO_SEJ = 'false' AND prestation LIKE 'D%' 
				GROUP BY 1
				;

                INSERT INTO activite.t_services_facturation(code_original, code, texte, texte_court, type_t2a, mode_traitement_id)
                SELECT code_original, code, texte, texte, '0'::text AS type_t2a, mode_traitement_id
                FROM w_services_facturation
                WHERE code_original NOT IN (SELECT code_original FROM activite.t_services_facturation)
                ;

                -- Unités fonctionnelles
                
                INSERT INTO activite.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.t_unites_fonctionnelles);
                
                DROP TABLE IF EXISTS w_unites_fonctionnelles;
				CREATE TEMP TABLE w_unites_fonctionnelles AS
				SELECT 
					unite_fonctionnelle_code_original AS code_original, 
					MAX(to_char(NUM_SOC,'FM900')||'-'||PRESTATION) AS code,
					MAX(SOCIETES.NOM || ' - ' || PRESTATION) AS texte
				FROM w_LIGNES_FACTURES
				JOIN prod_hemat2a.SOCIETES ON NUM_SOC = SOCIETES.NUMERO
				WHERE HONO_SEJ = 'false' AND prestation LIKE 'D%' 
				GROUP BY 1
				;

                INSERT INTO activite.t_unites_fonctionnelles(code_original, code, texte, texte_court)
                SELECT code_original, code, texte, texte
                FROM w_unites_fonctionnelles
                WHERE code_original NOT IN (SELECT code_original FROM activite.t_unites_fonctionnelles)
                ;
                
                    
                -- Unités médicales = unités fonctionnelles
                INSERT INTO activite.t_unites_medicales(oid, code_original, code, texte, texte_court)
                SELECT oid, code_original, code, texte, texte
                FROM activite.t_unites_fonctionnelles
                WHERE oid NOT IN (SELECT oid FROM activite.t_unites_medicales)
                ;

                -- Activités (RIEN
                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);


                -- Etages et lits (SOCIETE)

                INSERT INTO activite[PX].t_etages(oid, code_original, code, texte, texte_court, nb_lits) 
                SELECT 0, 0, '', 'Non renseigné', 'Non renseigné', 0 
				WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_etages);
    
                INSERT INTO activite[PX].t_lits(oid, code_original, code, texte, texte_court, etage_id, chambre_particuliere)
                SELECT 0, '', '***', 'Non renseigné', 'Non renseigné', 0, 'N'
				WHERE 0 NOT IN (SELECT oid FROM activite[PX].t_lits);
    
            ]]></sqlcmd>
        </NODE>
                
        <NODE label="Facturation">
            <sqlcmd><![CDATA[
                
                -- Rubriques et prestations

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

                DROP TABLE IF EXISTS w_RUBRIQUE_FACTUR_source;
				CREATE TEMP TABLE w_RUBRIQUE_FACTUR_source AS
				SELECT *,
					0::bigint AS rubrique_facturation_id,
					0::bigint AS prestation_id,
					0::bigint AS acte_id,
					0::bigint AS compte_produit_id
				FROM prod_hemat2a.RUBRIQUE_FACTUR
				;

                ANALYSE w_RUBRIQUE_FACTUR_source
                ;
                
		
				UPDATE w_RUBRIQUE_FACTUR_source
				SET CODE_CETEL = PRESTATION 
				WHERE CODE_CETEL IS NULL OR CODE_CETEL = ''
				;

				UPDATE w_RUBRIQUE_FACTUR_source SET
					CODE_CCAM = w_RUBRIQUE_FACTUR_source2.PRESTATION,
					PRESTATION = COALESCE(t_ccam_regroupements.code,w_RUBRIQUE_FACTUR_source2.CODE_REGROUP_CCAM),
					CODE_CETEL = COALESCE(t_ccam_regroupements.code,w_RUBRIQUE_FACTUR_source2.CODE_REGROUP_CCAM),
					LIBELLE_ACTE = COALESCE(t_prestations.texte,w_RUBRIQUE_FACTUR_source2.LIBELLE_ACTE)
				FROM w_RUBRIQUE_FACTUR_source w_RUBRIQUE_FACTUR_source2	 
				LEFT JOIN base.t_actes ON w_RUBRIQUE_FACTUR_source2.PRESTATION ILIKE t_actes.code AND length(w_RUBRIQUE_FACTUR_source2.PRESTATION) = 7
				LEFT JOIN base.t_ccam_regroupements ON ccam_regroupement_id_1 = t_ccam_regroupements.oid
				LEFT JOIN activite.t_prestations ON t_ccam_regroupements.code = t_prestations.code
				WHERE w_RUBRIQUE_FACTUR_source2.NUM_ACTE = w_RUBRIQUE_FACTUR_source.NUM_ACTE AND
					(
					w_RUBRIQUE_FACTUR_source.ACTE_CCAM = 'true' OR
					t_actes.oid IS NOT NULL
					)
				;

				DROP TABLE IF EXISTS w_rubriques_facturation;
				CREATE TEMP TABLE w_rubriques_facturation AS
				SELECT PRESTATION AS code_original, 
					MAX(CASE WHEN LIBELLE_ACTE <> '' THEN LIBELLE_ACTE ELSE COALESCE(t_prestations.code,CODE_CETEL) END) AS texte
				FROM w_RUBRIQUE_FACTUR_source
				LEFT JOIN activite.t_prestations ON CODE_CETEL = t_prestations.code
				WHERE PRESTATION <> ''
				GROUP BY 1
				ORDER BY 1
				;

                INSERT INTO activite.t_rubriques_facturation(code_original, code, texte, texte_court)
                SELECT code_original, code_original, texte, texte
                FROM w_rubriques_facturation
                WHERE code_original NOT IN (SELECT code_original FROM activite.t_rubriques_facturation)
                ;
                
                
                INSERT INTO activite.t_prestations(code, code_original, texte, texte_court)
                SELECT CODE_CETEL, CODE_CETEL,CODE_CETEL, CODE_CETEL
                FROM w_RUBRIQUE_FACTUR_source
                WHERE CODE_CETEL NOT IN (SELECT code FROM activite.t_prestations WHERE code IS NOT NULL)
                GROUP BY 1
                ;
                    
                
                INSERT INTO activite.t_protocoles(oid, code_original, code, texte, texte_court) 
                SELECT 0, 0, '***', 'Non renseigné', 'Non renseigné' WHERE 0 NOT IN (SELECT oid FROM activite.t_protocoles);

                INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                SELECT 
                    UPPER(CODE_CCAM), 
                    UPPER(CODE_CCAM),
                    UPPER(CODE_CCAM),
                    'CCAM'
                FROM w_RUBRIQUE_FACTUR_source
                WHERE
                    CODE_CCAM <> '' AND
                    UPPER(CODE_CCAM) NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                GROUP BY UPPER(CODE_CCAM)
                ;
                INSERT INTO base.t_actes(code, texte, texte_court, nomenclature)
                SELECT 
                    CODE_CETEL, 
                    CODE_CETEL, 
                    CODE_CETEL, 
                    'NGAP'
                FROM w_RUBRIQUE_FACTUR_source
                WHERE
                    HONO_SEJ = 'true' AND 
                    ACTE_CCAM = 'false' AND
                    CODE_CETEL NOT IN (SELECT code FROM base.t_actes WHERE code IS NOT NULL)
                GROUP BY CODE_CETEL
                ;
				
				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.t_compte(code_original, code, texte, texte_court)
				SELECT CPT_COMPTA,CPT_COMPTA, CPT_COMPTA, CPT_COMPTA
				FROM w_RUBRIQUE_FACTUR_source
				WHERE CPT_COMPTA <> '' AND
					CPT_COMPTA NOT IN (SELECT code FROM activite.t_compte WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO activite.t_compte(code_original, code, texte, texte_court)
				SELECT CPT_COMPTA,CPT_COMPTA, CPT_COMPTA, CPT_COMPTA
				FROM w_LIGNES_FACTURES
				WHERE CPT_COMPTA <> '' AND
					CPT_COMPTA NOT IN (SELECT code FROM activite.t_compte WHERE code IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;
				

                UPDATE w_RUBRIQUE_FACTUR_source
                SET rubrique_facturation_id = t_rubriques_facturation.oid
                FROM activite.t_rubriques_facturation 
                WHERE PRESTATION = t_rubriques_facturation.code_original
                ;

                UPDATE w_RUBRIQUE_FACTUR_source
                SET prestation_id = t_prestations.oid
                FROM activite.t_prestations
                WHERE CODE_CETEL = t_prestations.code
                ;


                UPDATE w_RUBRIQUE_FACTUR_source
                SET acte_id = t_actes.oid
                FROM base.t_actes
                WHERE CODE_CETEL = t_actes.code AND
					HONO_SEJ = 'true' 
                ;

                UPDATE w_RUBRIQUE_FACTUR_source
                SET acte_id = t_actes.oid
                FROM base.t_actes
                WHERE CODE_CCAM = t_actes.code AND
					HONO_SEJ = 'true' AND
					CODE_CCAM <> ''
                ;
				
				UPDATE w_RUBRIQUE_FACTUR_source
                SET compte_produit_id = t_compte.oid
                FROM activite.t_compte
                WHERE CPT_COMPTA = t_compte.code AND
					CPT_COMPTA <> ''
                ;	
                
                                        
                
                                        
            ]]></sqlcmd>
        </NODE>
        
    </NODE>
        
    <NODE name="POST" label="TRAITEMENTS COMPLEMENTAIRES">
    
       
    </NODE>
    
    <NODE name="ENCOURS" label="ENCOURS ET VALORISATION DES NON FACTURES">
    
    </NODE>
    

</ROOT>
