[Bezeichnung, Rolle]. */ private const SECTIONS = [ 'preparation' => 'Vorbereitung', 'execution' => 'Durchführung', 'trainer_notes' => 'Trainerhinweise', ]; public function configured(): bool { return filled(config('services.shinkan.url')) && filled(config('services.shinkan.key')); } /** * Zustand der Anbindung ohne Werte: Adresse und Schlüssel stehen nur in der Umgebungsdatei des Servers. * * @return array{url: bool, key: bool, host: string|null} */ public function status(): array { $url = (string) config('services.shinkan.url'); return [ 'url' => filled($url), 'key' => filled(config('services.shinkan.key')), 'host' => filled($url) ? (parse_url($url, PHP_URL_HOST) ?: null) : null, ]; } /** * Verbindung prüfen, ohne etwas zu speichern. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier * wird nur gezählt, was die Quelle für Lara & Felix bereitstellt. * * @return array{ok: bool, message: string} */ public function check(): array { if (! $this->configured()) { return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse und Schlüssel fehlen in der Umgebung des Servers.']; } try { $catalog = $this->get('/catalog'); } catch (Throwable $exception) { return ['ok' => false, 'message' => 'Die Verbindung ist fehlgeschlagen: '.$this->plain($exception)]; } $count = count((array) ($catalog['exercises'] ?? [])); return ['ok' => true, 'message' => 'Die Verbindung funktioniert. Die Quelle stellt '.$count.($count === 1 ? ' Übung' : ' Übungen').' bereit. Es wurde nichts übernommen.']; } public function fetch(): ExerciseImportRun { $run = ExerciseImportRun::query()->create(['status' => 'laeuft', 'started_at' => now()]); if (! $this->configured()) { return $this->finish($run, 'fehler', error: 'Die Anbindung ist nicht eingerichtet. Adresse und Schlüssel fehlen in der Umgebung.'); } $previous = ExerciseImportRun::query()->where('status', 'ok')->orderByDesc('id')->value('cursor'); $counts = ['added' => 0, 'updated' => 0, 'removed' => 0]; try { try { $catalog = $this->get('/catalog', $previous === null ? [] : ['cursor' => $previous]); } catch (RequestException $exception) { // Ein ungültiger Cursor heißt nur: ganz neu abgleichen. if ($previous === null || $exception->response->status() !== 400) { throw $exception; } $catalog = $this->get('/catalog'); } foreach ((array) ($catalog['changes'] ?? []) as $change) { $id = (string) ($change['source_id'] ?? ''); $kind = (string) ($change['change'] ?? ''); if ($id === '') { continue; } if ($kind === 'removed') { ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', $id) ->update(['availability' => ExerciseSource::WITHDRAWN]); $counts['removed']++; continue; } $document = $this->get('/catalog/'.$id); $this->record($document); $counts[$kind === 'added' ? 'added' : 'updated']++; } foreach ((array) ($catalog['exercises'] ?? []) as $listed) { ExerciseSource::query()->where('source_system', 'shinkan')->where('source_id', (string) ($listed['source_id'] ?? '')) ->update(['availability' => ExerciseSource::PROVIDED, 'last_seen_at' => now()]); } } catch (Throwable $exception) { return $this->finish($run, 'fehler', $counts, 'Der Abruf ist fehlgeschlagen: '.$this->plain($exception).' Der gespeicherte Stand blieb unverändert.'); } return $this->finish($run, 'ok', $counts, null, (string) ($catalog['next_cursor'] ?? $previous)); } /** * Hält einen abgerufenen Inhaltsstand fest. Derselbe Stand (Quelle und Prüfsumme) wird nie doppelt gespeichert. * * @param array $document Detail der Quelle mit `source_id`, `content_hash` und den Feldern */ public function record(array $document): ExerciseSourceSnapshot { $id = (string) ($document['source_id'] ?? ''); $hash = (string) ($document['content_hash'] ?? ''); if ($id === '' || $hash === '') { throw new DomainRuleException('Der Abruf liefert keine Quellkennung oder Prüfsumme.'); } return DB::transaction(function () use ($id, $hash, $document): ExerciseSourceSnapshot { $source = ExerciseSource::query()->firstOrCreate( ['source_system' => 'shinkan', 'source_id' => $id], ['title' => (string) ($document['title'] ?? '')], ); $source->update([ 'title' => (string) ($document['title'] ?? $source->title), 'availability' => ExerciseSource::PROVIDED, 'last_hash' => $hash, 'last_seen_at' => now(), ]); return $source->snapshots()->firstOrCreate( ['content_hash' => $hash], ['payload' => $document, 'fetched_at' => now()], ); }); } /** * Zustand einer Quellübung für die Redaktion. */ public function state(ExerciseSource $source): string { $latest = $source->latestSnapshot(); return match (true) { $source->availability === ExerciseSource::WITHDRAWN => 'nicht_mehr_bereitgestellt', $latest === null => 'neu', $latest->adopted_version_id !== null => 'uebernommen', $source->composition_id !== null => 'geaendert', default => 'neu', }; } /** * Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie, * entsteht keine zweite Fassung. Lokale Ergänzungen der bisherigen Fassung werden übernommen. */ public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null): CompositionVersion { $snapshot->refresh(); if ($snapshot->adopted_version_id !== null) { return $snapshot->adoptedVersion; } return DB::transaction(function () use ($snapshot, $actor): CompositionVersion { $source = $snapshot->source; $document = $snapshot->payload; $content = app(ContentService::class); $title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan'; $composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? '')); $previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first(); $variants = []; $members = []; foreach (self::SECTIONS as $field => $label) { $text = trim((string) ($document[$field] ?? '')); if ($text !== '') { $members[] = [ 'role' => $label, 'target' => $this->section($source, $field, $title.' · '.$label, $text), 'origin' => 'quelle', ]; } } foreach ((array) ($document['variants'] ?? []) as $variant) { $key = (string) ($variant['id'] ?? ''); if ($key === '') { continue; } $variants[] = [ 'key' => $key, 'name' => (string) ($variant['name'] ?? '') ?: 'Variante', 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle', ]; $changes = trim((string) ($variant['execution_changes'] ?? '')); if ($changes !== '') { $members[] = [ 'role' => 'Abweichung der Durchführung', 'target' => $this->section($source, 'variant:'.$key, $title.' · '.($variant['name'] ?? 'Variante').' · Abweichung', $changes), 'variant' => $key, 'origin' => 'quelle', ]; } } [$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key')); $version = $content->publishComposition( $composition, [...$members, ...$localMembers], $actor, 'Übernahme aus Shinkan', [ 'learning_goal' => $document['goal'] ?? null, 'duration_minutes' => $document['duration_min'] ?? null, 'duration_max' => $document['duration_max'] ?? null, 'material_note' => $document['equipment'] ?? null, 'source_snapshot_id' => $snapshot->id, ], [...$variants, ...$localVariants], ); $snapshot->update(['adopted_version_id' => $version->id]); $source->update(['composition_id' => $composition->id]); return $version; }); } /** * Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer * Quellvariante, die es nicht mehr gibt, wandert in den gemeinsamen Teil, damit nichts verloren geht. * * @param list $sourceVariantKeys * @return array{0: list>, 1: list>} */ private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys): array { if ($previous === null) { return [[], []]; } $localVariants = $previous->variants->where('origin', 'lokal')->map(fn (CompositionVersionVariant $variant): array => [ 'key' => $variant->key, 'name' => $variant->name, 'description' => $variant->description, 'origin' => 'lokal', ])->values()->all(); $known = [...$sourceVariantKeys, ...array_column($localVariants, 'key')]; $members = []; foreach ($previous->members->where('origin', 'lokal') as $member) { $variant = $member->variant?->key; $members[] = [ 'role' => $member->role, 'note' => $member->placement_note, 'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion, 'variant' => $variant !== null && in_array($variant, $known, true) ? $variant : null, 'requirement' => $member->requirement, 'selection' => $member->variant_selection, 'origin' => 'lokal', ]; } return [$members, $localVariants]; } /** * Die Textfassung eines Abschnitts der Quelle. Unveränderter Text bleibt dieselbe Fassung. */ private function section(ExerciseSource $source, string $field, string $title, string $text): ContentElementVersion { $content = app(ContentService::class); $ref = 'shinkan:'.$source->source_id.':'.$field; $element = ContentElement::query()->where('source_ref', $ref)->first(); if ($element === null) { $element = $content->createElement('text', 'text', $title); $element->source_ref = $ref; $element->save(); } $latest = $element->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first(); return $latest !== null && trim((string) $latest->body) === $text ? $latest : $content->publishElementVersion($element, $text, [], 'Übernahme aus Shinkan'); } private function createComposition(string $title, string $summary): Composition { $composition = app(ContentService::class)->createComposition($title, CompositionKind::Exercise); $composition->editorial_content_kind_id = EditorialContentKind::query()->where('slug', 'uebung')->value('id'); if ($summary !== '') { $composition->summary = $summary; } $composition->save(); return $composition; } /** * @param array $query * @return array */ private function get(string $path, array $query = []): array { $response = Http::withToken((string) config('services.shinkan.key')) ->acceptJson() ->timeout(20) ->get(rtrim((string) config('services.shinkan.url'), '/').'/api/distribution/v1'.$path, $query) ->throw(); $json = $response->json(); if (! is_array($json)) { throw new DomainRuleException('Die Antwort der Quelle ist kein gültiges JSON.'); } return $json; } /** * @param array{added?: int, updated?: int, removed?: int} $counts */ private function finish(ExerciseImportRun $run, string $status, array $counts = [], ?string $error = null, ?string $cursor = null): ExerciseImportRun { $run->update([ 'status' => $status, 'cursor' => $cursor, 'added' => $counts['added'] ?? 0, 'updated' => $counts['updated'] ?? 0, 'removed' => $counts['removed'] ?? 0, 'error' => $error, 'finished_at' => now(), ]); return $run; } /** Fehlertext ohne Adresse und Schlüssel. */ private function plain(Throwable $exception): string { if ($exception instanceof RequestException) { return 'Die Quelle antwortete mit Status '.$exception->response->status().'.'; } return $exception instanceof DomainRuleException ? $exception->getMessage() : 'Die Quelle ist nicht erreichbar.'; } }