Cotton code
175 lines · 6.1 KB · RustRaw
//! Account rows shared by the money handlers.use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{fail, flag, rows, text, update_row, Valid};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Order, Query};use cotton_core::constants::{MoneyAccountKind, MoneyAccountSubtype};use serde_json::{Map, Value};pub const MONEY_ACCOUNT_COLUMNS: &[&str] = &[    "id",    "kind",    "subtype",    "name",    "counterparty_person_id",    "currency",    "institution",    "number_mask",    "is_default",    "is_pooled",    "archived_at",    "created_at",];#[derive(Debug, Clone)]pub struct MoneyAccount {    pub id: String,    pub kind: MoneyAccountKind,    pub subtype: MoneyAccountSubtype,    pub name: String,    pub person_id: Option<String>,    pub currency: String,    pub institution: Option<String>,    pub number_mask: Option<String>,    pub is_default: bool,    pub is_pooled: Option<bool>,    pub archived_at: Option<String>,}fn known<T>(value: Option<T>, raw: &str, column: &str) -> Valid<T> {    value.ok_or_else(|| ToolFailure::new(format!("{column} has an unknown value {raw}")))}pub fn to_money_account(row: &Map<String, Value>) -> Valid<MoneyAccount> {    let kind = text(row, "kind").unwrap_or_default();    let subtype = text(row, "subtype").unwrap_or_default();    Ok(MoneyAccount {        id: text(row, "id").unwrap_or_default(),        kind: known(MoneyAccountKind::parse(&kind), &kind, "money account kind")?,        subtype: known(            MoneyAccountSubtype::parse(&subtype),            &subtype,            "money account subtype",        )?,        name: text(row, "name").unwrap_or_default(),        person_id: text(row, "counterparty_person_id"),        currency: text(row, "currency").unwrap_or_default(),        institution: text(row, "institution"),        number_mask: text(row, "number_mask"),        is_default: flag(row, "is_default"),        is_pooled: row.get("is_pooled").and_then(Value::as_bool),        archived_at: text(row, "archived_at"),    })}pub fn load_money_accounts(ctx: &Ctx<'_>) -> Valid<Vec<MoneyAccount>> {    Ok(rows(        ctx,        &Query::on("cotton_money_accounts")            .columns(MONEY_ACCOUNT_COLUMNS)            .order_by("created_at", Order::Asc)            .order_by("id", Order::Asc),    )?    .iter()    .map(to_money_account)    .collect::<Valid<Vec<_>>>()?)}pub fn load_movement_accounts(ctx: &Ctx<'_>, _: &[Option<&str>]) -> Valid<Vec<MoneyAccount>> {    load_money_accounts(ctx)}pub fn takes_movements(subtype: &str, open: bool) -> bool {    open && matches!(        MoneyAccountSubtype::parse(subtype),        Some(            MoneyAccountSubtype::Bank                | MoneyAccountSubtype::Cash                | MoneyAccountSubtype::Wallet                | MoneyAccountSubtype::CreditCard                | MoneyAccountSubtype::Loan        )    )}pub fn can_be_usual(subtype: &str) -> bool {    matches!(        MoneyAccountSubtype::parse(subtype),        Some(MoneyAccountSubtype::Bank | MoneyAccountSubtype::Cash | MoneyAccountSubtype::Wallet)    )}pub enum Landing<'a> {    On(&'a MoneyAccount),    Ask(Vec<&'a MoneyAccount>),}pub fn landing<'a>(accounts: &'a [MoneyAccount], given: Option<&str>) -> Valid<Landing<'a>> {    let places: Vec<_> = accounts        .iter()        .filter(|a| takes_movements(a.subtype.as_str(), a.archived_at.is_none()))        .collect();    if let Some(a) = given.and_then(|id| places.iter().find(|a| a.id == id)) {        return Ok(Landing::On(a));    }    if let Some(a) = places.iter().find(|a| a.is_default) {        return Ok(Landing::On(a));    }    match places.as_slice() {        [] => fail("Add an account before recording money."),        [a] => Ok(Landing::On(a)),        _ => Ok(Landing::Ask(places)),    }}pub fn usual_refusal(a: &MoneyAccount) -> Option<String> {    (!can_be_usual(a.subtype.as_str()) || a.archived_at.is_some())        .then(|| format!("{} cannot be your usual account", a.name))}pub fn take_usual_off_others(ctx: &mut Ctx<'_>, accounts: &[MoneyAccount], keep: &str) -> Valid<()> {    for a in accounts.iter().filter(|a| a.is_default && a.id != keep) {        let mut p = Map::new();        p.insert("is_default".into(), Value::Bool(false));        update_row(ctx, "cotton_money_accounts", &a.id, p)?;    }    Ok(())}pub fn make_usual(ctx: &mut Ctx<'_>, accounts: &[MoneyAccount], id: &str) -> Valid<()> {    let a = accounts        .iter()        .find(|a| a.id == id)        .ok_or_else(|| ToolFailure::new("no account with that id"))?;    if let Some(e) = usual_refusal(a) {        return fail(e);    }    take_usual_off_others(ctx, accounts, id)?;    let mut p = Map::new();    p.insert("is_default".into(), Value::Bool(true));    update_row(ctx, "cotton_money_accounts", id, p)}pub fn clear_usual(ctx: &mut Ctx<'_>, accounts: &[MoneyAccount]) -> Valid<()> {    take_usual_off_others(ctx, accounts, "")}#[cfg(test)]mod tests {    use super::*;    use serde_json::json;    /// Every account kind the personal kit serves is accepted by the shared    /// reader and remains the same value after parsing.    #[test]    fn personal_kit_account_kinds_round_trip() {        let kit: Value = serde_json::from_str(include_str!(            "../../../../../cotton-core/kits/personal/tables/money_account.json"        ))        .expect("the personal money account definition");        let kinds = kit["columns"]            .as_array()            .and_then(|columns| columns.iter().find(|column| column["key"] == "kind"))            .and_then(|column| column["choices"].as_array())            .expect("the personal kit's account kinds");        for kind in kinds.iter().map(|kind| kind.as_str().expect("a string kind")) {            let row = json!({                "id": format!("synthetic-{kind}"),                "kind": kind,                "subtype": kind,                "name": "Synthetic account",                "currency": "EUR",                "is_default": false,            });            let account = to_money_account(row.as_object().expect("an account row")).expect(kind);            assert_eq!(account.kind.as_str(), kind);        }    }}