DELIMITER $$

DROP PROCEDURE IF EXISTS `ht_EDI_tools`$$

CREATE DEFINER=`root`@`localhost` PROCEDURE `ht_EDI_tools`(
     IN _MODE 		VARCHAR(100),        -- tryb pracy
	 IN _RecGUID  	VARCHAR(38),         -- GUID operacji       
     INOUT _RepContent LONGTEXT
)
/*
procedura generująca dokument XML z faktury
*/

SPROC: BEGIN

	DECLARE S TEXT;
	DECLARE _Kraj  VARCHAR(20);
	DECLARE _REGON  VARCHAR(20);
	DECLARE _Email, _PaymentTerm, _PaymentMean, _OwnerMode VARCHAR(200);
	DECLARE _PelnaNazwa,  _Ulica, _Adres  VARCHAR(200);
	DECLARE _SQLText TEXT;
	DECLARE _Miasto, _BankAccountNumber  VARCHAR(50);
	
	DECLARE cVatZw, CSpKF,  CSpKR, _InvoiceType, _RokKorekty, cSL INTEGER;
	DECLARE _InvoiceNumber, _RelatedInvoiceNumber VARCHAR(30);
	DECLARE _InvoiceIssueDate, _InvoiceDueDate, _SalesDate, _RelatedInvoiceDate, _PayDate VARCHAR(17);
	DECLARE _Kod_poczt, _NrDomu, _NrLok, _CurrencyCoded, _RokKorektyStr VARCHAR(10);
	DECLARE _PurchaseOrderNumber, _HavingSQL, _OrderBySQL VARCHAR(500);
	
	DECLARE _ShowAllCorrLines BOOLEAN;  -- _Korekta, 
	
	DECLARE _PozGUID, _FinGUID VARCHAR(38);
	-- delivery:
	DECLARE _dGLN      VARCHAR(13);
	DECLARE _dNoteNo   VARCHAR(35);
	DECLARE _dNoteDate VARCHAR(8);
	
	DECLARE _IRN, _MRN VARCHAR(14);  --  interchange reference number,  Message reference number
	DECLARE _EAN, _ItemDesc1,  _ItemDesc2 VARCHAR(35);
	DECLARE _EDI_UoM VARCHAR(3);
	
	DECLARE _InvoiceQty, _NetPrice, _InvoiceNetAmount, _InvoiceTaxAmount, _InvoiceGrossAmount, _AllowSummary DOUBLE;
	
	DECLARE cSegTerm CHAR(1); -- = '''';  -- segment terminator
	DECLARE _SegmCount INTEGER;  -- licznik segmentów (wstawiany do UNT)
	DECLARE _PAT_period, _MiastoIdn  INTEGER;
	
	DECLARE CSTKU INTEGER DEFAULT 85;
	
	SET cSL = 4;

	SET cSegTerm = '''';  -- apostrof
	SET _SegmCount = 0;

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'invoice.to.EDI.Stanpol.create'
		Wygenerowanie dokumentu XML z fakturą do podpisania
		Parametry
		_MODE			Tryb pracy
		IN _RecGUID     GUID operacji z tab. opng
		
		_RepContent     Wygenerowana zawartość pliku XML
		
		CALL ht_EDI_tools('invoice.to.EDI.Stanpol.create', '{0A3F4841-12FB-422F-9509-547BBDE770C7}', @invoice.to.EDI.Content);
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/		
IF _MODE = 'invoice.to.EDI.Stanpol.create' THEN

	SET @OwnerGLN = '5909000650';  --  z konf.

	/*  nagłówek faktury  */

    -- segment UNB = Interchange header
	SET @invoice.to.EDI.Content = 'UNB+';  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNOC:3+');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, @OwnerGLN, ':14+');  -- Sender GLN  (GLN:	590|238300|L1L2L3|K  )   <- GLN Stanpolu
    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '3020115110000:14+');  -- Recipient  GLN, always 3020115110000  <-  GLN Casino
	
	-- DATE/TIME OF PREPARATION
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%y%m%d'), ':');  	 -- Creation date M n6 Format YYMMDD
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%H%i'),   '+');  	 -- Creation time M n4 Format hhmm
	SET _IRN = CONCAT('NB', DATE_FORMAT(NOW(), '%y%m%d%H%i%s'));  -- Interchange control reference M an..14 Unique interchange reference number
	
	-- L'utilisation de l'indicateur de test (DE 0035 = 1) est INTERDITE.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _IRN, cSegTerm, '\n');  
	
	-- segment UNH = Message header segment
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNH+'); 
	SET	 _MRN = CONCAT('NH', DATE_FORMAT(NOW(), '%y%m%d%H%i%s'));  -- Message reference number M an..14 Sender’s unique message reference
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _MRN, '+');   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'INVOIC:D:96A:UN:EAN008', cSegTerm, '\n');  
	SET _SegmCount = _SegmCount + 1;
	
	/*  pobranie danych z faktury */
	DROP TEMPORARY TABLE IF EXISTS `t_oper_ng`;	
	
	CREATE TEMPORARY TABLE `t_oper_ng`
	SELECT 
	    p.dni,
		-- CONCAT(k.nazwa, '+', k.ulica, '+', k.NazwaMiasta, '++', k.zipcode, '+PL') AS buyer,   
		o.idn, REPLACE(o.nrdokfin, '/', '') AS nrdokfin,
		DATE_FORMAT(o.datawystaw, '%Y%m%d') AS datawystaw,  DATE_FORMAT(o.datasprzed, '%Y%m%d') AS datasprzed,
		DATE_FORMAT(o.dataplatnosci, '%Y%m%d') AS dataplatnosci, 
		o.datawplywu, o.data_vat, o.rodzaj
	FROM opng o  
	LEFT JOIN kontrah k ON k.GUID = o.kontrGUID 
	LEFT JOIN platnosc p ON p.idn = o.sposobplatn
	WHERE o.guid = _RecGUID;
	
	SELECT 
		nrdokfin, datawystaw, datasprzed, dataplatnosci, dni, rodzaj  -- , buyer
	FROM 
		t_oper_ng
	INTO _InvoiceNumber, _InvoiceIssueDate,  _SalesDate, _PayDate, _PAT_period, _InvoiceType;   -- , _PelnaNazwa;
	
	-- SET @invoice.to.EDI_Korekta = _InvoiceType IN (SELECT rodzaj FROM operdoc WHERE nazwa LIKE 'ST-%');  -- 3,4, 85, 90
	
	-- segment BGM = Begin of Message
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'BGM+'); 
    /* 380 = Facture
	   381 = Avoir	  <-  opng.rodzaj = 85  (CSTKU)  */
	IF _InvoiceType = CSTKU THEN
	  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '381+');  	
	ELSE   
	  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '380+');  	
	END IF;  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNumber, '+'); -- Document / message number C an..35 Invoice number / identifier 
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '9', cSegTerm, '\n'); -- Message function, coded C an..3 9 = original
	SET _SegmCount = _SegmCount + 1;
	
	/* 137 = Date du message
		35 = Date réelle livraison
	   200 = Date d’enlevement
		11 = Date d’expédition  */
	-- Invoice date  137 = document / message date  (data wystaw.)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+137:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceIssueDate, ':');  -- data wystaw.  opng.datawystaw
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;

	-- 35 = delivery date = Date réelle livraison = data dostawy
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+35:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _SalesDate, ':');  -- na razie opng.datasprzed
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;

	-- FTX+REG+++PEINTOU:SARL:100000EUR’  opisy na str.5 "Invoic D96.A"   SARL = Sp. z o.o.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'FTX+REG+++Stanpol:sp z o.o.', cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- okreslenie GUIDa Wztki
	SELECT 
		DISTINCT idnoper 
	FROM	oppo 
	WHERE 	idnoperfin = _RecGUID	LIMIT 1
	INTO _FinGUID;
	
	-- pobranie danych
	SELECT IFNULL(k.gln, 'brak danych') AS GLN, IFNULL(REPLACE(wz.nrdokmag, '/', '')  , '') AS nrdokmag, DATE_FORMAT(wz.datawystaw, '%Y%m%d') AS datawystaw  
	FROM opng wz 
	JOIN kontrah k ON k.guid = wz.kontrguid
	WHERE wz.guid = _FinGUID
	INTO _dGLN, _dNoteNo, _dNoteDate;  
	
	-- The delivery note number is a mandatory information and must not contain leading zeros  RFF+DQ:49158'  -- jakies pole z opng.  (max.35 znakow) str. 17
	-- z WZ-tki: albo numer mag., albo nr z pola "dotyczy:"  _dNoteNo
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+DQ:', _dNoteNo, cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- dla avoir (korekty) być moze beda potrzebne jeszcze inne dane w segmencie RFF (str 6-7)
	
	-- The delivery note date is a mandatory information. DTM+171:20080514:102'   
	-- WZ-tka (opng.datawystaw)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+171:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _dNoteDate, ':');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;
	

	
	/* NOM ET ADRESSE
	   -- SEGMENT NAD Nom et adresse (Groupe SG2)   	
	   http://www.gs1.org/docs/gsmp/eancom/2012/ean02s4/part2/invoic/059.htm : 
	A segment identifying names and addresses of the parties, in coded or clear form, and their functions relevant to the invoice. 
	Identification of the seller and buyer parties is mandatory for the invoice message */
	
	-- płatnik (buyer) :
	-- NAD+IV+3020119911001::9++DISTRIBUTION CASINO FRANCE SAS+1 ESPLANADE DE FRANCE+SAINT-ETIENNE++42008+FR’ 
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+IV+3020119911001::9++DISTRIBUTION CASINO FRANCE SAS+1 ESPLANADE DE FRANCE+SAINT-ETIENNE++42008+FR', cSegTerm, '\n'); 
	
	-- Vendeur (sprzedawca / seller):
			
	-- GLN i adres dostawcy (Stanpolu): NAD+SE+3010000000000::9++RS VENDEUR+ADRESSE+VILLE++75003+FR
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+SE+', @OwnerGLN, '::9++');	
	-- nazwa, miasto, ulica, kod poczt.
	/* CALL _IReg_Get('Owner', 'Name', 0, 'STRING', _PelnaNazwa, '(brak danych)');
	CALL _IReg_Get('Owner', 'Miasto', 0, 'STRING', _Miasto, '(brak danych)');    */
	CALL _IReg_Get('DaneFirmy', 'Pelna_nazwa', 0, 'STRING', _PelnaNazwa, '(brak danych)');
	CALL _IReg_Get('DaneFirmy', 'Miasto', '0', 'INTEGER', _MiastoIdn, '0'); 	
	SELECT NazwaMiasta FROM `Miasta` WHERE idn = _MiastoIdn INTO _Miasto;
	-- CALL _IReg_Get('DaneFirmy', 'Miasto', 0, 'STRING', _Miasto, '(brak danych)');    
	CALL _IReg_Get('DaneFirmy', 'Ulica', 0, 'STRING', _Ulica, '(brak danych)');   
	CALL _IReg_Get('DaneFirmy', 'Nr_domu', 0, 'STRING', _NrDomu, '(brak danych)');  
	CALL _IReg_Get('DaneFirmy', 'Kod_poczt', 0, 'STRING', _Kod_poczt, '(brak danych)');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PelnaNazwa, '+', _Ulica, ' ', _NrDomu, '+', _Miasto, '++', _Kod_poczt, '+PL', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	/*  jesli NAD+CO (siedziba sprzedawcy) bedzie wymagane, to skopiowac sekcje 'NAD+SE+' */
	
	/* RE 	= 	Party to receive commercial invoice remittance 	(przekaz)
				Party to whom payment for a commercial invoice or bill should be remitted.   
				NAD+RE+3034001450100::9' 				*/
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+RE+', @OwnerGLN, '::9', cSegTerm, '\n');					
				
	
	-- VAT ID dostawcy  RFF+VA:PL123456789'  TVA = VAT
	CALL _IReg_Get('DaneFirmy', 'NIP', 0, 'STRING', @DaneFirmy_NIP, 0);    
	SET @DaneFirmy_NIP = REPLACE(@DaneFirmy_NIP, '-', '');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+VA:PL', @DaneFirmy_NIP, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- buyer (nabywca / acheteur) (CASINO)  "3020115110000" - bledne 
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+BY+3020119911001::9', cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
/*	-- delivery point: NAD+DP+4335815000058::9   
	NAD+DP n’est pas obligatoire
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+DP+', _dGLN, '::9', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;  
	delivery point jest tu identyczny z NAD+BY  (kontrahent na MG WZ i na ST UE jest ten sam
	*/
	
	
	   
	-- CUX+2:EUR:4'   Stating the reference currency is mandatory
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'CUX+2:EUR:4', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- PAT 	- 	M 	1 	- Payment terms basis   _PAT_period  3 = Date fixe, 22 = Conditions d'escompte, 20 = Conditions de pénalité
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'PAT+3++5:3:D:', _PAT_period, cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- data platnosci (?)  <= PAT+3    DTM+13:20140216:102'
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+13:', _PayDate, ':102', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- PAT+22  22 = Conditions d'escompte  => PCD+12:3.0:13’   Escompte conditionnel: 3% de la valeur facture   Casino - rabat 0%
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'PAT+22++5:3:D:', _PAT_period, cSegTerm, '\n');
	-- PCD+12:0.55:13'
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'PCD+12:0.0:13', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 2;
	
	-- PAT+20'
		
	/*  koniec sekcji nagłówka faktury  */
	
	/*  pozycje faktury; faktury są na ogól jednoliniowe, a zawsze dotycza jednego towaru
	    wiec po zgrupowaniu po towarze zawsze powstanie jedna linia  	*/
		
	 select          
            SUM(P.ilosc) AS ilosc, SUM(P.wartnet) AS wartnet, SUM(P.wartvat) AS wartvat, P.cenanet, 
            -- P.idnvat, P.towrsymb, P.pkwiu,
			-- LEFT(P.towrnazwa, 33) AS nazwa_cz1,  SUBSTR(P.towrnazwa, 34) AS nazwa_cz2,  
			'Filet frais de cabillaud 100-200g' AS nazwa_cz1, 'avec flanc'  AS nazwa_cz2,  
			T.kod_kreskowy,		LEFT(IFNULL(J.EDI_index, 'PCE'), 3)  AS EDI_UoM			
	  FROM opng N 
            LEFT JOIN oppo P ON N.GUID = P.idnoperfin 
            LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
            LEFT JOIN Jednostki J ON J.idn = P.jednostka		
		    WHERE P.idnoperfin = _RecGUID 
            GROUP BY P.idntowr 
	  INTO  _InvoiceQty, _InvoiceNetAmount, _InvoiceTaxAmount, _NetPrice, 
			_ItemDesc1,  _ItemDesc2, _EAN, _EDI_UoM;

	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'LIN+1++', _EAN, ':EN', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	-- PIA+1+123456789:GN'  <- PKWiU jest opcjonalne  P.pkwiu,	
	
	-- IMD
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'IMD+E+ANM+:::', _ItemDesc1, ':', _ItemDesc2, cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- invoiced qty QTY+47:15120:PCE' or QTY+47:15120
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'QTY+47:');    -- 47 = invoiced quantity
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceQty, ':');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _EDI_UoM, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+203:');    -- 203 = Montant net de la ligne
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- PRI+AAA:6549.25’
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'PRI+AAA:');    -- AAA = unit net price  AAA = Prix unitaire net HT
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _NetPrice, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- TAX+7+VAT+++:::5+S'  stawka VAT 5%   TAX+7+VAT+++:::19.6'
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT+++:::0', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- ALC+A++2+1+QD:::REMISE QUANTITATIVE'   A segment identifying the charge or allowance and, where necessary its calculation sequence.
	
	-- PCD Percentage details. 	This segment is used to specify percentage discounts or charges for the line item being invoiced.
	-- MOA+204  - powiazane z segmentem PCD
	-- TAX+   - stawki VAT odn. PCD, podajemy jesli inne niż inne niż SG33-TAX
	
	/*  Invoice Summary Section - sekcja podsumowan */
	
	-- Section control	This segment is used to identify the break between the message detail and message trailer sections.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNS+S', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	/*  
	125 = Montant taxable      (HT)  125 	= 	Taxable amount 	Amount on which a tax has to be applied.
	128 = Montant total       (TTC)  128 	= 	Total amount 	The amount specified is the total amount.
	124 = Montant de la taxe  (TVA)  124 	= 	Tax amount 	  Tax imposed by government or other official authority related to the weight/volume charge or valuation charge. 
		
	    MOA+125:69832.5'
		MOA+128:83519.66'    TTC = 125 + 124
		MOA+124:13687.16'   */
			
