Files
fewo-stommer/tests/Feature/PortalMailTest.php
Lars 783068501c
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m33s
Generische iCal-Kanäle mit Bestandsklärung und sicheren Exporten bereitstellen
2026-10-27 17:14:45 +01:00

215 lines
9.8 KiB
PHP
Raw Permalink 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\MonitorChannels;
use App\Actions\ProcessPortalMail;
use App\Actions\SyncChannel;
use App\Channels\Mail\PortalMail;
use App\Channels\Mail\PortalMailParser;
use App\Enums\BookingStatus;
use App\Enums\ChannelTaskAction;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
use App\Mail\ChannelConflict;
use App\Mail\MailboxAlert;
use App\Mail\PortalMailNotification;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
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;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;
class PortalMailTest extends TestCase
{
use RefreshDatabase;
private const BOOKING_MAIL = <<<'TXT'
Hallo Brigitte,
gute Nachrichten! Sie haben eine neue Buchung erhalten.
Gast: Max Mustermann
Anreise: Sa., 7. Nov. 2026
Abreise: Di., 10. Nov. 2026
Reisende: 2 Erwachsene
Buchungsnummer: HA-7X3K9Q
Ihr FeWo-direkt Team
TXT;
private Property $property;
private Channel $fewo;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
$this->seed(PropertySeeder::class);
$this->property = Property::sole();
$this->fewo = Channel::factory()->for($this->property)->create([
'name' => 'FeWo-direkt',
'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/x.ics', 'email_senders' => 'fewo-direkt.de, vrbo.com'],
]);
Mail::fake();
}
/**
* @return array<string, array{string, string, PortalEmailType, ?string, ?string, ?string}>
*/
public static function mailProvider(): array
{
return [
'deutsche Buchung' => ['Neue Buchung: Ferienwohnung Stommer', self::BOOKING_MAIL, PortalEmailType::Booking, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'],
'englische Buchung' => ['Booking confirmed – Instant Booking', "Check-in: Nov 7, 2026\nCheck-out: Nov 10, 2026\nReservation ID: HA-ABCDE1", PortalEmailType::Booking, '2026-11-07', '2026-11-10', 'HA-ABCDE1'],
'numerische Daten' => ['Buchungsbestätigung', 'Ihr Gast reist vom 07.11.2026 bis zum 10.11.2026 an.', PortalEmailType::Booking, '2026-11-07', '2026-11-10', null],
'Anfrage ist keine Buchung' => ['Neue Buchungsanfrage von Max', self::BOOKING_MAIL, PortalEmailType::Inquiry, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'],
'Stornierung' => ['Buchung storniert: HA-7X3K9Q', 'Die Buchung vom 07.11.2026 bis 10.11.2026 wurde storniert.', PortalEmailType::Cancellation, '2026-11-07', '2026-11-10', 'HA-7X3K9Q'],
'unbekannt' => ['Ihr monatlicher Bericht', 'Statistik für Oktober 2026', PortalEmailType::Unknown, null, null, null],
];
}
#[DataProvider('mailProvider')]
public function test_parser_recognises_portal_mails(string $subject, string $text, PortalEmailType $type, ?string $arrival, ?string $departure, ?string $reference): void
{
$parsed = (new PortalMailParser)->parse($subject, $text);
$this->assertSame([$type, $arrival, $departure, $reference], [$parsed->type, $parsed->startsOn?->toDateString(), $parsed->endsOn?->toDateString(), $parsed->reference]);
}
public function test_booking_mail_blocks_immediately_and_informs_other_manual_portals(): void
{
$ostseeklar = Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true]);
$record = $this->process('Neue Buchung', self::BOOKING_MAIL);
$this->assertSame(PortalEmailStatus::Blocked, $record->status);
$block = $this->fewo->blockedPeriods()->sole();
$this->assertSame(['email', '2026-11-07', '2026-11-10', 'email:HA-7X3K9Q'], [$block->source, $block->starts_on->toDateString(), $block->ends_on->toDateString(), $block->external_uid]);
$this->assertSame(ChannelTaskAction::Block, $ostseeklar->tasks()->sole()->action);
Mail::assertSent(PortalMailNotification::class);
$this->assertNull($this->process('Neue Buchung', self::BOOKING_MAIL), 'same message is processed only once');
$this->assertSame(PortalEmailStatus::AlreadyKnown, $this->process('Neue Buchung', self::BOOKING_MAIL, 'other-id')->status);
$this->assertNull($this->process('Neue Buchung', self::BOOKING_MAIL, 'x', 'news@unbekannt.de'));
}
public function test_overlap_with_an_existing_booking_raises_a_conflict(): void
{
Booking::factory()->for($this->property)->create(['arrival' => '2026-11-09', 'departure' => '2026-11-12', 'status' => BookingStatus::Confirmed]);
$this->process('Neue Buchung', self::BOOKING_MAIL);
Mail::assertSent(ChannelConflict::class);
}
public function test_calendar_without_shared_identity_keeps_the_mail_block_for_review(): void
{
Channel::factory()->for($this->property)->create(['name' => 'Ostseeklar', 'requires_manual_blocking' => true]);
$this->process('Neue Buchung', self::BOOKING_MAIL);
$tasksBefore = ChannelTask::count();
$this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261110");
(new SyncChannel)->handle($this->fewo);
$this->assertSame(2, $this->fewo->blockedPeriods()->count());
$this->assertSame(2, $this->fewo->blockedPeriods()->where('needs_review', true)->count());
$this->assertSame($tasksBefore, ChannelTask::count());
}
public function test_calendar_entry_with_overlapping_dates_does_not_replace_an_unidentified_mail_block(): void
{
$this->process('Neue Buchung', self::BOOKING_MAIL);
$this->fakeFeed("UID:vrbo-123\r\nDTSTART;VALUE=DATE:20261107\r\nDTEND;VALUE=DATE:20261111");
(new SyncChannel)->handle($this->fewo);
$this->assertSame(2, $this->fewo->blockedPeriods()->count());
$this->assertSame(1, $this->fewo->blockedPeriods()->where('source', 'email')->count());
$this->assertSame('2026-11-11', $this->fewo->blockedPeriods()->where('source', 'channel')->sole()->ends_on->toDateString());
}
public function test_mail_blocks_survive_a_calendar_sync_that_does_not_know_them_yet(): void
{
$this->process('Neue Buchung', self::BOOKING_MAIL);
$this->fakeFeed('');
(new SyncChannel)->handle($this->fewo);
$this->assertSame(1, $this->fewo->blockedPeriods()->count());
}
public function test_cancellation_releases_the_mail_block(): void
{
$this->process('Neue Buchung', self::BOOKING_MAIL);
$record = $this->process('Buchung storniert: HA-7X3K9Q', 'Die Buchung wurde storniert.', 'cancel-1');
$this->assertSame(PortalEmailStatus::Released, $record->status);
$this->assertSame(0, $this->fewo->blockedPeriods()->count());
}
public function test_booking_without_readable_dates_needs_review_and_can_be_blocked_in_the_admin(): void
{
$record = $this->process('Neue Buchung', 'Details finden Sie in Ihrem Vermieterkonto.');
$this->assertSame(PortalEmailStatus::NeedsReview, $record->status);
$this->assertSame(0, $this->fewo->blockedPeriods()->count());
Mail::assertSent(PortalMailNotification::class);
$this->actingAs(User::factory()->create());
Livewire::test(ListPortalEmails::class)
->assertCanSeeTableRecords([$record])
->callTableAction('block', $record, ['starts_on' => '2026-11-20', 'ends_on' => '2026-11-23']);
$this->assertSame(PortalEmailStatus::Blocked, $record->fresh()->status);
$this->assertSame('2026-11-20', $this->fewo->blockedPeriods()->sole()->starts_on->toDateString());
}
public function test_n8n_can_push_mails_with_a_signed_request(): void
{
config(['fewo.automation.secret' => 'geheim']);
$body = json_encode(['message_id' => 'n8n-1', 'from' => 'noreply@fewo-direkt.de', 'subject' => 'Neue Buchung', 'text' => self::BOOKING_MAIL]);
$this->call('POST', route('channels.portal-mail'), [], [], [], ['HTTP_X-Signature' => 'falsch', 'CONTENT_TYPE' => 'application/json'], $body)->assertForbidden();
$this->call('POST', route('channels.portal-mail'), [], [], [], ['HTTP_X-Signature' => hash_hmac('sha256', $body, 'geheim'), 'CONTENT_TYPE' => 'application/json'], $body)
->assertOk()
->assertJson(['processed' => true, 'type' => 'booking', 'status' => 'blocked']);
$this->assertSame(1, PortalEmail::count());
}
public function test_mailbox_outage_is_alerted_once(): void
{
// 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']]);
$this->assertSame(1, (new MonitorChannels)->handle());
$this->assertSame(0, (new MonitorChannels)->handle());
Mail::assertSent(MailboxAlert::class, 1);
}
private function process(string $subject, string $text, string $messageId = 'msg-1', string $from = 'noreply@fewo-direkt.de'): ?PortalEmail
{
return app(ProcessPortalMail::class)->handle(new PortalMail($messageId, $from, $subject, $text, CarbonImmutable::now()));
}
private function fakeFeed(string $event): void
{
$body = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic Test//EN\r\n".($event !== '' ? "BEGIN:VEVENT\r\nDTSTAMP:20261022T080000Z\r\n{$event}\r\nEND:VEVENT\r\n" : '').'END:VCALENDAR';
Http::fake(['*' => Http::response($body)]);
}
}