* test_echivalenta_cache_rtvai.prg - S13, Testul 1 EXTINS: echivalenta cache vs ANAF cu RTVAI
* ca al treilea termen de comparatie (docs\stories-cache-anaf.md sectiunea S13, extindere ceruta
* in handoff_cache_anaf.md - "ANAF nu da istoricul complet").
*
* PROBLEMA cu testul simplu cache-vs-ANAF (deja facut de S6, 200 coduri sintetice, 0 diferente):
* daca ANAF si cache-ul stiu AMANDOI o singura perioada (ANAF nu intoarce istoricul complet -
* verificat direct pe serviciu: CUI 16548698 da 2015-05-27->2024-11-01, rtvai_istoric are 9
* perioade din 2013), cei doi termeni sunt de acord CHIAR SI CAND raspunsul e gresit pentru o
* data din trecut. Testul simplu nu ar prinde asta niciodata.
*
* SOLUTIE: pe 8 CUI REALE (companii reale, alese din rtvai_istoric pe MARIUSM_AUTO/CONTAFIN_ORACLE,
* 7-9 perioade fiecare - interogare si tabel complet in docs\diff-S13-teste-echivalenta.md), pentru
* fiecare cod:
*   - seed ISTORIC_CODURI_FISCALE cu O SINGURA perioada (cea mai recenta din rtvai_istoric - proxy
*     pentru "ce ar spune ANAF azi", documentat/asumat explicit, vezi diff) - asta e SIMULTAN
*     termenul (a) cache SI baza termenului (b) ANAF (vezi mai jos)
*   - termen (a) CACHE: CitesteIstoricPentruCoduri REALA (validare.prg, cu garda S6) la o data
*     VECHE, dinaintea perioadei seedate
*   - termen (b) ANAF: simplul test de interval [pLatStart,pLatEnd] - ACELASI interval cu care a
*     fost seedat cache-ul (nu exista alt canal ANAF disponibil headless) - reprezinta explicit
*     ce ar raspunde cache-ul DACA garda S6 nu ar exista (formula v_tvainc e identica)
*   - termen (c) RTVAI: pack_roartvai.PartenerInRTVAI, PROCEDURA REALA neschimbata (S2 nu a
*     atins-o inca), citeste rtvai_istoric COMPLET (toate perioadele)
* Plus control: aceeasi comparatie la o data DIN INTERIORUL perioadei seedate - toti 3 termenii
* trebuie sa fie de acord (garda nu trebuie sa strice calea normala).
*
* PASS per cod: la data veche, (a) abtine (nu returneaza rand - garda S6 functioneaza), (b) = 0
* (ANAF/cache-fara-garda ar fi spus gresit "nu"), (c) = 1 (RTVAI, ground truth, spune "da") -
* garda impiedica exact propagarea verdictului gresit pe care (b) l-ar fi dat. La data control,
* (a)=(b)=(c)=1.
*
* Fara CREATEOBJECT/ADDPROPERTY in interiorul unei PROCEDURE (capcana l, depanare_testare_vfp.md) -
* obiectele se construiesc INLINE in programul principal.

SET SAFETY OFF
SET TALK OFF
SET DELETED ON
SET EXACT ON
SET CENTURY ON
SET DATE DMY
SET NULLDISPLAY TO ''
CLOSE DATABASES

PUBLIC gcTestLog, gnTestOk, gnTestTotal
gcTestLog = "D:\ROA\ROACONT\COMUN\utile\Teste\cache_anaf\test_echivalenta_cache_rtvai_log.txt"
gnTestOk = 0
gnTestTotal = 0
STRTOFILE("START " + TTOC(DATETIME()) + CHR(13)+CHR(10), gcTestLog)

ON ERROR DO VpaErrRTVAI WITH ERROR(), MESSAGE(), PROGRAM(), LINENO()
ON SHUTDOWN QUIT

