Cotton code
268 lines · 9.3 KB · RustRaw
//! Monthly expected occurrences for a definition's runway window. Values stay//! in this read; settlement remains the sole writer of one next expectation.use super::{day_plan, FigureRows, FigureTotal, ListExtras, Page, Stored};use crate::mcp::{    dispatch::Ctx,    handlers::{        common::{text, today_in, workspace_timezone, Valid},        money::occurrences::{self, Window},    },    protocol::ToolFailure,    read_db::{Query, ReadDb},};use chrono::{Days, Months, NaiveDate};use cotton_core::{    definitions::{computed::Computed, SummaryOp, TableDefinition},    records::{self, Data, WhereClause},};use serde_json::Value;use std::collections::BTreeSet;pub(super) fn handles(definition: &TableDefinition) -> bool {    definition.source.as_ref().is_some_and(|source| {        source.table == "transaction"            && source                .where_                .as_ref()                .and_then(|conditions| conditions.get("status"))                .and_then(Value::as_str)                == Some("expected")    })}pub(super) fn varies_by_occurrence(definition: &TableDefinition, column: &str) -> bool {    matches!(column, "occurred_on" | "due_date" | "for_period")        || definition            .column(column)            .is_some_and(|column| column.computed.is_some())}/// The months a runway reads from its first day when the definition names no/// `horizon`.const HORIZON_MONTHS: u32 = 3;/// The window's end is the read's own `to`, else the definition's horizon in/// whole months from the first day; a saved definition never holds one under 1.pub(super) fn window(    definition: &TableDefinition,    today: &str,    from: Option<&str>,    to: Option<&str>,) -> Valid<Window> {    let months = match definition.horizon {        None => HORIZON_MONTHS,        Some(months) => u32::try_from(months)            .ok()            .filter(|months| *months >= 1)            .ok_or_else(|| ToolFailure::new("A Money runway's horizon is a whole number of months, at least 1."))?,    };    let from = from.unwrap_or(today);    let start = NaiveDate::parse_from_str(from, "%Y-%m-%d")        .map_err(|_| ToolFailure::new("A Money window needs a calendar start date."))?;    let end = match to {        Some(to) => to.to_string(),        None => start            .checked_add_months(Months::new(months))            .and_then(|day| day.checked_sub_days(Days::new(1)))            .ok_or_else(|| ToolFailure::new("The Money window exceeds the supported calendar."))?            .format("%Y-%m-%d")            .to_string(),    };    Window::new(Some(from), &end)}pub(super) fn window_for_list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    view: &day_plan::View,) -> Valid<Window> {    let zone = view.timezone.clone().unwrap_or(workspace_timezone(ctx)?);    let today = match &view.today {        Some(day) => day.clone(),        None => today_in(&zone, ctx.now.timestamp_millis())?,    };    window(definition, &today, view.from.as_deref(), view.to.as_deref())}/// The complete logical view is evaluated before a caller's search, project/// or where narrows its display. Narrowing a page cannot change a balance.pub(super) fn rows(    read: &ReadDb<'_>,    definition: &TableDefinition,    window: &Window,) -> Valid<Vec<Stored>> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    let physical = super::builtin::derivation_rows_through_window(        read.driver(),        read.workspace_id(),        definition,        window,    )?;    let input: Vec<Data> = physical.into_iter().map(|(_, data)| data).collect();    let viewed = super::viewed(definition)?;    let expanded: Vec<_> = occurrences::expand(input, window)?        .into_iter()        .filter(|data| viewed.iter().all(|clause| records::holds(data, clause, &zone)))        .filter_map(|data| Some((text(&data, "id")?, data)))        .collect();    let values = crate::derive::values_for_read_rows(read.driver(), definition, expanded)        .map_err(super::sql_err)?;    Ok(values        .into_iter()        .map(|(id, data)| Stored {            id,            created_at: text(&data, "created_at"),            updated_at: text(&data, "updated_at"),            deleted_at: None,            byline: None,            data,        })        .collect())}pub(super) fn list(    ctx: &Ctx<'_>,    definition: &TableDefinition,    selected: Query,    clauses: &[WhereClause],    members: Option<&[String]>,    offset: i64,    limit: i64,    view: &day_plan::View,) -> Valid<(Page, ListExtras)> {    let zone = crate::mcp::handlers::common::where_zone(ctx)?;    if view.section.is_some() {        return Err(ToolFailure::new(            "A Money runway is read through its date window, without a section.",        ));    }    let window = window_for_list(ctx, definition, view)?;    let allowed: BTreeSet<String> = ctx        .read        .select(&window.narrow(selected).columns(&["id"]))        .map_err(super::sql_err)?        .into_iter()        .filter_map(|data| text(&data, "id"))        .collect();    let mut rows = rows(&ctx.read, definition, &window)?;    rows.retain(|row| {        let stored = row            .data            .get("stored_id")            .and_then(Value::as_str)            .unwrap_or(&row.id);        allowed.contains(stored)            && clauses                .iter()                .all(|clause| records::holds(&row.data, clause, &zone))            && members.is_none_or(|members| {                members                    .iter()                    .any(|member| member == &row.id || member == stored)            })    });    let total = rows.len() as i64;    let mut page: Vec<_> = rows        .into_iter()        .skip(offset.max(0) as usize)        .take(limit.max(0) as usize + 1)        .collect();    let more = page.len() as i64 > limit;    page.truncate(limit.max(0) as usize);    // The remaining raw source fields were needed for recurrence and ordering,    // not for the record. Carry only declared columns and its read identity.    for row in &mut page {        row.data.retain(|key, _| {            definition.column(key).is_some()                || matches!(key.as_str(), "stored_id" | "occurrence_index")        });    }    Ok((        Page {            records: page,            more,            total,        },        ListExtras::default(),    ))}pub(super) fn figure(    read: &ReadDb<'_>,    definition: &TableDefinition,    clauses: &[WhereClause],    span: Option<(&str, &str)>,    op: SummaryOp,    column: Option<&str>,    today: NaiveDate,    resolved: &mut FigureRows,) -> Valid<FigureTotal> {    let zone = crate::mcp::handlers::common::read_where_zone(read)?;    if !resolved.contains_key(&definition.id) {        let window = window(definition, &today.format("%Y-%m-%d").to_string(), None, None)?;        resolved.insert(definition.id.clone(), rows(read, definition, &window)?);    }    let keeps = |row: &Stored| {        clauses.iter().all(|clause| records::holds(&row.data, clause, &zone))            && span.is_none_or(|(from, until)| {                let date = definition                    .date                    .as_deref()                    .and_then(|key| row.data.get(key))                    .and_then(Value::as_str)                    .unwrap_or_default();                date >= from && date < until            })    };    if matches!(op, SummaryOp::Min | SummaryOp::Max) {        if let Some(column) = column.and_then(|key| definition.column(key)).filter(|column| {            matches!(column.computed, Some(Computed::Running(_)))        }) {            // A running balance that becomes unknown cannot yield a valid            // extreme from the earlier numeric prefix. Inspect all eligible            // occurrences, including null balances, before aggregating.            let mut currencies = BTreeSet::new();            let mut unknown = false;            for row in resolved[&definition.id].iter().filter(|row| keeps(row)) {                unknown |= row.data.get(&column.key).and_then(Value::as_i64).is_none();                let currency = match column.currency.as_deref() {                    Some(key) if definition.column(key).is_some() => {                        row.data.get(key).and_then(Value::as_str)                    }                    code => code,                };                currencies.extend(currency.filter(|code| !code.trim().is_empty()));            }            if currencies.len() > 1 {                return Ok(FigureTotal { mixed: true, ..FigureTotal::default() });            }            if unknown {                return Ok(FigureTotal::default());            }        }    }    if op != SummaryOp::Count {        return super::builtin::rows_total(            read,            definition,            clauses,            span,            op,            column.ok_or_else(|| ToolFailure::new("A Money figure needs its column."))?,            resolved,        );    }    let rows = &resolved[&definition.id];    let count = rows        .iter()        .filter(|row| keeps(row))        .filter(|row| {            column.is_none_or(|key| row.data.get(key).is_some_and(|value| !value.is_null()))        })        .count();    Ok(FigureTotal {        total: count as i64,        ..FigureTotal::default()    })}