autocompra/importar_tickets.py

95 lines
3.3 KiB
Python

import os
import re
from datetime import datetime
import mysql.connector
from PyPDF2 import PdfReader
# Configura tu conexión
DB_CONFIG = {
'host': 'tecnologia-facil.es',
'user': 'tatvil',
'password': 'Eavne,e1m',
'database': 'autocompra'
}
TICKETS_DIR = './tickets'
def extraer_datos_pdf(ruta_pdf):
reader = PdfReader(ruta_pdf)
texto = ""
for page in reader.pages:
texto += page.extract_text() + "\n"
# Fecha
match_fecha = re.search(r"(\d{2}/\d{2}/\d{4})", texto)
fecha = datetime.strptime(match_fecha.group(1), "%d/%m/%Y") if match_fecha else None
# Total
match_total = re.search(r"TOTAL\s*\(?€?\)?\s*(\d+,\d{2})", texto)
total = float(match_total.group(1).replace(",", ".")) if match_total else 0.0
# Método de pago
metodo = "Tarjeta" if "TARJETA" in texto.upper() else "Efectivo"
# Productos
productos = []
for linea in texto.splitlines():
linea = linea.strip()
if re.match(r".*TOTAL.*|TARJETA|IVA|CUOTA|BASE|AUT:|VERIFICADO|N\.C:|IMPORTE|DEVOLUCIONES", linea, re.IGNORECASE):
continue
match = re.match(r"(\d+)\s+(.*?)\s+(\d+,\d{2})\s+(\d+,\d{2})", linea)
if match:
cantidad = int(match.group(1))
nombre = match.group(2).strip().upper()
precio_unitario = float(match.group(3).replace(",", "."))
precio_total = float(match.group(4).replace(",", "."))
productos.append((nombre, cantidad, precio_unitario, precio_total))
else:
match_simple = re.match(r"1\s+(.*?)\s+(\d+,\d{2})", linea)
if match_simple:
nombre = match_simple.group(1).strip().upper()
precio = float(match_simple.group(2).replace(",", "."))
productos.append((nombre, 1, precio, precio))
return fecha, total, metodo, productos
def insertar_en_bd(fecha, total, metodo, productos, cursor):
cursor.execute(
"INSERT INTO tickets (fecha, total, metodo_pago) VALUES (%s, %s, %s)",
(fecha, total, metodo)
)
ticket_id = cursor.lastrowid
for nombre, cantidad, precio_unitario, precio_total in productos:
cursor.execute(
"INSERT INTO productos (ticket_id, nombre, cantidad, precio_unitario, precio_total) VALUES (%s, %s, %s, %s, %s)",
(ticket_id, nombre, cantidad, precio_unitario, precio_total)
)
def procesar_todos_los_pdfs():
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
for archivo in os.listdir(TICKETS_DIR):
if archivo.lower().endswith(".pdf"):
ruta = os.path.join(TICKETS_DIR, archivo)
print(f"📄 Procesando: {archivo}")
try:
fecha, total, metodo, productos = extraer_datos_pdf(ruta)
if fecha and productos:
insertar_en_bd(fecha, total, metodo, productos, cursor)
print(f"✅ Insertado: {len(productos)} productos (fecha {fecha.strftime('%d/%m/%Y')})")
else:
print(f"⚠️ No se pudo extraer la información de {archivo}")
except Exception as e:
print(f"❌ Error procesando {archivo}: {e}")
conn.commit()
cursor.close()
conn.close()
print("🎉 Proceso finalizado.")
if __name__ == "__main__":
procesar_todos_los_pdfs()