//Faza 1: hMARFA 8.8D1 - Upgrade evidenta TVA in 2017 -modif.hMARFA

NewMsg()

// -------------------------------------------------------------------------
h_OpenOut(slogf,.T.)
// h_PutLine("Upgrade de la 01.10.2016")
// h_PutLine("Societatea:   " + x_SocData ())
// h_PutLine("Baza de date: " + sDBName)
// h_PutLine("Versiunea:    HMARFA: " +sVM+ "  HMARFT: "+sVt)
// h_PutLine("---------------------------------------------------------------------------------")
// h_PutLine("")
    
// -------------------------------------------------------------------------

// Modificari V 8.8C3
// -------------------
#IF sVM = "V 8.8C1"
    // -------------------------------------------------
    //Comenzi generale hMARFA
    PutMsg("MOD:gcmd-M")
    #IF !h_UseAlias("gcmd")
        h_PutLine("*** Eroare deschidere fisier Comenzi generale")
        Abandon("C")
    #ENDIF
    
    // modificare DFAC_1 -incrementare nr.doc
    __dbLocate( {|| gcmd->COD="DFAC_1"},,,, .F. )
    #IF Found()
        xx_pp := NIL
        xx_ll := NIL 
        xx_scnt1 := '#IF !("V"$fac->STARE)'                               +Chr(13)+Chr(10)+ ;
                    '    pac_writefld("PAC_ERRMSG","Validare nereusita")' +Chr(13)+Chr(10)+ ;
                    '    Abandon(,"R")'                                   +Chr(13)+Chr(10)+ ;
                    '#ENDIF'
        xx_scnt1 := StrTran(xx_scnt1, " ", "")
        // varianta corecta    
        xx_scnt2 := StrTran(xx_scnt1,'"R"','"A"')
        #IF (h_AtB(xx_scnt2,gcmd->CMD,@xx_pp,@xx_ll) > 0)
        // OK, nu se face nimic
        #ELSEIF (h_AtB(xx_scnt1,gcmd->CMD,@xx_pp,@xx_ll) > 0)
            StrTran(SubStr(gcmd->CMD,xx_pp,xx_ll),'"R"','"A"')
            gcmd->CMD := Left(gcmd->CMD, xx_pp-1)+                           ;
                         StrTran(SubStr(gcmd->CMD,xx_pp,xx_ll),'"R"','"A"')+ ;
                         SubStr(gcmd->CMD,xx_pp+xx_ll)
            h_PutLine('    Modificat apelul Abandon(,"R") -->  Abandon(,"A") in sectiunea DOC_SFIRSIT din comanda generala DFAC_1')             
        #ELSE
            h_PutLine("*   Verificati algoritmul de validare bon fiscal in sectiunea DOC_SFIRSIT din comanda generala DFAC_1")
        #ENDIF
    #ELSE
        h_PutLIne("**  DFAC_1 -comanda generala nedefinita. Verificati!")
    #ENDIF
    
    // modificare M_BON -verificare Partener
    __dbLocate( {|| gcmd->COD="M_BON "},,,, .F. )
    #IF Found()
        xx_pp := NIL
        xx_ll := NIL 
        xx_scnt1 := '#IF !tip_part394 ("F"+xF_CodClient,,xF_DataFac,,@xx_Tip,,@xx_TipPers,,,,,,,,,,,@xx_err)'
        xx_scnt1 := StrTran(xx_scnt1, " ", "")
        // varianta corecta    
        xx_scnt2 := '#IF !tip_part394 (xF_TipClient[1]+xF_CodClient,,xF_DataFac,,@xx_Tip,,@xx_TipPers,,,,,,,,,,,@xx_err)'
        #IF (h_AtB(StrTran(xx_scnt2, " ", ""),gcmd->CMD,@xx_pp,@xx_ll) > 0)
        // OK, nu se face nimic
        #ELSEIF (h_AtB(xx_scnt1,gcmd->CMD,@xx_pp,@xx_ll) > 0)
            gcmd->CMD := Left(gcmd->CMD, xx_pp-1) + xx_scnt2 + SubStr(gcmd->CMD,xx_pp+xx_ll)
            h_PutLine("    Actualizat algoritmul de validare partener in M_BON")             
        #ELSE
            h_PutLine("*   Actualizarea algoritmului de validare partener in M_BON nereusita!")
        #ENDIF
    #ELSE
        h_PutLIne("**  M_BON -comanda generala nedefinita. Verificati!")
    #ENDIF
    
    h_CloseAlias()

    // Parametrii
    
    //Fisierul Stare hMARFA
    PutMsg("MOD:stat-M")
    #IF !h_UseAlias("stat")
        h_PutLine("*** Eroare deschidere fisier Stare hMARFA")
        Abandon("C")
    #ENDIF
    
    sman := RTrim(h_GetSubMemo(stat->DESCR,"S_PARAM"))
    
    xx_lModif := .F.
    
    xx_pp    := NIL
    xx_ll    := NIL
    xx_scnt1 := 'OP_TVAI_16 := {"MV", "D", .F.," ", "Ix",     , "OpTva eronat"}'
    xx_scnt1 := StrTran(xx_scnt1," ","")
    xx_scnt2 := 'OP_TVAI_16 := {"MV", "D", .F.," ", "Iz", "Ix", "OpTva Ix"}'
    xx_scnt2 := StrTran(xx_scnt2," ","")
    #IF (h_AtB(xx_scnt2,sman,@xx_pp,@xx_ll) > 0)
    // ok
    #ELSEIF (h_AtB(xx_scnt1,sman,@xx_pp,@xx_ll) > 0)
        xx_i := At('"Ix"',SubStr(sman,xx_pp,xx_ll))
        sman := Left(sman, xx_pp-1+xx_i-1)+'"Iz", "Ix", "OpTva Ix"'+SubStr(sman,xx_pp+xx_ll-1)
        xx_lModif := .T.
        h_PutLine("    Parametrii: modificat OP_TVAI_16 din sectiunea TVAI")
    #ELSE
        h_PutLine("*   Parametrii: OP_TVAI_16 din sectiunea TVAI negasit/nu este standard. Verificati!")
    #ENDIF
          
    man := stat->DESCR
    #IF h_PutSubMemo(@man,"S_PARAM",sman)
    #ELSE
        h_PutLine("**  Nu s-a reusit actualizarea in Parametri hMARFA !")
    #ENDIF
    stat->DESCR := man
    h_CloseAlias()
     
