feat(domain): R2.2 report migration, rebase, sheet snapshot and layered archive reading in Rust; draft restore and archive import operations

migrateReportV2ToV3 / readReportDocument (version read on the raw value,
JS truthiness kept, a malformed mapped path still fails the read),
rebaseReportOnSheet (??= labels, archived names first-match),
buildSheetSnapshot / assertSnapshot (raw depth, shape, caps in UTF-16 and
UTF-8, integrity), readArchiveDocument (layered: report first, wrapper,
snapshot gate, sheet invariant, unsupported_envelope origin quirk).
Checked against 84 cases frozen from the TypeScript and 765 Zod verdicts
(one declared difference: L1, a lone surrogate reads as U+FFFD), the
ported report and archive suites and the 612 legacy leaves. Facade:
draft.restore (content kinds invalid / unsupported_version, rebase_failed
never a content kind), archive.import (incompatible_version with found,
no_attachment), archive.snapshot.
This commit is contained in:
bchanot committed 2026-10-14 00:28:02 +02:00
1 parent 6c0533c1da
commit 21906c4358
28 files changed
+5239 -213

No files matched your search

+4
View File
@@ -3,9 +3,13 @@
pub mod branding;
pub mod envelope;
pub mod labels;
pub mod read;
pub mod snapshot;
pub mod snapshot_rules;
pub use branding::*;
pub use envelope::*;
pub use labels::*;
pub use read::{ArchiveOrigin, ArchiveReadOutcome, parse_envelope, read_archive_document};
pub use snapshot::*;
pub use snapshot_rules::{SnapshotRejection, assert_snapshot, build_sheet_snapshot};
+125
View File
@@ -0,0 +1,125 @@
//! Layered reading of a PDF attachment (`archive/envelope.ts`, STEP6 §4, §14 "Read").
//!
//! The report is located and parsed first so it is never lost because of its wrapper; the
//! wrapper is then validated whole or dropped with a reason. Accepted shapes: a bare Report v2
//! or v3, or an archive envelope of version 1.
use serde::Serialize;
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::envelope::{ENVELOPE_VERSION, EnvelopeVersion1, EnvelopeWrapper, ReportArchiveEnvelope};
use super::snapshot::SheetSnapshot;
use super::snapshot_rules::{SnapshotRejection, assert_snapshot};
use crate::domain::report::read::{ReadFailure, read_report_document, version_of};
use crate::domain::report::{Report, ReportMigrationMap};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum ArchiveOrigin {
EnvelopeV1,
BareV3,
V2,
}
/// What an attachment gave back: always the report, the envelope when accepted.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct ArchiveReadOutcome {
pub report: Report,
pub origin: ArchiveOrigin,
pub migrated: bool,
/// From the v2 migration; 0 for a v3 report.
pub unresolved_zones: u32,
pub unresolved_findings: u32,
/// The validated envelope, when accepted.
pub archive: Option<ReportArchiveEnvelope>,
/// Envelope present but dropped, with the reason.
#[serde(skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "ts", ts(optional))]
pub snapshot_rejected: Option<SnapshotRejection>,
}
/// An envelope of any version is recognised by a numeric `envelopeVersion`.
fn envelope_version_of(data: &Value) -> Option<f64> {
data.as_object()?.get("envelopeVersion")?.as_f64()
}
/// Reads the JSON of a PDF attachment of any supported shape. Fails only when the report
/// itself cannot be read (unknown version, corrupt document).
pub fn read_archive_document(
data: &Value,
map: &ReportMigrationMap,
) -> Result<ArchiveReadOutcome, ReadFailure> {
let envelope_version = envelope_version_of(data);
let report_data = match envelope_version {
Some(_) => data.get("report").unwrap_or(&Value::Null),
None => data,
};
let outcome = read_report_document(report_data, map)?;
let migrated = version_of(report_data) != Some(3.0);
let mut read = ArchiveReadOutcome {
report: outcome.report,
origin: if migrated {
ArchiveOrigin::V2
} else {
ArchiveOrigin::BareV3
},
migrated,
unresolved_zones: outcome.unresolved_zones,
unresolved_findings: outcome.unresolved_findings,
archive: None,
snapshot_rejected: None,
};
let Some(version) = envelope_version else {
return Ok(read);
};
if version != f64::from(ENVELOPE_VERSION) {
// The origin stays the report's: the envelope of an unknown version is not read.
read.snapshot_rejected = Some(SnapshotRejection::UnsupportedEnvelope);
return Ok(read);
}
read.origin = ArchiveOrigin::EnvelopeV1;
match read_envelope_v1(data, &read.report) {
Ok(archive) => read.archive = Some(archive),
Err(reason) => read.snapshot_rejected = Some(reason),
}
Ok(read)
}
/// A v1 envelope: wrapper schema → snapshot gate → sheet invariant.
fn read_envelope_v1(
data: &Value,
report: &Report,
) -> Result<ReportArchiveEnvelope, SnapshotRejection> {
let wrapper: EnvelopeWrapper =
serde_json::from_value(data.clone()).map_err(|_| SnapshotRejection::Schema)?;
let snapshot = assert_snapshot(data.get("sheetSnapshot").unwrap_or(&Value::Null))?;
if !snapshot_matches(&snapshot, report) {
return Err(SnapshotRejection::SheetMismatch);
}
Ok(ReportArchiveEnvelope {
format: wrapper.format,
envelope_version: EnvelopeVersion1,
exported_at: wrapper.exported_at,
locale: wrapper.locale,
report: report.clone(),
sheet_snapshot: snapshot,
branding: wrapper.branding,
labels: wrapper.labels,
})
}
fn snapshot_matches(snapshot: &SheetSnapshot, report: &Report) -> bool {
snapshot.reference.sheet_id == report.sheet.sheet_id
&& snapshot.reference.document_sha256 == report.sheet.document_sha256
}
/// `ReportArchiveEnvelopeSchema.parse`: the shape of a whole envelope (the snapshot's shape
/// only, no caps nor integrity), as the session keeps it.
pub fn parse_envelope(data: &Value) -> Result<ReportArchiveEnvelope, serde_json::Error> {
serde_json::from_value(data.clone())
}
@@ -0,0 +1,331 @@
//! Building and gating the sheet snapshot of an archive (`archive/snapshot.ts`).
//!
//! The snapshot is a valid, lean sheet document (every view, annotation, category and region;
//! finding trees pruned to the paths the report uses; bibliography emptied) plus the SVG text
//! of every asset a view reaches. `assert_snapshot` is the single gate an imported snapshot
//! passes, in this order: finding depth on the raw input, shape, caps, integrity.
use std::collections::{HashMap, HashSet};
use serde::Serialize;
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::snapshot::{SheetSnapshot, SheetSnapshotAsset, SheetSnapshotRef, SnapshotCaps};
use crate::domain::js;
use crate::domain::report::Report;
use crate::domain::sheet::validate::{SheetIssueSeverity, validate_sheet_document};
use crate::domain::sheet::{
AnatomicalSheetDocument, Annotation, FindingCategory, FindingNode, FindingZone, LoadedSheet,
LocalizedOptionalText, SheetView,
};
/// Why an imported snapshot (or its envelope) is dropped; the import reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "snake_case")]
pub enum SnapshotRejection {
UnsupportedEnvelope,
Schema,
Caps,
Integrity,
SheetMismatch,
}
// ---------------------------------------------------------------------------
// Build
/// The snapshot of `sheet` that `report` needs: pure, deterministic (document order
/// everywhere). A missing asset is left out and caught by `assert_snapshot`.
pub fn build_sheet_snapshot(sheet: &LoadedSheet, report: &Report) -> SheetSnapshot {
SheetSnapshot {
status: sheet.status,
reference: SheetSnapshotRef {
sheet_id: sheet.reference.sheet_id.clone(),
version_id: sheet.reference.version_id.clone(),
document_sha256: sheet.reference.document_sha256.clone(),
schema_version: sheet.schema_version,
species_id: sheet.species_id.clone(),
},
document: lean_document(&sheet.document, report),
assets: snapshot_assets(sheet),
}
}
/// Finding paths of the report grouped by zone, resolved and unresolved alike.
fn paths_by_zone(report: &Report) -> HashMap<&str, Vec<&[String]>> {
let mut by_zone: HashMap<&str, Vec<&[String]>> = HashMap::new();
for finding in report.observations.iter().flat_map(|o| &o.findings) {
by_zone
.entry(finding.finding_zone_id.as_str())
.or_default()
.push(&finding.path);
}
by_zone
}
/// Paths whose segment at `depth` is `id`.
fn under<'a>(paths: &[&'a [String]], depth: usize, id: &str) -> Vec<&'a [String]> {
paths
.iter()
.filter(|p| p.get(depth).is_some_and(|segment| segment == id))
.copied()
.collect()
}
/// Keeps, in document order, the nodes at `depth` of some path and their used descendants.
fn prune_nodes(nodes: &[FindingNode], paths: &[&[String]], depth: usize) -> Vec<FindingNode> {
nodes
.iter()
.filter_map(|node| {
let kept = under(paths, depth, &node.id);
(!kept.is_empty()).then(|| FindingNode {
id: node.id.clone(),
name: node.name.clone(),
description: LocalizedOptionalText::default(),
requires_vet_referral: node.requires_vet_referral,
reference_ids: Vec::new(),
review_status: node.review_status,
children: prune_nodes(&node.children, &kept, depth + 1),
})
})
.collect()
}
fn prune_categories(categories: &[FindingCategory], paths: &[&[String]]) -> Vec<FindingCategory> {
categories
.iter()
.filter_map(|category| {
let kept = under(paths, 0, &category.id);
(!kept.is_empty()).then(|| FindingCategory {
id: category.id.clone(),
kind: category.kind,
name: category.name.clone(),
description: LocalizedOptionalText::default(),
reference_ids: Vec::new(),
review_status: category.review_status,
children: prune_nodes(&category.children, &kept, 1),
})
})
.collect()
}
fn lean_document(document: &AnatomicalSheetDocument, report: &Report) -> AnatomicalSheetDocument {
let used = paths_by_zone(report);
let prune_zone = |zone: &FindingZone| FindingZone {
id: zone.id.clone(),
name: zone.name.clone(),
categories: prune_categories(
&zone.categories,
used.get(zone.id.as_str()).map_or(&[], Vec::as_slice),
),
};
AnatomicalSheetDocument {
schema_version: document.schema_version,
species_id: document.species_id.clone(),
name: document.name.clone(),
description: document.description.clone(),
scope_disclaimer: document.scope_disclaimer.clone(),
attribution: document.attribution.clone(),
vertebral_config: document.vertebral_config.clone(),
references: Vec::new(),
categories: document.categories.clone(),
views: document.views.clone(),
annotations: document.annotations.clone(),
finding_zones: document.finding_zones.iter().map(prune_zone).collect(),
}
}
/// Views by id, last entry wins (`new Map(views.map(v => [v.id, v]))`).
fn views_by_id(views: &[SheetView]) -> HashMap<&str, &SheetView> {
views.iter().map(|v| (v.id(), v)).collect()
}
/// The asset a view draws: its own, else the first one up its parent chain.
fn asset_of_view<'a>(view: &'a SheetView, views: &HashMap<&str, &'a SheetView>) -> Option<&'a str> {
let mut visited = HashSet::new();
let mut current = Some(view);
while let Some(v) = current {
if !visited.insert(v.id()) {
return None;
}
if let Some(asset) = v.svg_asset_id() {
return Some(asset);
}
current = v
.parent_view_id()
.and_then(|parent| views.get(parent).copied());
}
None
}
/// Asset ids reachable from the views, in view order, each once.
fn reachable_asset_ids(document: &AnatomicalSheetDocument) -> Vec<&str> {
let views = views_by_id(&document.views);
let mut ids: Vec<&str> = Vec::new();
for view in &document.views {
if let Some(id) = asset_of_view(view, &views)
&& !ids.contains(&id)
{
ids.push(id);
}
}
ids
}
fn snapshot_assets(sheet: &LoadedSheet) -> Vec<SheetSnapshotAsset> {
reachable_asset_ids(&sheet.document)
.into_iter()
.filter_map(|id| {
let svg = sheet.assets.get(id)?;
Some(SheetSnapshotAsset {
svg_asset_id: id.to_owned(),
sha256: sheet.asset_hashes.get(id).cloned(),
svg: svg.clone(),
})
})
.collect()
}
// ---------------------------------------------------------------------------
// Assert
/// The single gate of an imported snapshot: depth on the raw input, then shape (`schema`),
/// caps, integrity rules and every view reaching a carried asset (`integrity`).
pub fn assert_snapshot(input: &Value) -> Result<SheetSnapshot, SnapshotRejection> {
assert_finding_depth(input)?;
let snapshot: SheetSnapshot =
serde_json::from_value(input.clone()).map_err(|_| SnapshotRejection::Schema)?;
assert_caps(&snapshot)?;
assert_integrity(&snapshot)?;
Ok(snapshot)
}
/// Depth of the finding trees on the raw input, before the shape parse recurses into it.
/// Iterative: an explicit stack of (node, depth) pairs, categories at depth 1.
fn assert_finding_depth(input: &Value) -> Result<(), SnapshotRejection> {
let zones = input
.as_object()
.and_then(|o| o.get("document"))
.and_then(Value::as_object)
.and_then(|d| d.get("finding_zones"))
.and_then(Value::as_array);
let Some(zones) = zones else { return Ok(()) };
let mut stack: Vec<(&Value, usize)> = zones
.iter()
.filter_map(|zone| zone.as_object()?.get("categories")?.as_array())
.flatten()
.map(|category| (category, 1))
.collect();
while let Some((node, depth)) = stack.pop() {
if depth > SnapshotCaps::FINDING_DEPTH {
return Err(SnapshotRejection::Caps);
}
let children = node
.as_object()
.and_then(|n| n.get("children"))
.and_then(Value::as_array);
stack.extend(children.into_iter().flatten().map(|c| (c, depth + 1)));
}
Ok(())
}
fn count_finding_nodes(document: &AnatomicalSheetDocument) -> usize {
fn nodes(list: &[FindingNode]) -> usize {
list.iter().map(|n| 1 + nodes(&n.children)).sum()
}
document
.finding_zones
.iter()
.flat_map(|z| &z.categories)
.map(|c| 1 + nodes(&c.children))
.sum()
}
/// Longest `name` label (`fr` or `en`, UTF-16 units) anywhere in the document.
fn longest_name(document: &AnatomicalSheetDocument) -> usize {
fn node_names(list: &[FindingNode], longest: &mut usize) {
for node in list {
*longest = (*longest).max(label_len(&node.name));
node_names(&node.children, longest);
}
}
let mut longest = label_len(&document.name);
let mut take = |len: usize| longest = longest.max(len);
document
.views
.iter()
.for_each(|v| take(label_len(v.name())));
document
.categories
.iter()
.for_each(|c| take(label_len(&c.name)));
document
.vertebral_config
.regions
.iter()
.for_each(|r| take(label_len(&r.name)));
for annotation in &document.annotations {
match annotation {
Annotation::Observable(a) => take(label_len(&a.name)),
Annotation::DetailTrigger(t) => take(t.name.as_ref().map_or(0, label_len)),
}
}
for zone in &document.finding_zones {
take(label_len(&zone.name));
for category in &zone.categories {
take(label_len(&category.name));
let mut deep = 0;
node_names(&category.children, &mut deep);
take(deep);
}
}
longest
}
fn label_len(text: &crate::domain::sheet::LocalizedText) -> usize {
js::utf16_len(&text.fr).max(js::utf16_len(&text.en))
}
fn assert_caps(snapshot: &SheetSnapshot) -> Result<(), SnapshotRejection> {
let document = &snapshot.document;
let sizes: Vec<usize> = snapshot.assets.iter().map(|a| a.svg.len()).collect();
let over = document.views.len() > SnapshotCaps::VIEWS
|| document.annotations.len() > SnapshotCaps::ANNOTATIONS
|| count_finding_nodes(document) > SnapshotCaps::FINDING_NODES
|| longest_name(document) > SnapshotCaps::LABEL_CHARS
|| snapshot.assets.len() > SnapshotCaps::ASSETS
|| sizes.iter().any(|&size| size > SnapshotCaps::ASSET_BYTES)
|| sizes.iter().sum::<usize>() > SnapshotCaps::ASSETS_TOTAL_BYTES;
if over {
Err(SnapshotRejection::Caps)
} else {
Ok(())
}
}
fn assert_integrity(snapshot: &SheetSnapshot) -> Result<(), SnapshotRejection> {
let has_error = validate_sheet_document(&snapshot.document)
.iter()
.any(|issue| issue.severity == SheetIssueSeverity::Error);
if has_error {
return Err(SnapshotRejection::Integrity);
}
let present: HashSet<&str> = snapshot
.assets
.iter()
.map(|a| a.svg_asset_id.as_str())
.collect();
let views = views_by_id(&snapshot.document.views);
let every_view_drawn = snapshot
.document
.views
.iter()
.all(|view| asset_of_view(view, &views).is_some_and(|id| present.contains(id)));
if every_view_drawn {
Ok(())
} else {
Err(SnapshotRejection::Integrity)
}
}
+1
View File
@@ -4,6 +4,7 @@ pub mod archive;
pub mod editor;
pub mod js;
pub mod report;
pub mod session;
pub mod sheet;
pub use report::{LateralSide, ReportZone, SheetRef, Unresolved, Vertebra};
+4
View File
@@ -2,9 +2,13 @@
pub mod identity;
pub mod migration_map;
pub mod read;
pub mod rebase;
pub mod v2;
pub mod v3;
pub use identity::*;
pub use migration_map::{ReportMigrationMap, finding_path_key};
pub use read::{MigrationOutcome, ReadFailure, migrate_report_v2_to_v3, read_report_document};
pub use rebase::{RebaseOutcome, rebase_report_on_sheet};
pub use v3::*;
+196
View File
@@ -0,0 +1,196 @@
//! Reading a report document of any supported version (`report/migrate.ts`).
//!
//! A Report v2 (PDF attachment or sessionStorage draft of the deployed application) is lifted
//! to v3 against the migration map of the reference sheet. A zone or finding the map cannot
//! place is kept verbatim with its snapshots and flagged `unresolved`. The JavaScript
//! truthiness of the original is kept on purpose: an empty `detailSourceId` means the main
//! view, `requiresVetReferral: false` is dropped, `vertebrae: []` is kept.
use serde::Serialize;
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::migration_map::{ReportMigrationMap, finding_path_key};
use super::v2::{FindingV2, ObservationV2, ObservationZoneV2, ReportV2, SeverityV2};
use super::v3::{
Finding, Observation, Report, ReportVersion3, ReportZone, Severity, Unresolved, Vertebra,
};
/// The report as v3 and what the migration could not place (0 for a v3 document).
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct MigrationOutcome {
pub report: Report,
/// Zones whose legacy id has no annotation in the map.
pub unresolved_zones: u32,
/// Findings whose legacy path no longer exists in the sheet.
pub unresolved_findings: u32,
}
/// Why a report document cannot be read.
#[derive(Debug, Clone, PartialEq)]
pub enum ReadFailure {
/// The `version` is not 2 or 3: the number found, `None` when there is none.
UnsupportedVersion(Option<f64>),
/// A document of a known version that does not parse: corrupt, not old.
Invalid(String),
}
impl ReadFailure {
fn invalid(error: impl std::fmt::Display) -> Self {
Self::Invalid(error.to_string())
}
}
/// `typeof data.version === 'number'`, on a non-array object.
pub fn version_of(data: &Value) -> Option<f64> {
data.as_object()?.get("version")?.as_f64()
}
/// Reads a report document of version 2 or 3 and returns it as v3.
pub fn read_report_document(
data: &Value,
map: &ReportMigrationMap,
) -> Result<MigrationOutcome, ReadFailure> {
let version = version_of(data);
if version == Some(3.0) {
let report: Report = serde_json::from_value(data.clone()).map_err(ReadFailure::invalid)?;
return Ok(MigrationOutcome {
report,
unresolved_zones: 0,
unresolved_findings: 0,
});
}
if version == Some(2.0) {
let report: ReportV2 =
serde_json::from_value(data.clone()).map_err(ReadFailure::invalid)?;
return migrate_report_v2_to_v3(&report, map);
}
Err(ReadFailure::UnsupportedVersion(version))
}
/// Lifts a parsed Report v2 to v3; the result passes the v3 schema like `ReportSchema.parse`.
pub fn migrate_report_v2_to_v3(
report: &ReportV2,
map: &ReportMigrationMap,
) -> Result<MigrationOutcome, ReadFailure> {
let observations = report
.observations
.iter()
.map(|o| migrate_observation(o, map))
.collect();
let migrated = Report {
version: ReportVersion3,
id: report.id.clone(),
created_at: report.created_at.clone(),
date: report.date.clone(),
practitioner: report.practitioner.clone(),
animal: report.animal.clone(),
owner: report.owner.clone(),
sheet: map.sheet.clone(),
observations,
conclusion: report.conclusion.clone(),
recommendations: report.recommendations.clone(),
next_appointment: report.next_appointment.clone(),
local_annotations: Vec::new(),
};
let report = reparse(&migrated)?;
let (unresolved_zones, unresolved_findings) = unresolved_counts(&report);
Ok(MigrationOutcome {
report,
unresolved_zones,
unresolved_findings,
})
}
/// `ReportSchema.parse` of a report built in code: every constraint checked again.
pub(crate) fn reparse(report: &Report) -> Result<Report, ReadFailure> {
let value = serde_json::to_value(report).map_err(ReadFailure::invalid)?;
serde_json::from_value(value).map_err(ReadFailure::invalid)
}
fn unresolved_counts(report: &Report) -> (u32, u32) {
let zones = report.observations.iter().flat_map(|o| &o.zones);
let findings = report.observations.iter().flat_map(|o| &o.findings);
(
count(zones.filter(|z| z.unresolved.is_some())),
count(findings.filter(|f| f.unresolved.is_some())),
)
}
fn count<T>(items: impl Iterator<Item = T>) -> u32 {
u32::try_from(items.count()).unwrap_or(u32::MAX)
}
fn migrate_zone(zone: &ObservationZoneV2, map: &ReportMigrationMap) -> ReportZone {
let entry = map.annotations.get(&zone.bone_id);
let view_id = match zone.detail_source_id.as_deref() {
Some(key) if !key.is_empty() => map.views.get(key).map_or(key, String::as_str),
_ => map.main_view_id.as_str(),
};
ReportZone {
annotation_id: entry.map_or(&zone.bone_id, |e| &e.id).clone(),
view_id: view_id.to_owned(),
side: zone.side,
vertebrae: zone.vertebrae.as_ref().map(|list| {
list.iter()
.map(|v| Vertebra {
region: v.region.clone(),
index: v.index,
})
.collect()
}),
label_fr_snapshot: entry.map(|e| e.name.fr.clone()),
label_en_snapshot: entry.map(|e| e.name.en.clone()),
unresolved: entry.is_none().then_some(Unresolved),
}
}
fn migrate_finding(finding: &FindingV2, map: &ReportMigrationMap) -> Finding {
let key = finding_path_key(&finding.zone_id, &finding.path);
let mut out = Finding {
finding_zone_id: finding.zone_id.clone(),
path: finding.path.clone(),
label_fr_snapshot: finding.label_fr_snapshot.clone(),
label_en_snapshot: finding.label_en_snapshot.clone(),
requires_vet_referral: (finding.requires_vet_referral == Some(true)).then_some(true),
side: finding.side,
unresolved: None,
};
match map.finding_paths.get(&key) {
Some(Some(mapped)) => {
// `const [zoneId, ...path] = mapped.split('/')`.
let mut segments = mapped.split('/').map(str::to_owned);
out.finding_zone_id = segments.next().unwrap_or_default();
out.path = segments.collect();
}
// null = removed by curation; absent = never part of the legacy catalog.
_ => out.unresolved = Some(Unresolved),
}
out
}
fn migrate_observation(obs: &ObservationV2, map: &ReportMigrationMap) -> Observation {
Observation {
id: obs.id.clone(),
zones: obs.zones.iter().map(|z| migrate_zone(z, map)).collect(),
findings: obs
.findings
.iter()
.map(|f| migrate_finding(f, map))
.collect(),
free_text_findings: obs.free_text_findings.clone(),
severity: obs.severity.map(severity_code),
comment: obs.comment.clone(),
}
}
fn severity_code(severity: SeverityV2) -> Severity {
match severity {
SeverityV2::Legere => Severity::Mild,
SeverityV2::Moderee => Severity::Moderate,
SeverityV2::Severe => Severity::Severe,
}
}
+153
View File
@@ -0,0 +1,153 @@
//! Moving a report onto the sheet the application has loaded (`report/rebase.ts`, STEP6 §3.5).
//!
//! A report written on another revision of the sheet keeps every datum: a zone or finding the
//! loaded sheet no longer holds is flagged `unresolved`, its labels taken from the archived
//! snapshot when the report carries none, and the report now references the loaded sheet.
//! Nothing happens when the report already sits on the loaded sheet.
use serde::Serialize;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::read::{ReadFailure, reparse};
use super::v3::{Finding, Observation, Report, ReportZone, Unresolved};
use crate::domain::archive::SheetSnapshot;
use crate::domain::sheet::{Annotation, IndexedDocument, LoadedSheet, LocalizedText};
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct RebaseOutcome {
pub report: Report,
/// Zones and findings newly flagged by this rebase.
pub unresolved_zones: u32,
pub unresolved_findings: u32,
pub rebased: bool,
}
#[derive(Default)]
struct Counters {
zones: u32,
findings: u32,
}
/// Rebases `report` on `sheet`; `archived` is the snapshot of the sheet it was written on.
pub fn rebase_report_on_sheet(
report: &Report,
sheet: &LoadedSheet,
archived: Option<&SheetSnapshot>,
) -> Result<RebaseOutcome, ReadFailure> {
if report.sheet.document_sha256 == sheet.reference.document_sha256 {
return Ok(RebaseOutcome {
report: report.clone(),
unresolved_zones: 0,
unresolved_findings: 0,
rebased: false,
});
}
let index = sheet.indexed();
let mut counters = Counters::default();
let mut rebased = report.clone();
rebased.sheet = sheet.reference.clone();
rebased.observations = report
.observations
.iter()
.map(|o| rebase_observation(o, &index, archived, &mut counters))
.collect();
Ok(RebaseOutcome {
report: reparse(&rebased)?,
unresolved_zones: counters.zones,
unresolved_findings: counters.findings,
rebased: true,
})
}
fn rebase_observation(
observation: &Observation,
index: &IndexedDocument<'_>,
archived: Option<&SheetSnapshot>,
counters: &mut Counters,
) -> Observation {
let mut out = observation.clone();
out.zones = observation
.zones
.iter()
.map(|z| rebase_zone(z, index, archived, counters))
.collect();
out.findings = observation
.findings
.iter()
.map(|f| rebase_finding(f, index, counters))
.collect();
out
}
fn rebase_zone(
zone: &ReportZone,
index: &IndexedDocument<'_>,
archived: Option<&SheetSnapshot>,
counters: &mut Counters,
) -> ReportZone {
if zone.unresolved.is_some() {
return zone.clone();
}
let known =
index.annotation(&zone.annotation_id).is_some() && index.view(&zone.view_id).is_some();
if known {
return zone.clone();
}
counters.zones += 1;
flag_zone(zone, archived)
}
fn flag_zone(zone: &ReportZone, archived: Option<&SheetSnapshot>) -> ReportZone {
let mut out = zone.clone();
out.unresolved = Some(Unresolved);
if let Some(name) = archived_name(archived, &zone.annotation_id) {
// `??=`: only a label the report does not carry at all is filled in.
out.label_fr_snapshot.get_or_insert_with(|| name.fr.clone());
out.label_en_snapshot.get_or_insert_with(|| name.en.clone());
}
out
}
/// The name the archived snapshot gives an annotation (a trigger: its own, else its view's),
/// first match in document order as `Array.prototype.find`.
fn archived_name<'a>(
archived: Option<&'a SheetSnapshot>,
annotation_id: &str,
) -> Option<&'a LocalizedText> {
let document = &archived?.document;
let annotation = document
.annotations
.iter()
.find(|a| a.id() == annotation_id)?;
match annotation {
Annotation::Observable(a) => Some(&a.name),
Annotation::DetailTrigger(t) => t.name.as_ref().or_else(|| {
document
.views
.iter()
.find(|v| v.id() == t.opens_view_id)
.map(|v| v.name())
}),
}
}
fn rebase_finding(
finding: &Finding,
index: &IndexedDocument<'_>,
counters: &mut Counters,
) -> Finding {
if finding.unresolved.is_some()
|| index
.node_at(&finding.finding_zone_id, &finding.path)
.is_some()
{
return finding.clone();
}
counters.findings += 1;
let mut out = finding.clone();
out.unresolved = Some(Unresolved);
out
}
+124
View File
@@ -0,0 +1,124 @@
//! The two session entries that read user data on the loaded sheet: restoring the tab's draft
//! (`reportStore.restoreDraft` + `persistence.ts`) and importing a PDF attachment
//! (`HomeRoute.importFile` after the byte scan). Pure: the caller passes the stored texts.
use serde::Serialize;
use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use super::archive::ReportArchiveEnvelope;
use super::archive::read::{ArchiveReadOutcome, parse_envelope, read_archive_document};
use super::js::parse_json;
use super::report::{ReadFailure, RebaseOutcome, read_report_document, rebase_report_on_sheet};
use super::sheet::LoadedSheet;
/// A restored draft: the rebase outcome carries the report the store opens.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct DraftRestore {
pub rebase: RebaseOutcome,
/// The session's archive envelope, when one was stored and still parses.
pub archive: Option<ReportArchiveEnvelope>,
/// An archive text was stored but no longer parses (the caller sets it aside).
pub archive_rejected: bool,
}
/// Why a draft cannot be restored. Content kinds only: the caller quarantines the text.
#[derive(Debug, Clone, PartialEq)]
pub enum RestoreFailure {
/// The draft carries a report version this build does not read (`None`: no version).
UnsupportedVersion(Option<f64>),
/// Not JSON, or a known version that does not parse.
Invalid(String),
/// The draft reads but cannot be moved onto the loaded sheet (its reference fails the
/// report schema): a defect of the loaded sheet, not of the draft, never a quarantine.
Rebase(String),
}
/// An imported attachment read and rebased onto the loaded sheet.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
pub struct ArchiveImport {
pub read: ArchiveReadOutcome,
pub rebase: RebaseOutcome,
}
/// Why an import fails, as `packages/pdf/src/read.ts` names it for the report part.
#[derive(Debug, Clone, PartialEq)]
pub enum ImportFailure {
/// A numeric but unknown report version.
IncompatibleVersion(f64),
/// No version at all, or a corrupt report: not a Faunosteo attachment.
NoAttachment,
/// The read report could not be moved onto the loaded sheet (the rebased report fails
/// its schema: a defect of the loaded sheet's reference, never of the file).
Invalid(String),
}
impl From<ReadFailure> for RestoreFailure {
fn from(failure: ReadFailure) -> Self {
match failure {
ReadFailure::UnsupportedVersion(found) => Self::UnsupportedVersion(found),
ReadFailure::Invalid(detail) => Self::Invalid(detail),
}
}
}
/// Reads the tab's draft (v3 as is, v2 migrated) and rebases it on `sheet` with the archived
/// snapshot of the session's envelope. An unreadable envelope never fails the draft.
pub fn restore_draft(
sheet: &LoadedSheet,
draft_text: &str,
archive_text: Option<&str>,
) -> Result<DraftRestore, RestoreFailure> {
let draft = parse_json(draft_text).map_err(|e| RestoreFailure::Invalid(e.to_string()))?;
let report = read_report_document(&draft, &sheet.migration_map)?.report;
let archive = archive_text.and_then(read_envelope_text);
let archive_rejected = archive_text.is_some() && archive.is_none();
let archived = archive.as_ref().map(|a| &a.sheet_snapshot);
let rebase =
rebase_report_on_sheet(&report, sheet, archived).map_err(|failure| match failure {
ReadFailure::Invalid(detail) => RestoreFailure::Rebase(detail),
ReadFailure::UnsupportedVersion(_) => {
RestoreFailure::Rebase("unsupported version".to_owned())
}
})?;
Ok(DraftRestore {
rebase,
archive,
archive_rejected,
})
}
fn read_envelope_text(text: &str) -> Option<ReportArchiveEnvelope> {
parse_json(text)
.ok()
.and_then(|value| parse_envelope(&value).ok())
}
/// Reads an attachment's JSON text and rebases the report onto `sheet` with the archived
/// snapshot when the envelope was accepted.
pub fn import_archive(
sheet: &LoadedSheet,
data_text: &str,
) -> Result<ArchiveImport, ImportFailure> {
let data: Value = parse_json(data_text).map_err(|_| ImportFailure::NoAttachment)?;
let read =
read_archive_document(&data, &sheet.migration_map).map_err(|failure| match failure {
ReadFailure::UnsupportedVersion(Some(found)) => {
ImportFailure::IncompatibleVersion(found)
}
_ => ImportFailure::NoAttachment,
})?;
let archived = read.archive.as_ref().map(|a| &a.sheet_snapshot);
let rebase =
rebase_report_on_sheet(&read.report, sheet, archived).map_err(|failure| match failure {
ReadFailure::Invalid(detail) => ImportFailure::Invalid(detail),
ReadFailure::UnsupportedVersion(_) => {
ImportFailure::Invalid("unsupported version".to_owned())
}
})?;
Ok(ArchiveImport { read, rebase })
}
+62
View File
@@ -7,10 +7,12 @@ use serde_json::Value;
#[cfg(feature = "ts")]
use ts_rs::TS;
use crate::domain::archive::build_sheet_snapshot;
use crate::domain::editor::{
self, EditorError, LeafClick, MoveDirection, NewReportDraft, NewReportStamp, VertebraAction,
};
use crate::domain::report::{LateralSide, Observation, Report, SheetRef, Vertebra};
use crate::domain::session::{self, ImportFailure, RestoreFailure};
use crate::domain::sheet::{LoadedSheet, SheetIndexData, check_sheet_document};
use crate::facade::{Failure, parse_input, to_value};
@@ -209,6 +211,9 @@ pub fn on_sheet(sheet: &LoadedSheet, op: &str, input: &str) -> Option<Outcome> {
"vertebra.initial" => vertebra_initial(sheet, input),
"vertebra.sync" => vertebra_sync(sheet, input),
"finding.toggle" => finding_toggle(sheet, input),
"draft.restore" => draft_restore(sheet, input),
"archive.import" => archive_import(sheet, input),
"archive.snapshot" => archive_snapshot(sheet, input),
_ => return None,
})
}
@@ -274,3 +279,60 @@ fn finding_toggle(sheet: &LoadedSheet, input: &str) -> Outcome {
.map_err(editor_failure)
.and_then(|observation| to_value(&observation))
}
#[derive(Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct DraftRestoreInput {
/// The raw text of the tab's draft.
pub draft: String,
/// The raw text of the session's archive envelope, when one is stored.
pub archive: Option<String>,
}
#[derive(Deserialize)]
#[cfg_attr(feature = "ts", derive(TS), ts(export))]
#[serde(rename_all = "camelCase")]
pub struct SnapshotInput {
pub report: Report,
}
/// A failure that names the document version a reader refused.
fn versioned(kind: &'static str, found: Option<f64>) -> Failure {
Failure {
found,
..Failure::new(kind, "")
}
}
/// Content kinds (`invalid`, `unsupported_version`) mean the draft itself is unreadable:
/// the caller sets it aside. `rebase_failed` is a defect of the loaded sheet, never of the
/// draft, and leaves it where it is.
fn draft_restore(sheet: &LoadedSheet, input: &str) -> Outcome {
let input: DraftRestoreInput = parse_input(input)?;
session::restore_draft(sheet, &input.draft, input.archive.as_deref())
.map_err(|failure| match failure {
RestoreFailure::UnsupportedVersion(found) => versioned("unsupported_version", found),
RestoreFailure::Invalid(detail) => Failure::new("invalid", detail),
RestoreFailure::Rebase(detail) => Failure::new("rebase_failed", detail),
})
.and_then(|restore| to_value(&restore))
}
/// The input is the attachment's JSON as the byte scan read it (any shape).
fn archive_import(sheet: &LoadedSheet, input: &str) -> Outcome {
session::import_archive(sheet, input)
.map_err(|failure| match failure {
ImportFailure::IncompatibleVersion(found) => {
versioned("incompatible_version", Some(found))
}
ImportFailure::NoAttachment => Failure::new("no_attachment", ""),
ImportFailure::Invalid(detail) => Failure::new("invalid", detail),
})
.and_then(|import| to_value(&import))
}
fn archive_snapshot(sheet: &LoadedSheet, input: &str) -> Outcome {
let input: SnapshotInput = parse_input(input)?;
to_value(&build_sheet_snapshot(sheet, &input.report))
}