| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | use crate::constant::{ACADEMIC_YEAR_CLASS_COUNT_FIELD, CLASS_GROUP_TABLE}; |
| 7 | use crate::database::{Database, tx_with_retry}; |
| 8 | use crate::db::field_update::{FieldUpdate, Refcount}; |
| 9 | use crate::db::page::PagedList; |
| 10 | use crate::domain::academic_year::AcademicYearId; |
| 11 | use crate::domain::class_group::{ClassGroup, ClassGroupId, ClassName}; |
| 12 | use crate::domain::grade::GradeLevel; |
| 13 | use crate::domain::user::UserId; |
| 14 | use crate::error::{AppError, ValidationError}; |
| 15 | |
| 16 | |
| 17 | |
| 18 | fn year_gone() -> AppError { |
| 19 | AppError::Validation(ValidationError::Invalid { |
| 20 | field: "year", |
| 21 | reason: "academic year does not exist", |
| 22 | }) |
| 23 | } |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | fn year_ref_move( |
| 31 | current: Option<&AcademicYearId>, |
| 32 | patch: &Option<Option<AcademicYearId>>, |
| 33 | ) -> (Option<AcademicYearId>, Option<AcademicYearId>) { |
| 34 | match patch { |
| 35 | None => (None, None), |
| 36 | Some(next) if next.as_ref() == current => (None, None), |
| 37 | Some(next) => (*next, current.copied()), |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | |
| 44 | |
| 45 | |
| 46 | |
| 47 | |
| 48 | pub async fn create( |
| 49 | db: &Database, |
| 50 | creator: &UserId, |
| 51 | name: ClassName, |
| 52 | grade_level: GradeLevel, |
| 53 | year: Option<AcademicYearId>, |
| 54 | teacher: Option<UserId>, |
| 55 | ) -> Result<ClassGroup, AppError> { |
| 56 | let id = ClassGroupId::generate(); |
| 57 | match &year { |
| 58 | Some(year) => { |
| 59 | |
| 60 | |
| 61 | |
| 62 | let written = sqlx::query_as!( |
| 63 | ClassGroup, |
| 64 | r#"WITH seat AS ( |
| 65 | UPDATE academic_year SET class_count = class_count + 1 |
| 66 | WHERE id = $1 |
| 67 | RETURNING 1) |
| 68 | INSERT INTO class_group (id, creator, name, grade_level, year, teacher) |
| 69 | SELECT $2, $3, $4, $5, $1, $6 WHERE EXISTS (SELECT 1 FROM seat) |
| 70 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 71 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 72 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, |
| 73 | year.uuid(), |
| 74 | id.uuid(), |
| 75 | creator.uuid(), |
| 76 | name.as_str(), |
| 77 | grade_level.get(), |
| 78 | teacher.as_ref().map(UserId::uuid) |
| 79 | ) |
| 80 | .fetch_optional(db) |
| 81 | .await; |
| 82 | match written { |
| 83 | Ok(Some(created)) => Ok(created), |
| 84 | |
| 85 | |
| 86 | |
| 87 | Ok(None) => Err(year_gone()), |
| 88 | |
| 89 | |
| 90 | Err(e) if crate::database::foreign_key_violation(&e) => Err(year_gone()), |
| 91 | |
| 92 | Err(e) if crate::database::unique_violation(&e).is_some() => { |
| 93 | Err(AppError::Internal("failed to create class".into())) |
| 94 | } |
| 95 | Err(e) => Err(e.into()), |
| 96 | } |
| 97 | } |
| 98 | None => { |
| 99 | let created = sqlx::query_as!( |
| 100 | ClassGroup, |
| 101 | r#"INSERT INTO class_group (id, creator, name, grade_level, year, teacher) |
| 102 | VALUES ($1, $2, $3, $4, $5, $6) |
| 103 | RETURNING id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 104 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 105 | year AS "year: AcademicYearId", teacher AS "teacher: UserId""#, |
| 106 | id.uuid(), |
| 107 | creator.uuid(), |
| 108 | name.as_str(), |
| 109 | grade_level.get(), |
| 110 | year.as_ref().map(AcademicYearId::uuid), |
| 111 | teacher.as_ref().map(UserId::uuid) |
| 112 | ) |
| 113 | .fetch_optional(db) |
| 114 | .await?; |
| 115 | |
| 116 | created.ok_or_else(|| AppError::Internal("failed to create class".into())) |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | pub async fn read(db: &Database, id: &ClassGroupId) -> Result<Option<ClassGroup>, AppError> { |
| 122 | let class = sqlx::query_as!( |
| 123 | ClassGroup, |
| 124 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 125 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 126 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 127 | FROM class_group WHERE id = $1"#, |
| 128 | id.uuid() |
| 129 | ) |
| 130 | .fetch_optional(db) |
| 131 | .await?; |
| 132 | Ok(class) |
| 133 | } |
| 134 | |
| 135 | |
| 136 | |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | |
| 142 | pub async fn list_all( |
| 143 | db: &Database, |
| 144 | grade_level: Option<GradeLevel>, |
| 145 | limit: Option<i64>, |
| 146 | offset: i64, |
| 147 | ) -> Result<(Vec<ClassGroup>, i64), AppError> { |
| 148 | let list = match grade_level { |
| 149 | None => PagedList::new(CLASS_GROUP_TABLE, "ORDER BY id DESC"), |
| 150 | Some(grade_level) => PagedList::new( |
| 151 | format!("{CLASS_GROUP_TABLE} WHERE grade_level = $1"), |
| 152 | "ORDER BY id DESC", |
| 153 | ) |
| 154 | .bind(grade_level.get() as i64), |
| 155 | }; |
| 156 | list.run(limit, offset, db).await |
| 157 | } |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | |
| 167 | |
| 168 | |
| 169 | |
| 170 | pub async fn update( |
| 171 | db: &Database, |
| 172 | class: ClassGroup, |
| 173 | name: Option<ClassName>, |
| 174 | grade_level: Option<GradeLevel>, |
| 175 | year: Option<Option<AcademicYearId>>, |
| 176 | teacher: Option<Option<UserId>>, |
| 177 | ) -> Result<ClassGroup, AppError> { |
| 178 | let (claim, release) = year_ref_move(class.year.as_ref(), &year); |
| 179 | let expected = class.year.as_ref().map(AcademicYearId::uuid); |
| 180 | FieldUpdate::new(CLASS_GROUP_TABLE, class.id.uuid()) |
| 181 | .set("name", name.map(|name| name.as_str().to_string())) |
| 182 | |
| 183 | |
| 184 | |
| 185 | .set("grade_level", grade_level.map(|grade| grade.get() as i64)) |
| 186 | .set("year", year.map(|year| year.map(|year| year.uuid()))) |
| 187 | |
| 188 | |
| 189 | .set( |
| 190 | "teacher", |
| 191 | teacher.map(|teacher| teacher.map(|teacher| teacher.uuid())), |
| 192 | ) |
| 193 | .refcount(Refcount { |
| 194 | counter_table: "academic_year", |
| 195 | counter_field: ACADEMIC_YEAR_CLASS_COUNT_FIELD, |
| 196 | link: "year", |
| 197 | expected, |
| 198 | claim: claim.map(|year| year.uuid()), |
| 199 | release: release.map(|year| year.uuid()), |
| 200 | refused: year_gone(), |
| 201 | }) |
| 202 | .run::<ClassGroup>(db) |
| 203 | .await |
| 204 | } |
| 205 | |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | pub async fn list_by_ids(db: &Database, ids: &[ClassGroupId]) -> Result<Vec<ClassGroup>, AppError> { |
| 211 | if ids.is_empty() { |
| 212 | return Ok(Vec::new()); |
| 213 | } |
| 214 | let ids: Vec<uuid::Uuid> = ids.iter().map(ClassGroupId::uuid).collect(); |
| 215 | let classes = sqlx::query_as!( |
| 216 | ClassGroup, |
| 217 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 218 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 219 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 220 | FROM class_group WHERE id = ANY($1)"#, |
| 221 | &ids |
| 222 | ) |
| 223 | .fetch_all(db) |
| 224 | .await?; |
| 225 | Ok(classes) |
| 226 | } |
| 227 | |
| 228 | |
| 229 | |
| 230 | |
| 231 | pub async fn list_for_grade( |
| 232 | db: &Database, |
| 233 | grade_level: GradeLevel, |
| 234 | ) -> Result<Vec<ClassGroup>, AppError> { |
| 235 | let classes = sqlx::query_as!( |
| 236 | ClassGroup, |
| 237 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 238 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 239 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 240 | FROM class_group WHERE grade_level = $1"#, |
| 241 | grade_level.get() |
| 242 | ) |
| 243 | .fetch_all(db) |
| 244 | .await?; |
| 245 | Ok(classes) |
| 246 | } |
| 247 | |
| 248 | |
| 249 | |
| 250 | |
| 251 | pub async fn list_for_year( |
| 252 | db: &Database, |
| 253 | year: &AcademicYearId, |
| 254 | ) -> Result<Vec<ClassGroup>, AppError> { |
| 255 | let classes = sqlx::query_as!( |
| 256 | ClassGroup, |
| 257 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 258 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 259 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 260 | FROM class_group WHERE year = $1 ORDER BY id"#, |
| 261 | year.uuid() |
| 262 | ) |
| 263 | .fetch_all(db) |
| 264 | .await?; |
| 265 | Ok(classes) |
| 266 | } |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | |
| 272 | |
| 273 | |
| 274 | |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | |
| 280 | |
| 281 | |
| 282 | |
| 283 | pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<ClassGroup>, AppError> { |
| 284 | let classes = sqlx::query_as!( |
| 285 | ClassGroup, |
| 286 | r#"SELECT id AS "id: ClassGroupId", creator AS "creator: UserId", |
| 287 | name AS "name: ClassName", grade_level AS "grade_level: GradeLevel", |
| 288 | year AS "year: AcademicYearId", teacher AS "teacher: UserId" |
| 289 | FROM class_group WHERE teacher = $1 ORDER BY id DESC"#, |
| 290 | user.uuid() |
| 291 | ) |
| 292 | .fetch_all(db) |
| 293 | .await?; |
| 294 | Ok(classes) |
| 295 | } |
| 296 | |
| 297 | |
| 298 | |
| 299 | |
| 300 | |
| 301 | pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> { |
| 302 | sqlx::query!( |
| 303 | r#"UPDATE class_group SET teacher = NULL WHERE teacher = $1"#, |
| 304 | user.uuid() |
| 305 | ) |
| 306 | .execute(db) |
| 307 | .await?; |
| 308 | Ok(()) |
| 309 | } |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | |
| 316 | |
| 317 | |
| 318 | |
| 319 | |
| 320 | |
| 321 | |
| 322 | |
| 323 | |
| 324 | |
| 325 | |
| 326 | |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | pub async fn delete(db: &Database, class: ClassGroup) -> Result<bool, AppError> { |
| 336 | tx_with_retry(db, false, async move |tx| { |
| 337 | |
| 338 | |
| 339 | |
| 340 | |
| 341 | let guard = sqlx::query!( |
| 342 | r#"SELECT class_member_count, class_course_count, year AS "year: uuid::Uuid" |
| 343 | FROM class_group WHERE id = $1 FOR UPDATE"#, |
| 344 | class.id.uuid() |
| 345 | ) |
| 346 | .fetch_optional(&mut *tx) |
| 347 | .await?; |
| 348 | let Some(guard) = guard else { |
| 349 | return Err(AppError::NotFound); |
| 350 | }; |
| 351 | if guard.class_member_count != 0 || guard.class_course_count != 0 { |
| 352 | return Ok(false); |
| 353 | } |
| 354 | |
| 355 | |
| 356 | |
| 357 | sqlx::query!( |
| 358 | r#"UPDATE event SET audience_class = NULL WHERE audience_class = $1"#, |
| 359 | class.id.uuid() |
| 360 | ) |
| 361 | .execute(&mut *tx) |
| 362 | .await?; |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | sqlx::query!( |
| 368 | r#"DELETE FROM class_member WHERE class = $1"#, |
| 369 | class.id.uuid() |
| 370 | ) |
| 371 | .execute(&mut *tx) |
| 372 | .await?; |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | sqlx::query!( |
| 380 | r#"UPDATE class_member SET source_class_group = NULL WHERE source_class_group = $1"#, |
| 381 | class.id.uuid() |
| 382 | ) |
| 383 | .execute(&mut *tx) |
| 384 | .await?; |
| 385 | sqlx::query!( |
| 386 | r#"UPDATE enrollment SET source = NULL WHERE source = $1"#, |
| 387 | class.id.uuid() |
| 388 | ) |
| 389 | .execute(&mut *tx) |
| 390 | .await?; |
| 391 | |
| 392 | |
| 393 | sqlx::query!(r#"DELETE FROM class_group WHERE id = $1"#, class.id.uuid()) |
| 394 | .execute(&mut *tx) |
| 395 | .await?; |
| 396 | if let Some(year) = guard.year { |
| 397 | sqlx::query!( |
| 398 | r#"UPDATE academic_year |
| 399 | SET class_count = GREATEST(class_count - 1, 0) |
| 400 | WHERE id = $1"#, |
| 401 | year |
| 402 | ) |
| 403 | .execute(&mut *tx) |
| 404 | .await?; |
| 405 | } |
| 406 | Ok(true) |
| 407 | }) |
| 408 | .await |
| 409 | } |
| 410 | |
| 411 | #[cfg(test)] |
| 412 | mod tests { |
| 413 | use super::*; |
| 414 | use sqlx::Row as _; |
| 415 | |
| 416 | use crate::domain::academic_year::{AcademicYear, AcademicYearName}; |
| 417 | |
| 418 | |
| 419 | |
| 420 | async fn a_named_user(db: &Database, username: &str) -> UserId { |
| 421 | |
| 422 | |
| 423 | sqlx::query( |
| 424 | "INSERT INTO app_user (id, username, created_at, role) \ |
| 425 | VALUES ($1, $2, 0, 'teacher') ON CONFLICT DO NOTHING", |
| 426 | ) |
| 427 | .bind(UserId::generate().uuid()) |
| 428 | .bind(username) |
| 429 | .execute(db) |
| 430 | .await |
| 431 | .unwrap(); |
| 432 | let id: uuid::Uuid = sqlx::query("SELECT id FROM app_user WHERE username = $1") |
| 433 | .bind(username) |
| 434 | .fetch_one(db) |
| 435 | .await |
| 436 | .unwrap() |
| 437 | .try_get(0) |
| 438 | .unwrap(); |
| 439 | UserId::from_key(&id.to_string()) |
| 440 | } |
| 441 | |
| 442 | |
| 443 | |
| 444 | async fn a_year(name: &str, db: &Database) -> AcademicYear { |
| 445 | let at = crate::domain::timestamp::Timestamp::from_millis; |
| 446 | crate::db::academic_year::create( |
| 447 | db, |
| 448 | &a_named_user(db, "manager").await, |
| 449 | AcademicYearName::try_new(name).unwrap(), |
| 450 | at(100), |
| 451 | at(200), |
| 452 | Vec::new(), |
| 453 | ) |
| 454 | .await |
| 455 | .unwrap() |
| 456 | } |
| 457 | |
| 458 | async fn class_on(year: Option<AcademicYearId>, db: &Database) -> ClassGroup { |
| 459 | let manager = a_named_user(db, "manager").await; |
| 460 | create( |
| 461 | db, |
| 462 | &manager, |
| 463 | ClassName::try_new("9-A").unwrap(), |
| 464 | GradeLevel::new(9).unwrap(), |
| 465 | year, |
| 466 | None, |
| 467 | ) |
| 468 | .await |
| 469 | .unwrap() |
| 470 | } |
| 471 | |
| 472 | |
| 473 | async fn class_of(teacher: Option<UserId>, db: &Database) -> ClassGroup { |
| 474 | let manager = a_named_user(db, "manager").await; |
| 475 | create( |
| 476 | db, |
| 477 | &manager, |
| 478 | ClassName::try_new("9-A").unwrap(), |
| 479 | GradeLevel::new(9).unwrap(), |
| 480 | None, |
| 481 | teacher, |
| 482 | ) |
| 483 | .await |
| 484 | .unwrap() |
| 485 | } |
| 486 | |
| 487 | |
| 488 | async fn teacher_of(class: &ClassGroupId, db: &Database) -> Option<UserId> { |
| 489 | read(db, class) |
| 490 | .await |
| 491 | .unwrap() |
| 492 | .unwrap() |
| 493 | .get_teacher() |
| 494 | .cloned() |
| 495 | } |
| 496 | |
| 497 | |
| 498 | |
| 499 | |
| 500 | async fn one_i64(db: &Database, sql: String) -> i64 { |
| 501 | sqlx::query(sqlx::AssertSqlSafe(sql)) |
| 502 | .fetch_one(db) |
| 503 | .await |
| 504 | .unwrap() |
| 505 | .try_get::<i64, _>(0) |
| 506 | .unwrap() |
| 507 | } |
| 508 | |
| 509 | |
| 510 | async fn count_on(year: &AcademicYearId, db: &Database) -> i64 { |
| 511 | one_i64( |
| 512 | db, |
| 513 | format!( |
| 514 | "SELECT COALESCE(class_count, 0) FROM academic_year WHERE id = '{}'", |
| 515 | year.uuid() |
| 516 | ), |
| 517 | ) |
| 518 | .await |
| 519 | } |
| 520 | |
| 521 | |
| 522 | async fn row_count(db: &Database, table: &str) -> i64 { |
| 523 | one_i64(db, format!("SELECT count(*) FROM {table}")).await |
| 524 | } |
| 525 | |
| 526 | |
| 527 | |
| 528 | |
| 529 | |
| 530 | #[tokio::test] |
| 531 | async fn the_homeroom_teacher_is_stored_set_cleared_and_left_alone() { |
| 532 | let (db, _leases) = crate::database::init_test_db().await; |
| 533 | let ada = a_named_user(&db, "ada").await; |
| 534 | let boole = a_named_user(&db, "boole").await; |
| 535 | |
| 536 | let bare = class_of(None, &db).await; |
| 537 | assert_eq!(teacher_of(bare.get_id(), &db).await, None); |
| 538 | let held = class_of(Some(ada), &db).await; |
| 539 | assert_eq!(teacher_of(held.get_id(), &db).await, Some(ada)); |
| 540 | |
| 541 | |
| 542 | let renamed = update( |
| 543 | &db, |
| 544 | held, |
| 545 | Some(ClassName::try_new("9-B").unwrap()), |
| 546 | None, |
| 547 | None, |
| 548 | None, |
| 549 | ) |
| 550 | .await |
| 551 | .unwrap(); |
| 552 | assert_eq!(renamed.get_name().as_str(), "9-B"); |
| 553 | assert_eq!(teacher_of(renamed.get_id(), &db).await, Some(ada)); |
| 554 | |
| 555 | let moved = update(&db, renamed, None, None, None, Some(Some(boole))) |
| 556 | .await |
| 557 | .unwrap(); |
| 558 | assert_eq!(teacher_of(moved.get_id(), &db).await, Some(boole)); |
| 559 | |
| 560 | let cleared = update(&db, moved, None, None, None, Some(None)) |
| 561 | .await |
| 562 | .unwrap(); |
| 563 | assert_eq!(teacher_of(cleared.get_id(), &db).await, None); |
| 564 | |
| 565 | |
| 566 | let again = update( |
| 567 | &db, |
| 568 | cleared, |
| 569 | None, |
| 570 | None, |
| 571 | None, |
| 572 | Some(Some(a_named_user(&db, "ada").await)), |
| 573 | ) |
| 574 | .await |
| 575 | .unwrap(); |
| 576 | assert_eq!(again.get_name().as_str(), "9-B"); |
| 577 | |
| 578 | |
| 579 | |
| 580 | sqlx::query("UPDATE class_group SET teacher = NULL WHERE id = $1") |
| 581 | .bind(bare.get_id().uuid()) |
| 582 | .execute(&db) |
| 583 | .await |
| 584 | .unwrap(); |
| 585 | assert_eq!(teacher_of(bare.get_id(), &db).await, None); |
| 586 | } |
| 587 | |
| 588 | |
| 589 | |
| 590 | #[tokio::test] |
| 591 | async fn unassign_everywhere_clears_only_that_users_classes() { |
| 592 | let (db, _leases) = crate::database::init_test_db().await; |
| 593 | let ada = a_named_user(&db, "ada").await; |
| 594 | let boole = a_named_user(&db, "boole").await; |
| 595 | let first = class_of(Some(ada), &db).await; |
| 596 | let second = class_of(Some(ada), &db).await; |
| 597 | let other = class_of(Some(boole), &db).await; |
| 598 | let none = class_of(None, &db).await; |
| 599 | |
| 600 | unassign_everywhere(&db, &ada).await.unwrap(); |
| 601 | for class in [&first, &second] { |
| 602 | assert_eq!( |
| 603 | teacher_of(class.get_id(), &db).await, |
| 604 | None, |
| 605 | "every class the demoted user homeroomed must be cleared" |
| 606 | ); |
| 607 | } |
| 608 | assert_eq!( |
| 609 | teacher_of(other.get_id(), &db).await, |
| 610 | Some(boole), |
| 611 | "…and nobody else's" |
| 612 | ); |
| 613 | assert_eq!(teacher_of(none.get_id(), &db).await, None); |
| 614 | } |
| 615 | |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | #[tokio::test] |
| 622 | async fn a_year_is_deletable_only_once_no_class_links_it() { |
| 623 | let (db, _leases) = crate::database::init_test_db().await; |
| 624 | let year = a_year("2026-2027", &db).await; |
| 625 | |
| 626 | let linked = class_on(Some(*year.get_id()), &db).await; |
| 627 | let patched = class_on(Some(*year.get_id()), &db).await; |
| 628 | assert_eq!( |
| 629 | one_i64( |
| 630 | &db, |
| 631 | "SELECT COALESCE(class_count, 0) FROM academic_year".to_string() |
| 632 | ) |
| 633 | .await, |
| 634 | 2, |
| 635 | "classes must count on class_count, not term_count" |
| 636 | ); |
| 637 | assert_eq!( |
| 638 | one_i64( |
| 639 | &db, |
| 640 | "SELECT COALESCE(term_count, 0) FROM academic_year".to_string() |
| 641 | ) |
| 642 | .await, |
| 643 | 0, |
| 644 | "the terms' counter is seeded from term rows and must stay untouched" |
| 645 | ); |
| 646 | assert!( |
| 647 | !crate::db::academic_year::delete(&db, year.clone()) |
| 648 | .await |
| 649 | .unwrap(), |
| 650 | "two linked classes must refuse the delete" |
| 651 | ); |
| 652 | |
| 653 | update(&db, patched, None, None, Some(None), None) |
| 654 | .await |
| 655 | .unwrap(); |
| 656 | assert!( |
| 657 | !crate::db::academic_year::delete(&db, year.clone()) |
| 658 | .await |
| 659 | .unwrap(), |
| 660 | "one link is still one link" |
| 661 | ); |
| 662 | |
| 663 | assert!(delete(&db, linked).await.unwrap()); |
| 664 | assert!( |
| 665 | crate::db::academic_year::delete(&db, year.clone()) |
| 666 | .await |
| 667 | .unwrap(), |
| 668 | "the last link gone, the year may go" |
| 669 | ); |
| 670 | let again = crate::db::academic_year::delete(&db, year).await; |
| 671 | assert!( |
| 672 | matches!(again, Err(AppError::NotFound)), |
| 673 | "a second delete is a 404, not a refusal: {again:?}" |
| 674 | ); |
| 675 | } |
| 676 | |
| 677 | |
| 678 | |
| 679 | |
| 680 | #[tokio::test] |
| 681 | async fn a_class_with_members_or_courses_refuses_to_delete() { |
| 682 | for field in ["class_member_count", "class_course_count"] { |
| 683 | let (db, _leases) = crate::database::init_test_db().await; |
| 684 | let year = a_year("2026-2027", &db).await; |
| 685 | let class = class_on(Some(*year.get_id()), &db).await; |
| 686 | sqlx::query(sqlx::AssertSqlSafe(format!( |
| 687 | "UPDATE class_group SET {field} = 1 WHERE id = $1" |
| 688 | ))) |
| 689 | .bind(class.get_id().uuid()) |
| 690 | .execute(&db) |
| 691 | .await |
| 692 | .unwrap(); |
| 693 | |
| 694 | assert!( |
| 695 | !delete(&db, class.clone()).await.unwrap(), |
| 696 | "{field} above zero must refuse the delete" |
| 697 | ); |
| 698 | assert!( |
| 699 | read(&db, class.get_id()).await.unwrap().is_some(), |
| 700 | "a refused delete may write nothing" |
| 701 | ); |
| 702 | assert_eq!( |
| 703 | count_on(year.get_id(), &db).await, |
| 704 | 1, |
| 705 | "…the year reference least of all" |
| 706 | ); |
| 707 | |
| 708 | |
| 709 | sqlx::query(sqlx::AssertSqlSafe(format!( |
| 710 | "UPDATE class_group SET {field} = 0 WHERE id = $1" |
| 711 | ))) |
| 712 | .bind(class.get_id().uuid()) |
| 713 | .execute(&db) |
| 714 | .await |
| 715 | .unwrap(); |
| 716 | assert!(delete(&db, class.clone()).await.unwrap()); |
| 717 | assert_eq!(count_on(year.get_id(), &db).await, 0); |
| 718 | let again = delete(&db, class).await; |
| 719 | assert!( |
| 720 | matches!(again, Err(AppError::NotFound)), |
| 721 | "a second delete is a 404, not a refusal: {again:?}" |
| 722 | ); |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | |
| 727 | |
| 728 | |
| 729 | #[tokio::test] |
| 730 | async fn a_refused_create_writes_neither_row_nor_count() { |
| 731 | let (db, _leases) = crate::database::init_test_db().await; |
| 732 | let year = a_year("2026-2027", &db).await; |
| 733 | let id = *year.get_id(); |
| 734 | assert!(crate::db::academic_year::delete(&db, year).await.unwrap()); |
| 735 | |
| 736 | let error = create( |
| 737 | &db, |
| 738 | &a_named_user(&db, "manager").await, |
| 739 | ClassName::try_new("9-A").unwrap(), |
| 740 | GradeLevel::anaokulu(), |
| 741 | Some(id), |
| 742 | None, |
| 743 | ) |
| 744 | .await |
| 745 | .expect_err("a year that is gone must not be linkable"); |
| 746 | assert!(error.to_string().contains("academic year does not exist")); |
| 747 | assert_eq!( |
| 748 | row_count(&db, "class_group").await, |
| 749 | 0, |
| 750 | "a refused create may write no row" |
| 751 | ); |
| 752 | assert_eq!( |
| 753 | row_count(&db, "academic_year").await, |
| 754 | 0, |
| 755 | "…and least of all a count on a year it just brought back" |
| 756 | ); |
| 757 | } |
| 758 | |
| 759 | |
| 760 | |
| 761 | |
| 762 | |
| 763 | |
| 764 | #[tokio::test] |
| 765 | async fn a_class_year_move_moves_the_count_or_neither() { |
| 766 | let (db, _leases) = crate::database::init_test_db().await; |
| 767 | let from = a_year("2026-2027", &db).await; |
| 768 | let to = a_year("2027-2028", &db).await; |
| 769 | let dead = a_year("2028-2029", &db).await; |
| 770 | let dead_id = *dead.get_id(); |
| 771 | assert!(crate::db::academic_year::delete(&db, dead).await.unwrap()); |
| 772 | let class = class_on(Some(*from.get_id()), &db).await; |
| 773 | |
| 774 | let error = update( |
| 775 | &db, |
| 776 | class.clone(), |
| 777 | Some(ClassName::try_new("9-B").unwrap()), |
| 778 | None, |
| 779 | Some(Some(dead_id)), |
| 780 | None, |
| 781 | ) |
| 782 | .await |
| 783 | .expect_err("a year that is gone must not be linkable"); |
| 784 | assert!(error.to_string().contains("academic year does not exist")); |
| 785 | let stored = read(&db, class.get_id()).await.unwrap().unwrap(); |
| 786 | assert_eq!(stored.get_year(), Some(from.get_id()), "the link stays put"); |
| 787 | assert_eq!(stored.get_name().as_str(), "9-A", "…and so does the row"); |
| 788 | assert_eq!( |
| 789 | count_on(from.get_id(), &db).await, |
| 790 | 1, |
| 791 | "the release must roll back with the abort" |
| 792 | ); |
| 793 | |
| 794 | let moved = update(&db, class, None, None, Some(Some(*to.get_id())), None) |
| 795 | .await |
| 796 | .unwrap(); |
| 797 | assert_eq!(moved.get_year(), Some(to.get_id())); |
| 798 | assert_eq!( |
| 799 | count_on(from.get_id(), &db).await, |
| 800 | 0, |
| 801 | "the old year is free" |
| 802 | ); |
| 803 | assert_eq!(count_on(to.get_id(), &db).await, 1, "the new one is not"); |
| 804 | } |
| 805 | |
| 806 | |
| 807 | |
| 808 | |
| 809 | |
| 810 | |
| 811 | |
| 812 | |
| 813 | |
| 814 | |
| 815 | #[tokio::test] |
| 816 | async fn a_stale_class_year_write_is_refused_and_moves_no_count() { |
| 817 | let (db, _leases) = crate::database::init_test_db().await; |
| 818 | let from = a_year("2026-2027", &db).await; |
| 819 | let to = a_year("2027-2028", &db).await; |
| 820 | let other = a_year("2028-2029", &db).await; |
| 821 | let class = class_on(Some(*from.get_id()), &db).await; |
| 822 | let stale = class.clone(); |
| 823 | update(&db, class, None, None, Some(Some(*to.get_id())), None) |
| 824 | .await |
| 825 | .unwrap(); |
| 826 | |
| 827 | |
| 828 | |
| 829 | let error = update( |
| 830 | &db, |
| 831 | stale.clone(), |
| 832 | None, |
| 833 | None, |
| 834 | Some(Some(*other.get_id())), |
| 835 | None, |
| 836 | ) |
| 837 | .await |
| 838 | .expect_err("a mover that read a link it no longer holds must be refused"); |
| 839 | assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); |
| 840 | |
| 841 | let error = update( |
| 842 | &db, |
| 843 | stale.clone(), |
| 844 | None, |
| 845 | None, |
| 846 | Some(Some(*from.get_id())), |
| 847 | None, |
| 848 | ) |
| 849 | .await |
| 850 | .expect_err("re-stating a link someone else moved must be refused"); |
| 851 | assert!(matches!(error, AppError::Conflict(_)), "{error:?}"); |
| 852 | |
| 853 | let stored = read(&db, stale.get_id()).await.unwrap().unwrap(); |
| 854 | assert_eq!(stored.get_year(), Some(to.get_id()), "the winner's link"); |
| 855 | assert_eq!(count_on(from.get_id(), &db).await, 0, "released once"); |
| 856 | assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once"); |
| 857 | assert_eq!(count_on(other.get_id(), &db).await, 0, "never claimed"); |
| 858 | |
| 859 | |
| 860 | let same = update(&db, stored, None, None, Some(Some(*to.get_id())), None) |
| 861 | .await |
| 862 | .expect("re-stating the link the row really holds is not a conflict"); |
| 863 | assert_eq!(same.get_year(), Some(to.get_id())); |
| 864 | assert_eq!(count_on(to.get_id(), &db).await, 1, "still one seat"); |
| 865 | } |
| 866 | |
| 867 | |
| 868 | |
| 869 | |
| 870 | |
| 871 | |
| 872 | #[tokio::test] |
| 873 | async fn a_soft_left_member_does_not_block_the_delete_and_goes_with_it() { |
| 874 | use crate::db::class_pump::{self, Attached}; |
| 875 | |
| 876 | let (db, _leases) = crate::database::init_test_db().await; |
| 877 | let manager = a_named_user(&db, "manager").await; |
| 878 | let class = class_of(None, &db).await; |
| 879 | |
| 880 | |
| 881 | let student = a_named_user(&db, "ada").await; |
| 882 | sqlx::query("UPDATE app_user SET role = 'student' WHERE id = $1") |
| 883 | .bind(student.uuid()) |
| 884 | .execute(&db) |
| 885 | .await |
| 886 | .unwrap(); |
| 887 | assert!(matches!( |
| 888 | class_pump::add_member(&db, class.get_id(), &student, &manager) |
| 889 | .await |
| 890 | .unwrap(), |
| 891 | Attached::Made(_) |
| 892 | )); |
| 893 | |
| 894 | assert_eq!( |
| 895 | class_pump::leave_member(&db, class.get_id(), &student) |
| 896 | .await |
| 897 | .unwrap(), |
| 898 | 1, |
| 899 | "the one live stint is the one the leave ends" |
| 900 | ); |
| 901 | |
| 902 | |
| 903 | assert_eq!( |
| 904 | one_i64( |
| 905 | &db, |
| 906 | format!( |
| 907 | "SELECT class_member_count FROM class_group WHERE id = '{}'", |
| 908 | class.get_id().uuid() |
| 909 | ) |
| 910 | ) |
| 911 | .await, |
| 912 | 0 |
| 913 | ); |
| 914 | assert_eq!(row_count(&db, "class_member").await, 1); |
| 915 | |
| 916 | assert!( |
| 917 | delete(&db, class.clone()).await.unwrap(), |
| 918 | "a soft-left member must not block the delete" |
| 919 | ); |
| 920 | assert_eq!( |
| 921 | row_count(&db, "class_member").await, |
| 922 | 0, |
| 923 | "…and the roster history goes with the şube" |
| 924 | ); |
| 925 | assert!( |
| 926 | matches!(delete(&db, class).await, Err(AppError::NotFound)), |
| 927 | "a second delete is still a 404" |
| 928 | ); |
| 929 | } |
| 930 | } |