Greg Claude Sonnet 4.6 commited on
Commit
138c1eb
·
1 Parent(s): 71c3a32

feat(ta-01): admin attendance endpoints (sections, roster, swipe, batch-toggle)

Browse files
backend/app/api/v1/endpoints/admin_attendance.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, date as date_type, time, timezone
2
+ from typing import Optional, List
3
+
4
+ from fastapi import APIRouter, Depends, HTTPException, Query
5
+ from pydantic import BaseModel
6
+ from sqlalchemy.orm import Session
7
+
8
+ from app.core.database import get_db
9
+ from app.middleware.rbac import RBAC
10
+ from app.models.user import User
11
+ from app.models.section import Section
12
+ from app.services.attendance import record_attendance, list_section_roster
13
+
14
+ router = APIRouter(prefix="/admin", tags=["admin-attendance"])
15
+
16
+
17
+ @router.get("/sections")
18
+ def admin_list_sections(
19
+ current_user: User = Depends(RBAC(["admin"])),
20
+ db: Session = Depends(get_db),
21
+ ):
22
+ rows = (
23
+ db.query(Section)
24
+ .filter(Section.account_id == current_user.account_id)
25
+ .order_by(Section.name)
26
+ .all()
27
+ )
28
+ return [{"id": s.id, "name": s.name} for s in rows]
29
+
30
+
31
+ @router.get("/sections/{section_id}/roster")
32
+ def admin_section_roster(
33
+ section_id: int,
34
+ on_date: Optional[str] = Query(None, alias="date"),
35
+ current_user: User = Depends(RBAC(["admin"])),
36
+ db: Session = Depends(get_db),
37
+ ):
38
+ section = (
39
+ db.query(Section)
40
+ .filter(
41
+ Section.id == section_id,
42
+ Section.account_id == current_user.account_id,
43
+ )
44
+ .first()
45
+ )
46
+ if not section:
47
+ raise HTTPException(status_code=404, detail="section not found")
48
+
49
+ day = (
50
+ datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today()
51
+ )
52
+ items = list_section_roster(
53
+ db,
54
+ account_id=current_user.account_id,
55
+ section_id=section_id,
56
+ on_date=day,
57
+ )
58
+ return [it.__dict__ for it in items]
59
+
60
+
61
+ class AdminSwipeRecord(BaseModel):
62
+ student_id: int
63
+ present: bool
64
+
65
+
66
+ class AdminSwipeRequest(BaseModel):
67
+ section_id: int
68
+ subject_id: Optional[int] = None
69
+ records: List[AdminSwipeRecord]
70
+
71
+
72
+ def _ensure_admin_section(payload_section_id: int, account_id: int, db: Session) -> Section:
73
+ section = (
74
+ db.query(Section)
75
+ .filter(
76
+ Section.id == payload_section_id,
77
+ Section.account_id == account_id,
78
+ )
79
+ .first()
80
+ )
81
+ if not section:
82
+ raise HTTPException(status_code=404, detail="section not found")
83
+ return section
84
+
85
+
86
+ @router.post("/attendance/swipe", status_code=201)
87
+ def admin_attendance_swipe(
88
+ payload: AdminSwipeRequest,
89
+ current_user: User = Depends(RBAC(["admin"])),
90
+ db: Session = Depends(get_db),
91
+ ):
92
+ _ensure_admin_section(payload.section_id, current_user.account_id, db)
93
+ when = datetime.now(timezone.utc)
94
+ created = 0
95
+ for rec in payload.records:
96
+ if not rec.present:
97
+ continue
98
+ record_attendance(
99
+ db,
100
+ account_id=current_user.account_id,
101
+ user_id=rec.student_id,
102
+ section_id=payload.section_id,
103
+ subject_id=payload.subject_id,
104
+ action="in",
105
+ marked_by_role="admin",
106
+ marked_by_user_id=current_user.id,
107
+ when=when,
108
+ note="Admin: contingencia",
109
+ )
110
+ created += 1
111
+ return {"created": created, "total": len(payload.records), "skipped": []}
112
+
113
+
114
+ @router.post("/attendance/batch-toggle")
115
+ def admin_batch_toggle(
116
+ payload: AdminSwipeRequest,
117
+ on_date: Optional[str] = Query(None, alias="date"),
118
+ current_user: User = Depends(RBAC(["admin"])),
119
+ db: Session = Depends(get_db),
120
+ ):
121
+ _ensure_admin_section(payload.section_id, current_user.account_id, db)
122
+ day = (
123
+ datetime.strptime(on_date, "%Y-%m-%d").date() if on_date else date_type.today()
124
+ )
125
+ when = (
126
+ datetime.now(timezone.utc)
127
+ if day == date_type.today()
128
+ else datetime.combine(day, time(12, 0), tzinfo=timezone.utc)
129
+ )
130
+ created = 0
131
+ for rec in payload.records:
132
+ if not rec.present:
133
+ continue
134
+ record_attendance(
135
+ db,
136
+ account_id=current_user.account_id,
137
+ user_id=rec.student_id,
138
+ section_id=payload.section_id,
139
+ subject_id=payload.subject_id,
140
+ action="in",
141
+ marked_by_role="admin",
142
+ marked_by_user_id=current_user.id,
143
+ when=when,
144
+ note="Admin batch: contingencia",
145
+ )
146
+ created += 1
147
+ return {"created": created, "total": len(payload.records), "skipped": []}
backend/app/api/v1/router.py CHANGED
@@ -1,6 +1,6 @@
1
  from fastapi import APIRouter
