diff --git a/app/Filament/Operator/Concerns/EditsTenantServices.php b/app/Filament/Operator/Concerns/EditsTenantServices.php index 0024c04..40d1cdf 100644 --- a/app/Filament/Operator/Concerns/EditsTenantServices.php +++ b/app/Filament/Operator/Concerns/EditsTenantServices.php @@ -10,6 +10,8 @@ * The service switches of the tenant form. They live in their own table, so the form state is read and * written separately from the landlord's own columns. Only wired services are written – a switch for a * service nothing asks about would promise something that does not happen. + * + * Holds no Filament hooks; EditsTenantSetup calls these. */ trait EditsTenantServices { @@ -17,7 +19,7 @@ trait EditsTenantServices * @param array $data * @return array */ - protected function mutateFormDataBeforeFill(array $data): array + private function fillServices(array $data): array { $tenant = $this->record; @@ -40,35 +42,7 @@ protected function mutateFormDataBeforeFill(array $data): array * @param array $data * @return array */ - protected function mutateFormDataBeforeCreate(array $data): array - { - return $this->withoutServices($data); - } - - /** - * @param array $data - * @return array - */ - protected function mutateFormDataBeforeSave(array $data): array - { - return $this->withoutServices($data); - } - - protected function afterCreate(): void - { - $this->saveServices(); - } - - protected function afterSave(): void - { - $this->saveServices(); - } - - /** - * @param array $data - * @return array - */ - private function withoutServices(array $data): array + private function takeServices(array $data): array { $this->services = is_array($data['services'] ?? null) ? $data['services'] : []; diff --git a/app/Filament/Operator/Concerns/EditsTenantSetup.php b/app/Filament/Operator/Concerns/EditsTenantSetup.php new file mode 100644 index 0000000..4396ccc --- /dev/null +++ b/app/Filament/Operator/Concerns/EditsTenantSetup.php @@ -0,0 +1,58 @@ +> */ + public array $services = []; + + /** @var list> */ + public array $websites = []; + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeFill(array $data): array + { + return $this->fillWebsites($this->fillServices($data)); + } + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeCreate(array $data): array + { + return $this->takeWebsites($this->takeServices($data)); + } + + /** + * @param array $data + * @return array + */ + protected function mutateFormDataBeforeSave(array $data): array + { + return $this->takeWebsites($this->takeServices($data)); + } + + protected function afterCreate(): void + { + $this->saveServices(); + $this->saveWebsites(); + } + + protected function afterSave(): void + { + $this->saveServices(); + $this->saveWebsites(); + } +} diff --git a/app/Filament/Operator/Concerns/EditsTenantWebsites.php b/app/Filament/Operator/Concerns/EditsTenantWebsites.php new file mode 100644 index 0000000..a8c8b39 --- /dev/null +++ b/app/Filament/Operator/Concerns/EditsTenantWebsites.php @@ -0,0 +1,182 @@ + $data + * @return array + */ + private function fillWebsites(array $data): array + { + $tenant = $this->record; + + if (! $tenant instanceof Tenant) { + return $data; + } + + $data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get() + ->map(fn (Site $site): array => [ + 'id' => $site->id, + 'name' => $site->name, + 'hosts' => $site->domains->pluck('host')->all(), + ]) + ->all(); + + return $data; + } + + /** + * @param array $data + * @return array + */ + private function takeWebsites(array $data): array + { + $this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : []; + + $this->normaliseWebsites(); + + unset($data['websites']); + + return $data; + } + + /** + * Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written. + */ + private function normaliseWebsites(): void + { + $seen = []; + + foreach ($this->websites as $index => $website) { + $hosts = []; + + foreach ((array) ($website['hosts'] ?? []) as $host) { + $host = SiteDomain::normalise(is_string($host) ? $host : null); + + if ($host === '') { + continue; + } + + if (in_array($host, $seen, true)) { + throw ValidationException::withMessages([ + 'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.', + ]); + } + + $seen[] = $host; + $hosts[] = $host; + } + + $this->websites[$index]['hosts'] = $hosts; + } + + $this->refuseForeignHosts($seen); + } + + /** + * @param list $hosts + */ + private function refuseForeignHosts(array $hosts): void + { + $ownIds = collect($this->websites)->pluck('id')->filter()->all(); + + $taken = SiteDomain::query() + ->whereIn('host', $hosts) + ->whereNotIn('site_id', $ownIds ?: [0]) + ->pluck('host'); + + if ($taken->isNotEmpty()) { + throw ValidationException::withMessages([ + 'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '), + ]); + } + } + + /** + * Writes the websites. A website that is new gets an empty home page straight away, because a website + * without one answers 404 and the landlord would have no way in. + */ + private function saveWebsites(): void + { + $tenant = $this->record; + + if (! $tenant instanceof Tenant) { + return; + } + + app(TenantContext::class)->run($tenant, function () use ($tenant): void { + $keep = []; + + foreach ($this->websites as $website) { + $name = trim((string) ($website['name'] ?? '')); + + if ($name === '') { + continue; + } + + $hosts = (array) ($website['hosts'] ?? []); + $site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts); + + $keep[] = $site->id; + + $site->domains()->whereNotIn('host', $hosts ?: [''])->delete(); + + foreach ($hosts as $host) { + SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]); + } + } + + $tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete()); + }); + } + + /** + * @param list $hosts + */ + private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site + { + $site = $id ? Site::query()->whereKey($id)->first() : null; + + if ($site !== null) { + $site->update(['name' => $name, 'domain' => $hosts[0] ?? null]); + + return $site; + } + + $site = Site::query()->create([ + 'tenant_id' => $tenant->id, + 'name' => $name, + 'domain' => $hosts[0] ?? null, + 'is_default' => $tenant->sites()->count() === 0, + 'theme' => config('themes.base'), + ]); + + Page::query()->create([ + 'site_id' => $site->id, + 'slug' => Page::HOME, + 'title' => $name, + 'sections' => [], + 'is_published' => true, + ]); + + return $site; + } +} diff --git a/app/Filament/Operator/Pages/SystemSettingsPage.php b/app/Filament/Operator/Pages/SystemSettingsPage.php new file mode 100644 index 0000000..00b9b04 --- /dev/null +++ b/app/Filament/Operator/Pages/SystemSettingsPage.php @@ -0,0 +1,114 @@ + */ + public array $data = []; + + public function mount(): void + { + $this->form->fill(collect(SystemSettings::EDITABLE) + ->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)]) + ->all()); + } + + public function form(Schema $schema): Schema + { + $sections = collect(SystemSettings::EDITABLE) + ->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true) + ->map(fn ($group, string $section) => Section::make($section) + ->columns(2) + ->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all())); + + return $schema + ->statePath('data') + ->components([ + Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'), + ...$sections->values()->all(), + ]); + } + + public function content(Schema $schema): Schema + { + return $schema->components([ + Form::make([EmbeddedSchema::make('form')]) + ->id('form') + ->livewireSubmitHandler('save') + ->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]), + ]); + } + + public function save(): void + { + $data = $this->form->getState(); + + SystemSettings::save(collect(SystemSettings::EDITABLE) + ->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null]) + ->all()); + + Notification::make()->title('Gespeichert')->success()->send(); + } + + /** + * Config keys contain dots, which Filament would read as nesting. + */ + private static function field(string $key): string + { + return str_replace('.', '__', $key); + } + + private function field_(string $key): TextInput|Select + { + [$label, $kind, , $help] = SystemSettings::EDITABLE[$key]; + $name = self::field($key); + + if ($kind === 'mailer') { + return Select::make($name) + ->label($label) + ->helperText($help) + ->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']); + } + + $field = TextInput::make($name)->label($label)->helperText($help); + + return match ($kind) { + 'int' => $field->numeric()->integer()->minValue(0), + 'secret' => $field->password()->revealable()->autocomplete(false), + default => $field, + }; + } +} diff --git a/app/Filament/Operator/TenantResource.php b/app/Filament/Operator/TenantResource.php index 015ba8b..c580942 100644 --- a/app/Filament/Operator/TenantResource.php +++ b/app/Filament/Operator/TenantResource.php @@ -11,6 +11,10 @@ use BackedEnum; use Filament\Actions\Action; use Filament\Actions\EditAction; +use Filament\Forms\Components\Hidden; +use Filament\Forms\Components\Repeater; +use Filament\Forms\Components\TagsInput; +use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; use Filament\Resources\Resource; @@ -52,9 +56,38 @@ public static function form(Schema $schema): Schema ->unique(ignoreRecord: true) ->maxLength(255), Toggle::make('is_active') - ->label('Aktiv') - ->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.') - ->default(true), + ->label('Zugang freigeschaltet') + ->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.') + ->default(true) + ->live(), + Textarea::make('suspended_message') + ->label('Hinweis bei gesperrtem Zugang') + ->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.') + ->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.') + ->rows(2) + ->columnSpanFull(), + Section::make('Einsprungsadressen') + ->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.') + ->columnSpanFull() + ->schema([ + Repeater::make('websites') + ->label('Websites') + ->addActionLabel('Weitere Website') + ->defaultItems(1) + ->itemLabel(fn (array $state): ?string => $state['name'] ?? null) + ->schema([ + Hidden::make('id'), + TextInput::make('name') + ->label('Name der Website') + ->required() + ->maxLength(120), + TagsInput::make('hosts') + ->label('Adressen') + ->placeholder('beispiel.de') + ->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.') + ->nestedRecursiveRules(['string', 'max:190']), + ]), + ]), Section::make('Dienste') ->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.') ->columnSpanFull() diff --git a/app/Filament/Operator/Tenants/Pages/CreateTenant.php b/app/Filament/Operator/Tenants/Pages/CreateTenant.php index 64512a6..496b5b2 100644 --- a/app/Filament/Operator/Tenants/Pages/CreateTenant.php +++ b/app/Filament/Operator/Tenants/Pages/CreateTenant.php @@ -2,16 +2,13 @@ namespace App\Filament\Operator\Tenants\Pages; -use App\Filament\Operator\Concerns\EditsTenantServices; +use App\Filament\Operator\Concerns\EditsTenantSetup; use App\Filament\Operator\TenantResource; use Filament\Resources\Pages\CreateRecord; class CreateTenant extends CreateRecord { - use EditsTenantServices; + use EditsTenantSetup; protected static string $resource = TenantResource::class; - - /** @var array> */ - public array $services = []; } diff --git a/app/Filament/Operator/Tenants/Pages/EditTenant.php b/app/Filament/Operator/Tenants/Pages/EditTenant.php index c8b147f..65892c6 100644 --- a/app/Filament/Operator/Tenants/Pages/EditTenant.php +++ b/app/Filament/Operator/Tenants/Pages/EditTenant.php @@ -2,16 +2,13 @@ namespace App\Filament\Operator\Tenants\Pages; -use App\Filament\Operator\Concerns\EditsTenantServices; +use App\Filament\Operator\Concerns\EditsTenantSetup; use App\Filament\Operator\TenantResource; use Filament\Resources\Pages\EditRecord; class EditTenant extends EditRecord { - use EditsTenantServices; + use EditsTenantSetup; protected static string $resource = TenantResource::class; - - /** @var array> */ - public array $services = []; } diff --git a/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php b/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php index ddb9099..8014294 100644 --- a/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php +++ b/app/Filament/Resources/Sites/Concerns/EditsSiteHosts.php @@ -3,13 +3,11 @@ namespace App\Filament\Resources\Sites\Concerns; use App\Models\Site; -use App\Models\SiteDomain; -use Illuminate\Validation\ValidationException; /** - * The further hostnames of a website. The field "Domain" stays the main address used for guest links; - * everything entered here answers as well. Needed as soon as there is a second landlord, because from - * then on an unknown host is a 404 and "www" is a host of its own. + * Shows the hostnames of a website in the landlord's admin. Read only: addresses are given out by the + * operator, because every address also has to be wired to this directory at the hoster, and because a + * landlord must not be able to point somebody else's address at their own website. */ trait EditsSiteHosts { @@ -25,112 +23,11 @@ protected function mutateFormDataBeforeFill(array $data): array return $data; } - $primary = SiteDomain::normalise($site->domain); - $data['extra_hosts'] = $site->domains() + ->where('host', '!=', (string) $site->domain) ->pluck('host') - ->reject(fn (string $host): bool => $host === $primary) - ->values() ->all(); return $data; } - - /** - * @param array $data - * @return array - */ - protected function mutateFormDataBeforeCreate(array $data): array - { - return $this->withoutHosts($data); - } - - /** - * @param array $data - * @return array - */ - protected function mutateFormDataBeforeSave(array $data): array - { - return $this->withoutHosts($data); - } - - protected function afterCreate(): void - { - $this->saveHosts(); - } - - protected function afterSave(): void - { - $this->saveHosts(); - } - - /** - * @param array $data - * @return array - */ - private function withoutHosts(array $data): array - { - $hosts = is_array($data['extra_hosts'] ?? null) ? $data['extra_hosts'] : []; - - $this->extraHosts = array_values(array_filter(array_map( - fn (mixed $host): string => SiteDomain::normalise(is_string($host) ? $host : null), - $hosts, - ))); - - $this->refuseForeignHosts(); - - unset($data['extra_hosts']); - - return $data; - } - - /** - * A hostname that already answers for another website must not be taken over – otherwise one landlord - * could pull another landlord's visitors onto their own site just by typing that address here. - */ - private function refuseForeignHosts(): void - { - $site = $this->record; - - $taken = SiteDomain::query() - ->whereIn('host', $this->extraHosts) - ->when($site instanceof Site, fn ($query) => $query->where('site_id', '!=', $site->id)) - ->pluck('host'); - - if ($taken->isNotEmpty()) { - throw ValidationException::withMessages([ - 'data.extra_hosts' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '), - ]); - } - } - - private function saveHosts(): void - { - $site = $this->record; - - if (! $site instanceof Site) { - return; - } - - $primary = SiteDomain::normalise($site->domain); - - $wanted = collect($this->extraHosts) - ->filter() - ->when(filled($primary), fn ($hosts) => $hosts->push($primary)) - ->unique() - ->values(); - - $site->domains()->whereNotIn('host', $wanted->all())->delete(); - - foreach ($wanted as $host) { - // Never take a host away from another website: that would hand one landlord's visitors to another. - $owner = SiteDomain::query()->where('host', $host)->value('site_id'); - - if ($owner !== null && $owner !== $site->id) { - continue; - } - - SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]); - } - } } diff --git a/app/Filament/Resources/Sites/Pages/CreateSite.php b/app/Filament/Resources/Sites/Pages/CreateSite.php index 4fd9dab..e98951a 100644 --- a/app/Filament/Resources/Sites/Pages/CreateSite.php +++ b/app/Filament/Resources/Sites/Pages/CreateSite.php @@ -2,16 +2,10 @@ namespace App\Filament\Resources\Sites\Pages; -use App\Filament\Resources\Sites\Concerns\EditsSiteHosts; use App\Filament\Resources\Sites\SiteResource; use Filament\Resources\Pages\CreateRecord; class CreateSite extends CreateRecord { - use EditsSiteHosts; - protected static string $resource = SiteResource::class; - - /** @var list */ - public array $extraHosts = []; } diff --git a/app/Filament/Resources/Sites/Pages/EditSite.php b/app/Filament/Resources/Sites/Pages/EditSite.php index 947fe92..4c3c53b 100644 --- a/app/Filament/Resources/Sites/Pages/EditSite.php +++ b/app/Filament/Resources/Sites/Pages/EditSite.php @@ -13,9 +13,6 @@ class EditSite extends EditRecord protected static string $resource = SiteResource::class; - /** @var list */ - public array $extraHosts = []; - protected function getHeaderActions(): array { return [ diff --git a/app/Filament/Resources/Sites/Schemas/SiteForm.php b/app/Filament/Resources/Sites/Schemas/SiteForm.php index 710fb95..b56c7e1 100644 --- a/app/Filament/Resources/Sites/Schemas/SiteForm.php +++ b/app/Filament/Resources/Sites/Schemas/SiteForm.php @@ -28,15 +28,14 @@ public static function configure(Schema $schema): Schema TextInput::make('name')->label('Name')->required()->maxLength(120), TextInput::make('domain') ->label('Hauptadresse') - ->placeholder('www.fewo-stommer.de') - ->helperText('Steht in Links an Gäste. Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Adresse, alles andere bekommt 404.') - ->unique(ignoreRecord: true) - ->maxLength(190), + ->helperText('Steht in Links an Gäste. Adressen werden vom Betreiber vergeben, weil sie beim Hoster eingerichtet werden müssen.') + ->disabled() + ->dehydrated(false), TagsInput::make('extra_hosts') - ->label('Weitere Adressen') - ->placeholder('stommer.info') - ->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Alle hier eingetragenen liefern dieselbe Website. Enter nach jeder Adresse.') - ->nestedRecursiveRules(['string', 'max:190']) + ->label('Antwortet außerdem auf') + ->placeholder('keine weitere Adresse') + ->disabled() + ->dehydrated(false) ->columnSpanFull(), Select::make('theme') ->label('Theme') diff --git a/app/Http/Middleware/ResolveTheme.php b/app/Http/Middleware/ResolveTheme.php index f29b899..f484669 100644 --- a/app/Http/Middleware/ResolveTheme.php +++ b/app/Http/Middleware/ResolveTheme.php @@ -2,6 +2,7 @@ namespace App\Http\Middleware; +use App\Models\Site; use App\Models\Tenant; use App\Models\User; use App\Tenancy\TenantContext; @@ -9,6 +10,7 @@ use App\Themes\ThemeFactory; use Closure; use Illuminate\Http\Request; +use Illuminate\Support\Facades\URL; use Symfony\Component\HttpFoundation\Response; /** @@ -36,15 +38,45 @@ public function handle(Request $request, Closure $next): Response if ($tenant !== null) { if (! $tenant->is_active && ! $this->operatorMayPass($request)) { - abort(404); + return $this->suspended($tenant); } $context->set($tenant); } + $this->useSiteOrigin($theme->site); + return $next($request); } + /** + * Links must carry the address the visitor came in on. AppServiceProvider forces APP_URL for every + * generated URL, because on Strato the document root is a release folder; with one landlord that was + * harmless, but a second website on its own domain would otherwise send every visitor to the first + * landlord's host. The forced root stays – only its value becomes the website that was resolved. + */ + private function useSiteOrigin(Site $site): void + { + $origin = $site->exists ? $site->origin() : null; + + if ($origin === null) { + return; + } + + URL::forceRootUrl($origin); + URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https'); + } + + /** + * What a visitor of a suspended landlord sees: a plain notice instead of a dead link. + */ + private function suspended(Tenant $tenant): Response + { + return response()->view('suspended', [ + 'message' => $tenant->suspended_message ?: 'Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.', + ], 503); + } + /** * A suspended landlord stays reachable for the operator, and the operator panel itself stays open. */ diff --git a/app/Models/SystemSetting.php b/app/Models/SystemSetting.php new file mode 100644 index 0000000..cf5006b --- /dev/null +++ b/app/Models/SystemSetting.php @@ -0,0 +1,28 @@ + */ + protected $hidden = ['value']; + + /** + * @return array + */ + protected function casts(): array + { + return [ + 'is_secret' => 'boolean', + ]; + } +} diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index 7c2442e..052d430 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -20,7 +20,7 @@ 'owner_name', 'owner_street', 'owner_city', 'owner_phone', 'contact_email', 'notification_emails', 'sender_name', 'sender_email', 'bank_account_holder', 'bank_iban', 'bank_bic', 'bank_name', 'tax_note', - 'operating_mode', 'test_recipient', + 'operating_mode', 'test_recipient', 'suspended_message', 'deposit_due_days', 'review_request_after_days', 'guest_retention_years', 'retention_inquiry_months', 'retention_portal_email_excerpt_days', 'retention_attribution_months', 'spam_min_seconds', 'spam_per_ip_per_hour', 'spam_per_email_per_day', 'spam_open_requests_per_email', 'spam_max_links', diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 9ce69e3..0ff9e98 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -3,6 +3,7 @@ namespace App\Providers; use App\Support\StripImageMetadata; +use App\Support\SystemSettings; use App\Tenancy\TenantConfig; use App\Tenancy\TenantContext; use Illuminate\Support\Facades\Event; @@ -27,9 +28,12 @@ public function register(): void */ public function boot(): void { - // Operating data of the landlord (addresses, periods) and test mode (every e-mail goes to the test - // recipient only, until switched live). Console and boot know the landlord only if there is exactly one. + // Settings of the installation first (they become the baseline a landlord may tighten), then the + // operating data of the landlord: addresses, periods and test mode, which sends every e-mail to the + // test recipient only until a landlord is switched live. Console and boot know the landlord only if + // there is exactly one. try { + SystemSettings::apply(); $this->app->make(TenantConfig::class)->refresh(); } catch (Throwable) { // no database yet (package discovery, first install) diff --git a/app/Providers/Filament/OperatorPanelProvider.php b/app/Providers/Filament/OperatorPanelProvider.php index 2934b72..a71dd28 100644 --- a/app/Providers/Filament/OperatorPanelProvider.php +++ b/app/Providers/Filament/OperatorPanelProvider.php @@ -3,6 +3,7 @@ namespace App\Providers\Filament; use App\Filament\Operator\Pages\SystemOverview; +use App\Filament\Operator\Pages\SystemSettingsPage; use App\Http\Middleware\ResolveTheme; use Filament\Auth\MultiFactor\App\AppAuthentication; use Filament\Http\Middleware\Authenticate; @@ -42,6 +43,7 @@ public function panel(Panel $panel): Panel ->pages([ Dashboard::class, SystemOverview::class, + SystemSettingsPage::class, ]) ->widgets([ AccountWidget::class, diff --git a/app/Support/SystemSettings.php b/app/Support/SystemSettings.php new file mode 100644 index 0000000..cc3675d --- /dev/null +++ b/app/Support/SystemSettings.php @@ -0,0 +1,162 @@ + [label, kind, section, help]. The kind decides the form field and + * whether the value is stored encrypted. + * + * @var array + */ + public const EDITABLE = [ + 'fewo.guest_retention_years' => ['Gästedaten löschen nach (Jahre)', 'int', 'Löschfristen', 'Obergrenze für alle Mandanten; ein Mandant kann kürzer löschen.'], + 'fewo.retention.inquiry_months' => ['Nicht gebuchte Anfragen löschen nach (Monate)', 'int', 'Löschfristen', ''], + 'fewo.retention.portal_email_excerpt_days' => ['Portal-Mail-Auszug löschen nach (Tage)', 'int', 'Löschfristen', ''], + 'fewo.retention.attribution_months' => ['Herkunftsangaben löschen nach (Monate)', 'int', 'Löschfristen', ''], + + 'fewo.spam.min_seconds' => ['Mindestzeit im Formular (Sekunden)', 'int', 'Bot-Schutz', 'Untergrenze; ein Mandant kann länger warten lassen.'], + 'fewo.spam.per_ip_per_hour' => ['Anfragen je IP und Stunde', 'int', 'Bot-Schutz', ''], + 'fewo.spam.per_email_per_day' => ['Anfragen je E-Mail und Tag', 'int', 'Bot-Schutz', ''], + 'fewo.spam.open_requests_per_email' => ['Gleichzeitig offene Anfragen je E-Mail', 'int', 'Bot-Schutz', ''], + 'fewo.spam.max_links' => ['Erlaubte Links im Text', 'int', 'Bot-Schutz', ''], + 'fewo.spam.total_per_hour' => ['Anfragen aller Websites zusammen, je Stunde', 'int', 'Bot-Schutz', 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.'], + + 'fewo.channels.stale_after_minutes' => ['Portal-Abgleich gilt als veraltet nach (Minuten)', 'int', 'Portale', ''], + 'fewo.channels.task_reminder_after_minutes' => ['Erinnerung an Portal-Aufgaben nach (Minuten)', 'int', 'Portale', ''], + + 'fewo.backup.keep' => ['Aufbewahrte Datenbank-Sicherungen', 'int', 'Sicherung', 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.'], + + 'mail.default' => ['Versandweg', 'mailer', 'E-Mail-Versand', '„log“ schreibt jede E-Mail nur in die Logdatei und versendet nichts.'], + 'mail.mailers.smtp.host' => ['SMTP-Server', 'text', 'E-Mail-Versand', ''], + 'mail.mailers.smtp.port' => ['SMTP-Port', 'int', 'E-Mail-Versand', ''], + 'mail.mailers.smtp.username' => ['SMTP-Benutzer', 'text', 'E-Mail-Versand', 'Die Absenderadresse eines Mandanten muss zu diesem Postfach passen, sonst lehnt Strato ab.'], + 'mail.mailers.smtp.password' => ['SMTP-Passwort', 'secret', 'E-Mail-Versand', ''], + 'fewo.mail_redirect_to' => ['Harte Umleitung aller E-Mails', 'text', 'E-Mail-Versand', 'Gefüllt: JEDE E-Mail dieses Servers geht nur hierhin, auch bei scharf geschalteten Mandanten. Leer: die Betriebsart jedes Mandanten entscheidet allein.'], + + 'fewo.scheduler_token' => ['Scheduler-Token', 'secret', 'Schnittstellen', 'Für GET /automation/scheduler. Leer = abgeschaltet.'], + 'fewo.channels.health_token' => ['Health-Token', 'secret', 'Schnittstellen', 'Für GET /health/sync. Leer = abgeschaltet.'], + 'fewo.automation.webhook_url' => ['Automation: Adresse', 'text', 'Schnittstellen', ''], + 'fewo.automation.secret' => ['Automation: Geheimnis', 'secret', 'Schnittstellen', ''], + ]; + + private const CACHE_KEY = 'system-settings'; + + /** + * What the server configured, before anything stored was laid over it. Captured once per process. + * + * @var array + */ + private static array $baseline = []; + + /** + * Lays the stored values over the configuration. Called at boot before any landlord is resolved, so + * TenantConfig takes these as its baseline. + */ + public static function apply(): void + { + $stored = self::stored(); + $values = []; + + foreach (array_keys(self::EDITABLE) as $key) { + if (! array_key_exists($key, self::$baseline)) { + self::$baseline[$key] = config($key); + } + + // A key the operator cleared has to give the .env value back in the same request, not only + // after the next boot – otherwise an emptied field looks saved while the old value still acts. + $values[$key] = array_key_exists($key, $stored) + ? self::cast($key, $stored[$key]) + : self::$baseline[$key]; + } + + config($values); + } + + /** + * The value in force: what the operator stored, else what the server's .env configured. + */ + public static function get(string $key): mixed + { + $stored = self::stored(); + + return array_key_exists($key, $stored) ? self::cast($key, $stored[$key]) : config($key); + } + + /** + * @param array $values config key => value; null or "" falls back to the .env again + */ + public static function save(array $values): void + { + foreach ($values as $key => $value) { + if (! array_key_exists($key, self::EDITABLE)) { + continue; + } + + $isSecret = self::EDITABLE[$key][1] === 'secret'; + + if (blank($value)) { + SystemSetting::query()->where('key', $key)->delete(); + + continue; + } + + SystemSetting::query()->updateOrCreate( + ['key' => $key], + ['value' => $isSecret ? encrypt((string) $value) : (string) $value, 'is_secret' => $isSecret], + ); + } + + Cache::forget(self::CACHE_KEY); + self::apply(); + } + + public static function forget(): void + { + Cache::forget(self::CACHE_KEY); + self::$baseline = []; + } + + /** + * @return array + */ + private static function stored(): array + { + try { + return Cache::rememberForever(self::CACHE_KEY, fn (): array => SystemSetting::query()->pluck('value', 'key')->all()); + } catch (Throwable) { + return []; // before the migrations ran + } + } + + private static function cast(string $key, ?string $value): mixed + { + if ($value === null) { + return null; + } + + $kind = self::EDITABLE[$key][1] ?? 'text'; + + return match ($kind) { + 'int' => (int) $value, + 'secret' => rescue(fn (): string => decrypt($value), null, report: false), + default => $value, + }; + } +} diff --git a/database/migrations/2026_10_24_120000_add_suspended_message_and_system_settings.php b/database/migrations/2026_10_24_120000_add_suspended_message_and_system_settings.php new file mode 100644 index 0000000..cdd1218 --- /dev/null +++ b/database/migrations/2026_10_24_120000_add_suspended_message_and_system_settings.php @@ -0,0 +1,37 @@ +text('suspended_message')->nullable(); + }); + + Schema::create('system_settings', function (Blueprint $table) { + $table->id(); + $table->string('key')->unique(); + $table->text('value')->nullable(); + $table->boolean('is_secret')->default(false); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('system_settings'); + + Schema::table('tenants', function (Blueprint $table) { + $table->dropColumn('suspended_message'); + }); + } +}; diff --git a/resources/views/filament/operator/system-overview.blade.php b/resources/views/filament/operator/system-overview.blade.php index 700e802..59be722 100644 --- a/resources/views/filament/operator/system-overview.blade.php +++ b/resources/views/filament/operator/system-overview.blade.php @@ -34,9 +34,8 @@ Grenzen für alle Mandanten - Aus der .env dieses Servers. Ein Mandant kann sie in seinem Admin verschärfen, aber nicht - überschreiten. Änderungen hier wären Änderungen an der Infrastruktur und gehören deshalb auf den Server, - nicht in eine Oberfläche, die ein Mandant erreichen könnte. + Ein Mandant kann sie in seinem Admin verschärfen, aber nicht überschreiten. Geändert werden sie unter + Einstellungen; dort gilt ein leeres Feld als „Wert aus der .env des Servers“.
diff --git a/resources/views/suspended.blade.php b/resources/views/suspended.blade.php new file mode 100644 index 0000000..d57d1be --- /dev/null +++ b/resources/views/suspended.blade.php @@ -0,0 +1,22 @@ + + + + + + + Webseite nicht erreichbar + + + +
+

Webseite nicht erreichbar

+

{{ $message }}

+
+ + diff --git a/tests/Feature/SystemSettingsTest.php b/tests/Feature/SystemSettingsTest.php new file mode 100644 index 0000000..7a482f0 --- /dev/null +++ b/tests/Feature/SystemSettingsTest.php @@ -0,0 +1,117 @@ + 30]); + + SystemSettings::save(['fewo.spam.total_per_hour' => '120']); + $this->assertSame(120, config('fewo.spam.total_per_hour')); + $this->assertSame(120, SystemSettings::get('fewo.spam.total_per_hour')); + + SystemSettings::save(['fewo.spam.total_per_hour' => '']); + config(['fewo.spam.total_per_hour' => 30]); + SystemSettings::apply(); + + $this->assertSame(30, config('fewo.spam.total_per_hour'), 'Leer = der Wert der .env gilt wieder.'); + $this->assertSame(0, SystemSetting::query()->count()); + } + + public function test_a_secret_is_stored_encrypted(): void + { + SystemSettings::save(['mail.mailers.smtp.password' => 'geheim']); + + $stored = DB::table('system_settings')->where('key', 'mail.mailers.smtp.password')->first(); + + $this->assertNotSame('geheim', $stored?->value); + $this->assertTrue((bool) $stored?->is_secret); + $this->assertSame('geheim', SystemSettings::get('mail.mailers.smtp.password')); + } + + /** + * The whole point of the ceiling: what the operator sets here binds every landlord. + */ + public function test_the_stored_limit_becomes_the_ceiling_for_a_landlord(): void + { + config(['fewo.guest_retention_years' => 10]); + SystemSettings::save(['fewo.guest_retention_years' => '4']); + + $tenant = Tenant::factory()->create(['guest_retention_years' => 9]); + app(TenantContext::class)->set($tenant); + app(TenantConfig::class)->refresh(); + + $this->assertSame(4, config('fewo.guest_retention_years'), 'Der Mandant darf die Obergrenze nicht überschreiten.'); + } + + public function test_the_operator_edits_the_settings_and_a_landlords_administrator_cannot_reach_the_page(): void + { + $tenant = Tenant::factory()->create(); + app(TenantContext::class)->set($tenant); + + $admin = User::factory()->create(); + $this->actingAs($admin)->get('/betreiber/einstellungen')->assertForbidden(); + + $admin->forceFill(['is_operator' => true])->saveQuietly(); + $this->actingAs($admin); + Filament::setCurrentPanel('operator'); + + $this->get('/betreiber/einstellungen')->assertOk()->assertSee('Systemweite Einstellungen'); + + Livewire::test(SystemSettingsPage::class) + ->set('data.fewo__spam__total_per_hour', '77') + ->set('data.fewo__mail_redirect_to', 'auffang@example.com') + ->call('save') + ->assertHasNoErrors(); + + $this->assertSame(77, SystemSettings::get('fewo.spam.total_per_hour')); + $this->assertSame('auffang@example.com', config('fewo.mail_redirect_to')); + } + + /** + * The hard redirect is the net that keeps a test server from writing to real guests. It is editable on + * purpose, so it must be obvious that emptying it hands the decision back to each landlord. + */ + public function test_emptying_the_hard_redirect_leaves_only_the_landlords_own_test_mode(): void + { + SystemSettings::save(['fewo.mail_redirect_to' => 'auffang@example.com']); + + $live = Tenant::factory()->create(['operating_mode' => 'live', 'notification_emails' => 'wirt@example.com']); + app(TenantContext::class)->set($live); + + $this->assertSame('auffang@example.com', Settings::mailRedirect()); + + SystemSettings::save(['fewo.mail_redirect_to' => '']); + + $this->assertNull(Settings::mailRedirect(), 'Ohne harte Umleitung entscheidet der Mandant allein.'); + } +} diff --git a/tests/Feature/TenantAccessTest.php b/tests/Feature/TenantAccessTest.php index a7361a3..6d3caf5 100644 --- a/tests/Feature/TenantAccessTest.php +++ b/tests/Feature/TenantAccessTest.php @@ -133,8 +133,10 @@ public function test_a_suspended_landlord_is_closed_except_for_the_operator(): v app(TenantContext::class)->set($tenant); $admin = User::factory()->create(); - $this->get('/')->assertNotFound(); - $this->actingAs($admin)->get('/admin')->assertNotFound(); + // Visitors and the landlord's own people see a notice, not a dead link; 503 keeps the pages in the + // search index, because a suspended landlord is a temporary state. + $this->get('/')->assertStatus(503)->assertSee('nicht erreichbar'); + $this->actingAs($admin)->get('/admin')->assertStatus(503); $admin->forceFill(['is_operator' => true])->saveQuietly(); diff --git a/tests/Feature/TenantProvisioningTest.php b/tests/Feature/TenantProvisioningTest.php new file mode 100644 index 0000000..cca059c --- /dev/null +++ b/tests/Feature/TenantProvisioningTest.php @@ -0,0 +1,159 @@ +withoutVite(); + } + + public function test_a_landlord_created_by_the_operator_is_reachable_at_once(): void + { + $this->asOperator(); + + Livewire::test(CreateTenant::class) + ->fillForm([ + 'name' => 'Ferienhaus Düne', + 'slug' => 'duene', + 'is_active' => true, + 'websites' => [['name' => 'Ferienhaus Düne', 'hosts' => ['duene.test', 'www.duene.test']]], + ]) + ->call('create') + ->assertHasNoErrors(); + + $tenant = Tenant::query()->where('slug', 'duene')->sole(); + $site = Site::withoutGlobalScope('tenant')->where('tenant_id', $tenant->id)->sole(); + + $this->assertSame(['duene.test', 'www.duene.test'], $site->domains()->orderBy('host')->pluck('host')->all()); + $this->assertSame('duene.test', $site->domain, 'Die erste Adresse ist die Hauptadresse.'); + + // Without a home page the website would answer 404 and the landlord could never get in. + $this->assertTrue( + app(TenantContext::class)->run($tenant, fn (): bool => $site->pages()->where('slug', Page::HOME)->exists()), + ); + + $this->get('http://duene.test/')->assertOk()->assertSee('Ferienhaus Düne'); + $this->get('http://www.duene.test/')->assertOk(); + } + + public function test_a_suspended_landlord_shows_a_notice_instead_of_a_dead_link(): void + { + $tenant = Tenant::factory()->create(['is_active' => true]); + $site = $this->websiteFor($tenant, 'duene.test'); + $this->assertNotNull($site); + + Tenant::factory()->create(); // a second landlord, so hosts really decide + + $this->get('http://duene.test/')->assertOk(); + + $tenant->update(['is_active' => false, 'suspended_message' => 'Die Vermietung pausiert bis Frühjahr.']); + + $response = $this->get('http://duene.test/'); + $response->assertStatus(503); + $response->assertSee('Die Vermietung pausiert bis Frühjahr.'); + $response->assertSee('nicht erreichbar'); + } + + public function test_the_default_notice_applies_when_none_was_written(): void + { + $tenant = Tenant::factory()->create(['is_active' => false]); + $this->websiteFor($tenant, 'duene.test'); + Tenant::factory()->create(); + + $this->get('http://duene.test/')->assertStatus(503)->assertSee('Bitte versuchen Sie es später noch einmal.'); + } + + /** + * Links on a website have to carry the address the visitor arrived on. APP_URL is a single value, so + * without this every link of a second landlord would point at the first landlord's host. + */ + public function test_links_carry_the_address_the_visitor_came_in_on(): void + { + config(['app.url' => 'https://erster.test']); + $first = Tenant::factory()->create(); + $this->websiteFor($first, 'erster.test'); + + $second = Tenant::factory()->create(); + $this->websiteFor($second, 'zweiter.test'); + + $html = $this->get('http://zweiter.test/')->assertOk()->getContent(); + + $this->assertStringNotContainsString('erster.test', (string) $html); + } + + public function test_the_operator_adds_an_address_to_an_existing_landlord(): void + { + $tenant = Tenant::factory()->create(); + $site = $this->websiteFor($tenant, 'duene.test'); + Tenant::factory()->create(); + + $this->get('http://neu.duene.test/')->assertNotFound(); + + $this->asOperator(); + + Livewire::test(EditTenant::class, ['record' => $tenant->getRouteKey()]) + ->fillForm(['websites' => [[ + 'id' => $site->id, + 'name' => $site->name, + 'hosts' => ['duene.test', 'neu.duene.test'], + ]]]) + ->call('save') + ->assertHasNoErrors(); + + $this->get('http://neu.duene.test/')->assertOk(); + $this->get('http://duene.test/')->assertOk(); + } + + private function asOperator(): void + { + $operator = User::factory()->create(); + $operator->forceFill(['is_operator' => true])->saveQuietly(); + $this->actingAs($operator); + Filament::setCurrentPanel('operator'); + } + + private function websiteFor(Tenant $tenant, string $host): Site + { + return app(TenantContext::class)->run($tenant, function () use ($tenant, $host): Site { + $site = Site::query()->create([ + 'tenant_id' => $tenant->id, + 'name' => 'Website von '.$tenant->name, + 'domain' => $host, + 'is_default' => true, + 'theme' => config('themes.base'), + ]); + + Page::query()->create([ + 'site_id' => $site->id, + 'slug' => Page::HOME, + 'title' => $site->name, + 'sections' => [], + 'is_published' => true, + ]); + + return $site; + }); + } +} diff --git a/tests/Feature/TenantSettingsTest.php b/tests/Feature/TenantSettingsTest.php index 0c3f44e..6d856a3 100644 --- a/tests/Feature/TenantSettingsTest.php +++ b/tests/Feature/TenantSettingsTest.php @@ -117,6 +117,7 @@ public function test_the_operator_creates_a_landlord_in_the_operator_panel(): vo 'name' => 'Ferienhaus Düne', 'slug' => 'duene', 'is_active' => true, + 'websites' => [['name' => 'Ferienhaus Düne', 'hosts' => ['duene.example']]], 'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => true, 'services.'.TenantServiceKey::PortalMail->value.'.is_enabled' => false, ]) diff --git a/tests/Feature/WebsiteTenancyTest.php b/tests/Feature/WebsiteTenancyTest.php index 1751068..5090869 100644 --- a/tests/Feature/WebsiteTenancyTest.php +++ b/tests/Feature/WebsiteTenancyTest.php @@ -3,15 +3,14 @@ namespace Tests\Feature; use App\Actions\SendOffer; -use App\Enums\UserRole; -use App\Filament\Resources\Sites\Pages\EditSite; +use App\Filament\Operator\Tenants\Pages\EditTenant; use App\Models\Booking; use App\Models\Page; use App\Models\Property; use App\Models\Site; use App\Models\Tenant; use App\Models\User; -use App\Tenancy\TenantContext; +use Filament\Facades\Filament; use Illuminate\Foundation\Testing\RefreshDatabase; use Livewire\Features\SupportTesting\Testable; use Livewire\Livewire; @@ -98,17 +97,24 @@ public function test_the_offer_link_uses_the_website_address(): void } /** - * Enters the further addresses through the real admin form, so the form's own defences are under test. + * Enters the addresses the way they are really entered: by the operator, on the landlord. The form's + * own defences are under test with them. * * @param list $hosts */ private function editHosts(Site $site, array $hosts): Testable { - app(TenantContext::class)->set($site->tenant); - $this->actingAs(User::factory()->role(UserRole::Admin)->create()); + $operator = User::factory()->create(); + $operator->forceFill(['is_operator' => true])->saveQuietly(); + $this->actingAs($operator); + Filament::setCurrentPanel('operator'); - return Livewire::test(EditSite::class, ['record' => $site->getRouteKey()]) - ->fillForm(['extra_hosts' => $hosts]) + return Livewire::test(EditTenant::class, ['record' => $site->tenant->getRouteKey()]) + ->fillForm(['websites' => [[ + 'id' => $site->id, + 'name' => $site->name, + 'hosts' => [$site->domain, ...$hosts], + ]]]) ->call('save'); }