github-actions[bot] commited on
Commit
bf8d35c
·
1 Parent(s): cfdd165

deploy: backend from db77c72

Browse files
main.py CHANGED
@@ -4433,6 +4433,14 @@ def _normalize_class_records(
4433
 
4434
  lrn_value = str(student.get("lrn", "")).strip()
4435
  email_value = str(student.get("email", "")).strip().lower()
 
 
 
 
 
 
 
 
4436
  if not lrn_value and not email_value:
4437
  rejected_rows.append(
4438
  {
@@ -5378,6 +5386,7 @@ class StudentAccountProvisionCommitRequest(BaseModel):
5378
  defaultPassword: Optional[str] = None
5379
  forcePasswordChange: bool = True
5380
  createAuthUsers: bool = True
 
5381
 
5382
 
5383
  class AdminCreateUserRequest(BaseModel):
@@ -6000,6 +6009,7 @@ async def preview_student_account_import(
6000
 
6001
  firestore_client = firebase_firestore.client() if (_firebase_ready and firebase_firestore) else None
6002
  for row in parsed_rows:
 
6003
  first_name = str(row.get("firstName") or "").strip()
6004
  last_name = str(row.get("lastName") or "").strip()
6005
  middle_name = str(row.get("middleName") or "").strip()
@@ -6011,15 +6021,17 @@ async def preview_student_account_import(
6011
 
6012
  issues: List[str] = []
6013
  if not first_name:
6014
- issues.append("Missing firstName")
6015
  if not last_name:
6016
- issues.append("Missing lastName")
6017
  if not student_id:
6018
- issues.append("Missing studentId/lrn")
 
 
6019
  if not grade:
6020
- issues.append("Missing grade")
6021
  if not section:
6022
- issues.append("Missing section")
6023
 
6024
  resolved_row_section_id, _, resolved_grade, resolved_section = _resolve_import_class_context(
6025
  class_section_id=None,
@@ -6033,6 +6045,10 @@ async def preview_student_account_import(
6033
  duplicate_in_file = False
6034
  duplicate_in_firestore = False
6035
  duplicate_in_auth = False
 
 
 
 
6036
 
6037
  student_id_key = student_id.lower()
6038
  email_key = generated_email.lower()
@@ -6055,6 +6071,18 @@ async def preview_student_account_import(
6055
  firestore_client.collection("users").where("lrn", "==", student_id).limit(1).stream()
6056
  )
6057
  duplicate_in_firestore = duplicate_in_firestore or len(existing_by_lrn) > 0
 
 
 
 
 
 
 
 
 
 
 
 
6058
  if generated_email:
6059
  existing_by_email = list(
6060
  firestore_client.collection("users").where("email", "==", generated_email).limit(1).stream()
@@ -6072,18 +6100,32 @@ async def preview_student_account_import(
6072
  warnings.append(f"Auth duplicate check warning for {generated_email}: {auth_err}")
6073
 
6074
  if duplicate_in_firestore:
6075
- issues.append("Duplicate with existing Firestore profile")
 
 
 
 
 
 
6076
  if duplicate_in_auth:
6077
- issues.append("Duplicate with existing Auth account")
6078
 
6079
  status = "valid"
6080
- if issues:
 
 
 
 
 
 
 
 
6081
  status = "invalid"
6082
- if duplicate_in_file or duplicate_in_firestore or duplicate_in_auth:
6083
  status = "duplicate"
6084
 
6085
  preview_row = {
6086
- "rowNumber": int(row.get("rowNumber") or 0),
6087
  "studentId": student_id,
6088
  "firstName": first_name,
6089
  "lastName": last_name,
@@ -6093,6 +6135,10 @@ async def preview_student_account_import(
6093
  "grade": resolved_grade,
6094
  "section": resolved_section,
6095
  "classSectionId": resolved_row_section_id,
 
 
 
 
6096
  "status": status,
6097
  "issues": issues,
6098
  "duplicateInFile": duplicate_in_file,
@@ -6164,7 +6210,10 @@ async def commit_student_account_import(
6164
 
6165
  client = firebase_firestore.client()
6166
  preview_rows = cast(List[Dict[str, Any]], preview.get("rows") or [])
6167
- candidate_rows = [row for row in preview_rows if str(row.get("status") or "") == "valid"]
 
 
 
6168
 
6169
  result_rows: List[Dict[str, Any]] = []
6170
  warnings: List[str] = []
@@ -6200,6 +6249,206 @@ async def commit_student_account_import(
6200
  )
6201
  continue
6202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6203
  existing_profile_doc = None
6204
  existing_uid: Optional[str] = None
6205
  try:
@@ -6216,6 +6465,32 @@ async def commit_student_account_import(
6216
  except Exception as duplicate_err:
6217
  warnings.append(f"Duplicate re-check warning for row {row_number}: {duplicate_err}")
6218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6219
  auth_uid: Optional[str] = None
6220
  temporary_password: Optional[str] = None
6221
  auth_existing = False
@@ -7891,6 +8166,17 @@ If a column doesn't match any field, skip it. Respond ONLY with a JSON object ma
7891
  file_students = normalized_result["rows"]
7892
  file_row_warnings = normalized_result["rowWarnings"]
7893
  file_rejected_rows = normalized_result.get("rejectedRows") or []
 
 
 
 
 
 
 
 
 
 
 
7894
  file_unknown_columns = normalized_result["unknownColumns"]
7895
  file_interpreted_rows = int(normalized_result.get("interpretedRows") or len(file_students))
7896
  file_rejected_rows_count = int(normalized_result.get("rejectedRowsCount") or len(file_rejected_rows))
 
4433
 
4434
  lrn_value = str(student.get("lrn", "")).strip()
4435
  email_value = str(student.get("email", "")).strip().lower()
4436
+ if lrn_value and not re.fullmatch(r"\d{12}", lrn_value):
4437
+ rejected_rows.append(
4438
+ {
4439
+ "row": int(idx) + 2,
4440
+ "reason": f"Row {int(idx) + 2}: LRN must contain exactly 12 digits.",
4441
+ }
4442
+ )
4443
+ continue
4444
  if not lrn_value and not email_value:
4445
  rejected_rows.append(
4446
  {
 
5386
  defaultPassword: Optional[str] = None
5387
  forcePasswordChange: bool = True
5388
  createAuthUsers: bool = True
5389
+ confirmSectionMoves: bool = False
5390
 
5391
 
5392
  class AdminCreateUserRequest(BaseModel):
 
6009
 
6010
  firestore_client = firebase_firestore.client() if (_firebase_ready and firebase_firestore) else None
6011
  for row in parsed_rows:
6012
+ row_number = int(row.get("rowNumber") or 0)
6013
  first_name = str(row.get("firstName") or "").strip()
6014
  last_name = str(row.get("lastName") or "").strip()
6015
  middle_name = str(row.get("middleName") or "").strip()
 
6021
 
6022
  issues: List[str] = []
6023
  if not first_name:
6024
+ issues.append(f"Row {row_number}: Missing firstName")
6025
  if not last_name:
6026
+ issues.append(f"Row {row_number}: Missing lastName")
6027
  if not student_id:
6028
+ issues.append(f"Row {row_number}: Missing studentId/lrn")
6029
+ elif not re.fullmatch(r"\d{12}", student_id):
6030
+ issues.append(f"Row {row_number}: LRN must contain exactly 12 digits")
6031
  if not grade:
6032
+ issues.append(f"Row {row_number}: Missing grade")
6033
  if not section:
6034
+ issues.append(f"Row {row_number}: Missing section")
6035
 
6036
  resolved_row_section_id, _, resolved_grade, resolved_section = _resolve_import_class_context(
6037
  class_section_id=None,
 
6045
  duplicate_in_file = False
6046
  duplicate_in_firestore = False
6047
  duplicate_in_auth = False
6048
+ already_enrolled = False
6049
+ enrolled_section_id = ""
6050
+ roster_student_uid = ""
6051
+ existing_profile_uid = ""
6052
 
6053
  student_id_key = student_id.lower()
6054
  email_key = generated_email.lower()
 
6071
  firestore_client.collection("users").where("lrn", "==", student_id).limit(1).stream()
6072
  )
6073
  duplicate_in_firestore = duplicate_in_firestore or len(existing_by_lrn) > 0
6074
+ if existing_by_lrn:
6075
+ existing_profile_uid = str(existing_by_lrn[0].id)
6076
+ existing_roster_rows = list(
6077
+ firestore_client.collection("managedStudents").where("lrn", "==", student_id).limit(1).stream()
6078
+ )
6079
+ if existing_roster_rows:
6080
+ roster_student_uid = str(existing_roster_rows[0].id)
6081
+ roster_data = _snapshot_to_dict(existing_roster_rows[0])
6082
+ enrolled_section_id = str(roster_data.get("classSectionId") or roster_data.get("classroomId") or "").strip()
6083
+ already_enrolled = bool(enrolled_section_id)
6084
+ if already_enrolled:
6085
+ duplicate_in_firestore = True
6086
  if generated_email:
6087
  existing_by_email = list(
6088
  firestore_client.collection("users").where("email", "==", generated_email).limit(1).stream()
 
6100
  warnings.append(f"Auth duplicate check warning for {generated_email}: {auth_err}")
6101
 
6102
  if duplicate_in_firestore:
6103
+ if already_enrolled and enrolled_section_id.lower() != resolved_row_section_id.lower():
6104
+ issues.append(
6105
+ f"Row {row_number}: Cannot import; already enrolled in {enrolled_section_id}. "
6106
+ "A section move requires explicit confirmation."
6107
+ )
6108
+ else:
6109
+ issues.append(f"Row {row_number}: Duplicate with existing Firestore profile")
6110
  if duplicate_in_auth:
6111
+ issues.append(f"Row {row_number}: Duplicate with existing Auth account")
6112
 
6113
  status = "valid"
6114
+ if already_enrolled and enrolled_section_id.lower() != resolved_row_section_id.lower():
6115
+ has_required_fields = bool(first_name and last_name and grade and section and re.fullmatch(r"\d{12}", student_id))
6116
+ if not has_required_fields:
6117
+ status = "invalid"
6118
+ elif duplicate_in_file:
6119
+ status = "duplicate"
6120
+ else:
6121
+ status = "move_confirmation_required"
6122
+ elif issues:
6123
  status = "invalid"
6124
+ if status != "move_confirmation_required" and (duplicate_in_file or duplicate_in_firestore or duplicate_in_auth):
6125
  status = "duplicate"
6126
 
6127
  preview_row = {
6128
+ "rowNumber": row_number,
6129
  "studentId": student_id,
6130
  "firstName": first_name,
6131
  "lastName": last_name,
 
6135
  "grade": resolved_grade,
6136
  "section": resolved_section,
6137
  "classSectionId": resolved_row_section_id,
6138
+ "enrolledSectionId": enrolled_section_id,
6139
+ "rosterStudentUid": roster_student_uid,
6140
+ "existingProfileUid": existing_profile_uid,
6141
+ "alreadyEnrolled": already_enrolled,
6142
  "status": status,
6143
  "issues": issues,
6144
  "duplicateInFile": duplicate_in_file,
 
6210
 
6211
  client = firebase_firestore.client()
6212
  preview_rows = cast(List[Dict[str, Any]], preview.get("rows") or [])
6213
+ candidate_rows = [
6214
+ row for row in preview_rows
6215
+ if str(row.get("status") or "") in {"valid", "move_confirmation_required"}
6216
+ ]
6217
 
6218
  result_rows: List[Dict[str, Any]] = []
6219
  warnings: List[str] = []
 
6249
  )
6250
  continue
6251
 
6252
+ if str(row.get("status") or "") == "move_confirmation_required":
6253
+ source_section_id = str(row.get("enrolledSectionId") or "").strip().lower()
6254
+ roster_student_uid = str(row.get("rosterStudentUid") or "").strip()
6255
+ if not payload.confirmSectionMoves:
6256
+ blocked_rows += 1
6257
+ result_rows.append(
6258
+ {
6259
+ "rowNumber": row_number,
6260
+ "studentId": student_id,
6261
+ "fullName": full_name,
6262
+ "email": email,
6263
+ "uid": None,
6264
+ "classSectionId": class_section_id,
6265
+ "status": "blocked",
6266
+ "message": f"Cannot import: already enrolled in {source_section_id}. Explicit move confirmation is required.",
6267
+ "temporaryPassword": None,
6268
+ }
6269
+ )
6270
+ continue
6271
+ if (
6272
+ not source_section_id
6273
+ or not roster_student_uid
6274
+ or (user.role != "admin" and not _teacher_can_manage_section(user, source_section_id))
6275
+ ):
6276
+ blocked_rows += 1
6277
+ result_rows.append(
6278
+ {
6279
+ "rowNumber": row_number,
6280
+ "studentId": student_id,
6281
+ "fullName": full_name,
6282
+ "email": email,
6283
+ "uid": None,
6284
+ "classSectionId": class_section_id,
6285
+ "status": "blocked",
6286
+ "message": "Cannot move student: source or destination section ownership could not be verified.",
6287
+ "temporaryPassword": None,
6288
+ }
6289
+ )
6290
+ continue
6291
+
6292
+ try:
6293
+ transaction = client.transaction()
6294
+ roster_ref = client.collection("managedStudents").document(roster_student_uid)
6295
+ profile_uid = str(row.get("existingProfileUid") or roster_student_uid).strip()
6296
+ profile_ref = client.collection("users").document(profile_uid)
6297
+ source_ownership_ref = client.collection("classSectionOwnership").document(source_section_id)
6298
+ destination_ownership_ref = client.collection("classSectionOwnership").document(class_section_id)
6299
+
6300
+ def read_transaction_snapshot(reference: Any) -> Any:
6301
+ transaction_read = transaction.get(reference)
6302
+ if hasattr(transaction_read, "exists"):
6303
+ return transaction_read
6304
+ return next(iter(transaction_read), None)
6305
+
6306
+ read_refs = [roster_ref, source_ownership_ref, destination_ownership_ref]
6307
+ snapshots = [read_transaction_snapshot(reference) for reference in read_refs]
6308
+ roster_snapshot, source_snapshot, destination_snapshot = snapshots
6309
+ source_classrooms = list(
6310
+ transaction.get(
6311
+ client.collection("classrooms").where("classSectionId", "==", source_section_id)
6312
+ )
6313
+ )
6314
+ destination_classrooms = list(
6315
+ transaction.get(
6316
+ client.collection("classrooms").where("classSectionId", "==", class_section_id)
6317
+ )
6318
+ )
6319
+ if not _snapshot_exists(roster_snapshot):
6320
+ raise ValueError("Student roster entry no longer exists")
6321
+
6322
+ current_roster = _snapshot_to_dict(roster_snapshot)
6323
+ current_section = str(current_roster.get("classSectionId") or current_roster.get("classroomId") or "").strip().lower()
6324
+ current_lrn = str(current_roster.get("lrn") or "").strip()
6325
+ if current_section != source_section_id:
6326
+ raise ValueError("Student roster section changed after preview")
6327
+ if current_lrn != student_id:
6328
+ raise ValueError("Student LRN changed after preview")
6329
+
6330
+ source_ownership = _snapshot_to_dict(source_snapshot) if _snapshot_exists(source_snapshot) else {}
6331
+ destination_ownership = (
6332
+ _snapshot_to_dict(destination_snapshot) if _snapshot_exists(destination_snapshot) else {}
6333
+ )
6334
+ for ownership_name, ownership_data in (
6335
+ ("source", source_ownership),
6336
+ ("destination", destination_ownership),
6337
+ ):
6338
+ matching_classrooms = source_classrooms if ownership_name == "source" else destination_classrooms
6339
+ ownership_matches = user.uid in {
6340
+ str(ownership_data.get("ownerTeacherId") or ""),
6341
+ str(ownership_data.get("managerId") or ""),
6342
+ }
6343
+ classroom_matches = any(
6344
+ user.uid
6345
+ in {
6346
+ str(classroom_data.get("teacherId") or ""),
6347
+ str(classroom_data.get("ownerTeacherId") or ""),
6348
+ str(classroom_data.get("managerId") or ""),
6349
+ }
6350
+ for classroom_data in (_snapshot_to_dict(snapshot) for snapshot in matching_classrooms)
6351
+ )
6352
+ if user.role != "admin" and not (ownership_matches or classroom_matches):
6353
+ raise ValueError(f"{ownership_name.title()} section ownership changed after preview")
6354
+ source_uids = set(cast(List[str], source_ownership.get("studentUids") or []))
6355
+ destination_uids = set(cast(List[str], destination_ownership.get("studentUids") or []))
6356
+ source_uids.discard(roster_student_uid)
6357
+ destination_uids.add(roster_student_uid)
6358
+ class_section_name = f"{grade} - {section}"
6359
+ class_metadata = _build_class_metadata(
6360
+ class_section_id=class_section_id,
6361
+ class_name=class_section_name,
6362
+ grade=grade,
6363
+ section=section,
6364
+ owner_teacher_id=str(destination_ownership.get("ownerTeacherId") or user.uid),
6365
+ owner_teacher_name=str(destination_ownership.get("ownerTeacherName") or user.email),
6366
+ adviser_teacher_id=user.uid,
6367
+ adviser_teacher_name=user.email,
6368
+ manager_id=str(destination_ownership.get("managerId") or user.uid),
6369
+ manager_name=str(destination_ownership.get("managerName") or user.email),
6370
+ )
6371
+
6372
+ transaction.update(
6373
+ roster_ref,
6374
+ {
6375
+ "classSectionId": class_section_id,
6376
+ "classroomId": class_section_id,
6377
+ "className": class_section_name,
6378
+ "grade": grade,
6379
+ "section": section,
6380
+ "classMetadata": class_metadata,
6381
+ "teacherId": user.uid,
6382
+ "adviserTeacherId": user.uid,
6383
+ "adviserTeacherName": user.email,
6384
+ "managerId": user.uid,
6385
+ "managerName": user.email,
6386
+ "updatedAt": FIRESTORE_SERVER_TIMESTAMP,
6387
+ },
6388
+ )
6389
+ transaction.set(
6390
+ profile_ref,
6391
+ {
6392
+ "classSectionId": class_section_id,
6393
+ "section": section,
6394
+ "grade": grade,
6395
+ "teacherId": user.uid,
6396
+ "adviserTeacherId": user.uid,
6397
+ "adviserTeacherName": user.email,
6398
+ "classMetadata": class_metadata,
6399
+ "updatedAt": FIRESTORE_SERVER_TIMESTAMP,
6400
+ },
6401
+ merge=True,
6402
+ )
6403
+ transaction.set(
6404
+ source_ownership_ref,
6405
+ {"studentUids": sorted(source_uids), "updatedAt": FIRESTORE_SERVER_TIMESTAMP},
6406
+ merge=True,
6407
+ )
6408
+ transaction.set(
6409
+ destination_ownership_ref,
6410
+ {
6411
+ "classSectionId": class_section_id,
6412
+ "className": class_section_name,
6413
+ "ownerTeacherId": str(destination_ownership.get("ownerTeacherId") or user.uid),
6414
+ "managerId": str(destination_ownership.get("managerId") or user.uid),
6415
+ "studentUids": sorted(destination_uids),
6416
+ "updatedAt": FIRESTORE_SERVER_TIMESTAMP,
6417
+ },
6418
+ merge=True,
6419
+ )
6420
+ transaction.commit()
6421
+ updated_rows += 1
6422
+ result_rows.append(
6423
+ {
6424
+ "rowNumber": row_number,
6425
+ "studentId": student_id,
6426
+ "fullName": full_name,
6427
+ "email": email,
6428
+ "uid": roster_student_uid,
6429
+ "classSectionId": class_section_id,
6430
+ "status": "updated",
6431
+ "message": f"Student moved from {source_section_id} to {class_section_id}.",
6432
+ "temporaryPassword": None,
6433
+ }
6434
+ )
6435
+ except Exception as move_err:
6436
+ blocked_rows += 1
6437
+ result_rows.append(
6438
+ {
6439
+ "rowNumber": row_number,
6440
+ "studentId": student_id,
6441
+ "fullName": full_name,
6442
+ "email": email,
6443
+ "uid": None,
6444
+ "classSectionId": class_section_id,
6445
+ "status": "blocked",
6446
+ "message": f"Cannot move student: {move_err}",
6447
+ "temporaryPassword": None,
6448
+ }
6449
+ )
6450
+ continue
6451
+
6452
  existing_profile_doc = None
6453
  existing_uid: Optional[str] = None
6454
  try:
 
6465
  except Exception as duplicate_err:
6466
  warnings.append(f"Duplicate re-check warning for row {row_number}: {duplicate_err}")
6467
 
6468
+ try:
6469
+ roster_rows = list(
6470
+ client.collection("managedStudents").where("lrn", "==", student_id).limit(1).stream()
6471
+ ) if student_id else []
6472
+ if roster_rows:
6473
+ roster_data = _snapshot_to_dict(roster_rows[0])
6474
+ enrolled_section_id = str(roster_data.get("classSectionId") or roster_data.get("classroomId") or "").strip()
6475
+ if enrolled_section_id:
6476
+ blocked_rows += 1
6477
+ result_rows.append(
6478
+ {
6479
+ "rowNumber": row_number,
6480
+ "studentId": student_id,
6481
+ "fullName": full_name,
6482
+ "email": email,
6483
+ "uid": None,
6484
+ "classSectionId": class_section_id,
6485
+ "status": "blocked",
6486
+ "message": f"Cannot import: already enrolled in {enrolled_section_id}.",
6487
+ "temporaryPassword": None,
6488
+ }
6489
+ )
6490
+ continue
6491
+ except Exception as roster_err:
6492
+ warnings.append(f"Roster membership check warning for row {row_number}: {roster_err}")
6493
+
6494
  auth_uid: Optional[str] = None
6495
  temporary_password: Optional[str] = None
6496
  auth_existing = False
 
8166
  file_students = normalized_result["rows"]
8167
  file_row_warnings = normalized_result["rowWarnings"]
8168
  file_rejected_rows = normalized_result.get("rejectedRows") or []
8169
+ invalid_lrn_rows = [
8170
+ item for item in file_rejected_rows
8171
+ if "LRN must contain exactly 12 digits" in str(item.get("reason") or "")
8172
+ ]
8173
+ if invalid_lrn_rows:
8174
+ file_students = []
8175
+ file_rejected_rows_count = len(file_rejected_rows)
8176
+ raise HTTPException(
8177
+ status_code=400,
8178
+ detail="Invalid LRN rows: " + "; ".join(str(item["reason"]) for item in invalid_lrn_rows),
8179
+ )
8180
  file_unknown_columns = normalized_result["unknownColumns"]
8181
  file_interpreted_rows = int(normalized_result.get("interpretedRows") or len(file_students))
8182
  file_rejected_rows_count = int(normalized_result.get("rejectedRowsCount") or len(file_rejected_rows))
routes/class_analytics_routes.py CHANGED
@@ -24,10 +24,55 @@ def _require_teacher(request: Request):
24
  return user
25
 
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  @router.get("/{class_id}")
28
  async def get_class_analytics(class_id: str, request: Request, refresh: bool = False):
29
  """Get full class analytics report. Cached for 30 min unless refresh=true."""
30
  user = _require_teacher(request)
 
31
 
32
  from services.class_analytics_engine import get_class_analytics_engine
33
  engine = get_class_analytics_engine()
@@ -41,6 +86,7 @@ async def get_class_students(
41
  ):
42
  """Get student summaries for a class with optional filtering."""
43
  user = _require_teacher(request)
 
44
 
45
  from services.class_analytics_engine import get_class_analytics_engine
46
  engine = get_class_analytics_engine()
@@ -66,6 +112,7 @@ async def get_class_students(
66
  async def get_class_topics(class_id: str, request: Request):
67
  """Get topic performance sorted by accuracy (worst first)."""
68
  user = _require_teacher(request)
 
69
 
70
  from services.class_analytics_engine import get_class_analytics_engine
71
  engine = get_class_analytics_engine()
@@ -79,6 +126,7 @@ async def get_class_topics(class_id: str, request: Request):
79
  async def refresh_class_insights(class_id: str, request: Request):
80
  """Force regeneration of AI insights. Rate limited: 1 per 5 min per class."""
81
  user = _require_teacher(request)
 
82
 
83
  last_refresh = _refresh_timestamps.get(class_id, 0)
84
  if time.time() - last_refresh < 300:
 
24
  return user
25
 
26
 
27
+ def _require_class_ownership(user, class_id: str) -> None:
28
+ if user.role == "admin":
29
+ return
30
+
31
+ from services.class_analytics_engine import _get_firestore_client
32
+
33
+ client = _get_firestore_client()
34
+ if not client:
35
+ raise HTTPException(status_code=503, detail="Class ownership could not be verified")
36
+
37
+ normalized_class_id = class_id.strip().lower()
38
+ try:
39
+ classroom = client.collection("classrooms").document(class_id).get()
40
+ if classroom.exists:
41
+ classroom_data = classroom.to_dict() or {}
42
+ if user.uid in {
43
+ str(classroom_data.get("teacherId") or ""),
44
+ str(classroom_data.get("ownerTeacherId") or ""),
45
+ str(classroom_data.get("managerId") or ""),
46
+ }:
47
+ return
48
+ raise HTTPException(status_code=403, detail="You are not allowed to view this class report")
49
+
50
+ ownership = client.collection("classSectionOwnership").document(normalized_class_id).get()
51
+ if ownership.exists:
52
+ ownership_data = ownership.to_dict() or {}
53
+ if user.uid in {
54
+ str(ownership_data.get("ownerTeacherId") or ""),
55
+ str(ownership_data.get("managerId") or ""),
56
+ }:
57
+ return
58
+
59
+ for field in ("teacherId", "ownerTeacherId", "managerId"):
60
+ classrooms = client.collection("classrooms").where("classSectionId", "==", normalized_class_id).where(
61
+ field, "==", user.uid
62
+ ).limit(1)
63
+ if list(classrooms.stream()):
64
+ return
65
+ except Exception as ownership_error:
66
+ logger.warning("Class ownership check failed for %s: %s", class_id, ownership_error)
67
+
68
+ raise HTTPException(status_code=403, detail="You are not allowed to view this class report")
69
+
70
+
71
  @router.get("/{class_id}")
72
  async def get_class_analytics(class_id: str, request: Request, refresh: bool = False):
73
  """Get full class analytics report. Cached for 30 min unless refresh=true."""
74
  user = _require_teacher(request)
75
+ _require_class_ownership(user, class_id)
76
 
77
  from services.class_analytics_engine import get_class_analytics_engine
78
  engine = get_class_analytics_engine()
 
86
  ):
87
  """Get student summaries for a class with optional filtering."""
88
  user = _require_teacher(request)
89
+ _require_class_ownership(user, class_id)
90
 
91
  from services.class_analytics_engine import get_class_analytics_engine
92
  engine = get_class_analytics_engine()
 
112
  async def get_class_topics(class_id: str, request: Request):
113
  """Get topic performance sorted by accuracy (worst first)."""
114
  user = _require_teacher(request)
115
+ _require_class_ownership(user, class_id)
116
 
117
  from services.class_analytics_engine import get_class_analytics_engine
118
  engine = get_class_analytics_engine()
 
126
  async def refresh_class_insights(class_id: str, request: Request):
127
  """Force regeneration of AI insights. Rate limited: 1 per 5 min per class."""
128
  user = _require_teacher(request)
129
+ _require_class_ownership(user, class_id)
130
 
131
  last_refresh = _refresh_timestamps.get(class_id, 0)
132
  if time.time() - last_refresh < 300:
services/user_provisioning_service.py CHANGED
@@ -15,6 +15,7 @@ logger = logging.getLogger("mathpulse")
15
  VALID_ROLES = {"student", "teacher", "admin"}
16
  VALID_STATUSES = {"active", "inactive"}
17
  EMAIL_REGEX = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
 
18
  PASSWORD_UPPER_REGEX = re.compile(r"[A-Z]")
19
  PASSWORD_LOWER_REGEX = re.compile(r"[a-z]")
20
  PASSWORD_DIGIT_REGEX = re.compile(r"\d")
@@ -179,6 +180,8 @@ class UserProvisioningService:
179
  lrn = (user_input.lrn or "").strip()
180
  if not lrn:
181
  raise UserProvisioningError("missing_lrn", "LRN is required for student accounts.", 400)
 
 
182
  payload.update(
183
  {
184
  "lrn": lrn,
@@ -221,6 +224,12 @@ class UserProvisioningService:
221
  validated_password = self._validate_password(user_input.password, user_input.confirm_password)
222
  role_lower = self._normalize_role(user_input.role)
223
  normalized_status = self._normalize_status(user_input.status)
 
 
 
 
 
 
224
 
225
  firestore_client = self._firestore_module.client()
226
  self._ensure_no_duplicate_email(normalized_email, firestore_client)
 
15
  VALID_ROLES = {"student", "teacher", "admin"}
16
  VALID_STATUSES = {"active", "inactive"}
17
  EMAIL_REGEX = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
18
+ LRN_REGEX = re.compile(r"^\d{12}$")
19
  PASSWORD_UPPER_REGEX = re.compile(r"[A-Z]")
20
  PASSWORD_LOWER_REGEX = re.compile(r"[a-z]")
21
  PASSWORD_DIGIT_REGEX = re.compile(r"\d")
 
180
  lrn = (user_input.lrn or "").strip()
181
  if not lrn:
182
  raise UserProvisioningError("missing_lrn", "LRN is required for student accounts.", 400)
183
+ if not LRN_REGEX.fullmatch(lrn):
184
+ raise UserProvisioningError("invalid_lrn", "LRN must contain exactly 12 digits.", 400)
185
  payload.update(
186
  {
187
  "lrn": lrn,
 
224
  validated_password = self._validate_password(user_input.password, user_input.confirm_password)
225
  role_lower = self._normalize_role(user_input.role)
226
  normalized_status = self._normalize_status(user_input.status)
227
+ if role_lower == "student":
228
+ normalized_lrn = (user_input.lrn or "").strip()
229
+ if not normalized_lrn:
230
+ raise UserProvisioningError("missing_lrn", "LRN is required for student accounts.", 400)
231
+ if not LRN_REGEX.fullmatch(normalized_lrn):
232
+ raise UserProvisioningError("invalid_lrn", "LRN must contain exactly 12 digits.", 400)
233
 
234
  firestore_client = self._firestore_module.client()
235
  self._ensure_no_duplicate_email(normalized_email, firestore_client)
tests/test_api.py CHANGED
@@ -910,7 +910,7 @@ class TestUploadClassRecordsGuardrails:
910
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
911
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
912
  files = {
913
- "files": ("records.csv", b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion\nAna,1001,ana@example.com,80,90,85,88\n", "text/csv"),
914
  }
915
  response = client.post(
916
  "/api/upload/class-records",
@@ -926,7 +926,7 @@ class TestUploadClassRecordsGuardrails:
926
  files = {
927
  "files": (
928
  "records.csv",
929
- b"name,lrn,email,attendance\nAna,1001,ana@example.com,90\n",
930
  "text/csv",
931
  ),
932
  }
@@ -951,7 +951,7 @@ class TestUploadClassRecordsGuardrails:
951
  "records.csv",
952
  (
953
  b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion,patient_diagnosis\n"
954
- b"Ana,1001,ana@example.com,80,90,85,88,none\n"
955
  ),
956
  "text/csv",
957
  ),
@@ -993,8 +993,8 @@ class TestUploadClassRecordsGuardrails:
993
  "records.csv",
994
  (
995
  b"name,lrn,avgQuizScore,attendance,engagementScore\n"
996
- b"Ana Cruz,1001,81,92,88\n"
997
- b"Ben Dela,1002,58,70,52\n"
998
  ),
999
  "text/csv",
1000
  ),
@@ -1022,16 +1022,48 @@ class TestUploadClassRecordsGuardrails:
1022
  assert class_metadata.get("gradeLevel") == "Grade 11"
1023
  assert class_metadata.get("classification") == "Senior High School"
1024
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1025
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1026
  def test_upload_class_records_reports_explicit_row_rejections(self, _mock_chat):
1027
  files = {
1028
  "files": (
1029
  "records.csv",
1030
  (
1031
- b"name,lrn,email,avgQuizScore,attendance,engagementScore\n"
1032
- b",1001,ana@example.com,81,92,88\n"
1033
- b"Ben Dela,,,58,70,52\n"
1034
- b"Cara Lim,1003,,77,83,75\n"
1035
  ),
1036
  "text/csv",
1037
  ),
@@ -1067,7 +1099,7 @@ class TestUploadClassRecordsGuardrails:
1067
  "records.csv",
1068
  (
1069
  b"name,lrn,avgQuizScore,attendance,engagementScore\n"
1070
- b"Ana Cruz,1001,81,92,88\n"
1071
  ),
1072
  "text/csv",
1073
  ),
@@ -1116,7 +1148,7 @@ class TestImportedOverviewAndTopicMastery:
1116
  {
1117
  "teacherId": "test-teacher-uid",
1118
  "name": "Ben Dela",
1119
- "lrn": "1002",
1120
  "classSectionId": "grade11_a",
1121
  "className": "Grade 11 - A",
1122
  "avgQuizScore": 68,
@@ -1600,6 +1632,9 @@ class _ProvisionDocumentRef:
1600
  existing.update(payload)
1601
  collection[self._doc_id] = existing
1602
 
 
 
 
1603
  def delete(self):
1604
  collection = self._store.setdefault(self._collection_name, {})
1605
  collection.pop(self._doc_id, None)
@@ -1671,6 +1706,29 @@ class _ProvisionFirestoreClient:
1671
  def collection(self, name: str):
1672
  return _ProvisionCollectionRef(self.store, name)
1673
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1674
 
1675
  class _ProvisionFirestoreModule:
1676
  class Query:
@@ -1693,7 +1751,7 @@ class TestStudentAccountProvisioningImport:
1693
  "users": {
1694
  "existing-student": {
1695
  "email": "existing@student.com",
1696
- "lrn": "1002",
1697
  "role": "student",
1698
  }
1699
  }
@@ -1713,9 +1771,9 @@ class TestStudentAccountProvisioningImport:
1713
  "accounts.csv",
1714
  (
1715
  b"First Name,Last Name,Student ID,Email,Grade,Section\n"
1716
- b"Ana,Cruz,1001,ana@student.com,Grade 11,STEM-A\n"
1717
- b"Ben,Dela,1002,existing@student.com,Grade 11,STEM-A\n"
1718
- b",Lim,1003,cara@student.com,Grade 11,STEM-A\n"
1719
  ),
1720
  "text/csv",
1721
  )
@@ -1745,7 +1803,7 @@ class TestStudentAccountProvisioningImport:
1745
  files={
1746
  "file": (
1747
  "accounts.csv",
1748
- b"First Name,Last Name,Student ID,Email,Grade,Section\nAna,Cruz,1001,ana@student.com,Grade 11,STEM-A\n",
1749
  "text/csv",
1750
  )
1751
  },
@@ -1778,6 +1836,149 @@ class TestStudentAccountProvisioningImport:
1778
  assert provisioned_profile.get("role") == "student"
1779
  assert provisioned_profile.get("forcePasswordChange") is True
1780
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1781
 
1782
  class _FakeEmailServiceSuccess:
1783
  def send_transactional_email(self, _message):
 
910
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
911
  def test_upload_class_records_rejects_unsupported_dataset_intent(self, _mock_chat):
912
  files = {
913
+ "files": ("records.csv", b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion\nAna,123456789001,ana@example.com,80,90,85,88\n", "text/csv"),
914
  }
915
  response = client.post(
916
  "/api/upload/class-records",
 
926
  files = {
927
  "files": (
928
  "records.csv",
929
+ b"name,lrn,email,attendance\nAna,123456789001,ana@example.com,90\n",
930
  "text/csv",
931
  ),
932
  }
 
951
  "records.csv",
952
  (
953
  b"name,lrn,email,avgQuizScore,attendance,engagementScore,assignmentCompletion,patient_diagnosis\n"
954
+ b"Ana,123456789001,ana@example.com,80,90,85,88,none\n"
955
  ),
956
  "text/csv",
957
  ),
 
993
  "records.csv",
994
  (
995
  b"name,lrn,avgQuizScore,attendance,engagementScore\n"
996
+ b"Ana Cruz,123456789001,81,92,88\n"
997
+ b"Ben Dela,123456789002,58,70,52\n"
998
  ),
999
  "text/csv",
1000
  ),
 
1022
  assert class_metadata.get("gradeLevel") == "Grade 11"
1023
  assert class_metadata.get("classification") == "Senior High School"
1024
 
1025
+ @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1026
+ def test_upload_class_records_imports_real_xlsx_rows(self, _mock_chat):
1027
+ from io import BytesIO
1028
+ from openpyxl import Workbook
1029
+
1030
+ workbook = BytesIO()
1031
+ excel = Workbook()
1032
+ sheet = excel.active
1033
+ assert sheet is not None
1034
+ sheet.append(["name", "lrn", "email", "avgQuizScore", "attendance", "engagementScore", "assignmentCompletion", "term", "assessmentName"])
1035
+ sheet.append(["Ana Cruz", "123456789001", "ana@example.com", 81, 92, 88, 90, "First Semester", "Algebra Quiz"])
1036
+ excel.save(workbook)
1037
+
1038
+ response = client.post(
1039
+ "/api/upload/class-records",
1040
+ files={
1041
+ "files": (
1042
+ "class-record.xlsx",
1043
+ workbook.getvalue(),
1044
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1045
+ )
1046
+ },
1047
+ data={"datasetIntent": "synthetic_student_records"},
1048
+ )
1049
+
1050
+ assert response.status_code == 200
1051
+ payload = response.json()
1052
+ assert payload["success"] is True
1053
+ assert payload["interpretedRows"] == 1
1054
+ assert payload["rejectedRows"] == 0
1055
+ assert payload["students"][0]["lrn"] == "123456789001"
1056
+
1057
  @patch("main.call_hf_chat", side_effect=Exception("mapper unavailable"))
1058
  def test_upload_class_records_reports_explicit_row_rejections(self, _mock_chat):
1059
  files = {
1060
  "files": (
1061
  "records.csv",
1062
  (
1063
+ b"name,email,avgQuizScore,attendance,engagementScore\n"
1064
+ b",ana@example.com,81,92,88\n"
1065
+ b"Ben Dela,,58,70,52\n"
1066
+ b"Cara Lim,cara@example.com,77,83,75\n"
1067
  ),
1068
  "text/csv",
1069
  ),
 
1099
  "records.csv",
1100
  (
1101
  b"name,lrn,avgQuizScore,attendance,engagementScore\n"
1102
+ b"Ana Cruz,123456789001,81,92,88\n"
1103
  ),
1104
  "text/csv",
1105
  ),
 
1148
  {
1149
  "teacherId": "test-teacher-uid",
1150
  "name": "Ben Dela",
1151
+ "lrn": "123456789002",
1152
  "classSectionId": "grade11_a",
1153
  "className": "Grade 11 - A",
1154
  "avgQuizScore": 68,
 
1632
  existing.update(payload)
1633
  collection[self._doc_id] = existing
1634
 
1635
+ def update(self, payload: Dict[str, Any]):
1636
+ self.set(payload, merge=True)
1637
+
1638
  def delete(self):
1639
  collection = self._store.setdefault(self._collection_name, {})
1640
  collection.pop(self._doc_id, None)
 
1706
  def collection(self, name: str):
1707
  return _ProvisionCollectionRef(self.store, name)
1708
 
1709
+ def transaction(self):
1710
+ return _ProvisionTransaction()
1711
+
1712
+
1713
+ class _ProvisionTransaction:
1714
+ def __init__(self):
1715
+ self._writes: List[tuple[str, _ProvisionDocumentRef, Dict[str, Any], bool]] = []
1716
+
1717
+ def get(self, reference: _ProvisionDocumentRef):
1718
+ if isinstance(reference, _ProvisionQuery):
1719
+ return iter(reference.stream())
1720
+ return iter([reference.get()])
1721
+
1722
+ def set(self, reference: _ProvisionDocumentRef, payload: Dict[str, Any], merge: bool = False):
1723
+ self._writes.append(("set", reference, payload, merge))
1724
+
1725
+ def update(self, reference: _ProvisionDocumentRef, payload: Dict[str, Any]):
1726
+ self._writes.append(("update", reference, payload, True))
1727
+
1728
+ def commit(self):
1729
+ for _, reference, payload, merge in self._writes:
1730
+ reference.set(payload, merge=merge)
1731
+
1732
 
1733
  class _ProvisionFirestoreModule:
1734
  class Query:
 
1751
  "users": {
1752
  "existing-student": {
1753
  "email": "existing@student.com",
1754
+ "lrn": "123456789002",
1755
  "role": "student",
1756
  }
1757
  }
 
1771
  "accounts.csv",
1772
  (
1773
  b"First Name,Last Name,Student ID,Email,Grade,Section\n"
1774
+ b"Ana,Cruz,123456789001,ana@student.com,Grade 11,STEM-A\n"
1775
+ b"Ben,Dela,123456789002,existing@student.com,Grade 11,STEM-A\n"
1776
+ b",Lim,123456789003,cara@student.com,Grade 11,STEM-A\n"
1777
  ),
1778
  "text/csv",
1779
  )
 
1803
  files={
1804
  "file": (
1805
  "accounts.csv",
1806
+ b"First Name,Last Name,Student ID,Email,Grade,Section\nAna,Cruz,123456789001,ana@student.com,Grade 11,STEM-A\n",
1807
  "text/csv",
1808
  )
1809
  },
 
1836
  assert provisioned_profile.get("role") == "student"
1837
  assert provisioned_profile.get("forcePasswordChange") is True
1838
 
1839
+ @staticmethod
1840
+ def _move_firestore() -> _ProvisionFirestoreModule:
1841
+ return _ProvisionFirestoreModule(
1842
+ {
1843
+ "users": {
1844
+ "student-uid": {
1845
+ "name": "Ana Cruz",
1846
+ "email": "ana@student.com",
1847
+ "lrn": "123456789001",
1848
+ "role": "student",
1849
+ "classSectionId": "grade_11_stem_a",
1850
+ "section": "STEM-A",
1851
+ "teacherId": "former-teacher",
1852
+ "adviserTeacherId": "former-teacher",
1853
+ }
1854
+ },
1855
+ "managedStudents": {
1856
+ "student-uid": {
1857
+ "name": "Ana Cruz",
1858
+ "email": "ana@student.com",
1859
+ "lrn": "123456789001",
1860
+ "classSectionId": "grade_11_stem_a",
1861
+ "classroomId": "grade_11_stem_a",
1862
+ "teacherId": "former-teacher",
1863
+ "adviserTeacherId": "former-teacher",
1864
+ }
1865
+ },
1866
+ "classSectionOwnership": {
1867
+ "grade_11_stem_a": {
1868
+ "ownerTeacherId": "admin-uid",
1869
+ "managerId": "admin-uid",
1870
+ "studentUids": ["student-uid"],
1871
+ },
1872
+ "grade_11_stem_b": {
1873
+ "ownerTeacherId": "admin-uid",
1874
+ "managerId": "admin-uid",
1875
+ "studentUids": [],
1876
+ },
1877
+ },
1878
+ "accessAuditLogs": {},
1879
+ }
1880
+ )
1881
+
1882
+ @staticmethod
1883
+ def _preview_move_import() -> Dict[str, Any]:
1884
+ response = client.post(
1885
+ "/api/import/student-accounts/preview",
1886
+ data={"classSectionId": "grade_11_stem_b"},
1887
+ files={
1888
+ "file": (
1889
+ "accounts.csv",
1890
+ b"First Name,Last Name,Student ID,Email,Grade,Section\nAna,Cruz,123456789001,ana@student.com,Grade 11,STEM-B\n",
1891
+ "text/csv",
1892
+ )
1893
+ },
1894
+ )
1895
+ assert response.status_code == 200
1896
+ return response.json()
1897
+
1898
+ def test_move_confirmation_reassigns_roster_with_sdk_transaction_iterators(self):
1899
+ firestore = self._move_firestore()
1900
+ token_claims = {"uid": "admin-uid", "email": "admin@example.com", "role": "admin"}
1901
+ with (
1902
+ patch.object(main_module, "firebase_firestore", firestore),
1903
+ patch.object(main_module, "_firebase_ready", True),
1904
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value=token_claims),
1905
+ patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")),
1906
+ ):
1907
+ unconfirmed_preview = self._preview_move_import()
1908
+ assert unconfirmed_preview["rows"][0]["status"] == "move_confirmation_required"
1909
+ unconfirmed = client.post(
1910
+ "/api/import/student-accounts/commit",
1911
+ json={"previewToken": unconfirmed_preview["previewToken"]},
1912
+ )
1913
+ assert unconfirmed.status_code == 200
1914
+ assert unconfirmed.json()["rows"][0]["message"].startswith("Cannot import")
1915
+ assert firestore.client().store["managedStudents"]["student-uid"]["classSectionId"] == "grade_11_stem_a"
1916
+
1917
+ confirmed_preview = self._preview_move_import()
1918
+ confirmed = client.post(
1919
+ "/api/import/student-accounts/commit",
1920
+ json={"previewToken": confirmed_preview["previewToken"], "confirmSectionMoves": True},
1921
+ )
1922
+
1923
+ assert confirmed.status_code == 200
1924
+ assert confirmed.json()["rows"][0]["status"] == "updated"
1925
+ moved_roster = firestore.client().store["managedStudents"]["student-uid"]
1926
+ moved_profile = firestore.client().store["users"]["student-uid"]
1927
+ assert moved_roster["classSectionId"] == "grade_11_stem_b"
1928
+ assert moved_roster["teacherId"] == "admin-uid"
1929
+ assert moved_roster["adviserTeacherId"] == "admin-uid"
1930
+ assert moved_profile["classSectionId"] == "grade_11_stem_b"
1931
+ assert firestore.client().store["classSectionOwnership"]["grade_11_stem_a"]["studentUids"] == []
1932
+ assert firestore.client().store["classSectionOwnership"]["grade_11_stem_b"]["studentUids"] == ["student-uid"]
1933
+
1934
+ def test_confirmed_move_blocks_when_roster_lrn_changed_after_preview(self):
1935
+ firestore = self._move_firestore()
1936
+ token_claims = {"uid": "admin-uid", "email": "admin@example.com", "role": "admin"}
1937
+ with (
1938
+ patch.object(main_module, "firebase_firestore", firestore),
1939
+ patch.object(main_module, "_firebase_ready", True),
1940
+ patch.object(main_module.firebase_auth, "verify_id_token", return_value=token_claims),
1941
+ patch.object(main_module.firebase_auth, "get_user_by_email", side_effect=Exception("user not found")),
1942
+ ):
1943
+ preview = self._preview_move_import()
1944
+ firestore.client().store["managedStudents"]["student-uid"]["lrn"] = "123456789999"
1945
+ response = client.post(
1946
+ "/api/import/student-accounts/commit",
1947
+ json={"previewToken": preview["previewToken"], "confirmSectionMoves": True},
1948
+ )
1949
+
1950
+ assert response.status_code == 200
1951
+ assert response.json()["rows"][0]["status"] == "blocked"
1952
+ assert firestore.client().store["managedStudents"]["student-uid"]["classSectionId"] == "grade_11_stem_a"
1953
+
1954
+
1955
+ def test_class_analytics_rejects_same_id_ownership_collision():
1956
+ from types import SimpleNamespace
1957
+ from fastapi import HTTPException
1958
+ from routes import class_analytics_routes
1959
+
1960
+ firestore = _ProvisionFirestoreModule(
1961
+ {
1962
+ "classrooms": {
1963
+ "collision-id": {
1964
+ "classSectionId": "owned-section",
1965
+ "teacherId": "different-teacher",
1966
+ }
1967
+ },
1968
+ "classSectionOwnership": {
1969
+ "collision-id": {"ownerTeacherId": "requesting-teacher"},
1970
+ "owned-section": {"ownerTeacherId": "requesting-teacher"},
1971
+ },
1972
+ }
1973
+ )
1974
+ user = SimpleNamespace(uid="requesting-teacher", role="teacher")
1975
+
1976
+ with patch("services.class_analytics_engine._get_firestore_client", return_value=firestore.client()):
1977
+ with pytest.raises(HTTPException) as error:
1978
+ class_analytics_routes._require_class_ownership(user, "collision-id")
1979
+
1980
+ assert error.value.status_code == 403
1981
+
1982
 
1983
  class _FakeEmailServiceSuccess:
1984
  def send_transactional_email(self, _message):