;** APSPC **********************************************************************
;* Apura‡Æo de PIS/COFINS - Saidas                                             *
;*******************************************************************************
;Autor           : Vise Informatica (VISERP)
;Desenvolvido    : 08/04/2011 por Bruno Carvalho
;Ultima Alteracao: 20/08/2012 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes desprezar item notai cancalado
;Ultima Alteracao: 18/09/2012 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes Novo Layout de relatorios e op‡äes de filtro

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

;****** Vendas *****************************************************************
If IsTable("\\Sistemas\\Vendas\\"+Dir_Trab+"NotaC") And
   IsTable("\\Sistemas\\Vendas\\"+Dir_Trab+"NotaI")
   Then {Ask} TypeIn "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaC" Enter
         Moveto [Codigo da Empresa      ] CheckPlus Example "cemp" TypeIn ", ~VSDGEMPRESA.."
         Moveto [Numero do Documento    ] CheckPlus Example "ndoc"
         Moveto [Serie do Documento     ] CheckPlus Example "sdoc"
         Moveto [Nome Fantasia Empresa  ] CheckPlus
         Moveto [Tipo do Documento      ] CheckPlus TypeIn VSDGTPDOC
         Moveto [Data de Emissao        ] TypeIn ">=~VSDGDTINI,<=~VSDGDTFIM"
         Switch
           Case VSDGOPERACAO=1 : Moveto [Descricao da Destinacao] TypeIn "..VEND.. or ..DEVOL.."
           Case VSDGOPERACAO=2 : Moveto [Valor Servico          ] TypeIn ">0"
         EndSwitch
         Moveto [Tipo Movimento Estoque ] TypeIn "S"
         Moveto [Situacao               ] TypeIn "Not C"
        {Ask} TypeIn "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaI" Enter
         Moveto [Codigo da Empresa      ] Example "cemp"
         Moveto [Numero do Documento    ] Example "ndoc"
         Moveto [Serie do Documento     ] Example "sdoc"
         Moveto [CFO                    ] CheckPlus TypeIn VSDGCFOP
         Moveto [Preco Total            ] CheckPlus
         Moveto [Valor Desconto Total   ] CheckPlus
         Moveto [Valor Frete Total      ] CheckPlus
         Moveto [Valor Seguro Total     ] CheckPlus
         Moveto [Valor OutDesp Total    ] CheckPlus
         Moveto [PIS_CST                ] CheckPlus TypeIn "~VSDGCST"
         Moveto [PIS_Aliquota           ] CheckPlus
         Moveto [PIS_BC                 ] CheckPlus
         Moveto [PIS_Valor              ] CheckPlus                     
         Moveto [COFINS_CST             ] CheckPlus TypeIn "~VSDGCST"
         Moveto [COFINS_Aliquota        ] CheckPlus
         Moveto [COFINS_BC              ] CheckPlus
         Moveto [COFINS_Valor           ] CheckPlus
         Moveto [Situacao_Item          ] TypeIn "Not C"
         Do_It!
         ClearAll
EndIf

EndProc  ;  (Seleciona)

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

