forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

persistence.rs1094 lines, 37.4 KiBHistoryRawDownload
1//! Boot-migration tests: seed a real deployment through the API, re-run the
2//! idempotent migration over the same live database — a second boot — and
3//! assert the seeded rows come back intact. The backfill-era machinery these
4//! tests once exercised is gone with the old engine; what remains is the
5//! durability contract: a migration must never disturb data that is already
6//! there.
7
8mod common;
9
10use axum::Router;
11use axum::http::StatusCode;
12use common::{
13 create_subject, enroll, login_as, me_id, select_instance_subject, send, set_role, taught_under,
14};
15use hezarfen_backend::database::Database;
16use hezarfen_backend::module::ModuleSet;
17use hezarfen_backend::rate_limit::RateLimitConfig;
18use hezarfen_backend::state::AppState;
19use hezarfen_backend::tenant::Tenants;
20use hezarfen_backend::{build_router, database};
21use serde_json::json;
22
23/// Re-apply the school schema to the live school database, run the boot's
24/// sweep over every registered school, and hand back a fresh router over the
25/// same deployment — a second boot in every way that matters to these tests.
26async fn reboot(db: &Database, tenants: &Tenants) -> Router {
27 database::migrate_school(db).await.expect("re-migration");
28 tenants.sweep_school_schemas().await;
29 build_router(AppState {
30 db: tenants.control().clone(),
31 tenants: tenants.clone(),
32 files_path: common::files_dir(),
33 cookie_secure: false,
34 rate_limit: RateLimitConfig::unlimited(),
35 chatbot_limit: Default::default(),
36 rag_limit: Default::default(),
37 exam_presence: Default::default(),
38 board_hub: Default::default(),
39 ai: None,
40 metrics: hezarfen_backend::telemetry::Metrics::noop(),
41 })
42}
43
44/// School policy and terms survive a second boot — the settings singleton
45/// (nested band objects included) and a dönem under its academic year both come
46/// back, untouched by the re-applied idempotent migration.
47#[tokio::test]
48async fn settings_and_terms_survive_remigration() {
49 let (app, db, tenants) = common::app_and_tenants().await;
50
51 let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" });
52 send(&app, "POST", "/auth/register", None, Some(creds)).await;
53 set_role(&db, "boss", "manager").await;
54 let login = json!({ "username": "boss", "password": "secret1" });
55 let cookie = send(&app, "POST", "/auth/login", None, Some(login.clone()))
56 .await
57 .cookie
58 .unwrap();
59
60 let res = send(
61 &app,
62 "PATCH",
63 "/settings",
64 Some(&cookie),
65 Some(json!({
66 "exam_kinds": [
67 { "name": "lab", "weight": 2 },
68 { "name": "quiz", "weight": 1 },
69 ],
70 "grade_bands": [{ "min": 0, "label": "F" }, { "min": 50, "label": "P" }],
71 })),
72 )
73 .await;
74 assert_eq!(res.status, StatusCode::OK);
75
76 // A dönem is a slice of an academic year now, so the calendar is minted in
77 // two steps — the year, then the term inside it.
78 let year = common::create_year(&app, &cookie, "2026-2027").await;
79 let term = common::create_term(&app, &cookie, &year, "2026 Fall").await;
80
81 let res = send(
82 &app,
83 "POST",
84 "/courses",
85 Some(&cookie),
86 Some(json!({ "title": "History" })),
87 )
88 .await;
89 assert_eq!(res.status, StatusCode::CREATED);
90
91 // Second boot: migration re-applied over live data.
92 let app = reboot(&db, &tenants).await;
93 let cookie = send(&app, "POST", "/auth/login", None, Some(login))
94 .await
95 .cookie
96 .unwrap();
97
98 let res = send(&app, "GET", "/settings", Some(&cookie), None).await;
99 assert_eq!(res.status, StatusCode::OK);
100 assert_eq!(
101 res.body["exam_kinds"],
102 json!([
103 { "name": "lab", "weight": 2 },
104 { "name": "quiz", "weight": 1 },
105 ])
106 );
107 assert_eq!(res.body["grade_bands"][0]["label"], "P");
108
109 let res = send(&app, "GET", &format!("/terms/{term}"), Some(&cookie), None).await;
110 assert_eq!(res.status, StatusCode::OK);
111 assert_eq!(res.body["name"], "2026 Fall");
112 assert_eq!(res.body["year"], year, "the dönem keeps its academic year");
113
114 let res = send(&app, "GET", "/courses", Some(&cookie), None).await;
115 let courses = common::items(&res.body);
116 assert_eq!(courses.len(), 1);
117 assert_eq!(courses[0]["title"], "History");
118}
119
120/// A weekly appointment series and a booking that carries a full proposal
121/// triple survive the re-applied migration, exact unix-ms stamps and all.
122#[tokio::test]
123async fn appointments_survive_remigration() {
124 /// Far enough ahead to clear `check_not_past` without touching the clock,
125 /// and deliberately not a round number of seconds.
126 const START: i64 = 1_900_000_000_123;
127 const END: i64 = 1_900_000_003_777;
128 const WEEK: i64 = 7 * 24 * 60 * 60 * 1000;
129 const PROPOSED_START: i64 = START + 5_000_001;
130 const PROPOSED_END: i64 = START + 8_000_003;
131
132 let (app, db, tenants) = common::app_and_tenants().await;
133 let teacher_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
134 let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
135 for creds in [&teacher_creds, &student_creds] {
136 assert_eq!(
137 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
138 .await
139 .status,
140 StatusCode::CREATED
141 );
142 }
143 set_role(&db, "ali", "teacher").await;
144 let teacher = send(
145 &app,
146 "POST",
147 "/auth/login",
148 None,
149 Some(json!({ "username": "ali", "password": "secret1" })),
150 )
151 .await
152 .cookie
153 .unwrap();
154 let student = send(
155 &app,
156 "POST",
157 "/auth/login",
158 None,
159 Some(json!({ "username": "ayse", "password": "secret1" })),
160 )
161 .await
162 .cookie
163 .unwrap();
164
165 // A weekly publish: three occurrences sharing one series id and one note.
166 let res = send(
167 &app,
168 "POST",
169 "/appointments/slots",
170 Some(&teacher),
171 Some(json!({
172 "starts_at": START,
173 "ends_at": END,
174 "note": "veli görüşmesi",
175 "repeat_weekly": true,
176 "until": START + 2 * WEEK,
177 })),
178 )
179 .await;
180 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
181 let published = res
182 .body
183 .as_array()
184 .expect("publish returns an array")
185 .clone();
186 assert_eq!(published.len(), 3, "{}", res.body);
187 let slot_id = published[0]["id"].as_str().unwrap().to_string();
188 let series = published[0]["series"].as_str().unwrap().to_string();
189 let slot_created_at = published[0]["created_at"].as_i64().unwrap();
190
191 // Book the first occurrence, counter-propose another time, accept it — the
192 // row then carries every optional column at once.
193 let res = send(
194 &app,
195 "POST",
196 "/appointments",
197 Some(&student),
198 Some(json!({ "slot": slot_id, "reason": "ödev" })),
199 )
200 .await;
201 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
202 let appointment = common::id_of(&res.body);
203 let created_at = res.body["created_at"].as_i64().unwrap();
204 let res = send(
205 &app,
206 "PATCH",
207 &format!("/appointments/{appointment}/reschedule"),
208 Some(&teacher),
209 Some(json!({ "starts_at": PROPOSED_START, "ends_at": PROPOSED_END })),
210 )
211 .await;
212 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
213 let res = send(
214 &app,
215 "PATCH",
216 &format!("/appointments/{appointment}/reschedule/accept"),
217 Some(&student),
218 Some(json!({
219 "proposed_starts_at": PROPOSED_START,
220 "proposed_ends_at": PROPOSED_END,
221 })),
222 )
223 .await;
224 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
225
226 // Second boot: migration re-applied over live data.
227 let app = reboot(&db, &tenants).await;
228 let teacher = send(&app, "POST", "/auth/login", None, Some(teacher_creds))
229 .await
230 .cookie
231 .unwrap();
232 let student = send(&app, "POST", "/auth/login", None, Some(student_creds))
233 .await
234 .cookie
235 .unwrap();
236
237 let res = send(&app, "GET", "/appointments/slots", Some(&teacher), None).await;
238 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
239 assert_eq!(common::total(&res.body), 3, "{}", res.body);
240 let slots = common::items(&res.body);
241 assert_eq!(slots[0]["id"], slot_id.as_str());
242 assert_eq!(slots[0]["starts_at"], START, "exact unix-ms, not rounded");
243 assert_eq!(slots[0]["ends_at"], END);
244 assert_eq!(slots[0]["note"], "veli görüşmesi");
245 assert_eq!(slots[0]["created_at"], slot_created_at);
246 for (week, slot) in slots.iter().enumerate() {
247 assert_eq!(slot["series"], series.as_str(), "one series, all weeks");
248 assert_eq!(slot["starts_at"], START + week as i64 * WEEK);
249 assert_eq!(slot["ends_at"], END + week as i64 * WEEK);
250 }
251
252 let res = send(&app, "GET", "/appointments", Some(&student), None).await;
253 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
254 assert_eq!(common::total(&res.body), 1, "{}", res.body);
255 let booking = &common::items(&res.body)[0];
256 assert_eq!(booking["id"], appointment.as_str());
257 assert_eq!(booking["slot"], slot_id.as_str());
258 assert_eq!(booking["status"], "approved");
259 assert_eq!(booking["reason"], "ödev");
260 assert_eq!(booking["proposed_starts_at"], PROPOSED_START);
261 assert_eq!(booking["proposed_ends_at"], PROPOSED_END);
262 assert_eq!(booking["proposed_by"]["username"], "ali");
263 assert_eq!(booking["decided_by"]["username"], "ayse");
264 // The accepted proposal *is* the meeting's time; the slot's own window lost.
265 assert_eq!(booking["starts_at"], PROPOSED_START);
266 assert_eq!(booking["ends_at"], PROPOSED_END);
267 assert_eq!(booking["teacher"]["username"], "ali");
268 assert_eq!(booking["requester"]["username"], "ayse");
269 assert_eq!(booking["created_at"], created_at);
270}
271
272/// Per-attempt exam history is durable, not just an in-request join: two
273/// sittings' answers and marks (keyed by `seq`) written before a reboot come
274/// back with the right seq afterwards — the seq-1 answer keeps its own text and
275/// both marks survive, oldest first, with seq 2 as the grade-of-record.
276#[tokio::test]
277async fn attempt_history_survives_remigration() {
278 let (app, db, tenants) = common::app_and_tenants().await;
279 let teacher_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
280 let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
281 for creds in [&teacher_creds, &student_creds] {
282 assert_eq!(
283 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
284 .await
285 .status,
286 StatusCode::CREATED
287 );
288 }
289 set_role(&db, "ali", "teacher").await;
290 let teacher = send(
291 &app,
292 "POST",
293 "/auth/login",
294 None,
295 Some(json!({ "username": "ali", "password": "secret1" })),
296 )
297 .await
298 .cookie
299 .unwrap();
300 let student = send(
301 &app,
302 "POST",
303 "/auth/login",
304 None,
305 Some(json!({ "username": "ayse", "password": "secret1" })),
306 )
307 .await
308 .cookie
309 .unwrap();
310 let student_id = me_id(&app, &student).await;
311
312 // The academic anchor is the instance — one catalog course as one şube
313 // teaches it. A manager mints the şube and names the teacher its homeroom
314 // teacher, so the teacher keeps rights over the instance; the catalog course
315 // it forms stays the teacher's own.
316 let mudur = login_as(&app, &db, "mudur", "manager").await;
317 let t = taught_under(&app, &mudur, &teacher, "biology").await;
318 let subject = create_subject(&app, &teacher, &t.course, "cells").await;
319 // The tag check reads the resolved syllabus — the topic rides the
320 // section's own set before any question may carry it.
321 select_instance_subject(&app, &teacher, &t.instance, &subject).await;
322 enroll(&app, &teacher, &t.instance, &student_id).await;
323 let res = send(
324 &app,
325 "POST",
326 &format!("/instances/{}/exams", t.instance),
327 Some(&teacher),
328 Some(json!({ "title": "quiz", "kind": "yazili", "mode": "open",
329 "max_attempts": 2, "term": t.term })),
330 )
331 .await;
332 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
333 let exam = common::id_of(&res.body);
334 let res = send(
335 &app,
336 "POST",
337 &format!("/exams/{exam}/questions"),
338 Some(&teacher),
339 Some(json!({ "subject_id": subject, "text": "Name an organelle.",
340 "kind": "text", "points": 10 })),
341 )
342 .await;
343 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
344 let question = common::id_of(&res.body);
345
346 // Two sittings: distinct answer text + distinct mark on each.
347 for (text, mark) in [("mitochondria", 40), ("chloroplast", 90)] {
348 assert_eq!(
349 send(
350 &app,
351 "POST",
352 &format!("/exams/{exam}/attempt"),
353 Some(&student),
354 None
355 )
356 .await
357 .status,
358 StatusCode::CREATED
359 );
360 let res = send(
361 &app,
362 "POST",
363 &format!("/exams/{exam}/attempt/answers"),
364 Some(&student),
365 Some(json!({ "question_id": question, "text": text })),
366 )
367 .await;
368 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
369 let res = send(
370 &app,
371 "POST",
372 &format!("/exams/{exam}/results"),
373 Some(&teacher),
374 Some(json!({ "mark": mark, "user_id": student_id })),
375 )
376 .await;
377 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
378 send(
379 &app,
380 "POST",
381 &format!("/exams/{exam}/attempt/finish"),
382 Some(&student),
383 None,
384 )
385 .await;
386 }
387
388 // Second boot: migration re-applied over the two sittings' live rows.
389 let app = reboot(&db, &tenants).await;
390 let teacher = send(
391 &app,
392 "POST",
393 "/auth/login",
394 None,
395 Some(json!({ "username": "ali", "password": "secret1" })),
396 )
397 .await
398 .cookie
399 .unwrap();
400
401 let res = send(
402 &app,
403 "GET",
404 &format!("/exams/{exam}/students/{student_id}/attempts"),
405 Some(&teacher),
406 None,
407 )
408 .await;
409 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
410 assert_eq!(res.body, json!([1, 2]), "both sittings survived the reboot");
411
412 // The seq-1 answer kept its own text through the reopen.
413 let res = send(
414 &app,
415 "GET",
416 &format!("/exams/{exam}/students/{student_id}/attempts/1/answers"),
417 Some(&teacher),
418 None,
419 )
420 .await;
421 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
422 assert_eq!(res.body["answers"][0]["text"], "mitochondria");
423
424 // Both marks survive, oldest first; the roster's grade-of-record is seq 2.
425 let res = send(
426 &app,
427 "GET",
428 &format!("/exams/{exam}/students/{student_id}/marks"),
429 Some(&teacher),
430 None,
431 )
432 .await;
433 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
434 let marks: Vec<i64> = res
435 .body
436 .as_array()
437 .unwrap()
438 .iter()
439 .map(|r| r["mark"].as_i64().unwrap())
440 .collect();
441 assert_eq!(
442 marks,
443 vec![40, 90],
444 "both sittings' marks durable, oldest first"
445 );
446 let res = send(
447 &app,
448 "GET",
449 &format!("/exams/{exam}/results"),
450 Some(&teacher),
451 None,
452 )
453 .await;
454 assert_eq!(
455 common::items(&res.body)[0]["mark"],
456 90,
457 "seq 2 is grade-of-record"
458 );
459}
460
461/// A chatbot thread and every turn in it die together: deleting the
462/// thread cascades its `chatbot_message` rows in one transaction, so no
463/// orphan survives a reboot. And the thread is owner-scoped end to end — a
464/// second user reads neither the thread nor its messages.
465#[tokio::test]
466async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
467 use hezarfen_backend::db::{chatbot_message, chatbot_thread};
468 use hezarfen_backend::domain::chatbot_message::{ChatContent, MessageStatus};
469 use hezarfen_backend::domain::user::UserId;
470
471 let (app, db, tenants) = common::app_and_tenants().await;
472 let owner_cookie = common::login(&app, "ali").await;
473 let other_cookie = common::login(&app, "ayse").await;
474 let owner = UserId::from_key(&me_id(&app, &owner_cookie).await);
475 let other = UserId::from_key(&me_id(&app, &other_cookie).await);
476
477 let thread = chatbot_thread::create_capped(&db, &owner, None)
478 .await
479 .expect("create");
480 let id = thread.get_id().clone();
481 let prompt = chatbot_message::append_user(
482 &db,
483 &id,
484 &owner,
485 ChatContent::try_new("selam").expect("content"),
486 )
487 .await
488 .expect("append user");
489 let reply = chatbot_message::append_pending_assistant(&db, &id, &owner)
490 .await
491 .expect("append assistant");
492 assert_eq!(reply.get_status(), MessageStatus::Pending);
493
494 let reply = chatbot_message::complete(
495 &db,
496 reply.get_id(),
497 ChatContent::try_new("aleykum selam").expect("content"),
498 false,
499 )
500 .await
501 .expect("complete");
502 assert_eq!(reply.get_status(), MessageStatus::Complete);
503 assert_eq!(reply.get_content().as_str(), "aleykum selam");
504 assert!(reply.get_completed_at().is_some());
505 assert_eq!(
506 chatbot_message::list_for_thread(&db, &id, None, 0)
507 .await
508 .expect("thread")
509 .0
510 .len(),
511 2
512 );
513
514 // The other user sees nothing of it, by thread or by message.
515 assert!(
516 chatbot_thread::read_for(&db, &id, &other)
517 .await
518 .expect("cross-user thread")
519 .is_none()
520 );
521 assert!(
522 chatbot_message::read_for(&db, prompt.get_id(), &other)
523 .await
524 .expect("cross-user message")
525 .is_none()
526 );
527 assert_eq!(
528 chatbot_thread::count_for_user(&db, &other)
529 .await
530 .expect("count"),
531 0
532 );
533 assert_eq!(
534 chatbot_thread::count_for_user(&db, &owner)
535 .await
536 .expect("count"),
537 1
538 );
539
540 chatbot_thread::delete(&db, thread).await.expect("delete");
541 assert!(
542 chatbot_thread::read_for(&db, &id, &owner)
543 .await
544 .expect("deleted thread")
545 .is_none()
546 );
547 assert_eq!(
548 chatbot_thread::list_for_user(&db, &owner, None, 0)
549 .await
550 .expect("owner's list after delete")
551 .0
552 .len(),
553 0
554 );
555
556 // Second boot: the migration re-applied over the swept store — and no
557 // `chatbot_message` row is left anywhere.
558 let _app = reboot(&db, &tenants).await;
559 let left = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM chatbot_message")
560 .fetch_one(&db)
561 .await
562 .expect("sweep");
563 assert_eq!(left, 0, "no chatbot_message row survived the delete");
564}
565
566/// A meal-slot list whose entries carry no serving minute survives a reboot
567/// and is still patchable afterwards — an omitted optional never wedges the
568/// settings row.
569#[tokio::test]
570async fn settings_slots_without_a_serving_minute_still_patch() {
571 let (app, db, tenants) = common::app_and_tenants().await;
572
573 let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" });
574 send(&app, "POST", "/auth/register", None, Some(creds)).await;
575 set_role(&db, "boss", "manager").await;
576 let login = json!({ "username": "boss", "password": "secret1" });
577
578 let res = send(
579 &app,
580 "PATCH",
581 "/settings",
582 Some(
583 &send(&app, "POST", "/auth/login", None, Some(login.clone()))
584 .await
585 .cookie
586 .unwrap(),
587 ),
588 Some(json!({ "meal_slots": [{ "name": "lunch" }] })),
589 )
590 .await;
591 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
592
593 // Second boot, then read and patch again.
594 let app = reboot(&db, &tenants).await;
595 let cookie = send(&app, "POST", "/auth/login", None, Some(login))
596 .await
597 .cookie
598 .unwrap();
599
600 let res = send(&app, "GET", "/settings", Some(&cookie), None).await;
601 assert_eq!(res.status, StatusCode::OK);
602 let slots = res.body["meal_slots"].as_array().expect("meal slots");
603 assert_eq!(slots.len(), 1, "{}", res.body);
604 assert_eq!(slots[0]["name"], "lunch");
605
606 let res = send(
607 &app,
608 "PATCH",
609 "/settings",
610 Some(&cookie),
611 Some(json!({ "meal_slots": [
612 { "name": "lunch" },
613 { "name": "breakfast" },
614 ] })),
615 )
616 .await;
617 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
618}
619
620/// Fee plans, their installment shape and the charges a placement raised all
621/// come back through a second boot: order, both keys of every installment,
622/// and the statement's arithmetic.
623#[tokio::test]
624async fn fee_plans_and_their_charges_survive_remigration() {
625 let (app, db, tenants) = common::app_and_tenants().await;
626 let manager_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
627 let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
628 for creds in [&manager_creds, &student_creds] {
629 assert_eq!(
630 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
631 .await
632 .status,
633 StatusCode::CREATED
634 );
635 }
636 set_role(&db, "ali", "manager").await;
637 let manager = send(
638 &app,
639 "POST",
640 "/auth/login",
641 None,
642 Some(json!({ "username": "ali", "password": "secret1" })),
643 )
644 .await
645 .cookie
646 .unwrap();
647 let student = send(
648 &app,
649 "POST",
650 "/auth/login",
651 None,
652 Some(json!({ "username": "ayse", "password": "secret1" })),
653 )
654 .await
655 .cookie
656 .unwrap();
657 let student_id = me_id(&app, &student).await;
658
659 let res = send(
660 &app,
661 "POST",
662 "/payments/plans",
663 Some(&manager),
664 Some(json!({
665 "name": "2026-2027 Yearly",
666 "installments": [
667 { "amount_minor": 150_000, "due_at": 1_760_000_000_123_i64 },
668 { "amount_minor": 250_000, "due_at": 1_770_000_000_456_i64 },
669 ],
670 })),
671 )
672 .await;
673 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
674 let plan = res.body["id"].as_str().unwrap().to_string();
675 let res = send(
676 &app,
677 "POST",
678 &format!("/payments/plans/{plan}/assignments"),
679 Some(&manager),
680 Some(json!({ "student_ids": [student_id] })),
681 )
682 .await;
683 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
684
685 let app = reboot(&db, &tenants).await;
686
687 let res = send(
688 &app,
689 "GET",
690 &format!("/payments/plans/{plan}"),
691 Some(&manager),
692 None,
693 )
694 .await;
695 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
696 assert_eq!(res.body["name"], "2026-2027 Yearly");
697 let installments = res.body["installments"].as_array().expect("installments");
698 assert_eq!(installments.len(), 2, "{}", res.body);
699 // Order and both keys of each entry, not merely the count.
700 assert_eq!(installments[0]["amount_minor"], 150_000);
701 assert_eq!(installments[0]["due_at"], 1_760_000_000_123_i64);
702 assert_eq!(installments[1]["amount_minor"], 250_000);
703 assert_eq!(installments[1]["due_at"], 1_770_000_000_456_i64);
704
705 let res = send(
706 &app,
707 "GET",
708 &format!("/payments/statement/{student_id}"),
709 Some(&manager),
710 None,
711 )
712 .await;
713 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
714 assert_eq!(res.body["entries"]["items"].as_array().unwrap().len(), 2);
715 assert_eq!(
716 res.body["balance_minor"], -400_000,
717 "the charges the placement raised are still owed"
718 );
719}
720
721/// Boards, their stroke log across epochs, and the counters the cap reads all
722/// survive a second boot — and the board is still writable afterwards.
723#[tokio::test]
724async fn boards_and_their_strokes_survive_remigration() {
725 let (app, db, tenants) = common::app_and_tenants().await;
726 let creds = json!({ "username": "ali", "password": "secret1" });
727 let cookie = common::login(&app, "ali").await;
728 let veli = common::login(&app, "veli").await;
729 let ali_id = me_id(&app, &cookie).await;
730 let veli_id = me_id(&app, &veli).await;
731
732 let res = send(
733 &app,
734 "POST",
735 "/boards",
736 Some(&cookie),
737 Some(json!({ "title": "Geometri", "participants": [veli_id] })),
738 )
739 .await;
740 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
741 let board = res.body["id"].as_str().unwrap().to_string();
742
743 // Two epochs: two marks cleared away, then one live mark.
744 let draw = async |epoch: i64, payload: &str| {
745 hezarfen_backend::db::board_stroke::append(
746 &db,
747 &hezarfen_backend::domain::board::BoardId::from_key(&board),
748 &hezarfen_backend::domain::user::UserId::from_key(&ali_id),
749 payload,
750 epoch,
751 )
752 .await
753 .expect("append")
754 };
755 draw(0, "{\"p\":[1]}").await;
756 draw(0, "{\"p\":[2]}").await;
757 let res = send(
758 &app,
759 "POST",
760 &format!("/boards/{board}/clear"),
761 Some(&cookie),
762 None,
763 )
764 .await;
765 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
766 draw(1, "{\"p\":[3]}").await;
767
768 // Second boot: the migration re-applied over live board data.
769 let app = reboot(&db, &tenants).await;
770 let cookie = send(&app, "POST", "/auth/login", None, Some(creds))
771 .await
772 .cookie
773 .unwrap();
774
775 let res = send(
776 &app,
777 "GET",
778 &format!("/boards/{board}"),
779 Some(&cookie),
780 None,
781 )
782 .await;
783 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
784 assert_eq!(res.body["title"], "Geometri");
785 assert_eq!(res.body["creator"], ali_id.as_str());
786 assert_eq!(res.body["participants"], json!([veli_id]));
787 assert_eq!(res.body["epoch"], 1, "the epoch survived");
788 assert!(res.body["closed_at"].is_null());
789
790 // The log came back whole: 2 marks, the marker that counted them, 1 live.
791 let res = send(
792 &app,
793 "GET",
794 &format!("/boards/{board}/history"),
795 Some(&cookie),
796 None,
797 )
798 .await;
799 assert_eq!(common::total(&res.body), 4, "{}", res.body);
800 let rows = common::items(&res.body);
801 assert_eq!(rows[0]["payload"], "{\"p\":[1]}");
802 assert_eq!(rows[2]["kind"], "clear");
803 assert_eq!(rows[2]["count"], 2, "the marker kept its count");
804 assert_eq!(rows[3]["payload"], "{\"p\":[3]}");
805 let res = send(
806 &app,
807 "GET",
808 &format!("/boards/{board}/strokes"),
809 Some(&cookie),
810 None,
811 )
812 .await;
813 assert_eq!(
814 common::total(&res.body),
815 1,
816 "the live canvas is the new epoch"
817 );
818
819 // The counters the schema carries but the struct does not, straight from
820 // the rows: a re-migration must not have reset either of them.
821 use sqlx::Row as _;
822 let board_id = hezarfen_backend::domain::board::BoardId::from_key(&board);
823 let row = sqlx::query("SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1")
824 .bind(board_id.uuid())
825 .fetch_one(&db)
826 .await
827 .expect("board row");
828 let epoch_count: i64 = row.try_get(0).unwrap();
829 let total_count: i64 = row.try_get(1).unwrap();
830 let user_id = hezarfen_backend::domain::user::UserId::from_key(&ali_id);
831 let board_count: i64 = sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1")
832 .bind(user_id.uuid())
833 .fetch_one(&db)
834 .await
835 .expect("creator row");
836 assert_eq!(
837 (epoch_count, total_count, board_count),
838 (1, 4, 1),
839 "epoch counter, lifetime counter (three strokes and the clear marker \
840 they paid for) and the creator's board_count"
841 );
842
843 // And the board is still writable after the boot — the counters that came
844 // back are the ones the cap reads.
845 draw(1, "{\"p\":[4]}").await;
846 let res = send(
847 &app,
848 "GET",
849 &format!("/boards/{board}/strokes"),
850 Some(&cookie),
851 None,
852 )
853 .await;
854 assert_eq!(
855 common::total(&res.body),
856 2,
857 "drawing resumed after the boot"
858 );
859}
860
861/// An empty module set is a decision, never a hole to fill: a school created
862/// with nothing switched on still reads an empty list after a second boot of
863/// the control schema.
864#[tokio::test]
865async fn an_empty_module_list_survives_a_second_boot() {
866 let tenants = database::init_test_tenants().await;
867 let bare = hezarfen_backend::tenant::SchoolId::generate();
868 tenants
869 .create(bare, "Bare School", ModuleSet::empty())
870 .await
871 .expect("a school with nothing switched on");
872
873 database::migrate_control(tenants.control())
874 .await
875 .expect("a second boot");
876
877 let stored: i64 = sqlx::query_scalar(
878 "SELECT count(*) FROM school_module sm
879 JOIN school s ON s.id = sm.school
880 WHERE s.id = $1",
881 )
882 .bind(bare.uuid())
883 .fetch_one(tenants.control())
884 .await
885 .expect("read the row back");
886 assert_eq!(
887 stored, 0,
888 "an empty list is a decision, never a hole to fill"
889 );
890}
891
892/// The control migration run twice over schools seeded through the registry
893/// leaves every school row exactly as it stood — idempotence is the whole
894/// contract of a second boot.
895#[tokio::test]
896async fn probe_control_migration_is_idempotent_over_aged_rows() {
897 let tenants = database::init_test_tenants().await;
898 let control = tenants.control().clone();
899
900 // Seed through the registry path itself: three schools, one per module
901 // posture the product distinguishes.
902 let mut narrow = ModuleSet::all();
903 narrow.remove(hezarfen_backend::module::Module::try_from_str("marks").unwrap());
904 for (slug, name, modules) in [
905 ("full", "Full School", ModuleSet::all()),
906 ("empty", "Empty School", ModuleSet::empty()),
907 ("narrow", "Narrow School", narrow),
908 ] {
909 tenants
910 .create(
911 hezarfen_backend::tenant::SchoolId::generate(),
912 name,
913 modules,
914 )
915 .await
916 .unwrap_or_else(|err| panic!("create {slug}: {err}"));
917 }
918
919 let before = school_rows(&control).await;
920 // The harness's demo school plus the three seeded here.
921 assert_eq!(before.len(), 4, "demo plus the three seeded schools");
922
923 database::migrate_control(&control)
924 .await
925 .expect("a second control boot");
926 database::migrate_control(&control)
927 .await
928 .expect("a third control boot");
929
930 let after = school_rows(&control).await;
931 assert_eq!(before, after, "a re-run must not disturb school rows");
932}
933
934/// A boot cut short mid-create leaves a `provisioning` row and no school
935/// database. The next boot finishes it — the row goes `active` and the
936/// school's own doors answer — instead of leaving a school the API advertises
937/// as ready while its database has no tables (every request a `500`).
938///
939/// Both halves of the window are pinned: while the row says `provisioning` its
940/// own doors refuse it (`403`-class, not a `500` from a table-less database),
941/// and after reconciliation the schema is really there.
942#[tokio::test]
943async fn a_half_made_school_is_finished_by_the_next_boot() {
944 let tenants = database::init_test_tenants().await;
945 let control = tenants.control().clone();
946 let id = hezarfen_backend::tenant::SchoolId::generate();
947
948 // Exactly what `Tenants::create` commits before it mints a database: the
949 // registry row (as `provisioning`) and its entitlements.
950 sqlx::query(
951 "INSERT INTO school (id, name, status, created_at) VALUES ($1, $2, $3, $4)",
952 )
953 .bind(id.uuid())
954 .bind("Half Made")
955 .bind("provisioning")
956 .bind(hezarfen_backend::domain::timestamp::Timestamp::now().as_millis())
957 .execute(&control)
958 .await
959 .expect("seed a half-made school row");
960
961 assert!(
962 tenants.get(&id).await.is_err(),
963 "a school that is still being made must not serve"
964 );
965 assert_eq!(status_of(&control, &id.as_str()).await, "provisioning");
966
967 tenants
968 .reconcile_provisioning()
969 .await
970 .expect("the boot finishes what the previous one started");
971
972 assert_eq!(status_of(&control, &id.as_str()).await, "active");
973 let db = tenants
974 .get(&id)
975 .await
976 .expect("the finished school answers");
977 let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user")
978 .fetch_one(&db)
979 .await
980 .expect("the school schema is really there, not merely the row's word");
981 assert_eq!(users, 0, "a finished school starts empty");
982
983 // The database the reconciliation minted is this test's, so it goes with
984 // the test (the harness only drops what `create` minted).
985 tenants
986 .drop(&id)
987 .await
988 .expect("clean up the minted school");
989}
990
991/// A school database that is behind the school-schema head is brought forward
992/// by the next boot — the invariant `sweep_school_schemas` exists for: a
993/// school database is migrated at mint and never again, so one minted before
994/// a migration landed keeps yesterday's tables for good unless the boot
995/// re-applies the schema to it.
996///
997/// The drift is the live deployment's, simulated end to end: a school created
998/// through the normal path (registry row, database, schema at head), then
999/// rolled back to what an older head left behind — the table a later
1000/// migration created is dropped and that migration's tracking row is deleted,
1001/// so sqlx believes it was never applied. Before the sweep that school stayed
1002/// exactly like that: the row is `active`, which is past
1003/// `reconcile_provisioning`, and a re-dial applies no migrations. Its podcast
1004/// routes answered `500` (`relation "podcast_job" does not exist`), which is
1005/// why this asserts on a query over the table and not on the catalogue alone.
1006#[tokio::test]
1007async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() {
1008 let tenants = database::init_test_tenants().await;
1009 let school = tenants
1010 .create(
1011 hezarfen_backend::tenant::SchoolId::generate(),
1012 "Behind The Head",
1013 ModuleSet::all(),
1014 )
1015 .await
1016 .expect("a school through the normal path — its database is at head");
1017
1018 // The drift: exactly what a school minted before the podcast migration
1019 // carries — no table and no tracking row for it.
1020 sqlx::query("DROP TABLE podcast_job")
1021 .execute(&school)
1022 .await
1023 .expect("drop the table a later school migration created");
1024 sqlx::query("DELETE FROM _sqlx_migrations WHERE version = 20260917000003")
1025 .execute(&school)
1026 .await
1027 .expect("forget the migration that created it");
1028 let err = sqlx::query_scalar::<_, i64>("SELECT count(*) FROM podcast_job")
1029 .fetch_one(&school)
1030 .await
1031 .expect_err("a school behind the head cannot read the table yet");
1032 assert!(
1033 err.to_string().contains("does not exist"),
1034 "the drift is the missing relation, not something else: {err}"
1035 );
1036
1037 // The boot: the sweep `database::init` runs before the server serves.
1038 tenants.sweep_school_schemas().await;
1039
1040 let jobs: i64 = sqlx::query_scalar("SELECT count(*) FROM podcast_job")
1041 .fetch_one(&school)
1042 .await
1043 .expect("the boot swept the school up to the schema head");
1044 assert_eq!(jobs, 0, "the re-created table starts empty");
1045
1046 // And the pending migration is recorded as applied, so the next boot's
1047 // sweep is a no-op rather than a re-run.
1048 let applied: i64 =
1049 sqlx::query_scalar("SELECT count(*) FROM _sqlx_migrations WHERE version = 20260917000003")
1050 .fetch_one(&school)
1051 .await
1052 .expect("the tracking table");
1053 assert_eq!(
1054 applied, 1,
1055 "the swept migration is recorded, keeping the next boot a no-op"
1056 );
1057}
1058
1059/// One school's stored status, straight off the registry row.
1060async fn status_of(control: &Database, school: &str) -> String {
1061 let id = uuid::Uuid::parse_str(school).expect("school id is a uuid");
1062 sqlx::query_scalar("SELECT status FROM school WHERE id = $1")
1063 .bind(id)
1064 .fetch_one(control)
1065 .await
1066 .unwrap()
1067}
1068
1069/// Every school row as `(slug, name, status, modules)`, in slug order — the
1070/// modules aggregated off the `school_module` child table, as every read path
1071/// assembles them.
1072async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec<String>)> {
1073 use sqlx::Row as _;
1074 sqlx::query(
1075 "SELECT s.id::text, s.name, s.status,
1076 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}')
1077 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
1078 GROUP BY s.id
1079 ORDER BY s.id",
1080 )
1081 .fetch_all(control)
1082 .await
1083 .unwrap()
1084 .into_iter()
1085 .map(|row| {
1086 (
1087 row.try_get::<String, _>(0).unwrap(),
1088 row.try_get::<String, _>(1).unwrap(),
1089 row.try_get::<String, _>(2).unwrap(),
1090 row.try_get::<Vec<String>, _>(3).unwrap(),
1091 )
1092 })
1093 .collect()
1094}