Loheide-eu-mitarbeiterplatt.../app/Support/Demo/DemoContent.php
Friederich Loheide 3addc09c38
All checks were successful
CI / PHP 8.3 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:10.6 (pull_request) Has been skipped
CI / PHP 8.3 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.4 / mariadb:11.4 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.0 (pull_request) Has been skipped
CI / PHP 8.3 / mysql:8.4 (pull_request) Has been skipped
CI / PHP 8.4 / mysql:8.4 (pull_request) Has been skipped
CI / Browser-Tests (pull_request) Successful in 8m33s
CI / Bekannte Sicherheitslücken in Paketen (pull_request) Successful in 9m8s
CI / PHP 8.3 / mysql:8.4-1 (pull_request) Successful in 17m55s
CI / Build-Artefakte aktuell (pull_request) Successful in 9m50s
Frag das Portal durchsucht alles, neue Demo-Inhalte (0.66.0)
- Wissensquellen: Termine, Downloads, Formulare, Stellen, Ideen, Umfragen,
  Personen, eigene IT-Tickets/Geräte (OpenNIT, je Anfrage zwischengespeichert)
- Ranking mit IDF, Abfrage je Begriff, Abkürzungen als ganze Wörter,
  LIKE unabhängig von Groß-/Kleinschreibung (JSON-Spalten), Datum im Prompt
- Demo-Inhalte für einen Träger der Eingliederungshilfe (DemoData),
  mehrseitige PDFs, vorhandene Inhalte je Bereich entfernen

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-07 20:01:00 +00:00