View Tabela
Coedit "Answer" 
Scan For [Codigo da Empresa]<>""

  vr_acresc  =[Valor Frete Total]+[Valor Seguro Total]+[Valor OutDesp Total]
  Vr_contabil=([Preco Total]-[Valor Desconto Total])+vr_acresc
  
  For i From 1 to 2 

    If [Answer->PIS_CST]=[Answer->COFINS_CST]
       Then i=3
            cst            =[PIS_CST        ] 
            PIS_Aliquota   =[PIS_Aliquota   ]
            COFINS_Aliquota=[COFINS_Aliquota] 
       Else Switch
              case i=1: cst            =[PIS_CST        ]
                        PIS_Aliquota   =[PIS_Aliquota   ]
                        COFINS_Aliquota=BlankNum()
              case i=2: cst            =[COFINS_CST     ]
                        COFINS_Aliquota=[COFINS_Aliquota]
                        PIS_Aliquota   =BlankNum()
            EndSwitch
    EndIf

    empr=[Answer->Codigo da Empresa    ]
    ndoc=[Answer->Numero do Documento  ]
    tdoc=[Answer->Tipo do Documento    ]
    sdoc=[Answer->Serie do Documento   ]
    cfop=[Answer->CFO                  ]

    Switch
      Case VSDGCODMODELO="01" :         sdoc="" ndoc=""  
      
      Case VSDGCODMODELO="02" : tdoc="" sdoc="" ndoc=""          
       
      Case VSDGCODMODELO="03" : tdoc="" sdoc="" ndoc="" cfop=""

      Case VSDGCODMODELO="04" :
       
    EndSwitch

    Moveto Tabela
    Moveto [Numero do Lancamento]
    Locate "",empr,tdoc,sdoc,ndoc,cfop,cst,"",PIS_Aliquota,COFINS_Aliquota                        
    If Not Retval
       Then
            End Down
            [Numero do Lancamento ]=""
            [Codigo da Empresa    ]=empr
            [Tipo do Documento    ]=tdoc
            [Serie do Documento   ]=sdoc
            [Numero do Documento  ]=ndoc
            [CFOP                 ]=cfop
            [CST                  ]=cst
            [NAT_BC_CRED          ]=""  
            [PIS_Aliquota         ]=PIS_Aliquota
            [COFINS_Aliquota      ]=COFINS_Aliquota      
    EndIf

    If i=3 Or i=1
       Then 
            [Valor Item     ]=[Answer->Preco Total          ]
            [Valor Desconto ]=[Answer->Valor Desconto Total ]
            [Valor Acrescimo]=vr_acresc
            [Valor Contabil ]=vr_contabil
    EndIf   

    If i=1 Or i=3
       Then [PIS_BC   ]=[PIS_BC   ]+[Answer->PIS_BC]
            [PIS_Valor]=[PIS_Valor]+[Answer->PIS_Valor]
    EndIf        
    If i=2 Or i=3
       Then [COFINS_BC   ]=[COFINS_BC   ]+[Answer->COFINS_BC]
            [COFINS_Valor]=[COFINS_Valor]+[Answer->COFINS_Valor]
    EndIf   
    UnLockRecord
    
    Moveto "Answer"
    If i=3 Then  QuitLoop EndIf

  EndFor
  
EndScan
Do_It!
ClearAll
Delete "Answer"

;******* Ajusta dados do cadastro de Empresas ******
{Ask} {\\Sistemas\\Cadastro\\Empresas}
Moveto [Codigo da Empresa    ] Example "empr"
Moveto [Nome Fantasia Empresa] Example "nome"
{Ask} TypeIn Tabela Enter TypeIn "Fast"
Moveto [Codigo da Empresa    ] Example "empr"
Moveto [Nome Fantasia Empresa] TypeIn "Changeto _nome"
Do_It!
ClearAll

EndProc  ; (Processa)


;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc SD_Dialog2(Disparo,Campo,Evento,Elemento)
Private Disparo,Campo,Evento,Elemento,Temp,MSG_CAMPO,TECLA

Temp=True
MSG_CAMPO=""
TECLA    =""
If Disparo="OPEN"    Then AoCriarShowDialog() EndIf
If Disparo="SELECT"  
   Then VSDGOPRELATORIO=ControlValue("TG_OPRELATORIO")
        AcceptDialog 
EndIf
If Disparo="EVENT" And Evento["Type"]="KEY" Then
   Switch
     Case Evento["KeyCode"] = 9    : Temp=False
     Case Evento["KeyCode"] = 27   : CancelDialog
     Case Evento["KeyCode"] = 13   :
       VSDGOPRELATORIO=ControlValue("TG_OPRELATORIO")
       AcceptDialog
   EndSwitch
EndIf
Switch
  Case Campo="TG_OPRELATORIO":
     MSG_CAMPO="Selecione o op‡„o desejada !"
     TECLA    ="=Selecionar  "
Endswitch
Monta_Prompt(MSG_CAMPO,TECLA)
Return Temp
EndProc

;*******************************************************************************
;* Rotina Impressao                                                            *
;*******************************************************************************
Proc Relatorios()

ShowDialog "Sele‡Æo" Proc "SD_Dialog2"
 Trigger "OPEN","SELECT"  
 Key "F1","ENTER","ESC","TAB"
  @ 01,01 Height 10 Width 74

  Label @ 00,00 "Modelos de Relat¢rios"  For "TG_OPRELATORIO"
  PickDynArray @1,01 Height 6 width 69
   Columns 1
    Array_OpRelatorios
     Tag "TG_OPRELATORIO"
      To VSDGOPRELATORIO

