Files
laraundfelix/app/Domain/Catalog/ShinkanImport.php
T
LarsandClaude Sonnet 5.5 26ca79cd22 Pflege Adresse und Zugangsschlüssel der Shinkan-Anbindung in der Verwaltung
Werte aus der Umgebung des Servers haben Vorrang, sonst gilt der in der Verwaltung gepflegte. Der Schlüssel liegt
verschlüsselt in site_settings und wird nie angezeigt. Änderung nur für Katalog- und Systemverwalter.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 17:38:00 +01:00

390 lines
15 KiB
PHP

<?php
namespace App\Domain\Catalog;
use App\Models\User;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* Übernahme von Übungen aus dem Shinkan-Katalog (`GET /api/distribution/v1/catalog` und Detailroute) in denselben
* Übungsbestand wie die lokalen Übungen.
*
* Grundsätze:
* - Die Quellübung ist an ihre stabile Kennung gebunden. Jeder Inhaltsstand (Prüfsumme der Quelle) wird genau einmal
* festgehalten; ein wiederholter Abruf erzeugt nichts Neues.
* - Eine lokale Fassung entsteht nur durch die bewusste Übernahme ({@see adopt}) und ist danach unveränderlich. Lokale
* Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten.
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
* rechtliche Sperre ist der lokale `block`.
* - Medien des Katalogs sind Metadaten ohne Datei. Sie begründen weder eine Ausgabe noch eine Nutzungsberechtigung und
* stehen nie in einem Artikel-Stand.
* - Ein fehlgeschlagener Abruf verändert den gespeicherten Stand nicht und rückt den Cursor nicht vor.
*/
class ShinkanImport
{
/** Abschnitte der Quelle in Lesereihenfolge: Feld => [Bezeichnung, Rolle]. */
private const SECTIONS = [
'preparation' => 'Vorbereitung',
'execution' => 'Durchführung',
'trainer_notes' => 'Trainerhinweise',
];
public function configured(): bool
{
return app(ShinkanConnection::class)->configured();
}
/**
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher sie kommen.
*
* @return array{url: bool, key: bool, host: string|null, url_source: string|null, key_source: string|null}
*/
public function status(): array
{
$connection = app(ShinkanConnection::class);
$url = $connection->url();
return [
'url' => $url !== null,
'key' => $connection->apiKey() !== null,
'host' => $url !== null ? (parse_url($url, PHP_URL_HOST) ?: null) : null,
'url_source' => $connection->source('url'),
'key_source' => $connection->source('key'),
];
}
/**
* 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 Zugangsschlüssel fehlen.'];
}
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 Zugangsschlüssel fehlen.');
}
$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<string, mixed> $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<string> $sourceVariantKeys
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
*/
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<string, mixed> $query
* @return array<string, mixed>
*/
private function get(string $path, array $query = []): array
{
$connection = app(ShinkanConnection::class);
$response = Http::withToken((string) $connection->apiKey())
->acceptJson()
->timeout(20)
->get((string) $connection->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.';
}
}