<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
		
		<NODE label="Tables Articles">
			
			<sqlcmd><![CDATA[
			
			SELECT base.cti_execute('INSERT INTO prod_medicagest.mvt05 SELECT * from prod_medicagest.mvt05_2016',1)
			WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'mvt05_2016') = 1;
			SELECT base.cti_execute('INSERT INTO prod_medicagest.mvt05 SELECT * from prod_medicagest.mvt05_2017',1)
			WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'mvt05_2017') = 1;
			SELECT base.cti_execute('INSERT INTO prod_medicagest.mvt05 SELECT * from prod_medicagest.mvt05_2018',1)
			WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'mvt05_2018') = 1;
			SELECT base.cti_execute('INSERT INTO prod_medicagest.mvt05 SELECT * from prod_medicagest.mvt05_2019',1)
			WHERE (SELECT count(*) FROM information_schema.tables WHERE table_name = 'mvt05_2019') = 1;
			
			INSERT INTO eco.t_types_mouvements(code, texte, texte_court, code_original)
			SELECT TPMVT, TPMVT, TPMVT, TPMVT
			FROM prod_medicagest.MVT05
			WHERE TPMVT <> ''
				AND TPMVT NOT IN (SELECT code_original FROM eco.t_types_mouvements)
			GROUP BY 1,2,3,4
			;

			-- Familles
			INSERT INTO eco.t_familles_articles(code, code_original,texte, texte_court)
			SELECT CDFAM, CDFAM, LBFAM, LBFAM
					FROM prod_medicagest.FAM01
					WHERE  CDFAM NOT IN (SELECT code_original FROM eco.t_familles_articles WHERE code_original IS NOT NULL)
					ORDER BY CDFAM;
					
			-- fournisseurs
			
			INSERT INTO eco.t_fournisseurs(code, texte, texte_court, code_original)
			SELECT CODEFRS, RSSCL, RSSCL, CODEFRS
			FROM prod_medicagest.FRS02
				LEFT JOIN eco.t_fournisseurs ON (code_original = CODEFRS)
			WHERE code_original IS NULL AND CODEFRS <> 0
			;
			
			UPDATE eco.t_fournisseurs SET
				texte = FRS02.RSSCL,
				texte_court = FRS02.RSSCL,
				siret = FRS02.SIRET,
				code_comptable = FRS02.COMPTE
			FROM prod_medicagest.FRS02
			WHERE t_fournisseurs.code_original = CODEFRS AND
				(
				t_fournisseurs.texte IS DISTINCT FROM FRS02.RSSCL OR
				t_fournisseurs.texte_court IS DISTINCT FROM FRS02.RSSCL OR
				t_fournisseurs.siret IS DISTINCT FROM FRS02.SIRET OR
				t_fournisseurs.code_comptable IS DISTINCT FROM FRS02.COMPTE
				)
			;

			UPDATE eco.t_fournisseurs SET
				texte = FRS02.RSSCL,
				texte_court = FRS02.RSSCL,
				cedex = '',
				siret = FRS02.SIRET,
				code_comptable = FRS02.COMPTE
			FROM prod_medicagest.FRS02
			WHERE code_original = CODEFRS AND
				(
				t_fournisseurs.texte IS DISTINCT FROM FRS02.RSSCL OR
				t_fournisseurs.texte_court IS DISTINCT FROM FRS02.RSSCL OR
				t_fournisseurs.siret IS DISTINCT FROM FRS02.SIRET OR
				t_fournisseurs.code_comptable IS DISTINCT FROM FRS02.COMPTE
				)
			;
			
			-- L'adresse n'est pas toujours fournie
			SELECT base.cti_execute('
			INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT CODPOS, UPPER(MAX(VILLE)), UPPER(MAX(LEFT(VILLE,50))), MAX(t_departements.oid)
				FROM prod_medicagest.FRS02
				LEFT JOIN base.t_codes_postaux ON CODPOS = t_codes_postaux.code
				JOIN base.t_departements ON 
					CODPOS NOT LIKE ''97%'' AND substr(CODPOS,1,2) = t_departements.code OR
					CODPOS LIKE ''97%'' AND substr(CODPOS,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL AND 
					length(CODPOS) = 5
				GROUP BY 1
			.,
			UPDATE eco.t_fournisseurs SET
				adresse = trim(ADRS1 || '' '' || ADRS2),
				code_postal_id = COALESCE(t_codes_postaux.oid,0),
				ville = COALESCE(FRS02.VILLE,'''')
			FROM prod_medicagest.FRS02
				LEFT JOIN base.t_codes_postaux ON CODPOS = t_codes_postaux.code
			WHERE code_original = CODEFRS AND
				(
				t_fournisseurs.adresse IS DISTINCT FROM trim(ADRS1 || '' '' || ADRS2) OR
				t_fournisseurs.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
				t_fournisseurs.ville IS DISTINCT FROM COALESCE(FRS02.VILLE,'''')
				)
			',1)
			WHERE ('codpos' IN (SELECT column_name FROM information_schema.columns WHERE table_schema = 'prod_medicagest' AND table_name = 'frs02'))
			;
			
			-- Types fournisseurs
			
			INSERT INTO eco.t_types_fournisseurs(code, texte, texte_court, code_original)
			SELECT NUMGRAC, NOMGRAC, NOMGRAC, NUMGRAC
			FROM prod_medicagest.GRACFR
			WHERE NUMGRAC <> 0 AND
				NUMGRAC NOT IN (SELECT code_original FROM eco.t_types_fournisseurs)
			GROUP BY 1,2,3,4
			;

			UPDATE eco.t_types_fournisseurs
			SET texte = NOMGRAC,
				texte_court = NOMGRAC
			FROM prod_medicagest.GRACFR
			WHERE 
				code_original = NUMGRAC AND
				(texte IS DISTINCT FROM NOMGRAC);
				
			-- Unités fonctionnelles
			
			INSERT INTO eco.t_unites_fonctionnelles(code, texte, texte_court, code_original)
			SELECT CDSEC, LBSEC, LBSEC, CDSEC 
			FROM prod_medicagest.SEC83
				LEFT JOIN eco.t_unites_fonctionnelles ON (code_original = CDSEC)
			WHERE code_original IS NULL;
			
			UPDATE eco.t_unites_fonctionnelles
			SET texte = LBSEC,
				texte_court = LBSEC
			FROM prod_medicagest.SEC83
			WHERE code_original = CDSEC
			AND (texte IS DISTINCT FROM LBSEC);
				
			-- Lieux
			
			INSERT INTO eco.t_lieux(code, texte, texte_court, code_original)
			SELECT CDSRV, LBSRV, LBSRV, CDSRV 
			FROM prod_medicagest.SER82
				LEFT JOIN eco.t_lieux ON (code_original = CDSRV)
			WHERE code_original IS NULL;
			
			UPDATE eco.t_lieux
			SET texte = LBSRV,
				texte_court = LBSRV
			FROM prod_medicagest.SER82
			WHERE code_original = CDSRV
			AND (texte IS DISTINCT FROM LBSRV);
				
			-- UCD
			--DROP TABLE IF EXISTS w_lpp_ucd;
			--CREATE TEMP TABLE w_lpp_ucd AS
			--SELECT 
			--	CDART,
			--	CASE WHEN LENGTH(CODEUCD) = 7 THEN CODEUCD 
			--		WHEN LENGTH(CODEUCD) = 13 THEN substr(codeucd,6,7)
			--		ELSE ''	END
			--		AS code,
			--	LIBEL
			--FROM prod_medicagest.ART01 
			--	LEFT JOIN base.t_lpp on CODEUCD = t_lpp.code
			--		OR substr(CODEUCD,6,7) = t_lpp.code 
			--	LEFT JOIN base.t_ucd on CODEUCD = t_ucd.code
			--		OR substr(CODEUCD,6,7) = t_ucd.code 
			--	WHERE 
			--		t_ucd.oid IS NULL AND t_lpp.oid is null
			--	AND LENGTH(CODEUCD) IN (7,13)
			--;
			--	
			---- LPP
			--INSERT INTO base.t_lpp (code,texte)
			--SELECT code, LIBEL FROM w_lpp_ucd WHERE code LIKE '3%'
			--	AND code NOT IN (SELECT code FROM base.t_lpp) 
			--;
			--
			---- UCD
			--INSERT INTO base.t_ucd (code,texte)
			--SELECT code, LIBEL FROM w_lpp_ucd WHERE code LIKE '9%'
			--	AND code NOT IN (SELECT code FROM base.t_ucd)
			--;
			
			-- Site
			INSERT INTO eco.t_sites(code, texte, texte_court, code_original)
			SELECT CDSEC, LBSEC, LBSEC, CDSEC 
			FROM prod_medicagest.SEC83
				LEFT JOIN eco.t_sites ON (code_original = CDSEC)
			WHERE code_original IS NULL;
			
			UPDATE eco.t_sites
			SET texte = LBSEC,
				texte_court = LBSEC
			FROM prod_medicagest.SEC83
			WHERE code_original = CDSEC
			AND (texte IS DISTINCT FROM LBSEC);

			]]></sqlcmd>
		</NODE>
		
		
		
		<NODE label="Articles">
			<sqlcmd><![CDATA[
			
		
			-- Catégories
				
				INSERT INTO eco.t_categories_articles(code, texte, texte_court, code_original)
				SELECT CDTHP, LBTHP, LEFT(LBTHP,50), CDTHP	
				FROM prod_medicagest.THP84
					LEFT JOIN eco.t_categories_articles ON (code_original = CDTHP)
				WHERE code_original IS NULL AND CDTHP <> ''
				;
				
				UPDATE eco.t_categories_articles
				SET texte = LBTHP,
					texte_court = LEFT(LBTHP,50)
				FROM prod_medicagest.THP84
				WHERE 
					CDTHP <> '' AND
					code_original = CDTHP AND
					(texte IS DISTINCT FROM LBTHP) OR
					(texte_court IS DISTINCT FROM LEFT(LBTHP,50));
					
			
					-- Gestionnaires
					-- Achats
					INSERT INTO eco.t_gestionnaires(code_original, code, texte, texte_court)
					SELECT replace(UTILISATEUR,' ','_'), replace(UTILISATEUR,' ','_'), UTILISATEUR, UTILISATEUR
					FROM prod_medicagest.MVT05
					WHERE replace(UTILISATEUR,' ','_') NOT IN (SELECT code_original FROM eco.t_gestionnaires)
					GROUP BY 1,2,3,4
					;
				

					
					-- Unites de stockage
					INSERT INTO eco.t_unites(code, code_original, texte, texte_court)
					SELECT
						CDFRM,
						CDFRM,
						LBFRM,
						LBFRM
					FROM
						prod_medicagest.FRM81
					WHERE CDFRM NOT IN (SELECT code_original from eco.t_unites)
					GROUP BY 1,2,3,4;

				-- comptes
				INSERT INTO eco.t_compte(code, texte, texte_court, code_original)
				SELECT CDCPT::text, COALESCE(LBCPT), LEFT(COALESCE(LBCPT),40), CDCPT
				FROM prod_medicagest.CPT03 
				WHERE CDCPT <> 0 AND
					CDCPT::text NOT IN (SELECT code_original FROM eco.t_compte)
				GROUP BY 1,2,3,4
				;
				
				INSERT INTO eco.t_compte(code, texte, texte_court, code_original)
				SELECT MVT05.CDCPT, COALESCE(LBCPT,MVT05.CDCPT), LEFT(COALESCE(LBCPT,MVT05.CDCPT),40), MVT05.CDCPT
				FROM prod_medicagest.MVT05
					LEFT JOIN prod_medicagest.CPT03 ON CPT03.CDCPT = MVT05.CDCPT
				WHERE MVT05.CDCPT <> ''
					AND MVT05.CDCPT NOT IN (SELECT code_original FROM eco.t_compte)
				GROUP BY 1,2,3,4
				;
					
				-- ATC / Cladimed
				
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court, est_cladimed )
				SELECT CDTHDM, CDTHDM, LBTHDM, LBTHDM, 1
				FROM prod_medicagest.THP90
					JOIN (
						SELECT 
							MERE AS ROOT_CODE,
							1 AS cladimed
						FROM prod_medicagest.THP90
						) sub ON MERE = ROOT_CODE
				LEFT JOIN eco.t_classification_atc ON (code_original = CDTHDM)
				WHERE MERE IS NOT NULL AND
					code_original IS NULL 
					GROUP BY 1,2,3,4
				;
				
				UPDATE eco.t_classification_atc
				SET texte = LBTHDM,
					texte_court = LBTHDM,
					est_cladimed = cladimed
				FROM prod_medicagest.THP90
					JOIN (
						SELECT 
							MERE AS ROOT_CODE,
							1 AS cladimed
						FROM prod_medicagest.THP90
						) sub ON MERE = ROOT_CODE
				WHERE 
					code_original = CDTHDM AND
					(texte IS DISTINCT FROM LBTHDM);
					

					-- Standard ATC
				SELECT eco.cti_reorganize_classification_atc();
			
					-- articles
					INSERT INTO eco.t_articles(code, texte, texte_court, code_original)
					SELECT CDART, LIBEL, substr(LIBEL,1,50), CDART
					FROM prod_medicagest.ART01
						LEFT JOIN eco.t_articles ON (code_original = CDART)
					WHERE code_original IS NULL;


					UPDATE eco.t_articles
					SET 
						texte = LIBEL,
						texte_court = substr(LIBEL,1,50),
						taux_tva_en_cours = CASE CDTVA WHEN 1 THEN 0 WHEN 2 THEN 2.1 WHEN 3 THEN 5.5 WHEN 4 THEN 20 WHEN 5 THEN 10 ELSE 0 END
					FROM prod_medicagest.ART01
					WHERE code_original = CDART
					AND (
						texte IS DISTINCT FROM LIBEL OR
						texte_court IS DISTINCT FROM substr(LIBEL,1,50) OR
						taux_tva_en_cours IS DISTINCT FROM CASE CDTVA WHEN 1 THEN 0 WHEN 2 THEN 2.1 WHEN 3 THEN 5.5 WHEN 4 THEN 20 WHEN 5 THEN 10 ELSE 0 END
						)
					;

				
					UPDATE eco.t_articles SET
					--	type_id = COALESCE(t_types_articles.oid,0),
						famille_id = COALESCE(t_familles_articles.oid,0),
						--sous_famille_id = COALESCE(t_sous_familles_articles.oid,0),
						categorie_id = COALESCE(t_categories_articles.oid,0),
						--sous_categorie_id = COALESCE(t_sous_categories_articles.oid,0),
						classification_atc_id = COALESCE(t_classification_atc.oid,0),
						unite_stockage_id = COALESCE(t_unites_stockage.oid,0),
						unite_distribution_id = COALESCE(t_unites_distribution.oid,0),
						lpp_id = COALESCE(t_lpp.oid,0),
						ucd_id = COALESCE(t_ucd.oid,0),
						gere_en_stock = CASE WHEN NONSTOCKE = 1 THEN 0 ELSE 1 END
					FROM prod_medicagest.ART01
						LEFT JOIN eco.t_familles_articles ON CDFAM = t_familles_articles.code_original
						--LEFT JOIN eco.t_sous_familles_articles ON NUM_TYP_PROD2 = upper(t_sous_familles_articles.code_original)
						--LEFT JOIN eco.t_types_articles ON TYPEART = t_types_articles.code_original
						LEFT JOIN eco.t_classification_atc ON CDTHP = upper(t_classification_atc.code_original)
						LEFT JOIN eco.t_categories_articles ON CDTHP = t_categories_articles.code_original
						--LEFT JOIN eco.t_sous_categories_articles ON REFCAT = t_sous_categories_articles.code_original
						LEFT JOIN eco.t_unites t_unites_stockage ON CDFRM = t_unites_stockage.code_original
						LEFT JOIN eco.t_unites t_unites_distribution ON CDFRM = t_unites_distribution.code_original
						LEFT JOIN base.t_lpp ON 
							CASE WHEN LENGTH(CODEUCD) = 7 THEN CODEUCD 
								WHEN LENGTH(CODEUCD) = 13 THEN substr(CODEUCD,6,7)
								ELSE '' END = t_lpp.code
						LEFT JOIN base.t_ucd ON 
							CASE WHEN LENGTH(CODEUCD) = 7 THEN CODEUCD 
								WHEN LENGTH(CODEUCD) = 13 THEN substr(CODEUCD,6,7)
								ELSE '' END = t_ucd.code
					WHERE
						t_articles.code_original = CDART AND
						(
					--	t_articles.type_id IS DISTINCT FROM COALESCE(t_types_articles.oid,0) OR
						t_articles.famille_id IS DISTINCT FROM COALESCE(t_familles_articles.oid,0) OR
						--t_articles.sous_famille_id IS DISTINCT FROM COALESCE(t_sous_familles_articles.oid,0) OR
						t_articles.categorie_id IS DISTINCT FROM COALESCE(t_categories_articles.oid,0) OR
						--t_articles.sous_categorie_id IS DISTINCT FROM COALESCE(t_sous_categories_articles.oid,0) OR
						t_articles.classification_atc_id IS DISTINCT FROM COALESCE(t_classification_atc.oid,0) OR
						t_articles.unite_stockage_id IS DISTINCT FROM COALESCE(t_unites_stockage.oid,0) OR
						t_articles.unite_distribution_id IS DISTINCT FROM COALESCE(t_unites_distribution.oid,0) OR
						t_articles.gere_en_stock IS DISTINCT FROM CASE WHEN NONSTOCKE = 1 THEN '0' ELSE '1' END OR
						lpp_id IS DISTINCT FROM COALESCE(t_lpp.oid,0) OR
						ucd_id IS DISTINCT FROM COALESCE(t_ucd.oid,0)
						);
						
			UPDATE eco.t_articles 
				SET 
					compte_id = compte_oid
				FROM
					(
					SELECT 
						CDART,
						MAX(t_compte.oid) as compte_oid
					FROM prod_medicagest.ART01
						JOIN eco.t_compte ON CDCPT = code_original
					GROUP BY 1
					) sub
				WHERE CDART = code_original AND
					compte_id IS DISTINCT FROM compte_oid
				;
						
				UPDATE eco.t_articles 
				SET 
					compte_id = compte_oid
				FROM
					(
					SELECT 
						CDART,
						(MAX(ARRAY[DATEM,oid::text]))[2]::bigint as compte_oid
					FROM 
						prod_medicagest.MVT05
						JOIN eco.t_compte ON CDCPT = code_original
					GROUP BY 1
					) sub
				WHERE CDART = code_original AND
					compte_id = 0 AND
					compte_id IS DISTINCT FROM compte_oid
				;

				
				UPDATE eco.t_articles 
				SET 
					ref_fournisseur_id[1] = t_fournisseurs.oid,
					ref_fournisseur_texte[1] = LIBEL || ' (' || COALESCE(REFCAT,CDART) || ')'
				FROM
					prod_medicagest.ART01
					JOIN eco.t_fournisseurs ON CDFRS = t_fournisseurs.code
				WHERE t_articles.code = CDART
				;
				-- réplication ref fournisseur sur autres fournisseurs du produit et fournisseur principal (dernier)
				UPDATE eco.t_articles
				SET 
					fournisseur_principal_id = last_fou,
					ref_fournisseur_id = ref_ids,
					ref_fournisseur_texte = ref_textes
				FROM (
					SELECT 
						article_id, 
						article_code, 
						ref_fournisseur_id, 
						ref_fournisseur_texte,
						array_agg(fournisseur_id) AS ref_ids, 
						array_agg(ref_fournisseur_texte[1]) as ref_textes,
						(MAX(ARRAY[date_commande::text, fournisseur_id::text]))[2]::bigint AS last_fou
					FROM ( 
						SELECT
							article_id,
							t_articles.code AS article_code,
							t_articles.texte AS article_texte,
							ref_fournisseur_id, 
							ref_fournisseur_texte, 
							fournisseur_id,
							max(date_commande) AS date_commande
						FROM eco.p_commandes 
							JOIN eco.p_lignes_commandes ON commande_id = p_commandes.oid
							JOIN eco.t_articles on article_id = t_articles.oid
						GROUP BY 1,2,3,4,5,6
						) sub
					GROUP BY 1,2,3,4
					ORDER BY 1
					) sub
				WHERE article_id = t_articles.oid
				;

				
				DROP TABLE IF EXISTS w_article_fournisseur;
				CREATE TEMP TABLE w_article_fournisseur AS
				SELECT
					CDART||'|'||CODEFRS AS code_original,
					MAX(t_articles.oid) AS article_id,
					MAX(t_fournisseurs.oid) AS fournisseur_id,
					(MAX(Array[DATEC::text,FLG10.REFCAT]))[2]::text AS code_reference_fournisseur,
					(MAX(Array[DATEC::text,FLG10.LIBEL]))[2]::text AS texte_reference_fournisseur,
					''::text AS code_cip,
					''::text AS code_cahpp,
					0::bigint AS unite_approvisionnement_id,
					(MAX(Array[DATEC::text,base.cti_to_number(CONDT)::text]))[2]::numeric AS nombre_conditionnement_approvisionnement,
					(MAX(Array[DATEC::text,base.cti_division(base.cti_to_number(PRIXC), base.cti_to_number(CONDT))::text]))[2]::numeric AS prix_unitaire_en_cours,
					'0'::text AS est_fournisseur_principal,
					0::bigint AS fournisseur_distributeur_id,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id,
					''::text AS code_ucd13,
					MAX(CDART) AS CDART,
					MAX(CODEFRS) AS CODEFRS,
					''::text AS code_ucd
				FROM prod_medicagest.FCT10 
				JOIN prod_medicagest.FLG10 ON FCT10.CODEFRS || FCT10.NOCOM || NUMBL = FRSCOMBL
				JOIN eco.t_articles ON t_articles.code_original = CDART
				JOIN eco.t_fournisseurs ON t_fournisseurs.code_original = CODEFRS
				GROUP BY 1
				;

				INSERT INTO w_article_fournisseur
				SELECT 
					CDART||'|'||CDFRS AS code_original,
					MAX(t_articles.oid) AS article_id,
					MAX(t_fournisseurs.oid) AS fournisseur_id,
					(MAX(Array[DATEC::text,REFCAT]))[2]::text AS code_reference_fournisseur,
					(MAX(Array[DATEC::text,LIBEL]))[2]::text AS texte_reference_fournisseur,
					''::text AS code_cip,
					''::text AS code_cahpp,
					0::bigint AS unite_approvisionnement_id,
					(MAX(Array[DATEC::text,base.cti_to_number(CONDT)::text]))[2]::numeric AS nombre_conditionnement_approvisionnement,
					(MAX(Array[DATEC::text,base.cti_division(base.cti_to_number(PRIXB), base.cti_to_number(CONDT))::text]))[2]::numeric AS prix_unitaire_en_cours,
					'0'::text AS est_fournisseur_principal,
					0::bigint AS fournisseur_distributeur_id,
					0::bigint AS ucd_id,
					0::bigint AS lpp_id,
					''::text AS code_ucd13,
					MAX(CDART) AS CDART,
					MAX(CDFRS) AS CODEFRS,
					''::text AS code_ucd
				FROM prod_medicagest.ART01
				JOIN eco.t_articles ON t_articles.code_original = CDART
				JOIN eco.t_fournisseurs ON t_fournisseurs.code_original = CDFRS
				WHERE (CDART||'|'||CDFRS) NOT IN (SELECT code_original FROM w_article_fournisseur)
				GROUP BY 1
				;

				
				UPDATE w_article_fournisseur SET
					code_reference_fournisseur = CASE WHEN w_article_fournisseur.CODEFRS = ART01.CDFRS THEN ART01.REFCAT ELSE w_article_fournisseur.code_reference_fournisseur END,
					texte_reference_fournisseur = CASE WHEN w_article_fournisseur.CODEFRS = ART01.CDFRS THEN ART01.LIBEL ELSE w_article_fournisseur.texte_reference_fournisseur END,
					nombre_conditionnement_approvisionnement = CASE WHEN w_article_fournisseur.CODEFRS = ART01.CDFRS THEN base.cti_to_number(ART01.CONDT) ELSE w_article_fournisseur.nombre_conditionnement_approvisionnement END,
					prix_unitaire_en_cours = CASE WHEN w_article_fournisseur.CODEFRS = ART01.CDFRS THEN base.cti_division(base.cti_to_number(ART01.PRIXB), base.cti_to_number(ART01.CONDT)) ELSE w_article_fournisseur.prix_unitaire_en_cours END,
					code_ucd = CASE WHEN length(ART01.CODEUCD) = 7 THEN ART01.CODEUCD WHEN length(ART01.CODEUCD) = 13 AND ART01.CODEUCD LIKE '34008%' THEN substr(ART01.CODEUCD,6) ELSE '' END,
					code_ucd13 = CASE WHEN length(ART01.CODEUCD) = 13 AND ART01.CODEUCD LIKE '34008%' THEN ART01.CODEUCD ELSE '' END,
					code_cip = CASE 
								WHEN length(ART01.CDART) = 13 AND ART01.CDART LIKE '34009%' THEN ART01.CDART 
								WHEN length(ART01.CODEUCD) = 13 AND ART01.CODEUCD LIKE '34009%' THEN ART01.CODEUCD 
								WHEN length(ART01.REFCAT) = 13 AND ART01.REFCAT LIKE '34009%' THEN ART01.REFCAT
								WHEN length(ART01.CDART) = 7 AND CODEUCD <> '' AND base.cti_to_number(ART01.CDART)::text = ART01.CDART THEN ART01.CDART
								ELSE '' END,
					est_fournisseur_principal = CASE WHEN w_article_fournisseur.CODEFRS = ART01.CDFRS THEN '1' ELSE '0' END
				FROM prod_medicagest.ART01
				WHERE ART01.CDART = w_article_fournisseur.CDART
				;
				
				UPDATE w_article_fournisseur
				SET ucd_id = t_ucd.oid
				FROM base.t_ucd
				WHERE code_ucd = t_ucd.code
				;
				
				INSERT INTO eco.t_article_fournisseur(
					code_original,
					article_id, 
					fournisseur_id,
					code_reference_fournisseur,
					texte_reference_fournisseur,
					code_cip,
					code_cahpp,
					unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours,
					est_fournisseur_principal,
					fournisseur_distributeur_id,
					ucd_id,
					lpp_id,
					code_ucd13
				)
				SELECT
					code_original,
					article_id,
					fournisseur_id,
					code_reference_fournisseur,
					texte_reference_fournisseur,
					code_cip,
					code_cahpp,
					unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours,
					est_fournisseur_principal,
					fournisseur_distributeur_id,
					ucd_id,
					lpp_id,
					code_ucd13
				FROM w_article_fournisseur
				WHERE w_article_fournisseur.code_original NOT IN (SELECT code_original FROM eco.t_article_fournisseur)
				;

				UPDATE eco.t_article_fournisseur SET
					article_id = w_article_fournisseur.article_id,
					fournisseur_id = w_article_fournisseur.fournisseur_id,
					code_reference_fournisseur = w_article_fournisseur.code_reference_fournisseur,
					texte_reference_fournisseur = w_article_fournisseur.texte_reference_fournisseur,
					code_cip = w_article_fournisseur.code_cip,
					code_cahpp = w_article_fournisseur.code_cahpp,
					unite_approvisionnement_id = w_article_fournisseur.unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement = w_article_fournisseur.nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours = w_article_fournisseur.prix_unitaire_en_cours,
					est_fournisseur_principal = w_article_fournisseur.est_fournisseur_principal,
					fournisseur_distributeur_id = w_article_fournisseur.fournisseur_distributeur_id,
					ucd_id = w_article_fournisseur.ucd_id,
					lpp_id = w_article_fournisseur.lpp_id,
					code_ucd13 = w_article_fournisseur.code_ucd13
				FROM w_article_fournisseur
				WHERE w_article_fournisseur.code_original = t_article_fournisseur.code_original AND
					(
					t_article_fournisseur.article_id IS DISTINCT FROM w_article_fournisseur.article_id OR
					t_article_fournisseur.fournisseur_id IS DISTINCT FROM w_article_fournisseur.fournisseur_id OR
					t_article_fournisseur.code_reference_fournisseur IS DISTINCT FROM w_article_fournisseur.code_reference_fournisseur OR
					t_article_fournisseur.texte_reference_fournisseur IS DISTINCT FROM w_article_fournisseur.texte_reference_fournisseur OR
					t_article_fournisseur.code_cip IS DISTINCT FROM w_article_fournisseur.code_cip OR
					t_article_fournisseur.code_cahpp IS DISTINCT FROM w_article_fournisseur.code_cahpp OR
					t_article_fournisseur.unite_approvisionnement_id IS DISTINCT FROM w_article_fournisseur.unite_approvisionnement_id OR
					t_article_fournisseur.nombre_conditionnement_approvisionnement IS DISTINCT FROM w_article_fournisseur.nombre_conditionnement_approvisionnement OR
					t_article_fournisseur.prix_unitaire_en_cours IS DISTINCT FROM w_article_fournisseur.prix_unitaire_en_cours OR
					t_article_fournisseur.est_fournisseur_principal IS DISTINCT FROM w_article_fournisseur.est_fournisseur_principal OR
					t_article_fournisseur.fournisseur_distributeur_id IS DISTINCT FROM w_article_fournisseur.fournisseur_distributeur_id OR
					t_article_fournisseur.ucd_id IS DISTINCT FROM w_article_fournisseur.ucd_id OR
					t_article_fournisseur.lpp_id IS DISTINCT FROM w_article_fournisseur.lpp_id OR
					t_article_fournisseur.code_ucd13 IS DISTINCT FROM w_article_fournisseur.code_ucd13
					)
				;
			]]></sqlcmd>
		</NODE>
		
		
	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
		<NODE label="Commandes">
			<sqlcmd><![CDATA[
			
						
				SELECT base.cti_disable_index('eco', 'i_commandes_1');
				SELECT base.cti_disable_index('eco', 'i_commandes_2');
				SELECT base.cti_disable_index('eco', 'i_commandes_3');
				SELECT base.cti_disable_index('eco', 'i_commandes_4');
				SELECT base.cti_disable_index('eco', 'i_commandes_5');
				SELECT base.cti_disable_index('eco', 'i_commandes_6');
				SELECT base.cti_disable_index('eco', 'i_commandes_7');
				SELECT base.cti_disable_index('eco', 'i_commandes_8');
				
					
					TRUNCATE eco.p_commandes;
						
					INSERT INTO eco.p_commandes(
						code_original,
						numero,
						date_commande,
						date_engagement,
						objet,
						reference,
						date_livraison_prevue,
						etat_reception,
						date_reception,
						etat_liquidation,
						fournisseur_id,
						gestionnaire_id,
						lieu_commande_id,
						lieu_facturation_id,
						lieu_livraison_id,
						unite_fonctionnelle_id,
						site_id,
						montant_commande_ht,
						montant_commande_remise,
						montant_commande_tva,
						montant_commande_port,
						montant_commande_total,
						montant_liquidation_ht,
						montant_liquidation_remise,
						montant_liquidation_tva,
						montant_liquidation_port,
						montant_liquidation_total)
					SELECT
						NOCOM AS code_original,
						NOCOM AS numero,
						date(DATEC) AS date_commande,
						date(DATEC) AS date_engagement,
						''::text AS objet,
						''::text AS reference,
						MAX(date(COALESCE(NULLIF(DATEL,''),'2099-12-31'))) AS date_livraison_prevue, -- Quand la commande est sans DATEL (=pas encore réceptionnée) on met 2099-12-31
						CASE WHEN MAX(COALESCE(NULLIF(DATEREC,''),'2099-12-31')) <> '2099-12-31' THEN 'T' ELSE 'N' END AS etat_reception,
						MAX(date(COALESCE(NULLIF(DATEL,''),'2099-12-31'))) AS date_reception,
						CASE WHEN MAX(COALESCE(NOFCT,'')) = '' THEN 'N' ELSE 'T' END AS etat_liquidation,
						MAX(COALESCE(t_fournisseurs.oid, 0)) AS fournisseur_id,
						MAX(COALESCE(t_gestionnaires.oid,0)) AS gestionnaire_id,
						0::bigint AS lieu_commande_id,
						MAX(COALESCE(t_lieux_facturation.oid,0)) AS lieu_facturation_id,
						MAX(COALESCE(t_lieux_facturation.oid,0)) AS lieu_livraison_id,
						0::bigint AS unite_fonctionnelle_id,
						MAX(COALESCE(t_sites.oid,0)) AS site_id,
						0::numeric AS montant_commande_ht,
						(MAX(ARRAY[COALESCE(NULLIF(DATEREC,''),'2099-12-31'),MTREMISE]))[2]::numeric AS montant_commande_remise,
						0::numeric AS montant_commande_tva,
						(MAX(ARRAY[COALESCE(NULLIF(DATEREC,''),'2099-12-31'),FRAISHT]))[2]::numeric AS montant_commande_port,
						0::numeric AS montant_commande_total,
						0::numeric AS montant_liquidation_ht,
						0::numeric AS montant_liquidation_remise,
						0::numeric AS montant_liquidation_tva,
						0::numeric AS montant_liquidation_port,
						0::numeric AS montant_liquidation_total
					FROM prod_medicagest.FCT10
						LEFT JOIN eco.t_fournisseurs ON t_fournisseurs.code_original = CODEFRS
						LEFT JOIN eco.t_lieux t_lieux_commande ON t_lieux_commande.code_original = 0
						LEFT JOIN eco.t_lieux t_lieux_livraison ON t_lieux_livraison.code_original = 0
						LEFT JOIN eco.t_lieux t_lieux_facturation ON t_lieux_facturation.code_original = 0
						LEFT JOIN eco.t_gestionnaires ON t_gestionnaires.code = 0
						LEFT JOIN eco.t_sites ON t_sites.code_original = 0
					WHERE DATEC >= '2015-01-01'
					GROUP BY 1,2,3,4,5,6
					ORDER BY 1;
					
						
				SELECT base.cti_enable_index('eco', 'i_commandes_1');
				SELECT base.cti_enable_index('eco', 'i_commandes_2');
				SELECT base.cti_enable_index('eco', 'i_commandes_3');
				SELECT base.cti_enable_index('eco', 'i_commandes_4');
				SELECT base.cti_enable_index('eco', 'i_commandes_5');
				SELECT base.cti_enable_index('eco', 'i_commandes_6');
				SELECT base.cti_enable_index('eco', 'i_commandes_7');
				SELECT base.cti_enable_index('eco', 'i_commandes_8');
				
				


				SELECT base.cti_disable_index('eco', 'i_ligne_commandes_1');
				SELECT base.cti_disable_index('eco', 'i_ligne_commandes_2');
				SELECT base.cti_disable_index('eco', 'i_ligne_commandes_3');

				DROP TABLE IF EXISTS w_FLG10;
				CREATE TEMP TABLE w_FLG10 AS 
				SELECT NOCOM,
					rank() OVER (PARTITION BY NOCOM ORDER BY FLCLEUNIK) AS NOLIG,
					FLCLEUNIK,
					flg10.CDART,
					flg10.LIBEL,
					flg10.QTCOM::numeric,
					PRIXC::numeric,
					flg10.CONDT::numeric,
					QTLIV::numeric,
					flg10.PRIXB::numeric,
					FLG10.SAISIE,
					MNTTTC::numeric,
					MVCLEUNIK,
					flg10.REFCAT,
					FRSCOMBL,
					REMISEL,
					MTREMISEL,
					COALESCE(DATEF,'20991231') AS DATEF,
					CASE WHEN MNTTTC::numeric != 0 THEN base.cti_division(MNTTTC::numeric,QTLIV::numeric*flg10.PRIXB::numeric)*flg10.QTCOM::numeric*flg10.PRIXB::numeric - flg10.QTCOM::numeric*flg10.PRIXB::numeric + MNTREMISE::numeric ELSE 0 END AS MNTTVA,
					CASE WHEN MNTTTC::numeric != 0 THEN MNTTTC::numeric - (flg10.QTCOM::numeric*flg10.PRIXB::numeric) ELSE 0 END AS MNTTVAL,
					CASE WHEN MNTTTC::numeric != 0 THEN MNTREMISE::numeric ELSE flg10.QTCOM::numeric*flg10.PRIXB::numeric END AS MNTREMISE,
					RIGHT(FRSCOMBL,-8) AS NUMLIV,
					cdtva
				FROM prod_medicagest.FLG10 
				JOIN 
					(
					SELECT CODEFRS, NOCOM, NUMBL, MAX(DATEF) AS DATEF
					FROM prod_medicagest.FCT10
					GROUP BY 1,2,3
					) FCT10 ON FCT10.CODEFRS || FCT10.NOCOM || NUMBL = FRSCOMBL
					LEFT JOIN prod_medicagest.art01 ON flg10.cdart = art01.cdart
				;
				
				VACUUM ANALYSE w_FLG10;
				
				-- Quand la quantité livrée est supérieure à la quantité commandée, il faut prendre la quantité livrée
				UPDATE w_FLG10 SET
					QTCOM = QTLIV,
					MNTTVA = CASE WHEN MNTTTC::numeric != 0 THEN base.cti_division(MNTTTC::numeric,QTLIV::numeric*PRIXB::numeric)*QTLIV::numeric*PRIXB::numeric - QTLIV::numeric*PRIXB::numeric + MNTREMISE::numeric ELSE 0 END,
					MNTTVAL = CASE WHEN MNTTTC::numeric != 0 THEN MNTTTC::numeric - (QTLIV::numeric*PRIXB::numeric) ELSE 0 END,
					MNTREMISE = CASE WHEN MNTTTC::numeric != 0 THEN MNTREMISE::numeric ELSE QTLIV::numeric*PRIXB::numeric END
				WHERE QTCOM < QTLIV
				;
				

				CREATE INDEX mvtcleunik_i ON w_FLG10 using btree(MVCLEUNIK);
				
				TRUNCATE eco.p_lignes_commandes;

				INSERT INTO eco.p_lignes_commandes(
					code_original,
					commande_id,
					ligne_commande,
					texte,
					article_id,
					unite_approvisionnement_id,
					compte_id,
					ucd_id,
					lpp_id,
					
					quantite_approvisionnement,
					prix_unitaire_approvisionnement,
					multiplicateur_stockage,
					quantite_stockage,
					prix_unitaire_stockage,
					
					montant_commande_ht,
					montant_commande_remise,
					montant_commande_tva,
					montant_commande_port,
					montant_commande_ttc,

					quantite_livraison_approvisionnement,
					quantite_livraison_stockage,
					montant_livraison_ht,
					montant_livraison_tva,
					montant_livraison_ttc,
					etat_livraison,

					montant_liquidation_ht,
					montant_liquidation_remise,
					montant_liquidation_tva,
					montant_liquidation_port,
					montant_liquidation_ttc,
					etat_liquidation)
				SELECT
					FLCLEUNIK AS code_original,
					COALESCE(p_commandes.oid,0) AS commande_id,
					NOLIG AS ligne_commande,
					LIBEL AS texte,
					COALESCE(t_articles.oid, 0) AS article_id,
					0::bigint AS unite_approvisionnement_id,
					compte_id, --possibilite de remonter le compte present dans le reglement 
					COALESCE(t_ucd.oid, t_articles.ucd_id, 0) AS ucd_id,
					COALESCE(t_lpp.oid, t_articles.lpp_id, 0) AS lpp_id,
					
					QTCOM * CONDT AS quantite_approvisionnement,
					PRIXB AS prix_unitaire_approvisionnement,
					CONDT AS multiplicateur_stockage,
					QTLIV AS quantite_stockage,
					PRIXC AS prix_unitaire_stockage,

					CASE WHEN PRIXB::numeric <> 0 THEN QTCOM::numeric*PRIXB::numeric ELSE QTCOM::numeric*PRIXC::numeric END AS montant_commande_ht,
					MNTREMISE AS montant_commande_remise,
					MNTTVA AS montant_commande_tva,
					0::numeric AS montant_commande_port,
					CASE WHEN mntttc::numeric = 0 THEN
					     prixc::numeric * (1 + (CASE CDTVA WHEN 1 THEN 0 WHEN 2 THEN 2.1 WHEN 3 THEN 5.5 WHEN 4 THEN 20 WHEN 5 THEN 10 ELSE 0 END) * 0.01) * QTCOM
						 ELSE base.cti_division(MNTTTC,QTLIV*PRIXB)*QTCOM*PRIXB 
					END AS montant_commande_ttc,

					QTLIV AS quantite_livraison_approvisionnement,
					QTLIV AS quantite_livraison_stockage,
					QTLIV*PRIXB AS montant_livraison_ht,
					CASE WHEN QTLIV != 0 THEN MNTTVAL ELSE 0 END AS montant_livraison_tva,
					CASE WHEN QTLIV != 0 THEN MNTTTC ELSE 0 END AS montant_livraison_ttc,
					CASE WHEN QTLIV = 0 THEN 'N'
						WHEN QTLIV = QTCOM THEN 'T'
						WHEN QTLIV <> QTCOM THEN 'P'
						END
						AS etat_livraison,
					CASE WHEN NULLIF(DATEF,'') IS NOT NULL THEN QTLIV*PRIXB ELSE 0 END as montant_liquidation_ht,
					CASE WHEN NULLIF(DATEF,'') IS NOT NULL THEN MNTREMISE ELSE 0 END as montant_liquidation_remise,
					CASE WHEN NULLIF(DATEF,'') IS NOT NULL THEN MNTTVAL ELSE 0 END as montant_liquidation_tva,
					0::numeric AS montant_liquidation_port,
					CASE WHEN NULLIF(DATEF,'') IS NOT NULL THEN MNTTTC END AS montant_liquidation_ttc,
					CASE WHEN NULLIF(DATEF,'') IS NOT NULL THEN 'T' ELSE 'N' END AS etat_liquidation
				FROM w_FLG10
					JOIN eco.p_commandes ON NOCOM = p_commandes.code_original
					LEFT JOIN eco.t_articles ON CDART = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN base.t_ucd ON ucd_id = t_ucd.oid AND t_ucd.oid != 0
					LEFT JOIN base.t_lpp ON lpp_id = t_lpp.oid AND t_lpp.oid != 0
					;
					
				SELECT base.cti_enable_index('eco', 'i_ligne_commandes_1');
				SELECT base.cti_enable_index('eco', 'i_ligne_commandes_2');
				SELECT base.cti_enable_index('eco', 'i_ligne_commandes_3');
				
				-- Taux tva selon article
				UPDATE eco.p_lignes_commandes
				SET taux_tva = t_articles.taux_tva_en_cours
				FROM eco.t_articles
				WHERE article_id = t_articles.oid AND
					p_lignes_commandes.taux_tva = 0
					;
				
				DROP TABLE IF EXISTS W_COM_TOT;
				CREATE TEMP TABLE w_COM_TOT AS 
				SELECT 
						commande_id,
						SUM(p_lignes_commandes.montant_commande_ht) AS montant_commande_ht,
						SUM(p_lignes_commandes.montant_commande_remise) AS montant_commande_remise,
						SUM(p_lignes_commandes.montant_commande_tva) AS montant_commande_tva,
						SUM(p_lignes_commandes.montant_commande_ttc) AS montant_commande_total,
						SUM(p_lignes_commandes.montant_liquidation_ht) AS montant_liquidation_ht,
						SUM(p_lignes_commandes.montant_liquidation_remise) AS montant_liquidation_remise,
						SUM(p_lignes_commandes.montant_liquidation_tva) AS montant_liquidation_tva,
						SUM(p_lignes_commandes.montant_liquidation_ttc) AS montant_liquidation_total
					FROM eco.p_lignes_commandes
					GROUP BY 1
					;
					
				VACUUM ANALYSE w_COM_TOT;
					
				CREATE INDEX commande_id_i ON w_COM_TOT using btree(commande_id);
				
				-- maj des commandes 
				UPDATE eco.p_commandes
				SET 
					montant_commande_ht = w_COM_TOT.montant_commande_ht,
					montant_commande_remise = w_COM_TOT.montant_commande_remise,
					montant_commande_tva = w_COM_TOT.montant_commande_tva,
					montant_commande_total = w_COM_TOT.montant_commande_total,
					montant_liquidation_ht = w_COM_TOT.montant_liquidation_ht,
					montant_liquidation_remise = w_COM_TOT.montant_liquidation_remise,
					montant_liquidation_tva = w_COM_TOT.montant_liquidation_tva,
					montant_liquidation_total = w_COM_TOT.montant_liquidation_total
				FROM 
					w_COM_TOT
				WHERE commande_id = p_commandes.oid
				;
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Mouvements">
			<sqlcmd><![CDATA[
				-- mouvements
							
				
				-- mouvements
							
				TRUNCATE eco.p_mouvements_articles;

				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_1');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_2');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_3');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_4');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_5');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_6');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_7');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_8');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_9');
				SELECT base.cti_disable_index('eco', 'i_mouvements_articles_10');

				DROP SEQUENCE IF EXISTS w_MVT_sequence;
				CREATE TEMP SEQUENCE w_mvt_sequence; 

				DROP TABLE IF EXISTS w_mvt05;
				CREATE TEMP TABLE w_mvt05 AS
				SELECT
					MVCLEUNIK::numeric,
					date(DATEM) as DATEM,
					TPMVT,
					PATIENT,
					QTUMV::numeric,
					QTEUC::numeric,
					PUMP::numeric,
					PUMPTTC::numeric,
					COALESCE(NULLIF(PRIXU,''),'0'::text)::numeric AS PRIXU,
					replace(UTILISATEUR,' ','_') AS UTILISATEUR,
					CDSRV,
					CDART,
					CDCPT,
					CODEFRS,
					TVA::numeric,
					''::text AS NOCOM,
					MNTREMISE::numeric,
					0 AS ligne,
					''::text AS SEJOUR
				FROM prod_medicagest.MVT05
				ORDER BY MVCLEUNIK  
				;

				VACUUM ANALYSE w_MVT05;

				CREATE INDEX mvtcleunik_i_mvt ON w_MVT05 using btree(MVCLEUNIK);
				
				
				-- Le séjour n'est pas toujours fourni
				SELECT base.cti_execute('
				UPDATE w_mvt05
				SET SEJOUR = MVT05.SEJOUR
				FROM prod_medicagest.MVT05
				WHERE w_MVT05.MVCLEUNIK = MVT05.MVCLEUNIK AND
					MVT05.SEJOUR <> ''''
				',1)
				WHERE ('sejour' IN (SELECT column_name FROM information_schema.columns WHERE table_schema = 'prod_medicagest' AND table_name = 'mvt05'))
				;
				
				UPDATE w_MVT05 SET
					NOCOM = w_FLG10.NOCOM,
					ligne = w_FLG10.NOLIG
				FROM w_FLG10
				WHERE w_FLG10.MVCLEUNIK = w_MVT05.MVCLEUNIK
				;
				
				INSERT INTO eco.p_mouvements_articles(
					oid,
					code_original,
					date, 
					sens_mouvement,
					type_mouvement_id, 
					texte, 
					gestionnaire_id, 
					lieu_id, 
					unite_fonctionnelle_id, 
					article_id, 
					compte_id, 
					fournisseur_id,
					commande_id,
					ligne_commande,
					site_id,
					lpp_id,
					ucd_id,
					prix_unitaire, 
					entree_quantite, 
					sortie_quantite,
					entree_montant_ht,
					entree_montant, 
					sortie_montant_ht,
					sortie_montant,
					prix_unitaire_calcule,
					stock_quantite_debut,
					stock_quantite_fin,
					date_fin,
					est_premier_jour,
					est_dernier_jour,
					no_sejour
					)
				SELECT 
					nextval(' w_MVT_sequence'::regclass) AS sequence,
					MVCLEUNIK AS code_original,
					DATEM AS date, --autre possible IPTDAT_0 mais imputation
					CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN 'E' ELSE 'S' END AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					PATIENT || ' (' || t_articles.code || ')' AS texte,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					COALESCE(t_lieux.oid,0) AS lieu_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid,0) AS article_id,
					COALESCE(t_compte.oid,t_articles.compte_id,0) AS compte_id,
					COALESCE(t_fournisseurs.oid,t_articles.fournisseur_principal_id,0) AS fournisseur_id,
					COALESCE(p_commandes.oid,0) AS commande_id,
					ligne,
					COALESCE(t_sites.oid,0) AS site_id,
					COALESCE(t_articles.lpp_id,0) AS lppid,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					PUMP AS prix_unitaire,
					CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END AS entree_quantite,
					CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END AS sortie_quantite,
					CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV *(CASE WHEN (TPMVT = 'E' OR TPMVT='e') AND PUMP = 0 THEN PRIXU ELSE PUMP END) - MNTREMISE ELSE 0 END AS entree_montant_ht,
					CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN (QTUMV *(CASE WHEN (TPMVT = 'E' OR TPMVT='e') AND PUMP = 0 THEN PRIXU ELSE PUMP END) - MNTREMISE)*((100+TVA)/100) ELSE 0 END AS entree_montant,
					CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN PUMP*(CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END) ELSE 0 END AS sortie_montant_ht,
					CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN PUMPTTC*(CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END) ELSE 0 END AS sortie_montant,
					PUMP AS prix_unitaire_calcule,
					QTEUC AS stock_quantite_debut,
					QTEUC + CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV ELSE -QTUMV END AS stock_quantite_fin,
					LEAD(DATEM) OVER (PARTITION BY CDART ORDER BY DATEM,MVCLEUNIK) AS date_fin,
					CASE WHEN (LAG(DATEM) OVER (PARTITION BY CDART ORDER BY DATEM,MVCLEUNIK)) != DATEM THEN 1 ELSE 0 END AS est_premier_jour,
					CASE WHEN (LEAD(DATEM) OVER (PARTITION BY CDART ORDER BY DATEM,MVCLEUNIK)) != DATEM THEN 1 ELSE 0 END AS est_dernier_jour,
					SEJOUR
				FROM w_MVT05
					LEFT JOIN eco.t_types_mouvements ON TPMVT = t_types_mouvements.code_original
					LEFT JOIN eco.t_gestionnaires ON replace(UTILISATEUR,' ','_') = t_gestionnaires.code_original
					LEFT JOIN eco.t_lieux ON w_MVT05.CDSRV = t_lieux.code_original
					LEFT JOIN prod_medicagest.SER82 ON w_MVT05.CDSRV = SER82.CDSRV 
					LEFT JOIN eco.t_unites_fonctionnelles ON CDSEC = t_unites_fonctionnelles.code_original
					LEFT JOIN eco.t_articles ON CDART = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN eco.t_compte ON CDCPT = t_compte.code_original
					LEFT JOIN eco.t_sites ON  w_MVT05.CDSRV = t_sites.code_original
					LEFT JOIN eco.t_fournisseurs ON CODEFRS = t_fournisseurs.code_original
					LEFT JOIN eco.p_commandes ON NOCOM = p_commandes.code_original
				WHERE DATEM >= date('2015-01-01')
				ORDER BY DATEM,w_MVT05.MVCLEUNIK;

				-- commandes d'apres texte
				UPDATE eco.p_mouvements_articles
				SET 
					commande_id = p_commandes.oid,
					ligne_commande = p_lignes_commandes.ligne_commande
				FROM 
					eco.p_lignes_commandes 
					JOIN eco.p_commandes ON commande_id = p_commandes.oid
					JOIN eco.t_articles ON article_id = t_articles.oid
				WHERE
					p_mouvements_articles.texte like 'BL%'
					AND p_mouvements_articles.commande_id = 0
					AND t_articles.code = LEFT(split_part(p_mouvements_articles.texte,'(',2),-1)
					AND p_commandes.numero = split_part(split_part(p_mouvements_articles.texte,'CDE ',2),' ',1)
				;
					
			
				UPDATE eco.p_lignes_commandes
				SET	
					montant_commande_ttc = montant_commande_ht * base.cti_division(entree_montant,entree_montant_ht)
				FROM eco.p_mouvements_articles
				WHERE 
					p_lignes_commandes.commande_id = p_mouvements_articles.commande_id 
					AND p_lignes_commandes.article_id = p_mouvements_articles.article_id
					AND montant_commande_ht != 0 and montant_commande_ttc = 0
				;
			
				
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_1');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_2');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_3');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_4');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_5');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_6');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_7');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_8');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_9');
				SELECT base.cti_enable_index('eco', 'i_mouvements_articles_10');
				
				UPDATE eco.p_mouvements_articles SET
					entree_quantite = 0 - entree_quantite,
					sortie_quantite = 0 - sortie_quantite,
					entree_montant = 0 - entree_montant,
					sortie_montant = 0 - sortie_montant,
					entree_montant_ht = 0 - entree_montant_ht,
					sortie_montant_ht = 0 - sortie_montant_ht,
					sortie_montant_original_ttc = 0 - sortie_montant_original_ttc,
					sortie_montant_original_ht = 0 - sortie_montant_original_ht
				FROM eco.t_types_mouvements
				WHERE type_mouvement_id = t_types_mouvements.oid AND
					t_types_mouvements.particularite_inverser_signe = '1';
					
			
			]]></sqlcmd>
		</NODE>
		
		<NODE label="Stocks">
			<sqlcmd><![CDATA[
				-- stocks
				SELECT base.cti_disable_index('eco', 'i_stock_1');
				SELECT base.cti_disable_index('eco', 'i_stock_2');
				SELECT base.cti_disable_index('eco', 'i_stock_3');
				SELECT base.cti_disable_index('eco', 'i_stock_4');
				SELECT base.cti_disable_index('eco', 'i_stock_5');

		
				
				-- insertion 
				TRUNCATE eco.p_stock
				;

				SELECT base.cti_disable_index('eco', 'i_stock_1');
				SELECT base.cti_disable_index('eco', 'i_stock_2');
				SELECT base.cti_disable_index('eco', 'i_stock_3');
				SELECT base.cti_disable_index('eco', 'i_stock_4');
				SELECT base.cti_disable_index('eco', 'i_stock_5');

		
				DROP TABLE IF EXISTS w_ART01;
				CREATE TEMP TABLE w_ART01 AS
				SELECT
					CDART,
					COALESCE(NULLIF(QTEUC,''),'0')::numeric AS QTEUC,
					COALESCE(NULLIF(PUMP,''),'0')::numeric AS PUMP,
					COALESCE(NULLIF(PUMPTTC,''),'0')::numeric AS PUMPTTC,
					CDCPT
				FROM prod_medicagest.ART01
				;

				-- etats
				INSERT INTO eco.p_stock
					(
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					site_id,
					lieu_id,
					date_debut,
					date_fin,
					entree_quantite,
					entree_montant,
					sortie_quantite,
					sortie_montant,
					pump,
					stock_quantite_debut,
					stock_quantite_fin,
					stock_valeur_debut,
					stock_valeur_debut_ttc,
					stock_valeur_fin,
					stock_valeur_fin_ttc
					)
				SELECT 
					t_articles.oid,
					COALESCE(t_compte.oid,compte_id, 0) AS compte_id,
					ucd_id,
					lpp_id,
					0 as site_id,
					COALESCE(t_lieux.oid,0),
					date_trunc('month',now() - interval '1 day'),
					date_trunc('month',now() - interval '1 day') + interval '1 month' - interval '1 day',
					COALESCE(SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END),0) as entree_quantite,
					COALESCE(SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV *(CASE WHEN TPMVT = 'E' THEN PRIXU ELSE w_MVT05.PUMP END) ELSE 0 END),0) AS entree_montant_ht,
					COALESCE(SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END),0) AS sortie_quantite,
					COALESCE(SUM(w_MVT05.PUMP*CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END),0) AS sortie_montant,
					MAX(w_ART01.PUMP) AS pump,
					MAX(w_ART01.QTEUC) - COALESCE(SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END) 
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END),0) AS stock_quantite_debut,
					MAX(w_ART01.QTEUC) AS stock_quantite_fin,
					MAX(w_ART01.QTEUC * w_ART01.PUMP)
					 - COALESCE(SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END)
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END),0)
					*  COALESCE((MIN(ARRAY[MVCLEUNIK,w_MVT05.PUMP]))[2],MAX(w_ART01.PUMP)) AS stock_valeur_debut,
					MAX(w_ART01.QTEUC * w_ART01.PUMPTTC)
					 - COALESCE(SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END)
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END),0)
					*  COALESCE((MIN(ARRAY[MVCLEUNIK,w_MVT05.PUMPTTC]))[2],MAX(w_ART01.PUMPTTC)) AS stock_valeur_debut_ttc,
					MAX(w_ART01.QTEUC * w_ART01.PUMP) AS stock_valeur_fin,
					MAX(w_ART01.QTEUC * w_ART01.PUMPTTC) AS stock_valeur_fin_ttc
				FROM w_ART01
					LEFT JOIN w_MVT05 ON w_MVT05.CDART = w_ART01.CDART AND date_trunc('month',now() - interval '1 day') = date_trunc('month',DATEM)
					JOIN eco.t_articles ON w_ART01.CDART = t_articles.code_original
					LEFT JOIN eco.t_compte ON w_ART01.CDCPT = t_compte.code_original
					LEFT JOIN eco.t_lieux ON 0 = t_lieux.code_original
					LEFT JOIN eco.t_sites ON 0 = t_sites.code_original
				GROUP BY 1,2,3,4,5,6,7,8
				;

				-- etat des mouvements
				INSERT INTO eco.p_stock
					(
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					site_id,
					lieu_id,
					date_debut,
					date_fin,
					entree_quantite,
					entree_montant,
					sortie_quantite,
					sortie_montant,
					pump,
					stock_quantite_debut,
					stock_quantite_fin,
					stock_valeur_debut,
					stock_valeur_debut_ttc,
					stock_valeur_fin,
					stock_valeur_fin_ttc
					)
				SELECT 
					t_articles.oid,
					COALESCE(t_compte.oid,compte_id, 0) AS compte_id,
					ucd_id,
					lpp_id,
					0 as site_id,
					COALESCE(t_lieux.oid,0),
					date_trunc('month',DATEM),
					date_trunc('month',DATEM) + interval '1 month' - interval '1 day',
					SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END) as entree_quantite,
					SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV *(CASE WHEN TPMVT = 'E' THEN PRIXU ELSE PUMP END) ELSE 0 END) AS entree_montant_ht,
					SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END) AS sortie_quantite,
					SUM(PUMP*CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV::numeric ELSE QTUMV::numeric END ELSE 0 END) AS sortie_montant,
					(MAX(ARRAY[MVCLEUNIK,PUMP]))[2] AS pump,
					(MIN(ARRAY[MVCLEUNIK,QTEUC]))[2] AS stock_quantite_debut,
					(MIN(ARRAY[MVCLEUNIK,QTEUC]))[2]
					+ SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END)  
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END) 
					AS stock_quantite_fin,
					(MIN(ARRAY[MVCLEUNIK,QTEUC]))[2] *(MIN(ARRAY[MVCLEUNIK,PUMP]))[2] AS stock_valeur_debut,
					(MIN(ARRAY[MVCLEUNIK,QTEUC]))[2] *(MIN(ARRAY[MVCLEUNIK,PUMPTTC]))[2] AS stock_valeur_debut_ttc,
					((MIN(ARRAY[MVCLEUNIK,QTEUC]))[2]
					+ SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END)  
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END))*(MAX(ARRAY[MVCLEUNIK,PUMP]))[2] AS stock_valeur_fin,
					((MIN(ARRAY[MVCLEUNIK,QTEUC]))[2]
					+ SUM(CASE WHEN TPMVT IN ('R','E','e') OR (TPMVT = 'C' AND QTUMV > 0) THEN QTUMV  ELSE 0 END)  
					- SUM(CASE WHEN TPMVT NOT IN ('R','E','e','C') OR (TPMVT = 'C' AND QTUMV < 0) THEN CASE WHEN TPMVT = 'C' THEN -QTUMV ELSE QTUMV END ELSE 0 END))*(MAX(ARRAY[MVCLEUNIK,PUMPTTC]))[2] AS stock_valeur_fin_ttc
				FROM w_MVT05
					JOIN eco.t_articles ON CDART = t_articles.code_original
					LEFT JOIN eco.t_compte ON CDCPT = t_compte.code_original
					LEFT JOIN eco.t_lieux ON 0 = t_lieux.code_original
					LEFT JOIN eco.t_sites ON 0 = t_sites.code_original
				WHERE date_trunc('month',DATEM) != date_trunc('month',now()::date)
				GROUP BY 1,2,3,4,5,6,7,8
				;

				
				-- ajout des stocks mensuels manquants
				SELECT base.cti_execute('
				INSERT INTO eco.p_stock
				(
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					site_id,
					lieu_id,
					date_debut,
					date_fin,
					entree_quantite,
					entree_montant,
					sortie_quantite,
					sortie_montant,
					pump,
					stock_quantite_debut,
					stock_quantite_fin,
					stock_valeur_debut,
					stock_valeur_debut_ttc,
					stock_valeur_fin,
					stock_valeur_fin_ttc
					)
				SELECT 
					p_stock.article_id,
					p_stock.compte_id,
					p_stock.ucd_id,
					p_stock.lpp_id,
					p_stock.site_id,
					p_stock.lieu_id,
					date(date_trunc(''month'',p_stock.date_debut) - interval ''1 month'') AS date_debut,
					date(date_trunc(''month'',p_stock.date_debut) - interval ''1 day'') AS date_fin,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					p_stock.pump,
					p_stock.stock_quantite_debut,
					p_stock.stock_quantite_debut,
					p_stock.stock_valeur_debut,
					p_stock.stock_valeur_debut_ttc,
					p_stock.stock_valeur_debut,
					p_stock.stock_valeur_debut_ttc
				FROM eco.p_stock
				LEFT JOIN eco.p_stock p_stock_prev ON
					p_stock.site_id = p_stock_prev.site_id AND
					p_stock.lieu_id = p_stock_prev.lieu_id AND
					p_stock.article_id = p_stock_prev.article_id AND
					date(date_trunc(''month'',p_stock.date_debut) - interval ''1 day'') = p_stock_prev.date_fin
				WHERE 
					p_stock.date_debut <= now() AND
					p_stock.date_fin >= ''2015-01-01'' AND
					p_stock.stock_quantite_debut != 0 AND
					p_stock_prev.article_id IS NULL
				',200)
				;

				SELECT base.cti_execute('
				INSERT INTO eco.p_stock
				(
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					site_id,
					lieu_id,
					date_debut,
					date_fin,
					entree_quantite,
					entree_montant,
					sortie_quantite,
					sortie_montant,
					pump,
					stock_quantite_debut,
					stock_quantite_fin,
					stock_valeur_debut,
					stock_valeur_debut_ttc,
					stock_valeur_fin,
					stock_valeur_fin_ttc
					)
				SELECT 
					p_stock.article_id,
					p_stock.compte_id,
					p_stock.ucd_id,
					p_stock.lpp_id,
					p_stock.site_id,
					p_stock.lieu_id,
					date(date_trunc(''month'',p_stock.date_debut) + interval ''1 month'') AS date_debut,
					date(date_trunc(''month'',p_stock.date_debut) + interval ''2 month'' - interval ''1 day'') AS date_fin,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					p_stock.pump,
					p_stock.stock_quantite_fin,
					p_stock.stock_quantite_fin,
					p_stock.stock_valeur_fin,
					p_stock.stock_valeur_fin_ttc,
					p_stock.stock_valeur_fin,
					p_stock.stock_valeur_fin_ttc
				FROM eco.p_stock
				LEFT JOIN eco.p_stock p_stock_next ON
					p_stock.site_id = p_stock_next.site_id AND
					p_stock.lieu_id = p_stock_next.lieu_id AND
					p_stock.article_id = p_stock_next.article_id AND
					p_stock.date_fin + interval ''1 day'' = p_stock_next.date_debut
				WHERE 
					p_stock.date_debut <= now() AND
					p_stock.date_fin >= ''2015-01-01'' AND
					p_stock.stock_quantite_fin != 0 AND
					p_stock_next.article_id IS NULL
				',200)
				;
				
				SELECT base.cti_enable_index('eco', 'i_stock_1');
				SELECT base.cti_enable_index('eco', 'i_stock_2');
				SELECT base.cti_enable_index('eco', 'i_stock_3');
				SELECT base.cti_enable_index('eco', 'i_stock_4');
				SELECT base.cti_enable_index('eco', 'i_stock_5');
			]]></sqlcmd>
		</NODE>
		
	</NODE>
	<NODE name="POST" label="POST-TRAITEMENTS">
		<sqlcmd><![CDATA[
				VACUUM ANALYSE eco.p_mouvements_articles;
				VACUUM ANALYSE eco.p_stock;
				
				SELECT eco.cti_reorganize_sejour();
				SELECT eco.cti_update_mvt_qte_stock();
				SELECT eco.cti_update_mvt_mnt_stock();
			
		]]></sqlcmd>
	</NODE>
	
</ROOT>
