first commit
This commit is contained in:
commit
dd6a740645
37 files changed
+5424
No files matched your search
+120
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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"))
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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
@@ -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),
|
||||
}
|
||||
}
|
||||
@@ -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?,
|
||||
)
|
||||
}
|
||||
@@ -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(¤t.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?,
|
||||
)
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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?,
|
||||
))
|
||||
}
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -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(¤t.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,
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user