/*	
	-- MOA+77:100482.07'  This segment contains the invoice total amount including tax.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+77:');    -- 77 = invoice amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, (_InvoiceNetAmount + _InvoiceTaxAmount), cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
		
	-- MOA+79:86341.14'  This segment contains the total of all line item amounts, excluding tax (net price * quantity).	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+79:');    -- 79 = total line items amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;    */
	
	-- MOA+125:86341.14'  The taxable amount represents the invoice amount before tax.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+125:');    -- 125 = taxable amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+128:');    
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, (_InvoiceNetAmount + _InvoiceTaxAmount), cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
		
	-- MOA+124:14140.93'   tax amount
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+124:');    -- 124 =
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceTaxAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	--  TAX+7+VAT++69832.5+:::19.6'   <- podaje się podstawę podatku (125 = Montant taxable)		   	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT++', _InvoiceNetAmount,'+:::0', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+124:14140.93'   tax amount
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+124:');    -- 124 =
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceTaxAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- Allowance or charge
	-- ALC+C+3001000002312+++TX:::DROITS'
	-- MOA+8:273.24'
	
	/*
	-- total position amount per tax rate in invoice currency
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+79:');    -- 79 = total line items amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+125:');    -- 125 = The total taxable amount of all taxable amounts per VAT rate.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- The TAX-segment needs to be repeated twice because only two repetitions of the following MOA segments are allowed according to EANCOM
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT+++:::5+S', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+124:14140.93'   The total VAT tax amount of all VAT amounts per rate.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+124:');    -- 124 =  VAT amount per VAT rate
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceTaxAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	*/
				
	-- UNT zamyka segment UNH  (end of the individual messages)		   
	--	Message trailer	This segment is a mandatory UN/EDIFACT segment. It must always be the last segment in the message.
	SET _SegmCount = _SegmCount + 1;  -- doliczamy segment UNH
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNT+', _SegmCount, '+', _MRN, cSegTerm, '\n'); -- _SegmCount - number of segments applied in this message including the service segments UNH and UNT.
	
	
	-- UNZ+1+459'  - UNZ zamyka segment UNOC		   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNZ+1+', _IRN, cSegTerm, '\n'); 
			   
	SET _RepContent = @invoice.to.EDI.Content;
END IF;
	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'invoice.to.EDI.DOS.create'
		Wygenerowanie dokumentu XML z fakturą do podpisania
		Parametry
		_MODE			Tryb pracy
		IN _RecGUID     GUID operacji z tab. opng
		
		_RepContent     Wygenerowana zawartość pliku XML
		
		CALL ht_EDI_tools('invoice.to.EDI.DOS.create', '{0A3F4841-12FB-422F-9509-547BBDE770C7}', @invoice.to.EDI.Content);
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/		
IF _MODE = 'invoice.to.EDI.DOS.create' THEN

    /* Lidl supports ANSI and UTF+8 character set. For UTF+8 please contact the Lidl EDI
	   support to adjust the settings. */
	   
	-- SET NAMES utf8;	  
	SET @OwnerGLN = '5902383000002';
	

	DROP TEMPORARY TABLE IF EXISTS `t_oper_ng`;	
	
	CREATE TEMPORARY TABLE `t_oper_ng`
	SELECT 
		CONCAT(k.nazwa, '+', k.ulica, '+', k.NazwaMiasta, '++', k.zipcode, '+PL') AS buyer,   
		o.idn, o.nrdokfin, -- REPLACE(o.nrdokfin, '/', '') AS nrdokfin,
		DATE_FORMAT(o.datawystaw, '%Y%m%d') AS datawystaw,  DATE_FORMAT(o.datasprzed, '%Y%m%d') AS datasprzed,
		o.datawplywu, o.data_vat
	FROM opng o  
	LEFT JOIN kontrah k ON k.GUID = o.kontrGUID 
	WHERE o.guid = _RecGUID;
	
	SELECT 
		nrdokfin, datawystaw, datasprzed, buyer
	FROM 
		t_oper_ng
	INTO _InvoiceNumber, _InvoiceIssueDate,  _SalesDate, _PelnaNazwa;
	
	/* dane z Wztki */
	
	-- okreslenie GUIDa Wztki
	SELECT 
		DISTINCT idnoper, GUIDzm  
	FROM	oppo 
	WHERE 	idnoperfin = _RecGUID	LIMIT 1
	INTO _FinGUID, @zmpo.GUID;
	
	-- pobranie numeru zamowienia kontrahenta
	SELECT zn.nrzamwkontr 
	FROM	zmng zn, zmpo zo
	WHERE zn.GUID = zo.IdnNG AND zo.guid = @zmpo.GUID
	INTO _PurchaseOrderNumber;
	
	-- pobranie danych
	SELECT 
		IFNULL(k.gln, 'brak danych') AS GLN, 
		-- IFNULL(REPLACE(wz.nrdokmag, '/', '')  , '') AS nrdokmag, -- _dNoteNo - usuwac wiodace zera i nie usuwac slasha 
		IFNULL(TRIM(LEADING '0' FROM wz.nrdokmag), '') AS nrdokmag,   
		DATE_FORMAT(wz.datawystaw, '%Y%m%d') AS datawystaw  
	FROM opng wz 
	JOIN kontrah k ON k.guid = wz.kontrguid
	WHERE wz.guid = _FinGUID
	INTO _dGLN, _dNoteNo, _dNoteDate;  -- _dNoteNo - usuwac wiodace zera i nie usuwac slasha 

	
    /*  koniec pobierania danych z Wztki */

    /*  poczatek sekcji nagłówka faktury  */

    -- segment UNB = Interchange header
	SET @invoice.to.EDI.Content = 'UNB+';  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNOD:3+');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '5902383000002:14+');  -- Sender GLN  (GLN:	590|238300|L1L2L3|K  )   <- GLN DOSa
    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '4333685000000:14+');  -- Recipient GLN, always 4333685000000
	-- DATE/TIME OF PREPARATION
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%y%m%d'), ':');  	 -- Creation date M n6 Format YYMMDD
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%H%i'),   '+');  	 -- Creation time M n4 Format hhmm
	SET _IRN = CONCAT('NB', DATE_FORMAT(NOW(), '%y%m%d%H%i%s'));  -- Interchange control reference M an..14 Unique interchange reference number
/*	faza testow
    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _IRN, '+');   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '+++++');    -- puste dane
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '1');        -- Test indicator C n1 1 = Test transfer, otherwise empty  */
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _IRN);   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, cSegTerm, '\n');
	
	-- segment UNH = Message header segment
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNH+'); 
	SET	 _MRN = CONCAT('NH', DATE_FORMAT(NOW(), '%y%m%d%H%i%s'));  -- Message reference number M an..14 Sender’s unique message reference
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _MRN, '+');   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'INVOIC:D:96A:UN:EAN008', cSegTerm, '\n');  
	SET _SegmCount = _SegmCount + 1;
	
	-- segment BGM = Begin of Message
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'BGM+'); 
    /* 380 = commercial invoice
       384 = correction invoice	 	   
	  currently it is not possible to use the EDI message type correction invoice. All correction invoices
      or credit notes have to be sent in hardcopy form (paper). 	   */
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '380:::');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'FAKTURA VAT+');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNumber, '+'); -- Document / message number C an..35 Invoice number / identifier 
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '9', cSegTerm, '\n'); -- Message function, coded C an..3 9 = original
	SET _SegmCount = _SegmCount + 1;
	
	-- Invoice date  137 = document / message date  (data wystaw.)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+137:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceIssueDate, ':');  -- data wystaw.  opng.datawystaw
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;
	
	-- 35 = delivery date
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+35:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _SalesDate, ':');  -- na razie opng.datasprzed
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;
	
	/* If the sales date is different from the invoice issue date, the sales date has to be declared
       additionally (see DTM+356 Segment).  if opng.datasprzed <> opng.datawystaw  */
	-- 356 = sales date / time, actual
	IF _InvoiceIssueDate <> _SalesDate THEN
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+356:');
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _SalesDate, ':');  -- opng.datasprzed
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD   
		SET _SegmCount = _SegmCount + 1;
	END IF;	
	
	-- FTX+AAK+1+ST2++PL'  opisy ST1, ST2, ST3 na str. 11 w "Segment Description for Electronic Data Interchange"
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'FTX+AAK+1+ST2++PL', cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- The delivery note number is a mandatory information and must not contain leading zeros  RFF+DQ:49158'  -- pole z opng.  (max.35 znakow) str. 17
	-- z WZ-tki: albo numer mag., albo nr z pola "dotyczy:"  _dNoteNo
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+DQ:', _dNoteNo, cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- The delivery note date is a mandatory information. DTM+171:20080514:102'   
	-- WZ-tka (opng.datawystaw)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DTM+171:');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _dNoteDate, ':');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '102', cSegTerm, '\n'); -- 102 = CCYYMMDD
	SET _SegmCount = _SegmCount + 1;
	
	-- The order number of the buyer is an optional information.  Example: RFF+ON:80000'
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+ON:', LEFT(_PurchaseOrderNumber, 35), cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	--  Buyer : NAD+BY+4335814000004::9++Lidl Polska Sklepy Spożywcze:Sp. z o.o. Sp. k.+Poznańska 48, Jankowice+Tarnowo Podgórne++62-080+PL‘  (zgodne z danymi kontrahenta na fakturze)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+BY+4335814000004::9++', _PelnaNazwa, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	-- kontrah.nazwa+k.ulica , miasto,+k. kod poczt.
	-- ANSI:
	-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+BY+4335814000004::9++Lidl Polska Sklepy Spożywcze:Sp. z o.o. Sp. k.+Poznańska 48, Jankowice+Tarnowo Podgórne++62-080+PL', cSegTerm, '\n'); -- ANSI
	-- UTF8:
	 -- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+BY+4335814000004::9++Lidl Polska Sklepy SpoĹĽywcze:Sp. z o.o. Sp. k.+PoznaĹ„ska 48, Jankowice+Tarnowo PodgĂłrne++62-080+PL', cSegTerm, '\n'); -- UTF8
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+VA:PL7772739996', cSegTerm, '\n'); -- VAT ID Lidl Polska
	SET _SegmCount = _SegmCount + 1;
	
	-- delivery point: NAD+DP+4335815000058::9   (GLN konkretnego LIDLa - okreslonego na WZ-ce)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+DP+', _dGLN, '::9', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- GLN i adres dostawcy (czyli DOSa): NAD+SU+9912346000990::9++Supplier XY GmbH+Example Street 7+Berlin++12345+DE’
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'NAD+SU+', @OwnerGLN, '::9++');	
	-- nazwa, miasto, ulica, kod poczt.
	CALL _IReg_Get('DaneFirmy', 'Pelna_nazwa', 0, 'STRING', _PelnaNazwa, '(brak danych)');
	-- CALL _IReg_Get('Owner', 'Miasto', 0, 'STRING', _Miasto, '(brak danych)');   
	CALL _IReg_Get('DaneFirmy', 'Miasto', '0', 'INTEGER', _MiastoIdn, '0'); 	
	SELECT NazwaMiasta FROM `Miasta` WHERE idn = _MiastoIdn INTO _Miasto;
	CALL _IReg_Get('DaneFirmy', 'Ulica', 0, 'STRING', _Ulica, '(brak danych)');   
	CALL _IReg_Get('DaneFirmy', 'Nr_domu', 0, 'STRING', _NrDomu, '(brak danych)');  
	CALL _IReg_Get('DaneFirmy', 'Kod_poczt', 0, 'STRING', _Kod_poczt, '(brak danych)');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PelnaNazwa, '+', _Ulica, ' ', _NrDomu, '+', _Miasto, '++', _Kod_poczt, '+PL', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	-- VAT ID dostawcy  RFF+VA:PL123456789'  
	/* Instead the use of an international VAT-No. polish suppliers may use their national tax no., e.g.:
	   RFF+VA:777-00-20-410'  */
	CALL _IReg_Get('DaneFirmy', 'NIP', 0, 'STRING', @DaneFirmy_NIP, 0);    	
	SET @DaneFirmy_NIP = REPLACE(@DaneFirmy_NIP, '-', '');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+VA:PL', @DaneFirmy_NIP, cSegTerm, '\n'); 	
	-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'RFF+VA:', @DaneFirmy_NIP, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	   
	-- CUX+2:PLN:4'   Stating the reference currency is mandatory
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'CUX+2:PLN:4', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	/*  koniec sekcji nagłówka faktury  */
	
	/*  pozycje faktury; faktury są na ogól jednoliniowe, a zawsze dotycza jednego towaru
	    wiec po zgrupowaniu po towarze zawsze powstanie jedna linia  	*/
		
	-- ciag 'Szprot wędzony 210 g - tacka MAP "Nautica"'  ma dlugosc 43 znaki, a tu mamy bloki po 35 znakow	
      select          
            SUM(P.ilosc) AS ilosc, SUM(P.wartnet) AS wartnet, SUM(P.wartvat) AS wartvat, P.cenanet, 
            -- P.idnvat, P.towrsymb, P.pkwiu,
			LEFT(P.towrnazwa, 33) AS nazwa_cz1,  SUBSTR(P.towrnazwa, 34) AS nazwa_cz2,  
			T.kod_kreskowy,		LEFT(IFNULL(J.EDI_index, 'PCE'), 3)  AS EDI_UoM			
	  FROM opng N 
            LEFT JOIN oppo P ON N.GUID = P.idnoperfin 
            LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
            LEFT JOIN Jednostki J ON J.idn = P.jednostka		
		    WHERE P.idnoperfin = _RecGUID 
            GROUP BY P.idntowr 
	  INTO  _InvoiceQty, _InvoiceNetAmount, _InvoiceTaxAmount, _NetPrice, 
			_ItemDesc1,  _ItemDesc2, _EAN, _EDI_UoM;

	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'LIN+1++', _EAN, ':EN', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	-- PIA+1+123456789:GN'  <- PKWiU jest opcjonalne  P.pkwiu,
	
	-- IMD+A++:::Item Text'
	-- ciag 'Szprot wędzony 210 g - tacka MAP "Nautica"'  ma dlugosc 43 znaki, a tu mamy bloki po 35 znakow
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'IMD+A++:::', _ItemDesc1, ':', _ItemDesc2, cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- invoiced qty QTY+47:15120:PCE' or QTY+47:15120
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'QTY+47:');    -- 47 = invoiced quantity
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceQty, ':');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _EDI_UoM, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+66:65492.50' line amount (net calc.)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+66:');    -- 66 = goods item total (net calculation)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- PRI+AAA:6549.25’
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'PRI+AAA:');    -- AAA = unit net price
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _NetPrice, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- TAX+7+VAT+++:::5+S'  stawka VAT 5%
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT+++:::5+S', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	/*  sekcja podsumowan */
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNS+S', cSegTerm, '\n');
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+77:100482.07'  This segment contains the invoice total amount including tax.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+77:');    -- 77 = invoice amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, (_InvoiceNetAmount + _InvoiceTaxAmount), cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
		
	-- MOA+79:86341.14'  This segment contains the total of all line item amounts, excluding tax (net price * quantity).	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+79:');    -- 79 = total line items amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+125:86341.14'  The taxable amount represents the invoice amount before tax.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+125:');    -- 125 = taxable amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+124:14140.93'   tax amount
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+124:');    -- 124 =
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceTaxAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
			   
	-- TAX+7+VAT+++:::5+S'  stawka VAT 5%
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT+++:::5+S', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	-- total position amount per tax rate in incoice currency
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+79:');    -- 79 = total line items amount (invoice currency)
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+125:');    -- 125 = The total taxable amount of all taxable amounts per VAT rate.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNetAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
	
	-- The TAX-segment needs to be repeated twice because only two repetitions of the following MOA segments are allowed according to EANCOM
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'TAX+7+VAT+++:::5+S', cSegTerm, '\n');	
	SET _SegmCount = _SegmCount + 1;
	
	-- MOA+124:14140.93'   The total VAT tax amount of all VAT amounts per rate.
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'MOA+124:');    -- 124 =  VAT amount per VAT rate
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceTaxAmount, cSegTerm, '\n'); 
	SET _SegmCount = _SegmCount + 1;
			   
	-- UNT+49+1'  UNT zamyka segment UNH  (end of the individual messages)		   
	SET _SegmCount = _SegmCount + 1;  -- doliczamy segment UNH
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNT+', _SegmCount, '+', _MRN, cSegTerm, '\n'); -- _SegmCount - number of segments applied in this message including the service segments UNH and UNT.
			   
	-- UNZ+1+459'  - UNZ zamyka segment UNOD		   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'UNZ+1+', _IRN, cSegTerm, '\n'); 
			   
	SET _RepContent = @invoice.to.EDI.Content;
