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


	<NODE name="INIT" label="INITIALISATIONS">


		<NODE label="Tables Articles">

			<sqlcmd><![CDATA[
			
				-- Table articles avec autres caractéristiques
				INSERT INTO eco.t_divers (code, texte, valeur, description)
				SELECT
					'X3_TYPART',
					'Source du type d''article',
					'0',
					'0=Première lettre du code, 1=Champ X_TYPACT_0'
				WHERE 'X3_TYPART' NOT IN (SELECT code FROM eco.t_divers)
                ;
			
				-- Table articles avec autres caractéristiques
				DROP TABLE IF EXISTS w_ITMMASTER;
				CREATE TEMP TABLE w_ITMMASTER AS
				SELECT ITMMASTER.*,
					''::text AS FAMCMP_CODE_CTI,
					''::text AS SFMCP_CODE_CTI
				FROM prod_sagex3.ITMMASTER
				;
				
				-- Colonne LPP selon integrateur
				SELECT base.cti_execute('ALTER TABLE w_ITMMASTER ADD COLUMN X_LPPT_0 text., UPDATE w_ITMMASTER SET X_LPPT_0 = X_LPP_0',1)
				WHERE 'x_lpp_0' IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmmaster' AND table_schema = 'prod_sagex3') AND
					'x_lppt_0' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmmaster' AND table_schema = 'prod_sagex3')
				;
				SELECT base.cti_execute('ALTER TABLE w_ITMMASTER ADD COLUMN X_LPPF_0 text., UPDATE w_ITMMASTER SET X_LPPF_0 = X_LPP_0',1)
				WHERE 'x_lpp_0' IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmmaster' AND table_schema = 'prod_sagex3') AND
					'x_lppf_0' NOT IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmmaster' AND table_schema = 'prod_sagex3')
				;
                
                CREATE INDEX w_ITMMASTER_i1 ON w_ITMMASTER USING btree (ITMREF_0);	


				DELETE FROM w_ITMMASTER
				USING
				(
				SELECT ITMREF_0, MAX(CTID) AS delCTID
				FROM w_ITMMASTER 
				GROUP BY 1
				HAVING count(*) > 1
				) subview
				WHERE w_ITMMASTER.ITMREF_0 = subview.ITMREF_0 AND 
					w_ITMMASTER.CTID = delCTID
                ;

				-- Unites de stockage
				INSERT INTO eco.t_unites(code, code_original, texte, texte_court)
				SELECT
					UOM_0,
					UOM_0,
					UOM_0,
					UOM_0
				FROM
					prod_sagex3.TABUNIT
				WHERE UOMTYP_0 IN (6,7)
					AND UOM_0 NOT IN (SELECT code_original from eco.t_unites);
					
				-- LPP
				SELECT base.cti_execute('
                INSERT INTO base.t_lpp (code, texte, texte_court)
				SELECT X_CODLPP_0, X_LIBELLE_0, XLPP
				FROM prod_sagex3.XLPP
				WHERE X_CODLPP_0 NOT IN (SELECT code FROM base.t_lpp)
					AND X_CODLPP_0 IN (SELECT X_LPPT_0 FROM w_ITMMASTER)',1)
                WHERE EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'prod_sagex3' AND table_name = 'xlpp');
				
				-- UCD
				SELECT base.cti_execute('
				INSERT INTO base.t_ucd (code, texte, texte_court, laboratoire_texte, conditionnement_texte)
				SELECT X_UCDCOD_0, MAX(X_LIBELLE_0), MAX(X_LIBELLE_0), MAX(X_LABO_0), MAX(X_FORME_0)
				FROM prod_sagex3.XUCD
				WHERE X_UCDCOD_0 NOT IN (SELECT code FROM base.t_ucd)
					AND X_UCDCOD_0 IN (SELECT X_UCDCOD_0 FROM w_ITMMASTER)
				GROUP BY 1',1)
				WHERE EXISTS (SELECT 1 FROM information_schema.tables WHERE table_schema = 'prod_sagex3' AND table_name = 'xucd');
				
				-- ATC
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD1_0), UPPER(MAX(X_ATCCOD1_0)), MAX(X_ATCDES1_0), MAX(X_ATCDES1_0) 
				FROM prod_sagex3.XATC1
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD1_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;

				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD2_0), UPPER(MAX(X_ATCCOD2_0)), MAX(X_ATCDES2_0), MAX(X_ATCDES2_0) 
				FROM prod_sagex3.XATC2
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD2_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;

				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD3_0), UPPER(MAX(X_ATCCOD3_0)), MAX(X_ATCDES3_0), MAX(X_ATCDES3_0) 
				FROM prod_sagex3.XATC3
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD3_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;

				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD4_0), UPPER(MAX(X_ATCCOD4_0)), MAX(X_ATCDES4_0), MAX(X_ATCDES4_0) 
				FROM prod_sagex3.XATC4
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD4_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;
	
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD5_0), UPPER(MAX(X_ATCCOD5_0)), MAX(X_ATCDES5_0), MAX(X_ATCDES5_0) 
				FROM prod_sagex3.XATC5
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD5_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;
				
				INSERT INTO eco.t_classification_atc(code_original, code, texte, texte_court )
				SELECT UPPER(X_ATCCOD_0), UPPER(MAX(X_ATCCOD_0)), MAX(X_ATCDES_0), MAX(X_ATCDES_0) 
				FROM prod_sagex3.XATC
				LEFT JOIN eco.t_classification_atc ON code_original = UPPER(X_ATCCOD_0)
				WHERE code_original IS NULL 
				GROUP BY 1
				ORDER BY 1;
				
				-- Standard ATC
				SELECT eco.cti_reorganize_classification_atc();
			
			
				-- Comptes
				INSERT INTO eco.t_compte(code, texte, texte_court, code_original)
				SELECT 
						GACCOUNT.ACC_0 AS code, 
						MAX(GACCOUNT.DES_0) AS texte, 
						MAX(GACCOUNT.DES_0) AS texte, 
						GACCOUNT.ACC_0 AS code_original
				FROM prod_sagex3.GACCOUNT
					JOIN w_ITMMASTER ON ACCCOD_0 = ACC_0
				WHERE ACC_0 NOT IN (SELECT code_original FROM eco.t_compte WHERE code_original IS NOT NULL)
				GROUP BY 1
				ORDER BY 1;
				
					
				-- Types d'articles
				INSERT INTO eco.t_types_articles(code, texte, texte_court, code_original)
				SELECT upper(substr(ITMREF_0,1,1)), upper(substr(ITMREF_0,1,1)),upper(substr(ITMREF_0,1,1)), upper(substr(ITMREF_0,1,1))
				FROM prod_sagex3.ITMMASTER
				JOIN eco.t_divers ON t_divers.code = 'X3_TYPART' AND t_divers.valeur <> '1'
				WHERE upper(substr(ITMREF_0,1,1)) NOT IN (SELECT code_original FROM eco.t_types_articles WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				ORDER BY 1;
				
				INSERT INTO eco.t_types_articles(code, texte, texte_court, code_original)
				SELECT LANNUM_0::text, LANMES_0, LANMES_0, LANNUM_0::text
				FROM prod_sagex3.APLSTD
				JOIN eco.t_divers ON t_divers.code = 'X3_TYPART' AND t_divers.valeur = '1'
				WHERE LANCHP_0 = '1019' AND
					LANNUM_0::text NOT IN (SELECT code_original FROM eco.t_types_articles WHERE code_original IS NOT NULL)
				ORDER BY 1;
					
				
				-- Familles d'articles
				DROP TABLE IF EXISTS w_FAMILLE;
				CREATE TEMP TABLE w_FAMILLE AS
				SELECT XFAMILLE.X_GRPFAM_0, 
					XFAMILLE.X_FAMCOD_0 AS CODE,
					UPPER(XFAMILLE.X_FAMCOD_0) AS CODE_CTI, 
					XFAMILLE.X_GRPCOD_0 AS GROUPE,
					XFAMILLE.X_FAMCOD_0 AS GROUPE_CODE, 
					MAX(XFAMILLE.X_FAMDES_0) AS LIBELLE
				FROM prod_sagex3.XFAMILLE
				JOIN w_ITMMASTER  ON
					XFAMILLE.X_GRPCOD_0 = w_ITMMASTER.X_GRPCOD_0 AND
					XFAMILLE.X_FAMCOD_0 = w_ITMMASTER.X_FAMCOD_0
				WHERE XFAMILLE.X_FAMCOD_0 != ''
				GROUP BY 1,2,3,4
				ORDER BY 1,2;
				
				UPDATE w_FAMILLE SET
					CODE_CTI = CODE_CTI || ' (' || GROUPE || ')',
					GROUPE_CODE = CODE || '-' || GROUPE
				WHERE CODE IN (SELECT CODE FROM w_FAMILLE GROUP BY 1 HAVING COUNT(DISTINCT LIBELLE) > 1);

				INSERT INTO eco.t_familles_articles(code, texte, texte_court, code_original)
				SELECT CODE_CTI, LIBELLE, LIBELLE, GROUPE_CODE
				FROM w_FAMILLE
				WHERE GROUPE_CODE != '' AND
					GROUPE_CODE NOT IN (SELECT code_original FROM eco.t_familles_articles WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				ORDER BY 1;

				UPDATE eco.t_familles_articles
				SET texte = LIBELLE, texte_court = LIBELLE
				FROM w_FAMILLE
				WHERE w_FAMILLE.GROUPE_CODE = code_original AND
					(texte IS DISTINCT FROM LIBELLE OR 
					texte_court IS DISTINCT FROM LIBELLE);

				
					
				-- Sous familles
				DROP TABLE IF EXISTS w_SOUS_FAMILLE;
				CREATE TEMP TABLE w_SOUS_FAMILLE AS
				SELECT XSFAMILLE.X_SFACOD_0 AS CODE, 
					UPPER(XSFAMILLE.X_SFACOD_0) AS CODE_CTI, 
					XSFAMILLE.X_GRPCOD_0 AS GROUPE,
					XSFAMILLE.X_SFACOD_0 AS GROUPE_CODE, 
					MAX(XSFAMILLE.X_SFADES_0) AS LIBELLE
				FROM prod_sagex3.XSFAMILLE
					JOIN w_ITMMASTER ON
						XSFAMILLE.X_GRPCOD_0 = w_ITMMASTER.X_GRPCOD_0 AND
						XSFAMILLE.X_SFACOD_0 = w_ITMMASTER.X_SFACOD_0
				WHERE XSFAMILLE.X_SFACOD_0 != ''
				GROUP BY 1,2,3
				ORDER BY 1,2;

				UPDATE w_SOUS_FAMILLE SET
					CODE_CTI = CODE_CTI || ' (' || GROUPE || ')',
					GROUPE_CODE = CODE || '-' || GROUPE
				WHERE CODE IN (SELECT CODE FROM w_SOUS_FAMILLE GROUP BY 1 HAVING COUNT(DISTINCT LIBELLE) > 1);

				INSERT INTO eco.t_sous_familles_articles(code, texte, texte_court, code_original)
				SELECT CODE_CTI, LIBELLE, LIBELLE, GROUPE_CODE
				FROM w_SOUS_FAMILLE
				WHERE 
					GROUPE_CODE NOT IN (SELECT code_original FROM eco.t_sous_familles_articles WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				ORDER BY 1;

				UPDATE eco.t_sous_familles_articles
				SET texte = LIBELLE, texte_court = LIBELLE
				FROM w_SOUS_FAMILLE
				WHERE w_SOUS_FAMILLE.GROUPE_CODE = code_original AND
					(texte IS DISTINCT FROM LIBELLE OR 
					texte_court IS DISTINCT FROM LIBELLE);
				
				
					
				-- Catégories
				DROP TABLE IF EXISTS w_XFAMCMP;
				CREATE TEMP TABLE w_XFAMCMP AS
				SELECT XFAMCMP.X_FMPCOD_0 AS CODE, 
					UPPER(XFAMCMP.X_FMPCOD_0) AS CODE_CTI, 
					XFAMCMP.X_FMPCOD_0 AS GROUPE_CODE, 
				MAX(XFAMCMP.X_FMPDES_0) AS LIBELLE
				FROM prod_sagex3.XFAMCMP
				JOIN w_ITMMASTER ON
					XFAMCMP.X_FMPCOD_0 = w_ITMMASTER.X_FMPCOD_0
				 WHERE XFAMCMP.X_FMPCOD_0 != ''
				GROUP BY 1,2,3
				ORDER BY 1,2;

				INSERT INTO eco.t_categories_articles(code, texte, texte_court, code_original)
				SELECT TCLCOD_0, TCLCOD_0, TCLCOD_0, TCLCOD_0
				FROM prod_sagex3.ITMCATEG
				WHERE
					TCLCOD_0 NOT IN (SELECT code_original FROM eco.t_categories_articles WHERE code_original IS NOT NULL)
				GROUP BY 1,2,3,4
				ORDER BY 1;

				UPDATE eco.t_categories_articles SET
					texte = TEXTE_0, texte_court = substr(TEXTE_0,1,50)
				FROM prod_sagex3.ATEXTRA
				WHERE code_original = IDENT1_0 AND
					LANGUE_0 = 'FRA' AND
					ZONE_0 = 'TCLAXX' AND
					(texte <> TEXTE_0 OR texte_court <> substr(TEXTE_0,1,50))
				;
					
				-- Sous catégories
				DROP TABLE IF EXISTS w_XSFACMP;
				CREATE TEMP TABLE w_XSFACMP AS
				SELECT XSFACMP.X_SFMCOD_0 AS CODE, 
					UPPER(XSFACMP.X_SFMCOD_0) AS CODE_CTI, 
					XSFACMP.X_SFMCOD_0 AS GROUPE_CODE, 
					MAX(XSFACMP.X_SFMDES_0) AS LIBELLE
				FROM prod_sagex3.XSFACMP
				JOIN w_ITMMASTER ON
					XSFACMP.X_SFMCOD_0 = w_ITMMASTER.X_SFMCOD_0
				GROUP BY 1,2,3
				ORDER BY 1,2;
			
				INSERT INTO eco.t_sous_categories_articles(code, code_original, texte, texte_court)
				SELECT x_GRPCOD_0, x_GRPCOD_0, MAX(x_GRPDES_0), MAX(x_GRPDES_0)
				FROM prod_sagex3.XGROUPE
				WHERE
					x_GRPCOD_0 NOT IN (SELECT code_original FROM eco.t_sous_categories_articles WHERE code_original IS NOT NULL)
				GROUP BY 1,2
				ORDER BY 1;

				UPDATE eco.t_sous_categories_articles
				SET texte = x_GRPDES_0, texte_court = substr(x_GRPDES_0,1,50)
				FROM prod_sagex3.XGROUPE
				WHERE x_GRPCOD_0 = code_original AND
					(
					texte IS DISTINCT FROM x_GRPDES_0 OR 
					texte_court IS DISTINCT FROM substr(x_GRPDES_0,1,50)
					);

				
				-- Articles

				INSERT INTO eco.t_articles(code, texte, texte_court, code_original)
				SELECT ITMREF_0, ITMDES1_0, substr(ITMDES1_0,1,50), ITMREF_0
				FROM w_ITMMASTER
					LEFT JOIN eco.t_articles ON (code_original = ITMREF_0)
				WHERE code_original IS NULL;


				UPDATE eco.t_articles
				SET 
					texte = ITMDES1_0,
					texte_court = substr(ITMDES1_0,1,50)
				FROM w_ITMMASTER
				WHERE code_original = ITMREF_0
				AND (
					texte IS DISTINCT FROM ITMDES1_0 OR
					texte_court IS DISTINCT FROM substr(ITMDES1_0,1,50));




				UPDATE eco.t_articles SET
					type_id = COALESCE(t_types_articles.oid,0),
					famille_id = COALESCE(t_familles_articles.oid,fam_grp.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)
				FROM w_ITMMASTER
					JOIN eco.t_divers ON t_divers.code = 'X3_TYPART'
					LEFT JOIN eco.t_familles_articles ON X_FAMCOD_0 = upper(t_familles_articles.code_original)
					LEFT JOIN eco.t_familles_articles fam_grp ON X_FAMCOD_0 || '-' || X_GRPCOD_0 = upper(fam_grp.code_original)
					LEFT JOIN eco.t_sous_familles_articles ON X_SFACOD_0 = upper(t_sous_familles_articles.code_original)
					LEFT JOIN eco.t_types_articles ON 
						CASE 
							WHEN t_divers.valeur = '1' THEN X_TYPACT_0::text
							ELSE upper(substr(ITMREF_0,1,1))
							END = upper(t_types_articles.code_original)

					LEFT JOIN eco.t_classification_atc ON X_ATCCOD5_0 = upper(t_classification_atc.code_original)
					LEFT JOIN eco.t_categories_articles ON TCLCOD_0 = upper(t_categories_articles.code_original)
					LEFT JOIN eco.t_sous_categories_articles ON X_GRPCOD_0 = upper(t_sous_categories_articles.code_original)
					LEFT JOIN eco.t_unites t_unites_stockage ON w_ITMMASTER.STU_0 = upper(t_unites_stockage.code_original)
					LEFT JOIN eco.t_unites t_unites_distribution ON w_ITMMASTER.SAU_0 = upper(t_unites_distribution.code_original)
					LEFT JOIN base.t_lpp ON coalesce(nullif(X_LPP_0, ''), nullif(x_lppf_0, ''), nullif(x_lppt_0, '')) = t_lpp.code
					LEFT JOIN base.t_ucd ON COALESCE(NULLIF(X_UCDCOD_0, '')) = t_ucd.code
				WHERE 
					t_articles.code_original = w_ITMMASTER.ITMREF_0 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,fam_grp.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
					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 = COALESCE(t_compte.oid,0)
				FROM w_ITMMASTER
					LEFT JOIN eco.t_compte ON ACCCOD_0 = t_compte.code_original
				WHERE 
					t_articles.code_original = ITMREF_0 AND
					(
					t_articles.compte_id IS DISTINCT FROM COALESCE(t_compte.oid,0)
					);

				UPDATE eco.t_articles SET compte_id = 0 WHERE compte_id IS NULL;
                
                -- gere en stock
				-- niveau articles
                UPDATE eco.t_articles
                SET gere_en_stock = CASE WHEN STOMGTCOD_0 = 1 OR X_TYPSTK_0 != 1 THEN '0' ELSE '1' END
                FROM prod_sagex3.ITMMASTER
                WHERE ITMREF_0 = code_original AND
                    gere_en_stock != CASE WHEN STOMGTCOD_0 = 1 THEN '0' ELSE '1' END
                ;
				
				-- niveau categorie (seulement pour désactiver)
				UPDATE eco.t_articles
                SET gere_en_stock = '0'
                FROM prod_sagex3.ITMCATEG
                WHERE TCLCOD_0 = categorie_code AND
                    LOCMGTCOD_0 = 0
                ;
				
				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
					);
					
					UPDATE eco.t_articles
					SET taux_tva_en_cours = VAT_RAT
					FROM
					(
					SELECT ITMREF_0, MAX(CASE WHEN VATRAT_0 = 20.6 THEN 20 ELSE VATRAT_0 END) AS VAT_RAT, count(*)
					FROM prod_sagex3.ITMMASTER
					JOIN prod_sagex3.TABVAC ON TABVAC.vacitm_0 = ITMMASTER.vacitm_0
					JOIN prod_sagex3.TABVAT ON TABVAC.VAT_0 = TABVAT.VAT_0
					GROUP BY 1
					) subview
					WHERE ITMREF_0 = t_articles.code_original AND
						taux_tva_en_cours IS DISTINCT FROM VAT_RAT
					;


			]]>			
