feat(pdf): archive check tool pnpm report:compare (attachment vs its v3 reading, unresolved items flagged, --diff/--summary/--identity); readAttachedDocument split out of extractReportJson; stale scaffold:species script removed; docs

This commit is contained in:
bchanot committed 2026-10-10 15:44:20 +02:00
1 parent 1e0491f3bc
commit dc78a00835
13 files changed
+753 -37

No files matched your search

+3 -1
View File
@@ -11,7 +11,8 @@
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0"
"lint": "eslint . --max-warnings 0",
"report:compare": "tsx scripts/compare-reports.ts"
},
"dependencies": {
"@faunosteo/anatomy": "workspace:*",
@@ -39,6 +40,7 @@
"eslint-plugin-react-hooks": "^5.1.0",
"globals": "^15.14.0",
"happy-dom": "^20.10.6",
"tsx": "^4.23.15",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vite": "^7.3.6",
+135
View File
@@ -0,0 +1,135 @@
/**
* Archive check: reads the report attached to one or more Faunosteo PDFs and
* prints it next to its v3 reading on the bundled reference sheet.
*
* pnpm report:compare <file.pdf | folder>... [--summary] [--identity]
* [--locale fr|en] [--diff a.pdf b.pdf]
*
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
* is checked against the sheet. Items the sheet cannot place are marked
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
* PDFs (an archive and its re-export after import, typically). Names are
* printed only with `--identity`. Reads only; never writes a file.
*/
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PDFDocument } from 'pdf-lib'
import {
readReportDocument,
REPORT_VERSION,
UnsupportedReportVersionError,
} from '@faunosteo/domain'
import { readAttachedDocument } from '../src/pdf/attachment'
import { MAX_PDF_BYTES } from '../src/pdf/import'
import { parseBundledSheet } from '../src/sheets/provider'
import { buildSheetIndex, type SheetIndex } from '../src/services/sheetIndex'
import {
compareReport,
diffLines,
parseArgs,
renderComparison,
renderSummary,
type CliArgs,
type Comparison,
} from './compare/report'
const SEED_DIR = resolve(
fileURLToPath(import.meta.url),
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
const CWD = process.env.INIT_CWD ?? process.cwd()
function loadSheet(): SheetIndex {
const json = (name: string) =>
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
// The comparison needs the document and the map, not the drawings.
return buildSheetIndex(
parseBundledSheet({
status: 'draft',
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
assets: {},
}),
)
}
function expandFiles(args: string[]): string[] {
const out: string[] = []
for (const arg of args) {
const path = resolve(CWD, arg)
if (statSync(path).isDirectory()) {
const pdfs = readdirSync(path)
.filter((f) => f.toLowerCase().endsWith('.pdf'))
.sort()
out.push(...pdfs.map((f) => join(path, f)))
} else out.push(path)
}
return out
}
async function compareFile(
path: string,
sheet: SheetIndex,
args: CliArgs,
): Promise<Comparison> {
const bytes = new Uint8Array(readFileSync(path))
if (bytes.byteLength > MAX_PDF_BYTES) throw new Error('file too large')
const pdf = await PDFDocument.load(bytes, { ignoreEncryption: true })
const raw = await readAttachedDocument(pdf)
const version = (raw as { version: number }).version
try {
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, version !== REPORT_VERSION, sheet, args)
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new Error(`report version ${version} cannot be read`)
}
throw err
}
}
async function main(argv: string[]): Promise<number> {
const args = parseArgs(argv)
const files = expandFiles(args.files)
if (files.length === 0 || (args.diff && files.length !== 2)) {
console.error(
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--identity] [--locale fr|en] [--diff a.pdf b.pdf]',
)
return 1
}
const sheet = loadSheet()
const results: Comparison[] = []
let failures = 0
for (const file of files) {
const name = basename(file)
try {
const c = await compareFile(file, sheet, args)
results.push(c)
if (!args.diff) {
const lines = args.summary
? [renderSummary(name, c)]
: [...renderComparison(name, c), '']
console.log(lines.join('\n'))
}
} catch (err) {
failures += 1
console.log(`!! ${name}: ${err instanceof Error ? err.message : err}`)
}
}
if (args.diff && results.length === 2) {
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
}
return failures ? 2 : 0
}
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(err) => {
console.error(err instanceof Error ? err.message : err)
process.exit(1)
},
)
+330
View File
@@ -0,0 +1,330 @@
import {
ReportV2Schema,
findingPathKey,
type Finding,
type FindingV2,
type MigrationOutcome,
type ObservationZoneV2,
type Report,
type ReportZone,
} from '@faunosteo/domain'
import type { Locale } from '../../src/i18n/types'
import { pickLabel, type SheetIndex } from '../../src/services/sheetIndex'
/**
* Pure comparison of a report document found in a PDF with its v3 reading:
* a v2 archive is shown legacy id → canonical id line by line, a v3 report
* is checked against the bundled sheet. Every item the sheet cannot place is
* marked `!! UNRESOLVED` with the reason, nothing is summarised away.
*/
export const UNRESOLVED = '!! UNRESOLVED'
export interface CompareOptions {
locale: Locale
/** Print practitioner, animal and owner names (off by default). */
identity: boolean
}
export interface Comparison {
/** `v2` when the attachment was migrated, `v3` when read as is. */
source: 'v2' | 'v3'
header: string[]
observations: string[][]
footer: string[]
/** Lines in the v3 vocabulary only, for `--diff` between two PDFs. */
normalized: string[]
counts: Counts
}
export interface Counts {
observations: number
zones: number
unresolvedZones: number
findings: number
unresolvedFindings: number
}
const q = (text: string) => `"${text}"`
function zoneRef(z: { annotationId: string; viewId: string; side?: string }) {
return `${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`
}
function findingRef(f: { findingZoneId: string; path: readonly string[] }) {
return findingPathKey(f.findingZoneId, f.path)
}
function vertebraeOf(z: { vertebrae?: { region: string; index: number }[] }) {
return z.vertebrae?.length
? ` [${z.vertebrae.map((v) => `${v.region}${v.index}`).join(', ')}]`
: ''
}
/** A v3 zone against the sheet: current label, or why it cannot be shown. */
function describeZone(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const ref = `${zoneRef(z)}${vertebraeOf(z)}`
const anno = sheet.annotation(z.annotationId)
if (z.unresolved) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} ${UNRESOLVED} legacy zone kept from the archive`
}
if (!anno || anno.view_id !== z.viewId) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} !! not in the sheet (unflagged)`
}
return `${ref} ${q(pickLabel(sheet.name(anno), locale))}`
}
/** A v3 finding against the sheet: current label, or why it cannot be shown. */
function describeFinding(
f: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const snapshot = q(locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot)
const vet = f.requiresVetReferral ? ' (!)' : ''
const side = f.side ? ` ${f.side}` : ''
const ref = `${findingRef(f)}${side}${vet}`
if (f.unresolved) {
return `${ref} ${snapshot} ${UNRESOLVED} kept with its snapshot`
}
const node = sheet.nodeAt(f.findingZoneId, f.path)
if (!node) return `${ref} ${snapshot} !! not in the sheet (unflagged)`
if (node.children.length > 0) {
return `${ref} ${snapshot} !! points at a category, not a leaf`
}
return `${ref} ${q(pickLabel(node.name, locale))}`
}
/** Legacy zone → migrated zone. */
function describeZoneMigration(
legacy: ObservationZoneV2,
out: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const side = legacy.side ? ` ${legacy.side}` : ''
const from = `${legacy.boneId}${legacy.detailSourceId ? '@' + legacy.detailSourceId : ''}${side}${vertebraeOf(legacy)}`
if (out.unresolved) {
return `${from} ${UNRESOLVED} unknown legacy id, kept as ${zoneRef(out)}`
}
const anno = sheet.annotation(out.annotationId)
const label = anno ? q(pickLabel(sheet.name(anno), locale)) : '!! missing'
return `${from} ${q(out.labelFrSnapshot ?? '')} → ${zoneRef(out)} ${label}`
}
/** Legacy finding → migrated finding, with the fate the map decided. */
function describeFindingMigration(
legacy: FindingV2,
out: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const map = sheet.sheet.migrationMap.finding_paths
const vet = legacy.requiresVetReferral ? ' (!)' : ''
const key = `${findingPathKey(legacy.zoneId, legacy.path)}${vet}`
const snapshot = q(
locale === 'en' ? legacy.labelEnSnapshot : legacy.labelFrSnapshot,
)
if (out.unresolved) {
const why = Object.hasOwn(map, findingPathKey(legacy.zoneId, legacy.path))
? 'removed from the sheet, kept with its label'
: 'never in the legacy catalog, kept with its label'
return `${key} ${snapshot} ${UNRESOLVED} ${why}`
}
const node = sheet.nodeAt(out.findingZoneId, out.path)
const label = node ? q(pickLabel(node.name, locale)) : '!! missing'
const target =
findingRef(out) === findingPathKey(legacy.zoneId, legacy.path)
? 'same'
: findingRef(out)
return `${key} ${snapshot} → ${target} ${label}`
}
function observationLines(
obs: Report['observations'][number],
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const lines = [
`[${obs.id}] severity ${obs.severity ?? 'none'}`,
...obs.zones.map((z) => `zone ${describeZone(z, sheet, opts.locale)}`),
...obs.findings.map(
(f) => `finding ${describeFinding(f, sheet, opts.locale)}`,
),
...obs.freeTextFindings.map((t) => `text ${q(t)}`),
]
if (obs.comment) lines.push(`comment ${q(obs.comment)}`)
return lines
}
function migratedObservationLines(
raw: unknown,
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[][] {
const v2 = ReportV2Schema.parse(raw)
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
? `${legacy.severity} → ${out.severity}`
: 'none'
const lines = [`[${legacy.id}] severity ${severity}`]
legacy.zones.forEach((z, j) => {
const line = describeZoneMigration(z, out.zones[j]!, sheet, opts.locale)
lines.push(`zone ${line}`)
})
legacy.findings.forEach((f, j) => {
const line = describeFindingMigration(
f,
out.findings[j]!,
sheet,
opts.locale,
)
lines.push(`finding ${line}`)
})
lines.push(...legacy.freeTextFindings.map((t) => `text ${q(t)}`))
if (legacy.comment) lines.push(`comment ${q(legacy.comment)}`)
return lines
})
}
function countsOf(report: Report): Counts {
const zones = report.observations.flatMap((o) => o.zones)
const findings = report.observations.flatMap((o) => o.findings)
return {
observations: report.observations.length,
zones: zones.length,
unresolvedZones: zones.filter((z) => z.unresolved).length,
findings: findings.length,
unresolvedFindings: findings.filter((f) => f.unresolved).length,
}
}
function headerLines(
source: 'v2' | 'v3',
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const ref = sheet.sheet.ref
const sameSheet =
report.sheet.sheetId === ref.sheetId &&
report.sheet.documentSha256 === ref.documentSha256
const sheetLine = sameSheet
? `sheet ${ref.sheetId} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${report.sheet.sheetId} !! written on another sheet document (sha ${report.sheet.documentSha256.slice(0, 12)}…)`
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
sheetLine,
`id ${report.id} · date ${report.date} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
if (opts.identity) {
lines.push(
`practitioner ${q(report.practitioner.name)} · animal ${q(report.animal.name)} · owner ${q(report.owner.name)}`,
)
}
return lines
}
function footerLines(report: Report): string[] {
const lines: string[] = []
if (report.conclusion) lines.push(`conclusion ${q(report.conclusion)}`)
if (report.recommendations) {
lines.push(`recommendations ${q(report.recommendations)}`)
}
if (report.nextAppointment) {
lines.push(`next appointment ${JSON.stringify(report.nextAppointment)}`)
}
return lines
}
/**
* `raw` is the attachment as found in the PDF, `outcome` its v3 reading
* (`readReportDocument`); `migrated` tells which vocabulary the lines use.
*/
export function compareReport(
raw: unknown,
outcome: MigrationOutcome,
migrated: boolean,
sheet: SheetIndex,
opts: CompareOptions,
): Comparison {
const { report } = outcome
const source = migrated ? 'v2' : 'v3'
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
)
return {
source,
header: headerLines(source, report, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
footer: footerLines(report),
normalized: [...v3Lines.flat(), ...footerLines(report)],
counts: countsOf(report),
}
}
export function renderComparison(name: string, c: Comparison): string[] {
return [
`== ${name}`,
...c.header.map((l) => ` ${l}`),
...c.observations.flatMap((lines) =>
lines.map((l, i) => (i === 0 ? ` ${l}` : ` ${l}`)),
),
...c.footer.map((l) => ` ${l}`),
]
}
export function renderSummary(name: string, c: Comparison): string {
const n = c.counts
return `${name} · ${c.source === 'v2' ? 'v2→v3' : 'v3'} · ${n.observations} obs · zones ${n.zones}/${n.unresolvedZones} unresolved · findings ${n.findings}/${n.unresolvedFindings} unresolved`
}
/** Lines of A absent from B and lines of B absent from A, in order. */
export function diffLines(a: string[], b: string[]): string[] {
const inB = new Set(b)
const inA = new Set(a)
return [
...a.filter((l) => !inB.has(l)).map((l) => `- ${l}`),
...b.filter((l) => !inA.has(l)).map((l) => `+ ${l}`),
]
}
export interface CliArgs extends CompareOptions {
files: string[]
summary: boolean
diff: boolean
}
export function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
files: [],
locale: 'fr',
identity: false,
summary: false,
diff: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]!
if (arg === '--identity') args.identity = true
else if (arg === '--summary') args.summary = true
else if (arg === '--diff') args.diff = true
else if (arg === '--locale') {
const value = argv[++i]
if (value !== 'fr' && value !== 'en') {
throw new Error('--locale takes fr or en')
}
args.locale = value
} else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)
else args.files.push(arg)
}
return args
}
+41 -29
View File
@@ -43,10 +43,45 @@ export interface ExtractedReport extends MigrationOutcome {
migrated: boolean
}
/**
* The raw report document carried by the PDF, of whatever version, before
* any migration: what the archive check tool shows next to the v3 result.
* Throws when the PDF carries no Faunosteo attachment or an oversized one.
*/
export async function readAttachedDocument(
pdfDoc: PDFDocument,
): Promise<unknown> {
const bytes = await attachmentBytes(pdfDoc)
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment too large')
}
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (versionOf(data) === null) {
throw new Error('attachment carries no report version')
}
return data
}
export async function extractReportJson(
pdfDoc: PDFDocument,
map: ReportMigrationMap,
): Promise<ExtractedReport> {
const data = await readAttachedDocument(pdfDoc)
try {
return {
...readReportDocument(data, map),
migrated: versionOf(data) !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
}
async function attachmentBytes(pdfDoc: PDFDocument): Promise<Uint8Array> {
const maybeApi = pdfDoc as unknown as {
getAttachments?: () => Array<{ name: string; data: Uint8Array }>
}
@@ -57,44 +92,21 @@ export async function extractReportJson(
list.find(
(a) => a.name.startsWith('osteo-report') && a.name.endsWith('.json'),
) ?? list[0]
return parseAttachment(hit.data, map)
return hit.data
}
}
const fallback = await traverseForJsonAttachment(pdfDoc)
if (!fallback) throw new Error('No osteo-report attachment found')
return parseAttachment(fallback, map)
return fallback
}
/** Hard ceiling on an attachment (inflated or not): a report is a few hundred KB at most. */
const MAX_ATTACHMENT_BYTES = 16 * 1024 * 1024
function parseAttachment(
bytes: Uint8Array,
map: ReportMigrationMap,
): ExtractedReport {
if (bytes.byteLength > MAX_ATTACHMENT_BYTES) {
throw new Error('attachment too large')
}
const data: unknown = JSON.parse(new TextDecoder().decode(bytes))
const version =
data !== null &&
typeof data === 'object' &&
typeof (data as { version?: unknown }).version === 'number'
? (data as { version: number }).version
: null
// No numeric version at all: not a Faunosteo attachment (legacy message), not an old one.
if (version === null) throw new Error('attachment carries no report version')
try {
return {
...readReportDocument(data, map),
migrated: version !== REPORT_VERSION,
}
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
throw new IncompatibleReportVersionError(err.foundVersion)
}
throw err
}
function versionOf(data: unknown): number | null {
if (data === null || typeof data !== 'object') return null
const v = (data as { version?: unknown }).version
return typeof v === 'number' ? v : null
}
interface RawObj {
+203
View File
@@ -0,0 +1,203 @@
/**
* The archive check tool (scripts/compare-reports.ts) on the frozen v2 PDF,
* on a synthetic v2 report with removed and unknown items, and on a v3 report.
*/
import { describe, it, expect, beforeAll } from 'vitest'
import { PDFDocument } from 'pdf-lib'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, resolve } from 'node:path'
import { readReportDocument, type ReportV2 } from '@faunosteo/domain'
import { readAttachedDocument } from '@/pdf/attachment'
import type { SheetIndex } from '@/services/sheetIndex'
import {
compareReport,
diffLines,
parseArgs,
renderComparison,
renderSummary,
UNRESOLVED,
} from '../../scripts/compare/report'
import { loadTestSheet, minimalReport } from '../helpers/sheet'
const HERE = dirname(fileURLToPath(import.meta.url))
const OPTS = { locale: 'fr' as const, identity: false }
let sheet: SheetIndex
function minimalV2(): ReportV2 {
return JSON.parse(
readFileSync(resolve(HERE, '../fixtures/report-v2.minimal.json'), 'utf8'),
) as ReportV2
}
function compareRaw(raw: unknown, identity = false) {
const outcome = readReportDocument(raw, sheet.sheet.migrationMap)
const migrated = (raw as { version: number }).version !== 3
return compareReport(raw, outcome, migrated, sheet, { ...OPTS, identity })
}
beforeAll(async () => {
sheet = await loadTestSheet()
})
describe('compareReport on the frozen v2 archive PDF', () => {
it('shows every legacy zone and finding next to its canonical target', async () => {
const bytes = readFileSync(resolve(HERE, '../fixtures/report-v2.full.pdf'))
const pdf = await PDFDocument.load(new Uint8Array(bytes))
const raw = await readAttachedDocument(pdf)
const c = compareRaw(raw)
const lines = renderComparison('full.pdf', c)
expect(c.source).toBe('v2')
expect(lines[0]).toBe('== full.pdf')
expect(lines).toContain(' v2 → v3 (migrated)')
expect(lines.join('\n')).toContain(
'point-mpbwtst0 left "Hanche (coxo-fémorale)" → hip@main left "Hanche (coxo-fémorale)"',
)
expect(lines.join('\n')).toContain(
'cervical/cervical-observations/stumbling-proprioceptive (!) "Trébuchements / déficit proprioceptif rapporté" → cervical/cervical-consultation-reasons/stumbling-proprioceptive',
)
expect(lines.join('\n')).toContain('severity modérée → moderate')
expect(lines.some((l) => l.includes(UNRESOLVED))).toBe(false)
expect(c.counts).toEqual({
observations: 3,
zones: 5,
unresolvedZones: 0,
findings: 4,
unresolvedFindings: 0,
})
expect(renderSummary('full.pdf', c)).toBe(
'full.pdf · v2→v3 · 3 obs · zones 5/0 unresolved · findings 4/0 unresolved',
)
expect(lines.join('\n')).not.toContain('practitioner')
expect(renderComparison('x', compareRaw(raw, true)).join('\n')).toContain(
'practitioner "Dr. Claire Dupont"',
)
})
})
describe('compareReport on unresolved items', () => {
it('names a removed finding, a finding unknown to the catalog and an unknown zone', () => {
const v2: ReportV2 = {
...minimalV2(),
observations: [
{
id: 'o',
zones: [{ boneId: 'point-gone' }],
findings: [
{
zoneId: 'ssb',
path: ['ssb-dysfunctions', 'sutures', 'sphenozygomatic'],
labelFrSnapshot: 'Suture sphéno-zygomatique',
labelEnSnapshot: 'Sphenozygomatic suture',
requiresVetReferral: true,
},
{
zoneId: 'nowhere',
path: ['x'],
labelFrSnapshot: 'X',
labelEnSnapshot: 'X',
},
],
freeTextFindings: [],
comment: '',
},
],
}
const text = renderComparison('odd.pdf', compareRaw(v2)).join('\n')
expect(text).toContain(
`point-gone ${UNRESOLVED} unknown legacy id, kept as point-gone@main`,
)
expect(text).toContain(
`ssb/ssb-dysfunctions/sutures/sphenozygomatic (!) "Suture sphéno-zygomatique" ${UNRESOLVED} removed from the sheet, kept with its label`,
)
expect(text).toContain(
`nowhere/x "X" ${UNRESOLVED} never in the legacy catalog, kept with its label`,
)
expect(text).toContain('1 zones (1 unresolved) · 2 findings (2 unresolved)')
})
it('reads a v3 report as is and flags what the sheet cannot place', () => {
const report = minimalReport(sheet, {
observations: [
{
id: 'o3',
zones: [{ annotationId: 'hip', viewId: 'main', side: 'left' }],
findings: [
{
findingZoneId: 'hip',
path: ['hip-dysfunctions', 'articular', 'restriction-flexion'],
labelFrSnapshot: 'Restriction en flexion',
labelEnSnapshot: 'Flexion restriction',
},
{
findingZoneId: 'atm',
path: ['atm-observations', 'headshaking'],
labelFrSnapshot: 'Headshaking (secouement de tête)',
labelEnSnapshot: 'Headshaking',
unresolved: true,
},
{
findingZoneId: 'hip',
path: ['hip-dysfunctions'],
labelFrSnapshot: 'Catégorie',
labelEnSnapshot: 'Category',
},
],
freeTextFindings: [],
comment: '',
},
],
})
const c = compareRaw(report)
const text = renderComparison('v3.pdf', c).join('\n')
expect(c.source).toBe('v3')
expect(text).toContain('v3 (read as is)')
expect(text).toContain('hip@main left "Hanche (coxo-fémorale)"')
expect(text).toContain(
'hip/hip-dysfunctions/articular/restriction-flexion "Restriction en flexion"',
)
expect(text).toContain(
`atm/atm-observations/headshaking "Headshaking (secouement de tête)" ${UNRESOLVED} kept with its snapshot`,
)
expect(text).toContain('!! points at a category, not a leaf')
expect(c.counts.unresolvedFindings).toBe(1)
})
it('warns when a v3 report was written on another sheet document', () => {
const report = minimalReport(sheet, {
sheet: { ...sheet.sheet.ref, documentSha256: 'b'.repeat(64) },
})
const text = renderComparison('other.pdf', compareRaw(report)).join('\n')
expect(text).toContain(
'!! written on another sheet document (sha bbbbbbbbbbbb…)',
)
})
})
describe('diff and arguments', () => {
it('diffs the v3 content of a migrated v2 report and its v3 re-reading', () => {
const v2 = minimalV2()
const migrated = readReportDocument(v2, sheet.sheet.migrationMap).report
const a = compareRaw(v2)
const b = compareRaw(migrated)
expect(diffLines(a.normalized, b.normalized)).toEqual([])
const edited = { ...migrated, conclusion: 'changed' }
expect(diffLines(a.normalized, compareRaw(edited).normalized)).toEqual([
'+ conclusion "changed"',
])
})
it('parses files and options, refuses unknown ones', () => {
expect(parseArgs(['a.pdf', '--summary', 'dir', '--locale', 'en'])).toEqual({
files: ['a.pdf', 'dir'],
locale: 'en',
identity: false,
summary: true,
diff: false,
})
expect(parseArgs(['--identity', '--diff', 'a', 'b']).identity).toBe(true)
expect(() => parseArgs(['--locale', 'de'])).toThrow('fr or en')
expect(() => parseArgs(['--json'])).toThrow('unknown option')
})
})
+1 -1
View File
@@ -23,6 +23,6 @@
"outDir": "dist",
"composite": false
},
"include": ["src", "tests"],
"include": ["src", "tests", "scripts"],
"exclude": ["node_modules", "dist"]
}