//! `restore_version` — put an earlier version of a record back.//!//! A record's history rows rebuild every version it had; this is the one//! write that takes the owner back to one of them. What it may write is not//! decided here: the kind's restore columns (`rules::history::fields`,//! `Restore::Columns`) and the row's own refusals//! (`rules::history::restorable::restore_block`) are the core's, enforced here.//!//! **A restore is an ordinary edit.** The values go through `update_row` like//! any other owner edit, so the restore itself leaves a version behind and can//! be taken back the same way, and it syncs like every other write.//!//! **A transaction's classification comes back through the money engine.** The//! category is the counter LINE's account, not a header column: the header's//! version snapshots its sides as they stood (`lines`), and putting the old one//! back is `apply_meaning` with the owner as the decider — the money tool's own//! act, never a raw write to a ledger line, so the entry still balances and the//! decider is the person who chose to go back.//!//! OWNER-SCOPE, for the reason every verb in this module is: going back over//! the person's own record is the person's act.use cotton_core::rules::history::trail::{record_trail, trail_tables, TRAIL_SQL};use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};use cotton_core::constants::VersionRecordKind;use cotton_core::rules::history::fields::history_kind;use cotton_core::rules::history::restorable::{restore_block, restore_patch};usecrate::mcp::dispatch::{Ctx, ToolResult};usecrate::mcp::handlers::common::{ require_string, row_by_id, update_row, Valid,};usecrate::mcp::protocol::ToolFailure;pubfn restore_version(ctx: &mutCtx<'_>, args: &Map<String, Value>) -> ToolResult {letSome(kind_word) = require_string(args, "kind") else {returnErr(ToolFailure::new("say which kind of record this is (kind)")); };letSome(kind) = VersionRecordKind::ALL .into_iter() .find(|candidate| candidate.as_str() == kind_word)else {returnErr(ToolFailure::new(format!("`{kind_word}` is not a kind that keeps versions" ))); };letSome(id) = require_string(args, "id") else {returnErr(ToolFailure::new("say which record (id)")); };letSome(version_id) = require_string(args, "version") else {returnErr(ToolFailure::new("say which version (version)")); };let table = history_kind(kind).table;let current = row_by_id(ctx, table, &id)?;// A version is the record as it stood before one edit, rebuilt from the// record's history rows over the live row.let [table_word, kind_word_too] = trail_tables(kind);let params = [id.as_str(), table_word, kind_word_too].map(|text| SqlValue::Text(text.to_string()));let rows = ctx .read .driver() .all(TRAIL_SQL, ¶ms) .map_err(|error| ToolFailure::new(format!("this record's history could not be read: {error}")))?;let trail = record_trail(kind, ctx.read.workspace_id(), &id, &rows, current.as_ref());let data = trail .into_iter() .find(|version| version.id == version_id) .ok_or_else(|| ToolFailure::new("this record has no such version"))? .data;ifletSome(block) = restore_block(kind, current.as_ref()) {returnErr(ToolFailure::new(block.words(&crate::presentation::line_rows(ctx.db(), ctx.workspace_id)))); }let current = current.unwrap_or_default();let patch = in_codec_shape(table, restore_patch(kind, &data, ¤t))?;let put_back: Vec<String> = patch.keys().cloned().collect();if !patch.is_empty() {if kind == VersionRecordKind::Transaction {letmut money_args = Map::new(); money_args.insert("id".into(), Value::from(id.clone()));for (column, value) in patch {let key = match column.as_str() {"occurred_on" => "occurredOn","account_id" => "accountId","amount_minor" => "amountMinor","amount_known" => "amountKnown","for_period" => "forPeriod","repeat_day" => "repeatDay","between_us" => "betweenUs","moves_money" => "movesMoney","payee_text" => "payeeText","counterparty_person_id" => "counterpartyPersonId","settles_transaction_id" => "settlesTransactionId","transfer_of" => "transferOf","due_date" => "dueDate", other => other, }; money_args.insert(key.into(), value); }crate::mcp::handlers::records_2::money::update_transaction(ctx, &money_args)?; } else { update_row(ctx, table, &id, patch)?; } }if put_back.is_empty() {returnErr(ToolFailure::new("this record already reads as that version — there is nothing to put back", )); } ctx.commit()?;Ok(json!({ "id": id, "kind": kind_word, "restored": put_back }))}/// Moves a transaction's counter line back to the account the version held,/// through the money engine with the owner deciding. `false` when the version/// kept no sides or the category is already the one it held./// A version holds each column as the FILE held it (`json_object` over the/// row: a switch as 0 or 1, a list as its JSON text); the writer takes each in/// its column's codec shape, so every value is read back through that codec.fn in_codec_shape(table: &str, patch: Map<String, Value>) -> Valid<Map<String, Value>> {use cotton_store::schema::codecs::decode_value;use rusqlite::types::ValueasSqlValue; patch .into_iter() .map(|(column, value)| {letSome(codec) = cotton_store::schema::specs::codec_of(table, &column) else {returnOk((column, value)); };let stored = match &value {Value::Null => SqlValue::Null,Value::Bool(flag) => SqlValue::Integer(i64::from(*flag)),Value::Number(number) => number .as_i64() .map(SqlValue::Integer) .unwrap_or_else(|| SqlValue::Real(number.as_f64().unwrap_or_default())),Value::String(text) => SqlValue::Text(text.clone()), other => SqlValue::Text(other.to_string()), };let shaped = decode_value(codec, &stored) .map_err(|error| ToolFailure::new(format!("{table}.{column} could not be put back: {error}")))?;Ok((column, if value.is_null() { Value::Null } else { shaped })) }) .collect()}