</sqlcmd>
		</NODE>


		<NODE label="Tables Fournisseurs">
			<sqlcmd><![CDATA[
			
				-- Types de fournisseurs
				UPDATE prod_sagex3.BPARTNER
				SET BPSFLG_0 = CASE WHEN BPRNUM_0 IN (SELECT BPSNUM_0 FROM prod_sagex3.BPSUPPLIER) THEN 2 ELSE 1 END
				WHERE BPSFLG_0 <> CASE WHEN BPRNUM_0 IN (SELECT BPSNUM_0 FROM prod_sagex3.BPSUPPLIER) THEN 2 ELSE 1 END
				;				
				
				-- Fournisseurs (basé sur commandes)
				INSERT INTO eco.t_fournisseurs(code, code_original, texte, texte_court)
				SELECT BPSNUM_0, BPSNUM_0, BPSNAM_0, CASE WHEN BPSSHO_0 != '' THEN BPSSHO_0 ELSE BPSNAM_0 END
				FROM prod_sagex3.BPSUPPLIER
						JOIN prod_sagex3.BPADDRESS ON BPSUPPLIER.BPSNUM_0 = BPADDRESS.BPANUM_0 
				WHERE BPSNUM_0 NOT IN (SELECT code_original FROM eco.t_fournisseurs WHERE code_original IS NOT NULL)
				   AND BPSNUM_0 IN (SELECT BPSNUM_0 FROM prod_sagex3.PORDER GROUP BY 1)
				   GROUP BY 1,2,3,4
				ORDER BY BPSNUM_0
				;
				
				-- fournisseurs (basés sur mouvements au cas ou)
				INSERT INTO eco.t_fournisseurs(code, code_original, texte, texte_court)
				SELECT BPRNUM_0, BPRNUM_0, BPRNAM_0, BPRNAM_0
				FROM prod_sagex3.BPARTNER
				WHERE BPRNUM_0 IN (SELECT BPRNUM_0 FROM prod_sagex3.STOJOU GROUP BY 1)
					AND BPRNUM_0 NOT IN (SELECT code_original FROM eco.t_fournisseurs)
					AND BPSFLG_0 = 2 --  BPRNUM_0 ~  '^[0-9].*$'
				;
				
				INSERT INTO eco.t_fournisseurs(code, code_original, texte, texte_court)
				SELECT BPRNUM_0, BPRNUM_0, BPRNAM_0, BPRNAM_0
				FROM prod_sagex3.BPARTNER
				WHERE BPRNUM_0 IN (SELECT BPSNUM_0 FROM prod_SAGEX3.ITMBPS GROUP BY 1)
					AND BPRNUM_0 NOT IN (SELECT code_original FROM eco.t_fournisseurs)
					AND BPSFLG_0 = 2 --  BPRNUM_0 ~  '^[0-9].*$'
				;

				INSERT INTO base.t_codes_postaux(code, texte, texte_court, departement_id)
				SELECT POSCOD_0, MAX(CTY_0), MAX(CTY_0), MAX(t_departements.oid)
				FROM prod_sagex3.BPSUPPLIER
				JOIN prod_sagex3.BPADDRESS ON BPSUPPLIER.BPSNUM_0 = BPADDRESS.BPANUM_0
				LEFT JOIN base.t_codes_postaux ON POSCOD_0 = t_codes_postaux.code
				JOIN base.t_departements ON CASE WHEN CRY_0 = 'FR' THEN substr(POSCOD_0,1,2) else '99' END = t_departements.code
				WHERE t_codes_postaux.oid IS NULL 
				GROUP BY 1
				;		
				
				UPDATE eco.t_fournisseurs
				SET 
					texte = BPSNAM_0,
					texte_court =  CASE WHEN BPSSHO_0 != '' THEN BPSSHO_0 ELSE BPSNAM_0 END,
					adresse = trim(BPAADDLIG_0 || ' ' || BPAADDLIG_1 || ' ' || BPAADDLIG_2),
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = CTY_0,
					telephone = TEL_0,
					fax = FAX_0,
					email = WEB_0
				FROM prod_sagex3.BPSUPPLIER
				JOIN prod_sagex3.BPADDRESS ON BPSUPPLIER.BPSNUM_0 = BPADDRESS.BPANUM_0
				LEFT JOIN base.t_codes_postaux ON POSCOD_0 = t_codes_postaux.code
				WHERE code_original = BPSUPPLIER.BPSNUM_0
				AND
					(
					t_fournisseurs.texte IS DISTINCT FROM BPSNAM_0 OR
					t_fournisseurs.texte_court IS DISTINCT FROM CASE WHEN BPSSHO_0 != '' THEN BPSSHO_0 ELSE BPSNAM_0 END OR
					t_fournisseurs.adresse IS DISTINCT FROM trim(BPAADDLIG_0 || ' ' || BPAADDLIG_1 || ' ' || BPAADDLIG_2) OR
					t_fournisseurs.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					t_fournisseurs.ville IS DISTINCT FROM CTY_0 OR
					t_fournisseurs.telephone IS DISTINCT FROM TEL_0 OR
					t_fournisseurs.fax IS DISTINCT FROM FAX_0 OR
					t_fournisseurs.email IS DISTINCT FROM WEB_0
					)
				;				
				
				UPDATE eco.t_fournisseurs
				SET 
					texte = BPRNAM_0,
					texte_court =  CASE WHEN BPRSHO_0 != '' THEN BPRSHO_0 ELSE BPRNAM_0 END,
					adresse = trim(BPAADDLIG_0 || ' ' || BPAADDLIG_1 || ' ' || BPAADDLIG_2),
					code_postal_id = COALESCE(t_codes_postaux.oid,0),
					ville = CTY_0,
					telephone = TEL_0,
					fax = FAX_0,
					email = WEB_0,
					siret = BPARTNER.CRN_0,
					iban = CASE WHEN length(BPARTNER.BIDNUM_0) = 23 THEN CASE WHEN IBAN_0 <> '' THEN IBAN_0 ELSE 'FR76' END || BPARTNER.BIDNUM_0 ELSE '' END,
					bic = COALESCE(BICCOD_0,'')
				FROM prod_sagex3.BPARTNER
				JOIN prod_sagex3.BPADDRESS ON BPARTNER.BPRNUM_0 = BPADDRESS.BPANUM_0 AND BPARTNER.BPAADD_0 = BPADDRESS.BPAADD_0
				LEFT JOIN base.t_codes_postaux ON POSCOD_0 = t_codes_postaux.code
				LEFT JOIN prod_sagex3.BID ON BPARTNER.BPRNUM_0 = BID.BPANUM_0
				WHERE code_original = BPARTNER.BPRNUM_0
				AND
					(
					t_fournisseurs.texte IS DISTINCT FROM BPRNAM_0 OR
					t_fournisseurs.texte_court IS DISTINCT FROM CASE WHEN BPRSHO_0 != '' THEN BPRSHO_0 ELSE BPRNAM_0 END OR
					t_fournisseurs.adresse IS DISTINCT FROM trim(BPAADDLIG_0 || ' ' || BPAADDLIG_1 || ' ' || BPAADDLIG_2) OR
					t_fournisseurs.code_postal_id IS DISTINCT FROM COALESCE(t_codes_postaux.oid,0) OR
					t_fournisseurs.ville IS DISTINCT FROM CTY_0 OR
					t_fournisseurs.telephone IS DISTINCT FROM TEL_0 OR
					t_fournisseurs.fax IS DISTINCT FROM FAX_0 OR
					t_fournisseurs.email IS DISTINCT FROM WEB_0 OR
					t_fournisseurs.siret IS DISTINCT FROM BPARTNER.CRN_0 OR
					t_fournisseurs.iban IS DISTINCT FROM CASE WHEN length(BPARTNER.BIDNUM_0) = 23 THEN CASE WHEN BPARTNER.CRY_0 = 'FR' THEN 'FR76' ELSE '' END || BPARTNER.BIDNUM_0 ELSE '' END OR
					t_fournisseurs.bic IS DISTINCT FROM COALESCE(BICCOD_0,'')
					)
				;

				UPDATE eco.t_fournisseurs
				SET type_id = 0
				WHERE type_id IS NULL;	
				
				UPDATE eco.t_fournisseurs SET
					type_code = t_types_fournisseurs.code,
					type_texte = t_types_fournisseurs.texte_court,
					type_section_id = t_types_fournisseurs.section_id,
					type_section_code = t_types_fournisseurs.section_code,
					type_section_texte = t_types_fournisseurs.section_texte
				FROM eco.t_types_fournisseurs
				WHERE type_id = t_types_fournisseurs.oid
					AND (
						type_code IS DISTINCT FROM t_types_fournisseurs.code OR
						type_texte IS DISTINCT FROM t_types_fournisseurs.texte_court OR
						type_section_id IS DISTINCT FROM t_types_fournisseurs.section_id OR
						type_section_code IS DISTINCT FROM t_types_fournisseurs.section_code OR
						type_section_texte IS DISTINCT FROM t_types_fournisseurs.section_texte
					);
					
					
				UPDATE eco.t_articles SET
					fournisseur_principal_id = t_fournisseurs.oid
				FROM w_ITMMASTER, eco.t_fournisseurs
				WHERE 1=1
					AND t_fournisseurs.code = X_BPSPRIO_0
					AND ITMREF_0 = t_articles.code
				;
				
				UPDATE eco.t_articles SET
					ref_fournisseur_id = subview.ref_fournisseur_id,
					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(ref_fournisseur_texte) AS ref_fournisseur_texte
						FROM 
						(
							SELECT 
								t_articles.oid AS article_id,
								t_fournisseurs.oid AS fournisseur_id,
								ITMDESBPS_0 || '(' || ITMREFBPS_0 || ')' AS ref_fournisseur_texte
							FROM eco.t_articles
								LEFT JOIN prod_sagex3.ITMBPS ON t_articles.code = ITMREF_0
								JOIN eco.t_fournisseurs ON BPSNUM_0 = t_fournisseurs.code
							GROUP BY 1,2,3
							ORDER BY 1,2,3
						) subview
						GROUP BY 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_texte IS DISTINCT FROM subview.ref_fournisseur_texte
						)
                ;
				
				-- Article fournisseur
				DROP TABLE IF EXISTS w_article_fournisseur_eco;
				CREATE TEMP TABLE w_article_fournisseur_eco AS
				SELECT
					ITMBPS.ITMREF_0 || '-' ||ITMBPS.BPSNUM_0 AS code_original,
					t_articles.oid AS article_id,
					t_fournisseurs.oid AS fournisseur_id,
					CASE WHEN ITMREFBPS_0 <> '' THEN ITMREFBPS_0 ELSE EANCODBPS_0 END AS code_reference_fournisseur,
					ITMDESBPS_0 AS texte_reference_fournisseur,
					X_CIPCOD13_0 AS code_cip,
					''::text AS code_cahpp,
					COALESCE(t_unites.oid,0) AS unite_approvisionnement_id,
					ITMBPS.PUUSTUCOE_0 AS nombre_conditionnement_approvisionnement,
					0::numeric AS prix_unitaire_en_cours,
					CASE WHEN row_number() OVER (PARTITION BY ITMBPS.ITMREF_0 ORDER BY PIO_0) = 1 THEn '1' ELSE '0' END AS est_fournisseur_principal,
					t_fournisseurs.oid AS fournisseur_distributeur_id,
					X_UCDCOD_0 AS ucd_code,
					0::bigint AS ucd_id,
					X_LPPT_0 AS lpp_code,
					0::bigint AS lpp_id,
					X_UCDCOD13_0 AS code_ucd13
				FROM prod_SAGEX3.ITMBPS
				JOIN w_ITMMASTER ITMMASTER ON ITMBPS.ITMREF_0 = ITMMASTER.ITMREF_0
				JOIN eco.t_articles ON ITMBPS.ITMREF_0 = t_articles.code_original
				JOIN eco.t_fournisseurs ON ITMBPS.BPSNUM_0 = t_fournisseurs.code_original
				LEFT JOIN eco.t_unites ON ITMBPS.PCU_0 = t_unites.code_original
				;
				
				ANALYSE w_article_fournisseur_eco
				;
				
				-- Champs supplémentaires provenant de ITMBPS
				SELECT base.cti_execute('
				UPDATE w_article_fournisseur_eco
				SET ucd_code = X_UCDITP_0
				FROM prod_SAGEX3.ITMBPS
				WHERE ITMBPS.ITMREF_0 || ''-'' ||ITMBPS.BPSNUM_0 = code_original AND
					X_UCDITP_0 <> '''' AND
					length(X_UCDITP_0) = 7 AND
					ucd_code <> X_UCDITP_0 
				',1)
				WHERE 'x_ucditp_0' IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmbps')
				;

				SELECT base.cti_execute('
				UPDATE w_article_fournisseur_eco
				SET code_ucd13 = X_UCDITP1_0
				FROM prod_SAGEX3.ITMBPS
				WHERE ITMBPS.ITMREF_0 || ''-'' ||ITMBPS.BPSNUM_0 = code_original AND
					X_UCDITP_0 <> '''' AND
					length(X_UCDITP1_0) = 13 AND
					code_ucd13 <> X_UCDITP1_0 AND
					X_UCDITP1_0 LIKE ''34008%''
				',1)
				WHERE 'x_ucditp1_0' IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmbps')
				;

				SELECT base.cti_execute('
				UPDATE w_article_fournisseur_eco
				SET code_cip = X_CIPITP1_0
				FROM prod_SAGEX3.ITMBPS
				WHERE ITMBPS.ITMREF_0 || ''-'' ||ITMBPS.BPSNUM_0 = code_original AND
					X_UCDITP_0 <> '''' AND
					length(X_CIPITP1_0) = 13 AND
					code_cip <> X_CIPITP1_0 AND
					X_CIPITP1_0 LIKE ''34%'' AND
					X_CIPITP1_0 NOT LIKE ''34008%''
				',1)
				WHERE 'x_cipitp1_0' IN (SELECT column_name FROM information_schema.columns WHERE table_name = 'itmbps')
				;
				
				-- Code UCD selon code ucd 13
				UPDATE w_article_fournisseur_eco
				SET ucd_code = substr(code_ucd13,6,7)
				WHERE ucd_code = '' AND code_ucd13 LIKE '34008%'
				;

				UPDATE w_article_fournisseur_eco
				SET ucd_id = t_ucd.oid
				FROM base.t_ucd 
				WHERE ucd_code = t_ucd.code
				;
				UPDATE w_article_fournisseur_eco
				SET lpp_id = t_lpp.oid
				FROM base.t_lpp 
				WHERE lpp_code = t_lpp.code
				;
				
				UPDATE w_article_fournisseur_eco
				SET prix_unitaire_en_cours = NETPRI_0
				FROM 
				(
				SELECT PORDERP.ITMREF_0 || '-' ||PORDER.BPSNUM_0 AS code_original,
					(MAX(ARRAY[ORDDAT_0::text,NETPRI_0::text]))[2]::numeric AS NETPRI_0
				FROM prod_sagex3.PORDER
				JOIN prod_sagex3.PORDERP ON PORDERP.POHNUM_0 = PORDER.POHNUM_0 
				GROUP BY 1
				) subview
				WHERE w_article_fournisseur_eco.code_original = subview.code_original
				;


				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,
					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
				FROM w_article_fournisseur_eco
				WHERE w_article_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_article_fournisseur_eco.article_id,
					fournisseur_id = w_article_fournisseur_eco.fournisseur_id,
					code_reference_fournisseur = w_article_fournisseur_eco.code_reference_fournisseur,
					texte_reference_fournisseur = w_article_fournisseur_eco.texte_reference_fournisseur,
					code_cip = w_article_fournisseur_eco.code_cip,
					code_ucd13 = w_article_fournisseur_eco.code_ucd13,
					ucd_id = w_article_fournisseur_eco.ucd_id,
					lpp_id = w_article_fournisseur_eco.lpp_id,
					code_cahpp = w_article_fournisseur_eco.code_cahpp,
					unite_approvisionnement_id = w_article_fournisseur_eco.unite_approvisionnement_id,
					nombre_conditionnement_approvisionnement = w_article_fournisseur_eco.nombre_conditionnement_approvisionnement,
					prix_unitaire_en_cours = w_article_fournisseur_eco.prix_unitaire_en_cours
				FROM w_article_fournisseur_eco
				WHERE t_article_fournisseur.code_original = w_article_fournisseur_eco.code_original AND
					(
						t_article_fournisseur.article_id IS DISTINCT FROM w_article_fournisseur_eco.article_id OR
						t_article_fournisseur.fournisseur_id IS DISTINCT FROM w_article_fournisseur_eco.fournisseur_id OR
						t_article_fournisseur.code_reference_fournisseur IS DISTINCT FROM w_article_fournisseur_eco.code_reference_fournisseur OR
						t_article_fournisseur.texte_reference_fournisseur IS DISTINCT FROM w_article_fournisseur_eco.texte_reference_fournisseur OR
						t_article_fournisseur.code_cip IS DISTINCT FROM w_article_fournisseur_eco.code_cip OR
						t_article_fournisseur.code_ucd13 IS DISTINCT FROM w_article_fournisseur_eco.code_ucd13 OR
						t_article_fournisseur.ucd_id IS DISTINCT FROM w_article_fournisseur_eco.ucd_id OR
						t_article_fournisseur.lpp_id IS DISTINCT FROM w_article_fournisseur_eco.lpp_id OR
						t_article_fournisseur.code_cahpp IS DISTINCT FROM w_article_fournisseur_eco.code_cahpp OR
						t_article_fournisseur.unite_approvisionnement_id IS DISTINCT FROM w_article_fournisseur_eco.unite_approvisionnement_id OR
						t_article_fournisseur.nombre_conditionnement_approvisionnement IS DISTINCT FROM w_article_fournisseur_eco.nombre_conditionnement_approvisionnement OR
						t_article_fournisseur.prix_unitaire_en_cours IS DISTINCT FROM w_article_fournisseur_eco.prix_unitaire_en_cours
					)
				;

			]]>			
</sqlcmd>
		</NODE>



		<NODE label="Autres tables">
			<sqlcmd><![CDATA[
			
				-- Gestionnaires
				
				-- Achats
				INSERT INTO eco.t_gestionnaires(code_original, code, texte, texte_court)
				SELECT USR_0, USR_0, NOMUSR_0, NOMUSR_0
				FROM prod_sagex3.AUTILIS 
					LEFT JOIN eco.t_gestionnaires ON (code_original = USR_0)
				WHERE code_original IS NULL AND
					USR_0 IN (SELECT USR_0 FROM prod_sagex3.PORDER);
					
				-- Stocks
				INSERT INTO eco.t_gestionnaires(code_original, code, texte, texte_court)
				SELECT USR_0, USR_0, NOMUSR_0, NOMUSR_0
				FROM prod_sagex3.AUTILIS 
					LEFT JOIN eco.t_gestionnaires ON (code_original = USR_0)
				WHERE code_original IS NULL AND
					USR_0 IN (SELECT UPDUSR_0 FROM prod_sagex3.STOCK);
				
			
				-- Unités fonctionnelles
				INSERT INTO eco.t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT BPRNUM_0, BPRNUM_0, BPRNAM_0, BPRNAM_0
				FROM prod_sagex3.BPARTNER
				WHERE BPRNUM_0 IN (
					SELECT BPRNUM_0 
					FROM prod_sagex3.STOJOU 
					GROUP BY 1
					)
					AND BPSFLG_0 = 1
					AND BPRNUM_0 NOT IN (SELECT code_original FROM eco.t_unites_fonctionnelles)
				;
			
				UPDATE eco.t_unites_fonctionnelles SET
					texte = FCYNAM_0,
					texte_court = FCYNAM_0
				FROM prod_sagex3.FACILITY 
					JOIN prod_sagex3.STOLOC ON FCY_0 = STOFCY_0
				WHERE code_original = FCY_0
				AND (texte IS DISTINCT FROM FCYNAM_0 OR
					texte_court IS DISTINCT FROM FCYNAM_0);
				
				-- Lieux
				INSERT INTO eco.t_lieux(code_original, code, texte, texte_court)
				SELECT STOFCY_0, STOFCY_0, STOFCY_0 , STOFCY_0
				FROM prod_sagex3.STOLOC
					LEFT JOIN eco.t_lieux ON (code_original = STOFCY_0)
				WHERE code_original IS NULL
				GROUP BY 1,2,3,4;
				
				INSERT INTO eco.t_lieux(code_original, code, texte, texte_court)
				SELECT LOC_0, LOC_0, LOC_0, LOC_0
				FROM prod_sagex3.STOLOC
					LEFT JOIN eco.t_lieux ON (code_original = LOC_0)
				WHERE code_original IS NULL
                GROUP BY 1,2,3,4;
								
				INSERT INTO eco.t_lieux(code_original, code, texte, texte_court)
				SELECT STOFCY_0, STOFCY_0, STOFCY_0 , STOFCY_0
				FROM prod_sagex3.STOLOC
					LEFT JOIN eco.t_lieux ON (code_original = STOFCY_0)
				WHERE code_original IS NULL
				GROUP BY 1,2,3,4;
									
					
				-- Site
				INSERT INTO eco.t_sites(code, code_original,texte, texte_court)
				SELECT FCY_0, FCY_0, FCYNAM_0, FCYNAM_0
						FROM prod_sagex3.FACILITY
						WHERE  FCY_0 IN (SELECT POHFCY_0 FROM prod_sagex3.PORDER) AND
							FCY_0 NOT IN (SELECT code_original FROM eco.t_sites WHERE code_original IS NOT NULL)
						ORDER BY FCY_0;
				
				INSERT INTO eco.t_sites(code, code_original,texte, texte_court)
				SELECT FCY_0, FCY_0, FCYNAM_0, FCYNAM_0
						FROM prod_sagex3.FACILITY
						WHERE  FCY_0 IN (SELECT STOFCY_0 FROM prod_sagex3.STOJOU) AND
							FCY_0 NOT IN (SELECT code_original FROM eco.t_sites WHERE code_original IS NOT NULL)
						ORDER BY FCY_0;				
				
				
				-- Types mouvements
				INSERT INTO eco.t_types_mouvements(code, texte, texte_court, code_original)
				SELECT LANNUM_0, LANMES_0, LANMES_0, LANNUM_0
				FROM prod_sagex3.APLSTD
					LEFT JOIN eco.t_types_mouvements ON code_original = LANNUM_0
				WHERE LANCHP_0 = 704 AND LAN_0 = 'FRA' AND t_types_mouvements.oid IS NULL
				GROUP BY 1,2,3,4;
			

			]]></sqlcmd>
		</NODE>

		<NODE label="Table optionelle PRECEIPTD">
			<condition><![CDATA[
				
				SELECT count(*) > 0 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'preceiptd'
            ;
			]]>			</condition>
			<sqlcmd><![CDATA[
				INSERT INTO eco.t_unites_fonctionnelles(code_original, code, texte, texte_court)
				SELECT BPRNUM_0, BPRNUM_0, BPRNAM_0, BPRNAM_0
				FROM prod_sagex3.BPARTNER
				WHERE BPSFLG_0 <> 2 AND
					BPRNUM_0 IN (
					SELECT X_SERVICE_0 
					FROM prod_sagex3.PRECEIPTD
					GROUP BY 1
					)
					AND BPRNUM_0 NOT IN (SELECT code_original FROM eco.t_unites_fonctionnelles)
				;
			]]></sqlcmd>
		</NODE>

	</NODE>
	<NODE name="PROD" label="RECUPERATION DES DONNEES DE PRODUCTION">

		<NODE label="Commandes">
			<sqlcmd><![CDATA[
            
                -- Cas de commandes en mode abonnement (même ligne commandée plusieurs fois)
                
                DROP TABLE IF EXISTS w_PORDER;
                CREATE TEMP TABLE w_PORDER AS
                SELECT *
                FROM prod_sagex3.PORDER
                ;


                DROP TABLE IF EXISTS w_PORDERP;
                CREATE TEMP TABLE w_PORDERP AS
                SELECT PORDERP.*, POHNUM_0 AS POHNUM_0_orig, COALESCE(VATRAT_0,0) AS VATRAT_0
                FROM prod_sagex3.PORDERP
                LEFT JOIN prod_sagex3.TABVAT ON PORDERP.VAT_0 = TABVAT.VAT_0
                ;

                DROP TABLE IF EXISTS w_PORDERP_multi;
                CREATE TEMP TABLE w_PORDERP_multi AS
                SELECT POHNUM_0
                FROM
                (
                SELECT POHNUM_0, POPLIN_0
                FROM w_PORDERP
                GROUP BY 1,2
                HAVING count(*) > 1
                ) subview
                GROUP BY 1
                ;

                UPDATE w_PORDERP
                SET POHNUM_0 = w_PORDERP.POHNUM_0 || '-' || to_char(STRDAT_0,'YYYYMMDD')
                FROM w_PORDERP_multi
                WHERE w_PORDERP.POHNUM_0 = w_PORDERP_multi.POHNUM_0
                ;

                DROP TABLE IF EXISTS w_PORDERP_eclat;
                CREATE TEMP TABLE w_PORDERP_eclat AS
                SELECT POHNUM_0_orig, w_PORDERP.POHNUM_0, MIN(STRDAT_0) AS STRDAT_0, MAX(POPDAT_0) AS POPDAT_0
                FROM w_PORDERP
                JOIN w_PORDERP_multi ON w_PORDERP_multi.POHNUM_0 = w_PORDERP.POHNUM_0_orig
                GROUP BY 1,2
                ;
                
                DROP TABLE IF EXISTS w_PORDER_new;
                CREATE TEMP TABLE w_PORDER_new AS	
                SELECT w_PORDER.*,
                    w_PORDERP_eclat.POHNUM_0 AS POHNUM_0_new,
                    w_PORDERP_eclat.STRDAT_0 AS STRDAT_0_new,
                    w_PORDERP_eclat.POPDAT_0 AS POPDAT_0_new
                FROM w_PORDER
                JOIN w_PORDERP_eclat ON w_PORDERP_eclat.POHNUM_0_orig = w_PORDER.POHNUM_0
                ;

                UPDATE w_PORDER_new SET
                    POHNUM_0 = POHNUM_0_new,
                    STRDAT_0 = STRDAT_0_new,
                    ORDDAT_0 = STRDAT_0_new
                ;

                ALTER TABLE w_PORDER_new DROP COLUMN POHNUM_0_new
                ;
                ALTER TABLE w_PORDER_new DROP COLUMN STRDAT_0_new
                ;
                ALTER TABLE w_PORDER_new DROP COLUMN POPDAT_0_new
                ;

                INSERT INTO w_PORDER SELECT * FROM w_PORDER_new
                ;


                DELETE FROM w_PORDER
                USING w_PORDERP_eclat 
                WHERE w_PORDERP_eclat.POHNUM_0_orig = w_PORDER.POHNUM_0
                ;
				
				-- Date livraison souhaitée mal saisie
				UPDATE w_PORDER
				SET X_LIVSOUH_0 = X_LIVSOUH_0 - (date_part('year',X_LIVSOUH_0)::text || ' year')::interval + (date_part('year',ORDDAT_0)::text || ' year')::interval
				WHERE date(X_LIVSOUH_0) - date(ORDDAT_0) > 300
				;

				UPDATE w_PORDER
				SET X_DATDISP_0 = X_DATDISP_0 - (date_part('year',X_DATDISP_0)::text || ' year')::interval + (date_part('year',ORDDAT_0)::text || ' year')::interval
				WHERE date(X_DATDISP_0) - date(ORDDAT_0) > 300
				;
							
                -- Livraisons
                DROP TABLE IF EXISTS w_PORDERQ_LIN;
                CREATE TEMP TABLE w_PORDERQ_LIN AS
                SELECT POHNUM_0, POPLIN_0, 
                    SUM(QTYUOM_0) AS QTYUOM_0,
                    SUM(QTYPUU_0) AS QTYPUU_0,
                    SUM(LINAMT_0) AS LINAMT_0,
                    SUM(LINATIAMT_0) AS LINATIAMT_0,
                    SUM(RCPQTYPUU_0) AS RCPQTYPUU_0,
                    MAX(LINCLEFLG_0) AS LINCLEFLG_0,
                    MAX(RCPCLEFLG_0) AS RCPCLEFLG_0,
                    MAX(ORDDAT_0) AS ORDDAT_0
                FROM prod_sagex3.PORDERQ
                
                GROUP BY 1,2
                ;
				
				ANALYSE w_PORDER
                ;

                ANALYSE w_PORDERQ_LIN
                ;
                


				
				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 
					POHNUM_0 AS code_original,
					POHNUM_0 AS numero,
					ORDDAT_0 AS date_commande,
					date(greatest(ORDDAT_0, X_LIVSOUH_0, X_DATDISP_0)) AS date_engagement,
					''::text AS objet,
					''::text AS reference,
					EXTRCPDAT1_0 AS date_livraison_prevue,
					CASE 
						WHEN RCPFLG_0 = 5 THEN 'T'
						WHEN RCPFLG_0 = 3 THEN 'T'
						WHEN RCPFLG_0 = 1 THEN 'N'
						WHEN RCPFLG_0 = 2 THEN 'P'
					ELSE 'P' END AS etat_reception,
					'20991231'::date AS date_reception,
					CASE 
						WHEN CLEFLG_0 = 2 THEN 'T'
						WHEN CLEFLG_0 = 1 THEN 'N'
						ELSE 'N' END AS etat_liquidation,
					COALESCE(t_fournisseurs.oid, 0) AS fournisseur_id,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					0::bigint AS lieu_commande_id,
					COALESCE(t_lieux_facturation.oid,0) AS lieu_facturation_id,
					COALESCE(t_lieux_facturation.oid,0) AS lieu_livraison_id,
					0::bigint AS unite_fonctionnelle_id,
					COALESCE(t_sites.oid,0) AS site_id,
					TOTORD_0 AS montant_commande_ht,
					0::numeric AS montant_commande_remise,
					TTVORD_0 - TOTORD_0 AS montant_commande_tva,
					0::numeric AS montant_commande_port,
					TTVORD_0 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 w_PORDER PORDER 
					LEFT JOIN eco.t_fournisseurs ON t_fournisseurs.code_original = BPSNUM_0
					LEFT JOIN eco.t_lieux t_lieux_commande ON t_lieux_commande.code_original = POHFCY_0
					LEFT JOIN eco.t_lieux t_lieux_livraison ON t_lieux_livraison.code_original = RCPFCY_0
					LEFT JOIN eco.t_lieux t_lieux_facturation ON t_lieux_facturation.code_original = INVFCY_0
					LEFT JOIN eco.t_gestionnaires ON t_gestionnaires.code = BUY_0
					LEFT JOIN eco.t_sites ON t_sites.code_original = POHFCY_0
				WHERE ORDDAT_0 >= '[ENV_ECO_ANNEEDEBUT]-01-01'
				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');
				
				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_ttc,
					etat_livraison,

					montant_liquidation_ht,
					montant_liquidation_remise,
					montant_liquidation_tva,
					montant_liquidation_port,
					montant_liquidation_ttc,
					etat_liquidation,
                    taux_tva,
                    taux_prorata_tva)
				SELECT
					p_commandes.code_original || '-' || PORDERP.POPLIN_0 AS code_original,
					p_commandes.oid AS commande_id,
					PORDERP.POPLIN_0 AS ligne_commande,
					ITMDES_0 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 par jointure avec GACCENTRYD ou A
					COALESCE(t_ucd.oid, t_articles.ucd_id, 0) AS ucd_id,
					COALESCE(t_lpp.oid, t_articles.lpp_id, 0) AS lpp_id,
					
					QTYUOM_0 AS quantite_approvisionnement,
					NETPRI_0 AS prix_unitaire_approvisionnement,
					0::numeric AS multiplicateur_stockage,
					0::numeric AS quantite_stockage,
					0::numeric AS prix_unitaire_stockage,

					LINAMT_0 AS montant_commande_ht,
					LINATIAMT_0 - LINAMT_0 AS montant_commande_tva,
					0::numeric AS montant_commande_port,
					LINATIAMT_0 AS montant_commande_ttc,

					RCPQTYPUU_0 AS quantite_livraison_approvisionnement,
					RCPQTYPUU_0 AS quantite_livraison_stockage,
					RCPQTYPUU_0*NETPRI_0 AS montant_livraison_ht,
					RCPQTYPUU_0*NETPRI_0*base.cti_division(LINATIAMT_0::numeric,LINAMT_0::numeric) AS montant_livraison_ttc,
					CASE WHEN QTYPUU_0 = RCPQTYPUU_0 THEN  'T' 
						WHEN RCPQTYPUU_0 > QTYPUU_0 THEN 'P'
						WHEN RCPQTYPUU_0 != 0 THEN 'P'
						ELSE 'N' END AS etat_livraison,
					AMTNOTLIN_0 AS montant_liquidation_ht,
					PINVOICED.DISCRGAMT1_0::numeric AS montant_liquidation_remise,
					AMTTAXLIN_0 AS montant_liquidation_tva,
					0::numeric AS montant_liquidation_port,
					AMTATILIN_0 AS montant_liquidation_ttc,
					CASE WHEN LINCLEFLG_0 = 2 THEN 'T' ELSE 'N' END,
					CASE WHEN VATRAT_0 = 20.6 AND ORDDAT_0 < '[ENV_ECO_ANNEEDEBUT]0101' THEN 19.6 WHEN VATRAT_0 = 20.6 THEN 20 ELSE VATRAT_0 END AS taux_tva,
                    0 -- todo
				FROM w_PORDERP PORDERP
					LEFT JOIN w_PORDERQ_LIN PORDERQ ON PORDERQ.POHNUM_0 = PORDERP.POHNUM_0 AND PORDERQ.POPLIN_0 = PORDERP.POPLIN_0
					LEFT JOIN (
						SELECT 
							POHNUM_0, 
							POPLIN_0, 
							SUM(QTYGLU_0) as QTYGLU_0, 
							SUM(AMTNOTLIN_0) AS AMTNOTLIN_0, 
							SUM(AMTATILIN_0) AS AMTATILIN_0, 
							SUM(AMTTAXLIN1_0) AS AMTTAXLIN_0,
							SUM(DISCRGAMT1_0) AS DISCRGAMT1_0
						FROM prod_sagex3.PINVOICED
						GROUP BY 1,2) PINVOICED
							ON PINVOICED.POHNUM_0 = PORDERP.POHNUM_0 AND PINVOICED.POPLIN_0 = PORDERP.POPLIN_0
				
					
					JOIN eco.p_commandes ON PORDERQ.POHNUM_0 = p_commandes.code_original
					LEFT JOIN eco.t_articles ON PORDERP.ITMREF_0 = 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
                    LEFT JOIN eco.t_prorata_tva ON p_commandes.date_engagement BETWEEN t_prorata_tva.date_debut AND t_prorata_tva.date_fin
					;
					
					
				-- Recalcul si remise
				UPDATE eco.p_lignes_commandes SET
					montant_commande_ht = montant_commande_ht + montant_commande_remise,
					montant_commande_tva = round((montant_commande_ht + montant_commande_remise) * montant_commande_tva / montant_commande_ht,2),
					montant_commande_ttc = round((montant_commande_ht + montant_commande_remise) * montant_commande_ttc / montant_commande_ht,2)
				WHERE montant_commande_remise <> 0 AND montant_commande_ht <> 0
				;

				UPDATE eco.p_lignes_commandes SET
					montant_livraison_ht = montant_livraison_ht + montant_commande_remise,
					montant_livraison_tva = round((montant_livraison_ht + montant_commande_remise) * montant_livraison_tva / montant_livraison_ht,2),
					montant_livraison_ttc = round((montant_livraison_ht + montant_commande_remise) * montant_livraison_ttc / montant_livraison_ht,2)
				WHERE montant_commande_remise <> 0 AND etat_livraison = 'T' AND montant_livraison_ht <> 0
				;
				
				UPDATE eco.p_lignes_commandes SET
					montant_liquidation_ht = montant_liquidation_ht + montant_liquidation_remise,
					montant_liquidation_tva = round((montant_liquidation_ht + montant_liquidation_remise) * montant_liquidation_tva / montant_liquidation_ht,2),
					montant_liquidation_ttc = round((montant_liquidation_ht + montant_liquidation_remise) * montant_liquidation_ttc / montant_liquidation_ht,2)
				WHERE montant_liquidation_remise <> 0 AND montant_liquidation_ht <> 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');
				
				DROP TABLE IF EXISTS w_PORDERQ_CMD;
                CREATE TEMP TABLE w_PORDERQ_CMD AS
                SELECT POHNUM_0,
					MAX(LASRCPDAT_0) AS LASRCPDAT_0
                FROM prod_sagex3.PORDERQ
                GROUP BY 1
                ;
				
				UPDATE eco.p_commandes
                SET date_reception = LASRCPDAT_0
                FROM w_PORDERQ_CMD
                WHERE code_original = POHNUM_0 AND
					date(LASRCPDAT_0) >= '19700101'
				;

			]]>			
</sqlcmd>
		</NODE>

		<NODE label="UF Commandes par table PRECEIPTD">
			<condition><![CDATA[
				
				SELECT count(*) > 0 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'preceiptd'
            ;
				
			]]></condition>
			<sqlcmd><![CDATA[
					
				-- services
				UPDATE eco.p_commandes 
				SET
					unite_fonctionnelle_id = t_unites_fonctionnelles.oid
				FROM
					prod_sagex3.PRECEIPTD
					 JOIN eco.t_unites_fonctionnelles ON X_SERVICE_0 = t_unites_fonctionnelles.code_original
				WHERE
					PRECEIPTD.POHNUM_0 = p_commandes.code_original 
				;

				UPDATE eco.p_lignes_commandes 
				SET
					unite_fonctionnelle_id = p_commandes.unite_fonctionnelle_id
				FROM
					eco.p_commandes
				WHERE
					p_commandes.oid = commande_id
				;
				
			]]></sqlcmd>
		</NODE>

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

												
				-- Table articles avec autres caractéristiques
				INSERT INTO eco.t_divers (code, texte, valeur, description)
				SELECT
					'X3_MVTREG',
					'Importer les mouvements de régulation',
					'1',
					'0=Non 1=Oui'
				WHERE 'X3_MVTREG' NOT IN (SELECT code FROM eco.t_divers)
                ;
			
                
                DROP TABLE IF EXISTS w_STOJOU;
				CREATE TEMP TABLE w_STOJOU AS
				SELECT 
                    LOC_0 AS LOC_0_add,
					BPSFLG_0,
                    STOJOU.*
				FROM 
					prod_sagex3.STOJOU
					LEFT JOIN prod_sagex3.BPARTNER ON BPARTNER.BPRNUM_0 = STOJOU.BPRNUM_0
				WHERE 1=1 AND 
					CASE WHEN (SELECT valeur FROM eco.t_divers WHERE code = 'SAGEX3_REG_MVT' AND valeur = '1') > 0 THEN VCRNUMREG_0 ELSE '' END = ''
				ORDER BY IPTDAT_0
				;
			
				-- prise en compte des inventaires
				UPDATE w_STOJOU SET LOC_0_add = sub.LOC_0 FROM (select CUNSSSNUM_0,ITMREF_0,LOC_0  as LOC_0 from prod_sagex3.CUNLISDET) sub WHERE sub.ITMREF_0 = w_STOJOU.ITMREF_0 AND CUNSSSNUM_0 = VCRNUMORI_0;
				--prise en compte des lieux de stocks possibles (update si 1 seul) -> todo a faire avec stoloc, plus simple
				UPDATE w_STOJOU SET LOC_0_add = sub.LOC_0 FROM (select ITMREF_0,STOFCY_0,MIN(LOC_0) AS LOC_0 from prod_sagex3.stojou where loc_0 != '' group by 1,2  having count(distinct loc_0) = 1) sub WHERE sub.ITMREF_0 = w_STOJOU.ITMREF_0 AND sub.STOFCY_0 = w_STOJOU.STOFCY_0;
				-- constitution du code avec arborescence
				--UPDATE w_STOJOU SET LOC_0_add = STOFCY_0 || '-' || LOC_0_add WHERE LOC_0_add != '';
				UPDATE w_STOJOU SET LOC_0_add = STOFCY_0 WHERE LOC_0_add = '';
			
				DROP TABLE IF EXISTS w_mvt;
				CREATE TEMP TABLE w_mvt AS
				SELECT 
					'STOJOU'::text||md5(w_STOJOU.STOFCY_0||'-'||w_STOJOU.VCRNUM_0||'-'||w_STOJOU.VCRLIN_0::text||'-'||w_STOJOU.ITMREF_0||'-'||w_STOJOU.MVTSEQ_0::text||'-'||w_STOJOU.MVTIND_0::text||'-'||w_STOJOU.CSTCOU_0::text||'-'||to_char(w_STOJOU.IPTDAT_0,'YYYYMMDD')||'-'||to_char(w_STOJOU.CREDAT_0,'YYYYMMDD')||'-'||w_STOJOU.CRETIM_0) AS mvt_code_original,
					null as oid,
					CRETIM_0 AS time,
					w_STOJOU.IPTDAT_0 AS date, --autre possible IPTDAT_0 mais imputation
					CASE WHEN w_STOJOU.QTYSTU_0 >= 0 THEN 'E' ELSE 'S' END AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					t_types_mouvements.texte || ' (' || VCRNUM_0 || '-' || VCRLIN_0 || ')' 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_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,
					VCRLINORI_0 AS ligne_commande,
					COALESCE(t_sites.oid,0) AS site_id,
					COALESCE(t_articles.lpp_id,0) AS lpp_id,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					w_STOJOU.PRIORD_0 AS prix_unitaire,
					CASE WHEN w_STOJOU.QTYSTU_0 >= 0 THEN w_STOJOU.QTYSTU_0 ELSE 0 END AS entree_quantite,
					CASE WHEN w_STOJOU.QTYSTU_0 < 0  THEN 0-w_STOJOU.QTYSTU_0 ELSE 0 END AS sortie_quantite,
					CASE WHEN w_STOJOU.QTYSTU_0 >= 0 THEN CASE WHEN AMTVAL_0 != 0 THEN AMTVAL_0 ELSE w_STOJOU.QTYSTU_0*w_STOJOU.PRIORD_0 END ELSE 0 END AS entree_montant,
					CASE WHEN w_STOJOU.QTYSTU_0 < 0 THEN CASE WHEN AMTVAL_0 != 0 THEN AMTVAL_0 ELSE -w_STOJOU.QTYSTU_0*w_STOJOU.PRIORD_0 END ELSE 0 END AS sortie_montant,
					0::numeric AS entree_montant_ht,
					0::numeric AS sortie_montant_ht,
					CUNLISDET.QTYSTU_0 - w_STOJOU.QTYPCU_0 AS stock_quantite_debut,
					CUNLISDET.QTYSTU_0 AS stock_quantite_fin,
					CASE 
						WHEN split_part(w_STOJOU.PJT_0,' ',2) LIKE '%/%' AND split_part(w_STOJOU.PJT_0,' ',3) <> '' AND split_part(w_STOJOU.PJT_0,' ',4) = '' THEN split_part(w_STOJOU.PJT_0,' ',1)
						WHEN split_part(w_STOJOU.PJT_0,' ',4) LIKE '%/%' AND split_part(w_STOJOU.PJT_0,' ',3) <> '' AND split_part(w_STOJOU.PJT_0,' ',5) = '' THEN split_part(w_STOJOU.PJT_0,' ',2)
						WHEN split_part(w_STOJOU.PJT_0,' ',5) LIKE '%/%' AND split_part(w_STOJOU.PJT_0,' ',3) <> '' AND split_part(w_STOJOU.PJT_0,' ',6) = '' THEN split_part(w_STOJOU.PJT_0,' ',2)
					ELSE '' END AS no_sejour,
					''::text AS no_patient
				FROM w_STOJOU
					LEFT JOIN eco.t_types_mouvements ON TRSTYP_0 = t_types_mouvements.code_original
					LEFT JOIN eco.t_gestionnaires ON CREUSR_0 = t_gestionnaires.code_original
					LEFT JOIN eco.t_lieux ON LOC_0_add = t_lieux.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON BPRNUM_0 = t_unites_fonctionnelles.code_original AND BPSFLG_0 = 1
					LEFT JOIN eco.t_articles ON ITMREF_0 = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN prod_sagex3.XMVTSART ON X_ITMREF_0 = ITMREF_0 AND X_STOFCY_0 = STOFCY_0 AND date_part('year',IPTDAT_0) = X_YEA_0 AND date_part('month',IPTDAT_0) = X_MON_0
					LEFT JOIN eco.t_compte ON  X_CPTACHAT_0 = t_compte.code_original
					LEFT JOIN eco.t_sites ON  STOFCY_0 = t_sites.code_original
					LEFT JOIN eco.t_fournisseurs ON (BPRNUM_0 = t_fournisseurs.code_original AND BPSFLG_0 = 2)
					LEFT JOIN eco.p_commandes ON VCRNUMORI_0 = p_commandes.code_original
					LEFT JOIN prod_sagex3.CUNLISDET ON CUNLISNUM_0 = VCRNUM_0 AND ITMLISNUM_0 = VCRLIN_0
				WHERE w_STOJOU.IPTDAT_0 >= date('[ENV_ECO_ANNEEDEBUT]-01-01')
					AND w_STOJOU.QTYSTU_0 != 0
				ORDER BY w_STOJOU.IPTDAT_0;

			
				UPDATE w_mvt SET 
					entree_montant_ht = entree_montant * montant_livraison_ht / montant_livraison_ttc 
				FROM eco.p_lignes_commandes
				WHERE 1=1 AND
					p_lignes_commandes.commande_id = w_mvt.commande_id AND
					p_lignes_commandes.ligne_commande = w_mvt.ligne_commande AND
					entree_quantite > 0 AND
					montant_livraison_ttc > 0
				;
	
				
				DROP TABLE IF EXISTS w_TAX;
				CREATE TEMP TABLE w_TAX AS
				SELECT 
					VACITM_0 AS tax_code,
					 100 + VATRAT_0 as tax_rate_inv
				FROM prod_sagex3.TABVAC
					JOIN prod_sagex3.TABVAT ON TABVAC.VACITM_0 = TABVAC.VACITM_0 AND TABVAC.VAT_0 = TABVAT.VAT_0  AND VACBPR_0 = 'FRA'
				;
				
				-- mise à jour montants ht sorties si facture commande
				UPDATE w_mvt SET
					sortie_montant = sortie_quantite * prix_unitaire
				WHERE sortie_quantite != 0 AND prix_unitaire != 0 AND sortie_montant_ht = 0;
				;
				
				-- mise à jour montants ht entrées si pas de commande (à partir des articles)
				UPDATE w_mvt SET
					entree_montant_ht = entree_montant * 100 / tax_rate_inv
				FROM eco.t_articles
					JOIN prod_sagex3.ITMMASTER ON ITMREF_0 = code
					JOIN w_TAX ON tax_code = VACITM_0
				WHERE article_id = t_articles.oid AND
					entree_quantite != 0 AND
					entree_montant_ht = 0
				;
				
				-- mise à jour montants ht sortie (à partir des articles)
				UPDATE w_mvt SET
					sortie_montant_ht = sortie_montant * 100 / tax_rate_inv
				FROM eco.t_articles
					JOIN prod_sagex3.ITMMASTER ON ITMREF_0 = code
					JOIN w_TAX ON tax_code = VACITM_0
				WHERE article_id = t_articles.oid AND
					sortie_quantite != 0
				;

				UPDATE w_mvt 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
				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="Livraisons par table PRECEIPTD">
			<condition><![CDATA[
				
				SELECT count(*) > 0 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'preceiptd'
            ;
				
			]]>			</condition>
			<sqlcmd><![CDATA[
				-- Ajout des lignes fictives produits non stockés
				DROP TABLE IF EXISTS w_articles_mvt;
				CREATE TABLE w_articles_mvt AS
				SELECT article_id
				FROM w_mvt
				GROUP BY 1
				;
				
				INSERT INTO w_mvt(
					mvt_code_original,
					oid,
					time,
					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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient)
				SELECT
					'PRECEIPTD'::text||PRECEIPTD.PTHNUM_0||'-'||PRECEIPTD.PTDLIN_0::text AS mvt_code_original,
					null as oid,
					CRETIM_0 AS time,
					PRECEIPTD.RCPDAT_0 AS date,
					'E'::text AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					CASE WHEN ITMDES_0 <> '' OR LINTEX_0 <> '' THEN trim(ITMDES_0 || ' ' || LINTEX_0) ELSE t_types_mouvements.texte END || ' (' || PRECEIPTD.PTHNUM_0 || ')' AS texte,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					0::bigint AS lieu_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid,0) AS article_id,
					COALESCE(t_articles.compte_id,0) AS compte_id,
					COALESCE(t_fournisseurs.oid,0) AS fournisseur_id,
					COALESCE(p_commandes.oid,0) AS commande_id,
					PRECEIPTD.POPLIN_0 AS ligne_commande,
					t_sites.oid AS site_id,
					COALESCE(t_articles.lpp_id,0) AS lppid,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					NETPRI_0 AS prix_unitaire,
					PRECEIPTD.QTYSTU_0 AS entree_quantite,
					LINATIAMT_0 AS entree_montant,
					LINAMT_0 AS entree_montaht_ht,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					0 AS sortie_montant_ht,
					0 AS stock_quantite_debut,
					0 AS stock_quantite_fin,
					CASE 
						WHEN split_part(PRECEIPTD.PJT_0,' ',2) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',4) = '' THEN split_part(PRECEIPTD.PJT_0,' ',1)
						WHEN split_part(PRECEIPTD.PJT_0,' ',4) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',5) = '' THEN split_part(PRECEIPTD.PJT_0,' ',2)
						WHEN split_part(PRECEIPTD.PJT_0,' ',5) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',6) = '' THEN split_part(PRECEIPTD.PJT_0,' ',2)
					ELSE '' END AS no_sejour,
					''::text AS no_patient
				FROM prod_sagex3.PRECEIPTD
					JOIN prod_sagex3.ITMMASTER ON PRECEIPTD.ITMREF_0 = ITMMASTER.ITMREF_0
					LEFT JOIN eco.p_commandes ON PRECEIPTD.POHNUM_0 = p_commandes.code_original 
					LEFT JOIN eco.t_sites ON PRECEIPTD.POHFCY_0 = t_sites.code_original 
					LEFT JOIN eco.t_articles ON PRECEIPTD.ITMREF_0 = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN eco.t_gestionnaires ON PRECEIPTD.CREUSR_0 = t_gestionnaires.code_original 
					LEFT JOIN eco.t_fournisseurs ON PRECEIPTD.BPSNUM_0 = t_fournisseurs.code_original 
					LEFT JOIN eco.t_types_mouvements ON '*NS' = t_types_mouvements.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON X_SERVICE_0 = t_unites_fonctionnelles.code_original
					LEFT JOIN prod_sagex3.STOJOU ON STOJOU.ITMREF_0 =  PRECEIPTD.ITMREF_0 AND STOJOU.VCRNUM_0 = PRECEIPTD.PTHNUM_0
				WHERE PRECEIPTD.RCPDAT_0 >= date('[ENV_ECO_ANNEEDEBUT]-01-01')
					AND STOJOU.ITMREF_0 IS NULL AND
					t_articles.oid <> ALL(SELECT article_id FROM w_articles_mvt)
				;


				INSERT INTO w_mvt(
					mvt_code_original,
					oid,
					time,
					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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient)
				SELECT
					'PRECEIPTD'::text||PRECEIPTD.PTHNUM_0||'-'||PRECEIPTD.PTDLIN_0::text AS mvt_code_original,
					null as oid, CRETIM_0 AS time,
					PRECEIPTD.RCPDAT_0 AS date,
					'S'::text AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					CASE WHEN ITMDES_0 <> '' OR LINTEX_0 <> '' THEN trim(ITMDES_0 || ' ' || LINTEX_0) ELSE t_types_mouvements.texte END || ' (' || PRECEIPTD.PTHNUM_0 || ')' AS texte,
					COALESCE(t_gestionnaires.oid,0) AS gestionnaire_id,
					0::bigint AS lieu_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid,0) AS article_id,
					COALESCE(t_articles.compte_id,0) AS compte_id,
					COALESCE(t_fournisseurs.oid,0) AS fournisseur_id,
					COALESCE(p_commandes.oid,0) AS commande_id,
					PRECEIPTD.POPLIN_0 AS ligne_commande,
					t_sites.oid AS site_id,
					COALESCE(t_articles.lpp_id,0) AS lppid,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					NETPRI_0 AS prix_unitaire,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS entree_montaht_ht,
					PRECEIPTD.QTYSTU_0 AS sortie_quantite,
					LINATIAMT_0 AS sortie_montant,
					LINAMT_0 AS sortie_montant_ht,
					0 AS stock_quantite_debut,
					0 AS stock_quantite_fin,
					CASE 
						WHEN split_part(PRECEIPTD.PJT_0,' ',2) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',4) = '' THEN split_part(PRECEIPTD.PJT_0,' ',1)
						WHEN split_part(PRECEIPTD.PJT_0,' ',4) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',5) = '' THEN split_part(PRECEIPTD.PJT_0,' ',2)
						WHEN split_part(PRECEIPTD.PJT_0,' ',5) LIKE '%/%' AND split_part(PRECEIPTD.PJT_0,' ',3) <> '' AND split_part(PRECEIPTD.PJT_0,' ',6) = '' THEN split_part(PRECEIPTD.PJT_0,' ',2)
					ELSE '' END AS no_sejour,
					''::text AS no_patient
				FROM prod_sagex3.PRECEIPTD
					JOIN prod_sagex3.ITMMASTER ON PRECEIPTD.ITMREF_0 = ITMMASTER.ITMREF_0
					LEFT JOIN eco.p_commandes ON PRECEIPTD.POHNUM_0 = p_commandes.code_original 
					LEFT JOIN eco.t_sites ON PRECEIPTD.POHFCY_0 = t_sites.code_original 
					LEFT JOIN eco.t_articles ON PRECEIPTD.ITMREF_0 = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN eco.t_gestionnaires ON PRECEIPTD.CREUSR_0 = t_gestionnaires.code_original 
					LEFT JOIN eco.t_fournisseurs ON PRECEIPTD.BPSNUM_0 = t_fournisseurs.code_original 
					LEFT JOIN eco.t_types_mouvements ON '*NS' = t_types_mouvements.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON X_SERVICE_0 = t_unites_fonctionnelles.code_original
					LEFT JOIN prod_sagex3.STOJOU ON STOJOU.ITMREF_0 =  PRECEIPTD.ITMREF_0 AND STOJOU.VCRNUM_0 = PRECEIPTD.PTHNUM_0
				WHERE PRECEIPTD.RCPDAT_0 >= date('[ENV_ECO_ANNEEDEBUT]-01-01')
					AND STOJOU.ITMREF_0 IS NULL AND
					t_articles.oid <> ALL(SELECT article_id FROM w_articles_mvt)
			;
			UPDATE eco.p_commandes 
			SET	date_reception = date
			FROM (
				SELECT 
					commande_id,
					MAX(date) as date
				FROM 
					w_mvt
					GROUP BY 1
				) sub
			WHERE oid = commande_id
			;
				
			UPDATE w_mvt
			SET sortie_montant_ht = sortie_montant / ((100 + VATRAT_0)/100)
			FROM (
				SELECT '(' || PTHNUM_0 || '-' || PTDLIN_0 || ')' AS ref, VATRAT_0 
				FROM prod_sagex3.PRECEIPTD 
					JOIN prod_sagex3.TABVAT ON TABVAT.VAT_0 = PRECEIPTD.VAT_0
				) sub
			WHERE substring(texte from '\([^\)]*\)$') =  ref
			;
			]]></sqlcmd>
		</NODE>
		<NODE label="Livraison par rapport à PORDERQ">
			<condition><![CDATA[
				
				SELECT count(*) = 0 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'preceiptd'
            ;
				
			]]>			</condition>
			<sqlcmd><![CDATA[
					
				-- Ajout des lignes fictives produits non stockés
				INSERT INTO w_mvt (
					mvt_code_original,
					oid,
					time,
					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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient)
				SELECT
					'PORDERP'::text||PORDERP.POHNUM_0||'-'||PORDERP.POPLIN_0::text AS mvt_code_original,
					null as oid,
					1200 AS time,
					PORDERQ.LASRCPDAT_0 AS date,
					'E'::text AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					CASE WHEN ITMDES_0 <> '' OR LINTEX_0 <> '' THEN trim(ITMDES_0 || ' ' || LINTEX_0) ELSE t_types_mouvements.texte || ' ' || t_articles.code END AS texte,
					p_commandes.gestionnaire_id,
					0::bigint AS lieu_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid,0) AS article_id,
					COALESCE(t_articles.compte_id,0) AS compte_id,
					p_commandes.fournisseur_id,
					p_commandes.oid AS commande_id,
					PORDERQ.POPLIN_0 AS ligne_commande,
					p_commandes.site_id,
					COALESCE(t_articles.lpp_id,0) AS lppid,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					NETPRI_0 AS prix_unitaire,
					RCPQTYPUU_0 AS entree_quantite,
					RCPQTYPUU_0*NETPRI_0*(base.cti_division(LINATIAMT_0::numeric, LINAMT_0::numeric)) AS entree_montant,
					RCPQTYPUU_0*NETPRI_0 AS entree_montaht_ht,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					0 AS sortie_montant_ht,
					0 AS stock_quantite_debut,
					0 AS stock_quantite_fin,
					CASE 
						WHEN split_part(PORDERP.PJT_0,' ',2) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',4) = '' THEN split_part(PORDERP.PJT_0,' ',1)
						WHEN split_part(PORDERP.PJT_0,' ',4) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',5) = '' THEN split_part(PORDERP.PJT_0,' ',2)
						WHEN split_part(PORDERP.PJT_0,' ',5) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',6) = '' THEN split_part(PORDERP.PJT_0,' ',2)
					ELSE '' END AS no_sejour,
					''::text AS no_patient
				FROM prod_sagex3.PORDERP
					JOIN prod_sagex3.PORDERQ ON PORDERQ.POHNUM_0 = PORDERP.POHNUM_0 AND PORDERQ.POPLIN_0 = PORDERP.POPLIN_0
					JOIN prod_sagex3.PORDER ON PORDER.POHNUM_0 = PORDERP.POHNUM_0 
					JOIN prod_sagex3.ITMMASTER ON PORDERP.ITMREF_0 = ITMMASTER.ITMREF_0
					JOIN eco.p_commandes ON PORDERQ.POHNUM_0 = p_commandes.code_original
					LEFT JOIN eco.t_articles ON PORDERQ.ITMREF_0 = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN eco.t_types_mouvements ON '*NS' = t_types_mouvements.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON PORDERP.X_SERVICE_0 = t_unites_fonctionnelles.code_original AND PORDERP.X_SERVICE_0 ~ '^[A-Z].*$'
				WHERE PORDERQ.LASRCPDAT_0 >= date('[ENV_ECO_ANNEEDEBUT]-01-01')
					AND	RCPQTYPUU_0 <> 0
				ORDER BY PORDERQ.LASRCPDAT_0;



				INSERT INTO w_mvt(
					mvt_code_original,
					oid,
					time,
					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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient)
				SELECT
					'PORDERP'::text||PORDERP.POHNUM_0||'-'||PORDERP.POPLIN_0::text AS mvt_code_original,
					null AS oid,
					1200 AS time,
					PORDERQ.LASRCPDAT_0 AS date,
					'S'::text AS sens_mouvement,
					COALESCE(t_types_mouvements.oid,0) AS type_mouvement_id,
					CASE WHEN ITMDES_0 <> '' OR LINTEX_0 <> '' THEN trim(ITMDES_0 || ' ' || LINTEX_0) ELSE t_types_mouvements.texte || ' ' || t_articles.code END AS texte,
					p_commandes.gestionnaire_id,
					0::bigint AS lieu_id,
					COALESCE(t_unites_fonctionnelles.oid,0) AS unite_fonctionnelle_id,
					COALESCE(t_articles.oid,0) AS article_id,
					COALESCE(t_articles.compte_id,0) AS compte_id,
					p_commandes.fournisseur_id,
					p_commandes.oid AS commande_id,
					PORDERQ.POPLIN_0 AS ligne_commande,
					p_commandes.site_id,
					COALESCE(t_articles.lpp_id,0) AS lppid,
					COALESCE(t_articles.ucd_id,0) AS ucd_id,
					NETPRI_0 AS prix_unitaire,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS entree_montant_ht,
					RCPQTYPUU_0 AS sortie_quantite,
					RCPQTYPUU_0*NETPRI_0*(base.cti_division(LINATIAMT_0::numeric, LINAMT_0::numeric)) AS sortie_montant,
					RCPQTYPUU_0*NETPRI_0 AS sortie_montant_ht,
					0 AS stock_quantite_debut,
					0 AS stock_quantite_fin,
					CASE 
						WHEN split_part(PORDERP.PJT_0,' ',2) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',4) = '' THEN split_part(PORDERP.PJT_0,' ',1)
						WHEN split_part(PORDERP.PJT_0,' ',4) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',5) = '' THEN split_part(PORDERP.PJT_0,' ',2)
						WHEN split_part(PORDERP.PJT_0,' ',5) LIKE '%/%' AND split_part(PORDERP.PJT_0,' ',3) <> '' AND split_part(PORDERP.PJT_0,' ',6) = '' THEN split_part(PORDERP.PJT_0,' ',2)
					ELSE '' END AS no_sejour,
					''::text AS no_patient
				FROM prod_sagex3.PORDERP
					JOIN prod_sagex3.PORDERQ ON PORDERQ.POHNUM_0 = PORDERP.POHNUM_0 AND PORDERQ.POPLIN_0 = PORDERP.POPLIN_0
					JOIN prod_sagex3.PORDER ON PORDER.POHNUM_0 = PORDERP.POHNUM_0 
					JOIN prod_sagex3.ITMMASTER ON PORDERP.ITMREF_0 = ITMMASTER.ITMREF_0
					JOIN eco.p_commandes ON PORDERQ.POHNUM_0 = p_commandes.code_original
					LEFT JOIN eco.t_articles ON PORDERQ.ITMREF_0 = t_articles.code_original AND t_articles.oid != 0
					LEFT JOIN eco.t_types_mouvements ON '*NS' = t_types_mouvements.code_original
					LEFT JOIN eco.t_unites_fonctionnelles ON PORDERP.X_SERVICE_0 = t_unites_fonctionnelles.code_original AND PORDERP.X_SERVICE_0 ~ '^[A-Z].*$'
				WHERE PORDERQ.LASRCPDAT_0 >= date('[ENV_ECO_ANNEEDEBUT]-01-01')
					AND	RCPQTYPUU_0 <> 0
				ORDER BY PORDERQ.LASRCPDAT_0;
			]]></sqlcmd>
		</NODE>
		<NODE label="Insertion des mouvements">
			<sqlcmd><![CDATA[
						
				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; 

				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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient)
				SELECT
					nextval('w_MVT_sequence'::regclass) AS sequence,
					mvt_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, 
					entree_montant, 
					entree_montant_ht,
					sortie_quantite,
					sortie_montant,
					sortie_montant_ht,
					stock_quantite_debut,
					stock_quantite_fin,
					no_sejour,
					no_patient					
				FROM (
					SELECT * FROM w_mvt
					ORDER BY date, time
				) sub
				;
				
				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');
				
				
			]]></sqlcmd>
		</NODE>
		<NODE label="Séjours par rapport SDELIVERYD">
			<condition><![CDATA[
				
				SELECT count(*) = 1 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'sdeliveryd'
            ;
				
			]]></condition>
			<sqlcmd><![CDATA[
				UPDATE eco.p_mouvements_articles 
				SET sortie_montant_ht = sortie_montant / ((100 + VATRAT_0)/100)
				FROM (
					SELECT '(' || SDHNUM_0 || '-' || SDDLIN_0 || ')' AS ref, VATRAT_0 
					FROM prod_sagex3.SDELIVERYD 
					JOIN prod_sagex3.TABVAT ON TABVAT.VAT_0 = SDELIVERYD.VAT_0
				) sub
				WHERE substring(texte from '\([^\)]*\)$') =  ref
					AND sortie_montant != 0 AND sortie_montant_ht = 0
				;
				
			]]></sqlcmd>
		</NODE>

		<NODE label="Séjours par rapport SDELIVERY">
			<condition><![CDATA[
				
				SELECT count(*) = 1 
				FROM information_schema.tables
				WHERE 1=1
					AND table_schema = 'prod_sagex3'
					AND table_name = 'sdelivery'
            ;
				
			]]></condition>
			<sqlcmd><![CDATA[
				UPDATE eco.p_mouvements_articles
				SET no_sejour = SDELIVERY.X_CODSEJ_0,
					no_patient = X_CODIPP_0
				FROM prod_sagex3.SDELIVERY 
					LEFT JOIN prod_sagex3.XPATIENT ON SDELIVERY.X_CODSEJ_0 = XPATIENT.X_CODSEJ_0
				WHERE SDHNUM_0 = regexp_replace(p_mouvements_articles.texte,'.*\(([A-Z]*\-[^\-\)]*)[^\)]*\)$',E'\\1');
				
				DROP TABLE IF EXISTS w_sejour_patient;
				CREATE TEMP TABLE w_sejour_patient AS
				SELECT no_sejour, MAX(no_patient) AS no_patient
				FROM eco.p_mouvements_articles
				WHERE no_patient <> '' AND no_sejour <> ''
				GROUP BY 1
				;

				ANALYSE w_sejour_patient
				;

				UPDATE eco.p_mouvements_articles
				SET no_patient = w_sejour_patient.no_patient
				FROM w_sejour_patient
				WHERE p_mouvements_articles.no_sejour = w_sejour_patient.no_sejour AND
					p_mouvements_articles.no_patient = '' 
				;
				
				SELECT eco.cti_reorganize_sejour();
				SELECT eco.cti_reorganize_sejour_ucd_lpp()
			]]></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');

			
				-- cumul ES d'après mouvements
				DROP TABLE IF EXISTS w_stock;
				CREATE TEMP TABLE w_stock AS
				SELECT 
					COALESCE(t_sites.code_original,'') AS site_code_original,
					t_articles.code_original AS article_code_original,
					p_mouvements_articles.article_id,
					t_articles.compte_id,
					t_articles.ucd_id,
					t_articles.lpp_id,
					p_mouvements_articles.fournisseur_id AS fournisseur_id,
					site_id,
					0 as lieu_id,
					date(date_trunc('month',date)) AS date_debut,
					date(date_trunc('month',date) + interval '1 month' - interval '1 day') AS date_fin,
					date_part('year',date)*12 + date_part('month',date) AS mois_sequence,
					SUM(entree_quantite) AS entree_quantite,
					SUM(entree_montant) AS entree_montant,
					SUM(sortie_quantite) AS sortie_quantite,
					SUM(sortie_montant) AS sortie_montant,
					0::numeric as pump,
					'0'::text AS ok_pump,
					0::numeric AS stock_quantite_debut,
					0::numeric AS stock_quantite_fin,
					0::numeric AS stock_valeur_debut,
					0::numeric AS stock_valeur_fin
				FROM eco.p_mouvements_articles
				JOIN eco.t_articles ON p_mouvements_articles.article_id = t_articles.oid
				JOIN eco.t_sites ON p_mouvements_articles.site_id = t_sites.oid
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12
				ORDER BY article_id,date_fin
				;

				--etats
				DROP TABLE IF EXISTS w_etat;
				CREATE TEMP TABLE w_etat AS 
				SELECT 
				CASE WHEN CSTCOD_0 = 4 THEN CST_0 ELSE '0.5' END as ok_pump,
				CASE WHEN REFDAT_0 = date_trunc('month',REFDAT_0) + interval '1 month' - interval '1 day' OR IPTDAT_0 IS NULL THEN STOVALWRK.QTYSTU_0 ELSE 
					STOVALWRK.QTYSTU_0 + SUM(CASE WHEN  IPTDAT_0 > REFDAT_0 THEN STOJOU.QTYSTU_0 ELSE 0 END) OVER 
						(PARTITION BY STOVALWRK.ITMREF_0, STOVALWRK.STOFCY_0, date_trunc('month',IPTDAT_0), IPTDAT_0 > REFDAT_0 ORDER BY IPTDAT_0) END as stock,
				STOVALWRK.ITMREF_0,STOVALWRK.STOFCY_0,CASE WHEN CSTCOD_0 = 4 THEN CST_0 ELSE 0 END as pump,
				date_trunc('month',REFDAT_0) AS date_ref, COALESCE(IPTDAT_0,REFDAT_0) AS date_mvt
				FROM prod_sagex3.STOVALWRK LEFT JOIN prod_sagex3.STOJOU ON
					STOVALWRK.ITMREF_0 = STOJOU.ITMREF_0 AND 
					STOVALWRK.STOFCY_0 = STOJOU.STOFCY_0 AND
					date_trunc('month',REFDAT_0) = date_trunc('month',IPTDAT_0)
				order by STOVALWRK.ITMREF_0,date_mvt;

				-- inventaires
				DROP TABLE IF EXISTS w_inv;
				CREATE TEMP TABLE w_inv AS 
				SELECT 
					CASE WHEN CUNDAT_0 > LASRCPDAT_0 THEN '1' ELSE '0.5' END AS ok_pump,
					CASE WHEN CUNDAT_0 = IPTDAT_0 OR IPTDAT_0 IS NULL THEN PHYSTO_0 ELSE  CUNSTO_0 + COALESCE(SUM(STOJOU.QTYSTU_0) OVER (PARTITION BY ITMMVT.ITMREF_0, ITMMVT.STOFCY_0, IPTDAT_0 > CUNDAT_0 ORDER BY IPTDAT_0 ),0) END as stock,
					ITMMVT.ITMREF_0,
					ITMMVT.STOFCY_0,
					X_PMPPER_0,
					date_trunc('month',CUNDAT_0) AS date_ref,
					COALESCE(IPTDAT_0, CUNDAT_0) AS date_mvt
				FROM prod_sagex3.ITMMVT JOIN prod_sagex3.STOJOU ON
					ITMMVT.ITMREF_0 = STOJOU.ITMREF_0 AND
					ITMMVT.STOFCY_0 = STOJOU.STOFCY_0 AND
					date_trunc('month',CUNDAT_0) = date_trunc('month',IPTDAT_0) AND
					CUNDAT_0 < IPTDAT_0
				order by itmmvt.itmref_0 
				;

				INSERT INTO w_stock
				SELECT 
					t_sites.code_original,
					t_articles.code_original,
					t_articles.oid,
					t_articles.compte_id,
					t_articles.ucd_id,
					t_articles.lpp_id,
					w_stock.fournisseur_id,
					t_sites.oid,
					0,
					date_ref AS date_debut,
					date_ref + interval '1 month' - interval '1 day' AS date_fin,
					date_part('year',date_ref)*12 + date_part('month',date_ref) AS mois_sequence,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					w_etat.pump,
					w_etat.ok_pump,
					0 AS stock_quantite_debut,
					(MAX(ARRAY[date_mvt::text,stock::text]))[2]::numeric AS stock_quantite_fin,
					0 AS stock_valeur_debut,
					(MAX(ARRAY[date_mvt::text,stock::text]))[2]::numeric * w_etat.pump AS stock_valeur_fin
				FROM w_etat
					JOIN eco.t_articles ON ITMREF_0 = t_articles.code_original
					JOIN eco.t_sites ON STOFCY_0 = t_sites.code_original
					LEFT JOIN w_stock ON 1=1 AND 
						ITMREF_0 = article_code_original AND
						date_ref = date_debut AND
						STOFCY_0 = t_sites.code_original
				WHERE date_debut IS NULL
				AND date_ref > '[ENV_ECO_ANNEEDEBUT]-01-01'
				GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,21
				;

				UPDATE w_stock
				SET 
					ok_pump = sub.ok_pump,
					--stock_quantite_debut = stock - entree_quantite + sortie_quantite,
					stock_quantite_fin = stock,
					stock_valeur_debut = (stock - entree_quantite + sortie_quantite) * sub.pump,
					stock_valeur_fin = stock * sub.pump,
					pump = sub.pump
				FROM  (
					SELECT ITMREF_0,
					STOFCY_0,
					date_ref,
					pump,
					ok_pump,
					(MAX(ARRAY[date_mvt::text,stock::text]))[2]::numeric as stock
					 FROM w_etat
					 GROUP BY 1,2,3,4,5) sub
				WHERE 1=1 
					AND ITMREF_0 = article_code_original
					AND STOFCY_0 = site_code_original
					AND date_ref = date_debut
					AND w_stock.ok_pump = '0'
				;
				
				UPDATE w_stock
				SET 
				stock_quantite_fin  = CASE WHEN w_stock.ok_pump = 0 THEN stock ELSE stock_quantite_fin END,
				pump = X_PMPPER_0,
				stock_valeur_fin = X_PMPPER_0 * stock,
				ok_pump = sub.ok_pump
				FROM 
				(SELECT ITMREF_0,
				STOFCY_0,
				date_ref,
				(MAX(ARRAY[date_mvt::text, stock::text]))[2]::numeric as stock,
				(MAX(ARRAY[date_mvt::text, X_PMPPER_0::text]))[2]::numeric as X_PMPPER_0,
				(MAX(ARRAY[date_mvt::text, ok_pump::text]))[2]::numeric as ok_pump
				FROM w_inv 
				GROUP BY 1,2,3) sub
				WHERE 1=1 AND
					article_code_original = ITMREF_0 AND
					site_code_original = STOFCY_0 AND
					date_debut = date_ref AND
					stock > 0
					;
					
				INSERT INTO w_stock
				SELECT 
					COALESCE(t_sites.code_original,'') AS site_code_original,
					t_articles.code_original AS article_code_original,
					t_articles.oid,
					t_articles.compte_id,
					t_articles.ucd_id,
					t_articles.lpp_id,
					w_stock.fournisseur_id,
					t_sites.oid,
					0,
					date_ref AS date_debut,
					date_ref + interval '1 month' - interval '1 day' AS date_fin,
					date_part('year',date_ref)*12 + date_part('month',date_ref) AS mois_sequence,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					CASE WHEN w_inv.ok_pump = '1' THEN X_PMPPER_0 ELSE 0 END as pump,
					w_inv.ok_pump,
					stock AS stock_quantite_debut,
					stock AS stock_quantite_fin,
					stock * X_PMPPER_0 AS stock_valeur_debut,
					stock * X_PMPPER_0 AS stock_valeur_fin
				FROM w_inv
					LEFT JOIN w_stock ON 1=1 AND
						ITMREF_0 = article_code_original AND
						STOFCY_0 = site_code_original AND
						date_ref = date_debut
					JOIN eco.t_articles ON ITMREF_0 = t_articles.code_original
					JOIN eco.t_sites ON STOFCY_0 = t_sites.code_original
						AND stock > 0
				WHERE date_debut IS NULL
					AND date_ref > '[ENV_ECO_ANNEEDEBUT]-01-01'
				ORDER BY article_id,date_fin
				;

				-- pas dans un état => stock à 0
				INSERT INTO w_stock
				SELECT 
					t_sites.code_original,
					t_articles.code_original,
					t_articles.oid,
					t_articles.compte_id,
					t_articles.ucd_id,
					t_articles.lpp_id,
					ref.fournisseur_id,
					t_sites.oid,
					0,
					date_trunc('month',periode.REFDAT_0) AS date_debut,
					date_trunc('month',periode.REFDAT_0) + interval '1 month' - interval '1 day' AS date_fin,
					date_part('year',date_trunc('month',periode.REFDAT_0))*12 + date_part('month',date_trunc('month',periode.REFDAT_0)) AS mois_sequence,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					0 AS pump,
					'0.5' AS ok_pump,
					0 AS stock_quantite_debut,
					0 AS stock_quantite_fin,
					0 AS stock_valeur_debut,
					0 AS stock_valeur_fin
				FROM 
					 (SELECT ITMREF_0, STOFCY_0 FROM prod_sagex3.STOJOU GROUP BY 1,2) w_exist
					JOIN
					 (SELECT STOFCY_0, REFDAT_0 FROM prod_sagex3.STOVALWRK GROUP BY 1,2) periode ON w_exist.STOFCY_0 = periode.STOFCY_0
					LEFT JOIN (SELECT date_ref, ITMREF_0, STOFCY_0  FROM w_etat GROUP BY 1,2,3) w_etat ON
						w_exist.ITMREF_0 = w_etat.ITMREF_0 AND
						w_exist.STOFCY_0 = w_etat.STOFCY_0 AND
						date_ref = date_trunc('month',REFDAT_0)
					LEFT JOIN w_stock ref ON 
						ref.article_code_original = w_exist.ITMREF_0 AND
						ref.site_code_original = w_exist.STOFCY_0 AND
						ref.date_debut = date_trunc('month',REFDAT_0)
					JOIN eco.t_articles ON w_exist.ITMREF_0 = t_articles.code_original
					JOIN eco.t_sites ON w_exist.STOFCY_0 = t_sites.code_original
				WHERE w_etat.date_ref IS NULL AND ref.date_debut IS NULL
				;

			drop table if exists temp.w_st;
			create table temp.w_st as select * from w_stock;
				
				-- initialisation des stock à 0 si premier mouvements détecté sur l'article et le site
				UPDATE w_stock
				SET 
					ok_pump = 0.5,
					stock_quantite_fin = entree_quantite - sortie_quantite
				FROM (SELECT ITMREF_0, STOFCY_0, min(IPTDAT_0) as min_date FROM prod_sagex3.STOJOU GROUP BY 1,2) start
				WHERE article_code_original = ITMREF_0
					AND site_code_original = STOFCY_0
					AND date(date_trunc('month',min_date)) = date_debut
					AND ok_pump = 0
				;
				
				-- maj croissante des quantités
				UPDATE w_stock
				SET ok_pump = '0.5',
					stock_quantite_fin = subview.stock_quantite_fin
				FROM
				(
				SELECT  w_stock.site_id, w_stock.lieu_id, w_stock.article_id, w_stock.mois_sequence, w_stock.date_fin,
					w_stock_ref.stock_quantite_fin + SUM(w_stock.entree_quantite - w_stock.sortie_quantite) OVER (PARTITION BY w_stock.site_id, w_stock.lieu_id, w_stock.article_id, last_ref ORDER BY w_stock.date_fin asc) AS stock_quantite_fin
				FROM w_stock JOIN 
					(SELECT 
						site_id,
						lieu_id,
						article_id,
						mois_sequence,
						stock_quantite_fin,
						COALESCE(lead(mois_sequence,1) OVER (PARTITION BY article_id, site_id, lieu_id ORDER BY mois_sequence),100000000) AS next_ref,
						COALESCE(lag(mois_sequence,1) OVER (PARTITION BY article_id, site_id, lieu_id ORDER BY mois_sequence),-100000000) AS last_ref
						FROM w_stock WHERE ok_pump != '0'
					) w_stock_ref ON  1=1
						AND w_stock.lieu_id = w_stock_ref.lieu_id
						AND w_stock.site_id = w_stock_ref.site_id
						AND w_stock.article_id = w_stock_ref.article_id
						AND w_stock.mois_sequence BETWEEN w_stock_ref.mois_sequence AND next_ref
						AND w_stock_ref.mois_sequence < w_stock.mois_sequence
						
				ORDER BY w_stock.date_fin
				) subview
				WHERE ok_pump = '0' AND
					w_stock.article_id = subview.article_id AND
					w_stock.site_id = subview.site_id AND
					w_stock.lieu_id = subview.lieu_id AND
					w_stock.mois_sequence = subview.mois_sequence
				;

				-- calcul quantités
				-- maj décroissante
				UPDATE w_stock
				SET ok_pump = '0.5',
					stock_quantite_fin = subview.stock_quantite_fin
				FROM
				(
				SELECT  w_stock.site_id, w_stock.lieu_id, w_stock.article_id, w_stock.mois_sequence, w_stock.date_fin,
					w_stock_ref.stock_quantite_fin - w_stock_ref.entree_quantite + w_stock_ref.sortie_quantite + w_stock.entree_quantite - w_stock.sortie_quantite - SUM(w_stock.entree_quantite 
					- w_stock.sortie_quantite) OVER (PARTITION BY w_stock.site_id, w_stock.lieu_id, w_stock.article_id, next_ref  ORDER BY w_stock.date_fin desc) AS stock_quantite_fin
				FROM w_stock
					JOIN (SELECT 
						site_id,
						lieu_id,
						article_id,
						mois_sequence,
						stock_quantite_fin,
						entree_quantite,
						sortie_quantite,
						COALESCE(lead(mois_sequence,1) OVER (PARTITION BY article_id, site_id, lieu_id ORDER BY mois_sequence),100000000) AS next_ref,
						COALESCE(lag(mois_sequence,1) OVER (PARTITION BY article_id, site_id, lieu_id ORDER BY mois_sequence),-100000000) AS last_ref
						FROM w_stock WHERE ok_pump != '0'
					) w_stock_ref  ON  1=1
						AND w_stock.lieu_id = w_stock_ref.lieu_id
						AND w_stock.site_id = w_stock_ref.site_id
						AND w_stock.article_id = w_stock_ref.article_id
						AND w_stock.mois_sequence BETWEEN last_ref ANd w_stock_ref.mois_sequence
						AND w_stock.mois_sequence != w_stock_ref.mois_sequence
				ORDER BY w_stock.date_fin
				) subview
				WHERE ok_pump = '0' AND
					w_stock.article_id = subview.article_id AND
					w_stock.site_id = subview.site_id AND
					w_stock.lieu_id = subview.lieu_id AND
					w_stock.mois_sequence = subview.mois_sequence
				;
				-- forcage pump avec dernières réceptions
				DROP TABLE IF EXISTS w_rec;
				CREATE TEMP TABLE w_rec AS 
				SELECT 
				'1' as ok_pump,
				ITMMVT.ITMREF_0,ITMMVT.STOFCY_0,X_PMPPER_0,
				 date_trunc('month',X_DATPMP_0) AS date_ref
				FROM prod_sagex3.ITMMVT
				;

                 -- Prix distri historisé si pas de pump
                DROP SEQUENCE IF EXISTS w_prix_distri_seq;
                CREATE TEMP SEQUENCE w_prix_distri_seq;
                
                DROP TABLE IF EXISTS w_prix_distri;
                CREATE TEMP TABLE w_prix_distri AS
                SELECT subview.*, '20991231'::date AS date_fin, nextval('w_prix_distri_seq'::regclass) AS prix_sequence
                FROM
                (
                SELECT STOFCY_0,ITMREF_0, date(date_trunc('month',IPTDAT_0)) AS date_debut,
                    (MAX(ARRAY[IPTDAT_0::text,PRIORD_0::text]))[2]::numeric AS prix_distri_ht,
                    0 AS prix_distri_ttc
                FROM prod_sagex3.STOJOU
                WHERE QTYSTU_0 < 0
					AND PRINAT_0 = 5  AND TRSTYP_0 = 4
                GROUP BY 1,2,3
                ORDER BY 1,2,3
                ) subview;

                UPDATE w_prix_distri
                SET date_fin = w_prix_distri_next.date_debut - interval '1 day'
                FROM w_prix_distri w_prix_distri_next
                WHERE w_prix_distri.ITMREF_0 = w_prix_distri_next.ITMREF_0 AND
			w_prix_distri.STOFCY_0 = w_prix_distri_next.STOFCY_0 AND
                    w_prix_distri.prix_sequence = w_prix_distri_next.prix_sequence - 1
                ;
                
                CREATE INDEX w_prix_distri_i1 ON w_prix_distri USING btree (ITMREF_0)
                ;	
                 CREATE INDEX w_prix_distri_i2 ON w_prix_distri USING btree (STOFCY_0)
                ;

				UPDATE w_stock
				SET 
				ok_pump = '1',
				pump = X_PMPPER_0,
				stock_valeur_fin = stock_quantite_fin * X_PMPPER_0,
				stock_valeur_debut = stock_quantite_debut * X_PMPPER_0
				FROM w_rec
				WHERE 1=1 AND
					ITMREF_0 = article_code_original AND
					STOFCY_0 = site_code_original AND
					date_ref <= date_debut AND
					w_stock.ok_pump = '0.5' AND
					X_PMPPER_0 != 0
				;	


				UPDATE w_STOCK SET
					pump = prix_distri_ht,
					stock_valeur_fin = w_STOCK.stock_quantite_fin * prix_distri_ht,
					ok_pump = 1
				FROM w_prix_distri
				WHERE w_prix_distri.ITMREF_0 = w_STOCK.article_code_original AND
				w_prix_distri.STOFCY_0 = w_STOCK.site_code_original AND
					w_STOCK.date_fin BETWEEN  w_prix_distri.date_debut AND w_prix_distri.date_fin
					AND ok_pump != '1'
					AND prix_distri_ht != 0
                ;


				
                 -- Prix reception historisé si toujours pas de pump
                DROP SEQUENCE IF EXISTS w_prix_rec_seq;
                CREATE TEMP SEQUENCE w_prix_rec_seq;
                
                DROP TABLE IF EXISTS w_prix_rec;
                CREATE TEMP TABLE w_prix_rec AS
                SELECT subview.*, '20991231'::date AS date_fin, nextval('w_prix_rec_seq'::regclass) AS prix_sequence
                FROM
                (
                SELECT STOFCY_0,ITMREF_0, date(date_trunc('month',IPTDAT_0)) AS date_debut,
                    (MAX(ARRAY[IPTDAT_0::text,PRIORD_0::text]))[2]::numeric AS prix_distri_ht,
                    0 AS prix_distri_ttc
                FROM prod_sagex3.STOJOU
                WHERE QTYSTU_0 > 0
					AND PRINAT_0 = 8
                GROUP BY 1,2,3
                ORDER BY 1,2,3
                ) subview;

                UPDATE w_prix_rec
                SET date_fin = w_prix_rec_next.date_debut - interval '1 day'
                FROM w_prix_rec w_prix_rec_next
                WHERE w_prix_rec.ITMREF_0 = w_prix_rec_next.ITMREF_0 AND
                w_prix_rec.STOFCY_0 = w_prix_rec_next.STOFCY_0 AND
                    w_prix_rec.prix_sequence = w_prix_rec_next.prix_sequence - 1
                ;
                
                CREATE INDEX w_prix_rec_i1 ON w_prix_rec USING btree (ITMREF_0)
                ;	
              
				CREATE INDEX w_prix_rec_i2 ON w_prix_rec USING btree (STOFCY_0)
                ;
				
				UPDATE w_STOCK SET
					pump = prix_distri_ht,
					stock_valeur_fin = w_STOCK.stock_quantite_fin * prix_distri_ht
				FROM w_prix_rec
				WHERE w_prix_rec.ITMREF_0 = w_STOCK.article_code_original AND
					w_prix_rec.STOFCY_0 = w_STOCK.site_code_original AND
					w_STOCK.date_fin BETWEEN  w_prix_rec.date_debut AND w_prix_rec.date_fin
					AND ok_pump != '1'
                ;

				UPDATE w_STOCK SET
					pump = prix_distri_ht,
					stock_valeur_fin = w_STOCK.stock_quantite_fin * prix_distri_ht
				FROM w_prix_rec
				WHERE w_prix_rec.ITMREF_0 = w_STOCK.article_code_original AND
					w_prix_rec.STOFCY_0 = w_STOCK.site_code_original AND
					w_STOCK.date_fin BETWEEN  w_prix_rec.date_debut AND w_prix_rec.date_fin
					AND ok_pump != '1'
                ;



				-- ajout des stocks mensuels manquants
				SELECT base.cti_execute('
				INSERT INTO w_stock
				SELECT 
					w_stock.site_code_original,
					w_stock.article_code_original,
					w_stock.article_id,
					w_stock.compte_id,
					w_stock.ucd_id,
					w_stock.lpp_id,
					w_stock.fournisseur_id,
					w_stock.site_id,
					w_stock.lieu_id,
					date(date_trunc(''month'',w_stock.date_debut) + interval ''1 month'') AS date_debut,
					date(date_trunc(''month'',w_stock.date_debut) + interval ''2 month'' - interval ''1 day'') AS date_fin,
					w_stock.mois_sequence + 1,
					0 AS entree_quantite,
					0 AS entree_montant,
					0 AS sortie_quantite,
					0 AS sortie_montant,
					w_stock.pump,
					w_stock.ok_pump,
					w_stock.stock_quantite_debut,
					w_stock.stock_quantite_fin,
					w_stock.stock_valeur_debut,
					w_stock.stock_valeur_fin
				FROM w_stock
				LEFT JOIN w_stock w_stock_next ON
					w_stock.site_id = w_stock_next.site_id AND
					w_stock.lieu_id = w_stock_next.lieu_id AND
					w_stock.article_code_original = w_stock_next.article_code_original AND
					w_stock.mois_sequence = w_stock_next.mois_sequence - 1
				WHERE 
					w_stock_next.mois_sequence IS NULL AND
					w_stock.date_debut <= date(now()) AND
					w_stock.date_fin >= ''[ENV_ECO_ANNEEDEBUT]-01-01'' AND
					w_stock.stock_quantite_fin != 0
				',200)
				;

                -- mise à jour des débuts
				UPDATE w_STOCK SET
					stock_quantite_debut = stock_quantite_fin - entree_quantite + sortie_quantite,
					stock_valeur_debut = stock_valeur_fin - entree_montant + sortie_montant
				;

				-- insertion 
				TRUNCATE eco.p_stock
				;
				
				INSERT INTO eco.p_stock
					(
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					fournisseur_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_fin
					)
				SELECT 
					article_id,
					compte_id,
					ucd_id,
					lpp_id,
					fournisseur_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_fin
				FROM w_stock
				WHERE stock_quantite_debut != 0 OR stock_quantite_fin != 0
				;
				
				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 label="Factures">
			<sqlcmd><![CDATA[
			
				
				SELECT base.cti_disable_index('eco', 'i_facture_1');
				SELECT base.cti_disable_index('eco', 'i_facture_2');
				SELECT base.cti_disable_index('eco', 'i_facture_3');
				SELECT base.cti_disable_index('eco', 'i_facture_4');
				SELECT base.cti_disable_index('eco', 'i_facture_5');
				
			
				TRUNCATE eco.p_facture;
				
				INSERT INTO eco.p_facture(
					code_original,
					no_facture,
					commande_id,
					date_facture,
					date_reglement,
					fournisseur_id,
					texte,
					montant_facture_article_ht,
					montant_facture_article_ttc,
					montant_facture_article_tva,
					montant_facture_port_ht,
					montant_facture_port_ttc,
					montant_facture_port_tva,
					montant_facture_ht,
					montant_facture_ttc,
					montant_facture_tva)
				SELECT 
					PINVOICED.NUM_0 AS code_original,
					MAX(PINVOICED.NUM_0) AS numero_facture,
					MAX(p_commandes.oid) AS commande_id,
					MAX(date(BPRDATVCR_0)) AS date_facture,
					MAX(date(GACCENTRY.ACCDAT_0)) AS date_reglement,
					MAX(t_fournisseurs.oid) AS fournisseur_id,
					MAX('Facture n°' || PINVOICED.NUM_0) as texte,
					SUM(AMTNOTLIN_0) AS montant_facture_article_ht,
					SUM(AMTATILIN_0) AS montant_facture_article_ttc,
					SUM(AMTTAXLIN1_0) AS montant_facture_article_tva,
					0::numeric,
					0::numeric,
					0::numeric,
					SUM(AMTNOTLIN_0) AS montant_facture_ht,
					SUM(AMTATILIN_0) AS montant_facture_tt,
					SUM(AMTTAXLIN1_0) AS montant_facture_tva
				FROM prod_sagex3.PINVOICED 
					JOIN eco.p_commandes ON POHNUM_0= p_commandes.code_original
					LEFT JOIN prod_sagex3.GACCENTRY ON GACCENTRY.NUM_0 = PINVOICED.NUM_0
					LEFT JOIN eco.t_fournisseurs ON t_fournisseurs.code_original = BPR_0
				WHERE PINVOICED.ACCDAT_0 >= '[ENV_ECO_ANNEEDEBUT]-01-01'
				GROUP BY 1
				ORDER BY 1;
			
				
				SELECT base.cti_enable_index('eco', 'i_facture_1');
				SELECT base.cti_enable_index('eco', 'i_facture_2');
				SELECT base.cti_enable_index('eco', 'i_facture_3');
				SELECT base.cti_enable_index('eco', 'i_facture_4');
				SELECT base.cti_enable_index('eco', 'i_facture_5');
				
				SELECT base.cti_disable_index('eco', 'i_lignes_facture_1');
				SELECT base.cti_disable_index('eco', 'i_lignes_facture_2');
				SELECT base.cti_disable_index('eco', 'i_lignes_facture_3');
				SELECT base.cti_disable_index('eco', 'i_lignes_facture_4');
				
			
				TRUNCATE eco.p_lignes_facture;
				
				INSERT INTO eco.p_lignes_facture(
					article_id,
					code_original,
					compte_id,
					facture_id,
					ligne_commande,
					ligne_commande_id,
					montant_facture_article_ht,
					montant_facture_article_ttc,
					montant_facture_article_tva,
					montant_facture_port_ht,
					montant_facture_port_ttc,
					montant_facture_port_tva,
					montant_facture_ht,
					montant_facture_ttc,
					montant_facture_tva
					)
				SELECT 
					t_articles.oid,
					PINVOICED.NUM_0 || '-' || PINVOICED.PIDLIN_0 AS code_original,
					t_articles.compte_id as compte_id,
					p_facture.oid,
					ligne_commande,
					p_lignes_commandes.oid,
					AMTNOTLIN_0 AS montant_facture_article_ht,
					AMTATILIN_0 AS montant_facture_article_ttc,
					AMTTAXLIN1_0 AS montant_facture_article_tva,
					0::numeric,
					0::numeric,
					0::numeric,
					AMTNOTLIN_0 AS montant_facture_ht,
					AMTATILIN_0 AS montant_facture_ttc,
					AMTTAXLIN1_0 AS montant_facture_tva
				FROM prod_sagex3.PINVOICED 
					JOIN eco.t_articles ON ITMREF_0 = t_articles.code_original
					JOIN eco.p_facture ON NUM_0 = p_facture.code_original
					JOIN eco.p_lignes_commandes ON POHNUM_0 || '-' || POPLIN_0 = p_lignes_commandes.code_original
					LEFT JOIN prod_sagex3.GACCENTRY ON GACCENTRY.NUM_0 = PINVOICED.NUM_0
				WHERE PINVOICED.ACCDAT_0 >= '[ENV_ECO_ANNEEDEBUT]-01-01'
				ORDER BY 2;
			
				SELECT base.cti_enable_index('eco', 'i_lignes_facture_1');
				SELECT base.cti_enable_index('eco', 'i_lignes_facture_2');
				SELECT base.cti_enable_index('eco', 'i_lignes_facture_3');
				SELECT base.cti_enable_index('eco', 'i_lignes_facture_4');
				
				DROP TABLE IF EXISTS w_engagement;
				CREATE TEMP TABLE w_engagement AS
				SELECT p_lignes_commandes.commande_id, MIN(date_facture) AS date_facture
				FROM eco.p_lignes_facture
				JOIN eco.p_facture ON facture_id = p_facture.oid
				JOIN eco.p_lignes_commandes ON ligne_commande_id = p_lignes_commandes.oid
				GROUP BY 1;

				UPDATE eco.p_commandes
				SET date_engagement = date_facture
				FROM w_engagement
				where oid = commande_id
				;
				
	
			]]></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_update_mvt_qte_stock();
			SELECT eco.cti_update_mvt_mnt_stock();
		]]></sqlcmd>
	</NODE>

</ROOT>
