QM-Texterkennung: Imagick nur mit Ghostscript als verfügbar melden
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Failing after 3m18s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Failing after 3m27s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Failing after 3m0s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Failing after 2m56s
CI / PHP 8.3 / mysql:8.0 (pull_request) Failing after 4m4s
CI / PHP 8.4 / mysql:8.0 (pull_request) Failing after 4m1s
CI / PHP 8.3 / mysql:8.4 (pull_request) Failing after 3m41s
CI / PHP 8.4 / mysql:8.4 (pull_request) Failing after 3m39s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m10s

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-26 16:38:17 +00:00
parent 5a360d3cc7
commit b50d089946
117 changed files with 1747 additions and 2 deletions

View file

@ -0,0 +1,27 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('speiseplan_weeks', function (Blueprint $table) {
$table->id();
$table->date('week_start')->unique(); // Montag der Woche
$table->string('path');
$table->string('original_name')->nullable();
$table->unsignedInteger('width')->nullable();
$table->unsignedInteger('height')->nullable();
$table->foreignId('uploaded_by')->nullable()->constrained('users')->nullOnDelete();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('speiseplan_weeks');
}
};

View file

@ -0,0 +1,14 @@
{
"slug": "speiseplan",
"name": "Speiseplan",
"version": "1.0.0",
"description": "Speisepläne der Kantine als Bild je Woche – mehrere Wochen im Voraus, PDF wird automatisch zum Bild. Anzeige der aktuellen und der nächsten Woche, Allergie-Informationen als PDF und randloser A4-Druck.",
"author": "Inhaus",
"namespace": "Inhaus\\Plugins\\Speiseplan\\",
"class": "Inhaus\\Plugins\\Speiseplan\\SpeiseplanPlugin",
"enabled_by_default": false,
"requires": {
"core": ">=0.12.0",
"php": ">=8.3"
}
}

View file

