Files
faunosteo/packages/anatomy/src/legacy/catalog.ts
T

250 lines
7.0 KiB
TypeScript

import type {
FindingCategoryKind,
FindingNodeInput,
LocalizedOptionalText,
} from '@faunosteo/domain'
import { isStableId, slugify } from './ids'
import type { Anomaly, ZoneStats } from './types'
/**
* Legacy findings catalog (pathologies.json, schema 2.0) → canonical
* finding zones in the lean authoring form: optional keys are written only
* when the source carries them, so the document stays as small as the
* catalog and the parser fills the defaults.
*/
export interface LegacyNode {
id: string
name_fr: string
name_en: string
description_fr?: string
description_en?: string
requires_vet_referral?: boolean
/** Inline citations of the legacy format; none exist, see importer guard. */
sources?: unknown[]
children?: LegacyNode[]
}
export interface LegacyZone {
id: string
name_fr: string
name_en: string
categories: LegacyNode[]
}
export interface LegacyCatalog {
schema_version: string
scope_disclaimer?: string
species?: { id: string; name_fr: string; name_en: string }
zones: Record<string, LegacyZone>
}
export interface CategoryInput {
id: string
kind: FindingCategoryKind
name: { fr: string; en: string }
description?: LocalizedOptionalText
children: FindingNodeInput[]
}
export interface ZoneInput {
id: string
name: { fr: string; en: string }
categories: CategoryInput[]
}
export interface MappedCatalog {
zones: ZoneInput[]
zoneStats: ZoneStats[]
nodeIdMap: Record<string, string>
missingDescriptionEn: number
sources: number
anomalies: Anomaly[]
}
/** Mutable tallies of one catalog walk; never shared between runs. */
interface WalkState {
nodeIdMap: Record<string, string>
anomalies: Anomaly[]
missingDescriptionEn: number
sources: number
}
export function parseLegacyCatalog(json: string): LegacyCatalog {
const catalog = JSON.parse(json) as LegacyCatalog
if (typeof catalog?.zones !== 'object' || catalog.zones === null) {
throw new Error('pathologies.json: "zones" object missing')
}
return catalog
}
export function categoryKind(categoryId: string): FindingCategoryKind {
if (categoryId.endsWith('-dysfunctions')) return 'dysfunction'
if (categoryId.endsWith('-observations')) return 'consultation_reason'
if (categoryId === 'anamnesis') return 'anamnesis'
return 'custom'
}
function description(node: LegacyNode): LocalizedOptionalText | undefined {
if (node.description_fr === undefined && node.description_en === undefined) {
return undefined
}
const text: LocalizedOptionalText = {}
if (node.description_fr !== undefined) text.fr = node.description_fr
if (node.description_en !== undefined) text.en = node.description_en
return text
}
function stableNodeId(id: string, path: string[], state: WalkState): string {
if (isStableId(id)) return id
const next = slugify(id) || 'node'
const key = [...path, id].join('/')
state.nodeIdMap[key] = next
state.anomalies.push({
code: 'finding.id.slugified',
level: 'a_valider',
subject: key,
message: `Identifiant hors motif stable, remplacé par « ${next} ».`,
})
return next
}
function tallyNode(node: LegacyNode, state: WalkState): void {
if (node.description_fr !== undefined && node.description_en === undefined) {
state.missingDescriptionEn += 1
}
state.sources += node.sources?.length ?? 0
}
function mapNode(
node: LegacyNode,
path: string[],
state: WalkState,
): FindingNodeInput {
tallyNode(node, state)
const id = stableNodeId(node.id, path, state)
const out: FindingNodeInput = {
id,
name: { fr: node.name_fr, en: node.name_en },
}
const text = description(node)
if (text) out.description = text
if (node.requires_vet_referral === true) out.requires_vet_referral = true
if (node.children) {
out.children = node.children.map((c) =>
mapNode(c, [...path, node.id], state),
)
}
return out
}
function mapCategory(
zoneId: string,
category: LegacyNode,
state: WalkState,
): CategoryInput {
tallyNode(category, state)
const kind = categoryKind(category.id)
if (kind === 'custom') {
state.anomalies.push({
code: 'finding.category.kind_unknown',
level: 'a_valider',
subject: `${zoneId}/${category.id}`,
message: 'Type de catégorie non reconnu, importé en « custom ».',
})
}
const path = [zoneId, category.id]
const out: CategoryInput = {
id: stableNodeId(category.id, [zoneId], state),
kind,
name: { fr: category.name_fr, en: category.name_en },
children: (category.children ?? []).map((c) => mapNode(c, path, state)),
}
const text = description(category)
if (text) out.description = text
return out
}
/** Counts categories as nodes, as the audit does (792 = 78 + 714). */
export function countTree(
nodes: ReadonlyArray<LegacyNode | FindingNodeInput>,
): TreeCounts {
let total = { nodes: 0, leaves: 0, vetReferrals: 0 }
for (const node of nodes) {
const children = node.children ?? []
const sub = countTree(children)
total = {
nodes: total.nodes + 1 + sub.nodes,
leaves: total.leaves + sub.leaves + (children.length === 0 ? 1 : 0),
vetReferrals:
total.vetReferrals +
sub.vetReferrals +
(node.requires_vet_referral ? 1 : 0),
}
}
return total
}
function zoneStatsOf(zone: LegacyZone): ZoneStats {
const counts = countTree(zone.categories)
const categoryLeaves = zone.categories.filter((c) => !c.children?.length)
return {
zoneId: zone.id,
nodes: counts.nodes,
leaves: counts.leaves - categoryLeaves.length,
vetReferrals: counts.vetReferrals,
}
}
export interface TreeCounts {
nodes: number
leaves: number
vetReferrals: number
}
/** Throws when the output tree does not hold exactly the input tree. */
export function assertNothingDropped(
zoneId: string,
before: TreeCounts,
after: TreeCounts,
): void {
const keys = ['nodes', 'leaves', 'vetReferrals'] as const
const diff = keys.filter((key) => before[key] !== after[key])
if (diff.length === 0) return
const detail = diff.map((k) => `${k} ${before[k]} in, ${after[k]} out`)
throw new Error(`zone ${zoneId}: ${detail.join('; ')}`)
}
function mapZone(key: string, zone: LegacyZone, state: WalkState): ZoneInput {
if (zone.id !== key) throw new Error(`zone key ${key} ≠ id ${zone.id}`)
const mapped: ZoneInput = {
id: key,
name: { fr: zone.name_fr, en: zone.name_en },
categories: zone.categories.map((c) => mapCategory(key, c, state)),
}
assertNothingDropped(
key,
countTree(zone.categories),
countTree(mapped.categories),
)
return mapped
}
export function mapCatalog(catalog: LegacyCatalog): MappedCatalog {
const state: WalkState = {
nodeIdMap: {},
anomalies: [],
missingDescriptionEn: 0,
sources: 0,
}
const entries = Object.entries(catalog.zones)
return {
zones: entries.map(([key, zone]) => mapZone(key, zone, state)),
zoneStats: entries.map(([, zone]) => zoneStatsOf(zone)),
nodeIdMap: state.nodeIdMap,
missingDescriptionEn: state.missingDescriptionEn,
sources: state.sources,
anomalies: state.anomalies,
}
}