DO D:\ROA\ROACONT\COMUN\utile\Teste\test_init_env_auto.prg WITH 'CENTRAL', 'MARIUSM_AUTO', 'ROMFASTSOFT'
IF gnHandle <= 0
	DO WriteTestLogRTVAI WITH 'EROARE: conectare Oracle esuata - GATA'
	QUIT
ENDIF
DO WriteTestLogRTVAI WITH 'mediu OK, schema=' + gcS

*!* 01.08.2026 marius.mutu: watermark pe ID, inainte de orice scriere - garda pt DELETE-ul din CurataIstoricRTVAITest
PUBLIC gnIdMaxIstoricRTVAI
gnIdMaxIstoricRTVAI = 0
IF goExecutor.oExecuta('SELECT NVL(MAX(ID),0) AS IDMAX FROM ISTORIC_CODURI_FISCALE', 'crsWmIstoricRTVAI')
	SELECT crsWmIstoricRTVAI
	GO TOP
	gnIdMaxIstoricRTVAI = IDMAX
	USE IN (SELECT('crsWmIstoricRTVAI'))
ENDIF
*!* 01.08.2026 marius.mutu: watermark invalid = SELECT esuat - avertisment explicit, stergerile se vor sari
IF gnIdMaxIstoricRTVAI <= 0
	DO WriteTestLogRTVAI WITH 'ATENTIE: watermark invalid (0) - stergerile din ISTORIC_CODURI_FISCALE vor fi SARITE'
ENDIF
DO WriteTestLogRTVAI WITH 'watermark ISTORIC_CODURI_FISCALE id_max=' + TRANSFORM(gnIdMaxIstoricRTVAI)

DO CurataIstoricRTVAITest

PUBLIC goVerifRTVAI
goVerifRTVAI = CREATEOBJECT('VerificareANAF')

* -- 8 CUI REALE, alese din rtvai_istoric (interogare + tabel complet de perioade in diff) --
* cui, pLatStart/pLatEnd = perioada cea mai recenta cunoscuta (proxy ANAF), dOld = in perioada
* VECHE (inainte de pLatStart), dCtrl = in interiorul perioadei recente (control)
IF USED('crsCoduriTest')
	USE IN crsCoduriTest
ENDIF
CREATE CURSOR crsCoduriTest (cui N(10), pLatStart D, pLatEnd D, dOld D, dCtrl D)
INSERT INTO crsCoduriTest VALUES (8060237,  {^2018-06-14}, {^2020-04-30}, {^2013-03-01}, {^2019-01-01})
INSERT INTO crsCoduriTest VALUES (16548698, {^2015-05-27}, {^2024-11-01}, {^2013-06-01}, {^2016-01-01})
INSERT INTO crsCoduriTest VALUES (17254755, {^2013-12-12}, {^2019-07-07}, {^2013-04-01}, {^2015-01-01})
INSERT INTO crsCoduriTest VALUES (18010589, {^2018-10-31}, {^2019-07-31}, {^2013-04-01}, {^2019-02-01})
INSERT INTO crsCoduriTest VALUES (21438829, {^2019-04-01}, {^2020-01-31}, {^2013-06-01}, {^2019-08-01})
INSERT INTO crsCoduriTest VALUES (28333609, {^2020-04-01}, {^2020-07-31}, {^2013-04-01}, {^2020-06-01})
INSERT INTO crsCoduriTest VALUES (28493170, {^2019-06-19}, {^2019-12-31}, {^2013-04-01}, {^2019-09-01})
INSERT INTO crsCoduriTest VALUES (30719386, {^2016-05-25}, {^2018-02-28}, {^2014-01-01}, {^2017-01-01})

LOCAL lnCui, ldLatStart, ldLatEnd, ldOld, ldCtrl
LOCAL llAAbstineOld, lnAOld, lnBOld, lnCOld, lnACtrl, lnBCtrl, lnCCtrl, llOk
LOCAL lnAllOk, lnTotal
lnAllOk = 0
lnTotal = 0

