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:
1 parent
c255783cec
commit
0689c0a591
68 files changed
+3350
-35
No files matched your search
@@ -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')))
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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])),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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'));
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
@@ -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.');
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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', ''],
|
||||
|
||||
Reference in new issue
Block a user