Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(promotions): admin promotion-table UX + Figma type alignment (#1271)

Viktor Holikd52053e3478c
diff --git a/.claude/skills/figma-ui/SKILL.md b/.claude/skills/figma-ui/SKILL.md
new file mode 100644
index 000000000..00691e76d
--- /dev/null
+++ b/.claude/skills/figma-ui/SKILL.md
@@ -0,0 +1,70 @@
+---
+name: figma-ui
+description: Convert a Figma design into Mercur dashboard UI code (admin or vendor panel) that matches the project's design-system conventions. Trigger whenever the user shares a figma.com URL, selects a Figma node/frame, or asks to "convert this design", "implement this design", "build this screen", "turn this mockup into code", or otherwise do design-to-code work in packages/admin or packages/vendor. Also trigger when the user describes the flow in their own words ("here's the Figma, make the page"). Use the Figma MCP to read the design, then map it onto the component inventory and patterns in this skill's references before writing any JSX.
+---
+
+# figma-ui — Figma design → Mercur dashboard code
+
+Turn a Figma design into React code for the **admin** (`packages/admin`) or **vendor** (`packages/vendor`) dashboard, using the shared design system (`@mercurjs/dashboard-shared` + `@medusajs/ui`). The goal is code that looks like the surrounding pages: same primitives, same section shells, same spacing, same tokens.
+
+This skill is the **judgment layer**. It does not lint. The conventions that matter — which primitive to use, how sections and modals are built, which spacing/tokens are correct — live in the reference files below. Read the relevant one before writing code; do not guess from memory.
+
+## References (read the one that fits the task)
+
+- **`references/components.md`** — the component inventory. Which `@mercurjs/dashboard-shared` / `@medusajs/ui` primitive maps to which Figma element, the page archetypes (list / detail / create / edit), and the compound sub-parts (`Form.Field`, `RouteDrawer.Body`, `DataTable`, `ActionMenu`, empty states). This replaces Code Connect — it is the source of truth for "what do I render".
+- **`references/spacing.md`** — the spacing scale and color/typography/effect tokens, and when to use each (`gap-y-3` page stack, `gap-y-4` drawer body, `gap-y-8` focus-modal body, `px-6 py-4` section rows, `p-16` tab body). Use this to translate Figma pixel values into the token scale instead of arbitrary values.
+- **`references/patterns.md`** — the recurring structural rules: section shell (`Container className="divide-y p-0"`), create = `RouteFocusModal` + `TabbedForm`, edit = `RouteDrawer`, forms go through `Form.Field`, destructive actions use a delete-action hook + `usePrompt`, compound-component export shape, i18n, `data-testid`. Read this before building any page. It also lists what NOT to do (raw `<input>`, raw `FocusModal`/`Drawer`, foreign UI/icon libraries, hardcoded colors).
+
+For the full narrative version of these conventions, `docs/UI-ARCHITECTURE.md` is the canonical repo doc; the references here are the condensed, task-focused extract.
+
+## The workflow
+
+### 1. Read the design from Figma — the screenshot is the source of truth
+
+Use the Figma MCP against the shared node/URL. **Only two tools are used, and the screenshot is the primary one:**
+
+- **`get_screenshot`** — the source of truth. Read the rendered image directly to get the **content** (all visible text: headings, labels, field placeholders, button copy, column names, badge text, empty-state copy) and the **visual state** (which button is filled vs. outline, badge colors, emphasis, density, spacing, layout). You transcribe the content and decide component variants + spacing from what you see here. Request a larger `maxDimension` if you need to read fine detail.
+- **`get_metadata`** — a lightweight structural outline (layer names, nesting, sizes, which layers are `hidden`). Use it only to confirm the archetype and reading order (e.g. sidebar + table + footer ⇒ list page); don't rely on it for content — names can be generic or stale.
+
+Do **not** depend on `get_variable_defs` or `get_design_context` — they are not part of this flow. Map colors and spacing yourself from the screenshot onto Medusa UI tokens using `references/spacing.md`.
+
+If the user gave a URL but no specific node, ask which frame/screen to build. If the frame's **name** disagrees with what the **screenshot** shows (names can be stale — e.g. a frame named "Create Promotion" that actually renders the Promotions list), trust the screenshot and say so.
+
+### 2. Decide the surface and the page archetype
+
+- **Surface**: admin (`packages/admin`, operator, `sdk.admin.*`) or vendor (`packages/vendor`, seller, `sdk.vendor.*`)? If the design doesn't make it obvious, ask.
+- **Archetype**: list, detail, create, or edit? Match it to `references/components.md` and find the closest existing page to mirror (e.g. `pages/categories/category-list`, `category-detail`, `pages/products/product-create`, `category-edit`).
+
+### 3. From the screenshot, pick component + variant + spacing, then write code
+
+Go region by region over what you saw in the screenshot. For each region make three decisions, each backed by a reference file — don't eyeball it:
+
+1. **Which component** → look it up in `references/components.md` (the inventory: page frame → `SingleColumnPage`/`TwoColumnPage`; card → section `Container`; field → `Form.Field`; create → `RouteFocusModal`+`TabbedForm`; edit → `RouteDrawer`; table → `DataTable`; row/section action → `ActionMenu`; empty → `NoRecords`/`NoResults`).
+2. **Which variant** → from the element's appearance in the screenshot, pick the exact prop using the **"Component variants & props"** table in `references/components.md`. Examples:
+ - a filled primary button → `<Button variant="primary">`; an outlined/cancel button → `variant="secondary"`; an inline text action → `variant="transparent"`; a red/destructive one → `variant="danger"`.
+ - a status pill's color (green/red/orange/grey…) → the matching `StatusBadge color`, sourced via `pages/<domain>/common/utils.ts` helpers.
+ - text emphasis/size → `Text size`/`weight`; a title → `Heading level`.
+ - Transcribe the **actual text** from the screenshot into these components (then route it through `t(...)` — see step 4).
+3. **Which spacing / tokens** → translate the screenshot's spacing and colors using `references/spacing.md`: snap to the scale (`gap-y-3` page stack, `gap-y-4` drawer body, `gap-y-8` focus-modal body, `px-6 py-4` section rows, `p-16` tab body) and use Medusa UI color tokens — never arbitrary hex/rgb/palette values.
+
+Follow `references/patterns.md` for the structural rules that tie it together: section shell, create/edit hosts, forms through `Form.Field`, destructive-action hook, compound-component export shape, i18n keys, and `data-testid`s. When the design shows a variant that isn't in the props table, stop and ask (step "When to stop and ask") rather than `className`-overriding a component.
+
+### 4. Verify against the design and the conventions
+
+- Compare your output to the `get_screenshot` reference and to the nearest existing page.
+- Run `bun run lint` and `bun run build`; keep them green.
+- Every user-facing string goes through `t(...)` — add keys to `packages/<pkg>/src/i18n/translations/en.json` first.
+
+## When to stop and ask the user
+
+- The design's surface (admin vs vendor) or archetype is ambiguous.
+- The design needs data/an endpoint that doesn't exist yet (a hook in `src/hooks/api/<domain>.tsx` or a backend route) — confirm the data contract before inventing one.
+- The design calls for a component that has no equivalent in `references/components.md` — ask whether to compose one from Medusa UI primitives or add a shared primitive to `@mercurjs/dashboard-shared`, rather than reaching for an outside library.
+- The Figma tokens don't map cleanly onto Medusa UI tokens — surface the mismatch instead of hardcoding a color.
+
+## What this skill does NOT do
+
+- It does not add new UI libraries or icon packs. Components come from `@medusajs/ui` / `@mercurjs/dashboard-shared`; icons from `@medusajs/icons` only.
+- It does not invent backend endpoints or data models — it consumes existing ones via the typed SDK.
+- It does not enforce rules mechanically (no linter); it relies on the references and `bun run lint` / `bun run build` as the gate.
+- It does not push code back into Figma; it is design-to-code only.
diff --git a/.claude/skills/figma-ui/references/components.md b/.claude/skills/figma-ui/references/components.md
new file mode 100644
index 000000000..74488af91
--- /dev/null
+++ b/.claude/skills/figma-ui/references/components.md
@@ -0,0 +1,129 @@
+# Component inventory (what to render)
+
+The map from a Figma element to the primitive you render. This replaces Code Connect: when you see a region in the design, find its row here and use that component. Everything comes from two sources only:
+
+- **`@mercurjs/dashboard-shared`** — the internal design-system layer (the primary "shared components" source).
+- **`@medusajs/ui`** — Medusa's design system (raw primitives: `Button`, `Input`, `Select`, `Heading`, `Text`, `Badge`, `StatusBadge`, `Container`, `Tooltip`, `clx`, `toast`, `usePrompt`, …).
+
+Icons come from **`@medusajs/icons`** only. Data comes from **`@mercurjs/client`** (the typed SDK, `sdk.admin.*` / `sdk.vendor.*`) — not a UI concern. Headless primitives that shared components are built on (`radix-ui`, `@ariakit/react`, `cmdk`, `@tanstack/react-table`, `@tanstack/react-virtual`, `@dnd-kit/*`, `react-hook-form`, `zod`) are allowed but you rarely reach for them directly. Also available from Medusa: `@medusajs/dashboard`, `@medusajs/admin-shared`, `@medusajs/ui-preset` (Tailwind preset, dev).
+
+**Never** introduce another component or icon library (no MUI, Chakra, Ant, Mantine, lucide, heroicons, react-icons, FontAwesome, styled-components, emotion). If a needed component isn't here, compose it from Medusa UI primitives or add it to `@mercurjs/dashboard-shared`.
+
+## Page archetypes → layout
+
+| Figma screen | Archetype | Layout primitive | Mirror this existing page |
+| --- | --- | --- | --- |
+| A table/list of records | **list** | `SingleColumnPage` + one `Container` (header + `DataTable`) | `packages/admin/src/pages/categories/category-list` |
+| A record with a main area + sidebar of meta | **detail** | `TwoColumnPage` (`.Main` + `.Sidebar`, each stacked `gap-y-3`) | `.../categories/category-detail` |
+| A full-screen "create" flow, often multi-step | **create** | `RouteFocusModal` + `TabbedForm` | `.../products/product-create` |
+| A quick side-panel edit of one entity | **edit** | `RouteDrawer` + `RouteDrawer.Form` | `.../categories/category-edit` |
+
+`SingleColumnPage` / `TwoColumnPage` support `showJSON` / `showMetadata` (pass `data={entity}`).
+
+## Layout & structure
+
+| Figma element | Render |
+| --- | --- |
+| Page frame (list/simple) | `SingleColumnPage` |
+| Page frame (detail w/ sidebar) | `TwoColumnPage` → `TwoColumnPage.Main`, `TwoColumnPage.Sidebar` |
+| Card / panel / section | `Container className="divide-y p-0"` (see `patterns.md`) |
+| Section header row | `<div className="flex items-center justify-between px-6 py-4">` with `<Heading>` + actions |
+| Label/value row | `SectionRow` (grid, `text-ui-fg-subtle`) |
+| Key–value metadata block | `MetadataSection` (or `SingleColumnPage showMetadata`) |
+| Raw JSON block | `JsonViewSection` |
+
+## Modals & drawers
+
+| Figma element | Render | Compound sub-parts |
+| --- | --- | --- |
+| Full-screen create/wizard | `RouteFocusModal` | `.Header .Title .Body .Description .Footer .Close .Form` |
+| Side-panel edit | `RouteDrawer` | `.Header .Title .Body .Description .Footer .Close .Form` |
+| Modal opened from inside a modal | `StackedFocusModal` | `.Trigger .Content .Header .Title .Body .Footer .Close` |
+| Drawer opened from inside a drawer | `StackedDrawer` | same as above |
+| Confirm/destructive dialog | `usePrompt()` (`@medusajs/ui`) via a delete-action hook, or `ConfirmPrompt` | — |
+
+Never render raw `FocusModal` / `Drawer` from `@medusajs/ui` for a page's create/edit surface — use the `Route*` wrappers so nav-blocking and dirty prompts work.
+
+## Forms
+
+| Figma element | Render |
+| --- | --- |
+| Any form field | `Form.Field` → `Form.Item` → `Form.Label` / `Form.Control` / `Form.ErrorMessage` (+ `Form.Hint` for help text) |
+| Text / number input | `Input` (`@medusajs/ui`) inside `Form.Control` |
+| Multi-line input | `Textarea` (`@medusajs/ui`) |
+| Dropdown | `Select` (`@medusajs/ui`); searchable → `Combobox` (shared) |
+| Toggle / switch (carded) | `SwitchBox` (shared) |
+| Tag / multi-value input | `ChipInput` (shared) |
+| File / image upload | `FileUpload` (shared) |
+| Country / province pickers | `CountrySelect` / `ProvinceSelect` (shared) |
+| Percentage / currency | `PercentageInput` (shared) / `react-currency-input-field` |
+| URL handle field | `HandleInput` (shared) |
+| Address / email / metadata composite | `AddressForm` / `EmailForm` / `MetadataForm` (shared) |
+| Multi-step form | `TabbedForm` + `useTabbedForm` + `defineTabMeta` (each tab a `Root` with `_tabMeta`) |
+
+Never use raw `<input>`, `<textarea>`, `<select>`, or react-hook-form `<Controller>` directly — always the primitives above inside `Form.Field`.
+
+## Tables & data display
+
+| Figma element | Render |
+| --- | --- |
+| Data table | `DataTable` + `useDataTable` (page size 20, `keepPreviousData`) |
+| Column cells | shared cells: `TextCell`, `DateCell`, `CreatedAtCell`, `EmailCell`, `MoneyAmountCell`, `NameCell`, `StatusCell`, `PlaceholderCell`, `CodeCell` |
+| Editable grid | `DataGrid` (`.TextCell .NumberCell .CurrencyCell .BooleanCell .MultilineCell .ExpandableTextCell .ReadonlyCell`) |
+| Row / section action menu | `ActionMenu` (groups of `{ label, icon, to | onClick }`) |
+| Empty (searched, no matches) | `NoResults` |
+| Empty (no records yet) | `NoRecords` (optional `action={{ to, label }}`) |
+| Filters / sorting | `FilterGroup`, `OrderBy`, `Query` (shared) |
+| Infinite / virtual list | `InfiniteList` |
+| Reorderable list / tree | `SortableList` / `SortableTree` |
+
+## Common bits
+
+| Figma element | Render |
+| --- | --- |
+| Status pill | `StatusBadge` (`@medusajs/ui`) — colors/labels from `pages/<domain>/common/utils.ts` |
+| Tag / chip | `Badge`, `ChipGroup`, `TaxBadge` |
+| Loading placeholder | `Skeleton` (detail pages: `TwoColumnPageSkeleton`) |
+| Avatar / logo | `IconAvatar`, `ImageAvatar`, `LogoBox`, `AvatarBox`, `Thumbnail` |
+| Segmented toggle | `SegmentedControl` |
+| Progress | `ProgressBar` |
+| Copyable id | `DisplayId` |
+| Tooltip (conditional) | `ConditionalTooltip` |
+
+## Data layer (not UI, but you'll wire it)
+
+- Hooks live in `packages/<pkg>/src/hooks/api/<domain>.tsx`, built on `queryKeysFactory(domain)` (shared) + TanStack Query.
+- Detail pages seed data via a `loader.ts` (react-router) passed as `initialData`.
+- Mutations invalidate `lists()` / `details()` / `detail(id)` keys.
+
+## Component variants & props (pick the right one from the design)
+
+Choosing the component is half the job — you also have to pick its variant/size to match the design's visual state. These are the **actual** prop unions from the installed `@medusajs/ui` types (`packages/admin/node_modules/@medusajs/ui/dist/cjs/components/*`). Map the Figma element's role/emphasis to a variant here; do not restyle with `className`.
+
+| Component | Prop | Values (default in **bold**) | Map from design |
+| --- | --- | --- | --- |
+| `Button` | `variant` | **primary** · secondary · transparent · danger | filled CTA → `primary`; outline/cancel → `secondary`; inline/icon-only text → `transparent`; destructive → `danger` |
+| `Button` | `size` | small · **base** · large · xlarge | toolbars/footers use `small` |
+| `Button` | `isLoading`, `asChild` | boolean | pending state / wrapping a `<Link>` |
+| `IconButton` | `variant` / `size` | primary · **transparent** / 2xsmall · xsmall · **small** · base · large · xlarge | action-menu trigger = `transparent` + `small` |
+| `Badge` | `color` | **grey** · green · red · blue · orange · purple | semantic tag color |
+| `Badge` | `size` | 2xsmall · xsmall · **small** · base · large | — |
+| `StatusBadge` | `color` | **grey** · green · red · blue · orange · purple | pull color/label from `pages/<domain>/common/utils.ts` helpers, don't hardcode |
+| `Text` | `size` | xsmall · **small** · base · large · xlarge | row text = `small`; chips/breadcrumbs = `xsmall` |
+| `Text` | `weight` / `leading` / `family` | **regular** · plus / **normal** · compact / **sans** · mono | emphasis = `weight="plus"`; table rows = `leading="compact"` |
+| `Heading` | `level` | **h1** · h2 · h3 | section title default; sidebar section = `h2` |
+| `Input` | `size` | small · **base** | dense forms use `small` |
+| `Select` | `size` | **base** · small | — |
+| `Switch` | `size` | **small** · base | toggles (prefer `SwitchBox` for carded toggles) |
+| `Hint` | `variant` | **info** · error | help text vs. error |
+
+Notes:
+- `Textarea`, `Checkbox`, `RadioGroup` have **no** style variants — one canonical look; don't invent sizes for them.
+- Everything else styles itself; you control layout via the spacing scale in `spacing.md`, not by overriding a component's internal colors.
+- Shared composites (`SwitchBox`, `FileUpload`, `ChipInput`, `DataTable`, `ActionMenu`, `NoRecords`, …) already bake in the correct styling — pass data/props, don't restyle.
+- If a design needs a variant that doesn't exist in the table above, that's a signal to ask the user, not to `className`-override a Medusa UI component (forbidden — see `patterns.md`).
+
+## Package extras (re-exported on top of shared)
+
+- **admin** `packages/admin/src/index.ts`: `TabbedForm`, `useTabbedForm`, `defineTabMeta`, `TabDefinition`, `Form`, `SwitchBox`, `FileUpload`, `ChipInput`, `DataTable`, `useDataTable`, `SingleColumnPage`, `ActionMenu`, `Notifications`, `PRODUCT_DETAIL_FIELDS`, `PRODUCT_DETAIL_QUERY`.
+- **vendor** `packages/vendor/src/index.ts`: `TabbedForm`, `useTabbedForm`, `TabDefinition`, `Notifications`.
diff --git a/.claude/skills/figma-ui/references/patterns.md b/.claude/skills/figma-ui/references/patterns.md
new file mode 100644
index 000000000..e4dee8cfc
--- /dev/null
+++ b/.claude/skills/figma-ui/references/patterns.md
@@ -0,0 +1,119 @@
+# Patterns (how the pieces fit together)
+
+The structural rules for Mercur dashboard pages. These are conventions, not lint rules — follow them so generated code reads like the rest of the codebase. Each pattern says what to do and, where it's a common mistake, what **not** to do.
+
+## Sections do X
+
+Every section on a page is a `Container` with the standard shell:
+
+```tsx
+<Container className="divide-y p-0" data-testid="customer-general-section">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("customers.general.title")}</Heading>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge {...statusProps}>{statusText}</StatusBadge>
+ <ActionMenu groups={[...]} />
+ </div>
+ </div>
+ {/* rows, each px-6 py-4; label/value rows use SectionRow */}
+</Container>
+```
+
+- **Do**: `className="divide-y p-0"`; header row `flex items-center justify-between px-6 py-4`; `<Heading>` on the left; status badge + `ActionMenu` on the right.
+- **Don't**: a `Container` for a section without `p-0` (you'll get default padding and misaligned rows); raw `<h2>`/`<h3>` instead of `<Heading>`; hand-built dropdowns instead of `ActionMenu`.
+
+## Modals do X
+
+- **Create** = `RouteFocusModal` host + `TabbedForm`. The page's `Root` opens the modal on mount and renders defaults unless children are passed:
+
+ ```tsx
+ const Root = ({ children }) => (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild><span className="sr-only">{t("...")}</span></RouteFocusModal.Title>
+ {Children.count(children) > 0 ? children : <CreateXForm />}
+ </RouteFocusModal>
+ )
+ ```
+
+ Each tab is a component whose `Root` carries `Root._tabMeta = defineTabMeta<Schema>({ id, labelKey, validationFields })`. Tab body: `flex flex-col items-center p-16` → inner `flex w-full max-w-[720px] flex-col gap-y-8`.
+
+- **Edit** = `RouteDrawer` host + `RouteDrawer.Form` + `KeyboundForm`:
+
+ ```tsx
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild><Heading>{t("domain.edit.header")}</Heading></RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">{t("domain.edit.description")}</RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {ready && <EditXForm entity={entity} />} {/* ready = !isPending && !!entity */}
+ </RouteDrawer>
+ ```
+
+ Drawer body: `flex flex-col gap-y-4`. Footer: secondary **Cancel** (`RouteDrawer.Close`) + primary **Save** (`isLoading={isPending}`). Close/redirect via `useRouteModal().handleSuccess()`.
+
+- **Don't**: render raw `FocusModal` / `Drawer` from `@medusajs/ui` for a page create/edit surface; nest a raw modal inside another (use `StackedFocusModal` / `StackedDrawer`).
+
+## Forms do X
+
+- Every field: `Form.Field` → `Form.Item` → `Form.Label` / `Form.Control` / `Form.ErrorMessage`. Help text via `Form.Hint`. Never render error text by hand (`Form.ErrorMessage` reads RHF).
+- React Hook Form + `zodResolver(schema)`; infer type with `z.infer`. One schema per form.
+- Wrap the `<form>` in `KeyboundForm` so Cmd/Ctrl+Enter submits.
+- Selects: destructure `{ ref, onChange, ...field }`, pass `onValueChange={onChange}` and `dir={useDocumentDirection()}`.
+- Nullable/optional values go through `transformNullableFormData` / `transformNullableFormNumber` before the mutation.
+- **Don't**: raw `<input>`/`<textarea>`/`<select>`; react-hook-form `<Controller>` directly. Use the primitives in `components.md`. (Rare justified exceptions — data-grid cells, custom comboboxes — exist in the codebase, but new page code should not need them.)
+
+## Destructive actions do Y
+
+Extract to a hook `pages/<domain>/common/hooks/use-delete-<entity>-action.tsx`:
+
+1. `usePrompt()` (`@medusajs/ui`) with i18n `title` / `description` / `confirmText` / `cancelText`.
+2. Await confirmation → call the mutation.
+3. `toast.success` / `toast.error`.
+4. Navigate back on success.
+
+Place the delete action **last**, in its own `ActionMenu` group (edit/navigation actions first). **Don't** inline a confirmation modal.
+
+## Compound-component export shape
+
+Every page exports a `Root` assembled with named parts, so downstream code can override slots:
+
+```tsx
+export const CategoryListPage = Object.assign(Root, {
+ Header: CategoryListHeader,
+ HeaderTitle: CategoryListTitle,
+ HeaderActions: CategoryListActions,
+ DataTable: CategoryListDataTable,
+})
+```
+
+`Root` uses `Children.count(children) > 0 ? children : <DefaultContent />` so it renders defaults when used as-is but exposes every part.
+
+## Data fetching
+
+- All HTTP via the typed SDK (`sdk.admin.*` / `sdk.vendor.*`) in `hooks/api/<domain>.tsx`. Never call `fetch` from a page.
+- One hook file per domain: `useX` (detail), `useXList` (list), `useCreate/Update/DeleteX` (mutations). Build keys with `queryKeysFactory("x")`.
+- Mutations invalidate `lists()` / `details()` / `detail(id)` and forward `onSuccess`.
+- Detail pages seed with a `loader.ts` → `initialData`. Throw on `isError` (`if (isError) throw error`) so `ErrorBoundary` catches it. Use `Skeleton` / `TwoColumnPageSkeleton` while loading.
+
+## Tables
+
+`DataTable` + `useDataTable`, page size 20, `keepPreviousData`. Build columns with `createColumnHelper<Row>()` + an `actions` display column rendering `ActionMenu`. Row navigation via `navigateTo={(row) => row.id}`. Empty states: `NoResults` (filtered) / `NoRecords` (no data).
+
+## Internationalization
+
+- Every visible string via `useTranslation()` / `t(key)`. No literal UI strings.
+- Add keys to `packages/<pkg>/src/i18n/translations/en.json` **first** (English is canonical). Common namespaces: `actions.*`, `fields.*`, `general.*`, `<domain>.domain` (sidebar), `<domain>.<verb>.header|hint|successToast|description`.
+
+## Test ids
+
+Every interactive element (buttons, inputs, selects, action menus, headings, sections, modals) carries a kebab-case `data-testid` scoped to the page/section, e.g. `customer-general-section-header`, `create-customer-form-first-name-input`.
+
+## Do-not list (quick scan)
+
+- No component library other than `@medusajs/ui` / `@mercurjs/dashboard-shared`.
+- No icon pack other than `@medusajs/icons`.
+- No raw `<input>` / `<textarea>` / `<select>` / `<Controller>` in forms.
+- No raw `FocusModal` / `Drawer` for page create/edit surfaces.
+- No hardcoded `#hex`, `rgb()/rgba()`, or palette utilities (`text-gray-*`, `bg-slate-*`) — use Medusa UI tokens (`spacing.md`).
+- No arbitrary spacing values where the scale has one (`gap-y-3/4/8`, `px-6 py-4`, `p-16`).
+- No literal UI strings — always `t(...)`.
diff --git a/.claude/skills/figma-ui/references/spacing.md b/.claude/skills/figma-ui/references/spacing.md
new file mode 100644
index 000000000..69fa9a7a7
--- /dev/null
+++ b/.claude/skills/figma-ui/references/spacing.md
@@ -0,0 +1,66 @@
+# Spacing & tokens (translate pixels into the scale)
+
+Figma gives you pixel values and raw colors. Do **not** copy them literally. Map them onto the scale and tokens below. Anything you can't map cleanly, surface to the user rather than hardcoding.
+
+Tokens are applied as Tailwind utilities from the Medusa `ui-preset`. Source of truth: `@medusajs/ui-preset/src/theme/tokens/{colors,typography,effects}.ts` and https://docs.medusajs.com/ui/colors/overview. Light/dark are handled automatically by the token — never fork colors per theme.
+
+## Spacing scale (the values you actually use)
+
+| Context | Utility | Where |
+| --- | --- | --- |
+| Outer page section stack | `gap-y-3` | between `Container` sections; `TwoColumnPage` sidebar/main stacks |
+| Section row padding | `px-6 py-4` | every row inside a `Container` section, and the section header row |
+| Drawer body field stack | `gap-y-4` | inside `RouteDrawer.Body` |
+| Focus-modal / tab form body stack | `gap-y-8` | inside a `TabbedForm` tab / `RouteFocusModal` form |
+| Tab body outer padding | `p-16` | wrapper of a create-form tab, then an inner `max-w-[720px]` column |
+| Form column max width | `max-w-[720px]` | the centered form column in focus modals |
+| Two-column field row | `grid grid-cols-1 gap-4 md:grid-cols-2` | side-by-side fields |
+| Cluster gaps (buttons, badges) | `gap-x-2` / `gap-x-3` / `gap-x-4` | toolbars, footers, header action clusters |
+
+Rule of thumb: vertical rhythm inside a card is `py-4`; horizontal inset is `px-6`; stacks are `gap-y-{3,4,8}` depending on surface (page / drawer / focus-modal). Prefer these over arbitrary `mt-*`/`space-y-[...]` values.
+
+## Section shell (memorize this)
+
+```tsx
+<Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("domain.section.title")}</Heading>
+ {/* StatusBadge + ActionMenu */}
+ </div>
+ {/* divided rows, each px-6 py-4 */}
+</Container>
+```
+
+## Color tokens — use these, never raw hex/rgb/palette
+
+Apply as Tailwind utilities: `bg-ui-*`, `text-ui-*`, `border-ui-*`, `shadow-*`. Never write `#fff`, `rgb(...)`, or palette utilities like `text-gray-500` / `bg-slate-100`.
+
+**Backgrounds** (`bg-ui-…`): `bg-base`, `bg-base-hover`, `bg-subtle`, `bg-subtle-hover`, `bg-component`, `bg-component-hover`, `bg-field`, `bg-field-component`, `bg-highlight`, `bg-interactive`, `bg-disabled`, `bg-overlay`, `bg-switch-off`.
+
+**Foreground / text** (`text-ui-fg-…`): `fg-base`, `fg-subtle`, `fg-muted`, `fg-disabled`, `fg-interactive`, `fg-on-color`, `fg-on-inverted`, `fg-error`.
+
+**Borders / dividers** (`border-ui-border-…`): `border-base`, `border-strong`, `border-interactive`, `border-error`, `border-danger`, `border-transparent`, `border-menu-top`, `border-menu-bot`. Section dividers use the `divide-y` utility (which resolves to the base border token).
+
+**Tags / badges** (`…-ui-tag-{neutral|blue|green|red|orange|purple}-{bg|bg-hover|text|border|icon}`): use these via `StatusBadge` / `Badge` rather than by hand.
+
+**Buttons**: don't hand-color buttons — use `Button` variants (`primary`, `secondary`, `transparent`, `danger`) and `IconButton`, which resolve to `--button-*` tokens.
+
+**Effects / shadows** (`shadow-…`): `shadow-elevation-card-rest`, `shadow-elevation-card-hover`, `shadow-borders-focus`, `shadow-borders-base`. Focus rings via `shadow-borders-focus`, not custom outlines.
+
+## Typography
+
+Use components, not raw `<h*>` / `<p>` with sizes:
+
+- Section titles → `<Heading>`; sidebar section titles → `<Heading level="h2">`.
+- Body / row text → `<Text size="small" leading="compact">`; chips/breadcrumbs → `<Text size="xsmall">`; emphasis → `weight="plus"`.
+- Help text → `<Hint>` (`info` default, `error` for form errors).
+- Subtle copy → `<Text className="text-ui-fg-subtle">` / `text-ui-fg-muted`.
+
+## Mapping Figma → tokens (from the screenshot)
+
+You work from the `get_screenshot` image, not from exported variables. Decide tokens by role, not by exact pixel/hex:
+
+1. Identify each color's **role** in the screenshot (page/card background vs. body text vs. subtle/muted text vs. border/divider vs. status pill) and pick the nearest token above.
+2. Match spacing to the nearest **scale** value (`py-4`, `gap-y-4`, `px-6`, `gap-y-8`, …) — don't introduce a new arbitrary value to hit an exact pixel.
+3. Status colors come from the `StatusBadge` color set via `pages/<domain>/common/utils.ts` helpers, not a hand-picked hex.
+4. If a color or spacing clearly doesn't map onto any token/scale value, ask the user; do not hardcode a raw value.
diff --git a/.vscode/settings.json b/.vscode/settings.json
new file mode 100644
index 000000000..9c88b3a13
--- /dev/null
+++ b/.vscode/settings.json
@@ -0,0 +1,21 @@
+{
+ "files.watcherExclude": {
+ "**/node_modules/**": true,
+ "**/.turbo/**": true,
+ "**/.medusa/**": true,
+ "**/dist/**": true,
+ "**/.claude/worktrees/**": true,
+ "**/.git/**": true
+ },
+ "search.exclude": {
+ "**/node_modules": true,
+ "**/.turbo": true,
+ "**/.medusa": true,
+ "**/dist": true,
+ "**/.claude/worktrees": true
+ },
+ "typescript.tsserver.watchOptions": { "watchDirectory": "useFsEvents" },
+ "typescript.tsserver.maxTsServerMemory": 6144,
+ "typescript.tsdk": "node_modules/typescript/lib",
+ "editor.formatOnSave": false
+}
diff --git a/CLAUDE.md b/CLAUDE.md
index 8dbea9a2f..7e89bda58 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,6 +6,10 @@
@docs/ARCHITECTURE.md
@docs/UI-ARCHITECTURE.md
+## Skills
+
+- **Design → code (Figma)**: when the task is turning a Figma design into dashboard UI code — the user shares a `figma.com` URL, selects a Figma node, or asks to "convert / implement / build this design / screen / mockup" in `packages/admin` or `packages/vendor` — load the `figma-ui` skill at `.claude/skills/figma-ui/SKILL.md` first. It reads the design from the Figma MCP (`get_screenshot` as the source of truth, `get_metadata` for structure) and maps it onto the design-system conventions in its `references/` (`components.md`, `spacing.md`, `patterns.md`) before writing JSX. Gate: `bun run lint` + `bun run build` stay green.
+
## Project Overview
Mercur.js is open source marketplace platform repository built using Medusa.js + Typescript + React. It adds a marketplace layer on top of Medusa.js. This repository is designed for long-running coding-agent work. The goal is not to maximize raw code output. The goal is to leave the repo in a state where the next session can continue without guessing.
diff --git a/integration-tests/http/promotions/admin/offer-targeting.spec.ts b/integration-tests/http/promotions/admin/offer-targeting.spec.ts
new file mode 100644
index 000000000..3a201c93c
--- /dev/null
+++ b/integration-tests/http/promotions/admin/offer-targeting.spec.ts
@@ -0,0 +1,184 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { createAdminUser, adminHeaders } from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createVendorProduct } from "../../../helpers/create-product"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Promotions offer targeting", () => {
+ let appContainer: MedusaContainer
+
+ const seedSellerOffer = async (opts: {
+ email: string
+ name: string
+ offerSku: string
+ }) => {
+ const tag = `${Date.now()}-${Math.round(Math.random() * 1e6)}`
+ const { seller, headers } = await createSellerUser(appContainer, {
+ email: opts.email,
+ name: opts.name,
+ })
+
+ const stockLocation = (
+ await api.post(
+ `/vendor/stock-locations`,
+ { name: `${opts.name} WH ${tag}` },
+ headers
+ )
+ ).data.stock_location
+
+ const product = await createVendorProduct(api, headers, {
+ title: `${opts.name} Product ${tag}`,
+ sku: `${opts.email}-V-SKU-${tag}`,
+ })
+
+ const shippingProfile = (
+ await api.post(
+ `/vendor/shipping-profiles`,
+ { name: `${opts.name} Profile ${tag}`, type: "default" },
+ headers
+ )
+ ).data.shipping_profile
+
+ const offer = (
+ await api.post(
+ `/vendor/offers`,
+ {
+ sku: opts.offerSku,
+ variant_id: product.variants[0].id,
+ shipping_profile_id: shippingProfile.id,
+ inventory_items: [
+ {
+ title: `${opts.name} Inv ${tag}`,
+ required_quantity: 1,
+ stock_levels: [
+ { location_id: stockLocation.id, stocked_quantity: 10 },
+ ],
+ },
+ ],
+ prices: [{ amount: 2000, currency_code: "usd" }],
+ },
+ headers
+ )
+ ).data.offer
+
+ return { seller, headers, offer }
+ }
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+ })
+
+ it("exposes both 'offer' and 'product' as target-rule attributes", async () => {
+ const response = await api.get(
+ `/admin/promotions/rule-attribute-options/target-rules?promotion_type=standard&application_method_target_type=items`,
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ const ids = response.data.attributes.map((a: any) => a.id)
+ expect(ids).toContain("offer")
+ expect(ids).toContain("product")
+
+ const offerAttr = response.data.attributes.find(
+ (a: any) => a.id === "offer"
+ )
+ expect(offerAttr.value).toEqual("items.metadata.offer_id")
+ })
+
+ it("returns offers from every seller as rule value options", async () => {
+ const s1 = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Admin VO Seller One",
+ offerSku: "ADMIN-VO-S1-OFFER",
+ })
+ const s2 = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Admin VO Seller Two",
+ offerSku: "ADMIN-VO-S2-OFFER",
+ })
+
+ const response = await api.get(
+ `/admin/promotions/rule-value-options/target-rules/offer`,
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ const values = response.data.values
+ expect(values.some((v: any) => v.value === s1.offer.id)).toBe(true)
+ expect(values.some((v: any) => v.value === s2.offer.id)).toBe(true)
+
+ const own = values.find((v: any) => v.value === s1.offer.id)
+ expect(own.label).toEqual("ADMIN-VO-S1-OFFER")
+ })
+
+ it("scopes offer value options to a store via seller_id", async () => {
+ const s1 = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Admin Scoped Seller One",
+ offerSku: "ADMIN-SCOPED-S1-OFFER",
+ })
+ const s2 = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Admin Scoped Seller Two",
+ offerSku: "ADMIN-SCOPED-S2-OFFER",
+ })
+
+ const response = await api.get(
+ `/admin/promotions/rule-value-options/target-rules/offer?seller_id=${s1.seller.id}`,
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ const values = response.data.values
+ expect(values.some((v: any) => v.value === s1.offer.id)).toBe(true)
+ expect(values.some((v: any) => v.value === s2.offer.id)).toBe(false)
+ })
+
+ it("creates a promotion targeting a specific offer", async () => {
+ const { offer } = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Admin Create Seller",
+ offerSku: "ADMIN-CREATE-OFFER",
+ })
+
+ const response = await api.post(
+ `/admin/promotions`,
+ {
+ code: "ADMIN-OFFER10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "fixed",
+ target_type: "items",
+ allocation: "each",
+ value: 500,
+ currency_code: "usd",
+ max_quantity: 1,
+ target_rules: [
+ {
+ attribute: "items.metadata.offer_id",
+ operator: "in",
+ values: [offer.id],
+ },
+ ],
+ },
+ },
+ adminHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(response.data.promotion.code).toEqual("ADMIN-OFFER10")
+ const targetRules =
+ response.data.promotion.application_method.target_rules
+ expect(
+ targetRules.some((r: any) => r.attribute === "items.metadata.offer_id")
+ ).toBe(true)
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/promotions/admin/owner.spec.ts b/integration-tests/http/promotions/admin/owner.spec.ts
new file mode 100644
index 000000000..8b674092c
--- /dev/null
+++ b/integration-tests/http/promotions/admin/owner.spec.ts
@@ -0,0 +1,242 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { createAdminUser, adminHeaders } from "../../../helpers/create-admin-user"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Promotion owner (seller)", () => {
+ let appContainer: MedusaContainer
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+ })
+
+ it("exposes the owning seller on a vendor promotion", async () => {
+ const { seller, headers } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Owner Store",
+ })
+
+ const promotion = (
+ await api.post(
+ `/vendor/promotions`,
+ {
+ code: "OWNED10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ headers
+ )
+ ).data.promotion
+
+ const detail = await api.get(
+ `/admin/promotions/${promotion.id}?fields=%2Bseller.id,%2Bseller.name`,
+ adminHeaders
+ )
+
+ expect(detail.status).toEqual(200)
+ expect(detail.data.promotion.seller?.id).toEqual(seller.id)
+ expect(detail.data.promotion.seller?.name).toEqual("Owner Store")
+ })
+
+ it("has no seller on a platform (admin) promotion", async () => {
+ const promotion = (
+ await api.post(
+ `/admin/promotions`,
+ {
+ code: "PLATFORM10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ adminHeaders
+ )
+ ).data.promotion
+
+ const detail = await api.get(
+ `/admin/promotions/${promotion.id}?fields=%2Bseller.id,%2Bseller.name`,
+ adminHeaders
+ )
+
+ expect(detail.status).toEqual(200)
+ expect(detail.data.promotion.seller ?? null).toBeNull()
+ })
+
+ it("upserts and exposes the coverage (cost_bearer) via the cost endpoint", async () => {
+ const promotion = (
+ await api.post(
+ `/admin/promotions`,
+ {
+ code: "COVERAGE10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ adminHeaders
+ )
+ ).data.promotion
+
+ const created = await api.post(
+ `/admin/promotions/${promotion.id}/cost`,
+ { cost_bearer: "marketplace" },
+ adminHeaders
+ )
+ expect(created.status).toEqual(200)
+ expect(created.data.promotion_cost.cost_bearer).toEqual("marketplace")
+
+ const afterCreate = await api.get(
+ `/admin/promotions/${promotion.id}?fields=%2Bpromotion_cost.cost_bearer`,
+ adminHeaders
+ )
+ expect(afterCreate.data.promotion.promotion_cost?.cost_bearer).toEqual(
+ "marketplace"
+ )
+
+ // Upsert again — the one-per-promotion record is updated, not duplicated.
+ const updated = await api.post(
+ `/admin/promotions/${promotion.id}/cost`,
+ { cost_bearer: "shared", shared_marketplace_percentage: 40 },
+ adminHeaders
+ )
+ expect(updated.status).toEqual(200)
+ expect(updated.data.promotion_cost.cost_bearer).toEqual("shared")
+
+ const afterUpdate = await api.get(
+ `/admin/promotions/${promotion.id}?fields=%2Bpromotion_cost.cost_bearer,%2Bpromotion_cost.shared_marketplace_percentage`,
+ adminHeaders
+ )
+ expect(afterUpdate.data.promotion.promotion_cost?.cost_bearer).toEqual(
+ "shared"
+ )
+ expect(
+ afterUpdate.data.promotion.promotion_cost?.shared_marketplace_percentage
+ ).toEqual(40)
+ })
+
+ it("filters the promotion list by owning seller", async () => {
+ const { seller, headers } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Filter Store",
+ })
+
+ const vendorPromotion = (
+ await api.post(
+ `/vendor/promotions`,
+ {
+ code: "FILTERVENDOR10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ headers
+ )
+ ).data.promotion
+
+ await api.post(
+ `/admin/promotions`,
+ {
+ code: "FILTERPLATFORM10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ adminHeaders
+ )
+
+ const bySeller = await api.get(
+ `/admin/promotions?seller_id=${seller.id}&fields=%2Bseller.id`,
+ adminHeaders
+ )
+
+ expect(bySeller.status).toEqual(200)
+ expect(bySeller.data.promotions).toHaveLength(1)
+ expect(bySeller.data.promotions[0].id).toEqual(vendorPromotion.id)
+ })
+
+ it("filters the promotion list to platform-owned promotions", async () => {
+ const { headers } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Platform Filter Store",
+ })
+
+ const platformPromotion = (
+ await api.post(
+ `/admin/promotions`,
+ {
+ code: "PLATFORMONLY10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ adminHeaders
+ )
+ ).data.promotion
+
+ const vendorPromotion = (
+ await api.post(
+ `/vendor/promotions`,
+ {
+ code: "PLATFORMFILTERVENDOR10",
+ type: "standard",
+ status: "active",
+ application_method: {
+ type: "percentage",
+ target_type: "order",
+ allocation: "across",
+ value: 10,
+ },
+ },
+ headers
+ )
+ ).data.promotion
+
+ const platformOnly = await api.get(
+ `/admin/promotions?seller_id=platform`,
+ adminHeaders
+ )
+
+ expect(platformOnly.status).toEqual(200)
+ const ids = platformOnly.data.promotions.map(
+ (p: { id: string }) => p.id
+ )
+ expect(ids).toContain(platformPromotion.id)
+ expect(ids).not.toContain(vendorPromotion.id)
+ })
+ })
+ },
+})
diff --git a/packages/admin/src/components/common/empty-table-content/empty-table-content.tsx b/packages/admin/src/components/common/empty-table-content/empty-table-content.tsx
index 88dfe2be0..fff3c5fe9 100644
--- a/packages/admin/src/components/common/empty-table-content/empty-table-content.tsx
+++ b/packages/admin/src/components/common/empty-table-content/empty-table-content.tsx
@@ -16,7 +16,7 @@ export const NoResults = ({ title, message, className }: NoResultsProps) => {
return (
<div
className={clx(
- "flex min-h-[400px] size-full items-center justify-center",
+ "flex h-[150px] w-full items-center justify-center",
className
)}
>
@@ -38,6 +38,7 @@ type ActionProps = {
to: string
label: string
}
+ dataTestId?: string
}
export type NoRecordsProps = {
@@ -48,19 +49,23 @@ export type NoRecordsProps = {
icon?: React.ReactNode
} & ActionProps
-const DefaultButton = ({ action }: ActionProps) =>
+const DefaultButton = ({ action, dataTestId }: ActionProps) =>
action && (
<Link to={action.to}>
- <Button variant="secondary" size="small">
+ <Button variant="secondary" size="small" data-testid={dataTestId}>
{action.label}
</Button>
</Link>
)
-const TransparentIconLeftButton = ({ action }: ActionProps) =>
+const TransparentIconLeftButton = ({ action, dataTestId }: ActionProps) =>
action && (
<Link to={action.to}>
- <Button variant="transparent" className="text-ui-fg-interactive">
+ <Button
+ variant="transparent"
+ className="text-ui-fg-interactive"
+ data-testid={dataTestId}
+ >
<PlusMini /> {action.label}
</Button>
</Link>
@@ -72,6 +77,7 @@ export const NoRecords = ({
action,
className,
buttonVariant = "default",
+ dataTestId,
icon = <ExclamationCircle className="text-ui-fg-subtle" />,
}: NoRecordsProps) => {
const { t } = useTranslation()
@@ -79,7 +85,7 @@ export const NoRecords = ({
return (
<div
className={clx(
- "flex min-h-[400px] size-full flex-col items-center justify-center gap-y-4",
+ "flex h-[150px] w-full flex-col items-center justify-center gap-y-4",
className
)}
>
@@ -100,9 +106,11 @@ export const NoRecords = ({
</div>
</div>
- {buttonVariant === "default" && <DefaultButton action={action} />}
+ {buttonVariant === "default" && (
+ <DefaultButton action={action} dataTestId={dataTestId} />
+ )}
{buttonVariant === "transparentIconLeft" && (
- <TransparentIconLeftButton action={action} />
+ <TransparentIconLeftButton action={action} dataTestId={dataTestId} />
)}
</div>
)
diff --git a/packages/admin/src/components/table/data-table/data-table.tsx b/packages/admin/src/components/table/data-table/data-table.tsx
index 4f4019965..d9e736eb7 100644
--- a/packages/admin/src/components/table/data-table/data-table.tsx
+++ b/packages/admin/src/components/table/data-table/data-table.tsx
@@ -11,7 +11,7 @@ interface DataTableProps<TData>
isLoading?: boolean
pageSize: number
queryObject?: Record<string, any>
- noRecords?: Pick<NoRecordsProps, "title" | "message" | "icon">
+ noRecords?: Pick<NoRecordsProps, "title" | "message" | "icon" | "action">
}
// Maybe we should use the memoized version of DataTableRoot
diff --git a/packages/admin/src/components/table/table-cells/promotion/status-cell/status-cell.tsx b/packages/admin/src/components/table/table-cells/promotion/status-cell/status-cell.tsx
index 6aed39984..e6b086ce1 100644
--- a/packages/admin/src/components/table/table-cells/promotion/status-cell/status-cell.tsx
+++ b/packages/admin/src/components/table/table-cells/promotion/status-cell/status-cell.tsx
@@ -1,6 +1,6 @@
import { HttpTypes } from "@medusajs/types"
import { getPromotionStatus } from "../../../../../lib/promotions"
-import { StatusCell as StatusCell_ } from "../../common/status-cell"
+import { DataTableStatusCell } from "@/components/data-table/components/data-table-status-cell/data-table-status-cell"
type PromotionCellProps = {
promotion: HttpTypes.AdminPromotion
@@ -9,5 +9,5 @@ type PromotionCellProps = {
export const StatusCell = ({ promotion }: PromotionCellProps) => {
const [color, text] = getPromotionStatus(promotion)
- return <StatusCell_ color={color}>{text}</StatusCell_>
+ return <DataTableStatusCell color={color}>{text}</DataTableStatusCell>
}
diff --git a/packages/admin/src/extension-targets.d.ts b/packages/admin/src/extension-targets.d.ts
index 23f3268c1..330923a5b 100644
--- a/packages/admin/src/extension-targets.d.ts
+++ b/packages/admin/src/extension-targets.d.ts
@@ -251,7 +251,7 @@ declare module "@mercurjs/dashboard-sdk" {
formZones: "create" | "edit"
formTabs: { "create": "campaign" | "promotion" | "type" }
displayZones: "campaign" | "general"
- displayFieldIds: "allocation" | "code" | "code_badge" | "is_automatic" | "is_tax_inclusive" | "status" | "type" | "value"
+ displayFieldIds: "allocation" | "code" | "code_badge" | "coverage" | "is_automatic" | "is_tax_inclusive" | "owner" | "status" | "type" | "usage_limit" | "value"
}
"reservation": {
formZones: "edit"
diff --git a/packages/admin/src/hooks/api/promotions.tsx b/packages/admin/src/hooks/api/promotions.tsx
index 87e13fc1e..e330c1e46 100644
--- a/packages/admin/src/hooks/api/promotions.tsx
+++ b/packages/admin/src/hooks/api/promotions.tsx
@@ -60,6 +60,30 @@ export const usePromotion = (
return { ...data, ...rest }
}
+type UpsertPromotionCostPayload = {
+ id: string
+ cost_bearer: "store" | "marketplace" | "shared"
+ shared_marketplace_percentage?: number | null
+}
+
+export const useUpsertPromotionCost = (
+ options?: UseMutationOptions<
+ { promotion_cost: unknown },
+ ClientError,
+ UpsertPromotionCostPayload
+ >
+) => {
+ return useMutation({
+ mutationFn: ({ id, ...payload }: UpsertPromotionCostPayload) =>
+ sdk.admin.promotions.$id.cost.mutate({ $id: id, ...payload }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: promotionsQueryKeys.detail(variables.id) })
+ options?.onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
+
export const usePromotionRules = (
id: string | null,
ruleType: string,
diff --git a/packages/admin/src/hooks/table/columns/use-promotion-table-columns.tsx b/packages/admin/src/hooks/table/columns/use-promotion-table-columns.tsx
index f9cfd81b7..ecd6630df 100644
--- a/packages/admin/src/hooks/table/columns/use-promotion-table-columns.tsx
+++ b/packages/admin/src/hooks/table/columns/use-promotion-table-columns.tsx
@@ -1,4 +1,5 @@
import { HttpTypes } from "@medusajs/types"
+import { SellerDTO } from "@mercurjs/types"
import { createColumnHelper } from "@tanstack/react-table"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
@@ -12,6 +13,7 @@ import {
TextHeader,
} from "../../../components/table/table-cells/common/text-cell"
import { StatusCell } from "../../../components/table/table-cells/promotion/status-cell"
+import { getPromotionType } from "../../../lib/promotions"
const columnHelper = createColumnHelper<HttpTypes.AdminPromotion>()
@@ -26,6 +28,12 @@ export const usePromotionTableColumns = () => {
cell: ({ row }) => <CodeCell code={row.original.code!} />,
}),
+ columnHelper.display({
+ id: "type",
+ header: () => <TextHeader text={t("promotions.fields.type")} />,
+ cell: ({ row }) => <TextCell text={getPromotionType(row.original)} />,
+ }),
+
columnHelper.display({
id: "method",
header: () => <TextHeader text={t("promotions.fields.method")} />,
@@ -38,6 +46,32 @@ export const usePromotionTableColumns = () => {
},
}),
+ columnHelper.display({
+ id: "campaign",
+ header: () => <TextHeader text={t("promotions.fields.campaign")} />,
+ cell: ({ row }) => (
+ <TextCell text={row.original.campaign?.name ?? "-"} />
+ ),
+ }),
+
+ columnHelper.display({
+ id: "owner",
+ header: () => <TextHeader text={t("promotions.fields.owner")} />,
+ cell: ({ row }) => {
+ const promotion = row.original as HttpTypes.AdminPromotion & {
+ seller?: Pick<SellerDTO, "name"> | null
+ }
+
+ return (
+ <TextCell
+ text={
+ promotion.seller?.name ?? t("promotions.fields.platformOwner")
+ }
+ />
+ )
+ },
+ }),
+
columnHelper.display({
id: "status",
header: () => <TextHeader text={t("fields.status")} />,
diff --git a/packages/admin/src/hooks/table/filters/use-promotion-table-filters.tsx b/packages/admin/src/hooks/table/filters/use-promotion-table-filters.tsx
index 246191a7c..ac84d84a1 100644
--- a/packages/admin/src/hooks/table/filters/use-promotion-table-filters.tsx
+++ b/packages/admin/src/hooks/table/filters/use-promotion-table-filters.tsx
@@ -1,13 +1,82 @@
import { useTranslation } from "react-i18next"
+import { useMemo } from "react"
+
import { Filter } from "../../../components/table/data-table"
+import { useCampaigns } from "../../api/campaigns"
+import { useSellers } from "../../api/sellers"
-export const usePromotionTableFilters = () => {
+export const usePromotionTableFilters = (): Filter[] => {
const { t } = useTranslation()
- let filters: Filter[] = [
- { label: t("fields.createdAt"), key: "created_at", type: "date" },
- { label: t("fields.updatedAt"), key: "updated_at", type: "date" },
- ]
+ const { campaigns } = useCampaigns({ limit: 100, fields: "id,name" })
+ const { sellers } = useSellers({ limit: 100, fields: "id,name" })
+
+ return useMemo(() => {
+ const typeFilter: Filter = {
+ key: "application_method_type",
+ label: t("promotions.fields.type"),
+ type: "select",
+ options: [
+ {
+ label: t("promotions.fields.typeLabels.percentageItems"),
+ value: "percentage",
+ },
+ {
+ label: t("promotions.fields.typeLabels.amountItems"),
+ value: "fixed",
+ },
+ ],
+ }
+
+ const methodFilter: Filter = {
+ key: "is_automatic",
+ label: t("promotions.fields.method"),
+ type: "select",
+ options: [
+ { label: t("promotions.form.method.code.title"), value: "false" },
+ {
+ label: t("promotions.form.method.automatic.title"),
+ value: "true",
+ },
+ ],
+ }
+
+ const campaignFilter: Filter = {
+ key: "campaign_id",
+ label: t("promotions.fields.campaign"),
+ type: "select",
+ searchable: true,
+ options: (campaigns ?? []).map((campaign) => ({
+ label: campaign.name!,
+ value: campaign.id,
+ })),
+ }
+
+ const ownerFilter: Filter = {
+ key: "seller_id",
+ label: t("promotions.fields.owner"),
+ type: "select",
+ searchable: true,
+ options: [
+ { label: t("promotions.fields.platformOwner"), value: "platform" },
+ ...(sellers ?? []).map((seller) => ({
+ label: seller.name!,
+ value: seller.id,
+ })),
+ ],
+ }
+
+ const dateFilters: Filter[] = [
+ { label: t("fields.createdAt"), key: "created_at", type: "date" },
+ { label: t("fields.updatedAt"), key: "updated_at", type: "date" },
+ ]
- return filters
+ return [
+ typeFilter,
+ methodFilter,
+ campaignFilter,
+ ownerFilter,
+ ...dateFilters,
+ ]
+ }, [t, campaigns, sellers])
}
diff --git a/packages/admin/src/hooks/table/query/use-promotion-table-query.tsx b/packages/admin/src/hooks/table/query/use-promotion-table-query.tsx
index 75892295e..7c4753f72 100644
--- a/packages/admin/src/hooks/table/query/use-promotion-table-query.tsx
+++ b/packages/admin/src/hooks/table/query/use-promotion-table-query.tsx
@@ -11,18 +11,50 @@ export const usePromotionTableQuery = ({
pageSize = 20,
}: UsePromotionTableQueryProps) => {
const queryObject = useQueryParams(
- ["offset", "q", "order", "created_at", "updated_at"],
+ [
+ "offset",
+ "q",
+ "order",
+ "created_at",
+ "updated_at",
+ "campaign_id",
+ "is_automatic",
+ "application_method_type",
+ "seller_id",
+ ],
prefix
)
- const { offset, q, order, created_at, updated_at } = queryObject
+ const {
+ offset,
+ q,
+ order,
+ created_at,
+ updated_at,
+ campaign_id,
+ is_automatic,
+ application_method_type,
+ seller_id,
+ } = queryObject
- const searchParams: HttpTypes.AdminGetPromotionsParams = {
+ const searchParams: HttpTypes.AdminGetPromotionsParams & {
+ is_automatic?: boolean
+ campaign_id?: string
+ application_method?: { type?: string }
+ seller_id?: string
+ } = {
limit: pageSize,
+ fields: "+seller.id,+seller.name",
created_at: created_at ? JSON.parse(created_at) : undefined,
updated_at: updated_at ? JSON.parse(updated_at) : undefined,
+ campaign_id: campaign_id || undefined,
+ seller_id: seller_id || undefined,
+ is_automatic: is_automatic ? is_automatic === "true" : undefined,
+ application_method: application_method_type
+ ? { type: application_method_type }
+ : undefined,
offset: offset ? Number(offset) : 0,
- order,
+ order: order || "-created_at",
q,
}
diff --git a/packages/admin/src/i18n/translations/$schema.json b/packages/admin/src/i18n/translations/$schema.json
index b8a2a7043..9c9fdc030 100644
--- a/packages/admin/src/i18n/translations/$schema.json
+++ b/packages/admin/src/i18n/translations/$schema.json
@@ -9451,20 +9451,25 @@
"type": "string"
}
}
- },
- "freeShipping": {
- "type": "object",
- "properties": {
- "title": {
- "type": "string"
- },
- "description": {
- "type": "string"
- }
- }
}
}
},
+ "list": {
+ "type": "object",
+ "properties": {
+ "noRecords": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ },
"domain": {
"type": "string"
},
@@ -9506,21 +9511,62 @@
"type": {
"type": "string"
},
+ "typeLabels": {
+ "type": "object",
+ "properties": {
+ "percentageItems": {
+ "type": "string"
+ },
+ "percentageShipping": {
+ "type": "string"
+ },
+ "percentageOrder": {
+ "type": "string"
+ },
+ "amountItems": {
+ "type": "string"
+ },
+ "amountShipping": {
+ "type": "string"
+ },
+ "amountOrder": {
+ "type": "string"
+ }
+ }
+ },
"value_type": {
"type": "string"
},
"value": {
"type": "string"
},
+ "promotion_value": {
+ "type": "string"
+ },
"campaign": {
"type": "string"
},
"method": {
"type": "string"
},
+ "owner": {
+ "type": "string"
+ },
+ "platformOwner": {
+ "type": "string"
+ },
+ "coverage": {
+ "type": "string"
+ },
"allocation": {
"type": "string"
},
+ "usageLimit": {
+ "type": "string"
+ },
+ "unlimited": {
+ "type": "string"
+ },
"addCondition": {
"type": "string"
},
@@ -9649,9 +9695,15 @@
"type",
"value_type",
"value",
+ "promotion_value",
"campaign",
"method",
+ "owner",
+ "platformOwner",
+ "coverage",
"allocation",
+ "usageLimit",
+ "unlimited",
"addCondition",
"clearAll",
"taxInclusive",
@@ -9660,6 +9712,43 @@
],
"additionalProperties": false
},
+ "campaignSection": {
+ "type": "object",
+ "properties": {
+ "noRecordsTitle": {
+ "type": "string"
+ },
+ "noRecordsMessage": {
+ "type": "string"
+ },
+ "addToCampaign": {
+ "type": "string"
+ },
+ "warnings": {
+ "type": "object",
+ "properties": {
+ "promotionMustBeActive": {
+ "type": "string"
+ },
+ "promotionExpires": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "promotionMustBeActive",
+ "promotionExpires"
+ ],
+ "additionalProperties": false
+ }
+ },
+ "required": [
+ "noRecordsTitle",
+ "noRecordsMessage",
+ "addToCampaign",
+ "warnings"
+ ],
+ "additionalProperties": false
+ },
"tooltips": {
"type": "object",
"properties": {
@@ -9915,6 +10004,34 @@
],
"additionalProperties": false
},
+ "storeOffers": {
+ "type": "object",
+ "properties": {
+ "title": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "label": {
+ "type": "string"
+ },
+ "placeholder": {
+ "type": "string"
+ },
+ "required": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "title",
+ "description",
+ "label",
+ "placeholder",
+ "required"
+ ],
+ "additionalProperties": false
+ },
"status": {
"type": "object",
"properties": {
@@ -10163,12 +10280,16 @@
"title": {
"type": "string"
},
+ "description": {
+ "type": "string"
+ },
"invalid": {
"type": "string"
}
},
"required": [
"title",
+ "description",
"invalid"
],
"additionalProperties": false
@@ -10251,11 +10372,15 @@
"list": {
"type": "object",
"properties": {
+ "noRecordsTitle": {
+ "type": "string"
+ },
"noRecordsMessage": {
"type": "string"
}
},
"required": [
+ "noRecordsTitle",
"noRecordsMessage"
],
"additionalProperties": false
diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.json
index 83e8576a6..0f19fe40a 100644
--- a/packages/admin/src/i18n/translations/en.json
+++ b/packages/admin/src/i18n/translations/en.json
@@ -2338,7 +2338,7 @@
"promotions": {
"templates": {
"amountOffProducts": {
- "title": "Amount off products",
+ "title": "Amount off items",
"description": "Discount specific products or collection of products"
},
"amountOffOrder": {
@@ -2346,7 +2346,7 @@
"description": "Discounts the total order amount"
},
"percentageOffProduct": {
- "title": "Percentage off product",
+ "title": "Percentage off items",
"description": "Discounts a percentage off selected products"
},
"percentageOffOrder": {
@@ -2356,10 +2356,12 @@
"buyGet": {
"title": "Buy X Get Y",
"description": "Buy X product(s), get Y product(s)"
- },
- "freeShipping": {
- "title": "Free shipping",
- "description": "Applies a 100% discount to shipping fees"
+ }
+ },
+ "list": {
+ "noRecords": {
+ "title": "No promotions yet",
+ "message": "Create promotions to offer discounts"
}
},
"domain": "Promotions",
@@ -2373,14 +2375,28 @@
},
"fields": {
"type": "Type",
+ "typeLabels": {
+ "percentageItems": "Percentage off items",
+ "percentageShipping": "Percentage off shipping",
+ "percentageOrder": "Percentage off order",
+ "amountItems": "Amount off items",
+ "amountShipping": "Amount off shipping",
+ "amountOrder": "Amount off order"
+ },
"value_type": "Value Type",
"value": "Value",
+ "promotion_value": "Promotion Value",
"campaign": "Campaign",
"method": "Method",
+ "owner": "Owner",
+ "platformOwner": "Mercur",
+ "coverage": "Coverage",
"allocation": "Allocation",
+ "usageLimit": "Usage limit",
+ "unlimited": "Unlimited",
"addCondition": "Add condition",
"clearAll": "Clear all",
- "taxInclusive": "Tax Inclusive",
+ "taxInclusive": "Taxes Included",
"amount": {
"tooltip": "Select the currency code to enable setting the amount"
},
@@ -2421,7 +2437,7 @@
},
"create": {},
"edit": {
- "title": "Edit Promotion Details",
+ "title": "Edit Promotions",
"rules": {
"title": "Edit usage conditions"
},
@@ -2448,7 +2464,11 @@
"campaignSection": {
"noRecordsTitle": "Not part of a campaign",
"noRecordsMessage": "Add this promotion to an existing campaign",
- "addToCampaign": "Add to Campaign"
+ "addToCampaign": "Add to Campaign",
+ "warnings": {
+ "promotionMustBeActive": "This promotion is part of a campaign but is not active, so it won't apply at checkout.",
+ "promotionExpires": "This campaign has an end date. The promotion will stop applying once the campaign ends."
+ }
},
"form": {
"required": "Required",
@@ -2478,6 +2498,38 @@
"title": "Does promotion include taxes?",
"description": "Enable this field to apply the promotion after taxes"
},
+ "limit": {
+ "title": "Usage Limit",
+ "description": "Maximum number of times this promotion can be used across all orders. Leave empty for unlimited usage."
+ },
+ "storeOffers": {
+ "title": "Which store offers will the promotion be applied to?",
+ "description": "Choose the store whose offers this promotion applies to.",
+ "label": "Store",
+ "placeholder": "Select",
+ "required": "Please select a store"
+ },
+ "costBearer": {
+ "label": "Who will cover the cost of promotion?",
+ "description": "Select who is responsible for covering the discount applied by this promotion.",
+ "tip": "Changes to created promotion won't affect orders that are already in progress.",
+ "store": {
+ "title": "Store",
+ "description": "The discount is deducted from the store's earnings"
+ },
+ "marketplace": {
+ "title": "Marketplace",
+ "description": "The discount is deducted from the commission"
+ },
+ "shared": {
+ "title": "Shared",
+ "description": "The cost is split between the marketplace and store"
+ },
+ "sharedPercentage": {
+ "title": "Marketplace share",
+ "description": "Percentage of the discount covered by the marketplace. The store covers the rest."
+ }
+ },
"status": {
"label": "Status",
"draft": {
@@ -2538,6 +2590,7 @@
},
"value": {
"title": "Promotion Value",
+ "description": "The amount to be discounted. eg. 100",
"invalid": "Invalid promotion value"
},
"value_type": {
@@ -2557,7 +2610,8 @@
"conditions": {
"add": "Add condition",
"list": {
- "noRecordsMessage": "Add a condition to restrict what items the promotion applies to."
+ "noRecordsTitle": "No conditions yet",
+ "noRecordsMessage": "Add a condition to restrict what items the promotion applies to"
}
}
},
diff --git a/packages/admin/src/lib/promotions.ts b/packages/admin/src/lib/promotions.ts
index 001c8462b..801b2cef0 100644
--- a/packages/admin/src/lib/promotions.ts
+++ b/packages/admin/src/lib/promotions.ts
@@ -25,6 +25,28 @@ const getPromotionStatusMap = (): Record<string, [StatusColors, string]> => ({
],
})
+export const getPromotionType = (promotion: HttpTypes.AdminPromotion) => {
+ const applicationMethod = promotion.application_method
+
+ if (!applicationMethod?.type) {
+ return "-"
+ }
+
+ const base =
+ applicationMethod.type === "fixed"
+ ? "promotions.fields.typeLabels.amount"
+ : "promotions.fields.typeLabels.percentage"
+
+ const targetSuffix =
+ applicationMethod.target_type === "shipping_methods"
+ ? "Shipping"
+ : applicationMethod.target_type === "order"
+ ? "Order"
+ : "Items"
+
+ return i18n.t(`${base}${targetSuffix}`)
+}
+
export const getPromotionStatus = (promotion: HttpTypes.AdminPromotion) => {
const date = new Date()
const campaign = promotion.campaign
diff --git a/packages/admin/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx b/packages/admin/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
index c77b4b84b..3ebccda72 100644
--- a/packages/admin/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
+++ b/packages/admin/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
@@ -1,4 +1,4 @@
-import { useEffect } from "react";
+import { useEffect, useRef } from "react";
import {
ApplicationMethodTargetTypeValues,
@@ -69,6 +69,12 @@ export const RuleValueFormField = ({
name: name,
});
+ const isOfferAttribute = attribute?.id === "offer";
+ const sellerId = useWatch({
+ control: form.control,
+ name: "seller_id",
+ }) as string | undefined;
+
const comboboxData = useComboboxData({
queryFn: async (params) => {
return await sdk.admin.promotions.ruleValueOptions.$ruleType.$ruleAttributeId.query({
@@ -76,15 +82,17 @@ export const RuleValueFormField = ({
$ruleAttributeId: attribute?.id,
...params,
...buildFilters(attribute?.id, store!),
+ ...(isOfferAttribute && sellerId ? { seller_id: sellerId } : {}),
application_method_target_type: applicationMethodTargetType,
});
},
enabled:
!!attribute?.id &&
["select", "multiselect"].includes(attribute.field_type) &&
- !isStoreLoading,
+ !isStoreLoading &&
+ (!isOfferAttribute || !!sellerId),
getOptions: (data) => data.values,
- queryKey: ["rule-value-options", ruleType, attribute?.id],
+ queryKey: ["rule-value-options", ruleType, attribute?.id, sellerId],
defaultValue: watchValue,
defaultValueKey: "value",
});
@@ -94,16 +102,15 @@ export const RuleValueFormField = ({
name: operator,
});
- useEffect(() => {
- const hasDirtyRules = Object.keys(form.formState.dirtyFields).length > 0;
+ const prevOperatorRef = useRef(watchOperator);
- /**
- * Don't reset values if fileds didn't change - this is to prevent reset of form on initial render when editing an existing rule
- */
- if (!hasDirtyRules) {
+ useEffect(() => {
+ if (prevOperatorRef.current === watchOperator) {
return;
}
+ prevOperatorRef.current = watchOperator;
+
if (watchOperator === "eq") {
form.setValue(name, "");
} else {
@@ -111,7 +118,6 @@ export const RuleValueFormField = ({
}
}, [
watchOperator,
- form.formState.dirtyFields,
name,
form
]);
diff --git a/packages/admin/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts b/packages/admin/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
index 21c70423e..f3f1e6679 100644
--- a/packages/admin/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
+++ b/packages/admin/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
@@ -1,7 +1,7 @@
export const requiredProductRule = {
- id: "product",
- attribute: "items.product.id",
- attribute_label: "Product",
+ id: "offer",
+ attribute: "items.metadata.offer_id",
+ attribute_label: "Offer",
operator: "eq",
operator_label: "Equal",
values: [],
diff --git a/packages/admin/src/pages/promotions/common/edit-rules/edit-rules.tsx b/packages/admin/src/pages/promotions/common/edit-rules/edit-rules.tsx
index ecc8a0b81..9860e7f06 100644
--- a/packages/admin/src/pages/promotions/common/edit-rules/edit-rules.tsx
+++ b/packages/admin/src/pages/promotions/common/edit-rules/edit-rules.tsx
@@ -2,8 +2,11 @@ import { PromotionRuleDTO } from "@medusajs/types"
import { Heading } from "@medusajs/ui"
import { useTranslation } from "react-i18next"
import { useParams } from "react-router-dom"
+import { useLinkQuery } from "@mercurjs/dashboard-shared"
+
import { RouteDrawer } from "../../../../components/modals"
import { usePromotion } from "../../../../hooks/api/promotions"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../../promotion-detail/loader"
import { EditRulesWrapper } from "./components/edit-rules-wrapper"
export enum RuleType {
@@ -29,7 +32,11 @@ export const EditRules = () => {
const ruleType = params.ruleType as RuleTypeValues
const id = params.id as string
const rules: PromotionRuleDTO[] = []
- const { promotion, isPending: isLoading, isError, error } = usePromotion(id)
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
+ const { promotion, isPending: isLoading, isError, error } = usePromotion(
+ id,
+ linkQuery
+ )
if (promotion) {
if (ruleType === RuleType.RULES) {
diff --git a/packages/admin/src/pages/promotions/promotion-add-campaign/promotion-add-campaign.tsx b/packages/admin/src/pages/promotions/promotion-add-campaign/promotion-add-campaign.tsx
index 1f53c37c9..8f7c11e3b 100644
--- a/packages/admin/src/pages/promotions/promotion-add-campaign/promotion-add-campaign.tsx
+++ b/packages/admin/src/pages/promotions/promotion-add-campaign/promotion-add-campaign.tsx
@@ -2,14 +2,18 @@ import { Heading } from "@medusajs/ui"
import { useTranslation } from "react-i18next"
import { useParams } from "react-router-dom"
+import { useLinkQuery } from "@mercurjs/dashboard-shared"
+
import { RouteDrawer } from "../../../components/modals"
import { usePromotion } from "../../../hooks/api/promotions"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../promotion-detail/loader"
import { AddCampaignPromotionForm } from "./components/add-campaign-promotion-form"
export const PromotionAddCampaign = () => {
const { id } = useParams()
const { t } = useTranslation()
- const { promotion, isPending, isError, error } = usePromotion(id!)
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
+ const { promotion, isPending, isError, error } = usePromotion(id!, linkQuery)
if (isError) {
throw error
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
index 6c4c47572..192ca392e 100644
--- a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
@@ -16,7 +16,10 @@ import { z } from "zod"
import { useRouteModal } from "../../../../../components/modals"
import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
-import { useCreatePromotion } from "../../../../../hooks/api/promotions"
+import {
+ useCreatePromotion,
+ useUpsertPromotionCost,
+} from "../../../../../hooks/api/promotions"
import { DEFAULT_CAMPAIGN_VALUES } from "../../../../campaigns/common/constants"
import { CreatePromotionSchema, CreatePromotionSchemaType } from "./form-schema"
import { PromotionCampaignTab } from "./promotion-campaign-tab"
@@ -34,6 +37,9 @@ const PROMOTION_CREATE_DEFAULTS = {
status: "draft" as PromotionStatusValues,
rules: [],
is_tax_inclusive: false,
+ limit: undefined,
+ cost_bearer: "store" as const,
+ shared_marketplace_percentage: null,
application_method: {
allocation: "each" as ApplicationMethodAllocationValues,
type: "fixed" as ApplicationMethodTypeValues,
@@ -70,6 +76,7 @@ export function CreatePromotionForm({
const { mutateAsync: createPromotion, isPending: isLoading } =
useCreatePromotion()
+ const { mutateAsync: upsertPromotionCost } = useUpsertPromotionCost()
const handleSubmit = form.handleSubmit(
async (data) => {
@@ -83,7 +90,10 @@ export function CreatePromotionForm({
campaign_choice: _campaignChoice,
is_automatic,
is_tax_inclusive,
+ cost_bearer,
+ shared_marketplace_percentage,
template_id: _templateId,
+ seller_id: _sellerId,
application_method,
rules,
...promotionData
@@ -159,7 +169,20 @@ export function CreatePromotionForm({
is_automatic: is_automatic === "true",
},
{
- onSuccess: ({ promotion }) => {
+ onSuccess: async ({ promotion }) => {
+ try {
+ await upsertPromotionCost({
+ id: promotion.id,
+ cost_bearer,
+ shared_marketplace_percentage:
+ cost_bearer === "shared"
+ ? shared_marketplace_percentage
+ : null,
+ })
+ } catch (e) {
+ toast.error((e as Error).message)
+ }
+
toast.success(
t("promotions.toasts.promotionCreateSuccess", {
code: promotion.code,
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/form-schema.ts b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/form-schema.ts
index bdab67d7d..5d00fac5c 100644
--- a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/form-schema.ts
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/form-schema.ts
@@ -29,6 +29,10 @@ export const CreatePromotionSchema = z
status: z.enum(["draft", "active", "inactive"]),
rules: RuleSchema,
is_tax_inclusive: z.boolean().optional(),
+ seller_id: z.string().optional(),
+ limit: z.number().int().min(1).nullable().optional(),
+ cost_bearer: z.enum(["store", "marketplace", "shared"]),
+ shared_marketplace_percentage: z.number().min(0).max(100).nullable(),
application_method: z.object({
allocation: z.enum(["each", "across", "once"]),
value: z.number().min(0).or(z.string().min(1)),
@@ -54,5 +58,31 @@ export const CreatePromotionSchema = z
message: i18n.t("validation.requiredField"),
}
)
+ .refine(
+ (data) => {
+ if (data.cost_bearer !== "shared") {
+ return true
+ }
+
+ return typeof data.shared_marketplace_percentage === "number"
+ },
+ {
+ path: ["shared_marketplace_percentage"],
+ message: i18n.t("validation.requiredField"),
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.type !== "buyget") {
+ return true
+ }
+
+ return !!data.seller_id
+ },
+ {
+ path: ["seller_id"],
+ message: i18n.t("promotions.form.storeOffers.required"),
+ }
+ )
export type CreatePromotionSchemaType = z.infer<typeof CreatePromotionSchema>
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
index 1cf207670..c20e147ad 100644
--- a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
@@ -1,8 +1,6 @@
-import { useEffect, useState } from "react"
+import { useEffect, useState } from "react";
-import type {
- ApplicationMethodAllocationValues,
-} from "@medusajs/types"
+import type { ApplicationMethodAllocationValues } from "@medusajs/types";
import {
Alert,
Badge,
@@ -10,72 +8,96 @@ import {
CurrencyInput,
Divider,
Heading,
+ InlineTip,
Input,
RadioGroup,
- Switch,
Text,
-} from "@medusajs/ui"
-import { useWatch } from "react-hook-form"
-import { Trans, useTranslation } from "react-i18next"
-
-import { Form } from "../../../../../components/common/form"
-import { DeprecatedPercentageInput } from "../../../../../components/inputs/percentage-input"
-import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
-import { defineTabMeta } from "../../../../../components/tabbed-form/types"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
-import { currencies, getCurrencySymbol } from "../../../../../lib/data/currencies"
-import { RulesFormField } from "../../../common/edit-rules/components/rules-form-field"
-import { CreatePromotionSchemaType } from "./form-schema"
+} from "@medusajs/ui";
+import { useWatch } from "react-hook-form";
+import { Trans, useTranslation } from "react-i18next";
+
+import { Form } from "../../../../../components/common/form";
+import { DeprecatedPercentageInput } from "../../../../../components/inputs/percentage-input";
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form";
+import { defineTabMeta } from "../../../../../components/tabbed-form/types";
+import { Combobox } from "../../../../../components/inputs/combobox";
+import { useComboboxData } from "../../../../../hooks/use-combobox-data";
+import { useDocumentDirection } from "../../../../../hooks/use-document-direction";
+import { sdk } from "../../../../../lib/client";
+import {
+ currencies,
+ getCurrencySymbol,
+} from "../../../../../lib/data/currencies";
+import { RulesFormField } from "../../../common/edit-rules/components/rules-form-field";
+import { CreatePromotionSchemaType } from "./form-schema";
+import { SwitchBox } from "@mercurjs/dashboard-shared";
-type AllocationMode = "each" | "across" | "once"
+type AllocationMode = "each" | "across" | "once";
type PromotionDetailsTabProps = {
currentTemplate?: {
- id: string
- titleKey: string
- hiddenFields: string[]
- }
-}
+ id: string;
+ titleKey: string;
+ hiddenFields: string[];
+ };
+};
const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
- const { t } = useTranslation()
- const direction = useDocumentDirection()
- const form = useTabbedForm<CreatePromotionSchemaType>()
- const { setValue } = form
+ const { t } = useTranslation();
+ const direction = useDocumentDirection();
+ const form = useTabbedForm<CreatePromotionSchemaType>();
+ const { setValue } = form;
- const [allocationMode, setAllocationMode] = useState<AllocationMode>("each")
+ const [allocationMode, setAllocationMode] = useState<AllocationMode>("each");
const watchValueType = useWatch({
control: form.control,
name: "application_method.type",
- })
- const isFixedValueType = watchValueType === "fixed"
+ });
+ const isFixedValueType = watchValueType === "fixed";
const watchAllocation = useWatch({
control: form.control,
name: "application_method.allocation",
- })
+ });
useEffect(() => {
if (watchAllocation) {
- setAllocationMode(watchAllocation as AllocationMode)
+ setAllocationMode(watchAllocation as AllocationMode);
}
- }, [watchAllocation])
+ }, [watchAllocation]);
const watchType = useWatch({
control: form.control,
name: "type",
- })
+ });
- const isTypeStandard = watchType === "standard"
- const isTypeBuyGet = watchType === "buyget"
+ const isTypeStandard = watchType === "standard";
+ const isTypeBuyGet = watchType === "buyget";
const targetType = useWatch({
control: form.control,
name: "application_method.target_type",
- })
+ });
- const isTargetTypeOrder = targetType === "order"
+ const isTargetTypeOrder = targetType === "order";
+
+ const watchCostBearer = useWatch({
+ control: form.control,
+ name: "cost_bearer",
+ });
+ const isSharedCost = watchCostBearer === "shared";
+
+ const stores = useComboboxData({
+ queryKey: ["promotion_stores"],
+ queryFn: (params) => sdk.admin.sellers.query({ ...params, fields: "id,name" }),
+ getOptions: (data) =>
+ data.sellers.map((seller: { id: string; name: string }) => ({
+ label: seller.name,
+ value: seller.id,
+ })),
+ enabled: isTypeBuyGet,
+ });
return (
<div className="flex size-full flex-col items-center">
@@ -142,7 +164,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
value="true"
label={t("promotions.form.method.automatic.title")}
description={t(
- "promotions.form.method.automatic.description"
+ "promotions.form.method.automatic.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-method-option-automatic"
@@ -151,7 +173,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Form.Control>
<Form.ErrorMessage data-testid="promotion-create-form-method-error" />
</Form.Item>
- )
+ );
}}
/>
@@ -178,7 +200,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
value="draft"
label={t("promotions.form.status.draft.title")}
description={t(
- "promotions.form.status.draft.description"
+ "promotions.form.status.draft.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-status-option-draft"
@@ -188,7 +210,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
value="active"
label={t("promotions.form.status.active.title")}
description={t(
- "promotions.form.status.active.description"
+ "promotions.form.status.active.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-status-option-active"
@@ -197,7 +219,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Form.Control>
<Form.ErrorMessage data-testid="promotion-create-form-status-error" />
</Form.Item>
- )
+ );
}}
/>
@@ -237,59 +259,144 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Text>
<Form.ErrorMessage data-testid="promotion-create-form-code-error" />
</Form.Item>
- )
+ );
}}
/>
</div>
{!currentTemplate?.hiddenFields?.includes("is_tax_inclusive") && (
<>
- <Divider />
- <div className="flex gap-x-2 gap-y-4">
- <Form.Field
- control={form.control}
- name="is_tax_inclusive"
- render={({ field: { onChange, value, ...field } }) => {
- return (
- <Form.Item
- className="basis-full"
- data-testid="promotion-create-form-tax-inclusive-item"
- >
- <div className="flex items-center justify-between">
- <div className="block">
- <Form.Label data-testid="promotion-create-form-tax-inclusive-label">
- {t("promotions.form.taxInclusive.title")}
- </Form.Label>
- <Form.Hint
- className="!mt-1"
- data-testid="promotion-create-form-tax-inclusive-hint"
- >
- {t("promotions.form.taxInclusive.description")}
- </Form.Hint>
- </div>
- <Form.Control
- className="mr-2 self-center"
- data-testid="promotion-create-form-tax-inclusive-control"
- >
- <Switch
- dir="ltr"
- className="mt-[2px] rtl:rotate-180"
- checked={!!value}
- onCheckedChange={onChange}
- {...field}
- data-testid="promotion-create-form-tax-inclusive-switch"
- />
- </Form.Control>
- </div>
- <Form.ErrorMessage data-testid="promotion-create-form-tax-inclusive-error" />
- </Form.Item>
- )
- }}
- />
- </div>
+ <SwitchBox
+ control={form.control}
+ name="is_tax_inclusive"
+ label={t("promotions.form.taxInclusive.title")}
+ description={t("promotions.form.taxInclusive.description")}
+ data-testid="promotion-create-form-tax-inclusive-switch"
+ />
</>
)}
+ <Divider />
+
+ <div className="flex flex-col gap-y-4">
+ <div className="flex flex-col">
+ <Heading
+ level="h2"
+ className="mb-2"
+ data-testid="promotion-create-form-cost-bearer-label"
+ >
+ {t("promotions.form.costBearer.label")}
+ </Heading>
+ <Text
+ className="txt-small text-ui-fg-subtle"
+ data-testid="promotion-create-form-cost-bearer-description"
+ >
+ {t("promotions.form.costBearer.description")}
+ </Text>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name="cost_bearer"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-create-form-cost-bearer-item">
+ <Form.Control data-testid="promotion-create-form-cost-bearer-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-cost-bearer-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="store"
+ label={t("promotions.form.costBearer.store.title")}
+ description={t(
+ "promotions.form.costBearer.store.description",
+ )}
+ className={clx("basis-1/3")}
+ data-testid="promotion-create-form-cost-bearer-option-store"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="marketplace"
+ label={t(
+ "promotions.form.costBearer.marketplace.title",
+ )}
+ description={t(
+ "promotions.form.costBearer.marketplace.description",
+ )}
+ className={clx("basis-1/3")}
+ data-testid="promotion-create-form-cost-bearer-option-marketplace"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="shared"
+ label={t("promotions.form.costBearer.shared.title")}
+ description={t(
+ "promotions.form.costBearer.shared.description",
+ )}
+ className={clx("basis-1/3")}
+ data-testid="promotion-create-form-cost-bearer-option-shared"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-cost-bearer-error" />
+ </Form.Item>
+ );
+ }}
+ />
+
+ {isSharedCost && (
+ <Form.Field
+ control={form.control}
+ name="shared_marketplace_percentage"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-shared-percentage-item"
+ >
+ <Form.Label data-testid="promotion-create-form-shared-percentage-label">
+ {t("promotions.form.costBearer.sharedPercentage.title")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-shared-percentage-control">
+ <DeprecatedPercentageInput
+ key="shared-percentage"
+ className="text-right"
+ min={0}
+ max={100}
+ {...field}
+ value={value ?? ""}
+ onChange={(e) => {
+ onChange(
+ e.target.value === ""
+ ? null
+ : parseFloat(e.target.value),
+ );
+ }}
+ data-testid="promotion-create-form-shared-percentage-input"
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage data-testid="promotion-create-form-shared-percentage-error" />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ <InlineTip
+ label={t("general.tip")}
+ data-testid="promotion-create-form-cost-bearer-tip"
+ >
+ {t("promotions.form.costBearer.tip")}
+ </InlineTip>
+ </div>
+
{!currentTemplate?.hiddenFields?.includes("type") && (
<Form.Field
control={form.control}
@@ -312,7 +419,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
value="standard"
label={t("promotions.form.type.standard.title")}
description={t(
- "promotions.form.type.standard.description"
+ "promotions.form.type.standard.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-type-option-standard"
@@ -322,7 +429,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
value="buyget"
label={t("promotions.form.type.buyget.title")}
description={t(
- "promotions.form.type.buyget.description"
+ "promotions.form.type.buyget.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-type-option-buyget"
@@ -331,7 +438,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Form.Control>
<Form.ErrorMessage data-testid="promotion-create-form-type-error" />
</Form.Item>
- )
+ );
}}
/>
)}
@@ -340,7 +447,9 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
<RulesFormField form={form} ruleType="rules" />
- {!currentTemplate?.hiddenFields?.includes("application_method.type") && (
+ {!currentTemplate?.hiddenFields?.includes(
+ "application_method.type",
+ ) && (
<>
<Divider />
<Form.Field
@@ -362,11 +471,9 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
>
<RadioGroup.ChoiceBox
value="fixed"
- label={t(
- "promotions.form.value_type.fixed.title"
- )}
+ label={t("promotions.form.value_type.fixed.title")}
description={t(
- "promotions.form.value_type.fixed.description"
+ "promotions.form.value_type.fixed.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-value-type-option-fixed"
@@ -375,10 +482,10 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
<RadioGroup.ChoiceBox
value="percentage"
label={t(
- "promotions.form.value_type.percentage.title"
+ "promotions.form.value_type.percentage.title",
)}
description={t(
- "promotions.form.value_type.percentage.description"
+ "promotions.form.value_type.percentage.description",
)}
className={clx("basis-1/2")}
data-testid="promotion-create-form-value-type-option-percentage"
@@ -387,32 +494,92 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Form.Control>
<Form.ErrorMessage data-testid="promotion-create-form-value-type-error" />
</Form.Item>
- )
+ );
}}
/>
</>
)}
{!currentTemplate?.hiddenFields?.includes(
- "application_method.value"
+ "application_method.allocation",
) && (
- <>
- <Divider />
+ <Form.Field
+ control={form.control}
+ name="application_method.allocation"
+ render={({ field }) => {
+ const handleAllocationChange = (value: AllocationMode) => {
+ setAllocationMode(value);
+ setValue(
+ "application_method.allocation",
+ value as ApplicationMethodAllocationValues,
+ );
+ field.onChange(value as ApplicationMethodAllocationValues);
+
+ if (value === "once") {
+ setValue("application_method.max_quantity", 1);
+ }
+ };
+
+ return (
+ <Form.Item data-testid="promotion-create-form-allocation-item">
+ <Form.Label data-testid="promotion-create-form-allocation-label">
+ {t("promotions.fields.allocation")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-allocation-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ value={allocationMode}
+ onValueChange={(val) =>
+ handleAllocationChange(val as AllocationMode)
+ }
+ data-testid="promotion-create-form-allocation-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="each"
+ label={t("promotions.form.allocation.each.title")}
+ description={t(
+ "promotions.form.allocation.each.description",
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-allocation-option-each"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="once"
+ label={t("promotions.form.allocation.once.title")}
+ description={t(
+ "promotions.form.allocation.once.description",
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-allocation-option-once"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-allocation-error" />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ {!currentTemplate?.hiddenFields?.includes(
+ "application_method.value",
+ ) && (
<Form.Field
control={form.control}
name="application_method.value"
render={({ field: { onChange, value, ...field } }) => {
const currencyCode =
- form.getValues().application_method.currency_code
+ form.getValues().application_method.currency_code;
const currencyInfo =
- currencies[currencyCode?.toUpperCase() || "USD"]
+ currencies[currencyCode?.toUpperCase() || "USD"];
return (
- <Form.Item
- className="basis-1/2"
- data-testid="promotion-create-form-value-item"
- >
+ <Form.Item data-testid="promotion-create-form-value-item">
<Form.Label
tooltip={
currencyCode || !isFixedValueType
@@ -436,9 +603,7 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
decimalScale={currencyInfo?.decimal_digits ?? 2}
decimalsLimit={currencyInfo?.decimal_digits ?? 2}
symbol={
- currencyCode
- ? getCurrencySymbol(currencyCode)
- : "$"
+ currencyCode ? getCurrencySymbol(currencyCode) : "$"
}
value={value}
disabled={!currencyCode}
@@ -456,8 +621,8 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
onChange(
e.target.value === ""
? null
- : parseFloat(e.target.value)
- )
+ : parseFloat(e.target.value),
+ );
}}
data-testid="promotion-create-form-value-percentage-input"
/>
@@ -481,28 +646,18 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Text>
<Form.ErrorMessage data-testid="promotion-create-form-value-error" />
</Form.Item>
- )
+ );
}}
/>
- </>
- )}
+ )}
- {(isTypeStandard || isTypeBuyGet) && allocationMode !== "across" && (
- <>
- {isTypeBuyGet && (
- <>
- <Divider />
- </>
- )}
+ {(isTypeStandard || isTypeBuyGet) && allocationMode !== "across" && (
<Form.Field
control={form.control}
name="application_method.max_quantity"
render={() => {
return (
- <Form.Item
- className="basis-1/2"
- data-testid="promotion-create-form-max-quantity-item"
- >
+ <Form.Item data-testid="promotion-create-form-max-quantity-item">
<Form.Label data-testid="promotion-create-form-max-quantity-label">
{t("promotions.form.max_quantity.title")}
</Form.Label>
@@ -533,72 +688,66 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
</Text>
<Form.ErrorMessage data-testid="promotion-create-form-max-quantity-error" />
</Form.Item>
- )
+ );
}}
/>
- </>
- )}
-
- {!currentTemplate?.hiddenFields?.includes(
- "application_method.allocation"
- ) && (
- <Form.Field
- control={form.control}
- name="application_method.allocation"
- render={({ field }) => {
- const handleAllocationChange = (value: AllocationMode) => {
- setAllocationMode(value)
- setValue(
- "application_method.allocation",
- value as ApplicationMethodAllocationValues
- )
- field.onChange(value as ApplicationMethodAllocationValues)
-
- if (value === "once") {
- setValue("application_method.max_quantity", 1)
- }
- }
+ )}
+ </div>
- return (
- <Form.Item data-testid="promotion-create-form-allocation-item">
- <Form.Label data-testid="promotion-create-form-allocation-label">
- {t("promotions.fields.allocation")}
- </Form.Label>
+ {isTypeBuyGet && (
+ <>
+ <Divider />
+ <div className="flex flex-col gap-y-4">
+ <div className="flex flex-col">
+ <Heading
+ level="h2"
+ className="mb-2"
+ data-testid="promotion-create-form-store-offers-heading"
+ >
+ {t("promotions.form.storeOffers.title")}
+ </Heading>
+ <Text
+ className="txt-small text-ui-fg-subtle"
+ data-testid="promotion-create-form-store-offers-description"
+ >
+ {t("promotions.form.storeOffers.description")}
+ </Text>
+ </div>
- <Form.Control data-testid="promotion-create-form-allocation-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- value={allocationMode}
- onValueChange={(val) =>
- handleAllocationChange(val as AllocationMode)
- }
- data-testid="promotion-create-form-allocation-radio-group"
+ <Form.Field
+ control={form.control}
+ name="seller_id"
+ render={({ field }) => {
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-store-item"
>
- <RadioGroup.ChoiceBox
- value="each"
- label={t("promotions.form.allocation.each.title")}
- description={t(
- "promotions.form.allocation.each.description"
- )}
- className={clx("basis-1/2")}
- data-testid="promotion-create-form-allocation-option-each"
- />
+ <Form.Label data-testid="promotion-create-form-store-label">
+ {t("promotions.form.storeOffers.label")}
+ </Form.Label>
- <RadioGroup.ChoiceBox
- value="once"
- label={t("promotions.form.allocation.once.title")}
- description={t("promotions.form.allocation.once.description")}
- className={clx("basis-1/2")}
- data-testid="promotion-create-form-allocation-option-once"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-allocation-error" />
- </Form.Item>
- )
- }}
- />
+ <Form.Control data-testid="promotion-create-form-store-control">
+ <Combobox
+ {...field}
+ value={field.value ?? ""}
+ options={stores.options}
+ searchValue={stores.searchValue}
+ onSearchValueChange={stores.onSearchValueChange}
+ fetchNextPage={stores.fetchNextPage}
+ placeholder={t(
+ "promotions.form.storeOffers.placeholder",
+ )}
+ data-testid="promotion-create-form-store-select"
+ />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-store-error" />
+ </Form.Item>
+ );
+ }}
+ />
+ </div>
+ </>
)}
{!isTypeStandard && (
@@ -622,10 +771,55 @@ const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
/>
</>
)}
+
+ <Divider />
+
+ <Form.Field
+ control={form.control}
+ name="limit"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-limit-item"
+ >
+ <Form.Label
+ optional
+ data-testid="promotion-create-form-limit-label"
+ >
+ {t("promotions.form.limit.title")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-create-form-limit-control">
+ <Input
+ {...field}
+ type="number"
+ min={1}
+ value={value ?? ""}
+ onChange={(e) => {
+ const val = e.target.value;
+ onChange(val === "" ? null : parseInt(val, 10));
+ }}
+ placeholder="100"
+ data-testid="promotion-create-form-limit-input"
+ />
+ </Form.Control>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-create-form-limit-description"
+ >
+ {t("promotions.form.limit.description")}
+ </Text>
+ <Form.ErrorMessage data-testid="promotion-create-form-limit-error" />
+ </Form.Item>
+ );
+ }}
+ />
</div>
</div>
- )
-}
+ );
+};
Root._tabMeta = defineTabMeta<CreatePromotionSchemaType>({
id: "promotion",
@@ -637,8 +831,11 @@ Root._tabMeta = defineTabMeta<CreatePromotionSchemaType>({
"status",
"rules",
"is_tax_inclusive",
+ "cost_bearer",
+ "shared_marketplace_percentage",
+ "limit",
"application_method",
],
-})
+});
-export const PromotionDetailsTab = Root
+export const PromotionDetailsTab = Root;
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/templates.ts b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/templates.ts
index 91b651a61..624cf69cd 100644
--- a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/templates.ts
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/templates.ts
@@ -3,12 +3,16 @@ const commonHiddenFields = [
"application_method.type",
]
-const amountOfOrderHiddenFields = [...commonHiddenFields]
+const amountOfOrderHiddenFields = [
+ ...commonHiddenFields,
+ "application_method.allocation",
+]
const amountOfProductHiddenFields = [...commonHiddenFields]
const percentageOfOrderHiddenFields = [
...commonHiddenFields,
"is_tax_inclusive",
+ "application_method.allocation",
]
const percentageOfProductHiddenFields = [
...commonHiddenFields,
@@ -21,13 +25,6 @@ const buyGetHiddenFields = [
"is_tax_inclusive",
]
-const freeShippingHiddenFields = [
- ...commonHiddenFields,
- "application_method.value",
- "application_method.allocation",
- "is_tax_inclusive",
-]
-
export const templates = [
{
id: "amount_off_products",
@@ -110,21 +107,4 @@ export const templates = [
},
},
},
- {
- id: "shipping_discount",
- type: "standard",
- titleKey: "promotions.templates.freeShipping.title",
- descriptionKey: "promotions.templates.freeShipping.description",
- hiddenFields: freeShippingHiddenFields,
- defaults: {
- is_automatic: "false",
- type: "standard",
- application_method: {
- allocation: "across",
- target_type: "shipping_methods",
- type: "percentage",
- value: 100,
- },
- },
- },
]
diff --git a/packages/admin/src/pages/promotions/promotion-detail/breadcrumb.tsx b/packages/admin/src/pages/promotions/promotion-detail/breadcrumb.tsx
index 35324f771..1d88a14b6 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/breadcrumb.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/breadcrumb.tsx
@@ -2,6 +2,7 @@ import { HttpTypes } from "@medusajs/types"
import { useLinkQuery } from "@mercurjs/dashboard-shared"
import { UIMatch } from "react-router-dom"
import { usePromotion } from "../../../hooks/api"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "./loader"
type PromotionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminPromotionResponse>
@@ -10,7 +11,7 @@ export const PromotionDetailBreadcrumb = (
) => {
const { id } = props.params || {}
- const linkQuery = useLinkQuery("promotion")
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
const { promotion } = usePromotion(id!, linkQuery, {
initialData: props.data,
enabled: Boolean(id),
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
index a9d4ddba6..c978ee4df 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
@@ -1,6 +1,6 @@
import { ArrowUpRightOnBox, PencilSquare } from "@medusajs/icons"
import { HttpTypes } from "@medusajs/types"
-import { Container, Heading, Text } from "@medusajs/ui"
+import { Container, Heading, InlineTip, Text } from "@medusajs/ui"
import { useTranslation } from "react-i18next"
import { useParams } from "react-router-dom"
@@ -10,12 +10,17 @@ import { ActionMenu } from "../../../../../components/common/action-menu"
import { DateRangeDisplay } from "../../../../../components/common/date-range-display"
import { NoRecords } from "../../../../../components/common/empty-table-content"
import { usePromotion } from "../../../../../hooks/api/promotions"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../../loader"
const CampaignDetailSection = ({
campaign,
+ warning,
}: {
campaign: HttpTypes.AdminCampaign
+ warning?: string
}) => {
+ const { t } = useTranslation()
+
return (
<div className="flex flex-col gap-y-3">
<div className="text-ui-fg-muted flex items-center gap-x-1.5">
@@ -34,23 +39,38 @@ const CampaignDetailSection = ({
endsAt={campaign.ends_at}
showTime
/>
+ {warning && (
+ <InlineTip variant="warning" label={t("general.warning")}>
+ {warning}
+ </InlineTip>
+ )}
</div>
)
}
export const CampaignSection = ({
campaign: campaignProp,
+ promotion: promotionProp,
}: {
campaign?: HttpTypes.AdminCampaign | null
+ promotion?: HttpTypes.AdminPromotion
}) => {
const { t } = useTranslation()
const { id } = useParams()
- const linkQuery = useLinkQuery("promotion")
- const { promotion } = usePromotion(id!, linkQuery, {
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
+ const { promotion: fetchedPromotion } = usePromotion(id!, linkQuery, {
enabled: campaignProp === undefined,
})
+ const promotion = promotionProp ?? fetchedPromotion
const campaign = campaignProp !== undefined ? campaignProp : (promotion?.campaign ?? null)
+ const warning =
+ campaign && promotion?.status !== "active"
+ ? t("promotions.campaignSection.warnings.promotionMustBeActive")
+ : campaign?.ends_at
+ ? t("promotions.campaignSection.warnings.promotionExpires")
+ : undefined
+
const actions = [
{
label: t("actions.edit"),
@@ -84,7 +104,7 @@ export const CampaignSection = ({
{campaign ? (
<div data-testid="promotion-campaign-section-detail">
- <CampaignDetailSection campaign={campaign} />
+ <CampaignDetailSection campaign={campaign} warning={warning} />
</div>
) : (
<div data-testid="promotion-campaign-section-no-records">
@@ -96,7 +116,6 @@ export const CampaignSection = ({
to: `/promotions/${id}/add-to-campaign`,
label: t("promotions.campaignSection.addToCampaign"),
}}
- buttonVariant="transparentIconLeft"
dataTestId="promotion-campaign-section-add-to-campaign-button"
/>
</div>
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
index 94fc1eda4..e5a556be6 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
@@ -13,6 +13,7 @@ import { ActionMenu } from "../../../../../components/common/action-menu";
import { BadgeListSummary } from "../../../../../components/common/badge-list-summary";
import { NoRecords } from "../../../../../components/common/empty-table-content";
import { usePromotion, usePromotionRules } from "../../../../../hooks/api/promotions";
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../../loader";
type RuleProps = {
rule: HttpTypes.AdminPromotionRule;
@@ -61,7 +62,7 @@ export const PromotionConditionsSection = ({
}: PromotionConditionsSectionProps) => {
const { t } = useTranslation();
const { id } = useParams();
- const linkQuery = useLinkQuery("promotion");
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS);
const { promotion } = usePromotion(id!, linkQuery, {
enabled: rulesProp === undefined,
});
@@ -121,13 +122,13 @@ export const PromotionConditionsSection = ({
>
<NoRecords
className="h-[180px]"
- title={t("general.noRecordsTitle")}
+ icon={null}
+ title={t("promotions.conditions.list.noRecordsTitle")}
message={t("promotions.conditions.list.noRecordsMessage")}
action={{
to: `${ruleType}/edit`,
label: t("promotions.conditions.add"),
}}
- buttonVariant="transparentIconLeft"
dataTestId={`promotion-conditions-section-add-condition-button-${ruleType}`}
/>
</div>
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
index 1b0b7edf5..f89494625 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
@@ -1,5 +1,6 @@
import { PencilSquare, Trash } from "@medusajs/icons"
import { HttpTypes } from "@medusajs/types"
+import { PromotionCostDTO } from "@mercurjs/types"
import {
Badge,
Container,
@@ -24,7 +25,8 @@ import { ActionMenu } from "../../../../../components/common/action-menu"
import { useDeletePromotion, usePromotion } from "../../../../../hooks/api/promotions"
import { formatCurrency } from "../../../../../lib/format-currency"
import { formatPercentage } from "../../../../../lib/percentage-helpers"
-import { getPromotionStatus } from "../../../../../lib/promotions"
+import { getPromotionStatus, getPromotionType } from "../../../../../lib/promotions"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../../loader"
type PromotionGeneralSectionProps = {
promotion?: HttpTypes.AdminPromotion
@@ -36,9 +38,12 @@ const GENERAL_FIELD_IDS = [
"is_automatic",
"code_badge",
"type",
+ "coverage",
+ "owner",
"value",
"allocation",
"is_tax_inclusive",
+ "usage_limit",
]
function getDisplayValue(promotion: HttpTypes.AdminPromotion) {
@@ -70,7 +75,7 @@ export const PromotionGeneralSection = ({
const prompt = usePrompt()
const navigate = useNavigate()
const { id } = useParams()
- const linkQuery = useLinkQuery("promotion")
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
const { promotion: fetched } = usePromotion(id!, linkQuery, {
enabled: !promotionProp,
})
@@ -105,6 +110,12 @@ export const PromotionGeneralSection = ({
})
}
+ const costBearer = (
+ promotion as HttpTypes.AdminPromotion & {
+ promotion_cost?: PromotionCostDTO | null
+ }
+ ).promotion_cost?.cost_bearer
+
const [color, text] = getPromotionStatus(promotion)
const displayValue = getDisplayValue(promotion)
@@ -117,7 +128,7 @@ export const PromotionGeneralSection = ({
</DisplayField>
</div>
- <div className="flex items-center gap-x-2">
+ <div className="flex items-center gap-x-4">
<DisplayField model="promotion" zone="general" id="status" data={promotion}>
<StatusBadge color={color} data-testid="promotion-general-section-status">{text}</StatusBadge>
</DisplayField>
@@ -147,6 +158,18 @@ export const PromotionGeneralSection = ({
</div>
</div>
+ <DisplayField model="promotion" zone="general" id="type" data={promotion}>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-type">
+ <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-type-label">
+ {t("promotions.fields.type")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty" data-testid="promotion-general-section-type-value">
+ {getPromotionType(promotion)}
+ </Text>
+ </div>
+ </DisplayField>
+
<DisplayField model="promotion" zone="general" id="is_automatic" data={promotion}>
<div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-method">
<Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-method-label">
@@ -185,17 +208,37 @@ export const PromotionGeneralSection = ({
</div>
</DisplayField>
- <DisplayField model="promotion" zone="general" id="type" data={promotion}>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-type">
- <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-type-label">
- {t("promotions.fields.type")}
- </Text>
+ {promotion.application_method?.type === "fixed" && (
+ <DisplayField model="promotion" zone="general" id="is_tax_inclusive" data={promotion}>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-tax-inclusive">
+ <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-tax-inclusive-label">
+ {t("promotions.fields.taxInclusive")}
+ </Text>
- <Text size="small" leading="compact" className="text-pretty capitalize" data-testid="promotion-general-section-type-value">
- {promotion.type}
- </Text>
- </div>
- </DisplayField>
+ <div className="flex items-center gap-x-2" data-testid="promotion-general-section-tax-inclusive-value">
+ <Text className="inline" size="small" leading="compact">
+ {promotion.is_tax_inclusive
+ ? t("general.yes")
+ : t("general.no")}
+ </Text>
+ </div>
+ </div>
+ </DisplayField>
+ )}
+
+ {costBearer && (
+ <DisplayField model="promotion" zone="general" id="coverage" data={promotion}>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-coverage">
+ <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-coverage-label">
+ {t("promotions.fields.coverage")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty" data-testid="promotion-general-section-coverage-value">
+ {t(`promotions.form.costBearer.${costBearer}.title`)}
+ </Text>
+ </div>
+ </DisplayField>
+ )}
<DisplayField model="promotion" zone="general" id="value" data={promotion}>
<div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-value">
@@ -228,23 +271,30 @@ export const PromotionGeneralSection = ({
</div>
</DisplayField>
- {promotion.application_method?.type === "fixed" && (
- <DisplayField model="promotion" zone="general" id="is_tax_inclusive" data={promotion}>
- <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-tax-inclusive">
- <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-tax-inclusive-label">
- {t("promotions.fields.taxInclusive")}
- </Text>
+ <DisplayField model="promotion" zone="general" id="usage_limit" data={promotion}>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-usage-limit">
+ <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-usage-limit-label">
+ {t("promotions.fields.usageLimit")}
+ </Text>
- <div className="flex items-center gap-x-2" data-testid="promotion-general-section-tax-inclusive-value">
- <Text className="inline" size="small" leading="compact">
- {promotion.is_tax_inclusive
- ? t("fields.true")
- : t("fields.false")}
- </Text>
- </div>
- </div>
- </DisplayField>
- )}
+ <Text size="small" leading="compact" className="text-pretty" data-testid="promotion-general-section-usage-limit-value">
+ {promotion.limit ?? t("promotions.fields.unlimited")}
+ </Text>
+ </div>
+ </DisplayField>
+
+ <DisplayField model="promotion" zone="general" id="owner" data={promotion}>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4" data-testid="promotion-general-section-owner">
+ <Text size="small" weight="plus" leading="compact" data-testid="promotion-general-section-owner-label">
+ {t("promotions.fields.owner")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty" data-testid="promotion-general-section-owner-value">
+ {(promotion as HttpTypes.AdminPromotion & { seller?: { name?: string } | null }).seller?.name
+ ?? t("promotions.fields.platformOwner")}
+ </Text>
+ </div>
+ </DisplayField>
<DisplayExtensionZone
model="promotion"
diff --git a/packages/admin/src/pages/promotions/promotion-detail/loader.ts b/packages/admin/src/pages/promotions/promotion-detail/loader.ts
index 9d4b08ac6..6df15acf2 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/loader.ts
+++ b/packages/admin/src/pages/promotions/promotion-detail/loader.ts
@@ -4,8 +4,11 @@ import { promotionsQueryKeys } from "../../../hooks/api/promotions"
import { sdk } from "../../../lib/client"
import { queryClient } from "../../../lib/query-client"
+export const PROMOTION_DETAIL_BASE_FIELDS =
+ "+seller.id,+seller.name,+promotion_cost.cost_bearer,+promotion_cost.shared_marketplace_percentage"
+
const promotionDetailQuery = (id: string) => {
- const query = getLinkQuery("promotion")
+ const query = getLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
return {
queryKey: promotionsQueryKeys.detail(id, query),
queryFn: async () => sdk.admin.promotions.$id.query({ $id: id, ...query }),
diff --git a/packages/admin/src/pages/promotions/promotion-detail/promotion-detail.tsx b/packages/admin/src/pages/promotions/promotion-detail/promotion-detail.tsx
index 4c89eb77d..68fdd30fe 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/promotion-detail.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/promotion-detail.tsx
@@ -9,7 +9,7 @@ import { usePromotion, usePromotionRules } from "../../../hooks/api/promotions";
import { CampaignSection } from "./components/campaign-section";
import { PromotionConditionsSection } from "./components/promotion-conditions-section";
import { PromotionGeneralSection } from "./components/promotion-general-section";
-import { promotionLoader } from "./loader";
+import { PROMOTION_DETAIL_BASE_FIELDS, promotionLoader } from "./loader";
const Root = ({ children }: { children?: ReactNode }) => {
const initialData = useLoaderData() as Awaited<
@@ -17,7 +17,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
>;
const { id } = useParams();
- const linkQuery = useLinkQuery("promotion");
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS);
const { promotion, isLoading } = usePromotion(id!, linkQuery, {
initialData,
});
@@ -68,7 +68,7 @@ const Root = ({ children }: { children?: ReactNode }) => {
</TwoColumnPage.Main>
<TwoColumnPage.Sidebar>
<WidgetZone id="promotions.detail.side" data={promotion}>
- <CampaignSection campaign={promotion.campaign!} />
+ <CampaignSection campaign={promotion.campaign!} promotion={promotion} />
</WidgetZone>
</TwoColumnPage.Sidebar>
</TwoColumnPage>
diff --git a/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx b/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx
index 27ca2a925..8d575cc04 100644
--- a/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx
+++ b/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx
@@ -2,7 +2,16 @@ import type {
AdminPromotion,
ApplicationMethodAllocationValues,
} from "@medusajs/types"
-import { Button, CurrencyInput, Input, RadioGroup, Text } from "@medusajs/ui"
+import {
+ Button,
+ CurrencyInput,
+ Divider,
+ InlineTip,
+ Input,
+ RadioGroup,
+ Text,
+ toast,
+} from "@medusajs/ui"
import { useWatch } from "react-hook-form"
import { Trans, useTranslation } from "react-i18next"
import { useEffect } from "react"
@@ -17,7 +26,10 @@ import { Form } from "../../../../../components/common/form"
import { DeprecatedPercentageInput } from "../../../../../components/inputs/percentage-input"
import { RouteDrawer, useRouteModal } from "../../../../../components/modals"
import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
-import { useUpdatePromotion } from "../../../../../hooks/api/promotions"
+import {
+ useUpdatePromotion,
+ useUpsertPromotionCost,
+} from "../../../../../hooks/api/promotions"
import {
currencies,
getCurrencySymbol,
@@ -41,20 +53,10 @@ const EditPromotionSchema = zod.object({
allocation: zod.enum(["each", "across", "once"]),
max_quantity: zod.number().optional().nullable(),
target_type: zod.enum(["order", "shipping_methods", "items"]),
+ cost_bearer: zod.enum(["store", "marketplace", "shared"]),
+ shared_marketplace_percentage: zod.number().min(0).max(100).nullable(),
+ limit: zod.number().int().min(1).nullable().optional(),
})
- .refine(
- (data) => {
- if (data.allocation === "across") {
- return true
- }
-
- return typeof data.max_quantity === "number"
- },
- {
- path: ["max_quantity"],
- message: `required field`,
- }
- )
export const EditPromotionDetailsForm = ({
promotion,
@@ -71,6 +73,23 @@ export const EditPromotionDetailsForm = ({
? "across"
: "each"
+ const promotionWithLinks = promotion as AdminPromotion & {
+ seller?: { id?: string } | null
+ promotion_cost?: {
+ cost_bearer?: "store" | "marketplace" | "shared" | null
+ shared_marketplace_percentage?: number | null
+ } | null
+ }
+
+ // Coverage (who bears the discount cost) is only editable for
+ // marketplace-owned promotions; when a store owns it, the field is hidden.
+ const isMercurOwned = !promotionWithLinks.seller
+
+ const costDefault =
+ promotionWithLinks.promotion_cost?.cost_bearer ?? "store"
+ const sharedPercentageDefault =
+ promotionWithLinks.promotion_cost?.shared_marketplace_percentage ?? null
+
const form = useExtendableForm({
schema: EditPromotionSchema,
model: "promotion",
@@ -86,6 +105,9 @@ export const EditPromotionDetailsForm = ({
max_quantity: promotion.application_method?.max_quantity ?? null,
value_type: promotion.application_method!.type,
target_type: promotion.application_method!.target_type,
+ cost_bearer: costDefault,
+ shared_marketplace_percentage: sharedPercentageDefault,
+ limit: promotion.limit ?? null,
},
})
@@ -99,9 +121,18 @@ export const EditPromotionDetailsForm = ({
name: "allocation",
})
+ const watchCostBearer = useWatch({
+ control: form.control,
+ name: "cost_bearer",
+ })
+
const isFixedValueType = watchValueType === "fixed"
+ const isSharedCost = watchCostBearer === "shared"
+ const isOrderTargetType =
+ promotion.application_method?.target_type === "order"
const { mutateAsync, isPending } = useUpdatePromotion(promotion.id)
+ const { mutateAsync: upsertPromotionCost } = useUpsertPromotionCost()
const handleSubmit = form.handleSubmit(async (data) => {
const value =
@@ -113,12 +144,37 @@ export const EditPromotionDetailsForm = ({
return
}
+ if (
+ !isOrderTargetType &&
+ data.allocation !== "across" &&
+ typeof data.max_quantity !== "number"
+ ) {
+ form.setError("max_quantity", {
+ message: t("validation.requiredField"),
+ })
+
+ return
+ }
+
+ if (
+ isMercurOwned &&
+ data.cost_bearer === "shared" &&
+ typeof data.shared_marketplace_percentage !== "number"
+ ) {
+ form.setError("shared_marketplace_percentage", {
+ message: t("validation.requiredField"),
+ })
+
+ return
+ }
+
await mutateAsync(
{
is_automatic: data.is_automatic === "true",
code: data.code,
status: data.status,
is_tax_inclusive: data.is_tax_inclusive,
+ limit: data.limit ?? null,
application_method: {
value,
type: data.value_type,
@@ -127,24 +183,28 @@ return
},
},
{
- onSuccess: () => {
+ onSuccess: async () => {
+ if (isMercurOwned) {
+ try {
+ await upsertPromotionCost({
+ id: promotion.id,
+ cost_bearer: data.cost_bearer,
+ shared_marketplace_percentage:
+ data.cost_bearer === "shared"
+ ? data.shared_marketplace_percentage
+ : null,
+ })
+ } catch (e) {
+ toast.error((e as Error).message)
+ }
+ }
+
handleSuccess()
},
}
)
})
- const allocationWatchValue = useWatch({
- control: form.control,
- name: "value_type",
- })
-
- useEffect(() => {
- if (!(allocationWatchValue === "fixed" && promotion.type === "standard")) {
- form.setValue("is_tax_inclusive", false)
- }
- }, [allocationWatchValue, form, promotion])
-
useEffect(() => {
if (watchAllocation === "once" && !form.getValues("max_quantity")) {
form.setValue("max_quantity", 1)
@@ -162,49 +222,39 @@ return (
<div className="flex flex-col gap-y-8">
<Form.Field
control={form.control}
- name="status"
+ name="is_automatic"
render={({ field }) => {
return (
- <Form.Item data-testid="promotion-edit-details-form-status-item">
- <Form.Label data-testid="promotion-edit-details-form-status-label">{t("promotions.form.status.label")}</Form.Label>
- <Form.Control data-testid="promotion-edit-details-form-status-control">
+ <Form.Item data-testid="promotion-edit-details-form-method-item">
+ <Form.Label data-testid="promotion-edit-details-form-method-label">{t("promotions.form.method.label")}</Form.Label>
+ <Form.Control data-testid="promotion-edit-details-form-method-control">
<RadioGroup
dir={direction}
className="flex-col gap-y-3"
{...field}
value={field.value}
onValueChange={field.onChange}
- data-testid="promotion-edit-details-form-status-radio-group"
+ data-testid="promotion-edit-details-form-method-radio-group"
>
<RadioGroup.ChoiceBox
- value="draft"
- label={t("promotions.form.status.draft.title")}
- description={t(
- "promotions.form.status.draft.description"
- )}
- data-testid="promotion-edit-details-form-status-option-draft"
- />
-
- <RadioGroup.ChoiceBox
- value="active"
- label={t("promotions.form.status.active.title")}
+ value="false"
+ label={t("promotions.form.method.code.title")}
description={t(
- "promotions.form.status.active.description"
+ "promotions.form.method.code.description"
)}
- data-testid="promotion-edit-details-form-status-option-active"
+ data-testid="promotion-edit-details-form-method-option-code"
/>
-
<RadioGroup.ChoiceBox
- value="inactive"
- label={t("promotions.form.status.inactive.title")}
+ value="true"
+ label={t("promotions.form.method.automatic.title")}
description={t(
- "promotions.form.status.inactive.description"
+ "promotions.form.method.automatic.description"
)}
- data-testid="promotion-edit-details-form-status-option-inactive"
+ data-testid="promotion-edit-details-form-method-option-automatic"
/>
</RadioGroup>
</Form.Control>
- <Form.ErrorMessage data-testid="promotion-edit-details-form-status-error" />
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-method-error" />
</Form.Item>
)
}}
@@ -212,54 +262,54 @@ return (
<Form.Field
control={form.control}
- name="is_automatic"
+ name="status"
render={({ field }) => {
return (
- <Form.Item data-testid="promotion-edit-details-form-method-item">
- <Form.Label data-testid="promotion-edit-details-form-method-label">{t("promotions.form.method.label")}</Form.Label>
- <Form.Control data-testid="promotion-edit-details-form-method-control">
+ <Form.Item data-testid="promotion-edit-details-form-status-item">
+ <Form.Label data-testid="promotion-edit-details-form-status-label">{t("promotions.form.status.label")}</Form.Label>
+ <Form.Control data-testid="promotion-edit-details-form-status-control">
<RadioGroup
dir={direction}
className="flex-col gap-y-3"
{...field}
value={field.value}
onValueChange={field.onChange}
- data-testid="promotion-edit-details-form-method-radio-group"
+ data-testid="promotion-edit-details-form-status-radio-group"
>
<RadioGroup.ChoiceBox
- value="false"
- label={t("promotions.form.method.code.title")}
+ value="draft"
+ label={t("promotions.form.status.draft.title")}
description={t(
- "promotions.form.method.code.description"
+ "promotions.form.status.draft.description"
)}
- data-testid="promotion-edit-details-form-method-option-code"
+ data-testid="promotion-edit-details-form-status-option-draft"
/>
+
<RadioGroup.ChoiceBox
- value="true"
- label={t("promotions.form.method.automatic.title")}
+ value="active"
+ label={t("promotions.form.status.active.title")}
description={t(
- "promotions.form.method.automatic.description"
+ "promotions.form.status.active.description"
)}
- data-testid="promotion-edit-details-form-method-option-automatic"
+ data-testid="promotion-edit-details-form-status-option-active"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="inactive"
+ label={t("promotions.form.status.inactive.title")}
+ description={t(
+ "promotions.form.status.inactive.description"
+ )}
+ data-testid="promotion-edit-details-form-status-option-inactive"
/>
</RadioGroup>
</Form.Control>
- <Form.ErrorMessage data-testid="promotion-edit-details-form-method-error" />
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-status-error" />
</Form.Item>
)
}}
/>
- {allocationWatchValue === "fixed" &&
- promotion.type === "standard" && (
- <SwitchBox
- control={form.control}
- name="is_tax_inclusive"
- label={t("promotions.form.taxInclusive.title")}
- description={t("promotions.form.taxInclusive.description")}
- />
- )}
-
<div className="flex flex-col gap-y-4">
<Form.Field
control={form.control}
@@ -290,54 +340,165 @@ return (
</Text>
</div>
- {promotion.application_method?.target_type !==
- "shipping_methods" && (
+ <SwitchBox
+ control={form.control}
+ name="is_tax_inclusive"
+ label={t("promotions.form.taxInclusive.title")}
+ description={t("promotions.form.taxInclusive.description")}
+ />
+
+ <Divider />
+
+ {isMercurOwned && (
<>
+ <div className="flex flex-col gap-y-4">
<Form.Field
control={form.control}
- name="value_type"
+ name="cost_bearer"
render={({ field }) => {
return (
- <Form.Item data-testid="promotion-edit-details-form-value-type-item">
- <Form.Label data-testid="promotion-edit-details-form-value-type-label">
- {t("promotions.fields.value_type")}
+ <Form.Item data-testid="promotion-edit-details-form-cost-bearer-item">
+ <Form.Label data-testid="promotion-edit-details-form-cost-bearer-label">
+ {t("promotions.fields.coverage")}
</Form.Label>
- <Form.Control data-testid="promotion-edit-details-form-value-type-control">
+ <Form.Control data-testid="promotion-edit-details-form-cost-bearer-control">
<RadioGroup
dir={direction}
className="flex-col gap-y-3"
{...field}
+ value={field.value}
onValueChange={field.onChange}
- data-testid="promotion-edit-details-form-value-type-radio-group"
+ data-testid="promotion-edit-details-form-cost-bearer-radio-group"
>
<RadioGroup.ChoiceBox
- value="fixed"
+ value="store"
+ label={t("promotions.form.costBearer.store.title")}
+ description={t(
+ "promotions.form.costBearer.store.description"
+ )}
+ data-testid="promotion-edit-details-form-cost-bearer-option-store"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="marketplace"
label={t(
- "promotions.form.value_type.fixed.title"
+ "promotions.form.costBearer.marketplace.title"
)}
description={t(
- "promotions.form.value_type.fixed.description"
+ "promotions.form.costBearer.marketplace.description"
)}
- data-testid="promotion-edit-details-form-value-type-option-fixed"
+ data-testid="promotion-edit-details-form-cost-bearer-option-marketplace"
/>
<RadioGroup.ChoiceBox
- value="percentage"
+ value="shared"
label={t(
- "promotions.form.value_type.percentage.title"
+ "promotions.form.costBearer.shared.title"
)}
description={t(
- "promotions.form.value_type.percentage.description"
+ "promotions.form.costBearer.shared.description"
)}
- data-testid="promotion-edit-details-form-value-type-option-percentage"
+ data-testid="promotion-edit-details-form-cost-bearer-option-shared"
/>
</RadioGroup>
</Form.Control>
- <Form.ErrorMessage data-testid="promotion-edit-details-form-value-type-error" />
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-cost-bearer-error" />
</Form.Item>
)
}}
/>
+
+ {isSharedCost && (
+ <Form.Field
+ control={form.control}
+ name="shared_marketplace_percentage"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item data-testid="promotion-edit-details-form-shared-percentage-item">
+ <Form.Label data-testid="promotion-edit-details-form-shared-percentage-label">
+ {t("promotions.form.costBearer.sharedPercentage.title")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-edit-details-form-shared-percentage-control">
+ <DeprecatedPercentageInput
+ key="shared-percentage"
+ className="text-right"
+ min={0}
+ max={100}
+ {...field}
+ value={value ?? ""}
+ onChange={(e) => {
+ onChange(
+ e.target.value === ""
+ ? null
+ : parseFloat(e.target.value)
+ )
+ }}
+ data-testid="promotion-edit-details-form-shared-percentage-input"
+ />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-shared-percentage-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ <InlineTip
+ label={t("general.tip")}
+ data-testid="promotion-edit-details-form-cost-bearer-tip"
+ >
+ {t("promotions.form.costBearer.tip")}
+ </InlineTip>
+ </div>
+
+ <Divider />
+ </>
+ )}
+
+ {promotion.application_method?.target_type !==
+ "shipping_methods" && (
+ <>
+ {promotion.application_method?.target_type !== "order" && (
+ <Form.Field
+ control={form.control}
+ name="allocation"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-edit-details-form-allocation-item">
+ <Form.Label data-testid="promotion-edit-details-form-allocation-label">
+ {t("promotions.fields.allocation")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-edit-details-form-allocation-control">
+ <RadioGroup
+ dir={direction}
+ className="flex-col gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ data-testid="promotion-edit-details-form-allocation-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="each"
+ label={t("promotions.form.allocation.each.title")}
+ description={t(
+ "promotions.form.allocation.each.description"
+ )}
+ data-testid="promotion-edit-details-form-allocation-option-each"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="once"
+ label={t("promotions.form.allocation.once.title")}
+ description={t("promotions.form.allocation.once.description")}
+ data-testid="promotion-edit-details-form-allocation-option-once"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-allocation-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
<Form.Field
control={form.control}
name="value"
@@ -352,7 +513,7 @@ return (
<Form.Item data-testid="promotion-edit-details-form-value-item">
<Form.Label data-testid="promotion-edit-details-form-value-label">
{isFixedValueType
- ? t("fields.amount")
+ ? t("promotions.fields.promotion_value")
: t("fields.percentage")}
</Form.Label>
<Form.Control data-testid="promotion-edit-details-form-value-control">
@@ -388,52 +549,24 @@ return (
/>
)}
</Form.Control>
- <Form.ErrorMessage data-testid="promotion-edit-details-form-value-error" />
- </Form.Item>
- )
- }}
- />
- <Form.Field
- control={form.control}
- name="allocation"
- render={({ field }) => {
- return (
- <Form.Item data-testid="promotion-edit-details-form-allocation-item">
- <Form.Label data-testid="promotion-edit-details-form-allocation-label">
- {t("promotions.fields.allocation")}
- </Form.Label>
- <Form.Control data-testid="promotion-edit-details-form-allocation-control">
- <RadioGroup
- dir={direction}
- className="flex-col gap-y-3"
- {...field}
- onValueChange={field.onChange}
- data-testid="promotion-edit-details-form-allocation-radio-group"
+ {isFixedValueType && (
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-edit-details-form-value-description"
>
- <RadioGroup.ChoiceBox
- value="each"
- label={t("promotions.form.allocation.each.title")}
- description={t(
- "promotions.form.allocation.each.description"
- )}
- data-testid="promotion-edit-details-form-allocation-option-each"
- />
-
- <RadioGroup.ChoiceBox
- value="once"
- label={t("promotions.form.allocation.once.title")}
- description={t("promotions.form.allocation.once.description")}
- data-testid="promotion-edit-details-form-allocation-option-once"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-edit-details-form-allocation-error" />
+ {t("promotions.form.value.description")}
+ </Text>
+ )}
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-value-error" />
</Form.Item>
)
}}
/>
- {(watchAllocation === "each" || watchAllocation === "once") && (
+ {!isOrderTargetType &&
+ (watchAllocation === "each" || watchAllocation === "once") && (
<Form.Field
control={form.control}
name="max_quantity"
@@ -475,6 +608,48 @@ return (
</>
)}
+ <Divider />
+
+ <Form.Field
+ control={form.control}
+ name="limit"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item data-testid="promotion-edit-details-form-limit-item">
+ <Form.Label
+ optional
+ data-testid="promotion-edit-details-form-limit-label"
+ >
+ {t("promotions.form.limit.title")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-edit-details-form-limit-control">
+ <Input
+ {...field}
+ type="number"
+ min={1}
+ value={value ?? ""}
+ onChange={(e) => {
+ const val = e.target.value
+ onChange(val === "" ? null : parseInt(val, 10))
+ }}
+ placeholder="100"
+ data-testid="promotion-edit-details-form-limit-input"
+ />
+ </Form.Control>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-edit-details-form-limit-description"
+ >
+ {t("promotions.form.limit.description")}
+ </Text>
+ <Form.ErrorMessage data-testid="promotion-edit-details-form-limit-error" />
+ </Form.Item>
+ )
+ }}
+ />
+
<FormExtensionZone
model="promotion"
zone="edit"
diff --git a/packages/admin/src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx b/packages/admin/src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx
index 9fcc9dd41..0704bdd28 100644
--- a/packages/admin/src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx
+++ b/packages/admin/src/pages/promotions/promotion-edit-details/promotion-edit-details.tsx
@@ -5,13 +5,14 @@ import { useParams } from "react-router-dom"
import { RouteDrawer } from "../../../components/modals"
import { usePromotion } from "../../../hooks/api/promotions"
+import { PROMOTION_DETAIL_BASE_FIELDS } from "../promotion-detail/loader"
import { EditPromotionDetailsForm } from "./components/edit-promotion-form"
export const PromotionEditDetails = () => {
const { id } = useParams()
const { t } = useTranslation()
- const linkQuery = useLinkQuery("promotion")
+ const linkQuery = useLinkQuery("promotion", PROMOTION_DETAIL_BASE_FIELDS)
const { promotion, isLoading, isError, error } = usePromotion(id!, linkQuery)
if (isError) {
diff --git a/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx b/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx
index 897740e4a..41375d8c6 100644
--- a/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx
+++ b/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx
@@ -1,4 +1,4 @@
-import { PencilSquare, Trash } from "@medusajs/icons"
+import { PencilSquare, ReceiptPercent, Trash } from "@medusajs/icons"
import { HttpTypes } from "@medusajs/types"
import { Button, Container, Heading, usePrompt } from "@medusajs/ui"
import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"
@@ -112,7 +112,14 @@ export const PromotionListDataTable = () => {
pagination
isLoading={isLoading}
queryObject={raw}
+ noRecords={{
+ icon: <ReceiptPercent className="text-ui-fg-subtle" />,
+ title: t("promotions.list.noRecords.title"),
+ message: t("promotions.list.noRecords.message"),
+ action: { to: "create", label: t("actions.create") },
+ }}
navigateTo={(row) => `${row.original.id}`}
+ defaultOrder="-created_at"
orderBy={[
{ key: "created_at", label: t("fields.createdAt") },
{ key: "updated_at", label: t("fields.updatedAt") },
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index d07dfcf5d..47f3d0ee0 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -188,12 +188,13 @@
"/admin/products/imports/:transaction_id/confirm": "typeof import(\"@medusajs/medusa/api/admin/products/imports/[transaction_id]/confirm/route\")",
"/admin/promotions": "typeof import(\"@medusajs/medusa/api/admin/promotions/route\")",
"/admin/promotions/:id": "typeof import(\"@medusajs/medusa/api/admin/promotions/[id]/route\")",
- "/admin/promotions/:id/:rule_type": "typeof import(\"@medusajs/medusa/api/admin/promotions/[id]/[rule_type]/route\")",
+ "/admin/promotions/:id/:rule_type": "typeof import(\"@mercurjs/core/api/admin/promotions/[id]/[rule_type]/route\")",
"/admin/promotions/:id/buy-rules/batch": "typeof import(\"@medusajs/medusa/api/admin/promotions/[id]/buy-rules/batch/route\")",
+ "/admin/promotions/:id/cost": "typeof import(\"@mercurjs/core/api/admin/promotions/[id]/cost/route\")",
"/admin/promotions/:id/rules/batch": "typeof import(\"@medusajs/medusa/api/admin/promotions/[id]/rules/batch/route\")",
"/admin/promotions/:id/target-rules/batch": "typeof import(\"@medusajs/medusa/api/admin/promotions/[id]/target-rules/batch/route\")",
- "/admin/promotions/rule-attribute-options/:rule_type": "typeof import(\"@medusajs/medusa/api/admin/promotions/rule-attribute-options/[rule_type]/route\")",
- "/admin/promotions/rule-value-options/:rule_type/:rule_attribute_id": "typeof import(\"@medusajs/medusa/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route\")",
+ "/admin/promotions/rule-attribute-options/:rule_type": "typeof import(\"@mercurjs/core/api/admin/promotions/rule-attribute-options/[rule_type]/route\")",
+ "/admin/promotions/rule-value-options/:rule_type/:rule_attribute_id": "typeof import(\"@mercurjs/core/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route\")",
"/admin/property-labels": "typeof import(\"@medusajs/medusa/api/admin/property-labels/route\")",
"/admin/property-labels/:id": "typeof import(\"@medusajs/medusa/api/admin/property-labels/[id]/route\")",
"/admin/property-labels/batch": "typeof import(\"@medusajs/medusa/api/admin/property-labels/batch/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 3c0788ccb..91d64e7bf 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -326,7 +326,7 @@ export type Routes = {
};
promotions: typeof import("@medusajs/medusa/api/admin/promotions/route") & {
$id: typeof import("@medusajs/medusa/api/admin/promotions/[id]/route") & {
- $ruleType: typeof import("@medusajs/medusa/api/admin/promotions/[id]/[rule_type]/route");
+ $ruleType: typeof import("../src/api/admin/promotions/[id]/[rule_type]/route");
buyRules: {
batch: typeof import("@medusajs/medusa/api/admin/promotions/[id]/buy-rules/batch/route");
};
@@ -336,13 +336,14 @@ export type Routes = {
targetRules: {
batch: typeof import("@medusajs/medusa/api/admin/promotions/[id]/target-rules/batch/route");
};
+ cost: typeof import("../src/api/admin/promotions/[id]/cost/route");
};
ruleAttributeOptions: {
- $ruleType: typeof import("@medusajs/medusa/api/admin/promotions/rule-attribute-options/[rule_type]/route");
+ $ruleType: typeof import("../src/api/admin/promotions/rule-attribute-options/[rule_type]/route");
};
ruleValueOptions: {
$ruleType: {
- $ruleAttributeId: typeof import("@medusajs/medusa/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route");
+ $ruleAttributeId: typeof import("../src/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route");
};
};
};
diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.ts
index 6325d1805..f9a5b25cf 100644
--- a/packages/core/src/api/admin/middlewares.ts
+++ b/packages/core/src/api/admin/middlewares.ts
@@ -13,6 +13,7 @@ import { adminMembersMiddlewares } from "./members/middlewares"
import { adminCommissionRatesMiddlewares } from "./commission-rates/middlewares"
import { adminProductsMiddlewares } from "./products/middlewares"
+import { adminPromotionsMiddlewares } from "./promotions/middlewares"
import { adminCollectionsMiddlewares } from "./collections/middlewares"
import { adminProductCategoriesMiddlewares } from "./product-categories/middlewares"
import { adminProductAttributesMiddlewares } from "./product-attributes/middlewares"
@@ -41,6 +42,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [
...adminMembersMiddlewares,
...adminCommissionRatesMiddlewares,
...adminProductsMiddlewares,
+ ...adminPromotionsMiddlewares,
...adminCollectionsMiddlewares,
...adminProductCategoriesMiddlewares,
...adminProductAttributesMiddlewares,
diff --git a/packages/core/src/api/admin/promotions/[id]/[rule_type]/route.ts b/packages/core/src/api/admin/promotions/[id]/[rule_type]/route.ts
new file mode 100644
index 000000000..45d007fb9
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/[id]/[rule_type]/route.ts
@@ -0,0 +1,153 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import {
+ ContainerRegistrationKeys,
+ RuleOperator,
+ RuleType,
+} from "@medusajs/framework/utils"
+
+import {
+ getRuleAttributesMap,
+ operatorsMap,
+ ruleQueryConfigurations,
+ validateRuleType,
+} from "../../utils"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse
+) => {
+ const { id, rule_type: ruleType } = req.params
+
+ validateRuleType(ruleType)
+
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const dasherizedRuleType = ruleType.split("-").join("_")
+
+ const {
+ data: [promotion],
+ } = await query.graph({
+ entity: "promotion",
+ filters: { id },
+ fields: [...req.queryConfig.fields, "seller.id"],
+ })
+
+ const ownerSellerId = promotion?.seller?.id
+
+ const ruleAttributes = getRuleAttributesMap({
+ promotionType: promotion?.type || (req.query.promotion_type as any),
+ applicationMethodType:
+ promotion?.application_method?.type ||
+ (req.query.application_method_type as any),
+ applicationMethodTargetType:
+ promotion?.application_method?.target_type ||
+ (req.query.application_method_target_type as any),
+ })[ruleType]
+
+ const promotionRules: any[] = []
+
+ if (dasherizedRuleType === RuleType.RULES) {
+ promotionRules.push(...(promotion?.rules || []))
+ } else if (dasherizedRuleType === RuleType.TARGET_RULES) {
+ promotionRules.push(...(promotion?.application_method?.target_rules || []))
+ } else if (dasherizedRuleType === RuleType.BUY_RULES) {
+ promotionRules.push(...(promotion?.application_method?.buy_rules || []))
+ }
+
+ const transformedRules: any[] = []
+ const disguisedRules = ruleAttributes.filter((attr: any) => !!attr.disguised)
+
+ for (const disguisedRule of disguisedRules) {
+ const getValues = () => {
+ const value = promotion?.application_method?.[disguisedRule.id]
+
+ if (disguisedRule.field_type === "number") {
+ return value
+ }
+
+ if (value) {
+ return [{ label: value, value }]
+ }
+
+ return []
+ }
+
+ const required = disguisedRule.required ?? true
+ const applicationMethod = promotion?.application_method
+ const recordValue = applicationMethod?.[disguisedRule.id]
+
+ if (required || recordValue) {
+ transformedRules.push({
+ ...disguisedRule,
+ id: undefined,
+ attribute: disguisedRule.id,
+ attribute_label: disguisedRule.label,
+ operator: RuleOperator.EQ,
+ operator_label: operatorsMap[RuleOperator.EQ].label,
+ value: undefined,
+ values: getValues(),
+ })
+ }
+ }
+
+ for (const promotionRule of [...promotionRules, ...transformedRules]) {
+ const currentRuleAttribute = ruleAttributes.find(
+ (attr: any) => attr.value === promotionRule.attribute
+ )
+
+ if (!currentRuleAttribute) {
+ continue
+ }
+
+ const queryConfig = ruleQueryConfigurations[currentRuleAttribute.id]
+
+ if (!queryConfig) {
+ continue
+ }
+
+ const filters: Record<string, any> = {
+ [queryConfig.valueAttr]: promotionRule.values?.map((v: any) => v.value),
+ }
+
+ if (queryConfig.entryPoint === "offer" && ownerSellerId) {
+ filters.seller_id = ownerSellerId
+ }
+
+ const { data: rows } = await query.graph({
+ entity: queryConfig.entryPoint,
+ filters,
+ fields: [queryConfig.labelAttr, queryConfig.valueAttr],
+ })
+
+ const valueLabelMap = new Map<string, string>(
+ rows.map((row: any) => [
+ row[queryConfig.valueAttr],
+ row[queryConfig.labelAttr],
+ ])
+ )
+
+ promotionRule.values =
+ promotionRule.values?.map((value: any) => ({
+ value: value.value,
+ label: valueLabelMap.get(value.value) || value.value,
+ })) || promotionRule.values
+
+ if (!currentRuleAttribute.hydrate) {
+ transformedRules.push({
+ ...currentRuleAttribute,
+ ...promotionRule,
+ attribute_label: currentRuleAttribute.label,
+ operator_label:
+ operatorsMap[promotionRule.operator as keyof typeof operatorsMap]
+ ?.label || promotionRule.operator,
+ })
+ }
+ }
+
+ res.json({
+ rules: transformedRules,
+ })
+}
diff --git a/packages/core/src/api/admin/promotions/[id]/cost/route.ts b/packages/core/src/api/admin/promotions/[id]/cost/route.ts
new file mode 100644
index 000000000..a98eb0bfb
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/[id]/cost/route.ts
@@ -0,0 +1,28 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+
+import { upsertPromotionCostsWorkflow } from "../../../../../workflows/promotion-cost"
+import { AdminUpsertPromotionCostType } from "./validators"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminUpsertPromotionCostType>,
+ res: MedusaResponse
+) => {
+ const { id } = req.params
+ const { cost_bearer, shared_marketplace_percentage } = req.validatedBody
+
+ const { result } = await upsertPromotionCostsWorkflow(req.scope).run({
+ input: {
+ promotion_id: id,
+ cost_bearer,
+ shared_marketplace_percentage:
+ cost_bearer === "shared" ? shared_marketplace_percentage ?? null : null,
+ },
+ })
+
+ const [promotion_cost] = Array.isArray(result) ? result : [result]
+
+ res.json({ promotion_cost })
+}
diff --git a/packages/core/src/api/admin/promotions/[id]/cost/validators.ts b/packages/core/src/api/admin/promotions/[id]/cost/validators.ts
new file mode 100644
index 000000000..55987b07c
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/[id]/cost/validators.ts
@@ -0,0 +1,10 @@
+import { z } from "zod"
+
+export const AdminUpsertPromotionCost = z.object({
+ cost_bearer: z.enum(["store", "marketplace", "shared"]),
+ shared_marketplace_percentage: z.number().min(0).max(100).nullish(),
+})
+
+export type AdminUpsertPromotionCostType = z.infer<
+ typeof AdminUpsertPromotionCost
+>
diff --git a/packages/core/src/api/admin/promotions/helpers.ts b/packages/core/src/api/admin/promotions/helpers.ts
new file mode 100644
index 000000000..bc65ed240
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/helpers.ts
@@ -0,0 +1,51 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaNextFunction,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+const PLATFORM_OWNER = "platform"
+
+export const applyPromotionSellerFilter = async (
+ req: AuthenticatedMedusaRequest,
+ _res: MedusaResponse,
+ next: MedusaNextFunction
+) => {
+ const filterableFields = req.filterableFields ?? {}
+ const sellerId = filterableFields.seller_id as string | string[] | undefined
+
+ if (!sellerId) {
+ return next()
+ }
+
+ delete filterableFields.seller_id
+
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const wantsPlatform =
+ sellerId === PLATFORM_OWNER ||
+ (Array.isArray(sellerId) && sellerId.includes(PLATFORM_OWNER))
+
+ if (wantsPlatform) {
+ const { data: links } = await query.graph({
+ entity: "promotion_seller",
+ fields: ["promotion_id"],
+ })
+ const ownedIds = links.map((l: { promotion_id: string }) => l.promotion_id)
+
+ filterableFields.id = ownedIds.length ? { $nin: ownedIds } : undefined
+ return next()
+ }
+
+ const { data: links } = await query.graph({
+ entity: "promotion_seller",
+ fields: ["promotion_id"],
+ filters: { seller_id: sellerId },
+ })
+ const promotionIds = links.map(
+ (l: { promotion_id: string }) => l.promotion_id
+ )
+
+ filterableFields.id = promotionIds.length ? promotionIds : ["__no_match__"]
+ return next()
+}
diff --git a/packages/core/src/api/admin/promotions/middlewares.ts b/packages/core/src/api/admin/promotions/middlewares.ts
new file mode 100644
index 000000000..3a7598bf7
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/middlewares.ts
@@ -0,0 +1,86 @@
+import {
+ validateAndTransformBody,
+ validateAndTransformQuery,
+} from "@medusajs/framework"
+import { MiddlewareRoute } from "@medusajs/framework/http"
+import {
+ listRuleValueTransformQueryConfig,
+ listTransformQueryConfig,
+} from "@medusajs/medusa/api/admin/promotions/query-config"
+import {
+ AdminGetPromotionsParams,
+ AdminGetPromotionsRuleValueParams,
+} from "@medusajs/medusa/api/admin/promotions/validators"
+import { z } from "zod"
+
+import { ORIGINAL_MIDDLEWARES } from "../../../utils/disable-medusa-middlewares"
+import { AdminUpsertPromotionCost } from "./[id]/cost/validators"
+import { applyPromotionSellerFilter } from "./helpers"
+
+const RULE_VALUE_MATCHER =
+ "/admin/promotions/rule-value-options/:rule_type/:rule_attribute_id"
+const LIST_MATCHER = "/admin/promotions"
+
+const capturedBase = (ORIGINAL_MIDDLEWARES[
+ "dist/api/admin/promotions/middlewares.js"
+] ?? []) as MiddlewareRoute[]
+
+const routeHasGet = (route: MiddlewareRoute) => {
+ const methods = Array.isArray(route.method)
+ ? route.method
+ : route.method
+ ? [route.method]
+ : []
+ return methods.includes("GET")
+}
+
+const baseWithoutOverrides = capturedBase.filter((route) => {
+ if (route.matcher === RULE_VALUE_MATCHER && routeHasGet(route)) {
+ return false
+ }
+ if (route.matcher === LIST_MATCHER && routeHasGet(route)) {
+ return false
+ }
+ return true
+})
+
+const AdminGetPromotionsRuleValueWithSeller =
+ AdminGetPromotionsRuleValueParams.merge(
+ z.object({ seller_id: z.string().optional() })
+ )
+
+const AdminGetPromotionsWithSeller = AdminGetPromotionsParams.merge(
+ z.object({
+ seller_id: z.union([z.string(), z.array(z.string())]).optional(),
+ })
+)
+
+export const adminPromotionsMiddlewares: MiddlewareRoute[] = [
+ ...baseWithoutOverrides,
+ {
+ method: ["GET"],
+ matcher: LIST_MATCHER,
+ middlewares: [
+ validateAndTransformQuery(
+ AdminGetPromotionsWithSeller,
+ listTransformQueryConfig
+ ),
+ applyPromotionSellerFilter,
+ ],
+ },
+ {
+ method: ["GET"],
+ matcher: RULE_VALUE_MATCHER,
+ middlewares: [
+ validateAndTransformQuery(
+ AdminGetPromotionsRuleValueWithSeller,
+ listRuleValueTransformQueryConfig
+ ),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/promotions/:id/cost",
+ middlewares: [validateAndTransformBody(AdminUpsertPromotionCost)],
+ },
+]
diff --git a/packages/core/src/api/admin/promotions/rule-attribute-options/[rule_type]/route.ts b/packages/core/src/api/admin/promotions/rule-attribute-options/[rule_type]/route.ts
new file mode 100644
index 000000000..563f55c49
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/rule-attribute-options/[rule_type]/route.ts
@@ -0,0 +1,34 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import {
+ ApplicationMethodTargetTypeValues,
+ ApplicationMethodTypeValues,
+ HttpTypes,
+ PromotionTypeValues,
+} from "@medusajs/types"
+
+import { getRuleAttributesMap, validateRuleType } from "../../utils"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminRuleAttributeOptionsListResponse>
+) => {
+ const { rule_type: ruleType } = req.params
+
+ validateRuleType(ruleType)
+
+ const attributes =
+ getRuleAttributesMap({
+ promotionType: req.query.promotion_type as PromotionTypeValues,
+ applicationMethodType: req.query
+ .application_method_type as ApplicationMethodTypeValues,
+ applicationMethodTargetType: req.query
+ .application_method_target_type as ApplicationMethodTargetTypeValues,
+ })[ruleType] || []
+
+ res.json({
+ attributes,
+ })
+}
diff --git a/packages/core/src/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route.ts b/packages/core/src/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route.ts
new file mode 100644
index 000000000..ae2468cc8
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route.ts
@@ -0,0 +1,72 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import {
+ ApplicationMethodTargetTypeValues,
+ HttpTypes,
+ RuleTypeValues,
+} from "@medusajs/types"
+
+import {
+ ruleQueryConfigurations,
+ validateRuleAttribute,
+ validateRuleType,
+} from "../../../utils"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminRuleValueOptionsListResponse>
+) => {
+ const { rule_type: ruleType, rule_attribute_id: ruleAttributeId } = req.params
+ const queryConfig = ruleQueryConfigurations[ruleAttributeId]
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const filterableFields: Record<string, any> = { ...req.filterableFields }
+
+ if (filterableFields.value) {
+ filterableFields[queryConfig.valueAttr] = filterableFields.value
+ delete filterableFields.value
+ }
+
+ validateRuleType(ruleType)
+ validateRuleAttribute({
+ ruleType: ruleType as RuleTypeValues,
+ ruleAttributeId,
+ promotionType: undefined,
+ applicationMethodType: undefined,
+ applicationMethodTargetType:
+ filterableFields.application_method_target_type as
+ | ApplicationMethodTargetTypeValues
+ | undefined,
+ })
+
+ if (filterableFields.application_method_target_type) {
+ delete filterableFields.application_method_target_type
+ }
+
+ // Offers are seller-owned; scope them to a store when the admin picks one
+ // (offer carries `seller_id` as a read-only column).
+ if (queryConfig.entryPoint === "offer" && req.query.seller_id) {
+ filterableFields.seller_id = req.query.seller_id
+ }
+
+ const { data: rows, metadata } = await query.graph({
+ entity: queryConfig.entryPoint,
+ filters: filterableFields,
+ fields: [queryConfig.labelAttr, queryConfig.valueAttr],
+ pagination: req.queryConfig.pagination,
+ })
+
+ const values = rows.map((r: any) => ({
+ label: r[queryConfig.labelAttr],
+ value: r[queryConfig.valueAttr],
+ }))
+
+ res.json({
+ values,
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
diff --git a/packages/core/src/api/admin/promotions/utils/index.ts b/packages/core/src/api/admin/promotions/utils/index.ts
new file mode 100644
index 000000000..b9837dfc3
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/index.ts
@@ -0,0 +1,5 @@
+export * from "./operators-map"
+export * from "./rule-attributes-map"
+export * from "./rule-query-configuration"
+export * from "./validate-rule-attribute"
+export * from "./validate-rule-type"
diff --git a/packages/core/src/api/admin/promotions/utils/operators-map.ts b/packages/core/src/api/admin/promotions/utils/operators-map.ts
new file mode 100644
index 000000000..32f56a461
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/operators-map.ts
@@ -0,0 +1,19 @@
+import { RuleOperator } from "@medusajs/framework/utils"
+
+export const operatorsMap = {
+ [RuleOperator.IN]: {
+ id: RuleOperator.IN,
+ value: RuleOperator.IN,
+ label: "In",
+ },
+ [RuleOperator.EQ]: {
+ id: RuleOperator.EQ,
+ value: RuleOperator.EQ,
+ label: "Equals",
+ },
+ [RuleOperator.NE]: {
+ id: RuleOperator.NE,
+ value: RuleOperator.NE,
+ label: "Not In",
+ },
+}
diff --git a/packages/core/src/api/admin/promotions/utils/rule-attributes-map.ts b/packages/core/src/api/admin/promotions/utils/rule-attributes-map.ts
new file mode 100644
index 000000000..dc9edd06e
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/rule-attributes-map.ts
@@ -0,0 +1,188 @@
+import {
+ ApplicationMethodTargetType,
+ ApplicationMethodType,
+ PromotionType,
+ RuleOperator,
+} from "@medusajs/framework/utils"
+import {
+ ApplicationMethodTargetTypeValues,
+ ApplicationMethodTypeValues,
+ PromotionTypeValues,
+} from "@medusajs/types"
+
+import { operatorsMap } from "./operators-map"
+
+export enum DisguisedRule {
+ APPLY_TO_QUANTITY = "apply_to_quantity",
+ BUY_RULES_MIN_QUANTITY = "buy_rules_min_quantity",
+ CURRENCY_CODE = "currency_code",
+}
+
+const ruleAttributes = [
+ {
+ id: "customer_group",
+ value: "customer.groups.id",
+ label: "Customer Group",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "region",
+ value: "region.id",
+ label: "Region",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "country",
+ value: "shipping_address.country_code",
+ label: "Country",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "sales_channel",
+ value: "sales_channel_id",
+ label: "Sales Channel",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+]
+
+const itemsAttributes = [
+ {
+ id: "offer",
+ value: "items.metadata.offer_id",
+ label: "Offer",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "product",
+ value: "items.product.id",
+ label: "Product",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "product_category",
+ value: "items.product.categories.id",
+ label: "Product Category",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "product_collection",
+ value: "items.product.collection_id",
+ label: "Product Collection",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "product_type",
+ value: "items.product.type_id",
+ label: "Product Type",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+ {
+ id: "product_tag",
+ value: "items.product.tags.id",
+ label: "Product Tag",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+]
+
+const shippingMethodsAttributes = [
+ {
+ id: "shipping_option_type",
+ value: "shipping_methods.shipping_option.shipping_option_type_id",
+ label: "Shipping Option Type",
+ required: false,
+ field_type: "multiselect",
+ operators: Object.values(operatorsMap),
+ },
+]
+
+const currencyRule = {
+ id: DisguisedRule.CURRENCY_CODE,
+ value: DisguisedRule.CURRENCY_CODE,
+ label: "Currency Code",
+ field_type: "select",
+ required: true,
+ disguised: true,
+ hydrate: true,
+ operators: [operatorsMap[RuleOperator.EQ]],
+}
+
+const buyGetBuyRules = [
+ {
+ id: DisguisedRule.BUY_RULES_MIN_QUANTITY,
+ value: DisguisedRule.BUY_RULES_MIN_QUANTITY,
+ label: "Minimum quantity of items",
+ field_type: "number",
+ required: true,
+ disguised: true,
+ operators: [operatorsMap[RuleOperator.EQ]],
+ },
+]
+
+const buyGetTargetRules = [
+ {
+ id: DisguisedRule.APPLY_TO_QUANTITY,
+ value: DisguisedRule.APPLY_TO_QUANTITY,
+ label: "Quantity of items promotion will apply to",
+ field_type: "number",
+ required: true,
+ disguised: true,
+ operators: [operatorsMap[RuleOperator.EQ]],
+ },
+]
+
+export const getRuleAttributesMap = ({
+ promotionType,
+ applicationMethodType,
+ applicationMethodTargetType,
+}: {
+ promotionType?: PromotionTypeValues
+ applicationMethodType?: ApplicationMethodTypeValues
+ applicationMethodTargetType?: ApplicationMethodTargetTypeValues
+}) => {
+ const map: Record<string, any[]> = {
+ rules: [...ruleAttributes],
+ "target-rules":
+ applicationMethodTargetType ===
+ ApplicationMethodTargetType.SHIPPING_METHODS
+ ? [...shippingMethodsAttributes]
+ : [...itemsAttributes],
+ "buy-rules":
+ applicationMethodTargetType ===
+ ApplicationMethodTargetType.SHIPPING_METHODS
+ ? [...shippingMethodsAttributes]
+ : [...itemsAttributes],
+ }
+
+ if (applicationMethodType === ApplicationMethodType.FIXED) {
+ map["rules"].push({ ...currencyRule })
+ } else {
+ map["rules"].push({ ...currencyRule, required: false })
+ }
+
+ if (promotionType === PromotionType.BUYGET) {
+ map["buy-rules"].push(...buyGetBuyRules)
+ map["target-rules"].push(...buyGetTargetRules)
+ }
+
+ return map
+}
diff --git a/packages/core/src/api/admin/promotions/utils/rule-query-configuration.ts b/packages/core/src/api/admin/promotions/utils/rule-query-configuration.ts
new file mode 100644
index 000000000..e298583f7
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/rule-query-configuration.ts
@@ -0,0 +1,65 @@
+export const ruleQueryConfigurations: Record<
+ string,
+ { entryPoint: string; labelAttr: string; valueAttr: string }
+> = {
+ region: {
+ entryPoint: "region",
+ labelAttr: "name",
+ valueAttr: "id",
+ },
+ currency_code: {
+ entryPoint: "currency",
+ labelAttr: "name",
+ valueAttr: "code",
+ },
+ customer_group: {
+ entryPoint: "customer_group",
+ labelAttr: "name",
+ valueAttr: "id",
+ },
+ sales_channel: {
+ entryPoint: "sales_channel",
+ labelAttr: "name",
+ valueAttr: "id",
+ },
+ country: {
+ entryPoint: "country",
+ labelAttr: "display_name",
+ valueAttr: "iso_2",
+ },
+ offer: {
+ entryPoint: "offer",
+ labelAttr: "sku",
+ valueAttr: "id",
+ },
+ product: {
+ entryPoint: "product",
+ labelAttr: "title",
+ valueAttr: "id",
+ },
+ product_category: {
+ entryPoint: "product_category",
+ labelAttr: "name",
+ valueAttr: "id",
+ },
+ product_collection: {
+ entryPoint: "product_collection",
+ labelAttr: "title",
+ valueAttr: "id",
+ },
+ product_type: {
+ entryPoint: "product_type",
+ labelAttr: "value",
+ valueAttr: "id",
+ },
+ product_tag: {
+ entryPoint: "product_tag",
+ labelAttr: "value",
+ valueAttr: "id",
+ },
+ shipping_option_type: {
+ entryPoint: "shipping_option_type",
+ labelAttr: "label",
+ valueAttr: "id",
+ },
+}
diff --git a/packages/core/src/api/admin/promotions/utils/validate-rule-attribute.ts b/packages/core/src/api/admin/promotions/utils/validate-rule-attribute.ts
new file mode 100644
index 000000000..f43b2d336
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/validate-rule-attribute.ts
@@ -0,0 +1,41 @@
+import { MedusaError } from "@medusajs/framework/utils"
+import {
+ ApplicationMethodTargetTypeValues,
+ ApplicationMethodTypeValues,
+ PromotionTypeValues,
+ RuleTypeValues,
+} from "@medusajs/types"
+
+import { getRuleAttributesMap } from "./rule-attributes-map"
+
+export function validateRuleAttribute(attributes: {
+ promotionType: PromotionTypeValues | undefined
+ ruleType: RuleTypeValues
+ ruleAttributeId: string
+ applicationMethodType?: ApplicationMethodTypeValues
+ applicationMethodTargetType?: ApplicationMethodTargetTypeValues
+}) {
+ const {
+ promotionType,
+ ruleType,
+ ruleAttributeId,
+ applicationMethodType,
+ applicationMethodTargetType,
+ } = attributes
+
+ const ruleAttributes =
+ getRuleAttributesMap({
+ promotionType,
+ applicationMethodType,
+ applicationMethodTargetType,
+ })[ruleType] || []
+
+ const ruleAttribute = ruleAttributes.find((obj) => obj.id === ruleAttributeId)
+
+ if (!ruleAttribute) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Invalid rule attribute - ${ruleAttributeId}`
+ )
+ }
+}
diff --git a/packages/core/src/api/admin/promotions/utils/validate-rule-type.ts b/packages/core/src/api/admin/promotions/utils/validate-rule-type.ts
new file mode 100644
index 000000000..da12327f3
--- /dev/null
+++ b/packages/core/src/api/admin/promotions/utils/validate-rule-type.ts
@@ -0,0 +1,14 @@
+import { MedusaError, RuleType } from "@medusajs/framework/utils"
+
+const validRuleTypes: string[] = Object.values(RuleType)
+
+export function validateRuleType(ruleType: string) {
+ const underscorizedRuleType = ruleType.split("-").join("_")
+
+ if (!validRuleTypes.includes(underscorizedRuleType)) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Invalid param rule_type (${ruleType})`
+ )
+ }
+}
diff --git a/packages/core/src/links/promotion-cost-link.ts b/packages/core/src/links/promotion-cost-link.ts
new file mode 100644
index 000000000..cb971becd
--- /dev/null
+++ b/packages/core/src/links/promotion-cost-link.ts
@@ -0,0 +1,18 @@
+import { defineLink } from "@medusajs/framework/utils"
+import PromotionModule from "@medusajs/medusa/promotion"
+
+import PromotionCostModule from "../modules/promotion-cost"
+
+export default defineLink(
+ {
+ linkable: PromotionModule.linkable.promotion,
+ field: "id",
+ },
+ {
+ ...PromotionCostModule.linkable.promotionCost.id,
+ primaryKey: "promotion_id",
+ },
+ {
+ readOnly: true,
+ }
+)
diff --git a/packages/core/src/modules/promotion-cost/index.ts b/packages/core/src/modules/promotion-cost/index.ts
new file mode 100644
index 000000000..ad1b36645
--- /dev/null
+++ b/packages/core/src/modules/promotion-cost/index.ts
@@ -0,0 +1,8 @@
+import { Module } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+import PromotionCostModuleService from "./service"
+
+export default Module(MercurModules.PROMOTION_COST, {
+ service: PromotionCostModuleService,
+})
diff --git a/packages/core/src/modules/promotion-cost/migrations/Migration20260722120000.ts b/packages/core/src/modules/promotion-cost/migrations/Migration20260722120000.ts
new file mode 100644
index 000000000..1e08e3d69
--- /dev/null
+++ b/packages/core/src/modules/promotion-cost/migrations/Migration20260722120000.ts
@@ -0,0 +1,19 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20260722120000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `create table if not exists "promotion_cost" ("id" text not null, "promotion_id" text not null, "cost_bearer" text check ("cost_bearer" in ('store', 'marketplace', 'shared')) not null default 'store', "shared_marketplace_percentage" integer null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "promotion_cost_pkey" primary key ("id"));`
+ )
+ this.addSql(
+ `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_promotion_cost_promotion_id_unique" ON "promotion_cost" ("promotion_id") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_promotion_cost_deleted_at" ON "promotion_cost" ("deleted_at") WHERE deleted_at IS NULL;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`drop table if exists "promotion_cost" cascade;`)
+ }
+}
diff --git a/packages/core/src/modules/promotion-cost/models/index.ts b/packages/core/src/modules/promotion-cost/models/index.ts
new file mode 100644
index 000000000..8a7b4288c
--- /dev/null
+++ b/packages/core/src/modules/promotion-cost/models/index.ts
@@ -0,0 +1 @@
+export { default as PromotionCost } from "./promotion-cost"
diff --git a/packages/core/src/modules/promotion-cost/models/promotion-cost.ts b/packages/core/src/modules/promotion-cost/models/promotion-cost.ts
new file mode 100644
index 000000000..8cce37343
--- /dev/null
+++ b/packages/core/src/modules/promotion-cost/models/promotion-cost.ts
@@ -0,0 +1,20 @@
+import { model } from "@medusajs/framework/utils"
+
+const PromotionCost = model
+ .define("PromotionCost", {
+ id: model.id({ prefix: "promcost" }).primaryKey(),
+ promotion_id: model.text(),
+ cost_bearer: model.enum(["store", "marketplace", "shared"]).default("store"),
+ shared_marketplace_percentage: model.number().nullable(),
+ metadata: model.json().nullable(),
+ })
+ .indexes([
+ {
+ name: "IDX_promotion_cost_promotion_id_unique",
+ on: ["promotion_id"],
+ unique: true,
+ where: "deleted_at IS NULL",
+ },
+ ])
+
+export default PromotionCost
diff --git a/packages/core/src/modules/promotion-cost/service.ts b/packages/core/src/modules/promotion-cost/service.ts
new file mode 100644
index 000000000..3271a38e3
--- /dev/null
+++ b/packages/core/src/modules/promotion-cost/service.ts
@@ -0,0 +1,50 @@
+import { MedusaService } from "@medusajs/framework/utils"
+import { UpsertPromotionCostDTO } from "@mercurjs/types"
+
+import { PromotionCost } from "./models"
+
+class PromotionCostModuleService extends MedusaService({
+ PromotionCost,
+}) {
+ async upsertPromotionCostsByPromotionId(
+ input: UpsertPromotionCostDTO | UpsertPromotionCostDTO[]
+ ) {
+ const data = Array.isArray(input) ? input : [input]
+
+ if (!data.length) {
+ return []
+ }
+
+ const existing = await this.listPromotionCosts({
+ promotion_id: data.map((entry) => entry.promotion_id),
+ })
+
+ const existingByPromotion = new Map(
+ existing.map((cost) => [cost.promotion_id, cost])
+ )
+
+ const toCreate: UpsertPromotionCostDTO[] = []
+ const toUpdate: (UpsertPromotionCostDTO & { id: string })[] = []
+
+ for (const entry of data) {
+ const current = existingByPromotion.get(entry.promotion_id)
+
+ if (current) {
+ toUpdate.push({ ...entry, id: current.id })
+ } else {
+ toCreate.push(entry)
+ }
+ }
+
+ const created = toCreate.length
+ ? await this.createPromotionCosts(toCreate)
+ : []
+ const updated = toUpdate.length
+ ? await this.updatePromotionCosts(toUpdate)
+ : []
+
+ return [...created, ...updated]
+ }
+}
+
+export default PromotionCostModuleService
diff --git a/packages/core/src/utils/disable-medusa-middlewares.ts b/packages/core/src/utils/disable-medusa-middlewares.ts
index 47ce21fdb..89d9e54a1 100644
--- a/packages/core/src/utils/disable-medusa-middlewares.ts
+++ b/packages/core/src/utils/disable-medusa-middlewares.ts
@@ -25,6 +25,7 @@ import pkgDir from "pkg-dir"
const OVERRIDES: string[] = [
"dist/api/admin/products/middlewares.js",
+ "dist/api/admin/promotions/middlewares.js",
"dist/api/admin/product-variants/middlewares.js",
"dist/api/admin/product-categories/middlewares.js",
"dist/api/admin/collections/middlewares.js",
diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.ts
index 40d055638..df7f4ffea 100644
--- a/packages/core/src/workflows/index.ts
+++ b/packages/core/src/workflows/index.ts
@@ -6,6 +6,7 @@ export * from "./inventory-item"
export * from "./order-group"
export * from "./price-list"
export * from "./promotion"
+export * from "./promotion-cost"
export * from "./seller"
export * from "./shipping-option"
export * from "./shipping-profile"
diff --git a/packages/core/src/workflows/promotion-cost/index.ts b/packages/core/src/workflows/promotion-cost/index.ts
new file mode 100644
index 000000000..68de82c9f
--- /dev/null
+++ b/packages/core/src/workflows/promotion-cost/index.ts
@@ -0,0 +1,2 @@
+export * from "./steps"
+export * from "./workflows"
diff --git a/packages/core/src/workflows/promotion-cost/steps/index.ts b/packages/core/src/workflows/promotion-cost/steps/index.ts
new file mode 100644
index 000000000..1e8ec822f
--- /dev/null
+++ b/packages/core/src/workflows/promotion-cost/steps/index.ts
@@ -0,0 +1 @@
+export * from "./upsert-promotion-costs"
diff --git a/packages/core/src/workflows/promotion-cost/steps/upsert-promotion-costs.ts b/packages/core/src/workflows/promotion-cost/steps/upsert-promotion-costs.ts
new file mode 100644
index 000000000..2505b9cc9
--- /dev/null
+++ b/packages/core/src/workflows/promotion-cost/steps/upsert-promotion-costs.ts
@@ -0,0 +1,61 @@
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { MercurModules, UpsertPromotionCostDTO } from "@mercurjs/types"
+
+import type PromotionCostModuleService from "../../../modules/promotion-cost/service"
+
+export const upsertPromotionCostsStep = createStep(
+ "upsert-promotion-costs",
+ async (input: UpsertPromotionCostDTO | UpsertPromotionCostDTO[], { container }) => {
+ const service = container.resolve<PromotionCostModuleService>(
+ MercurModules.PROMOTION_COST
+ )
+
+ const entries = Array.isArray(input) ? input : [input]
+
+ const existing = await service.listPromotionCosts({
+ promotion_id: entries.map((entry) => entry.promotion_id),
+ })
+
+ const costs = await service.upsertPromotionCostsByPromotionId(entries)
+
+ return new StepResponse(costs, { entries, existing })
+ },
+ async (compensation, { container }) => {
+ if (!compensation) {
+ return
+ }
+
+ const service = container.resolve<PromotionCostModuleService>(
+ MercurModules.PROMOTION_COST
+ )
+
+ const { entries, existing } = compensation
+ const existingPromotionIds = new Set(
+ existing.map((cost) => cost.promotion_id)
+ )
+
+ if (existing.length) {
+ await service.updatePromotionCosts(
+ existing.map((cost) => ({
+ id: cost.id,
+ cost_bearer: cost.cost_bearer,
+ shared_marketplace_percentage: cost.shared_marketplace_percentage,
+ }))
+ )
+ }
+
+ const createdPromotionIds = entries
+ .map((entry) => entry.promotion_id)
+ .filter((promotionId) => !existingPromotionIds.has(promotionId))
+
+ if (createdPromotionIds.length) {
+ const created = await service.listPromotionCosts({
+ promotion_id: createdPromotionIds,
+ })
+
+ if (created.length) {
+ await service.deletePromotionCosts(created.map((cost) => cost.id))
+ }
+ }
+ }
+)
diff --git a/packages/core/src/workflows/promotion-cost/workflows/index.ts b/packages/core/src/workflows/promotion-cost/workflows/index.ts
new file mode 100644
index 000000000..1e8ec822f
--- /dev/null
+++ b/packages/core/src/workflows/promotion-cost/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./upsert-promotion-costs"
diff --git a/packages/core/src/workflows/promotion-cost/workflows/upsert-promotion-costs.ts b/packages/core/src/workflows/promotion-cost/workflows/upsert-promotion-costs.ts
new file mode 100644
index 000000000..403628208
--- /dev/null
+++ b/packages/core/src/workflows/promotion-cost/workflows/upsert-promotion-costs.ts
@@ -0,0 +1,16 @@
+import {
+ createWorkflow,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { UpsertPromotionCostDTO } from "@mercurjs/types"
+
+import { upsertPromotionCostsStep } from "../steps"
+
+export const upsertPromotionCostsWorkflow = createWorkflow(
+ "upsert-promotion-costs",
+ function (input: UpsertPromotionCostDTO | UpsertPromotionCostDTO[]) {
+ const costs = upsertPromotionCostsStep(input)
+
+ return new WorkflowResponse(costs)
+ }
+)
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 4328b97d1..6c41c1e8b 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -18,6 +18,9 @@ export * from "./payout"
// Offer types
export * from "./offer"
+// Promotion cost types
+export * from "./promotion-cost"
+
// Product types — explicit re-export overrides Medusa's product surface.
// Mercur's runtime enums and Mercur-extended DTOs (Omit + intersection over
// upstream) win over the wholesale `export * from "@medusajs/types"` above.
diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.ts
index f3caf0281..f12fafd8d 100644
--- a/packages/types/src/modules.ts
+++ b/packages/types/src/modules.ts
@@ -11,4 +11,5 @@ export enum MercurModules {
ADMIN_UI = "admin_ui",
CODEGEN = "codegen",
SEARCH = "search",
+ PROMOTION_COST = "promotion_cost",
}
diff --git a/packages/types/src/promotion-cost/common.ts b/packages/types/src/promotion-cost/common.ts
new file mode 100644
index 000000000..9424f021e
--- /dev/null
+++ b/packages/types/src/promotion-cost/common.ts
@@ -0,0 +1,16 @@
+export type PromotionCostBearer = "store" | "marketplace" | "shared"
+
+export interface PromotionCostDTO {
+ id: string
+ promotion_id: string
+ cost_bearer: PromotionCostBearer
+ shared_marketplace_percentage: number | null
+ metadata: Record<string, unknown> | null
+}
+
+export interface UpsertPromotionCostDTO {
+ promotion_id: string
+ cost_bearer: PromotionCostBearer
+ shared_marketplace_percentage?: number | null
+ metadata?: Record<string, unknown> | null
+}
diff --git a/packages/types/src/promotion-cost/index.ts b/packages/types/src/promotion-cost/index.ts
new file mode 100644
index 000000000..488a94fdf
--- /dev/null
+++ b/packages/types/src/promotion-cost/index.ts
@@ -0,0 +1 @@
+export * from "./common"
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
index e4004d298..2bc01ae7a 100644
--- a/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
@@ -62,6 +62,11 @@ export const RuleValueFormField = ({
const { currency_code, isPending: isSellerLoading } = useCurrentSeller();
+ const watchValue = useWatch({
+ control: form.control,
+ name,
+ });
+
const comboboxData = useComboboxData({
queryFn: async (params) => {
return await sdk.vendor.promotions.ruleValueOptions.$ruleType.$ruleAttributeId.query(
@@ -83,6 +88,8 @@ export const RuleValueFormField = ({
!isSellerLoading,
getOptions: (data) => data.values,
queryKey: ["rule-value-options", ruleType, attribute?.id],
+ defaultValue: watchValue,
+ defaultValueKey: "value",
});
const watchOperator = useWatch({
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
index 0e2c0c981..663855912 100644
--- a/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
@@ -161,7 +161,15 @@ export const RulesFormField = ({
} else if (applicationMethodType !== "fixed" && currencyIndex !== -1) {
remove(currencyIndex);
}
- }, [applicationMethodType, ruleType, scope, form, append, remove, promotion?.id]);
+ }, [
+ applicationMethodType,
+ ruleType,
+ scope,
+ form,
+ append,
+ remove,
+ promotion?.id,
+ ]);
return (
<div className="flex flex-col">
@@ -311,7 +319,11 @@ export const RulesFormField = ({
ref={ref}
className="bg-ui-bg-base"
>
- <Select.Value placeholder={t('promotions.form.selectOperator')} />
+ <Select.Value
+ placeholder={t(
+ "promotions.form.selectOperator",
+ )}
+ />
</Select.Trigger>
<Select.Content>
diff --git a/skills-lock.json b/skills-lock.json
index ff044d1ef..365b0ca4f 100644
--- a/skills-lock.json
+++ b/skills-lock.json
@@ -1,4 +1,11 @@
{
"version": 1,
- "skills": {}
+ "skills": {
+ "figma-code-connect": {
+ "source": "figma/mcp-server-guide",
+ "sourceType": "github",
+ "skillPath": "skills/figma-code-connect/SKILL.md",
+ "computedHash": "97115879461e3fb0766ea31d35a370e47f140c0e2896e33ccdd1f8a693e78358"
+ }
+ }
}