SELECT crsCoduriTest
SCAN
	lnCui = cui
	ldLatStart = pLatStart
	ldLatEnd = pLatEnd
	ldOld = dOld
	ldCtrl = dCtrl

	* -- seed cache cu perioada "cunoscuta de ANAF" (aceeasi forma ca crsANAF din ParseJsonANAFv8) --
	IF USED('crsSeedANAF')
		USE IN crsSeedANAF
	ENDIF
	CREATE CURSOR crsSeedANAF (cui N(13), data D, denumire V(100), firma V(100), adresa C(244), nrRegCom C(30), ;
		scpTVA L, data_inceput_ScpTVA D, data_sfarsit_ScpTVA D, data_anul_imp_ScpTVA D, mesaj_ScpTVA C(244), ;
		dataInceputTvaInc D, dataSfarsitTvaInc D, dataActualizareTvaInc D, dataPublicareTvaInc D, tipActTvaInc C(100), statusTvaIncasare L, ;
		dataInactivare D, dataReactivare D, dataPublicare D, dataRadiere D, statusInactivi L, ;
		dataInceputSplitTVA D, dataAnulareSplitTVA D, tva L, tvaincasare L, splittva L, inactiv L, ;
		mesaj V(100), judet V(100), strada V(100), nr V(20), localitate V(100), Bloc V(20), scara V(20), etaj V(20), apart V(20), ;
		sursa C(20), data_sursa D)
	INSERT INTO crsSeedANAF (cui, data, dataInceputTvaInc, dataSfarsitTvaInc, tvaincasare) ;
		VALUES (lnCui, DATE(), ldLatStart, ldLatEnd, .T.)

	goVerifRTVAI.SalveazaIstoricDinCursor('crsSeedANAF', gnIdUtil)
	USE IN crsSeedANAF

	* -- termen (a): cache REAL (cu garda S6), la data VECHE - asteptat: abtinere (niciun rand) --
	IF USED('crsCacheOld')
		USE IN crsCacheOld
	ENDIF
	goVerifRTVAI.CitesteIstoricPentruCoduri(TRANSFORM(lnCui), ldOld, 'crsCacheOld')
	llAAbstineOld = .T.
	lnAOld = -1
	IF USED('crsCacheOld')
		SELECT crsCacheOld
		LOCATE FOR cui = lnCui
		IF FOUND()
			llAAbstineOld = .F.
			lnAOld = IIF(tvaincasare, 1, 0)
		ENDIF
	ENDIF

	* -- termen (b): ANAF - acelasi interval unic folosit la seed (nu exista alt canal ANAF headless) --
	lnBOld = IIF(BETWEEN(ldOld, ldLatStart, ldLatEnd), 1, 0)

	* -- termen (c): RTVAI - procedura REALA neschimbata, citeste rtvai_istoric complet --
	lnCOld = ObtineVerdictRTVAI(lnCui, ldOld)

	* -- control: data in interiorul perioadei cunoscute - toti 3 termenii trebuie sa fie de acord --
	IF USED('crsCacheCtrl')
		USE IN crsCacheCtrl
	ENDIF
	goVerifRTVAI.CitesteIstoricPentruCoduri(TRANSFORM(lnCui), ldCtrl, 'crsCacheCtrl')
	lnACtrl = -1
	IF USED('crsCacheCtrl')
		SELECT crsCacheCtrl
		LOCATE FOR cui = lnCui
		IF FOUND()
			lnACtrl = IIF(tvaincasare, 1, 0)
		ENDIF
	ENDIF
	lnBCtrl = IIF(BETWEEN(ldCtrl, ldLatStart, ldLatEnd), 1, 0)
	lnCCtrl = ObtineVerdictRTVAI(lnCui, ldCtrl)

	lnTotal = lnTotal + 1
	llOk = (lnCOld = 1) AND llAAbstineOld AND (lnBOld = 0) AND ;
		(lnCCtrl = 1) AND (lnACtrl = 1) AND (lnBCtrl = 1)
	IF llOk
		lnAllOk = lnAllOk + 1
	ENDIF

	DO WriteTestLogRTVAI WITH 'cui=' + TRANSFORM(lnCui) + ;
		' | dOld=' + DTOC(ldOld) + ' a(abstine)=' + TRANSFORM(llAAbstineOld) + ' a(val)=' + TRANSFORM(lnAOld) + ' b=' + TRANSFORM(lnBOld) + ' c=' + TRANSFORM(lnCOld) + ;
		' | dCtrl=' + DTOC(ldCtrl) + ' a=' + TRANSFORM(lnACtrl) + ' b=' + TRANSFORM(lnBCtrl) + ' c=' + TRANSFORM(lnCCtrl) + ;
		' -> ' + IIF(llOk, 'PASS', 'FAIL')

	IF USED('crsCacheOld')
		USE IN crsCacheOld
	ENDIF
	IF USED('crsCacheCtrl')
		USE IN crsCacheCtrl
	ENDIF
	SELECT crsCoduriTest
