Files
sorsfonalak/services/backend/src/routes/payments.rs
T

68 lines
2.4 KiB
Rust
Raw Normal View History

//! Packages and payments. Until Stripe is connected, `MOCK_PAYMENTS=true`
//! turns on a stand-in: "paying" grants the package right away, so the paid
//! flow can be used end to end.
use axum::Json;
use axum::extract::State;
use axum_extra::extract::WithRejection;
use serde::Deserialize;
use serde_json::{Value, json};
use super::{Body, St};
use crate::auth::AuthUser;
use crate::credits::{self, Unit};
use crate::error::{ApiError, ApiResult};
use crate::packages::{self, CATALOG, Source};
use crate::persons;
/// The package catalog (public).
pub async fn catalog() -> Json<Value> {
Json(json!({ "packages": CATALOG.iter().map(packages::Package::view).collect::<Vec<_>>() }))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MockPayment {
/// A package id from the catalog.
package: Option<String>,
/// Shorthand: the cheapest package with one unit of this kind.
unit: Option<Unit>,
}
/// What the user has now: units left and person slots.
pub async fn holdings(state: &crate::AppState, auth: &AuthUser) -> Result<Value, ApiError> {
let mut conn = state.db.acquire().await?;
let balance = credits::balance(&mut conn, auth.id()).await?;
let persons = persons::slots(&mut conn, auth, state.config.free_person_slots).await?;
Ok(json!({
"analyses_left": balance.view(),
"persons": persons.view(),
}))
}
/// Grants a package as a (pretend) purchase.
pub async fn mock(
State(state): St,
auth: AuthUser,
WithRejection(Json(req), _): Body<MockPayment>,
) -> ApiResult<Json<Value>> {
if !state.config.mock_payments {
return Err(ApiError::NotFound("payment method"));
}
let id = match (req.package.as_deref(), req.unit) {
(Some(id), None) => id,
(None, Some(Unit::Natal)) => "single",
(None, Some(Unit::Synastry)) => "addon_synastry",
(None, Some(Unit::Forecast)) => "addon_forecast",
(None, Some(Unit::Person)) => "addon_persons",
(None, Some(Unit::Question)) => "addon_questions",
_ => return Err(ApiError::BadRequest("give either package or unit".into())),
};
let package = packages::find(id).ok_or(ApiError::NotFound("package"))?;
let mut tx = state.db.begin().await?;
packages::grant(&mut tx, auth.id(), package, Source::Mock, Some(auth.id()), Some("mock payment")).await?;
tx.commit().await?;
tracing::info!(user = %auth.id(), package = package.id, "mock payment");
Ok(Json(holdings(&state, &auth).await?))
}