2
 
3
- from app.api.v1.endpoints import auth, users, subjects, sections, teacher_sections, enrollments, attendances, dashboard, facial, settings, teacher, section_subjects, teacher_subjects, permissions, developer, card_templates, representative, audit_logs, reports, holidays, photos
4
 
5
  router = APIRouter(prefix="/api/v1")
6
  router.include_router(auth.router)
@@ -24,3 +24,4 @@ router.include_router(audit_logs.router)
24
  router.include_router(reports.router)
25
  router.include_router(holidays.router)
26
  router.include_router(photos.router)
 
 
1
  from fastapi import APIRouter
2
 
3
+ from app.api.v1.endpoints import auth, users, subjects, sections, teacher_sections, enrollments, attendances, dashboard, facial, settings, teacher, section_subjects, teacher_subjects, permissions, developer, card_templates, representative, audit_logs, reports, holidays, photos, admin_attendance
4
 
5
  router = APIRouter(prefix="/api/v1")
6
  router.include_router(auth.router)
 
24
  router.include_router(reports.router)
25
  router.include_router(holidays.router)
26
  router.include_router(photos.router)
27
+ router.include_router(admin_attendance.router)
backend/tests/test_admin_attendance.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import date
2
+ import pytest
3
+ from fastapi.testclient import TestClient
4
+
5
+ from app.main import app
6
+ from app.core.database import SessionLocal, Base, engine
7
+ from app.models.plan import Plan
8
+ from app.models.account import Account
9
+ from app.models.user import User
10
+ from app.models.section import Section
11
+ from app.models.subject import Subject
12
+ from app.models.enrollment import Enrollment
13
+ from app.models.attendance import Attendance
14
+ from app.models.entrance_log import EntranceLog
15
+ from app.core.security import hash_password
16
+
17
+
18
+ @pytest.fixture(scope="module")
19
+ def client():
20
+ Base.metadata.create_all(bind=engine)
21
+ yield TestClient(app)
22
+
23
+
24
+ def _cleanup(db, org_name):
25
+ accs = db.query(Account).filter(Account.organization_name == org_name).all()
26
+ for acc in accs:
27
+ try:
28
+ from app.models.audit_log import AuditLog
29
+ db.query(AuditLog).filter(AuditLog.account_id == acc.id).delete()
30
+ except Exception:
31
+ pass
32
+ db.query(EntranceLog).filter(EntranceLog.account_id == acc.id).delete()
33
+ db.query(Attendance).filter(Attendance.account_id == acc.id).delete()
34
+ db.query(Enrollment).filter(Enrollment.account_id == acc.id).delete()
35
+ db.query(Section).filter(Section.account_id == acc.id).delete()
36
+ db.query(Subject).filter(Subject.account_id == acc.id).delete()
37
+ db.query(User).filter(User.account_id == acc.id).update({"parent_id": None})
38
+ db.query(User).filter(User.account_id == acc.id).delete()
39
+ db.query(Account).filter(Account.id == acc.id).delete()
40
+ db.commit()
41
+
42
+
43
+ def _seed(db, org_name, admin_email, student_email, teacher_email=None):
44
+ plan = db.query(Plan).first()
45
+ if not plan:
46
+ plan = Plan(name="basic", features=[], price=0)
47
+ db.add(plan); db.commit(); db.refresh(plan)
48
+ acc = Account(organization_name=org_name, plan_id=plan.id, category="school")
49
+ db.add(acc); db.commit(); db.refresh(acc)
50
+ admin = User(account_id=acc.id, name="A", lastname="A",
51
+ email=admin_email, password_hash=hash_password("x"),
52
+ role="admin", is_active="1")
53
+ student = User(account_id=acc.id, name="S", lastname="S",
54
+ email=student_email, password_hash=hash_password("x"),
55
+ role="student", is_active="1", sex="M")
56
+ users = [admin, student]
57
+ teacher = None
58
+ if teacher_email:
59
+ teacher = User(account_id=acc.id, name="T", lastname="T",
60
+ email=teacher_email, password_hash=hash_password("x"),
61
+ role="teacher", is_active="1")
62
+ users.append(teacher)
63
+ db.add_all(users); db.commit()
64
+ for u in users: db.refresh(u)
65
+ sec = Section(account_id=acc.id, name="S1", academic_period="2025-2026", max_students=40)
66
+ subj = Subject(account_id=acc.id, name="Mate")
67
+ db.add_all([sec, subj]); db.commit(); db.refresh(sec); db.refresh(subj)
68
+ db.add(Enrollment(account_id=acc.id, section_id=sec.id, student_id=student.id))
69
+ db.commit()
70
+ return acc, admin, student, sec, subj, teacher
71
+
72
+
73
+ def _login(client, email):
74
+ r = client.post("/api/v1/auth/login", json={"email": email, "password": "x"})
75
+ return r.json()["access_token"]
76
+
77
+
78
+ # Task 20: GET /admin/sections
79
+
80
+ def test_admin_lists_all_sections_of_their_account(client):
81
+ org = "AdminAtt_ListSections"
82
+ db = SessionLocal()
83
+ try:
84
+ _cleanup(db, org)
85
+ acc, admin, _, sec, _, _ = _seed(db, org, "ad_ls_admin@talos.com", "ad_ls_s@talos.com")
86
+ section_id = sec.id
87
+ finally:
88
+ db.close()
89
+
90
+ token = _login(client, "ad_ls_admin@talos.com")
91
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
92
+ assert r.status_code == 200, r.text
93
+ ids = [s["id"] for s in r.json()]
94
+ assert section_id in ids
95
+
96
+ db = SessionLocal()
97
+ try:
98
+ _cleanup(db, org)
99
+ finally:
100
+ db.close()
101
+
102
+
103
+ def test_admin_cannot_see_sections_of_other_account(client):
104
+ org_a = "AdminAtt_CrossA"; org_b = "AdminAtt_CrossB"
105
+ db = SessionLocal()
106
+ try:
107
+ _cleanup(db, org_a); _cleanup(db, org_b)
108
+ _, admin_a, _, _, _, _ = _seed(db, org_a, "ad_xa_admin@talos.com", "ad_xa_s@talos.com")
109
+ _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_xb_admin@talos.com", "ad_xb_s@talos.com")
110
+ sec_b_id = sec_b.id
111
+ finally:
112
+ db.close()
113
+
114
+ token = _login(client, "ad_xa_admin@talos.com")
115
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
116
+ assert r.status_code == 200
117
+ ids = [s["id"] for s in r.json()]
118
+ assert sec_b_id not in ids
119
+
120
+ db = SessionLocal()
121
+ try:
122
+ _cleanup(db, org_a); _cleanup(db, org_b)
123
+ finally:
124
+ db.close()
125
+
126
+
127
+ def test_teacher_role_is_forbidden_on_admin_sections(client):
128
+ org = "AdminAtt_TeacherForbid"
129
+ db = SessionLocal()
130
+ try:
131
+ _cleanup(db, org)
132
+ _seed(db, org, "ad_tf_admin@talos.com", "ad_tf_s@talos.com", "ad_tf_teacher@talos.com")
133
+ finally:
134
+ db.close()
135
+
136
+ token = _login(client, "ad_tf_teacher@talos.com")
137
+ r = client.get("/api/v1/admin/sections", headers={"Authorization": f"Bearer {token}"})
138
+ assert r.status_code in (401, 403)
139
+
140
+ db = SessionLocal()
141
+ try:
142
+ _cleanup(db, org)
143
+ finally:
144
+ db.close()
145
+
146
+
147
+ # Task 21: GET /admin/sections/{id}/roster
148
+
149
+ def test_admin_roster_returns_enrolled_students(client):
150
+ org = "AdminAtt_Roster"
151
+ db = SessionLocal()
152
+ try:
153
+ _cleanup(db, org)
154
+ acc, admin, student, sec, _, _ = _seed(db, org, "ad_r_admin@talos.com", "ad_r_s@talos.com")
155
+ sec_id, student_id = sec.id, student.id
156
+ finally:
157
+ db.close()
158
+
159
+ token = _login(client, "ad_r_admin@talos.com")
160
+ r = client.get(
161
+ f"/api/v1/admin/sections/{sec_id}/roster",
162
+ headers={"Authorization": f"Bearer {token}"},
163
+ )
164
+ assert r.status_code == 200, r.text
165
+ items = r.json()
166
+ assert any(it["id"] == student_id for it in items)
167
+ item = next(it for it in items if it["id"] == student_id)
168
+ assert "already_checked_in" in item
169
+ assert "entrance_logged" in item
170
+
171
+ db = SessionLocal()
172
+ try:
173
+ _cleanup(db, org)
174
+ finally:
175
+ db.close()
176
+
177
+
178
+ def test_admin_roster_404_for_foreign_section(client):
179
+ org_a = "AdminAtt_RostA"; org_b = "AdminAtt_RostB"
180
+ db = SessionLocal()
181
+ try:
182
+ _cleanup(db, org_a); _cleanup(db, org_b)
183
+ _, _, _, _, _, _ = _seed(db, org_a, "ad_rxa_admin@talos.com", "ad_rxa_s@talos.com")
184
+ _, _, _, sec_b, _, _ = _seed(db, org_b, "ad_rxb_admin@talos.com", "ad_rxb_s@talos.com")
185
+ sec_b_id = sec_b.id
186
+ finally:
187
+ db.close()
188
+
189
+ token = _login(client, "ad_rxa_admin@talos.com")
190
+ r = client.get(
191
+ f"/api/v1/admin/sections/{sec_b_id}/roster",
192
+ headers={"Authorization": f"Bearer {token}"},
193
+ )
194
+ assert r.status_code == 404
195
+
196
+ db = SessionLocal()
197
+ try:
198
+ _cleanup(db, org_a); _cleanup(db, org_b)
199
+ finally:
200
+ db.close()
201
+
202
+
203
+ # Task 22: POST /admin/attendance/swipe
204
+
205
+ def test_admin_swipe_marks_with_admin_attribution(client):
206
+ org = "AdminAtt_SwipeAttrib"
207
+ db = SessionLocal()
208
+ try:
209
+ _cleanup(db, org)
210
+ _, admin, student, sec, subj, _ = _seed(
211
+ db, org, "ad_sw_admin@talos.com", "ad_sw_s@talos.com"
212
+ )
213
+ admin_id, sec_id, subj_id, student_id = admin.id, sec.id, subj.id, student.id
214
+ finally:
215
+ db.close()
216
+
217
+ token = _login(client, "ad_sw_admin@talos.com")
218
+ r = client.post(
219
+ "/api/v1/admin/attendance/swipe",
220
+ headers={"Authorization": f"Bearer {token}"},
221
+ json={
222
+ "section_id": sec_id,
223
+ "subject_id": subj_id,
224
+ "records": [{"student_id": student_id, "present": True}],
225
+ },
226
+ )
227
+ assert r.status_code == 201, r.text
228
+ assert r.json()["created"] == 1
229
+
230
+ db = SessionLocal()
231
+ try:
232
+ row = (
233
+ db.query(Attendance)
234
+ .filter(
235
+ Attendance.user_id == student_id,
236
+ Attendance.section_id == sec_id,
237
+ )
238
+ .order_by(Attendance.id.desc())
239
+ .first()
240
+ )
241
+ assert row is not None
242
+ assert row.marked_by_role == "admin"
243
+ assert row.marked_by_user_id == admin_id
244
+ finally:
245
+ _cleanup(db, org)
246
+ db.close()
247
+
248
+
249
+ def test_admin_swipe_works_without_entrance_log(client):
250
+ """Admin marks should never block on gate, ever."""
251
+ org = "AdminAtt_SwipeNoGate"
252
+ db = SessionLocal()
253
+ try:
254
+ _cleanup(db, org)
255
+ _, _, student, sec, subj, _ = _seed(db, org, "ad_swng_admin@talos.com", "ad_swng_s@talos.com")
256
+ sec_id, subj_id, student_id = sec.id, subj.id, student.id
257
+ finally:
258
+ db.close()
259
+
260
+ token = _login(client, "ad_swng_admin@talos.com")
261
+ r = client.post(
262
+ "/api/v1/admin/attendance/swipe",
263
+ headers={"Authorization": f"Bearer {token}"},
264
+ json={
265
+ "section_id": sec_id,
266
+ "subject_id": subj_id,
267
+ "records": [{"student_id": student_id, "present": True}],
268
+ },
269
+ )
270
+ assert r.status_code == 201
271
+ assert r.json()["created"] == 1
272
+
273
+ db = SessionLocal()
274
+ try:
275
+ _cleanup(db, org)
276
+ finally:
277
+ db.close()
278
+
279
+
280
+ def test_admin_swipe_404_for_foreign_section(client):
281
+ org_a = "AdminAtt_SwipeXA"; org_b = "AdminAtt_SwipeXB"
282
+ db = SessionLocal()
283
+ try:
284
+ _cleanup(db, org_a); _cleanup(db, org_b)
285
+ _, _, _, _, _, _ = _seed(db, org_a, "ad_sxa_admin@talos.com", "ad_sxa_s@talos.com")
286
+ _, _, student_b, sec_b, subj_b, _ = _seed(
287
+ db, org_b, "ad_sxb_admin@talos.com", "ad_sxb_s@talos.com"
288
+ )
289
+ sec_b_id, subj_b_id, student_b_id = sec_b.id, subj_b.id, student_b.id
290
+ finally:
291
+ db.close()
292
+
293
+ token = _login(client, "ad_sxa_admin@talos.com")
294
+ r = client.post(
295
+ "/api/v1/admin/attendance/swipe",
296
+ headers={"Authorization": f"Bearer {token}"},
297
+ json={
298
+ "section_id": sec_b_id,
299
+ "subject_id": subj_b_id,
300
+ "records": [{"student_id": student_b_id, "present": True}],
301
+ },
302
+ )
303
+ assert r.status_code == 404
304
+
305
+ db = SessionLocal()
306
+ try:
307
+ _cleanup(db, org_a); _cleanup(db, org_b)
308
+ finally:
309
+ db.close()
310
+
311
+
312
+ # Task 23: POST /admin/attendance/batch-toggle
313
+
314
+ def test_admin_batch_toggle_for_past_date(client):
315
+ org = "AdminAtt_BatchPastDate"
316
+ db = SessionLocal()
317
+ try:
318
+ _cleanup(db, org)
319
+ _, admin, student, sec, subj, _ = _seed(db, org, "ad_b_admin@talos.com", "ad_b_s@talos.com")
320
+ sec_id, subj_id, student_id, admin_id = sec.id, subj.id, student.id, admin.id
321
+ finally:
322
+ db.close()
323
+
324
+ token = _login(client, "ad_b_admin@talos.com")
325
+ r = client.post(
326
+ "/api/v1/admin/attendance/batch-toggle?date=2026-06-01",
327
+ headers={"Authorization": f"Bearer {token}"},
328
+ json={
329
+ "section_id": sec_id,
330
+ "subject_id": subj_id,
331
+ "records": [{"student_id": student_id, "present": True}],
332
+ },
333
+ )
334
+ assert r.status_code == 200, r.text
335
+
336
+ db = SessionLocal()
337
+ try:
338
+ row = (
339
+ db.query(Attendance)
340
+ .filter(
341
+ Attendance.user_id == student_id,
342
+ Attendance.section_id == sec_id,
343
+ )
344
+ .order_by(Attendance.id.desc())
345
+ .first()
346
+ )
347
+ assert row is not None
348
+ assert row.marked_by_role == "admin"
349
+ assert row.marked_by_user_id == admin_id
350
+ assert row.time_log.date().isoformat() == "2026-06-01"
351
+ finally:
352
+ _cleanup(db, org)
353
+ db.close()