File size: 10,076 Bytes
6aa6081
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Seed script: clears all data except admin user, then creates test data."""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app.core.database import SessionLocal, engine
from app.models import *
from sqlalchemy import text

def seed():
    db = SessionLocal()
    try:
        admin = db.query(User).filter(User.role == "admin").first()
        if not admin:
            print("No admin user found. Aborting.")
            return
        account_id = admin.account_id
        admin_id = admin.id
        admin_password_hash = admin.password_hash
        print(f"Admin: {admin.name} {admin.lastname} (account_id={account_id})")

        # Disable FK checks for truncation
        db.execute(text("SET FOREIGN_KEY_CHECKS = 0"))

        # Delete in dependency order, preserving admin
        for tbl in [AuditLog, FaceEncoding, Attendance, SectionSchedule, Enrollment,
                    TeacherSubject, TeacherSection, SectionSubject, Section, Subject,
                    UserPermission, User]:
            if tbl == User:
                db.query(User).filter(User.account_id == account_id, User.id != admin_id).delete(synchronize_session=False)
            else:
                db.query(tbl).filter(tbl.account_id == account_id).delete(synchronize_session=False)
        # Also delete users with different account_id (e.g. any orphans)
        db.query(User).filter(User.id != admin_id).delete(synchronize_session=False)

        db.execute(text("SET FOREIGN_KEY_CHECKS = 1"))
        db.commit()
        print("Cleared: all non-admin data.")

        # --- Create Subjects ---
        subject_data = [
            ("Matemáticas", "MAT-01"),
            ("Lenguaje", "LEN-01"),
            ("Ciencias", "CIE-01"),
            ("Historia", "HIS-01"),
            ("Inglés", "ING-01"),
        ]
        subjects = []
        for name, code in subject_data:
            sub = Subject(account_id=account_id, name=name, code=code)
            db.add(sub)
            db.flush()
            subjects.append(sub)
        print(f"Created {len(subjects)} subjects.")

        # --- Create Sections ---
        section_names = [
            "1er Grado A", "2do Grado A", "3er Grado A",
            "4to Grado A", "5to Grado A",
        ]
        sections = []
        for i, name in enumerate(section_names):
            sec = Section(
                account_id=account_id,
                subject_id=subjects[i].id,
                name=name,
                academic_period="2025-2026",
                max_students=40,
            )
            db.add(sec)
            db.flush()
            # Link all subjects to this section
            for sub in subjects:
                db.add(SectionSubject(account_id=account_id, section_id=sec.id, subject_id=sub.id))
            sections.append(sec)
        print(f"Created {len(sections)} sections with subject links.")

        # --- Create Teachers ---
        teacher_data = [
            ("María", "González", "V-10000001", "maria.gonzalez@test.com", "1234567890"),
            ("José", "Martínez", "V-10000002", "jose.martinez@test.com", "1234567891"),
            ("Ana", "Rodríguez", "V-10000003", "ana.rodriguez@test.com", "1234567892"),
        ]
        teachers = []
        for name, lastname, card_id, email, phone in teacher_data:
            t = User(
                account_id=account_id, name=name, lastname=lastname,
                card_id=card_id, email=email, phone_number=phone,
                role="teacher", is_active="1",
                password_hash=admin_password_hash,  # same hash so password works
            )
            db.add(t)
            db.flush()
            # Assign all subjects to teacher
            for sub in subjects:
                db.add(TeacherSubject(account_id=account_id, teacher_id=t.id, subject_id=sub.id))
            teachers.append(t)
        print(f"Created {len(teachers)} teachers with subject assignments.")

        # --- Create Administrativos ---
        admin_staff_data = [
            ("Rosa", "Mendoza", "V-40000001", "rosa.mendoza@test.com", "1234567920"),
            ("Luis", "Torres", "V-40000002", "luis.torres@test.com", "1234567921"),
        ]
        admin_staff = []
        for name, lastname, card_id, email, phone in admin_staff_data:
            a = User(
                account_id=account_id, name=name, lastname=lastname,
                card_id=card_id, email=email, phone_number=phone,
                role="administrativo", is_active="1",
                password_hash=admin_password_hash,
            )
            db.add(a)
            db.flush()
            admin_staff.append(a)
        print(f"Created {len(admin_staff)} administrativos.")

        # --- Create Obreros ---
        obrero_data = [
            ("Pedro", "García", "V-50000001", "pedro.garcia@test.com", "1234567922"),
            ("Manuel", "Rivas", "V-50000002", "manuel.rivas@test.com", "1234567923"),
            ("José", "Silva", "V-50000003", "jose.silva@test.com", "1234567924"),
        ]
        obreros = []
        for name, lastname, card_id, email, phone in obrero_data:
            o = User(
                account_id=account_id, name=name, lastname=lastname,
                card_id=card_id, email=email, phone_number=phone,
                role="obrero", is_active="1",
                password_hash=admin_password_hash,
            )
            db.add(o)
            db.flush()
            obreros.append(o)
        print(f"Created {len(obreros)} obreros.")

        # --- Create Representatives ---
        rep_data = [
            ("Pedro", "Pérez", "V-20000001", "pedro.perez@test.com", "1234567893"),
            ("Luisa", "Fernández", "V-20000002", "luisa.fernandez@test.com", "1234567894"),
            ("Carlos", "López", "V-20000003", "carlos.lopez@test.com", "1234567895"),
            ("Marta", "Díaz", "V-20000004", "marta.diaz@test.com", "1234567896"),
            ("Jorge", "Ramírez", "V-20000005", "jorge.ramirez@test.com", "1234567897"),
        ]
        representatives = []
        for name, lastname, card_id, email, phone in rep_data:
            r = User(
                account_id=account_id, name=name, lastname=lastname,
                card_id=card_id, email=email, phone_number=phone,
                role="representative", is_active="1",
                password_hash=admin_password_hash,
            )
            db.add(r)
            db.flush()
            representatives.append(r)
        print(f"Created {len(representatives)} representatives.")

        # --- Create Students (3 per section, 15 total) ---
        student_data = [
            ("Sofía", "Pérez", "V-30000001", "sofia.perez@test.com", "1234567898", 0),
            ("Mateo", "Pérez", "V-30000002", "mateo.perez@test.com", "1234567899", 0),
            ("Valentina", "Pérez", "V-30000003", "valentina.perez@test.com", "1234567900", 0),
            ("Santiago", "Fernández", "V-30000004", "santiago.fernandez@test.com", "1234567901", 1),
            ("Isabella", "Fernández", "V-30000005", "isabella.fernandez@test.com", "1234567902", 1),
            ("Nicolás", "Fernández", "V-30000006", "nicolas.fernandez@test.com", "1234567903", 1),
            ("Camila", "López", "V-30000007", "camila.lopez@test.com", "1234567904", 2),
            ("Sebastián", "López", "V-30000008", "sebastian.lopez@test.com", "1234567905", 2),
            ("Gabriela", "López", "V-30000009", "gabriela.lopez@test.com", "1234567906", 2),
            ("Daniel", "Díaz", "V-30000010", "daniel.diaz@test.com", "1234567907", 3),
            ("Emily", "Díaz", "V-30000011", "emily.diaz@test.com", "1234567908", 3),
            ("Samuel", "Díaz", "V-30000012", "samuel.diaz@test.com", "1234567909", 3),
            ("Victoria", "Ramírez", "V-30000013", "victoria.ramirez@test.com", "1234567910", 4),
            ("Benjamín", "Ramírez", "V-30000014", "benjamin.ramirez@test.com", "1234567911", 4),
            ("Luciana", "Ramírez", "V-30000015", "luciana.ramirez@test.com", "1234567912", 4),
        ]
        students = []
        for name, lastname, card_id, email, phone, rep_idx in student_data:
            s = User(
                account_id=account_id,
                name=name, lastname=lastname,
                card_id=card_id, email=email, phone_number=phone,
                role="student", is_active="1",
                parent_id=representatives[rep_idx].id,
                password_hash=admin_password_hash,
            )
            db.add(s)
            db.flush()
            students.append(s)

        # Enroll students: first 3 in section 0, next 3 in section 1, etc.
        for i, student in enumerate(students):
            sec_idx = i // 3
            db.add(Enrollment(
                account_id=account_id,
                section_id=sections[sec_idx].id,
                student_id=student.id,
            ))
        print(f"Created {len(students)} students with enrollments.")

        # --- Link teachers to sections (2 teachers per section, rotating) ---
        for i, sec in enumerate(sections):
            t1 = teachers[i % len(teachers)]
            t2 = teachers[(i + 1) % len(teachers)]
            db.add(TeacherSection(account_id=account_id, section_id=sec.id, teacher_id=t1.id))
            db.add(TeacherSection(account_id=account_id, section_id=sec.id, teacher_id=t2.id))
        print("Linked teachers to sections.")

        db.commit()
        print("\nSeed complete! Created:")
        print(f"  - {len(subjects)} subjects")
        print(f"  - {len(sections)} sections")
        print(f"  - {len(teachers)} teachers")
        print(f"  - {len(admin_staff)} administrativos")
        print(f"  - {len(obreros)} obreros")
        print(f"  - {len(representatives)} representatives")
        print(f"  - {len(students)} students")
        print(f"  - All users share admin's password hash")

    except Exception as e:
        db.rollback()
        print(f"Error: {e}")
        raise
    finally:
        db.close()

if __name__ == "__main__":
    seed()