Pattern Playbook

Course › Day 2 · Money comes in › Scene 9 of 49 · 50 min

She paid two minutes after her hold expired

The booking lifecycle as states, holds that expire on a schedule, late payments, refunds with Idempotency-Key

State

On this page
  1. The incident
  2. The broken code
  3. The fix, part 1: one class per state
  4. The fix, part 2: callers ask the state
  5. The fix, part 3: refunding a late payment, safely
  6. The pattern
  7. Laravel inside: how the scheduler runs every minute
  8. Tests
  9. Remember

#supportWednesday 14:52

Mona · supportA guest paid at 14:29. Her hold had expired at 14:27. Stripe took €1,105.50, the booking says expired, and the webhook job has failed five times with "Booking 812 is expired and can’t be confirmed".

Sara · tech leadAlso: who expires holds? Half of them never expire at all; the code only checks when someone opens the booking.

The broken code

The rules about what can happen to a booking are spread over every class that touches it, as if checks on the status:

scattered across the app (before)the bug
// BookingConfirmation (scene 6)
if ($booking->status !== BookingStatus::Pending) {
    throw new LogicException("Booking {$booking->id} is {$booking->status->value} and can't be confirmed.");
}

// BookingController@show: the only place a hold "expires"
if ($booking->status === BookingStatus::Pending && $booking->expires_at->isPast()) {
    $booking->update(['status' => BookingStatus::Expired]);
}

// CancelBookingController
if (in_array($booking->status, [BookingStatus::Pending, BookingStatus::Confirmed])) { /* ... */ }

Nobody wrote down what an expired booking may do when a late payment arrives, so the answer was "throw". The guest’s money is now held with no booking and no refund.

The real rule, once the team agreed on it: a late payment re-confirms the booking if its nights are still free, and is refunded in full if someone else has booked them since. Either way the guest is told: the confirmation email from scene 6, or a short one saying the money is on its way back.

How the fix works, in one picture

Before

hold expired at 14:27payment 14:29confirm?fails 5 timesexpiryonly when opened

Nothing knew what a payment for an expired booking means, and holds expired only when someone looked.

After

the schedulerevery minuteexpire holdsa late paymentExpired staterefund it

Each state says what it allows: an expired booking refunds a late payment. Holds expire on a schedule.

The fix, part 1: one class per state

Every status gets a class that answers the same three questions: what happens if you confirm, cancel or expire a booking in this state? A base class makes every transition invalid by default, so each state only writes down what it allows.

app/Bookings/States/BookingState.phpnew file
<?php

namespace App\Bookings\States;

use App\Models\Booking;

abstract class BookingState
{
    /** @return bool true when the booking changed, false when it was already in the target state */
    public function confirm(Booking $booking): bool
    {
        throw InvalidTransition::from($booking, 'confirm');
    }

    public function cancel(Booking $booking): bool
    {
        throw InvalidTransition::from($booking, 'cancel');
    }

    public function expire(Booking $booking): bool
    {
        throw InvalidTransition::from($booking, 'expire');
    }
}
app/Bookings/States/InvalidTransition.phpnew file
<?php

namespace App\Bookings\States;

use App\Models\Booking;
use LogicException;

final class InvalidTransition extends LogicException
{
    public static function from(Booking $booking, string $action): self
    {
        return new self("A {$booking->status->value} booking can't {$action} (booking {$booking->id}).");
    }
}

Pending: the hold

app/Bookings/States/PendingState.phpnew file
<?php

namespace App\Bookings\States;

use App\Enums\BookingStatus;
use App\Models\Booking;

final class PendingState extends BookingState
{
    public function confirm(Booking $booking): bool
    {
        $booking->status = BookingStatus::Confirmed;
        $booking->confirmed_at = now();
        $booking->expires_at = null;
        $booking->save();

        return true;
    }

    public function cancel(Booking $booking): bool
    {
        $booking->status = BookingStatus::Cancelled;
        $booking->cancelled_at = now();
        $booking->save();

        return true;
    }

