Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added __pycache__/database.cpython-312.pyc
Binary file not shown.
137 changes: 137 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import streamlit as st
from controllers.user_controller import create_user, authenticate_user
from controllers.category_controller import create_category, get_categories
from controllers.product_controller import create_product, get_products
from controllers.shopping_list_controller import create_shopping_list, get_shopping_lists, add_item_to_list, get_list_items, get_shopping_list_by_id
from controllers.stock_controller import add_to_stock, get_stock, remove_from_stock

def main():
st.title("Lista de Compras")

if 'user' not in st.session_state:
st.session_state.user = None

if st.session_state.user:
st.write(f"Bem-vindo, {st.session_state.user['username']}!")
if st.button("Logout"):
st.session_state.user = None
st.rerun()

st.header("Categorias")
category_name = st.text_input("Nova Categoria")
if st.button("Adicionar Categoria"):
if create_category(category_name) is not None:
st.success("Categoria adicionada com sucesso!")
else:
st.error("Erro ao adicionar categoria.")

st.header("Produtos")
product_name = st.text_input("Novo Produto")
categories = get_categories()
category_id = st.selectbox("Categoria", [c['id'] for c in categories], format_func=lambda x: [c['name'] for c in categories if c['id'] == x][0])
if st.button("Adicionar Produto"):
if create_product(product_name, category_id) is not None:
st.success("Produto adicionado com sucesso!")
else:
st.error("Erro ao adicionar produto.")

st.header("Minhas Listas de Compras")

st.subheader("Criar Nova Lista")
list_name = st.text_input("Nome da Nova Lista")
if st.button("Criar"):
list_id = create_shopping_list(list_name, st.session_state.user['id'])
if list_id:
st.success(f"Lista '{list_name}' criada com sucesso!")
else:
st.error("Erro ao criar lista.")

st.subheader("Importar Lista")
shared_link = st.text_input("Link da Lista Compartilhada")
if st.button("Importar"):
try:
shared_list_id = int(shared_link.split("=")[-1])
shared_list = get_shopping_list_by_id(shared_list_id)
if shared_list:
new_list_id = create_shopping_list(f"Importada - {shared_list['name']}", st.session_state.user['id'])
if new_list_id:
items = get_list_items(shared_list_id)
for item in items:
add_item_to_list(new_list_id, item['product_id'], item['quantity'])
st.success("Lista importada com sucesso!")
else:
st.error("Erro ao importar lista.")
else:
st.error("Lista compartilhada não encontrada.")
except:
st.error("Link inválido.")

shopping_lists = get_shopping_lists(st.session_state.user['id'])
selected_list_id = st.selectbox("Selecione uma lista", [l['id'] for l in shopping_lists], format_func=lambda x: [l['name'] for l in shopping_lists if l['id'] == x][0])

if selected_list_id:
st.header(f"Itens da Lista")

share_url = f"http://localhost:8501/?list_id={selected_list_id}"
st.write(f"Link para compartilhar: `{share_url}`")

products = get_products()
product_id = st.selectbox("Produto", [p['id'] for p in products], format_func=lambda x: [p['name'] for p in products if p['id'] == x][0])
quantity = st.number_input("Quantidade", min_value=1, value=1)
if st.button("Adicionar Item"):
if add_item_to_list(selected_list_id, product_id, quantity):
st.success("Item adicionado com sucesso!")
else:
st.error("Erro ao adicionar item.")

items = get_list_items(selected_list_id)
for item in items:
col1, col2 = st.columns([3, 1])
with col1:
st.write(f"- {item['name']} (Quantidade: {item['quantity']})")
with col2:
if st.button("Comprar", key=f"buy_{item['id']}"):
if add_to_stock(st.session_state.user['id'], item['product_id'], item['quantity']):
st.success(f"{item['name']} adicionado ao estoque!")
else:
st.error("Erro ao adicionar ao estoque.")

st.header("Meu Estoque")
stock_items = get_stock(st.session_state.user['id'])
for item in stock_items:
col1, col2, col3 = st.columns([2, 1, 1])
with col1:
st.write(f"- {item['name']} (Quantidade: {item['quantity']})")
with col2:
quantity_to_remove = st.number_input("Quantidade a remover", min_value=1, max_value=item['quantity'], value=1, key=f"remove_qty_{item['id']}")
with col3:
if st.button("Dar Baixa", key=f"remove_{item['id']}"):
if remove_from_stock(item['id'], quantity_to_remove):
st.success("Baixa realizada com sucesso!")
st.rerun()
else:
st.error("Erro ao dar baixa no estoque.")

else:
choice = st.selectbox("Login ou Cadastro", ["Login", "Cadastro"])
if choice == "Login":
username = st.text_input("Usuário")
password = st.text_input("Senha", type="password")
if st.button("Login"):
user = authenticate_user(username, password)
if user:
st.session_state.user = user
st.rerun()
else:
st.error("Usuário ou senha inválidos")
else:
username = st.text_input("Usuário")
password = st.text_input("Senha", type="password")
if st.button("Cadastrar"):
if create_user(username, password) is not None:
st.success("Usuário criado com sucesso! Faça o login.")
else:
st.error("Este nome de usuário já existe.")

if __name__ == "__main__":
main()
Empty file added controllers/__init__.py
Empty file.
Binary file added controllers/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
21 changes: 21 additions & 0 deletions controllers/category_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from database import get_db_connection

