Compare commits

..
Author SHA1 Message Date
Lars Stommer 2f2aceb3bd Merge branch 'feature/mandanten-dienste' (Dienste-Steuerung und Host-Verwaltung)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-24 09:25:23 +02:00
Lars StommerandClaude Opus 5 2e3f2ca938 Mehrere Adressen je Website, damit ein zweiter Mandant niemanden abschaltet
Bisher schrieb das Feld „Domain" genau einen Host nach `site_domains` und
löschte den vorherigen. Solange es einen Mandanten gibt, fällt das nicht
auf: jede Adresse liefert die Standard-Website. Ab dem zweiten Mandanten
bekommt jede nicht eingetragene Adresse 404 – und „www.beispiel.de" ist
eine eigene Adresse. stommer.info hätte einen zweiten Mandanten nicht
überlebt.

Das Formular hat jetzt „Hauptadresse" (steht in Gästelinks) und „Weitere
Adressen". Eingaben werden normalisiert, „https://WWW.Beispiel.de/" wird
zu „www.beispiel.de".

Eine Adresse, die schon zu einer anderen Website gehört, wird abgelehnt.
Ohne diese Sperre könnte ein Mandant die Besucher eines anderen auf seine
eigene Seite ziehen, indem er dessen Adresse einträgt.

242 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:25:22 +02:00
Lars StommerandClaude Opus 5 fd2a7f7ded 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>
2026-10-24 09:14:10 +02:00
Lars StommerandClaude Opus 5 220ec6bfdb Doku: Sicherung, Migrationsstand und Prüfung des Phase-3-Deploys
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:02:29 +02:00
Lars StommerandClaude Opus 5 afffa79289 Doku: Phase 3 ist auf stommer.info; Release-Nummern korrigiert
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Im Stand stand noch `20261023100346`, obwohl danach vier weitere Deploys
liefen (Grundriss, Fotos-Fix). Jetzt steht überall die wirklich aktive
Version `20261023195835` mit Phase 3.

