diff --git a/app/Actions/AnonymizeGuests.php b/app/Actions/AnonymizeGuests.php index 8d7e767..a98e40a 100644 --- a/app/Actions/AnonymizeGuests.php +++ b/app/Actions/AnonymizeGuests.php @@ -5,6 +5,7 @@ use App\Models\Booking; use App\Models\Guest; use App\Models\PortalEmail; +use App\Models\ProcessTestRun; /** * GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and @@ -44,6 +45,9 @@ public function handle(): int private function purgeOperationalData(): void { + // Process tester reports (synthetic data only, decision O3). + ProcessTestRun::query()->where('created_at', '<', now()->subDays(config('fewo.retention.process_test_run_days')))->delete(); + PortalEmail::query() ->whereNotNull('excerpt') ->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days'))) diff --git a/app/Actions/TakeOverExternalBooking.php b/app/Actions/TakeOverExternalBooking.php index 68807a2..49cf248 100644 --- a/app/Actions/TakeOverExternalBooking.php +++ b/app/Actions/TakeOverExternalBooking.php @@ -111,7 +111,7 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar */ private function checkEvidence(BlockedPeriod $evidence): ?Booking { - if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) { + if (! in_array($evidence->source, ['channel', 'email', 'api'], true) || $evidence->channel_id === null) { throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.'); } if ($evidence->occupationKind() === OccupationKind::Block) { diff --git a/app/Channels/Contracts/DeliversEvents.php b/app/Channels/Contracts/DeliversEvents.php new file mode 100644 index 0000000..3abec53 --- /dev/null +++ b/app/Channels/Contracts/DeliversEvents.php @@ -0,0 +1,20 @@ + + */ + public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array; +} diff --git a/app/Channels/Contracts/ReceivesWebhooks.php b/app/Channels/Contracts/ReceivesWebhooks.php new file mode 100644 index 0000000..b0e162c --- /dev/null +++ b/app/Channels/Contracts/ReceivesWebhooks.php @@ -0,0 +1,19 @@ + empty when the signature is not valid + */ + public function receive(Channel $channel, Request $request): array; +} diff --git a/app/Channels/Events/BookingCancelledByChannel.php b/app/Channels/Events/BookingCancelledByChannel.php new file mode 100644 index 0000000..61b75b9 --- /dev/null +++ b/app/Channels/Events/BookingCancelledByChannel.php @@ -0,0 +1,14 @@ +provenance->channel; + if (! $channel->isPortal() || $channel->tenant_id === null) { + throw new InvalidArgumentException('Kanalereignisse kommen nur von Portalen.'); + } + + return app(TenantContext::class)->run($channel->tenant, fn (): ?IntakeDecision => match (true) { + $event instanceof IncomingBooking => $this->booking($event), + $event instanceof BookingCancelledByChannel => $this->report($event, IntakeOutcome::CancellationSignal, $channel->name.' meldet über die Schnittstelle eine Stornierung'.($event->note ? ' ('.$event->note.')' : '').'. Bitte prüfen Sie die Buchung und die nächsten Schritte.'), + $event instanceof BookingChangedByChannel => $this->report($event, IntakeOutcome::ChangeSignal, $channel->name.' meldet über die Schnittstelle eine Änderung'.($event->arrival && $event->departure ? ': '.$event->arrival->format('d.m.').'–'.$event->departure->format('d.m.Y') : '').($event->guests ? ', '.$event->guests.' Personen' : '').'. Die Buchung bleibt unverändert, bis Sie entscheiden.'), + $event instanceof PaymentReported => $this->payment($event), + $event instanceof PayoutReported => $this->payout($event), + default => throw new InvalidArgumentException('Unbekanntes Kanalereignis '.$event::class.'.'), + }); + } + + /** + * A booking binding at the portal: blocked like a booking e-mail – source api, reference in the identifier – and judged + * by PortalIntake – the same case, never a second one; a case only when certain. + */ + private function booking(IncomingBooking $event): IntakeDecision + { + $provenance = $event->provenance; + $reference = $provenance->externalReference; + // The reference is the identity of the block (as for booking mails); without one it is never taken as a reference. + $uid = $reference !== null ? 'api:'.$reference : 'api-event:'.$provenance->evidenceRef; + $block = $provenance->channel->blockedPeriods()->withTrashed()->where('source', 'api')->where('external_uid', $uid)->first() + ?? new BlockedPeriod(['property_id' => $provenance->channel->property_id, 'source' => 'api', 'reason' => $provenance->channel->name, 'external_uid' => $uid]); + $block->fill(['starts_on' => $event->arrival->toDateString(), 'ends_on' => $event->departure->toDateString()]); + if ($block->trashed()) { + $block->restore(); + } + $provenance->channel->blockedPeriods()->save($block); + + return $this->intake->process($block->fresh(), IntakeObservation::SOURCE_API); + } + + private function report(BookingCancelledByChannel|BookingChangedByChannel $event, IntakeOutcome $outcome, string $message): ?IntakeDecision + { + $case = $this->case($event); + if ($case === null) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference); + } + $this->intake->reportToCase($event->provenance->channel, $case, $outcome, $message, 'api:'.$event->provenance->evidenceRef, IntakeObservation::SOURCE_API); + + return new IntakeDecision($outcome, [$message], $case, reference: $event->provenance->externalReference); + } + + private function payment(PaymentReported $event): ?IntakeDecision + { + $case = $this->case($event); + if ($case === null) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Zahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference); + } + $this->amounts->handle($case, null, [], [['amount' => $event->amount, 'paid_on' => $event->paidOn->toDateString()]], $event->provenance->channel->name); + + return new IntakeDecision(IntakeOutcome::Link, ['Zahlung des Gastes laut Portal erfasst (kein Eingang auf unserem Konto).'], $case); + } + + private function payout(PayoutReported $event): ?IntakeDecision + { + $case = $this->case($event); + if ($case === null) { + return new IntakeDecision(IntakeOutcome::Clarify, ['Auszahlungsmeldung keinem gebuchten Vorgang sicher zuzuordnen.'], reference: $event->provenance->externalReference); + } + if ($event->executed) { + // Evidence level "laut Portal erledigt" – the receipt on our account is recorded by the landlord (O5). + CaseLog::record($case, 'evidence', 'Auszahlung laut '.$event->provenance->channel->name.' ausgeführt: '.Money::format($event->amount).' am '.$event->paidOn->format('d.m.Y').' – Eingang auf unserem Konto noch nicht erfasst.', data: ['module' => 'portal.payout', 'level' => 'stated_by_portal', 'source' => $event->provenance->transport, 'ref' => $event->provenance->evidenceRef], actor: $event->provenance->channel->name); + } else { + $this->amounts->handle($case, null, [['kind' => 'payout_announced', 'amount' => $event->amount, 'due_on' => $event->paidOn->toDateString()]], [], $event->provenance->channel->name); + } + + return new IntakeDecision(IntakeOutcome::Link, ['Auszahlung laut Portal vermerkt.'], $case); + } + + /** + * The binding case of the event: by the portal's booking reference only (no merging by dates for reports). + */ + private function case(ChannelEvent $event): ?Booking + { + $reference = $event->provenance->externalReference; + $case = $reference === null ? null : $this->intake->caseByReference($event->provenance->channel, $reference); + + return $case !== null && $case->isBinding() ? $case : null; + } +} diff --git a/app/Channels/Events/IncomingBooking.php b/app/Channels/Events/IncomingBooking.php new file mode 100644 index 0000000..6b44c3f --- /dev/null +++ b/app/Channels/Events/IncomingBooking.php @@ -0,0 +1,16 @@ +authenticity === self::AUTHENTICATED; + } +} diff --git a/app/Channels/Intake/PortalIntake.php b/app/Channels/Intake/PortalIntake.php index 4507bda..04b3aac 100644 --- a/app/Channels/Intake/PortalIntake.php +++ b/app/Channels/Intake/PortalIntake.php @@ -65,7 +65,7 @@ public function evaluate(BlockedPeriod $block): IntakeDecision $channel = $block->channel; $reference = self::reference($block); - if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) { + if ($channel === null || ! in_array($block->source, ['channel', 'email', 'api'], true)) { return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference); } if ($block->trashed()) { @@ -246,6 +246,15 @@ public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, Por return $case; } + /** + * A report of the portal about a known case (channel events, Architektur V2: cancellation or change via an API): + * the case gets a task and a history entry, nothing about the booking changes (E-019, stage M2 of 02 §8.2). + */ + public function reportToCase(Channel $channel, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source): void + { + $this->report($channel, $channel->case_intake ?? CaseIntakeMode::Off, $case, $outcome, $message, $key, $source); + } + /** * A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates * cases; otherwise only recorded. @@ -292,6 +301,11 @@ public static function reference(BlockedPeriod $block): ?string return trim((string) $fromRules); } + // A block of a portal's API (channel events, Architektur V2) carries the reference like a booking mail. + if ($block->source === 'api' && str_starts_with((string) $block->external_uid, 'api:')) { + return substr((string) $block->external_uid, 4); + } + if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) { $reference = substr((string) $block->external_uid, 6); @@ -315,7 +329,7 @@ public function caseByReference(Channel $channel, string $reference): ?Booking } $linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id') - ->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id'); + ->whereIn('external_uid', [$reference, 'email:'.$reference, 'api:'.$reference])->value('linked_booking_id'); return $linked !== null ? Booking::query()->find($linked) : null; } @@ -346,6 +360,9 @@ private function certainty(BlockedPeriod $block, ?string $reference): ?string if ($block->source === 'email') { return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null; } + if ($block->source === 'api') { + return $reference === null ? 'Portalmeldung ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : null; + } // Classified by the landlord as a reservation booked at this portal. if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) { diff --git a/app/Console/Commands/ProcessSandboxRun.php b/app/Console/Commands/ProcessSandboxRun.php new file mode 100644 index 0000000..25c87f3 --- /dev/null +++ b/app/Console/Commands/ProcessSandboxRun.php @@ -0,0 +1,40 @@ +argument('run') || config('sandbox.run') !== $this->argument('run')) { + $this->error('Nur innerhalb eines vom Prozess-Tester gestarteten Laufs.'); + + return self::FAILURE; + } + + $directory = (string) config('sandbox.directory'); + try { + $report = $driver->run((array) json_decode((string) file_get_contents($directory.'/input.json'), true)); + } catch (Throwable $exception) { + $report = ['aborted' => 'Lauf abgebrochen: '.class_basename($exception).': '.$exception->getMessage(), 'timeline' => [], 'violations' => EffectLedger::violations()]; + } + file_put_contents($directory.'/report.json', json_encode($report, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + return self::SUCCESS; + } +} diff --git a/app/Console/Commands/ProcessSandboxTemplate.php b/app/Console/Commands/ProcessSandboxTemplate.php new file mode 100644 index 0000000..bb70d5f --- /dev/null +++ b/app/Console/Commands/ProcessSandboxTemplate.php @@ -0,0 +1,49 @@ +warn('pdo_sqlite fehlt – der Prozess-Tester bleibt gesperrt.'); + + return self::SUCCESS; + } + + $directory = storage_path('app/sandbox'); + @mkdir($directory.'/runs', 0775, true); + $file = $directory.'/template.building.sqlite'; + @unlink($file); + touch($file); + + config(['database.connections.sandbox_template' => ['driver' => 'sqlite', 'database' => $file, 'prefix' => '', 'foreign_key_constraints' => true]]); + // `migrate --database` switches the default connection of this process and does not switch it back. + $default = DB::getDefaultConnection(); + try { + Artisan::call('migrate', ['--database' => 'sandbox_template', '--force' => true, '--no-interaction' => true]); + } finally { + DB::setDefaultConnection($default); + DB::purge('sandbox_template'); + config(['database.connections.sandbox_template' => null]); + } + + rename($file, $directory.'/template.sqlite'); + $this->info('Vorlage erstellt: '.$directory.'/template.sqlite'); + + return self::SUCCESS; + } +} diff --git a/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php b/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php index 1b2e092..de0e6e4 100644 --- a/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php +++ b/app/Filament/Resources/Bookings/Pages/Concerns/HandlesWishAndStay.php @@ -13,9 +13,12 @@ use App\Enums\BookingTaskStatus; use App\Enums\DocumentKind; use App\Enums\IntakeKind; +use App\Enums\Responsibility; +use App\Exceptions\ReservationException; use App\Filament\Forms\DocumentCompositionFields; use App\Models\Booking; use App\Models\BookingTask; +use App\Pricing\CaseMoney; use App\Pricing\StayRequest; use App\Process\CaseClosure; use App\Process\CaseLog; @@ -230,14 +233,37 @@ private function settleAction(): Action ->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Completed, BookingStatus::Cancelled], true) && $this->record->settled_at === null) ->modalHeading('Kaufmännisch abschließen') ->modalDescription(fn (): string => 'Noch offen: '.implode(' ', CaseClosure::commercialPoints($this->record)).' Abschließen nur, wenn das geklärt ist (z. B. kleine Differenz akzeptiert, Forderung ausgebucht).') - ->schema([Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500)]) + ->schema([ + // Decision O5: with portal collection an open payout needs its financial clarification, not only a reason. + Select::make('clarification')->label('Wie ist die Auszahlung geklärt?') + ->options(CaseClosure::PAYOUT_CLARIFICATIONS) + ->visible(fn (): bool => $this->payoutOpen()) + ->required(fn (): bool => $this->payoutOpen()) + ->helperText('Eine Meldung des Portals über die Auszahlung ist kein Nachweis des Geldeingangs. „Als offene Forderung weiterführen“ legt eine Aufgabe an; der Vorgang bleibt kaufmännisch offen.'), + Textarea::make('note')->label('Begründung')->required()->rows(2)->maxLength(500), + ]) ->action(function (array $data): void { - CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor()); + try { + CaseClosure::settle($this->record, trim((string) $data['note']), CaseLog::actor(), $data['clarification'] ?? null); + } catch (ReservationException $exception) { + Notification::make()->title('Nicht abgeschlossen')->body($exception->getMessage())->danger()->send(); + + return; + } $this->record->refresh(); - Notification::make()->title('Kaufmännisch abgeschlossen')->success()->send(); + Notification::make()->title($this->record->settled_at !== null ? 'Kaufmännisch abgeschlossen' : 'Als offene Forderung weitergeführt')->success()->send(); }); } + /** + * Whether the portal's payout is open or deviating (decision O5). + */ + private function payoutOpen(): bool + { + return CaseMoney::of($this->record)->collector() === Responsibility::Portal + && collect(CaseClosure::commercialPoints($this->record))->contains(fn (string $point): bool => str_contains($point, 'Auszahlung')); + } + /** * Open tasks the landlord can settle on the page (not the ones with an action of their own). * diff --git a/app/Filament/Resources/Channels/ChannelResource.php b/app/Filament/Resources/Channels/ChannelResource.php index a8f3645..ab20d75 100644 --- a/app/Filament/Resources/Channels/ChannelResource.php +++ b/app/Filament/Resources/Channels/ChannelResource.php @@ -5,6 +5,7 @@ use App\Filament\Concerns\FollowsAdminMode; use App\Filament\Concerns\SelectsRecordProperty; use App\Filament\Resources\Channels\Pages\ChannelProcess; +use App\Filament\Resources\Channels\Pages\ChannelProcessTest; use App\Filament\Resources\Channels\Pages\ChannelRules; use App\Filament\Resources\Channels\Pages\CreateChannel; use App\Filament\Resources\Channels\Pages\EditChannel; @@ -63,6 +64,7 @@ public static function getPages(): array 'edit' => EditChannel::route('/{record}/edit'), 'rules' => ChannelRules::route('/{record}/rules'), 'process' => ChannelProcess::route('/{record}/process'), + 'test' => ChannelProcessTest::route('/{record}/test'), ]; } } diff --git a/app/Filament/Resources/Channels/Pages/ChannelProcess.php b/app/Filament/Resources/Channels/Pages/ChannelProcess.php index 5470513..1b8f209 100644 --- a/app/Filament/Resources/Channels/Pages/ChannelProcess.php +++ b/app/Filament/Resources/Channels/Pages/ChannelProcess.php @@ -211,6 +211,15 @@ public function save(): void Notification::make()->title('Ablauf gespeichert')->body('Gilt für neue Vorgänge.'.($running > 0 ? ' '.$running.' laufende Vorgänge behalten ihren bisherigen Ablauf.' : ''))->success()->send(); } + /** + * Opens the process tester with the current – also unsaved – draft of this intake kind. + */ + public function test(): void + { + session()->put('process-tester.draft.'.$this->record->id.'.'.$this->intake, $this->drafts[$this->intake]); + $this->redirect(ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake])); + } + /** * The effective value a new case would get, for the landlord's comparison (expert view). */ diff --git a/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php b/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php new file mode 100644 index 0000000..f149275 --- /dev/null +++ b/app/Filament/Resources/Channels/Pages/ChannelProcessTest.php @@ -0,0 +1,151 @@ + */ + public array $inputs = []; + + /** @var array */ + public array $draft = []; + + public int $steps = 1; + + public ?int $runId = null; + + public static function canAccess(array $parameters = []): bool + { + $user = auth()->user(); + + return $user instanceof User && $user->hasRole(UserRole::Admin); + } + + public function mount(int|string $record): void + { + $this->record = $this->resolveRecord($record); + $intakes = array_map(fn (IntakeKind $intake): string => $intake->value, app(ChannelProcessConfiguration::class)->intakes($this->record)); + $requested = (string) request()->query('intake', ''); + $this->intake = in_array($requested, $intakes, true) ? $requested : ($intakes[0] ?? 'inquiry'); + $this->draft = (array) session()->get($this->draftKey(), []); + if ($this->draft === []) { + $current = app(ChannelProcessConfiguration::class)->current($this->record, IntakeKind::from($this->intake)); + $stored = (array) (($this->record->process_overrides ?? [])[$this->intake] ?? []); + $this->draft = ['model' => $current['model'], 'variant' => $current['variant'], 'steps' => (array) ($stored['steps'] ?? []), 'settings' => []]; + } + $this->scenario = (string) array_key_first($this->scenarios()); + $this->resetInputs(); + } + + public function draftKey(): string + { + return 'process-tester.draft.'.$this->record->id.'.'.$this->intake; + } + + /** + * @return array> + */ + public function scenarios(): array + { + return ScenarioCatalogue::for(IntakeKind::from($this->intake), $this->record->isWebsite()); + } + + public function updatedScenario(): void + { + $this->resetInputs(); + $this->runId = null; + $this->steps = 1; + } + + private function resetInputs(): void + { + $class = $this->scenarios()[$this->scenario] ?? null; + $this->inputs = $class === null ? [] : array_map(fn (array $input): mixed => $input['type'] === 'date' ? now()->modify((string) $input['default'])->toDateString() : $input['default'], $class::inputs()); + } + + /** + * @return list + */ + public function requirements(): array + { + return ProcessSandbox::requirements(); + } + + public function start(): void + { + $this->steps = 1; + $this->play(); + } + + public function next(): void + { + $this->steps++; + $this->play(); + } + + private function play(): void + { + try { + $run = app(ProcessSandbox::class)->run($this->record, IntakeKind::from($this->intake), $this->draft, $this->scenario, $this->inputs, $this->steps, auth()->user()); + $this->runId = $run->id; + } catch (Throwable $exception) { + Notification::make()->title('Test nicht möglich')->body($exception->getMessage())->danger()->persistent()->send(); + } + } + + public function run(): ?ProcessTestRun + { + return $this->runId === null ? null : ProcessTestRun::query()->find($this->runId); + } + + /** + * @return iterable + */ + public function recent(): iterable + { + return ProcessTestRun::query()->where('channel_id', $this->record->id)->latest()->limit(5)->get(); + } + + protected function getHeaderActions(): array + { + return [ + Action::make('back')->label('Zurück zum Ablauf')->color('gray')->url(fn (): string => ChannelResource::getUrl('process', ['record' => $this->record])), + ]; + } +} diff --git a/app/Models/IntakeObservation.php b/app/Models/IntakeObservation.php index 6c11e06..2bcc946 100644 --- a/app/Models/IntakeObservation.php +++ b/app/Models/IntakeObservation.php @@ -24,6 +24,9 @@ class IntakeObservation extends Model public const SOURCE_ADOPTION = 'adoption'; + /** A normalised channel event of a portal's interface (Architektur V2, App\Channels\Events). */ + public const SOURCE_API = 'api'; + /** * Get the attributes that should be cast. * diff --git a/app/Models/ProcessTestRun.php b/app/Models/ProcessTestRun.php new file mode 100644 index 0000000..ed49eab --- /dev/null +++ b/app/Models/ProcessTestRun.php @@ -0,0 +1,39 @@ + 'array', + 'inputs' => 'array', + 'report' => 'array', + ]; + } + + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } +} diff --git a/app/Process/CaseClosure.php b/app/Process/CaseClosure.php index b09b070..18f0dfe 100644 --- a/app/Process/CaseClosure.php +++ b/app/Process/CaseClosure.php @@ -3,8 +3,10 @@ namespace App\Process; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; use App\Enums\BookingTaskStatus; use App\Enums\Responsibility; +use App\Exceptions\ReservationException; use App\Models\Booking; use App\Models\BookingTask; use App\Pricing\CaseMoney; @@ -21,6 +23,16 @@ */ final class CaseClosure { + /** Kinds of financial clarification that allow settling an open portal payout (decision O5). */ + public const PAYOUT_CLARIFICATIONS = [ + 'offset' => 'Verrechnung dokumentiert', + 'difference_booked' => 'Differenz geklärt und verbucht', + 'written_off' => 'Forderung ausgebucht', + self::CLAIM_OPEN => 'Als offene Forderung weiterführen', + ]; + + public const CLAIM_OPEN = 'open_claim'; + public const AUTOMATIC = 'automatisch'; /** @@ -92,8 +104,26 @@ public static function refresh(Booking $booking): void * The landlord settles the case although points are open (e.g. a small payout difference accepted); open commercial * tasks are closed with the same note. The reason is required and kept. */ - public static function settle(Booking $booking, string $note, string $by): void + public static function settle(Booking $booking, string $note, string $by, ?string $clarification = null): void { + // Decision O5: with portal collection, an open or deviating payout is settled only after its financial + // clarification – a reason alone is not enough, and a portal's report of a payout is no proof of the receipt. + $payoutPoints = $booking->status !== BookingStatus::Cancelled && CaseMoney::of($booking)->collector() === Responsibility::Portal + ? self::portalMoney($booking, CaseMoney::of($booking)) : []; + if ($payoutPoints !== [] && ! array_key_exists((string) $clarification, self::PAYOUT_CLARIFICATIONS)) { + throw new ReservationException('Bei Inkasso durch das Portal ist der kaufmännische Abschluss erst nach finanzieller Klärung möglich: Auszahlung eingegangen, Verrechnung, verbuchte Differenz oder ausgebuchte Forderung. Offen: '.implode(' ', $payoutPoints)); + } + if ($clarification === self::CLAIM_OPEN) { + // The claim stays traceable: an open task of its own, the case stays commercially open. + BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::OpenClaim, 'status' => BookingTaskStatus::Open], ['tenant_id' => $booking->tenant_id, 'due_on' => today()->addDays(14), 'note' => mb_substr($note, 0, 1000)]); + CaseLog::record($booking, 'settled', 'Als offene Forderung weitergeführt', reason: $note, data: ['open_points' => $payoutPoints, 'clarification' => $clarification], actor: $by); + + return; + } + if ($clarification !== null && isset(self::PAYOUT_CLARIFICATIONS[$clarification])) { + $note = self::PAYOUT_CLARIFICATIONS[$clarification].': '.$note; + } + foreach (BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get() as $task) { if ($task->kind->isCommercial()) { $task->complete($by, 'Mit dem kaufmännischen Abschluss geklärt: '.$note); diff --git a/app/Process/ProcessPlan.php b/app/Process/ProcessPlan.php index 76c00d7..e4aba86 100644 --- a/app/Process/ProcessPlan.php +++ b/app/Process/ProcessPlan.php @@ -69,6 +69,8 @@ public static function derive(ProcessProfile $profile): self public static function freeze(ProcessProfile $profile, array $configuration, bool $sandbox = false): self { $catalogue = app(ProcessCatalogue::class); + // Inside a process tester run (its own process, SandboxBootstrapper) tester-only variants are allowed. + $sandbox = $sandbox || filled(config('sandbox.run')); $chosen = (string) ($configuration['model'] ?? ''); if ($chosen === '') { return self::build($catalogue->model($catalogue->derivedModel($profile)), 'standard', (array) ($configuration['steps'] ?? []), self::DERIVED); diff --git a/app/Process/Tester/EffectLedger.php b/app/Process/Tester/EffectLedger.php new file mode 100644 index 0000000..87a60b1 --- /dev/null +++ b/app/Process/Tester/EffectLedger.php @@ -0,0 +1,50 @@ + $data + */ + public static function record(string $type, array $data = []): void + { + if (self::$path === null) { + return; + } + file_put_contents(self::$path, json_encode(['type' => $type, ...$data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)."\n", FILE_APPEND | LOCK_EX); + } + + /** + * @return list> + */ + public static function entries(): array + { + if (self::$path === null || ! is_file(self::$path)) { + return []; + } + + return array_values(array_map(fn (string $line): array => (array) json_decode($line, true), array_filter(explode("\n", (string) file_get_contents(self::$path))))); + } + + public static function violations(): array + { + return array_values(array_filter(self::entries(), fn (array $entry): bool => ($entry['type'] ?? null) === 'violation')); + } +} diff --git a/app/Process/Tester/ProcessSandbox.php b/app/Process/Tester/ProcessSandbox.php new file mode 100644 index 0000000..e6c3e2a --- /dev/null +++ b/app/Process/Tester/ProcessSandbox.php @@ -0,0 +1,199 @@ + + */ + public static function requirements(): array + { + $missing = []; + if (! extension_loaded('pdo_sqlite')) { + $missing[] = 'Die PHP-Erweiterung pdo_sqlite fehlt (eigene Testdatenbank je Lauf).'; + } + if (! is_file(storage_path('app/sandbox/template.sqlite'))) { + $missing[] = 'Die Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).'; + } + $disabled = array_map('trim', explode(',', (string) ini_get('disable_functions'))); + if (! function_exists('proc_open') || in_array('proc_open', $disabled, true)) { + $missing[] = 'Eigene Prozesse lassen sich nicht starten (proc_open gesperrt) – ohne eigenen Prozess ist keine sichere Trennung möglich.'; + } + if (str_contains(str_replace(DIRECTORY_SEPARATOR, '/', self::php()), '/') && ! is_file(self::php())) { + $missing[] = 'Das PHP-Programm für den Testlauf wurde nicht gefunden.'; + } + + return $missing; + } + + /** + * Plays a scenario with the (possibly unsaved) draft of a channel's process and returns the stored report. + * + * @param array $draft + * @param array $inputs + */ + public function run(Channel $channel, IntakeKind $intake, array $draft, string $scenario, array $inputs, int $steps, User $user): ProcessTestRun + { + if (($missing = self::requirements()) !== []) { + throw new RuntimeException('Der Prozess-Tester ist auf diesem Server gesperrt: '.implode(' ', $missing)); + } + if (ScenarioCatalogue::find($scenario) === null) { + throw new RuntimeException('Unbekanntes Szenario.'); + } + if (($problems = app(ChannelProcessConfiguration::class)->problems($channel, $intake, $draft, sandbox: true)) !== []) { + throw new RuntimeException('Die Konfiguration ist nicht zulässig: '.implode(' ', $problems)); + } + + self::prune(); + $locks = $this->slot($channel->tenant_id); + $run = (string) Str::uuid(); + $directory = SandboxBootstrapper::directory($run); + + try { + File::ensureDirectoryExists($directory.'/files', 0700); + $input = [ + 'snapshot' => SandboxSnapshot::build($channel, $intake, $draft), + 'scenario' => $scenario, + 'inputs' => $inputs, + 'steps' => $steps, + 'start' => now()->startOfMinute()->toIso8601String(), + ]; + File::put($directory.'/input.json', (string) json_encode($input, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); + + $result = Process::path(base_path()) + ->timeout(self::TIMEOUT_SECONDS) + ->env([SandboxBootstrapper::ENV => $run, ...self::childEnvironment(), ...(app()->environment('testing') ? (array) config('fewo.sandbox.test_environment', []) : [])]) + ->run([self::php(), 'artisan', 'process:sandbox-run', $run, '--no-interaction']); + + $report = is_file($directory.'/report.json') ? (array) json_decode((string) File::get($directory.'/report.json'), true) : []; + if ($report === []) { + $report = ['aborted' => 'Der Testlauf hat keinen Bericht geliefert'.($result->successful() ? '.' : ': '.mb_substr(trim($result->errorOutput() ?: $result->output()), 0, 300)), 'timeline' => [], 'violations' => []]; + } + + return ProcessTestRun::query()->create([ + 'tenant_id' => $channel->tenant_id, + 'channel_id' => $channel->id, + 'user_id' => $user->id, + 'intake' => $intake->value, + 'scenario' => $scenario, + 'configuration' => $draft, + 'inputs' => $inputs, + 'steps' => $steps, + 'report' => $report, + 'outcome' => filled($report['aborted'] ?? null) ? ProcessTestRun::ABORTED : ProcessTestRun::COMPLETED, + 'release' => self::release(), + ]); + } finally { + File::deleteDirectory($directory); + foreach ($locks as $lock) { + flock($lock, LOCK_UN); + fclose($lock); + } + } + } + + /** + * Removes directories of runs that ended abnormally (older than an hour). + */ + public static function prune(): void + { + foreach (glob(storage_path('app/sandbox/runs/*'), GLOB_ONLYDIR) ?: [] as $directory) { + if (filemtime($directory) < time() - 3600) { + File::deleteDirectory($directory); + } + } + } + + /** + * The release the report belongs to. + */ + public static function release(): ?string + { + // Releases on Strato live in releases/- (pipeline-manager, scripts/deploy.sh). + $release = basename(base_path()); + + return preg_match('/^\d{14}-[0-9a-f]{7,40}$/', $release) === 1 ? $release : null; + } + + /** + * The PHP command line program for the run (Strato: php-cli next to the web PHP). + */ + public static function php(): string + { + $configured = (string) config('fewo.sandbox.php', ''); + if ($configured !== '') { + return $configured; + } + + return PHP_SAPI === 'cli' ? PHP_BINARY : (is_file('/opt/RZphp84/bin/php-cli') ? '/opt/RZphp84/bin/php-cli' : 'php'); + } + + /** + * Environment of the run's process: what Laravel needs to boot – never database, mail or service credentials (the + * run's configuration replaces them anyway, this keeps them out of its environment, too). + * + * @return array + */ + private static function childEnvironment(): array + { + $blank = []; + foreach (array_keys(getenv()) as $key) { + if (preg_match('/^(DB_|MAIL_|REDIS_|AWS_|MAILBOX_|FEWO_MAILBOX|OPENAI|ANTHROPIC|OPENROUTER|N8N_|PIPELINE_)/', (string) $key) === 1) { + $blank[$key] = false; + } + } + + return $blank; + } + + /** + * One run per landlord and at most SLOTS on the server, as file locks (they end with the process). + * + * @return list the held locks (landlord, slot) + */ + private function slot(int $tenant): array + { + $directory = storage_path('app/sandbox/slots'); + File::ensureDirectoryExists($directory, 0700); + $tenantLock = fopen($directory.'/tenant-'.$tenant.'.lock', 'c'); + if ($tenantLock === false || ! flock($tenantLock, LOCK_EX | LOCK_NB)) { + throw new RuntimeException('Für diesen Vermieter läuft bereits ein Test. Bitte einen Moment warten.'); + } + for ($index = 1; $index <= self::SLOTS; $index++) { + $slot = fopen($directory.'/slot-'.$index.'.lock', 'c'); + if ($slot !== false && flock($slot, LOCK_EX | LOCK_NB)) { + return [$tenantLock, $slot]; + } + if ($slot !== false) { + fclose($slot); + } + } + fclose($tenantLock); + + throw new RuntimeException('Der Prozess-Tester ist gerade belegt. Bitte gleich noch einmal versuchen.'); + } +} diff --git a/app/Process/Tester/ProcessSandboxDriver.php b/app/Process/Tester/ProcessSandboxDriver.php new file mode 100644 index 0000000..465fb5c --- /dev/null +++ b/app/Process/Tester/ProcessSandboxDriver.php @@ -0,0 +1,207 @@ + every mail of the run (simulated: the only mailer is `array`) */ + private array $sent = []; + + /** + * @param array $input input.json of the run + * @return array the report + */ + public function run(array $input): array + { + $this->assertSandbox(); + $started = microtime(true); + // Mails are collected when they are sent: the transport is rebuilt whenever the landlord context changes. + Event::listen(MessageSent::class, function (MessageSent $event): void { + $this->sent[] = $event->message; + EffectLedger::record('mail', ['subject' => (string) $event->message->getSubject()]); + }); + SandboxSnapshot::seed($input['snapshot']); + Date::setTestNow(CarbonImmutable::parse((string) $input['start'])); + + $tenant = Tenant::query()->findOrFail($input['snapshot']['tenant_id']); + $channel = Channel::withoutGlobalScopes()->findOrFail($input['snapshot']['channel_id']); + $intake = IntakeKind::from((string) $input['snapshot']['intake']); + $class = ScenarioCatalogue::find((string) $input['scenario']) ?? throw new \RuntimeException('Unbekanntes Szenario.'); + /** @var Scenario $scenario */ + $scenario = new $class; + + return app(TenantContext::class)->run($tenant, function () use ($input, $channel, $intake, $scenario, $started): array { + $property = Property::query()->findOrFail($channel->property_id); + $context = new SandboxContext($channel, $intake, $property, (array) $input['inputs']); + $events = array_slice($scenario->events($context->inputs), 0, min(self::MAX_EVENTS, max(1, (int) $input['steps']))); + $timeline = []; + $aborted = null; + + if (filled(config('sandbox.probe'))) { + // Negative tests only: a probe tries forbidden accesses before the scenario. + rescue(fn () => app((string) config('sandbox.probe'))->handle($context), report: false); + } + + foreach ($events as $event) { + $error = null; + try { + ($event->run)($context); + } catch (Throwable $exception) { + $error = class_basename($exception).': '.$exception->getMessage(); + } + $timeline[] = ['label' => $event->label, 'at' => now()->format('d.m.Y H:i'), 'error' => $error, ...$this->capture($context)]; + + if (EffectLedger::violations() !== []) { + $aborted = 'Unzulässiger Zugriff – Lauf abgebrochen.'; + break; + } + if (microtime(true) - $started > self::MAX_SECONDS) { + $aborted = 'Laufzeitgrenze erreicht – Lauf abgebrochen.'; + break; + } + } + + $booking = $context->booking?->fresh(); + + return [ + 'scenario' => ['key' => $scenario::key(), 'label' => $scenario::label(), 'inputs' => $context->inputs, 'available_events' => count($scenario->events($context->inputs))], + 'plan' => $booking === null ? null : $this->plan($booking), + 'timeline' => $timeline, + 'result' => $booking === null ? null : ['status' => $booking->status->getLabel(), 'situation' => CaseActivities::situation($booking), 'next' => CaseActivities::next($booking)?->label], + 'violations' => EffectLedger::violations(), + 'aborted' => $aborted ?? (EffectLedger::violations() !== [] ? 'Unzulässiger Zugriff – Lauf abgebrochen.' : null), + ]; + }); + } + + /** + * Refuses to run unless the process really is a sandbox (defence in depth behind SandboxBootstrapper). + */ + private function assertSandbox(): void + { + $connections = array_keys((array) config('database.connections')); + $mailers = array_keys((array) config('mail.mailers')); + if (config('database.default') !== 'sandbox' || $connections !== ['sandbox'] || $mailers !== ['array'] || config('cache.default') !== 'array' || blank(config('sandbox.run'))) { + throw new \RuntimeException('Sicherheitsprüfung des Prozess-Testers fehlgeschlagen: der Prozess ist nicht isoliert ('.json_encode(['db' => config('database.default'), 'connections' => $connections, 'mailers' => $mailers, 'cache' => config('cache.default')]).').'); + } + } + + /** + * @return array + */ + private function plan(Booking $booking): array + { + $plan = ProcessPlan::of($booking); + $profile = $booking->process(); + + return [ + 'model' => $plan->model, + 'label' => $plan->modelDefinition()::label(), + 'version' => $plan->modelVersion, + 'variant' => $plan->variant, + 'modules' => $plan->modules, + 'case_type' => strtoupper($profile->caseType->value), + 'configuration' => collect(ProcessSetting::cases())->map(fn ($setting): array => ['question' => $setting->question(), 'value' => $setting->describe($profile->value($setting)), 'source' => ProcessProfile::sourceLabel($profile->source($setting))])->all(), + ]; + } + + /** + * The case after one event: its course, the skipped steps, the simulated mails and effects. + * + * @return array + */ + private function capture(SandboxContext $context): array + { + $booking = $context->booking?->fresh(); + $ledger = EffectLedger::entries(); + $effects = array_slice($ledger, $this->ledgerSeen); + $this->ledgerSeen = count($ledger); + + if ($booking === null) { + return ['activities' => [], 'skipped' => [], 'mails' => $this->mails(), 'effects' => $effects]; + } + + $caseContext = CaseContext::of($booking); + $catalogue = app(ProcessCatalogue::class); + $skipped = []; + foreach ($caseContext->plan->moduleKeys() as $key) { + if (! $catalogue->hasModule($key)) { + continue; + } + $module = $catalogue->module($key); + $reason = match (true) { + ! $caseContext->plan->enabled($key) => 'übersprungen (Konfiguration)', + ! $module->applies($caseContext) => 'trifft hier nicht zu', + default => null, + }; + if ($reason !== null) { + $skipped[] = ['label' => $module::definition()->label, 'reason' => $reason]; + } + } + + return [ + 'status' => $booking->status->getLabel(), + 'situation' => CaseActivities::situation($booking), + 'activities' => array_map(fn ($activity): array => ['label' => $activity->label, 'state' => $activity->state->getLabel(), 'state_key' => $activity->state->value, 'detail' => $activity->detail], CaseActivities::for($booking)), + 'skipped' => $skipped, + 'calendar' => ['occupying' => Booking::query()->occupying()->whereKey($booking->id)->exists(), 'hold_until' => $booking->isHoldActive() ? $booking->hold_expires_at->format('d.m.Y H:i') : null], + 'price' => ['total' => $booking->total, 'lines' => array_map(fn (array $line): array => ['label' => $line['label'] ?? '', 'amount' => $line['amount'] ?? 0], (array) ($booking->quote['lines'] ?? []))], + 'mails' => $this->mails(), + 'effects' => $effects, + ]; + } + + /** + * Mails sent since the last capture – simulated, never delivered. Links are shown as text only. + * + * @return list + */ + private function mails(): array + { + $new = array_slice($this->sent, $this->mailsSeen); + $this->mailsSeen = count($this->sent); + + return array_values(array_map(function (Email $email): array { + $text = trim(preg_replace('/\s+/', ' ', strip_tags((string) ($email->getTextBody() ?? $email->getHtmlBody() ?? ''))) ?? ''); + + return [ + 'subject' => (string) $email->getSubject(), + 'to' => implode(', ', array_map(fn ($address): string => $address->getAddress(), $email->getTo())), + 'excerpt' => mb_substr((string) preg_replace('~https?://\S+~', '[Link]', $text), 0, 400), + ]; + }, $new)); + } +} diff --git a/app/Process/Tester/SandboxBootstrapper.php b/app/Process/Tester/SandboxBootstrapper.php new file mode 100644 index 0000000..411f71a --- /dev/null +++ b/app/Process/Tester/SandboxBootstrapper.php @@ -0,0 +1,117 @@ +set('database.default', 'sandbox'); + $config->set('database.connections', ['sandbox' => [ + 'driver' => 'sqlite', + 'database' => $directory.'/db.sqlite', + 'prefix' => '', + 'foreign_key_constraints' => true, + ]]); + $config->set('database.redis', []); + + $config->set('mail.default', 'array'); + $config->set('mail.mailers', ['array' => ['transport' => 'array']]); + $config->set('mail.from', ['address' => 'tester@sandbox.invalid', 'name' => 'Prozess-Tester']); + $config->set('fewo.mail_redirect_to', null); + + $config->set('cache.default', 'array'); + $config->set('cache.stores', ['array' => ['driver' => 'array', 'serialize' => false]]); + $config->set('session.driver', 'array'); + $config->set('queue.default', 'sync'); + $config->set('queue.connections', ['sync' => ['driver' => 'sync']]); + $config->set('queue.failed', ['driver' => 'null']); + + $files = $directory.'/files'; + $config->set('filesystems.default', 'local'); + $config->set('filesystems.disks', [ + 'local' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true], + 'private' => ['driver' => 'local', 'root' => $files.'/private', 'throw' => true], + 'public' => ['driver' => 'local', 'root' => $files.'/public', 'throw' => true], + 'media' => ['driver' => 'local', 'root' => $files.'/media', 'throw' => true], + ]); + + $config->set('logging.default', 'sandbox'); + $config->set('logging.channels', [ + 'sandbox' => ['driver' => 'single', 'path' => $directory.'/log.txt', 'level' => 'debug'], + 'null' => ['driver' => 'monolog', 'handler' => NullHandler::class], + 'emergency' => ['path' => $directory.'/log.txt'], + ]); + + $config->set('app.key', 'base64:'.base64_encode(random_bytes(32))); + $config->set('app.previous_keys', []); + + // Secrets and outside services: blank. The scripted answers of the scenario replace them. + foreach (['services', 'fewo.mailbox', 'fewo.automation', 'fewo.llm'] as $key) { + if (is_array($config->get($key))) { + $config->set($key, array_map(fn (mixed $value): mixed => is_array($value) ? [] : null, (array) $config->get($key))); + } + } + + $config->set('sandbox', ['run' => $run, 'directory' => $directory, 'probe' => self::probe($app)]); + // Registered after every framework provider, so its bindings replace the managers before anything resolves them. + $config->set('app.providers', [...($config->get('app.providers') ?? ServiceProvider::defaultProviders()->toArray()), SandboxServiceProvider::class]); + } + + /** + * A probe that deliberately tries forbidden accesses – only for the negative tests of the test suite. + */ + private static function probe(Application $app): ?string + { + $probe = getenv('FEWO_SANDBOX_PROBE') ?: null; + + return $probe !== null && $app->environment('testing') && class_exists($probe) ? $probe : null; + } +} diff --git a/app/Process/Tester/SandboxChannelRegistry.php b/app/Process/Tester/SandboxChannelRegistry.php new file mode 100644 index 0000000..d271392 --- /dev/null +++ b/app/Process/Tester/SandboxChannelRegistry.php @@ -0,0 +1,22 @@ + $inputs + */ + public function __construct( + public readonly Channel $channel, + public readonly IntakeKind $intake, + public readonly Property $property, + public readonly array $inputs, + ) {} + + public function arrival(): CarbonImmutable + { + $value = (string) ($this->inputs['arrival'] ?? '+21 days'); + + return CarbonImmutable::parse($value, now()->getTimezone())->startOfDay(); + } + + public function departure(): CarbonImmutable + { + return $this->arrival()->addDays(max(1, (int) ($this->inputs['nights'] ?? 4))); + } + + public function guests(): int + { + return max(1, (int) ($this->inputs['guests'] ?? 2)); + } + + /** + * A request through the same action as the website's booking form. + * + * @param array $guest + */ + public function request(array $guest): Booking + { + return $this->booking = app(CreateReservation::class)->handle( + $this->property, + new StayRequest($this->arrival(), $this->departure(), $this->guests()), + ['first_name' => 'Testgast', 'last_name' => 'Sandbox', 'email' => 'gast@tester.invalid', ...$guest], + source: $this->channel->isWebsite() ? 'website' : 'channel', + originChannel: $this->channel->isWebsite() ? null : $this->channel, + ); + } + + /** + * Time passes: the clock moves on and the case-related schedulers run in the order of routes/console.php. + */ + public function travel(int $minutes): void + { + Date::setTestNow(now()->addMinutes($minutes)); + foreach (['bookings:expire-holds', 'bookings:auto-offers', 'cases:data-requests'] as $command) { + Artisan::call($command); + } + app(SendBookingReminders::class)->handle(); + app(PrepareStays::class)->handle(); + app(RequestReviews::class)->handle(); + } + + public function travelTo(CarbonImmutable $moment): void + { + $minutes = (int) max(0, now()->diffInMinutes($moment)); + $this->travel($minutes); + } +} diff --git a/app/Process/Tester/SandboxMailboxReader.php b/app/Process/Tester/SandboxMailboxReader.php new file mode 100644 index 0000000..6d8449e --- /dev/null +++ b/app/Process/Tester/SandboxMailboxReader.php @@ -0,0 +1,26 @@ +|null)> host => answer */ + private static array $answers = []; + + /** + * @param callable(Request): (PromiseInterface|array|null) $answer + */ + public static function script(string $host, callable $answer): void + { + self::$answers[$host] = $answer; + } + + public static function reset(): void + { + self::$answers = []; + } + + public static function answer(Request $request): ?PromiseInterface + { + $host = (string) parse_url($request->url(), PHP_URL_HOST); + $answer = isset(self::$answers[$host]) ? (self::$answers[$host])($request) : null; + + return match (true) { + $answer === null => null, + $answer instanceof PromiseInterface => $answer, + default => Http::response($answer), + }; + } +} diff --git a/app/Process/Tester/SandboxServiceProvider.php b/app/Process/Tester/SandboxServiceProvider.php new file mode 100644 index 0000000..1041fbd --- /dev/null +++ b/app/Process/Tester/SandboxServiceProvider.php @@ -0,0 +1,126 @@ +app->singleton('db', fn ($app): DatabaseManager => new class($app, $app['db.factory'], $file) extends DatabaseManager + { + public function __construct($app, $factory, private string $file) + { + parent::__construct($app, $factory); + } + + public function connection($name = null) + { + $name ??= $this->getDefaultConnection(); + [$database] = $this->parseConnectionName($name); + if ($database !== 'sandbox') { + throw SandboxViolation::record('database', "Verbindung [{$name}] ist im Prozess-Tester nicht erlaubt."); + } + + return parent::connection($name); + } + + /** Every (re)connected sandbox connection gets the guard: each statement must go to the run's own file. */ + protected function configure(Connection $connection, $type) + { + $connection = parent::configure($connection, $type); + $expected = realpath($this->file) ?: $this->file; + $connection->beforeExecuting(function (string $query, array $bindings, Connection $connection) use ($expected): void { + $actual = (string) $connection->getConfig('database'); + if ((realpath($actual) ?: $actual) !== $expected) { + throw SandboxViolation::record('database', 'Abfrage an eine andere Datenbankdatei: '.basename($actual)); + } + }); + + return $connection; + } + }); + + $this->app->singleton('filesystem', fn ($app): FilesystemManager => new class($app) extends FilesystemManager + { + public function build($config) + { + $root = is_array($config) ? (string) ($config['root'] ?? '') : ''; + if (! str_starts_with(str_replace('\\', '/', $root), str_replace('\\', '/', (string) config('sandbox.directory')))) { + throw SandboxViolation::record('file', 'Dateiablage außerhalb des Laufverzeichnisses ist im Prozess-Tester nicht erlaubt.'); + } + + return parent::build($config); + } + }); + + // Mail and cache come from deferred providers, which would register their managers again on first use: they are + // loaded and replaced just before the application boots, when the list of deferred services is complete. + $this->app->booting(function (): void { + foreach (['mail.manager', 'cache'] as $service) { + $this->app->loadDeferredProvider($service); + } + + $this->app->singleton('mail.manager', fn ($app): MailManager => new class($app) extends MailManager + { + public function mailer($name = null) + { + if (($name ?? $this->getDefaultDriver()) !== 'array') { + throw SandboxViolation::record('mail', "Mailer [{$name}] ist im Prozess-Tester nicht erlaubt."); + } + + return parent::mailer($name); + } + }); + + $this->app->singleton('cache', fn ($app): CacheManager => new class($app) extends CacheManager + { + public function store($name = null) + { + if (($name ?? $this->getDefaultDriver()) !== 'array') { + throw SandboxViolation::record('cache', "Cache [{$name}] ist im Prozess-Tester nicht erlaubt."); + } + + return parent::store($name); + } + }); + }); + + $this->app->singleton(MailboxReader::class, fn (): MailboxReader => new SandboxMailboxReader); + $this->app->singleton(ChannelRegistry::class, fn (): ChannelRegistry => new SandboxChannelRegistry); + } + + public function boot(): void + { + // No network: only the scenario's scripted answers (ProcessSandboxDriver::script) are served. + Http::preventStrayRequests(); + Http::fake(function (Request $request) { + $answer = SandboxNetwork::answer($request); + if ($answer === null) { + throw SandboxViolation::record('network', 'Netzzugriff ohne Szenario-Antwort: '.$request->method().' '.parse_url($request->url(), PHP_URL_HOST)); + } + EffectLedger::record('network', ['method' => $request->method(), 'host' => parse_url($request->url(), PHP_URL_HOST), 'scripted' => true]); + + return $answer; + }); + } +} diff --git a/app/Process/Tester/SandboxSnapshot.php b/app/Process/Tester/SandboxSnapshot.php new file mode 100644 index 0000000..dd78a71 --- /dev/null +++ b/app/Process/Tester/SandboxSnapshot.php @@ -0,0 +1,142 @@ + ['mailbox_password'], + 'channels' => ['previous_export_token', 'export_snapshot', 'ical_analysis'], + 'blocked_periods' => ['ical_properties', 'ical_raw', 'ical_interpretation', 'linked_booking_id', 'guest_name'], + ]; + + /** Encrypted columns that are carried as plain values and encrypted again in the run. */ + public const ENCRYPTED = ['tenants' => ['bank_account_holder', 'bank_iban', 'bank_bic', 'bank_name', 'tax_note']]; + + /** + * @param array $draft model, variant, steps, settings of the tested channel and intake kind + * @return array{tenant_id: int, channel_id: int, intake: string, tables: array>>, encrypted: array>} + */ + public static function build(Channel $channel, IntakeKind $intake, array $draft): array + { + $tenant = Tenant::query()->findOrFail($channel->tenant_id); + $propertyIds = DB::table('properties')->where('tenant_id', $tenant->id)->pluck('id')->all(); + $tables = []; + + foreach (self::TABLES as $table) { + if (! Schema::hasTable($table)) { + continue; + } + $query = DB::table($table); + $query = match (true) { + $table === 'tenants' => $query->where('id', $tenant->id), + Schema::hasColumn($table, 'tenant_id') => $query->where('tenant_id', $tenant->id), + Schema::hasColumn($table, 'property_id') => $query->whereIn('property_id', $propertyIds), + default => null, + }; + if ($query === null) { + continue; + } + $tables[$table] = $query->orderBy('id')->get()->map(fn (object $row): array => self::clean($table, (array) $row))->all(); + } + + // The tested channel carries the draft (also unsaved) – and creates cases from portal mails in the run. + foreach ($tables['channels'] ?? [] as $index => $row) { + if ((int) $row['id'] === $channel->id) { + $overrides = (array) json_decode((string) ($row['process_overrides'] ?? '[]'), true); + $overrides[$intake->value] = [...array_filter((array) ($draft['settings'] ?? []), fn (mixed $value): bool => $value !== null && $value !== ''), 'model' => $draft['model'] ?? null, 'variant' => $draft['variant'] ?? 'standard', 'steps' => (array) ($draft['steps'] ?? [])]; + $tables['channels'][$index]['process_overrides'] = json_encode($overrides); + $tables['channels'][$index]['case_intake'] = 'create'; + // In the run the tested portal is active, so its (synthetic) booking mails are recognised. + $tables['channels'][$index]['is_active'] = 1; + $tables['channels'][$index]['status'] = 'active'; + $settings = (array) json_decode((string) ($row['settings'] ?? '[]'), true); + $settings['email_senders'] = filled($settings['email_senders'] ?? null) ? $settings['email_senders'] : 'portal.invalid'; + $tables['channels'][$index]['settings'] = json_encode($settings); + } + } + + return ['tenant_id' => $tenant->id, 'channel_id' => $channel->id, 'intake' => $intake->value, 'tables' => $tables, 'encrypted' => self::ENCRYPTED]; + } + + /** + * @param array $row + * @return array + */ + private static function clean(string $table, array $row): array + { + foreach (self::DROPPED[$table] ?? [] as $column) { + if (array_key_exists($column, $row)) { + $row[$column] = null; + } + } + foreach (self::ENCRYPTED[$table] ?? [] as $column) { + if (filled($row[$column] ?? null)) { + try { + $row[$column] = Crypt::decryptString((string) $row[$column]); + } catch (Throwable) { + $row[$column] = null; + } + } + } + if ($table === 'channels' && array_key_exists('export_token', $row)) { + // The real export link is never part of a run: a random one of no use outside it. + $row['export_token'] = bin2hex(random_bytes(20)); + } + if ($table === 'tenants') { + // The run is always in test operation and writes only to its own test address. + $row['operating_mode'] = 'test'; + $row['test_recipient'] = 'tester@sandbox.invalid'; + } + + return $row; + } + + /** + * Writes the snapshot into the run's own database (inside the tester process only). + * + * @param array{tables: array>>, encrypted: array>} $snapshot + */ + public static function seed(array $snapshot): void + { + if (config('database.default') !== 'sandbox') { + throw SandboxViolation::record('database', 'Einspielen nur in die Testdatenbank.'); + } + + Schema::disableForeignKeyConstraints(); + foreach ($snapshot['tables'] as $table => $rows) { + if (! Schema::hasTable($table)) { + continue; + } + $columns = array_flip(Schema::getColumnListing($table)); + foreach ($rows as $row) { + foreach ($snapshot['encrypted'][$table] ?? [] as $column) { + if (filled($row[$column] ?? null)) { + $row[$column] = Crypt::encryptString((string) $row[$column]); + } + } + DB::table($table)->insert(array_intersect_key($row, $columns)); + } + } + Schema::enableForeignKeyConstraints(); + } +} diff --git a/app/Process/Tester/SandboxViolation.php b/app/Process/Tester/SandboxViolation.php new file mode 100644 index 0000000..6513ddc --- /dev/null +++ b/app/Process/Tester/SandboxViolation.php @@ -0,0 +1,20 @@ + $kind, 'message' => $message]); + + return new self('Prozess-Tester: unzulässiger Zugriff ('.$kind.'): '.$message); + } +} diff --git a/app/Process/Tester/ScenarioCatalogue.php b/app/Process/Tester/ScenarioCatalogue.php new file mode 100644 index 0000000..3d59e32 --- /dev/null +++ b/app/Process/Tester/ScenarioCatalogue.php @@ -0,0 +1,55 @@ +> */ + public const SCENARIOS = [CompleteRequest::class, MissingAddress::class, PortalInquiry::class, ReturningGuest::class, CommunicationFailure::class, PortalBooking::class]; + + /** + * @return array> + */ + public static function for(IntakeKind $intake, bool $website): array + { + $scenarios = []; + foreach (self::SCENARIOS as $class) { + if (! in_array($intake, $class::intakes(), true)) { + continue; + } + // A website request is never a portal's request and vice versa. + if (($class === PortalInquiry::class && $website) || ($website === false && $intake === IntakeKind::Inquiry && in_array($class, [CompleteRequest::class, MissingAddress::class, ReturningGuest::class, CommunicationFailure::class], true))) { + continue; + } + $scenarios[$class::key()] = $class; + } + + return $scenarios; + } + + /** + * @return class-string|null + */ + public static function find(string $key): ?string + { + foreach (self::SCENARIOS as $class) { + if ($class::key() === $key) { + return $class; + } + } + + return null; + } +} diff --git a/app/Process/Tester/Scenarios/CommunicationFailure.php b/app/Process/Tester/Scenarios/CommunicationFailure.php new file mode 100644 index 0000000..47bc6a1 --- /dev/null +++ b/app/Process/Tester/Scenarios/CommunicationFailure.php @@ -0,0 +1,49 @@ + $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])), + ]; + } +} diff --git a/app/Process/Tester/Scenarios/CompleteRequest.php b/app/Process/Tester/Scenarios/CompleteRequest.php new file mode 100644 index 0000000..d97ac93 --- /dev/null +++ b/app/Process/Tester/Scenarios/CompleteRequest.php @@ -0,0 +1,57 @@ + $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])), + new ScenarioEvent('Sie senden das Angebot (falls es nicht automatisch ging)', function (SandboxContext $context): void { + $booking = $context->booking->fresh(); + if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->process()->preReservation()) { + app(SendOffer::class)->handle($booking); + } + }), + new ScenarioEvent('Gast nimmt das Angebot an', function (SandboxContext $context): void { + $booking = $context->booking->fresh(); + if ($booking->status === BookingStatus::OfferSent) { + app(AcceptOffer::class)->handle($booking, $booking->offer_version); + } + }), + new ScenarioEvent('Zwei Tage vor der Anreise', fn (SandboxContext $context) => $context->travelTo($context->arrival()->subDays(2)->setTime(9, 0))), + new ScenarioEvent('Drei Tage nach der Abreise', fn (SandboxContext $context) => $context->travelTo($context->departure()->addDays(3)->setTime(9, 0))), + ]; + } +} diff --git a/app/Process/Tester/Scenarios/MissingAddress.php b/app/Process/Tester/Scenarios/MissingAddress.php new file mode 100644 index 0000000..60cd9f0 --- /dev/null +++ b/app/Process/Tester/Scenarios/MissingAddress.php @@ -0,0 +1,57 @@ + ['label' => 'Antwort des Gastes nach (Stunden)', 'default' => 26, 'type' => 'int'], + 'answer_by' => ['label' => 'Antwort über', 'default' => 'link', 'type' => 'select', 'options' => ['link' => 'Link im Formular', 'email' => 'E-Mail (ausgewertete Angaben)']], + ]; + } + + public function events(array $inputs): array + { + return [ + new ScenarioEvent('Gast fragt ohne Anschrift an', fn (SandboxContext $context) => $context->request([])), + new ScenarioEvent('Zwei Stunden vergehen (Klärungsfrist)', fn (SandboxContext $context) => $context->travel(125)), + new ScenarioEvent('Gast antwortet mit seiner Anschrift', function (SandboxContext $context) use ($inputs): void { + $context->travel(max(0, (int) ($inputs['answer_after_hours'] ?? 26) * 60 - 125)); + app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.street' => 'Teststraße 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], ($inputs['answer_by'] ?? 'link') === 'email' ? FactSource::Email : FactSource::GuestLink); + }), + new ScenarioEvent('Die Angebotsfrist vergeht ohne Annahme', fn (SandboxContext $context) => $context->travel(73 * 60)), + ]; + } +} diff --git a/app/Process/Tester/Scenarios/PortalBooking.php b/app/Process/Tester/Scenarios/PortalBooking.php new file mode 100644 index 0000000..f62c380 --- /dev/null +++ b/app/Process/Tester/Scenarios/PortalBooking.php @@ -0,0 +1,85 @@ + ['label' => 'Gesamtpreis laut Portal (€)', 'default' => 980, 'type' => 'int'], + 'cancellation' => ['label' => 'Portal meldet eine Stornierung', 'default' => false, 'type' => 'bool'], + ]; + } + + public function events(array $inputs): array + { + $total = max(1, (int) ($inputs['portal_total'] ?? 980)) * 100; + $events = [ + new ScenarioEvent('Buchungsmail des Portals kommt an', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Neue Buchung: '.$context->property->name, $this->text($context))), + new ScenarioEvent('Dieselbe Buchungsmail kommt noch einmal', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Neue Buchung: '.$context->property->name, $this->text($context))), + new ScenarioEvent('Gastdaten laut Portal', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.first_name' => 'Testgast', 'guest.last_name' => 'Portal', 'guest.email' => 'portalgast@tester.invalid', 'booking.guests' => (string) $context->guests()], FactSource::PortalMail)), + new ScenarioEvent('Portal meldet Preis, Gastzahlung und angekündigte Auszahlung', fn (SandboxContext $context) => app(RecordPortalAmounts::class)->handle($context->booking->fresh(), $total, [['kind' => 'payout_announced', 'amount' => (int) round($total * 0.9)]], [['amount' => (int) round($total * 0.4), 'paid_on' => now()->toDateString()]], $context->channel->name)), + ]; + if ((bool) ($inputs['cancellation'] ?? false)) { + $events[] = new ScenarioEvent('Portal meldet eine Stornierung', fn (SandboxContext $context) => $this->sendPortalMail($context, 'Buchung storniert: '.$this->reference($context), 'Die Buchung vom '.$context->arrival()->format('d.m.Y').' bis '.$context->departure()->format('d.m.Y').' wurde storniert. Buchungsnummer: '.$this->reference($context))); + } + $events[] = new ScenarioEvent('Drei Tage nach der Abreise', fn (SandboxContext $context) => $context->travelTo($context->departure()->addDays(3)->setTime(9, 0))); + + return $events; + } + + private function reference(SandboxContext $context): string + { + return 'TEST-'.$context->arrival()->format('md'); + } + + private function text(SandboxContext $context): string + { + return "Gast: Testgast Portal\nAnreise: ".$context->arrival()->format('d.m.Y')."\nAbreise: ".$context->departure()->format('d.m.Y')."\nBuchungsnummer: ".$this->reference($context); + } + + private function sendPortalMail(SandboxContext $context, string $subject, string $text): void + { + $senders = array_values(array_filter(array_map('trim', explode(',', (string) ($context->channel->setting('email_senders') ?? ''))))); + $sender = 'buchung@'.($senders[0] ?? 'portal.invalid'); + app(ProcessPortalMail::class)->handle(new PortalMail('<'.md5($subject).'@tester.invalid>', $sender, $subject, $text, CarbonImmutable::now())); + $context->booking = Booking::query()->latest('id')->first() ?? $context->booking; + } +} diff --git a/app/Process/Tester/Scenarios/PortalInquiry.php b/app/Process/Tester/Scenarios/PortalInquiry.php new file mode 100644 index 0000000..d71dd75 --- /dev/null +++ b/app/Process/Tester/Scenarios/PortalInquiry.php @@ -0,0 +1,47 @@ +booking = app(TakeOverPortalInquiry::class)->handle($context->channel, $context->arrival(), $context->departure(), 'ANF-'.$context->arrival()->format('md')); + }), + new ScenarioEvent('Kontaktdaten laut Portal', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.first_name' => 'Testgast', 'guest.last_name' => 'Anfrage', 'guest.email' => 'anfrage@tester.invalid', 'booking.guests' => (string) $context->guests()], FactSource::PortalMail)), + new ScenarioEvent('Gast ergänzt seine Anschrift', fn (SandboxContext $context) => app(ContributeCaseFacts::class)->handle($context->booking->fresh(), ['guest.street' => 'Teststraße 1', 'guest.postal_code' => '18225', 'guest.city' => 'Kühlungsborn', 'guest.country' => 'DE'], FactSource::GuestLink)), + ]; + } +} diff --git a/app/Process/Tester/Scenarios/ReturningGuest.php b/app/Process/Tester/Scenarios/ReturningGuest.php new file mode 100644 index 0000000..2486bd1 --- /dev/null +++ b/app/Process/Tester/Scenarios/ReturningGuest.php @@ -0,0 +1,64 @@ + ['label' => 'Gast war schon einmal da', 'default' => true, 'type' => 'bool']]; + } + + public function events(array $inputs): array + { + return [ + new ScenarioEvent('Früherer Aufenthalt (nur in den Testdaten)', function (SandboxContext $context) use ($inputs): void { + if (! (bool) ($inputs['returning'] ?? true)) { + return; + } + $guest = Guest::query()->create(['tenant_id' => $context->property->tenant_id, 'first_name' => 'Testgast', 'last_name' => 'Sandbox', 'email' => 'gast@tester.invalid']); + Booking::query()->create(['tenant_id' => $context->property->tenant_id, 'property_id' => $context->property->id, 'guest_id' => $guest->id, 'status' => BookingStatus::Completed, 'intake' => 'inquiry', + 'arrival' => now()->subYear()->toDateString(), 'departure' => now()->subYear()->addDays(7)->toDateString(), 'guests' => 2, 'total' => 80000, 'deposit' => 20000, 'completed_at' => now()->subYear()->addDays(8)]); + }), + new ScenarioEvent('Gast fragt mit allen Angaben an', fn (SandboxContext $context) => $context->request(['street' => 'Teststraße 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn', 'country' => 'DE'])), + new ScenarioEvent('Sie senden das Angebot (falls es nicht automatisch ging)', function (SandboxContext $context): void { + $booking = $context->booking->fresh(); + if ($booking->status === BookingStatus::Reserved && $booking->offer_version === 0 && $booking->process()->preReservation()) { + app(SendOffer::class)->handle($booking); + } + }), + ]; + } +} diff --git a/app/Process/Tester/Scenarios/Scenario.php b/app/Process/Tester/Scenarios/Scenario.php new file mode 100644 index 0000000..c11241f --- /dev/null +++ b/app/Process/Tester/Scenarios/Scenario.php @@ -0,0 +1,42 @@ + */ + abstract public static function intakes(): array; + + /** + * Inputs the landlord may change, with their defaults. + * + * @return array}> + */ + public static function inputs(): array + { + return [ + 'arrival' => ['label' => 'Anreise', 'default' => '+21 days', 'type' => 'date'], + 'nights' => ['label' => 'Nächte', 'default' => 4, 'type' => 'int'], + 'guests' => ['label' => 'Personen', 'default' => 2, 'type' => 'int'], + ]; + } + + /** + * @param array $inputs + * @return list + */ + abstract public function events(array $inputs): array; +} diff --git a/app/Process/Tester/Scenarios/ScenarioEvent.php b/app/Process/Tester/Scenarios/ScenarioEvent.php new file mode 100644 index 0000000..08864cb --- /dev/null +++ b/app/Process/Tester/Scenarios/ScenarioEvent.php @@ -0,0 +1,17 @@ +app->make(TenantConfig::class)->refresh(); } catch (Throwable) { // no database yet (package discovery, first install) diff --git a/app/Support/SystemSettings.php b/app/Support/SystemSettings.php index cc3675d..2bfc624 100644 --- a/app/Support/SystemSettings.php +++ b/app/Support/SystemSettings.php @@ -30,6 +30,7 @@ class SystemSettings 'fewo.retention.inquiry_months' => ['Nicht gebuchte Anfragen löschen nach (Monate)', 'int', 'Löschfristen', ''], 'fewo.retention.portal_email_excerpt_days' => ['Portal-Mail-Auszug löschen nach (Tage)', 'int', 'Löschfristen', ''], 'fewo.retention.attribution_months' => ['Herkunftsangaben löschen nach (Monate)', 'int', 'Löschfristen', ''], + 'fewo.retention.process_test_run_days' => ['Berichte des Prozess-Testers löschen nach (Tage)', 'int', 'Löschfristen', 'Nur synthetische Testdaten; Grundlage 30 Tage (Entscheidung O3).'], 'fewo.spam.min_seconds' => ['Mindestzeit im Formular (Sekunden)', 'int', 'Bot-Schutz', 'Untergrenze; ein Mandant kann länger warten lassen.'], 'fewo.spam.per_ip_per_hour' => ['Anfragen je IP und Stunde', 'int', 'Bot-Schutz', ''], diff --git a/bootstrap/app.php b/bootstrap/app.php index 1c6e525..2d3342e 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -3,12 +3,14 @@ use App\Http\Middleware\ForceHttps; use App\Http\Middleware\ResolveTheme; use App\Http\Middleware\SecurityHeaders; +use App\Process\Tester\SandboxBootstrapper; use Illuminate\Foundation\Application; +use Illuminate\Foundation\Bootstrap\LoadConfiguration; use Illuminate\Foundation\Configuration\Exceptions; use Illuminate\Foundation\Configuration\Middleware; use Illuminate\Http\Request; -return Application::configure(basePath: dirname(__DIR__)) +$app = Application::configure(basePath: dirname(__DIR__)) ->withRouting( web: __DIR__.'/../routes/web.php', commands: __DIR__.'/../routes/console.php', @@ -30,3 +32,11 @@ fn (Request $request) => $request->is('api/*') || $request->expectsJson(), ); })->create(); + +// Process tester (Architektur V2, docs/Prozessarchitektur/Architektur/04 §3): a process started for a tester run is +// turned into a sandbox right after its configuration is loaded – before any provider registers or anything resolves. +if (SandboxBootstrapper::active()) { + $app->afterBootstrapping(LoadConfiguration::class, fn (Application $app) => SandboxBootstrapper::configure($app)); +} + +return $app; diff --git a/config/fewo.php b/config/fewo.php index 6db4510..48a5852 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -81,6 +81,16 @@ 'portal_email_excerpt_days' => (int) env('FEWO_RETENTION_PORTAL_EMAIL_EXCERPT_DAYS', 90), // Marketing attribution (UTM parameters, "how did you hear about us") is removed after … months. 'attribution_months' => (int) env('FEWO_RETENTION_ATTRIBUTION_MONTHS', 24), + // Reports of the process tester (synthetic data only) are deleted after … days (decision O3). + 'process_test_run_days' => (int) env('FEWO_RETENTION_PROCESS_TEST_RUN_DAYS', 30), + ], + + /* + | Process tester (Architektur V2): the PHP command line program its isolated runs start with. Empty: the running PHP + | in the console, on Strato /opt/RZphp84/bin/php-cli. + */ + 'sandbox' => [ + 'php' => env('FEWO_SANDBOX_PHP'), ], /* diff --git a/database/migrations/2026_11_07_100000_create_process_test_runs_table.php b/database/migrations/2026_11_07_100000_create_process_test_runs_table.php new file mode 100644 index 0000000..8b8901b --- /dev/null +++ b/database/migrations/2026_11_07_100000_create_process_test_runs_table.php @@ -0,0 +1,37 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->foreignId('channel_id')->nullable()->constrained()->nullOnDelete(); + $table->foreignId('user_id')->nullable()->constrained()->nullOnDelete(); + $table->string('intake', 20); + $table->string('scenario', 60); + $table->json('configuration'); + $table->json('inputs'); + $table->unsignedSmallInteger('steps'); + $table->json('report'); + $table->string('outcome', 20); + $table->string('release', 80)->nullable(); + $table->timestamps(); + $table->index(['tenant_id', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('process_test_runs'); + } +}; diff --git a/docs/BETRIEB.md b/docs/BETRIEB.md index 04ec6d8..20262ac 100644 --- a/docs/BETRIEB.md +++ b/docs/BETRIEB.md @@ -204,12 +204,21 @@ ## 7a. Datensicherung, Löschfristen, Automationen ``` Regelmäßig z. B. per Aufgabenplanung des NAS/PC ausführen (braucht den SSH-Schlüssel aus §4). - **Löschfristen** (Vorschläge, rechtlich zu bestätigen – `config/fewo.php` bzw. `.env`): Gästedaten 10 Jahre nach letztem Aufenthalt (`FEWO_GUEST_RETENTION_YEARS`), nie verbindlich gewordene Anfragen/Angebote 6 Monate (`FEWO_RETENTION_INQUIRY_MONTHS`), Textauszüge von Portal-Mails 90 Tage (`FEWO_RETENTION_PORTAL_EMAIL_EXCERPT_DAYS`), Herkunftsangaben/UTM 24 Monate (`FEWO_RETENTION_ATTRIBUTION_MONTHS`). Läuft täglich 03:00. Anonymisierung ersetzt Name, Kontaktdaten, Nachrichten, Notizen, Herkunft und Bewertungs-Anzeigenamen; Buchung, Preise und Zahlungen bleiben als Beleg. +- **Testberichte des Prozess-Testers:** 30 Tage (`FEWO_RETENTION_PROCESS_TEST_RUN_DAYS`, Entscheidung O3; System › Einstellungen › Löschfristen), gelöscht vom selben täglichen Lauf. Sie enthalten nur synthetische Testdaten. - **Bot-Schutz der Buchungsanfrage** (ohne externen Captcha-Dienst, `config/fewo.php › spam`): verstecktes Köderfeld, Zeitsperre (Absenden schneller als 4 s nach dem Öffnen = Bot, wird still ignoriert), höchstens 5 Anfragen/Stunde je IP, 3/Tag je E-Mail-Adresse, 30/Stunde insgesamt, höchstens 2 gleichzeitig vorgemerkte Anfragen je E-Mail-Adresse (sonst könnten Bots den Kalender blockieren), keine Links in Namen und höchstens 1 Link in der Nachricht. - **Automationen (n8n):** Token bitte als Header `Authorization: Bearer ` senden (landet nicht in Server-Logs); `?token=` funktioniert übergangsweise weiter. - **HTTPS:** `App\Http\Middleware\ForceHttps` leitet HTTP-Aufrufe (GET/HEAD 301, sonst 308) auf HTTPS um, in der Anwendung statt in der `.htaccess` – diese wird bei jedem Deployment neu geschrieben. Abschaltbar mit `FEWO_FORCE_HTTPS=false`. Zusätzlich sollte in Strato „SSL erzwingen“ aktiv sein, falls das Paket die Option anbietet. - **Restore-Test (30.10.2026, lokal, SQLite):** Dump mit `backup:database` aus einer frisch migrierten und gesäten Datenbank, in eine leere Datei zurückgespielt: 42 von 42 Tabellen, alle Zeilenzahlen gleich, 66 Migrationen „Ran“, keine ausstehend. Für **MariaDB (Strato) steht der Nachweis noch aus**: Dump mit `backup:database` erzeugen, in eine zweite, leere Strato-Datenbank per phpMyAdmin/`mysql` einspielen und Zeilenzahlen von `bookings`, `guests`, `pages`, `channels` vergleichen. Die Produktionsdatenbank wird dabei nicht verändert. - **Fotos:** Beim Hochladen werden Metadaten (GPS, Kamera) aus dem Original entfernt; bestehende Fotos einmalig: `php artisan photos:strip-metadata` (`--force` bearbeitet auch bereits markierte erneut). Hinweis: bewusst mit GD – Imagick (auf Strato installiert) behält EXIF beim Speichern. +## 7b. Prozess-Tester und Prozesskern (Architektur V2) + +- **Was er ist:** Kanal › Ablauf › „Ablauf testen“ spielt ausgedachte Vorgänge mit der (auch ungespeicherten) Einstellung durch – in einem **eigenen PHP-Prozess** (`php artisan process:sandbox-run`), der nur eine eigene SQLite-Datei je Lauf (`shared/storage/app/sandbox/runs//`), den Mailer `array`, den Cache `array` und Netzantworten des Szenarios kennt. Details: `docs/Prozessarchitektur/Architektur/04_PROZESS_TESTER.md`. +- **Voraussetzungen auf dem Server** (sonst ist der Tester gesperrt und sagt warum): PHP-Erweiterung `pdo_sqlite` (CLI: vorhanden, 04.11.2026), erlaubtes `proc_open` im Web-PHP, PHP-CLI unter `/opt/RZphp84/bin/php-cli` (abweichend: `FEWO_SANDBOX_PHP` in `shared/.env`), Vorlage `shared/storage/app/sandbox/template.sqlite` – sie entsteht bei jedem Deployment (`php artisan process:sandbox-template` nach `migrate`, `pipeline.toml`). +- **Grenzen (Restrisiko, dokumentiert):** Shared Hosting bietet keine Trennung auf Betriebssystemebene. Der Testprozess läuft unter demselben Systembenutzer; nativer PHP-Code könnte `shared/.env` lesen. Die Anwendung verhindert das über die ersetzte Konfiguration, entzogene Umgebungsvariablen und den statischen `SideEffectPathsTest`, der native Netz-, Mail-, Datenbank- und Dateizugriffe in `app/` verbietet. +- **Grenzen der Last:** höchstens 1 Lauf je Mandant, 3 gleichzeitig, 20 s und 60 Ereignisse je Lauf, Abbruch nach 30 s. Abgebrochene Laufverzeichnisse räumt der nächste Lauf (älter als 1 h). +- **Prüfbefehle:** `bash scripts/deploy.sh staging artisan process:check --cases` (Katalog und eingefrorene Pläne aller Vorgänge), `… artisan process:fingerprint` (Prüfsummen von Vorgängen, Kanalkonfiguration und Sperren; vor und nach einem Deployment vergleichen), `… artisan process:impact `. + ## 8. Bekannte Eigenheiten und Lösungen | Problem | Ursache | Lösung (umgesetzt) | diff --git a/docs/LOESCHKONZEPT.md b/docs/LOESCHKONZEPT.md index b61a77a..be87685 100644 --- a/docs/LOESCHKONZEPT.md +++ b/docs/LOESCHKONZEPT.md @@ -39,6 +39,8 @@ ## 2. Frist-Übersicht | Webserver-Logs STRATO | Hosting | technisch | Anbieterabhängig | ❓ | Strato-Info/AVV | ❓ | | Audit-Log (neu) | `audit_events` | Nachweis Sicherheit | z. B. 12 Monate ⚖ | existiert nicht | einführen | 🗓 | | Fehlgeschlagene Jobs | `failed_jobs` | technisch | 30 Tage | Standard behalten | Job `queue:prune-failed` | ⚠ | +| Testberichte des Prozess-Testers | `process_test_runs` | technisch (nur synthetische Daten, Konfiguration, Benutzer-ID) | **30 Tage** (Entscheidung O3, 04.11.2026) | `AnonymizeGuests` löscht nach `fewo.retention.process_test_run_days` | – | ✅ | +| Laufverzeichnisse des Prozess-Testers | `storage/app/sandbox/runs` | technisch (synthetisch) | Ende des Laufs | gelöscht nach jedem Lauf, Reste nach 1 h beim nächsten Lauf | – | ✅ | | Datenbank-Backups | Strato/eigen | technisch | z. B. 30 Tage rollierend ⚖ | ❓ nicht belegt | dokumentieren; Restore-Test; Löschung aus Backups via Frist | ❓ | ## 3. Löschmechanik (Soll) diff --git a/docs/Prozessarchitektur/Abnahme/ARCHITEKTUR_MODULAR_ABNAHME.md b/docs/Prozessarchitektur/Abnahme/ARCHITEKTUR_MODULAR_ABNAHME.md new file mode 100644 index 0000000..59d8551 --- /dev/null +++ b/docs/Prozessarchitektur/Abnahme/ARCHITEKTUR_MODULAR_ABNAHME.md @@ -0,0 +1,58 @@ +# Abnahmeprotokoll: Modulare Prozessarchitektur V2 (Kanalkonfigurator und Prozess-Tester) + +Stand: 04.11.2026 · Umsetzung `feature/prozessarchitektur-v2` · Testsystem https://www.stommer.info + +Teil A ist die technische Abnahme. Sie wurde vor der Bereitstellung durchgeführt, die Ergebnisse stehen im [Abschlussbericht](../Implementierungsstände/ABSCHLUSSBERICHT_PROZESSARCHITEKTUR_V2.md). Teil B ist das Drehbuch für die fachliche Abnahme durch den Betreiber. Konfigurator und Tester werden gemeinsam abgenommen. + +--- + +## Teil A – Technische Abnahme (automatisiert) + +| Kriterium | Nachweis (Testklasse) | +|---|---| +| N1 A1-Bestand | `BehaviourComparisonTest` (a1_*), `ProcessCoreTest`, `EndToEndAcceptanceTest` | +| N2 A4-Bestand | `BehaviourComparisonTest` (a4_booking), `ChannelProcessConfiguratorTest` (K08), `EndToEndStayAcceptanceTest` (T20) | +| N3 Loyalty | `LoyaltyArchitectureProofTest`, `ProcessTesterTest::test_the_loyalty_variant_runs_in_the_tester_only` | +| N4 gemischter Kanal | `ChannelProcessConfiguratorTest::test_a_mixed_channel_…` | +| N5 optionaler Schritt aus | `ChannelProcessConfiguratorTest::test_a_switched_off_optional_step_…`, `ProcessRunnerTest` | +| N6 Prozess-Tester | `ProcessTesterTest`, `ProcessTesterSecurityTest` (15 Negativfälle), `SideEffectPathsTest` | +| N7 neue Portal-API | `ChannelEventContractTest::test_a_new_api_adapter_uses_the_same_intake` | +| K01–K10 | `ChannelProcessConfiguratorTest` | +| T1 Abhängigkeiten | `ProcessRunnerTest`, `ProcessCoreTest`, `LoyaltyArchitectureProofTest` | +| T2 Sicherheitsgrenzen | `ProcessTesterSecurityTest`, `SideEffectPathsTest`, `04` §3.1a | +| T3 historische Versionen | `ProcessCoreTest::test_a_finished_case_of_a_retired_version_stays_readable`, `process:check --cases` | +| Laufende/abgeschlossene Vorgänge | `OngoingCaseRegressionTest` (12 eingefrorene v0.11-Fälle) | +| Verhaltensvergleich alt/neu | `BehaviourComparisonTest` (11 Abläufe, 198 Konstellationen; Abweichungen nur I-004/I-005) | +| O3 Aufbewahrung | `ProcessTestRunRetentionTest` | +| O4 Aussetzen der Außenwirkungen | `PortalReportSuspendsAutomationTest` | +| O5 Abschluss nach finanzieller Klärung | `SettlementClarificationTest` | +| Kanalereignisse, Duplikate | `ChannelEventContractTest` | +| Bestehende Regression | gesamte Suite | + +--- + +## Teil B – Fachliche Abnahme durch den Betreiber (Drehbuch) + +**Schutz des Testsystems:** Für die Abnahme werden ausschließlich der Prozess-Tester (ohne Wirkung auf echte Daten) und synthetische Testvorgänge verwendet. Es werden keine echten Gäste angeschrieben, keine Portalbuchungen ausgelöst, keine Kalender verändert, keine bestehenden Buchungen umgeschrieben. Der Mandant steht im Testbetrieb (Mails nur an die Testadresse). + +Vorher und nachher: `bash scripts/deploy.sh staging artisan process:fingerprint` – die Prüfsummen `h_bookings`, `h_overrides` und `h_blocks` müssen gleich bleiben. Ausnahme ist eine bewusste Speicherung im Konfigurator; sie ändert nur `h_overrides`, und dann nur den betreffenden Kanal. + +| # | Schritt | Erwartung | Ergebnis / Notiz | +|---|---|---|---| +| B1 | Einrichtung › Kanäle › „Eigene Webseite“ › **Ablauf** | Frage „Wie wird eine Anfrage … abgewickelt?“. Wählbar: „Angebot mit Vorreservierung“ und „Unverbindliche Auskunft“. Schritte nach Phasen, Pflichtschritte mit Schloss. | | +| B2 | An einem Schritt einen Wert ändern, z. B. Haltefrist | „hier gesetzt“; die Vorschau zeigt den Ablauf sofort; „auf geerbten Wert zurücksetzen“ möglich | | +| B3 | „Bitte um eine Bewertung“ ausschalten | Schritt „aus“, in der Vorschau durchgestrichen mit „im Kanal abgeschaltet“ | | +| B4 | **Ablauf testen** → „Vollständige Anfrage bis zur Buchung“ → „Test starten“, dann mehrmals „Weiter“ | Bericht: Modell und Version, wirksame Einstellungen mit Herkunft, je Ereignis Schritte, Kalender, Preis, simulierte Mails (an tester@sandbox.invalid), übersprungene Schritte; „Bewertung“ übersprungen (Konfiguration) | | +| B5 (A1) | Szenario „Fehlende Anschrift, späte Antwort“ | Rückfrage beim Gast und Klärungsreservierung laufen nebeneinander; die Reservierung läuft ab, die Anfrage bleibt offen; nach der Antwort geht das Angebot; danach läuft die Angebotsfrist ab | | +| B6 (Loyalty) | Variante „Angebot mit Stammgastrabatt“ wählen, Szenario „Stammgast fragt an“ testen, dann **Speichern** versuchen | Im Bericht erscheint die Rabattzeile im Preis vor dem Angebot. Speichern wird abgewiesen („nur im Prozess-Tester verwendbar“). | | +| B7 (A2) | Kanal FeWo-direkt › Ablauf › Reiter „Anfragen“ | wählbar: „Portalanfrage mit Angebot“ / „… mit Auskunft“; Test „Anfrage über das Portal“ | | +| B8 (A4) | FeWo-direkt › Reiter „Feste Buchungen“ | nur „Portalbuchung, Inkasso beim Portal“ (O2). Bei „Anreise-Informationen“ lässt sich „Portal“ wählen, ohne das Modell zu wechseln. Test „Feste Buchung über das Portal“ zeigt: Buchungsmail zweimal → ein Vorgang; Zahlung „laut Portal“; Auszahlung offen | | +| B9 (Storno-Meldung) | Im selben Test „Portal meldet eine Stornierung“ anhaken | Aufgabe „Portal meldet Stornierung“, Buchung bleibt fest, automatische Nachrichten warten (O4) | | +| B10 (A3) | Kanal Destination Solution › Ablauf | nur „Portalbuchung, eigene Abwicklung“; Test „Feste Buchung über das Portal“ | | +| B11 (A5) | Nur über ein Portal mit Kanalprofil „Sonstiges Portal“ wählbar (für FeWo-direkt bewusst nicht) | Modell vorhanden, synthetisch getestet | | +| B12 (gemischter Kanal) | FeWo-direkt: beide Reiter verschiedene Modelle | Anfrage und Buchung desselben Kanals folgen verschiedenen Modellen | | +| B13 | Nach dem Speichern: laufende Vorgänge | Hinweis „laufende Vorgänge behalten ihren bisherigen Ablauf“; bestehende Vorgänge unverändert (`process:fingerprint`: `h_bookings` gleich) | | +| B14 (O5) | Ein abgereister Portalvorgang mit offener Auszahlung: „Kaufmännisch abschließen …“ | Ohne Klärungsart nicht möglich; „Als offene Forderung weiterführen“ legt eine Aufgabe an | nur mit synthetischem Vorgang | +| B15 | Bestandsfälle öffnen (abgeschlossene und laufende Vorgänge) | Ablauf, Preise und Fristen wie vorher | | + +**Freigabe:** ☐ Konfigurator betriebsfähig ☐ Prozess-Tester schadensfrei · Datum / Name: ____________ diff --git a/docs/Prozessarchitektur/Architektur/00_MANAGEMENT_ZUSAMMENFASSUNG.md b/docs/Prozessarchitektur/Architektur/00_MANAGEMENT_ZUSAMMENFASSUNG.md index 6f5b863..76eadd8 100644 --- a/docs/Prozessarchitektur/Architektur/00_MANAGEMENT_ZUSAMMENFASSUNG.md +++ b/docs/Prozessarchitektur/Architektur/00_MANAGEMENT_ZUSAMMENFASSUNG.md @@ -78,16 +78,16 @@ ## Verbleibende Risiken ## Entscheidungen -Entschieden sind E1–E9 sowie D4 und D6 (als Regel). D3 ist aus den Geschäftsregeln abgeleitet. Die Matrix mit Begründung, Komponenten, Auswirkung und Testnachweis steht in `06` §9.1. +Entschieden sind E1–E9, D3/D4/D6 sowie – mit dem Implementierungsauftrag vom 04.11.2026 – **O1–O5** (`06` §9.2): -**Tatsächlich noch offen** (`06` §9.2): +- **O1:** Vertragsdokumentation bleibt archetypbestimmend. +- **O2:** FeWo-direkt: Anfrage A2, Buchung zunächst nur A4; Destination Solutions A3; gesteuert über das Kanalprofil. +- **O3:** Testberichte 30 Tage, im Löschkonzept. +- **O4:** Zugeordnete Portal-Storno-/Änderungsmeldungen setzen betroffene automatische Außenwirkungen aus. +- **O5:** Abschluss bei Portal-Inkasso nur nach finanzieller Klärung. -| # | Frage | Empfehlung | -|---|---|---| -| O1 | Bleibt die Vertragsdokumentation archetypbestimmend (`Documents = Portal` ⇒ A5)? | ja | -| O2 | FeWo-direkt zusätzlich A5 oder A3? | zunächst nur A4 | -| O3 | Aufbewahrungsfrist der Testberichte im Löschkonzept | kurz, z. B. 30 Tage | -| O4 | Gemeldete Portal-Stornierung/-Änderung setzt automatische Außenwirkungen aus? | ja | -| O5 | Abschluss A4/A5 ohne erfassten Auszahlungseingang? | nur begründet, mit Protokoll | +Zusätzliche technische Anforderungen: **T1** harte/weiche Abhängigkeiten (`02` §7), **T2** tatsächliche Sicherheitsgrenzen des Testers (`04` §3), **T3** historische Modellversionen (`02` §5.3, `06` §10). -Vor Beginn (U-0): tatsächlichen Repository- und Testsystemstand prüfen, V1/V6 auf dem Server prüfen, Referenz-Snapshots erzeugen. +## Umsetzungsstand + +Umgesetzt auf `feature/prozessarchitektur-v2` (U-0 bis U-E), Abweichungen und Einschränkungen in `06` §10, Ergebnisse im Abschlussbericht (`../Implementierungsstände/ABSCHLUSSBERICHT_PROZESSARCHITEKTUR_V2.md`) und im Abnahmeprotokoll (`../Abnahme/ARCHITEKTUR_MODULAR_ABNAHME.md`). diff --git a/docs/Prozessarchitektur/Architektur/02_FACHMODUL_ARCHITEKTUR.md b/docs/Prozessarchitektur/Architektur/02_FACHMODUL_ARCHITEKTUR.md index e7ee7fd..0900263 100644 --- a/docs/Prozessarchitektur/Architektur/02_FACHMODUL_ARCHITEKTUR.md +++ b/docs/Prozessarchitektur/Architektur/02_FACHMODUL_ARCHITEKTUR.md @@ -294,7 +294,7 @@ ### 5.3 Versionierung und Schutz laufender Vorgänge (K3) Geld- und Fristwirkungen auf bereits **verbindliche** Vorgänge werden nicht durch Code korrigiert, sondern als Aufgabe für den Vermieter ausgewiesen. - **R5 – Kein Neuberechnen.** Kein Release berechnet Preise, Rabatte, Fristen oder Status bestehender Vorgänge neu, außer eine fachliche Action wird ausdrücklich ausgelöst. -- **R6 – Aufbewahrung alter Versionen.** Alte Modell- und Modulklassen bleiben, solange offene Vorgänge sie im Plan tragen. `process:check` meldet Versionen ohne offene Vorgänge; erst dann wird entfernt. +- **R6 – Aufbewahrung alter Versionen (T3, entschieden).** Eine Modellversion bleibt registriert, solange **irgendein** Vorgang – auch ein abgeschlossener – sie im Plan trägt; `process:check --cases` prüft das. Der Plan speichert zusätzlich die Bezeichnungen seiner Schritte. Wird ein Modul dennoch einmal entfernt, erscheint sein Schritt bei abgeschlossenen Vorgängen als „(frühere Fassung)“; eine fehlende Modellversion fällt beim Lesen auf die aktuelle Definition desselben Modells zurück (`ProcessPlan::isHistoric`). Alte Programmlogik muss nicht ausführbar bleiben; offene Vorgänge brauchen ihre Modulversion (oder eine als kompatibel erklärte, `config/process.php` › `compatible`). Es wird **nicht** verlangt, frühere Anwendungsversionen vollständig zu betreiben. Ältere Vorgänge werden sicher weitergeführt, weil @@ -384,6 +384,15 @@ ### 6.4 Was geändert wird und was unverändert bleibt ## 7. Ausführungslogik (K1) [Vorschlag] +### 7.0 Umsetzung T1 (entschieden) + +- **Harte Abhängigkeit** (`Dependency::hard`): Der Schritt läuft erst, wenn der andere `Done` ist. Ein nicht zutreffender oder (nur bei optionalen Schritten möglich) abgeschalteter Schritt erfüllt sie, weil seine Bedingung den Fall nicht betrifft. `blocksDependents` gibt es nicht: Die Kante entscheidet, nicht der wartende Schritt. +- **Weiche Abhängigkeit** (`Dependency::soft`): Sind beide in derselben Runde bereit, läuft die weiche Voraussetzung zuerst. Wartet oder scheitert sie, läuft der Schritt trotzdem. +- **Unabhängig:** keine Kante. **Bedingt:** `applies()`. +- **Neubewertung:** genau ein Schritt je Runde, danach wird der Vorgang neu gelesen. Eine Liste bereiter Schritte wird nie über eine Zustandsänderung weitergereicht. +- **Auslöser:** Die Module erklären, nach welchen Ereignissen sie bewertet werden (`triggers`). Der Runner berücksichtigt nur passende Module. +- Pflichttests: `ProcessRunnerTest` (u. a. Zustandsänderung während einer Runde), `ProcessCoreTest` (Klärungsreservierung parallel zur Datenbeschaffung, Adressprüfung mit Wartezustand), `LoyaltyArchitectureProofTest` (Preis nach Loyalty-Prüfung). + ### 7.1 Grundsatz: eine Wahrheit, abgeleitete Bereitschaft - **Zustand** jedes Schritts wird wie heute aus den Falldaten **abgeleitet**: Status, Versionen, Zeitstempel, `data_requests`, `case_facts`, `booking_tasks`. Der Runner speichert **keinen** Schrittzustand. Es gibt also keine zweite Wahrheit. diff --git a/docs/Prozessarchitektur/Architektur/04_PROZESS_TESTER.md b/docs/Prozessarchitektur/Architektur/04_PROZESS_TESTER.md index dde35f7..6b1d33d 100644 --- a/docs/Prozessarchitektur/Architektur/04_PROZESS_TESTER.md +++ b/docs/Prozessarchitektur/Architektur/04_PROZESS_TESTER.md @@ -75,6 +75,18 @@ ### 3.1 Bewertung des bisherigen Entwurfs **Korrektur:** Der Lauf findet in einer **eigenen Sandbox-Anfrage** statt. Diese wird von Anfang an im Sandbox-Modus gestartet. Die echte Datenbank ist in ihr **nicht konfiguriert**, und es gibt nichts wiederherzustellen, weil der PHP-Prozess der Anfrage endet. Laravel Octane oder ein anderer langlebiger Prozess wird nicht eingesetzt [Befund: `composer.json`]; jede Anfrage beginnt mit frischem Anwendungszustand. +### 3.1a Umsetzung T2 (entschieden): eigener Prozess, anwendungsseitige Isolation + +Umgesetzt ist die Sandbox nicht als eigene HTTP-Anfrage, sondern als **eigener PHP-Prozess** (`php artisan process:sandbox-run `). Die Admin-Anfrage startet ihn über die `Process`-Fassade mit der Umgebungsvariable `FEWO_SANDBOX_RUN`; `bootstrap/app.php` ruft dann `SandboxBootstrapper::configure` direkt nach dem Laden der Konfiguration auf. + +| Ebene | Was erreicht ist | Was nicht erreichbar ist (Shared Hosting) | +|---|---|---| +| Betriebssystem | eigener Prozess mit eigenem Speicher; Umgebungsvariablen für Datenbank, Mail, Dienste werden dem Kindprozess entzogen | kein eigener Systembenutzer, kein Netzwerk- oder Dateisystem-Sandboxing: der Prozess könnte mit nativem Code `shared/.env` lesen | +| Anwendung | Konfiguration ersetzt (nur `sandbox`, `array`, `sync`), Manager zeichnen Verstöße auf und werfen, Wächter auf jeder Sandbox-Verbindung, Netz nur mit Szenario-Antwort, eigener App-Schlüssel, `SystemSettings` werden nicht angewendet | – | +| Code | `SideEffectPathsTest` verbietet native Wege (PDO, Sockets, curl, `mail()`, Dateien per Pfad, Programme, `env()`) in `app/` | Code in `vendor/` wird nicht geprüft | + +**Voraussetzungen**, sonst ist der Tester gesperrt (keine Ausweichlösung): `pdo_sqlite`, Vorlage der Testdatenbank, erlaubtes `proc_open`, PHP-CLI (`FEWO_SANDBOX_PHP`, sonst `/opt/RZphp84/bin/php-cli`). Geprüft in der Anfrage, die den Lauf starten würde (`ProcessSandbox::requirements()`). + ### 3.2 Ablauf eines Testschritts ``` @@ -117,7 +129,7 @@ ### 3.3 Standardmäßig gesperrt: Konfiguration der Sandbox-Anfrage |---|---|---| | Datenbank | `database.connections` = **nur** `sandbox` (SQLite, Pfad `/db.sqlite`); `database.default = sandbox`; Redis-Konfiguration leer | `DB::connection('mysql')` → `InvalidArgumentException: Database connection [mysql] not configured` → Abbruch | | Zusätzlich | `beforeExecuting` auf `sandbox` prüft, dass der PDO-Dateipfad gleich `/db.sqlite` ist | `SandboxViolation` | -| Mail | `mail.mailers` = nur `array`; `mail.default = array`; `EnforceMailTestMode` bleibt aktiv (Sandbox-Mandant im Testbetrieb, Testadresse `tester@invalid`) | anderer Mailer → „not defined“ → Abbruch | +| Mail | `mail.mailers` = nur `array`; `mail.default = array`; `EnforceMailTestMode` bleibt aktiv (Sandbox-Mandant im Testbetrieb, Testadresse `tester@sandbox.invalid`) | anderer Mailer → „not defined“ → Abbruch | | HTTP | `Http::preventStrayRequests()`; `Http::fake` nur mit Szenario-Antworten (KI, iCal, künftige API, n8n-Webhook von `CreateChannelTasks`) | `StrayRequestException` → Abbruch | | IMAP | `MailboxReader` an `SandboxMailboxReader` gebunden (wirft); `config('fewo.mailbox')` leer | `SandboxViolation` | | Connectors | `ChannelRegistry` an Szenario-Connectors gebunden | unbekannter Connector → Abbruch | diff --git a/docs/Prozessarchitektur/Architektur/06_MIGRATIONS_UND_UMSETZUNGSPLAN.md b/docs/Prozessarchitektur/Architektur/06_MIGRATIONS_UND_UMSETZUNGSPLAN.md index 4c8ceaa..a8492e5 100644 --- a/docs/Prozessarchitektur/Architektur/06_MIGRATIONS_UND_UMSETZUNGSPLAN.md +++ b/docs/Prozessarchitektur/Architektur/06_MIGRATIONS_UND_UMSETZUNGSPLAN.md @@ -251,14 +251,38 @@ ### 9.1 Entscheidungsmatrix | K5 | eigene Sandbox-Anfrage, standardmäßig gesperrt | Umschalten in der Admin-Anfrage nicht sicher | `SandboxBootstrapper`, Sandbox-Manager | keine | `04` §7 | | K10 | Ereignisse als Ergänzung, Transporte unverändert | kleinster tragfähiger Ansatz | `ChannelEventHandler`, `PortalIntake` (2 Stellen) | keine | `TransportParityTest` | -### 9.2 Tatsächlich noch offen +### 9.2 Entscheidungen O1–O5 [Entschieden, Implementierungsauftrag 04.11.2026] -| # | Frage | Empfehlung | Nötig vor | +| # | Entscheidung | Umsetzung | Test | |---|---|---|---| -| **O1** | Bleibt die Vertragsdokumentation archetypbestimmend (`Documents = Portal` ⇒ A5, wie heute codiert)? | ja | U-C | -| **O2** | Lässt FeWo-direkt neben A4 auch A5 oder A3 zu? | zunächst nur A4 | U-C | -| **O3** | Aufbewahrungsfrist der Testberichte im Löschkonzept | kurz, z. B. 30 Tage; mit dem Löschkonzept bestätigen | U-D | -| **O4** | Setzt eine offene Portal-Storno-/Änderungsmeldung automatische Außenwirkungen aus? | ja (beabsichtigte Abweichung von v0.11) | U-A | -| **O5** | Kaufmännischer Abschluss A4/A5 ohne erfassten Auszahlungseingang? | nur als begründeter Abschluss mit Protokoll | U-C | +| **O1** | Die verbindliche Vertragsdokumentation bleibt archetypbestimmend (A3–A5 wie bisher). Ergänzende Unterlagen, Anreiseinformation, Kommunikation und lokale Aufgaben sind im Modell wählbar. | `Responsibilities` je Modell (`contract_documents` fest), `ConfigureChannelProcess` weist `documents = portal` in A4 ab | `ChannelProcessConfiguratorTest::test_arrival_information_can_go_to_the_portal_within_a4_without_changing_the_model` | +| **O2** | FeWo-direkt: Anfrage A2 (Angebot/Auskunft), feste Buchung zunächst nur A4. Destination Solutions: A3. Die Zulässigkeit steuert das Kanalprofil, nicht der Prozesskern. | `config/channels.php` › `portal_profiles`, Auswahl am Kanal (`settings.portal_profile`) | `test_only_admissible_models_per_channel_and_intake_are_offered` (auch: anderes Profil gibt weitere Modelle frei) | +| **O3** | Testberichte 30 Tage, im Löschkonzept, anpassbar | `fewo.retention.process_test_run_days` (Systemeinstellungen), Löschung in `AnonymizeGuests` | `ProcessTestRunRetentionTest` | +| **O4** | Betroffene automatische Außenwirkungen werden bei einer zugeordneten, offenen Portal-Storno-/Änderungsmeldung ausgesetzt; interne Prüfungen, Fristen, Konflikterkennung und Aufgaben laufen weiter; die Meldung ändert die Buchung nie. | `OutwardSuspension` (nur Aufgaben `PortalCancellationReported`/`PortalChangeReported`, die `PortalIntake` nur für sicher zugeordnete Vorgänge anlegt); Runner, `SendBookingReminders`, `RequestReviews` | `PortalReportSuspendsAutomationTest`, `ProcessRunnerTest::test_an_open_portal_report_suspends_outward_steps_only` | +| **O5** | Kaufmännischer Abschluss bei Portal-Inkasso nur nach finanzieller Klärung; eine Portalmeldung ist kein Nachweis; Freitext allein genügt nicht; die Forderung bleibt nachvollziehbar. | `CaseClosure::settle` verlangt bei offener/abweichender Auszahlung eine Klärungsart (Verrechnung, verbuchte Differenz, ausgebuchte Forderung). „Als offene Forderung weiterführen“ legt die Aufgabe `OpenClaim` an; der Vorgang bleibt dann kaufmännisch offen, der Aufenthalt kann abgeschlossen sein. | `SettlementClarificationTest` | -Technische Prüfungen statt Entscheidungen: V1 und V6 (U-0). +Technische Prüfungen statt Entscheidungen: V1 (U-0: `pdo_sqlite` im CLI vorhanden; im Web-PHP prüft der Tester zur Laufzeit) und V6 (nicht nötig, SQLite verfügbar). + +--- + +## 10. Umsetzungsstand und technische Detailentscheidungen (04.11.2026) + +Die Pakete U-0 bis U-E sind auf `feature/prozessarchitektur-v2` umgesetzt. Wo die Umsetzung vom Plan abweicht, steht hier die kleinste tragfähige Alternative mit Grund. + +| Thema | Plan | Umsetzung | Grund | +|---|---|---|---| +| Tester-Isolation (T2) | eigene Sandbox-**Anfrage** | eigener **Prozess** `php artisan process:sandbox-run `, gestartet über die `Process`-Fassade; die Konfiguration wird beim Laden ersetzt (`SandboxBootstrapper`) | Stärkere Trennung (eigener Speicher, eigene Umgebung), ohne zustandslose Token-Anfrage; im Testlauf identisch prüfbar. Ohne erlaubtes `proc_open` ist der Tester gesperrt. | +| Abhängigkeiten (T1) | `requires` + `blocksDependents` | `Dependency::hard()` / `Dependency::soft()` an der Kante; `blocksDependents` entfällt | Eine harte Voraussetzung kann so nicht durch eine Eigenschaft des wartenden Schritts aufgehoben werden. | +| Auslöser | vorhandene Stellen | wie geplant; die Module erklären ihre Auslöser (`triggers`), der Runner berücksichtigt nur passende Module | Jeder Aufrufer behält genau seinen v0.11-Umfang (Verhaltensvergleich gleich). | +| Preis-Erweiterungspunkt | 5 Aufrufer umstellen | nur `SendOffer::quoteFor` | Alle Preisfestlegungen vor Verbindlichkeit (Angebot, Auskunft, Wunsch, Vorschau) laufen schon über `quoteFor`. | +| Loyalty-Status | Fakt mit `FactSource::System` | aus den Aufenthalten abgeleitet (keine zweite Wahrheit), Nachweis im Schritt | Kein Eingriff in den gemeinsamen Fakteneingang nötig. | +| Historische Versionen (T3) | Versionen ohne offene Vorgänge melden/entfernen | **nie entfernen**, solange irgendein Vorgang (auch abgeschlossen) sie im Plan trägt (`process:check --cases`); der Plan speichert die Bezeichnungen seiner Schritte; ein nicht mehr registriertes Modul erscheint als „(frühere Fassung)“, eine fehlende Modellversion fällt beim Lesen auf die aktuelle Definition zurück | Abgeschlossene Vorgänge bleiben lesbar, ohne alte Programmlogik ausführbar halten zu müssen. | +| Kanalereignisse | `PortalIntake` an 2 Stellen | `PortalIntake` (Quelle `api`, Referenz, `reportToCase`) und `TakeOverExternalBooking` (Quelle `api` als Beleg) | Sonst hätte eine API-Buchung keinen Vorgang werden können. `SyncChannel` und `ProcessPortalMail` unverändert. | +| Release-Kennung | Datei vom Deploy-Skript | Name des Release-Verzeichnisses (`-`) | Das Deployment läuft über den PipelineManager (anderes Repository). | +| „So arbeite ich“ | dieselbe Schrittansicht | unverändert (Feldliste) | Bekannte Einschränkung; der Vermieterstandard wirkt weiter als Grundlage des Konfigurators. | + +**Bekannte Einschränkungen:** + +- Eine Buchung, die per API **und** per iCal eintrifft, wird ein Vorgang. Im Kalender stehen aber bis zur Klärung zwei Sperren nebeneinander, weil `SyncChannel` nur Mail-Sperren ersetzt. Das ist erst relevant, wenn ein echter API-Adapter kommt. +- Der Tester spielt eine Gast-Antwort per E-Mail als ausgewertete Angaben (`ContributeCaseFacts`, Quelle E-Mail) ein, nicht über Postfach und KI. +- Native PHP-Aufrufe am Framework vorbei sind nur statisch ausgeschlossen (`SideEffectPathsTest`). diff --git a/pipeline.toml b/pipeline.toml index 60dfe37..f1617d8 100644 --- a/pipeline.toml +++ b/pipeline.toml @@ -52,6 +52,7 @@ public = "public" backup = [["@php", "artisan", "backup:database", "--no-interaction"]] activate = [ ["@php", "artisan", "migrate", "--force", "--no-interaction"], + ["@php", "artisan", "process:sandbox-template", "--no-interaction"], ["@php", "artisan", "optimize", "--no-interaction"], ["@php", "artisan", "filament:optimize", "--no-interaction"], ] diff --git a/resources/views/filament/resources/channels/channel-process-test.blade.php b/resources/views/filament/resources/channels/channel-process-test.blade.php new file mode 100644 index 0000000..4564c5d --- /dev/null +++ b/resources/views/filament/resources/channels/channel-process-test.blade.php @@ -0,0 +1,103 @@ + + @php + $muted = 'color:#6b7280;font-size:.8rem'; + $input = 'border:1px solid rgba(128,128,128,.4);border-radius:.375rem;padding:.3rem .45rem;background:transparent'; + $card = 'border:1px solid rgba(128,128,128,.3);border-radius:.5rem;padding:.75rem 1rem;margin-bottom:.6rem'; + $requirements = $this->requirements(); + $scenarios = $this->scenarios(); + $run = $this->run(); + $report = $run?->report ?? []; + $stateColor = ['done' => '#15803d', 'external' => '#0369a1', 'open' => '#b45309', 'problem' => '#b91c1c', 'waiting' => '#6d28d9', 'later' => '#6b7280', 'not_applicable' => '#9ca3af']; + @endphp + + +

Der Test spielt einen ausgedachten Vorgang mit Ihrer aktuellen – auch noch nicht gespeicherten – Einstellung durch. Er nutzt dieselben Abläufe wie ein echter Vorgang, aber in einem eigenen, abgeschotteten Lauf: eigene Testdatenbank, keine echten Gäste, keine Mails an echte Empfänger, keine Portale, keine Kalender. Mails werden nur angezeigt. Links in den Mails sind nur Text.

+
+ + @if ($requirements !== []) + +
    + @foreach ($requirements as $requirement)
  • {{ $requirement }}
  • @endforeach +
+

Ohne diese Voraussetzungen lässt sich die Trennung von den echten Daten nicht sicher herstellen. Es gibt deshalb keinen Ausweichbetrieb.

+
+ @else + +

Ablauf: {{ app(\App\Process\ProcessCatalogue::class)->model($this->draft['model'])::label() }}{{ ($this->draft['variant'] ?? 'standard') !== 'standard' ? ' · Variante '.$this->draft['variant'] : '' }} · {{ $this->intake === 'booking' ? 'feste Buchungen' : 'Anfragen' }} über {{ $this->record->name }}

+
+ + @if ($class = $scenarios[$this->scenario] ?? null) + @foreach ($class::inputs() as $key => $definition) + + @endforeach + @endif +
+ @if ($class)

{{ $class::description() }}

@endif +
+ Test starten + @if ($run && count($report['timeline'] ?? []) < ($report['scenario']['available_events'] ?? 0) && blank($report['aborted'] ?? null)) + Weiter: nächstes Ereignis + @endif + Testlauf läuft … +
+
+ @endif + + @if ($run) + + @if (filled($report['aborted'] ?? null)) +

{{ $report['aborted'] }}

+ @foreach ($report['violations'] ?? [] as $violation)

{{ $violation['message'] ?? '' }}

@endforeach + @endif + @if ($plan = $report['plan'] ?? null) +

{{ $plan['label'] }} ({{ $plan['model'] }} Version {{ $plan['version'] }}{{ $plan['variant'] !== 'standard' ? ', Variante '.$plan['variant'] : '' }}) · Vorgangsart {{ $plan['case_type'] }}

+
Wirksame Einstellungen +
    + @foreach ($plan['configuration'] as $row)
  • {{ $row['question'] }}: {{ $row['value'] }} ({{ $row['source'] }})
  • @endforeach +
+
+ @endif + + @foreach ($report['timeline'] ?? [] as $index => $event) +
+
{{ $index + 1 }}. {{ $event['label'] }}{{ $event['at'] }} (simuliert)
+ @if ($event['error'])

Fehler: {{ $event['error'] }}

@endif + @isset($event['situation'])

{{ $event['status'] }} · {{ $event['situation'] }}

@endisset +
    + @foreach ($event['activities'] as $activity) +
  • {{ $activity['state'] }} – {{ $activity['label'] }}@if ($activity['detail']) · {{ $activity['detail'] }}@endif
  • + @endforeach +
+ @if (($event['skipped'] ?? []) !== []) +

Übersprungen: {{ collect($event['skipped'])->map(fn ($skipped) => $skipped['label'].' ('.$skipped['reason'].')')->implode(', ') }}

+ @endif + @if (isset($event['calendar'])) +

Kalender: {{ $event['calendar']['occupying'] ? 'Zeitraum belegt' : 'Zeitraum frei' }}{{ $event['calendar']['hold_until'] ? ', reserviert bis '.$event['calendar']['hold_until'] : '' }} · Preis: {{ $event['price']['total'] !== null ? \App\Support\Money::format($event['price']['total']) : 'noch offen' }}

+ @endif + @foreach ($event['mails'] as $mail) +
✉ simuliert: {{ $mail['subject'] }} an {{ $mail['to'] }}

{{ $mail['excerpt'] }}

+ @endforeach +
+ @endforeach + + @if ($result = $report['result'] ?? null) +

Ergebnis: {{ $result['status'] }} · {{ $result['situation'] }}@if ($result['next']) · nächster Schritt: {{ $result['next'] }}@endif

+ @endif +

Bericht Nr. {{ $run->id }} vom {{ $run->created_at->format('d.m.Y H:i') }} · wird nach {{ config('fewo.retention.process_test_run_days') }} Tagen gelöscht.

+
+ @endif +
diff --git a/resources/views/filament/resources/channels/channel-process.blade.php b/resources/views/filament/resources/channels/channel-process.blade.php index 41d2458..fee9bda 100644 --- a/resources/views/filament/resources/channels/channel-process.blade.php +++ b/resources/views/filament/resources/channels/channel-process.blade.php @@ -130,9 +130,8 @@ @endforeach

Gilt für neue Vorgänge. Laufende Vorgänge dieses Kanals ({{ $this->runningCases() }}) behalten ihren bisherigen Ablauf.

- @if (\Illuminate\Support\Facades\Route::has('filament.admin.resources.channels.test')) - Ablauf testen - @endif + Ablauf testen +

Spielt einen ausgedachten Vorgang mit genau dieser Einstellung durch – ohne Wirkung auf echte Daten.

diff --git a/tests/Feature/EndToEndStayAcceptanceTest.php b/tests/Feature/EndToEndStayAcceptanceTest.php index f8b8407..dc44f4f 100644 --- a/tests/Feature/EndToEndStayAcceptanceTest.php +++ b/tests/Feature/EndToEndStayAcceptanceTest.php @@ -430,9 +430,12 @@ public function test_t22_stay_closed_while_commercial_points_are_open(): void $portal->refresh(); $this->assertSame(BookingStatus::Completed, $portal->status); $this->assertNull($portal->settled_at, 'the 5,51 € difference is not settled by the system'); - Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert']); + // Decision O5 (Architektur V2): a reason alone is not enough with portal collection – the kind of clarification is required. + Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'])->assertHasActionErrors(['clarification']); + $this->assertNull($portal->fresh()->settled_at); + Livewire::test(ViewBooking::class, ['record' => $portal->getRouteKey()])->callAction('settle', ['clarification' => 'difference_booked', 'note' => 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert']); $portal->refresh(); - $this->assertSame(['Ingrid', 'Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'], [$portal->settled_by, $portal->settled_note]); + $this->assertSame(['Ingrid', 'Differenz geklärt und verbucht: Differenz 5,51 € laut FeWo-direkt Servicegebühr – akzeptiert'], [$portal->settled_by, $portal->settled_note]); } /** T24 – landlord, property, portal and case settings decide the whole run. */ diff --git a/tests/Feature/Process/ChannelEventContractTest.php b/tests/Feature/Process/ChannelEventContractTest.php new file mode 100644 index 0000000..787aa50 --- /dev/null +++ b/tests/Feature/Process/ChannelEventContractTest.php @@ -0,0 +1,181 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + Mail::fake(); + $this->fewo = Channel::factory()->for(Property::sole())->create(['name' => 'FeWo-direkt', 'booking_model' => 'mixed', 'case_intake' => 'create', 'import_enabled' => false, + 'settings' => ['import_url' => 'https://www.fewo-direkt.de/icalendar/x.ics', 'email_senders' => 'fewo-direkt.de']]); + app(ConfigureChannelProcess::class)->handle($this->fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking']); + $this->fewo->refresh(); + } + + public function test_an_api_booking_becomes_one_case_whatever_the_transport_and_order(): void + { + $first = $this->handle(new IncomingBooking($this->provenance('HA-API1'), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'))); + $this->assertSame(IntakeOutcome::Create, $first->outcome, implode(' ', $first->reasons)); + $case = Booking::query()->sole(); + $this->assertSame(['a4.portal_booking', BookingStatus::Confirmed, 'HA-API1'], [$case->profile['plan']['model'], $case->status, $case->portal_reference]); + + // The same event again, then the booking mail of the same booking: still one case. + $this->assertSame(IntakeOutcome::Link, $this->handle(new IncomingBooking($this->provenance('HA-API1'), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10')))->outcome); + app(ProcessPortalMail::class)->handle(new PortalMail('', 'noreply@fewo-direkt.de', 'Neue Buchung', "Anreise: 07.11.2026\nAbreise: 10.11.2026\nBuchungsnummer: HA-API1", CarbonImmutable::now())); + $this->assertSame(1, Booking::query()->count()); + } + + public function test_a_mail_first_and_the_api_event_afterwards_stay_one_case(): void + { + app(ProcessPortalMail::class)->handle(new PortalMail('', 'noreply@fewo-direkt.de', 'Neue Buchung', "Anreise: 14.11.2026\nAbreise: 18.11.2026\nBuchungsnummer: HA-API2", CarbonImmutable::now())); + $this->assertSame(1, Booking::query()->count()); + + $decision = $this->handle(new IncomingBooking($this->provenance('HA-API2'), CarbonImmutable::parse('2026-11-14'), CarbonImmutable::parse('2026-11-18'))); + + $this->assertSame(IntakeOutcome::Link, $decision->outcome); + $this->assertSame(1, Booking::query()->count()); + } + + public function test_an_api_booking_without_reference_or_with_another_reference_on_the_same_nights_is_clarified(): void + { + $this->assertSame(IntakeOutcome::Clarify, $this->handle(new IncomingBooking($this->provenance(null), CarbonImmutable::parse('2026-12-01'), CarbonImmutable::parse('2026-12-05')))->outcome); + $this->assertSame(0, Booking::query()->count()); + + $this->handle(new IncomingBooking($this->provenance('HA-A'), CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14'))); + $this->assertSame(IntakeOutcome::Clarify, $this->handle(new IncomingBooking($this->provenance('HA-B'), CarbonImmutable::parse('2026-12-10'), CarbonImmutable::parse('2026-12-14')))->outcome); + $this->assertSame(1, Booking::query()->count()); + } + + public function test_a_cancellation_report_is_a_task_and_never_a_cancellation(): void + { + $case = $this->booking('HA-C'); + + $decision = $this->handle(new BookingCancelledByChannel($this->provenance('HA-C', 'evt-1'), 'vom Gast im Portal')); + $this->handle(new BookingCancelledByChannel($this->provenance('HA-C', 'evt-1'), 'vom Gast im Portal')); + + $case->refresh(); + $this->assertSame(IntakeOutcome::CancellationSignal, $decision->outcome); + $this->assertSame(BookingStatus::Confirmed, $case->status, 'the booking stays binding'); + $this->assertNull($case->cancelled_at); + $this->assertSame(1, BookingTask::query()->where('booking_id', $case->id)->where('kind', BookingTaskKind::PortalCancellationReported)->count(), 'one task, also when repeated'); + $this->assertFalse($case->payments()->where('kind', PaymentKind::Refund)->exists()); + $this->assertNotNull(OutwardSuspension::reason($case), 'O4: automatic messages wait'); + $this->assertTrue(Booking::query()->occupying()->whereKey($case->id)->exists(), 'the calendar stays blocked'); + + $this->assertSame(IntakeOutcome::Clarify, $this->handle(new BookingCancelledByChannel($this->provenance('UNBEKANNT', 'evt-2')))->outcome, 'an unassigned report stops nothing'); + } + + public function test_a_change_report_leaves_the_booking_as_it_is(): void + { + $case = $this->booking('HA-D'); + + $this->handle(new BookingChangedByChannel($this->provenance('HA-D', 'evt-3'), CarbonImmutable::parse('2026-11-08'), CarbonImmutable::parse('2026-11-12'), 3)); + + $case->refresh(); + $this->assertSame(['2026-11-07', '2026-11-10'], [$case->arrival->toDateString(), $case->departure->toDateString()]); + $this->assertTrue(BookingTask::query()->where('booking_id', $case->id)->where('kind', BookingTaskKind::PortalChangeReported)->exists()); + } + + public function test_portal_payments_and_payouts_are_only_stated_by_the_portal(): void + { + $case = $this->booking('HA-E'); + + $this->handle(new PaymentReported($this->provenance('HA-E', 'p1'), 39061, CarbonImmutable::parse('2026-10-22'))); + $this->handle(new PaymentReported($this->provenance('HA-E', 'p1'), 39061, CarbonImmutable::parse('2026-10-22'))); + $this->handle(new PayoutReported($this->provenance('HA-E', 'p2'), 89469, CarbonImmutable::parse('2026-11-12'), executed: true)); + + $case->refresh(); + $this->assertSame(1, $case->payments()->where('kind', PaymentKind::GuestViaPortal)->count(), 'recorded once, "laut Portal"'); + $this->assertSame(0, $case->payments()->whereIn('kind', [PaymentKind::Guest, PaymentKind::PortalPayout])->count(), 'never money on our account by a report'); + $this->assertTrue($case->events()->where('type', 'evidence')->exists(), 'the payout is evidence "laut Portal"'); + } + + public function test_only_portals_deliver_events(): void + { + $this->expectException(InvalidArgumentException::class); + $this->handle(new PaymentReported(new Provenance(Channel::websiteOf(Property::sole()), 'api', Provenance::AUTHENTICATED, 'X', 'e', CarbonImmutable::now()), 1, CarbonImmutable::now())); + } + + /** N7: a new portal interface needs only its adapter and its registry entry. */ + public function test_a_new_api_adapter_uses_the_same_intake(): void + { + config(['channels.connectors' => [...config('channels.connectors'), FakeApiConnector::class]]); + Http::fake(['api.portal.example/*' => Http::response(['bookings' => [['reference' => 'HA-N7', 'arrival' => '2026-11-21', 'departure' => '2026-11-24', 'guests' => 2, 'paid' => 10000, 'paid_on' => '2026-10-22']]])]); + $this->assertArrayHasKey('fake_api', app(ChannelRegistry::class)->connectors()); + + foreach (app(FakeApiConnector::class)->fetchEvents($this->fewo, null) as $event) { + $this->handle($event); + } + foreach (app(FakeApiConnector::class)->fetchEvents($this->fewo, null) as $event) { + $this->handle($event); + } + + $case = Booking::query()->sole(); + $this->assertSame(['HA-N7', 'a4.portal_booking'], [$case->portal_reference, $case->profile['plan']['model']]); + $this->assertSame(1, $case->payments()->where('kind', PaymentKind::GuestViaPortal)->count()); + } + + private function booking(string $reference): Booking + { + $this->handle(new IncomingBooking($this->provenance($reference), CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'))); + + return Booking::query()->where('portal_reference', $reference)->sole(); + } + + private function provenance(?string $reference, string $evidence = 'evt'): Provenance + { + return new Provenance($this->fewo, 'api', Provenance::AUTHENTICATED, $reference, $evidence.'-'.($reference ?? 'none'), CarbonImmutable::now()); + } + + private function handle(object $event): ?IntakeDecision + { + return app(ChannelEventHandler::class)->handle($event); + } +} diff --git a/tests/Feature/Process/ProcessTestRunRetentionTest.php b/tests/Feature/Process/ProcessTestRunRetentionTest.php new file mode 100644 index 0000000..29cf89b --- /dev/null +++ b/tests/Feature/Process/ProcessTestRunRetentionTest.php @@ -0,0 +1,46 @@ +travelTo(CarbonImmutable::parse('2026-10-23 10:00')); + $this->seed(PropertySeeder::class); + $channel = Channel::websiteOf(Property::sole()); + $user = User::factory()->create(); + $run = fn (): ProcessTestRun => ProcessTestRun::query()->create(['tenant_id' => $channel->tenant_id, 'channel_id' => $channel->id, 'user_id' => $user->id, 'intake' => 'inquiry', 'scenario' => 'complete_request', 'configuration' => [], 'inputs' => [], 'steps' => 1, 'report' => [], 'outcome' => ProcessTestRun::COMPLETED]); + + $old = $run(); + $this->travel(29)->days(); + $recent = $run(); + $this->travel(2)->days(); + + $this->assertSame(30, config('fewo.retention.process_test_run_days')); + $this->assertArrayHasKey('fewo.retention.process_test_run_days', SystemSettings::EDITABLE); + app(AnonymizeGuests::class)->handle(); + + $this->assertModelMissing($old); + $this->assertModelExists($recent); + } +} diff --git a/tests/Feature/Process/ProcessTesterSecurityTest.php b/tests/Feature/Process/ProcessTesterSecurityTest.php new file mode 100644 index 0000000..b334b80 --- /dev/null +++ b/tests/Feature/Process/ProcessTesterSecurityTest.php @@ -0,0 +1,192 @@ +travelTo(CarbonImmutable::parse('2026-10-23 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + Settings::tenant()->update(['test_recipient' => 'vermieter@example.org', 'mailbox_password' => 'geheim']); + $this->website = Channel::websiteOf(Property::sole()); + $this->user = User::factory()->create(); + ProcessTesterTest::template(); + + $this->operational = storage_path('framework/testing/operational-'.getmypid().'.sqlite'); + File::ensureDirectoryExists(dirname($this->operational)); + @unlink($this->operational); + $pdo = new PDO('sqlite:'.$this->operational); + $pdo->exec('create table probe (id integer primary key, value text)'); + $pdo->exec("insert into probe (value) values ('real')"); + $pdo = null; + } + + protected function tearDown(): void + { + @unlink($this->operational); + @unlink(base_path('sandbox-probe.txt')); + parent::tearDown(); + } + + /** + * @return array + */ + public static function forbidden(): array + { + return [ + 'N-DB1 other connection' => ['db_other_connection', 'database'], + 'N-DB3 new connection to the real file' => ['db_new_connection', 'database'], + 'N-DB3 sandbox redirected to the real file' => ['db_redirected_sandbox', 'database'], + 'N-NET1 network without scripted answer' => ['network', 'network'], + 'N-NET2 automation webhook' => ['webhook', 'network'], + 'N-IMAP mailbox' => ['imap', 'imap'], + 'N-MAIL other mailer' => ['mail_other_mailer', 'mail'], + 'N-FILE storage outside the run' => ['file_outside', 'file'], + 'N-CACHE other store' => ['cache_other_store', 'cache'], + ]; + } + + #[DataProvider('forbidden')] + public function test_a_forbidden_access_is_recorded_aborts_the_run_and_changes_nothing(string $case, string $kind): void + { + $before = hash_file('sha256', $this->operational); + + $run = $this->probe($case); + + $this->assertSame(ProcessTestRun::ABORTED, $run->outcome, json_encode($run->report)); + $this->assertSame($kind, $run->report['violations'][0]['kind'] ?? null, json_encode($run->report['violations'])); + $this->assertSame($before, hash_file('sha256', $this->operational), 'the operational database file is unchanged'); + $this->assertFileDoesNotExist(base_path('sandbox-probe.txt')); + $this->assertSame(0, Booking::query()->count()); + } + + /** N-DB2: the run's own database has no access to the operational tables at all. */ + public function test_the_runs_database_does_not_contain_the_operational_tables(): void + { + $before = hash_file('sha256', $this->operational); + + $run = $this->probe('db_operational_table'); + + $probe = collect($run->report['timeline'][0]['effects'] ?? [])->firstWhere('type', 'probe'); + $this->assertSame('QueryException', $probe['outcome'] ?? null); + $this->assertSame($before, hash_file('sha256', $this->operational)); + } + + /** No credentials, no real configuration, no real cases inside the run; its key is its own. */ + public function test_the_run_has_no_credentials_no_real_data_and_its_own_key(): void + { + Booking::factory()->for(Property::sole())->create(); + + $run = $this->probe('environment'); + + $probe = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe'); + $this->assertFalse($probe['db_password_env']); + $this->assertSame(['sandbox'], $probe['connections']); + $this->assertSame(['array'], $probe['mailers']); + $this->assertNull($probe['smtp_password']); + $this->assertTrue($probe['app_key_differs']); + $this->assertSame([0, 0], [$probe['bookings'], $probe['guests']], 'no real case or guest is copied'); + $snapshot = SandboxSnapshot::build($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer']); + $this->assertArrayNotHasKey('bookings', $snapshot['tables']); + $this->assertNull($snapshot['tables']['tenants'][0]['mailbox_password']); + } + + /** N-SIGN: a link signed inside a run is worthless in the real application. */ + public function test_a_link_signed_in_a_run_is_invalid_outside(): void + { + $run = $this->probe('signed_link'); + + $url = collect($run->report['timeline'][0]['effects'])->firstWhere('type', 'probe')['url']; + $this->assertStringContainsString('signature=', $url); + $this->assertFalse(URL::hasValidSignature(Request::create($url))); + } + + /** N-TOKEN: the run command refuses to work outside a run the tester started. */ + public function test_the_run_command_refuses_outside_a_prepared_run(): void + { + $this->artisan('process:sandbox-run', ['run' => '00000000-0000-0000-0000-000000000000'])->assertFailed(); + } + + /** N-PAR: one run per landlord at a time. */ + public function test_a_second_run_of_the_same_landlord_waits(): void + { + $directory = storage_path('app/sandbox/slots'); + File::ensureDirectoryExists($directory); + $lock = fopen($directory.'/tenant-'.$this->website->tenant_id.'.lock', 'c'); + flock($lock, LOCK_EX | LOCK_NB); + + try { + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('läuft bereits'); + $this->probe('none'); + } finally { + flock($lock, LOCK_UN); + fclose($lock); + } + } + + /** N-ABORT: the directory of an aborted run is removed by the next run. */ + public function test_leftovers_of_aborted_runs_are_removed(): void + { + $left = storage_path('app/sandbox/runs/11111111-1111-1111-1111-111111111111'); + File::ensureDirectoryExists($left); + touch($left, time() - 7200); + + $this->probe('none'); + + $this->assertDirectoryDoesNotExist($left); + } + + private function probe(string $case): ProcessTestRun + { + config(['fewo.sandbox.test_environment' => [ + 'FEWO_SANDBOX_PROBE' => HostileProbe::class, + 'FEWO_SANDBOX_PROBE_CASE' => $case, + 'FEWO_SANDBOX_PROBE_FILE' => $this->operational, + 'FEWO_SANDBOX_PROBE_PARENT_KEY' => (string) config('app.key'), + 'APP_ENV' => 'testing', + ]]); + + return app(ProcessSandbox::class)->run($this->website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', ['arrival' => '2026-11-07', 'nights' => 3], 1, $this->user); + } +} diff --git a/tests/Feature/Process/ProcessTesterTest.php b/tests/Feature/Process/ProcessTesterTest.php new file mode 100644 index 0000000..ad27a59 --- /dev/null +++ b/tests/Feature/Process/ProcessTesterTest.php @@ -0,0 +1,186 @@ +travelTo(CarbonImmutable::parse('2026-10-23 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051', 'test_recipient' => 'vermieter@example.org', 'process_defaults' => ['processing' => 'automatic', 'clarification_hold_auto_minutes' => 120, 'data_request_mode' => 'automatic']]); + $this->user = User::factory()->create(); + self::template(); + } + + public static function template(): void + { + $template = storage_path('app/sandbox/template.sqlite'); + $newest = max(array_map('filemtime', glob(database_path('migrations/*.php')))); + if (! is_file($template) || filemtime($template) < $newest) { + // A fresh process, as at deployment (the migrator binds the schema of the process that runs it). + Process::path(base_path())->timeout(120)->run([PHP_BINARY, 'artisan', 'process:sandbox-template'])->throw(); + } + } + + public function test_a_scenario_runs_isolated_with_the_real_business_logic_and_leaves_no_trace(): void + { + Mail::fake(); + $website = Channel::websiteOf($this->property); + + $run = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'missing_address', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 3, $this->user); + + $report = $run->report; + $this->assertNull($report['aborted'] ?? null, json_encode($report)); + $this->assertSame(ProcessTestRun::COMPLETED, $run->outcome); + $this->assertCount(3, $report['timeline']); + $this->assertSame(['a1.offer', 1, 'A1'], [$report['plan']['model'], $report['plan']['version'], $report['plan']['case_type']]); + + // Same logic as the real case: data request and clarification hold, later the offer. + [$request, $expired, $answer] = $report['timeline']; + $this->assertStringContainsString('reserviert', $request['situation']); + $this->assertContains('tester@sandbox.invalid', array_column($request['mails'], 'to'), 'mails are simulated and go to the test address'); + $this->assertSame('Angebot gesendet', $answer['status']); + $this->assertStringContainsString('Angebot', implode(' ', array_column($answer['mails'], 'subject'))); + $this->assertSame([], $report['violations']); + + // Nothing reached the real data: no case, no mail. + $this->assertSame(0, Booking::query()->count()); + Mail::assertNothingSent(); + $this->assertDirectoryDoesNotExist(storage_path('app/sandbox/runs/'.$run->id)); + } + + public function test_a_run_with_the_same_snapshot_gives_the_same_report(): void + { + $website = Channel::websiteOf($this->property); + $inputs = ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2]; + + $first = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', $inputs, 3, $this->user); + $second = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer'], 'complete_request', $inputs, 3, $this->user); + + $strip = fn (array $report): array => array_map(fn (array $event): array => array_diff_key($event, ['effects' => true]), $report['timeline']); + $this->assertSame($strip($first->report), $strip($second->report)); + } + + public function test_the_loyalty_variant_runs_in_the_tester_only(): void + { + $website = Channel::websiteOf($this->property); + + $run = app(ProcessSandbox::class)->run($website, IntakeKind::Inquiry, ['model' => 'a1.offer', 'variant' => 'loyalty'], 'returning_guest', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 3, $this->user); + + $this->assertNull($run->report['aborted'] ?? null, json_encode($run->report)); + $this->assertSame('loyalty', $run->report['plan']['variant']); + $timeline = $run->report['timeline']; + $lines = array_column(end($timeline)['price']['lines'], 'label'); + $this->assertNotEmpty(array_filter($lines, fn (string $label): bool => str_starts_with($label, 'Stammgastrabatt')), 'the discount enters the price before it is fixed'); + $this->assertNull($website->fresh()->process_overrides['inquiry']['variant'] ?? null, 'nothing was saved'); + } + + /** S07/S08/S13: a portal booking by mail (twice), portal amounts and a cancellation report – A4 of FeWo-direkt */ + public function test_a_portal_booking_scenario_with_cancellation_report(): void + { + $fewo = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'mixed', 'status' => 'setup', 'is_active' => false, 'import_enabled' => false, 'settings' => ['import_url' => 'https://www.fewo-direkt.de/x.ics']]); + + $run = app(ProcessSandbox::class)->run($fewo, IntakeKind::Booking, ['model' => 'a4.portal_booking', 'settings' => ['guest_messages' => 'portal']], 'portal_booking', ['arrival' => '2026-11-14', 'nights' => 4, 'guests' => 2, 'portal_total' => 980, 'cancellation' => true], 6, $this->user); + + $report = $run->report; + $this->assertNull($report['aborted'] ?? null, json_encode($report)); + $this->assertSame(['a4.portal_booking', 'A4'], [$report['plan']['model'], $report['plan']['case_type']]); + [$mail, $repeated, , $amounts, $cancellation] = $report['timeline']; + $this->assertSame('Bestätigt', $mail['status'] ?? null, json_encode($mail)); + $this->assertSame($mail['situation'], $repeated['situation'], 'the same mail twice: one case'); + $this->assertStringContainsString('laut Portal', implode(' ', array_column($amounts['activities'], 'detail'))); + $this->assertContains('Das Portal meldet eine Stornierung – bitte prüfen', array_column($cancellation['activities'], 'label')); + $this->assertSame('Bestätigt', $cancellation['status'], 'the report never cancels'); + $this->assertSame(0, Booking::query()->count()); + $this->assertFalse((bool) $fewo->fresh()->is_active, 'the real channel is unchanged'); + } + + /** S12/T06: a failing mail server leaves the case in a defined state */ + public function test_a_mail_failure_keeps_the_case(): void + { + $run = app(ProcessSandbox::class)->run(Channel::websiteOf($this->property), IntakeKind::Inquiry, ['model' => 'a1.offer'], 'mail_failure', ['arrival' => '2026-11-07', 'nights' => 3, 'guests' => 2], 2, $this->user); + + $request = $run->report['timeline'][1]; + $this->assertNull($run->report['aborted'] ?? null); + // v0.11 behaviour: the offer is saved even if its mail fails (SendOffer reports it); nothing went out. + $this->assertSame('Angebot gesendet', $request['status'], 'the case is kept'); + $this->assertSame([], $request['mails'], 'no mail went out'); + } + + /** T01/T02: from the configurator with the unsaved draft, step by step, with a readable report */ + public function test_the_landlord_tests_the_unsaved_draft_step_by_step(): void + { + $this->actingAs($this->user); + $website = Channel::websiteOf($this->property); + + $configurator = Livewire::test(ChannelProcess::class, ['record' => $website->getRouteKey()]) + ->call('toggleStep', 'review.request') + ->call('test'); + $configurator->assertRedirect(); + $this->assertFalse(session('process-tester.draft.'.$website->id.'.inquiry')['steps']['review.request']['on']); + + Livewire::test(ChannelProcessTest::class, ['record' => $website->getRouteKey()]) + ->assertSee('Vollständige Anfrage bis zur Buchung') + ->set('inputs.arrival', '2026-11-07') + ->call('start') + ->assertSee('Bericht') + ->assertSee('Gast fragt mit allen Angaben an') + ->assertSee('simuliert') + ->call('next') + ->assertSee('Sie senden das Angebot'); + $this->assertNull($website->fresh()->process_overrides['inquiry']['steps'] ?? null, 'the draft was never saved'); + $this->assertSame(2, ProcessTestRun::query()->count()); + } + + public function test_without_the_isolation_the_tester_is_locked(): void + { + $this->actingAs($this->user); + $template = storage_path('app/sandbox/template.sqlite'); + rename($template, $template.'.off'); + + try { + Livewire::test(ChannelProcessTest::class, ['record' => Channel::websiteOf($this->property)->getRouteKey()]) + ->assertSee('auf diesem Server gesperrt') + ->assertDontSee('Test starten'); + } finally { + rename($template.'.off', $template); + } + } +} diff --git a/tests/Feature/Process/SettlementClarificationTest.php b/tests/Feature/Process/SettlementClarificationTest.php new file mode 100644 index 0000000..8b396eb --- /dev/null +++ b/tests/Feature/Process/SettlementClarificationTest.php @@ -0,0 +1,78 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed(PropertySeeder::class); + Mail::fake(); + $portal = Channel::factory()->for(Property::sole())->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking', 'process_overrides' => ['booking' => ['payments' => 'portal']]]); + $this->booking = Booking::factory()->for(Property::sole())->create(['status' => BookingStatus::Completed, 'intake' => 'booking', 'import_channel_id' => $portal->id, 'origin_channel_id' => $portal->id, + 'arrival' => '2026-10-10', 'departure' => '2026-10-17', 'total' => 97951, 'completed_at' => now()]); + app(RecordPortalAmounts::class)->handle($this->booking->fresh(), null, [['kind' => 'payout_announced', 'amount' => 89469]], [], 'FeWo-direkt'); + } + + public function test_a_reason_alone_does_not_settle_an_open_payout(): void + { + $this->expectException(ReservationException::class); + CaseClosure::settle($this->booking->fresh(), 'Portal hat ausgezahlt', 'Lars'); + } + + public function test_an_open_claim_stays_traceable_and_the_case_stays_commercially_open(): void + { + CaseClosure::settle($this->booking->fresh(), 'Auszahlung fehlt, beim Portal nachgefragt', 'Lars', CaseClosure::CLAIM_OPEN); + + $this->assertNull($this->booking->fresh()->settled_at); + $this->assertTrue(BookingTask::query()->where('booking_id', $this->booking->id)->where('kind', BookingTaskKind::OpenClaim)->where('status', BookingTaskStatus::Open)->exists()); + } + + public function test_a_written_off_claim_settles_with_its_clarification_on_record(): void + { + CaseClosure::settle($this->booking->fresh(), 'Kulanz, Betrag ausgebucht', 'Lars', 'written_off'); + + $booking = $this->booking->fresh(); + $this->assertNotNull($booking->settled_at); + $this->assertSame('Forderung ausgebucht: Kulanz, Betrag ausgebucht', $booking->settled_note); + } + + public function test_the_received_payout_settles_by_itself(): void + { + app(RecordPayment::class)->handle($this->booking->fresh(), 89469, CarbonImmutable::today(), kind: PaymentKind::PortalPayout, source: 'FeWo-direkt'); + + $this->assertNotNull($this->booking->fresh()->settled_at); + } +} diff --git a/tests/Feature/Process/SideEffectPathsTest.php b/tests/Feature/Process/SideEffectPathsTest.php new file mode 100644 index 0000000..dfdd4d7 --- /dev/null +++ b/tests/Feature/Process/SideEffectPathsTest.php @@ -0,0 +1,63 @@ + what it is). */ + private const FORBIDDEN = [ + '/new\s+\\\\?PDO\b/' => 'own database connection', + '/->getPdo\(/' => 'raw database handle', + '/\b(fsockopen|pfsockopen|stream_socket_client|socket_create)\s*\(/' => 'socket', + '/\bcurl_[a-z_]+\s*\(/' => 'curl', + '/(?:$])(? 'mail()', + '/(?:$])(? 'file by path', + '/(?:])(exec|shell_exec|passthru|system|popen|proc_open)\s*\(/' => 'program', + '/(?:$])env\s*\(/' => 'environment outside config/', + '/\bgetenv\s*\(/' => 'environment outside config/', + ]; + + /** Files allowed to use a forbidden call, with the reason. */ + private const ALLOWED = [ + 'Console/Commands/BackupDatabase.php' => 'backup of the real database; console only, never reachable in a tester run (no scheduler there)', + 'Console/Commands/ProcessCheck.php' => 'writes MODULMATRIX.md (developer command)', + 'Console/Commands/ProcessSandboxRun.php' => 'writes the report into the run directory', + 'Console/Commands/ProcessSandboxTemplate.php' => 'builds the template file', + 'Filament/Resources/Guests/Pages/ListGuests.php' => 'CSV download to php://output', + 'Process/Tester/EffectLedger.php' => 'appends to the run ledger', + 'Process/Tester/ProcessSandbox.php' => 'slot locks and the check of proc_open', + 'Process/Tester/SandboxBootstrapper.php' => 'reads FEWO_SANDBOX_RUN and copies the template before the application starts', + 'Process/Tester/SandboxSnapshot.php' => 'none expected', + ]; + + public function test_no_native_way_around_the_framework_in_the_application(): void + { + $violations = []; + foreach (Finder::create()->files()->in(app_path())->name('*.php') as $file) { + $relative = str_replace('\\', '/', $file->getRelativePathname()); + if (array_key_exists($relative, self::ALLOWED)) { + continue; + } + $code = (string) preg_replace('~//[^\n]*|/\*.*?\*/~s', '', $file->getContents()); + foreach (self::FORBIDDEN as $pattern => $what) { + if (preg_match($pattern, $code, $match) === 1) { + $violations[] = "{$relative}: {$what} ({$match[0]})"; + } + } + } + + $this->assertSame([], $violations, 'Native calls bypass the process tester\'s isolation – use Laravel facades (DB, Http, Mail, Storage, Process).'); + } +} diff --git a/tests/Fixtures/process/intended.md b/tests/Fixtures/process/intended.md index eb43011..2d1d138 100644 --- a/tests/Fixtures/process/intended.md +++ b/tests/Fixtures/process/intended.md @@ -4,9 +4,12 @@ # Beabsichtigte Abweichungen von der v0.11-Referenz | # | Abweichung | Begründung | Test | betroffene Referenzen | |---|---|---|---|---| -| I-001 | Ereignistypen der Schrittdetails kommen aus der Moduldefinition statt aus `ActivityDetails::EVENT_TYPES` | eine Quelle (Architektur `02` §7.7) | `ActivityDetailsTest` unverändert grün | keine (gleiches Ergebnis) | +| I-001 | ~~Ereignistypen aus der Moduldefinition~~ – **entfällt**: `ActivityDetails::EVENT_TYPES` bleibt; die Moduldefinition nennt die Typen zusätzlich für Konfigurator und Analyse | – | – | – | | I-002 | Offene, einem Vorgang zugeordnete Portalmeldung (Storno/Änderung) setzt automatische **Außenwirkungen** aus: Unterlagen, Erinnerungen, Anreiseinformation | Entscheidung O4 | `PortalReportSuspendsAutomationTest` | `portal_mail_cancellation` (nur wenn Außenwirkungen anstanden) | | I-003 | ~~Zeit-Actions rufen danach `advance`~~ – **entfällt**: `bookings:auto-offers` bewertet offene Anfragen alle 5 Minuten über den Runner neu; `ExpireReservations` und `handOver` machen keinen Schritt bereit | – | – | – | | I-004 | Angebotsschritt bei belegtem Zeitraum = `problem`, ohne Senden-Aktion | Fehler F-001 | `BehaviourComparisonTest` (`a1_dates_taken`, neu aufgenommen) | `a1_dates_taken.answer_dates_taken` | | I-005 | Detail des Angebotsschritts zeigt den tatsächlichen Reservierungszustand | Fehler F-002 | `BehaviourComparisonTest` (`a1_dates_taken`), `OngoingCaseRegressionTest` (`legacy_migration_offer`) | `a1_dates_taken.answer_dates_taken`; Bestandsfall `legacy_migration_offer` | | I-006 | Technischer Fehler eines automatischen Schritts: einheitlicher Text „Technischer Fehler beim automatischen Weiterbearbeiten – bitte von Hand fortsetzen.“ je Schritt (vorher je Aufrufer eigener Text); `CreateReservation` behält seinen Text, wenn der Runner selbst scheitert | ein Ablaufkern | `ProcessRunnerTest::test_a_failing_step_is_reported_and_independent_steps_go_on` | keine (kein Fehlerfall in der Referenz) | +| I-007 | Kaufmännischer Abschluss bei Portal-Inkasso mit offener oder abweichender Auszahlung nur mit Klärungsart (Verrechnung, verbuchte Differenz, ausgebuchte Forderung) oder Überführung in eine offene Forderung; eine Begründung allein genügt nicht | Entscheidung O5 | `SettlementClarificationTest`; angepasst: `EndToEndStayAcceptanceTest::test_t22_…` (Klärungsart „Differenz geklärt und verbucht“, Notiz mit Präfix) | keine Referenzdatei | +| I-008 | Die Prozesseinstellungen eines Kanals stehen nicht mehr als flache Liste im Kanalformular, sondern unter Kanal › Ablauf am Schritt | Anforderung U-C | `ChannelProcessConfiguratorTest`; angepasst: `ChannelManagerTest::test_the_channel_manager_lists_the_website_and_saves_its_settings` | keine | + diff --git a/tests/Support/Process/FakeApiConnector.php b/tests/Support/Process/FakeApiConnector.php new file mode 100644 index 0000000..4abc68d --- /dev/null +++ b/tests/Support/Process/FakeApiConnector.php @@ -0,0 +1,58 @@ +json('bookings', []) as $row) { + $provenance = new Provenance($channel, 'api', Provenance::AUTHENTICATED, (string) $row['reference'], 'fake-api:'.$row['reference'], CarbonImmutable::now()); + $events[] = new IncomingBooking($provenance, CarbonImmutable::parse($row['arrival']), CarbonImmutable::parse($row['departure']), $row['guests'] ?? null); + if (isset($row['paid'])) { + $events[] = new PaymentReported($provenance, (int) $row['paid'], CarbonImmutable::parse($row['paid_on'])); + } + } + + return $events; + } +} diff --git a/tests/Support/Process/HostileProbe.php b/tests/Support/Process/HostileProbe.php new file mode 100644 index 0000000..d32994f --- /dev/null +++ b/tests/Support/Process/HostileProbe.php @@ -0,0 +1,66 @@ + DB::connection('mysql')->select('select 1'), + 'db_new_connection' => (function () use ($operational): void { + config(['database.connections.evil' => ['driver' => 'sqlite', 'database' => $operational, 'prefix' => '']]); + DB::connection('evil')->insert('insert into probe (value) values (?)', ['evil']); + })(), + 'db_redirected_sandbox' => (function () use ($operational): void { + config(['database.connections.sandbox.database' => $operational]); + DB::purge('sandbox'); + DB::connection('sandbox')->insert('insert into probe (value) values (?)', ['evil']); + })(), + 'db_operational_table' => DB::table('probe')->insert(['value' => 'evil']), + 'network' => Http::get('https://example.org/'), + 'webhook' => Http::withHeaders(['X-Signature' => 'x'])->post('https://n8n.example/webhook/channel-task', ['task' => 1]), + 'imap' => app(MailboxReader::class)->fetchAll(), + 'mail_other_mailer' => Mail::mailer('smtp')->raw('Test', fn ($message) => $message->to('someone@example.org')), + 'file_outside' => Storage::build(['driver' => 'local', 'root' => base_path()])->put('sandbox-probe.txt', 'evil'), + 'cache_other_store' => Cache::store('database')->put('probe', 'evil'), + 'signed_link' => EffectLedger::record('probe', ['url' => URL::temporarySignedRoute('offers.show', now()->addDay(), ['booking' => 1, 'v' => 1])]), + 'environment' => EffectLedger::record('probe', [ + 'db_password_env' => getenv('DB_PASSWORD'), + 'connections' => array_keys((array) config('database.connections')), + 'mailers' => array_keys((array) config('mail.mailers')), + 'smtp_password' => config('mail.mailers.smtp.password'), + 'app_key_differs' => config('app.key') !== getenv('FEWO_SANDBOX_PROBE_PARENT_KEY'), + 'bookings' => DB::table('bookings')->count(), + 'guests' => DB::table('guests')->count(), + ]), + default => null, + }; + EffectLedger::record('probe', ['case' => $case, 'outcome' => 'no exception']); + } catch (Throwable $exception) { + EffectLedger::record('probe', ['case' => $case, 'outcome' => class_basename($exception), 'message' => mb_substr($exception->getMessage(), 0, 200)]); + + throw $exception; + } + } +}