;** SW_CONSV *******************************************************************
;*  Lista das Vendas                                                           *
;*******************************************************************************
;Autor           : Vise Informatica (VISERP)
;Desenvolvido    : 07/06/2016 por Anivel Augusto Rodrigues
;Ultima Alteracao: 08/06/2016 por Bruno Carvalho 
;Motivo Alteracao: Adicionado verifica‡Æo de diret¢rio na proc slcarregalista() 
;Ultima Alteracao: 04/01/2017 por Rafael Matos
;Motivo Alteracao: Ajustes slcarregalista()  
;Ultima Alteracao: 30/03/2017 por Anivel Augusto Rodrigues
;Motivo Alteracao: Ajustes dados da lista, tipo movimento
;Ultima Alteracao: 05/02/2019 por Bruno Carvalho
;Motivo Alteracao: Ajustes slcarregalista() -> Retirando a linha comentada da [Descricao da Destinacao] e [Tipo Movimento Estoque]
;                  Se necess rio comentar campos apenas para clientes espec¡ficos (conforme solicita‡Æo)         
;Ultima Alteracao: 05/02/2019 por Bruno Carvalho
;Motivo Alteracao: Ajustes ao selecionar as notas de saida, verificando destinacao se [Atualiza Estoque]
;Ultima Alteracao: 24/12/2019 por Bruno Carvalho
;Motivo Alteracao: Adicionado Bib_Proc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
Proc slsd_dialog(Disparo,Campo,Evento,Elemento)
Private Disparo,Campo,Evento,Elemento, 
        temp, msg_campo, tecla
 
TECLA   =" Esc=Retornar  "
MSGCAMPO=""
Temp    =True

If (Disparo="EVENT" And Evento["Type"]="KEY" And Evento["KeyCode"] = 120 And Campo="TG_LISTA") Or 
   (Disparo="SELECT" And Campo="TG_LISTA")
    Then 
          switch
            case sltiposelecao="" : ; sem item            
            case sltiposelecao="U": ; um unico item
            case sltiposelecao="M": ; returna uma lista de itens
              slarraylista[ControlValue("TG_LISTA")]=slsetaxselecionado(slarraylista[ControlValue("TG_LISTA")])
          endswitch 
EndIf

If Disparo="OPEN"  
   Then AoCriarShowDialog()
        TiraSombraShowDialog()
EndIf
If Disparo="EVENT" And Evento["Type"]="KEY" Then
   Switch
     Case Evento["KeyCode"] = 9: Temp=False

;    Case Evento["KeyCode"] = ?: 
;         slexcluiitemlista(ControlValue("TG_LISTA"))
          
     Case Evento["KeyCode"] =  27: 
          Temp=False
          Switch 
            Case Campo="TG_LISTA"     :
                switch
                  case sltiposelecao="" : CancelDialog
                  case sltiposelecao="U": CancelDialog
                  case sltiposelecao="M": Campo="NO"
                endswitch 
            Case Campo="YES" Or Campo="NO" : Campo="TG_LISTA"
          EndSwitch
          
     Case Evento["KeyCode"] = 13: 
          Temp=False
          Switch 
            Case Campo="TG_LISTA"     :
              switch
                case sltiposelecao="" : 
                case sltiposelecao="U": AcceptDialog
                case sltiposelecao="M": Campo="YES"
              endswitch 
          EndSwitch
          RefreshDialog
          
   EndSwitch
EndIf  


Switch                
  Case Campo="TG_LISTA":
    switch
      case sltiposelecao="" : ; sem item
        MSG_CAMPO=""

      case sltiposelecao="U": ; um unico item
        MSG_CAMPO="Selecione o item desejado !"

      case sltiposelecao="M": ; returna uma lista de itens
        TECLA="[Espa‡o]=Marca/Desmarca  "

    endswitch 
EndSwitch
TECLA=TECLA+"/Home/End/PgDn/PgUp=Paginar  "

MontaRodapeSD(MSGCAMPO, TECLA)

Return Temp
EndProc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slcrialista()

If IsAssigned(slarraylista)        then Release Vars slarraylista         endIf
If IsAssigned(slarraylistacoluna)  then Release Vars slarraylistacoluna   endIf

Dynarray slarraylista[]
Dynarray slarraylistacoluna[]

;--nomecoluna, titulocoluna, tipocoluna --