def create_category(name):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO categories (name) VALUES (?)", (name,))
conn.commit()
return cursor.lastrowid
except:
return None
finally:
conn.close()

def get_categories():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM categories")
categories = cursor.fetchall()
conn.close()
return categories
25 changes: 25 additions & 0 deletions controllers/product_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from database import get_db_connection

def create_product(name, category_id):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO products (name, category_id) VALUES (?, ?)", (name, category_id))
conn.commit()
return cursor.lastrowid
except:
return None
finally:
conn.close()

def get_products():
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT p.id, p.name, c.name as category_name
FROM products p
JOIN categories c ON p.category_id = c.id
""")
products = cursor.fetchall()
conn.close()
return products
54 changes: 54 additions & 0 deletions controllers/shopping_list_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
from database import get_db_connection

def create_shopping_list(name, user_id):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO shopping_lists (name, user_id) VALUES (?, ?)", (name, user_id))
conn.commit()
return cursor.lastrowid
except:
return None
finally:
conn.close()

def get_shopping_lists(user_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM shopping_lists WHERE user_id = ?", (user_id,))
lists = cursor.fetchall()
conn.close()
return lists

def add_item_to_list(shopping_list_id, product_id, quantity):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("INSERT INTO shopping_list_items (shopping_list_id, product_id, quantity) VALUES (?, ?, ?)", (shopping_list_id, product_id, quantity))
conn.commit()
return True
except:
return False
finally:
conn.close()

def get_list_items(shopping_list_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT sli.id, p.id as product_id, p.name, sli.quantity
FROM shopping_list_items sli
JOIN products p ON sli.product_id = p.id
WHERE sli.shopping_list_id = ?
""", (shopping_list_id,))
items = cursor.fetchall()
conn.close()
return items

def get_shopping_list_by_id(list_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM shopping_lists WHERE id = ?", (list_id,))
shopping_list = cursor.fetchone()
conn.close()
return shopping_list
51 changes: 51 additions & 0 deletions controllers/stock_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from database import get_db_connection

def add_to_stock(user_id, product_id, quantity):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM stock WHERE user_id = ? AND product_id = ?", (user_id, product_id))
item = cursor.fetchone()
if item:
new_quantity = item['quantity'] + quantity
cursor.execute("UPDATE stock SET quantity = ? WHERE id = ?", (new_quantity, item['id']))
else:
cursor.execute("INSERT INTO stock (user_id, product_id, quantity) VALUES (?, ?, ?)", (user_id, product_id, quantity))
conn.commit()
return True
except:
return False
finally:
conn.close()

def get_stock(user_id):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT s.id, p.name, s.quantity
FROM stock s
JOIN products p ON s.product_id = p.id
WHERE s.user_id = ?
""", (user_id,))
stock = cursor.fetchall()
conn.close()
return stock

def remove_from_stock(stock_id, quantity_to_remove):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM stock WHERE id = ?", (stock_id,))
item = cursor.fetchone()
if item:
new_quantity = item['quantity'] - quantity_to_remove
if new_quantity > 0:
cursor.execute("UPDATE stock SET quantity = ? WHERE id = ?", (new_quantity, stock_id))
else:
cursor.execute("DELETE FROM stock WHERE id = ?", (stock_id,))
conn.commit()
return True
except:
return False
finally:
conn.close()
28 changes: 28 additions & 0 deletions controllers/user_controller.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import sqlite3
from werkzeug.security import generate_password_hash, check_password_hash
from database import get_db_connection

def create_user(username, password):
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute(
"INSERT INTO users (username, password) VALUES (?, ?)",
(username, generate_password_hash(password))
)
conn.commit()
return cursor.lastrowid
except sqlite3.IntegrityError:
return None
finally:
conn.close()

def authenticate_user(username, password):
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
if user and check_password_hash(user['password'], password):
return user
return None
73 changes: 73 additions & 0 deletions database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import sqlite3
import os

def get_db_connection():
db_name = 'test_shopping_list.db' if os.environ.get('TESTING') else 'shopping_list.db'
conn = sqlite3.connect(db_name)
conn.row_factory = sqlite3.Row
return conn

def create_tables():
conn = get_db_connection()
cursor = conn.cursor()

cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL UNIQUE,
password TEXT NOT NULL
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS categories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS products (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
category_id INTEGER,
FOREIGN KEY (category_id) REFERENCES categories (id)
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS shopping_lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
user_id INTEGER,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS shopping_list_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
shopping_list_id INTEGER,
product_id INTEGER,
quantity INTEGER NOT NULL,
FOREIGN KEY (shopping_list_id) REFERENCES shopping_lists (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)
''')

cursor.execute('''
CREATE TABLE IF NOT EXISTS stock (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
product_id INTEGER,
quantity INTEGER NOT NULL,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (product_id) REFERENCES products (id)
)
''')

conn.commit()
conn.close()

if __name__ == '__main__':
create_tables()
Empty file added models/__init__.py
Empty file.
Empty file added models/category.py
Empty file.
Empty file added models/product.py
Empty file.
Empty file added models/shopping_list.py
Empty file.
Empty file added models/stock.py
Empty file.
Empty file added models/user.py
Empty file.
2 changes: 2 additions & 0 deletions pytest.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[pytest]
pythonpath = .
Binary file added shopping_list.db
Binary file not shown.
Loading