Importierte Übungen werden im selben Editor bearbeitet und als neue Fassung gespeichert. Lokal bearbeitete Texte und Felder bleiben bei der nächsten Übernahme erhalten, bei Änderung auf beiden Seiten entscheidet die Redaktion. Ein Fehler im Editor setzte die Herkunft der Varianten auf lokal und ist behoben. Übungen haben einen Einstieg unter Inhalte, Fachliche Säulen und Redaktionelle Stammdaten stehen in der Gruppe Stammdaten, die Übernahme ist ein Weg im Übungsbestand. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
828 lines
36 KiB
PHP
828 lines
36 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 adoptPreviewed}) und ist danach unveränderlich.
|
|
* Lokale Ergänzungen (Herkunft „lokal“) bleiben bei einer neuen Quellfassung erhalten. Entfällt die Quellvariante einer
|
|
* lokalen Ergänzung, legt die Redaktion die neue Zuordnung fest.
|
|
* - Das Ausblenden an der Quelle setzt nur die Verfügbarkeit. Lokale Fassungen und Verwendungen bleiben unberührt; eine
|
|
* rechtliche Sperre ist der lokale `block`. Ausgeblendete Quellen sind von der Übernahme ausgeschlossen.
|
|
* - 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. */
|
|
public const SECTIONS = [
|
|
'preparation' => 'Vorbereitung',
|
|
'execution' => 'Durchführung',
|
|
'trainer_notes' => 'Trainerhinweise',
|
|
];
|
|
|
|
/** Änderungshinweis der Textfassungen, die die Übernahme angelegt hat. Alles andere ist eine lokale Bearbeitung. */
|
|
private const IMPORT_NOTE = 'Übernahme aus Shinkan';
|
|
|
|
/** Fassungsfelder der Quelle: Katalogfeld => [Feld der lokalen Fassung, Bezeichnung]. */
|
|
private const FIELDS = [
|
|
'goal' => ['learning_goal', 'Lernziel'],
|
|
'duration_min' => ['duration_minutes', 'Dauer (von)'],
|
|
'duration_max' => ['duration_max', 'Dauer (bis)'],
|
|
'equipment' => ['material_note', 'Ausstattung'],
|
|
];
|
|
|
|
public function configured(): bool
|
|
{
|
|
return app(ShinkanConnection::class)->configured();
|
|
}
|
|
|
|
/**
|
|
* Zustand der Anbindung ohne Werte: ob Adresse und Schlüssel vorhanden sind und woher der Schlüssel kommt.
|
|
*
|
|
* @return array{url: bool, key: bool, host: 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,
|
|
'key_source' => $connection->keySource(),
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Verbindung prüfen, ohne etwas zu speichern. Mit `$candidateKey` wird ein noch nicht hinterlegter Schlüssel
|
|
* geprüft. Der Katalogabruf legt auf der Seite von Shinkan einen Stand an; hier wird nur gezählt.
|
|
*
|
|
* @return array{ok: bool, message: string}
|
|
*/
|
|
public function check(?string $candidateKey = null): array
|
|
{
|
|
$connection = app(ShinkanConnection::class);
|
|
$key = filled($candidateKey) ? trim((string) $candidateKey) : $connection->apiKey();
|
|
|
|
if ($connection->url() === null || $key === null) {
|
|
return ['ok' => false, 'message' => 'Die Anbindung ist nicht eingerichtet. Adresse oder Zugangsschlüssel fehlen.'];
|
|
}
|
|
|
|
try {
|
|
$catalog = $this->get('/catalog', [], $key);
|
|
} 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 oder 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',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Vorschau der geplanten Übernahme: verfügbare Texte, Varianten und Medienhinweise, bei einer neuen Quellfassung die
|
|
* fachlich relevanten Änderungen zur zuletzt übernommenen Fassung und offene Zuordnungen lokaler Ergänzungen.
|
|
*
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function preview(ExerciseSource $source): array
|
|
{
|
|
$snapshot = $source->latestSnapshot();
|
|
$state = $this->state($source);
|
|
$document = $snapshot?->payload ?? [];
|
|
$previous = $this->lastAdopted($source);
|
|
$sections = [];
|
|
|
|
foreach (self::SECTIONS as $field => $label) {
|
|
if (trim((string) ($document[$field] ?? '')) !== '') {
|
|
$sections[] = ['label' => $label, 'text' => mb_strimwidth(trim((string) $document[$field]), 0, 280, '…')];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'source' => $source->id,
|
|
'snapshot' => $snapshot?->id,
|
|
'hash' => $snapshot?->content_hash,
|
|
'state' => $state,
|
|
'title' => (string) ($document['title'] ?? $source->title),
|
|
'summary' => (string) ($document['summary'] ?? ''),
|
|
'goal' => (string) ($document['goal'] ?? ''),
|
|
'duration' => $this->duration($document),
|
|
'equipment' => (string) ($document['equipment'] ?? ''),
|
|
'sections' => $sections,
|
|
'variants' => array_map(fn (array $variant): array => [
|
|
'key' => (string) ($variant['id'] ?? ''),
|
|
'name' => (string) ($variant['name'] ?? ''),
|
|
'description' => (string) ($variant['description'] ?? ''),
|
|
'changes' => trim((string) ($variant['execution_changes'] ?? '')) !== '',
|
|
], array_values(array_filter((array) ($document['variants'] ?? []), 'is_array'))),
|
|
'media' => array_map(fn (array $media): string => ($media['title'] ?? 'Medium').' ('.($media['media_type'] ?? '').')', array_values(array_filter((array) ($document['media'] ?? []), 'is_array'))),
|
|
'changes' => $previous === null ? [] : $this->changes($previous->payload, $document, $source),
|
|
'conflicts' => $snapshot === null ? [] : $this->conflicts($source, $document),
|
|
'text_conflicts' => $snapshot === null ? [] : $this->textDecisions($source, $document, 'conflict'),
|
|
'kept_local' => $snapshot === null ? [] : array_column($this->textDecisions($source, $document, 'keep_local'), 'label'),
|
|
'identical' => $snapshot !== null && $snapshot->adopted_version_id !== null,
|
|
'excluded' => $source->availability === ExerciseSource::WITHDRAWN,
|
|
];
|
|
}
|
|
|
|
/**
|
|
* Fachlich relevante Änderungen einer neuen Quellfassung zur zuletzt übernommenen.
|
|
*
|
|
* @param array<string, mixed> $before
|
|
* @param array<string, mixed> $after
|
|
* @return list<string>
|
|
*/
|
|
public function changes(array $before, array $after, ?ExerciseSource $source = null): array
|
|
{
|
|
$lines = [];
|
|
$labels = [
|
|
'title' => 'Titel', 'summary' => 'Kurzbeschreibung', 'goal' => 'Lernziel', 'equipment' => 'Ausstattung',
|
|
'duration_min' => 'Dauer (von)', 'duration_max' => 'Dauer (bis)',
|
|
] + self::SECTIONS;
|
|
|
|
foreach ($labels as $field => $label) {
|
|
if (trim((string) ($before[$field] ?? '')) !== trim((string) ($after[$field] ?? ''))) {
|
|
$lines[] = $label.' geändert';
|
|
}
|
|
}
|
|
|
|
$old = collect((array) ($before['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
|
$new = collect((array) ($after['variants'] ?? []))->keyBy(fn (array $variant): string => (string) ($variant['id'] ?? ''));
|
|
|
|
foreach ($new->diffKeys($old) as $variant) {
|
|
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ neu';
|
|
}
|
|
|
|
foreach ($old->diffKeys($new) as $variant) {
|
|
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ entfällt';
|
|
}
|
|
|
|
foreach ($new->intersectByKeys($old) as $key => $variant) {
|
|
if (($variant['name'] ?? '') !== ($old[$key]['name'] ?? '')) {
|
|
$lines[] = 'Variante „'.($old[$key]['name'] ?? '').'“ heißt jetzt „'.($variant['name'] ?? '').'“';
|
|
}
|
|
|
|
if (trim((string) ($variant['description'] ?? '')) !== trim((string) ($old[$key]['description'] ?? ''))
|
|
|| trim((string) ($variant['execution_changes'] ?? '')) !== trim((string) ($old[$key]['execution_changes'] ?? ''))) {
|
|
$lines[] = 'Variante „'.($variant['name'] ?? '').'“ geändert';
|
|
}
|
|
}
|
|
|
|
$common = $old->keys()->intersect($new->keys())->values()->all();
|
|
|
|
if ($common !== [] && $common !== $new->keys()->intersect($old->keys())->values()->all()) {
|
|
$lines[] = 'Reihenfolge der Varianten geändert';
|
|
}
|
|
|
|
if ($source?->composition !== null) {
|
|
if (($before['title'] ?? '') !== ($after['title'] ?? '') && $source->composition->designation !== ($before['title'] ?? '')) {
|
|
$lines[] = 'Der Titel wurde lokal geändert und bleibt unverändert';
|
|
}
|
|
|
|
if (($before['summary'] ?? '') !== ($after['summary'] ?? '') && filled($source->composition->summary) && $source->composition->summary !== ($before['summary'] ?? '')) {
|
|
$lines[] = 'Die Kurzbeschreibung wurde lokal geändert und bleibt unverändert';
|
|
}
|
|
}
|
|
|
|
return $lines;
|
|
}
|
|
|
|
/**
|
|
* Lokal ergänzte Bestandteile, die einer Quellvariante zugeordnet sind, die die neue Quellfassung nicht mehr kennt.
|
|
* Die Redaktion legt deren neue Zuordnung fest.
|
|
*
|
|
* @param array<string, mixed> $document
|
|
* @return list<array{key: string, name: string, members: list<string>}>
|
|
*/
|
|
public function conflicts(ExerciseSource $source, array $document): array
|
|
{
|
|
$latest = $source->composition?->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
|
|
|
if ($latest === null) {
|
|
return [];
|
|
}
|
|
|
|
$keep = array_merge(
|
|
array_map(fn (array $variant): string => (string) ($variant['id'] ?? ''), array_filter((array) ($document['variants'] ?? []), 'is_array')),
|
|
$latest->variants->where('origin', 'lokal')->pluck('key')->all(),
|
|
);
|
|
$open = [];
|
|
|
|
foreach ($latest->members->where('origin', 'lokal') as $member) {
|
|
$key = $member->variant?->key;
|
|
|
|
if ($key !== null && ! in_array($key, $keep, true)) {
|
|
$open[$key]['key'] = $key;
|
|
$open[$key]['name'] = $member->variant->name;
|
|
$open[$key]['members'][] = $member->role;
|
|
}
|
|
}
|
|
|
|
return array_values($open);
|
|
}
|
|
|
|
/**
|
|
* Texte und Felder, die lokal bearbeitet wurden: `keep_local` bleiben erhalten, bei `conflict` hat auch die Quelle
|
|
* geändert und die Redaktion entscheidet.
|
|
*
|
|
* @param array<string, mixed> $document
|
|
* @return list<array{key: string, label: string}>
|
|
*/
|
|
public function textDecisions(ExerciseSource $source, array $document, string $wanted): array
|
|
{
|
|
$previousSnapshot = $this->lastAdopted($source);
|
|
|
|
if ($previousSnapshot === null || $source->composition === null) {
|
|
return [];
|
|
}
|
|
|
|
$previousSource = $previousSnapshot->payload;
|
|
$result = [];
|
|
|
|
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
|
if ($item['kind'] === 'text' && $item['decision'] === $wanted) {
|
|
$result[] = ['key' => $item['key'], 'label' => $item['label']];
|
|
}
|
|
}
|
|
|
|
$latest = $source->composition->versions()->orderByDesc('number')->first();
|
|
|
|
foreach (self::FIELDS as $field => [$column, $label]) {
|
|
if ($latest !== null && $this->classifyField($latest->{$column}, $previousSource[$field] ?? null, $document[$field] ?? null) === $wanted) {
|
|
$result[] = ['key' => $field, 'label' => $label];
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
/**
|
|
* Übernimmt genau den Stand, den die Redaktion in der Vorschau gesehen hat. Hat sich der Stand seither geändert oder
|
|
* wurde die Quelle ausgeblendet, wird nichts übernommen. Identische bereits übernommene Stände ergeben keine Fassung.
|
|
*
|
|
* @param array<string, string> $reassign neue Zuordnung entfallener Quellvarianten: alter Schlüssel => neuer Schlüssel oder ''
|
|
* @param array<string, string> $choices bei lokal und in der Quelle geänderten Angaben: Schlüssel => `lokal` oder `quelle`
|
|
* @return array{status: string, message: string, version?: CompositionVersion}
|
|
*/
|
|
public function adoptPreviewed(ExerciseSource $source, int $previewedSnapshot, array $reassign = [], ?User $actor = null, array $choices = []): array
|
|
{
|
|
$source->refresh();
|
|
$latest = $source->latestSnapshot();
|
|
|
|
if ($source->availability === ExerciseSource::WITHDRAWN) {
|
|
return ['status' => 'ausgeschlossen', 'message' => 'Die Quelle stellt diese Übung nicht mehr bereit. Sie wird nicht übernommen.'];
|
|
}
|
|
|
|
if ($latest === null || $latest->id !== $previewedSnapshot) {
|
|
return ['status' => 'geaendert', 'message' => 'Der Quellstand hat sich seit der Vorschau geändert. Prüfe die aktualisierte Vorschau und bestätige den neuen Stand.'];
|
|
}
|
|
|
|
if ($latest->adopted_version_id !== null) {
|
|
return ['status' => 'unveraendert', 'message' => 'Dieser Stand ist bereits übernommen. Es entsteht keine weitere Fassung.', 'version' => $latest->adoptedVersion];
|
|
}
|
|
|
|
try {
|
|
$version = $this->adopt($latest, $actor, $reassign, $choices);
|
|
} catch (DomainRuleException $exception) {
|
|
return ['status' => 'fehler', 'message' => $exception->getMessage()];
|
|
}
|
|
|
|
return ['status' => 'uebernommen', 'message' => 'Fassung '.$version->number.' ist lokal angelegt und unveränderlich.', 'version' => $version];
|
|
}
|
|
|
|
/**
|
|
* Die bewusste Übernahme: aus dem Inhaltsstand wird eine neue, unveränderliche lokale Fassung. Wiederholt man sie,
|
|
* entsteht keine zweite Fassung.
|
|
*
|
|
* Eine importierte Übung ist eine Übung wie jede andere und lässt sich bearbeiten. Lokal bearbeitete Texte und Felder
|
|
* bleiben deshalb erhalten, solange die Quelle sie nicht ebenfalls geändert hat. Haben beide Seiten geändert, legt die
|
|
* Redaktion fest, welcher Stand gilt (`$choices`). Lokale Ergänzungen bleiben erhalten; entfällt ihre Quellvariante,
|
|
* legt die Redaktion die neue Zuordnung fest (`$reassign`).
|
|
*
|
|
* @param array<string, string> $reassign
|
|
* @param array<string, string> $choices Schlüssel => `lokal` oder `quelle`
|
|
*/
|
|
public function adopt(ExerciseSourceSnapshot $snapshot, ?User $actor = null, array $reassign = [], array $choices = []): CompositionVersion
|
|
{
|
|
$snapshot->refresh();
|
|
|
|
if ($snapshot->adopted_version_id !== null) {
|
|
return $snapshot->adoptedVersion;
|
|
}
|
|
|
|
return DB::transaction(function () use ($snapshot, $actor, $reassign, $choices): CompositionVersion {
|
|
$source = $snapshot->source;
|
|
$document = $snapshot->payload;
|
|
$content = app(ContentService::class);
|
|
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
|
$previousSnapshot = $this->lastAdopted($source);
|
|
$previousSource = $previousSnapshot?->payload ?? [];
|
|
$composition = $source->composition ?? $this->createComposition($title, (string) ($document['summary'] ?? ''));
|
|
|
|
if ($source->composition !== null && $previousSnapshot !== null) {
|
|
$this->carryOverTexts($composition, $previousSource, $document);
|
|
}
|
|
|
|
$previous = $composition->versions()->orderByDesc('number')->with('members.variant', 'variants')->first();
|
|
$variants = [];
|
|
$members = [];
|
|
|
|
foreach ($this->plan($source, $document, $previousSource) as $item) {
|
|
if ($item['kind'] === 'variant') {
|
|
$variants[] = $item['variant'];
|
|
|
|
continue;
|
|
}
|
|
|
|
$latest = $item['latest'];
|
|
$decision = $item['decision'];
|
|
|
|
if ($decision === 'conflict') {
|
|
$decision = ($choices[$item['key']] ?? null) === 'lokal' ? 'keep_local'
|
|
: (($choices[$item['key']] ?? null) === 'quelle' ? 'source' : 'conflict');
|
|
}
|
|
|
|
if ($decision === 'conflict') {
|
|
throw new DomainRuleException('„'.$item['label'].'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
|
}
|
|
|
|
$keepLocal = $decision === 'keep_local' && $latest !== null;
|
|
$target = $keepLocal ? $latest : $this->sectionVersion($source, $item['field'], $item['title'], $item['text'], $latest);
|
|
$members[] = array_filter([
|
|
'role' => $item['role'],
|
|
'target' => $target,
|
|
'variant' => $item['variant_key'],
|
|
'origin' => $keepLocal || ($latest !== null && $latest->id === $target->id && $latest->change_note !== self::IMPORT_NOTE) ? 'lokal' : 'quelle',
|
|
], fn ($value): bool => $value !== null);
|
|
}
|
|
|
|
// Fassungsfelder: lokal geändert bleibt erhalten, solange die Quelle den Wert nicht ebenfalls geändert hat.
|
|
$fields = [];
|
|
|
|
foreach (self::FIELDS as $field => [$column, $label]) {
|
|
$value = $document[$field] ?? null;
|
|
|
|
if ($previous !== null && $previousSnapshot !== null) {
|
|
$decision = $this->classifyField($previous->{$column}, $previousSource[$field] ?? null, $value);
|
|
|
|
if ($decision === 'conflict') {
|
|
$decision = ($choices[$field] ?? null) === 'lokal' ? 'keep_local' : (($choices[$field] ?? null) === 'quelle' ? 'source' : 'conflict');
|
|
}
|
|
|
|
if ($decision === 'conflict') {
|
|
throw new DomainRuleException('„'.$label.'“ wurde lokal und in der Quelle geändert. Lege fest, welcher Stand gilt.');
|
|
}
|
|
|
|
$value = $decision === 'keep_local' ? $previous->{$column} : $value;
|
|
}
|
|
|
|
$fields[$column] = $value;
|
|
}
|
|
|
|
[$localMembers, $localVariants] = $this->localAdditions($previous, array_column($variants, 'key'), $reassign);
|
|
$version = $content->publishComposition(
|
|
$composition,
|
|
[...$members, ...$localMembers],
|
|
$actor,
|
|
self::IMPORT_NOTE,
|
|
[
|
|
'learning_goal' => $fields['learning_goal'],
|
|
'duration_minutes' => $fields['duration_minutes'],
|
|
'duration_max' => $fields['duration_max'],
|
|
'material_note' => $fields['material_note'],
|
|
'source_snapshot_id' => $snapshot->id,
|
|
],
|
|
[...$variants, ...$localVariants],
|
|
);
|
|
|
|
$snapshot->update(['adopted_version_id' => $version->id]);
|
|
$source->update(['composition_id' => $composition->id]);
|
|
|
|
return $version;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Was die Übernahme aus dem Quellstand anlegen würde, mit der Entscheidung je Text: `source` (Quelltext gilt),
|
|
* `keep_local` (lokal bearbeitet, die Quelle hat sich nicht geändert) oder `conflict` (beide haben geändert).
|
|
*
|
|
* @param array<string, mixed> $document
|
|
* @param array<string, mixed> $previousSource
|
|
* @return list<array<string, mixed>>
|
|
*/
|
|
private function plan(ExerciseSource $source, array $document, array $previousSource): array
|
|
{
|
|
$plan = [];
|
|
$title = trim((string) ($document['title'] ?? '')) ?: 'Übung aus Shinkan';
|
|
|
|
foreach (self::SECTIONS as $field => $label) {
|
|
$text = trim((string) ($document[$field] ?? ''));
|
|
|
|
if ($text !== '') {
|
|
$plan[] = $this->textItem($source, $field, $label, $title.' · '.$label, $label, $text, null, $previousSource[$field] ?? null);
|
|
}
|
|
}
|
|
|
|
foreach ((array) ($document['variants'] ?? []) as $variant) {
|
|
$key = (string) ($variant['id'] ?? '');
|
|
|
|
if ($key === '') {
|
|
continue;
|
|
}
|
|
|
|
$name = (string) ($variant['name'] ?? '') ?: 'Variante';
|
|
$plan[] = [
|
|
'kind' => 'variant',
|
|
'variant' => ['key' => $key, 'name' => $name, 'description' => (string) ($variant['description'] ?? ''), 'origin' => 'quelle'],
|
|
];
|
|
$changes = trim((string) ($variant['execution_changes'] ?? ''));
|
|
|
|
if ($changes !== '') {
|
|
$before = collect((array) ($previousSource['variants'] ?? []))->firstWhere('id', $key);
|
|
$plan[] = $this->textItem(
|
|
$source,
|
|
'variant:'.$key,
|
|
'Abweichung der Durchführung ('.$name.')',
|
|
$title.' · '.$name.' · Abweichung',
|
|
'Abweichung der Durchführung',
|
|
$changes,
|
|
$key,
|
|
is_array($before) ? ($before['execution_changes'] ?? null) : null,
|
|
'variant_'.$key,
|
|
);
|
|
}
|
|
}
|
|
|
|
return $plan;
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function textItem(ExerciseSource $source, string $field, string $label, string $title, string $role, string $text, ?string $variantKey, ?string $previousText, ?string $key = null): array
|
|
{
|
|
$element = ContentElement::query()->where('source_ref', 'shinkan:'.$source->source_id.':'.$field)->first();
|
|
$latest = $element?->versions()->where('status', ContentVersionStatus::Bereit)->orderByDesc('number')->first();
|
|
|
|
return [
|
|
'kind' => 'text',
|
|
'key' => $key ?? $field,
|
|
'field' => $field,
|
|
'label' => $label,
|
|
'title' => $title,
|
|
'role' => $role,
|
|
'text' => $text,
|
|
'variant_key' => $variantKey,
|
|
'latest' => $latest,
|
|
'decision' => $this->classifyText($latest, $text, $previousText),
|
|
];
|
|
}
|
|
|
|
private function classifyText(?ContentElementVersion $latest, string $text, ?string $previousText): string
|
|
{
|
|
if ($latest === null || trim((string) $latest->body) === $text || $latest->change_note === self::IMPORT_NOTE) {
|
|
return 'source';
|
|
}
|
|
|
|
return $previousText === null || trim($previousText) !== $text ? 'conflict' : 'keep_local';
|
|
}
|
|
|
|
private function classifyField(mixed $local, mixed $previousSource, mixed $new): string
|
|
{
|
|
$plain = fn (mixed $value): string => $value === null ? '' : trim((string) $value);
|
|
|
|
if ($plain($local) === $plain($new) || $plain($local) === $plain($previousSource)) {
|
|
return 'source';
|
|
}
|
|
|
|
return $plain($previousSource) !== $plain($new) ? 'conflict' : 'keep_local';
|
|
}
|
|
|
|
/**
|
|
* Titel und Kurzbeschreibung gehören zur Übung und nicht zur Fassung. Sie folgen der Quelle, solange die Redaktion sie
|
|
* nicht lokal geändert hat; ein lokal geänderter Wert bleibt.
|
|
*
|
|
* @param array<string, mixed> $before
|
|
* @param array<string, mixed> $after
|
|
*/
|
|
private function carryOverTexts(Composition $composition, array $before, array $after): void
|
|
{
|
|
if (trim((string) ($after['title'] ?? '')) !== '' && $composition->designation === ($before['title'] ?? null)) {
|
|
$composition->designation = trim((string) $after['title']);
|
|
}
|
|
|
|
if (array_key_exists('summary', $after) && ((string) $composition->summary === '' || $composition->summary === ($before['summary'] ?? null))) {
|
|
$composition->summary = trim((string) $after['summary']) ?: null;
|
|
}
|
|
|
|
$composition->save();
|
|
}
|
|
|
|
private function lastAdopted(ExerciseSource $source): ?ExerciseSourceSnapshot
|
|
{
|
|
return $source->snapshots()->reorder()->whereNotNull('adopted_version_id')->orderByDesc('id')->first();
|
|
}
|
|
|
|
/**
|
|
* Was die Redaktion lokal ergänzt hat, bleibt bei einer neuen Quellfassung erhalten. Eine lokale Zuordnung zu einer
|
|
* Quellvariante, die es nicht mehr gibt, braucht eine ausdrücklich festgelegte neue Zuordnung.
|
|
*
|
|
* @param list<string> $sourceVariantKeys
|
|
* @param array<string, string> $reassign
|
|
* @return array{0: list<array<string, mixed>>, 1: list<array<string, mixed>>}
|
|
*/
|
|
private function localAdditions(?CompositionVersion $previous, array $sourceVariantKeys, array $reassign): 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;
|
|
|
|
if ($variant !== null && ! in_array($variant, $known, true)) {
|
|
if (! array_key_exists($variant, $reassign)) {
|
|
throw new DomainRuleException('Die lokale Ergänzung „'.$member->role.'“ gehört zur Quellvariante „'.$member->variant->name.'“, die es nicht mehr gibt. Lege ihre neue Zuordnung fest.');
|
|
}
|
|
|
|
$target = (string) $reassign[$variant];
|
|
|
|
if ($target !== '' && ! in_array($target, $known, true)) {
|
|
throw new DomainRuleException('Die gewählte neue Zuordnung gibt es in der neuen Fassung nicht.');
|
|
}
|
|
|
|
$variant = $target === '' ? null : $target;
|
|
}
|
|
|
|
$members[] = [
|
|
'role' => $member->role,
|
|
'note' => $member->placement_note,
|
|
'target' => $member->content_element_version_id !== null ? $member->contentElementVersion : $member->nestedCompositionVersion,
|
|
'variant' => $variant,
|
|
'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 sectionVersion(ExerciseSource $source, string $field, string $title, string $text, ?ContentElementVersion $latest): 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();
|
|
}
|
|
|
|
return $latest !== null && trim((string) $latest->body) === $text
|
|
? $latest
|
|
: $content->publishElementVersion($element, $text, [], self::IMPORT_NOTE);
|
|
}
|
|
|
|
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> $document
|
|
*/
|
|
private function duration(array $document): string
|
|
{
|
|
$min = $document['duration_min'] ?? null;
|
|
$max = $document['duration_max'] ?? null;
|
|
|
|
return match (true) {
|
|
$min !== null && $max !== null && $min !== $max => $min.' bis '.$max.' Minuten',
|
|
$min !== null => $min.' Minuten',
|
|
$max !== null => $max.' Minuten',
|
|
default => '',
|
|
};
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $query
|
|
* @return array<string, mixed>
|
|
*/
|
|
private function get(string $path, array $query = [], ?string $key = null): array
|
|
{
|
|
$connection = app(ShinkanConnection::class);
|
|
$response = Http::withToken((string) ($key ?? $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 match ($exception->response->status()) {
|
|
401, 403 => 'Shinkan akzeptiert den Zugangsschlüssel nicht (Status '.$exception->response->status().').',
|
|
404 => 'Der Katalog ist unter dieser Adresse nicht erreichbar oder die Distribution ist in Shinkan nicht aktiv (Status 404).',
|
|
default => 'Die Quelle antwortete mit Status '.$exception->response->status().'.',
|
|
};
|
|
}
|
|
|
|
if ($exception instanceof DomainRuleException) {
|
|
return $exception->getMessage();
|
|
}
|
|
|
|
return $this->networkCause($exception);
|
|
}
|
|
|
|
/**
|
|
* Benennt die Ursache eines Netzwerkfehlers, ohne Adresse, Pfad oder Schlüssel auszugeben. Genannt wird nur der
|
|
* Servername, damit die Redaktion erkennt, ob die richtige Quelle gemeint ist.
|
|
*/
|
|
private function networkCause(Throwable $exception): string
|
|
{
|
|
$host = app(ShinkanConnection::class)->url();
|
|
$host = $host === null ? 'der Quelle' : (string) (parse_url($host, PHP_URL_HOST) ?: 'der Quelle');
|
|
preg_match('/cURL error (\d+)/', $exception->getMessage(), $match);
|
|
$code = isset($match[1]) ? (int) $match[1] : null;
|
|
|
|
$cause = match (true) {
|
|
$code === 6 => 'Der Servername konnte von diesem Server aus nicht aufgelöst werden (Namensauflösung, DNS).',
|
|
$code === 7 => 'Der Server nimmt die Verbindung nicht an (abgelehnt, falscher Port oder Firewall).',
|
|
$code === 28 => 'Die Verbindung hat die Zeit überschritten (ausgehende Verbindungen sind möglicherweise blockiert).',
|
|
in_array($code, [35, 51, 58, 60, 77, 83], true) => 'Das Zertifikat oder die verschlüsselte Verbindung wird nicht akzeptiert.',
|
|
$code === 56 || $code === 52 => 'Die Verbindung wurde unterbrochen.',
|
|
$code !== null => 'Netzwerkfehler (cURL '.$code.').',
|
|
default => 'Netzwerkfehler.',
|
|
};
|
|
|
|
return 'Die Quelle '.$host.' ist von diesem Server aus nicht erreichbar. '.$cause;
|
|
}
|
|
}
|