-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgestor_financiero.py
More file actions
718 lines (639 loc) · 25.6 KB
/
Copy pathgestor_financiero.py
File metadata and controls
718 lines (639 loc) · 25.6 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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
import sys
import os
import sqlite3
from datetime import datetime
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from PySide6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QComboBox, QLineEdit, QPushButton, QTableView,
QMessageBox, QGroupBox, QInputDialog, QDialog, QListWidget, QListWidgetItem
)
from PySide6 import QtSql, QtCore, QtGui
DB = "tienda.db"
# =====================
# UTILIDADES DB
# =====================
def execute_sql(query, params=()):
conn = sqlite3.connect(DB)
cur = conn.cursor()
cur.execute(query, params)
conn.commit()
conn.close()
def fetch_sql(query, params=()):
conn = sqlite3.connect(DB)
cur = conn.cursor()
cur.execute(query, params)
rows = cur.fetchall()
conn.close()
return rows
# =====================
# CREAR TABLAS BASE
# =====================
def crear_tabla_base():
# tabla base (la dejamos por compatibilidad, no se usa cuando hay perfiles activos)
execute_sql("""
CREATE TABLE IF NOT EXISTS registros (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tipo TEXT,
valor REAL,
descripcion TEXT,
fecha TEXT,
hora TEXT
)
""")
# tabla perfiles y config
execute_sql("""
CREATE TABLE IF NOT EXISTS perfiles (
id INTEGER PRIMARY KEY AUTOINCREMENT,
nombre TEXT UNIQUE
)
""")
execute_sql("""
CREATE TABLE IF NOT EXISTS config (
llave TEXT PRIMARY KEY,
valor TEXT
)
""")
crear_tabla_base()
# =====================
# SANITIZAR NOMBRE PERFIL -> nombre tabla
# =====================
def sanitize_profile_name(name: str) -> str:
# strip, lower, replace sequences of non-alnum with underscore
if not name:
return "default"
n = name.strip()
res_chars = []
for c in n:
if c.isalnum():
res_chars.append(c.lower())
elif c in (" ", "-", "_"):
res_chars.append("_")
else:
# otros caracteres -> underscore
res_chars.append("_")
# collapse multiple underscores
s = "".join(res_chars)
while "__" in s:
s = s.replace("__", "_")
s = s.strip("_")
if not s:
s = "default"
return s
# =====================
# TABLA POR PERFIL
# =====================
def profile_table_name(profile_display_name: str) -> str:
"""
Dado el nombre visible del perfil devuelve el nombre de la tabla.
"""
safe = sanitize_profile_name(profile_display_name)
return f"registros_{safe}"
def ensure_table_for_profile(profile_display_name: str):
tabla = profile_table_name(profile_display_name)
execute_sql(f'''
CREATE TABLE IF NOT EXISTS "{tabla}" (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tipo TEXT,
valor REAL,
descripcion TEXT,
fecha TEXT,
hora TEXT
)
''')
return tabla
# =====================
# CONFIG: leer/escribir perfil actual
# =====================
def get_current_profile():
rows = fetch_sql("SELECT valor FROM config WHERE llave='perfil_actual'")
return rows[0][0] if rows else None
def set_current_profile(profile_display_name: str):
execute_sql("INSERT OR REPLACE INTO config (llave, valor) VALUES ('perfil_actual', ?)", (profile_display_name,))
def remove_current_profile_if_matches(profile_display_name: str):
execute_sql("DELETE FROM config WHERE llave='perfil_actual' AND valor=?", (profile_display_name,))
# =====================
# FUNCIONES GESTION PERFIL (RENOMBRAR / BORRAR)
# =====================
def rename_profile(old_display_name: str, new_display_name: str):
"""
Renombra perfil en tabla 'perfiles' y renombra la tabla de datos si existe.
"""
old_table = profile_table_name(old_display_name)
new_table = profile_table_name(new_display_name)
conn = sqlite3.connect(DB)
cur = conn.cursor()
try:
# actualizar nombre en perfiles
cur.execute("UPDATE perfiles SET nombre=? WHERE nombre=?", (new_display_name, old_display_name))
conn.commit()
# si existe la tabla antigua, renombrarla
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (old_table,))
if cur.fetchone():
# rename table
cur.execute(f'ALTER TABLE "{old_table}" RENAME TO "{new_table}"')
conn.commit()
# si el perfil renombrado era el actual, actualizar config
cur.execute("SELECT valor FROM config WHERE llave='perfil_actual'")
row = cur.fetchone()
if row and row[0] == old_display_name:
cur.execute("INSERT OR REPLACE INTO config (llave, valor) VALUES ('perfil_actual', ?)", (new_display_name,))
conn.commit()
except Exception as e:
conn.rollback()
conn.close()
raise
conn.close()
def delete_profile(profile_display_name: str):
"""
Elimina perfil de la tabla perfiles, borra su tabla de datos y quita config si aplica.
"""
tabla = profile_table_name(profile_display_name)
conn = sqlite3.connect(DB)
cur = conn.cursor()
try:
# borrar perfil
cur.execute("DELETE FROM perfiles WHERE nombre=?", (profile_display_name,))
# borrar tabla de datos si existe
cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name=?", (tabla,))
if cur.fetchone():
cur.execute(f'DROP TABLE "{tabla}"')
# quitar config si estaba seleccionado
cur.execute("DELETE FROM config WHERE llave='perfil_actual' AND valor=?", (profile_display_name,))
conn.commit()
except Exception as e:
conn.rollback()
conn.close()
raise
conn.close()
# =====================
# VENTANA SELECCIÓN / GESTIÓN DE PERFILES (DIALOG)
# =====================
class ProfileManagerDialog(QDialog):
"""
Dialogo que permite seleccionar/crear/renombrar/eliminar perfiles.
Si se llama sin parent (al inicio), al hacer 'Seleccionar' el dialogo hará accept()
y el main abrirá la App con ese perfil.
Si se llama desde la App (parent pasa la instancia App), al seleccionar actualizará la app en caliente.
"""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("👤 Seleccionar / Gestionar Perfiles")
self.setFixedSize(420, 360)
self.parent = parent
layout = QVBoxLayout(self)
layout.addWidget(QLabel("Perfiles disponibles (máx 5):"))
self.list_widget = QListWidget()
layout.addWidget(self.list_widget)
# botones
btns = QHBoxLayout()
btn_add = QPushButton("➕ Agregar")
btn_ren = QPushButton("✏️ Renombrar")
btn_del = QPushButton("🗑️ Eliminar")
btn_sel = QPushButton("✅ Seleccionar")
btn_close = QPushButton("Cerrar")
btn_add.clicked.connect(self.add_profile)
btn_ren.clicked.connect(self.rename_profile)
btn_del.clicked.connect(self.delete_profile)
btn_sel.clicked.connect(self.select_profile)
btn_close.clicked.connect(self.reject)
btns.addWidget(btn_add)
btns.addWidget(btn_ren)
btns.addWidget(btn_del)
btns.addWidget(btn_sel)
btns.addWidget(btn_close)
layout.addLayout(btns)
# mostrar perfil actual
self.lbl_actual = QLabel("")
layout.addWidget(self.lbl_actual)
self.refresh_list()
def refresh_list(self):
self.list_widget.clear()
rows = fetch_sql("SELECT nombre FROM perfiles ORDER BY id")
for r in rows:
item = QListWidgetItem(r[0])
self.list_widget.addItem(item)
# seleccionar el actual si existe
current = get_current_profile()
if current:
# marcar el item que coincide
for i in range(self.list_widget.count()):
if self.list_widget.item(i).text() == current:
self.list_widget.setCurrentRow(i)
break
self.show_current_label()
def show_current_label(self):
cur = get_current_profile()
if cur:
self.lbl_actual.setText(f"Perfil actual: {cur}")
else:
self.lbl_actual.setText("Perfil actual: (ninguno)")
def add_profile(self):
# verificar límite
cnt = fetch_sql("SELECT COUNT(*) FROM perfiles")[0][0]
if cnt >= 5:
QMessageBox.warning(self, "Límite", "Máximo 5 perfiles.")
return
nombre, ok = QInputDialog.getText(self, "Agregar perfil", "Nombre del perfil:")
if not ok or not nombre.strip():
return
nombre = nombre.strip()
try:
execute_sql("INSERT INTO perfiles (nombre) VALUES (?)", (nombre,))
# crear tabla del perfil
ensure_table_for_profile(nombre)
except sqlite3.IntegrityError:
QMessageBox.warning(self, "Error", "Ese nombre ya existe.")
return
self.refresh_list()
def rename_profile(self):
item = self.list_widget.currentItem()
if not item:
QMessageBox.warning(self, "Error", "Selecciona un perfil para renombrar.")
return
actual = item.text()
nuevo, ok = QInputDialog.getText(self, "Renombrar perfil", "Nuevo nombre:", text=actual)
if not ok or not nuevo.strip():
return
nuevo = nuevo.strip()
if nuevo == actual:
return
try:
# renombrar perfil + tabla
rename_profile(actual, nuevo)
except sqlite3.IntegrityError:
QMessageBox.warning(self, "Error", "Ese nombre ya existe.")
return
except Exception as e:
QMessageBox.warning(self, "Error", f"Ocurrió un error: {e}")
return
self.refresh_list()
def delete_profile(self):
item = self.list_widget.currentItem()
if not item:
QMessageBox.warning(self, "Error", "Selecciona un perfil para eliminar.")
return
actual = item.text()
confirmar = QMessageBox.question(self, "Confirmar", f"¿Eliminar perfil '{actual}'? Esto borrará sus datos.", QMessageBox.Yes | QMessageBox.No)
if confirmar != QMessageBox.Yes:
return
try:
delete_profile(actual)
except Exception as e:
QMessageBox.warning(self, "Error", f"Ocurrió un error: {e}")
return
self.refresh_list()
def select_profile(self):
item = self.list_widget.currentItem()
if not item:
QMessageBox.warning(self, "Error", "Selecciona un perfil para usar.")
return
elegido = item.text()
# asegurar tabla
ensure_table_for_profile(elegido)
set_current_profile(elegido)
# si estamos embebidos dentro de la app (parent es App), actualizamos en caliente
if isinstance(self.parent, App):
# notificar al parent para refrescar
self.parent.on_profile_changed()
QMessageBox.information(self, "Seleccionado", f"Perfil '{elegido}' seleccionado.")
self.accept()
return
# si se abrió al inicio, aceptamos y cerramos el dialog para que el main abra la App
QMessageBox.information(self, "Seleccionado", f"Perfil '{elegido}' seleccionado. Ahora se abrirá la aplicación.")
self.accept()
# =====================
# APP PRINCIPAL
# =====================
class App(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("📦 Registro de Tienda — Control de Ingresos, Gastos y Extras")
self.resize(1200, 700)
self.editando_id = None
# DB (QtSql)
self.db = QtSql.QSqlDatabase.addDatabase("QSQLITE")
self.db.setDatabaseName(DB)
self.db.open()
central = QWidget()
self.setCentralWidget(central)
wrapper = QVBoxLayout(central)
wrapper.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignHCenter)
wrapper.setContentsMargins(24, 24, 24, 24)
wrapper.setSpacing(18)
# botón perfiles (para abrir gestión en caliente)
btn_perfiles = QPushButton("👤 Perfiles")
btn_perfiles.clicked.connect(self.open_profile_manager_from_app)
wrapper.addWidget(btn_perfiles, alignment=QtCore.Qt.AlignLeft)
# formulario y balance (mantengo tu UI)
formulario_box = QGroupBox("📥 Agregar / Editar Registro")
formulario_layout = QVBoxLayout()
formulario_box.setLayout(formulario_layout)
fixed_width = 420
fixed_height = 260
formulario_box.setFixedWidth(fixed_width)
formulario_box.setFixedHeight(fixed_height)
self.combo_tipo = QComboBox()
self.combo_tipo.addItems(["", "Ingreso", "Gasto", "Extra"])
self.input_valor = QLineEdit()
self.input_valor.setPlaceholderText("Valor en COP")
self.input_valor.setValidator(QtGui.QDoubleValidator(0.0, 1e12, 2))
self.input_desc = QLineEdit()
self.input_desc.setPlaceholderText("Descripción (opcional)")
btn_add = QPushButton("Guardar")
btn_add.clicked.connect(self.agregar_o_editar)
btn_cancelar = QPushButton("Cancelar edición")
btn_cancelar.clicked.connect(self.cancelar_edicion)
btn_cancelar.setVisible(False)
self.btn_cancelar = btn_cancelar
btn_pdf = QPushButton("📄 Exportar Reporte PDF")
btn_pdf.clicked.connect(self.exportar_pdf)
formulario_layout.addWidget(QLabel("Tipo:"))
formulario_layout.addWidget(self.combo_tipo)
formulario_layout.addWidget(QLabel("Valor:"))
formulario_layout.addWidget(self.input_valor)
formulario_layout.addWidget(QLabel("Descripción:"))
formulario_layout.addWidget(self.input_desc)
formulario_layout.addStretch()
formulario_layout.addWidget(btn_add)
formulario_layout.addWidget(btn_cancelar)
formulario_layout.addWidget(btn_pdf)
balance_box = QGroupBox("📊 Balance General")
balance_layout = QVBoxLayout()
balance_box.setLayout(balance_layout)
balance_box.setFixedWidth(fixed_width)
balance_box.setFixedHeight(fixed_height)
self.lbl_ingresos = QLabel("Ingresos: $0")
self.lbl_gastos = QLabel("Gastos: $0")
self.lbl_extras = QLabel("Extras: $0")
self.lbl_balance = QLabel("Balance Final: $0")
for lbl in [self.lbl_ingresos, self.lbl_gastos, self.lbl_extras, self.lbl_balance]:
lbl.setStyleSheet("font-size: 15px; font-weight: bold; margin: 6px 0;")
balance_layout.addWidget(self.lbl_ingresos)
balance_layout.addWidget(self.lbl_gastos)
balance_layout.addWidget(self.lbl_extras)
balance_layout.addStretch()
balance_layout.addWidget(self.lbl_balance, alignment=QtCore.Qt.AlignBottom)
hbox_superior = QHBoxLayout()
hbox_superior.setSpacing(20)
hbox_superior.addWidget(formulario_box)
hbox_superior.addWidget(balance_box)
wrapper.addLayout(hbox_superior)
# tabla (QSqlTableModel)
self.model = QtSql.QSqlTableModel(self, self.db)
# setTable will be hecho por on_profile_changed() al iniciar
self.model.setHeaderData(0, QtCore.Qt.Horizontal, "ID")
self.model.setHeaderData(1, QtCore.Qt.Horizontal, "Tipo")
self.model.setHeaderData(2, QtCore.Qt.Horizontal, "Valor")
self.model.setHeaderData(3, QtCore.Qt.Horizontal, "Descripción")
self.model.setHeaderData(4, QtCore.Qt.Horizontal, "Fecha")
self.model.setHeaderData(5, QtCore.Qt.Horizontal, "Hora")
tabla_box = QGroupBox("📋 Registros Guardados")
tabla_layout = QVBoxLayout()
tabla_box.setLayout(tabla_layout)
self.view = QTableView()
self.view.setModel(self.model)
self.view.horizontalHeader().setStretchLastSection(True)
self.view.setMinimumHeight(320)
tabla_layout.addWidget(self.view)
btns = QHBoxLayout()
btn_edit = QPushButton("✏️ Editar seleccionado")
btn_edit.clicked.connect(self.cargar_edicion)
btn_del = QPushButton("🗑️ Eliminar seleccionado")
btn_del.clicked.connect(self.eliminar_registro)
btns.addWidget(btn_edit)
btns.addWidget(btn_del)
tabla_layout.addLayout(btns)
wrapper.addWidget(tabla_box)
# al iniciar, actualizar segun perfil actual
self.on_profile_changed()
# ---------------------
# Abrir gestor perfiles desde app (en caliente)
# ---------------------
def open_profile_manager_from_app(self):
dlg = ProfileManagerDialog(parent=self)
dlg.exec()
# ---------------------
# Cuando cambia/elijo perfil -> refrescar tabla y balance
# ---------------------
def on_profile_changed(self):
perfil = get_current_profile()
if not perfil:
# si no hay perfil actual, abrir dialog para elegir o crear
dlg = ProfileManagerDialog(parent=self)
if dlg.exec() != QDialog.Accepted:
# si usuario cancela, no hacemos nada (dejamos tabla base)
# fallback: usar tabla base 'registros'
self.model.setTable("registros")
self.model.select()
self.actualizar_balance()
return
# asegurar tabla creada
perfil = get_current_profile()
if not perfil:
# fallback a tabla base
self.model.setTable("registros")
else:
tabla = ensure_table_for_profile(perfil)
# QtSql requiere el nombre de la tabla sin comillas; pero pueden contener caracteres seguros
# usar tabla entre comillas puede fallar para QSqlTableModel en algunos drivers; usamos el nombre directo
self.model.setTable(tabla)
self.model.select()
self.actualizar_balance()
# =====================
# AGREGAR / EDITAR
# =====================
def agregar_o_editar(self):
tipo = self.combo_tipo.currentText()
valor = self.input_valor.text().strip()
desc = self.input_desc.text().strip()
if not tipo or not valor:
QMessageBox.warning(self, "Error", "Completa tipo y valor.")
return
try:
valor = float(valor)
except Exception:
QMessageBox.warning(self, "Error", "Valor inválido.")
return
fecha = datetime.now().strftime("%Y-%m-%d")
hora = datetime.now().strftime("%H:%M:%S")
perfil = get_current_profile()
if not perfil:
QMessageBox.warning(self, "Error", "No hay perfil seleccionado.")
return
tabla = profile_table_name(perfil)
conn = sqlite3.connect(DB)
cur = conn.cursor()
if self.editando_id is not None:
cur.execute(f'''
UPDATE "{tabla}" SET tipo=?, valor=?, descripcion=? WHERE id=?
''', (tipo, valor, desc, self.editando_id))
conn.commit()
conn.close()
self.editando_id = None
self.btn_cancelar.setVisible(False)
QMessageBox.information(self, "Editado", "Registro actualizado correctamente.")
else:
cur.execute(f'''
INSERT INTO "{tabla}" (tipo, valor, descripcion, fecha, hora)
VALUES (?, ?, ?, ?, ?)
''', (tipo, valor, desc, fecha, hora))
conn.commit()
conn.close()
QMessageBox.information(self, "OK", "Registro agregado correctamente.")
self.model.select()
self.actualizar_balance()
self.combo_tipo.setCurrentIndex(0)
self.input_valor.clear()
self.input_desc.clear()
# =====================
# CARGAR EDICIÓN
# =====================
def cargar_edicion(self):
index = self.view.currentIndex()
if not index.isValid():
QMessageBox.warning(self, "Error", "Selecciona un registro.")
return
fila = index.row()
self.editando_id = self.model.index(fila, 0).data()
tipo = self.model.index(fila, 1).data()
valor = self.model.index(fila, 2).data()
desc = self.model.index(fila, 3).data()
self.combo_tipo.setCurrentText(tipo)
self.input_valor.setText(str(valor))
self.input_desc.setText(desc)
self.btn_cancelar.setVisible(True)
def cancelar_edicion(self):
self.editando_id = None
self.combo_tipo.setCurrentIndex(0)
self.input_valor.clear()
self.input_desc.clear()
self.btn_cancelar.setVisible(False)
# =====================
# ELIMINAR
# =====================
def eliminar_registro(self):
index = self.view.currentIndex()
if not index.isValid():
QMessageBox.warning(self, "Error", "Selecciona un registro para eliminar.")
return
fila = index.row()
id_reg = self.model.index(fila, 0).data()
perfil = get_current_profile()
if not perfil:
QMessageBox.warning(self, "Error", "No hay perfil seleccionado.")
return
tabla = profile_table_name(perfil)
confirm = QMessageBox.question(self, "Confirmar", "¿Seguro que deseas eliminar este registro?", QMessageBox.Yes | QMessageBox.No)
if confirm == QMessageBox.Yes:
conn = sqlite3.connect(DB)
conn.execute(f'DELETE FROM "{tabla}" WHERE id=?', (id_reg,))
conn.commit()
conn.close()
self.model.select()
self.actualizar_balance()
QMessageBox.information(self, "Eliminado", "Registro eliminado correctamente.")
# =====================
# BALANCE
# =====================
def actualizar_balance(self):
perfil = get_current_profile()
if not perfil:
# mostrar 0s
self.lbl_ingresos.setText("Ingresos: $0")
self.lbl_gastos.setText("Gastos: $0")
self.lbl_extras.setText("Extras: $0")
self.lbl_balance.setText("Balance Final: $0")
return
tabla = profile_table_name(perfil)
conn = sqlite3.connect(DB)
try:
datos = conn.execute(f'SELECT tipo, valor FROM "{tabla}"').fetchall()
except sqlite3.OperationalError:
datos = []
conn.close()
total_ing = sum(v for t, v in datos if t == "Ingreso")
total_gas = sum(v for t, v in datos if t == "Gasto")
total_ext = sum(v for t, v in datos if t == "Extra")
balance = total_ing - total_gas + total_ext
self.lbl_ingresos.setText(f"Ingresos: ${total_ing:,.0f}")
self.lbl_gastos.setText(f"Gastos: ${total_gas:,.0f}")
self.lbl_extras.setText(f"Extras: ${total_ext:,.0f}")
self.lbl_balance.setText(f"Balance Final: ${balance:,.0f}")
# =====================
# PDF
# =====================
def exportar_pdf(self):
perfil = get_current_profile()
if not perfil:
QMessageBox.information(self, "Sin datos", "No hay perfil seleccionado.")
return
tabla = profile_table_name(perfil)
conn = sqlite3.connect(DB)
try:
datos = conn.execute(f'SELECT * FROM "{tabla}" ORDER BY fecha DESC, hora DESC').fetchall()
except sqlite3.OperationalError:
datos = []
conn.close()
if not datos:
QMessageBox.information(self, "Sin datos", "No hay registros.")
return
nombre = "reporte_tienda.pdf"
doc = SimpleDocTemplate(nombre, pagesize=letter)
estilos = getSampleStyleSheet()
elems = []
elems.append(Paragraph("<b>REPORTE COMPLETO DE TIENDA</b>", estilos["Title"]))
elems.append(Spacer(1, 20))
total_ing = 0
total_gas = 0
total_ext = 0
for r in datos:
_, tipo, valor, desc, fecha, hora = r
if tipo == "Ingreso":
total_ing += valor
if tipo == "Gasto":
total_gas += valor
if tipo == "Extra":
total_ext += valor
linea = f"{fecha} {hora} — {tipo}: ${valor:,.0f} — {desc}"
elems.append(Paragraph(linea, estilos["Normal"]))
elems.append(Spacer(1, 5))
elems.append(Spacer(1, 20))
resumen = (
f"<b>Total ingresos:</b> ${total_ing:,.0f}<br/>"
f"<b>Total gastos:</b> ${total_gas:,.0f}<br/>"
f"<b>Total extras:</b> ${total_ext:,.0f}<br/>"
f"<b>Balance final:</b> ${(total_ing - total_gas + total_ext):,.0f}"
)
elems.append(Paragraph(resumen, estilos["Normal"]))
doc.build(elems)
QMessageBox.information(self, "PDF generado", f"PDF creado: {os.path.abspath(nombre)}")
# =====================
# INICIO DEL PROGRAMA
# =====================
def ensure_has_at_least_one_profile():
cnt = fetch_sql("SELECT COUNT(*) FROM perfiles")[0][0]
if cnt == 0:
# crear un perfil por defecto llamado 'General'
try:
execute_sql("INSERT INTO perfiles (nombre) VALUES (?)", ("General",))
ensure_table_for_profile("General")
except Exception:
pass
if __name__ == "__main__":
# asegurar al menos 1 perfil
ensure_has_at_least_one_profile()
# Abrir dialogo de selección de perfiles (modal). Si el usuario selecciona, se abre App.
app = QApplication(sys.argv)
dlg = ProfileManagerDialog()
res = dlg.exec()
if res == QDialog.Accepted:
# abrir app con perfil seleccionado
win = App()
win.show()
sys.exit(app.exec())
else:
# usuario canceló -> salir
sys.exit(0)