    public function expire(Booking $booking): bool
    {
        if ($booking->expires_at->isFuture()) {
            throw InvalidTransition::from($booking, 'expire before its hold ends');
        }

        $booking->status = BookingStatus::Expired;
        $booking->save();

        return true;
    }
}

Confirmed

Confirming again changes nothing: that’s what makes a repeated webhook harmless. Expiring is not allowed (inherited).

app/Bookings/States/ConfirmedState.phpnew file
<?php

namespace App\Bookings\States;

use App\Enums\BookingStatus;
use App\Models\Booking;

final class ConfirmedState extends BookingState
{
    public function confirm(Booking $booking): bool
    {
        return false;                                         // already confirmed
    }

    public function cancel(Booking $booking): bool
    {
        $booking->status = BookingStatus::Cancelled;
        $booking->cancelled_at = now();
        $booking->save();                                     // scene 10 adds the refund

        return true;
    }
}

Expired: the rule nobody had written

The late payment case lives here and nowhere else. It checks the nights under the same property lock as scene 4, so a new booking can’t take them in between.

app/Bookings/States/ExpiredState.phpnew file
<?php

namespace App\Bookings\States;

use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\Property;

final class ExpiredState extends BookingState
{
    /** A late payment: re-confirm only if nobody has taken the nights since. */
    public function confirm(Booking $booking): bool
    {
        Property::whereKey($booking->property_id)->lockForUpdate()->firstOrFail();   // inside the caller's transaction

        $taken = $booking->property->bookings()
            ->overlapping($booking->stay)
            ->whereKeyNot($booking->id)
            ->exists();

        if ($taken) {
            throw DatesNoLongerAvailable::for($booking);
        }

        $booking->status = BookingStatus::Confirmed;
        $booking->confirmed_at = now();
        $booking->expires_at = null;
        $booking->save();

        return true;
    }

    public function expire(Booking $booking): bool
    {
        return false;                                         // already expired
    }
}
app/Bookings/States/CancelledState.phpnew file
<?php

namespace App\Bookings\States;

use App\Models\Booking;

final class CancelledState extends BookingState
{
    public function cancel(Booking $booking): bool
    {
        return false;                                         // already cancelled; nothing else is allowed
    }
}
app/Bookings/States/DatesNoLongerAvailable.phpnew file
<?php

namespace App\Bookings\States;

use App\Models\Booking;
use RuntimeException;

final class DatesNoLongerAvailable extends RuntimeException
{
    public static function for(Booking $booking): self
    {
        return new self("The nights of booking {$booking->id} were booked by someone else after its hold expired.");
    }
}

The booking hands out its state

The status column stays the single source of truth; the state object is built from it on demand.

