Files
fewo-stommer/tests/Feature/Process/TemplateCompositionTest.php
LarsandClaude Sonnet 5.5 221ce8ca81 Anfrage-Basisprozess inquiry.request mit Schablonen für Antwort und Gastkommunikation
Antwortart (Auskunft/Angebot) und Reservierung sind entkoppelt (neue Einstellung inquiry_answer;
pre_reservation bleibt die Reservierungsstrategie). Anlass-bezogene Absender für Anreise-Information
und Bewertungsbitte; Schablonen liefern Standardwerte unterhalb aller einstellbaren Ebenen.
A1/A2 bleiben Voreinstellungen und Altfassungen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:40:22 +01:00

541 lines
22 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\SendBookingReminders;
use App\Actions\TakeOverExternalBooking;
use App\Enums\ActivityState;
use App\Enums\CaseType;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Process\CaseActivities;
use App\Process\ChannelProcessConfiguration;
use App\Process\Models\ExternalBookingModel;
use App\Process\Models\ProcessModel;
use App\Process\Models\Responsibilities;
use App\Process\Models\Step;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use App\Process\ProcessProfile;
use App\Process\Templates\FunctionTemplate;
use App\Process\Templates\OwnCollection;
use App\Process\Templates\TemplateArea;
use App\Process\Templates\TemplateComposer;
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 Illuminate\Validation\ValidationException;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Composition of function templates on the base process of externally binding bookings (docs/Prozessarchitektur/
* SCHABLONEN.md): the four combinations of collection and contract documentation, equivalence with the archetypes
* A3–A5, refusal of invalid combinations and versioning.
*/
#[Group('configurator')]
class TemplateCompositionTest 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();
}
/**
* @return array<string, array{0: string, 1: string, 2: CaseType, 3: bool}> collection, documents, classification, whether the payout check is part of the course
*/
public static function combinations(): array
{
return [
'own collection + own documents (A3)' => ['collection.own', 'contract_docs.own', CaseType::A3, false],
'portal collection + own documents (A4)' => ['collection.portal', 'contract_docs.own', CaseType::A4, true],
'portal collection + external documents (A5)' => ['collection.portal', 'contract_docs.external', CaseType::A5, true],
'own collection + external documents (no archetype)' => ['collection.own', 'contract_docs.external', CaseType::A3, false],
];
}
public function test_the_catalogue_with_templates_is_consistent(): void
{
$this->assertSame([], app(ProcessCatalogue::class)->problems());
}
#[DataProvider('combinations')]
public function test_every_combination_is_composed_into_a_valid_versioned_plan(string $collection, string $documents, CaseType $type, bool $payout): void
{
$model = app(ProcessCatalogue::class)->model('external.booking');
$chosen = ['collection' => $collection, 'contract_documents' => $documents];
$this->assertSame([], app(TemplateComposer::class)->problems($model, $chosen));
$channel = $this->configured($chosen);
$booking = $this->takeOver($channel, 'COMBO');
$plan = ProcessPlan::of($booking);
$this->assertSame(['external.booking', 1], [$plan->model, $plan->modelVersion]);
$this->assertEquals(['collection' => $collection.'@1', 'contract_documents' => $documents.'@1', 'guest_communication' => 'guest_comm.own@1'], $plan->templates);
$this->assertSame($payout, array_key_exists('portal.payout', $plan->modules));
$this->assertArrayHasKey('payments.monitor', $plan->modules);
$this->assertArrayHasKey('documents.send', $plan->modules);
$this->assertSame($type, $booking->case_type, 'the case type is only a classification');
$this->assertNull($plan->notice);
}
public function test_the_fourth_combination_collects_ourselves_while_the_portal_provides_the_documents(): void
{
$booking = $this->takeOver($this->configured(['collection' => 'collection.own', 'contract_documents' => 'contract_docs.external']), 'VIER');
$profile = $booking->process();
$this->assertSame([Responsibility::Landlord, Responsibility::Portal], [$profile->payments(), $profile->documents()]);
$this->assertSame(ProcessProfile::TEMPLATE, $profile->source(ProcessSetting::Payments));
$this->assertSame(ProcessProfile::TEMPLATE, $profile->source(ProcessSetting::Documents));
$activities = collect(CaseActivities::for($booking))->keyBy('key');
$this->assertNotSame(ActivityState::External, $activities['payment']->state, 'we monitor the guest payments ourselves');
$this->assertStringNotContainsString('Portal', $activities['payment']->label, 'no portal collection shown');
$this->assertNull($activities['payout'] ?? null, 'no payout check without portal collection');
$this->assertNull($booking->fresh()->confirmation_sent_at, 'the portal provides the contract documents: we send none');
}
#[DataProvider('archetypes')]
public function test_a_combination_behaves_like_the_archetype_it_reproduces(string $legacy, string $collection, string $documents): void
{
$old = $this->takeOver($this->legacyChannel($legacy), 'ALT', '2027-07-10');
$new = $this->takeOver($this->configured(['collection' => $collection, 'contract_documents' => $documents]), 'NEU', '2027-08-10');
$oldValues = $old->process()->values;
$newValues = $new->process()->values;
unset($oldValues['contract_template_id'], $newValues['contract_template_id']);
$this->assertEquals($oldValues, $newValues, 'identical effective configuration');
$this->assertSame($old->case_type, $new->case_type);
$summarise = fn (Booking $booking): array => collect(CaseActivities::for($booking))->map(fn ($activity): array => [$activity->key, $activity->label, $activity->state->value])->all();
$this->assertSame($summarise($old), $summarise($new), 'identical activities and states');
$oldModules = array_keys(ProcessPlan::of($old)->modules);
$newModules = array_keys(ProcessPlan::of($new)->modules);
$this->assertSame(array_values(array_diff($oldModules, $legacy === 'a3.portal_booking' ? ['portal.payout'] : [])), $newModules, 'the course is the archetype course (the payout check only where the portal collects)');
}
/**
* @return array<string, array{0: string, 1: string, 2: string}>
*/
public static function archetypes(): array
{
return [
'A3' => ['a3.portal_booking', 'collection.own', 'contract_docs.own'],
'A4' => ['a4.portal_booking', 'collection.portal', 'contract_docs.own'],
'A5' => ['a5.portal_booking', 'collection.portal', 'contract_docs.external'],
];
}
#[DataProvider('combinations')]
public function test_payment_requests_arise_from_own_collection_only_and_never_twice(string $collection, string $documents, CaseType $type, bool $payout): void
{
$channel = $this->configured(['collection' => $collection, 'contract_documents' => $documents]);
$booking = app(TakeOverExternalBooking::class)->handle($this->property, $channel, CarbonImmutable::parse('2027-07-10'), CarbonImmutable::parse('2027-07-17'), [
'portal_reference' => 'ZAHL', 'portal_total' => 98000, 'guests' => 2,
'guest' => ['first_name' => 'Pia', 'last_name' => 'Portal', 'email' => 'pia@example.org', 'street' => 'Weg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'],
]);
$this->travelTo(CarbonImmutable::parse('2027-06-25 10:00'));
app(SendBookingReminders::class)->handle();
$first = BookingTask::query()->where('booking_id', $booking->id)->count();
app(SendBookingReminders::class)->handle();
$second = BookingTask::query()->where('booking_id', $booking->id)->count();
$this->assertSame($first, $second, 'repeated runs create no second request');
$collection === 'collection.own' ? $this->assertGreaterThan(0, $first, 'we collect: payment tasks exist') : $this->assertSame(0, $first, 'the portal collects: no own payment request towards the guest');
$this->assertNull($booking->fresh()->confirmation_sent_at, 'a portal event or reminder never creates or changes our contract');
}
public function test_the_archetypes_are_presets_of_the_base_process(): void
{
$catalogue = app(ProcessCatalogue::class);
foreach (['a3.portal_booking', 'a4.portal_booking', 'a5.portal_booking'] as $key) {
$model = $catalogue->model($key);
$this->assertTrue($model::isLegacy());
$this->assertSame([], app(TemplateComposer::class)->problems($catalogue->model('external.booking'), $model::presetTemplates()));
}
$this->assertFalse(ExternalBookingModel::isLegacy());
}
public function test_unsuitable_combinations_are_refused_with_a_reason(): void
{
$composer = app(TemplateComposer::class);
$model = app(ProcessCatalogue::class)->model('external.booking');
$this->assertStringContainsString('gehört zu', implode(' ', $composer->problems($model, ['collection' => 'contract_docs.own'])), 'a template only fits the slot of its area');
$this->assertStringContainsString('gibt es nicht', implode(' ', $composer->problems($model, ['collection' => 'collection.gibt-es-nicht'])));
$this->assertStringContainsString('keinen Platz', implode(' ', $composer->problems($model, ['gastronomie' => 'collection.own'])));
}
public function test_double_effects_missing_prerequisites_contradictions_and_exclusions_are_detected(): void
{
$this->register(DoubleCollectionTemplate::class, NeedyDocumentsTemplate::class, ContradictingDocumentsTemplate::class, ExcludingDocumentsTemplate::class, DuplicateModuleTemplate::class);
$composer = app(TemplateComposer::class);
$model = app(ProcessCatalogue::class)->model('external.booking');
$problems = fn (array $chosen): string => implode(' | ', $composer->problems($model, $chosen));
$this->assertStringContainsString('doppelt erzeugt', $problems(['contract_documents' => DoubleCollectionTemplate::key()]), 'the collection result may come from one template only');
$this->assertStringContainsString('voraus', $problems(['contract_documents' => NeedyDocumentsTemplate::key()]));
$this->assertStringContainsString('Widersprüchliche Verantwortlichkeit', $problems(['contract_documents' => ContradictingDocumentsTemplate::key()]));
$this->assertStringContainsString('nicht kombinieren', $problems(['collection' => 'collection.portal', 'contract_documents' => ExcludingDocumentsTemplate::key()]));
$this->assertSame('', $problems(['collection' => 'collection.own', 'contract_documents' => ExcludingDocumentsTemplate::key()]), 'the exclusion only concerns portal collection');
$this->assertStringContainsString('mehrfach', $problems(['collection' => DuplicateModuleTemplate::key()]));
}
public function test_a_hard_dependency_on_a_module_the_templates_would_have_supplied_is_unmet(): void
{
config(['process.models' => [...config('process.models'), 'test.model' => [1 => ModelWithDependentStep::class]]]);
$this->register(SuppliesStayTemplate::class);
$model = app(ProcessCatalogue::class)->model('test.model');
$this->assertStringContainsString('braucht zwingend', implode(' ', app(TemplateComposer::class)->problems($model, ['collection' => 'collection.own'])));
$this->assertSame([], app(TemplateComposer::class)->problems($model, ['collection' => SuppliesStayTemplate::key()]));
}
public function test_a_new_template_version_applies_to_new_cases_only_and_old_plans_stay_readable(): void
{
$channel = $this->configured(['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own']);
$first = $this->takeOver($channel, 'V1');
config(['process.templates' => [...config('process.templates'), 'collection.own' => [1 => OwnCollection::class, 2 => OwnCollectionVersion2::class]]]);
$second = $this->takeOver($channel->fresh(), 'V2', '2027-08-10');
$this->assertSame('collection.own@1', ProcessPlan::of($first->fresh())->templates['collection']);
$this->assertSame('collection.own@2', ProcessPlan::of($second)->templates['collection']);
$this->assertSame($first->profile['plan'], $first->fresh()->profile['plan'], 'the running case keeps its frozen plan');
$legacy = ProcessPlan::fromArray(['model' => 'a3.portal_booking', 'model_version' => 2, 'modules' => ['intake.record' => 1]]);
$this->assertSame([], $legacy->templates, 'plans frozen before the composition have no templates');
}
public function test_the_unsaved_choice_shows_in_the_preview_with_the_template_of_each_step(): void
{
$channel = $this->channel('Test Portal');
$rows = collect(app(ChannelProcessConfiguration::class)->preview($channel, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.external']]));
$this->assertSame('Portal-Inkasso', $rows->firstWhere('module', 'portal.payout')['template']);
$this->assertSame('Externe Vertragsunterlagen', $rows->firstWhere('module', 'documents.send')['template']);
$this->assertNull($rows->firstWhere('module', 'stay')['template']);
}
public function test_the_base_process_cannot_be_saved_with_templates_the_portal_cannot_support(): void
{
$channel = $this->channel('FeWo-direkt Test');
$configure = app(ConfigureChannelProcess::class);
$draft = ['model' => 'external.booking', 'templates' => ['collection' => 'collection.own', 'contract_documents' => 'contract_docs.own'], 'capabilities' => ['collects_payment' => '1', 'provides_contract_documents' => '0']];
try {
$configure->handle($channel, IntakeKind::Booking, $draft);
$this->fail('own collection although the portal collects');
} catch (ValidationException $exception) {
$this->assertStringContainsString('Zieht das Portal das Geld', implode(' ', $exception->errors()['process']));
}
$this->assertNull(($channel->fresh()->process_overrides ?? [])['booking'] ?? null, 'nothing saved');
$configure->handle($channel, IntakeKind::Booking, [...$draft, 'templates' => ['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own']]);
$this->assertEquals(['collection' => 'collection.portal', 'contract_documents' => 'contract_docs.own', 'guest_communication' => 'guest_comm.own'], $channel->fresh()->process_overrides['booking']['templates']);
}
/**
* @param array<string, string> $templates
*/
private function configured(array $templates): Channel
{
$channel = $this->channel('Vergleichsportal', suffix: md5(json_encode($templates)));
app(ConfigureChannelProcess::class)->handle($channel, IntakeKind::Booking, ['model' => 'external.booking', 'templates' => $templates]);
return $channel->fresh();
}
/**
* @param class-string<FunctionTemplate> ...$classes
*/
private function register(string ...$classes): void
{
$templates = config('process.templates');
foreach ($classes as $class) {
$templates[$class::key()] = [1 => $class];
}
config(['process.templates' => $templates]);
}
private function legacyChannel(string $model): Channel
{
$channel = $this->channel('Vergleichsportal', suffix: 'alt');
app(ConfigureChannelProcess::class)->handle($channel, IntakeKind::Booking, ['model' => $model]);
return $channel->fresh();
}
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]);
}
private function channel(string $name, string $suffix = ''): Channel
{
return Channel::factory()->for($this->property)->create(['name' => $name, 'booking_model' => 'portal_booking', 'import_enabled' => false, 'settings' => ['import_url' => 'https://portal.example/'.md5($name.$suffix).'.ics', 'portal_profile' => 'generic']]);
}
}
/** Test doubles: templates and a model that exist only to provoke the composition checks. */
abstract class TestTemplate extends FunctionTemplate
{
public static function version(): int
{
return 1;
}
public static function key(): string
{
return 'test.'.strtolower(substr(strrchr(static::class, '\\'), 1));
}
public static function purpose(): string
{
return 'Testschablone';
}
public static function label(): string
{
return static::key();
}
}
final class DoubleCollectionTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::ContractDocuments;
}
public static function modules(): array
{
return ['documents.send'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
public static function provides(): array
{
return [TemplateArea::ContractDocuments->result(), TemplateArea::Collection->result()];
}
}
final class NeedyDocumentsTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::ContractDocuments;
}
public static function modules(): array
{
return ['documents.send'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
public static function requires(): array
{
return ['signature.qualified'];
}
}
final class ContradictingDocumentsTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::ContractDocuments;
}
public static function modules(): array
{
return ['documents.send'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
public static function fixes(): array
{
return ['documents' => 'landlord', 'payments' => 'portal'];
}
}
final class ExcludingDocumentsTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::ContractDocuments;
}
public static function modules(): array
{
return ['documents.send'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
public static function incompatibleWith(): array
{
return ['collection.portal' => 'Beide würden die Auszahlung dokumentieren.'];
}
}
final class DuplicateModuleTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::Collection;
}
public static function modules(): array
{
return ['payments.monitor', 'documents.send'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
}
final class SuppliesStayTemplate extends TestTemplate
{
public static function area(): TemplateArea
{
return TemplateArea::Collection;
}
public static function modules(): array
{
return ['stay'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
}
final class OwnCollectionVersion2 extends TestTemplate
{
public static function key(): string
{
return 'collection.own';
}
public static function version(): int
{
return 2;
}
public static function area(): TemplateArea
{
return TemplateArea::Collection;
}
public static function modules(): array
{
return ['payments.monitor'];
}
public static function responsibility(): Responsibility
{
return Responsibility::Landlord;
}
}
/** A model whose review step needs the stay, which a collection template may supply. */
final class ModelWithDependentStep extends ProcessModel
{
public static function key(): string
{
return 'test.model';
}
public static function version(): int
{
return 1;
}
public static function label(): string
{
return 'Testmodell';
}
public static function description(): string
{
return '';
}
public static function caseTypes(): array
{
return [CaseType::A3];
}
public static function intakes(): array
{
return [IntakeKind::Booking];
}
public static function responsibilities(): Responsibilities
{
return Responsibilities::of(fixed: []);
}
public static function defaultTemplates(): array
{
return ['collection' => 'collection.own'];
}
public function steps(): array
{
return [Step::module('intake.record'), Step::slot(TemplateArea::Collection), Step::module('review.request')];
}
}