//! 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::ValueasSqlValue;use serde_json::{json, Map, Value};usesuper::record_fields::recorded_as;usecrate::mcp::dispatch::Ctx;usecrate::mcp::handlers::money::model::{landing, load_movement_accounts, Landing};usecrate::mcp::protocol::ToolFailure;/// What the acts read of a thread.structRecord { kind: Option<String>, amount_minor: Option<i64>, currency: Option<String>, merchant: Option<String>, on: Option<String>, reference: Option<String>, subject: Option<String>,}implRecord {/// 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: &mutCtx<'_>, from_kind: &str, from_id: &str, thread: &str) -> Result<(), ToolFailure> {letmut 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.pubfn record_as_transaction(ctx: &mutCtx<'_>, thread: &str) -> Result<Value, ToolFailure> {ifletSome(id) = recorded_as(ctx, thread, "transaction") {returnOk(json!({ "transactionId": id, "threadId": thread, "already": true })); }let record = read(ctx, thread)?;if !matches!(record.kind.as_deref(), Some("receipt" | "statement")) {returnErr(ToolFailure::new("Only a receipt or a statement is recorded as a transaction.")); }letSome(amount) = record.amount_minor.filter(|amount| *amount > 0) else {returnErr(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())?;letmut 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));ifletSome(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)?;ifletSome(merchant) = &record.merchant {letmut 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.pubfn add_to_calendar(ctx: &mutCtx<'_>, thread: &str) -> Result<Value, ToolFailure> {ifletSome(id) = recorded_as(ctx, thread, "event") {returnOk(json!({ "eventId": id, "threadId": thread, "already": true })); }let record = read(ctx, thread)?;if !matches!(record.kind.as_deref(), Some("ticket" | "booking")) {returnErr(ToolFailure::new("Only a ticket or a booking is added to the calendar.")); }letSome(on) = record.on.clone() else {returnErr(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(), };letmut 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 }))}