*!* 16.10.2023
*!*  ExportEFactura.xmlEFactura : se pare ca la ultima versiune de verificare, cota 0 trebuie sa aiba cod de scutire sau text scutire

*!*	31.10.2023
*!*	ExportEFactura.xmlEFactura : corectat eroare articol codbare

*!*	13.11.2023
*!*	ParseEFactura - tratare xml CreditNote

*!*	28.11.2023
*!*	TrimiteFacturi - se trateaza ExecutionStatus cu sau fara spatii

*!*	04.01.2024
*!*	ExportEFactura.xmlEFactura : limitare strada adresa client la 150 caractere
*!* getXmlEFactura : nu validez xmlefactura daca plFaraValidareEFactura = .T. (din borderou efactura)

*!*	10.01.2024
*!*	ExportEFactura.xmlEFactura: corectie completare strada si denumire client. S-au completat in poDate
*!*	ExportEFactura.xmlEFactura: am pus la loc "adresa" in loc de "strada" la <client.streetname>
*!*	AnafEFactura.SendEfactura: am pus parametrul "EXTERN=DA" pentru trimiterea facturilor cu clienti externi

*!*	15.01.2024
*!*	ExportEFactura.xmlEFactura: explicatia de pe articol se sparge in primele 200 caractere pe Item.descrition si urmatoarele 300 pe InvoiceLine.note

*!*	19.01.2024
*!*	ParseEFactura : am tratat fisierele fara cbc, cac; am tratat invoice.note._nodetext_
 
*!*	23.01.2024
*!*	RaspunsuriFactura : se apeleza endpoint-ul cu paginatie, in caz ca sunt mai mult de 500 de raspunsuri

*!*	26.01.2024
*!*	ExportEFactura.xmlEFactura: limitare la 300 caractere invoice.note

*!*	30.01.2024
*!*	ExportEFactura.xmlEFactura: cumulare discount pe cote TVA

*!*	06.03.2024
*!*	ParseEFactura: extragere TotalTVARON, articol (codCPV, codNC8, codBare, codFurnizor, codClient)


*!* 08.03.2024
*!* ExportEFactura.xmlEFactura: se completeaza AllowanceCharge la nivel de Invoice.InvoiceLine si Invoice.InvoiceLine.Item.Price
*!* daca optiunile gnEFACTURA_XML_DISC_PLISTA_LINIE si gnEFACTURA_XML_DISC_PLISTA_ART = 1

*!* 08.03.2024
*!* ExportEFactura.xmlEFactura: se completeaza Invoice.Id cu seria + nr factura, Invoice.Note cu cursul valutar

*!* 29.03.2024
*!* ExportEFactura.xmlEFactura: Se completeaza corect codul taxa pentru operatiile scutite

*!* 10.04.2024
*!* ExportEFactura.xmlEFactura - nu este permis pret negativ. se shimba semnul intre cantitate si pret

*!* 02.07.2024
*!*	xmlEFactura - limitare detalii la 4000 caractere

*!*	04.07.2024
*!*	xmlEFactura - salvare raspunsuri facturi primite/trimise intr-un director comun 

*!*	15.07.2024
*!*	xmlEFactura - 10 conturi bancare din datele firmei la modalitati de plata, in loc de 3 conturi bancare

*!*	07.08.2024
*!*	xmlEFactura - Atasamente inglobate in xml
*!* xmlEFactura - completare registrul comertului in BT-46 (client si furnizor)
*!* xmlEFactura - completare capital social subscris si varsat in BT-33

*!*	08.08.2024
*!*	xmlEFactura - Furnizor.StreetName = strada si numar

*!*	28.10.2024
*!*	xmlEFactura - GetTipTaxa - completare explicatia TVA la motivul scutirii TVA, cota 0%

*!*	06.12.2024
*!*	getXmlEFactura - xml efactura clienti persoane fizice fara cod fiscal - se completeaza Customer.Party.PartyLegalEntity.CompanyId cu 13 zero

*!* 13.03.2026
*!* ValidareEFacturaANAF - folosire validare oauth daca exista token

*!*	14.04.2026
*!*	getXmlEFactura - corecta adresa de livrare loClient.cod_judetL, in loc de loClient.cod_judet


* DO TestValidareEFactura
#define precizie_max_pret_vz	6
#define precizie_max_pret_ach	6

Do TestParseEFactura

Procedure getXmlEFactura
	Lparameters toDateFactura, tcCursorLiniiFactura, tlSilentios, tcFisierXML, tcMesaj
* tcFisierXML OUT
* tcMesaj OUT pentru cazu in care generarea xml este silentioasa

	Local loEFactura As "ExportEFactura"
	Local lcFisierXML, llOk, loInfo, llValidareOnline, lcToken

	llOk = .F.
	lcMesaj = ''
	lcFisierXML = ''
	lcToken = ''

	loInfo = Createobject("empty")
	AddProperty(loInfo, 'lOk', m.llOk)
	AddProperty(loInfo, 'cFile', m.lcFisierXML)
	AddProperty(loInfo, 'cMesaj', m.lcMesaj)

	IF TYPE('pcTokenEfactura') = 'C' AND !EMPTY(m.pcTokenEfactura)
		lcToken = m.pcTokenEfactura
	ENDIF 
	
	loEFactura = Createobject("ExportEFactura", m.tlSilentios, m.lcToken)
	lcFisierXML = loEFactura.xmlEFactura(toDateFactura, tcCursorLiniiFactura)
	loInfo.cFile = Iif(Type('lcFisierXml') = 'C', m.lcFisierXML, '')

	* Daca nu validez eFactura
	llFaraValidare = .F.
	If Type('plFaraValidareEFactura') = 'L'
		* Definesc plFaraValidareEFactura pentru a suprascrie parametrul la momentul listarii (in borderoul eFactura)
		llFaraValidare = m.plFaraValidareEFactura
	ENDIF
	

	If !m.llFaraValidare AND !Empty(m.lcFisierXML) And File(m.lcFisierXML)

		* gnEFACTURA_VALIDARE_ONLINE optiune globala 
		llValidareOnline = Iif(Type('gnEFACTURA_VALIDARE_ONLINE') = 'N', (m.gnEFACTURA_VALIDARE_ONLINE = 1), .F.)

		* Definesc plValidareEfacturaOnline pentru a suprascrie parametrul la momentul listarii (in borderoul eFactura)
		If Type('plValidareEfacturaOnline') = 'L'
			llValidareOnline = m.plValidareEfacturaOnline
		Endif
		llOk = loEFactura.ValidareEFactura(m.lcFisierXML, @lcMesaj, m.llValidareOnline)
		loInfo.lOk = m.llOk
		loInfo.cMesaj = m.lcMesaj
	ENDIF

	* Daca nu trebuie sa validez, intorc SUCCES
	IF m.llFaraValidare 
		loInfo.lOk = .T.
	ENDIF 

	Return m.loInfo
Endproc && xmlEFactura

Define Class ExportEFactura As Custom
	lSilentios = .F.
	cToken = '' && token eFactura, din anaf_efactura.prg

	Procedure Init
		Lparameters tlSilentios, tcToken
		This.lSilentios = m.tlSilentios

		IF TYPE('tcToken') = 'C' AND !EMPTY(m.tcToken)
			This.cToken = m.tcToken
		ENDIF 
	Endproc && Init
*
	Procedure xmlEFactura
		Lparameters toDateFactura, tcCursorLiniiFactura
* toDateFactura = obiect cu capul facturii
* tcCursorLiniiFactura = cursor cu liniile facturii, asa cum sunt la listare

		Local oxml As "msxml2.DOMDocument"
		Local lcBanca, lcCaleFisier, lcCodBare, lcCont, lcFileName, lcNumeClient, lcNumeFirma, lcNumeFisier
		Local lcText, lcTextAditional, lcTipTVA, llSucces, llTaxareInversaSauIntracomunitar, lnCont
		Local lnSucces, loClient, lFurnizorPlatitorTVA, lClientPlatitorTVA, llExtern
		Local lcExplicatie, lcLocalitateBuc, lcMotiv, lcTextDescriere, lcTextNota, lcTip, lnDiscftva
		Local lnPretftva, lnPretftvai, lnProcDisc, lnProcTva, lnValDisc, lnValftva, lnValftvai, loRec
		Local laFiles[1], lcDir, lcExtensie, lcFacturaFile, lcFile, lcMimeType, lcScheletonFile, lcSerieAct
		Local ldDataFactura, lnFile, lnFiles, lnNumarFactura, lcText
*:Global oAdditionalDocumentReference, oAttachment

		*:Global oAllowance, oBaseAmount

*:Global agettipcota[1], maccize, mcodfiscal, mcodjudet, mcomanda, mdensoc, mdiscounturi, mincasat
*:Global minf_suplm, minvoicetype, mlinii, mliniireducere, mliniistornare, mmoneda, mnrliniiavans
*:Global mprefix, msector, msufix, mtara, mtipfactura, mtiptert, mtiptvacurent, mtotalallowances
*:Global mtotalbrut, mtotalcharges, mtotalnet, mtotalnetliniifactura, mtotaltva, mtvai, mtvatotal
*:Global mum, oPayeeFinancialAccount, oPayeeFinancialAccountId, oPayeeFinancialAccountName
*:Global oPaymentMeans, oPaymentMeansCode, oadresa, oadresalivrare, oadresas, oallowancecharge
*:Global oamount, obuyeritem, oclassificationcodbare, oclassificationlot, oclassificationnc
*:Global oclassificationstandardidnc, ocodbare, ocontact, ocontacts, ocontractreference, ocustomer
*:Global odelivery, odeliverylocation, odocallowancecharge, oendpointid, oformalegala, oformalegalas
*:Global oidentificatorformalegala, oidentificatorformalegalas, oidparty, oidpartys, oidstandard
*:Global oinvoice, oinvoiceline, oitem, oitemamount, oitemprice, oitemtaxcategory, oitemtaxscheme
*:Global olot, omonetarytotal, oorderreference, oparty, opartyidentification, opartyidentifications
*:Global opartys, oschemataxe, oschemataxes, oselleritem, ostandarditem, osubtotal, osubtotaltaxa
*:Global osupplier, otara, otaralivrare, otaras, otaxablesubtotal, otaxcategoryallowance
*:Global otaxcategorycharge, otaxcategorytotals, otaxe, otaxes, otaxschemeallowance
*:Global otaxschemetotals, otaxtotal, ototal, ototalbrut, ototaldeduceri, ototalincasat, ototalnet
*:Global ototalnetfaratva, ototalplata, ototaltaxe, oum

		If !(Type('toDateFactura.nract') = 'N' And Type('tcCursorLiniiFactura') = 'C' And !Empty(m.tcCursorLiniiFactura) And Used(m.tcCursorLiniiFactura))
			AMESSAGEBOX('Apelati exportul xml EFactura cu parametrii (DateFactura, CursorFactura)!', 0 + 48, _Screen.Caption)
			Return ''
		Endif

		Local lcSelect, llRectificativa, tcNumeFisier, tcCaleFacturi, loDate, llInstitutiePublica
		lcSelect = Select()

		loDate = toDateFactura
