Cotton code
172 lines · 7.6 KB · RustRaw
//! A Records thread's two acts (architect brief, Records slips typed by kind,//! landing 3): never automatic, each the owner's tap on the thread's page.//!//! - **Record as a transaction** (a receipt or a statement): one transaction//!   in Money, pre-filled with the thread's amount, merchant and date, in the//!   account Money lands a movement in. Its currency is that account's, so a//!   thread in another currency is refused by name BEFORE anything is written//!   — a receipt in euros is never booked as rupees.//! - **Add to calendar** (a ticket or a booking): one all-day event on the day//!   the record is about, named by its merchant and reference.//!//! Each writes its record AND the link from it to the thread (`cotton_links`,//! new record → thread) in the same write, so the two are never apart: the//! thread then answers the record in place of the act (`transaction_id`,//! `event_id`) and the record answers the thread (`email_thread_id`). A thread//! already recorded answers the record it has — a second tap makes nothing.use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use super::record_fields::recorded_as;use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::money::model::{landing, load_movement_accounts, Landing};use crate::mcp::protocol::ToolFailure;/// What the acts read of a thread.struct Record {    kind: Option<String>,    amount_minor: Option<i64>,    currency: Option<String>,    merchant: Option<String>,    on: Option<String>,    reference: Option<String>,    subject: Option<String>,}impl Record {    /// What the new record is called: the merchant, else the subject.    fn name(&self) -> String {        self.merchant            .clone()            .or_else(|| self.subject.clone())            .filter(|name| !name.trim().is_empty())            .unwrap_or_else(|| "A record from mail".to_string())    }}fn read(ctx: &Ctx<'_>, thread: &str) -> Result<Record, ToolFailure> {    let row = ctx        .db()        .get(            "SELECT record_kind, amount_minor, currency, merchant, record_on, reference, subject \               FROM cotton_email_threads WHERE id = ?1 AND workspace_id = ?2",            &[SqlValue::Text(thread.to_string()), SqlValue::Text(ctx.workspace_id.to_string())],        )        .map_err(|error| ToolFailure::new(error.to_string()))?        .ok_or_else(|| ToolFailure::new("That thread is not in this database."))?;    let text = |key: &str| row.text(key).filter(|value| !value.is_empty()).map(str::to_string);    Ok(Record {        kind: text("record_kind"),        amount_minor: row.int("amount_minor"),        currency: text("currency"),        merchant: text("merchant"),        on: text("record_on"),        reference: text("reference"),        subject: text("subject"),    })}fn created(out: &Value) -> Result<String, ToolFailure> {    out.get("id")        .and_then(Value::as_str)        .map(str::to_string)        .ok_or_else(|| ToolFailure::new("the record was written but its id was not answered"))}/// The link from the new record to the thread.fn link(ctx: &mut Ctx<'_>, from_kind: &str, from_id: &str, thread: &str) -> Result<(), ToolFailure> {    let mut args = Map::new();    args.insert("fromKind".into(), Value::from(from_kind));    args.insert("fromId".into(), Value::from(from_id));    args.insert("toKind".into(), Value::from("email_thread"));    args.insert("toId".into(), Value::from(thread));    crate::mcp::handlers::owner::work::create_link(ctx, &args)?;    Ok(())}/// The account a thread's money lands in, in its own currency — or why it/// cannot be booked as it is.fn account_for(ctx: &Ctx<'_>, currency: Option<&str>) -> Result<String, ToolFailure> {    let accounts = load_movement_accounts(ctx, &[])?;    let wanted = |account: &&crate::mcp::handlers::money::model::MoneyAccount| {        currency.is_none_or(|currency| account.currency.eq_ignore_ascii_case(currency))    };    match landing(&accounts, None)? {        Landing::On(account) if wanted(&account) => Ok(account.id.clone()),        Landing::On(account) => Err(ToolFailure::new(format!(            "This record is in {}, and the account Money puts it in keeps {}. Record it in Money by hand.",            currency.unwrap_or_default(),            account.currency        ))),        Landing::Ask(places) => {            let fitting: Vec<_> = places.iter().filter(|account| wanted(account)).collect();            match fitting.as_slice() {                [only] => Ok(only.id.clone()),                _ => Err(ToolFailure::new(                    "Money has more than one account this could have been paid from. Record it in Money by hand.",                )),            }        }    }}/// Record as a transaction: `{transactionId, threadId}`, with `already: true`/// when the thread was recorded before.pub fn record_as_transaction(ctx: &mut Ctx<'_>, thread: &str) -> Result<Value, ToolFailure> {    if let Some(id) = recorded_as(ctx, thread, "transaction") {        return Ok(json!({ "transactionId": id, "threadId": thread, "already": true }));    }    let record = read(ctx, thread)?;    if !matches!(record.kind.as_deref(), Some("receipt" | "statement")) {        return Err(ToolFailure::new("Only a receipt or a statement is recorded as a transaction."));    }    let Some(amount) = record.amount_minor.filter(|amount| *amount > 0) else {        return Err(ToolFailure::new("This record names no amount it is sure of. Record it in Money by hand."));    };    let account = account_for(ctx, record.currency.as_deref())?;    let mut args = Map::new();    args.insert("direction".into(), Value::from("out"));    args.insert("status".into(), Value::from("actual"));    args.insert("amountMinor".into(), Value::from(amount));    args.insert("description".into(), Value::from(record.name()));    args.insert("accountId".into(), Value::from(account));    if let Some(on) = &record.on {        args.insert("occurredOn".into(), Value::from(on.clone()));    }    let out = crate::mcp::handlers::records_2::money::record_transaction(ctx, &args)?;    let id = created(&out)?;    if let Some(merchant) = &record.merchant {        let mut payee = Map::new();        payee.insert("payee_text".into(), Value::from(merchant.clone()));        crate::mcp::handlers::common::update_row(ctx, "cotton_money_transactions", &id, payee)?;    }    link(ctx, "transaction", &id, thread)?;    Ok(json!({ "transactionId": id, "threadId": thread }))}/// Add to calendar: `{eventId, threadId}`, with `already: true` when the/// thread was added before.pub fn add_to_calendar(ctx: &mut Ctx<'_>, thread: &str) -> Result<Value, ToolFailure> {    if let Some(id) = recorded_as(ctx, thread, "event") {        return Ok(json!({ "eventId": id, "threadId": thread, "already": true }));    }    let record = read(ctx, thread)?;    if !matches!(record.kind.as_deref(), Some("ticket" | "booking")) {        return Err(ToolFailure::new("Only a ticket or a booking is added to the calendar."));    }    let Some(on) = record.on.clone() else {        return Err(ToolFailure::new("This record names no day it is sure of. Add it to the calendar by hand."));    };    let title = match &record.reference {        Some(reference) => format!("{} · {reference}", record.name()),        None => record.name(),    };    let mut args = Map::new();    args.insert("title".into(), Value::from(title));    args.insert("startsAt".into(), Value::from(on));    let out = crate::mcp::handlers::records_1::events::create_event(ctx, &args)?;    let id = created(&out)?;    link(ctx, "event", &id, thread)?;    Ok(json!({ "eventId": id, "threadId": thread }))}