Merge branch 'feature/mandanten-dienste' (Dienste-Steuerung und Host-Verwaltung)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped

This commit is contained in:
Lars Stommer committed 2026-10-24 09:25:23 +02:00
commit 2f2aceb3bd
23 files changed
+834 -58

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Bash(git merge *)"
]
}
}
+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([
@@ -0,0 +1,136 @@
<?php
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.
*/
trait EditsSiteHosts
{
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeFill(array $data): array
{
$site = $this->record;
if (! $site instanceof Site) {
return $data;
}
$primary = SiteDomain::normalise($site->domain);
$data['extra_hosts'] = $site->domains()
->pluck('host')
->reject(fn (string $host): bool => $host === $primary)
->values()
->all();
return $data;
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
return $this->withoutHosts($data);
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
return $this->withoutHosts($data);
}
protected function afterCreate(): void
{
$this->saveHosts();
}
protected function afterSave(): void
{
$this->saveHosts();
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
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]);
}
}
}
@@ -2,10 +2,16 @@
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<string> */
public array $extraHosts = [];
}
@@ -2,14 +2,20 @@
namespace App\Filament\Resources\Sites\Pages;
use App\Filament\Resources\Sites\Concerns\EditsSiteHosts;
use App\Filament\Resources\Sites\SiteResource;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditSite extends EditRecord
{
use EditsSiteHosts;
protected static string $resource = SiteResource::class;
/** @var list<string> */
public array $extraHosts = [];
protected function getHeaderActions(): array
{
return [
@@ -7,6 +7,7 @@
use App\Themes\ThemeRegistry;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
@@ -26,11 +27,17 @@ public static function configure(Schema $schema): Schema
->schema([
TextInput::make('name')->label('Name')->required()->maxLength(120),
TextInput::make('domain')
->label('Domain')
->label('Hauptadresse')
->placeholder('www.fewo-stommer.de')
->helperText('Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Domain.')
->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),
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'])
->columnSpanFull(),
Select::make('theme')
->label('Theme')
->options(fn (): array => app(ThemeRegistry::class)->options())
@@ -15,7 +15,8 @@ public static function configure(Table $table): Table
return $table
->columns([
TextColumn::make('name')->label('Website')->weight('medium'),
TextColumn::make('domain')->label('Domain')->placeholder('alle übrigen Adressen'),
TextColumn::make('domain')->label('Hauptadresse')->placeholder('alle übrigen Adressen'),
TextColumn::make('domains.host')->label('Antwortet auf')->badge()->placeholder('jede Adresse'),
TextColumn::make('theme')->label('Theme')->formatStateUsing(fn (string $state): string => app(ThemeRegistry::class)->get($state)->name),
TextColumn::make('properties_count')->label('Wohnungen')->counts('properties'),
IconColumn::make('is_default')->label('Standard')->boolean(),
@@ -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
+13
View File
@@ -12,6 +12,19 @@
#[Fillable(['site_id', 'host'])]
class SiteDomain extends Model
{
/**
* Turns what someone typed into a bare hostname: "https://WWW.Example.de/" becomes "www.example.de".
* Returns an empty string when nothing usable is left, so callers can skip it.
*/
public static function normalise(?string $value): string
{
$host = mb_strtolower(trim((string) $value));
$host = (string) preg_replace('~^[a-z]+://~', '', $host);
$host = (string) preg_replace('~[/?#].*$~', '', $host);
return trim($host, '.');
}
/**
* @return BelongsTo<Site, $this>
*/
+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));
}
/**
+57
View File
@@ -3,12 +3,18 @@
namespace Tests\Feature;
use App\Actions\SendOffer;
use App\Enums\UserRole;
use App\Filament\Resources\Sites\Pages\EditSite;
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 Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportTesting\Testable;
use Livewire\Livewire;
use Tests\TestCase;
class WebsiteTenancyTest extends TestCase
@@ -40,6 +46,42 @@ public function test_a_second_landlord_is_reached_only_on_their_own_address(): v
$this->get('http://unbekannt.test/')->assertNotFound();
}
/**
* The trap that would take a live site down: as long as there is one landlord every address works, so
* nobody notices that no host is entered. The second landlord turns every unentered address into a 404 –
* including "www", which is a host of its own.
*/
public function test_a_website_answers_on_every_address_entered_for_it(): void
{
$site = $this->website('Nordhaus', 'nordhaus.test');
$this->website('Südheim', 'suedheim.test');
$this->get('http://www.nordhaus.test/')->assertNotFound();
$this->editHosts($site, ['www.nordhaus.test', 'https://ALT.nordhaus.test/'])->assertHasNoFormErrors();
$this->get('http://nordhaus.test/')->assertOk()->assertSee('Nordhaus');
$this->get('http://www.nordhaus.test/')->assertOk()->assertSee('Nordhaus');
$this->get('http://alt.nordhaus.test/')->assertOk()->assertSee('Nordhaus');
$this->get('http://unbekannt.test/')->assertNotFound();
$this->assertSame(
['alt.nordhaus.test', 'nordhaus.test', 'www.nordhaus.test'],
$site->domains()->orderBy('host')->pluck('host')->all(),
);
}
public function test_a_host_of_another_website_cannot_be_taken_over(): void
{
$nord = $this->website('Nordhaus', 'nordhaus.test');
$sued = $this->website('Südheim', 'suedheim.test');
$this->editHosts($nord, ['suedheim.test'])->assertHasFormErrors();
$this->get('http://suedheim.test/')->assertOk()->assertSee('Südheim')->assertDontSee('Nordhaus');
$this->assertSame([$sued->id], $sued->domains()->pluck('site_id')->all());
}
public function test_the_offer_link_uses_the_website_address(): void
{
$site = $this->website('Nordhaus', 'nordhaus.test');
@@ -55,6 +97,21 @@ public function test_the_offer_link_uses_the_website_address(): void
$this->assertStringContainsString('signature=', $url);
}
/**
* Enters the further addresses through the real admin form, so the form's own defences are under test.
*
* @param list<string> $hosts
*/
private function editHosts(Site $site, array $hosts): Testable
{
app(TenantContext::class)->set($site->tenant);
$this->actingAs(User::factory()->role(UserRole::Admin)->create());
return Livewire::test(EditSite::class, ['record' => $site->getRouteKey()])
->fillForm(['extra_hosts' => $hosts])
->call('save');
}
private function website(string $name, ?string $domain = null): Site
{
$tenant = Tenant::factory()->create();