//! Cotton Days' four views (`days.show`, CONTRACT.md section 11) and search //! (`days.find`, section 12), over this device's own copy. Each answers rows //! of the one shape (section 1) with their day beside them. use std::collections::{HashMap, HashSet}; use cotton_core::cotton_rules::days::{ layout::{self, Item, Kind, Place, Whose}, rhythm::{fold, holds_all, rhythm}, words::{fill, Words}, }; use cotton_core::cotton_rules::js::parse_date_ms; use cotton_core::cotton_rules::zoned_clock::{civil_from_days, day_key, local_day}; use rusqlite::types::Value as SqlValue; use serde_json::{json, Value}; use cotton_tools::mcp::dispatch::Ctx; use super::{ bad, done_place, due_place, event_items, live_copies, ms_of, open_place, reading, rows, said, sql, text, todos_of, ws, Reading, Todo, }; use crate::methods::MethodError; /// The most rows one page of Done answers. const MOST_DONE: i64 = 500; /// How far ahead a repeating event's next occurrence is looked for. const LOOK_AHEAD: i64 = 400; /// "Sun 25 Oct" this year, "25 Oct 2025" another; "Sometime" for no day. fn day_words(day: Option, today: i64, words: &Words) -> String { let Some(day) = day else { return words.no_day.clone() }; let (year, month, date) = civil_from_days(day); let (this_year, ..) = civil_from_days(today); let month = &words.months_short[(month - 1) as usize]; if year == this_year { let weekday = &words.weekdays_short[cotton_core::cotton_rules::days::weekday_monday_first(day)]; fill(&words.this_year_day, &[("weekday", weekday), ("day", &date.to_string()), ("month", month)]) } else { fill(&words.other_year_day, &[("day", &date.to_string()), ("month", month), ("year", &year.to_string())]) } } /// One item's row on `day` (its first, for one many days long), as Days /// draws it there. fn row_on(item: &Item, day: i64, at: &Reading, words: &Words) -> Result, MethodError> { let by_day = layout::rows_by_day(std::slice::from_ref(item), day, day, at.today, &at.zone, words).map_err(sql)?; Ok(by_day.get(&day).and_then(|rows| rows.first()).map(|row| serde_json::to_value(row).unwrap_or(Value::Null))) } /// A to-do as an item on `place`. fn todo_item(todo: &Todo, place: Place, order: i64) -> Item { Item { key: format!("todo:{}", todo.id), kind: Kind::Todo, whose: Whose::Yours, words: todo.title.clone(), mark: todo.mark.clone(), done: todo.status == "done", place, opens: json!({ "sheet": "todo", "id": todo.id }), order, } } /// A to-do's row on its day, or with no day (Sometime), its day beside it. fn todo_row(todo: &Todo, place: Option, order: i64, at: &Reading, words: &Words) -> Result, MethodError> { let day = match &place { Some(Place::Todo { day, .. }) => Some(*day), _ => None, }; let drawn = place.unwrap_or(Place::Todo { day: at.today, minute: None, from: None }); let Some(mut row) = row_on(&todo_item(todo, drawn, order), day.unwrap_or(at.today), at, words)? else { return Ok(None) }; row["day"] = day.map_or(Value::Null, |day| Value::from(day_key(day))); row["dayWords"] = Value::from(day_words(day, at.today, words)); if todo.status == "dropped" { row["dropped"] = Value::Bool(true); } Ok(Some(row)) } /// Where a to-do stands in a list of days: its kept day while kept, else /// where it belongs (`Some(None)`: Sometime; `None`: on no list). fn standing(todo: &Todo, at: &Reading) -> Result>, MethodError> { if let Some(kept) = at.keep.get(&todo.id) { let Some(kept) = kept else { return Ok(Some(None)) }; let place = [open_place(todo, at)?, done_place(todo, at)?] .into_iter() .flatten() .find(|place| matches!(place, Place::Todo { day, .. } if day == kept)) .unwrap_or(Place::Todo { day: *kept, minute: None, from: None }); return Ok(Some(Some(place))); } Ok(match todo.status.as_str() { "done" => done_place(todo, at)?.map(Some), "open" => Some(open_place(todo, at)?), // A dropped one stands on the day it was due, or on none. "dropped" => Some(own_day(todo, at)?), _ => None, }) } /// A to-do on the day it is due (late or not), at its time. fn own_day(todo: &Todo, at: &Reading) -> Result, MethodError> { let Some(due) = todo.at.as_deref() else { return Ok(None) }; Ok(due_place(due, at)?.map(|(day, minute)| Place::Todo { day, minute, from: None })) } // ── days.show ─────────────────────────────────────────────────────────────── /// `days.show { timezone, today, view, keep?, after?, limit? }`. pub(super) fn show(ctx: &mut Ctx<'_>, request: &Value) -> Result { let at = reading(ctx, request)?; let words = said(request); let view = text(request, "view").ok_or_else(|| bad("`view` is late, repeating, dropped or done"))?; let (title, empty, rows, next) = match view { "late" => (&words.late, &words.nothing_late, late(ctx, &at, words)?, None), "repeating" => (&words.repeating, &words.nothing_repeats, repeating(ctx, &at, words)?, None), "dropped" => (&words.dropped, &words.nothing_dropped, dropped(ctx, &at, words)?, None), "done" => { let limit = request.get("limit").and_then(Value::as_i64).unwrap_or(100).clamp(1, MOST_DONE); let (rows, next) = done(ctx, &at, words, text(request, "after"), limit)?; (&words.done, &words.nothing_done, rows, next) } other => return Err(bad(format!("`view` is late, repeating, dropped or done, not {other}"))), }; Ok(json!({ "view": view, "title": title, "rows": rows, "empty": empty, "next": next })) } /// Every open to-do from before today (a repeating one's live copy once), /// oldest first, on the day it was due; a kept one stays. fn late(ctx: &Ctx<'_>, at: &Reading, words: &Words) -> Result, MethodError> { let found = todos_of(ctx, "AND status IN ('open', 'done') AND due_at IS NOT NULL", &[])?; let shown = live_copies(&found, &at.keep); let mut out: Vec<((i64, i64, usize), Value)> = Vec::new(); for (order, todo) in found.iter().enumerate() { if !shown.contains(&todo.id) || (todo.status != "open" && !at.keep.contains_key(&todo.id)) { continue; } let Some(place @ Place::Todo { day, minute, .. }) = own_day(todo, at)? else { continue }; if day >= at.today { continue; } if let Some(row) = todo_row(todo, Some(place), order as i64, at, words)? { out.push(((day, minute.unwrap_or(-1), order), row)); } } out.sort_by_key(|(key, _)| *key); Ok(out.into_iter().map(|(_, row)| row).collect()) } /// Each repeating item once: to-dos by their series (its live copy's day), /// and repeating events (their next occurrence from today). fn repeating(ctx: &Ctx<'_>, at: &Reading, words: &Words) -> Result, MethodError> { let mut out: Vec<((i64, String), Value)> = Vec::new(); let trashed = if super::holds(ctx, "cotton_todo_recurrences", "trashed_at")? { "AND trashed_at IS NULL" } else { "" }; let series = rows( ctx, &format!("SELECT id, rrule, dtstart FROM cotton_todo_recurrences WHERE workspace_id = ? AND (paused IS NULL OR paused = 0) {trashed}"), &[ws(ctx)], )?; let found = todos_of(ctx, "AND status IN ('open', 'done') AND recurrence_id IS NOT NULL", &[])?; let shown = live_copies(&found, &at.keep); for template in &series { let id = template.text("id").unwrap_or_default(); let live = found.iter().enumerate().find(|(_, todo)| todo.series.as_deref() == Some(id) && shown.contains(&todo.id) && (todo.status == "open" || at.keep.contains_key(&todo.id))); let Some((order, todo)) = live else { continue }; let place = own_day(todo, at)?; let first = template.text("dtstart").and_then(parse_date_ms).map(|ms| local_day(ms, &at.db_zone)).transpose().map_err(sql)?.unwrap_or(at.today); let Some(mut row) = todo_row(todo, place.clone(), order as i64, at, words)? else { continue }; row["rhythm"] = Value::from(rhythm(template.text("rrule").unwrap_or_default(), first, words)); let day = match place { Some(Place::Todo { day, .. }) => day, _ => i64::MAX, }; out.push(((day, todo.title.to_lowercase()), row)); } // Repeating events: each series once, at its next occurrence. let masters = rows( ctx, "SELECT id, rrule, starts_at FROM cotton_events WHERE rrule IS NOT NULL AND series_id IS NULL AND trashed_at IS NULL AND (my_response IS NULL OR my_response != 'declined')", &[], )?; if !masters.is_empty() { let ahead = event_items(ctx, at, at.today, at.today + LOOK_AHEAD)?; let mut next: HashMap = HashMap::new(); for item in &ahead { let Some(id) = item.opens.get("id").and_then(Value::as_str) else { continue }; next.entry(id.to_string()).or_insert(item); } for master in &masters { let id = master.text("id").unwrap_or_default(); let Some(item) = next.get(id) else { continue }; let Place::Event { starts, .. } = item.place else { continue }; let day = local_day(starts, &at.zone).map_err(sql)?.max(at.today); let Some(mut row) = row_on(item, day, at, words)? else { continue }; let first = master.text("starts_at").and_then(parse_date_ms).map(|ms| local_day(ms, &at.zone)).transpose().map_err(sql)?.unwrap_or(day); row["rhythm"] = Value::from(rhythm(master.text("rrule").unwrap_or_default(), first, words)); row["day"] = Value::from(day_key(day)); row["dayWords"] = Value::from(day_words(Some(day), at.today, words)); out.push(((day, item.words.to_lowercase()), row)); } } out.sort_by(|a, b| a.0.cmp(&b.0)); Ok(out.into_iter().map(|(_, row)| row).collect()) } /// To-dos the person dropped, newest first. A copy let go by Skip (its /// series still going) is not one; a stopped series is listed once. fn dropped(ctx: &Ctx<'_>, at: &Reading, words: &Words) -> Result, MethodError> { let stopped: HashSet = rows(ctx, "SELECT id FROM cotton_todo_recurrences WHERE workspace_id = ? AND paused = 1", &[ws(ctx)])? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); let found = todos_of(ctx, "AND status IN ('dropped', 'open', 'done')", &[])?; let changed: HashMap = rows(ctx, "SELECT id, updated_at FROM cotton_todos WHERE workspace_id = ? AND status = 'dropped' AND trashed_at IS NULL", &[ws(ctx)])? .iter() .filter_map(|row| Some((row.text("id")?.to_string(), row.text("updated_at").unwrap_or_default().to_string()))) .collect(); let mut seen: HashSet<&str> = HashSet::new(); let mut out: Vec<(String, Value)> = Vec::new(); let mut newest_first: Vec<(usize, &Todo)> = found.iter().enumerate().filter(|(_, todo)| todo.status == "dropped" || at.keep.contains_key(&todo.id)).collect(); newest_first.sort_by(|a, b| changed.get(&b.1.id).cmp(&changed.get(&a.1.id)).then_with(|| b.1.id.cmp(&a.1.id))); for (order, todo) in newest_first { if todo.status == "dropped" { if let Some(series) = todo.series.as_deref() { if !stopped.contains(series) || !seen.insert(series) { continue; } } } else if !at.keep.contains_key(&todo.id) { continue; } if let Some(row) = todo_row(todo, own_day(todo, at)?, order as i64, at, words)? { out.push((changed.get(&todo.id).cloned().unwrap_or_default(), row)); } } Ok(out.into_iter().map(|(_, row)| row).collect()) } /// Done to-dos, newest first, a page at a time: `after` is the cursor the /// page before answered (`|`). fn done(ctx: &Ctx<'_>, at: &Reading, words: &Words, after: Option<&str>, limit: i64) -> Result<(Vec, Option), MethodError> { let (when, id) = after.and_then(|cursor| cursor.split_once('|')).map_or(("9999".to_string(), String::new()), |(w, i)| (w.to_string(), i.to_string())); let ids: Vec = rows( ctx, &format!( "SELECT id FROM cotton_todos WHERE workspace_id = ?1 AND trashed_at IS NULL AND status = 'done' AND completed_at IS NOT NULL AND (completed_at < ?2 OR (completed_at = ?2 AND id < ?3)) ORDER BY completed_at DESC, id DESC LIMIT {}", limit + 1 ), &[ws(ctx), SqlValue::Text(when), SqlValue::Text(id)], )? .iter() .filter_map(|row| row.text("id").map(str::to_string)) .collect(); let mut by_id: HashMap = HashMap::new(); for chunk in ids.chunks(400) { let marks = (0..chunk.len()).map(|n| format!("?{}", n + 3)).collect::>().join(", "); let asked: Vec = chunk.iter().map(|id| SqlValue::Text(id.clone())).collect(); let found = todos_of(ctx, &format!("AND id IN ({marks})"), &asked)?; by_id.extend(found.into_iter().map(|todo| (todo.id.clone(), todo))); } let page: Vec = ids.iter().filter_map(|id| by_id.remove(id)).collect(); let more = page.len() as i64 > limit; let page: Vec = page.into_iter().take(limit as usize).collect(); let next = if more { page.last().map(|todo| format!("{}|{}", todo.completed_at.clone().unwrap_or_default(), todo.id)) } else { None }; // Ticked back to open here: kept on the day it stood on, at the top of // that day's done rows. let kept: Vec = if at.keep.is_empty() { Vec::new() } else { todos_of(ctx, "AND status = 'open'", &[])?.into_iter().filter(|todo| matches!(at.keep.get(&todo.id), Some(Some(_)))).collect() }; let mut out = Vec::new(); let mut placed: HashSet = HashSet::new(); for (order, todo) in page.iter().enumerate() { let Some(Place::Todo { day, .. }) = done_place(todo, at)? else { continue }; let here: Vec<&Todo> = kept.iter().filter(|k| at.keep.get(&k.id) == Some(&Some(day)) && !placed.contains(&k.id)).collect(); for back in here { placed.insert(back.id.clone()); if let Some(row) = todo_row(back, Some(Place::Todo { day, minute: None, from: None }), order as i64, at, words)? { out.push(row); } } if let Some(row) = todo_row(todo, Some(Place::Todo { day, minute: None, from: None }), order as i64, at, words)? { out.push(row); } } Ok((out, next)) } // ── days.find ─────────────────────────────────────────────────────────────── /// One result, with the order it is listed in and where a tap lands. struct Found { day: Option, /// The minute in its day, for the order inside one day. minute: i64, row: Value, } /// `days.find { words, timezone, today, keep?, limit? }` (CONTRACT.md /// section 12): everything Days keeps whose title or note holds every /// typed word, Coming (today on, soonest first, then Sometime) and Before /// (newest first). pub(super) fn find(ctx: &mut Ctx<'_>, request: &Value) -> Result { let at = reading(ctx, request)?; let words = said(request); let typed = request.get("words").and_then(Value::as_str).unwrap_or_default().trim().to_string(); let asked: Vec = fold(&typed).split_whitespace().map(str::to_string).collect(); if asked.is_empty() { return Ok(json!({ "coming": [], "before": [], "empty": null })); } let limit = request.get("limit").and_then(Value::as_i64).unwrap_or(100).clamp(1, 500) as usize; let mut found: Vec = Vec::new(); find_todos(ctx, &at, words, &asked, &mut found)?; find_events(ctx, &at, words, &asked, &mut found)?; find_birthdays(ctx, &at, words, &asked, &mut found)?; let (mut coming, mut before): (Vec, Vec) = found.into_iter().partition(|one| match one.day { Some(day) => day >= at.today, None => one.row.get("dropped").is_none(), }); coming.sort_by_key(|one| (one.day.unwrap_or(i64::MAX), one.minute)); before.sort_by_key(|one| (std::cmp::Reverse(one.day.unwrap_or(i64::MIN)), std::cmp::Reverse(one.minute))); let empty = (coming.is_empty() && before.is_empty()).then(|| fill(&words.nothing_found, &[("words", &typed)])); let take = |list: Vec| list.into_iter().take(limit).map(|one| one.row).collect::>(); Ok(json!({ "coming": take(coming), "before": take(before), "empty": empty })) } /// Where a tap on a result lands. fn lands(day: Option, dropped: bool) -> Value { match (dropped, day) { (true, _) => json!({ "place": "show", "view": "dropped" }), (false, Some(day)) => json!({ "place": "days", "day": day_key(day) }), (false, None) => json!({ "place": "sometime" }), } } fn find_todos(ctx: &Ctx<'_>, at: &Reading, words: &Words, asked: &[String], out: &mut Vec) -> Result<(), MethodError> { let notes: HashMap = rows(ctx, "SELECT id, notes FROM cotton_todos WHERE workspace_id = ? AND trashed_at IS NULL AND notes IS NOT NULL", &[ws(ctx)])? .iter() .filter_map(|row| Some((row.text("id")?.to_string(), row.text("notes")?.to_string()))) .collect(); let all = todos_of(ctx, "AND status IN ('open', 'done', 'dropped')", &[])?; let matching: Vec<(usize, &Todo)> = all .iter() .enumerate() .filter(|(_, todo)| { let within = match notes.get(&todo.id) { Some(note) => fold(&format!("{}\n{note}", todo.title)), None => fold(&todo.title), }; holds_all(&within, asked) }) .collect(); let open: Vec = matching.iter().filter(|(_, t)| t.status == "open").map(|(_, t)| clone_todo(t)).collect(); let shown = live_copies(&open, &at.keep); // A repeating series is its live copy and its latest done copy. let mut once: HashSet = HashSet::new(); let mut by_done: Vec<&(usize, &Todo)> = matching.iter().collect(); by_done.sort_by(|a, b| b.1.completed_at.cmp(&a.1.completed_at)); let mut skip: HashSet<&str> = HashSet::new(); for (_, todo) in &by_done { if let (Some(series), "done") = (todo.series.as_deref(), todo.status.as_str()) { if !at.keep.contains_key(&todo.id) && !once.insert(format!("done:{series}")) { skip.insert(todo.id.as_str()); } } if let (Some(series), "dropped") = (todo.series.as_deref(), todo.status.as_str()) { if !once.insert(format!("dropped:{series}")) { skip.insert(todo.id.as_str()); } } } for (order, todo) in matching { if skip.contains(todo.id.as_str()) || (todo.status == "open" && !at.keep.contains_key(&todo.id) && !shown.contains(&todo.id)) { continue; } let Some(place) = standing(todo, at)? else { continue }; let (day, minute) = match &place { Some(Place::Todo { day, minute, .. }) => (Some(*day), minute.unwrap_or(-1)), _ => (None, -1), }; let Some(mut row) = todo_row(todo, place, order as i64, at, words)? else { continue }; row["lands"] = lands(day, todo.status == "dropped"); out.push(Found { day, minute, row }); } Ok(()) } fn clone_todo(todo: &Todo) -> Todo { Todo { id: todo.id.clone(), title: todo.title.clone(), status: todo.status.clone(), at: todo.at.clone(), completed_at: todo.completed_at.clone(), series: todo.series.clone(), occurrence_at: todo.occurrence_at.clone(), mark: todo.mark.clone(), created_at: todo.created_at.clone(), } } fn find_events(ctx: &Ctx<'_>, at: &Reading, words: &Words, asked: &[String], out: &mut Vec) -> Result<(), MethodError> { let your_note = super::optional(ctx, "cotton_events", "your_note")?; let events = rows( ctx, &format!( "SELECT id, title, notes, {your_note}, starts_at, ends_at, rrule FROM cotton_events WHERE trashed_at IS NULL AND series_id IS NULL AND (my_response IS NULL OR my_response != 'declined')" ), &[], )?; let matching: Vec<&cotton_store::driver::Row> = events .iter() .filter(|row| { let within = fold(&[row.text("title"), row.text("notes"), row.text("your_note")].iter().flatten().copied().collect::>().join("\n")); holds_all(&within, asked) }) .collect(); for event in matching { let id = event.text("id").unwrap_or_default(); let Some(starts) = event.text("starts_at").and_then(parse_date_ms) else { continue }; let first = local_day(starts, &at.zone).map_err(sql)?; // A one-off event on its own day; a repeating one at its next // occurrence from today, or its last when all are past. let (from, to) = if event.text("rrule").is_none() { let last = ms_of(event.text("ends_at")).filter(|ends| *ends > starts).map_or(first, |ends| local_day(ends - 1, &at.zone).unwrap_or(first)); (first, last.max(first)) } else { (at.today.max(first), at.today.max(first) + LOOK_AHEAD) }; let mut items: Vec = event_items(ctx, at, from, to)?.into_iter().filter(|item| item.opens.get("id").and_then(Value::as_str) == Some(id)).collect(); if items.is_empty() && event.text("rrule").is_some() && first < at.today { // All past: its last occurrence, within a year and a little back. items = event_items(ctx, at, first.max(at.today - LOOK_AHEAD), at.today - 1)?.into_iter().filter(|item| item.opens.get("id").and_then(Value::as_str) == Some(id)).collect(); items.reverse(); } let Some(item) = items.into_iter().next() else { continue }; let Place::Event { starts, all_day, .. } = item.place else { continue }; let day = local_day(starts, &at.zone).map_err(sql)?; // An event that began before today and is still on is on today. let day = if event.text("rrule").is_none() && day < at.today && to >= at.today { at.today } else { day }; let Some(mut row) = row_on(&item, day, at, words)? else { continue }; let minute = if all_day { -1 } else { cotton_core::cotton_rules::zoned_clock::zoned_parts(starts, &at.zone).map(|p| p.hour * 60 + p.minute).unwrap_or(-1) }; row["day"] = Value::from(day_key(day)); row["dayWords"] = Value::from(day_words(Some(day), at.today, words)); row["lands"] = lands(Some(day), false); out.push(Found { day: Some(day), minute, row }); } Ok(()) } fn find_birthdays(ctx: &Ctx<'_>, at: &Reading, words: &Words, asked: &[String], out: &mut Vec) -> Result<(), MethodError> { // A birthday is its next one: the coming year's birthdays, matched by // the words their row says. for item in super::birthday_items(ctx, at.today, at.today + 365, words)? { if !holds_all(&fold(&item.words), asked) { continue; } let Place::Birthday { day } = item.place else { continue }; if out.iter().any(|one| one.row.get("key") == Some(&Value::from(item.key.clone()))) { continue; } let person = item.opens.get("person").cloned(); if out.iter().any(|one| one.row.get("opens").and_then(|o| o.get("person")) == person.as_ref() && person.is_some()) { continue; } let Some(mut row) = row_on(&item, day, at, words)? else { continue }; row["day"] = Value::from(day_key(day)); row["dayWords"] = Value::from(day_words(Some(day), at.today, words)); row["lands"] = lands(Some(day), false); out.push(Found { day: Some(day), minute: -1, row }); } Ok(()) }