diff --git a/src/state/practitionerCache.ts b/src/state/practitionerCache.ts index d74afb0b..81f992aa 100644 --- a/src/state/practitionerCache.ts +++ b/src/state/practitionerCache.ts @@ -1,28 +1,29 @@ -import type { Practitioner } from '@/domain/schema/practitioner' +import { + PractitionerSchema, + type Practitioner, +} from '@/domain/schema/practitioner' const STORAGE_KEY = 'osteo:lastPractitioner' -/** - * Reads the last-used practitioner block from localStorage. - * Returns undefined if no cache entry exists or data is invalid. - */ export function readCachedPractitioner(): Practitioner | undefined { - throw new Error('not implemented') -} - -/** - * Writes the practitioner block to localStorage for prefill on next session. - * Silently no-ops if localStorage is unavailable. - */ -export function writeCachedPractitioner(_practitioner: Practitioner): void { - throw new Error('not implemented') -} - -/** - * Clears the practitioner cache from localStorage. - */ -export function clearPractitionerCache(): void { - if (typeof localStorage !== 'undefined') { - localStorage.removeItem(STORAGE_KEY) + if (typeof localStorage === 'undefined') return undefined + const raw = localStorage.getItem(STORAGE_KEY) + if (!raw) return undefined + try { + const data = JSON.parse(raw) + const parsed = PractitionerSchema.safeParse(data) + return parsed.success ? parsed.data : undefined + } catch { + return undefined } } + +export function writeCachedPractitioner(practitioner: Practitioner): void { + if (typeof localStorage === 'undefined') return + localStorage.setItem(STORAGE_KEY, JSON.stringify(practitioner)) +} + +export function clearPractitionerCache(): void { + if (typeof localStorage === 'undefined') return + localStorage.removeItem(STORAGE_KEY) +} diff --git a/tests/unit/state.practitionerCache.test.ts b/tests/unit/state.practitionerCache.test.ts new file mode 100644 index 00000000..1cb7a5ca --- /dev/null +++ b/tests/unit/state.practitionerCache.test.ts @@ -0,0 +1,33 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { + readCachedPractitioner, + writeCachedPractitioner, + clearPractitionerCache, +} from '@/state/practitionerCache' + +beforeEach(() => localStorage.clear()) + +describe('practitionerCache', () => { + it('returns undefined when empty', () => { + expect(readCachedPractitioner()).toBeUndefined() + }) + + it('round-trips a valid practitioner', () => { + writeCachedPractitioner({ name: 'Dr. Dupont', cabinet: 'Clinic A' }) + expect(readCachedPractitioner()).toEqual({ + name: 'Dr. Dupont', + cabinet: 'Clinic A', + }) + }) + + it('returns undefined on malformed JSON', () => { + localStorage.setItem('osteo:lastPractitioner', 'not-json') + expect(readCachedPractitioner()).toBeUndefined() + }) + + it('clear removes the entry', () => { + writeCachedPractitioner({ name: 'Dr. Dupont' }) + clearPractitionerCache() + expect(readCachedPractitioner()).toBeUndefined() + }) +})