web/pages/account/
script.rs1use axum::{
2 Extension,
3 extract::{Path, State},
4 response::IntoResponse,
5};
6use server::command::{CmdResult, script::RunScriptOnAccount};
7use server::script_run::TransactionFailure;
8use sqlx::types::Uuid;
9use std::sync::Arc;
10
11use crate::{AppState, jwt_auth::JWTAuthMiddleware, response::WebError};
12
13pub async fn run_account_script(
14 Path((account_id, script_id)): Path<(Uuid, Uuid)>,
15 State(_data): State<Arc<AppState>>,
16 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
17) -> Result<impl IntoResponse, WebError> {
18 let answer = RunScriptOnAccount::new()
19 .user_id(jwt_auth.user.id)
20 .script_id(script_id)
21 .account_id(account_id)
22 .run()
23 .await?;
24 let Some(CmdResult::ScriptRun(run)) = answer else {
25 return Err(WebError::internal("Script run answered", answer));
26 };
27 if let Some(failure) = run.failures.first() {
28 return Err(script_failure(failure));
29 }
30 Ok(report(&run.ran, &run.committed))
31}
32
33fn report(ran: &[Uuid], committed: &[Uuid]) -> String {
35 let outcome = |id: &Uuid| match committed.contains(id) {
36 true => t!("committed"),
37 false => t!("unchanged"),
38 };
39 [
40 format!("{}: {}", t!("Processed transactions"), ran.len()),
41 format!("{}: {}", t!("Committed transactions"), committed.len()),
42 ]
43 .into_iter()
44 .chain(ran.iter().map(|id| format!("{id}: {}", outcome(id))))
45 .collect::<Vec<_>>()
46 .join("\n")
47}
48
49fn script_failure(failure: &TransactionFailure) -> WebError {
50 WebError::unprocessable(format!(
51 "{}: failed: script {}: {}: {} (nothing was written)",
52 failure.transaction_id, failure.script_id, failure.code, failure.message
53 ))
54}
55
56#[cfg(test)]
57#[path = "script_tests.rs"]
58mod tests;