pp-planer/app/Services/CcliImportService.php
Thorsten Bus ae42b48753 feat(songs): per-song sections + section editing; fix CCLI import bugs
Refactor lyric storage so each song owns its sections instead of sharing
global labels. Adds song_sections (per song+label) owning song_slides;
labels stay global ProPresenter group tags (name/color/macro). Arrangements
now reference sections, so editing/importing one song no longer corrupts
others that share a label name.

- New: song_sections table + migration with safe backfill; SongSection,
  SongArrangementSection models; SongSectionController (edit/add/delete
  sections, immediate persistence) wired into SongEditModal.
- Refactor writers/readers: CcliImport, ProImport, SongService,
  ArrangementController, SongController, ProExport, PDF, Translation
  (translation reset now section-scoped), CCLI pairing.
- CCLI import fixes: parse SongSelect copy-icon format (German "Vers"
  abbrev + trailing author), fill empty CTS-synced songs instead of
  blocking as duplicate, distinct label colors per section kind,
  import&edit/existing-song open the edit modal (no 404/405), teleport
  paste dialog above assign dialog, preview shows section content,
  correct SongSelect search URL, copy-icon instructions.
- Bookmarklet clicks #generalCopyLyricsButton and captures clipboard;
  serves correct host from request.
- Export: embed key-visual/background under fixed bundle-relative names.
- Tests updated for the section model; new section + isolation coverage.
2026-05-31 14:45:47 +02:00

184 lines
6.4 KiB
PHP

<?php
namespace App\Services;
use App\Exceptions\DuplicateCcliSongException;
use App\Models\ApiRequestLog;
use App\Models\Label;
use App\Models\Setting;
use App\Models\Song;
use App\Models\SongArrangement;
use App\Models\SongArrangementLabel;
use App\Models\SongSection;
use App\Services\DTO\ParsedCcliSection;
use App\Services\DTO\ParsedCcliSong;
use App\Support\CcliLabels;
use Illuminate\Support\Facades\DB;
use RuntimeException;
final class CcliImportService
{
private const LABEL_KIND_COLORS = [
'Verse' => '#3B82F6',
'Chorus' => '#10B981',
'Bridge' => '#F59E0B',
'Pre-Chorus' => '#8B5CF6',
'Tag' => '#EC4899',
'Ending' => '#EF4444',
'Intro' => '#14B8A6',
'Interlude' => '#6366F1',
'Outro' => '#F97316',
'Misc' => '#64748B',
];
public function __construct(
private readonly CcliPasteParser $parser,
) {}
/** @return array{song: Song, status: 'created'|'restored', warnings: string[]} */
public function import(string $rawText, ?string $sourceUrl = null): array
{
$startedAt = microtime(true);
$parsed = $this->parser->parse($rawText);
if ($parsed->ccliId === null || trim($parsed->ccliId) === '') {
throw new RuntimeException('Keine CCLI-Nummer gefunden — bitte vollständige SongSelect-Liedseite einfügen.');
}
$song = Song::withTrashed()->where('ccli_id', $parsed->ccliId)->first();
$status = 'created';
if ($song !== null && ! $song->trashed() && $this->songHasContent($song)) {
throw new DuplicateCcliSongException($song->id);
}
if ($song !== null) {
$status = 'restored';
}
return DB::transaction(function () use ($parsed, $sourceUrl, $song, $status, $startedAt): array {
if ($song !== null && $song->trashed()) {
$song->restore();
}
$song = $this->upsertSong($parsed, $sourceUrl, $song);
$warnings = [];
$translationLanguage = Setting::get('default_translation_language', 'DE');
if ($translationLanguage === null || trim($translationLanguage) === '') {
$warnings[] = 'Keine Standard-Übersetzungssprache gesetzt, DE wird verwendet.';
}
$sectionIds = [];
$hasTranslation = false;
foreach ($parsed->sections as $order => $parsedSection) {
$label = $this->resolveLabel($parsedSection);
$section = SongSection::firstOrCreate(
['song_id' => $song->id, 'label_id' => $label->id],
['order' => $order + 1],
);
$section->update(['order' => $order + 1]);
$sectionIds[] = $section->id;
$section->slides()->delete();
foreach ($parsedSection->lines as $slideOrder => $line) {
$translatedLine = $parsedSection->linesTranslated[$slideOrder] ?? null;
$hasTranslation = $hasTranslation || ($translatedLine !== null && trim($translatedLine) !== '');
$section->slides()->create([
'order' => $slideOrder + 1,
'text_content' => $line,
'text_content_translated' => $translatedLine,
]);
}
}
$song->update([
'has_translation' => $hasTranslation,
'imported_from_ccli_at' => now(),
'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
]);
$arrangement = SongArrangement::updateOrCreate(
['song_id' => $song->id, 'name' => 'normal'],
['is_default' => true],
);
SongArrangementLabel::where('song_arrangement_id', $arrangement->id)->delete();
foreach ($sectionIds as $order => $sectionId) {
SongArrangementLabel::create([
'song_arrangement_id' => $arrangement->id,
'song_section_id' => $sectionId,
'order' => $order + 1,
]);
}
$song = $song->fresh(['arrangements.arrangementSections.section.slides', 'arrangements.arrangementSections.section.label']);
ApiRequestLog::create([
'method' => 'import',
'endpoint' => 'paste',
'status' => 'success',
'request_context' => ['ccli_id' => $parsed->ccliId, 'mode' => $status],
'response_summary' => "Song {$status}: {$song->title}",
'response_body' => null,
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000),
]);
return ['song' => $song, 'status' => $status, 'warnings' => $warnings];
});
}
private function upsertSong(ParsedCcliSong $parsed, ?string $sourceUrl, ?Song $song): Song
{
$songData = [
'title' => $parsed->title,
'author' => $parsed->author,
'copyright_text' => $parsed->copyrightText,
'copyright_year' => $parsed->year,
'publisher' => $parsed->copyrightText,
'ccli_source_url' => $sourceUrl ?? $parsed->sourceUrl,
];
if ($song !== null) {
$song->update($songData);
return $song;
}
return Song::create(array_merge($songData, ['ccli_id' => $parsed->ccliId]));
}
private function songHasContent(Song $song): bool
{
return $song->sections()->whereHas('slides')->exists();
}
private function resolveLabel(ParsedCcliSection $section): Label
{
$canonicalKind = CcliLabels::normalizeLabelName($section->kind);
$canonicalLabelName = CcliLabels::normalizeLabelName(
$section->kind.($section->number ? ' '.$section->number : ''),
);
return Label::firstOrCreate(
['name' => $canonicalLabelName],
['color' => $this->labelColor($canonicalKind), 'last_imported_at' => now()],
);
}
private function labelColor(string $canonicalKind): string
{
if (array_key_exists($canonicalKind, self::LABEL_KIND_COLORS)) {
return self::LABEL_KIND_COLORS[$canonicalKind];
}
$colors = array_values(self::LABEL_KIND_COLORS);
return $colors[crc32($canonicalKind) % count($colors)];
}
}