#Define TIP_TRANZIT 'TRANZIT'
#Define TIP_CHEIAJ 'CHEIAJ'
#Define TIP_APA 'APA'
#Define TIP_CHIRII 'CHIRII'
#Define TIP_PILOTAJ 'PILOTAJ'
#Define TIP_ALTE 'ALTE'
#Define TIP_PENALITATI 'PENALITATI'
#Define TIP_DIVERSE 'DIVERSE'

#Define NTIP_TRANZIT 0
#Define NTIP_CHEIAJ 1
#Define NTIP_APA 2
#Define NTIP_CHIRII 3
#Define NTIP_PILOTAJ 4
#Define NTIP_ALTE 5
#Define NTIP_PENALITATI 6
#Define NTIP_DIVERSE 9

*!*	29.10.2019
*!*	marius.mutu
*!* factura_salvare_db - initializeaza_date_factura(tip_factura, id_beneficiar)

*!*	08.01.2020
*!*	marius.mutu
*!*	vizualizare_tarife_contracte - se salveaza ctr_articole.valoare

*!* 08.01.2020
*!* marius.mutu
*!* STERG_CHEIAJ - corectare eroare la stergere din IPS_BERTHING_DETAILS_VANZARI - se stergeau toate inregistrarile
*!*	vizualizare_tranzit, calcul_cheiaj, salvare_cheiaj, listeaza_recapitulatie_cheiaj - completare ips_voyages_vanzari.document

*!* 09.01.2020
*!* marius.mutu
*!* make_cheiaj_prestatii + id_locatia, locatia

*!* GetObiectTVA - + tnIdJtvaColoana 
*!* make_factura_penalitati - explicatia tva Neimpozabil (id_jtva_coloana = 12)

*!* completeaza_actactan - completez partener pentru contul 419 (4111 = 419)

*!* 03.02.2020
*!* completeaza_regdoc_tranzit, vizualizare_tranzit_nave se tine cont ca ips_voyage_locks (ecluzarile) este acum defalcat pe membrii convoi, nu doar pe convoi

*!* 19.03.2020
*!* salvare_cheiaj - se salveaza numele navei suprascris de utilizator daca difera de numele din ips_vessels
*!* pentru facturarea convoiului generic "FARA" DECLARATIE

*!* calcul_penalitati2 - s-a inclus vanzari.tip
*!* + completeaza_regdoc_penalitati - defalcare cregdoc penalitati pe locatii si articole pentru inregistrarea in contabilitate
*!* make_factura_penalitati - se completeaza data referinta in denumirea articolului

*!* 13.04.2020
*!* marius.mutu
*!* + CopyDeclCdtPdf - copiere declaratii comandant pdf in directorul cu facturi

*!* 01.06.2020
*!*	completeaza_actactan - centralizare note tva pe cote tva. pentru ca la defalcarea facturilor de tranzit pe camere/sasuri se generau tva-uri individuale cu aceeasi cota, am centralizat sumele tva pe cote

*!*	17.06.2020
*!*	completeaza_actactan - am corectat id_jtva_coloana pentru notele de TVA. Au ramas gresit Livrare in loc de TVA livrare de la modificarea din 01.06.2020

*!* 06.07.2020
*!* marius.mutu
*!* completeaza_regdoc_cheiaj - in cRegdoc se salva doar ultimul voiaj, in cazul incare era o factura pentru mai multe istorice de cheiaj


*!*	22.09.2020
*!* calcul_tranzit: am calculat tarifele la capacitatea totala a convoiului, nu numai la capacitatea navelor alese pentru factura curenta
*!* listeaza_recapitulatie_tranzit:
*!*	Selectez capacitatea totala a convoiului, nu numai a navelor de pe factura curenta.
*!*	Este posibil sa fac facturi catre clienti diferiti pe un singur convoi.

*!*	09.10.2020
*!* listeaza_recapitulatie_tranzit:
*!* Am luat capacitatea totala de pe toate facturile de pe un convoi, dar distinct nave. 
*!* Era posibil sa am si facturi de stornare si facturi refacute pe acelasi convoi si se duplica capacitatea

*!* 09.02.2020
*!* calcul_penalitati2 - afisez si facturile cu sold < 0
*!* cerere Lacramioara Guta

*!* 28.04.2021
*!* listeaza_recapitulatie_tranzit 
*!* calcul total capacitate convoi. tratare caz in care o factura este stornata si refacturata cu barje cu corectie de TCAP

*!* 09.06.2021
*!* calcul_penalitati_linie, calcul_penalitati2
*!* corectie calcul zile penalitati pentru contractele cu perioada de gratie
*!* recalculare databaza pentru contractele cu perioada de gratie astfel incat, in luna in care se incheie perioada de gratie sa se factureze penalitati si pentru perioada de gratie

*!* 01.10.2021
*!* calcul_penalitati2
*!* s-au inclus incasarile din toata baza de date in loc de luna curenta, daca calculul este facut fata de data scadenta in loc de luna anterioara

*!* 27.03.2022
*!* completare TaxCode SAFT in factura_salvare (crsFactura), factura_salvare_bd (vanzari_detalii), completeaza_actactan (actactan)

*!* 10.01.2023
*!* vizualizare_regdoc (registru documente pe locatii) + document2 (numarul istoric de stationare)


*!*	22.01.2024
*!*	make_factura - pentru pret negativ, se face cantitate negativa si pret pozitiv, pentru eFactura

*!* 09.04.2024
*!* salvare_tranzit - salvare ips_voyage_members_vanzari.marfa_country_id

*!*	21.10.2024
*!*	factura_salvare_db - INITIALIZARE_dATE_FACTURA TIP_SAFT

*!*	23.07.2025
*!*	factura_salvare_db - tratare taxcode = NULL

Procedure vizualizare_regdoc
	Private poRegdoc
	poRegdoc = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam
	Text To lcSchema Noshow
id  N(20), id_vanzare  N(20), tip N(3), cTip C(50), id_articol N(12), articol C(100), id_locatia N(12), locatia C(50), id_valuta N(12), valuta C(20), id_client N(12), client C(70), id_contract N(12), contract C(50), pret N(18,4), curs N(12,4), cantitate N(18,4), valval N(18,4), valftva N(18,4), um C(20), document C(30), data D, document2 C(30), numar_act N(14), data_act D, ctdebitor C(10), ctaideb C(10), ctaedeb C(10), ctcreditor C(10), ctaicred C(10), ctaecred C(10), ctpideb C(10), ctapideb C(10), ctpicred C(10), ctapicred C(10)
	Endtext
	lcOrder = [data, id]
	lcFiltru = [extract(year from data) * 12 + extract(month from data) = ?gnAn*12+?gnLuna]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Noshow
select id,
       id_vanzare,
       tip,
       ctip,
       id_articol,
       articol,
       id_locatia,
       locatia,
       id_valuta,
       valuta,
       id_client,
       client,
       id_contract,
       contract,
       pret,
       curs,
       cantitate,
       valval,
       valftva,
       um,
       document,
       data,
       document2,
       numar_act,
       data_act,
       ctdebitor,
       ctaideb,
       ctaedeb,
       ctcreditor,
       ctaicred,
       ctaecred,
       ctpideb,
       ctapideb,
       ctpicred,
       ctapicred       
  from ips_vregdoc
	Endtext

	gencursor('poRegDoc', 'crsRegdoc', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poRegdoc.ca_baza1.afisare()
	loFrmRegdoc = Createobject("frm_registru") && oacnpro.vcx
	loFrmRegdoc.Show(1)
Endproc && vizualizare_regdoc

******************************************
*** Vizualizare convoaie si date facturi
******************************************
Procedure vizualizare_tranzit_facturi
	Lparameters tnTip
	* tnTip: 0 = TRANZIT, 1 = CHEIAJ
	Private poConvoaie
	poConvoaie = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam
	lcSchema = []
	lcOrder = [data_act, numar_act]
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = Iif(Pcount() = 0, [], [(tip IS NULL OR ] + Iif(Empty(m.tnTip), [tip=0], [tip=1]) + [)])

	Text To lcSelect Noshow
select 0 as ales,
	   vv_id,
       vz_id,
       vye_id,
       convoy_nam,
       declaratio,
       document,
       generation,
       origin,
       destinatio,
       indicativ,
       client,
       client_id,
       contract_client,
       beneficiar,
       beneficiar_id,
       total_fara_tva,
       total_tva,
       total_cu_tva,
       numar_act,
       serie_act,
       data_act,
       ctip_factura
  from ips_vvanzari_voyages
	Endtext

	gencursor('poConvoaie', 'crsConvoaie', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poConvoaie.ca_baza1.afisare()
	loFrmConvoaie = Createobject("frm_tranzit_facturi", m.tnTip) && oacnpro.vcx
	loFrmConvoaie.Show(1)
Endproc && vizualizare_tranzit_facturi

******************************************
*** Vizualizare convoaie, nave, date facturare
******************************************
Procedure vizualizare_tranzit_nave
	Lparameters tnTip
	* tnTip: 1 = selectie din ips_vanzari_voyage_members, 2 = selectie din ips_vanzari_voyage_members_n
	* 1 = nu calculeaza valori pe sasn/cameran
	* 2 = calculeaza valori pe sasn/cameran, nu se mai foloseste, doar pentru verificari 01/2020-05/2020

	Private poConvoaie
	poConvoaie = Null

	Local lnTip
	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam

	lnTip = Iif(Empty(m.tnTip), 1, m.tnTip)

	lcSchema = []
	lcOrder = [data_act, numar_act, rn, indicativ]
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Textmerge Noshow
select vmv_id,
       vv_id,
       client_id,
       client,
       contract_client,
       client_ctr_id,
       beneficiar_id,
       tiprecap,
       beneficiar,
       intern,
       vz_id,
       serie_act,
       numar_act,
       data_act,
       cuplat,
       arm_id,
       armator,
       kmi,
       kmf,
       rte_id,
       ruta,
       convoy_nam,
       declaratio,
       generation,
       vye_id,
       aviz,
       data_aviz,
       origin,
       destinatio,
       vms_id,
       vsl_id,
       ctt_id,
       dirty_tank,
       rstart_id,
       rfin_id,
       distanta,
       distanta_cdmn,
       distanta_pamn,
       contact,
       indicativ,
       nava_country,
       nava_country_id,       
       lbd,
       trn,
       hp,
       tcap,
       tcap_conv,
       procdiv,
       vtp_id,
       tip_nava,
       vgrp_id,
       grupa_nava,
       marfa,
       cant_marfa,
       um_marfa,
       gds_id,
       grp_id,
       grupa_marfa,
       periculos,
       corect,
       procdist,
       id_valuta,
       valuta,
       tarif,
       cant,
       um,
       marfa_country,
       marfa_country_id,       
       valval,
       tvaval,
       totval,
       valftva,
       valtva,
       valctva,
       curs,
       agigea,
       cernavoda,
       navodari,
       ovidiu,
       agigea_data,
       cernavoda_data,
       navodari_data,
       ovidiu_data,
       agigea_sas1,
       agigea_sas2,
       agigea_sasn,
       cernavoda_sas1,
       cernavoda_sas2,
       cernavoda_sasn,
       ovidiu_c1,
       ovidiu_c2,
       ovidiu_cn,
       navodari_c1,
       navodari_c2,
       navodari_cn,
       agigea1_valoare,
       agigea2_valoare,
       agigean_valoare,
       cernavoda1_valoare,
       cernavoda2_valoare,
       cernavodan_valoare,
       ovidiu1_valoare,
       ovidiu2_valoare,
       ovidiun_valoare,
       navodari1_valoare,
       navodari2_valoare,
       navodarin_valoare,
       senal_cdmn1_valoare,
       senal_pam1_valoare,
       agigea_valoare,
       cernavoda_valoare,
       ovidiu_valoare,
       navodari_valoare,
       senal_cdmn_valoare,
       senal_pam_valoare,
       rn,
       pvalftva
  from <<IIF(m.lnTip = 1, 'ips_vanzari_voyage_members', 'ips_vanzari_voyage_members_n')>>
	Endtext

	gencursor('poConvoaie', 'crsConvoaie', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poConvoaie.ca_baza1.afisare()

	loFrmConvoaie = Createobject("frm_tranzit_nave") && oacnpro.vcx
	loFrmConvoaie.Show(1)
Endproc && vizualizare_tranzit_nave



******************************************
*** Registru Cheiaj Nave. Vizualizare convoaie, nave, date facturare
******************************************
Procedure vizualizare_cheiaj_nave
	Private poCheiaje
	poCheiaje = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam

	lcSchema = []
	lcOrder = [an,luna,data_act,numar_act,client,contract]
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Textmerge Noshow
select an,
       luna,
       serie_act,
       data_act,
       numar_act,
       client,
       contract,
       beneficiar,
       total_fara_tva,
       port,
       declaratie,
       document,
       vas,
       tip_vas,
       grupa_vas,
       dana,
       ctip,
       cant,
       um,
       tarif,
       articol,
       datai,
       datap,
       durata,
       valftva,
       valtva,
       valctva,
       nume_val,
       curs,
       valval,
       tvaval,
       totval,
       cap,
       trn,
       lung,
       cp,
       lbd,
       zi,
       cap_val,
       trn_val,
       lung_val,
       cp_val,
       lbd_val,
       zi_val
  from ips_vanzari_cheiaje_members
	Endtext

	gencursor('poCheiaje', 'crsCheiaje', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poCheiaje.ca_baza1.afisare()

	loFrmCheiaje = Createobject("frm_cheiaje_nave") && oacnpro.vcx
	loFrmCheiaje.Show(1)
Endproc && vizualizare_cheiaj_nave

******************************************
*** Vizualizare convoaie si selectie unul sau mai multe in scopul facturarii
*** Se apeleaza din factura
******************************************
Procedure vizualizare_tranzit
	Lparameters tnTip
	* tnTip: 0 = TRANZIT, 1 = CHEIAJ

	Private poConvoaie
	poConvoaie = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam
	lcSchema = []
	lcOrder = [declaratio]
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Noshow
select 0 as ales,
	   id,
	   vye_id,
       generation,
       vms_id,
       convoy_nam,
       declaratio,
       notificati,
       data_avizare,
       notificat2,
       avizare,
       origin,
       destinatio,
       mtr_name,
       state,
       indicativ,
       cast('' as Varchar2(50)) as document
  from ips_vvoyages
	Endtext

	gencursor('poConvoaie', 'crsConvoaie', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poConvoaie.ca_baza1.afisare()
	loFrmConvoaie = Createobject("frm_tranzit", m.tnTip) && oacnpro.vcx
	loFrmConvoaie.Show(1)

	llSucces = (m.gnButon = 1)
	Return m.llSucces
Endproc && vizualizare_tranzit

******************************************
*** Vizualizare contracte si selectie unul sau mai multe in scopul facturarii
*** Se apeleaza din factura
*** De fapt primeste din factura id_ctr si lanseaza direct calcul_contract
******************************************
Procedure vizualizare_contract
	Lparameters tnIdCtr
	Local llSucces
	llSucces = calcul_contract(m.tnIdCtr)

	Return m.llSucces
Endproc && vizualizare_contract


Procedure vizualizare_penalitati
	Lparameters tnTipCalcul, tnCalculZile
	* tnTipCalcul: 1 (default) = incasari si sold; 2 = incasari; 3 = sold; 4 = evaluare
	* tnCalculZile: 1 (default) = calcul zile fata de luna precedenta; 2 = fata de data scadenta


	Private pdDataReferinta, pnCalculZile, pnTipCalcul, pl4118, plFacturate, plSterse
	Local loPenalitati As "frm_penalitati"
	Local loRec
	Local lnZileProcent1, lnZileProcent2, lnPenalitati

	pdDataReferinta = Gomonth(Date(m.gnAn, m.gnLuna, 1), 1) - 1
	pnTipCalcul = Iif(Empty(m.tnTipCalcul), 1, m.tnTipCalcul)
	pnCalculZile = Iif(Empty(m.tnCalculZile), 1, m.tnCalculZile)
	pl4118 = .F.
	plFacturate = .F. && se includ documentele (facturi, incasari) deja facturate? ex: daca se doreste stornarea si refacturarea penalitatilor
	plSterse = .F. && se includ documentele sterse de utilizator

	Private pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru
	Store "" To pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru

	Do make_contracte && crsContracte
	Do make_valute && crsValute

	Use In (Select('crsCalculPenalitati'))
	Use In (Select('crsClientiPenalitati'))
	make_cCalculPenalitati()
	make_cClientiPenalitati()

	Select crsCalculPenalitati
	loPenalitati = Createobject("frm_penalitati")
	loPenalitati.lEvaluare = .T.
	loPenalitati.dDataReferinta = m.pdDataReferinta
	If m.pnTipCalcul = 3 && evaluare
		loPenalitati.lb_titlu_alb_b121.Caption = 'Penalitati - evaluare la ' + Dtoc(m.pdDataReferinta)
		loPenalitati.grdPenalitati.cNrDoc.Visible = .F.
		loPenalitati.grdPenalitati.cSuma.Header1.Caption = 'Sold restant'
		loPenalitati.grdPenalitati.cDataDoc.Header1.Caption = 'Data referinta'
		loPenalitati.cmd_Executa1.Visible = .F.
	Endif

	loPenalitati.Show(1)

	Use In (Select('crsCalculPenalitati'))
	Use In (Select('crsClientiPenalitati'))

	Return (m.gnButon = 1)
Endproc && vizualizare_penalitati

Procedure configurare_articole_conturi

	Local loFrmConturi As "frm_configurare_articole_conturi"
	Local lcSelectV, lcSql, lcSqlDelete, lcSqlInsert, lcSqlUpdate, llScris, llSucces, llSucces2
	Local lnModificat, lnRec
	Private poRec
	*:Global gnButon

	lcSelectV = Select()

	Do make_locatii && crsLocatii

	lcSql = [select id_articol, codmat, denumire, descriere, um, id_grupa, grupa, id_subgrupa, subgrupa, tip from vnom_articole where inactiv = 0 and tip = 1 order by denumire]
	llSucces = goExecutor.oExecuta(m.lcSql, 'crsArticole')

	If m.llSucces
		Select crsArticole
		Index On denumire Tag denumire

		lcSql = [select id, id_articol, articol, id_locatia, locatia, ctdebitor, ctcreditor, ctaideb, ctaedeb, ctaicred, ctaecred, ctpideb, ctapideb, ctpicred, ctapicred, 0 as modificat from ips_vprestatii_locatii order by articol, locatia]
		llSucces = goExecutor.oExecuta(m.lcSql, 'crsConturi')
	Endif

	If m.llSucces
		Select crsArticole
		loFrmConturi = Createobject("frm_configurare_articole_conturi") && oacnpro.vcx
		loFrmConturi.Show(1)
	Else
		gnButon = 2
	Endif

	lcSqlDelete = [DELETE from ips_prestatii_locatii WHERE id = ?poRec.Id]

	Text To lcSqlInsert Noshow
  INSERT INTO ips_prestatii_locatii
    (id_articol,
     id_locatia,
     ctdebitor,
     ctcreditor,
     ctaideb,
     ctaedeb,
     ctaicred,
     ctaecred,
     ctpideb,
     ctapideb,
     ctpicred,
     ctapicred)
  values
    (?poRec.id_articol,
     ?poRec.id_locatia,
     ?poRec.ctdebitor,
     ?poRec.ctcreditor,
     ?poRec.ctaideb,
     ?poRec.ctaedeb,
     ?poRec.ctaicred,
     ?poRec.ctaecred,
     ?poRec.ctpideb,
     ?poRec.ctapideb,
     ?poRec.ctpicred,
     ?poRec.ctapicred)
	Endtext

	Text To lcSqlUpdate Noshow
  UPDATE ips_prestatii_locatii
     set id_articol = ?poRec.id_articol,
         id_locatia = ?poRec.id_locatia,
         ctdebitor  = ?poRec.ctdebitor,
         ctcreditor = ?poRec.ctcreditor,
         ctaideb    = ?poRec.ctaideb,
         ctaedeb    = ?poRec.ctaedeb,
         ctaicred   = ?poRec.ctaicred,
         ctaecred   = ?poRec.ctaecred,
         ctpideb    = ?poRec.ctpideb,
         ctapideb   = ?poRec.ctapideb,
         ctpicred   = ?poRec.ctpicred,
         ctapicred  = ?poRec.ctapicred
       where id = ?poRec.id  
	Endtext

	* Am apasat (Terminat) sau (Renunt si am sters un articol si trebuie sa sterg si conturile asociate)
	Set Deleted Off
	Select Id From crsConturi Where !Empty(Id) And modificat = 2 And Deleted() Into Cursor cConturiSterse
	Set Deleted On
	If (m.gnButon = 2 And Reccount('cConturiSterse') > 0)
		Select cConturiSterse
		Scan
			Scatter Name poRec
			llSucces = goExecutor.oExecuta(m.lcSqlDelete)
			If !m.llSucces
				Exit
			Endif
		Endscan
	Endif
	Use In (Select('cConturiSterse'))

	If m.gnButon = 1
		Select crsConturi
		Set Filter To

		llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

		If m.llSucces && transactions
			*** SELECTEZ IREG STERSE
			Set Deleted Off
			Select Id From crsConturi Where Deleted() Into Cursor cConturiSterse
			Set Deleted On

			Select cConturiSterse
			Scan
				Scatter Name poRec
				llSucces = goExecutor.oExecuta(m.lcSqlDelete)
				If !m.llSucces
					Exit
				Endif
			Endscan
			Use In (Select('cConturiSterse'))
			*** STERG IN IPS_PRESTATII_LOCATII IREG STERSE

			If m.llSucces
				*** MODIFIC IN ips_prestatii_locatii IREG MODIFICATE IN TEMPORAR
				Calculate Cnt() To m.lnModificat For Nvl(modificat, 0) = 1 In crsConturi

				lnRec = 0
				Select crsConturi
				Scan For Nvl(modificat, 0) = 1
					Scatter Name poRec Memo

					lnRec = m.lnRec + 1
					Wait Window 'Configurare noua/modificata ' + Alltrim(Str(m.lnRec)) + '/' + Alltrim(Str(m.lnModificat)) Nowait

					If Empty(Nvl(poRec.Id, 0))
						llSucces = goExecutor.oExecuta(m.lcSqlInsert)
					Else
						llSucces = goExecutor.oExecuta(m.lcSqlUpdate)
					Endif
					If !m.llSucces
						Exit
					Endif
				Endscan
			Endif && llSucces

			If !m.llSucces
				lcSql = "ROLLBACK"
				llScris = .F.
			Else
				lcSql = "COMMIT"
				llScris = .T.
			Endif
			llScris = goExecutor.oExecuta(m.lcSql)

			llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
			If !m.llSucces2
				amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
			Endif

			llSucces = m.llSucces And m.llScris
		Endif && gnButon

		If m.llSucces
			amessagebox('Configurare articole/conturi modificate cu succes!', 0 + 64, _Screen.Caption)
		Else
			amessagebox('Articole/conturi nu s-au modificat!', 0 + 64, _Screen.Caption)
		Endif
	Endif && gnButon

	Use In (Select('crsLocatii'))

	Use In (Select('crsArticole'))
	Use In (Select('crsConturi'))

	Select (m.lcSelectV)
	Return m.llSucces
Endproc && configurare_articole_conturi

**************************************************************************************************************************
Procedure calcul_tranzit
	Lparameters tcVyeIds

	Private poVoyage, pcVyeIds, pcVyeId, pnVVId
	Local lcEcluzari, lcVoyageLocksText, lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelectV, lcSql, lcTitlu, lcSelect
	Local llAfiseaza, llModParam, llSucces, loFrmTranzit
	Local lcDeclaratie, lcEcluzari2, lcIndicativ, lcVmsId, lnEclDif

	poVoyage = Null
	pnVVId = 0
	llSucces = .F.
	If Empty(Nvl(m.tcVyeIds, ''))
		Return m.llSucces
	Else
		pcVyeIds = m.tcVyeIds
	Endif
	lcSelect = Select()
	Do make_grupe_vase && crsGrupeVase
	Do make_grupe_marfa && crsGrupeMarfa
	*	Do make_contracte With "1=2" && crsContracte
	Do make_contacts && crsContacts
	Do make_vessel_types && crsVesselTypes
	Do make_routes && crsRoutes
	Do make_vas_echivalent	&& crsVasEchivalent
	Do make_vas_um && crsVasUM
	Do make_grup_tip_nave && crsGrupTipNave

	* Creez cursorul crsVoyage
	Select Id, vye_id, generation, vms_id, convoy_nam, declaratio, notificati, data_avizare, notificat2, avizare, origin, destinatio, mtr_name, state, indicativ, Document, ;
		Cast(Null As I) As vv_id, Cast(Null As I) As client_id, Cast(Null As I) As client_ctr_id, 0 As eagent, Cast(Null As I) As beneficiar_id, 0 As tiprecap, 0 As intern, 0 As tip ;
		From crsConvoaie ;
		Where At(['] + Alltrim(vye_id) + ['], m.pcVyeIds) > 0 ;
		Into Cursor crsVoyage Readwrite

	llSucces = (Reccount('crsVoyage') > 0)

	If m.llSucces
		* pun 0 la vmv_id sa inserez de fiecare data, in loc sa suprascriu voiajul, in ips_vvoyage_members_vanzari, in salvare tranzit
		Text To lcSelectV Noshow
select 0 as ales,
	   vv_id,
	   vmv_id,
       tiprecap,
       cuplat,
       arm_id,
       armator,
       kmi,
       kmf,
       rte_id,
       ruta,
       convoy_nam,
       declaratio,
       generation,
       vms_id,
       vye_id,
       vsl_id,
       ctt_id,
       dirty_tank,
       rstart_id,
       rfin_id,
       distanta,
       distanta_cdmn,
       aviz,
       contact,
       indicativ,
       lbd,
       trn,
       hp,
       tcap,
       procdiv,
       vtp_id,
       tip_nava,
       vgrp_id,
       grupa_nava,
       felcargo,
       cargo,
       gds_id,
       gdsg_id,
       marfa_country_id,
       marfa_country,
       grupa_marfa,
       periculos,
       corect,
       procdist,
       id_valuta,
       valuta,
       tarif,
       cant,
       um,
       valval,
       valftva,
       valtva,
       valctva,
       CAST(null as varchar2(200)) as ecluzari,
       0 AS elcdif
  from ips_vvoyage_members_calcul
		Endtext

		lcSchema = [ALES N(1), VV_ID N(20), VMV_ID N(20), TIPRECAP N(1), CUPLAT N(1), ] + ;
			[ARM_ID C(36), ARMATOR C(100), KMI N(7,2), KMF N(7,2), RTE_ID N(10), RUTA C(100), CONVOY_NAM C(100), DECLARATIO C(10), GENERATION T, ] + ;
			[VMS_ID C(36), VYE_ID C(36), VSL_ID C(36), CTT_ID C(36), DIRTY_TANK N(1), ] + ;
			[RSTART_ID C(36), RFIN_ID C(36), DISTANTA N(12,2), DISTANTA_CDMN N(12,2), AVIZ C(20), CONTACT C(100), INDICATIV C(240), ] + ;
			[LBD N(10,2), TRN N(10,2), HP N(10,2), TCAP N(10,2), PROCDIV N(8,3), VTP_ID C(36), TIP_NAVA C(100), VGRP_ID C(36), GRUPA_NAVA C(100), ] + ;
			[FELCARGO C(100), CARGO N(10,2), GDS_ID C(36), GDSG_ID N(10), MARFA_COUNTRY_ID C(36) NULL, MARFA_COUNTRY C(100) NULL, GRUPA_MARFA C(240), PERICULOS N(1), CORECT N(6,3), PROCDIST N(6,3), ] + ;
			[ID_VALUTA N(10), VALUTA C(20), TARIF N(20,4), CANT N(10,2), UM C(10), VALVAL N(20,4), VALFTVA N(20,4), VALTVA N(20,4), VALCTVA N(20,4), ECLUZARI V(200), ECLDIF N(1)]

		lcOrder = []
		lcFiltru = []
		llAfiseaza = .F.
		lcGroup = []
		llModParam = .T.
		lcFiltruOriginal = [vye_id in (] + m.pcVyeIds + [)]

		gencursor('poVoyage', 'crsVoyages', m.lcSelectV, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
		poVoyage.ca_baza1.afisare()
		llSucces = Used('crsVoyages')
	Endif && llSucces

	If m.llSucces
		lcTitlu = 'CALCUL TRANZIT DECLARATIE: '
		lcEcluzari = 'ECLUZARI: '
		Sele crsVoyage
		Scan
			* Titlu
			lcDeclaratie = Alltrim(Nvl(declaratio, ''))
			lcIndicativ = Alltrim(Nvl(convoy_nam, ''))
			lcTitlu = lcTitlu + m.lcDeclaratie + ' - CONVOI: ' + m.lcIndicativ + Iif(Recno() <= Reccount(), '; ', '')

			pcVyeId = Alltrim(vye_id)

			* Selectez ecluzari pe convoi
			Text To lcSql Noshow
select stringagg(trim(replace(upper(lock_name), 'ECLUZA', '')) || ' (' ||
                 TO_CHAR(ldata, 'dd.mm.yyyy hh24:mi') || ')') as ecluzari
  from (select lock_name, MIN("date") as ldata
          from ips_vvoyage_locks
         where vye_id = ?pcVyeId
         group by lock_name
         order by 2)
			Endtext
			lcVoyageLocksText = ''
			llSucces = goExecutor.oSelecteaza2Value(m.lcSql, @lcVoyageLocksText)
			If m.llSucces
				lcEcluzari = m.lcEcluzari + m.lcDeclaratie + ' ' + Alltrim(Nvl(lcVoyageLocksText, '')) + ' '
			Else
				Exit
			Endif

			* Selectez camera ecluzare pe fiecare nava si completez in vrsVoyages
			* atentie = 1 daca eluzarile unei nave nu sunt egale cu ecluzarile convoiului
			Text To lcSql Noshow
select l1.vms_id,
       l1.ecluzari,
       decode(l1.lock_name, l2.lock_name, 0, 1) as ecldif
  from (with lx as (select vm.id as vms_id, "date" as ldata,
                       vl.lock_name,
                       (case
                         when vl.chamber_name is not null then
                          trim(replace(upper(vl.lock_name), 'ECLUZA', '')) || '-' ||
                          vl.chamber_name || ' (' ||
                          TO_CHAR("date", 'dd.mm.yyyy hh24:mi') || ')'
                         else
                          ''
                       end) as ecluza
                  from ips_voyage_members vm
                  left join ips_voyage_locks vl
                    on vm.id = vl.vms_id
                 where vm.vye_id = ?pcVyeId
                 order by vms_id, "date")
          select vms_id,
               concatenate_list(CURSOR(select lock_name from lx lx1 where lx1.lock_name is not null and lx1.vms_id = lx2.vms_id order by ldata)) as lock_name,
               concatenate_list(CURSOR(select ecluza from lx lx1 where lx1.lock_name is not null and lx1.vms_id = lx2.vms_id order by ldata)) as ecluzari
          from lx lx2
         group by vms_id) l1,
       (select concatenate_list(cursor(select lock_name from (select lock_name, min("date") as ldata
                  from ips_voyage_locks
                 where vye_id = ?pcVyeId
                 group by lock_name) order by ldata)) as lock_name  from dual) l2
			Endtext

			llSucces = goExecutor.oExecuta(m.lcSql, 'crsVoyageLocksTemp')
			If m.llSucces
				Select crsVoyageLocksTemp
				Scan
					lcVmsId = vms_id
					lcEcluzari2 = Alltrim(ecluzari)
					lnEclDif = ecldif

					Select crsVoyages
					Locate For vms_id = m.lcVmsId
					If Found()
						Replace ecluzari With m.lcEcluzari2, ecldif With m.lnEclDif
					Endif
				Endscan
				Use In (Select('crsVoyageLocksTemp'))
			Endif
		Endscan
	Endif && llSucces

	If m.llSucces
		Select crsVoyages
		loFrmTranzit = Crea("frm_calcul_tranzit", m.lcTitlu, m.lcEcluzari)
		loFrmTranzit.Show(1)
		llSucces = (m.gnButon = 1)
	Endif

	Use In (Select('crsGrupeVase'))
	Use In (Select('crsGrupeMarfa'))
	Use In (Select('crsContacts'))
	Use In (Select('crsVesselTypes'))
	Use In (Select('crsRoutes'))
	Use In (Select('crsVasEchivalent'))
	Use In (Select('crsVasUM'))
	Use In (Select('crsGrupTipNave'))
	Use In (Select('crsVoyage'))
	Use In (Select('crsVoyages'))

	Select (m.lcSelect)
	Return m.llSucces
Endproc && calcul_tranzit


**************************************************************************************************************************
Procedure calcul_cheiaj
	Lparameters tcVyeIds

	Private pcVyeIds, poBerthings, poBerthingDetails
	Local lcEcluzari, lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelectV, lcSql, lcTitlu
	Local llAfiseaza, llModParam, llSucces, loFrmTranzit, lcSelect
	poBerthings = Null
	poBerthingDetails = Null
	llSucces = .F.

	If Empty(Nvl(m.tcVyeIds, ''))
		Return m.llSucces
	Else
		pcVyeIds = m.tcVyeIds
	Endif
	lcSelect = Select()

	* Do make_contracte With "1=2" && crsContracte
	Do make_aramis_tip_nave && crsAramisTipNave
	Do make_locatii && crsLocatii
	Do make_dane && crsDane
	Do make_articole && crsArticole
	Do make_valute && crsValute
	Do make_cheiaj_prestati && crsCheiajPrestatii

	* Creez cursorul crsVoyage
	Select Id, vye_id, generation, vms_id, convoy_nam, declaratio, notificati, data_avizare, notificat2, avizare, origin, destinatio, mtr_name, state, indicativ, Document, ;
		Cast(Null As I) As client_id, Cast(Null As I) As client_ctr_id, 0 As eagent, Cast(Null As I) As beneficiar_id, 0 As tiprecap, 0 As intern, 1 As tip, ;
		Cast(Null As I) As vv_id, Cast(Null As I) As bv_id ;
		From crsConvoaie ;
		Where At(['] + Alltrim(vye_id) + ['], m.pcVyeIds) > 0 ;
		Into Cursor crsVoyage Readwrite

	llSucces = (Reccount('crsVoyage') > 0)

	*** Import din berthings dupa vye_id
	If m.llSucces
		Text To lcSelectV Noshow
select 0 as ales,
	   id,
       CAST(null as NUMBER(20)) as bv_id,	   
       vye_id,
       declaratio,
       ves_id,
       nava,
       nava as vs_name,
       tipn_id,
       tipn,
       NVL(lbd, 0) as lbd,
       NVL(trn, 0) as trn,
       NVL(hp, 0) as trn,
       NVL(cap, 0) as cap,
       NVL(lung, 0) as cap,
       CAST(null as NUMBER(12)) as id_locatia,
       TIP AS dana_id,
       CTIP AS cdana,
       rpt_id,
       rpt_name,
       datai,
       datap
  from ips_vberthings
		Endtext

		* vs_name este pentru facturarea unei declaratii generice "FARA" si trebuie completat numele navei
		Text To lcSchema Noshow
ales N(1), id C(36), bv_id N(20), vye_id C(36), declaratio C(36), ves_id C(36), nava C(240), vs_name C(240), tipn_id N(7), tipn C(100), lbd N(12,2), trn N(12,2), hp N(12,2), cap N(12,2), lung N(12,2), id_locatia N(12), dana_id N(3), cdana C(20), rpt_id C(36), rpt_name C(100), datai T(8), datap T(8)
		Endtext

		lcOrder = [datai desc,declaratio,nava]
		lcFiltru = []
		llAfiseaza = .F.
		lcGroup = []
		llModParam = .T.
		lcFiltruOriginal = [vye_id in (] + m.pcVyeIds + [)]

		gencursor('poBerthings', 'crsBerthings', m.lcSelectV, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
		poBerthings.ca_baza1.afisare()
		llSucces = Used('crsBerthings')
		If m.llSucces
			Select crsBerthings
			Scan
				lcRptName = Upper(Alltrim(rpt_name))
				If Seek(m.lcRptName, 'crsLocatii', 'denumire')
					Replace crsBerthings.id_locatia With crsLocatii.Id
				Endif
			Endscan
			Go Top
		Endif
	Endif && llSucces


	*** Creez cursor gol berthings_detalii_vanzari pentru completare
	If m.llSucces
		Text To lcSelectV Noshow
select id,
	   bts_id,
	   ves_id,
	   indicativ,
       datai,
       datap,
       id_valuta,
       valuta,
       id_articol,
       tarif,
       cant,
       durata,
       um,
       valval,
       tvaval,
       totval,
       valftva,
       valtva,
       valctva,
       curs
  from ips_vberthing_details_vanzari
		Endtext

		Text To lcSchema Noshow
id N(20), bts_id C(36), ves_id C(36), nava C(100), datai T(8), datap T(8), id_valuta N(7), valuta C(20), id_articol N(10), tarif N(18,4), cant N(12,2), durata N(10,3), um C(10), valval N(18,4), tvaval N(18,4), totval N(18,4), valftva N(18,4), valtva N(18,4), valctva N(18,4), curs N(14,6)
		Endtext

		lcOrder = []
		lcFiltru = [1=2]
		llAfiseaza = .F.
		lcGroup = []
		llModParam = .T.
		lcFiltruOriginal = []

		gencursor('poBerthingDetails', 'crsBerthingDetails', m.lcSelectV, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
		poBerthingDetails.ca_baza1.afisare()
		llSucces = Used('crsBerthingDetails')

	Endif && llSucces

	If m.llSucces
		Sele crsVoyage
		Go Top
		lcTitlu = 'CALCUL CHEIAJ DECLARATIE: ' + Alltrim(Nvl(declaratio, '')) + ' - CONVOI: ' + Alltrim(Nvl(convoy_nam, ''))


		Select crsVoyage
		*		Do Form frm_calcul_cheiaj Name loFrmTranzit With m.lcTitlu
		loFrmTranzit = Crea("frm_calcul_cheiaj", m.lcTitlu)
		loFrmTranzit.Show(1)
		llSucces = (m.gnButon = 1)
	Endif

	Use In (Select('crsGrupeVase'))
	Use In (Select('crsGrupeMarfa'))
	Use In (Select('crsContacts'))
	Use In (Select('crsVesselTypes'))
	Use In (Select('crsRoutes'))
	Use In (Select('crsVasEchivalent'))
	Use In (Select('crsVasUM'))
	Use In (Select('crsGrupTipNave'))
	Use In (Select('crsVoyage'))
	Use In (Select('crsVoyages'))

	Select (m.lcSelect)
	Return m.llSucces

Endproc && calcul_cheiaj

**************************************************************************************************************************
Procedure calcul_contract
	Lparameters tnIdCtr

	Local lcSql, lcTitlu, llSucces, loFrmContract, lcSelect
	Private pnIdCtr
	llSucces = .F.
	lcSelect = Select()

	pnIdCtr = Iif(!Empty(Nvl(m.tnIdCtr, 0)), m.tnIdCtr, 0)
	Use In (Select('crsArticoleContract'))
	Text To lcSql Textmerge Noshow
select id_part, client, contract_client, id_ctr, id_articol, articol, CAST(' ' as Varchar2(100)) as perioada, um, pret_unitar as pret, cant as cantitate, ROUND(valoare, ?gnPC) as valval, id_valuta, valuta, id_locatia, locatia, proc_tvav
	from vctr_articole2 
	where id_ctr = <<m.pnIdCtr>>
	order by locatia, articol
	Endtext

	llSucces = goExecutor.oExecuta(m.lcSql, 'crsArticoleContract')

	If m.llSucces
		Sele crsArticoleContract
		Go Top
		lcTitlu = 'CALCUL CONTRACT: ' + Alltrim(Nvl(contract_client, '')) + ' - ' + Alltrim(Nvl(client, ''))

		loFrmContract = Crea("frm_calcul_contract", m.lcTitlu)
		loFrmContract.Show(1)
		llSucces = (m.gnButon = 1)
	Endif

	Use In (Select('crsArticoleContract'))

	Select (m.lcSelect)
	Return m.llSucces

Endproc && calcul_contract

*******************
*** Este veche si nu se mai foloseste. Se foloseste calcul_penalitati2
*******************
Procedure calcul_penalitati
	* pnTipCalcul: 1 (default) = incasari si sold; 2 = incasari; 3 = sold; 4 = evaluare
	* pnCalculZile: 1 (default) = calcul zile fata de luna precedenta; 2 = fata de data scadenta


	Private pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru
	Store "" To pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru
	* 1. Se calculeaza penalitatile pentru incasari
	* 2. Se calculeaza penalitatile pentru soldul facturilor

	If Inlist(m.pnTipCalcul, 1, 2)  && 1 = incasari + sold, 2 = incasari
		* INCASARILE DIN LUNA INCASATE DUPA DATA SCADENTA + DATELE DE FACTURARE

		Text To lcSql Textmerge Noshow
Select v.id_fact, v.id_part as clie_id, v.id_ctr, v.id_beneficiar, p2.denumire as beneficiar, v.numar_act as nrfact, v.data_act as datafact, v.data_scad as datascad, v.total_cu_tva as valctva, v.totval, v.Curs, v.id_Valuta, vl.nume_val as valuta,
  '' as explicatia, v.id_ctr, cast(TRIM(to_char(c.numar)) || (case when c.data_inceput is not null then '/' || to_char(c.data_inceput, 'dd.mm.yyyy') else '' end) as varchar2(100)) as contract,
  p1.denumire As nume, i.id_doc, i.nract, i.dataact, i.suma, i.suma_val As sumaval, i.pereche, i.id_fact, 
  c.coef_penalitati as ppenzi, c.coef_penalitati2 as ppenzi2, c.zile_penalitati as penzile, c.zile_penalitati2 as penzile2, c.descriere, c.zile_gratie_penalitati as zilegratie, 
  i.dataact - v.data_scad As nr_zile, Cast(0 As number) As nr_zile1, Cast(0 As number) As nr_zile2, CAST(0 as number) As penalitati,
  v.data_scad As databaza, i.dataact as dataref, i.Cont
	From vanzari v JOIN nom_parteneri p1 ON v.id_part = p1.id_part 
	left join nom_parteneri p2 ON v.id_beneficiar = p2.id_part 
    left join vnom_valute vl on v.id_valuta = vl.id_valuta		
	left join contracte c on v.id_ctr = c.id_ctr
	Join (Select id_fact as id_doc, nract, dataact, id_partc as id_part, partc as nume, perechec as pereche, id_factc as id_fact, scc As cont, Sum(suma) As suma, Sum(suma_val) As suma_val
		From vact Where an = <<m.gnAn>> and luna = <<m.gnLuna>> and scc in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>) And scd <> '4118' 
			Group By id_fact, nract, dataact, id_partc, partc, perechec, id_factc, scc) i On i.id_fact = v.id_fact
	Where v.tip_factura <> 6 and i.dataact > v.data_scad And i.dataact < TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD')
		Endtext
		llSucces = goExecutor.oExecuta(m.lcSql, "cFiordIncasari")

		&& nu facturez incasarile pe care utilizatorul le-a facturat deja sau incasarile pe care le-a sters manual
		Text To lcSql Noshow
SELECT p.id_doc_incasare, p.id_fact FROM penalitati p join vanzari v on p.id_fact_pen = v.id_fact WHERE p.sters = 0 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = ?m.gnAn * 12 + ?m.gnLuna
union 
SELECT p.id_doc_incasare, p.id_fact FROM penalitati p WHERE p.sters = 1 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = ?m.gnAn * 12 + ?m.gnLuna
		Endtext
		llSucces = goExecutor.oExecuta(m.lcSql, 'cPenalitatiFactSters')
		If m.llSucces
			Select cPenalitatiFactSters
			Scan
				Scatter Name loRec
				Delete From cFiordIncasari Where id_fact = loRec.id_fact And id_doc = loRec.id_doc_incasare
			Endscan
		Endif && llSucces

		Use In (Select('cPenalitatiFactSters'))
		Select * From cFiordIncasari Into Cursor cFiordTemp NOFILTER Readwrite
		Use In (Select('cFiordIncasari'))
	Endif && INLIST(m.pnTipCalcul, 1, 2)  && 1 = incasari + sold, 2 = incasari


	If Inlist(m.pnTipCalcul, 1, 3, 4)  && 1 = incasari + sold, 3 = sold, 4 = evaluare

		*** SELECTEZ FACTURILE DIN FACTURARE (EMISE DE COMERCIAL) DAR CU SOLD IN VANZLUN SI DEBLUN IN LUNA CURENTA
		Text To lcSql Textmerge Noshow
Select v.id_fact, v.id_part as clie_id, v.id_ctr, v.id_beneficiar, p2.denumire as beneficiar, v.numar_act as nrfact, v.data_act as datafact, v.data_scad as datascad, v.total_cu_tva as valctva, v.totval, v.Curs, v.id_Valuta, vl.nume_val as valuta,
	'' as EXPLICATIA, v.id_ctr, cast(TRIM(to_char(c.numar)) || (case when c.data_inceput is not null then '/' || to_char(c.data_inceput, 'dd.mm.yyyy') else '' end) as varchar2(100)) as contract,
	p2.denumire As nume, 0 as id_doc, 0 As nract, TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') As dataact, i.sold As suma, i.soldval As sumaval, 0 As PERECHE, 0 as id_fact, 
	c.coef_penalitati as ppenzi, c.coef_penalitati2 as ppenzi2, c.zile_penalitati as penzile, c.zile_penalitati2 as penzile2, c.descriere, c.zile_gratie_penalitati as zilegratie,
	TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') - v.data_scad As nr_zile, Cast(0 As number) As nr_zile1, Cast(0 As number) As nr_zile2, CAST(0 as number) As penalitati,
	v.data_scad As databaza, TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') As dataref, i.Cont 
	From vanzari v join nom_parteneri p1 ON v.id_part = p1.id_part 
    left join vnom_valute vl on v.id_valuta = vl.id_valuta	
	left join nom_parteneri p2 ON v.id_beneficiar = p2.id_part 
	left join contracte c on v.id_ctr = c.id_ctr
	Join (Select id_fact, nract, dataact, precdeb+debit-preccred-credit as sold, precvaldeb+valdebit-precvalcred-credit as soldval, Cont 
		From ireg_parteneri 
		WHERE an = <<m.gnAn>> and luna = <<m.gnLuna>> and cont in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>)) i On v.id_fact = i.id_fact
	Where v.tip_factura <> 6 and i.sold > 0 And v.data_scad < TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD')
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, "cFiordSold")

		If Used('cFiordTemp')
			Select cFiordTemp
			Append From Dbf('cFiordSold')
		Else
			Select * From cFiordSold Into Cursor cFiordTemp NOFILTER Readwrite
		Endif
		Use In (Select('cFiordSold'))
	Endif && INLIST(m.pnTipCalcul, 1, 3, 4)  && 1 = incasari + sold, 3 = sold, 4 = evaluare

	Select * From cFiordTemp Order By nume, contract, datafact, nrfact Into Cursor crsCalculPenalitatiTemp
	Use In (Select('cFiordTemp'))

	Select crsCalculPenalitati
	Delete All
	Append From Dbf('crsCalculPenalitatiTemp')
	Use In (Select('crsCalculPenalitatiTemp'))

	If m.pnCalculZile = 1 && calcul zile fata de luna precedenta, 2 = fata de data scadenta
		Update crsCalculPenalitati Set databaza = Max(datascad, Date(m.gnAn, m.gnLuna, 1) - 1)
	Else
		Update crsCalculPenalitati Set databaza = datascad
	Endif
	Update crsCalculPenalitati Set dataref = Min(dataref, m.pdDataReferinta)

	*** nu calculez zile de penalitati daca numarul de zile este mai mic decat numarul de zile de gratie
	Update crsCalculPenalitati Set nr_zile = Iif(dataref - databaza <= zilegratie, 0, dataref - databaza)
	Update crsCalculPenalitati Set penalitati = Round(Round(ppenzi / 100 * suma, m.gnZ) * nr_zile, m.gnZ)

	* Recalculez penalitatile pentru contractele cu 2 cote de penalitati
	* Poate fi folosita si pentru contractele cu o singura cota de penalitati, dar in perioada de testare verific doar contractele cu doua cote
	Select crsCalculPenalitati
	Scan For ppenzi2 <> 0
		lnPenalitati = penalitati
		lnZileProcent1 = nr_zile
		lnZileProcent2 = 0
		lnPenalitati = CalculeazaPenalitati(ppenzi, ppenzi2, penzile, penzile2, datascad, databaza, dataref, zilegratie, suma, @lnZileProcent1, @lnZileProcent2)
		Replace penalitati With lnPenalitati, nr_zile1 With m.lnZileProcent1, nr_zile2 With m.lnZileProcent2
	Endscan

	Go Top In crsCalculPenalitati

Endproc && calcul_penalitati

****************************************
*** TEMPORAR!!! FOLOSESC DOAR IREG_PARTENERI, FARA VANZARI, PANA IMPORT VANZARILE!!!!!!
****************************************
Procedure calcul_penalitati2
	Lparameters tnIdClient
	* pnTipCalcul: 1 (default) = incasari si sold; 2 = incasari; 3 = sold; 4 = evaluare
	* pnCalculZile: 1 (default) = calcul zile fata de luna precedenta; 2 = fata de data scadenta

	*!!! De facut: facturile cu sold <> 0 in loc de sold > 0; initializare explicatie TVA; seria AVN; EXPLICATIE TVA ID_JTVA_COLOANA = 12 OPERATIUNI NEIMPOZABILE

	Local lcFiltruAIdPart, lcFiltruVIdPart, lcSql, lcSql1, lcSql2, llSucces, lnPenalitati
	Local lnZileProcent1, lnZileProcent2, loRec
	make_cCalculPenalitati()
	make_cClientiPenalitati()

	lcFiltruVIdPart = Iif(!Empty(m.tnIdClient), [ and v.id_part = ] + Alltrim(Str(m.tnIdClient)), [])
	lcFiltruAIdPart = Iif(!Empty(m.tnIdClient), [ and id_partc = ] + Alltrim(Str(m.tnIdClient)), [])

	Private pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru
	Store "" To pcNumeFiltru, pcAgentFiltru, pcContractFiltru, pcExplicatiaFiltru
	* 1. Se calculeaza penalitatile pentru incasari
	* 2. Se calculeaza penalitatile pentru soldul facturilor
	If Inlist(m.pnTipCalcul, 1, 2)  && 1 = incasari + sold, 2 = incasari
		* INCASARILE DIN LUNA INCASATE DUPA DATA SCADENTA + DATELE DE FACTURARE
		* DACA CALCULUL ESTE FATA DE LUNA PRECEDENTA, INCASARILE LE IAU DIN LUNA CURENTA SI APOI SA FAC FILTRUL SA FIE DATA INCASARII > DATA SCADENTA
		* DACA CALCULUL ESTE FATA DE DATA SCADENTA, INCASARILE LE IAU DIN TOATA BAZA DE DATE SI APOI SA FAC FILTRUL SA FIE DATA INCASARII > DATA SCADENTA
		
		*** SERIE_ACT = AVN - FACTURI DE PENALITATI, DACA IAU DIN VANZARI.TIP_FACTURA <> 6
		*** la facturile 4118 id_fact nu mai corespunde cu id_fact 4111 original si nu mai gasesc factura originala. caut id_Fact original dupa nrfact 
		Text To lcSql Textmerge Noshow
Select <<IIF(m.pl4118, [NVL(vz1.id_fact, vz2.id_fact)], [NVL(vz1.id_fact,0)])>> as id_fact, v.id_part as clie_id, v.id_ctr, 0 as id_beneficiar, '' as beneficiar, v.nract as nrfact, v.dataact as datafact, v.datascad as datascad, (v.precdeb + v.debit) as valctva, (v.precvaldeb + v.valdebit) as totval, v.Curs, v.id_Valuta, vl.nume_val as valuta,
  '' as explicatia, v.id_ctr, c.numar, cast(TRIM(to_char(c.numar)) || (case when c.data_inceput is not null then '/' || to_char(c.data_inceput, 'dd.mm.yyyy') else '' end) as varchar2(100)) as contract,
  p1.denumire As nume, i.id_doc, i.nract, i.dataact, i.suma, i.suma_val As sumaval, i.pereche, i.id_fact, 
  c.coef_penalitati as ppenzi, c.coef_penalitati2 as ppenzi2, c.zile_penalitati as penzile, c.zile_penalitati2 as penzile2, c.descriere, c.zile_gratie_penalitati as zilegratie, 
  i.dataact - v.datascad As nr_zile, Cast(0 As number) As nr_zile1, Cast(0 As number) As nr_zile2, CAST(0 as number) As penalitati,
  v.datascad As databaza, i.dataact as dataref, <<IIF(m.pl4118, [NVL(vz1.tip_factura, NVL(vz2.tip_factura,0))], [NVL(vz1.tip_factura,0)])>> as tip
	From ireg_parteneri v JOIN nom_parteneri p1 ON v.id_part = p1.id_part 
	left join vanzari vz1 on v.cont <> '4118' and v.id_fact = vz1.id_fact and vz1.sters = 0
	<<IIF(m.pl4118, [left join vanzari vz2 on v.cont = '4118' and v.nract = vz2.numar_act and v.dataact = vz2.data_act and v.id_part = vz2.id_part and vz2.sters = 0], [])>>
    left join vnom_valute vl on v.id_valuta = vl.id_valuta	
	left join contracte c on v.id_ctr = c.id_ctr
	Join (Select id_fact as id_doc, nract, dataact, id_partc as id_part, partc as nume, perechec as pereche, id_factc as id_fact, scc As cont, Sum(suma) As suma, Sum(suma_val) As suma_val
		From vact Where <<IIF(m.pnCalculZile = 1, [ an = ] + ALLTRIM(STR(m.gnAn)) + [ and luna = ] + ALLTRIM(STR(m.gnLuna)), '1=1')>>  <<m.lcFiltruAIdPart>> and scc in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>) And scd <> '4118' 
			Group By id_fact, nract, dataact, id_partc, partc, perechec, id_factc, scc) i On i.id_fact = v.id_fact
	Where v.an = <<m.gnAn>> and v.luna = <<m.gnLuna>> <<m.lcFiltruVIdPart>> and v.cont in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>) and i.dataact > v.datascad And i.dataact <= TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') 
	and <<IIF(m.pl4118, [NVL(vz1.tip_factura, NVL(vz2.tip_factura,0))], [NVL(vz1.tip_factura,0)])>> <> 6
		Endtext
		llSucces = goExecutor.oExecuta(m.lcSql, "cFiordIncasari")

		*!*			&& nu facturez incasarile pe care utilizatorul le-a facturat deja pe o factura de penalitati sau incasarile pe care le-a sters manual
		*!*			Text To lcSql TEXTMERGE Noshow
		*!*	SELECT p.id_doc_incasare, p.id_fact FROM penalitati p join ireg_parteneri v on p.id_fact_pen = v.id_fact WHERE p.sters = 0 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = <<m.gnAn * 12 + m.gnLuna>> AND v.an = <<m.gnAn>> and v.luna = <<m.gnLuna>> <<m.lcFiltruVIdPart>> and v.cont in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>)
		*!*	union 
		*!*	SELECT p.id_doc_incasare, p.id_fact FROM penalitati p WHERE p.sters = 2 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = <<m.gnAn * 12 + m.gnLuna>>
		*!*			Endtext
		*!*			llSucces = goExecutor.oExecuta(m.lcSql, 'cPenalitatiFactSters')
		*!*			If m.llSucces
		*!*				Select cPenalitatiFactSters
		*!*				Scan
		*!*					Scatter Name loRec
		*!*					Delete From cFiordIncasari Where id_fact = loRec.id_fact And id_doc = loRec.id_doc_incasare
		*!*				Endscan
		*!*			Endif && llSucces


		Select .F. as facturate, .F. as sterse, i.* From cFiordIncasari i Into Cursor cFiordTemp NOFILTER Readwrite
		Use In (Select('cFiordIncasari'))
	Endif && INLIST(m.pnTipCalcul, 1, 2)  && 1 = incasari + sold, 2 = incasari


	If Inlist(m.pnTipCalcul, 1, 3, 4)  && 1 = incasari + sold, 3 = sold, 4 = evaluare

		*** SELECTEZ FACTURILE DIN FACTURARE (EMISE DE COMERCIAL) DAR CU SOLD IN VANZLUN SI DEBLUN IN LUNA CURENTA
		*** SERIE_ACT = AVN - FACTURI DE PENALITATI, DACA IAU DIN VANZARI.TIP_FACTURA <> 6
		Text To lcSql Textmerge Noshow
Select <<IIF(m.pl4118, [NVL(vz1.id_fact, vz2.id_fact)], [NVL(vz1.id_fact,0)])>> as id_fact, v.id_part as clie_id, v.id_ctr, 0 as id_beneficiar, '' as beneficiar, v.nract as nrfact, v.dataact as datafact, v.datascad as datascad, (v.precdeb + v.debit) as valctva, (v.precvaldeb + v.valdebit) as totval, v.Curs, v.id_Valuta, vl.nume_val as valuta,
	'' as EXPLICATIA, v.id_ctr, c.numar, cast(TRIM(to_char(c.numar)) || (case when c.data_inceput is not null then '/' || to_char(c.data_inceput, 'dd.mm.yyyy') else '' end) as varchar2(100)) as contract,
	p1.denumire As nume, 0 as id_doc, 0 As nract, TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') As dataact, (v.precdeb+v.debit-v.preccred-v.credit) as suma, (v.precvaldeb+v.valdebit-v.precvalcred-v.valcredit) As sumaval, 0 As PERECHE, 0 as id_fact, 
	c.coef_penalitati as ppenzi, c.coef_penalitati2 as ppenzi2, c.zile_penalitati as penzile, c.zile_penalitati2 as penzile2, c.descriere, c.zile_gratie_penalitati as zilegratie,
	TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') - v.datascad As nr_zile, Cast(0 As number) As nr_zile1, Cast(0 As number) As nr_zile2, CAST(0 as number) As penalitati,
	v.datascad As databaza, TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') As dataref, <<IIF(m.pl4118, [NVL(vz1.tip_factura, NVL(vz2.tip_factura,0))], [NVL(vz1.tip_factura,0)])>> as tip 
	From ireg_parteneri v join nom_parteneri p1 ON v.id_part = p1.id_part 
	left join vanzari vz1 on v.cont <> '4118' and v.id_fact = vz1.id_fact and vz1.sters = 0
	<<IIF(m.pl4118, [left join vanzari vz2 on v.cont = '4118' and v.nract = vz2.numar_act and v.dataact = vz2.data_act and v.id_part = vz2.id_part and vz2.sters = 0], [])>>
    left join vnom_valute vl on v.id_valuta = vl.id_valuta	
	left join contracte c on v.id_ctr = c.id_ctr
	Where v.an = <<m.gnAn>> and v.luna = <<m.gnLuna>> <<m.lcFiltruVIdPart>> and v.cont in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>) and (v.precdeb+v.debit-v.preccred-v.credit) <> 0 And v.datascad <= TO_DATE('<<DTOS(pdDataReferinta)>>','YYYYMMDD') 
	and <<IIF(m.pl4118, [NVL(vz1.tip_factura, NVL(vz2.tip_factura,0))], [NVL(vz1.tip_factura,0)])>> <> 6
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, "cFiordSold")

		If Used('cFiordTemp')
			Select cFiordTemp
			Append From Dbf('cFiordSold')
		Else
			Select .F. as facturate, .F. as sterse, s.* From cFiordSold s Into Cursor cFiordTemp NOFILTER Readwrite
		Endif
		Use In (Select('cFiordSold'))
	Endif && INLIST(m.pnTipCalcul, 1, 3, 4)  && 1 = incasari + sold, 3 = sold, 4 = evaluare

	********************************
	* Nu includ facturile si incasarile pe care utilizatorul le-a facturat deja pe o factura de penalitati sau facturile si incasarile pe care le-a sters manual
	* Daca le includ (plFacturate, plSterse), le marchez si colorez corespunzator
	********************************
		Text To lcSql Textmerge Noshow
