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
Added issuing store credits from Loyalty → Store Credits (#14818)
Damian Legawiec7fa7a647d537
diff --git a/.changeset/dashboard-issue-store-credit.md b/.changeset/dashboard-issue-store-credit.mdnew file mode 100644index 0000000000..403550de5a--- /dev/null+++ b/.changeset/dashboard-issue-store-credit.md@@ -0,0 +1,5 @@+---+"@spree/dashboard": patch+---++Added an "Issue store credit" button to Loyalty → Store Credits, so a credit can be issued to any customer without opening their profile first. The page also links to its documentation now.diff --git a/.changeset/dashboard-picker-refetch.md b/.changeset/dashboard-picker-refetch.mdnew file mode 100644index 0000000000..ad83c237db--- /dev/null+++ b/.changeset/dashboard-picker-refetch.md@@ -0,0 +1,5 @@+---+"@spree/dashboard-core": patch+---++Search pickers (customers, products, sellers and others) now search again each time they open, so a record created elsewhere in the dashboard shows up without reloading the page.diff --git a/docs/user/loyalty/store-credits-list.mdx b/docs/user/loyalty/store-credits-list.mdxindex 61ae3f2ebd..8d093462b7 100644--- a/docs/user/loyalty/store-credits-list.mdx+++ b/docs/user/loyalty/store-credits-list.mdx@@ -3,13 +3,15 @@ title: "Store Credits List"description: "See how much your store owes in prepaid balances, to whom, and why."----A store credit is money your store owes a customer. Issued one at a time from-a customer profile, they are easy to lose track of: without a place to see them+A store credit is money your store owes a customer. Spread across many+customers, credits are easy to lose track of: without a place to see themtogether, answering "how much do we owe in total" means opening every customerin turn.**Loyalty → Store Credits** shows every credit in your store on one page, with-the outstanding balance summarised above it.+the outstanding balance summarised above it. You can also issue a new credit to+any customer from here with **Issue store credit** - see+[Issue Store Credits](/user/loyalty/store-credits).## Read the Outstanding Balancediff --git a/docs/user/loyalty/store-credits.mdx b/docs/user/loyalty/store-credits.mdxindex ee977bf7f3..16a0ad1712 100644--- a/docs/user/loyalty/store-credits.mdx+++ b/docs/user/loyalty/store-credits.mdx@@ -9,62 +9,45 @@ In more advanced use cases, store credits can serve as the primary payment metho## How to Issue Store Credits-To issue store credits, navigate to **Customers** in the admin dashboard.+You can issue a store credit from two places:-+- **Loyalty → Store Credits** - click **Issue store credit** and choose the+ customer to credit. Use this when you already know who should receive the+ credit and don't want to open their profile first.+- **Customers → a customer's profile** - click **Issue store credit** in the+ **Store credit** card. The credit goes to that customer.-Find and click on the customer to open their profile page.+Both open the same form:-+- **Customer** - who receives the credit (only asked on the Store Credits page)+- **Amount** - the value of the store credit+- **Currency** - which currency the credit is in, if your store sells in more+ than one+- **Memo** - an optional internal note explaining why you issued the credit-You can issue store credit in two ways:-- Click the **three-dot menu** in the top right corner and select **Add Store Credit**-- Or click **Add Store Credit** directly from the analytics section at the top of the customer profile----Clicking on either of these will redirect you to the store credit creation form.--## Configure the Store Credit----Complete the following fields:-- **Amount** - The value of the store credit-- **Currency** - Select the currency (if your store supports multiple currencies)-- **Memo** - Optional internal note explaining the reason for issuing the credit--Click **Create** to assign the credit. The balance will immediately be available to the customer and visible in the **Store Credits** section of the customer profile.+Click **Issue store credit** to save. The balance is available to the customer+straight away. When you issue from the Store Credits page, the new credit opens+so you can check it.## Edit Store Credits---To edit a store credit assignment:+1. Open the customer's profile+2. In the **Store credit** card, open the menu (**⋮**) on the credit's row+3. Click **Edit**, change the amount or memo, and click **Save**-1. Navigate to the customer profile-2. Scroll to the **Store Credits** section-3. Click on a store credit assignment to be redirected to that credit’s form-4. Click **Edit** in the Details section-5. Modify the store credit assignment as necessary and click **Update**+You can't change the currency of a credit. Once a customer has spent part of a+credit, its amount is locked too; only the memo can change.## Delete Store Credits---To remove a store credit:--1. Navigate to the customer profile-2. Scroll to the **Store Credits** section-3. Click on a store credit assignment to be redirected to that credit’s form-4. Click the **three-dot menu** in the top-right corner-5. Click **Delete** from the menu+1. Open the customer's profile+2. In the **Store credit** card, open the menu (**⋮**) on the credit's row+3. Click **Delete** and confirm-<Note>Deleting store credit will permanently remove the assigned balance from the customer’s account.</Note>+<Note>Deleting a store credit permanently removes the balance from the customer's account.</Note>## See Every Customer's Credit in One Place-Issuing and editing a credit happens on the customer profile, but to see what-your store owes in total, go to **Loyalty → Store Credits**. See+To see what your store owes in total, go to **Loyalty → Store Credits**. See[Store Credits List](/user/loyalty/store-credits-list) for how to read andfilter it.diff --git a/packages/dashboard-core/src/components/resource-combobox.tsx b/packages/dashboard-core/src/components/resource-combobox.tsxindex 5a985413a1..76ea532bc2 100644--- a/packages/dashboard-core/src/components/resource-combobox.tsx+++ b/packages/dashboard-core/src/components/resource-combobox.tsx@@ -105,7 +105,10 @@ export function ResourceCombobox<T extends ComboboxOption>({const { data: searchData } = useQuery({queryKey: [queryKey, tenantId, 'search', trimmedQuery],queryFn: () => search(trimmedQuery),- staleTime: 30_000,+ // The cache key is the picker's own, not the resource's, so a mutation+ // elsewhere (a customer created on another page) never invalidates it.+ // Every search refetches; cached rows for a repeated term still paint first.+ staleTime: 0,})// Hydrate the currently selected ID into a record so the trigger showsdiff --git a/packages/dashboard/e2e/companies.spec.ts b/packages/dashboard/e2e/companies.spec.tsindex 661a009d28..958ede2f85 100644--- a/packages/dashboard/e2e/companies.spec.ts+++ b/packages/dashboard/e2e/companies.spec.ts@@ -135,7 +135,7 @@ test.describe('companies', () => {.getByRole('button', { name: /^save$/i }).click()- await expect(page.getByText(/state \/ province is required/i)).toBeVisible({+ await expect(page.getByText(/state \/ province (is required|can't be blank)/i)).toBeVisible({timeout: 15_000,})await expect(addressBook.getByText('1 Test Street')).toHaveCount(0)diff --git a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts b/packages/dashboard/e2e/seller-invitation-acceptance.spec.tsindex 5f5ade81c9..d6aee6ae09 100644--- a/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts+++ b/packages/dashboard/e2e/seller-invitation-acceptance.spec.ts@@ -79,7 +79,9 @@ test.describe('seller invitation lifecycle', () => {// panel has to carry too — keys defined only in the operator's bundle// render as their own name here.await inviteePage.goto(`${SELLER_PANEL}${new URL(inviteePage.url()).pathname}/settings`)- await expect(inviteePage.getByText('Settings').first()).toBeVisible({ timeout: 20_000 })+ await expect(inviteePage.getByRole('heading', { name: /^settings$/i })).toBeVisible({+ timeout: 20_000,+ })await expect(inviteePage.getByText(/admin\.settings_page/)).toHaveCount(0)} finally {await inviteeContext.close()diff --git a/packages/dashboard/e2e/store-credits.spec.ts b/packages/dashboard/e2e/store-credits.spec.tsindex 1b09d908f3..cea1774ce3 100644--- a/packages/dashboard/e2e/store-credits.spec.ts+++ b/packages/dashboard/e2e/store-credits.spec.ts@@ -35,6 +35,58 @@ test.describe('store credits', () => {await expect(row.getByText('$40.00').first()).toBeVisible()})+ test('issues a credit to a customer picked on the page', async ({ page }) => {+ const creds = await login(page)+ const memo = `E2E loyalty credit ${Date.now()}`++ await page.goto(STORE_CREDITS_PATH(creds.store_id))+ await expect(page.getByRole('link', { name: /learn more/i })).toBeVisible({ timeout: 15_000 })+ await page.getByRole('button', { name: /issue store credit/i }).click()++ const dialog = page.getByRole('dialog')+ await dialog.getByPlaceholder(/search customers/i).fill(FIXTURE_PROMO_CUSTOMER_EMAIL)+ await page+ .getByRole('option', { name: new RegExp(escapeRegex(FIXTURE_PROMO_CUSTOMER_EMAIL)) })+ .first()+ .click()+ await dialog.getByLabel(/amount/i).fill('15')+ await dialog.getByLabel(/memo/i).fill(memo)+ await dialog.getByRole('button', { name: /^issue store credit$/i }).click()++ const sheet = page.getByRole('dialog')+ await expect(sheet.getByText(memo)).toBeVisible({ timeout: 15_000 })+ await expect(sheet.getByText('$15.00').first()).toBeVisible()+ })++ test('offers a customer created after the picker last searched', async ({ page }) => {+ const creds = await login(page)+ const email = `e2e-fresh-${Date.now()}@example.com`++ await page.goto(STORE_CREDITS_PATH(creds.store_id))+ await page.getByRole('button', { name: /issue store credit/i }).click()+ const dialog = page.getByRole('dialog')+ await dialog.getByPlaceholder(/search customers/i).fill(email)+ await expect(page.getByText(/no customers match/i)).toBeVisible({ timeout: 15_000 })+ await page.keyboard.press('Escape')+ await page.keyboard.press('Escape')+ await expect(dialog).toHaveCount(0)++ const created = await page.request.post('/api/v3/admin/customers', {+ headers: { Authorization: `Bearer ${creds.accessToken}` },+ data: { email },+ })+ expect(created.status(), await created.text()).toBe(201)++ await page.getByRole('button', { name: /issue store credit/i }).click()+ await page+ .getByRole('dialog')+ .getByPlaceholder(/search customers/i)+ .fill(email)+ await expect(page.getByRole('option', { name: new RegExp(escapeRegex(email)) })).toBeVisible({+ timeout: 15_000,+ })+ })+test('opens a credit and follows it to the customer', async ({ page }) => {const creds = await login(page)const memo = `E2E refund credit ${Date.now()}`diff --git a/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx b/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsxindex 74d424a454..41d5d3abae 100644--- a/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx+++ b/packages/dashboard/src/components/spree/customers/customer-store-credits-card.tsx@@ -5,7 +5,6 @@ import {currencyParts,mapSpreeErrorsToForm,normalizeMoneyInput,- useStore,} from '@spree/dashboard-core'import {Badge,@@ -44,22 +43,20 @@ import {useConfirm,} from '@spree/dashboard-ui'import { EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'-import { useEffect, useState } from 'react'-import { Controller, useForm } from 'react-hook-form'+import { useState } from 'react'+import { useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useCurrencyLocale } from '../../../hooks/use-currency-locale'import {type StoreCreditUpdateParams,- useCreateCustomerStoreCredit,useDeleteCustomerStoreCredit,useUpdateCustomerStoreCredit,} from '../../../hooks/use-customer-store-credits'import {type EditStoreCreditFormValues,editStoreCreditFormSchema,- type IssueStoreCreditFormValues,- issueStoreCreditFormSchema,} from '../../../schemas/store-credit'+import { IssueStoreCreditDialog } from '../store-credits/issue-store-credit-dialog'export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {const { t } = useTranslation()@@ -308,158 +305,3 @@ function EditStoreCreditDialog({</Dialog>)}--function IssueStoreCreditDialog({- customerId,- open,- onOpenChange,-}: {- customerId: string- open: boolean- onOpenChange: (open: boolean) => void-}) {- const { t } = useTranslation()- // Seed `currency` with the store default so the merchant doesn't have to- // pick one explicitly — `CurrencySelect` displays it but no longer commits- // it via onChange, so the form value needs to start populated.- const { defaultCurrency } = useStore()- const form = useForm<IssueStoreCreditFormValues>({- // eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(issueStoreCreditFormSchema) as any,- defaultValues: { amount: '', currency: defaultCurrency, memo: '' },- })- const { errors } = form.formState-- const mutation = useCreateCustomerStoreCredit(customerId)- const localeForCurrency = useCurrencyLocale()- const selectedCurrency = form.watch('currency')- const { symbol } = currencyParts(selectedCurrency, localeForCurrency(selectedCurrency) || 'en')-- // Clear any prior submission state when the dialog re-opens so a fresh form- // is presented (otherwise stale "Issue $20" values linger across opens).- useEffect(() => {- if (open) {- form.reset({ amount: '', currency: defaultCurrency, memo: '' })- }- }, [open, form, defaultCurrency])-- // Switching currency re-displays the amount in the new currency's locale- // format, so the value the merchant sees always matches the locale it will be- // normalized under on submit. Without this, `25.00` typed under USD would be- // re-read under EUR's `de` locale (where `.` groups thousands) and persist as- // 2500. Canonicalize from the old locale, then swap to the new locale's- // decimal separator.- function handleCurrencyChange(- next: string,- field: { value: string; onChange: (v: string) => void },- ) {- const prev = field.value- field.onChange(next)- const raw = form.getValues('amount')?.trim()- if (!raw) return- const canonical = normalizeMoneyInput(raw, localeForCurrency(prev) || 'en')- const { decimal } = currencyParts(next, localeForCurrency(next) || 'en')- form.setValue('amount', decimal === '.' ? canonical : canonical.replace('.', decimal))- }-- async function onSubmit(values: IssueStoreCreditFormValues) {- try {- await mutation.mutateAsync({- // Normalize the merchant's localized input (entered under the selected- // currency's market locale) to the canonical `"1234.56"` the API- // expects. The server never parses comma-vs-period.- amount: normalizeMoneyInput(values.amount, localeForCurrency(values.currency) || 'en'),- currency: values.currency,- memo: values.memo || undefined,- })- onOpenChange(false)- } catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) throw err- }- }-- return (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent>- <DialogHeader>- <DialogTitle>{t('admin.pages.customers.detail.issue_credit')}</DialogTitle>- <DialogDescription>- {t('admin.customers.detail.store_credit.add_description')}- </DialogDescription>- </DialogHeader>- <form onSubmit={form.handleSubmit(onSubmit)}>- <DialogBody>- {errors.root?.message && (- <p className="text-sm text-destructive" role="alert">- {errors.root.message}- </p>- )}- <FieldGroup>- <div className="grid grid-cols-2 gap-3">- <Field>- <FieldLabel htmlFor="sc-amount">- {t('admin.fields.store_credit.amount.label')}- </FieldLabel>- <InputGroup>- <InputGroupAddon>- <InputGroupText>{symbol}</InputGroupText>- </InputGroupAddon>- <InputGroupInput- id="sc-amount"- type="text"- inputMode="decimal"- required- aria-invalid={!!errors.amount || undefined}- {...form.register('amount')}- />- </InputGroup>- <FieldError errors={[errors.amount]} />- </Field>- <Field>- <FieldLabel htmlFor="sc-currency">- {t('admin.fields.store_credit.currency.label')}- </FieldLabel>- <Controller- name="currency"- control={form.control}- render={({ field }) => (- <CurrencySelect- id="sc-currency"- value={field.value || ''}- onChange={(next) => handleCurrencyChange(next, field)}- required- />- )}- />- </Field>- </div>- <Field>- <FieldLabel htmlFor="sc-memo">- {t('admin.fields.store_credit.memo.label')}- </FieldLabel>- <Textarea- id="sc-memo"- rows={3}- placeholder={t('admin.fields.store_credit.memo.placeholder')}- aria-invalid={!!errors.memo || undefined}- {...form.register('memo')}- />- <FieldError errors={[errors.memo]} />- </Field>- </FieldGroup>- </DialogBody>- <DialogFooter>- <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>- {t('admin.actions.cancel')}- </Button>- <Button type="submit" disabled={mutation.isPending}>- {mutation.isPending- ? t('admin.actions.saving')- : t('admin.pages.customers.detail.issue_credit')}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}diff --git a/packages/dashboard/src/components/spree/store-credits/issue-store-credit-dialog.tsx b/packages/dashboard/src/components/spree/store-credits/issue-store-credit-dialog.tsxnew file mode 100644index 0000000000..1057e93550--- /dev/null+++ b/packages/dashboard/src/components/spree/store-credits/issue-store-credit-dialog.tsx@@ -0,0 +1,229 @@+import { zodResolver } from '@hookform/resolvers/zod'+import type { Customer, StoreCredit } from '@spree/admin-sdk'+import {+ CurrencySelect,+ currencyParts,+ mapSpreeErrorsToForm,+ normalizeMoneyInput,+ ResourceCombobox,+ useStore,+} from '@spree/dashboard-core'+import {+ Button,+ Dialog,+ DialogBody,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ Field,+ FieldError,+ FieldGroup,+ FieldLabel,+ InputGroup,+ InputGroupAddon,+ InputGroupInput,+ InputGroupText,+ Textarea,+} from '@spree/dashboard-ui'+import { useEffect } from 'react'+import { Controller, useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'+import { useCurrencyLocale } from '../../../hooks/use-currency-locale'+import { useCreateCustomerStoreCredit } from '../../../hooks/use-customer-store-credits'+import { customerAutocompleteProps } from '../../../hooks/use-customers'+import {+ type IssueStoreCreditFormValues,+ issueStoreCreditFormSchema,+} from '../../../schemas/store-credit'++/**+ * Issues a store credit. Opened from a customer profile it credits that+ * customer; opened without a `customerId` it asks which customer to credit.+ */+export function IssueStoreCreditDialog({+ customerId,+ open,+ onOpenChange,+ onIssued,+}: {+ customerId?: string+ open: boolean+ onOpenChange: (open: boolean) => void+ onIssued?: (credit: StoreCredit) => void+}) {+ const { t } = useTranslation()+ // Seed `currency` with the store default so the merchant doesn't have to+ // pick one explicitly — `CurrencySelect` displays it but no longer commits+ // it via onChange, so the form value needs to start populated.+ const { defaultCurrency } = useStore()+ const emptyValues = {+ customer_id: customerId ?? '',+ amount: '',+ currency: defaultCurrency,+ memo: '',+ }+ const form = useForm<IssueStoreCreditFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(issueStoreCreditFormSchema) as any,+ defaultValues: emptyValues,+ })+ const { errors } = form.formState++ const mutation = useCreateCustomerStoreCredit()+ const localeForCurrency = useCurrencyLocale()+ const selectedCurrency = form.watch('currency')+ const { symbol } = currencyParts(selectedCurrency, localeForCurrency(selectedCurrency) || 'en')++ // Clear any prior submission state when the dialog re-opens so a fresh form+ // is presented (otherwise stale "Issue $20" values linger across opens).+ // biome-ignore lint/correctness/useExhaustiveDependencies: reset only on open+ useEffect(() => {+ if (open) form.reset(emptyValues)+ }, [open, form, defaultCurrency, customerId])++ // Switching currency re-displays the amount in the new currency's locale+ // format, so the value the merchant sees always matches the locale it will be+ // normalized under on submit. Without this, `25.00` typed under USD would be+ // re-read under EUR's `de` locale (where `.` groups thousands) and persist as+ // 2500. Canonicalize from the old locale, then swap to the new locale's+ // decimal separator.+ function handleCurrencyChange(+ next: string,+ field: { value: string; onChange: (v: string) => void },+ ) {+ const prev = field.value+ field.onChange(next)+ const raw = form.getValues('amount')?.trim()+ if (!raw) return+ const canonical = normalizeMoneyInput(raw, localeForCurrency(prev) || 'en')+ const { decimal } = currencyParts(next, localeForCurrency(next) || 'en')+ form.setValue('amount', decimal === '.' ? canonical : canonical.replace('.', decimal))+ }++ async function onSubmit(values: IssueStoreCreditFormValues) {+ try {+ const credit = await mutation.mutateAsync({+ customerId: values.customer_id,+ // Normalize the merchant's localized input (entered under the selected+ // currency's market locale) to the canonical `"1234.56"` the API+ // expects. The server never parses comma-vs-period.+ amount: normalizeMoneyInput(values.amount, localeForCurrency(values.currency) || 'en'),+ currency: values.currency,+ memo: values.memo || undefined,+ })+ onOpenChange(false)+ onIssued?.(credit)+ } catch (err) {+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>{t('admin.pages.customers.detail.issue_credit')}</DialogTitle>+ <DialogDescription>+ {customerId+ ? t('admin.customers.detail.store_credit.add_description')+ : t('admin.store_credits.issue_description')}+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <DialogBody>+ {errors.root?.message && (+ <p className="text-sm text-destructive" role="alert">+ {errors.root.message}+ </p>+ )}+ <FieldGroup>+ {!customerId && (+ <Field>+ <FieldLabel htmlFor="sc-customer">+ {t('admin.fields.customer_id.label')}+ </FieldLabel>+ <Controller+ name="customer_id"+ control={form.control}+ render={({ field }) => (+ <ResourceCombobox<Customer>+ {...customerAutocompleteProps('store-credit-customer-picker')}+ id="sc-customer"+ value={field.value || undefined}+ onChange={(id) => field.onChange(id ?? '')}+ />+ )}+ />+ <FieldError errors={[errors.customer_id]} />+ </Field>+ )}+ <div className="grid grid-cols-2 gap-3">+ <Field>+ <FieldLabel htmlFor="sc-amount">+ {t('admin.fields.store_credit.amount.label')}+ </FieldLabel>+ <InputGroup>+ <InputGroupAddon>+ <InputGroupText>{symbol}</InputGroupText>+ </InputGroupAddon>+ <InputGroupInput+ id="sc-amount"+ type="text"+ inputMode="decimal"+ required+ aria-invalid={!!errors.amount || undefined}+ {...form.register('amount')}+ />+ </InputGroup>+ <FieldError errors={[errors.amount]} />+ </Field>+ <Field>+ <FieldLabel htmlFor="sc-currency">+ {t('admin.fields.store_credit.currency.label')}+ </FieldLabel>+ <Controller+ name="currency"+ control={form.control}+ render={({ field }) => (+ <CurrencySelect+ id="sc-currency"+ value={field.value || ''}+ onChange={(next) => handleCurrencyChange(next, field)}+ required+ />+ )}+ />+ </Field>+ </div>+ <Field>+ <FieldLabel htmlFor="sc-memo">+ {t('admin.fields.store_credit.memo.label')}+ </FieldLabel>+ <Textarea+ id="sc-memo"+ rows={3}+ placeholder={t('admin.fields.store_credit.memo.placeholder')}+ aria-invalid={!!errors.memo || undefined}+ {...form.register('memo')}+ />+ <FieldError errors={[errors.memo]} />+ </Field>+ </FieldGroup>+ </DialogBody>+ <DialogFooter>+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ {t('admin.actions.cancel')}+ </Button>+ <Button type="submit" disabled={mutation.isPending}>+ {mutation.isPending+ ? t('admin.actions.saving')+ : t('admin.pages.customers.detail.issue_credit')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/packages/dashboard/src/hooks/use-customer-store-credits.ts b/packages/dashboard/src/hooks/use-customer-store-credits.tsindex e85f04d044..9b90786dda 100644--- a/packages/dashboard/src/hooks/use-customer-store-credits.ts+++ b/packages/dashboard/src/hooks/use-customer-store-credits.ts@@ -8,11 +8,11 @@ export type { StoreCreditUpdateParams }// The `amount` arrives already normalized to canonical `"1234.56"` form — the// form converts the merchant's localized input client-side (see// docs/plans/5.5-client-side-money-normalization.md), so no request locale.-export function useCreateCustomerStoreCredit(customerId: string) {+export function useCreateCustomerStoreCredit() {return useResourceMutation({- mutationFn: (params: StoreCreditCreateParams) =>+ mutationFn: ({ customerId, ...params }: StoreCreditCreateParams & { customerId: string }) =>adminClient.customers.storeCredits.create(customerId, params),- invalidate: [['customers', customerId]],+ invalidate: [['customers'], ['store-credits']],successMessage: i18n.t('admin.messages.store_credit_saved'),})}@@ -21,7 +21,7 @@ export function useUpdateCustomerStoreCredit(customerId: string, creditId: strinreturn useResourceMutation({mutationFn: (params: StoreCreditUpdateParams) =>adminClient.customers.storeCredits.update(customerId, creditId, params),- invalidate: [['customers', customerId]],+ invalidate: [['customers', customerId], ['store-credits']],successMessage: i18n.t('admin.messages.store_credit_saved'),})}@@ -29,7 +29,7 @@ export function useUpdateCustomerStoreCredit(customerId: string, creditId: strinexport function useDeleteCustomerStoreCredit(customerId: string) {return useResourceMutation({mutationFn: (id: string) => adminClient.customers.storeCredits.delete(customerId, id),- invalidate: [['customers', customerId]],+ invalidate: [['customers', customerId], ['store-credits']],successMessage: i18n.t('admin.messages.store_credit_removed'),})}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex b0a5baeb9a..7337329011 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -6073,8 +6073,9 @@},"table": {"search_placeholder": "البحث في الملاحظات…",- "empty": "لا توجد أرصدة بعد. أصدر رصيدًا من ملف العميل."+ "empty": "لا توجد أرصدة بعد."},+ "issue_description": "اختر عميلًا والمبلغ الذي تريد إضافته إلى حسابه.","no_customer": "بدون عميل","page": {"subtitle": "ما يدين به المتجر من أرصدة مدفوعة مسبقًا لجميع العملاء."diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 4bda4dfa5c..f5c18019e1 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -6033,8 +6033,9 @@},"table": {"search_placeholder": "Notizen durchsuchen…",- "empty": "Noch kein Guthaben. Stellen Sie eines im Kundenprofil aus."+ "empty": "Noch kein Guthaben."},+ "issue_description": "Wählen Sie einen Kunden und den Betrag, der seinem Konto gutgeschrieben wird.","no_customer": "Kein Kunde","page": {"subtitle": "Was der Shop an Guthaben schuldet, über alle Kunden hinweg."diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 6aa8a061fa..1c7f7b6039 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -6033,8 +6033,9 @@},"table": {"search_placeholder": "Search memos…",- "empty": "No store credits yet. Issue one from a customer profile."+ "empty": "No store credits yet."},+ "issue_description": "Choose a customer and the amount to add to their account.","no_customer": "No customer","page": {"subtitle": "What the store owes in prepaid balances, across every customer."diff --git a/packages/dashboard/src/locales/es.json b/packages/dashboard/src/locales/es.jsonindex 18494a5b07..df7c64773d 100644--- a/packages/dashboard/src/locales/es.json+++ b/packages/dashboard/src/locales/es.json@@ -5003,8 +5003,9 @@},"table": {"search_placeholder": "Buscar notas…",- "empty": "Todavía no hay créditos de tienda. Emití uno desde el perfil de un cliente."+ "empty": "Todavía no hay créditos de tienda."},+ "issue_description": "Elegí un cliente y el monto que querés sumar a su cuenta.","no_customer": "Sin cliente","page": {"subtitle": "Lo que la tienda debe en saldos prepagos, en todos los clientes."diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 768d10353a..ecef7cf96b 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -6033,8 +6033,9 @@},"table": {"search_placeholder": "Rechercher dans les notes…",- "empty": "Aucun avoir. Émettez-en un depuis une fiche client."+ "empty": "Aucun avoir."},+ "issue_description": "Choisissez un client et le montant à ajouter à son compte.","no_customer": "Aucun client","page": {"subtitle": "Total des avoirs dus par la boutique, tous clients confondus."diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 042cdc0ebd..86de3b425a 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -6101,8 +6101,9 @@},"table": {"search_placeholder": "Szukaj w notatkach…",- "empty": "Brak środków. Wystaw je z profilu klienta."+ "empty": "Brak środków."},+ "issue_description": "Wybierz klienta i kwotę, którą chcesz dodać do jego konta.","no_customer": "Brak klienta","page": {"subtitle": "Ile sklep jest winien w środkach, w rozbiciu na wszystkich klientów."diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 0356bb0477..b65f464d7b 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -6020,8 +6020,9 @@},"table": {"search_placeholder": "搜索备注…",- "empty": "暂无店铺信用。可从客户资料中发放。"+ "empty": "暂无店铺信用。"},+ "issue_description": "选择客户以及要添加到其账户的金额。","no_customer": "无客户","page": {"subtitle": "店铺在所有客户中欠下的预付余额总额。"diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsxindex 61344f0226..629d7678f1 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx@@ -1,5 +1,11 @@import type { StoreCredit, StoreCreditCurrencyTotal } from '@spree/admin-sdk'-import { PageHeader, ResourceTable, resourceSearchSchema } from '@spree/dashboard-core'+import {+ Can,+ PageHeader,+ ResourceTable,+ resourceSearchSchema,+ Subject,+} from '@spree/dashboard-core'import {Badge,Button,@@ -17,11 +23,13 @@ import {Skeleton,useRowClickBridge,} from '@spree/dashboard-ui'+import { PlusIcon } from '@spree/dashboard-ui/icons'import { useIsFetching } from '@tanstack/react-query'import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'+import { IssueStoreCreditDialog } from '../../../../components/spree/store-credits/issue-store-credit-dialog'import {listStoreCredits,useStoreCredit,@@ -44,16 +52,15 @@ export const Route = createFileRoute('/_authenticated/$storeId/loyalty/store-creconst LIST_EXPAND = ['customer', 'created_by']/**- * What the store owes in prepaid balances, across every customer.- *- * Read-only: a credit belongs to one customer and is issued, edited and- * deleted on that customer's profile. This page answers how much is owed, to- * whom, and why.+ * What the store owes in prepaid balances, across every customer, and where a+ * credit can be issued to any of them. Editing and deleting stay on the+ * customer's profile. This page answers how much is owed, to whom, and why.*/function StoreCreditsPage() {const { t } = useTranslation()const search = Route.useSearch()const navigate = useNavigate()+ const [issueOpen, setIssueOpen] = useState(false)// Mirrored from the list response rather than fetched separately, so the// cards always describe the same filtered set as the rows. `queryFn` only// runs on an actual fetch, so the last totals are kept across a cached@@ -86,8 +93,17 @@ function StoreCreditsPage() {<div className="flex flex-col gap-6"><PageHeadertitle={t('admin.nav.store_credits')}- subtitle={t('admin.store_credits.page.subtitle')}+ description={t('admin.store_credits.page.subtitle')}+ docsPath="loyalty/store-credits-list"sticky={false}+ actions={+ <Can I="create" a={Subject.StoreCredit}>+ <Button size="sm" onClick={() => setIssueOpen(true)}>+ <PlusIcon className="size-4" />+ {t('admin.pages.customers.detail.issue_credit')}+ </Button>+ </Can>+ }/><OutstandingTotals totals={totals} stale={refetching} />@@ -109,6 +125,12 @@ function StoreCreditsPage() {/></div>+ <IssueStoreCreditDialog+ open={issueOpen}+ onOpenChange={setIssueOpen}+ onIssued={(credit) => openCredit(credit.id)}+ />+{search.credit && (// Keyed by the credit so a deep link from one credit to another// remounts the sheet rather than showing the previous ledger page.diff --git a/packages/dashboard/src/schemas/store-credit.ts b/packages/dashboard/src/schemas/store-credit.tsindex 24f7961cb7..a144102956 100644--- a/packages/dashboard/src/schemas/store-credit.ts+++ b/packages/dashboard/src/schemas/store-credit.ts@@ -23,6 +23,7 @@ const amountField = z})export const issueStoreCreditFormSchema = z.object({+ customer_id: z.string().min(1, { error: requiredMessage('customer_id') }),amount: amountField,currency: z.string().min(1, { error: requiredMessage('currency') }),memo: z.string(),diff --git a/packages/dashboard/src/tables/store-credits.tsx b/packages/dashboard/src/tables/store-credits.tsxindex 91f6e15ce3..40cefd5043 100644--- a/packages/dashboard/src/tables/store-credits.tsx+++ b/packages/dashboard/src/tables/store-credits.tsx@@ -24,7 +24,7 @@ const ORIGIN_OPTIONS = []defineTable<StoreCredit>('store-credits', {- docsPath: 'loyalty/store-credits',+ docsPath: 'loyalty/store-credits-list',description: i18n.t('admin.table_descriptions.store_credits'),title: i18n.t('admin.nav.store_credits'),searchParam: 'memo_cont',