Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added edit and delete to the store credits list (#14822)

Damian Legawieca44267ddc527
diff --git a/.changeset/dashboard-store-credits-edit-delete.md b/.changeset/dashboard-store-credits-edit-delete.md
new file mode 100644
index 0000000000..2f037335c3
--- /dev/null
+++ b/.changeset/dashboard-store-credits-edit-delete.md
@@ -0,0 +1,5 @@
+---
+"@spree/dashboard": patch
+---
+
+Store credits can now be edited and deleted from the Loyalty → Store Credits page, from each row's menu or the credit's panel, matching the gift cards page.
diff --git a/docs/user/loyalty/store-credits-list.mdx b/docs/user/loyalty/store-credits-list.mdx
index 8d093462b7..adf9a0ae84 100644
--- a/docs/user/loyalty/store-credits-list.mdx
+++ b/docs/user/loyalty/store-credits-list.mdx
@@ -62,8 +62,12 @@ allocated when created, authorised when a customer starts a checkout with it,
captured when that order is paid, and voided or credited back if the order is
cancelled.
-The panel is read-only. To change an amount or a memo, or to delete a credit,
-use **Open customer profile** and edit it there. See
+## Edit or Delete a Credit
+
+Use **Edit** to change a credit's amount or memo, or **Delete** to remove it.
+Both are in the menu at the end of each row and at the bottom of the credit's
+panel. **Open customer profile** takes you to the customer who holds the
+credit, where the same actions are available. See
[Issue Store Credits](/user/loyalty/store-credits).
<Note>
diff --git a/packages/dashboard/e2e/store-credits.spec.ts b/packages/dashboard/e2e/store-credits.spec.ts
index cea1774ce3..a600e37cba 100644
--- a/packages/dashboard/e2e/store-credits.spec.ts
+++ b/packages/dashboard/e2e/store-credits.spec.ts
@@ -1,5 +1,5 @@
import { expect, type Page, test } from '@playwright/test'
-import { escapeRegex, FIXTURE_PROMO_CUSTOMER_EMAIL, login } from './helpers'
+import { escapeRegex, FIXTURE_PROMO_CUSTOMER_EMAIL, login, openRowMenu } from './helpers'
const STORE_CREDITS_PATH = (storeId: string) => `/${storeId}/loyalty/store-credits`
@@ -108,4 +108,33 @@ test.describe('store credits', () => {
await expect(page).toHaveURL(/\/customers\/cust_/, { timeout: 15_000 })
await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_EMAIL).first()).toBeVisible()
})
+
+ test('edits and deletes a credit from the list', async ({ page }) => {
+ const creds = await login(page)
+ const memo = `E2E credit to change ${Date.now()}`
+ const editedMemo = `${memo} edited`
+ await issueStoreCredit(page, creds.accessToken, memo)
+
+ await page.goto(STORE_CREDITS_PATH(creds.store_id))
+ await page.getByRole('searchbox').fill(memo)
+ await expect(page.locator('tr').filter({ hasText: memo })).toHaveCount(1, { timeout: 15_000 })
+
+ await openRowMenu(page, memo)
+ await page.getByRole('menuitem', { name: /^edit$/i }).click()
+ const dialog = page.getByRole('dialog')
+ await expect(dialog.getByRole('heading', { name: /edit store credit/i })).toBeVisible()
+ await dialog.getByLabel(/memo/i).fill(editedMemo)
+ await dialog.getByRole('button', { name: /^save$/i }).click()
+ await expect(page.locator('tr').filter({ hasText: editedMemo })).toHaveCount(1, {
+ timeout: 15_000,
+ })
+
+ await openRowMenu(page, editedMemo)
+ await page.getByRole('menuitem', { name: /^delete$/i }).click()
+ await page
+ .getByRole('dialog')
+ .getByRole('button', { name: /^delete$/i })
+ .click()
+ await expect(page.locator('tr').filter({ hasText: memo })).toHaveCount(0, { timeout: 15_000 })
+ })
})
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.tsx
index 41d5d3abae..9fb35ec337 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
@@ -1,11 +1,4 @@
-import { zodResolver } from '@hookform/resolvers/zod'
import type { Customer, StoreCredit } from '@spree/admin-sdk'
-import {
- CurrencySelect,
- currencyParts,
- mapSpreeErrorsToForm,
- normalizeMoneyInput,
-} from '@spree/dashboard-core'
import {
Badge,
Button,
@@ -14,48 +7,23 @@ import {
CardContent,
CardHeader,
CardTitle,
- Dialog,
- DialogBody,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
- Field,
- FieldError,
- FieldGroup,
- FieldLabel,
- InputGroup,
- InputGroupAddon,
- InputGroupInput,
- InputGroupText,
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
- Textarea,
useConfirm,
} from '@spree/dashboard-ui'
import { EllipsisVerticalIcon, PencilIcon, PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'
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,
- useDeleteCustomerStoreCredit,
- useUpdateCustomerStoreCredit,
-} from '../../../hooks/use-customer-store-credits'
-import {
- type EditStoreCreditFormValues,
- editStoreCreditFormSchema,
-} from '../../../schemas/store-credit'
+import { useDeleteCustomerStoreCredit } from '../../../hooks/use-customer-store-credits'
+import { EditStoreCreditDialog } from '../store-credits/edit-store-credit-dialog'
import { IssueStoreCreditDialog } from '../store-credits/issue-store-credit-dialog'
export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {
@@ -65,7 +33,7 @@ export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {
const confirm = useConfirm()
const credits = customer.store_credits ?? []
- const deleteMutation = useDeleteCustomerStoreCredit(customer.id)
+ const deleteMutation = useDeleteCustomerStoreCredit()
return (
<>
@@ -138,7 +106,7 @@ export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {
confirmLabel: t('admin.actions.delete'),
})
) {
- deleteMutation.mutate(sc.id)
+ deleteMutation.mutate({ customerId: customer.id, id: sc.id })
}
}}
>
@@ -169,139 +137,3 @@ export function CustomerStoreCreditsCard({ customer }: { customer: Customer }) {
</>
)
}
-
-function EditStoreCreditDialog({
- customerId,
- credit,
- onOpenChange,
-}: {
- customerId: string
- credit: StoreCredit
- onOpenChange: (open: boolean) => void
-}) {
- const { t } = useTranslation()
- // 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 localeForCurrency = useCurrencyLocale()
- // Currency is locked on edit, so resolve its market locale once. The amount
- // hydrates from the canonical API value (`"50.00"`) but is displayed/edited
- // in that locale's format (`"50,00"` for EUR); on submit we normalize back to
- // canonical. Displaying in the same locale we normalize from keeps an
- // untouched amount from being mangled on save.
- const creditLocale = localeForCurrency(credit.currency) || 'en'
- const { decimal, symbol } = currencyParts(credit.currency, creditLocale)
-
- const form = useForm<EditStoreCreditFormValues>({
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- resolver: zodResolver(editStoreCreditFormSchema) as any,
- defaultValues: {
- amount: credit.amount ? credit.amount.replace('.', decimal) : '',
- memo: credit.memo ?? '',
- },
- })
- const { errors } = form.formState
-
- const mutation = useUpdateCustomerStoreCredit(customerId, credit.id)
-
- async function onSubmit(values: EditStoreCreditFormValues) {
- const params: StoreCreditUpdateParams = {}
-
- if (!amountLocked) {
- const amountValue = values.amount.toString().trim()
- // Normalize from the credit's display locale to the canonical
- // `"1234.56"` the API expects.
- if (amountValue) {
- params.amount = normalizeMoneyInput(amountValue, creditLocale)
- }
- }
-
- params.memo = values.memo
-
- try {
- await mutation.mutateAsync(params)
- onOpenChange(false)
- } catch (err) {
- if (!mapSpreeErrorsToForm(err, form.setError)) throw err
- }
- }
-
- return (
- <Dialog open onOpenChange={onOpenChange}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>{t('admin.pages.customers.detail.edit_credit')}</DialogTitle>
- <DialogDescription>
- {t('admin.customers.detail.store_credit.edit_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="edit-sc-amount">
- {t('admin.fields.store_credit.amount.label')}
- </FieldLabel>
- <InputGroup>
- <InputGroupAddon>
- <InputGroupText>{symbol}</InputGroupText>
- </InputGroupAddon>
- <InputGroupInput
- id="edit-sc-amount"
- type="text"
- inputMode="decimal"
- disabled={amountLocked}
- aria-invalid={!!errors.amount || undefined}
- {...form.register('amount')}
- />
- </InputGroup>
- <FieldError errors={[errors.amount]} />
- </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">
- {t('admin.fields.store_credit.currency.label')}
- </FieldLabel>
- <CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
- </Field>
- </div>
- <Field>
- <FieldLabel htmlFor="edit-sc-memo">
- {t('admin.fields.store_credit.memo.label')}
- </FieldLabel>
- <Textarea
- id="edit-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.actions.save')}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/packages/dashboard/src/components/spree/store-credits/edit-store-credit-dialog.tsx b/packages/dashboard/src/components/spree/store-credits/edit-store-credit-dialog.tsx
new file mode 100644
index 0000000000..7191a32e52
--- /dev/null
+++ b/packages/dashboard/src/components/spree/store-credits/edit-store-credit-dialog.tsx
@@ -0,0 +1,174 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import type { StoreCredit } from '@spree/admin-sdk'
+import {
+ CurrencySelect,
+ currencyParts,
+ mapSpreeErrorsToForm,
+ normalizeMoneyInput,
+} 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 { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
+import { useCurrencyLocale } from '../../../hooks/use-currency-locale'
+import {
+ type StoreCreditUpdateParams,
+ useUpdateCustomerStoreCredit,
+} from '../../../hooks/use-customer-store-credits'
+import {
+ type EditStoreCreditFormValues,
+ editStoreCreditFormSchema,
+} from '../../../schemas/store-credit'
+
+export function EditStoreCreditDialog({
+ customerId,
+ credit,
+ onOpenChange,
+}: {
+ customerId: string
+ credit: StoreCredit
+ onOpenChange: (open: boolean) => void
+}) {
+ const { t } = useTranslation()
+ // 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 localeForCurrency = useCurrencyLocale()
+ // Currency is locked on edit, so resolve its market locale once. The amount
+ // hydrates from the canonical API value (`"50.00"`) but is displayed/edited
+ // in that locale's format (`"50,00"` for EUR); on submit we normalize back to
+ // canonical. Displaying in the same locale we normalize from keeps an
+ // untouched amount from being mangled on save.
+ const creditLocale = localeForCurrency(credit.currency) || 'en'
+ const { decimal, symbol } = currencyParts(credit.currency, creditLocale)
+
+ const form = useForm<EditStoreCreditFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(editStoreCreditFormSchema) as any,
+ defaultValues: {
+ amount: credit.amount ? credit.amount.replace('.', decimal) : '',
+ memo: credit.memo ?? '',
+ },
+ })
+ const { errors } = form.formState
+
+ const mutation = useUpdateCustomerStoreCredit(customerId, credit.id)
+
+ async function onSubmit(values: EditStoreCreditFormValues) {
+ const params: StoreCreditUpdateParams = {}
+
+ if (!amountLocked) {
+ const amountValue = values.amount.toString().trim()
+ // Normalize from the credit's display locale to the canonical
+ // `"1234.56"` the API expects.
+ if (amountValue) {
+ params.amount = normalizeMoneyInput(amountValue, creditLocale)
+ }
+ }
+
+ params.memo = values.memo
+
+ try {
+ await mutation.mutateAsync(params)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('admin.pages.customers.detail.edit_credit')}</DialogTitle>
+ <DialogDescription>
+ {t('admin.customers.detail.store_credit.edit_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="edit-sc-amount">
+ {t('admin.fields.store_credit.amount.label')}
+ </FieldLabel>
+ <InputGroup>
+ <InputGroupAddon>
+ <InputGroupText>{symbol}</InputGroupText>
+ </InputGroupAddon>
+ <InputGroupInput
+ id="edit-sc-amount"
+ type="text"
+ inputMode="decimal"
+ disabled={amountLocked}
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount')}
+ />
+ </InputGroup>
+ <FieldError errors={[errors.amount]} />
+ </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">
+ {t('admin.fields.store_credit.currency.label')}
+ </FieldLabel>
+ <CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
+ </Field>
+ </div>
+ <Field>
+ <FieldLabel htmlFor="edit-sc-memo">
+ {t('admin.fields.store_credit.memo.label')}
+ </FieldLabel>
+ <Textarea
+ id="edit-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.actions.save')}
+ </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.ts
index 9b90786dda..e377a9b951 100644
--- a/packages/dashboard/src/hooks/use-customer-store-credits.ts
+++ b/packages/dashboard/src/hooks/use-customer-store-credits.ts
@@ -26,10 +26,11 @@ export function useUpdateCustomerStoreCredit(customerId: string, creditId: strin
})
}
-export function useDeleteCustomerStoreCredit(customerId: string) {
+export function useDeleteCustomerStoreCredit() {
return useResourceMutation({
- mutationFn: (id: string) => adminClient.customers.storeCredits.delete(customerId, id),
- invalidate: [['customers', customerId], ['store-credits']],
+ mutationFn: ({ customerId, id }: { customerId: string; id: string }) =>
+ adminClient.customers.storeCredits.delete(customerId, id),
+ invalidate: [['customers'], ['store-credits']],
successMessage: i18n.t('admin.messages.store_credit_removed'),
})
}
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx
index 629d7678f1..1405ef379a 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx
@@ -5,6 +5,7 @@ import {
ResourceTable,
resourceSearchSchema,
Subject,
+ usePermissions,
} from '@spree/dashboard-core'
import {
Badge,
@@ -14,6 +15,7 @@ import {
cn,
Pagination,
RelativeTime,
+ RowActions,
Sheet,
SheetContent,
SheetDescription,
@@ -21,15 +23,18 @@ import {
SheetHeader,
SheetTitle,
Skeleton,
+ useConfirm,
useRowClickBridge,
} from '@spree/dashboard-ui'
-import { PlusIcon } from '@spree/dashboard-ui/icons'
+import { PencilIcon, PlusIcon, TrashIcon } 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 { EditStoreCreditDialog } from '../../../../components/spree/store-credits/edit-store-credit-dialog'
import { IssueStoreCreditDialog } from '../../../../components/spree/store-credits/issue-store-credit-dialog'
+import { useDeleteCustomerStoreCredit } from '../../../../hooks/use-customer-store-credits'
import {
listStoreCredits,
useStoreCredit,
@@ -53,14 +58,16 @@ const LIST_EXPAND = ['customer', 'created_by']
/**
* 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.
+ * credit can be issued, edited or deleted. 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)
+ const [editing, setEditing] = useState<StoreCredit | null>(null)
+ const { canEdit, canDelete, deleteCredit, deletePending } = useStoreCreditActions()
// 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
@@ -88,6 +95,11 @@ function StoreCreditsPage() {
useRowClickBridge('data-store-credit-id', openCredit)
+ async function handleDelete(credit: StoreCredit) {
+ const deleted = await deleteCredit(credit)
+ if (deleted && credit.id === search.credit) closeSheet()
+ }
+
return (
<>
<div className="flex flex-col gap-6">
@@ -98,7 +110,7 @@ function StoreCreditsPage() {
sticky={false}
actions={
<Can I="create" a={Subject.StoreCredit}>
- <Button size="sm" onClick={() => setIssueOpen(true)}>
+ <Button onClick={() => setIssueOpen(true)}>
<PlusIcon className="size-4" />
{t('admin.pages.customers.detail.issue_credit')}
</Button>
@@ -119,6 +131,24 @@ function StoreCreditsPage() {
}}
searchParams={search}
defaultParams={{ expand: LIST_EXPAND }}
+ rowActions={(credit) => (
+ <RowActions
+ actions={[
+ {
+ key: 'edit',
+ visible: canEdit(credit),
+ onSelect: () => setEditing(credit),
+ },
+ {
+ key: 'delete',
+ destructive: true,
+ visible: canDelete(credit),
+ disabled: deletePending,
+ onSelect: () => handleDelete(credit),
+ },
+ ]}
+ />
+ )}
// The page mounts its own header so the totals can sit between the
// title and the list; without this the table renders a second one.
hideHeader
@@ -138,12 +168,62 @@ function StoreCreditsPage() {
key={search.credit}
id={search.credit}
onOpenChange={(open) => !open && closeSheet()}
+ canEdit={canEdit}
+ canDelete={canDelete}
+ deletePending={deletePending}
+ onEdit={setEditing}
+ onDelete={handleDelete}
+ />
+ )}
+
+ {editing?.customer_id && (
+ <EditStoreCreditDialog
+ customerId={editing.customer_id}
+ credit={editing}
+ onOpenChange={(open) => !open && setEditing(null)}
/>
)}
</>
)
}
+/**
+ * Edit and delete go through the customer that holds the credit, so a credit
+ * without one offers neither. A credit with any of its balance used can no
+ * longer be deleted; the server refuses it, so the action is not offered.
+ */
+function useStoreCreditActions() {
+ const { t } = useTranslation()
+ const confirm = useConfirm()
+ const { permissions } = usePermissions()
+ const deleteMutation = useDeleteCustomerStoreCredit()
+
+ const canEdit = (credit: StoreCredit) =>
+ !!credit.customer_id && permissions.can('update', Subject.StoreCredit)
+
+ const canDelete = (credit: StoreCredit) =>
+ !!credit.customer_id &&
+ Number(credit.amount_used) === 0 &&
+ permissions.can('destroy', Subject.StoreCredit)
+
+ /** Resolves to whether the credit was deleted, so a cancel keeps the panel open. */
+ async function deleteCredit(credit: StoreCredit) {
+ if (!credit.customer_id) return false
+ const ok = await confirm({
+ message: t('admin.customers.detail.store_credit.delete_confirm_message'),
+ variant: 'destructive',
+ confirmLabel: t('admin.actions.delete'),
+ })
+ if (!ok) return false
+ return deleteMutation.mutateAsync({ customerId: credit.customer_id, id: credit.id }).then(
+ () => true,
+ () => false,
+ )
+ }
+
+ return { canEdit, canDelete, deleteCredit, deletePending: deleteMutation.isPending }
+}
+
/**
* The store's liability, one card per currency. Reads the totals the list
* returned, so filtering by a customer turns these into that customer's
@@ -195,16 +275,23 @@ function OutstandingTotals({
)
}
-/**
- * The credit's details and its ledger. Read-only — editing a credit happens
- * on the customer profile, which the footer links to.
- */
+/** The credit's details and its ledger. */
function StoreCreditSheet({
id,
onOpenChange,
+ canEdit,
+ canDelete,
+ deletePending,
+ onEdit,
+ onDelete,
}: {
id: string
onOpenChange: (open: boolean) => void
+ canEdit: (credit: StoreCredit) => boolean
+ canDelete: (credit: StoreCredit) => boolean
+ deletePending: boolean
+ onEdit: (credit: StoreCredit) => void
+ onDelete: (credit: StoreCredit) => void
}) {
const { t } = useTranslation()
const [ledgerPage, setLedgerPage] = useState(1)
@@ -319,6 +406,17 @@ function StoreCreditSheet({
</div>
<SheetFooter>
+ {credit && canDelete(credit) && (
+ <Button
+ variant="destructive"
+ className="mr-auto"
+ disabled={deletePending}
+ onClick={() => onDelete(credit)}
+ >
+ <TrashIcon className="size-4" />
+ {t('admin.actions.delete')}
+ </Button>
+ )}
{credit?.customer_id && (
<Button asChild variant="outline">
<Link
@@ -329,6 +427,12 @@ function StoreCreditSheet({
</Link>
</Button>
)}
+ {credit && canEdit(credit) && (
+ <Button onClick={() => onEdit(credit)}>
+ <PencilIcon className="size-4" />
+ {t('admin.actions.edit')}
+ </Button>
+ )}
</SheetFooter>
</SheetContent>
</Sheet>