2025-10-11 20:25:08 -03:00
|
|
|
use diesel::prelude::*;
|
2025-10-06 10:30:17 -03:00
|
|
|
use log::info;
|
|
|
|
|
use rhai::Dynamic;
|
|
|
|
|
use rhai::Engine;
|
|
|
|
|
use serde_json::{json, Value};
|
|
|
|
|
|
2025-10-06 20:49:38 -03:00
|
|
|
use crate::shared::models::TriggerKind;
|
2025-10-11 12:29:03 -03:00
|
|
|
use crate::shared::models::UserSession;
|
2025-10-11 20:25:08 -03:00
|
|
|
use crate::shared::state::AppState;
|
2025-10-06 10:30:17 -03:00
|
|
|
|
2025-10-11 20:25:08 -03:00
|
|
|
pub fn set_schedule_keyword(state: &AppState, _user: UserSession, engine: &mut Engine) {
|
2025-10-11 12:29:03 -03:00
|
|
|
let state_clone = state.clone();
|
2025-10-06 10:30:17 -03:00
|
|
|
|
|
|
|
|
engine
|
2025-10-11 20:02:14 -03:00
|
|
|
.register_custom_syntax(&["SET_SCHEDULE", "$string$"], true, {
|
2025-10-06 10:30:17 -03:00
|
|
|
move |context, inputs| {
|
|
|
|
|
let cron = context.eval_expression_tree(&inputs[0])?.to_string();
|
2025-10-16 11:43:02 -03:00
|
|
|
let param = format!("cron_{}.rhai", cron.replace(' ', "_"));
|
2025-10-06 10:30:17 -03:00
|
|
|
|
2025-10-11 20:25:08 -03:00
|
|
|
let mut conn = state_clone.conn.lock().unwrap();
|
2025-10-16 11:43:02 -03:00
|
|
|
let result = execute_set_schedule(&mut *conn, &cron, ¶m)
|
2025-10-11 12:29:03 -03:00
|
|
|
.map_err(|e| format!("DB error: {}", e))?;
|
2025-10-06 10:30:17 -03:00
|
|
|
|
|
|
|
|
if let Some(rows_affected) = result.get("rows_affected") {
|
|
|
|
|
Ok(Dynamic::from(rows_affected.as_i64().unwrap_or(0)))
|
|
|
|
|
} else {
|
|
|
|
|
Err("No rows affected".into())
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.unwrap();
|
|
|
|
|
}
|
|
|
|
|
|
2025-10-11 12:29:03 -03:00
|
|
|
pub fn execute_set_schedule(
|
2025-10-11 20:25:08 -03:00
|
|
|
conn: &mut diesel::PgConnection,
|
2025-10-06 10:30:17 -03:00
|
|
|
cron: &str,
|
2025-10-16 11:43:02 -03:00
|
|
|
param: &str,
|
2025-10-06 10:30:17 -03:00
|
|
|
) -> Result<Value, Box<dyn std::error::Error>> {
|
|
|
|
|
info!(
|
2025-10-16 11:43:02 -03:00
|
|
|
"Starting execute_set_schedule with cron: {}, param: {}",
|
|
|
|
|
cron, param
|
2025-10-06 10:30:17 -03:00
|
|
|
);
|
|
|
|
|
|
2025-10-11 12:29:03 -03:00
|
|
|
use crate::shared::models::system_automations;
|
|
|
|
|
|
|
|
|
|
let new_automation = (
|
|
|
|
|
system_automations::kind.eq(TriggerKind::Scheduled as i32),
|
|
|
|
|
system_automations::schedule.eq(cron),
|
2025-10-16 11:43:02 -03:00
|
|
|
system_automations::param.eq(param),
|
2025-10-11 12:29:03 -03:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
let result = diesel::insert_into(system_automations::table)
|
|
|
|
|
.values(&new_automation)
|
2025-10-11 20:25:08 -03:00
|
|
|
.execute(&mut *conn)?;
|
2025-10-06 10:30:17 -03:00
|
|
|
|
|
|
|
|
Ok(json!({
|
|
|
|
|
"command": "set_schedule",
|
|
|
|
|
"schedule": cron,
|
2025-10-16 11:43:02 -03:00
|
|
|
"param": param,
|
2025-10-11 12:29:03 -03:00
|
|
|
"rows_affected": result
|
2025-10-06 10:30:17 -03:00
|
|
|
}))
|
|
|
|
|
}
|