untitled

Pasted Nov 16, 2026, 4:43 PM1 file1,181 lines

Scan to open on your phone

Point a camera at the QR code - it opens this exact paste, no app needed.

https://codepastes.com/zzgs3q792w4506b9
untitled
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import hashlib
import math
from datetime import datetime, timedelta, timezone
import winsound
from PIL import Image, ImageTk
import os
import sys
import gspread
from oauth2client.service_account import ServiceAccountCredentials

def hash_password(password, salt):
    return hashlib.sha256((password + salt).encode()).hexdigest()

SECRET_KEY = "X9kL2pA8sQ"
historial = {}  # Diccionario: HWID -> (serial, fecha_exp)

sheet = None

def conectar_sheets():
    global sheet

    if sheet is None:

        scope = [
            "https://spreadsheets.google.com/feeds",
            "https://www.googleapis.com/auth/drive"
        ]

        ruta_credenciales = obtener_ruta_recurso("credenciales.json")

        creds = ServiceAccountCredentials.from_json_keyfile_name(
            ruta_credenciales, scope
        )

        cliente = gspread.authorize(creds)

        sheet = cliente.open("Licencias").sheet1

    return sheet

def conectar_usuarios():
    scope = [
        "https://spreadsheets.google.com/feeds",
        "https://www.googleapis.com/auth/drive"
    ]

    ruta_credenciales = obtener_ruta_recurso("credenciales.json")

    creds = ServiceAccountCredentials.from_json_keyfile_name(
        ruta_credenciales, scope
    )

    cliente = gspread.authorize(creds)

    sheet = cliente.open("Licencias").worksheet("usuarios")
    return sheet


def validar_login(user, password):
    sheet = conectar_usuarios()
    data = sheet.get_all_records()

    for fila in data:
        usuario = str(fila.get("usuario", "")).strip()
        hash_guardado = str(fila.get("password", "")).strip()
        salt = str(fila.get("salt", "")).strip()

        if usuario == user:
            hash_input = hash_password(password, salt)
            return hash_input == hash_guardado

    return False

