Files
sorsfonalak/services/backend/src/persons.rs
T

93 lines
3.6 KiB
Rust
Raw Normal View History

//! Persons: charts of other people (name and birth data) a user adds next to
//! their own. Each new person uses one `person` unit, bought in packages;
//! deleting a person does not give it back. The `unlimited_persons`
//! entitlement, a running unlimited package and admins have no limit.
//!
//! A person's birth data can be corrected within an hour of adding them,
//! then it is locked (admins: any time).
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::{Duration, OffsetDateTime};
use uuid::Uuid;
use crate::auth::AuthUser;
use crate::error::ApiError;
use db::Role;
/// How long after adding a person their birth data can be corrected.
pub const EDIT_WINDOW: Duration = Duration::hours(1);
pub const LIMIT_MESSAGE: &str = "Elérted a felvehető személyek számát. További személyekhez bővítsd a csomagodat.";
pub const LOCKED_MESSAGE: &str = "A személy születési adatai csak a felvételt követő egy órán belül javíthatók.";
/// A user's person slots.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Slots {
/// Persons added so far (deleted ones included).
pub used: i64,
/// Free slots plus the bought (or granted) ones.
pub granted: i64,
pub unlimited: bool,
}
impl Slots {
/// Slots left; `None`: no limit.
pub fn left(self) -> Option<i64> {
(!self.unlimited).then(|| (self.granted - self.used).max(0))
}
pub fn view(self) -> Value {
json!({
"used": self.used,
"limit": (!self.unlimited).then_some(self.granted),
"left": self.left(),
"unlimited": self.unlimited,
})
}
}
pub async fn slots(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<Slots, ApiError> {
let (used, bought, entitled): (i64, i64, bool) = sqlx::query_as(
"SELECT \
(SELECT COUNT(*) FROM credit_ledger WHERE user_id = $1 AND unit = 'person' AND reason = 'person'), \
(SELECT COALESCE(SUM(delta), 0)::bigint FROM credit_ledger \
WHERE user_id = $1 AND unit = 'person' AND reason <> 'person'), \
EXISTS (SELECT 1 FROM entitlements WHERE user_id = $1 \
AND (entitlement = 'unlimited_persons' OR (entitlement = 'unlimited' AND expires_at > now())))",
)
.bind(auth.id())
.fetch_one(conn)
.await?;
Ok(Slots { used, granted: free + bought, unlimited: entitled || auth.user.has_role(Role::Admin) })
}
/// Fails when no slot is left (a quick check before calculating a chart).
pub async fn check(conn: &mut PgConnection, auth: &AuthUser, free: i64) -> Result<(), ApiError> {
if slots(conn, auth, free).await?.left() == Some(0) {
return Err(ApiError::conflict("person_limit_reached", LIMIT_MESSAGE));
}
Ok(())
}
/// Uses a slot for the new person `chart_id`, inside the transaction that
/// saves it. The user row is locked, so parallel saves cannot overspend.
pub async fn spend(tx: &mut PgConnection, auth: &AuthUser, free: i64, chart_id: Uuid) -> Result<(), ApiError> {
sqlx::query("SELECT id FROM users WHERE id = $1 FOR UPDATE").bind(auth.id()).execute(&mut *tx).await?;
check(tx, auth, free).await?;
sqlx::query(
"INSERT INTO credit_ledger (id, user_id, unit, delta, reason, chart_id) VALUES ($1, $2, 'person', -1, 'person', $3)",
)
.bind(Uuid::now_v7())
.bind(auth.id())
.bind(chart_id)
.execute(tx)
.await?;
Ok(())
}
/// Whether the birth data of a person added at `created_at` can still be corrected.
pub fn editable(auth: &AuthUser, created_at: OffsetDateTime, now: OffsetDateTime) -> bool {
auth.user.has_role(Role::Admin) || now - created_at < EDIT_WINDOW
}