pp-planer/.sisyphus/notepads/cts-presenter-app/learnings.md
Thorsten Bus 27f8402ae8 feat: Wave 4 - Song DB Management + Finalization (T20-T24)
T20: Song DB Page
- Songs/Index.vue with search, action buttons, pagination
- Upload area for .pro files (calls T23 placeholder)
- Song-Datenbank nav link added to AuthenticatedLayout
- Tests: 9 new (44 assertions)

T21: Song DB Edit Popup
- SongEditModal.vue with metadata + ArrangementConfigurator
- Auto-save with fetch (500ms debounce for text, immediate on blur)
- Tests: 11 new (53 assertions)

T22: Song DB Translate Page
- Songs/Translate.vue with two-column editor
- URL fetch or manual paste, line-count constraints
- Group headers with colors, save marks has_translation=true
- Tests: 1 new (12 assertions)

T23: .pro File Placeholders
- ProParserNotImplementedException with HTTP 501
- ProFileController with importPro/downloadPro placeholders
- German error messages
- Tests: 5 new (7 assertions)

T24: Service Finalization + Status
- Two-step finalization with warnings (unmatched songs, missing slides)
- Download placeholder toast
- isReadyToFinalize accessor on Service model
- Tests: 11 new (30 assertions)

All tests passing: 174/174 (905 assertions)
Build: ✓ Vite production build successful
German UI: All user-facing text in German with 'Du' form
2026-03-01 20:30:07 +01:00

238 lines
19 KiB
Markdown