@ -0,0 +1,113 @@
<script setup>
import { ref } from 'vue';
import { router, useForm } from '@inertiajs/vue3';
import { FileText, LoaderCircle, Trash2, Upload } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import FormField from '@/components/FormField.vue';
import NativeSelect from '@/components/NativeSelect.vue';
import { pdfToImage } from '../pdfToImage';
const props = defineProps({
manage: { type: Object, required: true },
allergens: { type: Object, default: null },
});
const form = useForm({ week: props.manage.suggested, image: null });
const converting = ref(false);
const dragging = ref(false);
const fileInput = ref(null);
const allergenInput = ref(null);
async function upload(file) {
if (!file) return;
let image = file;
if (file.type === 'application/pdf' || /\.pdf$/i.test(file.name)) {
converting.value = true;
try {
image = await pdfToImage(file);
} catch {
toast.error('Das PDF ließ sich nicht umwandeln. Bitte als Bild hochladen.');
return;
} finally {
converting.value = false;
}
}
form.image = image;
form.post('/speiseplan/wochen', {
forceFormData: true,
preserveScroll: true,
onError: (errors) => toast.error(Object.values(errors)[0]),
onSuccess: () => {
form.image = null;
form.week = props.manage.suggested;
},
});
}
function uploadAllergens(file) {
if (!file) return;
router.post('/speiseplan/allergene', { file }, { forceFormData: true, preserveScroll: true, onError: (e) => toast.error(Object.values(e)[0]) });
}
function remove(plan) {
if (window.confirm(`Speiseplan ${plan.label} entfernen?`)) router.delete(`/speiseplan/wochen/${plan.id}`, { preserveScroll: true });
}
</script>
<template>
<section class="mt-10 rounded-lg border bg-card print:hidden">
<h2 class="border-b px-5 py-3 text-base font-semibold">Speiseplan hochladen</h2>
<div class="grid gap-6 p-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<div class="grid content-start gap-4">
<FormField id="sp-week" label="Woche" :error="form.errors.week">
<NativeSelect id="sp-week" v-model="form.week" :options="manage.options" />
</FormField>
<button
type="button"
class="grid place-items-center rounded-lg border-2 border-dashed px-6 py-10 text-center transition-colors"
:class="dragging ? 'border-brand-400 bg-brand-soft/60' : 'hover:border-brand-300'"
:disabled="form.processing || converting"
@click="fileInput?.click()"
@dragover.prevent="dragging = true"
@dragleave.prevent="dragging = false"
@drop.prevent="dragging = false; upload($event.dataTransfer.files[0])"
>
<LoaderCircle v-if="form.processing || converting" class="size-7 animate-spin text-muted-foreground" />
<Upload v-else class="size-7 text-muted-foreground" />
<span class="mt-2 text-sm font-medium">{{ converting ? 'PDF wird umgewandelt …' : form.processing ? 'Wird hochgeladen …' : 'PDF oder Bild hierher ziehen oder klicken' }}</span>
<span class="mt-1 text-xs text-muted-foreground">Ein PDF wird automatisch zum Bild (erste Seite, A4). Ist für die Woche schon ein Plan da, wird er ersetzt.</span>
</button>
<input ref="fileInput" type="file" accept="application/pdf,image/jpeg,image/png,image/webp" class="hidden" @change="upload($event.target.files[0]); $event.target.value = ''" />
<div class="flex flex-wrap items-center gap-3 rounded-md bg-muted/50 px-3 py-2.5 text-sm">
<FileText class="size-4 text-muted-foreground" />
<span class="min-w-0 flex-1 truncate">{{ allergens ? allergens.name : 'Noch keine Allergie-Informationen hinterlegt' }}</span>
<Button size="sm" variant="outline" @click="allergenInput?.click()">{{ allergens ? 'Ersetzen' : 'PDF hochladen' }}</Button>
<Button v-if="allergens" size="icon" variant="ghost" class="size-8" aria-label="Allergie-Informationen entfernen" @click="router.delete('/speiseplan/allergene', { preserveScroll: true })"><Trash2 /></Button>
<input ref="allergenInput" type="file" accept="application/pdf" class="hidden" @change="uploadAllergens($event.target.files[0]); $event.target.value = ''" />
</div>
</div>
<div>
<p class="mb-2 text-sm font-medium">Hochgeladene Wochen</p>
<ul v-if="manage.uploaded.length" class="grid grid-cols-[repeat(auto-fill,minmax(7rem,1fr))] gap-3">
<li v-for="plan in manage.uploaded" :key="plan.id" class="group relative">
<a :href="plan.image_url" target="_blank" class="block overflow-hidden rounded-md border bg-white" :class="{ 'opacity-60': plan.past }">
<img :src="plan.image_url" :alt="plan.label" class="aspect-[210/297] w-full object-cover object-top" loading="lazy" />
</a>
<p class="mt-1 text-xs font-medium">KW {{ plan.week }}</p>
<p class="text-[11px] text-muted-foreground">{{ plan.past ? 'vergangen' : plan.label.split('· ')[1] }}</p>
<button type="button" class="absolute top-1 right-1 grid size-7 place-items-center rounded-md bg-card/90 text-destructive opacity-0 shadow-xs ring-1 ring-border group-hover:opacity-100 focus-visible:opacity-100" :aria-label="`KW ${plan.week} entfernen`" @click="remove(plan)"><Trash2 class="size-3.5" /></button>
</li>
</ul>
<p v-else class="text-sm text-muted-foreground">Noch keine Pläne hochgeladen.</p>
<p class="mt-3 text-xs text-muted-foreground">Vergangene Wochen werden nach {{ manage.keepWeeks }} Wochen automatisch gelöscht.</p>
</div>
</div>
</section>
</template>

View file

