;** RestauDp *******************************************************************
;*  Restaura‡ao das Duplicatas                                                 *
;*******************************************************************************
;Autor           : Vise Informatica (VISERP)
;Desenvolvido    : 04/09/2018 por Anivel Augusto Rodrigues
;Ultima Alteracao: 27/09/2018 por Anivel Augusto Rodrigues 
;Motivo Alteracao: ajuste limpar controle dia
;Ultima Alteracao: 14/03/2019 por Anivel Augusto Rodrigues                           
;Motivo Alteracao: Ajustes Numero_Lancamento("Interno","Locked_Down")

;*******************************************************************************
;* ROTINA PROCESSA  -> realiza o processamento da Restaura‡ao                  *
;*******************************************************************************
Proc PROCESSA()
private Arquivo, wi

AGUARDE("Aguarde, Restaurando Duplicatas")
ClearAll

If Not IsTable(VSDGDRIVE+"\\Duplic")   
   Then Mensagem("Na Unidade "+VSDGDRIVE+" n„o contem Duplicatas !")
        Return
endif        

Array Arquivo[1]
Arquivo[1] ="Duplic"

for wi from 1 to 1 

  If Not IsTable(VSDGDRIVE+"\\"+Arquivo[wi])   
     Then loop
  endif        

  AGUARDE("Aguarde, Restaurando "+VSDGDRIVE+"\\"+Arquivo[wi]+" ["+Format("W2,AR",wi)+"/1]")

  switch
    case wi=1 :
      {Ask} TypeIn VSDGDRIVE+"\\DupliC" Enter Check
      Moveto [Codigo da Empresa      ] TypeIn "~VSDGEMPRESA.."
      Moveto [Data de Emissao        ] TypeIn ">=~VSDGDTINI, <=~VSDGDTFIM"
      Moveto [Tipo do Documento      ] TypeIn "Not ROM.."
      Moveto [Codigo do Documento    ] TypeIn "~VSDGTPDOCTO.."
      Do_It!
      ClearAll
    
    otherwise :
  
  endswitch

endfor

If IsEmpty("Answer")
   Then 
        Mensagem("NĆo existe(m) duplicatas(s) conforme sele‡Ćo !// //Verificar Empresa, TpDocto, Data Referente !")
        Return
EndIf

NR    =NRecords("Answer")

Regexiste=0
Regnovo  =0

View "Duplic"
Coedit "Answer"

Scan
  Barra(NR, RecNo())
  Aguarde("Aguarde, Processando Duplicatas "+BARRA_STRING)
  
  copytoarray reg_answer

  CHV_EMPRESA =[Answer->Codigo da Empresa  ]
  CHV_TPDOCTO =[Answer->Codigo do Documento]
  CHV_NUMERO  =[Answer->Numero do Documento]
    
  Moveto "\\Sistemas\\Ctarec\\Duplic"
  Moveto [Codigo da Empresa]
  Locate IndexOrder by "Inddup1" CHV_EMPRESA,CHV_TPDOCTO,CHV_NUMERO
  If RetVal
     Then While [Codigo da Empresa   ]=CHV_EMPRESA and
                [Codigo do Documento ]=CHV_TPDOCTO and
                [Numero do Documento ]=CHV_NUMERO
                
                
            regexiste=regexiste+1
            quitloop
          endwhile
          
     else
          While True
            End
            Moveto [Numero do Lancamento]
            If Numero_Lancamento("Interno","Locked_Down")
               Then CR_LANC = PROXLANCTO_NLANC
                    Release Vars PROXLANCTO_NLANC
                    quitloop
            EndIf    
          EndWhile
     
         ;While True
         ;  Moveto [Numero do Lancamento]
         ;  End
         ;  If Numero_Lancamento("Interno","")
         ;     Then CR_LANC = PROXLANCTO_NLANC
         ;          Release Vars PROXLANCTO_NLANC
         ;  EndIf
         ;  Locate CR_LANC
         ;  If Not Retval
         ;     Then End Down
         ;          [Numero do Lancamento ]=CR_LANC
         ;          If Not IsLockRecord()
         ;             Then QuitLoop
         ;             Else Del
         ;          EndIf
         ;  EndIf
         ;EndWhile

          regnovo  =regnovo+1
          
          reg_answer["Numero do Lancamento"]=CR_LANC
          reg_answer["Numero_Controle_Dia" ]=""
          
          copyfromarray reg_answer
          Controle_Dia()
          UnLockRecord
  endif        
  
  Moveto "Answer"
EndScan
Do_It!
ClearAll

IMPDP=True

EndProc

;*******************************************************************************
;* Rotina para gerar o log de registro por usu rio                             *
;*******************************************************************************
Proc Gera_Log()          

If VSDGDTINI<>BlankDate()
   Then AUX_DATA = ", periodo de "+StrVal(VSDGDTINI)+" ate "+StrVal(VSDGDTFIM)
   Else AUX_DATA = ", periodo ate "+StrVal(VSDGDTFIM)