EndDialog
If RetVal
   Then Return True
   Else Return False
EndIf

EndProc ;(Relatorios)

;************************************
;* ROTINA PARA Ler/Gravacao Opcao   *
;************************************
Proc ConfOpcoes(Opcao)
Private Opcao

Switch
  Case Opcao="Ler":
       DynArray Array_OpRelatorios[]
       Array_OpRelatorios[01]="01-Saidas/Sint‚tico por TpDocto/CFOP/CST/%PIS e ou COFINS"
       Array_OpRelatorios[02]="02-Saidas/Sint‚tico por         CFOP/CST/%PIS e ou COFINS"
       Array_OpRelatorios[03]="03-Saidas/Sint‚tico por              CST/%PIS e ou COFINS"
       Array_OpRelatorios[04]="04-Saidas/Anal¡tico por documento                           "

  Case Opcao="Gravar":
EndSwitch
EndProc ;

;*******************************************************************************
;* Rotina                                                                      *
;*******************************************************************************
Proc SD_Dialog(Disparo,Campo,Evento,Elemento)
Private Disparo,Campo,Evento,Elemento,Temp,MSG_CAMPO,TECLA

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:
          Switch
            Case Campo="TG_CODMODELO" : If RELATORIOS()
                                           Then VSDGCODMODELO=SubStr(Array_OpRelatorios[VSDGOPRELATORIO],1,02) 
                                                VSDGMODELO   =SubStr(Array_OpRelatorios[VSDGOPRELATORIO],4,70)
                                        EndIf   
            OtherWise                 : Dialog_F1()
          EndSwitch  
     Case Evento["KeyCode"] =  27:
          Temp=False
          Switch
            Case Campo="TG_EMPRESA"       : Campo="NO"
            Case Campo="TG_TPDOC"         : Campo="TG_EMPRESA"
            Case Campo="TG_CFOP"          : Campo="TG_TPDOC"
            Case Campo="TG_CST"           : Campo="TG_CFOP"
            Case Campo="TG_DTINI"         : Campo="TG_CST"
            Case Campo="TG_DTFIM"         : Campo="TG_DTINI"
            Case Campo="TG_OPERACAO"      : Campo="TG_DTFIM"  
            Case Campo="TG_CODMODELO"     : Campo="TG_OPERACAO"  
            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_TPDOC"
                    Case Campo="TG_TPDOC"         : Campo="TG_CFOP"
                     VSDGTPDOC=ControlValue("TG_TPDOC")
                    Case Campo="TG_CFOP"          : Campo="TG_CST"
                     VSDGCFOP=ControlValue("TG_CFOP")
                    Case Campo="TG_CST"           : Campo="TG_DTINI"
                     VSDGCST=ControlValue("TG_CST")
                    Case Campo="TG_DTINI"         : Campo="TG_DTFIM"
                    Case Campo="TG_DTFIM"         : Campo="TG_OPERACAO"
                    Case Campo="TG_OPERACAO"      : Campo="TG_CODMODELO"
                    Case Campo="TG_CODMODELO"     : Campo="YES"
                     VSDGCODMODELO=AlinhM(ControlValue("TG_CODMODELO"),2)
                     VSDGMODELO=""
                     For wc From 1 To DynArraySize(Array_OpRelatorios) 
                       If VSDGCODMODELO=SubStr(Array_OpRelatorios[wc],1,02)
                          Then VSDGMODELO   =SubStr(Array_OpRelatorios[wc],4,70)
                               QuitLoop
                       EndIf        
                     EndFor
                    
                  EndSwitch
          EndIf
          RefreshDialog
   EndSwitch
EndIf
Switch
  Case Campo="TG_DTFIM"     : MSG_CAMPO="Informe a Data Final"
  Case Campo="TG_TPDOC"     : MSG_CAMPO="Informe um Tipo de documento.. ou Em Branco=TODOS"
  Case Campo="TG_CFOP"      : MSG_CAMPO="Informe um CFOP.. ou Em Branco=TODOS"
  Case Campo="TG_CST"       : MSG_CAMPO="Informe um CST ou Em Branco=TODOS"
  Case Campo="TG_OPERACAO":
       MSG_CAMPO="Selecione uma op‡„o !"
       TECLA    ="=Selecionar  "
  Case Campo="TG_CODMODELO" : TECLA="F1=Consulta"