;         1         2         3         4         5         6         7         8
;12345678901234567890123456789012345678901234567890123456789012345678901234567890
;
;999999 1234 1234567890 99/99/9999 123456789012 X

                       ;         1         2         3         4         5         6         7         8
                       ;12345678901234567890123456789012345678901234567890123456789012345678901234567890

slarraylistacoluna[01]="nc[Sequencia]             ,tc[Seq]             ,tac[L] ,tdc[A] ,tmc[03] ,fc[W03,AL]"
slarraylistacoluna[02]="nc[Data de Emissao]       ,tc[Emissao]         ,tac[C] ,tdc[D] ,tmc[08] ,fc[D10]"
slarraylistacoluna[03]="nc[TpMov]                 ,tc[TpOper]          ,tac[L] ,tdc[A] ,tmc[06] ,fc[W06,AL]"
slarraylistacoluna[04]="nc[Pessoa]                ,tc[Pessoa]          ,tac[L] ,tdc[A] ,tmc[30] ,fc[W30,AL]  , totc[Count, Pessoa]"
slarraylistacoluna[05]="nc[Quantidade]            ,tc[Quantidade]      ,tac[R] ,tdc[N] ,tmc[10] ,fc[W10.1,EIC]"
slarraylistacoluna[06]="nc[Unidade]               ,tc[UN]              ,tac[L] ,tdc[A] ,tmc[02] ,fc[W02,AL]"
slarraylistacoluna[07]="nc[Preco Unitario]        ,tc[Pre‡oUnit]       ,tac[R] ,tdc[$] ,tmc[10] ,fc[W10.2,EIC]"
                                                      
slmontatitulo()

slcc=0
slcs=0

endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slmontatitulo()
private posini, wc, ms, pos1, pos2, tmc, tc, tac, vr

