;** Rm_1260 ********************************************************************
;*  Registro de Duplicatas - Registros importados                              *
;*******************************************************************************
;Autor           : Vise Informatica (VISERP)
;Desenvolvido    : 07/02/2012 por Anivel Augusto Rodrigues
;Alterado em		 :   /  /     por                         

;*******************************************************************************
;* Rotina p/ Selecionar e Order Registros                                      *
;*******************************************************************************
Proc Seleciona()
ClearAll

If IsTable("\\Sistemas\\Ctarec\\"+Dir_Trab+"Duplic") And
   IsTable("\\Sistemas\\Ctarec\\"+Dir_Trab+"DupBaixa")  
   Then {Ask} TypeIn "\\Sistemas\\Ctarec\\"+Dir_Trab+"Duplic" Enter
        Moveto [Numero do Lancamento] CheckPlus Example "NLAN" TypeIn "!"  
        Moveto [Codigo da Empresa   ] CheckPlus TypeIn "~VSDGEMPRESA.."
        Moveto [Numero do Documento ] CheckPlus
        Moveto [Serie do Documento  ] CheckPlus 
        Moveto [Data de Emissao     ] CheckPlus TypeIn ">=~VSDGDTINI,<=~VSDGDTFIM"
        Moveto [Data de Vencimento  ] CheckPlus
        Moveto [Valor do Documento  ] CheckPlus
        Moveto [Saldo do Documento  ] CheckPlus
        Moveto [Codigo do Destinatario] CheckPlus
        Moveto [Razao Social        ] CheckPlus
        Moveto [Documento Referente ] CheckPlus
        {Ask} TypeIn "\\Sistemas\\Ctarec\\"+Dir_Trab+"DupBaixa" Enter
        Moveto [Numero do Lancamento] Example "NLAN"
        Moveto [Data do Pagamento   ] TypeIn "Calc Max as Data do Pagamento" 
        Do_It!
        ClearAll

        {Ask} {Answer}
        Moveto [Saldo do Documento  ] TypeIn ">0.01" 
        Moveto [Data do Pagamento   ] TypeIn "Changeto Blank"
        Do_It!
        ClearAll

        {Ask} {Answer}
        Moveto [Numero do Lancamento] Example "NLAN" 
        Moveto [Codigo da Empresa   ] Example "EMPRE"
        Moveto [Numero do Documento ] Example "DOCTO"
        Moveto [Serie do Documento  ] Example "SERIE"
        Moveto [Data de Emissao     ] Example "DATEM"
        Moveto [Codigo do Destinatario ] Example "CODIG"
        Moveto [Razao Social        ] Example "NOMEC"
        Moveto [Data de Vencimento  ] Example "DATVE"
        Moveto [Valor do Documento  ] Example "VRDUP"
        Moveto [Documento Referente ] Example "NNF"
        Moveto [Data do Pagamento   ] Example "DATPG"

        {Ask} TypeIn Tabela Enter TypeIn "Fast Insert"
        Moveto [Numero do Lancamento] Example "NLAN"
        Moveto [Codigo da Empresa   ] Example "EMPRE"
        Moveto [Numero do Documento ] Example "DOCTO"
        Moveto [Serie do Documento  ] Example "SERIE"
        Moveto [Codigo              ] Example "CODIG"
        Moveto [Razao Social        ] Example "NOMEC"
        Moveto [Data de Emissao     ] Example "DATEM"
        Moveto [Data Vencimento     ] Example "DATVE"
        Moveto [Valor               ] Example "VRDUP"
        Moveto [Documento Referente ] Example "NNF"
        Moveto [Data Pagamento      ] Example "DATPG"
        Do_It!
        ClearAll
EndIf
EndProc  ; (Seleciona)

;*******************************************************************************
;* Rotina p/ processar Db temporaria                                           *
;*******************************************************************************
Proc Processa()

{Ask} TypeIn Tabela Enter TypeIn "Fast"
Moveto [Situacao           ] TypeIn "C"
Moveto [Codigo             ] TypeIn "Changeto Blank"
Moveto [Razao Social       ] TypeIn "Changeto" TypeIn "\"* * * CANCELADA * * *\""
Moveto [Valor              ] TypeIn "Changeto Blank"
Moveto [Data Vencimento    ] TypeIn "Changeto Blank"
Do_It!
ClearAll

