Assign the existing site to one landlord so stommer.info can run tenancy.

Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
LarsandCursor committed 2026-10-23 12:00:11 +02:00
1 parent d9e52c4789
commit 8ebc1a3878
93 files changed
+2506 -112

No files matched your search

+25 -1
View File
@@ -14,6 +14,8 @@
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -38,6 +40,24 @@ public function __construct(
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
{
$tenant = $property->tenant;
if ($tenant === null) {
throw new TenantContextMissing(Property::class);
}
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
);
}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
@@ -91,7 +111,11 @@ private function guestFor(array $guestData): array
$guest = Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([...$guestData, 'email' => $email]), []];
return [Guest::create([
...$guestData,
'email' => $email,
'tenant_id' => app(TenantContext::class)->id(),
]), []];
}
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
+4 -1
View File
@@ -98,7 +98,10 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
*/
public function offerUrl(Booking $booking): string
{
return URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]);
$parameters = ['booking' => $booking, 'v' => $booking->offer_version];
return $booking->website()?->temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters)
?? URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters);
}
/**
+46 -2
View File
@@ -3,7 +3,9 @@
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
@@ -13,7 +15,7 @@
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content} {--tenant= : Kurzname des Mandanten}')]
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
class CreateUser extends Command
{
@@ -22,6 +24,12 @@ class CreateUser extends Command
*/
public function handle(): int
{
$tenant = $this->resolveTenant();
if ($tenant === false) {
return self::FAILURE;
}
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
$email = mb_strtolower(trim($email));
@@ -51,7 +59,12 @@ public function handle(): int
return self::FAILURE;
}
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
$user = User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
if ($tenant instanceof Tenant) {
app(TenantContext::class)->set($tenant);
$user->attachCurrentRole($tenant);
}
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
@@ -59,4 +72,35 @@ public function handle(): int
return self::SUCCESS;
}
/**
* One landlord is used automatically. Several landlords need --tenant. None is allowed:
* the account exists and is attached later.
*/
private function resolveTenant(): Tenant|false|null
{
$slug = $this->option('tenant');
if (is_string($slug) && $slug !== '') {
$tenant = Tenant::query()->where('slug', $slug)->first();
if ($tenant === null) {
$this->error("Kein Mandant mit dem Kurznamen {$slug}.");
return false;
}
return $tenant;
}
$count = Tenant::query()->count();
if ($count > 1) {
$this->error('Es gibt mehrere Mandanten. Bitte --tenant=kurzname angeben.');
return false;
}
return $count === 1 ? Tenant::query()->first() : null;
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('users:promote-operator {email : E-Mail-Adresse}')]
#[Description('Grant the operator flag. The account keeps its password, two-factor setup and any landlord role.')]
class PromoteOperator extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$email = mb_strtolower(trim((string) $this->argument('email')));
$user = User::query()->where('email', $email)->first();
if ($user === null) {
$this->error('Kein Benutzer mit dieser E-Mail.');
return self::FAILURE;
}
$user->forceFill(['is_operator' => true])->save();
$this->info("{$email} ist jetzt Betreiber. Eine bestehende Mandanten-Rolle bleibt.");
return self::SUCCESS;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Enums;
/**
* What a role may do inside the current landlord. A new role is a new case on UserRole plus a list here.
*/
enum Permission: string
{
case Bookings = 'bookings';
case Properties = 'properties';
case Guests = 'guests';
case Reviews = 'reviews';
case Channels = 'channels';
case Content = 'content';
case Users = 'users';
case Settings = 'settings';
}
+30 -2
View File
@@ -14,7 +14,7 @@ enum UserRole: string implements HasDescription, HasLabel
public function getLabel(): string
{
return match ($this) {
self::Admin => 'Administrator',
self::Admin => 'Mandanten-Administrator',
self::Rentals => 'Vermietung',
self::Content => 'Inhalte',
};
@@ -23,9 +23,37 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Admin => 'Alles, inklusive Benutzerverwaltung',
self::Admin => 'Alles im eigenen Mandanten, inklusive Benutzerverwaltung',
self::Rentals => 'Buchungen, Gäste, Preise, Angebote und Bewertungen',
self::Content => 'Bilder, Texte, FAQ, Hinweise und Bewertungen',
};
}
public function grants(Permission $permission): bool
{
return in_array($permission, $this->permissions(), true);
}
/**
* Abilities inside the current landlord. The operator is not a role here.
*
* @return list<Permission>
*/
public function permissions(): array
{
return match ($this) {
self::Admin => Permission::cases(),
self::Rentals => [
Permission::Bookings,
Permission::Properties,
Permission::Guests,
Permission::Reviews,
Permission::Channels,
],
self::Content => [
Permission::Content,
Permission::Reviews,
],
};
}
}
+91
View File
@@ -0,0 +1,91 @@
<?php
namespace App\Filament\Operator;
use App\Filament\Operator\Tenants\Pages\CreateTenant;
use App\Filament\Operator\Tenants\Pages\EditTenant;
use App\Filament\Operator\Tenants\Pages\ListTenants;
use App\Models\Tenant;
use App\Models\TenantAccessLog;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Table;
class TenantResource extends Resource
{
protected static ?string $model = Tenant::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice;
protected static ?string $modelLabel = 'Mandant';
protected static ?string $pluralModelLabel = 'Mandanten';
protected static ?string $navigationLabel = 'Mandanten';
protected static ?int $navigationSort = 1;
public static function form(Schema $schema): Schema
{
return $schema
->components([
TextInput::make('name')
->label('Name')
->required()
->maxLength(255),
TextInput::make('slug')
->label('Kurzname')
->required()
->alphaDash()
->unique(ignoreRecord: true)
->maxLength(255),
Toggle::make('is_active')
->label('Aktiv')
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
->default(true),
]);
}
public static function table(Table $table): Table
{
return $table
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('slug')->label('Kurzname'),
ToggleColumn::make('is_active')->label('Aktiv'),
])
->recordActions([
EditAction::make(),
Action::make('openAdmin')
->label('Im Admin öffnen')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->action(function (Tenant $record) {
TenantAccessLog::query()->create([
'tenant_id' => $record->id,
'user_id' => auth()->id(),
]);
$domain = $record->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
return redirect(is_string($domain) && $domain !== '' ? 'https://'.$domain.'/admin' : url('/admin'));
}),
]);
}
public static function getPages(): array
{
return [
'index' => ListTenants::route('/'),
'create' => CreateTenant::route('/create'),
'edit' => EditTenant::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\CreateRecord;
class CreateTenant extends CreateRecord
{
protected static string $resource = TenantResource::class;
}
@@ -0,0 +1,11 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\TenantResource;
use Filament\Resources\Pages\EditRecord;
class EditTenant extends EditRecord
{
protected static string $resource = TenantResource::class;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Filament\Operator\Tenants\Pages;
use App\Filament\Operator\TenantResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListTenants extends ListRecords
{
protected static string $resource = TenantResource::class;
protected function getHeaderActions(): array
{
return [
CreateAction::make(),
];
}
}
@@ -28,7 +28,7 @@ public static function configure(Schema $schema): Schema
TextInput::make('domain')
->label('Domain')
->placeholder('www.fewo-stommer.de')
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
->helperText('Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Domain.')
->unique(ignoreRecord: true)
->maxLength(190),
Select::make('theme')
@@ -3,9 +3,40 @@
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use App\Models\User;
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
class CreateUser extends CreateRecord
{
protected static string $resource = UserResource::class;
/**
* An address that already belongs to another landlord is attached. The account, its password
* and its two-factor setup stay as they are.
*
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
$email = is_string($data['email'] ?? null) ? $data['email'] : '';
$existing = User::query()->where('email', $email)->first();
if ($existing === null) {
return parent::handleRecordCreation($data);
}
$attributes = [
'name' => $data['name'] ?? $existing->name,
'role' => $data['role'] ?? $existing->role,
];
if (array_key_exists('admin_mode', $data)) {
$attributes['admin_mode'] = $data['admin_mode'];
}
$existing->forceFill($attributes)->save();
return $existing;
}
}
@@ -3,6 +3,7 @@
namespace App\Filament\Resources\Users\Pages;
use App\Filament\Resources\Users\UserResource;
use App\Models\User;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
@@ -16,4 +17,22 @@ protected function getHeaderActions(): array
DeleteAction::make(),
];
}
/**
* A hidden password field must not be writable by a crafted request either.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
$actor = auth()->user();
$record = $this->getRecord();
if (! $actor instanceof User || ! $record instanceof User || ! $actor->mayResetCredentials($record)) {
unset($data['password']);
}
return $data;
}
}
@@ -4,6 +4,9 @@
use App\Enums\AdminMode;
use App\Enums\UserRole;
use App\Models\User;
use App\Tenancy\TenantContext;
use Closure;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
@@ -21,15 +24,54 @@ public static function configure(Schema $schema): Schema
->maxLength(255),
TextInput::make('email')
->label('E-Mail (Anmeldename)')
->helperText('Besteht die E-Mail schon, kommt das Konto zu diesem Mandanten dazu. Passwort und Zwei-Faktor-Anmeldung bleiben.')
->email()
->required()
->unique(ignoreRecord: true)
->maxLength(255),
->maxLength(255)
->rules([
fn (?User $record): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
if (! is_string($value)) {
return;
}
$existing = User::query()->where('email', $value)->first();
if ($existing === null) {
return;
}
if ($record !== null) {
if ($existing->isNot($record)) {
$fail('Diese E-Mail wird schon verwendet.');
}
return;
}
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null && $existing->tenants()->where('tenants.id', $tenantId)->exists()) {
$fail('Diese Person gehört schon zu diesem Mandanten.');
}
},
]),
Radio::make('role')
->label('Rolle')
->helperText('Bestimmt, was die Person darf.')
->helperText('Gilt für diesen Mandanten.')
->options(UserRole::class)
->required()
->afterStateHydrated(function (Radio $component, ?User $record): void {
if ($record === null) {
return;
}
$tenantId = app(TenantContext::class)->id();
$role = $tenantId !== null ? ($record->roleOn($tenantId) ?? $record->role) : $record->role;
if ($role !== null) {
$component->state($role->value);
}
})
->columnSpanFull(),
Radio::make('admin_mode')
->label('Ansicht')
@@ -42,6 +84,15 @@ public static function configure(Schema $schema): Schema
->revealable()
->minLength(10)
->required(fn (string $operation): bool => $operation === 'create')
->visible(function (string $operation, ?User $record): bool {
if ($operation === 'create') {
return true;
}
$actor = auth()->user();
return $actor instanceof User && $actor->mayResetCredentials($record);
})
->dehydrated(fn (?string $state): bool => filled($state)),
]);
}
@@ -2,7 +2,9 @@
namespace App\Filament\Resources\Users\Tables;
use App\Enums\UserRole;
use App\Models\User;
use App\Tenancy\TenantContext;
use Filament\Actions\Action;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
@@ -20,7 +22,18 @@ public static function configure(Table $table): Table
->columns([
TextColumn::make('name')->label('Name')->searchable(),
TextColumn::make('email')->label('E-Mail')->searchable(),
TextColumn::make('role')->label('Rolle')->badge(),
TextColumn::make('role')
->label('Rolle')
->badge()
->state(function (User $record): ?UserRole {
$tenantId = app(TenantContext::class)->id();
if ($tenantId === null) {
return $record->role;
}
return $record->roleOn($tenantId) ?? $record->role;
}),
TextColumn::make('mode')->label('Ansicht')->state(fn (User $record): string => $record->adminMode()->getLabel()),
IconColumn::make('two_factor')->label('2FA')->state(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))->boolean(),
])
@@ -32,12 +45,35 @@ public static function configure(Table $table): Table
->color('warning')
->requiresConfirmation()
->modalDescription('Zum Beispiel bei verlorenem Handy: Die Person richtet die Zwei-Faktor-Anmeldung bei der nächsten Anmeldung neu ein.')
->visible(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))
->visible(function (User $record): bool {
$actor = auth()->user();
return filled($record->getAppAuthenticationSecret())
&& $actor instanceof User
&& $actor->mayResetCredentials($record);
})
->action(function (User $record): void {
$actor = auth()->user();
if (! $actor instanceof User || ! $actor->mayResetCredentials($record)) {
return;
}
$record->saveAppAuthenticationSecret(null);
$record->saveAppAuthenticationRecoveryCodes(null);
Notification::make()->title('2FA zurückgesetzt')->success()->send();
}),
Action::make('revokeAccess')
->label('Zugang entziehen')
->icon(Heroicon::OutlinedNoSymbol)
->color('danger')
->requiresConfirmation()
->modalDescription('Das Konto bleibt bestehen und verliert nur den Zugang zu diesem Mandanten. Passwort und Zwei-Faktor-Anmeldung bleiben.')
->visible(fn (User $record): bool => $record->tenants()->count() >= 2)
->action(function (User $record): void {
$record->revokeCurrentTenant();
Notification::make()->title('Zugang entzogen')->success()->send();
}),
DeleteAction::make(),
]);
}
@@ -9,11 +9,13 @@
use App\Filament\Resources\Users\Schemas\UserForm;
use App\Filament\Resources\Users\Tables\UsersTable;
use App\Models\User;
use App\Tenancy\TenantContext;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class UserResource extends Resource
@@ -30,6 +32,23 @@ class UserResource extends Resource
protected static ?string $pluralModelLabel = 'Benutzer';
/**
* Accounts are global. This list shows only people who belong to the landlord that is open.
*
* @return Builder<User>
*/
public static function getEloquentQuery(): Builder
{
$query = parent::getEloquentQuery();
$tenantId = app(TenantContext::class)->id();
if ($tenantId === null) {
return $query;
}
return $query->whereHas('tenants', fn (Builder $membership) => $membership->where('tenants.id', $tenantId));
}
public static function form(Schema $schema): Schema
{
return UserForm::configure($schema);
@@ -20,7 +20,8 @@ public function confirm(Guest $guest): View
return view('marketing-consent', [
'title' => 'Anmeldung bestätigt',
'message' => 'Vielen Dank! Wir informieren Sie künftig über freie Termine und Angebote. Sie können sich jederzeit wieder abmelden.',
'unsubscribeUrl' => URL::signedRoute('marketing.unsubscribe', $guest),
'unsubscribeUrl' => $guest->website()?->signedRoute('marketing.unsubscribe', $guest)
?? URL::signedRoute('marketing.unsubscribe', $guest),
]);
}
+12 -3
View File
@@ -7,6 +7,7 @@
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use DateTimeInterface;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
@@ -38,8 +39,8 @@ public function show(Request $request, Booking $booking, AcceptOffer $accept): V
'booking' => $booking,
'problem' => $problem,
'canAnswer' => $booking->status === BookingStatus::OfferSent && $problem === null,
'acceptUrl' => URL::temporarySignedRoute('offers.accept', $expires, ['booking' => $booking, 'v' => $version]),
'rejectUrl' => URL::temporarySignedRoute('offers.reject', $expires, ['booking' => $booking, 'v' => $version]),
'acceptUrl' => $this->signed($booking, 'offers.accept', $expires, $version),
'rejectUrl' => $this->signed($booking, 'offers.reject', $expires, $version),
'title' => 'Ihr Angebot',
]);
}
@@ -62,7 +63,7 @@ public function reject(Request $request, Booking $booking, RejectOffer $reject):
private function answer(Request $request, Booking $booking, callable $action, string $success): RedirectResponse
{
$version = (int) $request->query('v');
$back = URL::temporarySignedRoute('offers.show', now()->addDays(30), ['booking' => $booking, 'v' => $version]);
$back = $this->signed($booking, 'offers.show', now()->addDays(30), $version);
try {
$action($version);
@@ -72,4 +73,12 @@ private function answer(Request $request, Booking $booking, callable $action, st
return redirect()->to($back)->with('offer.success', $success);
}
private function signed(Booking $booking, string $name, DateTimeInterface $expiration, int $version): string
{
$parameters = ['booking' => $booking, 'v' => $version];
return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters)
?? URL::temporarySignedRoute($name, $expiration, $parameters);
}
}
+38 -1
View File
@@ -2,6 +2,9 @@
namespace App\Http\Middleware;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use App\Themes\Theme;
use App\Themes\ThemeFactory;
use Closure;
@@ -17,8 +20,42 @@ public function __construct(private ThemeFactory $factory) {}
public function handle(Request $request, Closure $next): Response
{
app()->instance(Theme::class, $this->factory->forRequest($request)->activate());
$context = app(TenantContext::class);
$context->forget();
$theme = $this->factory->forRequest($request)->activate();
app()->instance(Theme::class, $theme);
$tenant = null;
if ($theme->site->exists && $theme->site->tenant_id !== null) {
$tenant = $theme->site->tenant;
} elseif (Tenant::query()->count() === 1) {
$tenant = Tenant::query()->first();
}
if ($tenant !== null) {
if (! $tenant->is_active && ! $this->operatorMayPass($request)) {
abort(404);
}
$context->set($tenant);
}
return $next($request);
}
/**
* A suspended landlord stays reachable for the operator, and the operator panel itself stays open.
*/
private function operatorMayPass(Request $request): bool
{
if ($request->is('betreiber', 'betreiber/*')) {
return true;
}
$user = $request->user();
return $user instanceof User && $user->is_operator;
}
}
+4 -2
View File
@@ -15,6 +15,7 @@
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
@@ -276,9 +277,10 @@ public function submit(CreateReservation $createReservation): void
*/
private function tooManyRequests(): bool
{
$tenantKey = (string) (app(TenantContext::class)->id() ?? 'global');
$limits = [
'booking-request:'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
'booking-request-email:'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
'booking-request:'.$tenantKey.':'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
'booking-request-email:'.$tenantKey.':'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
'booking-request-all' => [config('fewo.spam.total_per_hour'), 3600],
];
+2 -1
View File
@@ -31,7 +31,8 @@ public function envelope(): Envelope
public function content(): Content
{
return new Content(
with: ['url' => URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
with: ['url' => $this->guest->website()?->temporarySignedRoute('marketing.confirm', now()->addDays(14), ['guest' => $this->guest])
?? URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
markdown: 'mail.marketing-consent-request',
);
}
+2 -1
View File
@@ -31,7 +31,8 @@ public function envelope(): Envelope
public function content(): Content
{
return new Content(
with: ['url' => URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
with: ['url' => $this->booking->website()?->temporarySignedRoute('reviews.create', now()->addDays(90), ['booking' => $this->booking])
?? URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
markdown: 'mail.review-request',
);
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\AmenityArea;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\AmenityFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,7 +17,7 @@
class Amenity extends Model
{
/** @use HasFactory<AmenityFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\AppearanceFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -19,7 +20,7 @@
class Appearance extends Model
{
/** @use HasFactory<AppearanceFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Texts an appearance can replace, with their admin labels. Sections read them through Theme::text().
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use App\Observers\BlockedPeriodObserver;
use Carbon\CarbonInterface;
use Database\Factories\BlockedPeriodFactory;
@@ -22,7 +23,7 @@
class BlockedPeriod extends Model
{
/** @use HasFactory<BlockedPeriodFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+38 -2
View File
@@ -4,6 +4,7 @@
use App\Enums\BookingStatus;
use App\Enums\ReferralSource;
use App\Models\Concerns\BelongsToTenant;
use App\Observers\BookingObserver;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
@@ -65,15 +66,41 @@
class Booking extends Model
{
/** @use HasFactory<BookingFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
static::created(function (Booking $booking): void {
$booking->forceFill(['reference' => $booking->created_at->format('Y').'-'.str_pad((string) $booking->id, 4, '0', STR_PAD_LEFT)])->saveQuietly();
$booking->forceFill(['reference' => $booking->nextReference()])->saveQuietly();
});
}
/**
* Next booking number of this landlord in the year of creation, continuing after the highest
* number already issued. Existing numbers are never rewritten.
*/
public function nextReference(): string
{
$year = $this->created_at->format('Y');
$references = static::withoutGlobalScope('tenant')
->where('tenant_id', $this->tenant_id)
->where('reference', 'like', $year.'-%')
->whereKeyNot($this->id)
->lockForUpdate()
->pluck('reference');
$number = 1;
foreach ($references as $reference) {
if (is_string($reference) && preg_match('/-(\d+)$/', $reference, $match) === 1) {
$number = max($number, ((int) $match[1]) + 1);
}
}
return $year.'-'.str_pad((string) $number, 4, '0', STR_PAD_LEFT);
}
/**
* Get the attributes that should be cast.
*
@@ -199,4 +226,13 @@ public function isHoldActive(): bool
{
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
}
/**
* The website this stay belongs to, regardless of which landlord is current.
*/
public function website(): ?Site
{
return $this->property()->withoutGlobalScope('tenant')->first()
?->site()->withoutGlobalScope('tenant')->first();
}
}
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ChannelFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
@@ -24,7 +25,7 @@
class Channel extends Model
{
/** @use HasFactory<ChannelFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
+3
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -9,6 +10,8 @@
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
class ChannelSyncLog extends Model
{
use BelongsToTenant;
public const UPDATED_AT = null;
/**
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ChannelTaskFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -20,7 +21,7 @@
class ChannelTask extends Model
{
/** @use HasFactory<ChannelTaskFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+118
View File
@@ -0,0 +1,118 @@
<?php
namespace App\Models\Concerns;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;
/**
* Every row belongs to exactly one landlord. When a landlord is current, queries only see that
* landlord. Inserts copy the landlord from the parent row, then from the current context.
*
* @mixin Model
*/
trait BelongsToTenant
{
public function initializeBelongsToTenant(): void
{
$this->mergeFillable(['tenant_id']);
}
public static function bootBelongsToTenant(): void
{
static::addGlobalScope('tenant', function (Builder $builder): void {
$context = app(TenantContext::class);
if ($context->id() !== null) {
$builder->where($builder->getModel()->qualifyColumn('tenant_id'), $context->id());
return;
}
if ($context->isRequired()) {
throw new TenantContextMissing($builder->getModel()::class);
}
});
static::creating(function (Model $model): void {
$inherited = self::tenantIdFromParent($model);
if ($inherited !== null) {
$model->setAttribute('tenant_id', $inherited);
return;
}
if (filled($model->getAttribute('tenant_id'))) {
return;
}
$current = app(TenantContext::class)->id();
if ($current !== null) {
$model->setAttribute('tenant_id', $current);
return;
}
if (app()->runningUnitTests() && ! app(TenantContext::class)->isRequired()) {
$model->setAttribute('tenant_id', Tenant::query()->create([
'name' => 'Testmandant',
'slug' => 'test-'.Str::lower(Str::random(10)),
])->id);
return;
}
throw new TenantContextMissing($model::class);
});
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
/**
* The parent row wins, so a booking cannot land on a different landlord than its apartment.
*/
private static function tenantIdFromParent(Model $model): ?int
{
$parents = [
'property_id' => Property::class,
'booking_id' => Booking::class,
'channel_id' => Channel::class,
'site_id' => Site::class,
'guest_id' => Guest::class,
];
foreach ($parents as $column => $class) {
$id = $model->getAttribute($column);
if (! $id) {
continue;
}
$tenantId = $class::withoutGlobalScope('tenant')->whereKey($id)->value('tenant_id');
if ($tenantId !== null) {
return (int) $tenantId;
}
}
return null;
}
}
+5 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
@@ -9,4 +10,7 @@
* Value of an editable website text; the available keys are defined in config/content.php.
*/
#[Fillable(['key', 'value'])]
class ContentBlock extends Model {}
class ContentBlock extends Model
{
use BelongsToTenant;
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\ExtraPricing;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ExtraFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -18,7 +19,7 @@
class Extra extends Model
{
/** @use HasFactory<ExtraFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\FaqFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -13,7 +14,7 @@
class Faq extends Model
{
/** @use HasFactory<FaqFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+10 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\GuestFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -17,7 +18,7 @@
class Guest extends Model
{
/** @use HasFactory<GuestFactory> */
use HasFactory, Notifiable;
use BelongsToTenant, HasFactory, Notifiable;
/**
* Get the attributes that should be cast.
@@ -96,4 +97,12 @@ public function anonymize(): void
])->save();
});
}
/**
* The website of this guest's landlord, regardless of which landlord is current.
*/
public function website(): ?Site
{
return $this->tenant?->sites()->withoutGlobalScope('tenant')->orderByDesc('is_default')->orderBy('id')->first();
}
}
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\NoticeTone;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\NoticeFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -17,7 +18,7 @@
class Notice extends Model
{
/** @use HasFactory<NoticeFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PageFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -18,7 +19,7 @@
class Page extends Model
{
/** @use HasFactory<PageFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
public const HOME = 'start';
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PaymentFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -16,7 +17,7 @@
class Payment extends Model
{
/** @use HasFactory<PaymentFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\PhotoCategory;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\PhotoFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -22,7 +23,7 @@
class Photo extends Model implements HasMedia
{
/** @use HasFactory<PhotoFactory> */
use HasFactory, InteractsWithMedia;
use BelongsToTenant, HasFactory, InteractsWithMedia;
public const COLLECTION = 'image';
+3
View File
@@ -4,6 +4,7 @@
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -15,6 +16,8 @@
#[Fillable(['channel_id', 'message_id', 'from', 'subject', 'received_at', 'type', 'status', 'starts_on', 'ends_on', 'reference', 'blocked_period_id', 'excerpt', 'note'])]
class PortalEmail extends Model
{
use BelongsToTenant;
/**
* Get the attributes that should be cast.
*
+11 -1
View File
@@ -2,11 +2,13 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonImmutable;
use Database\Factories\PropertyFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
@@ -36,7 +38,7 @@
class Property extends Model
{
/** @use HasFactory<PropertyFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
@@ -68,6 +70,14 @@ protected function casts(): array
/**
* @return HasMany<Season, $this>
*/
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
public function seasons(): HasMany
{
return $this->hasMany(Season::class)->orderBy('starts_on');
+2 -1
View File
@@ -3,6 +3,7 @@
namespace App\Models;
use App\Enums\ReviewStatus;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\ReviewFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
@@ -38,7 +39,7 @@
class Review extends Model
{
/** @use HasFactory<ReviewFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/** Rating categories besides the overall rating, with their German labels. */
public const CATEGORIES = [
+2 -1
View File
@@ -2,6 +2,7 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\SeasonFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -19,7 +20,7 @@
class Season extends Model
{
/** @use HasFactory<SeasonFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+99 -1
View File
@@ -2,12 +2,16 @@
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Carbon\CarbonInterface;
use Database\Factories\SiteFactory;
use DateInterval;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\URL;
/**
* A website: domain, theme with its settings, pages and appearances, and the properties it shows.
@@ -17,7 +21,14 @@
class Site extends Model
{
/** @use HasFactory<SiteFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
protected static function booted(): void
{
static::saved(function (Site $site): void {
$site->syncDomainHost();
});
}
/**
* Get the attributes that should be cast.
@@ -32,6 +43,93 @@ protected function casts(): array
];
}
/**
* @return HasMany<SiteDomain, $this>
*/
public function domains(): HasMany
{
return $this->hasMany(SiteDomain::class);
}
/**
* Scheme and host for guest links. Empty while the website has no hostname yet.
*/
public function origin(): ?string
{
$host = $this->domains()->value('host') ?: $this->domain;
if (! is_string($host) || $host === '') {
return null;
}
$scheme = in_array($host, ['localhost', '127.0.0.1'], true) ? 'http' : 'https';
return $scheme.'://'.$host;
}
/**
* @param array<string, mixed> $parameters
*/
public function temporarySignedRoute(string $name, DateTimeInterface|DateInterval|int $expiration, array $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::temporarySignedRoute($name, $expiration, $parameters));
}
public function signedRoute(string $name, mixed $parameters = []): string
{
return $this->withOrigin(fn (): string => URL::signedRoute($name, $parameters));
}
/**
* Keep the single domain field and the host table on the same hostname.
*/
public function syncDomainHost(): void
{
if (! $this->wasRecentlyCreated && ! $this->wasChanged('domain')) {
return;
}
$previous = $this->getOriginal('domain');
if (is_string($previous) && $previous !== '' && $previous !== $this->domain) {
$this->domains()->where('host', mb_strtolower($previous))->delete();
}
if (! is_string($this->domain) || $this->domain === '') {
return;
}
SiteDomain::query()->updateOrCreate(
['host' => mb_strtolower($this->domain)],
['site_id' => $this->id],
);
}
/**
* @param callable(): string $callback
*/
private function withOrigin(callable $callback): string
{
$origin = $this->origin();
if ($origin === null) {
return $callback();
}
$generator = app('url');
$previousRoot = (fn () => $this->forcedRoot)->call($generator);
$previousScheme = (fn () => $this->forceScheme)->call($generator);
URL::forceRootUrl($origin);
URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https');
try {
return $callback();
} finally {
URL::forceRootUrl($previousRoot);
URL::forceScheme(is_string($previousScheme) ? strstr($previousScheme, ':', true) : null);
}
}
/**
* @return HasMany<Page, $this>
*/
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One hostname of a website. A host belongs to exactly one website.
*/
#[Fillable(['site_id', 'host'])]
class SiteDomain extends Model
{
/**
* @return BelongsTo<Site, $this>
*/
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
}
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Enums\DiscountType;
use App\Enums\OfferKind;
use App\Models\Concerns\BelongsToTenant;
use App\Pricing\StayRequest;
use App\Support\Money;
use Carbon\CarbonImmutable;
@@ -48,7 +49,7 @@
class SpecialOffer extends Model
{
/** @use HasFactory<SpecialOfferFactory> */
use HasFactory;
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Models;
use Database\Factories\TenantFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* A landlord. Owns websites, apartments, guests, bookings and settings. One account can belong
* to several landlords; the operator is not a landlord.
*/
#[Fillable(['name', 'slug', 'is_active'])]
class Tenant extends Model
{
/** @use HasFactory<TenantFactory> */
use HasFactory;
/**
* The landlord the existing single-website data belongs to.
*/
public static function stommer(): self
{
return static::query()->firstOrCreate(
['slug' => 'stommer'],
['name' => 'Stommer'],
);
}
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'is_active' => 'boolean',
];
}
/**
* @return HasMany<Site, $this>
*/
public function sites(): HasMany
{
return $this->hasMany(Site::class);
}
/**
* @return HasMany<Property, $this>
*/
public function properties(): HasMany
{
return $this->hasMany(Property::class);
}
/**
* @return BelongsToMany<User, $this>
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(User::class)->withPivot('role')->withTimestamps();
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* Written when an operator opens a landlord's admin. Support access stays visible.
*/
#[Fillable(['tenant_id', 'user_id', 'created_at'])]
class TenantAccessLog extends Model
{
public $timestamps = false;
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'created_at' => 'datetime',
];
}
protected static function booted(): void
{
static::creating(function (TenantAccessLog $log): void {
$log->created_at ??= now();
});
}
/**
* @return BelongsTo<Tenant, $this>
*/
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
/**
* @return BelongsTo<User, $this>
*/
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
+169 -3
View File
@@ -5,6 +5,7 @@
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\AdminMode;
use App\Enums\UserRole;
use App\Tenancy\TenantContext;
use Database\Factories\UserFactory;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthenticationRecovery;
@@ -15,6 +16,7 @@
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
@@ -25,12 +27,24 @@ class User extends Authenticatable implements FilamentUser, HasAppAuthentication
/** @use HasFactory<UserFactory> */
use HasFactory, InteractsWithAppAuthentication, InteractsWithAppAuthenticationRecovery, Notifiable;
protected static function booted(): void
{
static::saved(function (User $user): void {
$user->attachCurrentRole();
});
}
/**
* Accounts are created by administrators only; an account without a role has no access.
* The operator panel is only for operators. The landlord admin needs a role there, or the operator flag.
* Password and two-factor belong to the account and are not a per-landlord setting.
*/
public function canAccessPanel(Panel $panel): bool
{
return $this->role !== null;
if ($panel->getId() === 'operator') {
return (bool) $this->is_operator;
}
return $this->currentRole() !== null || (bool) $this->is_operator;
}
/**
@@ -43,7 +57,158 @@ public function adminMode(): AdminMode
public function hasRole(UserRole ...$roles): bool
{
return in_array($this->role, $roles, true);
return in_array($this->currentRole(), $roles, true);
}
/**
* Role inside the landlord that is current. The operator acts as administrator of whichever landlord is open.
* With exactly one landlord, the old account role still applies until a membership exists.
*/
public function currentRole(): ?UserRole
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
if ($this->is_operator) {
return UserRole::Admin;
}
$role = $this->roleOn($tenantId);
if ($role !== null) {
return $role;
}
if ($this->role !== null && Tenant::query()->count() === 1) {
return $this->role;
}
return null;
}
if ($this->role !== null) {
return $this->role;
}
if ($this->is_operator) {
return UserRole::Admin;
}
$memberships = $this->tenants()->get();
if ($memberships->count() === 1) {
return $this->roleFromPivot($memberships->first()?->pivot?->role);
}
return null;
}
public function roleOn(int $tenantId): ?UserRole
{
$membership = $this->tenants()->where('tenants.id', $tenantId)->first();
return $this->roleFromPivot($membership?->pivot?->role);
}
/**
* Copy the account role onto the current landlord. Does nothing without a role or a landlord.
*/
public function attachCurrentRole(?Tenant $tenant = null): void
{
if ($this->role === null) {
return;
}
$tenant ??= app(TenantContext::class)->get();
if ($tenant === null) {
return;
}
$alreadyMember = $this->tenants()->where('tenants.id', $tenant->id)->exists();
if ($alreadyMember) {
if ($this->wasChanged('role')) {
$this->tenants()->updateExistingPivot($tenant->id, ['role' => $this->role->value]);
}
return;
}
$this->tenants()->attach($tenant->id, ['role' => $this->role->value]);
}
/**
* Password and two-factor stay on the account. A landlord admin may reset them only when the
* account belongs to no other landlord. Otherwise only the operator may.
*/
public function mayResetCredentials(?User $other): bool
{
if ($this->is_operator) {
return true;
}
if (! $this->hasRole(UserRole::Admin)) {
return false;
}
if ($other === null) {
return true;
}
return $other->tenants()->count() < 2;
}
/**
* Another landlord this account belongs to, when that landlord has its own domain.
*/
public function otherTenantAdminUrl(): ?string
{
$current = app(TenantContext::class)->id();
$other = $this->tenants()->where('tenants.id', '!=', $current)->first();
if ($other === null) {
return null;
}
$domain = $other->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
if (! is_string($domain) || $domain === '') {
return null;
}
return 'https://'.$domain.'/admin';
}
public function showsTenantSwitch(): bool
{
return $this->otherTenantAdminUrl() !== null;
}
public function revokeCurrentTenant(): void
{
$tenantId = app(TenantContext::class)->id();
if ($tenantId !== null) {
$this->tenants()->detach($tenantId);
}
}
/**
* @return BelongsToMany<Tenant, $this>
*/
public function tenants(): BelongsToMany
{
return $this->belongsToMany(Tenant::class)->withPivot('role')->withTimestamps();
}
private function roleFromPivot(mixed $role): ?UserRole
{
if ($role instanceof UserRole) {
return $role;
}
return is_string($role) ? UserRole::tryFrom($role) : null;
}
/**
@@ -58,6 +223,7 @@ protected function casts(): array
'password' => 'hashed',
'role' => UserRole::class,
'admin_mode' => AdminMode::class,
'is_operator' => 'boolean',
];
}
}
+7 -1
View File
@@ -47,6 +47,12 @@ private function occupies(BookingStatus|string|null $status): bool
private function tasks(Booking $booking, ChannelTaskAction $action): void
{
$this->createChannelTasks->handle($booking->property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
$property = $booking->property()->withoutGlobalScope('tenant')->first();
if ($property === null) {
return;
}
$this->createChannelTasks->handle($property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class AmenityPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class AppearancePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class BlockedPeriodPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Bookings;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class BookingPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Bookings;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class ChannelTaskPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Channels;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class FaqPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class GuestPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Guests;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class NoticePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PagePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PhotoPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Content];
return Permission::Content;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PortalEmailPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Channels;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class PropertyPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals];
return Permission::Properties;
}
}
+3 -3
View File
@@ -2,12 +2,12 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
class ReviewPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [UserRole::Rentals, UserRole::Content];
return Permission::Reviews;
}
}
+5 -7
View File
@@ -2,18 +2,16 @@
namespace App\Policies;
use App\Enums\UserRole;
use App\Enums\Permission;
use App\Models\User;
/**
* Grants every ability to the roles listed in roles(). Administrators always have access.
* Grants every ability that the current membership includes. The operator counts as administrator
* of the landlord that is open. A new role is added on UserRole, not in each policy.
*/
abstract class RolePolicy
{
/**
* @return list<UserRole>
*/
abstract protected function roles(): array;
abstract protected function permission(): Permission;
public function viewAny(User $user): bool
{
@@ -52,6 +50,6 @@ public function reorder(User $user): bool
protected function allows(User $user): bool
{
return $user->hasRole(UserRole::Admin, ...$this->roles());
return (bool) $user->currentRole()?->grants($this->permission());
}
}
+4 -2
View File
@@ -2,10 +2,12 @@
namespace App\Policies;
use App\Enums\Permission;
class SitePolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [];
return Permission::Settings;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Policies;
use App\Models\Tenant;
use App\Models\User;
/**
* Landlords are created and suspended by the operator. Deleting one is a later, separate step.
*/
class TenantPolicy
{
public function viewAny(User $user): bool
{
return $user->is_operator;
}
public function view(User $user, Tenant $tenant): bool
{
return $user->is_operator;
}
public function create(User $user): bool
{
return $user->is_operator;
}
public function update(User $user, Tenant $tenant): bool
{
return $user->is_operator;
}
public function delete(User $user, Tenant $tenant): bool
{
return false;
}
public function deleteAny(User $user): bool
{
return false;
}
}
+10 -4
View File
@@ -2,20 +2,26 @@
namespace App\Policies;
use App\Enums\Permission;
use App\Models\User;
/**
* Only administrators manage accounts; nobody can delete their own account.
* Only administrators of the current landlord manage accounts. A shared account is detached, not deleted,
* and nobody can delete their own account.
*/
class UserPolicy extends RolePolicy
{
protected function roles(): array
protected function permission(): Permission
{
return [];
return Permission::Users;
}
public function delete(User $user, ?User $model = null): bool
{
return $this->allows($user) && ! $user->is($model);
if (! $this->allows($user) || $user->is($model)) {
return false;
}
return $model === null || $model->tenants()->count() < 2;
}
}
+2 -1
View File
@@ -4,6 +4,7 @@
use App\Support\Settings;
use App\Support\StripImageMetadata;
use App\Tenancy\TenantContext;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
@@ -16,7 +17,7 @@ class AppServiceProvider extends ServiceProvider
*/
public function register(): void
{
//
$this->app->singleton(TenantContext::class);
}
/**
@@ -3,6 +3,7 @@
namespace App\Providers\Filament;
use App\Enums\AdminMode;
use App\Http\Middleware\ResolveTheme;
use App\Models\User;
use Filament\Actions\Action;
use Filament\Auth\MultiFactor\App\AppAuthentication;
@@ -49,6 +50,11 @@ public function panel(Panel $panel): Panel
isRequired: true,
)
->userMenuItems([
'tenant-switch' => Action::make('switchTenant')
->label('Anderer Mandant')
->icon(Heroicon::OutlinedArrowsRightLeft)
->visible(fn (): bool => self::currentUser()?->showsTenantSwitch() ?? false)
->url(fn (): ?string => self::currentUser()?->otherTenantAdminUrl()),
'admin-mode' => Action::make('switchAdminMode')
->label(fn (): string => (self::currentUser()?->adminMode() ?? AdminMode::Expert)->other()->switchLabel())
->icon(fn (): Heroicon => self::currentUser()?->adminMode() === AdminMode::Simple ? Heroicon::OutlinedAdjustmentsHorizontal : Heroicon::OutlinedSparkles)
@@ -79,6 +85,7 @@ public function panel(Panel $panel): Panel
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ResolveTheme::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
@@ -0,0 +1,63 @@
<?php
namespace App\Providers\Filament;
use App\Http\Middleware\ResolveTheme;
use Filament\Auth\MultiFactor\App\AppAuthentication;
use Filament\Http\Middleware\Authenticate;
use Filament\Http\Middleware\AuthenticateSession;
use Filament\Http\Middleware\DisableBladeIconComponents;
use Filament\Http\Middleware\DispatchServingFilamentEvent;
use Filament\Pages\Dashboard;
use Filament\Panel;
use Filament\PanelProvider;
use Filament\Support\Colors\Color;
use Filament\Widgets\AccountWidget;
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\PreventRequestForgery;
use Illuminate\Routing\Middleware\SubstituteBindings;
use Illuminate\Session\Middleware\StartSession;
use Illuminate\View\Middleware\ShareErrorsFromSession;
class OperatorPanelProvider extends PanelProvider
{
public function panel(Panel $panel): Panel
{
return $panel
->id('operator')
->path('betreiber')
->login()
->profile(isSimple: false)
->multiFactorAuthentication(
[AppAuthentication::make()->brandName('FeWo Stommer')->recoverable()],
isRequired: true,
)
->brandName('Betreiber')
->colors([
'primary' => Color::Slate,
])
->discoverResources(in: app_path('Filament/Operator'), for: 'App\Filament\Operator')
->pages([
Dashboard::class,
])
->widgets([
AccountWidget::class,
])
->middleware([
EncryptCookies::class,
AddQueuedCookiesToResponse::class,
StartSession::class,
ResolveTheme::class,
AuthenticateSession::class,
ShareErrorsFromSession::class,
PreventRequestForgery::class,
SubstituteBindings::class,
DisableBladeIconComponents::class,
DispatchServingFilamentEvent::class,
])
->authMiddleware([
Authenticate::class,
]);
}
}
+14 -2
View File
@@ -4,6 +4,7 @@
use App\Models\ContentBlock;
use App\Models\Photo;
use App\Tenancy\TenantContext;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\HtmlString;
@@ -54,7 +55,7 @@ public static function save(array $values): void
ContentBlock::updateOrCreate(['key' => $key], ['value' => $value]);
}
Cache::forget(self::CACHE_KEY);
Cache::forget(self::cacheKey());
}
/**
@@ -84,6 +85,17 @@ private static function definition(string $key): array
*/
private static function stored(): array
{
return Cache::rememberForever(self::CACHE_KEY, fn (): array => ContentBlock::pluck('value', 'key')->all());
return Cache::rememberForever(self::cacheKey(), fn (): array => ContentBlock::pluck('value', 'key')->all());
}
/**
* Stored texts are cached per landlord. Without a current landlord the key stays the historical one,
* which only happens before a request has chosen a website.
*/
private static function cacheKey(): string
{
$tenantId = app(TenantContext::class)->id();
return $tenantId === null ? self::CACHE_KEY : self::CACHE_KEY.'.'.$tenantId;
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace App\Tenancy;
use Illuminate\Support\Facades\DB;
/**
* Points every existing row at the landlord "Stommer". Used once, when tenancy is introduced
* on a database that already has the single-landlord data. Fresh databases have nothing to assign.
*/
class AssignLegacyData
{
/**
* Tables that gain a tenant_id. Order is irrelevant; nothing is deleted.
*
* @var list<string>
*/
public const TABLES = [
'sites',
'properties',
'guests',
'bookings',
'channels',
'portal_emails',
'photos',
'pages',
'appearances',
'notices',
'faqs',
'blocked_periods',
'amenities',
'reviews',
'channel_tasks',
'payments',
'seasons',
'extras',
'special_offers',
'channel_sync_logs',
'content_blocks',
];
public static function run(): void
{
$pending = false;
foreach (self::TABLES as $table) {
if (DB::table($table)->whereNull('tenant_id')->exists()) {
$pending = true;
break;
}
}
if (! $pending) {
return;
}
$tenantId = DB::table('tenants')->where('slug', 'stommer')->value('id');
if ($tenantId === null) {
$tenantId = DB::table('tenants')->insertGetId([
'name' => 'Stommer',
'slug' => 'stommer',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
foreach (self::TABLES as $table) {
DB::table($table)->whereNull('tenant_id')->update(['tenant_id' => $tenantId]);
}
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Tenancy;
use App\Models\Tenant;
/**
* The landlord of the current request, job or command. Empty means "not chosen yet".
* While presence is required, a query on a tenant-owned model without a landlord fails closed.
*/
class TenantContext
{
private ?Tenant $tenant = null;
private bool $required = false;
public function set(Tenant $tenant): void
{
$this->tenant = $tenant;
}
public function forget(): void
{
$this->tenant = null;
$this->required = false;
}
public function get(): ?Tenant
{
return $this->tenant;
}
public function id(): ?int
{
return $this->tenant?->id;
}
public function requirePresence(bool $required = true): void
{
$this->required = $required;
}
public function isRequired(): bool
{
return $this->required;
}
/**
* Run a callback as $tenant, then restore whoever was current before.
*
* @template T
*
* @param callable(): T $callback
* @return T
*/
public function run(Tenant $tenant, callable $callback): mixed
{
$previous = $this->tenant;
$this->tenant = $tenant;
try {
return $callback();
} finally {
$this->tenant = $previous;
}
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Tenancy;
use RuntimeException;
/**
* A tenant-owned query or insert ran without a current landlord while one was required.
*/
class TenantContextMissing extends RuntimeException
{
public function __construct(string $model)
{
parent::__construct("No current tenant for [{$model}].");
}
}
+59 -4
View File
@@ -4,6 +4,8 @@
use App\Models\Appearance;
use App\Models\Site;
use App\Models\SiteDomain;
use App\Models\Tenant;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
@@ -17,7 +19,12 @@ public function __construct(private ThemeRegistry $registry) {}
public function forRequest(Request $request): Theme
{
$site = $this->site($request->getHost());
$site = $this->siteForRequest($request->getHost());
if ($site === null) {
abort(404);
}
$isSigned = ($request->query('vorschau') || $request->query('theme')) && $request->hasValidSignature();
$preview = $isSigned && $request->query('vorschau') ? $site->appearances()->find($request->query('vorschau')) : null;
@@ -43,15 +50,63 @@ public function forSite(Site $site, ?Appearance $preview = null, bool $isPreview
);
}
/**
* The website for a console command: a matching host, otherwise the default website.
*/
public function site(?string $host = null): Site
{
return $this->matchedSite($host) ?? $this->defaultSite();
}
/**
* The website for an HTTP request. With two or more landlords an unknown host is not a website.
*/
public function siteForRequest(?string $host): ?Site
{
if (! Schema::hasTable('sites')) {
return $this->fallbackSite();
}
return ($host ? Site::query()->where('domain', $host)->first() : null)
?? Site::query()->where('is_default', true)->first()
?? Site::query()->orderBy('id')->first()
$matched = $this->matchedSite($host);
if ($matched !== null) {
return $matched;
}
if (Schema::hasTable('tenants') && Tenant::query()->count() > 1) {
return null;
}
return $this->defaultSite();
}
private function matchedSite(?string $host): ?Site
{
$host = is_string($host) ? mb_strtolower(trim($host)) : '';
if ($host === '' || ! Schema::hasTable('sites')) {
return null;
}
if (Schema::hasTable('site_domains')) {
$siteId = SiteDomain::query()->where('host', $host)->value('site_id');
if ($siteId) {
return Site::withoutGlobalScope('tenant')->find($siteId);
}
}
return Site::withoutGlobalScope('tenant')->whereRaw('lower(domain) = ?', [$host])->first();
}
private function defaultSite(): Site
{
if (! Schema::hasTable('sites')) {
return $this->fallbackSite();
}
return Site::withoutGlobalScope('tenant')->where('is_default', true)->first()
?? Site::withoutGlobalScope('tenant')->orderBy('id')->first()
?? $this->fallbackSite();
}
+2
View File
@@ -2,10 +2,12 @@
use App\Providers\AppServiceProvider;
use App\Providers\Filament\AdminPanelProvider;
use App\Providers\Filament\OperatorPanelProvider;
use App\Providers\ThemeServiceProvider;
return [
AppServiceProvider::class,
AdminPanelProvider::class,
OperatorPanelProvider::class,
ThemeServiceProvider::class,
];
+10
View File
@@ -36,6 +36,16 @@ public function definition(): array
];
}
public function configure(): static
{
return $this->afterCreating(function (Booking $booking): void {
Guest::withoutGlobalScope('tenant')
->whereKey($booking->guest_id)
->where('tenant_id', '!=', $booking->tenant_id)
->update(['tenant_id' => $booking->tenant_id]);
});
}
public function reserved(?\DateTimeInterface $holdExpiresAt = null): static
{
return $this->state(fn (): array => [
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace Database\Factories;
use App\Models\Tenant;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
/**
* @extends Factory<Tenant>
*/
class TenantFactory extends Factory
{
/**
* @return array<string, mixed>
*/
public function definition(): array
{
$name = fake()->unique()->company();
return [
'name' => $name,
'slug' => Str::slug($name).'-'.Str::lower(Str::random(4)),
'is_active' => true,
];
}
}
+18
View File
@@ -3,7 +3,9 @@
namespace Database\Factories;
use App\Enums\UserRole;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
@@ -18,6 +20,22 @@ class UserFactory extends Factory
*/
protected static ?string $password;
public function configure(): static
{
return $this->afterCreating(function (User $user): void {
if ($user->role === null || app(TenantContext::class)->id() !== null) {
return;
}
$tenant = Tenant::query()->count() === 1
? Tenant::query()->firstOrFail()
: Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$user->attachCurrentRole($tenant);
});
}
/**
* Define the model's default state.
*
@@ -0,0 +1,100 @@
<?php
use App\Tenancy\AssignLegacyData;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Add landlords and point every existing row at "Stommer". Columns start nullable so the
* assignment can run, then become required. Old code ignores the new columns.
*/
public function up(): void
{
Schema::create('tenants', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
$table->boolean('is_active')->default(true);
$table->timestamps();
});
foreach (AssignLegacyData::TABLES as $name) {
Schema::table($name, function (Blueprint $table) {
$table->foreignId('tenant_id')->nullable()->constrained()->restrictOnDelete();
});
}
AssignLegacyData::run();
foreach (AssignLegacyData::TABLES as $name) {
Schema::table($name, function (Blueprint $table) {
$table->unsignedBigInteger('tenant_id')->nullable(false)->change();
});
}
Schema::table('bookings', function (Blueprint $table) {
$table->dropUnique(['reference']);
$table->unique(['tenant_id', 'reference']);
});
Schema::table('content_blocks', function (Blueprint $table) {
$table->dropUnique(['key']);
$table->unique(['tenant_id', 'key']);
});
Schema::table('portal_emails', function (Blueprint $table) {
$table->dropUnique(['message_id']);
$table->unique(['tenant_id', 'message_id']);
});
Schema::table('properties', function (Blueprint $table) {
$table->dropUnique(['slug']);
$table->unique(['tenant_id', 'slug']);
});
Schema::table('guests', function (Blueprint $table) {
$table->index(['tenant_id', 'email']);
});
}
/**
* Drops the landlord assignment. Rows stay; the link to a landlord does not.
*/
public function down(): void
{
Schema::table('guests', function (Blueprint $table) {
$table->dropIndex(['tenant_id', 'email']);
});
Schema::table('properties', function (Blueprint $table) {
$table->dropUnique(['tenant_id', 'slug']);
$table->unique('slug');
});
Schema::table('portal_emails', function (Blueprint $table) {
$table->dropUnique(['tenant_id', 'message_id']);
$table->unique('message_id');
});
Schema::table('content_blocks', function (Blueprint $table) {
$table->dropUnique(['tenant_id', 'key']);
$table->unique('key');
});
Schema::table('bookings', function (Blueprint $table) {
$table->dropUnique(['tenant_id', 'reference']);
$table->unique('reference');
});
foreach (array_reverse(AssignLegacyData::TABLES) as $name) {
Schema::table($name, function (Blueprint $table) {
$table->dropConstrainedForeignId('tenant_id');
});
}
Schema::dropIfExists('tenants');
}
};
@@ -0,0 +1,68 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Membership is the role inside one landlord. The operator flag stays off here: it is granted
* afterwards with users:promote-operator, never by copying the old global role.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->boolean('is_operator')->default(false);
});
Schema::create('tenant_user', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('role');
$table->timestamps();
$table->unique(['tenant_id', 'user_id']);
});
Schema::create('tenant_access_logs', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->timestamp('created_at')->useCurrent();
});
$tenantId = DB::table('tenants')->where('slug', 'stommer')->value('id');
if ($tenantId === null) {
return;
}
$now = now();
foreach (DB::table('users')->whereNotNull('role')->get(['id', 'role']) as $user) {
DB::table('tenant_user')->insert([
'tenant_id' => $tenantId,
'user_id' => $user->id,
'role' => $user->role,
'created_at' => $now,
'updated_at' => $now,
]);
}
}
/**
* Drops memberships and the operator flag. Accounts and their old role column stay.
*/
public function down(): void
{
Schema::dropIfExists('tenant_access_logs');
Schema::dropIfExists('tenant_user');
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('is_operator');
});
}
};
@@ -0,0 +1,38 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* A website can answer on more than one host. The existing sites.domain value is the first host.
*/
public function up(): void
{
Schema::create('site_domains', function (Blueprint $table) {
$table->id();
$table->foreignId('site_id')->constrained()->cascadeOnDelete();
$table->string('host')->unique();
$table->timestamps();
});
$now = now();
foreach (DB::table('sites')->whereNotNull('domain')->where('domain', '!=', '')->get(['id', 'domain']) as $site) {
DB::table('site_domains')->insert([
'site_id' => $site->id,
'host' => mb_strtolower($site->domain),
'created_at' => $now,
'updated_at' => $now,
]);
}
}
public function down(): void
{
Schema::dropIfExists('site_domains');
}
};
+6
View File
@@ -4,6 +4,8 @@
use App\Enums\ExtraPricing;
use App\Models\Property;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use Illuminate\Database\Seeder;
/**
@@ -16,7 +18,11 @@ class PropertySeeder extends Seeder
*/
public function run(): void
{
$tenant = Tenant::stommer();
app(TenantContext::class)->set($tenant);
$property = Property::create([
'tenant_id' => $tenant->id,
'name' => 'Ferienwohnung Stommer',
'slug' => 'ferienwohnung-stommer',
'address' => 'Strandstraße 15, 18225 Kühlungsborn',
+6
View File
@@ -5,6 +5,8 @@
use App\Models\Page;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use Illuminate\Database\Seeder;
use Illuminate\Support\Arr;
@@ -19,7 +21,11 @@ class SiteSeeder extends Seeder
*/
public function run(): void
{
$tenantId = Property::withoutGlobalScope('tenant')->value('tenant_id') ?? Tenant::stommer()->id;
app(TenantContext::class)->set(Tenant::query()->findOrFail($tenantId));
$site = Site::create([
'tenant_id' => $tenantId,
'name' => 'Ferienwohnung Stommer',
'domain' => null,
'is_default' => true,
+3 -1
View File
@@ -5,6 +5,7 @@
use App\Enums\AmenityArea;
use App\Models\Faq;
use App\Models\Property;
use App\Tenancy\TenantContext;
use Illuminate\Database\Seeder;
/**
@@ -17,7 +18,8 @@ class WebsiteContentSeeder extends Seeder
*/
public function run(): void
{
$property = Property::query()->firstOrFail();
$property = Property::withoutGlobalScope('tenant')->firstOrFail();
app(TenantContext::class)->set($property->tenant);
$amenities = [
AmenityArea::General->value => ['Schnelles WLAN kostenlos', 'Pkw-Stellplatz inklusive', 'Abschließbarer Fahrradraum für 2 Räder', 'Diele mit großem Kleiderschrank und Spiegeln'],
+2
View File
@@ -2,6 +2,8 @@ # Mandantenfähigkeit – Anforderungen
Stand: 23.10.2026 · Anforderungen, noch keine Planung · Planung und Umbau in einer eigenen Sitzung · Grundlage: [KONZEPT.md](KONZEPT.md) („Mehrfähigkeit offen halten“), [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7
> Plan zur Freigabe: [MANDANTEN-PLAN.md](MANDANTEN-PLAN.md) (23.10.2026). Noch nicht umgesetzt.
>
> **Kurz:** Kein Portal und kein Marktplatz. Das Produkt ist **„die individuelle Website mit Vermieter-Funktionen“**. Einige Vermieter aus dem Bekanntenkreis sollen das System für ihre **eigene** Website nutzen können, mit eigenem Admin-Bereich und eigenen Diensten. Außerdem sollen weitere **eigene** Wohnungen unter fewo-stommer.de angeboten werden können. Das Datenmodell ist dafür nur zur Hälfte vorbereitet (§4). Der Umbau soll jetzt sauber geplant werden, solange es nur einen Vermieter gibt.
---
+293
View File
@@ -0,0 +1,293 @@
# Mandantenfähigkeit – Umbauplan
Stand: 23.10.2026 · freigegeben, Phase 1 und 2 im Code auf `feature/mandanten`, Datenbank noch nicht migriert · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §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.
Die Umsetzung läuft auf dem Branch `feature/mandanten`. Phasen 1–5 sind der Grundumbau. Marke/Bildwelt (Phase 6) und mehrere Wohnungen je Website (Phase 7) folgen in der festgelegten Reihenfolge und starten erst, wenn die Theme-Sitzung die Vertragsänderung aus [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6 übernehmen kann. `resources/themes/**` bleibt bis dahin unangetastet.
---
## 1. Entscheidungen vom 23.10.2026
| # | Frage | Entscheidung |
|---|---|---|
| 1 | Mandant und Website | **Getrennt.** Ein Mandant besitzt seine Websites. Betrieben wird zunächst eine Website je Mandant. Die Domain zeigt auf die Website und darüber auf den Mandanten. |
| 2 | Wohnung und Website | **Genau eine Website.** `properties.site_id` bleibt. Die Wohnung gehört zusätzlich direkt dem Mandanten. |
| 3 | Globale Einstellungen | **Geteilt**, siehe §5. Infrastruktur und der Schutz des Gesamtsystems bleiben global. Vermieterdaten, Texte, Postfach, Betriebsart und Regeln liegen je Mandant, Regeln innerhalb fester Grenzen. |
| 4 | Portal-Postfach | **Eigenes IMAP-Postfach je Mandant.** Zugangsdaten verschlüsselt, leeres Postfach = aus. Die Zuordnung einer Mail zum Portal bleibt die Absenderliste am Kanal. |
| 5 | KI-Schlüssel | **Beides, nur als Datengrundlage.** Voreinstellung ist der Schlüssel des Betreibers, Verbrauch je Mandant gezählt. Ein eigener Schlüssel des Mandanten ist möglich und ersetzt dann den des Betreibers. Kein KI-Aufruf in diesem Umbau. |
| 6 | Reihenfolge | **Mandant → Marke/Bildwelt → mehrere Wohnungen je Website.** |
Dazu die Sicherheitsregel aus A6a und A6b, bestätigt am 23.10.2026:
Passwort und 2FA gehören zum **Konto**, die Rolle zur **Mitgliedschaft**. Ein Mandanten-Administrator setzt Passwort und 2FA nur zurück, wenn das Konto ausschließlich seinem Mandanten gehört. Gehört es mehreren Mandanten, darf das nur der Betreiber. Die Mitgliedschaft (Rolle ändern, Zugang zu diesem Mandanten sperren) bleibt beim Mandanten-Administrator.
Die einfache/Expertenansicht bleibt eine Einstellung **je Benutzer** (A6c). Eine eigene Ansicht je Mandant gibt es in diesem Umbau nicht.
---
## 2. Geprüfter Ist-Stand
Prüfung im Code am 23.10.2026. Filament ist in `v5.10.3` installiert (`filament/filament`). Die Mandantenfunktion ist vorhanden und **nicht eingeschaltet** (`AdminPanelProvider` setzt keinen Mandanten).
Was Filament mitbringt (`Panel::tenant()`, `HasTenants`, Middleware `IdentifyTenant`, Trait `BelongsToTenant`):
- Der Admin filtert Ressourcen, sobald ein Mandant gesetzt ist, und setzt bei neuen Datensätzen die Zugehörigkeit, wenn das Modell eine `tenant()`-Beziehung vom Typ `BelongsTo` hat.
- Ohne `tenantDomain()` hängt Filament eine zusätzliche URL-Stufe `/admin/{mandant}` an. Mit `tenantDomain('{tenant}')` bleibt der Pfad `/admin`, der Mandant kommt aus dem Host. So bleibt Brigittes Adresse.
- Der eingebaute Filter gilt **nur im Admin-Panel, und erst nachdem der Mandant erkannt wurde**. Website, signierte Links, Cron, Mails und eigene Abfragen sind nicht gefiltert. `unique()`- und `exists()`-Regeln umgehen den Filter. Filament schreibt das selbst so: die Trennung bleibt unsere Aufgabe (A3).
Deshalb entsteht ein eigener Mandantenkontext für die ganze Anwendung. Filament nutzt ihn im Admin mit, ersetzt ihn aber nicht.
### Was §4 schon stimmt
- `sites` (Domain, Theme, `is_default`), `pages` und `appearances` mit `site_id`, `properties.site_id`.
- Saisons, Extras, Buchungen, Sperrzeiten, Angebote, Fotos, Ausstattung, Bewertungen und Kanäle hängen an der Wohnung.
- Die Website wählt die Site über den Host (`ThemeFactory`, Middleware `ResolveTheme`). Die Seed-Site hat `domain = null` und `is_default = true`; jeder unbekannte Host landet heute auf dieser Site.
- Themes und Portal-Connectoren sind austauschbare Pakete.
- Rollen heute: eine Spalte `users.role` (`admin`, `rentals`, `content`). Richtlinien prüfen nur die Rolle, nicht den Datensatz. Die Benutzerverwaltung ist systemweit und nur für Administratoren.
- Die einfache Ansicht ist die Menüliste `AdminMode::SIMPLE_NAVIGATION`. Benutzer, Websites, Texte und Betrieb stehen dort nicht. Brigitte sieht sie in der einfachen Ansicht nicht.
### Was die Prüfung gegenüber §4 korrigiert
| Stelle | Befund |
|---|---|
| Zahlungen | Nur `booking_id`. Die Trennung wäre nur über Buchung → Wohnung → Website gegeben. `Payment::query()` ist offen. |
| `channel_sync_logs`, `channel_tasks` | Nur `channel_id`, also Kanal → Wohnung → Website. Dieselben offenen Abfragen. |
| `portal_emails` | Nicht herrenlos: `channel_id` ist Pflicht. Global sind das eindeutige `message_id` und das eine IMAP-Postfach aus der `.env`. |
| Buchungsnummern | Beim Anlegen `Jahr-` plus globale `id`, eindeutig über alle Zeilen (`Booking`, Hook `created`). Kein eigener Nummernkreis (A13). Bestehende Nummern, z. B. `2026-0002`, bleiben unverändert. |
| Gästekartei | `CreateReservation` sucht `Guest::where('email')` **ohne** Grenze. Dieselbe Adresse wäre ab dem zweiten Mandanten ein gemeinsamer Gast (verletzt A2). Die E-Mail ist nicht eindeutig, zwei getrennte Zeilen sind also möglich, sobald die Suche den Mandanten kennt. |
| Texte und Einstellungen | `content_blocks.key` und `settings.key` sind systemweit eindeutig. |
| `properties.slug` | Systemweit eindeutig. |
| Links in Mails | `URL::forceRootUrl(APP_URL)` außerhalb von local/testing pinnt jeden signierten Link (Angebot, Bewertung, Einwilligung, Vorschau) auf **eine** Adresse. |
| Mails | Absender und Antwortadresse kommen beim Start aus `Settings` und überschreiben `config` für den ganzen Prozess. Ein Cron-Lauf über mehrere Mandanten würde die Absender vermischen, wenn das so bleibt. Mails sind nicht in der Queue. |
| Marke | `public/brand/`, Bausteine nutzen `$theme->property()` (die erste aktive Wohnung der Site). |
---
## 3. Zielbild
```text
Betreiber (Lars, außerhalb der Mandanten)
│
▼
Mandant „Stommer“ ── besitzt ── Website fewo-stommer.de / stommer.info
│ Theme, Seiten, Erscheinungsbilder
│ genau die Wohnungen dieser Website
├── Benutzer (Mitgliedschaft + Rolle)
├── Gäste, Buchungen, Nummernkreis
├── Texte, Vermieterdaten, Bank, Postfach, Betriebsart
└── Dienste (an/aus, Schlüssel, Verbrauch)
```
**Erkennung.** Öffentliche Anfrage und Admin lesen den Host, finden die Website, daraus den Mandanten, und setzen den Kontext, bevor eine fachliche Abfrage läuft. `/admin` bekommt keine zusätzliche Pfadstufe.
**Unbekannter Host.** Solange es genau einen Mandanten gibt, gilt wie heute die Standard-Website (lokal, und solange die Domain noch leer ist). Ab dem zweiten Mandanten antwortet ein unbekannter Host mit 404. Er zeigt nicht still die Daten von Stommer.
**Kontext fehlt.** Im HTTP-Request wirft eine fachliche Abfrage ohne Mandanten eine Ausnahme (geschlossen, nicht offen). Ausnahmen sind nur die Token-Wege: iCal-Feed, Health, Scheduler-Anstoß, Automation. Dort gilt das Token als Ausweis, der Datensatz bestimmt den Mandanten, und erst dann laufen weitere Abfragen. Artisan-Befehle, die alle Mandanten betreffen, setzen den Kontext in der Schleife. Der Betreiber-Bereich umgeht den Filter nur dort, nie im Mandanten-Admin.
**Brigitte.** Eine Mitgliedschaft, Rolle Mandanten-Administrator, einfache Ansicht. Menü, Pfad `/admin` und Ablauf Anfrage → Angebot → Annahme bleiben. Der Mandantenwechsel erscheint erst, wenn ein Konto mehr als einen Mandanten hat. Die Beschriftung der Verwaltung für Stommer bleibt „FeWo Stommer · Verwaltung“. Der Name in der Authenticator-App für bestehende Einrichtungen bleibt.
---
## 4. Datenmodell und Übernahme
Neue Tabelle `tenants`: Name, Slug (`stommer`), aktiv/gesperrt, Vermieterdaten, Bank, Steuerangabe, Absender, Benachrichtigungsadressen, Betriebsart, Testempfänger, Postfach, Fristen und Grenzen aus §5. Bank, Steuerangabe und Postfach-Passwort über das Laravel-`encrypted`-Cast (`APP_KEY`). Ein zweites Verschlüsselungsverfahren gibt es nicht.
Neue Tabelle `tenant_user`: `tenant_id`, `user_id`, `role`, eindeutig je Paar. `users.email` bleibt systemweit eindeutig (ein Konto, eine 2FA). `users.is_operator` (Standard nein). `users.admin_mode` bleibt am Benutzer. Die Spalte `users.role` wird in die Mitgliedschaft kopiert und danach entfernt.
`tenant_id` (Pflicht, Index, `BelongsTo`) an jeder fachlichen Tabelle, die eigene Abfragen oder einen Filament-Eintrag hat und die beim Export oder bei der Löschung eines Mandanten direkt gefunden werden muss:
`sites`, `properties`, `guests`, `bookings`, `channels`, `portal_emails`, `photos`, `pages`, `appearances`, `notices`, `faqs`, `blocked_periods`, `amenities`, `reviews`, `channel_tasks`, `payments`, `seasons`, `extras`, `special_offers`, `channel_sync_logs`, `content_blocks`.
Kinder ohne eigenen Bildschirm (Zahlungen, Sync-Protokoll) bekommen die Spalte trotzdem. Löschen und Exportieren eines Mandanten ist dann eine Liste von `where tenant_id`, nicht ein Join über acht Stufen (A25). Medien bleiben an ihrem Modell hängen (Spatie); sie werden über das Elternmodell gelöscht, damit die Dateien mit verschwinden.
`settings` wird nicht mitgezogen. Die wenigen Schlüssel (Betriebsart, Adressen, Absender) werden Spalten des Mandanten. Danach ist die Tabelle leer und entfällt. Es gibt einen Speicher für Betriebsdaten, nicht zwei.
Schlüssel, die heute systemweit eindeutig sind und sich je Mandant wiederholen dürfen:
| Spalte | Neu |
|---|---|
| `content_blocks.key` | eindeutig je Mandant |
| `properties.slug` | eindeutig je Website |
| `bookings.reference` | eindeutig je Mandant |
| `portal_emails.message_id` | eindeutig je Mandant |
`channels.export_token` bleibt systemweit eindeutig. Der Token ist der Ausweis für den Feed; die Suche danach setzt danach den Mandanten des Kanals.
### Buchungsnummern (A13)
Format bleibt `2026-0001`. Der Zähler ist das Maximum der laufenden Nummer dieses Mandanten in diesem Jahr plus eins, mit Sperre beim Anlegen. Bestehende Nummern von Stommer werden nicht umgeschrieben. Der nächste Stommer-Vorgang zählt ab der höchsten vorhandenen Nummer weiter, nicht ab der globalen `id`.
### Gäste (A2)
Suche und Neuanlage in `CreateReservation` filtern auf den aktuellen Mandanten. Dieselbe E-Mail bei zwei Mandanten ergibt zwei Gäste. Rate-Limits der Buchungsanfrage, die heute nur die E-Mail kennen, schließen den Mandanten ein. Die systemweite Flutgrenze zählt weiter über alle Mandanten.
### Migration ohne Ausfall (A26)
MySQL bestätigt Schemaänderungen sofort, auch mitten in einer Migration. Die Übernahme ist deshalb so geschnitten, dass die **alte** Fassung nach jedem Schritt noch läuft, und die **neue** Fassung erst ausgeliefert wird, wenn die Daten stehen. Der Datenbestand ist klein (eine Wohnung, eine Testbuchung); die Füllung passiert in der Migration, nicht in einem eigenen Job.
1. Tabellen und Spalten anlegen, `tenant_id` noch ohne Pflicht.
2. Mandant „Stommer“ anlegen. Bestehende Website, alle Wohnungen und alle abhängigen Zeilen darauf setzen. Gäste, Texte, Einstellungen, FAQ und Hinweise ebenso, es gibt nur diesen Bestand.
3. Heutige Werte aus `settings` und aus `config/fewo.php` (Vermieter, Bank, Fristen, Postfach, Betriebsart) in den Mandanten schreiben. `.env` bleibt für die globalen Werte.
4. Mitgliedschaften aus `users.role` erzeugen. Niemand wird in der Migration zum Betreiber.
5. Erst jetzt Pflicht, Fremdschlüssel und die neuen Eindeutigkeiten. `users.role` und `settings` entfernen, sobald der ausgelieferte Code sie nicht mehr liest (eigener Schritt am Ende von Phase 2 bzw. 3, nicht zusammen mit dem Anlegen).
Slug `stommer`, Name aus dem bisherigen Vermieter. Die Website bleibt Standard-Website mit leerer Domain, bis die echten Hosts eingetragen sind. Vor dem zweiten Mandanten werden die Hosts von Stommer gepflegt (stommer.info, später fewo-stommer.de und `www`). Dafür reicht eine kleine Tabelle `site_domains` (Website, Host, eindeutig). Ein Host gehört zu genau einer Website.
Nach dem Deploy einmalig, von Lars, nicht in der Migration: `php artisan users:promote-operator` für das eigene Konto. Bis dahin ist der einzige Mandanten-Administrator über seine Mitgliedschaft handlungsfähig. Brigittes Konto wird nicht befördert; es existiert laut STATUS noch nicht und wird später normal als Mandanten-Administratorin angelegt.
---
## 5. Was global bleibt, was umzieht
**Bleibt in `.env` / `config` (Betreiber, nicht im Mandanten-Admin):**
| Wert | Grund |
|---|---|
| Datenbank, `APP_KEY`, SMTP-Host, SMTP-Benutzer, SMTP-Passwort | ein Versandweg für alle; die Absenderadresse ist trotzdem je Mandant |
| `FEWO_MAIL_REDIRECT_TO` | harte Umleitung des ganzen Servers (Testbetrieb auf stommer.info) |
| Backup-Aufbewahrung | ein Backup der ganzen Datenbank (A25) |
| Scheduler-Token, Health-Token, Automation-Webhook und -Geheimnis | Betrieb des Gesamtsystems |
| `spam.total_per_hour` | Flutgrenze über alle Websites |
| Obergrenzen für Löschfristen und für die Bot-Schutz-Werte | ein Mandant kann sie verschärfen, nicht abschalten |
**Zieht an den Mandanten:** Name, Anschrift, Telefon, E-Mail, Bank, Steuerangabe, Impressum und Datenschutz (weiter über die Texte), Mietbedingungen, Storno, Mail- und Vertragstexte, FAQ, Hinweise, Absender, Benachrichtigungen, Postfach, Betriebsart Test/scharf, Anzahlungsfrist, Bewertungsfrist, Löschfristen, Bot-Schutz außer der Flutgrenze, Fristen der Portal-Überwachung. Anzahlungssatz, Endreinigung und Mindestaufenthalt liegen schon an der Wohnung und bleiben dort.
`config/content.php` bleibt der **Feldkatalog** (dieselben Felder für jeden Mandanten, Standardtexte im Code). Die gepflegten Werte liegen in `content_blocks` je Mandant. Neue Felder kommen per Deploy für alle.
Der Code liest Vermieter, Bank, Fristen und Adressen über den aktuellen Mandanten. `config('fewo.owner.*')` und `Settings::get()` werden an diesen Stellen abgelöst. Die globalen Schlüssel bleiben über `config('fewo.*')` erreichbar.
### Dienste (A15–A17, ohne Funktion dahinter)
Tabelle `tenant_services`: Mandant, Schlüssel (`portal_sync`, `portal_mail`, `ai_offers`, `ai_marketing`, `ai_guest_mail`), an/aus, eigener API-Schlüssel verschlüsselt und leer erlaubt.
Tabelle `service_usages`: Mandant, Dienst, Menge, Zeitpunkt. Es wird noch nichts gezählt, weil noch kein Dienst aufruft. Der Betreiber schaltet Dienste je Mandant. Ist ein eigener Schlüssel leer, gilt später der Schlüssel des Betreibers aus der `.env`. Diesen zentralen Schlüssel gibt es in diesem Umbau noch nicht als Aufruf, nur als vorgesehene Stelle.
---
## 6. Rollen, Admin, Betreiber
Rollen bleiben ein PHP-Enum, gespeichert als Text in `tenant_user.role`. Dazu ein Rechtekatalog an einer Stelle (`UserRole::permissions()`): Buchungen sehen, Buchungen ändern, Gäste, Preise, Bilder, Texte, Benutzer, Betrieb, … Die Richtlinien fragen das Recht des **aktuellen** Mandanten, nicht mehr „ist Administrator oder steht auf dieser Liste“. Eine spätere Rolle Reinigung oder Steuerberater ist ein neuer Enum-Fall und eine Rechtemenge, ohne neue Tabellen und ohne den Filter neu zu bauen (A6d).
| Rolle | Bedeutung | Rechte, unverändert zur heutigen Aufgabe |
|---|---|---|
| Mandanten-Administrator | bisher `admin`, nur dieser Mandant | alles im Mandanten, einschließlich Benutzer |
| Vermietung | bisher `rentals` | Buchungen, Gäste, Preise, Angebote, Bewertungen |
| Inhalte | bisher `content` | Bilder, Texte, FAQ, Hinweise, Bewertungen |
| Betreiber | `users.is_operator`, **keine** Mitgliedsrolle | Mandanten anlegen und sperren, ersten Mandanten-Administrator anlegen, Dienste, Domains, Systemzustand, Wechsel in einen Mandanten |
Der Admin nutzt Filaments Mandantenfunktion mit `tenantDomain('{tenant}')` und `resolveTenantUsing`: der Host ist der Schlüssel, die Website mit diesem Host liefert den Mandanten. `User` erfüllt `HasTenants`. `canAccessTenant` ist wahr bei einer Mitgliedschaft oder beim Betreiber.
Der Betreiber-Bereich ist ein zweites Panel ohne Mandantenfilter, Pfad `/betreiber`, nur für `is_operator`. Dort entstehen Mandanten und der erste Administrator. „In den Mandanten wechseln“ öffnet `https://<host>/admin` und schreibt einen Eintrag (Benutzer, Mandant, Zeitpunkt). Im Mandanten-Admin gilt derselbe Filter wie für jeden anderen; der Betreiber sieht dort nur diesen Mandanten. Hat er dort keine Mitgliedschaft, gelten für den Support die Rechte des Mandanten-Administrators, und der Zugriff bleibt protokolliert.
**Benutzerverwaltung (A6a).** Der Mandanten-Administrator sieht nur Mitglieder seines Mandanten. Neue E-Mail legt ein Konto an (Passwort, 2FA beim ersten Login wie heute). Bestehende E-Mail hängt das Konto an diesen Mandanten, ohne die andere Mitgliedschaft zu zeigen oder zu ändern. Rolle ändern und Mitgliedschaft entziehen betrifft nur diese Zeile. Passwort und 2FA nach der Regel in §1. Er kann die Betreiber-Markierung nicht setzen und keine Rolle außerhalb der drei Mandantenrollen vergeben.
Die einfache Ansicht zeigt die Benutzerverwaltung weiterhin nicht. Brigitte arbeitet dort nicht anders als heute.
---
## 7. Domain, Cron, Mails
**Öffentliche Website.** `ResolveTheme` setzt neben Theme und Erscheinungsbild den Mandanten. Buchungsformular, Seiten und FAQ laufen in diesem Kontext.
**Signierte Links.** Angebot, Annahme, Bewertung und Einwilligung werden mit dem Ursprung der Website erzeugt (Schema und Host der Site), nicht mit einem für alle pinnten `APP_URL`. Die bestehende Festlegung der Root-URL bleibt der Schutz davor, dass auf dem jetzigen Host Pfade wie `/current/public` in Links geraten; sie wird nicht zur Mandantenerkennung und nicht auf fremde Domains ausgedehnt. Ein Link von Mandant A ist auf dem Host von Mandant B ungültig (die Signatur umfasst die ganze URL) und die Buchung wäre dort zusätzlich außerhalb des Filters.
**Cron** (`routes/console.php`). Backup bleibt ein globaler Lauf. Alle anderen Aufgaben laufen je aktivem Mandanten in dessen Kontext: Fristen, Erinnerungen, Bewertungen, Anonymisierung, Kanalabgleich, Portal-Mail, Aufgaben-Erinnerung. Grenzen und Postfach kommen aus dem Mandanten. Ein Lauf setzt Absender und Antwortadresse für diesen Versand und setzt sie danach zurück; nichts davon bleibt als Prozess-`config` für den nächsten Mandanten hängen. Die Mail-Klassen bekommen Absender, Antwortadresse und Umleitung als Werte beim Erzeugen, nicht beim späteren Lesen aus der Konfiguration.
**Postfach.** `MailboxReader` bekommt die Zugangsdaten des Mandanten. Leer = dieser Mandant wird übersprungen. Verarbeitete `message_id` gelten je Mandant.
**Betriebsart.** Test/scharf ist je Mandant. `FEWO_MAIL_REDIRECT_TO` gewinnt weiterhin für den ganzen Server. Auf stommer.info bleiben damit alle Mails bei der Testadresse, auch nach dem Umbau.
**iCal.** Der Export-Token sucht den Kanal ohne Mandantenfilter, setzt dann dessen Mandanten, und der Feed enthält nur dessen Belegung.
---
## 8. Phasen
Jede Phase liegt auf `feature/mandanten`, hat grüne Tests (`php artisan test --compact` auf die betroffenen Dateien, am Ende der Phase die ganze Suite) und ist für sich nach `main` zusammenführbar. Ausgeliefert wird nur aus `main`. `resources/themes/**` wird nicht geändert. Nach dem Zusammenführen schreibt die Sitzung `docs/STATUS.md`. Eine Änderung am Vorlagen-Vertrag gibt es in Phase 1–5 nicht; §6 von ZUSAMMENARBEIT bleibt deshalb in diesen Phasen leer.
### Phase 1 – Mandant und Daten
Ziel: Alles, was heute existiert, gehört Stommer. Ein zweiter Mandant sieht davon nichts. Verhalten mit nur diesem Mandanten ist dasselbe.
- Tabellen, Trait, Kontext, Middleware für die Website, Übernahme wie §4.
- Fabriken legen den Mandanten an und hängen Daten daran.
- Buchungsnummern je Mandant, Gästesuche je Mandant.
- `users.role` wird noch mitgeführt, damit Phase 1 ohne die neue Rechteprüfung auskommt.
Tests: Übernahme setzt jede bestehende Zeile auf Stommer. Zwei Mandanten, gleiche Gast-E-Mail, zwei Gäste, getrennte Buchungen. Nummernkreis `2026-0001` je Mandant, Stommer zählt an seiner höchsten Nummer weiter. Abfrage ohne Kontext im HTTP-Test schlägt fehl.
### Phase 2 – Rollen, Admin, Benutzer
Ziel: Brigitte arbeitet im selben `/admin`. Ein zweiter Mandant hat eigene Benutzer und kommt an Stommer nicht heran.
- Mandant über die Domain (eigener Kontext, Pfad bleibt `/admin`), Panel `/betreiber`, Rechtekatalog, Richtlinien, Benutzerverwaltung nach §6. Umgesetzt.
- `users.role` bleibt, solange der Code sie noch als Übergang liest. Entfernen, wenn kein Leser mehr übrig ist.
- Befehl `users:promote-operator`. Umgesetzt.
Tests: Mitglied von A öffnet eine Buchung von B per Adresse und bekommt 404. Mandanten-Administrator vergibt keine Betreiber-Markierung und sieht keine fremden Benutzer. Konto mit zwei Mitgliedschaften: Passwort-Reset durch den Mandanten-Administrator wird verweigert, durch den Betreiber nicht. Rolle Vermietung kann keine Benutzer anlegen. Einfache Ansicht enthält dieselben Menüpunkte wie vor dem Umbau. Konto mit einem Mandanten sieht keinen Wechsel.
### Phase 3 – Einstellungen, Texte, Dienste-Grundlage
Ziel: Vermieterdaten und Texte sind Daten des Mandanten. Die `.env` von Stommer ist nach der Übernahme nur noch Infrastruktur.
- Spalten am Mandanten, `content_blocks` je Mandant, FAQ und Hinweise je Mandant, Seite „Betrieb“ schreibt den aktuellen Mandanten.
- Katalog in `config/content.php` bleibt.
- `tenant_services` und `service_usages`, Schalter nur im Betreiber-Bereich.
- Tabelle `settings` entfernen.
Tests: Zwei Mandanten, unterschiedliches Impressum, unterschiedliche Bank, unterschiedliche Betriebsart. Mandant kann die Flutgrenze und die Löschfrist nicht über die globale Obergrenze heben. Leerer Dienst-Schlüssel ist erlaubt.
### Phase 4 – Domain, Cron, Mail, Postfach
Ziel: Host, Erinnerungen und Portal-Mails gehören dem richtigen Mandanten.
- `site_domains`, 404 für unbekannte Hosts ab dem zweiten Mandanten. Umgesetzt. Mit genau einem Mandanten bleibt die Standard-Website auf jeder Adresse.
- Links mit dem Ursprung der Website. Umgesetzt für Angebot, Annahme, Bewertung und Einwilligung.
- Scheduler-Schleife, Postfach je Mandant, Absender je Versand. Noch nicht.
Tests: Angebotslink trägt den Host der Website. Erinnerungslauf für A schreibt keine Mail an Gäste von B und nicht mit dem Absender von B. Postfach-Passwort von A ist aus dem Kontext von B nicht lesbar. iCal-Token von A liefert keine Belegung von B. Unbekannter Host bei zwei Mandanten: 404. Mit einem Mandanten: Standard-Website wie heute.
### Phase 5 – Abnahme der Trennung und Kündigung
Ziel: Ein Befehl exportiert und löscht genau einen Mandanten (A25). Die Trennung ist als Suite festgehalten, nicht nur in den einzelnen Phasen.
- Befehl des Betreibers: Export (Daten + Dateien dieses Mandanten) und Löschung in der Reihenfolge, die die Fremdschlüssel erlauben, einschließlich Medien.
- Eine Testklasse je Bereich aus A1: Wohnungen, Preise, Kalender, Buchungen, Zahlungen, Gäste, Bewertungen, Portale, Texte, Fotos, Seiten, Einstellungen, Benutzer.
Tests: Nach der Löschung von A ist B vollständig da, inklusive Dateien und Buchungsnummern. Export von A enthält keine Zeile von B.
### Phase 6 – Marke und Bildwelt (danach, eigene Freigabe)
A14, A18, A19, A20, A22. Nicht zusammen mit Phase 1–5, und nicht solange der Branch `theme/<key>` die Vorlagen noch nicht nachziehen kann.
- Marke (Logo, Favicon, Logo für Mail und PDF) als Medien der Website. `public/brand/` wird zur Quelle, aus der Stommer einmalig übernommen wird, und ist danach nicht mehr der Ablageort.
- Bildwelten als Pakete neben den Themes (`resources/image-worlds/<key>/`, Manifest und SVGs), analog zu Themes, nicht als Upload. Die Website wählt eine Bildwelt. Eine Wohnung kann sie überschreiben (A20); das ist die Stelle für die Berg-Wohnung, auch wenn Phase 7 die Auswahl in den Bausteinen erst danach scharf schaltet.
- Themes sprechen nur Plätze an (Trenner, Abschlussband, Vignette), keine feste Ostsee-Datei (A19). Das ändert den Vorlagen-Vertrag. Vor der ersten geänderten Theme-Datei steht der Eintrag in ZUSAMMENARBEIT.md §6. Das parallel entstehende Theme wird nicht von dieser Sitzung editiert.
### Phase 7 – Mehrere Wohnungen je Website (zuletzt)
A21. Die Seite bleibt bei einer Wohnung, solange ein Baustein keine nennt.
- Im Seiten-Baukasten kann ein Baustein eine Wohnung dieser Website wählen. Ohne Wahl gilt `primaryProperty()` wie heute.
- Der Renderer setzt diese Wohnung, bevor der Baustein läuft. Bestehende Vorlagen, die `$theme->property()` rufen, bleiben gültig. Eine neue Übersicht auf der Startseite und eine Suche über mehrere Wohnungen sind neue Bausteine im Katalog; auch das ist ein Eintrag in §6, bevor eine Theme-Datei entsteht.
---
## 9. Betrieb und Abgrenzung
- Hosting bleibt vorerst Strato. Domain und Zertifikat eines neuen Mandanten richtet der Betreiber von Hand ein und trägt den Host in `site_domains` ein (A23). Der Umbau speichert keine Strato-Pfade, keine fest verdrahtete Weiterleitung und keine zweite Root-URL-Logik für den Release-Ordner.
- Umzug auf einen eigenen Server ändert das Datenmodell nicht (A24).
- Eine Datenbank, ein Backup. Export und Löschung eines Mandanten können den Rest (Phase 5).
- Keine Selbstregistrierung, keine Abrechnung, kein Portal, keine gemeinsame Suche.
- AVV, Nutzungsbedingungen und die Nennung der Unterauftragnehmer (A27, A28) bleiben eine rechtliche Aufgabe. Technisch ist nur sichergestellt, dass Impressum und Datenschutz die Texte des Mandanten sind und der Betreiber sie nicht als eigene Vermieterdaten ausliefert.
- Parallel laufendes Theme: diese Sitzung ändert `resources/themes/**` nicht. Wünsche der Design-Sitzung weiter über ZUSAMMENARBEIT.md §5.
---
## 10. Freigabe
Phase 1 und 2 sowie der Website-Teil von Phase 4 sind im Code, zusammen mit Seebad 0.3. Die Datenbank auf stommer.info ist noch nicht migriert: Auslieferung aus `main` (das Skript migriert), danach `users:promote-operator` für das eigene Konto. Phase 3 bis 5 folgen und 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.
+6 -5
View File
@@ -1,6 +1,6 @@
# Projektstand
Stand: 22.10.2026, spätabends · ausgelieferter Stand: siehe neuester Git-Tag `deploy/staging/*` · 200 Tests grün
Stand: 23.10.2026 · ausgelieferter Stand: siehe neuester Git-Tag `deploy/staging/*` · 217 Feature-Tests grün auf `feature/mandanten`
> Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“).
@@ -24,7 +24,7 @@ ## 1. Fertig (umgesetzt, getestet, auf stommer.info)
- **Bewertungen:** Einladung per E-Mail, Freigabe im Admin, Anzeige mit Pflichthinweis zur Echtheit.
**Verwaltung (Admin)**
- **Rollen:** Administrator, Vermietung, Inhalte.
- **Rollen:** Mandanten-Administrator, Vermietung, Inhalte. Auf `feature/mandanten` gilt die Rolle je Mandant; der ausgelieferte Stand hat noch die eine Rolle je Konto.
- **Ansichten:** Die **einfache Ansicht** zeigt Anfragen & Buchungen, Sperrzeiten, **Preise & Angebote**, Gäste, Portal-Aufgaben, Bewertungen und Bilder. Die **Expertenansicht** zeigt alles. Umschalten im Benutzermenü.
- **Sicherheit:** 2FA ist für **alle** Konten Pflicht; Administratoren können die 2FA eines anderen Kontos zurücksetzen und Passwörter neu vergeben.
@@ -69,7 +69,8 @@ ## 3. Offen
**Technik**
- Cronjob auf Strato einrichten (BETRIEB.md §6).
- Neues Design-Theme: läuft in einer eigenen Session auf dem privaten Rechner (ZUSAMMENARBEIT.md, THEME-ERSTELLUNG.md).
- 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 liegen auf `feature/mandanten`, zusammen mit Seebad 0.3 (Mandant, Mitgliedschaften, `/betreiber`, Host je Website, Gäste-Links). Cron, Postfach und Absender je Mandant fehlen noch; mit genau einem Mandanten bleibt der bisherige Betrieb. Die Datenbank auf stommer.info ist noch nicht migriert. 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:
@@ -87,7 +88,7 @@ ## 4. Nächste Schritte (Vorschlag)
1. Cronjob einrichten; SMTP einschalten und mit `mail:test` prüfen (Mails landen wegen Testbetrieb nur bei Lars); Konto für Brigitte anlegen.
1a. Vor dem Go-Live: System › Betrieb auf „scharf geschaltet“ stellen – erst dann erhalten Gäste die Mails. Beim Go-Live außerdem unter System › Betrieb › Adressen Kontakt-/Antwortadresse und Benachrichtigungen von fewo@stommer.de auf **info@fewo-stommer.de** umstellen (Entscheidung 23.10.2026; Absender ist bereits info@fewo-stommer.de).
2. Brigitte probt Anfrage → Angebot → Annahme mit einem eigenen Test (Angebotslink über die Aktion „Angebotslink“).
3. Design-Theme auf dem privaten Rechner (eigene Session, siehe ZUSAMMENARBEIT.md).
3. Testinstanz stommer.info auf den Mandanten heben: aus `main` ausliefern (Migration läuft dabei), danach `users:promote-operator` für `lars@stommer.com`. Vor einem zweiten Mandanten den Host `stommer.info` an der Website eintragen.
4. Rechtstexte und Bedingungen einpflegen, Produktion einrichten, Umzug von WordPress.
## 5. Schnellreferenz Code
@@ -98,7 +99,7 @@ ## 5. Schnellreferenz Code
| Preise/Angebote | `app/Pricing/*` (PriceCalculator, OfferShowcase, AdvertisedOffer), `app/Availability/*` (AvailabilityChecker, GapFinder) |
| Verwaltung | `app/Filament/**` (Ansichten: `App\Enums\AdminMode`, Trait `FollowsAdminMode`) |
| Webseite | `app/Themes/**`, `resources/themes/ostsee-licht/**`, `config/themes.php` |
| Befehle | `users:create`, `photos:import`, `photos:strip-metadata`, `backup:database`, `themes:make/check/preview`, `channels:sync`, `bookings:expire-holds` |
| Befehle | `users:create`, `users:promote-operator`, `photos:import`, `photos:strip-metadata`, `backup:database`, `themes:make/check/preview`, `channels:sync`, `bookings:expire-holds` |
| Zeitpläne | `routes/console.php` (jede Minute Postfach, alle 5 Min. Fristen/Abgleich, täglich Erinnerungen, Bewertungen, Anonymisierung 03:00, Backup 02:30) |
| Einstellungen | `config/fewo.php` (Frist, Löschfristen, Backup, Mail-Umleitung), `config/content.php` (bearbeitbare Texte) |
+1 -1
View File
@@ -37,5 +37,5 @@
Route::get('/', [PageController::class, 'home'])->name('home');
Route::get('/buchen', [PageController::class, 'show'])->defaults('slug', 'buchen')->name('booking.create');
Route::get('/{slug}', [PageController::class, 'show'])
->where('slug', '(?!admin|livewire|storage|up$)[a-z0-9-]+')
->where('slug', '(?!admin|betreiber|livewire|storage|up$)[a-z0-9-]+')
->name('page');
+3
View File
@@ -8,6 +8,7 @@
use App\Models\Property;
use App\Models\Season;
use App\Models\SpecialOffer;
use App\Models\Tenant;
use App\Pricing\AdvertisedOffer;
use App\Pricing\OfferShowcase;
use Carbon\CarbonImmutable;
@@ -105,7 +106,9 @@ public function test_gap_below_minimum_stay_is_not_advertised_unless_the_offer_w
public function test_offers_section_shows_the_advertised_offers_on_the_website(): void
{
$this->travelTo($this->now);
$unusedLandlord = $this->property->tenant_id;
$this->property->delete();
Tenant::query()->whereKey($unusedLandlord)->delete();
$this->seed([PropertySeeder::class, SiteSeeder::class]);
SpecialOffer::factory()->for(Property::query()->sole())->create(['name' => 'Ab 3 Nächten −10 %', 'min_nights' => 3, 'discount_value' => 10]);
+1 -1
View File
@@ -67,7 +67,7 @@ public function test_request_creates_a_held_reservation_and_sends_quote_and_noti
$this->assertSame(BookingStatus::Reserved, $booking->status);
$this->assertSame('2026-10-24 10:00', $booking->hold_expires_at->format('Y-m-d H:i'));
$this->assertSame(3 * 6500 + 10800, $booking->total);
$this->assertSame('2026-'.str_pad((string) $booking->id, 4, '0', STR_PAD_LEFT), $booking->reference);
$this->assertSame('2026-0001', $booking->reference);
$this->assertSame('anna@example.com', $booking->guest->email);
Mail::assertSent(ReservationReceived::class, fn (ReservationReceived $mail): bool => $mail->hasTo('anna@example.com'));
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->hasTo(config('fewo.notification_email')));
+209
View File
@@ -0,0 +1,209 @@
<?php
namespace Tests\Feature;
use App\Enums\UserRole;
use App\Filament\Operator\Tenants\Pages\ListTenants;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Users\Pages\CreateUser;
use App\Filament\Resources\Users\Pages\ListUsers;
use App\Filament\Resources\Users\UserResource;
use App\Models\Booking;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Filament\Actions\Testing\TestAction;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Livewire\Livewire;
use Tests\TestCase;
class TenantAccessTest extends TestCase
{
use RefreshDatabase;
public function test_a_member_cannot_open_another_landlords_booking(): void
{
[$ours, $theirs] = $this->twoLandlords();
$admin = $this->memberOf($ours);
$foreign = Booking::factory()->for(Property::factory()->create(['tenant_id' => $theirs->id]))->create();
$this->actingAs($admin);
$this->get(BookingResource::getUrl('view', ['record' => $foreign]))->assertNotFound();
$this->get(BookingResource::getUrl('index'))->assertOk()->assertDontSee($foreign->reference);
}
public function test_a_landlord_admin_sees_only_their_own_members(): void
{
[$ours, $theirs] = $this->twoLandlords();
$admin = $this->memberOf($ours);
$foreign = $this->memberOf($theirs, 'fremd@example.com');
$this->actingAs($admin);
$this->get(UserResource::getUrl('index'))
->assertOk()
->assertSee($admin->email)
->assertDontSee($foreign->email);
}
public function test_an_existing_account_can_be_added_without_changing_its_password(): void
{
[$ours, $theirs] = $this->twoLandlords();
$admin = $this->memberOf($ours);
$shared = $this->memberOf($theirs, 'geteilt@example.com');
$shared->forceFill(['password' => Hash::make('altes-passwort-123')])->saveQuietly();
$this->actingAs($admin);
app(TenantContext::class)->set($ours);
Livewire::test(CreateUser::class)
->fillForm([
'name' => 'Geteilt',
'email' => 'geteilt@example.com',
'role' => UserRole::Content->value,
'password' => 'neues-passwort-123',
])
->call('create')
->assertHasNoFormErrors();
$shared->refresh();
$this->assertTrue(Hash::check('altes-passwort-123', $shared->password));
$this->assertSame(UserRole::Content, $shared->roleOn($ours->id));
$this->assertSame(UserRole::Admin, $shared->roleOn($theirs->id));
$this->assertSame(1, User::query()->where('email', 'geteilt@example.com')->count());
}
public function test_password_and_two_factor_of_a_shared_account_stay_with_the_operator(): void
{
[$ours, $theirs] = $this->twoLandlords();
$admin = $this->memberOf($ours);
$shared = $this->memberOf($ours, 'geteilt@example.com');
$shared->tenants()->attach($theirs->id, ['role' => UserRole::Rentals->value]);
$operator = $this->memberOf($ours, 'betrieb@example.com');
$operator->forceFill(['is_operator' => true])->saveQuietly();
$this->assertFalse($admin->mayResetCredentials($shared));
$this->assertTrue($operator->mayResetCredentials($shared));
$this->assertFalse($shared->fresh()->is_operator);
$shared->update(['is_operator' => true]);
$this->assertFalse($shared->fresh()->is_operator);
$this->actingAs($admin);
Livewire::test(ListUsers::class)
->assertActionHidden(TestAction::make('resetTwoFactor')->table($shared));
$this->assertNotNull($shared->fresh()->getAppAuthenticationSecret());
$this->actingAs($operator);
Livewire::test(ListUsers::class)
->callAction(TestAction::make('resetTwoFactor')->table($shared));
$this->assertNull($shared->fresh()->getAppAuthenticationSecret());
}
public function test_the_membership_role_counts_inside_that_landlord(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$user = User::factory()->create();
$user->tenants()->updateExistingPivot($tenant->id, ['role' => UserRole::Rentals->value]);
$user->forceFill(['role' => UserRole::Admin])->saveQuietly();
app(TenantContext::class)->set($tenant);
$this->assertTrue($user->hasRole(UserRole::Rentals));
$this->assertFalse($user->hasRole(UserRole::Admin));
}
public function test_a_suspended_landlord_is_closed_except_for_the_operator(): void
{
$tenant = Tenant::factory()->create(['is_active' => false]);
Site::factory()->create([
'tenant_id' => $tenant->id,
'domain' => 'localhost',
'is_default' => true,
]);
app(TenantContext::class)->set($tenant);
$admin = User::factory()->create();
$this->get('/')->assertNotFound();
$this->actingAs($admin)->get('/admin')->assertNotFound();
$admin->forceFill(['is_operator' => true])->saveQuietly();
$this->actingAs($admin)->get('/admin')->assertOk();
}
public function test_only_the_operator_opens_the_operator_panel_and_the_visit_is_recorded(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$admin = User::factory()->create();
$this->actingAs($admin)->get('/betreiber')->assertForbidden();
$admin->forceFill(['is_operator' => true])->saveQuietly();
$this->actingAs($admin)->get('/betreiber')->assertOk()->assertSee('Mandanten');
Livewire::test(ListTenants::class)
->callAction(TestAction::make('openAdmin')->table($tenant));
$this->assertDatabaseHas('tenant_access_logs', [
'tenant_id' => $tenant->id,
'user_id' => $admin->id,
]);
}
public function test_promote_operator_keeps_the_membership(): void
{
$tenant = Tenant::factory()->create();
app(TenantContext::class)->set($tenant);
$user = User::factory()->role(UserRole::Rentals)->create();
$this->artisan('users:promote-operator', ['email' => $user->email])->assertSuccessful();
$user->refresh();
$this->assertTrue($user->is_operator);
$this->assertSame(UserRole::Rentals, $user->roleOn($tenant->id));
$this->assertNull($user->otherTenantAdminUrl());
}
/**
* @return array{0: Tenant, 1: Tenant}
*/
private function twoLandlords(): array
{
$ours = Tenant::factory()->create();
$theirs = Tenant::factory()->create();
Site::factory()->create([
'tenant_id' => $ours->id,
'domain' => 'localhost',
'is_default' => false,
]);
Site::factory()->create([
'tenant_id' => $theirs->id,
'domain' => 'andere.test',
'is_default' => false,
]);
return [$ours, $theirs];
}
private function memberOf(Tenant $tenant, ?string $email = null): User
{
app(TenantContext::class)->set($tenant);
return User::factory()->create(array_filter([
'email' => $email,
]));
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace Tests\Feature;
use App\Actions\CreateReservation;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\Property;
use App\Models\Tenant;
use App\Pricing\StayRequest;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
class TenantIsolationTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
Mail::fake();
}
public function test_the_same_email_address_is_a_separate_guest_for_each_landlord(): void
{
$this->seed(PropertySeeder::class);
$stommer = Tenant::query()->where('slug', 'stommer')->firstOrFail();
$other = Tenant::factory()->create();
$foreign = Guest::factory()->create([
'tenant_id' => $other->id,
'email' => 'anna@example.com',
'first_name' => 'Bert',
]);
$booking = app(CreateReservation::class)->handle(
Property::withoutGlobalScope('tenant')->where('tenant_id', $stommer->id)->firstOrFail(),
new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2),
['first_name' => 'Anna', 'last_name' => 'Muster', 'email' => 'anna@example.com'],
);
$this->assertNotSame($foreign->id, $booking->guest_id);
$this->assertSame('Anna', $booking->guest->first_name);
$this->assertSame($stommer->id, $booking->guest->tenant_id);
app(TenantContext::class)->set($stommer);
$this->assertSame(1, Guest::query()->where('email', 'anna@example.com')->count());
app(TenantContext::class)->set($other);
$this->assertSame('Bert', Guest::query()->where('email', 'anna@example.com')->firstOrFail()->first_name);
}
public function test_booking_numbers_continue_per_landlord_and_start_again_for_the_next_one(): void
{
$firstLandlord = Tenant::factory()->create();
$secondLandlord = Tenant::factory()->create();
$firstProperty = Property::factory()->create(['tenant_id' => $firstLandlord->id]);
$existing = Booking::factory()->for($firstProperty)->create();
$existing->forceFill(['reference' => '2026-0042'])->saveQuietly();
$next = Booking::factory()->for($firstProperty)->create();
$other = Booking::factory()->for(Property::factory()->create(['tenant_id' => $secondLandlord->id]))->create();
$this->assertSame('2026-0043', $next->reference);
$this->assertSame('2026-0001', $other->reference);
$this->assertSame($firstLandlord->id, $next->tenant_id);
$this->assertSame($secondLandlord->id, $other->tenant_id);
}
public function test_a_query_fails_when_a_landlord_is_required_and_none_is_current(): void
{
$context = app(TenantContext::class);
$context->forget();
$context->requirePresence();
$this->expectException(TenantContextMissing::class);
Guest::query()->count();
}
public function test_the_seeded_apartment_belongs_to_stommer(): void
{
$this->seed(PropertySeeder::class);
$property = Property::withoutGlobalScope('tenant')->sole();
$this->assertSame('stommer', $property->tenant->slug);
$this->assertSame($property->tenant_id, $property->seasons()->withoutGlobalScope('tenant')->firstOrFail()->tenant_id);
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace Tests\Feature;
use App\Actions\SendOffer;
use App\Models\Booking;
use App\Models\Page;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class WebsiteTenancyTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->withoutVite();
}
public function test_one_landlord_still_answers_on_any_address(): void
{
$site = $this->website('Einzige Wohnung');
$this->get('http://fremd.test/')->assertOk()->assertSee('Einzige Wohnung');
$this->assertSame($site->id, Site::query()->where('is_default', true)->value('id'));
}
public function test_a_second_landlord_is_reached_only_on_their_own_address(): void
{
$this->website('Nordhaus', 'nordhaus.test');
$this->website('Südheim', 'suedheim.test');
$this->get('http://nordhaus.test/')->assertOk()->assertSee('Nordhaus')->assertDontSee('Südheim');
$this->get('http://suedheim.test/')->assertOk()->assertSee('Südheim')->assertDontSee('Nordhaus');
$this->get('http://unbekannt.test/')->assertNotFound();
}
public function test_the_offer_link_uses_the_website_address(): void
{
$site = $this->website('Nordhaus', 'nordhaus.test');
$property = Property::factory()->create(['site_id' => $site->id]);
$booking = Booking::factory()->for($property)->create([
'hold_expires_at' => now()->addDay(),
'offer_version' => 1,
]);
$url = app(SendOffer::class)->offerUrl($booking);
$this->assertStringStartsWith('https://nordhaus.test/angebot/', $url);
$this->assertStringContainsString('signature=', $url);
}
private function website(string $name, ?string $domain = null): Site
{
$tenant = Tenant::factory()->create();
$site = Site::factory()->create([
'tenant_id' => $tenant->id,
'name' => $name,
'domain' => $domain,
'is_default' => $domain === null,
]);
Page::factory()->create([
'site_id' => $site->id,
'slug' => Page::HOME,
'title' => $name,
'sections' => [],
]);
return $site;
}
}