*!*			lcTipTVA = Upper(Nvl(citeste_optiune('D394_TIP'), 'LUNAR'))
*!*			lcTipTVA = Iif(!Inlist(m.lcTipTVA, 'LUNAR', 'TRIMESTRIAL', 'SEMESTRIAL', 'ANUAL'), 'LUNAR', m.lcTipTVA)

* Factura rectificativa
		llRectificativa = Iif(Type('loDate.nRectificativa') = 'N', (loDate.nRectificativa = 1), .F.)
		llRectificativa = m.llRectificativa Or Iif(Type('loDate.tip_saft') = 'N', (loDate.tip_saft = 384), .F.)

* Institutie publica - se folosesc coduri articole CPV sau NC8
		llInstitutiePublica = Iif(Type('loDate.institutie_publica') = 'N', (loDate.institutie_publica = 1), .F.)

		maccize = 0
		mliniireducere = 0
		mtotalcharges = 0
		mtotalallowances = 0
		mtvai = 0
		mincasat = 0

		If Type('gofirma.codfiscalfro') = 'U'
			AddProperty(gofirma, 'codfiscalfro', getnrfromstring(gofirma.cod_fiscal))
		Endif
		lnSucces = update_jtva_coloane("JV", "cJTVAVanzariTemp", 0)
		llSucces = update_um() && vnom_um

		Select a.*, b.coloana_jv, ;
			Iif(Left(b.coloana_jv, 2) = 'CE', 1, 0) As intracomunitar, ;
			Iif(b.coloana_jv = 'ROTI', 1, 0) As taxare_inversa, ;
			Iif(Inlist(b.coloana_jv, 'WRSCDD', 'WRSCFDD', 'WRN', 'FODD', 'WRSCDDAB', 'WRSCDDCD'), 1, 0) As scutit, ;
			Iif('DISCOUNT' $ Upper(a.denumire) And a.pretftva < 0, 1, 0) As discount ;
			From (m.tcCursorLiniiFactura) a Left Join cJTVAVanzariTemp b On a.id_jtva_coloana = b.id_jtva_coloana ;
			Into Cursor C_IES_FORM Readwrite

		
		* Nu este permis pret unitar negativ. Schimb semnul intre cantitate si pret unitar
		SELECT c_ies_form
		SCAN FOR pretftva < 0
			REPLACE cantitate WITH -cantitate, pretftva WITH -pretftva, pretctva WITH -pretctva, pretctvai WITH -pretctvai, pretftvai WITH -pretftvai
		ENDSCAN 
	

		Select(proc_tva - 1) * 100 As proc_tva, intracomunitar, taxare_inversa, scutit, expltva, ;
			Sum(valtva) As tva, ;
			Sum(valftva) As valoare, CAST('F' as C(5)) As tip, Replicate(' ',  100) As explicatie,  Replicate(' ', 100) As  motiv ;
			From C_IES_FORM  ;
			Group By proc_tva, intracomunitar, taxare_inversa, scutit, expltva ;
			Into Cursor C_TVA_FACTURA  ;
			Readwrite

		Select C_TVA_FACTURA
		Sum tva To mtotaltva
		Index On proc_tva Tag procent

		loClient = loDate.oClient
		loClient.cod_tara = ALLTRIM(NVL(loClient.cod_tara,''))
		IF EMPTY(loClient.cod_tara)
			loClient.cod_tara = 'RO'
		ENDIF 

		llExtern = (loClient.cod_tara <> 'RO')
		lFurnizorPlatitorTVA = (LEFT(UPPER(ALLTRIM(goFirma.cod_fiscal)),2) = 'RO')
		lClientPlatitorTVA = (LEFT(UPPER(ALLTRIM(loClient.cod_fiscal)),2) = 'RO')
		
		mcomanda = ""
		mincasat = 0
		mmoneda = Iif(loDate.in_valuta = 0, 'RON', Iif(!Empty(Nvl(loDate.cValuta, '')), Upper(Alltrim(loDate.cValuta)), 'RON'))
		mmoneda = Iif(mmoneda = 'EURO', 'EUR', mmoneda)

*!*			mcodfiscal = Alltrim(Nvl(loClient.cod_fiscal, ''))
		mtipfactura = loDate.tip_doc_394 && 'F', 'S', 'M', 'U', 'H'
*!*			mtara = Alltrim(Nvl(loClient.cod_tara, 'RO'))
*!*			mtiptert = Iif(loClient.id_cetatenie = 1, '',  Iif(loClient.id_cetatenie = 2, 'I', 'E')) && 1 = RO, 2 = UE, 3 = NON-UE
*!*			mtiptvacurent = Iif(m.lcTipTVA = 'LUNAR', 1,  Iif(m.lcTipTVA = 'TRIMESTRIAL', 2, 1)) && 1 = lunar, 2 = trimestrial, 3 = anulare TVA
		mtvai = loDate.tva_incasare
		minf_suplm = ''
		If  !Inlist(mtipfactura, 'F', 'S', 'M', 'U', 'H')
			AMESSAGEBOX( "Pentru acest document nu se genereaza factura electronica momentan.", 64, "Atentie...")
			Return ''
		Endif
* discount-ul are valoare negativa, il inmultesc cu -1
		Select C_IES_FORM
		Calculate Cnt(), Sum(-1 * valftva) For discount = 1 To mliniireducere, mdiscounturi
		Calculate Cnt() For cantitate < 0 To mliniistornare
		mlinii = Reccount('C_IES_FORM')
		mnrliniiavans = 0 && 419
		mtotalallowances = 0
		mtotalallowances = mtotalallowances + mdiscounturi
		Select C_IES_FORM
		Locate For taxare_inversa = 1 Or intracomunitar = 1
		llTaxareInversaSauIntracomunitar = Found()

* nomenclator 5305: S=Standard rate,Z=Zero rated goods,E=Exempt from tax,AE=VAT Reverse charge,K=VAT exempt for EEA intra-community supply of goods and services,G=Free export item, tax not charged,O=Service outside scope of tax,L=Canary Islands general indirect tax,M=Tax for production, services and importation in Ceuta and Melilla
		Select C_TVA_FACTURA
		SCAN
			SCATTER NAME loRec
			lcExplicatie = ''
			lcMotiv = ''
			lcTip = This.GetTipTaxa(mtipfactura, loRec.intracomunitar, loRec.taxare_inversa, loRec.scutit, loRec.proc_tva, @lcExplicatie, @lcMotiv, loRec.expltva)
			REPLACE tip WITH m.lcTip, explicatie WITH m.lcExplicatie, motiv WITH m.lcMotiv
			
*!*				Do Case
*!*					Case intracomunitar = 1
*!*						Replace tip With  'K', explicatie  With  'Livrare intracomunitara', motiv With 'VATEX-EU-IC'
*!*					Case taxare_inversa = 1
*!*						Replace tip With  'AE', explicatie  With  'Taxare inversa', motiv With 'VATEX-EU-AE'
*!*					Case scutit = 1
*!*						Replace tip With 'E', explicatie With  'Scutit cu drept de deducere'
*!*					Case mtipfactura = 'F' And proc_tva = 0
*!*						Replace tip With 'Z'
*!*					Case mtipfactura = 'H'
*!*						Replace tip With 'E', explicatie With 'Bunuri second-hand', motiv With 'VATEX-EU-F'
*!*					Case mtipfactura = 'U'
*!*						Replace tip With 'E', explicatie With 'Regim special agentii de turism', motiv With 'VATEX-EU-D'
*!*					Otherwise
*!*						Replace tip With 'S'
*!*				Endcase
		Endscan