@ -0,0 +1,61 @@
<script setup>
import { watch } from 'vue';
import { usePage } from '@inertiajs/vue3';
import { FileText, Printer, UtensilsCrossed } from '@lucide/vue';
import { toast } from 'vue-sonner';
import { Button } from '@/components/ui/button';
import PageHeader from '@/components/PageHeader.vue';
import AppLayout from '@/layouts/AppLayout.vue';
import ManagePanel from '../components/ManagePanel.vue';
const props = defineProps({
weeks: { type: Array, required: true },
allergens: { type: Object, default: null },
canManage: { type: Boolean, default: false },
manage: { type: Object, default: null },
});
const page = usePage();
watch(() => page.props.flash.status, (status) => status && toast.success(status), { immediate: true });
const printUrl = (ids) => `/speiseplan/druck${ids.length ? `?wochen=${ids.join(',')}` : ''}`;
const available = () => props.weeks.filter((w) => w.plan).map((w) => w.plan.id);
</script>
<template>
<AppLayout title="Speiseplan">
<PageHeader title="Speiseplan" description="Unsere Kantine – diese und nächste Woche.">
<template #actions>
<Button v-if="allergens" variant="outline" as-child><a :href="allergens.url" target="_blank" rel="noopener"><FileText /> Allergie-Informationen</a></Button>
<Button v-if="available().length" as-child><a :href="printUrl(available())" target="_blank" rel="noopener"><Printer /> Drucken</a></Button>
</template>
</PageHeader>
<div class="grid gap-6 lg:grid-cols-2">
<section v-for="week in weeks" :key="week.week_start" class="overflow-hidden rounded-lg border bg-card">
<header class="flex items-center justify-between gap-3 border-b px-4 py-2.5">
<div>
<h2 class="text-sm font-semibold">{{ week.title }}</h2>
<p class="text-xs text-muted-foreground">{{ week.label }}</p>
</div>
<Button v-if="week.plan" size="sm" variant="ghost" as-child><a :href="printUrl([week.plan.id])" target="_blank" rel="noopener"><Printer /> Nur diese Woche</a></Button>
</header>
<a v-if="week.plan" :href="week.plan.image_url" target="_blank" rel="noopener" class="block bg-muted/40 p-3" title="In voller Größe öffnen">
<img :src="week.plan.image_url" :alt="`Speiseplan ${week.label}`" class="mx-auto w-full max-w-2xl rounded shadow-sm" />
</a>
<div v-else class="grid aspect-[210/297] max-h-[36rem] w-full place-items-center bg-muted/30 text-center">
<div>
<UtensilsCrossed class="mx-auto size-8 text-muted-foreground" :stroke-width="1.5" />
<p class="mt-2 text-sm text-muted-foreground">Für diese Woche liegt noch kein Speiseplan vor.</p>
</div>
</div>
</section>
</div>
<p v-if="allergens" class="mt-6 text-sm">
<a :href="allergens.url" target="_blank" rel="noopener" class="inline-flex items-center gap-1.5 font-medium text-brand-text hover:underline"><FileText class="size-4" /> Allergie-Informationen (PDF)</a>
</p>
<ManagePanel v-if="canManage && manage" :manage="manage" :allergens="allergens" />
</AppLayout>
</template>

View file

@ -0,0 +1,118 @@
<script setup>
import { onMounted } from 'vue';
import { Head } from '@inertiajs/vue3';
/**
* Druckansicht ohne Portal-Rahmen: jeder Plan füllt eine A4-Seite randlos.
*/
const props = defineProps({
plans: { type: Array, required: true },
});
function print() {
window.print();
}
onMounted(async () => {
// Erst drucken, wenn alle Bilder geladen sind.
await Promise.all([...document.querySelectorAll('.sp-page img')].map((img) => (img.complete ? null : new Promise((r) => (img.onload = img.onerror = r)))));
if (props.plans.length) setTimeout(print, 150);
});
</script>
<template>
<Head title="Speiseplan drucken" />
<div class="sp-toolbar">
<strong>Speiseplan drucken</strong>
<span>{{ plans.length }} {{ plans.length === 1 ? 'Seite' : 'Seiten' }} · A4, randlos. Falls Adresse oder Datum mitgedruckt werden: im Druckdialog „Kopf- und Fußzeilen“ abschalten.</span>
<button type="button" @click="print">Drucken</button>
</div>
<p v-if="!plans.length" class="sp-empty">Kein Speiseplan zum Drucken vorhanden.</p>
<div v-for="plan in plans" :key="plan.id" class="sp-page">
<img :src="plan.image_url" :alt="`Speiseplan ${plan.label}`" />
</div>
</template>
<style>
@page {
size: A4 portrait;
margin: 0;
}
.sp-toolbar {
position: sticky;
top: 0;
z-index: 10;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 12px 16px;
background: #fff;
border-bottom: 1px solid #e5e7eb;
font: 14px/1.4 system-ui, sans-serif;
color: #111827;
}
.sp-toolbar span {
flex: 1;
color: #6b7280;
min-width: 240px;
}
.sp-toolbar button {
padding: 6px 14px;
border-radius: 6px;
background: #111827;
color: #fff;
border: 0;
cursor: pointer;
}
.sp-empty {
padding: 24px;
font: 14px system-ui, sans-serif;
}
.sp-page {
width: 210mm;
height: 297mm;
margin: 16px auto;
box-shadow: 0 1px 6px rgb(0 0 0 / 0.15);
background: #fff;
overflow: hidden;
}
.sp-page img {
display: block;
width: 100%;
height: 100%;
object-fit: fill;
}
@media print {
html,
body {
margin: 0 !important;
padding: 0 !important;
background: #fff !important;
}
.sp-toolbar,
.sp-empty {
display: none !important;
}
.sp-page {
margin: 0;
box-shadow: none;
break-after: page;
page-break-after: always;
}
.sp-page:last-child {
break-after: auto;
page-break-after: auto;
}
}
</style>

