//! The second reading of a statement: figures from the PDF text layer must //! agree with figures read from the rendered page before money is recorded. //! //! A PDF can say one thing to a text extractor while showing another thing to //! its reader. Rendering is platform work, so this module keeps the rule pure //! and takes its page reading through [`StatementVisualVerifier`]. An absent //! verifier is an explicit refusal; it is never permission to trust text. use std::collections::BTreeMap; use super::engine_shim::StatementReadOutput; use cotton_core::constants::LineDirection; use serde_json::json; /// The dates printed in the statement heading as seen in its rendered pages. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VisualStatementHeader { /// Page carrying the printed heading figures, supplied by the renderer. pub page: i64, pub period_start: String, pub period_end: String, pub opening_balance_minor: Option, pub closing_balance_minor: Option, } /// One amount and date read from a rendered statement page. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VisualStatementLine { pub page: i64, pub posted_on: String, pub amount_minor: i64, pub direction: LineDirection, pub balance_after_minor: Option, /// Opening/totals rows are visible but do not move money. pub ignored: bool, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct StatementFigures { pub header: VisualStatementHeader, pub lines: Vec, } /// The trusted renderer's independent OCR and CMap readings. #[derive(Debug, Clone, PartialEq, Eq)] pub struct VisualStatementReading { /// Whether the source page had an extractable text layer. For that case /// `font_glyph_reading` is mandatory; a scan has no maps to decode. pub has_text_layer: bool, /// The figures after the PDF's own glyph map was decoded. This is kept /// beside OCR so an encoded decoy cannot bless either reading by itself. pub font_glyph_reading: Option, pub figures: StatementFigures, } /// A platform renderer plus OCR. It receives the stored statement identity, /// never caller-provided page claims, so a submitter cannot bless its own text. pub trait StatementVisualVerifier: Send + Sync { fn rendered_reading( &self, workspace_id: &str, statement_id: &str, candidate: &StatementFigures, ) -> Result; } /// A safe, typed explanation for a reading that cannot be trusted. Its text /// intentionally names only a page and field, never a figure from the paper. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum VisualCheckError { #[error("could not read: this server cannot verify the rendered statement pages")] Unavailable, #[error("could not read: the page renderer failed")] Renderer, #[error("could not read: the PDF font glyph maps were not decoded")] GlyphMaps, #[error("could not read: page {page} heading {field} disagrees with the rendered page")] Header { page: i64, field: &'static str }, #[error("could not read: page {page} {field} disagrees with the rendered page")] Page { page: i64, field: &'static str }, } impl VisualCheckError { /// The synced, machine-readable reason. Its projection draws the person's /// definition line; this value contains no statement figure. pub fn stored_reason(&self) -> String { let value = match self { Self::Unavailable => json!({ "code": "visual_unavailable" }), Self::Renderer => json!({ "code": "visual_renderer_failed" }), Self::GlyphMaps => json!({ "code": "visual_glyph_maps_unread" }), Self::Header { page, field } => json!({ "page": page, "code": "visual_mismatch", "field": field.replace(' ', "_"), }), Self::Page { page, field } => json!({ "code": "visual_mismatch", "page": page, "field": field, }), }; value.to_string() } } fn count( lines: impl IntoIterator, bool)>, ) -> BTreeMap<(i64, String, i64, &'static str, Option, bool), usize> { let mut counts = BTreeMap::new(); for line in lines { *counts.entry(line).or_default() += 1; } counts } /// Compare the text-layer reading against what a person sees on each page. /// /// The full multiset is compared so duplicate transactions remain meaningful: /// one visually missing duplicate is a refusal, rather than being hidden by a /// set membership check. fn compare_figures( text: &StatementFigures, visual: &StatementFigures, ) -> Result<(), VisualCheckError> { if text.header.period_start != visual.header.period_start { return Err(VisualCheckError::Header { page: visual.header.page, field: "period start", }); } if text.header.period_end != visual.header.period_end { return Err(VisualCheckError::Header { page: visual.header.page, field: "period end", }); } if text.header.opening_balance_minor != visual.header.opening_balance_minor { return Err(VisualCheckError::Header { page: visual.header.page, field: "opening balance", }); } if text.header.closing_balance_minor != visual.header.closing_balance_minor { return Err(VisualCheckError::Header { page: visual.header.page, field: "closing balance", }); } let visual_counts = count(visual.lines.iter().map(|line| { ( line.page, line.posted_on.clone(), line.amount_minor, line.direction.as_str(), line.balance_after_minor, line.ignored, ) })); let text_counts = count(text.lines.iter().map(|line| { ( line.page, line.posted_on.clone(), line.amount_minor, line.direction.as_str(), line.balance_after_minor, line.ignored, ) })); for line in &text.lines { let exact = ( line.page, line.posted_on.clone(), line.amount_minor, line.direction.as_str(), line.balance_after_minor, line.ignored, ); if text_counts.get(&exact) == visual_counts.get(&exact) { continue; } let dated: Vec<_> = visual .lines .iter() .filter(|shown| shown.page == line.page && shown.posted_on == line.posted_on) .collect(); let amounts: Vec<_> = dated .iter() .filter(|shown| shown.amount_minor == line.amount_minor) .collect(); let directed: Vec<_> = amounts .iter() .filter(|shown| shown.direction == line.direction) .collect(); let field = if dated.is_empty() { "date" } else if amounts.is_empty() { "amount" } else if directed.is_empty() { "direction" } else if !directed .iter() .any(|shown| shown.balance_after_minor == line.balance_after_minor) { "balance" } else if !directed.iter().any(|shown| shown.ignored == line.ignored) { "entry_type" } else { "entry_count" }; return Err(VisualCheckError::Page { page: line.page, field, }); } let extra = visual_counts .iter() .find(|(line, n)| text_counts.get(*line).copied().unwrap_or_default() != **n); if let Some(((page, _, _, _, _, _), _)) = extra { return Err(VisualCheckError::Page { page: *page, field: "entry_count", }); } Ok(()) } pub fn compare_rendered_reading( text: &StatementFigures, visual: &VisualStatementReading, ) -> Result<(), VisualCheckError> { if visual.has_text_layer && visual.font_glyph_reading.is_none() { return Err(VisualCheckError::GlyphMaps); } compare_figures(text, &visual.figures)?; if let Some(glyphs) = &visual.font_glyph_reading { compare_figures(glyphs, &visual.figures)?; } Ok(()) } pub fn visual_facts_from_output(text: &StatementReadOutput) -> StatementFigures { StatementFigures { header: VisualStatementHeader { page: 1, period_start: text.header.period_start.clone(), period_end: text.header.period_end.clone(), opening_balance_minor: text.header.opening_balance_minor, closing_balance_minor: text.header.closing_balance_minor, }, lines: text .lines .iter() .map(|line| VisualStatementLine { page: line.page, posted_on: line.posted_on.clone(), amount_minor: line.amount_minor, direction: line.direction, balance_after_minor: line.balance_after_minor, ignored: line.ignored_reason.is_some(), }) .collect(), } } /// Get the trusted rendered reading and compare it with a text-layer reading. pub fn verify_statement_reading( verifier: Option<&dyn StatementVisualVerifier>, workspace_id: &str, statement_id: &str, text: &StatementReadOutput, ) -> Result<(), VisualCheckError> { verify_visual_facts( verifier, workspace_id, statement_id, &visual_facts_from_output(text), ) } pub fn verify_visual_facts( verifier: Option<&dyn StatementVisualVerifier>, workspace_id: &str, statement_id: &str, facts: &StatementFigures, ) -> Result<(), VisualCheckError> { let verifier = verifier.ok_or(VisualCheckError::Unavailable)?; let visual = verifier .rendered_reading(workspace_id, statement_id, &facts) .map_err(|_| VisualCheckError::Renderer)?; compare_rendered_reading(facts, &visual) } #[cfg(test)] mod tests { use super::*; use crate::mcp::handlers::money::engine_shim::{StatementReadHeader, StatementReadLine}; use cotton_core::constants::{LineDirection, StatementKind}; fn text() -> StatementReadOutput { StatementReadOutput { header: StatementReadHeader { institution: "Test".into(), number_mask: None, kind: StatementKind::Bank, period_start: "2026-01-01".into(), period_end: "2026-01-31".into(), opening_balance_minor: None, closing_balance_minor: None, currency: "INR".into(), account_name: "Test".into(), }, lines: vec![StatementReadLine { page: 2, posted_on: "2026-01-20".into(), text: "payment".into(), amount_minor: 400, direction: LineDirection::Out, balance_after_minor: None, reference: None, ignored_reason: None, }], } } fn visual(amount_minor: i64) -> VisualStatementReading { let figures = StatementFigures { header: VisualStatementHeader { page: 1, period_start: "2026-01-01".into(), period_end: "2026-01-31".into(), opening_balance_minor: None, closing_balance_minor: None, }, lines: vec![VisualStatementLine { page: 2, posted_on: "2026-01-20".into(), amount_minor, direction: LineDirection::Out, balance_after_minor: None, ignored: false, }], }; VisualStatementReading { has_text_layer: true, font_glyph_reading: Some(figures.clone()), figures, } } /// RULE: Text from a PDF is never enough to record money, because a decoy text layer can show a different amount than the page a person sees. #[test] fn decoy_text_amount_is_refused_with_its_page() { assert_eq!( compare_rendered_reading(&visual_facts_from_output(&text()), &visual(401)), Err(VisualCheckError::Page { page: 2, field: "amount" }) ); } #[test] fn clean_rendered_page_agrees() { assert_eq!( compare_rendered_reading(&visual_facts_from_output(&text()), &visual(400)), Ok(()) ); } #[test] fn duplicate_omitted_from_a_page_is_refused() { let mut facts = visual_facts_from_output(&text()); facts.lines.push(facts.lines[0].clone()); assert_eq!( compare_rendered_reading(&facts, &visual(400)), Err(VisualCheckError::Page { page: 2, field: "entry_count" }) ); } #[test] fn date_direction_balance_and_header_disagreements_are_refused() { let facts = visual_facts_from_output(&text()); let mut date = visual(400); date.figures.lines[0].posted_on = "2026-01-21".into(); assert_eq!( compare_rendered_reading(&facts, &date), Err(VisualCheckError::Page { page: 2, field: "date" }) ); let mut direction = visual(400); direction.figures.lines[0].direction = LineDirection::In; assert_eq!( compare_rendered_reading(&facts, &direction), Err(VisualCheckError::Page { page: 2, field: "direction" }) ); let mut balance = visual(400); balance.figures.lines[0].balance_after_minor = Some(1); assert_eq!( compare_rendered_reading(&facts, &balance), Err(VisualCheckError::Page { page: 2, field: "balance" }) ); let mut ignored = visual(400); ignored.figures.lines[0].ignored = true; assert_eq!( compare_rendered_reading(&facts, &ignored), Err(VisualCheckError::Page { page: 2, field: "entry_type" }) ); let mut header = visual(400); header.figures.header.closing_balance_minor = Some(1); assert_eq!( compare_rendered_reading(&facts, &header), Err(VisualCheckError::Header { page: 1, field: "closing balance" }) ); } #[test] fn missing_or_disagreeing_glyph_maps_are_refused() { let facts = visual_facts_from_output(&text()); let mut missing = visual(400); missing.font_glyph_reading = None; assert_eq!( compare_rendered_reading(&facts, &missing), Err(VisualCheckError::GlyphMaps) ); let mut glyphs = visual(400); glyphs.font_glyph_reading.as_mut().expect("maps").lines[0].amount_minor = 401; assert_eq!( compare_rendered_reading(&facts, &glyphs), Err(VisualCheckError::Page { page: 2, field: "amount" }) ); } /// RULE: A mismatch names the field on that date, even when its amount appears on another date; a global set of amounts cannot explain a swapped figure. #[test] fn a_swapped_amount_names_amount_on_its_own_date() { let mut shown = visual(400); let mut other = shown.figures.lines[0].clone(); other.posted_on = "2026-01-21".into(); other.amount_minor = 401; shown.figures.lines.push(other); shown.font_glyph_reading = Some(shown.figures.clone()); let mut candidate = shown.figures.clone(); candidate.lines[0].amount_minor = 401; assert_eq!( compare_rendered_reading(&candidate, &shown), Err(VisualCheckError::Page { page: 2, field: "amount" }) ); } }