-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
213 lines (171 loc) · 7.78 KB
/
Copy pathapp.py
File metadata and controls
213 lines (171 loc) · 7.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import customtkinter as ctk
from pymongo import MongoClient
import os
from tkinter import messagebox
from PIL import Image, ImageTk
import requests
from io import BytesIO
from dotenv import load_dotenv
# Cargar variables del .env
load_dotenv()
uri = os.environ["MONGODB_URI"]
dbname = os.environ["MONGODB_DB"]
dbtable = os.environ["MONGODB_TABLE"]
client = MongoClient(uri)
db = client[dbname]
products_collection = db[dbtable]
# ----------------- Ventana principal -----------------
ctk.set_appearance_mode("System")
ctk.set_default_color_theme("blue")
class PanelAdmin(ctk.CTk):
def __init__(self):
super().__init__()
self.title("Panel de Administrador")
self.geometry("800x600")
# Tabs
self.tabs = ctk.CTkTabview(self, width=780, height=560)
self.tabs.pack(pady=20, padx=20)
self.tabs.add("Agregar")
self.tabs.add("Listar")
self.tabs.add("Actualizar")
self.tabs.add("Eliminar")
# Crear todas las tabs primero
self.crear_tab_agregar()
self.crear_tab_listar()
self.crear_tab_actualizar()
self.crear_tab_eliminar()
# Refrescar combos/listas después de crear todos los widgets
self.refrescar_listas()
# ----------------- TAB AGREGAR -----------------
def crear_tab_agregar(self):
tab = self.tabs.tab("Agregar")
ctk.CTkLabel(tab, text="Nombre del producto").pack(pady=3)
self.nombre_entry = ctk.CTkEntry(tab)
self.nombre_entry.pack(pady=3)
ctk.CTkLabel(tab, text="Ingredientes").pack(pady=3)
self.ingredientes_entry = ctk.CTkEntry(tab)
self.ingredientes_entry.pack(pady=3)
ctk.CTkLabel(tab, text="Precio").pack(pady=3)
self.precio_entry = ctk.CTkEntry(tab)
self.precio_entry.pack(pady=3)
ctk.CTkLabel(tab, text="Stock").pack(pady=3)
self.stock_entry = ctk.CTkEntry(tab)
self.stock_entry.pack(pady=3)
ctk.CTkLabel(tab, text="URL de la Imagen").pack(pady=3)
self.image_entry = ctk.CTkEntry(tab)
self.image_entry.pack(pady=3)
ctk.CTkButton(tab, text="Agregar Producto", command=self.agregar_producto).pack(pady=10)
def agregar_producto(self):
nombre = self.nombre_entry.get()
ingredientes = self.ingredientes_entry.get()
precio = self.precio_entry.get()
stock = self.stock_entry.get()
image_url = self.image_entry.get()
if not nombre or not ingredientes or not precio.isdigit() or not stock.isdigit() or not image_url:
messagebox.showerror("Error", "Verifique los datos ingresados")
return
product = {
"name": nombre,
"ingredients": ingredientes,
"price": int(precio),
"stock": int(stock),
"image": image_url
}
products_collection.insert_one(product)
messagebox.showinfo("Éxito", f"Producto '{nombre}' agregado correctamente")
self.nombre_entry.delete(0, "end")
self.ingredientes_entry.delete(0, "end")
self.precio_entry.delete(0, "end")
self.stock_entry.delete(0, "end")
self.image_entry.delete(0, "end")
self.refrescar_listas()
# ----------------- TAB LISTAR -----------------
def crear_tab_listar(self):
tab = self.tabs.tab("Listar")
# Scrollable frame para lista de productos
self.scrollable_frame = ctk.CTkScrollableFrame(tab, width=740, height=500)
self.scrollable_frame.pack(pady=10, padx=10)
self.scrollable_frame.grid_rowconfigure(0, weight=1)
self.scrollable_frame.grid_columnconfigure(0, weight=1)
# ----------------- TAB ACTUALIZAR -----------------
def crear_tab_actualizar(self):
tab = self.tabs.tab("Actualizar")
ctk.CTkLabel(tab, text="Seleccione producto").pack(pady=5)
self.actualizar_combo = ctk.CTkComboBox(tab, values=[])
self.actualizar_combo.pack(pady=5)
ctk.CTkLabel(tab, text="Nuevo Precio").pack(pady=5)
self.nuevo_precio_entry = ctk.CTkEntry(tab)
self.nuevo_precio_entry.pack(pady=5)
ctk.CTkLabel(tab, text="Nuevo Stock").pack(pady=5)
self.nuevo_stock_entry = ctk.CTkEntry(tab)
self.nuevo_stock_entry.pack(pady=5)
ctk.CTkButton(tab, text="Actualizar", command=self.actualizar_producto).pack(pady=10)
def actualizar_producto(self):
nombre = self.actualizar_combo.get()
precio = self.nuevo_precio_entry.get()
stock = self.nuevo_stock_entry.get()
update_data = {}
if precio.isdigit():
update_data["price"] = int(precio)
if stock.isdigit():
update_data["stock"] = int(stock)
if not update_data:
messagebox.showerror("Error", "Ingrese al menos precio o stock válido")
return
products_collection.update_one({"name": nombre}, {"$set": update_data})
messagebox.showinfo("Éxito", f"Producto '{nombre}' actualizado correctamente")
self.nuevo_precio_entry.delete(0, "end")
self.nuevo_stock_entry.delete(0, "end")
self.refrescar_listas()
# ----------------- TAB ELIMINAR -----------------
def crear_tab_eliminar(self):
tab = self.tabs.tab("Eliminar")
ctk.CTkLabel(tab, text="Seleccione producto").pack(pady=5)
self.eliminar_combo = ctk.CTkComboBox(tab, values=[])
self.eliminar_combo.pack(pady=5)
ctk.CTkButton(tab, text="Eliminar", command=self.eliminar_producto).pack(pady=10)
def eliminar_producto(self):
nombre = self.eliminar_combo.get()
if not nombre:
messagebox.showerror("Error", "Seleccione un producto")
return
confirm = messagebox.askyesno("Confirmar", f"¿Está seguro de eliminar '{nombre}'?")
if confirm:
products_collection.delete_one({"name": nombre})
messagebox.showinfo("Éxito", f"Producto '{nombre}' eliminado correctamente")
self.refrescar_listas()
# ----------------- REFRESCAR LISTAS -----------------
def refrescar_listas(self):
productos = list(products_collection.find())
# Actualizar Combo de Actualizar
if hasattr(self, "actualizar_combo"):
self.actualizar_combo.configure(values=[prod["name"] for prod in productos])
# Actualizar Combo de Eliminar
if hasattr(self, "eliminar_combo"):
self.eliminar_combo.configure(values=[prod["name"] for prod in productos])
# Actualizar ScrollableFrame de Listar con mini-imágenes
if hasattr(self, "scrollable_frame"):
# Limpiar frame
for widget in self.scrollable_frame.winfo_children():
widget.destroy()
for i, prod in enumerate(productos):
frame = ctk.CTkFrame(self.scrollable_frame, width=700, height=100)
frame.pack(pady=5, padx=10, fill="x")
# Cargar imagen desde URL
try:
response = requests.get(prod["image"])
img_data = Image.open(BytesIO(response.content)).resize((80, 80))
img = ImageTk.PhotoImage(img_data)
label_img = ctk.CTkLabel(frame, image=img)
label_img.image = img # Mantener referencia
label_img.pack(side="left", padx=10)
except:
label_img = ctk.CTkLabel(frame, text="[No Image]", width=10)
label_img.pack(side="left", padx=10)
# Info producto
info = f"{prod['name']}\nIngredientes: {prod['ingredients']}\nPrecio: ${prod['price']} | Stock: {prod['stock']}"
ctk.CTkLabel(frame, text=info, justify="left").pack(side="left", padx=10)
# ----------------- Ejecutar app -----------------
if __name__ == "__main__":
app = PanelAdmin()
app.mainloop()