View file

@ -0,0 +1,28 @@
/**
* Erste Seite eines PDFs als JPEG in A4-Druckqualität (ca. 200 dpi) – im Browser,
* damit der Server nichts umwandeln muss.
*/
export async function pdfToImage(file, targetWidth = 1654) {
const [pdfjs, worker] = await Promise.all([import('pdfjs-dist'), import('pdfjs-dist/build/pdf.worker.min.mjs?url')]);
pdfjs.GlobalWorkerOptions.workerSrc = worker.default;
const pdf = await pdfjs.getDocument({ data: await file.arrayBuffer(), isEvalSupported: false, enableXfa: false }).promise;
try {
const page = await pdf.getPage(1);
const viewport = page.getViewport({ scale: targetWidth / page.getViewport({ scale: 1 }).width });
const canvas = document.createElement('canvas');
canvas.width = Math.round(viewport.width);
canvas.height = Math.round(viewport.height);
const context = canvas.getContext('2d');
context.fillStyle = '#ffffff';
context.fillRect(0, 0, canvas.width, canvas.height);
await page.render({ canvasContext: context, viewport }).promise;
const blob = await new Promise((resolve) => canvas.toBlob(resolve, 'image/jpeg', 0.9));
return new File([blob], file.name.replace(/\.pdf$/i, '') + '.jpg', { type: 'image/jpeg' });
} finally {
pdf.destroy();
}
}

View file

@ -0,0 +1,19 @@
<?php
use Illuminate\Support\Facades\Route;
use Inhaus\Plugins\Speiseplan\Http\Controllers\SpeiseplanController;
Route::middleware('auth')->prefix('speiseplan')->name('speiseplan.')->controller(SpeiseplanController::class)
->where(['week' => '[0-9]+'])
->group(function () {
Route::get('/', 'index')->name('index');
Route::get('/druck', 'print')->name('print');
Route::get('/bild/{week}', 'image')->name('image');
Route::get('/allergene', 'allergensFile')->name('allergens.show');
// Pflege (Recht „speiseplan.manage“)
Route::post('/wochen', 'store')->name('store');
Route::delete('/wochen/{week}', 'destroy')->name('destroy');
Route::post('/allergene', 'storeAllergens')->name('allergens.store');
Route::delete('/allergene', 'destroyAllergens')->name('allergens.destroy');
});

View file

