Admins use analysis units and questions too
They add their own units on the admin page when they need more, and testing shows the same balance as users see. Regenerating and prompt previews stay free. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -31,7 +31,6 @@ use crate::auth::AuthUser;
|
|||||||
use crate::credits::{self, Unit};
|
use crate::credits::{self, Unit};
|
||||||
use crate::error::{ApiError, ApiResult};
|
use crate::error::{ApiError, ApiResult};
|
||||||
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
use crate::views::{rfc3339, rfc3339_opt, sha256_hex};
|
||||||
use db::Role;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, sqlx::FromRow)]
|
#[derive(Debug, Clone, sqlx::FromRow)]
|
||||||
/// An analysis as users see it; the model is left out on purpose (a business secret).
|
/// An analysis as users see it; the model is left out on purpose (a business secret).
|
||||||
@@ -136,10 +135,8 @@ async fn request(
|
|||||||
req: AnalysisRequest,
|
req: AnalysisRequest,
|
||||||
) -> ApiResult<(StatusCode, Json<Value>)> {
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
||||||
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
let language = validate_locale(state, Some(req.language.as_deref().unwrap_or(&auth.user.locale)))?;
|
||||||
// Admins use no unit.
|
// Admins use units too (they can add more on the admin page).
|
||||||
let admin = auth.user.has_role(Role::Admin);
|
|
||||||
let unit = match target {
|
let unit = match target {
|
||||||
_ if admin => None,
|
|
||||||
Target::Synastry { .. } => Some(Unit::Synastry),
|
Target::Synastry { .. } => Some(Unit::Synastry),
|
||||||
Target::Forecast { .. } => Some(Unit::Forecast),
|
Target::Forecast { .. } => Some(Unit::Forecast),
|
||||||
_ => Some(Unit::Natal),
|
_ => Some(Unit::Natal),
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ use axum::Json;
|
|||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use axum_extra::extract::WithRejection;
|
use axum_extra::extract::WithRejection;
|
||||||
use db::Role;
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
use sqlx::PgPool;
|
use sqlx::PgPool;
|
||||||
@@ -145,7 +144,6 @@ pub async fn ask(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let admin = auth.user.has_role(Role::Admin);
|
|
||||||
let (model, fallback, prompt_version) = model_and_version(&state, &analysis.language).await?;
|
let (model, fallback, prompt_version) = model_and_version(&state, &analysis.language).await?;
|
||||||
let question_id = Uuid::now_v7();
|
let question_id = Uuid::now_v7();
|
||||||
let mut tx = state.db.begin().await?;
|
let mut tx = state.db.begin().await?;
|
||||||
@@ -161,13 +159,12 @@ pub async fn ask(
|
|||||||
.bind(&analysis.language)
|
.bind(&analysis.language)
|
||||||
.bind(&model)
|
.bind(&model)
|
||||||
.bind(&prompt_version)
|
.bind(&prompt_version)
|
||||||
.bind(i32::from(!admin))
|
.bind(1i32)
|
||||||
.bind(&fallback)
|
.bind(&fallback)
|
||||||
.fetch_one(&mut *tx)
|
.fetch_one(&mut *tx)
|
||||||
.await?;
|
.await?;
|
||||||
if !admin {
|
// Admins use questions too (they can add more on the admin page).
|
||||||
credits::spend_question(&mut tx, auth.id(), question_id).await?;
|
credits::spend_question(&mut tx, auth.id(), question_id).await?;
|
||||||
}
|
|
||||||
tx.commit().await?;
|
tx.commit().await?;
|
||||||
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -277,6 +277,15 @@ impl TestApp {
|
|||||||
r.body["session"]["token"].as_str().unwrap().to_string()
|
r.body["session"]["token"].as_str().unwrap().to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// An admin adds units to their own account (admins use units too).
|
||||||
|
async fn add_own_units(&self, admin: &str, unit: &str, delta: i32) {
|
||||||
|
let id = self.get("/v1/me", Some(admin)).await.body["user"]["id"].as_str().unwrap().to_string();
|
||||||
|
let r = self
|
||||||
|
.post(&format!("/v1/admin/users/{id}/credits"), Some(admin), json!({"unit": unit, "delta": delta}))
|
||||||
|
.await;
|
||||||
|
assert!(r.status.is_success(), "{}", r.body);
|
||||||
|
}
|
||||||
|
|
||||||
async fn chart(&self, token: &str, label: &str, primary: bool, date: &str) -> Value {
|
async fn chart(&self, token: &str, label: &str, primary: bool, date: &str) -> Value {
|
||||||
let r = self
|
let r = self
|
||||||
.post(
|
.post(
|
||||||
@@ -1061,13 +1070,18 @@ async fn birth_data_changes_are_limited(pool: PgPool) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrator = "db::MIGRATOR")]
|
#[sqlx::test(migrator = "db::MIGRATOR")]
|
||||||
async fn admins_get_free_analyses_and_mock_payments_add_units(pool: PgPool) {
|
async fn admins_use_units_too_and_mock_payments_add_units(pool: PgPool) {
|
||||||
let app = TestApp::new(pool).await;
|
let app = TestApp::new(pool).await;
|
||||||
let admin = app.register("admin@example.com", "Admin").await;
|
let admin = app.register("admin@example.com", "Admin").await;
|
||||||
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||||
let r =
|
let analyses = format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap());
|
||||||
app.call("POST", &format!("/v1/charts/{}/analyses", chart["id"].as_str().unwrap()), Some(&admin), None).await;
|
// Admins pay with units like everyone (they add their own on the admin page).
|
||||||
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(0)), "{}", r.body);
|
let r = app.call("POST", &analyses, Some(&admin), None).await;
|
||||||
|
assert_eq!(r.status, StatusCode::PAYMENT_REQUIRED, "{}", r.body);
|
||||||
|
app.add_own_units(&admin, "natal", 2).await;
|
||||||
|
let r = app.call("POST", &analyses, Some(&admin), None).await;
|
||||||
|
assert_eq!((r.status, &r.body["credits_charged"]), (StatusCode::ACCEPTED, &json!(1)), "{}", r.body);
|
||||||
|
assert_eq!(app.get("/v1/credits", Some(&admin)).await.body["balance"]["natal"], 1);
|
||||||
|
|
||||||
// a user "pays", which adds a unit, then requests the analysis
|
// a user "pays", which adds a unit, then requests the analysis
|
||||||
let anna = app.register("anna@example.com", "Anna").await;
|
let anna = app.register("anna@example.com", "Anna").await;
|
||||||
@@ -1750,6 +1764,7 @@ async fn admins_choose_the_model_of_each_function(pool: PgPool) {
|
|||||||
assert_eq!((r.status, &r.body["model"], &r.body["custom"]), (StatusCode::OK, &json!("openai/gpt-x"), &json!(true)));
|
assert_eq!((r.status, &r.body["model"], &r.body["custom"]), (StatusCode::OK, &json!("openai/gpt-x"), &json!(true)));
|
||||||
|
|
||||||
// new analyses use it; regenerating writes it again in place with the current model
|
// new analyses use it; regenerating writes it again in place with the current model
|
||||||
|
app.add_own_units(&admin, "natal", 1).await;
|
||||||
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||||
let chart_id = chart["id"].as_str().unwrap();
|
let chart_id = chart["id"].as_str().unwrap();
|
||||||
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
|
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
|
||||||
@@ -1880,6 +1895,7 @@ async fn admins_restart_open_generations_with_the_current_models(pool: PgPool) {
|
|||||||
async move { app.call("PUT", "/v1/admin/models/analysis", Some(admin), Some(body)).await }
|
async move { app.call("PUT", "/v1/admin/models/analysis", Some(admin), Some(body)).await }
|
||||||
};
|
};
|
||||||
assert_eq!(put("openai/gpt-x").await.status, StatusCode::OK);
|
assert_eq!(put("openai/gpt-x").await.status, StatusCode::OK);
|
||||||
|
app.add_own_units(&admin, "natal", 1).await;
|
||||||
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
let chart = app.chart(&admin, "Saját", true, "1990-03-15").await;
|
||||||
let chart_id = chart["id"].as_str().unwrap();
|
let chart_id = chart["id"].as_str().unwrap();
|
||||||
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
|
let r = app.post(&format!("/v1/charts/{chart_id}/analyses"), Some(&admin), json!({})).await;
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ export function AnalysisQuestions({
|
|||||||
setBuying(false);
|
setBuying(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
const canAsk = isAdmin || left > 0;
|
const canAsk = left > 0;
|
||||||
return (
|
return (
|
||||||
<section className="questions" aria-labelledby={`${fieldId}-title`}>
|
<section className="questions" aria-labelledby={`${fieldId}-title`}>
|
||||||
<h3 id={`${fieldId}-title`}>{TEXTS[about].title}</h3>
|
<h3 id={`${fieldId}-title`}>{TEXTS[about].title}</h3>
|
||||||
@@ -196,11 +196,7 @@ export function AnalysisQuestions({
|
|||||||
{busy ? "Küldés…" : "Kérdés küldése"}
|
{busy ? "Küldés…" : "Kérdés küldése"}
|
||||||
</button>
|
</button>
|
||||||
<span className="hint">
|
<span className="hint">
|
||||||
{waiting
|
{waiting ? "Várd meg az előző válaszát." : `Még ${left} kérdésed van.`}{" "}
|
||||||
? "Várd meg az előző válaszát."
|
|
||||||
: isAdmin
|
|
||||||
? "Adminként ingyenes."
|
|
||||||
: `Még ${left} kérdésed van.`}{" "}
|
|
||||||
{text.length > MAX_CHARS - 100 && `${text.length}/${MAX_CHARS}`}
|
{text.length > MAX_CHARS - 100 && `${text.length}/${MAX_CHARS}`}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ export function DetailedAnalysis({
|
|||||||
<div className="msg msg-error" role="alert">
|
<div className="msg msg-error" role="alert">
|
||||||
<p style={{ margin: 0 }}>
|
<p style={{ margin: 0 }}>
|
||||||
Az elemzés többszöri próbálkozás után sem készült el.
|
Az elemzés többszöri próbálkozás után sem készült el.
|
||||||
{isAdmin || analysis.credits_charged === 0
|
{analysis.credits_charged === 0
|
||||||
? " Próbáld újra."
|
? " Próbáld újra."
|
||||||
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
|
: " A felhasznált egységet visszaadtuk, így ingyen újra kérheted."}
|
||||||
</p>
|
</p>
|
||||||
@@ -211,14 +211,7 @@ export function DetailedAnalysis({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isAdmin ? (
|
{left > 0 ? (
|
||||||
<div className="form-actions">
|
|
||||||
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
|
|
||||||
{busy ? "Indítás…" : `${t.item} készítése`}
|
|
||||||
</button>
|
|
||||||
<span className="hint">Adminként ingyenes.</span>
|
|
||||||
</div>
|
|
||||||
) : left > 0 ? (
|
|
||||||
step === "confirm" ? (
|
step === "confirm" ? (
|
||||||
<div className="form-actions">
|
<div className="form-actions">
|
||||||
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
|
<button type="button" className="btn btn-primary" onClick={start} disabled={busy}>
|
||||||
|
|||||||
Reference in New Issue
Block a user