Files
fewo-stommer/app/Tenancy/TenantArchive.php
T
Lars StommerandClaude Opus 5 c55937d20e 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>
2026-10-24 11:15:55 +02:00

235 lines
7.1 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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');
}
}