posini=0
foreach wc in slarraylistacoluna 
  ms=slarraylistacoluna[wc]
  
  pos1=Search(",tmc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tmc =NumVal(Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5))))

  posini=posini+tmc
endforeach 

sltitl=fill(" ",posini+1)

posini=1
For wc from 1 to DynarraySize(slarraylistacoluna)
  ms=slarraylistacoluna[wc]
  
  pos1=Search(",tmc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tmc =NumVal(Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5))))

  pos1=Search(",tc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tc=Ltrim(RTrim(substr(ms, pos1+4, pos2-pos1-4)))
  if tc="" then tc=" " endif

  pos1=Search(",tac[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tac =Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5)))   

  switch
    case tac<>"": vr=format("W"+strval(tmc)+",A"+tac,tc)
    otherwise   : vr=format("W"+strval(tmc)+",AL"   ,tc)
  endswitch
  
  ms=sltitl
  sltitl=substr(ms,1,posini)
  sltitl=sltitl+vr
  sltitl=sltitl+substr(ms,(posini+tmc),len(ms)-(posini+tmc))
  
  posini=posini+tmc+1
endfor 

endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc sladdlistacoluna(coluna, valor, s)
private coluna, valor, s, posini, wc, ms, pos1, pos2, tmc, tdc, fc, vr

posini=0
For wc from 1 to DynarraySize(slarraylistacoluna)
  ms=slarraylistacoluna[wc]
  
  pos1=Search(",tmc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tmc =NumVal(Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5))))

  if Search("nc["+ltrim(rtrim(coluna))+"]",ms)>0
     then 
          pos1=Search(",tdc[",ms)
          pos2=SearchFrom("]",ms,pos1)
          tdc=Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5)))
          
          pos1=Search(",fc[",ms)
          pos2=SearchFrom("]",ms,pos1)
          fc=Ltrim(RTrim(substr(ms, pos1+4, pos2-pos1-4)))
                    
          switch
            case tdc="A": vr=format(fc,valor)
            case tdc="$": vr=format(fc,valor)
            case tdc="S": vr=format(fc,valor)
            case tdc="N": vr=format(fc,valor)
            case tdc="D": vr=format(fc,valor)
          endswitch

          ms=s
          s=substr(ms,1,posini)
          s=s+vr
          s=s+substr(ms,(posini+tmc),len(ms)-(posini+tmc))
          
          
          return s
  endif   

  posini=posini+tmc+1
EndFor

endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc Sltotcoluna(ms, valor ,posini, tmc, fc)
private ms, valor, tmc, fc, pos1, pos2, totc, tptotc, coluna, vr

vr=""

pos1=Search(",totc[",ms)
pos2=SearchFrom("]",ms,pos1)
totc=Ltrim(RTrim(substr(ms, pos1+6, pos2-pos1-6)))

if totc<>""
   then
        pos1=Search(",",totc)
        tptotc=Ltrim(RTrim(substr(totc, 1, pos1-1)))
        coluna=Ltrim(RTrim(substr(totc, pos1+1, len(totc))))
        
        switch
          case upper(tptotc)="COUNT"  : slcc=slcc+1       vr=slcc
          case upper(tptotc)="SUM"    : slcs=slcs+valor   vr=slcs
        endswitch
        
endif
ms=sltot
sltot=substr(ms,1,posini+1)
sltot=sltot+format(fc,vr)
sltot=sltot+substr(ms,(posini+tmc),len(ms)-(posini+tmc))

endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slcarregalista()
private ntable, wc, s, i, MM, AAAA, dtini, dtfim, dir_trab,tpmov

LimpaRodape(0)
Aguarde("Verificando compras")

ntable=table()
wc    =0

dtfim=today()
dtini=today()

for i from 1 to PARAM_NMES_CONSULTA
  dtini=Primeiro_Dia_Data(Primeiro_Dia_Data(dtini)-1)
endfor
if dtini=dtfim then dtini=blankdate() endif

MM     =month(dtfim)
AAAA   = year(dtfim)

i =0
while true          

  switch
    case i=0 : Dir_Trab= ""
    
    otherwise: Dir_Trab="Fechames\\"+AlinhM(StrVal(AAAA),4)+"_"+AlinhM(StrVal(MM),2)+"\\"

  endswitch

  If DirExists("\\Sistemas\\Vendas\\"+Dir_Trab)>0 And IsTable("\\Sistemas\\Vendas\\"+Dir_Trab+"NotaI")
     Then 
          Aguarde("Verificando vendas  "+Dir_Trab)

          {Ask} {\\Sistemas\\Vendas\\Destin}
          Moveto [Codigo da Destinacao   ] Example "CodD"
          Moveto [Atualiza Estoque       ] TypeIn "S"
          {Ask} TypeIn "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaC" Enter
          Moveto [Codigo da Empresa      ] Example "cemp" 
          Moveto [Numero do Documento    ] Example "ndoc"
          Moveto [Serie do Documento     ] Example "sdoc"
          Moveto [Data de Emissao        ] CheckPlus TypeIn ">=~dtini, <=~dtfim"
          Moveto [Codigo                 ] CheckPlus
          Moveto [Razao Social           ] CheckPlus
          Moveto [Descricao da Destinacao] TypeIn "..VEND.. or ..SERV.. or ..SAIDA.."
          Moveto [Tipo Movimento Estoque ] TypeIn "S"
          Moveto [Codigo da Destinacao   ] Example "CodD"
          Moveto [Descricao da Destinacao] CheckPlus
          Moveto [Tipo Movimento Estoque ] CheckPlus
          Moveto [Situacao               ] TypeIn "Not C"
          {Ask} TypeIn "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaI" Enter
          Moveto [Codigo da Empresa      ] Example "cemp"
          Moveto [Numero do Documento    ] CheckPlus Example "ndoc"
          Moveto [Serie do Documento     ] Example "sdoc"
          Moveto [Codigo do Item         ] CheckPlus TypeIn "~item"
          Moveto [Unidade Fiscal         ] CheckPlus
          Moveto [Quantidade             ] CheckPlus
          Moveto [Preco Unitario         ] CheckPlus
          Moveto [Situacao_Item          ] TypeIn "Not C"
          Do_It!

          if not isempty("Answer")
             then
                  Sort "Answer" on "Data de Emissao" D, "Numero do Documento"
                  scan
             
                    s=Fill(" ",len(sltitl))
                    wc=wc+1
              
                    s=sladdlistacoluna("Sequencia", AlinhM(strval(wc),3), s)
                    s=sladdlistacoluna("Data de Emissao", [Data de Emissao], s)
                    
                    switch
                      case [Tipo Movimento Estoque ]="S" and search("DEVOL",[Descricao da Destinacao])>0: tpmov="S-DEV"
                      case [Tipo Movimento Estoque ]="S" and search("VEND" ,[Descricao da Destinacao])>0: tpmov="S-VEND"
                      case [Tipo Movimento Estoque ]="S"                                                : tpmov="S-OUT"

                      case [Tipo Movimento Estoque ]="E" and search("DEVOL",[Descricao da Destinacao])>0: tpmov="E-DEV"
                      case [Tipo Movimento Estoque ]="E"                                                : tpmov="E-OUT"

                      otherwise                                                                         : tpmov="??????" 
                    endswitch
                    s=sladdlistacoluna("TpMov", tpmov, s)
                    s=sladdlistacoluna("Pessoa", Completa(Substr([Razao Social],1,24),24," ")+"-"+Completa([Codigo],4," "), s)
                    s=sladdlistacoluna("Quantidade", [Quantidade], s)
                    s=sladdlistacoluna("Unidade", Rtrim([Unidade Fiscal]), s)
                    s=sladdlistacoluna("Preco Unitario", [Preco Unitario], s)
              
                    slarraylista[wc]=s
                    
                    If wc>=999
                       Then MSG = "Sr. USUARIO. // //"
                            MSG = MSG +"MEMORIA INSUFICIENTE. (DOS/EMS)//"
                            MSG = MSG +"Somente parte das registros serÆo mostrados."
                            Mensagem(MSG)
                           
                            quitloop
                    EndIf
                  Endscan
          endif
                       
          Moveto "Answer"                                ClearImage
          Moveto "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaC" ClearImage
          Moveto "\\Sistemas\\Vendas\\"+Dir_Trab+"NotaI" ClearImage
  EndIf   

  If wc>=999
    Then quitloop
  EndIf

  if i=PARAM_NMES_CONSULTA then quitloop endif

  i =i+1

  MM=MM-1
  if MM=0 then MM=12 AAAA=AAAA-1 endif

endwhile
 
if wc>20
   then slhl=20
   else if wc>2
           then slhl=wc
           else slhl=5
        endif   
endif           

switch
  case sltiposelecao="" : ; sem item
       slhj=slhl+4
  case sltiposelecao="U": ; um unico item
       slhj=slhl+4
  case sltiposelecao="M": ; returna uma lista de itens
       slhj=slhl+7
endswitch 

;sltotcoluna()

moveto ntable

LimpaRodape(0)

endproc


;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slexcluiitemlista(indice)
private indice, wcr, wc                     

Release Vars slarraylistaretorno
Dynarray slarraylistaretorno[]

wcr=0
foreach wc in slarraylista
  if wc<>indice
     then wcr=wcr+1
          slarraylistaretorno[wcr]=slarraylista[wc]
  endif
endforeach 

Release Vars slarraylista
Dynarray slarraylista[]

foreach wc in slarraylistaretorno
   slarraylista[wc]=slarraylistaretorno[wc]
endforeach

Release Vars slarraylistaretorno
endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slsetaxselecionado(s)
private s, posini, wc, ms, pos1, pos2, tmc, vr                
     
posini=0
For wc from 1 to DynarraySize(slarraylistacoluna)
  ms=slarraylistacoluna[wc]
  
  pos1=Search(",tmc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tmc =NumVal(Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5))))

  if Search("nc[XSelecionado]",ms)>0
     then 
          vr=slvalorlistacoluna("XSelecionado", s)
          if vr="X"
             then vr=" "
             else vr="X"
          endIf
          
          ms=s
          s=substr(ms,1,posini)
          s=s+vr
          s=s+substr(ms,(posini+2),len(ms)-(posini+1))
          
          return s
  endif   

  posini=posini+tmc+1
EndFor

endproc


;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slvalorlistacoluna(coluna, s)
private coluna, s, posini, wc, ms, pos1, pos2, tmc, tdc, s1

posini=0
For wc from 1 to DynarraySize(slarraylistacoluna)
  ms=slarraylistacoluna[wc]
  
  pos1=Search(",tmc[",ms)
  pos2=SearchFrom("]",ms,pos1)
  tmc =NumVal(Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5))))

  if Search("nc["+ltrim(rtrim(coluna))+"]",ms)>0
     then 
          pos1=Search(",tdc[",ms)
          pos2=SearchFrom("]",ms,pos1)
          tdc=Ltrim(RTrim(substr(ms, pos1+5, pos2-pos1-5)))
          
          s1=LTrim(RTrim(substr(s,posini+1,tmc)))
          
          switch
            case tdc="A": s1=Rtrim(Ltrim(s1))
            case tdc="$": s1=numval(s1) 
            case tdc="S": s1=numval(s1)
            case tdc="N": s1=numval(s1)
            case tdc="D": s1=Dateval(s1)
          endswitch
          
          return s1
  endif   

  posini=posini+tmc+1
