Cotton code
116 lines · 4.6 KB · RustRaw
//! One edit, as a reader meets it — the port of//! `packages/core/src/engine/history/entries.ts`.//!//! The off-by-one worth stating out loud: a version row is the state BEFORE the//! edit that dated it, not after. So the edit at `version.created_at` turned//! `version.data` into the NEXT NEWER version's data — or, for the newest row,//! into the record as it stands now. Pairing it the other way would file every//! change under the wrong moment and the wrong name.use serde::{Deserialize, Serialize};use serde_json::Value;use crate::constants::{VersionOp, VersionRecordKind};use super::actor::{version_actor, VersionActor};use super::diff::{diff_fields, FieldChange, RecordRow};use super::fields::{history_columns, history_field, HistoryFieldForm};/// One version row as the trail hands it over — `IRecordVersion`/// from `packages/core/src/models/version/types.ts`.////// `data` is the entire prior row as stored (snake_case keys), kind-generic on/// purpose: the history screen renders the fields it knows and ignores the/// rest, so a future column arrives in history for free.////// `actor_role` stays a `String` rather than becoming/// [`super::actor::VersionActorRole`]. It is free text in the file — a row/// migrated from Postgres carries whatever JWT role wrote it, and a role this/// build has never heard of must deserialise and read as `Direct`, not fail the/// whole trail.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct RecordVersion {    pub id: String,    pub workspace_id: String,    pub record_kind: VersionRecordKind,    pub record_id: String,    pub op: VersionOp,    pub data: RecordRow,    pub actor_role: String,    pub created_at: String,}/// One edit: when it happened, whose hand it was, and what it changed.////// It BORROWS the version and the state after it rather than cloning either —/// a trail is drawn straight from the rows the service already holds, and the/// TypeScript's object shares those references too. Only `changes` is new.#[derive(Debug, Clone, PartialEq)]pub struct HistoryEntry<'a> {    pub version: &'a RecordVersion,    /// Where the record was left by this edit — `None` when it was a delete.    pub after: Option<&'a RecordRow>,    pub actor: VersionActor,    /// Only the columns this kind draws, only those that moved.    pub changes: Vec<FieldChange>,}/// A trail (newest first) plus the live row, as readable edits.////// `current` is the live row snapshot-shaped — the same omissions and the same/// redaction the trigger applies, which `historyService.list` has already done./// Handing it a raw row would report a redacted column as freshly added on the/// newest edit, every time.////// `kind` is the caller's, not `version.record_kind`: the columns drawn are the/// ones the SCREEN asked for. The two coincide in every real caller, and the/// TypeScript takes them as two arguments for the same reason — `journal` and/// `note` are one table read two ways.pub fn history_entries<'a>(    kind: VersionRecordKind,    versions: &'a [RecordVersion],    current: Option<&'a RecordRow>,) -> Vec<HistoryEntry<'a>> {    let columns = history_columns(kind);    versions        .iter()        .enumerate()        .map(|(index, version)| {            let after = if version.op == VersionOp::Delete {                None            } else if index == 0 {                current            } else {                Some(&versions[index - 1].data)            };            HistoryEntry {                version,                after,                actor: version_actor(&version.actor_role),                changes: diff_fields(&version.data, after, &columns)                    .into_iter()                    .filter(|change| {                        // A generic write carries booleans; the live SQLite                        // row carries 0/1. Only declared flags equate them.                        let flag = history_field(kind, &change.column)                            .is_some_and(|field| field.form == HistoryFieldForm::Flag);                        !flag || !same_flag_forms(&change.before, &change.after)                    })                    .collect(),            }        })        .collect()}fn same_flag_forms(before: &Value, after: &Value) -> bool {    match (before, after) {        (Value::Bool(flag), Value::Number(number))        | (Value::Number(number), Value::Bool(flag)) => number.as_i64() == Some(i64::from(*flag)),        _ => false,    }}#[cfg(test)]#[path = "entries_tests.rs"]mod tests;