Endswitch
Monta_Prompt(MSG_CAMPO,TECLA)
Return Temp
EndProc

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

VSDGEMPRESA =""
VSDGTPDOCTO =""
VSDGCFOP    =""
VSDGCST     =""
VSDGDTINI   =BlankDate()
VSDGDTFIM   =BlankDate()

VSDGCODMODELO     = ""
VSDGMODELO        = ""

ConfOpcoes("Ler")

While True

  ShowDialog "Apura‡Æo PIS/COFINS - Saidas" 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 74

    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  @ 00,34 "TpDocto"  For "TG_TPDOC"
    Accept @ 01,35 Width 08 "A6"  Picture "!*!" Tag "TG_TPDOC" To VSDGTPDOC

    Label  @ 00,44 "CFOP"  For "TG_CFOP"
    Accept @ 01,44 Width 08 "A5"  Picture "!*!" Tag "TG_CFOP" To VSDGCFOP

    Label  @ 00,53 "CST"  For "TG_CST"
    Accept @ 01,53 Width 07 "A2"  Picture "#*#" Tag "TG_CST" To VSDGCST 

    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 "Opera‡äes " For "TG_OPERACAO"
    RadioButtons @ 05,00 Height 1 Width 60
      "~1~ Vendas e devolu‡äes",
      "~2~ Servi‡os",
      "~3~ Todas"
        Tag "TG_OPERACAO"
        To VSDGOPERACAO

    Label  @ 06,00  "Modelo de Relat¢rio"  For "TG_CODMODELO"
    Accept @ 07,01  Width 06 "A2"  Picture "#*#" Tag "TG_CODMODELO" To VSDGCODMODELO
    Accept @ 07,06  Width 64 "A60"  Picture "!*!" Tag "TG_MODELO" To VSDGMODELO        

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

  EndDialog
  If Not RetVal Then QuitLoop EndIf
  If Not Usuario_Vendedor() Then Loop EndIf  

  If IsBlank(VSDGDTFIM)
     Then Mensagem("Data Final Invalida !")
          Loop
  EndIf
  If IsBlank(VSDGCODMODELO)
     Then Mensagem("Modelo relat¢rio invalido !")
          Loop
  EndIf

  DISPOSITIVO()
  If OK=""  Then Loop EndIf

  AGUARDE("Aguarde, gerando o relat¢rio")
  
  Tabela=Cria_Temp(PrivDir())
  Copy "\\Base\\Sistemas\\Icms_Ipi\\apspc" Tabela
  Empty(Tabela)

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

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

  Filtro="Filtro = "
  Switch
    Case VSDGOPERACAO=1 : Filtro=Filtro+"Operacao=Vendas e Devolucoes  "
    Case VSDGOPERACAO=2 : Filtro=Filtro+"Operacao=Servicos  "
    OtherWise           : Filtro=Filtro+"Operacao=TODAS  "
  EndSwitch

  Switch
    Case VSDGTPDOC<>""  : Filtro=Filtro+"TPDOC="+VSDGTPDOC+"  "
    OtherWise           : Filtro=Filtro+"TPDOC=TODOS  "
  EndSwitch

  Switch
    Case VSDGCFOP <>""  : Filtro=Filtro+" CFOP="+VSDGCFOP +"  "
    OtherWise           : Filtro=Filtro+" CFOP=TODOS  "
  EndSwitch

  Switch
    Case VSDGCST  <>""  : Filtro=Filtro+"  CST="+VSDGCST  +"  "
    OtherWise           : Filtro=Filtro+"  CST=TODOS  "
  EndSwitch
  
  Switch
    Case VSDGCODMODELO="01" : IMPRIREL(Tabela,"R")
    Case VSDGCODMODELO="02" : IMPRIREL(Tabela,"R")
    Case VSDGCODMODELO="03" : IMPRIREL(Tabela,"R")
    Case VSDGCODMODELO="04" : IMPRIREL(Tabela,"1")
    OtherWise:
      Mensagem("Modelo relat¢rio invalido !")
  EndSwitch
  
  Delete Tabela
       
EndWhile
ClearAll
Release Vars All
Release Procs All