app/Models/Booking.phpchanged since scene 7: +16
<?php namespace App\Models; use App\Bookings\States\BookingState;use App\Bookings\States\CancelledState;use App\Bookings\States\ConfirmedState;use App\Bookings\States\ExpiredState;use App\Bookings\States\PendingState;use App\Bookings\Stay;use App\Casts\MoneyCast;use App\Casts\StayCast;
46 unchanged linesuse App\Enums\BookingStatus;use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany; class Booking extends Model{ use HasFactory; protected $fillable = ['guest_name', 'guest_email', 'check_in', 'check_out', 'guests']; protected function casts(): array { return [ 'check_in' => 'date:Y-m-d', 'check_out' => 'date:Y-m-d', 'status' => BookingStatus::class, 'expires_at' => 'datetime', 'confirmed_at' => 'datetime', 'cancelled_at' => 'datetime', 'total' => MoneyCast::class . ':total_cents', // Money from total_cents + currency 'stay' => StayCast::class, // Stay from check_in + check_out ]; } public function property(): BelongsTo { return $this->belongsTo(Property::class); } public function payments(): HasMany { return $this->hasMany(Payment::class); } public function lineItems(): HasMany { return $this->hasMany(BookingLineItem::class); } /** Bookings that share at least one night with $stay: $property->bookings()->overlapping($stay). */ public function scopeOverlapping(Builder $query, Stay $stay): void { $query->whereIn('status', BookingStatus::blocking())
->where('check_in', '<', $stay->checkOut->toDateString()) // starts before the new stay ends ->where('check_out', '>', $stay->checkIn->toDateString()); // ends after the new stay starts } /** What this booking may do now. The status column stays the single source of truth. */ public function state(): BookingState { return match ($this->status) { BookingStatus::Pending => new PendingState(), BookingStatus::Confirmed => new ConfirmedState(), BookingStatus::Expired => new ExpiredState(), BookingStatus::Cancelled => new CancelledState(), }; // a new status without a state class fails here, loudly }}

The fix, part 2: callers ask the state

The facade from scene 6

No status checks left in it: it asks the state, and only runs the other steps when the booking actually changed.

app/Bookings/BookingConfirmation.phpchanged since scene 6: +4 −14
<?php namespace App\Bookings; use App\Enums\BookingStatus;use App\Enums\PaymentStatus;use App\Models\Booking;use App\Models\Payment;use App\Notifications\BookingConfirmed;use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Notification;use LogicException; final class BookingConfirmation{    public function confirm(Booking $booking, Payment $payment): void    {        DB::transaction(function () use ($booking, $payment): void {            $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail();   // fresh, and locked             if ($booking->status === BookingStatus::Confirmed) {                return;                                                // confirmed already: nothing to do            }            if ($booking->status !== BookingStatus::Pending) {                throw new LogicException("Booking {$booking->id} is {$booking->status->value} and can't be confirmed.");            }             $booking->status = BookingStatus::Confirmed;               // step 1            $booking->confirmed_at = now();            $booking->expires_at = null;                               // no longer a hold            $booking->save();             if (! $booking->state()->confirm($booking)) {               // step 1: the state decides                return;                                                // already confirmed: nothing else to do            }             $payment->status = PaymentStatus::Succeeded;               // step 2            $payment->save(); 
7 unchanged lines Notification::route('mail', $booking->guest_email) // step 3, after the commit ->notify((new BookingConfirmed($booking))->afterCommit()); // Day 3 adds: close the dates on every channel. Day 4: schedule guest messages. Day 5: plan the cleaning. }); }}

Holds expire on a schedule

Every minute, a command expires the holds whose time is up. Each booking is locked first, so a payment confirming the same booking at that moment waits, and the loser of the race sees the winner’s result.

withoutOverlapping() stops a slow run from overlapping the next one. lazyById() walks the rows in batches without loading them all (scene 11 looks inside it).

app/Console/Commands/ExpireHolds.phpnew file
<?php

namespace App\Console\Commands;

use App\Enums\BookingStatus;
use App\Models\Booking;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ExpireHolds extends Command
{
    protected $signature = 'bookings:expire-holds';

    protected $description = 'Expire pending bookings whose hold has ended';

    public function handle(): void
    {
        Booking::query()
            ->where('status', BookingStatus::Pending)
            ->where('expires_at', '<=', now())
            ->lazyById()
            ->each(function (Booking $booking): void {
                DB::transaction(function () use ($booking): void {
                    $booking = Booking::whereKey($booking->id)->lockForUpdate()->firstOrFail();

                    if ($booking->status === BookingStatus::Pending) {   // a payment may have won the race
                        $booking->state()->expire($booking);
                    }
                });
            });
    }
}

Scheduled in routes/console.php. The whole file, replacing Laravel’s example inspire command:

routes/console.phpnew file
<?php

use Illuminate\Support\Facades\Schedule;

// The server runs the scheduler once a minute:  * * * * * php artisan schedule:run
// Locally:                                     php artisan schedule:work

Schedule::command('bookings:expire-holds')->everyMinute()->withoutOverlapping();

The fix, part 3: refunding a late payment, safely

When the nights are gone, the money goes back. A refund is money leaving the company, so it must happen exactly once, even though the job that sends it can retry.

The danger: the job calls Stripe, Stripe refunds, and then the job crashes before saving anything. The retry would refund again. Stripe’s answer is the Idempotency-Key: send the same key with the same request, and Stripe returns the first result instead of acting twice (keys are kept for 24 hours). The key must be built from our own data, so every retry produces the same one.

Refunds have been recorded since May, when cancellations first paid money back (scene 10 looks at that code). If your app doesn’t have the table yet, this is it:

database/migrations/2024_05_06_000002_create_refunds_table.phpnew file
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('refunds', function (Blueprint $table) {
            $table->id();
            $table->foreignId('payment_id')->constrained();
            $table->unsignedInteger('amount_cents');
            $table->char('currency', 3);
            $table->string('provider_refund_id')->unique();         // one Stripe refund, one row
            $table->string('reason');
            $table->timestamps();
        });
    }
};
app/Models/Refund.phpnew file
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Refund extends Model
{
    protected $fillable = ['amount_cents', 'currency', 'provider_refund_id', 'reason'];

    public function payment(): BelongsTo
    {
        return $this->belongsTo(Payment::class);
    }
}

Every Stripe POST gets a key

The gateway from scene 5 takes an idempotency key on both of its calls, and gains refund().

app/Payments/PaymentGateway.phpchanged since scene 5: +4 −1
9 unchanged lines<?php namespace App\Payments; use App\Money\Money; interface PaymentGateway{ /**
* @param array<string, string> $metadata * @return array{id: string, client_secret: string} */ public function createPaymentIntent(Money $amount, array $metadata = []): array; public function createPaymentIntent(Money $amount, array $metadata, string $idempotencyKey): array; /** @return string the provider's refund id */ public function refund(string $paymentIntentId, Money $amount, string $idempotencyKey): string;}

The Stripe implementation passes each key to Stripe, and gains refund():

app/Payments/StripeGateway.phpchanged since scene 5: +12 −2
10 unchanged lines<?php namespace App\Payments; use App\Money\Money;use Stripe\StripeClient; final readonly class StripeGateway implements PaymentGateway{ public function __construct(private StripeClient $stripe)
{ } public function createPaymentIntent(Money $amount, array $metadata = []): array public function createPaymentIntent(Money $amount, array $metadata, string $idempotencyKey): array { $intent = $this->stripe->paymentIntents->create([ 'amount' => $amount->amount, // already in minor units 'currency' => strtolower($amount->currency->value), 'automatic_payment_methods' => ['enabled' => true], 'metadata' => $metadata, ]); ], ['idempotency_key' => $idempotencyKey]); // same key, same PaymentIntent return ['id' => $intent->id, 'client_secret' => $intent->client_secret]; } public function refund(string $paymentIntentId, Money $amount, string $idempotencyKey): string { $refund = $this->stripe->refunds->create( ['payment_intent' => $paymentIntentId, 'amount' => $amount->amount], ['idempotency_key' => $idempotencyKey], // same key, same refund: never a second one ); return $refund->id; }}

Starting a payment passes a key built from the booking. A second click gets the same PaymentIntent back, so the payment row is written with createOrFirst(): the unique key on provider_payment_id would turn a plain create() into a 500.

app/Payments/StartBookingPayment.phpchanged since scene 5: +14 −8
13 unchanged lines<?php namespace App\Payments; use App\Enums\PaymentStatus;use App\Models\Booking; final readonly class StartBookingPayment{ public function __construct(private PaymentGateway $gateway) { }
/** @return string the client secret the browser needs to confirm the payment with Stripe */ public function handle(Booking $booking): string { $intent = $this->gateway->createPaymentIntent($booking->total, ['booking_id' => (string) $booking->id]); $booking->payments()->create([ 'amount_cents' => $booking->total->amount, 'currency' => $booking->total->currency->value, 'status' => PaymentStatus::Pending, 'provider_payment_id' => $intent['id'], ]); $intent = $this->gateway->createPaymentIntent( $booking->total, ['booking_id' => (string) $booking->id], "booking-{$booking->id}-payment", // a double click on "Pay" gets the same PaymentIntent ); $booking->payments()->createOrFirst( ['provider_payment_id' => $intent['id']], // the second click finds the row the first one wrote [ 'amount_cents' => $booking->total->amount, 'currency' => $booking->total->currency->value, 'status' => PaymentStatus::Pending, ], ); return $intent['client_secret']; }}

A payment knows its refunds:

app/Models/Payment.phpchanged since the foundation: +6
<?php namespace App\Models; use App\Enums\PaymentStatus;use Illuminate\Database\Eloquent\Factories\HasFactory;use Illuminate\Database\Eloquent\Model;use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany; class Payment extends Model{
10 unchanged lines use HasFactory; protected $fillable = ['amount_cents', 'currency', 'status', 'provider_payment_id']; protected function casts(): array { return ['status' => PaymentStatus::class]; } public function booking(): BelongsTo
{ return $this->belongsTo(Booking::class); } public function refunds(): HasMany { return $this->hasMany(Refund::class); }}

The guest hears about it

app/Notifications/LatePaymentRefunded.phpnew file
<?php

namespace App\Notifications;

use App\Models\Booking;
use App\Money\Money;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class LatePaymentRefunded extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public Booking $booking, public Money $amount)
    {
    }

    /** @return list<string> */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage())
            ->subject("Your payment for {$this->booking->property->name} is being refunded")
            ->greeting("Hi {$this->booking->guest_name},")
            ->line('Your payment arrived after the booking had expired, and the nights have been booked by someone else since.')
            ->line("We have sent {$this->amount->format()} back to your card. It usually arrives within 5 to 10 days.");
    }
}

The webhook job handles the late payment

handle() now also receives the gateway. createOrFirst() on the unique refund id (scene 8) means a retry that gets the same refund back from Stripe doesn’t record it twice either.

app/Jobs/ProcessStripeWebhook.phpchanged since scene 8: +24 −2
<?php namespace App\Jobs; use App\Bookings\BookingConfirmation;use App\Bookings\States\DatesNoLongerAvailable;use App\Enums\PaymentStatus;use App\Models\Payment;use App\Models\WebhookEvent;use App\Money\Money;use App\Notifications\LatePaymentRefunded;use App\Payments\Events\PaymentFailed;use App\Payments\Events\PaymentSucceeded;use App\Payments\Events\StripeEventFactory;use App\Payments\PaymentGateway;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Queue\Queueable;use Illuminate\Support\Facades\Notification;use Throwable;use UnexpectedValueException; 
13 unchanged linesclass ProcessStripeWebhook implements ShouldQueue{ use Queueable; public int $tries = 5; public function __construct(public WebhookEvent $webhook) { } /** @return list<int> seconds to wait before each retry */ public function backoff(): array {
return [10, 60, 300, 900]; } public function handle(BookingConfirmation $confirmation): void public function handle(BookingConfirmation $confirmation, PaymentGateway $gateway): void { $event = StripeEventFactory::fromPayload($this->webhook->payload); if ($event instanceof PaymentSucceeded) { $payment = $this->payment($event->paymentIntentId); $expected = Money::of($payment->amount_cents, $payment->currency); if (! $event->amount->equals($expected)) { throw new UnexpectedValueException("Stripe received {$event->amount->format()} for payment {$payment->id}, expected {$expected->format()}."); } $confirmation->confirm($payment->booking, $payment); try { $confirmation->confirm($payment->booking, $payment); } catch (DatesNoLongerAvailable) { $payment->status = PaymentStatus::Succeeded; // the money did arrive $payment->save(); $refundId = $gateway->refund($event->paymentIntentId, $event->amount, "payment-{$payment->id}-late-refund"); $refund = $payment->refunds()->createOrFirst(['provider_refund_id' => $refundId], [ 'amount_cents' => $event->amount->amount, 'currency' => $event->amount->currency->value, 'reason' => 'Paid after the hold expired; the nights were already booked.', ]); if ($refund->wasRecentlyCreated) { // told once, however often Stripe retries Notification::route('mail', $payment->booking->guest_email) ->notify(new LatePaymentRefunded($payment->booking, $event->amount)); } } } if ($event instanceof PaymentFailed) {
18 unchanged lines $payment = $this->payment($event->paymentIntentId); $payment->status = PaymentStatus::Failed; $payment->save(); } $this->webhook->markProcessed(); // also for types we don't act on } public function failed(Throwable $exception): void { $this->webhook->markFailed($exception->getMessage()); } private function payment(string $paymentIntentId): Payment { return Payment::where('provider_payment_id', $paymentIntentId)->firstOrFail(); }}

You just wrote the State pattern

StateAn object’s behaviour depends on its state, so each state is its own class, and the object hands each request to its current state.

From ↓ / action →confirmcancelexpire
Pending→ Confirmed→ Cancelled→ Expired (only after the hold ends)
Confirmedno change→ Cancellednot allowed
Expired→ Confirmed if the nights are free, else refundnot allowedno change
Cancellednot allowedno changenot allowed
  • Every rule about a status lives in that status’s class. "What can an expired booking do?" has one answer, in ExpiredState.
  • Forbidden transitions fail loudly with InvalidTransition, instead of silently writing an impossible status.
  • A new status is a new class and one match arm, not a hunt through every if.

When not to use it

  • Two statuses with no rules between them (active/inactive): an enum and one if is clearer.
  • Don’t let state classes do the work around a transition (emails, payments, channel pushes). They change the status; the facade in scene 6 runs the rest.

Laravel inside: how the scheduler runs every minute

Laravel has no daemon for schedules. The server’s cron runs schedule:run once a minute; it asks each scheduled event "are you due now?" and runs the ones that are. withoutOverlapping() takes a cache lock for the event and skips the run if the lock is still held by the previous one.

Illuminate/Console/Scheduling/ScheduleRunCommand.php (simplified)
public function handle(Schedule $schedule)
{
    foreach ($schedule->dueEvents($this->laravel) as $event) {      // cron expression matches this minute
        if (! $event->filtersPass($this->laravel)) {
            continue;
        }

        $this->runEvent($event);    // withoutOverlapping(): Cache::lock('framework/schedule-...')->get() or skip
    }
}

Running the app on two servers? Add ->onOneServer() too, or both servers expire the same holds (scene 45).

TestsEvery transition, expiring holds, and the late payment both ways
tests/Feature/BookingStateTest.phpnew file
<?php

use App\Bookings\States\InvalidTransition;
use App\Enums\BookingStatus;
use App\Models\Booking;

it('allows only the transitions in the table', function (BookingStatus $from, string $action, BookingStatus|string $result) {
    $booking = Booking::factory()->create(['status' => $from, 'expires_at' => now()->subMinute()]);   // the hold has ended

    if ($result === 'invalid') {
        expect(fn () => $booking->state()->{$action}($booking))->toThrow(InvalidTransition::class);

        return;
    }

    $booking->state()->{$action}($booking);
    expect($booking->fresh()->status)->toBe($result);
})->with([
    [BookingStatus::Pending, 'confirm', BookingStatus::Confirmed],
    [BookingStatus::Pending, 'cancel', BookingStatus::Cancelled],
    [BookingStatus::Pending, 'expire', BookingStatus::Expired],
    [BookingStatus::Confirmed, 'confirm', BookingStatus::Confirmed],
    [BookingStatus::Confirmed, 'expire', 'invalid'],
    [BookingStatus::Expired, 'cancel', 'invalid'],
    [BookingStatus::Cancelled, 'confirm', 'invalid'],
]);

it('expires only holds whose time is up', function () {
    $due = Booking::factory()->pending()->create(['expires_at' => now()->subMinute()]);
    $notYet = Booking::factory()->pending()->create(['expires_at' => now()->addMinutes(5)]);

    $this->artisan('bookings:expire-holds')->assertSuccessful();

    expect($due->fresh()->status)->toBe(BookingStatus::Expired)
        ->and($notYet->fresh()->status)->toBe(BookingStatus::Pending);
});

Scene 6’s last test still passes: confirming a cancelled booking now throws InvalidTransition, which is a LogicException whose message names the "cancelled" status.

tests/Feature/LatePaymentTest.phpnew file
<?php

use App\Enums\BookingStatus;
use App\Jobs\ProcessStripeWebhook;
use App\Models\Booking;
use App\Models\Payment;
use App\Models\Refund;
use App\Models\WebhookEvent;
use App\Notifications\LatePaymentRefunded;
use App\Payments\PaymentGateway;
use Illuminate\Support\Facades\Notification;
use Tests\Fakes\FakePaymentGateway;

beforeEach(function () {
    Notification::fake();
    $this->gateway = new FakePaymentGateway();
    $this->app->instance(PaymentGateway::class, $this->gateway);

    $this->booking = Booking::factory()->forStay('2027-07-10', 3)->create(['status' => BookingStatus::Expired]);
    $this->payment = Payment::factory()->for($this->booking)->create(['provider_payment_id' => 'pi_late', 'amount_cents' => 110_550, 'currency' => 'EUR']);
    $this->webhook = WebhookEvent::create(['provider' => 'stripe', 'event_id' => 'evt_late', 'type' => 'payment_intent.succeeded', 'payload' => [
        'type' => 'payment_intent.succeeded', 'data' => ['object' => ['id' => 'pi_late', 'amount_received' => 110_550, 'currency' => 'eur']],
    ]]);
});

it('re-confirms a late payment when the nights are still free', function () {
    app()->call([new ProcessStripeWebhook($this->webhook), 'handle']);

    expect($this->booking->fresh()->status)->toBe(BookingStatus::Confirmed)
        ->and($this->gateway->refunded)->toBe([]);
});

it('refunds a late payment exactly once when the nights are taken, even if the job runs twice', function () {
    Booking::factory()->for($this->booking->property)->forStay('2027-07-11', 2)->create();   // someone else took them

    app()->call([new ProcessStripeWebhook($this->webhook), 'handle']);
    app()->call([new ProcessStripeWebhook($this->webhook), 'handle']);                   // a retry

    expect($this->booking->fresh()->status)->toBe(BookingStatus::Expired)
        ->and(array_unique(array_column($this->gateway->refunded, 'key')))->toBe(["payment-{$this->payment->id}-late-refund"])
        ->and(Refund::count())->toBe(1);
    Notification::assertSentOnDemandTimes(LatePaymentRefunded::class, 1);                // one email, not one per retry
});

The fake behaves like Stripe

The fake from scene 5 now records idempotency keys and, like Stripe, returns the same refund for the same key.

tests/Fakes/FakePaymentGateway.phpchanged since scene 5: +13 −3
6 unchanged lines<?php namespace Tests\Fakes; use App\Money\Money;use App\Payments\PaymentGateway;
final class FakePaymentGateway implements PaymentGateway{ /** @var list<Money> every amount the app tried to charge */ /** @var list<Money> */ public array $charged = []; public function createPaymentIntent(Money $amount, array $metadata = []): array /** @var list<array{key: string, amount: Money}> */ public array $refunded = []; public function createPaymentIntent(Money $amount, array $metadata, string $idempotencyKey): array { $this->charged[] = $amount; $id = 'pi_fake_' . count($this->charged); $id = 'pi_fake_' . md5($idempotencyKey); return ['id' => $id, 'client_secret' => "{$id}_secret"]; } public function refund(string $paymentIntentId, Money $amount, string $idempotencyKey): string { $this->refunded[] = ['key' => $idempotencyKey, 'amount' => $amount]; return 're_fake_' . md5($idempotencyKey); // same key, same refund id }}

Scene 5’s test asserted pi_fake_1; with keys it becomes 'pi_fake_' . md5("booking-{$booking->id}-payment").

And the double click, added to scene 5’s test file. With create() the second call fails on the unique key:

tests/Feature/StartBookingPaymentTest.php (one more test)
it('gives a double click the same payment, not a second row', function () {
    $this->app->instance(PaymentGateway::class, new FakePaymentGateway());
    $booking = Booking::factory()->create(['total_cents' => 45_030, 'currency' => 'EUR']);

    $first = app(StartBookingPayment::class)->handle($booking);
    $second = app(StartBookingPayment::class)->handle($booking);

    expect($second)->toBe($first)
        ->and($booking->payments()->count())->toBe(1);
});

Remember

  • A lifecycle with rules is states and allowed transitions, not booleans scattered over the code.
  • Time-based changes (holds expiring) need a scheduler, never "when someone opens the page".

Late payments are handled. Thursday: a guest cancels a strict booking three days out and gets every cent back.