EndIf   
          
If VSDGDTREF<>BlankDate()
   Then AUX_DTREF = ", data de transa‡„o em "+StrVal(VSDGDTREF)
   Else AUX_DTREF = ""
EndIf

AUX_OPCAO = "" 
If VSDGTPDOCTO<>"" Then AUX_OPCAO = ", Tipo do Documento: "+VSDGTPDOCTO+" "+VSDGNOMTPDOCTO EndIf

Grava_LogEx("VENDAS RestauDp")  

EndProc ;Gera_Log()                    

;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc SD_Dialog(Disparo,Campo,Evento,Elemento)
Temp=True
MSG_CAMPO=""
TECLA=""
If Disparo="OPEN"  Then AoCriarShowDialog() EndIf
If Disparo="EVENT" And Evento["Type"]="KEY" Then
   Switch
     Case Evento["KeyCode"] =   9: Temp=False
     Case Evento["KeyCode"] = -59: Dialog_F1()
     Case (Evento["KeyCode"] <= -104 And Evento["KeyCode"] >= -113) Or
           Evento["KeyCode"]  = -139 Or  Evento["KeyCode"]  = -140:
           SYS_TECLA_ACIONADA=Evento["KeyCode"]
           Seta_Tecla_Acionada()
           CancelDialog
     Case Evento["KeyCode"] =  27:
          Temp=False
          Switch
            Case Campo="TG_EMPRESA"       : Campo="NO"
            Case Campo="TG_TPDOCTO"       : Campo="TG_EMPRESA"
            Case Campo="TG_DTINI"         : Campo="TG_TPDOCTO"
            Case Campo="TG_DTFIM"         : Campo="TG_DTINI"
            Case Campo="TG_DTREF"         : Campo="TG_DTFIM"
            Case Campo="TG_DRIVES"        : Campo="TG_DTREF"
            Case Campo="YES" Or Campo="NO": Campo="TG_EMPRESA"
          EndSwitch
     Case Evento["KeyCode"] = 13:
          Temp=False
          If Checa_TAG()
             Then Switch
                    Case Campo="TG_EMPRESA" : Campo="TG_TPDOCTO"
                    Case Campo="TG_TPDOCTO" : Campo="TG_DTINI"
                    Case Campo="TG_DTINI"   : 
                         If Isblank(VSDGDTINI)
                            Then Mensagem("Data inicial invalida !")
                                 Campo="TG_DTINI"
                            Else Campo="TG_DTFIM"
                         EndIf
                    Case Campo="TG_DTFIM"   : 
                         If IsBlank(VSDGDTFIM) Or
                            VSDGDTFIM<VSDGDTINI
                            Then Mensagem("Data final invalida !")
                            Else Campo="TG_DTREF"
                         EndIf
                    Case Campo="TG_DTREF"   : Campo="TG_DRIVES"
                    Case Campo="TG_DRIVES"   :
                         VSDGDRIVE=ControlValue("TG_DRIVES")
                         Campo="YES"
                  EndSwitch
          EndIf
   EndSwitch
EndIf

Switch
  Case Campo="TG_EMPRESA":
       MSG_CAMPO="Informe uma Empresa"
  Case Campo="TG_DTREF" :
       MSG_CAMPO="Informe a data da Transa‡„o"
  Case Campo="TG_DTINI":
       MSG_CAMPO="Informe a data inicial"
  Case Campo="TG_DRIVES":
       MSG_CAMPO="Selecione o drive desejado !"
       TECLA=Chr(27)+""+Chr(26)+"=Selecionar  "
EndSwitch

Monta_Prompt(MSG_CAMPO,TECLA)
Return Temp
EndProc


;*******************************************************************************
;* ROTINA PARA DELETAR ARQUIVOS                                                *
;*******************************************************************************
Proc Deleta_Arquivos()

Deleta_Arquivo(VSDGDRIVE+"\\DUPLIC.*")
Sleep 2000

EndProc ;Deleta_Arquivos() 

;*******************************************************************************
;* ROTINA PRINCIPAL                                                            *
;*******************************************************************************
AutoLib="\\Sistemas\\Cadastro\\Bib_Show,\\Sistemas\\Cadastro\\Bibliot"
LimpAguarde()

If Not IsAssigned(SYS_CODIGO_CLIENTE)  Then SYS_CODIGO_CLIENTE=""  EndIf

VSDGEMPRESA=""
VSDGTPDOCTO=""
VSDGDTINI  =BlankDate()
VSDGDTFIM  =Today()-1
VSDGDTREF  =BlankDate()

DynArray Array_Drives[]
SysInfo Drives To Array_Drives
If IsFile("OIMPDPS.sc")
   Then Play "OIMPDPS"
   Else VSDGDRIVE=SubStr(Directory(),1,2)
EndIf

