first commit

This commit is contained in:
Romulus21 committed 2026-10-26 13:21:14 +01:00
commit dd6a740645
37 files changed
+5424

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
/target
*.db
*.db-shm
*.db-wal
Generated
+2287
View File
File diff suppressed because it is too large. Load diff
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "tempus"
version = "0.1.0"
edition = "2024"
[dependencies]
anyhow = "1.0.104"
askama = "0.16.1"
axum = "0.8"
chrono = { version = "0.4.45", features = ["serde"] }
directories = "6.0.0"
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.154"
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "chrono", "migrate", "macros"] }
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["full"] }
tower-http = { version = "0.7.1", features = ["trace"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
[dev-dependencies]
http-body-util = "0.1.5"
tower = { version = "0.5.3", features = ["util"] }
+63
View File
@@ -0,0 +1,63 @@
# Tempus
Time tracker local pour suivre le temps passé sur chaque projet de chaque client.
Un seul binaire Rust (axum + SQLite) qui sert une interface web et une API JSON.
## Lancer
```sh
cargo run --release
# → http://127.0.0.1:7878
```
| Variable | Défaut | Rôle |
|---------------|------------------------------------------|------------------------------------|
| `TEMPUS_DB` | `~/.local/share/tempus/tempus.db` | Chemin (ou URL `sqlite:`) de la base |
| `TEMPUS_ADDR` | `127.0.0.1:7878` | Adresse d'écoute |
| `RUST_LOG` | `tempus=info,tower_http=info` | Niveau de logs |
Aucune authentification : le service est prévu pour tourner en local.
## Pages
- `/` — timer (démarrer / basculer / arrêter) et entrées du jour
- `/entries` — liste filtrable, saisie manuelle, édition inline (⚠ = chevauchement)
- `/reports` — totaux par client, projet ou jour sur une période
- `/clients` — clients et projets (nom, couleur, archiver, supprimer)
## API JSON (`/api`)
| Méthode | Route |
|--------------|----------------------------------------------------|
| GET, POST | `/clients` (`?archived=true` pour inclure les archivés) — `{"name", "color"?}` |
| PATCH, DELETE| `/clients/{id}` — `{"name"?, "archived"?, "color"?}` |
| GET, POST | `/clients/{id}/projects` — `{"name", "color"?}` |
| PATCH, DELETE| `/projects/{id}` — `"color": null` pour reprendre celle du client |
| GET | `/timer` — entrée en cours ou `null` |
| POST | `/timer/start` `{"project_id", "note"?}` · `/timer/stop` |
| GET, POST | `/entries` (`?from&to&client_id&project_id`) |
| PATCH, DELETE| `/entries/{id}` |
| GET | `/reports?from&to&group_by=client\|project\|day&client_id&project_id` |
Les couleurs sont au format `#rrggbb`. Un client reçoit automatiquement une couleur
de la palette s'il n'en précise pas ; un projet sans couleur utilise celle de son client
(`effective_color` dans les réponses).
Les dates d'entrées sont en RFC 3339 (`2026-10-26T09:00:00+01:00`) ; les périodes
(`from`, `to`, inclusives) sont des dates `YYYY-MM-DD` dans le fuseau local.
```sh
curl -XPOST localhost:7878/api/clients -H 'content-type: application/json' -d '{"name":"Acme"}'
curl -XPOST localhost:7878/api/timer/start -H 'content-type: application/json' -d '{"project_id":1}'
```
## Développement
```sh
cargo test
cargo clippy --all-targets -- -D warnings
```
Le schéma est dans `migrations/` (appliqué automatiquement au démarrage).
Les horodatages sont stockés en UTC au format fixe `YYYY-MM-DDTHH:MM:SSZ`
(voir `src/clock.rs`) pour que les comparaisons SQL sur le texte restent valides.
+33
View File
@@ -0,0 +1,33 @@
-- Timestamps are stored as UTC text, always formatted as "YYYY-MM-DDTHH:MM:SSZ"
-- so that lexicographic comparison matches chronological order.
CREATE TABLE clients (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
archived INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL
);
CREATE TABLE projects (
id INTEGER PRIMARY KEY,
client_id INTEGER NOT NULL REFERENCES clients (id) ON DELETE CASCADE,
name TEXT NOT NULL,
archived INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
UNIQUE (client_id, name)
);
CREATE TABLE time_entries (
id INTEGER PRIMARY KEY,
project_id INTEGER NOT NULL REFERENCES projects (id) ON DELETE CASCADE,
started_at TEXT NOT NULL,
ended_at TEXT,
note TEXT NOT NULL DEFAULT '',
CHECK (ended_at IS NULL OR ended_at > started_at)
);
-- At most one running timer: every running entry indexes the same value (1).
CREATE UNIQUE INDEX one_running_timer ON time_entries ((ended_at IS NULL)) WHERE ended_at IS NULL;
CREATE INDEX idx_entries_started ON time_entries (started_at);
CREATE INDEX idx_entries_project ON time_entries (project_id);
CREATE INDEX idx_projects_client ON projects (client_id);
+15
View File
@@ -0,0 +1,15 @@
-- Clients always have a color; projects inherit their client's color unless set.
ALTER TABLE clients ADD COLUMN color TEXT NOT NULL DEFAULT '#2f6f5e';
ALTER TABLE projects ADD COLUMN color TEXT;
-- Spread existing clients over the default palette (see repo::PALETTE).
UPDATE clients SET color = CASE (id - 1) % 8
WHEN 0 THEN '#2f6f5e'
WHEN 1 THEN '#3b6fb6'
WHEN 2 THEN '#c2410c'
WHEN 3 THEN '#7c3aed'
WHEN 4 THEN '#be185d'
WHEN 5 THEN '#a16207'
WHEN 6 THEN '#0e7490'
ELSE '#4d7c0f'
END;
+120
View File
@@ -0,0 +1,120 @@
//! Time helpers. Storage is UTC; periods and display use the local timezone.
use chrono::{
DateTime, Datelike, Duration, Local, NaiveDate, NaiveDateTime, SubsecRound, TimeZone, Utc,
};
pub fn now() -> DateTime<Utc> {
Utc::now().trunc_subsecs(0)
}
pub fn today() -> NaiveDate {
Local::now().date_naive()
}
/// Canonical storage format; must stay fixed-width for text comparisons in SQL.
pub fn ts(dt: &DateTime<Utc>) -> String {
dt.format("%Y-%m-%dT%H:%M:%SZ").to_string()
}
/// Converts a local wall-clock time to UTC, resolving DST gaps/folds to the earliest instant.
pub fn local_to_utc(naive: NaiveDateTime) -> DateTime<Utc> {
let local = Local
.from_local_datetime(&naive)
.earliest()
// Inside a DST gap the wall-clock time does not exist: shift past it.
.or_else(|| {
Local
.from_local_datetime(&(naive + Duration::hours(1)))
.earliest()
})
.unwrap_or_else(|| Utc.from_utc_datetime(&naive).with_timezone(&Local));
local.with_timezone(&Utc).trunc_subsecs(0)
}
pub fn local_midnight(date: NaiveDate) -> DateTime<Utc> {
local_to_utc(date.and_hms_opt(0, 0, 0).expect("midnight is valid"))
}
pub fn local_date(dt: &DateTime<Utc>) -> NaiveDate {
dt.with_timezone(&Local).date_naive()
}
pub fn week_start(date: NaiveDate) -> NaiveDate {
date - Duration::days(date.weekday().num_days_from_monday() as i64)
}
pub fn month_start(date: NaiveDate) -> NaiveDate {
date.with_day(1).expect("day 1 is valid")
}
/// Formats a duration as `h:mm`.
pub fn hhmm(seconds: i64) -> String {
let minutes = seconds.max(0) / 60;
format!("{}:{:02}", minutes / 60, minutes % 60)
}
/// Value for an `<input type="datetime-local">`.
pub fn input_value(dt: &DateTime<Utc>) -> String {
dt.with_timezone(&Local)
.format("%Y-%m-%dT%H:%M")
.to_string()
}
/// Parses an `<input type="datetime-local">` value as local time.
pub fn parse_input(value: &str) -> Option<DateTime<Utc>> {
["%Y-%m-%dT%H:%M", "%Y-%m-%dT%H:%M:%S"]
.iter()
.find_map(|fmt| NaiveDateTime::parse_from_str(value.trim(), fmt).ok())
.map(local_to_utc)
}
pub fn fmt_time(dt: &DateTime<Utc>) -> String {
dt.with_timezone(&Local).format("%H:%M").to_string()
}
pub fn fmt_day(date: NaiveDate) -> String {
const DAYS: [&str; 7] = ["lun.", "mar.", "mer.", "jeu.", "ven.", "sam.", "dim."];
format!(
"{} {}",
DAYS[date.weekday().num_days_from_monday() as usize],
date.format("%d/%m/%Y")
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hhmm_formats() {
assert_eq!(hhmm(0), "0:00");
assert_eq!(hhmm(59), "0:00");
assert_eq!(hhmm(3600 + 5 * 60), "1:05");
assert_eq!(hhmm(-10), "0:00");
}
#[test]
fn month_bounds() {
let d = NaiveDate::from_ymd_opt(2026, 12, 15).unwrap();
assert_eq!(
month_start(d),
NaiveDate::from_ymd_opt(2026, 12, 1).unwrap()
);
}
#[test]
fn week_starts_monday() {
let sunday = NaiveDate::from_ymd_opt(2026, 10, 25).unwrap();
assert_eq!(
week_start(sunday),
NaiveDate::from_ymd_opt(2026, 10, 19).unwrap()
);
}
#[test]
fn input_roundtrip() {
let dt = parse_input("2026-10-26T09:30").unwrap();
assert_eq!(input_value(&dt), "2026-10-26T09:30");
}
}
+33
View File
@@ -0,0 +1,33 @@
use std::net::SocketAddr;
use std::path::PathBuf;
use anyhow::{Context, Result};
pub struct Config {
pub database_url: String,
pub addr: SocketAddr,
}
impl Config {
/// Reads `TEMPUS_DB` (a file path or `sqlite:` URL) and `TEMPUS_ADDR`.
pub fn from_env() -> Result<Self> {
let database_url = match std::env::var("TEMPUS_DB") {
Ok(v) if v.starts_with("sqlite:") => v,
Ok(path) => format!("sqlite://{path}"),
Err(_) => format!("sqlite://{}", default_db_path()?.display()),
};
let addr = std::env::var("TEMPUS_ADDR")
.unwrap_or_else(|_| "127.0.0.1:7878".into())
.parse()
.context("invalid TEMPUS_ADDR")?;
Ok(Self { database_url, addr })
}
}
fn default_db_path() -> Result<PathBuf> {
let dirs = directories::ProjectDirs::from("", "", "tempus")
.context("cannot determine a data directory; set TEMPUS_DB")?;
let dir = dirs.data_dir();
std::fs::create_dir_all(dir).with_context(|| format!("cannot create {}", dir.display()))?;
Ok(dir.join("tempus.db"))
}
+30
View File
@@ -0,0 +1,30 @@
use std::str::FromStr;
use sqlx::SqlitePool;
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
/// Opens the database and applies pending migrations.
pub async fn connect(url: &str) -> Result<SqlitePool, sqlx::Error> {
let in_memory = url.contains(":memory:");
let mut opts = SqliteConnectOptions::from_str(url)?
.create_if_missing(true)
.foreign_keys(true);
if !in_memory {
opts = opts.journal_mode(SqliteJournalMode::Wal);
}
// Every connection to `:memory:` is a separate database, so keep exactly one alive.
let pool_opts = if in_memory {
SqlitePoolOptions::new()
.max_connections(1)
.min_connections(1)
.idle_timeout(None)
.max_lifetime(None)
} else {
SqlitePoolOptions::new().max_connections(5)
};
let pool = pool_opts.connect_with(opts).await?;
sqlx::migrate!().run(&pool).await?;
Ok(pool)
}
+64
View File
@@ -0,0 +1,64 @@
use axum::Json;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("ressource introuvable")]
NotFound,
#[error("{0}")]
Conflict(String),
#[error("{0}")]
Validation(String),
#[error("erreur de base de données")]
Db(#[source] sqlx::Error),
#[error("erreur interne")]
Internal(#[source] anyhow::Error),
}
pub type AppResult<T> = Result<T, AppError>;
impl AppError {
pub fn status(&self) -> StatusCode {
match self {
Self::NotFound => StatusCode::NOT_FOUND,
Self::Conflict(_) => StatusCode::CONFLICT,
Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
Self::Db(_) | Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
}
}
pub fn log(&self) {
match self {
Self::Db(e) => tracing::error!(error = %e, "database error"),
Self::Internal(e) => tracing::error!(error = %e, "internal error"),
_ => {}
}
}
}
impl From<sqlx::Error> for AppError {
fn from(e: sqlx::Error) -> Self {
match &e {
sqlx::Error::RowNotFound => Self::NotFound,
sqlx::Error::Database(db) if db.is_unique_violation() => {
Self::Conflict("cet élément existe déjà".into())
}
_ => Self::Db(e),
}
}
}
impl From<askama::Error> for AppError {
fn from(e: askama::Error) -> Self {
Self::Internal(e.into())
}
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
self.log();
(self.status(), Json(json!({ "error": self.to_string() }))).into_response()
}
}
+7
View File
@@ -0,0 +1,7 @@
pub mod clock;
pub mod config;
pub mod db;
pub mod error;
pub mod models;
pub mod repo;
pub mod routes;
+29
View File
@@ -0,0 +1,29 @@
use anyhow::Context;
use tempus::{config::Config, db, routes};
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "tempus=info,tower_http=info".into()),
)
.init();
let config = Config::from_env()?;
let pool = db::connect(&config.database_url)
.await
.with_context(|| format!("cannot open {}", config.database_url))?;
let listener = tokio::net::TcpListener::bind(config.addr)
.await
.with_context(|| format!("cannot listen on {}", config.addr))?;
tracing::info!(db = %config.database_url, "Tempus disponible sur http://{}", config.addr);
axum::serve(listener, routes::app(pool))
.with_graceful_shutdown(async {
let _ = tokio::signal::ctrl_c().await;
})
.await?;
Ok(())
}
+225
View File
@@ -0,0 +1,225 @@
use std::fmt::Display;
use std::str::FromStr;
use chrono::{DateTime, FixedOffset, NaiveDate, Utc};
use serde::{Deserialize, Deserializer, Serialize};
use crate::clock;
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Client {
pub id: i64,
pub name: String,
pub color: String,
pub archived: bool,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Project {
pub id: i64,
pub client_id: i64,
pub client_name: String,
pub name: String,
/// Own color; `None` means the client's color is used.
pub color: Option<String>,
/// `color`, or the client's color.
pub effective_color: String,
pub archived: bool,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Serialize, sqlx::FromRow)]
pub struct Entry {
pub id: i64,
pub project_id: i64,
pub project_name: String,
pub client_id: i64,
pub client_name: String,
/// The project's effective color.
pub color: String,
pub client_color: String,
pub started_at: DateTime<Utc>,
/// `None` while the timer is running.
pub ended_at: Option<DateTime<Utc>>,
pub note: String,
/// Elapsed seconds (up to now for a running entry).
pub seconds: i64,
/// True when another entry covers part of the same time span.
pub overlaps: bool,
}
impl Entry {
pub fn running(&self) -> bool {
self.ended_at.is_none()
}
pub fn duration(&self) -> String {
clock::hhmm(self.seconds)
}
pub fn day(&self) -> String {
clock::fmt_day(clock::local_date(&self.started_at))
}
pub fn start_time(&self) -> String {
clock::fmt_time(&self.started_at)
}
pub fn end_time(&self) -> String {
self.ended_at
.as_ref()
.map(clock::fmt_time)
.unwrap_or_else(|| "…".into())
}
pub fn start_input(&self) -> String {
clock::input_value(&self.started_at)
}
pub fn end_input(&self) -> String {
self.ended_at
.as_ref()
.map(clock::input_value)
.unwrap_or_default()
}
pub fn started_rfc3339(&self) -> String {
self.started_at.to_rfc3339()
}
}
// --- API inputs -------------------------------------------------------------
#[derive(Debug, Deserialize)]
pub struct NameInput {
pub name: String,
/// `#rrggbb`. Clients get one from the palette, projects inherit their client's.
#[serde(default)]
pub color: Option<String>,
}
#[derive(Debug, Default, Deserialize)]
pub struct UpdateInput {
pub name: Option<String>,
pub archived: Option<bool>,
/// Absent: unchanged. `null`: reset to the client's color (projects only).
#[serde(default, deserialize_with = "present")]
pub color: Option<Option<String>>,
}
#[derive(Debug, Deserialize)]
pub struct StartTimer {
pub project_id: i64,
#[serde(default)]
pub note: String,
}
#[derive(Debug, Deserialize)]
pub struct NewEntry {
pub project_id: i64,
pub started_at: DateTime<FixedOffset>,
pub ended_at: DateTime<FixedOffset>,
#[serde(default)]
pub note: String,
}
#[derive(Debug, Default, Deserialize)]
pub struct UpdateEntry {
pub project_id: Option<i64>,
pub started_at: Option<DateTime<FixedOffset>>,
pub ended_at: Option<DateTime<FixedOffset>>,
pub note: Option<String>,
}
#[derive(Debug, Default, Clone, Deserialize)]
pub struct EntryFilter {
#[serde(default, deserialize_with = "empty_as_none")]
pub from: Option<NaiveDate>,
/// Inclusive.
#[serde(default, deserialize_with = "empty_as_none")]
pub to: Option<NaiveDate>,
#[serde(default, deserialize_with = "empty_as_none")]
pub client_id: Option<i64>,
#[serde(default, deserialize_with = "empty_as_none")]
pub project_id: Option<i64>,
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GroupBy {
Client,
#[default]
Project,
Day,
}
#[derive(Debug, Default, Clone, Deserialize)]
pub struct ReportQuery {
#[serde(default, deserialize_with = "empty_as_none")]
pub from: Option<NaiveDate>,
#[serde(default, deserialize_with = "empty_as_none")]
pub to: Option<NaiveDate>,
#[serde(default)]
pub group_by: GroupBy,
#[serde(default, deserialize_with = "empty_as_none")]
pub client_id: Option<i64>,
#[serde(default, deserialize_with = "empty_as_none")]
pub project_id: Option<i64>,
}
#[derive(Debug, Serialize)]
pub struct Report {
pub from: NaiveDate,
pub to: NaiveDate,
pub group_by: GroupBy,
pub rows: Vec<ReportRow>,
pub total_seconds: i64,
}
impl Report {
pub fn total(&self) -> String {
clock::hhmm(self.total_seconds)
}
}
#[derive(Debug, Serialize)]
pub struct ReportRow {
pub key: String,
pub label: String,
pub seconds: i64,
/// Client or project color; `None` for days.
pub color: Option<String>,
/// Share of the largest row, 0–100, for bar rendering.
pub percent: u32,
}
impl ReportRow {
pub fn duration(&self) -> String {
clock::hhmm(self.seconds)
}
}
/// Distinguishes an explicit `null` (`Some(None)`) from an absent field (`None`).
fn present<'de, D, T>(de: D) -> Result<Option<Option<T>>, D::Error>
where
D: Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<T>::deserialize(de).map(Some)
}
/// HTML forms send empty strings for unset fields.
pub fn empty_as_none<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
T: FromStr,
T::Err: Display,
{
match Option::<String>::deserialize(de)? {
Some(s) if !s.trim().is_empty() => {
s.trim().parse().map(Some).map_err(serde::de::Error::custom)
}
_ => Ok(None),
}
}
+87
View File
@@ -0,0 +1,87 @@
use sqlx::SqlitePool;
use super::{PALETTE, affected, clean_color, clean_name};
use crate::clock;
use crate::error::{AppError, AppResult};
use crate::models::{Client, UpdateInput};
pub async fn list(pool: &SqlitePool, include_archived: bool) -> AppResult<Vec<Client>> {
Ok(sqlx::query_as(
"SELECT id, name, color, archived, created_at FROM clients
WHERE ?1 OR archived = 0
ORDER BY archived, name COLLATE NOCASE",
)
.bind(include_archived)
.fetch_all(pool)
.await?)
}
pub async fn get(pool: &SqlitePool, id: i64) -> AppResult<Client> {
Ok(
sqlx::query_as("SELECT id, name, color, archived, created_at FROM clients WHERE id = ?1")
.bind(id)
.fetch_one(pool)
.await?,
)
}
pub async fn create(pool: &SqlitePool, name: &str, color: Option<&str>) -> AppResult<Client> {
let name = clean_name(name)?;
let color = match color {
Some(c) => clean_color(c)?,
None => next_color(pool).await?,
};
let id = sqlx::query("INSERT INTO clients (name, color, created_at) VALUES (?1, ?2, ?3)")
.bind(name)
.bind(color)
.bind(clock::ts(&clock::now()))
.execute(pool)
.await?
.last_insert_rowid();
get(pool, id).await
}
pub async fn update(pool: &SqlitePool, id: i64, input: &UpdateInput) -> AppResult<Client> {
let name = input.name.as_deref().map(clean_name).transpose()?;
let color = match &input.color {
None => None,
Some(Some(c)) => Some(clean_color(c)?),
Some(None) => {
return Err(AppError::Validation(
"un client doit avoir une couleur".into(),
));
}
};
affected(
sqlx::query(
"UPDATE clients SET name = COALESCE(?2, name), archived = COALESCE(?3, archived),
color = COALESCE(?4, color)
WHERE id = ?1",
)
.bind(id)
.bind(name)
.bind(input.archived)
.bind(color)
.execute(pool)
.await?,
)?;
get(pool, id).await
}
/// The palette color for the next client, cycling once all are used.
pub async fn next_color(pool: &SqlitePool) -> AppResult<String> {
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM clients")
.fetch_one(pool)
.await?;
Ok(PALETTE[count as usize % PALETTE.len()].to_owned())
}
/// Deletes the client with all its projects and time entries.
pub async fn delete(pool: &SqlitePool, id: i64) -> AppResult<()> {
affected(
sqlx::query("DELETE FROM clients WHERE id = ?1")
.bind(id)
.execute(pool)
.await?,
)
}
+193
View File
@@ -0,0 +1,193 @@
use chrono::{DateTime, Duration, Utc};
use sqlx::SqlitePool;
use super::affected;
use crate::clock;
use crate::error::{AppError, AppResult};
use crate::models::{Entry, EntryFilter, NewEntry, UpdateEntry};
/// `?1` is always "now", used to measure running entries.
const SELECT: &str =
"SELECT e.id, e.project_id, p.name AS project_name, p.client_id, c.name AS client_name,
COALESCE(p.color, c.color) AS color, c.color AS client_color,
e.started_at, e.ended_at, e.note,
strftime('%s', COALESCE(e.ended_at, ?1)) - strftime('%s', e.started_at) AS seconds,
EXISTS (SELECT 1 FROM time_entries o
WHERE o.id <> e.id
AND o.started_at < COALESCE(e.ended_at, ?1)
AND COALESCE(o.ended_at, ?1) > e.started_at) AS overlaps
FROM time_entries e
JOIN projects p ON p.id = e.project_id
JOIN clients c ON c.id = p.client_id";
/// Entries intersecting the filter's period, most recent first.
pub async fn list(
pool: &SqlitePool,
filter: &EntryFilter,
now: DateTime<Utc>,
) -> AppResult<Vec<Entry>> {
let from = filter.from.map(|d| clock::ts(&clock::local_midnight(d)));
let to = filter
.to
.map(|d| clock::ts(&clock::local_midnight(d + Duration::days(1))));
Ok(sqlx::query_as(&format!(
"{SELECT}
WHERE (?2 IS NULL OR COALESCE(e.ended_at, ?1) > ?2)
AND (?3 IS NULL OR e.started_at < ?3)
AND (?4 IS NULL OR p.client_id = ?4)
AND (?5 IS NULL OR e.project_id = ?5)
ORDER BY e.started_at DESC"
))
.bind(clock::ts(&now))
.bind(from)
.bind(to)
.bind(filter.client_id)
.bind(filter.project_id)
.fetch_all(pool)
.await?)
}
pub async fn get(pool: &SqlitePool, id: i64) -> AppResult<Entry> {
Ok(sqlx::query_as(&format!("{SELECT} WHERE e.id = ?2"))
.bind(clock::ts(&clock::now()))
.bind(id)
.fetch_one(pool)
.await?)
}
/// The running timer, if any.
pub async fn running(pool: &SqlitePool) -> AppResult<Option<Entry>> {
Ok(
sqlx::query_as(&format!("{SELECT} WHERE e.ended_at IS NULL"))
.bind(clock::ts(&clock::now()))
.fetch_optional(pool)
.await?,
)
}
/// Starts a timer on `project_id`, stopping the running one first if needed.
pub async fn start(pool: &SqlitePool, project_id: i64, note: &str) -> AppResult<Entry> {
super::projects::get_active(pool, project_id).await?;
let now = clock::now();
let mut tx = pool.begin().await?;
// An entry started in this very second would end up empty: drop it instead.
sqlx::query("DELETE FROM time_entries WHERE ended_at IS NULL AND started_at >= ?1")
.bind(clock::ts(&now))
.execute(&mut *tx)
.await?;
sqlx::query("UPDATE time_entries SET ended_at = ?1 WHERE ended_at IS NULL")
.bind(clock::ts(&now))
.execute(&mut *tx)
.await?;
let id =
sqlx::query("INSERT INTO time_entries (project_id, started_at, note) VALUES (?1, ?2, ?3)")
.bind(project_id)
.bind(clock::ts(&now))
.bind(note.trim())
.execute(&mut *tx)
.await?
.last_insert_rowid();
tx.commit().await?;
get(pool, id).await
}
/// Stops the running timer.
pub async fn stop(pool: &SqlitePool) -> AppResult<Entry> {
let entry = running(pool)
.await?
.ok_or_else(|| AppError::Conflict("aucun timer en cours".into()))?;
let now = clock::now();
if now <= entry.started_at {
// Less than a second of work: nothing worth keeping.
delete(pool, entry.id).await?;
return Err(AppError::Conflict(
"timer arrêté sans durée, entrée supprimée".into(),
));
}
sqlx::query("UPDATE time_entries SET ended_at = ?2 WHERE id = ?1")
.bind(entry.id)
.bind(clock::ts(&now))
.execute(pool)
.await?;
get(pool, entry.id).await
}
pub async fn create(pool: &SqlitePool, input: &NewEntry) -> AppResult<Entry> {
super::projects::get_active(pool, input.project_id).await?;
let started = input.started_at.with_timezone(&Utc);
let ended = input.ended_at.with_timezone(&Utc);
validate_span(&started, Some(&ended))?;
let id = sqlx::query(
"INSERT INTO time_entries (project_id, started_at, ended_at, note) VALUES (?1, ?2, ?3, ?4)",
)
.bind(input.project_id)
.bind(clock::ts(&started))
.bind(clock::ts(&ended))
.bind(input.note.trim())
.execute(pool)
.await?
.last_insert_rowid();
get(pool, id).await
}
pub async fn update(pool: &SqlitePool, id: i64, input: &UpdateEntry) -> AppResult<Entry> {
let current = get(pool, id).await?;
let project_id = input.project_id.unwrap_or(current.project_id);
if project_id != current.project_id {
super::projects::get_active(pool, project_id).await?;
}
let started = input
.started_at
.map(|d| d.with_timezone(&Utc))
.unwrap_or(current.started_at);
let ended = input
.ended_at
.map(|d| d.with_timezone(&Utc))
.or(current.ended_at);
validate_span(&started, ended.as_ref())?;
let note = input.note.as_deref().unwrap_or(&current.note).trim();
sqlx::query(
"UPDATE time_entries SET project_id = ?2, started_at = ?3, ended_at = ?4, note = ?5
WHERE id = ?1",
)
.bind(id)
.bind(project_id)
.bind(clock::ts(&started))
.bind(ended.as_ref().map(clock::ts))
.bind(note)
.execute(pool)
.await?;
get(pool, id).await
}
pub async fn delete(pool: &SqlitePool, id: i64) -> AppResult<()> {
affected(
sqlx::query("DELETE FROM time_entries WHERE id = ?1")
.bind(id)
.execute(pool)
.await?,
)
}
fn validate_span(started: &DateTime<Utc>, ended: Option<&DateTime<Utc>>) -> AppResult<()> {
match ended {
Some(ended) if ended <= started => Err(AppError::Validation(
"la fin doit être postérieure au début".into(),
)),
// A running entry cannot start in the future.
None if *started > clock::now() => Err(AppError::Validation(
"un timer en cours ne peut pas commencer dans le futur".into(),
)),
_ => Ok(()),
}
}
/// The project of the most recently started entry.
pub async fn last_project_id(pool: &SqlitePool) -> AppResult<Option<i64>> {
Ok(
sqlx::query_scalar("SELECT project_id FROM time_entries ORDER BY started_at DESC LIMIT 1")
.fetch_optional(pool)
.await?,
)
}
+43
View File
@@ -0,0 +1,43 @@
pub mod clients;
pub mod entries;
pub mod projects;
pub mod reports;
use crate::error::{AppError, AppResult};
/// Trims a user-provided name and rejects empty ones.
fn clean_name(name: &str) -> AppResult<String> {
let name = name.trim();
if name.is_empty() {
return Err(AppError::Validation("le nom ne peut pas être vide".into()));
}
Ok(name.to_owned())
}
/// Colors handed out to new clients, in order.
pub const PALETTE: [&str; 8] = [
"#2f6f5e", "#3b6fb6", "#c2410c", "#7c3aed", "#be185d", "#a16207", "#0e7490", "#4d7c0f",
];
/// Validates a `#rrggbb` color and normalizes it to lowercase.
fn clean_color(color: &str) -> AppResult<String> {
let color = color.trim();
let valid = color.len() == 7
&& color.starts_with('#')
&& color[1..].chars().all(|c| c.is_ascii_hexdigit());
if !valid {
return Err(AppError::Validation(format!(
"couleur invalide « {color} » (format attendu : #rrggbb)"
)));
}
Ok(color.to_ascii_lowercase())
}
/// Maps "zero rows affected" to `NotFound`.
fn affected(result: sqlx::sqlite::SqliteQueryResult) -> AppResult<()> {
if result.rows_affected() == 0 {
Err(AppError::NotFound)
} else {
Ok(())
}
}
+105
View File
@@ -0,0 +1,105 @@
use sqlx::SqlitePool;
use super::{affected, clean_color, clean_name};
use crate::clock;
use crate::error::{AppError, AppResult};
use crate::models::{Project, UpdateInput};
const SELECT: &str = "SELECT p.id, p.client_id, c.name AS client_name, p.name,
p.color, COALESCE(p.color, c.color) AS effective_color, p.archived, p.created_at
FROM projects p JOIN clients c ON c.id = p.client_id";
/// Lists projects, optionally for one client. Archived projects (or projects of
/// archived clients) are only included on request.
pub async fn list(
pool: &SqlitePool,
client_id: Option<i64>,
include_archived: bool,
) -> AppResult<Vec<Project>> {
Ok(sqlx::query_as(&format!(
"{SELECT}
WHERE (?1 IS NULL OR p.client_id = ?1)
AND (?2 OR (p.archived = 0 AND c.archived = 0))
ORDER BY c.name COLLATE NOCASE, p.archived, p.name COLLATE NOCASE"
))
.bind(client_id)
.bind(include_archived)
.fetch_all(pool)
.await?)
}
pub async fn get(pool: &SqlitePool, id: i64) -> AppResult<Project> {
Ok(sqlx::query_as(&format!("{SELECT} WHERE p.id = ?1"))
.bind(id)
.fetch_one(pool)
.await?)
}
pub async fn create(
pool: &SqlitePool,
client_id: i64,
name: &str,
color: Option<&str>,
) -> AppResult<Project> {
let name = clean_name(name)?;
let color = color.map(clean_color).transpose()?;
// Surface a missing client as 404 rather than a foreign key error.
super::clients::get(pool, client_id).await?;
let id = sqlx::query(
"INSERT INTO projects (client_id, name, color, created_at) VALUES (?1, ?2, ?3, ?4)",
)
.bind(client_id)
.bind(name)
.bind(color)
.bind(clock::ts(&clock::now()))
.execute(pool)
.await?
.last_insert_rowid();
get(pool, id).await
}
pub async fn update(pool: &SqlitePool, id: i64, input: &UpdateInput) -> AppResult<Project> {
let name = input.name.as_deref().map(clean_name).transpose()?;
let color = match &input.color {
Some(Some(c)) => Some(clean_color(c)?),
_ => None,
};
affected(
sqlx::query(
"UPDATE projects SET name = COALESCE(?2, name), archived = COALESCE(?3, archived),
color = CASE WHEN ?4 THEN ?5 ELSE color END
WHERE id = ?1",
)
.bind(id)
.bind(name)
.bind(input.archived)
.bind(input.color.is_some())
.bind(color)
.execute(pool)
.await?,
)?;
get(pool, id).await
}
/// Deletes the project with all its time entries.
pub async fn delete(pool: &SqlitePool, id: i64) -> AppResult<()> {
affected(
sqlx::query("DELETE FROM projects WHERE id = ?1")
.bind(id)
.execute(pool)
.await?,
)
}
/// Fetches a project that time can be tracked on.
pub async fn get_active(pool: &SqlitePool, id: i64) -> AppResult<Project> {
let project = get(pool, id).await.map_err(|e| match e {
AppError::NotFound => AppError::Validation("projet inconnu".into()),
e => e,
})?;
let client = super::clients::get(pool, project.client_id).await?;
if project.archived || client.archived {
return Err(AppError::Validation("ce projet est archivé".into()));
}
Ok(project)
}
+130
View File
@@ -0,0 +1,130 @@
use std::collections::HashMap;
use chrono::{DateTime, Duration, NaiveDate, Utc};
use sqlx::SqlitePool;
use crate::clock;
use crate::error::{AppError, AppResult};
use crate::models::{Entry, EntryFilter, GroupBy, Report, ReportRow};
/// Above this span, days without any time are not listed.
const MAX_FILLED_DAYS: i64 = 62;
pub async fn build(
pool: &SqlitePool,
from: NaiveDate,
to: NaiveDate,
group_by: GroupBy,
client_id: Option<i64>,
project_id: Option<i64>,
now: DateTime<Utc>,
) -> AppResult<Report> {
if to < from {
return Err(AppError::Validation(
"la date de fin précède la date de début".into(),
));
}
let filter = EntryFilter {
from: Some(from),
to: Some(to),
client_id,
project_id,
};
let entries = super::entries::list(pool, &filter, now).await?;
Ok(aggregate(&entries, from, to, group_by, now))
}
/// Sums entry durations clipped to `[from, to]` (local days, inclusive).
pub fn aggregate(
entries: &[Entry],
from: NaiveDate,
to: NaiveDate,
group_by: GroupBy,
now: DateTime<Utc>,
) -> Report {
let start = clock::local_midnight(from);
let end = clock::local_midnight(to + Duration::days(1));
let mut totals: HashMap<String, (String, Option<String>, i64)> = HashMap::new();
let mut add = |key: String, label: String, color: Option<&str>, seconds: i64| {
totals
.entry(key)
.or_insert((label, color.map(str::to_owned), 0))
.2 += seconds;
};
for e in entries {
let s = e.started_at.max(start);
let t = e.ended_at.unwrap_or(now).min(end);
if t <= s {
continue;
}
match group_by {
GroupBy::Client => add(
e.client_id.to_string(),
e.client_name.clone(),
Some(&e.client_color),
secs(s, t),
),
GroupBy::Project => add(
e.project_id.to_string(),
format!("{} / {}", e.client_name, e.project_name),
Some(&e.color),
secs(s, t),
),
GroupBy::Day => {
// Split at local midnights so an entry spanning two days counts on both.
let mut cur = s;
while cur < t {
let day = clock::local_date(&cur);
let next = clock::local_midnight(day + Duration::days(1)).min(t);
add(day.to_string(), clock::fmt_day(day), None, secs(cur, next));
cur = next;
}
}
}
}
if group_by == GroupBy::Day && (to - from).num_days() < MAX_FILLED_DAYS {
for day in from.iter_days().take_while(|d| *d <= to) {
add(day.to_string(), clock::fmt_day(day), None, 0);
}
}
let mut rows: Vec<ReportRow> = totals
.into_iter()
.map(|(key, (label, color, seconds))| ReportRow {
key,
label,
seconds,
color,
percent: 0,
})
.collect();
match group_by {
// ISO dates sort chronologically.
GroupBy::Day => rows.sort_by(|a, b| a.key.cmp(&b.key)),
_ => rows.sort_by(|a, b| {
b.seconds
.cmp(&a.seconds)
.then_with(|| a.label.cmp(&b.label))
}),
}
let max = rows.iter().map(|r| r.seconds).max().unwrap_or(0);
if max > 0 {
for r in &mut rows {
r.percent = (r.seconds * 100 / max) as u32;
}
}
Report {
from,
to,
group_by,
total_seconds: rows.iter().map(|r| r.seconds).sum(),
rows,
}
}
fn secs(from: DateTime<Utc>, to: DateTime<Utc>) -> i64 {
(to - from).num_seconds()
}
+184
View File
@@ -0,0 +1,184 @@
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::routing::{get, patch, post};
use axum::{Json, Router};
use serde::Deserialize;
use sqlx::SqlitePool;
use crate::clock;
use crate::error::AppResult;
use crate::models::{
Client, Entry, EntryFilter, NameInput, NewEntry, Project, Report, ReportQuery, StartTimer,
UpdateEntry, UpdateInput,
};
use crate::repo::{clients, entries, projects, reports};
pub fn router() -> Router<SqlitePool> {
Router::new()
.route("/clients", get(list_clients).post(create_client))
.route("/clients/{id}", patch(update_client).delete(delete_client))
.route(
"/clients/{id}/projects",
get(list_projects).post(create_project),
)
.route(
"/projects/{id}",
patch(update_project).delete(delete_project),
)
.route("/timer", get(timer))
.route("/timer/start", post(start_timer))
.route("/timer/stop", post(stop_timer))
.route("/entries", get(list_entries).post(create_entry))
.route("/entries/{id}", patch(update_entry).delete(delete_entry))
.route("/reports", get(report))
}
#[derive(Deserialize)]
struct ArchivedQuery {
#[serde(default)]
archived: bool,
}
async fn list_clients(
State(pool): State<SqlitePool>,
Query(q): Query<ArchivedQuery>,
) -> AppResult<Json<Vec<Client>>> {
Ok(Json(clients::list(&pool, q.archived).await?))
}
async fn create_client(
State(pool): State<SqlitePool>,
Json(input): Json<NameInput>,
) -> AppResult<(StatusCode, Json<Client>)> {
Ok((
StatusCode::CREATED,
Json(clients::create(&pool, &input.name, input.color.as_deref()).await?),
))
}
async fn update_client(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Json(input): Json<UpdateInput>,
) -> AppResult<Json<Client>> {
Ok(Json(clients::update(&pool, id, &input).await?))
}
async fn delete_client(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
) -> AppResult<StatusCode> {
clients::delete(&pool, id).await?;
Ok(StatusCode::NO_CONTENT)
}
async fn list_projects(
State(pool): State<SqlitePool>,
Path(client_id): Path<i64>,
Query(q): Query<ArchivedQuery>,
) -> AppResult<Json<Vec<Project>>> {
clients::get(&pool, client_id).await?;
Ok(Json(
projects::list(&pool, Some(client_id), q.archived).await?,
))
}
async fn create_project(
State(pool): State<SqlitePool>,
Path(client_id): Path<i64>,
Json(input): Json<NameInput>,
) -> AppResult<(StatusCode, Json<Project>)> {
Ok((
StatusCode::CREATED,
Json(projects::create(&pool, client_id, &input.name, input.color.as_deref()).await?),
))
}
async fn update_project(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Json(input): Json<UpdateInput>,
) -> AppResult<Json<Project>> {
Ok(Json(projects::update(&pool, id, &input).await?))
}
async fn delete_project(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
) -> AppResult<StatusCode> {
projects::delete(&pool, id).await?;
Ok(StatusCode::NO_CONTENT)
}
async fn timer(State(pool): State<SqlitePool>) -> AppResult<Json<Option<Entry>>> {
Ok(Json(entries::running(&pool).await?))
}
async fn start_timer(
State(pool): State<SqlitePool>,
Json(input): Json<StartTimer>,
) -> AppResult<(StatusCode, Json<Entry>)> {
Ok((
StatusCode::CREATED,
Json(entries::start(&pool, input.project_id, &input.note).await?),
))
}
async fn stop_timer(State(pool): State<SqlitePool>) -> AppResult<Json<Entry>> {
Ok(Json(entries::stop(&pool).await?))
}
async fn list_entries(
State(pool): State<SqlitePool>,
Query(filter): Query<EntryFilter>,
) -> AppResult<Json<Vec<Entry>>> {
Ok(Json(entries::list(&pool, &filter, clock::now()).await?))
}
async fn create_entry(
State(pool): State<SqlitePool>,
Json(input): Json<NewEntry>,
) -> AppResult<(StatusCode, Json<Entry>)> {
Ok((
StatusCode::CREATED,
Json(entries::create(&pool, &input).await?),
))
}
async fn update_entry(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
Json(input): Json<UpdateEntry>,
) -> AppResult<Json<Entry>> {
Ok(Json(entries::update(&pool, id, &input).await?))
}
async fn delete_entry(
State(pool): State<SqlitePool>,
Path(id): Path<i64>,
) -> AppResult<StatusCode> {
entries::delete(&pool, id).await?;
Ok(StatusCode::NO_CONTENT)
}
/// Defaults to the current week.
async fn report(
State(pool): State<SqlitePool>,
Query(q): Query<ReportQuery>,
) -> AppResult<Json<Report>> {
let today = clock::today();
let from = q.from.unwrap_or_else(|| clock::week_start(today));
let to = q.to.unwrap_or(today.max(from));
Ok(Json(
reports::build(
&pool,
from,
to,
q.group_by,
q.client_id,
q.project_id,
clock::now(),
)
.await?,
))
}
+40
View File
@@ -0,0 +1,40 @@
mod api;
mod pages;
use axum::Router;
use axum::http::header;
use axum::response::IntoResponse;
use axum::routing::get;
use sqlx::SqlitePool;
use tower_http::trace::TraceLayer;
pub fn app(pool: SqlitePool) -> Router {
Router::new()
.merge(pages::router())
.nest("/api", api::router())
.route("/health", get(|| async { "ok" }))
.route(
"/static/htmx.min.js",
get(|| asset("text/javascript", include_str!("../../static/htmx.min.js"))),
)
.route(
"/static/app.js",
get(|| asset("text/javascript", include_str!("../../static/app.js"))),
)
.route(
"/static/app.css",
get(|| asset("text/css", include_str!("../../static/app.css"))),
)
.layer(TraceLayer::new_for_http())
.with_state(pool)
}
async fn asset(content_type: &'static str, body: &'static str) -> impl IntoResponse {
(
[
(header::CONTENT_TYPE, content_type),
(header::CACHE_CONTROL, "public, max-age=3600"),
],
body,
)
}
+620
View File
@@ -0,0 +1,620 @@
//! 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/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))
}
// --- 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,
}
#[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,
}
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 dashboard(State(pool): State<SqlitePool>) -> PageResult {
let TimerTpl { running, groups } = timer_state(&pool).await?;
let TodayTpl {
today_entries,
today_total,
} = today_state(&pool).await?;
render(DashboardTpl {
nav: "dashboard",
running,
groups,
today_entries,
today_total,
})
}
async fn today_fragment(State(pool): State<SqlitePool>) -> PageResult {
render(today_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>,
}
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 })
}
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,
})
}
+161
View File
@@ -0,0 +1,161 @@
:root {
--bg: #f6f5f2;
--surface: #ffffff;
--text: #1d1d1f;
--muted: #6b6b70;
--border: #e3e1dc;
--accent: #2f6f5e;
--accent-text: #ffffff;
--danger: #b3402f;
--running: #e8f3ef;
--warn: #b7791f;
--radius: 10px;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #151517;
--surface: #1f1f22;
--text: #ececef;
--muted: #9a9aa2;
--border: #2f2f34;
--accent: #5fb39a;
--accent-text: #0d1f1a;
--danger: #e0705e;
--running: #1d2e29;
--warn: #e0a84a;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif;
}
a { color: var(--accent); }
h1, h2 { margin: 0 0 .75rem; font-weight: 600; }
h2 { font-size: 1.1rem; }
.topbar {
display: flex; align-items: center; gap: 2rem; flex-wrap: wrap;
padding: .75rem max(16px, calc((100vw - 960px) / 2));
background: var(--surface); border-bottom: 1px solid var(--border);
}
.brand { font-weight: 700; font-size: 1.15rem; color: var(--text); text-decoration: none; }
.topbar nav { display: flex; gap: .25rem; flex-wrap: wrap; }
.topbar nav a {
padding: .35rem .75rem; border-radius: 999px; color: var(--muted); text-decoration: none;
}
.topbar nav a[aria-current="page"] { background: var(--bg); color: var(--text); font-weight: 600; }
main { max-width: 960px; margin: 1.5rem auto; padding: 0 16px; display: grid; gap: 1rem; }
.card {
background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
padding: 1.25rem; min-width: 0;
}
.card.archived { opacity: .65; }
.card-head { display: flex; justify-content: space-between; align-items: center; gap: 1rem; flex-wrap: wrap; margin-bottom: .75rem; }
.card-head h2 { margin: 0; }
.total { font-variant-numeric: tabular-nums; font-weight: 600; font-size: 1.1rem; }
.row { display: flex; gap: .5rem; align-items: center; }
.row.wrap { flex-wrap: wrap; }
.grow { flex: 1; min-width: 0; }
.row.grow input { flex: 1; min-width: 0; }
.stack { display: grid; gap: .35rem; }
.muted, .empty { color: var(--muted); }
.empty { margin: .25rem 0; }
.nowrap { white-space: nowrap; }
input, select, button { font: inherit; color: inherit; }
input, select {
background: var(--bg); border: 1px solid var(--border); border-radius: 8px;
padding: .45rem .6rem; min-width: 0; max-width: 100%;
}
input:focus, select:focus { outline: 2px solid var(--accent); outline-offset: -1px; }
.title-input { font-weight: 600; font-size: 1.05rem; }
label { display: flex; align-items: center; gap: .35rem; color: var(--muted); }
.btn {
border: 1px solid var(--border); background: var(--surface); border-radius: 8px;
padding: .45rem .9rem; cursor: pointer; white-space: nowrap;
}
.btn:hover { border-color: var(--muted); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; }
.btn.danger { color: var(--danger); }
.btn.small { padding: .2rem .55rem; font-size: .85rem; }
.htmx-request .btn, .btn.htmx-request { opacity: .6; }
.badge { font-size: .75rem; padding: .1rem .5rem; border-radius: 999px; background: var(--bg); color: var(--muted); }
/* Timer */
.timer.is-running { background: var(--running); border-color: var(--color, var(--accent)); border-left-width: 6px; }
.current { display: grid; grid-template-columns: 1fr auto auto; gap: 1rem; align-items: center; margin-bottom: 1rem; }
.current-project { font-size: 1.3rem; font-weight: 600; }
.clock { font-size: 2rem; font-weight: 600; font-variant-numeric: tabular-nums; }
.start { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr) auto; gap: .5rem; }
.note { color: var(--muted); font-size: .9rem; }
/* Tables */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; font-weight: 500; color: var(--muted); font-size: .85rem; }
th, td { padding: .5rem .5rem; border-bottom: 1px solid var(--border); vertical-align: top; }
tr:last-child td { border-bottom: 0; }
.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
.time { white-space: nowrap; font-variant-numeric: tabular-nums; color: var(--muted); }
.client { color: var(--muted); }
tr.running { background: var(--running); }
tr.editing td { background: var(--bg); }
tr.editing input, tr.editing select { width: 100%; }
td.actions { text-align: right; white-space: nowrap; }
.warn { color: var(--warn); cursor: help; }
/* Colors */
.dot {
display: inline-block; width: .65rem; height: .65rem; border-radius: 50%;
background: var(--color); margin-right: .4rem; vertical-align: baseline; flex: none;
}
.client-card { border-left: 6px solid var(--color); }
input[type="color"] {
width: 2.2rem; height: 2.2rem; padding: .15rem; flex: none; cursor: pointer;
}
.projects input[type="color"] { width: 1.8rem; height: 1.8rem; }
/* Projects list */
.projects { list-style: none; margin: 0 0 1rem; padding: 0; }
.projects li {
display: flex; justify-content: space-between; align-items: center; gap: .5rem; flex-wrap: wrap;
padding: .4rem 0; border-bottom: 1px solid var(--border);
}
.projects li.archived { opacity: .6; }
/* Periods & reports */
.presets { display: flex; gap: .35rem; flex-wrap: wrap; margin-bottom: .75rem; }
.presets a {
padding: .25rem .7rem; border-radius: 999px; border: 1px solid var(--border);
color: var(--muted); text-decoration: none; font-size: .9rem;
}
.presets a[aria-current="true"] { border-color: var(--accent); color: var(--accent); font-weight: 600; }
.filters { margin-bottom: 1rem; }
.report .label { width: 35%; }
.bar-cell { width: 50%; vertical-align: middle; }
.bar { height: .7rem; border-radius: 4px; background: var(--color, var(--accent)); min-width: 2px; }
.report tfoot td { font-weight: 600; border-top: 2px solid var(--border); }
#toast {
position: fixed; bottom: 1rem; left: 50%; transform: translateX(-50%);
background: var(--danger); color: #fff; padding: .6rem 1rem; border-radius: 8px;
max-width: calc(100vw - 32px); box-shadow: 0 4px 16px rgb(0 0 0 / .2);
}
@media (max-width: 640px) {
.current { grid-template-columns: 1fr auto; }
.current .btn { grid-column: 1 / -1; }
.start { grid-template-columns: 1fr; }
.report .label { width: auto; }
.bar-cell { width: 30%; }
}
+33
View File
@@ -0,0 +1,33 @@
// Live clock for the running timer.
function tick() {
for (const el of document.querySelectorAll(".clock[data-started]")) {
const secs = Math.max(0, Math.floor((Date.now() - Date.parse(el.dataset.started)) / 1000));
const h = Math.floor(secs / 3600);
const m = String(Math.floor((secs % 3600) / 60)).padStart(2, "0");
const s = String(secs % 60).padStart(2, "0");
el.textContent = `${h}:${m}:${s}`;
}
}
tick();
setInterval(tick, 1000);
// Show server errors from htmx requests in a toast.
let toastTimer;
function toast(message) {
const el = document.getElementById("toast");
el.textContent = message;
el.hidden = false;
clearTimeout(toastTimer);
toastTimer = setTimeout(() => (el.hidden = true), 5000);
}
document.body.addEventListener("htmx:responseError", (event) => {
const html = new DOMParser().parseFromString(event.detail.xhr.responseText, "text/html");
toast(html.getElementById("error-message")?.textContent || "Une erreur est survenue");
});
document.body.addEventListener("htmx:sendError", () => toast("Serveur injoignable"));
// Confirmation for plain (non-htmx) destructive forms.
document.addEventListener("submit", (event) => {
const message = event.target.dataset.confirm;
if (message && !confirm(message)) event.preventDefault();
});
+1
View File
@@ -0,0 +1 @@
var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/<head(\s[^>]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('<body><template class="internal-htmx-wrapper">'+t+"</template></body>");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toStrinLine truncated
+19
View File
@@ -0,0 +1,19 @@
<tr id="entry-{{ e.id }}" class="editing">
<td colspan="2">
<div class="stack">
<input type="datetime-local" name="started_at" value="{{ e.start_input() }}" required aria-label="Début">
{% if e.running() %}
<span class="muted">en cours</span>
{% else %}
<input type="datetime-local" name="ended_at" value="{{ e.end_input() }}" required aria-label="Fin">
{% endif %}
</div>
</td>
<td><select name="project_id" aria-label="Projet">{% include "_project_select.html" %}</select></td>
<td><input name="note" value="{{ e.note }}" aria-label="Note"></td>
<td></td>
<td class="actions">
<button class="btn small primary" hx-put="/ui/entries/{{ e.id }}" hx-include="closest tr" hx-target="closest tr" hx-swap="outerHTML">Enregistrer</button>
<button class="btn small" hx-get="/ui/entries/{{ e.id }}" hx-target="closest tr" hx-swap="outerHTML">Annuler</button>
</td>
</tr>
+14
View File
@@ -0,0 +1,14 @@
<tr id="entry-{{ e.id }}"{% if e.running() %} class="running"{% endif %}>
<td class="nowrap">{{ e.day() }}</td>
<td class="time">
{{ e.start_time() }} – {{ e.end_time() }}
{% if e.overlaps %}<span class="warn" title="Chevauche une autre entrée">⚠</span>{% endif %}
</td>
<td><span class="dot" style="--color: {{ e.color }}"></span><span class="client">{{ e.client_name }}</span> / {{ e.project_name }}</td>
<td class="note">{{ e.note }}</td>
<td class="num">{{ e.duration() }}</td>
<td class="actions">
<button class="btn small" hx-get="/ui/entries/{{ e.id }}/edit" hx-target="closest tr" hx-swap="outerHTML">Modifier</button>
<button class="btn small danger" hx-delete="/ui/entries/{{ e.id }}" hx-target="closest tr" hx-swap="outerHTML" hx-confirm="Supprimer cette entrée ?">Suppr.</button>
</td>
</tr>
+5
View File
@@ -0,0 +1,5 @@
<div class="presets">
{% for p in presets %}
<a href="?from={{ p.from }}&amp;to={{ p.to }}{{ extra_query }}"{% if p.active %} aria-current="true"{% endif %}>{{ p.label }}</a>
{% endfor %}
</div>
+5
View File
@@ -0,0 +1,5 @@
{% for g in groups %}
<optgroup label="{{ g.name }}">
{% for p in g.projects %}<option value="{{ p.id }}"{% if p.selected %} selected{% endif %}>{{ p.name }}</option>{% endfor %}
</optgroup>
{% endfor %}
+22
View File
@@ -0,0 +1,22 @@
<section id="timer" class="card timer{% if running.is_some() %} is-running{% endif %}"{% if let Some(e) = running %} style="--color: {{ e.color }}"{% endif %}>
{% if let Some(e) = running %}
<div class="current">
<div class="current-label">
<div class="muted"><span class="dot" style="--color: {{ e.client_color }}"></span>{{ e.client_name }}</div>
<div class="current-project">{{ e.project_name }}</div>
{% if !e.note.is_empty() %}<div class="note">{{ e.note }}</div>{% endif %}
</div>
<div class="clock" data-started="{{ e.started_rfc3339() }}">{{ e.duration() }}</div>
<button class="btn danger" hx-post="/ui/timer/stop" hx-target="#timer" hx-swap="outerHTML">Arrêter</button>
</div>
{% endif %}
{% if groups.is_empty() %}
<p class="empty">Aucun projet actif. <a href="/clients">Crée un client et un projet</a> pour commencer.</p>
{% else %}
<form class="start" hx-post="/ui/timer/start" hx-target="#timer" hx-swap="outerHTML">
<select name="project_id" required aria-label="Projet">{% include "_project_select.html" %}</select>
<input name="note" placeholder="Sur quoi travailles-tu ?" aria-label="Note">
<button class="btn primary">{% if running.is_some() %}Basculer{% else %}Démarrer{% endif %}</button>
</form>
{% endif %}
</section>
+24
View File
@@ -0,0 +1,24 @@
<section id="today" class="card" hx-get="/ui/today" hx-trigger="entries-changed from:body" hx-swap="outerHTML">
<div class="card-head">
<h2>Aujourd'hui</h2>
<span class="total">{{ today_total }}</span>
</div>
{% if today_entries.is_empty() %}
<p class="empty">Rien de saisi pour l'instant.</p>
{% else %}
<table class="entries">
<tbody>
{% for e in today_entries %}
<tr{% if e.running() %} class="running"{% endif %}>
<td class="time">{{ e.start_time() }} – {{ e.end_time() }}</td>
<td>
<span class="dot" style="--color: {{ e.color }}"></span><span class="client">{{ e.client_name }}</span> / {{ e.project_name }}
{% if !e.note.is_empty() %}<div class="note">{{ e.note }}</div>{% endif %}
</td>
<td class="num">{{ e.duration() }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endif %}
</section>
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{% block title %}Tempus{% endblock %} · Tempus</title>
<link rel="stylesheet" href="/static/app.css">
<script src="/static/htmx.min.js" defer></script>
<script src="/static/app.js" defer></script>
</head>
<body>
<header class="topbar">
<a class="brand" href="/">Tempus</a>
<nav>
<a href="/" {% if nav == "dashboard" %}aria-current="page"{% endif %}>Aujourd'hui</a>
<a href="/entries" {% if nav == "entries" %}aria-current="page"{% endif %}>Entrées</a>
<a href="/reports" {% if nav == "reports" %}aria-current="page"{% endif %}>Rapports</a>
<a href="/clients" {% if nav == "clients" %}aria-current="page"{% endif %}>Clients</a>
</nav>
</header>
<main>
{% block content %}{% endblock %}
</main>
<div id="toast" role="alert" hidden></div>
</body>
</html>
+70
View File
@@ -0,0 +1,70 @@
{% extends "base.html" %}
{% block title %}Clients{% endblock %}
{% block content %}
<section class="card">
<h2>Nouveau client</h2>
<form method="post" action="/ui/clients" class="row">
<input type="color" name="color" value="{{ next_color }}" aria-label="Couleur du client">
<input name="name" required placeholder="Nom du client" aria-label="Nom du client" class="grow">
<button class="btn primary">Ajouter</button>
</form>
</section>
{% if clients.is_empty() %}
<p class="empty">Aucun client pour l'instant.</p>
{% endif %}
{% for c in clients %}
<section class="card client-card{% if c.client.archived %} archived{% endif %}" style="--color: {{ c.client.color }}">
<div class="card-head">
<form method="post" action="/ui/clients/{{ c.client.id }}" class="row grow">
<input type="color" name="color" value="{{ c.client.color }}" aria-label="Couleur du client">
<input name="name" value="{{ c.client.name }}" required aria-label="Nom du client" class="title-input">
<button class="btn">Enregistrer</button>
</form>
<div class="row">
{% if c.client.archived %}<span class="badge">archivé</span>{% endif %}
<form method="post" action="/ui/clients/{{ c.client.id }}/archive">
<input type="hidden" name="archived" value="{{ !c.client.archived }}">
<button class="btn">{% if c.client.archived %}Réactiver{% else %}Archiver{% endif %}</button>
</form>
<form method="post" action="/ui/clients/{{ c.client.id }}/delete" data-confirm="Supprimer ce client, ses projets et tout le temps saisi ?">
<button class="btn danger">Supprimer</button>
</form>
</div>
</div>
<ul class="projects">
{% for p in c.projects %}
<li{% if p.archived %} class="archived"{% endif %}>
<form method="post" action="/ui/projects/{{ p.id }}" class="row grow">
<input type="color" name="color" value="{{ p.effective_color }}" aria-label="Couleur du projet"
title="{% if p.color.is_some() %}Couleur propre au projet{% else %}Couleur du client{% endif %}">
<input name="name" value="{{ p.name }}" required aria-label="Nom du projet">
<button class="btn small">Enregistrer</button>
{% if p.color.is_some() %}
<button class="btn small" name="inherit" value="true" title="Reprendre la couleur du client">↺</button>
{% endif %}
</form>
<div class="row">
{% if p.archived %}<span class="badge">archivé</span>{% endif %}
<form method="post" action="/ui/projects/{{ p.id }}/archive">
<input type="hidden" name="archived" value="{{ !p.archived }}">
<button class="btn small">{% if p.archived %}Réactiver{% else %}Archiver{% endif %}</button>
</form>
<form method="post" action="/ui/projects/{{ p.id }}/delete" data-confirm="Supprimer ce projet et tout le temps saisi dessus ?">
<button class="btn small danger">Supprimer</button>
</form>
</div>
</li>
{% endfor %}
</ul>
<form method="post" action="/ui/clients/{{ c.client.id }}/projects" class="row">
<input type="color" name="color" value="{{ c.client.color }}" aria-label="Couleur du projet" title="Garder la couleur du client ou en choisir une autre">
<input name="name" required placeholder="Nouveau projet" aria-label="Nouveau projet" class="grow">
<button class="btn">Ajouter le projet</button>
</form>
</section>
{% endfor %}
{% endblock %}
+6
View File
@@ -0,0 +1,6 @@
{% extends "base.html" %}
{% block title %}Aujourd'hui{% endblock %}
{% block content %}
{% include "_timer.html" %}
{% include "_today.html" %}
{% endblock %}
+56
View File
@@ -0,0 +1,56 @@
{% extends "base.html" %}
{% block title %}Entrées{% endblock %}
{% block content %}
<section class="card">
<h2>Ajouter du temps</h2>
{% if groups.is_empty() %}
<p class="empty">Aucun projet actif. <a href="/clients">Crée un client et un projet</a> d'abord.</p>
{% else %}
<form method="post" action="/ui/entries" class="row wrap">
<select name="project_id" required aria-label="Projet">{% include "_project_select.html" %}</select>
<input type="datetime-local" name="started_at" value="{{ default_start }}" required aria-label="Début">
<input type="datetime-local" name="ended_at" value="{{ default_end }}" required aria-label="Fin">
<input name="note" placeholder="Note" aria-label="Note" class="grow">
<button class="btn primary">Ajouter</button>
</form>
{% endif %}
</section>
<section class="card">
<div class="card-head">
<h2>Entrées</h2>
<span class="total">{{ total }}</span>
</div>
{% include "_presets.html" %}
<form method="get" class="row wrap filters">
<label>Du <input type="date" name="from" value="{{ from }}"></label>
<label>au <input type="date" name="to" value="{{ to }}"></label>
<select name="client_id" aria-label="Client">
<option value="">Tous les clients</option>
{% for c in clients %}<option value="{{ c.id }}"{% if c.selected %} selected{% endif %}>{{ c.name }}</option>{% endfor %}
</select>
<select name="project_id" aria-label="Projet">
<option value="">Tous les projets</option>
{% for g in filter_groups %}
<optgroup label="{{ g.name }}">
{% for p in g.projects %}<option value="{{ p.id }}"{% if p.selected %} selected{% endif %}>{{ p.name }}</option>{% endfor %}
</optgroup>
{% endfor %}
</select>
<button class="btn">Filtrer</button>
</form>
{% if entries.is_empty() %}
<p class="empty">Aucune entrée sur cette période.</p>
{% else %}
<div class="table-wrap">
<table class="entries">
<thead><tr><th>Jour</th><th>Horaire</th><th>Projet</th><th>Note</th><th class="num">Durée</th><th></th></tr></thead>
<tbody>
{% for e in entries %}{% include "_entry_row.html" %}{% endfor %}
</tbody>
</table>
</div>
{% endif %}
</section>
{% endblock %}
+9
View File
@@ -0,0 +1,9 @@
{% extends "base.html" %}
{% block title %}Erreur{% endblock %}
{% block content %}
<section class="card">
<h1>Oups</h1>
<p id="error-message">{{ message }}</p>
<p><a href="javascript:history.back()">← Retour</a></p>
</section>
{% endblock %}
+44
View File
@@ -0,0 +1,44 @@
{% extends "base.html" %}
{% block title %}Rapports{% endblock %}
{% block content %}
<section class="card">
<div class="card-head">
<h2>Rapport</h2>
<span class="total">{{ report.total() }}</span>
</div>
{% include "_presets.html" %}
<form method="get" class="row wrap filters">
<label>Du <input type="date" name="from" value="{{ report.from }}"></label>
<label>au <input type="date" name="to" value="{{ report.to }}"></label>
<select name="group_by" aria-label="Regrouper par">
<option value="project"{% if group_by == "project" %} selected{% endif %}>Par projet</option>
<option value="client"{% if group_by == "client" %} selected{% endif %}>Par client</option>
<option value="day"{% if group_by == "day" %} selected{% endif %}>Par jour</option>
</select>
<select name="client_id" aria-label="Client">
<option value="">Tous les clients</option>
{% for c in clients %}<option value="{{ c.id }}"{% if c.selected %} selected{% endif %}>{{ c.name }}</option>{% endfor %}
</select>
<button class="btn">Afficher</button>
</form>
{% if report.rows.is_empty() %}
<p class="empty">Aucun temps sur cette période.</p>
{% else %}
<table class="report">
<tbody>
{% for r in report.rows %}
<tr>
<td class="label">{% if let Some(c) = r.color %}<span class="dot" style="--color: {{ c }}"></span>{% endif %}{{ r.label }}</td>
<td class="bar-cell"><div class="bar" style="width: {{ r.percent }}%{% if let Some(c) = r.color %}; --color: {{ c }}{% endif %}"></div></td>
<td class="num">{{ r.duration() }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr><td>Total</td><td></td><td class="num">{{ report.total() }}</td></tr>
</tfoot>
</table>
{% endif %}
</section>
{% endblock %}
+594
View File
@@ -0,0 +1,594 @@
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<Value>) -> (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&note=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&note=",
)
.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"));
}
#[tokio::test]
async fn colors() {
let app = app().await;
// Palette colors are handed out in order; an explicit color wins.
let (_, a) = send(&app, "POST", "/api/clients", Some(json!({ "name": "A" }))).await;
let (_, b) = send(&app, "POST", "/api/clients", Some(json!({ "name": "B" }))).await;
assert_eq!(a["color"], tempus::repo::PALETTE[0]);
assert_eq!(b["color"], tempus::repo::PALETTE[1]);
let (status, c) = send(
&app,
"POST",
"/api/clients",
Some(json!({ "name": "C", "color": "#FF0000" })),
)
.await;
assert_eq!(status, StatusCode::CREATED);
assert_eq!(c["color"], "#ff0000");
for bad in [json!("red"), json!("#12345"), json!("#gggggg"), Value::Null] {
let (status, _) = send(
&app,
"PATCH",
&format!("/api/clients/{}", a["id"]),
Some(json!({ "color": bad })),
)
.await;
assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{bad}");
}
// Projects inherit their client's color until they get their own.
let (_, p) = send(
&app,
"POST",
&format!("/api/clients/{}/projects", a["id"]),
Some(json!({ "name": "Site" })),
)
.await;
assert!(p["color"].is_null());
assert_eq!(p["effective_color"], a["color"]);
let (_, a2) = send(
&app,
"PATCH",
&format!("/api/clients/{}", a["id"]),
Some(json!({ "color": "#000000" })),
)
.await;
assert_eq!(a2["name"], "A", "other fields are untouched");
let (_, list) = send(
&app,
"GET",
&format!("/api/clients/{}/projects", a["id"]),
None,
)
.await;
assert_eq!(list[0]["effective_color"], "#000000");
let uri = format!("/api/projects/{}", p["id"]);
let (_, p) = send(&app, "PATCH", &uri, Some(json!({ "color": "#00ff00" }))).await;
assert_eq!(p["effective_color"], "#00ff00");
let (_, p) = send(&app, "PATCH", &uri, Some(json!({ "name": "Site web" }))).await;
assert_eq!(p["color"], "#00ff00", "absent color is left unchanged");
// Entries and reports carry the colors.
add_entry(
&app,
p["id"].as_i64().unwrap(),
local(2026, 3, 10, 9, 0),
local(2026, 3, 10, 10, 0),
)
.await;
let (_, entries) = send(&app, "GET", "/api/entries", None).await;
assert_eq!(entries[0]["color"], "#00ff00");
assert_eq!(entries[0]["client_color"], "#000000");
let (_, r) = send(
&app,
"GET",
"/api/reports?from=2026-03-10&to=2026-03-10&group_by=client",
None,
)
.await;
assert_eq!(r["rows"][0]["color"], "#000000");
let (_, r) = send(
&app,
"GET",
"/api/reports?from=2026-03-10&to=2026-03-10&group_by=day",
None,
)
.await;
assert!(r["rows"][0]["color"].is_null());
let (_, p) = send(&app, "PATCH", &uri, Some(json!({ "color": null }))).await;
assert!(p["color"].is_null());
assert_eq!(p["effective_color"], "#000000");
// HTML forms: an untouched picker keeps inheriting, "↺" resets.
let id = p["id"].as_i64().unwrap();
let (status, _) = send_form(
&app,
&format!("/ui/projects/{id}"),
"name=Site&color=%23000000",
)
.await;
assert_eq!(status, StatusCode::SEE_OTHER);
let (_, list) = send(
&app,
"GET",
&format!("/api/clients/{}/projects", a["id"]),
None,
)
.await;
assert!(list[0]["color"].is_null());
send_form(
&app,
&format!("/ui/projects/{id}"),
"name=Site&color=%23123456",
)
.await;
let (_, list) = send(
&app,
"GET",
&format!("/api/clients/{}/projects", a["id"]),
None,
)
.await;
assert_eq!(list[0]["color"], "#123456");
send_form(
&app,
&format!("/ui/projects/{id}"),
"name=Site&color=%23123456&inherit=true",
)
.await;
let (_, list) = send(
&app,
"GET",
&format!("/api/clients/{}/projects", a["id"]),
None,
)
.await;
assert!(list[0]["color"].is_null());
let (status, html) = get_html(&app, "/clients").await;
assert_eq!(status, StatusCode::OK);
assert!(html.contains("--color: #000000"));
}