//! The SQL a date column is read by when a list orders or narrows by its day //! of the year rather than the stored date: a `next` sort (the next time a //! yearly day comes round from the reader's day). It takes a date column's //! SQL value — a stored column, a user table's, or a built-in's computed //! date through its SQL twin — never a table or column name, so every //! yearly date (birthdays, anniversaries, renewals) orders the same way. //! The maths it mirrors is `cotton_core::transforms::zoned_clock::next_yearly_occurrence`. use super::day_plan; use crate::mcp::dispatch::Ctx; use crate::mcp::handlers::common::today_in; use crate::mcp::protocol::ToolFailure; /// "MM-DD" of a date value — "1992-08-17", "--08-17" or a day with its /// time — or NULL when blank. `value` is read once, so an expression that /// binds parameters binds them in place: the year-less form is given a /// year of zeros and the month-day is read at one place for both. pub(super) fn month_day(value: &str) -> String { format!("NULLIF(substr(replace('@' || {value}, '@--', '@0000-'), 7, 5), '')") } /// A date value falls in `month` (1–12), whatever its year. pub(super) fn in_month(value: &str, month: i64) -> String { format!("substr(replace('@' || {value}, '@--', '@0000-'), 7, 2) = '{month:02}'") } /// The ascending terms that order rows by the next occurrence of their /// yearly day from `today` (YYYY-MM-DD): the undated last, then the days /// still to come this year (today first), then those already past. A day /// clamped into a short month (29 February in a year without one) orders /// as its own month-day, beside the day it is kept on. pub(super) fn next_terms(mut value: impl FnMut() -> String, today: &str) -> [String; 3] { // `today` is a parsed day, so its five characters are digits and a dash. let from = &today[5..10]; let undated = month_day(&value()); let past = month_day(&value()); [format!("{undated} IS NULL"), format!("{past} < '{from}'"), month_day(&value())] } /// The reader's day a `next` sort counts from: `today` when the read says /// it, else the day in its `timezone`, else the UTC day. pub(super) fn reader_day(ctx: &Ctx<'_>, view: &day_plan::View) -> Result { if let Some(day) = &view.today { return chrono::NaiveDate::parse_from_str(day, "%Y-%m-%d") .map(|day| day.format("%Y-%m-%d").to_string()) .map_err(|_| ToolFailure::new(format!("today is a day, YYYY-MM-DD, not {day:?}"))); } match &view.timezone { Some(zone) => today_in(zone, ctx.now.timestamp_millis()), None => Ok(ctx.now.format("%Y-%m-%d").to_string()), } }