SELECT 1 as facturate, 0 as sterse, p.id_doc_incasare, p.id_fact FROM penalitati p join ireg_parteneri v on p.id_fact_pen = v.id_fact WHERE p.sters = 0 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = <<m.gnAn * 12 + m.gnLuna>> AND v.an = <<m.gnAn>> and v.luna = <<m.gnLuna>> <<m.lcFiltruVIdPart>> and v.cont in ('4111', '461'<<IIF(m.pl4118, [, '4118'], [])>>)
UNION
SELECT 0 as facturate, 1 as sterse, p.id_doc_incasare, p.id_fact FROM penalitati p WHERE p.sters = 2 and extract(year FROM p.dataact) * 12 + extract(MONTH FROM p.dataact) = <<m.gnAn * 12 + m.gnLuna>>
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, 'cPenalitatiFactSters')
		If m.llSucces
			Select cPenalitatiFactSters
			Scan
				Scatter Name loRec
				WITH loRec
					DO CASE 
						CASE m.plFacturate AND .facturate = 1
							UPDATE cFiordTemp SET facturate = .T. Where id_fact = .id_fact And Nvl(id_doc, 0) = Nvl(.id_doc_incasare, 0)
						CASE m.plSterse AND .sterse = 1
							UPDATE cFiordTemp SET sterse = .T. Where id_fact = .id_fact And Nvl(id_doc, 0) = Nvl(.id_doc_incasare, 0)
						OTHERWISE 			
							Delete From cFiordTemp Where id_fact = .id_fact And Nvl(id_doc, 0) = Nvl(.id_doc_incasare, 0)
					ENDCASE 
				ENDWITH 
			Endscan
		Endif && llSucces

		Use In (Select('cPenalitatiFactSters'))

	********************************

	Select * From cFiordTemp Order By nume, contract, datafact, nrfact, dataact, nract Into Cursor crsCalculPenalitatiTemp
	Use In (Select('cFiordTemp'))

	Select crsCalculPenalitati
	Delete All
	Append From Dbf('crsCalculPenalitatiTemp')
	Use In (Select('crsCalculPenalitatiTemp'))

*!*		If m.pnCalculZile = 1 && calcul zile fata de luna precedenta, 2 = fata de data scadenta
*!*			Update crsCalculPenalitati Set databaza = Max(datascad, Date(m.gnAn, m.gnLuna, 1) - 1)
*!*		Else
*!*			Update crsCalculPenalitati Set databaza = datascad
*!*		Endif
*!*		Update crsCalculPenalitati Set dataref = Min(dataref, m.pdDataReferinta)

	Select crsCalculPenalitati
	Scan
		calcul_penalitati_linie(m.pnCalculZile, m.pdDataReferinta)
	Endscan

	Go Top In crsCalculPenalitati

	Use In (Select('crsClientiPenalitati'))
	Create Cursor crsClientiPenalitati (nume C(100), clie_id N(12) )
	Select Distinct nume, clie_id From crsCalculPenalitati Order By nume Into Cursor cClientiTemp
	If _Tally > 1 && daca vreau facturile pentru toti client nu mai adaug <TOTI> pentru filtrarea facturilor
		Insert Into crsClientiPenalitati (nume, clie_id) Values ('Alegeti clientul...', 0)
	Endif
	Select crsClientiPenalitati
	Append From Dbf('cClientiTemp')
	Use In (Select('cClientiTemp'))

Endproc && calcul_penalitati2

***********************************************
* calculeaza numarul de zile si valoarea penalitatilor pentru documentul curent din crsCalculPenalitati
* in functie de cotele de penalitati pe perioade
* se apeleaza initial in calcul_penalitati2 si apoi la modificari din frm_penalitati
***********************************************
Procedure calcul_penalitati_linie
	LPARAMETERS tnCalculZile, tdDataReferinta, m.tdDataBaza
	* tnCalculZile: 1 = calcul zile fata de luna precedenta, 2 = fata de data scadenta
	* tdDataReferinta: data referinta a calculului de penalitati
	* tdDataBaza: optional, daca se apeleaza din frm_penalitati si se modifica de utilizator databaza
		
	Select crsCalculPenalitati
	ldDataScad = IIF(!EMPTY(datascad), datascad, GOMONTH(dataact,1))
	ldDataRef = MIN(dataref, m.tdDataReferinta) && daca sunt incasari, data de referinta pentru incasari este data incasarii, daca este mai mica decat data de referinta
	
	* Calculez data baza
	DO CASE 
		CASE !EMPTY(m.tdDataBaza)
			ldDataBaza = m.tdDataBaza
		CASE m.tnCalculZile = 1
			* tnCalculZile = 1 : fata de luna precedenta

			* Data de baza este ultima zi din luna precedenta sau data scadenta, care este mai mare
			ldDataBaza = Max(m.ldDataScad, Date(m.gnAn, m.gnLuna, 1) - 1)

			* Data de gratie este ultima zi in care nu se calculeaza penalitati (data scadenta + zile gratie)
			ldDataGratie = m.ldDataScad + zilegratie

			* Daca data referinta > data de gratie si data gratie este in luna de referinta
			* sunt in luna in care s-a sfarsit perioada de gratie si calculez penalitati inclusiv pana la data scadenta
			* in loc de pana la ultima zi a lunii anterioare
			IF m.tdDataReferinta > m.ldDataGratie AND YEAR(m.ldDataGratie) = year(m.tdDataReferinta) AND MONTH(m.ldDataGratie) = MONTH(m.tdDataReferinta)
				ldDataBaza = m.ldDataScad
			ENDIF 	
		OTHERWISE 
			* tnCalculZile = 2 : fata de data scadenta
			ldDataBaza = m.ldDataScad
	ENDCASE 
	
	* Recalculez penalitatile pentru contractele cu 2 cote de penalitati
	* Poate fi folosita si pentru contractele cu o singura cota de penalitati, dar in perioada de testare verific doar contractele cu doua cote
	Replace ppenzi With Nvl(ppenzi, 0), ppenzi2 With Nvl(ppenzi2, 0), penzile With Nvl(penzile, 0), penzile2 With Nvl(penzile2, 0), ;
		nr_zile With Nvl(nr_zile, 0), nr_zile1 With Nvl(nr_zile1, 0), nr_zile2 With Nvl(nr_zile2, 0), ;
		zilegratie With Nvl(zilegratie, 0), penalitati With Nvl(penalitati, 0), dataref WITH m.ldDataRef, databaza WITH m.ldDataBaza
	If id_ctr = 0
		Replace id_ctr With Null
	Endif
	If .T. && ppenzi2 <> 0
		lnPenalitati = penalitati
		lnZileProcent1 = 0
		lnZileProcent2 = 0
		lnZilePenalitati = 0
		lnPenalitati = CalculeazaPenalitati(ppenzi, ppenzi2, penzile, penzile2, datascad, databaza, dataref, zilegratie, suma, @lnZilePenalitati, @lnZileProcent1, @lnZileProcent2)
		Replace penalitati With lnPenalitati, nr_zile1 With m.lnZileProcent1, nr_zile2 With m.lnZileProcent2, nr_zile WITH m.lnZilePenalitati
	Endif
Endproc && calcul_penalitati_linie

*********************************************************************
*** lucreaza cu 2 procente de penalitati. un procent in primele x zile de restanta, un procent pentru restul zilelor de restanta
*********************************************************************
Function CalculeazaPenalitati
	Lparameters tnProcentPenalitatiZi1, tnProcentPenalitatiZi2, tnPerioadaPenalitati1, tnPerioadaPenalitati2, tdDataScadenta, tdDataBaza, tdDataReferinta, tnZileGratie, tnSuma, lnZilePenalitati, lnZileProcent1, lnZileProcent2
	* tnProcentPenalitatiZi1: procent penalitati pentru zilele de restanta <= tnPerioadaPenalitati2-tnPerioadaPenalitati1
	* tnProcentPenalitatiZi2: procent penalitati pentru zilele de restanta > tnPerioadaPenalitati2-tnPerioadaPenalitati1
	* tnPerioadaPenalitati1: dupa cate zile fata de emiterea facturii se aplica primul procent de penalitati (egal cu zile de scadenta)
	* tnPerioadaPenalitati2: dupa cate zile fata de emiterea facturii se aplica al doilea procent de penalitati
	* tdDataScadenta: data scadenta a facturii
	* tdDataBaza: max(sfarsitul lunii precedente, data scadenta)
	* tdDataReferinta: data de referinta cand se face calculul penalitatilor = min(data incasare data de referinta pentru calculul penalitati)
	* tnSuma: suma la care se calculeaza penalitati (incasare sau sold)
	* tnZileGratie: zile restante pentru care NU se calculeaza penalitati

	Local lnPenalitati, lnZileProcent, lnZileRestante, lnZileProcent1, lnZileProcent2

	lnZileProcent = m.tnPerioadaPenalitati2 - m.tnPerioadaPenalitati1 && dupa cate zile de la scadenta se schimba procentul de penalitati
	lnZileRestante = m.tdDataReferinta - m.tdDataScadenta

	* nu calculez zile de penalitati in perioada de gratie (numarul de zile restante fata de data scadenta mai mic decat numarul de zile de gratie)
	lnZilePenalitati = Iif(m.lnZileRestante <= m.tnZileGratie, 0, m.tdDataReferinta - m.tdDataBaza)

	* pentru cate zile de restanta se foloseste tnProcentPenalitatiZi2
	lnZileProcent2 = Iif(m.lnZileRestante <= m.tnZileGratie, 0, IIF(m.tnPerioadaPenalitati2 = 0, 0, Iif(m.lnZileRestante > m.lnZileProcent, Min(m.lnZilePenalitati, m.lnZileRestante - m.lnZileProcent), 0)))

	* pentru cate zile de restanta se foloseste tnProcentPenalitatiZi1
	lnZileProcent1 = Iif(m.lnZileRestante <= m.tnZileGratie, 0, Iif(m.lnZilePenalitati > m.lnZileProcent2, m.lnZilePenalitati - m.lnZileProcent2, 0))

	lnPenalitati = Round(Round(m.tnProcentPenalitatiZi1 / 100 * tnSuma, m.gnZ) * m.lnZileProcent1, m.gnZ) + Round(Round(m.tnProcentPenalitatiZi2 / 100 * m.tnSuma, m.gnZ) * m.lnZileProcent2, m.gnZ)

	Return m.lnPenalitati
Endfunc && CalculeazaPenalitati

