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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let admins apply discount codes to draft orders
Damian Legawiecc3c556f3e601
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 1e003ae34b..ec7e11c140 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -1112,6 +1112,32 @@ export class AdminClient {this.request<void>('DELETE', `/orders/${orderId}/discounts/${id}`, options),},+ /**+ * Discount codes on a draft order — same pending semantics as the+ * storefront cart endpoint (a real-but-not-yet-eligible code is stored+ * and activates on recalculation). Completed orders respond 422+ * (`discount_not_editable`); use manual discounts instead.+ */+ discountCodes: {+ create: (+ orderId: string,+ params: { code: string },+ options?: RequestOptions,+ ): Promise<Order> =>+ this.request<Order>('POST', `/orders/${orderId}/discount_codes`, {+ ...options,+ body: params,+ }),++ /** `code` is the discount code string, not an ID. */+ delete: (orderId: string, code: string, options?: RequestOptions): Promise<Order> =>+ this.request<Order>(+ 'DELETE',+ `/orders/${orderId}/discount_codes/${encodeURIComponent(code)}`,+ options,+ ),+ },+fees: {list: (orderId: string,diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex a1441fe765..fd0500eb62 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1384,6 +1384,15 @@"ship_message": "شحن هذا الوفاء؟","void_message": "Void هذه الدفعة؟"},+ "discount_section": {+ "apply_dialog_description": "أدخل رمزاً أو اختر أحد عروض القسائم.",+ "apply_dialog_title": "تطبيق رمز الخصم",+ "code_placeholder": "SUMMER10",+ "label": "رمز الخصم",+ "pending_hint": "يُطبق عندما يصبح الطلب مؤهلاً",+ "promotions_label": "عروض القسائم",+ "remove_confirm_message": "إزالة رمز الخصم من هذا الطلب؟"+ },"dropdown": {"cancel_shipment": "Cancel Shipment","complete_order": "Complete Order",@@ -1413,7 +1422,7 @@"none_applied": "لم يتم تطبيق أي شيء","requires_customer": "يتطلب العميل","store_credit_label": "Store credit",- "title": "Gift Card & Store Credit"+ "title": "الخصومات والرصيد"},"items_table": {"item": "غرض",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex c9a68ec540..55acd6aa64 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1384,6 +1384,15 @@"ship_message": "Diese Lieferung versenden?","void_message": "Diese Zahlung stornieren?"},+ "discount_section": {+ "apply_dialog_description": "Code eingeben oder eine Coupon-Aktion auswählen.",+ "apply_dialog_title": "Rabattcode anwenden",+ "code_placeholder": "SOMMER10",+ "label": "Rabattcode",+ "pending_hint": "wird angewendet, sobald die Bestellung qualifiziert",+ "promotions_label": "Coupon-Aktionen",+ "remove_confirm_message": "Rabattcode von dieser Bestellung entfernen?"+ },"dropdown": {"cancel_shipment": "Lieferung stornieren","complete_order": "Auftrag abschließen",@@ -1413,7 +1422,7 @@"none_applied": "Keine angewendet","requires_customer": "Erfordert einen Kunden","store_credit_label": "Guthaben",- "title": "Geschenkkarte & Guthaben"+ "title": "Rabatte & Guthaben"},"items_table": {"item": "Artikel",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex b633697ebc..ded1c6ef88 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1384,6 +1384,15 @@"ship_message": "Ship this fulfillment?","void_message": "Void this payment?"},+ "discount_section": {+ "apply_dialog_description": "Enter a code or pick one of the coupon promotions.",+ "apply_dialog_title": "Apply Discount Code",+ "code_placeholder": "SUMMER10",+ "label": "Discount code",+ "pending_hint": "applies once the order qualifies",+ "promotions_label": "Coupon promotions",+ "remove_confirm_message": "Remove the discount code from this order?"+ },"dropdown": {"cancel_shipment": "Cancel Shipment","complete_order": "Complete Order",@@ -1413,7 +1422,7 @@"none_applied": "None applied","requires_customer": "Requires a customer","store_credit_label": "Store credit",- "title": "Gift Card & Store Credit"+ "title": "Discounts & Credit"},"items_table": {"item": "Item",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex f9ce82d3e4..447d1b2635 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1384,6 +1384,15 @@"ship_message": "Expédier cet envoi ?","void_message": "Annuler ce paiement ?"},+ "discount_section": {+ "apply_dialog_description": "Saisissez un code ou choisissez une promotion à coupon.",+ "apply_dialog_title": "Appliquer un code de réduction",+ "code_placeholder": "ETE10",+ "label": "Code de réduction",+ "pending_hint": "s'applique dès que la commande est éligible",+ "promotions_label": "Promotions à coupon",+ "remove_confirm_message": "Retirer le code de réduction de cette commande ?"+ },"dropdown": {"cancel_shipment": "Annuler l'envoi","complete_order": "Finaliser la commande",@@ -1413,7 +1422,7 @@"none_applied": "Aucun appliqué","requires_customer": "Nécessite un client","store_credit_label": "Avoir",- "title": "Carte cadeau et avoir"+ "title": "Remises et avoirs"},"items_table": {"item": "Article",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 7c4a8f12a8..4da763bfff 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1390,6 +1390,15 @@"ship_message": "Wysłać tę realizację?","void_message": "Unieważnić tę płatność?"},+ "discount_section": {+ "apply_dialog_description": "Wpisz kod lub wybierz promocję kuponową.",+ "apply_dialog_title": "Zastosuj kod rabatowy",+ "code_placeholder": "LATO10",+ "label": "Kod rabatowy",+ "pending_hint": "zostanie zastosowany, gdy zamówienie się zakwalifikuje",+ "promotions_label": "Promocje kuponowe",+ "remove_confirm_message": "Usunąć kod rabatowy z tego zamówienia?"+ },"dropdown": {"cancel_shipment": "Anuluj wysyłkę","complete_order": "Sfinalizuj zamówienie",@@ -1419,7 +1428,7 @@"none_applied": "Brak zastosowanych","requires_customer": "Wymaga klienta","store_credit_label": "Kredyt sklepowy",- "title": "Karta podarunkowa i kredyt sklepowy"+ "title": "Rabaty i środki"},"items_table": {"item": "Pozycja",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex add2005af8..7ab0ba1bdf 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1384,6 +1384,15 @@"ship_message": "发货此履约单吗?","void_message": "作废此付款吗?"},+ "discount_section": {+ "apply_dialog_description": "输入折扣码或选择一个优惠码促销。",+ "apply_dialog_title": "应用折扣码",+ "code_placeholder": "SUMMER10",+ "label": "折扣码",+ "pending_hint": "订单符合条件后生效",+ "promotions_label": "优惠码促销",+ "remove_confirm_message": "从此订单移除折扣码?"+ },"dropdown": {"cancel_shipment": "取消发货","complete_order": "完成订单",@@ -1413,7 +1422,7 @@"none_applied": "未应用","requires_customer": "需要客户","store_credit_label": "店铺积分",- "title": "礼品卡和店铺积分"+ "title": "折扣与余额"},"items_table": {"item": "商品",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex ce39e80fa3..283951b14b 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -9,6 +9,7 @@ import {PageHeader,Slot,TagCombobox,+ useResourceKey,useResourceMutation,} from '@spree/dashboard-core'import {@@ -1917,10 +1918,14 @@ function DiscountsCard({ order }: { order: Order }) {const { orderId } = Route.useParams()const confirm = useConfirm()const [giftCardOpen, setGiftCardOpen] = useState(false)+ const [couponOpen, setCouponOpen] = useState(false)const removeGiftCardMutation = useOrderMutation(orderId, () =>adminClient.orders.giftCards.remove(orderId, order.gift_card?.id ?? ''),)+ const removeCouponMutation = useOrderMutation(orderId, () =>+ adminClient.orders.discountCodes.delete(orderId, order.coupon_code ?? ''),+ )const applyStoreCreditMutation = useOrderMutation(orderId, () =>adminClient.orders.storeCredits.apply(orderId),)@@ -1930,6 +1935,8 @@ function DiscountsCard({ order }: { order: Order }) {const hasStoreCredit = Number.parseFloat(order.store_credit_total) > 0const hasCustomer = Boolean(order.customer_id)+ const isEditable = !order.completed_at+ const couponPending = Boolean(order.coupon_code) && Number.parseFloat(order.discount_total) === 0return (<>@@ -1938,6 +1945,52 @@ function DiscountsCard({ order }: { order: Order }) {<CardTitle>{t('admin.orders.detail.gift_card_section.title')}</CardTitle></CardHeader><CardContent className="flex flex-col gap-3">+ {/* Discount code — editable on drafts; frozen after completion */}+ <div className="flex items-center justify-between gap-2">+ <div className="flex flex-col">+ <span className="text-sm font-medium">+ {t('admin.orders.detail.discount_section.label')}+ </span>+ {order.coupon_code ? (+ <span className="font-mono text-xs text-muted-foreground">+ {order.coupon_code}+ {couponPending && ` · ${t('admin.orders.detail.discount_section.pending_hint')}`}+ </span>+ ) : (+ <span className="text-xs text-muted-foreground">+ {t('admin.orders.detail.gift_card_section.none_applied')}+ </span>+ )}+ </div>+ {isEditable &&+ (order.coupon_code ? (+ <Button+ size="sm"+ variant="outline"+ onClick={async () => {+ if (+ await confirm({+ message: t('admin.orders.detail.discount_section.remove_confirm_message'),+ confirmLabel: t('admin.actions.remove'),+ })+ ) {+ removeCouponMutation.mutate(undefined)+ }+ }}+ disabled={removeCouponMutation.isPending}+ >+ {t('admin.actions.remove')}+ </Button>+ ) : (+ <Button size="sm" variant="outline" onClick={() => setCouponOpen(true)}>+ <PlusIcon className="size-4" />+ {t('admin.actions.apply')}+ </Button>+ ))}+ </div>++ <Separator />+{/* Gift card */}<div className="flex items-center justify-between gap-2"><div className="flex flex-col">@@ -2035,10 +2088,117 @@ function DiscountsCard({ order }: { order: Order }) {</Card><ApplyGiftCardDialog orderId={orderId} open={giftCardOpen} onOpenChange={setGiftCardOpen} />+ <CouponCodeDialog orderId={orderId} open={couponOpen} onOpenChange={setCouponOpen} /></>)}+function CouponCodeDialog({+ orderId,+ open,+ onOpenChange,+}: {+ orderId: string+ open: boolean+ onOpenChange: (open: boolean) => void+}) {+ const { t } = useTranslation()+ const [code, setCode] = useState('')++ const promotionsQuery = useQuery({+ queryKey: useResourceKey('promotions', 'coupon-options'),+ queryFn: () => adminClient.promotions.list({ q: { kind_eq: 'coupon_code' }, per_page: 100 }),+ enabled: open,+ })+ const couponPromotions = (promotionsQuery.data?.data ?? []).filter((promotion) => promotion.code)++ const mutation = useOrderMutation(orderId, (params: { code: string }) =>+ adminClient.orders.discountCodes.create(orderId, params),+ )++ function handleSubmit(e: FormEvent<HTMLFormElement>) {+ e.preventDefault()+ const trimmed = code.trim()+ if (!trimmed) return+ mutation.mutate(+ { code: trimmed },+ {+ onSuccess: () => {+ setCode('')+ onOpenChange(false)+ },+ },+ )+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.orders.detail.discount_section.apply_dialog_title')}</DialogTitle>+ <DialogDescription>+ {t('admin.orders.detail.discount_section.apply_dialog_description')}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit}>+ <DialogBody>+ <FieldGroup>+ <Field>+ <FieldLabel htmlFor="coupon-code">{t('admin.fields.code.label')}</FieldLabel>+ <Input+ id="coupon-code"+ name="code"+ value={code}+ onChange={(e) => setCode(e.target.value)}+ placeholder={t('admin.orders.detail.discount_section.code_placeholder')}+ required+ autoFocus+ />+ </Field>+ {couponPromotions.length > 0 && (+ <Field>+ <FieldLabel>+ {t('admin.orders.detail.discount_section.promotions_label')}+ </FieldLabel>+ <div className="flex max-h-48 flex-col gap-1 overflow-y-auto">+ {couponPromotions.map((promotion) => (+ <button+ type="button"+ key={promotion.id}+ onClick={() => setCode(promotion.code ?? '')}+ className={cn(+ 'flex items-center justify-between rounded-md border px-3 py-2 text-left text-sm hover:bg-accent',+ code === promotion.code && 'border-primary',+ )}+ >+ <span className="truncate">{promotion.name}</span>+ <span className="ml-2 shrink-0 font-mono text-xs text-muted-foreground">+ {promotion.code}+ </span>+ </button>+ ))}+ </div>+ </Field>+ )}+ {mutation.isError && (+ <p className="text-sm text-destructive">{(mutation.error as Error).message}</p>+ )}+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={mutation.isPending}>+ {t('admin.actions.apply')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}+function ApplyGiftCardDialog({orderId,open,diff --git a/spree/api/app/controllers/spree/api/v3/admin/orders/discount_codes_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/orders/discount_codes_controller.rbnew file mode 100644index 0000000000..c48b747d7b--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/orders/discount_codes_controller.rb@@ -0,0 +1,86 @@+module Spree+ module Api+ module V3+ module Admin+ module Orders+ # Applies/removes a discount code on a draft order — the admin+ # counterpart of the storefront cart endpoint, with the same pending+ # semantics: a real-but-not-yet-eligible code is kept and activates+ # on the first recalculation where the order qualifies. Completed+ # orders are frozen; their discounts change only through manual rows+ # (see DiscountsController).+ class DiscountCodesController < BaseController+ skip_before_action :set_resource, raise: false++ # POST /api/v3/admin/orders/:order_id/discount_codes+ def create+ with_order_lock do+ return render_completed_order_error if @parent.completed?++ @parent.coupon_code = permitted_params[:code]++ coupon_handler.apply++ if coupon_handler.successful? || pending_eligibility?+ @parent.save!(validate: false) if @parent.changed?+ render json: serialize_resource(@parent.reload), status: :created+ else+ @parent.update_column(:coupon_code, nil) if @parent.read_attribute(:coupon_code).present?+ render_errors(coupon_handler.error)+ end+ end+ end++ # DELETE /api/v3/admin/orders/:order_id/discount_codes/:id+ # :id is the discount code string.+ def destroy+ with_order_lock do+ return render_completed_order_error if @parent.completed?++ coupon_handler.remove(params[:id])++ if coupon_handler.successful?+ render json: serialize_resource(@parent.reload)+ else+ render_errors(coupon_handler.error)+ end+ end+ end++ protected++ def model_class+ Spree::Order+ end++ def serializer_class+ Spree.api.admin_order_serializer+ end++ private++ def coupon_handler+ @coupon_handler ||= Spree.coupon_handler.new(@parent, enable_gift_cards: false)+ end++ def pending_eligibility?+ coupon_handler.status_code == :coupon_code_not_eligible+ end++ def render_completed_order_error+ render_error(+ code: ERROR_CODES[:discount_not_editable],+ message: Spree.t('errors.messages.coupon_code_frozen_after_completion'),+ status: :unprocessable_content+ )+ end++ def permitted_params+ params.permit(:code)+ end+ end+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex 71390ad046..330100e529 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -427,6 +427,7 @@ Spree::Core::Engine.add_routes doresources :refunds, controller: 'orders/refunds', only: [:index, :create]resources :tax_lines, controller: 'orders/tax_lines', only: [:index, :show]resources :discounts, controller: 'orders/discounts', only: [:index, :show, :create, :update, :destroy]+ resources :discount_codes, controller: 'orders/discount_codes', only: [:create, :destroy]resources :fees, controller: 'orders/fees', only: [:index, :show, :create, :update, :destroy]resources :gift_cards, controller: 'orders/gift_cards', only: [:create, :destroy]resource :store_credits, controller: 'orders/store_credits', only: [:create, :destroy]diff --git a/spree/api/spec/controllers/spree/api/v3/admin/orders/discount_codes_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/orders/discount_codes_controller_spec.rbnew file mode 100644index 0000000000..69cac2485c--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders/discount_codes_controller_spec.rb@@ -0,0 +1,80 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::Orders::DiscountCodesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let(:store) { @default_store }+ let!(:promotion) do+ create(:promotion_with_item_total_rule, :with_line_item_adjustment,+ code: 'save5', kind: :coupon_code, store: store,+ item_total_threshold_amount: 30, adjustment_rate: 5)+ end++ before { request.headers.merge!(headers) }++ describe 'POST #create' do+ context 'with a qualifying draft order' do+ let(:order) { create(:order_with_line_items, store: store, line_items_price: 50) }++ it 'applies the code and returns the order' do+ post :create, params: { order_id: order.prefixed_id, code: 'SAVE5' }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['coupon_code']).to eq('save5')+ expect(order.reload.discounts.where(promotion_id: promotion.id)).to be_present+ end+ end++ context 'with a draft order below the promotion threshold' do+ let(:order) { create(:order_with_line_items, store: store, line_items_price: 10) }++ it 'keeps the code pending without discount rows' do+ post :create, params: { order_id: order.prefixed_id, code: 'save5' }, as: :json++ expect(response).to have_http_status(:created)+ expect(order.reload.read_attribute(:coupon_code)).to eq('save5')+ expect(order.discounts.where(promotion_id: promotion.id)).to be_empty+ end+ end++ context 'with an unknown code' do+ let(:order) { create(:order_with_line_items, store: store, line_items_price: 50) }++ it 'rejects and does not persist the code' do+ post :create, params: { order_id: order.prefixed_id, code: 'bogus' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(order.reload.read_attribute(:coupon_code)).to be_nil+ end+ end++ context 'with a completed order' do+ let(:order) { create(:completed_order_with_totals, store: store) }++ it 'refuses — completed orders take manual discounts only' do+ post :create, params: { order_id: order.prefixed_id, code: 'save5' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('discount_not_editable')+ end+ end+ end++ describe 'DELETE #destroy' do+ let(:order) { create(:order_with_line_items, store: store, line_items_price: 50) }++ it 'removes the promotion and clears the stored code' do+ order.update!(coupon_code: 'save5')+ order.update_with_updater!+ expect(order.reload.discounts.where(promotion_id: promotion.id)).to be_present++ delete :destroy, params: { order_id: order.prefixed_id, id: 'save5' }, as: :json++ expect(response).to have_http_status(:ok)+ expect(order.reload.read_attribute(:coupon_code)).to be_nil+ expect(order.discounts.where(promotion_id: promotion.id)).to be_empty+ end+ end+enddiff --git a/spree/core/app/models/spree/promotion.rb b/spree/core/app/models/spree/promotion.rbindex 67fc8e98c4..f982c0f191 100644--- a/spree/core/app/models/spree/promotion.rb+++ b/spree/core/app/models/spree/promotion.rb@@ -90,7 +90,7 @@ module Spree## `name` is whitelisted so the admin global search / command palette can# filter via the `name_or_code_cont` predicate without a dedicated scope.- self.whitelisted_ransackable_attributes = ['name', 'path', 'promotion_category_id', 'code', 'starts_at', 'expires_at']+ self.whitelisted_ransackable_attributes = ['name', 'path', 'promotion_category_id', 'code', 'kind', 'starts_at', 'expires_at']self.whitelisted_ransackable_associations = %w[coupon_codes]def self.with_coupon_code(coupon_code)diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 80dc993006..da21c123b7 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -928,6 +928,7 @@ en:cannot_delete_default_channel: Default channel cannot be deleted. Promote another channel to default first.cart_currency_mismatch: carts in different currencies cannot be mergedchannel_store_mismatch: must belong to the same store+ coupon_code_frozen_after_completion: coupon codes cannot be changed on a completed order — add a manual discount insteaddelivery_zone_postal_definition_required: postal code member requires a prefix or a from/to rangedelivery_zone_prefix_and_range_exclusive: cannot be combined with a from/to rangedelivery_zone_range_inverted: must be greater than or equal to postal_code_from