#ENDIF

// Modificari V 8.8C5
// -------------------
#IF sVM = "V 8.8C1" .OR. sVM = "V 8.8C3" .OR. sVM = "V 8.8C4"

    // --------------------------------------
    // Adaugare fisier x2 
    
    PutMsg("DEL:cmpf-x2")
    del_cmpf("X2    ","X2zzzz")
    PutMsg("DEL:cmps-x2")
    del_cmps("X2    ","X2zzzz")
    PutMsg("DEL:tfl-X2")
    del_tfl("X2   ","X2zzz")
    
    add_file("F1M_FILE")
    CopyFile("INTNRDOC", .F., fil_x2, "x2")
    
    PutMsg("ADD:cmpf-x2")
    add_cmpf("F1M_CMPF")
    PutMsg("ADD:cmps-x2")
    add_cmps("F1M_CMPS")
    PutMsg("ADD:tfl-X2")
    add_tfl("F1M_TFL")
    
    h_PutLine("    Adaugat fisierul x2 -"+h_UserNames[fil_x2])
    
    // Dictionar, adaugare rubrica noua Tip plaja
    PutMsg("MOD:dict")
    #IF !h_UseAlias({"dict"})
        h_PutLine("*** Eroare deschider Dictionar !")
        #DO FUABANDN.TXT
    #ENDIF
    // sterge rubrica
    DbEval({|| DbDelete() },{|| dict->RUB="Tip plaja   "})    
    __dbApp( (homepath+"DICTIONA"), { }, {|| field->RUB="Tip plaja   "},,,, .F. )
    h_PutLine("    Dictionar, adaugare rubrica noua: Tip plaja")
    h_CloseAlias()
    
    // -------------------------------------------------
    // Tipuri de documente
    
    PutMsg("MOD:tdoc")
    #IF !h_UseAlias("tdoc")
        h_PutLine("*** Eroare deschidere fisier Tipuri de documente")
        Abandon("C")
    #ENDIF
    xx_sini := ""
    xx_i    := 0
    __dbLocate( {|| tdoc->NRJUR="MVF" .AND. tdoc->COD!="TFAUS" .AND. tdoc->MODEL="A" .AND.   ;
                    (xx_sini := h_GetSubMemo(tdoc->DESCR,"INITIALI"),                        ;
                     HB_RegExMatch('\{.*"4Ix".*\}',xx_sini) .AND. !HB_RegExMatch('\{.*"4In".*\}',xx_sini))},,,, .F. )
    #IF Found()
        aMatch  := HB_RegExAtX('\{.*"4Ix".*\}',xx_sini)
        xx_sss  := SubStr(xx_sini,aMatch[1,2],aMatch[1,3]-aMatch[1,2]+1)
        
        xx_i    := At('"4Ix"',xx_sss)
        xx_sss  := Left(xx_sss,xx_i-1)+'"4In",'+SubStr(xx_sss,xx_i)
        
        xx_sini := Left(xx_sini,aMatch[1,2]-1)+xx_sss+SubStr(xx_sini,aMatch[1,3]+1)
        
        sman    := tdoc->DESCR
        #IF h_PutSubMemo(@sman, "INITIALI", xx_sini)
            tdoc->DESCR := sman
            h_PutLine("    "+tdoc->NRJUR+"/"+tdoc->COD+"/"+tdoc->MODEL+' -introdus "4In" in lista op.TVA din formula de initializare!')
        #ELSE
            h_PutLine("*** "+tdoc->NRJUR+"/"+tdoc->COD+"/"+tdoc->MODEL+" -depasire lungime submemo")
        #ENDIF
    #ENDIF        
    
    __dbLocate( {|| tdoc->NRJUR="MVF " .AND. tdoc->COD="TFBEN" .AND. tdoc->MODEL="A"},,,, .F. )
    #IF !Found()
        __dbApp( (homepath+"TIPDOC"), { }, ;
                 {|| field->NRJUR="MVF " .AND. field->COD="TFBEN" .AND. field->MODEL="A"},,,, .F. )
        h_PutLine("    Adaugat noul tip de document TFBEN -Factura emisa de beneficiar")         
    #ELSE
        h_PutLine("**  Tip doucument existent TFBEN. Noul TFBEN nu s-a putut adauga!")         
    #ENDIF         
    
    h_CloseAlias()
    
    // -------------------------------------------------------------------------
    // Comenzi generale
    
    PutMsg("MOD:gcmd-M")
    #IF !h_UseAlias("gcmd")
        h_PutLine("*** Eroare deschidere fisier Comenzi generale")
        Abandon("C")
    #ENDIF
    DbSelectArea("gcmd")
    // X2VERI se inlocuieste in V 8.8C6
    // sscript  :="OFAC_T,X2VERI,HCIFF ,"
    sscript  :="OFAC_T,HCIFF ,"
    DBEval( {|| DbDelete()}, {|| (gcmd->COD+",") $ sscript},,,, .F. )
    __dbApp( (homepath+"GENCMDM"), { },{|| (field->COD+",") $ sscript},,,, .F. )
    h_PutLine("    Inlocuit comanzi generale: "+StrTran(Left(sscript,Len(sscript)-1)," ",""))
    
    h_CloseAlias()
    
    // -------------------------------------------------------------------------
    //  Se incarca fisierul x2 -Numerotare documente
    
    // Citeste seriile de regim special din perioada 01.10.2016-31.12.2016
    PutMsg("Citeste seriile de regim special")
    #IF !h_UseAlias({"fac","x2"})
        h_PutLine("*** Eroare deschidere Facturi/Iesiri !")
        #DO FUABANDN.TXT
    #ENDIF
    DbSelectArea("fac")
    DbSetOrder(2)
    // Index.nr.2: H_DTOC(DATAFAC,"AAAA.LL.ZZ")
    // se parcurg facturile din intervalul 01.10.2016-31.12.2016
    aSerii := {=>}
    HSetAutoAdd(aSerii,.T.)
    HSetAACompatibility( aSerii, .T. )
    
    xx_sdatainc := "2016.10.01"
    xx_sdatasf  := "2016.12.31"
    #IF h_prT()="D"
        xx_sdatainc := "2016.07.01"
    #ENDIF
      
    DbSeek(xx_sdatainc,.T.)
    xx_i := 1
    #WHILE !Eof() .AND. h_DtoC(fac->DATAFAC,"aaaa.ll.zz") <= xx_sdatasf
        #IF fac->NRJUR="MV" .AND. Len(RTrim(fac->NRRS))>3
            xx_serie := Left(fac->NRRS,3)
            
            // Tip plaja
            xx_tipPl  := NIL
            #IF     ("F"$fac->CODL .AND. !HB_RegExMatch("[BUXbc3]",fac->CODL)) .OR. ;
                     (HB_RegExMatch("[an4]",fac->CODL)) 
                xx_tipPl := "F "
            #ELSEIF ("b" $ fac->CODL)
                xx_tipPl := "FA"
            #ELSEIF ("3" $ fac->CODL)
                xx_tipPl := "FB"
            #ELSEIF HB_RegExMatch("[BUXc]",fac->CODL)
                xx_tipPl := "--"
            #ELSE
                xx_tipPl := "  "
            #ENDIF 
            
            #IF xx_serie IN aSerii
                IIf(aSerii[xx_serie]:nrrs  > SubStr(fac->NRRS,4), (aSerii[xx_serie]:nrrs  := SubStr(fac->NRRS,4)), NIL)
                IIf(aSerii[xx_serie]:nrfac > fac->NRFAC,          (aSerii[xx_serie]:nrfac := fac->NRFAC),          NIL)
                IIf(!(aSerii[xx_serie]:tippl==xx_tipPl),          (aSerii[xx_serie]:tippl := "?"),                 NIL)
            #ELSE
                aSerii[xx_serie] := {"NRRS"  => SubStr(fac->NRRS,4), ;
                                     "NRFAC" => fac->NRFAC,          ;
                                     "TIPPL" => xx_tipPl}
            #ENDIF
        #ENDIF
        
        DbSelectArea("fac")
        DbSkip()
    #ENDDO
    
    xx_i := 0
    #WHILE ++xx_i <= Len(aSerii)
    
        xx_serie := HaaGetKeyAt(aSerii,xx_i)
        #IF aSerii[xx_serie]:tippl == "--"
            #LOOP
        #ENDIF
    
        DbSelectArea("x2")
        #IF !h_AddRec()
            h_PutLine("*** Adaugare articol nereusit la fisierul x2 -Numerotare documente !")
            #DO FUABANDN.TXT
        #ENDIF
        
        x2->SX2A1 := h_CtoD(xx_sdatainc,"aaaa.ll.zz")
        x2->SX2A2 := h_CtoD(xx_sdatasf, "aaaa.ll.zz")
        x2->SX2B1 := "MV"
        x2->SX2C0 := StrTran(aSerii[xx_serie]:tippl,"?","")
        x2->SX2D0 := xx_serie
        x2->SX2D1 := aSerii[xx_serie]:nrrs
        x2->SX2E1 := aSerii[xx_serie]:nrfac
        #IF x2->SX2C0 = "F "
            x2->SX2F1 := '""'
            x2->SX2F2 := "xF_NrFac"
        #ELSEIF x2->SX2C0 = "FA" .OR. x2->SX2C0 = "FB"
            x2->SX2F1 := '""'
            x2->SX2F2 := "SUBSTR(xF_NrRegSp,4)"
        #ELSE
            x2->SX2F1 := ""
            x2->SX2F2 := ""
        #ENDIF
    #ENDDO    
    
    h_CloseAlias({"fac","x2"})
