| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | use std::collections::HashMap; |
| 16 | |
| 17 | use crate::web::tenant_state::State; |
| 18 | use axum::Json; |
| 19 | use axum::extract::{Path, Query}; |
| 20 | use axum::http::StatusCode; |
| 21 | use serde::{Deserialize, Serialize}; |
| 22 | use utoipa::ToSchema; |
| 23 | use utoipa_axum::router::OpenApiRouter; |
| 24 | use utoipa_axum::routes; |
| 25 | |
| 26 | use crate::database::Database; |
| 27 | use crate::domain::fee_plan::{FeePlan, FeePlanId, FeePlanName, Installment}; |
| 28 | use crate::domain::payment_ledger::{ |
| 29 | LedgerAmount, LedgerMethod, LedgerNote, PaymentLedger, PaymentLedgerId, PaymentLedgerKind, |
| 30 | PaymentRequestKey, |
| 31 | }; |
| 32 | use crate::domain::role::Role; |
| 33 | use crate::domain::timestamp::Timestamp; |
| 34 | use crate::domain::user::{User, UserId}; |
| 35 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 36 | use crate::service; |
| 37 | use crate::state::AppState; |
| 38 | |
| 39 | use super::{CurrentUser, Page, PageParams, PersonRef, RequireManager, paginate, person_map}; |
| 40 | |
| 41 | pub 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 | |
| 57 | |
| 58 | |
| 59 | |
| 60 | #[derive(Debug, Deserialize, ToSchema)] |
| 61 | struct InstallmentBody { |
| 62 | |
| 63 | |
| 64 | #[schema(minimum = 1, maximum = 10000000, example = 150000_i64)] |
| 65 | amount_minor: i64, |
| 66 | |
| 67 | |
| 68 | |
| 69 | #[schema(minimum = 0, example = 1_760_000_000_000_i64)] |
| 70 | due_at: i64, |
| 71 | } |
| 72 | |
| 73 | impl InstallmentBody { |
| 74 | fn into_domain(self) -> Result<Installment, AppError> { |
| 75 | |
| 76 | |
| 77 | |
| 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)] |
| 96 | struct CreateFeePlan { |
| 97 | #[schema(example = "2026-2027 Yearly", max_length = 120)] |
| 98 | name: String, |
| 99 | |
| 100 | |
| 101 | #[schema(min_items = 1, max_items = 60)] |
| 102 | installments: Vec<InstallmentBody>, |
| 103 | } |
| 104 | |
| 105 | #[derive(Deserialize, ToSchema)] |
| 106 | struct UpdateFeePlan { |
| 107 | #[schema(max_length = 120)] |
| 108 | name: Option<String>, |
| 109 | |
| 110 | |
| 111 | |
| 112 | #[schema(min_items = 1, max_items = 60)] |
| 113 | installments: Option<Vec<InstallmentBody>>, |
| 114 | } |
| 115 | |
| 116 | #[derive(Serialize, ToSchema)] |
| 117 | struct InstallmentResponse { |
| 118 | |
| 119 | amount_minor: i64, |
| 120 | due_at: i64, |
| 121 | } |
| 122 | |
| 123 | #[derive(Serialize, ToSchema)] |
| 124 | struct FeePlanResponse { |
| 125 | id: String, |
| 126 | name: String, |
| 127 | installments: Vec<InstallmentResponse>, |
| 128 | created_by: PersonRef, |
| 129 | created_at: i64, |
| 130 | } |
| 131 | |
| 132 | impl 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 | |
| 152 | async 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 | |
| 163 | async 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 | |
| 170 | |
| 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 | )] |
| 185 | async 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 | |
| 205 | |
| 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 | )] |
| 219 | async 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 | |
| 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 | )] |
| 244 | async 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 | |
| 257 | |
| 258 | |
| 259 | |
| 260 | |
| 261 | |
| 262 | |
| 263 | |
| 264 | |
| 265 | |
| 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 | )] |
| 283 | async 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 | |
| 300 | |
| 301 | |
| 302 | |
| 303 | |
| 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 | )] |
| 318 | async 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 | |
| 331 | |
| 332 | #[derive(Deserialize, ToSchema)] |
| 333 | struct AssignFeePlan { |
| 334 | |
| 335 | |
| 336 | #[schema(max_items = 200, example = json!(["019732e3-7b00-7000-8000-000000000a0b"]))] |
| 337 | student_ids: Vec<String>, |
| 338 | } |
| 339 | |
| 340 | #[derive(Serialize, ToSchema)] |
| 341 | struct AssignmentOutcome { |
| 342 | student_id: String, |
| 343 | |
| 344 | |
| 345 | |
| 346 | #[schema(example = "assigned")] |
| 347 | status: &'static str, |
| 348 | |
| 349 | reason: Option<&'static str>, |
| 350 | } |
| 351 | |
| 352 | #[derive(Serialize, ToSchema)] |
| 353 | struct FeePlanAssignmentResponse { |
| 354 | id: String, |
| 355 | plan: String, |
| 356 | student: PersonRef, |
| 357 | assigned_by: PersonRef, |
| 358 | created_at: i64, |
| 359 | } |
| 360 | |
| 361 | |
| 362 | |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | |
| 375 | |
| 376 | |
| 377 | |
| 378 | |
| 379 | |
| 380 | |
| 381 | |
| 382 | |
| 383 | |
| 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 | )] |
| 400 | async 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 | |
| 433 | |
| 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 | )] |
| 448 | async 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 | |
| 478 | |
| 479 | #[derive(Serialize, ToSchema)] |
| 480 | struct PaymentLineResponse { |
| 481 | id: String, |
| 482 | student: PersonRef, |
| 483 | |
| 484 | #[schema(example = "charge")] |
| 485 | kind: String, |
| 486 | |
| 487 | #[schema(example = 150000)] |
| 488 | amount_minor: i64, |
| 489 | |
| 490 | |
| 491 | |
| 492 | source: Option<String>, |
| 493 | |
| 494 | due_at: Option<i64>, |
| 495 | method: Option<String>, |
| 496 | note: Option<String>, |
| 497 | recorded_by: PersonRef, |
| 498 | created_at: i64, |
| 499 | } |
| 500 | |
| 501 | impl 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 | |
| 519 | async 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 | |
| 537 | async 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 | |
| 548 | async 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)] |
| 556 | struct RecordPayment { |
| 557 | |
| 558 | charge_id: String, |
| 559 | |
| 560 | |
| 561 | #[schema(minimum = 1, maximum = 10000000, example = 50000)] |
| 562 | amount_minor: i64, |
| 563 | |
| 564 | |
| 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 | |
| 570 | |
| 571 | |
| 572 | |
| 573 | |
| 574 | #[schema(min_length = 1, max_length = 64, example = "receipt-2026-114")] |
| 575 | request_key: Option<String>, |
| 576 | } |
| 577 | |
| 578 | #[derive(Deserialize, ToSchema)] |
| 579 | struct RecordRefund { |
| 580 | |
| 581 | credit_id: String, |
| 582 | |
| 583 | |
| 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 | |
| 591 | |
| 592 | |
| 593 | #[schema(min_length = 1, max_length = 64, example = "refund-2026-114")] |
| 594 | request_key: Option<String>, |
| 595 | } |
| 596 | |
| 597 | #[derive(Deserialize, ToSchema)] |
| 598 | struct RecordReversal { |
| 599 | |
| 600 | line_id: String, |
| 601 | #[schema(max_length = 500, example = "billed in error")] |
| 602 | note: Option<String>, |
| 603 | } |
| 604 | |
| 605 | fn method_of(raw: Option<&str>) -> Result<Option<LedgerMethod>, AppError> { |
| 606 | Ok(raw.map(LedgerMethod::try_new).transpose()?.flatten()) |
| 607 | } |
| 608 | |
| 609 | fn note_of(raw: Option<&str>) -> Result<Option<LedgerNote>, AppError> { |
| 610 | Ok(raw.map(LedgerNote::try_new).transpose()?.flatten()) |
| 611 | } |
| 612 | |
| 613 | fn request_key_of(raw: Option<&str>) -> Result<Option<PaymentRequestKey>, AppError> { |
| 614 | Ok(raw.map(PaymentRequestKey::try_new).transpose()?) |
| 615 | } |
| 616 | |
| 617 | |
| 618 | |
| 619 | |
| 620 | |
| 621 | |
| 622 | |
| 623 | |
| 624 | |
| 625 | |
| 626 | |
| 627 | |
| 628 | |
| 629 | |
| 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 | )] |
| 646 | async 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 | |
| 666 | |
| 667 | |
| 668 | |
| 669 | |
| 670 | |
| 671 | |
| 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 | )] |
| 688 | async 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 | |
| 708 | |
| 709 | |
| 710 | |
| 711 | |
| 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 | )] |
| 727 | async 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 | |
| 744 | |
| 745 | |
| 746 | |
| 747 | |
| 748 | |
| 749 | |
| 750 | |
| 751 | async 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 | |
| 760 | |
| 761 | |
| 762 | |
| 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 | |
| 774 | |
| 775 | |
| 776 | |
| 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 | )] |
| 790 | async 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)] |
| 806 | struct StatementEntry { |
| 807 | |
| 808 | charge_id: String, |
| 809 | |
| 810 | plan: Option<String>, |
| 811 | plan_name: Option<String>, |
| 812 | |
| 813 | #[schema(example = 150000)] |
| 814 | amount_minor: i64, |
| 815 | |
| 816 | due_at: Option<i64>, |
| 817 | |
| 818 | credited_minor: i64, |
| 819 | |
| 820 | |
| 821 | refunded_minor: i64, |
| 822 | |
| 823 | |
| 824 | outstanding_minor: i64, |
| 825 | |
| 826 | reversed: bool, |
| 827 | |
| 828 | |
| 829 | overdue: bool, |
| 830 | } |
| 831 | |
| 832 | #[derive(Serialize, ToSchema)] |
| 833 | struct StatementResponse { |
| 834 | student: PersonRef, |
| 835 | |
| 836 | |
| 837 | |
| 838 | entries: Page<StatementEntry>, |
| 839 | |
| 840 | |
| 841 | #[schema(example = -100000)] |
| 842 | balance_minor: i64, |
| 843 | } |
| 844 | |
| 845 | |
| 846 | |
| 847 | |
| 848 | |
| 849 | |
| 850 | |
| 851 | |
| 852 | |
| 853 | |
| 854 | |
| 855 | async 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 | |
| 863 | |
| 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 | |
| 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 | |
| 895 | |
| 896 | |
| 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 | |
| 918 | |
| 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 | |
| 957 | |
| 958 | |
| 959 | balance_minor: PaymentLedger::fold_balance(lines.iter().map(PaymentLedger::folded)), |
| 960 | })) |
| 961 | } |
| 962 | |
| 963 | |
| 964 | |
| 965 | |
| 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 | )] |
| 978 | async 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 | |
| 988 | |
| 989 | |
| 990 | |
| 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 | )] |
| 1004 | async 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)] |
| 1017 | struct PaymentBalanceResponse { |
| 1018 | student: PersonRef, |
| 1019 | |
| 1020 | |
| 1021 | |
| 1022 | #[schema(example = -100000)] |
| 1023 | balance_minor: i64, |
| 1024 | } |
| 1025 | |
| 1026 | async 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 | |
| 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 | )] |
| 1048 | async 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 | |
| 1056 | |
| 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 | )] |
| 1069 | async 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)] |
| 1080 | mod tests { |
| 1081 | use super::*; |
| 1082 | |
| 1083 | |
| 1084 | |
| 1085 | |
| 1086 | |
| 1087 | |
| 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 | |
| 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 | |
| 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 | } |