View "\\Sistemas\\Cadastro\\Destinat"
CoEdit Tabela
Scan
  COD=[Codigo]

  Moveto "\\Sistemas\\Cadastro\\Destinat"
  Moveto [Codigo]
  Locate COD
  If RetVal
     Then CODANTER=SubStr([Conta Contabil],2,5)
          CGC     =[CGC]  
     Else CODANTER=""
          CGC     =""
  EndIf

  Moveto Tabela
  [Codigo Alternativo]=CODANTER
  [CGC               ]=CGC

EndScan
Do_It!
ClearAll

If VSDGOPCAO="1"
   Then Sort Tabela on "Codigo da Empresa","Data de Emissao","Serie do Documento","Numero do Documento","Ordem do Documento"
   Else Sort Tabela on "Codigo da Empresa","Serie do Documento","Numero do Documento","Ordem do Documento"
EndIf

EndProc    ;  (Processa)

;*******************************************************************************
;* Rotina p/ Impressao                                                         *
;*******************************************************************************
Proc Imprimir()

AGUARDE("Aguarde, processando dados")

If Not IsAssigned(NOMEMPRESA) Then NOMEMPRESA="TESTE" EndIf

View NoWindow "\\Sistemas\\Cadastro\\Empresas"
View NoWindow Tabela
CODEMP="****"
DTEMIS="****"
pag=VSDGPAGINI-1
CONT=0
INICIO=True
c     =0
TOTAL_DIA    =0
TOTAL_EMPRESA=0
DATA_ANTERIOR=BlankDate()
Scan
  If VSDGOPCAO="1"
     Then If [Codigo da Empresa  ] <> CODEMP Or
             [Data de Emissao    ] <> DTEMIS
             Then TotalDia()
                  If [Codigo da Empresa]<>CODEMP
                     Then TotalEmpresa()
                          Ler_Empresa()
                          Cabecalho()
                  EndIf
                  If [Data de Emissao]=DATA_ANTERIOR
                     Then GRUPO_DATA_ANTERIOR()
                     Else GRUPO_DATA()
                  EndIf
                  INICIO=False
                  CODEMP=[Codigo da Empresa  ]
                  DTEMIS=[Data de Emissao    ]

          EndIf
     Else If [Codigo da Empresa  ] <> CODEMP
             Then TotalEmpresa()
                  Ler_Empresa()
                  Cabecalho()
                  CODEMP=[Codigo da Empresa  ]
                  DTEMIS=[Data de Emissao    ]
                  INICIO=False
          EndIf
  EndIf
  
  Detalhe()

EndScan
If VSDGOPCAO="1" Then TotalDia() EndIf
TotalEmpresa()
ClearAll
EndProc   ;  (Imprimir)


;*******************************************************************************
;* Rotina p/ quebrar pelo grupo data                                           *
;*******************************************************************************
Proc GRUPO_DATA()
ChecaLinhaPagina()
Printline(ASP1+"Emissao: "+Format("D13",[Data de Emissao])+ASP2+"\n")
c=c+1
EndProc

;*******************************************************************************
;* Rotina p/ quebrar pelo grupo data Anterior                                  *
;*******************************************************************************
Proc GRUPO_DATA_ANTERIOR()
Printline(ASP1+"Emissao: "+Format("D13",DATA_ANTERIOR)+ASP2+"\n")
c=c+1
EndProc

;*******************************************************************************
;* Rotina p/ Ler dados da Empresa                                              *
;*******************************************************************************
Proc Ler_Empresa()
CODEMP=[Codigo da Empresa]
Moveto "\\Sistemas\\Cadastro\\Empresas"
Moveto [Codigo da Empresa]
Locate CODEMP
NOMEMP=[Razao Social Empresa]
CGC   =[CGC EMPRESA]
IE    =[IE EMPRESA]
Moveto TABELA

EndProc