END IF;  -- 'invoice.to.EDI.DOS.create'	

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'invoice.to.EDI.stanpol.wrap'
		Opakowanie podpisanego dokumentu XML w komunikat <sh:StandardBusinessDocument>
		Parametry
		_MODE			Tryb pracy
		IN _RecGUID     nieuzywany
		
		_RepContent     na wejściu : podpisany <eanucc:message>, na wyjściu : gotowy komunikat <sh:StandardBusinessDocument>
		
		CALL ht_EDI_tools('invoice.to.EDI.stanpol.create', '{0A3F4841-12FB-422F-9509-547BBDE770C7}', @invoice.to.EDI.Content);
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/		
IF _MODE = 'invoice.to.EDI.STANPOL.wrap' THEN
		
	-- SET @invoice.to.EDI.Content = '';
	
	SET @invoice.to.EDI.Content = '<?xml version="1.0" encoding="UTF-8" ?>\n';
	-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:eanucc="urn:ean.ucc:2" xmlns:pay="urn:ean.ucc:pay:2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.3/schemas/sbdh/StandardBusinessDocumentHeader.xsd">\n');
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.3/schemas/sbdh/StandardBusinessDocumentHeader.xsd">\n');
	
	-- naglowek dokumentu
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:StandardBusinessDocumentHeader>\n');
			
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:HeaderVersion>1.0</sh:HeaderVersion>\n');
				-- nadawca: Stanpol
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Sender>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Identifier Authority="EAN.UCC">');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  '5909000650');   -- GLN z konf.
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Identifier>\n');					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Sender>\n');
				-- odbiorca: DISTRIBUTION CASINO France (symbol: CASINO)  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Receiver>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Identifier Authority="EAN.UCC">');
					-- SELECT gln FROM kontrah WHERE symbol='CASINO' => '3020115110000';
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '3020115110000');    
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Identifier>\n');					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Receiver>\n');
	/*	<sh:Sender>
			<sh:Identifier Authority="EAN.UCC">2203148000007</sh:Identifier>			
		</sh:Sender>
		<sh:Receiver>
			<sh:Identifier Authority="EAN.UCC">6903148000007</sh:Identifier>			
		</sh:Receiver>				*/		
				
			
		/*	identyfikacja dokumentu	
		<sh:DocumentIdentification>
			<sh:Standard>http://www.uc-council.org/smp/schemas/simpl-eb/OrderResponse</sh:Standard>
			<sh:TypeVersion>Order Response V1.3</sh:TypeVersion>
			<sh:InstanceIdentifier>100003</sh:InstanceIdentifier>
			<sh:Type>Ordering</sh:Type>
			<sh:MultipleType>false</sh:MultipleType>
			<sh:CreationDateAndTime>2003-05-09T00:31:52Z</sh:CreationDateAndTime>
		</sh:DocumentIdentification>  */
			    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:DocumentIdentification>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Standard>EAN.UCC</sh:Standard>\n');
	                SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:TypeVersion>2.3</sh:TypeVersion>\n'); 			
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:InstanceIdentifier>'); 			
					  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, CONCAT('TRA-', UUID()));  -- Identifiant unique d'Ă©change
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:InstanceIdentifier>\n'); 			
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Type>Invoice</sh:Type>\n');
					-- <sh:CreationDateAndTime>2003-05-09T00:31:52Z</sh:CreationDateAndTime> -- YYYY-MM-DDTHH:MN:SS+HH:MN
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:CreationDateAndTime>'); 			
					  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%Y-%m-%dT%T'));
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:CreationDateAndTime>\n'); 								
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:DocumentIdentification>\n');
				
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:StandardBusinessDocumentHeader>\n');	
	
	-- teraz tutaj wstawiamy podpisany <eanucc:message>
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _RepContent);

  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '\n</sh:StandardBusinessDocument>');
  SET _RepContent = @invoice.to.EDI.Content;
	
