feat(app): editor Vérification tab and review submission

This commit is contained in:
bchanot committed 2026-11-04 13:59:16 +01:00
1 parent 877bad0021
commit 447d0a4272
12 files changed
+987 -4

No files matched your search

@@ -380,3 +380,70 @@ Every key below is a proposal for the owner's separate review; none is declared
| `editor.annotations.geometry.unapplied_tag` | non appliqué | not applied | Marker on a field of an unapplied group | plan wording FR; EN proposal |
| `editor.annotations.geometry.revert` | Revenir aux valeurs enregistrées | Back to the saved values | Geometry group after a refusal | plan wording FR; EN proposal |
| `editor.annotations.geometry.number` | Chaque champ doit contenir un nombre. | Each field must hold a number. | Geometry group, input shape | proposal |
## Lot J (Vérification, submission)
| Key | FR | EN | Where | Origin |
|---|---|---|---|---|
| `editor.verification.title` | Contrôle du brouillon | Draft check | Panel title (L27) | L27 FR/EN |
| `editor.verification.errors` | {count} erreurs bloquantes | {count} blocking errors | Badge | L28 FR/EN |
| `editor.verification.warnings` | {count} avertissements | {count} warnings | Badge | L28 FR/EN |
| `editor.verification.to_confirm` | {count} éléments à confirmer | {count} items to confirm | Badge | L28 FR/EN |
| `editor.verification.none` | Aucun problème détecté | No issues found | Panel, no issue | L27 FR/EN |
| `editor.verification.warnings_title` | Avertissements | Warnings | Heading over the warnings | proposal |
| `editor.verification.goto` | Aller à {tab} | Go to {tab} | Issue button (tab name filled in) | plan wording « Aller à … »; form proposal |
| `editor.verification.to_confirm_info` | Des éléments restent à confirmer : cela n'empêche pas la soumission. | Some items are still to confirm: this does not prevent submission. | Info notice on to_confirm elements | proposal |
| `editor.verification.completeness` | Complétude | Completeness | Section heading | proposal |
| `editor.verification.vet_referrals` | {count} renvoi(s) vers un vétérinaire | {count} veterinary referral(s) | Completeness line | proposal |
| `editor.verification.uncited` | {count} constat(s) sans référence citée | {count} finding(s) citing no reference | Completeness line | proposal |
| `editor.verification.groups` | Statuts par groupe | Statuses per group | Section heading | proposal |
| `editor.verification.group_removed` | supprimé | removed | Group row tag | proposal |
| `editor.verification.status.to_confirm` | À confirmer | To confirm | Status count label | ratified status wording |
| `editor.verification.status.reviewed` | Relu | Reviewed | Status count label | ratified status wording |
| `editor.verification.status.inherited` | Hérité, non relu | Inherited, not reviewed | Status count label | ratified status wording |
| `editor.verification.size_title` | Taille du document | Document size | Section heading | proposal |
| `editor.verification.size` | {bytes} o sur {cap} o | {bytes} B of {cap} B | Document size against the cap | plan wording FR; EN proposal |
| `editor.verification.caps_exceeded` | Limites dépassées : {caps}. | Limits exceeded: {caps}. | Caps exceeded, named | proposal |
| `editor.verification.cap.views` | vues | views | Cap name | proposal |
| `editor.verification.cap.annotations` | annotations | annotations | Cap name | proposal |
| `editor.verification.cap.finding_nodes` | catégories et nœuds de constats | finding categories and nodes | Cap name | proposal |
| `editor.verification.cap.finding_depth` | profondeur des constats | finding depth | Cap name | proposal |
| `editor.verification.cap.label_length` | longueur des noms | name length | Cap name | proposal |
| `editor.verification.cap.drawings` | illustrations | drawings | Cap name | proposal |
| `editor.verification.cap.drawing_bytes` | taille d'une illustration | size of a drawing | Cap name | proposal |
| `editor.verification.cap.drawings_total_bytes` | taille totale des illustrations | total size of the drawings | Cap name | proposal |
| `editor.verification.cap.document_bytes` | taille du document | document size | Cap name | proposal |
| `editor.verification.note_hint` | 1 à {max} caractères. | 1 to {max} characters. | Note field hint | proposal |
| `editor.verification.note` | Note de soumission (obligatoire) | Submission note (required) | Field | plan wording FR; EN proposal |
| `editor.verification.submit_title` | Soumission | Submission | Section accessible name | proposal |
| `editor.verification.submit` | Soumettre à la revue | Submit for review | Button | plan wording FR; EN proposal |
| `editor.verification.hint.errors` | Corrigez les {count} erreurs bloquantes pour soumettre. | Fix the {count} blocking errors to submit. | Hint under the disabled button | plan wording FR; EN proposal |
| `editor.verification.hint.unsaved` | Enregistrez le brouillon avant de le soumettre. | Save the draft before submitting it. | Hint under the disabled button (unsaved or stale base) | plan wording FR; EN proposal |
| `editor.verification.hint.note` | Saisissez la note de soumission pour soumettre. | Enter the submission note to submit. | Hint under the disabled button | proposal |
| `editor.verification.issue.unknown` | Ce point ne respecte pas une règle de la fiche. Corrigez l'élément indiqué. | This item breaks a rule of the sheet. Fix the item shown. | Fallback for a code without a message | proposal |
| `editor.verification.issue.view.main.count` | La fiche doit avoir exactement une vue principale. | The sheet must have exactly one main view. | Issue | proposal |
| `editor.verification.issue.view.id.duplicate` | Deux vues ont le même identifiant. | Two views have the same id. | Issue | proposal |
| `editor.verification.issue.view.parent.missing` | Le parent de cette vue détaillée n'existe pas. | The parent of this detail view does not exist. | Issue | proposal |
| `editor.verification.issue.view.parent.cycle` | Les vues détaillées se renvoient en boucle. | The detail views refer to each other in a loop. | Issue | proposal |
| `editor.verification.issue.view.unreachable` | Aucun accès d'une annotation n'ouvre cette vue détaillée. | No link of an annotation opens this detail view. | Issue | proposal |
| `editor.verification.issue.view.asset.missing` | Cette vue n'a ni illustration ni cadrage. | This view has neither a drawing nor a crop. | Issue | proposal |
| `editor.verification.issue.view.frame.unknown` | Le cadre de cette vue est inconnu : ni cadrage ni viewBox de l'illustration utilisables. | The frame of this view is unknown: no usable crop or drawing viewBox. | Issue | proposal |
| `editor.verification.issue.annotation.id.duplicate` | Deux annotations ont le même identifiant. | Two annotations have the same id. | Issue | proposal |
| `editor.verification.issue.annotation.view.missing` | Cette annotation est placée sur une vue qui n'existe pas. | This annotation sits on a view that does not exist. | Issue | proposal |
| `editor.verification.issue.annotation.category.missing` | La catégorie de cette annotation n'existe pas. | The category of this annotation does not exist. | Issue | proposal |
| `editor.verification.issue.annotation.opens_view.invalid` | La vue ouverte par cet accès n'est pas une vue détaillée de sa propre vue. | The view this link opens is not a detail view of its own view. | Issue | proposal |
| `editor.verification.issue.annotation.finding_zone.missing` | La zone de constats de cette annotation n'existe pas. | The findings zone of this annotation does not exist. | Issue | proposal |
| `editor.verification.issue.annotation.region.missing` | La région vertébrale de cette annotation n'est pas définie. | The vertebral region of this annotation is not defined. | Issue | proposal |
| `editor.verification.issue.annotation.no_findings` | Cette annotation n'est liée à aucune zone de constats : un clic dessus ne proposera rien. | This annotation is linked to no findings zone: a click on it will offer nothing. | Warning | proposal |
| `editor.verification.issue.annotation.geometry.missing` | Cette annotation n'a pas de géométrie. | This annotation has no geometry. | Issue | proposal |
| `editor.verification.issue.annotation.geometry.out_of_frame` | Cette annotation n'est pas entièrement dans le cadre de sa vue. | This annotation is not entirely inside the frame of its view. | Issue | proposal |
| `editor.verification.issue.annotation.geometry.too_small` | Cette annotation s'affiche trop petite sur l'aperçu téléphone. | This annotation shows too small on the phone preview. | Issue | proposal |
| `editor.verification.issue.annotation.geometry.interior_too_small` | L'intérieur de cette zone est trop étroit pour être touché sur l'aperçu téléphone. | The inside of this zone is too narrow to tap on the phone preview. | Issue | proposal |
| `editor.verification.issue.region.code.duplicate` | Deux régions vertébrales ont le même code. | Two vertebral regions have the same code. | Issue | proposal |
| `editor.verification.issue.region.count_range.invalid` | Le nombre habituel de cette région n'est pas dans la variation indiquée. | The usual count of this region is outside the stated variation. | Issue | proposal |
| `editor.verification.issue.category.id.duplicate` | Deux catégories d'annotation ont le même identifiant. | Two annotation categories have the same id. | Issue | proposal |
| `editor.verification.issue.finding_zone.id.duplicate` | Deux zones de constats ont le même identifiant. | Two findings zones have the same id. | Issue | proposal |
| `editor.verification.issue.finding_zone.unreferenced` | Aucune annotation ne pointe vers cette zone de constats. | No annotation points to this findings zone. | Warning | proposal |
| `editor.verification.issue.finding.id.duplicate` | Deux constats voisins ont le même identifiant. | Two sibling findings have the same id. | Issue | proposal |
| `editor.verification.issue.finding.reference.missing` | Ce constat cite une référence qui n'est pas déclarée. | This finding cites a reference that is not declared. | Issue | proposal |
| `editor.verification.issue.reference.id.duplicate` | Deux références ont le même identifiant. | Two references have the same id. | Issue | proposal |
@@ -1,4 +1,5 @@
import { useState, type KeyboardEvent } from 'react'
import { useEditorStore } from '@/editor/state/editorStore'
import { tabsFor, type EditorTabId } from '@/editor/tabs'
import type { TabTier } from '@/editor/useViewport'
import { useT } from '@/i18n/useT'
@@ -13,6 +14,24 @@ const ACTIVE =
const IDLE =
'border-transparent text-[var(--color-ink-muted)] hover:text-[var(--color-ink)]'
/** The blocking-error count on the Vérification tab; absent at zero. */
function ErrorCount({ tab }: { tab: EditorTabId }) {
const count = useEditorStore(
(s) =>
s.previewState?.report.issues.filter((i) => i.severity === 'error')
.length ?? 0,
)
if (tab !== 'verification' || count === 0) return null
return (
<span
aria-hidden="true"
className="ml-2 rounded-md bg-red-50 px-1.5 text-xs text-red-700"
>
{count}
</span>
)
}
interface EditorTabsProps {
active: EditorTabId
tier: TabTier
@@ -70,6 +89,7 @@ export default function EditorTabs({
className={`-mb-px ${BASE} ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
<ErrorCount tab={tab} />
</button>
))}
</div>
@@ -100,6 +120,7 @@ export default function EditorTabs({
className={`rounded-md px-3 ${BASE} border-b-0 ${tab === active ? ACTIVE : IDLE}`}
>
{t(`editor.tab.${tab}`)}
<ErrorCount tab={tab} />
</button>
</li>
))}
@@ -1,14 +1,89 @@
import type {
AnatomicalSheetDocument,
SheetReport,
} from '@faunosteo/core-wasm/types'
import IssueList from '@/components/editor/verification/IssueList'
import {
Completeness,
GroupStatuses,
SizeAndCaps,
} from '@/components/editor/verification/ReviewFigures'
import SubmitPanel from '@/components/editor/verification/SubmitPanel'
import VerificationSummary from '@/components/editor/verification/VerificationSummary'
import Notice from '@/components/ui/Notice'
import { useEditorStore } from '@/editor/state/editorStore'
import { useSheetDocument } from '@/editor/sheetDocument'
import type { EditorTabProps } from '@/editor/tabs'
import { splitIssues } from '@/editor/verification'
import { useT } from '@/i18n/useT'
/** Placeholder: Lot J replaces the body and keeps the props contract (`EditorTabProps`). */
export default function VerificationTab(_props: EditorTabProps) {
interface PanelProps extends EditorTabProps {
report: SheetReport
doc: AnatomicalSheetDocument
}
function Panel({
report,
doc,
readOnly,
onSelectTab,
reloadSheet,
}: PanelProps) {
const t = useT()
const { errors, warnings } = splitIssues(report)
const { to_confirm } = report.completeness.statuses
return (
<>
<VerificationSummary
errors={errors.length}
warnings={warnings.length}
toConfirm={to_confirm}
/>
{errors.length + warnings.length === 0 && (
<Notice tone="success">{t('editor.verification.none')}</Notice>
)}
<IssueList
issues={errors}
tone="error"
doc={doc}
onSelectTab={onSelectTab}
/>
{warnings.length > 0 && (
<h3 className="text-sm font-medium">
{t('editor.verification.warnings_title')}
</h3>
)}
<IssueList
issues={warnings}
tone="info"
doc={doc}
onSelectTab={onSelectTab}
/>
{to_confirm > 0 && (
<Notice tone="info">{t('editor.verification.to_confirm_info')}</Notice>
)}
<Completeness report={report} />
<GroupStatuses report={report} doc={doc} />
<SizeAndCaps report={report} />
{!readOnly && (
<SubmitPanel errorCount={errors.length} reloadSheet={reloadSheet} />
)}
</>
)
}
/** Vérification: the in-page check of the draft (not the server's verdict) and its submission. */
export default function VerificationTab(props: EditorTabProps) {
const t = useT()
const report = useEditorStore((s) => s.previewState?.report)
const doc = useSheetDocument()
return (
<section
data-testid="editor-tab-verification"
aria-label={t('editor.tab.verification')}
className="min-h-24"
/>
className="min-h-24 space-y-4"
>
{report && doc && <Panel {...props} report={report} doc={doc} />}
</section>
)
}
@@ -0,0 +1,61 @@
import type {
AnatomicalSheetDocument,
SheetIssue,
} from '@faunosteo/core-wasm/types'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { issueMessageKey, issueTarget } from '@/editor/verification'
import type { EditorTabId } from '@/editor/tabs'
import { useT } from '@/i18n/useT'
import { useLocaleStore } from '@/state/localeStore'
interface IssueListProps {
issues: readonly SheetIssue[]
tone: 'error' | 'info'
doc: AnatomicalSheetDocument
onSelectTab: (tab: EditorTabId) => void
}
/** One notice per issue: the page's own message, the element's name, « Aller à … ». */
export default function IssueList({
issues,
tone,
doc,
onSelectTab,
}: IssueListProps) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
if (issues.length === 0) return null
return (
<ul className="space-y-2">
{issues.map((issue, index) => {
const target = issueTarget(doc, issue.path, locale)
return (
<li key={`${issue.code}:${issue.path}:${index}`}>
<Notice tone={tone}>
<p>
{target?.name && <strong>{target.name}</strong>}
{target?.name ? ' : ' : ''}
{t(issueMessageKey(issue.code))}
</p>
{target && (
<Button
type="button"
size="sm"
variant="secondary"
className="mt-2"
onClick={() => onSelectTab(target.tab)}
>
{t('editor.verification.goto').replace(
'{tab}',
t(`editor.tab.${target.tab}`),
)}
</Button>
)}
</Notice>
</li>
)
})}
</ul>
)
}
@@ -0,0 +1,123 @@
import type {
AnatomicalSheetDocument,
ReviewGroup,
SheetReport,
StatusCounts,
} from '@faunosteo/core-wasm/types'
import { elementLabel } from '@/editor/sheetDocument'
import { DOCUMENT_BYTES_CAP, groupThousands } from '@/editor/verification'
import { useT } from '@/i18n/useT'
import type { Locale } from '@/i18n/types'
import { useLocaleStore } from '@/state/localeStore'
type Translate = ReturnType<typeof useT>
function statusLine(t: Translate, counts: StatusCounts): string {
return (['to_confirm', 'reviewed', 'inherited'] as const)
.map(
(status) =>
`${t(`editor.verification.status.${status}`)} ${counts[status]}`,
)
.join(' · ')
}
/** The group key the core builds (`general`, `view:<id>`, `zone:<id>`) as a readable name. */
function groupName(
t: Translate,
doc: AnatomicalSheetDocument,
key: string,
locale: Locale,
): string {
if (key === 'general') return t('editor.tab.general')
const [kind, id] = key.split(/:(.*)/s)
if (kind === 'view') return elementLabel(doc, { kind: 'view', id }, locale)
if (kind === 'zone') return elementLabel(doc, { kind: 'zone', id }, locale)
return key
}
function GroupRow({ group, label }: { group: ReviewGroup; label: string }) {
const t = useT()
return (
<li className="flex flex-wrap justify-between gap-x-4">
<span>
{label}
{group.removed && ` (${t('editor.verification.group_removed')})`}
</span>
<span className="text-[var(--color-ink-muted)]">
{statusLine(t, group.statuses)}
</span>
</li>
)
}
export function Completeness({ report }: { report: SheetReport }) {
const t = useT()
const { statuses, vet_referrals, uncited } = report.completeness
const count = (key: string, n: number) => t(key).replace('{count}', String(n))
return (
<section
aria-label={t('editor.verification.completeness')}
className="space-y-1 text-sm"
>
<h3 className="font-medium">{t('editor.verification.completeness')}</h3>
<p>{statusLine(t, statuses)}</p>
<p>{count('editor.verification.vet_referrals', vet_referrals)}</p>
<p>{count('editor.verification.uncited', uncited)}</p>
</section>
)
}
export function GroupStatuses({
report,
doc,
}: {
report: SheetReport
doc: AnatomicalSheetDocument
}) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
return (
<section
aria-label={t('editor.verification.groups')}
className="space-y-1 text-sm"
>
<h3 className="font-medium">{t('editor.verification.groups')}</h3>
<ul className="space-y-1">
{report.groups.map((group) => (
<GroupRow
key={group.key}
group={group}
label={groupName(t, doc, group.key, locale)}
/>
))}
</ul>
</section>
)
}
export function SizeAndCaps({ report }: { report: SheetReport }) {
const t = useT()
const { exceeded } = report.caps
const size = t('editor.verification.size')
.replace('{bytes}', groupThousands(report.document_bytes))
.replace('{cap}', groupThousands(DOCUMENT_BYTES_CAP))
return (
<section
aria-label={t('editor.verification.size_title')}
className="space-y-1 text-sm"
>
<h3 className="font-medium">{t('editor.verification.size_title')}</h3>
<p>{size}</p>
{exceeded.length > 0 && (
<p role="alert" className="text-[var(--color-danger)]">
{t('editor.verification.caps_exceeded').replace(
'{caps}',
exceeded
.map((cap) => t(`editor.verification.cap.${cap}`))
.join(', '),
)}
</p>
)}
</section>
)
}
@@ -0,0 +1,80 @@
import Button from '@/components/ui/Button'
import FormField from '@/components/ui/FormField'
import Textarea from '@/components/ui/Textarea'
import { useEditorStore } from '@/editor/state/editorStore'
import { NOTE_MAX_LENGTH } from '@/editor/verification'
import { useT } from '@/i18n/useT'
import { useSubmission } from './useSubmission'
interface SubmitPanelProps {
errorCount: number
reloadSheet: () => void
}
/** The hint that explains why the button is off, strongest reason first. */
function useBlockingHint(
errorCount: number,
noteBlank: boolean,
): string | null {
const t = useT()
const unsaved = useEditorStore((s) => s.unsaved || s.staleBase)
if (errorCount > 0) {
return t('editor.verification.hint.errors').replace(
'{count}',
String(errorCount),
)
}
if (unsaved) return t('editor.verification.hint.unsaved')
return noteBlank ? t('editor.verification.hint.note') : null
}
/** « Note de soumission (obligatoire) » and « Soumettre à la revue » (board 06 A). */
export default function SubmitPanel({
errorCount,
reloadSheet,
}: SubmitPanelProps) {
const t = useT()
const submitting = useEditorStore((s) => s.submitting)
const { note, setNote, submit, message } = useSubmission(reloadSheet)
const noteBlank = note.trim() === ''
const hint = useBlockingHint(errorCount, noteBlank)
return (
<section
aria-label={t('editor.verification.submit_title')}
className="space-y-3"
>
<FormField
id="verification-note"
label={t('editor.verification.note')}
hint={t('editor.verification.note_hint').replace(
'{max}',
String(NOTE_MAX_LENGTH),
)}
error={message ?? undefined}
>
<Textarea
id="verification-note"
value={note}
maxLength={NOTE_MAX_LENGTH}
onChange={(event) => setNote(event.target.value)}
/>
</FormField>
<Button
type="button"
disabled={hint !== null || submitting}
aria-describedby={hint ? 'verification-submit-hint' : undefined}
onClick={() => void submit()}
>
{t('editor.verification.submit')}
</Button>
{hint && (
<p
id="verification-submit-hint"
className="text-sm text-[var(--color-ink-muted)]"
>
{hint}
</p>
)}
</section>
)
}
@@ -0,0 +1,36 @@
import Badge from '@/components/ui/Badge'
import { useT } from '@/i18n/useT'
interface VerificationSummaryProps {
errors: number
warnings: number
toConfirm: number
}
/** Board 06 A: the three counts under the panel title (L27, L28). */
export default function VerificationSummary({
errors,
warnings,
toConfirm,
}: VerificationSummaryProps) {
const t = useT()
const count = (key: string, n: number) => t(key).replace('{count}', String(n))
return (
<div className="space-y-2">
<h2 className="text-base font-medium">
{t('editor.verification.title')}
</h2>
<p className="flex flex-wrap gap-2">
<Badge tone={errors > 0 ? 'danger' : 'neutral'}>
{count('editor.verification.errors', errors)}
</Badge>
<Badge tone={warnings > 0 ? 'warn' : 'neutral'}>
{count('editor.verification.warnings', warnings)}
</Badge>
<Badge tone="accent">
{count('editor.verification.to_confirm', toConfirm)}
</Badge>
</p>
</div>
)
}
@@ -0,0 +1,49 @@
import { useEffect, useRef, useState } from 'react'
import { failureMessage } from '@/admin/labels'
import { useEditorStore } from '@/editor/state/editorStore'
import type { SubmitOutcome } from '@/editor/state/editorTypes'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/** What a refused submission tells; the conflict dialog and silent kinds tell nothing. */
function refusalMessage(t: Translate, outcome: SubmitOutcome): string | null {
if (outcome.ok) return null
if (outcome.reason === 'server') {
return outcome.kind === 'draft_conflict'
? null
: failureMessage(t, outcome.kind)
}
if (outcome.reason !== 'blocked') return null
if (outcome.kind === 'unsaved' || outcome.kind === 'stale_base') {
return t('editor.verification.hint.unsaved')
}
return null
}
/** The note and the submission: success reloads the sheet (the round freezes the draft). */
export function useSubmission(reloadSheet: () => void) {
const t = useT()
const [note, setNote] = useState('')
const [message, setMessage] = useState<string | null>(null)
const mounted = useRef(true)
useEffect(() => {
mounted.current = true
return () => {
mounted.current = false
}
}, [])
const submit = async () => {
setMessage(null)
const outcome = await useEditorStore.getState().submit(note.trim())
if (!mounted.current) return
if (outcome.ok) {
setNote('')
reloadSheet()
} else {
setMessage(refusalMessage(t, outcome))
}
}
return { note, setNote, submit, message }
}
+131
View File
@@ -0,0 +1,131 @@
import type {
AnatomicalSheetDocument,
ElementKey,
SheetIssue,
SheetReport,
} from '@faunosteo/core-wasm/types'
import type { Locale } from '@/i18n/types'
import { elementLabel } from './sheetDocument'
import type { EditorTabId } from './tabs'
/** The server's cap on the document text (contract §12.2), shown beside the measure. */
export const DOCUMENT_BYTES_CAP = 2_097_152
/** The submission note bounds of board 06 A (the server decides at submit). */
export const NOTE_MAX_LENGTH = 1000
/** The issue codes the core reports (crates/core/src/domain/sheet), each with a message. */
export const ISSUE_CODES: readonly string[] = [
'view.main.count',
'view.id.duplicate',
'view.parent.missing',
'view.parent.cycle',
'view.unreachable',
'view.asset.missing',
'view.frame.unknown',
'annotation.id.duplicate',
'annotation.view.missing',
'annotation.category.missing',
'annotation.opens_view.invalid',
'annotation.finding_zone.missing',
'annotation.region.missing',
'annotation.no_findings',
'annotation.geometry.missing',
'annotation.geometry.out_of_frame',
'annotation.geometry.too_small',
'annotation.geometry.interior_too_small',
'region.code.duplicate',
'region.count_range.invalid',
'category.id.duplicate',
'finding_zone.id.duplicate',
'finding_zone.unreferenced',
'finding.id.duplicate',
'finding.reference.missing',
'reference.id.duplicate',
]
/** The i18n key of an issue's message; a code the page does not know gets the neutral one. */
export function issueMessageKey(code: string): string {
return ISSUE_CODES.includes(code)
? `editor.verification.issue.${code}`
: 'editor.verification.issue.unknown'
}
export function splitIssues(report: SheetReport): {
errors: SheetIssue[]
warnings: SheetIssue[]
} {
const { issues } = report
return {
errors: issues.filter((issue) => issue.severity === 'error'),
warnings: issues.filter((issue) => issue.severity === 'warning'),
}
}
const ROOT_TAB: Record<string, EditorTabId> = {
views: 'views',
annotations: 'annotations',
finding_zones: 'findings',
categories: 'general',
references: 'references',
}
const REGION_PATH = /^vertebral_config\.regions\[(\d+)\]/
const ROOT_PATH = /^(\w+)\[(\d+)\]/
export interface IssueTarget {
tab: EditorTabId
/** The named element (its label), when the path resolves in the document. */
name: string | null
}
function keyOf(
doc: AnatomicalSheetDocument,
root: string,
index: number,
): ElementKey | null {
switch (root) {
case 'views':
return idKey('view', doc.views[index])
case 'annotations':
return idKey('annotation', doc.annotations[index])
case 'categories':
return idKey('category', doc.categories[index])
case 'finding_zones':
return idKey('zone', doc.finding_zones[index])
case 'references':
return idKey('reference', doc.references[index])
default:
return null
}
}
function idKey<
K extends 'view' | 'annotation' | 'category' | 'zone' | 'reference',
>(kind: K, item: { id: string } | undefined): ElementKey | null {
return item ? ({ kind, id: item.id } as ElementKey) : null
}
/** The tab holding the element an issue path names (« Aller à … »); null when none. */
export function issueTarget(
doc: AnatomicalSheetDocument,
path: string,
locale: Locale,
): IssueTarget | null {
const region = REGION_PATH.exec(path)?.[1]
if (region !== undefined) {
const code = doc.vertebral_config.regions[Number(region)]?.code
const name = code
? elementLabel(doc, { kind: 'region', code }, locale)
: null
return { tab: 'vertebrae', name }
}
const match = ROOT_PATH.exec(path)
const tab = match ? ROOT_TAB[match[1]] : undefined
if (!match || !tab) return null
const key = keyOf(doc, match[1], Number(match[2]))
return { tab, name: key ? elementLabel(doc, key, locale) : null }
}
/** « 2 097 152 » with plain spaces, as the plan words the size. */
export function groupThousands(value: number): string {
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ' ')
}
+62
View File
@@ -1517,4 +1517,66 @@ export const en: Dict = {
'editor.findings.references': 'Cited references',
'editor.findings.references_none': 'No reference cited.',
'editor.findings.reference_add': 'Cite a reference',
'editor.verification.title': 'Draft check',
'editor.verification.errors': '{count} blocking errors',
'editor.verification.warnings': '{count} warnings',
'editor.verification.to_confirm': '{count} items to confirm',
'editor.verification.none': 'No issues found',
'editor.verification.warnings_title': 'Warnings',
'editor.verification.goto': 'Go to {tab}',
'editor.verification.to_confirm_info': 'Some items are still to confirm: this does not prevent submission.',
'editor.verification.completeness': 'Completeness',
'editor.verification.vet_referrals': '{count} veterinary referral(s)',
'editor.verification.uncited': '{count} finding(s) citing no reference',
'editor.verification.groups': 'Statuses per group',
'editor.verification.group_removed': 'removed',
'editor.verification.status.to_confirm': 'To confirm',
'editor.verification.status.reviewed': 'Reviewed',
'editor.verification.status.inherited': 'Inherited, not reviewed',
'editor.verification.size_title': 'Document size',
'editor.verification.size': '{bytes} B of {cap} B',
'editor.verification.caps_exceeded': 'Limits exceeded: {caps}.',
'editor.verification.cap.views': 'views',
'editor.verification.cap.annotations': 'annotations',
'editor.verification.cap.finding_nodes': 'finding categories and nodes',
'editor.verification.cap.finding_depth': 'finding depth',
'editor.verification.cap.label_length': 'name length',
'editor.verification.cap.drawings': 'drawings',
'editor.verification.cap.drawing_bytes': 'size of a drawing',
'editor.verification.cap.drawings_total_bytes': 'total size of the drawings',
'editor.verification.cap.document_bytes': 'document size',
'editor.verification.note_hint': '1 to {max} characters.',
'editor.verification.note': 'Submission note (required)',
'editor.verification.submit_title': 'Submission',
'editor.verification.submit': 'Submit for review',
'editor.verification.hint.errors': 'Fix the {count} blocking errors to submit.',
'editor.verification.hint.unsaved': 'Save the draft before submitting it.',
'editor.verification.hint.note': 'Enter the submission note to submit.',
'editor.verification.issue.unknown': 'This item breaks a rule of the sheet. Fix the item shown.',
'editor.verification.issue.view.main.count': 'The sheet must have exactly one main view.',
'editor.verification.issue.view.id.duplicate': 'Two views have the same id.',
'editor.verification.issue.view.parent.missing': 'The parent of this detail view does not exist.',
'editor.verification.issue.view.parent.cycle': 'The detail views refer to each other in a loop.',
'editor.verification.issue.view.unreachable': 'No link of an annotation opens this detail view.',
'editor.verification.issue.view.asset.missing': 'This view has neither a drawing nor a crop.',
'editor.verification.issue.view.frame.unknown': 'The frame of this view is unknown: no usable crop or drawing viewBox.',
'editor.verification.issue.annotation.id.duplicate': 'Two annotations have the same id.',
'editor.verification.issue.annotation.view.missing': 'This annotation sits on a view that does not exist.',
'editor.verification.issue.annotation.category.missing': 'The category of this annotation does not exist.',
'editor.verification.issue.annotation.opens_view.invalid': 'The view this link opens is not a detail view of its own view.',
'editor.verification.issue.annotation.finding_zone.missing': 'The findings zone of this annotation does not exist.',
'editor.verification.issue.annotation.region.missing': 'The vertebral region of this annotation is not defined.',
'editor.verification.issue.annotation.no_findings': 'This annotation is linked to no findings zone: a click on it will offer nothing.',
'editor.verification.issue.annotation.geometry.missing': 'This annotation has no geometry.',
'editor.verification.issue.annotation.geometry.out_of_frame': 'This annotation is not entirely inside the frame of its view.',
'editor.verification.issue.annotation.geometry.too_small': 'This annotation shows too small on the phone preview.',
'editor.verification.issue.annotation.geometry.interior_too_small': 'The inside of this zone is too narrow to tap on the phone preview.',
'editor.verification.issue.region.code.duplicate': 'Two vertebral regions have the same code.',
'editor.verification.issue.region.count_range.invalid': 'The usual count of this region is outside the stated variation.',
'editor.verification.issue.category.id.duplicate': 'Two annotation categories have the same id.',
'editor.verification.issue.finding_zone.id.duplicate': 'Two findings zones have the same id.',
'editor.verification.issue.finding_zone.unreferenced': 'No annotation points to this findings zone.',
'editor.verification.issue.finding.id.duplicate': 'Two sibling findings have the same id.',
'editor.verification.issue.finding.reference.missing': 'This finding cites a reference that is not declared.',
'editor.verification.issue.reference.id.duplicate': 'Two references have the same id.',
}
+62
View File
@@ -1548,4 +1548,66 @@ export const fr: Dict = {
'editor.findings.references': 'Références citées',
'editor.findings.references_none': 'Aucune référence citée.',
'editor.findings.reference_add': 'Citer une référence',
'editor.verification.title': 'Contrôle du brouillon',
'editor.verification.errors': '{count} erreurs bloquantes',
'editor.verification.warnings': '{count} avertissements',
'editor.verification.to_confirm': '{count} éléments à confirmer',
'editor.verification.none': 'Aucun problème détecté',
'editor.verification.warnings_title': 'Avertissements',
'editor.verification.goto': 'Aller à {tab}',
'editor.verification.to_confirm_info': "Des éléments restent à confirmer : cela n'empêche pas la soumission.",
'editor.verification.completeness': 'Complétude',
'editor.verification.vet_referrals': '{count} renvoi(s) vers un vétérinaire',
'editor.verification.uncited': '{count} constat(s) sans référence citée',
'editor.verification.groups': 'Statuts par groupe',
'editor.verification.group_removed': 'supprimé',
'editor.verification.status.to_confirm': 'À confirmer',
'editor.verification.status.reviewed': 'Relu',
'editor.verification.status.inherited': 'Hérité, non relu',
'editor.verification.size_title': 'Taille du document',
'editor.verification.size': '{bytes} o sur {cap} o',
'editor.verification.caps_exceeded': 'Limites dépassées : {caps}.',
'editor.verification.cap.views': 'vues',
'editor.verification.cap.annotations': 'annotations',
'editor.verification.cap.finding_nodes': 'catégories et nœuds de constats',
'editor.verification.cap.finding_depth': 'profondeur des constats',
'editor.verification.cap.label_length': 'longueur des noms',
'editor.verification.cap.drawings': 'illustrations',
'editor.verification.cap.drawing_bytes': "taille d'une illustration",
'editor.verification.cap.drawings_total_bytes': 'taille totale des illustrations',
'editor.verification.cap.document_bytes': 'taille du document',
'editor.verification.note_hint': '1 à {max} caractères.',
'editor.verification.note': 'Note de soumission (obligatoire)',
'editor.verification.submit_title': 'Soumission',
'editor.verification.submit': 'Soumettre à la revue',
'editor.verification.hint.errors': 'Corrigez les {count} erreurs bloquantes pour soumettre.',
'editor.verification.hint.unsaved': 'Enregistrez le brouillon avant de le soumettre.',
'editor.verification.hint.note': 'Saisissez la note de soumission pour soumettre.',
'editor.verification.issue.unknown': "Ce point ne respecte pas une règle de la fiche. Corrigez l'élément indiqué.",
'editor.verification.issue.view.main.count': 'La fiche doit avoir exactement une vue principale.',
'editor.verification.issue.view.id.duplicate': 'Deux vues ont le même identifiant.',
'editor.verification.issue.view.parent.missing': "Le parent de cette vue détaillée n'existe pas.",
'editor.verification.issue.view.parent.cycle': 'Les vues détaillées se renvoient en boucle.',
'editor.verification.issue.view.unreachable': "Aucun accès d'une annotation n'ouvre cette vue détaillée.",
'editor.verification.issue.view.asset.missing': "Cette vue n'a ni illustration ni cadrage.",
'editor.verification.issue.view.frame.unknown': "Le cadre de cette vue est inconnu : ni cadrage ni viewBox de l'illustration utilisables.",
'editor.verification.issue.annotation.id.duplicate': 'Deux annotations ont le même identifiant.',
'editor.verification.issue.annotation.view.missing': "Cette annotation est placée sur une vue qui n'existe pas.",
'editor.verification.issue.annotation.category.missing': "La catégorie de cette annotation n'existe pas.",
'editor.verification.issue.annotation.opens_view.invalid': "La vue ouverte par cet accès n'est pas une vue détaillée de sa propre vue.",
'editor.verification.issue.annotation.finding_zone.missing': "La zone de constats de cette annotation n'existe pas.",
'editor.verification.issue.annotation.region.missing': "La région vertébrale de cette annotation n'est pas définie.",
'editor.verification.issue.annotation.no_findings': "Cette annotation n'est liée à aucune zone de constats : un clic dessus ne proposera rien.",
'editor.verification.issue.annotation.geometry.missing': "Cette annotation n'a pas de géométrie.",
'editor.verification.issue.annotation.geometry.out_of_frame': "Cette annotation n'est pas entièrement dans le cadre de sa vue.",
'editor.verification.issue.annotation.geometry.too_small': "Cette annotation s'affiche trop petite sur l'aperçu téléphone.",
'editor.verification.issue.annotation.geometry.interior_too_small': "L'intérieur de cette zone est trop étroit pour être touché sur l'aperçu téléphone.",
'editor.verification.issue.region.code.duplicate': 'Deux régions vertébrales ont le même code.',
'editor.verification.issue.region.count_range.invalid': "Le nombre habituel de cette région n'est pas dans la variation indiquée.",
'editor.verification.issue.category.id.duplicate': "Deux catégories d'annotation ont le même identifiant.",
'editor.verification.issue.finding_zone.id.duplicate': 'Deux zones de constats ont le même identifiant.',
'editor.verification.issue.finding_zone.unreferenced': 'Aucune annotation ne pointe vers cette zone de constats.',
'editor.verification.issue.finding.id.duplicate': 'Deux constats voisins ont le même identifiant.',
'editor.verification.issue.finding.reference.missing': "Ce constat cite une référence qui n'est pas déclarée.",
'editor.verification.issue.reference.id.duplicate': 'Deux références ont le même identifiant.',
}
@@ -0,0 +1,216 @@
/** Lot J: the Vérification tab and the submission. */
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { SheetFailure } from '@faunosteo/supabase'
import VerificationTab from '@/components/editor/tabs/VerificationTab'
import { ISSUE_CODES, issueMessageKey } from '@/editor/verification'
import { getDict } from '@/i18n'
import { useLocaleStore } from '@/state/localeStore'
import { insert, point } from '../helpers/editorFixtures'
import {
baseText,
commitMove,
openReady,
resetStore,
sb,
store,
} from '../helpers/editorHarness'
vi.mock('@/lib/supabase', () => ({ getSupabaseClient: () => ({}) }))
vi.mock('@faunosteo/supabase', async (orig) => ({
...(await orig<typeof import('@faunosteo/supabase')>()),
getSheetVersion: vi.fn(),
downloadSheetDrawing: vi.fn(),
saveSheetDraft: vi.fn(),
getOfficialSheetAdmin: vi.fn(),
submitSheetReview: vi.fn(),
}))
const onSelectTab = vi.fn()
const reloadSheet = vi.fn()
const props = { readOnly: false, onSelectTab, reloadSheet }
const SUBMIT = 'Soumettre à la revue'
/** An annotation without geometry: a blocking error of the core. */
function textWithError(): string {
const bare = point('anno-bare', 10, 10, 2)
const value = {
...bare.value,
geometry: null,
name: { fr: 'Sans tracé', en: 'Bare' },
}
return insert(baseText(), { kind: 'annotation', value } as typeof bare)
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(() => {
cleanup()
resetStore()
onSelectTab.mockReset()
reloadSheet.mockReset()
})
describe('Vérification panel', () => {
it('shows the counts, the warning apart, the size and the groups', async () => {
await openReady()
render(<VerificationTab {...props} />)
expect(screen.getByText('0 erreurs bloquantes')).toBeTruthy()
expect(screen.getByText('1 avertissements')).toBeTruthy()
expect(screen.getByText('1 éléments à confirmer')).toBeTruthy()
expect(screen.getByRole('heading', { name: 'Avertissements' })).toBeTruthy()
expect(
screen.getByText(/lié(e)? à aucune zone|liée à aucune zone/),
).toBeTruthy()
expect(screen.getByText(/sur 2 097 152 o$/)).toBeTruthy()
expect(
screen.getByRole('heading', { name: 'Statuts par groupe' }),
).toBeTruthy()
expect(screen.getByText(/n'empêche pas la soumission/)).toBeTruthy()
})
it('names an error with its message and goes to the tab of the element', async () => {
await openReady({ text: textWithError() })
const user = userEvent.setup()
render(<VerificationTab {...props} />)
expect(screen.getByText('1 erreurs bloquantes')).toBeTruthy()
expect(screen.getAllByText('Sans tracé')).toHaveLength(2)
expect(screen.getByText(/n'a pas de géométrie/)).toBeTruthy()
await user.click(
screen.getAllByRole('button', { name: 'Aller à Annotations' })[0],
)
expect(onSelectTab).toHaveBeenCalledWith('annotations')
expect(screen.queryByText('Aucun problème détecté')).toBeNull()
})
it('disables the submission with the hint while errors exist', async () => {
await openReady({ text: textWithError() })
render(<VerificationTab {...props} />)
const button = screen.getByRole('button', {
name: SUBMIT,
}) as HTMLButtonElement
expect(button.disabled).toBe(true)
expect(
screen.getByText('Corrigez les 1 erreurs bloquantes pour soumettre.'),
).toBeTruthy()
})
it('phrases the issues in English', async () => {
useLocaleStore.setState({ locale: 'en' })
await openReady({ text: textWithError() })
render(<VerificationTab {...props} />)
expect(screen.getByText('1 blocking errors')).toBeTruthy()
expect(screen.getByText(/This annotation has no geometry/)).toBeTruthy()
expect(
screen.getAllByRole('button', { name: 'Go to Annotations' }),
).toHaveLength(3)
})
it('hides the submission when read-only', async () => {
await openReady()
render(<VerificationTab {...props} readOnly />)
expect(screen.queryByRole('button', { name: SUBMIT })).toBeNull()
expect(screen.getByText('0 erreurs bloquantes')).toBeTruthy()
})
})
describe('Submission', () => {
it('needs a note and the saved draft', async () => {
await openReady()
const user = userEvent.setup()
render(<VerificationTab {...props} />)
const button = screen.getByRole('button', {
name: SUBMIT,
}) as HTMLButtonElement
expect(button.disabled).toBe(true)
expect(screen.getByText(/Saisissez la note/)).toBeTruthy()
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
' ',
)
expect(button.disabled).toBe(true)
act(() => void commitMove(60))
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
'Prête',
)
expect(button.disabled).toBe(true)
expect(
screen.getByText('Enregistrez le brouillon avant de le soumettre.'),
).toBeTruthy()
})
it('submits the trimmed note on the saved revision and reloads the sheet', async () => {
await openReady()
sb.submitSheetReview.mockResolvedValue('review-1' as never)
const user = userEvent.setup()
render(<VerificationTab {...props} />)
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
' Prête ',
)
await user.click(screen.getByRole('button', { name: SUBMIT }))
await waitFor(() => expect(reloadSheet).toHaveBeenCalled())
expect(sb.submitSheetReview).toHaveBeenCalledWith(expect.anything(), {
version_id: 'ver-1',
expected_revision: 3,
note: 'Prête',
})
})
it('shows a server refusal and keeps the note', async () => {
await openReady()
sb.submitSheetReview.mockRejectedValue(new SheetFailure('draft.frozen'))
const user = userEvent.setup()
render(<VerificationTab {...props} />)
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
'Prête',
)
await user.click(screen.getByRole('button', { name: SUBMIT }))
expect(await screen.findByRole('alert')).toBeTruthy()
expect(reloadSheet).not.toHaveBeenCalled()
expect(
(
screen.getByLabelText(
'Note de soumission (obligatoire)',
) as HTMLTextAreaElement
).value,
).toBe('Prête')
})
it('opens the conflict read on a draft conflict and shows no message', async () => {
await openReady()
sb.submitSheetReview.mockRejectedValue(new SheetFailure('draft_conflict'))
sb.getOfficialSheetAdmin.mockRejectedValue(new Error('x'))
const user = userEvent.setup()
render(<VerificationTab {...props} />)
await user.type(
screen.getByLabelText('Note de soumission (obligatoire)'),
'Prête',
)
await user.click(screen.getByRole('button', { name: SUBMIT }))
await waitFor(() =>
expect(store.getState().conflict).toEqual({ status: 'unknown' }),
)
expect(screen.queryByRole('alert')).toBeNull()
expect(reloadSheet).not.toHaveBeenCalled()
expect(sb.submitSheetReview).toHaveBeenCalledTimes(1)
})
})
describe('Issue messages', () => {
it('has an FR and an EN message for every known code', () => {
for (const code of ISSUE_CODES) {
const key = issueMessageKey(code)
expect(getDict('fr')[key], key).toBeTruthy()
expect(getDict('en')[key], key).toBeTruthy()
}
})
it('falls back to a neutral message for an unknown code', () => {
const key = issueMessageKey('something.new')
expect(key).toBe('editor.verification.issue.unknown')
expect(getDict('fr')[key]).toBeTruthy()
})
})