Feature: Order Updates, Events, Order Flows, Shipment And COD support

This commit is contained in:
2026-09-14 00:03:06 +03:00
parent 78bbd8390a
commit 44c6b7defd
73 changed files with 2854 additions and 464 deletions
@@ -0,0 +1,169 @@
<?php
namespace Modules\Core\Order\Services;
use Lunar\Models\Order;
use Lunar\Shipping\Models\ShippingMethod;
use Modules\Core\Order\DTOs\OrderFulfillmentResult;
use Modules\Core\Order\Events\OrderPickedUp;
use Modules\Core\Order\Events\OrderReadyForDispatch;
use Modules\Core\Order\Events\OrderReadyForPickup;
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
use Modules\Core\Shipping\DTOs\ShipmentRequest;
use Throwable;
/**
* The staff-facing fulfillment/return/payment workflow behind the three
* header actions in Modules\Core\Shipping\Extensions\OrderViewExtension
* ("Create Shipment", "Update Status", "Mark Paid") — every guard check,
* status write (via Modules\Core\Order\Services\OrderStatusWriter), and
* event dispatch lives here, keeping this workflow usable and testable
* independent of Filament.
*
* Every method re-validates its own precondition internally (not just
* trusted from the caller's own visible()-equivalent check) — protects
* against a stale page load racing a concurrent automatic transition
* (e.g. a carrier tracking checkpoint advancing the same order between
* page load and button click).
*/
class OrderFulfillmentService
{
public function __construct(
private readonly OrderStatusWriter $writer,
private readonly OrderStatusFlow $flow,
) {}
public function markReady(Order $order): OrderFulfillmentResult
{
if ($order->status !== 'processing') {
return OrderFulfillmentResult::failure('This order must be in Processing before it can be marked ready.');
}
$target = $order->isStorePickupOrder() ? 'ready_for_pickup' : 'ready_for_dispatch';
$this->writer->write($order, $target, self::class.'::markReady');
if ($order->isStorePickupOrder()) {
OrderReadyForPickup::dispatch($order);
} else {
OrderReadyForDispatch::dispatch($order);
}
return OrderFulfillmentResult::success('Order marked ready.');
}
public function createShipmentAndDispatch(Order $order, ShipmentRequest $request): OrderFulfillmentResult
{
if ($order->status !== 'ready_for_dispatch') {
return OrderFulfillmentResult::failure('This order is not ready to be dispatched.');
}
$service = $this->resolveFulfillmentService($order);
if (! $service) {
return OrderFulfillmentResult::failure('No carrier fulfillment integration is configured for this order.');
}
try {
$service->createShipment($order, $request);
} catch (Throwable $e) {
report($e);
return OrderFulfillmentResult::failure('Failed to create shipment: '.$e->getMessage());
}
$this->writer->write($order, 'dispatched', self::class.'::createShipmentAndDispatch');
return OrderFulfillmentResult::success('Shipment created and order dispatched.');
}
public function markPickedUp(Order $order): OrderFulfillmentResult
{
if ($order->status !== 'ready_for_pickup') {
return OrderFulfillmentResult::failure('This order is not ready for pickup.');
}
$this->writer->write($order, 'picked_up', self::class.'::markPickedUp');
OrderPickedUp::dispatch($order);
return OrderFulfillmentResult::success('Order marked as picked up.');
}
/**
* The general-purpose entry point for any transition with no special
* side effect — a manual override, not restricted to the guided next
* step(s), so staff can revert to an earlier status in the order's
* own branch. Validates $to is actually a member of
* OrderStatusFlow::allOptions() before writing (server-side
* re-validation of whatever the Select offered) — still refuses a
* status from the WRONG branch or an unknown value.
*/
public function transitionTo(Order $order, string $to): OrderFulfillmentResult
{
if (! array_key_exists($to, $this->flow->allOptions($order))) {
return OrderFulfillmentResult::failure('That status is not valid for this order.');
}
$this->writer->write($order, $to, self::class.'::transitionTo');
return OrderFulfillmentResult::success('Order status updated.');
}
/**
* Independent of `status` entirely — offered by the single "Update
* Status" action regardless of current status (see
* OrderStatusFlow::canMarkPaid()).
*/
public function markPaid(Order $order): OrderFulfillmentResult
{
if (! $this->flow->canMarkPaid($order)) {
return OrderFulfillmentResult::failure('This order cannot be marked paid right now.');
}
$this->writer->markPaid($order, self::class.'::markPaid');
return OrderFulfillmentResult::success('Order marked as paid.');
}
public function canCreateShipment(Order $order): bool
{
return $order->status === 'ready_for_dispatch'
&& ! $order->isStorePickupOrder()
&& $order->shipments()->exists() === false
&& $this->resolveFulfillmentService($order) !== null;
}
/**
* Public wrapper around resolveCarrier() — Modules\Core\Shipping\
* Extensions\OrderViewExtension needs to know which carrier an order
* uses to branch the "Create Shipment" form (Box Now's box-size
* repeater vs. every other carrier's plain weight field).
*/
public function carrierFor(Order $order): ?string
{
return $this->resolveCarrier($order);
}
private function resolveCarrier(Order $order): ?string
{
$code = $order->shippingAddress?->shipping_option;
if (! $code) {
return null;
}
return ShippingMethod::where('code', $code)->value('driver');
}
private function resolveFulfillmentService(Order $order): ?CarrierFulfillmentInterface
{
$carrier = $this->resolveCarrier($order);
if (! $carrier) {
return null;
}
return app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]);
}
}
+140
View File
@@ -0,0 +1,140 @@
<?php
namespace Modules\Core\Order\Services;
use Lunar\Models\Order;
use Modules\Core\Payment\Models\PaymentMethod;
/**
* Two status sequences — carrier, pickup (Order::isStorePickupOrder()) —
* NOT four. Payment method (prepaid vs. cash-on-delivery) does not affect
* the status SEQUENCE at all; it only affects Order::paid, an entirely
* separate field this class also offers a transition for (see
* canMarkPaid()). `status` never includes a "paid" step — COD
* reconciliation can happen at any point in, or after, the fulfillment
* journey (same-day to months later), so it cannot occupy a fixed slot in
* a linear sequence.
*/
class OrderStatusFlow
{
private const FLOW_CARRIER = [
'awaiting_payment', 'processing', 'ready_for_dispatch', 'dispatched',
'delivered', 'completed', 'return_requested', 'returned',
];
private const FLOW_PICKUP = [
'awaiting_payment', 'processing', 'ready_for_pickup', 'picked_up',
'completed', 'return_requested', 'returned',
];
private const REFUND_OPTIONS = ['partially_refunded', 'refunded'];
private const RETURN_ELIGIBLE_FROM = ['delivered', 'picked_up', 'completed'];
public function resolveFlow(Order $order): array
{
return $order->isStorePickupOrder() ? self::FLOW_PICKUP : self::FLOW_CARRIER;
}
/**
* Order.meta['payment_method'] (written by
* Modules\Core\Checkout\Services\CheckoutService::initiatePayment())
* is the durable source of truth. Falls back to the most recent
* Transaction.driver (a payment TYPE slug) only if meta is missing —
* e.g. an order placed before this field existed.
*/
public function isCod(Order $order): bool
{
$type = $order->meta['payment_method'] ?? $order->transactions()->latest('id')->value('driver');
if ($type === null) {
return false;
}
return PaymentMethod::where('type', $type)->value('driver') === 'cash-on-delivery';
}
/**
* @return array<string, string> value => label — every status in the
* order's own branch (carrier or pickup), plus the refund options,
* for a manual-override "New status" select. Deliberately not
* filtered to nextOptions()'s guided next-step(s) — staff can jump
* to any status in their branch, including reverting to an earlier
* one (e.g. undoing a mistaken click). transitionTo() still
* validates $to is actually a member of this set server-side.
*/
public function allOptions(Order $order): array
{
$statuses = [...$this->resolveFlow($order), ...self::REFUND_OPTIONS, 'delivery_failed'];
return collect($statuses)
->unique()
->mapWithKeys(fn (string $status) => [$status => $this->label($status)])
->all();
}
/**
* @return array<string, string> value => label — status-sequence
* transitions offered as the guided next step(s). Does not include
* the "mark paid" pseudo-option — see canMarkPaid().
*/
public function nextOptions(Order $order): array
{
$flow = $this->resolveFlow($order);
$current = $order->status;
$position = array_search($current, $flow, true);
$options = [];
if ($position !== false && isset($flow[$position + 1])) {
$options[] = $flow[$position + 1];
}
// delivery_failed — a possible outcome of any delivery attempt,
// carrier flow only, checked on $current directly (not on the
// flow's literal next value) since it's a branch on the attempt
// itself, not on sequence position.
if ($current === 'dispatched') {
$options[] = 'delivery_failed';
}
// From delivery_failed: retry dispatch, or give up and treat as
// a return.
if ($current === 'delivery_failed') {
array_push($options, 'dispatched', 'return_requested');
}
if (in_array($current, self::RETURN_ELIGIBLE_FROM, true)) {
$options[] = 'return_requested';
}
if ($current === 'return_requested') {
$options[] = 'returned';
}
if ($current === 'returned') {
array_push($options, ...self::REFUND_OPTIONS);
}
return collect($options)
->unique()
->mapWithKeys(fn (string $status) => [$status => $this->label($status)])
->all();
}
/**
* Whether the "mark paid" option should be offered right now —
* entirely independent of $order->status. True whenever this is a
* cash-on-delivery order and payment hasn't been recorded yet,
* regardless of fulfillment progress (before OR after completed).
*/
public function canMarkPaid(Order $order): bool
{
return ! $order->paid && $this->isCod($order);
}
private function label(string $status): string
{
return (string) str($status)->replace('_', ' ')->title();
}
}
@@ -0,0 +1,27 @@
<?php
namespace Modules\Core\Order\Services;
use Lunar\Models\Order;
use Modules\Core\Order\Models\OrderStatusTransition;
/**
* The single place every order_status_transitions row gets written —
* called by Modules\Core\Order\Listeners\RecordStatusTransition, itself
* listening to Modules\Core\Order\Events\OrderStatusChanged and
* OrderPaidChanged, dispatched by Modules\Core\Order\Services\
* OrderStatusWriter (the only writer of Order::status/paid left in this
* package).
*/
final class OrderStatusTransitionRecorder
{
public function record(Order $order, ?string $from, string $to, string $eventClass): void
{
OrderStatusTransition::create([
'order_id' => $order->id,
'from_status' => $from,
'to_status' => $to,
'event_class' => $eventClass,
]);
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace Modules\Core\Order\Services;
use Lunar\Models\Order;
use Modules\Core\Order\Events\OrderPaidChanged;
use Modules\Core\Order\Events\OrderStatusChanged;
/**
* The one place Order::status/paid actually get written — replaces the
* earlier per-axis Modules\Core\Order\Services\OrderAxisWriter now that
* there is a single status column plus one independent `paid` field (see
* Modules\Core\Order\Services\OrderStatusFlow's own docblock for why
* payment timing is not a status-sequence step).
*
* write() relies on Modules\Core\Order\Observers\OrderObserver to
* generically dispatch OrderStatusUpdated whenever `status` actually
* changes — there's no separate axis-changed event to dispatch here
* anymore, since there's only one column left to watch. markPaid() is
* genuinely independent: it dispatches its own OrderPaidChanged, since
* OrderObserver only watches `status`, not `paid`.
*
* Cause is passed explicitly through every call rather than smuggled
* through a runtime property on the model — Lunar\Models\Order has
* $guarded = [], so Eloquent treats ANY property assignment as a real
* column to persist; an earlier design that tried
* $order->statusTransitionCause = ... broke immediately with an
* "undefined column" error the moment ->update() ran.
*/
class OrderStatusWriter
{
public function write(Order $order, string $to, string $causeClass): void
{
$from = $order->status;
if ($from === $to) {
return;
}
$order->update(['status' => $to]);
OrderStatusChanged::dispatch($order, $from, $to, $causeClass);
}
public function markPaid(Order $order, string $causeClass): void
{
if ($order->paid) {
return;
}
$order->update(['paid' => true, 'paid_at' => now()]);
OrderPaidChanged::dispatch($order, $causeClass);
}
}