Files
fewo-stommer/tests/Feature/TenantScheduleTest.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

172 lines
6.7 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 Tests\Feature;
use App\Actions\ExpireReservations;
use App\Channels\Mail\MailboxReader;
use App\Mail\ReservationExpired;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Site;
use App\Models\Tenant;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantRunner;
use Carbon\CarbonImmutable;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;
/**
* Phase 4: everything running in the background belongs to one landlord. Without a landlord the scheduler
* sees no landlord at all – queries stop filtering and mail falls back to the server's sender, which would
* send one landlord's reminders under another one's address.
*/
class TenantScheduleTest extends TestCase
{
use RefreshDatabase;
protected function setUp(): void
{
parent::setUp();
$this->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 <nord@example.com>');
[$b, $bookingB] = $this->landlordWithExpiredHold('Südheim', 'sued@example.com', 'Absender Süd <sued@example.com>');
$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,
]));
}
}