#ENDIF

// Modificari V 8.8C6
// -------------------
#IF sVM = "V 8.8C1" .OR. sVM = "V 8.8C3" .OR. sVM = "V 8.8C4" .OR. sVM = "V 8.8C5"

    // Dictionar, adaugare termen nou: CODL-F -S -Facturi simplificate cu CIF
    PutMsg("MOD:dict")
    #IF !h_UseAlias({"dict"})
        h_PutLine("*** Eroare deschidere Dictionar !")
        #DO FUABANDN.TXT
    #ENDIF
    // sterge rubrica
    __dbLocate( {|| dict->RUB="CODL-F      " .AND. dict->TERM="S "},,,, .F. )
    #IF !Found()
        __dbApp( (homepath+"DICTIONA"), { }, {|| field->RUB="CODL-F      " .AND. field->TERM="S "},,,, .F. )
        h_PutLine("    Dictionar, adaugare termenul nou: CODL-F/ S")
    #ENDIF
    
    __dbLocate( {|| dict->RUB = "CODL-F      " .AND. AllTrim(dict->TERM)=="U" .AND. ;
                    RTrim(dict->DEN) == "Facturi simplificate"},,,, .F. )
    #IF Found()
        dict->DEN := "Facturi simplificate fara CIF"
    #ENDIF
    
    DbSetOrder(0)
    xx_aord := {"B" => "31", "X" => "32", "S" => "33", "U" => "34"}
    DbEval({|| dict->ORD := xx_aord[AllTrim(dict->TERM)]}, ;
           {|| dict->RUB = "CODL-F      " .AND. (AllTrim(dict->TERM) IN xx_aord)})
    h_CloseAlias()
    
    // Comenzi generale
    PutMsg("MOD:gcmd-M")
    #IF !h_UseAlias("gcmd")
        h_PutLine("*** Eroare deschidere fisier Comenzi generale")
        Abandon("C")
    #ENDIF
    DbSelectArea("gcmd")
    sscript  :="X2VERI,"
    DBEval( {|| DbDelete()}, {|| (gcmd->COD+",") $ sscript},,,, .F. )
    __dbApp( (homepath+"GENCMDM"), { },{|| (field->COD+",") $ sscript},,,, .F. )
    h_PutLine("    Inlocuit comanda generala: "+StrTran(Left(sscript,Len(sscript)-1)," ",""))
    
    h_CloseAlias()
#ENDIF    