;*******************************************************************************
;* Rotina p/ Totalizar o Dia                                                   *
;*******************************************************************************
Proc TotalDia()
If INICIO=False
	 Then If CONT>1
           Then ChecaLinhaPagina()
                If c=9 Then GRUPO_DATA_ANTERIOR() EndIf
								Printline(ASP1+SPACES(67)+"Total Dia.... "+Format("W12.2,EIC,AR",TOTAL_DIA)+ASP2+"\n\n")
                c=c+2
					 Else Printline(ASP1+ASP2+"\n")
        EndIf
        c=c+1
        CONT=0
        TOTAL_DIA=0
EndIf
EndProc

;*******************************************************************************
;* Rotina p/ Totalizar por Empresa                                             *
;*******************************************************************************
Proc TotalEmpresa()
If INICIO=False
   Then If VSDGOPCAO="1"
					 Then Printline(ASP1+SPACES(60)+"Total da Empresa.... "+Format("W12.2,EIC,AR",TOTAL_EMPRESA)+ASP2+"\n")
					 Else Printline(ASP1+SPACES(71)+"Total da Empresa.... "+Format("W12.2,EIC,AR",TOTAL_EMPRESA)+ASP2+"\n")
        EndIf
        TOTAL_EMPRESA=0
        Rodape()
        c=100
EndIf
EndProc

;*******************************************************************************
;* Rotina p/ Cabecalho                                                         *
;*******************************************************************************
Proc ChecaLinhaPagina()

If VSDGOPCAO="1"
   Then TOT_LINHAS=64
   Else TOT_LINHAS=53
EndIf
If C>=TOT_LINHAS
   Then Rodape()
        PrintLine(ASP1+"\f"+ASP2+"\n")
        Cabecalho()
        If VSDGOPCAO="1"
           Then If [Data de Emissao]=DATA_ANTERIOR
                   Then GRUPO_DATA_ANTERIOR()
                EndIf
        EndIf
EndIf

EndProc

;*******************************************************************************
;* Rotina p/ Cabecalho                                                         *
;*******************************************************************************
Proc Cabecalho()

pag=pag+1

Printline(ASP1+CI_15CPP+CI_6LPP+ASP2+"\n")
Printline(ASP1+Fill("-",132)+ASP2+"\n")
Printline(ASP1+Completa(NOMEMPRESA,90," ")+"Emissao.: "+
					AlinhM(LTrim(Format("D13",Today())),10)+"-"+
          AlinhM(LTrim(Time()),8)+"  Pag.:"+Format("W4,EIC",pag)+ASP2+"\n")
Printline(ASP1+Fill("-",132)+ASP2+"\n\n")
Printline(ASP1+"Empresa: "+COMPLETA(NOMEMP,40," ")+Spaces(15)+"Registro de Duplicatas de "+Format("D13",VSDGDTINI)+" ate "+Format("D13",VSDGDTFIM)+ASP2+"\n")
Printline(ASP1+"   CNPJ: "+Completa(CGC,20," ")+ "IE: "+Completa(IE,20," ")+ASP2+"\n\n")

If VSDGOPCAO="1"
	 Then
				Printline(ASP1+"Duplicata Destinatario                       CNPJ/CPF           CodAn   Vencto          Valor Referente          Pagto    Obs      "+ASP2+"\n")
				Printline(ASP1+"--------- ---------------------------------- ------------------ ----- ---------- ------------ ---------------- ---------- ---------"+ASP2+"\n")
	 Else
				Printline(ASP1+"Duplicata Destinatario                       CNPJ/CPF           CodAn  Emissao     Vencto          Valor Referente          Pagto   "+ASP2+"\n")
				Printline(ASP1+"--------- ---------------------------------- ------------------ ----- ---------- ---------- ------------ ---------------- ----------"+ASP2+"\n")
EndIf

C=10

EndProc   ; (Cabecalho)

;*******************************************************************************
;* Rotina p/ Detalhe                                                           *
;*******************************************************************************
Proc Detalhe()

