Files
tempus/src/routes/pages.rs
T
Romulus21andClaude Opus 5.5 7c22567b07 Permet de dupliquer une entrée
Bouton « Dupliquer » sur chaque ligne de /entries : ouvre sous l'entrée
un formulaire prérempli (début, fin, projet, note) à ajuster avant de
créer la copie. Une entrée en cours propose « maintenant » comme fin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 15:49:07 +01:00

684 lines
19 KiB
Rust

//! Server-rendered pages and the htmx fragments they swap in.
use askama::Template;
use axum::Form;
use axum::Router;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::{AppendHeaders, Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use chrono::{Duration, NaiveDate};
use serde::Deserialize;
use sqlx::SqlitePool;
use crate::clock;
use crate::error::AppError;
use crate::models::{
Client, Entry, EntryFilter, GroupBy, NewEntry, Project, Report, ReportQuery, UpdateEntry,
UpdateInput, empty_as_none,
};
use crate::repo::{clients, entries, projects, reports};
pub fn router() -> Router<SqlitePool> {
Router::new()
.route("/", get(dashboard))
.route("/clients", get(clients_page))
.route("/entries", get(entries_page))
.route("/reports", get(reports_page))
.route("/ui/today", get(today_fragment))
.route("/ui/dernieres-entrees", get(recent_fragment))
.route("/ui/timer/start", post(start_timer))
.route("/ui/timer/stop", post(stop_timer))
.route("/ui/clients", post(create_client))
.route("/ui/clients/{id}", post(save_client))
.route("/ui/clients/{id}/archive", post(archive_client))
.route("/ui/clients/{id}/delete", post(delete_client))
.route("/ui/clients/{id}/projects", post(create_project))
.route("/ui/projects/{id}", post(save_project))
.route("/ui/projects/{id}/archive", post(archive_project))
.route("/ui/projects/{id}/delete", post(delete_project))
.route("/ui/entries", post(create_entry))
.route(
"/ui/entries/{id}",
get(entry_row).put(update_entry).delete(delete_entry),
)
.route("/ui/entries/{id}/edit", get(entry_edit))
.route(
"/ui/entries/{id}/dupliquer",
get(entry_duplicate).post(duplicate_entry),
)
}
// --- Plumbing ---------------------------------------------------------------
/// Renders errors as an HTML page; `app.js` extracts the message for htmx requests.
pub struct PageError(AppError);
impl From<AppError> for PageError {
fn from(e: AppError) -> Self {
Self(e)
}
}
impl From<askama::Error> for PageError {
fn from(e: askama::Error) -> Self {
Self(e.into())
}
}
#[derive(Template)]
#[template(path = "error.html")]
struct ErrorTpl {
nav: &'static str,
message: String,
}
impl IntoResponse for PageError {
fn into_response(self) -> Response {
self.0.log();
let tpl = ErrorTpl {
nav: "",
message: self.0.to_string(),
};
let body = tpl.render().unwrap_or_else(|_| self.0.to_string());
(self.0.status(), Html(body)).into_response()
}
}
type PageResult<T = Response> = Result<T, PageError>;
fn render(tpl: impl Template) -> PageResult {
Ok(Html(tpl.render()?).into_response())
}
/// Tells listeners on the page (e.g. today's list) that entries changed.
fn with_entries_changed(resp: Response) -> Response {
(AppendHeaders([("HX-Trigger", "entries-changed")]), resp).into_response()
}
struct ProjectOption {
id: i64,
name: String,
selected: bool,
}
struct ProjectGroup {
name: String,
projects: Vec<ProjectOption>,
}
/// Groups projects (already sorted by client) for `<optgroup>`s.
fn group_projects(list: Vec<Project>, selected: Option<i64>) -> Vec<ProjectGroup> {
let mut groups: Vec<ProjectGroup> = Vec::new();
for p in list {
if groups.last().is_none_or(|g| g.name != p.client_name) {
groups.push(ProjectGroup {
name: p.client_name.clone(),
projects: Vec::new(),
});
}
let name = if p.archived {
format!("{} (archivé)", p.name)
} else {
p.name
};
groups
.last_mut()
.expect("just pushed")
.projects
.push(ProjectOption {
id: p.id,
name,
selected: Some(p.id) == selected,
});
}
groups
}
struct ClientOption {
id: i64,
name: String,
selected: bool,
}
fn client_options(list: Vec<Client>, selected: Option<i64>) -> Vec<ClientOption> {
list.into_iter()
.map(|c| ClientOption {
selected: Some(c.id) == selected,
id: c.id,
name: c.name,
})
.collect()
}
struct Preset {
label: &'static str,
from: NaiveDate,
to: NaiveDate,
active: bool,
}
fn presets(from: NaiveDate, to: NaiveDate) -> Vec<Preset> {
let today = clock::today();
let last_month = clock::month_start(today) - Duration::days(1);
[
("Aujourd'hui", today, today),
("Cette semaine", clock::week_start(today), today),
(
"Semaine dernière",
clock::week_start(today) - Duration::days(7),
clock::week_start(today) - Duration::days(1),
),
("Ce mois", clock::month_start(today), today),
("Mois dernier", clock::month_start(last_month), last_month),
]
.into_iter()
.map(|(label, f, t)| Preset {
label,
from: f,
to: t,
active: f == from && t == to,
})
.collect()
}
/// Query-string suffix that keeps the current filters when switching period.
fn id_params(client_id: Option<i64>, project_id: Option<i64>) -> String {
let mut s = String::new();
if let Some(id) = client_id {
s.push_str(&format!("&client_id={id}"));
}
if let Some(id) = project_id {
s.push_str(&format!("&project_id={id}"));
}
s
}
/// Resolves an optional period, defaulting to the current week.
fn period(from: Option<NaiveDate>, to: Option<NaiveDate>) -> (NaiveDate, NaiveDate) {
let today = clock::today();
let from = from.unwrap_or_else(|| clock::week_start(today));
(from, to.unwrap_or(today.max(from)))
}
// --- Dashboard & timer ------------------------------------------------------
#[derive(Template)]
#[template(path = "dashboard.html")]
struct DashboardTpl {
nav: &'static str,
running: Option<Entry>,
groups: Vec<ProjectGroup>,
today_entries: Vec<Entry>,
today_total: String,
recent_entries: Vec<Entry>,
}
#[derive(Template)]
#[template(path = "_timer.html")]
struct TimerTpl {
running: Option<Entry>,
groups: Vec<ProjectGroup>,
}
#[derive(Template)]
#[template(path = "_today.html")]
struct TodayTpl {
today_entries: Vec<Entry>,
today_total: String,
}
#[derive(Template)]
#[template(path = "_recent.html")]
struct RecentTpl {
recent_entries: Vec<Entry>,
}
/// How many entries the dashboard lists under "Dernières entrées".
const RECENT_LIMIT: i64 = 20;
async fn timer_state(pool: &SqlitePool) -> PageResult<TimerTpl> {
let running = entries::running(pool).await?;
// Preselect the running project, else the most recently tracked one.
let selected = match &running {
Some(e) => Some(e.project_id),
None => entries::last_project_id(pool).await?,
};
let groups = group_projects(projects::list(pool, None, false).await?, selected);
Ok(TimerTpl { running, groups })
}
async fn today_state(pool: &SqlitePool) -> PageResult<TodayTpl> {
let today = clock::today();
let now = clock::now();
let filter = EntryFilter {
from: Some(today),
to: Some(today),
..Default::default()
};
let today_entries = entries::list(pool, &filter, now).await?;
let total = reports::aggregate(&today_entries, today, today, GroupBy::Client, now);
Ok(TodayTpl {
today_entries,
today_total: total.total(),
})
}
async fn recent_state(pool: &SqlitePool) -> PageResult<RecentTpl> {
let recent_entries = entries::recent(pool, RECENT_LIMIT, clock::now()).await?;
Ok(RecentTpl { recent_entries })
}
async fn dashboard(State(pool): State<SqlitePool>) -> PageResult {
let TimerTpl { running, groups } = timer_state(&pool).await?;
let TodayTpl {
today_entries,
today_total,
} = today_state(&pool).await?;
let RecentTpl { recent_entries } = recent_state(&pool).await?;
render(DashboardTpl {
nav: "dashboard",
running,
groups,
today_entries,
today_total,
recent_entries,
})
}
async fn today_fragment(State(pool): State<SqlitePool>) -> PageResult {
render(today_state(&pool).await?)
}
async fn recent_fragment(State(pool): State<SqlitePool>) -> PageResult {
render(recent_state(&pool).await?)
}
#[derive(Deserialize)]
struct StartForm {
project_id: i64,
#[serde(default)]
note: String,
}
async fn start_timer(State(pool): State<SqlitePool>, Form(form): Form<StartForm>) -> PageResult {
entries::start(&pool, form.project_id, &form.note).await?;
Ok(with_entries_changed(render(timer_state(&pool).await?)?))
}
async fn stop_timer(State(pool): State<SqlitePool>) -> PageResult {
match entries::stop(&pool).await {
// Already stopped (e.g. from another tab): just refresh the widget.
Ok(_) | Err(AppError::Conflict(_)) => {}
Err(e) => return Err(e.into()),
}
Ok(with_entries_changed(render(timer_state(&pool).await?)?))
}
// --- Clients & projects -----------------------------------------------------
struct ClientCard {
client: Client,
projects: Vec<Project>,
}
#[derive(Template)]
#[template(path = "clients.html")]
struct ClientsTpl {
nav: &'static str,
clients: Vec<ClientCard>,
next_color: String,
}
async fn clients_page(State(pool): State<SqlitePool>) -> PageResult {
let all_projects = projects::list(&pool, None, true).await?;
let clients = clients::list(&pool, true)
.await?
.into_iter()
.map(|client| {
let projects = all_projects
.iter()
.filter(|p| p.client_id == client.id)
.cloned()
.collect();
ClientCard { client, projects }
})
.collect();
render(ClientsTpl {
nav: "clients",
clients,
next_color: clients::next_color(&pool).await?,
})
}
#[derive(Deserialize)]
struct ItemForm {
name: String,
#[serde(default, deserialize_with = "empty_as_none")]
color: Option<String>,
/// Projects only: go back to the client's color.
#[serde(default)]
inherit: bool,
}
#[derive(Deserialize)]
struct ArchiveForm {
archived: bool,
}
fn back_to_clients() -> PageResult {
Ok(Redirect::to("/clients").into_response())
}
fn archive_input(archived: bool) -> UpdateInput {
UpdateInput {
archived: Some(archived),
..Default::default()
}
}
async fn create_client(State(pool): State<SqlitePool>, Form(f): Form<ItemForm>) -> PageResult {
clients::create(&pool, &f.name, f.color.as_deref()).await?;
back_to_clients()
}
async fn save_client(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Form(f): Form<ItemForm>,
) -> PageResult {
let input = UpdateInput {
name: Some(f.name),
color: f.color.map(Some),
..Default::default()
};
clients::update(&pool, id, &input).await?;
back_to_clients()
}
async fn archive_client(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Form(f): Form<ArchiveForm>,
) -> PageResult {
clients::update(&pool, id, &archive_input(f.archived)).await?;
back_to_clients()
}
async fn delete_client(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
clients::delete(&pool, id).await?;
back_to_clients()
}
async fn create_project(
State(pool): State<SqlitePool>,
Path(client_id): Path<i64>,
Form(f): Form<ItemForm>,
) -> PageResult {
// The color picker is prefilled with the client's color: keeping it means inheriting.
let client = clients::get(&pool, client_id).await?;
let color = f.color.filter(|c| !c.eq_ignore_ascii_case(&client.color));
projects::create(&pool, client_id, &f.name, color.as_deref()).await?;
back_to_clients()
}
async fn save_project(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Form(f): Form<ItemForm>,
) -> PageResult {
let current = projects::get(&pool, id).await?;
let color = if f.inherit {
Some(None)
} else {
// Untouched picker: leave the color (own or inherited) as it is.
f.color
.filter(|c| !c.eq_ignore_ascii_case(&current.effective_color))
.map(Some)
};
let input = UpdateInput {
name: Some(f.name),
color,
..Default::default()
};
projects::update(&pool, id, &input).await?;
back_to_clients()
}
async fn archive_project(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Form(f): Form<ArchiveForm>,
) -> PageResult {
projects::update(&pool, id, &archive_input(f.archived)).await?;
back_to_clients()
}
async fn delete_project(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
projects::delete(&pool, id).await?;
back_to_clients()
}
// --- Entries ----------------------------------------------------------------
#[derive(Template)]
#[template(path = "entries.html")]
struct EntriesTpl {
nav: &'static str,
from: NaiveDate,
to: NaiveDate,
presets: Vec<Preset>,
extra_query: String,
clients: Vec<ClientOption>,
filter_groups: Vec<ProjectGroup>,
groups: Vec<ProjectGroup>,
entries: Vec<Entry>,
total: String,
default_start: String,
default_end: String,
}
#[derive(Template)]
#[template(path = "_entry_row.html")]
struct EntryRowTpl {
e: Entry,
}
#[derive(Template)]
#[template(path = "_entry_edit.html")]
struct EntryEditTpl {
e: Entry,
groups: Vec<ProjectGroup>,
}
#[derive(Template)]
#[template(path = "_entry_duplicate.html")]
struct EntryDuplicateTpl {
e: Entry,
/// A running entry has no end yet: offer "now".
end: String,
groups: Vec<ProjectGroup>,
}
async fn entries_page(
State(pool): State<SqlitePool>,
Query(filter): Query<EntryFilter>,
) -> PageResult {
let (from, to) = period(filter.from, filter.to);
let filter = EntryFilter {
from: Some(from),
to: Some(to),
..filter
};
let now = clock::now();
let list = entries::list(&pool, &filter, now).await?;
let total = reports::aggregate(&list, from, to, GroupBy::Client, now).total();
let last_project = list.first().map(|e| e.project_id);
let today = clock::today();
render(EntriesTpl {
nav: "entries",
from,
to,
presets: presets(from, to),
extra_query: id_params(filter.client_id, filter.project_id),
clients: client_options(clients::list(&pool, true).await?, filter.client_id),
filter_groups: group_projects(projects::list(&pool, None, true).await?, filter.project_id),
groups: group_projects(projects::list(&pool, None, false).await?, last_project),
entries: list,
total,
default_start: format!("{today}T09:00"),
default_end: format!("{today}T10:00"),
})
}
#[derive(Deserialize)]
struct EntryForm {
project_id: i64,
started_at: String,
#[serde(default)]
ended_at: String,
#[serde(default)]
note: String,
}
fn parse_datetime(value: &str, field: &str) -> Result<chrono::DateTime<chrono::Utc>, AppError> {
clock::parse_input(value).ok_or_else(|| AppError::Validation(format!("{field} invalide")))
}
async fn create_entry(State(pool): State<SqlitePool>, Form(f): Form<EntryForm>) -> PageResult {
let started = parse_datetime(&f.started_at, "début")?;
let ended = parse_datetime(&f.ended_at, "fin")?;
let entry = entries::create(
&pool,
&NewEntry {
project_id: f.project_id,
started_at: started.fixed_offset(),
ended_at: ended.fixed_offset(),
note: f.note,
},
)
.await?;
// Land on the week containing the new entry so it is visible.
let day = clock::local_date(&entry.started_at);
let from = clock::week_start(day);
Ok(Redirect::to(&format!(
"/entries?from={from}&to={}",
from + Duration::days(6)
))
.into_response())
}
async fn entry_row(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
render(EntryRowTpl {
e: entries::get(&pool, id).await?,
})
}
async fn entry_edit(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
let e = entries::get(&pool, id).await?;
let groups = group_projects(projects::list(&pool, None, true).await?, Some(e.project_id));
render(EntryEditTpl { e, groups })
}
/// Form to create a copy of an entry, prefilled with its values.
async fn entry_duplicate(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
let e = entries::get(&pool, id).await?;
let end = clock::input_value(&e.ended_at.unwrap_or_else(clock::now));
let groups = group_projects(
projects::list(&pool, None, false).await?,
Some(e.project_id),
);
render(EntryDuplicateTpl { e, end, groups })
}
/// Creates the copy and swaps the form for its row.
async fn duplicate_entry(State(pool): State<SqlitePool>, Form(f): Form<EntryForm>) -> PageResult {
let started = parse_datetime(&f.started_at, "début")?;
let ended = parse_datetime(&f.ended_at, "fin")?;
let e = entries::create(
&pool,
&NewEntry {
project_id: f.project_id,
started_at: started.fixed_offset(),
ended_at: ended.fixed_offset(),
note: f.note,
},
)
.await?;
Ok(with_entries_changed(render(EntryRowTpl { e })?))
}
async fn update_entry(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Form(f): Form<EntryForm>,
) -> PageResult {
let started = parse_datetime(&f.started_at, "début")?;
let ended = match f.ended_at.trim() {
"" => None,
v => Some(parse_datetime(v, "fin")?),
};
let e = entries::update(
&pool,
id,
&UpdateEntry {
project_id: Some(f.project_id),
started_at: Some(started.fixed_offset()),
ended_at: ended.map(|d| d.fixed_offset()),
note: Some(f.note),
},
)
.await?;
Ok(with_entries_changed(render(EntryRowTpl { e })?))
}
async fn delete_entry(State(pool): State<SqlitePool>, Path(id): Path<i64>) -> PageResult {
entries::delete(&pool, id).await?;
// htmx swaps the row with this empty body, removing it.
Ok(with_entries_changed((StatusCode::OK, "").into_response()))
}
// --- Reports ----------------------------------------------------------------
#[derive(Template)]
#[template(path = "reports.html")]
struct ReportsTpl {
nav: &'static str,
report: Report,
presets: Vec<Preset>,
extra_query: String,
clients: Vec<ClientOption>,
group_by: &'static str,
}
async fn reports_page(State(pool): State<SqlitePool>, Query(q): Query<ReportQuery>) -> PageResult {
let (from, to) = period(q.from, q.to);
let report = reports::build(
&pool,
from,
to,
q.group_by,
q.client_id,
q.project_id,
clock::now(),
)
.await?;
let group_by = match q.group_by {
GroupBy::Client => "client",
GroupBy::Project => "project",
GroupBy::Day => "day",
};
render(ReportsTpl {
nav: "reports",
presets: presets(from, to),
extra_query: format!(
"&group_by={group_by}{}",
id_params(q.client_id, q.project_id)
),
clients: client_options(clients::list(&pool, true).await?, q.client_id),
group_by,
report,
})
}