740 lines · 28.2 KB · RustRaw
//! Direct readers and writers for the one Money row.use serde_json::{json, Map, Value};use crate::mcp::dispatch::{Ctx, ToolResult};use crate::mcp::handlers::common::{ insert_row, optional_string, require_string, require_uuid, rows, update_row, Valid,};use crate::mcp::handlers::money::accounts::account_answer;use crate::mcp::handlers::money::model::load_money_accounts;use crate::mcp::handlers::money::transactions::{load_transactions, LoadWindow, TransactionLite};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::Query;use cotton_core::constants::LineDirection;use cotton_core::rules::money::row::{ExpectedCertainty, MoneyRepeat, MoneyRow, MoneyRowStatus};use cotton_store::protocol::derived_id::derived_id;fn value_or_null(value: Option<String>) -> Value { value.map_or(Value::Null, Value::from)}fn masked(number: Option<String>) -> Value { let Some(number) = number else { return Value::Null; }; Value::from(cotton_core::records::account_number_ending(&number))}/// Accounts answer only the identifying ending, including old imports that/// accidentally kept a full number in `number_mask`.pub fn list_money_accounts(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let include_archived = args .get("includeArchived") .and_then(Value::as_bool) .unwrap_or(false); let accounts: Vec<_> = load_money_accounts(ctx)? .into_iter() .filter(|account| include_archived || account.archived_at.is_none()) .collect(); let facts = crate::mcp::handlers::money_views::engine_rows( ctx, "money_account", accounts .iter() .map(|account| { let mut row = Map::new(); row.insert("kind".into(), Value::from(account.kind.as_str())); row.insert("subtype".into(), Value::from(account.subtype.as_str())); row.insert( "number_mask".into(), value_or_null(account.number_mask.clone()), ); (account.id.clone(), row) }) .collect(), &Map::new(), ) .map_err(ToolFailure::new)?; let answer: Vec<Value> = accounts .into_iter() .zip(facts) .map(|(account, fact)| { let mut value = account_answer(&account); if let Some(object) = value.as_object_mut() { object.insert( "numberMask".into(), fact.get("number_mask") .cloned() .unwrap_or_else(|| masked(account.number_mask)), ); object.insert( "kind".into(), fact.get("kind") .cloned() .unwrap_or_else(|| Value::from(account.kind.as_str())), ); object.insert( "isPooled".into(), fact.get("is_pooled").cloned().unwrap_or(Value::Bool(false)), ); object.insert( "balanceMinor".into(), fact.get("balance_minor").cloned().unwrap_or(Value::Null), ); } value }) .collect(); Ok(json!({"accounts": answer}))}fn transaction_answer(row: &TransactionLite) -> Map<String, Value> { let mut out = Map::new(); out.insert("id".into(), Value::from(row.id.clone())); if row.status == "expected" && row.repeat == "monthly" { out.insert("storedId".into(), Value::from(row.stored_id.clone())); out.insert("occurrenceIndex".into(), Value::from(row.occurrence_index)); } out.insert("occurredOn".into(), Value::from(row.occurred_on.clone())); out.insert("description".into(), Value::from(row.description.clone())); out.insert("payeeText".into(), value_or_null(row.payee_text.clone())); out.insert("accountId".into(), value_or_null(row.account_id.clone())); out.insert( "amountMinor".into(), row.amount_minor.map_or(Value::Null, Value::from), ); out.insert("amountKnown".into(), Value::Bool(row.amount_known)); out.insert("direction".into(), Value::from(row.direction.clone())); out.insert("currency".into(), Value::from(row.currency.clone())); out.insert("forPeriod".into(), Value::from(row.for_period.clone())); out.insert("status".into(), Value::from(row.status.clone())); out.insert("certainty".into(), value_or_null(row.certainty.clone())); out.insert("repeat".into(), Value::from(row.repeat.clone())); out.insert( "repeatDay".into(), row.repeat_day.map_or(Value::Null, Value::from), ); out.insert("betweenUs".into(), Value::Bool(row.between_us)); out.insert("movesMoney".into(), Value::Bool(row.moves_money)); out.insert("tag".into(), value_or_null(row.tag.clone())); out.insert("dueDate".into(), value_or_null(row.due_date.clone())); out.insert("notes".into(), value_or_null(row.notes.clone())); out.insert("source".into(), value_or_null(row.source.clone())); out.insert( "personId".into(), value_or_null(row.counterparty_person_id.clone()), ); out.insert( "settlesTransactionId".into(), value_or_null(row.settles_transaction_id.clone()), ); out.insert("transferOf".into(), value_or_null(row.transfer_of.clone())); out}pub fn money_transaction_record(ctx: &Ctx<'_>, id: &str) -> Valid<Map<String, Value>> { if let Some((_, occurrence)) = crate::mcp::handlers::money::occurrences::resolve(&ctx.read, id)? { return Ok(transaction_answer(&crate::mcp::handlers::money::transactions::money(&occurrence))); } let found = load_transactions(ctx, Some(&[id.to_string()]), None)?; found .first() .map(transaction_answer) .ok_or_else(|| ToolFailure::new(format!("no transaction with id {id}")))}pub fn list_money_transactions(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let limit = args .get("limit") .and_then(Value::as_i64) .unwrap_or(100) .clamp(1, 1000); let window = LoadWindow { from: optional_string(args, "from"), to: optional_string(args, "to"), limit: Some(limit), status: optional_string(args, "status"), account_id: optional_string(args, "accountId"), person_id: optional_string(args, "personId"), }; let rows = load_transactions(ctx, None, Some(&window))?; Ok(json!({"transactions": rows.iter().map(transaction_answer).collect::<Vec<_>>() }))}fn status(value: &str) -> Valid<MoneyRowStatus> { match value { "actual" => Ok(MoneyRowStatus::Actual), "expected" => Ok(MoneyRowStatus::Expected), _ => Err(ToolFailure::new("status must be actual or expected")), }}fn certainty(value: Option<&str>) -> Valid<Option<ExpectedCertainty>> { match value { None => Ok(None), Some("fixed") => Ok(Some(ExpectedCertainty::Fixed)), Some("expected") => Ok(Some(ExpectedCertainty::Expected)), Some("estimate") => Ok(Some(ExpectedCertainty::Estimate)), Some(_) => Err(ToolFailure::new( "certainty must be fixed, expected or estimate", )), }}fn direction(value: &str) -> Valid<LineDirection> { match value { "in" => Ok(LineDirection::In), "out" => Ok(LineDirection::Out), _ => Err(ToolFailure::new("direction must be in or out")), }}fn bool_arg(args: &Map<String, Value>, key: &str, default: bool) -> bool { args.get(key).and_then(Value::as_bool).unwrap_or(default)}fn nullable_string(args: &Map<String, Value>, key: &str) -> Option<String> { args.get(key).and_then(Value::as_str).map(str::to_string)}fn money_row(id: String, values: &Map<String, Value>) -> Valid<MoneyRow> { for field in ["amountKnown", "movesMoney", "betweenUs"] { if values.get(field).is_some_and(|value| !value.is_boolean()) { return Err(ToolFailure::new(format!("{field} must be true or false"))); } } for field in ["status", "repeat", "currency", "forPeriod", "direction"] { if values.get(field).is_some_and(|value| !value.is_string()) { return Err(ToolFailure::new(format!("{field} must be text"))); } } for field in [ "accountId", "personId", "certainty", "tag", "dueDate", "notes", "payeeText", ] { if values .get(field) .is_some_and(|value| !value.is_null() && !value.is_string()) { return Err(ToolFailure::new(format!("{field} must be text or null"))); } } if values .get("amountMinor") .is_some_and(|value| !value.is_null() && value.as_i64().is_none()) { return Err(ToolFailure::new("amountMinor must be whole minor units")); } // An empty period is the column's none (`for_period TEXT NOT NULL // DEFAULT ''`): a row made without one (an import, a booked line) is // merged back on every update and must not be refused for it. if let Some(period) = values.get("forPeriod").and_then(Value::as_str).filter(|period| !period.is_empty()) { if period.len() != 7 || !cotton_core::records::is_date(&format!("{period}-01")) { return Err(ToolFailure::new( "forPeriod must be a calendar month in YYYY-MM", )); } } if let Some(currency) = values.get("currency").and_then(Value::as_str) { if currency.len() != 3 || !currency.bytes().all(|byte| byte.is_ascii_uppercase()) { return Err(ToolFailure::new( "currency must be a three-letter uppercase code", )); } } if let Some(day) = values.get("dueDate").and_then(Value::as_str) { if !cotton_core::records::is_date(day) { return Err(ToolFailure::new("dueDate must be a calendar date")); } } if values.get("betweenUs").and_then(Value::as_bool) == Some(true) && values .get("personId") .is_none_or(|value| value.as_str().is_none_or(str::is_empty)) { return Err(ToolFailure::new("betweenUs needs a personId")); } let status = status( require_string(values, "status") .unwrap_or_else(|| "actual".into()) .as_str(), )?; let repeat = match nullable_string(values, "repeat") .as_deref() .unwrap_or("none") { "none" => MoneyRepeat::None, "monthly" => { let day = values .get("repeatDay") .and_then(Value::as_u64) .ok_or_else(|| ToolFailure::new("repeatDay is required for a monthly repeat"))?; if day > u8::MAX as u64 { return Err(ToolFailure::new("repeatDay must be from 1 to 31")); } MoneyRepeat::Monthly { day: day as u8 } } _ => return Err(ToolFailure::new("repeat must be none or monthly")), }; let amount_known = bool_arg(values, "amountKnown", true); let amount_minor = values.get("amountMinor").and_then(Value::as_i64); let occurred_on = require_string(values, "occurredOn") .ok_or_else(|| ToolFailure::new("occurredOn is required"))?; if !cotton_core::records::is_date(&occurred_on) { return Err(ToolFailure::new("occurredOn must be a valid calendar day")); } let row = MoneyRow { id, occurred_on, account_id: nullable_string(values, "accountId"), amount_minor, amount_known, direction: direction( require_string(values, "direction") .ok_or_else(|| ToolFailure::new("direction is required"))? .as_str(), )?, moves_money: bool_arg(values, "movesMoney", true), status, certainty: certainty(nullable_string(values, "certainty").as_deref())?, repeat, }; row.validate() .map_err(|error| ToolFailure::new(error.to_string()))?; Ok(row)}fn row_patch(row: &MoneyRow, values: &Map<String, Value>) -> Map<String, Value> { let mut patch = Map::new(); patch.insert("occurred_on".into(), Value::from(row.occurred_on.clone())); patch.insert("account_id".into(), value_or_null(row.account_id.clone())); patch.insert( "amount_minor".into(), row.amount_minor.map_or(Value::Null, Value::from), ); patch.insert("amount_known".into(), Value::Bool(row.amount_known)); patch.insert( "direction".into(), Value::from(match row.direction { LineDirection::In => "in", LineDirection::Out => "out", }), ); patch.insert( "status".into(), Value::from(match row.status { MoneyRowStatus::Actual => "actual", MoneyRowStatus::Expected => "expected", }), ); patch.insert( "certainty".into(), value_or_null(row.certainty.map(|value| { match value { ExpectedCertainty::Fixed => "fixed", ExpectedCertainty::Expected => "expected", ExpectedCertainty::Estimate => "estimate", } .to_string() })), ); match row.repeat { MoneyRepeat::None => { patch.insert("repeat".into(), Value::from("none")); patch.insert("repeat_day".into(), Value::Null); } MoneyRepeat::Monthly { day } => { patch.insert("repeat".into(), Value::from("monthly")); patch.insert("repeat_day".into(), Value::from(day)); } } for (camel, snake) in [ ("description", "description"), ("payeeText", "payee_text"), ("currency", "currency"), ("forPeriod", "for_period"), ("tag", "tag"), ("personId", "counterparty_person_id"), ("dueDate", "due_date"), ("notes", "notes"), ] { if let Some(value) = values.get(camel) { patch.insert(snake.into(), value.clone()); } } for (camel, snake) in [("betweenUs", "between_us"), ("movesMoney", "moves_money")] { if let Some(value) = values.get(camel) { patch.insert(snake.into(), value.clone()); } } patch}fn booked(ctx: &Ctx<'_>, id: &str) -> Valid<bool> { Ok(!rows( ctx, &Query::on("cotton_money_evidence") .columns(&["id"]) .eq("transaction_id", id.to_string()) .eq("kind", "statement_line".to_string()) .limit(1), )? .is_empty())}fn validate_links(ctx: &Ctx<'_>, row: &MoneyRow, values: &Map<String, Value>) -> Valid<()> { if let Some(account_id) = row.account_id.as_deref() { let account = rows( ctx, &Query::on("cotton_money_accounts") .columns(&["id", "currency"]) .eq("id", account_id.to_string()) .limit(1), )?; let account = account .first() .ok_or_else(|| ToolFailure::new("accountId does not name an account"))?; if let Some(currency) = values.get("currency").and_then(Value::as_str) { if account.get("currency").and_then(Value::as_str) != Some(currency) { return Err(ToolFailure::new( "A money row must use its account's currency", )); } } } if let Some(person_id) = nullable_string(values, "personId") { if rows( ctx, &Query::on("cotton_people") .columns(&["id"]) .eq("id", person_id) .limit(1), )? .is_empty() { return Err(ToolFailure::new("personId does not name a person")); } } Ok(())}pub fn record_transaction(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let id = ctx.new_uuid(); let row = money_row(id.clone(), args)?; validate_links(ctx, &row, args)?; let mut patch = row_patch(&row, args); patch.insert( "description".into(), Value::from(require_string(args, "description").unwrap_or_default()), ); let currency = match ( nullable_string(args, "accountId"), require_string(args, "currency"), ) { (_, Some(currency)) => currency, (Some(account_id), None) => load_money_accounts(ctx)? .into_iter() .find(|account| account.id == account_id) .map(|account| account.currency) .ok_or_else(|| ToolFailure::new("accountId does not name an account"))?, (None, None) => { return Err(ToolFailure::new( "currency is required when accountId is empty", )) } }; patch.insert("currency".into(), Value::from(currency)); let period = require_string(args, "forPeriod").unwrap_or_else(|| row.occurred_on[..7].into()); if period.len() != 7 || !period.as_bytes().get(4).is_some_and(|byte| *byte == b'-') || !cotton_core::records::is_date(&format!("{period}-01")) { return Err(ToolFailure::new( "forPeriod must be a calendar month in YYYY-MM", )); } patch.insert("for_period".into(), Value::from(period)); patch.entry("between_us").or_insert(Value::Bool(false)); patch.entry("moves_money").or_insert(Value::Bool(true)); patch.insert("source".into(), Value::from("manual")); insert_row(ctx, "cotton_money_transactions", &id, patch)?; ctx.commit()?; Ok(Value::Object(money_transaction_record(ctx, &id)?))}pub fn update_transaction(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let id = require_uuid(args, "id")?; let existing = money_transaction_record(ctx, &id)?; let mut merged = existing.clone(); for (key, value) in args { if key != "id" { merged.insert(key.clone(), value.clone()); } } let changes = |keys: &[&str]| keys.iter().any(|key| merged.get(*key) != existing.get(*key)); if existing.get("transferOf").is_some_and(|value| !value.is_null()) && changes(&["accountId", "amountMinor", "amountKnown", "direction", "currency", "status", "movesMoney"]) { return Err(ToolFailure::new("A marked transfer keeps its two movements' account, amount, currency, direction and status.")); } if changes(&["status", "currency", "direction"]) { let settles = existing.get("settlesTransactionId").is_some_and(|value| !value.is_null()); let settled = !rows(ctx, &Query::on("cotton_money_transactions") .columns(&["id"]) .eq("settles_transaction_id", id.clone()) .eq("status", "actual".to_owned()) .filter(crate::mcp::read_db::Filter::IsNull("trashed_at".into())) .limit(1))?.is_empty(); if settles || settled { return Err(ToolFailure::new("Linked actual and expected rows keep their status, currency and direction.")); } } let row = money_row(id.clone(), &merged)?; validate_links(ctx, &row, &merged)?; if booked(ctx, &id)? && [ "occurredOn", "accountId", "amountMinor", "amountKnown", "direction", "currency", "status", "certainty", "movesMoney", ] .iter() .any(|key| { args.get(*key) .is_some_and(|value| existing.get(*key) != Some(value)) }) { return Err(ToolFailure::new( "A booked statement row keeps its date, account, amount, direction and currency.", )); } if existing.get("status").and_then(Value::as_str) == Some("expected") && row.status == MoneyRowStatus::Actual { let previous = load_transactions(ctx, Some(&[id.clone()]), None)?; if let Some(previous) = previous.first() { materialize_next_expected(ctx, previous)?; } } update_row( ctx, "cotton_money_transactions", &id, row_patch(&row, &merged), )?; ctx.commit()?; Ok(Value::Object(money_transaction_record(ctx, &id)?))}/// Booked evidence is permanent: removing the Money row would leave a/// statement line pretending it was never booked.pub fn delete_transaction(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let id = require_uuid(args, "id")?; if booked(ctx, &id)? { return Err(ToolFailure::new( "A booked statement row cannot be deleted.", )); } crate::mcp::handlers::bin::put_away(ctx, cotton_core::constants::BinKind::Transaction, &id)?; ctx.commit()?; Ok(json!({"id": id, "deleted": true}))}/// Settling preserves both facts: the expected row remains an expectation and/// the actual row points at it. Readers exclude an expected row named by an/// actual settlement, so it cannot be counted in Ahead twice.pub fn settle_expected(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult { let actual_id = require_uuid(args, "actualId")?; let asked = optional_string(args, "expectedId").unwrap_or_default(); let expected_id = match crate::mcp::handlers::money::occurrences::resolve(&ctx.read, &asked)? { Some((stored, _)) => stored, None => require_uuid(args, "expectedId")?, }; let found = load_transactions(ctx, Some(&[actual_id.clone(), expected_id.clone()]), None)?; let actual = found .iter() .find(|row| row.id == actual_id) .ok_or_else(|| ToolFailure::new("actualId does not name a Money row"))?; let expected = found .iter() .find(|row| row.id == expected_id) .ok_or_else(|| ToolFailure::new("expectedId does not name a Money row"))?; if actual.status != "actual" || expected.status != "expected" { return Err(ToolFailure::new( "settle_expected needs one actual row and one expected row", )); } if actual.currency != expected.currency || actual.direction != expected.direction { return Err(ToolFailure::new( "A settlement must have the expected currency and direction", )); } if let Some(settles) = actual.settles_transaction_id.as_deref() { if settles == expected_id { materialize_next_expected(ctx, expected)?; ctx.commit()?; return Ok(json!({"actualId": actual_id, "expectedId": expected_id})); } return Err(ToolFailure::new( "This actual row already settles another expected row.", )); } if !rows( ctx, &Query::on("cotton_money_transactions") .columns(&["id"]) .eq("settles_transaction_id", expected_id.clone()) .eq("status", "actual".to_owned()) .filter(crate::mcp::read_db::Filter::IsNull("trashed_at".into())) .limit(1), )? .is_empty() { return Err(ToolFailure::new("This expected row is already settled.")); } let mut patch = Map::new(); patch.insert( "settles_transaction_id".into(), Value::from(expected_id.clone()), ); update_row(ctx, "cotton_money_transactions", &actual_id, patch)?; materialize_next_expected(ctx, expected)?; ctx.commit()?; Ok(json!({"actualId": actual_id, "expectedId": expected_id}))}/// THE PHONE MAKES A SETTLED EXPECTATION'S NEXT MONTH once money rows are/// sealed (e2e rulings R3, 16 Nov 2026): the object cannot copy words it/// cannot read, so it makes none (apps/business/src/money.ts/// `settleExpected`), and the writer of record's pass makes it here, under/// the derived id the object used, so two phones make one row. While the/// object works money in the clear it makes them itself and this makes none.pub fn materialize_settled_expectations(ctx: &mut Ctx<'_>) -> Valid<usize> { if crate::money_run::object_works_the_run(ctx.read.driver()).map_err(|error| ToolFailure::new(error.to_string()))? { return Ok(0); } let settled: Vec<String> = rows( ctx, &Query::on("cotton_money_transactions") .columns(&["settles_transaction_id"]) .eq("status", "actual".to_owned()) .filter(crate::mcp::read_db::Filter::IsNull("trashed_at".into())) .filter(crate::mcp::read_db::Filter::NotNull("settles_transaction_id".into())), )? .iter() .filter_map(|row| row.get("settles_transaction_id").and_then(Value::as_str).map(str::to_owned)) .collect::<std::collections::BTreeSet<_>>() .into_iter() .collect(); if settled.is_empty() { return Ok(0); } let mut made = 0; for expected in load_transactions(ctx, Some(&settled), None)? { if expected.status != "expected" || expected.repeat != "monthly" { continue; } if materialize_next_expected(ctx, &expected)? { made += 1; } } Ok(made)}/// Materialise precisely one next monthly expectation. The derived id makes a/// repeated settlement or a retry on another device converge on the same row.fn materialize_next_expected(ctx: &mut Ctx<'_>, expected: &TransactionLite) -> Valid<bool> { let repeat = match expected.repeat.as_str() { "none" | "" => return Ok(false), "monthly" => { let day = expected .repeat_day .ok_or_else(|| ToolFailure::new("A monthly Money row is missing repeat_day."))?; if !(1..=31).contains(&day) { return Err(ToolFailure::new( "A monthly Money row has an invalid repeat_day.", )); } MoneyRepeat::Monthly { day: day as u8 } } _ => return Err(ToolFailure::new("A Money row has an unknown repeat rule.")), }; let Some(occurred_on) = cotton_core::rules::money::recurrence::next_occurrence(&expected.occurred_on, repeat) .map_err(|error| ToolFailure::new(error.to_string()))? else { return Ok(false); }; let id = derived_id("cotton_money_transactions", &[&expected.id, &occurred_on]); if ctx .read .by_id("cotton_money_transactions", &id) .map_err(|error| ToolFailure::new(error.to_string()))? .is_some() { return Ok(false); } let for_period = cotton_core::rules::money::dates::month_index(&format!("{}-01", expected.for_period)) .map(|month| cotton_core::rules::money::dates::month_label(month + 1)) .unwrap_or_else(|_| occurred_on[..7].to_string()); let due_date = expected .due_date .as_deref() .map(|day| { let day_number = day .get(8..10) .and_then(|day| day.parse::<u8>().ok()) .ok_or_else(|| ToolFailure::new("A monthly Money row has an invalid due date."))?; cotton_core::rules::money::recurrence::next_occurrence( day, MoneyRepeat::Monthly { day: day_number }, ) .map_err(|error| ToolFailure::new(error.to_string())) }) .transpose()? .flatten(); let mut patch = Map::new(); for (key, value) in [ ("occurred_on", Value::from(occurred_on.clone())), ("description", Value::from(expected.description.clone())), ("payee_text", value_or_null(expected.payee_text.clone())), ("account_id", value_or_null(expected.account_id.clone())), ( "amount_minor", expected.amount_minor.map_or(Value::Null, Value::from), ), ("amount_known", Value::Bool(expected.amount_known)), ("direction", Value::from(expected.direction.clone())), ("currency", Value::from(expected.currency.clone())), ("for_period", Value::from(for_period)), ("status", Value::from("expected")), ("certainty", value_or_null(expected.certainty.clone())), ("repeat", Value::from(expected.repeat.clone())), ( "repeat_day", expected.repeat_day.map_or(Value::Null, Value::from), ), ("between_us", Value::Bool(expected.between_us)), ("moves_money", Value::Bool(expected.moves_money)), ("tag", value_or_null(expected.tag.clone())), ("due_date", value_or_null(due_date)), ("notes", value_or_null(expected.notes.clone())), ("source", value_or_null(expected.source.clone())), ( "counterparty_person_id", value_or_null(expected.counterparty_person_id.clone()), ), ] { patch.insert(key.into(), value); } insert_row(ctx, "cotton_money_transactions", &id, patch)?; Ok(true)}