ChecaLinhaPagina()
  If VSDGOPCAO="1"
     Then
					s=ASP1+COMPLETA([Numero do Documento],10," ")
					s=s+COMPLETA([Codigo],5," ")+Completa([Razao Social],28," ")+"  "
					s=s+Completa([CGC],19," ")
					s=s+Completa([Codigo Alternativo],6," ")
					s=s+Completa(Format("D13",[Data Vencimento]),10," ")+" "
					s=s+Completa(Format("W12.2,EIC,AR",[Valor]),12," ")+" "
					s=s+Completa([Documento Referente  ],17," ")
					s=s+Completa(Format("D13",[Data Pagamento]),10," ")+" "
					s=s+ASP2+"\n"
     Else
					s=ASP1+COMPLETA([Numero do Documento],10," ")
					s=s+COMPLETA([Codigo],5," ")+Completa([Razao Social],28," ")+"  "
					s=s+Completa([CGC],19," ")
					s=s+Completa([Codigo Alternativo],6," ")
					s=s+Completa(Format("D13",[Data de Emissao]),10," ")+" "
					s=s+Completa(Format("D13",[Data Vencimento]),10," ")+" "
					s=s+Completa(Format("W12.2,EIC,AR",[Valor]),12," ")+" "
					s=s+Completa([Documento Referente  ],17," ")
					s=s+Completa(Format("D13",[Data Pagamento]),10," ")+" "
					s=s+ASP2+"\n"
  EndIf
printline(s)
CONT=CONT+1
TOTAL_DIA    =TOTAL_DIA    +[Valor]
TOTAL_EMPRESA=TOTAL_EMPRESA+[Valor]
DATA_ANTERIOR=[Data de Emissao]
C=C+1
EndProc    ;  (Detalhe)

;*******************************************************************************
;* Rotina p/ Imprimir Linha 																									 *
;*******************************************************************************
Proc printline(linha)

If OPCAOPAG<>"Todas"
   Then If pag<OPCAOPAGINI Or
           pag>OPCAOPAGFIM
					 Then Return
				EndIf
EndIf
Print File ARQIMP linha
endproc


;*******************************************************************************
;* Rotina p/ Imprimir Rodape                                                   *
;*******************************************************************************
Proc Rodape()
Printline(ASP1+CI_10CPP+CI_6LPP+ASP2+"\n")
EndProc

;*******************************************************************************
;* 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"] =  27:
          Temp=False
          Switch
            Case Campo="TG_EMPRESA"       : Campo="NO"
            Case Campo="TG_DTINI"         : Campo="TG_EMPRESA"
            Case Campo="TG_DTFIM"         : Campo="TG_DTINI"
            Case Campo="TG_OPCAO"         : Campo="TG_DTFIM"
            Case Campo="TG_PAGINI"        : Campo="TG_OPCAO"
            Case Campo="YES" Or Campo="NO": Campo="TG_EMPRESA"
          EndSwitch
     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"] = 13:
          Temp=False
          If Checa_TAG()
             Then Switch
                    Case Campo="TG_EMPRESA" : Campo="TG_DTINI"
                    Case Campo="TG_DTINI"   :
                         If Not VSDGDTINI=BlankDate()
                            Then Campo="TG_DTFIM"
                         Endif
                    Case Campo="TG_DTFIM"   : Campo="TG_OPCAO"
                    Case Campo="TG_OPCAO"   : Campo="TG_PAGINI"
                        VSDGOPCAO=ControlValue("TG_OPCAO")
                        If IsBlank(VSDGOPCAO) or (VSDGOPCAO="1")
                           Then VSDGOPCAO="1"
                                VSDGNOMOPCAO="DATA EMISSŽO"
                           Else VSDGOPCAO="2"
                                VSDGNOMOPCAO="NUMERO DUPLICATA"
                        EndIf
                    Case Campo="TG_PAGINI":
                         VSDGPAGINI=ControlValue("TG_PAGINI")
                         If Not IsBlank(VSDGPAGINI)
                            Then Campo="YES"
                         EndIf
                  EndSwitch
          EndIf
          RefreshDialog
   EndSwitch
EndIf
Switch
  Case Campo="TG_DTINI":
       MSG_CAMPO="Informe a Data Inicial"
  Case Campo="TG_DTFIM":
       MSG_CAMPO="Informe a Data Final"
  Case Campo="TG_OPCAO":
       MSG_CAMPO=" 1=Data de EmissÆo  2=Numero Duplicata"
  Case Campo="TG_PAGINI":
       MSG_CAMPO="Informe a P gina Inicial do Relat¢rio"