* Nu am accize. Introduc o linie cu valoare 0
* Nu mai introduc o linie cu cota TVA = 0, pentru ca daca am penalitati cu cota TVA = 0, se duplica liniile cu cota TVA = 0
*Insert Into C_TVA_FACTURA (proc_tva, tva, valoare, tip, explicatie, motiv) Values (0, 0, maccize, 'Z', 'Acciza', '')

		oxml = Createobject("msxml2.DOMDocument")
		oxml.appendchild(oxml.createnode("PROCESSINGINSTRUCTION", "xml", ""))
		oinvoice = oxml.appendchild(oxml.createelement("Invoice"))
		oinvoice.setattribute("xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")
		oinvoice.setattribute("xmlns:udt", "urn:oasis:names:specification:ubl:schema:xsd:UnqualifiedDataTypes-2")
		oinvoice.setattribute("xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")
		oinvoice.setattribute("xmlns:ccts", "urn:un:unece:uncefact:documentation:2")
		oinvoice.setattribute("xmlns", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2")
		oinvoice.setattribute("xmlns:qdt", "urn:oasis:names:specification:ubl:schema:xsd:QualifiedDataTypes-2")
		oinvoice.setattribute("xsi:schemaLocation", "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 http://docs.oasis-open.org/ubl/os-UBL-2.1/xsd/maindoc/UBL-Invoice-2.1.xsd")
		oinvoice.setattribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
		oinvoice.appendchild(oxml.createelement("cbc:UBLVersionID"))
		oinvoice.lastchild.Text = "2.1"
		oinvoice.appendchild(oxml.createelement("cbc:CustomizationID"))
		oinvoice.lastchild.Text = "urn:cen.eu:en16931:2017#compliant#urn:efactura.mfinante.ro:CIUS-RO:1.0.1"
		oinvoice.appendchild(oxml.createelement("cbc:ID"))
		lcSerieAct = UPPER(Alltrim(XmlSpecialCharacters(RemoveCharacters(loDate.serie_act, .T.))))
		oinvoice.lastchild.Text = m.lcSerieAct + IIF(!EMPTY(m.lcSerieAct), ' ', '') + Alltrim(Str(loDate.nract, 30, 0))
		oinvoice.appendchild(oxml.createelement("cbc:IssueDate"))
		oinvoice.lastchild.Text = Alltrim(Str(Year(loDate.dataact))) + "-" + Padl(Alltrim(Str(Month(loDate.dataact))), 2, "0") +  "-" + Padl(Alltrim(Str(Day(loDate.dataact))), 2, "0")
		If !Empty(Nvl(loDate.datascad, {}))
			oinvoice.appendchild(oxml.createelement("cbc:DueDate"))
			oinvoice.lastchild.Text = Alltrim(Str(Year(loDate.datascad))) + "-" + Padl(Alltrim(Str(Month(loDate.datascad))), 2, "0") + "-" + Padl(Alltrim(Str(Day(loDate.datascad))), 2, "0")
		Endif
		minvoicetype = ""

		If Type('loDate.tip_saft') = 'N' And !Empty(Nvl(loDate.tip_saft, 0))
			minvoicetype = Alltrim(Str(loDate.tip_saft))
		Else
			Do Case
				Case m.llRectificativa
					minvoicetype = "384"
				Case Alltrim(getnrfromstring(loClient.cod_fiscal)) == Alltrim(gofirma.codfiscalfro)
					minvoicetype = "389"
				Case mliniistornare = mlinii
					minvoicetype = "380"
				Otherwise
					minvoicetype = "380"
			Endcase
		Endif
		oinvoice.appendchild(oxml.createelement("cbc:InvoiceTypeCode"))
		oinvoice.lastchild.Text = minvoicetype

		lcTextAditional = Alltrim(Nvl(loDate.text_aditional, ''))
		If mtvai = 1
			lcTextAditional = m.lcTextAditional + Iif(!Empty(m.lcTextAditional), ' # ', '') +  "TVA la incasare"
		Endif
		If  m.llTaxareInversaSauIntracomunitar
			lcTextAditional = m.lcTextAditional + Iif(!Empty(m.lcTextAditional), ' # ', '') +  "Taxare inversa"
		ENDIF
		
		IF loDate.in_valuta = 1 AND !EMPTY(NVL(loDate.curs,0)) AND ATC('curs', m.lcTextAditional) = 0
			lcTextAditional = m.lcTextAditional + Iif(!Empty(m.lcTextAditional), ' # ', '') +  "Curs: " + ALLTRIM(STR(loDate.curs, 10,4)) + " RON/" + STRTRAN(ALLTRIM(Nvl(loDate.cValuta, '')),'EURO', 'EUR',1,1,1)
		ENDIF 

		If  !Empty(m.lcTextAditional)
			oinvoice.appendchild(oxml.createelement("cbc:Note"))
			lcText = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(m.lcTextAditional, .T.)), 300))
			oinvoice.lastchild.Text = m.lcText
		Endif
		oinvoice.appendchild(oxml.createelement("cbc:DocumentCurrencyCode"))
		If loDate.in_valuta = 1
			oinvoice.lastchild.Text = m.mmoneda
		Else
			oinvoice.lastchild.Text = "RON"
		Endif
		oinvoice.appendchild(oxml.createelement("cbc:TaxCurrencyCode"))
		oinvoice.lastchild.Text = "RON"
		If  loDate.tip = 3 And !Empty(Nvl(loDate.descriere, ''))
			oorderreference = oinvoice.appendchild(oxml.createelement("cac:OrderReference"))
			oorderreference.appendchild(oxml.createelement("cbc:ID"))
			oorderreference.lastchild.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(loDate.descriere, .T.)), 100))
			
		Endif
		If !Empty(Nvl(loDate.contract, ''))
			ocontractreference = oinvoice.appendchild(oxml.createelement("cac:ContractDocumentReference"))
			ocontractreference.appendchild(oxml.createelement("cbc:ID"))
			ocontractreference.lastchild.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(loDate.contract, .T.)), 100))
		ENDIF
		
		* Atasamente inglobate in xml
		IF TYPE('pnAtasamenteEfactura') = 'N' AND m.pnAtasamenteEfactura > 0
			* pnAtasamente = 0: nimic, 1 : factura, 2: toate inclusiv factura, 3: toate fara factura
			ldDataFactura = loDate.dataact
			lnNumarFactura = loDate.nract
			lcFacturaFile = GetPDFFacturaFile(m.ldDataFactura, m.lnNumarFactura) && d:\roa\pdf\20200402_12346_factura.pdf			
			lcScheletonFile = Strtran(lcFacturaFile, 'factura', '*', 1, 10, 1) && d:\roa\pdf\20200402_12346_*.pdf (_recapitulatia.pdf, _situatie_stationare.pdf, _declaratie_comandant.pdf)
			lcDir = Addbs(Justpath(m.lcFacturaFile))
			lnFiles = Adir(laFiles, m.lcScheletonFile)
			For lnFile = 1 To m.lnFiles
				lcFileName = laFiles[m.lnFile, 1]
				lcFile = m.lcDir + laFiles[m.lnFile, 1]
				IF !FILE(m.lcFile)
					LOOP
				ENDIF 
				IF (m.pnAtasamenteEfactura = 1 AND '_factura'$ LOWER(m.lcFileName)) OR m.pnAtasamenteEfactura = 2 OR (m.pnAtasamenteEfactura = 3 AND !'_factura'$ LOWER(m.lcFileName))
					oAdditionalDocumentReference = oinvoice.appendchild(oxml.createelement("cac:AdditionalDocumentReference"))
					oAdditionalDocumentReference.appendchild(oxml.createelement("cbc:ID"))
					oAdditionalDocumentReference.lastchild.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(m.lcFileName, .T.)), 50))
					oAdditionalDocumentReference.appendchild(oxml.createelement("cbc:DocumentDescription"))
					oAdditionalDocumentReference.lastchild.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(m.lcFileName, .T.)), 50))					
					oAttachment = oAdditionalDocumentReference.appendchild(oxml.createelement("cac:Attachment"))
					oEmbeddedDocumentBinaryObject = oAttachment.appendchild(oxml.createelement("cbc:EmbeddedDocumentBinaryObject"))
					lcExtensie = LOWER(JUSTEXT(m.lcFileName))
					lcMimeType = GetMimeType(m.lcExtensie) && wwutils.prg
					oEmbeddedDocumentBinaryObject.setattribute("mimeCode", m.lcMimeType)
					oEmbeddedDocumentBinaryObject.setattribute("filename", m.lcFileName)	
					oEmbeddedDocumentBinaryObject.Text = STRCONV(FILETOSTR(m.lcFile),13)
				ENDIF 				
			Endfor						
		ENDIF && Type(pnAtasamenteEfactura)
		
		
		osupplier = oinvoice.appendchild(oxml.createelement("cac:AccountingSupplierParty"))
		oparty = osupplier.appendchild(oxml.createelement("cac:Party"))
		If Empty(Nvl(gofirma.email, ''))
			AMESSAGEBOX( ;
				  "Completati adresa de email a societatii in datele firmei." +  ;
				  Chr(13) +  ;
				  "Aceasta este necesara pentru primirea raspunsului facturii electronice.",  ;
				  48,  ;
				  "Date incomplete..." ;
				  )
			Return ''
		Endif

		oendpointid = oparty.appendchild(oxml.createelement("cbc:EndpointID"))
		oendpointid.setattribute("schemeID", ;
			  "EM")
		oendpointid.Text = Alltrim(gofirma.email)
		
		lcPartyIdentification = ALLTRIM(NVL(goFirma.reg_comert, ''))
		If !Empty(m.lcPartyIdentification)
			opartyidentification = oparty.appendchild(oxml.createelement("cac:PartyIdentification"))
			oidparty = opartyidentification.appendchild(oxml.createelement("cbc:ID")) && BT-29
			oidparty.Text = m.lcPartyIdentification
		Endif
		oadresa = oparty.appendchild(oxml.createelement("cac:PostalAddress"))
		If Empty(Nvl(gofirma.strada, ''))
			AMESSAGEBOX( "Completati strada in datele firmei.", 48, "Date incomplete..." )
			Return ''
		Endif

		oadresa.appendchild(oxml.createelement("cbc:StreetName"))
		oadresa.lastchild.Text = Alltrim(Nvl(gofirma.strada, '')) + ' ' + Alltrim(Nvl(gofirma.numar, ''))

		If Empty(Nvl(gofirma.localitate, ''))
			AMESSAGEBOX( "Completati localitatea in datele firmei.",  48, "Date incomplete..." )
			Return ''
		Endif
		If Empty(Nvl(gofirma.judet, ''))
			AMESSAGEBOX( "Alegeti judetul in datele firmei.", 48, "Date incomplete..." )
			Return ''
			* Nu mai completez sectorul, doar localitatea "BUCURESTI SECTORUL 1"
