diff --git a/apps/app/src/app/routes/EditorRoute.tsx b/apps/app/src/app/routes/EditorRoute.tsx index 491ec754..c0858ea1 100644 --- a/apps/app/src/app/routes/EditorRoute.tsx +++ b/apps/app/src/app/routes/EditorRoute.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useNavigate } from 'react-router-dom' import AnatomyCanvas from '@/components/canvas/AnatomyCanvas' import DetailModal from '@/components/canvas/DetailModal' @@ -29,6 +29,7 @@ import { import type { ViewStates } from '@/anatomy/drawing' import { exportReportToPdf } from '@/pdf/export' import type { ExportWarning } from '@faunosteo/pdf' +import type { RebaseOutcome } from '@faunosteo/domain' import { useT } from '@/i18n/useT' import { DEFAULT_SPECIES_ID } from './NewReportRoute' @@ -39,6 +40,11 @@ function missingItemsOf(warnings: readonly ExportWarning[]): string[] { return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId)) } +/** Zones and findings a draft rebase could not find on the loaded sheet. */ +function unresolvedCountOf(outcome: RebaseOutcome): number { + return outcome.unresolvedZones + outcome.unresolvedFindings +} + /** Editor on the reference sheet: wires the canvas, the pickers and the store. */ export default function EditorRoute() { const navigate = useNavigate() @@ -55,18 +61,28 @@ export default function EditorRoute() { const [disclaimer, setDisclaimer] = useState(null) const [exporting, setExporting] = useState(false) const [editDraft, setEditDraft] = useState(null) + // One alert per restore, even if the effect runs again before the re-render. + const rebaseAlerted = useRef(false) useEffect(() => { window.scrollTo({ top: 0, left: 0, behavior: 'auto' }) }, []) // No report in memory: restore the per-tab draft once the sheet is known. + // A draft rebased on another sheet is announced with its unresolved count. useEffect(() => { if (report) return - if (sheet.status === 'ready') store.restoreDraft(sheet.index) + if (sheet.status === 'ready') { + const outcome = store.restoreDraft(sheet.index) + if (outcome?.rebased && !rebaseAlerted.current) { + rebaseAlerted.current = true + const count = String(unresolvedCountOf(outcome)) + window.alert(t('editor.draft_rebased').replace('{count}', count)) + } + } if (sheet.status !== 'loading' && !useReportStore.getState().report) navigate('/') - }, [report, sheet, store, navigate]) + }, [report, sheet, store, navigate, t]) useEffect(() => { if (sheet.status !== 'ready' || typeof sessionStorage === 'undefined') diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 8790af36..d7d9b327 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -68,6 +68,8 @@ export const en: Dict = { 'editor.export_failed': 'PDF generation failed. Retry or contact support.', 'editor.export_warnings': 'PDF exported with missing elements: {items}. Check the browser console.', + 'editor.draft_rebased': + 'Draft restored on an anatomical sheet different from the one it was created on. Items not found: {count} (kept with their labels).', 'editor.edit_infos': 'Edit info', 'editor.edit_dialog_title': 'Edit information', 'editor.disclaimer_title': 'Legal scope of animal osteopathy', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index ad68956e..df31e2d5 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -74,6 +74,8 @@ export const fr: Dict = { 'Échec de la génération du PDF. Réessayez ou contactez le support.', 'editor.export_warnings': 'PDF exporté avec des éléments manquants : {items}. Vérifiez la console du navigateur.', + 'editor.draft_rebased': + 'Brouillon restauré sur une fiche anatomique différente de celle où il a été créé. Éléments non retrouvés : {count} (conservés avec leurs libellés).', 'editor.edit_infos': 'Modifier les infos', 'editor.edit_dialog_title': 'Modifier les informations', 'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale", diff --git a/apps/app/tests/unit/i18n.keys.test.ts b/apps/app/tests/unit/i18n.keys.test.ts index 2c8c41a0..f4f9ab19 100644 --- a/apps/app/tests/unit/i18n.keys.test.ts +++ b/apps/app/tests/unit/i18n.keys.test.ts @@ -31,6 +31,7 @@ const PLACEHOLDERS: Record = { 'home.import.migrated': '{count}', 'home.import.rebased': '{count}', 'home.import.snapshot_rejected': '{reason}', + 'editor.draft_rebased': '{count}', 'vertebra.extend_to': '{max}', } diff --git a/apps/app/tests/unit/routes.EditorRoute.test.tsx b/apps/app/tests/unit/routes.EditorRoute.test.tsx index ba040887..2ec67c54 100644 --- a/apps/app/tests/unit/routes.EditorRoute.test.tsx +++ b/apps/app/tests/unit/routes.EditorRoute.test.tsx @@ -1,7 +1,8 @@ /** * The editor route on the bundled sheet: the click chain end to end (DOM * click on a generated marker → service → store), the detail view by its - * localized name, the sheet status line, the disclaimer once per session. + * localized name, the sheet status line, the disclaimer once per session, + * the draft restore (silent on the same sheet, one alert after a rebase). */ import { describe, @@ -40,6 +41,7 @@ beforeEach(() => { sessionStorage.clear() sessionStorage.setItem(DISCLAIMER_FLAG, '1') window.scrollTo = vi.fn() as unknown as typeof window.scrollTo + vi.stubGlobal('alert', vi.fn()) useReportStore.setState({ report: null, activeObservationIndex: 0 }) useReportStore.getState().hydrateReport( minimalReport(sheet, { @@ -58,6 +60,7 @@ beforeEach(() => { afterEach(() => { cleanup() vi.restoreAllMocks() + vi.unstubAllGlobals() }) const zonesOf = (i = 0) => @@ -199,7 +202,7 @@ describe('EditorRoute on the canonical sheet', () => { expect(sessionStorage.getItem(DISCLAIMER_FLAG)).toBe('1') }) - it('restores the per-tab draft when the store is empty, migrating a v2 one', async () => { + it('restores the per-tab draft when the store is empty, silently on the same sheet', async () => { const report = useReportStore.getState().report! useReportStore.setState({ report: null }) sessionStorage.setItem( @@ -208,5 +211,40 @@ describe('EditorRoute on the canonical sheet', () => { ) await mount() expect(useReportStore.getState().report?.id).toBe(report.id) + expect(window.alert).not.toHaveBeenCalled() + }) + + it('a draft from another sheet is rebased, its lost zone flagged, and announced once with the count', async () => { + const report = useReportStore.getState().report! + useReportStore.setState({ report: null }) + const foreign = { + ...report, + sheet: { ...report.sheet, documentSha256: '0'.repeat(64) }, + observations: [ + { + ...report.observations[0]!, + zones: [ + { + annotationId: 'ghost-zone', + viewId: 'main', + labelFrSnapshot: 'Zone disparue', + labelEnSnapshot: 'Vanished zone', + }, + ], + }, + ], + } + sessionStorage.setItem('osteo:draft', JSON.stringify(foreign)) + await mount() + const restored = useReportStore.getState().report! + expect(restored.sheet).toEqual(sheet.sheet.ref) + expect(restored.observations[0]!.zones[0]).toMatchObject({ + annotationId: 'ghost-zone', + unresolved: true, + }) + expect(window.alert).toHaveBeenCalledTimes(1) + expect(window.alert).toHaveBeenCalledWith( + fr['editor.draft_rebased'].replace('{count}', '1'), + ) }) })