2026-11-18 18:44:20 +00:00
|
|
|
//! Questions about a finished detailed analysis: a natal chart analysis or a
|
|
|
|
|
//! yearly forecast. Each question uses a `question` unit (admins ask for
|
2026-11-18 21:11:08 +00:00
|
|
|
//! free). The worker answers with the question model of the admin page,
|
|
|
|
|
//! seeing the chart data, the analysis and the earlier questions about it.
|
2026-11-18 18:44:20 +00:00
|
|
|
|
|
|
|
|
use analysis_prompt::{Kind, QUESTION_MAX_CHARS};
|
|
|
|
|
use axum::Json;
|
|
|
|
|
use axum::extract::{Path, State};
|
|
|
|
|
use axum::http::StatusCode;
|
|
|
|
|
use axum_extra::extract::WithRejection;
|
|
|
|
|
use db::Role;
|
|
|
|
|
use serde::Deserialize;
|
|
|
|
|
use serde_json::{Value, json};
|
|
|
|
|
use sqlx::PgPool;
|
|
|
|
|
use time::OffsetDateTime;
|
|
|
|
|
use uuid::Uuid;
|
|
|
|
|
|
|
|
|
|
use super::analyses::{can_see, find_analysis};
|
|
|
|
|
use super::{Body, IdPath, St};
|
|
|
|
|
use crate::auth::{AdminUser, AuthUser};
|
|
|
|
|
use crate::credits;
|
|
|
|
|
use crate::error::{ApiError, ApiResult};
|
|
|
|
|
use crate::views::{rfc3339, rfc3339_opt};
|
|
|
|
|
|
|
|
|
|
/// The analyses that can be asked about.
|
|
|
|
|
const ASKABLE: [&str; 2] = ["natal", "forecast"];
|
|
|
|
|
/// A safety cap per analysis.
|
|
|
|
|
const MAX_PER_ANALYSIS: i64 = 100;
|
|
|
|
|
|
|
|
|
|
/// A question as users see it (the model is left out on purpose).
|
|
|
|
|
#[derive(Debug, sqlx::FromRow)]
|
|
|
|
|
pub struct QuestionRow {
|
|
|
|
|
pub id: Uuid,
|
|
|
|
|
pub analysis_id: Uuid,
|
|
|
|
|
pub question: String,
|
|
|
|
|
pub status: String,
|
|
|
|
|
pub answer: Option<String>,
|
|
|
|
|
pub error: Option<String>,
|
|
|
|
|
pub credits_charged: i32,
|
|
|
|
|
pub created_at: OffsetDateTime,
|
|
|
|
|
pub completed_at: Option<OffsetDateTime>,
|
2026-11-18 21:47:37 +00:00
|
|
|
pub attempts: i32,
|
|
|
|
|
pub next_attempt_at: OffsetDateTime,
|
|
|
|
|
pub requested_at: OffsetDateTime,
|
2026-11-18 18:44:20 +00:00
|
|
|
}
|
|
|
|
|
|
2026-11-18 21:47:37 +00:00
|
|
|
const QUESTION_COLUMNS: &str = "id, analysis_id, question, status, answer, error, credits_charged, created_at, \
|
|
|
|
|
completed_at, attempts, next_attempt_at, requested_at";
|
2026-11-18 18:44:20 +00:00
|
|
|
|
|
|
|
|
impl QuestionRow {
|
|
|
|
|
pub fn view(&self) -> Value {
|
|
|
|
|
json!({
|
|
|
|
|
"id": self.id,
|
|
|
|
|
"analysis_id": self.analysis_id,
|
|
|
|
|
"question": self.question,
|
|
|
|
|
"status": self.status,
|
|
|
|
|
"answer": self.answer,
|
|
|
|
|
"error": self.error,
|
|
|
|
|
"credits_charged": self.credits_charged,
|
|
|
|
|
"created_at": rfc3339(self.created_at),
|
|
|
|
|
"completed_at": rfc3339_opt(self.completed_at),
|
2026-11-18 21:47:37 +00:00
|
|
|
"attempts": self.attempts,
|
|
|
|
|
"next_attempt_at": rfc3339(self.next_attempt_at),
|
|
|
|
|
"requested_at": rfc3339(self.requested_at),
|
2026-11-18 18:44:20 +00:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async fn find_question(db: &PgPool, id: Uuid) -> Result<Option<QuestionRow>, sqlx::Error> {
|
|
|
|
|
sqlx::query_as(&format!("SELECT {QUESTION_COLUMNS} FROM questions WHERE id = $1")).bind(id).fetch_optional(db).await
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-18 21:11:08 +00:00
|
|
|
/// The question model (and its fallback) and the version of the question
|
|
|
|
|
/// prompt in force.
|
2026-11-18 21:31:09 +00:00
|
|
|
pub(super) async fn model_and_version(
|
2026-11-18 18:44:20 +00:00
|
|
|
state: &crate::AppState,
|
|
|
|
|
language: &str,
|
2026-11-18 21:11:08 +00:00
|
|
|
) -> Result<(String, Option<String>, String), sqlx::Error> {
|
|
|
|
|
let (model, fallback) = crate::models::models_for(state, Kind::Question).await?;
|
2026-11-18 18:44:20 +00:00
|
|
|
let base = &state.config.prompt_version;
|
|
|
|
|
let version = match super::prompts::current_revision(&state.db, Kind::Question.as_str(), language).await? {
|
|
|
|
|
Some(id) => format!("{base}-r{id}"),
|
|
|
|
|
None => base.clone(),
|
|
|
|
|
};
|
2026-11-18 21:11:08 +00:00
|
|
|
Ok((model, fallback, version))
|
2026-11-18 18:44:20 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn list(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
|
|
|
|
let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
|
|
|
|
if !can_see(&state.db, &analysis, auth.id()).await? {
|
|
|
|
|
return Err(ApiError::NotFound("analysis"));
|
|
|
|
|
}
|
|
|
|
|
let rows: Vec<QuestionRow> =
|
|
|
|
|
sqlx::query_as(&format!("SELECT {QUESTION_COLUMNS} FROM questions WHERE analysis_id = $1 ORDER BY created_at"))
|
|
|
|
|
.bind(id)
|
|
|
|
|
.fetch_all(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
Ok(Json(json!({ "questions": rows.iter().map(QuestionRow::view).collect::<Vec<_>>() })))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Deserialize)]
|
|
|
|
|
#[serde(deny_unknown_fields)]
|
|
|
|
|
pub struct AskQuestion {
|
|
|
|
|
question: String,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn ask(
|
|
|
|
|
State(state): St,
|
|
|
|
|
auth: AuthUser,
|
|
|
|
|
WithRejection(Path(id), _): IdPath,
|
|
|
|
|
WithRejection(Json(req), _): Body<AskQuestion>,
|
|
|
|
|
) -> ApiResult<(StatusCode, Json<Value>)> {
|
|
|
|
|
let analysis = find_analysis(&state.db, id).await?.ok_or(ApiError::NotFound("analysis"))?;
|
|
|
|
|
if !can_see(&state.db, &analysis, auth.id()).await? {
|
|
|
|
|
return Err(ApiError::NotFound("analysis"));
|
|
|
|
|
}
|
|
|
|
|
if !ASKABLE.contains(&analysis.kind.as_str()) {
|
|
|
|
|
return Err(ApiError::BadRequest("questions can be asked about a natal analysis or a forecast".into()));
|
|
|
|
|
}
|
|
|
|
|
if analysis.status != "done" {
|
|
|
|
|
return Err(ApiError::conflict("analysis_not_ready", "Az elemzés még nem készült el."));
|
|
|
|
|
}
|
|
|
|
|
let question = req.question.trim().replace("\r\n", "\n");
|
|
|
|
|
let length = question.chars().count();
|
|
|
|
|
if !(3..=QUESTION_MAX_CHARS).contains(&length) {
|
|
|
|
|
return Err(ApiError::BadRequest(format!("the question must be 3 to {QUESTION_MAX_CHARS} characters long")));
|
|
|
|
|
}
|
|
|
|
|
let (open, total): (i64, i64) = sqlx::query_as(
|
|
|
|
|
"SELECT count(*) FILTER (WHERE status IN ('pending', 'running')), count(*) FROM questions WHERE analysis_id = $1",
|
|
|
|
|
)
|
|
|
|
|
.bind(id)
|
|
|
|
|
.fetch_one(&state.db)
|
|
|
|
|
.await?;
|
|
|
|
|
if open > 0 {
|
|
|
|
|
return Err(ApiError::conflict(
|
|
|
|
|
"question_in_progress",
|
|
|
|
|
"Az előző kérdésedre még készül a válasz. Várd meg, és utána kérdezz újra.",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
if total >= MAX_PER_ANALYSIS {
|
|
|
|
|
return Err(ApiError::conflict(
|
|
|
|
|
"question_limit_reached",
|
|
|
|
|
"Ehhez az elemzéshez már nem lehet több kérdést feltenni.",
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let admin = auth.user.has_role(Role::Admin);
|
2026-11-18 21:11:08 +00:00
|
|
|
let (model, fallback, prompt_version) = model_and_version(&state, &analysis.language).await?;
|
2026-11-18 18:44:20 +00:00
|
|
|
let question_id = Uuid::now_v7();
|
|
|
|
|
let mut tx = state.db.begin().await?;
|
|
|
|
|
let row: QuestionRow = sqlx::query_as(&format!(
|
2026-11-18 21:11:08 +00:00
|
|
|
"INSERT INTO questions (id, analysis_id, asked_by, question, language, model, prompt_version, credits_charged, \
|
|
|
|
|
fallback_model) \
|
|
|
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING {QUESTION_COLUMNS}"
|
2026-11-18 18:44:20 +00:00
|
|
|
))
|
|
|
|
|
.bind(question_id)
|
|
|
|
|
.bind(id)
|
|
|
|
|
.bind(auth.id())
|
|
|
|
|
.bind(&question)
|
|
|
|
|
.bind(&analysis.language)
|
|
|
|
|
.bind(&model)
|
|
|
|
|
.bind(&prompt_version)
|
|
|
|
|
.bind(i32::from(!admin))
|
2026-11-18 21:11:08 +00:00
|
|
|
.bind(&fallback)
|
2026-11-18 18:44:20 +00:00
|
|
|
.fetch_one(&mut *tx)
|
|
|
|
|
.await?;
|
|
|
|
|
if !admin {
|
|
|
|
|
credits::spend_question(&mut tx, auth.id(), question_id).await?;
|
|
|
|
|
}
|
|
|
|
|
tx.commit().await?;
|
|
|
|
|
Ok((StatusCode::ACCEPTED, Json(row.view())))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub async fn get_one(State(state): St, auth: AuthUser, WithRejection(Path(id), _): IdPath) -> ApiResult<Json<Value>> {
|
|
|
|
|
let row = find_question(&state.db, id).await?.ok_or(ApiError::NotFound("question"))?;
|
|
|
|
|
let analysis = find_analysis(&state.db, row.analysis_id).await?.ok_or(ApiError::NotFound("question"))?;
|
|
|
|
|
if !can_see(&state.db, &analysis, auth.id()).await? {
|
|
|
|
|
return Err(ApiError::NotFound("question"));
|
|
|
|
|
}
|
|
|
|
|
Ok(Json(row.view()))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Admin: answers a question again in place, with the current question prompt
|
2026-11-18 21:11:08 +00:00
|
|
|
/// and model. Nobody is charged.
|
2026-11-18 18:44:20 +00:00
|
|
|
pub async fn regenerate(
|
|
|
|
|
State(state): St,
|
|
|
|
|
_admin: AdminUser,
|
|
|
|
|
WithRejection(Path(id), _): IdPath,
|
|
|
|
|
) -> ApiResult<Json<Value>> {
|
2026-11-18 21:11:08 +00:00
|
|
|
let language: String = sqlx::query_scalar("SELECT language FROM questions WHERE id = $1")
|
|
|
|
|
.bind(id)
|
|
|
|
|
.fetch_optional(&state.db)
|
|
|
|
|
.await?
|
|
|
|
|
.ok_or(ApiError::NotFound("question"))?;
|
|
|
|
|
let (model, fallback, prompt_version) = model_and_version(&state, &language).await?;
|
2026-11-18 18:44:20 +00:00
|
|
|
let mut tx = state.db.begin().await?;
|
|
|
|
|
let row: QuestionRow = sqlx::query_as(&format!(
|
|
|
|
|
"UPDATE questions SET status = 'pending', answer = NULL, error = NULL, model_used = NULL, input_tokens = NULL, \
|
|
|
|
|
output_tokens = NULL, cost_usd = NULL, attempts = 0, next_attempt_at = now(), started_at = NULL, \
|
2026-11-18 21:47:37 +00:00
|
|
|
completed_at = NULL, model = $2, prompt_version = $3, fallback_model = $4, on_fallback = false, \
|
|
|
|
|
requested_at = now() \
|
2026-11-18 18:44:20 +00:00
|
|
|
WHERE id = $1 AND status IN ('done', 'failed') RETURNING {QUESTION_COLUMNS}"
|
|
|
|
|
))
|
|
|
|
|
.bind(id)
|
|
|
|
|
.bind(&model)
|
|
|
|
|
.bind(&prompt_version)
|
2026-11-18 21:11:08 +00:00
|
|
|
.bind(&fallback)
|
2026-11-18 18:44:20 +00:00
|
|
|
.fetch_optional(&mut *tx)
|
|
|
|
|
.await?
|
|
|
|
|
.ok_or_else(|| ApiError::conflict("question_in_progress", "Erre a kérdésre éppen készül a válasz."))?;
|
|
|
|
|
sqlx::query("SELECT pg_notify('analyses', '')").execute(&mut *tx).await?;
|
|
|
|
|
tx.commit().await?;
|
|
|
|
|
Ok(Json(row.view()))
|
|
|
|
|
}
|