Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e532c32cab | ||
|
|
6a51b672c8 | ||
|
|
956e9e88a6 | ||
|
|
4489475840 | ||
|
|
e4e008167a | ||
|
|
a5f3008ce2 | ||
|
|
d9fb3bbde6 | ||
|
|
26b4c5bfd7 | ||
|
|
57fc28ca06 | ||
|
|
9d3e54e5df | ||
|
|
44c6b7defd | ||
|
|
78bbd8390a | ||
|
|
99e55902ac | ||
|
|
864c8b19aa | ||
|
|
8f4c1a22ea | ||
|
|
13d5833d18 |
+311
@@ -4,6 +4,317 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
## [0.17.3] - 2026-09-15
|
||||
|
||||
### Changed
|
||||
- Removed the `lunarphp/stripe` dependency in favour of depending on `stripe/stripe-php` directly.
|
||||
`Modules\Core\Payment\Drivers\StripePaymentDriver` had already replaced every bit of Lunar's own
|
||||
Stripe payment flow (checkout, webhook processing) with its own — all that remained load-bearing
|
||||
from the package was raw API-client access, amount conversion, and a correlation table, none of
|
||||
which are Lunar-specific. Added first-party replacements: `Modules\Core\Payment\Support\
|
||||
StripeManager` (API client + `toStripeAmount()`/`fromStripeAmount()`), `Modules\Core\Payment\
|
||||
Models\StripePaymentIntent` (now with a proper `context` array cast, replacing manual
|
||||
`json_encode`/`json_decode`), and `Modules\Core\Payment\Http\Middleware\
|
||||
StripeWebhookMiddleware`. Added `database/migrations/..._create_stripe_payment_intents_table.php`,
|
||||
a first-party copy of the vendor migration (guarded with `Schema::hasTable()` so it's a no-op on
|
||||
any environment that already has the table from the vendor package's own earlier migration run,
|
||||
and only actually creates it on a genuinely fresh install). No behavior change for consuming
|
||||
apps — same table, same driver contract, same webhook endpoint.
|
||||
|
||||
## [0.17.2] - 2026-09-15
|
||||
|
||||
### Fixed
|
||||
- `Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus` never advanced `Order::status` past
|
||||
`awaiting_payment` on a capture — only `paid`/`paid_at` were written, so a fully captured order
|
||||
could sit indefinitely at "awaiting payment" until a staff member manually clicked "Update
|
||||
Status". Now, on `PaymentCaptured` (not `PaymentAuthorized` — an authorization isn't yet
|
||||
captured funds), `status` advances to the next step in the order's flow
|
||||
(`Modules\Core\Order\Services\OrderStatusFlow::nextOptions()`) — but only when it's still
|
||||
exactly `awaiting_payment`, so a duplicate/delayed capture event never regresses an order staff
|
||||
already moved further.
|
||||
- The backoffice "Capture" action on the order page (Filament) called vendor Lunar's
|
||||
`Lunar\Models\Transaction::capture()` directly, which resolves `Lunar\Facades\Payments` — an
|
||||
entirely separate, unused driver registry — and never dispatched `Modules\Core\Payment\Events\
|
||||
PaymentCaptured`. This meant a manual capture from the admin panel never ran this app's own
|
||||
payment pipeline at all (including the status-advance fix above). `Modules\Core\Order\Filament\
|
||||
Extensions\OrderActionsExtension` (renamed from `OrderRefundActionsExtension`, since it now
|
||||
fixes both the refund and capture header actions — see below) now routes capture through
|
||||
`Modules\Core\Payment\Support\TransactionDriverAdapter::capture()`, the same app-level path
|
||||
checkout-time captures use.
|
||||
- `Modules\Core\Payment\Drivers\StripePaymentDriver` never extracted a card's brand/last four
|
||||
digits from Stripe's response, so `Lunar\Models\Transaction::card_type`/`last_four` were always
|
||||
empty and the admin's "Payment of :amount on card ending :last_four" activity-log line rendered
|
||||
with no digits — reproduced on both checkout-time and manual captures. Added
|
||||
`cardMetaFromIntent()`, reading `payment_method_details` off the PaymentIntent's `latest_charge`
|
||||
(same source `lunarphp/stripe`'s own `StoreCharges` uses), populated into `PaymentResult::$meta`
|
||||
from `resultFromIntent()` and `capture()`. `Modules\Core\Order\Services\TransactionRecorder`
|
||||
now maps `meta['card_type']`/`meta['last_four']` onto the `Transaction` row. Only applies to
|
||||
transactions recorded after this change — existing rows are not backfilled.
|
||||
|
||||
### Changed
|
||||
- `Modules\Core\Order\Filament\Extensions\OrderRefundActionsExtension` renamed to
|
||||
`OrderActionsExtension` — the class now fixes both the refund and capture header actions on the
|
||||
order page, not just refund, so the old name undersold its scope.
|
||||
|
||||
## [0.17.1] - 2026-09-15
|
||||
|
||||
### Fixed
|
||||
- `Modules\Core\Payment\Drivers\StripePaymentDriver::createAndConfirm()` only set
|
||||
`automatic_payment_methods` when no `payment_method` was given — the actual checkout flow always
|
||||
sends one, so it was omitted, and Stripe fell back to whatever payment methods are enabled in the
|
||||
Dashboard and demanded a `return_url` on confirm. Fixed by setting `automatic_payment_methods`
|
||||
unconditionally with `allow_redirects: never` — the storefront's Payment Element already restricts
|
||||
itself to `paymentMethodTypes: ['card']`, so this just tells Stripe the same thing server-side,
|
||||
which drops the `return_url` requirement.
|
||||
|
||||
## [0.17.0] - 2026-09-14
|
||||
|
||||
### Added
|
||||
- `Modules\Core\Order\Notifications\OrderPlacedNotification` — an order confirmation email,
|
||||
registered against `Modules\Core\Checkout\Events\OrderPlaced` (fires exactly once per order,
|
||||
regardless of `capture_mode`/driver). Previously only a Stripe (auto-captured) order triggered
|
||||
any placement email at all, via `OrderCapturedNotification` — a different concern (payment
|
||||
confirmation) that happened to fire at the same moment for that one driver; an offline or
|
||||
bank-transfer order got no confirmation whatsoever. Verified live via Mailpit.
|
||||
- `Modules\Core\Order\Listeners\DecrementStockOnOrderPlaced` — also wired to `OrderPlaced`, the
|
||||
first stock decrement anywhere in this codebase (previously nothing wrote to
|
||||
`ProductVariant::stock` as a result of an order at all — overselling was possible). A single
|
||||
atomic `UPDATE ... SET stock = GREATEST(stock - qty, 0)` per variant, not a read-then-write on
|
||||
the Eloquent model, to avoid a lost-update race between two orders decrementing the same variant
|
||||
concurrently. Only touches `purchasable === 'in_stock'` variants on `physical` order lines —
|
||||
`always`/`backorder` variants are deliberately left alone (their stock has no purchasing
|
||||
consequence, decrementing it would just make the column an inaccurate negative number). Also
|
||||
re-triggers Scout reindexing for every affected product, closing the gap `Modules\Core\Catalog\
|
||||
Services\ProductIndexer`'s own docblock flagged ("nothing currently reindexes a product when an
|
||||
order decrements its stock") — the search index's `in_stock` filter now reflects the change
|
||||
immediately rather than only on the next scheduled reindex.
|
||||
- `Modules\Core\Cart\Services\CartLifecycleService` — the single source of truth for the four
|
||||
cart lifecycle states (Ongoing, Abandoned Cart, Abandoned Checkout, Completed) documented in
|
||||
`docs/cart.md`. Previously `Modules\Core\Cart\Filament\Resources\CartResource\Pages\ListCarts`
|
||||
and `Modules\Core\Cart\Commands\DetectAbandonedCarts` each reimplemented the same query split
|
||||
independently, which is exactly the kind of drift that lets the admin panel and the
|
||||
recovery-email pipeline quietly disagree about what "abandoned" means. Both now build on the
|
||||
same `ongoing()`/`abandonedCarts()`/`abandonedCheckouts()`/`completed()` methods, each taking a
|
||||
`Builder` so callers compose the scope onto whatever base query they already have — Filament's
|
||||
own tab query (search/sort/pagination intact) for `ListCarts`, a bare `Cart::query()` for the
|
||||
command.
|
||||
- `core.cart.unrecoverable_after` config (default `90 days`) — beyond this age, a stale cart
|
||||
stops being treated as an active "Abandoned Cart"/"Abandoned Checkout" at all (excluded from
|
||||
both `CartLifecycleService` methods), rather than staying flagged as an actionable abandonment
|
||||
forever. A 90-day-old (or older) cart's pricing/stock/tax have very likely moved on, so it's not
|
||||
a realistic recovery target — this is about the abandoned-cart pipeline only, not data
|
||||
retention; no rows are deleted or pruned.
|
||||
- `Modules\Core\Cart\Filament\Resources\CartResource\Pages\ViewCart`'s Lines section now shows
|
||||
each line's product thumbnail, name (linking to the product's edit page), and variant options —
|
||||
not just SKU/quantity/price — mirroring Lunar's own order line item display
|
||||
(`OrderItemsTable`). Also added a new Shipping section: the resolved shipping method name (not
|
||||
the bare `acs`-style identifier), destination country, shipping total, and each
|
||||
`shippingBreakdown` line item individually (carrier rate, plus any payment-method fee — see
|
||||
0.16.3's `ApplyPaymentMethodFee`) so staff can see what makes up the total, not just the sum.
|
||||
Guards around `Lunar\Models\ProductVariant::getDescription()`/`getOption()`: both are typed to
|
||||
return `string` but internally read `translateAttribute()`/`translate()`, which return `null`
|
||||
for a product/option with no attribute data set for the active locale — a real `TypeError` hit
|
||||
live against an existing test-fixture product. Reads the underlying relations directly instead
|
||||
of calling through those methods, falling back to "—" rather than crashing the page.
|
||||
|
||||
- `Modules\Core\Payment\Drivers\CashOnDeliveryPaymentDriver` — cash-on-delivery/cash-on-pickup was
|
||||
previously wired to `OfflinePaymentDriver`, the same immediate-capture driver as cash-in-hand,
|
||||
which meant a COD order was marked paid the instant it was placed even though no money had
|
||||
actually changed hands. The new driver's `pay()` returns `PaymentResultStatus::Pending` and
|
||||
dispatches nothing, so payment stays unresolved until staff explicitly confirm cash was received
|
||||
(see `Order::paid`/`paid_at` below). A data migration repoints the already-seeded
|
||||
`cash-on-delivery` `PaymentMethod` row to the new driver key.
|
||||
- `Order::paid`/`paid_at` — an entirely independent boolean/timestamp pair tracking payment,
|
||||
settable at any point in an order's lifecycle regardless of fulfillment progress. Exists because
|
||||
cash-on-delivery payment timing has no relationship to the fulfillment sequence at all — a
|
||||
courier might not reconcile cash for weeks after an order is already marked completed.
|
||||
|
||||
### Changed
|
||||
- **Order status model, redesigned from scratch.** `Order.status` is a single column again
|
||||
(a same-session 3-axis `payment_status`/`fulfillment_status`/`return_status` design was built,
|
||||
then abandoned before shipping — three independent selects let staff set any combination with no
|
||||
cross-field validation, and didn't map onto how staff actually think about an order: one linear
|
||||
journey, not three simultaneous dials). Now driven by `Modules\Core\Order\Services\
|
||||
OrderStatusFlow`, a pure transition-table service offering exactly two sequences — carrier and
|
||||
store-pickup (`Order::isStorePickupOrder()`) — never four; payment method (prepaid vs. COD)
|
||||
affects `Order::paid` only, not which sequence an order follows or where it sits in it. The
|
||||
Filament order page's several guided buttons are replaced by three header actions: "Update
|
||||
Status" offers every status in the order's own branch (`OrderStatusFlow::allOptions()`) — not
|
||||
just the guided next step — so staff can also revert to an earlier status (e.g. undoing a
|
||||
mistaken click); it also replaces vendor `ManageOrder`'s own built-in "Update Status" (same
|
||||
action name, previously left in place unintentionally, producing two duplicate buttons), since
|
||||
vendor's writes `status` directly with no audit trail or branch validation. It is a PLAIN status
|
||||
write with no side effects — picking 'dispatched' there does not create a real shipment. "Create
|
||||
Shipment" is its own separate action, visible only for a carrier order at 'ready_for_dispatch'
|
||||
(`OrderFulfillmentService::canCreateShipment()`) — the one action that talks to a real carrier
|
||||
API, so its weight/locker inputs only ever appear for that specific real-world action rather than
|
||||
inside the general-purpose status select for every manual override of 'dispatched'. "Mark Paid"
|
||||
is a third, separate header action — `Order::paid` is independent of `status`, so it doesn't
|
||||
belong bundled into the status select either — visible only when the order's payment method
|
||||
doesn't auto-capture at checkout (currently only cash-on-delivery). New status vocabulary
|
||||
(`awaiting_payment`, `processing`, `ready_for_dispatch`/`ready_for_pickup`, `dispatched`,
|
||||
`delivery_failed`, `picked_up`, `delivered`, `completed`, `return_requested`, `returned`,
|
||||
`partially_refunded`, `refunded`) replaces the old hyphenated 7-value list in
|
||||
`config/lunar/orders.php` — a breaking rename backed by a one-time data migration that maps every
|
||||
existing order onto the new vocabulary (preferring axis-system data where an order was actually
|
||||
moved through it during this session's testing, falling back to the legacy flat status otherwise)
|
||||
and derives `paid` from historical transaction data. (The carrier branch's post-delivery status
|
||||
was initially named `return_window_open`; renamed to `delivered` — same one combined moment,
|
||||
parcel arrived and return window open — via a follow-up migration once the internal name turned
|
||||
out to be a confusing thing for staff to see on an order.) A new "Payment Method" entry on the
|
||||
order summary sidebar (`Order.meta['payment_method']`, falling back to the latest transaction's
|
||||
driver) surfaces which method a shopper actually used, previously shown nowhere on the order
|
||||
page. The order list topbar's tabs (Lunar's own `favourite` config flag) are trimmed to the
|
||||
main-journey statuses only, rather than all twelve — the exception/branch statuses stay reachable
|
||||
via the table's own filter.
|
||||
- "Create Shipment"'s form now branches by carrier (`OrderFulfillmentService::carrierFor()`):
|
||||
- A weight-billed carrier (ACS) gets its weight field pre-filled from the order's own line
|
||||
weights via the new `Modules\Core\Shipping\Support\WeightCalculator` (the same unit-conversion
|
||||
table `AcsRateDriver::totalWeightInKg()` already used for live rate quoting, now shared rather
|
||||
than duplicated) — still staff-editable, not forced.
|
||||
- Box Now ships by compartment size, not weight, so it gets a repeatable list of boxes (one row
|
||||
per physical parcel, each with its own S/M/L size — `ShipmentRequest::$boxes`) instead of the
|
||||
weight field. `BoxNowFulfillmentService::createShipment()` sends one `items` entry per box in a
|
||||
single delivery request and now creates one `Shipment` row per parcel returned (was hardcoded to
|
||||
exactly one box/compartmentSize=1, silently ignoring anything beyond the first parcel) — each row
|
||||
independently trackable/printable/cancellable, linked to its siblings via a shared
|
||||
`meta['delivery_request_id']`.
|
||||
- Box Now's locker field is locked read-only once the shopper's own checkout selection
|
||||
(`$order->shippingAddress->meta['box_now_locker']`) is present — staff can no longer silently
|
||||
redirect a parcel to a different locker than the one the customer picked at checkout; it's only
|
||||
editable for the (current, checkout-UI-less) case where nothing set it yet.
|
||||
- New "Shipments" section on the order page (`Modules\Core\Shipping\Extensions\
|
||||
OrderShipmentsExtension`, between Transactions and Timeline) — "Create Shipment" previously had no
|
||||
counterpart anywhere to actually see what it created. One entry per `Shipment` record (a multi-box
|
||||
Box Now order shows one entry per parcel), rendered as two inline-labelled lines — carrier +
|
||||
tracking reference, then status + a "Created … · Locker …" helper line — rather than a grid of
|
||||
individually stacked label/value blocks, which reads as a wall of repeated labels once the admin's
|
||||
main content area narrows below Filament's own grid breakpoint (1024px, common with the sidebar
|
||||
open). Two actions per shipment: "Print Label" and "Cancel". Also added `Modules\Core\Shipping\
|
||||
Http\Controllers\DownloadShipmentLabelController` (short-lived signed URL, same auth model as
|
||||
Lunar's own vendor order-PDF download) — the only other place that called
|
||||
`CarrierFulfillmentInterface::printLabel()` (`ManagePickupManifests`' bulk "Print" action)
|
||||
discarded the returned bytes entirely; this is the first place in the codebase that actually
|
||||
delivers a label to staff. Hit and fixed two bugs while wiring this up: a `TextEntry` with a blank
|
||||
`state('')` skips rendering its `suffixActions()` entirely (Filament's own empty-state branch
|
||||
returns before reaching the actions markup), so the label-download entry needed a real,
|
||||
non-blank value; and the label-download route, registered via `loadRoutesFrom()` with no
|
||||
middleware group, had `SubstituteBindings` never run, so a type-hinted `Shipment $shipment`
|
||||
parameter silently resolved to an empty, non-existent model instead of 404ing — fixed by taking a
|
||||
plain `int $shipment` and looking the record up directly in the controller.
|
||||
- `Modules\Core\Shipping\Enums\TrackingStatus::Failed` — previously unused — is now wired to the
|
||||
new `delivery_failed` status via `Modules\Core\Order\Listeners\
|
||||
MarkDeliveryFailedOnCarrierCheckpoint`, from which staff can retry dispatch or convert to a
|
||||
return.
|
||||
- Fixed a separate, unrelated bug hit while testing the above: `Lunar\Shipping\Models\
|
||||
ShippingMethod::macro('isStorePickup', ...)` silently never registered — `Lunar\Base\Traits\
|
||||
HasModelExtending::__callStatic()` (used by every `Lunar\Base\BaseModel` subclass that doesn't
|
||||
declare its own `macro()`, `ShippingMethod` included) intercepts *every* unmatched static call
|
||||
and dispatches it as an instance call instead of forwarding to `Macroable`, so `hasMacro()` always
|
||||
returned `false` and every order was silently treated as carrier-fulfilled — including store-pickup
|
||||
ones. `Order::isStorePickupOrder()` (the only caller) now reads `ShippingMethod.data
|
||||
['fulfillment_type']` directly instead of going through the broken macro.
|
||||
- `CartResource::getEloquentQuery()` no longer filters to carts with a known `user_id`/
|
||||
`customer_id` — every cart is now listed, guest carts included. Reverses an earlier deliberate
|
||||
exclusion (an anonymous cart has nothing a staff member could click into — no name, no email),
|
||||
which held for that specific concern but not for the resource's other real use: seeing how many
|
||||
carts are ongoing/abandoned right now. Most real storefront traffic never reaches an identified
|
||||
user/customer, so excluding it silently undercounted exactly what `CartLifecycleService` exists
|
||||
to report on. A guest row's Customer/User columns just render "—" (no link) rather than the row
|
||||
being hidden.
|
||||
- `CartLifecycleService::abandonedCarts()` now requires `whereHas('lines')` — an empty cart
|
||||
(created but nothing ever added, e.g. a bot, or a session that never shopped) is no longer
|
||||
counted as "abandoned." There's nothing to recover, so it was a false positive: 9 of 16 carts in
|
||||
the "Abandoned Cart" tab during testing were empty. Removed the now-redundant post-hoc
|
||||
`lines->isEmpty()` skip (and its `with('lines')` eager load) from `DetectAbandonedCarts`, since
|
||||
the query itself excludes them now.
|
||||
- `Modules\Core\Shipping\Models\Manifest` — a real record of "a manifest was issued", replacing the
|
||||
loose `shipments.manifest_reference` string. ACS's own `ACS_Issue_Pickup_List` call returns
|
||||
nothing beyond a `PickupList_No`, so there was previously no way to see which shipments were on a
|
||||
given manifest, or when it was issued, once the moment passed — only per-shipment breadcrumbs.
|
||||
`shipments.manifest_id` (FK, replacing `manifest_reference`) now links each shipment to the
|
||||
`Manifest` row `AcsFulfillmentService::issueManifest()` creates; `ManifestResult::success()`
|
||||
carries the created `Manifest` instead of a bare reference string. A one-time data migration
|
||||
backfills a `Manifest` row per distinct existing `(carrier, manifest_reference)` pair, using the
|
||||
earliest `label_printed_at` (or `updated_at`) among that group as a best-effort `issued_at`, since
|
||||
the real issue time was never recorded anywhere.
|
||||
- Split the standalone `Modules\Core\Shipping\Filament\Pages\ManagePickupManifests` page into two
|
||||
real Filament resources — a bare `Page` has no access to Filament's resource-level pill-tab UI
|
||||
(`HasTabs` is scoped to `ListRecords`), which carrier-by-carrier separation needed:
|
||||
- `Modules\Core\Shipping\Filament\Resources\ShipmentResource` ("Pending Vouchers") — shipments not
|
||||
yet on an issued manifest, one tab per carrier that implements `SupportsManifestBatching` (ACS
|
||||
today; Box Now has no manifest concept at all — courier pickup is booked at shipment-creation
|
||||
time — so it gets no tab). Adding a future carrier with its own manifest endpoints (e.g.
|
||||
Speedex) needs zero UI changes here — tabs are derived from `Shipping::getSupportedDrivers()`,
|
||||
not hardcoded.
|
||||
- `Modules\Core\Shipping\Filament\Resources\ManifestResource` ("Issued Manifests") — lists issued
|
||||
`Manifest` rows (also tabbed by carrier), with a view page and a `ShipmentsRelationManager`
|
||||
showing which shipments a manifest included, each individually reprintable.
|
||||
- Both bulk actions ("Print selected", "Issue Manifest") now catch `Throwable` around the actual
|
||||
carrier API call and surface a Filament notification instead of an unhandled 500 — previously
|
||||
neither had any error handling at all, so an `AcsApiException` (routine against a voucher/pickup
|
||||
date the carrier no longer recognizes) crashed the whole page.
|
||||
- Fixed a bug introduced while building this: `ViewManifest` initially overrode
|
||||
`getRelationManagers()` directly instead of registering `ShipmentsRelationManager` via
|
||||
`ManifestResource::getRelations()` (the actual wiring point —
|
||||
`HasRelationManagers::getAllRelationManagers()` reads from `Resource::getRelations()`, not a
|
||||
page-level override). The override bypassed the trait's own record-check/caching logic and
|
||||
broke the relation manager's Livewire component mount, surfacing as a CSRF-token 419 redirect
|
||||
loop specifically on `/boboko/manifests/{id}`.
|
||||
- "Create Shipment"'s ACS branch gained a "Number of packages" field (`ShipmentRequest::
|
||||
$packageCount`, already plumbed through to ACS's `Item_Quantity`/`persistMultipartVouchers()` but
|
||||
never exposed in the form) — more than 1 issues a main voucher plus a multi-part sub-voucher per
|
||||
extra package, each its own `Shipment` row sharing the same total weight. The existing weight
|
||||
field was relabeled "Total weight (kg)" to make explicit that ACS bills by one total shipment
|
||||
weight, not per package.
|
||||
|
||||
## [0.16.3] - 2026-09-10
|
||||
|
||||
### Fixed
|
||||
- Stripe `createAndConfirm()` built its `PaymentIntent` params with
|
||||
`'automatic_payment_methods' => isset($data['payment_method']) ? null : ['enabled' => true]`. The
|
||||
Stripe PHP SDK does not omit `null`-valued params from `create()` — it serializes them to an empty
|
||||
string (`ApiRequestor::_encodeObjects()` → `Util::utf8(null)`), and Stripe's API rejects an empty
|
||||
`automatic_payment_methods`. Every Stripe charge failed before it started whenever a
|
||||
`payment_method` was supplied (i.e. every real charge in this flow). Fixed by building `$params`
|
||||
conditionally so the key is either omitted entirely or set to `['enabled' => true]`, never `null`.
|
||||
- `Modules\Core\Payment\Filament\Resources\PaymentMethodResource`'s "Driver status" column only
|
||||
flagged a payment method whose driver *class* no longer resolves (`driver_missing_at`) — it gave
|
||||
no indication when a driver resolves fine but fails `Configurable::isConfigured()` (e.g. Stripe
|
||||
enabled in the DB with no `services.stripe.key` set), which `CheckoutService::getPaymentMethods()`
|
||||
filters out identically. An admin had no way to tell "this method is silently absent at checkout
|
||||
because of missing config" from "everything's fine" at a glance. The same icon column now also
|
||||
reflects `isConfigured()`, with a tooltip distinguishing "driver not found" from "missing required
|
||||
configuration" from "fully configured."
|
||||
- `Modules\Core\Payment\Pipelines\Cart\ApplyCashOnDeliveryFee` (now `ApplyPaymentMethodFee`) had two
|
||||
stacked bugs that together meant a configured payment-method fee (e.g. €5 on Cash on Delivery)
|
||||
never actually reached the cart total:
|
||||
- `PaymentMethod::where(...)->value('data->fee')` silently returned `null` on Postgres — Laravel's
|
||||
query builder does not translate the `->` JSON-path column-selector syntax in `value()`/`pluck()`
|
||||
the way it does inside `where()` clauses, so this resolved to a discarded
|
||||
`stdClass::$data->fee` property access instead of the actual fee. Fixed by loading the model and
|
||||
reading the cast `->data['fee']` attribute instead.
|
||||
- Even with the fee correctly read, adding it directly to `$cart->shippingTotal` didn't survive:
|
||||
`Lunar\Pipelines\Cart\CalculateTax`, which runs later in the same cart-calculation pipeline,
|
||||
unconditionally recomputes `shippingTotal` (and shipping tax) from `$cart->shippingBreakdown`'s
|
||||
item sum — silently discarding anything set only on the plain property. Fixed by adding the fee
|
||||
as its own `Lunar\Base\ValueObjects\Cart\ShippingBreakdownItem` on `shippingBreakdown` instead,
|
||||
so it survives `CalculateTax`'s recompute and is correctly included in shipping tax too.
|
||||
- Also generalized while fixing: the pipeline was hardcoded to the literal type string
|
||||
`cash-on-delivery`. Renamed to `ApplyPaymentMethodFee` and changed it to look up whichever
|
||||
`PaymentMethod` row matches `Cart::meta['payment_method']` and apply its own `data.fee` if
|
||||
present — works for any payment method configured with a fee, not just one specific slug.
|
||||
- `Modules\Core\Checkout\Services\CheckoutService::selectPaymentMethod()` called `$cart->calculate()`
|
||||
after saving the new payment method, but `Lunar\Models\Cart::calculate()` no-ops if the cart
|
||||
instance was already calculated earlier in the same request (`Cart::isCalculated()`) —
|
||||
`Lunar\Managers\CartSessionManager` memoizes one `Cart` instance per request, so this was true on
|
||||
every request where the checkout page's initial render had already calculated the cart. The
|
||||
result: after switching payment methods, the just-saved `meta['payment_method']` change was
|
||||
persisted, but the cart's totals silently kept reflecting whichever method was calculated *first*
|
||||
in the request — a shopper switching from Cash in Hand to Cash on Delivery would keep seeing Cash
|
||||
in Hand's total, with no COD fee applied, until something else forced a fresh calculation. Fixed
|
||||
by calling `$cart->recalculate()` instead, which forces the pipeline to re-run.
|
||||
|
||||
## [0.16.2] - 2026-09-09
|
||||
|
||||
### Fixed
|
||||
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
"name": "boboko/core",
|
||||
"description": "Core module — authentication and shared panel behaviour",
|
||||
"type": "library",
|
||||
"version": "0.16.2",
|
||||
"version": "0.17.3",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Modules\\Core\\": "src/"
|
||||
@@ -18,7 +18,7 @@
|
||||
"lunarphp/search": "*",
|
||||
"lunarphp/meilisearch": "*",
|
||||
"spatie/laravel-translation-loader": "^2.8",
|
||||
"lunarphp/stripe": "^1.5"
|
||||
"stripe/stripe-php": "^16.6"
|
||||
},
|
||||
"require-dev": {
|
||||
"fakerphp/faker": "^1.23",
|
||||
|
||||
@@ -30,6 +30,39 @@ return [
|
||||
|
||||
'cart' => [
|
||||
'abandoned_after' => '1 hour',
|
||||
|
||||
/*
|
||||
|----------------------------------------------------------------------
|
||||
| Unrecoverable Cap
|
||||
|----------------------------------------------------------------------
|
||||
|
|
||||
| Beyond this age, a stale cart stops being treated as an active
|
||||
| "Abandoned Cart"/"Abandoned Checkout" (Modules\Core\Cart\Services\
|
||||
| CartLifecycleService) — too old to be a realistic recovery target
|
||||
| (pricing/stock/tax likely stale by then). This is about the
|
||||
| abandoned-cart pipeline only, not data retention — no rows are
|
||||
| deleted or pruned based on this value.
|
||||
|
|
||||
*/
|
||||
|
||||
'unrecoverable_after' => '90 days',
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Order Return Window
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| How many days after a carrier order is delivered (Order::fulfillment_status
|
||||
| becomes 'return_window_open') before Modules\Core\Order\Commands\
|
||||
| CloseExpiredReturnWindows auto-completes it, if no return was requested.
|
||||
| Store-pickup orders have no return-window step and are unaffected by
|
||||
| this value (see Modules\Core\Order\Listeners\CompleteOrderOnPickedUp).
|
||||
|
|
||||
*/
|
||||
|
||||
'order' => [
|
||||
'return_window_days' => 14,
|
||||
],
|
||||
|
||||
];
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
use Modules\Core\Payment\Pipelines\Cart\ApplyCashOnDeliveryFee;
|
||||
use Modules\Core\Payment\Pipelines\Cart\ApplyPaymentMethodFee;
|
||||
|
||||
return [
|
||||
/*
|
||||
@@ -9,8 +9,8 @@ return [
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Appended to config('lunar.cart.pipelines.cart') after ApplyShipping so
|
||||
| the cash-on-delivery fee is added to the shipping total before the
|
||||
| final Calculate step sums everything up.
|
||||
| the selected payment method's own fee (if any) is added to the
|
||||
| shipping total before the final Calculate step sums everything up.
|
||||
|
|
||||
| This is the one thing left in this file — everything about WHICH
|
||||
| payment methods exist (driver mapping, capture_mode, statuses) moved
|
||||
@@ -23,6 +23,6 @@ return [
|
||||
|
|
||||
*/
|
||||
'cart_pipeline' => [
|
||||
ApplyCashOnDeliveryFee::class,
|
||||
ApplyPaymentMethodFee::class,
|
||||
],
|
||||
];
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Lunar\Base\Migration;
|
||||
|
||||
/**
|
||||
* First-party copy of lunarphp/stripe's own create_stripe_payment_intents_table
|
||||
* migration (package removed in favour of depending on stripe/stripe-php
|
||||
* directly — see Modules\Core\Payment\Support\StripeManager and
|
||||
* Modules\Core\Payment\Models\StripePaymentIntent, which replace the
|
||||
* package's own classes over this same table). Timestamped to run just
|
||||
* before this app's own add_context_to_stripe_payment_intents migration,
|
||||
* which already alters this table.
|
||||
*
|
||||
* Guarded with hasTable(): on any environment that already ran
|
||||
* lunarphp/stripe's own copy of this migration before the package was
|
||||
* removed, the table already exists — this migration is only the one that
|
||||
* actually creates it on a fresh install/database from now on.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
if (Schema::hasTable($this->prefix.'stripe_payment_intents')) {
|
||||
return;
|
||||
}
|
||||
|
||||
Schema::create($this->prefix.'stripe_payment_intents', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('cart_id')->constrained($this->prefix.'carts');
|
||||
$table->foreignId('order_id')->nullable()->constrained($this->prefix.'orders');
|
||||
$table->string('intent_id')->index();
|
||||
$table->string('status')->nullable();
|
||||
$table->string('event_id')->index()->nullable();
|
||||
$table->timestamp('processing_at')->nullable();
|
||||
$table->timestamp('processed_at')->nullable();
|
||||
$table->timestamps();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists($this->prefix.'stripe_payment_intents');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Splits Lunar's single flat `status` column into three independently
|
||||
* tracked axes — payment, fulfillment, return — so a payment refund and a
|
||||
* fulfillment dispatch stop racing to write the same field, and each axis
|
||||
* can be filtered/queried directly instead of overloading one string for
|
||||
* three unrelated concerns. See Modules\Core\Order\Enums\OrderPaymentStatus/
|
||||
* OrderFulfillmentStatus/OrderReturnStatus for the value vocabularies, and
|
||||
* Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus and friends for
|
||||
* where these columns actually get written. `status` itself is left in
|
||||
* place, unchanged — Lunar core still reads/writes it in places this
|
||||
* package doesn't own — but nothing in this package's business logic keys
|
||||
* off it anymore after this migration's consumers land.
|
||||
*
|
||||
* lunar_customers already has a direct precedent for a boboko-core
|
||||
* migration altering a Lunar-owned table (see
|
||||
* 2026_07_02_000002_drop_otp_from_lunar_customers_table.php) — this is not
|
||||
* a new pattern for this codebase, just the first time it's applied to
|
||||
* lunar_orders.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->string('payment_status')->default('awaiting_payment')->after('status')->index();
|
||||
$table->string('fulfillment_status')->default('unfulfilled')->after('payment_status')->index();
|
||||
$table->string('return_status')->default('none')->after('fulfillment_status')->index();
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->dropColumn(['payment_status', 'fulfillment_status', 'return_status']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Append-only audit trail for Order's three status axes (see
|
||||
* 2026_09_11_000001_add_status_axes_to_orders_table.php) — the thing
|
||||
* `Lunar\Models\Order::getDefaultLogExcept()` explicitly denies (`status`
|
||||
* is excluded from Lunar's own Spatie activity log), so this is a
|
||||
* from-scratch mechanism, not a gap in an existing one.
|
||||
*
|
||||
* No `updated_at` — a row is never edited after it's written, only ever
|
||||
* inserted. `event_class` is the FQCN of whatever business event/action
|
||||
* caused the write (e.g. Modules\Core\Order\Events\OrderDispatched, or a
|
||||
* plain string like 'Modules\Core\Shipping\Extensions\OrderViewExtension::
|
||||
* markDispatchedAction' for a manual Filament action that has no backing
|
||||
* event class of its own) — see Modules\Core\Order\Services\
|
||||
* OrderStatusTransitionRecorder.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('order_status_transitions', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->foreignId('order_id')->constrained('lunar_orders')->cascadeOnDelete();
|
||||
$table->string('axis');
|
||||
$table->string('from_status')->nullable();
|
||||
$table->string('to_status');
|
||||
$table->string('event_class');
|
||||
$table->timestamp('created_at')->useCurrent();
|
||||
$table->index(['order_id', 'axis']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('order_status_transitions');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Order\Enums\PaymentStatus;
|
||||
use Modules\Core\Order\Support\OrderStatus;
|
||||
|
||||
/**
|
||||
* Maps every existing order's flat `status` (as it stood before
|
||||
* 2026_09_11_000001_add_status_axes_to_orders_table.php) onto the new
|
||||
* payment_status/fulfillment_status/return_status columns. A separate
|
||||
* migration from the schema change so the schema migration stays simply
|
||||
* reversible via down(), and this data pass can be independently re-run.
|
||||
*
|
||||
* The flat status never captured refunds at all (no 'refunded' value was
|
||||
* ever added to config('lunar.orders.statuses')), so the table-driven
|
||||
* mapping below is corrected per-order by re-deriving
|
||||
* Modules\Core\Order\Support\OrderStatus::payment() — the existing,
|
||||
* unchanged derived-enum logic — and overriding payment_status to
|
||||
* refunded/partially_refunded wherever it disagrees with the flat-status
|
||||
* mapping. This is the one place the "keep the old derived enums" design
|
||||
* decision earns its keep: refund-fraction math isn't reimplemented here,
|
||||
* just reused.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private const MAP = [
|
||||
'awaiting-payment' => ['payment_status' => 'awaiting_payment', 'fulfillment_status' => 'unfulfilled'],
|
||||
'payment-offline' => ['payment_status' => 'awaiting_payment', 'fulfillment_status' => 'unfulfilled'],
|
||||
'payment-received' => ['payment_status' => 'paid', 'fulfillment_status' => 'unfulfilled'],
|
||||
'ready-for-dispatch' => ['payment_status' => 'paid', 'fulfillment_status' => 'ready'],
|
||||
'ready-for-pickup' => ['payment_status' => 'paid', 'fulfillment_status' => 'ready'],
|
||||
'dispatched' => ['payment_status' => 'paid', 'fulfillment_status' => 'in_transit'],
|
||||
'completed' => ['payment_status' => 'paid', 'fulfillment_status' => 'completed'],
|
||||
];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
Order::query()->with('transactions')->chunkById(200, function ($orders) {
|
||||
foreach ($orders as $order) {
|
||||
$mapped = self::MAP[$order->status] ?? null;
|
||||
|
||||
if ($mapped === null) {
|
||||
Log::warning('Order status axis backfill: unmapped status, leaving column defaults', [
|
||||
'order_id' => $order->id,
|
||||
'status' => $order->status,
|
||||
]);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$paymentStatus = $mapped['payment_status'];
|
||||
|
||||
$derived = OrderStatus::payment($order);
|
||||
|
||||
if ($derived === PaymentStatus::Refunded) {
|
||||
$paymentStatus = 'refunded';
|
||||
} elseif ($derived === PaymentStatus::PartialRefund) {
|
||||
$paymentStatus = 'partially_refunded';
|
||||
}
|
||||
|
||||
DB::table('lunar_orders')->where('id', $order->id)->update([
|
||||
'payment_status' => $paymentStatus,
|
||||
'fulfillment_status' => $mapped['fulfillment_status'],
|
||||
'return_status' => 'none',
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// Column defaults (set in the schema migration) are the correct
|
||||
// "undo" — no need to reverse-map back to the flat status, since
|
||||
// `status` itself was never touched by this migration.
|
||||
}
|
||||
};
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* captured_status/authorized_status/refunded_status let a merchant pick
|
||||
* which per-method Order::status label a payment outcome resulted in — a
|
||||
* mechanism that only made sense while Order.status was the single field
|
||||
* carrying that meaning. Modules\Core\Order\Listeners\
|
||||
* ApplyResolvedPaymentStatus now writes a fixed 3-value payment_status
|
||||
* column instead (see 2026_09_11_000001_add_status_axes_to_orders_table.php);
|
||||
* there is no longer any per-method flexibility to preserve — "paid" is
|
||||
* "paid" regardless of which method captured it. Dropped rather than left
|
||||
* vestigial: keeping them visible in the admin would let a merchant
|
||||
* configure something that silently does nothing.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('payment_methods', function (Blueprint $table) {
|
||||
$table->dropColumn(['captured_status', 'authorized_status', 'refunded_status']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('payment_methods', function (Blueprint $table) {
|
||||
$table->string('captured_status')->nullable();
|
||||
$table->string('authorized_status')->nullable();
|
||||
$table->string('refunded_status')->nullable();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Order::paid/paid_at — entirely independent of the `status` column (see
|
||||
* Modules\Core\Order\Services\OrderStatusFlow's own docblock for why
|
||||
* payment timing, especially for cash-on-delivery, cannot be modeled as a
|
||||
* status-sequence step). `paid` is the fast-filter boolean; `paid_at` is
|
||||
* when it actually happened.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->boolean('paid')->default(false)->after('status')->index();
|
||||
$table->timestamp('paid_at')->nullable()->after('paid');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->dropColumn(['paid', 'paid_at']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Order\Enums\PaymentStatus;
|
||||
use Modules\Core\Order\Support\OrderStatus;
|
||||
|
||||
/**
|
||||
* Collapses the 3-axis (payment_status/fulfillment_status/return_status)
|
||||
* model this session briefly built — abandoned before shipping — back
|
||||
* onto a single `status` column plus the new independent `paid`/`paid_at`
|
||||
* fields. Must run after 2026_09_12_000001 (adds paid/paid_at) and before
|
||||
* 2026_09_12_000003 (drops the axis columns this migration still reads).
|
||||
*
|
||||
* Priority rule: axis data where it's genuinely non-default (this order
|
||||
* was really moved through the axis system during this session's manual
|
||||
* testing); the legacy `status` column (which may still hold pre-session
|
||||
* hyphenated values) as fallback everywhere else.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
private const LEGACY_MAP = [
|
||||
'awaiting-payment' => 'awaiting_payment',
|
||||
'payment-offline' => 'awaiting_payment',
|
||||
'payment-received' => 'processing',
|
||||
'ready-for-dispatch' => 'ready_for_dispatch',
|
||||
'ready-for-pickup' => 'ready_for_pickup',
|
||||
'dispatched' => 'dispatched',
|
||||
'completed' => 'completed',
|
||||
];
|
||||
|
||||
/**
|
||||
* Axis fulfillment_status -> new single status, given branch. Axis
|
||||
* 'delivered' folds into 'return_window_open' (same combined-value
|
||||
* decision the going-forward design makes). Axis payment_status is
|
||||
* used only to decide whether a fully-unfulfilled order should read
|
||||
* as 'awaiting_payment' or 'processing'.
|
||||
*/
|
||||
private function mapFromAxes(string $payment, string $fulfillment, string $return, bool $isPickup): ?string
|
||||
{
|
||||
if ($return === 'returned') {
|
||||
return 'returned';
|
||||
}
|
||||
if ($return === 'requested') {
|
||||
return 'return_requested';
|
||||
}
|
||||
|
||||
return match ($fulfillment) {
|
||||
'unfulfilled' => $payment === 'paid' ? 'processing' : 'awaiting_payment',
|
||||
'processing' => 'processing',
|
||||
'ready' => $isPickup ? 'ready_for_pickup' : 'ready_for_dispatch',
|
||||
'in_transit' => 'dispatched',
|
||||
'delivered', 'return_window_open' => 'return_window_open',
|
||||
'picked_up' => 'picked_up',
|
||||
'completed' => 'completed',
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
Order::query()->with('transactions')->chunkById(200, function ($orders) {
|
||||
foreach ($orders as $order) {
|
||||
$isPickup = $order->isStorePickupOrder();
|
||||
|
||||
$axisIsDefault = $order->payment_status === 'awaiting_payment'
|
||||
&& $order->fulfillment_status === 'unfulfilled'
|
||||
&& $order->return_status === 'none';
|
||||
|
||||
$status = $axisIsDefault
|
||||
? (self::LEGACY_MAP[$order->status] ?? null)
|
||||
: $this->mapFromAxes($order->payment_status, $order->fulfillment_status, $order->return_status, $isPickup);
|
||||
|
||||
if ($status === null) {
|
||||
Log::warning('Single-status backfill: unmapped order, defaulting to awaiting_payment', [
|
||||
'order_id' => $order->id,
|
||||
'status' => $order->status,
|
||||
'payment_status' => $order->payment_status,
|
||||
'fulfillment_status' => $order->fulfillment_status,
|
||||
'return_status' => $order->return_status,
|
||||
]);
|
||||
$status = 'awaiting_payment';
|
||||
}
|
||||
|
||||
$derived = OrderStatus::payment($order);
|
||||
$paid = $order->payment_status === 'paid'
|
||||
|| in_array($derived, [PaymentStatus::Captured, PaymentStatus::Refunded, PaymentStatus::PartialRefund], true);
|
||||
|
||||
// A refund implies the order concluded via a return —
|
||||
// even one backfilled to an early status (e.g. an order
|
||||
// refunded before fulfillment ever started) is corrected
|
||||
// to refunded/partially_refunded here, not left stuck
|
||||
// pre-fulfillment with no sign a refund ever happened.
|
||||
if ($derived === PaymentStatus::Refunded) {
|
||||
$status = 'refunded';
|
||||
} elseif ($derived === PaymentStatus::PartialRefund) {
|
||||
$status = 'partially_refunded';
|
||||
}
|
||||
|
||||
DB::table('lunar_orders')->where('id', $order->id)->update([
|
||||
'status' => $status,
|
||||
'paid' => $paid,
|
||||
'paid_at' => $paid ? ($order->placed_at ?? now()) : null,
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// No reverse mapping — column defaults (post-rollback of the
|
||||
// schema migrations) are the correct "undo".
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Reverses 2026_09_11_000001_add_status_axes_to_orders_table.php — the
|
||||
* 3-axis model was abandoned before shipping in favor of a single
|
||||
* `status` column plus independent `paid`/`paid_at` (see
|
||||
* 2026_09_12_000001/000002). Must run after 2026_09_12_000002, which
|
||||
* still reads these columns for the backfill.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->dropColumn(['payment_status', 'fulfillment_status', 'return_status']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
// Mirrors 2026_09_11_000001's own down() — restores columns
|
||||
// empty/defaulted, does not attempt to resurrect real per-order
|
||||
// values.
|
||||
Schema::table('lunar_orders', function (Blueprint $table) {
|
||||
$table->string('payment_status')->default('awaiting_payment')->after('paid_at')->index();
|
||||
$table->string('fulfillment_status')->default('unfulfilled')->after('payment_status')->index();
|
||||
$table->string('return_status')->default('none')->after('fulfillment_status')->index();
|
||||
});
|
||||
}
|
||||
};
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* There is only one status column left to audit (plus the synthetic
|
||||
* 'paid' entry — see Modules\Core\Order\Listeners\RecordStatusTransition),
|
||||
* so the `axis` column this table was created with
|
||||
* (2026_09_11_000002_create_order_status_transitions_table.php) no longer
|
||||
* means anything.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('order_status_transitions', function (Blueprint $table) {
|
||||
$table->dropIndex(['order_id', 'axis']);
|
||||
$table->dropColumn('axis');
|
||||
$table->index('order_id');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('order_status_transitions', function (Blueprint $table) {
|
||||
$table->dropIndex(['order_id']);
|
||||
$table->string('axis')->default('status')->after('order_id');
|
||||
$table->index(['order_id', 'axis']);
|
||||
});
|
||||
}
|
||||
};
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* The seeded 'cash-on-delivery' PaymentMethod row
|
||||
* (Modules\Core\Command\InstallLunarCommand::seedPaymentMethods()) was
|
||||
* wired to driver => 'offline' — the same immediate-capture driver as
|
||||
* cash-in-hand. That's the bug that made COD "pay immediately" instead of
|
||||
* waiting for staff to confirm cash was actually received. Repoints
|
||||
* already-seeded environments to the new dedicated
|
||||
* Modules\Core\Payment\Drivers\CashOnDeliveryPaymentDriver; the seeder
|
||||
* itself is fixed separately for fresh installs.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('payment_methods')->where('type', 'cash-on-delivery')->update(['driver' => 'cash-on-delivery']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('payment_methods')->where('type', 'cash-on-delivery')->update(['driver' => 'offline']);
|
||||
}
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* 'return_window_open' is renamed to 'delivered' — same status value,
|
||||
* same meaning (the parcel arrived AND the return window is now open,
|
||||
* still one combined moment — see Modules\Core\Order\Listeners\
|
||||
* AdvanceFulfillmentOnDelivered), just a name a merchant expects to read
|
||||
* on the order page rather than an internal mechanic. Also renames it in
|
||||
* order_status_transitions' audit rows so the history stays consistent
|
||||
* with `status` going forward.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('lunar_orders')->where('status', 'return_window_open')->update(['status' => 'delivered']);
|
||||
DB::table('order_status_transitions')->where('from_status', 'return_window_open')->update(['from_status' => 'delivered']);
|
||||
DB::table('order_status_transitions')->where('to_status', 'return_window_open')->update(['to_status' => 'delivered']);
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
DB::table('lunar_orders')->where('status', 'delivered')->update(['status' => 'return_window_open']);
|
||||
DB::table('order_status_transitions')->where('from_status', 'delivered')->update(['from_status' => 'return_window_open']);
|
||||
DB::table('order_status_transitions')->where('to_status', 'delivered')->update(['to_status' => 'return_window_open']);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* A real record of "a manifest was issued", not just a loose
|
||||
* manifest_reference string stamped onto each Shipment row — ACS's own
|
||||
* ACS_Issue_Pickup_List call returns nothing beyond a PickupList_No (see
|
||||
* Modules\Core\Shipping\Carriers\Acs\AcsFulfillmentService::issueManifest()),
|
||||
* so this table is entirely our own bookkeeping: when the manifest was
|
||||
* issued and how many shipments it included, not something re-derivable
|
||||
* from the carrier later. `shipment_count` is denormalized (also
|
||||
* countable via shipments()->count()) purely so the manifests list can
|
||||
* render without an extra query per row.
|
||||
*
|
||||
* carrier-agnostic by design — see Modules\Core\Shipping\Contracts\
|
||||
* SupportsManifestBatching, the same contract any future carrier
|
||||
* (Speedex, etc.) implements to get manifest batching at all; this table
|
||||
* has no ACS-specific columns.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::create('manifests', function (Blueprint $table) {
|
||||
$table->id();
|
||||
$table->string('carrier');
|
||||
$table->string('reference');
|
||||
$table->unsignedInteger('shipment_count')->default(0);
|
||||
$table->timestamp('issued_at');
|
||||
$table->timestamps();
|
||||
|
||||
$table->unique(['carrier', 'reference']);
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::dropIfExists('manifests');
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
/**
|
||||
* Replaces the loose manifest_reference string with a real manifests
|
||||
* relation — see 2026_09_13_000002_create_manifests_table.php. Backfills
|
||||
* one Manifest row per distinct (carrier, manifest_reference) pair
|
||||
* already present in shipments, using the earliest label_printed_at (or
|
||||
* updated_at as a fallback) among that group as a best-effort issued_at,
|
||||
* since the exact original issue time was never recorded anywhere.
|
||||
*/
|
||||
return new class extends Migration
|
||||
{
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('shipments', function (Blueprint $table) {
|
||||
$table->foreignId('manifest_id')->nullable()->after('manifest_reference')->constrained()->nullOnDelete();
|
||||
});
|
||||
|
||||
$groups = DB::table('shipments')
|
||||
->select('carrier', 'manifest_reference')
|
||||
->whereNotNull('manifest_reference')
|
||||
->distinct()
|
||||
->get();
|
||||
|
||||
foreach ($groups as $group) {
|
||||
$shipments = DB::table('shipments')
|
||||
->where('carrier', $group->carrier)
|
||||
->where('manifest_reference', $group->manifest_reference)
|
||||
->get();
|
||||
|
||||
$issuedAt = $shipments->pluck('label_printed_at')->filter()->min()
|
||||
?? $shipments->pluck('updated_at')->min();
|
||||
|
||||
$manifestId = DB::table('manifests')->insertGetId([
|
||||
'carrier' => $group->carrier,
|
||||
'reference' => $group->manifest_reference,
|
||||
'shipment_count' => $shipments->count(),
|
||||
'issued_at' => $issuedAt,
|
||||
'created_at' => $issuedAt,
|
||||
'updated_at' => $issuedAt,
|
||||
]);
|
||||
|
||||
DB::table('shipments')
|
||||
->where('carrier', $group->carrier)
|
||||
->where('manifest_reference', $group->manifest_reference)
|
||||
->update(['manifest_id' => $manifestId]);
|
||||
}
|
||||
|
||||
Schema::table('shipments', function (Blueprint $table) {
|
||||
$table->dropColumn('manifest_reference');
|
||||
});
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('shipments', function (Blueprint $table) {
|
||||
$table->string('manifest_reference')->nullable()->after('parent_reference');
|
||||
});
|
||||
|
||||
DB::table('shipments')
|
||||
->whereNotNull('manifest_id')
|
||||
->orderBy('id')
|
||||
->each(function ($shipment) {
|
||||
$manifest = DB::table('manifests')->find($shipment->manifest_id);
|
||||
|
||||
if ($manifest) {
|
||||
DB::table('shipments')->where('id', $shipment->id)->update([
|
||||
'manifest_reference' => $manifest->reference,
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
Schema::table('shipments', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('manifest_id');
|
||||
});
|
||||
}
|
||||
};
|
||||
+48
-40
@@ -1,28 +1,34 @@
|
||||
# Cart Admin Visibility
|
||||
|
||||
`Modules\Core\Cart\Filament\Resources\CartResource` gives staff read-only visibility into
|
||||
customer/user carts in the Filament admin panel. Lunar itself ships no cart admin view at
|
||||
all — no Filament resource for `Cart`/`CartLine` exists anywhere in `lunarphp/lunar` or
|
||||
`lunarphp/core` — this is a from-scratch addition, not an extension of something Lunar
|
||||
half-built. See `docs/lunar.md`'s "Cart and Checkout" section for the underlying Lunar cart
|
||||
mechanics this resource reads from.
|
||||
every cart in the Filament admin panel, guest carts included. Lunar itself ships no cart
|
||||
admin view at all — no Filament resource for `Cart`/`CartLine` exists anywhere in
|
||||
`lunarphp/lunar` or `lunarphp/core` — this is a from-scratch addition, not an extension of
|
||||
something Lunar half-built. See `docs/lunar.md`'s "Cart and Checkout" section for the
|
||||
underlying Lunar cart mechanics this resource reads from.
|
||||
|
||||
---
|
||||
|
||||
## Scope: only carts with a known customer or user
|
||||
## Scope: every cart, identified or not
|
||||
|
||||
`CartResource::getEloquentQuery()` filters to `Cart::whereNotNull('user_id')->orWhereNotNull('customer_id')`
|
||||
— an anonymous guest's session cart is excluded entirely.
|
||||
`CartResource` lists every cart the four lifecycle states (below) cover, with no
|
||||
`user_id`/`customer_id` filter — an anonymous guest's session cart is included.
|
||||
|
||||
This was a deliberate call, not an oversight: an anonymous cart carries no identity a staff
|
||||
member could act on — no name, no email, nothing to follow up with — so listing every guest
|
||||
session cart would be noise, not a real admin capability. This does **not** mirror Shopify's
|
||||
admin (Shopify has no "all carts" view at all — only "Abandoned checkouts," gated on a
|
||||
shopper reaching checkout and entering contact info, a later/narrower stage than Lunar's
|
||||
`Cart`). Lunar's own `Cart` model already gets `user_id`/`customer_id` set the moment a
|
||||
shopper is authenticated (via `Lunar\Listeners\CartSessionAuthListener` on login), with no
|
||||
checkout step required — so scoping to "identifiable" here is broader than Shopify's
|
||||
equivalent, not a copy of it.
|
||||
This was a reversal of an earlier, deliberate call to exclude guest carts entirely (on the
|
||||
reasoning that an anonymous cart carries no identity a staff member could act on — no name, no
|
||||
email, nothing to follow up with — so listing every guest session cart would be noise, not a
|
||||
real admin capability). That reasoning holds for "can I click through to a Customer record,"
|
||||
but not for the resource's other real use — seeing how many carts are ongoing/abandoned right
|
||||
now regardless of who's shopping. Most real storefront traffic never reaches an identified
|
||||
user/customer, so excluding it silently undercounts exactly the thing `ListCarts`'s tabs (and
|
||||
`CartLifecycleService`, which they and `DetectAbandonedCarts` both build on) exist to report
|
||||
on. The `Customer`/`User` columns on a guest row just render "—" (Filament's `placeholder()`)
|
||||
instead of a link — nothing to click into, but the row and its contents are still visible via
|
||||
`ViewCart`.
|
||||
|
||||
This does **not** mirror Shopify's admin (Shopify has no "all carts" view at all — only
|
||||
"Abandoned checkouts," gated on a shopper reaching checkout and entering contact info, a
|
||||
later/narrower stage than Lunar's `Cart`).
|
||||
|
||||
---
|
||||
|
||||
@@ -40,28 +46,29 @@ distinct states together: no order ever started, vs. a draft order exists
|
||||
different purchase-intent signals (see "Abandoned Cart vs Abandoned Checkout" below) and
|
||||
different reachability (checkout usually captures an email even for a guest), so
|
||||
`ListCarts::getTabs()` splits them into four tabs instead of `scopeActive()`'s two-state
|
||||
split:
|
||||
split.
|
||||
|
||||
- **Ongoing** — `scopeActive()` and recent `updated_at` (within `abandonedCutoff()`). Default
|
||||
active tab on page load.
|
||||
- **Abandoned Cart** — `whereDoesntHave('orders')` and stale `updated_at`.
|
||||
- **Abandoned Checkout** — has an order with `placed_at IS NULL`, and stale `updated_at`.
|
||||
- **Completed** — has an order with `placed_at IS NOT NULL`.
|
||||
`Modules\Core\Cart\Services\CartLifecycleService` is the single source of truth for these four
|
||||
query shapes — both `ListCarts::getTabs()` (staff browsing) and `DetectAbandonedCarts`
|
||||
(abandonment-event dispatch) build on it, rather than each reimplementing the same split
|
||||
independently (which is what happened before this service existed, and is exactly the kind of
|
||||
drift that lets the admin panel and the recovery-email pipeline quietly disagree about what
|
||||
"abandoned" means):
|
||||
|
||||
```php
|
||||
// Ongoing
|
||||
$query->active()->where('updated_at', '>', CartResource::abandonedCutoff());
|
||||
- **Ongoing** (`ongoing()`) — `scopeActive()` and recent `updated_at` (within
|
||||
`abandonedCutoff()`). Default active tab on page load.
|
||||
- **Abandoned Cart** (`abandonedCarts()`) — `whereDoesntHave('orders')` and stale
|
||||
`updated_at`.
|
||||
- **Abandoned Checkout** (`abandonedCheckouts()`) — has an order with `placed_at IS NULL`,
|
||||
and stale `updated_at`.
|
||||
- **Completed** (`completed()`) — has an order with `placed_at IS NOT NULL`.
|
||||
|
||||
// Abandoned Cart
|
||||
$query->whereDoesntHave('orders')->where('updated_at', '<=', CartResource::abandonedCutoff());
|
||||
|
||||
// Abandoned Checkout
|
||||
$query->whereHas('orders', fn ($q) => $q->whereNull('placed_at'))
|
||||
->where('updated_at', '<=', CartResource::abandonedCutoff());
|
||||
|
||||
// Completed
|
||||
$query->whereHas('orders', fn ($q) => $q->whereNotNull('placed_at'));
|
||||
```
|
||||
Each method takes a `Builder` and returns it further scoped, so callers compose it onto
|
||||
whatever base query they already have (`CartResource::getEloquentQuery()` for the Filament
|
||||
tabs, a bare `Cart::query()` for the command). Deliberately query-shape-only: consent
|
||||
(`meta->recovery_consent`) and non-empty-lines filtering stay in `DetectAbandonedCarts`, not on
|
||||
the service — those gate whether a recovery *event* should fire, not what "abandoned" means to
|
||||
a staff member browsing the list.
|
||||
|
||||
There is deliberately **no "All" tab.** Every row shown is always scoped to one of the four
|
||||
states above — the list never runs an unfiltered `Cart::query()->get()` over the whole
|
||||
@@ -111,7 +118,7 @@ runs once per admin page load, not once per cart row.
|
||||
```php
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
return (string) static::getEloquentQuery()->active()->count();
|
||||
return (string) static::getEloquentQuery()->active()->where('updated_at', '<=', static::abandonedCutoff())->count();
|
||||
}
|
||||
```
|
||||
|
||||
@@ -235,9 +242,10 @@ just upper-cases the code; `Lunar\Managers\DiscountManager::validateCoupon()` (v
|
||||
via a normal Eloquent write, so there's no model-event hook to dispatch from directly.
|
||||
`Modules\Core\Cart\Commands\DetectAbandonedCarts` (registered on an hourly schedule by
|
||||
`Modules\Core\Providers\CartServiceProvider`) is the only place that moment gets detected: it
|
||||
queries the same two branches `ListCarts::getTabs()` uses (no order at all vs. draft order
|
||||
never placed) and dispatches `Modules\Core\Recovery\Events\CartAbandoned`/`CheckoutAbandoned`
|
||||
for anything currently stale.
|
||||
builds on the same `CartLifecycleService::abandonedCarts()`/`abandonedCheckouts()` queries
|
||||
`ListCarts::getTabs()` uses (no order at all vs. draft order never placed) and dispatches
|
||||
`Modules\Core\Recovery\Events\CartAbandoned`/`CheckoutAbandoned` for anything currently stale
|
||||
that also has `meta->recovery_consent = true`.
|
||||
|
||||
### Cart/Checkout have zero abandonment-related writes — by design
|
||||
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
<p>Hi,</p>
|
||||
|
||||
<p>Your order <strong>{{ $reference }}</strong> is complete. Thanks for shopping with us!</p>
|
||||
@@ -0,0 +1,3 @@
|
||||
<p>Hi,</p>
|
||||
|
||||
<p>Your order <strong>{{ $reference }}</strong> is on its way.</p>
|
||||
@@ -0,0 +1,3 @@
|
||||
<p>Hi,</p>
|
||||
|
||||
<p>Your order <strong>{{ $reference }}</strong> is ready for pickup in store.</p>
|
||||
@@ -0,0 +1,11 @@
|
||||
<p>Hi,</p>
|
||||
|
||||
<p>Thanks for your order! Your order <strong>{{ $reference }}</strong> is confirmed.</p>
|
||||
|
||||
<ul>
|
||||
@foreach ($lines as $line)
|
||||
<li>{{ $line->quantity }} × {{ $line->description }} — {{ $line->total?->formatted }}</li>
|
||||
@endforeach
|
||||
</ul>
|
||||
|
||||
<p>Total: <strong>{{ $total }}</strong></p>
|
||||
@@ -1,3 +0,0 @@
|
||||
<x-filament-panels::page>
|
||||
{{ $this->table }}
|
||||
</x-filament-panels::page>
|
||||
@@ -5,7 +5,7 @@ namespace Modules\Core\Cart\Commands;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Lunar\Models\Cart;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource;
|
||||
use Modules\Core\Cart\Services\CartLifecycleService;
|
||||
use Modules\Core\Recovery\Events\CartAbandoned;
|
||||
use Modules\Core\Recovery\Events\CheckoutAbandoned;
|
||||
|
||||
@@ -37,7 +37,14 @@ use Modules\Core\Recovery\Events\CheckoutAbandoned;
|
||||
* sends (Checkout\Services\CheckoutService::setRecoveryConsent() is where
|
||||
* that consent is actually recorded), and a non-consenting cart's
|
||||
* abandonment must never be dispatched at all, not merely filtered later
|
||||
* at send time — see docs referenced above for the legal reasoning.
|
||||
* at send time — see docs referenced above for the legal reasoning. This
|
||||
* consent filter stays here rather than on Modules\Core\Cart\Services\
|
||||
* CartLifecycleService, whose two "abandoned" queries this command builds
|
||||
* on — dispatch eligibility is this command's own concern, not part of
|
||||
* what "abandoned" means to a staff member browsing the admin panel. (The
|
||||
* non-empty-lines requirement, by contrast, IS part of what "abandoned"
|
||||
* means either way, so it lives on CartLifecycleService::abandonedCarts()
|
||||
* itself, not here.)
|
||||
*/
|
||||
class DetectAbandonedCarts extends Command
|
||||
{
|
||||
@@ -45,33 +52,22 @@ class DetectAbandonedCarts extends Command
|
||||
|
||||
protected $description = 'Dispatch CartAbandoned/CheckoutAbandoned for carts that just crossed the abandonment threshold.';
|
||||
|
||||
public function handle(): void
|
||||
public function handle(CartLifecycleService $lifecycle): void
|
||||
{
|
||||
$cutoff = CartResource::abandonedCutoff();
|
||||
|
||||
$cartsAbandoned = 0;
|
||||
$checkoutsAbandoned = 0;
|
||||
|
||||
Cart::query()
|
||||
->whereDoesntHave('orders')
|
||||
->where('updated_at', '<=', $cutoff)
|
||||
$lifecycle->abandonedCarts(Cart::query())
|
||||
->where('meta->recovery_consent', true)
|
||||
->with('lines')
|
||||
->chunkById(200, function ($carts) use (&$cartsAbandoned) {
|
||||
foreach ($carts as $cart) {
|
||||
if ($cart->lines->isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Event::dispatch(new CartAbandoned($cart));
|
||||
|
||||
$cartsAbandoned++;
|
||||
}
|
||||
});
|
||||
|
||||
Cart::query()
|
||||
->whereHas('orders', fn ($query) => $query->whereNull('placed_at'))
|
||||
->where('updated_at', '<=', $cutoff)
|
||||
$lifecycle->abandonedCheckouts(Cart::query())
|
||||
->where('meta->recovery_consent', true)
|
||||
->with(['orders' => fn ($query) => $query->whereNull('placed_at')])
|
||||
->chunkById(200, function ($carts) use (&$checkoutsAbandoned) {
|
||||
|
||||
@@ -9,20 +9,22 @@ use Modules\Core\Cart\Filament\Resources\CartResource\Pages\ViewCart;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Lunar\Admin\Filament\Resources\CustomerResource;
|
||||
use Lunar\Models\Cart;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource\Pages;
|
||||
use Modules\Core\Cart\Services\CartLifecycleService;
|
||||
|
||||
/**
|
||||
* Read-only — a cart is managed entirely through the storefront (add/update/remove
|
||||
* line, checkout), never hand-edited by staff. Scoped to carts with a known
|
||||
* `user_id`/`customer_id` only: an anonymous guest's session cart carries no
|
||||
* identity a staff member could act on (no name, no email, nothing to follow up
|
||||
* with), so listing every such row would be noise, not a real admin capability —
|
||||
* see docs/cart.md for the reasoning (Lunar itself ships no cart admin view at all
|
||||
* to follow a precedent from).
|
||||
* line, checkout), never hand-edited by staff. Lists every cart, guest carts
|
||||
* included — see docs/cart.md ("Scope: every cart, identified or not"). An
|
||||
* anonymous cart's Customer/User columns just render "—" (see table() below)
|
||||
* rather than the row being hidden outright: most real traffic never reaches
|
||||
* an identified user/customer, and "how many carts are ongoing/abandoned
|
||||
* right now" is a real reporting need regardless of identity — excluding
|
||||
* anonymous carts would silently undercount it. Lunar itself ships no cart
|
||||
* admin view at all to follow a precedent from.
|
||||
*/
|
||||
class CartResource extends Resource
|
||||
{
|
||||
@@ -36,12 +38,6 @@ class CartResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Carts';
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
return parent::getEloquentQuery()
|
||||
->where(fn (Builder $query) => $query->whereNotNull('user_id')->orWhereNotNull('customer_id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Count only, not a fetch — no rows are loaded. Combines BOTH abandoned
|
||||
* states (`active()` already covers "no order at all" and "draft order,
|
||||
@@ -56,6 +52,11 @@ class CartResource extends Resource
|
||||
return (string) static::getEloquentQuery()->active()->where('updated_at', '<=', static::abandonedCutoff())->count();
|
||||
}
|
||||
|
||||
public static function lifecycle(): CartLifecycleService
|
||||
{
|
||||
return app(CartLifecycleService::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* `Cart::scopeActive()` (not-yet-converted-to-an-order carts) mixes two very
|
||||
* different things together: a cart someone is actively shopping in right now,
|
||||
@@ -67,7 +68,7 @@ class CartResource extends Resource
|
||||
*/
|
||||
public static function abandonedCutoff(): Carbon
|
||||
{
|
||||
return now()->sub(config('core.cart.abandoned_after', '1 hour'));
|
||||
return static::lifecycle()->abandonedCutoff();
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
|
||||
@@ -6,6 +6,7 @@ use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource;
|
||||
use Modules\Core\Cart\Services\CartLifecycleService;
|
||||
|
||||
class ListCarts extends ListRecords
|
||||
{
|
||||
@@ -27,30 +28,24 @@ class ListCarts extends ListRecords
|
||||
* bucket — same distinction Modules\Core\Recovery\Events\CartAbandoned /
|
||||
* Modules\Core\Recovery\Events\CheckoutAbandoned draw.
|
||||
*
|
||||
* "Ongoing" vs the two abandoned tabs all split on `updated_at` against
|
||||
* `CartResource::abandonedCutoff()` — Lunar has no time-based staleness
|
||||
* signal of its own, so recent activity is the only thing distinguishing a
|
||||
* cart someone is shopping in right now from one genuinely left behind.
|
||||
* The four query shapes below live on Modules\Core\Cart\Services\
|
||||
* CartLifecycleService, shared with Modules\Core\Cart\Commands\
|
||||
* DetectAbandonedCarts — see that service's docblock for why duplicating
|
||||
* them independently in both places was worth centralizing.
|
||||
*/
|
||||
public function getTabs(): array
|
||||
{
|
||||
$lifecycle = app(CartLifecycleService::class);
|
||||
|
||||
return [
|
||||
'abandoned_cart' => Tab::make('Abandoned Cart')
|
||||
->modifyQueryUsing(fn(Builder $query) => $query
|
||||
->whereDoesntHave('orders')
|
||||
->where('updated_at', '<=', CartResource::abandonedCutoff())),
|
||||
->modifyQueryUsing(fn (Builder $query) => $lifecycle->abandonedCarts($query)),
|
||||
'abandoned_checkout' => Tab::make('Abandoned Checkout')
|
||||
->modifyQueryUsing(fn(Builder $query) => $query
|
||||
->whereHas('orders', fn(Builder $query) => $query->whereNull('placed_at'))
|
||||
->where('updated_at', '<=', CartResource::abandonedCutoff())),
|
||||
|
||||
->modifyQueryUsing(fn (Builder $query) => $lifecycle->abandonedCheckouts($query)),
|
||||
'ongoing' => Tab::make('Ongoing')
|
||||
->modifyQueryUsing(fn(Builder $query) => $query->active()->where('updated_at', '>', CartResource::abandonedCutoff())),
|
||||
->modifyQueryUsing(fn (Builder $query) => $lifecycle->ongoing($query)),
|
||||
'completed' => Tab::make('Completed')
|
||||
->modifyQueryUsing(fn(Builder $query) => $query->whereHas(
|
||||
'orders',
|
||||
fn(Builder $query) => $query->whereNotNull('placed_at'),
|
||||
)),
|
||||
->modifyQueryUsing(fn (Builder $query) => $lifecycle->completed($query)),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,12 +5,18 @@ namespace Modules\Core\Cart\Filament\Resources\CartResource\Pages;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Infolists\Components\ImageEntry;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Support\Colors\Color;
|
||||
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
|
||||
use Illuminate\Support\Facades\Blade;
|
||||
use Lunar\Admin\Filament\Resources\CustomerResource;
|
||||
use Lunar\Admin\Filament\Resources\ProductResource\Pages\EditProduct;
|
||||
use Lunar\Models\Cart;
|
||||
use Lunar\Models\CartLine;
|
||||
use Lunar\Models\ProductVariant;
|
||||
use Modules\Core\Cart\Filament\Resources\CartResource;
|
||||
|
||||
class ViewCart extends ViewRecord
|
||||
@@ -35,12 +41,23 @@ class ViewCart extends ViewRecord
|
||||
* (a single view page load), not per-row in the list table, since running the
|
||||
* full pipeline for every row of a paginated table would be expensive for no
|
||||
* real benefit — see docs/lunar.md's Cart gotchas.
|
||||
*
|
||||
* Eager-loads what the Lines section (below) reads off each line's
|
||||
* purchasable — name, thumbnail, options — the same relations Lunar's
|
||||
* own OrderItemsTable loads for an order's line items (`with(['purchasable'])`,
|
||||
* see vendor/lunarphp/lunar/.../OrderItemsTable::getDefaultTable()) — so
|
||||
* rendering the product grid doesn't N+1 per line.
|
||||
*/
|
||||
protected function resolveRecord(int|string $key): Cart
|
||||
{
|
||||
/** @var Cart $cart */
|
||||
$cart = parent::resolveRecord($key);
|
||||
|
||||
$cart->load('lines.purchasable', 'shippingAddress.country');
|
||||
|
||||
EloquentCollection::make($cart->lines->pluck('purchasable')->filter(fn ($p) => $p instanceof ProductVariant))
|
||||
->loadMissing(['product.thumbnail', 'images', 'values']);
|
||||
|
||||
return $cart->calculate();
|
||||
}
|
||||
|
||||
@@ -77,6 +94,37 @@ class ViewCart extends ViewRecord
|
||||
RepeatableEntry::make('lines')
|
||||
->hiddenLabel()
|
||||
->schema([
|
||||
ImageEntry::make('image')
|
||||
->hiddenLabel()
|
||||
->state(fn (CartLine $record) => $record->purchasable instanceof ProductVariant
|
||||
? $record->purchasable->getThumbnail()?->getUrl('small')
|
||||
: null)
|
||||
->defaultImageUrl(fn () => 'data:image/svg+xml;base64,'.base64_encode(
|
||||
Blade::render('<x-filament::icon icon="heroicon-o-photo" style="color:rgb('.Color::Gray[400].');"/>')
|
||||
))
|
||||
->imageSize(48),
|
||||
TextEntry::make('description')
|
||||
->label('Product')
|
||||
// ProductVariant::getDescription()/getOption() are typed
|
||||
// string but internally read translateAttribute()/
|
||||
// translate(), which return null for a product/option
|
||||
// with no attribute data set for the active locale —
|
||||
// reading the underlying relations directly here avoids
|
||||
// that TypeError rather than calling through them.
|
||||
->state(fn (CartLine $record) => $record->purchasable instanceof ProductVariant
|
||||
? ($record->purchasable->product?->translateAttribute('name') ?? '—')
|
||||
: '—')
|
||||
->url(fn (CartLine $record) => $record->purchasable instanceof ProductVariant
|
||||
? EditProduct::getUrl(['record' => $record->purchasable->product_id])
|
||||
: null)
|
||||
->weight('bold'),
|
||||
TextEntry::make('options')
|
||||
->label('Options')
|
||||
->state(fn (CartLine $record) => $record->purchasable instanceof ProductVariant
|
||||
? ($record->purchasable->values->map(fn ($value) => $value->translate('name'))->filter()->join(', ') ?: null)
|
||||
: null)
|
||||
->placeholder('—')
|
||||
->badge(),
|
||||
TextEntry::make('purchasable.sku')
|
||||
->label('SKU')
|
||||
->placeholder('—'),
|
||||
@@ -90,6 +138,53 @@ class ViewCart extends ViewRecord
|
||||
])
|
||||
->columns(4),
|
||||
]),
|
||||
Section::make('Shipping')
|
||||
->columns(3)
|
||||
->schema([
|
||||
TextEntry::make('shippingAddress.shipping_option')
|
||||
->label('Shipping method')
|
||||
// The raw identifier (e.g. "acs") is all a
|
||||
// CartAddress row stores — the human-readable
|
||||
// name only exists on the resolved
|
||||
// Lunar\DataTypes\ShippingOption, which is what
|
||||
// shippingBreakdown's items are keyed/named
|
||||
// from below, so fall back to that name rather
|
||||
// than showing the bare identifier.
|
||||
->formatStateUsing(fn (Cart $record, ?string $state) => $state
|
||||
? ($record->shippingBreakdown?->items->get($state)?->name ?? $state)
|
||||
: null)
|
||||
->placeholder('Not selected'),
|
||||
TextEntry::make('shippingAddress.country.name')
|
||||
->label('Shipping to')
|
||||
->placeholder('—'),
|
||||
TextEntry::make('shippingTotal')
|
||||
->label('Shipping total')
|
||||
->formatStateUsing(fn (Cart $record) => $record->shippingTotal?->formatted() ?? '—')
|
||||
->weight('bold'),
|
||||
RepeatableEntry::make('shippingBreakdownItems')
|
||||
->label('Breakdown')
|
||||
->columnSpanFull()
|
||||
// shippingBreakdown->items is a plain (non-Eloquent)
|
||||
// Collection of Lunar\Base\ValueObjects\Cart\
|
||||
// ShippingBreakdownItem — e.g. the carrier rate and,
|
||||
// separately, Modules\Core\Payment\Pipelines\Cart\
|
||||
// ApplyPaymentMethodFee's own line item when the
|
||||
// selected payment method carries a fee (see
|
||||
// CHANGELOG 0.16.3) — both show up here individually
|
||||
// rather than only as the summed shippingTotal above.
|
||||
->state(fn (Cart $record) => $record->shippingBreakdown?->items->values() ?? [])
|
||||
->schema([
|
||||
TextEntry::make('name')
|
||||
->hiddenLabel(),
|
||||
TextEntry::make('price')
|
||||
->hiddenLabel()
|
||||
->formatStateUsing(fn ($state) => $state?->formatted() ?? '—')
|
||||
->alignEnd(),
|
||||
])
|
||||
->columns(2)
|
||||
->visible(fn (Cart $record) => (bool) $record->shippingBreakdown?->items->isNotEmpty()),
|
||||
])
|
||||
->visible(fn (Cart $record) => $record->shippingAddress !== null),
|
||||
Section::make('Totals')
|
||||
->columns(3)
|
||||
->schema([
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Cart\Services;
|
||||
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Lunar\Models\Cart;
|
||||
|
||||
/**
|
||||
* The single source of truth for the four cart lifecycle states documented in
|
||||
* docs/cart.md ("Four states, not two — and not Cart::completed_at"). Both
|
||||
* Modules\Core\Cart\Filament\Resources\CartResource/ListCarts (staff-facing
|
||||
* browsing/tabs) and Modules\Core\Cart\Commands\DetectAbandonedCarts
|
||||
* (abandonment-event dispatch) build on these same four query shapes — before
|
||||
* this existed, each reimplemented them independently, which is exactly the
|
||||
* kind of drift that lets the admin panel and the recovery-email pipeline
|
||||
* quietly disagree about what "abandoned" means.
|
||||
*
|
||||
* `Cart::completed_at` is declared/cast on the model but never actually
|
||||
* written anywhere in Lunar core — not a real signal, not used here.
|
||||
* `Cart::scopeActive()` (Lunar's own "not yet converted to an order" scope)
|
||||
* mixes two distinct states together (no order at all vs. a draft order that
|
||||
* was never placed) — see docs/cart.md for why they're kept apart as
|
||||
* different purchase-intent/reachability signals rather than folded into one
|
||||
* "not converted" bucket.
|
||||
*
|
||||
* Query shape only: consent (`meta->recovery_consent`) and non-empty-lines
|
||||
* filtering stay in DetectAbandonedCarts, not here — those are specific to
|
||||
* whether a recovery event should fire, not to what "abandoned" means. Staff
|
||||
* browsing the admin panel should see every abandoned cart, consenting or
|
||||
* not.
|
||||
*
|
||||
* `unrecoverableCutoff()` is a second, older threshold
|
||||
* (`core.cart.unrecoverable_after`, default 90 days) applied as a lower
|
||||
* bound on both abandoned*() methods below: a cart past it is too old to be
|
||||
* a realistic recovery target (pricing/stock/tax have likely moved on), so
|
||||
* it drops out of "Abandoned Cart"/"Abandoned Checkout" entirely rather than
|
||||
* staying flagged as an actionable abandonment forever. It does not appear
|
||||
* in `ongoing()`/`completed()` either — this is about the abandoned-cart
|
||||
* pipeline specifically, not a retention/deletion policy (no rows are
|
||||
* touched here).
|
||||
*/
|
||||
class CartLifecycleService
|
||||
{
|
||||
public function abandonedCutoff(): Carbon
|
||||
{
|
||||
return now()->sub(config('core.cart.abandoned_after', '1 hour'));
|
||||
}
|
||||
|
||||
public function unrecoverableCutoff(): Carbon
|
||||
{
|
||||
return now()->sub(config('core.cart.unrecoverable_after', '90 days'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Not yet converted to an order (scopeActive()), with recent activity —
|
||||
* someone plausibly shopping right now, not (yet) left behind.
|
||||
*/
|
||||
public function ongoing(Builder $query): Builder
|
||||
{
|
||||
return $query->active()->where('updated_at', '>', $this->abandonedCutoff());
|
||||
}
|
||||
|
||||
/**
|
||||
* No order started at all, stale, not yet past the unrecoverable cap, and
|
||||
* actually has something in it — the weaker of the two abandoned states
|
||||
* (see docs/cart.md's "Abandoned Cart vs Abandoned Checkout"). An empty
|
||||
* cart (created but nothing ever added — e.g. a bot, or a session that
|
||||
* never shopped) was never really "abandoned"; there's nothing to
|
||||
* recover, so it's excluded rather than counted as a false positive.
|
||||
*/
|
||||
public function abandonedCarts(Builder $query): Builder
|
||||
{
|
||||
return $query->whereDoesntHave('orders')
|
||||
->whereHas('lines')
|
||||
->where('updated_at', '<=', $this->abandonedCutoff())
|
||||
->where('updated_at', '>', $this->unrecoverableCutoff());
|
||||
}
|
||||
|
||||
/**
|
||||
* A draft order exists (checkout was started) but was never placed,
|
||||
* stale, and not yet past the unrecoverable cap — the stronger of the
|
||||
* two abandoned states.
|
||||
*/
|
||||
public function abandonedCheckouts(Builder $query): Builder
|
||||
{
|
||||
return $query->whereHas('orders', fn (Builder $query) => $query->whereNull('placed_at'))
|
||||
->where('updated_at', '<=', $this->abandonedCutoff())
|
||||
->where('updated_at', '>', $this->unrecoverableCutoff());
|
||||
}
|
||||
|
||||
/**
|
||||
* Has an order that was actually placed, not just drafted.
|
||||
*/
|
||||
public function completed(Builder $query): Builder
|
||||
{
|
||||
return $query->whereHas('orders', fn (Builder $query) => $query->whereNotNull('placed_at'));
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,12 @@ use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
* quantity 1, via ProductVariant::canBeFulfilledAtQuantity() (Lunar's own
|
||||
* purchasability rule: `purchasable === 'always'` is always true regardless of
|
||||
* stock, `in_stock` checks stock alone, anything else checks stock+backorder).
|
||||
* Reflects stock as of the last reindex only — nothing currently reindexes a
|
||||
* product when an order decrements its stock (see docs/product-listing.md).
|
||||
* Modules\Core\Order\Listeners\DecrementStockOnOrderPlaced reindexes a product
|
||||
* the moment an order placed against it decrements its stock — see that
|
||||
* class's own docblock for why only `purchasable === 'in_stock'`
|
||||
* variants are ever touched. Any other stock edit (a manual admin
|
||||
* change, a future inventory-sync integration) still only reflects here
|
||||
* as of the next reindex (see docs/product-listing.md).
|
||||
*
|
||||
* - recommendations (recommendations.id filterable): [{id, name, price, image}, ...]
|
||||
* up to 4 other products to show alongside this one (a "related products"
|
||||
|
||||
@@ -173,19 +173,19 @@ class CheckoutService
|
||||
|
||||
/**
|
||||
* Records which payment type the shopper picked (Cart::meta
|
||||
* ['payment_method']) — read by e.g. Modules\Core\Payment\Pipelines\
|
||||
* Cart\ApplyCashOnDeliveryFee to add that type's own cart-total
|
||||
* adjustments before recalculation.
|
||||
* ['payment_method']) — read by Modules\Core\Payment\Pipelines\
|
||||
* Cart\ApplyPaymentMethodFee to add that method's own `data.fee` (if
|
||||
* any) before recalculation.
|
||||
*
|
||||
* Also snapshots Cart::fingerprint() into meta, *after* saving the
|
||||
* chosen type — the fingerprint has to reflect the final total
|
||||
* including any payment-type-specific adjustment (e.g. a COD
|
||||
* surcharge), which only exists once payment_method is set and the
|
||||
* cart recalculates. Captured here, server-side, rather than asked of
|
||||
* the storefront: this is the last moment before initiatePayment() that
|
||||
* the shopper's reviewed total is known, and initiatePayment() reads it
|
||||
* back internally instead of taking a fingerprint parameter — a
|
||||
* storefront should never need to know Cart::fingerprint() exists.
|
||||
* including any payment-method-specific fee, which only exists once
|
||||
* payment_method is set and the cart recalculates. Captured here,
|
||||
* server-side, rather than asked of the storefront: this is the last
|
||||
* moment before initiatePayment() that the shopper's reviewed total is
|
||||
* known, and initiatePayment() reads it back internally instead of
|
||||
* taking a fingerprint parameter — a storefront should never need to
|
||||
* know Cart::fingerprint() exists.
|
||||
*
|
||||
* Does not itself call a payment driver — selecting a method and
|
||||
* initiating payment against it are deliberately separate steps, same
|
||||
@@ -204,7 +204,15 @@ class CheckoutService
|
||||
$cart->meta = [...($cart->meta?->toArray() ?? []), 'payment_method' => $type];
|
||||
$cart->save();
|
||||
|
||||
$cart = $cart->calculate();
|
||||
// Cart::calculate() no-ops if this cart instance was already
|
||||
// calculated earlier in the request (Cart::isCalculated()) — which
|
||||
// it will have been if the shopper switches payment method after
|
||||
// the checkout page's first render already calculated it. Without
|
||||
// recalculate() forcing a fresh run, the just-saved payment_method
|
||||
// (and any fee tied to it, see ApplyPaymentMethodFee) would never
|
||||
// be reflected — the summary would keep showing whichever method
|
||||
// was calculated first.
|
||||
$cart = $cart->recalculate();
|
||||
$cart->meta = [...($cart->meta?->toArray() ?? []), 'checkout_fingerprint' => $cart->fingerprint()];
|
||||
$cart->save();
|
||||
|
||||
@@ -289,6 +297,7 @@ class CheckoutService
|
||||
|
||||
$order->meta = [
|
||||
...($order->meta?->toArray() ?? []),
|
||||
'payment_method' => $type,
|
||||
'terms_accepted' => true,
|
||||
'terms_accepted_at' => now()->toIso8601String(),
|
||||
'terms_accepted_policy_version' => $policyVersion,
|
||||
|
||||
@@ -311,9 +311,8 @@ class InstallLunarCommand extends Command
|
||||
PaymentMethod::create([
|
||||
'type' => 'cash-on-delivery',
|
||||
'name' => 'Cash on Delivery',
|
||||
'driver' => 'offline',
|
||||
'driver' => 'cash-on-delivery',
|
||||
'capture_mode' => 'pay',
|
||||
'captured_status' => 'payment-offline',
|
||||
'position' => 0,
|
||||
'enabled' => false,
|
||||
'data' => [],
|
||||
|
||||
+9
-5
@@ -27,15 +27,18 @@ use Modules\Core\Catalog\Filament\Extensions\ProductOptionResourceExtension;
|
||||
use Modules\Core\Catalog\Filament\Extensions\ValuesRelationManagerExtension;
|
||||
use Modules\Core\Localization\Filament\Resources\LanguageLineResource;
|
||||
use Modules\Core\Order\Filament\Extensions\OrderItemsTableExtension;
|
||||
use Modules\Core\Order\Filament\Extensions\OrderRefundActionsExtension;
|
||||
use Modules\Core\Order\Filament\Extensions\OrderPaymentMethodSummaryExtension;
|
||||
use Modules\Core\Order\Filament\Extensions\OrderActionsExtension;
|
||||
use Modules\Core\Order\Filament\Extensions\OrderTransactionsExtension;
|
||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource;
|
||||
use Modules\Core\Review\Filament\Extensions\ProductResourceExtension;
|
||||
use Modules\Core\Review\Models\ProductReview;
|
||||
use Modules\Core\Shipping\Extensions\OrderShipmentsExtension;
|
||||
use Modules\Core\Shipping\Extensions\OrderViewExtension;
|
||||
use Modules\Core\Shipping\Extensions\ShippingMethodListExtension;
|
||||
use Modules\Core\Shipping\Extensions\ShippingMethodResourceExtension;
|
||||
use Modules\Core\Shipping\Filament\Pages\ManagePickupManifests;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
|
||||
|
||||
class CorePlugin implements Plugin
|
||||
{
|
||||
@@ -55,9 +58,10 @@ class CorePlugin implements Plugin
|
||||
LanguageLineResource::class,
|
||||
CartResource::class,
|
||||
PaymentMethodResource::class,
|
||||
ShipmentResource::class,
|
||||
ManifestResource::class,
|
||||
])
|
||||
->plugin(ShippingPlugin::make())
|
||||
->pages([ManagePickupManifests::class]);
|
||||
->plugin(ShippingPlugin::make());
|
||||
|
||||
LunarPanel::extensions([
|
||||
StaffResource::class => StaffResourceExtension::class,
|
||||
@@ -66,7 +70,7 @@ class CorePlugin implements Plugin
|
||||
ValuesRelationManager::class => ValuesRelationManagerExtension::class,
|
||||
ShippingMethodResource::class => ShippingMethodResourceExtension::class,
|
||||
ListShippingMethod::class => ShippingMethodListExtension::class,
|
||||
ManageOrder::class => [OrderViewExtension::class, OrderRefundActionsExtension::class, OrderTransactionsExtension::class],
|
||||
ManageOrder::class => [OrderViewExtension::class, OrderActionsExtension::class, OrderTransactionsExtension::class, OrderPaymentMethodSummaryExtension::class, OrderShipmentsExtension::class],
|
||||
OrderItemsTable::class => OrderItemsTableExtension::class,
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Order\Events\OrderCompleted;
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
|
||||
/**
|
||||
* Auto-completes a carrier order once its 14-day return window has
|
||||
* elapsed with no return requested — the automatic counterpart to the
|
||||
* staff "Update Status" action's manual completion. Store-pickup orders
|
||||
* have no return-window step at all (Modules\Core\Order\Listeners\
|
||||
* CompleteOrderOnPickedUp completes them immediately), so this only ever
|
||||
* touches carrier orders sitting in 'delivered' (the status also carrying
|
||||
* "return window is open" — see AdvanceFulfillmentOnDelivered).
|
||||
*
|
||||
* Registered at exactly dailyAt('00:00') in
|
||||
* Modules\Core\Providers\OrderServiceProvider — a compliance requirement
|
||||
* that this run at exact midnight, not Laravel's own arbitrary default
|
||||
* time for a plain daily() schedule.
|
||||
*
|
||||
* "When did the window open" is read from order_status_transitions rather
|
||||
* than Order::updated_at, which any unrelated field write would bump —
|
||||
* this is the concrete reason the audit table exists beyond pure logging.
|
||||
*
|
||||
* Window length is config('core.order.return_window_days') — a legal/
|
||||
* policy value a store may need to change without a code deploy, not a
|
||||
* hardcoded constant.
|
||||
*/
|
||||
class CloseExpiredReturnWindows extends Command
|
||||
{
|
||||
protected $signature = 'boboko:order:close-expired-return-windows';
|
||||
|
||||
protected $description = 'Auto-complete carrier orders whose return window has elapsed with no return requested.';
|
||||
|
||||
public function handle(OrderStatusWriter $writer): void
|
||||
{
|
||||
$cutoff = now()->subDays(config('core.order.return_window_days', 14));
|
||||
|
||||
$orderIds = Order::query()
|
||||
->where('status', 'delivered')
|
||||
->whereHas('statusTransitions', function ($query) use ($cutoff) {
|
||||
$query->where('to_status', 'delivered')
|
||||
->where('created_at', '<=', $cutoff);
|
||||
})
|
||||
->pluck('id');
|
||||
|
||||
$completed = 0;
|
||||
|
||||
foreach ($orderIds as $orderId) {
|
||||
$order = Order::find($orderId);
|
||||
|
||||
if (! $order || $order->status !== 'delivered') {
|
||||
continue; // idempotent no-op — moved on since the query ran
|
||||
}
|
||||
|
||||
$writer->write($order, 'completed', self::class);
|
||||
|
||||
OrderCompleted::dispatch($order);
|
||||
|
||||
$completed++;
|
||||
}
|
||||
|
||||
$this->components->info("Completed {$completed} order(s) past their return window.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\DTOs;
|
||||
|
||||
/**
|
||||
* What a Modules\Core\Order\Services\OrderFulfillmentService method
|
||||
* returns instead of throwing/echoing a Filament notification directly —
|
||||
* keeps that service usable outside a Filament action (a future API
|
||||
* endpoint, a console command, a test) without dragging
|
||||
* Filament\Notifications\Notification along. Modules\Core\Shipping\
|
||||
* Extensions\OrderViewExtension is the one place that translates this
|
||||
* into an actual on-screen notification.
|
||||
*/
|
||||
final class OrderFulfillmentResult
|
||||
{
|
||||
private function __construct(
|
||||
public readonly bool $success,
|
||||
public readonly string $message,
|
||||
) {}
|
||||
|
||||
public static function success(string $message): self
|
||||
{
|
||||
return new self(true, $message);
|
||||
}
|
||||
|
||||
public static function failure(string $message): self
|
||||
{
|
||||
return new self(false, $message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* The one terminal signal every notification/reporting concern that only
|
||||
* cares about "this order is fully done" should listen to, regardless of
|
||||
* which path actually got it there — dispatched by all four:
|
||||
* Modules\Core\Order\Listeners\CompleteOrderOnPickedUp (store-pickup),
|
||||
* Modules\Core\Order\Commands\CloseExpiredReturnWindows (carrier,
|
||||
* automatic 14-day return-window expiry), or Modules\Core\Shipping\
|
||||
* Extensions\OrderViewExtension's "Mark Completed" action (manual
|
||||
* universal fallback, either branch).
|
||||
*/
|
||||
class OrderCompleted
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Shipping\Models\ShipmentInfo;
|
||||
|
||||
/**
|
||||
* Dispatched by either of the two paths that move a carrier order's
|
||||
* `status` to 'dispatched' — Modules\Core\Order\Listeners\
|
||||
* AdvanceFulfillmentOnCarrierCheckpoint (automatic, reacting to a real
|
||||
* carrier checkpoint) or Modules\Core\Order\Services\
|
||||
* OrderFulfillmentService::createShipmentAndDispatch() (staff-driven, via
|
||||
* the single "Update Status" action). $shipmentInfo is nullable
|
||||
* specifically because of that second path — populated with the
|
||||
* triggering checkpoint when it's real, null when staff drove it
|
||||
* manually. Mirrors OrderDelivered's {order, shipmentInfo} shape, just
|
||||
* with the nullability this one event additionally needs.
|
||||
*/
|
||||
class OrderDispatched
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
public readonly ?ShipmentInfo $shipmentInfo = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* Dispatched by Modules\Core\Order\Services\OrderStatusWriter::markPaid()
|
||||
* whenever Order::paid flips to true — entirely independent of the
|
||||
* `status` column (see OrderStatusFlow's own docblock for why payment
|
||||
* timing, especially for cash-on-delivery, cannot be modeled as a step in
|
||||
* that sequence). Order::status changes are instead picked up generically
|
||||
* by Modules\Core\Order\Events\OrderStatusUpdated (dispatched by
|
||||
* OrderObserver whenever `status` changes, regardless of writer).
|
||||
*/
|
||||
class OrderPaidChanged
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
public readonly string $causeClass,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* Dispatched by Modules\Core\Order\Services\OrderFulfillmentService::
|
||||
* markPickedUp(), the staff-driven "Update Status" action's handling of
|
||||
* the 'picked_up' target — the customer has collected a store-pickup
|
||||
* order in person. Store-pickup only; a carrier order's equivalent
|
||||
* "arrived" moment is OrderDelivered. Modules\Core\Order\Listeners\
|
||||
* CompleteOrderOnPickedUp reacts to this by moving `status` straight to
|
||||
* 'completed' — no return-window step for store-pickup, per the business
|
||||
* design.
|
||||
*/
|
||||
class OrderPickedUp
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* Dispatched by Modules\Core\Shipping\Extensions\OrderViewExtension's
|
||||
* "Mark Ready" action, carrier branch (Order::isStorePickupOrder() ===
|
||||
* false) — staff has packed/staged the order for carrier handoff.
|
||||
* Staff-internal: nothing customer-facing happens at this moment, so no
|
||||
* notification listens to this event (compare OrderReadyForPickup, which
|
||||
* does trigger a customer email).
|
||||
*/
|
||||
class OrderReadyForDispatch
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* Dispatched by Modules\Core\Shipping\Extensions\OrderViewExtension's
|
||||
* "Mark Ready" action, store-pickup branch (Order::isStorePickupOrder()
|
||||
* === true) — staff has packed/staged the order for the customer to
|
||||
* collect in store. Drives Modules\Core\Order\Notifications\
|
||||
* OrderPickupReadyNotification ("come collect your order").
|
||||
*/
|
||||
class OrderReadyForPickup
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Events;
|
||||
|
||||
use Illuminate\Foundation\Events\Dispatchable;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* Dispatched by Modules\Core\Order\Services\OrderStatusWriter::write()
|
||||
* alongside the generic Modules\Core\Order\Events\OrderStatusUpdated
|
||||
* (which Modules\Core\Order\Observers\OrderObserver dispatches for ANY
|
||||
* `status` write, regardless of cause, and which
|
||||
* OrderStatusUpdatedNotification already listens to). This event exists
|
||||
* only because the audit trail (Modules\Core\Order\Listeners\
|
||||
* RecordStatusTransition) needs $causeClass, which OrderStatusUpdated
|
||||
* does not carry — OrderStatusWriter is the only writer of `status` this
|
||||
* package has left, so it's the only place that needs to know its own
|
||||
* cause.
|
||||
*/
|
||||
class OrderStatusChanged
|
||||
{
|
||||
use Dispatchable;
|
||||
|
||||
public function __construct(
|
||||
public readonly Order $order,
|
||||
public readonly ?string $previousStatus,
|
||||
public readonly string $newStatus,
|
||||
public readonly string $causeClass,
|
||||
) {}
|
||||
}
|
||||
+50
-39
@@ -32,10 +32,6 @@ use ReflectionProperty;
|
||||
* could return a real, honest failure — see Payment\Support\
|
||||
* TransactionDriverAdapter's own docblock for that history.
|
||||
*
|
||||
* Fix, for capture: wrap the action's own action() closure so that, on
|
||||
* Halt, we call $action->sendFailureNotification() ourselves before letting
|
||||
* the Halt continue propagating — everything else is untouched.
|
||||
*
|
||||
* Fix, for refund: same notification fix, but the action() closure is
|
||||
* replaced outright (not wrapped) rather than reused, because refund also
|
||||
* needs a "Refund via" driver Select added to the modal (see
|
||||
@@ -43,15 +39,28 @@ use ReflectionProperty;
|
||||
* Payment\Support\TransactionDriverAdapter::refundVia() instead of
|
||||
* Lunar\Models\Transaction::refund() — see fixRefundAction()'s own
|
||||
* docblock.
|
||||
*
|
||||
* Fix, for capture: same notification fix, but the action() closure is
|
||||
* also replaced outright — the actual call is routed through
|
||||
* Payment\Support\TransactionDriverAdapter::capture() instead of
|
||||
* Lunar\Models\Transaction::capture() (see fixCaptureAction()), so a
|
||||
* manual backoffice capture goes through the app's own payment driver
|
||||
* registry and dispatches Payment\Events\PaymentCaptured exactly like a
|
||||
* checkout-time capture does — the vendor path resolved
|
||||
* Lunar\Facades\Payments (an entirely separate, unused driver registry)
|
||||
* and never dispatched that event, which is why Order::status used to
|
||||
* stay stuck on 'awaiting_payment' after a manual capture even though
|
||||
* Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus now advances it
|
||||
* on PaymentCaptured.
|
||||
*/
|
||||
class OrderRefundActionsExtension extends ViewPageExtension
|
||||
class OrderActionsExtension extends ViewPageExtension
|
||||
{
|
||||
public function headerActions(array $actions): array
|
||||
{
|
||||
return array_map(
|
||||
fn (Action $action) => match ($action->getName()) {
|
||||
'refund' => $this->fixRefundAction($action),
|
||||
'capture' => $this->fixFailureNotification($action),
|
||||
'capture' => $this->fixCaptureAction($action),
|
||||
default => $action,
|
||||
},
|
||||
$actions,
|
||||
@@ -123,6 +132,41 @@ class OrderRefundActionsExtension extends ViewPageExtension
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mirrors fixRefundAction()'s notification fix, but for the "amount"
|
||||
* field already on the vendor schema — no extra field needed, since
|
||||
* capture always goes back through the transaction's own original
|
||||
* driver (there's no equivalent to refunding via a different driver).
|
||||
*/
|
||||
private function fixCaptureAction(Action $action): Action
|
||||
{
|
||||
return $action->action(function (array $data, Action $action) {
|
||||
$transaction = Transaction::find($data['transaction']);
|
||||
|
||||
if (! $transaction instanceof CoreTransaction) {
|
||||
$action->failureNotification(fn () => Notification::make('capture_failure')->danger()->title('Transaction not found.'))
|
||||
->sendFailureNotification();
|
||||
|
||||
throw new Halt;
|
||||
}
|
||||
|
||||
$response = app(TransactionDriverAdapter::class)->capture(
|
||||
$transaction,
|
||||
(int) bcmul((string) $data['amount'], (string) $transaction->order->currency->factor),
|
||||
);
|
||||
|
||||
if (! $response->success) {
|
||||
$action->failureNotification(
|
||||
fn () => Notification::make('capture_failure')->color('danger')->title($response->message)
|
||||
)->sendFailureNotification();
|
||||
|
||||
throw new Halt;
|
||||
}
|
||||
|
||||
$action->success();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
@@ -163,37 +207,4 @@ class OrderRefundActionsExtension extends ViewPageExtension
|
||||
|
||||
return $reflected->getValue($object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps the action's own configured action() closure so that, if it
|
||||
* halts (Lunar's closures throw via $action->halt() to signal failure —
|
||||
* see this class's own docblock for why that alone never sends the
|
||||
* notification queued via failureNotification()), we send that
|
||||
* notification ourselves before letting the Halt continue propagating
|
||||
* (still needed — it's what stops callMountedAction() from treating
|
||||
* this as a success and closing the modal/committing the DB transaction).
|
||||
*
|
||||
* $this->evaluate() (not a plain call) matches exactly how Action::call()
|
||||
* itself invokes the closure — Lunar's closures type-hint $data/$record/
|
||||
* $action and rely on Filament's own container-style parameter
|
||||
* resolution, not positional arguments.
|
||||
*/
|
||||
private function fixFailureNotification(Action $action): Action
|
||||
{
|
||||
$originalAction = $action->getActionFunction();
|
||||
|
||||
if ($originalAction === null) {
|
||||
return $action;
|
||||
}
|
||||
|
||||
return $action->action(function (array $arguments) use ($action, $originalAction) {
|
||||
try {
|
||||
return $action->evaluate($originalAction, $arguments);
|
||||
} catch (Halt $exception) {
|
||||
$action->sendFailureNotification();
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use Filament\Tables\Table;
|
||||
use Lunar\Admin\Support\Extending\BaseExtension;
|
||||
|
||||
/**
|
||||
* Same fix as OrderRefundActionsExtension, applied to the order lines
|
||||
* Same fix as OrderActionsExtension, applied to the order lines
|
||||
* table's "bulk_refund" toolbar action (Lunar\Admin\...\OrderItemsTable::
|
||||
* getBulkRefundAction()) — see that class's docblock for the underlying
|
||||
* Filament bug (failureNotification()+failure()+halt() never actually
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Filament\Extensions;
|
||||
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Lunar\Admin\Support\Extending\ViewPageExtension;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
/**
|
||||
* Adds a "Payment Method" entry to the order summary sidebar — previously
|
||||
* nowhere on the order page told staff which payment method a shopper
|
||||
* actually used. Reads Order.meta['payment_method'] (written by
|
||||
* Modules\Core\Checkout\Services\CheckoutService::initiatePayment()), the
|
||||
* same source Modules\Core\Order\Services\OrderStatusFlow::isCod() reads,
|
||||
* so this entry and the "Mark Paid" action's visibility always agree on
|
||||
* what payment method an order used. Falls back to the most recent
|
||||
* Transaction.driver for an order placed before that field existed.
|
||||
*
|
||||
* Uses the extendOrderSummarySchema hook, same as the deleted 3-axis
|
||||
* OrderStatusSummaryExtension did — see that class's git history for the
|
||||
* hook's own docblock/rationale.
|
||||
*/
|
||||
class OrderPaymentMethodSummaryExtension extends ViewPageExtension
|
||||
{
|
||||
public function extendOrderSummarySchema(array $schema): array
|
||||
{
|
||||
$schema[] = TextEntry::make('payment_method')
|
||||
->label('Payment method')
|
||||
->state(fn (Order $record) => $this->resolveLabel($record))
|
||||
->placeholder('—')
|
||||
->alignEnd();
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
private function resolveLabel(Order $record): ?string
|
||||
{
|
||||
$type = $record->meta['payment_method'] ?? $record->transactions()->latest('id')->value('driver');
|
||||
|
||||
if ($type === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return PaymentMethod::where('type', $type)->value('name') ?? $type;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Modules\Core\Order\Events\OrderDispatched;
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
use Modules\Core\Shipping\Enums\TrackingStatus;
|
||||
use Modules\Core\Shipping\Events\ShipmentStatusUpdatedByCarrier;
|
||||
|
||||
/**
|
||||
* The automatic half of "Dispatched" — the manual fallback is the staff
|
||||
* "Update Status" action (Modules\Core\Shipping\Extensions\
|
||||
* OrderViewExtension). Listens to ShipmentStatusUpdatedByCarrier directly,
|
||||
* the same event Modules\Core\Order\Listeners\DeriveOrderDeliveredFromShipment
|
||||
* listens to.
|
||||
*
|
||||
* Reacts to either TrackingStatus::CollectedFromSender (the carrier
|
||||
* collected the parcel from the merchant) or InTransit directly, for a
|
||||
* carrier that skips straight there without a distinct collection
|
||||
* checkpoint.
|
||||
*
|
||||
* Guarded to only fire from 'ready_for_dispatch' — a late/duplicate
|
||||
* checkpoint, or an order the manual action already advanced, is a
|
||||
* silent no-op.
|
||||
*/
|
||||
class AdvanceFulfillmentOnCarrierCheckpoint
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderStatusWriter $writer,
|
||||
) {}
|
||||
|
||||
public function handle(ShipmentStatusUpdatedByCarrier $event): void
|
||||
{
|
||||
if ($event->shipmentInfo->status !== TrackingStatus::InTransit
|
||||
&& $event->shipmentInfo->status !== TrackingStatus::CollectedFromSender) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order = $event->shipmentInfo->shipment->order;
|
||||
|
||||
if (! $order || $order->status !== 'ready_for_dispatch') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->writer->write($order, 'dispatched', self::class);
|
||||
|
||||
OrderDispatched::dispatch($order, $event->shipmentInfo);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Modules\Core\Order\Events\OrderDelivered;
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
|
||||
/**
|
||||
* Writes `status` to 'delivered' once a carrier confirms delivery, rather
|
||||
* than jumping straight to 'completed'. Carrier orders get a return
|
||||
* window between delivery and completion (see Modules\Core\Order\
|
||||
* Commands\CloseExpiredReturnWindows, which auto-completes an order once
|
||||
* that window elapses) — 'delivered' is both "the parcel arrived" and
|
||||
* "the return window is now open"; nothing distinguishes those as
|
||||
* separate instants, they're the same moment, so there is only the one
|
||||
* status value.
|
||||
*
|
||||
* Kept separate from Modules\Core\Order\Listeners\
|
||||
* DeriveOrderDeliveredFromShipment, which only ever dispatches
|
||||
* OrderDelivered — deriving "was this delivered" and acting on it by
|
||||
* writing `status` are deliberately two different listeners.
|
||||
*
|
||||
* Guarded to only fire from 'dispatched' — a duplicate/late Delivered
|
||||
* checkpoint, or an order a manual action already moved past, is a
|
||||
* silent no-op.
|
||||
*/
|
||||
class AdvanceFulfillmentOnDelivered
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderStatusWriter $writer,
|
||||
) {}
|
||||
|
||||
public function handle(OrderDelivered $event): void
|
||||
{
|
||||
$order = $event->order;
|
||||
|
||||
if ($order->status !== 'dispatched') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->writer->write($order, 'delivered', self::class);
|
||||
}
|
||||
}
|
||||
@@ -5,43 +5,50 @@ namespace Modules\Core\Order\Listeners;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||
use Modules\Core\Order\Enums\PaymentStatus;
|
||||
use Modules\Core\Order\Services\OrderStatusFlow;
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
use Modules\Core\Order\Support\OrderStatus;
|
||||
use Modules\Core\Payment\Events\PaymentAuthorized;
|
||||
use Modules\Core\Payment\Events\PaymentCaptured;
|
||||
use Modules\Core\Payment\Events\PaymentRefunded;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
use Modules\Core\Payment\Services\PaymentMethodCache;
|
||||
|
||||
/**
|
||||
* The only place an Order's status column is written in reaction to a
|
||||
* payment outcome. Registered against PaymentCaptured, PaymentAuthorized,
|
||||
* AND PaymentRefunded (see OrderServiceProvider) — same handler for all
|
||||
* three, differing only in which PaymentMethod column decides the
|
||||
* resulting status and, for a refund, which PaymentMethod row that even
|
||||
* is (see resolvePaymentMethod()).
|
||||
* Registered against PaymentCaptured, PaymentAuthorized, AND
|
||||
* PaymentRefunded (see OrderServiceProvider).
|
||||
*
|
||||
* PaymentCaptured writes both Order::paid/paid_at (via
|
||||
* OrderStatusWriter::markPaid()) AND advances `status` out of
|
||||
* 'awaiting_payment' to the next step in the order's flow (see
|
||||
* OrderStatusFlow::nextOptions()) — re-confirmed with the user: a
|
||||
* captured payment, manual or via Stripe's webhook, should never leave an
|
||||
* order sitting at 'awaiting_payment'. Only fires when status is still
|
||||
* exactly 'awaiting_payment', so a duplicate/delayed capture event never
|
||||
* regresses an order staff already advanced further. PaymentAuthorized
|
||||
* only marks paid — an authorization is not yet captured funds, so
|
||||
* status stays put until the actual capture.
|
||||
*
|
||||
* A refund still moves `status` (returned -> refunded/partially_refunded)
|
||||
* — refunds are a normal step in Modules\Core\Order\Services\
|
||||
* OrderStatusFlow's own sequence, unlike captures. Derives
|
||||
* Refunded/PartialRefund from Modules\Core\Order\Support\OrderStatus::
|
||||
* payment() — the existing, unchanged derived-enum logic, reused rather
|
||||
* than reimplemented.
|
||||
*
|
||||
* Reads $event->context['order_id'] to find which Order this outcome
|
||||
* belongs to — Payment has no concept of an Order, so this is the one
|
||||
* place that context key gets consumed on the Order side (Payment's own
|
||||
* StripePaymentDriver reads $context['order_id'] independently, for its
|
||||
* own unrelated correlation need — see that class's rememberIntent()).
|
||||
* belongs to — Payment has no concept of an Order.
|
||||
*
|
||||
* Loads and saves the model (not a bulk ::whereKey()->update()) so
|
||||
* Order::observe()'s updated() hook fires and OrderStatusUpdated goes out
|
||||
* the same as any other status write — see that event's own docblock for
|
||||
* why it's meant to fire "regardless of what wrote it."
|
||||
* Dispatches Checkout\Events\OrderPlaced itself, once placed_at is set.
|
||||
* Never fires from the PaymentRefunded path — a refund can only ever
|
||||
* happen after an order was already placed.
|
||||
*
|
||||
* Dispatches Checkout\Events\OrderPlaced itself, once placed_at is set —
|
||||
* see that event's own docblock for why this, not CheckoutService, is now
|
||||
* the dispatch point. Never fires from the PaymentRefunded path — a
|
||||
* refund can only ever happen after an order was already placed.
|
||||
*
|
||||
* Deliberately does NOT react to PaymentVoided — see PaymentMethod's own
|
||||
* docblock for why there's no void_status column at all yet.
|
||||
* Deliberately does NOT react to PaymentVoided.
|
||||
*/
|
||||
class ApplyResolvedPaymentStatus
|
||||
{
|
||||
public function __construct(
|
||||
private readonly PaymentMethodCache $paymentMethods,
|
||||
private readonly OrderStatusWriter $writer,
|
||||
private readonly OrderStatusFlow $flow,
|
||||
) {}
|
||||
|
||||
public function handle(PaymentCaptured|PaymentAuthorized|PaymentRefunded $event): void
|
||||
@@ -54,59 +61,59 @@ class ApplyResolvedPaymentStatus
|
||||
|
||||
$order = Order::findOrFail($orderId);
|
||||
|
||||
$method = $this->resolvePaymentMethod($event, $order);
|
||||
$column = match (true) {
|
||||
$event instanceof PaymentCaptured => 'captured_status',
|
||||
$event instanceof PaymentAuthorized => 'authorized_status',
|
||||
$event instanceof PaymentRefunded => 'refunded_status',
|
||||
};
|
||||
$status = $method?->{$column};
|
||||
if ($event instanceof PaymentRefunded) {
|
||||
$this->applyRefund($order, $event);
|
||||
|
||||
if ($status === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$wasPlaced = ! blank($order->placed_at);
|
||||
|
||||
$order->update([
|
||||
'status' => $status,
|
||||
'placed_at' => $order->placed_at ?? now(),
|
||||
]);
|
||||
$this->writer->markPaid($order, $event::class);
|
||||
|
||||
if (! $wasPlaced && ! $event instanceof PaymentRefunded) {
|
||||
if ($event instanceof PaymentCaptured) {
|
||||
$this->advancePastAwaitingPayment($order, $event);
|
||||
}
|
||||
|
||||
if (! $wasPlaced) {
|
||||
$order->update(['placed_at' => $order->placed_at ?? now()]);
|
||||
Event::dispatch(new OrderPlaced($order));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PaymentCaptured/PaymentAuthorized carry $event->type as the
|
||||
* PaymentMethod.type that was actually charged — a direct lookup.
|
||||
*
|
||||
* PaymentRefunded's $event->type is the REFUND driver's own registry
|
||||
* key (e.g. 'bank-transfer' — see BankTransferPaymentDriver::refund()),
|
||||
* which may not correspond to any PaymentMethod row at all when the
|
||||
* admin refunded through a different driver than the one that took
|
||||
* the original payment (Payment\Support\TransactionDriverAdapter::
|
||||
* refundVia()). refunded_status is a business decision about the
|
||||
* ORIGINAL payment method, not the refund mechanism, so this instead
|
||||
* finds the order's earliest successful capture/intent transaction —
|
||||
* the actual payment the refund is reversing — and resolves that
|
||||
* transaction's own driver (a real PaymentMethod.type) instead.
|
||||
*/
|
||||
private function resolvePaymentMethod(PaymentCaptured|PaymentAuthorized|PaymentRefunded $event, Order $order): ?PaymentMethod
|
||||
private function advancePastAwaitingPayment(Order $order, PaymentCaptured $event): void
|
||||
{
|
||||
if (! $event instanceof PaymentRefunded) {
|
||||
return $this->paymentMethods->all()->firstWhere('type', $event->type);
|
||||
if ($order->status !== 'awaiting_payment') {
|
||||
return;
|
||||
}
|
||||
|
||||
$originalType = $order->transactions()
|
||||
->whereIn('type', ['capture', 'intent'])
|
||||
->where('success', true)
|
||||
->oldest('created_at')
|
||||
->value('driver');
|
||||
$next = $this->flow->nextOptions($order);
|
||||
$target = array_key_first($next);
|
||||
|
||||
return $originalType !== null
|
||||
? $this->paymentMethods->all()->firstWhere('type', $originalType)
|
||||
: null;
|
||||
if ($target !== null) {
|
||||
$this->writer->write($order, $target, $event::class);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires the refund Transaction row to already exist (Modules\Core\
|
||||
* Order\Listeners\RecordPaymentTransaction must run first — see
|
||||
* OrderServiceProvider's listener registration order for
|
||||
* PaymentRefunded), so the relation is refreshed here rather than
|
||||
* trusted from a possibly-stale $order instance.
|
||||
*/
|
||||
private function applyRefund(Order $order, PaymentRefunded $event): void
|
||||
{
|
||||
$order->load('transactions');
|
||||
|
||||
$target = match (OrderStatus::payment($order)) {
|
||||
PaymentStatus::Refunded => 'refunded',
|
||||
PaymentStatus::PartialRefund => 'partially_refunded',
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($target !== null && $order->status !== $target) {
|
||||
$this->writer->write($order, $target, $event::class);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Modules\Core\Order\Events\OrderCompleted;
|
||||
use Modules\Core\Order\Events\OrderPickedUp;
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
|
||||
/**
|
||||
* The store-pickup mirror of AdvanceFulfillmentOnDelivered — reacts to
|
||||
* OrderPickedUp (dispatched by Modules\Core\Order\Services\
|
||||
* OrderFulfillmentService::markPickedUp() the moment staff confirm the
|
||||
* customer collected the order) by moving `status` straight to
|
||||
* 'completed'. No return-window step for store-pickup orders, per the
|
||||
* business design — unlike the carrier branch, there is no 'delivered'
|
||||
* intermediate value on this path.
|
||||
*
|
||||
* Guarded to only fire from 'picked_up' — a duplicate dispatch (e.g. a
|
||||
* stale page re-submitting the action) is a silent no-op.
|
||||
*/
|
||||
class CompleteOrderOnPickedUp
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderStatusWriter $writer,
|
||||
) {}
|
||||
|
||||
public function handle(OrderPickedUp $event): void
|
||||
{
|
||||
$order = $event->order;
|
||||
|
||||
if ($order->status !== 'picked_up') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->writer->write($order, 'completed', self::class);
|
||||
|
||||
OrderCompleted::dispatch($order);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Lunar\Models\Product;
|
||||
use Lunar\Models\ProductVariant;
|
||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||
|
||||
/**
|
||||
* The only place ProductVariant::stock is written as a result of an order —
|
||||
* fires once per order regardless of capture_mode/driver, same reasoning as
|
||||
* Modules\Core\Order\Notifications\OrderPlacedNotification: OrderPlaced is
|
||||
* dispatched exactly once, from the one place an order's placed_at
|
||||
* actually gets set (Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus),
|
||||
* so this can't double-decrement across a capture/authorize/refund sequence
|
||||
* the way listening to PaymentCaptured directly could.
|
||||
*
|
||||
* Only decrements for `purchasable === 'in_stock'` variants — 'always' and
|
||||
* 'backorder' variants are deliberately allowed to sell past (or without
|
||||
* regard to) their stock count already (see ProductVariant::
|
||||
* canBeFulfilledAtQuantity()), so decrementing their stock would just make
|
||||
* that column an inaccurate, decreasingly-negative number with no purchasing
|
||||
* consequence. Only `OrderLine::type === 'physical'` lines are considered —
|
||||
* a digital line has no stock to decrement (ProductVariant::getType()).
|
||||
*
|
||||
* A single UPDATE per variant (`DB::table(...)->decrement()`), not a
|
||||
* read-then-write on the Eloquent model — avoids a lost-update race between
|
||||
* two orders decrementing the same variant concurrently, and skips
|
||||
* Modules\Core\Catalog\Services\ProductIndexer::stock's staleness gap for
|
||||
* the DB value itself even though the search index still only refreshes on
|
||||
* the next reindex event/nightly job (see that class's own docblock).
|
||||
*
|
||||
* Never lets stock go negative (`GREATEST(stock - qty, 0)` via a raw
|
||||
* expression) — an order can still be placed against a variant whose stock
|
||||
* was already fully consumed by another concurrent order (Lunar has no
|
||||
* stock-reservation step at cart/checkout time), so this is a best-effort
|
||||
* count, not a hard inventory guarantee.
|
||||
*/
|
||||
class DecrementStockOnOrderPlaced
|
||||
{
|
||||
public function handle(OrderPlaced $event): void
|
||||
{
|
||||
$lines = $event->order->lines()
|
||||
->where('type', 'physical')
|
||||
->where('purchasable_type', ProductVariant::morphName())
|
||||
->get(['purchasable_id', 'quantity']);
|
||||
|
||||
foreach ($lines as $line) {
|
||||
DB::table((new ProductVariant())->getTable())
|
||||
->where('id', $line->purchasable_id)
|
||||
->where('purchasable', 'in_stock')
|
||||
->update([
|
||||
'stock' => DB::raw('GREATEST(stock - '.(int) $line->quantity.', 0)'),
|
||||
]);
|
||||
}
|
||||
|
||||
$productIds = ProductVariant::whereIn('id', $lines->pluck('purchasable_id'))
|
||||
->pluck('product_id')
|
||||
->unique();
|
||||
|
||||
Product::whereIn('id', $productIds)->get()->each->searchable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Modules\Core\Order\Services\OrderStatusWriter;
|
||||
use Modules\Core\Shipping\Enums\TrackingStatus;
|
||||
use Modules\Core\Shipping\Events\ShipmentStatusUpdatedByCarrier;
|
||||
|
||||
/**
|
||||
* Wires TrackingStatus::Failed to the 'delivery_failed' status for the
|
||||
* first time — previously an unused enum case. Guarded to only fire from
|
||||
* 'dispatched': a stale/duplicate checkpoint, or an order a manual action
|
||||
* already moved past, is a silent no-op.
|
||||
*/
|
||||
class MarkDeliveryFailedOnCarrierCheckpoint
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderStatusWriter $writer,
|
||||
) {}
|
||||
|
||||
public function handle(ShipmentStatusUpdatedByCarrier $event): void
|
||||
{
|
||||
if ($event->shipmentInfo->status !== TrackingStatus::Failed) {
|
||||
return;
|
||||
}
|
||||
|
||||
$order = $event->shipmentInfo->shipment->order;
|
||||
|
||||
if (! $order || $order->status !== 'dispatched') {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->writer->write($order, 'delivery_failed', self::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Listeners;
|
||||
|
||||
use Modules\Core\Order\Events\OrderPaidChanged;
|
||||
use Modules\Core\Order\Events\OrderStatusChanged;
|
||||
use Modules\Core\Order\Services\OrderStatusTransitionRecorder;
|
||||
|
||||
/**
|
||||
* The one place order_status_transitions rows actually get written —
|
||||
* listens to OrderStatusChanged (every write of the single `status`
|
||||
* column, via Modules\Core\Order\Services\OrderStatusWriter::write()) and
|
||||
* OrderPaidChanged (every write of Order::paid, via
|
||||
* OrderStatusWriter::markPaid()). paid isn't really a "status", but gets
|
||||
* one consistent audit trail entry ('paid', with a null from_status)
|
||||
* rather than a second, separate table.
|
||||
*/
|
||||
class RecordStatusTransition
|
||||
{
|
||||
public function __construct(
|
||||
private readonly OrderStatusTransitionRecorder $recorder,
|
||||
) {}
|
||||
|
||||
public function handleStatusChanged(OrderStatusChanged $event): void
|
||||
{
|
||||
$this->recorder->record($event->order, $event->previousStatus, $event->newStatus, $event->causeClass);
|
||||
}
|
||||
|
||||
public function handlePaidChanged(OrderPaidChanged $event): void
|
||||
{
|
||||
$this->recorder->record($event->order, null, 'paid', $event->causeClass);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Lunar\Models\Order;
|
||||
|
||||
/**
|
||||
* One append-only row per write to Order::status (plus one synthetic
|
||||
* 'paid' entry per Order::paid write — see
|
||||
* Modules\Core\Order\Listeners\RecordStatusTransition) — see
|
||||
* database/migrations/2026_09_11_000002_create_order_status_transitions_table.php
|
||||
* and Modules\Core\Order\Services\OrderStatusTransitionRecorder, which is
|
||||
* the only thing that ever creates a row. Never updated after creation —
|
||||
* $timestamps is disabled since there's no updated_at column and
|
||||
* created_at is DB-defaulted (`useCurrent()`), not Eloquent-managed.
|
||||
*/
|
||||
class OrderStatusTransition extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
public function order(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Notifications;
|
||||
|
||||
use Illuminate\Notifications\AnonymousNotifiable;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Support\Facades\Notification as NotificationFacade;
|
||||
use Modules\Core\Notification\BaseNotification;
|
||||
use Modules\Core\Order\Events\OrderCompleted;
|
||||
|
||||
class OrderCompletedNotification extends BaseNotification
|
||||
{
|
||||
public function __construct(private readonly OrderCompleted $event) {}
|
||||
|
||||
public static function getKey(): string
|
||||
{
|
||||
return 'order.completed.customer.mail';
|
||||
}
|
||||
|
||||
public static function listensTo(): string
|
||||
{
|
||||
return OrderCompleted::class;
|
||||
}
|
||||
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function notifiable(): AnonymousNotifiable
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
$email = $order->billingAddress?->contact_email ?? $order->shippingAddress?->contact_email;
|
||||
|
||||
return NotificationFacade::route('mail', $email);
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): MailMessage
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
return (new MailMessage)
|
||||
->subject(__('Your order :reference is complete', ['reference' => $order->reference]))
|
||||
->view('core::order.notifications.completed', [
|
||||
'reference' => $order->reference,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Notifications;
|
||||
|
||||
use Illuminate\Notifications\AnonymousNotifiable;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Support\Facades\Notification as NotificationFacade;
|
||||
use Modules\Core\Notification\BaseNotification;
|
||||
use Modules\Core\Order\Events\OrderDispatched;
|
||||
|
||||
/**
|
||||
* Fills a real, previously-unfilled customer-communication gap — before
|
||||
* this redesign nothing notified a customer when their carrier order left
|
||||
* the building at all.
|
||||
*/
|
||||
class OrderDispatchedNotification extends BaseNotification
|
||||
{
|
||||
public function __construct(private readonly OrderDispatched $event) {}
|
||||
|
||||
public static function getKey(): string
|
||||
{
|
||||
return 'order.dispatched.customer.mail';
|
||||
}
|
||||
|
||||
public static function listensTo(): string
|
||||
{
|
||||
return OrderDispatched::class;
|
||||
}
|
||||
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function notifiable(): AnonymousNotifiable
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
$email = $order->billingAddress?->contact_email ?? $order->shippingAddress?->contact_email;
|
||||
|
||||
return NotificationFacade::route('mail', $email);
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): MailMessage
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
return (new MailMessage)
|
||||
->subject(__('Your order :reference is on its way', ['reference' => $order->reference]))
|
||||
->view('core::order.notifications.dispatched', [
|
||||
'reference' => $order->reference,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Notifications;
|
||||
|
||||
use Illuminate\Notifications\AnonymousNotifiable;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Support\Facades\Notification as NotificationFacade;
|
||||
use Modules\Core\Notification\BaseNotification;
|
||||
use Modules\Core\Order\Events\OrderReadyForPickup;
|
||||
|
||||
/**
|
||||
* "Your order is ready to collect" — listens to the specific
|
||||
* OrderReadyForPickup event (dispatched by Modules\Core\Shipping\
|
||||
* Extensions\OrderViewExtension's "Mark Ready" action, store-pickup
|
||||
* branch only), not the generic OrderStatusUpdated. Modules\Core\Order\
|
||||
* Notifications\OrderStatusUpdatedNotification still separately
|
||||
* suppresses itself for the legacy 'ready-for-pickup' status string, kept
|
||||
* defensively even though nothing writes that literal value to
|
||||
* Order::status anymore after this redesign.
|
||||
*/
|
||||
class OrderPickupReadyNotification extends BaseNotification
|
||||
{
|
||||
public function __construct(private readonly OrderReadyForPickup $event) {}
|
||||
|
||||
public static function getKey(): string
|
||||
{
|
||||
return 'order.pickup_ready.customer.mail';
|
||||
}
|
||||
|
||||
public static function listensTo(): string
|
||||
{
|
||||
return OrderReadyForPickup::class;
|
||||
}
|
||||
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function notifiable(): AnonymousNotifiable
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
$email = $order->billingAddress?->contact_email ?? $order->shippingAddress?->contact_email;
|
||||
|
||||
return NotificationFacade::route('mail', $email);
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): MailMessage
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
return (new MailMessage)
|
||||
->subject(__('Your order :reference is ready for pickup', ['reference' => $order->reference]))
|
||||
->view('core::order.notifications.pickup-ready', [
|
||||
'reference' => $order->reference,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Order\Notifications;
|
||||
|
||||
use Illuminate\Notifications\AnonymousNotifiable;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Support\Facades\Notification as NotificationFacade;
|
||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||
use Modules\Core\Notification\BaseNotification;
|
||||
|
||||
/**
|
||||
* The order confirmation email — fires once, for every capture_mode and
|
||||
* driver alike (Stripe, offline, bank-transfer), since OrderPlaced is
|
||||
* dispatched from the one place an order's placed_at actually gets set
|
||||
* (Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus), not from a
|
||||
* driver-specific event like OrderCaptured. Before this existed, an
|
||||
* offline/bank-transfer order got no placement email at all — only a
|
||||
* Stripe (auto-captured) order did, via OrderCapturedNotification, which is
|
||||
* a different concern (payment confirmation, not order confirmation) that
|
||||
* happens to fire at the same moment for that one driver.
|
||||
*/
|
||||
class OrderPlacedNotification extends BaseNotification
|
||||
{
|
||||
public function __construct(private readonly OrderPlaced $event) {}
|
||||
|
||||
public static function getKey(): string
|
||||
{
|
||||
return 'order.placed.customer.mail';
|
||||
}
|
||||
|
||||
public static function listensTo(): string
|
||||
{
|
||||
return OrderPlaced::class;
|
||||
}
|
||||
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
public function notifiable(): AnonymousNotifiable
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
$email = $order->billingAddress?->contact_email ?? $order->shippingAddress?->contact_email;
|
||||
|
||||
return NotificationFacade::route('mail', $email);
|
||||
}
|
||||
|
||||
public function toMail(object $notifiable): MailMessage
|
||||
{
|
||||
$order = $this->event->order;
|
||||
|
||||
return (new MailMessage)
|
||||
->subject(__('Your order :reference is confirmed', ['reference' => $order->reference]))
|
||||
->view('core::order.notifications.placed', [
|
||||
'reference' => $order->reference,
|
||||
'total' => $order->total->formatted,
|
||||
'lines' => $order->lines,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,20 @@ class OrderStatusUpdatedNotification extends BaseNotification
|
||||
return OrderStatusUpdated::class;
|
||||
}
|
||||
|
||||
/**
|
||||
* 'ready-for-pickup' has its own, richer notification
|
||||
* (Modules\Core\Order\Notifications\OrderPickupReadyNotification) —
|
||||
* both listen to the same OrderStatusUpdated event via
|
||||
* NotificationRegistry, so without this the customer would get two
|
||||
* emails for that one transition. Returning no channels is the
|
||||
* standard Laravel way to suppress a notification outright.
|
||||
*/
|
||||
public function via(object $notifiable): array
|
||||
{
|
||||
if ($this->event->newStatus === 'ready-for-pickup') {
|
||||
return [];
|
||||
}
|
||||
|
||||
return ['mail'];
|
||||
}
|
||||
|
||||
|
||||
@@ -5,18 +5,32 @@ namespace Modules\Core\Order\Observers;
|
||||
use Lunar\Models\Order;
|
||||
use Modules\Core\Order\Events\OrderStatusUpdated;
|
||||
|
||||
/**
|
||||
* Generically dispatches OrderStatusUpdated for ANY write to `status`,
|
||||
* regardless of what wrote it (Modules\Core\Order\Services\
|
||||
* OrderStatusWriter, artisan tinker, a future API) — the general-purpose
|
||||
* hook notifications listen to. OrderStatusWriter separately dispatches
|
||||
* its own OrderStatusChanged (carrying $causeClass, which this event does
|
||||
* not) for the audit trail — see Modules\Core\Order\Listeners\
|
||||
* RecordStatusTransition.
|
||||
*
|
||||
* Does NOT try to generically watch Order::paid — an earlier design had
|
||||
* this observer thread a "what caused this" value through a runtime
|
||||
* $order->statusTransitionCause property, abandoned because
|
||||
* Lunar\Models\Order's $guarded = [] means Eloquent tries to persist any
|
||||
* property set that way as a real column. OrderStatusWriter::markPaid()
|
||||
* dispatches OrderPaidChanged directly instead.
|
||||
*/
|
||||
class OrderObserver
|
||||
{
|
||||
public function updated(Order $order): void
|
||||
{
|
||||
if (! $order->wasChanged('status')) {
|
||||
return;
|
||||
if ($order->wasChanged('status')) {
|
||||
OrderStatusUpdated::dispatch(
|
||||
$order,
|
||||
$order->getOriginal('status'),
|
||||
$order->status,
|
||||
);
|
||||
}
|
||||
|
||||
OrderStatusUpdated::dispatch(
|
||||
$order,
|
||||
$order->getOriginal('status'),
|
||||
$order->status,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,8 @@ class TransactionRecorder
|
||||
'reference' => $result->reference,
|
||||
'status' => $result->status->name,
|
||||
'notes' => $result->failureReason,
|
||||
'card_type' => $result->meta['card_type'] ?? null,
|
||||
'last_four' => $result->meta['last_four'] ?? null,
|
||||
'meta' => $result->meta,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ use Modules\Core\Payment\Events\PaymentRefunded;
|
||||
* chooses this driver explicitly in the refund action, independent of
|
||||
* which driver the original payment went through (see
|
||||
* Payment\Support\TransactionDriverAdapter::refundVia() and
|
||||
* Order\Filament\Extensions\OrderRefundActionsExtension). pay() exists so
|
||||
* Order\Filament\Extensions\OrderActionsExtension). pay() exists so
|
||||
* the same driver also covers receiving a payment by bank transfer, but
|
||||
* the admin UI for that (bank reference, notes, proof-of-transfer upload)
|
||||
* is deliberately not built yet — see the follow-up work tracked from this
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Drivers;
|
||||
|
||||
use Illuminate\Support\Str;
|
||||
use Lunar\DataTypes\Price;
|
||||
use Modules\Core\Payment\Contracts\Configurable;
|
||||
use Modules\Core\Payment\Contracts\SupportsPay;
|
||||
use Modules\Core\Payment\DTOs\PaymentResult;
|
||||
use Modules\Core\Payment\Enums\PaymentResultStatus;
|
||||
|
||||
/**
|
||||
* Cash-on-delivery/cash-on-pickup — the shopper pays staff in person, at
|
||||
* delivery or pickup, not at checkout, and reconciliation can happen
|
||||
* anywhere from same-day to months later, entirely independent of the
|
||||
* order's fulfillment progress (this is WHY Order::paid is its own field,
|
||||
* not a status-sequence step — see Modules\Core\Order\Services\
|
||||
* OrderStatusFlow's own docblock).
|
||||
*
|
||||
* Unlike OfflinePaymentDriver (cash-in-hand, immediate capture), pay()
|
||||
* here must NOT dispatch PaymentCaptured — doing so would immediately
|
||||
* flip Order::paid via Modules\Core\Order\Listeners\
|
||||
* ApplyResolvedPaymentStatus, which is exactly wrong: no money has
|
||||
* changed hands yet. Returns PaymentResultStatus::Pending instead — the
|
||||
* documented convention for "unresolved" (see SupportsPay's own
|
||||
* docblock). ApplyResolvedPaymentStatus and RecordPaymentTransaction both
|
||||
* only listen to Captured/Authorized/Voided/Refunded, so a Pending result
|
||||
* triggers neither.
|
||||
*
|
||||
* Order::paid only ever becomes true for a COD order via staff explicitly
|
||||
* marking it received (Modules\Core\Order\Services\
|
||||
* OrderFulfillmentService::markPaid()), offered by the single "Update
|
||||
* Status" action at any time, independent of status.
|
||||
*/
|
||||
class CashOnDeliveryPaymentDriver implements Configurable, SupportsPay
|
||||
{
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function pay(string $type, Price $amount, array $data = [], array $context = []): PaymentResult
|
||||
{
|
||||
return new PaymentResult(
|
||||
status: PaymentResultStatus::Pending,
|
||||
reference: 'cod-'.Str::uuid(),
|
||||
amount: $amount,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,12 @@ use Modules\Core\Payment\Enums\PaymentResultStatus;
|
||||
use Modules\Core\Payment\Events\PaymentCaptured;
|
||||
|
||||
/**
|
||||
* Shared by every payment type with no real gateway to confirm against —
|
||||
* cash-in-hand, cash-on-delivery — where the shopper pays at pickup/on
|
||||
* delivery, not at checkout. There is no separate hold-then-settle model
|
||||
* Cash-in-hand — a shopper paying in person at the moment of pickup, with
|
||||
* nothing left to reconcile afterward, so capture is immediate. NOT used
|
||||
* for cash-on-delivery, which has its own Modules\Core\Payment\Drivers\
|
||||
* CashOnDeliveryPaymentDriver — COD payment happens at an unpredictable
|
||||
* later time (same-day to months), so it must not capture immediately the
|
||||
* way this driver does. There is no separate hold-then-settle model
|
||||
* (SupportsAuthorization/SupportsCaptures/SupportsVoids) and no async
|
||||
* resolution (HandlesPaymentCallback) — pay() decides success immediately
|
||||
* and dispatches PaymentCaptured before returning.
|
||||
|
||||
@@ -4,9 +4,6 @@ namespace Modules\Core\Payment\Drivers;
|
||||
|
||||
use Lunar\DataTypes\Price;
|
||||
use Lunar\Models\Currency;
|
||||
use Lunar\Stripe\Facades\Stripe;
|
||||
use Lunar\Stripe\Managers\StripeManager;
|
||||
use Lunar\Stripe\Models\StripePaymentIntent;
|
||||
use Modules\Core\Payment\Contracts\Configurable;
|
||||
use Modules\Core\Payment\Contracts\HandlesPaymentCallback;
|
||||
use Modules\Core\Payment\Contracts\SupportsAuthorization;
|
||||
@@ -26,17 +23,20 @@ use Modules\Core\Payment\Events\PaymentRefundFailed;
|
||||
use Modules\Core\Payment\Events\PaymentRefunded;
|
||||
use Modules\Core\Payment\Events\PaymentVoidFailed;
|
||||
use Modules\Core\Payment\Events\PaymentVoided;
|
||||
use Modules\Core\Payment\Models\StripePaymentIntent;
|
||||
use Modules\Core\Payment\Support\StripeManager;
|
||||
use Stripe\Exception\ApiErrorException;
|
||||
use Stripe\PaymentIntent;
|
||||
|
||||
/**
|
||||
* Talks to Stripe's PaymentIntent API directly — deliberately NOT via
|
||||
* Lunar\Stripe\Facades\Stripe::createIntent()/fetchOrCreateIntent(), which
|
||||
* take a Lunar\Models\Cart and derive amount/currency from it. Payment
|
||||
* must never receive a Cart (see docs/payments.md) — pay()/authorize()
|
||||
* already receive $amount explicitly as their own required Lunar Price
|
||||
* parameter (see PaymentResult's own docblock), the caller's job to
|
||||
* assemble, same as every other driver.
|
||||
* Lunar's own checkout flow (lunarphp/stripe, since removed — see
|
||||
* Modules\Core\Payment\Support\StripeManager's own docblock), which took a
|
||||
* Lunar\Models\Cart and derived amount/currency from it. Payment must
|
||||
* never receive a Cart (see docs/payments.md) — pay()/authorize() already
|
||||
* receive $amount explicitly as their own required Lunar Price parameter
|
||||
* (see PaymentResult's own docblock), the caller's job to assemble, same
|
||||
* as every other driver.
|
||||
*
|
||||
* Every amount that crosses this class's own boundary is converted right
|
||||
* there: Lunar's Price -> Stripe's minor-unit int going INTO a gateway
|
||||
@@ -45,12 +45,11 @@ use Stripe\PaymentIntent;
|
||||
* Nothing outside this class ever sees a Stripe-scaled integer.
|
||||
*
|
||||
* Correlating a later handleCallback() (a separate request — a webhook)
|
||||
* back to whatever $context identified this attempt is solved the same
|
||||
* way lunarphp/stripe's own StripePaymentType/ProcessStripeWebhook solve
|
||||
* it: real cart_id/order_id columns on Lunar\Stripe\Models\
|
||||
* StripePaymentIntent (a table already owned by lunarphp/stripe, already
|
||||
* shaped for exactly this), not a generic context blob. See
|
||||
* docs/payments.md "Async resolution" for the full reasoning.
|
||||
* back to whatever $context identified this attempt is solved via real
|
||||
* cart_id/order_id columns on Modules\Core\Payment\Models\
|
||||
* StripePaymentIntent (a table this app now owns outright, already shaped
|
||||
* for exactly this), not a generic context blob. See docs/payments.md
|
||||
* "Async resolution" for the full reasoning.
|
||||
*/
|
||||
class StripePaymentDriver implements
|
||||
Configurable,
|
||||
@@ -61,16 +60,18 @@ class StripePaymentDriver implements
|
||||
SupportsRefunds,
|
||||
HandlesPaymentCallback
|
||||
{
|
||||
public function __construct(
|
||||
private readonly StripeManager $stripe,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Same key lunarphp/stripe's own StripeManager reads its API key from
|
||||
* (Stripe::setApiKey(config('services.stripe.key'))) — no key, no
|
||||
* usable driver.
|
||||
* Same key StripeManager reads its API key from — no key, no usable
|
||||
* driver.
|
||||
*/
|
||||
public function isConfigured(): bool
|
||||
{
|
||||
return filled(config('services.stripe.key'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Atomic charge — capture_method: automatic. Stripe still frequently
|
||||
* confirms into requires_action/requires_confirmation rather than
|
||||
@@ -95,17 +96,27 @@ class StripePaymentDriver implements
|
||||
|
||||
private function createAndConfirm(string $type, Price $amount, array $data, array $context, string $captureMethod): PaymentResult
|
||||
{
|
||||
$params = [
|
||||
'amount' => StripeManager::toStripeAmount($amount->value, $amount->currency),
|
||||
'currency' => $amount->currency->code,
|
||||
'capture_method' => $captureMethod,
|
||||
'confirm' => true,
|
||||
// 'never' rather than the client-side paymentMethodTypes: ['card']
|
||||
// restriction alone — the storefront's Payment Element already
|
||||
// excludes every redirect-based method, but without this Stripe
|
||||
// still falls back to whatever's enabled in the Dashboard and
|
||||
// demands a return_url on confirm. Setting this unconditionally
|
||||
// (not only when no payment_method is given) matches the actual
|
||||
// flow: a payment_method is always supplied here.
|
||||
'automatic_payment_methods' => ['enabled' => true, 'allow_redirects' => 'never'],
|
||||
];
|
||||
|
||||
if (isset($data['payment_method'])) {
|
||||
$params['payment_method'] = $data['payment_method'];
|
||||
}
|
||||
|
||||
try {
|
||||
$paymentIntent = Stripe::getClient()->paymentIntents->create([
|
||||
'amount' => StripeManager::toStripeAmount($amount->value, $amount->currency),
|
||||
'currency' => $amount->currency->code,
|
||||
'capture_method' => $captureMethod,
|
||||
'confirm' => true,
|
||||
'payment_method' => $data['payment_method'] ?? null,
|
||||
'automatic_payment_methods' => isset($data['payment_method'])
|
||||
? null
|
||||
: ['enabled' => true],
|
||||
]);
|
||||
$paymentIntent = $this->stripe->getClient()->paymentIntents->create($params);
|
||||
} catch (ApiErrorException $e) {
|
||||
return $this->declined($type, $amount, $e, $context, authorizing: $captureMethod === 'manual');
|
||||
}
|
||||
@@ -119,7 +130,7 @@ class StripePaymentDriver implements
|
||||
{
|
||||
[$intentModel, $type, $context] = $this->resolveIntentModel($reference, $context, $data['type'] ?? '');
|
||||
|
||||
$paymentIntent = Stripe::getClient()->paymentIntents->retrieve($reference);
|
||||
$paymentIntent = $this->stripe->getClient()->paymentIntents->retrieve($reference);
|
||||
|
||||
$authorizing = $paymentIntent->capture_method === PaymentIntent::CAPTURE_METHOD_MANUAL;
|
||||
|
||||
@@ -127,7 +138,7 @@ class StripePaymentDriver implements
|
||||
// automatic capture_method, but Stripe stopped short of
|
||||
// capturing (rare, but the API contract allows it) — finish
|
||||
// the job pay() started.
|
||||
$paymentIntent = Stripe::getClient()->paymentIntents->capture($reference);
|
||||
$paymentIntent = $this->stripe->getClient()->paymentIntents->capture($reference);
|
||||
}
|
||||
|
||||
$intentModel?->update(['status' => $paymentIntent->status]);
|
||||
@@ -142,7 +153,7 @@ class StripePaymentDriver implements
|
||||
[$intentModel, $type, $context] = $this->resolveIntentModel($reference, $context);
|
||||
|
||||
try {
|
||||
$paymentIntent = Stripe::getClient()->paymentIntents->capture($reference, [
|
||||
$paymentIntent = $this->stripe->getClient()->paymentIntents->capture($reference, [
|
||||
'amount_to_capture' => StripeManager::toStripeAmount($amount->value, $amount->currency),
|
||||
]);
|
||||
} catch (ApiErrorException $e) {
|
||||
@@ -161,6 +172,7 @@ class StripePaymentDriver implements
|
||||
reference: $paymentIntent->id,
|
||||
amount: $amount,
|
||||
raw: $paymentIntent->toArray(),
|
||||
meta: $this->cardMetaFromIntent($paymentIntent),
|
||||
);
|
||||
|
||||
$paymentIntent->status === PaymentIntent::STATUS_SUCCEEDED
|
||||
@@ -175,7 +187,7 @@ class StripePaymentDriver implements
|
||||
[$intentModel, $type, $context] = $this->resolveIntentModel($reference, $context);
|
||||
|
||||
try {
|
||||
$paymentIntent = Stripe::getClient()->paymentIntents->cancel($reference);
|
||||
$paymentIntent = $this->stripe->getClient()->paymentIntents->cancel($reference);
|
||||
} catch (ApiErrorException $e) {
|
||||
$result = $this->failure($amount, $e, $reference);
|
||||
PaymentVoidFailed::dispatch($type, $result, $context);
|
||||
@@ -206,7 +218,7 @@ class StripePaymentDriver implements
|
||||
[$intentModel, $type, $context] = $this->resolveIntentModel($reference, $context);
|
||||
|
||||
try {
|
||||
$refund = Stripe::getClient()->refunds->create([
|
||||
$refund = $this->stripe->getClient()->refunds->create([
|
||||
'payment_intent' => $reference,
|
||||
'amount' => StripeManager::toStripeAmount($amount->value, $amount->currency),
|
||||
]);
|
||||
@@ -243,7 +255,7 @@ class StripePaymentDriver implements
|
||||
'order_id' => $context['order_id'] ?? null,
|
||||
'status' => $paymentIntent->status,
|
||||
'payment_type' => $type,
|
||||
'context' => json_encode($context),
|
||||
'context' => $context,
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -268,28 +280,10 @@ class StripePaymentDriver implements
|
||||
return [
|
||||
$intentModel,
|
||||
$intentModel?->payment_type ?? $typeFallback,
|
||||
$this->decodeContext($intentModel) ?? $context,
|
||||
$intentModel?->context ?? $context,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* StripePaymentIntent is a vendor model (lunarphp/stripe) with no cast
|
||||
* declared for our own 'context' column (added by boboko-core's own
|
||||
* migration, see database/migrations/..._add_context_to_stripe_
|
||||
* payment_intents.php) — we can't edit the vendor model to add one, so
|
||||
* decode manually here instead of assuming Eloquent already did it.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
private function decodeContext(?StripePaymentIntent $intentModel): ?array
|
||||
{
|
||||
if (! $intentModel || ! $intentModel->context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return json_decode($intentModel->context, associative: true) ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a live Stripe PaymentIntent's own amount/currency back
|
||||
* into Lunar's Price — the one place this class reads a Stripe
|
||||
@@ -331,6 +325,7 @@ class StripePaymentDriver implements
|
||||
amount: $amount,
|
||||
failureReason: $paymentIntent->last_payment_error->message ?? null,
|
||||
raw: $paymentIntent->toArray(),
|
||||
meta: $status === PaymentResultStatus::Pending ? [] : $this->cardMetaFromIntent($paymentIntent),
|
||||
continuation: $continuation,
|
||||
);
|
||||
|
||||
@@ -353,6 +348,40 @@ class StripePaymentDriver implements
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* card_type/last_four for Modules\Core\Order\Services\
|
||||
* TransactionRecorder to map onto Transaction (see PaymentResult::
|
||||
* $meta's own docblock) — same fields, same source
|
||||
* (payment_method_details on the underlying Charge) as lunarphp/
|
||||
* stripe's own StoreCharges, just reached via latest_charge instead of
|
||||
* an order-level charge list, since this driver has no Order/Cart to
|
||||
* enumerate charges from.
|
||||
*
|
||||
* @return array{card_type?: string, last_four?: string}
|
||||
*/
|
||||
private function cardMetaFromIntent(PaymentIntent $paymentIntent): array
|
||||
{
|
||||
$chargeId = $paymentIntent->latest_charge;
|
||||
|
||||
if (blank($chargeId)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$charge = $this->stripe->getCharge(is_string($chargeId) ? $chargeId : $chargeId->id);
|
||||
|
||||
$paymentType = collect($charge->payment_method_details)->keys()->first();
|
||||
$details = collect($charge->payment_method_details)->first();
|
||||
|
||||
if (blank($details)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return array_filter([
|
||||
'card_type' => $details['brand'] ?? $paymentType,
|
||||
'last_four' => $details['last4'] ?? null,
|
||||
], fn ($value) => filled($value));
|
||||
}
|
||||
|
||||
private function declined(string $type, Price $amount, ApiErrorException $e, array $context, bool $authorizing): PaymentResult
|
||||
{
|
||||
$result = $this->failure($amount, $e);
|
||||
|
||||
@@ -7,12 +7,12 @@ use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Modules\Core\Payment\Contracts\Configurable;
|
||||
use Modules\Core\Payment\Events\PaymentMethodsReordered;
|
||||
use Modules\Core\Payment\Filament\Resources\PaymentMethodResource\Pages\ListPaymentMethods;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
@@ -44,16 +44,16 @@ use Modules\Core\Payment\Services\PaymentMethodService;
|
||||
* already correct in the database by the time it fires.
|
||||
*
|
||||
* `driver_missing_at` (set by the `boboko:payment:sync-drivers` command
|
||||
* when a row's driver no longer resolves) is surfaced as its own table
|
||||
* when a row's driver no longer resolves) drives the "Driver status"
|
||||
* column, deliberately distinct from `enabled` — an admin needs to tell
|
||||
* "I turned this off" apart from "the driver code was removed" at a
|
||||
* glance, not have both look like the same disabled state.
|
||||
* "I turned this off" apart from "this driver isn't usable right now" at
|
||||
* a glance, not have both look like the same disabled state. That column
|
||||
* also folds in Configurable::isConfigured() (e.g. Stripe with no API key
|
||||
* set) — a class-resolves-but-isn't-usable state that CheckoutService::
|
||||
* getPaymentMethods() filters out identically to a missing driver, so an
|
||||
* admin needs the same at-a-glance warning for it, not just a silently
|
||||
* absent checkout option.
|
||||
*
|
||||
* `authorized_status` only appears in the form when `capture_mode` is
|
||||
* "Hold now, charge later" — it's simply unreachable for a "Charge
|
||||
* immediately" method (that mode only ever produces PaymentCaptured,
|
||||
* never PaymentAuthorized), so showing it unconditionally would just be
|
||||
* a confusing, always-irrelevant field for most methods.
|
||||
*/
|
||||
class PaymentMethodResource extends Resource
|
||||
{
|
||||
@@ -85,13 +85,12 @@ class PaymentMethodResource extends Resource
|
||||
IconColumn::make('driver_missing_at')
|
||||
->label('Driver status')
|
||||
->boolean()
|
||||
->trueIcon('heroicon-o-exclamation-triangle')
|
||||
->falseIcon('heroicon-o-check-circle')
|
||||
->trueColor('danger')
|
||||
->falseColor('success')
|
||||
->tooltip(fn (PaymentMethod $record) => $record->driver_missing_at
|
||||
? 'Driver not found as of '.$record->driver_missing_at->diffForHumans()
|
||||
: 'Driver resolves correctly'),
|
||||
->state(fn (PaymentMethod $record) => ! $record->driver_missing_at && static::driverIsConfigured($record->driver))
|
||||
->trueIcon('heroicon-o-check-circle')
|
||||
->falseIcon('heroicon-o-exclamation-triangle')
|
||||
->trueColor('success')
|
||||
->falseColor('danger')
|
||||
->tooltip(fn (PaymentMethod $record) => static::driverStatusTooltip($record)),
|
||||
ToggleColumn::make('enabled')
|
||||
->label('Enabled')
|
||||
->updateStateUsing(fn (PaymentMethod $record, $state) => app(PaymentMethodService::class)
|
||||
@@ -146,13 +145,6 @@ class PaymentMethodResource extends Resource
|
||||
->default('pay')
|
||||
->live()
|
||||
->required(),
|
||||
static::getOrderStatusSelect('captured_status', 'Order status once paid')
|
||||
->helperText('Applied the moment a payment is fully charged.'),
|
||||
static::getOrderStatusSelect('authorized_status', 'Order status once held')
|
||||
->helperText('Applied the moment a hold is placed, before it\'s charged.')
|
||||
->visible(fn (Get $get) => $get('capture_mode') === 'authorize'),
|
||||
static::getOrderStatusSelect('refunded_status', 'Order status once refunded')
|
||||
->helperText('Applied when a payment taken through this method is refunded — even if the refund itself is processed through a different method.'),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -164,24 +156,6 @@ class PaymentMethodResource extends Resource
|
||||
->required();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lunar's own Order::status is a plain, admin-extensible string
|
||||
* (config('lunar.orders.statuses')) rather than a fixed enum —
|
||||
* deliberately so a store can add its own custom status without a
|
||||
* code change (see docs/payments.md). This Select still reads from
|
||||
* that same open-ended list, just so an admin picks a real status
|
||||
* instead of typing a slug from memory.
|
||||
*/
|
||||
private static function getOrderStatusSelect(string $name, string $label): Select
|
||||
{
|
||||
return Select::make($name)
|
||||
->label($label)
|
||||
->options(collect(config('lunar.orders.statuses', []))
|
||||
->map(fn (array $status) => $status['label'] ?? $status)
|
||||
->all())
|
||||
->native(false);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
@@ -206,7 +180,7 @@ class PaymentMethodResource extends Resource
|
||||
->icon('heroicon-o-pencil-square')
|
||||
->schema(static::getFormComponents())
|
||||
->fillForm(fn (PaymentMethod $record) => $record->only([
|
||||
'name', 'type', 'driver', 'capture_mode', 'captured_status', 'authorized_status', 'refunded_status',
|
||||
'name', 'type', 'driver', 'capture_mode',
|
||||
]))
|
||||
->action(fn (PaymentMethod $record, array $data) => app(PaymentMethodService::class)->update($record, $data));
|
||||
}
|
||||
@@ -260,4 +234,33 @@ class PaymentMethodResource extends Resource
|
||||
|
||||
return app(PaymentDriverRegistry::class)->label($key) ?? $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* False for a missing driver too, since Configurable::isConfigured()
|
||||
* has nothing to ask in that case — driverStatusTooltip() below is
|
||||
* what tells the two reasons apart for the admin.
|
||||
*/
|
||||
private static function driverIsConfigured(?string $key): bool
|
||||
{
|
||||
$driver = $key ? app(PaymentDriverRegistry::class)->resolve($key) : null;
|
||||
|
||||
if (! $driver instanceof Configurable) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $driver->isConfigured();
|
||||
}
|
||||
|
||||
private static function driverStatusTooltip(PaymentMethod $record): string
|
||||
{
|
||||
if ($record->driver_missing_at) {
|
||||
return 'Driver not found as of '.$record->driver_missing_at->diffForHumans();
|
||||
}
|
||||
|
||||
if (! static::driverIsConfigured($record->driver)) {
|
||||
return 'Driver resolves, but is missing required configuration (e.g. an API key) — it will not be offered at checkout.';
|
||||
}
|
||||
|
||||
return 'Driver resolves correctly and is fully configured.';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,18 +9,17 @@ use Modules\Core\Payment\Drivers\StripePaymentDriver;
|
||||
use Stripe\Webhook;
|
||||
|
||||
/**
|
||||
* A boboko-owned webhook endpoint for Stripe — deliberately NOT
|
||||
* lunarphp/stripe's own route (vendor/lunarphp/stripe/routes/webhooks.php),
|
||||
* which dispatches into Lunar's own Payments::driver('stripe') flow (the
|
||||
* flow StripePaymentDriver was built to replace, see that class's own
|
||||
* docblock). Signature verification is handled by
|
||||
* Lunar\Stripe\Http\Middleware\StripeWebhookMiddleware, registered on this
|
||||
* route (see src/Payment/routes/webhooks.php) — pure Stripe SDK
|
||||
* verification + event-type filtering, safe to reuse even though this
|
||||
* controller never touches the rest of that vendor package's flow. This
|
||||
* controller verifies the signature again itself (Webhook::constructEvent())
|
||||
* to get the constructed Event object — the middleware doesn't stash one
|
||||
* anywhere reusable, it only gates the request through.
|
||||
* A boboko-owned webhook endpoint for Stripe — never went through Lunar's
|
||||
* own Payments::driver('stripe') flow (the flow StripePaymentDriver was
|
||||
* built to replace, see that class's own docblock), and lunarphp/stripe
|
||||
* has since been removed entirely (see Modules\Core\Payment\Support\
|
||||
* StripeManager's own docblock). Signature verification is handled by
|
||||
* Modules\Core\Payment\Http\Middleware\StripeWebhookMiddleware, registered
|
||||
* on this route (see src/Payment/routes/webhooks.php) — pure Stripe SDK
|
||||
* verification + event-type filtering. This controller verifies the
|
||||
* signature again itself (Webhook::constructEvent()) to get the
|
||||
* constructed Event object — the middleware doesn't stash one anywhere
|
||||
* reusable, it only gates the request through.
|
||||
*
|
||||
* Resolves the driver directly by class, not via
|
||||
* Modules\Core\Payment\Services\PaymentDriverRegistry — this endpoint is
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Stripe\Exception\SignatureVerificationException;
|
||||
use Stripe\Exception\UnexpectedValueException;
|
||||
use Stripe\Webhook;
|
||||
|
||||
/**
|
||||
* First-party replacement for Lunar\Stripe\Http\Middleware\
|
||||
* StripeWebhookMiddleware (lunarphp/stripe removed — see
|
||||
* Modules\Core\Payment\Support\StripeManager's own docblock). Registered
|
||||
* on the same route as before (src/Payment/routes/webhooks.php) purely to
|
||||
* gate malformed/irrelevant requests before they reach
|
||||
* Modules\Core\Payment\Http\Controllers\StripeWebhookController, which
|
||||
* re-verifies the signature itself (see that controller's own docblock)
|
||||
* to get the constructed Event object — this duplication predates the
|
||||
* package removal and is left unchanged here.
|
||||
*/
|
||||
class StripeWebhookMiddleware
|
||||
{
|
||||
public function handle(Request $request, ?Closure $next = null)
|
||||
{
|
||||
$secret = config('services.stripe.webhooks.lunar');
|
||||
$stripeSig = $request->header('Stripe-Signature');
|
||||
|
||||
try {
|
||||
$event = Webhook::constructEvent(
|
||||
$request->getContent(),
|
||||
$stripeSig,
|
||||
$secret
|
||||
);
|
||||
} catch (UnexpectedValueException|SignatureVerificationException $e) {
|
||||
abort(400, $e->getMessage());
|
||||
}
|
||||
|
||||
if (! in_array(
|
||||
$event->type,
|
||||
[
|
||||
'payment_intent.payment_failed',
|
||||
'payment_intent.succeeded',
|
||||
]
|
||||
)) {
|
||||
return response('', 200);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Model;
|
||||
* creatable/deletable, same split Modules\Core\Shipping's own
|
||||
* shipping_methods table already has (see docs/payments.md):
|
||||
* - type: unique, machine-facing slug (Cart::meta['payment_method'],
|
||||
* ApplyCashOnDeliveryFee's lookup key, every Payment event's $type).
|
||||
* ApplyPaymentMethodFee's lookup key, every Payment event's $type).
|
||||
* - name: admin-facing label.
|
||||
* - driver: the Modules\Core\Payment\Services\PaymentDriverRegistry key
|
||||
* — NOT the same as `type`, and not unique (two rows can share one
|
||||
@@ -18,16 +18,6 @@ use Illuminate\Database\Eloquent\Model;
|
||||
* - capture_mode: 'pay' or 'authorize' — which SupportsPay/
|
||||
* SupportsAuthorization method CheckoutService::initiatePayment()
|
||||
* calls for this row.
|
||||
* - captured_status / authorized_status / refunded_status: the
|
||||
* Order::status value Modules\Core\Order\Listeners\
|
||||
* ApplyResolvedPaymentStatus applies on a PaymentCaptured/
|
||||
* PaymentAuthorized/PaymentRefunded event. For a refund, this is
|
||||
* always the ORIGINAL payment method's row (the one the customer
|
||||
* actually paid with), never the driver the refund itself was routed
|
||||
* through (Payment\Support\TransactionDriverAdapter::refundVia() may
|
||||
* use a different one entirely — e.g. a cash-on-delivery order
|
||||
* refunded via a Bank Transfer driver with no PaymentMethod row of
|
||||
* its own) — see that listener's own docblock.
|
||||
* - position: admin-controlled display/checkout order.
|
||||
* - driver_missing_at: set by `payment:sync-drivers` when `driver` no
|
||||
* longer resolves via the registry — separate from `enabled`, so a
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Models;
|
||||
|
||||
use Lunar\Base\BaseModel;
|
||||
|
||||
/**
|
||||
* First-party replacement for Lunar\Stripe\Models\StripePaymentIntent (the
|
||||
* lunarphp/stripe package was removed — see Modules\Core\Payment\Support\
|
||||
* StripeManager's own docblock). Same table (lunar_stripe_payment_intents,
|
||||
* created by database/migrations/..._create_stripe_payment_intents_table,
|
||||
* a first-party copy of the vendor migration), including the app-owned
|
||||
* `context`/`payment_type` columns Modules\Core\Payment\Drivers\
|
||||
* StripePaymentDriver::handleCallback() needs to recover $context/$type
|
||||
* across the separate request a webhook arrives on — see that class's own
|
||||
* docblock for "Async resolution".
|
||||
*
|
||||
* Extends Lunar\Base\BaseModel (from lunarphp/core, unaffected by removing
|
||||
* lunarphp/stripe) purely so table-prefix resolution
|
||||
* (config('lunar.database.table_prefix')) stays identical to how the
|
||||
* vendor model resolved it — this table was created under that prefix.
|
||||
*/
|
||||
class StripePaymentIntent extends BaseModel
|
||||
{
|
||||
protected $table = 'stripe_payment_intents';
|
||||
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'context' => 'array',
|
||||
];
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Pipelines\Cart;
|
||||
|
||||
use Closure;
|
||||
use Lunar\DataTypes\Price;
|
||||
use Lunar\Models\Contracts\Cart as CartContract;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
final class ApplyCashOnDeliveryFee
|
||||
{
|
||||
/**
|
||||
* Called just before cart totals are calculated.
|
||||
*
|
||||
* @param Closure(CartContract): mixed $next
|
||||
*/
|
||||
public function handle(CartContract $cart, Closure $next): mixed
|
||||
{
|
||||
if (($cart->meta['payment_method'] ?? null) === 'cash-on-delivery') {
|
||||
$fee = (int) (PaymentMethod::where('type', 'cash-on-delivery')->value('data->fee') ?? 0);
|
||||
|
||||
$cart->shippingTotal = new Price(
|
||||
($cart->shippingTotal?->value ?? 0) + $fee,
|
||||
$cart->currency,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
return $next($cart);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Pipelines\Cart;
|
||||
|
||||
use Closure;
|
||||
use Lunar\Base\ValueObjects\Cart\ShippingBreakdownItem;
|
||||
use Lunar\DataTypes\Price;
|
||||
use Lunar\Models\Contracts\Cart as CartContract;
|
||||
use Modules\Core\Payment\Models\PaymentMethod;
|
||||
|
||||
final class ApplyPaymentMethodFee
|
||||
{
|
||||
/**
|
||||
* Called just before cart totals are calculated, right after
|
||||
* Lunar\Pipelines\Cart\ApplyShipping. Generic across every
|
||||
* Modules\Core\Payment\Models\PaymentMethod row, not just cash on
|
||||
* delivery — whichever type the shopper picked (Cart::meta
|
||||
* ['payment_method']), its own `data.fee` (set via the Filament "Edit
|
||||
* fee" action) is applied if present, no matter its slug/name/driver.
|
||||
*
|
||||
* Must add the fee as its own Lunar\Base\ValueObjects\Cart\
|
||||
* ShippingBreakdownItem on $cart->shippingBreakdown rather than
|
||||
* bumping $cart->shippingTotal directly — the later Lunar\Pipelines\
|
||||
* Cart\CalculateTax step unconditionally recomputes shippingTotal
|
||||
* (and shipping tax) from shippingBreakdown's item sum, so a value
|
||||
* set only on the plain property is silently discarded before the
|
||||
* cart finishes calculating.
|
||||
*
|
||||
* @param Closure(CartContract): mixed $next
|
||||
*/
|
||||
public function handle(CartContract $cart, Closure $next): mixed
|
||||
{
|
||||
$type = $cart->meta['payment_method'] ?? null;
|
||||
|
||||
if ($type) {
|
||||
$fee = (int) (PaymentMethod::where('type', $type)->first()?->data['fee'] ?? 0);
|
||||
|
||||
if ($fee > 0) {
|
||||
$cart->shippingBreakdown->items->put('payment-method-fee', new ShippingBreakdownItem(
|
||||
name: 'Payment method fee',
|
||||
identifier: 'payment-method-fee',
|
||||
price: new Price($fee, $cart->currency, 1),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return $next($cart);
|
||||
}
|
||||
}
|
||||
@@ -70,8 +70,7 @@ class PaymentMethodService
|
||||
public function delete(PaymentMethod $method): void
|
||||
{
|
||||
$snapshot = $method->only([
|
||||
'id', 'type', 'name', 'driver', 'capture_mode',
|
||||
'captured_status', 'authorized_status', 'position', 'enabled',
|
||||
'id', 'type', 'name', 'driver', 'capture_mode', 'position', 'enabled',
|
||||
]);
|
||||
|
||||
$method->delete();
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Payment\Support;
|
||||
|
||||
use Lunar\Models\Contracts\Currency as CurrencyContract;
|
||||
use Stripe\Charge;
|
||||
use Stripe\StripeClient;
|
||||
|
||||
/**
|
||||
* First-party replacement for Lunar\Stripe\Facades\Stripe +
|
||||
* Lunar\Stripe\Managers\StripeManager — lunarphp/stripe was removed once
|
||||
* Modules\Core\Payment\Drivers\StripePaymentDriver already replaced every
|
||||
* bit of Lunar's own Stripe payment flow (see that class's own docblock);
|
||||
* all that remained load-bearing from the package was raw API-client
|
||||
* access and amount conversion, neither of which is Lunar-specific. Only
|
||||
* the methods StripePaymentDriver actually called are kept — no
|
||||
* fetchOrCreateIntent()/cart-bound helpers, which belonged to Lunar's own
|
||||
* (unused) checkout flow.
|
||||
*
|
||||
* getClient()/getCharge() call the Stripe SDK directly rather than going
|
||||
* through a facade — StripePaymentDriver resolves this class via the
|
||||
* container instead, same as every other dependency it takes.
|
||||
*/
|
||||
class StripeManager
|
||||
{
|
||||
public function getClient(): StripeClient
|
||||
{
|
||||
return new StripeClient([
|
||||
'api_key' => config('services.stripe.key'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function getCharge(string $chargeId): Charge
|
||||
{
|
||||
return $this->getClient()->charges->retrieve($chargeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zero-decimal currencies, per Stripe. The amount sent to Stripe is the
|
||||
* major unit amount as-is.
|
||||
*
|
||||
* @see https://docs.stripe.com/currencies#zero-decimal
|
||||
*/
|
||||
protected const ZERO_DECIMAL_CURRENCIES = [
|
||||
'bif', 'clp', 'djf', 'gnf', 'jpy', 'kmf', 'krw', 'mga', 'pyg',
|
||||
'rwf', 'ugx', 'vnd', 'vuv', 'xaf', 'xof', 'xpf',
|
||||
];
|
||||
|
||||
/**
|
||||
* Three-decimal currencies, per Stripe. The amount sent to Stripe is the
|
||||
* major unit amount multiplied by 1000.
|
||||
*
|
||||
* @see https://docs.stripe.com/currencies#three-decimal
|
||||
*/
|
||||
protected const THREE_DECIMAL_CURRENCIES = ['bhd', 'jod', 'kwd', 'omr', 'tnd'];
|
||||
|
||||
/**
|
||||
* HUF, TWD and UGX are ISO zero-decimal currencies, but Stripe still
|
||||
* requires amounts to be sent as if they had two decimal places.
|
||||
*
|
||||
* @see https://docs.stripe.com/currencies#special-cases
|
||||
*/
|
||||
protected const SPECIAL_ZERO_DECIMAL_CURRENCIES = ['huf', 'twd', 'ugx'];
|
||||
|
||||
/**
|
||||
* Convert a Lunar price value to the amount expected by Stripe.
|
||||
*
|
||||
* Lunar stores prices as integers scaled by `Currency::decimal_places`,
|
||||
* which merchants can set independently of what Stripe expects for a
|
||||
* given currency. This converts back to the major unit amount first,
|
||||
* then re-scales it to whatever sub-unit Stripe requires for the
|
||||
* currency, so the result is correct regardless of how the merchant has
|
||||
* configured `Currency::decimal_places`.
|
||||
*
|
||||
* @see https://docs.stripe.com/currencies
|
||||
*/
|
||||
public static function toStripeAmount(int $value, CurrencyContract $currency): int
|
||||
{
|
||||
return self::rescale($value, max($currency->decimal_places, 0), self::stripeDecimalPlaces($currency));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an amount received from Stripe back to a Lunar price value,
|
||||
* scaled by `Currency::decimal_places`. Inverse of `toStripeAmount()`.
|
||||
*/
|
||||
public static function fromStripeAmount(int $amount, CurrencyContract $currency): int
|
||||
{
|
||||
return self::rescale($amount, self::stripeDecimalPlaces($currency), max($currency->decimal_places, 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of decimal places Stripe expects amounts in for a currency.
|
||||
*/
|
||||
protected static function stripeDecimalPlaces(CurrencyContract $currency): int
|
||||
{
|
||||
$code = strtolower($currency->code);
|
||||
|
||||
// UGX is also in the zero-decimal list; the special case takes precedence.
|
||||
if (in_array($code, self::SPECIAL_ZERO_DECIMAL_CURRENCIES, true)) {
|
||||
return 2;
|
||||
}
|
||||
|
||||
if (in_array($code, self::ZERO_DECIMAL_CURRENCIES, true)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (in_array($code, self::THREE_DECIMAL_CURRENCIES, true)) {
|
||||
return 3;
|
||||
}
|
||||
|
||||
return 2;
|
||||
}
|
||||
|
||||
protected static function rescale(int $value, int $fromDecimalPlaces, int $toDecimalPlaces): int
|
||||
{
|
||||
$exponent = $toDecimalPlaces - $fromDecimalPlaces;
|
||||
|
||||
if ($exponent >= 0) {
|
||||
return $value * (10 ** $exponent);
|
||||
}
|
||||
|
||||
$divisor = 10 ** (-$exponent);
|
||||
|
||||
return intdiv(abs($value) + intdiv($divisor, 2), $divisor) * ($value < 0 ? -1 : 1);
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,7 @@ class TransactionDriverAdapter
|
||||
/**
|
||||
* The PaymentDriverRegistry key $transaction was originally taken
|
||||
* through — what refund()/capture() resolve against by default, and
|
||||
* what Order\Filament\Extensions\OrderRefundActionsExtension defaults
|
||||
* what Order\Filament\Extensions\OrderActionsExtension defaults
|
||||
* its "Refund via" driver Select to, before an admin overrides it.
|
||||
*/
|
||||
public function driverKeyFor(Transaction $transaction): ?string
|
||||
@@ -72,7 +72,7 @@ class TransactionDriverAdapter
|
||||
* when refunding through the transaction's own original driver.
|
||||
*
|
||||
* Called directly by Order\Filament\Extensions\
|
||||
* OrderRefundActionsExtension when the admin picks a different driver
|
||||
* OrderActionsExtension when the admin picks a different driver
|
||||
* in the refund modal, bypassing Lunar\Models\Transaction::refund()
|
||||
* (whose fixed refund(int $amount, $notes = null) signature has no
|
||||
* room for a driver override) — see that extension's own docblock.
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
|
||||
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
use Lunar\Stripe\Http\Middleware\StripeWebhookMiddleware;
|
||||
use Modules\Core\Payment\Http\Controllers\StripeWebhookController;
|
||||
use Modules\Core\Payment\Http\Middleware\StripeWebhookMiddleware;
|
||||
|
||||
Route::post(
|
||||
config('payment.stripe.webhook_path', 'payments/stripe/webhook'),
|
||||
|
||||
@@ -2,16 +2,34 @@
|
||||
|
||||
namespace Modules\Core\Providers;
|
||||
|
||||
use Illuminate\Console\Scheduling\Schedule as ConsoleSchedule;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Lunar\Models\Order;
|
||||
use Lunar\Models\Transaction;
|
||||
use Modules\Core\Checkout\Events\OrderPlaced;
|
||||
use Modules\Core\Notification\NotificationRegistry;
|
||||
use Modules\Core\Order\Commands\CloseExpiredReturnWindows;
|
||||
use Modules\Core\Order\Events\OrderDelivered;
|
||||
use Modules\Core\Order\Events\OrderPaidChanged;
|
||||
use Modules\Core\Order\Events\OrderPickedUp;
|
||||
use Modules\Core\Order\Events\OrderStatusChanged;
|
||||
use Modules\Core\Order\Listeners\AdvanceFulfillmentOnCarrierCheckpoint;
|
||||
use Modules\Core\Order\Listeners\AdvanceFulfillmentOnDelivered;
|
||||
use Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus;
|
||||
use Modules\Core\Order\Listeners\CompleteOrderOnPickedUp;
|
||||
use Modules\Core\Order\Listeners\DecrementStockOnOrderPlaced;
|
||||
use Modules\Core\Order\Listeners\DeriveOrderDeliveredFromShipment;
|
||||
use Modules\Core\Order\Listeners\MarkDeliveryFailedOnCarrierCheckpoint;
|
||||
use Modules\Core\Order\Listeners\RecordPaymentTransaction;
|
||||
use Modules\Core\Order\Listeners\RecordStatusTransition;
|
||||
use Modules\Core\Order\Models\OrderStatusTransition;
|
||||
use Modules\Core\Order\Notifications\OrderCapturedNotification;
|
||||
use Modules\Core\Order\Notifications\OrderCompletedNotification;
|
||||
use Modules\Core\Order\Notifications\OrderDeliveredNotification;
|
||||
use Modules\Core\Order\Notifications\OrderDispatchedNotification;
|
||||
use Modules\Core\Order\Notifications\OrderPickupReadyNotification;
|
||||
use Modules\Core\Order\Notifications\OrderPlacedNotification;
|
||||
use Modules\Core\Order\Notifications\OrderRefundedNotification;
|
||||
use Modules\Core\Order\Notifications\OrderStatusUpdatedNotification;
|
||||
use Modules\Core\Order\Observers\OrderObserver;
|
||||
@@ -33,20 +51,43 @@ class OrderServiceProvider extends ServiceProvider
|
||||
Order::macro('paymentStatus', fn () => OrderStatus::payment($this));
|
||||
Order::macro('fulfillmentStatus', fn () => OrderStatus::fulfillment($this));
|
||||
|
||||
Order::resolveRelationUsing('statusTransitions', function ($order) {
|
||||
return $order->hasMany(OrderStatusTransition::class);
|
||||
});
|
||||
|
||||
Event::listen(ShipmentStatusUpdatedByCarrier::class, DeriveOrderDeliveredFromShipment::class);
|
||||
Event::listen(ShipmentStatusUpdatedByCarrier::class, AdvanceFulfillmentOnCarrierCheckpoint::class);
|
||||
Event::listen(ShipmentStatusUpdatedByCarrier::class, MarkDeliveryFailedOnCarrierCheckpoint::class);
|
||||
Event::listen(OrderDelivered::class, AdvanceFulfillmentOnDelivered::class);
|
||||
Event::listen(OrderPickedUp::class, CompleteOrderOnPickedUp::class);
|
||||
|
||||
Event::listen(PaymentCaptured::class, ApplyResolvedPaymentStatus::class);
|
||||
Event::listen(PaymentAuthorized::class, ApplyResolvedPaymentStatus::class);
|
||||
Event::listen(PaymentRefunded::class, ApplyResolvedPaymentStatus::class);
|
||||
Event::listen(PaymentCaptured::class, RecordPaymentTransaction::class);
|
||||
Event::listen(PaymentAuthorized::class, RecordPaymentTransaction::class);
|
||||
Event::listen(PaymentVoided::class, RecordPaymentTransaction::class);
|
||||
// RecordPaymentTransaction must run before ApplyResolvedPaymentStatus
|
||||
// for PaymentRefunded specifically — the latter now reads
|
||||
// $order->transactions (via OrderStatus::payment()) to resolve
|
||||
// Refunded vs PartiallyRefunded, which requires the refund
|
||||
// Transaction row to already exist.
|
||||
Event::listen(PaymentRefunded::class, RecordPaymentTransaction::class);
|
||||
Event::listen(PaymentRefunded::class, ApplyResolvedPaymentStatus::class);
|
||||
|
||||
Event::listen(OrderPlaced::class, DecrementStockOnOrderPlaced::class);
|
||||
|
||||
Event::listen(OrderStatusChanged::class, [RecordStatusTransition::class, 'handleStatusChanged']);
|
||||
Event::listen(OrderPaidChanged::class, [RecordStatusTransition::class, 'handlePaidChanged']);
|
||||
|
||||
NotificationRegistry::get()->register([
|
||||
OrderDeliveredNotification::class,
|
||||
OrderStatusUpdatedNotification::class,
|
||||
OrderRefundedNotification::class,
|
||||
OrderCapturedNotification::class,
|
||||
OrderPlacedNotification::class,
|
||||
OrderPickupReadyNotification::class,
|
||||
OrderDispatchedNotification::class,
|
||||
OrderCompletedNotification::class,
|
||||
]);
|
||||
|
||||
// Lets the consuming app override copy/markup without forking core
|
||||
@@ -56,5 +97,17 @@ class OrderServiceProvider extends ServiceProvider
|
||||
$this->publishes([
|
||||
__DIR__ . '/../../resources/views/order/notifications' => resource_path('views/vendor/core/order/notifications'),
|
||||
], 'core-views');
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([CloseExpiredReturnWindows::class]);
|
||||
}
|
||||
|
||||
// Exact midnight per an explicit compliance requirement — not a
|
||||
// loose dailyAt() offset or plain daily().
|
||||
$this->app->booted(function () {
|
||||
$this->app->make(ConsoleSchedule::class)
|
||||
->command(CloseExpiredReturnWindows::class)
|
||||
->dailyAt('00:00');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ use Lunar\Models\Contracts\Transaction as TransactionContract;
|
||||
use Lunar\Pipelines\Cart\ApplyShipping;
|
||||
use Modules\Core\Command\SyncPaymentDriversCommand;
|
||||
use Modules\Core\Payment\Drivers\BankTransferPaymentDriver;
|
||||
use Modules\Core\Payment\Drivers\CashOnDeliveryPaymentDriver;
|
||||
use Modules\Core\Payment\Drivers\OfflinePaymentDriver;
|
||||
use Modules\Core\Payment\Drivers\StripePaymentDriver;
|
||||
use Modules\Core\Payment\Events\PaymentMethodCreated;
|
||||
@@ -33,6 +34,7 @@ class PaymentServiceProvider extends ServiceProvider
|
||||
$registry->register('offline', OfflinePaymentDriver::class, 'Offline / Manual');
|
||||
$registry->register('stripe', StripePaymentDriver::class, 'Stripe');
|
||||
$registry->register('bank-transfer', BankTransferPaymentDriver::class, 'Bank Transfer');
|
||||
$registry->register('cash-on-delivery', CashOnDeliveryPaymentDriver::class, 'Cash on Delivery');
|
||||
|
||||
$cartPipeline = config('lunar.cart.pipelines.cart', []);
|
||||
$insertAfter = array_search(ApplyShipping::class, $cartPipeline, true);
|
||||
|
||||
@@ -65,10 +65,52 @@ class ShippingServiceProvider extends ServiceProvider
|
||||
__DIR__ . '/../../config/shippingCarriers/boxnow.php' => config_path('shippingCarriers/boxnow.php'),
|
||||
], 'core-config');
|
||||
|
||||
// Signed-URL auth only, same model as Lunar's own vendor
|
||||
// lunar.pdf.download route — see Modules\Core\Shipping\Http\
|
||||
// Controllers\DownloadShipmentLabelController's own docblock.
|
||||
$this->loadRoutesFrom(__DIR__ . '/../Shipping/routes/web.php');
|
||||
|
||||
Order::resolveRelationUsing('shipments', function ($order) {
|
||||
return $order->hasMany(Shipment::class);
|
||||
});
|
||||
|
||||
// Order has no direct ShippingMethod relation — shippingAddress.
|
||||
// shipping_option is only ever a code string (see
|
||||
// Modules\Core\Shipping\Extensions\OrderViewExtension::
|
||||
// resolveCarrier() for the same lookup pattern already used to
|
||||
// resolve a carrier driver from it).
|
||||
//
|
||||
// Reads ShippingMethod.data['fulfillment_type'] directly rather
|
||||
// than through a ShippingMethod::macro('isStorePickup', ...) —
|
||||
// Lunar\Base\Traits\HasModelExtending::__callStatic() (used by
|
||||
// Lunar\Shipping\Models\ShippingMethod via Lunar\Base\BaseModel)
|
||||
// intercepts EVERY unmatched static call, including macro()
|
||||
// itself, and dispatches it as (new static)->macro(...) instead
|
||||
// of forwarding to Macroable — so a macro registered this way
|
||||
// silently never gets stored, and hasMacro() always returns
|
||||
// false. (Lunar\Models\Order is unaffected because it declares
|
||||
// its own macro() method directly, bypassing __callStatic
|
||||
// entirely — that's why Order::macro('isStorePickupOrder', ...)
|
||||
// below still works.) Defaults to 'carrier' (false) for any row
|
||||
// saved before this field existed.
|
||||
Order::macro('isStorePickupOrder', function () {
|
||||
/** @var Order $this */
|
||||
$code = $this->shippingAddress?->shipping_option;
|
||||
|
||||
if (! $code) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// ->value('data') is deliberately avoided here — on Postgres,
|
||||
// ->value()/->pluck() on a JSON column silently return the
|
||||
// wrong result (works fine in ->where(), not in a column
|
||||
// projection); loading the model and reading its cast
|
||||
// attribute avoids that entirely.
|
||||
$method = ShippingMethod::where('code', $code)->first();
|
||||
|
||||
return ($method?->data['fulfillment_type'] ?? 'carrier') === 'store_pickup';
|
||||
});
|
||||
|
||||
foreach ([CartLineAdded::class, CartLineUpdated::class, CartLineRemoved::class, CartCleared::class, ShippingAddressSet::class] as $event) {
|
||||
Event::listen($event, [InvalidateShippingOptions::class, 'handle']);
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ use Modules\Core\Shipping\DTOs\ManifestResult;
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\DTOs\TrackingCheckpoint;
|
||||
use Modules\Core\Shipping\Enums\TrackingStatus;
|
||||
use Modules\Core\Shipping\Models\Manifest;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsManifestBatching, SupportsTracking
|
||||
@@ -88,7 +89,7 @@ class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsMani
|
||||
|
||||
public function cancelShipment(Shipment $shipment): void
|
||||
{
|
||||
if ($shipment->manifest_reference) {
|
||||
if ($shipment->manifest_id) {
|
||||
throw new RuntimeException('Cannot cancel a shipment already included in an issued manifest.');
|
||||
}
|
||||
|
||||
@@ -103,7 +104,7 @@ class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsMani
|
||||
{
|
||||
return Shipment::query()
|
||||
->where('carrier', 'acs')
|
||||
->whereNull('manifest_reference')
|
||||
->whereNull('manifest_id')
|
||||
->whereNull('cancelled_at')
|
||||
->get();
|
||||
}
|
||||
@@ -123,11 +124,18 @@ class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsMani
|
||||
|
||||
$pickupListNo = (string) $response->valueOutput['PickupList_No'];
|
||||
|
||||
$manifest = Manifest::create([
|
||||
'carrier' => 'acs',
|
||||
'reference' => $pickupListNo,
|
||||
'shipment_count' => $shipments->count(),
|
||||
'issued_at' => now(),
|
||||
]);
|
||||
|
||||
$shipments->each(fn (Shipment $shipment) => $shipment->update([
|
||||
'manifest_reference' => $pickupListNo,
|
||||
'manifest_id' => $manifest->id,
|
||||
]));
|
||||
|
||||
return ManifestResult::success($pickupListNo, $shipments);
|
||||
return ManifestResult::success($manifest, $shipments);
|
||||
}
|
||||
|
||||
public function trackShipment(Shipment $shipment): Collection
|
||||
@@ -176,6 +184,11 @@ class AcsFulfillmentService implements CarrierFulfillmentInterface, SupportsMani
|
||||
{
|
||||
$action = strtolower($action);
|
||||
|
||||
// TODO: no live ACS payload sample yet showing a distinct
|
||||
// collection checkpoint separate from transit ("arrival"/
|
||||
// "departure" already map to InTransit) — add a str_contains()
|
||||
// arm mapping to TrackingStatus::CollectedFromSender here once
|
||||
// one is confirmed.
|
||||
return match (true) {
|
||||
str_contains($action, 'delivery to consignee') => TrackingStatus::Delivered,
|
||||
str_contains($action, 'on delivery') => TrackingStatus::OutForDelivery,
|
||||
|
||||
@@ -11,6 +11,7 @@ use Modules\Core\Shipping\Carriers\Acs\Exceptions\AcsApiException;
|
||||
use Modules\Core\Shipping\Concerns\CachesLivePricing;
|
||||
use Modules\Core\Shipping\Concerns\ResolvesFixedPricing;
|
||||
use Modules\Core\Shipping\Contracts\SupportsLivePricing;
|
||||
use Modules\Core\Shipping\Support\WeightCalculator;
|
||||
|
||||
class AcsRateDriver implements ShippingRateInterface, SupportsLivePricing
|
||||
{
|
||||
@@ -103,26 +104,6 @@ class AcsRateDriver implements ShippingRateInterface, SupportsLivePricing
|
||||
|
||||
private function totalWeightInKg($cart): float
|
||||
{
|
||||
$weight = 0.0;
|
||||
|
||||
foreach ($cart->lines->load('purchasable') as $line) {
|
||||
$variant = $line->purchasable;
|
||||
|
||||
if (! $variant || ! $variant->weight_value) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$unit = $variant->weight_unit ?? 'kg';
|
||||
$value = (float) $variant->weight_value;
|
||||
|
||||
$weight += match ($unit) {
|
||||
'g' => $value / 1000,
|
||||
'lb' => $value * 0.45359237,
|
||||
'oz' => $value * 0.0283495231,
|
||||
default => $value, // kg
|
||||
} * $line->quantity;
|
||||
}
|
||||
|
||||
return max($weight, 0.5); // ACS minimum billable weight
|
||||
return max(WeightCalculator::totalKg($cart->lines), 0.5); // ACS minimum billable weight
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,10 +21,21 @@ use Modules\Core\Shipping\Models\Shipment;
|
||||
* Box Now delivers to lockers, not addresses. The storefront locker-picker
|
||||
* is out of scope for this pass — createShipment() requires the chosen
|
||||
* locker's Box Now locationId via ShipmentRequest::$destinationLocationId
|
||||
* (e.g. set manually by admin staff until checkout UI exists).
|
||||
* (e.g. set manually by admin staff until checkout UI exists — see
|
||||
* Modules\Core\Shipping\Extensions\OrderViewExtension, which locks the
|
||||
* field instead once the shopper's own checkout selection is present in
|
||||
* $order->shippingAddress->meta['box_now_locker']).
|
||||
*
|
||||
* Box Now ships by compartment size, not weight — unlike ACS, which bills
|
||||
* by kg. One 'items' entry per box in ShipmentRequest::$boxes, so an order
|
||||
* needing more than one physical parcel (doesn't fit one compartment)
|
||||
* sends that many entries in a single delivery request rather than
|
||||
* several separate ones.
|
||||
*/
|
||||
class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsTracking
|
||||
{
|
||||
private const COMPARTMENT_SIZES = ['S' => 1, 'M' => 2, 'L' => 3];
|
||||
|
||||
public function __construct(private readonly BoxNowClient $client) {}
|
||||
|
||||
public function createShipment(Order $order, ShipmentRequest $request): Shipment
|
||||
@@ -36,6 +47,10 @@ class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsT
|
||||
throw new BoxNowApiException('No Box Now locker (locationId) was provided for this shipment.');
|
||||
}
|
||||
|
||||
if (empty($request->boxes)) {
|
||||
throw new BoxNowApiException('At least one box (compartment size) is required for a Box Now shipment.');
|
||||
}
|
||||
|
||||
$isCod = $request->paymentMode === 'cod';
|
||||
|
||||
$response = $this->client->request('post', '/delivery-requests', [
|
||||
@@ -57,31 +72,37 @@ class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsT
|
||||
'contactName' => trim("{$address->first_name} {$address->last_name}"),
|
||||
'locationId' => $destinationLocationId,
|
||||
],
|
||||
'items' => [
|
||||
[
|
||||
'id' => (string) $order->id,
|
||||
'name' => 'Order '.$order->reference,
|
||||
'value' => '0.00',
|
||||
'compartmentSize' => 1,
|
||||
'weight' => $request->weight ?? 0,
|
||||
],
|
||||
],
|
||||
'items' => collect($request->boxes)->values()->map(fn (string $size, int $index) => [
|
||||
'id' => $order->id.'-'.($index + 1),
|
||||
'name' => 'Order '.$order->reference.' (box '.($index + 1).')',
|
||||
'value' => '0.00',
|
||||
'compartmentSize' => self::COMPARTMENT_SIZES[$size] ?? self::COMPARTMENT_SIZES['S'],
|
||||
])->all(),
|
||||
]);
|
||||
|
||||
$parcelId = (string) ($response['parcels'][0]['id'] ?? throw new BoxNowApiException(
|
||||
'Box Now delivery request succeeded but returned no parcel id.',
|
||||
$response,
|
||||
));
|
||||
$parcels = collect($response['parcels'] ?? []);
|
||||
|
||||
return Shipment::create([
|
||||
if ($parcels->isEmpty()) {
|
||||
throw new BoxNowApiException('Box Now delivery request succeeded but returned no parcel ids.', $response);
|
||||
}
|
||||
|
||||
// One Shipment row per box/parcel — each is independently
|
||||
// trackable/printable/cancellable via its own tracking_reference
|
||||
// (printLabel()/cancelShipment()/trackShipment() below already
|
||||
// operate per-Shipment), even though all boxes were submitted in
|
||||
// one delivery request. Siblings are linked via the shared
|
||||
// delivery_request_id in meta.
|
||||
$shipments = $parcels->map(fn (array $parcel) => Shipment::create([
|
||||
'order_id' => $order->id,
|
||||
'carrier' => 'box-now',
|
||||
'tracking_reference' => $parcelId,
|
||||
'tracking_reference' => (string) $parcel['id'],
|
||||
'meta' => [
|
||||
'delivery_request_id' => $response['id'] ?? null,
|
||||
'locker_id' => $destinationLocationId,
|
||||
],
|
||||
]);
|
||||
]));
|
||||
|
||||
return $shipments->first();
|
||||
}
|
||||
|
||||
public function printLabel(Shipment $shipment): string
|
||||
@@ -136,6 +157,13 @@ class BoxNowFulfillmentService implements CarrierFulfillmentInterface, SupportsT
|
||||
|
||||
private function mapState(string $state): TrackingStatus
|
||||
{
|
||||
// TODO: confirm against a live BoxNow webhook payload whether a
|
||||
// distinct collected-from-sender state exists (e.g. between 'new'
|
||||
// and 'in-transit') before mapping it to
|
||||
// TrackingStatus::CollectedFromSender — BoxNow's own model is
|
||||
// locker-drop-off-based, so it may not have one. No guessed match
|
||||
// arm added; 'new' still falls through to Pending, InTransit
|
||||
// remains the earliest recognized checkpoint.
|
||||
return match ($state) {
|
||||
'new' => TrackingStatus::Pending,
|
||||
'in-transit', 'in-depot' => TrackingStatus::InTransit,
|
||||
|
||||
@@ -3,24 +3,26 @@
|
||||
namespace Modules\Core\Shipping\DTOs;
|
||||
|
||||
use Illuminate\Support\Collection;
|
||||
use Modules\Core\Shipping\Models\Manifest;
|
||||
|
||||
class ManifestResult
|
||||
{
|
||||
private function __construct(
|
||||
public readonly bool $success,
|
||||
public readonly ?string $reference,
|
||||
public readonly ?Manifest $manifest,
|
||||
public readonly Collection $includedShipments,
|
||||
public readonly Collection $blockedShipments,
|
||||
public readonly ?string $reason,
|
||||
) {}
|
||||
|
||||
public static function success(string $reference, Collection $includedShipments): self
|
||||
public static function success(Manifest $manifest, Collection $includedShipments): self
|
||||
{
|
||||
return new self(true, $reference, $includedShipments, collect(), null);
|
||||
return new self(true, $manifest->reference, $manifest, $includedShipments, collect(), null);
|
||||
}
|
||||
|
||||
public static function blocked(Collection $blockedShipments, string $reason): self
|
||||
{
|
||||
return new self(false, null, collect(), $blockedShipments, $reason);
|
||||
return new self(false, null, null, collect(), $blockedShipments, $reason);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,27 @@ namespace Modules\Core\Shipping\DTOs;
|
||||
/**
|
||||
* Carrier-agnostic input for CarrierFulfillmentInterface::createShipment().
|
||||
* Every field is optional — a carrier reads only what it needs and ignores
|
||||
* the rest (e.g. destinationLocationId only matters to locker-delivery
|
||||
* carriers like Box Now; ACS has no use for it).
|
||||
* the rest (e.g. destinationLocationId/boxes only matter to locker-delivery
|
||||
* carriers like Box Now; ACS has no use for either — it ships by weight,
|
||||
* not by box/compartment size).
|
||||
*/
|
||||
class ShipmentRequest
|
||||
{
|
||||
/**
|
||||
* @param array<int, string> $boxes Box Now only — one entry per
|
||||
* physical parcel, each a compartment size ('S'|'M'|'L'). A single
|
||||
* shipment can be split across several lockers of the same
|
||||
* destinationLocationId's collection point, e.g. two Large boxes for
|
||||
* an order that doesn't fit one compartment. Empty for every other
|
||||
* carrier, which ships as a single package described by $weight
|
||||
* instead.
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ?float $weight = null,
|
||||
public readonly int $packageCount = 1,
|
||||
public readonly ?string $destinationLocationId = null,
|
||||
public readonly ?string $paymentMode = null,
|
||||
public readonly ?float $amountToCollect = null,
|
||||
public readonly array $boxes = [],
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,25 @@ namespace Modules\Core\Shipping\Enums;
|
||||
enum TrackingStatus: string
|
||||
{
|
||||
case Pending = 'pending';
|
||||
|
||||
/**
|
||||
* The carrier collected the parcel from the merchant — deliberately
|
||||
* NOT named "PickedUp" to avoid colliding with the unrelated
|
||||
* order status 'picked_up' (Modules\Core\Order\Services\
|
||||
* OrderStatusFlow), which means the opposite end of a different flow
|
||||
* (a CUSTOMER collecting a store-pickup order). Consumed by
|
||||
* Modules\Core\Order\Listeners\AdvanceFulfillmentOnCarrierCheckpoint.
|
||||
*
|
||||
* Not yet mapped from either carrier driver's own checkpoint data —
|
||||
* see Carriers\BoxNow\BoxNowFulfillmentService::mapState() and
|
||||
* Carriers\Acs\AcsFulfillmentService::guessStatusFromAction() for
|
||||
* TODOs on confirming against real payload samples before adding a
|
||||
* mapping. Until then this case exists but nothing produces it, and
|
||||
* InTransit remains the effective first real checkpoint for both
|
||||
* carriers.
|
||||
*/
|
||||
case CollectedFromSender = 'collected_from_sender';
|
||||
|
||||
case InTransit = 'in_transit';
|
||||
case OutForDelivery = 'out_for_delivery';
|
||||
case Delivered = 'delivered';
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Extensions;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Infolists\Components\RepeatableEntry;
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Lunar\Admin\Support\Extending\ViewPageExtension;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Adds a "Shipments" section to the order page's main column — previously
|
||||
* "Create Shipment" (Modules\Core\Shipping\Extensions\OrderViewExtension)
|
||||
* had no counterpart anywhere on the order to actually SEE what it
|
||||
* created (carrier, tracking reference, current status, whether a label's
|
||||
* been printed or the shipment cancelled). One row per Shipment record —
|
||||
* a Box Now order with several boxes shows one row per box/parcel (see
|
||||
* Modules\Core\Shipping\Carriers\BoxNow\BoxNowFulfillmentService, which
|
||||
* creates one Shipment row per parcel Box Now returns), not one row per
|
||||
* "Create Shipment" click.
|
||||
*
|
||||
* Uses the extendInfolistSchema hook (main column — alongside shipping
|
||||
* address, order lines, totals, transactions, timeline), not
|
||||
* extendInfolistAsideSchema (sidebar) — a shipment list can grow long
|
||||
* (multi-box Box Now orders, a re-dispatched order after a delivery
|
||||
* failure) and reads more naturally as a main-column section like
|
||||
* Transactions, not a compact sidebar entry.
|
||||
*
|
||||
* Each shipment renders as two inline-labelled lines (carrier + tracking
|
||||
* reference, then status + timestamp) rather than a grid of individually
|
||||
* stacked label/value blocks — Filament's own multi-column grid still
|
||||
* collapses to one column below its lg breakpoint (1024px), which is
|
||||
* exactly where the admin's main content area commonly sits with the
|
||||
* sidebar open, so a 5-6 field grid reads as a wall of repeated labels
|
||||
* there.
|
||||
*
|
||||
* "Print Label" opens Modules\Core\Shipping\Http\Controllers\
|
||||
* DownloadShipmentLabelController via a short-lived signed URL — the same
|
||||
* auth model (and Action wiring pattern) Lunar's own vendor PdfDownload
|
||||
* action uses for order PDFs. Previously the only place that called
|
||||
* CarrierFulfillmentInterface::printLabel() (Modules\Core\Shipping\
|
||||
* Filament\Pages\ManagePickupManifests) discarded the returned bytes
|
||||
* entirely — this is the first place that actually delivers a label to
|
||||
* staff.
|
||||
*/
|
||||
class OrderShipmentsExtension extends ViewPageExtension
|
||||
{
|
||||
/**
|
||||
* Inserted right after Transactions and before Timeline — vendor
|
||||
* ManageOrder::getInfolistSchema() builds this array as
|
||||
* [shipping, orderLines, orderTotals, transactions, timeline] (see
|
||||
* Lunar\Admin\...\Concerns\DisplaysTransactions/DisplaysTimeline), so
|
||||
* splicing at index 4 lands the new section there regardless of how
|
||||
* many earlier entries any OTHER extension on this same hook has
|
||||
* already added/removed — counting from the end (timeline is always
|
||||
* last) would be equally fragile to some other extension appending
|
||||
* its own section after timeline, so this anchors on the known
|
||||
* vendor order instead.
|
||||
*/
|
||||
public function extendInfolistSchema(array $schema): array
|
||||
{
|
||||
array_splice($schema, 4, 0, [$this->shipmentsSection()]);
|
||||
|
||||
return $schema;
|
||||
}
|
||||
|
||||
private function shipmentsSection(): Section
|
||||
{
|
||||
return Section::make('shipments')
|
||||
->heading('Shipments')
|
||||
->compact()
|
||||
->collapsed(fn ($record) => $record->shipments->isEmpty())
|
||||
->collapsible(fn ($record) => $record->shipments->isNotEmpty())
|
||||
->schema([
|
||||
RepeatableEntry::make('shipments')
|
||||
->hiddenLabel()
|
||||
->placeholder('No shipments have been created for this order yet.')
|
||||
->contained(true)
|
||||
->schema([
|
||||
TextEntry::make('tracking_reference')
|
||||
->label(fn (Shipment $record) => $this->carrierLabel($record))
|
||||
->inlineLabel()
|
||||
->copyable(),
|
||||
TextEntry::make('status')
|
||||
->label('Status')
|
||||
->inlineLabel()
|
||||
->state(fn (Shipment $record) => $this->statusLabel($record))
|
||||
->badge()
|
||||
->color(fn (Shipment $record) => $this->statusColor($record))
|
||||
->helperText(fn (Shipment $record) => $this->helperText($record))
|
||||
->suffixActions([
|
||||
Action::make('print_label')
|
||||
->label('Print Label')
|
||||
->icon('heroicon-o-printer')
|
||||
->url(fn (Shipment $record) => URL::temporarySignedRoute(
|
||||
'shipments.label',
|
||||
now()->addMinutes(5),
|
||||
['shipment' => $record->id],
|
||||
), shouldOpenInNewTab: true)
|
||||
->visible(fn (Shipment $record) => ! $record->cancelled_at),
|
||||
Action::make('cancel_shipment')
|
||||
->label('Cancel')
|
||||
->icon('heroicon-o-x-circle')
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Cancels this shipment with the carrier. This cannot be undone.')
|
||||
->action(fn (Shipment $record) => $this->cancel($record))
|
||||
->visible(fn (Shipment $record) => ! $record->cancelled_at),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
private function carrierLabel(Shipment $record): string
|
||||
{
|
||||
return match ($record->carrier) {
|
||||
'acs' => 'ACS',
|
||||
'box-now' => 'Box Now',
|
||||
default => (string) str($record->carrier)->title(),
|
||||
};
|
||||
}
|
||||
|
||||
private function helperText(Shipment $record): string
|
||||
{
|
||||
$parts = ['Created '.$record->created_at->format('Y-m-d H:i')];
|
||||
|
||||
if ($record->carrier === 'box-now' && $locker = $record->meta['locker_id'] ?? null) {
|
||||
$parts[] = 'Locker '.$locker;
|
||||
}
|
||||
|
||||
return implode(' · ', $parts);
|
||||
}
|
||||
|
||||
private function statusLabel(Shipment $record): string
|
||||
{
|
||||
if ($record->cancelled_at) {
|
||||
return 'Cancelled';
|
||||
}
|
||||
|
||||
$latest = $record->latestShipmentInfo();
|
||||
|
||||
return $latest ? (string) str($latest->status->value)->replace('_', ' ')->title() : 'Pending';
|
||||
}
|
||||
|
||||
private function statusColor(Shipment $record): string
|
||||
{
|
||||
if ($record->cancelled_at) {
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
return match ($record->latestShipmentInfo()?->status?->value) {
|
||||
'delivered' => 'success',
|
||||
'failed', 'returned' => 'danger',
|
||||
'in_transit', 'out_for_delivery', 'collected_from_sender' => 'warning',
|
||||
default => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
private function cancel(Shipment $record): void
|
||||
{
|
||||
$service = app(CarrierFulfillmentInterface::class, ['carrier' => $record->carrier]);
|
||||
|
||||
try {
|
||||
$service->cancelShipment($record);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()
|
||||
->title('Failed to cancel shipment: '.$e->getMessage())
|
||||
->color('danger')
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Shipment cancelled.')
|
||||
->color('success')
|
||||
->send();
|
||||
}
|
||||
}
|
||||
@@ -3,24 +3,90 @@
|
||||
namespace Modules\Core\Shipping\Extensions;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Closure;
|
||||
use Throwable;
|
||||
use Filament\Actions;
|
||||
use Filament\Forms;
|
||||
use Filament\Notifications\Notification;
|
||||
use Lunar\Admin\Support\Extending\ViewPageExtension;
|
||||
use Lunar\Models\Order;
|
||||
use Lunar\Shipping\Models\ShippingMethod;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Order\DTOs\OrderFulfillmentResult;
|
||||
use Modules\Core\Order\Services\OrderFulfillmentService;
|
||||
use Modules\Core\Order\Services\OrderStatusFlow;
|
||||
use Modules\Core\Shipping\DTOs\ShipmentRequest;
|
||||
use Modules\Core\Shipping\Support\WeightCalculator;
|
||||
|
||||
/**
|
||||
* Filament wiring only (labels, icons, visibility, form schema) for the
|
||||
* staff-facing status workflow — every guard check, status write, and
|
||||
* event dispatch lives in Modules\Core\Order\Services\
|
||||
* OrderFulfillmentService/OrderStatusFlow, resolved via app() (a
|
||||
* ViewPageExtension is instantiated by Lunar's own extension mechanism,
|
||||
* not the container, so there's no constructor-injection seam here).
|
||||
*
|
||||
* Strips Lunar's own "Update Status" header action (registered by vendor
|
||||
* ManageOrder as Action::make('update_status')) and replaces it with our
|
||||
* own action of the same name — vendor's writes $record->status directly
|
||||
* with no audit trail, no branch validation, and no side effects. Our
|
||||
* replacement offers every status in the order's own branch (carrier or
|
||||
* pickup — see OrderStatusFlow::allOptions()), not just the guided next
|
||||
* step, so staff can freely revert to an earlier status too. It is a
|
||||
* PLAIN status write — picking 'dispatched' here does not create a real
|
||||
* shipment (see "Create Shipment" below for that).
|
||||
*
|
||||
* "Create Shipment" is its own separate header action, visible only for a
|
||||
* carrier order sitting at 'ready_for_dispatch' — this is the one action
|
||||
* that talks to a real carrier API and writes Order::status to
|
||||
* 'dispatched' as a side effect of that succeeding, so it needs its own
|
||||
* weight/locker inputs specific to that one real-world action, not
|
||||
* bundled into the general-purpose status select where they'd appear for
|
||||
* every revert/manual-override use of 'dispatched' too. The form branches
|
||||
* on which carrier the order actually uses
|
||||
* (OrderFulfillmentService::carrierFor()): a weight-billed carrier (ACS)
|
||||
* gets a single TOTAL weight field for the whole shipment (ACS has no
|
||||
* per-package weight concept — one Weight value is sent alongside
|
||||
* Item_Quantity in the same ACS_Create_Voucher call, see
|
||||
* AcsFulfillmentService::createShipment()), pre-filled from the order's
|
||||
* own line weights (Modules\Core\Shipping\Support\WeightCalculator) but
|
||||
* still staff-editable, plus a package count (ShipmentRequest::
|
||||
* $packageCount) — more than 1 issues a main voucher plus a
|
||||
* multi-part sub-voucher per extra package (persistMultipartVouchers()),
|
||||
* each recorded as its own Shipment row sharing the same total weight in
|
||||
* meta. Box Now, which bills by compartment size rather than
|
||||
* weight, gets a repeatable list of boxes (one row per physical parcel,
|
||||
* each with its own S/M/L size) instead — see
|
||||
* Modules\Core\Shipping\Carriers\BoxNow\BoxNowFulfillmentService for how
|
||||
* multiple boxes become multiple Shipment rows from one delivery request.
|
||||
* Box Now's locker is locked to read-only once the shopper's own checkout
|
||||
* selection ($order->shippingAddress->meta['box_now_locker']) is present
|
||||
* — staff can only fill it in manually for the (current, checkout-UI-less)
|
||||
* case where nothing set it yet.
|
||||
*
|
||||
* "Mark Paid" is a third, separate header action — Order::paid is
|
||||
* independent of `status` (see OrderStatusFlow's own docblock), so it
|
||||
* doesn't belong bundled into the status select either. Visible only when
|
||||
* the order's payment method doesn't auto-capture at checkout (currently
|
||||
* only cash-on-delivery — see OrderStatusFlow::canMarkPaid()); a
|
||||
* processor-managed method (Stripe) or an immediate-capture offline
|
||||
* method (cash-in-hand, bank-transfer) sets Order::paid automatically via
|
||||
* Modules\Core\Order\Listeners\ApplyResolvedPaymentStatus, so this button
|
||||
* never appears for those.
|
||||
*
|
||||
* Also strips Lunar's own "Download PDF" header action (getDefaultHeaderActions()
|
||||
* in vendor ManageOrder) — its lunarpanel::pdf.order template does not meet
|
||||
* Greek AADE e-invoicing requirements, so it must not be offered as a
|
||||
* downloadable document until a compliant invoice generator exists.
|
||||
*/
|
||||
class OrderViewExtension extends ViewPageExtension
|
||||
{
|
||||
public function headerActions(array $actions): array
|
||||
{
|
||||
$actions = array_filter($actions, fn ($action) => method_exists($action, 'getName')
|
||||
? ! in_array($action->getName(), ['download_pdf', 'update_status'], true)
|
||||
: true);
|
||||
|
||||
$actions[] = $this->createShipmentAction();
|
||||
$actions[] = $this->updateStatusAction();
|
||||
$actions[] = $this->markPaidAction();
|
||||
|
||||
return $actions;
|
||||
}
|
||||
@@ -31,91 +97,133 @@ class OrderViewExtension extends ViewPageExtension
|
||||
->label('Create Shipment')
|
||||
->icon('heroicon-o-truck')
|
||||
->modalSubmitActionLabel('Create Shipment')
|
||||
->schema([
|
||||
TextInput::make('weight')
|
||||
->label('Package weight (kg)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->helperText('Leave blank to use the carrier\'s default.'),
|
||||
TextInput::make('destination_location_id')
|
||||
->label('Box Now locker ID')
|
||||
->helperText('Only required for Box Now shipments.')
|
||||
->default(fn (Order $record) => $record->shippingAddress?->meta['box_now_locker']['locationId'] ?? null),
|
||||
Toggle::make('confirm')
|
||||
->label('Confirm')
|
||||
->helperText('This will create a real shipment with the carrier.')
|
||||
->rules([
|
||||
function () {
|
||||
return function (string $attribute, $value, Closure $fail) {
|
||||
if ($value !== true) {
|
||||
$fail('Please confirm before creating the shipment.');
|
||||
}
|
||||
};
|
||||
},
|
||||
]),
|
||||
])
|
||||
->action(function (Order $record, array $data, Action $action) {
|
||||
$service = $this->resolveFulfillmentService($record);
|
||||
->schema(function (Order $record) {
|
||||
$isBoxNow = $this->service()->carrierFor($record) === 'box-now';
|
||||
$lockerId = $record->shippingAddress?->meta['box_now_locker']['locationId'] ?? null;
|
||||
|
||||
if (! $service) {
|
||||
Notification::make()
|
||||
->title('No carrier fulfillment integration is configured for this order.')
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
$action->halt();
|
||||
|
||||
return;
|
||||
if (! $isBoxNow) {
|
||||
return [
|
||||
TextInput::make('weight')
|
||||
->label('Total weight (kg)')
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->default(fn () => round(WeightCalculator::totalKg($record->lines), 2) ?: null)
|
||||
->helperText("Calculated from the order's line weights — adjust if needed, or leave blank to use the carrier's default. One figure for the whole shipment, not per package."),
|
||||
TextInput::make('package_count')
|
||||
->label('Number of packages')
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(1)
|
||||
->default(1)
|
||||
->required()
|
||||
->helperText('More than 1 issues a main voucher plus a sub-voucher per extra package, all sharing the total weight above.'),
|
||||
];
|
||||
}
|
||||
|
||||
$request = new ShipmentRequest(
|
||||
weight: filled($data['weight'] ?? null) ? (float) $data['weight'] : null,
|
||||
destinationLocationId: $data['destination_location_id'] ?? null,
|
||||
return [
|
||||
TextInput::make('destination_location_id')
|
||||
->label('Box Now locker ID')
|
||||
->default($lockerId)
|
||||
// Locked once the shopper's own checkout selection is
|
||||
// known — staff should not be able to redirect a
|
||||
// parcel to a different locker than the one the
|
||||
// customer picked. Only editable for the (current,
|
||||
// checkout-UI-less) case where nothing set it yet.
|
||||
->disabled(filled($lockerId))
|
||||
->dehydrated()
|
||||
->required()
|
||||
->helperText($lockerId
|
||||
? 'Set by the customer at checkout.'
|
||||
: 'No locker was selected at checkout — enter it manually.'),
|
||||
Repeater::make('boxes')
|
||||
->label('Boxes')
|
||||
->schema([
|
||||
Select::make('size')
|
||||
->label('Size')
|
||||
->options(['S' => 'Small', 'M' => 'Medium', 'L' => 'Large'])
|
||||
->default('S')
|
||||
->native(false)
|
||||
->required(),
|
||||
])
|
||||
->defaultItems(1)
|
||||
->addActionLabel('Add another box')
|
||||
->minItems(1)
|
||||
->helperText('One row per physical parcel — Box Now ships by compartment size, not weight.'),
|
||||
];
|
||||
})
|
||||
->action(function (Order $record, array $data, Action $action) {
|
||||
$result = $this->service()->createShipmentAndDispatch(
|
||||
$record,
|
||||
new ShipmentRequest(
|
||||
weight: filled($data['weight'] ?? null) ? (float) $data['weight'] : null,
|
||||
packageCount: (int) ($data['package_count'] ?? 1),
|
||||
destinationLocationId: $data['destination_location_id'] ?? null,
|
||||
boxes: collect($data['boxes'] ?? [])->pluck('size')->all(),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
$service->createShipment($record, $request);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()
|
||||
->title('Failed to create shipment: '.$e->getMessage())
|
||||
->danger()
|
||||
->send();
|
||||
$this->notify($result);
|
||||
|
||||
if (! $result->success) {
|
||||
$action->halt();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title('Shipment created.')
|
||||
->success()
|
||||
->send();
|
||||
})
|
||||
->visible(fn (Order $record) => $record->shipments()->exists() === false
|
||||
&& $this->resolveFulfillmentService($record) !== null);
|
||||
->visible(fn (Order $record) => $this->service()->canCreateShipment($record));
|
||||
}
|
||||
|
||||
private function resolveCarrier(Order $record): ?string
|
||||
private function updateStatusAction(): Action
|
||||
{
|
||||
$code = $record->shippingAddress?->shipping_option;
|
||||
return Action::make('update_status')
|
||||
->label('Update Status')
|
||||
->icon('heroicon-o-adjustments-horizontal')
|
||||
->schema(fn (Order $record) => [
|
||||
Select::make('to_status')
|
||||
->label('New status')
|
||||
->options(app(OrderStatusFlow::class)->allOptions($record))
|
||||
->default($record->status)
|
||||
->native(false)
|
||||
->required(),
|
||||
])
|
||||
->action(function (Order $record, array $data, Action $action) {
|
||||
$to = $data['to_status'];
|
||||
$service = $this->service();
|
||||
|
||||
if (! $code) {
|
||||
return null;
|
||||
}
|
||||
$result = match (true) {
|
||||
($to === 'ready_for_dispatch' || $to === 'ready_for_pickup') && $record->status === 'processing' => $service->markReady($record),
|
||||
$to === 'picked_up' && $record->status === 'ready_for_pickup' => $service->markPickedUp($record),
|
||||
default => $service->transitionTo($record, $to),
|
||||
};
|
||||
|
||||
return ShippingMethod::where('code', $code)->value('driver');
|
||||
$this->notify($result);
|
||||
|
||||
if (! $result->success) {
|
||||
$action->halt();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private function resolveFulfillmentService(Order $record): ?CarrierFulfillmentInterface
|
||||
private function markPaidAction(): Action
|
||||
{
|
||||
$carrier = $this->resolveCarrier($record);
|
||||
return Action::make('mark_paid')
|
||||
->label('Mark Paid')
|
||||
->icon('heroicon-o-banknotes')
|
||||
->color('success')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Confirms payment for this order has been received outside the system.')
|
||||
->visible(fn (Order $record) => app(OrderStatusFlow::class)->canMarkPaid($record))
|
||||
->action(fn (Order $record) => $this->notify($this->service()->markPaid($record)));
|
||||
}
|
||||
|
||||
if (! $carrier) {
|
||||
return null;
|
||||
}
|
||||
private function service(): OrderFulfillmentService
|
||||
{
|
||||
return app(OrderFulfillmentService::class);
|
||||
}
|
||||
|
||||
return app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]);
|
||||
private function notify(OrderFulfillmentResult $result): void
|
||||
{
|
||||
Notification::make()
|
||||
->title($result->message)
|
||||
->color($result->success ? 'success' : 'danger')
|
||||
->send();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,11 +18,41 @@ class ShippingMethodResourceExtension extends ResourceExtension
|
||||
{
|
||||
public function extendForm(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components(
|
||||
$this->replaceChargeByField(
|
||||
return $schema->components([
|
||||
...$this->replaceChargeByField(
|
||||
$this->replaceDriverField($schema->getComponents())
|
||||
)
|
||||
);
|
||||
),
|
||||
$this->fulfillmentTypeSelect(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* ShippingMethod.data['fulfillment_type'] — 'carrier' (default) or
|
||||
* 'store_pickup'. Same free-form-`data`-column pattern as charge_by
|
||||
* above, not a migrated column: ShippingMethod is a vendor
|
||||
* (lunarphp/table-rate-shipping) table, and this codebase avoids
|
||||
* forking vendor migrations for a merchant-configurable extra (see
|
||||
* PaymentMethod.data.fee for the same convention on a different
|
||||
* vendor-adjacent model).
|
||||
*
|
||||
* What this actually gates: Modules\Core\Shipping\Extensions\
|
||||
* OrderViewExtension's "Create Shipment" action only makes sense for
|
||||
* a 'carrier' method (it books a real carrier voucher) — a
|
||||
* 'store_pickup' order instead moves through Order.status
|
||||
* 'ready-for-pickup' -> a staff "Mark Picked Up" action, no shipment
|
||||
* ever created. See docs/checkout.md for the full status-flow design.
|
||||
*/
|
||||
private function fulfillmentTypeSelect(): Select
|
||||
{
|
||||
return Select::make('data.fulfillment_type')
|
||||
->label('Fulfillment type')
|
||||
->options([
|
||||
'carrier' => 'Carrier delivery',
|
||||
'store_pickup' => 'Collect in store',
|
||||
])
|
||||
->default('carrier')
|
||||
->required()
|
||||
->helperText('Whether an order using this method is handed to a carrier, or collected by the customer in person.');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Pages;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\BulkAction;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Concerns\InteractsWithTable;
|
||||
use Filament\Tables\Contracts\HasTable;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\SupportsManifestBatching;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
class ManagePickupManifests extends Page implements HasTable
|
||||
{
|
||||
use InteractsWithTable;
|
||||
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-truck';
|
||||
|
||||
protected static ?string $navigationLabel = 'Pickup Manifests';
|
||||
|
||||
/**
|
||||
* Without an explicit group, this page had no navigation group at all —
|
||||
* Filament's Panel::getUrl() falls back to "first item in the first
|
||||
* navigation group" when no homeUrl is set (neither Lunar nor CorePlugin
|
||||
* sets one), and an ungrouped page sorted ahead of every one of Lunar's
|
||||
* own grouped resources (Sales, Catalog, etc.), making this page the
|
||||
* panel's de facto home instead of the real Dashboard. Grouping it under
|
||||
* Sales — alongside CartResource, OrderResource — fixes that by letting
|
||||
* a legitimate item sort first again. Sorted last within the group
|
||||
* deliberately (a high explicit navigationSort — Lunar's own
|
||||
* OrderResource uses 1) so this page never competes to be first even as
|
||||
* more Sales-group items are added later.
|
||||
*/
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Sales';
|
||||
|
||||
protected static ?int $navigationSort = 100;
|
||||
|
||||
protected string $view = 'core::shipping.filament.pages.manage-pickup-manifests';
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->query($this->pendingQuery())
|
||||
->columns([
|
||||
TextColumn::make('carrier')->badge(),
|
||||
TextColumn::make('tracking_reference')->label('Tracking #'),
|
||||
TextColumn::make('order.reference')->label('Order'),
|
||||
TextColumn::make('label_printed_at')->label('Printed')->dateTime()->placeholder('Not printed'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('print')
|
||||
->label('Print')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Shipment $record) => $this->printShipment($record)),
|
||||
])
|
||||
->toolbarActions([
|
||||
BulkAction::make('print_selected')
|
||||
->label('Print selected')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Collection $records) => $records->each(fn (Shipment $shipment) => $this->printShipment($shipment))),
|
||||
BulkAction::make('issue_manifest')
|
||||
->label('Issue Manifest')
|
||||
->icon('heroicon-o-check-circle')
|
||||
->action(fn (Collection $records) => $this->issueManifest($records)),
|
||||
]);
|
||||
}
|
||||
|
||||
private function pendingQuery(): Builder
|
||||
{
|
||||
$carriers = collect(Shipping::getSupportedDrivers())->keys()->filter(
|
||||
fn (string $carrier) => $this->fulfillmentService($carrier) instanceof SupportsManifestBatching
|
||||
);
|
||||
|
||||
return Shipment::query()
|
||||
->whereIn('carrier', $carriers)
|
||||
->whereNull('manifest_reference')
|
||||
->whereNull('cancelled_at');
|
||||
}
|
||||
|
||||
private function printShipment(Shipment $shipment): void
|
||||
{
|
||||
$this->fulfillmentService($shipment->carrier)?->printLabel($shipment);
|
||||
}
|
||||
|
||||
private function issueManifest(Collection $shipments): void
|
||||
{
|
||||
$shipments->groupBy('carrier')->each(function (Collection $group, string $carrier) {
|
||||
$service = $this->fulfillmentService($carrier);
|
||||
|
||||
if (! $service instanceof SupportsManifestBatching) {
|
||||
return;
|
||||
}
|
||||
|
||||
$result = $service->issueManifest($group);
|
||||
|
||||
if (! $result->success) {
|
||||
Notification::make()
|
||||
->title("Manifest blocked for {$carrier}: {$result->reason}")
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title("Manifest issued for {$carrier}: {$result->reference}")
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
private function fulfillmentService(string $carrier): ?CarrierFulfillmentInterface
|
||||
{
|
||||
return app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources;
|
||||
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource\Pages\ListManifests;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource\Pages\ViewManifest;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource\RelationManagers\ShipmentsRelationManager;
|
||||
use Modules\Core\Shipping\Models\Manifest;
|
||||
|
||||
/**
|
||||
* Issued manifests — Modules\Core\Shipping\Models\Manifest is the only
|
||||
* record of "which shipments were on manifest X, and when" this codebase
|
||||
* keeps; ACS's own ACS_Issue_Pickup_List call returns nothing beyond a
|
||||
* reference number, so there is nothing to re-fetch from the carrier
|
||||
* later (see that model's own docblock). Complements
|
||||
* Modules\Core\Shipping\Filament\Resources\ShipmentResource, which only
|
||||
* ever shows shipments NOT YET on a manifest.
|
||||
*/
|
||||
class ManifestResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Manifest::class;
|
||||
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-clipboard-document-list';
|
||||
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Sales';
|
||||
|
||||
protected static ?string $navigationLabel = 'Issued Manifests';
|
||||
|
||||
protected static ?string $modelLabel = 'Manifest';
|
||||
|
||||
protected static ?int $navigationSort = 101;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('carrier')->badge(),
|
||||
TextColumn::make('reference')->label('Reference')->copyable(),
|
||||
TextColumn::make('shipment_count')->label('Shipments'),
|
||||
TextColumn::make('issued_at')->label('Issued')->dateTime(),
|
||||
])
|
||||
->recordActions([
|
||||
ViewAction::make(),
|
||||
])
|
||||
->defaultSort('issued_at', 'desc');
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
ShipmentsRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListManifests::route('/'),
|
||||
'view' => ViewManifest::route('/{record}'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources\ManifestResource\Pages;
|
||||
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Shipping\Contracts\SupportsManifestBatching;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
|
||||
|
||||
class ListManifests extends ListRecords
|
||||
{
|
||||
protected static string $resource = ManifestResource::class;
|
||||
|
||||
public function getTabs(): array
|
||||
{
|
||||
$carriers = collect(Shipping::getSupportedDrivers())
|
||||
->keys()
|
||||
->filter(fn (string $carrier) => ShipmentResource::fulfillmentService($carrier) instanceof SupportsManifestBatching);
|
||||
|
||||
return $carriers->mapWithKeys(fn (string $carrier) => [
|
||||
$carrier => Tab::make(ucwords(str_replace('-', ' ', $carrier)))
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->where('carrier', $carrier)),
|
||||
])->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources\ManifestResource\Pages;
|
||||
|
||||
use Filament\Infolists\Components\TextEntry;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Schema;
|
||||
use Modules\Core\Shipping\Filament\Resources\ManifestResource;
|
||||
|
||||
/**
|
||||
* Relation managers (ShipmentsRelationManager) are registered on
|
||||
* ManifestResource::getRelations() — the actual wiring point
|
||||
* (Filament\Resources\Pages\Concerns\HasRelationManagers::
|
||||
* getAllRelationManagers() reads from Resource::getRelations(), not from
|
||||
* an override here). An earlier version of this page overrode
|
||||
* getRelationManagers() directly, bypassing that trait's own
|
||||
* canViewForRecord()/caching logic and causing a broken Livewire
|
||||
* component mount (surfaced as a 419/redirect loop on this exact page).
|
||||
*/
|
||||
class ViewManifest extends ViewRecord
|
||||
{
|
||||
protected static string $resource = ManifestResource::class;
|
||||
|
||||
public function infolist(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
TextEntry::make('carrier')->badge(),
|
||||
TextEntry::make('reference')->label('Reference')->copyable(),
|
||||
TextEntry::make('shipment_count')->label('Shipments'),
|
||||
TextEntry::make('issued_at')->label('Issued')->dateTime(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources\ManifestResource\RelationManagers;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
/**
|
||||
* The shipments a given Manifest actually included — read-only (a
|
||||
* shipment's manifest membership is set once, at issueManifest() time,
|
||||
* never edited here). Reuses ShipmentResource::printShipment() for the
|
||||
* "Print" action rather than duplicating its try/catch-and-notify
|
||||
* handling.
|
||||
*/
|
||||
class ShipmentsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'shipments';
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('tracking_reference')->label('Tracking #'),
|
||||
TextColumn::make('order.reference')->label('Order'),
|
||||
TextColumn::make('label_printed_at')->label('Printed')->dateTime()->placeholder('Not printed'),
|
||||
TextColumn::make('cancelled_at')->label('Cancelled')->dateTime()->placeholder('—'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('print')
|
||||
->label('Print')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Shipment $record) => ShipmentResource::printShipment($record)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources;
|
||||
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\BulkAction;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Contracts\SupportsManifestBatching;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource\Pages\ListShipments;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Replaces the standalone Modules\Core\Shipping\Filament\Pages\
|
||||
* ManagePickupManifests page — a bare Page has no access to Filament's
|
||||
* resource-level pill-tab UI (Filament\Resources\Concerns\HasTabs is
|
||||
* scoped to ListRecords), so carrier-by-carrier separation
|
||||
* (ListShipments::getTabs(), one tab per SupportsManifestBatching
|
||||
* implementer) needed a real Resource to attach to.
|
||||
*
|
||||
* Shows only shipments NOT yet on an issued manifest — see
|
||||
* Modules\Core\Shipping\Filament\Resources\ManifestResource for
|
||||
* shipments that already are.
|
||||
*/
|
||||
class ShipmentResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Shipment::class;
|
||||
|
||||
protected static string | \BackedEnum | null $navigationIcon = 'heroicon-o-truck';
|
||||
|
||||
protected static string | \UnitEnum | null $navigationGroup = 'Sales';
|
||||
|
||||
protected static ?string $navigationLabel = 'Pending Vouchers';
|
||||
|
||||
protected static ?string $modelLabel = 'Shipment';
|
||||
|
||||
protected static ?int $navigationSort = 100;
|
||||
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
return parent::getEloquentQuery()
|
||||
->whereNull('manifest_id')
|
||||
->whereNull('cancelled_at');
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('carrier')->badge(),
|
||||
TextColumn::make('tracking_reference')->label('Tracking #'),
|
||||
TextColumn::make('order.reference')->label('Order'),
|
||||
TextColumn::make('label_printed_at')->label('Printed')->dateTime()->placeholder('Not printed'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('print')
|
||||
->label('Print')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Shipment $record) => self::printShipment($record)),
|
||||
])
|
||||
->toolbarActions([
|
||||
BulkAction::make('print_selected')
|
||||
->label('Print selected')
|
||||
->icon('heroicon-o-printer')
|
||||
->action(fn (Collection $records) => $records->each(fn (Shipment $shipment) => self::printShipment($shipment))),
|
||||
BulkAction::make('issue_manifest')
|
||||
->label('Issue Manifest')
|
||||
->icon('heroicon-o-check-circle')
|
||||
->action(fn (Collection $records) => self::issueManifest($records)),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function printShipment(Shipment $shipment): void
|
||||
{
|
||||
$service = self::fulfillmentService($shipment->carrier);
|
||||
|
||||
if (! $service) {
|
||||
Notification::make()
|
||||
->title("No fulfillment integration configured for {$shipment->carrier}.")
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$service->printLabel($shipment);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()
|
||||
->title("Failed to print label for {$shipment->tracking_reference}: {$e->getMessage()}")
|
||||
->danger()
|
||||
->send();
|
||||
}
|
||||
}
|
||||
|
||||
public static function issueManifest(Collection $shipments): void
|
||||
{
|
||||
$shipments->groupBy('carrier')->each(function (Collection $group, string $carrier) {
|
||||
$service = self::fulfillmentService($carrier);
|
||||
|
||||
if (! $service instanceof SupportsManifestBatching) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$result = $service->issueManifest($group);
|
||||
} catch (Throwable $e) {
|
||||
report($e);
|
||||
|
||||
Notification::make()
|
||||
->title("Failed to issue manifest for {$carrier}: {$e->getMessage()}")
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (! $result->success) {
|
||||
Notification::make()
|
||||
->title("Manifest blocked for {$carrier}: {$result->reason}")
|
||||
->danger()
|
||||
->send();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Notification::make()
|
||||
->title("Manifest issued for {$carrier}: {$result->reference}")
|
||||
->success()
|
||||
->send();
|
||||
});
|
||||
}
|
||||
|
||||
public static function fulfillmentService(string $carrier): ?CarrierFulfillmentInterface
|
||||
{
|
||||
return app(CarrierFulfillmentInterface::class, ['carrier' => $carrier]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListShipments::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Filament\Resources\ShipmentResource\Pages;
|
||||
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Lunar\Shipping\Facades\Shipping;
|
||||
use Modules\Core\Shipping\Contracts\SupportsManifestBatching;
|
||||
use Modules\Core\Shipping\Filament\Resources\ShipmentResource;
|
||||
|
||||
/**
|
||||
* One tab per carrier that actually implements SupportsManifestBatching
|
||||
* (ACS today) — a carrier with no manifest concept at all (Box Now,
|
||||
* which books courier pickup at shipment-creation time, no separate
|
||||
* batching step) never gets a tab here, since there is nothing to batch.
|
||||
* Adding a new carrier (e.g. Speedex) that also implements the contract
|
||||
* needs zero changes to this page — the tab list is derived from
|
||||
* Shipping::getSupportedDrivers(), not hardcoded.
|
||||
*/
|
||||
class ListShipments extends ListRecords
|
||||
{
|
||||
protected static string $resource = ShipmentResource::class;
|
||||
|
||||
public function getTabs(): array
|
||||
{
|
||||
$carriers = collect(Shipping::getSupportedDrivers())
|
||||
->keys()
|
||||
->filter(fn (string $carrier) => ShipmentResource::fulfillmentService($carrier) instanceof SupportsManifestBatching);
|
||||
|
||||
return $carriers->mapWithKeys(fn (string $carrier) => [
|
||||
$carrier => Tab::make(ucwords(str_replace('-', ' ', $carrier)))
|
||||
->modifyQueryUsing(fn (Builder $query) => $query->where('carrier', $carrier)),
|
||||
])->all();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Routing\Controller;
|
||||
use Modules\Core\Shipping\Contracts\CarrierFulfillmentInterface;
|
||||
use Modules\Core\Shipping\Models\Shipment;
|
||||
|
||||
/**
|
||||
* Streams a carrier's raw label bytes (CarrierFulfillmentInterface::
|
||||
* printLabel() — already whatever file format the carrier's own API
|
||||
* returns, e.g. a PDF for both ACS and Box Now today) straight to the
|
||||
* browser. Only reachable via a short-lived signed URL (see
|
||||
* Modules\Core\Shipping\Extensions\OrderShipmentsExtension's "Print
|
||||
* Label" action) — the same auth model Lunar's own vendor
|
||||
* DownloadPdfController uses for order PDFs (a valid signature IS the
|
||||
* auth check; there is no separate staff-session check here, matching
|
||||
* that precedent), so the link only works for the few minutes it's
|
||||
* actually open in a browser tab.
|
||||
*
|
||||
* Looks the Shipment up manually from a plain {shipment} id rather than
|
||||
* relying on implicit route-model-binding — this route is registered via
|
||||
* loadRoutesFrom() with no middleware group (see
|
||||
* Modules\Core\Providers\ShippingServiceProvider::boot()), so
|
||||
* SubstituteBindings never runs and a type-hinted Shipment parameter
|
||||
* silently resolves to an empty, non-existent model instead of 404ing.
|
||||
*
|
||||
* Sets label_printed_at as a side effect of a successful stream — this is
|
||||
* the first place in the codebase that actually delivers a label's bytes
|
||||
* to a human; the existing Modules\Core\Shipping\Filament\Pages\
|
||||
* ManagePickupManifests "Print" action calls printLabel() too, but only
|
||||
* to mark the timestamp, discarding the returned bytes entirely (no
|
||||
* download route existed until this one).
|
||||
*/
|
||||
class DownloadShipmentLabelController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, int $shipment)
|
||||
{
|
||||
if (! $request->hasValidSignature()) {
|
||||
abort(401);
|
||||
}
|
||||
|
||||
$shipment = Shipment::findOrFail($shipment);
|
||||
|
||||
$service = app(CarrierFulfillmentInterface::class, ['carrier' => $shipment->carrier]);
|
||||
|
||||
$bytes = $service->printLabel($shipment);
|
||||
|
||||
return response($bytes, 200, [
|
||||
'Content-Type' => 'application/pdf',
|
||||
'Content-Disposition' => 'inline; filename="shipment-'.$shipment->tracking_reference.'.pdf"',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace Modules\Core\Shipping\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* A carrier pickup-list/manifest as WE recorded it at the moment it was
|
||||
* issued (Modules\Core\Shipping\Contracts\SupportsManifestBatching::
|
||||
* issueManifest()) — the carrier's own API (ACS's ACS_Issue_Pickup_List
|
||||
* included) typically returns nothing beyond a reference number, so this
|
||||
* table is the only place "which shipments were on manifest X, and when"
|
||||
* is ever recorded; it cannot be re-derived from the carrier later.
|
||||
*/
|
||||
class Manifest extends Model
|
||||
{
|
||||
protected $guarded = [];
|
||||
|
||||
protected $casts = [
|
||||
'issued_at' => 'datetime',
|
||||
];
|
||||
|
||||
public function shipments(): HasMany
|
||||
{
|
||||
return $this->hasMany(Shipment::class);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,11 @@ class Shipment extends Model
|
||||
return $this->belongsTo(Order::class);
|
||||
}
|
||||
|
||||
public function manifest(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Manifest::class);
|
||||
}
|
||||
|
||||
public function shipmentInfo(): HasMany
|
||||
{
|
||||
return $this->hasMany(ShipmentInfo::class);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user