Phase 4 und 5: Hintergrundläufe je Mandant, Export und Kündigung
**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 <slug>` schreibt alle Zeilen und Dateien in ein Zip, `tenants:delete <slug>` 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 <noreply@anthropic.com>
This commit is contained in:
1 parent
c2cf632ad5
commit
c55937d20e
20 files changed
+986
-40
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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<string, mixed>|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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
use function Laravel\Prompts\confirm;
|
||||
|
||||
#[Signature('tenants:delete {slug : Kurzname des Mandanten} {--keep-export : Nicht vorher exportieren} {--force : Ohne Rückfrage}')]
|
||||
#[Description('Export a landlord and then remove them with all their data and files')]
|
||||
class DeleteTenant extends Command
|
||||
{
|
||||
/**
|
||||
* Exports first, unless told otherwise: a deletion that cannot be undone should leave something behind.
|
||||
*/
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('tenants:export {slug : Kurzname des Mandanten} {--to= : Zielordner, sonst storage/app/private/exports}')]
|
||||
#[Description('Write all data and files of one landlord into a zip archive')]
|
||||
class ExportTenant extends Command
|
||||
{
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->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';
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
]);
|
||||
|
||||
|
||||
@@ -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'];
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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 <slug>`, which
|
||||
* writes an export first and asks before it acts.
|
||||
*/
|
||||
class TenantPolicy
|
||||
{
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tenancy;
|
||||
|
||||
use App\Models\Photo;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\File;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use RuntimeException;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use ZipArchive;
|
||||
|
||||
/**
|
||||
* Hands a landlord their data back and removes them (A25). Everything of one landlord is reachable by
|
||||
* `tenant_id`, so neither is a join across eight levels – it is a list of tables.
|
||||
*/
|
||||
class TenantArchive
|
||||
{
|
||||
/**
|
||||
* Child rows first, so foreign keys allow the delete. The reverse order is the one in which the rows
|
||||
* were assigned when tenancy was introduced.
|
||||
*
|
||||
* @var list<string>
|
||||
*/
|
||||
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<array{id: int, name: string, email: string, role: ?string, weitere_mandanten: int}>
|
||||
*/
|
||||
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<string, int> 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<int>
|
||||
*/
|
||||
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<string>
|
||||
*/
|
||||
public function tables(): array
|
||||
{
|
||||
return array_values(array_filter(self::DELETE_ORDER, fn (string $table): bool => $this->hasTenantColumn($table)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array<string, mixed>>
|
||||
*/
|
||||
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<int, Media>
|
||||
*/
|
||||
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');
|
||||
}
|
||||
}
|
||||
@@ -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<string, mixed>
|
||||
*/
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
namespace App\Tenancy;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use Closure;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Runs background work once per landlord, with that landlord current. Everything the scheduler does –
|
||||
* expiring holds, importing portals, writing reminders – acts on one landlord's data and sends mail with
|
||||
* one landlord's sender, so it has to be told which one.
|
||||
*
|
||||
* Without this, a run with several landlords sees no landlord at all: queries fall back to unfiltered and
|
||||
* mail falls back to the .env sender, which would send one landlord's reminders with another one's address.
|
||||
*
|
||||
* A landlord whose run fails does not stop the others – the next one still gets its turn.
|
||||
*/
|
||||
class TenantRunner
|
||||
{
|
||||
/**
|
||||
* @param Closure(Tenant): void $callback
|
||||
* @return int how many landlords ran without an error
|
||||
*/
|
||||
public function each(Closure $callback, bool $onlyActive = true): int
|
||||
{
|
||||
$context = app(TenantContext::class);
|
||||
$succeeded = 0;
|
||||
|
||||
foreach ($this->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<int, Tenant>
|
||||
*/
|
||||
public function tenants(bool $onlyActive = true): Collection
|
||||
{
|
||||
return Tenant::query()
|
||||
->when($onlyActive, fn ($query) => $query->where('is_active', true))
|
||||
->orderBy('id')
|
||||
->get();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user