ironflow_api/routes/schedules/
list.rs1use axum::extract::{Query, State};
4use axum::response::IntoResponse;
5use serde::Deserialize;
6
7use ironflow_auth::extractor::Authenticated;
8
9use crate::entities::ScheduleResponse;
10use crate::error::ApiError;
11use crate::response::ok_paged;
12use crate::state::AppState;
13
14#[derive(Debug, Deserialize)]
16pub struct ListSchedulesQuery {
17 #[serde(default = "default_page")]
19 pub page: u32,
20 #[serde(default = "default_per_page")]
22 pub per_page: u32,
23}
24
25fn default_page() -> u32 {
26 1
27}
28
29fn default_per_page() -> u32 {
30 20
31}
32
33#[cfg_attr(
39 feature = "openapi",
40 utoipa::path(
41 get,
42 path = "/api/v1/schedules",
43 tags = ["schedules"],
44 params(
45 ("page" = Option<u32>, Query, description = "Page number (1-based)"),
46 ("per_page" = Option<u32>, Query, description = "Items per page"),
47 ),
48 responses(
49 (status = 200, description = "Paginated schedules", body = Vec<ScheduleResponse>),
50 (status = 401, description = "Unauthorized")
51 ),
52 security(("Bearer" = []))
53 )
54)]
55pub async fn list_schedules(
56 _auth: Authenticated,
57 State(state): State<AppState>,
58 Query(query): Query<ListSchedulesQuery>,
59) -> Result<impl IntoResponse, ApiError> {
60 let page = state
61 .store
62 .list_schedules(query.page, query.per_page)
63 .await?;
64
65 let items: Vec<ScheduleResponse> = page.items.into_iter().map(ScheduleResponse::from).collect();
66
67 Ok(ok_paged(items, page.page, page.per_page, page.total))
68}
69
70#[cfg(test)]
71mod tests {
72 use axum::Router;
73 use axum::body::Body;
74 use axum::http::{Request, StatusCode};
75 use axum::routing::get;
76 use http_body_util::BodyExt;
77 use ironflow_auth::jwt::{AccessToken, JwtConfig};
78 use ironflow_auth::password;
79 use ironflow_core::providers::claude::ClaudeCodeProvider;
80 use ironflow_engine::context::WorkflowContext;
81 use ironflow_engine::engine::Engine;
82 use ironflow_engine::handler::{HandlerFuture, WorkflowHandler};
83 use ironflow_engine::notify::Event;
84 use ironflow_store::entities::{NewSchedule, NewUser, ScheduleSource};
85 use ironflow_store::memory::InMemoryStore;
86 use ironflow_store::store::Store;
87 use serde_json::json;
88 use std::sync::Arc;
89 use tokio::sync::broadcast;
90 use tower::ServiceExt;
91 use uuid::Uuid;
92
93 use crate::state::AppState;
94
95 use super::*;
96
97 struct TestWorkflow;
98
99 impl WorkflowHandler for TestWorkflow {
100 fn name(&self) -> &str {
101 "deploy"
102 }
103
104 fn execute<'a>(&'a self, _ctx: &'a mut WorkflowContext) -> HandlerFuture<'a> {
105 Box::pin(async move { Ok(()) })
106 }
107 }
108
109 fn test_jwt_config() -> Arc<JwtConfig> {
110 Arc::new(JwtConfig {
111 secret: "test-secret-for-schedule-list".to_string(),
112 access_token_ttl_secs: 900,
113 refresh_token_ttl_secs: 604800,
114 cookie_domain: None,
115 cookie_secure: false,
116 })
117 }
118
119 async fn test_state_with_user() -> (AppState, Uuid) {
120 let store: Arc<dyn Store> = Arc::new(InMemoryStore::new());
121 let provider = Arc::new(ClaudeCodeProvider::new());
122 let mut engine = Engine::new(store.clone(), provider);
123 engine.register(TestWorkflow).expect("register");
124 let (event_sender, _) = broadcast::channel::<Event>(1);
125 let state = AppState::new(
126 store.clone(),
127 Arc::new(engine),
128 test_jwt_config(),
129 "test-worker-token".to_string(),
130 event_sender,
131 );
132 let hash = password::hash("password123").expect("hash");
133 let user = store
134 .create_user(NewUser {
135 email: "test@example.com".to_string(),
136 username: "testuser".to_string(),
137 password_hash: hash,
138 is_admin: None,
139 })
140 .await
141 .expect("create user");
142 (state, user.id)
143 }
144
145 fn make_auth_header(user_id: Uuid, state: &AppState) -> String {
146 let token =
147 AccessToken::for_user(user_id, "testuser", false, &state.jwt_config).expect("token");
148 format!("Bearer {}", token.0)
149 }
150
151 #[tokio::test]
152 async fn list_schedules_empty() {
153 let (state, user_id) = test_state_with_user().await;
154 let auth = make_auth_header(user_id, &state);
155 let app = Router::new()
156 .route("/", get(list_schedules))
157 .with_state(state);
158
159 let req = Request::builder()
160 .uri("/")
161 .header("authorization", &auth)
162 .body(Body::empty())
163 .expect("build");
164
165 let resp = app.oneshot(req).await.expect("request");
166 assert_eq!(resp.status(), StatusCode::OK);
167
168 let body = resp.into_body().collect().await.expect("body").to_bytes();
169 let val: serde_json::Value = serde_json::from_slice(&body).expect("json");
170 assert_eq!(val["data"], json!([]));
171 assert_eq!(val["meta"]["total"], 0);
172 }
173
174 #[tokio::test]
175 async fn list_schedules_with_data() {
176 let (state, user_id) = test_state_with_user().await;
177 state
178 .store
179 .create_schedule(NewSchedule {
180 workflow_name: "deploy".to_string(),
181 cron_expression: "0 0 * * * *".to_string(),
182 inputs: json!({}),
183 source: ScheduleSource::Api,
184 created_by_user_id: Some(user_id),
185 next_trigger_at: None,
186 })
187 .await
188 .expect("create");
189
190 let auth = make_auth_header(user_id, &state);
191 let app = Router::new()
192 .route("/", get(list_schedules))
193 .with_state(state);
194
195 let req = Request::builder()
196 .uri("/")
197 .header("authorization", &auth)
198 .body(Body::empty())
199 .expect("build");
200
201 let resp = app.oneshot(req).await.expect("request");
202 assert_eq!(resp.status(), StatusCode::OK);
203
204 let body = resp.into_body().collect().await.expect("body").to_bytes();
205 let val: serde_json::Value = serde_json::from_slice(&body).expect("json");
206 assert_eq!(val["meta"]["total"], 1);
207 assert_eq!(val["data"][0]["workflow_name"], "deploy");
208 }
209}