File size: 3,760 Bytes
6a7fb3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""
Script de inicialização automática da base de dados
Executado automaticamente ao iniciar a aplicação no Hugging Face Spaces
"""

import sqlite3
import bcrypt
from pathlib import Path

def init_database():
    """Inicializa a base de dados se não existir"""
    
    BASE_DIR = Path(__file__).parent
    DB_PATH = BASE_DIR / "db" / "app.db"
    
    # Se a base de dados já existe, não fazer nada
    if DB_PATH.exists():
        print("✅ Base de dados já existe")
        return
    
    # Criar diretório
    DB_PATH.parent.mkdir(parents=True, exist_ok=True)
    
    print("=" * 60)
    print("Inicialização da Base de Dados")
    print("=" * 60)
    
    # Conectar à BD
    conn = sqlite3.connect(DB_PATH)
    conn.execute("PRAGMA foreign_keys = ON")
    cur = conn.cursor()
    
    # Criar tabela users
    print("\n[1/4] Criando tabela 'users'...")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT UNIQUE NOT NULL,
        password_hash TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
    """)
    print("✅ Tabela 'users' criada")
    
    # Criar tabela tasks
    print("\n[2/4] Criando tabela 'tasks'...")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS tasks (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        task_code TEXT UNIQUE NOT NULL,
        task_name TEXT NOT NULL,
        task_date DATE NOT NULL,
        start_time TIMESTAMP NOT NULL,
        end_time TIMESTAMP NOT NULL,
        planned_hours REAL NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (username) REFERENCES users(username) ON DELETE CASCADE
    )
    """)
    print("✅ Tabela 'tasks' criada")
    
    # Criar tabela subtasks
    print("\n[3/4] Criando tabela 'subtasks'...")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS subtasks (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        task_id INTEGER NOT NULL,
        subtask_code TEXT UNIQUE NOT NULL,
        subtask_name TEXT NOT NULL,
        start_time TIMESTAMP NOT NULL,
        end_time TIMESTAMP NOT NULL,
        planned_hours REAL NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
    )
    """)
    print("✅ Tabela 'subtasks' criada")
    
    # Criar tabela task_logs
    print("\n[4/4] Criando tabela 'task_logs'...")
    cur.execute("""
    CREATE TABLE IF NOT EXISTS task_logs (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT NOT NULL,
        task_id INTEGER,
        activity TEXT NOT NULL,
        event_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        FOREIGN KEY (username) REFERENCES users(username) ON DELETE CASCADE,
        FOREIGN KEY (task_id) REFERENCES tasks(id) ON DELETE CASCADE
    )
    """)
    print("✅ Tabela 'task_logs' criada")
    
    # Criar utilizador de teste
    print("\n[5/5] Criando utilizador de teste...")
    username = "admin"
    password = "admin123"
    pw_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt()).decode()
    
    try:
        cur.execute(
            "INSERT INTO users (username, password_hash) VALUES (?, ?)",
            (username, pw_hash)
        )
        print(f"✅ Utilizador de teste criado:")
        print(f"   Username: {username}")
        print(f"   Password: {password}")
    except sqlite3.IntegrityError:
        print(f"⚠️  Utilizador '{username}' já existe")
    
    # Commit e fechar
    conn.commit()
    conn.close()
    
    print("\n" + "=" * 60)
    print("✅ BASE DE DADOS INICIALIZADA COM SUCESSO!")
    print("=" * 60)

if __name__ == "__main__":
    init_database()