fix(pdf): bundle the branding assets into the app (no fetch at export), export returns its warnings and the editor reports missing elements
This commit is contained in:
1 parent
80e95ca61d
commit
293a6e0b36
22 files changed
+199
-185
No files matched your search
@@ -153,10 +153,11 @@ pnpm format # Prettier write
|
|||||||
```
|
```
|
||||||
faunosteo/
|
faunosteo/
|
||||||
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
|
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
|
||||||
├─ public/ ← logos only (no anatomy asset: the sheet is bundled)
|
├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset)
|
||||||
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
|
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
|
||||||
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
|
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
|
||||||
├─ src/
|
├─ src/
|
||||||
|
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
|
||||||
│ ├─ app/
|
│ ├─ app/
|
||||||
│ │ ├─ App.tsx ← root router
|
│ │ ├─ App.tsx ← root router
|
||||||
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
|
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
|
||||||
@@ -187,7 +188,7 @@ faunosteo/
|
|||||||
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
|
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
|
||||||
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
|
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
|
||||||
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
|
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
|
||||||
│ │ └─ branding.ts + browserRasterizer.ts ← public/ logos → Branding; Image/canvas Rasterizer adapter
|
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
|
||||||
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
|
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
|
||||||
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
|
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
|
||||||
│ └─ main.tsx
|
│ └─ main.tsx
|
||||||
@@ -258,12 +259,12 @@ SVG interaction
|
|||||||
|
|
||||||
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
|
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
|
||||||
→ exportReportToPdf(report, index, { locale })
|
→ exportReportToPdf(report, index, { locale })
|
||||||
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 public/ files, each may fail alone) + defaultPdfLabels
|
→ buildSheetSnapshot(index.sheet, report) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
|
||||||
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
|
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
|
||||||
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
|
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
|
||||||
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
|
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
|
||||||
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
|
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
|
||||||
→ { pdf, envelope, warnings } → browser download
|
→ { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views
|
||||||
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
|
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
|
||||||
|
|
||||||
PDF import
|
PDF import
|
||||||
|
|||||||
@@ -28,11 +28,17 @@ import {
|
|||||||
} from '@/services/zoneInteraction'
|
} from '@/services/zoneInteraction'
|
||||||
import type { ViewStates } from '@/anatomy/drawing'
|
import type { ViewStates } from '@/anatomy/drawing'
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
|
import type { ExportWarning } from '@faunosteo/pdf'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
|
||||||
|
|
||||||
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
const DISCLAIMER_FLAG = 'osteo:disclaimer-shown'
|
||||||
|
|
||||||
|
/** What the PDF lacks, named for the practitioner: logo slots and view ids. */
|
||||||
|
function missingItemsOf(warnings: readonly ExportWarning[]): string[] {
|
||||||
|
return warnings.map((w) => (w.kind === 'logo_failed' ? w.slot : w.viewId))
|
||||||
|
}
|
||||||
|
|
||||||
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
|
/** Editor on the reference sheet: wires the canvas, the pickers and the store. */
|
||||||
export default function EditorRoute() {
|
export default function EditorRoute() {
|
||||||
const navigate = useNavigate()
|
const navigate = useNavigate()
|
||||||
@@ -144,14 +150,22 @@ export default function EditorRoute() {
|
|||||||
if (!report) return
|
if (!report) return
|
||||||
setExporting(true)
|
setExporting(true)
|
||||||
try {
|
try {
|
||||||
const bytes = await exportReportToPdf(report, index, { locale })
|
const { pdf, warnings } = await exportReportToPdf(report, index, {
|
||||||
const blob = new Blob([bytes as BlobPart], { type: 'application/pdf' })
|
locale,
|
||||||
|
})
|
||||||
|
const blob = new Blob([pdf as BlobPart], { type: 'application/pdf' })
|
||||||
const url = URL.createObjectURL(blob)
|
const url = URL.createObjectURL(blob)
|
||||||
const a = document.createElement('a')
|
const a = document.createElement('a')
|
||||||
a.href = url
|
a.href = url
|
||||||
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
|
a.download = `bilan-${report.animal.name}-${report.date}.pdf`
|
||||||
a.click()
|
a.click()
|
||||||
URL.revokeObjectURL(url)
|
URL.revokeObjectURL(url)
|
||||||
|
const missing = missingItemsOf(warnings)
|
||||||
|
if (missing.length) {
|
||||||
|
window.alert(
|
||||||
|
t('editor.export_warnings').replace('{items}', missing.join(', ')),
|
||||||
|
)
|
||||||
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('PDF export failed', err)
|
console.error('PDF export failed', err)
|
||||||
window.alert(t('editor.export_failed'))
|
window.alert(t('editor.export_failed'))
|
||||||
|
|||||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -1,5 +1,6 @@
|
|||||||
import { useConfig } from '@/app/providers/ConfigProvider'
|
import { useConfig } from '@/app/providers/ConfigProvider'
|
||||||
import { useT } from '@/i18n/useT'
|
import { useT } from '@/i18n/useT'
|
||||||
|
import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url'
|
||||||
|
|
||||||
export default function Footer() {
|
export default function Footer() {
|
||||||
const cfg = useConfig()
|
const cfg = useConfig()
|
||||||
@@ -37,7 +38,7 @@ export default function Footer() {
|
|||||||
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium"
|
className="text-[var(--color-accent)] hover:text-[var(--color-accent-strong)] transition-colors font-medium"
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
src="/Paws_in_harmony.svg"
|
src={pawsInHarmonyUrl}
|
||||||
alt="Paws in Harmony"
|
alt="Paws in Harmony"
|
||||||
className="h-6 w-auto inline-block align-middle"
|
className="h-6 w-auto inline-block align-middle"
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -66,6 +66,8 @@ export const en: Dict = {
|
|||||||
'editor.export': 'Export as PDF',
|
'editor.export': 'Export as PDF',
|
||||||
'editor.exporting': 'Generating…',
|
'editor.exporting': 'Generating…',
|
||||||
'editor.export_failed': 'PDF generation failed. Retry or contact support.',
|
'editor.export_failed': 'PDF generation failed. Retry or contact support.',
|
||||||
|
'editor.export_warnings':
|
||||||
|
'PDF exported with missing elements: {items}. Check the browser console.',
|
||||||
'editor.edit_infos': 'Edit info',
|
'editor.edit_infos': 'Edit info',
|
||||||
'editor.edit_dialog_title': 'Edit information',
|
'editor.edit_dialog_title': 'Edit information',
|
||||||
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
'editor.disclaimer_title': 'Legal scope of animal osteopathy',
|
||||||
|
|||||||
@@ -72,6 +72,8 @@ export const fr: Dict = {
|
|||||||
'editor.exporting': 'Génération…',
|
'editor.exporting': 'Génération…',
|
||||||
'editor.export_failed':
|
'editor.export_failed':
|
||||||
'Échec de la génération du PDF. Réessayez ou contactez le support.',
|
'É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.edit_infos': 'Modifier les infos',
|
'editor.edit_infos': 'Modifier les infos',
|
||||||
'editor.edit_dialog_title': 'Modifier les informations',
|
'editor.edit_dialog_title': 'Modifier les informations',
|
||||||
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
|
'editor.disclaimer_title': "Périmètre légal de l'ostéopathie animale",
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
import type { Branding, ImageAsset } from '@faunosteo/domain'
|
import type { Branding, ImageAsset } from '@faunosteo/domain'
|
||||||
|
import headerLogoDataUrl from '@/assets/brand/faunosteo-logo-horizontal-512.png?inline'
|
||||||
|
import footerLogoDataUrl from '@/assets/brand/faunosteo-horizontal-com-512.png?inline'
|
||||||
|
import poweredByLogoDataUrl from '@/assets/brand/zenquality-logo-fr.png?inline'
|
||||||
|
import partnerLogoSvg from '@/assets/brand/paws-in-harmony.svg?raw'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
|
* The visual identity the export embeds (STEP6 §14 "Branding in the app"):
|
||||||
* the four `public/` files fetched by their current URLs, each failure
|
* the four logo files bundled with the application (`src/assets/brand`), so
|
||||||
* leaving its slot empty with a warning (the page then prints the credit's
|
* an export needs no network and no deployed file, plus the credit URLs. The
|
||||||
* fallback text), plus the credit URLs. The result travels inside the
|
* result travels inside the archive, so a re-export never needs them again.
|
||||||
* archive, so a re-export never needs these files again.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// shortcut: the site URL and the credit constants belong to the runtime
|
// shortcut: the site URL and the credit constants belong to the runtime
|
||||||
@@ -20,62 +23,22 @@ const PARTNER = {
|
|||||||
fallbackText: '@paws.iin.harmony',
|
fallbackText: '@paws.iin.harmony',
|
||||||
}
|
}
|
||||||
|
|
||||||
const HEADER_LOGO_URL = '/assets/faunosteo_logo_horizontal-512.png'
|
const PNG_DATA_URL_PREFIX = 'data:image/png;base64,'
|
||||||
const FOOTER_LOGO_URL = '/assets/faunosteo-horizontal-com-512.png'
|
|
||||||
const POWERED_BY_LOGO_URL = '/brand/zenquality-logo-fr.png'
|
|
||||||
const PARTNER_LOGO_URL = '/Paws_in_harmony.svg'
|
|
||||||
|
|
||||||
/** btoa takes a binary string; chunking keeps the argument list small. */
|
/** A `?inline` PNG import is a base64 data URL; the engine wants the base64 alone. */
|
||||||
function bytesToBase64(bytes: Uint8Array): string {
|
function pngAsset(dataUrl: string): ImageAsset {
|
||||||
const CHUNK = 0x8000
|
if (!dataUrl.startsWith(PNG_DATA_URL_PREFIX)) {
|
||||||
let binary = ''
|
throw new Error('bundled logo is not a base64 PNG data URL')
|
||||||
for (let i = 0; i < bytes.length; i += CHUNK) {
|
|
||||||
binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK))
|
|
||||||
}
|
|
||||||
return btoa(binary)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function fetchOk(url: string): Promise<Response> {
|
|
||||||
const resp = await fetch(url)
|
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`)
|
|
||||||
return resp
|
|
||||||
}
|
|
||||||
|
|
||||||
async function pngAsset(url: string): Promise<ImageAsset> {
|
|
||||||
const bytes = new Uint8Array(await (await fetchOk(url)).arrayBuffer())
|
|
||||||
return { kind: 'png', base64: bytesToBase64(bytes) }
|
|
||||||
}
|
|
||||||
|
|
||||||
async function svgAsset(url: string): Promise<ImageAsset> {
|
|
||||||
return { kind: 'svg', svg: await (await fetchOk(url)).text() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/** A slot fails alone: the export goes on without that logo. */
|
|
||||||
async function slot(
|
|
||||||
load: Promise<ImageAsset>,
|
|
||||||
url: string,
|
|
||||||
): Promise<ImageAsset | null> {
|
|
||||||
try {
|
|
||||||
return await load
|
|
||||||
} catch (err) {
|
|
||||||
console.warn(`Branding asset ${url} skipped:`, err)
|
|
||||||
return null
|
|
||||||
}
|
}
|
||||||
|
return { kind: 'png', base64: dataUrl.slice(PNG_DATA_URL_PREFIX.length) }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function loadBranding(): Promise<Branding> {
|
export async function loadBranding(): Promise<Branding> {
|
||||||
const [headerLogo, footerLogo, poweredByLogo, partnerLogo] =
|
|
||||||
await Promise.all([
|
|
||||||
slot(pngAsset(HEADER_LOGO_URL), HEADER_LOGO_URL),
|
|
||||||
slot(pngAsset(FOOTER_LOGO_URL), FOOTER_LOGO_URL),
|
|
||||||
slot(pngAsset(POWERED_BY_LOGO_URL), POWERED_BY_LOGO_URL),
|
|
||||||
slot(svgAsset(PARTNER_LOGO_URL), PARTNER_LOGO_URL),
|
|
||||||
])
|
|
||||||
return {
|
return {
|
||||||
siteUrl: SITE_URL,
|
siteUrl: SITE_URL,
|
||||||
headerLogo,
|
headerLogo: pngAsset(headerLogoDataUrl),
|
||||||
footerLogo,
|
footerLogo: pngAsset(footerLogoDataUrl),
|
||||||
poweredBy: { logo: poweredByLogo, ...POWERED_BY },
|
poweredBy: { logo: pngAsset(poweredByLogoDataUrl), ...POWERED_BY },
|
||||||
partner: { logo: partnerLogo, ...PARTNER },
|
partner: { logo: { kind: 'svg', svg: partnerLogoSvg }, ...PARTNER },
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
import { buildSheetSnapshot, type Report } from '@faunosteo/domain'
|
||||||
import { defaultPdfLabels, exportReportArchive } from '@faunosteo/pdf'
|
import {
|
||||||
|
defaultPdfLabels,
|
||||||
|
exportReportArchive,
|
||||||
|
type ExportWarning,
|
||||||
|
} from '@faunosteo/pdf'
|
||||||
import type { Locale } from '@/i18n/types'
|
import type { Locale } from '@/i18n/types'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { loadBranding } from './branding'
|
import { loadBranding } from './branding'
|
||||||
@@ -9,17 +13,23 @@ export interface PdfExportOptions {
|
|||||||
locale: Locale
|
locale: Locale
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface PdfExportResult {
|
||||||
|
pdf: Uint8Array
|
||||||
|
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
|
||||||
|
warnings: ExportWarning[]
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Exports the report as an archive PDF through the engine: the loaded sheet
|
* Exports the report as an archive PDF through the engine: the loaded sheet
|
||||||
* becomes the snapshot the pages are drawn from and the attachment carries,
|
* becomes the snapshot the pages are drawn from and the attachment carries,
|
||||||
* the branding is fetched once from `public/`, the browser rasterises the
|
* the branding comes from the bundled logos, the browser rasterises the
|
||||||
* views. Non-fatal engine warnings (a logo or a view that failed) are logged.
|
* views. Warnings are logged and returned for the caller to surface.
|
||||||
*/
|
*/
|
||||||
export async function exportReportToPdf(
|
export async function exportReportToPdf(
|
||||||
report: Report,
|
report: Report,
|
||||||
index: SheetIndex,
|
index: SheetIndex,
|
||||||
opts: PdfExportOptions,
|
opts: PdfExportOptions,
|
||||||
): Promise<Uint8Array> {
|
): Promise<PdfExportResult> {
|
||||||
const result = await exportReportArchive({
|
const result = await exportReportArchive({
|
||||||
report,
|
report,
|
||||||
sheet: buildSheetSnapshot(index.sheet, report),
|
sheet: buildSheetSnapshot(index.sheet, report),
|
||||||
@@ -32,5 +42,5 @@ export async function exportReportToPdf(
|
|||||||
for (const warning of result.warnings) {
|
for (const warning of result.warnings) {
|
||||||
console.warn('PDF export warning', warning)
|
console.warn('PDF export warning', warning)
|
||||||
}
|
}
|
||||||
return result.pdf
|
return { pdf: result.pdf, warnings: result.warnings }
|
||||||
}
|
}
|
||||||
Vendored
+2
-2
@@ -30,8 +30,8 @@ What the PDF pipeline produced right before the Step 6 refactor, recorded by
|
|||||||
Reports: `v2full` (`report-v2.full.json` migrated), `demo` (`report-v3.demo.json`),
|
Reports: `v2full` (`report-v2.full.json` migrated), `demo` (`report-v3.demo.json`),
|
||||||
`v2unresolved` (legacy `sphenoid` and `ssb` leaves plus one `frontal` leaf, migrated;
|
`v2unresolved` (legacy `sphenoid` and `ssb` leaves plus one `frontal` leaf, migrated;
|
||||||
zone-less, so its `images` and `views` goldens are empty). Logo modes: `nologos`
|
zone-less, so its `images` and `views` goldens are empty). Logo modes: `nologos`
|
||||||
(fetch 404, 1×1 rasteriser) and `logos` (fetch serves the four `public/` logo files,
|
(every branding slot empty, 1×1 rasteriser) and `logos` (the four logo files bundled
|
||||||
rasteriser stubbed to a 2×1 PNG).
|
under `apps/app/src/assets/brand`, rasteriser stubbed to a 2×1 PNG).
|
||||||
|
|
||||||
Never regenerate these files without a user decision; the Step 6 engine must
|
Never regenerate these files without a user decision; the Step 6 engine must
|
||||||
reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run
|
reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
import { dirname, resolve } from 'node:path'
|
import { dirname, resolve } from 'node:path'
|
||||||
import { expect, vi } from 'vitest'
|
import { expect, vi } from 'vitest'
|
||||||
@@ -12,8 +12,14 @@ import {
|
|||||||
PDFPage,
|
PDFPage,
|
||||||
PDFString,
|
PDFString,
|
||||||
} from 'pdf-lib'
|
} from 'pdf-lib'
|
||||||
import type { Observation, Report, SheetSnapshot } from '@faunosteo/domain'
|
import type {
|
||||||
|
Branding,
|
||||||
|
Observation,
|
||||||
|
Report,
|
||||||
|
SheetSnapshot,
|
||||||
|
} from '@faunosteo/domain'
|
||||||
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
|
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
|
||||||
|
import { nologosBranding } from './sheet'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine,
|
* Step 6 Phase 0 freeze: what the PDF pipeline drew before the engine,
|
||||||
@@ -41,7 +47,6 @@ export const TWO_BY_ONE_PNG = Uint8Array.from(
|
|||||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
|
export const FIXTURES_DIR = resolve(HERE, '../fixtures')
|
||||||
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
||||||
const PUBLIC_DIR = resolve(HERE, '../../public')
|
|
||||||
|
|
||||||
/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */
|
/** `MAKE_GOLDEN=1` writes the goldens instead of asserting them. */
|
||||||
export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1'
|
export const MAKE_GOLDEN = process.env.MAKE_GOLDEN === '1'
|
||||||
@@ -179,42 +184,16 @@ export async function readLinks(bytes: Uint8Array): Promise<LinkEntry[]> {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
const LOGO_FILES: Readonly<Record<string, string>> = {
|
/**
|
||||||
'/assets/faunosteo_logo_horizontal-512.png':
|
* The branding of one logo mode, for a test that mocks `@/pdf/branding`:
|
||||||
'assets/faunosteo_logo_horizontal-512.png',
|
* `logos` is the real module (the bundled files), `nologos` every slot
|
||||||
'/assets/faunosteo-horizontal-com-512.png':
|
* empty with the credits' fallback texts (the Phase 0 fetch 404).
|
||||||
'assets/faunosteo-horizontal-com-512.png',
|
*/
|
||||||
'/brand/zenquality-logo-fr.png': 'brand/zenquality-logo-fr.png',
|
export async function brandingOf(mode: LogoMode): Promise<Branding> {
|
||||||
'/Paws_in_harmony.svg': 'Paws_in_harmony.svg',
|
if (mode === 'nologos') return nologosBranding()
|
||||||
}
|
const real =
|
||||||
|
await vi.importActual<typeof import('@/pdf/branding')>('@/pdf/branding')
|
||||||
function serveLogo(path: string): Response {
|
return real.loadBranding()
|
||||||
const relative = LOGO_FILES[path]
|
|
||||||
const file = relative ? resolve(PUBLIC_DIR, relative) : null
|
|
||||||
if (!file || !existsSync(file))
|
|
||||||
return new Response('not found', { status: 404 })
|
|
||||||
return new Response(new Uint8Array(readFileSync(file)), { status: 200 })
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stubs fetch with a path → Response handler; returns the restore function. */
|
|
||||||
export function installFetch(respond: (path: string) => Response): () => void {
|
|
||||||
const real = globalThis.fetch
|
|
||||||
globalThis.fetch = (async (input: RequestInfo | URL) =>
|
|
||||||
respond(
|
|
||||||
new URL(String(input), 'http://localhost').pathname,
|
|
||||||
)) as typeof fetch
|
|
||||||
return () => {
|
|
||||||
globalThis.fetch = real
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Stubs fetch for one logo mode; returns the restore function. */
|
|
||||||
export function installLogoFetch(mode: LogoMode): () => void {
|
|
||||||
return installFetch((path) =>
|
|
||||||
mode === 'logos'
|
|
||||||
? serveLogo(path)
|
|
||||||
: new Response('not found', { status: 404 }),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const HIGHLIGHT_FILL = '#b85a3f'
|
const HIGHLIGHT_FILL = '#b85a3f'
|
||||||
|
|||||||
@@ -31,9 +31,6 @@ let findings: Finding[]
|
|||||||
let unresolvedFindings: number
|
let unresolvedFindings: number
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
// No logo served: the branding loader leaves every slot empty.
|
|
||||||
globalThis.fetch = (async () =>
|
|
||||||
new Response('not found', { status: 404 })) as typeof fetch
|
|
||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
const leaves = legacyLeaves(loadLegacyBaseline())
|
const leaves = legacyLeaves(loadLegacyBaseline())
|
||||||
const v2 = leavesAsV2Report(leaves)
|
const v2 = leavesAsV2Report(leaves)
|
||||||
@@ -60,7 +57,9 @@ describe('the 612 legacy leaves in the application', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
|
it('keeps every finding, resolved or not, through an archive PDF export and import', async () => {
|
||||||
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
const { pdf: bytes } = await exportReportToPdf(report, sheet, {
|
||||||
|
locale: 'fr',
|
||||||
|
})
|
||||||
const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
|
const back = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
|
||||||
expect(back.migrated).toBe(false)
|
expect(back.migrated).toBe(false)
|
||||||
expect(back.origin).toBe('envelope_v1')
|
expect(back.origin).toBe('envelope_v1')
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import {
|
|||||||
buildSheetIndex,
|
buildSheetIndex,
|
||||||
buildSheetSnapshot,
|
buildSheetSnapshot,
|
||||||
ReportSchema,
|
ReportSchema,
|
||||||
|
type Branding,
|
||||||
type FindingCategory,
|
type FindingCategory,
|
||||||
type FindingNode,
|
type FindingNode,
|
||||||
type Report,
|
type Report,
|
||||||
@@ -33,8 +34,6 @@ import type { SheetIndex } from '@/services/sheetIndex'
|
|||||||
import { loadTestSheet } from '../helpers/sheet'
|
import { loadTestSheet } from '../helpers/sheet'
|
||||||
import {
|
import {
|
||||||
FIXTURES_DIR,
|
FIXTURES_DIR,
|
||||||
installFetch,
|
|
||||||
installLogoFetch,
|
|
||||||
ONE_PX_PNG,
|
ONE_PX_PNG,
|
||||||
readLinks,
|
readLinks,
|
||||||
recordDrawing,
|
recordDrawing,
|
||||||
@@ -50,10 +49,17 @@ vi.mock('@/pdf/browserRasterizer', async () => {
|
|||||||
const { TWO_BY_ONE_PNG } = await import('../helpers/goldens')
|
const { TWO_BY_ONE_PNG } = await import('../helpers/goldens')
|
||||||
return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) }
|
return { browserRasterizer: vi.fn(async () => TWO_BY_ONE_PNG) }
|
||||||
})
|
})
|
||||||
|
// The bundled branding, unless a scenario swaps the deployment's logos.
|
||||||
|
const branding = vi.hoisted(() => ({ current: null as Branding | null }))
|
||||||
|
vi.mock('@/pdf/branding', async (importOriginal) => {
|
||||||
|
const real = await importOriginal<typeof import('@/pdf/branding')>()
|
||||||
|
return {
|
||||||
|
loadBranding: vi.fn(async () => branding.current ?? real.loadBranding()),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
let demo: Report
|
let demo: Report
|
||||||
let restoreFetch: () => void = () => undefined
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
@@ -65,8 +71,8 @@ beforeAll(async () => {
|
|||||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
})
|
})
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
restoreFetch()
|
branding.current = null
|
||||||
restoreFetch = () => undefined
|
vi.unstubAllGlobals()
|
||||||
})
|
})
|
||||||
afterAll(() => vi.restoreAllMocks())
|
afterAll(() => vi.restoreAllMocks())
|
||||||
|
|
||||||
@@ -96,18 +102,9 @@ const facts = ({ texts, images, links }: Facts): Facts => ({
|
|||||||
links,
|
links,
|
||||||
})
|
})
|
||||||
|
|
||||||
/** The app export path, logos served from public/, under the recorder. */
|
/** The app export path, bundled logos, under the recorder. */
|
||||||
async function appExport(
|
function appExport(index: SheetIndex): Promise<Facts & { pdf: Uint8Array }> {
|
||||||
index: SheetIndex,
|
return recorded(() => exportReportToPdf(demo, index, { locale: 'fr' }))
|
||||||
): Promise<Facts & { pdf: Uint8Array }> {
|
|
||||||
const restore = installLogoFetch('logos')
|
|
||||||
try {
|
|
||||||
return await recorded(async () => ({
|
|
||||||
pdf: await exportReportToPdf(demo, index, { locale: 'fr' }),
|
|
||||||
}))
|
|
||||||
} finally {
|
|
||||||
restore()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> {
|
async function archiveOf(pdf: Uint8Array): Promise<ReportArchiveEnvelope> {
|
||||||
@@ -181,18 +178,27 @@ describe('the archive survives its resources', () => {
|
|||||||
const archive = await archiveOf(first.pdf)
|
const archive = await archiveOf(first.pdf)
|
||||||
|
|
||||||
// The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG.
|
// The deployment now ships other logos: a 1×1 PNG everywhere, another partner SVG.
|
||||||
|
const onePx = {
|
||||||
|
kind: 'png' as const,
|
||||||
|
base64: Buffer.from(ONE_PX_PNG).toString('base64'),
|
||||||
|
}
|
||||||
const otherSvg =
|
const otherSvg =
|
||||||
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
|
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10"><rect width="10" height="10"/></svg>'
|
||||||
const fetchSpy = vi.fn((path: string) =>
|
branding.current = {
|
||||||
path.endsWith('.svg')
|
...archive.branding,
|
||||||
? new Response(otherSvg, { status: 200 })
|
headerLogo: onePx,
|
||||||
: new Response(ONE_PX_PNG, { status: 200 }),
|
footerLogo: onePx,
|
||||||
)
|
poweredBy: { ...archive.branding.poweredBy!, logo: onePx },
|
||||||
restoreFetch = installFetch(fetchSpy)
|
partner: {
|
||||||
|
...archive.branding.partner!,
|
||||||
|
logo: { kind: 'svg', svg: otherSvg },
|
||||||
|
},
|
||||||
|
}
|
||||||
const current = await loadBranding()
|
const current = await loadBranding()
|
||||||
expect(current.headerLogo).not.toBeNull()
|
expect(current.headerLogo).not.toBeNull()
|
||||||
expect(current).not.toEqual(archive.branding)
|
expect(current).not.toEqual(archive.branding)
|
||||||
fetchSpy.mockClear()
|
const fetchSpy = vi.fn()
|
||||||
|
vi.stubGlobal('fetch', fetchSpy)
|
||||||
|
|
||||||
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
|
const again = await recorded(() => exportFromEnvelope(archive, REEXPORT))
|
||||||
expect(fetchSpy).not.toHaveBeenCalled()
|
expect(fetchSpy).not.toHaveBeenCalled()
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
/**
|
/**
|
||||||
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
|
* Step 6 Phase 0 freeze (STEP6_PDF_ARCHIVE_ANALYSIS.md §17) replayed on the
|
||||||
* application export path: `exportReportToPdf` now runs the engine with the
|
* application export path: `exportReportToPdf` now runs the engine with the
|
||||||
* bundled sheet snapshotted, the branding fetched from `public/` and the
|
* bundled sheet snapshotted, the bundled branding (mocked to every slot empty
|
||||||
* browser rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
|
* for the `nologos` mode, the real module for `logos`) and the browser
|
||||||
|
* rasterizer (mocked to fixed PNGs, as the Phase 0 stub was). Text,
|
||||||
* images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites
|
* images and links goldens are asserted as frozen; `MAKE_GOLDEN=1` rewrites
|
||||||
* them, never without a user decision. Never regenerate `report-v3.bare.pdf`:
|
* them, never without a user decision. Never regenerate `report-v3.bare.pdf`:
|
||||||
* it is the Step 5 bare export, an import fixture only.
|
* it is the Step 5 bare export, an import fixture only.
|
||||||
@@ -30,7 +31,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
checkGolden,
|
checkGolden,
|
||||||
FIXTURES_DIR,
|
FIXTURES_DIR,
|
||||||
installLogoFetch,
|
|
||||||
ONE_PX_PNG,
|
ONE_PX_PNG,
|
||||||
readGolden,
|
readGolden,
|
||||||
readLinks,
|
readLinks,
|
||||||
@@ -48,6 +48,11 @@ const raster = vi.hoisted(() => ({ png: new Uint8Array() }))
|
|||||||
vi.mock('@/pdf/browserRasterizer', () => ({
|
vi.mock('@/pdf/browserRasterizer', () => ({
|
||||||
browserRasterizer: vi.fn(async () => raster.png),
|
browserRasterizer: vi.fn(async () => raster.png),
|
||||||
}))
|
}))
|
||||||
|
const logoMode = vi.hoisted(() => ({ current: 'nologos' as LogoMode }))
|
||||||
|
vi.mock('@/pdf/branding', async () => {
|
||||||
|
const { brandingOf } = await import('../helpers/goldens')
|
||||||
|
return { loadBranding: vi.fn(() => brandingOf(logoMode.current)) }
|
||||||
|
})
|
||||||
|
|
||||||
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
|
const REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
|
||||||
type ReportName = (typeof REPORTS)[number]
|
type ReportName = (typeof REPORTS)[number]
|
||||||
@@ -103,15 +108,14 @@ async function exportWith(
|
|||||||
locale: Locale,
|
locale: Locale,
|
||||||
): Promise<Exported> {
|
): Promise<Exported> {
|
||||||
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
raster.png = mode === 'logos' ? TWO_BY_ONE_PNG : ONE_PX_PNG
|
||||||
const restoreFetch = installLogoFetch(mode)
|
logoMode.current = mode
|
||||||
const recording = recordDrawing()
|
const recording = recordDrawing()
|
||||||
try {
|
try {
|
||||||
const bytes = await exportReportToPdf(report, sheet, { locale })
|
const { pdf: bytes } = await exportReportToPdf(report, sheet, { locale })
|
||||||
const { texts, images } = recording
|
const { texts, images } = recording
|
||||||
return { bytes, texts, images, links: await readLinks(bytes) }
|
return { bytes, texts, images, links: await readLinks(bytes) }
|
||||||
} finally {
|
} finally {
|
||||||
recording.stop()
|
recording.stop()
|
||||||
restoreFetch()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,11 +17,16 @@ import { AFRelationship, PDFDocument, PDFPage } from 'pdf-lib'
|
|||||||
import { readFileSync } from 'node:fs'
|
import { readFileSync } from 'node:fs'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
import { dirname, resolve } from 'node:path'
|
import { dirname, resolve } from 'node:path'
|
||||||
import { buildSheetSnapshot, type Observation } from '@faunosteo/domain'
|
import {
|
||||||
|
buildSheetSnapshot,
|
||||||
|
type Observation,
|
||||||
|
type Report,
|
||||||
|
} from '@faunosteo/domain'
|
||||||
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
|
import { composeHighlightedViewSvg, defaultPdfLabels } from '@faunosteo/pdf'
|
||||||
import { exportReportToPdf } from '@/pdf/export'
|
import { exportReportToPdf } from '@/pdf/export'
|
||||||
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
import { importReportFromPdf, ImportError } from '@/pdf/import'
|
||||||
import { formatDate } from '@/lib/dates'
|
import { formatDate } from '@/lib/dates'
|
||||||
|
import type { Locale } from '@/i18n/types'
|
||||||
import type { SheetIndex } from '@/services/sheetIndex'
|
import type { SheetIndex } from '@/services/sheetIndex'
|
||||||
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
||||||
|
|
||||||
@@ -34,29 +39,25 @@ vi.mock('@/pdf/browserRasterizer', async () => {
|
|||||||
/** The static PDF strings now belong to the engine's label set. */
|
/** The static PDF strings now belong to the engine's label set. */
|
||||||
const { fr, en } = defaultPdfLabels
|
const { fr, en } = defaultPdfLabels
|
||||||
|
|
||||||
|
/** The bytes of an app export (its warnings are not under test here). */
|
||||||
|
async function exportPdf(report: Report, locale: Locale): Promise<Uint8Array> {
|
||||||
|
return (await exportReportToPdf(report, sheet, { locale })).pdf
|
||||||
|
}
|
||||||
|
|
||||||
const HERE = dirname(fileURLToPath(import.meta.url))
|
const HERE = dirname(fileURLToPath(import.meta.url))
|
||||||
const fixture = (name: string) =>
|
const fixture = (name: string) =>
|
||||||
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
|
new Uint8Array(readFileSync(resolve(HERE, '../fixtures', name)))
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
let drawn: string[] = []
|
let drawn: string[] = []
|
||||||
const fetched: string[] = []
|
|
||||||
const realFetch = globalThis.fetch
|
|
||||||
|
|
||||||
beforeAll(async () => {
|
beforeAll(async () => {
|
||||||
sheet = await loadTestSheet()
|
sheet = await loadTestSheet()
|
||||||
globalThis.fetch = (async (input: RequestInfo | URL) => {
|
|
||||||
fetched.push(String(input))
|
|
||||||
return new Response('not found', { status: 404 })
|
|
||||||
}) as typeof fetch
|
|
||||||
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
vi.spyOn(console, 'warn').mockImplementation(() => undefined)
|
||||||
})
|
})
|
||||||
afterAll(() => {
|
afterAll(() => vi.restoreAllMocks())
|
||||||
globalThis.fetch = realFetch
|
|
||||||
})
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
drawn = []
|
drawn = []
|
||||||
fetched.length = 0
|
|
||||||
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
|
vi.spyOn(PDFPage.prototype, 'drawText').mockImplementation(function (
|
||||||
this: PDFPage,
|
this: PDFPage,
|
||||||
text: string,
|
text: string,
|
||||||
@@ -118,7 +119,7 @@ describe('export on a full v3 report (FR)', () => {
|
|||||||
observations: [fullObservation()],
|
observations: [fullObservation()],
|
||||||
conclusion: 'ok',
|
conclusion: 'ok',
|
||||||
})
|
})
|
||||||
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
const bytes = await exportPdf(report, 'fr')
|
||||||
const doc = await PDFDocument.load(bytes)
|
const doc = await PDFDocument.load(bytes)
|
||||||
expect(doc.getPageCount()).toBe(2)
|
expect(doc.getPageCount()).toBe(2)
|
||||||
const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!)
|
const zonesIdx = drawn.indexOf(fr['pdf.section.zones']!)
|
||||||
@@ -145,7 +146,7 @@ describe('export on a full v3 report (FR)', () => {
|
|||||||
it('attaches the envelope and roundtrips in both locales', async () => {
|
it('attaches the envelope and roundtrips in both locales', async () => {
|
||||||
const report = minimalReport(sheet, { observations: [fullObservation()] })
|
const report = minimalReport(sheet, { observations: [fullObservation()] })
|
||||||
for (const locale of ['fr', 'en'] as const) {
|
for (const locale of ['fr', 'en'] as const) {
|
||||||
const bytes = await exportReportToPdf(report, sheet, { locale })
|
const bytes = await exportPdf(report, locale)
|
||||||
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
|
const out = await importReportFromPdf(bytes, sheet.sheet.migrationMap)
|
||||||
expect(out.migrated).toBe(false)
|
expect(out.migrated).toBe(false)
|
||||||
expect(out.origin).toBe('envelope_v1')
|
expect(out.origin).toBe('envelope_v1')
|
||||||
@@ -242,7 +243,7 @@ describe('PDF content on a two-observation report', () => {
|
|||||||
|
|
||||||
it('draws free findings, comments, the conclusion page and the header on every page', async () => {
|
it('draws free findings, comments, the conclusion page and the header on every page', async () => {
|
||||||
const report = fullReport()
|
const report = fullReport()
|
||||||
const bytes = await exportReportToPdf(report, sheet, { locale: 'fr' })
|
const bytes = await exportPdf(report, 'fr')
|
||||||
const pages = (await PDFDocument.load(bytes)).getPageCount()
|
const pages = (await PDFDocument.load(bytes)).getPageCount()
|
||||||
expect(drawn).toContain(fr['pdf.section.free_findings'])
|
expect(drawn).toContain(fr['pdf.section.free_findings'])
|
||||||
expect(joined()).toContain('Sensibilité au garrot')
|
expect(joined()).toContain('Sensibilité au garrot')
|
||||||
@@ -260,7 +261,7 @@ describe('PDF content on a two-observation report', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
it('sets the PDF metadata and the archive keyword', async () => {
|
it('sets the PDF metadata and the archive keyword', async () => {
|
||||||
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
|
const bytes = await exportPdf(fullReport(), 'fr')
|
||||||
const doc = await PDFDocument.load(bytes)
|
const doc = await PDFDocument.load(bytes)
|
||||||
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
|
expect(doc.getTitle()).toBe(`${fr['pdf.title.suffix.bilan']}Mistral`)
|
||||||
expect(doc.getAuthor()).toBe('Dr. Dupont')
|
expect(doc.getAuthor()).toBe('Dr. Dupont')
|
||||||
@@ -268,17 +269,28 @@ describe('PDF content on a two-observation report', () => {
|
|||||||
expect(doc.getKeywords()).toContain('faunosteo-archive/1')
|
expect(doc.getKeywords()).toContain('faunosteo-archive/1')
|
||||||
})
|
})
|
||||||
|
|
||||||
it('fetches the logos at export time', async () => {
|
it('embeds the four bundled logos without any network request', async () => {
|
||||||
await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
|
const fetchSpy = vi.fn()
|
||||||
expect(
|
vi.stubGlobal('fetch', fetchSpy)
|
||||||
fetched.some(
|
try {
|
||||||
(u) => u.endsWith('.png') || u.endsWith('Paws_in_harmony.svg'),
|
const { pdf, warnings } = await exportReportToPdf(fullReport(), sheet, {
|
||||||
),
|
locale: 'fr',
|
||||||
).toBe(true)
|
})
|
||||||
|
expect(fetchSpy).not.toHaveBeenCalled()
|
||||||
|
expect(warnings).toEqual([])
|
||||||
|
const out = await importReportFromPdf(pdf, sheet.sheet.migrationMap)
|
||||||
|
const branding = out.archive!.branding
|
||||||
|
expect(branding.headerLogo?.kind).toBe('png')
|
||||||
|
expect(branding.footerLogo?.kind).toBe('png')
|
||||||
|
expect(branding.poweredBy?.logo?.kind).toBe('png')
|
||||||
|
expect(branding.partner?.logo?.kind).toBe('svg')
|
||||||
|
} finally {
|
||||||
|
vi.unstubAllGlobals()
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
|
it('attaches osteo-report.json as a Flate EmbeddedFile, AFRelationship Data, "Faunosteo report archive v1"', async () => {
|
||||||
const bytes = await exportReportToPdf(fullReport(), sheet, { locale: 'fr' })
|
const bytes = await exportPdf(fullReport(), 'fr')
|
||||||
const doc = await PDFDocument.load(bytes)
|
const doc = await PDFDocument.load(bytes)
|
||||||
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
|
const objects = [...doc.context.enumerateIndirectObjects()].map(([, o]) =>
|
||||||
String(o),
|
String(o),
|
||||||
@@ -368,7 +380,7 @@ describe('import of the frozen v2 archive PDFs', () => {
|
|||||||
)
|
)
|
||||||
// Re-export and re-import: stable.
|
// Re-export and re-import: stable.
|
||||||
const again = await importReportFromPdf(
|
const again = await importReportFromPdf(
|
||||||
await exportReportToPdf(report, sheet, { locale: 'fr' }),
|
await exportPdf(report, 'fr'),
|
||||||
sheet.sheet.migrationMap,
|
sheet.sheet.migrationMap,
|
||||||
)
|
)
|
||||||
expect(again.report).toEqual(report)
|
expect(again.report).toEqual(report)
|
||||||
@@ -440,7 +452,7 @@ describe('import of the frozen v2 archive PDFs', () => {
|
|||||||
expect(out.unresolvedZones).toBe(1)
|
expect(out.unresolvedZones).toBe(1)
|
||||||
// The migrated document is a valid v3 document: exporting it again keeps the flags.
|
// The migrated document is a valid v3 document: exporting it again keeps the flags.
|
||||||
const again = await importReportFromPdf(
|
const again = await importReportFromPdf(
|
||||||
await exportReportToPdf(out.report, sheet, { locale: 'en' }),
|
await exportPdf(out.report, 'en'),
|
||||||
sheet.sheet.migrationMap,
|
sheet.sheet.migrationMap,
|
||||||
)
|
)
|
||||||
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
|
expect(again.report.observations[0]!.findings[0]!.unresolved).toBe(true)
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* Step 6 Phase 0 characterisation of the export flow on the editor route,
|
* Step 6 Phase 0 characterisation of the export flow on the editor route,
|
||||||
* with `exportReportToPdf` mocked: the call shape (store report, loaded
|
* with `exportReportToPdf` mocked: the call shape (store report, loaded
|
||||||
* index, locale), the download name and the failure alert. Phase 4 adapts
|
* index, locale), the download name, the failure alert and the alert that
|
||||||
* only the mocked module path and the call-shape assertion.
|
* names what the exported PDF lacks when the engine warned.
|
||||||
*/
|
*/
|
||||||
import {
|
import {
|
||||||
describe,
|
describe,
|
||||||
@@ -27,6 +27,7 @@ import { loadTestSheet, minimalReport } from '../helpers/sheet'
|
|||||||
|
|
||||||
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
|
vi.mock('@/pdf/export', () => ({ exportReportToPdf: vi.fn() }))
|
||||||
const exportMock = vi.mocked(exportReportToPdf)
|
const exportMock = vi.mocked(exportReportToPdf)
|
||||||
|
const PDF_BYTES = new Uint8Array([37, 80, 68, 70])
|
||||||
|
|
||||||
let sheet: SheetIndex
|
let sheet: SheetIndex
|
||||||
const downloads: string[] = []
|
const downloads: string[] = []
|
||||||
@@ -74,7 +75,7 @@ async function mountAndExport(label: string): Promise<void> {
|
|||||||
|
|
||||||
describe('EditorRoute export', () => {
|
describe('EditorRoute export', () => {
|
||||||
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
|
it('calls exportReportToPdf with the store report, the loaded index and the FR locale', async () => {
|
||||||
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
|
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
||||||
await mountAndExport(fr['editor.export']!)
|
await mountAndExport(fr['editor.export']!)
|
||||||
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
||||||
const [report, index, options] = exportMock.mock.calls[0]!
|
const [report, index, options] = exportMock.mock.calls[0]!
|
||||||
@@ -85,14 +86,14 @@ describe('EditorRoute export', () => {
|
|||||||
|
|
||||||
it('passes the active locale (EN)', async () => {
|
it('passes the active locale (EN)', async () => {
|
||||||
useLocaleStore.setState({ locale: 'en' })
|
useLocaleStore.setState({ locale: 'en' })
|
||||||
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
|
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
||||||
await mountAndExport(en['editor.export']!)
|
await mountAndExport(en['editor.export']!)
|
||||||
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
await waitFor(() => expect(exportMock).toHaveBeenCalledTimes(1))
|
||||||
expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' })
|
expect(exportMock.mock.calls[0]![2]).toEqual({ locale: 'en' })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('downloads bilan-<animal>-<date>.pdf through a blob URL it then revokes', async () => {
|
it('downloads bilan-<animal>-<date>.pdf through a blob URL it then revokes', async () => {
|
||||||
exportMock.mockResolvedValue(new Uint8Array([37, 80, 68, 70]))
|
exportMock.mockResolvedValue({ pdf: PDF_BYTES, warnings: [] })
|
||||||
await mountAndExport(fr['editor.export']!)
|
await mountAndExport(fr['editor.export']!)
|
||||||
await waitFor(() => expect(downloads).toHaveLength(1))
|
await waitFor(() => expect(downloads).toHaveLength(1))
|
||||||
expect(downloads[0]).toBe('bilan-Mistral-2026-10-10.pdf')
|
expect(downloads[0]).toBe('bilan-Mistral-2026-10-10.pdf')
|
||||||
@@ -103,6 +104,22 @@ describe('EditorRoute export', () => {
|
|||||||
expect(window.alert).not.toHaveBeenCalled()
|
expect(window.alert).not.toHaveBeenCalled()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('downloads then alerts editor.export_warnings naming the failed logo slots and views', async () => {
|
||||||
|
exportMock.mockResolvedValue({
|
||||||
|
pdf: PDF_BYTES,
|
||||||
|
warnings: [
|
||||||
|
{ kind: 'logo_failed', slot: 'headerLogo' },
|
||||||
|
{ kind: 'view_raster_failed', observationId: 'obs-1', viewId: 'head' },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
await mountAndExport(fr['editor.export']!)
|
||||||
|
await waitFor(() => expect(window.alert).toHaveBeenCalledTimes(1))
|
||||||
|
expect(downloads).toEqual(['bilan-Mistral-2026-10-10.pdf'])
|
||||||
|
expect(window.alert).toHaveBeenCalledWith(
|
||||||
|
'PDF exporté avec des éléments manquants : headerLogo, head. Vérifiez la console du navigateur.',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
it('alerts editor.export_failed when the export rejects', async () => {
|
it('alerts editor.export_failed when the export rejects', async () => {
|
||||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||||
exportMock.mockRejectedValue(new Error('render exploded'))
|
exportMock.mockRejectedValue(new Error('render exploded'))
|
||||||
|
|||||||
@@ -84,6 +84,8 @@ rules as the catalog):
|
|||||||
| `assets` | the SVG text of every asset a view reaches, with the catalog's content hash when known |
|
| `assets` | the SVG text of every asset a view reaches, with the catalog's content hash when known |
|
||||||
|
|
||||||
`branding` is the exact set of images, URLs and credit texts used at export;
|
`branding` is the exact set of images, URLs and credit texts used at export;
|
||||||
|
the application builds it from logos bundled at build time
|
||||||
|
(`apps/app/src/assets/brand`), so the export makes no network request.
|
||||||
`labels` is the engine dictionary in both languages. A re-export of the
|
`labels` is the engine dictionary in both languages. A re-export of the
|
||||||
archive uses these three blocks and nothing from the current application, so
|
archive uses these three blocks and nothing from the current application, so
|
||||||
a new logo, a reworded heading or a curated sheet never changes how an old
|
a new logo, a reworded heading or a curated sheet never changes how an old
|
||||||
|
|||||||
@@ -27,6 +27,8 @@ export const LEGACY_BASELINE = resolve(
|
|||||||
export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures')
|
export const FIXTURES_DIR = resolve(REPO_ROOT, 'apps/app/tests/fixtures')
|
||||||
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
export const GOLDEN_DIR = resolve(FIXTURES_DIR, 'goldens/step6')
|
||||||
export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public')
|
export const PUBLIC_DIR = resolve(REPO_ROOT, 'apps/app/public')
|
||||||
|
/** The logo files the app bundles into its export branding. */
|
||||||
|
export const BRAND_ASSETS_DIR = resolve(REPO_ROOT, 'apps/app/src/assets/brand')
|
||||||
|
|
||||||
export function readJson<T = unknown>(path: string): T {
|
export function readJson<T = unknown>(path: string): T {
|
||||||
return JSON.parse(readFileSync(path, 'utf8')) as T
|
return JSON.parse(readFileSync(path, 'utf8')) as T
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import type {
|
|||||||
SheetSnapshot,
|
SheetSnapshot,
|
||||||
} from '@faunosteo/domain'
|
} from '@faunosteo/domain'
|
||||||
import { composeHighlightedViewSvg, type Rasterizer } from '../../src'
|
import { composeHighlightedViewSvg, type Rasterizer } from '../../src'
|
||||||
import { GOLDEN_DIR, PUBLIC_DIR } from './draft'
|
import { BRAND_ASSETS_DIR, GOLDEN_DIR } from './draft'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Step 6 Phase 0 goldens, replayed on the engine: the same recorder on
|
* Step 6 Phase 0 goldens, replayed on the engine: the same recorder on
|
||||||
@@ -60,8 +60,8 @@ const PARTNER = {
|
|||||||
fallbackText: '@paws.iin.harmony',
|
fallbackText: '@paws.iin.harmony',
|
||||||
}
|
}
|
||||||
|
|
||||||
function publicPng(relative: string): { kind: 'png'; base64: string } {
|
function brandPng(file: string): { kind: 'png'; base64: string } {
|
||||||
const bytes = readFileSync(resolve(PUBLIC_DIR, relative))
|
const bytes = readFileSync(resolve(BRAND_ASSETS_DIR, file))
|
||||||
return { kind: 'png', base64: Buffer.from(bytes).toString('base64') }
|
return { kind: 'png', base64: Buffer.from(bytes).toString('base64') }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,20 +76,20 @@ export function nologosBranding(): Branding {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** The four real `public/` files (Phase 0 fetch stub). */
|
/** The four real logo files the app bundles (served by a fetch stub in Phase 0). */
|
||||||
export function logosBranding(): Branding {
|
export function logosBranding(): Branding {
|
||||||
return {
|
return {
|
||||||
siteUrl: SITE_URL,
|
siteUrl: SITE_URL,
|
||||||
headerLogo: publicPng('assets/faunosteo_logo_horizontal-512.png'),
|
headerLogo: brandPng('faunosteo-logo-horizontal-512.png'),
|
||||||
footerLogo: publicPng('assets/faunosteo-horizontal-com-512.png'),
|
footerLogo: brandPng('faunosteo-horizontal-com-512.png'),
|
||||||
poweredBy: {
|
poweredBy: { logo: brandPng('zenquality-logo-fr.png'), ...POWERED_BY },
|
||||||
logo: publicPng('brand/zenquality-logo-fr.png'),
|
|
||||||
...POWERED_BY,
|
|
||||||
},
|
|
||||||
partner: {
|
partner: {
|
||||||
logo: {
|
logo: {
|
||||||
kind: 'svg',
|
kind: 'svg',
|
||||||
svg: readFileSync(resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'), 'utf8'),
|
svg: readFileSync(
|
||||||
|
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
|
||||||
|
'utf8',
|
||||||
|
),
|
||||||
},
|
},
|
||||||
...PARTNER,
|
...PARTNER,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ import { addLinkAnnotation } from '../src/render/linkAnnotation'
|
|||||||
import { parseSvg, serializeSvg } from '../src/svg/parse'
|
import { parseSvg, serializeSvg } from '../src/svg/parse'
|
||||||
import { sanitizeSvgRoot } from '../src/svg/sanitize'
|
import { sanitizeSvgRoot } from '../src/svg/sanitize'
|
||||||
import { rasterSizeOf } from '../src/svg/view'
|
import { rasterSizeOf } from '../src/svg/view'
|
||||||
import { DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
|
import { BRAND_ASSETS_DIR, DRAFT_DIR, PUBLIC_DIR } from './helpers/draft'
|
||||||
import {
|
import {
|
||||||
FIXED_EXPORTED_AT,
|
FIXED_EXPORTED_AT,
|
||||||
logosBranding,
|
logosBranding,
|
||||||
@@ -391,10 +391,10 @@ describe('hostile SVG assets', () => {
|
|||||||
expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 })
|
expect(sizes[0]).toEqual({ widthPx: 1200, heightPx: 2400 })
|
||||||
})
|
})
|
||||||
|
|
||||||
it('horse.svg and Paws_in_harmony.svg pass with nothing removed and an identical serialisation', () => {
|
it('horse.svg and paws-in-harmony.svg pass with nothing removed and an identical serialisation', () => {
|
||||||
for (const file of [
|
for (const file of [
|
||||||
resolve(DRAFT_DIR, 'assets/horse.svg'),
|
resolve(DRAFT_DIR, 'assets/horse.svg'),
|
||||||
resolve(PUBLIC_DIR, 'Paws_in_harmony.svg'),
|
resolve(BRAND_ASSETS_DIR, 'paws-in-harmony.svg'),
|
||||||
]) {
|
]) {
|
||||||
const text = readFileSync(file, 'utf8')
|
const text = readFileSync(file, 'utf8')
|
||||||
const pristine = serializeSvg(parseSvg(text))
|
const pristine = serializeSvg(parseSvg(text))
|
||||||
|
|||||||
Reference in new issue
Block a user