Neu vermerkt: die Bankverbindung ist am Mandanten leer, weil die .env von
stommer.info keine `FEWO_BANK_*`-Werte hat – sie gehört jetzt in
System › Betrieb.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:01:53 +02:00
25 changed files with 847 additions and 71 deletions

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();
}
};
+2 -2
View File
@@ -1,6 +1,6 @@
# Mandantenfähigkeit – Umbauplan
Stand: 23.10.2026, abends · Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf `main`; auf stommer.info liegt noch Release `20261023100346` (ohne Phase 3) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7
Stand: 23.10.2026, abends · Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf `main` und auf stommer.info (Release `20261023195835`) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7
Kein Portal, kein Marktplatz. Das Produkt bleibt die eigene Website eines Vermieters mit Vermietung. Wenige Mandanten, eine gemeinsame Datenbank, Laravel und Filament bleiben die Basis. Ein Python-Dienst ist nicht Teil dieses Umbaus.
@@ -290,6 +290,6 @@ ## 9. Betrieb und Abgrenzung
## 10. Freigabe
Phase 1 und 2 sowie der Website-Teil von Phase 4 sind auf stommer.info (Release `20261023100346`). Phase 3 ist auf `main` und noch nicht ausgeliefert. Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Die nächste Codesitzung ist der Rest von Phase 4; Übergabe mit den gebauten Bausteinen: [STATUS.md](STATUS.md) Abschnitt 7. Phase 4 und 5 bringen weitere Migrationen. Phase 6 und 7 warten auf eine eigene Freigabe.
Phase 1, 2 und 3 sowie der Website-Teil von Phase 4 sind auf stommer.info (Release `20261023195835`). Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Die nächste Codesitzung ist der Rest von Phase 4; Übergabe mit den gebauten Bausteinen: [STATUS.md](STATUS.md) Abschnitt 7. Phase 4 und 5 bringen weitere Migrationen. Phase 6 und 7 warten auf eine eigene Freigabe.
Die Sicherheitsregel in §1 gilt: Passwort und 2FA gehören zum Konto, die Rolle zur Mitgliedschaft. Der Betreiber darf zusätzlich Mandanten-Administrator der eigenen Wohnung sein.
+11 -11
View File
@@ -1,6 +1,6 @@
# Projektstand
Stand: 23.10.2026 · ausgelieferter Stand: `deploy/staging/20261023100346` · 234 Feature-Tests grün
Stand: 23.10.2026 · ausgelieferter Stand: `deploy/staging/20261023195835` · 235 Feature-Tests grün
> Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“).
@@ -70,7 +70,7 @@ ## 3. Offen
**Technik**
- Cronjob auf Strato einrichten (BETRIEB.md §6).
- Design-Theme Seebad 0.3 ist auf `main` und auf stommer.info aktiv (Abschnitt 6).
- Mandantenfähigkeit: Phase 1, 2 und der Website-Teil von Phase 4 sind auf stommer.info; Phase 3 (Einstellungen, Texte, Dienste) liegt auf `main` und ist **noch nicht ausgeliefert**. **Nächste Codesitzung: Rest von Phase 4.** Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`.
- Mandantenfähigkeit: Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf stommer.info. **Nächste Codesitzung: Rest von Phase 4.** Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`.
- Logo in E-Mails und im Vertrags-PDF (`public/brand/logo-600.png` liegt bereit).
- Content-Security-Policy: braucht wegen Livewire/Filament Nonces und einen sorgfältigen Test.
- Produktion `www.fewo-stommer.de` vorbereiten:
@@ -139,21 +139,21 @@ ## 7. Mandanten – Übergabe an die nächste Sitzung
**Hier weitermachen: der Rest von Phase 4** (Scheduler-Schleife über die Mandanten, Portal-Postfach je Mandant, Absender je Versand, iCal-Token). Danach Phase 5 (Export und Löschung eines Mandanten). Phase 6 und 7 erst nach eigener Freigabe und einem Eintrag in ZUSAMMENARBEIT.md §6. Neuen Branch von `main` abzweigen.
**Phase 3 ist auf `main`, aber nicht ausgeliefert.** Sie bringt zwei Migrationen mit (Spalten am Mandanten plus `tenant_services`/`service_usages`; danach fällt `settings` weg). Vor dem nächsten Deploy auf stommer.info also sichern wie beim letzten Mal, dann `scripts/deploy.sh staging deploy` – Code und Migration in einem Schritt.
**Phase 3 ist ausgeliefert** (Release `20261023195835`, 23.10.2026 abends). Die zwei Migrationen sind auf der MariaDB von stommer.info durch, `settings` ist weg, die Werte stehen am Mandanten Stommer.
### Ausgeliefert
| | |
|---|---|
| Server | nur **stommer.info** (Staging). `www.fewo-stommer.de` ist unberührt und bleibt WordPress. |
| Release | `20261023100346`, Git-Tag `deploy/staging/20261023100346`, Commit `cec49da` |
| Code danach | Commits auf `main` nach `cec49da` sind Dokumentation. Sie sind nicht erneut ausgeliefert. Ein Deploy nur wegen dieser Texte ist unnötig: das Skript nimmt `docs/` nicht mit. |
| Migration | drei Migrationen vom 23.10. sind auf der MariaDB von stommer.info durch. Vorhandene Zeilen gehören zum Mandanten **Stommer** (`slug` `stommer`). Ein zweites Migrieren legt keinen zweiten Stommer an, solange keine Zeile ohne Mandant übrig ist. |
| Sicherung davor | `C:\Dev\fewo-backups\staging\20261023-120038` (Datenbank-Dump und Dateien). Ein Rollback der Version nimmt die Migration **nicht** zurück. |
| Release | `20261023195835`, Git-Tag `deploy/staging/20261023195835`, Commit `f143a4f` (Phase 3) |
| Code danach | Commits auf `main` nach `f143a4f` sind Dokumentation. Sie sind nicht erneut ausgeliefert. Ein Deploy nur wegen dieser Texte ist unnötig: das Skript nimmt `docs/` nicht mit. |
| Migration | fünf Migrationen vom 23.10. sind auf der MariaDB von stommer.info durch. Vorhandene Zeilen gehören zum Mandanten **Stommer** (`slug` `stommer`); die Betriebsdaten stehen an dessen Spalten, `settings` ist weg. Ein zweites Migrieren legt keinen zweiten Stommer an, solange keine Zeile ohne Mandant übrig ist. |
| Sicherung davor | `C:\Dev\fewo-backups\staging\20261023-215553` (Datenbank-Dump mit noch vorhandener `settings`-Tabelle und Dateien, 29 MB; erstellt mit `scripts/backup-pull.sh staging`). Ein Rollback der Version nimmt die Migration **nicht** zurück. |
| Konto | `php artisan users:promote-operator lars@stommer.com` ist auf dem Server gelaufen. Passwort und 2FA sind gleich geblieben. |
| Prüfung | `https://stommer.info/`, `/wohnung` und `/buchen` antworten 200 und zeigen weiter Seebad und Stommer. `/admin` und `/betreiber` leiten ohne Anmeldung auf die Login-Seite um (302). Lars hat den Admin danach angemeldet geprüft: funktionsfähig. |
| Prüfung | `https://stommer.info/`, `/wohnung` und `/buchen` antworten 200 und zeigen weiter Seebad und Stommer samt Vermieterdaten aus den Mandanten-Spalten. `/admin` und `/betreiber` leiten ohne Anmeldung auf die Login-Seite um (302). Betriebsart Testbetrieb, Umleitung an `lars@stommer.com`. **Noch nicht angemeldet geprüft:** die Seite System › Betrieb mit den neuen Abschnitten. |
Die lokale Datei `database/database.sqlite` (`.env`: `DB_CONNECTION=sqlite`, `APP_URL=http://localhost:8000`) ist **nicht** migriert. `php artisan serve` auf diesem Rechner trifft das alte Schema und läuft mit dem neuen Code nicht. Testinstanz ist stommer.info. Die lokale Datei nur migrieren, wenn jemand bewusst lokal arbeiten will (`php artisan migrate`, danach `users:promote-operator` für das lokale Konto). Die `.env` nicht auf die Datenbank von stommer.info zeigen lassen.
Die lokale Datei `database/database.sqlite` (`.env`: `DB_CONNECTION=sqlite`, `APP_URL=http://localhost:8000`) ist **nicht** vollständig migriert (die zwei Migrationen von Phase 3 stehen dort auf „Pending“). `php artisan serve` auf diesem Rechner trifft das alte Schema und läuft mit dem neuen Code nicht. Testinstanz ist stommer.info. Die lokale Datei nur migrieren, wenn jemand bewusst lokal arbeiten will (`php artisan migrate`, danach `users:promote-operator` für das lokale Konto). Die `.env` nicht auf die Datenbank von stommer.info zeigen lassen.
Nicht committet und nicht Teil des Umbaus: `styles/satz3/svg/haus.svg`, `styles/satz3/svg/haus-klein.svg`.
@@ -187,12 +187,12 @@ ### So ist es gebaut
| `settings` | Entfernt. Modell `App\Models\Setting` gelöscht, `Settings::get/save` gibt es nicht mehr. |
| Noch global | Postfach, Absender des Scheduler-Laufs und der Scheduler selbst kennen keinen Mandanten (Rest von Phase 4). Der Cronjob auf Strato ist weiterhin nicht eingerichtet, der Versandweg ist `log`. Das ist mit einem Mandanten der bisherige Betrieb. Ein Mandant ohne eigene Adressen fällt für die Testumleitung auf `FEWO_NOTIFICATION_EMAIL` zurück, damit nichts versehentlich an echte Gäste geht. |
Tests dazu: `tests/Feature/TenantIsolationTest.php`, `TenantAccessTest.php`, `WebsiteTenancyTest.php`, `TenantSettingsTest.php`, `OperationsModeTest.php`. Zuletzt 234 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`.
Tests dazu: `tests/Feature/TenantIsolationTest.php`, `TenantAccessTest.php`, `WebsiteTenancyTest.php`, `TenantSettingsTest.php`, `OperationsModeTest.php`. Zuletzt 235 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`.
### Offen, aber nicht in derselben Sitzung nötig gewesen
- Rest von Phase 4 und Phase 5. Jede davon bringt eigene Migrationen. Auslieferung und Migration wieder in einem Schritt, nach Sicherung.
- Phase 3 ausliefern (zwei Migrationen, `settings` fällt weg). Danach in System › Betrieb prüfen, ob Vermieterdaten, Bank und Fristen richtig übernommen wurden – sie kamen aus `settings` und aus der `.env`.
- **Bankverbindung eintragen:** Die `.env` von stommer.info hat keine `FEWO_BANK_*`-Werte, deshalb sind Kontoinhaber, IBAN, BIC und Bank am Mandanten leer (wie vorher auch). Sie gehören jetzt in System › Betrieb › Bankverbindung und Steuer; `mail/partials/bank.blade.php` und der Vertrag zeigen den Block erst, wenn eine IBAN da ist.
- Betreiber-Bereich https://stommer.info/betreiber einmal öffnen. Der Admin ist geprüft.
- Host `stommer.info` an der Website eintragen, bevor ein zweiter Mandant entsteht. Später ebenso `www` und `fewo-stommer.de`, wenn die Produktion umzieht.
- Brigitte, Cronjob, SMTP, Rechtstexte: Abschnitt 4, unverändert und unabhängig vom Mandanten-Code.
@@ -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();