285 lines
9.2 KiB
PHP
285 lines
9.2 KiB
PHP
<?php
|
||
|
||
namespace App\Tenancy;
|
||
|
||
use App\Models\Booking;
|
||
use App\Models\Photo;
|
||
use App\Models\Site;
|
||
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 Illuminate\Support\Facades\Storage;
|
||
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(),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* Include media metadata, original files, conversions and every retained document version.
|
||
*/
|
||
private function addFiles(ZipArchive $zip, Tenant $tenant): void
|
||
{
|
||
$mediaItems = $this->mediaOf($tenant);
|
||
$zip->addFromString('daten/media.json', (string) $mediaItems->toJson(JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
|
||
|
||
foreach ($mediaItems as $media) {
|
||
$path = $media->getPath();
|
||
|
||
if (is_string($path) && File::exists($path)) {
|
||
$directory = dirname($path);
|
||
foreach (File::allFiles($directory) as $file) {
|
||
$relative = str_replace('\\', '/', substr($file->getPathname(), strlen($directory) + 1));
|
||
$zip->addFile($file->getPathname(), 'dateien/'.$media->id.'-'.$relative);
|
||
}
|
||
}
|
||
}
|
||
|
||
foreach ($this->documentPaths($tenant) as $path) {
|
||
$zip->addFile(Storage::disk('local')->path($path), 'dateien/local/'.$path);
|
||
}
|
||
}
|
||
|
||
private function deleteFiles(Tenant $tenant): void
|
||
{
|
||
$documents = $this->documentPaths($tenant);
|
||
|
||
foreach ($this->mediaOf($tenant) as $media) {
|
||
$media->delete(); // removes the stored file as well
|
||
}
|
||
|
||
Storage::disk('local')->delete($documents);
|
||
}
|
||
|
||
/**
|
||
* @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)
|
||
->concat(Site::query()->with('media')->get()->flatMap(fn (Site $site) => $site->media)),
|
||
);
|
||
}
|
||
|
||
/**
|
||
* New documents have a tenant directory, including earlier offer versions. Existing installations
|
||
* also have flat paths: accept only those explicitly referenced by this tenant and never a shared file.
|
||
*
|
||
* @return list<string>
|
||
*/
|
||
private function documentPaths(Tenant $tenant): array
|
||
{
|
||
$disk = Storage::disk('local');
|
||
$paths = $disk->allFiles('contracts/tenants/'.$tenant->id);
|
||
$bookings = Booking::withoutGlobalScope('tenant')->where('tenant_id', $tenant->id)->get(['contract_path', 'offer_path']);
|
||
|
||
foreach ($bookings as $booking) {
|
||
foreach ([$booking->contract_path, $booking->offer_path] as $path) {
|
||
if (! is_string($path) || ! preg_match('~\Acontracts/[^/\\\\]+\.pdf\z~', $path) || ! $disk->exists($path)) {
|
||
continue;
|
||
}
|
||
|
||
$shared = Booking::withoutGlobalScope('tenant')->where('tenant_id', '!=', $tenant->id)
|
||
->where(fn ($query) => $query->where('contract_path', $path)->orWhere('offer_path', $path))->exists();
|
||
|
||
if ($shared) {
|
||
throw new RuntimeException('Vertragsdatei ist mehreren Mandanten zugeordnet: '.$path);
|
||
}
|
||
|
||
$paths[] = $path;
|
||
}
|
||
}
|
||
|
||
return array_values(array_unique($paths));
|
||
}
|
||
|
||
private function hasTenantColumn(string $table): bool
|
||
{
|
||
static $known = [];
|
||
|
||
return $known[$table] ??= Schema::hasTable($table)
|
||
&& Schema::hasColumn($table, 'tenant_id');
|
||
}
|
||
}
|