#INCLUDE "PROTHEUS.CH"
User Function WMSQYABA()
Local cArmazem := PARAMIXB[1]
Local cEndereco := PARAMIXB[2]
Local cProduto := PARAMIXB[3]
Local cPrdOrig := PARAMIXB[4]
Local cLoteCtl := PARAMIXB[5]
Local cSubLote := PARAMIXB[6]
Local cQuery := ""
Local aTamSX3 := TamSx3("D14_QTDEST")
Local cAliasD14 := GetNextAlias()
cQuery := "SELECT DC3_ORDEM,"
cQuery += " D14_ENDER,"
cQuery += " D14_ESTFIS,"
cQuery += " D14_LOTECT,"
cQuery += " D14_NUMLOT,"
cQuery += " D14_DTVALD,"
cQuery += " D14_NUMSER,"
cQuery += " D14_PRIOR,"
cQuery += " D14_IDUNIT,"
cQuery += " (D14_QTDEST-(D14_QTDEMP+D14_QTDBLQ)) D14_QTDLIB,"
cQuery += " D14_QTDSPR,"
cQuery += " (D14_QTDEST-(D14_QTDEMP+D14_QTDBLQ+D14_QTDSPR)) D14_SALDO"
cQuery += " FROM "+RetSqlName("D14")+" D14"
cQuery += " INNER JOIN "+RetSqlName("DC3")+" DC3"
cQuery += " ON DC3.DC3_FILIAL = '"+xFilial("DC3")+"'"
cQuery += " AND DC3.DC3_LOCAL = D14.D14_LOCAL"
cQuery += " AND DC3.DC3_CODPRO = D14.D14_PRODUT"
cQuery += " AND DC3.DC3_TPESTR = D14.D14_ESTFIS"
cQuery += " AND DC3.D_E_L_E_T_ = ' '"
cQuery += " INNER JOIN "+RetSqlName("DC8")+" DC8"
cQuery += " ON DC8.DC8_FILIAL = '"+xFilial("DC8")+"'"
cQuery += " AND DC8.DC8_CODEST = D14.D14_ESTFIS"
cQuery += " AND DC8.DC8_TPESTR IN ('1','2')" // Considera estruturas de picking e pulmão
cQuery += " AND DC8.D_E_L_E_T_ = ' '"
cQuery += " WHERE D14_FILIAL = '"+xFilial("D14")+"'"
cQuery += " AND D14_LOCAL = '"+cArmazem+"'"
cQuery += " AND D14_PRODUT = '"+cProduto+"'"
cQuery += " AND D14_PRDORI = '"+cPrdOrig+"'"
If Rastro(cProduto)
If !Empty(cLoteCtl)
cQuery += " AND D14_LOTECT = '"+cLoteCtl+"'"
EndIf
If !Empty(cSubLote)
cQuery += " AND D14_NUMLOT = '"+cSubLote+"'"
EndIf
EndIf
cQuery += " AND D14.D14_ENDER <> '"+cEndereco+"'"
cQuery += " AND (D14_QTDEST-(D14_QTDEMP+D14_QTDBLQ)) > 0"
cQuery += " AND D14.D_E_L_E_T_ = ' '"
cQuery += " ORDER BY D14_DTVALD,D14_PRIOR,D14_SALDO,D14_LOTECT,D14_NUMLOT,D14_IDUNIT,D14_ENDER"
cQuery := ChangeQuery(cQuery)
DbUseArea(.T.,'TOPCONN',TcGenQry(,,cQuery),cAliasD14,.F.,.T.)
// Ajustando o tamanho dos campos da query
TcSetField(cAliasD14,'D14_QTDLIB','N',aTamSX3[1],aTamSX3[2])
TcSetField(cAliasD14,'D14_QTDSPR','N',aTamSX3[1],aTamSX3[2])
TcSetField(cAliasD14,'D14_SALDO' ,'N',aTamSX3[1],aTamSX3[2])
TcSetField(cAliasD14,'D14_DTVALD','D')
Return cAliasD14