Order Management System Design: State Machines
Order, payment and fulfilment as three separate state machines: enums declare the legal transitions, one service enforces them under a row lock with a full audit trail, plus split shipments and capped partial refunds - with tested code.
Table of contents
An order's status column starts innocent: pending, shipped, done. Then support asks why a cancelled order was refunded twice, a shipment went out for an unpaid order, and nobody can reconstruct who changed what, when. The problem is not the column - it is that a plain column allows every transition, including the meaningless ones. The fix is a state machine per concern: order, payment, and fulfilment as three separate machines, PHP enums that declare the legal transitions, one service that enforces them under a row lock, and an audit row for every change. All code below ran on Laravel 13 / PHP 8.4 against MySQL; the test output is embedded verbatim.
Why three machines, not one#
"Order status" is really three independent lifecycles wearing one name. The order itself (pending, confirmed, completed, cancelled), the money (unpaid, authorized, paid, partially refunded, refunded, failed), and the goods (unfulfilled, partially fulfilled, fulfilled). They move independently: a confirmed order can be unpaid; a paid order can ship in two boxes; a fully refunded order can still be fulfilled if the warehouse already shipped. One column forces these into a single sequence that fits none of them - or into a combinatorial blob like paid_partially_shipped that explodes with every new state.
Two rules keep the machines honest:
- Command states vs derived states.
confirmedorpaidare commands - someone or something decides them.partially_refunded,refunded, and both fulfilment states are derived - they must always agree with the refund rows and shipment rows. Derived states get dedicated methods (refund(),recordShipment()) that write the underlying facts; the generic transition path refuses to set them, so no caller can mark an order fulfilled with nothing shipped or refunded with no refund row. - Cross-machine policy lives in one place. Whether you may ship an unpaid order or cancel a shipped one depends on both machines at once. That policy is domain-specific - the rules below are one example, not universal law - but wherever yours land, enforce them in the service on locked state, not in controllers.
Enums that declare the law#
namespace App\Enums;
enum OrderStatus: string
{
case Pending = 'pending';
case Confirmed = 'confirmed';
case Completed = 'completed';
case Cancelled = 'cancelled';
/** @return list<self> Legal next states from this one. */
public function allowedTransitions(): array
{
return match ($this) {
self::Pending => [self::Confirmed, self::Cancelled],
self::Confirmed => [self::Completed, self::Cancelled],
self::Completed, self::Cancelled => [], // terminal states
};
}
public function canTransitionTo(self $target): bool
{
return in_array($target, $this->allowedTransitions(), true);
}
}
namespace App\Enums;
enum PaymentStatus: string
{
case Unpaid = 'unpaid';
case Authorized = 'authorized';
case Paid = 'paid';
case PartiallyRefunded = 'partially_refunded';
case Refunded = 'refunded';
case Failed = 'failed';
/** @return list<self> Legal next states from this one. */
public function allowedTransitions(): array
{
return match ($this) {
self::Unpaid => [self::Authorized, self::Paid, self::Failed],
self::Authorized => [self::Paid, self::Failed],
self::Paid => [self::PartiallyRefunded, self::Refunded],
self::PartiallyRefunded => [self::Refunded],
self::Refunded, self::Failed => [], // terminal states
};
}
public function canTransitionTo(self $target): bool
{
return in_array($target, $this->allowedTransitions(), true);
}
}
namespace App\Enums;
enum FulfilmentStatus: string
{
case Unfulfilled = 'unfulfilled';
case PartiallyFulfilled = 'partially_fulfilled';
case Fulfilled = 'fulfilled';
/** @return list<self> Legal next states from this one. */
public function allowedTransitions(): array
{
return match ($this) {
self::Unfulfilled => [self::PartiallyFulfilled, self::Fulfilled],
self::PartiallyFulfilled => [self::Fulfilled],
self::Fulfilled => [], // terminal state
};
}
public function canTransitionTo(self $target): bool
{
return in_array($target, $this->allowedTransitions(), true);
}
}Terminal states return an empty list; anything not listed is illegal. There is no default-allow.
The service that enforces it#
Every transition goes through one service. It re-reads the row with lockForUpdate inside a transaction, checks the enum and the cross-machine policy on that locked state, writes the change, and inserts an audit event with the actor - all in one transaction, so a rejected transition leaves nothing behind:
declare(strict_types=1);
namespace App\Services;
use App\Enums\FulfilmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentStatus;
use App\Models\Order;
use DomainException;
use Illuminate\Support\Facades\DB;
class OrderStateService
{
/**
* Direct transitions: the order machine, plus payment transitions that are
* real commands (authorize, capture, fail). Fulfilment is never set here -
* it is derived from shipments. Refund-driven payment states are never set
* here either - they are derived by refund(), which writes the refund rows.
*/
public function transition(int $orderId, string $machine, string $toState, ?string $reason = null, ?int $actorId = null): void
{
if ($machine === 'fulfilment') {
throw new DomainException('Fulfilment is derived from shipments; record a shipment instead');
}
if ($machine === 'payment'
&& in_array($toState, [PaymentStatus::PartiallyRefunded->value, PaymentStatus::Refunded->value], true)) {
throw new DomainException('Refund states are derived; call refund() so the refund is recorded');
}
if ($machine !== 'order' && $machine !== 'payment') {
throw new DomainException("Unknown machine: $machine");
}
DB::transaction(function () use ($orderId, $machine, $toState, $reason, $actorId) {
// Re-read the row under a lock: every decision below uses this state.
$order = Order::whereKey($orderId)->lockForUpdate()->firstOrFail();
[$column, $enumClass] = $machine === 'order'
? ['status', OrderStatus::class]
: ['payment_status', PaymentStatus::class];
$from = $enumClass::from($order->$column);
$to = $enumClass::from($toState);
if (! $from->canTransitionTo($to)) {
throw new DomainException(
"Illegal {$machine} transition: {$from->value} -> {$to->value}"
);
}
if ($machine === 'order') {
$this->enforceOrderPolicy($order, $to);
}
$order->$column = $to->value;
$order->save();
DB::table('order_state_events')->insert([
'order_id' => $order->id,
'machine' => $machine,
'from_state' => $from->value,
'to_state' => $to->value,
'reason' => $reason,
'actor_id' => $actorId,
'created_at' => now(),
]);
});
}
/**
* One example of cross-machine policy - yours will differ by domain:
* ship only a confirmed order that is (at least mostly) paid;
* complete only when fully fulfilled with money settled;
* never cancel once anything has shipped (that becomes a return).
*/
private function enforceOrderPolicy(Order $order, OrderStatus $to): void
{
if ($to === OrderStatus::Completed) {
if ($order->fulfilment_status !== FulfilmentStatus::Fulfilled->value) {
throw new DomainException('Cannot complete an order that is not fully fulfilled');
}
if (! in_array($order->payment_status, [
PaymentStatus::Paid->value,
PaymentStatus::PartiallyRefunded->value,
PaymentStatus::Refunded->value,
], true)) {
throw new DomainException('Cannot complete an order without settled payment');
}
}
if ($to === OrderStatus::Cancelled) {
$shipped = DB::table('shipment_items')
->join('shipments', 'shipments.id', '=', 'shipment_items.shipment_id')
->where('shipments.order_id', $order->id)
->sum('qty');
if ($shipped > 0) {
throw new DomainException('Cannot cancel after items have shipped; that is a return workflow');
}
}
}
/** Record a (possibly partial) shipment and recompute fulfilment. */
public function recordShipment(int $orderId, array $items, ?int $actorId = null): void
{
if ($items === []) {
throw new DomainException('A shipment must contain at least one item');
}
foreach ($items as $sku => $qty) {
if (! is_int($qty) || $qty < 1 || $qty > 1_000_000) {
throw new DomainException('Shipment quantities must be positive integers within bounds');
}
}
DB::transaction(function () use ($orderId, $items, $actorId) {
$order = Order::whereKey($orderId)->lockForUpdate()->firstOrFail();
// Cross-machine policy: ship only a confirmed, (mostly) paid order.
if ($order->status !== OrderStatus::Confirmed->value) {
throw new DomainException('Only a confirmed order can be shipped');
}
if (! in_array($order->payment_status, [
PaymentStatus::Paid->value,
PaymentStatus::PartiallyRefunded->value,
], true)) {
throw new DomainException('Only a paid order can be shipped');
}
$ordered = DB::table('order_items')->where('order_id', $order->id)
->pluck('qty', 'sku');
if ($ordered->isEmpty()) {
throw new DomainException('Cannot ship an order with no lines');
}
$shipped = DB::table('shipment_items')
->join('shipments', 'shipments.id', '=', 'shipment_items.shipment_id')
->where('shipments.order_id', $order->id)
->selectRaw('sku, SUM(qty) as qty')->groupBy('sku')
->pluck('qty', 'sku');
foreach ($items as $sku => $qty) {
if (! isset($ordered[$sku])) {
throw new DomainException("Unknown SKU for this order: $sku");
}
$remaining = $ordered[$sku] - ($shipped[$sku] ?? 0);
if ($qty > $remaining) {
throw new DomainException(
"Cannot ship $qty of $sku: $remaining remaining"
);
}
}
$shipmentId = DB::table('shipments')->insertGetId([
'order_id' => $order->id, 'actor_id' => $actorId, 'created_at' => now(),
]);
foreach ($items as $sku => $qty) {
DB::table('shipment_items')->insert([
'shipment_id' => $shipmentId, 'sku' => $sku, 'qty' => $qty,
]);
$shipped[$sku] = ($shipped[$sku] ?? 0) + $qty;
}
$complete = $ordered->keys()->every(
fn ($sku) => ($shipped[$sku] ?? 0) >= $ordered[$sku]
);
$target = $complete
? FulfilmentStatus::Fulfilled->value
: FulfilmentStatus::PartiallyFulfilled->value;
if ($target !== $order->fulfilment_status) {
$from = FulfilmentStatus::from($order->fulfilment_status);
$to = FulfilmentStatus::from($target);
if (! $from->canTransitionTo($to)) {
throw new DomainException(
"Illegal fulfilment transition: {$from->value} -> {$to->value}"
);
}
$order->fulfilment_status = $to->value;
$order->save();
DB::table('order_state_events')->insert([
'order_id' => $order->id, 'machine' => 'fulfilment',
'from_state' => $from->value, 'to_state' => $to->value,
'reason' => 'shipment recorded', 'actor_id' => $actorId,
'created_at' => now(),
]);
}
});
}
/**
* Records a confirmed local refund fact and moves the payment machine to
* match. No provider is called and no money moves here - provider
* orchestration and reconciliation are outside this example. Integer minor
* units only on 64-bit PHP; compare before adding, never float.
*/
/** Canonical non-negative decimal string -> int, or null if malformed/above PHP_INT_MAX. */
private static function rawMinorToInt(mixed $raw): ?int
{
$s = (string) $raw;
if (! preg_match('/^(0|[1-9][0-9]*)$/', $s)) {
return null;
}
$max = (string) PHP_INT_MAX;
// strcmp, not > : numeric-string comparison would parse as numbers here
if (strlen($s) > strlen($max) || (strlen($s) === strlen($max) && strcmp($s, $max) > 0)) {
return null;
}
return (int) $s;
}
// $amountMinor is mixed on purpose: a typed int parameter would still
// silently coerce values passed from non-strict callers. Reject anything
// that is not a real integer.
public function refund(int $orderId, mixed $amountMinor, ?string $reason = null, ?int $actorId = null): void
{
if (! is_int($amountMinor) || $amountMinor < 1) {
throw new DomainException('Refund amount must be a positive integer of minor units');
}
DB::transaction(function () use ($orderId, $amountMinor, $reason, $actorId) {
$order = Order::whereKey($orderId)->lockForUpdate()->firstOrFail();
$status = PaymentStatus::from($order->payment_status);
if (! in_array($status, [PaymentStatus::Paid, PaymentStatus::PartiallyRefunded], true)) {
throw new DomainException(
"Cannot refund from payment state: {$status->value}"
);
}
// Validate the RAW stored counters as decimal strings BEFORE any
// integer cast: Eloquent's integer cast would coerce a stored value
// above PHP_INT_MAX, so casting first cannot detect it. This runs
// on 64-bit PHP; anything outside [0, PHP_INT_MAX] is rejected for review.
$total = self::rawMinorToInt($order->getRawOriginal('amount_minor'));
$already = self::rawMinorToInt($order->getRawOriginal('refunded_minor'));
if ($total === null || $already === null || $already > $total) {
throw new DomainException('Order money counters are inconsistent; rejected for review');
}
// Compare before adding: this subtraction can never overflow.
if ($amountMinor > $total - $already) {
throw new DomainException(
"Refund of $amountMinor exceeds remaining " . ($total - $already)
);
}
$refunded = $already + $amountMinor;
DB::table('refunds')->insert([
'order_id' => $order->id, 'amount_minor' => $amountMinor,
'reason' => $reason, 'actor_id' => $actorId, 'created_at' => now(),
]);
$target = $refunded === $total
? PaymentStatus::Refunded
: PaymentStatus::PartiallyRefunded;
$order->refunded_minor = $refunded;
if ($target !== $status) {
if (! $status->canTransitionTo($target)) {
throw new DomainException(
"Illegal payment transition: {$status->value} -> {$target->value}"
);
}
$order->payment_status = $target->value;
DB::table('order_state_events')->insert([
'order_id' => $order->id, 'machine' => 'payment',
'from_state' => $status->value, 'to_state' => $target->value,
'reason' => $reason ?? "refund $amountMinor minor units",
'actor_id' => $actorId,
'created_at' => now(),
]);
}
$order->save();
});
}
}The details that carry the weight:
- Checks happen on locked state inside the transaction. A check-then-write outside the lock lets two concurrent requests both pass; the lock serializes them and the second is judged on the post-first state.
- Refunds are rows, not just a counter.
refunded_minoraccumulates for the cap check, but every refund is also its ownrefundsrow with amount, reason and actor. The stored counters are validated from their raw decimal strings before any integer cast - Eloquent's integer cast would coerce a database value abovePHP_INT_MAX, so casting first cannot detect it - and anything malformed, negative, abovePHP_INT_MAX, or above the order total rejects the refund for review. The cap compares before adding (amount <= total - already), so the arithmetic can never overflow, and the comparison isstrcmpon equal-length digit strings, never>on numeric strings (PHP would parse those as numbers). The refund amount itself is amixedparameter rejected unlessis_int- a typedintparameter would still silently coerce values passed from non-strict callers, which the test suite demonstrates. This ran on 64-bit PHP; near-limit, above-range, corrupt-counter and non-integer-amount tests are all in the suite. - No money moves here.
refund()records a confirmed local refund fact and moves the payment machine to match; calling the payment provider and reconciling the result are orchestration concerns outside this example. - Every shipment carries its actor, including ones that change no state (the second partial shipment still gets a row with
actor_id). - Fulfilment is computed from shipment items after validating each line: non-empty shipment, known SKUs, positive integer quantities within bounds, never more than remains unshipped.
order_itemshas aunique(order_id, sku)so a SKU's ordered quantity lives in exactly one row.
Integration prerequisites#
The exact setup the tests ran against
This is not turnkey. It assumes a pre-existing orders table with at least: id, status (string), gateway_ref (string, unique - the test factory generates unique refs for this reason), amount_minor (unsigned big integer), currency (string), and timestamps. The migration below adds payment_status, fulfilment_status and refunded_minor to it and creates the order_items, shipments, shipment_items, refunds and order_state_events tables. The Order model casts the money columns to integer for ordinary reads (MySQL returns them as strings otherwise) - but the refund guard does not rely on those casts, since the cast itself would coerce an out-of-range database value; it validates the raw stored strings via getRawOriginal() instead:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $guarded = [];
// MySQL returns integers as strings without casts; money logic needs ints.
protected $casts = [
'amount_minor' => 'integer',
'refunded_minor' => 'integer',
];
}
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::table('orders', function (Blueprint $table) {
$table->string('payment_status')->default('unpaid');
$table->string('fulfilment_status')->default('unfulfilled');
$table->unsignedBigInteger('refunded_minor')->default(0);
});
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id');
$table->string('sku');
$table->unsignedInteger('qty');
$table->unsignedBigInteger('price_minor'); // integer minor units, never float
$table->unique(['order_id', 'sku']); // one line per SKU per order
});
Schema::create('shipments', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id');
$table->foreignId('actor_id')->nullable(); // who recorded it; null = system
$table->timestamp('created_at')->nullable();
});
Schema::create('shipment_items', function (Blueprint $table) {
$table->id();
$table->foreignId('shipment_id');
$table->string('sku');
$table->unsignedInteger('qty');
});
Schema::create('refunds', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id');
$table->unsignedBigInteger('amount_minor');
$table->string('reason')->nullable();
$table->foreignId('actor_id')->nullable();
$table->timestamp('created_at')->nullable();
});
Schema::create('order_state_events', function (Blueprint $table) {
$table->id();
$table->foreignId('order_id');
$table->string('machine'); // order | payment | fulfilment
$table->string('from_state');
$table->string('to_state');
$table->string('reason')->nullable();
$table->foreignId('actor_id')->nullable(); // who caused it; null = system
$table->timestamp('created_at')->nullable();
});
}
public function down(): void
{
Schema::dropIfExists('order_state_events');
Schema::dropIfExists('refunds');
Schema::dropIfExists('shipment_items');
Schema::dropIfExists('shipments');
Schema::dropIfExists('order_items');
Schema::table('orders', function (Blueprint $table) {
$table->dropColumn(['payment_status', 'fulfilment_status', 'refunded_minor']);
});
}
};Scope: a bounded tutorial example. Out of scope, stated plainly: idempotency keys on the endpoints (a retried "record shipment" call would create two shipments - this article covers the fix), provider orchestration and reconciliation for real refunds, inventory reservation, return workflows (cancel-after-ship is rejected, not reversed), and admin tooling, which can still touch rows outside the service.
The tests, and their real output#
Fifteen feature tests: legal transitions with audit and actor, illegal transitions with zero side effects, both derived-state bypasses rejected, the cross-machine policy (complete needs fulfilled + settled payment, no cancel after shipping, no shipping unpaid or unconfirmed), shipment input validation (empty, zero, string, float, unknown SKU, overship), split shipments with actor on every row, refund accumulation and cap, near-int64 refund compared before adding, raw stored counters of PHP_INT_MAX+1 and the max unsigned bigint rejected instead of silently clamped, non-integer refund amounts ('100', 1.5) rejected from a non-strict caller, and corrupt-counter rejection:
tests/Feature/OrderStateMachineTest.php
namespace Tests\Feature;
use App\Services\OrderStateService;
use DomainException;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;
class OrderStateMachineTest extends TestCase
{
use DatabaseTransactions;
private function makeOrder(string $status = 'pending', string $payment = 'unpaid', int $total = 10000): int
{
return DB::table('orders')->insertGetId([
'status' => $status,
'payment_status' => $payment,
'fulfilment_status' => 'unfulfilled',
'amount_minor' => $total, // 100.00 in minor units
'refunded_minor' => 0,
'currency' => 'EGP',
'gateway_ref' => 'oms-' . uniqid(), // gateway_ref is UNIQUE in this schema
'created_at' => now(), 'updated_at' => now(),
]);
}
private function addLine(int $orderId, string $sku, int $qty): void
{
DB::table('order_items')->insert([
'order_id' => $orderId, 'sku' => $sku, 'qty' => $qty, 'price_minor' => 3000,
]);
}
private function svc(): OrderStateService
{
return app(OrderStateService::class);
}
public function test_legal_transition_is_saved_and_audited(): void
{
$id = $this->makeOrder();
$this->svc()->transition($id, 'order', 'confirmed', 'payment received', 42);
$this->assertSame('confirmed', DB::table('orders')->where('id', $id)->value('status'));
$event = DB::table('order_state_events')->where('order_id', $id)->sole();
$this->assertSame('pending', $event->from_state);
$this->assertSame('confirmed', $event->to_state);
$this->assertSame(42, (int) $event->actor_id);
}
public function test_illegal_transition_is_rejected_without_side_effects(): void
{
$id = $this->makeOrder('pending');
try {
$this->svc()->transition($id, 'order', 'completed');
$this->fail('Expected DomainException');
} catch (DomainException $e) {
$this->assertSame('Illegal order transition: pending -> completed', $e->getMessage());
}
$this->assertSame('pending', DB::table('orders')->where('id', $id)->value('status'));
$this->assertSame(0, DB::table('order_state_events')->where('order_id', $id)->count());
}
public function test_generic_transition_cannot_set_fulfilment(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->expectException(DomainException::class);
$this->expectExceptionMessage('Fulfilment is derived from shipments');
try {
$this->svc()->transition($id, 'fulfilment', 'fulfilled');
} finally {
$this->assertSame('unfulfilled', DB::table('orders')->where('id', $id)->value('fulfilment_status'));
$this->assertSame(0, DB::table('order_state_events')->where('order_id', $id)->count());
}
}
public function test_generic_transition_cannot_set_refund_states(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->expectException(DomainException::class);
$this->expectExceptionMessage('Refund states are derived');
try {
$this->svc()->transition($id, 'payment', 'partially_refunded');
} finally {
$this->assertSame(0, DB::table('refunds')->where('order_id', $id)->count());
$this->assertSame(0, (int) DB::table('orders')->where('id', $id)->value('refunded_minor'));
}
}
public function test_cannot_complete_before_fulfilled_and_paid(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->addLine($id, 'A', 1);
try {
$this->svc()->transition($id, 'order', 'completed');
$this->fail('Expected DomainException');
} catch (DomainException $e) {
$this->assertSame('Cannot complete an order that is not fully fulfilled', $e->getMessage());
}
$this->svc()->recordShipment($id, ['A' => 1], 7);
$this->svc()->transition($id, 'order', 'completed');
$this->assertSame('completed', DB::table('orders')->where('id', $id)->value('status'));
}
public function test_cannot_cancel_after_anything_shipped(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->addLine($id, 'A', 2);
$this->svc()->recordShipment($id, ['A' => 1]);
$this->expectException(DomainException::class);
$this->expectExceptionMessage('return workflow');
$this->svc()->transition($id, 'order', 'cancelled');
}
public function test_cannot_ship_unpaid_or_unconfirmed_order(): void
{
$unpaid = $this->makeOrder('confirmed', 'unpaid');
$this->addLine($unpaid, 'A', 1);
try {
$this->svc()->recordShipment($unpaid, ['A' => 1]);
$this->fail('Expected DomainException');
} catch (DomainException $e) {
$this->assertSame('Only a paid order can be shipped', $e->getMessage());
}
$pending = $this->makeOrder('pending', 'paid');
$this->addLine($pending, 'A', 1);
$this->expectException(DomainException::class);
$this->expectExceptionMessage('Only a confirmed order can be shipped');
$this->svc()->recordShipment($pending, ['A' => 1]);
}
public function test_shipment_input_validation(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->addLine($id, 'A', 1);
foreach ([[], ['A' => 0], ['A' => '1'], ['A' => 1.5], ['B' => 1], ['A' => 2]] as $bad) {
try {
$this->svc()->recordShipment($id, $bad);
$this->fail('Expected DomainException for ' . json_encode($bad));
} catch (DomainException) {
}
}
// nothing written by any of the rejected attempts
$this->assertSame(0, DB::table('shipments')->where('order_id', $id)->count());
$this->assertSame('unfulfilled', DB::table('orders')->where('id', $id)->value('fulfilment_status'));
}
public function test_split_shipments_drive_fulfilment_with_actor_on_every_row(): void
{
$id = $this->makeOrder('confirmed', 'paid');
$this->addLine($id, 'A', 3);
$this->svc()->recordShipment($id, ['A' => 1], 7);
$this->assertSame('partially_fulfilled', DB::table('orders')->where('id', $id)->value('fulfilment_status'));
$this->svc()->recordShipment($id, ['A' => 1], 8); // still partial
$this->assertSame('partially_fulfilled', DB::table('orders')->where('id', $id)->value('fulfilment_status'));
$this->svc()->recordShipment($id, ['A' => 1], 9);
$this->assertSame('fulfilled', DB::table('orders')->where('id', $id)->value('fulfilment_status'));
// every shipment row carries its actor, even ones that changed no state
$this->assertSame([7, 8, 9], DB::table('shipments')->where('order_id', $id)
->orderBy('id')->pluck('actor_id')->map(fn ($v) => (int) $v)->all());
$this->assertSame(2, DB::table('order_state_events')
->where('order_id', $id)->where('machine', 'fulfilment')->count());
}
public function test_partial_refunds_accumulate_and_cap_at_paid_total(): void
{
$id = $this->makeOrder('confirmed', 'paid', 10000);
$this->svc()->refund($id, 4000);
$this->assertSame('partially_refunded', DB::table('orders')->where('id', $id)->value('payment_status'));
$this->svc()->refund($id, 6000);
$this->assertSame('refunded', DB::table('orders')->where('id', $id)->value('payment_status'));
$this->assertSame(10000, (int) DB::table('orders')->where('id', $id)->value('refunded_minor'));
$this->assertSame([4000, 6000], DB::table('refunds')->where('order_id', $id)
->orderBy('id')->pluck('amount_minor')->map(fn ($v) => (int) $v)->all());
$this->expectException(DomainException::class);
$this->expectExceptionMessage('Cannot refund from payment state');
$this->svc()->refund($id, 1);
}
public function test_over_refund_rejected_near_int64_limit_without_overflow(): void
{
$id = $this->makeOrder('confirmed', 'paid', PHP_INT_MAX - 100);
$this->svc()->refund($id, PHP_INT_MAX - 100); // exactly the total, no overflow
$this->assertSame('refunded', DB::table('orders')->where('id', $id)->value('payment_status'));
$id2 = $this->makeOrder('confirmed', 'paid', PHP_INT_MAX - 100);
try {
$this->svc()->refund($id2, PHP_INT_MAX - 99); // one minor unit over the total
$this->fail('Expected DomainException');
} catch (DomainException $e) {
$this->assertStringContainsString('exceeds remaining', $e->getMessage());
}
$this->assertSame(0, (int) DB::table('orders')->where('id', $id2)->value('refunded_minor'));
}
public function test_refund_that_would_overflow_is_compared_before_adding(): void
{
$id = $this->makeOrder('confirmed', 'paid', PHP_INT_MAX);
DB::table('orders')->where('id', $id)->update([
'refunded_minor' => PHP_INT_MAX - 50,
'payment_status' => 'partially_refunded',
]);
try {
$this->svc()->refund($id, 100); // already + 100 would overflow if added first
$this->fail('Expected DomainException');
} catch (DomainException $e) {
$this->assertStringContainsString('exceeds remaining 50', $e->getMessage());
}
$this->svc()->refund($id, 50); // exactly the remainder: allowed, no overflow
$this->assertSame('refunded', DB::table('orders')->where('id', $id)->value('payment_status'));
}
public function test_raw_counter_above_int64_max_is_rejected_not_clamped(): void
{
foreach (['9223372036854775808', '18446744073709551615'] as $raw) { // PHP_INT_MAX+1, max unsigned bigint
$id = $this->makeOrder('confirmed', 'paid', 10000);
DB::table('orders')->where('id', $id)->update(['amount_minor' => $raw]);
try {
$this->svc()->refund($id, 1);
$this->fail("Expected DomainException for raw amount $raw");
} catch (DomainException $e) {
$this->assertStringContainsString('inconsistent', $e->getMessage());
}
$this->assertSame(0, DB::table('refunds')->where('order_id', $id)->count());
}
}
public function test_refund_amount_must_be_a_real_integer(): void
{
$id = $this->makeOrder('confirmed', 'paid', 10000);
// this test file has no strict_types declaration: a typed int parameter
// would coerce these. The mixed guard must reject them instead.
foreach (['100', 1.5, 0, -50] as $bad) {
try {
$this->svc()->refund($id, $bad);
$this->fail('Expected DomainException for ' . var_export($bad, true));
} catch (DomainException) {
}
}
$this->assertSame(0, DB::table('refunds')->where('order_id', $id)->count());
$this->assertSame(0, (int) DB::table('orders')->where('id', $id)->value('refunded_minor'));
$this->assertSame('paid', DB::table('orders')->where('id', $id)->value('payment_status'));
}
public function test_corrupt_money_counters_rejected(): void
{
$id = $this->makeOrder('confirmed', 'paid', 10000);
DB::table('orders')->where('id', $id)->update(['refunded_minor' => 10001]); // refunded > total
$this->expectException(DomainException::class);
$this->expectExceptionMessage('inconsistent');
$this->svc()->refund($id, 1);
}
}Real output of that exact file (PHPUnit 12.5.43, PHP 8.4.27, Laravel 13, MySQL 8.4):
Runtime: PHP 8.4.27
Configuration: /tmp/laravel/scratch/phpunit.xml
............... 15 / 15 (100%)
Time: 00:00.191, Memory: 40.50 MB
OK (15 tests, 49 assertions)Two limits to state. These are sequential tests: the row lock makes concurrent transitions serialize by construction, but this suite does not prove race behavior - that takes a real concurrent harness, outside scope here. And duplicate-request semantics are excluded by design (see prerequisites).
State machines vs. the alternatives#
| Approach | What goes wrong |
|---|---|
| Plain string column, set anywhere | Every transition is legal, including refunded -> pending; audit is a plea in a code comment |
| Validation rules at the controller | Guards live in one door; jobs, webhooks and console commands walk around them |
| One mega-status column | paid_partially_shipped combinatorics; adding a state touches every check |
| Enum machines + one service (this article) | Illegal transitions are unrepresentable through the service; audit is structural |
Common mistakes#
| Mistake | What it costs |
|---|---|
| One status column for order + payment + fulfilment | Combinatorial states; rules that fit none of the lifecycles |
| Checking state before the lock, writing after | Two concurrent transitions both pass; the audit log lies |
| Letting callers set derived states directly | fulfilled orders with nothing shipped; "refunded" with no refund rows |
| Refunds as a bare counter | No way to answer "which refunds make up this total?" |
| Adding before comparing in the cap check | Overflow near int64 limits turns a huge refund into an accepted one |
| Floats near refund math | Rounding drift between refunded_minor and the refund rows |
| Silent no-ops on illegal transitions | The caller believes the change happened; throw instead |
| Trusting sequential tests as concurrency proof | The lock is the argument; the tests only cover the guards |
Checklist#
- One enum per lifecycle; legal transitions declared in the enum; terminal states explicit
- Command vs derived states separated; derived states only via dedicated methods
- All transitions through one service, checks on
lockForUpdatestate inside the transaction - Cross-machine policy (what may ship, complete, cancel) enforced in the service
- Audit row per transition: machine, from/to, reason, actor, timestamp - and actor on every shipment and refund row
- Money in integer minor units; counters validated; cap compared before adding; every refund a row
- Fulfilment derived from shipment items; overship and bad input rejected; one row per SKU per order
- Illegal transitions throw; nothing is written on rejection
- Idempotency keys on the endpoints (out of scope here - link above)
- Concurrent-harness test before claiming race safety
Key takeaways#
Model order, payment and fulfilment as three small machines, not one big column. Declare legal transitions on backed enums, keep command and derived states apart, enforce everything in one service that checks locked state inside a transaction, and audit every change with its actor. Keep money in integers, compare before you add, and make refunds rows. Illegal transitions must throw loudly - a silent no-op is a lie your future self will debug.
References#
- Laravel database transactions and locking: https://laravel.com/docs/database#database-transactions
- PHP backed enums: https://www.php.net/manual/en/language.enumerations.backed.php
- Idempotency keys for the endpoints around this: /en/blog/idempotency-keys-laravel-stop-double-charges
- Money in minor units and rounding: /en/blog/money-bugs-currency-rounding-discounts-vat
- Reconciling what the gateway says against these tables: /en/blog/payment-reconciliation-for-engineers
Designing an order system or untangling one that already grew a mega-status? See /en/services.