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.

Orders: surface step validation errors, fix drafts New Order CTA, draft-creation e2e

Damian Legawiec9a652798cf0c
diff --git a/packages/dashboard/e2e/global-setup.ts b/packages/dashboard/e2e/global-setup.ts
index e49972d279..58115419f1 100644
--- a/packages/dashboard/e2e/global-setup.ts
+++ b/packages/dashboard/e2e/global-setup.ts
@@ -57,6 +57,11 @@ const BOOTSTRAP_RUBY = [
`shipping_category = Spree::ShippingCategory.first || Spree::ShippingCategory.create!(name: 'Default')`,
`product = Spree::Product.where(name: '${FIXTURE_PROMO_PRODUCT}').first_or_create!(price: 19.99, shipping_category: shipping_category, stores: [s], status: 'active')`,
`product.taxons << category unless product.taxons.include?(category)`,
+ // Stock the promo product on the store's default stock location so
+ // order-creation tests can add it to a draft order without the
+ // +"Quantity not available"+ validation kicking in.
+ `default_location = s.default_stock_location`,
+ `product.variants_including_master.each { |v| default_location.stock_items.where(variant: v).first_or_create!.update!(count_on_hand: 100, backorderable: true) }`,
// Disjoint product fixtures for products-bulk.spec.ts. Each test owns its
// own pair (A/B → status, C/D → categories, E/F → tags, G/H → delete,
// I → row-action clone/delete) so the serial suite can mutate them in any
diff --git a/packages/dashboard/e2e/orders.spec.ts b/packages/dashboard/e2e/orders.spec.ts
new file mode 100644
index 0000000000..57e7d11f05
--- /dev/null
+++ b/packages/dashboard/e2e/orders.spec.ts
@@ -0,0 +1,107 @@
+import { expect, type Page, test } from '@playwright/test'
+import { FIXTURE_PROMO_PRODUCT, login } from './helpers'
+
+const ORDERS_PATH = (storeId: string) => `/${storeId}/orders`
+const DRAFTS_PATH = (storeId: string) => `/${storeId}/orders/drafts`
+const NEW_ORDER_PATH = (storeId: string) => `/${storeId}/orders/new`
+const CTA = /new order/i
+
+// Both orders/ and orders/drafts wrap the CTA in <Button asChild><Link/></Button>,
+// so the rendered DOM element is an <a> — getByRole('link') matches it.
+async function gotoOrdersIndex(page: Page, path: string) {
+ await page.goto(path)
+ await expect(page.getByRole('link', { name: CTA })).toBeVisible({ timeout: 15_000 })
+}
+
+test.describe('orders', () => {
+ test('lists completed orders with the New Order CTA', async ({ page }) => {
+ const creds = await login(page)
+ await gotoOrdersIndex(page, ORDERS_PATH(creds.store_id))
+ })
+
+ test('New Order CTA on the orders list navigates to the new-order page', async ({ page }) => {
+ const creds = await login(page)
+ await gotoOrdersIndex(page, ORDERS_PATH(creds.store_id))
+
+ await page.getByRole('link', { name: CTA }).click()
+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/new$`), { timeout: 15_000 })
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible()
+ })
+})
+
+test.describe('draft orders', () => {
+ test('lists drafts with the New Order CTA', async ({ page }) => {
+ const creds = await login(page)
+ await gotoOrdersIndex(page, DRAFTS_PATH(creds.store_id))
+ })
+
+ // Regression: the drafts page rendered the CTA as a bare <Button> with no
+ // <Link>, so clicking did nothing. Confirms the navigation now matches the
+ // completed-orders list.
+ test('New Order CTA on the drafts list navigates to the new-order page', async ({ page }) => {
+ const creds = await login(page)
+ await gotoOrdersIndex(page, DRAFTS_PATH(creds.store_id))
+
+ await page.getByRole('link', { name: CTA }).click()
+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/new$`), { timeout: 15_000 })
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible()
+ })
+})
+
+async function fillNewOrderForm(page: Page, email: string) {
+ // Skip the customer combobox and use the email-only path — the form
+ // accepts either, and an email-only payload is the minimum the backend
+ // service needs (no addresses required for a draft).
+ await page.locator('#order-email').fill(email)
+
+ // Variant typeahead requires 3+ chars and renders a flyout of buttons.
+ await page.getByPlaceholder(/search variant/i).fill(FIXTURE_PROMO_PRODUCT)
+ await page
+ .getByRole('button', { name: new RegExp(FIXTURE_PROMO_PRODUCT, 'i') })
+ .first()
+ .click()
+}
+
+test.describe('new order', () => {
+ test('creates a draft order with email + variant and lands on the detail page', async ({
+ page,
+ }) => {
+ const creds = await login(page)
+ await page.goto(NEW_ORDER_PATH(creds.store_id))
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible({ timeout: 15_000 })
+
+ const email = `e2e-order-${Date.now()}@example.com`
+ await fillNewOrderForm(page, email)
+
+ // Submit button shares the "New Order" label with the back-button on the
+ // sidebar; scope by type=submit so the locator is unambiguous.
+ await page.locator('button[type="submit"]').click()
+
+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/or_[^/]+$`), {
+ timeout: 15_000,
+ })
+ })
+
+ test('newly-created draft shows up in the drafts list', async ({ page }) => {
+ const creds = await login(page)
+ await page.goto(NEW_ORDER_PATH(creds.store_id))
+ await expect(page.getByRole('heading', { name: CTA })).toBeVisible({ timeout: 15_000 })
+
+ const email = `e2e-drafts-${Date.now()}@example.com`
+ await fillNewOrderForm(page, email)
+ await page.locator('button[type="submit"]').click()
+ await expect(page).toHaveURL(new RegExp(`/${creds.store_id}/orders/or_[^/]+$`), {
+ timeout: 15_000,
+ })
+
+ // Pull the order number from the H1 (PageHeader renders it as a top-level
+ // heading on the order detail page) so we can find the matching row.
+ const heading = await page.getByRole('heading', { level: 1 }).first().textContent()
+ const numberMatch = heading?.match(/R\d+/)
+ expect(numberMatch).toBeTruthy()
+ const number = numberMatch?.[0] as string
+
+ await page.goto(DRAFTS_PATH(creds.store_id))
+ await expect(page.getByText(`#${number}`)).toBeVisible({ timeout: 15_000 })
+ })
+})
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/drafts.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/drafts.tsx
index ffa7c5295f..90869f8ec2 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/drafts.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/drafts.tsx
@@ -1,6 +1,6 @@
import { adminClient, ResourceTable, resourceSearchSchema } from '@spree/dashboard-core'
import { Button } from '@spree/dashboard-ui'
-import { createFileRoute } from '@tanstack/react-router'
+import { createFileRoute, Link } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import '@/tables/orders'
@@ -13,6 +13,7 @@ export const Route = createFileRoute('/_authenticated/$storeId/orders/drafts')({
function DraftOrdersPage() {
const { t } = useTranslation()
const searchParams = Route.useSearch()
+ const { storeId } = Route.useParams()
return (
<ResourceTable
@@ -23,9 +24,11 @@ function DraftOrdersPage() {
defaultParams={{ incomplete: 1, expand: ['channel'] }}
title={t('admin.pages.orders.drafts_title')}
actions={
- <Button size="sm" className="h-[2.125rem]">
- <PlusIcon className="size-4" />
- {t('admin.pages.orders.new.title')}
+ <Button size="sm" className="h-[2.125rem]" asChild>
+ <Link to="/$storeId/orders/new" params={{ storeId }}>
+ <PlusIcon className="size-4" />
+ {t('admin.pages.orders.new.title')}
+ </Link>
</Button>
}
/>
diff --git a/spree/core/app/services/spree/orders/create.rb b/spree/core/app/services/spree/orders/create.rb
index 978d0ff11f..f64b621809 100644
--- a/spree/core/app/services/spree/orders/create.rb
+++ b/spree/core/app/services/spree/orders/create.rb
@@ -107,12 +107,33 @@ module Spree
def add_items(order)
result = Spree::Orders::UpsertItems.call(order: order, items: @params[:items])
- raise ActiveRecord::RecordInvalid, order if result.failure?
+ return if result.success?
+
+ propagate_step_failure!(order, result, fallback: 'Failed to add items to order')
end
def build_shipments(order)
result = Spree::Orders::BuildShipments.call(order: order)
- raise ActiveRecord::RecordInvalid, order if result.failure?
+ return if result.success?
+
+ propagate_step_failure!(order, result, fallback: 'Failed to build shipments')
+ end
+
+ # Surface the failing record's errors on the order so the API response
+ # carries an actionable message instead of an empty +processing_error+.
+ # Falls back to a static message when neither the record nor the result
+ # carry one — better than raising +RecordInvalid+ with an empty errors
+ # collection.
+ def propagate_step_failure!(order, result, fallback:)
+ record = result.value
+ if record.respond_to?(:errors) && record.errors.any?
+ record.errors.full_messages.each { |msg| order.errors.add(:base, msg) }
+ elsif result.error.to_s.present?
+ order.errors.add(:base, result.error.to_s)
+ else
+ order.errors.add(:base, fallback)
+ end
+ raise ActiveRecord::RecordInvalid, order
end
def apply_coupon(order)
diff --git a/spree/core/spec/services/spree/orders/create_spec.rb b/spree/core/spec/services/spree/orders/create_spec.rb
index f049711e8f..535c0e5cbc 100644
--- a/spree/core/spec/services/spree/orders/create_spec.rb
+++ b/spree/core/spec/services/spree/orders/create_spec.rb
@@ -199,6 +199,37 @@ module Spree
expect(order.total).to eq(order.item_total)
end
end
+
+ context 'when add_items fails because the variant is out of stock' do
+ # Product factory propagates stock items as +backorderable: true+ by
+ # default. Strip both so the LineItem +quantity_available+ validation
+ # fires and UpsertItems returns a failing line_item.
+ let(:out_of_stock_product) do
+ create(:product).tap do |p|
+ p.master.stock_items.update_all(count_on_hand: 0, backorderable: false)
+ end
+ end
+ let(:params) do
+ {
+ email: '[email protected]',
+ items: [{ variant_id: out_of_stock_product.default_variant.prefixed_id, quantity: 1 }]
+ }
+ end
+
+ it 'returns a failure result' do
+ expect(subject).to be_failure
+ end
+
+ it 'propagates the failing record errors onto the order so the controller renders 422 with content' do
+ order = subject.value
+ expect(order).to be_a(Spree::Order)
+ expect(order.errors[:base]).not_to be_empty
+ end
+
+ it 'rolls back the order so no draft is persisted on failure' do
+ expect { subject }.not_to change(Spree::Order, :count)
+ end
+ end
end
end
end