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

payments.rs1183 lines, 47.6 KiBHistoryRawDownload
1//! School fees: the plans a manager writes, the students they are placed on,
2//! and the append-only ledger the placement bills into.
3//!
4//! Every write here is manager+ — money is school administration, and a teacher
5//! has no business in it. The read gate is deliberately *narrower* than the
6//! per-student reports elsewhere
7//! ([`crate::service::parent_link::ensure_can_observe`]): a student sees
8//! their own record, a parent a linked student's, manager+ everyone's, and a
9//! teacher nothing at all.
10//!
11//! No route edits or deletes a ledger line, and none exists to write: a mistake
12//! is corrected by appending its opposite. Balances and statements are folded
13//! from the lines on every read and stored nowhere.
14
15use std::collections::HashMap;
16
17use crate::web::tenant_state::State;
18use axum::Json;
19use axum::extract::{Path, Query};
20use axum::http::StatusCode;
21use serde::{Deserialize, Serialize};
22use utoipa::ToSchema;
23use utoipa_axum::router::OpenApiRouter;
24use utoipa_axum::routes;
25
26use crate::database::Database;
27use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment};
28use crate::domain::payment_ledger::{
29 LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind,
30 PaymentRequestKey,
31};
32use crate::domain::role::Role;
33use crate::domain::timestamp::Timestamp;
34use crate::domain::user::{User, UserId};
35use crate::error::{AppError, ErrorResponse, ValidationError};
36use crate::service;
37use crate::state::AppState;
38
39use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map};
40
41pub fn routes() -> OpenApiRouter<AppState> {
42 OpenApiRouter::new()
43 .routes(routes!(create_plan, list_plans))
44 .routes(routes!(get_plan, update_plan, delete_plan))
45 .routes(routes!(assign_plan, list_plan_assignments))
46 .routes(routes!(record_payment))
47 .routes(routes!(record_refund))
48 .routes(routes!(record_reversal))
49 .routes(routes!(user_ledger))
50 .routes(routes!(my_statement))
51 .routes(routes!(user_statement))
52 .routes(routes!(my_balance))
53 .routes(routes!(user_balance))
54}
55
56// ---- fee plans --------------------------------------------------------------
57
58/// One installment as a client sends it. Both fields are required: a plan is a
59/// schedule, and an installment with no date is not part of one.
60#[derive(Debug, Deserialize, ToSchema)]
61struct InstallmentBody {
62 /// What this installment bills, **minor units**, positive. Integer
63 /// only: this API never speaks decimals or floats about money.
64 #[schema(minimum = 1, maximum = 10000000, example = 150000_i64)]
65 amount_minor: i64,
66 /// When it falls due, unix milliseconds. **May be in the past** — a school
67 /// adopting the app mid-year assigns plans whose first installments were
68 /// already due. Negative is a `400`: that is not an instant.
69 #[schema(minimum = 0, example = 1_760_000_000_000_i64)]
70 due_at: i64,
71}
72
73impl InstallmentBody {
74 fn into_domain(self) -> Result<Installment, AppError> {
75 // A past due date is legal on purpose; a *negative* one is not an
76 // instant at all, and it would leave the charge it bills permanently
77 // `overdue` with no date a client could have meant.
78 if self.due_at < 0 {
79 return Err(AppError::Validation(ValidationError::Invalid {
80 field: "due_at",
81 reason: "must not be negative",
82 }));
83 }
84 Ok(Installment::new(
85 LedgerAmount::try_new(self.amount_minor)?,
86 Timestamp::from_millis(self.due_at),
87 ))
88 }
89
90 fn list(body: Vec<Self>) -> Result<Vec<Installment>, AppError> {
91 body.into_iter().map(Self::into_domain).collect()
92 }
93}
94
95#[derive(Deserialize, ToSchema)]
96struct CreateFeePlan {
97 #[schema(example = "2026-2027 Yearly", max_length = 120)]
98 name: String,
99 /// The schedule, 1 to 60 entries. Assigning the plan bills every one of
100 /// them at once, so this is what a student ends up owing.
101 #[schema(min_items = 1, max_items = 60)]
102 installments: Vec<InstallmentBody>,
103}
104
105#[derive(Deserialize, ToSchema)]
106struct UpdateFeePlan {
107 #[schema(max_length = 120)]
108 name: Option<String>,
109 /// Replaces the whole schedule. Refused (`409`) once anyone is on the plan
110 /// — their charges are frozen copies, so an edit would only make the plan
111 /// and the money disagree.
112 #[schema(min_items = 1, max_items = 60)]
113 installments: Option<Vec<InstallmentBody>>,
114}
115
116#[derive(Serialize, ToSchema)]
117struct InstallmentResponse {
118 /// Minor units.
119 amount_minor: i64,
120 due_at: i64,
121}
122
123#[derive(Serialize, ToSchema)]
124struct FeePlanResponse {
125 id: String,
126 name: String,
127 installments: Vec<InstallmentResponse>,
128 created_by: PersonRef,
129 created_at: i64,
130}
131
132impl FeePlanResponse {
133 fn new(plan: &FeePlan, people: &HashMap<String, PersonRef>) -> Self {
134 Self {
135 id: plan.get_id().key().to_string(),
136 name: plan.get_name().as_str().to_string(),
137 installments: plan
138 .get_installments()
139 .iter()
140 .map(|installment| InstallmentResponse {
141 amount_minor: installment.get_amount_minor().as_minor(),
142 due_at: installment.get_due_at().as_millis(),
143 })
144 .collect(),
145 created_by: PersonRef::resolve(people, plan.get_created_by()),
146 created_at: plan.get_created_at().as_millis(),
147 }
148 }
149}
150
151/// Join the authors onto a page of plans — one query for the whole page.
152async fn plan_responses(
153 plans: &[FeePlan],
154 db: &Database,
155) -> Result<Vec<FeePlanResponse>, AppError> {
156 let people = person_map(plans.iter().map(|plan| *plan.get_created_by()), db).await?;
157 Ok(plans
158 .iter()
159 .map(|plan| FeePlanResponse::new(plan, &people))
160 .collect())
161}
162
163async fn require_plan(id: &str, db: &Database) -> Result<FeePlan, AppError> {
164 service::fee_plan::read(db, &FeePlanId::from_key(id))
165 .await?
166 .ok_or(AppError::NotFound)
167}
168
169/// Write a fee plan: a name and the installments it is paid in. Creating one
170/// bills nobody — assigning it does.
171#[utoipa::path(
172 post,
173 path = "/plans",
174 tag = "payments",
175 security(("session_cookie" = [])),
176 request_body = CreateFeePlan,
177 responses(
178 (status = 201, description = "Plan created", body = FeePlanResponse),
179 (status = 400, description = "Invalid name, amount, due date, or installment count", body = ErrorResponse),
180 (status = 401, description = "Not authenticated", body = ErrorResponse),
181 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
182 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
183 ),
184)]
185async fn create_plan(
186 State(st): State<AppState>,
187 RequireManager(manager): RequireManager,
188 Json(req): Json<CreateFeePlan>,
189) -> Result<(StatusCode, Json<FeePlanResponse>), AppError> {
190 let plan = service::fee_plan::create(
191 &st.db,
192 FeePlanName::try_new(&req.name)?,
193 InstallmentBody::list(req.installments)?,
194 manager.get_id(),
195 )
196 .await?;
197 let people = PersonRef::map_of(&[&manager]);
198 Ok((
199 StatusCode::CREATED,
200 Json(FeePlanResponse::new(&plan, &people)),
201 ))
202}
203
204/// Every fee plan, newest first. Paged via `?limit=&offset=` (omit `limit` for
205/// all of them); returns a `{items, total, limit, offset}` envelope.
206#[utoipa::path(
207 get,
208 path = "/plans",
209 tag = "payments",
210 security(("session_cookie" = [])),
211 params(PageParams),
212 responses(
213 (status = 200, description = "A page of plans (all of them when unpaged)", body = Page<FeePlanResponse>),
214 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
215 (status = 401, description = "Not authenticated", body = ErrorResponse),
216 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
217 ),
218)]
219async fn list_plans(
220 State(st): State<AppState>,
221 RequireManager(_user): RequireManager,
222 Query(page): Query<PageParams>,
223) -> Result<Json<Page<FeePlanResponse>>, AppError> {
224 let (limit, offset) = page.resolve()?;
225 let (rows, total) = service::fee_plan::list_all(&st.db, limit, offset).await?;
226 let items = plan_responses(&rows, &st.db).await?;
227 Ok(Json(Page::new(items, total, limit, offset)))
228}
229
230/// One fee plan with its schedule.
231#[utoipa::path(
232 get,
233 path = "/plans/{id}",
234 tag = "payments",
235 security(("session_cookie" = [])),
236 params(("id" = String, Path, description = "Fee plan id")),
237 responses(
238 (status = 200, description = "The plan", body = FeePlanResponse),
239 (status = 401, description = "Not authenticated", body = ErrorResponse),
240 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
241 (status = 404, description = "No such plan", body = ErrorResponse),
242 ),
243)]
244async fn get_plan(
245 State(st): State<AppState>,
246 RequireManager(_user): RequireManager,
247 Path(id): Path<String>,
248) -> Result<Json<FeePlanResponse>, AppError> {
249 let plan = require_plan(&id, &st.db).await?;
250 let items = plan_responses(std::slice::from_ref(&plan), &st.db).await?;
251 Ok(Json(
252 items.into_iter().next().expect("one plan in, one out"),
253 ))
254}
255
256/// Edit a plan's name and/or its schedule. Refused (`409`) once the plan has
257/// been assigned to anyone: those charges are frozen copies of the installments
258/// as they stood, so editing afterwards would leave the plan and the money
259/// telling different stories. Write a new plan instead.
260///
261/// The refusal is decided by the database as the edit is written, not by a
262/// read taken before it, so an assign arriving at the same instant cannot end
263/// up on either side of the edit: it either freezes the plan first (and this is
264/// a `409`) or bills the edited schedule. A PATCH carrying no field at all
265/// writes nothing and returns the plan unchanged, assigned or not.
266#[utoipa::path(
267 patch,
268 path = "/plans/{id}",
269 tag = "payments",
270 security(("session_cookie" = [])),
271 params(("id" = String, Path, description = "Fee plan id")),
272 request_body = UpdateFeePlan,
273 responses(
274 (status = 200, description = "The updated plan", body = FeePlanResponse),
275 (status = 400, description = "Invalid name, amount, due date, or installment count", body = ErrorResponse),
276 (status = 401, description = "Not authenticated", body = ErrorResponse),
277 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
278 (status = 404, description = "No such plan", body = ErrorResponse),
279 (status = 409, description = "The plan is already assigned to a student", body = ErrorResponse),
280 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
281 ),
282)]
283async fn update_plan(
284 State(st): State<AppState>,
285 RequireManager(_user): RequireManager,
286 Path(id): Path<String>,
287 Json(req): Json<UpdateFeePlan>,
288) -> Result<Json<FeePlanResponse>, AppError> {
289 let plan = require_plan(&id, &st.db).await?;
290 let name = req.name.as_deref().map(FeePlanName::try_new).transpose()?;
291 let installments = req.installments.map(InstallmentBody::list).transpose()?;
292 let plan = service::fee_plan::update(&st.db, plan, name, installments).await?;
293 let items = plan_responses(std::slice::from_ref(&plan), &st.db).await?;
294 Ok(Json(
295 items.into_iter().next().expect("one plan in, one out"),
296 ))
297}
298
299/// Delete a plan. Refused (`409`) once it has been assigned to anyone — the
300/// charges it raised name it, and a school's financial history keeps its
301/// references. Decided as the delete is written, the same way the edit is, so a
302/// simultaneous assign can never leave a live assignment pointing at a plan
303/// that is gone.
304#[utoipa::path(
305 delete,
306 path = "/plans/{id}",
307 tag = "payments",
308 security(("session_cookie" = [])),
309 params(("id" = String, Path, description = "Fee plan id")),
310 responses(
311 (status = 204, description = "Plan deleted"),
312 (status = 401, description = "Not authenticated", body = ErrorResponse),
313 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
314 (status = 404, description = "No such plan", body = ErrorResponse),
315 (status = 409, description = "The plan is already assigned to a student", body = ErrorResponse),
316 ),
317)]
318async fn delete_plan(
319 State(st): State<AppState>,
320 RequireManager(_user): RequireManager,
321 Path(id): Path<String>,
322) -> Result<StatusCode, AppError> {
323 let plan = require_plan(&id, &st.db).await?;
324 if !service::fee_plan::delete(&st.db, plan).await? {
325 return Err(AppError::Conflict("an assigned plan cannot be deleted"));
326 }
327 Ok(StatusCode::NO_CONTENT)
328}
329
330// ---- assignments ------------------------------------------------------------
331
332#[derive(Deserialize, ToSchema)]
333struct AssignFeePlan {
334 /// The students to place on the plan, at most 200 per call. Each is
335 /// reported on individually — one bad id does not lose the rest.
336 #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))]
337 student_ids: Vec<String>,
338}
339
340#[derive(Serialize, ToSchema)]
341struct AssignmentOutcome {
342 student_id: String,
343 /// `assigned` (placed and billed now), `already_assigned` (a replay — the
344 /// student was already on this plan, and nothing was billed again), or
345 /// `rejected`.
346 #[schema(example = "assigned")]
347 status: &'static str,
348 /// Why it was rejected; absent otherwise.
349 reason: Option<&'static str>,
350}
351
352#[derive(Serialize, ToSchema)]
353struct FeePlanAssignmentResponse {
354 id: String,
355 plan: String,
356 student: PersonRef,
357 assigned_by: PersonRef,
358 created_at: i64,
359}
360
361/// Place a plan on students, which is what turns it into money owed: every
362/// installment is appended as a charge line right away, each with its own due
363/// date. **Replay-safe** — a student already on the plan is reported
364/// `already_assigned` and is not billed a second time, and an assignment whose
365/// charges landed only in part heals when the call is repeated.
366///
367/// Only students carry a fee record, so any other target is rejected. One bad
368/// id never loses the rest of the batch: the response reports each student
369/// separately.
370///
371/// Placing the first student **freezes** the plan: it can no longer be edited
372/// or deleted. The installments billed are read back from the stored plan at
373/// that instant, so an edit that landed a moment earlier is the one billed,
374/// never the version this request first looked at. A plan deleted while the
375/// batch is running is `rejected` from that student on — a per-student outcome
376/// like any other, so the students it already billed stay in the report.
377///
378/// One request is bounded by the **charges it would raise**, not by the head
379/// count alone: `student_ids × installments` may not exceed 3 000 (200
380/// students up to a 15-installment plan; 50 at a time on a 60-installment
381/// one). Past that the whole call is a `400` telling the caller to split the
382/// batch — nothing is written, because a money route that billed half a batch
383/// and gave up would leave a bursar guessing which families were charged.
384#[utoipa::path(
385 post,
386 path = "/plans/{id}/assignments",
387 tag = "payments",
388 security(("session_cookie" = [])),
389 params(("id" = String, Path, description = "Fee plan id")),
390 request_body = AssignFeePlan,
391 responses(
392 (status = 200, description = "Per-student outcome, in the order sent", body = Vec<AssignmentOutcome>),
393 (status = 400, description = "Too many students named, or too many charges for one request", body = ErrorResponse),
394 (status = 401, description = "Not authenticated", body = ErrorResponse),
395 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
396 (status = 404, description = "No such plan", body = ErrorResponse),
397 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
398 ),
399)]
400async fn assign_plan(
401 State(st): State<AppState>,
402 RequireManager(manager): RequireManager,
403 Path(id): Path<String>,
404 Json(req): Json<AssignFeePlan>,
405) -> Result<Json<Vec<AssignmentOutcome>>, AppError> {
406 let outcomes =
407 service::fee_plan_assignment::assign_batch(&st.db, &id, manager.get_id(), req.student_ids)
408 .await?;
409 Ok(Json(
410 outcomes
411 .into_iter()
412 .map(|(student_id, outcome)| {
413 let (status, reason) = match outcome {
414 service::fee_plan_assignment::Outcome::Assigned => ("assigned", None),
415 service::fee_plan_assignment::Outcome::AlreadyAssigned => {
416 ("already_assigned", None)
417 }
418 service::fee_plan_assignment::Outcome::Rejected(reason) => {
419 ("rejected", Some(reason))
420 }
421 };
422 AssignmentOutcome {
423 student_id,
424 status,
425 reason,
426 }
427 })
428 .collect(),
429 ))
430}
431
432/// Who is on this plan, newest first. Paged via `?limit=&offset=`; returns a
433/// `{items, total, limit, offset}` envelope.
434#[utoipa::path(
435 get,
436 path = "/plans/{id}/assignments",
437 tag = "payments",
438 security(("session_cookie" = [])),
439 params(("id" = String, Path, description = "Fee plan id"), PageParams),
440 responses(
441 (status = 200, description = "A page of assignments (all of them when unpaged)", body = Page<FeePlanAssignmentResponse>),
442 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
443 (status = 401, description = "Not authenticated", body = ErrorResponse),
444 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
445 (status = 404, description = "No such plan", body = ErrorResponse),
446 ),
447)]
448async fn list_plan_assignments(
449 State(st): State<AppState>,
450 RequireManager(_user): RequireManager,
451 Path(id): Path<String>,
452 Query(page): Query<PageParams>,
453) -> Result<Json<Page<FeePlanAssignmentResponse>>, AppError> {
454 let (limit, offset) = page.resolve()?;
455 let plan = require_plan(&id, &st.db).await?;
456 let (rows, total) =
457 service::fee_plan_assignment::list_for_plan(&st.db, plan.get_id(), limit, offset).await?;
458 let people = person_map(
459 rows.iter()
460 .flat_map(|row| [*row.get_student(), *row.get_assigned_by()]),
461 &st.db,
462 )
463 .await?;
464 let items = rows
465 .iter()
466 .map(|row| FeePlanAssignmentResponse {
467 id: row.get_id().key().to_string(),
468 plan: row.get_plan().key().to_string(),
469 student: PersonRef::resolve(&people, row.get_student()),
470 assigned_by: PersonRef::resolve(&people, row.get_assigned_by()),
471 created_at: row.get_created_at().as_millis(),
472 })
473 .collect();
474 Ok(Json(Page::new(items, total, limit, offset)))
475}
476
477// ---- the ledger -------------------------------------------------------------
478
479#[derive(Serialize, ToSchema)]
480struct PaymentLineResponse {
481 id: String,
482 student: PersonRef,
483 /// `charge`, `credit`, `refund`, or `reversal`.
484 #[schema(example = "charge")]
485 kind: String,
486 /// Always positive — the sign is the `kind`'s business.
487 #[schema(example = 150000)]
488 amount_minor: i64,
489 /// What caused the line: the assignment on a `charge`, the paid charge on a
490 /// `credit`, the returned credit on a `refund`, the undone line on a
491 /// `reversal`.
492 source: Option<String>,
493 /// When this installment falls due. Charges only.
494 due_at: Option<i64>,
495 method: Option<String>,
496 note: Option<String>,
497 recorded_by: PersonRef,
498 created_at: i64,
499}
500
501impl PaymentLineResponse {
502 fn new(line: &PaymentLedger, people: &HashMap<String, PersonRef>) -> Self {
503 Self {
504 id: line.get_id().key().to_string(),
505 student: PersonRef::resolve(people, line.get_student()),
506 kind: line.get_kind().as_str().to_string(),
507 amount_minor: line.get_amount_minor().as_minor(),
508 source: line.get_source_key().map(str::to_string),
509 due_at: line.get_due_at().map(|due| due.as_millis()),
510 method: line.get_method().map(|method| method.as_str().to_string()),
511 note: line.get_note().map(|note| note.as_str().to_string()),
512 recorded_by: PersonRef::resolve(people, line.get_recorded_by()),
513 created_at: line.get_created_at().as_millis(),
514 }
515 }
516}
517
518/// Join the people onto a page of ledger lines — one query for the whole page.
519async fn line_responses(
520 lines: &[PaymentLedger],
521 db: &Database,
522) -> Result<Vec<PaymentLineResponse>, AppError> {
523 let people = person_map(
524 lines
525 .iter()
526 .flat_map(|line| [*line.get_student(), *line.get_recorded_by()]),
527 db,
528 )
529 .await?;
530 Ok(lines
531 .iter()
532 .map(|line| PaymentLineResponse::new(line, &people))
533 .collect())
534}
535
536/// The single appended line, as a `201`. Shared by all three money routes.
537async fn appended(
538 line: PaymentLedger,
539 db: &Database,
540) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> {
541 let items = line_responses(std::slice::from_ref(&line), db).await?;
542 Ok((
543 StatusCode::CREATED,
544 Json(items.into_iter().next().expect("one line in, one out")),
545 ))
546}
547
548async fn require_line(id: &str, db: &Database) -> Result<PaymentLedger, AppError> {
549 let id = PaymentLedgerId::from_key(id);
550 service::payment_ledger::read(db, &id)
551 .await?
552 .ok_or(AppError::NotFound)
553}
554
555#[derive(Deserialize, ToSchema)]
556struct RecordPayment {
557 /// The charge line this money pays.
558 charge_id: String,
559 /// How much came in, **minor units**, positive. Partial payments
560 /// are the norm; together they may not exceed the charge.
561 #[schema(minimum = 1, maximum = 10000000, example = 50000)]
562 amount_minor: i64,
563 /// How it arrived ("cash", "havale", …). Free text — the backend speaks to
564 /// no payment gateway and stores no card data.
565 #[schema(max_length = 50, example = "havale")]
566 method: Option<String>,
567 #[schema(max_length = 500, example = "receipt 2026-114")]
568 note: Option<String>,
569 /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` (no `_`: it is the
570 /// separator inside a ledger line's id). Send one and a
571 /// retry after a timeout returns the **same** line instead of recording the
572 /// money twice; omit it and two identical calls are two payments. The same
573 /// key sent with a different `amount_minor` or `charge_id` is a `409`.
574 #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")]
575 request_key: Option<String>,
576}
577
578#[derive(Deserialize, ToSchema)]
579struct RecordRefund {
580 /// The payment being handed back.
581 credit_id: String,
582 /// How much goes back out, **minor units**, positive. Partials
583 /// allowed, up to what the credit was worth.
584 #[schema(minimum = 1, maximum = 10000000, example = 50000)]
585 amount_minor: i64,
586 #[schema(max_length = 50, example = "cash")]
587 method: Option<String>,
588 #[schema(max_length = 500)]
589 note: Option<String>,
590 /// Optional client-chosen idempotence key, `[A-Za-z0-9-]` — the same
591 /// retry-safety a payment gets, keyed by the credit it returns. The same
592 /// key with a different `amount_minor` or `credit_id` is a `409`.
593 #[schema(min_length = 1, max_length = 64, example = "refund-2026-114")]
594 request_key: Option<String>,
595}
596
597#[derive(Deserialize, ToSchema)]
598struct RecordReversal {
599 /// The `charge` or `refund` to undo, for its exact amount.
600 line_id: String,
601 #[schema(max_length = 500, example = "billed in error")]
602 note: Option<String>,
603}
604
605fn method_of(raw: Option<&str>) -> Result<Option<LedgerMethod>, AppError> {
606 Ok(raw.map(LedgerMethod::try_new).transpose()?.flatten())
607}
608
609fn note_of(raw: Option<&str>) -> Result<Option<LedgerNote>, AppError> {
610 Ok(raw.map(LedgerNote::try_new).transpose()?.flatten())
611}
612
613fn request_key_of(raw: Option<&str>) -> Result<Option<PaymentRequestKey>, AppError> {
614 Ok(raw.map(PaymentRequestKey::try_new).transpose()?)
615}
616
617/// Record money received against one named charge. Allocation is recorded, not
618/// inferred: a payment always says which installment it settles. Partial
619/// payments accumulate; one that would take the charge past what it is worth is
620/// a `409`. A charge that was **reversed** takes no payment either — it is no
621/// longer owed — and that `409` says so, rather than reporting money that never
622/// arrived as "paid in full".
623///
624/// **Retry-safe on request** — send a `request_key` and a repeat of the call
625/// (a client retry after a network timeout) returns the line the first attempt
626/// wrote rather than recording the money a second time, even when that payment
627/// filled the charge exactly. The same key with a different `amount_minor` or
628/// `charge_id` is a `409`: that is a client bug, not a replay. Without a key
629/// two identical calls are two payments, as before.
630#[utoipa::path(
631 post,
632 path = "/credits",
633 tag = "payments",
634 security(("session_cookie" = [])),
635 request_body = RecordPayment,
636 responses(
637 (status = 201, description = "Payment recorded", body = PaymentLineResponse),
638 (status = 400, description = "Invalid amount, method, note, or a target that is not a charge", body = ErrorResponse),
639 (status = 401, description = "Not authenticated", body = ErrorResponse),
640 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
641 (status = 404, description = "No such ledger line", body = ErrorResponse),
642 (status = 409, description = "The charge is already paid in full, the charge was reversed (so it is no longer owed), it already carries the most lines that may be applied to it, or the request_key was used for a different amount or charge", body = ErrorResponse),
643 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
644 ),
645)]
646async fn record_payment(
647 State(st): State<AppState>,
648 RequireManager(manager): RequireManager,
649 Json(req): Json<RecordPayment>,
650) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> {
651 let charge = require_line(&req.charge_id, &st.db).await?;
652 let line = service::payment_ledger::credit(
653 &st.db,
654 &charge,
655 LedgerAmount::try_new(req.amount_minor)?,
656 method_of(req.method.as_deref())?,
657 note_of(req.note.as_deref())?,
658 request_key_of(req.request_key.as_deref())?.as_ref(),
659 manager.get_id(),
660 )
661 .await?;
662 appended(line, &st.db).await
663}
664
665/// Hand money back, against one named payment — how an over-payment or a
666/// payment recorded in error is returned, and the only way a mistaken *credit*
667/// is corrected (a credit is never reversed). Capped by that credit's amount.
668///
669/// **Retry-safe on request** the same way a payment is: a `request_key` makes a
670/// repeat return the existing refund, and the same key with a different
671/// `amount_minor` or `credit_id` is a `409`.
672#[utoipa::path(
673 post,
674 path = "/refunds",
675 tag = "payments",
676 security(("session_cookie" = [])),
677 request_body = RecordRefund,
678 responses(
679 (status = 201, description = "Refund recorded", body = PaymentLineResponse),
680 (status = 400, description = "Invalid amount, method, note, or a target that is not a payment", body = ErrorResponse),
681 (status = 401, description = "Not authenticated", body = ErrorResponse),
682 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
683 (status = 404, description = "No such ledger line", body = ErrorResponse),
684 (status = 409, description = "The payment is already refunded in full, it already carries the most lines that may be applied to it, or the request_key was used for a different amount or payment", body = ErrorResponse),
685 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
686 ),
687)]
688async fn record_refund(
689 State(st): State<AppState>,
690 RequireManager(manager): RequireManager,
691 Json(req): Json<RecordRefund>,
692) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> {
693 let credit = require_line(&req.credit_id, &st.db).await?;
694 let line = service::payment_ledger::refund(
695 &st.db,
696 &credit,
697 LedgerAmount::try_new(req.amount_minor)?,
698 method_of(req.method.as_deref())?,
699 note_of(req.note.as_deref())?,
700 request_key_of(req.request_key.as_deref())?.as_ref(),
701 manager.get_id(),
702 )
703 .await?;
704 appended(line, &st.db).await
705}
706
707/// Undo a line entered by mistake, for its exact amount — the line itself stays,
708/// with an opposing one appended beside it. Only a `charge` or a `refund` may be
709/// reversed (`400` otherwise): a mistaken payment is corrected with a refund, so
710/// money leaving the school is always spelled the one way. **Idempotent** — a
711/// line has at most one reversal, however often the call is retried.
712#[utoipa::path(
713 post,
714 path = "/reversals",
715 tag = "payments",
716 security(("session_cookie" = [])),
717 request_body = RecordReversal,
718 responses(
719 (status = 201, description = "Reversal recorded (or the existing one replayed)", body = PaymentLineResponse),
720 (status = 400, description = "Invalid note, or a target that is not a charge or a refund", body = ErrorResponse),
721 (status = 401, description = "Not authenticated", body = ErrorResponse),
722 (status = 403, description = "Requires manager role or higher", body = ErrorResponse),
723 (status = 404, description = "No such ledger line", body = ErrorResponse),
724 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
725 ),
726)]
727async fn record_reversal(
728 State(st): State<AppState>,
729 RequireManager(manager): RequireManager,
730 Json(req): Json<RecordReversal>,
731) -> Result<(StatusCode, Json<PaymentLineResponse>), AppError> {
732 let target = require_line(&req.line_id, &st.db).await?;
733 let line = service::payment_ledger::reversal(
734 &st.db,
735 &target,
736 note_of(req.note.as_deref())?,
737 manager.get_id(),
738 )
739 .await?;
740 appended(line, &st.db).await
741}
742
743// ---- reads ------------------------------------------------------------------
744
745/// May `caller` read `target`'s payment record? Own always; a parent only for a
746/// student they hold a live link to; manager+ for anyone.
747///
748/// Deliberately narrower than
749/// [`crate::service::parent_link::ensure_can_observe`]: **a teacher sees no
750/// money**. What a family owes the school is not classroom information.
751async fn ensure_can_read_payments(
752 caller: &User,
753 target: &UserId,
754 db: &Database,
755) -> Result<(), AppError> {
756 if caller.get_id() == target || caller.get_role().at_least(Role::Manager) {
757 return Ok(());
758 }
759 // The link row alone is not the grant: a link whose student side changed
760 // role must be inert, so the target's live role is re-read. A missing or
761 // non-student target falls through to the same 403 — a parent never gets an
762 // existence oracle.
763 if caller.get_role() == Role::Parent
764 && crate::service::parent_link::links_live(db, caller.get_id(), target).await?
765 {
766 return Ok(());
767 }
768 Err(AppError::Forbidden(
769 "requires manager role or higher, or a parent link to this student",
770 ))
771}
772
773/// One student's raw ledger, newest line first: every charge, payment, refund,
774/// and reversal. Nothing here is ever edited or deleted — a correction is
775/// another line. Own record always; otherwise manager+ or a parent link (a
776/// teacher gets a `403`). Paged via `?limit=&offset=`.
777#[utoipa::path(
778 get,
779 path = "/ledger/{user}",
780 tag = "payments",
781 security(("session_cookie" = [])),
782 params(("user" = String, Path, description = "Student id"), PageParams),
783 responses(
784 (status = 200, description = "A page of ledger lines (all of them when unpaged)", body = Page<PaymentLineResponse>),
785 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
786 (status = 401, description = "Not authenticated", body = ErrorResponse),
787 (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
788 ),
789)]
790async fn user_ledger(
791 State(st): State<AppState>,
792 CurrentUser(caller): CurrentUser,
793 Path(user): Path<String>,
794 Query(page): Query<PageParams>,
795) -> Result<Json<Page<PaymentLineResponse>>, AppError> {
796 let (limit, offset) = page.resolve()?;
797 let target = UserId::from_key(&user);
798 ensure_can_read_payments(&caller, &target, &st.db).await?;
799 let (rows, total) =
800 service::payment_ledger::list_for_student(&st.db, &target, limit, offset).await?;
801 let items = line_responses(&rows, &st.db).await?;
802 Ok(Json(Page::new(items, total, limit, offset)))
803}
804
805#[derive(Serialize, ToSchema)]
806struct StatementEntry {
807 /// The charge line this row rolls up.
808 charge_id: String,
809 /// The plan it came from, and its name when the plan still exists.
810 plan: Option<String>,
811 plan_name: Option<String>,
812 /// What the installment bills, minor units.
813 #[schema(example = 150000)]
814 amount_minor: i64,
815 /// When it falls due, unix milliseconds.
816 due_at: Option<i64>,
817 /// Payments recorded against it.
818 credited_minor: i64,
819 /// Of those payments, how much was handed back (a reversed refund does not
820 /// count — it never left).
821 refunded_minor: i64,
822 /// `amount - credited + refunded`, or `0` for a reversed charge. Negative
823 /// means the charge was over-paid.
824 outstanding_minor: i64,
825 /// Was the charge itself undone? Such a charge owes nothing.
826 reversed: bool,
827 /// Still owed, and its due date has passed. Derived on every read, never
828 /// stored — there is no scheduler and no overdue sweep.
829 overdue: bool,
830}
831
832#[derive(Serialize, ToSchema)]
833struct StatementResponse {
834 student: PersonRef,
835 /// One row per charge, newest first, in the standard
836 /// `{items, total, limit, offset}` envelope. Paging windows these rows
837 /// only — `balance_minor` is folded from every line either way.
838 entries: Page<StatementEntry>,
839 /// `credits + reversals - charges - refunds`, minor units. Negative means
840 /// the family owes the school.
841 #[schema(example = -100000)]
842 balance_minor: i64,
843}
844
845/// The per-charge rollup, folded from the student's lines on every read.
846///
847/// Everything derived here — what a charge collected, what went back out,
848/// what is still owed, and whether it is late — is computed from the raw lines
849/// at request time and stored nowhere: a stored rollup is a second version of
850/// the truth, and the ledger is the first.
851///
852/// `limit`/`offset` window the returned rows **after** the whole fold, never
853/// the lines it folds: a page of a statement must still report the same
854/// `balance_minor` (and the same overdue arithmetic) as every other page.
855async fn statement_response(
856 student: &UserId,
857 limit: Option<i64>,
858 offset: i64,
859 db: &Database,
860) -> Result<Json<StatementResponse>, AppError> {
861 let (lines, _) = service::payment_ledger::list_for_student(db, student, None, 0).await?;
862 // Index every line by what it points at, so the rollup is one pass over the
863 // student's history rather than a query per charge.
864 let mut children: HashMap<&str, Vec<&PaymentLedger>> = HashMap::new();
865 for line in &lines {
866 if let Some(source) = line.get_source_key() {
867 children.entry(source).or_default().push(line);
868 }
869 }
870 let reversed = |key: &str| {
871 children.get(key).is_some_and(|kids| {
872 kids.iter()
873 .any(|kid| kid.get_kind() == PaymentLedgerKind::Reversal)
874 })
875 };
876
877 // A charge names its assignment, and the assignment names the plan.
878 let (assignments, _) =
879 service::fee_plan_assignment::list_for_student(db, student, None, 0).await?;
880 let mut plan_names: HashMap<String, Option<String>> = HashMap::new();
881 let mut plan_of: HashMap<String, &FeePlanId> = HashMap::new();
882 for assignment in &assignments {
883 let plan = assignment.get_plan();
884 if !plan_names.contains_key(plan.key().as_str()) {
885 let name = service::fee_plan::read(db, plan)
886 .await?
887 .map(|plan| plan.get_name().as_str().to_string());
888 plan_names.insert(plan.key().to_string(), name);
889 }
890 plan_of.insert(assignment.get_id().key(), plan);
891 }
892
893 let now = Timestamp::now().as_millis();
894 // The window is taken over the charges, not over the lines: the rollup
895 // above (and the balance below) still reads every line, so a page reports
896 // exactly the arithmetic the unpaged document does.
897 let charges: Vec<&PaymentLedger> = lines
898 .iter()
899 .filter(|line| line.get_kind() == PaymentLedgerKind::Charge)
900 .collect();
901 let total = charges.len() as i64;
902 let entries: Vec<StatementEntry> = paginate(&charges, limit, offset)
903 .iter()
904 .map(|charge| {
905 let paid: Vec<&&PaymentLedger> = children
906 .get(charge.get_id().key())
907 .map(|kids| {
908 kids.iter()
909 .filter(|kid| kid.get_kind() == PaymentLedgerKind::Credit)
910 .collect()
911 })
912 .unwrap_or_default();
913 let credited: i64 = paid
914 .iter()
915 .map(|credit| credit.get_amount_minor().as_minor())
916 .sum();
917 // A refund hangs off the credit it returns, one level below the
918 // charge — and a refund that was itself reversed never left.
919 let refunded: i64 = paid
920 .iter()
921 .filter_map(|credit| children.get(credit.get_id().key()))
922 .flatten()
923 .filter(|kid| {
924 kid.get_kind() == PaymentLedgerKind::Refund && !reversed(kid.get_id().key())
925 })
926 .map(|refund| refund.get_amount_minor().as_minor())
927 .sum();
928 let charge_reversed = reversed(charge.get_id().key());
929 let outstanding = if charge_reversed {
930 0
931 } else {
932 charge.get_amount_minor().as_minor() - credited + refunded
933 };
934 let due_at = charge.get_due_at().map(|due| due.as_millis());
935 let plan = plan_of.get(charge.get_source_key().unwrap_or_default());
936 StatementEntry {
937 charge_id: charge.get_id().key().to_string(),
938 plan: plan.map(|plan| plan.key().to_string()),
939 plan_name: plan
940 .and_then(|plan| plan_names.get(plan.key().as_str()).cloned().flatten()),
941 amount_minor: charge.get_amount_minor().as_minor(),
942 due_at,
943 credited_minor: credited,
944 refunded_minor: refunded,
945 outstanding_minor: outstanding,
946 reversed: charge_reversed,
947 overdue: outstanding > 0 && due_at.is_some_and(|due| due < now),
948 }
949 })
950 .collect();
951
952 let people = person_map(std::iter::once(*student), db).await?;
953 Ok(Json(StatementResponse {
954 student: PersonRef::resolve(&people, student),
955 entries: Page::new(entries, total, limit, offset),
956 // Folded from the very lines the rollup above walked, never re-read: a
957 // payment landing between two reads would leave one document saying
958 // both "still owed" and "already settled" about the same money.
959 balance_minor: PaymentLedger::fold_balance(lines.iter().map(PaymentLedger::folded)),
960 }))
961}
962
963/// The caller's own statement. The per-charge rows are paged via
964/// `?limit=&offset=` (omit `limit` for all of them); `balance_minor` is the
965/// same on every page, because the fold behind it reads every line.
966#[utoipa::path(
967 get,
968 path = "/statement/me",
969 tag = "payments",
970 security(("session_cookie" = [])),
971 params(PageParams),
972 responses(
973 (status = 200, description = "The caller's statement", body = StatementResponse),
974 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
975 (status = 401, description = "Not authenticated", body = ErrorResponse),
976 ),
977)]
978async fn my_statement(
979 State(st): State<AppState>,
980 CurrentUser(user): CurrentUser,
981 Query(page): Query<PageParams>,
982) -> Result<Json<StatementResponse>, AppError> {
983 let (limit, offset) = page.resolve()?;
984 statement_response(user.get_id(), limit, offset, &st.db).await
985}
986
987/// One student's statement: a row per charge with what it collected, what went
988/// back out, what is still owed, and whether it is overdue. Own record always;
989/// otherwise manager+ or a parent link (a teacher gets a `403`). The rows are
990/// paged via `?limit=&offset=`; `balance_minor` is the same on every page.
991#[utoipa::path(
992 get,
993 path = "/statement/{user}",
994 tag = "payments",
995 security(("session_cookie" = [])),
996 params(("user" = String, Path, description = "Student id"), PageParams),
997 responses(
998 (status = 200, description = "The student's statement", body = StatementResponse),
999 (status = 400, description = "Invalid limit or offset", body = ErrorResponse),
1000 (status = 401, description = "Not authenticated", body = ErrorResponse),
1001 (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1002 ),
1003)]
1004async fn user_statement(
1005 State(st): State<AppState>,
1006 CurrentUser(caller): CurrentUser,
1007 Path(user): Path<String>,
1008 Query(page): Query<PageParams>,
1009) -> Result<Json<StatementResponse>, AppError> {
1010 let (limit, offset) = page.resolve()?;
1011 let target = UserId::from_key(&user);
1012 ensure_can_read_payments(&caller, &target, &st.db).await?;
1013 statement_response(&target, limit, offset, &st.db).await
1014}
1015
1016#[derive(Serialize, ToSchema)]
1017struct PaymentBalanceResponse {
1018 student: PersonRef,
1019 /// `credits + reversals - charges - refunds`, in **minor units**.
1020 /// Negative means the family owes the school. Derived on every read, never
1021 /// stored.
1022 #[schema(example = -100000)]
1023 balance_minor: i64,
1024}
1025
1026async fn balance_response(
1027 student: &UserId,
1028 db: &Database,
1029) -> Result<Json<PaymentBalanceResponse>, AppError> {
1030 let people = person_map(std::iter::once(*student), db).await?;
1031 Ok(Json(PaymentBalanceResponse {
1032 student: PersonRef::resolve(&people, student),
1033 balance_minor: service::payment_ledger::balance_of(db, student).await?,
1034 }))
1035}
1036
1037/// What the caller owes the school (or has on account).
1038#[utoipa::path(
1039 get,
1040 path = "/balance/me",
1041 tag = "payments",
1042 security(("session_cookie" = [])),
1043 responses(
1044 (status = 200, description = "The caller's fee balance", body = PaymentBalanceResponse),
1045 (status = 401, description = "Not authenticated", body = ErrorResponse),
1046 ),
1047)]
1048async fn my_balance(
1049 State(st): State<AppState>,
1050 CurrentUser(user): CurrentUser,
1051) -> Result<Json<PaymentBalanceResponse>, AppError> {
1052 balance_response(user.get_id(), &st.db).await
1053}
1054
1055/// One student's fee balance. Own record always; otherwise manager+ or a parent
1056/// link (a teacher gets a `403`).
1057#[utoipa::path(
1058 get,
1059 path = "/balance/{user}",
1060 tag = "payments",
1061 security(("session_cookie" = [])),
1062 params(("user" = String, Path, description = "Student id")),
1063 responses(
1064 (status = 200, description = "The student's fee balance", body = PaymentBalanceResponse),
1065 (status = 401, description = "Not authenticated", body = ErrorResponse),
1066 (status = 403, description = "Requires manager role or higher, or a parent link", body = ErrorResponse),
1067 ),
1068)]
1069async fn user_balance(
1070 State(st): State<AppState>,
1071 CurrentUser(caller): CurrentUser,
1072 Path(user): Path<String>,
1073) -> Result<Json<PaymentBalanceResponse>, AppError> {
1074 let target = UserId::from_key(&user);
1075 ensure_can_read_payments(&caller, &target, &st.db).await?;
1076 balance_response(&target, &st.db).await
1077}
1078
1079#[cfg(test)]
1080mod tests {
1081 use super::*;
1082
1083 /// The statement is the one piece of arithmetic this layer owns, and it is
1084 /// arithmetic about money: a charge's payments, the refunds hanging a level
1085 /// below them, a reversal that zeroes the whole row, and `overdue` derived
1086 /// from a due date that has passed. Folded against the engine, because the
1087 /// shape of `source` links is exactly what the fold walks.
1088 #[tokio::test]
1089 async fn the_statement_rolls_each_charge_up_from_its_own_lines() {
1090 let (db, _leases) = crate::database::init_test_db().await;
1091 let manager = crate::db::class_member::tests::fixture_user(&db, "stmt-manager").await;
1092 let student = crate::db::class_member::tests::fixture_user(&db, "stmt-student").await;
1093 let future = Timestamp::now().as_millis() + 30 * 24 * 60 * 60 * 1000;
1094 let plan = service::fee_plan::create(
1095 &db,
1096 FeePlanName::try_new("Yearly").unwrap(),
1097 vec![
1098 // Already due, and only part paid — the overdue row.
1099 Installment::new(
1100 LedgerAmount::try_new(10_000).unwrap(),
1101 Timestamp::from_millis(1_000),
1102 ),
1103 Installment::new(
1104 LedgerAmount::try_new(20_000).unwrap(),
1105 Timestamp::from_millis(future),
1106 ),
1107 ],
1108 &manager,
1109 )
1110 .await
1111 .unwrap();
1112 service::fee_plan_assignment::assign(&db, &plan, &student, &manager)
1113 .await
1114 .unwrap();
1115
1116 let (lines, _) = service::payment_ledger::list_for_student(&db, &student, None, 0)
1117 .await
1118 .unwrap();
1119 let charge = |amount: i64| {
1120 lines
1121 .iter()
1122 .find(|line| line.get_amount_minor().as_minor() == amount)
1123 .expect("the installment was billed")
1124 .clone()
1125 };
1126 let paid = service::payment_ledger::credit(
1127 &db,
1128 &charge(10_000),
1129 LedgerAmount::try_new(6_000).unwrap(),
1130 None,
1131 None,
1132 None,
1133 &manager,
1134 )
1135 .await
1136 .unwrap();
1137 service::payment_ledger::refund(
1138 &db,
1139 &paid,
1140 LedgerAmount::try_new(1_000).unwrap(),
1141 None,
1142 None,
1143 None,
1144 &manager,
1145 )
1146 .await
1147 .unwrap();
1148 service::payment_ledger::reversal(&db, &charge(20_000), None, &manager)
1149 .await
1150 .unwrap();
1151
1152 let statement = statement_response(&student, None, 0, &db).await.unwrap().0;
1153 let entry = |n: &str| {
1154 statement
1155 .entries
1156 .items
1157 .iter()
1158 .find(|entry| entry.charge_id.ends_with(n))
1159 .expect("a row per charge")
1160 };
1161 let first = entry("_c1");
1162 assert_eq!(first.plan_name.as_deref(), Some("Yearly"));
1163 assert_eq!(first.credited_minor, 6_000);
1164 assert_eq!(first.refunded_minor, 1_000);
1165 // 10 000 billed, 6 000 paid, 1 000 of that handed back.
1166 assert_eq!(first.outstanding_minor, 5_000);
1167 assert!(!first.reversed);
1168 assert!(first.overdue, "unpaid and its due date has passed");
1169
1170 let second = entry("_c2");
1171 assert!(second.reversed);
1172 assert_eq!(
1173 second.outstanding_minor, 0,
1174 "a reversed charge owes nothing"
1175 );
1176 assert!(!second.overdue);
1177
1178 assert_eq!(
1179 statement.balance_minor, -5_000,
1180 "the fold and the rollup must agree about what is owed"
1181 );
1182 }
1183}