1
use axum::{
2
    Extension,
3
    extract::{Path, State},
4
    response::IntoResponse,
5
};
6
use server::command::{CmdResult, script::RunScriptOnAccount};
7
use server::script_run::TransactionFailure;
8
use sqlx::types::Uuid;
9
use std::sync::Arc;
10

            
11
use crate::{AppState, jwt_auth::JWTAuthMiddleware, response::WebError};
12

            
13
5
pub async fn run_account_script(
14
5
    Path((account_id, script_id)): Path<(Uuid, Uuid)>,
15
5
    State(_data): State<Arc<AppState>>,
16
5
    Extension(jwt_auth): Extension<JWTAuthMiddleware>,
17
5
) -> Result<impl IntoResponse, WebError> {
18
5
    let answer = RunScriptOnAccount::new()
19
5
        .user_id(jwt_auth.user.id)
20
5
        .script_id(script_id)
21
5
        .account_id(account_id)
22
5
        .run()
23
5
        .await?;
24
3
    let Some(CmdResult::ScriptRun(run)) = answer else {
25
        return Err(WebError::internal("Script run answered", answer));
26
    };
27
3
    if let Some(failure) = run.failures.first() {
28
1
        return Err(script_failure(failure));
29
2
    }
30
2
    Ok(report(&run.ran, &run.committed))
31
5
}
32

            
33
/// The committed report: one line per transaction the script ran on.
34
4
fn report(ran: &[Uuid], committed: &[Uuid]) -> String {
35
8
    let outcome = |id: &Uuid| match committed.contains(id) {
36
5
        true => t!("committed"),
37
3
        false => t!("unchanged"),
38
8
    };
39
    [
40
4
        format!("{}: {}", t!("Processed transactions"), ran.len()),
41
4
        format!("{}: {}", t!("Committed transactions"), committed.len()),
42
    ]
43
    .into_iter()
44
8
    .chain(ran.iter().map(|id| format!("{id}: {}", outcome(id))))
45
    .collect::<Vec<_>>()
46
4
    .join("\n")
47
4
}
48

            
49
3
fn script_failure(failure: &TransactionFailure) -> WebError {
50
3
    WebError::unprocessable(format!(
51
3
        "{}: failed: script {}: {}: {} (nothing was written)",
52
3
        failure.transaction_id, failure.script_id, failure.code, failure.message
53
3
    ))
54
3
}
55

            
56
#[cfg(test)]
57
#[path = "script_tests.rs"]
58
mod tests;