EndFor

endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slvalidaitemselecionado()
private wc, wcr

If IsAssigned(slarraylistaretorno) then Release Vars slarraylistaretorno  endIf
Dynarray slarraylistaretorno[]

switch
  case sltiposelecao="" : ; sem item
    return true
  
  case sltiposelecao="U": ; um unico item
    if DynarraySize(slarraylista)>0
       then return true
    endif
  
  case sltiposelecao="M": ; returna uma lista de itens
    wcr=0
    For wc from 1 to DynarraySize(slarraylista)
      if slvalorlistacoluna("XSelecionado", slarraylista[wc])="X"
         then wcr=wcr+1
              slarraylistaretorno[wcr]=slarraylista[wc]
      endif
    EndFor
     
    if DynarraySize(slarraylistaretorno)>0
       then return true
    endif
 
endswitch 


return false
endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slshowlista()
private lj, cj, wj, titj, nlb 



;-- Indicar qual tipo de sele‡Æo para a lista! ---------------------------------
;sltiposelecao="M" ; returna uma lista de itens
;sltiposelecao="U" ; um unico item
sltiposelecao=""  ; sem item

;-- Indicar a altura, largura da janela ----------------------------------------
slhj=17 ; maximo
wj=80   ; maximo
;wj=57   ; largura da janela