Function TestCalculeazaPenalitati
	gnZ = 2
	lnZilePenalitati = 0
	lnPenalitati = 0
	lnZileProcent1 = 0
	lnZileProcent2 = 0
	lnppenzi = 0.15
	lnppenzi2 = 0.10
	lnpenzile = 30
	lnpenzile2 = 60
	lnsuma = 100
	lnzilegratie = 0
	ldDataScad = Date(2019, 2, 21)

	* februarie
	lddatabaza = Date(2019, 2, 21)
	lddataref = Date(2019, 2, 28)
	lnPenalitati = CalculeazaPenalitati(lnppenzi, lnppenzi2, lnpenzile, lnpenzile2, ldDataScad, lddatabaza, lddataref, lnzilegratie, lnsuma, @lnZilePenalitati, @lnZileProcent1, @lnZileProcent2)
	Messagebox('Penalitati Februarie: ' + Transform(m.lnPenalitati) + ' ' + Transform((m.lnPenalitati = 1.05)) + ' | Zile Proc. Pen. 1: ' + Transform(m.lnZileProcent1) + ' | Zile Proc. Pen. 2: ' + Transform(m.lnZileProcent2))

	* martie
	lddatabaza = Date(2019, 2, 28)
	lddataref = Date(2019, 3, 31)
	lnPenalitati = CalculeazaPenalitati(lnppenzi, lnppenzi2, lnpenzile, lnpenzile2, ldDataScad, lddatabaza, lddataref, lnzilegratie, lnsuma, @lnZilePenalitati, @lnZileProcent1, @lnZileProcent2)
	Messagebox('Penalitati Martie: ' + Transform(m.lnPenalitati) + ' ' + Transform((m.lnPenalitati = 4.25)) + ' | Zile Proc. Pen. 1: ' + Transform(m.lnZileProcent1) + ' | Zile Proc. Pen. 2: ' + Transform(m.lnZileProcent2))

	* aprilie
	lddatabaza = Date(2019, 3, 31)
	lddataref = Date(2019, 4, 30)
	lnPenalitati = CalculeazaPenalitati(lnppenzi, lnppenzi2, lnpenzile, lnpenzile2, ldDataScad, lddatabaza, lddataref, lnzilegratie, lnsuma, @lnZilePenalitati, @lnZileProcent1, @lnZileProcent2)
	Messagebox('Penalitati Aprilie: ' + Transform(m.lnPenalitati) + ' ' + Transform((m.lnPenalitati = 3.00)) + ' | Zile Proc. Pen. 1: ' + Transform(m.lnZileProcent1) + ' | Zile Proc. Pen. 2: ' + Transform(m.lnZileProcent2))


	* data scadenta 05.01.2020, data referinta 31.01.2020, zile restanta = 26, valoare penalitati 1.56
	lnPenalitati = 0
	lnZileProcent1 = 0
	lnZileProcent2 = 0
	lnppenzi = 0.06
	lnppenzi2 = 0.10
	lnpenzile = 30
	lnpenzile2 = 60
	lnsuma = 100
	lnzilegratie = 0
	ldDataScad = Date(2020, 1, 5)
	lddatabaza = Date(2020, 1, 5)
	lddataref = Date(2020, 1, 31)
	lnPenalitati = CalculeazaPenalitati(lnppenzi, lnppenzi2, lnpenzile, lnpenzile2, ldDataScad, lddatabaza, lddataref, lnzilegratie, lnsuma, @lnZilePenalitati, @lnZileProcent1, @lnZileProcent2)
	Messagebox('Penalitati ianuarie: ' + Transform(m.lnPenalitati) + ' ' + Transform((m.lnPenalitati = 1.56)) + ' | Zile Proc. Pen. 1: ' + Transform(m.lnZileProcent1) + ' | Zile Proc. Pen. 2: ' + Transform(m.lnZileProcent2))

Endfunc && TestCalculeazaPenalitati


****************************************************************************************************************************
*** Salveaza datele calculate pentru o factura din cheiaj
****************************************************************************************************************************
Procedure salvare_cheiaj
	Private poVoyage, poRec, poRecD, pnVVId

	Local lcSql, lcSqlBDDel, lcSqlBDIns, lcSqlBVIns, lcSqlVVIns, llScris, llSucces, llSucces2
	Local lcVVIds
	lcVVIds = ''

	* Completez IPS_VOYAGES_VANZARI
	Text To lcSqlVVIns Noshow
INSERT INTO IPS_VOYAGES_VANZARI(vye_id,client_id,client_ctr_id,eagent,beneficiar_id,tiprecap,intern,tip,document)
VALUES (?poVoyage.vye_id,?poVoyage.client_id,?poVoyage.client_ctr_id,?poVoyage.eagent,?poVoyage.beneficiar_id,?poVoyage.tiprecap,?poVoyage.intern,?poVoyage.tip,?poVoyage.document)
RETURNING id into ?@pnVVId
	Endtext

	Text To lcSqlBVIns Noshow
	insert into ips_berthings_vanzari
	  (vv_id,
	   vye_id,
	   bts_id,
	   rpt_id,
	   ves_id,
	   vs_name,
	   cap,
	   lbd,
	   trn,
	   hp,
	   lung,
	   datai,
	   datap,
	   id_locatia,
	   dana_id)
	values
	  (?m.pnVVId,
	   ?poRec.vye_id,
	   ?poRec.id,
	   ?poRec.rpt_id,
	   ?poRec.ves_id,
	   ?poRec.nava,
	   ?poRec.cap,
	   ?poRec.lbd,
	   ?poRec.trn,
	   ?poRec.hp,
	   ?poRec.lung,
	   ?poRec.datai,
	   ?poRec.datap,
	   ?poRec.id_locatia,
	   ?poRec.dana_id)
	   RETURNING id into ?@poRec.bv_id
	Endtext

	* COMPLETEZ IPS_BERTHING_DETAILS_VANZARI
	lcSqlBDDel = [delete from ips_berthing_details_vanzari where bv_id = ?poRec.bv_id]

	Text To lcSqlBDIns Noshow
	insert into ips_berthing_details_vanzari
	  (bv_id,
	   datai,
	   datap,
	   cant,
	   tarif,
	   um,
	   id_valuta,
	   curs,
	   valval,
	   tvaval,
	   totval,
	   valftva,
	   valtva,
	   valctva,
	   durata,
	   id_articol)
	values
	  (?poRec.bv_id,
	   ?poRecD.datai,
	   ?poRecD.datap,
	   ?poRecD.cant,
	   ?poRecD.tarif,
	   ?poRecD.um,
	   ?poRecD.id_valuta,
	   ?poRecD.curs,
	   ?poRecD.valval,
	   ?poRecD.tvaval,
	   ?poRecD.totval,
	   ?poRecD.valftva,
	   ?poRecD.valtva,
	   ?poRecD.valctva,
	   ?poRecD.durata,
	   ?poRecD.id_articol)
	Endtext

	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

	Select crsVoyage
	Scan
		If !m.llSucces
			Exit
		Endif

		Scatter Name poVoyage
		poVoyage.tip = NTIP_CHEIAJ && CHEIAJ
		poVoyage.client_ctr_id = Iif(!Empty(Nvl(poVoyage.client_ctr_id, 0)), poVoyage.client_ctr_id, Null) && nu exista contract cu id=0 si nu se valideaza constrangerea
		poVoyage.beneficiar_id = Iif(!Empty(Nvl(poVoyage.beneficiar_id, 0)), poVoyage.beneficiar_id, Null)
		poVoyage.Document = Alltrim(poVoyage.Document)
		poVoyage.vye_id = Alltrim(poVoyage.vye_id)

		* Completez IPS_VOYAGES_VANZARI
		* Se adauga o inreigstrare in IPS_VOYAGES_VANZARI la fiecare factura, nu se suprascrie inregistrarea curenta!
		pnVVId = 0 && Nvl(poVoyage.vv_id, 0)
		llSucces = goExecutor.oExecuta(m.lcSqlVVIns)

		* COMPLETEZ IPS_BERTHINGS_VANZARI
		If m.llSucces
			Replace vv_id With m.pnVVId In crsVoyage
			lcVVIds = m.lcVVIds + ',' + Alltrim(Str(Int(m.pnVVId)))

			* Actualizez ips_berthings_vanzari
			Select crsBerthings
			Scan For ales = 1 And vye_id = poVoyage.vye_id
				Scatter Name poRec
				poRec.vye_id = Alltrim(poRec.vye_id)
				poRec.Id = Alltrim(poRec.Id)
				poRec.rpt_id = Alltrim(poRec.rpt_id)
				poRec.ves_id = Alltrim(poRec.ves_id)
				* completez ips_berthings_vanzari.vs_name doar daca este diferit de cel al navei din IPS_VESSELS
				* in cazul facturarii unui convoi generic declcdt = "FARA"
				* Sunt situatii cand nu exista convoiul in RORIS
				poRec.nava = Iif(Alltrim(Nvl(poRec.nava, '')) <> Alltrim(Nvl(poRec.vs_name, '')), Alltrim(Nvl(poRec.nava, '')), '')

				llSucces = goExecutor.oExecuta(m.lcSqlBVIns)
				If !m.llSucces
					Exit
				Endif
				Select crsBerthings
				Replace bv_id With poRec.bv_id

				* Sterg detaliile vechi
				llSucces = goExecutor.oExecuta(m.lcSqlBDDel)

				* Introduc detaliile noi			
				Select crsBerthingDetails
				Scan For bts_id = poRec.Id And ves_id = poRec.ves_id
					Scatter Name poRecD
					llSucces = goExecutor.oExecuta(m.lcSqlBDIns)
					If !m.llSucces
						Exit
					Endif
					Select crsBerthingDetails
					Replace Id With poRecD.Id
				Endscan && crsBerthingDetails
			Endscan && crsBerthings
		Endif && llSucces
	Endscan && crsVoyage

	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris

	If !Empty(m.lcVVIds)
		lcVVIds = Substr(m.lcVVIds, 2)
	Endif
	poDate.uuid = m.lcVVIds

	Return m.lcVVIds
Endproc && salvare_cheiaj



****************************************************************************************************************************
*** Salveaza datele calculate pentru factura din tranzit
*** Intoarce o lista de ips_voyage_vazari.id, corespunzatoare fiecarui convoi ales
****************************************************************************************************************************
Procedure salvare_tranzit
	Private poVoyage, poRec, pnVVId

	lcVVIds = ''

	* Completez IPS_VOYAGES_VANZARI
	* Se adauga o inreigstrare in IPS_VOYAGES_VANZARI la fiecare factura, nu se suprascrie inregistrarea curenta!
	* Nu are rost ramura cu Update, dar pana la stabilizarea aplicatiei, ramane

	Text To lcSqlVIns Noshow
INSERT INTO IPS_VOYAGES_VANZARI(vye_id,client_id,client_ctr_id,eagent,beneficiar_id,tiprecap,intern,tip)
	VALUES (?poVoyage.vye_id,?poVoyage.client_id,?poVoyage.client_ctr_id,?poVoyage.eagent,?poVoyage.beneficiar_id,?poVoyage.tiprecap,?poVoyage.intern,?poVoyage.tip)
	RETURNING id into ?@pnVVId
	Endtext

	Text To lcSqlVMIns Noshow
insert into ips_voyage_members_vanzari
  (vv_id,
   vye_id,
   vms_id,
   rte_id,
   kmi,
   kmf,
   cuplat,
   corect,
   periculos,
   procdist,
   tcap,
   lbd,
   trn,
   hp,
   distanta,
   distanta_cdmn,
   tarif,
   um,
   cant,
   id_valuta,
   valval,
   vtp_id,
   procdiv,
   gds_id,
   quantity,
   marfa_country_id)
values
  (?poRec.vv_id,
   ?poRec.vye_id,
   ?poRec.vms_id,
   ?poRec.rte_id,
   ?NVL(poRec.kmi,0),
   ?NVL(poRec.kmf,0),
   ?poRec.cuplat,
   ?poRec.corect,
   ?poRec.periculos,
   ?poRec.procdist,
   ?NVL(poRec.tcap,0),
   ?NVL(poRec.lbd,0),
   ?NVL(poRec.trn,0),
   ?NVL(poRec.hp,0),
   ?NVL(poRec.distanta,0),
   ?NVL(poRec.distanta_cdmn,0),
   ?NVL(poRec.tarif,0),
   ?TRIM(poRec.um),
   ?NVL(poRec.cant,0),
   ?poRec.id_valuta,
   ?poRec.valval,
   ?poRec.vtp_id,
   ?poRec.procdiv,
   ?poRec.gds_id,
   ?poRec.cargo,
   ?poRec.marfa_country_id)
   RETURNING id into ?@poRec.vmv_id
	Endtext

	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

	Select crsVoyage
	Scan
		If !m.llSucces
			Exit
		Endif

		Scatter Name poVoyage
		poVoyage.tip = NTIP_TRANZIT
		poVoyage.client_ctr_id = Iif(!Empty(Nvl(poVoyage.client_ctr_id, 0)), poVoyage.client_ctr_id, Null) && nu exista contract cu id=0 si nu se valideaza constrangerea
		poVoyage.beneficiar_id = Iif(!Empty(Nvl(poVoyage.beneficiar_id, 0)), poVoyage.beneficiar_id, Null)

		pnVVId = 0 && Nvl(poVoyage.vv_id, 0)

		llSucces = goExecutor.oExecuta(m.lcSqlVIns)
		If !m.llSucces
			Exit
		Endif

		Replace vv_id With m.pnVVId In crsVoyage
		lcVVIds = m.lcVVIds + ',' + Alltrim(Str(Int(m.pnVVId)))

		* COMPLETEZ IPS_VOYAGE_MEMBERS_VANZARI
		Select crsVoyages
		Scan For ales = 1 And vye_id = poVoyage.vye_id
			Scatter Name poRec
			poRec.vv_id = m.pnVVId
			llSucces = goExecutor.oExecuta(m.lcSqlVMIns)
			If !m.llSucces
				Exit
			Endif
			Select crsVoyages
			Replace vmv_id With poRec.vmv_id
		Endscan && crsVoyages
	Endscan && crsVoyage

	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris

	If !Empty(m.lcVVIds)
		lcVVIds = Substr(m.lcVVIds, 2)
	Endif
	poDate.uuid = m.lcVVIds

	Return m.lcVVIds
Endproc && salvare_tranzit


****************************************************************************************************************************
*** Salveaza datele calculate pentru factura din contract
*** Intoarce o lista de ips_regdoc.id, corespunzatoare fiecarei inregistrari adaugate
****************************************************************************************************************************
Procedure salvare_contract
	Local lcRgdIds, ldData, lcDocument, lcSqlIns, lcSelect
	Private poRec
	lcRgdIds = ''
	lcSelect = Select()

	Text To lcSqlIns Noshow
insert into ips_regdoc
  (tip,
   id_articol,
   id_locatia,
   id_valuta,
   id_client,
   id_contract,
   pret,
   cantitate,
   valval,
   proc_tvav,
   document,
   data,
   perioada)
values
  (?poRec.tip,
   ?poRec.id_articol,
   ?poRec.id_locatia,
   ?poRec.id_valuta,
   ?poRec.id_client,
   ?poRec.id_contract,
   ?poRec.pret,
   ?poRec.cantitate,
   ?poRec.valval,
   ?poRec.proc_tvav,
   ?poRec.document,
   ?poRec.data,
   ?poRec.perioada)
   RETURNING id into ?@poRec.id
	Endtext

	ldData = crsCapFactura.dataact
	lcDocument = Substr(Sys(2015), 2)
	Select Cast(0 As N(20, 0)) As Id, poDate.nTipFactura As tip, m.ldData As Data, m.lcDocument As Document, id_articol, id_locatia, id_valuta, id_part As id_client, id_ctr As id_contract, Pret, cantitate, valval, proc_tvav, perioada ;
		From crsArticoleContract  ;
		With (Buffering = .T.) ;
		Into Cursor crsRegDocTemp

	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

	Select crsRegDocTemp
	Scan
		Scatter Name poRec
		poRec.perioada = Alltrim(Nvl(poRec.perioada, ''))

		llSucces = goExecutor.oExecuta(m.lcSqlIns)
		If !m.llSucces
			Exit
		Endif

		lcRgdIds = m.lcRgdIds + ',' + Alltrim(Str(Int(m.poRec.Id)))
	Endscan && crsRegDocTemp
	Use In (Select('crsRegDocTemp'))

	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris

	If !Empty(m.lcRgdIds)
		lcRgdIds = Substr(m.lcRgdIds, 2)
	Endif

	poDate.uuid = m.lcRgdIds

	Select (m.lcSelect)
	Return m.lcRgdIds
Endproc && salvare_contract

****************************************************************************************************************************
*** Deocamdata nu salveaza nimic in baza de date. Salvarea recapitulatiei se face la salvarea facturii
****************************************************************************************************************************
Procedure salvare_penalitati
	Local lcSelect, lcDel
	lcSelect = Select()

	Use In (Select('crsCalculPenalitatiAles'))
	lcDel = Set("Deleted")
	Set Deleted Off

	* Selectez inregistrarile alese si pe cele sterse, sa le marchez sterse si in penalitati
	* penalitati.sters = 2 (sters explicit de utilizator, nu sters automat la stergerea unei facturi de penalitati)
	Select * From crsCalculPenalitati ;
		With (Buffering = .T.) ;
		Where ales Or sters = 2 ;
		Into Cursor crsCalculPenalitatiAles Readwrite

	Set Deleted &lcDel

	Select (m.lcSelect)
	Return '0'
Endproc && salvare_penalitati

*****************************************
*** Sterg din IPS_REGDOC inregistrarile adaugate pentru CONTRACTE (CHIRII, APA), daca dau renunt la factura
*****************************************
Procedure STERG_CONTRACT_REGDOC
	Local lcRgdIds, lcSql, llSucces
	lcRgdIds = poDate.uuid
	llSucces = .T.

	If !Empty(m.lcRgdIds)
		lcSql = [DELETE FROM IPS_REGDOC WHERE ID IN (] + m.lcRgdIds + [)]
		llSucces = goExecutor.oExecuta(m.lcSql)
	Endif
	Return m.llSucces
Endproc && STERG_CONTRACT_REGDOC

*****************************************
*** Sterg din IPS_VOYAGES_VANZARI inregistrarile adaugate, daca dau renunt la factura
*****************************************
Procedure STERG_TRANZIT
	Local lcRgdIds, lcSql, llSucces
	lcVVIds = poDate.uuid
	llSucces = .T.

	If !Empty(m.lcVVIds)
		Text To lcSql Textmerge Noshow
BEGIN 
	DELETE FROM ips_voyage_members_vanzari WHERE VV_ID IN (<<m.lcVVIds>>);
	DELETE FROM IPS_VOYAGES_VANZARI WHERE ID IN (<<m.lcVVIds>>); 
END;
		Endtext
		llSucces = goExecutor.oExecuta(m.lcSql)
	Endif && lcVVIds
	Return m.llSucces
Endproc && STERG_TRANZIT

*****************************************
*** Sterg din IPS_VOYAGES_VANZARI inregistrarile adaugate, daca dau renunt la factura
*****************************************
Procedure STERG_CHEIAJ
	Local lcRgdIds, lcSql, llSucces
	lcVVIds = poDate.uuid
	llSucces = .T.

	If !Empty(m.lcVVIds)
		Text To lcSql Textmerge Noshow
BEGIN
	DELETE FROM ips_berthing_details_vanzari where bv_id IN (SELECT ID FROM IPS_BERTHINGS_VANZARI WHERE VV_ID IN (<<m.lcVVIds>>));
	DELETE FROM ips_berthings_vanzari WHERE VV_ID IN (<<m.lcVVIds>>);
	DELETE FROM IPS_VOYAGES_VANZARI WHERE ID IN (<<m.lcVVIds>>);
END;
		Endtext
		llSucces = goExecutor.oExecuta(m.lcSql)
	Endif  && lcVVIds

	Return m.llSucces
Endproc && STERG_CHEIAJ

*******************************************************************************************
*** completez cursul valutar si valorile in lei pe barje, dupa factura, in scopul calcularii valorilor defalcate pe ecluze, senal
*******************************************************************************************
Procedure update_tranzit
	Lparameters tcVVIds

	Local lcSql, llScris, llSucces, llSucces2
	Private pnVVId, pnCurs, pnIdValuta, pnProcTva

	Text To lcSql Textmerge Noshow
update ips_voyage_members_vanzari set curs = ?pnCurs,
    tvaval = ROUND(valval * ?pnProcTVA, ?gnPVal),
    totval = valval + ROUND(valval * ?pnProcTVA, ?gnPVal),
   	valftva = ROUND(valval * ?pnCurs, ?gnPC),
   	valtva = ROUND(ROUND(valval * ?pnCurs, ?gnPC) * ?pnProcTVA , ?gnPC),
   	valctva = ROUND(valval * ?pnCurs, ?gnPC) + ROUND(ROUND(valval * ?pnCurs, ?gnPC) * ?pnProcTVA , ?gnPC)
 where vv_id in (<<m.tcVVIds>>) and id_valuta = ?pnIdValuta
	Endtext

	Select Distinct Curs, id_valuta, proc_tva From crsFactura Into Cursor cValuteTemp
	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)
	If m.llSucces
		Select cValuteTemp
		Scan
			pnCurs = Curs
			pnIdValuta = id_valuta
			pnProcTva = (proc_tva - 1)
			llSucces = goExecutor.oExecuta(m.lcSql)
			If !m.llSucces
				Exit
			Endif
		Endscan
	Endif && llSucces
	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris
	Use In (Select('cValuteTemp'))
	Return m.llSucces
Endproc && update_tranzit

*******************************************************************************************
*** completez in ips_berthing_details_vanzari: cursul valutar si valorile in lei pe barje, dupa factura, in scopul calcularii valorilor defalcate pe ecluze, senal
*******************************************************************************************
Procedure update_cheiaj
	Lparameters tcVVIds

	Local lcSql, llScris, llSucces, llSucces2
	Private pnVVId, pnCurs, pnIdValuta, pnProcTva

	Text To lcSql Textmerge Noshow
update ips_berthing_details_vanzari set curs = ?pnCurs,
    tvaval = ROUND(valval * ?pnProcTVA, ?gnPVal),
    totval = valval + ROUND(valval * ?pnProcTVA, ?gnPVal),
   	valftva = ROUND(valval * ?pnCurs, ?gnPC),
   	valtva = ROUND(ROUND(valval * ?pnCurs, ?gnPC) * ?pnProcTVA , ?gnPC),
   	valctva = ROUND(valval * ?pnCurs, ?gnPC) + ROUND(ROUND(valval * ?pnCurs, ?gnPC) * ?pnProcTVA , ?gnPC)
 where id_valuta = ?pnIdValuta and bv_id in (select id from ips_berthings_vanzari where vv_id in (<<m.tcVVIds>>))
	Endtext

	Select Distinct Curs, id_valuta, proc_tva From crsFactura Into Cursor cValuteTemp
	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)
	If m.llSucces
		Select cValuteTemp
		Scan
			pnCurs = Curs
			pnIdValuta = id_valuta
			pnProcTva = (proc_tva - 1)
			llSucces = goExecutor.oExecuta(m.lcSql)
			If !m.llSucces
				Exit
			Endif
		Endscan
	Endif && llSucces
	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris
	Use In (Select('cValuteTemp'))
	Return m.llSucces
Endproc && update_cheiaj

*******************************************************************************************
*** completez in ips_regdoc: cursul valutar si valorile in lei
*******************************************************************************************
Procedure update_contracte
	Lparameters tcRgdIds

	Local lcSql, llScris, llSucces, llSucces2, lcSqlValuta
	Private pnVVId, pnCurs, pnIdValuta, pnProcTva, pnProcTVAV

	* Folosesc 4 zecimale la rotunjire, pentru ca in recapitulatie sa apara cu 4 zecimale, iar in factura adun toate liniile intr-una singura si rotunjesc suma totala la 2 zecimale
	Text To lcSql Textmerge Noshow
update ips_regdoc set curs = ?pnCurs,
    tvaval = ROUND(valval * ?pnProcTVA, ?gnPval),
    totval = valval + ROUND(valval * ?pnProcTVA, ?gnPval),
   	valftva = ROUND(valval * ?pnCurs, ?gnPC),
   	valtva = ROUND(ROUND(valval * ?pnCurs, ?gnPval) * ?pnProcTVA , ?gnPC),
   	valctva = ROUND(valval * ?pnCurs, ?gnPval) + ROUND(ROUND(valval * ?pnCurs, ?gnPval) * ?pnProcTVA , ?gnPc)
 where id_valuta = ?pnIdValuta and proc_tvav = ?pnProcTVAV and id in (<<m.tcRgdIds>>)
	Endtext

	* In crsFactura este o singura linie cu id_valuta = LEI pentru INTERN sau id_valuta distinct pentru EXTERN
	* Trebuie sa iau id_valuta din IPS_REGDOC, nu din crsFactura
	Text To lcSqlValuta Textmerge Noshow
SELECT distinct id_valuta, proc_tvav FROM ips_regdoc WHERE id in (<<m.tcRgdIds>>)
	Endtext

	llSucces = goExecutor.oExecuta(m.lcSqlValuta, 'cValuteRgd')
	If m.llSucces
		Select r.id_valuta, r.proc_tvav As proc_tva, C.Curs From cValuteRgd r Left Join crsCursuri C On r.id_valuta = C.id_valuta Into Cursor cValuteTemp
	Endif
	Use In (Select('cValuteRgd'))

	llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)
	If m.llSucces
		Select cValuteTemp
		Scan
			pnCurs = Nvl(Curs, 1) && CURS LEI = 1
			pnIdValuta = id_valuta
			pnProcTva = (proc_tva - 1)
			pnProcTVAV = proc_tva
			llSucces = goExecutor.oExecuta(m.lcSql)
			If !m.llSucces
				Exit
			Endif
		Endscan
	Endif && llSucces
	If !m.llSucces
		lcSql = "ROLLBACK"
		llScris = .F.
	Else
		lcSql = "COMMIT"
		llScris = .T.
	Endif
	llScris = goExecutor.oExecuta(m.lcSql)

	llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
	If !m.llSucces2
		amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
	Endif

	llSucces = m.llSucces And m.llScris
	Use In (Select('cValuteTemp'))
	Return m.llSucces
Endproc && update_contracte

