use axum::Router; use axum::body::Body; use axum::http::{Request, StatusCode, header}; use chrono::{Local, NaiveDate, TimeZone}; use http_body_util::BodyExt; use serde_json::{Value, json}; use tower::ServiceExt; async fn app() -> Router { let pool = tempus::db::connect("sqlite::memory:").await.unwrap(); tempus::routes::app(pool) } async fn send(app: &Router, method: &str, uri: &str, body: Option) -> (StatusCode, Value) { let mut req = Request::builder().method(method).uri(uri); let body = match body { Some(v) => { req = req.header(header::CONTENT_TYPE, "application/json"); Body::from(v.to_string()) } None => Body::empty(), }; let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap(); let status = resp.status(); let bytes = resp.into_body().collect().await.unwrap().to_bytes(); let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null); (status, value) } async fn send_form(app: &Router, uri: &str, form: &str) -> (StatusCode, String) { let req = Request::post(uri) .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded") .body(Body::from(form.to_owned())) .unwrap(); let resp = app.clone().oneshot(req).await.unwrap(); let status = resp.status(); let bytes = resp.into_body().collect().await.unwrap().to_bytes(); (status, String::from_utf8(bytes.to_vec()).unwrap()) } async fn get_html(app: &Router, uri: &str) -> (StatusCode, String) { let resp = app .clone() .oneshot(Request::get(uri).body(Body::empty()).unwrap()) .await .unwrap(); let status = resp.status(); let bytes = resp.into_body().collect().await.unwrap().to_bytes(); (status, String::from_utf8(bytes.to_vec()).unwrap()) } /// Local wall-clock time as RFC3339 with offset. fn local(y: i32, m: u32, d: u32, h: u32, min: u32) -> String { Local .from_local_datetime( &NaiveDate::from_ymd_opt(y, m, d) .unwrap() .and_hms_opt(h, min, 0) .unwrap(), ) .earliest() .unwrap() .to_rfc3339() } /// Creates a client with one project; returns the project id. async fn project(app: &Router, client: &str, name: &str) -> i64 { let (_, c) = send(app, "POST", "/api/clients", Some(json!({ "name": client }))).await; let (status, p) = send( app, "POST", &format!("/api/clients/{}/projects", c["id"]), Some(json!({ "name": name })), ) .await; assert_eq!(status, StatusCode::CREATED); p["id"].as_i64().unwrap() } async fn add_entry( app: &Router, project_id: i64, start: String, end: String, ) -> (StatusCode, Value) { send( app, "POST", "/api/entries", Some(json!({ "project_id": project_id, "started_at": start, "ended_at": end })), ) .await } #[tokio::test] async fn clients_and_projects_crud() { let app = app().await; let (status, client) = send( &app, "POST", "/api/clients", Some(json!({ "name": " Acme " })), ) .await; assert_eq!(status, StatusCode::CREATED); assert_eq!(client["name"], "Acme"); let id = client["id"].as_i64().unwrap(); let (status, _) = send( &app, "POST", "/api/clients", Some(json!({ "name": "Acme" })), ) .await; assert_eq!(status, StatusCode::CONFLICT); let (status, _) = send(&app, "POST", "/api/clients", Some(json!({ "name": " " }))).await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); let (status, p) = send( &app, "POST", &format!("/api/clients/{id}/projects"), Some(json!({ "name": "Site web" })), ) .await; assert_eq!(status, StatusCode::CREATED); assert_eq!(p["client_name"], "Acme"); let (status, _) = send( &app, "POST", "/api/clients/999/projects", Some(json!({ "name": "X" })), ) .await; assert_eq!(status, StatusCode::NOT_FOUND); let (status, c) = send( &app, "PATCH", &format!("/api/clients/{id}"), Some(json!({ "name": "Acme Corp", "archived": true })), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(c["name"], "Acme Corp"); assert_eq!(c["archived"], true); let (_, list) = send(&app, "GET", "/api/clients", None).await; assert_eq!(list.as_array().unwrap().len(), 0); let (_, list) = send(&app, "GET", "/api/clients?archived=true", None).await; assert_eq!(list.as_array().unwrap().len(), 1); // Tracking on a project of an archived client is refused. let (status, _) = send( &app, "POST", "/api/timer/start", Some(json!({ "project_id": p["id"] })), ) .await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); let (status, _) = send(&app, "DELETE", &format!("/api/clients/{id}"), None).await; assert_eq!(status, StatusCode::NO_CONTENT); let (status, _) = send(&app, "DELETE", &format!("/api/projects/{}", p["id"]), None).await; assert_eq!( status, StatusCode::NOT_FOUND, "projects are deleted with their client" ); } #[tokio::test] async fn timer_start_switch_stop() { let app = app().await; let site = project(&app, "Acme", "Site").await; let api = project(&app, "Globex", "API").await; let (status, timer) = send(&app, "GET", "/api/timer", None).await; assert_eq!(status, StatusCode::OK); assert!(timer.is_null()); let (status, first) = send( &app, "POST", "/api/timer/start", Some(json!({ "project_id": site, "note": "maquettes" })), ) .await; assert_eq!(status, StatusCode::CREATED); assert!(first["ended_at"].is_null()); // Backdate it so switching leaves a non-empty entry. let hour_ago = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339(); let (status, _) = send( &app, "PATCH", &format!("/api/entries/{}", first["id"]), Some(json!({ "started_at": hour_ago })), ) .await; assert_eq!(status, StatusCode::OK); let (_, second) = send( &app, "POST", "/api/timer/start", Some(json!({ "project_id": api })), ) .await; let (_, timer) = send(&app, "GET", "/api/timer", None).await; assert_eq!(timer["id"], second["id"]); assert_eq!(timer["client_name"], "Globex"); let (_, entries) = send(&app, "GET", "/api/entries", None).await; let first = entries .as_array() .unwrap() .iter() .find(|e| e["id"] == first["id"]) .unwrap(); assert!( !first["ended_at"].is_null(), "switching stops the previous timer" ); assert!((3599..=3601).contains(&first["seconds"].as_i64().unwrap())); assert_eq!(first["note"], "maquettes"); // Same-second stop discards the empty entry; either way nothing runs afterwards. send(&app, "POST", "/api/timer/stop", None).await; let (_, timer) = send(&app, "GET", "/api/timer", None).await; assert!(timer.is_null()); let (status, _) = send(&app, "POST", "/api/timer/stop", None).await; assert_eq!(status, StatusCode::CONFLICT); } #[tokio::test] async fn manual_entries() { let app = app().await; let p = project(&app, "Acme", "Site").await; let (status, e) = add_entry( &app, p, local(2026, 3, 10, 9, 0), local(2026, 3, 10, 11, 30), ) .await; assert_eq!(status, StatusCode::CREATED); assert_eq!(e["seconds"], 9000); assert_eq!(e["overlaps"], false); let (status, _) = add_entry( &app, p, local(2026, 3, 10, 12, 0), local(2026, 3, 10, 11, 0), ) .await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); let (status, _) = add_entry( &app, 999, local(2026, 3, 10, 12, 0), local(2026, 3, 10, 13, 0), ) .await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); let (status, o) = add_entry( &app, p, local(2026, 3, 10, 11, 0), local(2026, 3, 10, 12, 0), ) .await; assert_eq!(status, StatusCode::CREATED); assert_eq!(o["overlaps"], true, "overlaps are allowed but flagged"); let (status, o) = send( &app, "PATCH", &format!("/api/entries/{}", o["id"]), Some(json!({ "started_at": local(2026, 3, 10, 11, 30), "note": "revue" })), ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(o["overlaps"], false); assert_eq!(o["seconds"], 1800); assert_eq!(o["note"], "revue"); let (_, list) = send( &app, "GET", "/api/entries?from=2026-03-10&to=2026-03-10", None, ) .await; assert_eq!(list.as_array().unwrap().len(), 2); let (_, list) = send(&app, "GET", "/api/entries?from=2026-03-11", None).await; assert_eq!(list.as_array().unwrap().len(), 0); let (status, _) = send(&app, "DELETE", &format!("/api/entries/{}", o["id"]), None).await; assert_eq!(status, StatusCode::NO_CONTENT); let (status, _) = send(&app, "DELETE", &format!("/api/entries/{}", o["id"]), None).await; assert_eq!(status, StatusCode::NOT_FOUND); } #[tokio::test] async fn reports_clip_and_group() { let app = app().await; let site = project(&app, "Acme", "Site").await; let api = project(&app, "Globex", "API").await; // 22:00 → 02:00 across the 10th and 11th. add_entry( &app, site, local(2026, 3, 10, 22, 0), local(2026, 3, 11, 2, 0), ) .await; add_entry( &app, api, local(2026, 3, 11, 9, 0), local(2026, 3, 11, 10, 30), ) .await; // Outside the period. add_entry( &app, api, local(2026, 3, 20, 9, 0), local(2026, 3, 20, 17, 0), ) .await; let (status, r) = send( &app, "GET", "/api/reports?from=2026-03-11&to=2026-03-11&group_by=client", None, ) .await; assert_eq!(status, StatusCode::OK); assert_eq!( r["total_seconds"], 2 * 3600 + 5400, "clipped at the period start" ); let rows = r["rows"].as_array().unwrap(); assert_eq!(rows[0]["label"], "Acme"); assert_eq!(rows[0]["seconds"], 7200); assert_eq!(rows[0]["percent"], 100); assert_eq!(rows[1]["label"], "Globex"); assert_eq!(rows[1]["percent"], 75); let (_, r) = send( &app, "GET", "/api/reports?from=2026-03-10&to=2026-03-12&group_by=day", None, ) .await; let days: Vec<(String, i64)> = r["rows"] .as_array() .unwrap() .iter() .map(|row| { ( row["key"].as_str().unwrap().to_owned(), row["seconds"].as_i64().unwrap(), ) }) .collect(); assert_eq!( days, vec![ ("2026-03-10".into(), 7200), ("2026-03-11".into(), 7200 + 5400), ("2026-03-12".into(), 0), ] ); let (_, r) = send( &app, "GET", &format!("/api/reports?from=2026-03-01&to=2026-03-31&project_id={api}"), None, ) .await; assert_eq!(r["total_seconds"], 5400 + 8 * 3600); assert_eq!(r["rows"][0]["label"], "Globex / API"); let (status, _) = send( &app, "GET", "/api/reports?from=2026-03-12&to=2026-03-11", None, ) .await; assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY); } #[tokio::test] async fn html_pages() { let app = app().await; let (status, _) = send_form(&app, "/ui/clients", "name=Acme").await; assert_eq!(status, StatusCode::SEE_OTHER); let (status, _) = send_form(&app, "/ui/clients/1/projects", "name=Site+web").await; assert_eq!(status, StatusCode::SEE_OTHER); let (status, html) = send_form(&app, "/ui/clients", "name=Acme").await; assert_eq!(status, StatusCode::CONFLICT); assert!(html.contains("id=\"error-message\"")); let (status, html) = get_html(&app, "/clients").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("Site web")); let (status, html) = send_form(&app, "/ui/timer/start", "project_id=1¬e=d%C3%A9mo").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("Arrêter") && html.contains("démo")); let (status, html) = get_html(&app, "/").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("data-started")); let (status, _) = send_form( &app, "/ui/entries", "project_id=1&started_at=2026-03-10T09%3A00&ended_at=2026-03-10T10%3A15¬e=", ) .await; assert_eq!(status, StatusCode::SEE_OTHER); let (status, html) = get_html(&app, "/entries?from=2026-03-09&to=2026-03-15&client_id=").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("1:15")); let (status, html) = get_html(&app, "/reports?from=2026-03-01&to=2026-03-31&group_by=day").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("1:15") && html.contains("mar. 10/03/2026")); let (status, html) = get_html(&app, "/").await; assert_eq!(status, StatusCode::OK); assert!(html.contains("Dernières entrées") && html.contains("mar. 10/03/2026")); } #[tokio::test] async fn dashboard_lists_20_most_recent_entries() { let app = app().await; let p = project(&app, "Acme", "Site web").await; for day in 1..=25 { let (status, _) = add_entry( &app, p, local(2026, 3, day, 9, 0), local(2026, 3, day, 10, 0), ) .await; assert_eq!(status, StatusCode::CREATED); } let (status, html) = get_html(&app, "/ui/dernieres-entrees").await; assert_eq!(status, StatusCode::OK); assert_eq!(html.matches("