END IF; 	-- _MODE = 'invoice.to.EDI.STANPOL.wrap'


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'invoice.to.EDI.stanpol.create.sh'
		Wygenerowanie dokumentu XML z fakturą do podpisania
		Parametry
		_MODE			Tryb pracy
		IN _RecGUID     GUID operacji z tab. opng
		
		_RepContent     Wygenerowana zawartość pliku XML
		
		CALL ht_EDI_tools('invoice.to.EDI.stanpol.create.sh', '{0A3F4841-12FB-422F-9509-547BBDE770C7}', @invoice.to.EDI.Content);
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/		
IF _MODE = 'invoice.to.EDI.stanpol.create.sh' THEN
BEGIN	
	
	DECLARE  _LastDay  DATE;
	DECLARE  _IlePoz  INTEGER;	
	DECLARE  _UwagiNg VARCHAR(400);	
	
	SET CSpKF = 03;
	SET CSpKR = 04;
	SET cVatZw   =  3;
		
	SET _AllowSummary = 0;
	
	DROP TEMPORARY TABLE IF EXISTS `t_oper_ng`;
	
	CREATE TEMPORARY TABLE `t_oper_ng`
		SELECT o.nrdokfin AS InvoiceNumber, o.rodzaj AS InvoiceType,
		    DATE_FORMAT(o.datawystaw, '%Y%m%dT%T') AS InvoiceIssueDate, -- o.*, 
			-- DATE_FORMAT(o.dataplatnosci, '%Y%m%dT%T') AS InvoiceDueDate,    
			DATE_FORMAT(o.dataplatnosci, '%Y-%m-%d') AS InvoiceDueDate,
			DATE_FORMAT(o.datasprzed, '%Y%m%dT%T') AS SalesDate,
			korektanrdokfin AS RelatedInvoiceNumber, o.rokkorekty AS RokKorekty,
			DATE_FORMAT(o.korektadata, '%Y%m%dT%T') AS RelatedInvoiceDate,
		    W.Symbol AS CurrencyCoded, 
			REPLACE(B.konto, ' ', '') AS BankAccountNumber,       -- B.NazwaBanku => BankName
			-- Replace(platnosc.nazwa,'%d',platnosc.dni) 
			P.rodzaj as rodzajplatnosci, IFNULL(Replace(P.nazwa, '%d', P.dni), 'BRAK DANYCH') AS PaymentTerm, -- IFNULL(CONCAT(P.nazwa, P.dni), 'BRAK DANYCH') AS PaymentTerm,
			IFNULL(P.nazwa, 'BRAK DANYCH') AS PaymentMean,
			K.GLN, K.analityka, K.reprezentant, K.UwagiNaFV, K.uwagi as uwagikontrah, 
            K.W_ulica, K.W_zipcode, K.W_nazwamiasta, K.odbierajacy as kontrodbierajacy, 
            K.EDI_Seller_CodeByBuyer, IFNULL(o.stawka_podat_dodatk, 0) AS AllowSummary,         -- w polu "stawka_podat_dodatk" mamy kwote rabatu
            K.w_TelKontaktowy, mi2.IDNKraju AS kraj 
            from opng o 
            LEFT join waluty W ON W.idn = o.waluta 
            LEFT JOIN platnosc P ON o.sposobplatn=P.idn 
            LEFT JOIN kontrah K ON K.GUID = o.kontrGUID 
			LEFT JOIN banki B ON B.idn = K.DomyslnyBank
            LEFT JOIN Miasta mi2 ON mi2.NazwaMiasta = K.W_NazwaMiasta 
            where o.guid = _RecGUID;
	
	SELECT 
		InvoiceNumber, InvoiceType, InvoiceIssueDate, CurrencyCoded, InvoiceDueDate, SalesDate, RelatedInvoiceNumber, RelatedInvoiceDate,
		BankAccountNumber, PaymentTerm, PaymentMean, AllowSummary		
	FROM 
		t_oper_ng
	INTO _InvoiceNumber, _InvoiceType, _InvoiceIssueDate, _CurrencyCoded, _InvoiceDueDate, _SalesDate, _RelatedInvoiceNumber, _RelatedInvoiceDate,
		_BankAccountNumber, _PaymentTerm, _PaymentMean, _AllowSummary;
	
	IF ISNULL(_BankAccountNumber) THEN
		CALL _IReg_Get('DaneFirmy', 'Bank', 0, 'STRING', _BankAccountNumber, '(brak danych)');    -- 'Owner'
	END IF;
	
	SET @invoice.to.EDI_Korekta = _InvoiceType IN (SELECT rodzaj FROM operdoc WHERE nazwa LIKE 'ST-%');  -- 3,4, 85, 90
	
	DROP TEMPORARY TABLE IF EXISTS `t_oper_poz`;	
	
	IF @invoice.to.EDI_Korekta THEN
	
		-- set _ShowAllCorrLines = FALSE:
		-- CALL _IReg_Get('Wydruki', 'Pokaz_wszystkie_pozycje_korekty', 0, 'BOOLEAN', _ShowAllCorrLines, IF(@session.globals.Owner='PBUCH', TRUE, FALSE));  
	
		-- IF _ShowAllCorrLines THEN
			set _HavingSQL = '';
		-- ELSE	
			CALL _IReg_Get('Wydruki', 'Having_pozycji_wydruku_korekty', 0, 'STRING', _HavingSQL, 
			' HAVING idnvat<>idnvat_jest or cenabrt<>cenabrt_jest or wartbrt_jest<>wartbrt or pkwiu_bylo <> pkwiu_jest or wartnetWal_jest<>wartnetWal or towrnazwa_jest<>towrnazwa_bylo ');  
		-- END IF;	
		
		set _OrderBySQL	= '';	
		CALL _IReg_Get('Wydruki\FV', 'Sortowanie pozycji dokumentu FV', 0, 'STRING', _OrderBySQL, 'P.Lp');  
		-- TEMPORARY
		SET _SQLText =  
		'CREATE TEMPORARY TABLE `t_oper_poz`    
		SELECT P.GUID,
			T.NazwaUProducenta, N.waluta, P.Lp, W.Symbol AS WalutaStr,
			P.kurs as kurs_jest, P2.towrsymb, P2.kurs, P.oplata_produktowa, 
			P.towrnazwa AS towrnazwa_jest,  P2.towrnazwa AS towrnazwa, 
			P2.idntowr, P2.wspolplatnosc, 
			IFNULL((SELECT 
			O.cenanet from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1), P2.cenanet) AS cenanet, 
			IFNULL((SELECT 
			O.Rabat from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1), P2.Rabat) As Rabat, 
			IFNULL((SELECT 
			O.idnVat from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1)+(select zerod from zero limit 1), P2.idnVat+(select zerod from zero limit 1)) As idnVat, 
			P2.Ilosc + 
			  IFNULL((SELECT 
			  sum(O.ilosc*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As Ilosc,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */
			  P.ilosc + P2.ilosc + 
			  IFNULL((SELECT 
			  sum(O.ilosc*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As Ilosc_jest,   /* stan po korekcie */

			  (P.wartvat + (P2.wartvat + 
			  IFNULL((SELECT sum(O.wartvat*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0))) as wartvat_jest,  
			  (P.wartnet + (P2.wartnet + 
			  IFNULL((SELECT sum(O.wartnet*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0))) as wartnet_jest,  

			  (P2.wartbrt) as wartbrt, /*  P2.cenabrt as cenabrt, to nie uwzglednialo kolejnych korekt */
			  IFNULL((SELECT O.cenabrt FROM oppo O FORCE INDEX (guidkorpo) 
				WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65, 66 ,70)) AND O.idn < P.Idn 
						ORDER BY idn DESC LIMIT 1 ), P2.cenabrt) AS cenabrt,
			  (P.wartbrt + P2.wartbrt) as wartbrt_jest, P.cenabrt as cenabrt_jest, 

			  IFNULL((SELECT 
			  O.CenaNetWalzRab from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			  ORDER BY idn desc LIMIT 1), P2.CenaNetWalzRab) As CenaNetWalzRab, 
			  P.CenaNetWalzRab as CenaNetWalzRab_jest, 

			  P2.wartvat + IFNULL((SELECT 
			  sum(O.wartvat*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartvat,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P2.wartnet + IFNULL((SELECT sum(O.wartnet*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartnet,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P2.wartnetWal +  IFNULL((SELECT sum(O.wartnetWal*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartnetWal,   /* oryginał (faktura poczatkowa) + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P.wartnetWal + P2.wartnetWal + 
			  IFNULL((SELECT 
			  sum(O.wartnetWal*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0) As wartnetWal_jest, 

			  P2.iloscdo As IloscDo, 
			  IF(J.Nazwa = '''', '''', J.Nazwa) As Jednostka, J.precyzja as JednostkaPrecyzja, 
			  P2.idnvat AS idnvat_bylo, P2.grupuj, P.GUIDKorPO, T.treenode, 
			  T.symbol, T.sww, T.symboludost, T.SymbolProducenta, 
			  T.dataprodukcji, T.nazwa_segment3, T.wyroznik,

			  IFNULL((SELECT O.uwagi FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.uwagi) AS uwagi_bylo, 
			  IFNULL((SELECT O.uwagi2 FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.uwagi2) AS uwagi2_bylo, 
			  IFNULL((SELECT O.pkwiu FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.pkwiu) AS pkwiu_bylo, 
			  P.uwagi AS uwagi_jest, P.uwagi2 AS uwagi2_jest, P.pkwiu AS pkwiu_jest, P.pkwiu, 

			  P2.towrnazwa AS towrnazwa_bylo, 

			  P.cenanet as cenanet_jest, 
			  P.rabat as rabat_jest, P.idnvat+(select zerod from zero limit 1) as idnvat_jest, 

			  (if(N2.rodzaj in (10, 11) ,N2.nrdokmag, N2.nrdokfin))  as NrdokfinDocKor, 

			  LEFT(IFNULL((SELECT group_concat(distinct NK.NrDokFin) from oppo##rok## O,opng##rok## NK   
			  where NK.GUID=O.idnoper and O.GUIDKorPo = P.GUIDKorPo and 
			  (O.idn<P.Idn) and (O.ilosc<>0) and not(O.rodzaj in (65,66,70)) ),''''),100) as DotychczasoweKorekty, 


			  (N2.datawystaw)  as DataWystawDocKor, N2.rodzaj as RodzajDocKor, 
			  
			   (select IFNULL(zm.nrzamwkontr, o.info) from  oppo o 
						left join zmpo udp ON  o.guidzm=udp.guid 
						left join zmng zm ON udp.idnng=zm.guid
							where P.guidkorpo = o.guid )  AS nrzamwkontr,
							
				(SELECT IFNULL(udp.lp, o.nrseryjny) FROM  oppo o 
					LEFT JOIN zmpo udp ON  o.guidzm=udp.guid 
						LEFT JOIN zmng zm ON udp.idnng=zm.guid
							WHERE P.guidkorpo = o.guid )  AS nrpozycji_zamwkontr, -- BuyerLineItemNum,			
											
				-- cast(IFNULL(zn.datawystaw, N.datawystaw) as char) as datazamowienia, 
			   P.datawystaw as datawystaw_pozycji, 
			   if(P.idnoper<>P.idnoperfin, (select NG.nrdokmag from opng NG where NG.guid=P.idnoper), N.nrdokmag) as nrdokmag, 
			   ifnull((select symbol_edi from oferty  WHERE  N.kontrGUID=oferty.kontrguid and P.idntowr = oferty.idntowr ), 
					   (select symbol_edi from oferty  WHERE  K.grupaGUID=oferty.kontrguid and P.idntowr = oferty.idntowr))   as oferty_symbol_edi, 
			   J.EDI_index, 
			  
			   P.ilosc AS ilosc_delta, P.wartvat AS wartvat_delta, P.wartnet AS wartnet_delta 
			  
			  FROM opng N 
			  INNER JOIN oppo P ON P.idnoper=N.GUID 
			  LEFT JOIN oppo##rok## P2 ON P.GUIDKorPo = P2.GUID 
			  LEFT JOIN opng N2 ON P2.idnoperFin = N2.GUID 
			  LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
			  LEFT JOIN Jednostki J ON J.idn = P.jednostka 
			  LEFT JOIN waluty W ON W.idn = N.waluta 
			  # dla korekt to nie ma sensu: LEFT JOIN zmpo zp ON zp.GUID = P.GUIDzm 
			  # dla korekt to nie ma sensu: LEFT JOIN zmng zn ON zn.GUID = zp.IdnNG 
			  LEFT JOIN kontrah K ON K.GUID = N.kontrGUID 

			  WHERE N.GUID = ''##where##'' and P.idnoper=N.GUID and T.opakowanie_zwrotne=0 

			   ##having## 
			  ORDER BY ##order## ;
			  ';
	
		set _RokKorekty = 0;
		select RokKorekty from t_oper_ng into _RokKorekty;
	
		set  _RokKorektyStr = if(_RokKorekty > 1900, _varSTR(_RokKorekty), '');
	
		SET _SQLText = REPLACE(_SQLText, '#CSpKF#', CSpKF);
		SET _SQLText = REPLACE(_SQLText, '#CSpKR#', CSpKR);
		SET _SQLText = REPLACE(_SQLText, '##rok##', _RokKorektyStr);
		SET _SQLText = REPLACE(_SQLText, '##having##', _HavingSQL);
		SET _SQLText = REPLACE(_SQLText, '##order##', _OrderBySQL);
		SET _SQLText = REPLACE(_SQLText, '##where##', _RecGUID);
		
		SET @cor_SQLText = _SQLText;		
		CALL _ExecuteCmd(_SQLText, @Error);
		
	ELSE
		CREATE TEMPORARY TABLE `t_oper_poz`
		select P.GUID, P.lp, P.TowrNazwa, P.TowrSymb, P.ilosc, P.wartnet, P.wartvat, P.idnvat, P.guidkorpo, P.PKWIU,
			T.kod_kreskowy, -- IFNULL(concat(zp.lp," "),"1") as zplp, 
            J.EDI_index, K.GLN, 
           -- 25570 dla korekt (rodzaj in CSpKF, CSpKR) trzeba pobrać nrzamwkontr z faktury oryginalnej (korygowanej)
            IFNULL(zn.nrzamwkontr, P.info) AS nrzamwkontr, 
			IFNULL(zp.lp, P.nrseryjny) AS nrpozycji_zamwkontr, -- BuyerLineItemNum
			
            if(P.idnoper<>P.idnoperfin, (select NG.nrdokmag from opng NG where NG.guid=P.idnoper), N.nrdokmag) as nrdokmag, 
            P.datawystaw as datawystaw_pozycji -- , //np. data wystawienia wz <> od daty wyst. FV
            -- cast(IFNULL(zn.datawystaw,N.datawystaw) as char) as datazamowienia 
            from opng N 
            LEFT JOIN oppo P ON N.GUID = P.idnoper 
            LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
            LEFT JOIN zmpo zp ON zp.GUID = P.GUIDzm 
            LEFT JOIN zmng zn ON zn.GUID = zp.IdnNG 
            LEFT JOIN Jednostki J ON J.idn = P.jednostka 
            LEFT JOIN kontrah K ON K.GUID = N.kontrGUID 
            where P.idnoper = _RecGUID 
            ORDER BY P.lp ;
	END IF;
	
	SELECT 
		count(*) 
	from 
		t_oper_poz
	INTO
		_IlePoz;
	
	SELECT 
		IFNULL(GROUP_CONCAT(DISTINCT nrzamwkontr), '') AS PurchaseOrderNumber 
	FROM   
		`t_oper_poz`
	INTO _PurchaseOrderNumber;
	
	/* 
	 - <Invoice> 
	     + <InvoiceHeader> 
	     + <InvoiceDetail> 
	     + <InvoiceSummary> 
	   </Invoice> 		
	*/	
	
		
	SET @invoice.to.EDI.Content = '';
	
	-- SET @invoice.to.EDI.Content = '<?xml version="1.0" encoding="UTF-8" ?>\n';
	
	/* 'invoice.to.EDI.STANPOL.wrap' :
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:StandardBusinessDocument xmlns:sh="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.unece.org/cefact/namespaces/StandardBusinessDocumentHeader http://www.gdsregistry.org/2.3/schemas/sbdh/StandardBusinessDocumentHeader.xsd">\n');
	

	-- naglowek dokumentu
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:StandardBusinessDocumentHeader>\n');
			
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:HeaderVersion>1.0</sh:HeaderVersion>\n');
				-- nadawca: Stanpol
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Sender>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Identifier Authority="EAN.UCC">');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  '1234567890123');   -- GLN z konf?
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Identifier>\n');					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Sender>\n');
				-- odbiorca: DISTRIBUTION CASINO France (symbol: CASINO)  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Receiver>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Identifier Authority="EAN.UCC">');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '0987654321098');    -- GLN Casino?
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Identifier>\n');					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:Receiver>\n');
	
			    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:DocumentIdentification>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Standard>EAN.UCC</sh:Standard>\n');
	                SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Standard>2.3</sh:Standard>\n'); 			
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:InstanceIdentifier>'); 			
					  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, UUID());  -- Identifiant unique d'Ă©change
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:InstanceIdentifier>\n'); 			
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:Type>Invoice</sh:Type>\n');
					-- <sh:CreationDateAndTime>2003-05-09T00:31:52Z</sh:CreationDateAndTime> -- YYYY-MM-DDTHH:MN:SS+HH:MN
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<sh:CreationDateAndTime>'); 			
					  SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, DATE_FORMAT(NOW(), '%Y-%m-%dT%T'));
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:CreationDateAndTime>\n'); 								
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:DocumentIdentification>\n');
				
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:StandardBusinessDocumentHeader>\n');	
*/	
	-- teraz tutaj ds:Signature, a w niej xades:QualifyingProperties  i eanucc:message

	/* teraz powinien byc albo eanucc:message -> pay:invoice  albo od razu pay:invoice   */
	-- <pay:invoice creationDateTime="2004-04-05T11:00:00.000" documentStatus="ORIGINAL" xsi:schemaLocation="urn:ean.ucc:2 ../Schemas/InvoiceProxy.xsd">
	
	/* w 1. kroku generować tylko <eanucc:message>, potem podpisać (trafi on do <ds:Object>), potem do podpisanego dolaczyc naglowek 
	sh:StandardBusinessDocumentHeader, a calosc opakować w sh:StandardBusinessDocument
	*/  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ds:Object xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="GS1_XML">');
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<eanucc:message xmlns:eanucc="urn:ean.ucc:2" xmlns:pay="urn:ean.ucc:pay:2" xmlns:fr="urn:gs1fr:pay:fr:1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:ean.ucc:2 http://xml.gs1.fr/schemas/InvoiceProxy.xsd urn:gs1fr:pay:fr:1 http://xml.gs1.fr/schemas/ean.ucc/pay/frInvoiceType/FrInvoiceTypeExtension.xsd">\n');  
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(1*4), '<entityIdentification>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(2*4), '<uniqueCreatorIdentification>');   			
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, CONCAT('MSG-', UUID()));  -- MSG-1366097148-516cfcfcb4f9e
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</uniqueCreatorIdentification>\n');
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(1*4), '</entityIdentification>\n');
		
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(1*4), '<eanucc:transaction>\n'); 
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(2*4), '<entityIdentification>\n'); 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(3*4), '<uniqueCreatorIdentification>');   
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, CONCAT('TRA-', UUID())); -- TRA-1366097148-516cfcfcb4f21
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</uniqueCreatorIdentification>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(2*4), '</entityIdentification>\n'); 
			
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(2*4), '<command>\n'); 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(3*4), '<eanucc:documentCommand>\n'); -- concat(@, SPACE(4), '')
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(4*4), '<documentCommandHeader type="ADD">\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(5*4), '<entityIdentification>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*4), '<uniqueCreatorIdentification>');   
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, CONCAT('CMD-', UUID())); -- CMD-1366097148-516cfcfcb4fe3
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</uniqueCreatorIdentification>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(5*4), '</entityIdentification>\n'); 
					/*
					<entityIdentification>
						<uniqueCreatorIdentification>CMD-912-54618595</uniqueCreatorIdentification>
						<contentOwner>
							<gln>8712345678913</gln>
						</contentOwner>
					</entityIdentification>
					*/
					
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(4*4), '</documentCommandHeader>\n'); 
					
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(4*4), '<documentCommandOperand>\n'); 
				
					/*
					   <pay:invoice>  - faktura
					*/
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(5*cSL), '<pay:invoice documentStatus="ADDITIONAL_TRANSMISSION">\n');	-- creationDateTime="2004-04-05T11:00:00.000": data utworzenia faktury, czy <pay:invoice> ?
					
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<invoiceIdentification>\n');	
							-- nr faktury
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<uniqueCreatorIdentification>'); -- Numéro de la facture			
								 SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNumber);
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</uniqueCreatorIdentification>\n'); 						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</invoiceIdentification>\n');	
						-- waluta (invoiceCurrency)
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<invoiceCurrency>\n');	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<currencyISOCode>'); 			
								 SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _CurrencyCoded);  -- text(3) np. EUR
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</currencyISOCode>\n'); 								
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</invoiceCurrency>\n');	
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<invoiceType>');	
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'INVOICE');				-- CREDIT_NOTE, INVOICE
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</invoiceType>\n');
						
						-- RSTZTMGPresentRep.ExportToXML
						
						-- buyer
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<buyer>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<partyIdentification>\n');
							/*	<partyIdentification>
								  <gln>8812345678903</gln>
								</partyIdentification>  */
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<gln>');	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '3020115110000');		-- 'GLN_nabywcy'		 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</gln>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</partyIdentification>\n');	
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</buyer>\n');
						
						-- seller
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<seller>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<partyIdentification>\n');
								/*	<partyIdentification>
								  <gln>8712345678913</gln>
								</partyIdentification>  */
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<gln>');	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '5909000650');	-- RegistryInt.GetRegIntValueString('GLN_Firmy', '', '');			
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</gln>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</partyIdentification>\n');		
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</seller>\n');
						
						-- orderedBy (analogicznie do <seller>)
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<orderedBy>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<partyIdentification>\n');
							/*	<partyIdentification>
								  <gln>8812345678903</gln>
								</partyIdentification>  */
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<gln>');	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '3020115110000');		-- 'GLN_nabywcy'		 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</gln>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</partyIdentification>\n');	
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</orderedBy>\n');
						
						
						/*	invoiceTotals
						parametr baseAmount   - kwota netto
						totalInvoiceAmount    - kwota brutto
						totalLineAmountInclusiveAllowancesCharges  - kwota netto po zwieksz/zmniejsz.
						totalTaxAmount        - kwota podatku
						taxSubTotal  -- 1..n  */
								
							/*
							<NetValue>		- wartosc netto faktury
							<GrossValue>    - wartosc brutto faktury
							<TaxValue>      - wart. podatku VAT
							<TotalAmountPayable>  - kwota do zapÔˇty
							<TotalTaxAmount>  - wart. podatku faktury
							<TotalAmountMinusDiscount> - wartosc brutto faktury  */
										 
							
							SET _InvoiceNetAmount = 0.0; 
							SET _InvoiceTaxAmount = 0.0;  
							SET _InvoiceGrossAmount = 0.0; 
							
							SELECT 
								IFNULL(SUM(netto), 0), IFNULL(SUM(vat), 0), IFNULL(SUM(brutto), 0) 
							FROM 
								opng_vat 
							WHERE 
								idnoper = _RecGUID
							INTO _InvoiceNetAmount, _InvoiceTaxAmount, _InvoiceGrossAmount;
					
								
								
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<invoiceTotals baseAmount="', ROUND(_InvoiceNetAmount, 2), '">\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<totalInvoiceAmount>');   -- wartosc brutto faktury					
												SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceGrossAmount, 2));					
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</totalInvoiceAmount>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<totalLineAmountInclusiveAllowancesCharges>');   -- kwota netto po zwieksz/zmniejsz.
												SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceNetAmount, 2));					
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</totalLineAmountInclusiveAllowancesCharges>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<TotalTaxAmount>');		-- wartosc podatku	VAT				
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceTaxAmount, 2));								
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalTaxAmount>\n');	

						/*  1..n
							taxSubTotal
								dutyTaxFeeType  VALUE_ADDED_TAX
								taxableAmount   netto
								taxAmount       kwota podatku
								taxPercentage   procent podatku VAT
						*/		
													
							BEGIN	-- tabelka pozycji vat
								DECLARE _SummaryIdVat Integer;
								DECLARE _done BOOL DEFAULT FALSE;
								DECLARE  _SummaryTaxPercent, _SummaryTaxTaxableAmount, _SummaryTaxTaxAmount  DOUBLE;
								
								DECLARE _v_proc CURSOR FOR			
									select  
										IdVat, netto, vat
									FROM 
										opng_vat 
									WHERE 
										idnoper = _RecGUID;
									
							
								DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;	
								
								OPEN _v_proc;	
								loop1: LOOP
									FETCH _v_proc INTO
										_SummaryIdVat, _SummaryTaxTaxableAmount, _SummaryTaxTaxAmount	;
									IF _done THEN
											LEAVE loop1;
									ELSE
										SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<taxSubTotal>\n');																				
											-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<dutyTaxFeeType>', IF(_SummaryIdVat = cVatZw, 'NON_VALUE_ADDED_TAX', 'VALUE_ADDED_TAX') , '</dutyTaxFeeType>\n'); 
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<dutyTaxFeeType>VALUE_ADDED_TAX</dutyTaxFeeType>\n');
											
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<TaxableAmount>', ROUND(_SummaryTaxTaxableAmount, 2), '</TaxableAmount>\n'); -- netto
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<TaxAmount>', ROUND(_SummaryTaxTaxAmount, 2), '</TaxAmount>\n');          -- podatek
											
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<taxPercentage>');
											select 	ifnull((100 * value), 0) from v_erp_vat where ID = _SummaryIdVat INTO _SummaryTaxPercent;
												SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_SummaryTaxPercent, 2)); 								
											SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</taxPercentage>\n');
																														
										SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</taxSubTotal>\n');
									END IF;
								END LOOP;
								CLOSE _v_proc;											
							END;
									
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</invoiceTotals>\n');
						
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<paymentTerms paymentTermsType="FIXED_DATE" paymentTermsEvent="DATE_OF_INVOICE">\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<netPayment>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<PaymentTimePeriod>\n');
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(9*cSL), '<date>');					
										SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceDueDate);	 -- data platnosci 
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</date>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '</PaymentTimePeriod>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</netPayment>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</paymentTerms>\n');
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<orderIdentification>\n');  
						    -- <uniqueCreatorIdentification>103057916</uniqueCreatorIdentification>  -- -- NumĂ©ro de la commande  - nr zamowienia?
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<uniqueCreatorIdentification>', '123', '</uniqueCreatorIdentification>\n');
						    
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</orderIdentification>\n');
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '<extension>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '<fr:frInvoiceTypeExtension>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(8*cSL), '<frInvoiceType>GOODS_INVOICE</frInvoiceType>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(7*cSL), '</fr:frInvoiceTypeExtension>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(6*cSL), '</extension>\n');
						
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(5*cSL), '</pay:invoice>\n');	
				 SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(4*4), '</documentCommandOperand>\n'); 						
			   SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(3*4), '</eanucc:documentCommand>\n'); 			
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(2*4), '</command>\n'); 
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, SPACE(1*4), '</eanucc:transaction>\n');  
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</eanucc:message></ds:Object>\n');		
 -- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</sh:StandardBusinessDocument>');
  SET _RepContent = @invoice.to.EDI.Content;
	
  LEAVE SPROC;		
  /* DOTAD */	
		
			
