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.

Added Gift Cards and Gift Card Batches Admin API

Damian Legawiec960456d02c44
diff --git a/packages/admin-sdk/src/types/generated/GiftCard.ts b/packages/admin-sdk/src/types/generated/GiftCard.ts
index c7a794c122..fc55f20151 100644
--- a/packages/admin-sdk/src/types/generated/GiftCard.ts
+++ b/packages/admin-sdk/src/types/generated/GiftCard.ts
@@ -1,6 +1,7 @@
-// Typelizer digest 47121a3f3103923c6389104d95eb4a23
+// Typelizer digest 0b47215f8a7f358a702d0676fb1c66cb
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
+import type {Customer, AdminUser, GiftCardBatch, Order} from '@/types'
interface GiftCard {
id: string;
@@ -20,6 +21,12 @@ interface GiftCard {
active: boolean;
created_at: string;
updated_at: string;
+ customer_id: string | null;
+ created_by_id: string | null;
+ customer?: Customer;
+ created_by?: AdminUser;
+ gift_card_batch?: GiftCardBatch;
+ orders?: Array<Order>;
}
export default GiftCard;
diff --git a/packages/admin-sdk/src/types/generated/GiftCardBatch.ts b/packages/admin-sdk/src/types/generated/GiftCardBatch.ts
new file mode 100644
index 0000000000..449a91e5c4
--- /dev/null
+++ b/packages/admin-sdk/src/types/generated/GiftCardBatch.ts
@@ -0,0 +1,17 @@
+// Typelizer digest 784b5e96992dd0313dd9e127def57ba3
+//
+// DO NOT MODIFY: This file was automatically generated by Typelizer.
+
+interface GiftCardBatch {
+ id: string;
+ codes_count: number;
+ currency: string | null;
+ prefix: string | null;
+ created_at: string;
+ updated_at: string;
+ amount: string | null;
+ expires_at: string | null;
+ created_by_id: string | null;
+}
+
+export default GiftCardBatch;
diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.ts
index 187318da99..435ca8820e 100644
--- a/packages/admin-sdk/src/types/generated/index.ts
+++ b/packages/admin-sdk/src/types/generated/index.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 148c379e5953e853ae3067057cf2d624
+// Typelizer digest fb48a6da6484b901cd424617ea0f9738
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
export type { default as Address } from './Address'
@@ -21,6 +21,7 @@ export type { default as DigitalLink } from './DigitalLink'
export type { default as Discount } from './Discount'
export type { default as Export } from './Export'
export type { default as Fulfillment } from './Fulfillment'
+export type { default as GiftCardBatch } from './GiftCardBatch'
export type { default as GiftCard } from './GiftCard'
export type { default as Invitation } from './Invitation'
export type { default as LineItem } from './LineItem'
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 30ff9018a2..fde83f2981 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -29,6 +29,7 @@ export type { default as Discount } from './generated/Discount'
export type { default as Export } from './generated/Export'
export type { default as Fulfillment } from './generated/Fulfillment'
export type { default as GiftCard } from './generated/GiftCard'
+export type { default as GiftCardBatch } from './generated/GiftCardBatch'
export type { default as Invitation } from './generated/Invitation'
export type { default as LineItem } from './generated/LineItem'
export type { default as Market } from './generated/Market'
diff --git a/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb
new file mode 100644
index 0000000000..3edd4e52bb
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/gift_card_batches_controller.rb
@@ -0,0 +1,31 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin bulk-issue endpoint for `Spree::GiftCardBatch`. Creating a
+ # batch synchronously generates the `codes_count` gift cards inline
+ # (or kicks off a background job when the count exceeds
+ # `Spree.config.gift_card_batch_web_limit`, default 500). Read-only
+ # access lives behind `list`/`show` so the SPA can surface batch
+ # context on the gift cards index (filter chip, batch chip on rows).
+ class GiftCardBatchesController < ResourceController
+ scoped_resource :gift_cards
+
+ protected
+
+ def model_class
+ Spree::GiftCardBatch
+ end
+
+ def serializer_class
+ Spree.api.admin_gift_card_batch_serializer
+ end
+
+ def permitted_params
+ params.permit(:prefix, :codes_count, :amount, :expires_at, :currency)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
new file mode 100644
index 0000000000..1be72aff48
--- /dev/null
+++ b/spree/api/app/controllers/spree/api/v3/admin/gift_cards_controller.rb
@@ -0,0 +1,33 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ # Admin CRUD for `Spree::GiftCard`. Scoped to the current store via
+ # the model's `SingleStoreResource` include — the base controller's
+ # `scope` already applies `model_class.for_store(current_store)`.
+ #
+ # `store` and `created_by` are auto-stamped by `build_resource` in
+ # `Spree::Api::V3::ResourceController`, so create requests only need
+ # to include user-facing attributes (amount, currency, expires_at,
+ # optional code, optional user_id).
+ class GiftCardsController < ResourceController
+ scoped_resource :gift_cards
+
+ protected
+
+ def model_class
+ Spree::GiftCard
+ end
+
+ def serializer_class
+ Spree.api.admin_gift_card_serializer
+ end
+
+ def permitted_params
+ params.permit(:code, :amount, :expires_at, :user_id, :currency)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/controllers/spree/api/v3/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
index 8f1e95bd87..7c5e47ec8a 100644
--- a/spree/api/app/controllers/spree/api/v3/resource_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/resource_controller.rb
@@ -50,12 +50,22 @@ module Spree
end
# DELETE /api/v3/resource/:id
- # Honors `can_be_deleted?` if the model defines it — domain rules like
- # "completed orders cannot be deleted" live on the model, not on
- # CanCanCan abilities, so they apply to all callers (JWT and API key).
+ # Domain rules like "redeemed gift cards cannot be deleted" live on
+ # the model via `can_be_deleted?` and apply to all callers (JWT and
+ # API key). When `can_be_deleted?` returns false we render 422
+ # (resource state forbids the request) rather than 403, since the
+ # caller is authorized — it's the resource's state that's blocking
+ # the operation. Models that prefer CanCan-gated destroy can opt in
+ # via their ability (e.g. `can :destroy, Spree::Order, &:can_be_deleted?`),
+ # which raises before the controller hook fires and yields 403.
def destroy
if @resource.respond_to?(:can_be_deleted?) && [email protected]_be_deleted?
- raise CanCan::AccessDenied.new("#{@resource.class.model_name.human} cannot be deleted")
+ message = Spree.t(:cannot_delete, scope: 'api', model: @resource.class.model_name.human)
+ return render_error(
+ code: ERROR_CODES[:validation_error],
+ message: message,
+ status: :unprocessable_content
+ )
end
@resource.destroy!
diff --git a/spree/api/app/serializers/spree/api/v3/admin/gift_card_batch_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/gift_card_batch_serializer.rb
new file mode 100644
index 0000000000..573512ae4f
--- /dev/null
+++ b/spree/api/app/serializers/spree/api/v3/admin/gift_card_batch_serializer.rb
@@ -0,0 +1,10 @@
+module Spree
+ module Api
+ module V3
+ module Admin
+ class GiftCardBatchSerializer < V3::GiftCardBatchSerializer
+ end
+ end
+ end
+ end
+end
diff --git a/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb
index 4b027fb238..6fe66d450c 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/gift_card_serializer.rb
@@ -2,8 +2,49 @@ module Spree
module Api
module V3
module Admin
+ # Admin serializer extends the store-facing one with operational
+ # context the admin UI needs: who the card was issued to (customer),
+ # who issued it (admin), and the orders that consumed it.
class GiftCardSerializer < V3::GiftCardSerializer
+ typelize customer_id: [:string, nullable: true],
+ created_by_id: [:string, nullable: true]
+
attributes created_at: :iso8601, updated_at: :iso8601
+
+ attribute :customer_id do |gift_card|
+ gift_card.user&.prefixed_id
+ end
+
+ attribute :created_by_id do |gift_card|
+ gift_card.created_by&.prefixed_id
+ end
+
+ # Customer the card was issued to. Gated behind `expand?` to keep
+ # the list payload thin — the SPA's list view passes
+ # `expand=customer,created_by` to populate the row chips.
+ one :user,
+ key: :customer,
+ resource: Spree.api.admin_customer_serializer,
+ if: proc { expand?('customer') }
+
+ # Admin who issued the card.
+ one :created_by,
+ resource: Spree.api.admin_admin_user_serializer,
+ if: proc { expand?('created_by') }
+
+ # Batch the card was issued as part of (bulk-issue flow). The
+ # `Spree::GiftCard#batch` association is keyed off
+ # `gift_card_batch_id`; we rename the JSON field to match that
+ # column for read/write symmetry.
+ one :batch,
+ key: :gift_card_batch,
+ resource: Spree.api.admin_gift_card_batch_serializer,
+ if: proc { expand?('gift_card_batch') }
+
+ # Orders that consumed the card. Detail-only — pass `expand=orders`.
+ many :orders,
+ resource: Spree.api.admin_order_serializer,
+ if: proc { expand?('orders') }
end
end
end
diff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.yml
index 348a2e7b99..511f350cfd 100644
--- a/spree/api/config/locales/en.yml
+++ b/spree/api/config/locales/en.yml
@@ -2,6 +2,7 @@
en:
spree:
api:
+ cannot_delete: "%{model} cannot be deleted"
current_password_invalid: Current password is invalid or missing
gateway_error: 'There was a problem with the payment gateway: %{text}'
invalid_api_key: Invalid API key (%{key}) specified.
diff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rb
index 204ab71ef9..cf0c9ac946 100644
--- a/spree/api/config/routes.rb
+++ b/spree/api/config/routes.rb
@@ -229,6 +229,12 @@ Spree::Core::Engine.add_routes do
# Customer groups (segmentation; used by promotion rules + bulk customer ops)
resources :customer_groups
+ # Gift cards (admin-issued; redemption + apply lives under :orders)
+ resources :gift_cards
+ # Bulk-issue batches: create generates `codes_count` cards inline
+ # (or via background job when >`gift_card_batch_web_limit`).
+ resources :gift_card_batches, only: [:index, :show, :create]
+
# Variants (top-level, for search/autocomplete across all products)
resources :variants, only: [:index, :show], concerns: :custom_fieldable
diff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rb
index 409c0dc53a..29dc882f9f 100644
--- a/spree/api/lib/spree/api/dependencies.rb
+++ b/spree/api/lib/spree/api/dependencies.rb
@@ -179,6 +179,7 @@ module Spree
admin_shipment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',
admin_fulfillment_serializer: 'Spree::Api::V3::Admin::FulfillmentSerializer',
admin_gift_card_serializer: 'Spree::Api::V3::Admin::GiftCardSerializer',
+ admin_gift_card_batch_serializer: 'Spree::Api::V3::Admin::GiftCardBatchSerializer',
admin_payment_serializer: 'Spree::Api::V3::Admin::PaymentSerializer',
admin_refund_serializer: 'Spree::Api::V3::Admin::RefundSerializer',
admin_adjustment_serializer: 'Spree::Api::V3::Admin::AdjustmentSerializer',
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/gift_card_batches_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/gift_card_batches_controller_spec.rb
new file mode 100644
index 0000000000..d2dc2b9c69
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/gift_card_batches_controller_spec.rb
@@ -0,0 +1,98 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::GiftCardBatchesController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ let!(:batch) { create(:gift_card_batch, store: store, prefix: 'WELCOME', amount: 50, currency: 'USD', codes_count: 3) }
+
+ it 'returns batches scoped to the current store' do
+ get :index, as: :json
+
+ expect(response).to have_http_status(:ok)
+ ids = json_response['data'].map { |b| b['id'] }
+ expect(ids).to include(batch.prefixed_id)
+ end
+
+ it 'excludes batches from other stores' do
+ other = create(:gift_card_batch, store: create(:store), prefix: 'OTHER', amount: 5, currency: 'USD', codes_count: 1)
+
+ get :index, as: :json
+ ids = json_response['data'].map { |b| b['id'] }
+ expect(ids).to include(batch.prefixed_id)
+ expect(ids).not_to include(other.prefixed_id)
+ end
+ end
+
+ describe 'POST #create' do
+ let(:base_params) do
+ { prefix: 'WELCOME', amount: '25.00', currency: 'USD', codes_count: 5, expires_at: '2030-12-31' }
+ end
+
+ it 'creates a batch scoped to the current store and stamps created_by' do
+ expect { post :create, params: base_params, as: :json }.to change(Spree::GiftCardBatch, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ batch = Spree::GiftCardBatch.last
+ expect(batch.store).to eq(store)
+ expect(batch.created_by_id).to eq(admin_user.id)
+ expect(batch.prefix).to eq('WELCOME')
+ expect(batch.codes_count).to eq(5)
+ end
+
+ it 'auto-generates the gift cards inline for small batches' do
+ expect { post :create, params: base_params.merge(codes_count: 3), as: :json }
+ .to change(Spree::GiftCard, :count).by(3)
+
+ batch = Spree::GiftCardBatch.last
+ expect(batch.gift_cards.count).to eq(3)
+ expect(batch.gift_cards.all? { |g| g.code.start_with?('welcome') }).to be(true)
+ expect(batch.gift_cards.all? { |g| g.currency == 'USD' && g.amount == 25 }).to be(true)
+ end
+
+ it 'returns 422 when prefix is blank' do
+ post :create, params: base_params.merge(prefix: ''), as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it 'returns 422 when codes_count is zero' do
+ post :create, params: base_params.merge(codes_count: 0), as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it 'returns 422 when codes_count exceeds the configured cap' do
+ allow(Spree::Config).to receive(:[]).and_call_original
+ allow(Spree::Config).to receive(:[]).with(:gift_card_batch_limit).and_return(10)
+
+ post :create, params: base_params.merge(codes_count: 11), as: :json
+
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+ end
+
+ describe 'GET #show' do
+ let!(:batch) { create(:gift_card_batch, store: store, prefix: 'WELCOME', amount: 50, currency: 'USD', codes_count: 2) }
+
+ it 'returns the batch' do
+ get :show, params: { id: batch.prefixed_id }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(batch.prefixed_id)
+ expect(json_response['prefix']).to eq('WELCOME')
+ expect(json_response['codes_count']).to eq(2)
+ end
+
+ it 'returns 404 for a batch from another store' do
+ other = create(:gift_card_batch, store: create(:store), prefix: 'OTHER', amount: 5, currency: 'USD', codes_count: 1)
+
+ get :show, params: { id: other.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/gift_cards_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/gift_cards_controller_spec.rb
new file mode 100644
index 0000000000..3f504904da
--- /dev/null
+++ b/spree/api/spec/controllers/spree/api/v3/admin/gift_cards_controller_spec.rb
@@ -0,0 +1,179 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Admin::GiftCardsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Admin authenticated'
+
+ let!(:gift_card) { create(:gift_card, store: store, amount: 50, currency: 'USD') }
+
+ before { request.headers.merge!(headers) }
+
+ describe 'GET #index' do
+ subject { get :index, as: :json }
+
+ it 'returns gift cards in the current store' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(json_response['data']).to be_an(Array)
+ expect(json_response['data'].map { |g| g['id'] }).to include(gift_card.prefixed_id)
+ end
+
+ it 'excludes gift cards from other stores' do
+ other_store = create(:store)
+ other_card = create(:gift_card, store: other_store, amount: 25, currency: 'USD')
+
+ subject
+ ids = json_response['data'].map { |g| g['id'] }
+ expect(ids).to include(gift_card.prefixed_id)
+ expect(ids).not_to include(other_card.prefixed_id)
+ end
+
+ it 'surfaces display_amount as a formatted money string and ISO timestamps' do
+ subject
+ entry = json_response['data'].find { |g| g['id'] == gift_card.prefixed_id }
+ expect(entry['display_amount']).to match(/\$50\.00/)
+ expect(entry['currency']).to eq('USD')
+ expect(entry['created_at']).to match(/\A\d{4}-\d{2}-\d{2}T/)
+ end
+
+ it 'does not embed customer or created_by by default' do
+ gift_card.update!(user: create(:user, email: '[email protected]'))
+
+ subject
+ entry = json_response['data'].find { |g| g['id'] == gift_card.prefixed_id }
+ expect(entry).not_to have_key('customer')
+ expect(entry).not_to have_key('created_by')
+ expect(entry).not_to have_key('gift_card_batch')
+ end
+
+ it 'exposes flat prefixed-ID references even without expand' do
+ customer = create(:user)
+ admin = create(:admin_user)
+ gift_card.update!(user: customer, created_by: admin)
+
+ subject
+ entry = json_response['data'].find { |g| g['id'] == gift_card.prefixed_id }
+ expect(entry['customer_id']).to eq(customer.prefixed_id)
+ expect(entry['created_by_id']).to eq(admin.prefixed_id)
+ end
+
+ it 'embeds customer + created_by when expand=customer,created_by is passed' do
+ customer = create(:user, email: '[email protected]')
+ admin = create(:admin_user, email: '[email protected]')
+ gift_card.update!(user: customer, created_by: admin)
+
+ get :index, params: { expand: 'customer,created_by' }, as: :json
+ entry = json_response['data'].find { |g| g['id'] == gift_card.prefixed_id }
+ expect(entry['customer']['id']).to eq(customer.prefixed_id)
+ expect(entry['customer']['email']).to eq('[email protected]')
+ expect(entry['created_by']['email']).to eq('[email protected]')
+ end
+ end
+
+ describe 'GET #show' do
+ subject { get :show, params: { id: gift_card.prefixed_id }, as: :json }
+
+ it 'returns the gift card' do
+ subject
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(gift_card.prefixed_id)
+ expect(json_response['code']).to eq(gift_card.display_code)
+ expect(json_response['status']).to eq('active')
+ end
+
+ it 'returns 404 for a gift card from another store' do
+ other_card = create(:gift_card, store: create(:store))
+
+ get :show, params: { id: other_card.prefixed_id }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+
+ it 'reports expired status when the card is past its expiration' do
+ expired = create(:gift_card, :expired, store: store, amount: 5, currency: 'USD')
+ get :show, params: { id: expired.prefixed_id }, as: :json
+ expect(json_response['status']).to eq('expired')
+ expect(json_response['expired']).to be(true)
+ expect(json_response['active']).to be(false)
+ end
+ end
+
+ describe 'POST #create' do
+ let(:create_params) { { amount: '25.00', currency: 'USD', expires_at: '2030-12-31' } }
+
+ it 'creates a gift card scoped to the current store and stamps created_by' do
+ expect { post :create, params: create_params, as: :json }.to change(Spree::GiftCard, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['display_amount']).to match(/\$25\.00/)
+ expect(json_response['currency']).to eq('USD')
+ created = Spree::GiftCard.last
+ expect(created.store).to eq(store)
+ # `created_by` is auto-stamped by Spree::Api::V3::ResourceController#build_resource.
+ expect(created.created_by_id).to eq(admin_user.id)
+ end
+
+ it 'attaches a customer when user_id is passed as a prefixed ID' do
+ customer = create(:user, email: '[email protected]')
+
+ post :create, params: create_params.merge(user_id: customer.prefixed_id, expand: 'customer'), as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['customer']['id']).to eq(customer.prefixed_id)
+ expect(json_response['customer']['email']).to eq('[email protected]')
+ end
+
+ it 'returns 422 when amount is missing' do
+ post :create, params: { currency: 'USD' }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(json_response['error']['code']).to eq('validation_error')
+ expect(json_response['error']['details']).to have_key('amount')
+ end
+
+ it 'returns 422 when amount is not positive' do
+ post :create, params: { amount: '0', currency: 'USD' }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ end
+
+ it 'auto-generates a code when not provided' do
+ post :create, params: create_params, as: :json
+ expect(response).to have_http_status(:created)
+ expect(json_response['code']).to match(/\A[A-Z0-9]+\z/)
+ end
+
+ it 'honors a caller-supplied code' do
+ post :create, params: create_params.merge(code: 'WELCOME50'), as: :json
+ expect(response).to have_http_status(:created)
+ expect(json_response['code']).to eq('WELCOME50')
+ end
+ end
+
+ describe 'PATCH #update' do
+ it 'updates editable attributes on an active card' do
+ patch :update, params: { id: gift_card.prefixed_id, amount: '75.00' }, as: :json
+ expect(response).to have_http_status(:ok)
+ expect(json_response['display_amount']).to match(/\$75\.00/)
+ end
+
+ it 'returns 404 for a card from another store' do
+ other_card = create(:gift_card, store: create(:store))
+ patch :update, params: { id: other_card.prefixed_id, amount: '5.00' }, as: :json
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
+ describe 'DELETE #destroy' do
+ it 'deletes an unused gift card' do
+ expect { delete :destroy, params: { id: gift_card.prefixed_id }, as: :json }
+ .to change(Spree::GiftCard, :count).by(-1)
+ expect(response).to have_http_status(:no_content)
+ end
+
+ it 'refuses to delete a redeemed gift card' do
+ redeemed = create(:gift_card, :redeemed, store: store, amount: 10, currency: 'USD')
+ delete :destroy, params: { id: redeemed.prefixed_id }, as: :json
+ expect(response).to have_http_status(:unprocessable_content)
+ expect(Spree::GiftCard.exists?(redeemed.id)).to be(true)
+ end
+ end
+end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
index a4cfabb593..18e7214cd0 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb
@@ -519,7 +519,7 @@ RSpec.describe Spree::Api::V3::Admin::OrdersController, type: :controller do
context 'with completed order' do
let!(:order) { create(:completed_order_with_totals, store: store) }
- it 'returns 403 (cannot delete completed orders)' do
+ it 'returns 403 (CanCan denies destroy on completed orders)' do
subject
expect(response).to have_http_status(:forbidden)
end
diff --git a/spree/api/spec/integration/spree/api/v3/admin/gift_card_batches_spec.rb b/spree/api/spec/integration/spree/api/v3/admin/gift_card_batches_spec.rb
new file mode 100644
index 0000000000..55309e5931
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/gift_card_batches_spec.rb
@@ -0,0 +1,139 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Gift Card Batches API', type: :request, swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let!(:batch) { create(:gift_card_batch, store: store, prefix: 'WELCOME', amount: 50, currency: 'USD', codes_count: 2) }
+
+ path '/api/v3/admin/gift_card_batches' do
+ get 'List gift card batches' do
+ tags 'Gift Cards'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Returns the gift card batches issued by the current store. Each batch
+ groups the cards generated together for a campaign or bulk-issuance
+ — the cards themselves live under `/admin/gift_cards` and reference
+ the batch via `gift_card_batch_id`.
+ DESC
+ admin_scope :read, :gift_cards
+
+ admin_sdk_example 'gift-card-batches/list'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true,
+ description: 'Bearer token for admin authentication'
+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'
+ parameter name: :limit, in: :query, type: :integer, required: false, description: 'Records per page'
+ parameter name: :'q[prefix_cont]', in: :query, type: :string, required: false,
+ description: 'Filter by prefix (contains)'
+ parameter name: :sort, in: :query, type: :string, required: false,
+ description: 'Sort by field. Prefix with `-` for descending.'
+
+ response '200', 'gift card batches found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ schema SwaggerSchemaHelpers.paginated('GiftCardBatch')
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['data'].pluck('id')).to include(batch.prefixed_id)
+ end
+ end
+ end
+
+ post 'Create a gift card batch' do
+ tags 'Gift Cards'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Issues a batch of gift cards in a single call. The server generates
+ `codes_count` cards inline for small batches (configurable via
+ `Spree.config.gift_card_batch_web_limit`, default 500) or enqueues
+ a background job for larger ones. Each card's code is the batch
+ `prefix` followed by random hex.
+ DESC
+ admin_scope :write, :gift_cards
+
+ admin_sdk_example 'gift-card-batches/create'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ required: %w[prefix amount codes_count],
+ properties: {
+ prefix: { type: :string, example: 'WELCOME', description: 'Lowercased and prepended to every generated code.' },
+ amount: { type: :string, example: '25.00', description: 'Decimal amount per card, greater than zero.' },
+ currency: { type: :string, example: 'USD', description: 'ISO 4217 currency code. Defaults to the store currency.' },
+ codes_count: { type: :integer, example: 100, description: 'Number of cards to generate. Capped at `gift_card_batch_limit`.' },
+ expires_at: { type: :string, example: '2030-12-31', nullable: true }
+ }
+ }
+
+ response '201', 'gift card batch created' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) { { prefix: 'NEWCAMP', amount: '25.00', currency: 'USD', codes_count: 5, expires_at: '2030-12-31' } }
+
+ schema '$ref' => '#/components/schemas/GiftCardBatch'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['prefix']).to eq('NEWCAMP')
+ expect(data['codes_count']).to eq(5)
+ end
+ end
+
+ response '422', 'validation error' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) { { prefix: '', amount: '25.00', codes_count: 5 } }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/admin/gift_card_batches/{id}' do
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Gift card batch prefixed ID'
+
+ get 'Get a gift card batch' do
+ tags 'Gift Cards'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Returns a single batch.'
+ admin_scope :read, :gift_cards
+
+ admin_sdk_example 'gift-card-batches/get'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+
+ response '200', 'gift card batch found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { batch.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/GiftCardBatch'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to eq(batch.prefixed_id)
+ end
+ end
+
+ response '404', 'gift card batch not found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { 'gcb_nonexistent' }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+end
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
new file mode 100644
index 0000000000..33c1d687f2
--- /dev/null
+++ b/spree/api/spec/integration/spree/api/v3/admin/gift_cards_spec.rb
@@ -0,0 +1,227 @@
+# frozen_string_literal: true
+
+require 'swagger_helper'
+
+RSpec.describe 'Admin Gift Cards API', type: :request, swagger_doc: 'api-reference/admin.yaml' do
+ include_context 'API v3 Admin'
+
+ let(:Authorization) { "Bearer #{admin_jwt_token}" }
+ let!(:gift_card) { create(:gift_card, store: store, amount: 50, currency: 'USD') }
+ let!(:other_card) { create(:gift_card, store: store, amount: 25, currency: 'USD') }
+
+ path '/api/v3/admin/gift_cards' do
+ get 'List gift cards' do
+ tags 'Gift Cards'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ 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.
+ DESC
+ admin_scope :read, :gift_cards
+
+ admin_sdk_example 'gift-cards/list'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true,
+ description: 'Bearer token for admin authentication'
+ parameter name: :page, in: :query, type: :integer, required: false, description: 'Page number'
+ 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,
+ 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`).'
+ parameter name: :fields, in: :query, type: :string, required: false,
+ description: 'Comma-separated list of fields to include. id is always included.'
+
+ response '200', 'gift cards found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+
+ schema SwaggerSchemaHelpers.paginated('GiftCard')
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['data']).to be_an(Array)
+ ids = data['data'].pluck('id')
+ expect(ids).to include(gift_card.prefixed_id, other_card.prefixed_id)
+ end
+ end
+
+ response '401', 'unauthorized' do
+ let(:'x-spree-api-key') { 'invalid' }
+ let(:Authorization) { 'Bearer invalid' }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+
+ post 'Create a gift card' do
+ tags 'Gift Cards'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Issues a gift card scoped to the current store. The code is
+ auto-generated when omitted. `currency` defaults to the store's
+ configured currency. Pass `user_id` (prefixed ID) to attach the
+ card to a specific customer.
+ DESC
+ admin_scope :write, :gift_cards
+
+ admin_sdk_example 'gift-cards/create'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ required: %w[amount],
+ properties: {
+ amount: { type: :string, example: '25.00', description: 'Decimal amount, greater than zero.' },
+ currency: { type: :string, example: 'USD', description: 'ISO 4217 currency code. Defaults to the store currency.' },
+ code: { type: :string, example: 'WELCOME50', description: 'Optional caller-supplied code. Auto-generated when omitted.' },
+ expires_at: { type: :string, example: '2030-12-31', description: 'ISO 8601 date.', nullable: true },
+ user_id: { type: :string, example: 'cus_UkLWZg9DAJ', description: 'Optional customer prefixed ID.', nullable: true }
+ }
+ }
+
+ response '201', 'gift card created' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) { { amount: '25.00', currency: 'USD', expires_at: '2030-12-31' } }
+
+ schema '$ref' => '#/components/schemas/GiftCard'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['display_amount']).to match(/\$25\.00/)
+ expect(data['status']).to eq('active')
+ end
+ end
+
+ response '422', 'validation error' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:body) { { amount: '0', currency: 'USD' } }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+ end
+
+ path '/api/v3/admin/gift_cards/{id}' do
+ parameter name: :id, in: :path, type: :string, required: true, description: 'Gift card prefixed ID'
+
+ get 'Get a gift card' do
+ tags 'Gift Cards'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description 'Returns a single gift card.'
+ admin_scope :read, :gift_cards
+
+ admin_sdk_example 'gift-cards/get'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :fields, in: :query, type: :string, required: false,
+ description: 'Comma-separated list of fields to include. id is always included.'
+
+ response '200', 'gift card found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { gift_card.prefixed_id }
+
+ schema '$ref' => '#/components/schemas/GiftCard'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['id']).to eq(gift_card.prefixed_id)
+ end
+ end
+
+ response '404', 'gift card not found' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { 'gc_nonexistent' }
+
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ run_test!
+ end
+ end
+
+ patch 'Update a gift card' do
+ tags 'Gift Cards'
+ consumes 'application/json'
+ produces 'application/json'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Updates an active gift card's editable attributes. Redeemed or
+ partially-redeemed cards cannot be edited.
+ DESC
+ admin_scope :write, :gift_cards
+
+ admin_sdk_example 'gift-cards/update'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+ parameter name: :body, in: :body, schema: {
+ type: :object,
+ properties: {
+ amount: { type: :string, example: '75.00' },
+ expires_at: { type: :string, example: '2031-12-31', nullable: true },
+ user_id: { type: :string, example: 'cus_UkLWZg9DAJ', nullable: true }
+ }
+ }
+
+ response '200', 'gift card updated' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { gift_card.prefixed_id }
+ let(:body) { { amount: '75.00' } }
+
+ schema '$ref' => '#/components/schemas/GiftCard'
+
+ run_test! do |response|
+ data = JSON.parse(response.body)
+ expect(data['display_amount']).to match(/\$75\.00/)
+ end
+ end
+ end
+
+ delete 'Delete a gift card' do
+ tags 'Gift Cards'
+ security [api_key: [], bearer_auth: []]
+ description <<~DESC
+ Deletes an unused gift card. Cards that have been redeemed or
+ partially redeemed cannot be deleted and return 422.
+ DESC
+ admin_scope :write, :gift_cards
+
+ admin_sdk_example 'gift-cards/delete'
+
+ parameter name: 'x-spree-api-key', in: :header, type: :string, required: true
+ parameter name: :Authorization, in: :header, type: :string, required: true
+
+ response '204', 'gift card deleted' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:id) { gift_card.prefixed_id }
+
+ run_test!
+ end
+
+ response '422', 'redeemed gift card cannot be deleted' do
+ let(:'x-spree-api-key') { secret_api_key.plaintext_token }
+ let(:redeemed_gift_card) do
+ create(:gift_card, store: store, amount: 100).tap do |gc|
+ gc.update_columns(amount_used: 25)
+ end
+ end
+ let(:id) { redeemed_gift_card.prefixed_id }
+
+ run_test!
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/gift_card.rb b/spree/core/app/models/spree/gift_card.rb
index 7618d43786..1afee7da9f 100644
--- a/spree/core/app/models/spree/gift_card.rb
+++ b/spree/core/app/models/spree/gift_card.rb
@@ -62,7 +62,7 @@ module Spree
#
# Ransack
#
- self.whitelisted_ransackable_attributes = %w[code user_id state]
+ self.whitelisted_ransackable_attributes = %w[code user_id 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]
diff --git a/spree/core/app/models/spree/gift_card_batch.rb b/spree/core/app/models/spree/gift_card_batch.rb
index 417554c9ba..188d071b12 100644
--- a/spree/core/app/models/spree/gift_card_batch.rb
+++ b/spree/core/app/models/spree/gift_card_batch.rb
@@ -18,7 +18,10 @@ module Spree
# Validations
#
validates :codes_count, :amount, :prefix, presence: true
- validates :codes_count, numericality: { greater_than: 0, less_than_or_equal_to: Spree::Config[:gift_card_batch_limit].to_i }
+ validates :codes_count, numericality: {
+ greater_than: 0,
+ less_than_or_equal_to: ->(_record) { Spree::Config[:gift_card_batch_limit].to_i }
+ }
validates :store, :currency, presence: true
validates :amount, numericality: { greater_than: 0 }