// Modificari V 8.8D1
// -------------------
#IF sVM = "V 8.8C1" .OR. sVM = "V 8.8C3" .OR. sVM = "V 8.8C4" .OR. sVM = "V 8.8C5" .OR. sVM = "V 8.8C6"

    // se inlocuieste fisierul COTETVA
    CopyFile ("COTETVA", .F., fil_icm, "icm")
    h_PutLine("    Inlocuit fisierul Cote TVA")
    
    // seteaza CRT cu cf. CRT2016 sau CRT2017
    #IF ! h_UseAlias("icm")
        h_PutLine("*** Deschidere fisier Cote TVA fisierelor !")
        #DO FUABANDN.TXT
    #ENDIF
    #IF !Empty(DataMarfa) .AND. DataMarfa < h_CtoD("2017.01.01","aaaa.ll.zz")
        DbEval({|| icm->CRT := icm->CRT2016})
        h_PutLine("    Setat cote TVA curente pentru 2016")
    #ELSE
        DbEval({|| icm->CRT := icm->CRT2017})
        h_PutLine("    Setat cote TVA curente pentru 2017")
    #ENDIF
    h_CloseAlias()
    
    // Nomenclator articole: se adauga Y-COMP-AGRIC-1
    PutMsg("ADD:nomm-Y-COMP-AGRIC-1")
    #IF ! h_UseAlias("nomm")
        h_PutLine("*** Deschidere fisier Nomenclator articole !")
        #DO FUABANDN.TXT
    #ENDIF
    DBEval( {|| DbDelete()}, {|| nomm->COD="Y-COMP-AGRIC-1 "},,,, .F. )
    __dbApp( (homepath+"NOMM1"), { },{|| field->COD="Y-COMP-AGRIC-1 "},,,, .F. )
    h_PutLine("    Adaugat Y-COMP-AGRIC-1 in Nomenclatorul de articole")
    h_CloseAlias()
    
    // Grupe materiale: se adauga Y-COMP-AGRIC-1
    PutMsg("ADD:grm-Y_CA")
    #IF ! h_UseAlias("grm")
        h_PutLine("*** Deschidere fisier Grupe materiale !")
        #DO FUABANDN.TXT
    #ENDIF
    DBEval( {|| DbDelete()}, {|| grm->COD="Y_CA  "},,,, .F. )
    __dbApp( (homepath+"GRM1"), { },{|| field->COD="Y-CA  "},,,, .F. )
    h_PutLine("    Adaugat Y_CA in Grupe de materiale")
    h_CloseAlias()
    
    // Conturi de stoc: se adauga gest:Y gr:Y-CA
    PutMsg("ADD:cnts-gest:Y gr:Y-CA")
    #IF ! h_UseAlias("cnts")
        h_PutLine("*** Deschidere fisier Conturi de stoc !")
        #DO FUABANDN.TXT
    #ENDIF
    DBEval( {|| DbDelete()}, {|| cnts->GEST="Y   " .AND. cnts->GRUPA="Y-CA  " .AND. cnts->TIP="C"},,,, .F. )
    __dbApp( (homepath+"CNTS1"), { },{|| field->GEST="Y   " .AND. field->GRUPA="Y-CA  " .AND. field->TIP="C"},,,, .F. )
    h_PutLine("    Adaugat gest:Y gr:Y-CA in Conturi de stoc")
    h_CloseAlias()
    
    // copiaza NOMM2017.DBF langa nomm
    PutMsg("COPY:NOMM2017.DBF")
    xx_Fnomm := h_AddPath("NOMM2017.DBF",h_FilePathes[fil_nomm])
    #IF !h_SafeErase(xx_Fnomm)
        h_PutLine("*   NOMM2017.DBF exista deja, nu a fost suprascris !")
    #ENDIF
    #IF !File(xx_Fnomm)
        h_CopyFile(homepath+"NOMM2017.DBF",xx_Fnomm)
        #IF File(xx_Fnomm)
            h_PutLine("    Copiat NOMM2017.DBF")
        #ELSE
            h_PutLine("*   Copiere nereusita NOMM2017.DBF !")
        #ENDIF
    #ENDIF
    
    // Comenzi generale
    PutMsg("MOD:gcmd-t")
    #IF !h_UseAlias("gcmd")
        h_PutLine("*** Eroare deschidere fisier Comenzi generale")
        Abandon("C")
    #ENDIF
    DbSelectArea("gcmd")
    sscript  :="HCIFO ,"
    DBEval( {|| DbDelete()}, {|| (gcmd->COD+",") $ sscript},,,, .F. )
    __dbApp( (homepath+"GENCMDM"), { },{|| (field->COD+",") $ sscript},,,, .F. )
    h_PutLine("    Inlocuit/adaugat comenzile generale: "+StrTran(Left(sscript,Len(sscript)-1)," ",""))
    h_CloseAlias()
#ENDIF

// Modificari V 8.9A1
// -------------------

// Se adauga noul camp CONTBANCA in tjur
// --------------------------------------
PutMsg("ADD:tjur/CONTBANCA")
#IF ! h_UseAlias("tjur")
    h_PutLine("*** Eroare deschidere fisier Tipuri de jurnale!")
    #DO FUABANDN.TXT
#ENDIF
#IF FieldPos("CONTBANCA")=0

    xx_aStr := DbStruct()

    ic   := FieldPos("NB_UPD")
    #IF ic = 0 
        h_PutLine("*** Fisierul Tipuri de jurnale: structura eronata !")
        #DO FUABANDN.TXT
    #ENDIF

    AINS(xx_aStr,ic,{"CONTBANCA", "C", 29, 0},.t.)
    h_CloseAlias("tjur")

    xx_sfile := "tjur"
    xx_ifile := fil_tjur
    xx_fM    := "MANTJUR"
    #DO FUPGR.TXT
    h_PutLine("    Adaugat campul CONTBANCA in fisierul Tipuri de jurnale")
#ENDIF
h_CloseAlias()

// Actualizare indecs x2
// --------------------------------------
PutMsg("INDX:x2")
add_file("F1M9_FILE")

#IF !h_UseAlias({"x2"})
    h_PutLine("*** Eroare deschidere fisier Numerotare documente!")
    #DO FUABANDN.TXT
#ENDIF
index_file ("x2")
h_CloseAlias()
h_PutLine("    Actualizat indecsii fisierului Numerotare documente")

// Constante si funcii -constanta noua PLAFN-REST
// -----------------------------------------------

PutMsg("MOD:cf")
#IF !h_UseAlias({"cf"})
    h_PutLine("*** Eroare deschider Constante si functii!")
    #DO FUABANDN.TXT
#ENDIF
// sterge rubrica
DbEval({|| DbDelete() },{|| cf->COD="PLAFN-REST  "})    
__dbApp( (homepath+"CNSTFUNC"), { }, {|| field->COD="PLAFN-REST  "},,,, .F. )
h_PutLine("    Adaugat constanta noua PLAFN-REST")
h_CloseAlias()
 