*!*			Else
*!*				If gofirma.judet = "BUCURESTI" And Empty(Nvl(gofirma.sector, ''))
*!*					AMESSAGEBOX( "Completati sectorul in datele firmei.",  48,  "Date incomplete..." )
*!*					Return ''
*!*				Endif
		Endif
		oadresa.appendchild(oxml.createelement("cbc:CityName"))
		If gofirma.judet = "BUCURESTI"
			oadresa.lastchild.Text = ALLTRIM(STRTRAN(Upper(gofirma.localitate), "BUCURESTI SECTORUL ", "SECTOR"))
		Else
			oadresa.lastchild.Text = Alltrim(Upper(gofirma.localitate))
		Endif
		mcodjudet = gofirma.indicativ_judet

		oadresa.appendchild(oxml.createelement("cbc:CountrySubentity"))

		oadresa.lastchild.Text = "RO-" + Alltrim(mcodjudet)
		otara = oadresa.appendchild(oxml.createelement("cac:Country"))
		otara.appendchild(oxml.createelement("cbc:IdentificationCode"))
		otara.lastchild.Text = "RO"
		
		otaxe = oparty.appendchild(oxml.createelement("cac:PartyTaxScheme"))
		otaxe.appendchild(oxml.createelement("cbc:CompanyID")) && BT-31
		otaxe.lastchild.Text = IIF(m.lFurnizorPlatitorTVA, "RO", "") + Alltrim(gofirma.codfiscalfro) 
		oschemataxe = otaxe.appendchild(oxml.createelement("cac:TaxScheme"))
		IF m.lFurnizorPlatitorTVA			
			oschemataxe.appendchild(oxml.createelement("cbc:ID"))
			oschemataxe.lastchild.Text = "VAT"
		ENDIF 	
		
		oformalegala = oparty.appendchild(oxml.createelement("cac:PartyLegalEntity"))
		oformalegala.appendchild(oxml.createelement("cbc:RegistrationName"))
		lcText = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(gofirma.firma, .T.)), 200))
		oformalegala.lastchild.Text = m.lcText 
		
		oidentificatorformalegala = oformalegala.appendchild(oxml.createelement("cbc:CompanyID")) && BT-30
		* Furnizor platitor TVA : Reg Comert, Furnizor neplatitor TVA : CIF
		IF !Empty(Nvl(gofirma.reg_comert, ''))
			oidentificatorformalegala.Text = Alltrim(gofirma.reg_comert)
		ELSE 	
			oidentificatorformalegala.Text = Alltrim(gofirma.codfiscalfro)
		Endif
		mdensoc = Upper(Alltrim(gofirma.firma)) + " "

		lcText = IIF(!EMPTY(NVL(gofirma.forma_juridica,'')), Alltrim(NVL(gofirma.forma_juridica,'')), '')
		lcText = m.lcText + IIF(!EMPTY(m.lcText), " # ", "") + IIF(!EMPTY(NVL(gofirma.capital_soc_sub, 0)), "Capital social subscris: " + Alltrim(STR(gofirma.capital_soc_sub)), '')
		lcText = m.lcText + IIF(!EMPTY(m.lcText), " # ", "") + IIF(!EMPTY(NVL(gofirma.capital_soc_var, 0)), "Capital social varsat: " + Alltrim(STR(gofirma.capital_soc_var)), '')
		If  !Empty(Nvl(gofirma.forma_juridica, ''))
			oformalegala.appendchild(oxml.createelement("cbc:CompanyLegalForm")) && BT-33
			oformalegala.lastchild.Text = m.lcText
			
		ENDIF
		
		If  !Empty(Nvl(gofirma.nume, '')) Or !Empty(Nvl(gofirma.prenume, '')) Or !Empty(Nvl(gofirma.email, '')) Or !Empty(Nvl(gofirma.telefon, ''))
			ocontact = oparty.appendchild(oxml.createelement("cac:Contact"))
			If  !Empty(Nvl(gofirma.nume, '')) Or !Empty(Nvl(gofirma.prenume, ''))
				ocontact.appendchild(oxml.createelement("cbc:Name"))
				ocontact.lastchild.Text = Alltrim(Nvl(gofirma.nume, '')) + " " + Alltrim(Nvl(gofirma.prenume, ''))
			Endif
			If !Empty(Nvl(gofirma.telefon, ''))
				ocontact.appendchild(oxml.createelement("cbc:Telephone"))
				ocontact.lastchild.Text = Alltrim(gofirma.telefon)
			Endif
			If !Empty(Nvl(gofirma.email, ''))
				ocontact.appendchild(oxml.createelement("cbc:ElectronicMail"))
				ocontact.lastchild.Text =  Alltrim(gofirma.email)
			Endif
		Endif

		ocustomer = oinvoice.appendchild(oxml.createelement("cac:AccountingCustomerParty"))
		opartys = ocustomer.appendchild(oxml.createelement("cac:Party"))
		If  !Empty(Nvl(loClient.email_facturare, ''))
			oendpointid = opartys.appendchild(oxml.createelement("cbc:EndpointID"))
			oendpointid.setattribute("schemeID", "EM")
			oendpointid.Text = Alltrim(loClient.email_facturare)
		ENDIF

		* Registrul Comertului
		lcPartyIdentification = IIF(!EMPTY(NVL(loClient.reg_comert,'')), ALLTRIM(NVL(loClient.reg_comert,'')), '')
		If  !Empty(m.lcPartyIdentification)
			opartyidentifications = opartys.appendchild(oxml.createelement("cac:PartyIdentification"))
			oidpartys = opartyidentifications.appendchild(oxml.createelement("cbc:ID")) && BT-46
			oidpartys.Text = m.lcPartyIdentification
		Endif
		oadresas = opartys.appendchild(oxml.createelement("cac:PostalAddress"))

		If Empty(Nvl(loClient.adresa, ''))
			AMESSAGEBOX("Completati adresa clientului.", 48, "Date incomplete..." )
			Return ''
		Endif
		oadresas.appendchild(oxml.createelement("cbc:StreetName")) && adresa linia 1
		oadresas.lastchild.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(loClient.adresa, .T.)), 150))
	
		If Empty(Nvl(loClient.localitate, ''))
			AMESSAGEBOX("Completati localitatea in adresa clientului.", 48, "Date incomplete..." )
			Return ''
		Endif
		oadresas.appendchild(oxml.createelement("cbc:CityName"))
		If !m.llExtern AND Empty(Nvl(loClient.judet, ''))
			AMESSAGEBOX("Alegeti judetul clientului.", 48, "Date incomplete..." )
			Return ''
		Endif
		If loClient.judet = "BUCURESTI"
			msector = ""
			lcLocalitateBuc = Upper(loClient.localitate)
			lcLocalitateBuc = Alltrim(Strtran(m.lcLocalitateBuc, 'BUCURESTI', ''))
			lcLocalitateBuc = Alltrim(Strtran(m.lcLocalitateBuc, 'SECTORUL ', 'SECTOR', 1, 1, 1)) && TREBUIE SA FIE "SECTOR1" in loc de "SECTORUL 1"

			If  !"SECTOR" $ m.lcLocalitateBuc
				AMESSAGEBOX("Alegeti un sector valid pentru Bucuresti in adresa clientului.", 48, "Atentie...")
				Return ''
			Endif
			oadresas.lastchild.Text = m.lcLocalitateBuc
		Else
			oadresas.lastchild.Text = Alltrim(loClient.localitate)
		ENDIF
		IF !m.llExtern
			oadresas.appendchild(oxml.createelement("cbc:CountrySubentity"))
			oadresas.lastchild.Text = IIF(!m.llExtern, "RO-" + Alltrim(loClient.indicativ_judet), '')
		ENDIF 	
		otaras = oadresas.appendchild(oxml.createelement("cac:Country"))
		otaras.appendchild(oxml.createelement("cbc:IdentificationCode"))
		otaras.lastchild.Text = Iif(!Empty(Nvl(loClient.cod_tara, '')), Alltrim(loClient.cod_tara), "RO")

		If Alltrim(loClient.cod_tara) = 'RO' And !Empty(Nvl(loClient.cod_fiscal, '')) AND 'RO'$UPPER(loClient.cod_fiscal) And verifcf(loClient.cod_fiscal)
			* clienti RO, platitori TVA, cu cod fiscal cu RO
			otaxes = opartys.appendchild(oxml.createelement("cac:PartyTaxScheme"))
			otaxes.appendchild(oxml.createelement("cbc:CompanyID"))
			otaxes.lastchild.Text = "RO" + Alltrim(getnrfromstring(Nvl(loClient.cod_fiscal, ''))) && BT-48
			oschemataxes = otaxes.appendchild(oxml.createelement("cac:TaxScheme"))
			oschemataxes.appendchild(oxml.createelement("cbc:ID"))
			oschemataxes.lastchild.Text = "VAT"
		ELSE 
			* clienti non-RO, cu cod fiscal
			otaxes = opartys.appendchild(oxml.createelement("cac:PartyTaxScheme"))
			IF !Empty(Nvl(loClient.cod_tara, '')) AND Alltrim(loClient.cod_tara) <> 'RO' AND !Empty(Nvl(loClient.cod_fiscal, ''))
				otaxes.appendchild(oxml.createelement("cbc:CompanyID"))
				otaxes.lastchild.Text = loClient.cod_tara + Alltrim(getnrfromstring(Nvl(loClient.cod_fiscal, '')))
			ENDIF 
			oschemataxes = otaxes.appendchild(oxml.createelement("cac:TaxScheme"))
			oschemataxes.appendchild(oxml.createelement("cbc:ID"))
			oschemataxes.lastchild.Text = "VAT"			
		Endif
		oformalegalas = opartys.appendchild(oxml.createelement("cac:PartyLegalEntity"))
		oformalegalas.appendchild(oxml.createelement("cbc:RegistrationName"))
		oformalegalas.lastchild.Text = Alltrim(Nvl(loClient.denumireclient, ''))

		If !Empty(Nvl(loClient.cod_fiscal, '')) 
			oidentificatorformalegalas = oformalegalas.appendchild(oxml.createelement("cbc:CompanyID")) && BT-47
			IF Alltrim(loClient.cod_tara) = 'RO'
				IF 'RO'$UPPER(NVL(loClient.cod_fiscal,''))
					* clienti RO, platitori TVA, pot sa pun Reg. Comert sau codul fiscal
					oidentificatorformalegalas.Text = ALLTRIM(NVL(loClient.reg_comert,''))
				ELSE
					* clienti RO, neplatitori TVA, se pune codul fiscal
					oidentificatorformalegalas.Text = Alltrim(getnrfromstring(Nvl(loClient.cod_fiscal, '')))
				ENDIF 	
			ELSE
				oidentificatorformalegalas.setattribute("schemeID", "0028") && International Standard ISO 6523 https://docs.peppol.eu/poacc/billing/3.0/codelist/ICD/
				oidentificatorformalegalas.text = loClient.cod_tara + Alltrim(getnrfromstring(Nvl(loClient.cod_fiscal, '')))
			ENDIF 
		ELSE 
			IF EMPTY(NVL(loClient.cod_fiscal,'')) AND NVL(loClient.tip_persoana,0) = 2 
				* clienti RO, persoane fizice, fara cod fiscal. se pune 0 de 13 ori
				oidentificatorformalegalas = oformalegalas.appendchild(oxml.createelement("cbc:CompanyID"))			
				oidentificatorformalegalas.Text =  REPLICATE('0',13)
			ELSE 
				IF m.llExtern && Alltrim(loClient.cod_tara) = 'RO'		
					IF EMPTY(NVL(loClient.reg_comert, ''))
						AMESSAGEBOX("Completati identificatorul clientului (Reg. Comert)!", 48, "Date incomplete..." )
						Return ''				
					ENDIF 
					oidentificatorformalegalas = oformalegalas.appendchild(oxml.createelement("cbc:CompanyID"))			
					oidentificatorformalegalas.text = ALLTRIM(NVL(loClient.reg_comert,''))
				ENDIF 	
			ENDIF 	
		Endif
		mdensoc = Alltrim(Nvl(loClient.denumireclient, '')) + " "
		mprefix = ""
		msufix = ""
		Do Case
			Case mdensoc = "S.C. " Or mdensoc = "SC "
				mprefix = "Societate comerciala"
			Case mdensoc = "P.F. " Or mdensoc = "PF "
				mprefix = "Persoana fizica"
			Case mdensoc = "P.F.A. " Or mdensoc = "PFA "
				mprefix = "Persoana fizica autorizata"
			Case mdensoc = "A.F. " Or mdensoc = "AF "
				mprefix = "Asociatie familiala"
		Endcase
		Do Case
			Case " S.R.L." $ mdensoc  ;
					.Or. " SRL " $ mdensoc
				msufix = "Societate cu raspundere limitata"
			Case " S.A." $ mdensoc .Or.  ;
					" SA " $ mdensoc
				msufix = "Societate pe actiuni"
		Endcase
		If !Empty(mprefix)
			oformalegalas.appendchild(oxml.createelement("cbc:CompanyLegalForm"))
			oformalegalas.lastchild.Text = mprefix
		Endif
		If !Empty(Nvl(loClient.telefon, '')) Or !Empty(Nvl(loClient.email_facturare, ''))
			ocontacts = opartys.appendchild(oxml.createelement("cac:Contact"))