********************************************************************************************
*** defalc valoarea pe ecluze si senale navigabile pentru fiecare nava din convoiul facturat pentru inregistrare in Reg. documente si apoi in contabilitate
*** Completez cursorul cRegDoc cu valori defalcate pe ecluze, senal pentru salvarea in Reg. Doc si in ontabilitate
********************************************************************************************
Procedure completeaza_regdoc_tranzit
	Lparameters tcVVIds
	* tnVVId: ips_voyages_vanzari.id

	Private pnVVId, pcVyeId
	Private pnIPSTranzitProcAG, pnIPSTranzitProcCV, pnIPSTranzitProcOV, pnIPSTranzitProcNV
	Local lcSql, llSucces
	Local lcEclC, lcEclP, lcLockName, llShowError, lnEcluzariCdmn, lnEcluzariPamn, lnProcent, lnTotValC
	Local lnTotValP, lnTranzitProcCDMN, lnTranzitProcPAMN, lnTvaValC, lnTvaValP, lnValctvaC, lnValctvaP
	Local lnValfftvaC, lnValfftvaP, lnValtvaC, lnValtvaP, lnValvalC, lnValvalP, loArticol, loRec, lcDeclCdt
	pnVVId = 0
	pcVyeId = ''
	lcDeclCdt = ''
	llSucces = .T.

	Create Cursor cVoyageMembersV (vv_id I, vye_id C(36), DECLCDT C(100), vms_id C(36), ;
		  valftva N(18, 2), valtva N(18, 2), valctva N(18, 2), valval N(18, 2), TVAVAL N(18, 2), totval N(18, 2), id_valuta N(5), procentCDMN N(18, 4), ;
		  valftvaCDMN N(18, 2), valtvaCDMN N(18, 2), valctvaCDMN N(18, 2), valvalCDMN N(18, 2), tvavalCDMN N(18, 2), totvalCDMN N(18, 2), ;
		  valftvaPAMN N(18, 2), valtvaPAMN N(18, 2), valctvaPAMN N(18, 2), valvalPAMN N(18, 2), tvavalPAMN N(18, 2), totvalPAMN N(18, 2), ;
		  valftvaAG1 N(18, 2), valtvaAG1 N(18, 2), valctvaAG1 N(18, 2), valvalAG1 N(18, 2), tvavalAG1 N(18, 2), totvalAG1 N(18, 2), ;
		  valftvaAG2 N(18, 2), valtvaAG2 N(18, 2), valctvaAG2 N(18, 2), valvalAG2 N(18, 2), tvavalAG2 N(18, 2), totvalAG2 N(18, 2), ;
		  valftvaCV1 N(18, 2), valtvaCV1 N(18, 2), valctvaCV1 N(18, 2), valvalCV1 N(18, 2), tvavalCV1 N(18, 2), totvalCV1 N(18, 2), ;
		  valftvaCV2 N(18, 2), valtvaCV2 N(18, 2), valctvaCV2 N(18, 2), valvalCV2 N(18, 2), tvavalCV2 N(18, 2), totvalCV2 N(18, 2), ;
		  valftvaOV1 N(18, 2), valtvaOV1 N(18, 2), valctvaOV1 N(18, 2), valvalOV1 N(18, 2), tvavalOV1 N(18, 2), totvalOV1 N(18, 2), ;
		  valftvaOV2 N(18, 2), valtvaOV2 N(18, 2), valctvaOV2 N(18, 2), valvalOV2 N(18, 2), tvavalOV2 N(18, 2), totvalOV2 N(18, 2), ;
		  valftvaNV1 N(18, 2), valtvaNV1 N(18, 2), valctvaNV1 N(18, 2), valvalNV1 N(18, 2), tvavalNV1 N(18, 2), totvalNV1 N(18, 2), ;
		  valftvaNV2 N(18, 2), valtvaNV2 N(18, 2), valctvaNV2 N(18, 2), valvalNV2 N(18, 2), tvavalNV2 N(18, 2), totvalNV2 N(18, 2), ;
		  valftvaCDMNS N(18, 2), valtvaCDMNS N(18, 2), valctvaCDMNS N(18, 2), valvalCDMNS N(18, 2), tvavalCDMNS N(18, 2), totvalCDMNS N(18, 2), ;
		  valftvaPAMNS N(18, 2), valtvaPAMNS N(18, 2), valctvaPAMNS N(18, 2), valvalPAMNS N(18, 2), tvavalPAMNS N(18, 2), totvalPAMNS N(18, 2))

	pnIPSTranzitProcAG = Iif(Type('gnIPSTranzitProcAG') = 'N', m.gnIPSTranzitProcAG, 0)
	pnIPSTranzitProcCV = Iif(Type('gnIPSTranzitProcCV') = 'N', m.gnIPSTranzitProcCV, 0)
	pnIPSTranzitProcOV = Iif(Type('gnIPSTranzitProcOV') = 'N', m.gnIPSTranzitProcOV, 0)
	pnIPSTranzitProcNV = Iif(Type('gnIPSTranzitProcNV') = 'N', m.gnIPSTranzitProcNV, 0)

	* Pentru fiecare voiaj ales selectez ecluzarile
	llSucces = goExecutor.oExecuta([select distinct vv_id, vye_id, declaratio FROM ips_vvoyages_vanzari where vv_id in (] + m.tcVVIds + [)], "cVVTemp")
	If !m.llSucces
		Create Cursor cVVTemp (vye_id I, declaratio C(20))
	Endif

	Select cVVTemp
	Scan
		pcVyeId = cVVTemp.vye_id
		pnVVId = cVVTemp.vv_id
		lcDeclCdt = Alltrim(Nvl(cVVTemp.declaratio, ''))

		* Selectez ecluzele AGIGEA, CERNAVODA, OVIDIU, NAVODARI prin care a ecluzat convoiul.
		* In IPS_VVOYAGE_LOCKS ecluzarile sunt defalcate pe membrii convoiului si pe camerele ecluzei, nu pe convoi si pe ecluze
		* De aceea selectez distinct id_lock

		* 26.05.2020 selectez si dupa vms_id (membru convoi) pentru ca inregistrez veniturile pe ecluze la nivel de camere de ecluzare
		* o nava poate sa treaca printr-o camera de ecluzare, alta nava prin alta camera sau deloc prin ecluza
		Text To lcSql Textmerge Noshow
		Select vms_id, id_lock,
			CAST(CASE WHEN UPPER(LOCK_NAME) LIKE '%AGIGEA%' THEN 'AGIGEA'
				WHEN UPPER(LOCK_NAME) LIKE '%CERNAVODA%' THEN 'CERNAVODA'
				WHEN UPPER(LOCK_NAME) LIKE '%OVIDIU%' THEN 'OVIDIU'
				WHEN UPPER(LOCK_NAME) LIKE '%NAVODARI%' THEN 'NAVODARI'
				ELSE '' END AS VARCHAR2(20)) AS lock_name,
			chamber_name,
			CAST(CASE WHEN UPPER(LOCK_NAME) LIKE '%AGIGEA%' THEN ?pnIPSTranzitProcAG
				WHEN UPPER(LOCK_NAME) LIKE '%CERNAVODA%' THEN ?pnIPSTranzitProcCV
				WHEN UPPER(LOCK_NAME) LIKE '%OVIDIU%' THEN ?pnIPSTranzitProcOV
				WHEN UPPER(LOCK_NAME) LIKE '%NAVODARI%' THEN ?pnIPSTranzitProcNV
				ELSE 0 END AS NUMBER(6,2)) AS PROCENT
			FROM IPS_VVOYAGE_LOCKS
			WHERE vye_id = ?pcVyeId
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, 'cVoyageLocksX')

		If m.llSucces
			lcSql = [Select VV_ID, VYE_ID,VMS_ID,VALFTVA,VALTVA,VALCTVA,VALVAL,TVAVAL,TOTVAL,ID_VALUTA,Round(DISTANTA_CDMN / DISTANTA, 4) As procentCDMN From IPS_VOYAGE_MEMBERS_VANZARI Where VV_ID = ?pnVVId]

			llSucces = goExecutor.oExecuta(m.lcSql, 'cVoyageMembersX')
			If m.llSucces
				Select cVoyageMembersV
				Append From Dbf('cVoyageMembersX')
				Use In (Select('cVoyageMembersX'))
			Endif
		Endif && m.llSucces

		If m.llSucces
			Select cVoyageMembersV
			Scan For vv_id = m.pnVVId
				lnVmsId = vms_id
				Replace DECLCDT With m.lcDeclCdt

				*** Daca este o singura ecluzare, se calculeaza valoarea senalului ca procent fix, iar diferenta trece pe ecluza
				*** Daca sunt mai multe ecluzari, se calculeaza valoare senalului ca diferenta dintre valoarea parcursa pe canal - valoare ecluzari

				********************************
				*** Valori totale pe CDMN si PAMN in functie de procentul de distanta parcurs de fiecare nava pe canalul CDMN
				********************************
				* CDMN
				Replace valftvaCDMN With Round(valftva * procentCDMN, 2), valctvaCDMN With Round(valctva * procentCDMN, 2)
				Replace valtvaCDMN With valctvaCDMN - valftvaCDMN
				Replace valvalCDMN With Round(valval * procentCDMN, 2), totvalCDMN With Round(totval * procentCDMN, 2)
				Replace tvavalCDMN With totvalCDMN - valvalCDMN

				* PAMN
				Replace valftvaPAMN With valftva - valftvaCDMN, valctvaPAMN With valctva - valctvaCDMN
				Replace valtvaPAMN With valtva - valtvaCDMN
				Replace valvalPAMN With valval - valvalCDMN, totvalPAMN With totval - totvalCDMN
				Replace tvavalPAMN With TVAVAL - tvavalCDMN

				*****************************************
				* Calculez valorile pe senale navigabile
				*****************************************
				lnTranzitProcCDMN = (100 - (m.pnIPSTranzitProcAG + m.pnIPSTranzitProcCV)) / 100
				lnTranzitProcPAMN = (100 - (m.pnIPSTranzitProcOV + m.pnIPSTranzitProcNV)) / 100

				Select cVoyageMembersV
				* Senal CDMN = valoarea CDMN * procent senal CDMN
				Replace valftvaCDMNS With Round(valftvaCDMN * m.lnTranzitProcCDMN, 2), valctvaCDMNS With Round(valctvaCDMN * lnTranzitProcCDMN, 2)
				Replace valtvaCDMNS With valctvaCDMNS - valftvaCDMNS

				Replace valvalCDMNS With Round(valvalCDMN * m.lnTranzitProcCDMN, 2), totvalCDMNS With Round(totvalCDMN * m.lnTranzitProcCDMN, 2)
				Replace tvavalCDMNS With totvalCDMNS - valvalCDMNS

				* Senal PAMN WITH valoarea PAMN * procent senal PAMN
				Replace valftvaPAMNS With Round(valftvaPAMN * m.lnTranzitProcPAMN, 2), valctvaPAMNS With Round(valctvaPAMN * lnTranzitProcPAMN, 2)
				Replace valtvaPAMNS With valctvaPAMNS - valftvaPAMNS

				Replace valvalPAMNS With Round(valvalPAMN * m.lnTranzitProcPAMN, 2), totvalPAMNS With Round(totvalPAMN * m.lnTranzitProcPAMN, 2)
				Replace tvavalPAMNS With totvalPAMNS - valvalPAMNS

				lnEcluzariCdmn = 0
				lnEcluzariPamn = 0
				lcEclC = ""
				lcEclP = ""
				lcChamberC = ""
				lcChamberP = ""

				* Ecluze
				Select cVoyageLocksX
				Scan For vms_id = m.lnVmsId
					lnProcent = procent / 100
					lcLockName = Alltrim(lock_name)
					lcChamberName = Alltrim(chamber_name)

					Select cVoyageMembersV
					Do Case
						Case m.lcLockName = 'AGIGEA' And m.lcChamberName = 'SAS1'
							Replace valftvaAG1 With Round(valftvaCDMN * lnProcent, 2), valctvaAG1 With Round(valctvaCDMN * lnProcent, 2)
							Replace valtvaAG1 With valctvaAG1 - valftvaAG1

							Replace valvalAG1 With Round(valvalCDMN * lnProcent, 2), totvalAG1 With Round(totvalCDMN * lnProcent, 2)
							Replace tvavalAG1 With totvalAG1 - valvalAG1

							lnEcluzariCdmn = lnEcluzariCdmn + 1
							lcEclC = m.lcLockName
							lcChamberC = m.lcChamberName
						Case m.lcLockName = 'AGIGEA' And m.lcChamberName = 'SAS2'
							Replace valftvaAG2 With Round(valftvaCDMN * lnProcent, 2), valctvaAG2 With Round(valctvaCDMN * lnProcent, 2)
							Replace valtvaAG2 With valctvaAG2 - valftvaAG2

							Replace valvalAG2 With Round(valvalCDMN * lnProcent, 2), totvalAG2 With Round(totvalCDMN * lnProcent, 2)
							Replace tvavalAG2 With totvalAG2 - valvalAG2

							lnEcluzariCdmn = lnEcluzariCdmn + 1
							lcEclC = m.lcLockName
							lcChamberC = m.lcChamberName
						Case m.lcLockName = 'CERNAVODA' And m.lcChamberName = 'SAS1'
							Replace valftvaCV1 With Round(valftvaCDMN * lnProcent, 2), valctvaCV1 With Round(valctvaCDMN * lnProcent, 2)
							Replace valtvaCV1 With valctvaCV1 - valftvaCV1

							Replace valvalCV1 With Round(valvalCDMN * lnProcent, 2), totvalCV1 With Round(totvalCDMN * lnProcent, 2)
							Replace tvavalCV1 With totvalCV1 - valvalCV1

							lcEclC = m.lcLockName
							lnEcluzariCdmn = lnEcluzariCdmn + 1
							lcChamberC = m.lcChamberName
						Case m.lcLockName = 'CERNAVODA' And m.lcChamberName = 'SAS2'
							Replace valftvaCV2 With Round(valftvaCDMN * lnProcent, 2), valctvaCV2 With Round(valctvaCDMN * lnProcent, 2)
							Replace valtvaCV2 With valctvaCV2 - valftvaCV2

							Replace valvalCV2 With Round(valvalCDMN * lnProcent, 2), totvalCV2 With Round(totvalCDMN * lnProcent, 2)
							Replace tvavalCV2 With totvalCV2 - valvalCV2

							lcEclC = m.lcLockName
							lnEcluzariCdmn = lnEcluzariCdmn + 1
							lcChamberC = m.lcChamberName
						Case m.lcLockName = 'OVIDIU' And m.lcChamberName = 'C1'
							Replace valftvaOV1 With Round(valftvaPAMN * lnProcent, 2), valctvaOV1 With Round(valctvaPAMN * lnProcent, 2)
							Replace valtvaOV1 With valctvaOV1 - valftvaOV1

							Replace valvalOV1 With Round(valvalPAMN * lnProcent, 2), totvalOV1 With Round(totvalPAMN * lnProcent, 2)
							Replace tvavalOV1 With totvalOV1 - valvalOV1

							lcEclP = m.lcLockName
							lnEcluzariPamn = lnEcluzariPamn + 1
							lcChamberP = m.lcChamberName
						Case m.lcLockName = 'OVIDIU' And m.lcChamberName = 'C2'
							Replace valftvaOV2 With Round(valftvaPAMN * lnProcent, 2), valctvaOV2 With Round(valctvaPAMN * lnProcent, 2)
							Replace valtvaOV2 With valctvaOV2 - valftvaOV2

							Replace valvalOV2 With Round(valvalPAMN * lnProcent, 2), totvalOV2 With Round(totvalPAMN * lnProcent, 2)
							Replace tvavalOV2 With totvalOV2 - valvalOV2

							lcEclP = m.lcLockName
							lnEcluzariPamn = lnEcluzariPamn + 1
							lcChamberP = m.lcChamberName
						Case m.lcLockName = 'NAVODARI' And m.lcChamberName = 'C1'
							Replace valftvaNV1 With Round(valftvaPAMN * lnProcent, 2), valctvaNV1 With Round(valctvaPAMN * lnProcent, 2)
							Replace valtvaNV1 With valctvaNV1 - valftvaNV1

							Replace valvalNV1 With Round(valvalPAMN * lnProcent, 2), totvalNV1 With Round(totvalPAMN * lnProcent, 2)
							Replace tvavalNV1 With totvalNV1 - valvalNV1

							lcEclP = m.lcLockName
							lnEcluzariPamn = lnEcluzariPamn + 1
							lcChamberP = m.lcChamberName
						Case m.lcLockName = 'NAVODARI' And m.lcChamberName = 'C2'
							Replace valftvaNV2 With Round(valftvaPAMN * lnProcent, 2), valctvaNV2 With Round(valctvaPAMN * lnProcent, 2)
							Replace valtvaNV2 With valctvaNV2 - valftvaNV2

							Replace valvalNV2 With Round(valvalPAMN * lnProcent, 2), totvalNV2 With Round(totvalPAMN * lnProcent, 2)
							Replace tvavalNV2 With totvalNV2 - valvalNV2

							lcEclP = m.lcLockName
							lnEcluzariPamn = lnEcluzariPamn + 1
							lcChamberP = m.lcChamberName
					Endcase
				Endscan && cVoyageLocksX

				*** Diferenta (tranzit CDMN/PAMN - senal CDMN/PAMN - ecluzari (AG,CV/OV,NV) trece pe ecluzare pe fiecare canal, daca exista, altfel pe senal
				Select cVoyageMembersV
				lnValfftvaC = valftvaCDMN - (valftvaCDMNS + valftvaAG1 + valftvaCV1 + valftvaAG2 + valftvaCV2)
				lnValctvaC = valctvaCDMN - (valctvaCDMNS + valctvaAG1 + valctvaCV1 + valctvaAG2 + valctvaCV2)
				lnValtvaC = m.lnValctvaC - m.lnValfftvaC

				lnValvalC = valvalCDMN - (valvalCDMNS + valvalAG1 + valvalCV1 + valvalAG2 + valvalCV2)
				lnTotValC = totvalCDMN - (totvalCDMNS + totvalAG1 + totvalCV1 + totvalAG2 + totvalCV2)
				lnTvaValC = m.lnTotValC - m.lnValvalC

				lnValfftvaP = valftvaPAMN - (valftvaPAMNS + valftvaOV1 + valftvaNV1 + valftvaOV2 + valftvaNV2)
				lnValctvaP = valctvaPAMN - (valctvaPAMNS + valctvaOV1 + valctvaNV1 + valctvaOV2 + valctvaNV2)
				lnValtvaP = m.lnValctvaP - m.lnValfftvaP

				lnValvalP = valvalPAMN - (valvalPAMNS + valvalOV1 + valvalNV1 + valvalOV2 + valvalNV2)
				lnTotValP = totvalPAMN - (totvalPAMNS + totvalOV1 + totvalNV1 + totvalOV2 + totvalNV2)
				lnTvaValP = m.lnTotValP - m.lnValvalP

				Select cVoyageMembersV
				If m.lnEcluzariCdmn = 0
					* Senal CDMN = valoarea CDMN - (AG + CV)
					Replace valftvaCDMNS With valftvaCDMNS + m.lnValfftvaC, valctvaCDMNS With valctvaCDMNS + m.lnValctvaC, valtvaCDMNS With valtvaCDMNS + lnValtvaC
					Replace valvalCDMNS With valvalCDMNS + m.lnValvalC, totvalCDMNS With totvalCDMNS + m.lnTotValC, tvavalCDMNS With tvavalCDMNS + m.lnTvaValC
				Else
					Do Case
						Case m.lcEclC = 'AGIGEA' And m.lcChamberC = 'SAS1' && pun diferenta pe ultima ecluza
							Replace valftvaAG1 With valftvaAG1 + m.lnValfftvaC, valctvaAG1 With valctvaAG1 + m.lnValctvaC, valtvaAG1 With valtvaAG1 + m.lnValtvaC
							Replace valvalAG1 With valvalAG1 + m.lnValvalC, totvalAG1 With totvalAG1 + m.lnTotValC, tvavalAG1 With tvavalAG1 + m.lnTvaValC

						Case m.lcEclC = 'AGIGEA' And m.lcChamberC = 'SAS2' && pun diferenta pe ultima ecluza
							Replace valftvaAG2 With valftvaAG2 + m.lnValfftvaC, valctvaAG2 With valctvaAG2 + m.lnValctvaC, valtvaAG2 With valtvaAG2 + m.lnValtvaC
							Replace valvalAG2 With valvalAG2 + m.lnValvalC, totvalAG2 With totvalAG2 + m.lnTotValC, tvavalAG2 With tvavalAG2 + m.lnTvaValC

						Case m.lcEclC = 'CERNAVODA' And m.lcChamberC = 'SAS1' && pun diferenta pe ultima ecluza
							Replace valftvaCV1 With valftvaCV1 + m.lnValfftvaC, valctvaCV1 With valctvaCV1 + m.lnValctvaC, valtvaCV1 With valtvaCV1 + m.lnValtvaC
							Replace valvalCV1 With valvalCV1 + m.lnValvalC, totvalCV1 With totvalCV1 + m.lnTotValC, tvavalCV1 With tvavalCV1 + m.lnTvaValC

						Otherwise && CASE m.lcEclC = 'CERNAVODA' AND m.lcChamber = 'SAS2' && pun diferenta pe ultima ecluza
							Replace valftvaCV2 With valftvaCV2 + m.lnValfftvaC, valctvaCV2 With valctvaCV2 + m.lnValctvaC, valtvaCV2 With valtvaCV2 + m.lnValtvaC
							Replace valvalCV2 With valvalCV2 + m.lnValvalC, totvalCV2 With totvalCV2 + m.lnTotValC, tvavalCV2 With tvavalCV2 + m.lnTvaValC
					Endcase
				Endif

				If m.lnEcluzariPamn = 0
					* Senal PAMN  = valoarea PAMN - (OV + NV)
					Replace valftvaPAMNS With valftvaPAMNS + m.lnValfftvaP, valctvaPAMNS With valctvaPAMNS + m.lnValctvaP, valtvaPAMNS With valtvaPAMNS + lnValtvaP
					Replace valvalPAMNS With valvalPAMNS + m.lnValvalP, totvalPAMNS With totvalPAMNS + m.lnTotValP, tvavalPAMNS With tvavalPAMNS + m.lnTvaValP
				Else
					Do Case
						Case m.lcEclP = 'OVIDIU' And m.lcChamberP = 'C1' && pun diferenta pe ultima ecluza
							Replace valftvaOV1 With valftvaOV1 + m.lnValfftvaP, valctvaOV1 With valctvaOV1 + m.lnValctvaP, valtvaOV1 With valtvaOV1 + m.lnValtvaP
							Replace valvalOV1 With valvalOV1 + m.lnValvalP, totvalOV1 With totvalOV1 + m.lnTotValP, tvavalOV1 With tvavalOV1 + m.lnTvaValP

						Case m.lcEclP = 'OVIDIU' And m.lcChamberP = 'C2' && pun diferenta pe ultima ecluza
							Replace valftvaOV2 With valftvaOV2 + m.lnValfftvaP, valctvaOV2 With valctvaOV2 + m.lnValctvaP, valtvaOV2 With valtvaOV2 + m.lnValtvaP
							Replace valvalOV2 With valvalOV2 + m.lnValvalP, totvalOV2 With totvalOV2 + m.lnTotValP, tvavalOV2 With tvavalOV2 + m.lnTvaValP

						Case m.lcEclP = 'NAVODARI' And m.lcChamberP = 'C1' && pun diferenta pe ultima ecluza
							Replace valftvaNV1 With valftvaNV1 + m.lnValfftvaP, valctvaNV1 With valctvaNV1 + m.lnValctvaP, valtvaNV1 With valtvaNV1 + m.lnValtvaP
							Replace valvalNV1 With valvalNV1 + m.lnValvalP, totvalNV1 With totvalNV1 + m.lnTotValP, tvavalNV1 With tvavalNV1 + m.lnTvaValP

						Otherwise && m.lcEclP = 'NAVODARI' AND m.lcChamber = 'C2'
							Replace valftvaNV2 With valftvaNV2 + m.lnValfftvaP, valctvaNV2 With valctvaNV2 + m.lnValctvaP, valtvaNV2 With valtvaNV2 + m.lnValtvaP
							Replace valvalNV2 With valvalNV2 + m.lnValvalP, totvalNV2 With totvalNV2 + m.lnTotValP, tvavalNV2 With tvavalNV2 + m.lnTvaValP
					Endcase
				Endif
			Endscan && cVoyageMembersV
		Endif && llSucces

		Use In (Select('cVoyageLocksX'))
	Endscan && cVVTemp
	Use In (Select('cVVTemp'))

	Select vye_id, DECLCDT, id_valuta, ;
		Sum(valftvaAG1) As valftvaAG1, Sum(valtvaAG1) As valtvaAG1, Sum(valctvaAG1) As valctvaAG1, Sum(valvalAG1) As valvalAG1, Sum(tvavalAG1) As tvavalAG1, Sum(totvalAG1) As totvalAG1, ;
		Sum(valftvaCV1) As valftvaCV1, Sum(valtvaCV1) As valtvaCV1, Sum(valctvaCV1) As valctvaCV1, Sum(valvalCV1) As valvalCV1, Sum(tvavalCV1) As tvavalCV1, Sum(totvalCV1) As totvalCV1, ;
		Sum(valftvaOV1) As valftvaOV1, Sum(valtvaOV1) As valtvaOV1, Sum(valctvaOV1) As valctvaOV1, Sum(valvalOV1) As valvalOV1, Sum(tvavalOV1) As tvavalOV1, Sum(totvalOV1) As totvalOV1, ;
		Sum(valftvaNV1) As valftvaNV1, Sum(valtvaNV1) As valtvaNV1, Sum(valctvaNV1) As valctvaNV1, Sum(valvalNV1) As valvalNV1, Sum(tvavalNV1) As tvavalNV1, Sum(totvalNV1) As totvalNV1, ;
		Sum(valftvaAG2) As valftvaAG2, Sum(valtvaAG2) As valtvaAG2, Sum(valctvaAG2) As valctvaAG2, Sum(valvalAG2) As valvalAG2, Sum(tvavalAG2) As tvavalAG2, Sum(totvalAG2) As totvalAG2, ;
		Sum(valftvaCV2) As valftvaCV2, Sum(valtvaCV2) As valtvaCV2, Sum(valctvaCV2) As valctvaCV2, Sum(valvalCV2) As valvalCV2, Sum(tvavalCV2) As tvavalCV2, Sum(totvalCV2) As totvalCV2, ;
		Sum(valftvaOV2) As valftvaOV2, Sum(valtvaOV2) As valtvaOV2, Sum(valctvaOV2) As valctvaOV2, Sum(valvalOV2) As valvalOV2, Sum(tvavalOV2) As tvavalOV2, Sum(totvalOV2) As totvalOV2, ;
		Sum(valftvaNV2) As valftvaNV2, Sum(valtvaNV2) As valtvaNV2, Sum(valctvaNV2) As valctvaNV2, Sum(valvalNV2) As valvalNV2, Sum(tvavalNV2) As tvavalNV2, Sum(totvalNV2) As totvalNV2, ;
		Sum(valftvaCDMNS) As valftvaCDMNS, Sum(valtvaCDMNS) As valtvaCDMNS, Sum(valctvaCDMNS) As valctvaCDMNS, Sum(valvalCDMNS) As valvalCDMNS, Sum(tvavalCDMNS) As tvavalCDMNS, Sum(totvalCDMNS) As totvalCDMNS, ;
		Sum(valftvaPAMNS) As valftvaPAMNS, Sum(valtvaPAMNS) As valtvaPAMNS, Sum(valctvaPAMNS) As valctvaPAMNS, Sum(valvalPAMNS) As valvalPAMNS, Sum(tvavalPAMNS) As tvavalPAMNS, Sum(totvalPAMNS) As totvalPAMNS ;
		From cVoyageMembersV ;
		Group By vye_id, DECLCDT, id_valuta ;
		Into Cursor cVoyagesValori

	Use In (Select('cVoyageMembersV'))

	Delete From cRegDoc && curat cRegDoc

	Select cVoyagesValori
	Scan
		Scatter Name loRec
		lnCantitate = Iif(valctvaAG1 < 0 Or valctvaCV1 < 0 Or valctvaOV1 < 0 Or valctvaNV1 < 0 Or valctvaCDMNS < 0 Or valctvaPAMNS < 0 Or valctvaAG2 < 0 Or valctvaCV2 < 0 Or valctvaOV2 < 0 Or valctvaNV2 < 0, -1, 1)
		With loRec
			If .valftvaAG1 <> 0 Or .valtvaAG1 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'AGIGEA-SAS1', .valftvaAG1, .valtvaAG1, .valctvaAG1, .valvalAG1, .valvalAG1, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaCV1 <> 0 Or .valtvaCV1 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'CERNAVODA-SAS1', .valftvaCV1, .valtvaCV1, .valctvaCV1, .valvalCV1, .valvalCV1, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaOV1 <> 0 Or .valtvaOV1 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'OVIDIU-C1', .valftvaOV1, .valtvaOV1, .valctvaOV1, .valvalOV1, .valvalOV1, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaNV1 <> 0 Or .valtvaNV1 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'NAVODARI-C1', .valftvaNV1, .valtvaNV1, .valctvaNV1, .valvalNV1, .valvalNV1, .id_valuta, m.lnCantitate)
			Endif

			If .valftvaAG2 <> 0 Or .valtvaAG2 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'AGIGEA-SAS2', .valftvaAG2, .valtvaAG2, .valctvaAG2, .valvalAG2, .valvalAG2, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaCV2 <> 0 Or .valtvaCV2 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'CERNAVODA-SAS2', .valftvaCV2, .valtvaCV2, .valctvaCV2, .valvalCV2, .valvalCV2, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaOV2 <> 0 Or .valtvaOV2 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'OVIDIU-C2', .valftvaOV2, .valtvaOV2, .valctvaOV2, .valvalOV2, .valvalOV2, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaNV2 <> 0 Or .valtvaNV2 <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'NAVODARI-C2', .valftvaNV2, .valtvaNV2, .valctvaNV2, .valvalNV2, .valvalNV2, .id_valuta, m.lnCantitate)
			Endif

			If .valftvaCDMNS <> 0 Or .valtvaCDMNS <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'SENAL CDMN', .valftvaCDMNS, .valtvaCDMNS, .valctvaCDMNS, .valvalCDMNS, .valvalCDMNS, .id_valuta, m.lnCantitate)
			Endif
			If .valftvaPAMNS <> 0 Or .valtvaPAMNS <> 0
				Insert Into cRegDoc(Document, locatia, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.DECLCDT, 'SENAL PAM', .valftvaPAMNS, .valtvaPAMNS, .valctvaPAMNS, .valvalPAMNS, .valvalPAMNS, .id_valuta, m.lnCantitate)
			Endif
		Endwith
	Endscan && cVoyagesValori
	Use In (Select('cVoyagesValori'))

	loArticol = GetPrestatieByTip(TIP_TRANZIT)

	Update cRegDoc Set id_articol = GetIdPrestatieByArticol(GetPrestatieByTip(TIP_TRANZIT)), id_locatia = GetIdLocatieByName(Alltrim(locatia))
	Return m.llSucces
Endproc && completeaza_regdoc_tranzit

********************************************************************************************
*** defalc valoarea pe locatii pentru fiecare nava din convoiul facturat pentru inregistrare in Reg. documente si apoi in contabilitate
*** Completez cursorul cRegDoc cu valori defalcate pe ecluze, senal pentru salvarea in Reg. Doc si in ontabilitate
********************************************************************************************
Procedure completeaza_regdoc_cheiaj
	Lparameters tcVVIds
	* tnVVId: ips_voyages_vanzari.id

	Private pnVVId
	Local lcSql, llSucces, lcDeclCdt

	pnVVId = 0
	llSucces = .T.
	lcDeclCdt = ''

	llSucces = goExecutor.oExecuta([select distinct vv_id, declaratio FROM ips_vvoyages_vanzari where vv_id in (] + m.tcVVIds + [)], "cVVTemp")
	If !m.llSucces
		Create Cursor cVVTemp (vye_id I, declaratio C(20))
	Endif

	Delete From cRegDoc && curat cRegdoc

	Select cVVTemp
	Scan
		lcDeclCdt = Alltrim(Nvl(cVVTemp.declaratio, ''))
		pnVVId = cVVTemp.vv_id

		Text To lcSql Noshow
Select b.vv_id, b.id_locatia, bd.id_articol, bd.id_valuta, Sum(bd.valftva) As valftva, Sum(bd.valtva) As valtva, Sum(bd.valctva) As valctva, Sum(bd.valval) As valval, Sum(bd.valval) As Pret 
	From ips_berthing_details_vanzari bd Join ips_berthings_vanzari b On bd.bv_id = b.Id 
	where b.vv_id = ?pnVVId
	Group By b.vv_id, b.id_locatia, bd.id_articol, bd.id_valuta
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, 'cCheiajValori')

		If m.llSucces
			Select cCheiajValori
			Scan
				Scatter Name loRec
				AddProperty(loRec, 'articol', GetArticolById(loRec.id_articol))
				AddProperty(loRec, 'locatia', GetLocatieById(loRec.id_locatia))
				AddProperty(loRec, 'document', m.lcDeclCdt)
				AddProperty(loRec, 'cantitate', Iif(loRec.valctva < 0, -1, 1))
				With loRec
					Insert Into cRegDoc(Document, id_locatia, locatia, id_articol, articol, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate) Values (.Document, .id_locatia, .locatia, .id_articol, .articol, .valftva, .valtva, .valctva, .valval, .valval, .id_valuta, .cantitate)
				Endwith
			Endscan
		Endif && llSucces
		Use In (Select('cCheiajValori'))
	Endscan && cVVTemp

	Use In (Select('cVVTemp'))

	Return m.llSucces
Endproc && completeaza_regdoc_cheiaj


********************************************************************************************
*** completez cRegdoc pe locatii din ips_regdoc
********************************************************************************************
Procedure completeaza_regdoc_contracte
	Lparameters tcRgdIds
	Local llSucces, loRec, llIntern

	Select crsCapFactura
	Go Top
	llIntern = (crsCapFactura.intern = 1)

	Text To lcSql Textmerge Noshow
SELECT id, document, id_locatia, locatia, id_articol, articol, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate, id_valuta, proc_tvav, CAST(0 as NUMBER(20)) as id_jtva_coloana, CAST(0 as NUMBER(20)) as id_jtva_coloana_ex FROM ips_vregdoc WHERE id in (<<m.tcRgdIds>>)
	Endtext

	llSucces = goExecutor.oExecuta(m.lcSql, 'cContractValori')

	If m.llSucces
		* Completez id_jtva_coloana din crsFactura
		Select id_valuta, proc_tva, id_jtva_coloana, id_jtva_coloana_ex From crsFactura Into Cursor cCoteFacturaTemp

		Select cCoteFacturaTemp
		Scan
			Scatter Name loRec
			* Factura intern are toate articolele modificate in LEI si nu mai corespund fata de regdoc
			If m.llIntern
				Update cContractValori Set id_jtva_coloana = loRec.id_jtva_coloana, id_jtva_coloana_ex = loRec.id_jtva_coloana_ex Where proc_tvav = loRec.proc_tva
			Else
				Update cContractValori Set id_jtva_coloana = loRec.id_jtva_coloana, id_jtva_coloana_ex = loRec.id_jtva_coloana_ex Where id_valuta = loRec.id_valuta And proc_tvav = loRec.proc_tva
			Endif
		Endscan

		Use In (Select('cCoteFacturaTemp'))

		Delete From cRegDoc && curat cRegDoc

		Select cContractValori
		Scan
			Scatter Name loRec
			With loRec
				Insert Into cRegDoc(Id, id_locatia, locatia, id_articol, articol, valftva, valtva, valctva, valval, Pret, id_valuta, cantitate, id_jtva_coloana, id_jtva_coloana_ex) ;
					Values (.Id, .id_locatia, .locatia, .id_articol, .articol, .valftva, .valtva, .valctva, .valval, .valval, .id_valuta, .cantitate, .id_jtva_coloana, .id_jtva_coloana_ex)
			Endwith
		Endscan
	Endif && llSucces
	Use In (Select('cContractValori'))

	llSucces = .T.

	Return m.llSucces
Endproc && completeaza_regdoc_contracte


********************************************************************************************
*** completez cRegdoc pe locatii din ips_regdoc
********************************************************************************************
Procedure completeaza_regdoc_penalitati
	Lparameters tcRgdIds


	Local lcSql, llSucces, lnCantitate, lnDiferenta, lnFactId, lnIdJtva, lnIdJtvaEx, lnIdMonedaNationala, loMonedaNationala
	Local lnPrestatieIdCheiaj, lnPrestatieIdTranzit, lnProcTva, lnValTvaF, lnValTvaR, lnValctvaF, lnValctvaR, lnValftvaF, lnValftvaR
	Local lcListaIdFact

	Select * From crsCalculPenalitatiAles Where sters = 0 Into Cursor cFacturiPenalitati NOFILTER

	*** REGDOC pentru facturile originale
	Select Distinct id_fact From cFacturiPenalitati Into Cursor cFacturiTemp
	lcListaIdFact = ''
	Select cFacturiTemp
	Scan
		lcListaIdFact = lcListaIdFact + ',' + Alltrim(Str(id_fact))
	Endscan
	lcListaIdFact = Iif(!Empty(m.lcListaIdFact), Substr(m.lcListaIdFact, 2), '')
	Use In (Select('cFacturiTemp'))

	lcSql = [SELECT v.id_fact, r.id, r.id_locatia, r.id_articol, r.id_valuta, r.valftva, r.valval FROM ips_regdoc r join vanzari v on r.id_vanzare = v.id_vanzare WHERE v.id_fact in (] + m.lcListaIdFact + [)]
	llSucces = goExecutor.oExecuta(m.lcSql, 'cRegdocPenalitati')
	If !m.llSucces
		Exit
	Endif


	*** selectez prestatiile facturate pentru tip 2,3,5,9 alte prestatii, chirii, livrare apa, facturi diverse
	*** trebuie sa defalc suma de penalitati dupa cont, analitic pentru fiecare prestatie, 

	*** calculez suma totala facturata pe fiecare document din regdoc, pentru calcularea proportiilor fiecarei prestatii
	Select id_fact, Sum(valftva) As valftva, Sum(valval) As valval ;
		From cRegdocPenalitati ;
		Group By id_fact ;
		Into Cursor cRegDocFacturi

	Select fp.id_fact, Cast(Nvl(r.id_articol, 0) As N(12)) As id_articol, Cast(Nvl(r.id_locatia, 0) As N(12)) As id_locatia, ;
		Cast(Iif(fp.suma <> 0 And Nvl(r.valftva, 0) <> 0 And Nvl(rf.valftva, 0) <> 0, Round((r.valftva / rf.valftva) * fp.penalitati, m.gnPC), Iif(Empty(Nvl(rf.id_fact, 0)), fp.penalitati, 0.00)) As N(16, 2)) As suma, ;
		fp.penalitati As psuma, Nvl(fp.tip, 0) As tip, fp.nrfact, fp.id_contract, fp.contract ;
		From (Select id_fact, Max(id_ctr) As id_contract, Max(numar) As contract, Max(nrfact) As nrfact, Max(Nvl(tip, 0)) As tip, Sum(suma) As suma, Sum(sumaval) As sumaval, Sum(penalitati) As penalitati ;
		  From cFacturiPenalitati ;
		  Where Inlist(tip, NTIP_TRANZIT, NTIP_CHEIAJ, NTIP_APA, NTIP_CHIRII, NTIP_ALTE, NTIP_DIVERSE) ;
		  Group By id_fact) fp Left Join cRegdocPenalitati r On r.id_fact = fp.id_fact ;
		Left Join cRegDocFacturi rf On rf.id_fact = fp.id_fact ;
		Order By fp.id_fact, r.valftva Desc ;
		Into Cursor cRegDocTemp Readwrite

	* Completez prestatia pentru cheiaj, daca nu o are completata
	lnPrestatieIdCheiaj = GetIdPrestatieByArticol(GetPrestatieByTip(TIP_CHEIAJ))
	lnPrestatieIdTranzit = GetIdPrestatieByArticol(GetPrestatieByTip(TIP_TRANZIT))
	Update cRegDocTemp Set id_articol = m.lnPrestatieIdCheiaj Where tip = NTIP_CHEIAJ And Empty(Nvl(id_articol, 0))
	Update cRegDocTemp Set id_articol = m.lnPrestatieIdTranzit Where tip = NTIP_TRANZIT And Empty(Nvl(id_articol, 0))

	Use In (Select('cFacturiPenalitati'))
	Use In (Select('cRegDocFacturi'))

	*** Completez diferentele de zecimale dintre suma globala de penalitati pe factura si sumele defalcate pe prestatii
	Select id_fact, Sum(suma) As suma, Min(psuma) As psuma ;
		From cRegDocTemp ;
		Group By id_fact ;
		Into Cursor cRegDocSume NOFILTER

	Select cRegDocSume
	Scan
		lnFactId = id_fact
		lnDiferenta = psuma - suma
		If m.lnDiferenta <> 0
			Select cRegDocTemp
			Locate For id_fact = m.lnFactId
			If Found()
				Replace suma With suma + m.lnDiferenta
			Endif
		Endif
	Endscan
	Use In (Select('cRegDocSume'))

	Select crsFactura
	Go Top
	lnIdJtva = id_jtva_coloana
	lnIdJtvaEx = id_jtva_coloana_ex
	lnCantitate = 1
	lnProcTva = proc_tva && 1,00
	loMonedaNationala = GetMonedaNationala()
	lnIdMonedaNationala = loMonedaNationala.id_valuta

	Delete From cRegDoc && curat cRegdoc la Facturi diverse

	Insert Into cRegDoc(id_locatia, locatia, id_articol, articol, valftva, valval, Pret, id_valuta, id_jtva_coloana, id_jtva_coloana_ex, cantitate, Document, id_contract, contract) ;
		Select id_locatia, GetLocatieById(id_locatia), id_articol, GetArticolById(id_articol), suma, suma, suma, m.lnIdMonedaNationala, m.lnIdJtva, m.lnIdJtvaEx, m.lnCantitate As cantitate, Alltrim(Str(nrfact)) As Document, id_contract, contract ;
		From cRegDocTemp

	Update cRegDoc Set valtva = Round(valftva * (m.lnProcTva - 1), m.gnPC), TVAVAL = Round(valval * (m.lnProcTva - 1), m.gnPC)
	Update cRegDoc Set valctva = valftva + valtva, totval = valval + TVAVAL

	* Ajustez diferenta dintre valoarea de pe factura si total valoare defalcata pe locatii si articole
	Calculate Sum(valftva), Sum(valtva), Sum(valctva) To lnValftvaF, lnValTvaF, lnValctvaF In crsFactura
	Calculate Sum(valftva), Sum(valtva), Sum(valctva) To lnValftvaR, lnValTvaR, lnValctvaR In cRegDoc

	Select cRegDoc
	Go Top
	Replace valftva With valftva + (m.lnValftvaF - m.lnValftvaR), valtva With valtva + (lnValTvaF - m.lnValTvaR), valctva With (lnValctvaF - m.lnValctvaR)
	Replace valval With valftva, TVAVAL With valtva, totval With valctva

	Use In (Select('cRegDocTemp'))

	llSucces = .T.

	Return m.llSucces
Endproc && completeaza_regdoc_penalitati

********************************************************************************************
*** facturi diverse. se iau articolele direct din factura
*** scriu valoarea pe locatii pentru fiecare articol din factura pentru inregistrare in Reg. documente si apoi in contabilitate
********************************************************************************************
Procedure completeaza_regdoc_alte
	Lparameters tuUid
	* Nu folosesc tuUid, pentru ca nu se completeaza intr-un formular distinct.
	* Apelez procedura la salvarea facturilor diverse si completez cRegdoc direct din crsFactura
	Local llSucces

	llSucces = .F.
	Delete From cRegDoc && curat cRegdoc la Facturi diverse

	Select crsFactura
	Scan
		Scatter Name loRec
		AddProperty(loRec, 'document', '')
		AddProperty(loRec, 'articol', GetArticolById(loRec.id_articol))
		AddProperty(loRec, 'locatia', GetLocatieById(loRec.id_locatia))

		With loRec
			Insert Into cRegDoc(id_locatia, locatia, id_articol, articol, valftva, valtva, valctva, valval, Pret, id_valuta, id_jtva_coloana, id_jtva_coloana_ex, cantitate) ;
				Values (.id_locatia, .locatia, .id_articol, .articol, .valftva, .valtva, .valctva, .valval, .pretval, .id_valuta, .id_jtva_coloana, .id_jtva_coloana_ex, .cantitate)
		Endwith

	Endscan
	llSucces = .T.

	Return m.llSucces
Endproc && completeaza_regdoc_alte

**************************************************
*** Completeaza cursul valutar in cRegdoc din crsFactura
**************************************************
Procedure completeaza_regdoc_curs
	Local lcSelect, lnCurs, lnIdValuta, llSucces
	llSucces = .T.

	lcSelect = Select()
	Select Distinct id_valuta, Curs From crsFactura Into Cursor cValuteTemp
	Select cValuteTemp
	Scan
		lnCurs = Curs
		lnIdValuta = id_valuta
		Update cRegDoc Set Curs = m.lnCurs Where id_valuta = m.lnIdValuta
	Endscan

	Use In (Select('cValuteTemp'))
	Select (m.lcSelect)

	Return m.llSucces
Endproc && completeaza_regdoc_curs

