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.rs210 lines, 8.6 KiBHistoryRawDownload
1//! The `fee_plan` table: the create, the reads, and the guarded edit and
2//! delete. Both guards are conditional single-record writes on the plan's own
3//! refcount (`assignment_count`) — the WHERE clause *is* the assigned-plan
4//! freeze rule — so they live here whole. The web-facing doors are
5//! [`crate::service::fee_plan`].
6//!
7//! Postgres replaces the old process lock with the row itself: the assign's
8//! claim (`UPDATE fee_plan SET assignment_count = …` in
9//! [`crate::db::fee_plan_assignment::create`]) and the guarded edit/delete
10//! below all rewrite this one row, so they take its row lock and re-check
11//! their condition against the committed winner — an assign racing an edit
12//! either claims first (the edit is refused) or claims after (and bills the
13//! edited plan, which it re-reads). No window, no mutex.
14
15use crate::database::Database;
16use crate::db::page::PagedList;
17use crate::domain::fee_plan::{
18 FeePlan, FeePlanId, FeePlanName, Installment, validate_installments,
19};
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::UserId;
22use crate::error::AppError;
23
24pub async fn create(
25 db: &Database,
26 name: FeePlanName,
27 installments: Vec<Installment>,
28 created_by: &UserId,
29) -> Result<FeePlan, AppError> {
30 validate_installments(&installments)?;
31 let installments = serde_json::to_value(&installments)
32 .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?;
33 let id = FeePlanId::generate();
34 let created_at = Timestamp::now();
35 sqlx::query_as!(
36 FeePlan,
37 "INSERT INTO fee_plan (id, name, installments, created_by, created_at) \
38 VALUES ($1, $2, $3, $4, $5) \
39 RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
40 id.uuid(),
41 name.as_str(),
42 installments,
43 created_by.uuid(),
44 created_at.as_millis(),
45 )
46 .fetch_one(db)
47 .await
48 .map_err(Into::into)
49}
50
51pub async fn read(db: &Database, id: &FeePlanId) -> Result<Option<FeePlan>, AppError> {
52 sqlx::query_as!(
53 FeePlan,
54 "SELECT id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"
55 FROM fee_plan WHERE id = $1",
56 id.uuid(),
57 )
58 .fetch_optional(db)
59 .await
60 .map_err(Into::into)
61}
62
63/// Every plan, newest first — a school runs a handful.
64pub async fn list_all(
65 db: &Database,
66 limit: Option<i64>,
67 offset: i64,
68) -> Result<(Vec<FeePlan>, i64), AppError> {
69 PagedList::new("fee_plan", "ORDER BY created_at DESC, id DESC")
70 .run(limit, offset, db)
71 .await
72}
73
74/// Write only the fields the PATCH carried — `None` means the request
75/// omitted it, so the column is left alone (`COALESCE` keeps the stored
76/// value) rather than re-stated from the snapshot this struct was read into.
77/// Zero rows = refused, nothing was written: somebody is already on the plan.
78///
79/// Editing a plan never moves money: charges are frozen copies of the
80/// installments as they stood when the plan was assigned. That is exactly
81/// why an assigned plan may not be edited at all — the plan and the charges
82/// raised from it would tell different stories. The roster is the plan's own
83/// `assignment_count` refcount, claimed in the same statement as the
84/// assignment row ([`crate::db::fee_plan_assignment::create`]), so the check
85/// and the write are one conditional `UPDATE` on one record: an assign
86/// racing this either claims first (and the edit is refused) or claims
87/// after (and bills the edited plan, which it re-reads). A
88/// `SELECT`-then-write could be, and was, stepped over in the gap between
89/// the two.
90///
91/// A request that carried no field at all is answered before the guarded
92/// statement: it writes nothing (and must not be refused as "assigned"),
93/// so the row is simply read back.
94pub async fn update(
95 db: &Database,
96 plan: FeePlan,
97 name: Option<FeePlanName>,
98 installments: Option<Vec<Installment>>,
99) -> Result<FeePlan, AppError> {
100 if let Some(installments) = &installments {
101 validate_installments(installments)?;
102 }
103 if name.is_none() && installments.is_none() {
104 // A PATCH asking for no change writes nothing; the row (or its 404)
105 // is the whole answer, assigned or not.
106 return read(db, &plan.id).await?.ok_or(AppError::NotFound);
107 }
108 let installments = installments
109 .as_ref()
110 .map(serde_json::to_value)
111 .transpose()
112 .map_err(|e| AppError::Internal(format!("fee plan encode: {e}")))?;
113 let edited = sqlx::query_as!(
114 FeePlan,
115 "UPDATE fee_plan \
116 SET name = COALESCE($2, name), installments = COALESCE($3, installments) \
117 WHERE id = $1 AND assignment_count = 0 \
118 RETURNING id AS \"id: FeePlanId\", name AS \"name: FeePlanName\", installments AS \"installments: sqlx::types::Json<Vec<Installment>>\", created_by AS \"created_by: UserId\", created_at AS \"created_at: Timestamp\"",
119 plan.id.uuid(),
120 name.map(|n| n.as_str().to_string()),
121 installments,
122 )
123 .fetch_optional(db)
124 .await?;
125 // Still assigned or already gone: the guarded `UPDATE` cannot tell those
126 // apart (zero rows covers both), so — exactly as [`delete`] does — only
127 // the refusal path pays for the read that can. A plan deleted in the
128 // window since the handler read it must not be refused as "assigned": it
129 // never was.
130 match edited {
131 Some(plan) => Ok(plan),
132 None => match read(db, &plan.id).await? {
133 Some(_) => Err(AppError::Conflict("an assigned plan cannot be edited")),
134 None => Err(AppError::NotFound),
135 },
136 }
137}
138
139/// Delete the plan, but only while nobody is on it. `false` = refused,
140/// nothing was written; `Err(NotFound)` keeps the answer a concurrent
141/// *delete* gives. Same one-record guard as [`update`], and the
142/// same reason — the charges an assignment raised name this plan, and a
143/// school's financial history keeps its references.
144///
145/// A single guarded statement needs no retry loop: the guard rewrites the
146/// plan row itself, so it contends with an assign's claim on that row's lock
147/// and whichever version lands, the loser re-evaluated against the winner's
148/// committed state. Nothing was written on a loss, so there is nothing to
149/// unwind.
150pub async fn delete(db: &Database, plan: FeePlan) -> Result<bool, AppError> {
151 let deleted = sqlx::query!(
152 "DELETE FROM fee_plan WHERE id = $1 AND assignment_count = 0 RETURNING id",
153 plan.id.uuid(),
154 )
155 .fetch_optional(db)
156 .await?;
157 if deleted.is_some() {
158 return Ok(true);
159 }
160 // Still assigned or already gone: the one statement cannot tell those
161 // apart, and only the refusal path pays for the read that can.
162 match read(db, &plan.id).await? {
163 Some(_) => Ok(false),
164 None => Err(AppError::NotFound),
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171 use crate::domain::payment_ledger::LedgerAmount;
172
173 /// The embedded-object DDL (`installments.*.amount_minor`) proved against
174 /// the engine: SCHEMAFULL rejects any nested key it was not told about, so
175 /// a plan that writes and reads back unchanged is what says the declared
176 /// shape and the stored one agree. A past due date is legal on purpose.
177 #[tokio::test]
178 async fn installments_survive_a_round_trip_through_the_schema() {
179 let (db, _leases) = crate::database::init_test_db().await;
180 let manager = crate::db::class_member::tests::fixture_user(&db, "fee-manager").await;
181 let installments = vec![
182 Installment::new(
183 LedgerAmount::try_new(150_000).unwrap(),
184 Timestamp::from_millis(1_000),
185 ),
186 Installment::new(
187 LedgerAmount::try_new(250_000).unwrap(),
188 Timestamp::from_millis(2_000),
189 ),
190 ];
191 let plan = create(
192 &db,
193 FeePlanName::try_new("Yearly").unwrap(),
194 installments.clone(),
195 &manager,
196 )
197 .await
198 .unwrap();
199
200 let stored = read(&db, plan.get_id()).await.unwrap().unwrap();
201 assert_eq!(stored.get_installments(), installments.as_slice());
202 assert_eq!(stored.get_name().as_str(), "Yearly");
203
204 // And a PATCH of the array lands whole.
205 let edited = update(&db, stored, None, Some(vec![installments[0].clone()]))
206 .await
207 .unwrap();
208 assert_eq!(edited.get_installments().len(), 1);
209 }
210}