Skip to content

Commit

Permalink
Correções importantes
Browse files Browse the repository at this point in the history
  • Loading branch information
victorrgouvea committed Sep 6, 2021
1 parent 9e3be17 commit ba63770
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 8 deletions.
5 changes: 2 additions & 3 deletions adm.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,6 @@ def CadastrarUser(self):
def BuscarHistorico(self):
self.tabAdmTabela.clearContents()
self.tabAdmTabela.setRowCount(0)

self.tabAdmTabela.setColumnCount(len(historico))
self.tabAdmTabela.setHorizontalHeaderLabels(historico)

Expand All @@ -122,7 +121,7 @@ def BuscarHistorico(self):
nomeQT = QTableWidgetItem(i[2])
dataQT = QTableWidgetItem(i[3])
quantQT = QTableWidgetItem(str(i[4]))
totalQT = QTableWidgetItem("R$" + str(round(i[5]*int(i[4]), 2)))
totalQT = QTableWidgetItem("R$ " + str(f'{i[5]*int(i[4]):.2f}').replace('.', ','))

self.tabAdmTabela.setItem(linhasCount, 0, codigoQT)
self.tabAdmTabela.setItem(linhasCount, 1, nomeQT)
Expand All @@ -148,7 +147,7 @@ def BuscarEstoque(self):
codigoQT = QTableWidgetItem(str(i[0]))
nomeQT = QTableWidgetItem(i[1])
quantQT = QTableWidgetItem(str(i[2]))
precoQT = QTableWidgetItem(("R$" + str(i[3])))
precoQT = QTableWidgetItem("R$ " + str(f'{i[3]:.2f}').replace('.', ','))

self.tabAdmTabela.setItem(linhasCount, 0, codigoQT)
self.tabAdmTabela.setItem(linhasCount, 1, nomeQT)
Expand Down
4 changes: 2 additions & 2 deletions conexoes.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,11 @@ def Remover_Estoque(produtos):
def Carregar_Produto(codigo):
"""
Recebe um codigo e retorna uma tupla com os dados desse produto cadastrados no estoque,
Na seguinte ordem: codigo(int), nome(str), valorUnit(float)
Na seguinte ordem: codigo(int), nome(str), valorUnit(float), quantidade(int)
"""
with Conectar(databasePath) as (conn, cursor):
cursor.execute(
f'SELECT codigo, nome, preco FROM estoque WHERE codigo = {codigo}')
f'SELECT codigo, nome, preco, quant FROM estoque WHERE codigo = {codigo}')
conn.commit()

retorno = cursor.fetchall()
Expand Down
83 changes: 80 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@


titulos = ['Código', 'Nome', 'Quantidade', 'Preço Unitário', 'Preço Total']
cache = []


class Main(QMainWindow, Ui_MainWindow):
Expand Down Expand Up @@ -37,7 +38,32 @@ def Add_Carrinho(self):
"DADOS INCOMPLETOS, COLOQUE ALGO")
return

if Verificar_Codigo(codigo, quant):
quantidade_anterior = 0
index = 0
in_cache = False
pode_add = False

# Procura o item no cache
for anterior in cache:
if int(codigo) in anterior:
index = cache.index(anterior)
quantidade_anterior = anterior[1]
in_cache = True
break

# Caso esteja no cache, verifica se tem estoque suficiente
if in_cache:
if quantidade_anterior >= int(quant) and quantidade_anterior > 0:
cache[index][1] -= int(quant)
pode_add = True

# Caso contrário, verifica se o item está presente no banco de dados
else:
if Verificar_Codigo(codigo, quant):
pode_add = True

# Se o item estiver registrado em algum desses lugares, ele é adiocionado ao carrinho
if pode_add:
# Traz o produto do banco de dados
produto = Carregar_Produto(codigo)

Expand All @@ -63,6 +89,10 @@ def Add_Carrinho(self):
self.tabCarrinho.setItem(linhasCount, 3, precoUnitQT)
self.tabCarrinho.setItem(linhasCount, 4, precoTotQT)

# Caso o item não esteja registrado no cache, ele é registrado já com a quantidade descontada
if not in_cache:
cache.append([produto[0], (produto[3]-int(quant))])

else:
self.txtMainCod.setText("")
self.txtMainQuant.clear()
Expand All @@ -76,41 +106,88 @@ def Limpar_Carrinho(self):
# Remove todas as colunas
self.tabCarrinho.setRowCount(0)

# Limpa o conteúdo do cache
cache.clear()

self.txtMainMessage.setText(
"CARRINHO LIMPO")

def Concluir_Compra(self):
lista_Compra = []
for linha in range(self.tabCarrinho.rowCount()):
produto = []
for coluna in range(0, 5):
item = self.tabCarrinho.item(linha, coluna)
produto.append(item.text())
item = item.text()
item = item.replace(',', '.')
item = item.replace('R$ ', '')
produto.append(item)
lista_Compra.append(produto)

# Cálculo do total da compra
total = 0
for linha in range(self.tabCarrinho.rowCount()):
item = self.tabCarrinho.item(linha, 4)
item = item.text()
item = item.replace(',', '.')
item = item.replace('R$ ', '')
total += (float(item))

# Apenas settar a mensagem de erro, as funções não são executadas caso a lista seja vazia
if lista_Compra == []:
self.txtMainMessage.setText(
"CARRINHO VAZIO")
else:
self.txtMainMessage.setText(
"COMPRA FINALIZADA! TOTAL DA COMPRA: R$ {:.2f}".format(total))

# Implementar chamada para Atualizar Estoque
Remover_Estoque(lista_Compra)
# Implementar chamada para Adicionar venda ao Histórico
Add_Historico(lista_Compra)

# Limpa as lacunas
self.txtMainCod.clear()
self.txtMainQuant.clear()

# Limpa todo o conteúdo da tabela
self.tabCarrinho.clearContents()

# Remove todas as colunas
self.tabCarrinho.setRowCount(0)

# Limpa o conteúdo do cache
cache.clear()

def Remover_Item(self):
# Busca a linha atual
linhaAtual = self.tabCarrinho.currentRow()

# Adiciona o valor de estoque previamente tirado do cache de volta ao mesmo
item = self.tabCarrinho.item(linhaAtual, 0)
item2 = self.tabCarrinho.item(linhaAtual, 2)

codigo = item.text()
quant = item2.text()

for i in cache:
if int(codigo) in i:
i[1] += int(quant)

# Remove a linha
self.tabCarrinho.removeRow(linhaAtual)

# Coloca a célula selecionada em nada
self.tabCarrinho.setCurrentCell(-1, 0)

self.txtMainMessage.setText(
"ITEM REMOVIDO COM SUCESSO")

def Mostrar_Login(self):
# Cria um novo objeto com a classe Login
self.loginWindow = Login()
self.loginWindow.show() # E mostra ele na tela


if __name__ == '__main__':
app = QApplication(sys.argv)
janela = Main()
Expand Down
Binary file modified padaria.db
Binary file not shown.

0 comments on commit ba63770

Please sign in to comment.