Endswitch
Monta_Prompt(MSG_CAMPO,TECLA)
Return Temp
EndProc

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

VSDGEMPRESA =""
VSDGDTINI   =BlankDate()
VSDGDTFIM   =BlankDate()
VSDGOPCAO   =""
VSDGPAGINI  =1


While True

  ShowDialog "Registro de Duplicatas - Especial" 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 12 Width 56

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

    Label  @ 02,00 "Per¡odo Referente" For "TG_DTINI"
    Label  @ 03,00 "de" For "TG_DTINI"
    Accept @ 03,04 Width 13 "D"  Picture "#[#];.##;.##[##]" Tag "TG_DTINI" To VSDGDTINI
    Label  @ 03,17 "at‚" For "TG_DTFIM"
    Accept @ 03,22 Width 13 "D"  Picture "#[#];.##;.##[##]" Tag "TG_DTFIM" To VSDGDTFIM

    Label  @ 04,00 "Op‡„o de Relat¢rio"  For "TG_OPCAO"
    Accept @ 05,01 Width 07 "A4"  Picture "1,2" Tag "TG_OPCAO" To VSDGOPCAO
    Accept @ 05,09 Width 23 "A20" Picture "!*!" Tag "TG_NOMOPCAO" To VSDGNOMOPCAO

    Label  @ 04,32 "P gina Inicial"  For "TG_PAGINI"
    Accept @ 05,33 Width 5 "N"  Picture "#*#" Tag "TG_PAGINI" To VSDGPAGINI

    Pushbutton @ 07,14 width 11 "~O~k"      OK     Default Value "Ok" Tag "YES" To BottonValue
    Pushbutton @ 07,28 width 11 "~C~ancela" CANCEL                    Tag "NO"  To BottonValue

    @ 09,01 ?? "** Alternativo ao do modulo de DUPLICATAS **" 
  EndDialog
  If Not RetVal Then QuitLoop EndIf

  If IsBlank(VSDGDTFIM)
     Then Mensagem("Data Final Invalida !")
          Loop
  EndIf

  DISPOSITIVO()
  If OK=""  Then Loop EndIf

  AGUARDE("Aguarde, Gerando Relat¢rio")

  Tabela=Cria_Temp(PrivDir())
  Empty "\\Base\\Sistemas\\Vendas\\RM_0260"
  Copy "\\Base\\Sistemas\\Vendas\\RM_0260" Tabela

  Monta_Dir_Trab(VSDGDTINI,VSDGDTFIM)
  While Novo_Dir_Trab()
    Seleciona()
  EndWhile
  Processa()

  If IsEmpty(Tabela)
     Then MENSAGEM("N„o existem registros a processar")
          Delete Tabela
          Loop
  EndIf

  ASP1=""
  ASP2=""
  ARQIMP = PrivDir()+"REGDUP.TXT"
  Switch
    Case OK="A": ARQIMP = DIREPORT+ARQUIVO+".TXT"
    Case OK="V": ASP1   ="\""
                 ASP2   ="\""
  EndSwitch
  If IsFile(ARQIMP) 
     Then Deleta_Arquivo(ARQIMP)
  EndIf
  If IsTable("Answer") Then Delete "Answer" EndIf

  AGUARDE("Imprimindo")
  Imprimir()

  If OK="V"
     Then {Tools} {Copy} {Table} {\\Base\\Sistemas\\Estoque\\Rm_tx160} {Answer} ClearAll
          {Tools} {ExportImport} {Import} {ASCII} {AppendDelimited} TypeIn ARQIMP Enter
          {Answer} ClearAll
          OPCAOPAG="Todas"
          IMPRIREL("Answer","R")
          Deleta_Arquivo(ARQIMP)
     Else Mensagem("Impress„o Concluida !")
          If OK="I"
						 Then ;---- Imprime Arquivo Impressao ------------------------------------------------
									ImpriArq(ARQIMP)
					EndIf
	EndIf

  If IsTable("Answer")
     Then Delete "Answer"
  EndIf
  If IsTable(Tabela)
     Then Delete Tabela
  EndIf


EndWhile
ClearAll
Release Vars All
Release Procs All