*!*			If  !EMPTY(C_IES_FORM.delegat)
*!*				ocontacts.appendchild(oxml.createelement("cbc:Name"))
*!*				ocontacts.lastchild.Text = ALLTRIM(C_IES_FORM.delegat)
*!*			Endif
			If !Empty(Nvl(loClient.telefon, ''))
				ocontacts.appendchild(oxml.createelement("cbc:Telephone"))
				ocontacts.lastchild.Text = Alltrim(loClient.telefon)
			Endif
			If !Empty(Nvl(loClient.email_facturare, ''))
				ocontacts.appendchild(oxml.createelement("cbc:ElectronicMail"))
				ocontacts.lastchild.Text = Alltrim(loClient.email_facturare)
			Endif
		Endif

		* la adresa de livrare, daca exista in xml, trebuie completata neaparat strada, nu numai judetul si localitatea
		If !Empty(Nvl(loClient.adresa_livrare, ''))
			odelivery = oinvoice.appendchild(oxml.createelement("cac:Delivery"))
			odeliverylocation = odelivery.appendchild(oxml.createelement("cac:DeliveryLocation"))
			oadresalivrare = odeliverylocation.appendchild(oxml.createelement("cac:Address"))
			IF EMPTY(Nvl(loClient.stradal, ''))
				AMESSAGEBOX( "Completati strada in adresa de livrare a clientului!", 48, "Atentie...")
				Return ''
			ENDIF 	
			oadresalivrare.appendchild(oxml.createelement("cbc:StreetName"))
			oadresalivrare.lastchild.Text = Alltrim(Nvl(loClient.stradal, ''))
	
			oadresalivrare.appendchild(oxml.createelement("cbc:CityName"))
			If Empty(Nvl(loClient.localitatel, ''))
				AMESSAGEBOX( "Alegeti localitatea din adresa de livrare.", 48, "Atentie...")
				Return ''
			Endif
			If Empty(Nvl(loClient.indicativ_judetl, ''))
				AMESSAGEBOX( "Alegeti judetul din adresa de livrare.", 48, "Atentie...")
				Return ''
			Endif
			If loClient.judetl = "BUCURESTI"
				msector = ""
				lcLocalitateBuc = Upper(loClient.localitatel)
				lcLocalitateBuc = Alltrim(Strtran(m.lcLocalitateBuc, 'BUCURESTI', ''))
				lcLocalitateBuc = Alltrim(Strtran(m.lcLocalitateBuc, 'SECTORUL ', 'SECTOR', 1, 1, 1)) && TREBUIE SA FIE "SECTOR1" in loc de "SECTORUL 1"

				If  !"SECTOR" $ m.lcLocalitateBuc
					AMESSAGEBOX( "Alegeti un sector valid pentru Bucuresti, in adresa de livrare.", 48, "Atentie...")
					Return ''
				Endif

				oadresalivrare.lastchild.Text = m.lcLocalitateBuc
			Else
				oadresalivrare.lastchild.Text = Alltrim(loClient.localitatel)
			Endif
			oadresalivrare.appendchild(oxml.createelement("cbc:CountrySubentity"))
			oadresalivrare.lastchild.Text = "RO-" + Alltrim(loClient.indicativ_judetl)
			otaralivrare = oadresalivrare.appendchild(oxml.createelement("cac:Country"))
			otaralivrare.appendchild(oxml.createelement("cbc:IdentificationCode"))
			otaralivrare.lastchild.Text = "RO"
		Endif && adresa_livrare


* Conturi IBAN instructiune plata
		For lnCont = 1 To 10
			lcCont = Alltrim(Nvl(Evaluate('goFirma.cont_banca' + Alltrim(Str(m.lnCont))), ''))
			lcBanca = Alltrim(Nvl(Evaluate('goFirma.banca' + Alltrim(Str(m.lnCont))), ''))

			If !Empty(Nvl(m.lcCont, ''))
				oPaymentMeans = oinvoice.appendchild(oxml.createelement("cac:PaymentMeans"))
				oPaymentMeansCode = oPaymentMeans.appendchild(oxml.createelement("cbc:PaymentMeansCode"))
				oPaymentMeansCode.Text = '42' && virament bancar
				oPayeeFinancialAccount = oPaymentMeans.appendchild(oxml.createelement("cac:PayeeFinancialAccount"))
				oPayeeFinancialAccountId = oPayeeFinancialAccount.appendchild(oxml.createelement("cbc:ID"))
				oPayeeFinancialAccountId.Text = m.lcCont && cont IBAN
				oPayeeFinancialAccountName = oPayeeFinancialAccount.appendchild(oxml.createelement("cbc:Name"))
				oPayeeFinancialAccountName.Text = m.lcBanca && nume cont
			Endif
		Endfor

		Select C_IES_FORM
		If mliniireducere > 0
			SELECT SUM(-1*valftva) as valftva, proc_tva ;
				FROM C_IES_FORM ;
				WHERE discount = 1 ;
				GROUP BY proc_tva ;
				ORDER BY proc_tva ;
				INTO CURSOR cDiscounturiTemp
			
			Select cDiscounturiTemp
			SCAN
				lnValftva = cDiscounturiTemp.valftva
				lnProcTva = cDiscounturiTemp.proc_tva
				
				oallowancecharge = oinvoice.appendchild(oxml.createelement("cac:AllowanceCharge"))
				oallowancecharge.appendchild(oxml.createelement("cbc:ChargeIndicator"))
				oallowancecharge.lastchild.Text = "false"
				oallowancecharge.appendchild(oxml.createelement("cbc:AllowanceChargeReasonCode"))
				oallowancecharge.lastchild.Text = "95"
				oallowancecharge.appendchild(oxml.createelement("cbc:AllowanceChargeReason"))
				oallowancecharge.lastchild.Text =  "Discount"
				odocallowancecharge = oallowancecharge.appendchild(oxml.createelement("cbc:Amount")) && BT-92
				odocallowancecharge.setattribute("currencyID", "RON")
				odocallowancecharge.Text = Alltrim(Str(m.lnValftva, 15, 2))
				otaxcategoryallowance = oallowancecharge.appendchild(oxml.createelement("cac:TaxCategory"))
				otaxcategoryallowance.appendchild(oxml.createelement("cbc:ID"))
				Select tip From  ;
					C_TVA_FACTURA  ;
					Where proc_tva = (m.lnProcTva - 1) * 100 ;
					Into Array agettipcota
				otaxcategoryallowance.lastchild.Text = Alltrim(agettipcota(1))
				otaxcategoryallowance.appendchild(oxml.createelement("cbc:Percent"))
				otaxcategoryallowance.lastchild.Text = Alltrim(Str((m.lnProcTva - 1) * 100, 2, 0))
				otaxschemeallowance = otaxcategoryallowance.appendchild(oxml.createelement("cac:TaxScheme"))
				otaxschemeallowance.appendchild(oxml.createelement("cbc:ID"))
				otaxschemeallowance.lastchild.Text =  "VAT"
			ENDSCAN
			
			USE IN (SELECT('cDiscounturiTemp'))
		Endif
		If maccize <> 0
			oallowancecharge = oinvoice.appendchild(oxml.createelement("cac:AllowanceCharge"))
			oallowancecharge.appendchild(oxml.createelement("cbc:ChargeIndicator"))
			oallowancecharge.lastchild.Text = "true"
			oallowancecharge.appendchild(oxml.createelement("cbc:AllowanceChargeReason"))
			oallowancecharge.lastchild.Text = "Acciza"
			odocallowancecharge = oallowancecharge.appendchild(oxml.createelement("cbc:Amount"))
			odocallowancecharge.setattribute("currencyID", "RON")
			odocallowancecharge.Text = Alltrim(Str(maccize, 15, 2))
			otaxcategorycharge = oallowancecharge.appendchild(oxml.createelement("cac:TaxCategory"))
			otaxcategorycharge.appendchild(oxml.createelement("cbc:ID"))
			otaxcategorycharge.lastchild.Text = "Z"
			otaxcategorycharge.appendchild(oxml.createelement("cbc:Percent"))
			otaxcategorycharge.lastchild.Text = "0"
			otaxschemeallowance = otaxcategorycharge.appendchild(oxml.createelement("cac:TaxScheme"))
			otaxschemeallowance.appendchild(oxml.createelement("cbc:ID"))
			otaxschemeallowance.lastchild.Text = "VAT"
		ENDIF

		If Reccount("C_TVA_FACTURA") > 0
			otaxtotal = oinvoice.appendchild(oxml.createelement("cac:TaxTotal"))
			Calculate Sum(tva) To mtvatotal In C_TVA_FACTURA

			ototal = otaxtotal.appendchild(oxml.createelement("cbc:TaxAmount"))
			ototal.setattribute("currencyID", mmoneda)
			ototal.Text = Alltrim(Str(mtvatotal, 15, 2))
			Select C_TVA_FACTURA
			Set Order To procent
			Scan
				otaxablesubtotal = otaxtotal.appendchild(oxml.createelement("cac:TaxSubtotal"))
				osubtotal = otaxablesubtotal.appendchild(oxml.createelement("cbc:TaxableAmount"))
				osubtotal.setattribute("currencyID", mmoneda)
				osubtotal.Text = Alltrim(Str(C_TVA_FACTURA.valoare, 15, 2))
				osubtotaltaxa = otaxablesubtotal.appendchild(oxml.createelement("cbc:TaxAmount"))
				osubtotaltaxa.setattribute("currencyID", mmoneda)
				osubtotaltaxa.Text = Alltrim(Str(C_TVA_FACTURA.tva, 15, 2))
				otaxcategorytotals = otaxablesubtotal.appendchild(oxml.createelement("cac:TaxCategory"))
				otaxcategorytotals.appendchild(oxml.createelement("cbc:ID"))
				otaxcategorytotals.lastchild.Text =  Alltrim(C_TVA_FACTURA.tip)
				otaxcategorytotals.appendchild(oxml.createelement("cbc:Percent"))
				otaxcategorytotals.lastchild.Text =  Alltrim(Str(C_TVA_FACTURA.proc_tva, 2, 0))