************************************
*** Completeaza notele contabile in actactan pentru salvarea in contabilitate
************************************
Procedure completeaza_actactan
	Lparameters tcTip

	Local lcAscc, lcAscd, lcExplicatia, lcScc, lcScd, lcTip, llIntern, llPenalitati, llSucces, lnIdJTvaColoana, lcSelect
	Local llTVAIncasare, lnIdArticol, lnIdLocatia, loFactura, loJTVA, loJtvaA, lnFacturaFaraTVA, lnFacturaTVA, lnFacturaFaraTVAVal, lnFacturaTVAVal, lnIdSet
	Local lcContTva, lcAcontTva
	Local llFurnizorRTVAI, lnActBaza, lnActBazaVal, lnActTVA, lnActTVAVal, lnDiferentaBaza
	Local lnDiferentaBazaVal, lnDiferentaTVA, lnDiferentaTVAVal, lnIdJtva, lnTaxCode

	lcTip = m.tcTip
	lnIdSet = 50200
	llSucces = .T.
	lcSelect = Select()

	Select crsCapFactura
	Go Top
	Scatter Name loFactura

	Select crsFactura
	Go Top
	loJTVA = GeJtvaColoana(crsFactura.id_jtva_coloana, goCalendar.tva_incasare, "JV")
	AddProperty(loFactura, "id_jtva_coloana", loJTVA.id_jtva_coloana)
	AddProperty(loFactura, "id_tva", loJTVA.id_tva)
	AddProperty(loFactura, "proc_tva", crsFactura.proc_tva)

	llIntern = (loFactura.intern = 1)
	llTVAIncasare = (goCalendar.tva_incasare = 1)

	Select id_articol, id_locatia, Cast(Iif(m.llIntern, 0, id_valuta) As N(5)) As id_valuta, Cast(Iif(m.llIntern, 0, Curs) As N(12, 6)) As Curs, ;
		Cast(0 As N(5, 2)) As proc_tva, id_jtva_coloana, Cast(0 As N(10)) As id_tva, CAST(null as N(9)) as taxcode, ;
		Space(4) As scd, Space(4) As ascd, Space(4) As scc, Space(4) As ascc, Space(100) As explicatia, ;
		Sum(valftva) As suma, Sum(valtva) As valtva, Sum(valctva) As valctva, ;
		Sum(valval) As suma_val, Cast(0 As N(20, 4)) As TVAVAL, Cast(0 As N(20, 4)) As totval ;
		From cRegDoc ;
		Group By 1, 2, 3, 4, 5, 6, 7 ;
		Into Cursor cActTemp Readwrite

	*** Completez conturi si analitice in functie de locatie si articol
	Sele cActTemp
	Scan
		llPenalitati = (m.lcTip = TIP_PENALITATI)
		lcScd = ''
		lcAscd = ''
		lcScc = ''
		lcAscc = ''
		lcExplicatia = ''
		lnIdArticol = id_articol
		lnIdLocatia = id_locatia
		lnIdJTvaColoana = Nvl(id_jtva_coloana, 0)
		llSucces = GetCont(m.lcTip, m.lnIdLocatia, m.lnIdArticol, m.llIntern, m.llPenalitati, @m.lcScd, @m.lcAscd, @m.lcScc, @m.lcAscc, @m.lcExplicatia)
		If !m.llSucces
			If amessagebox('Doriti sa continuati fara conturi configurate?', 4 + 32, _Screen.Caption) = 6
				llSucces = .T.
			Else
				Exit
			Endif
		Endif

		If !Empty(m.lnIdJTvaColoana)
			loJtvaA = GeJtvaColoana(m.lnIdJTvaColoana, goCalendar.tva_incasare, "JV")
		Else
			loJtvaA = loJTVA && Explicatie TVA din prima linie din factura
		Endif
		
		lnTaxCode = NULL
		IF m.gl406
			llFurnizorRTVAI = .F.
			lnIdJtva = Nvl(loJtvaA.id_jtva_coloana, 0)
			lnTaxCode = GetTaxCode(m.gnAn, m.gnLuna, loFactura.dataact, m.lnIdJtva, m.llFurnizorRTVAI)
		ENDIF 

		Select cActTemp
		Replace id_jtva_coloana With Nvl(loJtvaA.id_jtva_coloana, 0), id_tva With Nvl(loJtvaA.id_tva, 0), proc_tva With Round(1 + loJtvaA.cota_tva / 100, 2)
		Replace scd With m.lcScd, ascd With m.lcAscd, scc With m.lcScc, ascc With m.lcAscc, TVAVAL With Round(suma_val * proc_tva / 100, m.gnPVal), totval With suma_val + Round(suma_val * proc_tva / 100, m.gnPVal)
		REPLACE taxcode WITH m.lnTaxCode
	Endscan && cActTemp

	If m.llSucces
		Select id_valuta, Curs, proc_tva, id_jtva_coloana, id_tva, taxcode, scd, ascd, scc, ascc, explicatia, ;
			Sum(suma) As suma, Sum(valtva) As valtva, Sum(valctva) As valctva, ;
			Sum(suma_val) As suma_val, Sum(TVAVAL) As TVAVAL, Sum(totval) As totval ;
			From cActTemp ;
			Group By 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ;
			Into Cursor cAct Readwrite

		* Calculez totalul de pe factura si corectez diferente de zecimale fata de selectia din REGDOC (mai multe randuri defalcate dupa locatii)
		Calculate Sum(suma), Sum(valtva), Sum(suma_val), Sum(TVAVAL) To lnActBaza, lnActTVA, lnActBazaVal, lnActTVAVal In cAct
		Calculate Sum(valftva), Sum(valtva), Sum(valval), Sum(TVAVAL) To lnFacturaFaraTVA, lnFacturaTVA, lnFacturaFaraTVAVal, lnFacturaTVAVal In crsFactura
		lnDiferentaBaza = (m.lnFacturaFaraTVA - m.lnActBaza)
		lnDiferentaTVA = (lnFacturaTVA - m.lnActTVA)
		lnDiferentaBazaVal = (m.lnFacturaFaraTVAVal - m.lnActBazaVal)
		lnDiferentaTVAVal = (lnFacturaTVAVal - m.lnActTVAVal)

		* Completez diferenta fata de factura pe primul rand din notele contabile
		Select cAct
		Go Top
		Replace suma With suma + m.lnDiferentaBaza, valtva With valtva + m.lnDiferentaTVA, valctva With  m.lnDiferentaBaza + m.lnDiferentaTVA
		Replace suma_val With suma_val + m.lnDiferentaBazaVal, TVAVAL With TVAVAL + m.lnDiferentaTVAVal, totval With  m.lnDiferentaBazaVal + m.lnDiferentaTVAVal

		Select actactan
		Delete All
		Append From Dbf('cAct')

		*** TVA
		* Totalizez sumele in cursorul cActTVA astfel incat sa am o singura linie de TVA 27.05.2020
		*!*			Select * From cAct Where valtva <> 0 Into Cursor cActTVA Readwrite
		*!*			Update cActTVA Set scc = Iif(m.llTVAIncasare, '4428', '4427'), ascc = '', suma = valtva, suma_val = TVAVAL, id_jtva_coloana = id_tva
		lcContTva = Iif(m.llTVAIncasare, '4428', '4427')
		lcAcontTva = ''
		Select id_valuta, Curs, proc_tva, id_tva As id_jtva_coloana, id_tva, taxcode, scd, ascd, m.lcContTva As scc, m.lcAcontTva As ascc, explicatia, ;
			Sum(valtva) As suma, ;
			Sum(TVAVAL) As suma_val ;
			From cAct ;
			Group By 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ;
			Into Cursor cActTVA Readwrite

		Delete From cActTVA Where suma = 0

		Use In (Select('cAct'))

		Select actactan
		Append From Dbf('cActTVA')
		Use In (Select('cActTVA'))

		Update actactan Set id_partd = loFactura.client_id, id_fdoc = loFactura.id_fdoc, id_ctr = loFactura.client_ctr_id, contract = loFactura.contract_client, ;
			dataact = loFactura.dataact, datascad = loFactura.datascad, dataireg = loFactura.dataact, nract = loFactura.nract, serie_act = loFactura.serie_act, id_set = m.lnIdSet, ;
			explicatia = m.lcTip

		* Completez partener credit contul 472 venituri in avans (4111 = 472)
		Update actactan Set id_partc = loFactura.client_id Where Inlist(Left(scc, 3), '472', '419', '411')
		If m.llIntern
			Update actactan Set suma_val = 0
		Endif
	Endif && llSucces
	Use In (Select('cActTemp'))

	Select (m.lcSelect)
	Return m.llSucces
Endproc && completeaza_actactan


***********************************
*** Obiect cu date aditionale pentru initializarea facturii
***********************************
Define Class oDateFacturaACN As Custom
	nIntern = 1
	cDenumireClient = ''
	nIdClient = Null
	cContractClient = ''
	nIdContractClient = Null
	lImportFactura = .F. && daca se apeleaza importul la intrarea in factura
Enddefine && oDateFacturaACN


****************************************************************************************************************************
*** creeaza cursoarele si obiectele necesare pentru facturare
*** procedura de facturare se lanseaza din formularul frm_factura2, in loc sa se porneasca din tranzit, cheiaj, contracte
*** in formularul de facturare se importa date de tranzit, cheiaj, contracte
****************************************************************************************************************************
Procedure factura_acn
	Lparameters tcTip, toDateAditionale
	* tcTip: tranzit/cheiaj/chirii/apa/diverse/penalitati

	* FACTURA TRANZIT, CHEIAJ, CHIRII, APA si PENALITATI genereaza o singura linie in crsFactura, prin import din formularele specifice de calcul 
	*** Nu se pot adauga linii suplimentare in factura
	* FACTURA DIVERSE - se adauga liber linii in crsFactura

	Private poDate
	Private poGeneratorNumere As "oGeneratorNumere"
	Local llSucces, llSuucces, lnIdJtva, lnIdJTVAExpl, lnIdSet, lnProcTva, lnTip, loTVAStandard
	Local lcTip, lcSelect

	If m.glLunaInchisa
		amessagebox("Nu puteti emite documente, deoarece aceasta luna este inchisa!", 0 + 48, "Luna inchisa")
		Return .F.
	Endif

	If Empty(m.tcTip)
		Return .F.
	Endif
	lcTip = Upper(Alltrim(m.tcTip))

	make_ccapfactura() && crsCapFactura
	make_cfactura() && crsFactura

	make_cregdoc() && cursor cRegDoc gol
	make_actactan() && cursor actactan gol

	make_jtva_explicatii() && crsJTVA
	make_cote_tva() && crsCoteTVA
	make_articole() && crsArticole
	make_locatii() && crsLocatii
	make_articole_locatii() && crsArticoleLocatii
	make_valute() && crsValute
	make_tipfactura() && crsTipFactura
	make_um() && crsUM
	Do make_contracte With "1=2" && crsContracte

	loTVAStandard = GetTVAStandard() && obiect TVA standard cu proprietatile: IdJtvaExpl, IdJtva, ProcTva
	lnIdJTVAExpl = loTVAStandard.IdJtvaExpl
	lnIdJtva = loTVAStandard.IdJtva
	lnProcTva = loTVAStandard.ProcTva

	lnTip = 51 && FACTURA ROAACNPRO
	lnIdSet = 50200

	If Type('poDate') <> 'O'
		poDate = Createobject("oDateFactura", m.lnIdSet, m.lnTip)
	Endif
	If Type('poGeneratorNumere') <> 'O'
		poGeneratorNumere = Createobject("oGeneratorNumere")
	Endif
	poDate.nIdTipDoc = 5 && FACTURA
	poGeneratorNumere.ResetNumere()

	poDate.rezultat_serii = poGeneratorNumere.creeaza_cursor_serii(poDate.nIdTipDoc)

	AddProperty(poDate, 'IdJTVAExpl', m.lnIdJTVAExpl)
	AddProperty(poDate, 'IdJTVA', m.lnIdJtva)
	AddProperty(poDate, 'ProcTVA', m.lnProcTva)
	AddProperty(poDate, 'uuid', '')
	AddProperty(poDate, 'document', '') && documentul pentru cheiaj se completeaza in frm_calcul_cheiaj
	AddProperty(poDate, 'cTip', m.lcTip)
	poDate.nTipFactura = cTip2nTip(m.lcTip) && tip intern factura 0=TRANZIT,1=CHEIAJ, 2=APA, 3=CHIRII, 4=PILOTAJ, 5=ALTE, 6=PENALITATI, 9=DIVERSE
	*	AddProperty(poDate, 'nIdBeneficiar', NULL) && am adaugat in oDate


	Select crsFactura
	loFrmFactura = Createobject("frm_factura", toDateAditionale)
	*	DO FORM frm_factura NAME loFrmFactura LINKED NOSHOW 
	loFrmFactura.Show(1)

	Release poDate, poGeneratorNumere
	Use In (Select('crsJTVA'))
	Use In (Select('crsCoteTVA'))
	Use In (Select('crsArticole'))
	Use In (Select('cRegDoc'))
	Use In (Select('actactan'))
	Use In (Select('crsLocatii'))
	Use In (Select('crsArticoleLocatii'))
	Use In (Select('crsValute'))
	Use In (Select('crsTipFactura'))
	Use In (Select('crsFactura'))
	Use In (Select('crsCapFactura'))
Endproc && factura_acn