ENDSCAN

DO WriteTestLogRTVAI WITH 'REZULTAT criteriul-8-extins-RTVAI: ' + TRANSFORM(lnAllOk) + '/' + TRANSFORM(lnTotal) + ' coduri PASS'

DO CurataIstoricRTVAITest

QUIT

*-- verdict "TVA la incasare la data D" din rtvai_istoric COMPLET (istoricul importat, nu ANAF),
*-- prin procedura Oracle REALA pack_roartvai.PartenerInRTVAI (neschimbata de S2 inca) --
PROCEDURE ObtineVerdictRTVAI
	LPARAMETERS tnCui, tdData
	PRIVATE pnCodFiscal, pdData, pcDenumire, pnRTVAI
	pnCodFiscal = tnCui
	pdData = tdData
	pcDenumire = ''
	pnRTVAI = 0
	LOCAL lcSql
	lcSql = [begin pack_roartvai.PartenerInRTVAI(?pnCodFiscal, ?pdData, ?@pcDenumire, ?@pnRTVAI); end;]
	IF !goExecutor.oExecuta(lcSql)
		RETURN -1
	ENDIF
	RETURN pnRTVAI
ENDPROC

PROCEDURE WriteTestLogRTVAI
	LPARAMETERS tcMesaj
	STRTOFILE(TTOC(DATETIME()) + ' ' + tcMesaj + CHR(13)+CHR(10), gcTestLog, 1)
ENDPROC

PROCEDURE VpaErrRTVAI
	LPARAMETERS tnErr, tcMsg, tcProg, tnLine
	DO WriteTestLogRTVAI WITH 'ON ERROR nEroare=' + TRANSFORM(tnErr) + ' mesaj=' + tcMsg + ' program=' + tcProg + ' linia=' + TRANSFORM(tnLine)
ENDPROC

*-- sterge DOAR cele 8 CUI reale folosite de acest test din ISTORIC_CODURI_FISCALE --
PROCEDURE CurataIstoricRTVAITest
	LOCAL lnSterse
	*!* 01.08.2026 marius.mutu: watermark invalid - nu sterg nimic (fara el, DELETE ar lovi tot istoricul comun)
	IF TYPE('gnIdMaxIstoricRTVAI') <> 'N' OR gnIdMaxIstoricRTVAI <= 0
		DO WriteTestLogRTVAI WITH 'CurataIstoricRTVAITest: SARIT - watermark invalid, nu sterg nimic'
		RETURN
	ENDIF
	*!* 01.08.2026 marius.mutu: garda pe ID > watermark (nu SCHEMA_SURSA - stergea randuri de referinta proprii)
	lnSterse = goExecutor.oExecuta([DELETE FROM ISTORIC_CODURI_FISCALE WHERE ID > ] + TRANSFORM(gnIdMaxIstoricRTVAI) + [ AND COD_FISCAL_N IN ] + ;
		[(8060237,16548698,17254755,18010589,21438829,28333609,28493170,30719386)])
	=goExecutor.oExecuta('COMMIT')
	DO WriteTestLogRTVAI WITH 'CurataIstoricRTVAITest: sters=' + TRANSFORM(lnSterse)
ENDPROC