* eroare regula: BR_Z_10: O detaliere a TVA (BG-23) cu codul categoriei de TVA (BT-118) Cota zero trebuie sa nu aiba un cod al motivului de exceptare de la TVA (BT-121) sau un text cu motivul exceptarii de la TVA (BT-120).

				If !Empty(C_TVA_FACTURA.motiv) AND (INLIST(Alltrim(C_TVA_FACTURA.tip), 'K', 'AE') OR C_TVA_FACTURA.proc_tva <> 0)
					* BT 121 CODUL MOTIVULUI SCUTIRII PENTRU LIVRARI INTRACOMUNITARE K (vatex-eu-k) SAU TAXARE INVERSA AE (vatex-eu-ae)
					otaxcategorytotals.appendchild(oxml.createelement("cbc:TaxExemptionReasonCode"))
					otaxcategorytotals.lastchild.Text = Alltrim(C_TVA_FACTURA.motiv)
				Endif
				If !Empty(C_TVA_FACTURA.explicatie) && And C_TVA_FACTURA.proc_tva <> 0 && se pare ca la ultima versiune de verificare, cota 0 trebuie sa aiba cod de scutire sau text scutire
					otaxcategorytotals.appendchild(oxml.createelement("cbc:TaxExemptionReason"))
					otaxcategorytotals.lastchild.Text = Alltrim(C_TVA_FACTURA.explicatie)
				Endif
				otaxschemetotals = otaxcategorytotals.appendchild(oxml.createelement("cac:TaxScheme"))
				otaxschemetotals.appendchild(oxml.createelement("cbc:ID"))
				otaxschemetotals.lastchild.Text = "VAT"
			Endscan

			Select C_IES_FORM
			Locate
			If mmoneda <> "RON"
				otaxtotal = oinvoice.appendchild(oxml.createelement("cac:TaxTotal"))
				ototal = otaxtotal.appendchild(oxml.createelement("cbc:TaxAmount"))
				ototal.setattribute("currencyID", "RON")
				ototal.Text = Alltrim(Str(Round(mtvatotal * loDate.Curs, 2), 15, 2))
			Endif
		Endif && Reccount("C_TVA_FACTURA") > 0

		Select C_IES_FORM
		Sum valftva To mtotalnet For discount = 0

		Locate
		mtotalnetliniifactura = mtotalnet

		mtotalnet = mtotalnet + mtotalcharges - mtotalallowances
		mtotalbrut = mtotalnet + mtotaltva
		omonetarytotal = oinvoice.appendchild(oxml.createelement("cac:LegalMonetaryTotal"))
		ototalnet = omonetarytotal.appendchild(oxml.createelement("cbc:LineExtensionAmount")) && BT-106
		ototalnet.setattribute("currencyID", mmoneda)
		ototalnet.Text = Alltrim(Str(mtotalnetliniifactura, 15, 2))
		ototalnetfaratva = omonetarytotal.appendchild(oxml.createelement("cbc:TaxExclusiveAmount")) && BT-109
		ototalnetfaratva.setattribute("currencyID", mmoneda)
		ototalnetfaratva.Text = Alltrim(Str(mtotalnet, 15, 2))
		ototalbrut = omonetarytotal.appendchild(oxml.createelement("cbc:TaxInclusiveAmount")) && BT-112
		ototalbrut.setattribute("currencyID", mmoneda)
		ototalbrut.Text = Alltrim(Str(mtotalbrut, 15, 2))
		If mtotalallowances <> 0
			ototaldeduceri = omonetarytotal.appendchild(oxml.createelement("cbc:AllowanceTotalAmount")) && BT-107
			ototaldeduceri.setattribute("currencyID", mmoneda)
			ototaldeduceri.Text = Alltrim(Str(mtotalallowances, 15, 2))
		Endif
		If mtotalcharges <> 0
			ototaltaxe = omonetarytotal.appendchild(oxml.createelement("cbc:ChargeTotalAmount")) && BT-108
			ototaltaxe.setattribute("currencyID", mmoneda)
			ototaltaxe.Text = Alltrim(Str(mtotalcharges, 15, 2))
		Endif
		If mincasat <> 0
			ototalincasat = omonetarytotal.appendchild(oxml.createelement("cbc:PrepaidAmount"))
			ototalincasat.setattribute("currencyID", mmoneda)
			ototalincasat.Text = Alltrim(Str(mincasat, 15, 2))
		Endif
		ototalplata = omonetarytotal.appendchild(oxml.createelement("cbc:PayableAmount"))
		ototalplata.setattribute("currencyID", mmoneda)
		ototalplata.Text = Alltrim(Str(mtotalbrut - mincasat, 15, 2))

		Select C_IES_FORM
		Scan For discount = 0
			SCATTER NAME loRec
			
			* Discount
			lnValftva = valftva
			lnValftvai = valftvai
			lnValDisc = valftvai-valftva
			lnPretftva = pretftva
			lnPretftvai = pretftvai
			lnDiscftva = pretftvai-pretftva
			lnProcDisc = proc_disc
			
			oinvoiceline = oinvoice.appendchild(oxml.createelement("cac:InvoiceLine"))
			oinvoiceline.appendchild(oxml.createelement("cbc:ID"))
			oinvoiceline.lastchild.Text = Alltrim(Str(Recno(), 4, 0))

			lcText = ''
			lcTextDescriere = ''
			lcTextNota = ''
			IF !EMPTY(ALLTRIM(NVL(C_IES_FORM.explicatie,'')))
				lcText = XmlSpecialCharacters(RemoveCharacters(Alltrim(C_IES_FORM.explicatie), .T.))
				lcTextDescriere = SUBSTR(m.lcText, 1, 200) && item.description, maxim 200 caractere
				lcTextNota = ALLTRIM(SUBSTR(m.lcText, 201, 300)) && line.note, maxim 300 caractere
			ENDIF 
			
			If  !EMPTY(m.lcTextNota)
				oinvoiceline.appendchild(oxml.createelement("cbc:Note"))
				oinvoiceline.lastchild.Text = m.lcTextNota
			ENDIF
			
			mum = Iif(Empty(Nvl(cod_um_iso, "")), "H87", Alltrim(cod_um_iso))
			oum = oinvoiceline.appendchild(oxml.createelement("cbc:InvoicedQuantity"))
			oum.setattribute("unitCode", mum)
			oum.Text = Alltrim(Str(C_IES_FORM.cantitate, 15, 3))
			oamount = oinvoiceline.appendchild(oxml.createelement("cbc:LineExtensionAmount")) && BT-131
			oamount.setattribute("currencyID", mmoneda)
			oamount.Text = Alltrim(Str(C_IES_FORM.valftva, 15, 2))
*!*			If _Tally > 0
*!*				oorderlinereference = oinvoiceline.appendchild(oxml.createelement("cac:OrderLineReference"))
*!*				oorderlinereference.appendchild(oxml.createelement("cbc:LineID"))
*!*				oorderlinereference.lastchild.Text =  ALLTRIM(agetcomenzilinie(1, 2)) + "/" + ALLTRIM(Dtoc(agetcomenzilinie(1, 3)))
*!*			Endif

			* Daca am discount (valftvai valoare de lista <> valftva valoare factura)
