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.rs180 lines, 5.7 KiBHistoryRawDownload
1//! A school fee plan: a name and the installments it is paid in. Managers
2//! write them; assigning one to a student is what turns it into money owed
3//! (see [`crate::domain::fee_plan_assignment`]).
4//!
5//! The installments are **embedded** on the plan row rather than child rows:
6//! a charge line copies the amount and due date it was assigned at, so the
7//! installment is a template, never a thing that has to be joined back to.
8//! The embedded list rides a `JSONB` column in stored order.
9//!
10//! Due dates may be in the **past**: a school adopting the app mid-year
11//! legitimately assigns a plan whose first installments were already due, so
12//! the no-past rule that guards exams, lessons and events deliberately does not
13//! apply here.
14
15use sqlx::types::Json;
16
17use crate::constant::{MAX_FEE_PLAN_INSTALLMENTS, MAX_FEE_PLAN_NAME_LEN};
18use crate::domain::monotonic_id::next_uuid;
19use crate::domain::payment_ledger::LedgerAmount;
20use crate::domain::timestamp::Timestamp;
21use crate::domain::user::UserId;
22use crate::error::ValidationError;
23use crate::validate::validate_required;
24
25#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
26#[sqlx(transparent)]
27pub struct FeePlanId(uuid::Uuid);
28
29impl FeePlanId {
30 /// A write-ordered id: plan listings read newest first.
31 pub fn generate() -> Self {
32 Self(next_uuid())
33 }
34
35 /// The inner uuid, for runtime-checked binds (Param/QueryBuilder) that
36 /// cannot take the newtype. Static `query!` binds take `self` directly.
37 pub fn uuid(&self) -> uuid::Uuid {
38 self.0
39 }
40
41 /// Parses a wire key. A key that is not a UUID parses as the nil UUID,
42 /// which matches no row.
43 pub fn from_key(key: &str) -> Self {
44 Self(uuid::Uuid::parse_str(key).unwrap_or(uuid::Uuid::nil()))
45 }
46
47 pub fn key(&self) -> String {
48 self.0.to_string()
49 }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
53#[sqlx(transparent)]
54pub struct FeePlanName(String);
55
56impl FeePlanName {
57 pub fn try_new(value: &str) -> Result<Self, ValidationError> {
58 let value = value.trim();
59 validate_required("name", value, MAX_FEE_PLAN_NAME_LEN)?;
60 Ok(Self(value.to_string()))
61 }
62
63 pub fn as_str(&self) -> &str {
64 &self.0
65 }
66}
67
68/// One instalment of a plan: what is owed, and when it falls due. Both fields
69/// are required, so the stored JSON shape always matches the written one.
70#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
71pub struct Installment {
72 amount_minor: LedgerAmount,
73 due_at: Timestamp,
74}
75
76impl Installment {
77 pub fn new(amount_minor: LedgerAmount, due_at: Timestamp) -> Self {
78 Self {
79 amount_minor,
80 due_at,
81 }
82 }
83
84 pub fn get_amount_minor(&self) -> LedgerAmount {
85 self.amount_minor
86 }
87
88 pub fn get_due_at(&self) -> Timestamp {
89 self.due_at
90 }
91}
92
93/// A plan is at least one installment and at most [`MAX_FEE_PLAN_INSTALLMENTS`]
94/// — an empty plan owes nothing and would assign nothing, and the ceiling is
95/// what bounds how many ledger lines one assignment may append.
96pub fn validate_installments(installments: &[Installment]) -> Result<(), ValidationError> {
97 if installments.is_empty() || installments.len() > MAX_FEE_PLAN_INSTALLMENTS {
98 return Err(ValidationError::Invalid {
99 field: "installments",
100 reason: "a plan must carry 1 to 60 installments",
101 });
102 }
103 Ok(())
104}
105
106#[derive(Debug, Clone, sqlx::FromRow)]
107pub struct FeePlan {
108 pub(crate) id: FeePlanId,
109 pub(crate) name: FeePlanName,
110 pub(crate) installments: Json<Vec<Installment>>,
111 pub(crate) created_by: UserId,
112 pub(crate) created_at: Timestamp,
113}
114
115impl FeePlan {
116 pub fn get_id(&self) -> &FeePlanId {
117 &self.id
118 }
119
120 pub fn get_name(&self) -> &FeePlanName {
121 &self.name
122 }
123
124 pub fn get_installments(&self) -> &[Installment] {
125 &self.installments
126 }
127
128 pub fn get_created_by(&self) -> &UserId {
129 &self.created_by
130 }
131
132 pub fn get_created_at(&self) -> Timestamp {
133 self.created_at
134 }
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn name_is_required_trimmed_and_bounded() {
143 assert_eq!(
144 FeePlanName::try_new(" Yearly ").unwrap().as_str(),
145 "Yearly"
146 );
147 assert!(FeePlanName::try_new("").is_err());
148 assert!(FeePlanName::try_new(" ").is_err());
149 assert!(FeePlanName::try_new(&"x".repeat(MAX_FEE_PLAN_NAME_LEN + 1)).is_err());
150 }
151
152 #[test]
153 fn a_plan_carries_between_one_and_sixty_installments() {
154 let one = Installment::new(
155 LedgerAmount::try_new(100).unwrap(),
156 Timestamp::from_millis(1),
157 );
158 assert!(validate_installments(&[]).is_err());
159 assert!(validate_installments(std::slice::from_ref(&one)).is_ok());
160 assert!(validate_installments(&vec![one.clone(); MAX_FEE_PLAN_INSTALLMENTS]).is_ok());
161 assert!(validate_installments(&vec![one; MAX_FEE_PLAN_INSTALLMENTS + 1]).is_err());
162 }
163
164 /// The installments ride the row as JSON, so the storage contract is that
165 /// an installment round-trips through `serde_json` unchanged — the amount
166 /// stays an integer minor-unit count and the due date a bare millisecond
167 /// number.
168 #[test]
169 fn an_installment_survives_the_json_round_trip() {
170 let one = Installment::new(
171 LedgerAmount::try_new(12_345).unwrap(),
172 Timestamp::from_millis(1_700_000_000_000),
173 );
174 let json = serde_json::to_value(&one).unwrap();
175 assert_eq!(json["amount_minor"], serde_json::json!(12_345));
176 assert_eq!(json["due_at"], serde_json::json!(1_700_000_000_000i64));
177 let back: Installment = serde_json::from_value(json).unwrap();
178 assert_eq!(back, one);
179 }
180}