Dienste wirklich anschließen: zentrale Steuerung statt folgenloser Schalter

Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las.
Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben.

`App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein
Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst
führen:

- `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder*
  Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst
  sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten
  Dienst auf.
- `Channel::importsOccupations()` – Import und Scheduler.
- Der öffentliche iCal-Feed antwortet mit 404.
- `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg.

`TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete
Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da,
bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber-
Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es
soweit ist (A16).

Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle
Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste
und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste.

Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei,
damit der Umbau laufenden Betrieb nicht stillschweigend stoppt.

240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Lars StommerandClaude Opus 5 committed 2026-10-24 09:14:10 +02:00
1 parent 220ec6bfdb
commit fd2a7f7ded
15 files changed
+598 -55

No files matched your search

+7
View File
@@ -8,12 +8,14 @@
use App\Channels\Mail\PortalMailParser;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Enums\TenantServiceKey;
use App\Mail\ChannelConflict;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -40,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail
return null;
}
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
return null;
}
$parsed = $this->parser->parse($mail->subject, $mail->text);
$conflicts = [];
+3
View File
@@ -5,7 +5,9 @@
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Enums\TenantServiceKey;
use App\Models\Channel;
use App\Tenancy\TenantFeatures;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
@@ -26,6 +28,7 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa
}
$senders = Channel::query()->active()->get()
->filter(fn (Channel $channel): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant))
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
->unique()
->values()
+55 -5
View File
@@ -3,7 +3,9 @@
namespace App\Enums;
/**
* Services the operator can switch on per landlord. The AI services have no function behind them yet.
* Services the operator unlocks per landlord. `isWired()` says whether the application really asks before
* it acts – a service that nothing asks for must not be offered as a switch, because switching it would
* promise something that does not happen.
*/
enum TenantServiceKey: string
{
@@ -17,10 +19,58 @@ public function label(): string
{
return match ($this) {
self::PortalSync => 'Portal-Abgleich (iCal)',
self::PortalMail => 'Portal-Postfach',
self::AiOffers => 'KI: Angebote',
self::AiMarketing => 'KI: Marketing',
self::AiGuestMail => 'KI: Gästepost',
self::PortalMail => 'Portal-Postfach (Schnellweg)',
self::AiOffers => 'KI: Angebotsentwürfe',
self::AiMarketing => 'KI: Vermarktungsassistent',
self::AiGuestMail => 'KI: Gästekommunikation',
};
}
public function description(): string
{
return match ($this) {
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
};
}
/**
* Whether the application asks this switch before it acts. Only wired services are offered for switching.
*/
public function isWired(): bool
{
return match ($this) {
self::PortalSync, self::PortalMail => true,
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
};
}
/**
* What applies to a landlord the operator has not decided about yet. The portal services were part of
* the product before there were landlords, so switching tenancy on must not silently stop them.
*/
public function enabledByDefault(): bool
{
return $this->isWired();
}
/**
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
*/
public function usesApiKey(): bool
{
return match ($this) {
self::AiOffers, self::AiMarketing, self::AiGuestMail => true,
self::PortalSync, self::PortalMail => false,
};
}
/**
* @return list<self>
*/
public static function wired(): array
{
return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired()));
}
}
@@ -4,11 +4,12 @@
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantService;
use App\Tenancy\TenantFeatures;
/**
* 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.
* 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.
*/
trait EditsTenantServices
{
@@ -24,10 +25,11 @@ protected function mutateFormDataBeforeFill(array $data): array
return $data; // creating: there is nothing to read yet
}
$data['services'] = $tenant->services
->mapWithKeys(fn (TenantService $service): array => [$service->service => [
'is_enabled' => $service->is_enabled,
'api_key' => $service->api_key,
$stored = $tenant->services->keyBy('service');
$data['services'] = collect(TenantServiceKey::wired())
->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [
'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(),
]])
->all();
@@ -83,18 +85,16 @@ private function saveServices(): void
return;
}
foreach (TenantServiceKey::cases() as $service) {
foreach (TenantServiceKey::wired() as $service) {
$state = $this->services[$service->value] ?? [];
$tenant->services()->updateOrCreate(
['service' => $service->value],
[
'is_enabled' => (bool) ($state['is_enabled'] ?? false),
'api_key' => filled($state['api_key'] ?? null) ? $state['api_key'] : null,
],
['is_enabled' => (bool) ($state['is_enabled'] ?? false)],
);
}
$tenant->unsetRelation('services');
app(TenantFeatures::class)->forget($tenant);
}
}
@@ -0,0 +1,116 @@
<?php
namespace App\Filament\Operator\Pages;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantAccessLog;
use App\Tenancy\TenantConfig;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Collection;
/**
* What applies to the whole installation: the limits every landlord is bound by, the delivery path, and
* who opened whose admin. These values come from the server's .env and are deliberately not editable here –
* they protect the system against the landlords, so a landlord's admin must not be able to reach them.
*/
class SystemOverview extends Page
{
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedServerStack;
protected static ?string $navigationLabel = 'System';
protected static ?string $title = 'System';
protected static ?string $slug = 'system';
protected static ?int $navigationSort = 2;
protected string $view = 'filament.operator.system-overview';
/**
* The ceilings a landlord may tighten but never exceed.
*
* @return list<array{label: string, value: string, note: string}>
*/
public function limits(): array
{
$config = app(TenantConfig::class);
$rows = [
['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'],
['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''],
['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''],
['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''],
['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'],
['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''],
['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''],
['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''],
['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''],
];
return array_map(fn (array $row): array => [
'label' => $row[0],
'value' => trim($config->baselineValue($row[1]).' '.$row[2]),
'note' => $row[3],
], $rows);
}
/**
* Values that belong to the whole installation and to no landlord.
*
* @return list<array{label: string, value: string, note: string}>
*/
public function global(): array
{
$redirect = config('fewo.mail_redirect_to');
return [
[
'label' => 'Anfragen aller Websites zusammen',
'value' => config('fewo.spam.total_per_hour').' je Stunde',
'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.',
],
[
'label' => 'Harte Mail-Umleitung',
'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt',
'note' => filled($redirect)
? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.'
: 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.',
],
[
'label' => 'Versandweg',
'value' => (string) config('mail.default'),
'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.',
],
[
'label' => 'Datenbank-Sicherungen',
'value' => config('fewo.backup.keep').' Stück',
'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.',
],
];
}
/**
* @return Collection<int, Tenant>
*/
public function tenants(): Collection
{
return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get();
}
public function wiredServiceCount(): int
{
return count(TenantServiceKey::wired());
}
/**
* @return Collection<int, TenantAccessLog>
*/
public function accessLog(): Collection
{
return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get();
}
}
+16 -13
View File
@@ -14,13 +14,14 @@
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
class TenantResource extends Resource
{
@@ -55,18 +56,17 @@ public static function form(Schema $schema): Schema
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
->default(true),
Section::make('Dienste')
->description('Welche Dienste dieser Mandant nutzen darf. Ein eigener Schlüssel ist freiwillig; bleibt er leer, gilt später der Schlüssel des Betreibers.')
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
->columnSpanFull()
->schema(array_map(fn (TenantServiceKey $service): Fieldset => Fieldset::make($service->label())
->columns(2)
->schema([
Toggle::make('services.'.$service->value.'.is_enabled')->label('Freigeschaltet'),
TextInput::make('services.'.$service->value.'.api_key')
->label('Eigener API-Schlüssel')
->password()
->revealable()
->maxLength(255),
]), TenantServiceKey::cases())),
->schema([
...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled')
->label($service->label())
->helperText($service->description()), TenantServiceKey::wired()),
Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map(
fn (TenantServiceKey $service): string => $service->label(),
array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())),
)).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'),
]),
]);
}
@@ -76,7 +76,10 @@ public static function table(Table $table): Table
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('slug')->label('Kurzname'),
TextColumn::make('services_count')->label('Dienste')->counts(['services' => fn ($query) => $query->where('is_enabled', true)]),
TextColumn::make('services_count')
->label('Dienste frei')
->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)])
->suffix(' von '.count(TenantServiceKey::wired())),
ToggleColumn::make('is_active')->label('Aktiv'),
])
->recordActions([
@@ -27,6 +27,8 @@ public function feed(string $token, ICalFeed $feed): Response
{
$channel = Channel::query()->where('export_token', $token)->where('is_active', true)->firstOrFail();
abort_unless($channel->servesItsLandlord(), 404);
return response($feed->build($channel), 200, [
'Content-Type' => 'text/calendar; charset=utf-8',
'Content-Disposition' => 'inline; filename="belegung.ics"',
+12 -1
View File
@@ -4,7 +4,9 @@
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
use App\Enums\TenantServiceKey;
use App\Models\Concerns\BelongsToTenant;
use App\Tenancy\TenantFeatures;
use Database\Factories\ChannelFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -100,7 +102,16 @@ public function connector(): ChannelConnector
public function importsOccupations(): bool
{
return $this->is_active && $this->connector()->canImport($this);
return $this->is_active && $this->servesItsLandlord() && $this->connector()->canImport($this);
}
/**
* Whether the landlord this channel belongs to has the portal synchronisation unlocked at all.
* Asked here, so that neither an import nor the export feed can run around the switch.
*/
public function servesItsLandlord(): bool
{
return app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $this->tenant);
}
public function exportUrl(): string
+11 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\Permission;
use App\Models\User;
use App\Tenancy\TenantFeatures;
/**
* Grants every ability that the current membership includes. The operator counts as administrator
@@ -48,8 +49,17 @@ public function reorder(User $user): bool
return $this->allows($user);
}
/**
* Both questions, in one place: the role says what this user may do, TenantFeatures says what the
* landlord has unlocked at all. An administrator of a landlord without the portal services does not
* reach the portal screens either – no role grants what the landlord does not have.
*/
protected function allows(User $user): bool
{
return (bool) $user->currentRole()?->grants($this->permission());
if (! $user->currentRole()?->grants($this->permission())) {
return false;
}
return app(TenantFeatures::class)->permits($this->permission());
}
}
@@ -2,6 +2,7 @@
namespace App\Providers\Filament;
use App\Filament\Operator\Pages\SystemOverview;
use App\Http\Middleware\ResolveTheme;
use Filament\Auth\MultiFactor\App\AppAuthentication;
use Filament\Http\Middleware\Authenticate;
@@ -40,6 +41,7 @@ public function panel(Panel $panel): Panel
->discoverResources(in: app_path('Filament/Operator'), for: 'App\Filament\Operator')
->pages([
Dashboard::class,
SystemOverview::class,
])
->widgets([
AccountWidget::class,
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Tenancy;
use App\Enums\Permission;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantService;
use Throwable;
/**
* The single place that answers "is this service unlocked for this landlord". Everything that acts on a
* service asks here: the policies of the admin, the console commands, the portal feed. Roles decide what a
* *user* may do, this decides what the *landlord* has at all – a landlord without the service keeps nobody
* out by role, so both questions have to be asked, and asking them in two places is how they drift apart.
*/
class TenantFeatures
{
/**
* Services a permission depends on. The permission is granted when at least one of them is unlocked,
* so a landlord with only the mailbox still reaches the portal screens.
*
* @var array<string, list<TenantServiceKey>>
*/
private const REQUIRES_ANY = [
Permission::Channels->value => [TenantServiceKey::PortalSync, TenantServiceKey::PortalMail],
];
/**
* Unlocked services per landlord id, for the length of one request.
*
* @var array<int, array<string, bool>>
*/
private array $cache = [];
/**
* Whether the landlord may use the service. Without a landlord (console before a context is chosen,
* boot) the default of the service applies, which keeps a single-landlord installation unchanged.
*/
public function enabled(TenantServiceKey $service, ?Tenant $tenant = null): bool
{
$tenant ??= app(TenantContext::class)->get();
if ($tenant === null) {
return $service->enabledByDefault();
}
return $this->forTenant($tenant)[$service->value] ?? $service->enabledByDefault();
}
/**
* Whether the landlord has what a permission needs. A permission that depends on no service is always
* granted here – the role still decides separately.
*/
public function permits(Permission $permission, ?Tenant $tenant = null): bool
{
$required = self::REQUIRES_ANY[$permission->value] ?? [];
if ($required === []) {
return true;
}
foreach ($required as $service) {
if ($this->enabled($service, $tenant)) {
return true;
}
}
return false;
}
/**
* Forgets what was read, so a switch takes effect without a new request.
*/
public function forget(?Tenant $tenant = null): void
{
if ($tenant === null) {
$this->cache = [];
return;
}
unset($this->cache[$tenant->id]);
}
/**
* @return array<string, bool>
*/
private function forTenant(Tenant $tenant): array
{
if (! array_key_exists($tenant->id, $this->cache)) {
try {
$this->cache[$tenant->id] = TenantService::query()
->where('tenant_id', $tenant->id)
->pluck('is_enabled', 'service')
->map(fn (mixed $enabled): bool => (bool) $enabled)
->all();
} catch (Throwable) {
return []; // before the migrations ran; the defaults apply
}
}
return $this->cache[$tenant->id];
}
}
@@ -0,0 +1,35 @@
<?php
use App\Enums\TenantServiceKey;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
return new class extends Migration
{
/**
* Writes the switches of the services that are wired, so the operator sees the state instead of an
* empty form. The portal services were part of the product before there were landlords, so every
* landlord that exists today keeps them.
*/
public function up(): void
{
$now = now();
foreach (DB::table('tenants')->pluck('id') as $tenantId) {
foreach (TenantServiceKey::wired() as $service) {
DB::table('tenant_services')->updateOrInsert(
['tenant_id' => $tenantId, 'service' => $service->value],
['is_enabled' => $service->enabledByDefault(), 'updated_at' => $now, 'created_at' => $now],
);
}
}
}
public function down(): void
{
DB::table('tenant_services')->whereIn('service', array_map(
fn (TenantServiceKey $service): string => $service->value,
TenantServiceKey::wired(),
))->delete();
}
};
@@ -0,0 +1,86 @@
<x-filament-panels::page>
<x-filament::section>
<x-slot name="heading">Mandanten</x-slot>
<x-slot name="description">Wer auf diesem Server liegt und was freigeschaltet ist.</x-slot>
<div class="fi-ta-ctn overflow-x-auto">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-500 dark:text-gray-400">
<th class="py-2 pr-4 font-medium">Name</th>
<th class="py-2 pr-4 font-medium">Kurzname</th>
<th class="py-2 pr-4 font-medium">Zustand</th>
<th class="py-2 font-medium">Dienste frei</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200 dark:divide-white/10">
@foreach ($this->tenants() as $tenant)
<tr>
<td class="py-2 pr-4 font-medium">{{ $tenant->name }}</td>
<td class="py-2 pr-4 text-gray-500 dark:text-gray-400">{{ $tenant->slug }}</td>
<td class="py-2 pr-4">
<x-filament::badge :color="$tenant->is_active ? 'success' : 'danger'">
{{ $tenant->is_active ? 'aktiv' : 'gesperrt' }}
</x-filament::badge>
</td>
<td class="py-2">{{ $tenant->services_count }} von {{ $this->wiredServiceCount() }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</x-filament::section>
<x-filament::section>
<x-slot name="heading">Grenzen für alle Mandanten</x-slot>
<x-slot name="description">
Aus der <code>.env</code> 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.
</x-slot>
<dl class="divide-y divide-gray-200 dark:divide-white/10">
@foreach ($this->limits() as $row)
<div class="grid gap-1 py-2 sm:grid-cols-3">
<dt class="text-gray-500 dark:text-gray-400">{{ $row['label'] }}</dt>
<dd class="font-medium">{{ $row['value'] }}</dd>
<dd class="text-xs text-gray-500 dark:text-gray-400">{{ $row['note'] }}</dd>
</div>
@endforeach
</dl>
</x-filament::section>
<x-filament::section>
<x-slot name="heading">Gilt für den ganzen Server</x-slot>
<dl class="divide-y divide-gray-200 dark:divide-white/10">
@foreach ($this->global() as $row)
<div class="grid gap-1 py-2 sm:grid-cols-3">
<dt class="text-gray-500 dark:text-gray-400">{{ $row['label'] }}</dt>
<dd class="font-medium">{{ $row['value'] }}</dd>
<dd class="text-xs text-gray-500 dark:text-gray-400">{{ $row['note'] }}</dd>
</div>
@endforeach
</dl>
</x-filament::section>
<x-filament::section>
<x-slot name="heading">Zugriffe des Betreibers</x-slot>
<x-slot name="description">Wer wann den Admin eines Mandanten geöffnet hat. Support-Zugriff bleibt sichtbar.</x-slot>
@if ($this->accessLog()->isEmpty())
<p class="text-sm text-gray-500 dark:text-gray-400">Noch kein Zugriff aufgezeichnet.</p>
@else
<ul class="divide-y divide-gray-200 text-sm dark:divide-white/10">
@foreach ($this->accessLog() as $entry)
<li class="flex flex-wrap gap-x-2 py-2">
<span class="text-gray-500 dark:text-gray-400">{{ $entry->created_at?->format('d.m.Y H:i') }}</span>
<span class="font-medium">{{ $entry->user?->name ?? 'Unbekannt' }}</span>
<span class="text-gray-500 dark:text-gray-400">öffnete</span>
<span class="font-medium">{{ $entry->tenant?->name ?? 'gelöschter Mandant' }}</span>
</li>
@endforeach
</ul>
@endif
</x-filament::section>
</x-filament-panels::page>
+115
View File
@@ -0,0 +1,115 @@
<?php
namespace Tests\Feature;
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\PortalEmail;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantFeatures;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Tests\TestCase;
/**
* A service the operator has locked must not be reachable by any route: not by the scheduler, not by the
* public feed, and not by a user whose role would otherwise allow it.
*/
class TenantServiceGateTest extends TestCase
{
use RefreshDatabase;
public function test_a_locked_portal_service_stops_the_import_and_the_feed(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$channel = Channel::factory()->create();
$this->assertTrue($channel->importsOccupations());
$this->get(route('channels.feed', ['token' => $channel->export_token]))->assertOk();
$this->lock($tenant, TenantServiceKey::PortalSync);
$this->assertFalse($channel->fresh()->importsOccupations());
$this->get(route('channels.feed', ['token' => $channel->export_token]))->assertNotFound();
}
public function test_the_sync_command_skips_a_landlord_without_the_service(): void
{
$allowed = Tenant::factory()->create(['name' => 'Mit Dienst']);
$locked = Tenant::factory()->create(['name' => 'Ohne Dienst']);
app(TenantContext::class)->set($allowed);
$allowedChannel = Channel::factory()->create();
app(TenantContext::class)->set($locked);
$lockedChannel = Channel::factory()->create();
$this->lock($locked, TenantServiceKey::PortalSync);
app(TenantContext::class)->forget();
$this->assertTrue($allowedChannel->fresh()->importsOccupations());
$this->assertFalse($lockedChannel->fresh()->importsOccupations());
}
public function test_a_locked_service_closes_the_admin_screens_whatever_the_role_says(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$admin = User::factory()->role(UserRole::Admin)->create();
$this->actingAs($admin);
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', ChannelTask::class));
$this->lock($tenant, TenantServiceKey::PortalSync);
$this->lock($tenant, TenantServiceKey::PortalMail);
$this->assertFalse(Gate::forUser($admin)->allows('viewAny', ChannelTask::class));
$this->assertFalse(Gate::forUser($admin)->allows('viewAny', PortalEmail::class));
// The role itself is untouched – the landlord simply does not have the service.
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', Booking::class));
}
public function test_the_mailbox_fast_path_stays_open_while_only_the_sync_is_locked(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$admin = User::factory()->role(UserRole::Admin)->create();
$this->lock($tenant, TenantServiceKey::PortalSync);
$this->assertTrue(Gate::forUser($admin)->allows('viewAny', PortalEmail::class));
}
public function test_the_system_page_shows_the_limits_and_stays_closed_for_a_landlords_administrator(): void
{
$tenant = Tenant::factory()->create(['name' => 'Beispiel GbR']);
app(TenantContext::class)->set($tenant);
config(['fewo.spam.total_per_hour' => 30, 'fewo.guest_retention_years' => 10]);
$admin = User::factory()->role(UserRole::Admin)->create();
$this->actingAs($admin)->get('/betreiber/system')->assertForbidden();
$admin->forceFill(['is_operator' => true])->saveQuietly();
$this->actingAs($admin)->get('/betreiber/system')
->assertOk()
->assertSee('Beispiel GbR')
->assertSee('30 je Stunde')
->assertSee('10 Jahre');
}
private function lock(Tenant $tenant, TenantServiceKey $service): void
{
$tenant->services()->updateOrCreate(['service' => $service->value], ['is_enabled' => false]);
app(TenantFeatures::class)->forget($tenant);
}
}
+22 -24
View File
@@ -10,9 +10,9 @@
use App\Support\Settings;
use App\Tenancy\TenantConfig;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantFeatures;
use Filament\Facades\Filament;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Livewire\Livewire;
use Tests\TestCase;
@@ -76,29 +76,27 @@ public function test_without_a_landlord_the_configuration_of_the_installation_ap
$this->assertNull(Settings::tenant());
}
public function test_the_operator_switches_services_per_landlord_and_an_empty_key_is_allowed(): void
public function test_only_services_the_application_really_asks_about_are_offered(): void
{
$tenant = Tenant::factory()->create();
$this->assertSame(
[TenantServiceKey::PortalSync, TenantServiceKey::PortalMail],
TenantServiceKey::wired(),
);
$tenant->services()->create(['service' => TenantServiceKey::PortalSync->value, 'is_enabled' => true, 'api_key' => null]);
$tenant->services()->create(['service' => TenantServiceKey::AiOffers->value, 'is_enabled' => true, 'api_key' => 'sk-beispiel']);
$sync = $tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole();
$ai = $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->sole();
$this->assertTrue($sync->is_enabled);
$this->assertNull($sync->api_key);
$this->assertSame('sk-beispiel', $ai->api_key);
$this->assertSame(0, Tenant::factory()->create()->services()->count());
foreach (TenantServiceKey::cases() as $service) {
if (! $service->isWired()) {
$this->assertFalse($service->enabledByDefault(), $service->value.' darf nicht vorgegeben an sein, solange nichts danach fragt.');
}
}
}
public function test_an_own_service_key_is_stored_encrypted(): void
public function test_a_landlord_without_a_decision_keeps_the_portal_services(): void
{
$tenant = Tenant::factory()->create();
$service = $tenant->services()->create(['service' => TenantServiceKey::AiMarketing->value, 'is_enabled' => true, 'api_key' => 'sk-geheim']);
$this->assertNotSame('sk-geheim', DB::table('tenant_services')->where('id', $service->id)->value('api_key'));
$this->assertSame('sk-geheim', $service->fresh()->api_key);
$this->assertSame(0, $tenant->services()->count());
$this->assertTrue(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant));
$this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::AiOffers, $tenant));
}
public function test_the_operator_switches_a_service_on_the_tenant_form(): void
@@ -112,17 +110,17 @@ public function test_the_operator_switches_a_service_on_the_tenant_form(): void
Livewire::test(EditTenant::class, ['record' => $tenant->getRouteKey()])
->fillForm([
'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => true,
'services.'.TenantServiceKey::AiOffers->value.'.is_enabled' => true,
'services.'.TenantServiceKey::AiOffers->value.'.api_key' => 'sk-beispiel',
'services.'.TenantServiceKey::PortalSync->value.'.is_enabled' => false,
'services.'.TenantServiceKey::PortalMail->value.'.is_enabled' => true,
])
->call('save')
->assertHasNoErrors();
$this->assertTrue($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->is_enabled);
$this->assertNull($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->api_key);
$this->assertSame('sk-beispiel', $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->sole()->api_key);
$this->assertFalse($tenant->services()->where('service', TenantServiceKey::AiGuestMail->value)->sole()->is_enabled);
$this->assertFalse($tenant->services()->where('service', TenantServiceKey::PortalSync->value)->sole()->is_enabled);
$this->assertTrue($tenant->services()->where('service', TenantServiceKey::PortalMail->value)->sole()->is_enabled);
$this->assertSame(0, $tenant->services()->where('service', TenantServiceKey::AiOffers->value)->count());
$this->assertFalse(app(TenantFeatures::class)->enabled(TenantServiceKey::PortalSync, $tenant));
}
/**