*!*				<cac:AllowanceCharge>
*!*					<cbc:ChargeIndicator>false</cbc:ChargeIndicator>
*!*					<cbc:AllowanceChargeReasonCode>95</cbc:AllowanceChargeReasonCode>
*!*					<cbc:MultiplierFactorNumeric>35.00</cbc:MultiplierFactorNumeric>
*!*					<cbc:Amount currencyID="RON">17.33</cbc:Amount>
*!*					<cbc:BaseAmount currencyID="RON">49.52</cbc:BaseAmount>
*!*				</cac:AllowanceCharge>			
			IF TYPE('gnEFACTURA_XML_DISC_PLISTA_LINIE') = 'N' AND m.gnEFACTURA_XML_DISC_PLISTA_LINIE = 1 AND m.lnPretftvai > m.lnPretftva
				oAllowance = oinvoiceline.appendchild(oxml.createelement("cac:AllowanceCharge"))

				oAllowance.appendchild(oxml.createelement("cbc:ChargeIndicator"))
				oAllowance.lastchild.Text = 'false'
				
				oAllowance.appendchild(oxml.createelement("cbc:AllowanceChargeReasonCode"))
				oAllowance.lastchild.Text = '95'

				oAllowance.appendchild(oxml.createelement("cbc:MultiplierFactorNumeric"))
				oAllowance.lastchild.Text = ALLTRIM(STR(m.lnProcDisc,5,2))

				oAmount = oAllowance.appendchild(oxml.createelement("cbc:Amount"))
				oAmount.setattribute("currencyID", mmoneda)
				oAmount.Text = Alltrim(Str(m.lnValDisc, 15, 2))

				oBaseAmount = oAllowance.appendchild(oxml.createelement("cbc:BaseAmount"))
				oBaseAmount.setattribute("currencyID", mmoneda)
				oBaseAmount.Text = Alltrim(Str(m.lnValftvai, 15, 2))				
			ENDIF 

			oitem = oinvoiceline.appendchild(oxml.createelement("cac:Item"))
			If  !Empty(m.lcTextDescriere)
				oitem.appendchild(oxml.createelement("cbc:Description"))
				oitem.lastchild.Text = m.lcTextDescriere
			Endif
			If !Empty(C_IES_FORM.denumire)
				oitem.appendchild(oxml.createelement("cbc:Name"))
				lcText = LEFT(XmlSpecialCharacters(RemoveCharacters(Alltrim(C_IES_FORM.denumire), .T.)),100) && maxim 100 caractere
				oitem.lastchild.Text = m.lcText
			Endif
			If !Empty(Nvl(C_IES_FORM.codmatc, ''))
				obuyeritem = oitem.appendchild(oxml.createelement("cac:BuyersItemIdentification"))
				obuyeritem.appendchild(oxml.createelement("cbc:ID"))
				obuyeritem.lastchild.Text = Alltrim(C_IES_FORM.codmatc)
			Endif
			If  !Empty(Nvl(C_IES_FORM.codmat, ''))
				oselleritem = oitem.appendchild(oxml.createelement("cac:SellersItemIdentification"))
				oselleritem.appendchild(oxml.createelement("cbc:ID"))
				oselleritem.lastchild.Text = Alltrim(C_IES_FORM.codmat)
			Endif

			lcCodBare = GetCodBareByIdArticol(C_IES_FORM.id_articol)
			If !Empty(m.lcCodBare)
				ostandarditem = oitem.appendchild(oxml.createelement("cac:StandardItemIdentification"))
				oidstandard = ostandarditem.appendchild(oxml.createelement("cbc:ID"))
				oidstandard.setattribute("schemeID", "0160")
				oidstandard.Text = Alltrim(m.lcCodBare)

				oclassificationcodbare =  oitem.appendchild(oxml.createelement("cac:CommodityClassification"))
				ocodbare = oclassificationcodbare.appendchild(oxml.createelement("cbc:ItemClassificationCode"))
				ocodbare.setattribute("listID", "EN")
				ocodbare.Text = Left(Alltrim(m.lcCodBare), 13)
			Endif

			If  !Empty(Nvl(C_IES_FORM.serie, ''))
				oclassificationlot =  oitem.appendchild(oxml.createelement("cac:CommodityClassification"))
				olot = oclassificationlot.appendchild(oxml.createelement("cbc:ItemClassificationCode"))
				olot.setattribute("listID", "BB")
				olot.Text = Alltrim(Left(XmlSpecialCharacters(RemoveCharacters(C_IES_FORM.serie, .T.)), 50))
			Endif

			If  !Empty(Nvl(C_IES_FORM.codcpv, ''))
				oclassificationnc = oitem.appendchild(oxml.createelement("cac:CommodityClassification"))
				oclassificationstandardidnc =  oclassificationnc.appendchild(oxml.createelement("cbc:ItemClassificationCode"))
				oclassificationstandardidnc.setattribute("listID", "STI")
				oclassificationstandardidnc.Text = Alltrim(C_IES_FORM.codcpv)
			Endif

			If  !Empty(Nvl(C_IES_FORM.codnc8, ''))
				oclassificationnc = oitem.appendchild(oxml.createelement("cac:CommodityClassification"))
				oclassificationstandardidnc =  oclassificationnc.appendchild(oxml.createelement("cbc:ItemClassificationCode"))
				oclassificationstandardidnc.setattribute("listID", "TSP")
				oclassificationstandardidnc.Text = Alltrim(C_IES_FORM.codnc8)
			Endif

			oitemtaxcategory = oitem.appendchild(oxml.createelement("cac:ClassifiedTaxCategory"))
*!*				Select tip From C_TVA_FACTURA ;
*!*					Where proc_tva = (C_IES_FORM.proc_tva - 1) * 100 ;
*!*					Into Array agettipcota
*!*				lcTip = Alltrim(agettipcota(1))

			lcTip = This.GetTipTaxa(mtipfactura, loRec.intracomunitar, loRec.taxare_inversa, loRec.scutit, (loRec.proc_tva -1)*100)
		
			oitemtaxcategory.appendchild(oxml.createelement("cbc:ID"))
			oitemtaxcategory.lastchild.Text =  m.lcTip
			oitemtaxcategory.appendchild(oxml.createelement("cbc:Percent"))
			oitemtaxcategory.lastchild.Text =  Alltrim(Str((C_IES_FORM.proc_tva - 1) * 100, 2, 0))
			oitemtaxscheme = oitemtaxcategory.appendchild(oxml.createelement("cac:TaxScheme"))
			oitemtaxscheme.appendchild(oxml.createelement("cbc:ID"))
			oitemtaxscheme.lastchild.Text = "VAT"
			oitemprice = oinvoiceline.appendchild(oxml.createelement("cac:Price"))
			oitemamount = oitemprice.appendchild(oxml.createelement("cbc:PriceAmount"))
			oitemamount.setattribute("currencyID", mmoneda)
			oitemamount.Text = Alltrim(Str(C_IES_FORM.pretftva, 15, precizie_max_pret_vz))
			
			* Discount unitar pret
*!*	            <cac:AllowanceCharge>
*!*	                <cbc:ChargeIndicator>false</cbc:ChargeIndicator>
*!*	                <cbc:Amount currencyID="RON">8.67</cbc:Amount>
*!*	                <cbc:BaseAmount currencyID="RON">24.76</cbc:BaseAmount>
*!*	            </cac:AllowanceCharge>			
			IF TYPE('gnEFACTURA_XML_DISC_PLISTA_ART') = 'N' AND m.gnEFACTURA_XML_DISC_PLISTA_ART = 1 AND m.lnPretftvai > m.lnPretftva
				oAllowance = oitemprice.appendchild(oxml.createelement("cac:AllowanceCharge"))

				oAllowance.appendchild(oxml.createelement("cbc:ChargeIndicator"))
				oAllowance.lastchild.Text = 'false'
				
				oAmount = oAllowance.appendchild(oxml.createelement("cbc:Amount"))
				oAmount.setattribute("currencyID", mmoneda)
				oAmount.Text = Alltrim(Str(ABS(m.lnDiscftva), 15, 4))

				oBaseAmount = oAllowance.appendchild(oxml.createelement("cbc:BaseAmount"))
				oBaseAmount.setattribute("currencyID", mmoneda)
				oBaseAmount.Text = Alltrim(Str(ABS(m.lnPretftvai), 15, 4))				
			ENDIF 			
			
		Endscan


		Wait Window 'Salvare fisier XML...' Nowait

		lcCaleFisier = GetPdfPath("Efactura") 

		lcNumeClient = WindowsSpecialCharacters(Nvl(loClient.denumireclient, ''), "_")
		lcNumeClient = Strtran(Alltrim(m.lcNumeClient), [ ], [_], 1, 100, 1)
		lcNumeClient = ALLTRIM(LEFT(WindowsSpecialCharacters(m.lcNumeClient, "_"), 70))		

		lcNumeFisier = 'efactura_' + Dtos(loDate.dataact) + '_' + Alltrim(Str(loDate.nract)) + '_' + m.lcNumeClient

		lcFileName = m.lcCaleFisier + lcNumeFisier + '.xml'
		
		If File(m.lcFileName)
			Delete File (m.lcFileName)
		Endif

* scriu fisierul xml
		oxml.Save(m.lcFileName)
		If File(m.lcFileName)
			Return m.lcFileName
		Else
			AMESSAGEBOX('Nu s-a putut salva fisierul ' + m.lcFileName, 0 + 48, _Screen.Caption)
			Return ''
		Endif

	Endproc && XMLEFactura
	
	
	* GetTipTaxa: intoarce Tip Taxa
	* tcExplicatie, tcMotiv pentru tip E scutit: optional OUT
	* lcTip = This.GetTipTaxa('F', 1, 0, 0, 0, @lcExplicatie, @lcMotiv, lcExplicatieTVA)
	PROCEDURE GetTipTaxa
		LPARAMETERS tcTipFactura, tnIntracomunitar, tnTaxareInversa, tnScutit, tnProcTva, tcExplicatie, tcMotiv, tcExplicatieTVA
		* tcExplicatieTVA (optional): pentru completarea tcExplicatie pentru Scutit, ca sa nu mai fie la toate "scutit cu drept de deducere"

		lcTip = ''
		tcExplicatie = ''
		tcMotiv = ''
		lcTipFactura = UPPER(ALLTRIM(NVL(m.tcTipFactura, '')))
		llIntracomunitar = (tnIntracomunitar = 1)
		llTaxareInversa = (tnTaxareInversa = 1)
		llScutit = (tnScutit = 1)
		lnProcTva = m.tnProcTva
		
		Do Case
			Case m.llIntracomunitar
				lcTip = 'K'
				tcExplicatie = 'Livrare intracomunitara'
				tcMotiv = 'VATEX-EU-IC'
			Case m.llTaxareInversa
				lcTip = 'AE'
				tcExplicatie = 'Taxare inversa'
				tcMotiv = 'VATEX-EU-AE'
			Case m.llScutit
				lcTip = 'E'
				tcExplicatie = IIF(!EMPTY(m.tcExplicatieTVA) and TYPE('tcExplicatieTVA') = 'C', m.tcExplicatieTVA, 'Scutit cu drept de deducere')
			Case m.lcTipFactura = 'F' And m.lnProcTva = 0
				lcTip = 'Z'
			Case m.lcTipFactura = 'H'
				lcTip = 'E'
				tcExplicatie = 'Bunuri second-hand'
				tcMotiv = 'VATEX-EU-F'
			Case m.lcTipFactura = 'U'
				lcTip = 'E'
				tcExplicatie = 'Regim special agentii de turism'
				tcMotiv = 'VATEX-EU-D'
			Otherwise
				lcTip = 'S'
		Endcase	
		
		RETURN m.lcTip
	ENDPROC && GetTipTaxa