- 2026-03-01: Fuer 1920x1080 Slide-Output ohne Upscaling funktioniert in Intervention Image v3 die Kombination aus schwarzer Canvas (`create()->fill('000000')`), `scaleDown(width: 1920, height: 1080)` und zentriertem `place(...)` stabil.
- 2026-03-01: Bei Fake-Storage in Tests muessen Zielordner vor direktem Intervention-`save()` explizit erstellt werden (`makeDirectory`/`mkdir`), sonst wirft Intervention `NotWritableException`.
- 2026-03-01: Fuer Testverifikation von Letterbox/Pillarbox sind farbige PNG-Testbilder sinnvoller als `UploadedFile::fake()->image(...)`, weil Fake-Bilder sonst komplett schwarz sein koennen.
- 2026-03-01: CTS-Sync laeuft stabil mit `EventRequest::where("from", heute)` + `EventAgendaRequest::fromEvent(...)->get()`, wenn Services per `cts_event_id` und Agenda-Songs per (`service_id`,`order`) upserted werden; CCLI-Matching bleibt strikt auf `songs.ccli_id` und setzt nur dann `song_id`/`matched_at`.
- 2026-03-01: SongController CRUD nutzt `auth:sanctum` Middleware; `actingAs()` in Tests funktioniert damit problemlos (Sanctum unterstuetzt Session-Auth in Tests).
- 2026-03-01: SQLite gibt `date`-Spalten als `YYYY-MM-DD 00:00:00` zurueck statt `YYYY-MM-DD` — Accessor muss `substr($date, 0, 10)` nutzen fuer saubere Date-Only Werte.
- 2026-03-01: `Attribute::get()` in Laravel 12 fuer berechnete Accessors statt altem `get{Name}Attribute()` Pattern. Snake_case `last_used_in_service` mapped automatisch auf `lastUsedInService()` Methode.
- 2026-03-01: Default-Gruppen (Strophe 1=#3B82F6, Refrain=#10B981, Bridge=#F59E0B) und Default-Arrangement 'Normal' werden automatisch bei Song-Erstellung via SongService erzeugt.
- 2026-03-01: `Rule::unique('songs', 'ccli_id')->ignore($songId)->whereNull('deleted_at')` stellt sicher, dass Soft-Deleted Songs die Unique-Constraint nicht blockieren.
- 2026-03-01: `bootstrap/app.php` braucht explizit `api: __DIR__.'/../routes/api.php'` in `withRouting()` — ist nicht automatisch registriert in Laravel 12.
- 2026-03-01: Service-Listenstatus laesst sich performant in einem Query aggregieren via `withCount(...)` fuer Song-Metriken plus `addSelect`-Subqueries fuer `has_sermon_slides` und datumsabhaengige `info_slides_count` (inkl. globaler `information`-Slides mit `service_id = null`).
- 2026-03-01: TranslationService line-count distribution: iterate groups (by order) → slides (by order), for each slide count lines in `text_content`, then slice that many lines from the translated text array. `array_slice` + offset tracking works cleanly.
- 2026-03-01: URL scraping is best-effort only: `Http::timeout(10)->get($url)` + `strip_tags()` + `trim()`. Return null on any failure — no exceptions bubble up. PHP 8.1+ allows `catch (\Exception)` without variable capture.
- 2026-03-01: Translation routes: `POST /api/translation/fetch-url` (preview), `POST /api/songs/{song}/translation/import` (save), `DELETE /api/songs/{song}/translation` (remove). All under `auth:sanctum` middleware.
- 2026-03-01: `removeTranslation` uses a two-step approach: collect slide IDs via `SongSlide::whereIn('song_group_id', $song->groups()->pluck('id'))` then bulk-update `text_content_translated = null`, avoiding N+1 queries.
- 2026-03-01: Der Arrangement-Konfigurator bleibt stabil bei mehrfachen Gruppeninstanzen, wenn die Sequenz mit Vue-Keys im Muster `${group.id}-${index}` gerendert und die Reihenfolge nach jedem Drag-End sofort per `router.put(..., { preserveScroll: true })` gespeichert wird.
## [2026-03-01] Wave 2 Complete — T8-T13
### T11: Arrangement Configurator
- ArrangementController: store (clone from default), clone (duplicate existing), update (reorder groups), destroy (prevent last)
- ArrangementConfigurator.vue: vue-draggable-plus with clone mode for group pills
- **CRITICAL**: Vue key for repeating groups MUST be `${group.id}-${index}` NOT just `group.id` (groups repeat in arrangements)
- Color picker integration: group_colors array in update payload, applied to SongGroup records
- Default arrangement protection: if deleting is_default=true, promote next arrangement to default
- Tests: 4 passing (17 assertions)
### T12: Song Matching Service
- SongMatchingService: autoMatch (CCLI), manualAssign, requestCreation (email), unassign
- ServiceSongController: API endpoints for /api/service-songs/{id}/assign, /request, /unassign
- Auto-match runs during CTS sync (ChurchToolsService updated to call autoMatch)
- MissingSongRequest mailable already existed from T7, reused here
- matched_at timestamp tracks when assignment occurred
- Tests: 14 passing (33 assertions)
### T13: Translation Service
- TranslationService: fetchFromUrl (HTTP + strip_tags), importTranslation (line-count distribution), removeTranslation
- TranslationController: POST /translation/fetch-url, POST /songs/{song}/translation/import, DELETE /songs/{song}/translation
- Line-count algorithm: for each slide (ordered by group.order, slide.order), take N lines from translated text where N = original slide line count
- Best-effort URL scraping: Http::timeout(10), catch all exceptions, return null on failure
- has_translation flag on Song model tracks translation state
- Tests: 18 passing (18 assertions)
### Wave 2 Summary
- All 6 tasks completed in parallel delegation
- T11 timed out during polling but work completed successfully
- Total: 103 tests passing (488 assertions)
- Vite build: ✓ successful
- Commit: d915f8c (27 files, +3951/-25 lines)
### Next: Wave 3 (T14-T19)
- Service Edit page layout + 4 blocks (Information, Moderation, Sermon, Songs)
- Song preview modal + PDF download
- All blocks integrate SlideUploader/SlideGrid from T10
- ArrangementConfigurator from T11 embedded in Songs block
## [2026-03-01] T16: Moderation Block (Service-Specific Slides)
- ModerationBlock.vue: Simple wrapper around SlideUploader + SlideGrid with `showExpireDate=false`
- Filtering: `type='moderation' AND service_id = current_service` via computed property
- SlideUploader/SlideGrid already support `showExpireDate` prop (from T10)
- Service-specific filtering ensures moderation slides from Service A don't appear in Service B
- No expire_date field anywhere in UI (unlike Information block)
- Tests: 5 passing (14 assertions) — verifies service-specific isolation
- Vite build: ✓ successful
### T17: Sermon Block (Service-Specific Slides)
- SermonBlock.vue: Identical to ModerationBlock but with `type='sermon'`
- Filters slides: `type='sermon' AND service_id = current_service`
- Uses SlideUploader with `type="sermon"`, `serviceId={current}`, `showExpireDate={false}`
- Uses SlideGrid with `showExpireDate={false}`
- Tests: 5 passing (14 assertions) — verifies service-specific filtering, type isolation, no expire_date
- Build: ✓ successful
- 2026-03-01: Songs-Block nutzt fuer unmatched CTS-Songs eine lokale Such-Eingabe plus gefiltertes Select (Titel/CCLI), danach `POST /api/service-songs/{id}/assign` und soft reload nur von `serviceSongs`.
- 2026-03-01: Arrangement-Auswahl wird ueber ein neues `arrangement-selected` Event aus dem ArrangementConfigurator nach oben gemeldet und per `PATCH /api/service-songs/{id}` als `song_arrangement_id` sofort gespeichert.
- 2026-03-01: Translation-Toggle im Songs-Block speichert direkt per `PATCH /api/service-songs/{id}` (`use_translation`) und bleibt so ohne separaten Save-Button konsistent mit dem Auto-Save-Prinzip.
## [2026-03-01] T15: Information Block (Slides + Expire Dates)
- InformationBlock.vue: Wraps SlideUploader + SlideGrid with `showExpireDate=true` and `serviceId=null` (global slides)
- Server-side filtering in ServiceController.edit(): `type='information' AND expire_date >= service.date AND (service_id IS NULL OR service_id = current)`
- Information slides are GLOBAL — not tied to a specific service, appear in all services where `expire_date >= service.date`
- The `whereNull('deleted_at')` in edit() query is redundant with SoftDeletes trait but harmless
- Slides without expire_date are excluded from information block (require scheduling)
- SlideUploader passes `serviceId=null` for information slides (they're global, not service-specific)
- ExpiringSoonCount computed: badges warn when slides expire within 3 days of service date
- Edit.vue updated: replaced placeholder for 'information' block key with actual InformationBlock component
- `router.reload({ preserveScroll: true })` used for refreshing page after slide upload/delete/update
- Tests: 7 passing (105 assertions) — covers expire date filtering, global visibility, soft-delete exclusion, type isolation, null expire_date, ordering
- Full suite: 122 tests passing (658 assertions)
- Vite build: ✓ successful
## [2026-03-01] T14: Service Edit Page Layout + Routing
### ServiceController::edit()
- Eager-loads `serviceSongs` (ordered), `serviceSongs.song`, `serviceSongs.arrangement`, `slides`
- Information slides query is complex: global (service_id=null) + service-specific, filtered by expire_date >= service.date
- Moderation/sermon slides filtered from loaded `$service->slides` collection via `->where('type', ...)`
- Service data returned as explicit array (not full model) to control frontend shape
- serviceSongs mapped to include nested song/arrangement data as null-safe arrays
### Edit.vue Page Pattern
- Uses collapsible accordion blocks (expandedBlocks ref with boolean per key)
- 4 blocks: Information, Moderation, Predigt, Songs — each with colored gradient icon, badge count, chevron toggle
- Block content area is placeholder div (T15-T18 will replace with actual components)
- Vue Transition with max-h trick for collapse animation
- `router.get(route('services.index'))` for back navigation
- German date format: `toLocaleDateString('de-DE', { weekday: 'long', day: '2-digit', month: 'long', year: 'numeric' })`
### Index.vue Integration
- "Bearbeiten" button now uses `router.get(route('services.edit', service.id))` instead of showComingSoon
### Route
- `GET /services/{service}/edit``services.edit` named route, uses implicit model binding
- Placed after finalize/reopen POST routes in web.php
### Test Pattern
- PHPUnit style (not Pest) in this project's ServiceControllerTest
- `$this->withoutVite()` required for Inertia page assertion tests
- `assertInertia(fn ($page) => $page->component(...)->has(...)->where(...))` for deep prop assertions
- Auth test: unauthenticated GET redirects to login route
## [2026-03-01] T19: Song Preview Modal + PDF Download
### SongPdfController
- Previous session left corrupted file: missing closing `}` for class and missing `use Illuminate\Http\Response` import
- Controller has two methods: `preview()` returns JSON (for Vue modal), `download()` returns PDF via barryvdh/laravel-dompdf
- `buildGroupsInOrder()` extracted as private helper used by both methods
- Route: `GET /songs/{song}/arrangements/{arrangement}/pdf` -> `songs.pdf`
- `abort_unless($arrangement->song_id === $song->id, 404)` prevents cross-song arrangement access
### PDF Template
- **CRITICAL**: Old-school CSS only (NO Tailwind) — DomPDF cannot render utility classes
- DejaVu Sans font (`font-family: 'DejaVu Sans', sans-serif`) handles German umlauts correctly
- `page-break-inside: avoid` on `.group-section` keeps groups together across pages
- `white-space: pre-wrap` preserves line breaks in slide text content
- Copyright footer uses `border-top` separator, `font-size: 8pt`, muted color
### SongPreviewModal.vue
- Teleport to body for z-index isolation
- Click-outside dismiss via `@click` on backdrop with `e.target === e.currentTarget` check
- Escape key listener added on mount, removed on unmount
- Groups sorted by `ag.order`, slides by `slide.order` in computed property
- Side-by-side translation display using `grid grid-cols-2 gap-4` when `useTranslation && slide.text_content_translated`
- PDF download link as `<a>` with `target="_blank"` (not router navigation)
### Tests (Pest style)
- 9 tests, 25 assertions — covers: content type, filename, groups in order, translations, copyright, 404 for wrong song, auth redirect, umlauts, empty arrangement
- DomPDF `download()` returns `Illuminate\Http\Response` with `Content-Disposition: attachment; filename=...`
- `assertHeader('Content-Type', 'application/pdf')` verifies PDF generation succeeded
- Content-Disposition header contains slugified `song.title` + `arrangement.name`
### T19 Update — Preview JSON Endpoint + Modal Refactor
- Added `preview()` method to SongPdfController returning JSON for Vue modal consumption
- Route: `GET /songs/{song}/arrangements/{arrangement}/preview` -> `songs.preview`
- SongPreviewModal.vue now fetches data via `fetch()` when modal opens (not props-based)
- Reuses existing Modal.vue component (dialog-based with Transition animations)
- `contrastColor()` utility calculates white/dark text based on group background luminance (0.299*R + 0.587*G + 0.114*B threshold)
- Preview tests: 4 additional tests (arrangement order, translations, 404 mismatch, auth) — total 13 tests for SongPdfTest
- barryvdh/laravel-dompdf v3.1.1 installed (dompdf v3.1.4 engine)
- Full suite: 137 tests passing (759 assertions)
## [2026-03-01] T23: .pro File Upload + Download Placeholders
- ProParserNotImplementedException: Custom exception extending Exception with German error message
- Exception renders as HTTP 501 with JSON response: `{ message, error: 'ProParserNotImplemented' }`
- ProFileController: Two placeholder methods (importPro, downloadPro) both throw the exception
- Routes: POST /api/songs/import-pro, GET /api/songs/{song}/download-pro under auth:sanctum middleware
- Tests: 5 passing (7 assertions) — covers 501 responses, German messages, auth requirements, 404 for missing song
- Both endpoints return 501 Not Implemented until .pro parser spec is finalized
- Unauthenticated API requests return 401 (via postJson/getJson helpers)
- Model binding returns 404 for non-existent songs before controller is reached
## [2026-03-01] T20: Song DB Page (List + Search + Filters)
- Songs/Index.vue fetches data from API (`/api/songs`) rather than Inertia props — better for dynamic debounced search
- Web route is a simple closure rendering `Inertia::render('Songs/Index')` with no props — API handles all data
- AuthenticatedLayout already had conditional Song-Datenbank NavLink checking `$page.props.ziggy?.routes?.['songs.index']`; adding route auto-enables it
- ResponsiveNavLink for mobile menu needed manual addition (wasn't conditionally pre-wired like desktop)
- `$this->withoutVite()` required in Inertia page render tests (ViteException without build manifest)
- Upload area is placeholder: shows German error message for .pro imports (T23 implements actual parser)
- Action buttons emit events (`$emit('edit', song)`) for modal integration (T21) and download (T23)
- Translate action links to `/songs/{id}/translate` route (T22)
- Soft-delete with confirm modal uses Teleport + Transition for proper z-index and animation
- Pagination with ellipsis range calculation: `pageRange()` shows first, last, ±2 around current
- Tests: 9 passing (44 assertions), full suite: 162 tests (840 assertions)
- Vite build: ✓ successful with new page bundle
## [2026-03-01] T24: Service Finalization + Status Management
### Finalization with Prerequisite Warnings
- Changed `ServiceController::finalize()` from redirect-based to JSON response for two-step confirmation flow
- `Service::finalizationStatus()` method returns `['ready' => bool, 'warnings' => string[]]` — checks songs matched, arrangements, sermon slides
- Song counts only warn when `$totalSongs > 0` (0/0 songs is not a problem)
- Frontend sends `confirmed: false` first call; if `needs_confirmation` returned, shows dialog; second call sends `confirmed: true` to force finalize
- `request()->boolean('confirmed')` cleanly handles the JSON boolean from fetch()
- `isReadyToFinalize` accessor uses `Attribute::get()` pattern from Laravel 12
### Download Placeholder
- `GET /services/{service}/download` returns JSON `{ message: '...' }` — placeholder for future show generation
- Route parameter kept as `Service $service` for model binding even though placeholder doesn't use it
### Frontend Pattern
- Finalize uses native `fetch()` with JSON instead of Inertia `router.post()` because we need to inspect the response before deciding whether to show the confirmation dialog or reload
- `router.reload({ preserveScroll: true })` after successful finalize to refresh the Inertia page data
- Confirmation dialog uses `<Teleport to="body">` with backdrop click-to-dismiss
- Toast system with types (success/warning/info) and auto-dismiss after 3.5s
### Test Pattern
- Updated existing `ServiceControllerTest::test_service_kann_abgeschlossen_werden` to use `postJson` with `confirmed: true`
- 11 new Pest tests covering: warnings returned, confirmed override, direct finalize, partial warnings, reopen, download placeholder, auth checks, model accessor
- Full suite: 162 tests, 840 assertions
- 2026-03-01: Die Translate-Seite bleibt stabil, wenn die Verteilung und der Export immer strikt in `group.order` + `slide.order` laufen und jede Uebersetzungs-Textarea direkt auf die Original-Zeilenanzahl begrenzt sowie mit Leerzeilen aufgefuellt wird.
## [2026-03-01] T21: Song DB Edit Popup (Metadata + Arrangement)
### SongEditModal.vue
- Uses `fetch()` + `useDebounceFn` (VueUse) instead of `useAutoSave` composable because SongController is an API route (`/api/songs/{id}`) returning JSON — Inertia `router.put()` in `useAutoSave` expects Inertia responses and fails with JSON APIs
- CSRF token from `document.querySelector('meta[name="csrf-token"]')` required for fetch-based PUT requests
- Teleport to body pattern (from SongPreviewModal T19): backdrop `@click` with `e.target === e.currentTarget` for click-outside dismiss
- Escape key listener: `onMounted`/`onUnmounted` lifecycle for document-level keydown listener
- Auto-save: 500ms debounce for text inputs via `useDebounceFn`, immediate save on blur via `debouncedSave.cancel()` then direct `performSave()`
- ArrangementConfigurator requires `arrangements` prop with nested `groups` array — must transform API response `arrangement_groups[].song_group_id` into full group objects by looking up in `songData.groups`
- Save status indicator: `saving`/`saved` refs with 2s auto-clear timeout for "Gespeichert" feedback
- Amber color scheme to match existing Songs/Index.vue design language (not indigo)
### Integration into Songs/Index.vue
- Index.vue already had `$emit('edit', song)` on Bearbeiten button — replaced with `openEditModal(song)` function
- `editSongId` ref + `showEditModal` ref control modal visibility
- `@updated` event from modal triggers `fetchSongs(meta.value.current_page)` to refresh the list after edits
### Tests
- 11 Pest tests, 53 assertions — covers: show full detail, title/ccli/copyright auto-save, null clearing, response structure, validation (required title, unique ccli), auth, 404 for deleted/nonexistent
- Full suite: 175 tests passing (925 assertions)
- Vite build: ✓ successful