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

+243
View File
@@ -0,0 +1,243 @@
//! Fixtures of the report and archive suites ported from `packages/domain/tests`: the committed
//! equine draft as the application bundles it, the horse slice, the legacy leaves, the sample
//! branding and labels.
#![allow(
dead_code,
clippy::disallowed_methods,
clippy::unwrap_used,
clippy::expect_used
)]
use faunosteo_core::domain::archive::{PDF_LABEL_KEYS, PdfLabelSet};
use faunosteo_core::domain::js::parse_json;
use faunosteo_core::domain::report::v2::ReportV2;
use faunosteo_core::domain::report::{Report, ReportMigrationMap};
use faunosteo_core::domain::sheet::{
AnatomicalSheetDocument, BundledSheetData, FindingNode, LoadedSheet,
};
use serde_json::{Map, Value, json};
use super::common::repo_file;
pub const DRAFT_DIR: &str = "supabase/seed/anatomical-sheets/equine/draft";
pub const HORSE_MAIN_ASSET_ID: &str = "3f6c1b52-8a4e-4d17-9b0c-5e2a7d91c4f8";
pub fn json_file(relative: &str) -> Value {
parse_json(&repo_file(relative)).unwrap()
}
pub fn from<T: serde::de::DeserializeOwned>(value: Value) -> T {
serde_json::from_value(value).unwrap()
}
pub fn to_value<T: serde::Serialize>(value: &T) -> Value {
serde_json::to_value(value).unwrap()
}
/// A loaded sheet from its parts (the bundled payload shape).
pub fn loaded(
reference: Value,
document: Value,
map: Value,
assets: Value,
hashes: Value,
) -> LoadedSheet {
let data: BundledSheetData = from(json!({
"status": "draft",
"ref": reference,
"document": document,
"migrationMap": map,
"assets": assets,
"assetHashes": hashes,
}));
LoadedSheet::from_bundle(data).unwrap()
}
/// The committed equine draft (`pnpm import:equine`) as the application bundles it.
pub fn draft_sheet() -> LoadedSheet {
let manifest = json_file(&format!("{DRAFT_DIR}/assets.json"));
let mut assets = Map::new();
let mut hashes = Map::new();
for asset in manifest.as_array().unwrap() {
let id = asset["svg_asset_id"].as_str().unwrap().to_owned();
let file = asset["file"].as_str().unwrap();
let svg = repo_file(&format!("{DRAFT_DIR}/assets/{file}"));
assets.insert(id.clone(), json!(svg));
hashes.insert(id, asset["sha256"].clone());
}
loaded(
json_file(&format!("{DRAFT_DIR}/sheet-ref.json")),
json_file(&format!("{DRAFT_DIR}/document.json")),
json_file(&format!("{DRAFT_DIR}/report-migration-map.json")),
Value::Object(assets),
Value::Object(hashes),
)
}
pub fn draft_map() -> ReportMigrationMap {
from(json_file(&format!("{DRAFT_DIR}/report-migration-map.json")))
}
/// The horse slice of `packages/domain/tests/fixtures/horse-slice.ts`, as Zod parsed it (the
/// characterisation oracle carries it, written by the TypeScript generator).
pub fn horse_slice() -> Value {
json_file("crates/core/tests/oracles/characterisation.json")["sheets"]["slice"]["document"]
.clone()
}
pub fn snake_ref(sheet_id: &str, version_id: Option<&str>, sha: &str) -> Value {
json!({
"sheet_id": sheet_id, "version_id": version_id, "document_sha256": sha,
"schema_version": 2, "species_id": "equine"
})
}
/// A loaded slice with one SVG asset (and its hash when given).
pub fn slice_sheet(
reference: Value,
document: Value,
svg: &str,
hash: Option<&str>,
) -> LoadedSheet {
let hashes = hash.map_or(json!({}), |h| json!({ HORSE_MAIN_ASSET_ID: h }));
loaded(
reference,
document,
minimal_map(),
json!({ HORSE_MAIN_ASSET_ID: svg }),
hashes,
)
}
/// A migration map no suite reads: the slices need one to load.
pub fn minimal_map() -> Value {
json!({
"schema_version": 1,
"sheet": { "sheetId": "s", "versionId": null, "documentSha256": "0".repeat(64) },
"main_view_id": "view-main", "views": {}, "annotations": {}, "finding_paths": {}
})
}
pub struct LegacyLeaf {
pub zone_id: String,
pub path: Vec<String>,
pub fr: String,
pub en: String,
pub vet: bool,
}
fn walk(zone_id: &str, nodes: &[FindingNode], prefix: &[String], out: &mut Vec<LegacyLeaf>) {
for node in nodes {
let mut path = prefix.to_vec();
path.push(node.id.clone());
if node.children.is_empty() {
out.push(LegacyLeaf {
zone_id: zone_id.to_owned(),
path,
fr: node.name.fr.clone(),
en: node.name.en.clone(),
vet: node.requires_vet_referral,
});
} else {
walk(zone_id, &node.children, &path, out);
}
}
}
/// Every leaf of the generated baseline (`legacy-import/document.json`), walked as
/// `tests/helpers/legacy-leaves.ts` does (a childless category is a leaf without a vet flag).
pub fn legacy_leaves() -> Vec<LegacyLeaf> {
let document: AnatomicalSheetDocument = from(json_file(
"supabase/seed/anatomical-sheets/equine/legacy-import/document.json",
));
let mut out = Vec::new();
for zone in &document.finding_zones {
for category in &zone.categories {
let prefix = vec![category.id.clone()];
if category.children.is_empty() {
out.push(LegacyLeaf {
zone_id: zone.id.clone(),
path: prefix,
fr: category.name.fr.clone(),
en: category.name.en.clone(),
vet: false,
});
} else {
walk(&zone.id, &category.children, &prefix, &mut out);
}
}
}
out
}
/// `leavesAsV2Report`: one observation per zone, in first-seen order.
pub fn leaves_as_v2_report(leaves: &[LegacyLeaf]) -> Value {
let mut zones: Vec<String> = Vec::new();
let mut observations: Map<String, Value> = Map::new();
for leaf in leaves {
if !zones.contains(&leaf.zone_id) {
zones.push(leaf.zone_id.clone());
let empty = json!({ "id": format!("obs-{}", leaf.zone_id), "zones": [],
"findings": [], "freeTextFindings": [], "comment": "" });
observations.insert(leaf.zone_id.clone(), empty);
}
let en = if leaf.en.is_empty() {
&leaf.fr
} else {
&leaf.en
};
let mut finding = json!({ "zoneId": leaf.zone_id, "path": leaf.path,
"labelFrSnapshot": leaf.fr, "labelEnSnapshot": en });
if leaf.vet {
finding["requiresVetReferral"] = json!(true);
}
observations[&leaf.zone_id]["findings"]
.as_array_mut()
.unwrap()
.push(finding);
}
let report = json!({
"version": 2, "id": "all-leaves", "createdAt": "2026-10-10T00:00:00Z",
"date": "2026-10-10", "practitioner": { "name": "Synthetic" },
"animal": { "speciesId": "equine", "name": "Synthetic" },
"owner": { "name": "Synthetic" },
"observations": zones.iter().map(|z| observations[z].clone()).collect::<Vec<_>>(),
"conclusion": "", "recommendations": ""
});
let _: ReportV2 = from(report.clone());
report
}
pub fn sample_branding() -> Value {
json!({
"siteUrl": "https://faunosteo.com",
"headerLogo": { "kind": "png", "base64": "iVBORw0KGgo=" },
"footerLogo": null,
"poweredBy": { "logo": null, "url": "https://zenquality.fr", "fallbackText": "zenquality.fr" },
"partner": {
"logo": { "kind": "svg", "svg": "<svg xmlns=\"http://www.w3.org/2000/svg\"/>" },
"url": "https://www.instagram.com/paws.iin.harmony",
"fallbackText": "@paws.iin.harmony"
}
})
}
/// Every key mapped to itself, in `PDF_LABEL_KEYS` order.
pub fn sample_labels() -> Value {
let mut labels = Map::new();
for key in PDF_LABEL_KEYS {
labels.insert(key.to_owned(), json!(key));
}
Value::Object(labels)
}
pub fn sample_label_set() -> Value {
let set = json!({ "fr": sample_labels(), "en": sample_labels() });
let _: PdfLabelSet = from(set.clone());
set
}
/// `JSON.parse(JSON.stringify(report))`.
pub fn report_value(report: &Report) -> Value {
to_value(report)
}