Cotton code
261 lines · 9.8 KB · RustRaw
//! Direct money-row loading and transfer marks.use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{    fail, in_chunks, int, require_uuid, rows, text, update_row, Valid,};use crate::mcp::read_db::{Filter, Order, Query};use serde_json::{json, Map, Value};#[derive(Debug, Clone)]pub struct TransactionLite {    pub id: String,    pub stored_id: String,    pub occurrence_index: u32,    pub occurred_on: String,    pub description: String,    pub payee_text: Option<String>,    pub account_id: Option<String>,    pub amount_minor: Option<i64>,    pub amount_known: bool,    pub direction: String,    pub currency: String,    pub for_period: String,    pub status: String,    pub tag: Option<String>,    pub certainty: Option<String>,    pub repeat: String,    pub repeat_day: Option<i64>,    pub between_us: bool,    pub moves_money: bool,    pub due_date: Option<String>,    pub notes: Option<String>,    pub source: Option<String>,    pub counterparty_person_id: Option<String>,    pub settles_transaction_id: Option<String>,    pub transfer_of: Option<String>,}const COLUMNS: &[&str] = &[    "id",    "occurred_on",    "description",    "payee_text",    "account_id",    "amount_minor",    "amount_known",    "direction",    "currency",    "for_period",    "status",    "certainty",    "repeat",    "repeat_day",    "between_us",    "moves_money",    "tag",    "due_date",    "notes",    "source",    "counterparty_person_id",    "settles_transaction_id",    "transfer_of",];#[derive(Debug, Clone, Default)]pub struct LoadWindow {    pub from: Option<String>,    pub to: Option<String>,    pub limit: Option<i64>,    pub status: Option<String>,    pub account_id: Option<String>,    pub person_id: Option<String>,}fn optional_int(row: &Map<String, Value>, column: &str) -> Option<i64> {    row.get(column)        .filter(|v| !v.is_null())        .map(|_| int(row, column))}pub(crate) fn money(row: &Map<String, Value>) -> TransactionLite {    TransactionLite {        id: text(row, "id").unwrap_or_default(),        stored_id: text(row, "stored_id").or_else(|| text(row, "id")).unwrap_or_default(),        occurrence_index: row.get("occurrence_index").and_then(Value::as_u64).unwrap_or(0) as u32,        occurred_on: text(row, "occurred_on").unwrap_or_default(),        description: text(row, "description").unwrap_or_default(),        payee_text: text(row, "payee_text"),        account_id: text(row, "account_id"),        amount_minor: optional_int(row, "amount_minor"),        amount_known: row            .get("amount_known")            .and_then(Value::as_bool)            .unwrap_or(true),        direction: text(row, "direction").unwrap_or_default(),        currency: text(row, "currency").unwrap_or_default(),        for_period: text(row, "for_period").unwrap_or_default(),        status: text(row, "status").unwrap_or_default(),        certainty: text(row, "certainty"),        repeat: text(row, "repeat").unwrap_or_default(),        repeat_day: optional_int(row, "repeat_day"),        between_us: row            .get("between_us")            .and_then(Value::as_bool)            .unwrap_or(false),        moves_money: row            .get("moves_money")            .and_then(Value::as_bool)            .unwrap_or(true),        tag: text(row, "tag"),        due_date: text(row, "due_date"),        notes: text(row, "notes"),        source: text(row, "source"),        counterparty_person_id: text(row, "counterparty_person_id"),        settles_transaction_id: text(row, "settles_transaction_id"),        transfer_of: text(row, "transfer_of"),    }}pub fn load_transactions(    ctx: &Ctx<'_>,    ids: Option<&[String]>,    window: Option<&LoadWindow>,) -> Valid<Vec<TransactionLite>> {    let projection = if ids.is_none() {        window.and_then(|window| window.to.as_deref().map(|to| super::occurrences::Window::new(window.from.as_deref(), to))).transpose()?    } else { None };    let found = match ids {        Some(ids) => in_chunks(ids, |batch| {            rows(                ctx,                &Query::on("cotton_money_transactions")                    .columns(COLUMNS)                    .filter(Filter::IsNull("trashed_at".into()))                    .filter(Filter::In(                        "id".into(),                        batch                            .iter()                            .map(|id| rusqlite::types::Value::Text(id.clone()))                            .collect(),                    )),            )        })?,        None => {            let window = window.cloned().unwrap_or_default();            let mut query = Query::on("cotton_money_transactions")                .columns(COLUMNS)                .filter(Filter::IsNull("trashed_at".into()))                .order_by("occurred_on", Order::Desc);            if let Some(from) = window.from {                query = if projection.is_some() {                    query.filter(Filter::ComposedBound("(occurred_on >= ? OR (status = 'expected' AND repeat = 'monthly'))".into(), vec![from.into()]))                } else { query.filter(Filter::Gte("occurred_on".into(), from.into())) };            }            if projection.is_some() {                query = query.filter(unsettled());            }            if let Some(to) = window.to {                query = query.filter(Filter::Lte("occurred_on".into(), to.into()));            }            if let Some(status) = window.status {                query = query.eq("status", status);            }            if let Some(account_id) = window.account_id {                query = query.eq("account_id", account_id);            }            if let Some(person_id) = window.person_id {                query = query.eq("counterparty_person_id", person_id);            }            if let Some(limit) = window.limit.filter(|_| projection.is_none()) {                query = query.limit(limit);            }            rows(ctx, &query)?        }    };    let mut found = match projection {        Some(window) => super::occurrences::expand(found, &window)?,        None => found,    };    found.sort_by(|a,b| text(b, "occurred_on").cmp(&text(a, "occurred_on")).then_with(|| text(a, "id").cmp(&text(b, "id"))));    if let Some(limit) = window.and_then(|window| window.limit) { found.truncate(limit.max(0) as usize); }    Ok(found.iter().map(money).collect())}/// A settlement already accounts for its expectation. Only its one stored/// next row may supply future monthly occurrences; null links match nothing.pub(crate) fn unsettled() -> Filter {    Filter::InQuery {        column: "id".into(),        query: Box::new(Query::on("cotton_money_transactions")            .columns(&["settles_transaction_id"])            .eq("status", "actual".to_string())            .filter(Filter::IsNull("trashed_at".into()))),        negate: true,    }}/// A transfer remains two visible rows; each points at the other.pub fn mark_transfer(ctx: &mut Ctx<'_>, first: &str, second: &str) -> Valid<()> {    if first == second {        return fail("a row cannot be its own transfer");    }    let found = load_transactions(ctx, Some(&[first.to_string(), second.to_string()]), None)?;    let a = found.iter().find(|row| row.id == first).ok_or_else(|| {        crate::mcp::protocol::ToolFailure::new(format!("no money row with id {first}"))    })?;    let b = found.iter().find(|row| row.id == second).ok_or_else(|| {        crate::mcp::protocol::ToolFailure::new(format!("no money row with id {second}"))    })?;    if !a.moves_money || !b.moves_money {        return fail("a transfer needs two rows that move money");    }    if a.status != "actual" || b.status != "actual" || !a.amount_known || !b.amount_known {        return fail("a transfer needs two actual rows with known amounts");    }    if a.account_id.is_none() || b.account_id.is_none() || a.account_id == b.account_id {        return fail("a transfer needs two different accounts");    }    let loan_accounts = rows(        ctx,        &Query::on("cotton_money_accounts")            .columns(&["id"])            .eq("kind", "loan".to_owned())            .filter(Filter::In(                "id".into(),                [                    a.account_id.as_ref().unwrap(),                    b.account_id.as_ref().unwrap(),                ]                .into_iter()                .cloned()                .map(rusqlite::types::Value::Text)                .collect(),            )),    )?;    let is_loan = |id: &Option<String>| {        loan_accounts            .iter()            .any(|account| text(account, "id").as_ref() == id.as_ref())    };    // A loan's bank-style statement balance is owed: reducing it is the    // opposite economic movement to reducing cash, although both rows say out.    let one_loan = is_loan(&a.account_id) != is_loan(&b.account_id);    if a.currency != b.currency        || a.amount_minor != b.amount_minor        || (a.direction == b.direction) != one_loan    {        return fail("a transfer needs equal amounts and opposite movement in the same currency");    }    if a.transfer_of.is_some() || b.transfer_of.is_some() {        return fail("one of these rows is already marked as a transfer");    }    let mut a_patch = Map::new();    a_patch.insert("transfer_of".into(), Value::from(second));    update_row(ctx, "cotton_money_transactions", first, a_patch)?;    let mut b_patch = Map::new();    b_patch.insert("transfer_of".into(), Value::from(first));    update_row(ctx, "cotton_money_transactions", second, b_patch)}pub fn mark_transfer_tool(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let first = require_uuid(args, "firstId")?;    let second = require_uuid(args, "secondId")?;    mark_transfer(ctx, &first, &second)?;    ctx.commit()?;    Ok(json!({"firstId":first,"secondId":second}))}