;-- Indicar poisicao inicial da janela -----------------------------------------
lj=01
cj=01

;-- Indicar a altura da lista --------------------------------------------------
slhl=10 ; minimo

;-- Titulo da janela e da lista ------------------------------------------------
sltitj="Vendas/Outras opera‡äes realizadas"
sltitl=""
sltot =""

switch
  case sltiposelecao="":  ; sem item
       nlb=3
  case sltiposelecao="U": ; um unico item
       nlb=3
  case sltiposelecao="M": ; returna uma lista de itens
       nlb=0
endswitch 

while true
  slcrialista()
  slcarregalista()
  
  While True
  
    ShowDialog sltitj Proc "slsd_dialog"
    Trigger "OPEN","ARRIVE","SELECT"
    Key "ENTER","ESC","TAB", "F1"  
      @ lj,cj Height slhj Width wj
  
      @ 00,00 ?? sltitl
      
      PickDynarray @1,00 Height slhl width wj-3
       Columns 1
        slarraylista
         Tag "TG_LISTA"
          To VSDGLISTA
          
      @ (1+slhl),00 ?? sltot

      Pushbutton @ (3+slhl+nlb),26 width 11 "~O~k"      OK     Default Value "Ok" Tag "YES" To BottonValue
      Pushbutton @ (3+slhl+nlb),40 width 11 "~C~ancela" CANCEL                    Tag "NO"  To BottonValue
  
      PaintCanvas Attribute 111 00, 00, 00, (wj-4)
      PaintCanvas Attribute 111 (1+slhl), 00, (1+slhl), (wj-4)
                            
    EndDialog
    If Not RetVal Then return false EndIf
    
    if slvalidaitemselecionado() 
       then return true
       else Mensagem("[Ok] Confirmado mas sem item selecionado na lista !")
    endif
  EndWhile

EndWhile
endproc

;*******************************************************************************
;*                                                                             *
;*******************************************************************************
proc slexecutaprocessodesejado()    
;private

endproc




;*******************************************************************************
;* Rotina Principal                                                            *
;*******************************************************************************
AutoLib="\\Sistemas\\Cadastro\\Bibliot,\\Sistemas\\Cadastro\\Bib_Show,\\Sistemas\\Cadastro\\Bib_Proc"
If Not IsAssigned(SYS_CODIGO_CLIENTE)  Then SYS_CODIGO_CLIENTE=""    EndIf
If Not IsAssigned(SYS_CLIENTE_CONFEC)  Then SYS_CLIENTE_CONFEC=""    EndIf

if slshowlista()
   then
        slexecutaprocessodesejado()    
endif   


release procs slarraylista, slarraylistacoluna, slarraylistaretorno, sltiposelecao,  
              slcc, slcs, sltitj, sltitl, sltot, 
              slhl, slhj

Release Procs slsd_dialog, slcrialista, slmontatitulo, sladdlistacoluna, Sltotcoluna, slcarregalista,
              slexcluiitemlista, slsetaxselecionado, slvalorlistacoluna, slvalidaitemselecionado,
              slshowlista, slexecutaprocessodesejado
