//! Limits on changing a user's own birth data. //! //! The first save is free. Within an hour of it the user may correct the data //! three more times; after that, once per 24 hours. Admins are not limited. use serde_json::{Value, json}; use sqlx::PgConnection; use time::{Duration, OffsetDateTime}; use uuid::Uuid; use crate::auth::AuthUser; use crate::error::ApiError; use crate::views::rfc3339; use db::Role; const GRACE_PERIOD: Duration = Duration::hours(1); const GRACE_CHANGES: usize = 3; const DAILY: Duration = Duration::hours(24); pub const DAILY_NOTICE: &str = "A rendszer csak napi egy módosítást engedélyez."; /// Where a user stands with changing their birth data. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Status { /// The grace period is over (or used up): one change per day. pub daily: bool, /// When the next change is possible; `None`: now. pub next_at: Option, } /// The rule itself, over the times of the earlier saves (oldest first). pub fn evaluate(saves: &[OffsetDateTime], now: OffsetDateTime) -> Status { let (Some(&first), Some(&last)) = (saves.first(), saves.last()) else { return Status { daily: false, next_at: None }; }; let corrections = saves.len() - 1; if now - first < GRACE_PERIOD && corrections < GRACE_CHANGES { return Status { daily: false, next_at: None }; } let next = last + DAILY; Status { daily: true, next_at: (next > now).then_some(next) } } async fn saves(conn: &mut PgConnection, user_id: Uuid) -> Result, ApiError> { let rows: Vec<(OffsetDateTime,)> = sqlx::query_as("SELECT created_at FROM birth_data_changes WHERE user_id = $1 ORDER BY created_at") .bind(user_id) .fetch_all(conn) .await?; Ok(rows.into_iter().map(|(t,)| t).collect()) } /// "23 óra 5 perc" / "40 perc" (rounded up to a minute). fn wait_text(wait: Duration) -> String { let minutes = (wait.whole_seconds() + 59) / 60; let (h, m) = (minutes / 60, minutes % 60); match (h, m) { (0, m) => format!("{m} perc"), (h, 0) => format!("{h} óra"), (h, m) => format!("{h} óra {m} perc"), } } fn limit_error(next_at: OffsetDateTime, now: OffsetDateTime) -> ApiError { ApiError::Limited { code: "birth_data_change_limit", message: format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next_at - now)), } } /// For `/v1/me`: whether the daily limit applies and, if so, the notice to show. pub async fn view(conn: &mut PgConnection, auth: &AuthUser) -> Result { if auth.user.has_role(Role::Admin) { return Ok(json!({ "limited": false, "next_change_at": null, "notice": null })); } let now = OffsetDateTime::now_utc(); let status = evaluate(&saves(conn, auth.id()).await?, now); let notice = match status.next_at { Some(next) => Some(format!("{DAILY_NOTICE} Legközelebb {} múlva módosíthatod.", wait_text(next - now))), None if status.daily => Some(DAILY_NOTICE.to_string()), None => None, }; Ok(json!({ "limited": status.daily, "next_change_at": status.next_at.map(rfc3339), "notice": notice, })) } /// Checks the limit and records the change, inside the transaction that /// makes `chart_id` the user's own chart. Locks the user row, so parallel /// saves are counted one after the other. pub async fn record(tx: &mut PgConnection, auth: &AuthUser, chart_id: Uuid) -> Result<(), ApiError> { sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?; if !auth.user.has_role(Role::Admin) { let now = OffsetDateTime::now_utc(); if let Some(next) = evaluate(&saves(tx, auth.id()).await?, now).next_at { return Err(limit_error(next, now)); } } sqlx::query("INSERT INTO birth_data_changes (id, user_id, chart_id) VALUES ($1, $2, $3)") .bind(Uuid::now_v7()) .bind(auth.id()) .bind(chart_id) .execute(tx) .await?; Ok(()) } #[cfg(test)] mod tests { use super::*; fn at(minutes: i64) -> OffsetDateTime { OffsetDateTime::UNIX_EPOCH + Duration::minutes(minutes) } #[test] fn first_save_is_free() { assert_eq!(evaluate(&[], at(0)), Status { daily: false, next_at: None }); } #[test] fn three_corrections_within_the_first_hour() { let now = at(30); assert_eq!(evaluate(&[at(0)], now).next_at, None); assert_eq!(evaluate(&[at(0), at(5), at(10)], now).next_at, None); // the third correction used up the grace period let s = evaluate(&[at(0), at(5), at(10), at(20)], now); assert!(s.daily); assert_eq!(s.next_at, Some(at(20) + DAILY)); } #[test] fn after_the_first_hour_once_a_day() { assert_eq!(evaluate(&[at(0)], at(61)), Status { daily: true, next_at: Some(at(24 * 60)) }); assert_eq!(evaluate(&[at(0)], at(24 * 60)), Status { daily: true, next_at: None }); assert_eq!(evaluate(&[at(0), at(24 * 60 + 5)], at(30 * 60)).next_at, Some(at(48 * 60 + 5))); } #[test] fn wait_is_written_in_hours_and_minutes() { assert_eq!(wait_text(Duration::minutes(40)), "40 perc"); assert_eq!(wait_text(Duration::hours(3)), "3 óra"); assert_eq!(wait_text(Duration::seconds(23 * 3600 + 4 * 60 + 1)), "23 óra 5 perc"); } }