END;  
END IF; 	-- _MODE = 'invoice.to.EDI.STANPOL.create'

IF _MODE = 'invoice.to.EDI.get.content' THEN
-- BEGIN
    SET NAMES utf8;	
	SET @invoice.to.EDI.Content = '';
	
	
	SET _OwnerMode = 'invoice.to.EDI.#owner#.create';
	SET _OwnerMode = REPLACE(_OwnerMode, '#owner#', _GetAppOwner());
	SET @_OwnerMode = _OwnerMode;
	
	-- CALL ht_EDI_tools('invoice.to.EDI.relacom.create', _RecGUID, @invoice.to.EDI.Content);
	CALL ht_EDI_tools(_OwnerMode, _RecGUID, @invoice.to.EDI.Content);
	
	DROP TEMPORARY TABLE IF EXISTS `t_to_edi_content`;
	CREATE TEMPORARY TABLE `t_to_edi_content` (
		Content LONGBLOB -- CHARACTER SET UTF8		
	);
	
	-- w warstwie aplikacji do tresci XML trafia zwracany "_RepContent"
	INSERT INTO `t_to_edi_content` SELECT @invoice.to.EDI.Content;
	SELECT Content AS _RepContent, @invoice.to.EDI.Content FROM `t_to_edi_content`;
	-- DROP TEMPORARY TABLE IF EXISTS `t_to_edi_content`;
END IF; 	-- _MODE = 'invoice.to.EDI.get.content'
	
	
IF _MODE = 'invoice.to.EDI.relacom.create.LineItem' THEN
BEGIN		
	DECLARE _TaxPercent DOUBLE;
	DECLARE _CorrNote, _CorrType VARCHAR(50);
   
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceItemDetail>\n');  -- odtad
	-- 2 glowne sekcje: InvoiceBaseItemDetail i InvoicePricingDetail	
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceBaseItemDetail>\n');
		-- 4 sekcje: LineItemNum, ItemIdentifiers, TotalQuantity, LineItemReferences
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemNum>\n');
			/*<BuyerLineItemNum>000010</BuyerLineItemNum>
			<SellerLineItemNum> 000100</SellerLineItemNum>*/
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<BuyerLineItemNum>');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, LPAD(IFNULL(@EDI_nrpozycji_zamwkontr, 0), 6, 0)); -- nrpozycji_zamwkontr
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</BuyerLineItemNum>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<SellerLineItemNum>');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, LPAD(IFNULL(@EDI_LP, 0), 6, 0));
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</SellerLineItemNum>\n');	
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</LineItemNum>\n');	

			-- dla korekt - pole z typem linii faktury korygującej		
			-- @EDI_LineItemType
			IF @invoice.to.EDI_Korekta THEN				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemType>\n');				
				IF @EDI_LineItemType = ''  THEN -- linia "różnicowa"
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemTypeCoded>Item</LineItemTypeCoded>\n');				
				ELSE
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemTypeCoded>Other</LineItemTypeCoded>\n');				
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemTypeCodedOther>', @EDI_LineItemType, '</LineItemTypeCodedOther>\n');				
				END IF;				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</LineItemType>\n');				
			END IF;
			
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ItemIdentifiers>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartNumbers>\n');
				
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<SellerPartNumber>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartNum>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartID>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, IFNULL(@EDI_SellerPartID, 'B.D.')); 	-- -- towrsymb		
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartID>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartNum>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</SellerPartNumber>\n');
					-- opcjonalnie
					/* if (Length(aCdsPo.FieldByName('oferty_symbol_edi').AsString)>0) then  // <- oferty.symbol_edi
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<BuyerPartNumber>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartNum>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartID>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _BuyerPartID); 	-- _BuyerPartID =  oferty_symbol_edi
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartID>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartNum>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</BuyerPartNumber>\n');
					*/
					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartNumbers>\n');	
				-- <ItemDescription>Item description</ItemDescription>  _ItemDescription
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ItemDescription>', IFNULL(@EDI_ItemDescription, 'B.D.'), '</ItemDescription>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ItemIdentifiers>\n');	
		
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalQuantity>\n');
			-- tutaj jestesmy z uzupelnianiem (ta sekcja)
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Quantity>\n');
					/*<QuantityValue>1.000</QuantityValue>
					<UnitOfMeasurement>
						<UOMCoded>EA</UOMCoded>
					</UnitOfMeasurement> */
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<QuantityValue>');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(IFNULL(@EDI_Quantity, 0), 3));
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</QuantityValue>\n');	
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<UnitOfMeasurement>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<UOMCoded>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  IFNULL(@EDI_UoM, ''));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</UOMCoded>\n');	
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</UnitOfMeasurement>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Quantity>\n');	
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalQuantity>\n');	
		
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LineItemReferences>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceReferences>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderReference>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderNumber>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Reference>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RefNum>');
									--  nr zamowienia
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, IFNULL(@EDI_nrzamwkontr, ''));
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RefNum>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Reference>\n');	
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderNumber>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderLineItemNumber>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, LPAD(IFNULL(@EDI_nrpozycji_zamwkontr, 0), 6, 0));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderLineItemNumber>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderReference>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceReferences>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</LineItemReferences>\n');						
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceBaseItemDetail>\n');	
		
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoicePricingDetail>\n'); 
		-- 4 sekcje: ListOfPrice, Tax, TotalValue, InvoiceCurrencyTotalValue
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfPrice>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Price>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<UnitPrice>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<UnitPriceValue>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, ROUND(IFNULL(@EDI_CenaNet, 0), 2)); -- IFNULL(@EDI_CenaNet, 0));  --  ROUND(IFNULL(@EDI_WartNet / @EDI_Quantity, 0), 2)  --  NULL gdy _Qty = 0  
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</UnitPriceValue>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</UnitPrice>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Price>\n');	
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfPrice>\n');	
			
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Tax>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxFunctionQualifierCoded>Tax</TaxFunctionQualifierCoded>\n'); 
			
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxCategoryCoded>');
				IF @EDI_IdnVAT = cVatZw THEN
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'ExemptFromTax');
				ELSE
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'StandardRate');
				END IF;
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxCategoryCoded>\n');
			
				IF @EDI_IdnVAT = cVatZw THEN
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ReasonTaxExemptCoded>Other</ReasonTaxExemptCoded>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ReasonTaxExemptCodedOther>', IFNULL(@EDI_PKWIU, ''), '</ReasonTaxExemptCodedOther>\n');
				END IF;
									
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxTypeCoded>ValueAddedTax</TaxTypeCoded>\n'); 	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxPercent>');							
					select 	ifnull((100 * value), 0) from v_erp_vat where ID = @EDI_IdnVAT INTO _TaxPercent;
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(IFNULL(_TaxPercent, 0), 2)); 							
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxPercent>\n');
				-- <TaxPaymentMethodCoded>SelfAssess</TaxPaymentMethodCoded>  nie ma tego pola w specyfikacji							
				-- <TaxAmount>890.16</TaxAmount>
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxAmount>');	
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, ROUND(IFNULL(@EDI_WartVat, 0), 2));
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxAmount>\n');								
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Tax>\n');	
								
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalValue>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
				-- <MonetaryAmount>4046.15</MonetaryAmount>
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, ROUND(IFNULL(@EDI_WartNet, 0), 2));  -- = UnitPrice * Qty
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');	
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalValue>\n');	
		
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceCurrencyTotalValue>\n');
				-- kopia sekcji <MonetaryValue> z <TotalValue> (gdy waluta PLN)
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');  
				-- <MonetaryAmount>4046.15</MonetaryAmount>
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, ROUND(IFNULL(@EDI_WartNet, 0), 2));  -- = UnitPrice * Qty
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceCurrencyTotalValue>\n');						
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoicePricingDetail>\n');		

		IF (@invoice.to.EDI_Korekta AND (@EDI_LineItemType = '') ) THEN		
		/* wstawiamy sekcję CorrectionReason 
		
		<ListOfStructuredNote>
                                        <StructuredNote>
                                                <GeneralNote>Quantity problem</GeneralNote>
                                                <TextTypeCoded>Other</TextTypeCoded>
                                                <TextTypeCodedOther>CorrectedQuantity</TextTypeCodedOther>
                                        </StructuredNote>
                                </ListOfStructuredNote>
		*/
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfStructuredNote>\n'); 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<StructuredNote>\n'); 
				
				SET _CorrNote = '';
				SET _CorrType = '';
				
				IF @EDI_Reason = 'Qty' THEN
					SET _CorrNote = 'Quantity problem';
					SET _CorrType = 'CorrectedQuantity';
				END IF;
				
				IF @EDI_Reason = 'Price' THEN
					SET _CorrNote = 'Price problem';
					SET _CorrType = 'CorrectedPrice';
				END IF;
				
				-- if idnvat_bylo <> idnvat_jest => CorrectedTax
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<GeneralNote>', _CorrNote, '</GeneralNote>\n'); 					
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TextTypeCoded>Other</TextTypeCoded>\n');				
					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TextTypeCodedOther>', _CorrType, '</TextTypeCodedOther>\n'); 
					
					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</StructuredNote>\n');		
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfStructuredNote>\n');		
		END IF;
		
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceItemDetail>\n');	
	
	SET _RepContent =  @invoice.to.EDI.Content;
END;  
END IF;	
	