// Dictionar 
// ----------
PutMsg("MOD:dict")
#IF !h_UseAlias({"dict"})
    h_PutLine("*** Eroare deschider Dictionar!")
    #DO FUABANDN.TXT
#ENDIF
// se marcheaza rubrica DA/NU sa apartina si de M-hMARFA
lModif := .F.
lExist := .F.
DbEval({|| IIF("M"$dict->TIP,,(dict->TIP := "M"-dict->TIP, lModif:=.T.)),lExist:=.T.},      ;
       {|| dict->RUB="DA/NU       "})
IIf(lModif,  h_PutLine("    Asociat rubrica DA/NU din Dictionar de hMARFA"),)
IIf(!lExist, h_PutLine("**  Rubrica DA/NU din Dictionar nu exista!"),)
h_CloseAlias()

// Comenzi generale
// -----------------
PutMsg("MOD:gcmd")
#IF !h_UseAlias({"gcmd"})
    h_PutLine("*** Eroare deschider Constante si functii!")
    #DO FUABANDN.TXT
#ENDIF
// sterge comenzile generale
xx_sgcmd  := "UUXLSF,UUXLSN,"
xx_sgcmdD := ""
DbEval({|| xx_sgcmdD+=gcmd->COD-",", DbDelete() },{|| (gcmd->COD+",") $ xx_sgcmd})
IIf(!Empty(xx_sgcmdD),h_PutLine("    Comenzi generale, sters: "+StrTran(xx_sgcmdD," ","")),NIL)
   
// adauga comenzile generale
xx_sgcmd := "XFACF5,XFURF5,X_CAMP,UUXLSI,UUXLS_,UUXML_,X_CAMP,X2VERI,X2_AF ,X2_AFA,OFAC_F,X2_INI,X2_SFR,"
DbEval({|| DbDelete() },{|| (gcmd->COD+",") $ xx_sgcmd})    
__dbApp( (homepath+"GENCMDM"), { }, {|| (field->COD+",") $ xx_sgcmd},,,, .F. )
h_PutLine("    Adaugat/Modificat comenzi generale: "+StrTran(xx_sgcmd," ",""))

// deschide comanda generala FISXML 
lModif := .F.
DbEval({|| gcmd->DESCH:=.T.,lModif:=.T.},{|| gcmd->COD="FISXML"})
IIf(lModif,h_PutLine("    Deschis comanda generala FISXML"),      ;
           h_PutLine("*   FISXML -comanda generala inexistenta!"))

h_CloseAlias()

//Fisierul Stare hMARFA
// ---------------------
PutMsg("MOD:stat-M")
#IF !h_UseAlias("stat")
    h_PutLine("*** Eroare deschidere fisier Stare hMARFA")
    Abandon("C")
#ENDIF
    
sman := RTrim(h_GetSubMemo(stat->DESCR,"S_PARAM"))

sSectie := "[IESIRI]"                                                                           +Chr(13)+Chr(10)+ ;
           "  // Algoritmul de calcul al numarului de regim special si"                         +Chr(13)+Chr(10)+ ; 
           "  // al numarului de document urmator:"                                             +Chr(13)+Chr(10)+ ; 
           "  // -Algoritmul nou, bazat pe Numere de interval si"                               +Chr(13)+Chr(10)+ ;
           "  //  modul lor de validare la completarea documentelor de iesire"                  +Chr(13)+Chr(10)+ ; 
           "  //   -.F. -atentionare, daca nu satisface criteriile din Numerotare documente,"   +Chr(13)+Chr(10)+ ; 
           "  //         este valoarea implicita"                                               +Chr(13)+Chr(10)+ ;
           "  //   -.T. -eroare"                                                                +Chr(13)+Chr(10)+ ;
           "  // -Algoritmul vechi"                                                             +Chr(13)+Chr(10)+ ;  
           "  //   -NIL -algoritmul vechi bazat pe comenzile generale NRD_MV"                   +Chr(13)+Chr(10)+ ;
           "  VAL_NRDOC := "+ValToPrg(VAL_NRDOC)                                                +Chr(13)+Chr(10)+Chr(13)+Chr(10)  

