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.

Ability to create customers in Admin SPA

Damian Legawiec188542e854a4
diff --git a/packages/admin/package.json b/packages/admin/package.json
index 4db2815f7d..032ac9ab48 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -32,6 +32,7 @@
"clsx": "^2.1.1",
"cmdk": "^1.1.1",
"date-fns": "^4.1.0",
+ "flag-icons": "^7.5.0",
"lucide-react": "^1.14.0",
"next-themes": "^0.4.6",
"react": "^19.2.6",
diff --git a/packages/admin/src/components/spree/nav-main.tsx b/packages/admin/src/components/spree/nav-main.tsx
index 7c883d01d9..516ad2d9f8 100644
--- a/packages/admin/src/components/spree/nav-main.tsx
+++ b/packages/admin/src/components/spree/nav-main.tsx
@@ -46,7 +46,13 @@ function CollapsedDropdown({ item, children }: { item: NavItem; children: React.
return (
<DropdownMenu open={open} onOpenChange={setOpen}>
- <DropdownMenuTrigger asChild onMouseEnter={() => setOpen(true)}>
+ {/* `nativeButton={false}` because the trigger renders a `<div>` wrapping
+ a `SidebarMenuButton` (whose inner element is a `<Link>` → `<a>`),
+ not a `<button>`. The wrapper exists to attach `onMouseLeave` for
+ the hover-out close, so we can't drop it; instead we tell Base UI
+ we're rendering a non-button trigger and let it apply menu role +
+ keyboard semantics. */}
+ <DropdownMenuTrigger asChild nativeButton={false} onMouseEnter={() => setOpen(true)}>
{/* biome-ignore lint/a11y/noStaticElementInteractions: hover trigger for collapsed nav */}
<div onMouseLeave={() => setOpen(false)}>{children}</div>
</DropdownMenuTrigger>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
index 25df86247c..f906ab9b65 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
@@ -1,6 +1,6 @@
import type { Address, Customer, Order, StoreCredit } from '@spree/admin-sdk'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { createFileRoute, Link } from '@tanstack/react-router'
+import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import {
EllipsisVerticalIcon,
MailIcon,
@@ -14,6 +14,7 @@ import { type FormEvent, type ReactNode, useState } from 'react'
import { adminClient } from '@/client'
import { AddressFormDialog, type AddressParams } from '@/components/spree/address-form-dialog'
import { useConfirm } from '@/components/spree/confirm-dialog'
+import { CurrencySelect } from '@/components/spree/currency-select'
import { CustomFieldsCard } from '@/components/spree/custom-fields/custom-fields-card'
import { MetadataCard } from '@/components/spree/metadata/metadata-card'
import { PageHeader } from '@/components/spree/page-header'
@@ -41,9 +42,25 @@ import {
} from '@/components/ui/dropdown-menu'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
import { Textarea } from '@/components/ui/textarea'
import { useAuth } from '@/hooks/use-auth'
import { useCountries } from '@/hooks/use-countries'
+import { useStoreCreditCategories } from '@/hooks/use-store-credit-categories'
export const Route = createFileRoute('/_authenticated/$storeId/customers/$customerId')({
component: CustomerDetailPage,
@@ -89,6 +106,8 @@ function CustomerDetailPage() {
}
function CustomerBody({ customer }: { customer: Customer }) {
+ const { storeId } = Route.useParams()
+ const navigate = useNavigate()
const { data, isLoading } = useCustomerOrders(customer.id, { limit: 10 })
const orders = data?.data ?? []
const totalCount = data?.meta?.count ?? orders.length
@@ -97,6 +116,14 @@ function CustomerBody({ customer }: { customer: Customer }) {
const defaultShipping = customer.addresses?.find((a) => a.is_default_shipping)
const location = [defaultShipping?.city, defaultShipping?.country_iso].filter(Boolean).join(', ')
+ // The server hard-deletes only when the customer has no completed orders
+ // (Spree::Core::DestroyWithOrdersError → 422 `customer_has_orders`). We
+ // surface the API error message inline rather than swallowing the failure.
+ const deleteMutation = useMutation({
+ mutationFn: () => adminClient.customers.delete(customer.id),
+ onSuccess: () => navigate({ to: '/$storeId/customers', params: { storeId } }),
+ })
+
return (
<ResourceLayout
header={
@@ -107,6 +134,8 @@ function CustomerBody({ customer }: { customer: Customer }) {
backTo="customers"
badges={customer.tags?.map((tag) => <Badge key={tag}>{tag}</Badge>)}
resource={{ id: customer.id }}
+ onDelete={() => deleteMutation.mutateAsync()}
+ deleteLabel="Delete customer"
jsonPreview={{
title: `Customer ${customer.email}`,
queryKey: ['json', 'customer', customer.id],
@@ -114,6 +143,9 @@ function CustomerBody({ customer }: { customer: Customer }) {
endpoint: `/api/v3/admin/customers/${customer.id}`,
}}
/>
+ {deleteMutation.error && (
+ <p className="text-sm text-destructive">{(deleteMutation.error as Error).message}</p>
+ )}
<LifetimeStatsCard customer={customer} />
</>
}
@@ -191,12 +223,12 @@ function ProfileCard({ customer }: { customer: Customer }) {
)}
</CardContent>
</Card>
- <EditProfileDialog customer={customer} open={editOpen} onOpenChange={setEditOpen} />
+ <EditProfileSheet customer={customer} open={editOpen} onOpenChange={setEditOpen} />
</>
)
}
-function EditProfileDialog({
+function EditProfileSheet({
customer,
open,
onOpenChange,
@@ -228,14 +260,14 @@ function EditProfileDialog({
}
return (
- <Dialog open={open} onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Edit Customer</DialogTitle>
- <DialogDescription>Update the customer's profile information.</DialogDescription>
- </DialogHeader>
- <form onSubmit={handleSubmit}>
- <DialogBody>
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>Edit Customer</SheetTitle>
+ <SheetDescription>Update the customer's profile information.</SheetDescription>
+ </SheetHeader>
+ <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
<FieldGroup>
<Field>
<FieldLabel htmlFor="email">Email</FieldLabel>
@@ -274,18 +306,24 @@ function EditProfileDialog({
</label>
</Field>
</FieldGroup>
- </DialogBody>
- <DialogFooter>
- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={mutation.isPending}
+ >
Cancel
</Button>
- <Button type="submit" disabled={mutation.isPending}>
+ <Button type="submit" size="sm" disabled={mutation.isPending}>
{mutation.isPending ? 'Saving…' : 'Save'}
</Button>
- </DialogFooter>
+ </SheetFooter>
</form>
- </DialogContent>
- </Dialog>
+ </SheetContent>
+ </Sheet>
)
}
@@ -334,7 +372,8 @@ function useCustomerOrders(customerId: string, params: { limit: number; status?:
queryKey: ['customer-orders', customerId, params],
queryFn: () =>
adminClient.orders.list({
- q: { user_id_eq: customerId, ...(params.status ? { status_eq: params.status } : {}) },
+ user_id_eq: customerId,
+ ...(params.status ? { status_eq: params.status } : {}),
limit: params.limit,
sort: '-completed_at',
expand: ['items'],
@@ -758,6 +797,7 @@ function CustomerAddressDialog({
function StoreCreditsCard({ customer }: { customer: Customer }) {
const [addOpen, setAddOpen] = useState(false)
+ const [editing, setEditing] = useState<StoreCredit | null>(null)
const confirm = useConfirm()
const credits = customer.store_credits ?? []
@@ -785,25 +825,33 @@ function StoreCreditsCard({ customer }: { customer: Customer }) {
<p className="text-sm text-muted-foreground">No store credits issued</p>
</CardContent>
) : (
- <CardContent>
+ <CardContent className="p-0">
<table className="w-full text-sm">
<thead>
<tr className="border-b text-muted-foreground text-left">
- <th className="py-2 font-normal">Amount</th>
- <th className="py-2 font-normal">Used</th>
- <th className="py-2 font-normal">Remaining</th>
- <th className="py-2 font-normal">Memo</th>
- <th className="py-2 w-10" />
+ <th className="px-6 py-2 font-normal">Amount</th>
+ <th className="px-6 py-2 font-normal">Used</th>
+ <th className="px-6 py-2 font-normal">Remaining</th>
+ <th className="px-6 py-2 font-normal">Category</th>
+ <th className="px-6 py-2 font-normal">Memo</th>
+ <th className="px-6 py-2 w-10" />
</tr>
</thead>
<tbody>
- {credits.map((sc: StoreCredit & { memo?: string | null }) => (
+ {credits.map((sc: StoreCredit) => (
<tr key={sc.id} className="border-b last:border-b-0">
- <td className="py-2">{sc.display_amount ?? sc.amount}</td>
- <td className="py-2">{sc.display_amount_used ?? sc.amount_used}</td>
- <td className="py-2">{sc.display_amount_remaining ?? sc.amount_remaining}</td>
- <td className="py-2 text-muted-foreground">{sc.memo ?? '—'}</td>
- <td className="py-2 text-right">
+ <td className="px-6 py-3 font-medium tabular-nums">
+ {sc.display_amount ?? sc.amount}
+ </td>
+ <td className="px-6 py-3 tabular-nums">
+ {sc.display_amount_used ?? sc.amount_used}
+ </td>
+ <td className="px-6 py-3 tabular-nums">
+ {sc.display_amount_remaining ?? sc.amount_remaining}
+ </td>
+ <td className="px-6 py-3 text-muted-foreground">{sc.category_name ?? '—'}</td>
+ <td className="px-6 py-3 text-muted-foreground">{sc.memo ?? '—'}</td>
+ <td className="px-6 py-3 text-right">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="ghost" size="icon-xs">
@@ -811,6 +859,10 @@ function StoreCreditsCard({ customer }: { customer: Customer }) {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setEditing(sc)}>
+ <PencilIcon className="size-4" />
+ Edit
+ </DropdownMenuItem>
<DropdownMenuItem
className="text-destructive focus:text-destructive"
onClick={async () => {
@@ -840,10 +892,164 @@ function StoreCreditsCard({ customer }: { customer: Customer }) {
</Card>
<IssueStoreCreditDialog customerId={customer.id} open={addOpen} onOpenChange={setAddOpen} />
+ {editing && (
+ <EditStoreCreditDialog
+ customerId={customer.id}
+ credit={editing}
+ onOpenChange={(o) => {
+ if (!o) setEditing(null)
+ }}
+ />
+ )}
+ </>
+ )
+}
+
+// Base UI's `<SelectValue>` defaults to rendering the raw `value` (the
+// prefixed category ID). Use the children render-prop to look up the
+// matching category's name from the dynamic options list.
+function StoreCreditCategorySelect({
+ id,
+ name,
+ defaultValue,
+ required,
+}: {
+ id: string
+ name: string
+ defaultValue?: string
+ required?: boolean
+}) {
+ const { data, isLoading } = useStoreCreditCategories()
+ const [value, setValue] = useState(defaultValue ?? '')
+ const categories = data?.data ?? []
+
+ return (
+ <>
+ {/* Hidden input keeps the FormData submit path working. */}
+ <input type="hidden" name={name} value={value} />
+ <Select value={value} onValueChange={setValue}>
+ <SelectTrigger id={id} aria-required={required}>
+ <SelectValue placeholder={isLoading ? 'Loading categories…' : 'Select a category'}>
+ {(v) => {
+ const category = categories.find((c) => c.id === v)
+ return category ? category.name : (v as string)
+ }}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {categories.map((c) => (
+ <SelectItem key={c.id} value={c.id}>
+ {c.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
</>
)
}
+function EditStoreCreditDialog({
+ customerId,
+ credit,
+ onOpenChange,
+}: {
+ customerId: string
+ credit: StoreCredit
+ onOpenChange: (open: boolean) => void
+}) {
+ // Server rejects amount changes once any of it has been used. Lock the
+ // field so the merchant doesn't submit a value that will only come back
+ // as a 422 store_credit_in_use.
+ const amountLocked = Number(credit.amount_used ?? 0) > 0
+
+ const mutation = useCustomerMutation(
+ customerId,
+ (params: Parameters<typeof adminClient.customers.storeCredits.update>[2]) =>
+ adminClient.customers.storeCredits.update(customerId, credit.id, params),
+ )
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ const params: Parameters<typeof adminClient.customers.storeCredits.update>[2] = {}
+
+ if (!amountLocked) {
+ const amountValue = String(fd.get('amount') ?? '').trim()
+ if (amountValue) params.amount = Number(amountValue)
+ }
+
+ const categoryId = String(fd.get('category_id') ?? '').trim()
+ if (categoryId) params.category_id = categoryId
+
+ params.memo = String(fd.get('memo') ?? '')
+
+ mutation.mutate(params, { onSuccess: () => onOpenChange(false) })
+ }
+
+ return (
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Edit Store Credit</DialogTitle>
+ <DialogDescription>
+ Update the memo, category, or amount.
+ {amountLocked &&
+ ' The amount cannot be changed because some of it has already been used.'}
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={handleSubmit}>
+ <DialogBody>
+ <FieldGroup>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="edit-sc-amount">Amount</FieldLabel>
+ <Input
+ id="edit-sc-amount"
+ name="amount"
+ type="number"
+ step="0.01"
+ defaultValue={credit.amount ?? ''}
+ disabled={amountLocked}
+ />
+ </Field>
+ <Field>
+ {/* Currency is locked: the API doesn't accept `currency`
+ on update (changing it on a partially-used credit
+ would invalidate amount_used / amount_remaining). We
+ surface it disabled so the merchant always sees which
+ currency the credit is in. */}
+ <FieldLabel htmlFor="edit-sc-currency">Currency</FieldLabel>
+ <CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor="edit-sc-category">Category</FieldLabel>
+ <StoreCreditCategorySelect
+ id="edit-sc-category"
+ name="category_id"
+ defaultValue={credit.category_id ?? ''}
+ />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="edit-sc-memo">Memo</FieldLabel>
+ <Textarea id="edit-sc-memo" name="memo" rows={3} defaultValue={credit.memo ?? ''} />
+ </Field>
+ </FieldGroup>
+ </DialogBody>
+ <DialogFooter>
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving…' : 'Save'}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
function IssueStoreCreditDialog({
customerId,
open,
@@ -890,12 +1096,12 @@ function IssueStoreCreditDialog({
</Field>
<Field>
<FieldLabel htmlFor="sc-currency">Currency</FieldLabel>
- <Input id="sc-currency" name="currency" defaultValue="USD" required />
+ <CurrencySelect id="sc-currency" name="currency" required />
</Field>
</div>
<Field>
- <FieldLabel htmlFor="sc-category">Category ID</FieldLabel>
- <Input id="sc-category" name="category_id" placeholder="e.g. 1" required />
+ <FieldLabel htmlFor="sc-category">Category</FieldLabel>
+ <StoreCreditCategorySelect id="sc-category" name="category_id" required />
</Field>
<Field>
<FieldLabel htmlFor="sc-memo">Memo</FieldLabel>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
index 7a697546eb..8db77a3645 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
@@ -1,24 +1,207 @@
-import { createFileRoute } from '@tanstack/react-router'
+import { useMutation } from '@tanstack/react-query'
+import { createFileRoute, useNavigate } from '@tanstack/react-router'
+import { PlusIcon } from 'lucide-react'
+import { type FormEvent, useState } from 'react'
+import { z } from 'zod/v4'
import { adminClient } from '@/client'
import { ExportButton } from '@/components/spree/export-button'
import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'
+import { TagCombobox } from '@/components/spree/tag-combobox'
+import { Button } from '@/components/ui/button'
+import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Input } from '@/components/ui/input'
+import {
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetFooter,
+ SheetHeader,
+ SheetTitle,
+} from '@/components/ui/sheet'
+import { Textarea } from '@/components/ui/textarea'
import '@/tables/customers'
+// Adds `?new=1` on top of the standard table search schema so the create sheet
+// is deep-linkable (`/customers?new=1`) and back-button friendly.
+const customersSearchSchema = resourceSearchSchema.extend({
+ new: z.coerce.boolean().optional(),
+})
+
export const Route = createFileRoute('/_authenticated/$storeId/customers/')({
- validateSearch: resourceSearchSchema,
+ validateSearch: customersSearchSchema,
component: CustomersPage,
})
function CustomersPage() {
- const searchParams = Route.useSearch()
+ const search = Route.useSearch() as z.infer<typeof customersSearchSchema>
+ const navigate = useNavigate()
+
+ const isCreating = !!search.new
+
+ function openCreate() {
+ navigate({ search: (prev: Record<string, unknown>) => ({ ...prev, new: true }) as never })
+ }
+
+ function closeSheet() {
+ navigate({
+ search: (prev: Record<string, unknown>) => {
+ const { new: _n, ...rest } = prev
+ return rest as never
+ },
+ })
+ }
+
+ return (
+ <>
+ <ResourceTable
+ tableKey="customers"
+ queryKey="customers"
+ queryFn={(params) => adminClient.customers.list(params)}
+ searchParams={search}
+ actions={(ctx) => (
+ <>
+ <ExportButton type="Spree::Exports::Customers" {...ctx} />
+ <Button size="sm" className="h-[2.125rem]" onClick={openCreate}>
+ <PlusIcon className="size-4" />
+ New Customer
+ </Button>
+ </>
+ )}
+ />
+ {isCreating && <NewCustomerSheet open onOpenChange={(o) => !o && closeSheet()} />}
+ </>
+ )
+}
+
+// ============================================================================
+// Create Sheet
+// ============================================================================
+
+function NewCustomerSheet({
+ open,
+ onOpenChange,
+}: {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+}) {
+ const { storeId } = Route.useParams()
+ const navigate = useNavigate()
+ const [tags, setTags] = useState<string[]>([])
+ const [acceptsMarketing, setAcceptsMarketing] = useState(false)
+
+ const createMutation = useMutation({
+ mutationFn: (params: Parameters<typeof adminClient.customers.create>[0]) =>
+ adminClient.customers.create(params),
+ onSuccess: (customer) => {
+ // Land on the new customer's detail page rather than leaving the user on
+ // the index — they almost always want to add an address or note next.
+ navigate({
+ to: '/$storeId/customers/$customerId',
+ params: { storeId, customerId: customer.id },
+ })
+ },
+ })
+
+ function handleSubmit(e: FormEvent<HTMLFormElement>) {
+ e.preventDefault()
+ const fd = new FormData(e.currentTarget)
+ const email = String(fd.get('email') ?? '').trim()
+ if (!email) return
+
+ const payload: Parameters<typeof adminClient.customers.create>[0] = { email }
+ const firstName = String(fd.get('first_name') ?? '').trim()
+ const lastName = String(fd.get('last_name') ?? '').trim()
+ const phone = String(fd.get('phone') ?? '').trim()
+ const internalNote = String(fd.get('internal_note') ?? '').trim()
+
+ if (firstName) payload.first_name = firstName
+ if (lastName) payload.last_name = lastName
+ if (phone) payload.phone = phone
+ if (internalNote) payload.internal_note = internalNote
+ if (tags.length) payload.tags = tags
+ payload.accepts_email_marketing = acceptsMarketing
+
+ createMutation.mutate(payload)
+ }
return (
- <ResourceTable
- tableKey="customers"
- queryKey="customers"
- queryFn={(params) => adminClient.customers.list(params)}
- searchParams={searchParams}
- actions={(ctx) => <ExportButton type="Spree::Exports::Customers" {...ctx} />}
- />
+ <Sheet open={open} onOpenChange={onOpenChange}>
+ <SheetContent>
+ <SheetHeader>
+ <SheetTitle>New Customer</SheetTitle>
+ <SheetDescription>
+ No password is set and no email is sent. Trigger a password reset from the customer's
+ page if they need to sign in.
+ </SheetDescription>
+ </SheetHeader>
+ <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
+ <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="email">Email</FieldLabel>
+ <Input id="email" name="email" type="email" required autoFocus />
+ </Field>
+ <div className="grid grid-cols-2 gap-3">
+ <Field>
+ <FieldLabel htmlFor="first_name">First name</FieldLabel>
+ <Input id="first_name" name="first_name" />
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="last_name">Last name</FieldLabel>
+ <Input id="last_name" name="last_name" />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor="phone">Phone</FieldLabel>
+ <Input id="phone" name="phone" />
+ </Field>
+ <Field>
+ <FieldLabel>Tags</FieldLabel>
+ <TagCombobox taggableType="Spree::User" value={tags} onChange={setTags} />
+ </Field>
+ <Field>
+ <label className="flex items-center gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="accepts_email_marketing"
+ checked={acceptsMarketing}
+ onChange={(e) => setAcceptsMarketing(e.target.checked)}
+ />
+ Subscribed to marketing
+ </label>
+ </Field>
+ <Field>
+ <FieldLabel htmlFor="internal_note">Internal note</FieldLabel>
+ <Textarea
+ id="internal_note"
+ name="internal_note"
+ rows={4}
+ placeholder="Staff-only context about this customer…"
+ />
+ </Field>
+ {createMutation.error && (
+ <p className="text-sm text-destructive">
+ {(createMutation.error as Error).message}
+ </p>
+ )}
+ </FieldGroup>
+ </div>
+ <SheetFooter>
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => onOpenChange(false)}
+ disabled={createMutation.isPending}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" size="sm" disabled={createMutation.isPending}>
+ {createMutation.isPending ? 'Creating…' : 'Create Customer'}
+ </Button>
+ </SheetFooter>
+ </form>
+ </SheetContent>
+ </Sheet>
)
}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
index 463ad03319..e116578953 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/customers_controller.rb
@@ -7,6 +7,13 @@ module Spree
def create
@resource = Spree.user_class.new(permitted_params)
+ # Admin-created customers don't pick a password upfront — they
+ # claim the account via password reset later.
+ # `Spree::UserMethods` exposes `skip_password_validation` so
+ # Devise's `:validatable` lets a nil credential through on this
+ # code path. Storefront registration never sets the flag, so
+ # customer self-signup still requires a password.
+ @resource.skip_password_validation = true if @resource.password.blank?
authorize!(:create, @resource)
if @resource.save
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/customers_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/customers_controller_spec.rb
index 26204d706e..2b27310ad3 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/customers_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/customers_controller_spec.rb
@@ -85,6 +85,31 @@ RSpec.describe Spree::Api::V3::Admin::CustomersController, type: :controller do
expect(response).to have_http_status(:unprocessable_content)
end
end
+
+ # Admin-created customers don't pick a password upfront — the merchant
+ # adds the profile and the customer claims the account via a separate
+ # password-reset flow. The host app's `Spree::User` is Devise-
+ # validatable; `Spree::UserMethods` exposes `skip_password_validation`
+ # so the admin controller can opt out of the presence check on create.
+ # The Store API registration path stays untouched (see store
+ # customers_controller spec).
+ context 'without password' do
+ let(:no_password_params) { { email: '[email protected]', first_name: 'Pat' } }
+
+ it 'creates the customer' do
+ expect { post :create, params: no_password_params, as: :json }.
+ to change(Spree.user_class, :count).by(1)
+
+ expect(response).to have_http_status(:created)
+ end
+
+ it 'leaves the customer with no usable credential' do
+ post :create, params: no_password_params, as: :json
+
+ created = Spree.user_class.find_by_prefix_id(json_response['id'])
+ expect(created.encrypted_password).to be_blank
+ end
+ end
end
describe 'PATCH #update' do
@@ -103,6 +128,24 @@ RSpec.describe Spree::Api::V3::Admin::CustomersController, type: :controller do
expect(response).to have_http_status(:ok)
expect(customer.reload.tag_list).to contain_exactly('new-tag')
end
+
+ # PATCH without a password must not blank an existing credential. Devise's
+ # `password_required?` already skips presence on persisted records when
+ # password is nil, so this is the regression guard for that contract —
+ # ensures a profile-only edit doesn't accidentally invalidate the
+ # customer's ability to log in.
+ context 'without password' do
+ it 'updates profile fields without touching the existing credential' do
+ original_digest = customer.encrypted_password
+ expect(original_digest).to be_present
+
+ patch :update, params: { id: customer.prefixed_id, first_name: 'Updated' }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(customer.reload.first_name).to eq('Updated')
+ expect(customer.encrypted_password).to eq(original_digest)
+ end
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/core/app/models/concerns/spree/user_methods.rb b/spree/core/app/models/concerns/spree/user_methods.rb
index e50337d13e..dfd7d99c09 100644
--- a/spree/core/app/models/concerns/spree/user_methods.rb
+++ b/spree/core/app/models/concerns/spree/user_methods.rb
@@ -12,9 +12,35 @@ module Spree
include Spree::Searchable
include Spree::Publishable
+ # Opt-in escape hatch for admin-side customer creation. When the host
+ # `Spree::User` includes Devise's `:validatable`, password presence is
+ # enforced on every create; admin-created customers don't pick a
+ # password upfront — they claim the account later via password reset.
+ # The admin Customers controller flips `skip_password_validation = true`
+ # when no password was supplied; the storefront registration path never
+ # sets it, so customer self-signup still requires a password.
+ #
+ # Prepended (not just defined) so it sits above Devise's own
+ # `password_required?` and can fall through with `super` when the flag
+ # isn't set. On `LegacyUser` (gem default, no Devise) `super` raises
+ # NoMethodError if invoked — but the early return covers the only
+ # branch that ever reaches this method on that path, and `LegacyUser`
+ # doesn't call `password_required?` at all, so the override is a no-op
+ # there.
+ module SkipPasswordValidation
+ def password_required?
+ return false if skip_password_validation && encrypted_password.blank? && password.blank?
+ super
+ end
+ end
+
included do
has_prefix_id :cus # Stripe: cus_
+ attr_accessor :skip_password_validation
+
+ prepend SkipPasswordValidation
+
# Enable lifecycle events for user models
publishes_lifecycle_events