Cotton code
261 lines · 10.1 KB · RustRaw
//! Read-only monthly occurrences of one stored expected Money row.use crate::mcp::{    handlers::common::{text, Valid},    protocol::ToolFailure,};use cotton_core::rules::money::{    dates::{month_index, month_label},    recurrence::next_occurrence,    row::MoneyRepeat,};use serde_json::{Map, Value};type Data = Map<String, Value>;pub(crate) struct Window {    pub from: Option<String>,    pub to: String,}impl Window {    pub fn narrow(&self, mut query: crate::mcp::read_db::Query) -> crate::mcp::read_db::Query {        use crate::mcp::read_db::Filter;        if let Some(from) = &self.from {            query = query.filter(Filter::ComposedBound(                "(occurred_on >= ? OR (status = 'expected' AND repeat = 'monthly'))".into(),                vec![from.clone().into()],            ));        }        query            .filter(Filter::Lte("occurred_on".into(), self.to.clone().into()))            .filter(super::transactions::unsettled())    }    pub fn new(from: Option<&str>, to: &str) -> Valid<Self> {        if !cotton_core::records::is_date(to)            || from.is_some_and(|from| !cotton_core::records::is_date(from) || from > to)        {            return Err(ToolFailure::new(                "A Money window needs ordered calendar dates in YYYY-MM-DD.",            ));        }        Ok(Self {            from: from.map(str::to_string),            to: to.into(),        })    }}/// An occurrence names its stored source and its zero-based month index. The/// first keeps the stored id; later ids resolve to that same row on a write.pub(crate) fn identity(id: &str) -> Option<(&str, u32)> {    let (stored, index) = id.rsplit_once("@money:")?;    if !crate::mcp::handlers::common::is_uuid(stored) {        return None;    }    let index: u32 = index.parse().ok()?;    (index > 0 && index.to_string() == id.rsplit_once("@money:")?.1).then_some((stored, index))}/// Resolve only this read identity. The normal UUID path remains with its/// caller; an encoded occurrence must really name a live monthly expectation.pub(crate) fn resolve(    read: &crate::mcp::read_db::ReadDb<'_>,    id: &str,) -> Valid<Option<(String, Data)>> {    let Some((stored, index)) = identity(id) else {        return Ok(None);    };    let row = read        .by_id("cotton_money_transactions", stored)        .map_err(|error| ToolFailure::new(error.to_string()))?        .filter(|row| row.get("trashed_at").is_none_or(Value::is_null))        .ok_or_else(|| ToolFailure::new("This Money occurrence no longer has a stored row."))?;    Ok(Some((stored.into(), at(&row, index)?)))}fn advance(day: &str, index: u32, on: u8) -> Valid<String> {    if index == 0 {        return Ok(day.into());    }    let month = month_index(day).map_err(|error| ToolFailure::new(error.to_string()))?;    let previous = format!("{}-01", month_label(month + i64::from(index) - 1));    next_occurrence(&previous, MoneyRepeat::Monthly { day: on })        .map_err(|error| ToolFailure::new(error.to_string()))?        .ok_or_else(|| ToolFailure::new("A monthly Money row needs a repeat day from 1 to 31."))}/// The stored row at one month index. No row, receipt or computed index is/// written; dates follow the same monthly calculator settlement uses.pub(crate) fn at(row: &Data, index: u32) -> Valid<Data> {    let mut occurrence = row.clone();    let id = text(row, "id")        .ok_or_else(|| ToolFailure::new("A Money occurrence needs its stored row id."))?;    let monthly = text(row, "status").as_deref() == Some("expected")        && text(row, "repeat").as_deref() == Some("monthly");    if monthly {        let occurred = text(row, "occurred_on").unwrap_or_default();        let period = text(row, "for_period").unwrap_or_default();        if !cotton_core::records::is_date(&occurred)            || !cotton_core::records::is_date(&format!("{period}-01"))        {            return Err(ToolFailure::new(                "A monthly Money row needs a valid occurrence date and month.",            ));        }        if row            .get("repeat_day")            .and_then(Value::as_u64)            .is_none_or(|day| !(1..=31).contains(&day))        {            return Err(ToolFailure::new(                "A monthly Money row needs a repeat day from 1 to 31.",            ));        }    }    if index > 0 {        if !monthly {            return Err(ToolFailure::new(                "Only a monthly expected Money row has later occurrences.",            ));        }        let repeat_day = row            .get("repeat_day")            .and_then(Value::as_u64)            .filter(|day| (1..=31).contains(day))            .ok_or_else(|| {                ToolFailure::new("A monthly Money row needs a repeat day from 1 to 31.")            })? as u8;        let occurred = text(row, "occurred_on")            .ok_or_else(|| ToolFailure::new("A Money row needs its occurrence date."))?;        occurrence.insert(            "occurred_on".into(),            Value::from(advance(&occurred, index, repeat_day)?),        );        if let Some(due) = text(row, "due_date") {            let due_day = due                .get(8..10)                .and_then(|day| day.parse::<u8>().ok())                .ok_or_else(|| ToolFailure::new("A monthly Money row has an invalid due date."))?;            occurrence.insert(                "due_date".into(),                Value::from(advance(&due, index, due_day)?),            );        }        let period = text(row, "for_period")            .ok_or_else(|| ToolFailure::new("A Money row needs its month."))?;        let period = month_index(&format!("{period}-01"))            .map_err(|error| ToolFailure::new(error.to_string()))?;        occurrence.insert(            "for_period".into(),            Value::from(month_label(period + i64::from(index))),        );        occurrence.insert("id".into(), Value::from(format!("{id}@money:{index}")));    }    occurrence.insert("stored_id".into(), Value::from(id));    occurrence.insert("occurrence_index".into(), Value::from(index));    Ok(occurrence)}/// Expand physical input rows only, retaining occurrences inside the inclusive/// read window. An old monthly source is retained even when its stored date/// precedes the window; the occurrence index remains relative to that source.pub(crate) fn expand(rows: Vec<Data>, window: &Window) -> Valid<Vec<Data>> {    let mut out = Vec::new();    for row in rows {        let occurred = text(&row, "occurred_on")            .ok_or_else(|| ToolFailure::new("A Money row needs its occurrence date."))?;        let monthly = text(&row, "status").as_deref() == Some("expected")            && text(&row, "repeat").as_deref() == Some("monthly");        let mut index = if monthly {            match &window.from {                Some(from) => (month_index(from)                    .map_err(|error| ToolFailure::new(error.to_string()))?                    - month_index(&occurred)                        .map_err(|error| ToolFailure::new(error.to_string()))?)                .max(0) as u32,                None => 0,            }        } else {            0        };        let last_index = if monthly {            Some(                month_index(&window.to).map_err(|error| ToolFailure::new(error.to_string()))?                    - month_index(&occurred)                        .map_err(|error| ToolFailure::new(error.to_string()))?,            )        } else {            None        };        loop {            if last_index.is_some_and(|last| i64::from(index) > last) {                break;            }            let occurrence = at(&row, index)?;            let date = text(&occurrence, "occurred_on")                .expect("an occurrence has its stored or calculated date");            if date > window.to {                break;            }            if window.from.as_ref().is_none_or(|from| date >= *from) {                out.push(occurrence);            }            if !monthly {                break;            }            index = index.checked_add(1).ok_or_else(|| {                ToolFailure::new("The Money window exceeds the supported calendar.")            })?;        }    }    Ok(out)}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    fn monthly() -> Data {        json!({"id":"11111111-1111-4111-8111-111111111111", "status":"expected", "repeat":"monthly", "repeat_day":31,            "occurred_on":"2026-01-31", "due_date":"2026-01-31", "for_period":"2026-02"}).as_object().unwrap().clone()    }    /// RULE: A clipped February occurrence retains the month's standing day    /// and period offset, so the March runway does not drift to the 28th.    #[test]    fn clipped_months_keep_the_rule_and_period_offset() {        let source = monthly();        let window = Window::new(Some("2026-02-01"), "2026-03-31").unwrap();        let rows = expand(vec![source.clone()], &window).unwrap();        assert_eq!(            rows.iter()                .map(|row| text(row, "occurred_on").unwrap())                .collect::<Vec<_>>(),            ["2026-02-28", "2026-03-31"]        );        assert_eq!(rows[0]["due_date"], "2026-02-28");        assert_eq!(rows[1]["due_date"], "2026-03-31");        assert_eq!(rows[0]["for_period"], "2026-03");        assert_eq!(rows[1]["for_period"], "2026-04");        assert_eq!(rows[0]["occurrence_index"], 1);        assert_eq!(rows[1]["occurrence_index"], 2);        assert_eq!(source, monthly());    }    /// RULE: A virtual identity cannot turn an actual or nonmonthly row into    /// a monthly expectation, and invalid dates never become guessed dates.    #[test]    fn an_occurrence_needs_a_real_monthly_rule_and_supported_dates() {        let mut source = monthly();        assert!(at(&source, u32::MAX).is_err());        source.insert("status".into(), json!("actual"));        assert!(at(&source, 1).is_err());        source.insert("status".into(), json!("expected"));        source.insert("repeat_day".into(), json!(0));        assert!(at(&source, 0).is_err());        assert!(Window::new(Some("2026-02-30"), "2026-03-31").is_err());        assert!(Window::new(Some("2026-04-01"), "2026-03-31").is_err());    }}