diff --git a/README.md b/README.md index e4781fe..880510f 100644 --- a/README.md +++ b/README.md @@ -342,17 +342,6 @@ composer test # pest + phpstan vendor/bin/pint # code style ``` -While Lunar v2 is in alpha, `lunarphp/core` on Packagist can lag behind the -contracts this package builds against. To test against a local monorepo -checkout, point Composer at it (not committed, both paths are local to you): - -```bash -composer config repositories.lunar '{"type":"path","url":"../lunar/packages/core","options":{"symlink":true}}' -composer require "lunarphp/core:2.x-dev" -W -``` - -Revert with `git checkout -- composer.json && composer update lunarphp/core`. - ### Known follow-ups - The suite runs serially in CI. Two files reach for helpers and fake gateway diff --git a/composer.json b/composer.json index 8f2dbf6..3a55bd5 100644 --- a/composer.json +++ b/composer.json @@ -20,22 +20,18 @@ "homepage": "https://lunarphp.io/" } ], - "repositories": [ - { - "type": "vcs", - "url": "https://github.com/lunarphp/lunar" - } - ], "require": { "php": "^8.4", "inertiajs/inertia-laravel": "^2.0|^3.0", "lunarphp/core": "^2.0@dev", - "lunarphp/lunarmono": "dev-checkout-deps as 2.x-dev", "spatie/laravel-data": "^4.23" }, "require-dev": { "larastan/larastan": "^3.0", "laravel/pint": "1.29.0", + "lunarphp/panel": "^2.0@alpha", + "lunarphp/stripe": "^2.0@alpha", + "lunarphp/table-rate-shipping": "^2.0@alpha", "mockery/mockery": "^1.6.9", "orchestra/testbench": "^10.0|^11.0", "pestphp/pest": "^3.0|^4.0", diff --git a/config/checkout.php b/config/checkout.php index 4759e0a..1478069 100644 --- a/config/checkout.php +++ b/config/checkout.php @@ -146,6 +146,14 @@ // webhook-less fallback. Small enough that a stuck customer is not // stuck, large enough not to race the immediate post-confirm webhook. 'on_view_after_seconds' => 5, + + // How long (minutes, aged on the pin) an intent may wait on the + // customer before it is voided and the session reopens for a retry + // on a fresh intent. A declined card and an abandoned 3-D Secure + // challenge both read as waiting on the customer and neither settles + // on its own, so without this the cart stays locked. Long enough to + // finish a challenge or a bank redirect. + 'requires_action_minutes' => 30, ], /* diff --git a/phpunit.xml b/phpunit.xml index c468861..0cbb54b 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -14,7 +14,7 @@ - + diff --git a/spec/0000-overview.md b/spec/0000-overview.md index ba5155e..649be2d 100644 --- a/spec/0000-overview.md +++ b/spec/0000-overview.md @@ -48,7 +48,7 @@ lunar/checkout Everything checkout. The element model: capability interfaces elements/gateways contribute Vue UI via runtime chunks, no rebuild (0009). │ ├── lunar/core The seams checkout rides: the cart API (Cart::set*), ShippingManifest, - │ Payments/AbstractPayment — plus ONE addition, the SupportsPaymentIntents + │ Payments/AbstractPayment, plus ONE addition, the ReconcilesPaymentIntents │ capability contract (fetch/void/refund by intent) gateway drivers adopt │ for the integrity protocol (0010). No checkout code. │ @@ -91,7 +91,7 @@ client. | 0009 | Frontend element extension | How third-party elements/gateways contribute Vue UI into the prebuilt app at runtime — `CheckoutAssets` registry, contributed ES-module chunks served same-origin, shared Vue + SDK via `window.Vue`/`window.Lunar` externals, build preset, version/fallback; first-party gateways prebuilt | | 0006 | Worked example (guide) | End-to-end walkthrough of one reference checkout through the Inertia spine — element impl, registration, session, DTO, Vue render, payment method, completion. Illustrative, not normative | | 0007 | Discount element | Resolves 0001's open question: discount is a `Summary`-region `CapturesData` element; adds an additive `Cart::setCoupon()` so it persists through the cart API | -| 0010 | Cart–session reconciliation | Backend-neutral session data model (no Lunar FKs; store only non-derivable); the full `CheckoutDriver` store/read surface; element bag; **driver-owned fingerprint + sync-while-Open + pin-and-confirm-at-pay** integrity with the completion re-verify + refund invariant; void-first invalidation on every terminalizing transition; one-active-session-per-cart via guarded unique-column concurrency; the `SupportsPaymentIntents` gateway seam; bounded `PaymentProcessing` reconciliation + stall protocol; lifecycle events | +| 0010 | Cart–session reconciliation | Backend-neutral session data model (no Lunar FKs; store only non-derivable); the full `CheckoutDriver` store/read surface; element bag; **driver-owned fingerprint + sync-while-Open + pin-and-confirm-at-pay** integrity with the completion re-verify + refund invariant; void-first invalidation on every terminalizing transition; one-active-session-per-cart via guarded unique-column concurrency; the `ReconcilesPaymentIntents` gateway seam; bounded `PaymentProcessing` reconciliation + stall protocol; lifecycle events | ### Cross-cutting decisions (apply to all specs) @@ -155,7 +155,7 @@ client. landing; future breaking changes require a spec + Rector rule per the package rule. - The checkout concern lives in its own `packages/checkout` sub-package (`Lunar\Checkout\…`), not a new core `Checkout/` folder — core's spec-0013 list is untouched; core gains only the - `SupportsPaymentIntents` capability contract (`Contracts/`, additive). + `ReconcilesPaymentIntents` capability contract (`Contracts/`, additive). - Depends on the planned `public_id` (ULID) and Region/`StorefrontContext` TODO items; until they land, cart identity stays resolved server-side via `CartSession` and the country list stays channel-scoped. @@ -184,7 +184,7 @@ client. ([[0008-checkout-ui-and-theming]]). It is **not** embedded into a consumer's Vue build; any storefront stack links to it. `storefront-ui` is a reference host with it installed. The Lunar-hosted page ([[0005-hosted-checkout]]) is the same app under a Lunar-operated deployment. - Core gains only the `SupportsPaymentIntents` capability contract. + Core gains only the `ReconcilesPaymentIntents` capability contract. - A transport-free **`checkout-core` split** (element model + session + driver, no Inertia/Vue) so a REST-only consumer (`lunar/api`) need not depend on the Inertia app package — recorded as an open question, not done now. (Owner: package maintainer.) diff --git a/spec/0001-core-element-model.md b/spec/0001-core-element-model.md index 44fdfc7..d4588f1 100644 --- a/spec/0001-core-element-model.md +++ b/spec/0001-core-element-model.md @@ -130,7 +130,7 @@ the configured validators and `recalculate()`: | Element | Write path | |---------|-----------| | `ContactInformation` | `$context->storeContact($validated)` → (driver) `storeContact` — guest email/phone ([[0010-cart-session-reconciliation]] §B); contact is **not** an address write | -| `AddressElement` | `$context->storeShippingAddress($validated)` / `storeBillingAddress($validated)` → (driver) → `Cart::setShippingAddress()` / `setBillingAddress()` (→ `AddAddress` action, `lunar.cart.validators.add_address`, tax-zone clear, recalc) | +| `AddressElement` | `$context->storeShippingAddress($validated)` / `storeBillingAddress($validated)` → (driver) → `Cart::setShippingAddress()` / `setBillingAddress()` (→ `AddAddress` action, the `StepList::AddAddressValidation` steps, tax-zone clear, recalc) | | `ShippingOptionsElement` | `$context->setShippingOption($identifier)` → (driver) resolves via `ShippingManifest::getOption($cart, $identifier)` → `Cart::setShippingOption($option)` (→ `SetShippingOption` action + validator + recalc); persists identifier only | Direct `fill()->save()` is forbidden: it bypasses the validators and the recalculation, letting diff --git a/spec/0002-payment-methods-and-driver.md b/spec/0002-payment-methods-and-driver.md index 246f7ec..4707413 100644 --- a/spec/0002-payment-methods-and-driver.md +++ b/spec/0002-payment-methods-and-driver.md @@ -65,15 +65,19 @@ like the element capability interfaces ([[0001-core-element-model]] §B): ```php namespace Lunar\Core\Contracts; -interface SupportsPaymentIntents +interface ReconcilesPaymentIntents { - public function fetchIntent(string $ref): PaymentIntentStatus; // enum: Pending, RequiresCapture, - // Captured, Voided, Failed - public function voidIntent(string $ref): void; - public function refundIntent(string $ref, int $amountMinor, string $idempotencyKey): string; // refund ref + // Null when the driver did not create the reference for the cart. + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot; + public function voidIntent(Cart $cart, string $reference): void; + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund; } ``` +`PaymentIntentSnapshot::$status` is a `PaymentIntentStatus`: `RequiresAction`, `Processing`, +`RequiresCapture`, `Captured`, `Voided` or `Failed`. `PaymentRefund::$reference` is the +gateway's refund id. + A gateway that does not implement it **cannot be voided or reconciled**: its sessions stay in `PaymentProcessing` and flow into the stall protocol ([[0010-cart-session-reconciliation]] §F). The interface is also the test seam — the contract-test fake gateway implements it (§E, @@ -153,9 +157,9 @@ re-verifying against the **session** total/currency before transition: - Recompute the session cart's total and verify `intent.amount`/`currency` match before capture/transition; on mismatch, fail and void/refund — routed through - `SupportsPaymentIntents` (§A). + `ReconcilesPaymentIntents` (§A). - Idempotent webhook handling (atomic claim), transaction recording, and intent reconciliation — - the fetch/void/refund-by-intent calls route through `SupportsPaymentIntents` (§A). + the fetch/void/refund-by-intent calls route through `ReconcilesPaymentIntents` (§A). - **Advisory intents.** `payment_intent_ref` is recorded at intent **creation**. A gateway success event that resolves to a non-current intent, or to a session not in `PaymentProcessing`, is **refunded** (`refundIntent`) — it never completes. Terminalizing an @@ -201,7 +205,7 @@ session's `PaymentProcessing` state (which rejects element stores), not a cart f - New `Lunar\Checkout\Contracts\PaymentMethod` + a payment-method registry (in `lunar/checkout`, gateway-agnostic) and the payment host element. **No dependency on `lunar/stripe`.** -- New **core** capability contract `Lunar\Core\Contracts\SupportsPaymentIntents` + the +- New **core** capability contract `Lunar\Core\Contracts\ReconcilesPaymentIntents` + the `PaymentIntentStatus` enum (§A) — additive, opt-in via `instanceof`; existing gateways are unaffected until they adopt it. - `lunar/stripe` (optional) gains a `StripeCardMethod implements PaymentMethod` + a prebuilt @@ -219,7 +223,7 @@ session's `PaymentProcessing` state (which rejects element stores), not a cart f - A payment-method **contract test** fixture each gateway runs to prove the seam (method resolves a registered `AbstractPayment` driver; submit → `authorize()` → `AwaitingPayment → InProcess` + `placed_at` + `Transaction` rows). The fixture's **fake gateway implements - `SupportsPaymentIntents`** (§A) so the intent-keyed verbs are exercised end-to-end. + `ReconcilesPaymentIntents`** (§A) so the intent-keyed verbs are exercised end-to-end. - A gateway success event for a **non-current intent**, or for a session **not in `PaymentProcessing`**, is refunded via `refundIntent` and never completes the session (§E). - Terminalizing an `Open` session **voids its advisory intent first** via `voidIntent` (§E, diff --git a/spec/0006-worked-example.md b/spec/0006-worked-example.md index c85a839..270cc07 100644 --- a/spec/0006-worked-example.md +++ b/spec/0006-worked-example.md @@ -42,7 +42,7 @@ Three packages, one contract ([[0000-overview]]): facade, the built-in element impls, the `/checkout/{uuid}/elements/{handle}` Inertia multiplexer. (A transport-free `checkout-core` split is an open question — [[0000-overview]].) - **`lunar/core`** — the surfaces checkout rides: `Cart::set*`, `ShippingManifest`, - `Payments`/`AbstractPayment` (plus the `SupportsPaymentIntents` capability). No checkout code. + `Payments`/`AbstractPayment` (plus the `ReconcilesPaymentIntents` capability). No checkout code. - **`lunar/api`** — the REST projection of the same DTO (not the spine here; see [[0003-transport-projections]] §A). This walkthrough uses the **Inertia spine**: the self-contained checkout app renders `` diff --git a/spec/0010-cart-session-reconciliation.md b/spec/0010-cart-session-reconciliation.md index a06bac9..6704636 100644 --- a/spec/0010-cart-session-reconciliation.md +++ b/spec/0010-cart-session-reconciliation.md @@ -386,10 +386,15 @@ second order, and the synchronous path creates or adopts it inside `complete()`: `Open`, so a session reopened mid-completion is never completed. Under the same lock, money stays put when the session was re-pinned against another intent meanwhile, or when the gateway's own `authorize()` placed an order - for the cart since the pin (the failure came after placement): that records - an attempt and stalls to the operator instead. An attempt is only counted - while the session is still `PaymentProcessing`, and before any listener - runs. Residual: a gateway that places the order in its own transaction + for this payment (the failure came after placement): that records an + attempt and stalls to the operator instead. An order counts as placed for + this payment when the gateway announced it for the session's current intent + (the success listener notes the order and the intent on the session before + it pins or completes, because a session pinned by that announcement is + pinned after the order was placed), or when it was placed since the pin. An + order an earlier checkout of the same cart placed is neither. An attempt is + only counted while the session is still `PaymentProcessing`, and before any + listener runs. Residual: a gateway that places the order in its own transaction without touching the session row (Stripe's `authorize()` does) can still commit that placement while the refund is in flight, so "never refunded" holds against checkout's own completion, not against every gateway's. `CheckoutCompletionFailed` @@ -411,9 +416,17 @@ second order, and the synchronous path creates or adopts it inside `complete()`: attempts fire `CheckoutSessionReconciliationStalled`. `CheckoutCompletionFailed` fires with a `reason` distinguishing **refunded / refund-pending / refund-failed**, carrying the refund - reference when one exists. A non-Lunar driver may substitute its own - remediation (a backorder, a manual-review hold) but MUST NOT silently - retain a charge that produced no order. + reference when one exists. A gateway keeps reporting a refunded intent as + captured (a Stripe intent stays `succeeded`), so every pass reads the + intent snapshot's refunded amount before it completes anything. A fully + refunded intent means an earlier pass returned the money and never + committed the reopen (it died after the refund, or the gateway's answer + was lost): the session moves `→ Open` with `refunded` and no reference, + without a second refund call. A partly refunded intent was refunded by + someone else and still holds money with no order, so it records an attempt + and stalls to the operator. Neither is ever completed. A non-Lunar driver + may substitute its own remediation (a backorder, a manual-review hold) but + MUST NOT silently retain a charge that produced no order. - **The draft survives, unplaced.** Neither a void nor a refund touches the order the pin drafted: it stays on the cart with `placed_at` null and no session points at it. The next Pay on the reopened session reuses that same @@ -476,9 +489,10 @@ exists, is voided **before** the terminal transition, and an unabortable / unknown-outcome void blocks the terminal transition exactly as above. Every intent operation in §E.2/§F — fetch, void, refund — goes through the new -core gateway capability interface `Lunar\Core\Contracts\SupportsPaymentIntents` -(`fetchIntent(string $ref)`, `voidIntent(string $ref)`, `refundIntent(string -$ref, int $amount, string $idempotencyKey)`), `instanceof`-checked on the +core gateway capability interface `Lunar\Core\Contracts\ReconcilesPaymentIntents` +(`fetchIntent(Cart $cart, string $reference)`, `voidIntent(Cart $cart, string +$reference)`, `refundIntent(Cart $cart, string $reference, PriceValue $amount, +string $idempotencyKey)`), `instanceof`-checked on the gateway driver ([[0002-payment-methods-and-driver]] carries the seam detail). A gateway that does not implement it cannot void — its session stays `PaymentProcessing` and resolves through the stall protocol below. @@ -491,7 +505,21 @@ aged on `payment_processing_at`, §A) and **forces reconciliation** through the gateway driver: `fetchIntent` → §E.2 (complete / refund) or void → `Open` (return-path hygiene, §E.2). Each run increments `reconciliation_attempts`; a still-pending intent on a slow method (bank transfer, voucher) **reschedules -without consuming an attempt**, up to a method-declared deadline. After the +without consuming an attempt**, up to a method-declared deadline. An intent +still **waiting on the customer** (a declined card, an abandoned challenge, an +async method that failed back to "pick another method") never settles on its +own, so it is pending only for `reconciliation.requires_action_minutes` +(default 30, aged on `payment_processing_at`); past that the intent is +**voided first** and the session then returns to `Open` with the reference +cleared (return-path hygiene, §E.2), no attempt consumed and no event, so the +customer retries on a fresh intent. The void is what makes the reopen safe: an +intent left confirmable could take a payment after the session reopened, when +the sweep no longer watches it and a retry would mint a second intent. A void +the gateway refuses (the payment went through between the fetch and the void) +leaves the session `PaymentProcessing` and consumes an attempt, so the next +pass settles on the real status, and a void that keeps failing stalls. The +customer-initiated release is the exception that keeps the intent: the customer +is on the page with the payment element still bound to it. After the maximum attempts the session is **stalled**: `CheckoutSessionReconciliationStalled` fires **once** (never per-run noise), and the session drops to a **low-frequency retry tier** — not silence. The @@ -503,6 +531,19 @@ until one of those exits applies. Retention pruning anchors on the terminal timestamps (`completed_at` / `cancelled_at` / `expires_at`); a stalled session is pruned only after it reaches a terminal state through a sanctioned exit. +**Return from a failed redirect.** A redirect payment method (Klarna, PayPal, a +full-page 3DS challenge) that fails or is cancelled sends the customer back to +the session URL with the session still pinned, and the in-page release never +ran because the browser had left the page. When that request carries Stripe's +`redirect_status=failed` for the session's own `payment_intent`, the session +page runs the customer-initiated release before it renders: `→ Open` with the +intent kept, only on the gateway's word that nothing was captured (a captured +intent resolves through §E.2 instead), then a redirect to the retry state. +Without those parameters the session waits out the window above. Stripe's +return URL documentation lists `payment_intent` but not `redirect_status`, so +the shortcut depends on a parameter Stripe sends without documenting it, and +its absence only costs the wait. + ### F.2 One active session per cart `cart_reference` 1:N sessions is per-*attempt* history, not per-attempt @@ -572,7 +613,7 @@ states (`Expired`, etc.); the table does not duplicate those. `src/DataObjects/` (`Lunar\Checkout\DataObjects\…`). - **Driver surface:** the §B verbs added to `CheckoutDriver`, plus the mandatory `AbstractCheckoutDriver` base class (§B). New core gateway capability - interface `Lunar\Core\Contracts\SupportsPaymentIntents` (§F). + interface `Lunar\Core\Contracts\ReconcilesPaymentIntents` (§F). - **Session API:** `hasDrifted()`, `putElementData()` / `getElementData()`. - **Actions:** `SyncCheckoutSession` (guarded single-statement re-sync while `Open`, §D), `InvalidateCheckoutSession` (void-first → `Cancelled` + reason, @@ -757,6 +798,6 @@ states (`Expired`, etc.); the table does not duplicate those. - `Lunar\Core\Models\Cart::setShippingAddress()` / `setBillingAddress()` / `setShippingOption()`, `Lunar\Core\Validation\Cart\ValidateCartForOrderCreation`, - `Lunar\Core\Contracts\SupportsPaymentIntents` (new, §F). Core's + `Lunar\Core\Contracts\ReconcilesPaymentIntents` (new, §F). Core's `Cart::fingerprint()` / `checkFingerprint()` / `GeneratesFingerprint` dedupe machinery is explicitly **not** a dependency (§D). diff --git a/spec/0012-express-payments.md b/spec/0012-express-payments.md index d75bdce..36dc2f7 100644 --- a/spec/0012-express-payments.md +++ b/spec/0012-express-payments.md @@ -42,11 +42,11 @@ session state. The state machine tracks money-safety states, not UI location. ### A. `SupportsPaymentHolds` (core capability) -New opt-in contract in `lunar/core` beside `CreatesPaymentIntents` / `SupportsPaymentIntents` / +New opt-in contract in `lunar/core` beside `CreatesPaymentIntents` / `ReconcilesPaymentIntents` / `SyncsPaymentIntents`, checked via `instanceof`, never a required part of `PaymentType`: ```php -interface SupportsPaymentHolds +interface SupportsPaymentHolds extends ReconcilesPaymentIntents { /** * Create (or resume) the cart's authorise-only intent: capture deferred, @@ -60,19 +60,19 @@ interface SupportsPaymentHolds * hold now covers it; NeedsReauthorization when this hold cannot stretch * (the customer re-opens the wallet for a fresh authorisation). */ - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment; + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment; /** * Capture an authorised hold for the final amount (<= authorised). * Idempotent per reference. MUST throw when the gateway cannot confirm * the capture; an unknown outcome is not a capture. */ - public function captureHold(string $reference, int $amountMinor): void; + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void; } ``` - `HoldAdjustment` is an enum: `Ok | NeedsReauthorization`. -- Releasing a hold is the existing `SupportsPaymentIntents::voidIntent()`; no new verb. +- Releasing a hold is the existing `ReconcilesPaymentIntents::voidIntent()`; no new verb. - **Express eligibility** = `$method->supportsExpress() && $driver instanceof SupportsPaymentHolds && $method->isAvailable($cart)`. A gateway that cannot hold cannot be express; the squeeze page's "not charged until you confirm" promise is only honest with a hold. @@ -165,7 +165,10 @@ session whose intent is hold-flavoured: 1. Total above authorised: `adjustHold`, BEFORE the pin (where the standard flow syncs its intent amount; a confirmed hold's amount cannot be edited, so holds adjust instead of syncing). `NeedsReauthorization` is a structured 422 with the session still `Open`: - nothing to unpin, the UI opens the re-open-wallet panel. + nothing to unpin, the UI opens the re-open-wallet panel. A hold the gateway refuses to + adjust at all (a `PaymentIntentException`: not this cart's, or no longer awaiting + capture) is reported and gets the same 422. A cart that has left the session's currency + skips the adjustment, because gate step 0 voids the hold and cancels the session. 2. Fingerprint pin, exactly as the standard flow (the squeeze page echoes the fingerprint it rendered; any drift is the existing `fingerprint_mismatch` 422). `Open -> PaymentProcessing`; the client is sent to the existing `processing` URL. diff --git a/spec/0013-pickup-points.md b/spec/0013-pickup-points.md index 26b15cd..4773c31 100644 --- a/spec/0013-pickup-points.md +++ b/spec/0013-pickup-points.md @@ -14,11 +14,11 @@ Click and collect works end to end in Lunar core and stops one step short in this package. **What core already does.** A collect order is any order whose shipping line carries -`meta.collect = true`. The `collection` shipping driver returns a `ShippingOption` with -`collect: true` and a `meta` array; `Pipelines\Order\Creation\CreateShippingLine` merges that -meta (plus the `collect` flag) onto the shipping order line; `FulfilmentMethods\Collection` +`meta.pickup = true`. The `pickup` shipping driver returns a `ShippingOption` with +`pickup: true` and a `meta` array; `Pipelines\Order\Creation\CreateShippingLine` merges that +meta (plus the `pickup` flag) onto the shipping order line; `FulfilmentMethods\Pickup` claims the order's physical lines by reading exactly that array and runs -Pending → Ready for collection → Collected; `ValidateCartForOrderCreation` waives the +Pending → Ready for pickup → Picked up; `ValidateCartForOrderCreation` waives the shipping-address requirement for a collect option. `FillOrderFromCart` also copies `cart.meta` onto `orders.meta`, and every shipping driver receives the cart in its `ShippingOptionRequest`. None of this knows *where* the customer collects from, and none of it needs to: with no pickup @@ -41,7 +41,7 @@ locations defined, an order simply is a collection order. is dropped by `LunarCheckoutDriver::getShippingOptions()` and never reaches the client. 4. **The panel cannot tell a collect order apart** beyond the fulfilment card's method badge. `OrderShowController::shippingOption()` reads the breakdown item, which carries neither - `collect` nor meta. + `pickup` nor meta. ## Proposal @@ -134,7 +134,7 @@ public function execute(Cart $cart, string $mode, ?string $pickupPoint = null): Behaviour: - `mode = 'collect'`: write `meta.fulfilment`. If a shipping address row exists, resolve the - cart's collect option through `ShippingManifest::getOptions($cart)->firstWhere('collect', true)` + cart's collect option through `ShippingManifest::getOptions($cart)->firstWhere('pickup', true)` and store it via `$cart->setShippingOption()` (a collect-capable cart always has exactly one; a cart with none keeps its current option and the projection says collect is unavailable). Then apply the point: the given handle if valid, else the single point if the provider offers @@ -187,7 +187,7 @@ public function handle(Cart $cart, Closure $next): mixed if (is_array($point)) { foreach (app(ShippingManifest::class)->options as $option) { - if ($option->collect) { + if ($option->pickup) { $option->meta = array_merge($option->meta ?? [], ['pickup_point' => $point]); } } @@ -199,18 +199,19 @@ public function handle(Cart $cart, Closure $next): mixed That is the whole write path. `ShippingManifest::getOption()` re-resolves the option from the cart at order creation, `CreateShippingLine` stamps the meta onto the shipping line, and the -placed order carries `order_lines(shipping).meta = {collect: true, …, pickup_point}`. It +placed order carries `order_lines(shipping).meta = {pickup: true, …, pickup_point}`. It works for any collect-capable driver, including a static `ShippingManifest::addOption()`, so the package's own tests can assert the line meta without table-rate-shipping. The checkout package does not touch the order and `OrderPlacing` listeners are not involved. `orders.meta.pickup_point` also arrives via `FillOrderFromCart`; the shipping line copy is -the normative one, because that is where `collect` lives and what the fulfilment method reads. +the normative one, because that is where `pickup` lives and what the fulfilment method reads. ### D. Validation through Lunar's seam `Validation\Cart\PickupPointRequired extends Lunar\Core\Validation\BaseValidator`, -appended by `CheckoutServiceProvider::register()` to `lunar.cart.validators.order_create` -after core's `ValidateCartForOrderCreation`: +appended in `CheckoutServiceProvider::boot()` with +`Steps::for(StepList::OrderCreateValidation)->append(...)`, after core's +`ValidateCartForOrderCreation`: - fail on `fulfilment` when `meta.fulfilment` and the stored option disagree (collect mode with a non-collect option, or the reverse), which is only reachable by a writer that bypassed @@ -299,14 +300,14 @@ The host owns that endpoint's route and auth; the action is the reuse boundary. ### H. Panel (sibling change: `panel`) `OrderShowController::shippingOption()` reads the shipping line in both branches and adds -`collect: bool` and `pickup_point: ?{handle, name, lines}` from `$line->meta`. The order -screen's Shipping section swaps the truck icon for the store icon when `collect` is true and +`pickup: bool` and `pickup_point: ?{handle, name, lines}` from `$line->meta`. The order +screen's Shipping section swaps the truck icon for the store icon when `pickup` is true and renders "Collect from {name}" with the lines beneath the method name. Nothing else changes: the fulfilment card already badges the method and drives its states; `location` stays the stock location, which is a different concept from the pickup point and deliberately not conflated. The order's shipping address on a collect order is the customer's own address (§F.1). Anything -that renders it as "Delivery address", in this panel or in a host, must check `collect` first +that renders it as "Delivery address", in this panel or in a host, must check `pickup` first and say so. The panel's Shipping address section is relabelled "Customer address" when the shipping line collects. @@ -330,14 +331,14 @@ Package (feature, alongside the existing checkout suite): - express start response carries the three keys; squeeze page confirm in collect mode with a point places the order with the point on the line. -`panel`: `OrderShowController` exposes `collect` and `pickup_point` for a collect order and -`collect: false` for a delivery order. +`panel`: `OrderShowController` exposes `pickup` and `pickup_point` for a collect order and +`pickup: false` for a delivery order. ## Out of scope - Offline / pay-later for collect orders. `PaymentMethods\Offline` already exists as the mechanism; when it is wanted, the host registers it with an `appliesTo()` that reads the - stored option's `collect` flag, exactly as its docblock illustrates. The decision for the + stored option's `pickup` flag, exactly as its docblock illustrates. The decision for the first storefront is that offline payment belongs to on-account orders, which are a separate piece of work. - Per-point availability (stock at a branch, opening hours, cut-offs). The provider gets the diff --git a/spec/RESUME.md b/spec/RESUME.md index a5a41a0..648f9df 100644 --- a/spec/RESUME.md +++ b/spec/RESUME.md @@ -12,7 +12,7 @@ Pick up the Lunar checkout-session work. Context: `active_cart_reference` unique-column concurrency; single-statement guarded session writes (guarded-transition helper = concurrency layer, spatie machine = legality layer); gate step 0 (currency/channel); sync-path gate inside `complete()`'s order transaction; the - `SupportsPaymentIntents` core capability seam; stall protocol + operator resolve; renames + `ReconcilesPaymentIntents` core capability seam; stall protocol + operator resolve; renames (`hasDrifted()`, `scopeExpirable`, `cancelled_at`, `config('lunar.checkout.driver')`); zero-total carts force the sync path; package home pinned to `packages/checkout` (`Lunar\Checkout\…`). - **Implementation: session-core slice LANDED (2026-06-12).** Everything in the Rework/Add lists @@ -51,7 +51,7 @@ Pick up the Lunar checkout-session work. Context: so the driver can't resolve it. - `tests/checkout/Unit/ArchitectureTest.php` — mirror core's arch rules (actions implement a contract, expose `execute()`, no facade imports). -- Core `SupportsPaymentIntents` interface (`packages/core` — small, additive: +- Core `ReconcilesPaymentIntents` interface (`packages/core`, small and additive: fetchIntent/voidIntent/refundIntent). - `AbstractCheckoutDriver` base class (mandatory for third-party drivers). - The guarded-transition helper (single-statement guarded UPDATEs over the spatie machine). diff --git a/spec/overview.md b/spec/overview.md index 95f92a7..d30febc 100644 --- a/spec/overview.md +++ b/spec/overview.md @@ -26,7 +26,7 @@ Three delivery/customisation tiers: | Package | Role | |---|---| | `lunar/checkout` | Everything checkout: the transport-agnostic element model, `CheckoutData` DTO, `CheckoutSession` + the swappable `CheckoutDriver` (default `LunarCheckoutDriver`), `PaymentMethod` registry — **and** the self-contained Inertia app: ``, registry, `CheckoutProvider`, composables, built-in elements, the `CheckoutAssets` extension seam, prebuilt `dist/`. (A transport-free `checkout-core` split is an open question — 0000.) | -| `lunar/core` | The seams checkout rides: `Cart::set*`, `ShippingManifest`, `Payments`/`AbstractPayment` — plus the `SupportsPaymentIntents` capability contract (0010). No checkout code. | +| `lunar/core` | The seams checkout rides: `Cart::set*`, `ShippingManifest`, `Payments`/`AbstractPayment`, plus the `ReconcilesPaymentIntents` capability contract (0010). No checkout code. | | `lunar/api` | REST projection of the same DTO (JSON:API envelope, Sanctum, headers). | | `storefront-ui` | Reference host app with `lunar/checkout` installed (demos install-and-go). | | hosted (future) | The **same** app under a Lunar-operated deployment, rendering a session by UUID. | @@ -116,7 +116,7 @@ Three delivery/customisation tiers: not portable to MySQL); all persisted session writes are single-statement guarded UPDATEs, with the guarded-transition helper as the concurrency layer over the spatie machine (the legality layer); gate step 0 (live currency/channel must equal pinned); the sync path runs the gate inside - `complete()`'s order transaction; the `SupportsPaymentIntents` core capability seam + `complete()`'s order transaction; the `ReconcilesPaymentIntents` core capability seam (fetch/void/refund by intent); the stall protocol + `lunar:checkout:reconcile` operator resolve; consistent-read completion + idempotent `complete()`; new transport verbs (`POST /checkout/{uuid}/pay`, `/contact`, `/elements/{handle}`); `CheckoutData` gains session-level fields (sessionUuid, status, @@ -145,11 +145,11 @@ Three delivery/customisation tiers: CI/release build step. - **Dual-Inertia coexistence** (0008 open question) — if the consumer's storefront also runs Inertia, two apps share a page lifecycle. Expected fine (separate root/manifest/namespace) but unverified. -- **0010 — `SupportsPaymentIntents` is new public surface in `lunar/core`.** Small and additive +- **0010: `ReconcilesPaymentIntents` is new public surface in `lunar/core`.** Small and additive (`Contracts/`, fetch/void/refund by intent), but contract on landing — confirm the verb shape before gateway drivers adopt it, because changing it later needs a spec + Rector rule. - **Gateway adoption of the capability interface.** The void-first/reconcile/refund-by-intent - protocol only works for gateways implementing `SupportsPaymentIntents`; gateways without it flow + protocol only works for gateways implementing `ReconcilesPaymentIntents`; gateways without it flow into the stall protocol (stalled event → low-frequency retries → operator resolve). Confirm that degraded path is acceptable for the gateways merchants actually run. - **0000 — the transport-free `checkout-core` split is unresolved.** Until it is, a REST-only diff --git a/src/Actions/InvalidateCheckoutSession.php b/src/Actions/InvalidateCheckoutSession.php index 9c27e0e..651ca98 100644 --- a/src/Actions/InvalidateCheckoutSession.php +++ b/src/Actions/InvalidateCheckoutSession.php @@ -28,13 +28,14 @@ public function execute(CheckoutSession $session, string $reason): bool { if ($reference = $session->payment_intent_ref) { $gateway = $this->gateways->for($session); + $cart = $this->gateways->cartFor($session); - if ($gateway === null) { + if ($gateway === null || $cart === null) { return false; } try { - $gateway->voidIntent($reference); + $gateway->voidIntent($cart, $reference); } catch (\Throwable) { // Unknown outcome is not a void — the charge may still land. return false; diff --git a/src/Actions/ReconcileCheckoutSession.php b/src/Actions/ReconcileCheckoutSession.php index 7a13ffa..8354d42 100644 --- a/src/Actions/ReconcileCheckoutSession.php +++ b/src/Actions/ReconcileCheckoutSession.php @@ -11,25 +11,31 @@ use Lunar\Checkout\Events\CheckoutSessionInvalidated; use Lunar\Checkout\Events\CheckoutSessionReconciliationStalled; use Lunar\Checkout\Exceptions\PaymentConfirmationException; +use Lunar\Checkout\Listeners\CompleteSessionOnPaymentSuccess; use Lunar\Checkout\Models\CheckoutSession; use Lunar\Checkout\States\CheckoutSession\Cancelled; use Lunar\Checkout\States\CheckoutSession\Completed; use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PaymentIntentGateway; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; +use Lunar\Core\Models\Cart; +use Lunar\Core\Models\Currency; use Lunar\Core\Models\Order; /** * Bounded resolution of a `PaymentProcessing` session (spec 0010 §F): the * gateway's actual intent outcome decides — captured completes (or refunds on * mismatch: no charge survives without an order), voided/failed reopens, - * pending reschedules without consuming an attempt. Exhausted attempts fire - * {@see CheckoutSessionReconciliationStalled} once; the operator `--resolve` - * override is the sanctioned stall exit. + * pending reschedules without consuming an attempt, and an intent left + * waiting on the customer past its window is voided and the session reopens. + * Exhausted attempts fire {@see CheckoutSessionReconciliationStalled} once; + * the operator `--resolve` override is the sanctioned stall exit. */ final class ReconcileCheckoutSession implements ReconcilesCheckoutSession { @@ -50,28 +56,42 @@ public function execute(CheckoutSession $session, ?string $resolve = null): stri $gateway = $this->gateways->for($session); $reference = $session->payment_intent_ref; + $cart = $this->gateways->cartFor($session); if ($resolve !== null) { - return $this->resolveByOperator($session, $gateway, $reference, $resolve); + return $this->resolveByOperator($session, $gateway, $cart, $reference, $resolve); } - if ($gateway === null || $reference === null) { + if ($gateway === null || $cart === null || $reference === null) { return $this->recordAttempt($session); } try { - $status = $gateway->fetchIntent($reference); + $intent = $gateway->fetchIntent($cart, $reference); } catch (PaymentIntentException) { return $this->recordAttempt($session); } + $status = $intent?->status; + return match ($status) { - // Legitimately still in flight (slow methods) — reschedule - // without consuming an attempt (spec 0010 §F). - PaymentIntentStatus::Pending => 'pending', + // Not an intent the gateway created for this cart: unknowable. + null => $this->recordAttempt($session), + + // A slow method that has yet to settle does so on its own: + // reschedule without consuming an attempt (spec 0010 §F). + PaymentIntentStatus::Processing => 'pending', + + // Waiting on the customer covers a recorded decline and an + // abandoned challenge as well as one still under way, and nothing + // settles the first two. Past the window the cart is freed for a + // retry. + PaymentIntentStatus::RequiresAction => $this->waitedOnCustomerTooLong($session) + ? $this->voidAndReopen($session, $gateway, $cart, $reference, 'intent_'.$status->value) + : 'pending', PaymentIntentStatus::Captured, - PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $reference, $status), + PaymentIntentStatus::RequiresCapture => $this->completeOrRefund($session, $gateway, $cart, $reference, $intent), PaymentIntentStatus::Voided, PaymentIntentStatus::Failed => $this->reopen($session, 'intent_'.$status->value), @@ -91,38 +111,57 @@ public function release(CheckoutSession $session): string // An intent exists, so money may exist. Reopen only on the // gateway's word that it was not captured; anything unknowable // stays frozen and the reconciliation sweep owns it. - if ($gateway === null) { + $cart = $this->gateways->cartFor($session); + + if ($gateway === null || $cart === null) { return 'unconfirmed'; } try { - $status = $gateway->fetchIntent($reference); + $intent = $gateway->fetchIntent($cart, $reference); } catch (PaymentIntentException) { return 'unconfirmed'; } - if (in_array($status, [PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture], true)) { + if ($intent === null) { + return 'unconfirmed'; + } + + if (in_array($intent->status, [PaymentIntentStatus::Captured, PaymentIntentStatus::RequiresCapture], true)) { // An authorise-only hold at RequiresCapture is not money // moved: the customer may keep editing and re-confirm, so // reopen with the hold intact instead of forcing completion. - if (! ($session->isHoldMode() && $status === PaymentIntentStatus::RequiresCapture)) { - return $this->completeOrRefund($session, $gateway, $reference, $status); + if (! ($session->isHoldMode() && $intent->status === PaymentIntentStatus::RequiresCapture)) { + return $this->completeOrRefund($session, $gateway, $cart, $reference, $intent); } } } - // Unlike reopen(), the intent reference survives: the customer's - // mounted payment element is still bound to it, the intent is still - // confirmable, and the retry re-syncs its amount at the pay boundary. - $grace = (int) config('lunar.checkout.session.reopen_grace_minutes', 30); + return $this->reopenKeepingIntent($session, 'released'); + } - $session->transitionGuarded([PaymentProcessing::$name], Open::$name, [ - 'payment_processing_at' => null, - 'reconciliation_attempts' => 0, - 'expires_at' => now()->addMinutes($grace), - ]); + /** + * Gives up on an intent the customer never finished. The void comes + * first: an intent left confirmable could take a payment after the + * session reopened, when nothing settles it and a retry mints a second + * intent. A void the gateway refuses means the payment may have gone + * through since the fetch, so the session stays pinned and the attempt + * counts: the next pass reads the real status. + */ + private function voidAndReopen( + CheckoutSession $session, + ReconcilesPaymentIntents $gateway, + Cart $cart, + string $reference, + string $reason, + ): string { + try { + $gateway->voidIntent($cart, $reference); + } catch (PaymentIntentException) { + return $this->recordAttempt($session); + } - return 'released'; + return $this->reopen($session, $reason); } /** @@ -131,13 +170,27 @@ public function release(CheckoutSession $session): string * (a hold, or a policy-mode requires_capture intent) voids; anything * actually captured (a standard intent, or a hold captured by this very * call) refunds. + * + * A gateway keeps reporting a refunded intent as captured, so money an + * earlier pass returned is recognised by the refunded amount. A full + * refund whose reopen never committed (the pass died, or the gateway's + * answer was lost) finishes here without a second refund call. A partial + * one is not this class's doing and leaves money with no order, so it + * stalls to the operator. Neither ever completes. */ private function completeOrRefund( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, - PaymentIntentStatus $status, + PaymentIntentSnapshot $intent, ): string { + if ($intent->refunded->value > 0) { + return $intent->refunded->value >= $intent->captured->value + ? $this->moneyBack($session, $gateway, $cart, $reference, captured: true, alreadyRefunded: true) + : $this->recordAttempt($session); + } + // An authorise-only hold is not money moved yet: capture it now, in // the one idempotent place every completion path funnels through, so // a crash between pin and capture recovers on the next reconcile. @@ -148,7 +201,7 @@ private function completeOrRefund( if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds) { try { - $gateway->captureHold($reference, (int) $session->amount_total); + $gateway->captureHold($cart, $reference, $this->pinnedAmount($session)); $holdCaptured = true; } catch (PaymentIntentException $e) { report($e); @@ -182,7 +235,7 @@ private function completeOrRefund( } } - return $this->moneyBack($session, $gateway, $reference, $holdCaptured || $status === PaymentIntentStatus::Captured); + return $this->moneyBack($session, $gateway, $cart, $reference, $holdCaptured || $intent->status === PaymentIntentStatus::Captured); } /** @@ -195,11 +248,13 @@ private function completeOrRefund( */ private function moneyBack( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, bool $captured, + bool $alreadyRefunded = false, ): string { - [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $reference, $captured): array { + [$outcome, $event] = $session->getConnection()->transaction(function () use ($session, $gateway, $cart, $reference, $captured, $alreadyRefunded): array { $locked = CheckoutSession::query()->whereKey($session->getKey())->lockForUpdate()->firstOrFail(); if ($locked->status instanceof Completed) { @@ -212,18 +267,10 @@ private function moneyBack( return ['not-applicable', null]; } - // The gateway's own authorize() placed an order for this cart - // since the pin, before complete() failed: returning the money - // would leave a placed order unpaid. The operator resolves it. - // An order an earlier checkout of the same cart placed does not - // count. - $placedForThisPayment = Order::query() - ->where('cart_id', (int) $session->cart_reference) - ->whereNotNull('placed_at') - ->when($locked->payment_processing_at, fn ($query, $pinnedAt) => $query->where('placed_at', '>=', $pinnedAt)) - ->exists(); - - if ($placedForThisPayment) { + // The gateway's own authorize() placed an order for this + // payment before complete() failed: returning the money would + // leave a placed order unpaid. The operator resolves it. + if ($this->orderPlacedForThisPayment($locked, $reference)) { return ['order-placed', null]; } @@ -233,7 +280,7 @@ private function moneyBack( // misconfiguration); voiding is still the safe answer. if (! $captured) { try { - $gateway->voidIntent($reference); + $gateway->voidIntent($cart, $reference); } catch (PaymentIntentException) { return ['void-failed', new CheckoutCompletionFailed($session, 'void-failed')]; } @@ -244,19 +291,27 @@ private function moneyBack( return ['voided', new CheckoutCompletionFailed($session, $holdMode ? 'hold-voided' : 'voided')]; } - try { - $refund = $gateway->refundIntent( - $reference, - $session->amount_total, - 'lunar-checkout-refund:'.$reference, - ); - } catch (PaymentIntentException) { - return ['refund-failed', new CheckoutCompletionFailed($session, 'refund-failed')]; + // A refund found on the intent has no reference to pass on: the + // snapshot carries amounts only, and the call that made it never + // returned one. + $refundReference = null; + + if (! $alreadyRefunded) { + try { + $refundReference = $gateway->refundIntent( + $cart, + $reference, + $this->pinnedAmount($session), + 'lunar-checkout-refund:'.$reference, + )->reference; + } catch (PaymentIntentException) { + return ['refund-failed', new CheckoutCompletionFailed($session, 'refund-failed')]; + } } $this->reopen($session, 'refunded'); - return ['refunded', new CheckoutCompletionFailed($session, 'refunded', $refund->reference)]; + return ['refunded', new CheckoutCompletionFailed($session, 'refunded', $refundReference)]; }); // Count the attempt before any listener runs, so a throwing @@ -273,16 +328,42 @@ private function moneyBack( return $result; } + /** + * Whether the gateway placed an order for the payment the session is + * pinned on. Two signals, either enough: the order the gateway announced + * for this intent ({@see CompleteSessionOnPaymentSuccess} notes it on the + * session), or an order placed since the pin, for a placement whose + * announcement never reached that listener. An order an earlier checkout + * of the same cart placed matches neither. + */ + private function orderPlacedForThisPayment(CheckoutSession $session, string $reference): bool + { + $placed = Order::query() + ->where('cart_id', (int) $session->cart_reference) + ->whereNotNull('placed_at'); + + $announced = $session->meta['gateway_placed_order'] ?? null; + + if (($announced['intent'] ?? null) === $reference && (clone $placed)->whereKey($announced['order'] ?? null)->exists()) { + return true; + } + + return $placed + ->when($session->payment_processing_at, fn ($query, $pinnedAt) => $query->where('placed_at', '>=', $pinnedAt)) + ->exists(); + } + private function resolveByOperator( CheckoutSession $session, - ?SupportsPaymentIntents $gateway, + ?ReconcilesPaymentIntents $gateway, + ?Cart $cart, ?string $reference, string $resolve, ): string { return match ($resolve) { 'complete' => $this->completeForOperator($session), - 'refund' => $gateway !== null && $reference !== null - ? $this->completeOrRefundByForce($session, $gateway, $reference) + 'refund' => $gateway !== null && $cart !== null && $reference !== null + ? $this->completeOrRefundByForce($session, $gateway, $cart, $reference) : 'refund-failed', 'cancel' => $this->cancelForOperator($session), default => throw new \InvalidArgumentException("Unknown resolution [{$resolve}]."), @@ -302,12 +383,14 @@ private function completeForOperator(CheckoutSession $session): string */ private function completeOrRefundByForce( CheckoutSession $session, - SupportsPaymentIntents $gateway, + ReconcilesPaymentIntents $gateway, + Cart $cart, string $reference, ): string { $refund = $gateway->refundIntent( + $cart, $reference, - $session->amount_total, + $this->pinnedAmount($session), 'lunar-checkout-refund:'.$reference, ); @@ -352,10 +435,11 @@ private function reopen(CheckoutSession $session, string $reason): string } /** - * Back to `Open` like {@see reopen()} but the intent reference survives: - * nothing was captured (the hold's own capture call failed), so there is - * no double-hold risk in leaving the customer bound to the same - * authorisation instead of forcing a fresh one. + * Back to `Open` like {@see reopen()} but the intent reference survives. + * Nothing was captured, so the customer stays bound to the same intent or + * authorisation instead of a fresh one: the mounted payment element still + * points at it, it is still confirmable, and the retry re-syncs its + * amount at the pay boundary. */ private function reopenKeepingIntent(CheckoutSession $session, string $reason): string { @@ -370,6 +454,35 @@ private function reopenKeepingIntent(CheckoutSession $session, string $reason): return $reason; } + /** + * A pin with no timestamp can never age into the window, so it counts as + * past it rather than holding the cart for good. + */ + private function waitedOnCustomerTooLong(CheckoutSession $session): bool + { + $minutes = (int) config('lunar.checkout.reconciliation.requires_action_minutes', 30); + + return $session->payment_processing_at?->lte(now()->subMinutes($minutes)) ?? true; + } + + /** + * The pinned total in the currency it was pinned in. The cart's currency + * may have changed since, and a gateway refuses an amount in another + * currency from the intent's, or missizes it. + * + * @throws PaymentIntentException when the store no longer has that + * currency, rather than guess another + */ + private function pinnedAmount(CheckoutSession $session): PriceValue + { + $currency = Currency::query()->where('code', $session->currency_code)->first() + ?? throw new PaymentIntentException( + "Checkout session [{$session->uuid}] was pinned in [{$session->currency_code}], which this store no longer has.", + ); + + return new PriceValue((int) $session->amount_total, $currency); + } + private function recordAttempt(CheckoutSession $session): string { $maxAttempts = (int) config('lunar.checkout.reconciliation.max_attempts', 5); diff --git a/src/Actions/SetFulfilment.php b/src/Actions/SetFulfilment.php index aac38f6..52e697d 100644 --- a/src/Actions/SetFulfilment.php +++ b/src/Actions/SetFulfilment.php @@ -22,7 +22,7 @@ public function execute(Cart $cart, string $mode, ?string $pickupPoint = null): ]); } - $cart = $cart->calculate(); + $cart = $cart->loadMissing('lines.purchasable')->calculate(); $meta = $cart->meta?->getArrayCopy() ?? []; $meta[PickupPoints::MODE_KEY] = $mode; @@ -75,7 +75,7 @@ private function storeCollectOption(Cart $cart): void return; } - $collect = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => $option->collect); + $collect = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => $option->pickup); if ($collect === null || $cart->shippingAddress->shipping_option === $collect->getIdentifier()) { return; @@ -96,7 +96,7 @@ private function leaveCollectOption(Cart $cart): void return; } - $courier = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => ! $option->collect); + $courier = $this->shippingManifest->getOptions($cart)->first(fn (ShippingOption $option): bool => ! $option->pickup); if ($courier !== null) { $cart->setShippingOption($courier); diff --git a/src/CheckoutServiceProvider.php b/src/CheckoutServiceProvider.php index 7b2de3c..856d139 100644 --- a/src/CheckoutServiceProvider.php +++ b/src/CheckoutServiceProvider.php @@ -37,9 +37,10 @@ use Lunar\Checkout\States\CheckoutSession\DefaultCheckoutSessionStateConfig; use Lunar\Checkout\Support\CheckoutAssets; use Lunar\Checkout\Validation\Cart\PickupPointRequired; +use Lunar\Core\Enums\StepList; use Lunar\Core\Events\PaymentAttemptEvent; +use Lunar\Core\Facades\Steps; use Lunar\Core\Modifiers\ShippingModifiers; -use Lunar\Core\Validation\Cart\ValidateCartForOrderCreation; use Lunar\Shipping\Models\ShippingZone; class CheckoutServiceProvider extends ServiceProvider @@ -166,17 +167,10 @@ public function boot(): void $this->app->make(ShippingModifiers::class)->add(PickupPointModifier::class); // Spec 0013 §D: order creation refuses a collect cart with no chosen - // point through Lunar's own validator seam, so canCreateOrder() is - // the authority for every caller, not only this package's pay boundary. - // The default matches core's own fallback for a missing key: setting - // the key ends that fallback, so reading it as an empty list would - // silently replace core's validator with this package's alone. - config([ - 'lunar.cart.validators.order_create' => array_values(array_unique([ - ...config('lunar.cart.validators.order_create', [ValidateCartForOrderCreation::class]), - PickupPointRequired::class, - ])), - ]); + // point through core's step registry, so canCreateOrder() is the + // authority for every caller, not only this package's pay boundary. + // append() skips a step already listed, so a second boot is harmless. + Steps::for(StepList::OrderCreateValidation)->append(PickupPointRequired::class); $this->loadViewsFrom(__DIR__.'/../resources/views', 'lunar-checkout'); diff --git a/src/Contracts/Actions/ReconcilesCheckoutSession.php b/src/Contracts/Actions/ReconcilesCheckoutSession.php index 917b4c6..4168f18 100644 --- a/src/Contracts/Actions/ReconcilesCheckoutSession.php +++ b/src/Contracts/Actions/ReconcilesCheckoutSession.php @@ -10,7 +10,12 @@ interface ReconcilesCheckoutSession * Resolve a `PaymentProcessing` session against the gateway's actual * intent outcome (spec 0010 §F): captured → complete (or refund on * mismatch — no charge survives without an order), voided/failed → back - * to `Open`, pending → rescheduled without consuming an attempt. + * to `Open`, pending → rescheduled without consuming an attempt. An + * intent still waiting on the customer counts as pending only for + * `lunar.checkout.reconciliation.requires_action_minutes` after the pin; + * past that the intent is voided and the session returns to `Open`. A + * void the gateway refuses keeps the session pinned and consumes an + * attempt. * * `$resolve` is the operator override (`complete` | `refund` | `cancel`) * — the sanctioned stall exit. Returns a stable outcome code. diff --git a/src/Contracts/CheckoutDriver.php b/src/Contracts/CheckoutDriver.php index d2a2547..224a1b4 100644 --- a/src/Contracts/CheckoutDriver.php +++ b/src/Contracts/CheckoutDriver.php @@ -63,7 +63,9 @@ public function resolveOrCreateSession(mixed $source, array $attributes = []): C public function complete(CheckoutSession $session, ?string $confirmationToken = null): mixed; /** - * Live, never-persisted view of the source cart (0010 §B). Reads never write. + * Live view of the source cart (0010 §B), built from freshly calculated + * totals. The snapshot itself is never persisted, but calculating it + * writes core's totals cache columns on the cart row. */ public function snapshot(CheckoutSession $session): CartSnapshot; diff --git a/src/Drivers/LunarCheckoutDriver.php b/src/Drivers/LunarCheckoutDriver.php index c7a2877..3813fda 100644 --- a/src/Drivers/LunarCheckoutDriver.php +++ b/src/Drivers/LunarCheckoutDriver.php @@ -75,7 +75,7 @@ public function createSession(mixed $source, array $attributes = []): CheckoutSe return $this->createCheckoutSession->execute( $source, - $this->buildSnapshot($source->calculate()), + $this->buildSnapshot($source->recalculate()), $attributes, ); } @@ -131,8 +131,7 @@ public function complete(CheckoutSession $session, ?string $confirmationToken = throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); } - $cart->calculate(); - $live = $this->buildSnapshot($cart); + $live = $this->buildSnapshot($cart->recalculate()); $isSync = $session->status instanceof Open; @@ -293,7 +292,9 @@ private function recordPayment(CheckoutSession $session, Order $order): void } try { - $gateway->order($order)->withData(['payment_intent' => $reference])->authorize(); + // `reference` is the key core's CreatesPaymentIntents documents; + // `payment_intent` is the one drivers read before it. + $gateway->order($order)->withData(['reference' => $reference, 'payment_intent' => $reference])->authorize(); } catch (\Throwable $e) { report(new PaymentRecordingException( "Could not record payment intent [{$reference}] on order [{$order->id}]: {$e->getMessage()}", @@ -304,7 +305,7 @@ private function recordPayment(CheckoutSession $session, Order $order): void public function snapshot(CheckoutSession $session): CartSnapshot { - return $this->buildSnapshot($this->resolveCart($session)->calculate()); + return $this->buildSnapshot($this->resolveCart($session)->recalculate()); } public function fingerprint(CheckoutSession $session): string @@ -336,8 +337,7 @@ public function assertReadyForPayment(CheckoutSession $session, string $confirme throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); } - $cart->calculate(); - $live = $this->buildSnapshot($cart); + $live = $this->buildSnapshot($cart->recalculate()); if (! hash_equals($confirmedFingerprint, $live->fingerprint)) { $this->events->dispatch(new CheckoutPaymentConfirmationFailed($session)); @@ -516,9 +516,9 @@ public function setShippingOption(CheckoutSession $session, string $identifier): // Mode and option never disagree (spec 0013 §B): a courier chosen // while collecting drops the point; the collect option chosen while // delivering records collect and applies a single offered point. - $mode = $option->collect ? PickupPoints::COLLECT : PickupPoints::DELIVERY; + $mode = $option->pickup ? PickupPoints::COLLECT : PickupPoints::DELIVERY; - if (PickupPoints::fulfilment($cart) !== $mode || $option->collect) { + if (PickupPoints::fulfilment($cart) !== $mode || $option->pickup) { $cart = $this->setFulfilment->execute($cart->refresh(), $mode); } @@ -607,7 +607,7 @@ public function associateCustomer(CheckoutSession $session, string $customerRefe $this->events->dispatch(new CustomerAssociated($session, $customerReference)); - return $this->buildSnapshot($cart); + return $this->buildSnapshot($cart->recalculate()); } /* @@ -636,7 +636,7 @@ public function getShippingOptions(CheckoutSession $session): array 'name' => $option->name, 'description' => $option->description, 'price' => $option->getPrice()->value, - 'collect' => $option->collect, + 'collect' => $option->pickup, ]) ->values() ->all(); @@ -675,6 +675,7 @@ public function getLines(CheckoutSession $session): array $cart = $this->resolveCart($session)->calculate(); return $cart->lines + ->loadMorph('purchasable', [ProductVariant::class => ['product.thumbnail', 'images']]) ->map(fn ($line): array => [ 'identifier' => (string) $line->id, 'description' => $line->purchasable?->getDescription(), @@ -726,7 +727,7 @@ public function getTotals(CheckoutSession $session): array private function resolveCart(CheckoutSession $session): Cart { - $cart = Cart::query()->find((int) $session->cart_reference); + $cart = Cart::query()->with('lines.purchasable')->find((int) $session->cart_reference); if ($cart === null) { throw new CheckoutSessionNotOperableException('The session\'s source cart no longer exists.'); diff --git a/src/Http/Controllers/CheckoutController.php b/src/Http/Controllers/CheckoutController.php index 42cc549..045e77b 100644 --- a/src/Http/Controllers/CheckoutController.php +++ b/src/Http/Controllers/CheckoutController.php @@ -42,12 +42,14 @@ use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Checkout\Support\PickupPoints; use Lunar\Core\Contracts\CreatesPaymentIntents; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\Contracts\SyncsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; +use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; use Lunar\Core\Models\Address; @@ -144,10 +146,30 @@ public function start(Request $request, CheckoutDriver $checkoutDriver): Symfony * caller returns a bare 409 SymfonyResponse rather than a RedirectResponse * (same reason `start()` above is typed against SymfonyResponse). */ - public function show(CheckoutSessionModel $session, CheckoutDriver $checkoutDriver, CheckoutTheme $theme): Response|RedirectResponse|SymfonyResponse + public function show(Request $request, CheckoutSessionModel $session, CheckoutDriver $checkoutDriver, CheckoutTheme $theme): Response|RedirectResponse|SymfonyResponse { $this->ensureOwnership($session); + /* + * A redirect payment method (Klarna, PayPal, a full-page 3DS + * challenge) that failed or was cancelled lands back here with the + * session still pinned: the browser left the page, so the in-page + * release never ran. Release it now, on the gateway's word that + * nothing was captured, and send the customer to the retry state. + */ + if ($session->status instanceof PaymentProcessing && $this->returnedFromFailedRedirect($request, $session)) { + try { + app(ReconcilesCheckoutSession::class)->release($session); + $session->refresh(); + } catch (\Throwable $e) { + report($e); + } + + if ($session->status instanceof Open) { + return redirect()->to(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + } + } + /* * A pinned session normally completes via the gateway webhook, but * webhooks can be slow, misconfigured or absent (local dev). The @@ -288,7 +310,7 @@ public function confirm(CheckoutSessionModel $session, CheckoutDriver $checkoutD [ 'elements' => $this->projectElements($session), 'hold' => [ - 'amountAuthorised' => $hold->amountMinor, + 'amountAuthorised' => $hold->amount->value, 'walletLabel' => $hold->walletLabel, ], ], @@ -312,27 +334,28 @@ public function confirm(CheckoutSessionModel $session, CheckoutDriver $checkoutD * in this controller: a session whose window has closed but whose row * has not yet been transitioned still reads `Open` and must not render. */ - private function liveHold(CheckoutSessionModel $session): ?HoldDescription + private function liveHold(CheckoutSessionModel $session): ?PaymentIntentSnapshot { if (! $session->status instanceof Open || $session->isExpired() || ! $session->isHoldMode() || $session->payment_intent_ref === null) { return null; } $gateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); + $cart = Cart::query()->find((int) $session->cart_reference); - if (! $gateway instanceof SupportsPaymentHolds) { + if (! $gateway instanceof SupportsPaymentHolds || $cart === null) { return null; } try { - $description = $gateway->describeHold($session->payment_intent_ref); + $snapshot = $gateway->fetchIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); return null; } - return $description?->status === PaymentIntentStatus::RequiresCapture ? $description : null; + return $snapshot?->status === PaymentIntentStatus::RequiresCapture ? $snapshot : null; } /** @@ -490,7 +513,7 @@ private function projectCheckout(CheckoutDriver $driver, CheckoutSessionModel $s 'coupon' => $driver->getCoupon($session), // The pay boundary echoes back the fingerprint of the state the // customer confirmed (spec 0010 §E). - 'fingerprint' => $driver->fingerprint($session), + 'fingerprint' => $snapshot->fingerprint, 'paymentMethods' => array_map(fn (PaymentMethod $method): array => [ 'handle' => $method->handle(), 'label' => $method->label(), @@ -991,7 +1014,7 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi 'renew' => ['sometimes', 'boolean'], ]); - $cart = Cart::query()->findOrFail((int) $session->cart_reference); + $cart = $this->freshCart($session); $method = $this->resolveAvailableMethod($methods, $cart, $data['payment_method']); @@ -1013,9 +1036,9 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi // Re-authorisation (payment change, or a hold the rail could not // stretch): release the old hold FIRST, so the customer is never // double-held. A void the gateway cannot confirm aborts the renewal. - if ($holdMode && ($data['renew'] ?? false) && $session->payment_intent_ref !== null && $gateway instanceof SupportsPaymentIntents) { + if ($holdMode && ($data['renew'] ?? false) && $session->payment_intent_ref !== null && $gateway instanceof ReconcilesPaymentIntents) { try { - $gateway->voidIntent($session->payment_intent_ref); + $gateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); @@ -1041,9 +1064,9 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi if (! $holdMode && $session->isHoldMode() && $session->payment_intent_ref !== null) { $previousGateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); - if ($previousGateway instanceof SupportsPaymentIntents) { + if ($previousGateway instanceof ReconcilesPaymentIntents) { try { - $previousGateway->voidIntent($session->payment_intent_ref); + $previousGateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); @@ -1056,8 +1079,8 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi try { $descriptor = $holdMode - ? $gateway->createHold($cart->calculate()) - : $gateway->createIntent($cart->calculate()); + ? $gateway->createHold($cart) + : $gateway->createIntent($cart); } catch (\Throwable $e) { // Gateway errors carry internals (Stripe's minimum-charge copy // links to its own docs); log the real one, say something human. @@ -1116,7 +1139,7 @@ public function storePaymentIntent(Request $request, CheckoutSessionModel $sessi return response()->json([ 'intent' => $descriptor->reference, - 'clientSecret' => $descriptor->clientSecret, + 'clientSecret' => $descriptor->clientPayload['client_secret'] ?? null, ]); } @@ -1143,7 +1166,7 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri 'payment_method' => ['required', 'string'], ]); - $cart = Cart::query()->findOrFail((int) $session->cart_reference); + $cart = $this->freshCart($session); $method = $this->resolveAvailableMethod($methods, $cart, $data['payment_method']); @@ -1153,7 +1176,7 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri // Live amount, not the session's pinned figure — the pin happens // inside assertReadyForPayment(), after this decision. - $amountTotal = $checkoutDriver->snapshot($session)->amountTotal; + $amountTotal = $cart->total?->value ?? 0; /* * The gateway intent was created when the payment form mounted, and @@ -1162,17 +1185,28 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri * customer is looking at BEFORE the pin, so a fingerprint rejection * costs nothing and a confirmed charge is never the stale figure. * - * A confirmed hold cannot be synced like an unconfirmed intent - * (Task 3 unit note: `$amountTotal` is Lunar minor units, equal to - * Stripe's for GBP): it stretches (incremental authorization) or it - * does not, so hold-mode sessions branch to adjustHold() instead of + * A confirmed hold cannot be synced like an unconfirmed intent: it + * stretches (incremental authorization) or it does not, so hold-mode + * sessions branch to adjustHold() instead of * SyncsPaymentIntents::syncIntent(). + * + * A cart that left the session's currency is skipped: the gateway + * refuses to resize an intent in another currency, and step 0 of + * the gate below voids that intent and cancels the session anyway. */ - if ($method->requiresIntent() && $amountTotal > 0) { + if ($method->requiresIntent() && $amountTotal > 0 && $cart->currency->code === $session->currency_code) { $gateway = Payments::driver($method->driver()); if ($session->isHoldMode() && $gateway instanceof SupportsPaymentHolds && $session->payment_intent_ref !== null) { - $adjustment = $gateway->adjustHold($session->payment_intent_ref, $amountTotal); + try { + $adjustment = $gateway->adjustHold($cart, $session->payment_intent_ref, new PriceValue($amountTotal, $cart->currency)); + } catch (PaymentIntentException $e) { + // A hold the gateway will not adjust (not this cart's, + // no longer awaiting capture) cannot cover the total. + report($e); + + $adjustment = HoldAdjustment::NeedsReauthorization; + } if ($adjustment === HoldAdjustment::NeedsReauthorization) { // Session still Open: nothing to unpin. The client @@ -1183,9 +1217,15 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri ]); } } elseif ($gateway instanceof SyncsPaymentIntents) { - $gateway->syncIntent( - Cart::query()->findOrFail((int) $session->cart_reference)->calculate(), - ); + try { + $gateway->syncIntent($cart); + } catch (PaymentIntentException $e) { + report($e); + + throw ValidationException::withMessages([ + 'payment_method' => 'Card payments are unavailable right now. Please try again in a moment.', + ]); + } } } @@ -1219,9 +1259,9 @@ public function pay(Request $request, CheckoutSessionModel $session, CheckoutDri if ($session->isHoldMode() && $session->payment_intent_ref !== null) { $holdGateway = Payments::driver((string) ($session->meta['payment_method'] ?? '')); - if ($holdGateway instanceof SupportsPaymentIntents) { + if ($holdGateway instanceof ReconcilesPaymentIntents) { try { - $holdGateway->voidIntent($session->payment_intent_ref); + $holdGateway->voidIntent($cart, $session->payment_intent_ref); } catch (\Throwable $e) { report($e); } @@ -1415,6 +1455,26 @@ private function redirectDeadSession(CheckoutSessionModel $session): RedirectRes )); } + /** + * Whether Stripe sent the customer back from a redirect payment method + * that did not go through. StripeCard.vue gives Stripe this page as its + * `return_url`, and Stripe appends the intent it was confirming and how + * the redirect ended. Only a failure for the session's own intent + * counts. These are the only gateway parameters the controller reads, + * and they grant nothing new: the session's owner can already ask for + * the same release through releasePayment(). + * + * Stripe's return_url documentation lists `payment_intent` but not + * `redirect_status`, which it sends all the same. A return without it + * is not treated as a failure: the session waits for reconciliation. + */ + private function returnedFromFailedRedirect(Request $request, CheckoutSessionModel $session): bool + { + return $request->query('redirect_status') === 'failed' + && $session->payment_intent_ref !== null + && $request->query('payment_intent') === $session->payment_intent_ref; + } + /** * Customer-facing copy for a rejected pay attempt. The exception message * carries the developer reason code ("Payment confirmation rejected @@ -1432,6 +1492,19 @@ private function paymentRejectionMessage(PaymentConfirmationException $e): strin }; } + /** + * The session's cart with totals from the pipeline, not the persisted + * snapshot: method availability, payment guards and the gateway amount + * are all money decisions, and the pin that follows uses fresh totals. + */ + private function freshCart(CheckoutSessionModel $session): Cart + { + return Cart::query() + ->with('lines.purchasable') + ->findOrFail((int) $session->cart_reference) + ->recalculate(); + } + /** * The registered method for this handle, provided the basket can actually * use it right now. "Available" means a survivor of diff --git a/src/Listeners/CompleteSessionOnPaymentSuccess.php b/src/Listeners/CompleteSessionOnPaymentSuccess.php index 2d0b4ef..9498b65 100644 --- a/src/Listeners/CompleteSessionOnPaymentSuccess.php +++ b/src/Listeners/CompleteSessionOnPaymentSuccess.php @@ -63,13 +63,55 @@ public function handle(PaymentAttemptEvent $event): void * finishes on the confirm page, which captures at reconcile; it is * never adopted from here. */ - if ($session->status instanceof Open && ($session->isHoldMode() || ! $this->pinForGatewayPayment($session))) { + if ($session->status instanceof Open && $session->isHoldMode()) { + return; + } + + $this->rememberPlacedOrder($session, $authorize->orderId); + + if ($session->status instanceof Open && ! $this->pinForGatewayPayment($session)) { return; } $this->driver->complete($session); } + /** + * Notes on the session which order the gateway placed for the intent the + * session carries, before anything else can fail. If complete() then + * throws, reconciliation must not refund that order's money, and it + * cannot tell by time: a session this listener pins is pinned after the + * order was placed. The intent is kept beside the order so the note + * stops counting once the session moves on to another intent. + * + * Written under the row lock for the reason pinForGatewayPayment() gives, + * in a transaction of its own that commits before that method takes its + * snapshot. The caller's copy of the session is left as it was read, so + * a session another process moved meanwhile is still caught by the pin's + * locked re-read, or by complete()'s guarded write. + */ + private function rememberPlacedOrder(CheckoutSession $session, int $orderId): void + { + DB::transaction(function () use ($session, $orderId): void { + $locked = CheckoutSession::query() + ->whereKey($session->getKey()) + ->lockForUpdate() + ->first(); + + if ($locked === null || ! ($locked->status instanceof Open || $locked->status instanceof PaymentProcessing)) { + return; + } + + CheckoutSession::query() + ->whereKey($session->getKey()) + ->update([ + 'meta' => json_encode(array_merge((array) $locked->meta, [ + 'gateway_placed_order' => ['order' => $orderId, 'intent' => $locked->payment_intent_ref], + ])), + ]); + }); + } + /** * The customer confirmed the payment with the gateway directly (e.g. * Stripe.js) without going through the pay boundary, so the session is @@ -92,10 +134,19 @@ private function pinForGatewayPayment(CheckoutSession $session): bool * The status moves with the same guarded raw update the pay * boundary uses (LunarCheckoutDriver::assertReadyForPayment()): * session states change through these one-statement guards, not - * model transitions. The snapshot is taken under the lock; complete() - * re-verifies it against the cart under the cart-row lock anyway. + * model transitions. + * + * The snapshot is taken before the session row is locked. Taking it + * writes the cart row's totals cache, and the pay boundary locks the + * cart row before it writes the session row, so snapshotting under + * the session lock could deadlock against it. The session lock never + * guarded the cart: a cart edit after the snapshot leaves a + * fingerprint that complete() rejects under the cart-row lock, and a + * session another process moved meanwhile fails the Open check below. */ - $pinned = DB::transaction(function () use ($session): int { + $live = $this->driver->snapshot($session); + + $pinned = DB::transaction(function () use ($session, $live): int { $locked = CheckoutSession::query() ->whereKey($session->getKey()) ->lockForUpdate() @@ -105,8 +156,6 @@ private function pinForGatewayPayment(CheckoutSession $session): bool return 0; } - $live = $this->driver->snapshot($locked); - return CheckoutSession::query() ->whereKey($session->getKey()) ->where('status', Open::$name) diff --git a/src/PaymentMethods/AbstractPaymentMethod.php b/src/PaymentMethods/AbstractPaymentMethod.php index 188d571..c907040 100644 --- a/src/PaymentMethods/AbstractPaymentMethod.php +++ b/src/PaymentMethods/AbstractPaymentMethod.php @@ -16,7 +16,7 @@ * * public function isAvailable(Cart $cart): bool * { - * return (bool) $cart->getShippingOption()?->collect; + * return (bool) $cart->getShippingOption()?->pickup; * } */ abstract class AbstractPaymentMethod implements PaymentMethod diff --git a/src/PaymentMethods/Offline.php b/src/PaymentMethods/Offline.php index d74948a..e890eb8 100644 --- a/src/PaymentMethods/Offline.php +++ b/src/PaymentMethods/Offline.php @@ -21,7 +21,7 @@ * * public function isAvailable(Cart $cart): bool * { - * return (bool) $cart->getShippingOption()?->collect; + * return (bool) $cart->getShippingOption()?->pickup; * } * } */ diff --git a/src/Shipping/PickupPointModifier.php b/src/Shipping/PickupPointModifier.php index 611d18f..fcbe6ac 100644 --- a/src/Shipping/PickupPointModifier.php +++ b/src/Shipping/PickupPointModifier.php @@ -28,7 +28,7 @@ public function handle(Cart $cart, Closure $next): mixed } foreach (app(ShippingManifest::class)->options as $option) { - if ($option instanceof ShippingOption && $option->collect) { + if ($option instanceof ShippingOption && $option->pickup) { $option->meta = array_merge($option->meta ?? [], [PickupPoints::POINT_KEY => $point]); } } diff --git a/src/Support/PaymentIntentGateway.php b/src/Support/PaymentIntentGateway.php index 55812c7..d9ee07a 100644 --- a/src/Support/PaymentIntentGateway.php +++ b/src/Support/PaymentIntentGateway.php @@ -3,12 +3,13 @@ namespace Lunar\Checkout\Support; use Lunar\Checkout\Models\CheckoutSession; -use Lunar\Core\Contracts\SupportsPaymentIntents; +use Lunar\Core\Contracts\ReconcilesPaymentIntents; use Lunar\Core\Managers\PaymentManager; +use Lunar\Core\Models\Cart; /** * Resolves the gateway driver behind a session's in-flight intent, when that - * driver opted into the {@see SupportsPaymentIntents} capability. The payment + * driver opted into the {@see ReconcilesPaymentIntents} capability. The payment * method handle is recorded on `meta.payment_method` when the intent is * created. Null means the intent's outcome cannot be confirmed — callers treat * that as "unabortable" and leave the session for reconciliation (0010 §F). @@ -19,7 +20,7 @@ public function __construct( private PaymentManager $payments, ) {} - public function for(CheckoutSession $session): ?SupportsPaymentIntents + public function for(CheckoutSession $session): ?ReconcilesPaymentIntents { $handle = $session->meta['payment_method'] ?? null; @@ -33,6 +34,16 @@ public function for(CheckoutSession $session): ?SupportsPaymentIntents return null; } - return $driver instanceof SupportsPaymentIntents ? $driver : null; + return $driver instanceof ReconcilesPaymentIntents ? $driver : null; + } + + /** + * The cart the intent verbs are scoped to, pruned or not. Lunar prunes + * idle carts by soft-deleting them, and money held or taken against one + * must still be voidable and refundable afterwards. + */ + public function cartFor(CheckoutSession $session): ?Cart + { + return Cart::query()->withTrashed()->find((int) $session->cart_reference); } } diff --git a/src/Support/PickupPoints.php b/src/Support/PickupPoints.php index d138495..d56bd6a 100644 --- a/src/Support/PickupPoints.php +++ b/src/Support/PickupPoints.php @@ -125,6 +125,6 @@ public static function storedOptionCollects(Cart $cart): bool return false; } - return (bool) ShippingManifest::getOption($cart, $identifier)?->collect; + return (bool) ShippingManifest::getOption($cart, $identifier)?->pickup; } } diff --git a/tests/Feature/CheckoutDriverFulfilmentTest.php b/tests/Feature/CheckoutDriverFulfilmentTest.php index 8150599..802bc0a 100644 --- a/tests/Feature/CheckoutDriverFulfilmentTest.php +++ b/tests/Feature/CheckoutDriverFulfilmentTest.php @@ -16,6 +16,7 @@ use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; use Lunar\Tests\Checkout\Utils\PickupPointsStub; +use Spatie\LaravelBlink\BlinkFacade as Blink; uses(TestCase::class, RefreshDatabase::class); @@ -31,7 +32,7 @@ function driverCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); CartSession::use($cart); @@ -148,3 +149,36 @@ function driverCart(): Cart expect($cart->refresh()->shippingAddress)->toBeNull(); }); + +it('stores the collect option on a multi-line cart without lazy loading its purchasables', function () { + $cart = driverCart(); + CheckoutCart::addLine($cart, 2500); + $driver = app(CheckoutDriver::class); + $session = $driver->resolveOrCreateSession($cart->refresh()); + Blink::flush(); + + $driver->setShippingOption($session, 'collection'); + + expect($driver->getFulfilment($session))->toBe('collect') + ->and($driver->getSelectedShippingOption($session))->toBe('collection') + ->and($driver->getLines($session))->toHaveCount(2); +}); + +it('stores the collect option when an address arrives in collect mode on a multi-line cart', function () { + $cart = driverCart(); + CheckoutCart::addLine($cart, 2500); + $cart->addresses()->where('type', 'shipping')->delete(); + $driver = app(CheckoutDriver::class); + $session = $driver->resolveOrCreateSession($cart->refresh()); + + $driver->setFulfilment($session, 'collect'); + Blink::flush(); + + $driver->storeShippingAddress($session, [ + 'first_name' => 'Terry', 'last_name' => 'Sparks', 'line1' => '1 Trade Counter Way', + 'city' => 'London', 'postcode' => 'SE1 1AA', 'country_code' => 'GB', + ]); + + expect($driver->getSelectedShippingOption($session))->toBe('collection') + ->and($driver->getFulfilment($session))->toBe('collect'); +}); diff --git a/tests/Feature/CheckoutErrorContractTest.php b/tests/Feature/CheckoutErrorContractTest.php index 2d2b513..e51b2af 100644 --- a/tests/Feature/CheckoutErrorContractTest.php +++ b/tests/Feature/CheckoutErrorContractTest.php @@ -17,6 +17,7 @@ use Lunar\Tests\Checkout\Stubs\User; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); @@ -135,6 +136,8 @@ */ class FailingIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { throw new RuntimeException('The amount must be greater than or equal to the minimum charge amount. See https://gateway.docs/internal'); diff --git a/tests/Feature/CheckoutRouteTest.php b/tests/Feature/CheckoutRouteTest.php index b0e55a1..89f80c0 100644 --- a/tests/Feature/CheckoutRouteTest.php +++ b/tests/Feature/CheckoutRouteTest.php @@ -9,15 +9,16 @@ use Lunar\Core\Models\Channel; use Lunar\Core\Models\Currency; use Lunar\Core\Models\CustomerGroup; +use Lunar\Core\Models\Language; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; uses(TestCase::class, RefreshDatabase::class); /** - * Storefront context every request has in a real app (default channel + - * currency), without a cart — so CartSession::current() can resolve and - * return null rather than throw. + * Storefront context every request has in a real app (default channel, + * currency and language), without a cart — so CartSession::current() can + * resolve and return null rather than throw. * * @return array{0: Channel, 1: Currency} */ @@ -29,6 +30,10 @@ function routeCheckoutContext(): array CustomerGroup::factory()->create(['default' => true]); } + if (! Language::query()->where('default', true)->exists()) { + Language::factory()->create(['code' => 'en', 'default' => true]); + } + $channel = Channel::query()->firstWhere('handle', 'webstore') ?? Channel::factory()->create(['handle' => 'webstore']); $currency = Currency::query()->firstWhere('code', 'GBP') diff --git a/tests/Feature/CompletionFailureRefundTest.php b/tests/Feature/CompletionFailureRefundTest.php index e092317..eff18ab 100644 --- a/tests/Feature/CompletionFailureRefundTest.php +++ b/tests/Feature/CompletionFailureRefundTest.php @@ -16,10 +16,13 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; +use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; +use Lunar\Core\Events\PaymentAttemptEvent; use Lunar\Core\Exceptions\PaymentIntentException; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -28,35 +31,54 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); -class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class CapturedIntentGateway extends OfflinePayment implements CreatesPaymentIntents { - /** @var array */ + /** @var array */ public static array $refunds = []; public static bool $refundFails = false; + public static int $captured = 0; + + /** What the gateway holds as refunded, whatever the caller heard back. */ + public static int $refunded = 0; + + /** Thrown once the gateway has made the refund: the caller never hears of it. */ + public static ?Throwable $failAfterRefunding = null; + public function createIntent(Cart $cart): PaymentIntentDescriptor { return new PaymentIntentDescriptor('pi_captured_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured, static::$captured, refunded: static::$refunded); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { if (static::$refundFails) { throw new PaymentIntentException('gateway refund failed'); } - static::$refunds[] = ['reference' => $reference, 'amount' => $amountMinor]; + if (static::$refunded > 0) { + throw new PaymentIntentException('nothing left to refund'); + } + + static::$refunds[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; + static::$refunded = $amount->value; + + if (static::$failAfterRefunding !== null) { + throw static::$failAfterRefunding; + } return new PaymentRefund(success: true, reference: 'refund_'.$reference); } @@ -93,6 +115,9 @@ public function component(): string beforeEach(function () { CapturedIntentGateway::$refunds = []; CapturedIntentGateway::$refundFails = false; + CapturedIntentGateway::$captured = 0; + CapturedIntentGateway::$refunded = 0; + CapturedIntentGateway::$failAfterRefunding = null; Payments::extend('captured-intent', fn () => app(CapturedIntentGateway::class)); app(PaymentMethodRegistry::class)->add(CapturedIntentMethod::class); @@ -119,14 +144,12 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $outcome = app(ReconcilesCheckoutSession::class)->execute($session); expect($outcome)->toBe('refunded') - ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total]]) + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) ->and($session->refresh()->status)->toBeInstanceOf(Open::class) ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0); @@ -138,9 +161,7 @@ function capturedSession(): CheckoutSession $failing = capturedSession(); $failing->forceFill(['payment_processing_at' => now()->subHours(2)])->save(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->artisan('lunar:checkout:reconcile')->assertSuccessful(); @@ -173,9 +194,7 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('SQLSTATE[40001]: Deadlock found when trying to get lock; try restarting transaction'), - ]); + FailingOrderCreationStep::register('SQLSTATE[40001]: Deadlock found when trying to get lock; try restarting transaction'); $outcome = app(ReconcilesCheckoutSession::class)->execute($session); @@ -205,9 +224,7 @@ function capturedSession(): CheckoutSession Exceptions::fake(); $session = capturedSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); Event::listen(CheckoutCompletionFailed::class, fn () => throw new LogicException('listener down')); expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session)) @@ -279,3 +296,213 @@ function capturedSession(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) ->and($session->reconciliation_attempts)->toBe(1); }); + +it('refunds in the currency the session was pinned in after the cart changed currency', function () { + $session = capturedSession(); + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refunds in the currency the session was pinned in when the operator forces the refund', function () { + $session = capturedSession(); + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session, 'refund'); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refuses to refund in another currency when the store no longer has the pinned one', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + $session->forceFill(['currency_code' => 'USD', 'cart_fingerprint' => 'stale'])->save(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('retry') + ->and(CapturedIntentGateway::$refunds)->toBeEmpty() + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); + + Event::assertDispatched(CheckoutCompletionFailed::class, fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refund-failed'); + + expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session, 'refund')) + ->toThrow(PaymentIntentException::class, 'USD'); + + expect(CapturedIntentGateway::$refunds)->toBeEmpty(); +}); + +it('lets the operator refund a session whose cart was pruned', function () { + $session = capturedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session, 'refund'); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toBe([['reference' => 'pi_captured_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('refunds a captured payment whose cart was pruned before it could complete', function () { + Exceptions::fake(); + $session = capturedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0); +}); + +it('never places an order on money an earlier pass refunded before it crashed', function () { + Exceptions::fake(); + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$failAfterRefunding = new RuntimeException('connection lost after the refund landed'); + + $placementVetoed = true; + Event::listen(OrderPlacing::class, function () use (&$placementVetoed) { + if ($placementVetoed) { + throw new LogicException('placement vetoed'); + } + }); + + expect(fn () => app(ReconcilesCheckoutSession::class)->execute($session)) + ->toThrow(RuntimeException::class, 'connection lost after the refund landed'); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); + + $placementVetoed = false; + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBeNull() + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1); + + Event::assertDispatched( + CheckoutCompletionFailed::class, + fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refunded' && $event->refundReference === null, + ); +}); + +it('reopens instead of retrying a refund whose response was lost', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + $session->forceFill(['cart_fingerprint' => 'stale'])->save(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$failAfterRefunding = new PaymentIntentException('refund response lost'); + + expect(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('retry'); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBeNull() + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1); + + $reasons = Event::dispatched(CheckoutCompletionFailed::class) + ->map(fn (array $arguments): string => $arguments[0]->reason) + ->countBy(); + + expect($reasons->get('refund-failed'))->toBe(1) + ->and($reasons->get('refunded'))->toBe(1); + + Event::assertDispatched( + CheckoutCompletionFailed::class, + fn (CheckoutCompletionFailed $event): bool => $event->reason === 'refunded' && $event->refundReference === null, + ); +}); + +it('never completes a refunded payment when the customer releases the session', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$refunded = $session->amount_total; + + $outcome = app(ReconcilesCheckoutSession::class)->release($session); + + expect($outcome)->toBe('refunded') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toBeEmpty(); +}); + +it('leaves a partly refunded payment pinned for the operator', function () { + Event::fake([CheckoutCompletionFailed::class]); + $session = capturedSession(); + CapturedIntentGateway::$captured = $session->amount_total; + CapturedIntentGateway::$refunded = 100; + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('retry') + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(0) + ->and(CapturedIntentGateway::$refunds)->toBeEmpty(); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); +}); + +it('never refunds an order the gateway placed before its success pinned the session', function () { + Exceptions::fake(); + $session = capturedSession(); + $session->forceFill(['status' => Open::$name, 'payment_processing_at' => null])->save(); + + $order = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); + $order->update(['placed_at' => now()]); + + // The gateway announces the order after placing it, so the pin that + // announcement causes is later than placed_at. + $this->travel(5)->seconds(); + + Event::listen(OrderPlacing::class, fn () => throw new LogicException('placement vetoed')); + + expect(fn () => PaymentAttemptEvent::dispatch(new PaymentAuthorize(success: true, orderId: $order->id, paymentType: 'captured-intent'))) + ->toThrow(LogicException::class, 'placement vetoed'); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->payment_processing_at->gt($order->refresh()->placed_at))->toBeTrue(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session); + + expect($outcome)->toBe('retry') + ->and(CapturedIntentGateway::$refunds)->toBeEmpty() + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); +}); + +it('still refunds a later payment on a session whose earlier payment the gateway placed', function () { + $session = capturedSession(); + + $earlier = Cart::query()->findOrFail((int) $session->cart_reference)->createOrder(); + $earlier->update(['placed_at' => now()->subDay()]); + + $session->forceFill([ + 'payment_intent_ref' => 'pi_captured_later', + 'cart_fingerprint' => 'stale', + 'meta' => array_merge((array) $session->meta, [ + 'gateway_placed_order' => ['order' => $earlier->id, 'intent' => 'pi_captured_earlier'], + ]), + ])->save(); + + $outcome = app(ReconcilesCheckoutSession::class)->execute($session->refresh()); + + expect($outcome)->toBe('refunded') + ->and(CapturedIntentGateway::$refunds)->toHaveCount(1) + ->and($session->refresh()->status)->toBeInstanceOf(Open::class); +}); diff --git a/tests/Feature/ConfirmPageTest.php b/tests/Feature/ConfirmPageTest.php index 70c17af..0a00756 100644 --- a/tests/Feature/ConfirmPageTest.php +++ b/tests/Feature/ConfirmPageTest.php @@ -2,7 +2,6 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Lunar\Checkout\Models\CheckoutSession; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Tests\Checkout\TestCase; @@ -11,7 +10,10 @@ uses(TestCase::class, RefreshDatabase::class); beforeEach(function () { - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; + FakeHoldGateway::$fetchScript = []; + FakeHoldGateway::$holdAmount = 0; + FakeHoldGateway::$walletLabel = null; }); /** @@ -68,11 +70,8 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('renders the confirm page for a session with a live hold', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: 2000, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = 2000; + FakeHoldGateway::$walletLabel = 'Apple Pay'; $this->get(route('lunar.checkout.confirm', $session->uuid), ['X-Inertia' => 'true']) ->assertOk() @@ -97,9 +96,16 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('redirects when the gateway does not verify requires-capture', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::Voided, amountMinor: 2000, walletLabel: null, - ); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::Voided; + FakeHoldGateway::$holdAmount = 2000; + + $this->get(route('lunar.checkout.confirm', $session->uuid)) + ->assertRedirect(route('lunar.checkout.show', $session->uuid)); +}); + +it('redirects when the gateway did not create the hold for the cart', function () { + $session = mintOpenHoldSession(); + FakeHoldGateway::$fetchScript = [null]; $this->get(route('lunar.checkout.confirm', $session->uuid)) ->assertRedirect(route('lunar.checkout.show', $session->uuid)); @@ -107,11 +113,8 @@ function mintOpenSessionWithStandardIntent(): CheckoutSession it('redirects an unswept expired session even though its row still reads Open', function () { $session = mintOpenHoldSession(); - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: 2000, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = 2000; + FakeHoldGateway::$walletLabel = 'Apple Pay'; // Expiry is swept lazily: backdate expires_at directly, without // transitioning `status` away from Open, the way a real session sits diff --git a/tests/Feature/DraftOrderAtPayGateTest.php b/tests/Feature/DraftOrderAtPayGateTest.php index e278aca..630be80 100644 --- a/tests/Feature/DraftOrderAtPayGateTest.php +++ b/tests/Feature/DraftOrderAtPayGateTest.php @@ -15,10 +15,11 @@ use Lunar\Checkout\States\CheckoutSession\Open; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -27,6 +28,8 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -34,7 +37,7 @@ * A card gateway that records captured money as a Transaction row on the * order it authorises against, the way Stripe's UpdateOrderFromIntent does. */ -class DraftAtPinGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class DraftAtPinGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array */ public static array $refunds = []; @@ -44,14 +47,14 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_draft_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { static::$refunds[] = $reference; @@ -238,9 +241,7 @@ function orderedQuantity(Order $order): int it('leaves the session open when the draft cannot be built', function () { $session = draftAtPinSession(); - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); expect(fn () => app(CheckoutDriver::class)->assertReadyForPayment($session, CheckoutCart::fingerprint($session))) ->toThrow(RuntimeException::class, 'order pipeline down'); @@ -274,9 +275,7 @@ function orderedQuantity(Order $order): int pressPay($session)->assertSuccessful(); $draftId = Order::query()->sole()->id; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); @@ -368,12 +367,14 @@ function orderedQuantity(Order $order): int // The gateway took payment with no Pay step: the session is pinned // against the live cart the way the webhook listener pins it, and the // draft still holds the cart from the first attempt. + $live = app(CheckoutDriver::class)->snapshot($session); + $session->forceFill([ 'status' => PaymentProcessing::$name, 'payment_intent_ref' => 'pi_without_pay', 'payment_processing_at' => now(), - 'cart_fingerprint' => CheckoutCart::fingerprint($session), - 'amount_total' => sessionCart($session)->calculate()->total->value, + 'cart_fingerprint' => $live->fingerprint, + 'amount_total' => $live->amountTotal, ])->save(); $this->get(route('lunar.checkout.processing', $session->uuid)); diff --git a/tests/Feature/ExpressCollectFlowTest.php b/tests/Feature/ExpressCollectFlowTest.php index 6c78221..305b675 100644 --- a/tests/Feature/ExpressCollectFlowTest.php +++ b/tests/Feature/ExpressCollectFlowTest.php @@ -9,10 +9,10 @@ use Lunar\Checkout\States\CheckoutSession\Completed; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; @@ -22,6 +22,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; use Lunar\Tests\Checkout\Utils\PickupPointsStub; uses(TestCase::class, RefreshDatabase::class); @@ -35,7 +36,7 @@ * cart gets is the wallet's billing address. Its own gateway and method * classes so nothing here collides with the other express suites'. */ -class CollectExpressGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds, SupportsPaymentIntents +class CollectExpressGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds { public function createHold(Cart $cart): PaymentIntentDescriptor { @@ -47,26 +48,21 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_collect_'.$cart->id); } - public function describeHold(string $reference): ?HoldDescription - { - return null; - } - - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { return HoldAdjustment::Ok; } - public function captureHold(string $reference, int $amountMinor): void {} + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::RequiresCapture; + return FakeIntents::snapshot($cart, PaymentIntentStatus::RequiresCapture); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_'.$reference); } @@ -190,7 +186,7 @@ function collectBasket(): Cart $line = $order->shippingLines()->firstOrFail(); expect($session->refresh()->status)->toBeInstanceOf(Completed::class) - ->and($line->meta['collect'])->toBeTrue() + ->and($line->meta['pickup'])->toBeTrue() ->and($line->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['fulfilment'])->toBe('collect') ->and($order->shippingAddress->contact_email)->toBe('terry@example.com') diff --git a/tests/Feature/ExpressProjectionTest.php b/tests/Feature/ExpressProjectionTest.php index 3780876..b0dc554 100644 --- a/tests/Feature/ExpressProjectionTest.php +++ b/tests/Feature/ExpressProjectionTest.php @@ -7,9 +7,10 @@ use Lunar\Checkout\PaymentMethods\AbstractPaymentMethod; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; @@ -18,6 +19,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -38,28 +40,23 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_fake_'.$cart->id); } - public function describeHold(string $reference): ?HoldDescription - { - return null; - } - - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { return HoldAdjustment::Ok; } - public function captureHold(string $reference, int $amountMinor): void {} + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} - // SupportsPaymentHolds extends SupportsPaymentIntents, so the release and + // SupportsPaymentHolds extends ReconcilesPaymentIntents, so the release and // reconciliation verbs come with it. - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::RequiresCapture; + return FakeIntents::snapshot($cart, PaymentIntentStatus::RequiresCapture); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_express_'.$reference); } diff --git a/tests/Feature/FreshPaymentTotalsTest.php b/tests/Feature/FreshPaymentTotalsTest.php new file mode 100644 index 0000000..cb69023 --- /dev/null +++ b/tests/Feature/FreshPaymentTotalsTest.php @@ -0,0 +1,330 @@ + */ + public static array $seen = []; + + public function createIntent(Cart $cart): PaymentIntentDescriptor + { + static::$seen['createIntent'] = $cart->total?->value; + + return new PaymentIntentDescriptor('pi_fresh_'.$cart->id); + } + + public function syncIntent(Cart $cart): void + { + static::$seen['syncIntent'] = $cart->total?->value; + } + + public function createHold(Cart $cart): PaymentIntentDescriptor + { + static::$seen['createHold'] = $cart->total?->value; + + return new PaymentIntentDescriptor('hold_fresh_'.$cart->id); + } + + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment + { + static::$seen['adjustHold'] = $amount->value; + + return HoldAdjustment::Ok; + } + + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void {} +} + +class FreshTotalsMethod extends AbstractPaymentMethod +{ + public function handle(): string + { + return 'fresh-card'; + } + + public function label(): string + { + return 'Card'; + } + + public function driver(): string + { + return 'fresh-totals'; + } + + public function requiresIntent(): bool + { + return true; + } + + public function component(): string + { + return 'stripe-card'; + } +} + +/** + * A credit-limit style method: offered only while the basket stays within a + * limit, the way a host's on-account closure decides. + */ +class FreshLimitedAccountMethod extends AbstractPaymentMethod +{ + public function handle(): string + { + return 'fresh-account'; + } + + public function label(): string + { + return 'Pay on account'; + } + + public function driver(): string + { + return 'offline'; + } + + public function component(): string + { + return 'offline-notice'; + } + + public function isAvailable(Cart $cart): bool + { + return $cart->calculate()->total->value <= 2000; + } +} + +class FreshLimitedCardMethod extends FreshTotalsMethod +{ + public function handle(): string + { + return 'fresh-limited-card'; + } + + public function isAvailable(Cart $cart): bool + { + return $cart->calculate()->total->value <= 2000; + } +} + +beforeEach(function () { + FreshTotalsGateway::$seen = []; + + Payments::extend('fresh-totals', fn () => app(FreshTotalsGateway::class)); + app(PaymentMethodRegistry::class) + ->add(FreshTotalsMethod::class) + ->add(FreshLimitedAccountMethod::class) + ->add(FreshLimitedCardMethod::class); +}); + +function calculatedSession(): CheckoutSession +{ + $cart = CheckoutCart::orderable(unitPrice: 1000); + $session = CheckoutCart::session($cart); + + expect($cart->total->value)->toBe(1000) + ->and($session->amount_total)->toBe(1000); + + return $session; +} + +/** + * Reprices the cart's variant straight in the database, which bumps no cart + * revision. Blink is flushed so the next request starts from the persisted + * totals alone, as a new production request would. + */ +function repriceSessionCart(CheckoutSession $session, int $price): void +{ + $variantId = Cart::query()->with('lines')->findOrFail((int) $session->cart_reference)->lines->first()->purchasable_id; + + DB::table((new Price)->getTable()) + ->where('priceable_id', $variantId) + ->update(['price' => $price]); + + Blink::flush(); +} + +it('creates the intent and pins the session from the repriced total, not the cached one', function () { + $session = calculatedSession(); + repriceSessionCart($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-card', + ])->assertOk(); + + expect(FreshTotalsGateway::$seen['createIntent'] ?? null)->toBe(2500); + + repriceSessionCart($session, 3000); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'fingerprint' => CheckoutCart::fingerprint($session), + ])->assertSuccessful(); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(3000) + ->and(FreshTotalsGateway::$seen['syncIntent'] ?? null)->toBe(3000); +}); + +it('creates the hold and pins the session from the repriced total, not the cached one', function () { + $session = calculatedSession(); + repriceSessionCart($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'mode' => 'hold', + ])->assertOk(); + + expect(FreshTotalsGateway::$seen['createHold'] ?? null)->toBe(2500); + + repriceSessionCart($session, 3000); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-card', + 'fingerprint' => CheckoutCart::fingerprint($session), + ])->assertSuccessful(); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(3000) + ->and(FreshTotalsGateway::$seen['adjustHold'] ?? null)->toBe(3000); +}); + +/** + * The cart's live price is $live while its persisted totals still say the + * session's 1000, which calculate() serves. Returns the fingerprint of the + * live basket, the one a customer looking at fresh totals would confirm. + */ +function staleCachedTotals(CheckoutSession $session, int $live): string +{ + repriceSessionCart($session, $live); + $fingerprint = CheckoutCart::fingerprint($session); + + repriceSessionCart($session, 1000); + Cart::query()->findOrFail((int) $session->cart_reference)->recalculate(); + + repriceSessionCart($session, $live); + + $cached = Cart::query()->findOrFail((int) $session->cart_reference); + expect($cached->totalsAreFresh())->toBeTrue() + ->and($cached->calculate()->total->value)->toBe(1000); + Blink::flush(); + + return $fingerprint; +} + +it('decides payment method availability at pay on the repriced total, not the cached one', function () { + $session = calculatedSession(); + $fingerprint = staleCachedTotals($session, 2500); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fresh-account', + 'fingerprint' => $fingerprint, + ])->assertUnprocessable()->assertJsonValidationErrors(['payment_method']); + + expect($session->refresh()->order_reference)->toBeNull(); +}); + +it('decides payment method availability for a new intent on the repriced total, not the cached one', function () { + $session = calculatedSession(); + staleCachedTotals($session, 2500); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'fresh-limited-card', + ])->assertUnprocessable()->assertJsonValidationErrors(['payment_method']); + + expect(FreshTotalsGateway::$seen)->not->toHaveKey('createIntent'); +}); + +/** + * The persisted totals still describe the old price, so anything that trusts + * calculate() would see the basket the customer confirmed. + */ +function expectCachedTotalsServable(CheckoutSession $session, int $cachedTotal): void +{ + $cart = Cart::query()->findOrFail((int) $session->cart_reference); + + expect($cart->totalsAreFresh())->toBeTrue() + ->and($cart->calculate()->total->value)->toBe($cachedTotal); + + Blink::flush(); +} + +it('refuses to pin a session whose cart was repriced behind fresh cached totals', function () { + $session = calculatedSession(); + $fingerprint = CheckoutCart::fingerprint($session); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + expect(fn () => app(CheckoutDriver::class)->assertReadyForPayment($session, $fingerprint)) + ->toThrow(PaymentConfirmationException::class, 'fingerprint_mismatch'); + + expect($session->refresh()->status)->not->toBeInstanceOf(PaymentProcessing::class) + ->and($session->amount_total)->toBe(1000); +}); + +it('refuses to complete a pinned session whose cart was repriced behind fresh cached totals', function () { + Event::fake([CheckoutCompletionFailed::class]); + + $session = calculatedSession(); + $driver = app(CheckoutDriver::class); + $driver->assertReadyForPayment($session, CheckoutCart::fingerprint($session)); + expect($session->status)->toBeInstanceOf(PaymentProcessing::class); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + expect(fn () => $driver->complete($session)) + ->toThrow(PaymentConfirmationException::class, 'fingerprint_mismatch'); + + Event::assertDispatched(CheckoutCompletionFailed::class, fn (CheckoutCompletionFailed $event): bool => $event->reason === 'verify-mismatch'); + expect($session->refresh()->order_reference)->toBeNull(); +}); + +it('returns the repriced snapshot when a customer is associated, not the cached one', function () { + $session = calculatedSession(); + + repriceSessionCart($session, 2500); + expectCachedTotalsServable($session, 1000); + + $snapshot = app(CheckoutDriver::class)->associateCustomer($session, '42', 'terry@example.com'); + + expect($snapshot->amountTotal)->toBe(2500) + ->and($snapshot->fingerprint)->toBe(CheckoutCart::fingerprint($session)); +}); diff --git a/tests/Feature/OrderCreateValidatorsProviderOrderTest.php b/tests/Feature/OrderCreateValidatorsProviderOrderTest.php new file mode 100644 index 0000000..e162c45 --- /dev/null +++ b/tests/Feature/OrderCreateValidatorsProviderOrderTest.php @@ -0,0 +1,14 @@ +all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); +}); diff --git a/tests/Feature/OrderCreateValidatorsTest.php b/tests/Feature/OrderCreateValidatorsTest.php index be4e144..c17f446 100644 --- a/tests/Feature/OrderCreateValidatorsTest.php +++ b/tests/Feature/OrderCreateValidatorsTest.php @@ -1,14 +1,26 @@ all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); +}); + +it('registers through the step registry and leaves the removed config key unset', function () { + expect(config()->has('lunar.cart.validators'))->toBeFalse(); +}); + +it('registers the validator once when the provider boots again', function () { + app()->getProvider(CheckoutServiceProvider::class)->boot(); - expect($validators)->toContain(ValidateCartForOrderCreation::class) - ->and($validators)->toContain(PickupPointRequired::class); + expect(Steps::for(StepList::OrderCreateValidation)->all()) + ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); }); diff --git a/tests/Feature/OrderSummaryItemsTest.php b/tests/Feature/OrderSummaryItemsTest.php index 75f0bda..679b8a7 100644 --- a/tests/Feature/OrderSummaryItemsTest.php +++ b/tests/Feature/OrderSummaryItemsTest.php @@ -44,3 +44,16 @@ expect($response->json('props.checkout.items.0'))->toHaveKeys(['id', 'title', 'sku', 'image', 'qty', 'price']); expect($response->json('props.checkout.items.0.image'))->toBeNull(); }); + +it('renders every line of a multi-line cart without lazy loading', function () { + $cart = CheckoutCart::orderable(); + CheckoutCart::addLine($cart, 2500); + $session = CheckoutCart::session($cart->refresh()); + + $response = $this->get(route('lunar.checkout.show', $session->uuid), ['X-Inertia' => 'true']) + ->assertOk(); + + expect($response->json('props.checkout.items'))->toHaveCount(2) + ->and($response->json('props.checkout.shippingMethods'))->not->toBeEmpty() + ->and($response->json('props.checkout.totals.sub_total'))->toBe(3500); +}); diff --git a/tests/Feature/PayBoundaryTest.php b/tests/Feature/PayBoundaryTest.php index 42cd038..0d2a12a 100644 --- a/tests/Feature/PayBoundaryTest.php +++ b/tests/Feature/PayBoundaryTest.php @@ -1,6 +1,7 @@ id); + } + public function syncIntent(Cart $cart): void { + if (static::$throwOnSync) { + throw new PaymentIntentException('fake gateway refused to sync the intent'); + } + static::$syncedAmount = $cart->calculate()->total->value; } } @@ -116,7 +138,6 @@ public function driver(): string it('syncs the gateway intent to the live total before pinning', function () { Payments::extend('sync-test', fn () => app(SyncingTestGateway::class)); - SyncingTestGateway::$syncedAmount = null; app(PaymentMethodRegistry::class)->add(SyncingIntentTestMethod::class); @@ -135,6 +156,28 @@ public function driver(): string ->and($session->status)->toBeInstanceOf(PaymentProcessing::class); }); +it('refuses to pin, with a retry message, when the gateway refuses to sync the intent', function () { + Exceptions::fake(); + Payments::extend('sync-test', fn () => app(SyncingTestGateway::class)); + SyncingTestGateway::$throwOnSync = true; + + app(PaymentMethodRegistry::class)->add(SyncingIntentTestMethod::class); + + $session = CheckoutCart::session(CheckoutCart::orderable()); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'fingerprint' => CheckoutCart::fingerprint($session), + 'payment_method' => 'sync-card', + ]) + ->assertUnprocessable() + ->assertJsonPath('errors.payment_method.0', 'Card payments are unavailable right now. Please try again in a moment.'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->meta['payment_handle'] ?? null)->toBeNull(); + + Exceptions::assertReported(PaymentIntentException::class); +}); + it('pins for confirmation with the order drafted but unplaced when the method needs an intent', function () { app(PaymentMethodRegistry::class)->add(IntentTestMethod::class); diff --git a/tests/Feature/PaymentHoldTest.php b/tests/Feature/PaymentHoldTest.php index 6ed8dce..d292177 100644 --- a/tests/Feature/PaymentHoldTest.php +++ b/tests/Feature/PaymentHoldTest.php @@ -2,6 +2,7 @@ use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Arr; use Illuminate\Support\Facades\Artisan; use Illuminate\Support\Facades\Exceptions; use Lunar\Checkout\Contracts\PaymentMethodRegistry; @@ -13,10 +14,10 @@ use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; use Lunar\Core\Contracts\SupportsPaymentHolds; -use Lunar\Core\Contracts\SupportsPaymentIntents; -use Lunar\Core\DataObjects\HoldDescription; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\HoldAdjustment; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Exceptions\PaymentIntentException; @@ -27,6 +28,8 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FailingOrderCreationStep; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -37,7 +40,7 @@ * doesn't need to (it only asserts driver behaviour) but the hold-routing * assertions here do. */ -class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds, SupportsPaymentIntents +class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentHolds { /** @var array */ public static array $createIntentCalls = []; @@ -48,10 +51,13 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S /** @var array */ public static array $voidedReferences = []; - /** @var array}> */ + /** @var array */ + public static array $adjustCalls = []; + + /** @var array}> */ public static array $captureCalls = []; - /** @var array}> */ + /** @var array */ public static array $refundCalls = []; public static int $holdSequence = 0; @@ -64,12 +70,19 @@ class FakeHoldGateway extends OfflinePayment implements CreatesPaymentIntents, S public static bool $throwOnVoid = false; + public static bool $throwOnAdjust = false; + /** - * Verified against by the confirm-page guard: null (the default) means - * "gateway doesn't recognise this reference", exactly like a real driver - * would answer for a non-hold or unknown reference. + * Answers for successive fetches, taken ahead of `$fetchStatus`. Null is + * a reference the gateway did not create for the cart. + * + * @var array */ - public static ?HoldDescription $describeOutcome = null; + public static array $fetchScript = []; + + public static int $holdAmount = 0; + + public static ?string $walletLabel = null; public function createIntent(Cart $cart): PaymentIntentDescriptor { @@ -85,35 +98,45 @@ public function createHold(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('hold_fake_'.$cart->id.'_'.(++static::$holdSequence)); } - public function describeHold(string $reference): ?HoldDescription + public function adjustHold(Cart $cart, string $reference, PriceValue $amount): HoldAdjustment { - return static::$describeOutcome; - } + if (static::$throwOnAdjust) { + throw new PaymentIntentException('fake gateway refused to adjust the hold'); + } + + static::$adjustCalls[] = [ + 'cart' => $cart->id, + 'reference' => $reference, + 'amount' => $amount->value, + 'currency' => $amount->resolveCurrency()->code, + ]; - public function adjustHold(string $reference, int $amountMinor): HoldAdjustment - { return static::$adjustOutcome; } - public function captureHold(string $reference, int $amountMinor): void + public function captureHold(Cart $cart, string $reference, PriceValue $amount): void { if (static::$throwOnCapture) { throw new PaymentIntentException('fake gateway capture failed'); } static::$captureCalls[] = [ + 'cart' => $cart->id, 'reference' => $reference, - 'amount' => $amountMinor, + 'amount' => $amount->value, + 'currency' => $amount->resolveCurrency()->code, 'unplaced_orders' => Order::query()->whereNull('placed_at')->pluck('id')->all(), ]; } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return static::$fetchStatus; + $status = static::$fetchScript === [] ? static::$fetchStatus : array_shift(static::$fetchScript); + + return $status ? FakeIntents::snapshot($cart, $status, static::$holdAmount, static::$walletLabel) : null; } - public function voidIntent(string $reference): void + public function voidIntent(Cart $cart, string $reference): void { if (static::$throwOnVoid) { throw new PaymentIntentException('fake gateway void failed'); @@ -122,9 +145,9 @@ public function voidIntent(string $reference): void static::$voidedReferences[] = $reference; } - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amountMinor]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; return new PaymentRefund(success: true, reference: 'refund_fake_'.$reference); } @@ -132,19 +155,18 @@ public function refundIntent(string $reference, int $amountMinor, string $idempo /** * A gateway that can only create standard intents, no hold capability, the - * way most drivers will stay. Also implements {@see SupportsPaymentIntents} - * (fetch/void/refund) so it doubles as the "hold mode flagged on a session + * way most drivers will stay. Its fetch/void/refund double as the "hold mode flagged on a session * whose driver never actually supports holds" misconfiguration fixture: a * hold-mode session pinned against this gateway reaches completeOrRefund() * with an intent-capable-but-not-hold-capable driver, exercising the flavour * branch that must void rather than refund an uncaptured hold. */ -class IntentOnlyGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class IntentOnlyGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array */ public static array $voidedReferences = []; - /** @var array}> */ + /** @var array */ public static array $refundCalls = []; public static PaymentIntentStatus $fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -154,19 +176,19 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_intent_only_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return static::$fetchStatus; + return FakeIntents::snapshot($cart, static::$fetchStatus); } - public function voidIntent(string $reference): void + public function voidIntent(Cart $cart, string $reference): void { static::$voidedReferences[] = $reference; } - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { - static::$refundCalls[] = ['reference' => $reference, 'amount' => $amountMinor]; + static::$refundCalls[] = ['reference' => $reference, 'amount' => $amount->value, 'currency' => $amount->resolveCurrency()->code]; return new PaymentRefund(success: true, reference: 'refund_intent_only_'.$reference); } @@ -363,6 +385,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession FakeHoldGateway::$createIntentCalls = []; FakeHoldGateway::$createHoldCalls = []; FakeHoldGateway::$voidedReferences = []; + FakeHoldGateway::$adjustCalls = []; FakeHoldGateway::$captureCalls = []; FakeHoldGateway::$refundCalls = []; FakeHoldGateway::$holdSequence = 0; @@ -370,7 +393,10 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; FakeHoldGateway::$throwOnCapture = false; FakeHoldGateway::$throwOnVoid = false; - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$throwOnAdjust = false; + FakeHoldGateway::$fetchScript = []; + FakeHoldGateway::$holdAmount = 0; + FakeHoldGateway::$walletLabel = null; IntentOnlyGateway::$voidedReferences = []; IntentOnlyGateway::$refundCalls = []; IntentOnlyGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -495,6 +521,46 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('asks for a fresh authorisation when the gateway refuses to adjust the hold', function () { + Exceptions::fake(); + $session = mintHoldSession(); + FakeHoldGateway::$throwOnAdjust = true; + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fake', + 'fingerprint' => CheckoutCart::fingerprint($session), + ]) + ->assertUnprocessable() + ->assertJsonPath('errors.hold.0', 'hold_reauthorization_required'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->meta['payment_handle'] ?? null)->toBeNull(); + + Exceptions::assertReported(PaymentIntentException::class); +}); + +it('cancels a hold session whose cart changed currency instead of asking the gateway to adjust the hold', function () { + Exceptions::fake(); + $session = mintHoldSession(); + $hold = $session->payment_intent_ref; + FakeHoldGateway::$throwOnAdjust = true; + + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $this->postJson(route('lunar.checkout.pay', $session->uuid), [ + 'payment_method' => 'fake', + 'fingerprint' => CheckoutCart::fingerprint($session), + ]) + ->assertUnprocessable() + ->assertJsonValidationErrorFor('fingerprint'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Cancelled::class) + ->and($session->meta['invalidation_reason'] ?? null)->toBe('context_diverged') + ->and(FakeHoldGateway::$voidedReferences)->toBe([$hold]); +}); + it('pins a hold session and reconcile captures then completes', function () { $session = mintHoldSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; @@ -510,8 +576,18 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $this->get(route('lunar.checkout.processing', $session->uuid)); - expect(FakeHoldGateway::$captureCalls)->toHaveCount(1) - ->and(FakeHoldGateway::$captureCalls[0]['amount'])->toBe($session->refresh()->amount_total) + $session->refresh(); + + $expected = [ + 'cart' => (int) $session->cart_reference, + 'reference' => $session->payment_intent_ref, + 'amount' => $session->amount_total, + 'currency' => $session->currency_code, + ]; + + expect(FakeHoldGateway::$adjustCalls)->toBe([$expected]) + ->and(FakeHoldGateway::$captureCalls)->toHaveCount(1) + ->and(Arr::except(FakeHoldGateway::$captureCalls[0], 'unplaced_orders'))->toBe($expected) ->and($session->status)->toBeInstanceOf(Completed::class); }); @@ -574,14 +650,26 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('captures and refunds a hold in the currency the session was pinned in after the cart changed currency', function () { + $session = mintPinnedHoldSession(); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; + + CheckoutCart::changeCurrency(Cart::query()->findOrFail((int) $session->cart_reference), 'EUR'); + + $this->get(route('lunar.checkout.processing', $session->uuid)); + + expect(Arr::only(FakeHoldGateway::$captureCalls[0] ?? [], ['reference', 'amount', 'currency'])) + ->toBe(['reference' => 'hold_fake_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']) + ->and(FakeHoldGateway::$refundCalls) + ->toBe([['reference' => 'hold_fake_pinned', 'amount' => $session->amount_total, 'currency' => 'GBP']]); +}); + it('refunds the captured hold when completion throws for any reason', function () { Exceptions::fake(); $session = mintPinnedHoldSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); @@ -596,9 +684,7 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession $session = mintPinnedStandardSession(); FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresCapture; - config()->set('lunar.orders.pipelines.creation', [ - fn () => throw new RuntimeException('order pipeline down'), - ]); + FailingOrderCreationStep::register(); $this->get(route('lunar.checkout.processing', $session->uuid)); @@ -638,6 +724,20 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession expect($session->refresh()->status)->toBeInstanceOf(Cancelled::class); }); +it('voids the hold of an expired session whose cart was pruned', function () { + $session = mintHoldSession(); + $reference = $session->payment_intent_ref; + + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + $session->forceFill(['expires_at' => now()->subMinute()])->save(); + + Artisan::call('lunar:checkout:expire-sessions'); + + expect(FakeHoldGateway::$voidedReferences)->toBe([$reference]) + ->and($session->refresh()->status)->toBeInstanceOf(Cancelled::class) + ->and($session->active_cart_reference)->toBeNull(); +}); + it('voids, never refunds, a stray hold when the driver never supported holds and completion fails', function () { $session = mintPinnedHoldSessionWithoutHoldSupport(); @@ -734,11 +834,8 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession it('processing routes a reopened hold session to confirm, keeping the payment=failed flag', function () { $session = mintPinnedHoldSession(); FakeHoldGateway::$throwOnCapture = true; - FakeHoldGateway::$describeOutcome = new HoldDescription( - status: PaymentIntentStatus::RequiresCapture, - amountMinor: $session->amount_total, - walletLabel: 'Apple Pay', - ); + FakeHoldGateway::$holdAmount = $session->amount_total; + FakeHoldGateway::$walletLabel = 'Apple Pay'; $this->get(route('lunar.checkout.processing', $session->uuid)) ->assertRedirect(route('lunar.checkout.confirm', $session->uuid).'?payment=failed'); @@ -747,10 +844,26 @@ function mintPinnedHoldSessionWithoutHoldSupport(): CheckoutSession ->and($session->payment_intent_ref)->toBe('hold_fake_pinned'); }); +it('voids a hold that waited on the customer too long and sends the customer back to the checkout', function () { + $session = mintPinnedHoldSession(); + $session->forceFill(['payment_processing_at' => now()->subMinutes(31)])->save(); + FakeHoldGateway::$fetchStatus = PaymentIntentStatus::RequiresAction; + + $this->get(route('lunar.checkout.processing', $session->uuid), ['X-Inertia' => 'true']) + ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and(FakeHoldGateway::$voidedReferences)->toBe(['hold_fake_pinned']) + ->and($session->payment_intent_ref)->toBeNull() + ->and(FakeHoldGateway::$captureCalls)->toBeEmpty(); +}); + it('processing falls back to show when a reopened hold no longer verifies', function () { $session = mintPinnedHoldSession(); FakeHoldGateway::$throwOnCapture = true; - FakeHoldGateway::$describeOutcome = null; + FakeHoldGateway::$fetchScript = [PaymentIntentStatus::RequiresCapture, null]; $this->get(route('lunar.checkout.processing', $session->uuid)) ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); diff --git a/tests/Feature/PaymentIntentReuseTest.php b/tests/Feature/PaymentIntentReuseTest.php index c18af72..998afab 100644 --- a/tests/Feature/PaymentIntentReuseTest.php +++ b/tests/Feature/PaymentIntentReuseTest.php @@ -14,6 +14,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); @@ -23,9 +24,11 @@ */ class ReusedIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { - return new PaymentIntentDescriptor('pi_reused_'.$cart->id, 'secret_'.$cart->id); + return new PaymentIntentDescriptor('pi_reused_'.$cart->id, clientPayload: ['client_secret' => 'secret_'.$cart->id]); } } @@ -63,6 +66,21 @@ function registerReusedIntentGateway(): void app(PaymentMethodRegistry::class)->add(ReusedIntentMethod::class); } +it('hands the browser the intent reference and the client secret from the gateway payload', function () { + registerReusedIntentGateway(); + + $cart = CheckoutCart::orderable(); + CartSession::use($cart); + $session = CheckoutCart::session($cart); + + $this->postJson(route('lunar.checkout.payment-intent.store', $session->uuid), [ + 'payment_method' => 'reused-card', + ])->assertOk()->assertExactJson([ + 'intent' => 'pi_reused_'.$cart->id, + 'clientSecret' => 'secret_'.$cart->id, + ]); +}); + it('lets a successor session take over the intent reference a dead session still holds', function () { registerReusedIntentGateway(); diff --git a/tests/Feature/PaymentMethodAvailabilityTest.php b/tests/Feature/PaymentMethodAvailabilityTest.php index e9a1ba5..4ccd57d 100644 --- a/tests/Feature/PaymentMethodAvailabilityTest.php +++ b/tests/Feature/PaymentMethodAvailabilityTest.php @@ -57,7 +57,7 @@ public function label(): string public function isAvailable(Cart $cart): bool { - return (bool) $cart->getShippingOption()?->collect; + return (bool) $cart->getShippingOption()?->pickup; } } diff --git a/tests/Feature/PaymentRecordingTest.php b/tests/Feature/PaymentRecordingTest.php index d339ee3..ec37fb5 100644 --- a/tests/Feature/PaymentRecordingTest.php +++ b/tests/Feature/PaymentRecordingTest.php @@ -9,10 +9,11 @@ use Lunar\Checkout\States\CheckoutSession\Completed; use Lunar\Checkout\States\CheckoutSession\PaymentProcessing; use Lunar\Core\Contracts\CreatesPaymentIntents; -use Lunar\Core\Contracts\SupportsPaymentIntents; use Lunar\Core\DataObjects\PaymentAuthorize; use Lunar\Core\DataObjects\PaymentIntentDescriptor; +use Lunar\Core\DataObjects\PaymentIntentSnapshot; use Lunar\Core\DataObjects\PaymentRefund; +use Lunar\Core\DataObjects\PriceValue; use Lunar\Core\Enums\PaymentIntentStatus; use Lunar\Core\Facades\CartSession; use Lunar\Core\Facades\Payments; @@ -21,6 +22,7 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\FakeIntents; uses(TestCase::class, RefreshDatabase::class); @@ -31,7 +33,7 @@ * checkout driver ran the shared authorize() path itself (spec 0002 §E) * instead of leaving it to a webhook. */ -class RecordingGateway extends OfflinePayment implements CreatesPaymentIntents, SupportsPaymentIntents +class RecordingGateway extends OfflinePayment implements CreatesPaymentIntents { /** @var array}> */ public static array $authorizeCalls = []; @@ -43,14 +45,14 @@ public function createIntent(Cart $cart): PaymentIntentDescriptor return new PaymentIntentDescriptor('pi_recording_'.$cart->id); } - public function fetchIntent(string $reference): PaymentIntentStatus + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { - return PaymentIntentStatus::Captured; + return FakeIntents::snapshot($cart, PaymentIntentStatus::Captured); } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void {} - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 'refund_'.$reference); } @@ -149,7 +151,10 @@ function pinnedRecordingSession(): CheckoutSession expect(RecordingGateway::$authorizeCalls)->toHaveCount(1) ->and(RecordingGateway::$authorizeCalls[0]['order_id'])->toBe($order->id) - ->and(RecordingGateway::$authorizeCalls[0]['data']['payment_intent'])->toBe('pi_recording_pinned') + ->and(RecordingGateway::$authorizeCalls[0]['data'])->toBe([ + 'reference' => 'pi_recording_pinned', + 'payment_intent' => 'pi_recording_pinned', + ]) ->and($session->status)->toBeInstanceOf(Completed::class) ->and($order->placed_at)->not->toBeNull() ->and($order->transactions()->where('type', 'capture')->count())->toBe(1) diff --git a/tests/Feature/PaymentReleaseTest.php b/tests/Feature/PaymentReleaseTest.php index 640b969..39b5470 100644 --- a/tests/Feature/PaymentReleaseTest.php +++ b/tests/Feature/PaymentReleaseTest.php @@ -1,18 +1,28 @@ */ + public static array $fetchedCartIds = []; + + /** @var array */ + public static array $voided = []; + + public static bool $throwOnVoid = false; + + public function fetchIntent(Cart $cart, string $reference): ?PaymentIntentSnapshot { + static::$fetchedCartIds[] = $cart->id; + if (static::$throwOnFetch) { throw new PaymentIntentException('gateway unreachable'); } - return static::$status; + return static::$status ? FakeIntents::snapshot($cart, static::$status) : null; } - public function voidIntent(string $reference): void {} + public function voidIntent(Cart $cart, string $reference): void + { + if (static::$throwOnVoid) { + throw new PaymentIntentException('the intent is no longer voidable'); + } + + static::$voided[] = $reference; + } - public function refundIntent(string $reference, int $amountMinor, string $idempotencyKey): PaymentRefund + public function refundIntent(Cart $cart, string $reference, PriceValue $amount, string $idempotencyKey): PaymentRefund { return new PaymentRefund(success: true, reference: 're_test'); } @@ -59,11 +87,193 @@ function pinnedSession(array $overrides = []) beforeEach(function () { Payments::extend('release-test', fn () => app(ReleaseTestGateway::class)); - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; ReleaseTestGateway::$throwOnFetch = false; + ReleaseTestGateway::$fetchedCartIds = []; + ReleaseTestGateway::$voided = []; + ReleaseTestGateway::$throwOnVoid = false; +}); + +dataset('in-flight intent statuses', [ + 'waiting on the customer' => [PaymentIntentStatus::RequiresAction], + 'gateway still deciding' => [PaymentIntentStatus::Processing], +]); + +it('reconciles a recently pinned in-flight intent to pending without consuming an attempt', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(29)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('pending'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); +})->with('in-flight intent statuses'); + +it('voids an intent that has waited on the customer past the window and reopens the session', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('intent_requires_action'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull() + ->and($session->payment_processing_at)->toBeNull() + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->expires_at->isFuture())->toBeTrue(); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); + Event::assertNotDispatched(CheckoutSessionReconciliationStalled::class); }); -it('reopens a pinned session when the gateway holds no captured money', function () { +it('keeps a session pinned while the gateway is still deciding, however long that takes', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; + + $session = pinnedSession(['payment_processing_at' => now()->subDays(3)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('pending'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); +}); + +it('reads how long an intent may wait on the customer from config', function () { + config()->set('lunar.checkout.reconciliation.requires_action_minutes', 5); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $inside = pinnedSession(['payment_processing_at' => now()->subMinutes(4)]); + $past = pinnedSession(['payment_processing_at' => now()->subMinutes(6), 'payment_intent_ref' => 'pi_test_456']); + + app(ReconcilesCheckoutSession::class)->execute($inside); + app(ReconcilesCheckoutSession::class)->execute($past); + + expect($inside->refresh()->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($past->refresh()->status)->toBeInstanceOf(Open::class); +}); + +it('reopens a session waiting on the customer whose pin time was never recorded', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => null]); + + app(ReconcilesCheckoutSession::class)->execute($session); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull(); +}); + +it('lets the sweep free a cart whose payment the customer abandoned', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(61)]); + $cart = Cart::query()->findOrFail((int) $session->cart_reference); + + expect(fn () => app(CheckoutDriver::class)->createSession($cart)) + ->toThrow(CheckoutSessionConflictException::class); + + $this->artisan('lunar:checkout:reconcile')->assertSuccessful(); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and($session->reconciliation_attempts)->toBe(0) + ->and($session->meta['reconciliation_stalled'] ?? false)->toBeFalse() + ->and(app(CheckoutDriver::class)->resolveOrCreateSession($cart)->is($session))->toBeTrue(); +}); + +it('keeps the session pinned and counts an attempt when the gateway refuses to void the waiting intent', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123') + ->and($session->reconciliation_attempts)->toBe(1); + + Event::assertNotDispatched(CheckoutCompletionFailed::class); + Event::assertNotDispatched(CheckoutSessionReconciliationStalled::class); +}); + +it('completes on the next pass when the payment went through just as the window closed', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + // The customer finished between the fetch and the void, so the gateway + // refuses the void and the next fetch reads the money. + app(ReconcilesCheckoutSession::class)->execute($session); + + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; + + expect(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('completed'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Completed::class) + ->and(Order::query()->whereNotNull('placed_at')->count())->toBe(1) + ->and((string) $session->order_reference)->toBe((string) Order::query()->firstOrFail()->id); +}); + +it('stalls for the operator when the waiting intent can never be voided', function () { + Event::fake([CheckoutCompletionFailed::class, CheckoutSessionReconciliationStalled::class]); + config()->set('lunar.checkout.reconciliation.max_attempts', 2); + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + ReleaseTestGateway::$throwOnVoid = true; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry') + ->and(app(ReconcilesCheckoutSession::class)->execute($session->refresh()))->toBe('stalled') + ->and($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); + + Event::assertDispatchedTimes(CheckoutSessionReconciliationStalled::class, 1); + Event::assertNotDispatched(CheckoutCompletionFailed::class); +}); + +it('counts an attempt when the gateway did not create the reference for the cart', function () { + ReleaseTestGateway::$status = null; + + $session = pinnedSession(); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(PaymentProcessing::class) + ->and($session->reconciliation_attempts)->toBe(1); +}); + +it('counts an attempt without asking the gateway when the cart is gone', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; + + $session = pinnedSession(['cart_reference' => '999999']); + + expect(app(ReconcilesCheckoutSession::class)->execute($session))->toBe('retry') + ->and($session->refresh()->reconciliation_attempts)->toBe(1) + ->and(ReleaseTestGateway::$fetchedCartIds)->toBeEmpty(); +}); + +it('reopens a pinned session when the gateway holds no captured money', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; + $session = pinnedSession(); $this->postJson(route('lunar.checkout.payment-release', $session->uuid)) @@ -78,7 +288,7 @@ function pinnedSession(array $overrides = []) // payment element is still bound to it. expect($session->status)->toBeInstanceOf(Open::class) ->and($session->payment_intent_ref)->toBe('pi_test_123'); -}); +})->with('in-flight intent statuses'); it('completes instead of releasing when the money was captured', function () { ReleaseTestGateway::$status = PaymentIntentStatus::Captured; @@ -107,6 +317,30 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); }); +it('stays frozen when the gateway did not create the reference for the cart', function () { + ReleaseTestGateway::$status = null; + + $session = pinnedSession(); + + $this->postJson(route('lunar.checkout.payment-release', $session->uuid)) + ->assertOk() + ->assertJsonPath('outcome', 'unconfirmed') + ->assertJsonPath('released', false); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); +}); + +it('releases on the gateway\'s word when the cart was pruned', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(); + Cart::query()->findOrFail((int) $session->cart_reference)->delete(); + + expect(app(ReconcilesCheckoutSession::class)->release($session))->toBe('released') + ->and($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(ReleaseTestGateway::$fetchedCartIds)->toBe([(int) $session->cart_reference]); +}); + it('is a no-op on a session that is not pinned', function () { $session = CheckoutCart::session(CheckoutCart::orderable()); @@ -169,6 +403,49 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); +it('reopens a pinned session at once when the customer returns from a failed gateway redirect', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinute()]); + + $response = $this->get(route('lunar.checkout.show', $session->uuid).'?payment_intent=pi_test_123&payment_intent_client_secret=secret&redirect_status=failed'); + + $session->refresh(); + + expect($session->status)->toBeInstanceOf(Open::class) + ->and($session->payment_intent_ref)->toBe('pi_test_123'); + + $response->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); +}); + +it('keeps a session pinned on view unless the redirect failed for its own intent', function (string $query) { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinute()]); + + $this->get(route('lunar.checkout.show', $session->uuid).$query, ['X-Inertia' => 'true'])->assertOk(); + + expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); +})->with([ + 'no redirect parameters' => [''], + 'a redirect that succeeded' => ['?payment_intent=pi_test_123&redirect_status=succeeded'], + 'a failed redirect for another intent' => ['?payment_intent=pi_test_other&redirect_status=failed'], + 'a failed redirect naming no intent' => ['?redirect_status=failed'], +]); + +it('completes instead of reopening when the gateway captured despite a failed redirect return', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::Captured; + + $session = pinnedSession(['success_url' => 'https://store.test/thanks']); + + $response = $this->get(route('lunar.checkout.show', $session->uuid).'?payment_intent=pi_test_123&redirect_status=failed'); + + expect($session->refresh()->status)->toBeInstanceOf(Completed::class) + ->and(Order::query()->count())->toBe(1); + + $response->assertRedirect('https://store.test/thanks'); +}); + it('processing settles a captured session and forwards to the success url', function () { ReleaseTestGateway::$status = PaymentIntentStatus::Captured; @@ -208,8 +485,21 @@ function pinnedSession(array $overrides = []) expect($session->refresh()->status)->toBeInstanceOf(Open::class); }); -it('processing renders the polling page while the outcome is in flight', function () { - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; +it('processing sends a payment that waited on the customer too long back to the checkout to retry', function () { + ReleaseTestGateway::$status = PaymentIntentStatus::RequiresAction; + + $session = pinnedSession(['payment_processing_at' => now()->subMinutes(31)]); + + $this->get(route('lunar.checkout.processing', $session->uuid), ['X-Inertia' => 'true']) + ->assertRedirect(route('lunar.checkout.show', $session->uuid).'?payment=failed'); + + expect($session->refresh()->status)->toBeInstanceOf(Open::class) + ->and(ReleaseTestGateway::$voided)->toBe(['pi_test_123']) + ->and($session->payment_intent_ref)->toBeNull(); +}); + +it('processing renders the polling page while the outcome is in flight', function (PaymentIntentStatus $status) { + ReleaseTestGateway::$status = $status; $session = pinnedSession(); @@ -219,10 +509,10 @@ function pinnedSession(array $overrides = []) ->assertJsonPath('props.pollUrl', route('lunar.checkout.processing', $session->uuid)); expect($session->refresh()->status)->toBeInstanceOf(PaymentProcessing::class); -}); +})->with('in-flight intent statuses'); it('processing shows the same merchant name as the checkout', function () { - ReleaseTestGateway::$status = PaymentIntentStatus::Pending; + ReleaseTestGateway::$status = PaymentIntentStatus::Processing; config(['lunar.checkout.merchant' => 'Edwardes Bros', 'app.name' => 'Lunar Store']); $session = pinnedSession(); diff --git a/tests/Feature/PickupPointModifierTest.php b/tests/Feature/PickupPointModifierTest.php index fa1b333..4c23013 100644 --- a/tests/Feature/PickupPointModifierTest.php +++ b/tests/Feature/PickupPointModifierTest.php @@ -21,7 +21,7 @@ $cart = app(SetsFulfilment::class)->execute($cart, 'collect'); $options = ShippingManifest::getOptions($cart); - $collect = $options->firstWhere('collect', true); + $collect = $options->firstWhere('pickup', true); expect($collect->meta['pickup_point'])->toBe([ 'handle' => 'dartford', @@ -31,13 +31,13 @@ 'location' => null, ]); - $options->where('collect', false)->each(fn ($option) => expect($option->meta['pickup_point'] ?? null)->toBeNull()); + $options->where('pickup', false)->each(fn ($option) => expect($option->meta['pickup_point'] ?? null)->toBeNull()); }); it('leaves option meta alone when no point is chosen', function () { $cart = CheckoutCart::orderable(collect: true); - $collect = ShippingManifest::getOptions($cart)->firstWhere('collect', true); + $collect = ShippingManifest::getOptions($cart)->firstWhere('pickup', true); expect($collect->meta['pickup_point'] ?? null)->toBeNull(); }); @@ -55,7 +55,7 @@ $order = Order::query()->firstOrFail(); $line = $order->shippingLines()->firstOrFail(); - expect($line->meta['collect'])->toBeTrue() + expect($line->meta['pickup'])->toBeTrue() ->and($line->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['pickup_point']['handle'])->toBe('dartford') ->and($order->meta['fulfilment'])->toBe('collect'); diff --git a/tests/Feature/PickupPointRoutesTest.php b/tests/Feature/PickupPointRoutesTest.php index e2c66c7..7a611e2 100644 --- a/tests/Feature/PickupPointRoutesTest.php +++ b/tests/Feature/PickupPointRoutesTest.php @@ -26,7 +26,7 @@ function routesCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); return $cart->refresh(); diff --git a/tests/Feature/PickupPointValidationTest.php b/tests/Feature/PickupPointValidationTest.php index c6c6196..9de4c77 100644 --- a/tests/Feature/PickupPointValidationTest.php +++ b/tests/Feature/PickupPointValidationTest.php @@ -5,9 +5,7 @@ use Lunar\Checkout\Contracts\CheckoutDriver; use Lunar\Checkout\DataTypes\PickupPoint; use Lunar\Checkout\Exceptions\PaymentConfirmationException; -use Lunar\Checkout\Validation\Cart\PickupPointRequired; use Lunar\Core\Facades\CartSession; -use Lunar\Core\Validation\Cart\ValidateCartForOrderCreation; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; use Lunar\Tests\Checkout\Utils\PickupPointsStub; @@ -80,8 +78,3 @@ expect($withLondon)->not->toBe($before) ->and($withDartford)->not->toBe($withLondon); }); - -it('appends the pickup point validator after core\'s own', function () { - expect(config('lunar.cart.validators.order_create')) - ->toBe([ValidateCartForOrderCreation::class, PickupPointRequired::class]); -}); diff --git a/tests/Feature/SetFulfilmentTest.php b/tests/Feature/SetFulfilmentTest.php index 05c5ba1..572fc02 100644 --- a/tests/Feature/SetFulfilmentTest.php +++ b/tests/Feature/SetFulfilmentTest.php @@ -32,7 +32,7 @@ function fulfilmentCart(): Cart identifier: 'collection', price: new PriceValue(0, Currency::query()->firstWhere('default', true)), taxClass: TaxClass::query()->firstWhere('default', true), - collect: true, + pickup: true, )); return $cart->refresh(); diff --git a/tests/Feature/WebhookFirstPlacementTest.php b/tests/Feature/WebhookFirstPlacementTest.php index 52c5988..08015c8 100644 --- a/tests/Feature/WebhookFirstPlacementTest.php +++ b/tests/Feature/WebhookFirstPlacementTest.php @@ -23,15 +23,18 @@ use Lunar\Core\PaymentTypes\OfflinePayment; use Lunar\Tests\Checkout\TestCase; use Lunar\Tests\Checkout\Utils\CheckoutCart; +use Lunar\Tests\Checkout\Utils\WithoutIntentReconciliation; uses(TestCase::class, RefreshDatabase::class); /** A Stripe-like gateway: the browser gets an intent it can confirm directly. */ class WebhookFirstIntentGateway extends OfflinePayment implements CreatesPaymentIntents { + use WithoutIntentReconciliation; + public function createIntent(Cart $cart): PaymentIntentDescriptor { - return new PaymentIntentDescriptor('pi_webhook_first_'.$cart->id, 'secret_'.$cart->id); + return new PaymentIntentDescriptor('pi_webhook_first_'.$cart->id, clientPayload: ['client_secret' => 'secret_'.$cart->id]); } } @@ -65,9 +68,9 @@ public function component(): string /** * Swap the checkout driver for a proxy whose snapshot() first runs $race. - * The listener calls snapshot() between its locked read and its guarded - * update, so this exercises the guarded update's lost-race fallback (in - * production the row lock serialises the other writer instead). + * The listener takes its snapshot before it locks the session row, so this + * is another process moving the session in that window: the locked re-read + * has to notice and leave the session to that process. */ function raceTheListener(Closure $race): void { @@ -244,3 +247,28 @@ function gatewayPlacesOrder(Order $order, bool $success = true): void Log::shouldNotHaveReceived('warning'); }); + +it('leaves a session alone when another process ends it just after the listener read it', function () { + Event::fake([OrderPlacing::class]); + + $cart = CheckoutCart::orderable(); + CartSession::use($cart); + $session = app(CheckoutDriver::class)->resolveOrCreateSession($cart); + $order = $cart->createOrder(); + + // The listener's copy still reads Open; the row another process wrote + // does not. + $ended = false; + CheckoutSession::retrieved(function (CheckoutSession $read) use (&$ended) { + if (! $ended) { + $ended = true; + CheckoutSession::query()->whereKey($read->getKey())->update(['status' => Cancelled::$name]); + } + }); + + gatewayPlacesOrder($order); + + expect($session->refresh()->status)->toBeInstanceOf(Cancelled::class); + + Event::assertNotDispatched(OrderPlacing::class); +}); diff --git a/tests/Utils/BareCartValidatorsTestCase.php b/tests/Utils/BareCartValidatorsTestCase.php deleted file mode 100644 index b6ed134..0000000 --- a/tests/Utils/BareCartValidatorsTestCase.php +++ /dev/null @@ -1,22 +0,0 @@ -set('lunar.cart.validators', []); - } -} diff --git a/tests/Utils/CheckoutCart.php b/tests/Utils/CheckoutCart.php index 048ef0a..22a3b66 100644 --- a/tests/Utils/CheckoutCart.php +++ b/tests/Utils/CheckoutCart.php @@ -95,7 +95,7 @@ public static function orderable(int $unitPrice = 1000, bool $collect = false): identifier: $collect ? 'collection' : 'standard', price: new PriceValue(0, $currency), taxClass: $taxClass, - collect: $collect, + pickup: $collect, ); ShippingManifest::addOption($option); @@ -146,6 +146,41 @@ public static function addLine(Cart $cart, int $unitPrice = 1000): Cart return $cart->refresh(); } + /** + * The shopper switched currency after the session pinned its own: the + * cart moves to `$code`, priced there, while the session keeps the old one. + */ + public static function changeCurrency(Cart $cart, string $code): Cart + { + $currency = Currency::factory()->createQuietly(['code' => $code, 'default' => false, 'decimal_places' => 2]); + + foreach ($cart->lines()->get() as $line) { + Price::factory()->create([ + 'price' => 1000, + 'min_quantity' => 1, + 'currency_id' => $currency->id, + 'priceable_type' => $line->purchasable_type, + 'priceable_id' => $line->purchasable_id, + ]); + } + + $options = ShippingManifest::getOptions($cart)->map(fn (ShippingOption $option) => new ShippingOption( + name: $option->name, + description: $option->description, + identifier: $option->identifier, + price: new PriceValue($option->price->value, $currency), + taxClass: $option->taxClass, + pickup: $option->pickup, + )); + + ShippingManifest::clearOptions(); + ShippingManifest::addOptions($options); + + $cart->update(['currency_id' => $currency->id]); + + return $cart->refresh(); + } + public static function session(Cart $cart): CheckoutSession { return app(CheckoutDriver::class)->createSession($cart); diff --git a/tests/Utils/CheckoutFirstProvidersTestCase.php b/tests/Utils/CheckoutFirstProvidersTestCase.php new file mode 100644 index 0000000..56b0b4b --- /dev/null +++ b/tests/Utils/CheckoutFirstProvidersTestCase.php @@ -0,0 +1,26 @@ + $provider !== CheckoutServiceProvider::class && $provider !== LunarServiceProvider::class)), + LunarServiceProvider::class, + ]; + } +} diff --git a/tests/Utils/FailingOrderCreationStep.php b/tests/Utils/FailingOrderCreationStep.php new file mode 100644 index 0000000..9db2577 --- /dev/null +++ b/tests/Utils/FailingOrderCreationStep.php @@ -0,0 +1,26 @@ +prepend(self::class); + } + + public function handle(Order $order, Closure $next): mixed + { + throw new RuntimeException(self::$message); + } +} diff --git a/tests/Utils/FakeIntents.php b/tests/Utils/FakeIntents.php new file mode 100644 index 0000000..bd06fd0 --- /dev/null +++ b/tests/Utils/FakeIntents.php @@ -0,0 +1,24 @@ + new PriceValue($value, $cart->currency); + + return new PaymentIntentSnapshot( + status: $status, + amount: $price($amount), + captured: $price($status === PaymentIntentStatus::Captured ? $amount : 0), + refunded: $price($refunded), + walletLabel: $walletLabel, + ); + } +} diff --git a/tests/Utils/WithoutIntentReconciliation.php b/tests/Utils/WithoutIntentReconciliation.php new file mode 100644 index 0000000..c86cd31 --- /dev/null +++ b/tests/Utils/WithoutIntentReconciliation.php @@ -0,0 +1,31 @@ +