1037 lines
41 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Support\Demo;
use App\Media\MediaLibrary;
use App\Models\DashboardTile;
use App\Models\Setting;
use App\Models\User;
use App\Pagebuilder\Content;
use App\Plugins\PluginManager;
use App\Support\Branding;
use App\Support\Settings;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Client\Pool;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inhaus\Plugins\Birthdays\Models\Birthday;
use Inhaus\Plugins\Downloads\Models\Download;
use Inhaus\Plugins\Downloads\Models\DownloadFolder;
use Inhaus\Plugins\Downloads\Models\DownloadVersion;
use Inhaus\Plugins\Events\Models\Event;
use Inhaus\Plugins\Forms\FormFields;
use Inhaus\Plugins\Forms\Models\Form;
use Inhaus\Plugins\Gemeinsam\Models\Entry;
use Inhaus\Plugins\Glossar\Models\GlossaryEntry;
use Inhaus\Plugins\Ideen\Models\Idea;
use Inhaus\Plugins\Ideen\Models\IdeaComment;
use Inhaus\Plugins\News\Models\NewsCategory;
use Inhaus\Plugins\News\Models\NewsPost;
use Inhaus\Plugins\Pages\Models\Page;
use Inhaus\Plugins\Qm\Indexer;
use Inhaus\Plugins\Qm\Models\QmCategory;
use Inhaus\Plugins\Qm\Models\QmEntry;
use Inhaus\Plugins\Qm\Models\QmFile;
use Inhaus\Plugins\Qm\Models\QmFolder;
use Inhaus\Plugins\Qm\Presenter;
use Inhaus\Plugins\Stellen\Models\JobPosting;
use Inhaus\Plugins\Umfragen\Models\Poll;
use Inhaus\Plugins\Umfragen\Questions;
use RuntimeException;
use Throwable;
/**
* Demo-Inhalte für Test- und Vorführinstallationen – per Klick im Admin-Bereich
* anlegen und vollständig wieder entfernen.
*
* Alles, was angelegt wird (Datensätze, Dateien, überschriebene Einstellungen),
* steht in der Einstellung „demo.records“. remove() löscht genau das wieder –
* in umgekehrter Reihenfolge und tolerant gegenüber bereits gelöschten Einträgen.
* Kommt ohne Faker/Factories aus (auf dem Kundenserver nicht vorhanden).
*/
class DemoContent
{
public const SETTING = 'demo.records';
public const EMAIL_DOMAIN = 'demo.inhaus.invalid';
/**
* @var array{installed_at?: string, by?: int|null, records: list<array{model: string, table: string, ids: list<int>}>, files: list<array{disk: string, path: string, image: bool}>, settings: list<array{key: string, existed: bool, previous: mixed, value: mixed}>, counts: list<array{label: string, count: int}>}
*/
private array $state = ['records' => [], 'files' => [], 'settings' => [], 'counts' => []];
/** @var list<User> */
private array $people = [];
private ?User $by = null;
public function __construct(
private readonly Settings $settings,
private readonly PluginManager $plugins,
) {}
public function isInstalled(): bool
{
return is_array($this->settings->get(self::SETTING));
}
/**
* Anzahl angelegter Inhalte je Art (für die Statusanzeige).
*
* @return array<string, int>
*/
public function counts(): array
{
$state = $this->settings->get(self::SETTING);
return collect(is_array($state) ? ($state['counts'] ?? []) : [])
->mapWithKeys(fn ($row) => [(string) ($row['label'] ?? '') => (int) ($row['count'] ?? 0)])
->all();
}
public function installedAt(): ?Carbon
{
$state = $this->settings->get(self::SETTING);
return is_array($state) && ! empty($state['installed_at']) ? Carbon::parse($state['installed_at']) : null;
}
/**
* @return array{counts: array<string, int>, warnings: list<string>}
*/
public function install(User $by): array
{
if ($this->isInstalled()) {
throw new RuntimeException('Die Demo-Inhalte sind bereits angelegt. Bitte zuerst entfernen.');
}
$this->by = $by;
$this->state = ['installed_at' => now()->toIso8601String(), 'by' => $by->id, 'records' => [], 'files' => [], 'settings' => [], 'counts' => []];
$this->persist();
$warnings = [];
$sections = [
'Personen' => fn () => $this->people(),
'Schnellzugriffe' => fn () => $this->quickLinks(),
'Startseiten-Kachel' => fn () => $this->dashboardTile(),
'Neuigkeiten' => fn () => $this->loaded('news') ? $this->news() : null,
'Termine' => fn () => $this->loaded('events') ? $this->events() : null,
'Seiten' => fn () => $this->loaded('pages') ? $this->pages() : null,
'Downloads' => fn () => $this->loaded('downloads') ? $this->downloads() : null,
'Qualitätsmanagement' => fn () => $this->loaded('qm') ? $this->qm() : null,
'Glossar' => fn () => $this->loaded('glossar') ? $this->glossary() : null,
'Stellenangebote' => fn () => $this->loaded('stellen') ? $this->jobs() : null,
'Ideenbox' => fn () => $this->loaded('ideen') ? $this->ideas() : null,
'Umfragen' => fn () => $this->loaded('umfragen') ? $this->polls() : null,
'Formulare' => fn () => $this->loaded('forms') ? $this->forms() : null,
'Gemeinsam feiern' => fn () => $this->loaded('gemeinsam') ? $this->gemeinsam() : null,
'Geburtstage' => fn () => $this->loaded('birthdays') ? $this->birthdays() : null,
];
foreach ($sections as $label => $section) {
try {
$section();
} catch (Throwable $e) {
report($e);
$warnings[] = "{$label}: ".Str::limit($e->getMessage(), 300);
} finally {
$this->persist();
}
}
return ['counts' => $this->counts(), 'warnings' => $warnings];
}
/**
* @return array{records: int, files: int, warnings: list<string>}
*/
public function remove(): array
{
$state = $this->settings->get(self::SETTING);
if (! is_array($state)) {
return ['records' => 0, 'files' => 0, 'warnings' => []];
}
$deleted = 0;
$warnings = [];
foreach (array_reverse((array) ($state['records'] ?? [])) as $group) {
$class = (string) ($group['model'] ?? '');
$table = (string) ($group['table'] ?? '');
$ids = array_reverse(array_map('intval', (array) ($group['ids'] ?? [])));
foreach ($ids as $id) {
try {
if (class_exists($class) && is_subclass_of($class, Model::class)) {
$record = $class::query()->find($id);
if ($record && $record->delete()) {
$deleted++;
}
} elseif ($table !== '') {
// Plugin inzwischen deaktiviert: Zeile direkt löschen.
$deleted += DB::table($table)->where('id', $id)->delete();
}
} catch (Throwable $e) {
$warnings[] = class_basename($class)." #{$id} konnte nicht gelöscht werden (vermutlich hängen inzwischen weitere Inhalte daran).";
}
}
}
$files = 0;
$library = app(MediaLibrary::class);
foreach ((array) ($state['files'] ?? []) as $file) {
try {
$disk = Storage::disk((string) $file['disk']);
if ($disk->exists((string) $file['path'])) {
$files++;
}
// Bilder samt Eintrag in der Mediathek entfernen
! empty($file['image']) ? $library->deletePath((string) $file['path']) : $disk->delete((string) $file['path']);
} catch (Throwable) {
$warnings[] = "Datei {$file['path']} konnte nicht gelöscht werden.";
}
}
// Überschriebene Einstellungen zurücksetzen – aber nur, wenn seitdem niemand sie geändert hat.
foreach (array_reverse((array) ($state['settings'] ?? [])) as $setting) {
$key = (string) $setting['key'];
if ($this->settings->get($key) != ($setting['value'] ?? null)) {
continue;
}
if (! empty($setting['existed'])) {
$this->settings->set($key, $setting['previous'] ?? null);
} else {
Setting::query()->whereKey($key)->delete();
$this->settings->flush();
}
}
Setting::query()->whereKey(self::SETTING)->delete();
$this->settings->flush();
return ['records' => $deleted, 'files' => $files, 'warnings' => $warnings];
}
/**
* Bereiche, deren vorhandene Inhalte sich vor dem Anlegen der Demo-Inhalte entfernen lassen
* (z. B. eigene Testbeiträge einer Vorführinstallation). Schlüssel = Plugin-Slug.
*
* @return array<string, string>
*/
public static function clearableAreas(): array
{
return [
'news' => 'Neuigkeiten (mit Kategorien, Kommentaren und Herzen)',
'events' => 'Termine (mit Anmeldungen)',
'pages' => 'Seiten',
'downloads' => 'Downloads',
'qm' => 'Qualitätsmanagement',
'glossar' => 'Glossar',
'stellen' => 'Stellenangebote (mit Bewerbungen)',
'ideen' => 'Ideenbox',
'umfragen' => 'Umfragen (mit Antworten)',
'forms' => 'Formulare (mit Einsendungen)',
'gemeinsam' => 'Gemeinsam feiern',
];
}
/**
* Alle vorhandenen Inhalte der gewählten Bereiche löschen – nicht rückgängig zu machen.
* Personen, Rollen, Einstellungen und Menü bleiben unberührt.
*
* @param list<string> $areas
* @return array<string, int> Bereich => gelöschte Einträge
*/
public function clear(array $areas): array
{
if ($this->isInstalled()) {
throw new RuntimeException('Bitte zuerst die Demo-Inhalte entfernen.');
}
$models = [
'news' => [NewsPost::class, NewsCategory::class],
'events' => [Event::class],
'pages' => [Page::class],
'downloads' => [Download::class, DownloadFolder::class],
'qm' => [QmEntry::class, QmFolder::class, QmCategory::class],
'glossar' => [GlossaryEntry::class],
'stellen' => [JobPosting::class],
'ideen' => [Idea::class],
'umfragen' => [Poll::class],
'forms' => [Form::class],
'gemeinsam' => [Entry::class],
];
$deleted = [];
foreach (array_intersect(array_keys($models), $areas) as $area) {
if (! $this->loaded($area)) {
continue;
}
$deleted[$area] = 0;
foreach ($models[$area] as $class) {
// Einzeln über das Modell löschen, damit Dateien und Abhängigkeiten mit verschwinden.
// Unterseiten und Unterordner zuerst (höchste ID zuletzt angelegt, also zuerst weg)
$class::query()->chunkByIdDesc(100, function ($records) use (&$deleted, $area) {
foreach ($records as $record) {
// Kann schon mit dem übergeordneten Eintrag verschwunden sein
if ($record->exists && $record->newQuery()->whereKey($record->getKey())->exists()) {
$record->delete();
$deleted[$area]++;
}
}
});
}
}
return $deleted;
}
// ---------------------------------------------------------------------
// Personen
// ---------------------------------------------------------------------
private function people(): void
{
$created = [];
foreach (DemoData::people() as [$first, $last, $title, $department, $location, $phone, $mobile, $manager, $daysAgo, $about]) {
$email = Str::slug($first.' '.$last, '.', 'de').'@'.self::EMAIL_DOMAIN;
$existing = User::query()->where('email', $email)->first();
if ($existing) {
$created[] = $existing;
continue;
}
$user = new User([
'first_name' => $first,
'last_name' => $last,
'email' => $email,
'password' => Str::random(40),
'job_title' => $title,
'department' => $department,
'location' => $location,
// Kurze Durchwahlen gehören zur Telefonanlage, längere Nummern sind extern
'phone' => $phone === null ? null : (strlen($phone) <= 4 ? DemoData::PHONE.$phone : $phone),
'mobile' => $mobile,
'about' => $about,
'manager_id' => $manager !== null ? ($created[$manager]->id ?? null) : null,
'is_active' => true,
]);
$user->created_at = now()->subDays($daysAgo)->setTime(8, 0);
$user->save();
$created[] = $this->track($user);
}
$this->people = $created;
$this->count('Personen', count($created));
}
private function person(int $index): ?User
{
return $this->people[$index] ?? $this->by;
}
/**
* @param list<int> $indexes
* @return list<int>
*/
private function personIds(array $indexes): array
{
return array_values(array_filter(array_map(fn ($i) => $this->people[$i]->id ?? null, $indexes)));
}
// ---------------------------------------------------------------------
// Schnellzugriffe und Startseite
// ---------------------------------------------------------------------
private function quickLinks(): void
{
if (filled($this->settings->get('portal.quick_links'))) {
return;
}
$this->setSetting('portal.quick_links', [
['label' => 'Vivendi PEP', 'subtitle' => 'Dienstplan, Urlaub, Zeitkonto', 'url' => 'https://example.com/vivendi-pep', 'icon' => 'calendar-days', 'pinned' => true, 'new_tab' => true],
['label' => 'Vivendi PD', 'subtitle' => 'Dokumentation', 'url' => 'https://example.com/vivendi-pd', 'icon' => 'notebook-pen', 'pinned' => true, 'new_tab' => true],
['label' => 'Vivendi NG', 'subtitle' => 'Klientenverwaltung', 'url' => 'https://example.com/vivendi-ng', 'icon' => 'users', 'pinned' => true, 'new_tab' => true],
['label' => 'DocuWare', 'subtitle' => 'Archiv und Rechnungen', 'url' => 'https://example.com/docuware', 'icon' => 'archive', 'pinned' => true, 'new_tab' => true],
['label' => 'Webmail', 'subtitle' => 'E-Mail von unterwegs', 'url' => 'https://example.com/mail', 'icon' => 'mail', 'pinned' => false, 'new_tab' => true],
['label' => 'Personen', 'subtitle' => 'Telefonbuch', 'url' => '/personen', 'icon' => 'users', 'pinned' => false, 'new_tab' => false],
]);
$this->count('Schnellzugriffe', 6);
}
private function dashboardTile(): void
{
$this->track(DashboardTile::query()->create([
'name' => 'Demo: Willkommen',
'type' => 'notice',
'area' => 'top',
'title' => 'Neu: Frag das Portal',
'body' => '<p>Stellen Sie Ihre Frage in eigenen Worten – zum Beispiel „Wie beantrage ich Urlaub?“ oder „Was tun bei einem Arbeitsunfall?“. Die Schaltfläche finden Sie unten rechts.</p>',
'variant' => 'brand',
'is_active' => true,
]));
$this->count('Startseiten-Kacheln', 1);
}
// ---------------------------------------------------------------------
// Neuigkeiten
// ---------------------------------------------------------------------
private function news(): void
{
$categories = [];
foreach (DemoData::newsCategories() as $i => $name) {
$slug = Str::slug($name, language: 'de');
$categories[$name] = NewsCategory::query()->where('slug', $slug)->first()
?? $this->track(NewsCategory::query()->create(['name' => $name, 'slug' => $slug, 'sort' => $i]));
}
$posts = DemoData::news();
$images = $this->images('news/demo-inhalte', array_filter(array_column($posts, 'image')));
foreach ($posts as $i => $post) {
$publishedAt = now()->subDays($post['days'])->setTime(7 + ($i * 3) % 9, ($i * 17) % 60);
$this->track(NewsPost::query()->create([
'category_id' => $categories[$post['category']]->id,
'author_id' => $this->person($post['author'])?->id,
'title' => $post['title'],
'teaser' => $post['teaser'],
'body' => $this->article($post),
'is_featured' => $post['featured'] ?? false,
'cover_path' => $post['image'] ? ($images[$post['image']] ?? null) : null,
'published_at' => $publishedAt->isFuture() ? now()->subMinutes(30) : $publishedAt,
'must_read' => isset($post['must_read']),
'must_read_until' => isset($post['must_read']) ? now()->addDays($post['must_read'])->toDateString() : null,
]));
}
$this->count('Neuigkeiten', count($posts));
}
/**
* @param array<string, mixed> $post
*/
private function article(array $post): string
{
$html = '<p>'.e($post['intro']).'</p>';
foreach ($post['sections'] as $section) {
$html .= '<h2>'.e($section[0]).'</h2><p>'.e($section[1]).'</p>';
if (! empty($section[2])) {
$html .= '<ul>'.implode('', array_map(fn ($item) => '<li>'.e($item).'</li>', $section[2])).'</ul>';
}
}
if (! empty($post['quote'])) {
$html .= '<blockquote><p>„'.e($post['quote'][0]).'“ – '.e($post['quote'][1]).'</p></blockquote>';
}
return $html.'<p>'.e($post['outro']).'</p>';
}
// ---------------------------------------------------------------------
// Termine
// ---------------------------------------------------------------------
private function events(): void
{
$events = DemoData::events();
$images = $this->images('events/demo-inhalte', array_filter(array_column($events, 6)));
foreach ($events as $event) {
[$title, $location, $inDays, $from, $to, $allDay, $image, $description, $author, $registration] = $event;
$duration = $event[10] ?? 0;
$day = now()->addDays($inDays)->startOfDay();
$this->track(Event::query()->create([
'author_id' => $this->person($author)?->id,
'title' => $title,
'description' => '<p>'.e($description).'</p>',
'location' => $location,
'starts_at' => $allDay ? $day : $day->copy()->setHour($from),
'ends_at' => $allDay ? ($duration ? $day->copy()->addDays($duration) : null) : $day->copy()->setHour($to),
'all_day' => $allDay,
'image_path' => $image ? ($images[$image] ?? null) : null,
'is_published' => true,
'registration_enabled' => $registration !== null,
'capacity' => $registration[0] ?? null,
'waitlist' => (bool) ($registration[1] ?? false),
'registration_deadline' => $registration !== null ? $day->copy()->subDays(2)->setHour(12) : null,
]));
}
$this->count('Termine', count($events));
}
// ---------------------------------------------------------------------
// Seiten
// ---------------------------------------------------------------------
private function pages(): void
{
$content = app(Content::class);
$created = [];
foreach (DemoData::pages() as $i => [$title, $parent, $blocks]) {
$page = $this->track(Page::query()->create([
'parent_id' => $parent ? ($created[$parent]->id ?? null) : null,
'title' => $title,
'sort' => $i,
'in_navigation' => $parent === null,
'created_by' => $this->by?->id,
]));
$page->publish($title, $content->sanitize(['blocks' => array_map(fn (array $block) => $this->block($block), $blocks)]), $this->by);
$created[$title] = $page;
}
$this->count('Seiten', count($created));
}
/**
* Kurzbeschreibung aus DemoData::pages() in einen Baustein übersetzen.
*
* @param array<int, mixed> $spec
* @return array<string, mixed>
*/
private function block(array $spec): array
{
return match ($spec[0]) {
'h' => $this->heading($spec[1], $spec[2] ?? '2'),
'p' => $this->text($spec[1]),
'quote' => $this->quote($spec[1], $spec[2]),
'icons' => $this->iconList($spec[1], $spec[2] ?? 'list'),
'box' => $this->box($spec[1], $spec[2], [$this->text($spec[3])]),
'acc' => $this->accordion(array_map(fn (array $item) => [$item[0], [$this->text($item[1])]], $spec[1])),
'contacts' => $this->contacts($spec[1], $this->personIds($spec[2])),
};
}
/** @return array<string, mixed> */
private function heading(string $text, string $level = '2'): array
{
return ['type' => 'heading', 'data' => ['text' => $text, 'level' => $level]];
}
/** @return array<string, mixed> */
private function text(string $html): array
{
return ['type' => 'text', 'data' => ['html' => $html]];
}
/** @return array<string, mixed> */
private function quote(string $text, string $source): array
{
return ['type' => 'quote', 'data' => ['text' => $text, 'source' => $source]];
}
/**
* @param list<array{0: string, 1: string, 2: string}> $items
* @return array<string, mixed>
*/
private function iconList(array $items, string $layout = 'list'): array
{
return ['type' => 'icon-list', 'data' => [
'items' => array_map(fn ($item) => ['icon' => $item[0], 'title' => $item[1], 'text' => $item[2], 'url' => ''], $items),
'layout' => $layout,
]];
}
/**
* @param list<array<string, mixed>> $blocks
* @return array<string, mixed>
*/
private function box(string $variant, string $title, array $blocks): array
{
return ['type' => 'box', 'data' => ['variant' => $variant, 'title' => $title, 'show_icon' => true], 'items' => [['blocks' => $blocks]]];
}
/**
* @param list<array{0: string, 1: list<array<string, mixed>>}> $sections
* @return array<string, mixed>
*/
private function accordion(array $sections): array
{
return ['type' => 'accordion', 'data' => ['first_open' => true, 'multiple' => false], 'items' => array_map(fn ($s) => ['title' => $s[0], 'blocks' => $s[1]], $sections)];
}
/**
* @param list<int> $people
* @return array<string, mixed>
*/
private function contacts(string $title, array $people): array
{
return ['type' => 'contacts', 'data' => ['title' => $title, 'people' => $people, 'layout' => 'cards']];
}
// ---------------------------------------------------------------------
// Downloads
// ---------------------------------------------------------------------
private function downloads(): void
{
$folders = DemoData::downloads();
$count = 0;
foreach (array_keys($folders) as $sort => $name) {
[$description, $files] = $folders[$name];
$folder = $this->track(DownloadFolder::query()->create([
'name' => $name,
'description' => $description,
'sort' => $sort,
'created_by' => $this->by?->id,
]));
foreach ($files as [$title, $fileDescription, $lines]) {
$download = $this->track($folder->downloads()->create([
'title' => $title,
'description' => $fileDescription,
'created_by' => $this->by?->id,
'updated_by' => $this->by?->id,
]));
$bytes = $this->pdf($title, [$fileDescription, '', ...$lines]);
$path = $this->storeFile(DownloadVersion::DISK, 'downloads/'.$folder->id.'/'.Str::random(40).'.pdf', $bytes);
$version = $this->track($download->versions()->create([
'version' => 1,
'name' => Str::slug($title, '-', 'de').'.pdf',
'path' => $path,
'mime' => 'application/pdf',
'size' => strlen($bytes),
'uploaded_by' => $this->by?->id,
'created_at' => now(),
]));
$download->forceFill(['current_version_id' => $version->id])->save();
$count++;
}
}
$this->count('Download-Ordner', count($folders));
$this->count('Downloads', $count);
}
// ---------------------------------------------------------------------
// Qualitätsmanagement
// ---------------------------------------------------------------------
private function qm(): void
{
$indexer = app(Indexer::class);
$folders = 0;
$entries = 0;
$sort = 0;
foreach (array_keys(DemoData::qm()) as $categorySort => $categoryName) {
$category = $this->track(QmCategory::query()->create(['name' => $categoryName, 'sort' => $categorySort]));
foreach (DemoData::qm()[$categoryName] as [$name, $color, $icon, $intro, $contacts, $items]) {
$folder = $this->track(QmFolder::query()->create([
'category_id' => $category->id,
'name' => $name,
'color' => $color,
'icon' => $icon,
'intro' => '<p>'.e($intro).'</p>',
'sort' => $sort++,
'created_by' => $this->by?->id,
]));
$folders++;
$folder->contacts()->sync(collect($this->personIds($contacts))->mapWithKeys(fn ($id, $position) => [$id => ['sort' => $position]])->all());
foreach ($items as $position => [$type, $title, $version, $daysAgo, $payload]) {
$validFrom = now()->subDays($daysAgo)->toDateString();
$entry = $this->track($folder->entries()->create([
'type' => $type,
'title' => $title,
'version' => $version,
'valid_from' => $validFrom,
'url' => $type === QmEntry::LINK ? $payload : null,
'sort' => $position,
'created_by' => $this->by?->id,
'updated_by' => $this->by?->id,
]));
if ($type === QmEntry::FILE) {
$bytes = $this->pdf($title, ['Version '.$version.' · gültig ab '.Carbon::parse($validFrom)->format('d.m.Y'), '', ...$payload]);
$file = $this->track($entry->files()->create([
'kind' => QmFile::READING,
'version' => $version,
'valid_from' => $validFrom,
'name' => Str::slug($title, '-', 'de').'.pdf',
'path' => $this->storeFile(QmFile::DISK, 'qm/'.$entry->id.'/'.Str::random(40).'.pdf', $bytes),
'mime' => 'application/pdf',
'size' => strlen($bytes),
'uploaded_by' => $this->by?->id,
'created_at' => now(),
]));
try {
$indexer->index($file);
} catch (Throwable) {
// Ohne Textauszug bleibt die Datei trotzdem nutzbar.
}
}
$entries++;
}
}
}
if (blank(strip_tags((string) $this->settings->get(Presenter::HOME_INTRO, '')))) {
$this->setSetting(Presenter::HOME_INTRO, '<p>Hier finden Sie alle gültigen Verfahrensanweisungen, Konzepte, Hygienepläne und Betriebsanweisungen – immer in der aktuellen Fassung. Ausdrucke gelten nur am Tag des Drucks.</p><p>Fragen und Verbesserungsvorschläge an die QM-Beauftragte Claudia Heyen (Durchwahl 150).</p>');
}
if (blank($this->settings->get(Presenter::HOME_CONTACTS)) && isset($this->people[DemoData::QM])) {
$this->setSetting(Presenter::HOME_CONTACTS, [$this->people[DemoData::QM]->id]);
}
$this->count('QM-Ordner', $folders);
$this->count('QM-Einträge', $entries);
}
// ---------------------------------------------------------------------
// Glossar, Stellen, Ideen, Umfragen, Formulare
// ---------------------------------------------------------------------
private function glossary(): void
{
$count = 0;
foreach (DemoData::glossary() as [$term, $aliases, $description]) {
if (GlossaryEntry::query()->where('term', $term)->exists()) {
continue;
}
$this->track(GlossaryEntry::query()->create(['term' => $term, 'aliases' => $aliases, 'description' => '<p>'.e($description).'</p>', 'created_by' => $this->by?->id]));
$count++;
}
$this->count('Glossar-Einträge', $count);
}
private function jobs(): void
{
foreach (DemoData::jobs() as $job) {
$posting = JobPosting::query()->make([
...collect($job)->except(['deadline', 'contact'])->all(),
'deadline' => now()->addDays($job['deadline'])->toDateString(),
'apply_mode' => 'online',
'contact_id' => $this->person($job['contact'])?->id,
'published_at' => now()->subDays(3),
'created_by' => $this->by?->id,
]);
// Als schon angekündigt markieren – Demo-Inhalte sollen niemanden benachrichtigen
$posting->forceFill(['announced_at' => now()->subDays(3)])->save();
$this->track($posting);
}
$this->count('Stellenangebote', count(DemoData::jobs()));
}
private function ideas(): void
{
foreach (DemoData::ideas() as [$title, $body, $author, $status, $note, $supports, $daysAgo]) {
$idea = new Idea([
'title' => $title,
'body' => $body,
'author_id' => $author !== null ? $this->person($author)?->id : $this->by?->id,
'anonymous' => $author === null,
'status' => $status,
'status_note' => $note,
'status_changed_at' => $note ? now()->subDays(max(0, $daysAgo - 5)) : null,
]);
$idea->supports_count = $supports;
$idea->created_at = now()->subDays($daysAgo);
$idea->save();
$this->track($idea);
if ($note) {
$this->track(IdeaComment::query()->create(['idea_id' => $idea->id, 'user_id' => $this->person(DemoData::GF)?->id, 'body' => $note, 'official' => true]));
$idea->forceFill(['comments_count' => 1])->save();
}
}
$this->count('Ideen', count(DemoData::ideas()));
}
private function polls(): void
{
foreach (DemoData::polls() as [$title, $description, $questions, $open, $daysAgo]) {
$this->track(Poll::query()->create([
'title' => $title,
'description' => $description,
'questions' => Questions::sanitize($questions),
'anonymous' => true,
'results_visibility' => Poll::AFTER_VOTE,
'published_at' => now()->subDays($daysAgo),
'closes_at' => $open ? now()->addDays(14) : now()->subDays(max(1, $daysAgo - 21)),
'announce' => false,
'author_id' => $this->person(DemoData::GF)?->id,
]));
}
$this->count('Umfragen', count(DemoData::polls()));
}
private function forms(): void
{
foreach (DemoData::forms() as [$title, $description, $fields]) {
$slug = Str::slug($title, '-', 'de');
if (Form::query()->where('slug', $slug)->exists()) {
continue;
}
$this->track(Form::query()->create([
'title' => $title,
'slug' => $slug,
'description' => $description,
'fields' => FormFields::normalize($fields),
'settings' => [],
'is_open' => true,
'created_by' => $this->by?->id,
]));
}
$this->count('Formulare', count(DemoData::forms()));
}
// ---------------------------------------------------------------------
// Gemeinsam feiern und Geburtstage
// ---------------------------------------------------------------------
private function gemeinsam(): void
{
$day = fn (int $n) => now()->startOfMonth()->addDays(min($n, now()->daysInMonth - 1))->toDateString();
$person = fn (int $i) => $this->people[$i] ?? null;
$entries = [
['section' => 'welcome', 'user_id' => $person(DemoData::IT_SUPPORT)?->id, 'name' => 'Merve Yıldız', 'date' => $day(0), 'department' => 'IT', 'location' => 'Geschäftsstelle'],
['section' => 'welcome', 'user_id' => $person(DemoData::AZUBI)?->id, 'name' => 'Elif Demir', 'date' => $day(3), 'department' => 'Wohnen', 'location' => 'Wohnhaus Lindenhof'],
['section' => 'jubilee', 'user_id' => $person(DemoData::WERKSTATT)?->id, 'name' => 'Frank Möller', 'date' => $day(9), 'department' => 'Werkstatt', 'location' => 'Werkstatt am Kanal', 'label' => '25 Jahre'],
['section' => 'jubilee', 'user_id' => $person(DemoData::MAV)?->id, 'name' => 'Martina Kamp', 'date' => $day(17), 'department' => 'Mitarbeitervertretung', 'location' => 'Geschäftsstelle', 'label' => '10 Jahre'],
['section' => 'farewell', 'user_id' => null, 'name' => 'Heinz-Werner Tebbe', 'date' => $day(27), 'department' => 'Haustechnik', 'location' => 'Werkstatt am Kanal', 'label' => 'Ruhestand', 'text' => 'Nach 32 Jahren verabschieden wir unseren Haustechniker in den Ruhestand. Danke für alles, Heinz-Werner!'],
];
foreach ($entries as $entry) {
$this->track(Entry::query()->create([...$entry, 'created_by' => $this->by?->id]));
}
$this->count('Gemeinsam feiern', count($entries));
}
private function birthdays(): void
{
$offsets = [DemoData::GF => 0, DemoData::IT => 2, DemoData::BBB => 5, DemoData::ABW => 12, DemoData::KUECHE => 40, DemoData::HOLZ => 75];
$count = 0;
foreach ($offsets as $index => $days) {
$person = $this->people[$index] ?? null;
if (! $person || ! $person->wasRecentlyCreated || Birthday::query()->where('user_id', $person->id)->exists()) {
continue;
}
$date = now()->addDays($days);
$this->track(Birthday::query()->create(['user_id' => $person->id, 'month' => $date->month, 'day' => $date->day]));
$count++;
}
$this->count('Geburtstage', $count);
}
// ---------------------------------------------------------------------
// Hilfsfunktionen
// ---------------------------------------------------------------------
private function loaded(string $slug): bool
{
return $this->plugins->isLoaded($slug);
}
/**
* @template T of Model
*
* @param T $model
* @return T
*/
private function track(Model $model): Model
{
$class = $model::class;
$last = array_key_last($this->state['records']);
if ($last !== null && $this->state['records'][$last]['model'] === $class) {
$this->state['records'][$last]['ids'][] = (int) $model->getKey();
} else {
$this->state['records'][] = ['model' => $class, 'table' => $model->getTable(), 'ids' => [(int) $model->getKey()]];
}
return $model;
}
private function count(string $label, int $count): void
{
if ($count > 0) {
$this->state['counts'][] = ['label' => $label, 'count' => $count];
}
}
private function setSetting(string $key, mixed $value): void
{
$existed = Setting::query()->whereKey($key)->exists();
$this->state['settings'][] = ['key' => $key, 'existed' => $existed, 'previous' => $this->settings->get($key), 'value' => $value];
$this->settings->set($key, $value);
}
private function persist(): void
{
$this->settings->set(self::SETTING, $this->state);
}
private function storeFile(string $disk, string $path, string $bytes, bool $image = false): string
{
Storage::disk($disk)->put($path, $bytes);
$this->state['files'][] = ['disk' => $disk, 'path' => $path, 'image' => $image];
return $path;
}
/**
* Fotos von picsum.photos (frei nutzbare Unsplash-Bilder) parallel laden,
* ohne Netz ruhige Farbflächen in der Markenfarbe.
*
* @param array<int|string, string> $seeds
* @return array<string, string> Seed => Pfad im Speicher „uploads“
*/
private function images(string $directory, array $seeds): array
{
$seeds = array_values(array_unique($seeds));
try {
$responses = Http::pool(fn (Pool $pool) => array_map(
fn (string $seed) => $pool->as($seed)->timeout(10)->connectTimeout(5)->get("https://picsum.photos/seed/inhaus-{$seed}/1600/900"),
$seeds,
));
} catch (Throwable) {
$responses = [];
}
$paths = [];
foreach ($seeds as $seed) {
$response = $responses[$seed] ?? null;
$ok = $response instanceof Response && $response->successful() && str_starts_with((string) $response->header('Content-Type'), 'image/');
$paths[$seed] = $this->storeFile('uploads', "{$directory}/{$seed}-".Str::lower(Str::random(6)).'.jpg', $ok ? $response->body() : $this->placeholder($seed), true);
}
return $paths;
}
private function placeholder(string $seed): string
{
$palette = app(Branding::class)->palette();
$shades = [$palette[700], $palette[800], $palette[900], $palette[600]];
[$r, $g, $b] = sscanf($shades[crc32($seed) % count($shades)], '#%02x%02x%02x');
$image = imagecreatetruecolor(1600, 900);
imagefill($image, 0, 0, imagecolorallocate($image, $r, $g, $b));
imagefilledellipse($image, 1300, 200, 1100, 1100, imagecolorallocatealpha($image, 255, 255, 255, 115));
ob_start();
imagejpeg($image, null, 85);
return (string) ob_get_clean();
}
/**
* Schlichtes einseitiges PDF (A4, Helvetica) mit Überschrift und Textzeilen.
*
* @param list<string> $lines
*/
/**
* Schlichtes PDF mit Textebene (Helvetica, WinAnsi) – mehrseitig, damit auch längere
* Verfahrensanweisungen vollständig lesbar und durchsuchbar sind.
*
* @param list<string> $lines
*/
private function pdf(string $title, array $lines): string
{
$encode = fn (string $text) => str_replace(['\\', '(', ')'], ['\\\\', '\\(', '\\)'], (string) mb_convert_encoding($text, 'Windows-1252', 'UTF-8'));
$streams = [];
$stream = 'BT /F1 18 Tf 72 760 Td ('.$encode($title).") Tj ET\n";
$stream .= 'BT /F1 9 Tf 72 740 Td ('.$encode('Demo-Dokument – Beispielinhalt für das Mitarbeiterportal').") Tj ET\n";
$y = 710;
foreach ($lines as $line) {
foreach (explode("\n", wordwrap($line, 85, "\n", true)) as $part) {
if ($y < 72) {
$streams[] = $stream;
$stream = '';
$y = 770;
}
$stream .= "BT /F1 11 Tf 72 {$y} Td (".$encode($part).") Tj ET\n";
$y -= 16;
}
$y -= 6; // Abstand zwischen Absätzen
}
$streams[] = $stream;
// 1 Katalog, 2 Seitenbaum, 3 Schrift, dann je Seite: Seite + Inhalt
$pageIds = array_map(fn (int $i) => 4 + $i * 2, array_keys($streams));
$objects = [
'<< /Type /Catalog /Pages 2 0 R >>',
'<< /Type /Pages /Kids ['.implode(' ', array_map(fn ($id) => "{$id} 0 R", $pageIds)).'] /Count '.count($streams).' >>',
'<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>',
];
foreach ($streams as $i => $content) {
$objects[] = '<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Resources << /Font << /F1 3 0 R >> >> /Contents '.($pageIds[$i] + 1).' 0 R >>';
$objects[] = '<< /Length '.strlen($content)." >>\nstream\n{$content}endstream";
}
$pdf = "%PDF-1.4\n%\xE2\xE3\xCF\xD3\n";
$offsets = [];
foreach ($objects as $i => $object) {
$offsets[] = strlen($pdf);
$pdf .= ($i + 1)." 0 obj\n{$object}\nendobj\n";
}
$xref = strlen($pdf);
$pdf .= 'xref'."\n0 ".(count($objects) + 1)."\n0000000000 65535 f \n";
foreach ($offsets as $offset) {
$pdf .= sprintf("%010d 00000 n \n", $offset);
}
return $pdf.'trailer'."\n<< /Size ".(count($objects) + 1)." /Root 1 0 R >>\nstartxref\n{$xref}\n%%EOF\n";
}
}