Procedure factura_import
	Lparameters tlImportCalculat
	* tlImportCalculat (optional, default .F.): daca s-au calculat deja datele pentru import intr-un formular de calcul si din formularul de calcul s-a lansat factura

	Local lcTip, lcSelect, llSucces, lnIdCtr, lnIdClient
	llSucces = .F.

	lcTip = Upper(Alltrim(poDate.cTip))
	lnIdCtr = crsCapFactura.client_ctr_id
	lnIdClient = crsCapFactura.client_id

	If Empty(m.lcTip) Or !Inlist(m.lcTip, TIP_TRANZIT, TIP_CHEIAJ, TIP_CHIRII, TIP_APA, TIP_PENALITATI)
		Return m.llSucces
	Endif

	* Nu mai intru in vizualizare daca este deja calculat 
	If m.tlImportCalculat
		llSucces = .T.
	Else
		Do Case
			Case m.lcTip = TIP_TRANZIT
				* vizualizare tranzit (alegere convoi) > calcul tranzit , salvare tarife si completare poDate.uUId CU VYE_ID's)
				llSucces = vizualizare_tranzit(NTIP_TRANZIT) && proceduri_acnpro.prg
			Case m.lcTip = TIP_CHEIAJ
				* vizualizare tranzit (alegere convoi) > calcul cheiaj , salvare tarife si completare poDate.uUId CU VYE_ID's)			
				llSucces = vizualizare_tranzit(NTIP_CHEIAJ) && proceduri_acnpro.prg
			Case Inlist(m.lcTip, TIP_CHIRII, TIP_APA)
				* vizualizare chirii, apa (calcul articole contract, salvare tarife si completare poDate.uUId cu IPS_REGDOC.ID's)			
				* adaug articolele din ctr_articole in ips_regdoc
				llSucces = vizualizare_contract(m.lnIdCtr) && proceduri_acnpro.prg
			Case m.lcTip = TIP_PENALITATI
				* vizualizare calcul penalitati
				* adaug articolele din ctr_articole in ips_regdoc
				llSucces = vizualizare_penalitati() && proceduri_acnpro.prg
			Otherwise
				llSucces = .T.
		Endcase
		If !m.llSucces
			Return m.llSucces
		Endif
	Endif && tlImportCalculat

	* Completez crsCapFactura si crsFactura
	llSucces = .F.
	Do Case
		Case m.lcTip = TIP_TRANZIT
			* Completeaza crsCapFactura, crsFactura cu date din tranzit pentru poDate.uUid
			llSucces = make_factura_tranzit()
		Case m.lcTip = TIP_CHEIAJ
			* Completeaza crsCapFactura, crsFactura cu date din tranzit pentru poDate.uUid
			llSucces = make_factura_cheiaj()
		Case m.lcTip = TIP_PENALITATI
			llSucces = make_factura_penalitati(m.tlImportCalculat)
		Case Inlist(m.lcTip, TIP_CHIRII, TIP_APA)
			* Completeaza crsFactura cu date din contracte pentru contractul selectat. initializeaza poDate.uUid = crsCapFactura.ctr_id
			llSucces = make_factura_contracte()
		Otherwise
			llSucces = .T.
	Endcase

	Return m.llSucces
Endproc && factura_import

Procedure factura_salvare
	Local lcTip, llSucces, luId, loEx As Exception
	llSucces = .F.
	luId = poDate.uuid
	lcTip = Upper(Alltrim(poDate.cTip))

	If Empty(m.luId) And Inlist(m.lcTip, TIP_TRANZIT, TIP_CHEIAJ, TIP_CHIRII, TIP_APA)
		amessagebox(Iif(Inlist(m.lcTip, TIP_TRANZIT, TIP_CHEIAJ), 'Alegeti convoiul', 'Adaugati prestatii') + '!', 0 + 48, _Screen.Caption)
		Return m.llSucces
	Endif
SET STEP ON 
	* Completex taxcode in crsFactura bazat pe id_jtva_coloana
	IF m.gl406
		SELECT crsFactura
		llFurnizorRTVAI = .F.
		SCAN 
			lnTaxCode = NULL
			lnIdJtva = Nvl(crsFactura.id_jtva_coloana, 0)
			lnTaxCode = GetTaxCode(m.gnAn, m.gnLuna, poDate.dataact, m.lnIdJtva, m.llFurnizorRTVAI)
			SELECT crsFactura
			REPLACE taxcode WITH m.lnTaxCode
		ENDSCAN  
	ENDIF

	Try
		Do Case
			Case  m.lcTip = TIP_TRANZIT
				llSucces = update_tranzit(m.luId) && completez data, nr, total cu tva pe convoi ips_voyages_vanzari, completez cursul valutar si valorile in lei pe barje ips_voyage_members_vanzari
				If m.llSucces
					llSucces = completeaza_regdoc_tranzit(m.luId) && completez cursorul cRegDoc cu valori defalcate pe ecluze, senale
				Endif

			Case  m.lcTip = TIP_CHEIAJ
				llSucces = update_cheiaj(m.luId) && completez data, nr, total cu tva pe convoi ips_voyages_vanzari, completez cursul valutar si valorile in lei pe barje ips_berthing_details_vanzari
				If m.llSucces
					llSucces = completeaza_regdoc_cheiaj(m.luId) && completez cursorul cRegDoc cu valori defalcate pe locatii
				Endif
			Case Inlist(m.lcTip, TIP_CHIRII, TIP_APA)
				llSucces = update_contracte(m.luId) && completez curs, valftva in ips_regdoc
				If m.llSucces
					llSucces = completeaza_regdoc_contracte(m.luId) && nu completez cursorul cRegDoc. Este scris in ips_regdoc din salvare_contract
				Endif
			Case  m.lcTip = TIP_PENALITATI
				llSucces = completeaza_regdoc_penalitati(m.luId) && completez cursorul cRegDoc cu valori defalcate pe locatii direct din crsFactura
			Otherwise && TIP_DIVERSE
				llSucces = completeaza_regdoc_alte(m.luId) && completez cursorul cRegDoc cu valori defalcate pe locatii direct din crsFactura
		Endcase && m.lcTip


		If m.llSucces
			llSucces = completeaza_regdoc_curs() && completez cursul valutar in cursorul cRegDoc
		Endif

		If m.llSucces
			llSucces = completeaza_actactan(m.lcTip) && completez cursorul actactan din cRegDoc
		Endif

		If m.llSucces
			llSucces = factura_salvare_db(m.lcTip) && salvez factura in contabilite, vanzari si regdoc folosind datele din cFactura (vanzari), cRegDoc , actactan
		Endif

		If m.llSucces
			poGeneratorNumere.verifica_numar(poDate.nIdTipDoc, poDate.nract)
		Else
			poGeneratorNumere.dezaloca_numar(poDate.nIdTipDoc)
		Endif
	Catch To loEx
		goApp.ShowErrorEx(loEx)
		llSucces = .F.
	Endtry

	Return m.llSucces

Endproc && factura_salvare

****************************************************************************************************************************
Procedure factura_salvare_db
	Lparameters tcTip
	*lcTip = poDate.cTip && TRANZIT/CHEIAJ/CHIRII/APA/DIVERSE/PENALITATI
	Private pnCod, pnVVId, poRec, pnIdFact
	poRec = Null
	pnIdFact = 0
	Local lcSql, lcTabelFisiere, lcTip, llScris, llSucces, llSucces2, lnIdJTvaColoana, lcCont
	Local lnProcTvav, lnSucces, lnSucces2, loRec, ltDataOra, loMonedaNationala, lnIdMonedaNationala
	pnCod = 0
	pnVVId = 0
	lcTip = m.tcTip

	llScris = .F.
	lnProcTvav = 0
	lnIdJTvaColoana = Null
	lcCont = ''

	*********************
	*** actactan
	*********************

	Use In (Select('crsvanztemp'))


	ltDataOra = Get_Ora()
	poDate.dataora_exp = ltDataOra
	Create Cursor crsvanztemp(id_articol N(20), explicatie C(240), Pret N(20, 4), proc_tvav N(7, 3), id_jtva_coloana N(10), id_jtva_coloana_ex N(10) Null, cantitate N(20, 4), discount_unitar N(20, 4), ;
		  id_gestiune N(20), Cont C(4), pret_cu_tva N(1), serie C(100), id_valuta N(10), codmat C(50), Curs N(20, 6), multiplicator N(10), pret_achizitie N(20, 4), ;
		  pretd N(20, 4), id_valuta_d N(10), taxcode N(6) null)

	Insert Into crsvanztemp(id_articol, explicatie, Pret, proc_tvav, id_jtva_coloana, id_jtva_coloana_ex, cantitate, discount_unitar, pret_cu_tva, ;
		  serie, codmat, id_valuta, Curs, multiplicator, pret_achizitie, pretd, id_valuta_d, taxcode) ;
		Select id_articol, denumire As explicatie, pretval As Pret, proc_tva As proc_tvav, id_jtva_coloana, id_jtva_coloana_ex, cantitate, ;
		0 As discount_unitar, Nvl(pret_cu_tva, 0) As pret_cu_tva, Space(100) As serie, Space(50) As codmat, ;
		Cast(Nvl(id_valuta, 0) As N(5)) As id_valuta, Curs, 1 As multiplicator, 0 As pret_achizitie, 0 As pretd, Cast(0 As N(5)) As id_valuta_d, taxcode ;
		From crsFactura

	lnSucces = SQLSetprop(gnHandle, "Transactions", 2)
	llSucces = (m.lnSucces >= 0)

	If m.llSucces
		* Generez pack_contafin.nCod
		lcSql = [begin pack_facturare.initializeaza_scriere_actrul(NULL,1); end;]
		llSucces = goExecutor.oExecuta(lcSql)
		If m.llSucces
			llSucces = goExecutor.oSelecteaza2Value([SELECT pack_contafin.get_cod() FROM dual], @pnCod)
			If m.llSucces
				Update actactan Set cod = m.pnCod
			Endif
		Endif
	Endif

	If m.llSucces
		lcSql = [begin pack_facturare.initializeaza_date_factura(] + ;
			[to_date('] + Alltrim(Dtoc(poDate.dataireg, 2)) + [','YYYYMMDD'),] + ;
			Nvl(Alltrim(Str(poDate.id_fdoc)), [NULL]) + [,to_date('] + Alltrim(Dtoc(poDate.dataact, 2)) + [','YYYYMMDD'),] + ;
			[to_date('] + Alltrim(Dtoc(poDate.datascad, 2)) + [','YYYYMMDD'),'] + Nvl(poDate.serie_act, []) + [',] + ;
			Alltrim(Str(poDate.nract, 14, 0)) + [,] + ;
			Iif(Isnull(poDate.id_client), [NULL], Alltrim(Str(poDate.id_client))) + [,] + ;
			Iif(Isnull(poDate.id_lucrare), [NULL], Alltrim(Str(poDate.id_lucrare))) + [,] + ;
			Iif(Isnull(poDate.id_sectie), [NULL], Alltrim(Str(poDate.id_sectie))) + [,] + ;
			Iif(Isnull(poDate.id_venchelt), [NULL], Alltrim(Str(poDate.id_venchelt))) + [,] + ;
			Iif(Isnull(poDate.id_responsabil), [NULL], Alltrim(Str(poDate.id_responsabil))) + [,] + ;
			Iif(Empty(Nvl(poDate.explicatia4, [])), [NULL], ['] + Strtran(Alltrim(poDate.explicatia4), ['], ['']) + [']) + [,] + ;		&&	modificare v 2.0.33
			Iif(Empty(Nvl(poDate.id_ordl, 0)), [NULL], Alltrim(Str(poDate.id_ordl))) + [,NULL,] + ;
			['] + Strtran(Alltrim(Nvl(poDate.descriere, [])), ['], ['']) + [',] + ;
			Alltrim(Str(poDate.tip)) + [,] + Alltrim(Str(poDate.id_set)) + [,] + ;
			[to_date('] + Dtoc(poDate.zi_curs, 2) + [','YYYYMMDD'),] + Alltrim(Str(poDate.id_valuta)) + [,] + ;
			Alltrim(Str(poDate.in_valuta)) + [,] + ;
			Alltrim(Str(poDate.tva_incasare)) + [,] + ;	&&	modificare ROAAUTO v 2.1.0
			Iif(Isnull(gnIdSucursala), [NULL], Alltrim(Str(gnIdSucursala))) + [,] + ;
			Alltrim(Str(gnIdUtil)) + [,] + ;
			Alltrim(Str(poDate.nTipFactura)) + [,] + ;
			Iif(Isnull(poDate.nIdBeneficiar), [NULL], Alltrim(Str(poDate.nIdBeneficiar))) + [,] + ;
			Iif(Isnull(poDate.tip_saft), [NULL], Alltrim(Str(poDate.tip_saft))) + [); end;]

		llSucces = goExecutor.oExecuta(lcSql)

		* Salvez articole
		If m.llSucces
			Private poArticol
			Select crsvanztemp
			Scan
				Scatter Name poArticol
				* Nu se completeaza articolul in factura pentru ca cumulez mai multe prestatii/locatii
				* Completez contul articolului din ips_prestatii_locatii
				IF EMPTY(NVL(poArticol.cont,''))
					lcCont = ''
					lcSql = [SELECT MAX(DECODE(CTDEBITOR, '4111', CTCREDITOR, '461', CTCREDITOR, '4118', CTCREDITOR, CTDEBITOR)) as cont FROM ips_vprestatii_locatii WHERE ID_ARTICOL = ?poArticol.id_articol]
					llSucces = goExecutor.oSelecteaza2Value(m.lcSql, @lcCont)
					poArticol.cont = m.lcCont
				ENDIF 
				lcSql = [begin pack_facturare.adauga_articol_factura_deviz(] + ;
					Alltrim(Str(poArticol.id_articol)) + [,] + ;
					['] + Strtran(Alltrim(Nvl(poArticol.explicatie, [])), ['], ['']) + [',] + ;
					['] + Strtran(Alltrim(Nvl(poArticol.serie, [])), ['], ['']) + [',] + ;
					Alltrim(Str(poArticol.pret_achizitie, 18, gnPPret)) + [,] + ;
					Alltrim(Str(poArticol.pretd, 18, gnPVal)) + [,] + ;
					Alltrim(Str(poArticol.id_valuta_d)) + [,] + ;
					Alltrim(Str(poArticol.Pret, 18, gnPPretV)) + [,] + ;
					Alltrim(Str(poArticol.id_valuta)) + [,] + ;
					Alltrim(Str(poArticol.Curs, 18, 6)) + [,] + ;
					Alltrim(Str(poArticol.multiplicator)) + [,] + ;
					Alltrim(Str(poArticol.proc_tvav, 18, 2)) + [,] + ;
					Alltrim(Str(poArticol.id_jtva_coloana)) + [,] + ;
					Alltrim(Str(poArticol.cantitate, 18, gnPCant)) + [,] + ;
					Alltrim(Str(poArticol.discount_unitar, 18, gnPPretV)) + [,] + ;
					Alltrim(Str(poArticol.id_gestiune)) + [,] + ;
					['] + Alltrim(Nvl(poArticol.Cont, '')) + [',] + ;
					Alltrim(Str(poArticol.pret_cu_tva)) + [,] + ;
					Alltrim(Str(poArticol.id_jtva_coloana_ex)) + [,] + ;
					Iif(Empty(Nvl(poDate.listaId, 0)), 'NULL', Alltrim(Str(poDate.listaId))) + [,] + ;
					Iif(Empty(Nvl(poArticol.taxcode, 0)), 'NULL', Alltrim(Str(poArticol.taxcode))) + [); end;]
				llSucces = goExecutor.oExecuta(lcSql)
				If !m.llSucces
					Exit
				Endif
			Endscan
		Endif && salvez articole

		If m.llSucces
			* Salvez Vanzari
			lcSql = [begin pack_facturare.scrie_in_vanzari(0,] + ;
				Iif(Isnull(poDate.id_delegat), [NULL], Alltrim(Str(poDate.id_delegat))) + [,] + ;
				Iif(Isnull(poDate.id_masina), [NULL], Alltrim(Str(poDate.id_masina))) + [,] + ;
				Iif(Isnull(poDate.id_facturare), [NULL], Alltrim(Str(poDate.id_facturare))) + [,] + ;
				Iif(Isnull(poDate.nListareDetaliata), [0], Alltrim(Str(poDate.nListareDetaliata))) + [,] + ;
				[?poDate.dataora_exp,] + ;
				Iif(Isnull(poDate.id_agent), [NULL], Alltrim(Str(poDate.id_agent))) + [,] + ;
				['] + Strtran(Alltrim(Nvl(poDate.text_aditional, [])), ['], ['']) + [',?@poDate.nid_vanzare); end;]
			llSucces = goExecutor.oExecuta(lcSql)
		Endif && salvez vanzari

		* Salvez Reg. Doc.
		If m.llSucces
			Update cRegDoc Set id_vanzare = poDate.nid_vanzare, id_client = poDate.id_client, Data = poDate.dataact, tip = cTip2nTip(m.lcTip)
			Update cRegDoc Set id_contract = poDate.listaId Where Empty(Nvl(id_contract, 0)) && de ex: la penalitati, contractul este completat pe fiecare factura din calcul penalitati si nu trebuie sa il suprascriu cu contractul din factura de penalitati
			loMonedaNationala = GetMonedaNationala()
			lnIdMonedaNationala = loMonedaNationala.id_valuta

			lcSql = [begin pack_acn.salveaza_regdoc(?.id, ?.id_vanzare, ?.tip, ?.id_articol, ?.id_locatia, ?.id_valuta, ?.id_client, ?.id_contract, ?.pret, ?.curs, ?.cantitate, ?.valval, ?.tvaval, ?.totval, ?.valftva, ?.valtva, ?.valctva, ?.document, ?.data); end;]

			Select cRegDoc
			Scan
				Scatter Name loRec
				loRec.Document = Alltrim(Nvl(loRec.Document, ''))
				loRec.id_valuta = Iif(Empty(loRec.id_valuta), m.lnIdMonedaNationala, loRec.id_valuta)
				loRec.id_client = Iif(Empty(loRec.id_client), Null, loRec.id_client)
				loRec.id_contract = Iif(Empty(loRec.id_contract), Null, loRec.id_contract)
				With loRec
					llSucces = goExecutor.oExecuta(m.lcSql)
					If !m.llSucces
						Exit
					Endif
				Endwith
			Endscan
		Endif && m.llSucces Reg Doc

		If m.llSucces And Inlist(m.lcTip, TIP_TRANZIT, TIP_CHEIAJ)
			* completez ips_voyages_vanzari.vz_id
			llSucces = goExecutor.oExecuta([UPDATE ips_voyages_vanzari SET vz_id = ?poDate.nid_vanzare WHERE id in (] + poDate.uuid + [)])
		Endif


		If m.llSucces
			* Salvez contabilitate
			If !Used('INFISIERE')
				lcTabelFisiere = gcAppPath + [\COMUN\DATEMENU\infisiere.dbf]
				Use (m.lcTabelFisiere) In 0 Alias INFISIERE
			Endif
			lnSucces = oscrie_in_fisiere(0, .F., .F., .T.)	&&	nu suprascriu codul pentru ca l-am generat la inceput si l-am completat in VANZARI
			llSucces = (m.lnSucces > 0)
		Endif

		* Completez VANZARI.ID_FACT DUPA SCRIEREA IN ACT
		If m.llSucces
			pnIdFact = 0
			llSucces = goExecutor.oSelecteaza2Value ([select pack_contafin.get_idFact() from dual], @pnIdFact)
		Endif
		If m.llSucces
			llSucces = goExecutor.oExecuta([update vanzari set id_fact = ?pnIdFact where id_vanzare = ?poDate.nid_vanzare])
		Endif

		* Salvez PENALITATI
		If m.llSucces And m.lcTip = TIP_PENALITATI
			Text To lcSql Noshow
insert into penalitati (id_ctr, id_part, id_fact_pen, id_fact, nrfact, datafact, datascad, valctva, id_doc_incasare, nract, dataact, suma, databaza, dataref, coef_penalitati, coef_penalitati2, nr_zile, nr_zile1, nr_zile2, nr_zile_gratie, penalitati, sters)
values (?poRec.id_ctr, ?poRec.clie_id, ?pnIdFact, ?poRec.id_fact, ?poRec.nrfact, ?poRec.datafact, ?poRec.datascad, ?poRec.valctva, ?poRec.id_doc, ?poRec.nract, ?poRec.dataact, ?poRec.suma, ?poRec.databaza, ?poRec.dataref, ?poRec.ppenzi, ?poRec.ppenzi2, ?poRec.nr_zile, ?poRec.nr_zile1, ?poRec.nr_zile2, ?poRec.zilegratie, ?poRec.penalitati, ?poRec.sters);
			Endtext

			Select crsCalculPenalitatiAles
			Scan
				Scatter Name poRec
				llSucces = goExecutor.oExecuta(m.lcSql)
				If !m.llSucces
					Exit
				Endif
			Endscan
		Endif && PENALITATI


		If !m.llSucces
			lcSql = "ROLLBACK"
			llScris = .F.
		Else
			lcSql = "COMMIT"
			llScris = .T.
		Endif
		llSucces2 = goExecutor.oExecuta(lcSql)

		lnSucces2 = SQLSetprop(gnHandle, "Transactions", 1)
		If lnSucces2 < 0
			amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
		Endif
	Endif && tranzactie manuala

	Use In (Select('crsvanztemp'))
	Use In (Select('crsFacturaACN'))
	*!*		Use In (Select('crsfacturaX'))

	Return m.llScris
Endproc && factura_salvare_db


****************************************************************************************************************************
*** Completez crsFactura cu valoarea tranzitului
****************************************************************************************************************************
Procedure make_factura_tranzit
	* tnVVId: ips_voyage_vanzari.id

	Private pcVVIds, pnVVId, pcConvoyName
	Local loFrmFactura As "frm_factura"
	Local lcSql, llSucces, lnCantitate, lnIdJtva, lnIdJTVAExpl, lnPret, lnProcTva, loArticol, loRec, loMonedaNationala, lnIdMonedaNationala
	Local lcNumeConvoi, lcDataConvoi, lcContract, llExplicatieEN, lcDenumireArticol, lnIntern, loTVAStandard
	pcVVIds = poDate.uuid
	pnVVId = 0
	llSucces = .T.
	pcConvoyName = ''

	If Empty(m.pcVVIds)
		amessagebox('Alegeti un convoi!', 0 + 48, _Screen.Caption)
		llSucces = .F.
	Endif

	If m.llSucces
		lnIntern = crsCapFactura.intern
		loTVAStandard = GetTVAStandard(m.lnIntern) && obiect TVA standard cu proprietatile: IdJtvaExpl, IdJtva, ProcTva
		lnIdJTVAExpl = loTVAStandard.IdJtvaExpl
		lnIdJtva = loTVAStandard.IdJtva
		lnProcTva = loTVAStandard.ProcTva

		llExplicatieEN = (crsCapFactura.intern = 0)
		loArticol = GetPrestatieByTip(TIP_TRANZIT, m.llExplicatieEN) && C/V TRANZITARE CDMN PENTRU CONVOIUL/BARJA [INDICATIV], DIN [DATA] CONFORM [CONTRACT] / TRANSIT FOR [INDICATIV], IN [DATA] ACCORDING TO THE [CONTRACT]
		lcDenumireArticol = loArticol.denumire

		loMonedaNationala = GetMonedaNationala()
		lnIdMonedaNationala = loMonedaNationala.id_valuta

		Text To lcSql Textmerge Noshow
select stringagg(convoy_nam) as convoy_nam
  from ips_vvoyages v
  join (SELECT distinct vye_id
          FROM ips_voyage_members_vanzari 
         WHERE vv_id in (<<m.pcVVIds>>)) vm
    on v.id = vm.vye_id
		Endtext

		llSucces = goExecutor.oSelecteaza2Value(m.lcSql, @pcConvoyName)

		If m.llSucces
			Text To lcSql Textmerge Noshow
SELECT vmv.id_valuta,
       v.nume_val as valuta,
       ROUND(SUM(vmv.valval), 2) as valval
  FROM ips_voyage_members_vanzari vmv
  JOIN vnom_valute v ON vmv.id_valuta = v.id_valuta
 WHERE vmv.vv_id in (<<m.pcVVIds>>)
 GROUP BY vmv.id_valuta, v.nume_val
			Endtext

			llSucces = goExecutor.oExecuta(m.lcSql, "crsValoareTemp")

		Endif

		If m.llSucces
			Select crsValoareTemp
			Scan
				Scatter Name loRec
				lnCantitate = 1
				lnPret = 0
				loRec.valval = Round(loRec.valval, m.gnPC) && rotunjesc la 2 zecimale
				If loRec.id_valuta = m.lnIdMonedaNationala
					lnPret = loRec.valval
				Endif

				lcNumeConvoi = Alltrim(Nvl(pcConvoyName, ''))
				lcDataConvoi = Dtoc(poDate.zi_curs) && Dtoc(Ttod(Nvl(generation, {//::})))
				lcContract = Alltrim(Nvl(crsCapFactura.contract_client, ''))

				loArticol.denumire = Strtran(m.lcDenumireArticol, '[INDICATIV]', m.lcNumeConvoi, 1, 10, 1)
				loArticol.denumire = Strtran(loArticol.denumire, '[DATA]', m.lcDataConvoi, 1, 10, 1)
				loArticol.denumire = Strtran(loArticol.denumire, '[CONTRACT]', Iif(!Empty(m.lcContract), 'CONTRACT ' + m.lcContract, Iif(m.llExplicatieEN, 'BOOKING', 'COMANDA')), 1, 10, 1)
				
				* Daca am factura storno cu pret -, fac cantitatea - si pretul +
				* La eFactura nu se valideaza cu pret -
				IF m.lnPret < 0
					lnCantitate = -m.lnCantitate
					lnPret = -m.lnPret
					loRec.valval = -loRec.valval
				ENDIF 
				
				Insert Into crsFactura(nrcrt, id_articol, denumire, id_valuta, pretval, Curs, Pret, cantitate, valftva, valtva, valctva, um, id_jtva_coloana_ex, id_jtva_coloana, proc_tva) Values (1, loArticol.id_articol, loArticol.denumire, loRec.id_valuta, loRec.valval, 0, m.lnPret, m.lnCantitate, 0, 0, 0, '', m.lnIdJTVAExpl, m.lnIdJtva, m.lnProcTva)
			Endscan && crsValoareTemp
			Use In (Select('crsValoareTemp'))
		Endif && llSucces
		Use In (Select('cDateConvoiTemp'))
	Endif && m.llSucces

	Return m.llSucces

Endproc && make_factura_tranzit

****************************************************************************************************************************
*** Completez crsFactura cu valoarea cheiajului
****************************************************************************************************************************
Procedure make_factura_cheiaj
	* tnVVId: ips_voyage_vanzari.id

	Private pcVVIds, pnVVId
	Local loFrmFactura As "frm_factura"
	Local lcSql, llSucces, lnCantitate, lnIdJtva, lnIdJTVAExpl, lnPret, lnProcTva, loArticol, loRec, loMonedaNationala, lnIdMonedaNationala, lcDenumire, lcPort, lcDataP, lcContract, lnIntern, loTVAStandard
	Local llExplicatieEN
	pcVVIds = poDate.uuid
	pnVVId = 0

	lcPort = ''
	lnIntern = crsCapFactura.intern
	loTVAStandard = GetTVAStandard(m.lnIntern) && obiect TVA standard cu proprietatile: IdJtvaExpl, IdJtva, ProcTva
	lnIdJTVAExpl = loTVAStandard.IdJtvaExpl
	lnIdJtva = loTVAStandard.IdJtva
	lnProcTva = loTVAStandard.ProcTva

	llExplicatieEN = (crsCapFactura.intern = 0)
	loArticol = GetPrestatieByTip(TIP_CHEIAJ, m.llExplicatieEN) && *C/V SERVICII PORTUARE IN PORTUL [PORT], DIN [DATA] CONFORM [CONTRACT]
	lcDenumire = loArticol.denumire

	loMonedaNationala = GetMonedaNationala()
	lnIdMonedaNationala = loMonedaNationala.id_valuta

	lcDataP = Dtoc(poDate.zi_curs) && Dtoc(Ttod(Nvl(datap, {//::})))
	lcContract = Alltrim(Nvl(crsCapFactura.contract_client, ''))

	* Port(uri)
	llSucces = goExecutor.oExecuta([select stringagg(locatia) as port from (SELECT distinct locatia FROM ips_vberthing_details_vanzari WHERE VV_ID in (] + m.pcVVIds + [))], [cDateCheiajTemp])
	If m.llSucces
		Select cDateCheiajTemp
		Go Top
		lcPort = Alltrim(Nvl(port, ''))

		Use In (Select('cDateCheiajTemp'))
	Endif

	loArticol.denumire = Strtran(m.lcDenumire, '[PORT]', m.lcPort, 1, 10, 1)
	loArticol.denumire = Strtran(loArticol.denumire, '[DATA]', m.lcDataP, 1, 10, 1)
	loArticol.denumire = Strtran(loArticol.denumire, '[CONTRACT]', Iif(!Empty(m.lcContract), 'CONTRACT ' + m.lcContract, Iif(m.llExplicatieEN, 'BOOKING', 'COMANDA')), 1, 10, 1)

	lcSql = [SELECT id_valuta, valuta, SUM(valval) as valval FROM ips_vberthing_details_vanzari WHERE VV_ID in (] + m.pcVVIds + [) GROUP BY id_valuta, valuta]
	llSucces = goExecutor.oExecuta(m.lcSql, "crsValoareTemp")
	If m.llSucces
		Select crsValoareTemp
		Scan
			Scatter Name loRec
			lnCantitate = 1
			lnPret = 0
			loRec.valval = Round(loRec.valval, m.gnPC) && rotunjesc la 2 zecimale
			If loRec.id_valuta = m.lnIdMonedaNationala
				lnPret = loRec.valval
			ENDIF
			
			* Daca am factura storno cu pret -, fac cantitatea - si pretul +
			* La eFactura nu se valideaza cu pret -
			IF m.lnPret < 0
				lnCantitate = -m.lnCantitate
				lnPret = -m.lnPret
				loRec.valval = -loRec.valval
			ENDIF 			

			Insert Into crsFactura(nrcrt, id_articol, denumire, id_valuta, pretval, Curs, Pret, cantitate, valftva, valtva, valctva, um, id_jtva_coloana_ex, id_jtva_coloana, proc_tva) ;
				Values (1, loArticol.id_articol, loArticol.denumire, loRec.id_valuta, loRec.valval, 0, m.lnPret, m.lnCantitate, 0, 0, 0, '', m.lnIdJTVAExpl, m.lnIdJtva, m.lnProcTva)
		Endscan && crsValoareTemp
	Endif && llSucces
	Use In (Select('crsValoareTemp'))


	Return m.llSucces
Endproc
**************************************************
Procedure make_factura_contracte

	Private pnIdCtr
	Local lcSql, llSucces, lnIdJtva, lnIdJTVAExpl, lnNrCrt, lnPret, lnProcTva, loRec, loMonedaNationala, lnIdMonedaNationala, lcSelect, lnIntern, loTVA, lcTipFactura, lnTipFactura, lcRegDocIds
	Local lnCotaTVA, lnNrCrt

	lcSelect = Select()
	llSucces = .F.

	Select crsCapFactura
	lcRegDocIds = poDate.uuid
	lcTipFactura = poDate.cTip && TRANZIT, CHEIAJ, CHIRII, APA, DIVERSE
	lnTipFactura = poDate.nTipFactura && tip intern factura 0=TRANZIT,1=CHEIAJ, 2=APA, 3=CHIRII, 4=PILOTAJ, 5=ALTE, 6=PENALITATI, 9=DIVERSE

	lnIntern = intern
	llExplicatieEN = (crsCapFactura.intern = 0)
	lcDataP = Dtoc(crsCapFactura.dataact) && Dtoc(Ttod(Nvl(datap, {//::})))
	lcContract = Alltrim(Nvl(crsCapFactura.contract_client, ''))

	loArticol = GetPrestatieByTip(m.lcTipFactura, m.llExplicatieEN) && un articol generic care cumuleaza toata valoarea
	lnIdArticol = loArticol.id_articol
	loArticol.denumire = Strtran(loArticol.denumire, '[CONTRACT]', Iif(!Empty(m.lcContract), 'CONTRACT ' + m.lcContract, Iif(m.llExplicatieEN, 'BOOKING', 'COMANDA')), 1, 10, 1)

	loMonedaNationala = GetMonedaNationala()
	lnIdMonedaNationala = loMonedaNationala.id_valuta

	* Factura INTERN se transforma valorile in valuta in lei, fara TVA, si se cumuleaza valorile in lei
	* Factura EXTERN sunt defalcate pe valuta
	* crsCursuri este deja creat in formularul de factura
	* pun acelasi articol pe toate liniile (trebuie sa fie un articol oarecare pe toate liniile). as putea sa pun si un articol generic sau un articol de pe contract

	lcSql = [SELECT id_valuta, proc_tvav, id_articol, valval FROM ips_vregdoc WHERE id in (] + m.lcRegDocIds + [)]
	llSucces = goExecutor.oExecuta(m.lcSql, "crsValoareTemp2")
	If m.llSucces And Reccount('crsValoareTemp2') > 0
		Select crsValoareTemp2
		Go Top
		*!*			lnIdArticol = id_articol

		If m.lnIntern = 1
			Select m.lnIdMonedaNationala As id_valuta, v.proc_tvav, ;
				Iif(v.id_valuta = m.lnIdMonedaNationala, Round(v.valval, m.gnPC), Round(v.valval * C.Curs, gnPC)) As valval ;
				From crsValoareTemp2 v Left Join crsCursuri C On v.id_valuta = C.id_valuta ;
				Into Cursor crsValoareTemp3

			Select id_valuta, proc_tvav, lnIdArticol As id_articol, Sum(valval) As valval From crsValoareTemp3	Group By id_valuta, proc_tvav Into Cursor crsValoareTemp
			Use In (Select('crsValoareTemp3'))
		Else
			Select id_valuta, proc_tvav, lnIdArticol As id_articol, Sum(valval) As valval From crsValoareTemp2 Group By id_valuta, proc_tvav Into Cursor crsValoareTemp
		Endif
		Use In (Select('crsValoareTemp2'))
SET STEP ON 
		Select crsValoareTemp
		Scan
			Scatter Name loRec
			*!*				loArticol = GetPrestatieById(loRec.id_articol)
			*!*				loArticol.denumire = loArticol.denumire + [ ] + Iif(!Empty(m.lcContract), Iif(m.llExplicatieEN, 'ACCORDING TO THE CONTRACT ', 'CONFORM CONTRACT ') + m.lcContract, Iif(m.llExplicatieEN, 'BOOKING', 'COMANDA'))
			lnNrCrt = Recno('crsValoareTemp')
			lnCantitate = 1
			lnPret = 0
			loRec.valval = Round(loRec.valval, m.gnPC) && rotunjesc la 2 zecimale
			If loRec.id_valuta = m.lnIdMonedaNationala
				lnPret = loRec.valval
			Endif
			lnCotaTVA = (loRec.proc_tvav - 1) * 100
			loTVA = GetObiectTVA(m.lnIntern, m.lnCotaTVA) && GetTVAStandard(m.lnIntern) && obiect TVA standard cu proprietatile: IdJtvaExpl, IdJtva, ProcTva
			lnIdJTVAExpl = loTVA.IdJtvaExpl
			lnIdJtva = loTVA.IdJtva
			lnProcTva = loTVA.ProcTva

			* Daca am factura storno cu pret -, fac cantitatea - si pretul +
			* La eFactura nu se valideaza cu pret -
			IF m.lnPret < 0
				lnCantitate = -m.lnCantitate
				lnPret = -m.lnPret
				loRec.valval = -loRec.valval
			ENDIF 
			
			Insert Into crsFactura(nrcrt, id_articol, denumire, id_valuta, pretval, Curs, Pret, cantitate, valftva, valtva, valctva, um, id_jtva_coloana_ex, id_jtva_coloana, proc_tva) ;
				Values (m.lnNrCrt, loArticol.id_articol, loArticol.denumire, loRec.id_valuta, loRec.valval, 0, m.lnPret, m.lnCantitate, 0, 0, 0, '', m.lnIdJTVAExpl, m.lnIdJtva, m.lnProcTva)
		Endscan && crsValoareTemp
	Endif && llSucces
	Use In (Select('crsValoareTemp'))

	Select (m.lcSelect)
	Return m.llSucces
Endproc

**************************************************
Procedure make_factura_penalitati
	Lparameters tlImportCalculat
	* tlImportCalculat (optional, default .F.): daca s-au calculat deja datele pentru import intr-un formular de calcul si din formularul de calcul s-a lansat factura

	Local lcContract, lcFiltru, lcRegDocIds, lcSelect, lcTipFactura, llExplicatieEN, llSucces
	Local lnIdArticol, lnIdJtva, lnIdJTVAExpl, lnIdMonedaNationala, lnIntern, lnPenalitati, lnProcTva
	Local lnTipFactura, loArticol, loMonedaNationala, loTVAStandard, ldDataReferinta, lnPret, lnPretVal, lnCantitate
	lcSelect = Select()
	llSucces = .T.

	* lcRegDocIds = poDate.uuid
	lcTipFactura = TIP_PENALITATI && poDate.cTip && TRANZIT, CHEIAJ, CHIRII, APA, DIVERSE
	lnIntern = crsCapFactura.intern

	lnCotaTVA = 0
	lnIdJTvaColoana = 12 && Neimpozabil
	loTVA = GetObiectTVA(m.lnIntern, m.lnCotaTVA, m.lnIdJTvaColoana)
	lnIdJTVAExpl = loTVA.IdJtvaExpl
	lnIdJtva = loTVA.IdJtva
	lnProcTva = loTVA.ProcTva

	loMonedaNationala = GetMonedaNationala()
	lnIdMonedaNationala = loMonedaNationala.id_valuta

	llExplicatieEN = (m.lnIntern = 0)
	lcContract = ''
	Select Distinct contract From crsCalculPenalitatiAles Where sters = 0 Order By contract Into Cursor cContracteTemp
	Select cContracteTemp
	Scan
		lcContract = lcContract + Iif(!Empty(Nvl(contract, '')), ', ' + Alltrim(contract), '')
	Endscan
	If !Empty(m.lcContract)
		lcContract = Substr(m.lcContract, 3)
	Endif
	Use In (Select('cContracteTemp'))

	* crsCalculPenalitati este filtrat pe un client
	Select crsCalculPenalitatiAles
	Calculate Sum(penalitati), Min(dataref) For sters = 0 To lnPenalitati, ldDataReferinta

	loArticol = GetPrestatieByTip(m.lcTipFactura, m.llExplicatieEN) && un articol generic care cumuleaza toata valoarea
	lnIdArticol = loArticol.id_articol
	loArticol.denumire = Strtran(loArticol.denumire, '[CONTRACT]', Iif(!Empty(m.lcContract), 'CONTRACT ' + m.lcContract, Iif(m.llExplicatieEN, 'BOOKING', 'COMANDA')), 1, 10, 1)
	loArticol.denumire = Strtran(loArticol.denumire, '[DATA]', Dtoc(m.ldDataReferinta), 1, 10, 1)

	* Daca am factura storno cu pret -, fac cantitatea - si pretul +
	* La eFactura nu se valideaza cu pret -
	lnCantitate = 1
	lnPret = m.lnPenalitati
	lnPretVal = m.lnPenalitati 
	IF m.lnPret < 0
		lnCantitate = -m.lnCantitate
		lnPret = -m.lnPret
		lnPretVal = m.lnPret && factura de penalitati este in RON, Pretval = Pret
	ENDIF 
	
	Insert Into crsFactura(nrcrt, id_articol, denumire, id_valuta, pretval, Curs, Pret, cantitate, valftva, valtva, valctva, um, id_jtva_coloana_ex, id_jtva_coloana, proc_tva) ;
		Values (1, loArticol.id_articol, loArticol.denumire, m.lnIdMonedaNationala, m.lnPret, 0, m.lnPret, m.lnCantitate, 0, 0, 0, '', m.lnIdJTVAExpl, m.lnIdJtva, m.lnProcTva)

	Select (m.lcSelect)
	Return m.llSucces
Endproc

Procedure make_ccapfactura
	*	IF !USED('crsCapFactura')
	Create Cursor crsCapFactura(uuid N(20) Null, dataact D, datascad D, nract N(20), serie_act C(10), client_id N(10) Null, client C(100) Null, client_ctr_id N(10) Null, contract_client C(250) Null, nr_zile_scadenta N(5) Null, tip_curs N(1) Null, eagent N(1) Null, intern N(1) Null, beneficiar_id N(10) Null, beneficiar C(100) Null, id_set N(10), id_fdoc N(5))
	*	ENDIF 	
Endproc

Procedure make_cfactura
	*	IF !USED('crsFactura')
	Create Cursor crsFactura (nrcrt N(5), id_articol N(20), denumire M, id_locatia N(12) Null, um C(20) Null, cantitate N(10, 4), Pret N(20, 4), valftva N(20, 4), valtva N(20, 4), valctva N(20, 4), pretval N(20, 4), valval N(20, 4), TVAVAL N(20, 4), totval N(20, 4), Curs N(12, 4), id_valuta N(10), id_jtva_coloana_ex N(10), id_jtva_coloana N(10), proc_tva N(5,2), pret_cu_tva N(1), taxcode N(6) null)
	*	ENDIF 
Endproc

Procedure make_cCalculPenalitati
	Create Cursor crsCalculPenalitati(ales L, facturate L, sterse L, clie_id N(12) Null, nrfact  N(16) Null, datafact D Null, datascad D Null, valctva N(18, 4) Null, totval N(18, 4) Null, Curs N(18, 6) Null, id_valuta N(12) Null, valuta C(20) Null, ;
		  explicatia  C(100) Null, id_ctr N(12) Null, numar C(100) Null, contract C(100) Null, nume C(100) Null, id_doc  N(20) Null, nract   N(16) Null, dataact D Null, suma N(18, 4) Null, sumaval N(18, 4) Null, ;
		  pereche N(16) Null, id_fact N(20) Null, ppenzi  N(8, 2) Null, ppenzi2 N(8, 2) Null, penzile N(6) Null, penzile2 N(6) Null, descriere   C(250) Null, zilegratie  N(6) Null, ;
		  nr_zile I Null, nr_zile1 I Null, nr_zile2 I Null, penalitati  N(18, 4) Null, databaza D Null, dataref D Null, tip N(2) Null, sters N(1))
Endproc && make_cCalculPenalitati

Procedure make_cClientiPenalitati
	Create Cursor crsClientiPenalitati (nume C(100), clie_id N(12) )
Endproc && make_cClientiPenalitati

*******************************
Procedure make_grupe_vase
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsGrupeVase")
		lcSql = [select id, grupa from ips_vgrupe_vase order By grupa]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsGrupeVase")
		If !m.llSucces
			Create Cursor crsGrupeVase(Id I, GRUPA C(100))
		Endif
		Select crsGrupeVase
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_grupe_vase

Procedure make_grupe_marfa
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsGrupeMarfa ")
		Create Cursor crsGrupeMarfa (Id N(10), GRUPA C(100), nstr_code C(6) Null)
		Insert Into crsGrupeMarfa (Id, GRUPA, nstr_code) Values (-1, 'FARA MARFA', '')
		Insert Into crsGrupeMarfa (Id, GRUPA, nstr_code) Values (0, '', '')

		lcSql = [Select id, nume, nstr_code From ips_vgoods_groups]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsGrupeMarfaTemp")
		If m.llSucces
			Insert Into crsGrupeMarfa (Id, GRUPA, nstr_code) ;
				Select Id, Padr(Id, 3, ' ') + nume As GRUPA, Cast(Nvl(nstr_code, '') As C(6)) From crsGrupeMarfaTemp Order By Id
			Use In (Select('crsGrupeMarfaTemp'))

			Select crsGrupeMarfa
			Index On Id Tag Id
		Endif
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_grupe_marfa

Procedure make_marfa
	Lparameters tnGrpId
	* tnGrpId (optional) : Numeric = grupa de marfa, Logic T = cu grupa de marfa, F/empty = toate
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsMarfa ")
		Create Cursor crsMarfa (Id C(36) Null, MARFA C(100), GRP_ID N(10) Null)
		Insert Into crsMarfa (Id, MARFA, GRP_ID) Values ('', '', - 1) && -1 = GRUPA FARA MARFA

		lcSql = [Select id, name as marfa, un_number as grp_id From ips_vgoods] + ;
			Iif(!Empty(m.tnGrpId), Iif(Type('tnGrpId') = 'N', [ where un_number = ] + Alltrim(Str(m.tnGrpId)), [ where NVL(un_number,0) <> 0]), []) + ;
			[ order by name]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsMarfaTemp")
		If m.llSucces
			Select crsMarfa
			Append From Dbf('crsMarfaTemp')
			Use In (Select('crsMarfaTemp'))

			Select crsMarfa
			Index On Id Tag Id
		Endif
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_marfa


***----------------------------------------------------------------------------------------
*creeaza un tabel crsContracte din contractele active si numele clientului cu conditie (ex: clie_id=2)
Procedure make_contracte
	Lparameters tcCond, tnIdCtr, tlToateInregistrarile

	&& tnIdCtr: daca dau id_ctr direct (facturile de penalitati) selectez numai acest contractul indiferent de iscontract_valid()
	&& tlToateInregistrarile: daca in tabelul cu contracte este o inregistrare "Toate contractele" cu id_ctr = 0 (pentru raport situatie tranzit toti clientii)
	Local lcWhere

	lcWhere = [incetat = 0] + m.gcCondSucursala

	If Type('tnIdCtr') = 'N' And !Empty(m.tnIdCtr)
		lcWhere = m.lcWhere + [ and (id_ctr = ] + Alltrim(Str(m.tnIdCtr)) + [)]
	Else
		lcAnLuna = Alltrim(Str(m.gnAn)) + Padl(m.gnLuna, 2, '0')
		lcWhere = m.lcWhere + [ and (] + Iif(!Empty(m.tcCond),  m.tcCond + [ and ], "") + Alltrim(Str(m.gnAn * 12 + m.gnLuna)) + [ between extract(year from data_inceput) * 12 + extract(month from data_inceput) and ] + ;
			[extract(year from nvl(data_sfarsit, to_date('] + m.lcAnLuna + [', 'yyyymm'))) * 12 + extract(month from nvl(data_sfarsit, to_date('] + m.lcAnLuna + [', 'yyyymm'))))]
	Endif

	lcSql = [select id_ctr, id_part, denumire, data, numar, data_inceput, data_sfarsit, scadenta_incasare as nr_zile_scadenta, tip_curs from vcontracte where ] + m.lcWhere + [ order by denumire, data_inceput]
	llSucces = goExecutor.oExecuta(m.lcSql, 'crsContracteTemp')

	Use In (Select('crsContracte'))

	If m.tlToateInregistrarile
		Select * From crsContracteTemp Into Cursor crsContracte Where 1 = 2 NOFILTER Readwrite
		Insert Into tcontracte (denumire) Values ('TOATE CONTRACTELE')
		Select crsContracte
		Append From Dbf('crsContracteTemp')
	Else
		Select * From crsContracteTemp Into Cursor crsContracte NOFILTER Readwrite
	Endif
	Use In (Select('crsContracteTemp'))

	Return "crsContracte"
Endproc && make_contracte

***----------------------------------------------------------------------------------------
Procedure make_contacts
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsContacts")
		lcSql = [Select id, name From IPS_VCONTACTS Order By Name]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsContacts")
		If !m.llSucces
			Create Cursor crsContacts(Id I, Name C(100))
		Endif
		Select crsContacts
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_contacts


***----------------------------------------------------------------------------------------
Procedure make_vessel_types
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsVesselTypes")
		lcSql = [Select id, name From ips_vvessel_types Order By Name]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsVesselTypes")
		If !m.llSucces
			Create Cursor crsVesselTypes(Id I, Name C(100))
		Endif
		Select crsVesselTypes
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_vessel_types

***----------------------------------------------------------------------------------------
Procedure make_routes
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsRoutes")
		lcSql = [select id, acronym, name, destinatio, rpt_id, rpt_id_has, rty_id, sens, distanta, ckmi, ckmf, kmi, kmf, orig, intern from ips_vroutes order by name]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsRoutes")
		If !m.llSucces
			Create Cursor crsRoutes(Id I, Name C(100), distanta N(10, 2))
		Endif
		Select crsRoutes
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_vessel_types

***----------------------------------------------------------------------------------------
Procedure make_vas_echivalent
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsVasEchivalent")
		lcSql = [select id, vtp_id, vum_id, id_grup from ips_vvas_echivalent]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsVasEchivalent")
		If !m.llSucces
			Create Cursor crsVasEchivalent(Id I, VTP_ID I, vum_id I, id_grup I)
		Endif
		Select crsVasEchivalent
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_vas_echivalent

***----------------------------------------------------------------------------------------
Procedure make_vas_um
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsVasUM")
		lcSql = [select id, um from ips_vvas_um order by um]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsVasUM")
		If !m.llSucces
			Create Cursor crsVasUM(Id I, um C(20))
		Endif
		Select crsVasUM
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_vas_um


***----------------------------------------------------------------------------------------
Procedure make_um
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsUM")
		lcSql = [select id, um from vnom_um order by um]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsUM")
		If !m.llSucces
			Create Cursor crsUM(Id I, um C(20))
		Endif
		Select crsUM
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_um

***----------------------------------------------------------------------------------------
*** crsGrupTipNave pentru tarife tranzit
Procedure make_grup_tip_nave
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsGrupTipNave")
		lcSql = [select id, nume from ips_vgrup_tip_nave]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsGrupTipNave")
		If !m.llSucces
			Create Cursor crsGrupTipNave(Id I, nume C(20))
		Endif
		Select crsGrupTipNave
		Index On Id Tag Id
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_grup_tip_nave

***----------------------------------------------------------------------------------------
Procedure make_aramis_tip_nave
	Local lcSelect, lcSql, llSucces

	lcSelect = Select()
	llSucces = .T.
	If !Used("crsAramisTipNave")
		lcSql = [select id, nume from ips_varamis_tip_nave]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsAramisTipNave")
		If !m.llSucces
			Create Cursor crsAramisTipNave(Id I, nume C(20))
		Endif
		Select crsAramisTipNave
		Index On Id Tag Id
		Index On nume Tag nume
		Set Order To nume
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_aramis_tip_nave

***----------------------------------------------------------------------------------------
Procedure make_dane
	lcSelect = Select()
	llSucces = .T.

	If !Used('crsDane')
		lcSql = [select id, descriere as dana, dana as cod from ips_dane]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsDane")
		If !m.llSucces
			Create Cursor crsDane(Id N(1), dana C(20), cod C(5))
			Insert Into crsDane (Id, dana, cod) Values (1, 'OPERARE/PORT', 'OP')
			Insert Into crsDane (Id, dana, cod) Values (2, 'ASTEPTARE', 'AS')
			Insert Into crsDane (Id, dana, cod) Values (3, 'IERNAT', 'IE')
			Insert Into crsDane (Id, dana, cod) Values (4, 'REPARATII', 'RE')				
			Insert Into crsDane (Id, dana, cod) Values (5, 'PESCUIT', 'PE')						
			Insert Into crsDane (Id, dana, cod) Values (9, 'ALTE', 'AL')
		ENDIF
			
		Select crsDane
		Index On Id Tag Id
		Index On dana Tag dana
		Set Order To Id
	Endif
	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_dane

****************************************************
*** creeaza cursor crsJTVA
****************************************************
Procedure make_jtva_explicatii
	Local lcSql, llSucces
	llSucces = .T.
	If !Used('crsJTVA')
		lcSql = [select id, denumire, id_jtva_coloana, id_tva, explicatie, ordine, cota_tva, coloana_jv, coloana_jc from vjtva_coloane_explicatii where inactiv = 0]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsJTVA")
		If m.llSucces
			Select crsJtva
			Index On Id Tag Id
		Endif
	Endif
	Return m.llSucces
Endproc && make_jtva_explicatii

****************************************************
*** creeaza cursor crsCoteTVA
****************************************************
Procedure make_cote_tva
	Local lcSql, llSucces
	llSucces = .T.
	If !Used('crsCoteTVA')
		Text To lcSql Noshow
  select rpad(trim(TO_CHAR(procent, '999')),25, ' ') as procent, proc_tva
    from vcote_tva 
    where an = ?gnAn and luna = ?gnLuna
	order by proc_tva desc
		Endtext
		*!*	UNION 
		*!*	SELECT ' < ALES LA FACTURARE > ' AS procent, -1 AS proc_tva FROM dual

		llSucces = goExecutor.oExecuta(m.lcSql, "crsCoteTVA")
		If m.llSucces
			Index On proc_tva Tag proc_tva Descending
		Endif && llSucces
	Endif && used

	Return m.llSucces
Endproc && make_cote_tva

****************************************************
*** creeaza cursor crsCheiajPrestatii
****************************************************
Procedure make_cheiaj_prestati
	Local lcSql, llSucces, lcSelect
	lcSelect = Select()
	m.llSucces = .T.
	If !Used('crsCheiajPrestatii')
		lcSql = [select id, dana_id, dana, tipn_id, tipn, id_articol, articol, id_locatia, locatia from ips_vcheiaj_prestatii]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsCheiajPrestatii")
	Endif
	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_cheiaj_prestati


****************************************************
*** creeaza cursor crsArticole
****************************************************
Procedure make_articole
	Local lcSql, llSucces, lcSelect
	lcSelect = Select()
	m.llSucces = .T.
	If !Used('crsArticole')
		lcSql = [select id_articol, codmat, denumire, descriere, um, id_grupa, grupa, id_subgrupa, subgrupa from vnom_articole where inactiv = 0 and tip = 1 order by denumire] && manopera
		llSucces = goExecutor.oExecuta(m.lcSql, "crsArticole")
		If m.llSucces
			Select crsArticole
			Index On id_articol Tag id_articol
			Index On denumire Tag denumire
		Endif
	Endif
	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_articole

****************************************************
*** creeaza cursor crsLocatii
****************************************************
Procedure make_locatii
	Local lcSql, llSucces, lcSelect
	lcSelect = Select()
	llSucces = .T.
	If !Used('crsLocatii')
		lcSql = [select id, denumire from vnom_locatii where inactiv = 0 order by denumire]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsLocatii")
		If m.llSucces
			Select crsLocatii
			Index On Id Tag Id
			Index On denumire Tag denumire
		Endif && llSucces
	Endif && used
	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_locatii

****************************************************
*** creeaza cursor crsArticoleLocatii
****************************************************
Procedure make_articole_locatii
	Local lcSql, llSucces, lcSelect
	lcSelect = Select()
	Use In (Select('crsArticoleLocatii'))

	llSucces = .T.
	If !Used('crsArticoleLocatii')
		lcSql = [select id_articol, id_locatia, ctdebitor, ctcreditor, ctaideb, ctaedeb, ctaicred, ctaecred, ctpideb, ctapideb, ctpicred, ctapicred from ips_vprestatii_locatii]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsArticoleLocatii")
		If m.llSucces
			Select crsArticoleLocatii
			Index On id_articol Tag id_articol
			Index On id_locatia Tag id_locatia
		Endif
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && crsArticoleLocatii

****************************************************
*** creeaza cursor crsValute
****************************************************
Procedure make_valute
	Local lcSql, llSucces, lcSelect
	lcSelect = Select()
	llSucces = .T.
	If !Used('crsValute')
		lcSql = [select id_valuta, nume_val, moneda_nationala from vnom_valute where inactiv = 0 order by nume_val]
		llSucces = goExecutor.oExecuta(m.lcSql, "crsValute")
		If m.llSucces
			Select crsValute
			Index On id_valuta Tag id_valuta
		Endif
	Endif

	Select (m.lcSelect)
	Return m.llSucces
Endproc && make_valute


*!*	****************************************************
*!*	*** creeaza cursor crsTarifeDiverseContract pentru contractul dat si tarifele generale pentru clientii fara contract
*!*	****************************************************
*!*	Procedure make_tarife_diverse_contract
*!*		Lparameters tnIdCtr, tnIdCtrFara
*!*		* tnIdCtrFara (optional)

*!*		Local lcSql, lnIdCtr, lnIdCtr2, lcSelect, llSucces
*!*		lcSelect = Select()
*!*		lnIdCtr = m.tnIdCtr
*!*		lnIdCtr2 = Iif(!Empty(m.tnIdCtrFara), m.tnIdCtrFara, m.tnIdCtr)

*!*		&& selectez tarifele de pe contract si pe cele generale
*!*		Text To lcSql Textmerge Noshow
*!*		select id, id_articol, lim1, lim2, umlim, corect, tar_prest, tar_furn, tar_total, numevaluta, ctr_id, tip, intern, loc_id, cant, um, plus, arebaza, baza, valval, ediscount, id_valuta
*!*			from ips_tarife_diverse
*!*			WHERE ctr_id in (<<m.lnIdCtr>>, <<m.lnIdCtr2>>)
*!*		Endtext
*!*		llSucces = goExecutor.oExecuta(m.lcSql, 'crsTarifeDiverseContract')

*!*		Select (m.lcSelect)
*!*		Return m.llSucces
*!*	Endproc

****************************************************
*** creeaza cursor crsTarifeCheiajContract pentru contractul dat si tarifele generale pentru clientii fara contract
****************************************************
Procedure make_tarife_cheiaj_contract
	Lparameters tnIdCtr, tnIdCtrFara
	* tnIdCtrFara (optional)

	Local lcSql, lnIdCtr, lnIdCtr2, lcSelect, llSucces
	lcSelect = Select()
	lnIdCtr = m.tnIdCtr
	lnIdCtr2 = Iif(!Empty(m.tnIdCtrFara), m.tnIdCtrFara, m.tnIdCtr)

	&& selectez tarifele de pe contract si pe cele generale
	Text To lcSql Textmerge Noshow
select id, id_articol, lim1, lim2, um, corect, valoare as tarif, valoare, ctr_id, intern, plus, arebaza, baza, id_valuta 
	from ips_tarife_cheiaj
	WHERE ctr_id in (<<m.lnIdCtr>>, <<m.lnIdCtr2>>)
	Endtext
	llSucces = goExecutor.oExecuta(m.lcSql, 'crsTarifeDiverseContract')

	Select (m.lcSelect)
	Return m.llSucces
Endproc

Procedure make_tipfactura
	If !Used('crsTipFactura')
		Create Cursor crsTipFactura (tip C(100))

		Insert Into crsTipFactura (tip) Values ('TRANZIT')
		Insert Into crsTipFactura (tip) Values ('CHEIAJ')
		Insert Into crsTipFactura (tip) Values ('CHIRII')
		Insert Into crsTipFactura (tip) Values ('APA')
		Insert Into crsTipFactura (tip) Values ('DIVERSE')
		Insert Into crsTipFactura (tip) Values ('PENALITATI')
		Insert Into crsTipFactura (tip) Values ('PROFORMA')
	Endif
Endproc

***----------------------------------------------------------------------------------------
*** intoarce id contract pentru clientul "FARA CONTRACT", pentru calcularea valorii facturii din tarifele pentru clientul FARA CONTRACT valabil in luna curenta
Function get_ctr_id_fara_contract
	Private pnId
	Local lnId, lcAnLuna, lcSelect, llSucces, llShowError
	lcSelect = Select()
	lnId = -3
	llShowError = .T.

	lcAnLuna = Alltrim(Str(Int(m.gnAn))) + Padl(Int(m.gnLuna), 2, '0')
	lcSql = [SELECT ID_CTR FROM VCONTRACTE WHERE DENUMIRE = 'FARA CONTRACT' and ] + Alltrim(Str(m.gnAn * 12 + m.gnLuna)) + [ between extract(year from data_inceput) * 12 + extract(month from data_inceput) and ] + ;
		[extract(year from nvl(data_sfarsit, to_date('] + m.lcAnLuna + [', 'yyyymm'))) * 12 + extract(month from nvl(data_sfarsit, to_date('] + m.lcAnLuna + [', 'yyyymm')))]

	pnId = 0
	llSucces = goExecutor.oSelecteaza2Value(m.lcSql, @pnId)

	If Empty(m.pnId)
		Do Case
			Case Val(m.an) < 2006
				lnId = -1
			Case Val(m.an) = 2006
				lnId = -2
			Otherwise && >= 2007
				lnId = -3
		Endcase
	Else
		lnId = m.pnId
	Endif

	Select (m.lcSelect)

	Return m.lnId
Endfunc && get_ctr_id_fara_contract

****************************************************
*** Intoarce un obiect cu id-ul si denumirea articolulul tranzit/cheiaj/penalitati
****************************************************
Function GetPrestatieByTip
	Lparameters tcTip, tlExplicatieEN
	* tcTip: Tranzit, Cheiaj, Penalitati
	* tlExplicatieEN: explicatia in engleza
	Local lcTip, loArticol, lcSelect, lcDescriere1, lcDescriere2, lcDescriereRO, lcDescriereEN
	Private pnId, pcDenumire
	pnId = 0
	lcSelect = Select()
	lcTip = m.tcTip
	loArticol = Createobject("empty")
	AddProperty(loArticol, "id_articol", 0)
	AddProperty(loArticol, "denumire", "")
	AddProperty(loArticol, "descriere", "")

	pcDenumire = '*' + m.lcTip && *TRANZIT/*CHEIAJ/*PENALITATI/*APA/*CHIRII
	lcSql = [SELECT id_articol, denumire, descriere FROM nom_articole WHERE denumire = ?pcDenumire]
	llSucces = goExecutor.oExecuta(m.lcSql, 'crsArticolTemp')
	If m.llSucces
		Select crsArticolTemp
		Go Top
		loArticol.id_articol = id_articol
		lcDescriere = Alltrim(Nvl(descriere, '')) && RO::C/V TRANZITARE CDMN PENTRU CONVOIUL/BARJA [INDICATIV], DIN [DATA] CONFORM [CONTRACT]|EN::TRANSIT FOR [INDICATIV], IN [DATA] ACCORDING TO THE [CONTRACT]
		lcDescriere1 = Getwordnum(m.lcDescriere, 1, '|')
		lcDescriere2 = Getwordnum(m.lcDescriere, 2, '|')
		If Left(m.lcDescriere1, 4) = 'RO::'
			lcDescriereRO = Strtran(m.lcDescriere1, 'RO::', '', 1, 1, 1)
			lcDescriereEN = Strtran(m.lcDescriere2, 'EN::', '', 1, 1, 1)
		Else
			lcDescriereRO = Strtran(m.lcDescriere2, 'RO::', '', 1, 1, 1)
			lcDescriereEN = Strtran(m.lcDescriere1, 'EN::', '', 1, 1, 1)
		Endif

		loArticol.denumire = Iif(m.tlExplicatieEN, m.lcDescriereEN, m.lcDescriereRO)
		loArticol.descriere = Iif(m.tlExplicatieEN, m.lcDescriereEN, m.lcDescriereRO)
		Use In (Select('crsArticolTemp'))
	Endif

	Select (m.lcSelect)
	Return loArticol
Endfunc && GetPrestatieByTip
****************************************************

****************************************************
*** Intoarce un obiect cu id-ul si denumirea articolulul cu id_articol din parametru
****************************************************
Function GetPrestatieById
	Lparameters tnIdArticol, tlExplicatieEN

	Private pnIdArticol
	Local loArticol As "empty"
	Local lcDescriere, lcDescriere1, lcDescriere2, lcDescriereEN, lcDescriereRO, lcSelect, lcSql
	Local llSucces
	pnIdArticol = tnIdArticol
	lcSelect = Select()

	loArticol = Createobject("empty")
	AddProperty(loArticol, "id_articol", 0)
	AddProperty(loArticol, "denumire", "")
	AddProperty(loArticol, "descriere", "")

	lcSql = [SELECT id_articol, denumire, descriere FROM nom_articole WHERE id_articol = ?pnIdArticol]
	llSucces = goExecutor.oExecuta(m.lcSql, 'crsArticolTemp')
	If m.llSucces
		Select crsArticolTemp
		Go Top
		loArticol.id_articol = id_articol
		loArticol.denumire = Alltrim(Nvl(denumire, ''))
		lcDescriere = Alltrim(Nvl(descriere, '')) && RO::C/V TRANZITARE CDMN PENTRU CONVOIUL/BARJA [INDICATIV], DIN [DATA] CONFORM [CONTRACT]|EN::TRANSIT FOR [INDICATIV], IN [DATA] ACCORDING TO THE [CONTRACT]
		lcDescriere1 = Getwordnum(m.lcDescriere, 1, '|')
		lcDescriere2 = Getwordnum(m.lcDescriere, 2, '|')
		If Left(m.lcDescriere1, 4) = 'RO::'
			lcDescriereRO = Strtran(m.lcDescriere1, 'RO::', '', 1, 1, 1)
			lcDescriereEN = Strtran(m.lcDescriere2, 'EN::', '', 1, 1, 1)
		Else
			lcDescriereRO = Strtran(m.lcDescriere2, 'RO::', '', 1, 1, 1)
			lcDescriereEN = Strtran(m.lcDescriere1, 'EN::', '', 1, 1, 1)
		Endif

		loArticol.descriere = Iif(m.tlExplicatieEN, m.lcDescriereEN, m.lcDescriereRO)
		Use In (Select('crsArticolTemp'))
	Endif

	Select (m.lcSelect)
	Return loArticol
Endfunc && GetPrestatieId
****************************************************

****************************************************
*** Intoarce id_Articol din obiectul articol.id_articol, denumire
****************************************************
Function GetIdPrestatieByArticol
	Lparameters toArticol

	Return Iif(Type('toArticol.id_articol') = 'N', toArticol.id_articol, 0)
Endfunc && GetIdPrestatieByArticol

****************************************************
*** Intoarce numele unui articol dupa Id din cursorul crsArticole sau din baza de date
****************************************************
Function GetArticolById
	Lparameters tnId

	Local llSucces, llShowError, lcSelect
	Private pnId, pcDenumire
	pnId = m.tnId
	pcDenumire = ''
	lcSelect = Select()
	If Used('crsArticole')
		If Seek(m.pnId, 'crsArticole', 'id_articol')
			pcDenumire = Alltrim(crsArticole.denumire)
		Endif
	Endif && USED

	If Empty(m.pcDenumire)
		llShowError = .T.
		llSucces = goExecutor.oSelecteaza2Value([SELECT denumire FROM vnom_articole WHERE id_articol = ?pnId], @pcDenumire)
	Endif
	Select (m.lcSelect)

	Return m.pcDenumire
Endfunc

****************************************************
*** Intoarce numele unei locatii dupa Id din cursorul crsLocatii sau din baza de date
****************************************************
Function GetLocatieById
	Lparameters tnId

	Local llSucces, llShowError, llSelect
	Private pnIdLocatie, pcLocatie
	pnId = m.tnId
	pcDenumire = ''
	lcSelect = Select()
	If Used('crsLocatii')
		If Seek(m.pnId, 'crsLocatii', 'id')
			pcDenumire = Alltrim(crsLocatii.denumire)
		Endif
	Endif && USED

	If Empty(m.pcDenumire)
		llShowError = .T.
		llSucces = goExecutor.oSelecteaza2Value([SELECT denumire FROM vnom_locatii WHERE id = ?pnId], @pcDenumire)
	Endif
	Select (m.lcSelect)

	Return m.pcDenumire
Endfunc

************************************
*** Intoarce id locatie dupa denumirea locatiei din cursorul crsLocatii sau din baza de date
************************************
Function GetIdLocatieByName
	Lparameters tcDenumire
	Private pcDenumire, pnId
	Local llShowError, lcSelect
	lcSelect = Select()
	pcDenumire = Upper(Alltrim(Nvl(m.tcDenumire, '')))
	pnId = 0

	If Used('crsLocatii')
		If Seek(m.pcDenumire, 'crsLocatii', 'denumire')
			pnId = crsLocatii.Id
		Endif
	Endif && USED

	If Empty(m.pnId)
		llShowError = .T.
		llSucces = goExecutor.oSelecteaza2Value([select id from vnom_locatii where denumire = ?pcDenumire], @pnId)
	Endif
	Select (m.lcSelect)

	Return m.pnId
Endfunc && GetIdLocatieByName




****************************************************
*** intoarce procent TVA standard 19/20/24
****************************************************
Function GetCotaTVAStandard
	Local lcSql, llSucces, lnProcTva, lcSelect
	lcSelect = Select()
	lnProcTva = Iif(m.gnAn*12+m.gnLuna >= 2025*12+8, 21, Iif(m.gnAn >= 2017, 19, Iif(m.gnAn >= 2016, 20, Iif(m.gnAn >= 2015, 24, 21))))

	lcSql = [select procent from cote_tva where an=?m.gnAn and luna = ?m.gnLuna and descriere = 'STANDARD']

	llSucces = goExecutor.oExecuta(m.lcSql, 'crsCoteTemp')

	If m.llSucces
		Select crsCoteTemp
		Go Top
		If Reccount() >= 1
			lnProcTva = crsCoteTemp.procent
		Endif
		Use In (Select('crsCoteTemp'))
	Endif
	Select (m.lcSelect)
	Return m.lnProcTva
Endfunc && GetCotaTVAStandard


****************************************************
*** intoarce obiect procent TVA standard (IdJtvaExpl, IdJtva, ProcTva)
*** trebuie sa existe crsJTVA: make_jtva_explicatii()
****************************************************
Function GetTVAStandard
	Lparameters tnIntern
	* tnIntern (optional): 1 = intern, 0 = extern, implicit 1
	Local lnInter, loTVA As "empty"

	lnIntern = Iif(Type('tnIntern') = 'N', m.tnIntern, 1)
	loTVA = GetObiectTVA(m.lnIntern)
	Return loTVA
Endfunc && GetTVAStandard

****************************************************
*** intoarce obiect procent TVA standard (IdJtvaExpl, IdJtva, ProcTva)
*** trebuie sa existe crsJTVA: make_jtva_explicatii()
****************************************************
Function GetObiectTVA
	Lparameters tnIntern, tnCotaTVA, tnIdJtvaColoana
	* tnIntern (optional): 1 = intern, 0 = extern, implicit .T. 
	* tnCotaTVA (optional, default COTA STANDARD): 19/20/24
	* tnIdJtvaColoana (optional) - intorc obiect tva cu id_jtva_coloana = tnIdJtvaColoana

	Local llIntern, lnCotaTVA, lcSelect, lnCotaTVAStandard, loTVA As "empty"
	lcSelect = Select()
	loTVA = Createobject("empty")
	AddProperty(loTVA, "IdJTVAExpl", 0)
	AddProperty(loTVA, "IdJTVA", 0)
	AddProperty(loTVA, "ProcTVA", 0)

	lnCotaTVAStandard = GetCotaTVAStandard()
	llIntern = Iif(Pcount() >= 1, Iif(m.tnIntern = 1, .T., .F.), .T.)
	Do Case
		Case !Empty(m.tnIdJtvaColoana)
			Select crsJtva
			Locate For id_jtva_coloana = m.tnIdJtvaColoana
		Otherwise
			If m.llIntern
				lnCotaTVA = Iif(Type('tnCotaTVA') = 'N', m.tnCotaTVA, m.lnCotaTVAStandard)
				Select crsJtva
				Locate For cota_tva = m.lnCotaTVA
				If !Found()
					Locate For cota_tva = m.lnCotaTVAStandard
				Endif
			Else
				Select crsJtva
				Locate For coloana_jv = 'WRSCDD' && alte livrari scutite cu drept de deducere
			Endif
	Endcase
	If Found()
		loTVA.IdJtvaExpl = Id
		loTVA.IdJtva = id_jtva_coloana
		loTVA.ProcTva = Round(1 + cota_tva / 100, 2)
	Endif

	Select (m.lcSelect)
	Return loTVA
Endfunc && GetObiectTVA

****************************************************
*** Creeaza cursorul cRegDoc pentru inregistrarea in Reg Doc.
*** Se inregistreaza factura in vanzari si apoi in Reg. Doc.
****************************************************
Procedure make_cregdoc
	Private poRegdoc
	poRegdoc = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam
	Text To lcSchema Noshow
id N(20), id_vanzare N(12), tip N(1), id_articol N(10), articol C(100), id_locatia N(5), locatia C(100), id_valuta N(5), valuta C(50), id_client N(10), client C(100), id_contract N(10), contract C(100), pret N(16,4), curs N(12, 4), cantitate N(10,3), valval N(20,4), tvaval N(20,4), totval N(20,4), valftva N(20,4), valtva N(20,4), valctva N(20,4), um C(20), document C(100), data D, id_jtva_coloana N(10), id_jtva_coloana_ex N(10) Null
	Endtext
	lcOrder = []
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []
	Text To lcSelect Noshow
select id, id_vanzare, tip, id_articol, articol, id_locatia, locatia, id_valuta, valuta, id_client, client, id_contract, contract, pret, curs, cantitate, valval, tvaval, totval, valftva, valtva, valctva, um, document, data, 0 as id_jtva_coloana, 0 as id_jtva_coloana_ex from ips_vregdoc
	Endtext
	gencursor('poRegDoc', 'cRegDoc', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poRegdoc.ca_baza1.afisare()
Endproc && make_cregdoc


****************************************************
*** Creeaza cursorul gol actactan
*** Intoarce .T. daca s-a creat cursorul actactan
****************************************************
Procedure make_actactan
	Private poAct
	poAct = Null

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam

	Text To lcSchema Noshow
	serie_act C(10),id_act N(20),luna N(4),an N(6),cod N(20),dataireg T,nract N(16),dataact T,suma N(20,4),explicatia C(100),scd C(4),ascd C(4),scc C(4),ascc C(4),pereched N(16),perechec N(16),suma_val N(20,4),explicatia2 C(100),explicatia3 C(100),curs N(14,6),datascad T,neimpozab N(20,4),nnir N(16),id_util N(7),util C(30),dataora T,id_utils N(7),utils C(30),dataoras T,id_respons N(12),nresp C(30),id_venchel N(7),dst_chlt C(100),id_lucrare N(12),nrord C(50),id_ctr N(10),contract C(61),id_sectie N(7),sectie C(50),proc_tva N(7,2),id_set N(20),id_fact N(20),id_factd N(20),id_factc N(20),id_partd N(12),partd C(70),id_partc N(12),partc C(70),id_sucursala N(7),sucursala C(30),id_fdoc N(7),fdoc C(30),id_gestin N(7),id_jtva_coloana N(6),gestin C(50),id_gestout N(7),gestout C(50),id_valuta N(7),nume_val C(20),id_pol N(10),nume_lista C(30),tva_incasare N(1),id_instiintare N(20),numar_instiintare N(16),nr_nota N(6),taxcode N(6),paymentcode V(9)
	Endtext

	lcOrder = []
	lcFiltru = [1=2]
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []
	Text To lcSelect Noshow
	select serie_act, id_act, luna, an, cod, dataireg, nract, dataact, suma, explicatia, scd, ascd, scc, ascc, pereched, perechec, suma_val, explicatia4, explicatia5, curs, datascad, neimpozab, nnir, id_util, util, dataora, id_utils, utils, dataoras, id_responsabil, nresp, id_venchelt, dst_chlt, id_lucrare, nrord, id_ctr, contract, id_sectie, sectie, proc_tva, id_set, id_fact, id_factd, id_factc, id_partd, partd, id_partc, partc, id_sucursala, sucursala, id_fdoc, fdoc, id_gestin, id_jtva_coloana, gestin, id_gestout, gestout, id_valuta, nume_val, id_pol, nume_lista_preturi, tva_incasare, id_instiintare, numar_instiintare, nr_nota, taxcode, paymentcode from vactan
	Endtext

	gencursor('poAct', 'actactan', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poAct.ca_baza1.afisare()

	Return Used('actactan')
Endproc && make_actactan


**************************************************
*** Intoarce conturi, analitice pentru o prestatie/activitate din crsArticoleLocatii (ips_varticole_locatii)
**************************************************
Procedure GetCont
	Lparameters tcTip, tnIdLocatia, tnIdArticol, tlIntern, tlPenalitati, tcScd, tcAscd, tcScc, tcAscc, tcExplicatia

	Local lcSelect, lcGrupa, llFound, llIntern, llPenalitati, lnTip, lnIdArticol, lnIdLocatia, lcTip, llSucces
	lcSelect = Select()
	llSucces = .F.
	tcScd = ''
	tcScc = ''
	tcAscd = ''
	tcAscc = ''
	tcExplicatia = ''

	lcTip = m.tcTip
	llIntern = m.tlIntern
	llPenalitati = m.tlPenalitati
	lnIdArticol = m.tnIdArticol
	lnIdLocatia = m.tnIdLocatia
	lcGrupa = ''

	llFound = .F.

	* Inca nu este implementat penalitati pentru facturi de tranzit pe locatii din ips_regdoc
	* pun penalitati tranzit pe locatia SEDIU
	If m.llPenalitati And Empty(Nvl(m.lnIdLocatia, 0))
		lnIdLocatia = GetIdLocatieByName('SEDIU')
	Endif

	*** caut prestatia pentru tipul respectiv.
	*** Daca este facturi diverse TIP = 9 sau alte prestatii TIP = 2, caut doar prestatia. La diverse, pot sa aleg prestatie de orice tip
	If !Empty(m.lnIdArticol) And !Empty(m.lnIdLocatia)
		Select crsArticoleLocatii
		Locate For id_articol = m.lnIdArticol And id_locatia = m.lnIdLocatia
		llFound = Found()
	Endif

	If !m.llFound
		lcGrupa = Iif(m.lcTip = TIP_TRANZIT, 'TRANZIT', Iif(m.lcTip = TIP_CHEIAJ, 'CHEIAJ', Iif(m.lcTip = TIP_PILOTAJ, 'PILOTAJ', Iif(m.lcTip = TIP_APA, 'LIVAPA', Iif(m.lcTip = TIP_DIVERSE, 'DIVERSE', '*')))))
		*** nu am gasit prestatia dupa ID, sau este o activitate fara prestatii - caut configurari generice dupa CAT = *, SUBCAT = TRANZIT/CHEIAJ/PILOTAJ/LIVAPA
		If m.llPenalitati
			Select crsArticole
			Locate For GRUPA = TIP_PENALITATI  And subgrupa = m.lcTip
		Else
			Select crsArticole
			Locate For GRUPA = m.lcTip And subgrupa = '*'
		Endif

		If Found()
			lnIdArticol = crsArticole.id_articol

			Select crsArticoleLocatii
			Locate For id_articol = m.lnIdArticol And id_locatia = m.lnIdLocatia
			llFound = Found()
		Endif
	Endif

	If m.llFound
		Select crsArticoleLocatii
		If !m.llPenalitati
			tcScd = Allt(Nvl(CTDEBITOR, ''))
			tcScc = Allt(Nvl(CTCREDITOR, ''))
			tcAscd = Alltrim(Iif(m.llIntern, Nvl(ctaideb, ''), Nvl(ctaedeb, '')))
			tcAscc = Alltrim(Iif(m.llIntern, Nvl(ctaicred, ''), Nvl(ctaecred, '')))
		Else
			tcScd = Allt(Nvl(CTPIDEB, ''))
			tcScc = Allt(Nvl(CTPICRED, ''))
			tcAscd = Alltrim(Nvl(CTAPIDEB, ''))
			tcAscc = Alltrim(Nvl(CTAPICRED, ''))
		Endif
		tcExplicatia = ''

		If Empty(tcScd) Or Empty(tcScc)
			lctext = 'Nu sunt completate conturile la prestatia ID: ' + Alltrim(Transform(lnIdArticol)) + ' ' + GetArticolById(m.lnIdArticol) + ' locatia ID: ' + Alltrim(Transform(m.lnIdLocatia)) + ' ' + GetLocatieById(m.lnIdLocatia) + Iif(m.lnIdLocatia <> m.tnIdLocatia, '(' + Alltrim(Str(m.tnIdLocatia))  + ' ' + GetLocatieById(m.tnIdLocatia) + ')', '') + ' GRUPA: ' + m.lcGrupa
			poLog.Log(m.lctext, Program())
			amessagebox(m.lctext, 0 + 48, _Screen.Caption)
		Endif
	Else

		lctext = 'Nu exista configurari pentru conturi la prestatia ID: ' + Alltrim(Transform(lnIdArticol)) + ' ' + GetArticolById(m.lnIdArticol) + ' locatia ID: ' + Alltrim(Transform(m.lnIdLocatia)) + ' ' + GetLocatieById(m.lnIdLocatia) + Iif(m.lnIdLocatia <> m.tnIdLocatia, '(' + Alltrim(Str(m.tnIdLocatia))  + ' ' + GetLocatieById(m.tnIdLocatia) + ')', '') + ' GRUPA: ' + m.lcGrupa
		poLog.Log(m.lctext, Program())
		amessagebox(m.lctext, 0 + 48, _Screen.Caption)
	Endif

	llSucces = !(Empty(m.tcScd) Or Empty(m.tcScc))

	Select (m.lcSelect)
	Return m.llSucces
Endproc && GetCont


**************************************************************
*** vizualizare tarife tranzit
**************************************************************
Procedure vizualizare_tarife_tranzit
	Local loFrmTarife As "frm_tarife_tranzit"
	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, lcSql, lcSqlDelete
	Local lcSqlInsert, lcSqlUpdate, llAfiseaza, llModParam, llScris, llSucces, llSucces2, lnModificat
	Local lnRec
	Private pnId, poRec, poTarife
	poTarife = Null


	Do make_contracte && crsContracte
	Do make_grupe_marfa && crsGrupeMarfa
	Do make_marfa With .T. && crsMarfa
	Do make_valute && crsValute
	Do make_vas_um && crsVasUM
	Do make_routes && crsRoutes
	Do make_grup_tip_nave && crsGrupTipNave

	Text To lcSchema Noshow
id N(10) null, intern N(1), ctr_id N(10) null, rte_id N(20) null, vum_id N(10), gtn_id N(10), gdsg_id N(10) NULL, gds_id C(36) null, id_valuta N(7), valoare N(20,4), tcap1 N(5), tcap2 N(5), tccap1 N(12), tccap2 N(12), modificat N(1)
	Endtext

	lcOrder = [intern desc, gtn_id, tcap1, tcap2, gdsg_id]
	lcFiltru = []
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Noshow
select id,
       intern,
       ctr_id,
       rte_id,
       vum_id,
       gtn_id,
       decode(gdsg_id, -1, 999888, gdsg_id) as gdsg_id,
       gds_id,       
       id_valuta,
       valoare,
       tcap1,
       tcap2,   
       tccap1,
       tccap2,
       0 as modificat
  from ips_vtarife_tranzit
	Endtext

	Update crsGrupeMarfa Set Id = Iif(Id = -1, 999888, Id) && nu se afisa corect grupa de marfa cu id = -1, am pus id = 999888, apoi l-am modificat in -1

	gencursor('poTarife', 'crsTarife', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poTarife.ca_baza1.afisare()
	Select crsTarife
	loFrmTarife = Createobject("frm_tarife_tranzit") && oacnpro.vcx
	*	DO FORM frm_tarife_tranzit NAME loFrmTarife NOSHOW 
	loFrmTarife.Show(1)

	If m.gnButon = 1
		lcSqlDelete = [DELETE from ips_tarife_tranzit WHERE id = ?pnId]

		Text To lcSqlInsert Noshow
		insert into ips_tarife_tranzit
  (intern, ctr_id, rte_id, tcap1, tcap2, vum_id, valoare, tccap1, tccap2, gdsg_id, gtn_id, gds_id, id_valuta)
values
(?poRec.intern, ?poRec.ctr_id, ?poRec.rte_id, ?poRec.tcap1, ?poRec.tcap2, ?poRec.vum_id, ?poRec.valoare, ?poRec.tccap1, ?poRec.tccap2, ?poRec.gdsg_id, ?poRec.gtn_id, ?poRec.gds_id, ?poRec.id_valuta)
		Endtext

		Text To lcSqlUpdate Noshow
update ips_tarife_tranzit
   set intern = ?poRec.intern,
       ctr_id = ?poRec.ctr_id,
       rte_id = ?poRec.rte_id,
       tcap1 = ?poRec.tcap1,
       tcap2 = ?poRec.tcap2,
       vum_id = ?poRec.vum_id,
       valoare = ?poRec.valoare,
       tccap1 = ?poRec.tccap1,
       tccap2 = ?poRec.tccap2,
       gdsg_id = ?poRec.gdsg_id,
       gtn_id = ?poRec.gtn_id,
       gds_id = ?poRec.gds_id,
       id_valuta = ?poRec.id_valuta
 where id = ?poRec.id;
		Endtext

		Select crsTarife
		Set Filter To

		llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

		If m.llSucces && transactions
			*** SELECTEZ IREG STERSE
			Set Deleted Off
			Sele Id From crsTarife Where Deleted() Into Cursor cTarifeSterse
			Set Deleted On

			Select cTarifeSterse
			Scan
				pnId = Id
				llSucces = goExecutor.oExecuta(m.lcSqlDelete)
				If !m.llSucces
					Exit
				Endif
			Endscan
			Use In (Select('cTarifeSterse'))
			*** STERG IN TARIFE_DIVERSE IREG STERSE

			If m.llSucces
				*** MODIFIC IN TARIFE IREG MODIFICATE IN TEMPORAR
				Sele crsTarife
				Set Filter To
				Calculate Cnt() To m.lnModificat For Nvl(modificat, 0) = 1

				lnRec = 0
				Sele crsTarife
				Scan For Nvl(modificat, 0) = 1
					Scatter Name poRec Memo
					poRec.gdsg_id = Iif(poRec.gdsg_id = 999888, -1, poRec.gdsg_id) && nu se afisa corect grupa de marfa cu id = -1, am pus id = 999888, apoi l-am modificat in -1
					lnRec = m.lnRec + 1
					Wait Window 'Tarif nou/modificat ' + Alltrim(Str(m.lnRec)) + '/' + Alltrim(Str(m.lnModificat)) Nowait

					If Empty(Nvl(poRec.Id, 0))
						llSucces = goExecutor.oExecuta(m.lcSqlInsert)
					Else
						llSucces = goExecutor.oExecuta(m.lcSqlUpdate)
					Endif
					If !m.llSucces
						Exit
					Endif
				Endscan
			Endif && llSucces

			If !m.llSucces
				lcSql = "ROLLBACK"
				llScris = .F.
			Else
				lcSql = "COMMIT"
				llScris = .T.
			Endif
			llScris = goExecutor.oExecuta(m.lcSql)

			llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
			If !m.llSucces2
				amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
			Endif

			llSucces = m.llSucces And m.llScris
		Endif && gnButon

		If m.llSucces
			amessagebox('Tarife modificate cu succes!', 0 + 64, _Screen.Caption)
		Else
			amessagebox('Tarifele nu s-au modificat!', 0 + 64, _Screen.Caption)
		Endif
	Endif && gnButon

	Use In (Select('crsContracte'))
	Use In (Select('crsGrupeMarfa'))
	Use In (Select('crsMarfa'))
	Use In (Select('crsValute'))
	Use In (Select('crsVasUM'))
	Use In (Select('crsRoutes'))
	Use In (Select('crsGrupTipNave'))

	Return m.llSucces
Endproc && vizualizare_tarife_tranzit


**************************************************************
*** vizualizare tarife cheiaj
**************************************************************
Procedure vizualizare_tarife_cheiaj
	Local loFrmTarife As "frm_tarife_tranzit"
	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, lcSql, lcSqlDelete
	Local lcSqlInsert, lcSqlUpdate, llAfiseaza, llModParam, llScris, llSucces, llSucces2, lnModificat
	Local lnRec
	Private pnId, poRec, poTarife
	poTarife = Null

	Do make_contracte && crsContracte
	Do make_articole && crsArticole
	Do make_valute && crsValute

	Text To lcSchema Noshow
id N(10) null, intern N(1), ctr_id N(10), id_articol N(12), articol C(100), id_valuta N(7), lim1 N(12,2), lim2 N(12,2), um C(10), corect N(2), valoare N(20,4), plus N(1), arebaza N(1), baza N(1), modificat N(1)
	Endtext

	lcOrder = [intern desc, articol, lim1, lim2]
	lcFiltru = []
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Noshow
select id,
       intern,
       ctr_id,
       id_articol,
       articol,
       id_valuta,
       lim1,
       lim2,
       um,
       corect,
       valoare,
       plus,
       arebaza,
       baza,
       0 as modificat
  from ips_vtarife_cheiaj
	Endtext

	gencursor('poTarife', 'crsTarife', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poTarife.ca_baza1.afisare()
	Select crsTarife
	loFrmTarife = Createobject("frm_tarife_cheiaj") && oacnpro.vcx
	loFrmTarife.Show(1)

	If m.gnButon = 1
		lcSqlDelete = [DELETE from ips_tarife_cheiaj WHERE id = ?pnId]

		Text To lcSqlInsert Noshow
		insert into ips_tarife_cheiaj
  (id_articol, lim1, lim2, um, corect, valoare, ctr_id, intern, plus, arebaza, baza, id_valuta)
values
(?poRec.id_articol, ?poRec.lim1, ?poRec.lim2, ?poRec.um, ?poRec.corect, ?poRec.valoare, ?poRec.ctr_id, ?poRec.intern, ?poRec.plus, ?poRec.arebaza, ?poRec.baza, ?poRec.id_valuta)
		Endtext

		Text To lcSqlUpdate Noshow
update ips_tarife_cheiaj
   set id_articol = ?poRec.id_articol,
       lim1 = ?poRec.lim1,
       lim2 = ?poRec.lim2,
       um = ?poRec.um,
       corect = ?poRec.corect,
       valoare = ?poRec.valoare,
       ctr_id = ?poRec.ctr_id,
       intern = ?poRec.intern,
       plus = ?poRec.plus,
       arebaza = ?poRec.arebaza,
       baza = ?poRec.baza,
       id_valuta = ?poRec.id_valuta
 where id = ?poRec.id;
		Endtext

		Select crsTarife
		Set Filter To

		llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

		If m.llSucces && transactions
			*** SELECTEZ IREG STERSE
			Set Deleted Off
			Sele Id From crsTarife Where Deleted() Into Cursor cTarifeSterse
			Set Deleted On

			Select cTarifeSterse
			Scan
				pnId = Id
				llSucces = goExecutor.oExecuta(m.lcSqlDelete)
				If !m.llSucces
					Exit
				Endif
			Endscan
			Use In (Select('cTarifeSterse'))
			*** STERG IN TARIFE_DIVERSE IREG STERSE

			If m.llSucces
				*** MODIFIC IN TARIFE IREG MODIFICATE IN TEMPORAR
				Sele crsTarife
				Set Filter To
				Calculate Cnt() To m.lnModificat For Nvl(modificat, 0) = 1

				lnRec = 0
				Sele crsTarife
				Scan For Nvl(modificat, 0) = 1
					Scatter Name poRec Memo
					lnRec = m.lnRec + 1
					Wait Window 'Tarif nou/modificat ' + Alltrim(Str(m.lnRec)) + '/' + Alltrim(Str(m.lnModificat)) Nowait

					If Empty(Nvl(poRec.Id, 0))
						llSucces = goExecutor.oExecuta(m.lcSqlInsert)
					Else
						llSucces = goExecutor.oExecuta(m.lcSqlUpdate)
					Endif
					If !m.llSucces
						Exit
					Endif
				Endscan
			Endif && llSucces

			If !m.llSucces
				lcSql = "ROLLBACK"
				llScris = .F.
			Else
				lcSql = "COMMIT"
				llScris = .T.
			Endif
			llScris = goExecutor.oExecuta(m.lcSql)

			llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
			If !m.llSucces2
				amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
			Endif

			llSucces = m.llSucces And m.llScris
		Endif && gnButon

		If m.llSucces
			amessagebox('Tarife modificate cu succes!', 0 + 64, _Screen.Caption)
		Else
			amessagebox('Tarifele nu s-au modificat!', 0 + 64, _Screen.Caption)
		Endif
	Endif && gnButon

	Use In (Select('crsContracte'))
	Use In (Select('crsGrupeMarfa'))
	Use In (Select('crsMarfa'))
	Use In (Select('crsValute'))
	Use In (Select('crsVasUM'))
	Use In (Select('crsRoutes'))
	Use In (Select('crsGrupTipNave'))

	Return m.llSucces
Endproc && vizualizare_tarife_cheiaj

**************************************************************
*** vizualizare tarife contracte
**************************************************************
Procedure vizualizare_tarife_contracte

	Local loFrmTarife As "frm_tarife_contracte"
	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcSchema, lcSelect, llAfiseaza, llModParam
	Local lcSql, lcSqlDelete, lcSqlInsert, lcSqlUpdate, llScris, llSucces, llSucces2, lnModificat, lnRec
	Private poRec, poTarife, pnPretftva, pnPretctva
	poTarife = Null
	poRec = Null
	pnPretftva = 0
	pnPretctva = 0

	Do make_contracte && crsContracte
	Do make_locatii && crsLocatii
	Do make_articole && crsArticole
	Do make_valute && crsValute
	Do make_um && crsUM
	make_cote_tva() && crsCoteTVA

	Text To lcSchema Noshow
id_ctr_art N(7) null, id_ctr N(7) null, id_articol N(20) null, articol C(100) null, um C(10) null, pret_cu_tva N(1) null, proc_tvav N(10,2) null, pret_unitar N(20,4) null, cant N(12,4) null, valoare N(20,4) null, coef_discount N(12,4) null, val_discount N(20,4) null, id_valuta N(7) null, explicatie C(100) null, nume_val C(20) null, moneda_nationala N(1) null, id_locatia N(5), locatia C(100), modificat N(1)
	Endtext

	lcOrder = [articol]
	lcFiltru = []
	llAfiseaza = .F.
	lcGroup = []
	llModParam = .T.
	lcFiltruOriginal = []

	Text To lcSelect Noshow
select id_ctr_art,
       id_ctr,
       id_articol,
       articol,
       um,
       NVL(pret_cu_tva,0) AS pret_cu_tva,
       NVL(proc_tvav, -1) as proc_tvav,
       pret_unitar,
       cant,
       ROUND(valoare, ?gnPC) as valoare,
       coef_discount,
       val_discount,
       id_valuta,
       explicatie,
       valuta,
       moneda_nationala,
       id_locatia,
       locatia,
       0 as modificat
  from vctr_articole2
	Endtext

	gencursor('poTarife', 'crsTarife', m.lcSelect, m.lcFiltru, m.lcSchema, m.lcOrder, m.llAfiseaza, m.lcGroup, m.llModParam, m.lcFiltruOriginal)
	poTarife.ca_baza1.afisare()
	Select crsTarife
	loFrmTarife = Createobject("frm_tarife_contracte") && oacnpro.vcx
	loFrmTarife.Show(1)

	If m.gnButon = 1
		lcSqlDelete = [DELETE from ctr_articole WHERE id_ctr_art = ?pnIdCtrArt]

		Text To lcSqlInsert Noshow
		insert into ctr_articole
  (id_ctr, pret_unitar, cant, valoare, coef_discount, val_discount, id_valuta, explicatie, um, id_articol, pret_cu_tva, proc_tvav, id_locatia)
values
(?poRec.id_ctr, ?poRec.pret_unitar, ?poRec.cant, ?poRec.valoare, ?poRec.coef_discount, ?poRec.val_discount, ?poRec.id_valuta, ?poRec.explicatie, ?poRec.um, ?poRec.id_articol, ?poRec.pret_cu_tva, ?poRec.proc_tvav, ?poRec.id_locatia)
		Endtext

		Text To lcSqlUpdate Noshow
update ctr_articole
   set id_ctr_art = ?poRec.id_ctr_art,
       id_ctr = ?poRec.id_ctr,
       pret_unitar = ?poRec.pret_unitar,
       cant = ?poRec.cant,
       valoare = ?poRec.valoare,
       coef_discount = ?poRec.coef_discount,
       val_discount = ?poRec.val_discount,
       id_valuta = ?poRec.id_valuta,
       explicatie = ?poRec.explicatie,
       um = ?poRec.um,
       id_articol = ?poRec.id_articol,
       pret_cu_tva = ?poRec.pret_cu_tva,
       proc_tvav = ?poRec.proc_tvav,
       id_locatia = ?poRec.id_locatia
 where id_ctr_art = ?poRec.id_ctr_art
		Endtext

		Select crsTarife
		Set Filter To

		llSucces = (SQLSetprop(gnHandle, "Transactions", 2) >= 0)

		If m.llSucces && transactions
			*** SELECTEZ IREG STERSE
			Set Deleted Off
			Sele id_ctr_art From crsTarife Where Deleted() Into Cursor cTarifeSterse
			Set Deleted On

			Select cTarifeSterse
			Scan
				pnIdCtrArt = id_ctr_art
				llSucces = goExecutor.oExecuta(m.lcSqlDelete)
				If !m.llSucces
					Exit
				Endif
			Endscan
			Use In (Select('cTarifeSterse'))
			*** STERG IN TARIFE_DIVERSE IREG STERSE

			If m.llSucces
				*** MODIFIC IN TARIFE IREG MODIFICATE IN TEMPORAR
				Sele crsTarife
				Set Filter To
				Calculate Cnt() To m.lnModificat For Nvl(modificat, 0) = 1

				lnRec = 0
				Sele crsTarife
				Scan For Nvl(modificat, 0) = 1
					Scatter Name poRec Memo
					poRec.proc_tvav = Iif(poRec.proc_tvav = -1, Null, poRec.proc_tvav)
					poRec.pret_cu_tva = Nvl(poRec.pret_cu_tva, 0)

					lnRec = m.lnRec + 1
					Wait Window 'Tarif nou/modificat ' + Alltrim(Str(m.lnRec)) + '/' + Alltrim(Str(m.lnModificat)) Nowait

					If Empty(Nvl(poRec.id_ctr_art, 0))
						llSucces = goExecutor.oExecuta(m.lcSqlInsert)
					Else
						llSucces = goExecutor.oExecuta(m.lcSqlUpdate)
					Endif
					If !m.llSucces
						Exit
					Endif
				Endscan
			Endif && llSucces

			If !m.llSucces
				lcSql = "ROLLBACK"
				llScris = .F.
			Else
				lcSql = "COMMIT"
				llScris = .T.
			Endif
			llScris = goExecutor.oExecuta(m.lcSql)

			llSucces2 = (SQLSetprop(gnHandle, "Transactions", 1) >= 0)
			If !m.llSucces2
				amessagebox('Programul nu a reusit sa treaca pe tranzactie automata. Iesiti din program si intrati din nou!', 48, 'Atentie!')
			Endif

			llSucces = m.llSucces And m.llScris
		Endif && gnButon

		If m.llSucces
			amessagebox('Tarife modificate cu succes!', 0 + 64, _Screen.Caption)
		Else
			amessagebox('Tarifele nu s-au modificat!', 0 + 64, _Screen.Caption)
		Endif
	Endif && gnButon

	Use In (Select('crsTarife'))
	Use In (Select('crsContracte'))
	Use In (Select('crsArticole'))
	Use In (Select('crsLocatii'))
	Use In (Select('crsValute'))
	Use In (Select('crsUM'))
	Use In (Select('crsCoteTVA'))

	Return m.llSucces
Endproc && vizualizare_tarife_contracte

********************************************
*** Genereaza data act din luna contabila curenta 
********************************************
Function GenDataAct
	Local ldData, ldDataCurenta
	ldData = Gomonth(Date(m.gnAn, m.gnLuna, 1), 1) - 1 && ultima zi din luna contabila curenta
	ldDataCurenta = Date()
	If !(Year(m.ldDataCurenta) = Year(m.ldData) And Month(m.ldDataCurenta) = Month(m.ldData))
		m.ldDataCurenta = m.ldData
	Endif
	Return m.ldDataCurenta
Endfunc && GenDataAct

********************************************
*** Intoarce numarul tipului de prestatie din numele tipului
********************************************
Function cTip2nTip
	Lparameters tcTip
	Local lcTip, lnTip
	lcTip = Upper(Alltrim(tcTip))
	lnTip = NTIP_TRANZIT

	Do Case
		Case m.lcTip = TIP_TRANZIT
			lnTip = NTIP_TRANZIT
		Case m.lcTip = TIP_CHEIAJ
			lnTip = NTIP_CHEIAJ
		Case m.lcTip = TIP_APA
			lnTip = NTIP_APA
		Case m.lcTip = TIP_CHIRII
			lnTip = NTIP_CHIRII
		Case m.lcTip = TIP_PILOTAJ
			lnTip = NTIP_PILOTAJ
		Case m.lcTip = TIP_ALTE
			lnTip = NTIP_ALTE
		Case m.lcTip = TIP_PENALITATI
			lnTip = NTIP_PENALITATI
		Case m.lcTip = TIP_DIVERSE
			lnTip = NTIP_DIVERSE
	Endcase
	Return m.lnTip
Endfunc && cTip2nTip

********************************************************
*** listare recapitulatie cheiaj
*** se apeleaza din frm_facturi
********************************************************
Procedure listeaza_recapitulatie_cheiaj

	Private pnIdVanzare, pnTotalValoare, pnTotalValoareVal
	pnTotalValoare = 0
	pnTotalValoareVal = 0

	pnIdVanzare = poDate.nid_vanzare
	poLog.Log('id_vanzare=' + Alltrim(Str(Nvl(m.pnIdVanzare, 0))), 'listeaza_recapitulatie_cheiaj')
	* Selectez membri convoaielor

	Text To lcSelect Textmerge Noshow
select vye_id,
       vz_id,
       numar_act,
       data_act,
       client_id,
       client,
       contract_client,
       client_ctr_id,
       beneficiar_id,
       beneficiar,
       intern,
       document,
       declcdt,
       nava,
       tipn_id,
       tipn,
       lbd,
       trn,
       hp,
       cap,
       lung,
       id_locatia,
       locatia,
       id_dana,
       dana,
       datai,
       datap,
       nrore,
       id_valuta,
       valuta,
       id_articol,
       articol,
       tarif,
       cant,
       durata,
       um,
       valval,
       tvaval,
       totval,
       valftva,
       valtva,
       valctva,
       curs
  from ips_vberthing_members_vanzari
  where vz_id = ?pnIdVanzare
	Endtext

	llSucces = goExecutor.oExecuta(m.lcSelect, 'crsBerthingMembersVanzari')

	If !m.llSucces
		Return
	Endif

	Select vye_id, ;
		vz_id, ;
		numar_act As nrfact, ;
		data_act As datafact, ;
		client_id, ;
		client, ;
		contract_client, ;
		client_ctr_id, ;
		beneficiar_id, ;
		beneficiar, ;
		(Nvl(intern, 0) = 1) As intern, ;
		Document, ;
		DECLCDT, ;
		nava, ;
		tipn_id, ;
		tipn, ;
		lbd, ;
		trn, ;
		hp, ;
		cap, ;
		lung, ;
		id_locatia, ;
		locatia, ;
		id_dana, ;
		dana, ;
		datai, ;
		datap, ;
		nrore, ;
		id_valuta, ;
		valuta, ;
		id_articol, ;
		articol, ;
		tarif, ;
		cant, ;
		durata, ;
		um, ;
		valval, ;
		TVAVAL, ;
		totval, ;
		valftva, ;
		valtva, ;
		valctva, ;
		Curs ;
		From crsBerthingMembersVanzari  ;
		Order By DECLCDT, nava ;
		Into Cursor crsRecapitulatie
	Use In (Select('crsBerthingMembersVanzari'))

	Select crsRecapitulatie
	Go Top
	llIntern = intern
	* Total valoare
	Select Max(Curs) As Curs, Sum(valval) As valval From crsRecapitulatie Into Cursor crsTotalTemp
	Select crsTotalTemp
	Go Top
	pnTotalValoare = Iif(m.llIntern, Round(Round(crsTotalTemp.valval, m.gnPC) * crsTotalTemp.Curs, m.gnPC), Round(crsTotalTemp.valval, m.gnPC)) && intern lei, extern valuta
	pnTotalValoareVal = Round(crsTotalTemp.valval, m.gnPC)

	Use In (Select('crsTotalTemp'))

	Select crsRecapitulatie
	lcRaport = 'recapitulatie_cheiaj.frx'
	Do listeaza_recapitulatie With 'crsRecapitulatie', m.lcRaport In ofacturare.prg

	Use In (Select('crsRecapitulatie'))

Endproc && listeaza_recapitulatie_cheiaj

********************************************************
*** listare recapitulatie tranzit
*** se apeleaza din frm_facturi
********************************************************
Procedure listeaza_recapitulatie_tranzit

	Local lcFiltru, lcFiltruOriginal, lcGroup, lcOrder, lcRaport, lcSchema, lcSelect, llAfiseaza
	Local llModParam, llSucces
	Local lcModCalcul, lcVyeId
	Private pnIdVanzare, pnTotalValoare

	pnTotalValoare = 0
	pnIdVanzare = poDate.nid_vanzare
	poLog.Log('id_vanzare=' + Alltrim(Str(Nvl(m.pnIdVanzare, 0))), 'listeaza_recapitulatie_tranzit')
	* Selectez membri convoaielor
	Text To lcSelect Textmerge Noshow
select vmv_id,
       vv_id,
       client_id,
       client,
       contract_client,
       client_ctr_id,
       beneficiar_id,
       tiprecap,
       beneficiar,
       intern,
       vz_id,
       numar_act,
       data_act,
       cuplat,
       arm_id,
       armator,
       kmi,
       kmf,
       rte_id,
       ruta,
       convoy_nam,
       declaratio,
       generation,
       vye_id,
       aviz,
       data_aviz,
       origin,
       destinatio,
       vms_id,
       vsl_id,
       ctt_id,
       dirty_tank,
       rstart_id,
       rfin_id,
       distanta,
       distanta_cdmn,
       contact,
       indicativ,
       lbd,
       trn,
       hp,
       tcap,
       procdiv,
       vtp_id,
       tip_nava,
       vgrp_id,
       grupa_nava,
       felcargo,
       cargo,
       gds_id,
       grp_id,
       grupa_marfa,
       periculos,
       corect,
       procdist,
       id_valuta,
       valuta,
       tarif,
       cant,
       um,
       valval,
       tvaval,
       totval,
       valftva,
       valtva,
       valctva,
       curs
  from ips_vvoyage_members_vanzari
  where vz_id = ?pnIdVanzare
	Endtext
	*	  from ips_vvoyage_members_vanzari3 ia o singura inregistrare din ips_cargoes, ca sa nu faca full scan pe ips_cargoes, dar trebuie cumulata cantitatea de marfa!!!
	* trebuie sa salvez cargo in ips_voyage_members_vanzari

	llSucces = goExecutor.oExecuta(m.lcSelect, 'crsVoyageMembers')

	If !m.llSucces
		Return
	Endif

	* Selectez capacitatea totala a convoiului, nu numai a navelor de pe factura curenta.
	* Este posibil sa fac facturi catre clienti diferiti pe un singur convoi.
	* Este posibil sa stornez factura si apoi sa o refacturez cu barje cu TCAP corectat
	* Daca o barja apare cu mai multe TCAP, din mai multe facturi, iau TCAP de la aceeasi barja de pe factura curenta
	Text To lcSql Noshow
Select vye_id, Sum(tcap) As tcap
from (select distinct vye_id,
                vms_id,
                LAST_VALUE(tcap) OVER(PARTITION BY vms_id ORDER BY fact ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS tcap
  from (Select vmv.vye_id,
               vmv.vms_id,
               vmv.tcap,
               decode(vv.vz_id, ?pnIdVanzare, 1, 0) as fact
          From IPS_VOYAGE_MEMBERS_VANZARI vmv
          join IPS_VOYAGES_VANZARI vv
            On vmv.vv_id = vv.id
         where vmv.vye_id in (SELECT distinct vmv1.vye_id
                                FROM ips_voyage_members_vanzari vmv1
                                join ips_voyages_vanzari vv1
                                  on vmv1.vv_id = vv1.id
                               WHERE vv1.vz_id = ?pnIdVanzare)))
   GROUP By vye_id                               
	Endtext                               
	* Select vye_id, Sum(tcap) As tcap From crsVoyageMembers Group By vye_id Into Cursor cCapacitateTemp

	llSucces = goExecutor.oExecuta(m.lcSql, 'cCapacitateTemp')

	If !m.llSucces
		Use In (Select('crsVoyageMembers'))
		Return
	Endif

	Select vm.vye_id, ;
		vm.armator, ;
		vm.declaratio As DECLCDT, ;
		vm.origin, ;
		vm.destinatio, ;
		vm.aviz, ;
		vm.data_aviz, ;
		vm.convoy_nam As numeconvoi, ;
		vm.client, ;
		vm.contract_client, ;
		(Nvl(vm.intern, 1) = 1) As intern, ;
		vm.beneficiar, ;
		vm.numar_act As nrfact, ;
		vm.data_act As datafact, ;
		vm.vv_id, ;
		vm.vmv_id, ;
		vm.tiprecap, ;
		vm.cuplat, ;
		vm.kmi, ;
		vm.kmf, ;
		vm.rte_id, ;
		vm.ruta, ;
		vm.vms_id, ;
		vm.vsl_id, ;
		vm.ctt_id, ;
		vm.dirty_tank, ;
		vm.rstart_id, ;
		vm.rfin_id, ;
		vm.distanta, ;
		vm.distanta_cdmn, ;
		vm.contact, ;
		vm.indicativ, ;
		vm.lbd, ;
		vm.trn, ;
		vm.hp, ;
		vm.tcap, ;
		vm.procdiv, ;
		vm.VTP_ID, ;
		vm.tip_nava, ;
		vm.vgrp_id, ;
		vm.grupa_nava, ;
		vm.felcargo, ;
		vm.cargo, ;
		vm.gds_id, ;
		vm.GRP_ID, ;
		vm.grupa_marfa, ;
		vm.periculos, ;
		vm.corect, ;
		vm.procdist, ;
		vm.id_valuta, ;
		vm.valuta, ;
		vm.Curs, ;
		vm.tarif, ;
		vm.cant, ;
		vm.um, ;
		vm.valval, ;
		vm.TVAVAL, ;
		vm.totval, ;
		vm.valftva, ;
		vm.valtva, ;
		vm.valctva, ;
		Cast(Nvl(C.tcap, 0) As N(20, 2)) As convoi_t, ;
		Cast('' As M) As mod_calcul ;
		From crsVoyageMembers vm Join cCapacitateTemp C On vm.vye_id = C.vye_id ;
		Order By vm.declaratio, vm.indicativ ;
		Into Cursor crsRecapitulatie Readwrite

	Select crsRecapitulatie
	Go Top
	llIntern = intern
	* Total valoare
	Select Max(Curs) As Curs, Sum(valval) As valval From crsRecapitulatie Into Cursor crsTotalTemp
	Select crsTotalTemp
	Go Top
	pnTotalValoare = Iif(m.llIntern, Round(crsTotalTemp.valval * crsTotalTemp.Curs, m.gnPC), crsTotalTemp.valval) && intern lei, extern valuta

	Use In (Select('crsTotalTemp'))

	Select Distinct vye_id From crsRecapitulatie Into Cursor cModCalcul

	Select cModCalcul
	Scan
		lcVyeId = Alltrim(cModCalcul.vye_id)
		lcModCalcul = mod_calcul_tranzit('crsRecapitulatie', m.lcVyeId)
		Update crsRecapitulatie Set mod_calcul = m.lcModCalcul Where vye_id = m.lcVyeId
	Endscan

	Use In (Select('cModCalcul'))
	Use In (Select('crsVoyageMembers'))
	Use In (Select('cCapacitateTemp'))

	lcRaport = 'recapitulatie_tranzit.frx'
	Do listeaza_recapitulatie With 'crsRecapitulatie', m.lcRaport In ofacturare.prg

	Use In (Select('crsRecapitulatie'))
Endproc && listeaza_recapitulatie_tranzit

*******************************************
*** se apeleaza din recapitulatie_tranzit.frx
*** intorce text cu modul de calcul valoare tranzit
*******************************************
Procedure mod_calcul_tranzit
	Lparameters tcTabel, tcVyeId
	Local lcModCalcul, llIntern, lnCurs, lnOldDecimals, lcSelect
	Local lnValftva, lnValval, lcValuta
	lcSelect = Select()
	llIntern = .F.

	lcModCalcul = ;
		[TARIF * CANT * %DIST * (%COR + %SUPL) = TOTAL ] + Chr(13) + Chr(10)

	lnValval = 0
	lnValftva = 0
	lnOldDecimals = Set("Decimals")
	lcValuta = ''
	Set Decimals To 4
	Select vye_id, intern, indicativ, tarif, valuta, cant, um, procdist, corect, procdiv, valval, Curs, valftva From (m.tcTabel) Where vye_id = m.tcVyeId Order By indicativ Into Cursor cModCalculTemp
	Select cModCalculTemp
	Scan
		lcModCalcul = lcModCalcul + Alltrim(Transform(tarif, GET_MASK(10, 4))) + [ ] + Allt(valuta) + [ * ] + Allt(Str(cant, 8, 2)) + [ ] + Allt(um) + [ * ] + Allt(Str(procdist, 6, m.gnProcDistPrecizie)) + [ * ] + Allt(Str(corect + procdiv, 5, 3)) + [ = ] + Alltrim(Transform(valval, GET_MASK(16, 2))) + [ ] + Allt(valuta)
		llIntern = intern
		lnCurs = Curs
		If m.llIntern
			* nu mai adaug contravaloarea in lei pentru ca totalul nu este suma la valorile individuale in lei, ci este valoarea totala in valuta * curs
			*!*				lcModCalcul = lcModCalcul + " * " + Alltrim(Str(Curs, 10, gnPcurs)) + " LEI/" + Allt(valuta) + " = " + Alltrim(Transform(valftva, GET_MASK(12, gnPC))) + " LEI" 
		Endif
		lcModCalcul = lcModCalcul + Chr(13)
		lnValval = lnValval + valval
		lnValftva = lnValftva + valftva
		lcValuta = Alltrim(valuta)
	Endscan && cModCalculTemp
	Use In (Select('cModCalculTemp'))

	lnValftva = Round(m.lnValval * m.lnCurs, m.gnPC) && totalul in lei = total in valuta * curs, nu suma totalurilor in lei

	If m.llIntern
		lcModCalcul = lcModCalcul + [TOTAL ] + Alltrim(Transform(lnValval, GET_MASK(13, 2))) + [ ] + Allt(m.lcValuta) + IIF(inlist(UPPER(allt(nvl(m.lcValuta, 'LEI'))),  'LEI', 'RON'), " ", " * " + Alltrim(Str(lnCurs, 10, gnPcurs)) + " LEI/" + Allt(m.lcValuta) + " = " + Alltrim(Transform(lnValftva, GET_MASK(12, gnZ))) + " LEI")
	Else
		lcModCalcul = lcModCalcul + [TOTAL ] + Alltrim(Transform(lnValval, GET_MASK(14, 2))) + [ ] + Allt(m.lcValuta)
	Endif

	Set Decimals To (lnOldDecimals)
	Select (m.lcSelect)
	Return lcModCalcul

Endproc && mod_calcul_tranzit

*********************************************
** Listeaza recapitulatie penalitati apelata din frm_facturi sau din formularul de penalitati, caz in care exista cursorul recapitulatie
*********************************************
Procedure listeaza_recapitulatie_penalitati
	Lparameters tlEvaluare, tcTitlu
	* tlEvaluare (optional): Default .F., daca se listeaza recapitulatia fara factura, din formularul de calcul.
	* tcTitlu (optional), daca se listeaza recapitulatia fara factura, din formularul de calcul

	Private pnIdVanzare, pcTitlu, pnNrFactPenalitati, pdDataFactPenalitati, pnIdFact
	Local lcSelect

	lcSelect = Select()
	pnIdVanzare = 0
	pcTitlu = Iif(!Empty(m.tcTitlu), m.tcTitlu, '')
	pnNrFactPenalitati = 0
	pdDataFactPenalitati = {}
	pnIdFact = 0

	If !m.tlEvaluare
		pnIdVanzare = poDate.nid_vanzare

		poLog.Log('id_vanzare=' + Alltrim(Str(Nvl(m.pnIdVanzare, 0))), 'listeaza_recapitulatie_penalitati')

		lcSql = [select v.id_fact, v.numar_act, v.data_act, p.denumire from vanzari v join nom_parteneri p on v.id_part = p.id_part WHERE v.id_vanzare = ?pnIdVanzare]
		llSucces = goExecutor.oExecuta(m.lcSql, 'cFacturaRTemp')
		If m.llSucces
			Select cFacturaRTemp
			Go Top
			pnIdFact = id_fact
			pnNrFactPenalitati = cFacturaRTemp.numar_act
			pdDataFactPenalitati = Ttod(cFacturaRTemp.data_act)
			pcTitlu = 'Situatia calculului penalitatilor de intarziere la ' + Alltrim(Transform(pdDataFactPenalitati)) + Chr(13) + Chr(10) + ' pentru ' + Alltrim(cFacturaRTemp.denumire)
		Endif  && llSucces
		Use In (Select('cFacturaRTemp'))

		Text To lcSql Noshow
	select id,
	       id_ctr,
	       contract,
	       id_part,
	       denumire as nume,
	       cod_fiscal,
	       nrfact,
	       datafact,
	       valctva,
	       nract,
	       dataact,
	       suma,
	       databaza,
	       dataref,
	       coef_penalitati as ppenzi,
	       coef_penalitati2 as ppenzi2,
	       nr_zile,
	       nr_zile1,
	       nr_zile2,
	       nr_zile_gratie,
	       penalitati,
	       datascad
	       from vpenalitati
	       where id_fact_pen = ?pnIdFact
		Endtext

		llSucces = goExecutor.oExecuta(m.lcSql, 'crsRecapitulatie')
	Endif


	If Used('crsRecapitulatie')
		Select crsRecapitulatie
		lcRaport = 'recapitulatie_penalitati.frx'
		Do listeaza_recapitulatie With 'crsRecapitulatie', m.lcRaport In ofacturare.prg
		Use In (Select('crsRecapitulatie'))
	Endif
	Select (m.lcSelect)
Endproc && listeaza_recapitulatie_penalitati

Procedure listeaza_recapitulatie_alte

	Private pnIdVanzare, pcValoareValute, pcCursValute
	pcValoareValute = ''
	pcCursValute = ''

	pnIdVanzare = poDate.nid_vanzare
	poLog.Log('id_vanzare=' + Alltrim(Str(Nvl(m.pnIdVanzare, 0))), 'listeaza_recapitulatie_alte')

	Text To lcSelect Textmerge Noshow
select id,
       id_vanzare,
       tip,
       id_articol,
       articol,
       id_locatia,
       locatia,
       id_valuta,
       valuta,
       moneda_nationala,
       id_client,
       client,
       id_contract,
       contract as contract_client,
       pret as tarif,
       curs,
       cantitate,
       valval,
       valftva,
       um,
       document,
       data,
       perioada,
       numar_act as nrfact,
       data_act as datafact,
       ctdebitor,
       ctaideb,
       ctaedeb,
       ctcreditor,
       ctaicred,
       ctaecred
  from ips_vregdoc
  where id_vanzare = ?pnIdVanzare
  order by id
	Endtext

	llSucces = goExecutor.oExecuta(m.lcSelect, 'crsRecapitulatie')

	If !m.llSucces
		Return
	Endif

	* pcValoareValute - il scriu la total in raport
	Select valuta, moneda_nationala, Curs, Sum(valval) As valval From crsRecapitulatie Group By valuta, Curs, moneda_nationala Order By moneda_nationala Desc, valuta Into Cursor cTotalTemp

	* daca nu are alte valute decat lei, nu il mai scriu
	Select cTotalTemp
	Locate For moneda_nationala = 0
	If Found()
		Scan
			pcValoareValute = pcValoareValute + ', ' + Alltrim(Str(valval, 16, m.gnPC)) + ' ' + Alltrim(valuta)
			If moneda_nationala = 0
				pcCursValute = pcCursValute + ', ' + Alltrim(Str(Curs, 12, m.gnPcurs)) + " LEI/" + Alltrim(valuta)
			Endif
		Endscan
		If !Empty(m.pcValoareValute)
			pcValoareValute = Alltrim(Substr(m.pcValoareValute, 2))
			pcCursValute = Alltrim(Substr(m.pcCursValute, 2))
		Endif
	Endif
	Use In (Select('cTotalTemp'))

	Select crsRecapitulatie
	lcRaport = 'recapitulatie_alte.frx'
	Do listeaza_recapitulatie With 'crsRecapitulatie', m.lcRaport In ofacturare.prg

	Use In (Select('crsRecapitulatie'))
Endproc && listeaza_recapitulatie_alte


*-------------------------------------
* meniu suplimentar pentru butonul Borderou din frm_facturi
Procedure meniu_borderou_plus
	Lparameters tcListaMeniu, tcListaProceduri
	* tcListaMeniu: titlurile optiunilor din meniu separate prin |
	* tcListaProceduri: numele procedurilor corespunzatoare optiunilor din meniu separate prin |
	* Procedurile primesc ca parametru tcVanzareIds (lista id_vanzare) si intorc llSucces
	Local lnNumarOptiuni
	lnNumarOptiuni = 1
	tcListaMeniu = 'Copiere declaratii comandant si istorice cheiaj in directorul cu facturi'
	tcListaProceduri = 'CopyDeclCdtPdf'

	Return lnNumarOptiuni
Endproc && meniu_borderou_plus

*-------------------------------------
* Copie (muta) declaratii comandant si istoricele de cheiaj pdf in directorul facturi pdf si redenumeste declaratiile cu data_nr_factura_declaratie.pdf
* Nu suprascrie
* Pentru a fi atasate la emailul cu borderou facturi
Procedure CopyDeclCdtPdf
	Lparameters tcVanzareIds
	* tcVanzareIds: lista id_vanzare facturi

	Local lcDeclPath, lcDeclaratie, lcDeclaratiiCopiate, lcDeclaratiiNecopiate, lcDeclaratiiNuExista, lcDeclaratiiExistaDeja
	Local lcDestinationFile, lcFacturaPath, lcFacturaPdf, lcSourceFile, lcSql, lcSufixDecl
	Local ldDataFactura, llSucces, lnNumarFactura, lnPos, lcCursor, lcSelect
	lcSelect = Select()
	lcDeclaratiiCopiate = ''
	lcDeclaratiiNecopiate = ''
	lcDeclaratiiNuExista = ''
	lcDeclaratiiExistaDeja = ''

	llSucces = .T.
	lcSufixDecl = 'DEC'

	lcDeclPath = GetDocumentPath('declcdt') && [pdf_declcdt_acn]
	lcFacturaPath = GetDocumentPath('factura') && [pdf_factura_acn]

	If Empty(m.lcDeclPath) Or !Directory(m.lcDeclPath)
		amessagebox('Directorul declaratii/istorice: ' + m.lcDeclPath + ' nu exista!')
		llSucces = .F.
	Endif
	If Empty(m.lcFacturaPath) Or !Directory(m.lcFacturaPath)
		amessagebox('Directorul facturi: ' + m.lcFacturaPath + ' nu exista!')
		llSucces = .F.
	Endif

	If Empty(m.tcVanzareIds)
		amessagebox('Selectati facturile de tranzit/cheiaj pentru care doriti sa copiati declaratiile/istoricele!', 0 + 48, _Screen.Caption)
		Return m.llSucces
	Endif

	* Selectez facturi, declaratii pentru tip_factura 0 = tranzit, , document stationare pentru tip_factura 1 = cheiaj
	Text To lcSql Textmerge Noshow
SELECT V.DATA_ACT, V.NUMAR_ACT, VYE.DECLARATIO AS DECLCDT, V.TIP_FACTURA, VV.DOCUMENT as ISTORIC, COUNT(*) OVER (PARTITION BY V.TIP_FACTURA, VYE.DECLARATIO) AS NR
	FROM VANZARI V JOIN IPS_VOYAGES_VANZARI VV ON V.ID_VANZARE = VV.VZ_ID JOIN IPS_VOYAGES VYE ON VV.VYE_ID = VYE.ID 
	WHERE V.ID_VANZARE IN (<<m.tcVanzareIds>>) AND V.TIP_FACTURA IN (0,1)
	ORDER BY V.DATA_ACT, V.NUMAR_ACT
	Endtext
	lcCursor = Sys(2015)

	If m.llSucces
		llSucces = goExecutor.oExecuta(m.lcSql, m.lcCursor)
	Endif && llSucces

	If m.llSucces
		If Reccount(m.lcCursor) = 0
			amessagebox('Nu exista rezultate. Alegeti facturi de tranzit!', 0 + 48, _Screen.Caption)
			llSucces = .F.
		Endif
	Endif

	If m.llSucces
		* O declaratie poate aparea pe mai multe facturi
		* Sterg declaratia pdf doar dupa ce am copiat declaratia pentru toate facturile
		Select Distinct Upper(DECLCDT) As DECLCDT, nr From (m.lcCursor) Into Cursor cDeclTemp Readwrite
		Select cDeclTemp
		Index On DECLCDT Tag DECLCDT

		Select Distinct Upper(istoric) As istoric, nr From (m.lcCursor) Into Cursor cIstoricTemp Readwrite
		Select cIstoricTemp
		Index On istoric Tag istoric

		* Scanez cursorul cu facturi si copiez fiecare declaratie din directorul declaratii in directorul facturi cu redenumirea declaratiei
		Select (m.lcCursor)
		Scan
			ldDataFactura = Ttod(data_act)
			lnNumarFactura = numar_act
			lcDeclaratie = Upper(Alltrim(DECLCDT)) && 20A0041
			lcIstoric = Upper(Alltrim(istoric))
			lnTipFactura = tip_factura

			lcFacturaPdf = GetPDFFacturaFile(m.ldDataFactura, m.lnNumarFactura) && 20200410_123456_factura.pdf
			lnPos = At('_', Juststem(m.lcFacturaPdf), 2) && caut a doua aparitie a '_' din 20200410_123456_factura
			If m.lnTipFactura = 0
				lcDestinationFileName = Left(Juststem(m.lcFacturaPdf), m.lnPos) + 'dec_' + m.lcDeclaratie + '.pdf' && 20200410_123456_dec_20A0041.pdf
				lcSourceFile = Addbs(m.lcDeclPath) + m.lcDeclaratie + '.pdf' && 20A0041.pdf
			Else
				lcDestinationFileName = Left(Juststem(m.lcFacturaPdf), m.lnPos) + 'ist_' + m.lcIstoric + '.pdf' && 20200410_123456_ist_20M271.pdf
				lcSourceFile = Addbs(m.lcDeclPath) + m.lcIstoric + '.pdf' && 20M271.pdf
			Endif

			lcDestinationFile = Addbs(m.lcFacturaPath) + m.lcDestinationFileName

			If goApp.FileExist(m.lcSourceFile)
				llCopie = .T.
				If goApp.FileExist(m.lcDestinationFile)
					llCopie = (amessagebox('Exista fisierul ' + m.lcDestinationFile + Chr(13) + 'Doriti sa il suprascrieti?', 4 + 32, _Screen.Caption) = 6)
				Endif
				If m.llCopie
					llSucces = goApp.CopyFile(m.lcSourceFile, m.lcDestinationFile) && override
				Else
					llSucces = .T.
				Endif
				If m.llSucces
					If m.lnTipFactura = 0
						* Sterg declaratia pdf daca a fost ultima aparitie a declaratiei pe o factura
						Select cDeclTemp
						If Seek(m.lcDeclaratie)
							Replace nr With nr - 1
							If nr = 0
								llSucces = goApp.DeleteFile(m.lcSourceFile)
							Endif
						Endif
					Else
						* Sterg istoric pdf daca a fost ultima aparitie a declaratiei pe o factura
						Select cIstoricTemp
						If Seek(m.lcIstoric)
							Replace nr With nr - 1
							If nr = 0
								llSucces = goApp.DeleteFile(m.lcSourceFile)
							Endif
						Endif
					Endif

					lcDeclaratiiCopiate = lcDeclaratiiCopiate + Justfname(m.lcSourceFile) + ' - ' + Justfname(m.lcDestinationFile) + Chr(13) + Chr(10)
				Else
					lcDeclaratiiNecopiate = lcDeclaratiiNecopiate + Justfname(m.lcSourceFile) + Chr(13) + Chr(10)
				Endif
			Else
				* Daca nu exista deja in destinatie de la o copiere anterioara declar declaratia ca nu exista
				If goApp.FileExist(m.lcDestinationFile)
					lcDeclaratiiExistaDeja = m.lcDeclaratiiExistaDeja + Justfname(m.lcDestinationFile) + Chr(13) + Chr(10)
				Else
					lcDeclaratiiNuExista = m.lcDeclaratiiNuExista + Justfname(m.lcSourceFile) + Chr(13) + Chr(10)
				Endif
			Endif
		Endscan && lcCursor
		Use In (Select(m.lcCursor))
		Use In (Select('cDeclTemp'))
		Use In (Select('cIstoricTemp'))
	Endif && llSucces

	amessagebox('Declaratii/istorice copiate din ' + m.lcDeclPath + ' in ' + m.lcFacturaPath + ':' + Chr(13) + Chr(10) + m.lcDeclaratiiCopiate + Chr(13) + Chr(10) + Chr(13) + Chr(10) + ;
		  'Declaratii/istorice necopiate (eroare) din ' + m.lcDeclPath + ' in ' + m.lcFacturaPath + ':' + Chr(13) + Chr(10) + m.lcDeclaratiiNecopiate + Chr(13) + Chr(10) + Chr(13) + Chr(10) + ;
		  'Declaratii/istorice care nu exista in ' + m.lcDeclPath + ':' + Chr(13) + Chr(10) + m.lcDeclaratiiNuExista + Chr(13) + Chr(10) + Chr(13) + Chr(10) + ;
		  'Declaratii/istorice existente deja in ' + m.lcFacturaPath + ':' + Chr(13) + Chr(10) + m.lcDeclaratiiExistaDeja, 0 + 64, _Screen.Caption)

	Select (m.lcSelect)

	llSucces = Empty(m.lcDeclaratiiNecopiate)
	Return m.llSucces
Endproc && CopyDeclCdtPdf 