//! A card's time fan and its When write (`shell.opened {step: "time"}`, `cards.when`), //! on the moment contract of [`crate::transforms::moment_split`]: a date //! column holds one instant, local midnight is a day with no time, and a //! write keeps the half it was not given — a new day keeps the hour, a new //! hour keeps the day. A column holding days ([`holds_days`]: a money row's //! date, a goal's target) is the exception: its When is a day alone, with //! no time fan, and it writes the bare day ([`written_day`]). use crate::constants::VersionRecordKind; use crate::definitions::TableDefinition; use crate::records::is_date; use crate::rules::history::fields::{history_kind, HistoryFieldForm}; use crate::rules::shell_lines::{self, LineRow}; use crate::transforms::moment_split::{self, MomentSplit, MomentSplitError}; use serde::Serialize; use serde_json::Value; /// What a date column holds, read in `zone`: its day and time, or nothing. /// A bare `YYYY-MM-DD` reads as that day with no time. pub fn held(value: Option<&Value>, zone: &str) -> Result, MomentSplitError> { match value.and_then(Value::as_str).filter(|text| !text.is_empty()) { None => Ok(None), Some(day) if is_date(day) => Ok(Some(MomentSplit { date: day.to_string(), time: None })), Some(at) => moment_split::split_moment(at, zone).map(Some), } } /// One card of the time fan. `time` is "HH:MM", absent on No time and on /// Pick a time (`key` "none" and "pick"). #[derive(Debug, Clone, PartialEq, Serialize)] pub struct TimeChoice { pub key: String, pub label: String, #[serde(skip_serializing_if = "Option::is_none")] pub time: Option, pub chosen: bool, } /// No time, the fan's hours, Pick a time — the record's own time chosen, /// and set among the hours in its place when it is none of them. pub fn time_choices(held: Option<&MomentSplit>, rows: &[LineRow]) -> Vec { let own = held.and_then(|moment| moment.time.clone()); let lines = shell_lines::resolved("editing", rows); let mut times: Vec = lines.as_ref().and_then(|set| set.pointer("/when/times")) .and_then(Value::as_object).into_iter().flat_map(|times| times.keys().cloned()).collect(); times.sort(); if let Some(own) = own.as_ref().filter(|own| !times.contains(own)) { times.push(own.clone()); times.sort(); } let said = |line: &str| shell_lines::resolve("editing", line, rows, &[]).unwrap_or_default(); let mut choices = vec![TimeChoice { key: "none".into(), label: said("when.no_time"), time: None, chosen: own.is_none() }]; choices.extend(times.into_iter().map(|time| TimeChoice { key: time.clone(), label: shell_lines::resolve("editing", &format!("when.times.{time}"), rows, &[]) .unwrap_or_else(|| time.strip_prefix('0').unwrap_or(&time).to_string()), chosen: own.as_ref() == Some(&time), time: Some(time), })); choices.push(TimeChoice { key: "pick".into(), label: said("when.pick_time"), time: None, chosen: false }); choices } /// The instant a When writes over `current` (the column's stored value), /// or `None` to clear it. Each half is absent (kept), null (a null date /// clears the column; a null time leaves the day with no time) or given; /// an hour given to a record with no day falls on `today` (`YYYY-MM-DD`). pub fn written( current: Option<&MomentSplit>, date: Option>, time: Option>, zone: &str, today: &str, ) -> Result, MomentSplitError> { let date = match (date, current, &time) { (Some(None), ..) => return Ok(None), (Some(Some(day)), ..) => day, (None, Some(current), _) => current.date.as_str(), (None, None, Some(Some(_))) => today, (None, None, _) => return Ok(None), }; let time = match time { None => current.and_then(|current| current.time.clone()), Some(time) => time.map(str::to_string), }; let next = MomentSplit { date: date.to_string(), time }; moment_split::join_moment(&next, zone).map(Some) } /// Whether `column` of `definition` holds a calendar day (`YYYY-MM-DD`), /// never an instant: its kind declares it a day (`history::fields`), and the /// kind's engine refuses a moment there (a money row's `occurred_on`). /// A yearly date (a person's birthday) is a day too: it comes round each /// year on its day, and local midnight as an instant is the day before east /// of UTC (India: "2026-11-07T18:30:00.000Z" for the 8th). pub fn holds_days(definition: &TableDefinition, column: &str) -> bool { let held = definition.column(column); let yearly = held.is_some_and(|held| held.yearly == Some(true)); // A made table's plain date takes a day and never an instant // (`records::check_value_in`): a trip's `starts` (13 Nov 2026, walked: // its When wrote an instant there and was refused). let plain = held.is_some_and(|held| { held.column_type == crate::definitions::ColumnType::Date && !definition.has_engine() && !matches!(held.format, Some(crate::definitions::ColumnFormat::Ago | crate::definitions::ColumnFormat::CalendarDatetime | crate::definitions::ColumnFormat::Countdown)) }); yearly || plain || VersionRecordKind::parse(&definition.id).is_some_and(|kind| { history_kind(kind).fields.iter().any(|field| field.column == column && field.form == Some(HistoryFieldForm::Day)) }) } /// Why a When on a column holding days is refused. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum DayWhenError { #[error("cotton: this card's date is a day, it takes no time")] TakesNoTime, #[error(transparent)] Day(#[from] MomentSplitError), } /// The day a When writes on a column that holds days: the day given, bare, /// else the day it holds; `None` clears it. A time given is refused — the /// column keeps none — and no time (null) is what it holds already. pub fn written_day(current: Option<&MomentSplit>, date: Option>, time: Option>) -> Result, DayWhenError> { if matches!(time, Some(Some(_))) { return Err(DayWhenError::TakesNoTime); } match date { Some(None) => Ok(None), Some(Some(day)) if moment_split::is_calendar_day(day) => Ok(Some(day.to_string())), Some(Some(day)) => Err(MomentSplitError::NotACalendarDay(day.to_string()).into()), None => Ok(current.map(|current| current.date.clone())), } } #[cfg(test)] #[path = "card_when_tests.rs"] mod tests;