From c55937d20ed35e1ed39741800f53c32aec2b406b Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Sat, 24 Oct 2026 11:15:55 +0200 Subject: [PATCH 1/2] =?UTF-8?q?Phase=204=20und=205:=20Hintergrundl=C3=A4uf?= =?UTF-8?q?e=20je=20Mandant,=20Export=20und=20K=C3=BCndigung?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit **Phase 4 – was im Hintergrund lief, kannte keinen Mandanten.** `App\Tenancy\TenantRunner` führt jeden Lauf einmal je aktivem Mandanten aus, mit gesetztem Kontext. Ohne ihn sah der Scheduler bei zwei Mandanten gar keinen: Abfragen filterten nicht mehr und der Absender fiel auf die .env zurück – eine Erinnerung des einen Vermieters wäre unter der Adresse des anderen verschickt worden. Seit gestern gibt es zwei Mandanten; nur weil der Cronjob auf Strato noch nicht eingerichtet ist, ist das bisher niemandem passiert. Betroffen: Vormerkungen, Portal-Abgleich, Portal-Postfach, Überwachung, Erinnerungen, Bewertungsbitten, Anonymisierung. Die Datenbank-Sicherung bleibt global – eine Datenbank, ein Dump. Ein Mandant, dessen Lauf scheitert, hält die anderen nicht auf. Das Postfach gehört jetzt dem Mandanten (`mailbox_*`, Passwort verschlüsselt, leerer Server = aus). Es steht im Mandanten-Admin und nur, wenn der Betreiber den Dienst freigeschaltet hat. Auch die Zustands- Schlüssel im Cache tragen den Mandanten – sonst meldeten zwei Mandanten einander ihre letzte erfolgreiche Abholung. **Phase 5 – Kündigung.** `App\Tenancy\TenantArchive` mit zwei Befehlen des Betreibers: `tenants:export ` schreibt alle Zeilen und Dateien in ein Zip, `tenants:delete ` exportiert erst, fragt nach und löscht dann in der Reihenfolge, die die Fremdschlüssel erlauben, Medien eingeschlossen. Konten, die nur zu diesem Mandanten gehörten, gehen mit – ein Konto, das nirgends mehr hineinkommt, ist personenbezogenes Datum ohne Zweck. Wer noch für einen anderen Mandanten arbeitet, und der Betreiber, bleiben. Der Export nennt die Konten mit Rolle, aber ohne Passwort-Hashes und ohne 2FA-Geheimnisse: er wird herausgegeben. Löschen ist bewusst keine Schaltfläche im Panel. `TenantSeparationTest` füllt jeden Bereich aus A1 für zwei Mandanten, exportiert und löscht einen und prüft, dass der andere Zeile für Zeile unverändert ist – auch die Hosts, die über die Website am Mandanten hängen und keine eigene tenant_id haben. Dieser Test merkt künftig, wenn eine neue Tabelle ihre tenant_id vergisst. 262 Feature-Tests grün. Der Export einmal auf echten Daten ausgeführt (2,3 MB mit Fotos); das Löschen nicht, weil es Dateien aus dem echten Speicher entfernt. Co-Authored-By: Claude Opus 5 --- .gitignore | 1 + app/Actions/MonitorChannels.php | 4 +- app/Channels/Mail/MailboxReader.php | 35 ++- app/Console/Commands/DeleteTenant.php | 51 ++++ .../Commands/ExpireReservationHolds.php | 12 +- app/Console/Commands/ExportTenant.php | 40 +++ app/Console/Commands/FetchPortalMail.php | 39 +-- app/Console/Commands/SyncChannels.php | 17 +- app/Filament/Pages/Operations.php | 31 +++ app/Http/Controllers/ChannelController.php | 4 +- app/Models/Tenant.php | 24 ++ app/Policies/TenantPolicy.php | 4 +- app/Tenancy/TenantArchive.php | 234 ++++++++++++++++++ app/Tenancy/TenantDefaults.php | 19 +- app/Tenancy/TenantRunner.php | 57 +++++ ...24_140000_add_mailbox_to_tenants_table.php | 43 ++++ routes/console.php | 16 +- tests/Feature/PortalMailTest.php | 4 +- tests/Feature/TenantScheduleTest.php | 171 +++++++++++++ tests/Feature/TenantSeparationTest.php | 220 ++++++++++++++++ 20 files changed, 986 insertions(+), 40 deletions(-) create mode 100644 app/Console/Commands/DeleteTenant.php create mode 100644 app/Console/Commands/ExportTenant.php create mode 100644 app/Tenancy/TenantArchive.php create mode 100644 app/Tenancy/TenantRunner.php create mode 100644 database/migrations/2026_10_24_140000_add_mailbox_to_tenants_table.php create mode 100644 tests/Feature/TenantScheduleTest.php create mode 100644 tests/Feature/TenantSeparationTest.php diff --git a/.gitignore b/.gitignore index c4f733f..b5ff25e 100644 --- a/.gitignore +++ b/.gitignore @@ -32,3 +32,4 @@ Thumbs.db # Deployment settings with access data /scripts/deploy.*.env !/scripts/deploy.example.env +storage/app/private/exports/ diff --git a/app/Actions/MonitorChannels.php b/app/Actions/MonitorChannels.php index 14ce7bd..6348b02 100644 --- a/app/Actions/MonitorChannels.php +++ b/app/Actions/MonitorChannels.php @@ -38,7 +38,7 @@ public static function mailboxIsStale(): bool return false; } - $lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY); + $lastSuccess = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY)); return $lastSuccess === null || CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes'))); @@ -56,7 +56,7 @@ private function monitorMailbox(): int return 0; } - Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY))); + Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY)))); Cache::forever(self::MAILBOX_ALERTED_KEY, true); return 1; diff --git a/app/Channels/Mail/MailboxReader.php b/app/Channels/Mail/MailboxReader.php index 94b951f..d898415 100644 --- a/app/Channels/Mail/MailboxReader.php +++ b/app/Channels/Mail/MailboxReader.php @@ -3,6 +3,7 @@ namespace App\Channels\Mail; use App\Channels\ChannelSyncException; +use App\Support\Settings; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\Cache; use Throwable; @@ -17,11 +18,31 @@ class MailboxReader { public const LAST_SUCCESS_KEY = 'mailbox:last_success_at'; + /** + * The state of one landlord's mailbox. Without the landlord in the key, two landlords would report + * each other's last success and alerts would be raised for the wrong one. + */ + public static function key(string $base): string + { + return $base.':'.(Settings::tenant()?->id ?? 0); + } + public const LAST_ERROR_KEY = 'mailbox:last_error'; + /** + * The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path + * is off for them. + * + * @return array|null + */ + public static function configuration(): ?array + { + return Settings::tenant()?->mailbox(); + } + public static function isConfigured(): bool { - return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username')); + return self::configuration() !== null; } /** @@ -32,7 +53,11 @@ public static function isConfigured(): bool */ public function fetch(array $senders): array { - $config = config('fewo.mailbox'); + $config = self::configuration(); + + if ($config === null) { + throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.'); + } try { $client = (new ClientManager)->make([ @@ -62,13 +87,13 @@ public function fetch(array $senders): array $client->disconnect(); } catch (Throwable $exception) { - Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage()); + Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage()); throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception); } - Cache::forever(self::LAST_SUCCESS_KEY, now()->toIso8601String()); - Cache::forget(self::LAST_ERROR_KEY); + Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String()); + Cache::forget(self::key(self::LAST_ERROR_KEY)); return $mails; } diff --git a/app/Console/Commands/DeleteTenant.php b/app/Console/Commands/DeleteTenant.php new file mode 100644 index 0000000..6bb5d71 --- /dev/null +++ b/app/Console/Commands/DeleteTenant.php @@ -0,0 +1,51 @@ +where('slug', $this->argument('slug'))->first(); + + if ($tenant === null) { + $this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.'); + + return self::FAILURE; + } + + if (! $this->option('keep-export')) { + $path = $archive->export($tenant, storage_path('app/private/exports')); + $this->info('Export geschrieben: '.$path); + } + + if (! $this->option('force') && ! confirm('Mandant '.$tenant->name.' mit allen Daten und Dateien endgültig löschen?', default: false)) { + $this->line('Abgebrochen.'); + + return self::SUCCESS; + } + + $removed = $archive->delete($tenant); + + foreach ($removed as $table => $count) { + $this->line(sprintf(' %-22s %d', $table, $count)); + } + + $this->info('Mandant '.$tenant->name.' gelöscht.'); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ExpireReservationHolds.php b/app/Console/Commands/ExpireReservationHolds.php index 26dd1ba..66652a2 100644 --- a/app/Console/Commands/ExpireReservationHolds.php +++ b/app/Console/Commands/ExpireReservationHolds.php @@ -3,22 +3,26 @@ namespace App\Console\Commands; use App\Actions\ExpireReservations; +use App\Models\Tenant; +use App\Tenancy\TenantRunner; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; #[Signature('bookings:expire-holds')] -#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord')] +#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord – once per landlord')] class ExpireReservationHolds extends Command { /** * Execute the console command. */ - public function handle(ExpireReservations $expireReservations): int + public function handle(ExpireReservations $expireReservations, TenantRunner $runner): int { - $count = $expireReservations->handle(); + $runner->each(function (Tenant $tenant) use ($expireReservations): void { + $count = $expireReservations->handle(); - $this->info("{$count} Vormerkung(en) abgelaufen."); + $this->info("{$tenant->name}: {$count} Vormerkung(en) abgelaufen."); + }); return self::SUCCESS; } diff --git a/app/Console/Commands/ExportTenant.php b/app/Console/Commands/ExportTenant.php new file mode 100644 index 0000000..0357462 --- /dev/null +++ b/app/Console/Commands/ExportTenant.php @@ -0,0 +1,40 @@ +where('slug', $this->argument('slug'))->first(); + + if ($tenant === null) { + $this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.'); + + return self::FAILURE; + } + + $path = $archive->export($tenant, (string) ($this->option('to') ?: storage_path('app/private/exports'))); + + $this->info('Export von '.$tenant->name.': '.$path.' ('.$this->size($path).')'); + + return self::SUCCESS; + } + + private function size(string $path): string + { + $bytes = (int) (filesize($path) ?: 0); + + return $bytes > 1048576 + ? round($bytes / 1048576, 1).' MB' + : round($bytes / 1024).' KB'; + } +} diff --git a/app/Console/Commands/FetchPortalMail.php b/app/Console/Commands/FetchPortalMail.php index 221b3bb..26b3137 100644 --- a/app/Console/Commands/FetchPortalMail.php +++ b/app/Console/Commands/FetchPortalMail.php @@ -7,53 +7,64 @@ use App\Channels\Mail\MailboxReader; use App\Enums\TenantServiceKey; use App\Models\Channel; +use App\Models\Tenant; use App\Tenancy\TenantFeatures; +use App\Tenancy\TenantRunner; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; #[Signature('channels:fetch-mail')] -#[Description('Read booking notifications of the portals from the mailbox and block recognised bookings immediately')] +#[Description('Read booking notifications of the portals from each landlord\'s mailbox and block recognised bookings immediately')] class FetchPortalMail extends Command { /** - * Execute the console command. + * Execute the console command. Every landlord has their own mailbox, so every landlord gets their own + * run – one landlord's credentials are never used to read another one's mail. */ - public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int + public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail, TenantRunner $runner): int { - if (! MailboxReader::isConfigured()) { - $this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).'); + $runner->each(fn (Tenant $tenant) => $this->fetchForCurrentLandlord($reader, $processPortalMail, $tenant)); - return self::SUCCESS; + return self::SUCCESS; + } + + private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMail $processPortalMail, Tenant $tenant): void + { + if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $tenant)) { + return; + } + + if (! MailboxReader::isConfigured()) { + $this->line("{$tenant->name}: kein Postfach hinterlegt."); + + return; } $senders = Channel::query()->active()->get() - ->filter(fn (Channel $channel): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) ->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel)) ->unique() ->values() ->all(); if ($senders === []) { - $this->line('Für kein Portal sind Absender hinterlegt.'); + $this->line("{$tenant->name}: für kein Portal sind Absender hinterlegt."); - return self::SUCCESS; + return; } try { $mails = $reader->fetch($senders); } catch (ChannelSyncException $exception) { - $this->error($exception->getMessage()); + $this->error("{$tenant->name}: {$exception->getMessage()}"); - return self::FAILURE; + return; } foreach ($mails as $mail) { if ($record = $processPortalMail->handle($mail)) { - $this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})"); + $this->info("{$tenant->name} – {$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})"); } } - - return self::SUCCESS; } } diff --git a/app/Console/Commands/SyncChannels.php b/app/Console/Commands/SyncChannels.php index f3f15a5..777c71c 100644 --- a/app/Console/Commands/SyncChannels.php +++ b/app/Console/Commands/SyncChannels.php @@ -4,18 +4,27 @@ use App\Actions\SyncChannel; use App\Models\Channel; +use App\Tenancy\TenantRunner; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; #[Signature('channels:sync {channel? : ID of a single channel}')] -#[Description('Import the occupations of all active portals (or one) and report conflicts')] +#[Description('Import the occupations of all active portals (or one) and report conflicts – once per landlord')] class SyncChannels extends Command { /** - * Execute the console command. + * Execute the console command. Runs per landlord so that conflict mails carry the right sender and + * reach the right people. */ - public function handle(SyncChannel $syncChannel): int + public function handle(SyncChannel $syncChannel, TenantRunner $runner): int + { + $runner->each(fn () => $this->syncCurrentLandlord($syncChannel)); + + return self::SUCCESS; + } + + private function syncCurrentLandlord(SyncChannel $syncChannel): void { $channels = Channel::query()->active() ->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id)) @@ -29,7 +38,5 @@ public function handle(SyncChannel $syncChannel): int ? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}") : $this->error("✗ {$channel->name}: {$log->message}"); } - - return self::SUCCESS; } } diff --git a/app/Filament/Pages/Operations.php b/app/Filament/Pages/Operations.php index da3273c..a69ca5d 100644 --- a/app/Filament/Pages/Operations.php +++ b/app/Filament/Pages/Operations.php @@ -2,14 +2,17 @@ namespace App\Filament\Pages; +use App\Enums\TenantServiceKey; use App\Enums\UserRole; use App\Filament\Concerns\FollowsAdminMode; use App\Models\Tenant; use App\Support\Settings; use App\Tenancy\TenantConfig; +use App\Tenancy\TenantFeatures; use BackedEnum; use Filament\Actions\Action; use Filament\Forms\Components\Radio; +use Filament\Forms\Components\Select; use Filament\Forms\Components\TagsInput; use Filament\Forms\Components\TextInput; use Filament\Notifications\Notification; @@ -90,6 +93,12 @@ public function mount(): void 'bank_iban' => $tenant->bank_iban, 'bank_bic' => $tenant->bank_bic, 'tax_note' => $tenant->tax_note, + 'mailbox_host' => $tenant->mailbox_host, + 'mailbox_port' => $tenant->mailbox_port, + 'mailbox_username' => $tenant->mailbox_username, + 'mailbox_password' => $tenant->mailbox_password, + 'mailbox_encryption' => $tenant->mailbox_encryption, + 'mailbox_folder' => $tenant->mailbox_folder, ...$this->periodValues($tenant), ]); } @@ -172,6 +181,22 @@ public function form(Schema $schema): Schema ->maxLength(255) ->columnSpanFull(), ]), + Section::make('Portal-Postfach') + ->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.') + ->columns(2) + ->collapsed() + ->visible(fn (): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail)) + ->schema([ + TextInput::make('mailbox_host')->label('IMAP-Server')->maxLength(190), + TextInput::make('mailbox_port')->label('Port')->numeric()->integer()->placeholder('993'), + TextInput::make('mailbox_username')->label('Benutzer')->maxLength(190), + TextInput::make('mailbox_password')->label('Passwort')->password()->revealable()->autocomplete(false)->maxLength(190), + Select::make('mailbox_encryption') + ->label('Verschlüsselung') + ->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS']) + ->placeholder('SSL'), + TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190), + ]), Section::make('Fristen und Grenzen') ->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.') ->columns(3) @@ -212,6 +237,12 @@ public function save(): void 'bank_iban' => $data['bank_iban'] ?? null, 'bank_bic' => $data['bank_bic'] ?? null, 'tax_note' => $data['tax_note'] ?? null, + 'mailbox_host' => $data['mailbox_host'] ?? null, + 'mailbox_port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null, + 'mailbox_username' => $data['mailbox_username'] ?? null, + 'mailbox_password' => $data['mailbox_password'] ?? null, + 'mailbox_encryption' => $data['mailbox_encryption'] ?? null, + 'mailbox_folder' => $data['mailbox_folder'] ?? null, ...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)), ]); diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php index c0ebca1..5632b24 100644 --- a/app/Http/Controllers/ChannelController.php +++ b/app/Http/Controllers/ChannelController.php @@ -51,8 +51,8 @@ public function health(Request $request): JsonResponse $mailbox = [ 'configured' => MailboxReader::isConfigured(), 'ok' => ! MonitorChannels::mailboxIsStale(), - 'last_success_at' => Cache::get(MailboxReader::LAST_SUCCESS_KEY), - 'last_error' => Cache::get(MailboxReader::LAST_ERROR_KEY), + 'last_success_at' => Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY)), + 'last_error' => Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY)), ]; $ok = $channels->every(fn (array $channel): bool => $channel['ok']) && $mailbox['ok']; diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index 052d430..c0ccac5 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -21,6 +21,7 @@ 'sender_name', 'sender_email', 'bank_account_holder', 'bank_iban', 'bank_bic', 'bank_name', 'tax_note', 'operating_mode', 'test_recipient', 'suspended_message', + 'mailbox_host', 'mailbox_port', 'mailbox_encryption', 'mailbox_username', 'mailbox_password', 'mailbox_folder', 'deposit_due_days', 'review_request_after_days', 'guest_retention_years', 'retention_inquiry_months', 'retention_portal_email_excerpt_days', 'retention_attribution_months', 'spam_min_seconds', 'spam_per_ip_per_hour', 'spam_per_email_per_day', 'spam_open_requests_per_email', 'spam_max_links', @@ -54,6 +55,7 @@ protected function casts(): array 'bank_bic' => 'encrypted', 'bank_name' => 'encrypted', 'tax_note' => 'encrypted', + 'mailbox_password' => 'encrypted', ]; } @@ -89,6 +91,28 @@ public function serviceUsages(): HasMany return $this->hasMany(ServiceUsage::class); } + /** + * The mailbox this landlord reads portal notifications from, or null when they have none. An empty + * host means the fast path is simply off for them. + * + * @return array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string}|null + */ + public function mailbox(): ?array + { + if (blank($this->mailbox_host) || blank($this->mailbox_username)) { + return null; + } + + return [ + 'host' => (string) $this->mailbox_host, + 'port' => (int) ($this->mailbox_port ?: 993), + 'encryption' => (string) ($this->mailbox_encryption ?: 'ssl'), + 'username' => (string) $this->mailbox_username, + 'password' => $this->mailbox_password, + 'folder' => (string) ($this->mailbox_folder ?: 'INBOX'), + ]; + } + public function isLive(): bool { return $this->operating_mode === 'live'; diff --git a/app/Policies/TenantPolicy.php b/app/Policies/TenantPolicy.php index 9a00192..2471b20 100644 --- a/app/Policies/TenantPolicy.php +++ b/app/Policies/TenantPolicy.php @@ -6,7 +6,9 @@ use App\Models\User; /** - * Landlords are created and suspended by the operator. Deleting one is a later, separate step. + * Landlords are created and suspended by the operator. Deleting one is deliberately not an action in the + * panel: it removes data and files for good. It happens through `php artisan tenants:delete `, which + * writes an export first and asks before it acts. */ class TenantPolicy { diff --git a/app/Tenancy/TenantArchive.php b/app/Tenancy/TenantArchive.php new file mode 100644 index 0000000..36e42cf --- /dev/null +++ b/app/Tenancy/TenantArchive.php @@ -0,0 +1,234 @@ + + */ + private const DELETE_ORDER = [ + 'floor_plans', + 'channel_sync_logs', + 'channel_tasks', + 'portal_emails', + 'payments', + 'reviews', + 'blocked_periods', + 'bookings', + 'special_offers', + 'extras', + 'seasons', + 'amenities', + 'photos', + 'appearances', + 'pages', + 'notices', + 'faqs', + 'content_blocks', + 'guests', + 'channels', + 'properties', + 'site_domains', + 'sites', + 'tenant_services', + 'service_usages', + 'tenant_access_logs', + 'tenant_user', + ]; + + /** + * Writes every row and every uploaded file of this landlord into one zip file. + * + * @return string the path of the written archive + */ + public function export(Tenant $tenant, string $directory): string + { + File::ensureDirectoryExists($directory); + + $path = rtrim($directory, '/\\').DIRECTORY_SEPARATOR.'mandant-'.$tenant->slug.'-'.now()->format('Ymd-His').'.zip'; + $zip = new ZipArchive; + + if ($zip->open($path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { + throw new RuntimeException('Archiv konnte nicht angelegt werden: '.$path); + } + + $zip->addFromString('mandant.json', (string) json_encode($tenant->toArray(), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + foreach ($this->tables() as $table) { + $rows = $this->rowsOf($table, $tenant); + + $zip->addFromString( + 'daten/'.$table.'.json', + (string) json_encode($rows, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + ); + } + + $zip->addFromString( + 'daten/benutzer.json', + (string) json_encode($this->usersOf($tenant), JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), + ); + + $this->addFiles($zip, $tenant); + + $zip->close(); + + return $path; + } + + /** + * Who worked for this landlord, with their role. Deliberately without password hashes and without the + * two-factor secrets: the export is handed out, and those would be worth stealing. + * + * @return list + */ + public function usersOf(Tenant $tenant): array + { + return User::query() + ->whereHas('tenants', fn ($query) => $query->where('tenants.id', $tenant->id)) + ->withCount('tenants') + ->get() + ->map(fn (User $user): array => [ + 'id' => $user->id, + 'name' => $user->name, + 'email' => $user->email, + 'role' => $user->roleOn($tenant->id)?->value, + 'weitere_mandanten' => max(0, $user->tenants_count - 1), + ]) + ->all(); + } + + /** + * Removes the landlord and everything that belongs to them, files included. The landlord row goes last. + * + * @return array how many rows were removed per table + */ + public function delete(Tenant $tenant): array + { + $this->deleteFiles($tenant); + + $orphans = $this->accountsLosingTheirLastLandlord($tenant); + $removed = []; + + DB::transaction(function () use ($tenant, $orphans, &$removed): void { + foreach (self::DELETE_ORDER as $table) { + if (! $this->hasTenantColumn($table)) { + continue; + } + + $count = DB::table($table)->where('tenant_id', $tenant->id)->delete(); + + if ($count > 0) { + $removed[$table] = $count; + } + } + + if ($orphans !== []) { + $removed['users'] = User::query()->whereKey($orphans)->delete(); + } + + $tenant->delete(); + }); + + return $removed; + } + + /** + * Accounts that belonged to this landlord only. They are removed with them – an account that can reach + * nothing is personal data without a purpose. An operator keeps their account, and so does anybody who + * still works for another landlord. + * + * @return list + */ + private function accountsLosingTheirLastLandlord(Tenant $tenant): array + { + return User::query() + ->where('is_operator', false) + ->whereHas('tenants', fn ($query) => $query->where('tenants.id', $tenant->id)) + ->withCount('tenants') + ->get() + ->filter(fn (User $user): bool => $user->tenants_count === 1) + ->pluck('id') + ->all(); + } + + /** + * Tables carrying a tenant_id, in a stable order. + * + * @return list + */ + public function tables(): array + { + return array_values(array_filter(self::DELETE_ORDER, fn (string $table): bool => $this->hasTenantColumn($table))); + } + + /** + * @return list> + */ + private function rowsOf(string $table, Tenant $tenant): array + { + return array_map( + fn (object $row): array => (array) $row, + DB::table($table)->where('tenant_id', $tenant->id)->get()->all(), + ); + } + + /** + * Photos keep their files through Spatie's media library; they hang off the photo, not off the landlord, + * so they are collected through the photos of this landlord. + */ + private function addFiles(ZipArchive $zip, Tenant $tenant): void + { + foreach ($this->mediaOf($tenant) as $media) { + $path = $media->getPath(); + + if (is_string($path) && File::exists($path)) { + $zip->addFile($path, 'dateien/'.$media->id.'-'.$media->file_name); + } + } + } + + private function deleteFiles(Tenant $tenant): void + { + foreach ($this->mediaOf($tenant) as $media) { + $media->delete(); // removes the stored file as well + } + } + + /** + * @return Collection + */ + private function mediaOf(Tenant $tenant): Collection + { + return app(TenantContext::class)->run( + $tenant, + fn () => Photo::query()->with('media')->get()->flatMap(fn (Photo $photo) => $photo->media), + ); + } + + private function hasTenantColumn(string $table): bool + { + static $known = []; + + return $known[$table] ??= Schema::hasTable($table) + && Schema::hasColumn($table, 'tenant_id'); + } +} diff --git a/app/Tenancy/TenantDefaults.php b/app/Tenancy/TenantDefaults.php index bfd682a..1312d17 100644 --- a/app/Tenancy/TenantDefaults.php +++ b/app/Tenancy/TenantDefaults.php @@ -37,6 +37,23 @@ public static function forLegacyLandlord(array $settings = [], bool $encryptBank ]; } + /** + * The mailbox the single-landlord installation used, taken from the .env for a raw database write. + * + * @return array + */ + public static function mailboxFromConfig(): array + { + return [ + 'mailbox_host' => config('fewo.mailbox.host'), + 'mailbox_port' => config('fewo.mailbox.port'), + 'mailbox_encryption' => config('fewo.mailbox.encryption'), + 'mailbox_username' => config('fewo.mailbox.username'), + 'mailbox_password' => self::bank(config('fewo.mailbox.password'), true), + 'mailbox_folder' => config('fewo.mailbox.folder'), + ]; + } + /** * The value of the installation, not the one a landlord may already have laid over the configuration. */ @@ -53,7 +70,7 @@ private static function setting(array $settings, string $key): ?string return filled($settings[$key] ?? null) ? (string) $settings[$key] : null; } - private static function bank(mixed $value, bool $encrypt): ?string + public static function bank(mixed $value, bool $encrypt): ?string { if (blank($value)) { return null; diff --git a/app/Tenancy/TenantRunner.php b/app/Tenancy/TenantRunner.php new file mode 100644 index 0000000..b201218 --- /dev/null +++ b/app/Tenancy/TenantRunner.php @@ -0,0 +1,57 @@ +tenants($onlyActive) as $tenant) { + try { + $context->run($tenant, fn () => $callback($tenant)); + $succeeded++; + } catch (Throwable $exception) { + Log::error('Lauf für Mandant '.$tenant->slug.' fehlgeschlagen: '.$exception->getMessage(), [ + 'tenant_id' => $tenant->id, + 'exception' => $exception, + ]); + } + } + + return $succeeded; + } + + /** + * @return Collection + */ + public function tenants(bool $onlyActive = true): Collection + { + return Tenant::query() + ->when($onlyActive, fn ($query) => $query->where('is_active', true)) + ->orderBy('id') + ->get(); + } +} diff --git a/database/migrations/2026_10_24_140000_add_mailbox_to_tenants_table.php b/database/migrations/2026_10_24_140000_add_mailbox_to_tenants_table.php new file mode 100644 index 0000000..e1f1426 --- /dev/null +++ b/database/migrations/2026_10_24_140000_add_mailbox_to_tenants_table.php @@ -0,0 +1,43 @@ +string('mailbox_host')->nullable(); + $table->unsignedSmallInteger('mailbox_port')->nullable(); + $table->string('mailbox_encryption', 10)->nullable(); + $table->string('mailbox_username')->nullable(); + $table->text('mailbox_password')->nullable(); + $table->string('mailbox_folder')->nullable(); + }); + + // Whatever the single-landlord installation had in its .env belongs to Stommer. + $stommer = DB::table('tenants')->where('slug', 'stommer')->first(); + + if ($stommer !== null && filled(config('fewo.mailbox.host'))) { + DB::table('tenants')->where('id', $stommer->id)->update(TenantDefaults::mailboxFromConfig()); + } + } + + public function down(): void + { + Schema::table('tenants', function (Blueprint $table) { + $table->dropColumn([ + 'mailbox_host', 'mailbox_port', 'mailbox_encryption', + 'mailbox_username', 'mailbox_password', 'mailbox_folder', + ]); + }); + } +}; diff --git a/routes/console.php b/routes/console.php index aac0c34..922b268 100644 --- a/routes/console.php +++ b/routes/console.php @@ -5,39 +5,45 @@ use App\Actions\RemindChannelTasks; use App\Actions\RequestReviews; use App\Actions\SendBookingReminders; +use App\Tenancy\TenantRunner; use Illuminate\Support\Facades\Schedule; +/** + * Everything that acts on a landlord's data runs once per landlord (TenantRunner), so queries see the right + * rows and mail goes out with the right sender. Only the database backup stays global: one database, one dump. + */ Schedule::command('bookings:expire-holds')->everyFiveMinutes()->withoutOverlapping(); Schedule::command('channels:sync')->everyFiveMinutes()->withoutOverlapping(10); Schedule::command('channels:fetch-mail')->everyMinute()->withoutOverlapping(5); -Schedule::call(fn (MonitorChannels $monitorChannels) => $monitorChannels->handle()) +Schedule::call(fn (TenantRunner $runner, MonitorChannels $monitorChannels) => $runner->each(fn () => $monitorChannels->handle())) ->name('channels:monitor') ->everyFifteenMinutes() ->withoutOverlapping(); -Schedule::call(fn (RemindChannelTasks $remindChannelTasks) => $remindChannelTasks->handle()) +Schedule::call(fn (TenantRunner $runner, RemindChannelTasks $remindChannelTasks) => $runner->each(fn () => $remindChannelTasks->handle())) ->name('channels:remind-tasks') ->everyFifteenMinutes() ->withoutOverlapping(); -Schedule::call(fn (SendBookingReminders $sendBookingReminders) => $sendBookingReminders->handle()) +Schedule::call(fn (TenantRunner $runner, SendBookingReminders $sendBookingReminders) => $runner->each(fn () => $sendBookingReminders->handle())) ->name('bookings:reminders') ->dailyAt('09:00') ->withoutOverlapping(); -Schedule::call(fn (RequestReviews $requestReviews) => $requestReviews->handle()) +Schedule::call(fn (TenantRunner $runner, RequestReviews $requestReviews) => $runner->each(fn () => $requestReviews->handle())) ->name('reviews:request') ->dailyAt('10:00') ->withoutOverlapping(); -Schedule::call(fn (AnonymizeGuests $anonymizeGuests) => $anonymizeGuests->handle()) +Schedule::call(fn (TenantRunner $runner, AnonymizeGuests $anonymizeGuests) => $runner->each(fn () => $anonymizeGuests->handle())) ->name('guests:anonymize') ->dailyAt('03:00') ->withoutOverlapping(); +// One database, one dump – across all landlords (see MANDANTEN-PLAN §5). Schedule::command('backup:database') ->name('backup:database') ->dailyAt('02:30') diff --git a/tests/Feature/PortalMailTest.php b/tests/Feature/PortalMailTest.php index b966fc9..41da38c 100644 --- a/tests/Feature/PortalMailTest.php +++ b/tests/Feature/PortalMailTest.php @@ -21,6 +21,7 @@ use App\Models\PortalEmail; use App\Models\Property; use App\Models\User; +use App\Support\Settings; use Carbon\CarbonImmutable; use Database\Seeders\PropertySeeder; use Illuminate\Foundation\Testing\RefreshDatabase; @@ -188,7 +189,8 @@ public function test_n8n_can_push_mails_with_a_signed_request(): void public function test_mailbox_outage_is_alerted_once(): void { - config(['fewo.mailbox.host' => 'imap.strato.de', 'fewo.mailbox.username' => 'fewo@stommer.de']); + // The mailbox belongs to the landlord now, not to the server's .env. + Settings::tenant()?->update(['mailbox_host' => 'imap.strato.de', 'mailbox_username' => 'fewo@stommer.de']); $this->fewo->update(['settings' => ['email_senders' => 'fewo-direkt.de']]); diff --git a/tests/Feature/TenantScheduleTest.php b/tests/Feature/TenantScheduleTest.php new file mode 100644 index 0000000..511b4db --- /dev/null +++ b/tests/Feature/TenantScheduleTest.php @@ -0,0 +1,171 @@ +travelTo(CarbonImmutable::parse('2026-11-01 09:00')); + Mail::fake(); + } + + public function test_the_runner_visits_every_active_landlord_with_that_landlord_current(): void + { + $first = Tenant::factory()->create(['name' => 'Erster']); + $second = Tenant::factory()->create(['name' => 'Zweiter']); + Tenant::factory()->create(['name' => 'Gesperrt', 'is_active' => false]); + + $seen = []; + $succeeded = app(TenantRunner::class)->each(function (Tenant $tenant) use (&$seen): void { + $seen[] = [$tenant->id, app(TenantContext::class)->id()]; + }); + + $this->assertSame(2, $succeeded); + $this->assertSame([[$first->id, $first->id], [$second->id, $second->id]], $seen); + $this->assertNull(app(TenantContext::class)->id(), 'Nach dem Lauf ist kein Mandant mehr gesetzt.'); + } + + public function test_a_failing_landlord_does_not_stop_the_others(): void + { + Tenant::factory()->create(); + Tenant::factory()->create(); + + $visited = 0; + $succeeded = app(TenantRunner::class)->each(function () use (&$visited): void { + $visited++; + + if ($visited === 1) { + throw new \RuntimeException('Postfach nicht erreichbar'); + } + }); + + $this->assertSame(2, $visited); + $this->assertSame(1, $succeeded); + } + + /** + * The test the plan asks for: a run for A must not write to B's guests, nor under B's sender. + */ + public function test_a_run_touches_only_its_own_landlord_and_uses_their_sender(): void + { + [$a, $bookingA] = $this->landlordWithExpiredHold('Nordhaus', 'nord@example.com', 'Absender Nord '); + [$b, $bookingB] = $this->landlordWithExpiredHold('Südheim', 'sued@example.com', 'Absender Süd '); + + $senders = []; + + app(TenantRunner::class)->each(function (Tenant $tenant) use (&$senders): void { + $senders[$tenant->name] = [config('mail.from.address'), config('fewo.owner.name')]; + + app(ExpireReservations::class)->handle(); + }); + + $this->assertSame(['nord@example.com', 'Nordhaus'], $senders['Nordhaus']); + $this->assertSame(['sued@example.com', 'Südheim'], $senders['Südheim']); + + // Each landlord is told about their own expired hold only. + Mail::assertSent(ReservationExpired::class, 2); + Mail::assertSent(ReservationExpired::class, fn (ReservationExpired $mail): bool => $mail->hasTo('nord@example.com')); + Mail::assertSent(ReservationExpired::class, fn (ReservationExpired $mail): bool => $mail->hasTo('sued@example.com')); + + $this->assertSame('expired', $bookingA->fresh()->status->value); + $this->assertSame('expired', $bookingB->fresh()->status->value); + $this->assertNotSame($a->id, $b->id); + } + + public function test_the_mailbox_belongs_to_the_landlord_and_is_unreadable_from_another_one(): void + { + $withBox = Tenant::factory()->create([ + 'mailbox_host' => 'imap.nord.example', + 'mailbox_username' => 'post@nord.example', + 'mailbox_password' => 'geheim', + ]); + $without = Tenant::factory()->create(); + + app(TenantContext::class)->set($withBox); + $this->assertTrue(MailboxReader::isConfigured()); + $this->assertSame('imap.nord.example', MailboxReader::configuration()['host']); + $this->assertSame('geheim', MailboxReader::configuration()['password']); + + app(TenantContext::class)->set($without); + $this->assertFalse(MailboxReader::isConfigured(), 'Ein Mandant ohne Postfach sieht keines – auch nicht das fremde.'); + $this->assertNull(MailboxReader::configuration()); + + // Stored encrypted, like the bank details. + $this->assertNotSame('geheim', DB::table('tenants')->where('id', $withBox->id)->value('mailbox_password')); + } + + public function test_the_ical_token_of_one_landlord_does_not_serve_another_ones_occupancy(): void + { + $nord = $this->websiteFor(Tenant::factory()->create(['name' => 'Nordhaus']), 'nord.test'); + $sued = $this->websiteFor(Tenant::factory()->create(['name' => 'Südheim']), 'sued.test'); + + $channel = app(TenantContext::class)->run($nord->tenant, fn (): Channel => Channel::factory()->create([ + 'property_id' => Property::factory()->create(['site_id' => $nord->id])->id, + ])); + + // On its own address the feed answers … + $this->get('http://nord.test'.route('channels.feed', ['token' => $channel->export_token], absolute: false))->assertOk(); + + // … on the other landlord's address it does not exist. + $this->get('http://sued.test'.route('channels.feed', ['token' => $channel->export_token], absolute: false))->assertNotFound(); + $this->assertNotNull($sued); + } + + /** + * @return array{Tenant, Booking} + */ + private function landlordWithExpiredHold(string $name, string $email, string $sender): array + { + $tenant = Tenant::factory()->create([ + 'name' => $name, + 'owner_name' => $name, + 'notification_emails' => $email, + 'sender_email' => $email, + 'sender_name' => 'Absender '.$name, + 'operating_mode' => 'live', + ]); + + $booking = app(TenantContext::class)->run($tenant, fn (): Booking => Booking::factory() + ->for(Property::factory()->create()) + ->reserved(now()->subHour()) + ->create()); + + return [$tenant, $booking]; + } + + private function websiteFor(Tenant $tenant, string $host): Site + { + return app(TenantContext::class)->run($tenant, fn (): Site => Site::factory()->create([ + 'tenant_id' => $tenant->id, + 'name' => $tenant->name, + 'domain' => $host, + 'is_default' => false, + ])); + } +} diff --git a/tests/Feature/TenantSeparationTest.php b/tests/Feature/TenantSeparationTest.php new file mode 100644 index 0000000..c2d2667 --- /dev/null +++ b/tests/Feature/TenantSeparationTest.php @@ -0,0 +1,220 @@ +landlordWithEverything('Geht'); + $stays = $this->landlordWithEverything('Bleibt'); + + $before = $this->census($stays); + $this->assertNotEmpty(array_filter($before), 'Der Aufbau muss jeden Bereich füllen.'); + + $archive = app(TenantArchive::class); + $directory = storage_path('framework/testing/tenant-export'); + $path = $archive->export($gone, $directory); + + $this->assertFileExists($path); + $this->assertExportHasOnly($path, $gone, $stays); + + $archive->delete($gone); + + $this->assertDatabaseMissing('tenants', ['id' => $gone->id]); + + foreach ($archive->tables() as $table) { + $this->assertSame( + 0, + DB::table($table)->where('tenant_id', $gone->id)->count(), + "In {$table} sind Zeilen des gelöschten Mandanten übrig.", + ); + } + + $this->assertSame($before, $this->census($stays), 'Der verbliebene Mandant hat sich verändert.'); + + // site_domains trägt keine tenant_id; die Hosts hängen über die Website am Mandanten. Bleibt hier + // eine Zeile übrig, zeigt ein Host auf eine gelöschte Website – schlimmstenfalls auf einen fremden. + $this->assertSame(0, DB::table('site_domains')->where('host', 'geht.test')->count(), 'Verwaister Host nach der Löschung.'); + $this->assertSame(1, DB::table('site_domains')->where('host', 'bleibt.test')->count()); + + File::deleteDirectory($directory); + } + + public function test_a_deleted_landlord_frees_their_booking_numbers_without_touching_the_others(): void + { + $gone = $this->landlordWithEverything('Geht'); + $stays = $this->landlordWithEverything('Bleibt'); + + $reference = app(TenantContext::class)->run($stays, fn (): string => Booking::query()->value('reference')); + + app(TenantArchive::class)->delete($gone); + + app(TenantContext::class)->run($stays, function () use ($reference): void { + $this->assertSame($reference, Booking::query()->value('reference')); + $this->assertSame(1, Booking::query()->count()); + }); + } + + public function test_accounts_of_the_deleted_landlord_go_with_them_unless_they_serve_somebody_else(): void + { + $gone = $this->landlordWithEverything('Geht'); + $stays = $this->landlordWithEverything('Bleibt'); + + $onlyTheirs = User::factory()->create(['email' => 'nur-dort@example.com']); + $onlyTheirs->tenants()->sync([$gone->id => ['role' => UserRole::Admin->value]]); + + $shared = User::factory()->create(['email' => 'beide@example.com']); + $shared->tenants()->sync([ + $gone->id => ['role' => UserRole::Rentals->value], + $stays->id => ['role' => UserRole::Rentals->value], + ]); + + $operator = User::factory()->create(['email' => 'betrieb@example.com']); + $operator->tenants()->sync([$gone->id => ['role' => UserRole::Admin->value]]); + $operator->forceFill(['is_operator' => true])->saveQuietly(); + + app(TenantArchive::class)->delete($gone); + + $this->assertDatabaseMissing('users', ['email' => 'nur-dort@example.com']); + $this->assertDatabaseHas('users', ['email' => 'beide@example.com']); + $this->assertDatabaseHas('users', ['email' => 'betrieb@example.com']); + $this->assertSame([$stays->id], $shared->fresh()->tenants()->pluck('tenants.id')->all()); + } + + public function test_the_export_names_the_accounts_but_not_their_passwords(): void + { + $tenant = $this->landlordWithEverything('Geht'); + $user = User::factory()->create(['email' => 'wirt@example.com', 'name' => 'Wirt']); + $user->tenants()->sync([$tenant->id => ['role' => UserRole::Admin->value]]); + + $exported = app(TenantArchive::class)->usersOf($tenant); + + $this->assertSame(['wirt@example.com'], array_column($exported, 'email')); + $this->assertSame('admin', $exported[0]['role']); + $this->assertArrayNotHasKey('password', $exported[0]); + $this->assertStringNotContainsString($user->password, (string) json_encode($exported)); + } + + /** + * The archive of one landlord must not carry a single row of the other. + */ + private function assertExportHasOnly(string $path, Tenant $exported, Tenant $other): void + { + $zip = new ZipArchive; + $this->assertTrue($zip->open($path) === true); + + $seen = 0; + + for ($i = 0; $i < $zip->numFiles; $i++) { + $name = (string) $zip->getNameIndex($i); + + if (! str_starts_with($name, 'daten/')) { + continue; + } + + $rows = json_decode((string) $zip->getFromIndex($i), true); + $this->assertIsArray($rows); + + foreach ($rows as $row) { + $seen++; + $this->assertSame($exported->id, $row['tenant_id'], "Fremde Zeile in {$name}."); + $this->assertNotSame($other->id, $row['tenant_id']); + } + } + + $zip->close(); + + $this->assertGreaterThan(0, $seen, 'Das Archiv enthält keine Daten.'); + } + + /** + * How many rows this landlord has per table – the yardstick for "unchanged". + * + * @return array + */ + private function census(Tenant $tenant): array + { + $counts = []; + + foreach (app(TenantArchive::class)->tables() as $table) { + $counts[$table] = DB::table($table)->where('tenant_id', $tenant->id)->count(); + } + + return $counts; + } + + /** + * One landlord with at least one row in every area of A1. + */ + private function landlordWithEverything(string $name): Tenant + { + $tenant = Tenant::factory()->create(['name' => $name]); + + app(TenantContext::class)->run($tenant, function () use ($name): void { + $site = Site::factory()->create([ + 'name' => $name, + 'domain' => mb_strtolower($name).'.test', + 'is_default' => false, + ]); + $property = Property::factory()->create(['site_id' => $site->id]); + + Page::factory()->create(['site_id' => $site->id, 'slug' => Page::HOME, 'sections' => []]); + Season::factory()->create(['property_id' => $property->id]); + Extra::factory()->create(['property_id' => $property->id]); + Amenity::factory()->create(['property_id' => $property->id]); + SpecialOffer::factory()->create(['property_id' => $property->id]); + Photo::factory()->create(['property_id' => $property->id]); + Faq::factory()->create(); + Notice::factory()->create(); + ContentBlock::query()->create(['key' => 'legal.imprint', 'value' => 'Impressum '.$name]); + + $guest = Guest::factory()->create(); + $booking = Booking::factory()->for($property)->create(['guest_id' => $guest->id]); + Payment::factory()->create(['booking_id' => $booking->id]); + Review::factory()->create(['booking_id' => $booking->id, 'property_id' => $property->id]); + + $channel = Channel::factory()->create(['property_id' => $property->id]); + BlockedPeriod::factory()->create(['property_id' => $property->id, 'channel_id' => $channel->id]); + }); + + return $tenant; + } +} From 9cd39f791f76e37efdd50f5ca053996048d7a03b Mon Sep 17 00:00:00 2001 From: Lars Stommer Date: Sat, 24 Oct 2026 17:15:30 +0200 Subject: [PATCH 2/2] =?UTF-8?q?Doku:=20Phasen=201=20bis=205=20umgesetzt,?= =?UTF-8?q?=20Grundumbau=20der=20Mandantenf=C3=A4higkeit=20fertig?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5 --- docs/MANDANTEN-PLAN.md | 17 ++++++++++------- docs/STATUS.md | 9 ++++++--- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/docs/MANDANTEN-PLAN.md b/docs/MANDANTEN-PLAN.md index 53d01cd..ec2a202 100644 --- a/docs/MANDANTEN-PLAN.md +++ b/docs/MANDANTEN-PLAN.md @@ -1,6 +1,6 @@ # Mandantenfähigkeit – Umbauplan -Stand: 23.10.2026, abends · Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf `main` und auf stommer.info (Release `20261023195835`) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7 +Stand: 24.10.2026 · **Phasen 1 bis 5 sind umgesetzt** – der Grundumbau ist fertig. Phase 6 und 7 warten auf eine eigene Freigabe · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) · Design: [DESIGN-KONZEPT.md](DESIGN-KONZEPT.md) §7 · Übergabe: [STATUS.md](STATUS.md) Abschnitt 7 Kein Portal, kein Marktplatz. Das Produkt bleibt die eigene Website eines Vermieters mit Vermietung. Wenige Mandanten, eine gemeinsame Datenbank, Laravel und Filament bleiben die Basis. Ein Python-Dienst ist nicht Teil dieses Umbaus. @@ -241,22 +241,23 @@ ### Phase 3 – Einstellungen, Texte, Dienste-Grundlage · umgesetzt Tests (`tests/Feature/TenantSettingsTest.php`, `OperationsModeTest.php`): Zwei Mandanten, unterschiedliches Impressum, unterschiedliche Bank, unterschiedliche Betriebsart. Mandant kann die Löschfrist und den Bot-Schutz nicht über die globale Obergrenze heben. Leerer Dienst-Schlüssel ist erlaubt, eigene Schlüssel und Bankdaten liegen verschlüsselt. -### Phase 4 – Domain, Cron, Mail, Postfach +### Phase 4 – Domain, Cron, Mail, Postfach · umgesetzt 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. Am 24.10. ergänzt: mehrere Adressen je Website im Admin, weil „www" ein eigener Host ist und das Feld „Domain" nur einen schrieb. Fremde Hosts werden abgelehnt. - Links mit dem Ursprung der Website. Umgesetzt für Angebot, Annahme, Bewertung und Einwilligung. -- Scheduler-Schleife, Postfach je Mandant, Absender je Versand. Noch nicht. +- Scheduler-Schleife, Postfach je Mandant, Absender je Versand. Umgesetzt am 24.10.: `App\Tenancy\TenantRunner` führt jeden Lauf einmal je aktivem Mandanten aus, mit gesetztem Kontext; ein scheiternder Mandant hält die anderen nicht auf. Die Datenbank-Sicherung bleibt global. Das Postfach liegt als `mailbox_*` am Mandanten (Passwort verschlüsselt, leerer Server = aus), steht im Mandanten-Admin und nur bei freigeschaltetem Dienst. Auch die Cache-Schlüssel der Postfach-Überwachung tragen den Mandanten. 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 +### Phase 5 – Abnahme der Trennung und Kündigung · umgesetzt 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. +- Befehl des Betreibers: `tenants:export ` und `tenants:delete ` (exportiert erst, fragt nach, löscht dann einschließlich Medien). `App\Tenancy\TenantArchive`. Löschen ist bewusst **keine** Schaltfläche im Panel. +- Konten, die nur zu diesem Mandanten gehörten, werden mitgelöscht; wer noch für einen anderen arbeitet, und der Betreiber bleiben. Der Export nennt die Konten mit Rolle, aber ohne Passwort-Hashes und ohne 2FA-Geheimnisse – er wird herausgegeben. +- `tests/Feature/TenantSeparationTest.php` füllt jeden Bereich aus A1 für zwei Mandanten, exportiert und löscht einen und prüft den anderen Zeile für Zeile, auch die Hosts (die über die Website hängen und keine eigene `tenant_id` haben). Der Test merkt künftig, wenn eine neue Tabelle ihre `tenant_id` vergisst. 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. @@ -290,6 +291,8 @@ ## 9. Betrieb und Abgrenzung ## 10. Freigabe -Phase 1, 2 und 3 sowie der Website-Teil von Phase 4 sind auf stommer.info (Release `20261023195835`). Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Die nächste Codesitzung ist der Rest von Phase 4; Übergabe mit den gebauten Bausteinen: [STATUS.md](STATUS.md) Abschnitt 7. Phase 4 und 5 bringen weitere Migrationen. Phase 6 und 7 warten auf eine eigene Freigabe. +**Phasen 1 bis 5 sind umgesetzt.** Der Grundumbau ist damit fertig: Daten, Rollen, Einstellungen, Domains, Hintergrundläufe, Export und Kündigung. Die bisherigen Daten gehören zum Mandanten Stommer, `lars@stommer.com` ist Betreiber. Ausgelieferter Stand und Übergabe: [STATUS.md](STATUS.md) Abschnitt 7. + +Offen und **nicht** Teil dieses Plans: Subscription und Abrechnung (§9 schließt sie aus; `service_usages` liegt als Grundlage bereit) sowie die Frage, ob Strato für die Domain eines Mandanten ein Zertifikat ausstellt – davon hängt ab, ob das Modell „Mandant bringt seine Domain mit" auf diesem Hosting trägt. Phase 6 und 7 warten auf eine eigene Freigabe und einen Eintrag in [ZUSAMMENARBEIT.md](ZUSAMMENARBEIT.md) §6. 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. diff --git a/docs/STATUS.md b/docs/STATUS.md index dea8744..385d49c 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -70,7 +70,7 @@ ## 3. Offen **Technik** - Cronjob auf Strato einrichten (BETRIEB.md §6). - Design-Theme Seebad 0.3 ist auf `main` und auf stommer.info aktiv (Abschnitt 6). -- Mandantenfähigkeit: Phase 1, 2, 3 und der Website-Teil von Phase 4 sind auf stommer.info. **Nächste Codesitzung: Rest von Phase 4.** Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`. +- Mandantenfähigkeit: **Phasen 1 bis 5 sind umgesetzt** – der Grundumbau ist fertig. Stand, Bausteine und Fallen stehen in Abschnitt 7. Plan: `docs/MANDANTEN-PLAN.md`. - Logo in E-Mails und im Vertrags-PDF (`public/brand/logo-600.png` liegt bereit). - Content-Security-Policy: braucht wegen Livewire/Filament Nonces und einen sorgfältigen Test. - Produktion `www.fewo-stommer.de` vorbereiten: @@ -137,7 +137,7 @@ ## 7. Mandanten – Übergabe an die nächste Sitzung Stand: 23.10.2026, abends · Branch `main` · Plan: [MANDANTEN-PLAN.md](MANDANTEN-PLAN.md) · Anforderungen: [MANDANTEN-ANFORDERUNGEN.md](MANDANTEN-ANFORDERUNGEN.md) -**Hier weitermachen: der Rest von Phase 4** (Scheduler-Schleife über die Mandanten, Portal-Postfach je Mandant, Absender je Versand, iCal-Token). Danach Phase 5 (Export und Löschung eines Mandanten). Phase 6 und 7 erst nach eigener Freigabe und einem Eintrag in ZUSAMMENARBEIT.md §6. Neuen Branch von `main` abzweigen. +**Der Grundumbau (Phasen 1–5) ist fertig.** Offen bleiben Phase 6 (Marke und Bildwelt) und Phase 7 (mehrere Wohnungen je Website) – beide erst nach eigener Freigabe und einem Eintrag in ZUSAMMENARBEIT.md §6, weil sie den Vorlagen-Vertrag ändern. Nicht im Plan und offen: Subscription/Abrechnung und die Zertifikatsfrage bei Strato. **Phase 3 ist ausgeliefert** (23.10.2026 abends). Die Migrationen sind auf der MariaDB von stommer.info durch, `settings` ist weg, die Werte stehen am Mandanten Stommer. @@ -194,6 +194,9 @@ ### So ist es gebaut | Betrieb (Phase 3) | Die Seite System › Betrieb schreibt jetzt den Mandanten des Kontextes (`Settings::tenant()`), nicht mehr die Tabelle `settings`. Sie enthält zusätzlich Vermieterdaten, Bank, Steuerangabe und die Fristen. Bank, Steuerangabe und Dienst-Schlüssel liegen über das `encrypted`-Cast verschlüsselt (`APP_KEY`). | | Dienste (Phase 3) | `tenant_services` (Mandant, Schlüssel aus `App\Enums\TenantServiceKey`, an/aus, eigener API-Schlüssel) wird nur im Betreiber-Bereich am Mandanten-Formular geschaltet. `service_usages` steht bereit; es zählt noch nichts, weil kein Dienst aufruft. | | `settings` | Entfernt. Modell `App\Models\Setting` gelöscht, `Settings::get/save` gibt es nicht mehr. | +| Läufe je Mandant (24.10.) | `App\Tenancy\TenantRunner` führt jeden Hintergrundlauf einmal je aktivem Mandanten aus, mit gesetztem Kontext (`routes/console.php` und die Befehle `bookings:expire-holds`, `channels:sync`, `channels:fetch-mail`). Ohne ihn sah der Scheduler bei zwei Mandanten **keinen** – Abfragen filterten nicht und der Absender fiel auf die `.env` zurück. Ein scheiternder Mandant hält die anderen nicht auf (Log-Eintrag). Die Datenbank-Sicherung bleibt global. | +| Postfach (24.10.) | Gehört dem Mandanten (`mailbox_*`, Passwort verschlüsselt, leerer Server = aus). Im Mandanten-Admin, sichtbar nur bei freigeschaltetem Dienst `portal_mail`. Die Cache-Schlüssel der Überwachung tragen den Mandanten. | +| Kündigung (24.10.) | `php artisan tenants:export ` schreibt Zeilen und Dateien in ein Zip; `tenants:delete ` exportiert erst, fragt nach und löscht dann einschließlich Medien. **Löschen ist bewusst keine Schaltfläche im Panel.** Konten, die nur zu diesem Mandanten gehörten, gehen mit; wer noch woanders arbeitet, und der Betreiber bleiben. Der Export nennt Konten mit Rolle, ohne Passwort-Hashes und ohne 2FA-Geheimnisse. Exporte liegen in `storage/app/private/exports` (nicht im Web, nicht in Git). | | Dienste (24.10.) | `App\Tenancy\TenantFeatures` ist die einzige Stelle, die beantwortet, ob ein Mandant einen Dienst hat. Abgefragt in `RolePolicy::allows()` (damit in **jeder** Richtlinie des Admins), in `Channel::importsOccupations()`, im öffentlichen iCal-Feed und im Postfach-Schnellweg. Keine Rolle wiegt einen gesperrten Dienst auf. `TenantServiceKey::isWired()` trennt Gebautes von Geplantem: nur verdrahtete Dienste sind schaltbar, die drei KI-Dienste stehen als Hinweis. Eigene API-Schlüssel gehören später in den Admin des Mandanten, nicht zum Betreiber. | | Einsprungsadressen (24.10.) | Gehören dem **Betreiber**: Mandanten-Formular › Einsprungsadressen, je Website eine Liste von Adressen. Die erste ist die Hauptadresse und steht in Gästelinks. Beim Anlegen entstehen Website, Host-Einträge und eine leere Startseite – ohne Startseite antwortet die Website 404. Im Mandanten-Admin sind die Adressen nur sichtbar. Eine fremde Adresse wird abgelehnt. Die Domain beim Hoster auf das Verzeichnis zu legen bleibt ein Schritt von Hand, auch bei Domains, die dem Mandanten gehören. | | Links (24.10.) | `URL::forceRootUrl(APP_URL)` zwang **alle** Links auf einen festen Host – mit einem Mandanten unsichtbar, mit zwei Domains hätte jeder interne Link der zweiten Website auf die erste gezeigt. `ResolveTheme` setzt den Ursprung jetzt auf die **Hauptadresse der aufgelösten Website**. Wer über eine Nebenadresse kommt (`www`), bekommt trotzdem Links auf die Hauptadresse – ein kanonischer Host. | @@ -201,7 +204,7 @@ ### So ist es gebaut | Systemweite Einstellungen (24.10.) | Betreiber › Einstellungen, gespeichert in `system_settings`: Löschfristen, Bot-Schutz, Flutgrenze, Sicherungen, Portal-Fristen, Versandweg, SMTP, harte Mail-Umleitung, Tokens. **Leer = der Wert der `.env` gilt wieder**, und zwar sofort. Geheimnisse liegen verschlüsselt. Datenbank-Zugang und `APP_KEY` sind nicht dabei und können es nicht sein: sie werden gebraucht, um die Datenbank zu öffnen und das Gespeicherte zu entschlüsseln. Betreiber › System bleibt die Übersicht (Mandanten, geltende Werte, Zugriffsprotokoll). | | Noch global | Postfach, Absender des Scheduler-Laufs und der Scheduler selbst kennen keinen Mandanten (Rest von Phase 4). Der Cronjob auf Strato ist weiterhin nicht eingerichtet, der Versandweg ist `log`. Das ist mit einem Mandanten der bisherige Betrieb. Ein Mandant ohne eigene Adressen fällt für die Testumleitung auf `FEWO_NOTIFICATION_EMAIL` zurück, damit nichts versehentlich an echte Gäste geht. | -Tests dazu: `tests/Feature/TenantIsolationTest.php`, `TenantAccessTest.php`, `WebsiteTenancyTest.php`, `TenantSettingsTest.php`, `OperationsModeTest.php`. Zuletzt 235 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`. +Tests dazu: `TenantIsolationTest`, `TenantAccessTest`, `WebsiteTenancyTest`, `TenantSettingsTest`, `OperationsModeTest`, `TenantServiceGateTest`, `TenantProvisioningTest`, `SystemSettingsTest`, `TenantScheduleTest` und `TenantSeparationTest` (alle in `tests/Feature`). Zuletzt 262 Feature-Tests grün. PHP auf diesem Rechner: `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.NTS.8.4_*\php.exe`, nicht im PATH der Git-Bash. Für `scripts/deploy.sh` von hier `COMPOSER_BIN` auf `php …/composer/composer.phar` setzen, sonst findet die Bash kein `composer`. ### Offen, aber nicht in derselben Sitzung nötig gewesen