Files
fewo-stommer/tests/Feature/Process/VisualProcessConfiguratorTest.php

262 lines
16 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\Process;
use App\Actions\ConfigureChannelProcess;
use App\Actions\TakeOverExternalBooking;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Filament\Resources\Channels\Pages\ChannelProcess;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\User;
use App\Process\ProcessBlocks;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use App\Process\ProcessSettings;
use App\Support\Content;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* The visual configurator: business blocks derived from the resolved plan, configuration inside the block, drafts that
* stay drafts, one authoritative process definition for new cases.
*/
#[Group('configurator')]
class VisualProcessConfiguratorTest extends TestCase
{
use RefreshDatabase;
private Property $property;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 18:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Storage::fake('local');
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
config(['mail.default' => 'array']);
Mail::swap(new MailManager($this->app));
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'test@example.org']);
Http::preventStrayRequests();
$this->actingAs(User::factory()->create());
}
/** Test A: own website – answer and reservation changed in the blocks, overview follows, draft is tested, then saved */
public function test_a_website_request_is_configured_in_the_blocks_and_the_overview_follows(): void
{
$website = Channel::websiteOf($this->property);
$page = Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()])
->call('chooseModel', 'inquiry.request')
->call('selectBlock', 'answer')
->assertSee('Verbindliches Angebot')
->call('chooseTemplate', 'inquiry_answer', 'inquiry.binding_offer');
$blocks = $page->instance()->blocks();
$this->assertSame('Verbindliches Angebot', $blocks['answer']['template']::label());
$this->assertTrue($page->instance()->dirty(), 'a changed draft is shown as unsaved');
$this->assertNull($website->fresh()->process_overrides['inquiry']['model'] ?? null, 'nothing is saved by choosing');
// The offer waits for exactly what it needs; data collection and availability do not wait for it.
$this->assertContains('Eingang und Gastdaten', array_column($blocks['answer']['waits_for'], 'label'));
$this->assertContains('Verfügbarkeit und Reservierung', array_column($blocks['answer']['waits_for'], 'label'));
$this->assertTrue($blocks['intake']['independent']);
$this->assertTrue($blocks['availability']['independent']);
$this->assertSame([], $blocks['availability']['waits_for']);
$reserving = collect($blocks['availability']['facts'])->firstWhere('key', 'pre_reservation');
$this->assertSame('ja', mb_strtolower(substr($reserving['value'], 0, 2)), 'the offer suggests holding the dates at the request');
$page->call('selectBlock', 'availability')->set('drafts.inquiry.settings.pre_reservation', '0')->set('drafts.inquiry.settings.data_request_mode', 'manual');
$blocks = $page->instance()->blocks();
$this->assertContains('Reservierung des Zeitraums', array_column($blocks['availability']['off'], 'label'), 'the hold step drops out of the overview at once');
$this->assertSame('hier gesetzt', collect($blocks['availability']['facts'])->firstWhere('key', 'pre_reservation')['source']);
$this->assertStringContainsString('selbst nach', mb_strtolower(collect($blocks['intake']['facts'])->firstWhere('key', 'data_request_mode')['value']), 'the data request mode is shown in its block');
// The tester gets the very same unsaved draft.
$page->call('test');
$draft = session('process-tester.draft.'.$website->id.'.inquiry');
$this->assertSame('inquiry.request', $draft['model']);
$this->assertSame('inquiry.binding_offer', $draft['templates']['inquiry_answer']);
$this->assertSame('0', $draft['settings']['pre_reservation']);
$page->call('save')->assertNotified('Ablauf gespeichert');
$saved = $website->fresh()->process_overrides['inquiry'];
$this->assertSame(['inquiry.request', 'inquiry.binding_offer'], [$saved['model'], $saved['templates']['inquiry_answer']]);
$this->assertFalse($saved['pre_reservation']);
$this->assertFalse($page->instance()->dirty(), 'after saving the stored configuration is shown');
}
public function test_selecting_never_saves_and_changes_can_be_discarded(): void
{
$website = Channel::websiteOf($this->property);
$page = Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()])->call('selectBlock', 'availability');
$this->assertFalse($page->instance()->dirty(), 'opening a block changes nothing');
$page->set('drafts.inquiry.settings.hold_hours', '12');
$this->assertTrue($page->instance()->dirty());
$this->assertNull(($website->fresh()->process_overrides['inquiry'] ?? [])['hold_hours'] ?? null);
$page->call('discard');
$this->assertFalse($page->instance()->dirty());
$this->assertArrayNotHasKey('hold_hours', $page->get('drafts')['inquiry']['settings']);
}
/** Test B: Destination Solutions – own collection, external contract documents, own booking notice, waiting for the portal */
public function test_destination_solutions_blocks_templates_modules_and_the_frozen_plan_agree(): void
{
$ds = $this->portal('Destination Solution');
app(ConfigureChannelProcess::class)->handle($ds, IntakeKind::Booking, [
'model' => 'external.booking',
'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.external'],
'settings' => ['await_portal_confirmation' => '1', 'booking_notice' => 'automatic'],
'capabilities' => ['collects_payment' => '0', 'provides_contract_documents' => '1'],
]);
$page = Livewire::test(ChannelProcess::class, ['record' => $ds->fresh()->getRouteKey()])->set('intake', 'booking');
$blocks = $page->instance()->blocks();
$this->assertSame('Eigenes Inkasso', $blocks['finance']['template']::label());
$this->assertSame('Externe Vertragsunterlagen', $blocks['documents']['template']::label());
$this->assertContains('Bestätigung des Portals', array_column($blocks['documents']['waits_for'], 'label'), 'the documents wait for the portal confirmation');
$this->assertTrue($blocks['finance']['independent'], 'collecting the money does not wait for it');
$this->assertTrue($blocks['communication']['independent'], 'neither does the guest communication');
$this->assertContains('Zahlungen des Gastes', array_column($blocks['finance']['fixed'], 'label'));
$this->assertContains('Mehrstufige Mahnungen (rechtliche Ausgestaltung offen)', $blocks['finance']['extensions']);
$this->assertSame('automatic', collect($blocks['documents']['facts'])->firstWhere('key', 'booking_notice') ? 'automatic' : null);
// What the overview shows is what a new case gets.
$booking = $this->takeOver($ds->fresh(), 'DS-1');
$plan = ProcessPlan::of($booking);
$shown = collect($blocks)->flatMap(fn (array $block): array => collect($block['modules'])->where('on', true)->pluck('module')->all())->sort()->values()->all();
$this->assertSame(collect(array_keys($plan->modules))->sort()->values()->all(), $shown);
$this->assertEqualsCanonicalizing(['collection' => 'collection.own@1', 'contract_documents' => 'contract_docs.external@1'], array_intersect_key($plan->templates, ['collection' => 1, 'contract_documents' => 1]));
$this->assertSame('landlord', $booking->process()->payments()->value);
$this->assertSame('portal', $booking->process()->documents()->value);
}
/** Test C: a stored legacy setting contradicts the chosen template – one definition, controlled adoption */
public function test_a_contradicting_legacy_setting_becomes_a_conflict_and_never_a_second_definition(): void
{
$website = Channel::websiteOf($this->property);
$website->update(['process_overrides' => ['inquiry' => ['model' => 'a1.offer', 'pre_reservation' => true]]]);
$page = Livewire::test(ChannelProcess::class, ['record' => $website->fresh()->getRouteKey()])
->call('chooseModel', 'inquiry.request')
->call('chooseTemplate', 'inquiry_answer', 'inquiry.information');
$conflicts = collect($page->instance()->conflicts())->map(fn (array $conflict): string => $conflict['setting']->value)->all();
$this->assertContains('pre_reservation', $conflicts);
$this->assertGreaterThan(0, $page->instance()->blocks()['availability']['attention'], 'the block that is affected is marked');
$page->assertSee('Bisherige Einstellungen widersprechen');
$page->call('save')->assertNotified('Nicht gespeichert');
$this->assertSame('a1.offer', $website->fresh()->process_overrides['inquiry']['model'], 'refused: still exactly the old definition');
$page->set('acknowledge', true)->call('save')->assertNotified('Ablauf gespeichert');
$saved = $website->fresh()->process_overrides['inquiry'];
$this->assertSame('inquiry.request', $saved['model']);
$this->assertArrayNotHasKey('pre_reservation', $saved, 'the stale legacy value is gone, not hidden behind the template');
$plan = ProcessPlan::freeze(app(ProcessSettings::class)->forWebsite($this->property), ProcessPlan::configurationOf($website->fresh(), IntakeKind::Inquiry));
$this->assertSame([ProcessPlan::CONFIGURED, 'inquiry.request', 'inquiry.information@1'], [$plan->source, $plan->model, $plan->templates['inquiry_answer']]);
$this->assertFalse(app(ProcessSettings::class)->forWebsite($this->property)->preReservation());
}
/** Test D: cases of the historical models keep their frozen plan when the channel is reconfigured */
public function test_historical_cases_keep_their_frozen_plan(): void
{
$fewo = $this->portal('FeWo-direkt', 'mixed');
app(ConfigureChannelProcess::class)->handle($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'capabilities' => ['collects_payment' => '1']]);
$old = $this->takeOver($fewo->fresh(), 'FD-ALT');
$frozen = $old->fresh()->profile;
$this->assertSame('a4.portal_booking', ProcessPlan::of($old)->model);
$page = Livewire::test(ChannelProcess::class, ['record' => $fewo->fresh()->getRouteKey()])->set('intake', 'booking')->call('applyPreset', 'a4.portal_booking');
$page->call('save')->assertNotified('Ablauf gespeichert');
$this->assertSame($frozen, $old->fresh()->profile);
$this->assertSame('a4.portal_booking', ProcessPlan::of($old->fresh())->model);
$this->assertSame('external.booking', ProcessPlan::of($this->takeOver($fewo->fresh(), 'FD-NEU', '2027-09-10'))->model);
}
/** Test E: the main view has few blocks, every module sits in exactly one of them, every control is reachable */
public function test_every_module_is_in_a_block_and_every_control_is_reachable_there(): void
{
$catalogue = app(ProcessCatalogue::class);
$grouped = collect(ProcessBlocks::BLOCKS)->flatMap(fn (array $block): array => $block['modules'])->all();
$this->assertSame([], array_values(array_diff(array_keys($catalogue->modules()), $grouped)), 'a new module needs a block');
$this->assertSame($grouped, array_values(array_unique($grouped)), 'no module is in two blocks');
$ds = $this->portal('Destination Solution');
$page = Livewire::test(ChannelProcess::class, ['record' => $ds->getRouteKey()])->set('intake', 'booking')->call('chooseModel', 'external.booking');
$blocks = $page->instance()->blocks();
$this->assertLessThanOrEqual(8, count($blocks), 'a handful of blocks, not 28 modules');
$this->assertNotContains(ProcessBlocks::OTHER, array_keys($blocks));
$reachable = [];
foreach ($blocks as $block) {
foreach ($block['configurable'] as $step) {
foreach ([$step['mode_setting'], $step['performer_setting'], ...array_map(fn (array $parameter) => ProcessSetting::from($parameter['key']), $step['parameters'])] as $setting) {
if ($setting !== null) {
$reachable[$step['module']][$setting->value] = true;
}
}
}
}
// Whatever the configurator can save for a step is offered inside the block of that step.
foreach ($page->instance()->steps() as $step) {
if (! $step['on']) {
continue;
}
$offered = array_filter([$step['mode_setting']?->value, ...(count($step['performer_options']) > 1 ? [$step['performer_setting']?->value] : []), ...array_column($step['parameters'], 'key')]);
foreach ($offered as $setting) {
$this->assertArrayHasKey($setting, $reachable[$step['module']] ?? [], $step['module'].' / '.$setting.' is not reachable in its block');
}
}
}
/** One authoritative definition: the derived legacy model is only an adapter for channels without a chosen model */
public function test_the_derived_legacy_model_is_only_used_where_nothing_is_chosen(): void
{
$users = collect(['app/Process', 'app/Actions', 'app/Filament', 'app/Console'])
->flatMap(fn (string $directory): array => collect(app('files')->allFiles(base_path($directory)))->map(fn ($file) => $file->getPathname())->all())
->filter(fn (string $path): bool => str_contains(file_get_contents($path), 'derivedModel('))
->map(fn (string $path): string => basename($path))->sort()->values()->all();
$this->assertSame(['ChannelProcessConfiguration.php', 'ProcessCatalogue.php', 'ProcessPlan.php'], $users, 'only plan resolution and the configurator show the adapter');
$website = Channel::websiteOf($this->property);
app(ConfigureChannelProcess::class)->handle($website, IntakeKind::Inquiry, ['model' => 'inquiry.request', 'templates' => ['inquiry_answer' => 'inquiry.binding_offer']]);
$profile = app(ProcessSettings::class)->forWebsite($this->property);
$plan = ProcessPlan::freeze($profile, ProcessPlan::configurationOf($website->fresh(), IntakeKind::Inquiry));
$this->assertSame([ProcessPlan::CONFIGURED, 'inquiry.request'], [$plan->source, $plan->model], 'a chosen model is never replaced by the derived one');
}
private function portal(string $name, string $model = 'portal_booking'): Channel
{
return Channel::factory()->for($this->property)->create(['name' => $name, 'booking_model' => $model, 'import_enabled' => false, 'settings' => ['import_url' => 'https://portal.example/'.md5($name).'.ics']]);
}
private function takeOver(Channel $channel, string $reference, string $arrival = '2027-07-10'): Booking
{
$arrival = CarbonImmutable::parse($arrival);
return app(TakeOverExternalBooking::class)->handle($this->property, $channel, $arrival, $arrival->addDays(7), ['portal_reference' => $reference]);
}
}