xx_p1 := At("[INTRARI]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    h_PutLine("*   Sectiunea INTRARI absenta din Parametrii!")   
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman += sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   

sSectie := '   // Coloane in fereastra de ajutor'                                          +Chr(13)+Chr(10)+ ;
           '   // Coloane implicite, care vor fi afisate neconditionat: "Cod", "Initiale"' +Chr(13)+Chr(10)+ ;
           '   // Coloane optionale: "Cod fiscal", "Localitate" si campurile suplimentare' +Chr(13)+Chr(10)+ ;
           '   // HLP_COL :={"Cod fiscal", "Localitate", "Camp_sup"}'                      +Chr(13)+Chr(10)+Chr(13)+Chr(10)
xx_p1 := At("[FIRME]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    h_PutLine("*   Sectiunea FIRME absenta din Parametrii!")   
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman := sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+"[FIRME]"+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+Chr(13)+Chr(10)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   

sSectie := '   // Coloane in fereastra de ajutor'                                               +Chr(13)+Chr(10)+ ;
           '   // Coloane implicite, care vor fi afisate neconditionat:'                        +Chr(13)+Chr(10)+ ;
           '   // "Cod", "Denumire",'                                                           +Chr(13)+Chr(10)+ ;
           '   // "Pu.livrare" -la adaugarea randurilor doc.de iesire in lei si cu pu livrare'  +Chr(13)+Chr(10)+ ;
           '   // "Pu.vanzare" -la adaugarea randurilor doc.de iesire in lei su cu pu amanuntul'+Chr(13)+Chr(10)+ ;
           '   // Coloane optionale "Grupa" si campurile suplimentare:'                         +Chr(13)+Chr(10)+ ;
           '   // HLP_COL :={"Grupa", "Camp_sup"}'                                              +Chr(13)+Chr(10)+Chr(13)+Chr(10)
xx_p1 := At("[NOMENCLATOR_ARTICOLE]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    h_PutLine("*   Sectiunea NOMENCLATOR_ARTICOLE absenta din Parametrii!")   
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman := sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+"[NOMENCLATOR_ARTICOLE]"+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+Chr(13)+Chr(10)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   
           
sSectie := '[LOCALITATI]'                                                                  +Chr(13)+Chr(10)+ ;
           '   // Coloane in fereastra de ajutor'                                          +Chr(13)+Chr(10)+ ;
           '   // Coloane implicite, care vor fi afisate neconditionat:'                   +Chr(13)+Chr(10)+ ;
           '   // "Localitate", "Tara"'                                                    +Chr(13)+Chr(10)+ ;
           '   // Coloane optionale:  "Judet" si campurile suplimentare'                   +Chr(13)+Chr(10)+ ;
           '   // HLP_COL :={"Camp_sup"}'                                                  +Chr(13)+Chr(10)+Chr(13)+Chr(10)
// se insereaza dupa FIRME
xx_p1 := At("[FIRME]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman := sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+"[LOCALITATI]"+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   

sSectie := '[SECTII]'                                                                      +Chr(13)+Chr(10)+ ;
           '   // Coloane in fereastra de ajutor'                                          +Chr(13)+Chr(10)+ ;
           '   // Coloane implicite, care vor fi afisate neconditionat:'                   +Chr(13)+Chr(10)+ ;
           '   // "Cod", "Denumire"'                                                       +Chr(13)+Chr(10)+ ;
           '   // Coloane optionale: campuri suplimentare'                                 +Chr(13)+Chr(10)+ ;
           '   // HLP_COL :={"Camp_sup"}'                                                  +Chr(13)+Chr(10)+Chr(13)+Chr(10)
// se insereaza dupa FIRME
xx_p1 := At("[FIRME]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman += sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+"[SECTII]"+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   

sSectie := '[PERSOANE]'                                                                    +Chr(13)+Chr(10)+ ;
           '   // Coloane in fereastra de ajutor'                                          +Chr(13)+Chr(10)+ ;
           '   // Coloane implicite, care vor fi afisate neconditionat:'                   +Chr(13)+Chr(10)+ ;
           '   // "Marca", "Nume si prenume"'                                              +Chr(13)+Chr(10)+ ;
           '   // Coloane optionale: "Firma", "Localitatea" si campurile suplimentare'     +Chr(13)+Chr(10)+ ;
           '   // HLP_COL :={"Firma", "Localitate", "Camp_sup"}'                           +Chr(13)+Chr(10)+Chr(13)+Chr(10)
// se insereaza dupa FIRME
xx_p1 := At("[FIRME]",sman)
xx_p2 := IIF(xx_p1==0, 0, AT(Chr(13)+Chr(10)+"[",SubStr(sman,xx_p1)))
#IF xx_p1==0 .OR. xx_p2==0
    // se adauga la sf.
    // se elimina randurile vide
    h_LoopBlock({|| sman := RTrim(Left(sman,Len(sman)-2))},{|| Right(sman,2)=Chr(13)+Chr(10)})
    sman := sman+Chr(13)+Chr(10)+Chr(13)+Chr(10)+"[PERSOANE]"+Chr(13)+Chr(10)+sSectie
#ELSE
    sman := Left(sman,xx_p1-1+xx_p2-1+2)+sSectie+SubStr(sman,xx_p1-1+xx_p2-1+3)
#ENDIF   

man := stat->DESCR
#IF h_PutSubMemo(@man,"S_PARAM",sman)
    stat->DESCR := man
    h_PutLine("    Adaugat sectiunea IESIRI in Parametrii")
#ELSE
    h_PutLine("**  Nu s-a reusit actualizarea in Parametri hMARFA !")
#ENDIF
h_CloseAlias()

// Campuri
// --------

PutMsg("DEL:cmps-X2D")
del_cmps("X2D   ","X2D   ")
h_PutLine("    Sterscampul X2D")

PutMsg("ADD:cmps-X2EPI")
add_cmps("F1M9_CMPS")
h_PutLine("    Adaugat cam nou X2EPI")

// Operatii/Ferestre/Liste
// ------------------------

PutMsg("ADD:tfl")
add_tfl("F1M9_TFL")
h_PutLine("    Adaugare fereastra de fisier X2/02")

// Atasare campuri la fer.fisier 02
// ---------------------------------
PutMsg("MOD:cmps-M")
#IF !h_UseAlias("cmps")
    h_PutLine("*** Eroare deschidere fisier Campuri")
    Abandon("C")
#ENDIF
DbEval({|| cmps->FF:=cmps->FF[1]+"X"+SubStr(cmps->FF,3)}, ;
       {|| (cmps->COMP+",") $ "X2A1  ,X2C0  ,X2D0  ,X2D1  ,X2E1  ,X2O   ,"})
h_PutLine("    Marcat campurile pentru fereastra de fisier X2/02")   

lModif := .F.
DbEval({|| cmps->TF:="Tp", lModif:=.T.},{|| cmps->COMP="X2C0  "}) 
IIf(lModif, h_PutLine("    Modificat titlu fereastra pt.campul X2C0"), ;
            h_PutLine("**  Camp inexistent X2C0 !"))      
lModif := .F.

DbEval({|| cmps->TF:="Explicatii", lModif:=.T.},{|| cmps->COMP="X2O   "}) 
IIf(lModif, h_PutLine("    Modificat titlu fereastra pt.campul X2O"), ;
            h_PutLine("**  Camp inexistent X2O !"))

lModif := .F.
xx_scamp := "X2O   ,"
DbEval({|| cmps->LGE:=40,lModif:=.T.}, {|| (cmps->COMP+",")$xx_scamp})
#IF lModif
    write_stru({"X2"})
    h_PutLine("    Modificat lungimea campului X20 la 40 de caractere")
#ELSE
    h_PutLine("*   Camp X20 nedefinit!")
#ENDIF
h_CloseAlias()

// Nomenclator articole
// -------------------------------------
PutMsg("MOD:nomm")
#IF !h_UseAlias("nomm")
    h_PutLine("*** Eroare deschidere fisier Nomenclator articole")
    Abandon("C")
#ENDIF
lModif := .F.
DbEval({|| nomm->DENUM:="Compensatie agricultori 1%",lModif:=.T.},{|| nomm->COD="Y-COMP-AGRIC-1"})
IIf(lModif,h_PutLine("    Modificat denumirea: Y-COMP-AGRIC-1 -Compensatie agricultori 1%"), ;
           h_PutLine("*   Y-COMP-AGRIC-1 -inexistent in Nomenclatorul de articole"))
h_CloseAlias()

// Copiere FISALOT1 si 2
// -------------------------------------
#IF "linux" $ h_Os("l")
    x_sdest := h_AddPath("FISALOT1",h_FilePathes[fil_lotf])
    #IF x_deltree (h_OsPath(x_sdest))
        h_DOS ("cp -R "+homepath+"FISALOT1 "+x_sdest)
        IIf(h_FDExist(homepath+"FISALOT1")="D", h_PutLine("    Copiat FISALOT1 in "+x_sdest), ;
                                                h_PutLine("*   Copiere FISALOT1 nereusita!"))
    #ELSE
        h_PutLine("*   Copiere FISALOT1 nereusita, nu s-a reusit stergerea catalogului existent!")
        h_PutLine("    ("+x_sdest+")")
    #ENDIF  
    x_sdest := h_AddPath("FISALOT2",h_FilePathes[fil_lotf])
    #IF x_deltree (h_OsPath(x_sdest))
        h_DOS ("cp -R "+homepath+"FISALOT2 "+x_sdest)
        IIf(h_FDExist(homepath+"FISALOT2")="D", h_PutLine("    Copiat FISALOT2 in "+x_sdest), ;
                                                h_PutLine("*   Copiere FISALOT2 nereusita!"))
    #ELSE
        h_PutLine("*   Copiere FISALOT2 nereusita, nu s-a reusit stergerea catalogului existent!")
        h_PutLine("    ("+x_sdest+")")
    #ENDIF  
#ELSE
    x_sdest := h_AddPath("FISALOT1",h_FilePathes[fil_lotf])
    #IF x_deltree (h_OsPath(x_sdest))
        h_DOS ("xcopy "+homepath+"FISALOT1 "+x_sdest+" /E /I /Y >NUL")
        IIf(h_FDExist(homepath+"FISALOT1")="D", h_PutLine("    Copiat FISALOT1 in "+x_sdest), ;
                                                h_PutLine("*   Copiere FISALOT1 nereusita!"))
    #ELSE
        h_PutLine("*   Copiere FISALOT1 nereusita, nu s-a reusit stergerea catalogului existent!")
        h_PutLine("    ("+x_sdest+")")
    #ENDIF  
    x_sdest := h_AddPath("FISALOT2",h_FilePathes[fil_lotf])
    #IF x_deltree (h_OsPath(x_sdest))
        h_DOS ("xcopy "+homepath+"FISALOT2 "+x_sdest+" /E /I /Y >NUL")
        IIf(h_FDExist(homepath+"FISALOT2")="D", h_PutLine("    Copiat FISALOT2 in "+x_sdest), ;
                                                h_PutLine("*   Copiere FISALOT2 nereusita!"))
    #ELSE
        h_PutLine("*   Copiere FISALOT2 nereusita, nu s-a reusit stergerea catalogului existent!")
        h_PutLine("    ("+x_sdest+")")
    #ENDIF  
#ENDIF

// -------------------------------------------------------------------------
//  Se incarca fisierul x2 -Numerotare documente

// Citeste seriile de regim special incepand cu 2017.01.01
PutMsg("Citeste seriile de regim special pt.anul 2017")
#IF !h_UseAlias({"fac"})
    h_PutLine("*** Eroare deschidere Facturi/Iesiri !")
    #DO FUABANDN.TXT
#ENDIF

// se deschide fisierul x2, ca fisier extern, ca sa fie luati
// in considerare indecsii noi
fobj      := h_ExtUse():new(h_FilePathes[fil_file], "M", "W" )
fobj:afis := {"x2"}
#IF !fobj:open()
    h_MesErr("Eroare deschidere fisiere Numerotare documente !",0)
    #DO FUABANDN.TXT
#ENDIF

DbSelectArea("fac")
DbSetOrder(2)
// Index.nr.2: H_DTOC(DATAFAC,"AAAA.LL.ZZ")
// se parcurg facturile din intervalul 01.10.2016-31.12.2016
aSerii := {=>}
HSetAutoAdd(aSerii,.T.)
HSetAACompatibility( aSerii, .T. )

xx_sdatainc := "2017.01.01"
xx_sdatasf  := "2017.12.31"

h_PutLine("    Generare plaje in Numerotare documente")  
DbSeek(xx_sdatainc,.T.)
xx_i := 1
#WHILE !Eof() .AND. h_DtoC(fac->DATAFAC,"aaaa.ll.zz") <= xx_sdatasf
    #IF "V" $ fac->STARE .AND. (fac->NRJUR="MVF" .OR. fac->NRJUR="MVR")
        xx_serie := Left(fac->NRRS,3)
        
        // Tip plaja
        xx_tipPl  := NIL
        #IF     ("F"$fac->CODL .AND. !HB_RegExMatch("[BUXbc3]",fac->CODL)) .OR. ;
                 (HB_RegExMatch("[an4]",fac->CODL)) 
            xx_tipPl := "F "
        #ELSEIF ("b" $ fac->CODL) .OR. ;
                !Empty(fac->NRRS) .AND. Empty(SubStr(fac->NRRS,4)) .AND. (Empty(fac->CODL) .OR. "c"$fac->CODL)
            xx_tipPl := "FA"
        #ELSEIF ("3" $ fac->CODL)
            xx_tipPl := "FB"
            IIf(Empty(xx_serie),(xx_serie:="---"),nil)
        #ELSEIF HB_RegExMatch("[BUXc]",fac->CODL)
            xx_tipPl := "  "
        #ELSE
            xx_tipPl := "  "
        #ENDIF 
        
        #IF xx_serie IN aSerii
            // pt.FB nu are importanta nr.reg.sp.
            IIF(xx_tipPl="FB", NIL,                                                                        ;
            IIf(Empty(aSerii[xx_serie]:nrrs)                                                         .OR.  ;
                (!Empty(SubStr(fac->NRRS,4))  .AND. aSerii[xx_serie]:nrrs  > SubStr(fac->NRRS,4)),         ;
                                                     (aSerii[xx_serie]:nrrs  := SubStr(fac->NRRS,4)), NIL))
            IIf(aSerii[xx_serie]:nrfac > fac->NRFAC, (aSerii[xx_serie]:nrfac := fac->NRFAC),          NIL)
            IIf(!(aSerii[xx_serie]:tippl==xx_tipPl), (aSerii[xx_serie]:tippl := "?"),                 NIL)
        #ELSE
            aSerii[xx_serie] := {"NRRS"  => IIF(xx_tipPl="FB",Space(12),SubStr(fac->NRRS,4)), ;
                                 "NRFAC" => fac->NRFAC,          ;
                                 "TIPPL" => xx_tipPl}
        #ENDIF
    #ENDIF
    
    DbSelectArea("fac")
    DbSkip()
#ENDDO

DbSelectArea("x2")
dbSetFilter( {|| "MV  2017"=x2->SX2B1+h_Dtoc(SX2A1,"aaaa")}, '"MV  2017"=x2->SX2B1+h_Dtoc(x2->SX2A1,"aaaa")')
// introduce "---" in seriile pentru FB -sa nu se confunda cu cele vide
DbSetOrder(1)
DbEval({|| x2->SX2D0:="---"},{|| x2->SX2C0="FB"})

xx_i := 0
#WHILE ++xx_i <= Len(aSerii)
    xx_serie := HaaGetKeyAt(aSerii,xx_i)
    // #IF xx_serie == "---"
    //     xx_serie := "   "
    // #ENDIF
    DbSetOrder(3)
    DbSeek(xx_serie+aSerii[xx_serie]:nrrs,.T.)
    xx_rinclS := 0
    #IF Found()
        xx_rinclS := RecNo()
    #ELSE
        DbSkip(-1)
        #IF !Bof() .AND. xx_serie == x2->SX2D0 .AND. ;
            x2->SX2D1 <= aSerii[xx_serie]:nrrs .AND. aSerii[xx_serie]:nrrs <= x2->SX2D2
            xx_rinclS := RecNo()
        #ENDIF
    #ENDIF
    
    DbSetOrder(4)
    DbSeek(aSerii[xx_serie]:nrfac,.T.)
    xx_rinclN   := 0
    #IF Found()
        xx_rinclN := RecNo()
    #ELSE
        DbSkip(-1)
        #IF !Bof() .AND. xx_serie == x2->SX2D0 .AND. ;
            x2->SX2E1 <= aSerii[xx_serie]:nrfac .AND. aSerii[xx_serie]:nrfac <= x2->SX2E2
            xx_rinclN := RecNo()
        #ENDIF
    #ENDIF
    #IF xx_rinclN==0 .AND. xx_rinclS==0
        DbSelectArea("x2")
        DbAppend()
        #IF NetErr()
            h_PutLine("*** Adaugare articol nereusit la fisierul x2 -Numerotare documente !")
            #DO FUABANDN.TXT
        #ENDIF
        
        x2->SX2A1 := h_CtoD(xx_sdatainc,"aaaa.ll.zz")
        x2->SX2A2 := h_CtoD(xx_sdatasf, "aaaa.ll.zz")
        x2->SX2B1 := "MV"
        x2->SX2C0 := StrTran(aSerii[xx_serie]:tippl,"?","")
        x2->SX2D0 := xx_serie
        IIf(!(x2->SX2C0="FB"), x2->SX2D1 := aSerii[xx_serie]:nrrs,NIL)
        x2->SX2E1 := aSerii[xx_serie]:nrfac
        #IF x2->SX2C0 = "F "
            x2->SX2F1 := '""'
            x2->SX2F2 := "xF_NrFac"
        #ELSEIF x2->SX2C0 = "FA" .OR. x2->SX2C0 = "FB"
            x2->SX2F1 := '""'
            x2->SX2F2 := "SUBSTR(xF_NrRegSp,4)"
        #ELSE
            x2->SX2F1 := ""
            x2->SX2F2 := ""
        #ENDIF
    #ELSEIF (xx_rinclN!=0 .OR. xx_rinclS!=0) .AND. !(xx_rinclN==xx_rinclS)
        // conflict, nu se adauga
        h_PutLine("*   Plaja cu NrRs: "+xx_serie+"-"+aSerii[xx_serie]:nrrs+" si nrfac: "+aSerii[xx_serie]:nrfac+" cu suprapunere, nu se adauga!")
    #ENDIF
#ENDDO    

// scoate eventualele serii "---"
DbSetOrder(1)
DbEval({|| x2->SX2D0:="   "},{|| x2->SX2D0="---"})

// se contopesc intervalele care indica plaje adiacente
// (acelasi tip, serie si perioada identica)
DbGoTop()
#WHILE !Eof()
    xx_recno := RecNo()
    
    xx_perinc := x2->SX2A1
    xx_persf  := x2->SX2A2
    xx_tipPl  := x2->SX2C0
    xx_serie  := x2->SX2D0

    DbSetOrder(3)
    DbSkip(-1)
    xx_recnoS := 0
    #IF !Bof() .AND. xx_serie ==x2->SX2D0 .AND. xx_tipPl ==x2->SX2C0 .AND. ;
                     xx_perinc==x2->SX2A1 .AND. xx_persf ==x2->SX2A2 .AND. ;
                     Empty(x2->SX2D2)
         xx_recnoS := RecNo()
    #ENDIF
    DbGoto(xx_recno)
    
    DbSetOrder(4)
    DbSkip(-1)
    xx_recnoN := 0
    #IF !Bof() .AND. xx_serie ==x2->SX2D0 .AND. xx_tipPl ==x2->SX2C0 .AND. ;
                     xx_perinc==x2->SX2A1 .AND. xx_persf ==x2->SX2A2 .AND. ;
                     Empty(x2->SX2E2)
         xx_recnoN := RecNo()
    #ENDIF
    
    DbGoto(xx_recno)
    DbSetOrder(1)
    // plajele pot fi contopite si din paretea numerelor de reg.sp. si 
    // din partea numerelor de factura
    #IF !Empty(xx_recnoS) .AND. !Empty(xx_recnoN) .AND. xx_recnoS == xx_recnoS
        DbDelete()
    #ENDIF
    DbSkip()    

#ENDDO 
h_CloseAlias({"fac","x2"})

// -------------------------------------------------------------------------
// Aplicatii
// DbSelectArea("apl")
// DBEval( {|| apl->V        := aref->V,                                        ;
//             apl->EXE_FILE := Left(apl->EXE_FILE,6)+SubStr(aref->EXE_FILE,7),      ;
//             apl->NRORD    := aref->NRORD,                                    ;
//             apl->OPT      := RTrim(aref->OPT)+IIf("$"$aref->OPT,"","$")},    ;
//         {|| apl->CODE ="M"},,,, .F. )
// h_CloseAlias()

// -------------------------------------------------------------------------
EndMsg()
h_CloseOut("")

#RETURN
// ---------------------------------------------------------------