*********
*******************************
* Validare eFactura online ANAF sau offline DukIntegrator
* OUT PARAMETER: mesaj eroare
* RETURN: .T. VALID, .F. INVALID
*******************************
	Procedure ValidareEFactura
		Lparameters tcFileName, tcMesaj, tlValidareEFacturaOnline

		Local llValid

		llValid = .F.

* tlOnline: (implicit .F.) .T. daca se valideaza xml eFactura Online
		If Pcount() < 3 Or !m.tlValidareEFacturaOnline
			llValid = This.ValidareEFacturaDUK(tcFileName, @tcMesaj)
		Else
			llValid = This.ValidareEFacturaANAF(tcFileName, @tcMesaj)
		Endif
		Return m.llValid
	Endproc

	Procedure ValidareEFacturaDUK
		Lparameters tcFileName, tcMesaj
* tcMesaj: OUT mesaj daca validarea este silentioasa

		Local lcFileName, lcFisierRaspuns, lnTimes
		Local lcComunPath, lcConfigDir, lcParams, lcValidator, llOk, lcMesaj
		lcMesaj = ''
		lcFileName = m.tcFileName
		llOk = .F.
		llSilentios = This.lSilentios

		Wait Window 'Validare fisier ' + m.lcFileName Nowait
		lcFisierRaspuns = Forceext(m.lcFileName, 'txt')
		If File(m.lcFisierRaspuns)
			Delete File (m.lcFisierRaspuns)
		Endif

* validez xml
		lcComunPath = m.gcBasePath + Iif(gcAppName = "CONCONT", "COMUNCONTAFIN\", "COMUNROA\")
		lcValidator = m.lcComunPath + [dist_efactura\DUKIntegrator.jar] && ROA\COMUNROA\DIST_EFACTURA\DUKIntegrator.jar
		If !File(m.lcValidator)
			open_default_app('https://mfinante.gov.ro/web/efactura/informatii-tehnice')
			AMESSAGEBOX('Nu exista fisierul: "' + m.lcValidator + '"!' + Chr(13) + Chr(10) + ;
				  'Pentru validare xml Efactura, instalati validatorul Efactura in directorul: "' + Justpath(m.lcValidator) + '"', 0 + 48, _Screen.Caption)
		Else
			lcConfigDir = 	m.lcComunPath + [dist_efactura\config]
			lcParams = ' -c "' + m.lcConfigDir + '" -v FACT1 "' +  m.lcFileName + '" "' +  m.lcFisierRaspuns + '"'

			open_default_app(m.lcValidator, m.lcParams)

			lnTimes = 0
			Do While lnTimes <= 10 And !File(m.lcFisierRaspuns)
				lnTimes = lnTimes + 1
				Wait Window Timeout 1 ""
			Enddo
			If File(m.lcFisierRaspuns)
				If Lower(Filetostr(m.lcFisierRaspuns)) = "ok"
					lcMesaj = "Factura este valida. O puteti încarca prin SPV, la sectiunea 'Factura electronica', cu optiunea de sintaxa XML - UBL" + Chr(13) + Chr(10) + m.lcFileName
					If !m.llSilentios
						AMESSAGEBOX(m.lcMesaj, 0 + 48, _Screen.Caption)
					Endif
					Delete File(m.lcFisierRaspuns)
					llOk = .T.
				Else
					lcMesaj = 'Validare cu erori fisier: ' + m.lcFileName

					If !m.llSilentios
						AMESSAGEBOX(m.lcMesaj, 0 + 48, _Screen.Caption)
						open_default_app(m.lcFisierRaspuns)
					Endif
					lcMesaj = m.lcMesaj +  + Chr(13) + Chr(10) + ;
						'Fisier raspuns: ' + m.lcFisierRaspuns + Chr(13) + Chr(10) + Chr(13) + Chr(10) ;
						+ Filetostr(m.lcFisierRaspuns)  + Chr(13) + Chr(10)  + Chr(13) + Chr(10)
				Endif
			Else
				lcMesaj = 'Nu s-a creat fisierul raspuns ' + m.lcFisierRaspuns + ' dupa validare!'
				If !m.llSilentios
					AMESSAGEBOX(m.lcMesaj, 0 + 48, _Screen.Caption)
				Endif
			Endif
		Endif

*** deschid explorer in directorul de export
		If !m.llSilentios
			open_default_app(Justpath(m.lcFileName))
		Endif

		tcMesaj = m.lcMesaj
		Return m.llOk
	Endproc && ValidareEFacturaDUK

	Procedure ValidareEFacturaANAF
		Lparameters tcFileName, tcMesaj
* tcMesaj: OUT mesaj daca validarea este silentioasa
* lReturn: .T. valid, .F. invalid
		Local loReturn, llValid
		Local loHTTP As 'winHTTP.winHTTPrequest.5.1'
		Local lcFileName, lcFisierRaspuns, lcMesaj, lcSend, lcServer, lcStare, llOk, llSilentios, llSucces
		Local lnMesaj, lnMesaje, loJson, loMessage, loEx as Exception, lcToken
		
		llValid = .F.
		lcMesaj = ''
		lcFileName = m.tcFileName
		llOk = .F.
		llSilentios = This.lSilentios
		lcMesaj = ''
		lcToken = This.cToken
		
		loReturn = Createobject("empty")
		AddProperty(loReturn, "lSucces", .F.)
		AddProperty(loReturn, "cFile", '')
		AddProperty(loReturn, "cResponse", '')
		AddProperty(loReturn, "nStatus", 0)

		Wait Window 'Validare fisier ' + m.lcFileName Nowait
		lcFisierRaspuns = Forceext(m.lcFileName, 'txt')
		If File(m.lcFisierRaspuns)
			Delete File (m.lcFisierRaspuns)
		Endif

* validez xml

		If !Empty(m.lcFileName) And Type('lcFileName') = 'C' And File(m.lcFileName)
			TRY 
				lcSend = Filetostr(m.lcFileName)
				
				IF !EMPTY(m.lcToken)
					*  validare oauth
					lcServer = [https://api.anaf.ro/prod/FCTEL/rest/validare/FACT1]
				ELSE 
					* validare fara autentificare
					lcServer = [https://webservicesp.anaf.ro/prod/FCTEL/rest/validare/FACT1]
				ENDIF 	
				
				loHTTP = Createobject('winHTTP.winHTTPrequest.5.1')
				loHTTP.Open('POST', lcServer, .F.)
				loHTTP.setRequestHeader("Content-Type", "text/plain")
				IF !EMPTY(m.lcToken) && validare oauth
					loHTTP.setRequestHeader('Authorization', 'Bearer ' + m.lcToken)
				ENDIF 
				Try
					poLog.Log(m.lcServer)
				Catch
				Endtry
				loHTTP.Send(m.lcSend)

				loReturn.nStatus = loHTTP.Status
				loReturn.cResponse = loHTTP.ResponseText
				loReturn.lSucces = (loHTTP.Status = 200)
			CATCH TO loEx
				loReturn.cResponse = m.lcMesaj + Chr(13) + Chr(10) + '<errorMessage="' + loEx.message + '">'
				loReturn.lSucces = .F.			
			ENDTRY 	

		Else
			loReturn.cResponse = m.lcMesaj + Chr(13) + Chr(10) + '<errorMessage="Nu exista fisierul' + m.lcFileName + '">'
			loReturn.lSucces = .F.
		Endif

		If loReturn.lSucces
			loJson = nfjsonread(loReturn.cResponse)
			If Type('loJson.stare') = 'C' And !Empty(loJson.stare)
				lcStare = Alltrim(Lower(loJson.stare))
				llValid = (m.lcStare == 'ok')
				If !m.llValid
					If Type('loJson.messages_vfpsafe_') = 'U'
						llSucces = .F.
						lcMesaj = 'Nu exista informatia [messages] in raspuns.' + Chr(13) + Chr(10) + loReturn.cResponse
					Else
						lnMesaje = Alen(loJson.messages_vfpsafe_)
						lcMesaj = ''
						For lnMesaj = 1 To m.lnMesaje
							loMessage = loJson.messages_vfpsafe_[m.lnMesaj]
							If Type('loMessage.message') = 'C'
								lcMesaj = lcMesaj + loMessage.Message + Chr(13) + Chr(10)
							Endif
						Endfor
					Endif && messages

					If !m.llSilentios And !Empty(m.lcMesaj)
						AMESSAGEBOX(m.lcMesaj, 0 + 48, _Screen.Caption)
					Endif

				Else
					lcMesaj = "Factura este valida. O puteti încarca prin SPV, la sectiunea 'Factura electronica', cu optiunea de sintaxa XML - UBL" + Chr(13) + Chr(10) + m.lcFileName
					If !m.llSilentios
						AMESSAGEBOX(m.lcMesaj, 0 + 48, _Screen.Caption)
					Endif
				Endif && llValid
			Endif && loJson.stare
		Endif && loReturn.lSucces

*** deschid explorer in directorul de export
		If !m.llSilentios
			open_default_app(Justpath(m.lcFileName))
		Endif

		tcMesaj = m.lcMesaj
		Return m.llValid
	Endproc && ValidareEFacturaANAF

Enddefine && ExportEFactura





PROCEDURE TestValidareEFactura
	
	Local loExport As 'ExportEFactura'
	Local lcFile, llValid, lcMesaj, llOnline
	lcMesaj = ''
	llOnline = .T.
	lcFile = 'f:\efactura_rompetrol.xml'
	loExport = CREATEOBJECT('ExportEFactura')
	SET STEP ON 
	llValid = loExport.ValidareEFactura(m.lcFile, @lcMesaj, m.llOnline)
	
ENDPROC && TestValidareEFactura                       