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

fee_plan_assignment.rs127 lines, 4.8 KiBHistoryRawDownload
1//! The `fee_plan_assignment` table: the claim that places a student on a plan
2//! (and freezes the plan), plus the reads over placements. The billing the
3//! claim triggers lives in [`crate::service::fee_plan_assignment::assign`];
4//! the ledger appends in [`crate::db::payment_ledger`].
5
6use crate::database::Database;
7use crate::db::cap::{self, Claimed};
8use crate::db::page::PagedList;
9use crate::domain::fee_plan::FeePlanId;
10use crate::domain::fee_plan_assignment::{FeePlanAssignment, FeePlanAssignmentId};
11use crate::domain::timestamp::Timestamp;
12use crate::domain::user::UserId;
13use crate::error::AppError;
14
15pub async fn read(
16 db: &Database,
17 id: &FeePlanAssignmentId,
18) -> Result<Option<FeePlanAssignment>, AppError> {
19 sqlx::query_as!(
20 FeePlanAssignment,
21 "SELECT plan AS \"plan: FeePlanId\", student AS \"student: UserId\", assigned_by AS \"assigned_by: UserId\", created_at AS \"created_at: Timestamp\"
22 FROM fee_plan_assignment WHERE plan = $1 AND student = $2",
23 id.plan.uuid(),
24 id.student.uuid(),
25 )
26 .fetch_optional(db)
27 .await
28 .map_err(Into::into)
29}
30
31/// Place one (plan, student) assignment and claim the plan's assignment
32/// refcount in the **same statement** — that increment is what makes the plan
33/// un-editable and un-deletable ([`crate::db::fee_plan::update`]/[`delete`]),
34/// and it has to be indivisible from the row it counts, or an edit could slip
35/// between the two. The claim recipe ([`crate::db::cap`]'s
36/// claim-and-create): a conditional `UPDATE` on the plan row seats the count,
37/// the `INSERT` rides `WHERE EXISTS` on that seat, and one statement decides.
38///
39/// The verdict maps as the guard layer promises: 23505 on
40/// `fee_plan_assignment_plan` → [`Claimed::Duplicate`] (someone assigned this
41/// pair first; their row is the answer); zero rows → [`Claimed::Full`] (the
42/// counter is uncapped, so the only miss is a plan a concurrent delete
43/// already removed); one row → [`Claimed::Made`].
44pub(crate) async fn create(
45 db: &Database,
46 plan: &FeePlanId,
47 student: &UserId,
48 assigned_by: &UserId,
49 created_at: Timestamp,
50) -> Result<Claimed<FeePlanAssignment>, AppError> {
51 let created = sqlx::query_as!(
52 FeePlanAssignment,
53 // The seat bump and the row land together or not at all: a refused
54 // insert takes its own seat bump back.
55 r#"WITH seat AS (
56 UPDATE fee_plan SET assignment_count = assignment_count + 1
57 WHERE id = $1 AND assignment_count < $2
58 RETURNING 1)
59 INSERT INTO fee_plan_assignment (plan, student, assigned_by, created_at)
60 SELECT $3, $4, $5, $6 WHERE EXISTS (SELECT 1 FROM seat)
61 RETURNING plan AS "plan: FeePlanId", student AS "student: UserId", assigned_by AS "assigned_by: UserId", created_at AS "created_at: Timestamp""#,
62 plan.uuid(),
63 cap::UNLIMITED,
64 plan.uuid(),
65 student.uuid(),
66 assigned_by.uuid(),
67 created_at.as_millis(),
68 )
69 .fetch_optional(db)
70 .await;
71 // Read the verdict off the *error* before the row count: a duplicate is
72 // the other writer's win, not a full house.
73 match created {
74 Ok(Some(row)) => Ok(Claimed::Made(row)),
75 Ok(None) => Ok(Claimed::Full),
76 Err(e) if crate::database::unique_violation(&e) == Some("fee_plan_assignment_plan") => {
77 Ok(Claimed::Duplicate)
78 }
79 Err(e) => Err(e.into()),
80 }
81}
82
83/// Who is on this plan, newest first.
84pub async fn list_for_plan(
85 db: &Database,
86 plan: &FeePlanId,
87 limit: Option<i64>,
88 offset: i64,
89) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
90 PagedList::new(
91 "fee_plan_assignment WHERE plan = $1",
92 "ORDER BY created_at DESC, plan DESC, student DESC",
93 )
94 .bind(plan.uuid())
95 .run(limit, offset, db)
96 .await
97}
98
99/// Is anybody on this plan? A scan, and no longer a guard: the edit and
100/// delete guards read the plan's own refcount, which no concurrent assign
101/// can be behind. Kept because a *test* asserting the rows and the counter
102/// agree is the only thing that would catch the counter drifting.
103pub async fn exists_for_plan(db: &Database, plan: &FeePlanId) -> Result<bool, AppError> {
104 let row = sqlx::query!(
105 "SELECT EXISTS (SELECT 1 FROM fee_plan_assignment WHERE plan = $1) AS \"exists!\"",
106 plan.uuid()
107 )
108 .fetch_one(db)
109 .await?;
110 Ok(row.exists)
111}
112
113/// Which plans a student is on — one student may hold several.
114pub async fn list_for_student(
115 db: &Database,
116 student: &UserId,
117 limit: Option<i64>,
118 offset: i64,
119) -> Result<(Vec<FeePlanAssignment>, i64), AppError> {
120 PagedList::new(
121 "fee_plan_assignment WHERE student = $1",
122 "ORDER BY created_at DESC, plan DESC, student DESC",
123 )
124 .bind(student.uuid())
125 .run(limit, offset, db)
126 .await
127}