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.

Retire the state machine on GiftCard and rename its state column

Damian Legawiec308db0c68825
diff --git a/docs/api-reference/admin.yaml b/docs/api-reference/admin.yaml
index b348314cdf..f4b8807142 100644
--- a/docs/api-reference/admin.yaml
+++ b/docs/api-reference/admin.yaml
@@ -8891,7 +8891,7 @@ paths:
description: |-
Returns the gift cards issued by the current store. Filter by
`q[code_cont]` for code search, `q[user_id_eq]` for cards issued
- to a specific customer, or `q[state_eq]` for status filtering.
+ to a specific customer, or `q[status_eq]` for status filtering.
**Required scope:** `read_gift_cards` (for API-key authentication).
@@ -8944,7 +8944,7 @@ paths:
description: Filter by gift card code (contains)
schema:
type: string
- - name: q[state_eq]
+ - name: q[status_eq]
in: query
required: false
description: Filter by status (active, redeemed, partially_redeemed, canceled)
diff --git a/packages/admin-sdk/tests/gift-cards.test.ts b/packages/admin-sdk/tests/gift-cards.test.ts
index e3625cbbc6..25431c247e 100644
--- a/packages/admin-sdk/tests/gift-cards.test.ts
+++ b/packages/admin-sdk/tests/gift-cards.test.ts
@@ -10,7 +10,7 @@ const sampleGiftCard = {
amount_used: '0.0',
amount_remaining: '100.0',
currency: 'USD',
- state: 'active',
+ status: 'active',
expires_at: null,
created_at: '2026-05-01T00:00:00Z',
updated_at: '2026-05-01T00:00:00Z',
@@ -48,9 +48,9 @@ describe('giftCards', () => {
}),
)
- await createTestClient().giftCards.list({ state_eq: 'active', code_cont: 'ABCD' })
+ await createTestClient().giftCards.list({ status_eq: 'active', code_cont: 'ABCD' })
- expect(url!.searchParams.get('q[state_eq]')).toBe('active')
+ expect(url!.searchParams.get('q[status_eq]')).toBe('active')
expect(url!.searchParams.get('q[code_cont]')).toBe('ABCD')
})
})
diff --git a/packages/dashboard/src/tables/gift-cards.tsx b/packages/dashboard/src/tables/gift-cards.tsx
index d082d011b4..632088635d 100644
--- a/packages/dashboard/src/tables/gift-cards.tsx
+++ b/packages/dashboard/src/tables/gift-cards.tsx
@@ -7,9 +7,9 @@ import { adminUserAutocompleteProps } from '../hooks/use-admin-users'
import { customerAutocompleteProps } from '../hooks/use-customers'
import { giftCardBatchAutocompleteProps } from '../hooks/use-gift-cards'
-// Server `Spree::GiftCard#display_state` exposes "expired" when the card
+// Server `Spree::GiftCard#display_status` exposes "expired" when the card
// is past its expiration date, even though the underlying column is still
-// "active" — keep this list in sync with the state machine + display_state
+// "active" — keep this list in sync with the statuses + display_status
// override in `app/models/spree/gift_card.rb`.
const STATUS_OPTIONS = [
{ value: 'active', label: i18n.t('admin.fields.active.label') },
@@ -61,10 +61,10 @@ defineTable<GiftCard>('gift-cards', {
{
key: 'status',
label: i18n.t('admin.fields.status.label'),
- // Ransack filters off the underlying `state` column — `display_state`
+ // Ransack filters off the underlying `status` column — `display_status`
// is a presentation-only override that returns 'expired' for active
- // cards past their `expires_at`. Server still indexes `state`.
- ransackAttribute: 'state',
+ // cards past their `expires_at`. Server still indexes `status`.
+ ransackAttribute: 'status',
filterable: true,
filterType: 'enum',
// Spread to narrow the readonly type into ColumnDef's mutable shape.
@@ -137,7 +137,7 @@ defineTable<GiftCard>('gift-cards', {
{
key: 'created_by',
label: i18n.t('admin.gift_cards.columns.issued_by'),
- // GiftCard whitelists `code`, `user_id`, `state`, `gift_card_batch_id`.
+ // GiftCard whitelists `code`, `user_id`, `status`, `gift_card_batch_id`.
// `created_by_id` is not whitelisted yet — Ransack will reject the
// predicate without it; we add it server-side alongside this column.
ransackAttribute: 'created_by_id',
diff --git a/spree/api/app/serializers/spree/api/v3/gift_card_serializer.rb b/spree/api/app/serializers/spree/api/v3/gift_card_serializer.rb
index e12223163c..5d2789df4b 100644
--- a/spree/api/app/serializers/spree/api/v3/gift_card_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/gift_card_serializer.rb
@@ -22,7 +22,7 @@ module Spree
end
attribute :status do |gift_card|
- gift_card.display_state
+ gift_card.display_status
end
attributes :currency
diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
index 5463efd581..7a05da1e40 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/carts/gift_card_controller_spec.rb
@@ -46,7 +46,7 @@ RSpec.describe Spree::Api::V3::Store::Carts::GiftCardsController, type: :control
end
it 'returns error for redeemed gift card' do
- gift_card.update!(state: :redeemed, redeemed_at: Time.current, amount_used: gift_card.amount)
+ gift_card.update!(status: :redeemed, redeemed_at: Time.current, amount_used: gift_card.amount)
post :create, params: { cart_id: order.prefixed_id, code: 'giftcard123' }
diff --git a/spree/api/spec/controllers/spree/api/v3/store/customer/gift_cards_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/customer/gift_cards_controller_spec.rb
index 254faa7643..673e9530c5 100644
--- a/spree/api/spec/controllers/spree/api/v3/store/customer/gift_cards_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/customer/gift_cards_controller_spec.rb
@@ -104,7 +104,7 @@ RSpec.describe Spree::Api::V3::Store::Customer::GiftCardsController, type: :cont
end
context 'with partially redeemed gift card' do
- let!(:partial_card) { create(:gift_card, customer: user, store: store, state: :partially_redeemed, amount: 50, amount_used: 20) }
+ let!(:partial_card) { create(:gift_card, customer: user, store: store, status: :partially_redeemed, amount: 50, amount_used: 20) }
it 'shows correct state and amounts' do
get :index
diff --git a/spree/api/spec/integration/spree/api/v3/admin/gift_cards_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/gift_cards_spec.rb
index d9dd7c78e7..6e6dcde885 100644
--- a/spree/api/spec/integration/spree/api/v3/admin/gift_cards_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/admin/gift_cards_spec.rb
@@ -17,7 +17,7 @@ RSpec.describe 'Admin Gift Cards API', type: :request, swagger_doc: 'api-referen
description <<~DESC
Returns the gift cards issued by the current store. Filter by
`q[code_cont]` for code search, `q[user_id_eq]` for cards issued
- to a specific customer, or `q[state_eq]` for status filtering.
+ to a specific customer, or `q[status_eq]` for status filtering.
DESC
admin_scope :read, :gift_cards
@@ -30,7 +30,7 @@ RSpec.describe 'Admin Gift Cards API', type: :request, swagger_doc: 'api-referen
parameter name: :limit, in: :query, type: :integer, required: false, description: 'Number of records per page'
parameter name: :'q[code_cont]', in: :query, type: :string, required: false,
description: 'Filter by gift card code (contains)'
- parameter name: :'q[state_eq]', in: :query, type: :string, required: false,
+ parameter name: :'q[status_eq]', in: :query, type: :string, required: false,
description: 'Filter by status (active, redeemed, partially_redeemed, canceled)'
parameter name: :sort, in: :query, type: :string, required: false,
description: 'Sort by field. Prefix with `-` for descending (e.g., `-created_at`).'
diff --git a/spree/api/spec/integration/spree/api/v3/store/gift_card_cart_spec.rb b/spree/api/spec/integration/spree/api/v3/store/gift_card_cart_spec.rb
index 782d152335..05d464851a 100644
--- a/spree/api/spec/integration/spree/api/v3/store/gift_card_cart_spec.rb
+++ b/spree/api/spec/integration/spree/api/v3/store/gift_card_cart_spec.rb
@@ -83,7 +83,7 @@ RSpec.describe 'Cart Gift Card API', type: :request, swagger_doc: 'api-reference
end
response '422', 'gift card already redeemed' do
- let!(:gift_card) { create(:gift_card, store: store, amount: 50, code: 'redeemedgc', amount_used: 50, state: :redeemed, redeemed_at: Time.current) }
+ let!(:gift_card) { create(:gift_card, store: store, amount: 50, code: 'redeemedgc', amount_used: 50, status: :redeemed, redeemed_at: Time.current) }
let(:'x-spree-api-key') { api_key.token }
let(:'Authorization') { "Bearer #{jwt_token}" }
let(:body) { { code: 'redeemedgc' } }
diff --git a/spree/api/spec/serializers/spree/api/v3/gift_card_serializer_spec.rb b/spree/api/spec/serializers/spree/api/v3/gift_card_serializer_spec.rb
index 8560fd0448..5f065be8b4 100644
--- a/spree/api/spec/serializers/spree/api/v3/gift_card_serializer_spec.rb
+++ b/spree/api/spec/serializers/spree/api/v3/gift_card_serializer_spec.rb
@@ -91,7 +91,7 @@ RSpec.describe Spree::Api::V3::GiftCardSerializer do
end
context 'with partially redeemed gift card' do
- let(:gift_card) { create(:gift_card, store: store, state: :partially_redeemed, amount: 100, amount_used: 40) }
+ let(:gift_card) { create(:gift_card, store: store, status: :partially_redeemed, amount: 100, amount_used: 40) }
it 'returns partially_redeemed status' do
expect(subject['status']).to eq('partially_redeemed')
diff --git a/spree/core/app/models/concerns/spree/purchase/gift_cards.rb b/spree/core/app/models/concerns/spree/purchase/gift_cards.rb
index 6dc1b6ad88..0a1f344adb 100644
--- a/spree/core/app/models/concerns/spree/purchase/gift_cards.rb
+++ b/spree/core/app/models/concerns/spree/purchase/gift_cards.rb
@@ -27,17 +27,17 @@ module Spree
# @param gift_card [Spree::GiftCard]
def apply_gift_card(gift_card)
- Spree.gift_card_apply_service.call(gift_card: gift_card, order: self)
+ Spree.gift_card_apply_workflow.call(gift_card: gift_card, order: self)
end
def remove_gift_card
- Spree.gift_card_remove_service.call(order: self)
+ Spree.gift_card_remove_workflow.call(order: self)
end
def redeem_gift_card
return unless gift_card.present?
- Spree.gift_card_redeem_service.call(gift_card: gift_card)
+ Spree.gift_card_redeem_workflow.call(gift_card: gift_card)
end
# In-lock read-compute-write keeping the gift-card payment amount in
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index abc619ac57..ac765ab468 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -10,26 +10,15 @@ module Spree
publishes_lifecycle_events
#
- # State machine
+ # Status
#
- state_machine :state, initial: :active do
- event :cancel do
- transition active: :canceled
- end
-
- event :redeem do
- transition active: :redeemed
- transition partially_redeemed: :redeemed
- end
- after_transition to: :redeemed, do: :after_redeem
- after_transition to: :redeemed, do: :publish_gift_card_redeemed_event
-
- event :partial_redeem do
- transition active: :partially_redeemed
- transition partially_redeemed: :partially_redeemed
- end
- after_transition to: :partially_redeemed, do: :publish_gift_card_partially_redeemed_event
- end
+ # No state machine — redemption and cancellation run through the
+ # Spree::GiftCards workflows (docs/plans/6.0-service-workflows.md).
+ # +active?+ is defined below rather than generated: a card past its expiry
+ # date still holds the `active` status but is not usable, and every caller
+ # asking "is this card active" means the latter.
+ include Spree::HasStatus
+ has_status :active, :partially_redeemed, :redeemed, :canceled, default: :active
#
# Validations
@@ -55,15 +44,19 @@ module Spree
#
# Scopes
#
- scope :active, -> { where(state: [:active, :partially_redeemed]).where(expires_at: [nil, Date.tomorrow..]) }
- scope :expired, -> { where(state: :active).where(expires_at: ..Date.current) }
- scope :redeemed, -> { where(state: [:redeemed]) }
- scope :partially_redeemed, -> { where(state: [:partially_redeemed]) }
+ # These deliberately override the plain status scopes has_status generates:
+ # usability is status *and* expiry, and a partially redeemed card is still
+ # spendable.
+ scope :active, -> { where(status: [:active, :partially_redeemed]).where(expires_at: [nil, Date.tomorrow..]) }
+ scope :expired, -> { where(status: :active).where(expires_at: ..Date.current) }
+ scope :redeemed, -> { where(status: [:redeemed]) }
+ scope :partially_redeemed, -> { where(status: [:partially_redeemed]) }
#
# Ransack
#
- self.whitelisted_ransackable_attributes = %w[code customer_id user_id state gift_card_batch_id created_by_id]
+ ransack_alias :state, :status # @deprecated filter alias — removed in 6.1
+ self.whitelisted_ransackable_attributes = %w[code customer_id user_id status state gift_card_batch_id created_by_id]
self.whitelisted_ransackable_associations = %w[users orders batch]
self.whitelisted_ransackable_scopes = %w[active expired redeemed partially_redeemed]
@@ -127,25 +120,73 @@ module Spree
# Checks if the gift card is active, i.e. not expired and not redeemed
# @return [Boolean]
def active?
- super && !expired?
+ status == 'active' && !expired?
end
- # Displays state as expired if the gift card is expired, otherwise displays the state
+ # Displays status as expired if the gift card is expired, otherwise the
+ # stored status. Expiry is derived from a date rather than stored, so it
+ # never appears in the column.
# @return [String]
- def display_state
+ def display_status
if expired?
:expired
else
- state
+ status
end.to_s
end
+ # @deprecated use +display_status+ — removed in 6.1
+ def display_state
+ Spree::Deprecation.warn('Spree::GiftCard#display_state is deprecated and will be removed in Spree 6.1. Use #display_status instead.')
+ display_status
+ end
+
+ # @deprecated read +status+ — removed in 6.1
+ def state
+ Spree::Deprecation.warn('Spree::GiftCard#state is deprecated and will be removed in Spree 6.1. Use #status instead.')
+ status
+ end
+
+ # @deprecated write +status+ — removed in 6.1
+ def state=(value)
+ Spree::Deprecation.warn('Spree::GiftCard#state= is deprecated and will be removed in Spree 6.1. Use #status= instead.')
+ self.status = value
+ end
+
+ # @deprecated Call Spree.gift_card_redeem_workflow — removed in 6.1.
+ # The workflow decides full versus partial redemption from the balance,
+ # so both old verbs land on it.
+ def redeem!
+ Spree::Deprecation.warn('Spree::GiftCard#redeem! is deprecated and will be removed in Spree 6.1. Call Spree.gift_card_redeem_workflow instead.')
+ run_gift_card_workflow(Spree.gift_card_redeem_workflow)
+ end
+ alias partial_redeem! redeem!
+
+ # @deprecated Call Spree.gift_card_cancel_workflow — removed in 6.1.
+ def cancel!
+ Spree::Deprecation.warn('Spree::GiftCard#cancel! is deprecated and will be removed in Spree 6.1. Call Spree.gift_card_cancel_workflow instead.')
+ run_gift_card_workflow(Spree.gift_card_cancel_workflow)
+ end
+
def to_csv(_store = nil)
Spree::CSV::GiftCardPresenter.new(self).call
end
private
+ # Mirrors the machine's bang events: an illegal move raised, so a rejected
+ # workflow raises here too rather than returning quietly.
+ def run_gift_card_workflow(workflow)
+ result = workflow.call(gift_card: self)
+
+ if result.failure?
+ errors.add(:base, result.error.value.to_s)
+ raise ActiveRecord::RecordInvalid, self
+ end
+
+ true
+ end
+
def generate_code
return if code.present?
@@ -159,18 +200,6 @@ module Spree
self.code = code.downcase if code.present?
end
- def after_redeem
- update!(redeemed_at: Time.current)
- end
-
- def publish_gift_card_redeemed_event
- publish_event('gift_card.redeemed')
- end
-
- def publish_gift_card_partially_redeemed_event
- publish_event('gift_card.partially_redeemed')
- end
-
def ensure_can_be_deleted
return if can_be_deleted?
diff --git a/spree/core/app/models/spree/gift_card_batch.rb b/spree/core/app/models/spree/gift_card_batch.rb
index 4ba34d6a9e..50371263fc 100644
--- a/spree/core/app/models/spree/gift_card_batch.rb
+++ b/spree/core/app/models/spree/gift_card_batch.rb
@@ -71,7 +71,7 @@ module Spree
def gift_card_hash
{
- state: :active,
+ status: :active,
gift_card_batch_id: id,
amount: amount,
currency: currency,
diff --git a/spree/core/app/models/spree/promotion_handler/coupon.rb b/spree/core/app/models/spree/promotion_handler/coupon.rb
index 817b58da3a..8e35167406 100644
--- a/spree/core/app/models/spree/promotion_handler/coupon.rb
+++ b/spree/core/app/models/spree/promotion_handler/coupon.rb
@@ -29,7 +29,7 @@ module Spree
if result.success?
set_success_code(:gift_card_applied)
else
- set_error_code(result.value, result.error.value || {})
+ set_error_code(result.error.value)
end
return self
diff --git a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
index 49cc0b3dbc..63cf1bf196 100644
--- a/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
+++ b/spree/core/app/presenters/spree/csv/gift_card_presenter.rb
@@ -31,7 +31,7 @@ module Spree
gift_card.display_amount_used,
gift_card.display_amount_remaining,
gift_card.currency,
- gift_card.display_state,
+ gift_card.display_status,
gift_card.expires_at&.strftime('%Y-%m-%d'),
gift_card.customer&.email,
gift_card.customer&.first_name,
diff --git a/spree/core/app/services/spree/gift_cards/apply.rb b/spree/core/app/services/spree/gift_cards/apply.rb
deleted file mode 100644
index 11fa5ed134..0000000000
--- a/spree/core/app/services/spree/gift_cards/apply.rb
+++ /dev/null
@@ -1,78 +0,0 @@
-# frozen_string_literal: true
-
-# Applies a gift card to an order
-# under the hood it creates a store credit payment record and updates the gift card amount used
-# @param gift_card [Spree::GiftCard] the gift card to apply
-# @param order [Spree::Order] the order to apply the gift card to
-# @return [Spree::Order] the order with the gift card applied
-module Spree
- module GiftCards
- class Apply
- prepend Spree::ServiceModule::Base
-
- def call(gift_card:, order:)
- # we shouldn't mix an order with a gift card and a store credit
- return failure(:gift_card_using_store_credit_error) if order.using_store_credit?
-
- # we shouldn't allow a gift card to be applied to an order with a different currency
- return failure(:gift_card_mismatched_currency) if gift_card.currency != order.currency
-
- # gift card requires logged user
- if gift_card.customer.present?
- # user must be logged in
- return failure(:gift_card_customer_not_logged_in) if order.customer.blank?
- # user must be the same as the gift card user
- return failure(:gift_card_mismatched_customer) if gift_card.customer != order.customer
- end
-
- store = order.store
-
- payment_method = ensure_store_credit_payment_method!(store)
-
- order.with_lock do
- gift_card.lock!
- amount = [gift_card.amount_remaining, order.total].min
-
- return failure(:gift_card_no_amount_remaining) unless amount.positive? || order.total.zero?
-
- store_credit = gift_card.store_credits.create!(
- store: store,
- customer: order.customer,
- amount: amount,
- currency: order.currency,
- originator: gift_card,
- action_originator: gift_card
- )
- gift_card.amount_used += amount
- gift_card.save!
-
- order.update!(gift_card: gift_card)
- order.payments.create!(
- source: store_credit,
- payment_method: payment_method,
- amount: amount,
- state: 'checkout',
- response_code: store_credit.generate_authorization_code
- )
- order.recalculate_totals!
- end
-
- success(order.reload)
- end
-
- private
-
- def ensure_store_credit_payment_method!(store)
- payment_method = store.payment_methods.find_or_initialize_by(
- type: 'Spree::PaymentMethod::StoreCredit'
- )
- payment_method.name ||= Spree.t(:store_credit_name)
- payment_method.active = true
-
- payment_method.save! if payment_method.new_record?
-
- payment_method
- end
- end
- end
-end
diff --git a/spree/core/app/services/spree/gift_cards/redeem.rb b/spree/core/app/services/spree/gift_cards/redeem.rb
deleted file mode 100644
index 27c795383b..0000000000
--- a/spree/core/app/services/spree/gift_cards/redeem.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-module Spree
- module GiftCards
- class Redeem
- prepend Spree::ServiceModule::Base
-
- def call(gift_card:)
- if gift_card.amount_remaining.zero?
- gift_card.redeem!
- else
- gift_card.partial_redeem!
- end
-
- success(gift_card)
- end
- end
- end
-end
diff --git a/spree/core/app/services/spree/gift_cards/remove.rb b/spree/core/app/services/spree/gift_cards/remove.rb
deleted file mode 100644
index 66114e50a2..0000000000
--- a/spree/core/app/services/spree/gift_cards/remove.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-module Spree
- module GiftCards
- class Remove
- prepend Spree::ServiceModule::Base
-
- def call(order:)
- return failure(:remove_gift_card_on_completed_order_error) if order.completed?
- return success(true) if order.gift_card.nil?
-
- gift_card = order.gift_card
-
- return failure(:gift_card_not_found) if gift_card.nil?
-
- order.with_lock do
- payments = order.payments.checkout.store_credits.where(source: gift_card.store_credits)
- payment_total = payments.sum(:amount)
- payments.each(&:invalidate!)
-
- gift_card.with_lock do
- gift_card.amount_used -= payment_total
- gift_card.save!
- end
-
- # we need to destroy the store credits here because they are not associated with the order
- # and we need to remove them from the gift card
- # TODO: rather than destroying the store credits, we should void them
- payments.each do |payment|
- payment.source.destroy!
- end
-
- order.update!(gift_card: nil)
- order.recalculate_totals!
- end
-
- success(true)
- end
- end
- end
-end
diff --git a/spree/core/app/workflows/spree/gift_cards/apply.rb b/spree/core/app/workflows/spree/gift_cards/apply.rb
new file mode 100644
index 0000000000..de7828cc71
--- /dev/null
+++ b/spree/core/app/workflows/spree/gift_cards/apply.rb
@@ -0,0 +1,113 @@
+module Spree
+ module GiftCards
+ # Puts a gift card's balance onto an order. The card is not spent here —
+ # it is drawn against: a store credit is issued for whatever the card can
+ # cover, a payment is created from it, and the card's used amount rises to
+ # match. Spree::GiftCards::Redeem records the outcome once the order is
+ # placed.
+ #
+ # A workflow rather than a service because the eligibility rules are the
+ # kind a store overrides — who may spend a card, on what, and up to how
+ # much — and because it writes several records that must stand or fall
+ # together.
+ class Apply < Spree::Workflow
+ hooks :validate, :after_apply
+
+ attr_reader :store_credit, :payment
+
+ # @param gift_card [Spree::GiftCard]
+ # @param order [Spree::Order]
+ # @return [Spree::ServiceModule::Result] value is the reloaded order
+ def perform(gift_card:, order:)
+ super
+
+ step :ensure_applicable
+ run_hooks :validate
+
+ order.with_lock do
+ step :lock_gift_card
+ step :ensure_amount_available
+ step :issue_store_credit
+ step :draw_down_gift_card
+ step :create_payment
+ step :recalculate_order
+ run_hooks :after_apply
+ end
+
+ success(order.reload)
+ end
+
+ private
+
+ def ensure_applicable
+ # A gift card and a store credit are two ways of paying from a
+ # balance; mixing them on one order is not supported.
+ failure(order, :gift_card_using_store_credit_error) if order.using_store_credit?
+ failure(order, :gift_card_mismatched_currency) if gift_card.currency != order.currency
+
+ return if gift_card.customer.blank?
+
+ # A card issued to someone is theirs alone.
+ failure(order, :gift_card_customer_not_logged_in) if order.customer.blank?
+ failure(order, :gift_card_mismatched_customer) if gift_card.customer != order.customer
+ end
+
+ def lock_gift_card
+ gift_card.lock!
+ end
+
+ def ensure_amount_available
+ return if amount.positive? || order.total.zero?
+
+ failure(order, :gift_card_no_amount_remaining)
+ end
+
+ def amount
+ @amount ||= [gift_card.amount_remaining, order.total].min
+ end
+
+ def issue_store_credit
+ @store_credit = gift_card.store_credits.create!(
+ store: order.store,
+ customer: order.customer,
+ amount: amount,
+ currency: order.currency,
+ originator: gift_card,
+ action_originator: gift_card
+ )
+ end
+
+ def draw_down_gift_card
+ gift_card.amount_used += amount
+ gift_card.save!
+ end
+
+ def create_payment
+ order.update!(gift_card: gift_card)
+ @payment = order.payments.create!(
+ source: store_credit,
+ payment_method: store_credit_payment_method,
+ amount: amount,
+ status: 'checkout',
+ response_code: store_credit.generate_authorization_code
+ )
+ end
+
+ def recalculate_order
+ order.recalculate_totals!
+ end
+
+ def store_credit_payment_method
+ @store_credit_payment_method ||= begin
+ payment_method = order.store.payment_methods.find_or_initialize_by(
+ type: 'Spree::PaymentMethod::StoreCredit'
+ )
+ payment_method.name ||= Spree.t(:store_credit_name)
+ payment_method.active = true
+ payment_method.save! if payment_method.new_record?
+ payment_method
+ end
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/gift_cards/cancel.rb b/spree/core/app/workflows/spree/gift_cards/cancel.rb
new file mode 100644
index 0000000000..cababe8234
--- /dev/null
+++ b/spree/core/app/workflows/spree/gift_cards/cancel.rb
@@ -0,0 +1,40 @@
+module Spree
+ module GiftCards
+ # Voids a gift card so it can no longer be spent. Refuses a card that has
+ # already been spent against, because cancelling it would silently take
+ # back value the customer has used.
+ class Cancel < Spree::Workflow
+ hooks :validate, :after_cancel
+
+ # @param gift_card [Spree::GiftCard]
+ # @return [Spree::ServiceModule::Result] value is the gift card
+ def perform(gift_card:)
+ super
+
+ step :ensure_cancellable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_canceled
+ run_hooks :after_cancel
+ end
+
+ gift_card.publish_event('gift_card.canceled')
+ success(gift_card)
+ end
+
+ private
+
+ def ensure_cancellable
+ failure(gift_card, :gift_card_already_canceled) if gift_card.canceled?
+ return if gift_card.status == 'active'
+
+ failure(gift_card, :gift_card_already_redeemed)
+ end
+
+ def mark_canceled
+ failure(gift_card) unless gift_card.update(status: 'canceled')
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/gift_cards/redeem.rb b/spree/core/app/workflows/spree/gift_cards/redeem.rb
new file mode 100644
index 0000000000..9303aa7f52
--- /dev/null
+++ b/spree/core/app/workflows/spree/gift_cards/redeem.rb
@@ -0,0 +1,59 @@
+module Spree
+ module GiftCards
+ # Marks a gift card spent. Called once the order that consumed it is
+ # placed, so it runs after the money has already been taken off the card
+ # by Spree::GiftCards::Apply — this records the outcome.
+ #
+ # A card is only fully redeemed when nothing is left on it; while a
+ # balance remains it becomes partially redeemed and stays spendable. The
+ # partial case deliberately republishes on every redemption, because each
+ # one is a separate spend the merchant may want to react to.
+ class Redeem < Spree::Workflow
+ hooks :validate, :after_redeem
+
+ # @param gift_card [Spree::GiftCard]
+ # @return [Spree::ServiceModule::Result] value is the gift card
+ def perform(gift_card:)
+ super
+
+ step :ensure_redeemable
+ run_hooks :validate
+
+ ApplicationRecord.transaction do
+ step :mark_redeemed
+ run_hooks :after_redeem
+ end
+
+ gift_card.publish_event("gift_card.#{fully_redeemed? ? 'redeemed' : 'partially_redeemed'}")
+ success(gift_card)
+ end
+
+ private
+
+ def ensure_redeemable
+ failure(gift_card, :gift_card_already_redeemed) if gift_card.redeemed?
+ failure(gift_card, :gift_card_canceled) if gift_card.canceled?
+ end
+
+ # Read once, before the write: which event fires has to describe the
+ # same spend the status does.
+ def fully_redeemed?
+ return @fully_redeemed unless @fully_redeemed.nil?
+
+ @fully_redeemed = gift_card.amount_remaining.zero?
+ end
+
+ # redeemed_at marks the moment the card was spent out, so it is only
+ # stamped on full redemption — a partial spend leaves it unset.
+ def mark_redeemed
+ attributes = if fully_redeemed?
+ { status: 'redeemed', redeemed_at: Time.current }
+ else
+ { status: 'partially_redeemed' }
+ end
+
+ failure(gift_card) unless gift_card.update(attributes)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/gift_cards/remove.rb b/spree/core/app/workflows/spree/gift_cards/remove.rb
new file mode 100644
index 0000000000..c718f2381b
--- /dev/null
+++ b/spree/core/app/workflows/spree/gift_cards/remove.rb
@@ -0,0 +1,72 @@
+module Spree
+ module GiftCards
+ # Takes a gift card back off an order, returning the drawn-down balance to
+ # the card. The reverse of Spree::GiftCards::Apply, and only possible
+ # while the order is still open.
+ class Remove < Spree::Workflow
+ hooks :validate, :after_remove
+
+ # @param order [Spree::Order]
+ # @return [Spree::ServiceModule::Result] value is true
+ def perform(order:)
+ super
+
+ step :ensure_removable
+ halt!(true) if order.gift_card.nil?
+ run_hooks :validate
+
+ order.with_lock do
+ step :void_payments
+ step :restore_gift_card_balance
+ step :discard_store_credits
+ step :detach_gift_card
+ step :recalculate_order
+ run_hooks :after_remove
+ end
+
+ success(true)
+ end
+
+ private
+
+ def ensure_removable
+ failure(order, :remove_gift_card_on_completed_order_error) if order.completed?
+ end
+
+ def gift_card
+ @gift_card ||= order.gift_card
+ end
+
+ def payments
+ @payments ||= order.payments.checkout.store_credits.where(source: gift_card.store_credits)
+ end
+
+ def void_payments
+ @payment_total = payments.sum(:amount)
+ payments.each(&:invalidate!)
+ end
+
+ def restore_gift_card_balance
+ gift_card.with_lock do
+ gift_card.amount_used -= @payment_total
+ gift_card.save!
+ end
+ end
+
+ # The store credits belong to the gift card rather than the order, so
+ # nothing else would clean them up.
+ # TODO: void these rather than destroying them.
+ def discard_store_credits
+ payments.each { |payment| payment.source.destroy! }
+ end
+
+ def detach_gift_card
+ order.update!(gift_card: nil)
+ end
+
+ def recalculate_order
+ order.recalculate_totals!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
index 53446c40d6..0c139f8448 100644
--- a/spree/core/app/workflows/spree/orders/complete.rb
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -89,7 +89,7 @@ module Spree
def redeem_gift_card
return if order.gift_card.nil?
- Spree.gift_card_redeem_service.call(gift_card: order.gift_card)
+ Spree.gift_card_redeem_workflow.call(gift_card: order.gift_card)
end
# Providers that opt into auto_fulfill? (digital delivery today) get
diff --git a/spree/core/db/migrate/20260819000002_rename_spree_gift_cards_state_to_status.rb b/spree/core/db/migrate/20260819000002_rename_spree_gift_cards_state_to_status.rb
new file mode 100644
index 0000000000..104439142b
--- /dev/null
+++ b/spree/core/db/migrate/20260819000002_rename_spree_gift_cards_state_to_status.rb
@@ -0,0 +1,5 @@
+class RenameSpreeGiftCardsStateToStatus < ActiveRecord::Migration[8.1]
+ def change
+ rename_column :spree_gift_cards, :state, :status
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 54a563ca0b..55c70e23a0 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -53,9 +53,10 @@ module Spree
checkout_remove_store_credit_service: 'Spree::Checkout::RemoveStoreCredit',
# gift cards
- gift_card_apply_service: 'Spree::GiftCards::Apply',
- gift_card_remove_service: 'Spree::GiftCards::Remove',
- gift_card_redeem_service: 'Spree::GiftCards::Redeem',
+ gift_card_apply_workflow: 'Spree::GiftCards::Apply',
+ gift_card_remove_workflow: 'Spree::GiftCards::Remove',
+ gift_card_redeem_workflow: 'Spree::GiftCards::Redeem',
+ gift_card_cancel_workflow: 'Spree::GiftCards::Cancel',
# order
order_approve_service: 'Spree::Orders::Approve',
@@ -213,7 +214,10 @@ module Spree
# not interchangeable with what the new call sites pass. Removed in 6.1.
LEGACY_SERVICE_KEYS = {
shipment_update_service: :fulfillment_update_workflow,
- fulfillment_update_service: :fulfillment_update_workflow
+ fulfillment_update_service: :fulfillment_update_workflow,
+ gift_card_apply_service: :gift_card_apply_workflow,
+ gift_card_remove_service: :gift_card_remove_workflow,
+ gift_card_redeem_service: :gift_card_redeem_workflow
}.freeze
def legacy_workflow_overrides
diff --git a/spree/core/lib/spree/testing_support/factories/gift_card_factory.rb b/spree/core/lib/spree/testing_support/factories/gift_card_factory.rb
index 35982762ce..6a759e540b 100644
--- a/spree/core/lib/spree/testing_support/factories/gift_card_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/gift_card_factory.rb
@@ -1,11 +1,11 @@
FactoryBot.define do
factory :gift_card, class: Spree::GiftCard do
- state { :active }
+ status { :active }
amount { 10.00 }
store { Spree::Store.default || create(:store) }
trait :redeemed do
- state { :redeemed }
+ status { :redeemed }
redeemed_at { Time.current }
amount_used { amount }
end
diff --git a/spree/core/spec/models/spree/gift_card_spec.rb b/spree/core/spec/models/spree/gift_card_spec.rb
index 20945de9d8..fe581c4d9a 100644
--- a/spree/core/spec/models/spree/gift_card_spec.rb
+++ b/spree/core/spec/models/spree/gift_card_spec.rb
@@ -28,14 +28,14 @@ RSpec.describe Spree::GiftCard, type: :model do
describe '#ensure_can_be_deleted' do
it "ensures a used gift card can't be destroyed" do
- expect(create(:gift_card, state: :redeemed).destroy).to be(false)
- expect(create(:gift_card, state: :partially_redeemed).destroy).to be(false)
- expect(create(:gift_card, state: :active).destroy).to be_destroyed
- expect(create(:gift_card, state: :canceled).destroy).to be_destroyed
+ expect(create(:gift_card, status: :redeemed).destroy).to be(false)
+ expect(create(:gift_card, status: :partially_redeemed).destroy).to be(false)
+ expect(create(:gift_card, status: :active).destroy).to be_destroyed
+ expect(create(:gift_card, status: :canceled).destroy).to be_destroyed
end
it 'adds an error' do
- gift_card = create(:gift_card, state: :redeemed)
+ gift_card = create(:gift_card, status: :redeemed)
gift_card.destroy
expect(gift_card).to_not be_destroyed
@@ -45,10 +45,10 @@ RSpec.describe Spree::GiftCard, type: :model do
end
describe 'Scopes' do
- let(:active_gift_card) { create(:gift_card, state: :active) }
- let(:redeemed_gift_card) { create(:gift_card, state: :redeemed) }
- let(:partially_redeemed_gift_card) { create(:gift_card, state: :partially_redeemed) }
- let(:expired_gift_card) { create(:gift_card, expires_at: Date.current, state: :active) }
+ let(:active_gift_card) { create(:gift_card, status: :active) }
+ let(:redeemed_gift_card) { create(:gift_card, status: :redeemed) }
+ let(:partially_redeemed_gift_card) { create(:gift_card, status: :partially_redeemed) }
+ let(:expired_gift_card) { create(:gift_card, expires_at: Date.current, status: :active) }
describe '#active' do
it 'returns active gift cards' do
@@ -77,7 +77,7 @@ RSpec.describe Spree::GiftCard, type: :model do
describe '#active?' do
context 'when expired' do
- let(:gift_card) { build(:gift_card, expires_at: Date.current, state: :active) }
+ let(:gift_card) { build(:gift_card, expires_at: Date.current, status: :active) }
it 'returns false' do
expect(gift_card.active?).to be(false)
@@ -85,7 +85,7 @@ RSpec.describe Spree::GiftCard, type: :model do
end
context 'when redeemed' do
- let(:gift_card) { build(:gift_card, state: :redeemed) }
+ let(:gift_card) { build(:gift_card, status: :redeemed) }
it 'returns false' do
expect(gift_card.active?).to be(false)
@@ -93,7 +93,7 @@ RSpec.describe Spree::GiftCard, type: :model do
end
context 'when active' do
- let(:gift_card) { build(:gift_card, expires_at: 1.day.from_now, state: :active) }
+ let(:gift_card) { build(:gift_card, expires_at: 1.day.from_now, status: :active) }
it 'returns true' do
expect(gift_card.active?).to be(true)
@@ -103,7 +103,7 @@ RSpec.describe Spree::GiftCard, type: :model do
describe '#amount_remaining' do
context 'when active' do
- let(:gift_card) { build(:gift_card, amount: 100, amount_used: 0, amount_authorized: 0, state: :active) }
+ let(:gift_card) { build(:gift_card, amount: 100, amount_used: 0, amount_authorized: 0, status: :active) }
it 'returns the remaining amount' do
expect(gift_card.amount_remaining).to eq(100)
@@ -111,7 +111,7 @@ RSpec.describe Spree::GiftCard, type: :model do
end
context 'when redeemed' do
- let(:gift_card) { build(:gift_card, amount: 100, amount_used: 100, amount_authorized: 0, state: :redeemed) }
+ let(:gift_card) { build(:gift_card, amount: 100, amount_used: 100, amount_authorized: 0, status: :redeemed) }
it 'returns 0' do
expect(gift_card.amount_remaining).to eq(0)
@@ -119,7 +119,7 @@ RSpec.describe Spree::GiftCard, type: :model do
end
context 'when authorized' do
- let(:gift_card) { build(:gift_card, amount: 100, amount_used: 0, amount_authorized: 50, state: :partially_redeemed) }
+ let(:gift_card) { build(:gift_card, amount: 100, amount_used: 0, amount_authorized: 50, status: :partially_redeemed) }
it 'returns the remaining amount' do
expect(gift_card.amount_remaining).to eq(50)
@@ -127,20 +127,20 @@ RSpec.describe Spree::GiftCard, type: :model do
end
end
- describe '#display_state' do
+ describe '#display_status' do
context 'when expired' do
- let(:gift_card) { build(:gift_card, expires_at: 1.day.ago, state: :active) }
+ let(:gift_card) { build(:gift_card, expires_at: 1.day.ago, status: :active) }
it 'returns expired' do
- expect(gift_card.display_state).to eq 'expired'
+ expect(gift_card.display_status).to eq 'expired'
end
end
context 'when active' do
- let(:gift_card) { build(:gift_card, expires_at: 1.day.from_now, state: :active) }
+ let(:gift_card) { build(:gift_card, expires_at: 1.day.from_now, status: :active) }
it 'returns active' do
- expect(gift_card.display_state).to eq 'active'
+ expect(gift_card.display_status).to eq 'active'
end
end
end
@@ -172,72 +172,56 @@ RSpec.describe Spree::GiftCard, type: :model do
end
end
- describe 'State transitions' do
- let(:store) { Spree::Store.default }
-
- context 'when active' do
- let(:gift_card) { create(:gift_card, state: :active, amount: 100, amount_used: 0, store: store) }
+ describe 'status' do
+ it 'has no state machine' do
+ expect(described_class).not_to respond_to(:state_machines)
+ end
- it 'transitions from active to partially_redeemed' do
- expect { gift_card.partial_redeem! }
- .to change(gift_card, :state).from('active').to('partially_redeemed')
+ it 'defaults to active' do
+ expect(described_class.new.status).to eq('active')
end
- it 'transitions from active to redeemed' do
- expect { gift_card.redeem! }
- .to change(gift_card, :state).from('active').to('redeemed')
+ it 'rejects an unknown status' do
+ expect(build(:gift_card, status: 'nonsense')).not_to be_valid
end
end
- context 'when partially_redeemed' do
- let(:gift_card) { create(:gift_card, state: :partially_redeemed, amount: 100, amount_used: 50, store: store) }
+ describe 'status scopes and predicates' do
+ let(:store) { Spree::Store.default }
+ let!(:active) { create(:gift_card, store: store, amount: 10) }
+ let!(:partial) { create(:gift_card, store: store, amount: 10, status: 'partially_redeemed') }
+ let!(:redeemed) { create(:gift_card, store: store, amount: 10, status: 'redeemed') }
+ let!(:expired) { create(:gift_card, store: store, amount: 10, expires_at: 1.day.ago) }
- it 'allows multiple partial redemptions (remains partially_redeemed)' do
- expect { gift_card.partial_redeem! }
- .to_not change(gift_card, :state)
- expect(gift_card.state).to eq('partially_redeemed')
+ it 'treats a partially redeemed card as still spendable and an expired one as not' do
+ expect(described_class.active).to include(active, partial)
+ expect(described_class.active).not_to include(redeemed, expired)
end
- it 'transitions from partially_redeemed to redeemed when fully used' do
- gift_card.update!(amount_used: 100)
- expect { gift_card.redeem! }
- .to change(gift_card, :state).from('partially_redeemed').to('redeemed')
+ it 'reports an expired card as inactive even though its status is active' do
+ expect(expired.status).to eq('active')
+ expect(expired).not_to be_active
+ expect(expired).to be_expired
end
- end
- context 'when redeemed' do
- let(:gift_card) { create(:gift_card, state: :redeemed, amount: 100, amount_used: 100, store: store) }
-
- it 'does not allow further redemption' do
- expect { gift_card.partial_redeem! }.to raise_error(StateMachines::InvalidTransition)
- expect { gift_card.redeem! }.to raise_error(StateMachines::InvalidTransition)
+ it 'exposes the plain column lookup through with_status' do
+ expect(described_class.with_status(:active)).to include(active, expired)
+ expect(described_class.with_status(:active, :redeemed)).to include(active, redeemed)
end
end
- end
- describe 'custom events', events: true do
- let(:store) { Spree::Store.default }
+ describe 'deprecated state bridge' do
+ let(:gift_card) { build(:gift_card, status: :redeemed) }
- describe 'gift_card.redeemed' do
- let(:gift_card) { create(:gift_card, state: :active, amount: 100, amount_used: 0, store: store) }
-
- it 'publishes gift_card.redeemed event when fully redeemed' do
- expect(gift_card).to receive(:publish_event).with('gift_card.redeemed')
- allow(gift_card).to receive(:publish_event).with(anything)
-
- gift_card.redeem!
- end
+ it 'reads status' do
+ expect(Spree::Deprecation).to receive(:warn)
+ expect(gift_card.state).to eq('redeemed')
end
- describe 'gift_card.partially_redeemed' do
- let(:gift_card) { create(:gift_card, state: :active, amount: 100, amount_used: 0, store: store) }
-
- it 'publishes gift_card.partially_redeemed event when partially redeemed' do
- expect(gift_card).to receive(:publish_event).with('gift_card.partially_redeemed')
- allow(gift_card).to receive(:publish_event).with(anything)
-
- gift_card.partial_redeem!
- end
+ it 'writes status' do
+ expect(Spree::Deprecation).to receive(:warn)
+ gift_card.state = 'active'
+ expect(gift_card.status).to eq('active')
end
end
end
diff --git a/spree/core/spec/models/spree/order/checkout_spec.rb b/spree/core/spec/models/spree/order/checkout_spec.rb
index 583447222b..d0e51b41ab 100644
--- a/spree/core/spec/models/spree/order/checkout_spec.rb
+++ b/spree/core/spec/models/spree/order/checkout_spec.rb
@@ -78,7 +78,7 @@ describe Spree::Order, type: :model do
it 'redeems the gift card' do
expect(gift_card.redeemed_at).to be_nil
- expect { order.finalize! }.to change { gift_card.reload.state }.from('active').to('redeemed')
+ expect { order.finalize! }.to change { gift_card.reload.status }.from('active').to('redeemed')
expect(gift_card.amount_used).to eq(order.total)
expect(gift_card.amount_remaining).to eq(0)
expect(gift_card.redeemed_at).to be_present
@@ -88,7 +88,7 @@ describe Spree::Order, type: :model do
let(:gift_card) { create(:gift_card, amount: order.total + 1, store: store) }
it 'partially redeems the gift card' do
- expect { order.finalize! }.to change { gift_card.reload.state }.from('active').to('partially_redeemed')
+ expect { order.finalize! }.to change { gift_card.reload.status }.from('active').to('partially_redeemed')
expect(gift_card.amount_used).to eq(order.total)
expect(gift_card.amount_remaining).to eq(1)
expect(gift_card.redeemed_at).to be_nil
diff --git a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
index 2ae379bea6..c5963c1f8f 100644
--- a/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
+++ b/spree/core/spec/presenters/spree/csv/gift_card_presenter_spec.rb
@@ -9,7 +9,7 @@ RSpec.describe Spree::CSV::GiftCardPresenter, type: :model do
amount: 50.00,
amount_used: 10.00,
currency: 'USD',
- state: 'active',
+ status: 'active',
expires_at: Date.new(Time.current.year, 12, 31),
user: user,
store: store)
diff --git a/spree/core/spec/services/spree/gift_cards/redeem_spec.rb b/spree/core/spec/services/spree/gift_cards/redeem_spec.rb
deleted file mode 100644
index e3d5fccf43..0000000000
--- a/spree/core/spec/services/spree/gift_cards/redeem_spec.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-require 'spec_helper'
-
-RSpec.describe Spree::GiftCards::Redeem do
- subject { described_class.call(gift_card: gift_card) }
-
- let(:store) { Spree::Store.default }
- let(:order) { create(:order, store: store) }
- let(:gift_card) { create(:gift_card, amount: 50, store: store) }
-
- before do
- order.update_column(:total, 30)
- order.update_column(:shipment_total, 10)
- end
-
- context 'when the gift card has no amount remaining' do
- before { gift_card.update!(amount_used: gift_card.amount) }
-
- it 'calls redeem! on the gift card' do
- expect(gift_card).to receive(:redeem!)
- subject
- end
-
- it 'returns success with the gift card' do
- expect(subject).to be_success
- expect(subject.value).to eq(gift_card)
- end
- end
-
- context 'when the gift card has amount remaining' do
- before { gift_card.update!(amount_used: 20) }
-
- it 'calls partial_redeem! on the gift card' do
- expect(gift_card).to receive(:partial_redeem!)
- subject
- end
-
- it 'returns success with the gift card' do
- expect(subject).to be_success
- expect(subject.value).to eq(gift_card)
- end
- end
-end
diff --git a/spree/core/spec/services/spree/gift_cards/apply_spec.rb b/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
similarity index 94%
rename from spree/core/spec/services/spree/gift_cards/apply_spec.rb
rename to spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
index 64b38ce411..c6f8eed5e8 100644
--- a/spree/core/spec/services/spree/gift_cards/apply_spec.rb
+++ b/spree/core/spec/workflows/spree/gift_cards/apply_spec.rb
@@ -53,7 +53,7 @@ RSpec.describe Spree::GiftCards::Apply do
expect { subject }.not_to change(Spree::StoreCredit, :count)
expect(subject).to be_failure
- expect(subject.value).to eq(:gift_card_using_store_credit_error)
+ expect(subject.error.value).to eq(:gift_card_using_store_credit_error)
expect(order.reload.gift_card).to be_nil
expect(order.total_applied_store_credit).to eq(10)
@@ -67,7 +67,7 @@ RSpec.describe Spree::GiftCards::Apply do
it 'responds with an error' do
expect(subject).to be_failure
- expect(subject.value).to eq(:gift_card_mismatched_currency)
+ expect(subject.error.value).to eq(:gift_card_mismatched_currency)
end
end
@@ -91,7 +91,7 @@ RSpec.describe Spree::GiftCards::Apply do
context 'with guest order' do
it 'responds with an error' do
expect(subject).to be_failure
- expect(subject.value).to eq(:gift_card_customer_not_logged_in)
+ expect(subject.error.value).to eq(:gift_card_customer_not_logged_in)
end
end
@@ -100,7 +100,7 @@ RSpec.describe Spree::GiftCards::Apply do
it 'responds with an error' do
expect(subject).to be_failure
- expect(subject.value).to eq(:gift_card_mismatched_customer)
+ expect(subject.error.value).to eq(:gift_card_mismatched_customer)
end
end
end
@@ -141,7 +141,7 @@ RSpec.describe Spree::GiftCards::Apply do
expect { subject }.not_to change(Spree::StoreCredit, :count)
expect(subject).to be_failure
- expect(subject.value).to eq(:gift_card_no_amount_remaining)
+ expect(subject.error.value).to eq(:gift_card_no_amount_remaining)
expect(order.reload.gift_card).to be_nil
end
diff --git a/spree/core/spec/workflows/spree/gift_cards/cancel_spec.rb b/spree/core/spec/workflows/spree/gift_cards/cancel_spec.rb
new file mode 100644
index 0000000000..cb8c706272
--- /dev/null
+++ b/spree/core/spec/workflows/spree/gift_cards/cancel_spec.rb
@@ -0,0 +1,36 @@
+require 'spec_helper'
+
+RSpec.describe Spree::GiftCards::Cancel do
+ subject { described_class.call(gift_card: gift_card) }
+
+ let(:store) { Spree::Store.default }
+ let(:gift_card) { create(:gift_card, amount: 50, store: store) }
+
+ it 'cancels an unspent card' do
+ expect { subject }.to change { gift_card.reload.status }.from('active').to('canceled')
+ expect(subject).to be_success
+ end
+
+ it 'publishes gift_card.canceled', events: true do
+ allow(gift_card).to receive(:publish_event).with(anything)
+ expect(gift_card).to receive(:publish_event).with('gift_card.canceled')
+ subject
+ end
+
+ context 'when the card has already been spent against' do
+ before { gift_card.update!(status: 'partially_redeemed', amount_used: 20) }
+
+ it 'refuses, so spent value is not taken back' do
+ expect(subject).not_to be_success
+ expect(gift_card.reload.status).to eq('partially_redeemed')
+ end
+ end
+
+ context 'when already canceled' do
+ before { gift_card.update!(status: 'canceled') }
+
+ it 'fails' do
+ expect(subject).not_to be_success
+ end
+ end
+end
diff --git a/spree/core/spec/workflows/spree/gift_cards/redeem_spec.rb b/spree/core/spec/workflows/spree/gift_cards/redeem_spec.rb
new file mode 100644
index 0000000000..5c7dce8971
--- /dev/null
+++ b/spree/core/spec/workflows/spree/gift_cards/redeem_spec.rb
@@ -0,0 +1,59 @@
+require 'spec_helper'
+
+RSpec.describe Spree::GiftCards::Redeem do
+ subject { described_class.call(gift_card: gift_card) }
+
+ let(:store) { Spree::Store.default }
+ let(:gift_card) { create(:gift_card, amount: 50, store: store) }
+
+ context 'when the gift card has no amount remaining' do
+ before { gift_card.update!(amount_used: gift_card.amount) }
+
+ it 'marks it redeemed and stamps redeemed_at' do
+ expect { subject }.to change { gift_card.reload.status }.from('active').to('redeemed')
+ expect(gift_card.redeemed_at).to be_present
+ end
+
+ it 'returns success with the gift card' do
+ expect(subject).to be_success
+ expect(subject.value).to eq(gift_card)
+ end
+
+ it 'publishes gift_card.redeemed', events: true do
+ allow(gift_card).to receive(:publish_event).with(anything)
+ expect(gift_card).to receive(:publish_event).with('gift_card.redeemed')
+ subject
+ end
+ end
+
+ context 'when the gift card has amount remaining' do
+ before { gift_card.update!(amount_used: 20) }
+
+ it 'marks it partially redeemed without stamping redeemed_at' do
+ expect { subject }.to change { gift_card.reload.status }.from('active').to('partially_redeemed')
+ expect(gift_card.redeemed_at).to be_nil
+ end
+
+ it 'publishes gift_card.partially_redeemed', events: true do
+ allow(gift_card).to receive(:publish_event).with(anything)
+ expect(gift_card).to receive(:publish_event).with('gift_card.partially_redeemed')
+ subject
+ end
+
+ it 'republishes on a further partial redemption' do
+ described_class.call(gift_card: gift_card)
+
+ allow(gift_card).to receive(:publish_event).with(anything)
+ expect(gift_card).to receive(:publish_event).with('gift_card.partially_redeemed')
+ described_class.call(gift_card: gift_card)
+ end
+ end
+
+ context 'when the gift card is already redeemed' do
+ before { gift_card.update!(status: 'redeemed', amount_used: gift_card.amount) }
+
+ it 'fails rather than redeeming twice' do
+ expect(subject).not_to be_success
+ end
+ end
+end
diff --git a/spree/core/spec/services/spree/gift_cards/remove_spec.rb b/spree/core/spec/workflows/spree/gift_cards/remove_spec.rb
similarity index 91%
rename from spree/core/spec/services/spree/gift_cards/remove_spec.rb
rename to spree/core/spec/workflows/spree/gift_cards/remove_spec.rb
index 2be39a4ffd..09a00057c3 100644
--- a/spree/core/spec/services/spree/gift_cards/remove_spec.rb
+++ b/spree/core/spec/workflows/spree/gift_cards/remove_spec.rb
@@ -35,7 +35,7 @@ RSpec.describe Spree::GiftCards::Remove do
expect(gift_card.amount_remaining).to eq(50)
expect(store_credit_payment).to be_present
- expect(store_credit_payment.state).to eq('invalid')
+ expect(store_credit_payment.status).to eq('invalid')
expect(store_credit_payment.source).to be_deleted
end
@@ -49,7 +49,7 @@ RSpec.describe Spree::GiftCards::Remove do
it 'responds with an error' do
expect(subject).to be_failure
- expect(subject.value).to eq(:remove_gift_card_on_completed_order_error)
+ expect(subject.error.value).to eq(:remove_gift_card_on_completed_order_error)
end
end
end