}>, files: list, settings: list, counts: list} */ private array $state = ['records' => [], 'files' => [], 'settings' => [], 'counts' => []]; /** @var list */ 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 */ 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, warnings: list} */ 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} */ 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 */ 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 $areas * @return array 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 $indexes * @return list */ 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' => '

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.

', '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 $post */ private function article(array $post): string { $html = '

'.e($post['intro']).'

'; foreach ($post['sections'] as $section) { $html .= '

'.e($section[0]).'

'.e($section[1]).'

'; if (! empty($section[2])) { $html .= '
    '.implode('', array_map(fn ($item) => '
  • '.e($item).'
  • ', $section[2])).'
'; } } if (! empty($post['quote'])) { $html .= '

„'.e($post['quote'][0]).'“ – '.e($post['quote'][1]).'

'; } return $html.'

'.e($post['outro']).'

'; } // --------------------------------------------------------------------- // 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' => '

'.e($description).'

', '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 $spec * @return array */ 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 */ private function heading(string $text, string $level = '2'): array { return ['type' => 'heading', 'data' => ['text' => $text, 'level' => $level]]; } /** @return array */ private function text(string $html): array { return ['type' => 'text', 'data' => ['html' => $html]]; } /** @return array */ private function quote(string $text, string $source): array { return ['type' => 'quote', 'data' => ['text' => $text, 'source' => $source]]; } /** * @param list $items * @return array */ 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> $blocks * @return array */ 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>}> $sections * @return array */ 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 $people * @return array */ 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' => '

'.e($intro).'

', '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, '

Hier finden Sie alle gültigen Verfahrensanweisungen, Konzepte, Hygienepläne und Betriebsanweisungen – immer in der aktuellen Fassung. Ausdrucke gelten nur am Tag des Drucks.

Fragen und Verbesserungsvorschläge an die QM-Beauftragte Claudia Heyen (Durchwahl 150).

'); } 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' => '

'.e($description).'

', '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 $seeds * @return array 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 $lines */ /** * Schlichtes PDF mit Textebene (Helvetica, WinAnsi) – mehrseitig, damit auch längere * Verfahrensanweisungen vollständig lesbar und durchsuchbar sind. * * @param list $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"; } }