While True
  ShowDialog "Importa‡„o Duplicatas" Proc "SD_Dialog"
  Trigger "OPEN","ARRIVE"
  Key "F1","ENTER","ESC","TAB",
    -104, -105, -106, -107, -108, -109, -110, -111, -112, -113, -139, -140
   @ 05,12   Height 13 Width 72

    Label  @ 00,00 "Empresa"  For "TG_EMPRESA"
    Accept @ 01,01 Width 07 "A4"  Picture "[&,#][#*#]" Tag "TG_EMPRESA" To VSDGEMPRESA
    Accept @ 01,09 Width 25 "A20" Picture "!*!" Tag "TG_NOMEMP"  To VSDGNOMEMP

    Label  @ 02,00 "Tipo do Documento"  For "TG_TPDOCTO"
    Accept @ 03,01 Width 07 "A4"  Picture "!*!" Tag "TG_TPDOCTO" To VSDGTPDOCTO
    Accept @ 03,09 Width 25 "A20" Picture "!*!" Tag "TG_NOMTPDOCTO"  To VSDGNOMTPDOCTO

    Label  @ 04,00 "Perˇodo EmissĆo de" For "TG_DTINI"
    Accept @ 05,03 Width 13 "D"  Picture "#[#];.##;.##[##]" Tag "TG_DTINI" To VSDGDTINI
    Label  @ 05,16 "at‚" For "TG_DTFIM"
    Accept @ 05,21 Width 13 "D"  Picture "#[#];.##;.##[##]" Tag "TG_DTFIM" To VSDGDTFIM

    Label  @ 06,00 "Data Transa‡„o" For "TG_DTREF"
    Accept @ 07,03 Width 13 "D"  Picture "#[#];.##;.##[##]" Tag "TG_DTREF" To VSDGDTREF

    Label  @ 00,35 "Drives:" For "TG_DRIVES"
    PickDynArrayIndex @ 01,36 Height 4 width 33
     Columns 7
      Array_Drives
       Tag "TG_DRIVES"
        To VSDGDRIVE

    Pushbutton @ 09,22 width 11 "~O~k"      OK     Default Value "Ok" Tag "YES" To BottonValue
    Pushbutton @ 09,36 width 11 "~C~ancela" CANCEL                    Tag "NO"  To BottonValue

  EndDialog
  If Not RetVal Then QuitLoop EndIf
  
  IMPDP=False
  
  Deleta_Arquivos()
  Gera_Log()
  
  If VSDGEMPRESA="" 
    Then CODEMP="0000" 
    Else CODEMP=VSDGEMPRESA
  EndIf

  ARQ_ARJ="PT_EDP_"+CODEMP+"_"+
          AlinhM(StrVal(Year(VSDGDTREF)),4) +
          AlinhM(StrVal(Month(VSDGDTREF)),2)+
          AlinhM(StrVal(Day(VSDGDTREF)),2)  +
          ".ARJ"

	Aguarde("Aguarde, descompactando o arquivo "+ARQ_ARJ)

  FileWrite PrivDir()+"funcmd.txt" From "CMD|"+"c:\\vise\\Varj.exe e -y "+VSDGDRIVE+"\\"+ARQ_ARJ+" "+VSDGDRIVE+"\\"+"\n"        
  ExecVisecf(PrivDir()+"funcmd.txt","")
  Sleep 3000

  Processa()
  Deleta_Arquivos()
  LimpAguarde()
  
  If IMPDP
     Then ARQ_IMP=VSDGDRIVE+"\\IMPORTADO_"+
                  Substr(ARQ_ARJ,1,20)+"_"+
                  Substr(Time(),1,2)  +
                  Substr(Time(),4,2)  +
                  Substr(Time(),7,2)  +
                  ".ARJ"
  
          Aguarde("Aguarde, renomeando arquivo importado")
          ExecVise("REN "+VSDGDRIVE+"\\"+ARQ_ARJ+" \""+ARQ_IMP+"\"")
          
          MSG="Opera‡ao Finalizada.// //"
          
          MSG=MSG+"Registros lidos        : "+format("W10,EIC",NR)+"//"
          MSG=MSG+"Registros gravados     : "+format("W10,EIC",regnovo)+"//"
          MSG=MSG+"Registros jaďexistentes: "+format("W10,EIC",regexiste)+"// //"
          
          MSG=MSG+"NĆo esque‡a de Verificar a Importa‡Ćo com // //o relat˘rio 78. Registro de duplicatas !"
     Else MSG="Opera‡„o Cancelada !"
  EndIf   
  Mensagem(MSG)

  FileWrite        "OIMPDPS.sc" From ";****** Variaveis de Configura‡„o Drive Padrao Vise Informatica"+"\n"
  FileWrite Append "OIMPDPS.sc" From "VSDGDRIVE="+CHR(34)+VSDGDRIVE+Chr(34)+"\n"

EndWhile
ClearAll
Release Vars All
Release Procs All
