diff --git a/Cargo.lock b/Cargo.lock index 2536a0e..0823756 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1697,6 +1697,7 @@ dependencies = [ "tokio", "tower", "tower-http", + "tower-livereload", "tracing", "tracing-subscriber", ] @@ -1824,6 +1825,20 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" +[[package]] +name = "tower-livereload" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df210bd982165dee3c20e31deed79a3585ee6b255c070d9c73ae015cc40d2f3" +dependencies = [ + "bytes", + "http", + "http-body", + "pin-project-lite", + "tokio", + "tower", +] + [[package]] name = "tower-service" version = "0.3.3" diff --git a/Cargo.toml b/Cargo.toml index 1118da7..6ad63c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,9 +15,14 @@ sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", thiserror = "2.0.21" tokio = { version = "1.54.1", features = ["full"] } tower-http = { version = "0.7.1", features = ["trace"] } +tower-livereload = { version = "0.10.3", optional = true } tracing = "0.1.44" tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } +[features] +# Recharge le navigateur au redémarrage du serveur (dev uniquement). +livereload = ["dep:tower-livereload"] + [dev-dependencies] http-body-util = "0.1.5" tower = { version = "0.5.3", features = ["util"] } diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..58eb2ca --- /dev/null +++ b/Makefile @@ -0,0 +1,53 @@ +DEPLOY_DIR ?= /var/www/tempus +SERVICE ?= tempus +HOST ?= tempus.loc +ADDR ?= 127.0.0.1:3110 +UNIT := $(HOME)/.config/systemd/user/$(SERVICE).service +SUBST := sed -e 's|@HOST@|$(HOST)|g' -e 's|@ADDR@|$(ADDR)|g' -e 's|@DEPLOY_DIR@|$(DEPLOY_DIR)|g' + +.PHONY: build setup deploy backup status logs dev + +## Compile le binaire (templates, CSS/JS et migrations sont embarqués). +build: + cargo build --release + +## Une seule fois : dossier, vhost Apache et /etc/hosts (sudo), service systemd utilisateur. +setup: + sudo install -d -o $(USER) -g www-data -m 755 $(DEPLOY_DIR) + $(SUBST) deploy/vh_tempus.conf | sudo tee /etc/apache2/sites-available/vh_tempus.conf >/dev/null + sudo a2ensite -q vh_tempus + sudo systemctl reload apache2 + grep -qw '$(HOST)' /etc/hosts || printf '127.0.0.1\t$(HOST)\n' | sudo tee -a /etc/hosts >/dev/null + install -d $(dir $(UNIT)) + $(SUBST) deploy/tempus.service > $(UNIT) + systemctl --user daemon-reload + systemctl --user enable $(SERVICE) + +## Sauvegarde la base, installe le nouveau binaire et redémarre le service. +deploy: build + systemctl --user stop $(SERVICE) + $(MAKE) --no-print-directory backup + install -m 755 target/release/tempus $(DEPLOY_DIR)/tempus + systemctl --user start $(SERVICE) + @for i in $$(seq 1 50); do \ + curl -sf -o /dev/null http://$(ADDR)/health && echo "Déployé : http://$(HOST)" && exit 0; \ + sleep 0.1; \ + done; echo "Le service ne répond pas : make logs" >&2; exit 1 + +## Copie la base (service arrêté) dans $(DEPLOY_DIR)/backups, garde les 10 dernières. +backup: + @if [ -f $(DEPLOY_DIR)/tempus.db ]; then \ + d=$(DEPLOY_DIR)/backups/$$(date +%Y%m%d-%H%M%S); mkdir -p $$d; \ + cp $(DEPLOY_DIR)/tempus.db* $$d/ && echo "Sauvegarde : $$d"; \ + ls -1dt $(DEPLOY_DIR)/backups/*/ | tail -n +11 | xargs -r rm -r; \ + fi + +status: + systemctl --user status $(SERVICE) --no-pager + +logs: + journalctl --user -u $(SERVICE) -f + +## Dev : recompile, redémarre et recharge le navigateur à chaque modif. +dev: + watchexec -r -e rs,html,css,js,sql -- cargo run --features livereload diff --git a/README.md b/README.md index 5a7154c..cdd89cf 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,33 @@ curl -XPOST localhost:7878/api/clients -H 'content-type: application/json' -d '{ curl -XPOST localhost:7878/api/timer/start -H 'content-type: application/json' -d '{"project_id":1}' ``` +## Production locale + +Binaire dans `/var/www/tempus`, service systemd utilisateur, vhost Apache +(reverse proxy) sur http://tempus.loc → `127.0.0.1:3110`. + +```sh +make setup # une fois (sudo) : dossier, vhost, /etc/hosts, service +make deploy # compile, sauvegarde la base, installe, redémarre +make status # / make logs +``` + +La base de prod est `/var/www/tempus/tempus.db` ; chaque `make deploy` la copie +dans `/var/www/tempus/backups/` (10 dernières conservées). Variables +surchargeables : `DEPLOY_DIR`, `HOST`, `ADDR`, `SERVICE`. + ## Développement +Rechargement automatique (recompile, redémarre et rafraîchit le navigateur) : + +```sh +cargo install watchexec-cli # une fois +make dev +``` + +La feature `livereload` injecte un script dans les pages (pas dans les fragments +htmx) et désactive le cache des assets ; elle n'est jamais active par défaut. + ```sh cargo test cargo clippy --all-targets -- -D warnings diff --git a/deploy/tempus.service b/deploy/tempus.service new file mode 100644 index 0000000..68a290c --- /dev/null +++ b/deploy/tempus.service @@ -0,0 +1,15 @@ +[Unit] +Description=Tempus (suivi du temps) +After=network.target + +[Service] +Type=simple +WorkingDirectory=@DEPLOY_DIR@ +Environment=TEMPUS_DB=@DEPLOY_DIR@/tempus.db +Environment=TEMPUS_ADDR=@ADDR@ +ExecStart=@DEPLOY_DIR@/tempus +Restart=on-failure +RestartSec=3 + +[Install] +WantedBy=default.target diff --git a/deploy/vh_tempus.conf b/deploy/vh_tempus.conf new file mode 100644 index 0000000..4312154 --- /dev/null +++ b/deploy/vh_tempus.conf @@ -0,0 +1,8 @@ + + ServerName @HOST@ + ProxyPreserveHost On + ProxyPass / http://@ADDR@/ + ProxyPassReverse / http://@ADDR@/ + ErrorLog /var/log/apache2/error.@HOST@.log + CustomLog /var/log/apache2/access.@HOST@.log combined + diff --git a/src/main.rs b/src/main.rs index 818fc32..4b25ef1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,7 +20,15 @@ async fn main() -> anyhow::Result<()> { .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)) + let app = routes::app(pool); + #[cfg(feature = "livereload")] + let app = app.layer( + // Les fragments htmx ne doivent pas recevoir le script injecté. + tower_livereload::LiveReloadLayer::new().request_predicate( + |req: &axum::http::Request| !req.headers().contains_key("hx-request"), + ), + ); + axum::serve(listener, app) .with_graceful_shutdown(async { let _ = tokio::signal::ctrl_c().await; }) diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 98bdcc0..41a5c60 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -56,11 +56,18 @@ pub fn app(pool: SqlitePool) -> Router { .with_state(pool) } +// En livereload, le CSS/JS doit être relu à chaque rechargement. +const CACHE_CONTROL: &str = if cfg!(feature = "livereload") { + "no-cache" +} else { + "public, max-age=3600" +}; + async fn asset(content_type: &'static str, body: &'static str) -> impl IntoResponse { ( [ (header::CONTENT_TYPE, content_type), - (header::CACHE_CONTROL, "public, max-age=3600"), + (header::CACHE_CONTROL, CACHE_CONTROL), ], body, ) diff --git a/src/routes/pages.rs b/src/routes/pages.rs index 78fd6ca..0564fa9 100644 --- a/src/routes/pages.rs +++ b/src/routes/pages.rs @@ -212,7 +212,7 @@ struct DashboardTpl { groups: Vec, today_entries: Vec, today_total: String, - recent_entries: Vec, + recent_days: Vec, } #[derive(Template)] @@ -232,7 +232,36 @@ struct TodayTpl { #[derive(Template)] #[template(path = "_recent.html")] struct RecentTpl { - recent_entries: Vec, + recent_days: Vec, +} + +/// Entries started on the same local day, with their total. +struct DayGroup { + day: String, + total: String, + entries: Vec, +} + +/// Groups a list sorted by start time into consecutive days. +fn group_by_day(list: Vec) -> Vec { + let mut days: Vec<(NaiveDate, i64, Vec)> = Vec::new(); + for e in list { + let date = clock::local_date(&e.started_at); + match days.last_mut() { + Some((d, secs, entries)) if *d == date => { + *secs += e.seconds; + entries.push(e); + } + _ => days.push((date, e.seconds, vec![e])), + } + } + days.into_iter() + .map(|(date, secs, entries)| DayGroup { + day: clock::fmt_day(date), + total: clock::hhmm(secs), + entries, + }) + .collect() } /// How many entries the dashboard lists under "Dernières entrées". @@ -266,8 +295,10 @@ async fn today_state(pool: &SqlitePool) -> PageResult { } async fn recent_state(pool: &SqlitePool) -> PageResult { - let recent_entries = entries::recent(pool, RECENT_LIMIT, clock::now()).await?; - Ok(RecentTpl { recent_entries }) + let recent = entries::recent(pool, RECENT_LIMIT, clock::now()).await?; + Ok(RecentTpl { + recent_days: group_by_day(recent), + }) } async fn dashboard(State(pool): State) -> PageResult { @@ -276,14 +307,14 @@ async fn dashboard(State(pool): State) -> PageResult { today_entries, today_total, } = today_state(&pool).await?; - let RecentTpl { recent_entries } = recent_state(&pool).await?; + let RecentTpl { recent_days } = recent_state(&pool).await?; render(DashboardTpl { nav: "dashboard", running, groups, today_entries, today_total, - recent_entries, + recent_days, }) } @@ -499,7 +530,7 @@ struct EntriesTpl { clients: Vec, filter_groups: Vec, groups: Vec, - entries: Vec, + days: Vec, total: String, default_start: String, default_end: String, @@ -552,7 +583,7 @@ async fn entries_page( 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, + days: group_by_day(list), total, default_start: format!("{today}T09:00"), default_end: format!("{today}T10:00"), diff --git a/static/app.css b/static/app.css index 5131af8..518b728 100644 --- a/static/app.css +++ b/static/app.css @@ -87,6 +87,14 @@ label { display: flex; align-items: center; gap: .35rem; 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; } +.btn.icon { display: inline-flex; align-items: center; justify-content: center; padding: .3rem; line-height: 0; } +.btn.icon svg { display: block; } +.btn-group { display: inline-flex; } +.btn-group > .btn { border-radius: 0; } +.btn-group > .btn + .btn { margin-left: -1px; } +.btn-group > .btn:first-child { border-radius: 8px 0 0 8px; } +.btn-group > .btn:last-child { border-radius: 0 8px 8px 0; } +.btn-group > .btn:hover { position: relative; z-index: 1; } .htmx-request .btn, .btn.htmx-request { opacity: .6; } .badge { font-size: .75rem; padding: .1rem .5rem; border-radius: 999px; background: var(--bg); color: var(--muted); } @@ -111,6 +119,8 @@ tr:last-child td { border-bottom: 0; } .time { white-space: nowrap; font-variant-numeric: tabular-nums; color: var(--muted); } .client { color: var(--muted); } tr.running { background: var(--running); } +tr.day-head th { color: var(--text); font-weight: 600; font-size: .9rem; padding-top: 1.1rem; } +tbody:first-of-type tr.day-head th { padding-top: .6rem; } tr.editing td { background: var(--bg); } tr.editing input, tr.editing select { width: 100%; } td.actions { text-align: right; white-space: nowrap; } diff --git a/templates/_entry_days.html b/templates/_entry_days.html new file mode 100644 index 0000000..cfd5711 --- /dev/null +++ b/templates/_entry_days.html @@ -0,0 +1,6 @@ +{% for d in days %} + + {{ d.day }}{{ d.total }} + {% for e in d.entries %}{% include "_entry_row.html" %}{% endfor %} + +{% endfor %} diff --git a/templates/_entry_duplicate.html b/templates/_entry_duplicate.html index 1b239f6..01ac63e 100644 --- a/templates/_entry_duplicate.html +++ b/templates/_entry_duplicate.html @@ -1,5 +1,5 @@ - +
diff --git a/templates/_entry_edit.html b/templates/_entry_edit.html index 7a5e5bb..261faff 100644 --- a/templates/_entry_edit.html +++ b/templates/_entry_edit.html @@ -1,5 +1,5 @@ - +
{% if e.running() %} diff --git a/templates/_entry_row.html b/templates/_entry_row.html index c7748af..c580190 100644 --- a/templates/_entry_row.html +++ b/templates/_entry_row.html @@ -1,5 +1,4 @@ - {{ e.day() }} {{ e.start_time() }} – {{ e.end_time() }} {% if e.overlaps %}⚠{% endif %} @@ -8,8 +7,10 @@ {{ e.note }} {{ e.duration() }} - - - +
+ + + +
diff --git a/templates/_recent.html b/templates/_recent.html index 6d446d2..f3ebe5c 100644 --- a/templates/_recent.html +++ b/templates/_recent.html @@ -3,24 +3,13 @@