/*------------------------------------------------------------------------------------------------------------------------------------------------------------------	
	'invoice.to.EDI.relacom.create'
		Wygenerowanie dokumentu XML z fakturą
		Parametry
		_MODE			Tryb pracy
		IN _RecGUID     GUID operacji z tab. opng
		
		_RepContent     Wygenerowana zawartość pliku XML
		
		CALL ht_EDI_tools('invoice.to.EDI.relacom.create', '{0A3F4841-12FB-422F-9509-547BBDE770C7}', @invoice.to.EDI.Content);
------------------------------------------------------------------------------------------------------------------------------------------------------------------*/		
IF _MODE = 'invoice.to.EDI.relacom.create' THEN
BEGIN	
	
	DECLARE  _LastDay  DATE;
	DECLARE  _IlePoz  INTEGER;	
	DECLARE  _UwagiNg VARCHAR(400);	
	
	SET CSpKF = 03;
	SET CSpKR = 04;
	SET cVatZw   =  3;
		
	SET _AllowSummary = 0;
	/* SET _TabStat = REPLACE('stat_prac_#Rok#', '#Rok#', _Rok);
	
	SET _SQLText =  'SELECT DATE(''#Rok#-12-31'') INTO @GUS_reports.Z06.create_LastDay';
	SET _SQLText = REPLACE(_SQLText, '#Rok#', _Rok);	
	SET @_SQLText = _SQLText;
	CALL _ExecuteCmd(_SQLText, @Error);	
	SET _LastDay = @GUS_reports.Z06.create_LastDay;
	*/
	
	DROP TEMPORARY TABLE IF EXISTS `t_oper_ng`;
	
	CREATE TEMPORARY TABLE `t_oper_ng`
		SELECT o.nrdokfin AS InvoiceNumber, o.rodzaj AS InvoiceType,
		    DATE_FORMAT(o.datawystaw, '%Y%m%dT%T') AS InvoiceIssueDate, -- o.*, 
			DATE_FORMAT(o.dataplatnosci, '%Y%m%dT%T') AS InvoiceDueDate,
			DATE_FORMAT(o.datasprzed, '%Y%m%dT%T') AS SalesDate,
			korektanrdokfin AS RelatedInvoiceNumber, o.rokkorekty AS RokKorekty,
			DATE_FORMAT(o.korektadata, '%Y%m%dT%T') AS RelatedInvoiceDate,
		    W.Symbol AS CurrencyCoded, 
			REPLACE(B.konto, ' ', '') AS BankAccountNumber,       -- B.NazwaBanku => BankName
			-- Replace(platnosc.nazwa,'%d',platnosc.dni) 
			P.rodzaj as rodzajplatnosci, IFNULL(Replace(P.nazwa, '%d', P.dni), 'BRAK DANYCH') AS PaymentTerm, -- IFNULL(CONCAT(P.nazwa, P.dni), 'BRAK DANYCH') AS PaymentTerm,
			IFNULL(P.nazwa, 'BRAK DANYCH') AS PaymentMean,
			K.GLN, K.analityka, K.reprezentant, K.UwagiNaFV, K.uwagi as uwagikontrah, 
            K.W_ulica, K.W_zipcode, K.W_nazwamiasta, K.odbierajacy as kontrodbierajacy, 
            K.EDI_Seller_CodeByBuyer, IFNULL(o.stawka_podat_dodatk, 0) AS AllowSummary,         -- w polu "stawka_podat_dodatk" mamy kwote rabatu
            K.w_TelKontaktowy, mi2.IDNKraju AS kraj 
            from opng o 
            LEFT join waluty W ON W.idn = o.waluta 
            LEFT JOIN platnosc P ON o.sposobplatn=P.idn 
            LEFT JOIN kontrah K ON K.GUID = o.kontrGUID 
			LEFT JOIN banki B ON B.idn = K.DomyslnyBank
            LEFT JOIN Miasta mi2 ON mi2.NazwaMiasta = K.W_NazwaMiasta 
            where o.guid = _RecGUID;
	
	SELECT 
		InvoiceNumber, InvoiceType, InvoiceIssueDate, CurrencyCoded, InvoiceDueDate, SalesDate, RelatedInvoiceNumber, RelatedInvoiceDate,
		BankAccountNumber, PaymentTerm, PaymentMean, AllowSummary		
	FROM 
		t_oper_ng
	INTO _InvoiceNumber, _InvoiceType, _InvoiceIssueDate, _CurrencyCoded, _InvoiceDueDate, _SalesDate, _RelatedInvoiceNumber, _RelatedInvoiceDate,
		_BankAccountNumber, _PaymentTerm, _PaymentMean, _AllowSummary;
	
	IF ISNULL(_BankAccountNumber) THEN
		CALL _IReg_Get('DaneFirmy', 'Bank', 0, 'STRING', _BankAccountNumber, '(brak danych)');    -- 'Owner'
	END IF;
	
	SET @invoice.to.EDI_Korekta = _InvoiceType IN (SELECT rodzaj FROM operdoc WHERE nazwa LIKE 'ST-%');  -- 3,4, 85, 90
	
	DROP TEMPORARY TABLE IF EXISTS `t_oper_poz`;	
	
	IF @invoice.to.EDI_Korekta THEN
	
		-- set _ShowAllCorrLines = FALSE:
		-- CALL _IReg_Get('Wydruki', 'Pokaz_wszystkie_pozycje_korekty', 0, 'BOOLEAN', _ShowAllCorrLines, IF(@session.globals.Owner='PBUCH', TRUE, FALSE));  
	
		-- IF _ShowAllCorrLines THEN
			set _HavingSQL = '';
		-- ELSE	
			CALL _IReg_Get('Wydruki', 'Having_pozycji_wydruku_korekty', 0, 'STRING', _HavingSQL, 
			' HAVING idnvat<>idnvat_jest or cenabrt<>cenabrt_jest or wartbrt_jest<>wartbrt or pkwiu_bylo <> pkwiu_jest or wartnetWal_jest<>wartnetWal or towrnazwa_jest<>towrnazwa_bylo ');  
		-- END IF;	
		
		set _OrderBySQL	= '';	
		CALL _IReg_Get('Wydruki\FV', 'Sortowanie pozycji dokumentu FV', 0, 'STRING', _OrderBySQL, 'P.Lp');  
		-- TEMPORARY
		SET _SQLText =  
		'CREATE TEMPORARY TABLE `t_oper_poz`    
		SELECT P.GUID,
			T.NazwaUProducenta, N.waluta, P.Lp, W.Symbol AS WalutaStr,
			P.kurs as kurs_jest, P2.towrsymb, P2.kurs, P.oplata_produktowa, 
			P.towrnazwa AS towrnazwa_jest,  P2.towrnazwa AS towrnazwa, 
			P2.idntowr, P2.wspolplatnosc, 
			IFNULL((SELECT 
			O.cenanet from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1), P2.cenanet) AS cenanet, 
			IFNULL((SELECT 
			O.Rabat from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1), P2.Rabat) As Rabat, 
			IFNULL((SELECT 
			O.idnVat from oppo##rok## O force index (guidkorpo) 
			where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			ORDER BY idn desc LIMIT 1)+(select zerod from zero limit 1), P2.idnVat+(select zerod from zero limit 1)) As idnVat, 
			P2.Ilosc + 
			  IFNULL((SELECT 
			  sum(O.ilosc*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As Ilosc,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */
			  P.ilosc + P2.ilosc + 
			  IFNULL((SELECT 
			  sum(O.ilosc*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As Ilosc_jest,   /* stan po korekcie */

			  (P.wartvat + (P2.wartvat + 
			  IFNULL((SELECT sum(O.wartvat*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0))) as wartvat_jest,  
			  (P.wartnet + (P2.wartnet + 
			  IFNULL((SELECT sum(O.wartnet*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0))) as wartnet_jest,  

			  (P2.wartbrt) as wartbrt, /*  P2.cenabrt as cenabrt, to nie uwzglednialo kolejnych korekt */
			  IFNULL((SELECT O.cenabrt FROM oppo O FORCE INDEX (guidkorpo) 
				WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65, 66 ,70)) AND O.idn < P.Idn 
						ORDER BY idn DESC LIMIT 1 ), P2.cenabrt) AS cenabrt,
			  (P.wartbrt + P2.wartbrt) as wartbrt_jest, P.cenabrt as cenabrt_jest, 

			  IFNULL((SELECT 
			  O.CenaNetWalzRab from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) and O.idn<P.Idn 
			  ORDER BY idn desc LIMIT 1), P2.CenaNetWalzRab) As CenaNetWalzRab, 
			  P.CenaNetWalzRab as CenaNetWalzRab_jest, 

			  P2.wartvat + IFNULL((SELECT 
			  sum(O.wartvat*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartvat,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P2.wartnet + IFNULL((SELECT sum(O.wartnet*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartnet,     /* faktura poczatkowa + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P2.wartnetWal +  IFNULL((SELECT sum(O.wartnetWal*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) 
			  ), 0) As wartnetWal,   /* oryginał (faktura poczatkowa) + zmiany (korekty) poprzedzające obecną korektę (oppo P) */

			  P.wartnetWal + P2.wartnetWal + 
			  IFNULL((SELECT 
			  sum(O.wartnetWal*(O.idn<P.Idn)) from oppo##rok## O force index (guidkorpo) 
			  where O.GUIDKorPo = P.GUIDKorPo and not(O.rodzaj in (65,66,70)) ), 0) As wartnetWal_jest, 

			  P2.iloscdo As IloscDo, 
			  IF(J.Nazwa = '''', '''', J.Nazwa) As Jednostka, J.precyzja as JednostkaPrecyzja, 
			  P2.idnvat AS idnvat_bylo, P2.grupuj, P.GUIDKorPO, T.treenode, 
			  T.symbol, T.sww, T.symboludost, T.SymbolProducenta, 
			  T.dataprodukcji, T.nazwa_segment3, T.wyroznik,

			  IFNULL((SELECT O.uwagi FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.uwagi) AS uwagi_bylo, 
			  IFNULL((SELECT O.uwagi2 FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.uwagi2) AS uwagi2_bylo, 
			  IFNULL((SELECT O.pkwiu FROM oppo O FORCE INDEX (guidkorpo) WHERE O.GUIDKorPo = P.GUIDKorPo AND NOT(O.rodzaj IN (65,66,70)) AND O.idn<P.Idn ORDER BY idn DESC LIMIT 1 ), P2.pkwiu) AS pkwiu_bylo, 
			  P.uwagi AS uwagi_jest, P.uwagi2 AS uwagi2_jest, P.pkwiu AS pkwiu_jest, P.pkwiu, 

			  P2.towrnazwa AS towrnazwa_bylo, 

			  P.cenanet as cenanet_jest, 
			  P.rabat as rabat_jest, P.idnvat+(select zerod from zero limit 1) as idnvat_jest, 

			  (if(N2.rodzaj in (10, 11) ,N2.nrdokmag, N2.nrdokfin))  as NrdokfinDocKor, 

			  LEFT(IFNULL((SELECT group_concat(distinct NK.NrDokFin) from oppo##rok## O,opng##rok## NK   
			  where NK.GUID=O.idnoper and O.GUIDKorPo = P.GUIDKorPo and 
			  (O.idn<P.Idn) and (O.ilosc<>0) and not(O.rodzaj in (65,66,70)) ),''''),100) as DotychczasoweKorekty, 


			  (N2.datawystaw)  as DataWystawDocKor, N2.rodzaj as RodzajDocKor, 
			  
			   (select IFNULL(zm.nrzamwkontr, o.info) from  oppo o 
						left join zmpo udp ON  o.guidzm=udp.guid 
						left join zmng zm ON udp.idnng=zm.guid
							where P.guidkorpo = o.guid )  AS nrzamwkontr,
							
				(SELECT IFNULL(udp.lp, o.nrseryjny) FROM  oppo o 
					LEFT JOIN zmpo udp ON  o.guidzm=udp.guid 
						LEFT JOIN zmng zm ON udp.idnng=zm.guid
							WHERE P.guidkorpo = o.guid )  AS nrpozycji_zamwkontr, -- BuyerLineItemNum,			
											
				-- cast(IFNULL(zn.datawystaw, N.datawystaw) as char) as datazamowienia, 
			   P.datawystaw as datawystaw_pozycji, 
			   if(P.idnoper<>P.idnoperfin, (select NG.nrdokmag from opng NG where NG.guid=P.idnoper), N.nrdokmag) as nrdokmag, 
			   ifnull((select symbol_edi from oferty  WHERE  N.kontrGUID=oferty.kontrguid and P.idntowr = oferty.idntowr ), 
					   (select symbol_edi from oferty  WHERE  K.grupaGUID=oferty.kontrguid and P.idntowr = oferty.idntowr))   as oferty_symbol_edi, 
			   J.EDI_index, 
			  
			   P.ilosc AS ilosc_delta, P.wartvat AS wartvat_delta, P.wartnet AS wartnet_delta 
			  
			  FROM opng N 
			  INNER JOIN oppo P ON P.idnoper=N.GUID 
			  LEFT JOIN oppo##rok## P2 ON P.GUIDKorPo = P2.GUID 
			  LEFT JOIN opng N2 ON P2.idnoperFin = N2.GUID 
			  LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
			  LEFT JOIN Jednostki J ON J.idn = P.jednostka 
			  LEFT JOIN waluty W ON W.idn = N.waluta 
			  # dla korekt to nie ma sensu: LEFT JOIN zmpo zp ON zp.GUID = P.GUIDzm 
			  # dla korekt to nie ma sensu: LEFT JOIN zmng zn ON zn.GUID = zp.IdnNG 
			  LEFT JOIN kontrah K ON K.GUID = N.kontrGUID 

			  WHERE N.GUID = ''##where##'' and P.idnoper=N.GUID and T.opakowanie_zwrotne=0 

			   ##having## 
			  ORDER BY ##order## ;
			  ';
	
		set _RokKorekty = 0;
		select RokKorekty from t_oper_ng into _RokKorekty;
	
		set  _RokKorektyStr = if(_RokKorekty > 1900, _varSTR(_RokKorekty), '');
	
		SET _SQLText = REPLACE(_SQLText, '#CSpKF#', CSpKF);
		SET _SQLText = REPLACE(_SQLText, '#CSpKR#', CSpKR);
		SET _SQLText = REPLACE(_SQLText, '##rok##', _RokKorektyStr);
		SET _SQLText = REPLACE(_SQLText, '##having##', _HavingSQL);
		SET _SQLText = REPLACE(_SQLText, '##order##', _OrderBySQL);
		SET _SQLText = REPLACE(_SQLText, '##where##', _RecGUID);
		
		SET @cor_SQLText = _SQLText;		
		CALL _ExecuteCmd(_SQLText, @Error);
		
	ELSE
		CREATE TEMPORARY TABLE `t_oper_poz`
		select P.GUID, P.lp, P.TowrNazwa, P.TowrSymb, P.ilosc, P.wartnet, P.wartvat, P.idnvat, P.guidkorpo, P.PKWIU,
			T.kod_kreskowy, -- IFNULL(concat(zp.lp," "),"1") as zplp, 
            J.EDI_index, K.GLN, 
           -- 25570 dla korekt (rodzaj in CSpKF, CSpKR) trzeba pobrać nrzamwkontr z faktury oryginalnej (korygowanej)
            IFNULL(zn.nrzamwkontr, P.info) AS nrzamwkontr, 
			IFNULL(zp.lp, P.nrseryjny) AS nrpozycji_zamwkontr, -- BuyerLineItemNum
			
            if(P.idnoper<>P.idnoperfin, (select NG.nrdokmag from opng NG where NG.guid=P.idnoper), N.nrdokmag) as nrdokmag, 
            P.datawystaw as datawystaw_pozycji -- , //np. data wystawienia wz <> od daty wyst. FV
            -- cast(IFNULL(zn.datawystaw,N.datawystaw) as char) as datazamowienia 
            from opng N 
            LEFT JOIN oppo P ON N.GUID = P.idnoper 
            LEFT JOIN TowrNg T ON T.GUID = P.idntowr 
            LEFT JOIN zmpo zp ON zp.GUID = P.GUIDzm 
            LEFT JOIN zmng zn ON zn.GUID = zp.IdnNG 
            LEFT JOIN Jednostki J ON J.idn = P.jednostka 
            LEFT JOIN kontrah K ON K.GUID = N.kontrGUID 
            where P.idnoper = _RecGUID 
            ORDER BY P.lp ;
	END IF;
	
	SELECT 
		count(*) 
	from 
		t_oper_poz
	INTO
		_IlePoz;
	
	SELECT 
		IFNULL(GROUP_CONCAT(DISTINCT nrzamwkontr), '') AS PurchaseOrderNumber 
	FROM   
		`t_oper_poz`
	INTO _PurchaseOrderNumber;
	
	/* 
	 - <Invoice> 
	     + <InvoiceHeader> 
	     + <InvoiceDetail> 
	     + <InvoiceSummary> 
	   </Invoice> 		
	*/	
	
	
	
	SET @invoice.to.EDI.Content = '';
	
	-- SET @invoice.to.EDI.Content = '<?xml version="1.0" encoding="UTF-8" ?>\n<?soxtype urn:x-commerceone:document:com:commerceone:XCBL35:XCBL35.sox$1.0?>\n<?import urn:x-commerceone:document:com:commerceone:XCBL35:XCBL35.sox$1.0?>\n';
	SET @invoice.to.EDI.Content = '<?soxtype urn:x-commerceone:document:com:commerceone:XCBL35:XCBL35.sox$1.0?>\n<?import urn:x-commerceone:document:com:commerceone:XCBL35:XCBL35.sox$1.0?>\n';
	
	
	
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Invoice>\n');
	    -- <InvoiceHeader> 
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceHeader>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceNumber>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Reference>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RefNum>');
					-- wstaw nr faktury  _InvoiceNumber
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceNumber);
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RefNum>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Reference>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceNumber>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceIssueDate>');
			-- data wyst. faktury
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceIssueDate);
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceIssueDate>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceReferences>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderReference>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderNumber>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Reference>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RefNum>');
								--  nr zamow referencyjnego  
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PurchaseOrderNumber);
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RefNum>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Reference>\n');										
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderNumber>\n');
					-- opcjonalnie SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PurchaseOrderDate>');
					-- data zamow. referencyjnego  aCdsPo.FieldByName('datazamowienia').AsString  
					-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderDate>\n');	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PurchaseOrderReference>\n');
				/*  sekcja warunkowa (faktura korygująca)	*/
				IF @invoice.to.EDI_Korekta THEN
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfRelatedInvoiceRef>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RelatedInvoiceRef>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RelatedInvoiceType>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceType>\n');
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceTypeCoded>');
									-- typ faktury korygowanej:  (DebitInvoice | CorrectedInvoice) Apro: u nas zawsze DebitInvoice (korekta do faktury, a nie korekta do korekty)
 									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'DebitInvoice');	  
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceTypeCoded>\n');	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceType>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RelatedInvoiceType>\n');
							--
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceNumber>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Reference>\n');
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RefNum>');
										-- nr faktury  korygwoanej
										SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _RelatedInvoiceNumber);
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RefNum>\n');
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<RefDate>');
										-- data faktury  korygwoanej
										SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _RelatedInvoiceDate);
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RefDate>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Reference>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceNumber>\n');
							--
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</RelatedInvoiceRef>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfRelatedInvoiceRef>\n');
				END IF;  -- IF _Korekta THEN				
				/*  koniec sekcji faktury koryg.	        */
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceReferences>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoicePurpose>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoicePurposeCoded>');
					-- rodzaj faktury: oryg. lub duplikat  (Original | Duplicate)
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'Original');	  -- Apro: na chwilę obecną (31.01.2011) - zawsze oryginał
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoicePurposeCoded>\n');	
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoicePurpose>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceType>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceTypeCoded>');
					-- typ faktury DebitInvoice | CorrectedInvoice
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, IF(@invoice.to.EDI_Korekta, 'CorrectedInvoice', 'DebitInvoice'));					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceTypeCoded>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceTypeCodedOther>');  
					-- tytul faktury  FAKTURA VAT | FAKTURA KORYGUJĄCA VAT | FAKTURA KOREKTA VAT
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, IF(@invoice.to.EDI_Korekta, 'FAKTURA KOREKTA VAT', 'Faktura VAT'));					
					-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, 'Faktura VAT');	  -- 						 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceTypeCodedOther>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceType>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceCurrency>\n');  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Currency>\n');  
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<CurrencyCoded>');
					-- waluta faktury  _CurrencyCoded
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _CurrencyCoded);
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</CurrencyCoded>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Currency>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceCurrency>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceLanguage>\n');  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Language>\n');  -- jezyk faktury
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LanguageCoded>Other</LanguageCoded>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<LanguageCodedOther>N/A</LanguageCodedOther>\n');					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Language>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceLanguage>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceMedium>\n');  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceMediumCoded>Electronically</InvoiceMediumCoded>\n'); -- nie ma tego pola w specyf. tech.
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceMedium>\n'); 
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceDates>\n');  
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceDueDate>');
					-- data platnosci faktury
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _InvoiceDueDate);	
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceDueDate>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfOtherInvoiceDates>\n');  
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfDateCoded>\n');  
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<DateCoded>\n');  
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Date>');
							-- data sprzedazy  datasprzed
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _SalesDate);	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Date>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<DateQualifier>\n');  
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<DateQualifierCoded>SalesDateAndOrTimeAndOrPeriod</DateQualifierCoded>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</DateQualifier>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</DateCoded>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfDateCoded>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfOtherInvoiceDates>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceDates>\n'); 
			
			-- <InvoiceParty>  // strony transakcji
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceParty>\n'); 
			    -- <BuyerParty> strona kupującego   - pobierać z danych
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<BuyerParty>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Party>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartyID>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>TPSA</Ident>\n'); 											
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartyID>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfIdentifier>\n'); 						
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>Other</AgencyCoded>\n'); 
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCodedOther>NIP</AgencyCodedOther>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>5260250995</Ident>\n');  -- NIP 	w bazie relacom: 5260250995										
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfIdentifier>\n'); 
						-- <NameAddress>		
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<NameAddress>\n'); 						
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Name1>Orange Polska S.A.</Name1>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Street>Al.Jerozolimskie 160</Street>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PostalCode>02-326</PostalCode>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<City>WARSZAWA</City>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Country>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<CountryCoded>PL</CountryCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Country>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</NameAddress>\n'); 						
						
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Party>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</BuyerParty>\n');
				-- </BuyerParty> koniec strony kupującego
				
				-- <SellerParty> strona sprzedajacego
				CALL _IReg_Get('DaneFirmy', 'NIP', 0, 'STRING', @DaneFirmy_NIP, 0); 
				SET @DaneFirmy_NIP = REPLACE(@DaneFirmy_NIP, '-', '');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<SellerParty>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Party>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartyID>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								CALL _IReg_Get('DaneFirmy', 'Nazwa_skrocona', 0, 'STRING', @DaneFirmy_NazwaSkr, '(brak danych)'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>');  -- wartosc stala nadana przez TP
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, @DaneFirmy_NazwaSkr);									
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Ident>\n'); 		
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartyID>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfIdentifier>\n'); 	
							-- NIP	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>Other</AgencyCoded>\n'); 
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCodedOther>NIP</AgencyCodedOther>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>');   -- NIP 		...DaneFirmy\NIP								
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, @DaneFirmy_NIP);									
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Ident>\n');  
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
							--  numer konta bankowego, _BankAccountNumber w Delphi: select ValueA from IReg where idpath like ''%Owner%'' and idkey=''Bank''
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>Other</AgencyCoded>\n'); 
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCodedOther>AccountNumber</AgencyCodedOther>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>');   -- jesli na kontrahencie ustawiono "domyślny bank", to tu jest wstawiane jego konto
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _BankAccountNumber);									
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Ident>\n');  
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfIdentifier>\n'); 
						-- <NameAddress>
						CALL _IReg_Get('DaneFirmy', 'Pelna_nazwa', '0', 'STRING', _PelnaNazwa, '(brak danych)');  -- _IReg_Get('Owner', 'Name', 0, 'STRING', _PelnaNazwa, '(brak danych)');  -- _IReg_Get('DaneFirmy', 'Pelna_nazwa', '0', 'STRING', _PelnaNazwa, '(brak danych)');
						CALL _IReg_Get('DaneFirmy', 'Kraj', 0, 'STRING', _Kraj, 'PL');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<NameAddress>\n'); 						
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Name1>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PelnaNazwa);	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Name1>\n');
							/* RegistryInt.GetRegIntValueString('Ulica', 'ul.', CINTREG_SUBPATH_DANEFIRMY) + ' '+
							   RegistryInt.GetRegIntValueString('Nr_domu', ' ', CINTREG_SUBPATH_DANEFIRMY);	*/						 
							CALL _IReg_Get('DaneFirmy', 'Ulica', 0, 'STRING', _Ulica, '(brak danych)');   
							CALL _IReg_Get('DaneFirmy', 'Nr_domu', 0, 'STRING', _NrDomu, '(brak danych)');  
							CALL _IReg_Get('DaneFirmy', 'Nr_lokalu', 0, 'STRING', _NrLok, '(brak danych)');  	
							CALL _IReg_Get('DaneFirmy', 'Miasto', 0, 'STRING', _Miasto, '(brak danych)');   
							CALL _IReg_Get('DaneFirmy', 'Kod_poczt', 0, 'STRING', _Kod_poczt, '(brak danych)');   
							SET _Adres = CONCAT(_Ulica, ' ', _NrDomu, '/', _NrLok);
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Street>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _Adres);	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Street>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PostalCode>');-- Kod_poczt	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _Kod_poczt);	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PostalCode>\n');  
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<City>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _Miasto);	
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</City>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Country>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<CountryCoded>');
									SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _Kraj);	
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</CountryCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Country>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</NameAddress>\n'); 						
						
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Party>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</SellerParty>\n');
				-- </SellerParty> koniec strony sprzedajacego
				
				-- <BillToParty> strona odbiorcy faktury				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<BillToParty>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Party>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PartyID>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Identifier>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Agency>\n'); 
								    SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AgencyCoded>AssignedByBuyerOrBuyersAgent</AgencyCoded>\n'); 
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Agency>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Ident>TPSA</Ident>\n'); 											
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Identifier>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PartyID>\n');
						
						-- <NameAddress>		
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<NameAddress>\n'); 						
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Name1>Orange Polska S.A.</Name1>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Street>Al.Jerozolimskie 160</Street>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PostalCode>02-326</PostalCode>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<City>WARSZAWA</City>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Country>\n');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<CountryCoded>PL</CountryCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Country>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</NameAddress>\n'); 												
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Party>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</BillToParty>\n');				
				-- </BillToParty> koniec strony odbiorcy faktury
				
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceParty>\n'); 
			
			-- <InvoicePaymentInstructions>
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoicePaymentInstructions>\n'); 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentInstructions>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentTerms>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentTerm>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentTermCoded>Other</PaymentTermCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentTermCodedOther>'); 
							-- warunki platnosci
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PaymentTerm);
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentTermCodedOther>\n'); 
							/*<PaymentTermCoded>Other</PaymentTermCoded>
							<PaymentTermCodedOther>NET30</PaymentTermCodedOther>*/
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentTerm>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentTerms>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentMethod>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentMeanCoded>Other</PaymentMeanCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<PaymentMeanCodedOther>'); 
							-- warunki platnosci
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, _PaymentTerm);   -- _PaymentMean
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentMeanCodedOther>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentMethod>\n'); 
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</PaymentInstructions>\n'); 
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoicePaymentInstructions>\n'); 
			-- </InvoicePaymentInstructions>
			
			
			
			SET _UwagiNg = '';
			select 
				IFNULL(LEFT(GROUP_CONCAT(replace(oppo.uwagi, '\r\n', ';')), 400), '') AS uwagi
			FROM oppo	
			WHERE idnoper = _RecGUID
			GROUP BY idnoper			
			INTO
				_UwagiNg;
			
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceHeaderNote>', _UwagiNg, '</InvoiceHeaderNote>\n'); 
			-- <InvoiceHeaderNote>Dotyczy lokalizacji : Poznań</InvoiceHeaderNote>  -- LEFT(GROUP_CONCAT(oppo.uwagi), 400)
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceHeader>\n');
		--  </InvoiceHeader> koniec sekcji nagłówka faktury
		
		 SET @EDI_header = @invoice.to.EDI.Content;
		
		IF _IlePoz > 0 THEN
			
			DROP TEMPORARY TABLE IF EXISTS `t_oper_poz_corr`;
			
			-- dla korekty - 3 linie dla kazdej pozycji faktury korygujacej
			CREATE TEMPORARY  TABLE `t_oper_poz_corr`
			(
			 lp integer not null default 0,
			 typ_linii varchar(50) not null default '',							-- wartości identyfikatora "LineItemTypeCodedOther" w sekcji "typ linii"
			 ilosc   double(16,4) not null default 0.0000,
			 wartnet double(16,4) not null default 0.0000,
			 wartvat double(16,4) not null default 0.0000,
			 cenanet double(16,4) not null default 0.0000,
			 reason varchar(10) not null default ''
			);  
			
			INSERT INTO t_oper_poz_corr (lp, TYP_LINII) VALUES (1, '');  -- 1.linia ("rożnica") nie ma identyfikatora "LineItemTypeCodedOther"  -- w HT: linia "Zmiana"
			INSERT INTO t_oper_poz_corr (lp, TYP_LINII) VALUES (2, 'Original');    -- w HT: linia "Bylo"
			INSERT INTO t_oper_poz_corr (lp, TYP_LINII) VALUES (3, 'Corrected');   -- w HT: linia "Jest"
			
			-- <InvoiceDetail> linie faktury 
			-- <ListOfInvoiceItemDetail>
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceDetail>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfInvoiceItemDetail>\n');	
		BEGIN
			DECLARE _done BOOL DEFAULT FALSE;
			DECLARE _lp, _IdnVAT, _kIdnVAT INTEGER;
			DECLARE _ItemDescription, _nrzamwkontr VARCHAR(150);
			DECLARE _nrpozycji_zamwkontr VARCHAR(250);
			DECLARE _PKWIU, _Reason VARCHAR(15);
			DECLARE _SellerPartID, _UoM, _GUIDKorPo VARCHAR(38);
			DECLARE _Quantity, _WartNet, _WartVat, _CenaNet, _TaxPercent DOUBLE;
			DECLARE _kQuantity, _kWartNet, _kWartVat DOUBLE;
			DECLARE _ilosc_delta, _wartvat_delta, _wartnet_delta,
					_ilosc_jest, _wartvat_jest, _wartnet_jest DOUBLE;
			-- DECLARE _done_corr BOOL:		
	
			DECLARE _c_proc CURSOR FOR			
				select  
					GUID, LP, TowrNazwa, TowrSymb, ilosc, EDI_index, wartnet, wartvat, idnvat,  nrzamwkontr, PKWIU, nrpozycji_zamwkontr  -- guidkorpo,
				from t_oper_poz;
				
			/* DECLARE _c_proc_corr CURSOR FOR			
				select  
					GUID, LP, TowrNazwa, TowrSymb, ilosc, EDI_index, wartnet, wartvat, idnvat, guidkorpo, nrzamwkontr, PKWIU
				from t_oper_poz;	*/
		
			DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;	
	
			OPEN _c_proc;	
			loop1: LOOP
				FETCH _c_proc INTO
						_PozGUID, _lp, _ItemDescription, _SellerPartID, _Quantity, _UoM, _WartNet, _WartVat,  _IdnVAT,  _nrzamwkontr, _PKWIU, _nrpozycji_zamwkontr;  -- _GUIDKorPo,
				IF _done THEN
						LEAVE loop1;
				ELSE	
										
					-- przepisz do zmiennych globanych i wywolaj gener. linii
						set @EDI_PozGUID = _PozGUID; -- _lp, _ItemDescription, _SellerPartID, _Quantity, _UoM, _WartNet, _WartVat,  _IdnVAT,  _nrzamwkontr, _PKWIU
						set @EDI_lp = _lp;
						set @EDI_nrpozycji_zamwkontr = _nrpozycji_zamwkontr;
						set @EDI_ItemDescription = _ItemDescription;
						set @EDI_SellerPartID = _SellerPartID;
						set @EDI_Quantity = _Quantity;
						set @EDI_UoM = _UoM;						
						set @EDI_WartNet = _WartNet;
						set @EDI_WartVat = _WartVat;
						set @EDI_IdnVAT = _IdnVAT;
						set @EDI_nrzamwkontr = _nrzamwkontr;
						set @EDI_PKWIU = _PKWIU;
						set @EDI_CenaNet = ROUND(IFNULL(@EDI_WartNet / @EDI_Quantity, 0), 2);
						
					   set @bylem='jo';
					   
					IF @invoice.to.EDI_Korekta THEN  -- czy korekta - to okresla naglowek
					BEGIN
						DECLARE _typ_linii varchar(50);
						DECLARE _done_corr BOOL DEFAULT FALSE;
						
						DECLARE _c_proc_corr CURSOR FOR			
							select  
								typ_linii, ilosc, wartnet, wartvat, cenanet, reason
							from 
								t_oper_poz_corr;
		
						DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done_corr = TRUE;	
		
						-- set @korekta =  _Korekta;
						-- w tej chwili w _Quantity, _WartNet, _WartVat mamy wartości do linii "original"
						update 
							t_oper_poz_corr
						set
							ilosc = _Quantity,
							wartnet = _WartNet,
							wartvat = _WartVat,
							cenanet = Round(ifnull(_WartNet/_Quantity, 0), 2)
						where 
							typ_linii	= 'Original' and lp = 2;   -- wystarczyłby warunek na 1 kolumnę  ;  linia "bylo"
							
						-- teraz pobieramy wartości do obu pozostałych linii ("roznica" (= *_delta), "ma być po korekcie" (= *_jest))
						
						select
							ilosc_delta, wartvat_delta, wartnet_delta,
							ilosc_jest, wartvat_jest, wartnet_jest
						from 
						    t_oper_poz
						where 
							guid = _PozGUID
						into _ilosc_delta, _wartvat_delta, _wartnet_delta,
							_ilosc_jest, _wartvat_jest, _wartnet_jest;
							
						update 
							t_oper_poz_corr
						set
							ilosc = _ilosc_jest,
							wartnet = _wartnet_jest,
							wartvat = _wartvat_jest,
							cenanet = Round(ifnull(_WartNet_jest/_ilosc_jest, ifnull(_WartNet/_Quantity, 0)), 2)  -- gdy dzielenie przez zero (zerowa ilosc po korekcie) to dostajemy nulla - wstawiamy tu cene "bylo" (bo cena sie nie zmienila)
						where 
							typ_linii	= 'Corrected' and lp = 3;	-- wystarczyłby warunek na 1 kolumnę	; linia "jest"
						
						-- 						linia roznicowa
						update 
							t_oper_poz_corr
						set
							ilosc = if(_ilosc_delta = 0, _ilosc_jest, _ilosc_delta),  -- jesli ilosc nie jest korygowana, to nie pokazujemy roznicy (=0) tylko tą niezmienioną wartosc 
							wartnet = _wartnet_delta,
							wartvat = _wartvat_delta,
							cenanet = Round
							(
							  ifnull(
							         if ( ( ( ifnull((_WartNet_jest/_ilosc_jest), (_WartNet/_Quantity)) - (_WartNet/_Quantity)) = 0), (_WartNet/_Quantity), 
  									            ((_WartNet_jest/_ilosc_jest) - (_WartNet/_Quantity))
									    ), 0
									),
							 2),  -- jesli cena nie jest korygowana, to nie pokazujemy roznicy (=0) tylko tą niezmienioną wartosc: (_WartNet/_Quantity) = oryginalna cena
							 reason = if(_ilosc_delta = 0, 'Price', 'Qty')
						where 
							lp = 1;			-- and  typ_linii	= ''   ; linia "zmiana"
						
						set @corr.cenanet_l = (_WartNet_jest/_ilosc_jest);
						set @corr.cenanet_m = (_WartNet/_Quantity);
						set @corr.cenanet = Round(ifnull((_WartNet_jest/_ilosc_jest) - (_WartNet/_Quantity), 0), 2);
						
						-- otwieramy kursor _c_proc_corr i wolamy generowanie linii	
						OPEN _c_proc_corr;
						loop_corr: LOOP
						
							FETCH _c_proc_corr INTO   -- typ_linii, ilosc, wartnet, wartvat
								_typ_linii, _Quantity, _WartNet, _WartVat, _CenaNet, _Reason;
								
							IF _done_corr THEN
								LEAVE loop_corr;
							ELSE
								set @EDI_LineItemType = _typ_linii;
								set @EDI_Quantity = _Quantity;
								set @EDI_WartNet = _WartNet;
								set @EDI_WartVat = _WartVat;
								set @EDI_CenaNet = _CenaNet;
								set @EDI_Reason = _Reason;

								CALL ht_EDI_tools('invoice.to.EDI.relacom.create.LineItem', _RecGUID, @invoice.to.EDI.Content);		
							END IF;
						
						END LOOP;
						CLOSE _c_proc_corr;
						
					END;						
					ELSE  -- faktura zwykla (nie korekta)  @EDI
					 -- przepisz do zmiennych globanych i wywolaj gener. linii
					/*	set @EDI_PozGUID = _PozGUID; -- _lp, _ItemDescription, _SellerPartID, _Quantity, _UoM, _WartNet, _WartVat,  _IdnVAT,  _nrzamwkontr, _PKWIU
						set @EDI_lp = _lp;
						set @EDI_ItemDescription = _ItemDescription;
						set @EDI_SellerPartID = _SellerPartID;
						set @EDI_Quantity = _Quantity;
						set @EDI_UoM = _UoM;						
						set @EDI_WartNet = _WartNet;
						set @EDI_WartVat = _WartVat;
						set @EDI_IdnVAT = _IdnVAT;
						set @EDI_nrzamwkontr = _nrzamwkontr;
						set @EDI_PKWIU = _PKWIU;
					*/
						-- <InvoiceItemDetail>	
						CALL ht_EDI_tools('invoice.to.EDI.relacom.create.LineItem', _RecGUID, @invoice.to.EDI.Content);
						-- </InvoiceItemDetail>	
					END IF;  -- IF _Korekta THEN  
										
					
				-- dotad
				END IF;		-- ELSE 
			END LOOP;
			CLOSE _c_proc;
						
		END;
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfInvoiceItemDetail>\n');
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceDetail>\n');
		
		END IF; -- IF _IlePoz > 0 THEN
		
		--  <InvoiceSummary>
		--				<InvoiceTotals>
		--				<ListOfTaxSummary>
		-- </InvoiceSummary>
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceSummary>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<InvoiceTotals>\n');
			/*
			<NetValue>		- wartosc netto faktury
			<GrossValue>    - wartosc brutto faktury
			<TaxValue>      - wart. podatku VAT
			<TotalAmountPayable>  - kwota do zapłaty
			<TotalTaxAmount>  - wart. podatku faktury
			<TotalAmountMinusDiscount> - wartosc brutto faktury
			 
			 wszystkie maja taka sama strukture:				
				<MonetaryValue>
					<MonetaryAmount>13228.94</MonetaryAmount>
				</MonetaryValue>				
			*/
			
			SET _InvoiceNetAmount = 0.0; 
			SET _InvoiceTaxAmount = 0.0;  
			SET _InvoiceGrossAmount = 0.0; 
			
			SELECT 
				IFNULL(SUM(netto), 0), IFNULL(SUM(vat), 0), IFNULL(SUM(brutto), 0) 
			FROM 
				opng_vat 
			WHERE 
				idnoper = _RecGUID
			INTO _InvoiceNetAmount, _InvoiceTaxAmount, _InvoiceGrossAmount;
	
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<NetValue>\n');   -- wartosc netto faktury
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceNetAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</NetValue>\n');
					
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<GrossValue>\n');  -- wartosc brutto faktury
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceGrossAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</GrossValue>\n');
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxValue>\n');				-- wartość podatku VAT faktury
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceTaxAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxValue>\n');
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalAmountPayable>\n');	-- kwota do zaplaty (wartosc brutto faktury)
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceGrossAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalAmountPayable>\n');
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalTaxAmount>\n');		-- ost. wartosc podatku
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceTaxAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalTaxAmount>\n');
				
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalAmountMinusDiscount>\n'); -- ost. kwota do zaplaty (wartosc brutto faktury)
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryValue>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_InvoiceGrossAmount, 2));
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryAmount>\n');
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n');
				SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalAmountMinusDiscount>\n');
				
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceTotals>\n');

			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ListOfTaxSummary>\n');	
			--	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxSummary>\n');
				
			BEGIN	
				DECLARE _SummaryIdVat Integer;
				DECLARE _done BOOL DEFAULT FALSE;
				DECLARE  _SummaryTaxPercent, _SummaryTaxTaxableAmount, _SummaryTaxTaxAmount  DOUBLE;
				
				DECLARE _v_proc CURSOR FOR			
					select  
						IdVat, netto, vat
					FROM 
						opng_vat 
					WHERE 
						idnoper = _RecGUID;
					
			
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET _done = TRUE;	
				
				OPEN _v_proc;	
				loop1: LOOP
					FETCH _v_proc INTO
						_SummaryIdVat, _SummaryTaxTaxableAmount, _SummaryTaxTaxAmount	;
					IF _done THEN
							LEAVE loop1;
					ELSE
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxSummary>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<Tax>\n');
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxFunctionQualifierCoded>Tax</TaxFunctionQualifierCoded>\n'); 
							-- <TaxCategoryCoded>StandardRate</TaxCategoryCoded>  StandardRate | ExemptFromTax
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxCategoryCoded>', IF(_SummaryIdVat = cVatZw, 'ExemptFromTax', 'StandardRate') , '</TaxCategoryCoded>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxTypeCoded>ValueAddedTax</TaxTypeCoded>\n');
							
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxPercent>');
							select 	ifnull((100 * value), 0) from v_erp_vat where ID = _SummaryIdVat INTO _SummaryTaxPercent;
								SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content,  ROUND(_SummaryTaxPercent, 2)); 								
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxPercent>\n');
							-- <TaxPaymentMethodCoded>SelfAssess</TaxPaymentMethodCoded> <- to jest w przykladowym pliku, ale nie ma specyfikacji
							
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxableAmount>', ROUND(_SummaryTaxTaxableAmount, 2), '</TaxableAmount>\n'); -- netto
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TaxAmount>', ROUND(_SummaryTaxTaxAmount, 2), '</TaxAmount>\n');          -- podatek
							
							-- <TaxAmountInTaxAccountingCurrency>16139.29</TaxAmountInTaxAccountingCurrency> dla faktur w walucie obcej
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Tax>\n');
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxSummary>\n');
					END IF;
				END LOOP;
				CLOSE _v_proc;
											
			END;
				-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TaxSummary>\n');
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</ListOfTaxSummary>\n');
			
			-- AllowOrChargeSummary
			-- upusty _AllowSummary
			IF _AllowSummary > 0 THEN
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AllowOrChargeSummary>\n'); 
				-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AllowOrChargeSummary>\n'); 
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<TotalAllowOrCharge>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AllowOrChargeIndicatorCoded>Allowance</AllowOrChargeIndicatorCoded>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<AllowanceOrChargeDescription>\n<AllowOrChgDesc>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<ServiceCoded>Allowance</ServiceCoded>\n'); 
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</AllowOrChgDesc>\n</AllowanceOrChargeDescription>\n'); 
						-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</AllowanceOrChargeDescription>\n');
						
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<SummaryAllowOrCharge>\n<MonetaryValue>\n'); 
							SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '<MonetaryAmount>', _AllowSummary, '</MonetaryAmount>\n');  
						SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</MonetaryValue>\n</SummaryAllowOrCharge>\n'); 
						
					SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</TotalAllowOrCharge>\n');
				-- SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</AllowOrChargeSummary>\n'); 
			SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</AllowOrChargeSummary>\n'); 
			END IF;
			
		SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</InvoiceSummary>\n');
		
	SET @invoice.to.EDI.Content = CONCAT(@invoice.to.EDI.Content, '</Invoice>');
	
	
	DROP TEMPORARY TABLE IF EXISTS `t_oper_poz`;
	
	-- SET @GUS_reports.Z06_RepContent = CONCAT(@GUS_reports.Z06_RepContent, '\n\n[Formularze]', '\nCount=1');
	
	-- zamiana parametrów na wartosci
	-- SET @GUS_reports.Z06_RepContent = REPLACE(@GUS_reports.Z06_RepContent, '#Rok#', _Rok);
	SET _RepContent = @invoice.to.EDI.Content;
	-- SELECT _varSTR_NOTNULL(@GUS_reports.Z06_RepContent) AS _RepContent;
			
END;  
END IF; 	-- _MODE = 'invoice.to.EDI.relacom.create'

/* tryb zachowany celem zgodności ze starymi wersjami, obecnie zastapiony przez _MODE = 'invoice.to.EDI.get.content' */
IF _MODE = 'invoice.to.EDI.relacom.create.get' THEN
-- BEGIN
	SET @invoice.to.EDI.Content = '';
	CALL ht_EDI_tools('invoice.to.EDI.relacom.create', _RecGUID, @invoice.to.EDI.Content);
	DROP TEMPORARY TABLE IF EXISTS `t_to_edi_content`;
	CREATE TEMPORARY TABLE `t_to_edi_content` (
		Content LONGBLOB -- CHARACTER SET UTF8		
	);
	-- SET @exp.MaxaZmienna = IFNULL(@exp.MaxaZmienna, 0);
	-- SELECT _varSTR_NOTNULL(@GUS_reports.Z06_RepContent) AS _RepContent;
	-- SELECT @invoice.to.EDI.Content AS _RepContent;
	INSERT INTO `t_to_edi_content` SELECT @invoice.to.EDI.Content;
	SELECT Content AS _RepContent, @invoice.to.EDI.Content FROM `t_to_edi_content`;
	-- DROP TEMPORARY TABLE IF EXISTS `t_to_edi_content`;
END IF; 	-- _MODE = 'invoice.to.EDI.relacom.create.get'

END$$

DELIMITER ;