@ -0,0 +1,176 @@
<?php
namespace Inhaus\Plugins\Speiseplan\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Support\Audit;
use App\Support\Settings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;
use Inhaus\Plugins\Speiseplan\Models\Week;
use Inhaus\Plugins\Speiseplan\SpeiseplanPlugin;
use Symfony\Component\HttpFoundation\Response as HttpResponse;
class SpeiseplanController extends Controller
{
private const ALLERGENS = 'speiseplan.allergens';
public function __construct(private readonly Settings $settings) {}
public function index(Request $request): Response
{
$monday = Week::mondayOf(now());
$weeks = Week::query()->whereIn('week_start', [$monday->toDateString(), $monday->copy()->addWeek()->toDateString()])->get()->keyBy(fn (Week $w) => $w->week_start->toDateString());
$canManage = (bool) $request->user()->can('speiseplan.manage');
$slot = fn ($start, string $title) => [
'title' => $title,
'label' => 'KW '.$start->isoWeek().' · '.$start->format('d.m.').' – '.$start->copy()->addDays(4)->format('d.m.Y'),
'week_start' => $start->toDateString(),
'plan' => ($w = $weeks->get($start->toDateString())) ? $w->present() : null,
];
return Inertia::render('speiseplan::Index', [
'weeks' => [$slot($monday, 'Diese Woche'), $slot($monday->copy()->addWeek(), 'Nächste Woche')],
'allergens' => $this->allergens(),
'canManage' => $canManage,
'manage' => $canManage ? $this->manageData($monday) : null,
]);
}
/**
* Druckansicht: jeder Plan eine A4-Seite, randlos.
*/
public function print(Request $request): Response
{
$ids = array_filter(array_map('intval', explode(',', (string) $request->query('wochen', ''))));
$monday = Week::mondayOf(now());
$query = Week::query()->orderBy('week_start');
$ids ? $query->whereIn('id', $ids) : $query->whereIn('week_start', [$monday->toDateString(), $monday->copy()->addWeek()->toDateString()]);
return Inertia::render('speiseplan::Print', ['plans' => $query->get()->map(fn (Week $w) => $w->present())->values()]);
}
public function image(Week $week): HttpResponse
{
return Storage::disk(Week::DISK)->response($week->path, 'speiseplan-kw'.$week->week_start->isoWeek().'.'.pathinfo($week->path, PATHINFO_EXTENSION), [
'Cache-Control' => 'private, max-age=86400',
'X-Content-Type-Options' => 'nosniff',
]);
}
private function allergens(): ?array
{
$file = $this->settings->get(self::ALLERGENS);
return is_array($file) && ! empty($file['path']) ? ['name' => $file['name'], 'url' => route('speiseplan.allergens.show')] : null;
}
public function store(Request $request): RedirectResponse
{
$this->authorizeManage($request);
$data = $request->validate([
'week' => ['required', 'date'],
'image' => ['required', 'file', 'max:20480', 'mimes:jpg,jpeg,png,webp'],
], ['image.mimes' => 'Bitte ein Bild (JPG, PNG, WebP) oder ein PDF hochladen.'], ['week' => 'Woche', 'image' => 'Speiseplan']);
$monday = Week::mondayOf($data['week']);
$file = $request->file('image');
[$width, $height] = @getimagesize($file->getRealPath()) ?: [null, null];
$path = $file->storeAs('speiseplan', $monday->toDateString().'-'.Str::random(12).'.'.strtolower($file->extension() ?: 'jpg'), Week::DISK);
$existing = Week::query()->where('week_start', $monday->toDateString())->first();
$old = $existing?->path;
Week::query()->updateOrCreate(['week_start' => $monday->toDateString()], [
'path' => $path, 'original_name' => $file->getClientOriginalName(), 'width' => $width, 'height' => $height, 'uploaded_by' => $request->user()->id,
]);
if ($old) {
Storage::disk(Week::DISK)->delete($old);
}
Audit::log('speiseplan.uploaded', ['week' => $monday->toDateString()]);
return back()->with('status', 'Speiseplan für KW '.$monday->isoWeek().($existing ? ' ersetzt.' : ' gespeichert.'));
}
public function destroy(Request $request, Week $week): RedirectResponse
{
$this->authorizeManage($request);
$week->delete();
return back()->with('status', 'Speiseplan für KW '.$week->week_start->isoWeek().' entfernt.');
}
public function storeAllergens(Request $request): RedirectResponse
{
$this->authorizeManage($request);
$request->validate(['file' => ['required', 'file', 'max:20480', 'mimes:pdf']], [], ['file' => 'Allergie-Informationen']);
$old = $this->settings->get(self::ALLERGENS);
$path = $request->file('file')->storeAs('speiseplan', 'allergene-'.Str::random(12).'.pdf', Week::DISK);
$this->settings->set(self::ALLERGENS, ['path' => $path, 'name' => $request->file('file')->getClientOriginalName()]);
if (is_array($old) && ! empty($old['path'])) {
Storage::disk(Week::DISK)->delete($old['path']);
}
return back()->with('status', 'Allergie-Informationen gespeichert.');
}
public function destroyAllergens(Request $request): RedirectResponse
{
$this->authorizeManage($request);
$old = $this->settings->get(self::ALLERGENS);
if (is_array($old) && ! empty($old['path'])) {
Storage::disk(Week::DISK)->delete($old['path']);
}
$this->settings->set(self::ALLERGENS, null);
return back()->with('status', 'Allergie-Informationen entfernt.');
}
public function allergensFile(): HttpResponse
{
$file = $this->settings->get(self::ALLERGENS);
abort_unless(is_array($file) && ! empty($file['path']) && Storage::disk(Week::DISK)->exists($file['path']), 404);
return Storage::disk(Week::DISK)->response($file['path'], $file['name'] ?? 'allergene.pdf', ['Content-Type' => 'application/pdf', 'X-Content-Type-Options' => 'nosniff']);
}
/**
* @return array<string, mixed>
*/
private function manageData($monday): array
{
$uploaded = Week::query()->where('week_start', '>=', $monday->copy()->subWeeks(SpeiseplanPlugin::KEEP_WEEKS)->toDateString())->orderBy('week_start')->get()->keyBy(fn (Week $w) => $w->week_start->toDateString());
$options = [];
for ($i = 0; $i < 12; $i++) {
$start = $monday->copy()->addWeeks($i);
$options[] = [
'value' => $start->toDateString(),
'label' => 'KW '.$start->isoWeek().' · '.$start->format('d.m.').' – '.$start->copy()->addDays(4)->format('d.m.Y').($uploaded->has($start->toDateString()) ? ' (vorhanden)' : ''),
'uploaded' => $uploaded->has($start->toDateString()),
];
}
return [
'options' => $options,
'suggested' => collect($options)->firstWhere('uploaded', false)['value'] ?? $options[0]['value'],
'uploaded' => $uploaded->values()->map(fn (Week $w) => $w->present() + ['past' => $w->week_start->lt($monday)])->all(),
'keepWeeks' => SpeiseplanPlugin::KEEP_WEEKS,
];
}
private function authorizeManage(Request $request): void
{
abort_unless($request->user()->can('speiseplan.manage'), 403);
}
}

