U-D/U-E/O5: Prozess-Tester im eigenen Prozess (standardmäßig gesperrt, 15 Negativtests, statischer Wächter), Szenarien und Bericht, Kanalereignisse (API-Eingang ohne Umbau von iCal/Mail), Abschluss nach finanzieller Klärung, Löschfrist 30 Tage

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-04 15:34:40 +01:00
1 parent c255783cec
commit 0689c0a591
68 files changed
+3350 -35

No files matched your search

+4
View File
@@ -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')))
+1 -1
View File
@@ -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) {
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\Events\ChannelEvent;
use App\Models\Channel;
use Carbon\CarbonImmutable;
/**
* Capability of a connector whose portal offers an interface for bookings, cancellations, changes and amounts
* (Architektur V2, 02 §8.4). The events go to ChannelEventHandler; the connector itself decides nothing. Network access
* only through the Http facade (SideEffectPathsTest), so the process tester can replace it.
*/
interface DeliversEvents
{
/**
* @return list<ChannelEvent>
*/
public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array;
}
@@ -0,0 +1,19 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\Events\ChannelEvent;
use App\Models\Channel;
use Illuminate\Http\Request;
/**
* Capability of a connector whose portal pushes events (webhook). The connector verifies the signature (authenticity
* of the origin) and translates the payload; the business decision stays with ChannelEventHandler.
*/
interface ReceivesWebhooks
{
/**
* @return list<ChannelEvent> empty when the signature is not valid
*/
public function receive(Channel $channel, Request $request): array;
}
@@ -0,0 +1,14 @@
<?php
namespace App\Channels\Events;
/**
* The portal reports a cancellation of a known booking: a task on the case, never a cancellation, refund or fee (E-019).
*/
final readonly class BookingCancelledByChannel extends ChannelEvent
{
public function __construct(Provenance $provenance, public ?string $note = null)
{
parent::__construct($provenance);
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal reports other dates or guests of a known booking: a task with the comparison, never a change of the booking.
*/
final readonly class BookingChangedByChannel extends ChannelEvent
{
public function __construct(Provenance $provenance, public ?CarbonImmutable $arrival = null, public ?CarbonImmutable $departure = null, public ?int $guests = null)
{
parent::__construct($provenance);
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Channels\Events;
/**
* A normalised business event of a portal, independent of its transport (Architektur V2, K4/K10). Future API or
* webhook adapters deliver these; ChannelEventHandler maps them onto the existing intake, so duplicates, origin and the
* external binding are judged in one place for every transport.
*/
abstract readonly class ChannelEvent
{
public function __construct(public Provenance $provenance) {}
}
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Channels\Events;
use App\Actions\RecordPortalAmounts;
use App\Channels\Intake\IntakeDecision;
use App\Channels\Intake\PortalIntake;
use App\Enums\IntakeOutcome;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\IntakeObservation;
use App\Process\CaseLog;
use App\Support\Money;
use App\Tenancy\TenantContext;
use InvalidArgumentException;
/**
* The one entry of channel events (docs/Prozessarchitektur/Architektur/02 §8.3–8.4): maps each normalised event onto
* the existing intake, so iCal, mail and future APIs are judged by the same rules – duplicates and certainty in
* PortalIntake, amounts in RecordPortalAmounts, reports about known cases as tasks. Contains no decision rules of its
* own and never changes a binding booking (stage M4 needs the landlord's action).
*/
final class ChannelEventHandler
{
public function __construct(private PortalIntake $intake, private RecordPortalAmounts $amounts) {}
public function handle(ChannelEvent $event): ?IntakeDecision
{
$channel = $event->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;
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* A booking binding at the portal (M1/M2): its dates and reference; becomes a case only through PortalIntake's certainty rules.
*/
final readonly class IncomingBooking extends ChannelEvent
{
public function __construct(Provenance $provenance, public CarbonImmutable $arrival, public CarbonImmutable $departure, public ?int $guests = null, public ?int $total = null)
{
parent::__construct($provenance);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal reports a payment of the guest to the portal: recorded "laut Portal" (GuestViaPortal), never as money on our account.
*/
final readonly class PaymentReported extends ChannelEvent
{
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn)
{
parent::__construct($provenance);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Channels\Events;
use Carbon\CarbonImmutable;
/**
* The portal announces or reports a payout to us: "laut Portal" only – a received payout is recorded by the landlord (decision O5).
*/
final readonly class PayoutReported extends ChannelEvent
{
public function __construct(Provenance $provenance, public int $amount, public CarbonImmutable $paidOn, public bool $executed = false)
{
parent::__construct($provenance);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace App\Channels\Events;
use App\Models\Channel;
use Carbon\CarbonImmutable;
/**
* Where a channel event came from (docs/Prozessarchitektur/Architektur/02 §8.2): channel, transport and whether its
* origin is technically authenticated (a signed webhook, an API call with credentials). It says nothing about whether a
* business action really happened – that is evidence, which only the landlord or a checked receipt provides (M3).
*/
final readonly class Provenance
{
public const AUTHENTICATED = 'authenticated';
public const UNAUTHENTICATED = 'unauthenticated';
public function __construct(
public Channel $channel,
public string $transport,
public string $authenticity,
public ?string $externalReference,
public string $evidenceRef,
public CarbonImmutable $receivedAt,
) {}
public function isAuthenticated(): bool
{
return $this->authenticity === self::AUTHENTICATED;
}
}
+19 -2
View File
@@ -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) {
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Process\Tester\EffectLedger;
use App\Process\Tester\ProcessSandboxDriver;
use App\Process\Tester\SandboxBootstrapper;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
/**
* Entry of a tester run – only inside the process ProcessSandbox starts for it (environment FEWO_SANDBOX_RUN, so the
* SandboxBootstrapper has turned the process into a sandbox before anything was resolved). Reads input.json of the run
* and writes report.json; never touches anything outside the run's directory.
*/
#[Signature('process:sandbox-run {run : id of the prepared run}')]
#[Description('Play a process tester scenario inside its isolated process (started by the process tester only)')]
class ProcessSandboxRun extends Command
{
public function handle(ProcessSandboxDriver $driver): int
{
if (! SandboxBootstrapper::active() || (string) getenv(SandboxBootstrapper::ENV) !== (string) $this->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;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
/**
* Builds the migrated, empty SQLite template of the process tester's databases (storage/app/sandbox/template.sqlite).
* Run at every deployment after the migrations; a run copies it instead of migrating. Touches only that file.
*/
#[Signature('process:sandbox-template')]
#[Description('Build the empty, migrated SQLite template for process tester runs')]
class ProcessSandboxTemplate extends Command
{
public function handle(): int
{
if (! extension_loaded('pdo_sqlite')) {
$this->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;
}
}
@@ -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).
*
@@ -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'),
];
}
}
@@ -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).
*/
@@ -0,0 +1,151 @@
<?php
namespace App\Filament\Resources\Channels\Pages;
use App\Enums\IntakeKind;
use App\Enums\UserRole;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use App\Process\Tester\ProcessSandbox;
use App\Process\Tester\ScenarioCatalogue;
use App\Process\Tester\Scenarios\Scenario;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\Concerns\InteractsWithRecord;
use Filament\Resources\Pages\Page;
use Throwable;
/**
* Ablauf testen (docs/Prozessarchitektur/Architektur/04): plays a predefined scenario with the channel's current – also
* unsaved – process configuration in an isolated run and shows the report step by step. Nothing of a run reaches the
* real data, mails, calendars or portals; on a server where the isolation cannot be established the tester is locked
* and says why. Landlord administrators only (decision E8).
*
* @property Channel $record
*/
class ChannelProcessTest extends Page
{
use InteractsWithRecord;
protected static string $resource = ChannelResource::class;
protected static ?string $title = 'Ablauf testen';
protected string $view = 'filament.resources.channels.channel-process-test';
public string $intake = 'inquiry';
public string $scenario = '';
/** @var array<string, mixed> */
public array $inputs = [];
/** @var array<string, mixed> */
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<string, class-string<Scenario>>
*/
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<string>
*/
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<ProcessTestRun>
*/
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])),
];
}
}
+3
View File
@@ -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.
*
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A stored report of the process tester: scenario, configuration (also unsaved), inputs, the report of the isolated
* run. Contains only synthetic case data; deleted after the retention period (decision O3).
*/
#[Fillable(['tenant_id', 'channel_id', 'user_id', 'intake', 'scenario', 'configuration', 'inputs', 'steps', 'report', 'outcome', 'release'])]
class ProcessTestRun extends Model
{
use BelongsToTenant;
public const COMPLETED = 'completed';
public const ABORTED = 'aborted';
protected function casts(): array
{
return [
'configuration' => 'array',
'inputs' => 'array',
'report' => 'array',
];
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
}
+31 -1
View File
@@ -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);
+2
View File
@@ -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);
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Process\Tester;
/**
* The record of a tester run: every simulated effect and every violation, appended line by line to a file in the
* run's directory – it survives exceptions, and what an action swallowed is still there.
*/
final class EffectLedger
{
private static ?string $path = null;
public static function open(string $path): void
{
self::$path = $path;
}
public static function isOpen(): bool
{
return self::$path !== null;
}
/**
* @param array<string, mixed> $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<array<string, mixed>>
*/
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'));
}
}
+199
View File
@@ -0,0 +1,199 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\User;
use App\Process\ChannelProcessConfiguration;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Illuminate\Support\Str;
use RuntimeException;
/**
* The process tester seen from the landlord's request (docs/Prozessarchitektur/Architektur/04 §3.2): checks that the
* isolation can be established on this server, prepares a run (read-only snapshot, run directory), starts the run in a
* process of its own – which knows neither the real database nor any real service – waits for its report, stores the
* report and removes the run's directory. The landlord's request never switches into sandbox mode itself.
*/
final class ProcessSandbox
{
/** At most this many runs at the same time on the server (one per landlord). */
public const SLOTS = 3;
public const TIMEOUT_SECONDS = 30;
/**
* What keeps the tester from running safely here (empty = it may run). Checked in the request that would start it.
*
* @return list<string>
*/
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<string, mixed> $draft
* @param array<string, mixed> $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/<timestamp>-<commit> (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<string, string|false>
*/
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<resource> 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.');
}
}
+207
View File
@@ -0,0 +1,207 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Process\CaseActivities;
use App\Process\CaseContext;
use App\Process\ProcessCatalogue;
use App\Process\ProcessPlan;
use App\Process\ProcessProfile;
use App\Process\Tester\Scenarios\Scenario;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Event;
use Symfony\Component\Mime\Email;
use Throwable;
/**
* Plays a scenario inside the tester process (docs/Prozessarchitektur/Architektur/04 §2): seeds the run's own database
* from the snapshot, then triggers the scenario's events through the real entry points and reads the case's course
* after each one with the same method the case page uses. Contains no business rules of its own.
*/
final class ProcessSandboxDriver
{
public const MAX_EVENTS = 60;
public const MAX_SECONDS = 20;
private int $mailsSeen = 0;
private int $ledgerSeen = 0;
/** @var list<Email> every mail of the run (simulated: the only mailer is `array`) */
private array $sent = [];
/**
* @param array<string, mixed> $input input.json of the run
* @return array<string, mixed> 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<string, mixed>
*/
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<string, mixed>
*/
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<array{subject: string, to: string, excerpt: string}>
*/
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));
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Process\Tester;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Support\ServiceProvider;
use Monolog\Handler\NullHandler;
use RuntimeException;
/**
* Turns the process that runs a tester scenario into a sandbox before anything is resolved (requirement T2,
* docs/Prozessarchitektur/Architektur/04 §3.3). Called right after the configuration is loaded and only when the
* process was started for a run (environment FEWO_SANDBOX_RUN, set by ProcessSandbox for its child process).
*
* Default deny: the configuration is replaced, not amended – the only database is the run's own SQLite file, the only
* mailer `array`, the only cache store `array`, the queue `sync`, every disk lies in the run's directory, logging goes
* to the run's log, all secrets are blanked and the application key is a fresh one per run (links and encrypted values
* of a run are worthless outside it). Whatever is not configured does not exist in this process.
*/
final class SandboxBootstrapper
{
public const ENV = 'FEWO_SANDBOX_RUN';
public static function active(): bool
{
return filled(getenv(self::ENV) ?: null);
}
public static function directory(string $run): string
{
if (preg_match('/^[a-f0-9-]{36}$/', $run) !== 1) {
throw new RuntimeException('Ungültige Laufkennung.');
}
return storage_path('app/sandbox/runs/'.$run);
}
public static function configure(Application $app): void
{
$run = (string) getenv(self::ENV);
$directory = self::directory($run);
if (! is_dir($directory) || ! is_file($directory.'/input.json')) {
throw new RuntimeException('Prozess-Tester: Laufverzeichnis fehlt.');
}
$config = $app['config'];
// The run's own database: a copy of the migrated, empty template made at deployment (process:sandbox-template).
$template = storage_path('app/sandbox/template.sqlite');
if (! is_file($directory.'/db.sqlite')) {
if (! is_file($template) || ! copy($template, $directory.'/db.sqlite')) {
throw new RuntimeException('Prozess-Tester: Vorlage der Testdatenbank fehlt (php artisan process:sandbox-template).');
}
}
$config->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;
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Process\Tester;
use App\Channels\ChannelRegistry;
use App\Channels\Contracts\ChannelConnector;
/**
* The connectors of a tester run: none reaches a portal. A scenario delivers portal data as events of its own.
*/
final class SandboxChannelRegistry extends ChannelRegistry
{
public function connectors(): array
{
return [];
}
public function resolve(string $key): ChannelConnector
{
throw SandboxViolation::record('connector', "Portalanbindung [{$key}] ist im Prozess-Tester nicht erlaubt.");
}
}
+88
View File
@@ -0,0 +1,88 @@
<?php
namespace App\Process\Tester;
use App\Actions\CreateReservation;
use App\Actions\PrepareStays;
use App\Actions\RequestReviews;
use App\Actions\SendBookingReminders;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Date;
/**
* What the events of a scenario work with inside a tester run: the tested channel and intake kind, the property, the
* case the scenario created, the landlord's inputs and the simulated clock.
*/
final class SandboxContext
{
public ?Booking $booking = null;
/**
* @param array<string, mixed> $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<string, string> $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);
}
}
@@ -0,0 +1,26 @@
<?php
namespace App\Process\Tester;
use App\Channels\Mail\MailboxReader;
/**
* The mailbox of a tester run: it cannot be read. Incoming mails of a scenario are fed in directly as PortalMail.
*/
final class SandboxMailboxReader extends MailboxReader
{
public function fetch(array $senders): array
{
throw SandboxViolation::record('imap', 'Postfachabruf ist im Prozess-Tester nicht erlaubt.');
}
public function fetchAll(): array
{
throw SandboxViolation::record('imap', 'Postfachabruf ist im Prozess-Tester nicht erlaubt.');
}
public function probe(array $config): int
{
throw SandboxViolation::record('imap', 'Postfachprüfung ist im Prozess-Tester nicht erlaubt.');
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Process\Tester;
use GuzzleHttp\Promise\PromiseInterface;
use Illuminate\Http\Client\Request;
use Illuminate\Support\Facades\Http;
/**
* The scripted network answers of a scenario (e.g. the landlord's AI access answering an extraction). Everything else
* is refused by SandboxServiceProvider.
*/
final class SandboxNetwork
{
/** @var array<string, callable(Request): (PromiseInterface|array<string, mixed>|null)> host => answer */
private static array $answers = [];
/**
* @param callable(Request): (PromiseInterface|array<string, mixed>|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),
};
}
}
@@ -0,0 +1,126 @@
<?php
namespace App\Process\Tester;
use App\Channels\ChannelRegistry;
use App\Channels\Mail\MailboxReader;
use Illuminate\Cache\CacheManager;
use Illuminate\Database\Connection;
use Illuminate\Database\DatabaseManager;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Http\Client\Request;
use Illuminate\Mail\MailManager;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;
/**
* Bindings of a tester process (only registered by SandboxBootstrapper): managers that refuse every name except the
* sandbox's own – recording the attempt in the run's ledger before they throw –, a guard on the sandbox connection that
* verifies the database file, a mailbox that cannot be read, no real connectors and no network without a scripted answer.
*/
final class SandboxServiceProvider extends ServiceProvider
{
public function register(): void
{
EffectLedger::open(config('sandbox.directory').'/ledger.jsonl');
// The file the run may use, fixed now: later changes of the configuration cannot widen it.
$file = (string) config('database.connections.sandbox.database');
$this->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;
});
}
}
+142
View File
@@ -0,0 +1,142 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Models\Channel;
use App\Models\Tenant;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Throwable;
/**
* What a tester run starts from (docs/Prozessarchitektur/Architektur/04 §3.2): read – never written – from the real
* database by the landlord's request, as plain values. Only the landlord's own setup: the tenant, its websites,
* properties with seasons, offers, extras, templates and texts, the channels (the tested one with the unsaved draft)
* and the calendar as anonymous blocks. Never guests, bookings, messages, facts, access data or keys: the run creates
* its cases synthetically. Encrypted values are decrypted here and encrypted again with the run's own key.
*/
final class SandboxSnapshot
{
/** Tables copied, in insert order. */
public const TABLES = ['tenants', 'sites', 'site_domains', 'properties', 'seasons', 'special_offers', 'extras', 'cancellation_policies', 'contract_templates', 'contract_annexes', 'content_blocks', 'channels', 'blocked_periods'];
/** Columns never copied (access data, tokens, raw portal data). */
public const DROPPED = [
'tenants' => ['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<string, mixed> $draft model, variant, steps, settings of the tested channel and intake kind
* @return array{tenant_id: int, channel_id: int, intake: string, tables: array<string, list<array<string, mixed>>>, encrypted: array<string, list<string>>}
*/
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<string, mixed> $row
* @return array<string, mixed>
*/
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<string, list<array<string, mixed>>>, encrypted: array<string, list<string>>} $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();
}
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Process\Tester;
use RuntimeException;
/**
* Something inside a tester run tried to reach the real world (a database other than the run's own, the network
* without a scripted answer, the mailbox, another mailer or store). It is recorded in the run's ledger before it is
* thrown, so a run that swallowed it is still reported as aborted (docs/Prozessarchitektur/Architektur/04 §3.3).
*/
final class SandboxViolation extends RuntimeException
{
public static function record(string $kind, string $message): self
{
EffectLedger::record('violation', ['kind' => $kind, 'message' => $message]);
return new self('Prozess-Tester: unzulässiger Zugriff ('.$kind.'): '.$message);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Process\Tester;
use App\Enums\IntakeKind;
use App\Process\Tester\Scenarios\CommunicationFailure;
use App\Process\Tester\Scenarios\CompleteRequest;
use App\Process\Tester\Scenarios\MissingAddress;
use App\Process\Tester\Scenarios\PortalBooking;
use App\Process\Tester\Scenarios\PortalInquiry;
use App\Process\Tester\Scenarios\ReturningGuest;
use App\Process\Tester\Scenarios\Scenario;
/**
* The predefined scenarios of the process tester (decision E9).
*/
final class ScenarioCatalogue
{
/** @var list<class-string<Scenario>> */
public const SCENARIOS = [CompleteRequest::class, MissingAddress::class, PortalInquiry::class, ReturningGuest::class, CommunicationFailure::class, PortalBooking::class];
/**
* @return array<string, class-string<Scenario>>
*/
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<Scenario>|null
*/
public static function find(string $key): ?string
{
foreach (self::SCENARIOS as $class) {
if ($class::key() === $key) {
return $class;
}
}
return null;
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
use Illuminate\Mail\Events\MessageSending;
use Illuminate\Support\Facades\Event;
use Symfony\Component\Mailer\Exception\TransportException;
/**
* S12: the mail server fails when the request comes in – the case must be kept and show a defined state (the real
* error type of the transport, no crash). The failure is simulated where every mail passes (MessageSending), without a
* transport of its own.
*/
final class CommunicationFailure extends Scenario
{
public static function key(): string
{
return 'mail_failure';
}
public static function label(): string
{
return 'Mailversand fällt aus';
}
public static function description(): string
{
return 'Beim Eingang der Anfrage ist der Mailserver nicht erreichbar. Der Vorgang bleibt erhalten und zeigt, was von Hand zu tun ist.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Mailserver fällt aus', function (SandboxContext $context): void {
Event::listen(MessageSending::class, function (): void {
throw new TransportException('Verbindung zum Mailserver fehlgeschlagen (simuliert).');
});
}),
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'])),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\AcceptOffer;
use App\Actions\SendOffer;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* S01/S06/S11: a complete request – offer (automatic or by the landlord), acceptance, binding booking, arrival, after
* departure (review request, closing; a switched-off step is shown as skipped).
*/
final class CompleteRequest extends Scenario
{
public static function key(): string
{
return 'complete_request';
}
public static function label(): string
{
return 'Vollständige Anfrage bis zur Buchung';
}
public static function description(): string
{
return 'Ein Gast fragt mit allen Angaben an, erhält das Angebot und nimmt es an; danach Anreise und Abreise.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
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);
}
}),
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))),
];
}
}
@@ -0,0 +1,57 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* S02/S03/S04/S05: a request without address – clarification hold and data request run side by side, the hold
* expires, the guest answers later (by link or by e-mail), the offer follows; finally the offer's deadline passes.
*/
final class MissingAddress extends Scenario
{
public static function key(): string
{
return 'missing_address';
}
public static function label(): string
{
return 'Fehlende Anschrift, späte Antwort';
}
public static function description(): string
{
return 'Die Anfrage kommt ohne Anschrift: Rückfrage beim Gast und Klärungsreservierung laufen nebeneinander, die Reservierung läuft ab, der Gast antwortet später.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function inputs(): array
{
return [
...parent::inputs(),
'answer_after_hours' => ['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)),
];
}
}
@@ -0,0 +1,85 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Actions\ProcessPortalMail;
use App\Actions\RecordPortalAmounts;
use App\Channels\Mail\PortalMail;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Process\Tester\SandboxContext;
use Carbon\CarbonImmutable;
/**
* S07/S08/S13: a booking binding at the portal arrives by e-mail through the same entry as the mailbox (twice:
* duplicate), guest details and the portal's amounts follow; optionally the portal reports a cancellation; then the
* stay and after departure.
*/
final class PortalBooking extends Scenario
{
public static function key(): string
{
return 'portal_booking';
}
public static function label(): string
{
return 'Feste Buchung über das Portal';
}
public static function description(): string
{
return 'Die Buchungsmail des Portals kommt (zweimal) an, Gastdaten und Portalbeträge folgen; auf Wunsch meldet das Portal eine Stornierung.';
}
public static function intakes(): array
{
return [IntakeKind::Booking];
}
public static function inputs(): array
{
return [
...parent::inputs(),
'portal_total' => ['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;
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\ContributeCaseFacts;
use App\Actions\TakeOverPortalInquiry;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Process\Tester\SandboxContext;
/**
* A2: a request of the portal – taken over like the portal's request mail, contact details from the portal, the
* address from the guest; then our own offer or information as the chosen model says.
*/
final class PortalInquiry extends Scenario
{
public static function key(): string
{
return 'portal_inquiry';
}
public static function label(): string
{
return 'Anfrage über das Portal';
}
public static function description(): string
{
return 'Das Portal leitet eine Anfrage weiter; Kontaktdaten kommen vom Portal, die Anschrift vom Gast.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public function events(array $inputs): array
{
return [
new ScenarioEvent('Portal leitet eine Anfrage weiter', function (SandboxContext $context): void {
$context->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)),
];
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Actions\SendOffer;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Guest;
use App\Process\Tester\SandboxContext;
/**
* S09/S10: a returning guest (a synthetic former stay in the run's own data) asks again – with the loyalty variant the
* status check comes first and the discount line enters the price before it is fixed. Architecture proof; the rules
* are test assumptions.
*/
final class ReturningGuest extends Scenario
{
public static function key(): string
{
return 'returning_guest';
}
public static function label(): string
{
return 'Stammgast fragt an (Architekturnachweis)';
}
public static function description(): string
{
return 'Ein Gast mit einem früheren Aufenthalt fragt erneut an. Mit der Variante „Stammgastrabatt“ wird der Status geprüft und der Rabatt vor der Preisfestlegung eingerechnet.';
}
public static function intakes(): array
{
return [IntakeKind::Inquiry];
}
public static function inputs(): array
{
return [...parent::inputs(), 'returning' => ['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);
}
}),
];
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Enums\IntakeKind;
/**
* A predefined tester scenario (decision E9): a fixed sequence of events through the same entry points as the real
* application; the landlord may change its inputs (dates, guests, missing details, returning guest, kind of failure),
* never the sequence.
*/
abstract class Scenario
{
abstract public static function key(): string;
abstract public static function label(): string;
abstract public static function description(): string;
/** @return list<IntakeKind> */
abstract public static function intakes(): array;
/**
* Inputs the landlord may change, with their defaults.
*
* @return array<string, array{label: string, default: string|int|bool, type: 'date'|'int'|'bool'|'select', options?: array<string, string>}>
*/
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<string, mixed> $inputs
* @return list<ScenarioEvent>
*/
abstract public function events(array $inputs): array;
}
@@ -0,0 +1,17 @@
<?php
namespace App\Process\Tester\Scenarios;
use App\Process\Tester\SandboxContext;
use Closure;
/**
* One event of a scenario: what happens (in plain words) and how – through the entry point the real application uses.
*/
final readonly class ScenarioEvent
{
/**
* @param Closure(SandboxContext): void $run
*/
public function __construct(public string $label, public Closure $run) {}
}
+6 -1
View File
@@ -3,6 +3,7 @@
namespace App\Providers;
use App\Process\ProcessCatalogue;
use App\Process\Tester\SandboxBootstrapper;
use App\Support\StripImageMetadata;
use App\Support\SystemSettings;
use App\Tenancy\TenantConfig;
@@ -35,7 +36,11 @@ public function boot(): void
// test recipient only until a landlord is switched live. Console and boot know the landlord only if
// there is exactly one.
try {
SystemSettings::apply();
// A process tester run keeps its own, closed configuration (SandboxBootstrapper): no stored operator
// settings – they carry SMTP and other access data – are laid over it.
if (! SandboxBootstrapper::active()) {
SystemSettings::apply();
}
$this->app->make(TenantConfig::class)->refresh();
} catch (Throwable) {
// no database yet (package discovery, first install)
+1
View File
@@ -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', ''],
+11 -1
View File
@@ -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;
+10
View File
@@ -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'),
],
/*
@@ -0,0 +1,37 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Reports of the process tester (Architektur V2, docs/Prozessarchitektur/Architektur/04 §6): synthetic runs only – no
* real guest data, no access data. Deleted after fewo.retention.process_test_run_days (decision O3: 30 days).
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('process_test_runs', function (Blueprint $table) {
$table->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');
}
};
+9
View File
@@ -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 <token>` 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/<lauf>/`), 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 <modul>`.
## 8. Bekannte Eigenheiten und Lösungen
| Problem | Ursache | Lösung (umgesetzt) |
+2
View File
@@ -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)
@@ -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: ____________
@@ -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`).
@@ -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.
@@ -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 <lauf>`). 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 `<run>/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 `<run>/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 |
@@ -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 <lauf>`, 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 (`<zeitstempel>-<commit>`) | 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`).
+1
View File
@@ -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"],
]
@@ -0,0 +1,103 @@
<x-filament-panels::page>
@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
<x-filament::section heading="So funktioniert der Test" collapsible collapsed>
<p style="font-size:.9rem">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.</p>
</x-filament::section>
@if ($requirements !== [])
<x-filament::section heading="Der Prozess-Tester ist auf diesem Server gesperrt">
<ul style="color:#b91c1c;font-size:.9rem;list-style:disc;padding-left:1.2rem">
@foreach ($requirements as $requirement)<li>{{ $requirement }}</li>@endforeach
</ul>
<p style="{{ $muted }}">Ohne diese Voraussetzungen lässt sich die Trennung von den echten Daten nicht sicher herstellen. Es gibt deshalb keinen Ausweichbetrieb.</p>
</x-filament::section>
@else
<x-filament::section heading="Szenario">
<p style="{{ $muted }}">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 }}</p>
<div style="display:flex;flex-wrap:wrap;gap:.8rem;align-items:end;margin-top:.5rem">
<label style="font-size:.85rem">Szenario
<select wire:model.live="scenario" style="{{ $input }};display:block">
@foreach ($scenarios as $key => $class)<option value="{{ $key }}">{{ $class::label() }}</option>@endforeach
</select>
</label>
@if ($class = $scenarios[$this->scenario] ?? null)
@foreach ($class::inputs() as $key => $definition)
<label style="font-size:.85rem">{{ $definition['label'] }}
@if ($definition['type'] === 'bool')
<input type="checkbox" wire:model="inputs.{{ $key }}" style="display:block">
@elseif ($definition['type'] === 'select')
<select wire:model="inputs.{{ $key }}" style="{{ $input }};display:block">
@foreach ($definition['options'] as $value => $label)<option value="{{ $value }}">{{ $label }}</option>@endforeach
</select>
@else
<input type="{{ $definition['type'] === 'date' ? 'date' : 'number' }}" wire:model="inputs.{{ $key }}" style="{{ $input }};display:block;width:10rem">
@endif
</label>
@endforeach
@endif
</div>
@if ($class)<p style="font-size:.85rem;margin-top:.5rem">{{ $class::description() }}</p>@endif
<div style="display:flex;gap:.5rem;margin-top:.8rem">
<x-filament::button wire:click="start" wire:loading.attr="disabled">Test starten</x-filament::button>
@if ($run && count($report['timeline'] ?? []) < ($report['scenario']['available_events'] ?? 0) && blank($report['aborted'] ?? null))
<x-filament::button color="gray" wire:click="next" wire:loading.attr="disabled">Weiter: nächstes Ereignis</x-filament::button>
@endif
<span wire:loading style="{{ $muted }}">Testlauf läuft …</span>
</div>
</x-filament::section>
@endif
@if ($run)
<x-filament::section heading="Bericht">
@if (filled($report['aborted'] ?? null))
<p style="color:#b91c1c;font-weight:600">{{ $report['aborted'] }}</p>
@foreach ($report['violations'] ?? [] as $violation)<p style="color:#b91c1c;font-size:.85rem">{{ $violation['message'] ?? '' }}</p>@endforeach
@endif
@if ($plan = $report['plan'] ?? null)
<p style="font-size:.9rem"><strong>{{ $plan['label'] }}</strong> ({{ $plan['model'] }} Version {{ $plan['version'] }}{{ $plan['variant'] !== 'standard' ? ', Variante '.$plan['variant'] : '' }}) · Vorgangsart {{ $plan['case_type'] }}</p>
<details style="font-size:.85rem;margin:.4rem 0"><summary>Wirksame Einstellungen</summary>
<ul style="padding-left:1.2rem;list-style:disc">
@foreach ($plan['configuration'] as $row)<li>{{ $row['question'] }}: <strong>{{ $row['value'] }}</strong> <span style="{{ $muted }}">({{ $row['source'] }})</span></li>@endforeach
</ul>
</details>
@endif
@foreach ($report['timeline'] ?? [] as $index => $event)
<div style="{{ $card }}">
<div style="display:flex;justify-content:space-between"><strong>{{ $index + 1 }}. {{ $event['label'] }}</strong><span style="{{ $muted }}">{{ $event['at'] }} (simuliert)</span></div>
@if ($event['error'])<p style="color:#b91c1c;font-size:.85rem">Fehler: {{ $event['error'] }}</p>@endif
@isset($event['situation'])<p style="font-size:.85rem;margin:.3rem 0">{{ $event['status'] }} · {{ $event['situation'] }}</p>@endisset
<ul style="font-size:.85rem;list-style:none;padding:0">
@foreach ($event['activities'] as $activity)
<li><span style="color:{{ $stateColor[$activity['state_key']] ?? '#6b7280' }};font-weight:600">{{ $activity['state'] }}</span> – {{ $activity['label'] }}@if ($activity['detail'])<span style="{{ $muted }}"> · {{ $activity['detail'] }}</span>@endif</li>
@endforeach
</ul>
@if (($event['skipped'] ?? []) !== [])
<p style="{{ $muted }};margin-top:.3rem">Übersprungen: {{ collect($event['skipped'])->map(fn ($skipped) => $skipped['label'].' ('.$skipped['reason'].')')->implode(', ') }}</p>
@endif
@if (isset($event['calendar']))
<p style="{{ $muted }}">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' }}</p>
@endif
@foreach ($event['mails'] as $mail)
<details style="font-size:.85rem;margin-top:.3rem"><summary>✉ simuliert: {{ $mail['subject'] }} <span style="{{ $muted }}">an {{ $mail['to'] }}</span></summary><p style="{{ $muted }}">{{ $mail['excerpt'] }}</p></details>
@endforeach
</div>
@endforeach
@if ($result = $report['result'] ?? null)
<p style="font-size:.9rem"><strong>Ergebnis:</strong> {{ $result['status'] }} · {{ $result['situation'] }}@if ($result['next']) · nächster Schritt: {{ $result['next'] }}@endif</p>
@endif
<p style="{{ $muted }}">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.</p>
</x-filament::section>
@endif
</x-filament-panels::page>
@@ -130,9 +130,8 @@
@endforeach
</ol>
<p style="{{ $muted }};margin-top:.6rem">Gilt für neue Vorgänge. Laufende Vorgänge dieses Kanals ({{ $this->runningCases() }}) behalten ihren bisherigen Ablauf.</p>
@if (\Illuminate\Support\Facades\Route::has('filament.admin.resources.channels.test'))
<x-filament::button tag="a" color="gray" :href="\App\Filament\Resources\Channels\ChannelResource::getUrl('test', ['record' => $this->record, 'intake' => $this->intake])" style="margin-top:.6rem">Ablauf testen</x-filament::button>
@endif
<x-filament::button color="gray" wire:click="test" style="margin-top:.6rem">Ablauf testen</x-filament::button>
<p style="{{ $muted }}">Spielt einen ausgedachten Vorgang mit genau dieser Einstellung durch – ohne Wirkung auf echte Daten.</p>
</x-filament::section>
</div>
</x-filament-panels::page>
+5 -2
View File
@@ -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. */
@@ -0,0 +1,181 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\ConfigureChannelProcess;
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelRegistry;
use App\Channels\Events\BookingCancelledByChannel;
use App\Channels\Events\BookingChangedByChannel;
use App\Channels\Events\ChannelEventHandler;
use App\Channels\Events\IncomingBooking;
use App\Channels\Events\PaymentReported;
use App\Channels\Events\PayoutReported;
use App\Channels\Events\Provenance;
use App\Channels\Intake\IntakeDecision;
use App\Channels\Mail\PortalMail;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\IntakeKind;
use App\Enums\IntakeOutcome;
use App\Enums\PaymentKind;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Process\OutwardSuspension;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\Group;
use Tests\Support\Process\FakeApiConnector;
use Tests\TestCase;
/**
* Package U-E (K4, K10, N7): normalised channel events of a future portal interface are mapped onto the existing intake.
* A report is never a business action: no cancellation, change, refund or payment on our account by itself; and one
* booking stays one case whether it arrives by API, mail or calendar.
*/
#[Group('channel-events')]
class ChannelEventContractTest extends TestCase
{
use RefreshDatabase;
private Channel $fewo;
protected function setUp(): void
{
parent::setUp();
$this->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('<m1@fewo-direkt.de>', '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('<m2@fewo-direkt.de>', '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);
}
}
@@ -0,0 +1,46 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\AnonymizeGuests;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Support\SystemSettings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Decision O3: reports of the process tester are deleted after 30 days by the existing retention job; the period is
* part of the retention settings (System › Löschfristen).
*/
#[Group('sandbox')]
class ProcessTestRunRetentionTest extends TestCase
{
use RefreshDatabase;
public function test_reports_older_than_the_retention_period_are_deleted(): void
{
$this->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);
}
}
@@ -0,0 +1,192 @@
<?php
namespace Tests\Feature\Process;
use App\Enums\IntakeKind;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Process\Tester\ProcessSandbox;
use App\Process\Tester\SandboxSnapshot;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\URL;
use PDO;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use RuntimeException;
use Tests\Support\Process\HostileProbe;
use Tests\TestCase;
/**
* Safety proof of the process tester (requirement T2, docs/Prozessarchitektur/Architektur/04 §7): a probe inside the
* tester process deliberately tries forbidden accesses. A passing happy path is no proof; these tests are. The
* "operational database" is a SQLite file of its own here; its hash before and after is compared.
*/
#[Group('sandbox')]
class ProcessTesterSecurityTest extends TestCase
{
use RefreshDatabase;
private Channel $website;
private User $user;
private string $operational;
protected function setUp(): void
{
parent::setUp();
$this->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<string, array{string, ?string}>
*/
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);
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace Tests\Feature\Process;
use App\Enums\IntakeKind;
use App\Filament\Resources\Channels\Pages\ChannelProcess;
use App\Filament\Resources\Channels\Pages\ChannelProcessTest;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ProcessTestRun;
use App\Models\Property;
use App\Models\User;
use App\Process\Tester\ProcessSandbox;
use App\Support\Content;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Database\Seeders\SiteSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Process;
use Livewire\Livewire;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Package U-D: the process tester plays scenarios in a process of its own with the same business logic (T01, T02,
* T05) and leaves the real data untouched (T03).
*/
#[Group('sandbox')]
class ProcessTesterTest extends TestCase
{
use RefreshDatabase;
private Property $property;
private User $user;
protected function setUp(): void
{
parent::setUp();
$this->travelTo(CarbonImmutable::parse('2026-10-23 10:00'));
$this->seed([PropertySeeder::class, SiteSeeder::class]);
$this->property = Property::sole();
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
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);
}
}
}
@@ -0,0 +1,78 @@
<?php
namespace Tests\Feature\Process;
use App\Actions\RecordPayment;
use App\Actions\RecordPortalAmounts;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\PaymentKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\Property;
use App\Process\CaseClosure;
use Carbon\CarbonImmutable;
use Database\Seeders\PropertySeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Mail;
use PHPUnit\Framework\Attributes\Group;
use Tests\TestCase;
/**
* Decision O5 (intended change I-007): with portal collection the commercial closing needs the financial clarification
* of the payout – received, offset, booked difference or written-off claim; a portal's report of the payout is no proof,
* a reason alone is not enough, and an open claim stays traceable as a task of its own.
*/
#[Group('module:case.settlement')]
class SettlementClarificationTest extends TestCase
{
use RefreshDatabase;
private Booking $booking;
protected function setUp(): void
{
parent::setUp();
$this->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);
}
}
@@ -0,0 +1,63 @@
<?php
namespace Tests\Feature\Process;
use PHPUnit\Framework\Attributes\Group;
use Symfony\Component\Finder\Finder;
use Tests\TestCase;
/**
* The limit of the process tester's isolation (docs/Prozessarchitektur/Architektur/04 §3.5, requirement T2): native PHP
* calls that bypass Laravel's managers – own database connections, sockets, curl, mail(), writing files by path,
* programs, reading the environment – cannot be stopped at run time on shared hosting. They are kept out of the
* application by this static check (like MailTestModeGateTest for mail): new ways out must use the framework's
* facades, which the tester controls. Every exception is named here with its reason.
*/
#[Group('sandbox')]
class SideEffectPathsTest extends TestCase
{
/** Forbidden native calls (regular expression => 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',
'/(?<![\w>:$])(?<!function )mail\s*\(/' => 'mail()',
'/(?<![\w>:$])(?<!function )(file_put_contents|fopen|fwrite|unlink|rename|copy|touch|mkdir)\s*\(/' => 'file by path',
'/(?<![\w>:])(exec|shell_exec|passthru|system|popen|proc_open)\s*\(/' => 'program',
'/(?<![\w>:$])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).');
}
}
+4 -1
View File
@@ -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 |
@@ -0,0 +1,58 @@
<?php
namespace Tests\Support\Process;
use App\Channels\Contracts\ChannelConnector;
use App\Channels\Contracts\DeliversEvents;
use App\Channels\Events\IncomingBooking;
use App\Channels\Events\PaymentReported;
use App\Channels\Events\Provenance;
use App\Models\Channel;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Http;
/**
* N7: a portal interface as it could come later – only an adapter and its registry entry. It reads the portal's
* bookings over HTTP (faked in the test) and delivers normalised channel events; it decides nothing.
*/
final class FakeApiConnector implements ChannelConnector, DeliversEvents
{
public static function key(): string
{
return 'fake_api';
}
public static function label(): string
{
return 'Beispiel-Schnittstelle (Test)';
}
public static function settingsSchema(): array
{
return [];
}
public function canImport(Channel $channel): bool
{
return false;
}
public function fetchOccupations(Channel $channel): array
{
return [];
}
public function fetchEvents(Channel $channel, ?CarbonImmutable $since): array
{
$events = [];
foreach ((array) Http::get('https://api.portal.example/bookings')->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;
}
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace Tests\Support\Process;
use App\Channels\Mail\MailboxReader;
use App\Process\Tester\EffectLedger;
use App\Process\Tester\SandboxContext;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Negative tests of the process tester (docs/Prozessarchitektur/Architektur/04 §7.2): runs inside the tester process
* and deliberately tries one forbidden access (environment FEWO_SANDBOX_PROBE_CASE). Only registered in the test suite
* (SandboxBootstrapper accepts a probe only with APP_ENV=testing). Records what it observed in the ledger.
*/
final class HostileProbe
{
public function handle(SandboxContext $context): void
{
$case = (string) getenv('FEWO_SANDBOX_PROBE_CASE');
$operational = (string) getenv('FEWO_SANDBOX_PROBE_FILE');
try {
match ($case) {
'db_other_connection' => 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;
}
}
}