Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Fix: Void offered on captured payments the gateway cannot void (#15057)

Damian Legawiecab0dec332d93
diff --git a/.changeset/payment-can-void-capture.md b/.changeset/payment-can-void-capture.md
new file mode 100644
index 0000000000..6da2fd0a85
--- /dev/null
+++ b/.changeset/payment-can-void-capture.md
@@ -0,0 +1,6 @@
+---
+"@spree/admin-sdk": patch
+"@spree/dashboard": patch
+---
+
+Admin API payments now return `can_void` and `can_capture`, which the payment method decides. The order page uses them to hide Void on captured payments that the gateway cannot void, such as Stripe. The dashboard no longer checks the payment status itself, so it needs a server that returns them.
diff --git a/packages/admin-sdk/src/types/generated/Payment.ts b/packages/admin-sdk/src/types/generated/Payment.ts
index 1bc2b08964..9924e4467c 100644
--- a/packages/admin-sdk/src/types/generated/Payment.ts
+++ b/packages/admin-sdk/src/types/generated/Payment.ts
@@ -1,4 +1,4 @@
-// Typelizer digest a4ec084724f06ebab5431522a77af81a
+// Typelizer digest 1c5b57a85ae48f7cce1377d061ea7562
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {CreditCard, StoreCredit, PaymentSource, PaymentMethod, CustomField, PaymentCaptureEvent, Order, Refund, PaymentSplit, PaymentStatus, PaymentSourceType} from '@/types'
@@ -26,6 +26,10 @@ interface Payment {
avs_risky: boolean;
/** Whether the card issuer reported that the security code did not match. */
cvv_risky: boolean;
+ /** Whether the payment can be voided now, as decided by its payment method. */
+ can_void: boolean;
+ /** Whether the payment can be captured now, as decided by its payment method. */
+ can_capture: boolean;
captured_amount: string;
order_id: string | null;
capture_events?: Array<PaymentCaptureEvent>;
diff --git a/packages/admin-sdk/src/zod/generated/Payment.ts b/packages/admin-sdk/src/zod/generated/Payment.ts
index 96ae0d2592..7b9a1ecb90 100644
--- a/packages/admin-sdk/src/zod/generated/Payment.ts
+++ b/packages/admin-sdk/src/zod/generated/Payment.ts
@@ -32,6 +32,8 @@ export const PaymentSchema = z.object({
updated_at: z.string(),
avs_risky: z.boolean(),
cvv_risky: z.boolean(),
+ can_void: z.boolean(),
+ can_capture: z.boolean(),
captured_amount: z.string(),
order_id: z.string().nullable(),
capture_events: z.array(PaymentCaptureEventSchema).optional(),
@@ -59,6 +61,8 @@ export const PaymentSchema = z.object({
updated_at: z.ZodType<Payment['updated_at']>;
avs_risky: z.ZodType<Payment['avs_risky']>;
cvv_risky: z.ZodType<Payment['cvv_risky']>;
+ can_void: z.ZodType<Payment['can_void']>;
+ can_capture: z.ZodType<Payment['can_capture']>;
captured_amount: z.ZodType<Payment['captured_amount']>;
order_id: z.ZodType<Payment['order_id']>;
capture_events: z.ZodOptional<z.ZodType<Exclude<Payment['capture_events'], undefined>>>;
diff --git a/packages/dashboard/e2e/orders.spec.ts b/packages/dashboard/e2e/orders.spec.ts
index 252dda3751..ec4e69bc0d 100644
--- a/packages/dashboard/e2e/orders.spec.ts
+++ b/packages/dashboard/e2e/orders.spec.ts
@@ -576,4 +576,58 @@ test.describe('order payments', () => {
await expect(dialog.getByText('CVV does not match')).toBeVisible()
await expect(dialog.getByRole('row').filter({ hasText: '€10.00' })).toBeVisible()
})
+
+ test('offers Void on a payment the gateway can void', async ({ page }) => {
+ const creds = await login(page)
+ const orders = await adminRequest<{ data: { id: string }[] }>(
+ page,
+ { ...creds, store_id: creds.comma_store_id },
+ 'get',
+ `/orders?q[email_eq]=${encodeURIComponent(FIXTURE_BOGUS_ORDER_EMAIL)}`,
+ )
+ await page.goto(`/${creds.comma_store_id}/orders/${orders.data[0].id}`)
+
+ await page
+ .locator('tr')
+ .filter({ hasText: FIXTURE_BOGUS_GATEWAY })
+ .getByRole('button', { name: /^actions$/i })
+ .click({ timeout: 15_000 })
+
+ await expect(page.getByRole('menuitem', { name: 'Void' })).toBeVisible()
+ })
+
+ test('hides Void when the gateway cannot void the payment', async ({ page }) => {
+ const creds = await login(page)
+ const orders = await adminRequest<{ data: { id: string }[] }>(
+ page,
+ { ...creds, store_id: creds.comma_store_id },
+ 'get',
+ `/orders?q[email_eq]=${encodeURIComponent(FIXTURE_BOGUS_ORDER_EMAIL)}`,
+ )
+ const orderId = orders.data[0].id
+
+ // The fixture gateway can void, so the order payload reports a gateway
+ // that cannot (as Stripe does for a captured payment).
+ await page.route(`**/api/v3/admin/orders/${orderId}**`, async (route) => {
+ const url = new URL(route.request().url())
+ if (route.request().method() !== 'GET' || !url.pathname.endsWith(`/orders/${orderId}`)) {
+ return route.fallback()
+ }
+ const response = await route.fetch()
+ const order = await response.json()
+ order.payments = order.payments.map((payment: object) => ({ ...payment, can_void: false }))
+ await route.fulfill({ response, json: order })
+ })
+
+ await page.goto(`/${creds.comma_store_id}/orders/${orderId}`)
+
+ await page
+ .locator('tr')
+ .filter({ hasText: FIXTURE_BOGUS_GATEWAY })
+ .getByRole('button', { name: /^actions$/i })
+ .click({ timeout: 15_000 })
+
+ await expect(page.getByRole('menuitem', { name: 'View details' })).toBeVisible()
+ await expect(page.getByRole('menuitem', { name: 'Void' })).toHaveCount(0)
+ })
})
diff --git a/packages/dashboard/src/components/spree/orders/order-payments-card.tsx b/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
index 2d5e835ee8..11ec7cd08d 100644
--- a/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
+++ b/packages/dashboard/src/components/spree/orders/order-payments-card.tsx
@@ -194,15 +194,8 @@ export function PaymentsCard({ order }: { order: Order }) {
currency={order.currency}
// Capturing or voiding a grouped payment acts on every
// order in the checkout, so this page only links out.
- canCapture={
- !grouped && (payment.status === 'checkout' || payment.status === 'pending')
- }
- canVoid={
- !grouped &&
- (payment.status === 'checkout' ||
- payment.status === 'pending' ||
- payment.status === 'completed')
- }
+ canCapture={!grouped && payment.can_capture}
+ canVoid={!grouped && payment.can_void}
onCapture={async () => {
if (
await confirm({
diff --git a/spree/api/app/serializers/spree/api/v3/admin/payment_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/payment_serializer.rb
index 148decb201..5f3b4d02f5 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/payment_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/payment_serializer.rb
@@ -16,7 +16,9 @@ module Spree
cvv_response_message: [:string, nullable: true],
gateway_dashboard_payment_url: [:string, nullable: true],
avs_risky: [:boolean, comment: 'Whether the card issuer reported that the billing address did not match.'],
- cvv_risky: [:boolean, comment: 'Whether the card issuer reported that the security code did not match.']
+ cvv_risky: [:boolean, comment: 'Whether the card issuer reported that the security code did not match.'],
+ can_void: [:boolean, comment: 'Whether the payment can be voided now, as decided by its payment method.'],
+ can_capture: [:boolean, comment: 'Whether the payment can be captured now, as decided by its payment method.']
attributes :metadata, :avs_response, :cvv_response_code, :cvv_response_message,
:gateway_dashboard_payment_url,
@@ -24,6 +26,8 @@ module Spree
attribute(:avs_risky, &:is_avs_risky?)
attribute(:cvv_risky, &:is_cvv_risky?)
+ attribute(:can_void, &:can_void?)
+ attribute(:can_capture, &:can_capture?)
money_attributes :captured_amount
typelize captured_amount: [:string, nullable: false]
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
index 5b3dc2d2f8..16ba7c82cc 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/payments_controller_spec.rb
@@ -63,6 +63,26 @@ RSpec.describe Spree::Api::V3::Admin::Orders::PaymentsController, type: :control
expect(json_response).to include('avs_risky' => false, 'cvv_risky' => true)
end
+ it 'reports whether the payment method allows voiding and capturing' do
+ allow_any_instance_of(Spree::PaymentMethod).to receive(:can_void?).and_return(false)
+ allow_any_instance_of(Spree::PaymentMethod).to receive(:can_capture?).and_return(false)
+ payment.update_columns(status: 'checkout')
+
+ get :show, params: { order_id: order_with_payment.prefixed_id, id: payment.prefixed_id }, as: :json
+
+ expect(json_response).to include('can_void' => false, 'can_capture' => false)
+ end
+
+ it 'reports true when the payment method allows voiding and capturing' do
+ allow_any_instance_of(Spree::PaymentMethod).to receive(:can_void?).and_return(true)
+ allow_any_instance_of(Spree::PaymentMethod).to receive(:can_capture?).and_return(true)
+ payment.update_columns(status: 'checkout')
+
+ get :show, params: { order_id: order_with_payment.prefixed_id, id: payment.prefixed_id }, as: :json
+
+ expect(json_response).to include('can_void' => true, 'can_capture' => true)
+ end
+
it 'returns 404 for unknown payment id' do
get :show, params: { order_id: order_with_payment.prefixed_id, id: 'pay_unknown' }, as: :json
diff --git a/spree/core/app/models/spree/payment.rb b/spree/core/app/models/spree/payment.rb
index dbb466cd04..208b54ae5e 100644
--- a/spree/core/app/models/spree/payment.rb
+++ b/spree/core/app/models/spree/payment.rb
@@ -27,6 +27,11 @@ module Spree
INVALID_STATES = INVALID_STATUSES
deprecate_constant :INVALID_STATES
+ # Statuses a payment can be voided / captured from, before the payment
+ # method is consulted. Extend them to support gateways with other flows.
+ VOIDABLE_STATUSES = %w[pending processing completed checkout].freeze
+ CAPTURABLE_STATUSES = %w[checkout pending].freeze
+
with_options inverse_of: :payments do
belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
belongs_to :cart, class_name: 'Spree::Cart', optional: true
@@ -219,8 +224,18 @@ module Spree
status.in?(%w[checkout processing])
end
+ # Whether the payment is in a status that can be voided and its payment
+ # method agrees. A gateway that cannot void a capture returns false from
+ # +can_void?(payment)+ for completed payments.
def can_void?
- status.in?(%w[pending processing completed checkout])
+ status.in?(VOIDABLE_STATUSES) &&
+ (!payment_method.respond_to?(:can_void?) || payment_method.can_void?(self))
+ end
+
+ # Whether the payment can be captured from the back office.
+ def can_capture?
+ status.in?(CAPTURABLE_STATUSES) &&
+ (!payment_method.respond_to?(:can_capture?) || payment_method.can_capture?(self))
end
# @deprecated read +status+ — removed in 6.1
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 7ee74537e5..a8147fe517 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -309,6 +309,19 @@ module Spree
raise ::NotImplementedError, 'You must implement cancel method for this payment method.'
end
+ # Whether the payment can be voided in its current state. Gateways that
+ # cannot void a captured payment override this.
+ # @param _payment [Spree::Payment]
+ def can_void?(_payment)
+ true
+ end
+
+ # Whether the payment can be captured in its current state.
+ # @param _payment [Spree::Payment]
+ def can_capture?(_payment)
+ true
+ end
+
def store_credit?
self.class == Spree::PaymentMethod::StoreCredit
end
diff --git a/spree/core/app/models/spree/payment_method/store_credit.rb b/spree/core/app/models/spree/payment_method/store_credit.rb
index 11e5d88f65..83943b932d 100644
--- a/spree/core/app/models/spree/payment_method/store_credit.rb
+++ b/spree/core/app/models/spree/payment_method/store_credit.rb
@@ -18,8 +18,10 @@ module Spree
['checkout', 'pending'].include?(payment.status)
end
+ # Mirrors Spree::StoreCredit#can_void?: a checkout payment can still be
+ # voided while its order is incomplete.
def can_void?(payment)
- payment.pending?
+ payment.pending? || (payment.checkout? && !payment.order&.completed?)
end
def authorize(money, store_credit, gateway_options = {})
diff --git a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb b/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
index 405ca80b23..9d7f2f1875 100644
--- a/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
+++ b/spree/core/spec/models/spree/payment_method/store_credit_spec.rb
@@ -332,4 +332,34 @@ describe Spree::PaymentMethod::StoreCredit do
it { expect(store_credit_payment_method.payment_source_class).to eq(Spree::StoreCredit) }
end
+
+ describe '#can_void?' do
+ let(:store_credit_payment_method) { create(:store_credit_payment_method) }
+
+ it 'allows a pending payment' do
+ expect(store_credit_payment_method.can_void?(build_stubbed(:payment, status: 'pending'))).to be true
+ end
+
+ it 'allows a checkout payment while the order is incomplete' do
+ payment = build_stubbed(:payment, status: 'checkout', order: build_stubbed(:order, completed_at: nil))
+
+ expect(store_credit_payment_method.can_void?(payment)).to be true
+ end
+
+ it 'allows a checkout payment held by a cart, with no order' do
+ payment = build_stubbed(:payment, status: 'checkout', order: nil, cart: build_stubbed(:cart))
+
+ expect(store_credit_payment_method.can_void?(payment)).to be true
+ end
+
+ it 'refuses a checkout payment once the order is complete' do
+ payment = build_stubbed(:payment, status: 'checkout', order: build_stubbed(:order, completed_at: Time.current))
+
+ expect(store_credit_payment_method.can_void?(payment)).to be false
+ end
+
+ it 'refuses a completed payment' do
+ expect(store_credit_payment_method.can_void?(build_stubbed(:payment, status: 'completed'))).to be false
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/payment_spec.rb b/spree/core/spec/models/spree/payment_spec.rb
index a9684fb5ca..e67414b11d 100644
--- a/spree/core/spec/models/spree/payment_spec.rb
+++ b/spree/core/spec/models/spree/payment_spec.rb
@@ -690,6 +690,41 @@ describe Spree::Payment, type: :model do
end
end
+ describe '#can_void?' do
+ let(:payment) { build_stubbed(:payment, status: 'completed') }
+
+ it 'is true for a completed payment by default' do
+ expect(payment.can_void?).to be true
+ end
+
+ it 'is false when the payment method cannot void the payment' do
+ allow(payment.payment_method).to receive(:can_void?).with(payment).and_return(false)
+
+ expect(payment.can_void?).to be false
+ end
+
+ it 'is false for a failed payment whatever the payment method says' do
+ payment.status = 'failed'
+
+ expect(payment.can_void?).to be false
+ end
+ end
+
+ describe '#can_capture?' do
+ it 'is true for a checkout or pending payment and false for a completed one' do
+ expect(build_stubbed(:payment, status: 'checkout').can_capture?).to be true
+ expect(build_stubbed(:payment, status: 'pending').can_capture?).to be true
+ expect(build_stubbed(:payment, status: 'completed').can_capture?).to be false
+ end
+
+ it 'is false when the payment method refuses' do
+ payment = build_stubbed(:payment, status: 'pending')
+ allow(payment.payment_method).to receive(:can_capture?).with(payment).and_return(false)
+
+ expect(payment.can_capture?).to be false
+ end
+ end
+
describe '#credit_allowed' do
# Regression test for #4403 & #4407
it 'is the difference between offsets total and payment amount' do
diff --git a/spree/core/spec/workflows/spree/payments/void_spec.rb b/spree/core/spec/workflows/spree/payments/void_spec.rb
index fcde2e671a..7d8935de0f 100644
--- a/spree/core/spec/workflows/spree/payments/void_spec.rb
+++ b/spree/core/spec/workflows/spree/payments/void_spec.rb
@@ -63,6 +63,17 @@ RSpec.describe Spree::Payments::Void do
expect(result.error.value).to eq(:payment_not_voidable)
end
+ it 'fails without calling the gateway when the payment method cannot void the payment' do
+ allow(gateway).to receive(:can_void?).with(payment).and_return(false)
+ expect(gateway).not_to receive(:void)
+
+ result = described_class.call(payment: payment)
+
+ expect(result).to be_failure
+ expect(result.error.value).to eq(:payment_not_voidable)
+ expect(payment.reload).to be_pending
+ end
+
it 'surfaces a gateway failure as a failure result and does not void' do
allow(gateway).to receive(:void).and_return(failed_response)
diff --git a/spree/providers/stripe/app/models/spree_stripe/gateway.rb b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
index c867cbf85c..c0cbf048f6 100644
--- a/spree/providers/stripe/app/models/spree_stripe/gateway.rb
+++ b/spree/providers/stripe/app/models/spree_stripe/gateway.rb
@@ -130,6 +130,12 @@ module SpreeStripe
end
end
+ # Voiding cancels the PaymentIntent, which Stripe refuses once it has
+ # succeeded; a captured payment has to be refunded instead.
+ def can_void?(payment)
+ !payment.completed?
+ end
+
def void(response_code, _source, _gateway_options)
return failure('Response code is blank') if response_code.blank?
diff --git a/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb b/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb
index 1ce2f5dda1..552667e390 100644
--- a/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb
+++ b/spree/providers/stripe/spec/models/spree_stripe/gateway_spec.rb
@@ -5,6 +5,16 @@ RSpec.describe SpreeStripe::Gateway do
let(:gateway) { create(:stripe_gateway, store: store) }
let(:amount) { 100 }
+ describe '#can_void?' do
+ it 'is false for a completed payment, which Stripe cannot cancel' do
+ expect(gateway.can_void?(build_stubbed(:payment, status: 'completed'))).to be false
+ end
+
+ it 'is true for an authorized payment' do
+ expect(gateway.can_void?(build_stubbed(:payment, status: 'pending'))).to be true
+ end
+ end
+
describe '#payment_intent_accepted?' do
subject { gateway.payment_intent_accepted?(stripe_payment_intent) }