View file

@ -0,0 +1,52 @@
<?php
namespace Inhaus\Plugins\Speiseplan\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
/**
* Speiseplan einer Kalenderwoche (ein Bild, A4 hoch).
*/
#[Fillable(['week_start', 'path', 'original_name', 'width', 'height', 'uploaded_by'])]
class Week extends Model
{
public const DISK = 'local';
protected $table = 'speiseplan_weeks';
protected static function booted(): void
{
static::deleted(fn (Week $week) => Storage::disk(self::DISK)->delete($week->path));
}
protected function casts(): array
{
return ['week_start' => 'date'];
}
public static function mondayOf(Carbon|string $date): Carbon
{
return Carbon::parse($date)->startOfWeek(Carbon::MONDAY)->startOfDay();
}
/**
* @return array<string, mixed>
*/
public function present(): array
{
$end = $this->week_start->copy()->addDays(4);
return [
'id' => $this->id,
'week_start' => $this->week_start->toDateString(),
'week' => (int) $this->week_start->isoWeek(),
'label' => 'KW '.$this->week_start->isoWeek().' · '.$this->week_start->format('d.m.').' – '.$end->format('d.m.Y'),
'image_url' => route('speiseplan.image', ['week' => $this->id, 'v' => $this->updated_at?->timestamp]),
'width' => $this->width,
'height' => $this->height,
];
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Inhaus\Plugins\Speiseplan;
use App\Plugins\Plugin;
use App\Support\Abilities;
use App\Support\Navigation;
use Illuminate\Support\Facades\Schedule;
use Inhaus\Plugins\Speiseplan\Models\Week;
class SpeiseplanPlugin extends Plugin
{
/** Vergangene Wochen bleiben so lange erhalten, dann werden sie gelöscht. */
public const KEEP_WEEKS = 2;
public function register(): void
{
$this->app->make(Navigation::class)->add('speiseplan', 'Speiseplan', '/speiseplan', active: 'speiseplan.*', sort: 70);
$this->app->make(Abilities::class)->define('speiseplan.manage', 'Speiseplan hochladen', 'Speiseplan');
}
public function boot(): void
{
Schedule::call(fn () => self::purge())->dailyAt('03:30')->name('speiseplan-purge')->withoutOverlapping(10);
}
public static function purge(): int
{
$cutoff = Week::mondayOf(now())->subWeeks(self::KEEP_WEEKS);
$old = Week::query()->where('week_start', '<', $cutoff->toDateString())->get();
$old->each->delete();
return $old->count();
}
}