1
//! The per-user `timezone` config: the zone a user's report dates are read in.
2

            
3
use chrono::{DateTime, NaiveDate, Utc};
4
pub use chrono_tz::Tz;
5

            
6
use crate::config::{ConfigError, ConfigOption, config_on};
7

            
8
/// The config key holding an IANA zone name; unset means UTC.
9
pub 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.
15
10266
pub fn parse_zone(name: &str) -> Result<Tz, String> {
16
10266
    name.parse::<Tz>()
17
3
        .map_err(|_| format!("unknown timezone '{name}', expected an IANA name like Asia/Tokyo"))
18
10266
}
19

            
20
/// Whether `field` is the timezone key, as the config table folds case.
21
#[must_use]
22
7210
pub fn is_key(field: &str) -> bool {
23
7210
    field.trim().eq_ignore_ascii_case(KEY)
24
7210
}
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.
31
75424
pub async fn zone_on(conn: &mut sqlx::PgConnection) -> Result<Tz, ConfigError> {
32
75424
    match config_on(conn, KEY).await {
33
        Ok(Some(ConfigOption::String(name))) => {
34
7022
            parse_zone(&name).map_err(|_| stored_invalid(&name))
35
        }
36
        Ok(Some(ConfigOption::Blob(_))) => Err(stored_invalid("<binary>")),
37
68402
        Ok(None) | Err(ConfigError::NoConfig(_)) => Ok(Tz::UTC),
38
        Err(err) => Err(err),
39
    }
40
75424
}
41

            
42
1
fn stored_invalid(name: &str) -> ConfigError {
43
1
    ConfigError::InvalidTimezone(format!(
44
1
        "the stored timezone '{name}' is not an IANA zone name; fix it with (set-config \"{KEY}\" \"Asia/Tokyo\")"
45
1
    ))
46
1
}
47

            
48
/// The calendar day `now` falls on in `zone`.
49
#[must_use]
50
74703
pub fn local_day(now: DateTime<Utc>, zone: Tz) -> NaiveDate {
51
74703
    now.with_timezone(&zone).date_naive()
52
74703
}
53

            
54
/// `at` as `YYYY-MM-DD HH:MM` on the clock of `zone`.
55
#[must_use]
56
28625
pub fn display(at: DateTime<Utc>, zone: Tz) -> String {
57
28625
    at.with_timezone(&zone).format("%Y-%m-%d %H:%M").to_string()
58
28625
}
59

            
60
#[cfg(test)]
61
#[path = "timezone_tests.rs"]
62
mod tests;