//! Editable system prompts of the analyses (admin only). //! //! Every save adds a row to `prompt_revisions`; the newest row of a //! (kind, language) is in force, `system` NULL meaning the built-in text. //! New analyses record the revision in `prompt_version`, so analyses that //! are already written or queued keep the text they were started with. use analysis_prompt::{Kind, default_system, user_template}; use axum::Json; use axum::extract::{Path, State}; use axum_extra::extract::WithRejection; use serde::Deserialize; use serde_json::{Value, json}; use sqlx::PgPool; use time::OffsetDateTime; use super::{Body, St}; use crate::AppState; use crate::auth::AdminUser; use crate::error::{ApiError, ApiResult}; use crate::views::rfc3339; /// The kinds whose prompt the admin page edits. const EDITABLE: [Kind; 2] = [Kind::Summary, Kind::Natal]; const MAX_CHARS: usize = 50_000; const HISTORY: i64 = 20; /// The revision id of an admin-edited prompt in force, `None` for the built-in one. pub async fn current_revision(db: &PgPool, kind: &str, language: &str) -> Result, sqlx::Error> { let row: Option<(i64, bool)> = sqlx::query_as( "SELECT id, system IS NOT NULL FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1", ) .bind(kind) .bind(language) .fetch_optional(db) .await?; Ok(row.filter(|(_, custom)| *custom).map(|(id, _)| id)) } type RevisionRow = (i64, Option, OffsetDateTime, Option); async fn entry(db: &PgPool, kind: Kind, language: &str) -> Result { let rows: Vec = sqlx::query_as( "SELECT r.id, r.system, r.created_at, u.email FROM prompt_revisions r \ LEFT JOIN users u ON u.id = r.created_by \ WHERE r.kind = $1 AND r.language = $2 ORDER BY r.id DESC LIMIT $3", ) .bind(kind.as_str()) .bind(language) .bind(HISTORY) .fetch_all(db) .await?; let default = default_system(kind, language); let current = rows.first(); let history: Vec = rows .iter() .map(|(id, system, at, by)| { json!({"id": id, "custom": system.is_some(), "system": system, "created_at": rfc3339(*at), "created_by": by}) }) .collect(); Ok(json!({ "kind": kind.as_str(), "language": language, "system": current.and_then(|r| r.1.clone()).unwrap_or_else(|| default.clone()), "custom": current.is_some_and(|r| r.1.is_some()), "updated_at": current.map(|r| rfc3339(r.2)), "updated_by": current.and_then(|r| r.3.clone()), "default": default, "user_template": user_template(kind), "history": history, })) } pub async fn list(State(state): St, _admin: AdminUser) -> ApiResult> { let mut prompts = Vec::new(); for kind in EDITABLE { for language in &state.config.supported_locales { prompts.push(entry(&state.db, kind, language).await?); } } Ok(Json(json!({ "prompts": prompts }))) } #[derive(Deserialize)] #[serde(deny_unknown_fields)] pub struct SavePrompt { /// The new system prompt; `null` restores the built-in one. system: Option, } fn parse_target(state: &AppState, kind: &str, language: &str) -> Result { let kind = Kind::parse(kind).filter(|k| EDITABLE.contains(k)).ok_or(ApiError::NotFound("prompt"))?; if !state.config.supported_locales.iter().any(|l| l == language) { return Err(ApiError::NotFound("prompt")); } Ok(kind) } pub async fn save( State(state): St, AdminUser(admin): AdminUser, WithRejection(Path((kind, language)), _): WithRejection, ApiError>, WithRejection(Json(req), _): Body, ) -> ApiResult> { let kind = parse_target(&state, &kind, &language)?; let default = default_system(kind, &language); // The built-in text is stored as NULL, so later code changes reach it. let system = match req.system.map(|s| s.trim().replace("\r\n", "\n")) { Some(s) if s.is_empty() => return Err(ApiError::BadRequest("the prompt must not be empty".into())), Some(s) if s.chars().count() > MAX_CHARS => { return Err(ApiError::BadRequest(format!("the prompt is longer than {MAX_CHARS} characters"))); } Some(s) if s == default.trim() => None, other => other, }; let current: Option<(Option,)> = sqlx::query_as( "SELECT system FROM prompt_revisions WHERE kind = $1 AND language = $2 ORDER BY id DESC LIMIT 1", ) .bind(kind.as_str()) .bind(&language) .fetch_optional(&state.db) .await?; let unchanged = match ¤t { Some((text,)) => *text == system, None => system.is_none(), }; if !unchanged { sqlx::query("INSERT INTO prompt_revisions (kind, language, system, created_by) VALUES ($1, $2, $3, $4)") .bind(kind.as_str()) .bind(&language) .bind(&system) .bind(admin.id()) .execute(&state.db) .await?; tracing::info!(admin = %admin.id(), kind = kind.as_str(), %language, custom = system.is_some(), "prompt changed"); } Ok(Json(entry(&state.db, kind, &language).await?)) }