<?xml version="1.0" encoding="ISO-8859-1"?>
<ROOT>
	<NODE name="INIT" label="INITIALISATIONS">
			
		<NODE label="Tables Articles">
			
			<sqlcmd><![CDATA[
			
				-- Pr?paration
				
				
			
				-- Comptes
				INSERT INTO eco.t_compte(code, texte, texte_court, code_original)
				SELECT CO1SKLMS, CO1SKLMS, LEFT(CO1SKLMS,50), CO1SKLMS
				FROM prod_qualiac.SKLMS
				WHERE CO1SKLMS IN (SELECT CO1SKLMS FROM prod_qualiac.SKLMS
				WHERE (ETOSKLMS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')) AND
					CO1SKLMS NOT IN (SELECT code_original FROM eco.t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4;
				
				
				-- unités
				INSERT INTO eco.t_unites (code_original, code, texte, texte_court)
				SELECT NUMSGUNI,NUMSGUNI,INTSGUNI,INRSGUNI
				FROM prod_qualiac.SGUNI
					LEFT JOIN eco.t_unites ON NUMSGUNI = code_original
				WHERE code_original IS NULL
				AND NUMSGUNI = ANY(ARRAY(SELECT DISTINCT UNSSGART FROM prod_qualiac.SGART))
				;
				
				-- ATC
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(NUMSGARS), UPPER(NUMSGARS), MAX(INTSGARS), MAX(INRSGARS) 
				FROM prod_qualiac.SGARS
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(NUMSGARS)
				WHERE code_original IS NULL 
					AND NUMSGARS = ANY (ARRAY(SELECT ARSSGART from prod_qualiac.SGART))
				GROUP BY 1,2
				ORDER BY 1
				;
				
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(NUMSGARE), UPPER(NUMSGARE), MAX(INTSGARE), MAX(INRSGARE) 
				FROM prod_qualiac.SGARE
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(NUMSGARE)
				WHERE code_original IS NULL 
					AND NUMSGARE = ANY (ARRAY(SELECT ARESGART from prod_qualiac.SGART))
				GROUP BY 1,2
				ORDER BY 1
				;

				-- Familles d'articles
				INSERT INTO eco.t_familles_articles(code_original, code, texte, texte_court )
				SELECT UPPER(NUMSGARM), UPPER(NUMSGARM), MAX(INTSGARM), MAX(INRSGARM) 
				FROM prod_qualiac.SGARM
				LEFT JOIN eco.t_familles_articles ON code_original = UPPER(NUMSGARM)
				WHERE code_original IS NULL 
					AND NUMSGARM = ANY (ARRAY(SELECT ARMSGART from prod_qualiac.SGART))
				GROUP BY 1,2
				ORDER BY 1
				;
				
				-- Types
				INSERT INTO eco.t_types_articles(code_original, code, texte, texte_court )
				SELECT LEFT(NUMSGART,1),LEFT(NUMSGART,1),LEFT(NUMSGART,1),LEFT(NUMSGART,1)
				FROM prod_qualiac.SGART
					LEFT JOIN eco.t_types_articles ON LEFT(NUMSGART,1) = code_original
				WHERE code_original IS NULL
				GROUP BY 1,2,3,4
				ORDER BY 1
				;
				
				-- Categories d'articles
				INSERT INTO eco.t_categories_articles(code_original, code, texte, texte_court )
				SELECT UPPER(CATSGATA), CATSGATA, CATSGATA, CATSGATA
				FROM prod_qualiac.SGATA
					LEFT JOIN eco.t_categories_articles ON code_original = UPPER(CATSGATA)
				WHERE code_original IS NULL 
					AND CATSGATA !='.'
				GROUP BY 1,2
				ORDER BY 1
				;
				
				-- Articles (+STFAR ?)
				INSERT INTO eco.t_articles(code_original, code, texte, texte_court)
				SELECT 
					NUMSGART,
					NUMSGART,
					INTSGART,
					COALESCE(NULLIF(INRSGART,'.'),LEFT(INTSGART,50))
				FROM prod_qualiac.SGART
					LEFT JOIN eco.t_articles ON code_original = NUMSGART
				WHERE code_original IS NULL
					AND NUMSGART = ANY(ARRAY(
						SELECT DISTINCT ARTSKLMS
						FROM prod_qualiac.SKLMS
						WHERE ETOSKLMS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
						)
					--AND ETASTFAR != 'S'
				ORDER BY 1;
				;
					
				-- gere en stock (fait par rapport au plus grand nomùbre de stock sur période car dépendant pas de l'article mais du lot)
				UPDATE eco.t_articles
				SET gere_en_stock = CASE WHEN MOSSKSTI_max = 'N' THEN 1 ELSE 0 END
				FROM (
					SELECT ARTSKSTI, (MAX(ARRAY[DTISKSTI::text, MOSSKSTI::text]))[2] AS MOSSKSTI_max
					FROM prod_qualiac.SKSTI
					WHERE DTISKSTI::date >= '[ENV_ECO_ANNEEDEBUT]0101'
					AND (ETSSKSTI = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					GROUP BY 1) sub
				WHERE t_articles.code_original = ARTSKSTI
					AND gere_en_stock != CASE WHEN MOSSKSTI_max = 'N' THEN 1 ELSE 0 END
				;
				-- ATC
				
				UPDATE eco.t_articles
				SET classification_atc_id = t_classification_atc.oid
				FROM prod_qualiac.SGART
					JOIN eco.t_classification_atc ON ARSSGART = code
				WHERE NUMSGART = t_articles.code_original
				;
				
				-- Standard ATC
				SELECT eco.cti_reorganize_classification_atc();
			
			
				-- comptes et tva
				UPDATE eco.t_articles
				SET 
					taux_tva_en_cours = TVVSGTAV::int/1000
				FROM prod_qualiac.SGTAV
				WHERE ARTSGTAV = code_original
					AND taux_tva_en_cours <> TVVSGTAV
					AND TVVSGTAV ~ '[1-9][0-9]*'
					AND ARTSGTAV != ''
					AND (ETSSGTAV = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				;
				
				
				-- unites
				UPDATE eco.t_articles
				SET 
					unite_distribution_id = t_unites.oid
				FROM prod_qualiac.SKLMS
					LEFT JOIN eco.t_unites ON UCOSKLMS = t_unites.code_original
				WHERE ARTSKLMS = t_articles.code_original
					AND (ETOSKLMS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND t_unites.oid != unite_distribution_id
				;
				
				-- types
				UPDATE eco.t_articles
				SET 
					type_id = t_types_articles.oid
				FROM prod_qualiac.SGART
					LEFT JOIN eco.t_types_articles ON LEFT(NUMSGART,1) = t_types_articles.code_original
				WHERE NUMSGART = t_articles.code_original
					AND t_types_articles.oid != type_id
				;
		
				-- categories
				UPDATE eco.t_articles
				SET 
					categorie_id = t_categories_articles.oid
				FROM prod_qualiac.SGATA
					LEFT JOIN eco.t_categories_articles ON CATSGATA = t_categories_articles.code_original
				WHERE ARTSGATA = t_articles.code_original
					AND (ETSSGATA = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND t_categories_articles.oid != categorie_id
				;
				-- autres
				 
				 -- maj des code, textes, sections


				UPDATE eco.t_articles SET
					type_code = t_types_articles.code,
					type_texte = t_types_articles.texte_court,
					type_section_id = t_types_articles.section_id,
					type_section_code = t_types_articles.section_code,
					type_section_texte = t_types_articles.section_texte,
					
					famille_code = t_familles_articles.code,
					famille_texte = t_familles_articles.texte_court,
					famille_section_id = t_familles_articles.section_id,
					famille_section_code = t_familles_articles.section_code,
					famille_section_texte = t_familles_articles.section_texte,

					sous_famille_code = t_sous_familles_articles.code,
					sous_famille_texte = t_sous_familles_articles.texte_court,
					sous_famille_section_id = t_sous_familles_articles.section_id,
					sous_famille_section_code = t_sous_familles_articles.section_code,
					sous_famille_section_texte = t_sous_familles_articles.section_texte,

					categorie_code = t_categories_articles.code,
					categorie_texte = t_categories_articles.texte_court,
					categorie_section_id = t_categories_articles.section_id,
					categorie_section_code = t_categories_articles.section_code,
					categorie_section_texte = t_categories_articles.section_texte,

					sous_categorie_code = t_sous_categories_articles.code,
					sous_categorie_texte = t_sous_categories_articles.texte_court,
					sous_categorie_section_id = t_sous_categories_articles.section_id,
					sous_categorie_section_code = t_sous_categories_articles.section_code,
					sous_categorie_section_texte = t_sous_categories_articles.section_texte,

					classification_atc_code = t_classification_atc.code,
					classification_atc_texte = t_classification_atc.texte_court,
					classification_atc_section_id = t_classification_atc.section_id,
					classification_atc_section_code = t_classification_atc.section_code,
					classification_atc_section_texte = t_classification_atc.section_texte,
					classification_atc_1_id = t_classification_atc.classification_atc_1_id,
					classification_atc_1_code = t_classification_atc.classification_atc_1_code,
					classification_atc_1_texte = t_classification_atc.classification_atc_1_texte,
					classification_atc_2_id = t_classification_atc.classification_atc_2_id,
					classification_atc_2_code = t_classification_atc.classification_atc_2_code,
					classification_atc_2_texte = t_classification_atc.classification_atc_2_texte,
					classification_atc_3_id = t_classification_atc.classification_atc_3_id,
					classification_atc_3_code = t_classification_atc.classification_atc_3_code,
					classification_atc_3_texte = t_classification_atc.classification_atc_3_texte,
					classification_atc_4_id = t_classification_atc.classification_atc_4_id,
					classification_atc_4_code = t_classification_atc.classification_atc_4_code,
					classification_atc_4_texte = t_classification_atc.classification_atc_4_texte,

					unite_stockage_code = t_unites_stockage.code,
					unite_stockage_texte = t_unites_stockage.texte_court,
					unite_stockage_section_id = t_unites_stockage.section_id,
					unite_stockage_section_code = t_unites_stockage.section_code,
					unite_stockage_section_texte = t_unites_stockage.section_texte,

					unite_distribution_code = t_unites_distribution.code,
					unite_distribution_texte = t_unites_distribution.texte_court,
					unite_distribution_section_id = t_unites_distribution.section_id,
					unite_distribution_section_code = t_unites_distribution.section_code,
					unite_distribution_section_texte = t_unites_distribution.section_texte,
					
					compte_code = t_compte.code,
					compte_texte = t_compte.texte_court,
					compte_section_id = t_compte.section_id,
					compte_section_code = t_compte.section_code,
					compte_section_texte = t_compte.section_texte

				FROM eco.t_types_articles ,
					eco.t_familles_articles,
					eco.t_sous_familles_articles,
					eco.t_categories_articles,
					eco.t_sous_categories_articles,
					eco.t_classification_atc,
					eco.t_unites t_unites_stockage,
					eco.t_unites t_unites_distribution,
					eco.t_compte
					
				WHERE type_id = t_types_articles.oid
					AND famille_id = t_familles_articles.oid
					AND sous_famille_id = t_sous_familles_articles.oid
					AND categorie_id = t_categories_articles.oid
					AND sous_categorie_id = t_sous_categories_articles.oid
					AND classification_atc_id = t_classification_atc.oid
					AND unite_stockage_id = t_unites_stockage.oid
					AND unite_distribution_id = t_unites_distribution.oid
					AND compte_id = t_compte.oid
					AND (
						type_code IS DISTINCT FROM t_types_articles.code OR
						type_texte IS DISTINCT FROM t_types_articles.texte_court OR
						type_section_id IS DISTINCT FROM t_types_articles.section_id OR
						type_section_code IS DISTINCT FROM t_types_articles.section_code OR
						type_section_texte IS DISTINCT FROM t_types_articles.section_texte OR
						
						famille_code IS DISTINCT FROM t_familles_articles.code OR
						famille_texte IS DISTINCT FROM t_familles_articles.texte_court OR
						famille_section_id IS DISTINCT FROM t_familles_articles.section_id OR
						famille_section_code IS DISTINCT FROM t_familles_articles.section_code OR
						famille_section_texte IS DISTINCT FROM t_familles_articles.section_texte OR
						
						sous_famille_code IS DISTINCT FROM t_sous_familles_articles.code OR
						sous_famille_texte IS DISTINCT FROM t_sous_familles_articles.texte_court OR
						sous_famille_section_id IS DISTINCT FROM t_sous_familles_articles.section_id OR
						sous_famille_section_code IS DISTINCT FROM t_sous_familles_articles.section_code OR
						sous_famille_section_texte IS DISTINCT FROM t_sous_familles_articles.section_texte OR
						
						categorie_code IS DISTINCT FROM t_categories_articles.code OR
						categorie_texte IS DISTINCT FROM t_categories_articles.texte_court OR
						categorie_section_id IS DISTINCT FROM t_categories_articles.section_id OR
						categorie_section_code IS DISTINCT FROM t_categories_articles.section_code OR
						categorie_section_texte IS DISTINCT FROM t_categories_articles.section_texte OR
						
						sous_categorie_code IS DISTINCT FROM t_sous_categories_articles.code OR
						sous_categorie_texte IS DISTINCT FROM t_sous_categories_articles.texte_court OR
						sous_categorie_section_id IS DISTINCT FROM t_sous_categories_articles.section_id OR
						sous_categorie_section_code IS DISTINCT FROM t_sous_categories_articles.section_code OR
						sous_categorie_section_texte IS DISTINCT FROM t_sous_categories_articles.section_texte OR
						
						t_articles.classification_atc_code IS DISTINCT FROM t_classification_atc.code OR
						t_articles.classification_atc_texte IS DISTINCT FROM t_classification_atc.texte_court OR
						t_articles.classification_atc_section_id IS DISTINCT FROM t_classification_atc.section_id OR
						t_articles.classification_atc_section_code IS DISTINCT FROM t_classification_atc.section_code OR
						t_articles.classification_atc_section_texte IS DISTINCT FROM t_classification_atc.section_texte OR
						t_articles.classification_atc_1_id IS DISTINCT FROM t_classification_atc.classification_atc_1_id OR
						t_articles.classification_atc_1_code IS DISTINCT FROM t_classification_atc.classification_atc_1_code OR
						t_articles.classification_atc_1_texte IS DISTINCT FROM t_classification_atc.classification_atc_1_texte OR
						t_articles.classification_atc_2_id IS DISTINCT FROM t_classification_atc.classification_atc_2_id OR
						t_articles.classification_atc_2_code IS DISTINCT FROM t_classification_atc.classification_atc_2_code OR
						t_articles.classification_atc_2_texte IS DISTINCT FROM t_classification_atc.classification_atc_2_texte OR
						t_articles.classification_atc_3_id IS DISTINCT FROM t_classification_atc.classification_atc_3_id OR
						t_articles.classification_atc_3_code IS DISTINCT FROM t_classification_atc.classification_atc_3_code OR
						t_articles.classification_atc_3_texte IS DISTINCT FROM t_classification_atc.classification_atc_3_texte OR
						t_articles.classification_atc_4_id IS DISTINCT FROM t_classification_atc.classification_atc_4_id OR
						t_articles.classification_atc_4_code IS DISTINCT FROM t_classification_atc.classification_atc_4_code OR
						t_articles.classification_atc_4_texte IS DISTINCT FROM t_classification_atc.classification_atc_4_texte OR

						t_articles.unite_stockage_code IS DISTINCT FROM t_unites_stockage.code OR
						t_articles.unite_stockage_texte IS DISTINCT FROM t_unites_stockage.texte_court OR
						t_articles.unite_stockage_section_id IS DISTINCT FROM t_unites_stockage.section_id OR
						t_articles.unite_stockage_section_code IS DISTINCT FROM t_unites_stockage.section_code OR
						t_articles.unite_stockage_section_texte IS DISTINCT FROM t_unites_stockage.section_texte OR
						
						t_articles.unite_distribution_code IS DISTINCT FROM t_unites_distribution.code OR
						t_articles.unite_distribution_texte IS DISTINCT FROM t_unites_distribution.texte_court OR
						t_articles.unite_distribution_section_id IS DISTINCT FROM t_unites_distribution.section_id OR
						t_articles.unite_distribution_section_code IS DISTINCT FROM t_unites_distribution.section_code OR
						t_articles.unite_distribution_section_texte IS DISTINCT FROM t_unites_distribution.section_texte OR

						t_articles.compte_code IS DISTINCT FROM t_compte.code OR
						t_articles.compte_texte IS DISTINCT FROM t_compte.texte_court OR
						t_articles.compte_section_id IS DISTINCT FROM t_compte.section_id OR
						t_articles.compte_section_code IS DISTINCT FROM t_compte.section_code OR
						t_articles.compte_section_texte IS DISTINCT FROM t_compte.section_texte
					);

					--lpp et ucd
					INSERT INTO base.t_lpp (code, texte, texte_court)
					SELECT 
						NUMSGARP, MAX(INTSGARP), LEFT(MAX(INRSGARP),50) 
					FROM 
						prod_qualiac.SGARP 
					WHERE 1=1 AND
						NUMSGARP NOT IN (SELECT code FROM base.t_lpp) AND
						NUMSGARP = ANY (ARRAY(SELECT ARPSGART from prod_qualiac.SGART)) AND
						NUMSGARP NOT IN ('GHS','NA','.')
					GROUP BY 1
					;
					
					UPDATE eco.t_articles
					SET 
						lpp_id = t_lpp.oid 
					FROM
						prod_qualiac.SGART
						JOIN base.t_lpp ON ARPSGART = t_lpp.code
					WHERE 1=1 AND
						ARPSGART != 'GHS' AND
						NUMSGART = t_articles.code_original AND
						lpp_id != t_lpp.oid
					;

					
			
		]]></sqlcmd>
		</NODE>
		
		
		<NODE label="Tables Fournisseurs">
			<sqlcmd><![CDATA[
			
				-- Types de fournisseurs
				
					
				-- Fournisseurs
				INSERT INTO eco.t_fournisseurs(code_original, code, texte, texte_court)
				SELECT
					NUMOETIE,NUMOETIE, NOMOETIE,NOROETIE
				FROM prod_qualiac.OETIE
					LEFT JOIN eco.t_fournisseurs ON code_original = NUMOETIE
				WHERE NUMOETIE = ANY (SELECT DISTINCT FOUSACDA FROM prod_qualiac.SACDA WHERE ETSSACDA = ANY(string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND code_original IS NULL;
				
				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT PTTOETIA, UPPER(MAX(VILOETIA)), UPPER(MAX(LEFT(VILOETIA,50))), MAX(t_departements.oid)
				FROM prod_qualiac.OETIA
				LEFT JOIN base.t_codes_postaux ON PTTOETIA = t_codes_postaux.code
				JOIN base.t_departements ON 
					PTTOETIA NOT LIKE '97%' AND substr(PTTOETIA,1,2) = t_departements.code OR
					PTTOETIA LIKE '97%' AND substr(PTTOETIA,1,3) = t_departements.code 
				WHERE t_codes_postaux.oid IS NULL AND 
					length(PTTOETIA) = 5
				GROUP BY 1
				;

				UPDATE eco.t_fournisseurs SET
					code = NUMOETIE,
					texte = NOMOETIE,
					texte_court = NOROETIE,
					adresse = COALESCE(trim(AD1OETIA || ' ' || AD2OETIA),''),
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = COALESCE(VILOETIA,''),
					cedex = '',
					telephone = COALESCE(TELOETIA,''),
					fax = COALESCE(FAXOETIA,''),
					email = COALESCE(null,''),
					code_cahpp = '',
					siret = COALESCE(SIROETIA,''),
					iban = COALESCE(substr(IBAOETID,1,4) || ' ' || substr(IBAOETID,5,4) || ' ' || substr(IBAOETID,9,4) || ' ' || substr(IBAOETID,13,4) || ' ' || substr(IBAOETID,17,4) || ' ' || substr(IBAOETID,21,4) || ' ' || substr(IBAOETID,25,4),''),
					bic = COALESCE(BICOETID,''),
					code_comptable = COALESCE(null,NUMOETIE)
				FROM prod_qualiac.OETIE
					JOIN prod_qualiac.OETIA ON NUMOETIE = TIEOETIA
					JOIN prod_qualiac.OETID ON NUMOETIE	= TIEOETID
					LEFT JOIN base.t_codes_postaux ON PTTOETIA = t_codes_postaux.code
				WHERE code_original = NUMOETIE AND
					(
					t_fournisseurs.code IS DISTINCT FROM NUMOETIE OR
					t_fournisseurs.texte IS DISTINCT FROM NOMOETIE OR
					t_fournisseurs.texte_court IS DISTINCT FROM NOROETIE OR
					t_fournisseurs.adresse IS DISTINCT FROM COALESCE(trim(AD1OETIA || ' ' || AD2OETIA),'') OR
					t_fournisseurs.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					t_fournisseurs.ville IS DISTINCT FROM COALESCE(VILOETIA,'') OR
					t_fournisseurs.cedex IS DISTINCT FROM '' OR
					t_fournisseurs.telephone IS DISTINCT FROM COALESCE(TELOETIA,'') OR
					t_fournisseurs.fax IS DISTINCT FROM COALESCE(FAXOETIA,'') OR
					t_fournisseurs.email IS DISTINCT FROM COALESCE(null,'') OR
					t_fournisseurs.code_cahpp IS DISTINCT FROM '' OR
					t_fournisseurs.siret IS DISTINCT FROM COALESCE(SIROETIA,'') OR
					t_fournisseurs.iban IS DISTINCT FROM COALESCE(substr(IBAOETID,1,4) || ' ' || substr(IBAOETID,5,4) || ' ' || substr(IBAOETID,9,4) || ' ' || substr(IBAOETID,13,4) || ' ' || substr(IBAOETID,17,4) || ' ' || substr(IBAOETID,21,4) || ' ' || substr(IBAOETID,25,4),'') OR
					t_fournisseurs.bic IS DISTINCT FROM COALESCE(BICOETID,'') OR
					t_fournisseurs.code_comptable IS DISTINCT FROM COALESCE(null,NUMOETIE)
					)
				;
				
				

				
				DROP TABLE IF EXISTS w_articles_fournisseur_eco;
				CREATE TEMP TABLE w_articles_fournisseur_eco  AS
				SELECT 
					ETSSARAF || '-' || ARTSARAF || '-' || FOUSARAF AS code_original,
					t_articles.oid as article_id,
					t_fournisseurs.oid as fournisseur_id,
					(MAX(Array[DFVSARAF::text,INTSARAF]))[2] AS ref_fournisseur_texte,
					(MAX(Array[DFVSARAF::text,REFSARAF]))[2] AS ref_fournisseur_code,
					(MAX(Array[DFVSARAF::text,CASE WHEN LENGTH(EANSARAF) = 13 AND SUBSTRING(EANSARAF,5,1) = '9' THEN EANSARAF ELSE '' END]))[2] AS code_cip,
				(MAX(Array[DFVSARAF::text,CASE WHEN LENGTH(ITFSARAF) >= 13 THEN  RIGHT(LEFT(ITFSARAF,-1),7)
						WHEN LENGTH(ITFSARAF) = '7' THEN ITFSARAF
					WHEN LENGTH(EANSARAF) >= 13 THEN  RIGHT(LEFT(EANSARAF,-1),7)
						WHEN LENGTH(EANSARAF) = '7' THEN EANSARAF ELSE '' END]))[2] as ucd_code,
				0::bigint AS ucd_id,
				0::bigint AS lpp_id,
				(MAX(Array[DFVSARAF::text,CASE WHEN LENGTH(ITFSARAF) = 13 AND SUBSTRING(ITFSARAF,5,1) = '8' THEN ITFSARAF 
				WHEN LENGTH(EANSARAF) = 13 AND SUBSTRING(EANSARAF,5,1) = '8' THEN ITFSARAF ELSE ''  END]))[2] AS code_ucd13,

				''::text AS code_cahpp,
				0 AS unite_approvisionnement_id,
				(MAX(Array[DFVSARAF::text,PATSARAF::text]))[2]::numeric  AS prix_unitaire_en_cours,
				(MAX(Array[DFVSARAF::text,CPASARAF::text]))[2]  AS CPASARAF,
				(MAX(Array[DFVSARAF::text,QTMSARAF::text]))[2]::numeric AS nombre_conditionnement_approvisionnement
				FROM prod_qualiac.SARAF
					JOIN eco.t_fournisseurs ON FOUSARAF = t_fournisseurs.code_original
					JOIN eco.t_articles ON ARTSARAF = t_articles.code_original
					
				 WHERE ( ETSSARAF = ANY(string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				 GROUP BY 1,2,3
				;

				UPDATE w_articles_fournisseur_eco
				SET
					ref_fournisseur_code = CASE WHEN w_articles_fournisseur_eco.ref_fournisseur_code = '' THEN sub.ref_fournisseur_code ELSE w_articles_fournisseur_eco.ref_fournisseur_code END,
					prix_unitaire_en_cours = CASE WHEN w_articles_fournisseur_eco.prix_unitaire_en_cours = 0 THEN sub.prix_unitaire_en_cours::numeric ELSE w_articles_fournisseur_eco.prix_unitaire_en_cours END
				FROM 
					(SELECT 
					ETSSALCA || '-' || ARTSALCA || '-' || FOUSACDA AS code_original,
					(MAX(Array[
						CASE WHEN RFOSALCA != '' OR split_part(split_part(INTSALCA,' REF ',2),' ',1) != '' THEN DCDSACDA::text ELSE '1900-01-01' END, 
						CASE 
							WHEN RFOSALCA != '' THEN RFOSALCA 
							WHEN INTSALCA LIKE '% REF%' THEN split_part(split_part(INTSALCA,' REF ',2),' ',1)  
							ELSE INTSALCA
							END]))[2] AS ref_fournisseur_code,
				(MAX(ARRAY[DCDSACDA::text,PVCSALCA::text]))[2]::numeric AS prix_unitaire_en_cours
				FROM prod_qualiac.SACDA
					JOIN prod_qualiac.SALCA ON ETSSALCA || '-' || NUISALCA =  ETSSACDA || '-' || NUISACDA
				 WHERE ( ETSSACDA = ANY(string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND FOUSACDA != ''
				GROUP BY 1
				ORDER BY 1
				) sub
				WHERE sub.code_original = w_articles_fournisseur_eco.code_original
				AND (w_articles_fournisseur_eco.ref_fournisseur_code != sub.ref_fournisseur_code OR  w_articles_fournisseur_eco.prix_unitaire_en_cours = 0)
				;
					
				UPDATE w_articles_fournisseur_eco
				SET lpp_id = t_lpp.oid
				FROM prod_qualiac.SGART
					JOIN eco.t_articles ON ARPSGART NOT IN('GHS','NA','.') AND
						NUMSGART = t_articles.code_original
					JOIN base.t_lpp ON t_lpp.code = ARPSGART
				WHERE 1=1 AND
					article_id = t_articles.oid AND
					w_articles_fournisseur_eco.lpp_id != t_lpp.oid	
				;	
					
				INSERT INTO base.t_ucd (code, texte, texte_court)
				SELECT ucd_code, ucd_code, ucd_code
				FROM w_articles_fournisseur_eco
				WHERE ucd_code != '' 
					AND ucd_code != ALL (ARRAY(SELECT code FROM base.t_ucd))
					AND ucd_code LIKE '9%'
				GROUP BY 1,2,3
				;
			
				UPDATE w_articles_fournisseur_eco
				SET ucd_id = t_ucd.oid
				FROM base.t_ucd
				WHERE 1=1 AND
					t_ucd.code = ucd_code AND
					w_articles_fournisseur_eco.ucd_id != t_ucd.oid	
				;	
				
				UPDATE eco.t_articles
				SET 
					ucd_id = t_article_fournisseur.ucd_id
				FROM
					eco.t_article_fournisseur 
				WHERE 1=1 AND
					t_articles.ucd_id != t_article_fournisseur.ucd_id AND
					article_id = t_articles.oid
				;
				
				UPDATE eco.t_articles
				SET 
					compte_id = t_compte.oid
				FROM
					w_articles_fournisseur_eco
					JOIN eco.t_compte ON CPASARAF = t_compte.code
				WHERE 1=1 AND
					t_articles.compte_id != t_compte.oid AND
					article_id = t_articles.oid
				;
			
				-- Référence article fournisseur
				UPDATE eco.t_articles SET
					ref_fournisseur_id = subview.ref_fournisseur_id,
					ref_fournisseur_code = subview.ref_fournisseur_code,
					ref_fournisseur_texte = subview.ref_fournisseur_texte
				FROM
				(
				SELECT article_id,
					base.cti_group_array3(fournisseur_id) AS ref_fournisseur_id,
					base.cti_group_array3(w_articles_fournisseur_eco.ref_fournisseur_code) AS ref_fournisseur_code,
					base.cti_group_array3(CASE WHEN w_articles_fournisseur_eco.ref_fournisseur_texte != '' THEN w_articles_fournisseur_eco.ref_fournisseur_texte ELSE texte END || CASE WHEN w_articles_fournisseur_eco.ref_fournisseur_code != '' AND w_articles_fournisseur_eco.ref_fournisseur_code != w_articles_fournisseur_eco.ref_fournisseur_texte THEN '(' || w_articles_fournisseur_eco.ref_fournisseur_code || ')' ELSE '' END) AS ref_fournisseur_texte
				FROM 
					w_articles_fournisseur_eco
				JOIN eco.t_articles ON article_id = t_articles.oid
				GROUP BY 1
				ORDER BY 2,1
				) subview
				WHERE t_articles.oid = subview.article_id AND
					(
					t_articles.ref_fournisseur_id IS DISTINCT FROM subview.ref_fournisseur_id OR
					t_articles.ref_fournisseur_code IS DISTINCT FROM subview.ref_fournisseur_code OR
					t_articles.ref_fournisseur_texte IS DIStINCT FROM subview.ref_fournisseur_texte
					)
				;
				
				DELETE FROM eco.t_article_fournisseur
				WHERE code_original NOT IN (SELECT w_articles_fournisseur_eco.code_original FROM w_articles_fournisseur_eco)
				;

				INSERT INTO eco.t_article_fournisseur (
					code_original,
					article_id,
					fournisseur_id,
					code_reference_fournisseur,
					texte_reference_fournisseur,
					code_cip,
					ucd_id,
					code_ucd13,
					lpp_id,
					code_cahpp,
					unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours
					)
				SELECT 
					code_original,
					article_id, 
					fournisseur_id,
					ref_fournisseur_code,
					ref_fournisseur_texte,
					code_cip,
					ucd_id,
					code_ucd13,
					lpp_id,
					code_cahpp,
					unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours
				FROM w_articles_fournisseur_eco
				WHERE w_articles_fournisseur_eco.code_original NOT IN (SELECT t_article_fournisseur.code_original FROM eco.t_article_fournisseur WHERE code_original IS NOT NULL)
				;

				UPDATE eco.t_article_fournisseur SET
					article_id = w_articles_fournisseur_eco.article_id,
					fournisseur_id = w_articles_fournisseur_eco.fournisseur_id,
					code_reference_fournisseur = w_articles_fournisseur_eco.ref_fournisseur_code,
					texte_reference_fournisseur = w_articles_fournisseur_eco.ref_fournisseur_texte,
					code_cip = w_articles_fournisseur_eco.code_cip,
					code_ucd13 = w_articles_fournisseur_eco.code_ucd13,
					ucd_id = w_articles_fournisseur_eco.ucd_id,
					lpp_id = w_articles_fournisseur_eco.lpp_id,
					code_cahpp = w_articles_fournisseur_eco.code_cahpp,
					unite_approvisionnement_id = w_articles_fournisseur_eco.unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement = w_articles_fournisseur_eco.nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours = w_articles_fournisseur_eco.prix_unitaire_en_cours
				FROM w_articles_fournisseur_eco
				WHERE t_article_fournisseur.code_original = w_articles_fournisseur_eco.code_original AND
					(
						t_article_fournisseur.article_id IS DISTINCT FROM w_articles_fournisseur_eco.article_id OR
						t_article_fournisseur.fournisseur_id IS DISTINCT FROM w_articles_fournisseur_eco.fournisseur_id OR
						t_article_fournisseur.code_reference_fournisseur IS DISTINCT FROM w_articles_fournisseur_eco.ref_fournisseur_code OR
						t_article_fournisseur.texte_reference_fournisseur IS DISTINCT FROM w_articles_fournisseur_eco.ref_fournisseur_texte OR
						t_article_fournisseur.code_cip IS DISTINCT FROM w_articles_fournisseur_eco.code_cip OR
						t_article_fournisseur.code_ucd13 IS DISTINCT FROM w_articles_fournisseur_eco.code_ucd13 OR
						t_article_fournisseur.ucd_id IS DISTINCT FROM w_articles_fournisseur_eco.ucd_id OR
						t_article_fournisseur.lpp_id IS DISTINCT FROM w_articles_fournisseur_eco.lpp_id OR
						t_article_fournisseur.code_cahpp IS DISTINCT FROM w_articles_fournisseur_eco.code_cahpp OR
						t_article_fournisseur.unite_approvisionnement_id IS DISTINCT FROM w_articles_fournisseur_eco.unite_approvisionnement_id OR
						t_article_fournisseur.nombre_conditionnement_approvisionnement IS DISTINCT FROM w_articles_fournisseur_eco.nombre_conditionnement_approvisionnement OR
						t_article_fournisseur.prix_unitaire_en_cours IS DISTINCT FROM w_articles_fournisseur_eco.prix_unitaire_en_cours
					)
				;
			
			]]></sqlcmd>
		</NODE>
		
		
		
		<NODE label="Autres tables">
			<sqlcmd><![CDATA[
			
				-- Gestionnaires
				
				INSERT INTO eco.t_gestionnaires(code_original, code, texte, texte_court)
				SELECT UCRSKLMS, UCRSKLMS, LEFT(UCRSKLMS,50), UCRSKLMS
				FROM prod_qualiac.sklms
				WHERE UCRSKLMS IN (SELECT UCRSKLMS FROM prod_qualiac.SKLMS
				WHERE (ETOSKLMS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1') AND
					UCRSKLMS NOT IN (SELECT code_original FROM eco.t_gestionnaires WHERE code_original IS NOT NULL))
				GROUP BY 1,2,3,4
				;
				
				
				INSERT INTO eco.t_gestionnaires(code_original, code, texte, texte_court)
				SELECT UCRSACDA, UCRSACDA, LEFT(UCRSACDA,50), UCRSACDA
				FROM prod_qualiac.SACDA
				WHERE  (ETSSACDA = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1') AND
					UCRSACDA NOT IN (SELECT code_original FROM eco.t_gestionnaires WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4;
				;
				
				-- Site
					INSERT INTO eco.t_sites(code_original, code, texte, texte_court)
				SELECT NUMGTETS, NUMGTETS, INTGTETS, INRGTETS
				FROM prod_qualiac.GTETS
					LEFT JOIN eco.t_sites ON (code_original = NUMGTETS)
				WHERE code_original IS NULL
					AND (NUMGTETS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1');
				
				
				-- Lieux
				INSERT INTO eco.t_lieux(code_original, code, texte, texte_court)
				SELECT ETSSGDEP || '-' || NUMSGDEP,NUMSGDEP,INTSGDEP,INRSGDEP
				FROM PROD_QUALIAC.SGDEP 
					LEFT JOIN eco.t_lieux ON (code_original = ETSSGDEP || '-' || NUMSGDEP)
				WHERE ETSSGDEP || '-' || NUMSGDEP IN (SELECT ETOSKMVS || '-' || DEOSKMVS FROM prod_qualiac.SKMVS) AND
					code_original IS NULL AND
					(ETSSGDEP = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				;
				
				
				-- UF
				INSERT INTO eco.t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT ETSOECGR || '-' || NUMOECGR, NUMOECGR, INTOECGR, INROECGR
				FROM PROD_QUALIAC.OECGR
					LEFT JOIN eco.t_unites_fonctionnelles ON (code_original = ETSOECGR || '-' || NUMOECGR)
				WHERE ETSOECGR || '-' || NUMOECGR IN (SELECT ETOSKLMS || '-' || GD1SKLMS FROM prod_qualiac.SKLMS) AND
					code_original IS NULL AND
					(ETSOECGR = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				;
				
					
				
				-- Types mouvements
				INSERT INTO eco.t_types_mouvements(code_original, code, texte, texte_court)
				SELECT ETSSKNMS || '-' || CLASKNMS, CLASKNMS, INTSKNMS, LEFT(INTSKNMS,50)
				FROM prod_qualiac.SKNMS 
					LEFT JOIN eco.t_types_mouvements ON code_original = ETSSKNMS || '-' || CLASKNMS
				WHERE CLASKNMS <> '' 
					AND t_types_mouvements.oid IS NULL
					AND (ETSSKNMS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				GROUP BY 1,2,3,4;
			
			]]></sqlcmd>
		</NODE>
		
		
	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">
	
		<NODE label="Pr?paration">
			<sqlcmd><![CDATA[
			
			DROP TABLE IF EXISTS w_mvt;
			CREATE TEMP TABLE w_mvt AS 
			SELECT  
				SKMVS.NUISKMVS,
				SKMVS.CLASKMVS,		--Mvmt
				SKMVS.NUMSKMVS,		--N° mvmt
				SKLMS.ETOSKLMS,		--Etablissement
				SKMVS.DEOSKMVS,		--D?p?t
				SKMVS.DEDSKMVS,		--Destination
				SKLMS.MOSSKLMS,		--Mode stockage
				SKMVS.DATSKMVS,		--Date
				SKLMS.ARTSKLMS,		--Article
				SKLMS.LOPSKLMS,		--Lot interne
				SKLMS.CNTSKLMS,		--Contenant
				SKLMS.QTESKLMS,		--Qt?
				SKLMS.STKSKLMS,		--MAJ Stock
				SKLMS.TPXSKLMS,		--Type de prix r?el
				SKLMS.PRXSKLMS,		--Prix r?el
				SKLMS.TPESKLMS,		--Type de prix estim?
				SKLMS.PXESKLMS,		--Prix estim? devise
				SKLMS.LOFSKLMS,		--Lot fnr
				SKLMS.SERSKLMS,		--Num?ro de s?rie
				SKLMS.CD1SKLMS,		--Compte d?bit
				SKLMS.GD1SKLMS,		--CGR A d?bit
				SKLMS.CO1SKLMS,		--Compte cr?dit
				SKLMS.GO1SKLMS,		--CGR A cr?dit
				SKMVS.DDCSKMVS,		--Date comptable
				SKMVS.TROSKMVS,		--Pi?ce
				SKLMS.DADSKLMS,		--Date d'annulation (valorisation secondaire)
				SKLMS.TADSKLMS,		--Pi?ce d'annulation (valorisation secondaire)
				SKMVS.INFSKMVS,		--Commentaires
				SKMVS.LBTSKMVS,		--Libell? tiers
				SKMVS.LBCSKMVS,		--Libell? commande
				SKMVS.LBDSKMVS,		--Libell? document
				CASE WHEN P15SKLMS <> '' THEN P15SKLMS ELSE SKMVS.MNESKMVS END AS MNESKMVS,		--N° s?jour
				SKLMS.TRASKLMS,		--Pi?ce d'annulation
				SKMVS.GESSKMVS,		--Gestionnaire
				SKMVS.TYPSKMVS,		--Type
				SKMVS.NATSKMVS,		--Nature
				SKMVS.GENSKMVS,		--Genre
				SKMVS.ROLSKMVS,		--R?le
				SKLMS.INFSKLMS,		--Informations
				SKLMS.QUCSKLMS,		--Quantit? en unit? de consommation
				SKLMS.UCOSKLMS,		--Unit? de consommation
				SKLMS.CCSSKLMS,		--Coeff. consommation ? stock
				SKLMS.DCSSKLMS,		--Divis? par
				SKLMS.EANSKLMS,		--Code EAN
				SKLMS.GESSKLMS,		--Gestionnaire
				SKLMS.NUMSKLMS,		--Num?ro de ligne
				SKLMS.NBESKLMS,		--Nombre d'?tiquettes
				SKLMS.NBCSKLMS,		--Nombre de colis
				SKLMS.PDSSKLMS,		--Poids
				SKLMS.VOLSKLMS,		--Volume
				SKLMS.TYPSKLMS,		--Type
				SKLMS.NATSKLMS,		--Nature
				SKLMS.GENSKLMS,		--Genre
				SKLMS.ROLSKLMS,		--R?le
				SKLMS.UCRSKLMS,		--Cr?ateur
				SKLMS.DCRSKLMS,		--Date cr?ation mvt
				SKLMS.HCRSKLMS,		--Heure
				SKLMS.UDMSKLMS,		--Modificateur
				SKLMS.DDMSKLMS,		--Date
				SKLMS.HDMSKLMS,		--Heure
				SKLMS.MPESKLMS,		--Date MAJ du prix estim?
				SKLMS.MPRSKLMS,		--Date MAJ du prix r?el
				SKNMS.SENSKNMS,
				SKMVS.OBSSKMVS,
				NICSKLMS,
				LIGSKLMS,
				COALESCE(PVRSALCA,0) AS PVRSALCA,
				COALESCE(PVFSALCA,0) AS PVFSALCA,
				COALESCE(PVCSALCA,0) AS PVCSALCA,
				COALESCE(QTRSALCA,0) As QTRSALCA,
				SKLMS.NUISKLMS::text || '-' || SKLMS.NUMSKLMS::text AS SKLMS_ID
			FROM prod_qualiac.SKMVS 
				JOIN prod_qualiac.SKLMS ON NUISKLMS = NUISKMVS 
				JOIN prod_qualiac.SKNMS ON CLASKMVS = CLASKNMS AND ETOSKMVS = ETSSKNMS
				LEFT JOIN prod_qualiac.SALCA ON ETOSKLMS || '-' || NICSKLMS || '-' || LIGSKLMS  = ETSSALCA || '-' || NUISALCA || '-' || NUMSALCA
				WHERE DATSKMVS > '[ENV_ECO_ANNEEDEBUT]0101' 
				AND (ETOSKMVS = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
			ORDER BY DATSKMVS,HDMSKLMS,NUMSKMVS,NUMSKLMS;
			
			DROP TABLE IF EXISTS w_cmd;
			CREATE TEMP TABLE w_cmd AS 
			SELECT	
				SACDA.ETSSACDA	, --Etablissement
				SACDA.CLASACDA	, --Classe
				SACDA.NUMSACDA	, --No commande
				SACDA.SNUSACDA	, --Sous num?ro
				SACDA.ECASACDA	, --Etape/Etat
				SACDA.FOUSACDA	, --Fournisseur
				SACDA.TIESACDA	, --Tiers facturation
				SACDA.TTCSACDA	, --Montant TTC
				SACDA.TAFSACDA	, --Adresse facturation
				SACDA.DCDSACDA	, --Date de commande
				SACDA.DRDSACDA	, --Livraison au plus t?t
				SACDA.DRFSACDA	, --Date au plus tard
				SACDA.DEPSACDA	, --D?p?t
				SACDA.DEVSACDA	, --Devise
				SACDA.DDESACDA	, --Date ?tape
				SACDA.OBSSACDA	, --Objet
				SACDA.TIPSACDA	, --Tiers paiement
				SACDA.TAPSACDA	, --Adresse paiement
				SACDA.TILSACDA	, --Tiers logistique
				SACDA.TALSACDA	, --Adresse logistique
				SACDA.TICSACDA	, --Tiers commande
				SACDA.TACSACDA	, --Adresse commande
				SACDA.TFESACDA	, --Tiers ? facturer
				SACDA.AFESACDA	, --Adresse ? facturer
				--SACDA.WINROECGR1	, --Libell?
				SACDA.CG2SACDA	, --C.G.R. B
				--SACDA.WINROECGR2	, --Libell?
				SACDA.DECSACDA	, --Date comptable
				SACDA.TTVSACDA	, --Type taxe
				SACDA.MODSACDA	, --Mode taxe
				SACDA.REGSACDA	, --R?gime taxe
				SACDA.DV1SACDA	, --Mode de change
				SACDA.DT1SACDA	, --Date du cours
				SACDA.TX1SACDA	, --Cours
				SACDA.DV2SACDA	, --Mode de change reporting
				SACDA.DT2SACDA	, --Date du cours reporting
				SACDA.TX2SACDA	, --Cours de reporting
				SACDA.PRTSACDA	, --Type de port
				SACDA.DESSACDA	, --Destination
				SACDA.NBCSACDA	, --Nbre colis
				SACDA.URGSACDA	, --Priorit?
				--SACDA.STKSACDA	, --Etat du stock
				--SACDA.WLSTKSACDa	, --Libell? ?tat du stock
				SACDA.DTSSACDA	, --Date MAJ stock
				SACDA.TC1SACDA	, --No pi?ce 1
				SACDA.DC1SACDA	, --Date transfert 1
				SACDA.TC2SACDA	, --No pi?ce 2
				SACDA.DC2SACDA	, --Date transfert 2
				SACDA.RECSACDA	, --R?ception
				SACDA.DRESACDA	, --Date de r?ception
				SACDA.FAASACDA	, --Facture
				--SACDA.WDATSAFAA	, --Date facture
				SACDA.CLSSACDA	, --Classe cde r?ception
				SACDA.CDSSACDA	, --No cde r?ception
				SACDA.SNSSACDA	, --Sous no cde r?ception
				SACDA.CLFSACDA	, --Classe cde facture
				SACDA.CDFSACDA	, --No cde facture
				SACDA.SNFSACDA	, --Sous no cde facture
				SACDA.MTISACDA	, --Montant initial
				SACDA.DCCSACDA	, --Date confirmation
				SACDA.REFSACDA	, --R?f?rence fournisseur
				SACDA.DCFSACDA	, --Date confirmation fourn.
				SACDA.NIRSACDA	, --Niveau de relance
				SACDA.DDRSACDA	, --Date de relance
				SACDA.DCOSACDA	, --Date contrat
				SACDA.OTSSACDA	, --Ouverture semaine
				SACDA.OBLSACDA	, --Observations / r?ception
				SACDA.OBFSACDA	, --Observations / facture
				SACDA.OBRSACDA	, --Observations / paiement
				SACDA.INXSACDA	, --Interlocuteur externe
				SACDA.INLSACDA	, --Interlocuteur logistique
				SACDA.ETASACDA	, --Etat
				SACDA.TYPSACDA	, --Type
				SACDA.NATSACDA	, --Nature
				SACDA.GENSACDA	, --Genre
				SACDA.ROLSACDA	, --R?le
				SACDA.RETSACDA	, --Code rejet
				SACDA.MOTSACDA	, --Motif du rejet
				SACDA.DPCSACDA	, --D?p?t fournisseur
				SACDA.STCSACDA	, --Flag de statistique(s) commande
				SACDA.STRSACDA	, --Flag de statistique(s) r?ception
				SACDA.RPFSACDA	, --R?ception apr?s facture
				SACDA.RSASACDA	, --R?ception ou solde r?ception annul?e
				SACDA.RARSACDA	, --Retour ou annulation r?ception
				SACDA.IN1SACDA	, --Informations 1
				SACDA.IN2SACDA	, --Informations 2
				SACDA.NRDSACDA	, --Cde retour d?finitif
				SACDA.ERDSACDA	, --Etape cde retour d?finitif
				SACDA.NRTSACDA	, --Cde retour temporaire
				SACDA.ERTSACDA	, --Etape cde retour temporaire
				SACDA.NUISACDA	, --No Interne
				SACDA.UCRSACDA	, --Cr?ateur
				SACDA.DCRSACDA	, --Cr?? le
				SACDA.PRCSACDA	, --Transaction
				SACDA.UDMSACDA	 --Modificateur
				FROM prod_qualiac.SACDA
				--	LEFT JOIN prod_qualiac.SACAE ON NUISACAE = NUISACDA AND ETSSACAE = ETSSACDA
				WHERE (ETSSACDA = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND DCDSACDA > '[ENV_ECO_ANNEEDEBUT]0101'
				;

				DROP TABLE IF EXISTS w_fac;
				CREATE TEMP TABLE w_fac AS
				SELECT 
					ETSSACAF,
					NUISACAF,
					MAX(CASE WHEN TYPSACAF = 'T' THEN MNTSACAF ELSE 0 END) as facture_ht,
					MAX(CASE WHEN TYPSACAF = 'TA' THEN MNTSACAF ELSE 0 END) as facture_tva,
					MAX(CASE WHEN TYPSACAF = 'TT' THEN MNTSACAF ELSE 0 END) as facture_ttc,
					MAX(CASE WHEN TYPSACAF = 'P' THEN MNTSACAF ELSE 0 END) as facture_port,
					MAX(CASE WHEN TYPSACAF = 'T' THEN MC0SACAF ELSE 0 END) as commande_ht,
					MAX(CASE WHEN TYPSACAF = 'TA' THEN MC0SACAF ELSE 0 END) as commande_tva,
					MAX(CASE WHEN TYPSACAF = 'TT' THEN MC0SACAF ELSE 0 END) as commande_ttc,
					MAX(CASE WHEN TYPSACAF = 'P' THEN MC0SACAF ELSE 0 END) as commande_port
				FROM prod_qualiac.SACAF
				GROUP BY 1,2
				;
			]]></sqlcmd>
		</NODE>
			
			
		<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');
				
				SELECT base.cti_execute('
					INSERT INTO eco.t_divers (code, valeur, texte, description) VALUES
					(''ETAT_COM_QUALIAC_INVALIDES'',''670,850,970'',''etat de commande non valides'',''etat de commandes a ne pas importer dans CTI'')',1)
				WHERE (SELECT count(*) FROM eco.t_divers WHERE code = 'ETAT_COM_QUALIAC_INVALIDES') = 0
				;
				
				SELECT base.cti_execute('
					INSERT INTO eco.t_divers (code, valeur, texte, description) VALUES
					(''TYPE_COM_QUALIAC_VALIDES'',''C,RDPM'',''type de commande valides'',''type de commandes a importer dans CTI'')',1)
				WHERE (SELECT count(*) FROM eco.t_divers WHERE code = 'TYPE_COM_QUALIAC_VALIDES') = 0
				;
				
				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,
					fournisseur_distributeur_id,
					gestionnaire_id,
					site_id,
					lieu_commande_id,
					lieu_facturation_id,
					lieu_livraison_id,
					unite_fonctionnelle_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 
					ETSSACDA || '-' || NUISACDA AS code_original,
					CLASACDA || NUMSACDA || CASE WHEN SNUSACDA > 1 THEN '-' || SNUSACDA ELSE '' END AS numero,
					DCDSACDA::date AS date_commande,
					date_trunc('month',DCDSACDA::date)  + interval '1 month' - interval '1 day' AS date_engagement,
					OBSSACDA AS objet,
					'' AS reference,
					CASE
						WHEN DRFSACDA != '' THEN DRFSACDA::date 
						WHEN DRDSACDA != '' THEN DRDSACDA::date 
						ELSE '20991231'::date END AS date_livraison_prevue,
					CASE WHEN RECSACDA > 0 THEN 'T' ELSE 'N' END AS etat_reception,
					CASE 
						WHEN DRESACDA != '' THEN DRESACDA::date 
						WHEN DC1SACDA != '' THEN DC1SACDA::date
						ELSE '20991231'::date END AS date_reception,
					CASE WHEN FAASACDA != 0 OR ECASACDA IN ('970','971') THEN 'T' ELSE 'N' END AS etat_liquidation,
					COALESCE(t_fournisseurs.oid,0) AS fournisseur_id,
					COALESCE(t_fournisseurs.fournisseur_distributeur_id, 0) AS fournisseur_distributeur_id,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					COALESCE(t_sites.oid,0),
					COALESCE(t_lieux.oid,0),
					0 AS lieu_facturation_id,
					COALESCE(t_lieux.oid,0),
					0::bigint AS unite_fonctionnelle_id,
					0::numeric AS montant_commande_ht,
					0::numeric AS montant_commande_remise,
					0::numeric AS montant_commande_tva,
					0::numeric AS montant_commande_port,
					MTISACDA 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,
					CASE WHEN FAASACDA != 0 THEN TTCSACDA ELSE 0 END AS montant_liquidation_total
				FROM w_cmd
					LEFT JOIN eco.t_fournisseurs ON FOUSACDA = t_fournisseurs.code_original
					LEFT JOIN eco.t_gestionnaires ON UCRSACDA = t_gestionnaires.code_original
					LEFT JOIN eco.t_sites ON ETSSACDA = t_sites.code_original
					LEFT JOIN eco.t_lieux ON DEPSACDA = t_lieux.code_original
				WHERE
					CLASACDA = ANY (ARRAY(SELECT string_to_array((SELECT valeur FROM eco.t_divers WHERE code = 'TYPE_COM_QUALIAC_VALIDES'),','))) -- commandes validées
					AND ECASACDA != ALL (ARRAY(SELECT string_to_array((SELECT valeur FROM eco.t_divers WHERE code = 'ETAT_COM_QUALIAC_INVALIDES'),','))) -- commandes validées
				;
				
				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');

				UPDATE eco.p_commandes
				SET 
					montant_liquidation_ht = facture_ht,
					montant_liquidation_tva = facture_tva,
					montant_liquidation_port = facture_port,
					montant_liquidation_total = facture_ttc,
					montant_commande_ht = commande_ht,
					montant_commande_tva = commande_tva,
					montant_commande_port = commande_port,
					montant_commande_total = commande_ttc
				FROM w_fac
				WHERE
					code_original = ETSSACAF || '-' || NUISACAF
				;

				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');
				
				TRUNCATE  eco.p_lignes_commandes;


				INSERT INTO eco.p_lignes_commandes(
					code_original,
					commande_id,
					ligne_commande,
					texte,
					fournisseur_distributeur_id,
					unite_fonctionnelle_id,
					article_id,
					unite_approvisionnement_id,
					lpp_id,
					ucd_id,
					compte_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_ttc,
					etat_livraison,

					montant_liquidation_ht,
					montant_liquidation_remise,
					montant_liquidation_tva,
					montant_liquidation_port,
					montant_liquidation_ttc,
					etat_liquidation,
					
					taux_tva)
				SELECT
					ETSSALCA || '-' || NUISALCA || '-' || NUMSALCA AS code_original,
					p_commandes.oid AS commande_id,
					NUMSALCA AS ligne_commande,
					INTSALCA AS texte,
					p_commandes.fournisseur_distributeur_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid, 0) AS article_id,
					COALESCE(t_unites.oid,t_articles.unite_stockage_id,0) AS unite_approvisionnement_id,
					COALESCE(t_articles.lpp_id,0),
					COALESCE(t_articles.ucd_id,0),
					COALESCE(t_compte.oid, t_articles.compte_id, 0) AS compte_id,
					QTCSALCA AS quantite_approvisionnement,
					PVCSALCA AS prix_unitaire_approvisionnement,
					1 AS multiplicateur_stockage,
					1 AS quantite_stockage,
					COALESCE(NULLIF(PVFSALCA,0),NULLIF(PVRSALCA,0),PVCSALCA) AS prix_unitaire_stockage,

					round((QTCSALCA * PVCSALCA)::numeric,2) AS montant_commande_ht,
					REMSALCA AS montant_commande_remise,
					round((QTCSALCA * PVCSALCA * COALESCE(TAUOETVA,0)/100)::numeric,2) AS montant_commande_tva,
					0 AS montant_commande_port,
					round((QTCSALCA * PVCSALCA)::numeric,2)+round((QTCSALCA * PVCSALCA * COALESCE(TAUOETVA,0)/100)::numeric,2) AS montant_commande_ttc,

					QTRSALCA AS quantite_livraison_approvisionnement,
					QTRSALCA AS quantite_livraison_stockage,
					round((QTRSALCA * COALESCE(NULLIF(PVRSALCA,0),PVCSALCA))::numeric,2) AS montant_livraison_ht,
					round((QTRSALCA * COALESCE(NULLIF(PVRSALCA,0),PVCSALCA))::numeric,2) +
						round((QTRSALCA * COALESCE(NULLIF(PVRSALCA,0),PVCSALCA) * COALESCE(TAUOETVA,0)/100)::numeric,2) AS montant_livraison_ttc,
					CASE 
						WHEN etat_reception = 'N' THEN 'N' 
						WHEN QTRSALCA = QTCSALCA AND QTRSALCA > 0 THEN 'T' 
						WHEN QTRSALCA > QTCSALCA THEN 'S' 
						WHEN QTRSALCA = 0 THEN 'N' 
						ELSE 'P' END AS etat_livraison,
					round((QTFSALCA * PVFSALCA)::numeric,2) AS montant_liquidation_ht,
					round((QTFSALCA * PVFSALCA * REMSALCA / 100 )::numeric,2) AS montant_liquidation_remise,
					round((QTFSALCA * PVFSALCA * TAUOETVA / 100)::numeric,2) AS montant_liquidation_tva,
					0::numeric AS montant_liquidation_port,
					round((QTFSALCA * PVFSALCA)::numeric,2) + round((QTFSALCA * PVFSALCA * TAUOETVA / 100)::numeric,2) AS montant_liquidation_ttc,
					p_commandes.etat_liquidation AS etat_liquidation,
					
					TAUOETVA
				FROM prod_qualiac.SALCA
					JOIN eco.p_commandes ON ETSSALCA || '-' || NUISALCA = p_commandes.code_original
					LEFT JOIN eco.t_articles ON ARTSALCA = t_articles.code_original
					LEFT JOIN eco.t_compte ON CPASALCA = t_compte.code_original
					LEFT JOIN eco.t_unites ON UNASALCA = t_unites.code_original AND t_unites.oid <> 0
					LEFT JOIN eco.t_unites_fonctionnelles ON ETSSALCA || '-' || CG1SALCA = t_unites_fonctionnelles.code_original
					LEFT JOIN prod_qualiac.OETVA ON TVASALCA = NUMOETVA AND ETSSALCA = ETSOETVA
				;
				
				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');
			
			]]></sqlcmd>
		</NODE>
		<NODE label="Mouvements">
			<sqlcmd><![CDATA[
			
				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');

				-- calc des pump
				DROP TABLE IF EXISTS w_sgpmp;
				CREATE TEMP TABLE w_sgpmp AS
				SELECT 
					ETSSGPMP,
					ARTSGPMP,
					DATSGPMP::date,
					COALESCE(LEAD(DATSGPMP) OVER (PARTITION BY ETSSGPMP,ARTSGPMP ORDER BY DATSGPMP),'2099-12-31')::date - interval '1 day' AS DATSGPMP_next,
					MNTSGPMP / QTESGPMP AS pump
				FROM prod_qualiac.SGPMP
				WHERE DOMSGPMP = 'A' AND QTESGPMP > 0
				;
				
				DELETE FROM w_sgpmp
				WHERE DATSGPMP > DATSGPMP_next
				;
			
				TRUNCATE eco.p_mouvements_articles;
			
				INSERT INTO eco.p_mouvements_articles(
					code_original,
					date, 
					sens_mouvement,
					type_mouvement_id, 
					texte, 
					gestionnaire_id, 
					site_id, 
					lieu_id, 
					unite_fonctionnelle_id, 
					article_id, 
					compte_id, 
					fournisseur_id,
					commande_id,
					ligne_commande,
					ucd_id,
					lpp_id,
					prix_unitaire, 
					entree_quantite, 
					sortie_quantite,
					entree_montant, 
					entree_montant_ht,
					sortie_montant,
					sortie_montant_ht,
					sortie_montant_original_ttc,
					sortie_montant_original_ht,
					prix_unitaire_calcule,
					stock_quantite_debut,
					stock_quantite_fin,
					date_fin,
					est_premier_jour,
					est_dernier_jour,
					no_sejour
					)
				SELECT 
					SKLMS_ID AS code_original,
					DATSKMVS::date AS date,
					SENSKNMS AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
						CASE WHEN trim(OBSSKMVS) NOT IN ('.','') THEN '-' || OBSSKMVS ELSE '' END ||
						CASE WHEN trim(LBDSKMVS) NOT IN ('.','') THEN '-' || LBDSKMVS ELSE '' END ||
						CASE WHEN trim(MNESKMVS) NOT IN ('.','') THEN '- sej. ' || MNESKMVS ELSE '' END ||
						CASE WHEN trim(LOPSKLMS) NOT IN ('.','') THEN '- lot. ' || LOFSKLMS ELSE '' END AS texte,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					COALESCE(t_sites.oid,0) AS site_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,0) AS fournisseur_id,
					COALESCE(commande_id, 0) AS commande_id,
					COALESCE(ligne_commande, 0) AS ligne_commande,
					t_articles.ucd_id,
					t_articles.lpp_id,
					COALESCE(NULLIF(PRXSKLMS,0),NULLIF(PVFSALCA,0),NULLIF(PVRSALCA,0),NULLIF(PVCSALCA,0),NULLIF(pump,0),0) AS prix_unitaire,
					CASE WHEN SENSKNMS = 'E' THEN QTESKLMS ELSE 0 END AS entree_quantite,
					CASE WHEN SENSKNMS = 'S' THEN QTESKLMS ELSE 0 END AS sortie_quantite,
					CASE WHEN SENSKNMS = 'E' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),NULLIF(PVFSALCA,0),NULLIF(PVRSALCA,0),NULLIF(PVCSALCA,0),0) ELSE 0 END AS entree_montant,
					CASE WHEN SENSKNMS = 'E' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),NULLIF(PVFSALCA,0),NULLIF(PVRSALCA,0),NULLIF(PVCSALCA,0),0) ELSE 0 END AS entree_montant_ht,
					CASE WHEN SENSKNMS = 'S' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),pump,0) ELSE 0 END AS sortie_montant,
					CASE WHEN SENSKNMS = 'S' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),pump,0) ELSE 0 END AS sortie_montant_ht,
					CASE WHEN SENSKNMS = 'S' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),pump,0) ELSE 0 END AS sortie_montant_original_ttc,
					CASE WHEN SENSKNMS = 'S' THEN QTESKLMS * COALESCE(NULLIF(PRXSKLMS,0),pump,0) ELSE 0 END AS sortie_montant_original_ht,
					PRXSKLMS AS prix_unitaire_calcule,
					0,
					0,
					CASE WHEN COALESCE(LEAD(DATSKMVS) OVER (PARTITION BY ARTSKLMS, DEOSKMVS ORDER BY DATSKMVS,HDMSKLMS,NUISKMVS),'2100-01-01') = DATSKMVS THEN
					DATSKMVS::date ELSE COALESCE(LEAD(DATSKMVS) OVER (PARTITION BY ARTSKLMS, DEOSKMVS ORDER BY DATSKMVS,HDMSKLMS,NUISKMVS),'2100-01-01')::date - interval '1 day'
					END as date_fin,
					CASE  WHEN rank() OVER (PARTITION BY ARTSKLMS, DEOSKMVS,DATSKMVS ORDER BY DATSKMVS,HDMSKLMS,NUISKMVS) = 1 THEN 1
					ELSE 0
					END AS est_premier_jour,
					CASE
					WHEN cume_dist() OVER (PARTITION BY ARTSKLMS, DEOSKMVS,DATSKMVS ORDER BY DATSKMVS,HDMSKLMS,NUISKMVS) = 1 THEN 1
					ELSE 0
					END AS est_dernier_jour,
					MNESKMVS AS no_sejour
				FROM w_mvt
					LEFT JOIN eco.t_types_mouvements ON ETOSKLMS || '-' || CLASKMVS = t_types_mouvements.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON t_unites_fonctionnelles.code_original = ETOSKLMS || '-' || GD1SKLMS
					LEFT JOIN eco.t_articles ON ARTSKLMS = t_articles.code_original AND t_articles.oid <> 0
					LEFT JOIN eco.t_gestionnaires ON UCRSKLMS = t_gestionnaires.code_original
					LEFT JOIN eco.t_lieux ON ETOSKLMS || '-'  || DEOSKMVS = t_lieux.code_original
					LEFT JOIN eco.t_sites ON ETOSKLMS = t_sites.code_original
					LEFT JOIN eco.t_compte ON CO1SKLMS = t_compte.code_original
					LEFT JOIN eco.t_fournisseurs ON 0 = t_fournisseurs.code_original
					LEFT JOIN eco.p_lignes_commandes ON ETOSKLMS || '-' || NICSKLMS || '-' || LIGSKLMS = p_lignes_commandes.code_original
					LEFT JOIN w_sgpmp ON ETOSKLMS || '-' || ARTSKLMS = ETSSGPMP || '-' || ARTSGPMP AND DATSKMVS BETWEEN DATSGPMP AND DATSGPMP_next
				WHERE DATSKMVS >= '[ENV_ECO_ANNEEDEBUT]0101' ;

				DROP TABLE IF EXISTS w_taux_histo;
				CREATE TEMP TABLE w_taux_histo AS
				SELECT 
					ARTSALCA,
					TVASALCA,
					(100 + TAUOETVA)/100 AS taux,
					DCRSALCA,
					COALESCE(LEAD(DCRSALCA) OVER (PARTITION BY ARTSALCA ORDER BY DCRSALCA)::date - interval '1 day','2099-12-31'::date) as next_DCRSALCA
				FROM prod_qualiac.SALCA
					 JOIN prod_qualiac.OETVA ON TVASALCA = NUMOETVA AND ETSSALCA = ETSOETVA
				WHERE (ETSSALCA = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
				;

				UPDATE eco.p_mouvements_articles SET
					sortie_montant = sortie_montant_ht * taux,
					entree_montant = entree_montant_ht * taux
				FROM w_taux_histo
				JOIN eco.t_articles ON code_original = ARTSALCA
				WHERE article_id = t_articles.oid
					AND date BETWEEN DCRSALCA::date AND next_DCRSALCA
					;
				
				
				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';
					
				UPDATE eco.p_mouvements_articles SET
					entree_quantite = sortie_quantite,
					sortie_quantite = entree_quantite,
					entree_montant = sortie_montant,
					sortie_montant = entree_montant,
					entree_montant_ht = sortie_montant_ht,
					sortie_montant_ht = entree_montant_ht,
					sortie_montant_original_ttc = sortie_montant_original_ht,
					sortie_montant_original_ht = sortie_montant_original_ttc,
					sens_mouvement = sens_force
				FROM eco.t_types_mouvements
				WHERE type_mouvement_id = t_types_mouvements.oid AND
					t_types_mouvements.sens_force IN ('E','S') AND t_types_mouvements.sens_force != p_mouvements_articles.sens_mouvement
				;
				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');

				VACUUM ANALYSE eco.p_mouvements_articles;

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

				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_stock;
				CREATE TEMP TABLE w_stock AS
				SELECT 
					DTISKSTI::date,
					ARTSKSTI,
					ETSSKSTI,
					DEPSKSTI,
					SUM(QTISKSTI) AS QTISKSTI,
					base.cti_division(SUM(QTISKSTI::numeric*PRXSKSTI::numeric),SUM(QTISKSTI::numeric)) AS PRXSKSTI,
					MAX(CPSSKSTI) AS CPSSKSTI
				FROM prod_qualiac.SKSTI
				WHERE 1=1
					AND (ETSSKSTI = ANY (string_to_array('[ETAB_ID]'::text,',')) OR '[ETAB_ID]' = '' OR '[ETAB_ID]' = '-1')
					AND date_trunc('month',DTISKSTI::date) + interval '1 month' - interval '1 day' = DTISKSTI::date
				GROUP BY 1,2,3,4
				;
				
				TRUNCATE eco.p_stock;
				
				INSERT INTO eco.p_stock(
					article_id,
					date_fin,
					date_debut,
					ucd_id,
					lpp_id,
					compte_id,
					site_id,
					lieu_id,
					provider_id,
					fournisseur_id,
					stock_quantite_debut,
					stock_valeur_debut,
					stock_valeur_debut_ttc,
					entree_quantite,
					entree_montant,
					pump,
					sortie_quantite,
					sortie_montant,
					stock_quantite_fin,
					stock_valeur_fin,
					stock_valeur_fin_ttc)

				SELECT 
					coalesce(t_articles.oid,0),
					DTISKSTI::date AS date_fin,
					date_trunc('month',DTISKSTI::date) AS date_debut,
					ucd_id,
					lpp_id,
					COALESCE(t_compte.oid,t_articles.compte_id,0),
					COALESCE(t_sites.oid,0),
					COALESCE(t_lieux.oid,0),
					0::bigint AS provider_id,
					t_articles.fournisseur_principal_id AS fournisseur_id,
					CASE WHEN LAG(DTISKSTI) OVER (PARTITION BY ETSSKSTI, ARTSKSTI, DEPSKSTI ORDER BY DTISKSTI) + interval '1 day' = date_trunc('month',DTISKSTI) THEN 
						LAG(QTISKSTI) OVER (PARTITION BY ETSSKSTI, ARTSKSTI, DEPSKSTI ORDER BY DTISKSTI) 
						ELSE 0 END,
					CASE WHEN LAG(DTISKSTI) OVER (PARTITION BY ETSSKSTI, ARTSKSTI, DEPSKSTI ORDER BY DTISKSTI) + interval '1 day' = date_trunc('month',DTISKSTI) THEN
						LAG(QTISKSTI) OVER (PARTITION BY ETSSKSTI, ARTSKSTI, DEPSKSTI ORDER BY DTISKSTI) * LAG(PRXSKSTI) OVER (PARTITION BY ETSSKSTI, ARTSKSTI, DEPSKSTI ORDER BY DTISKSTI) 
						ELSE 0 END,
					0,
					0,
					0,
					PRXSKSTI,
					0,
					0,
					QTISKSTI,
					QTISKSTI * PRXSKSTI,
					0
				FROM w_stock
					LEFT JOIN eco.t_articles ON ARTSKSTI = t_articles.code_original
					LEFT JOIN eco.t_sites ON ETSSKSTI = t_sites.code_original
					LEFT JOIN eco.t_lieux ON ETSSKSTI || '-' || DEPSKSTI = t_lieux.code_original
					LEFT JOIN eco.t_compte ON CPSSKSTI = t_compte.code_original
				WHERE DTISKSTI > '[ENV_ECO_ANNEEDEBUT]0101'
				;
				
				INSERT INTO eco.p_stock
				(
					fournisseur_id,
					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.fournisseur_id,
					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,
					0,
					p_stock.stock_valeur_fin,
					p_stock.stock_valeur_fin_ttc,
					0,
					0
				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 >= '[ENV_ECO_ANNEEDEBUT]0101' AND
					p_stock.stock_quantite_fin != 0 AND
					p_stock_next.article_id IS NULL
				;

				DROP TABLE IF EXISTS w_mv_sto;
				CREATE TEMP TABLE w_mv_sto AS
				SELECT 
					article_id,
					date_trunc('month',date) AS date_debut,
					site_id,
					lieu_id,
					SUM(entree_quantite) AS entrees_quantite,
					SUM(entree_montant) AS entrees_montant,
					SUM(sortie_quantite) AS sorties_quantite,
					SUM(sortie_montant) AS sorties_montant
				FROM eco.p_mouvements_articles
				GROUP BY 1,2,3,4
				;
				
				UPDATE eco.p_stock
				SET
					entree_quantite = entrees_quantite,
					entree_montant = entrees_montant,
					sortie_quantite = sorties_quantite,
					sortie_montant = sorties_montant
				FROM w_mv_sto
				WHERE 
					p_stock.article_id = w_mv_sto.article_id
					AND p_stock.site_id = w_mv_sto.site_id
					AND p_stock.lieu_id = w_mv_sto.lieu_id
					AND p_stock.date_debut = w_mv_sto.date_debut
				;
					
				UPDATE eco.p_stock SET
					stock_valeur_fin_ttc = stock_valeur_fin * taux
				FROM w_taux_histo
				JOIN eco.t_articles ON code_original = ARTSALCA
				WHERE article_id = t_articles.oid
					AND date_fin BETWEEN DCRSALCA AND next_DCRSALCA
				;
					
				UPDATE eco.p_stock SET
					stock_valeur_debut_ttc = stock_valeur_debut_ttc * taux
				FROM w_taux_histo
				JOIN eco.t_articles ON code_original = ARTSALCA
				WHERE article_id = t_articles.oid
					AND date_debut BETWEEN DCRSALCA AND next_DCRSALCA
				;
					
				
				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');

				SELECT eco.cti_update_mvt_qte_stock();
				SELECT eco.cti_update_mvt_mnt_stock();
				
			]]></sqlcmd>
		</NODE>
		
		<NODEx label="Factures">
			<sqlcmd><![CDATA[
			
				

			
			]]></sqlcmd>
		</NODEx>
		
		</NODE>
	<NODE name="POST" label="POST-TRAITEMENTS">
		<sqlcmd><![CDATA[
				SELECT eco.cti_reorganize_sejour();
		]]></sqlcmd>
	</NODE>
	
</ROOT>