Dernières entrées

Tout voir
- {% if recent_entries.is_empty() %} + {% if recent_days.is_empty() %}

Aucune entrée pour l'instant.

{% else %}
- - {% for e in recent_entries %} - - - - - - - {% endfor %} - + + {% let days = recent_days %}{% include "_entry_days.html" %}
{{ e.day() }}{{ e.start_time() }} – {{ e.end_time() }} - {{ e.client_name }} / {{ e.project_name }} - {% if !e.note.is_empty() %}
{{ e.note }}
{% endif %} -
{{ e.duration() }}
HoraireProjetNoteDurée
{% endif %} diff --git a/templates/_today.html b/templates/_today.html index 287872e..bac889d 100644 --- a/templates/_today.html +++ b/templates/_today.html @@ -6,19 +6,13 @@ {% if today_entries.is_empty() %}

Rien de saisi pour l'instant.

{% else %} - - - {% for e in today_entries %} - - - - - - {% endfor %} - -
{{ e.start_time() }} – {{ e.end_time() }} - {{ e.client_name }} / {{ e.project_name }} - {% if !e.note.is_empty() %}
{{ e.note }}
{% endif %} -
{{ e.duration() }}
+
+ + + + {% for e in today_entries %}{% include "_entry_row.html" %}{% endfor %} + +
HoraireProjetNoteDurée
+
{% endif %} diff --git a/templates/entries.html b/templates/entries.html index da90dcf..0c6a6ad 100644 --- a/templates/entries.html +++ b/templates/entries.html @@ -16,7 +16,7 @@ {% endif %} -
+

Entrées

{{ total }} @@ -40,15 +40,13 @@ - {% if entries.is_empty() %} + {% if days.is_empty() %}

Aucune entrée sur cette période.

{% else %}
- - - {% for e in entries %}{% include "_entry_row.html" %}{% endfor %} - + + {% include "_entry_days.html" %}
JourHoraireProjetNoteDurée
HoraireProjetNoteDurée
{% endif %} diff --git a/tests/api.rs b/tests/api.rs index 36fe729..68e504a 100644 --- a/tests/api.rs +++ b/tests/api.rs @@ -467,7 +467,7 @@ async fn dashboard_lists_20_most_recent_entries() { let (status, html) = get_html(&app, "/ui/dernieres-entrees").await; assert_eq!(status, StatusCode::OK); - assert_eq!(html.matches("