Skip to main content

server/
timezone.rs

1//! The per-user `timezone` config: the zone a user's report dates are read in.
2
3use chrono::{DateTime, NaiveDate, Utc};
4pub use chrono_tz::Tz;
5
6use crate::config::{ConfigError, ConfigOption, config_on};
7
8/// The config key holding an IANA zone name; unset means UTC.
9pub const KEY: &str = "timezone";
10
11/// The zone named `name`, or the reason it is unknown.
12///
13/// # Errors
14/// A message naming the unknown zone.
15pub fn parse_zone(name: &str) -> Result<Tz, String> {
16    name.parse::<Tz>()
17        .map_err(|_| format!("unknown timezone '{name}', expected an IANA name like Asia/Tokyo"))
18}
19
20/// Whether `field` is the timezone key, as the config table folds case.
21#[must_use]
22pub fn is_key(field: &str) -> bool {
23    field.trim().eq_ignore_ascii_case(KEY)
24}
25
26/// The user's zone on `conn`; UTC when unset.
27///
28/// # Errors
29/// [`ConfigError::Sqlx`] on a database error; [`ConfigError::InvalidTimezone`]
30/// when the stored value is not a zone, naming it and the way to fix it.
31pub async fn zone_on(conn: &mut sqlx::PgConnection) -> Result<Tz, ConfigError> {
32    match config_on(conn, KEY).await {
33        Ok(Some(ConfigOption::String(name))) => {
34            parse_zone(&name).map_err(|_| stored_invalid(&name))
35        }
36        Ok(Some(ConfigOption::Blob(_))) => Err(stored_invalid("<binary>")),
37        Ok(None) | Err(ConfigError::NoConfig(_)) => Ok(Tz::UTC),
38        Err(err) => Err(err),
39    }
40}
41
42fn stored_invalid(name: &str) -> ConfigError {
43    ConfigError::InvalidTimezone(format!(
44        "the stored timezone '{name}' is not an IANA zone name; fix it with (set-config \"{KEY}\" \"Asia/Tokyo\")"
45    ))
46}
47
48/// The calendar day `now` falls on in `zone`.
49#[must_use]
50pub fn local_day(now: DateTime<Utc>, zone: Tz) -> NaiveDate {
51    now.with_timezone(&zone).date_naive()
52}
53
54/// `at` as `YYYY-MM-DD HH:MM` on the clock of `zone`.
55#[must_use]
56pub fn display(at: DateTime<Utc>, zone: Tz) -> String {
57    at.with_timezone(&zone).format("%Y-%m-%d %H:%M").to_string()
58}
59
60#[cfg(test)]
61#[path = "timezone_tests.rs"]
62mod tests;