def mostrar_dialogo_personalizado(titulo, mensaje, tipo="info", parent=None): 
    if parent is None: 
        parent = tk._default_root

    dlg = tk.Toplevel(parent)
    dlg.withdraw()
    dlg.transient(parent)
    dlg.grab_set()
    dlg.resizable(False, False)
    dlg.title(titulo)

    try:
        dlg.iconbitmap(obtener_ruta_recurso("icono.ico"))
    except:
        pass

    # 🎨 Colores según tipo
    colores = {
        "info":    ("#1e1e1e", "#4caf50"),
        "warning": ("#1e1e1e", "#ffc107"),
        "error":   ("#1e1e1e", "#f44336"),
        "confirm": ("#1e1e1e", "#2196f3")
    }

    bg, color_borde = colores.get(tipo, ("#1e1e1e", "#4caf50"))

    # 📐 Tamaño dinámico
    lineas = mensaje.count("\n") + 1
    alto = 170 + (lineas * 10)
    ancho = 420

    dlg.geometry(f"{ancho}x{alto}")

    # 📍 Centrar
    parent.update_idletasks()
    x = parent.winfo_rootx() + (parent.winfo_width() // 2) - (ancho // 2)
    y = parent.winfo_rooty() + (parent.winfo_height() // 2) - (alto // 2)
    dlg.geometry(f"{ancho}x{alto}+{x}+{y}")

    # ✨ Fade in
    dlg.attributes("-alpha", 0.0)
    dlg.deiconify()

    def fade_in(op=0.0):
        if op < 1.0:
            dlg.attributes("-alpha", op)
            dlg.after(20, fade_in, op + 0.08)
        else:
            dlg.attributes("-alpha", 1.0)

    fade_in()

    # 🔊 Sonido
    sonidos = {
        "info": winsound.MB_ICONASTERISK,
        "warning": winsound.MB_ICONEXCLAMATION,
        "error": winsound.MB_ICONHAND,
        "confirm": winsound.MB_ICONQUESTION
    }

    try:
        winsound.MessageBeep(sonidos.get(tipo, winsound.MB_OK))
    except:
        pass

    # 🎨 Frame principal
    frame = tk.Frame(dlg, bg=bg, bd=2, relief="flat")
    frame.pack(fill="both", expand=True)

    # Barra lateral de color
    barra = tk.Frame(frame, bg=color_borde, width=6)
    barra.pack(side="left", fill="y")

    contenido = tk.Frame(frame, bg=bg, padx=15, pady=15)
    contenido.pack(fill="both", expand=True)

    # 🖼️ Icono
    try:
        if tipo == "warning":
            path = obtener_ruta_recurso("icon_warning.png")
        elif tipo == "error":
            path = obtener_ruta_recurso("icon_error.png")
        else:
            path = obtener_ruta_recurso("icon_success.png")

        img = Image.open(path).resize((48, 48))
        icon = ImageTk.PhotoImage(img)

        lbl_icon = tk.Label(contenido, image=icon, bg=bg)
        lbl_icon.image = icon
        lbl_icon.grid(row=0, column=0, rowspan=2, padx=(0, 10), sticky="n")
    except:
        tk.Label(contenido, text="⚠️", font=("Segoe UI Emoji", 30), bg=bg, fg="white")\
            .grid(row=0, column=0, rowspan=2)

    # 📝 Texto
    tk.Label(
        contenido,
        text=titulo,
        font=("Segoe UI", 11, "bold"),
        bg=bg,
        fg="white"
    ).grid(row=0, column=1, sticky="w")

    tk.Label(
        contenido,
        text=mensaje,
        wraplength=300,
        justify="left",
        bg=bg,
        fg="#dcdcdc",
        font=("Segoe UI", 10)
    ).grid(row=1, column=1, sticky="w", pady=5)

    resultado = {"value": False}

    # 🔘 Botones
    btn_frame = tk.Frame(contenido, bg=bg)
    btn_frame.grid(row=2, column=0, columnspan=2, sticky="e", pady=10)

    def fade_out(callback):
        op = dlg.attributes("-alpha")
        if op > 0:
            dlg.attributes("-alpha", op - 0.08)
            dlg.after(20, fade_out, callback)
        else:
            callback()

    def aceptar():
        resultado["value"] = True
        fade_out(dlg.destroy)

    def cancelar():
        resultado["value"] = False
        fade_out(dlg.destroy)

    def crear_boton(texto, comando, tipo="normal"):
        colores = {
            "normal": {
                "bg": "#2d2d2d",
                "hover": "#3a3a3a",
                "active": "#1f1f1f"
            },
            "primary": {
                "bg": "#4caf50",      # verde elegante
                "hover": "#43a047",
                "active": "#388e3c"
            },
            "danger": {
                "bg": "#e53935",
                "hover": "#d32f2f",
                "active": "#b71c1c"
            }
        }

        c = colores.get(tipo, colores["normal"])

        btn = tk.Label(
            btn_frame,
            text=texto,
            bg=c["bg"],
            fg="white",
            font=("Segoe UI", 9, "bold"),
            padx=14,
            pady=7,
            cursor="hand2"
        )

    # Hover
        btn.bind("<Enter>", lambda e: btn.config(bg=c["hover"]))
        btn.bind("<Leave>", lambda e: btn.config(bg=c["bg"]))

    # Click efecto
        def click(e):
            btn.config(bg=c["active"])
            btn.after(100, lambda: comando())

        btn.bind("<Button-1>", click)

        btn.pack(side="right", padx=6)
        return btn

    if tipo == "confirm":
        crear_boton("Cancelar", cancelar, "normal")
        crear_boton("Aceptar", aceptar, "primary")
    else:
        crear_boton("Aceptar", aceptar, "primary")

    dlg.protocol("WM_DELETE_WINDOW", cancelar)

    parent.wait_window(dlg)
    return resultado["value"]

def ahora_utc():
    return datetime.now(timezone.utc)

def convertir_a_local(fecha_utc):
    return fecha_utc.astimezone()  # usa la zona horaria del sistema

def obtener_ruta_recurso(nombre):
    if hasattr(sys, "_MEIPASS"):
        return os.path.join(sys._MEIPASS, nombre)
    return os.path.join(os.path.abspath("."), nombre)

def buscar_hwid_sheets(hwid):
    sheet = conectar_sheets()

    data = sheet.get_all_values()  # 👈 IMPORTANTE (no usar get_all_records)

    for i, fila in enumerate(data):
        # fila[0] = columna HWID
        if i == 0:
            continue  # saltar encabezado

        if fila[0] == hwid:
            return fila, i + 1  # 👈 índice real de Google Sheets

    return None, None

def existe_hwid_local(hwid):
    return hwid in historial

def cargar_licencias_sheets():
    global historial

    sheet = conectar_sheets()
    data = sheet.get_all_records()

    historial.clear()  # 🔥 importante para evitar duplicados al recargar

    for fila in data:
        try:
            hwid = fila["HWID"]
            serial = fila["Serial"]
            fecha_exp = datetime.strptime(
                fila["Fecha_vencimiento"], "%Y-%m-%d %H:%M:%S"
            ).replace(tzinfo=timezone.utc)
            estado_excel = fila.get("Estado", "").lower()

            dias_restantes = math.ceil((fecha_exp - ahora_utc()).total_seconds() / 86400)

            # 🔒 Mantener bloqueadas
            if estado_excel == "bloqueada":
                estado = "bloqueada"
            else:
                if dias_restantes <= 0:
                    estado = "vencida"
                elif dias_restantes <= 5:
                    estado = "por_vencer"
                else:
                    estado = "activo"

                # 🔥 Sincronizar estado si cambió
                if estado_excel != estado:
                    fila_data, fila_num = buscar_hwid_sheets(hwid)
                    if fila_data:
                        actualizar_estado_sheets(hwid, estado)

            # Guardar en historial
            historial[hwid] = (serial, fecha_exp, estado)

        except Exception as e:
            print(f"Error cargando fila: {fila} -> {e}")

    actualizar_historial()
def guardar_licencia_sheets(hwid, serial, fecha_inicio, fecha_vencimiento, estado):
    sheet = conectar_sheets()
    sheet.append_row([
        hwid,
        serial,
        fecha_inicio.strftime("%Y-%m-%d %H:%M:%S"),
        fecha_vencimiento.strftime("%Y-%m-%d %H:%M:%S"),
        estado
    ])

def actualizar_licencia_sheets(fila, serial, fecha_vencimiento):

    sheet = conectar_sheets()

    sheet.update(range_name=f"B{fila}", values=[[serial]])
    sheet.update(range_name=f"D{fila}", values=[[fecha_vencimiento.strftime("%Y-%m-%d %H:%M:%S")]])

def actualizar_estado_sheets(hwid, estado):
    fila_data, fila = buscar_hwid_sheets(hwid)
    if fila_data:
        sheet = conectar_sheets()
        sheet.update(range_name=f"E{fila}", values=[[estado]])

# === Función para generar o renovar serial ===
def generar_serial():
    hwid = entry_hwid.get().strip()
    dias_texto = entry_dias.get().strip()

    if not hwid:
        mostrar_dialogo_personalizado("Advertencia", "Debes ingresar el HWID", "warning")
        return
    if not dias_texto.isdigit():
        mostrar_dialogo_personalizado("Error", "Los días deben ser un número", "error")
        return

    dias = int(dias_texto)
    fecha_actual = ahora_utc()

    try:
        fila_data, fila = buscar_hwid_sheets(hwid)
    except Exception as e:
        mostrar_dialogo_personalizado("Error", f"No se pudo conectar con Google Sheets\n{e}", "error")
        return
    
    if hwid in historial:
        mostrar_dialogo_personalizado("Aviso", "Este HWID ya tiene una licencia. Usa el botón EXTENDER.", "warning")
        return

    fecha_exp = fecha_actual + timedelta(days=dias)

    fecha_str = fecha_exp.strftime("%Y%m%d")
    base = hwid + SECRET_KEY + fecha_str
    firma = hashlib.sha256(base.encode()).hexdigest().upper()
    serial = f"{firma[:5]}-{firma[5:10]}-{firma[10:15]}-{fecha_str}-{firma[15:20]}"

    # Determinar estado según días restantes
    dias_restantes = max(
        math.ceil((fecha_exp - fecha_actual).total_seconds() / 86400),
        0
    )
    if dias_restantes <= 0:
        estado = "vencida"
    elif dias_restantes <= 5:
        estado = "por_vencer"
    else:
        estado = "activo"

    # Guardar en historial
    historial[hwid] = (serial, fecha_exp, estado)

    if fila_data:
        actualizar_licencia_sheets(fila, serial, fecha_exp)
        actualizar_estado_sheets(hwid, estado)
    else:
        guardar_licencia_sheets(hwid, serial, fecha_actual, fecha_exp, estado)

    mostrar_serial_y_fecha(hwid)
    actualizar_historial(hwid)  # actualización inmediata en Treeview

def renovar_todos_reiniciando():
    fecha_actual = ahora_utc()

    for hwid in list(historial.keys()):
        dias_texto = entry_dias.get().strip()
        if not dias_texto.isdigit():
            continue
        dias = int(dias_texto)

        # Reinicia desde hoy
        fecha_exp = fecha_actual + timedelta(days=dias)
        fecha_str = fecha_exp.strftime("%Y%m%d")
        base = hwid + SECRET_KEY + fecha_str
        firma = hashlib.sha256(base.encode()).hexdigest().upper()
        serial = f"{firma[:5]}-{firma[5:10]}-{firma[10:15]}-{fecha_str}-{firma[15:20]}"

        historial[hwid] = (serial, fecha_exp, "activo")

        # Actualizar Google Sheets
        fila_data, fila = buscar_hwid_sheets(hwid)
        if fila_data:
            actualizar_licencia_sheets(fila, serial, fecha_exp)
        else:
            guardar_licencia_sheets(hwid, serial, fecha_actual, fecha_exp)

    # Actualizar interfaz
    actualizar_historial()
    mostrar_dialogo_personalizado("Éxito", "Todos los seriales fueron reiniciados", "info")

# === Mostrar serial y fecha en la interfaz ===
def mostrar_serial_y_fecha(hwid):
    if hwid not in historial:
        return

    serial, fecha_exp, estado = historial[hwid]
    

    # Mostrar serial
    entry_serial.config(state="normal")
    entry_serial.delete(0, tk.END)
    entry_serial.insert(0, serial)
    entry_serial.config(state="readonly")

    # Mostrar fecha y días restantes
    dias_restantes = max(
        math.ceil((fecha_exp -  ahora_utc()).total_seconds() / 86400),
        0
    )
    fecha_local = convertir_a_local(fecha_exp)

    label_fecha.config(
        text=f"Expira el: {fecha_local.strftime('%d/%m/%Y %H:%M')} | Días restantes: {dias_restantes}"
    )

    # Cambiar color según días restantes
    if dias_restantes <= 2:
        frame_serial.config(style="Rojo.TLabelframe")
    elif dias_restantes <= 5:
        frame_serial.config(style="Amarillo.TLabelframe")
    else:
        frame_serial.config(style="Verde.TLabelframe")

    actualizar_historial(hwid)

# === Detectar HWID existente y cargar datos automáticamente ===
def hwid_key_release(event=None):
    hwid = entry_hwid.get().strip()
    existe = existe_hwid_local(hwid) if hwid else False

    if existe:
        btn_generar.config(text=" Ya existe (usar Extender)", state="disabled")
    else:
        btn_generar.config(text=" Generar Licencia", state="normal")

    if hwid in historial:
        fecha_exp = historial[hwid][1]
        dias_restantes = max(
            math.ceil((fecha_exp - ahora_utc()).total_seconds() / 86400),
            0
        )
        entry_dias.delete(0, tk.END)
        entry_dias.insert(0, str(dias_restantes))
        mostrar_serial_y_fecha(hwid)
    else:
        # Si HWID no existe, limpiar serial y fecha
        entry_serial.config(state="normal")
        entry_serial.delete(0, tk.END)
        entry_serial.config(state="readonly")
        label_fecha.config(text="Expira el: --/--/----")
        frame_serial.config(style="Verde.TLabelframe")

# === Actualizar historial visual ===
def actualizar_historial(resaltar_hwid=None):
    # Limpiar tabla
    for row in tree_historial.get_children():
        tree_historial.delete(row)

    item_seleccion = None

    for hwid, (serial, fecha_exp, estado) in sorted(historial.items(), key=lambda x: x[1][1]):
        dias_restantes = max(
            math.ceil((fecha_exp -  ahora_utc()).total_seconds() / 86400),
            0
        )
        fecha_local = convertir_a_local(fecha_exp)
        expira = fecha_local.strftime('%d/%m/%Y %H:%M')

        # Determinar estado automático si no está bloqueado
        if estado != "bloqueada":
            if dias_restantes <= 0:
                estado_real = "vencida"
            elif dias_restantes <= 5:
                estado_real = "por_vencer"
            else:
                estado_real = "activo"
        else:
            estado_real = "bloqueada"

        # Insertar en el treeview
        item = tree_historial.insert(
            "",
            "end",
            values=(hwid, serial, expira, dias_restantes, estado_real.capitalize()),
            tags=(estado_real,)
        )

        # Seleccionar si corresponde
        if hwid == resaltar_hwid:
            item_seleccion = item

    if item_seleccion:
        tree_historial.selection_set(item_seleccion)
        tree_historial.see(item_seleccion)

    actualizar_estadisticas()    

def filtrar_estado(tipo):
    for row in tree_historial.get_children():
        tree_historial.delete(row)

    for hwid, (serial, fecha_exp, estado) in historial.items():
        dias = max(
            math.ceil((fecha_exp - ahora_utc()).total_seconds() / 86400),
            0
        )

        if estado == "bloqueada":
            estado_real = "bloqueada"
        elif dias <= 0:
            estado_real = "vencida"
        elif dias <= 5:
            estado_real = "por_vencer"
        else:
            estado_real = "activo"

        if tipo == "todos" or estado_real == tipo:
            tree_historial.insert(
                "",
                "end",
                values=(
                    hwid,
                    serial,
                    convertir_a_local(fecha_exp).strftime("%d/%m/%Y %H:%M"),
                    dias,
                    estado_real.capitalize()
                ),
                tags=(estado_real,)
            )

def buscar_en_historial():
    texto = entry_buscar.get().strip().lower()

    # 👉 Si está vacío, mostrar todo ordenado
    if texto == "":
        actualizar_historial()
        return

    # Limpiar tabla
    for row in tree_historial.get_children():
        tree_historial.delete(row)

    # Filtrar resultados
    for hwid, (serial, fecha_exp, estado) in historial.items():
        if texto in hwid.lower() or texto in serial.lower():

            dias_restantes = math.ceil((fecha_exp - ahora_utc()).total_seconds() / 86400)

            if estado == "bloqueada":
                tag = "bloqueada"
            elif dias_restantes <= 0:
                tag = "vencida"
            elif dias_restantes <= 5:
                tag = "por_vencer"
            else:
                tag = "activo"

            tree_historial.insert(
                "",
                "end",
                values=(
                    hwid,
                    serial,
                    convertir_a_local(fecha_exp).strftime("%d/%m/%Y %H:%M"),
                    dias_restantes,
                    estado.capitalize()
                ),
                tags=(tag,)
            )
def actualizar_estadisticas():

    activas = 0
    vencidas = 0
    bloqueadas = 0
    por_vencer = 0

    for hwid, (serial, fecha_exp, estado) in historial.items():

        dias_restantes = math.ceil(
            (fecha_exp - ahora_utc()).total_seconds() / 86400
        )

        if estado == "bloqueada":
            bloqueadas += 1

        elif dias_restantes <= 0:
            vencidas += 1

        elif dias_restantes <= 5:
            por_vencer += 1

        else:
            activas += 1

    total = len(historial)

    label_stats.config(
        text=(
            f"Todas: {total}   |   "
            f"Activas: {activas}   |   "
            f"Por vencer: {por_vencer}   |   "
            f"Vencidas: {vencidas}   |   "
            f"Bloqueadas: {bloqueadas}"
        )
    )

# === Copiar serial al portapapeles ===
def copiar_serial(root):
    print("DEBUG copiar_serial ejecutado")

    serial = entry_serial.get()
    print("SERIAL:", serial)

    if serial:
        root.clipboard_clear()
        root.clipboard_append(serial)

        mostrar_dialogo_personalizado(
            "Éxito",
            "Serial copiado al portapapeles",
            "info",
            parent=root
        )
    else:
        print("Serial vacío")

# === Exportar historial a .txt ===
def exportar_historial():
    if not historial:
        mostrar_dialogo_personalizado("Advertencia", "No hay seriales para exportar", "warning")
        return
    ruta = filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Archivos de texto", "*.txt")],
        title="Guardar historial"
    )
    if ruta:
        with open(ruta, "w") as f:
            for hwid, (serial, fecha_exp, estado) in historial.items():
                dias_restantes = max(
                    math.ceil((fecha_exp - ahora_utc()).total_seconds() / 86400),
                    0
                )
                f.write(f"{hwid} | {serial} | Expira: {convertir_a_local(fecha_exp).strftime('%d/%m/%Y %H:%M')} | Días restantes: {dias_restantes} | Estado: {estado}\n")
        mostrar_dialogo_personalizado("Éxito", f"Historial guardado en {ruta}", "info")


def limpiar_historial():
    global historial
    if mostrar_dialogo_personalizado("Confirmar", "¿Deseas borrar todo el historial?", "confirm"):
        historial.clear()
        actualizar_historial()

def renovar_todos():
    for hwid in list(historial.keys()):
        entry_hwid.delete(0, tk.END)
        entry_hwid.insert(0, hwid)
        generar_serial()
    mostrar_dialogo_personalizado("Éxito", "Todos los seriales fueron renovados", "info")


# --- Extender / Restar días / Bloquear ---
def extender_licencia():
    hwid = entry_hwid.get().strip()
    if hwid not in historial:
        mostrar_dialogo_personalizado("Error", "HWID no encontrado", "error")
        return
    dias_texto = entry_dias.get().strip()
    if not dias_texto.isdigit():
        mostrar_dialogo_personalizado("Error", "Días inválidos", "error")
        return
    dias = int(dias_texto)
    fecha_exp = historial[hwid][1] + timedelta(days=dias)
    serial = generar_nuevo_serial(hwid, fecha_exp)
    historial[hwid] = (serial, fecha_exp, "activo")
    fila_data, fila = buscar_hwid_sheets(hwid)
    if fila_data:
        actualizar_licencia_sheets(fila, serial, fecha_exp)
    actualizar_historial(hwid)
    mostrar_serial_y_fecha(hwid)
    mostrar_dialogo_personalizado("Éxito", f"{hwid} extendido {dias} días", "info")

def restar_dias_licencia():
    hwid = entry_hwid.get().strip()
    if hwid not in historial:
        mostrar_dialogo_personalizado("Error", "HWID no encontrado", "error")
        return
    dias_texto = entry_dias.get().strip()
    if not dias_texto.isdigit():
        mostrar_dialogo_personalizado("Error", "Días inválidos", "error")
        return
    dias = int(dias_texto)
    fecha_exp = historial[hwid][1] - timedelta(days=dias)
    if fecha_exp < ahora_utc():
        fecha_exp = ahora_utc()
    serial = generar_nuevo_serial(hwid, fecha_exp)
    historial[hwid] = (serial, fecha_exp, "activo")
    fila_data, fila = buscar_hwid_sheets(hwid)
    if fila_data:
        actualizar_licencia_sheets(fila, serial, fecha_exp)
    actualizar_historial(hwid)
    mostrar_serial_y_fecha(hwid)
    mostrar_dialogo_personalizado("Éxito", f"{hwid} restado {dias} días", "info")

def bloquear_licencia():
    hwid = entry_hwid.get().strip()

    if hwid not in historial:
        mostrar_dialogo_personalizado("Error", "HWID no encontrado", "error")
        return

    serial, fecha_exp, estado = historial[hwid]

    historial[hwid] = (serial, fecha_exp, "bloqueada")

    actualizar_estado_sheets(hwid, "bloqueada")

    actualizar_historial(hwid)
    mostrar_serial_y_fecha(hwid)

    mostrar_dialogo_personalizado("Éxito", f"{hwid} bloqueado", "info")

def desbloquear_licencia():
    hwid = entry_hwid.get().strip()

    if hwid not in historial:
        mostrar_dialogo_personalizado("Error", "HWID no encontrado", "error")
        return

    serial, fecha_exp, estado = historial[hwid]

    historial[hwid] = (serial, fecha_exp, "activo")

    actualizar_estado_sheets(hwid, "activo")

    actualizar_historial(hwid)
    mostrar_serial_y_fecha(hwid)

    mostrar_dialogo_personalizado("Éxito", f"{hwid} desbloqueado", "info")

def eliminar_licencia():
    seleccionado = tree_historial.selection()

    if not seleccionado:
        mostrar_dialogo_personalizado("Advertencia", "Selecciona una licencia", "warning")
        return

    values = tree_historial.item(seleccionado[0], "values")
    hwid = values[0]

    confirmar = mostrar_dialogo_personalizado(
        "Confirmar",
        f"¿Eliminar licencia de {hwid}?",
        "confirm"
    )

    if not confirmar:
        return

    # Eliminar de Google Sheets PRIMERO
    fila_data, fila = buscar_hwid_sheets(hwid)

    if fila_data:
        sheet = conectar_sheets()
        print(f"Eliminando fila real: {fila}")
        sheet.delete_rows(fila)
    else:
        mostrar_dialogo_personalizado("Error", "No se encontró en Google Sheets", "error")

    # Luego eliminar del historial local
    if hwid in historial:
        del historial[hwid]

    actualizar_historial()
    mostrar_dialogo_personalizado("Éxito", "Licencia eliminada correctamente", "info")

# --- Generar serial auxiliar para extender/restar ---
def generar_nuevo_serial(hwid, fecha_exp):
    fecha_str = fecha_exp.strftime("%Y%m%d")
    base = hwid + SECRET_KEY + fecha_str
    firma = hashlib.sha256(base.encode()).hexdigest().upper()
    return f"{firma[:5]}-{firma[5:10]}-{firma[10:15]}-{fecha_str}-{firma[15:20]}"




# === Interfaz ===
def iniciar_app(root):
    global entry_hwid, entry_dias, tree_historial
    global btn_generar, entry_serial, label_fecha, frame_serial
    global label_stats, entry_buscar
    

    # ICONO
    try:
        root.iconbitmap(obtener_ruta_recurso("icono.ico"))
    except:
        pass

    try:
        icono_img = tk.PhotoImage(file=obtener_ruta_recurso("icono.png"))
        root.iconphoto(True, icono_img)
        root.icono_img = icono_img
    except:
        pass

    # 🔥 ICONOS (AQUÍ ES DONDE FALLABA)
    global icon_generar, icon_extender, icon_restar, icon_bloquear
    global icon_desbloquear, icon_eliminar, icon_limpiar
    global icon_exportar, icon_copiar, icon_renovar

    icon_generar = tk.PhotoImage(file=obtener_ruta_recurso("icons/generar.png"))
    icon_extender = tk.PhotoImage(file=obtener_ruta_recurso("icons/extender.png"))
    icon_restar = tk.PhotoImage(file=obtener_ruta_recurso("icons/restar.png"))
    icon_bloquear = tk.PhotoImage(file=obtener_ruta_recurso("icons/bloquear.png"))
    icon_desbloquear = tk.PhotoImage(file=obtener_ruta_recurso("icons/desbloquear.png"))
    icon_eliminar = tk.PhotoImage(file=obtener_ruta_recurso("icons/eliminar.png"))
    icon_limpiar = tk.PhotoImage(file=obtener_ruta_recurso("icons/limpiar.png"))
    icon_exportar = tk.PhotoImage(file=obtener_ruta_recurso("icons/exportar.png"))
    icon_copiar = tk.PhotoImage(file=obtener_ruta_recurso("icons/copiar.png"))
    icon_renovar = tk.PhotoImage(file=obtener_ruta_recurso("icons/renovar.png"))

    # evitar garbage collector
    root.icon_generar = icon_generar
    root.icon_extender = icon_extender
    root.icon_restar = icon_restar
    root.icon_bloquear = icon_bloquear
    root.icon_desbloquear = icon_desbloquear
    root.icon_eliminar = icon_eliminar
    root.icon_limpiar = icon_limpiar
    root.icon_exportar = icon_exportar
    root.icon_copiar = icon_copiar
    root.icon_renovar = icon_renovar

    root.title("Generador de Licencias PRO+")
    root.geometry("650x620")
    root.resizable(True, True)

# Estilos
    style = ttk.Style()

    style.theme_use("clam")

# Botones modernos
    style.configure("TButton",
        font=("Segoe UI", 10, "bold"),
        padding=6
    )

# Labels
    style.configure("TLabel",
        font=("Segoe UI", 10)
    )

# Entradas
    style.configure("TEntry",
        padding=5
    )

# Treeview moderno
    style.configure("Treeview",
        font=("Segoe UI", 10),
        rowheight=28
    )

    style.configure("Treeview.Heading",
        font=("Segoe UI", 10, "bold")
    )

# Fondo general

    style.map("Treeview",
        background=[("selected", "#347083")]
    )
    style.configure(
        "Treeview",
        rowheight=25
    )

    style.map(
        "Treeview",
        background=[("selected", "#347083")]
    )
    style.configure("Verde.TLabelframe", background="#d4edda", foreground="#155724")
    style.configure("Amarillo.TLabelframe", background="#fff3cd", foreground="#856404")
    style.configure("Rojo.TLabelframe", background="#f8d7da", foreground="#721c24")
    style.configure("TLabelframe.Label", font=("Segoe UI", 11, "bold"))

    frame = ttk.Frame(root, padding=15)
    frame.pack(fill="both", expand=True)

# Entrada HWID
    ttk.Label(
        frame,
        text="BUSCAR HWID O SERIAL",
        font=("Segoe UI", 9, "bold"),
        anchor="center"
    ).pack(pady=(10,2))

    entry_buscar = ttk.Entry(frame, width=40, justify="center")
    entry_buscar.pack(pady=(0,10))

    entry_buscar.bind("<KeyRelease>", lambda e: buscar_en_historial())

    frame_filtros = ttk.Frame(frame)
    frame_filtros.pack(fill="x", pady=5)

    def crear_boton_filtro(parent, texto, color, comando):
        frame_btn = ttk.Frame(parent)
        frame_btn.pack(side="left", padx=5)

    # Barra de color
        barra = tk.Label(frame_btn, width=2, background=color)
        barra.pack(side="left", fill="y")

    # Botón
        btn = ttk.Button(frame_btn, text=texto, command=comando)
        btn.pack(side="left")

# Crear botones
    crear_boton_filtro(frame_filtros, "Todos", "#007bff", lambda: actualizar_historial())
    crear_boton_filtro(frame_filtros, "Activos", "#28a745", lambda: filtrar_estado("activo"))
    crear_boton_filtro(frame_filtros, "Por vencer", "#ffc107", lambda: filtrar_estado("por_vencer"))
    crear_boton_filtro(frame_filtros, "Vencidas", "#dc3545", lambda: filtrar_estado("vencida"))
    crear_boton_filtro(frame_filtros, "Bloqueadas", "#6c757d", lambda: filtrar_estado("bloqueada"))

    ttk.Label(
        frame,
        text="HWID DEL CLIENTE",
        font=("Segoe UI", 9, "bold"),
        anchor="center"
    ).pack(pady=(10,2))

    entry_hwid = ttk.Entry(frame, width=40, justify="center")
    entry_hwid.pack(pady=(0,10))
    entry_hwid.bind("<KeyRelease>", hwid_key_release)

# Entrada días
    ttk.Label(
        frame,
        text="DÍAS DE LICENCIA",
        font=("Segoe UI", 9, "bold"),
        anchor="center"
    ).pack(pady=(10,2))

    entry_dias = ttk.Entry(frame, width=15, justify="center")
    entry_dias.insert(0, "30")
    entry_dias.pack(pady=(0,10))

# Botón generar / renovar
    btn_generar = ttk.Button(
        frame,
        text=" Generar Licencia",
        image=icon_generar,
        compound="left",
        command=generar_serial
    )   
    btn_generar.pack(pady=(0,10))

# Serial generado
    frame_serial = ttk.Labelframe(frame, text="Serial generado", padding=10, style="Verde.TLabelframe")
    frame_serial.pack(fill="x", pady=(0,10))
    entry_serial = ttk.Entry(frame_serial, width=50, state="readonly", font=("Consolas", 12))
    entry_serial.pack(pady=(5,0))
    label_fecha = ttk.Label(frame_serial, text="Expira el: --/--/----", font=("Segoe UI", 9))
    label_fecha.pack(pady=(5,0))

    ttk.Button(
        frame,
        text=" Copiar",
        image=icon_copiar,
        compound="left",
        command=lambda: copiar_serial(root)
    ).pack(pady=(5,10))

# Historial
# Historial
    label_stats = ttk.Label(
        frame,
        text="Activas: 0 | Vencidas: 0 | Bloqueadas: 0",
        font=("Segoe UI", 10, "bold")
    )
    label_stats.pack(anchor="w", pady=(10,5))   
    ttk.Label(frame, text="Historial de seriales generados:", font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(10,3))

    frame_historial = ttk.Frame(frame)
    frame_historial.pack(fill="both", expand=True, pady=(0,10))

# Frame lista
    frame_lista = ttk.Frame(frame_historial)
    frame_lista.pack(fill="both", expand=True)

    scroll_y = ttk.Scrollbar(frame_lista, orient="vertical")
    scroll_x = ttk.Scrollbar(frame_lista, orient="horizontal")

    tree_historial = ttk.Treeview(
        frame_lista,
        columns=("HWID","SERIAL","EXPIRA","DIAS","ESTADO"),
        show="headings",
        yscrollcommand=scroll_y.set,
        xscrollcommand=scroll_x.set
    )

    tree_historial.tag_configure("activo", background="#28a745", foreground="white")      # success
    tree_historial.tag_configure("por_vencer", background="#ffc107", foreground="black")  # warning
    tree_historial.tag_configure("vencida", background="#dc3545", foreground="white")     # danger
    tree_historial.tag_configure("bloqueada", background="#6c757d", foreground="white")   # gris

    tree_historial.heading("HWID", text="HWID")
    tree_historial.heading("SERIAL", text="Serial")
    tree_historial.heading("EXPIRA", text="Expira")
    tree_historial.heading("DIAS", text="Días")
    tree_historial.heading("ESTADO", text="Estado")

    tree_historial.column("HWID", width=180)
    tree_historial.column("SERIAL", width=260)
    tree_historial.column("EXPIRA", width=100)
    tree_historial.column("DIAS", width=60, anchor="center")
    tree_historial.column("ESTADO", width=100, anchor="center")


    scroll_y.config(command=tree_historial.yview)
    scroll_x.config(command=tree_historial.xview)

    scroll_y.pack(side="right", fill="y")
    scroll_x.pack(side="bottom", fill="x")
    tree_historial.pack(fill="both", expand=True)
    cargar_licencias_sheets()
    def seleccionar_hwid(event): 
        seleccionado = tree_historial.selection() 
        if seleccionado: 
            values = tree_historial.item(seleccionado[0], "values")
            hwid = values[0]
            entry_hwid.delete(0, tk.END)
            entry_hwid.insert(0, hwid)
            hwid_key_release()

    tree_historial.bind("<ButtonRelease-1>", seleccionar_hwid)

# Botón exportar (queda fijo abajo)
    frame_exportar = ttk.Frame(frame_historial)
    frame_exportar.pack(fill="x")

    frame_leyenda = ttk.Frame(frame_historial)
    frame_leyenda.pack(fill="x", pady=5)

    tk.Label(frame_leyenda, text="   ", background="#28a745").pack(side="left", padx=(5,2))
    tk.Label(frame_leyenda, text="Licencia activa").pack(side="left", padx=(0,10))

    tk.Label(frame_leyenda, text="   ", background="#ffc107").pack(side="left", padx=(5,2))
    tk.Label(frame_leyenda, text="Por vencer").pack(side="left", padx=(0,10))

    tk.Label(frame_leyenda, text="   ", background="#dc3545").pack(side="left", padx=(5,2))
    tk.Label(frame_leyenda, text="Vencida").pack(side="left", padx=(0,10))

    tk.Label(frame_leyenda, text="   ", background="#6c757d").pack(side="left", padx=(5,2))
    tk.Label(frame_leyenda, text="Bloqueada").pack(side="left", padx=(0,10))

    frame_botones_historial = ttk.Frame(frame_historial)
    frame_botones_historial.pack(fill="x", pady=5)


# Nuevo: Limpiar historial
    btn_limpiar = ttk.Button(frame_botones_historial, text=" Limpiar historial",
    image=icon_limpiar,
    compound="left", command=limpiar_historial)
    btn_limpiar.pack(side="left", padx=5, pady=5)

    btn_extender = ttk.Button(frame_botones_historial, text=" Extender",
    image=icon_extender,
    compound="left", command=extender_licencia)
    btn_extender.pack(side="left", padx=5, pady=5)

    btn_restar = ttk.Button(frame_botones_historial, text=" Reducir",
    image=icon_restar,
    compound="left", command=restar_dias_licencia)
    btn_restar.pack(side="left", padx=5, pady=5)

    btn_bloquear = ttk.Button(frame_botones_historial, text=" Bloquear",
    image=icon_bloquear,
    compound="left",command=bloquear_licencia)
    btn_bloquear.pack(side="left", padx=5, pady=5)

    btn_desbloquear = ttk.Button(frame_botones_historial, text=" Desbloquear",
    image=icon_desbloquear,
    compound="left", command=desbloquear_licencia)
    btn_desbloquear.pack(side="left", padx=5, pady=5)

    btn_eliminar = ttk.Button(
        frame_botones_historial,
        text=" Eliminar",
    image=icon_eliminar,
    compound="left",
        command=eliminar_licencia
    )
    btn_eliminar.pack(side="left", padx=5, pady=5)

# Agregar color gris para bloqueadas en el Treeview
    tree_historial.tag_configure("bloqueada", background="#6c757d", foreground="white")
# Nuevo: Renovar todos
    btn_renovar_todos = ttk.Button(
        frame_exportar,
        text=" Renovar Todos",
        image=icon_renovar,
        compound="left",
        command=renovar_todos_reiniciando
    )
    btn_renovar_todos.pack(side="left", padx=5, pady=5)

    btn_exportar = ttk.Button(
        frame_exportar,
        text=" Exportar",
    image=icon_exportar,
    compound="left",
        command=exportar_historial
    )

    btn_exportar.pack(side="right", padx=5, pady=5)

    

if __name__ == "__main__":
    print("Este archivo no se ejecuta directamente. Usa login.py")

36,351 chars · codepastes.com