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: initialize core-vendor package with essential configurations (#701)

Jakub Sieradzkif07d708b0afd
diff --git a/apps/vendor/mercur.config.ts b/apps/vendor/mercur.config.ts
index a375dbde3..6d0199eb3 100644
--- a/apps/vendor/mercur.config.ts
+++ b/apps/vendor/mercur.config.ts
@@ -6,5 +6,6 @@ export default {
components: {
Sidebar: './sidebar'
},
+
baseUrl: 'http://localhost:9000',
} satisfies MercurConfig
\ No newline at end of file
diff --git a/bun.lock b/bun.lock
index 9cc1167e8..51ec03f68 100644
--- a/bun.lock
+++ b/bun.lock
@@ -196,6 +196,7 @@
"@dnd-kit/utilities": "^3.2.2",
"@hookform/error-message": "^2.0.1",
"@hookform/resolvers": "3.4.2",
+ "@medusajs/admin-shared": "^2.13.0",
"@medusajs/dashboard": "^2.13.0",
"@medusajs/icons": "2.13.1",
"@medusajs/ui": "4.1.1",
@@ -2061,6 +2062,8 @@
"fast-levenshtein": ["[email protected]", "", {}, "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw=="],
+ "fast-uri": ["[email protected]", "", {}, "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA=="],
+
"fast-xml-parser": ["[email protected]", "", { "dependencies": { "strnum": "^2.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-EFd6afGmXlCx8H8WTZHhAoDaWaGyuIBoZJ2mknrNxug+aZKjkp0a0dlars9Izl+jF+7Gu1/5f/2h68cQpe0IiA=="],
"fastq": ["[email protected]", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="],
@@ -3483,6 +3486,8 @@
"accepts/negotiator": ["[email protected]", "", {}, "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg=="],
+ "ajv-draft-04/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g=="],
+
"ajv-formats/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2", "uri-js": "^4.4.1" } }, "sha512-PRA911Blj99jR5RMeTunVbNXMF6Lp4vZXnk5GQjcnUWUTsrXtekg/pnmFFI2u/I36Y/2bITGS30GZCXei6uNkA=="],
"ansi-align/string-width": ["[email protected]", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="],
@@ -3961,6 +3966,8 @@
"@typescript-eslint/typescript-estree/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ=="],
+ "ajv-draft-04/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
+
"ajv-formats/ajv/json-schema-traverse": ["[email protected]", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="],
"ansi-align/string-width/strip-ansi": ["[email protected]", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="],
diff --git a/packages/dashboard-sdk/src/plugin.ts b/packages/dashboard-sdk/src/plugin.ts
index c40aa6c32..8fee44dcd 100644
--- a/packages/dashboard-sdk/src/plugin.ts
+++ b/packages/dashboard-sdk/src/plugin.ts
@@ -7,13 +7,12 @@ import type { MercurConfig, BuiltMercurConfig } from "./types"
function buildConfig(config: MercurConfig, root: string): BuiltMercurConfig {
const srcDir = path.join(root, "src")
- const configPath = path.join(root, CONFIG_NAME)
return {
...config,
root,
srcDir,
- configPath,
+ configPath: path.resolve(root, CONFIG_NAME),
}
}
@@ -24,8 +23,7 @@ async function loadMercurConfig(root: string): Promise<BuiltMercurConfig> {
return buildConfig(mod.default, root)
} catch (error) {
throw new Error(
- `[@mercurjs/dashboard-sdk] Could not find config file "${CONFIG_NAME}" in ${root}. ` +
- `Please create a ${CONFIG_NAME} file in your project root.`
+ `[@mercurjs/dashboard-sdk] Could not find or load ${CONFIG_NAME} in ${root}`
)
}
}
diff --git a/packages/dashboard-sdk/src/types.ts b/packages/dashboard-sdk/src/types.ts
index 4477f6212..3a8427e38 100644
--- a/packages/dashboard-sdk/src/types.ts
+++ b/packages/dashboard-sdk/src/types.ts
@@ -5,6 +5,8 @@ export interface MercurConfig {
Sidebar?: string
},
baseUrl: string;
+ storefrontUrl?: string;
+ disableSellersRegistration?: boolean;
}
export interface BuiltMercurConfig extends MercurConfig {
diff --git a/packages/vendor/CLAUDE.md b/packages/vendor/CLAUDE.md
new file mode 100644
index 000000000..0d390046e
--- /dev/null
+++ b/packages/vendor/CLAUDE.md
@@ -0,0 +1,246 @@
+# Core Admin - File-Based Routing Guide
+
+## Quick Reference
+
+```
+src/pages/
+├── _layout.tsx # Root layout (ProtectedRoute)
+├── products/ # Main route: /products
+│ ├── index.tsx # List page (export Component)
+│ ├── [id]/ # Dynamic route: /products/:id
+│ │ ├── index.tsx # Detail page (export Component, loader, Breadcrumb)
+│ │ └── edit/ # Nested: /products/:id/edit
+│ ├── create/ # /products/create
+│ └── _components/ # Internal components (not routes)
+├── settings/ # Settings section: /settings/*
+│ ├── index.tsx # Settings landing page
+│ ├── regions/ # /settings/regions
+│ └── users/ # /settings/users
+└── login/ # Public route (no auth required)
+```
+
+## Page File Requirements
+
+Every page MUST export `Component`:
+
+```tsx
+// Minimal page
+export const Component = () => <div>Hello</div>
+
+// With loader (for data pre-fetching)
+export const loader = (queryClient: QueryClient) => async () => {
+ // Pre-fetch data
+ return queryClient.fetchQuery(...)
+}
+export const Component = () => { ... }
+
+// With breadcrumb (for dynamic routes like [id])
+export const Breadcrumb = (props: UIMatch<DataType>) => {
+ return <span>{props.data.name}</span>
+}
+export const Component = () => { ... }
+export { loader } from "./loader"
+```
+
+## Folder Conventions
+
+| Pattern | URL | Description |
+|---------|-----|-------------|
+| `products/index.tsx` | `/products` | List page |
+| `products/[id]/index.tsx` | `/products/:id` | Detail page (dynamic) |
+| `products/[id]/edit/index.tsx` | `/products/:id/edit` | Edit page |
+| `products/create/index.tsx` | `/products/create` | Create page |
+| `products/_components/` | - | Internal components (NOT routes) |
+| `products/common/` | - | Shared utilities (NOT routes) |
+| `settings/regions/` | `/settings/regions` | Settings sub-route |
+
+## Route Classification
+
+Routes are automatically classified:
+
+1. **Public routes** - `/login`, `/invite`, `/reset-password` → `PublicLayout`
+2. **Settings routes** - `/settings/*` → `SettingsLayout` (separate from main)
+3. **Main routes** - Everything else → `MainLayout` with sidebar
+
+## Creating a New Route
+
+### 1. Main Route (e.g., /vendors)
+
+```
+src/pages/vendors/
+├── index.tsx # List page
+├── [id]/
+│ ├── index.tsx # Detail page
+│ ├── edit/index.tsx # Edit modal/page
+│ ├── breadcrumb.tsx # Dynamic breadcrumb
+│ ├── loader.ts # Data loader
+│ └── _components/ # Page-specific components
+├── create/index.tsx # Create modal/page
+├── _components/ # Shared list components
+└── common/ # Shared hooks, utils, constants
+```
+
+### 2. Settings Route (e.g., /settings/api-keys)
+
+```
+src/pages/settings/api-keys/
+├── index.tsx # List page
+├── [id]/
+│ └── index.tsx # Detail/edit page
+├── create/index.tsx
+└── _components/
+```
+
+## Component Patterns
+
+### List Page Pattern
+
+```tsx
+// pages/vendors/index.tsx
+import { SingleColumnPage } from "@components/layout/pages"
+import { useExtension } from "@providers/extension-provider"
+import { VendorListTable } from "./_components/vendor-list-table"
+
+const VendorList = () => {
+ const { getWidgets } = useExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("vendor.list.before"),
+ after: getWidgets("vendor.list.after"),
+ }}
+ >
+ <VendorListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = VendorList
+```
+
+### Detail Page Pattern
+
+```tsx
+// pages/vendors/[id]/index.tsx
+import { useLoaderData, useParams } from "react-router-dom"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useVendor } from "@hooks/api/vendors"
+
+const VendorDetail = () => {
+ const initialData = useLoaderData()
+ const { id } = useParams()
+ const { vendor, isPending } = useVendor(id!, { initialData })
+
+ if (isPending || !vendor) {
+ return <SingleColumnPageSkeleton />
+ }
+
+ return (
+ <SingleColumnPage data={vendor} showJSON showMetadata>
+ <VendorGeneralSection vendor={vendor} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = VendorDetail
+export { vendorLoader as loader } from "./loader"
+export { VendorBreadcrumb as Breadcrumb } from "./breadcrumb"
+```
+
+### Breadcrumb Pattern
+
+```tsx
+// pages/vendors/[id]/breadcrumb.tsx
+import { UIMatch } from "react-router-dom"
+import { useVendor } from "@hooks/api/vendors"
+
+type Props = UIMatch<VendorResponse>
+
+export const VendorBreadcrumb = (props: Props) => {
+ const { id } = props.params || {}
+ const { vendor } = useVendor(id!, { initialData: props.data })
+
+ return <span>{vendor?.name}</span>
+}
+```
+
+### Loader Pattern
+
+```tsx
+// pages/vendors/[id]/loader.ts
+import { QueryClient } from "@tanstack/react-query"
+import { vendorQueryKeys } from "@hooks/api/vendors"
+import { sdk } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const vendorDetailQuery = (id: string) => ({
+ queryKey: vendorQueryKeys.detail(id),
+ queryFn: () => sdk.admin.vendor.retrieve(id),
+})
+
+export const vendorLoader = (client: QueryClient) => {
+ return async ({ params }: { params: { id: string } }) => {
+ const query = vendorDetailQuery(params.id)
+ return queryClient.getQueryData(query.queryKey) ??
+ (await client.fetchQuery(query))
+ }
+}
+```
+
+## Import Aliases
+
+Always use aliases, never relative imports outside the module:
+
+```tsx
+// Good
+import { Button } from "@components/ui/button"
+import { useVendor } from "@hooks/api/vendors"
+import { sdk } from "@lib/client"
+
+// Bad
+import { Button } from "../../../components/ui/button"
+```
+
+Available aliases:
+- `@components/` → `src/components/`
+- `@hooks/` → `src/hooks/`
+- `@lib/` → `src/lib/`
+- `@providers/` → `src/providers/`
+- `@pages/` → `src/pages/`
+
+## Modal Routes
+
+For create/edit modals that appear over the list:
+
+```tsx
+// pages/vendors/create/index.tsx
+import { RouteFocusModal } from "@components/modals"
+import { CreateVendorForm } from "./_components/create-vendor-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreateVendorForm />
+ </RouteFocusModal>
+ )
+}
+```
+
+## Drawer Routes
+
+For side panel edits:
+
+```tsx
+// pages/vendors/[id]/edit/index.tsx
+import { RouteDrawer } from "@components/modals"
+import { EditVendorForm } from "./_components/edit-vendor-form"
+
+export const Component = () => {
+ return (
+ <RouteDrawer>
+ <EditVendorForm />
+ </RouteDrawer>
+ )
+}
+```
diff --git a/packages/vendor/package.json b/packages/vendor/package.json
index 7bab59013..c7fbb3a91 100644
--- a/packages/vendor/package.json
+++ b/packages/vendor/package.json
@@ -28,6 +28,7 @@
"@dnd-kit/utilities": "^3.2.2",
"@hookform/error-message": "^2.0.1",
"@hookform/resolvers": "3.4.2",
+ "@medusajs/admin-shared": "^2.13.0",
"@medusajs/dashboard": "^2.13.0",
"@medusajs/icons": "2.13.1",
"@medusajs/ui": "4.1.1",
diff --git a/packages/vendor/src/app.tsx b/packages/vendor/src/app.tsx
index 93c1843ed..88fa7f604 100644
--- a/packages/vendor/src/app.tsx
+++ b/packages/vendor/src/app.tsx
@@ -1,4 +1,4 @@
-// import customRoutes from "virtual:mercur/routes";
+import customRoutes from "virtual:mercur/routes";
import { HelmetProvider } from "react-helmet-async";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "./providers";
@@ -6,21 +6,34 @@ import { I18nProvider, Toaster, TooltipProvider } from "@medusajs/ui";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { I18n } from "./components/utilities/i18n";
import { getRouteMap } from "./get-route-map";
+import { DashboardExtensionManager } from "./extensions";
+import { DashboardExtensionProvider } from "./extensions/dashboard-extension-provider";
const queryClient = new QueryClient();
+const extensionManager = new DashboardExtensionManager({
+ formModule: { customFields: {} } as any,
+ displayModule: { displays: {} } as any,
+ menuItemModule: { menuItems: [] },
+ widgetModule: { widgets: [] },
+});
+
export default function App() {
return (
<TooltipProvider>
<HelmetProvider>
<QueryClientProvider client={queryClient}>
- <ThemeProvider>
- <I18n />
- <I18nProvider>
- <RouterProvider router={createBrowserRouter(getRouteMap())} />
- </I18nProvider>
- <Toaster />
- </ThemeProvider>
+ <DashboardExtensionProvider api={extensionManager.api}>
+ <ThemeProvider>
+ <I18n />
+ <I18nProvider>
+ <RouterProvider
+ router={createBrowserRouter(getRouteMap(customRoutes))}
+ />
+ </I18nProvider>
+ <Toaster />
+ </ThemeProvider>
+ </DashboardExtensionProvider>
</QueryClientProvider>
</HelmetProvider>
</TooltipProvider>
diff --git a/packages/vendor/src/components/common/image-avatar/image-avatar.tsx b/packages/vendor/src/components/common/image-avatar/image-avatar.tsx
new file mode 100644
index 000000000..c436ba64b
--- /dev/null
+++ b/packages/vendor/src/components/common/image-avatar/image-avatar.tsx
@@ -0,0 +1,25 @@
+import { clx } from "@medusajs/ui"
+import imagesConverter from "../../../utils/images-conventer"
+
+export default function ImageAvatar({
+ src,
+ size = 6,
+ rounded = false,
+}: {
+ src: string
+ size?: number
+ rounded?: boolean
+}) {
+ const formattedSrc = imagesConverter(src)
+
+ return (
+ <img
+ src={formattedSrc}
+ alt="avatar"
+ className={clx(
+ `w-${size} h-${size} border rounded-md`,
+ rounded && "rounded-full"
+ )}
+ />
+ )
+}
diff --git a/packages/vendor/src/components/common/image-avatar/index.tsx b/packages/vendor/src/components/common/image-avatar/index.tsx
new file mode 100644
index 000000000..82b3388eb
--- /dev/null
+++ b/packages/vendor/src/components/common/image-avatar/index.tsx
@@ -0,0 +1 @@
+export { default as ImageAvatar } from "./image-avatar"
diff --git a/packages/vendor/src/components/common/logo-box/avatar-box.tsx b/packages/vendor/src/components/common/logo-box/avatar-box.tsx
index 2269ede1a..e66bf3756 100644
--- a/packages/vendor/src/components/common/logo-box/avatar-box.tsx
+++ b/packages/vendor/src/components/common/logo-box/avatar-box.tsx
@@ -50,37 +50,19 @@ export default function AvatarBox({ checked }: { checked?: boolean }) {
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
- <rect width="400" height="400" fill="#18181B" />
- <path
- d="M238.088 51.1218L238.089 51.1223L310.605 92.8101C334.028 106.308 348.526 131.32 347.868 157.953L347.867 157.966V157.978V241.688C347.867 268.68 333.687 293.362 310.271 306.856L310.269 306.858L237.754 348.878C214.336 362.374 185.643 362.374 162.225 348.878L89.7127 306.859C66.6206 293.361 52.1113 268.674 52.1113 241.688V157.978C52.1113 131.326 66.6211 106.307 89.7088 92.8093C89.7101 92.8085 89.7114 92.8078 89.7127 92.807L162.556 51.1233L162.559 51.1218C185.977 37.6261 214.67 37.6261 238.088 51.1218ZM124.634 200C124.634 241.576 158.502 275.372 200.156 275.372C242.142 275.372 276.013 241.578 276.013 200C276.013 158.419 241.805 124.628 200.156 124.628C158.502 124.628 124.634 158.424 124.634 200Z"
- fill="url(#paint0_linear_11869_12671)"
- stroke="url(#paint1_linear_11869_12671)"
- strokeWidth="2"
- />
- <defs>
- <linearGradient
- id="paint0_linear_11869_12671"
- x1="200"
- y1="40"
- x2="200"
- y2="360"
- gradientUnits="userSpaceOnUse"
- >
- <stop stopColor="white" />
- <stop offset="1" stopColor="white" stopOpacity="0.7" />
- </linearGradient>
- <linearGradient
- id="paint1_linear_11869_12671"
- x1="200"
- y1="40"
- x2="200"
- y2="360"
- gradientUnits="userSpaceOnUse"
- >
- <stop stopColor="white" stopOpacity="0" />
- <stop offset="1" stopColor="white" stopOpacity="0.7" />
- </linearGradient>
- </defs>
+ <rect width="400" height="400" rx="40" fill="#18181B" />
+ <text
+ x="200"
+ y="200"
+ textAnchor="middle"
+ dominantBaseline="central"
+ fill="white"
+ fontSize="200"
+ fontWeight="bold"
+ fontFamily="Inter, system-ui, sans-serif"
+ >
+ M
+ </text>
</svg>
</IconAvatar>
)
diff --git a/packages/vendor/src/components/common/logo-box/logo-box.tsx b/packages/vendor/src/components/common/logo-box/logo-box.tsx
index 9df3cc542..716783d9b 100644
--- a/packages/vendor/src/components/common/logo-box/logo-box.tsx
+++ b/packages/vendor/src/components/common/logo-box/logo-box.tsx
@@ -64,10 +64,18 @@ export const LogoBox = ({
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
- <path
- d="M30.85 6.16832L22.2453 1.21782C19.4299 -0.405941 15.9801 -0.405941 13.1648 1.21782L4.52043 6.16832C1.74473 7.79208 0 10.802 0 14.0099V23.9505C0 27.198 1.74473 30.1683 4.52043 31.7921L13.1251 36.7822C15.9405 38.4059 19.3903 38.4059 22.2056 36.7822L30.8103 31.7921C33.6257 30.1683 35.3307 27.198 35.3307 23.9505V14.0099C35.41 10.802 33.6653 7.79208 30.85 6.16832ZM17.6852 27.8317C12.8079 27.8317 8.8426 23.8713 8.8426 19C8.8426 14.1287 12.8079 10.1683 17.6852 10.1683C22.5625 10.1683 26.5674 14.1287 26.5674 19C26.5674 23.8713 22.6022 27.8317 17.6852 27.8317Z"
- className="fill-ui-button-inverted relative drop-shadow-sm"
- />
+ <text
+ x="18"
+ y="19"
+ textAnchor="middle"
+ dominantBaseline="central"
+ fontSize="24"
+ fontWeight="bold"
+ fontFamily="Inter, system-ui, sans-serif"
+ className="fill-ui-button-inverted"
+ >
+ M
+ </text>
</svg>
</div>
)
diff --git a/packages/vendor/src/extensions/dashboard-extension-manager/dashboard-extension-manager.tsx b/packages/vendor/src/extensions/dashboard-extension-manager/dashboard-extension-manager.tsx
new file mode 100644
index 000000000..8302778b7
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-manager/dashboard-extension-manager.tsx
@@ -0,0 +1,350 @@
+import {
+ CustomFieldContainerZone,
+ CustomFieldFormTab,
+ CustomFieldFormZone,
+ CustomFieldModel,
+ InjectionZone,
+ NESTED_ROUTE_POSITIONS,
+} from "@medusajs/admin-shared"
+import * as React from "react"
+import { INavItem } from "../../components/layout/nav-item"
+import {
+ ConfigExtension,
+ ConfigField,
+ ConfigFieldMap,
+ DisplayExtension,
+ DisplayMap,
+ DisplayModule,
+ FormExtension,
+ FormField,
+ FormFieldExtension,
+ FormFieldMap,
+ FormModule,
+ FormZoneMap,
+ MenuItemExtension,
+ MenuItemKey,
+ MenuItemModule,
+ WidgetExtension,
+ WidgetModule,
+ ZoneStructure,
+} from "../types"
+
+export type DashboardExtensionManagerProps = {
+ formModule: FormModule
+ displayModule: DisplayModule
+ menuItemModule: MenuItemModule
+ widgetModule: WidgetModule
+}
+
+export class DashboardExtensionManager {
+ private widgets: Map<InjectionZone, React.ComponentType[]>
+ private menus: Map<MenuItemKey, INavItem[]>
+ private fields: FormFieldMap
+ private configs: ConfigFieldMap
+ private displays: DisplayMap
+
+ constructor({
+ widgetModule,
+ menuItemModule,
+ displayModule,
+ formModule,
+ }: DashboardExtensionManagerProps) {
+ this.widgets = this.populateWidgets(widgetModule.widgets)
+ this.menus = this.populateMenus(menuItemModule.menuItems)
+
+ const { fields, configs } = this.populateForm(formModule)
+ this.fields = fields
+ this.configs = configs
+ this.displays = this.populateDisplays(displayModule)
+ }
+
+ private populateWidgets(widgets: WidgetExtension[] | undefined) {
+ const registry = new Map<InjectionZone, React.ComponentType[]>()
+
+ if (!widgets) {
+ return registry
+ }
+
+ widgets.forEach((widget) => {
+ widget.zone.forEach((zone) => {
+ if (!registry.has(zone)) {
+ registry.set(zone, [])
+ }
+ registry.get(zone)!.push(widget.Component)
+ })
+ })
+
+ return registry
+ }
+
+ private populateMenus(menuItems: MenuItemExtension[] | undefined) {
+ const registry = new Map<MenuItemKey, INavItem[]>()
+ const tempRegistry: Record<string, INavItem> = {}
+
+ if (!menuItems) {
+ return registry
+ }
+
+ menuItems.sort((a, b) => a.path.length - b.path.length)
+
+ menuItems.forEach((item) => {
+ if (item.path.includes("/:")) {
+ if (process.env.NODE_ENV === "development") {
+ console.warn(
+ `[@medusajs/dashboard] Menu item for path "${item.path}" can't be added to the sidebar as it contains a parameter.`
+ )
+ }
+ return
+ }
+
+ const isSettingsPath = item.path.startsWith("/settings")
+ const key = isSettingsPath ? "settingsExtensions" : "coreExtensions"
+
+ const pathParts = item.path.split("/").filter(Boolean)
+ const parentPath = "/" + pathParts.slice(0, -1).join("/")
+
+ // Check if this is a nested settings path
+ if (isSettingsPath && pathParts.length > 2) {
+ if (process.env.NODE_ENV === "development") {
+ console.warn(
+ `[@medusajs/dashboard] Nested settings menu item "${item.path}" can't be added to the sidebar. Only top-level settings items are allowed.`
+ )
+ }
+ return // Skip this item entirely
+ }
+
+ // Find the parent item if it exists
+ const parentItem = menuItems.find(
+ (menuItem) => menuItem.path === parentPath
+ )
+
+ // Check if parent item is a nested route under existing route
+ if (
+ parentItem?.nested &&
+ NESTED_ROUTE_POSITIONS.includes(parentItem?.nested) &&
+ pathParts.length > 1
+ ) {
+ if (process.env.NODE_ENV === "development") {
+ console.warn(
+ `[@medusajs/dashboard] Nested menu item "${item.path}" can't be added to the sidebar as it is nested under "${parentItem.nested}".`
+ )
+ }
+ return
+ }
+
+ const navItem: INavItem = {
+ label: item.label,
+ to: item.path,
+ icon: item.icon ? <item.icon /> : undefined,
+ items: [],
+ nested: item.nested,
+ }
+
+ if (parentPath !== "/" && tempRegistry[parentPath]) {
+ if (!tempRegistry[parentPath].items) {
+ tempRegistry[parentPath].items = []
+ }
+ tempRegistry[parentPath].items!.push(navItem)
+ } else {
+ if (!registry.has(key)) {
+ registry.set(key, [])
+ }
+ registry.get(key)!.push(navItem)
+ }
+
+ tempRegistry[item.path] = navItem
+ })
+
+ return registry
+ }
+
+ private populateForm(formModule: FormModule): {
+ fields: FormFieldMap
+ configs: ConfigFieldMap
+ } {
+ const fields: FormFieldMap = new Map()
+ const configs: ConfigFieldMap = new Map()
+
+ Object.entries(formModule.customFields).forEach(
+ ([model, customization]) => {
+ fields.set(
+ model as CustomFieldModel,
+ this.processFields(customization.forms)
+ )
+ configs.set(
+ model as CustomFieldModel,
+ this.processConfigs(customization.configs)
+ )
+ }
+ )
+
+ return { fields, configs }
+ }
+
+ private processFields(forms: FormExtension[]): FormZoneMap {
+ const formZoneMap: FormZoneMap = new Map()
+
+ forms.forEach((fieldDef) =>
+ this.processFieldDefinition(formZoneMap, fieldDef)
+ )
+
+ return formZoneMap
+ }
+
+ private processConfigs(
+ configs: ConfigExtension[]
+ ): Map<CustomFieldFormZone, ConfigField[]> {
+ const modelConfigMap = new Map<CustomFieldFormZone, ConfigField[]>()
+
+ configs.forEach((configDef) => {
+ const { zone, fields } = configDef
+ const zoneConfigs: ConfigField[] = []
+
+ Object.entries(fields).forEach(([name, config]) => {
+ zoneConfigs.push({
+ name,
+ defaultValue: config.defaultValue,
+ validation: config.validation,
+ })
+ })
+
+ modelConfigMap.set(zone, zoneConfigs)
+ })
+
+ return modelConfigMap
+ }
+
+ private processFieldDefinition(
+ formZoneMap: FormZoneMap,
+ fieldDef: FormExtension
+ ) {
+ const { zone, tab, fields: fieldsDefinition } = fieldDef
+ const zoneStructure = this.getOrCreateZoneStructure(formZoneMap, zone)
+
+ Object.entries(fieldsDefinition).forEach(([fieldKey, fieldDefinition]) => {
+ const formField = this.createFormField(fieldKey, fieldDefinition)
+ this.addFormFieldToZoneStructure(zoneStructure, formField, tab)
+ })
+ }
+
+ private getOrCreateZoneStructure(
+ formZoneMap: FormZoneMap,
+ zone: CustomFieldFormZone
+ ): ZoneStructure {
+ let zoneStructure = formZoneMap.get(zone)
+ if (!zoneStructure) {
+ zoneStructure = { components: [], tabs: new Map() }
+ formZoneMap.set(zone, zoneStructure)
+ }
+ return zoneStructure
+ }
+
+ private createFormField(
+ fieldKey: string,
+ fieldDefinition: FormFieldExtension
+ ): FormField {
+ return {
+ name: fieldKey,
+ validation: fieldDefinition.validation,
+ label: fieldDefinition.label,
+ description: fieldDefinition.description,
+ Component: fieldDefinition.Component,
+ }
+ }
+
+ private addFormFieldToZoneStructure(
+ zoneStructure: ZoneStructure,
+ formField: FormField,
+ tab?: CustomFieldFormTab
+ ) {
+ if (tab) {
+ let tabFields = zoneStructure.tabs.get(tab)
+ if (!tabFields) {
+ tabFields = []
+ zoneStructure.tabs.set(tab, tabFields)
+ }
+ tabFields.push(formField)
+ } else {
+ zoneStructure.components.push(formField)
+ }
+ }
+
+ private populateDisplays(displayModule: DisplayModule): DisplayMap {
+ const displays = new Map<
+ CustomFieldModel,
+ Map<CustomFieldContainerZone, React.ComponentType<{ data: any }>[]>
+ >()
+
+ Object.entries(displayModule.displays).forEach(([model, customization]) => {
+ displays.set(
+ model as CustomFieldModel,
+ this.processDisplays(customization)
+ )
+ })
+
+ return displays
+ }
+
+ private processDisplays(
+ displays: DisplayExtension[]
+ ): Map<CustomFieldContainerZone, React.ComponentType<{ data: any }>[]> {
+ const modelDisplayMap = new Map<
+ CustomFieldContainerZone,
+ React.ComponentType<{ data: any }>[]
+ >()
+
+ displays.forEach((display) => {
+ const { zone, Component } = display
+ if (!modelDisplayMap.has(zone)) {
+ modelDisplayMap.set(zone, [])
+ }
+ modelDisplayMap.get(zone)!.push(Component)
+ })
+
+ return modelDisplayMap
+ }
+
+ private getMenu(path: MenuItemKey) {
+ return this.menus.get(path) || []
+ }
+
+ private getWidgets(zone: InjectionZone) {
+ return this.widgets.get(zone) || []
+ }
+
+ private getFormFields(
+ model: CustomFieldModel,
+ zone: CustomFieldFormZone,
+ tab?: CustomFieldFormTab
+ ) {
+ const zoneMap = this.fields.get(model)?.get(zone)
+
+ if (!zoneMap) {
+ return []
+ }
+
+ if (tab) {
+ return zoneMap.tabs.get(tab) || []
+ }
+
+ return zoneMap.components
+ }
+
+ private getFormConfigs(model: CustomFieldModel, zone: CustomFieldFormZone) {
+ return this.configs.get(model)?.get(zone) || []
+ }
+
+ private getDisplays(model: CustomFieldModel, zone: CustomFieldContainerZone) {
+ return this.displays.get(model)?.get(zone) || []
+ }
+
+ get api() {
+ return {
+ getMenu: this.getMenu.bind(this),
+ getWidgets: this.getWidgets.bind(this),
+ getFormFields: this.getFormFields.bind(this),
+ getFormConfigs: this.getFormConfigs.bind(this),
+ getDisplays: this.getDisplays.bind(this),
+ }
+ }
+}
diff --git a/packages/vendor/src/extensions/dashboard-extension-manager/index.ts b/packages/vendor/src/extensions/dashboard-extension-manager/index.ts
new file mode 100644
index 000000000..a5f2aa4a6
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-manager/index.ts
@@ -0,0 +1 @@
+export * from "./dashboard-extension-manager"
diff --git a/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-context.tsx b/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-context.tsx
new file mode 100644
index 000000000..f3afbf057
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-context.tsx
@@ -0,0 +1,7 @@
+import { createContext } from "react"
+import { DashboardExtensionManager } from "../dashboard-extension-manager"
+
+type DasboardExtenstionContextValue = DashboardExtensionManager["api"]
+
+export const DashboardExtensionContext =
+ createContext<DasboardExtenstionContextValue | null>(null)
diff --git a/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-provider.tsx b/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-provider.tsx
new file mode 100644
index 000000000..4efcb5378
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-provider/dashboard-extension-provider.tsx
@@ -0,0 +1,18 @@
+import { PropsWithChildren } from "react"
+import { DashboardExtensionManager } from "../dashboard-extension-manager/dashboard-extension-manager"
+import { DashboardExtensionContext } from "./dashboard-extension-context"
+
+type DashboardExtensionProviderProps = PropsWithChildren<{
+ api: DashboardExtensionManager["api"]
+}>
+
+export const DashboardExtensionProvider = ({
+ api,
+ children,
+}: DashboardExtensionProviderProps) => {
+ return (
+ <DashboardExtensionContext.Provider value={api}>
+ {children}
+ </DashboardExtensionContext.Provider>
+ )
+}
diff --git a/packages/vendor/src/extensions/dashboard-extension-provider/index.ts b/packages/vendor/src/extensions/dashboard-extension-provider/index.ts
new file mode 100644
index 000000000..be9ca07a3
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-provider/index.ts
@@ -0,0 +1,2 @@
+export { DashboardExtensionProvider } from "./dashboard-extension-provider"
+export { useDashboardExtension } from "./use-dashboard-extension"
diff --git a/packages/vendor/src/extensions/dashboard-extension-provider/use-dashboard-extension.tsx b/packages/vendor/src/extensions/dashboard-extension-provider/use-dashboard-extension.tsx
new file mode 100644
index 000000000..0c0a93718
--- /dev/null
+++ b/packages/vendor/src/extensions/dashboard-extension-provider/use-dashboard-extension.tsx
@@ -0,0 +1,12 @@
+import { useContext } from "react"
+import { DashboardExtensionContext } from "./dashboard-extension-context"
+
+export const useDashboardExtension = () => {
+ const context = useContext(DashboardExtensionContext)
+ if (!context) {
+ throw new Error(
+ "useDashboardExtension must be used within a DashboardExtensionProvider"
+ )
+ }
+ return context
+}
diff --git a/packages/vendor/src/extensions/forms/form-extension-zone/form-extension-zone.tsx b/packages/vendor/src/extensions/forms/form-extension-zone/form-extension-zone.tsx
new file mode 100644
index 000000000..d230a840b
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/form-extension-zone/form-extension-zone.tsx
@@ -0,0 +1,128 @@
+import { InlineTip, Input, Switch } from "@medusajs/ui"
+import { ComponentType } from "react"
+import { ControllerRenderProps, FieldPath, FieldValues, UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { Form } from "../../../components/common/form"
+import { FormField } from "../../types"
+import { FormFieldType } from "./types"
+import { getFieldType } from "./utils"
+
+type FormExtensionZoneProps<TFieldValues extends FieldValues = FieldValues> = {
+ fields: FormField[]
+ form: UseFormReturn<TFieldValues>
+}
+
+export const FormExtensionZone = <TFieldValues extends FieldValues = FieldValues>({
+ fields,
+ form
+}: FormExtensionZoneProps<TFieldValues>) => {
+ return (
+ <div>
+ {fields.map((field, index) => (
+ <FormExtensionField key={index} field={field} form={form} />
+ ))}
+ </div>
+ )
+}
+
+function getFieldLabel(field: FormField) {
+ if (field.label) {
+ return field.label
+ }
+
+ return field.name
+ .split("_")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ")
+}
+
+type FormExtensionFieldProps<TFieldValues extends FieldValues = FieldValues> = {
+ field: FormField
+ form: UseFormReturn<TFieldValues>
+}
+
+const FormExtensionField = <TFieldValues extends FieldValues = FieldValues>({
+ field,
+ form
+}: FormExtensionFieldProps<TFieldValues>) => {
+ const label = getFieldLabel(field)
+ const description = field.description
+ const placeholder = field.placeholder
+ const Component = field.Component
+
+ const type = getFieldType(field.validation)
+
+ const { control } = form
+
+ return (
+ <Form.Field
+ control={control}
+ name={`additional_data.${field.name}` as FieldPath<TFieldValues>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{label}</Form.Label>
+ {description && <Form.Hint>{description}</Form.Hint>}
+ <Form.Control>
+ <FormExtensionFieldComponent
+ field={field}
+ type={type}
+ component={Component}
+ placeholder={placeholder}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ )
+}
+
+type FormExtensionFieldComponentProps<
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
+> = {
+ field: ControllerRenderProps<TFieldValues, TName>
+ type: FormFieldType
+ component?: ComponentType<ControllerRenderProps<TFieldValues, TName> & { placeholder?: string }>
+ placeholder?: string
+}
+
+const FormExtensionFieldComponent = <
+ TFieldValues extends FieldValues = FieldValues,
+ TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
+>({
+ field,
+ type,
+ component,
+ placeholder,
+}: FormExtensionFieldComponentProps<TFieldValues, TName>) => {
+ const { t } = useTranslation()
+
+ if (component) {
+ const Component = component
+
+ return <Component {...field} placeholder={placeholder} />
+ }
+
+ switch (type) {
+ case "text": {
+ return <Input {...field} placeholder={placeholder} />
+ }
+ case "number": {
+ return <Input {...field} placeholder={placeholder} type="number" />
+ }
+ case "boolean": {
+ return <Switch {...field} />
+ }
+ default: {
+ return (
+ <InlineTip variant="warning" label={t("general.warning")}>
+ The field type does not support rendering a fallback component. Please
+ provide a component prop.
+ </InlineTip>
+ )
+ }
+ }
+}
diff --git a/packages/vendor/src/extensions/forms/form-extension-zone/index.ts b/packages/vendor/src/extensions/forms/form-extension-zone/index.ts
new file mode 100644
index 000000000..5eb18f330
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/form-extension-zone/index.ts
@@ -0,0 +1 @@
+export * from "./form-extension-zone"
diff --git a/packages/vendor/src/extensions/forms/form-extension-zone/types.ts b/packages/vendor/src/extensions/forms/form-extension-zone/types.ts
new file mode 100644
index 000000000..44ce13491
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/form-extension-zone/types.ts
@@ -0,0 +1 @@
+export type FormFieldType = "text" | "number" | "boolean" | "unsupported"
diff --git a/packages/vendor/src/extensions/forms/form-extension-zone/utils.ts b/packages/vendor/src/extensions/forms/form-extension-zone/utils.ts
new file mode 100644
index 000000000..5bfb6f5cc
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/form-extension-zone/utils.ts
@@ -0,0 +1,66 @@
+import {
+ ZodBoolean,
+ ZodEffects,
+ ZodNull,
+ ZodNullable,
+ ZodNumber,
+ ZodOptional,
+ ZodString,
+ ZodType,
+ ZodUndefined,
+} from "zod"
+import { FormFieldType } from "./types"
+
+export function getFieldLabel(name: string, label?: string) {
+ if (label) {
+ return label
+ }
+
+ return name
+ .split("_")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ")
+}
+
+export function getFieldType(type: ZodType): FormFieldType {
+ if (type instanceof ZodString) {
+ return "text"
+ }
+
+ if (type instanceof ZodNumber) {
+ return "number"
+ }
+
+ if (type instanceof ZodBoolean) {
+ return "boolean"
+ }
+
+ if (type instanceof ZodNullable) {
+ const innerType = type.unwrap()
+
+ return getFieldType(innerType)
+ }
+
+ if (type instanceof ZodOptional) {
+ const innerType = type.unwrap()
+
+ return getFieldType(innerType)
+ }
+
+ if (type instanceof ZodEffects) {
+ const innerType = type.innerType()
+
+ return getFieldType(innerType)
+ }
+
+ return "unsupported"
+}
+
+export function getIsFieldOptional(type: ZodType) {
+ return (
+ type instanceof ZodOptional ||
+ type instanceof ZodNull ||
+ type instanceof ZodUndefined ||
+ type instanceof ZodNullable
+ )
+}
diff --git a/packages/vendor/src/extensions/forms/hooks.tsx b/packages/vendor/src/extensions/forms/hooks.tsx
new file mode 100644
index 000000000..0abef39d2
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/hooks.tsx
@@ -0,0 +1,92 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { FieldValues, useForm, UseFormProps } from "react-hook-form"
+import { z, ZodEffects, ZodObject } from "zod"
+
+import { ConfigField } from "../types"
+
+interface UseExtendableFormProps<
+ TSchema extends ZodObject<any> | ZodEffects<ZodObject<any>>,
+ TContext = any,
+ TData = any,
+> extends Omit<UseFormProps<z.infer<TSchema>, TContext>, "resolver"> {
+ schema: TSchema
+ configs: ConfigField[]
+ data?: TData
+}
+
+function createAdditionalDataSchema(configs: ConfigField[]) {
+ return configs.reduce(
+ (acc, config) => {
+ acc[config.name] = config.validation
+ return acc
+ },
+ {} as Record<string, z.ZodTypeAny>
+ )
+}
+
+function createExtendedSchema<
+ TSchema extends ZodObject<any> | ZodEffects<ZodObject<any>>,
+>(baseSchema: TSchema, additionalDataSchema: Record<string, z.ZodTypeAny>) {
+ const extendedObjectSchema = z.object({
+ ...(baseSchema instanceof ZodEffects
+ ? baseSchema.innerType().shape
+ : baseSchema.shape),
+ additional_data: z.object(additionalDataSchema).optional(),
+ })
+
+ return baseSchema instanceof ZodEffects
+ ? baseSchema
+ .superRefine((data, ctx) => {
+ const result = extendedObjectSchema.safeParse(data)
+ if (!result.success) {
+ result.error.issues.forEach((issue) => ctx.addIssue(issue))
+ }
+ })
+ .and(extendedObjectSchema)
+ : extendedObjectSchema
+}
+
+function createExtendedDefaultValues<TData>(
+ baseDefaultValues: any,
+ configs: ConfigField[],
+ data?: TData
+) {
+ const additional_data = configs.reduce(
+ (acc, config) => {
+ const { name, defaultValue } = config
+
+ acc[name] =
+ typeof defaultValue === "function" ? defaultValue(data) : defaultValue
+ return acc
+ },
+ {} as Record<string, any>
+ )
+
+ return Object.assign(baseDefaultValues, { additional_data })
+}
+
+export const useExtendableForm = <
+ TSchema extends ZodObject<any> | ZodEffects<ZodObject<any>>,
+ TContext = any,
+ TTransformedValues extends FieldValues | undefined = undefined,
+>({
+ defaultValues: baseDefaultValues,
+ schema: baseSchema,
+ configs,
+ data,
+ ...props
+}: UseExtendableFormProps<TSchema, TContext>) => {
+ const additionalDataSchema = createAdditionalDataSchema(configs)
+ const schema = createExtendedSchema(baseSchema, additionalDataSchema)
+ const defaultValues = createExtendedDefaultValues(
+ baseDefaultValues,
+ configs,
+ data
+ )
+
+ return useForm<z.infer<TSchema>, TContext, TTransformedValues>({
+ ...props,
+ defaultValues,
+ resolver: zodResolver(schema),
+ })
+}
diff --git a/packages/vendor/src/extensions/forms/index.ts b/packages/vendor/src/extensions/forms/index.ts
new file mode 100644
index 000000000..f8b577c7f
--- /dev/null
+++ b/packages/vendor/src/extensions/forms/index.ts
@@ -0,0 +1,2 @@
+export * from "./form-extension-zone"
+export * from "./hooks"
diff --git a/packages/vendor/src/extensions/index.ts b/packages/vendor/src/extensions/index.ts
new file mode 100644
index 000000000..9fc175d2d
--- /dev/null
+++ b/packages/vendor/src/extensions/index.ts
@@ -0,0 +1,12 @@
+export * from "./dashboard-extension-manager"
+export * from "./dashboard-extension-provider"
+export * from "./forms"
+export * from "./routes/utils"
+
+export {
+ type DisplayModule,
+ type FormModule,
+ type MenuItemModule,
+ type RouteModule,
+ type WidgetModule,
+} from "./types"
diff --git a/packages/vendor/src/extensions/routes/utils.ts b/packages/vendor/src/extensions/routes/utils.ts
new file mode 100644
index 000000000..af2eb1aa6
--- /dev/null
+++ b/packages/vendor/src/extensions/routes/utils.ts
@@ -0,0 +1,197 @@
+import { ComponentType } from "react"
+import { LoaderFunction, RouteObject } from "react-router-dom"
+import { ErrorBoundary } from "../../components/utilities/error-boundary"
+import { RouteExtension, RouteModule } from "../types"
+
+/**
+ * Used to test if a route is a settings route.
+ */
+const settingsRouteRegex = /^\/settings\//
+
+export const getRouteExtensions = (
+ module: RouteModule,
+ type: "settings" | "core"
+) => {
+ return module.routes.filter((route) => {
+ if (type === "settings") {
+ return settingsRouteRegex.test(route.path)
+ }
+
+ return !settingsRouteRegex.test(route.path)
+ })
+}
+
+/**
+ * Creates a route object for a branch node in the route tree
+ * @param segment - The path segment for this branch
+ */
+const createBranchRoute = (segment: string): RouteObject => ({
+ path: segment,
+ children: [],
+})
+
+/**
+ * Creates a route object for a leaf node with its component
+ * @param Component - The React component to render at this route
+ */
+const createLeafRoute = (
+ Component: ComponentType,
+ loader?: LoaderFunction,
+ handle?: object
+): RouteObject => ({
+ path: "",
+ ErrorBoundary: ErrorBoundary,
+ async lazy() {
+ const result: {
+ Component: ComponentType
+ loader?: LoaderFunction
+ handle?: object
+ } = { Component }
+
+ if (loader) {
+ result.loader = loader
+ }
+
+ if (handle) {
+ result.handle = handle
+ }
+
+ return result
+ },
+})
+
+/**
+ * Creates a parallel route configuration
+ * @param path - The route path
+ * @param Component - The React component to render
+ */
+const createParallelRoute = (
+ path: string,
+ Component: ComponentType,
+ loader?: LoaderFunction,
+ handle?: object
+) => ({
+ path,
+ async lazy() {
+ const result: {
+ Component: ComponentType
+ loader?: LoaderFunction
+ handle?: object
+ } = { Component }
+
+ if (loader) {
+ result.loader = loader
+ }
+
+ if (handle) {
+ result.handle = handle
+ }
+
+ return result
+ },
+})
+
+/**
+ * Processes parallel routes by cleaning their paths relative to the current path
+ * @param parallelRoutes - Array of parallel route extensions
+ * @param currentFullPath - The full path of the current route
+ */
+const processParallelRoutes = (
+ parallelRoutes: RouteExtension[] | undefined,
+ currentFullPath: string
+): RouteObject[] | undefined => {
+ return parallelRoutes
+ ?.map(({ path, Component, loader, handle }) => {
+ const childPath = path?.replace(currentFullPath, "").replace(/^\/+/, "")
+ if (!childPath) {
+ return null
+ }
+ return createParallelRoute(childPath, Component, loader, handle)
+ })
+ .filter(Boolean) as RouteObject[]
+}
+
+/**
+ * Recursively builds the route tree by adding routes at the correct level
+ * @param pathSegments - Array of remaining path segments to process
+ * @param Component - The React component for the route
+ * @param currentLevel - Current level in the route tree
+ * @param parallelRoutes - Optional parallel routes to add
+ * @param fullPath - The full path up to the current level
+ */
+const addRoute = (
+ pathSegments: string[],
+ Component: ComponentType,
+ currentLevel: RouteObject[],
+ loader?: LoaderFunction,
+ handle?: object,
+ parallelRoutes?: RouteExtension[],
+ fullPath?: string
+) => {
+ if (!pathSegments.length) {
+ return
+ }
+
+ const [currentSegment, ...remainingSegments] = pathSegments
+ let route = currentLevel.find((r) => r.path === currentSegment)
+
+ if (!route) {
+ route = createBranchRoute(currentSegment)
+ currentLevel.push(route)
+ }
+
+ const currentFullPath = fullPath
+ ? `${fullPath}/${currentSegment}`
+ : currentSegment
+
+ if (remainingSegments.length === 0) {
+ route.children ||= []
+ const leaf = createLeafRoute(Component, loader)
+
+ /**
+ * The handle needs to be set on the wrapper route object,
+ * in order for it to be resolved correctly thoughout
+ * the branch.
+ */
+ if (handle) {
+ route.handle = handle
+ }
+
+ leaf.children = processParallelRoutes(parallelRoutes, currentFullPath)
+ route.children.push(leaf)
+ } else {
+ route.children ||= []
+ addRoute(
+ remainingSegments,
+ Component,
+ route.children,
+ loader,
+ handle,
+ parallelRoutes,
+ currentFullPath
+ )
+ }
+}
+
+/**
+ * Creates a complete route map from route extensions
+ * @param routes - Array of route extensions to process
+ * @param ignore - Optional path prefix to ignore when processing routes
+ * @returns An array of route objects forming a route tree
+ */
+export const createRouteMap = (
+ routes: RouteExtension[],
+ ignore?: string
+): RouteObject[] => {
+ const root: RouteObject[] = []
+
+ routes.forEach(({ path, Component, loader, handle, children }) => {
+ const cleanedPath = ignore
+ ? path.replace(ignore, "").replace(/^\/+/, "")
+ : path.replace(/^\/+/, "")
+ const pathSegments = cleanedPath.split("/").filter(Boolean)
+ addRoute(pathSegments, Component, root, loader, handle, children)
+ })
+
+ return root
+}
diff --git a/packages/vendor/src/extensions/types.ts b/packages/vendor/src/extensions/types.ts
new file mode 100644
index 000000000..4d42070d6
--- /dev/null
+++ b/packages/vendor/src/extensions/types.ts
@@ -0,0 +1,121 @@
+import {
+ CustomFieldContainerZone,
+ CustomFieldFormTab,
+ CustomFieldFormZone,
+ CustomFieldModel,
+ InjectionZone,
+ NestedRoutePosition,
+} from "@medusajs/admin-shared"
+import { ComponentType } from "react"
+import { LoaderFunction } from "react-router-dom"
+import { ZodFirstPartySchemaTypes } from "zod"
+
+export type RouteExtension = {
+ Component: ComponentType
+ loader?: LoaderFunction
+ handle?: object
+ children?: RouteExtension[]
+ path: string
+}
+
+export type MenuItemExtension = {
+ label: string
+ path: string
+ icon?: ComponentType
+ nested?: NestedRoutePosition
+}
+
+export type WidgetExtension = {
+ Component: ComponentType
+ zone: InjectionZone[]
+}
+
+export type DisplayExtension = {
+ Component: ComponentType<{ data: any }>
+ zone: CustomFieldContainerZone
+}
+
+export type FormFieldExtension = {
+ validation: ZodFirstPartySchemaTypes
+ Component?: ComponentType<any>
+ label?: string
+ description?: string
+ placeholder?: string
+}
+
+export type FormExtension = {
+ zone: CustomFieldFormZone
+ tab?: CustomFieldFormTab
+ fields: Record<string, FormFieldExtension>
+}
+
+export type ConfigFieldExtension = {
+ defaultValue: ((data: any) => any) | any
+ validation: ZodFirstPartySchemaTypes
+}
+
+export type ConfigExtension = {
+ zone: CustomFieldFormZone
+ fields: Record<string, ConfigFieldExtension>
+}
+
+export type LinkModule = {
+ links: Record<CustomFieldModel, (string | string[])[]>
+}
+
+export type DisplayModule = {
+ displays: Record<CustomFieldModel, DisplayExtension[]>
+}
+
+export type FormModule = {
+ customFields: Record<
+ CustomFieldModel,
+ {
+ forms: FormExtension[]
+ configs: ConfigExtension[]
+ }
+ >
+}
+
+export type WidgetModule = {
+ widgets: WidgetExtension[]
+}
+
+export type RouteModule = {
+ routes: RouteExtension[]
+}
+
+export type MenuItemModule = {
+ menuItems: MenuItemExtension[]
+}
+
+export type MenuItemKey = "coreExtensions" | "settingsExtensions"
+
+export type FormField = FormFieldExtension & {
+ name: string
+}
+
+export type TabFieldMap = Map<CustomFieldFormTab, FormField[]>
+
+export type ZoneStructure = {
+ components: FormField[]
+ tabs: TabFieldMap
+}
+
+export type FormZoneMap = Map<CustomFieldFormZone, ZoneStructure>
+
+export type FormFieldMap = Map<CustomFieldModel, FormZoneMap>
+
+export type ConfigField = ConfigFieldExtension & {
+ name: string
+}
+
+export type ConfigFieldMap = Map<
+ CustomFieldModel,
+ Map<CustomFieldFormZone, ConfigField[]>
+>
+
+export type DisplayMap = Map<
+ CustomFieldModel,
+ Map<CustomFieldContainerZone, React.ComponentType<{ data: any }>[]>
+>
diff --git a/packages/vendor/src/get-route-map.tsx b/packages/vendor/src/get-route-map.tsx
index 04de757fa..542f179d9 100644
--- a/packages/vendor/src/get-route-map.tsx
+++ b/packages/vendor/src/get-route-map.tsx
@@ -1,3 +1,4 @@
+import { ComponentType } from "react";
import { HttpTypes } from "@medusajs/types";
import { t } from "i18next";
import { Outlet, RouteObject, UIMatch } from "react-router-dom";
@@ -6,11 +7,85 @@ import { MainLayout } from "./components/layout/main-layout";
import { PublicLayout } from "./components/layout/public-layout";
import { SettingsLayout } from "./components/layout/settings-layout";
import { ErrorBoundary } from "./components/utilities/error-boundary";
-import { TaxRegionDetailBreadcrumb } from "./routes/tax-regions/tax-region-detail/breadcrumb";
-import { taxRegionLoader } from "./routes/tax-regions/tax-region-detail/loader";
-export function getRouteMap() {
+export type CustomRoute = {
+ Component: ComponentType;
+ path: string;
+ handle?: unknown;
+ loader?: unknown;
+};
+
+function normalizePath(p: string): string {
+ return ("/" + p).replace(/\/+/g, "/").replace(/\/$/, "") || "/";
+}
+
+function applyOverrides(
+ routes: RouteObject[],
+ overrides: Map<string, CustomRoute>,
+ parentPath: string = ""
+): RouteObject[] {
+ return routes.map((route) => {
+ let fullPath = parentPath;
+ if (route.path != null) {
+ fullPath = route.path.startsWith("/")
+ ? route.path
+ : normalizePath(parentPath + "/" + route.path);
+ }
+
+ const override = overrides.get(fullPath);
+
+ const updated = override
+ ? {
+ ...route,
+ lazy: undefined,
+ Component: override.Component,
+ ...(override.handle != null && { handle: override.handle }),
+ ...(override.loader != null && { loader: override.loader }),
+ }
+ : { ...route };
+
+ if (override) {
+ overrides.delete(fullPath);
+ }
+
+ if (updated.children) {
+ updated.children = applyOverrides(updated.children, overrides, fullPath);
+ }
+
+ return updated;
+ });
+}
+
+export function getRouteMap(customRoutes: CustomRoute[] = []): RouteObject[] {
+ const overrides = new Map(customRoutes.map((r) => [normalizePath(r.path), r]));
+
+ const routes: RouteObject[] = buildBaseRoutes();
+
+ const result = applyOverrides(routes, overrides);
+
+ // Add remaining custom routes (new pages) under main layout
+ if (overrides.size > 0) {
+ const mainLayoutChildren =
+ result[0]?.children?.[0]?.children;
+ if (mainLayoutChildren) {
+ for (const [, route] of overrides) {
+ mainLayoutChildren.push({
+ path: route.path,
+ Component: route.Component,
+ errorElement: <ErrorBoundary />,
+ ...(route.handle != null && { handle: route.handle }),
+ ...(route.loader != null && { loader: route.loader }),
+ });
+ }
+ }
+ }
+
+ return result;
+}
+
+function buildBaseRoutes(): RouteObject[] {
return [
+ // PROTECTED - MAIN LAYOUT
{
element: <ProtectedRoute />,
errorElement: <ErrorBoundary />,
@@ -18,788 +93,758 @@ export function getRouteMap() {
{
element: <MainLayout />,
children: [
+ // HOME
{
path: "/",
errorElement: <ErrorBoundary />,
- lazy: () => import("./routes/home"),
+ lazy: () => import("./pages/home"),
},
+
+ // PRODUCTS
{
path: "/products",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("products.domain"),
- },
+ handle: { breadcrumb: () => t("products.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/products/product-list"),
+ lazy: () => import("./pages/products"),
children: [
{
path: "create",
- lazy: () => import("./routes/products/product-create"),
+ lazy: () => import("./pages/products/create"),
},
{
path: "import",
- lazy: () => import("./routes/products/product-import"),
+ lazy: () => import("./pages/products/import"),
},
{
path: "export",
- lazy: () => import("./routes/products/product-export"),
+ lazy: () => import("./pages/products/export"),
},
],
},
{
path: ":id",
- errorElement: <ErrorBoundary />,
lazy: async () => {
- const { Breadcrumb, loader } =
- await import("./routes/products/product-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/products/[id]"
+ );
return {
Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminProductResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
path: "",
- lazy: () => import("./routes/products/product-detail"),
+ lazy: () => import("./pages/products/[id]"),
children: [
{
path: "edit",
- lazy: () => import("./routes/products/product-edit"),
- },
- {
- path: "edit-variant",
- lazy: () =>
- import("./routes/product-variants/product-variant-edit"),
+ lazy: () => import("./pages/products/[id]/edit"),
},
{
path: "sales-channels",
lazy: () =>
- import("./routes/products/product-sales-channels"),
- },
- {
- path: "attributes",
- lazy: () =>
- import("./routes/products/product-attributes"),
+ import("./pages/products/[id]/sales-channels"),
},
{
path: "organization",
lazy: () =>
- import("./routes/products/product-organization"),
- },
- {
- path: "shipping-profile",
- lazy: () =>
- import("./routes/products/product-shipping-profile"),
+ import("./pages/products/[id]/organization"),
},
{
path: "media",
- lazy: () => import("./routes/products/product-media"),
+ lazy: () => import("./pages/products/[id]/media"),
},
{
- path: "images/:image_id/variants",
- lazy: () =>
- import("./routes/products/product-image-variants-edit"),
- },
- {
- path: "prices",
- lazy: () =>
- import("./routes/products/product-prices"),
- },
- {
- path: "options/create",
- lazy: () =>
- import("./routes/products/product-create-option"),
- },
- {
- path: "options/:option_id/edit",
+ path: "attributes",
lazy: () =>
- import("./routes/products/product-edit-option"),
+ import("./pages/products/[id]/attributes"),
},
{
- path: "variants/create",
+ path: "additional-attributes",
lazy: () =>
- import("./routes/products/product-create-variant"),
- },
- {
- path: "stock",
- lazy: () => import("./routes/products/product-stock"),
+ import(
+ "./pages/products/[id]/additional-attributes"
+ ),
},
{
- path: "metadata/edit",
+ path: "metadata",
lazy: () =>
- import("./routes/products/product-metadata"),
+ import("./pages/products/[id]/metadata"),
},
- ],
- },
- {
- path: "variants/:variant_id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/product-variants/product-variant-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- // eslint-disable-next-line max-len
- match: UIMatch<HttpTypes.AdminProductVariantResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
{
- path: "edit",
+ path: "shipping-profile",
lazy: () =>
- import("./routes/product-variants/product-variant-edit"),
+ import("./pages/products/[id]/shipping-profile"),
},
{
path: "prices",
- lazy: () =>
- import("./routes/products/product-prices"),
- },
- {
- path: "manage-items",
- lazy: () =>
- import("./routes/product-variants/product-variant-manage-inventory-items"),
+ lazy: () => import("./pages/products/[id]/prices"),
},
{
- path: "media",
+ path: "options/create",
lazy: () =>
- import("./routes/product-variants/product-variant-media"),
+ import("./pages/products/[id]/options/create"),
},
{
- path: "metadata/edit",
+ path: "variants/create",
lazy: () =>
- import("./routes/product-variants/product-variant-metadata"),
+ import("./pages/products/[id]/variants/create"),
},
],
},
+ {
+ path: "stock",
+ lazy: () => import("./pages/products/[id]/stock"),
+ },
],
},
],
},
+
+ // ORDERS
{
- path: "/categories",
+ path: "/orders",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("categories.domain"),
- },
+ handle: { breadcrumb: () => t("orders.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/categories/category-list"),
- children: [
- {
- path: "create",
- lazy: () => import("./routes/categories/category-create"),
- },
- {
- path: "organize",
- lazy: () =>
- import("./routes/categories/category-organize"),
- },
- ],
+ lazy: () => import("./pages/orders"),
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/categories/category-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/orders/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminProductCategoryResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () => import("./routes/categories/category-edit"),
- },
- {
- path: "products",
- lazy: () =>
- import("./routes/categories/category-products"),
- },
- {
- path: "organize",
- lazy: () =>
- import("./routes/categories/category-organize"),
+ path: "",
+ lazy: () => import("./pages/orders/[id]"),
+ children: [
+ {
+ path: "fulfillment",
+ lazy: () =>
+ import("./pages/orders/[id]/fulfillment"),
+ },
+ {
+ path: "allocate-items",
+ lazy: () =>
+ import("./pages/orders/[id]/allocate-items"),
+ },
+ ],
},
{
- path: "metadata/edit",
- lazy: () =>
- import("./routes/categories/categories-metadata"),
+ path: "fulfillments/:f_id/shipment",
+ lazy: () => import("./pages/orders/[id]/shipment"),
},
],
},
],
},
+
+ // CATEGORIES
{
- path: "/orders",
+ path: "/categories",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("orders.domain"),
- },
+ handle: { breadcrumb: () => t("categories.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/orders/order-list"),
+ lazy: () => import("./pages/categories"),
children: [
{
- path: "export",
- lazy: () => import("./routes/orders/order-export"),
+ path: "organize",
+ lazy: () => import("./pages/categories/organize"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/orders/order-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/categories/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminOrderResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "fulfillment",
- lazy: () =>
- import("./routes/orders/order-create-fulfillment"),
- },
- {
- path: "returns/:return_id/receive",
- lazy: () =>
- import("./routes/orders/order-receive-return"),
- },
- {
- path: "allocate-items",
- lazy: () =>
- import("./routes/orders/order-allocate-items"),
- },
- {
- path: ":f_id/create-shipment",
- lazy: () =>
- import("./routes/orders/order-create-shipment"),
- },
- {
- path: "returns",
- lazy: () => import("./routes/orders/order-create-return"),
- },
- {
- path: "claims",
- lazy: () => import("./routes/orders/order-create-claim"),
- },
- {
- path: "exchanges",
- lazy: () =>
- import("./routes/orders/order-create-exchange"),
- },
- {
- path: "edits",
- lazy: () => import("./routes/orders/order-create-edit"),
- },
- {
- path: "refund",
- lazy: () => import("./routes/orders/order-create-refund"),
- },
- {
- path: "transfer",
- lazy: () =>
- import("./routes/orders/order-request-transfer"),
- },
- {
- path: "email",
- lazy: () => import("./routes/orders/order-edit-email"),
- },
- {
- path: "shipping-address",
- lazy: () =>
- import("./routes/orders/order-edit-shipping-address"),
- },
- {
- path: "billing-address",
- lazy: () =>
- import("./routes/orders/order-edit-billing-address"),
- },
- {
- path: "metadata/edit",
- lazy: () => import("./routes/orders/order-metadata"),
+ path: "",
+ lazy: () => import("./pages/categories/[id]"),
+ children: [
+ {
+ path: "products",
+ lazy: () =>
+ import("./pages/categories/[id]/products"),
+ },
+ {
+ path: "organize",
+ lazy: () =>
+ import("./pages/categories/[id]/organize"),
+ },
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/categories/[id]/metadata"),
+ },
+ ],
},
],
},
],
},
+
+ // COLLECTIONS
{
- path: "/promotions",
+ path: "/collections",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("promotions.domain"),
- },
+ handle: { breadcrumb: () => t("collections.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/promotions/promotion-list"),
- },
- {
- path: "create",
- lazy: () => import("./routes/promotions/promotion-create"),
+ lazy: () => import("./pages/collections"),
+ children: [
+ {
+ path: "create",
+ lazy: () => import("./pages/collections/create"),
+ },
+ ],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/promotions/promotion-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/collections/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminPromotionResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/promotions/promotion-edit-details"),
- },
- {
- path: "add-to-campaign",
- lazy: () =>
- import("./routes/promotions/promotion-add-campaign"),
- },
- {
- path: ":ruleType/edit",
- lazy: () =>
- import("./routes/promotions/common/edit-rules"),
+ path: "",
+ lazy: () => import("./pages/collections/[id]"),
+ children: [
+ {
+ path: "add-products",
+ lazy: () =>
+ import("./pages/collections/[id]/add-products"),
+ },
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/collections/[id]/metadata"),
+ },
+ ],
},
],
},
],
},
+
+ // CUSTOMERS
{
- path: "/campaigns",
+ path: "/customers",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("campaigns.domain"),
- },
+ handle: { breadcrumb: () => t("customers.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/campaigns/campaign-list"),
- children: [],
- },
- {
- path: "create",
- lazy: () => import("./routes/campaigns/campaign-create"),
+ lazy: () => import("./pages/customers"),
+ children: [
+ {
+ path: "create",
+ lazy: () => import("./pages/customers/create"),
+ },
+ ],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/campaigns/campaign-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/customers/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminCampaignResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () => import("./routes/campaigns/campaign-edit"),
- },
- {
- path: "configuration",
- lazy: () =>
- import("./routes/campaigns/campaign-configuration"),
- },
- {
- path: "edit-budget",
- lazy: () =>
- import("./routes/campaigns/campaign-budget-edit"),
- },
- {
- path: "add-promotions",
- lazy: () =>
- import("./routes/campaigns/add-campaign-promotions"),
+ path: "",
+ lazy: () => import("./pages/customers/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () => import("./pages/customers/[id]/edit"),
+ },
+ {
+ path: "add-customer-groups",
+ lazy: () =>
+ import(
+ "./pages/customers/[id]/add-customer-groups"
+ ),
+ },
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/customers/[id]/metadata"),
+ },
+ ],
},
],
},
],
},
+
+ // CUSTOMER GROUPS
{
- path: "/collections",
+ path: "/customer-groups",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("collections.domain"),
- },
+ handle: { breadcrumb: () => t("customerGroups.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/collections/collection-list"),
+ lazy: () => import("./pages/customer-groups"),
children: [
{
path: "create",
- lazy: () =>
- import("./routes/collections/collection-create"),
+ lazy: () => import("./pages/customer-groups/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/collections/collection-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/customer-groups/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminCollectionResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/collections/collection-edit"),
- },
- {
- path: "products",
- lazy: () =>
- import("./routes/collections/collection-add-products"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/collections/collection-metadata"),
+ path: "",
+ lazy: () => import("./pages/customer-groups/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () =>
+ import("./pages/customer-groups/[id]/edit"),
+ },
+ {
+ path: "add-customers",
+ lazy: () =>
+ import(
+ "./pages/customer-groups/[id]/add-customers"
+ ),
+ },
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/customer-groups/[id]/metadata"),
+ },
+ ],
},
],
},
],
},
+
+ // INVENTORY
{
- path: "/price-lists",
+ path: "/inventory",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("priceLists.domain"),
- },
+ handle: { breadcrumb: () => t("inventory.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/price-lists/price-list-list"),
+ lazy: () => import("./pages/inventory"),
children: [
{
path: "create",
- lazy: () =>
- import("./routes/price-lists/price-list-create"),
+ lazy: () => import("./pages/inventory/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/price-lists/price-list-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/inventory/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminPriceListResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/price-lists/price-list-edit"),
- },
- {
- path: "configuration",
- lazy: () =>
- import("./routes/price-lists/price-list-configuration"),
- },
- {
- path: "products/add",
- lazy: () =>
- import("./routes/price-lists/price-list-prices-add"),
- },
- {
- path: "products/edit",
- lazy: () =>
- import("./routes/price-lists/price-list-prices-edit"),
+ path: "",
+ lazy: () => import("./pages/inventory/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () =>
+ import(
+ "./pages/inventory/[id]/_components/edit-inventory-item"
+ ),
+ },
+ {
+ path: "attributes",
+ lazy: () =>
+ import(
+ "./pages/inventory/[id]/_components/edit-inventory-item-attributes"
+ ),
+ },
+ {
+ path: "stock",
+ lazy: () => import("./pages/inventory/[id]/stock"),
+ },
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/inventory/[id]/metadata"),
+ },
+ {
+ path: "locations",
+ lazy: () =>
+ import(
+ "./pages/inventory/[id]/_components/manage-locations"
+ ),
+ },
+ {
+ path: "locations/:location_id",
+ lazy: () =>
+ import(
+ "./pages/inventory/[id]/_components/adjust-inventory"
+ ),
+ },
+ ],
},
],
},
],
},
+
+ // PROMOTIONS
{
- path: "/customers",
+ path: "/promotions",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("customers.domain"),
- },
+ handle: { breadcrumb: () => t("promotions.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/customers/customer-list"),
+ lazy: () => import("./pages/promotions"),
children: [
{
path: "create",
- lazy: () => import("./routes/customers/customer-create"),
+ lazy: () => import("./pages/promotions/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/customers/customer-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/promotions/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminCustomerResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () => import("./routes/customers/customer-edit"),
- },
- {
- path: "create-address",
- lazy: () =>
- import("./routes/customers/customer-create-address"),
- },
- {
- path: "add-customer-groups",
- lazy: () =>
- import("./routes/customers/customers-add-customer-group"),
- },
- {
- path: ":order_id/transfer",
- lazy: () =>
- import("./routes/orders/order-request-transfer"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/customers/customer-metadata"),
+ path: "",
+ lazy: () => import("./pages/promotions/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () => import("./pages/promotions/[id]/edit"),
+ },
+ {
+ path: "add-to-campaign",
+ lazy: () =>
+ import("./pages/promotions/[id]/add-to-campaign"),
+ },
+ ],
},
],
},
],
},
+
+ // CAMPAIGNS
{
- path: "/customer-groups",
+ path: "/campaigns",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("customerGroups.domain"),
- },
+ handle: { breadcrumb: () => t("campaigns.domain") },
children: [
{
path: "",
- lazy: () =>
- import("./routes/customer-groups/customer-group-list"),
+ lazy: () => import("./pages/campaigns"),
children: [
{
path: "create",
- lazy: () =>
- import("./routes/customer-groups/customer-group-create"),
+ lazy: () => import("./pages/campaigns/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/customer-groups/customer-group-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/campaigns/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminCustomerGroupResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/customer-groups/customer-group-edit"),
- },
- {
- path: "add-customers",
- lazy: () =>
- import("./routes/customer-groups/customer-group-add-customers"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/customer-groups/customer-group-metadata"),
+ path: "",
+ lazy: () => import("./pages/campaigns/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () => import("./pages/campaigns/[id]/edit"),
+ },
+ {
+ path: "configuration",
+ lazy: () =>
+ import("./pages/campaigns/[id]/configuration"),
+ },
+ {
+ path: "edit-budget",
+ lazy: () =>
+ import("./pages/campaigns/[id]/edit-budget"),
+ },
+ {
+ path: "add-promotions",
+ lazy: () =>
+ import("./pages/campaigns/[id]/add-promotions"),
+ },
+ ],
},
],
},
],
},
+
+ // PRICE LISTS
{
- path: "/reservations",
+ path: "/price-lists",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("reservations.domain"),
- },
+ handle: { breadcrumb: () => t("priceLists.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/reservations/reservation-list"),
+ lazy: () => import("./pages/price-lists"),
children: [
{
path: "create",
- lazy: () =>
- import("./routes/reservations/reservation-create"),
+ lazy: () => import("./pages/price-lists/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/reservations/reservation-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/price-lists/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminReservationResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/reservations/reservation-detail/components/edit-reservation"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/reservations/reservation-metadata"),
+ path: "",
+ lazy: () => import("./pages/price-lists/[id]"),
+ children: [
+ {
+ path: "edit",
+ lazy: () => import("./pages/price-lists/[id]/edit"),
+ },
+ {
+ path: "configuration",
+ lazy: () =>
+ import("./pages/price-lists/[id]/configuration"),
+ },
+ {
+ path: "products/add",
+ lazy: () =>
+ import("./pages/price-lists/[id]/products/add"),
+ },
+ {
+ path: "products/edit",
+ lazy: () =>
+ import("./pages/price-lists/[id]/products/edit"),
+ },
+ {
+ path: "products/:variant_id/edit",
+ lazy: () =>
+ import(
+ "./pages/price-lists/[id]/products/[variant_id]/edit"
+ ),
+ },
+ ],
},
],
},
],
},
+
+ // RESERVATIONS
{
- path: "/inventory",
+ path: "/reservations",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("inventory.domain"),
- },
+ handle: { breadcrumb: () => t("reservations.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/inventory/inventory-list"),
+ lazy: () => import("./pages/reservations"),
children: [
{
path: "create",
- lazy: () => import("./routes/inventory/inventory-create"),
- },
- {
- path: "stock",
- lazy: () => import("./routes/inventory/inventory-stock"),
+ lazy: () => import("./pages/reservations/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/inventory/inventory-detail");
-
+ const { Breadcrumb, loader } = await import(
+ "./pages/reservations/[id]"
+ );
return {
- Component,
+ Component: Outlet,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminInventoryItemResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
- lazy: () =>
- import("./routes/inventory/inventory-detail/components/edit-inventory-item"),
- },
- {
- path: "attributes",
- lazy: () =>
- import("./routes/inventory/inventory-detail/components/edit-inventory-item-attributes"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/inventory/inventory-metadata"),
+ path: "",
+ lazy: () => import("./pages/reservations/[id]"),
+ children: [
+ {
+ path: "metadata",
+ lazy: () =>
+ import("./pages/reservations/[id]/metadata"),
+ },
+ ],
},
+ ],
+ },
+ ],
+ },
+
+ // PRODUCT VARIANTS (standalone routes)
+ {
+ path: "/products/:product_id/variants/:variant_id",
+ errorElement: <ErrorBoundary />,
+ lazy: async () => {
+ const { loader } = await import(
+ "./pages/product-variants/product-variant-detail"
+ );
+ return {
+ Component: Outlet,
+ loader,
+ };
+ },
+ children: [
+ {
+ path: "",
+ lazy: () =>
+ import(
+ "./pages/product-variants/product-variant-detail"
+ ),
+ children: [
{
- path: "locations",
- lazy: () =>
- import("./routes/inventory/inventory-detail/components/manage-locations"),
+ path: "edit",
+ lazy: async () => {
+ const { ProductVariantEdit } = await import(
+ "./pages/product-variants/product-variant-edit/product-variant-edit"
+ );
+ return { Component: ProductVariantEdit };
+ },
},
{
- path: "locations/:location_id",
- lazy: () =>
- import("./routes/inventory/inventory-detail/components/adjust-inventory"),
+ path: "prices",
+ lazy: () => import("./pages/products/[id]/prices"),
},
],
},
@@ -809,443 +854,93 @@ export function getRouteMap() {
},
],
},
+
+ // PROTECTED - SETTINGS LAYOUT
{
element: <ProtectedRoute />,
errorElement: <ErrorBoundary />,
children: [
{
path: "/settings",
- handle: {
- breadcrumb: () => t("app.nav.settings.header"),
- },
element: <SettingsLayout />,
children: [
+ // INDEX
{
index: true,
errorElement: <ErrorBoundary />,
- lazy: () => import("./routes/settings"),
- },
- {
- path: "profile",
- errorElement: <ErrorBoundary />,
- lazy: () => import("./routes/profile/profile-detail"),
- handle: {
- breadcrumb: () => t("profile.domain"),
- },
- children: [
- {
- path: "edit",
- lazy: () => import("./routes/profile/profile-edit"),
- },
- ],
- },
- {
- path: "regions",
- errorElement: <ErrorBoundary />,
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("regions.domain"),
- },
- children: [
- {
- path: "",
- lazy: () => import("./routes/regions/region-list"),
- children: [
- {
- path: "create",
- lazy: () => import("./routes/regions/region-create"),
- },
- ],
- },
- {
- path: ":id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/regions/region-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminRegionResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "edit",
- lazy: () => import("./routes/regions/region-edit"),
- },
- {
- path: "countries/add",
- lazy: () =>
- import("./routes/regions/region-add-countries"),
- },
- {
- path: "metadata/edit",
- lazy: () => import("./routes/regions/region-metadata"),
- },
- ],
- },
- ],
- },
- {
- path: "store",
- errorElement: <ErrorBoundary />,
- lazy: () => import("./routes/store/store-detail"),
- handle: {
- breadcrumb: () => t("store.domain"),
- },
- children: [
- {
- path: "edit",
- lazy: () => import("./routes/store/store-edit"),
- },
- {
- path: "currencies",
- lazy: () => import("./routes/store/store-add-currencies"),
- },
- {
- path: "locales",
- lazy: () => import("./routes/store/store-add-locales"),
- },
- {
- path: "metadata/edit",
- lazy: () => import("./routes/store/store-metadata"),
- },
- ],
+ lazy: () => import("./pages/settings"),
},
- {
- path: "users",
- errorElement: <ErrorBoundary />,
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("users.domain"),
- },
- children: [
- {
- path: "",
- lazy: () => import("./routes/users/user-list"),
- children: [
- {
- path: "invite",
- lazy: () => import("./routes/users/user-invite"),
- },
- ],
- },
- {
- path: ":id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/users/user-detail");
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminUserResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "edit",
- lazy: () => import("./routes/users/user-edit"),
- },
- {
- path: "metadata/edit",
- lazy: () => import("./routes/users/user-metadata"),
- },
- ],
- },
- ],
- },
- {
- path: "sales-channels",
- errorElement: <ErrorBoundary />,
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("salesChannels.domain"),
- },
- children: [
- {
- path: "",
- lazy: () =>
- import("./routes/sales-channels/sales-channel-list"),
- children: [
- {
- path: "create",
- lazy: () =>
- import("./routes/sales-channels/sales-channel-create"),
- },
- ],
- },
- {
- path: ":id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/sales-channels/sales-channel-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminSalesChannelResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/sales-channels/sales-channel-edit"),
- },
- {
- path: "add-products",
- lazy: () =>
- import("./routes/sales-channels/sales-channel-add-products"),
- },
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/sales-channels/sales-channel-metadata"),
- },
- ],
- },
- ],
- },
+ // SELLER
{
- path: "locations",
+ path: "seller",
errorElement: <ErrorBoundary />,
- element: <Outlet />,
handle: {
- breadcrumb: () => t("locations.domain"),
+ breadcrumb: () => t("seller.domain", "Seller"),
},
children: [
- {
- path: "",
- lazy: () => import("./routes/locations/location-list"),
- },
- {
- path: "create",
- lazy: () => import("./routes/locations/location-create"),
- },
- {
- path: "shipping-profiles",
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("shippingProfile.domain"),
- },
- children: [
- {
- path: "",
- lazy: () =>
- import("./routes/shipping-profiles/shipping-profiles-list"),
- children: [
- {
- path: "create",
- lazy: () =>
- import("./routes/shipping-profiles/shipping-profile-create"),
- },
- ],
- },
- {
- path: ":shipping_profile_id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/shipping-profiles/shipping-profile-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- // eslint-disable-next-line max-len
- match: UIMatch<HttpTypes.AdminShippingProfileResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "metadata/edit",
- lazy: () =>
- import("./routes/shipping-profiles/shipping-profile-metadata"),
- },
- ],
- },
- ],
- },
- {
- path: "shipping-option-types",
- errorElement: <ErrorBoundary />,
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("shippingOptionTypes.domain"),
- },
- children: [
- {
- path: "",
- lazy: () =>
- import("./routes/shipping-option-types/shipping-option-type-list"),
- children: [
- {
- path: "create",
- lazy: () =>
- import("./routes/shipping-option-types/shipping-option-type-create"),
- },
- ],
- },
- {
- path: ":id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/shipping-option-types/shipping-option-type-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- // eslint-disable-next-line max-len
- match: UIMatch<HttpTypes.AdminShippingOptionTypeResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/shipping-option-types/shipping-option-type-edit"),
- },
- ],
- },
- ],
- },
- {
- path: ":location_id",
- lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/locations/location-detail");
-
- return {
- Component,
- loader,
- handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminStockLocationResponse>
- ) => <Breadcrumb {...match} />,
- },
- };
- },
- children: [
- {
- path: "edit",
- lazy: () => import("./routes/locations/location-edit"),
- },
- {
- path: "sales-channels",
- lazy: () =>
- import("./routes/locations/location-sales-channels"),
- },
+ {
+ path: "",
+ lazy: () => import("./pages/settings/seller"),
+ children: [
{
- path: "fulfillment-providers",
- lazy: () =>
- import("./routes/locations/location-fulfillment-providers"),
+ path: "edit",
+ lazy: () => import("./pages/settings/seller/edit"),
},
+ ],
+ },
+ ],
+ },
+
+ // PROFILE
+ {
+ path: "profile",
+ errorElement: <ErrorBoundary />,
+ handle: { breadcrumb: () => t("profile.domain") },
+ children: [
+ {
+ path: "",
+ lazy: () => import("./pages/settings/profile"),
+ children: [
{
- path: "fulfillment-set/:fset_id",
- children: [
- {
- path: "service-zones/create",
- lazy: () =>
- import("./routes/locations/location-service-zone-create"),
- },
- {
- path: "service-zone/:zone_id",
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/locations/location-service-zone-edit"),
- },
- {
- path: "areas",
- lazy: () =>
- import("./routes/locations/location-service-zone-manage-areas"),
- },
- {
- path: "shipping-option",
- children: [
- {
- path: "create",
- lazy: () =>
- import("./routes/locations/location-service-zone-shipping-option-create"),
- },
- {
- path: ":so_id",
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/locations/location-service-zone-shipping-option-edit"),
- },
- {
- path: "pricing",
- lazy: () =>
- import("./routes/locations/location-service-zone-shipping-option-pricing"),
- },
- ],
- },
- ],
- },
- ],
- },
- ],
+ path: "edit",
+ lazy: () => import("./pages/settings/profile/edit"),
},
],
},
],
},
+
+ // REGIONS
{
- path: "product-tags",
+ path: "regions",
errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("productTags.domain"),
- },
+ handle: { breadcrumb: () => t("regions.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/product-tags/product-tag-list"),
+ lazy: () => import("./pages/settings/regions"),
children: [
{
path: "create",
- lazy: () =>
- import("./routes/product-tags/product-tag-create"),
+ lazy: () => import("./pages/settings/regions/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/product-tags/product-tag-detail");
-
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/regions/[id]"
+ );
return {
Component,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminProductTagResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
@@ -1253,50 +948,56 @@ export function getRouteMap() {
{
path: "edit",
lazy: () =>
- import("./routes/product-tags/product-tag-edit"),
+ import("./pages/settings/regions/[id]/edit"),
+ },
+ {
+ path: "countries/add",
+ lazy: () =>
+ import(
+ "./pages/settings/regions/[id]/countries/add"
+ ),
},
{
path: "metadata/edit",
lazy: () =>
- import("./routes/product-tags/product-tag-metadata"),
+ import("./pages/settings/regions/[id]/metadata"),
},
],
},
],
},
+
+ // USERS
{
- path: "product-types",
+ path: "users",
errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("productTypes.domain"),
- },
+ handle: { breadcrumb: () => t("users.domain") },
children: [
{
path: "",
- lazy: () =>
- import("./routes/product-types/product-type-list"),
+ lazy: () => import("./pages/settings/users"),
children: [
{
- path: "create",
+ path: "invite",
lazy: () =>
- import("./routes/product-types/product-type-create"),
+ import("./pages/settings/users/invite"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/product-types/product-type-detail");
-
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/users/[id]"
+ );
return {
Component,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminProductTypeResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
@@ -1304,55 +1005,99 @@ export function getRouteMap() {
{
path: "edit",
lazy: () =>
- import("./routes/product-types/product-type-edit"),
+ import("./pages/settings/users/[id]/edit"),
},
{
path: "metadata/edit",
lazy: () =>
- import("./routes/product-types/product-type-metadata"),
+ import("./pages/settings/users/[id]/metadata"),
},
],
},
],
},
+
+ // LOCATIONS
{
- path: "publishable-api-keys",
+ path: "locations",
+ errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("apiKeyManagement.domain.publishable"),
- },
+ handle: { breadcrumb: () => t("locations.domain") },
children: [
{
path: "",
+ lazy: () => import("./pages/settings/locations"),
+ children: [
+ {
+ path: "create",
+ lazy: () =>
+ import("./pages/settings/locations/create"),
+ },
+ ],
+ },
+ {
+ path: "shipping-profiles",
element: <Outlet />,
+ handle: {
+ breadcrumb: () => t("shippingProfile.domain"),
+ },
children: [
{
path: "",
lazy: () =>
- import("./routes/api-key-management/api-key-management-list"),
+ import("./pages/settings/shipping-profiles"),
children: [
{
path: "create",
lazy: () =>
- import("./routes/api-key-management/api-key-management-create"),
+ import(
+ "./pages/settings/shipping-profiles/create"
+ ),
+ },
+ ],
+ },
+ {
+ path: ":shipping_profile_id",
+ lazy: async () => {
+ const { Component, Breadcrumb, loader } =
+ await import(
+ "./pages/settings/shipping-profiles/[id]"
+ );
+ return {
+ Component,
+ loader,
+ handle: {
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
+ },
+ };
+ },
+ children: [
+ {
+ path: "metadata/edit",
+ lazy: () =>
+ import(
+ "./pages/settings/shipping-profiles/[id]/metadata"
+ ),
},
],
},
],
},
{
- path: ":id",
+ path: ":location_id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/api-key-management/api-key-management-detail");
-
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/locations/[location_id]"
+ );
return {
Component,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminApiKeyResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
@@ -1360,152 +1105,155 @@ export function getRouteMap() {
{
path: "edit",
lazy: () =>
- import("./routes/api-key-management/api-key-management-edit"),
+ import(
+ "./pages/settings/locations/[location_id]/edit"
+ ),
},
{
path: "sales-channels",
lazy: () =>
- import("./routes/api-key-management/api-key-management-sales-channels"),
+ import(
+ "./pages/settings/locations/[location_id]/sales-channels"
+ ),
+ },
+ {
+ path: "fulfillment-providers",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-providers"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zones/create",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zone/:zone_id/edit",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zone/:zone_id/areas",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zone/:zone_id/shipping-option/create",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zone/:zone_id/shipping-option/:so_id/edit",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit"
+ ),
+ },
+ {
+ path: "fulfillment-set/:fset_id/service-zone/:zone_id/shipping-option/:so_id/pricing",
+ lazy: () =>
+ import(
+ "./pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing"
+ ),
},
],
},
],
},
+
+ // TAX REGIONS
{
- path: "secret-api-keys",
+ path: "tax-regions",
+ errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("apiKeyManagement.domain.secret"),
- },
+ handle: { breadcrumb: () => t("taxRegions.domain") },
children: [
{
path: "",
- element: <Outlet />,
+ lazy: () => import("./pages/settings/tax-regions"),
children: [
{
- path: "",
+ path: "create",
lazy: () =>
- import("./routes/api-key-management/api-key-management-list"),
- children: [
- {
- path: "create",
- lazy: () =>
- import("./routes/api-key-management/api-key-management-create"),
- },
- ],
+ import("./pages/settings/tax-regions/create"),
},
],
},
{
path: ":id",
lazy: async () => {
- const { Component, Breadcrumb, loader } =
- await import("./routes/api-key-management/api-key-management-detail");
-
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/tax-regions/[id]"
+ );
return {
Component,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminApiKeyResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
children: [
{
- path: "edit",
+ path: "tax-rates/create",
lazy: () =>
- import("./routes/api-key-management/api-key-management-edit"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-rates/create"
+ ),
},
- ],
- },
- ],
- },
- {
- path: "tax-regions",
- element: <Outlet />,
- handle: {
- breadcrumb: () => t("taxRegions.domain"),
- },
- children: [
- {
- path: "",
- lazy: () => import("./routes/tax-regions/tax-region-list"),
- children: [
{
- path: "create",
+ path: "tax-rates/:tax_rate_id/edit",
lazy: () =>
- import("./routes/tax-regions/tax-region-create"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit"
+ ),
},
- ],
- },
- {
- path: ":id",
- Component: Outlet,
- loader: taxRegionLoader,
- handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminTaxRegionResponse>
- ) => <TaxRegionDetailBreadcrumb {...match} />,
- },
- children: [
{
- path: "",
- lazy: async () => {
- const { Component } =
- await import("./routes/tax-regions/tax-region-detail");
-
- return {
- Component,
- };
- },
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/tax-regions/tax-region-edit"),
- },
- {
- path: "provinces/create",
- lazy: () =>
- import("./routes/tax-regions/tax-region-province-create"),
- },
- {
- path: "overrides/create",
- lazy: () =>
- import("./routes/tax-regions/tax-region-tax-override-create"),
- },
- {
- path: "overrides/:tax_rate_id/edit",
- lazy: () =>
- import("./routes/tax-regions/tax-region-tax-override-edit"),
- },
- {
- path: "tax-rates/create",
- lazy: () =>
- import("./routes/tax-regions/tax-region-tax-rate-create"),
- },
- {
- path: "tax-rates/:tax_rate_id/edit",
- lazy: () =>
- import("./routes/tax-regions/tax-region-tax-rate-edit"),
- },
- ],
+ path: "tax-overrides/create",
+ lazy: () =>
+ import(
+ "./pages/settings/tax-regions/[id]/tax-overrides/create"
+ ),
+ },
+ {
+ path: "tax-overrides/:tax_rate_id/edit",
+ lazy: () =>
+ import(
+ "./pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit"
+ ),
+ },
+ {
+ path: "provinces/create",
+ lazy: () =>
+ import(
+ "./pages/settings/tax-regions/[id]/provinces/create"
+ ),
},
{
path: "provinces/:province_id",
lazy: async () => {
const { Component, Breadcrumb, loader } =
- await import("./routes/tax-regions/tax-region-province-detail");
-
+ await import(
+ "./pages/settings/tax-regions/[id]/provinces/[province_id]"
+ );
return {
Component,
loader,
handle: {
- breadcrumb: (
- match: UIMatch<HttpTypes.AdminTaxRegionResponse>
- ) => <Breadcrumb {...match} />,
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
},
};
},
@@ -1513,22 +1261,30 @@ export function getRouteMap() {
{
path: "tax-rates/create",
lazy: () =>
- import("./routes/tax-regions/tax-region-tax-rate-create"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-rates/create"
+ ),
},
{
path: "tax-rates/:tax_rate_id/edit",
lazy: () =>
- import("./routes/tax-regions/tax-region-tax-rate-edit"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit"
+ ),
},
{
- path: "overrides/create",
+ path: "tax-overrides/create",
lazy: () =>
- import("./routes/tax-regions/tax-region-tax-override-create"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-overrides/create"
+ ),
},
{
- path: "overrides/:tax_rate_id/edit",
+ path: "tax-overrides/:tax_rate_id/edit",
lazy: () =>
- import("./routes/tax-regions/tax-region-tax-override-edit"),
+ import(
+ "./pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit"
+ ),
},
],
},
@@ -1536,101 +1292,123 @@ export function getRouteMap() {
},
],
},
+
+ // PRODUCT TAGS
{
- path: "return-reasons",
+ path: "product-tags",
+ errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("returnReasons.domain"),
- },
+ handle: { breadcrumb: () => t("productTags.domain") },
children: [
{
path: "",
- lazy: () =>
- import("./routes/return-reasons/return-reason-list"),
+ lazy: () => import("./pages/settings/product-tags"),
+ },
+ {
+ path: ":id",
+ lazy: async () => {
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/product-tags/[id]"
+ );
+ return {
+ Component,
+ loader,
+ handle: {
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
+ },
+ };
+ },
children: [
{
- path: "create",
+ path: "edit",
lazy: () =>
- import("./routes/return-reasons/return-reason-create"),
- },
-
- {
- path: ":id",
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/return-reasons/return-reason-edit"),
- },
- ],
+ import("./pages/settings/product-tags/[id]/edit"),
},
],
},
],
},
+
+ // PRODUCT TYPES
{
- path: "refund-reasons",
+ path: "product-types",
+ errorElement: <ErrorBoundary />,
element: <Outlet />,
- handle: {
- breadcrumb: () => t("refundReasons.domain"),
- },
+ handle: { breadcrumb: () => t("productTypes.domain") },
children: [
{
path: "",
- lazy: () =>
- import("./routes/refund-reasons/refund-reason-list"),
+ lazy: () => import("./pages/settings/product-types"),
children: [
{
path: "create",
lazy: () =>
- import("./routes/refund-reasons/refund-reason-create"),
+ import("./pages/settings/product-types/create"),
},
-
+ ],
+ },
+ {
+ path: ":id",
+ lazy: async () => {
+ const { Component, Breadcrumb, loader } = await import(
+ "./pages/settings/product-types/[id]"
+ );
+ return {
+ Component,
+ loader,
+ handle: {
+ breadcrumb: (match: UIMatch<any>) => (
+ <Breadcrumb {...match} />
+ ),
+ },
+ };
+ },
+ children: [
{
- path: ":id",
- children: [
- {
- path: "edit",
- lazy: () =>
- import("./routes/refund-reasons/refund-reason-edit"),
- },
- ],
+ path: "edit",
+ lazy: () =>
+ import("./pages/settings/product-types/[id]/edit"),
},
],
},
],
},
+
+ // RETURN REASONS
{
- path: "translations",
+ path: "return-reasons",
errorElement: <ErrorBoundary />,
- handle: {
- breadcrumb: () => t("translations.domain"),
- },
+ element: <Outlet />,
+ handle: { breadcrumb: () => t("returnReasons.domain") },
children: [
{
path: "",
- lazy: () => import("./routes/translations/translation-list"),
+ lazy: () => import("./pages/settings/return-reasons"),
children: [
{
- path: "settings",
- lazy: () => import("./routes/translations/settings"),
+ path: "create",
+ lazy: () =>
+ import("./pages/settings/return-reasons/create"),
+ },
+ {
+ path: ":id/edit",
+ lazy: () =>
+ import(
+ "./pages/settings/return-reasons/[id]/edit"
+ ),
},
],
},
- {
- path: "edit",
- lazy: () => import("./routes/translations/translations-edit"),
- },
- {
- path: "add-locales",
- lazy: () => import("./routes/translations/add-locales"),
- },
],
},
],
},
],
},
+
+ // PUBLIC LAYOUT
{
element: <PublicLayout />,
children: [
@@ -1639,19 +1417,23 @@ export function getRouteMap() {
children: [
{
path: "/login",
- lazy: () => import("./routes/login"),
+ lazy: () => import("./pages/login"),
+ },
+ {
+ path: "/register",
+ lazy: () => import("./pages/register"),
},
{
path: "/reset-password",
- lazy: () => import("./routes/reset-password"),
+ lazy: () => import("./pages/reset-password"),
},
{
path: "/invite",
- lazy: () => import("./routes/invite"),
+ lazy: () => import("./pages/invite"),
},
{
path: "*",
- lazy: () => import("./routes/no-match"),
+ lazy: () => import("./pages/no-match"),
},
],
},
diff --git a/packages/vendor/src/hooks/api/auth.tsx b/packages/vendor/src/hooks/api/auth.tsx
index 9f88c760a..536fdd386 100644
--- a/packages/vendor/src/hooks/api/auth.tsx
+++ b/packages/vendor/src/hooks/api/auth.tsx
@@ -5,6 +5,7 @@ import {
} from "@mercurjs/client";
import { UseMutationOptions, useMutation } from "@tanstack/react-query";
import { sdk } from "../../lib/client";
+import { backendUrl } from "../../lib/client";
export const useSignInWithEmailPass = (
options?: UseMutationOptions<
@@ -17,12 +18,25 @@ export const useSignInWithEmailPass = (
>
) => {
return useMutation({
- mutationFn: (payload) =>
- sdk.auth.$actorType.$authProvider.mutate({
+ mutationFn: async (payload) => {
+ const data = (await sdk.auth.$actorType.$authProvider.mutate({
actorType: "user",
authProvider: "emailpass",
...payload,
- }),
+ })) as { token: string };
+
+ // Exchange JWT token for a session cookie
+ await fetch(`${backendUrl}/auth/session`, {
+ method: "POST",
+ credentials: "include",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${data.token}`,
+ },
+ });
+
+ return data;
+ },
onSuccess: async (data, variables, context) => {
options?.onSuccess?.(data, variables, context);
},
@@ -56,6 +70,29 @@ export const useSignUpWithEmailPass = (
});
};
+export const useSignUpForInvite = (
+ options?: UseMutationOptions<
+ InferClientOutput<typeof sdk.auth.$actorType.$authProvider.register.mutate>,
+ ClientError,
+ Omit<
+ InferClientInput<
+ typeof sdk.auth.$actorType.$authProvider.register.mutate
+ >,
+ "actorType" | "authProvider"
+ >
+ >
+) => {
+ return useMutation({
+ mutationFn: (payload) =>
+ sdk.auth.$actorType.$authProvider.register.mutate({
+ actorType: "user",
+ authProvider: "emailpass",
+ ...payload,
+ }),
+ ...options,
+ });
+};
+
export const useResetPasswordForEmailPass = (
options?: UseMutationOptions<
InferClientOutput<
diff --git a/packages/vendor/src/hooks/api/customers.tsx b/packages/vendor/src/hooks/api/customers.tsx
index 6045fc362..37b67c370 100644
--- a/packages/vendor/src/hooks/api/customers.tsx
+++ b/packages/vendor/src/hooks/api/customers.tsx
@@ -4,15 +4,17 @@ import {
InferClientOutput,
} from "@mercurjs/client";
import {
+ QueryKey,
UseMutationOptions,
UseQueryOptions,
useMutation,
useQuery,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
import { customerGroupsQueryKeys } from "./customer-groups";
+import { filterOrders } from "../../pages/orders/common/orderFiltering";
const CUSTOMERS_QUERY_KEY = "customers" as const;
export const customersQueryKeys = queryKeysFactory(CUSTOMERS_QUERY_KEY);
@@ -288,3 +290,32 @@ export const useCustomerAddress = (
return { ...data, ...rest };
};
+
+export const useCustomerOrders = (
+ id: string,
+ query?: Record<string, any>,
+ options?: Omit<
+ UseQueryOptions<
+ { orders: any[] },
+ Error,
+ { orders: any[] },
+ QueryKey
+ >,
+ "queryFn" | "queryKey"
+ >,
+ filters?: any
+) => {
+ const { data, ...rest } = useQuery({
+ queryKey: [CUSTOMERS_QUERY_KEY, id, "orders"],
+ queryFn: async () =>
+ fetchQuery(`/vendor/customers/${id}/orders`, {
+ method: "GET",
+ query,
+ }),
+ ...options,
+ });
+
+ const filteredOrders = filterOrders(data?.orders, filters, filters?.sort);
+
+ return { ...data, orders: filteredOrders, ...rest };
+};
diff --git a/packages/vendor/src/hooks/api/orders.tsx b/packages/vendor/src/hooks/api/orders.tsx
index f03021e1c..9fcc5eb05 100644
--- a/packages/vendor/src/hooks/api/orders.tsx
+++ b/packages/vendor/src/hooks/api/orders.tsx
@@ -4,12 +4,13 @@ import {
InferClientOutput,
} from "@mercurjs/client";
import {
+ QueryKey,
useMutation,
UseMutationOptions,
useQuery,
UseQueryOptions,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory, TQueryKey } from "../../lib/query-key-factory";
import { inventoryItemsQueryKeys } from "./inventory";
@@ -504,3 +505,56 @@ export const useExportOrders = (
...options,
});
};
+
+export const useCompleteOrder = (
+ orderId: string,
+ options?: UseMutationOptions<any, Error, void>
+) => {
+ return useMutation({
+ mutationFn: () =>
+ fetchQuery(`/vendor/orders/${orderId}/complete`, {
+ method: "POST",
+ }),
+ onSuccess: (data: any, variables: any, context: any) => {
+ queryClient.invalidateQueries({
+ queryKey: ordersQueryKeys.detail(orderId),
+ });
+
+ queryClient.invalidateQueries({
+ queryKey: ordersQueryKeys.preview(orderId),
+ });
+
+ queryClient.invalidateQueries({
+ queryKey: ordersQueryKeys.list(),
+ });
+
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
+
+type OrderCommission = {
+ commission: any
+}
+
+export const useOrderCommission = (
+ id: string,
+ query?: Record<string, any>,
+ options?: Omit<
+ UseQueryOptions<OrderCommission, Error, OrderCommission, QueryKey>,
+ "queryFn" | "queryKey"
+ >
+) => {
+ const { data, ...rest } = useQuery({
+ queryFn: async () =>
+ fetchQuery(`/vendor/orders/${id}/commission`, {
+ method: "GET",
+ query,
+ }),
+ queryKey: ordersQueryKeys.detail(`${id}/commission`, query),
+ ...options,
+ });
+
+ return { commission: data?.commission, ...rest };
+};
diff --git a/packages/vendor/src/hooks/api/price-lists.tsx b/packages/vendor/src/hooks/api/price-lists.tsx
index ca35bb2cb..eca5d3f65 100644
--- a/packages/vendor/src/hooks/api/price-lists.tsx
+++ b/packages/vendor/src/hooks/api/price-lists.tsx
@@ -4,12 +4,13 @@ import {
InferClientOutput,
} from "@mercurjs/client";
import {
+ QueryKey,
UseMutationOptions,
UseQueryOptions,
useMutation,
useQuery,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
import { customerGroupsQueryKeys } from "./customer-groups";
@@ -201,3 +202,24 @@ export const usePriceListLinkProducts = (
...options,
});
};
+
+export const usePriceListProducts = (
+ id: string,
+ query?: Record<string, string | number>,
+ options?: Omit<
+ UseQueryOptions<any, Error, any, QueryKey>,
+ "queryKey" | "queryFn"
+ >
+) => {
+ const { data, ...rest } = useQuery({
+ queryFn: () =>
+ fetchQuery(`/vendor/price-lists/${id}/products`, {
+ method: "GET",
+ query,
+ }),
+ queryKey: [PRICE_LISTS_QUERY_KEY, id, "products"],
+ ...options,
+ });
+
+ return { ...data, ...rest };
+};
diff --git a/packages/vendor/src/hooks/api/products.tsx b/packages/vendor/src/hooks/api/products.tsx
index f3b81f01c..05936630e 100644
--- a/packages/vendor/src/hooks/api/products.tsx
+++ b/packages/vendor/src/hooks/api/products.tsx
@@ -12,7 +12,7 @@ import {
useQuery,
UseQueryOptions,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
import { inventoryItemsQueryKeys } from "./inventory.tsx";
@@ -617,3 +617,54 @@ export const useBatchVariantImages = (
...options,
});
};
+
+type ProductAttributesResponse = {
+ attributes: any[]
+}
+
+const productAttributesQueryKey = (id: string) => [
+ "product-attributes",
+ id,
+]
+
+export const useProductAttributes = (id: string) => {
+ const { data, ...rest } = useQuery<ProductAttributesResponse>({
+ queryFn: () =>
+ fetchQuery(`/vendor/products/${id}/applicable-attributes`, {
+ method: "GET",
+ query: { fields: "+is_required" },
+ }),
+ queryKey: productAttributesQueryKey(id),
+ })
+
+ return { ...data, ...rest }
+}
+
+export const useBulkDeleteProducts = (
+ options?: UseMutationOptions<any[], ClientError, string[]>
+) => {
+ return useMutation({
+ mutationFn: async (productIds: string[]) => {
+ const deletePromises = productIds.map((id) =>
+ fetchQuery(`/vendor/products/${id}`, {
+ method: "DELETE",
+ })
+ )
+ return Promise.all(deletePromises)
+ },
+ onSuccess: (data: any, variables: any, context: any) => {
+ queryClient.invalidateQueries({
+ queryKey: productsQueryKeys.lists(),
+ })
+
+ variables.forEach((id: string) => {
+ queryClient.invalidateQueries({
+ queryKey: productsQueryKeys.detail(id),
+ })
+ })
+
+ options?.onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/packages/vendor/src/hooks/api/promotions.tsx b/packages/vendor/src/hooks/api/promotions.tsx
index e26333b00..bf8416998 100644
--- a/packages/vendor/src/hooks/api/promotions.tsx
+++ b/packages/vendor/src/hooks/api/promotions.tsx
@@ -9,7 +9,7 @@ import {
useQuery,
UseQueryOptions,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
import { campaignsQueryKeys } from "./campaigns";
@@ -340,3 +340,30 @@ export const usePromotionUpdateRules = (
...options,
});
};
+
+export const useRemovePromotionFromCampaign = (
+ promotionId: string,
+ options?: UseMutationOptions<any, Error, void>
+) => {
+ return useMutation({
+ mutationFn: () =>
+ fetchQuery(`/vendor/promotions/${promotionId}`, {
+ method: "POST",
+ body: { campaign_id: null },
+ }),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({
+ queryKey: promotionsQueryKeys.all,
+ });
+ queryClient.invalidateQueries({
+ queryKey: campaignsQueryKeys.details(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: campaignsQueryKeys.lists(),
+ });
+
+ options?.onSuccess?.(data, variables, context);
+ },
+ ...options,
+ });
+};
diff --git a/packages/vendor/src/hooks/api/users.tsx b/packages/vendor/src/hooks/api/users.tsx
index 7ba541322..2190a0cf2 100644
--- a/packages/vendor/src/hooks/api/users.tsx
+++ b/packages/vendor/src/hooks/api/users.tsx
@@ -9,7 +9,7 @@ import {
useMutation,
useQuery,
} from "@tanstack/react-query";
-import { sdk } from "../../lib/client";
+import { sdk, fetchQuery } from "../../lib/client";
import { queryClient } from "../../lib/query-client";
import { queryKeysFactory } from "../../lib/query-key-factory";
@@ -119,3 +119,20 @@ export const useDeleteUser = (
...options,
});
};
+
+export const useUserMe = (
+ query?: Record<string, any>,
+ options?: UseQueryOptions<any, Error, any>
+) => {
+ const { data, ...rest } = useQuery({
+ queryFn: () =>
+ fetchQuery(`/vendor/me`, {
+ method: "GET",
+ query: query as { [key: string]: string | number },
+ }),
+ queryKey: [USERS_QUERY_KEY, "user", "me"],
+ ...options,
+ });
+
+ return { ...data, ...rest };
+};
diff --git a/packages/vendor/src/hooks/table/query/use-product-variants-table-query.tsx b/packages/vendor/src/hooks/table/query/use-product-variants-table-query.tsx
new file mode 100644
index 000000000..747694d96
--- /dev/null
+++ b/packages/vendor/src/hooks/table/query/use-product-variants-table-query.tsx
@@ -0,0 +1,76 @@
+import { useQueryParams } from "../../use-query-params"
+
+type UseProductVariantsTableQueryProps = {
+ prefix?: string
+ pageSize?: number
+}
+
+const DEFAULT_FIELDS =
+ "*options,*inventory_items,*inventory_items.inventory,*inventory_items.inventory.location_levels"
+
+export const useProductVariantsTableQuery = ({
+ prefix,
+ pageSize = 10,
+}: UseProductVariantsTableQueryProps) => {
+ const queryObject = useQueryParams(
+ [
+ "offset",
+ "order",
+ "q",
+ "id",
+ "sku",
+ "title",
+ "manage_inventory",
+ "allow_backorder",
+ "created_at",
+ "updated_at",
+ ],
+ prefix
+ )
+
+ const {
+ offset,
+ order,
+ q,
+ id,
+ sku,
+ title,
+ manage_inventory,
+ allow_backorder,
+ created_at,
+ updated_at,
+ } = queryObject
+
+ const searchParams: {
+ limit: number
+ offset: number
+ fields: string
+ order?: string
+ q?: string
+ id?: string | string[]
+ sku?: string | string[]
+ title?: string | string[]
+ manage_inventory?: boolean
+ allow_backorder?: boolean
+ created_at?: any
+ updated_at?: any
+ } = {
+ limit: pageSize,
+ offset: offset ? Number(offset) : 0,
+ fields: DEFAULT_FIELDS,
+ order: order,
+ q: q,
+ id: id ? id.split(",") : undefined,
+ sku: sku ? sku.split(",") : undefined,
+ title: title ? title.split(",") : undefined,
+ manage_inventory: manage_inventory ? manage_inventory === "true" : undefined,
+ allow_backorder: allow_backorder ? allow_backorder === "true" : undefined,
+ created_at: created_at ? JSON.parse(created_at) : undefined,
+ updated_at: updated_at ? JSON.parse(updated_at) : undefined,
+ }
+
+ return {
+ searchParams,
+ raw: queryObject,
+ }
+}
diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.json
index b3820bea7..e1ecc4c8a 100644
--- a/packages/vendor/src/i18n/translations/en.json
+++ b/packages/vendor/src/i18n/translations/en.json
@@ -2912,11 +2912,26 @@
},
"login": {
"forgotPassword": "Forgot password? - <0>Reset</0>",
- "title": "Welcome to Medusa",
- "hint": "Sign in to access the account area"
+ "title": "Welcome to Mercur",
+ "hint": "Sign in to access the vendor area",
+ "notSellerYet": "Not a seller yet? - <0>Register</0>"
+ },
+ "register": {
+ "title": "Create your account",
+ "hint": "Register as a seller on Mercur",
+ "alreadySeller": "Already a seller? - <0>Log in</0>"
+ },
+ "validation": {
+ "rules": {
+ "lower": "At least one lowercase letter",
+ "upper": "At least one uppercase letter",
+ "12chars": "At least 12 characters",
+ "digit": "At least one digit",
+ "specialChar": "At least one special character"
+ }
},
"invite": {
- "title": "Welcome to Medusa",
+ "title": "Welcome to Mercur",
"hint": "Create your account below",
"backToLogin": "Back to login",
"createAccount": "Create account",
@@ -2924,8 +2939,8 @@
"emailTooltip": "Your email cannot be changed. If you would like to use another email, a new invite must be sent.",
"invalidInvite": "The invite is invalid or has expired.",
"successTitle": "Your account has been registered",
- "successHint": "Get started with Medusa Admin right away.",
- "successAction": "Start Medusa Admin",
+ "successHint": "Get started with Mercur right away.",
+ "successAction": "Start Mercur",
"invalidTokenTitle": "Your invite token is invalid",
"invalidTokenHint": "Try requesting a new invite link.",
"passwordMismatch": "Passwords do not match",
@@ -3305,7 +3320,7 @@
"auth": {
"login": {
"authenticationFailed": "Authentication failed",
- "cloud": "Log in with Medusa Cloud"
+ "cloud": "Log in with Mercur"
}
}
}
diff --git a/packages/vendor/src/lib/client/client.ts b/packages/vendor/src/lib/client/client.ts
index 957297ede..6a3e94809 100644
--- a/packages/vendor/src/lib/client/client.ts
+++ b/packages/vendor/src/lib/client/client.ts
@@ -8,3 +8,92 @@ export const sdk: InferClient<Routes> = createClient<Routes>({
credentials: 'include',
},
})
+
+export const backendUrl = config.baseUrl
+
+export const fetchQuery = async (
+ url: string,
+ {
+ method,
+ body,
+ query,
+ headers,
+ }: {
+ method: 'GET' | 'POST' | 'DELETE'
+ body?: object
+ query?: Record<string, string | number | object>
+ headers?: { [key: string]: string }
+ }
+) => {
+ const params = Object.entries(query || {}).reduce((acc, [key, value]) => {
+ if (value !== null && value !== undefined && value !== '') {
+ if (Array.isArray(value)) {
+ const arrayParams = value
+ .map(
+ (item) =>
+ `${encodeURIComponent(key)}[]=${encodeURIComponent(item)}`
+ )
+ .join('&')
+ if (acc) {
+ acc += '&' + arrayParams
+ } else {
+ acc = arrayParams
+ }
+ } else {
+ const separator = acc ? '&' : ''
+ const serializedValue =
+ typeof value === 'object' ? JSON.stringify(value) : value
+ acc += `${separator}${encodeURIComponent(key)}=${encodeURIComponent(serializedValue)}`
+ }
+ }
+ return acc
+ }, '')
+
+ const response = await fetch(
+ `${backendUrl}${url}${params ? `?${params}` : ''}`,
+ {
+ method,
+ credentials: 'include',
+ headers: {
+ 'Content-Type': 'application/json',
+ ...headers,
+ },
+ body: body ? JSON.stringify(body) : null,
+ }
+ )
+
+ if (!response.ok) {
+ const errorData = await response.json()
+
+ if (response.status === 401) {
+ window.location.href = '/login?reason=Unauthorized'
+ return
+ }
+
+ const error = new Error(errorData.message || 'Server error')
+ ;(error as Error & { status: number }).status = response.status
+ throw error
+ }
+
+ return response.json()
+}
+
+export const uploadFilesQuery = async (files: any[]) => {
+ const formData = new FormData()
+
+ for (const { file } of files) {
+ formData.append('files', file)
+ }
+
+ const response = await fetch(`${backendUrl}/vendor/uploads`, {
+ method: 'POST',
+ credentials: 'include',
+ body: formData,
+ })
+
+ if (!response.ok) {
+ return null
+ }
+
+ return response.json()
+}
diff --git a/packages/vendor/src/lib/is-fetch-error.ts b/packages/vendor/src/lib/is-fetch-error.ts
index eff5a3be9..5e41541f6 100644
--- a/packages/vendor/src/lib/is-fetch-error.ts
+++ b/packages/vendor/src/lib/is-fetch-error.ts
@@ -3,3 +3,7 @@ import { ClientError } from "@mercurjs/client"
export const isClientError = (error: any): error is ClientError => {
return error instanceof ClientError
}
+
+export const isFetchError = (error: any): error is Error & { status: number } => {
+ return error instanceof Error && "status" in error
+}
diff --git a/packages/vendor/src/lib/sanitize-number-input.ts b/packages/vendor/src/lib/sanitize-number-input.ts
new file mode 100644
index 000000000..d5458e935
--- /dev/null
+++ b/packages/vendor/src/lib/sanitize-number-input.ts
@@ -0,0 +1,12 @@
+const DISALLOWED_KEYS = ["e", "E", "-", "+"]
+
+export function sanitizeNumberInput(
+ e: React.KeyboardEvent<HTMLInputElement>,
+ disallowedKeys?: string[]
+) {
+ if (
+ [...DISALLOWED_KEYS, ...(disallowedKeys || [])].some((key) => key === e.key)
+ ) {
+ e.preventDefault()
+ }
+}
diff --git a/packages/vendor/src/lib/shipping-options.ts b/packages/vendor/src/lib/shipping-options.ts
index 4a23b6166..65d0ceffd 100644
--- a/packages/vendor/src/lib/shipping-options.ts
+++ b/packages/vendor/src/lib/shipping-options.ts
@@ -21,6 +21,19 @@ export function isOptionEnabledInStore(
/**
* Return a name for the shipping option location or generate one based on the locations address
*/
+export function getShippingProfileName(name: string) {
+ return name.split(":")[1]
+}
+
+export function isSameLocation(
+ shippingOption: HttpTypes.AdminShippingOption,
+ locationId: string
+) {
+ return (
+ shippingOption?.service_zone?.fulfillment_set?.location?.id === locationId
+ )
+}
+
export function getFormattedShippingOptionLocationName(
shippingOption: HttpTypes.AdminShippingOption
) {
diff --git a/packages/vendor/src/lib/storefront.ts b/packages/vendor/src/lib/storefront.ts
index 9bec00983..a7544bc55 100644
--- a/packages/vendor/src/lib/storefront.ts
+++ b/packages/vendor/src/lib/storefront.ts
@@ -1,2 +1,4 @@
+import config from "virtual:mercur/config"
+
export const MEDUSA_STOREFRONT_URL =
- __STOREFRONT_URL__ ?? "http://localhost:8000"
+ config.storefrontUrl ?? "http://localhost:8000"
diff --git a/packages/vendor/src/module.d.ts b/packages/vendor/src/module.d.ts
index 2b0c8f379..ed2da29af 100644
--- a/packages/vendor/src/module.d.ts
+++ b/packages/vendor/src/module.d.ts
@@ -1,6 +1,6 @@
declare module "virtual:mercur/routes" {
- import { RouteObject } from 'react-router-dom'
- const routes: RouteObject[]
+ import { CustomRoute } from './get-route-map'
+ const routes: CustomRoute[]
export default routes
}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/campaign-budget.tsx b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/campaign-budget.tsx
new file mode 100644
index 000000000..4f36791f5
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/campaign-budget.tsx
@@ -0,0 +1,77 @@
+import { ChartPie, PencilSquare } from "@medusajs/icons"
+import { AdminCampaign } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { Trans, useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+
+type CampaignBudgetProps = {
+ campaign: AdminCampaign
+}
+
+export const CampaignBudget = ({ campaign }: CampaignBudgetProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="flex justify-between">
+ <div className="flex-grow">
+ <div className="bg-ui-bg-base shadow-borders-base float-left flex size-7 items-center justify-center rounded-md">
+ <div className="bg-ui-bg-component flex size-6 items-center justify-center rounded-[4px]">
+ <ChartPie className="text-ui-fg-subtle" />
+ </div>
+ </div>
+
+ <Heading
+ className="text-ui-fg-subtle ml-10 mt-[1.5px] font-normal"
+ level="h3"
+ >
+ {t("campaigns.fields.budget_limit")}
+ </Heading>
+ </div>
+
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `edit-budget`,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ <div>
+ <Text
+ className="text-ui-fg-subtle border-ui-border-strong border-l-4 pl-3"
+ size="small"
+ leading="compact"
+ >
+ <Trans
+ i18nKey="campaigns.totalSpend"
+ values={{
+ amount: campaign?.budget?.limit || "no limit",
+ currency:
+ campaign?.budget?.type === "spend" && campaign?.budget.limit
+ ? campaign.budget?.currency_code
+ : "",
+ }}
+ components={[
+ <span
+ key="amount"
+ className="text-ui-fg-base txt-compact-medium-plus text-lg"
+ />,
+ <span
+ key="currency"
+ className="text-ui-fg-base txt-compact-medium-plus text-lg"
+ />,
+ ]}
+ />
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/index.ts
new file mode 100644
index 000000000..bcf0c7fe7
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-budget/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-budget"
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/campaign-configuration-section.tsx b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/campaign-configuration-section.tsx
new file mode 100644
index 000000000..cc6820455
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/campaign-configuration-section.tsx
@@ -0,0 +1,43 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+
+import { PencilSquare } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { DateRangeDisplay } from "@components/common/date-range-display"
+
+type CampaignConfigurationSectionProps = {
+ campaign: HttpTypes.AdminCampaign
+}
+
+export const CampaignConfigurationSection = ({
+ campaign,
+}: CampaignConfigurationSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex flex-col gap-y-4">
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("campaigns.configuration.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: "configuration",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <DateRangeDisplay
+ startsAt={campaign.starts_at}
+ endsAt={campaign.ends_at}
+ showTime
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/index.ts
new file mode 100644
index 000000000..f2071ef92
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-configuration-section/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-configuration-section"
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/campaign-general-section.tsx b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/campaign-general-section.tsx
new file mode 100644
index 000000000..b4336a727
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/campaign-general-section.tsx
@@ -0,0 +1,137 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { AdminCampaignResponse } from "@medusajs/types"
+import {
+ Badge,
+ Container,
+ Heading,
+ StatusBadge,
+ Text,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteCampaign } from "@hooks/api/campaigns"
+import { currencies } from "@lib/data/currencies"
+import {
+ campaignStatus,
+ statusColor,
+} from "../../../common/utils/campaign-status"
+
+type CampaignGeneralSectionProps = {
+ campaign: AdminCampaignResponse["campaign"]
+}
+
+export const CampaignGeneralSection = ({
+ campaign,
+}: CampaignGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+ const { mutateAsync } = useDeleteCampaign(campaign.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("campaigns.delete.title"),
+ description: t("campaigns.delete.description", {
+ name: campaign.name,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("campaigns.delete.successToast", {
+ name: campaign.name,
+ })
+ )
+
+ navigate("/campaigns", { replace: true })
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ const status = campaignStatus(campaign)
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{campaign.name}</Heading>
+
+ <div className="flex items-center gap-x-4">
+ <StatusBadge color={statusColor(status)}>
+ {t(`campaigns.status.${status}`)}
+ </StatusBadge>
+
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/campaigns/${campaign.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("campaigns.fields.identifier")}
+ </Text>
+
+ <Text size="small" leading="compact">
+ {campaign.campaign_identifier}
+ </Text>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.description")}
+ </Text>
+
+ <Text size="small" leading="compact">
+ {campaign.description || "-"}
+ </Text>
+ </div>
+
+ {campaign?.budget && campaign.budget.type === "spend" && (
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.currency")}
+ </Text>
+
+ <div>
+ <Badge size="xsmall">{campaign?.budget.currency_code}</Badge>
+ <Text className="inline pl-3" size="small" leading="compact">
+ {currencies[campaign?.budget.currency_code?.toUpperCase()]?.name}
+ </Text>
+ </div>
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/index.ts
new file mode 100644
index 000000000..0e0d68d08
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-general-section"
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/campaign-promotion-section.tsx b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/campaign-promotion-section.tsx
new file mode 100644
index 000000000..ee63a4fc5
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/campaign-promotion-section.tsx
@@ -0,0 +1,241 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { AdminCampaign, AdminPromotion } from "@medusajs/types"
+import { Button, Checkbox, Container, Heading, usePrompt } from "@medusajs/ui"
+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useRemovePromotionFromCampaign } from "@hooks/api/promotions"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { campaignsQueryKeys } from "@hooks/api/campaigns"
+import { promotionsQueryKeys } from "@hooks/api/promotions"
+import { usePromotionTableColumns } from "@hooks/table/columns/use-promotion-table-columns"
+import { usePromotionTableFilters } from "@hooks/table/filters/use-promotion-table-filters"
+import { usePromotionTableQuery } from "@hooks/table/query/use-promotion-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type CampaignPromotionSectionProps = {
+ campaign: AdminCampaign & { promotions?: AdminPromotion[] }
+}
+
+const PAGE_SIZE = 10
+
+export const CampaignPromotionSection = ({
+ campaign,
+}: CampaignPromotionSectionProps) => {
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const columns = useColumns()
+ const filters = usePromotionTableFilters()
+ const { raw } = usePromotionTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const promotions = campaign.promotions
+ const count = promotions?.length ?? 0
+
+ const { table } = useDataTable({
+ data: promotions ?? [],
+ columns,
+ count,
+ getRowId: (row) => row.id,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ meta: { campaignId: campaign.id },
+ })
+
+ const handleRemove = async () => {
+ const keys = Object.keys(rowSelection)
+
+ const res = await prompt({
+ title: t("campaigns.promotions.remove.title", {
+ count: keys.length,
+ }),
+ description: t("campaigns.promotions.remove.description", {
+ count: keys.length,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ /* Solution below isn't ideal, we should consider making additional backend logic for assigning/unassigning promotions from campaigns, especially batched */
+
+ await Promise.all(
+ keys.map((promotionId) =>
+ fetchQuery(`/vendor/promotions/${promotionId}`, {
+ method: "POST",
+ body: { campaign_id: null },
+ })
+ )
+ )
+
+ queryClient.invalidateQueries({
+ queryKey: campaignsQueryKeys.details(),
+ })
+ queryClient.invalidateQueries({
+ queryKey: promotionsQueryKeys.all,
+ })
+
+ setRowSelection({})
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("promotions.domain")}</Heading>
+ <Link to={`/campaigns/${campaign.id}/add-promotions`}>
+ <Button variant="secondary" size="small">
+ {t("general.add")}
+ </Button>
+ </Link>
+ </div>
+
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ isLoading={false}
+ count={count}
+ navigateTo={(row) => `/promotions/${row.id}`}
+ filters={filters}
+ search
+ pagination
+ orderBy={[
+ { key: "code", label: t("fields.code") },
+ { key: "type", label: t("fields.type") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ commands={[
+ {
+ action: handleRemove,
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ noRecords={{
+ message: t("campaigns.promotions.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const PromotionActions = ({ promotion }: { promotion: AdminPromotion }) => {
+ const { t } = useTranslation()
+ const { mutateAsync } = useRemovePromotionFromCampaign(promotion.id)
+
+ const prompt = usePrompt()
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("campaigns.promotions.remove.title", {
+ count: 1,
+ }),
+ description: t("campaigns.promotions.remove.description", {
+ count: 1,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync()
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/promotions/${promotion.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.remove"),
+ onClick: handleRemove,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdminPromotion>()
+
+const useColumns = () => {
+ const columns = usePromotionTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...columns,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <PromotionActions promotion={row.original} />
+ },
+ }),
+ ],
+ [columns]
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/index.ts
new file mode 100644
index 000000000..7dcc64f5f
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-promotion-section/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-promotion-section"
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/campaign-spend.tsx b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/campaign-spend.tsx
new file mode 100644
index 000000000..b4f61e317
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/campaign-spend.tsx
@@ -0,0 +1,59 @@
+import { CurrencyDollar } from "@medusajs/icons"
+import { AdminCampaign } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { Trans, useTranslation } from "react-i18next"
+
+type CampaignSpendProps = {
+ campaign: AdminCampaign
+}
+
+export const CampaignSpend = ({ campaign }: CampaignSpendProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="mb-2 grid grid-cols-[28px_1fr] items-center gap-x-3">
+ <div className="bg-ui-bg-base shadow-borders-base flex size-7 items-center justify-center rounded-md">
+ <div className="bg-ui-bg-component flex size-6 items-center justify-center rounded-[4px]">
+ <CurrencyDollar className="text-ui-fg-subtle" />
+ </div>
+ </div>
+
+ <Heading level="h3" className="text-ui-fg-subtle font-normal">
+ {campaign.budget?.type === "spend"
+ ? t("campaigns.fields.total_spend")
+ : t("campaigns.fields.total_used")}
+ </Heading>
+ </div>
+
+ <div>
+ <Text
+ className="text-ui-fg-subtle border-ui-border-strong border-l-4 pl-3"
+ size="small"
+ leading="compact"
+ >
+ <Trans
+ i18nKey="campaigns.totalSpend"
+ values={{
+ amount: campaign?.budget?.used || 0,
+ currency:
+ campaign?.budget?.type === "spend"
+ ? campaign?.budget?.currency_code
+ : "",
+ }}
+ components={[
+ <span
+ key="amount"
+ className="text-ui-fg-base txt-compact-medium-plus text-lg"
+ />,
+ <span
+ key="currency"
+ className="text-ui-fg-base txt-compact-medium-plus text-lg"
+ />,
+ ]}
+ />
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/index.ts
new file mode 100644
index 000000000..a2cb55ae2
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/campaign-spend/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-spend"
diff --git a/packages/vendor/src/pages/campaigns/[id]/_components/index.ts b/packages/vendor/src/pages/campaigns/[id]/_components/index.ts
new file mode 100644
index 000000000..484dc36de
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/_components/index.ts
@@ -0,0 +1,5 @@
+export * from "./campaign-budget"
+export * from "./campaign-configuration-section"
+export * from "./campaign-general-section"
+export * from "./campaign-promotion-section"
+export * from "./campaign-spend"
diff --git a/packages/vendor/src/pages/campaigns/[id]/add-promotions/add-campaign-promotions-form.tsx b/packages/vendor/src/pages/campaigns/[id]/add-promotions/add-campaign-promotions-form.tsx
new file mode 100644
index 000000000..f2c2d492a
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/add-promotions/add-campaign-promotions-form.tsx
@@ -0,0 +1,262 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminCampaign, HttpTypes } from "@medusajs/types"
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { RouteFocusModal, useRouteModal } from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useAddOrRemoveCampaignPromotions } from "@hooks/api/campaigns"
+import { usePromotions } from "@hooks/api/promotions"
+import { usePromotionTableColumns } from "@hooks/table/columns/use-promotion-table-columns"
+import { usePromotionTableFilters } from "@hooks/table/filters/use-promotion-table-filters"
+import { usePromotionTableQuery } from "@hooks/table/query/use-promotion-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type AddCampaignPromotionsFormProps = {
+ campaign: AdminCampaign
+}
+
+const AddCampaignPromotionsSchema = zod.object({
+ promotion_ids: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 50
+
+export const AddCampaignPromotionsForm = ({
+ campaign,
+}: AddCampaignPromotionsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof AddCampaignPromotionsSchema>>({
+ defaultValues: { promotion_ids: [] },
+ resolver: zodResolver(AddCampaignPromotionsSchema),
+ })
+
+ const { setValue } = form
+ const { mutateAsync, isPending } = useAddOrRemoveCampaignPromotions(
+ campaign.id
+ )
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+ const ids = Object.keys(state)
+
+ setValue("promotion_ids", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const { searchParams, raw } = usePromotionTableQuery({ pageSize: PAGE_SIZE })
+ const { promotions: promotionsRaw, isPending: isLoading } = usePromotions({
+ ...searchParams,
+ fields: "+status",
+ })
+
+ const promotions = promotionsRaw?.filter((item) => item !== null)
+ const count = promotions?.length ?? 0
+
+ const columns = useColumns()
+ const filters = usePromotionTableFilters()
+
+ const { table } = useDataTable({
+ data: promotions ?? [],
+ columns,
+ enableRowSelection: (row) => {
+ return row.original.campaign_id !== campaign.id
+ },
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ count,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ meta: {
+ campaignId: campaign.id,
+ currencyCode: campaign?.budget?.currency_code,
+ budgetType: campaign?.budget?.type,
+ },
+ })
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ { add: values.promotion_ids },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("campaigns.promotions.toast.success", {
+ count: values.promotion_ids.length,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => toast.error(error.message),
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.promotion_ids && (
+ <Hint variant="error">
+ {form.formState.errors.promotion_ids.message}
+ </Hint>
+ )}
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex size-full flex-col overflow-y-auto">
+ <_DataTable
+ table={table}
+ count={count}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "code", label: t("fields.code") },
+ { key: "type", label: t("fields.type") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ queryObject={raw}
+ layout="fill"
+ pagination
+ search="autofocus"
+ noRecords={{
+ message: t("campaigns.promotions.add.list.noRecordsMessage"),
+ }}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminPromotion>()
+
+const useColumns = () => {
+ const base = usePromotionTableColumns()
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) => table.toggleAllRowsSelected(!!value)}
+ />
+ )
+ },
+ cell: ({ row, table }) => {
+ const { campaignId, currencyCode, budgetType } = table.options
+ .meta as {
+ campaignId: string
+ currencyCode: string
+ budgetType: string
+ }
+
+ const isTypeSpend = budgetType === "spend"
+ const isAdded = row.original.campaign_id === campaignId
+ const isAddedToADiffCampaign =
+ !!row.original.campaign_id &&
+ row.original.campaign_id !== campaignId
+ const currencyMismatch =
+ isTypeSpend &&
+ row.original.application_method?.currency_code !== currencyCode
+ const isSelected = row.getIsSelected() || isAdded
+ const isIndeterminate = currencyMismatch || isAddedToADiffCampaign
+
+ const Component = (
+ <Checkbox
+ checked={isIndeterminate ? "indeterminate" : isSelected}
+ disabled={isAdded || isAddedToADiffCampaign || currencyMismatch}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isAddedToADiffCampaign) {
+ return (
+ <Tooltip
+ content={t("campaigns.promotions.alreadyAddedDiffCampaign", {
+ name: row.original?.campaign?.name!,
+ })}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ if (currencyMismatch) {
+ return (
+ <Tooltip
+ content={t("campaigns.promotions.currencyMismatch")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ if (isAdded) {
+ return (
+ <Tooltip
+ content={t("campaigns.promotions.alreadyAdded")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ ...base,
+ ],
+ [t, base]
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.ts b/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.ts
new file mode 100644
index 000000000..7e4a29e33
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.ts
@@ -0,0 +1 @@
+export * from "./add-campaign-promotions-form"
diff --git a/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.tsx b/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.tsx
new file mode 100644
index 000000000..9157a03e6
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/add-promotions/index.tsx
@@ -0,0 +1,20 @@
+// Route: /campaigns/:id/add-promotions
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useCampaign } from "@hooks/api/campaigns"
+import { AddCampaignPromotionsForm } from "./add-campaign-promotions-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { campaign, isError, error } = useCampaign(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {campaign && <AddCampaignPromotionsForm campaign={campaign} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/campaign-configuration-form.tsx b/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/campaign-configuration-form.tsx
new file mode 100644
index 000000000..72e018c2f
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/campaign-configuration-form.tsx
@@ -0,0 +1,134 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminCampaign } from "@medusajs/types"
+import { Button, DatePicker, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateCampaign } from "@hooks/api/campaigns"
+
+type CampaignConfigurationFormProps = {
+ campaign: AdminCampaign
+}
+
+const CampaignConfigurationSchema = z.object({
+ starts_at: z.date().nullable(),
+ ends_at: z.date().nullable(),
+})
+
+export const CampaignConfigurationForm = ({
+ campaign,
+}: CampaignConfigurationFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof CampaignConfigurationSchema>>({
+ defaultValues: {
+ starts_at: campaign.starts_at ? new Date(campaign.starts_at) : undefined,
+ ends_at: campaign.ends_at ? new Date(campaign.ends_at) : undefined,
+ },
+ resolver: zodResolver(CampaignConfigurationSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateCampaign(campaign.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ starts_at: data.starts_at || null,
+ ends_at: data.ends_at || null,
+ },
+ {
+ onSuccess: ({ campaign }) => {
+ toast.success(
+ t("campaigns.configuration.edit.successToast", {
+ name: campaign.name,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="starts_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.start_date")}</Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ hourCycle={12}
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="ends_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.end_date")}</Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button
+ isLoading={isPending}
+ type="submit"
+ variant="primary"
+ size="small"
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/index.ts b/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/index.ts
new file mode 100644
index 000000000..b6f67aaae
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/configuration/campaign-configuration-form/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-configuration-form"
diff --git a/packages/vendor/src/pages/campaigns/[id]/configuration/index.tsx b/packages/vendor/src/pages/campaigns/[id]/configuration/index.tsx
new file mode 100644
index 000000000..315734440
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/configuration/index.tsx
@@ -0,0 +1,34 @@
+// Route: /campaigns/:id/configuration
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCampaign } from "@hooks/api/campaigns"
+import { CampaignConfigurationForm } from "./campaign-configuration-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ const { id } = useParams()
+ const { campaign, isLoading, isError, error } = useCampaign(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("campaigns.configuration.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("campaigns.configuration.edit.description")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {!isLoading && campaign && (
+ <CampaignConfigurationForm campaign={campaign} />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/constants.ts b/packages/vendor/src/pages/campaigns/[id]/constants.ts
new file mode 100644
index 000000000..777c758fd
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/constants.ts
@@ -0,0 +1 @@
+export const CAMPAIGN_DETAIL_FIELDS = "*promotions"
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/edit-campaign-budget-form.tsx b/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/edit-campaign-budget-form.tsx
new file mode 100644
index 000000000..f82f0352c
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/edit-campaign-budget-form.tsx
@@ -0,0 +1,138 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminCampaign } from "@medusajs/types"
+import { Button, CurrencyInput, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateCampaign } from "@hooks/api/campaigns"
+import { getCurrencySymbol } from "@lib/data/currencies"
+
+type EditCampaignBudgetFormProps = {
+ campaign: AdminCampaign
+}
+
+const EditCampaignSchema = zod.object({
+ limit: zod.number().min(0).optional().nullable(),
+})
+
+export const EditCampaignBudgetForm = ({
+ campaign,
+}: EditCampaignBudgetFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditCampaignSchema>>({
+ defaultValues: {
+ limit: campaign?.budget?.limit || undefined,
+ },
+ resolver: zodResolver(EditCampaignSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateCampaign(campaign.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ budget: {
+ limit: data.limit ? data.limit : null,
+ },
+ },
+ {
+ onSuccess: ({ campaign }) => {
+ toast.success(
+ t("campaigns.edit.successToast", {
+ name: campaign.name,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="limit"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Label>
+ {t("campaigns.budget.fields.limit")}
+ </Form.Label>
+
+ <Form.Control>
+ {campaign.budget?.type === "spend" ? (
+ <CurrencyInput
+ min={0}
+ onValueChange={(value) =>
+ onChange(value ? parseInt(value) : null)
+ }
+ code={campaign.budget?.currency_code}
+ symbol={
+ campaign.budget?.currency_code
+ ? getCurrencySymbol(
+ campaign.budget?.currency_code
+ )
+ : ""
+ }
+ {...field}
+ value={value || undefined}
+ />
+ ) : (
+ <Input
+ key="usage"
+ min={0}
+ {...field}
+ value={value || undefined}
+ onChange={(e) => {
+ onChange(
+ e.target.value === ""
+ ? null
+ : parseInt(e.target.value)
+ )
+ }}
+ />
+ )}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button
+ isLoading={isPending}
+ type="submit"
+ variant="primary"
+ size="small"
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/index.ts b/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/index.ts
new file mode 100644
index 000000000..4dcee0c54
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit-budget/edit-campaign-budget-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-campaign-budget-form"
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit-budget/index.tsx b/packages/vendor/src/pages/campaigns/[id]/edit-budget/index.tsx
new file mode 100644
index 000000000..2a5304c53
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit-budget/index.tsx
@@ -0,0 +1,30 @@
+// Route: /campaigns/:id/edit-budget
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCampaign } from "@hooks/api/campaigns"
+import { EditCampaignBudgetForm } from "./edit-campaign-budget-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ const { id } = useParams()
+ const { campaign, isLoading, isError, error } = useCampaign(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("campaigns.budget.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+
+ {!isLoading && campaign && <EditCampaignBudgetForm campaign={campaign} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/edit-campaign-form.tsx b/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/edit-campaign-form.tsx
new file mode 100644
index 000000000..fc8271b5f
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/edit-campaign-form.tsx
@@ -0,0 +1,194 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminCampaign } from "@medusajs/types"
+import { Button, DatePicker, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateCampaign } from "@hooks/api/campaigns"
+
+type EditCampaignFormProps = {
+ campaign: AdminCampaign
+}
+
+const EditCampaignSchema = zod.object({
+ name: zod.string(),
+ description: zod.string().optional(),
+ campaign_identifier: zod.string().optional(),
+ starts_at: zod.date().optional(),
+ ends_at: zod.date().optional(),
+})
+
+export const EditCampaignForm = ({ campaign }: EditCampaignFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditCampaignSchema>>({
+ defaultValues: {
+ name: campaign.name || "",
+ description: campaign.description || "",
+ campaign_identifier: campaign.campaign_identifier || "",
+ starts_at: campaign.starts_at ? new Date(campaign.starts_at) : undefined,
+ ends_at: campaign.ends_at ? new Date(campaign.ends_at) : undefined,
+ },
+ resolver: zodResolver(EditCampaignSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateCampaign(campaign.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ name: data.name,
+ description: data.description,
+ campaign_identifier: data.campaign_identifier,
+ starts_at: data.starts_at,
+ ends_at: data.ends_at,
+ },
+ {
+ onSuccess: ({ campaign }) => {
+ toast.success(
+ t("campaigns.edit.successToast", {
+ name: campaign.name,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.description")}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="campaign_identifier"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.identifier")}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="starts_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.start_date")}</Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ hourCycle={12}
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="ends_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.end_date")}</Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button
+ isLoading={isPending}
+ type="submit"
+ variant="primary"
+ size="small"
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/index.ts b/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/index.ts
new file mode 100644
index 000000000..3008a60d0
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit/edit-campaign-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-campaign-form"
diff --git a/packages/vendor/src/pages/campaigns/[id]/edit/index.tsx b/packages/vendor/src/pages/campaigns/[id]/edit/index.tsx
new file mode 100644
index 000000000..e54f36c56
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/edit/index.tsx
@@ -0,0 +1,34 @@
+// Route: /campaigns/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { VisuallyHidden } from "@components/utilities/visually-hidden"
+import { useCampaign } from "@hooks/api/campaigns"
+import { EditCampaignForm } from "./edit-campaign-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ const { id } = useParams()
+ const { campaign, isLoading, isError, error } = useCampaign(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("campaigns.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description asChild>
+ <VisuallyHidden>{t("campaigns.edit.description")}</VisuallyHidden>
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+
+ {!isLoading && campaign && <EditCampaignForm campaign={campaign} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/[id]/index.tsx b/packages/vendor/src/pages/campaigns/[id]/index.tsx
new file mode 100644
index 000000000..3a720c7d3
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/[id]/index.tsx
@@ -0,0 +1,105 @@
+// Route: /campaigns/:id
+import { useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useCampaign, campaignsQueryKeys } from "@hooks/api/campaigns"
+import { usePromotionTableQuery } from "@hooks/table/query/use-promotion-table-query"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { CampaignBudget } from "./_components/campaign-budget"
+import { CampaignConfigurationSection } from "./_components/campaign-configuration-section"
+import { CampaignGeneralSection } from "./_components/campaign-general-section"
+import { CampaignPromotionSection } from "./_components/campaign-promotion-section"
+import { CampaignSpend } from "./_components/campaign-spend"
+import { CAMPAIGN_DETAIL_FIELDS } from "./constants"
+
+const campaignDetailQuery = (id: string) => ({
+ queryKey: campaignsQueryKeys.detail(id, { fields: CAMPAIGN_DETAIL_FIELDS }),
+ queryFn: async () =>
+ fetchQuery(`/vendor/campaigns/${id}`, {
+ method: "GET",
+ query: {
+ fields: CAMPAIGN_DETAIL_FIELDS,
+ },
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = campaignDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
+
+type CampaignDetailBreadcrumbProps = UIMatch<HttpTypes.AdminCampaignResponse>
+
+export const Breadcrumb = (props: CampaignDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { campaign } = useCampaign(
+ id!,
+ {
+ fields: CAMPAIGN_DETAIL_FIELDS,
+ },
+ {
+ initialData: props.data,
+ enabled: Boolean(id),
+ }
+ )
+
+ if (!campaign) {
+ return null
+ }
+
+ return <span>{campaign.name}</span>
+}
+
+export const Component = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+
+ const { id } = useParams()
+ const { searchParams } = usePromotionTableQuery({})
+ const { campaign, isLoading, isError, error } = useCampaign(
+ id!,
+ { ...searchParams, fields: CAMPAIGN_DETAIL_FIELDS },
+ {
+ placeholderData: initialData,
+ }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !campaign) {
+ return <TwoColumnPageSkeleton mainSections={2} sidebarSections={3} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("campaign.details.after"),
+ before: getWidgets("campaign.details.before"),
+ sideAfter: getWidgets("campaign.details.side.after"),
+ sideBefore: getWidgets("campaign.details.side.before"),
+ }}
+ hasOutlet
+ data={campaign}
+ >
+ <TwoColumnPage.Main>
+ <CampaignGeneralSection campaign={campaign} />
+ <CampaignPromotionSection campaign={campaign} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <CampaignConfigurationSection campaign={campaign} />
+ <CampaignSpend campaign={campaign} />
+ <CampaignBudget campaign={campaign} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/_components/campaign-list-table.tsx b/packages/vendor/src/pages/campaigns/_components/campaign-list-table.tsx
new file mode 100644
index 000000000..2f9325843
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/_components/campaign-list-table.tsx
@@ -0,0 +1,157 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { AdminCampaign } from "@medusajs/types"
+import { Button, Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import {
+ useCampaigns,
+ useDeleteCampaign,
+} from "@hooks/api/campaigns"
+import { useCampaignTableColumns } from "@hooks/table/columns/use-campaign-table-columns"
+import { useCampaignTableQuery } from "@hooks/table/query/use-campaign-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const CampaignListTable = () => {
+ const { t } = useTranslation()
+ const { raw, searchParams } = useCampaignTableQuery({ pageSize: PAGE_SIZE })
+
+ const {
+ campaigns,
+ count,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useCampaigns(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: campaigns ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("campaigns.domain")}</Heading>
+ <Link to="/campaigns/create">
+ <Button size="small" variant="secondary">
+ {t("actions.create")}
+ </Button>
+ </Link>
+ </div>
+
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ pagination
+ search
+ navigateTo={(row) => row.id}
+ isLoading={isLoading}
+ queryObject={raw}
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ />
+ </Container>
+ )
+}
+
+const CampaignActions = ({ campaign }: { campaign: AdminCampaign }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteCampaign(campaign.id)
+
+ const handleDelete = async () => {
+ const confirm = await prompt({
+ title: t("general.areYouSure"),
+ description: t("campaigns.deleteCampaignWarning", {
+ name: campaign.name,
+ }),
+ verificationInstruction: t("general.typeToConfirm"),
+ verificationText: campaign.name,
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!confirm) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("campaigns.delete.successToast", { name: campaign.name })
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/campaigns/${campaign.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<AdminCampaign>()
+
+const useColumns = () => {
+ const base = useCampaignTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <CampaignActions campaign={row.original} />
+ },
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/_components/index.ts b/packages/vendor/src/pages/campaigns/_components/index.ts
new file mode 100644
index 000000000..fbd56f6be
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/_components/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-list-table"
diff --git a/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/create-campaign-form-fields.tsx b/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/create-campaign-form-fields.tsx
new file mode 100644
index 000000000..6239316c6
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/create-campaign-form-fields.tsx
@@ -0,0 +1,367 @@
+import {
+ CurrencyInput,
+ DatePicker,
+ Heading,
+ Input,
+ RadioGroup,
+ Select,
+ Text,
+ Textarea,
+} from "@medusajs/ui"
+import { useEffect } from "react"
+import { Path, PathValue, UseFormReturn, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { useStore } from "@hooks/api/store"
+import {
+ currencies,
+ getCurrencySymbol,
+} from "@lib/data/currencies"
+import { CampaignFormFields, WithNestedCampaign } from "@custom-types/campaign"
+
+
+type CreateCampaignFormFieldsProps<T extends CampaignFormFields | WithNestedCampaign> = {
+ form: UseFormReturn<T>
+ fieldScope?: string
+}
+
+export const CreateCampaignFormFields = <T extends CampaignFormFields | WithNestedCampaign>({
+ form,
+ fieldScope = ""
+}: CreateCampaignFormFieldsProps<T>) => {
+
+ const { t } = useTranslation()
+ const { store } = useStore()
+
+ const watchValueType = useWatch({
+ control: form.control,
+ name: `${fieldScope}budget.type` as Path<T>,
+ })
+
+ const isTypeSpend = watchValueType === "spend"
+
+ const currencyValue = useWatch({
+ control: form.control,
+ name: `${fieldScope}budget.currency_code` as Path<T>,
+ })
+
+ const promotionCurrencyValue = useWatch({
+ control: form.control,
+ name: `application_method.currency_code` as Path<T>,
+ })
+
+ const currency = currencyValue || promotionCurrencyValue
+
+ useEffect(() => {
+ form.resetField(`${fieldScope}budget.limit` as Path<T>)
+
+ if (fieldScope) {
+ const currencyPath = `campaign.budget.currency_code` as Path<T>
+
+ if (isTypeSpend && promotionCurrencyValue) {
+ const currencyValue = promotionCurrencyValue as PathValue<T, typeof currencyPath>
+ form.setValue(currencyPath, currencyValue)
+ } else if (watchValueType === "usage") {
+ const nullValue = null as PathValue<T, typeof currencyPath>
+ form.setValue(currencyPath, nullValue)
+ }
+ }
+ }, [watchValueType, fieldScope, form, isTypeSpend, promotionCurrencyValue])
+
+ if (promotionCurrencyValue && fieldScope) {
+ const formValues = form.getValues()
+ const budget = (formValues as WithNestedCampaign)?.campaign?.budget
+
+ if (
+ budget?.type === "spend" &&
+ budget?.currency_code !== promotionCurrencyValue
+ ) {
+ const currencyPath = "campaign.budget.currency_code" as Path<T>
+ form.setValue(currencyPath, promotionCurrencyValue)
+ }
+ }
+
+ return (
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <Heading>{t("campaigns.create.header")}</Heading>
+
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("campaigns.create.hint")}
+ </Text>
+ </div>
+
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}name` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} value={(field.value as string) ?? ""} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}campaign_identifier` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("campaigns.fields.identifier")}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} value={(field.value as string) ?? ""} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}description` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.description")}</Form.Label>
+
+ <Form.Control>
+ <Textarea {...field} value={(field.value as string) ?? ""} />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}starts_at` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("campaigns.fields.start_date")}
+ </Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ value={field.value as Date | null | undefined}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}ends_at` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("campaigns.fields.end_date")}
+ </Form.Label>
+
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ value={field.value as Date | null | undefined}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <div>
+ <Heading>{t("campaigns.budget.create.header")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("campaigns.budget.create.hint")}
+ </Text>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}budget.type` as Path<T>}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={
+ fieldScope?.length && !currency
+ ? t("promotions.tooltips.campaignType")
+ : undefined
+ }
+ >
+ {t("campaigns.budget.fields.type")}
+ </Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ value={field.value as string}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={"usage"}
+ label={t("campaigns.budget.type.usage.title")}
+ description={t("campaigns.budget.type.usage.description")}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={"spend"}
+ label={t("campaigns.budget.type.spend.title")}
+ description={t("campaigns.budget.type.spend.description")}
+ disabled={fieldScope?.length ? !currency : false}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ {isTypeSpend && (
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}budget.currency_code` as Path<T>}
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={
+ fieldScope?.length && !currency
+ ? t("promotions.campaign_currency.tooltip")
+ : undefined
+ }
+ >
+ {t("fields.currency")}
+ </Form.Label>
+ <Form.Control>
+ <Select
+ {...field}
+ value={field.value as string}
+ onValueChange={onChange}
+ disabled={!!fieldScope?.length}
+ >
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+
+ <Select.Content>
+ {Object.values(currencies)
+ .filter(
+ (currency) =>
+ !!store?.supported_currencies?.find(
+ (c) =>
+ c.currency_code ===
+ currency.code.toLocaleLowerCase()
+ )
+ )
+ .map((currency) => (
+ <Select.Item
+ value={currency.code.toLowerCase()}
+ key={currency.code}
+ >
+ {currency.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ <Form.Field
+ control={form.control}
+ name={`${fieldScope}budget.limit` as Path<T>}
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Label
+ tooltip={
+ !currency && isTypeSpend
+ ? t("promotions.fields.amount.tooltip")
+ : undefined
+ }
+ >
+ {t("campaigns.budget.fields.limit")}
+ </Form.Label>
+
+ <Form.Control>
+ {isTypeSpend ? (
+ <CurrencyInput
+ min={0}
+ onValueChange={(value) =>
+ onChange(value ? parseInt(value) : "")
+ }
+ code={currencyValue as string}
+ symbol={
+ currencyValue ? getCurrencySymbol(currencyValue as string) : ""
+ }
+ {...field}
+ value={value as string | number | undefined}
+ disabled={!currency && isTypeSpend}
+ />
+ ) : (
+ <Input
+ type="number"
+ key="usage"
+ {...field}
+ min={0}
+ value={value as string | number | undefined ?? ""}
+ onChange={(e) => {
+ onChange(
+ e.target.value === ""
+ ? null
+ : parseInt(e.target.value)
+ )
+ }}
+ />
+ )}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/index.ts b/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/index.ts
new file mode 100644
index 000000000..409513f53
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/common/components/create-campaign-form-fields/index.ts
@@ -0,0 +1 @@
+export { CreateCampaignFormFields } from "./create-campaign-form-fields"
\ No newline at end of file
diff --git a/packages/vendor/src/pages/campaigns/common/constants.ts b/packages/vendor/src/pages/campaigns/common/constants.ts
new file mode 100644
index 000000000..401d086f8
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/common/constants.ts
@@ -0,0 +1,14 @@
+import { CampaignBudgetTypeValues } from "@medusajs/types"
+
+export const DEFAULT_CAMPAIGN_VALUES = {
+ name: "",
+ description: "",
+ campaign_identifier: "",
+ starts_at: null,
+ ends_at: null,
+ budget: {
+ type: "usage" as CampaignBudgetTypeValues,
+ currency_code: null,
+ limit: null,
+ },
+}
diff --git a/packages/vendor/src/pages/campaigns/common/utils/campaign-status.ts b/packages/vendor/src/pages/campaigns/common/utils/campaign-status.ts
new file mode 100644
index 000000000..3a8384068
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/common/utils/campaign-status.ts
@@ -0,0 +1,31 @@
+import { AdminCampaign } from "@medusajs/types"
+import { isAfter, isBefore } from "date-fns"
+
+export function campaignStatus(campaign: AdminCampaign) {
+ if (campaign.ends_at) {
+ if (isBefore(new Date(campaign.ends_at), new Date())) {
+ return "expired"
+ }
+ }
+
+ if (campaign.starts_at) {
+ if (isAfter(new Date(campaign.starts_at), new Date())) {
+ return "scheduled"
+ }
+ }
+
+ return "active"
+}
+
+export const statusColor = (status: string) => {
+ switch (status) {
+ case "expired":
+ return "red"
+ case "scheduled":
+ return "orange"
+ case "active":
+ return "green"
+ default:
+ return "grey"
+ }
+}
diff --git a/packages/vendor/src/pages/campaigns/create/create-campaign-form/create-campaign-form.tsx b/packages/vendor/src/pages/campaigns/create/create-campaign-form/create-campaign-form.tsx
new file mode 100644
index 000000000..10c059290
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/create/create-campaign-form/create-campaign-form.tsx
@@ -0,0 +1,107 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { VisuallyHidden } from "@components/utilities/visually-hidden"
+import { useCreateCampaign } from "@hooks/api/campaigns"
+import { CreateCampaignFormFields } from "../../common/components/create-campaign-form-fields"
+import { DEFAULT_CAMPAIGN_VALUES } from "../../common/constants"
+
+export const CreateCampaignSchema = zod.object({
+ name: zod.string().min(1),
+ description: zod.string().optional(),
+ campaign_identifier: zod.string().min(1),
+ starts_at: zod.date().nullable(),
+ ends_at: zod.date().nullable(),
+ budget: zod.object({
+ limit: zod.number().min(0).nullish(),
+ type: zod.enum(["spend", "usage"]),
+ currency_code: zod.string().nullish(),
+ }),
+})
+
+export const CreateCampaignForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { mutateAsync, isPending } = useCreateCampaign()
+
+ const form = useForm<zod.infer<typeof CreateCampaignSchema>>({
+ defaultValues: DEFAULT_CAMPAIGN_VALUES,
+ resolver: zodResolver(CreateCampaignSchema),
+ })
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ name: data.name,
+ description: data.description,
+ campaign_identifier: data.campaign_identifier,
+ starts_at: data.starts_at,
+ ends_at: data.ends_at,
+ budget: {
+ type: data.budget.type,
+ limit: data.budget.limit ? data.budget.limit : undefined,
+ currency_code: data.budget.currency_code,
+ },
+ },
+ {
+ onSuccess: ({ campaign }) => {
+ toast.success(
+ t("campaigns.create.successToast", {
+ name: campaign.name,
+ })
+ )
+ handleSuccess(`/campaigns/${campaign.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex size-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <RouteFocusModal.Title asChild>
+ <VisuallyHidden>{t("campaigns.create.title")}</VisuallyHidden>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <VisuallyHidden>{t("campaigns.create.description")}</VisuallyHidden>
+ </RouteFocusModal.Description>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex size-full flex-col items-center overflow-auto py-16">
+ <CreateCampaignFormFields form={form} />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ variant="primary"
+ type="submit"
+ isLoading={isPending}
+ >
+ {t("actions.create")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/create/create-campaign-form/index.ts b/packages/vendor/src/pages/campaigns/create/create-campaign-form/index.ts
new file mode 100644
index 000000000..1de588963
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/create/create-campaign-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-campaign-form"
diff --git a/packages/vendor/src/pages/campaigns/create/index.tsx b/packages/vendor/src/pages/campaigns/create/index.tsx
new file mode 100644
index 000000000..2e443cab5
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/create/index.tsx
@@ -0,0 +1,11 @@
+// Route: /campaigns/create
+import { RouteFocusModal } from "@components/modals"
+import { CreateCampaignForm } from "./create-campaign-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreateCampaignForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/campaigns/index.tsx b/packages/vendor/src/pages/campaigns/index.tsx
new file mode 100644
index 000000000..70f992859
--- /dev/null
+++ b/packages/vendor/src/pages/campaigns/index.tsx
@@ -0,0 +1,20 @@
+// Route: /campaigns
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { CampaignListTable } from "./_components/campaign-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("campaign.list.after"),
+ before: getWidgets("campaign.list.before"),
+ }}
+ hasOutlet
+ >
+ <CampaignListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-general-section/category-general-section.tsx b/packages/vendor/src/pages/categories/[id]/_components/category-general-section/category-general-section.tsx
new file mode 100644
index 000000000..eac50a6a0
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-general-section/category-general-section.tsx
@@ -0,0 +1,36 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+type CategoryGeneralSectionProps = {
+ category: HttpTypes.AdminProductCategory
+}
+
+export const CategoryGeneralSection = ({
+ category,
+}: CategoryGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{category.name}</Heading>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 gap-3 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.description")}
+ </Text>
+ <Text size="small" leading="compact">
+ {category.description || "-"}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 gap-3 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.handle")}
+ </Text>
+ <Text size="small" leading="compact">
+ /{category.handle}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-general-section/index.ts b/packages/vendor/src/pages/categories/[id]/_components/category-general-section/index.ts
new file mode 100644
index 000000000..d3f09e090
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./category-general-section"
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/category-organize-section.tsx b/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/category-organize-section.tsx
new file mode 100644
index 000000000..8f3d5f922
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/category-organize-section.tsx
@@ -0,0 +1,198 @@
+import { FolderIllustration, TriangleRightMini } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Badge, Container, Heading, Text, Tooltip } from "@medusajs/ui"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { LinkButton } from "@components/common/link-button"
+import { Skeleton } from "@components/common/skeleton"
+import { useProductCategory } from "@hooks/api/categories"
+import { getCategoryChildren, getCategoryPath } from "../../../common/utils"
+
+type CategoryOrganizeSectionProps = {
+ category: HttpTypes.AdminProductCategory
+}
+
+export const CategoryOrganizeSection = ({
+ category,
+}: CategoryOrganizeSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("categories.organize.header")}</Heading>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start gap-3 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("categories.fields.path.label")}
+ </Text>
+ <PathDisplay category={category} />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start gap-3 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("categories.fields.children.label")}
+ </Text>
+ <ChildrenDisplay category={category} />
+ </div>
+ </Container>
+ )
+}
+
+const PathDisplay = ({
+ category,
+}: {
+ category: HttpTypes.AdminProductCategory
+}) => {
+ const [expanded, setExpanded] = useState(false)
+
+ const { t } = useTranslation()
+
+ const {
+ product_category: withParents,
+ isLoading,
+ isError,
+ error,
+ } = useProductCategory(category.id, {
+ include_ancestors_tree: true,
+ fields: "id,name,*parent_category",
+ })
+
+ const chips = useMemo(() => getCategoryPath(withParents), [withParents])
+
+ if (isLoading || !withParents) {
+ return <Skeleton className="h-5 w-16" />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ if (!chips.length) {
+ return (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )
+ }
+
+ if (chips.length > 1 && !expanded) {
+ return (
+ <div className="grid grid-cols-[20px_1fr] items-start gap-x-2">
+ <FolderIllustration />
+ <div className="flex w-full items-center gap-x-0.5 overflow-hidden">
+ <Tooltip content={t("categories.fields.path.tooltip")}>
+ <button
+ className="outline-none"
+ type="button"
+ onClick={() => setExpanded(true)}
+ >
+ <Text size="xsmall" leading="compact" weight="plus">
+ ...
+ </Text>
+ </button>
+ </Tooltip>
+ <div className="flex size-[15px] shrink-0 items-center justify-center">
+ <TriangleRightMini />
+ </div>
+ <Text
+ size="xsmall"
+ leading="compact"
+ weight="plus"
+ className="truncate"
+ >
+ {chips[chips.length - 1].name}
+ </Text>
+ </div>
+ </div>
+ )
+ }
+
+ if (chips.length > 1 && expanded) {
+ return (
+ <div className="grid grid-cols-[20px_1fr] items-start gap-x-2">
+ <FolderIllustration />
+ <div className="gap- flex flex-wrap items-center gap-x-0.5 gap-y-1">
+ {chips.map((chip, index) => {
+ return (
+ <div key={chip.id} className="flex items-center gap-x-0.5">
+ {index === chips.length - 1 ? (
+ <Text size="xsmall" leading="compact" weight="plus">
+ {chip.name}
+ </Text>
+ ) : (
+ <LinkButton
+ to={`/categories/${chip.id}`}
+ className="txt-compact-xsmall-plus text-ui-fg-subtle hover:text-ui-fg-base focus-visible:text-ui-fg-base"
+ >
+ {chip.name}
+ </LinkButton>
+ )}
+ {index < chips.length - 1 && <TriangleRightMini />}
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+ }
+
+ return (
+ <div className="grid grid-cols-1 items-start gap-x-2">
+ {chips.map((chip, index) => (
+ <div key={chip.id} className="flex items-center gap-x-0.5">
+ <Text size="xsmall" leading="compact" weight="plus">
+ {chip.name}
+ </Text>
+ {index < chips.length - 1 && <TriangleRightMini />}
+ </div>
+ ))}
+ </div>
+ )
+}
+
+const ChildrenDisplay = ({
+ category,
+}: {
+ category: HttpTypes.AdminProductCategory
+}) => {
+ const {
+ product_category: withChildren,
+ isLoading,
+ isError,
+ error,
+ } = useProductCategory(category.id, {
+ include_descendants_tree: true,
+ fields: "id,name,category_children",
+ })
+
+ const chips = useMemo(() => getCategoryChildren(withChildren), [withChildren])
+
+ if (isLoading || !withChildren) {
+ return <Skeleton className="h-5 w-16" />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ if (!chips.length) {
+ return (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )
+ }
+
+ return (
+ <div className="flex w-full flex-wrap gap-1">
+ {chips.map((chip) => (
+ <Badge key={chip.id} size="2xsmall" className="max-w-full" asChild>
+ <Link to={`/categories/${chip.id}`}>
+ <span className="truncate">{chip.name}</span>
+ </Link>
+ </Badge>
+ ))}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/index.ts b/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/index.ts
new file mode 100644
index 000000000..6271191dd
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-organize-section/index.ts
@@ -0,0 +1 @@
+export * from "./category-organize-section"
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-product-section/category-product-section.tsx b/packages/vendor/src/pages/categories/[id]/_components/category-product-section/category-product-section.tsx
new file mode 100644
index 000000000..08cad14aa
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-product-section/category-product-section.tsx
@@ -0,0 +1,209 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { RowSelectionState } from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type CategoryProductSectionProps = {
+ category: HttpTypes.AdminProductCategory
+}
+
+const PAGE_SIZE = 10
+
+export const CategoryProductSection = ({
+ category,
+}: CategoryProductSectionProps) => {
+ const { t } = useTranslation()
+
+ const [selection, setSelection] = useState<RowSelectionState>({})
+
+ const { raw, searchParams } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { products, count, isLoading, isError, error } = useProducts(
+ {
+ ...searchParams,
+ fields: "*categories.id",
+ // limit: 9999,
+ limit: searchParams.limit,
+ offset: searchParams.offset,
+ category_id: category.id,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: Array.isArray(products)
+ ? products.map((p) => ({
+ ...p,
+ images: p.images ?? null,
+ }))
+ : [],
+ columns,
+ count,
+ getRowId: (original) => original.id,
+ pageSize: PAGE_SIZE,
+ enableRowSelection: true,
+ enablePagination: true,
+ rowSelection: {
+ state: selection,
+ updater: setSelection,
+ },
+ })
+
+ // Not used, there's a lot of commented code, leaving it commented for future
+ // const { mutateAsync } = useUpdateProductCategoryProducts(category.id)
+
+ // const handleRemove = async () => {
+ // const selected = Object.keys(selection)
+
+ // const res = await prompt({
+ // title: t("general.areYouSure"),
+ // description: t("categories.products.remove.confirmation", {
+ // count: selected.length,
+ // }),
+ // confirmText: t("actions.remove"),
+ // cancelText: t("actions.cancel"),
+ // })
+
+ // if (!res) {
+ // return
+ // }
+
+ // await mutateAsync(
+ // {
+ // remove: selected,
+ // },
+ // {
+ // onSuccess: () => {
+ // toast.success(
+ // t("categories.products.remove.successToast", {
+ // count: selected.length,
+ // })
+ // )
+
+ // setSelection({})
+ // },
+ // onError: (error) => {
+ // toast.error(error.message)
+ // },
+ // }
+ // )
+ // }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.domain")}</Heading>
+ {/* <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.add"),
+ icon: <PlusMini />,
+ to: "products",
+ },
+ ],
+ },
+ ]}
+ /> */}
+ </div>
+ <_DataTable
+ table={table}
+ // filters={filters}
+ columns={columns}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ pageSize={PAGE_SIZE}
+ count={count}
+ navigateTo={(row) => `/products/${row.id}`}
+ isLoading={isLoading}
+ queryObject={raw}
+ noRecords={{
+ message: t("categories.products.list.noRecordsMessage"),
+ }}
+ />
+ {/* <CommandBar open={!!Object.keys(selection).length}>
+ <CommandBar.Bar>
+ <CommandBar.Value>
+ {t("general.countSelected", {
+ count: Object.keys(selection).length,
+ })}
+ </CommandBar.Value>
+ <CommandBar.Seperator />
+ <CommandBar.Command
+ action={handleRemove}
+ label={t("actions.remove")}
+ shortcut="r"
+ />
+ </CommandBar.Bar>
+ </CommandBar> */}
+ </Container>
+ )
+}
+
+// const columnHelper = createColumnHelper<HttpTypes.AdminProduct>()
+
+const useColumns = () => {
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ // columnHelper.display({
+ // id: "select",
+ // header: ({ table }) => {
+ // return (
+ // <Checkbox
+ // checked={
+ // table.getIsSomePageRowsSelected()
+ // ? "indeterminate"
+ // : table.getIsAllPageRowsSelected()
+ // }
+ // onCheckedChange={(value) =>
+ // table.toggleAllPageRowsSelected(!!value)
+ // }
+ // />
+ // )
+ // },
+ // cell: ({ row }) => {
+ // return (
+ // <Checkbox
+ // checked={row.getIsSelected()}
+ // onCheckedChange={(value) => row.toggleSelected(!!value)}
+ // onClick={(e) => {
+ // e.stopPropagation()
+ // }}
+ // />
+ // )
+ // },
+ // }),
+ ...base,
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/_components/category-product-section/index.ts b/packages/vendor/src/pages/categories/[id]/_components/category-product-section/index.ts
new file mode 100644
index 000000000..c66de67a1
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/category-product-section/index.ts
@@ -0,0 +1 @@
+export * from "./category-product-section"
diff --git a/packages/vendor/src/pages/categories/[id]/_components/index.ts b/packages/vendor/src/pages/categories/[id]/_components/index.ts
new file mode 100644
index 000000000..896f5dab7
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/_components/index.ts
@@ -0,0 +1,3 @@
+export * from "./category-general-section"
+export * from "./category-organize-section"
+export * from "./category-product-section"
diff --git a/packages/vendor/src/pages/categories/[id]/index.tsx b/packages/vendor/src/pages/categories/[id]/index.tsx
new file mode 100644
index 000000000..749fe9b27
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/index.tsx
@@ -0,0 +1,100 @@
+// Route: /categories/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useProductCategory } from "@hooks/api"
+import { categoriesQueryKeys } from "@hooks/api/categories"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { CategoryGeneralSection } from "./_components/category-general-section"
+import { CategoryOrganizeSection } from "./_components/category-organize-section"
+import { CategoryProductSection } from "./_components/category-product-section"
+
+// Loader
+const categoryDetailQuery = (id: string) => ({
+ queryKey: categoriesQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/product-categories/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = categoryDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type CategoryDetailBreadcrumbProps = UIMatch<HttpTypes.AdminProductCategoryResponse>
+
+export const Breadcrumb = (props: CategoryDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { product_category } = useProductCategory(
+ id!,
+ { fields: "name" },
+ { initialData: props.data, enabled: Boolean(id) }
+ )
+
+ if (!product_category) {
+ return null
+ }
+
+ return <span>{product_category.name}</span>
+}
+
+// Main component
+export const Component = () => {
+ const { id } = useParams()
+ const { getWidgets } = useDashboardExtension()
+
+ const {
+ product_category,
+ isLoading: categoryLoading,
+ isError: categoryError,
+ error,
+ } = useProductCategory(id!, {
+ fields: "+is_active,+is_internal",
+ })
+
+ if (categoryLoading || !product_category) {
+ return (
+ <TwoColumnPageSkeleton
+ mainSections={2}
+ sidebarSections={1}
+ showJSON
+ showMetadata
+ />
+ )
+ }
+
+ if (categoryError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("product_category.details.after"),
+ before: getWidgets("product_category.details.before"),
+ sideAfter: getWidgets("product_category.details.side.after"),
+ sideBefore: getWidgets("product_category.details.side.before"),
+ }}
+ data={product_category}
+ >
+ <TwoColumnPage.Main>
+ <CategoryGeneralSection category={product_category} />
+ <CategoryProductSection category={product_category} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <CategoryOrganizeSection category={product_category} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/metadata/index.tsx b/packages/vendor/src/pages/categories/[id]/metadata/index.tsx
new file mode 100644
index 000000000..5888d126e
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/metadata/index.tsx
@@ -0,0 +1,27 @@
+// Route: /categories/:id/metadata
+import { useParams } from "react-router-dom"
+import { useProductCategory, useUpdateProductCategory } from "@hooks/api"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { RouteDrawer } from "@components/modals"
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { product_category, isPending, isError, error } = useProductCategory(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateProductCategory(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <MetadataForm
+ isPending={isPending}
+ isMutating={isMutating}
+ hook={mutateAsync}
+ metadata={product_category?.metadata}
+ />
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/organize/index.tsx b/packages/vendor/src/pages/categories/[id]/organize/index.tsx
new file mode 100644
index 000000000..f2c815f1c
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/organize/index.tsx
@@ -0,0 +1,11 @@
+// Route: /categories/:id/organize
+import { RouteFocusModal } from "@components/modals"
+import { OrganizeCategoryForm } from "./organize-category-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <OrganizeCategoryForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/index.ts b/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/index.ts
new file mode 100644
index 000000000..bc62ef48a
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/index.ts
@@ -0,0 +1 @@
+export { OrganizeCategoryForm, OrganizeCategoryForm as Component } from "./organize-category-form"
diff --git a/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/organize-category-form.tsx b/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/organize-category-form.tsx
new file mode 100644
index 000000000..2872a02a8
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/organize/organize-category-form/organize-category-form.tsx
@@ -0,0 +1,131 @@
+import { useMutation } from "@tanstack/react-query"
+
+import { UniqueIdentifier } from "@dnd-kit/core"
+import { Spinner } from "@medusajs/icons"
+type FetchError = Error & { status?: number }
+import { HttpTypes } from "@medusajs/types"
+import { toast } from "@medusajs/ui"
+import { useState } from "react"
+import { RouteFocusModal } from "@components/modals"
+import {
+ categoriesQueryKeys,
+ useProductCategories,
+} from "@hooks/api/categories"
+import { sdk } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { CategoryTree } from "../../../common/components/category-tree"
+import { CategoryTreeItem } from "../../../common/types"
+
+const QUERY = {
+ fields: "id,name,parent_category_id,rank,*category_children",
+ parent_category_id: "null",
+ include_descendants_tree: true,
+ limit: 9999,
+}
+
+export const OrganizeCategoryForm = () => {
+ const {
+ product_categories,
+ isPending,
+ isError,
+ error: fetchError,
+ } = useProductCategories(QUERY)
+
+ const [snapshot, setSnapshot] = useState<CategoryTreeItem[]>([])
+
+ const { mutateAsync, isPending: isMutating } = useMutation({
+ mutationFn: async ({
+ value,
+ }: {
+ value: {
+ id: string
+ parent_category_id: string | null
+ rank: number | null
+ }
+ arr: CategoryTreeItem[]
+ }) => {
+ await sdk.admin.productCategory.update(value.id, {
+ rank: value.rank ?? 0,
+ parent_category_id: value.parent_category_id,
+ })
+ },
+ onMutate: async (update) => {
+ // Cancel any outgoing refetches (so they don't overwrite our optimistic update)
+ await queryClient.cancelQueries({
+ queryKey: categoriesQueryKeys.list(QUERY),
+ })
+
+ // Snapshot the previous value
+ const previousValue:
+ | HttpTypes.AdminProductCategoryListResponse
+ | undefined = queryClient.getQueryData(categoriesQueryKeys.list(QUERY))
+
+ const nextValue = {
+ ...previousValue,
+ product_categories: update.arr,
+ }
+
+ // Optimistically update to the new value
+ queryClient.setQueryData(categoriesQueryKeys.list(QUERY), nextValue)
+
+ return {
+ previousValue,
+ }
+ },
+ onError: (error: FetchError, _newValue, context) => {
+ // Roll back to the previous value
+ queryClient.setQueryData(
+ categoriesQueryKeys.list(QUERY),
+ context?.previousValue
+ )
+
+ toast.error(error.message)
+ },
+ onSettled: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: categoriesQueryKeys.all,
+ })
+ },
+ })
+
+ const handleRankChange = async (
+ value: {
+ id: UniqueIdentifier
+ parentId: UniqueIdentifier | null
+ index: number
+ },
+ arr: CategoryTreeItem[]
+ ) => {
+ const val = {
+ id: value.id as string,
+ parent_category_id: value.parentId as string | null,
+ rank: value.index,
+ }
+
+ setSnapshot(arr)
+ await mutateAsync({ value: val, arr })
+ }
+
+ const loading = isPending || isMutating
+
+ if (isError) {
+ throw fetchError
+ }
+
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end">
+ {loading && <Spinner className="animate-spin" />}
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="bg-ui-bg-subtle flex flex-1 flex-col overflow-y-auto">
+ <CategoryTree
+ renderValue={(item) => item.name}
+ value={loading ? snapshot : product_categories || []}
+ onChange={handleRankChange}
+ />
+ </RouteFocusModal.Body>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/edit-category-products-form.tsx b/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/edit-category-products-form.tsx
new file mode 100644
index 000000000..20a027fd9
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/edit-category-products-form.tsx
@@ -0,0 +1,243 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { z } from "zod"
+
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProductCategoryProducts } from "@hooks/api/categories"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type EditCategoryProductsFormProps = {
+ categoryId: string
+ products?: Pick<ExtendedAdminProduct, "id">[]
+}
+
+const EditCategoryProductsSchema = z.object({
+ product_ids: z.array(z.string()),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "p"
+
+export const EditCategoryProductsForm = ({
+ categoryId,
+ products = [],
+}: EditCategoryProductsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const [selection, setSelection] = useState<RowSelectionState>(
+ products.reduce((acc, p) => {
+ acc[p.id!] = true
+ return acc
+ }, {} as RowSelectionState)
+ )
+
+ const form = useForm<z.infer<typeof EditCategoryProductsSchema>>({
+ defaultValues: {
+ product_ids: [],
+ },
+ resolver: zodResolver(EditCategoryProductsSchema),
+ })
+
+ const updater: OnChangeFn<RowSelectionState> = (newSelection) => {
+ const value =
+ typeof newSelection === "function"
+ ? newSelection(selection)
+ : newSelection
+
+ form.setValue("product_ids", Object.keys(value), {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setSelection(value)
+ }
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const {
+ products: data,
+ count,
+ isPending,
+ isError,
+ error,
+ } = useProducts({
+ ...searchParams,
+ })
+
+ const columns = useColumns()
+ const filters = useProductTableFilters(["categories"])
+
+ const { table } = useDataTable({
+ data,
+ columns,
+ getRowId: (original) => original.id,
+ count,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ enableRowSelection: (row) => {
+ return !products.some((p) => p.id === row.original.id)
+ },
+ enablePagination: true,
+ rowSelection: {
+ state: selection,
+ updater,
+ },
+ })
+
+ const { mutateAsync, isPending: isMutating } =
+ useUpdateProductCategoryProducts(categoryId)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ add: data.product_ids,
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("categories.products.add.successToast", {
+ count: data.product_ids.length - products.length,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.product_ids && (
+ <Hint variant="error">
+ {form.formState.errors.product_ids.message}
+ </Hint>
+ )}
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isMutating}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ queryObject={raw}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ prefix={PREFIX}
+ isLoading={isPending}
+ layout="fill"
+ pagination
+ search="autofocus"
+ />
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreSelected = !row.getCanSelect()
+ const isSelected = row.getIsSelected() || isPreSelected
+
+ const Component = (
+ <Checkbox
+ checked={isSelected}
+ disabled={isPreSelected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isPreSelected) {
+ return (
+ <Tooltip
+ content={t("categories.products.add.disabledTooltip")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ ...base,
+ ],
+ [t, base]
+ )
+}
diff --git a/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/index.ts b/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/index.ts
new file mode 100644
index 000000000..f5846f757
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/products/edit-category-products-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-category-products-form"
diff --git a/packages/vendor/src/pages/categories/[id]/products/index.tsx b/packages/vendor/src/pages/categories/[id]/products/index.tsx
new file mode 100644
index 000000000..e3fac89fb
--- /dev/null
+++ b/packages/vendor/src/pages/categories/[id]/products/index.tsx
@@ -0,0 +1,28 @@
+// Route: /categories/:id/products
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useProductCategory } from "@hooks/api"
+import { EditCategoryProductsForm } from "./edit-category-products-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { product_category, isLoading, isError, error } = useProductCategory(
+ id!,
+ { fields: "*products" }
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && product_category && (
+ <EditCategoryProductsForm
+ categoryId={id!}
+ products={product_category.products}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/_components/category-list-table/category-list-table.tsx b/packages/vendor/src/pages/categories/_components/category-list-table/category-list-table.tsx
new file mode 100644
index 000000000..06d6a4b3d
--- /dev/null
+++ b/packages/vendor/src/pages/categories/_components/category-list-table/category-list-table.tsx
@@ -0,0 +1,91 @@
+import { Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProductCategories } from "@hooks/api/categories"
+import { useDataTable } from "@hooks/use-data-table"
+import { useCategoryTableColumns } from "./use-category-table-columns"
+import { useCategoryTableQuery } from "./use-category-table-query"
+
+const PAGE_SIZE = 20
+
+export const CategoryListTable = () => {
+ const { t } = useTranslation()
+
+ const { raw, searchParams } = useCategoryTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const query = raw.q
+ ? {
+ include_ancestors_tree: true,
+ fields: "id,name,handle,is_active,is_internal,parent_category",
+ ...searchParams,
+ }
+ : {
+ include_descendants_tree: true,
+ parent_category_id: "null",
+ fields: "id,name,category_children,handle,is_internal,is_active",
+ ...searchParams,
+ }
+
+ const { product_categories, count, isLoading, isError, error } =
+ useProductCategories(
+ {
+ ...query,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: product_categories || [],
+ columns,
+ count,
+ getRowId: (original) => original.id,
+ getSubRows: (original) => original.category_children,
+ enableExpandableRows: true,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("categories.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ Organize products into categories.
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-2">
+ </div>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ navigateTo={(row) => row.id}
+ queryObject={raw}
+ search
+ pagination
+ />
+ </Container>
+ )
+}
+
+const useColumns = () => {
+ const base = useCategoryTableColumns()
+
+ return useMemo(() => [...base], [base])
+}
diff --git a/packages/vendor/src/pages/categories/_components/category-list-table/index.ts b/packages/vendor/src/pages/categories/_components/category-list-table/index.ts
new file mode 100644
index 000000000..0422d9cf0
--- /dev/null
+++ b/packages/vendor/src/pages/categories/_components/category-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./category-list-table"
diff --git a/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-columns.tsx b/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-columns.tsx
new file mode 100644
index 000000000..36d069988
--- /dev/null
+++ b/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-columns.tsx
@@ -0,0 +1,130 @@
+import { TriangleRightMini } from "@medusajs/icons"
+import { AdminProductCategoryResponse } from "@medusajs/types"
+import { IconButton, Text, clx } from "@medusajs/ui"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+// import { StatusCell } from "@components/table/table-cells/common/status-cell';
+import {
+ TextCell,
+ TextHeader,
+} from "@components/table/table-cells/common/text-cell"
+import {
+ getCategoryPath,
+ // getIsActiveProps,
+ // getIsInternalProps,
+} from "../../common/utils"
+
+const columnHelper =
+ createColumnHelper<AdminProductCategoryResponse["product_category"]>()
+
+export const useCategoryTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("name", {
+ header: () => <TextHeader text={t("fields.name")} />,
+ cell: ({ getValue, row }) => {
+ const expandHandler = row.getToggleExpandedHandler()
+
+ if (row.original.parent_category !== undefined) {
+ const path = getCategoryPath(row.original)
+
+ return (
+ <div className="flex size-full items-center gap-1 overflow-hidden">
+ {path.map((chip, index) => (
+ <div
+ key={chip.id}
+ className={clx("overflow-hidden", {
+ "text-ui-fg-muted flex items-center gap-x-1":
+ index !== path.length - 1,
+ })}
+ >
+ <Text size="small" leading="compact" className="truncate">
+ {chip.name}
+ </Text>
+ {index !== path.length - 1 && (
+ <Text size="small" leading="compact">
+ /
+ </Text>
+ )}
+ </div>
+ ))}
+ </div>
+ )
+ }
+
+ return (
+ <div className="flex size-full items-center gap-x-3 overflow-hidden">
+ <div className="flex size-7 items-center justify-center">
+ {row.getCanExpand() ? (
+ <IconButton
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation()
+ e.preventDefault()
+
+ expandHandler()
+ }}
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-subtle"
+ >
+ <TriangleRightMini
+ className={clx({
+ "rotate-90 transition-transform will-change-transform":
+ row.getIsExpanded(),
+ })}
+ />
+ </IconButton>
+ ) : null}
+ </div>
+ <span className="truncate">{getValue()}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("handle", {
+ header: () => <TextHeader text={t("fields.handle")} />,
+ cell: ({ getValue }) => {
+ return <TextCell text={`/${getValue()}`} />
+ },
+ }),
+ // columnHelper.accessor('is_active', {
+ // header: () => (
+ // <TextHeader text={t('fields.status')} />
+ // ),
+ // cell: ({ getValue }) => {
+ // console.log('getValue', getValue());
+ // // const { color, label } = getIsActiveProps(
+ // // getValue(),
+ // // t
+ // // );
+
+ // return (
+ // // <StatusCell color={color}>{label}</StatusCell>
+ // <span>eee</span>
+ // );
+ // },
+ // }),
+ // columnHelper.accessor('is_internal', {
+ // header: () => (
+ // <TextHeader
+ // text={t('categories.fields.visibility.label')}
+ // />
+ // ),
+ // cell: ({ getValue }) => {
+ // // const { color, label } = getIsInternalProps(
+ // // getValue(),
+ // // t
+ // // );
+
+ // return <span>ddd</span>;
+ // },
+ // }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-query.tsx b/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-query.tsx
new file mode 100644
index 000000000..444e3399c
--- /dev/null
+++ b/packages/vendor/src/pages/categories/_components/category-list-table/use-category-table-query.tsx
@@ -0,0 +1,23 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useCategoryTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(["q", "offset", "order"], prefix)
+
+ const searchParams = {
+ q: raw.q,
+ limit: pageSize,
+ offset: raw.offset ? Number(raw.offset) : 0,
+ order: raw.order,
+ }
+
+ return {
+ raw,
+ searchParams,
+ }
+}
diff --git a/packages/vendor/src/pages/categories/_components/index.ts b/packages/vendor/src/pages/categories/_components/index.ts
new file mode 100644
index 000000000..0422d9cf0
--- /dev/null
+++ b/packages/vendor/src/pages/categories/_components/index.ts
@@ -0,0 +1 @@
+export * from "./category-list-table"
diff --git a/packages/vendor/src/pages/categories/common/components/category-tree/category-tree.tsx b/packages/vendor/src/pages/categories/common/components/category-tree/category-tree.tsx
new file mode 100644
index 000000000..065a8324f
--- /dev/null
+++ b/packages/vendor/src/pages/categories/common/components/category-tree/category-tree.tsx
@@ -0,0 +1,55 @@
+import { UniqueIdentifier } from "@dnd-kit/core"
+import { ReactNode } from "react"
+
+import { SortableTree } from "@components/common/sortable-tree"
+import { CategoryTreeItem } from "../../types"
+
+type CategoryTreeProps = {
+ value: CategoryTreeItem[]
+ onChange: (
+ value: {
+ id: UniqueIdentifier
+ parentId: UniqueIdentifier | null
+ index: number
+ },
+ items: CategoryTreeItem[]
+ ) => void
+ renderValue: (item: CategoryTreeItem) => ReactNode
+ enableDrag?: boolean | ((item: CategoryTreeItem) => boolean)
+ isLoading?: boolean
+}
+
+export const CategoryTree = ({
+ value,
+ onChange,
+ renderValue,
+ enableDrag = true,
+ isLoading = false,
+}: CategoryTreeProps) => {
+ if (isLoading) {
+ return (
+ <div className="txt-compact-small relative flex-1 overflow-y-auto">
+ {Array.from({ length: 10 }).map((_, i) => (
+ <CategoryLeafPlaceholder key={i} />
+ ))}
+ </div>
+ )
+ }
+
+ return (
+ <SortableTree
+ items={value}
+ childrenProp="category_children"
+ collapsible
+ enableDrag={enableDrag}
+ onChange={onChange}
+ renderValue={renderValue}
+ />
+ )
+}
+
+const CategoryLeafPlaceholder = () => {
+ return (
+ <div className="bg-ui-bg-base -mb-px flex h-12 animate-pulse items-center border-y px-6 py-2.5" />
+ )
+}
diff --git a/packages/vendor/src/pages/categories/common/components/category-tree/index.ts b/packages/vendor/src/pages/categories/common/components/category-tree/index.ts
new file mode 100644
index 000000000..9f2bfa63d
--- /dev/null
+++ b/packages/vendor/src/pages/categories/common/components/category-tree/index.ts
@@ -0,0 +1 @@
+export * from "./category-tree"
diff --git a/packages/vendor/src/pages/categories/common/hooks/use-delete-product-category-action.tsx b/packages/vendor/src/pages/categories/common/hooks/use-delete-product-category-action.tsx
new file mode 100644
index 000000000..5e103f375
--- /dev/null
+++ b/packages/vendor/src/pages/categories/common/hooks/use-delete-product-category-action.tsx
@@ -0,0 +1,49 @@
+import { HttpTypes } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { useDeleteProductCategory } from "@hooks/api/categories"
+
+export const useDeleteProductCategoryAction = (
+ category: HttpTypes.AdminProductCategory
+) => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteProductCategory(category.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("categories.delete.confirmation", {
+ name: category.name,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("categories.delete.successToast", {
+ name: category.name,
+ })
+ )
+
+ navigate("/categories", {
+ replace: true,
+ })
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
diff --git a/packages/vendor/src/pages/categories/common/types.ts b/packages/vendor/src/pages/categories/common/types.ts
new file mode 100644
index 000000000..20f09fc88
--- /dev/null
+++ b/packages/vendor/src/pages/categories/common/types.ts
@@ -0,0 +1,7 @@
+export type CategoryTreeItem = {
+ id: string
+ name: string
+ parent_category_id: string | null
+ category_children: CategoryTreeItem[] | null
+ rank: number | null
+}
diff --git a/packages/vendor/src/pages/categories/common/utils.ts b/packages/vendor/src/pages/categories/common/utils.ts
new file mode 100644
index 000000000..9cad8d2d7
--- /dev/null
+++ b/packages/vendor/src/pages/categories/common/utils.ts
@@ -0,0 +1,157 @@
+import { AdminProductCategoryResponse } from "@medusajs/types"
+import { TFunction } from "i18next"
+
+import { CategoryTreeItem } from "./types"
+
+export function getIsActiveProps(
+ isActive: boolean,
+ t: TFunction
+): { color: "green" | "red"; label: string } {
+ switch (isActive) {
+ case true:
+ return {
+ label: t("categories.fields.status.active"),
+ color: "green",
+ }
+ case false:
+ return {
+ label: t("categories.fields.status.inactive"),
+ color: "red",
+ }
+ }
+}
+
+export function getIsInternalProps(
+ isInternal: boolean,
+ t: TFunction
+): { color: "blue" | "green"; label: string } {
+ switch (isInternal) {
+ case true:
+ return {
+ label: t("categories.fields.visibility.internal"),
+ color: "blue",
+ }
+ case false:
+ return {
+ label: t("categories.fields.visibility.public"),
+ color: "green",
+ }
+ }
+}
+
+type ChipProps = {
+ id: string
+ name: string
+}
+
+export function getCategoryPath(
+ category?: AdminProductCategoryResponse["product_category"]
+): ChipProps[] {
+ if (!category) {
+ return []
+ }
+
+ const path = category.parent_category
+ ? getCategoryPath(category.parent_category)
+ : []
+ path.push({ id: category.id, name: category.name })
+
+ return path
+}
+
+export function getCategoryChildren(
+ category?: AdminProductCategoryResponse["product_category"]
+): ChipProps[] {
+ if (!category || !category.category_children) {
+ return []
+ }
+
+ return category.category_children.map((child) => ({
+ id: child.id,
+ name: child.name,
+ }))
+}
+
+export const insertCategoryTreeItem = (
+ categories: CategoryTreeItem[],
+ newItem: CategoryTreeItem
+): CategoryTreeItem[] => {
+ const seen = new Set<string>()
+
+ const remove = (
+ items: CategoryTreeItem[],
+ id: string
+ ): CategoryTreeItem[] => {
+ const stack = [...items]
+ const result: CategoryTreeItem[] = []
+
+ while (stack.length > 0) {
+ const item = stack.pop()!
+ if (item.id !== id) {
+ if (item.category_children) {
+ item.category_children = remove(item.category_children, id)
+ }
+ result.push(item)
+ }
+ }
+
+ return result
+ }
+
+ const insert = (items: CategoryTreeItem[]): CategoryTreeItem[] => {
+ const stack = [...items]
+
+ while (stack.length > 0) {
+ const item = stack.pop()!
+ if (seen.has(item.id)) {
+ continue // Prevent revisiting the same node
+ }
+ seen.add(item.id)
+
+ if (item.id === newItem.parent_category_id) {
+ if (!item.category_children) {
+ item.category_children = []
+ }
+
+ if (newItem.rank === null) {
+ item.category_children.push(newItem)
+ } else {
+ item.category_children.splice(newItem.rank, 0, newItem)
+ }
+
+ item.category_children.forEach((child, index) => {
+ child.rank = index
+ })
+
+ item.category_children.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0))
+ return categories
+ }
+ if (item.category_children) {
+ stack.push(...item.category_children)
+ }
+ }
+ return items
+ }
+
+ categories = remove(categories, newItem.id)
+
+ if (newItem.parent_category_id === null && newItem.rank === null) {
+ categories.unshift(newItem)
+
+ categories.forEach((child, index) => {
+ child.rank = index
+ })
+ } else if (newItem.parent_category_id === null && newItem.rank !== null) {
+ categories.splice(newItem.rank, 0, newItem)
+
+ categories.forEach((child, index) => {
+ child.rank = index
+ })
+ } else {
+ categories = insert(categories)
+ }
+
+ categories.sort((a, b) => (a.rank ?? 0) - (b.rank ?? 0))
+
+ return categories
+}
diff --git a/packages/vendor/src/pages/categories/index.tsx b/packages/vendor/src/pages/categories/index.tsx
new file mode 100644
index 000000000..ca785840c
--- /dev/null
+++ b/packages/vendor/src/pages/categories/index.tsx
@@ -0,0 +1,20 @@
+// Route: /categories
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { CategoryListTable } from "./_components/category-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_category.list.after"),
+ before: getWidgets("product_category.list.before"),
+ }}
+ hasOutlet
+ >
+ <CategoryListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/categories/organize/index.tsx b/packages/vendor/src/pages/categories/organize/index.tsx
new file mode 100644
index 000000000..0b06312f6
--- /dev/null
+++ b/packages/vendor/src/pages/categories/organize/index.tsx
@@ -0,0 +1,11 @@
+// Route: /categories/organize
+import { RouteFocusModal } from "@components/modals"
+import { OrganizeCategoryForm } from "../[id]/organize/organize-category-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <OrganizeCategoryForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/collection-general-section.tsx b/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/collection-general-section.tsx
new file mode 100644
index 000000000..56a515126
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/collection-general-section.tsx
@@ -0,0 +1,27 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+type CollectionGeneralSectionProps = {
+ collection: HttpTypes.AdminCollection
+}
+
+export const CollectionGeneralSection = ({
+ collection,
+}: CollectionGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{collection.title}</Heading>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.handle")}
+ </Text>
+ <Text size="small">/{collection.handle}</Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/index.ts b/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/index.ts
new file mode 100644
index 000000000..6c2173aea
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/_components/collection-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./collection-general-section"
diff --git a/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/collection-product-section.tsx b/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/collection-product-section.tsx
new file mode 100644
index 000000000..d14e0df30
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/collection-product-section.tsx
@@ -0,0 +1,275 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useUpdateCollectionProducts } from "@hooks/api/collections"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type CollectionProductSectionProps = {
+ collection: HttpTypes.AdminCollection
+}
+
+const PAGE_SIZE = 10
+
+export const CollectionProductSection = ({
+ collection,
+}: CollectionProductSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { products, count, isLoading, isError, error } = useProducts({
+ ...searchParams,
+ fields: "+thumbnail",
+ collection_id: collection.id!,
+ })
+
+ const filters = useProductTableFilters(["collections"])
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: products ?? [],
+ columns,
+ getRowId: (row) => row.id,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ meta: {
+ collectionId: collection.id,
+ },
+ })
+
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useUpdateCollectionProducts(collection.id!)
+
+ const handleRemove = async (selection: Record<string, boolean>) => {
+ const ids = Object.keys(selection)
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("collections.removeProductsWarning", {
+ count: ids.length,
+ }),
+ confirmText: t("actions.remove"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(
+ {
+ remove: ids,
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("collections.products.remove.successToast", {
+ count: ids.length,
+ })
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.domain")}</Heading>
+ {/* <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Plus />,
+ label: t('actions.add'),
+ to: 'products',
+ },
+ ],
+ },
+ ]}
+ /> */}
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ search
+ pagination
+ pageSize={PAGE_SIZE}
+ navigateTo={({ original }) => `/products/${original.id}`}
+ count={count}
+ filters={filters}
+ isLoading={isLoading}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ commands={[
+ {
+ action: handleRemove,
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ noRecords={{
+ message: t("collections.products.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const ProductActions = ({
+ product,
+ collectionId,
+}: {
+ product: ExtendedAdminProduct
+ collectionId: string
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useUpdateCollectionProducts(collectionId)
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("collections.removeSingleProductWarning", {
+ title: product.title,
+ }),
+ confirmText: t("actions.remove"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(
+ {
+ remove: [product.id],
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("collections.products.remove.successToast", {
+ count: 1,
+ })
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/products/${product.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.remove"),
+ onClick: handleRemove,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const columns = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...columns,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row, table }) => {
+ const { collectionId } = table.options.meta as {
+ collectionId: string
+ }
+
+ return (
+ <ProductActions
+ product={row.original}
+ collectionId={collectionId}
+ />
+ )
+ },
+ }),
+ ],
+ [columns]
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/index.ts b/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/index.ts
new file mode 100644
index 000000000..7f00be294
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/_components/collection-product-section/index.ts
@@ -0,0 +1 @@
+export * from "./collection-product-section"
diff --git a/packages/vendor/src/pages/collections/[id]/_components/index.ts b/packages/vendor/src/pages/collections/[id]/_components/index.ts
new file mode 100644
index 000000000..792a9fd92
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/_components/index.ts
@@ -0,0 +1,2 @@
+export * from "./collection-general-section"
+export * from "./collection-product-section"
diff --git a/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/add-products-to-collection-form.tsx b/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/add-products-to-collection-form.tsx
new file mode 100644
index 000000000..34fa0a710
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/add-products-to-collection-form.tsx
@@ -0,0 +1,258 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals/index.ts"
+import { _DataTable } from "@components/table/data-table/data-table.tsx"
+import { KeyboundForm } from "@components/utilities/keybound-form/keybound-form.tsx"
+import { useUpdateCollectionProducts } from "@hooks/api/collections.tsx"
+import { useProducts } from "@hooks/api/products.tsx"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns.tsx"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters.tsx"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query.tsx"
+import { useDataTable } from "@hooks/use-data-table.tsx"
+import { ExtendedAdminProduct } from "@custom-types/products.ts"
+
+type AddProductsToCollectionFormProps = {
+ collection: HttpTypes.AdminCollection
+}
+
+const AddProductsToCollectionSchema = zod.object({
+ add: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "p"
+
+export const AddProductsToCollectionForm = ({
+ collection,
+}: AddProductsToCollectionFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof AddProductsToCollectionSchema>>({
+ defaultValues: {
+ add: [],
+ },
+ resolver: zodResolver(AddProductsToCollectionSchema),
+ })
+
+ const { setValue } = form
+
+ const { mutateAsync, isPending: isMutating } = useUpdateCollectionProducts(
+ collection.id!
+ )
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const updater: OnChangeFn<RowSelectionState> = (newSelection) => {
+ const update =
+ typeof newSelection === "function"
+ ? newSelection(rowSelection)
+ : newSelection
+
+ setValue(
+ "add",
+ Object.keys(update).filter((k) => update[k]),
+ {
+ shouldDirty: true,
+ shouldTouch: true,
+ }
+ )
+
+ setRowSelection(update)
+ }
+
+ useEffect(() => {
+ setValue(
+ "add",
+ Object.keys(rowSelection).filter((k) => rowSelection[k]),
+ {
+ shouldDirty: true,
+ shouldTouch: true,
+ }
+ )
+ }, [rowSelection, setValue])
+
+ const { searchParams, raw } = useProductTableQuery({
+ prefix: PREFIX,
+ pageSize: PAGE_SIZE,
+ })
+
+ const { products, count, isLoading, isError, error } = useProducts(
+ {
+ fields: "*variants,*sales_channels",
+ ...searchParams,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns()
+ const filters = useProductTableFilters(["collections"])
+
+ const { table } = useDataTable({
+ data: products ?? [],
+ columns,
+ count,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ getRowId: (row) => row.id,
+ enableRowSelection: true,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ enablePagination: true,
+ meta: {
+ collectionId: collection.id,
+ },
+ })
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ add: values.add,
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("collections.products.add.successToast", {
+ count: values.add.length,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.add && (
+ <Hint variant="error">{form.formState.errors.add.message}</Hint>
+ )}
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isMutating}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ queryObject={raw}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ prefix={PREFIX}
+ isLoading={isLoading}
+ layout="fill"
+ pagination
+ search="autofocus"
+ />
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row, table }) => {
+ const { collectionId } = table.options.meta as {
+ collectionId: string
+ }
+
+ const isAdded = row.original.collection_id === collectionId
+
+ const isSelected = row.getIsSelected() || isAdded
+
+ const Component = (
+ <Checkbox
+ checked={isSelected}
+ disabled={isAdded}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isAdded) {
+ return (
+ <Tooltip
+ content={t("salesChannels.productAlreadyAdded")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ ...base,
+ ],
+ [t, base]
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/index.ts b/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/index.ts
new file mode 100644
index 000000000..4fbbd8d08
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/add-products/add-products-to-collection-form/index.ts
@@ -0,0 +1 @@
+export * from "./add-products-to-collection-form"
diff --git a/packages/vendor/src/pages/collections/[id]/add-products/index.tsx b/packages/vendor/src/pages/collections/[id]/add-products/index.tsx
new file mode 100644
index 000000000..34dbe8458
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/add-products/index.tsx
@@ -0,0 +1,20 @@
+// Route: /collections/:id/add-products
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useCollection } from "@hooks/api/collections"
+import { AddProductsToCollectionForm } from "./add-products-to-collection-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { product_collection, isLoading, isError, error } = useCollection(id!)
+
+ if (isError) throw error
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && product_collection && (
+ <AddProductsToCollectionForm collection={product_collection} />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/index.tsx b/packages/vendor/src/pages/collections/[id]/index.tsx
new file mode 100644
index 000000000..4ad0f9147
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/index.tsx
@@ -0,0 +1,69 @@
+// Route: /collections/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useCollection } from "@hooks/api/collections"
+import { collectionsQueryKeys } from "@hooks/api/collections"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { CollectionGeneralSection } from "./_components/collection-general-section"
+import { CollectionProductSection } from "./_components/collection-product-section"
+
+// Loader
+const collectionDetailQuery = (id: string) => ({
+ queryKey: collectionsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/product-collections/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = collectionDetailQuery(id!)
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type CollectionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminCollectionResponse>
+
+export const Breadcrumb = (props: CollectionDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+ const { product_collection } = useCollection(id!, {
+ initialData: { product_collection: props.data?.collection },
+ })
+
+ if (!product_collection) return null
+ return <span>{product_collection.title}</span>
+}
+
+// Main component
+export const Component = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+ const { id } = useParams()
+ const { product_collection, isLoading, isError, error } = useCollection(id!, { initialData })
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !product_collection) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ if (isError) throw error
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_collection.details.after"),
+ before: getWidgets("product_collection.details.before"),
+ }}
+ data={product_collection}
+ >
+ <CollectionGeneralSection collection={product_collection} />
+ <CollectionProductSection collection={product_collection} />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/[id]/metadata/index.tsx b/packages/vendor/src/pages/collections/[id]/metadata/index.tsx
new file mode 100644
index 000000000..39cdbdd98
--- /dev/null
+++ b/packages/vendor/src/pages/collections/[id]/metadata/index.tsx
@@ -0,0 +1,21 @@
+// Route: /collections/:id/metadata
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form/metadata-form"
+import { useCollection, useUpdateCollection } from "@hooks/api"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { product_collection, isPending, isError, error } = useCollection(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateCollection(product_collection?.id!)
+
+ if (isError) throw error
+
+ return (
+ <MetadataForm
+ metadata={product_collection?.metadata}
+ hook={mutateAsync}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/collections/_components/collection-list-table/collection-list-table.tsx b/packages/vendor/src/pages/collections/_components/collection-list-table/collection-list-table.tsx
new file mode 100644
index 000000000..f19f368a1
--- /dev/null
+++ b/packages/vendor/src/pages/collections/_components/collection-list-table/collection-list-table.tsx
@@ -0,0 +1,94 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo } from "react"
+import { _DataTable } from "@components/table/data-table"
+import { useCollections } from "@hooks/api/collections"
+import { useCollectionTableColumns } from "@hooks/table/columns/use-collection-table-columns"
+import { useCollectionTableFilters } from "@hooks/table/filters"
+import { useCollectionTableQuery } from "@hooks/table/query"
+import { useDataTable } from "@hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const CollectionListTable = () => {
+ const { t } = useTranslation()
+ const { searchParams, raw } = useCollectionTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { product_collections, count, isError, error, isLoading } =
+ useCollections(
+ {
+ ...searchParams,
+ fields: "*products",
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = useCollectionTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: product_collections ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row, index) => row.id ?? `${index}`,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("collections.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("collections.subtitle")}
+ </Text>
+ </div>
+ <Link to="/collections/create">
+ <Button size="small" variant="secondary">
+ Request Collection
+ </Button>
+ </Link>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "handle", label: t("fields.handle") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ search
+ navigateTo={(row) => `/collections/${row.original.id}`}
+ queryObject={raw}
+ isLoading={isLoading}
+ />
+ </Container>
+ )
+}
+
+const useColumns = () => {
+ const base = useCollectionTableColumns()
+
+ return useMemo(() => [...base], [base])
+}
diff --git a/packages/vendor/src/pages/collections/_components/collection-list-table/collection-row-actions.tsx b/packages/vendor/src/pages/collections/_components/collection-list-table/collection-row-actions.tsx
new file mode 100644
index 000000000..7ae9dca53
--- /dev/null
+++ b/packages/vendor/src/pages/collections/_components/collection-list-table/collection-row-actions.tsx
@@ -0,0 +1,54 @@
+import { Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteCollection } from "@hooks/api/collections"
+
+export const CollectionRowActions = ({
+ collection,
+}: {
+ collection: HttpTypes.AdminCollection
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteCollection(collection.id!)
+
+ const handleDeleteCollection = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("collections.deleteWarning", {
+ title: collection.title,
+ }),
+ verificationText: collection.title,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync()
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDeleteCollection,
+ icon: <Trash />,
+ disabled: !collection.id,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/collections/_components/collection-list-table/index.ts b/packages/vendor/src/pages/collections/_components/collection-list-table/index.ts
new file mode 100644
index 000000000..cd5c7323f
--- /dev/null
+++ b/packages/vendor/src/pages/collections/_components/collection-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./collection-list-table"
diff --git a/packages/vendor/src/pages/collections/_components/index.ts b/packages/vendor/src/pages/collections/_components/index.ts
new file mode 100644
index 000000000..cd5c7323f
--- /dev/null
+++ b/packages/vendor/src/pages/collections/_components/index.ts
@@ -0,0 +1 @@
+export * from "./collection-list-table"
diff --git a/packages/vendor/src/pages/collections/create/create-collection-form/create-collection-form.tsx b/packages/vendor/src/pages/collections/create/create-collection-form/create-collection-form.tsx
new file mode 100644
index 000000000..c5d0c9adc
--- /dev/null
+++ b/packages/vendor/src/pages/collections/create/create-collection-form/create-collection-form.tsx
@@ -0,0 +1,117 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { HandleInput } from "@components/inputs/handle-input"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateCollection } from "@hooks/api/collections"
+
+const CreateCollectionSchema = zod.object({
+ title: zod.string().min(1),
+ handle: zod.string().optional(),
+})
+
+export const CreateCollectionForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof CreateCollectionSchema>>({
+ defaultValues: {
+ title: "",
+ handle: "",
+ },
+ resolver: zodResolver(CreateCollectionSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateCollection()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: () => {
+ handleSuccess()
+ toast.success("Collection requested successfully")
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit}>
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ variant="primary"
+ type="submit"
+ isLoading={isPending}
+ >
+ {t("actions.create")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <Heading>{t("collections.createCollection")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("collections.createCollectionHint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="handle"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ optional
+ tooltip={t("collections.handleTooltip")}
+ >
+ {t("fields.handle")}
+ </Form.Label>
+ <Form.Control>
+ <HandleInput {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/create/create-collection-form/index.ts b/packages/vendor/src/pages/collections/create/create-collection-form/index.ts
new file mode 100644
index 000000000..19ae8e208
--- /dev/null
+++ b/packages/vendor/src/pages/collections/create/create-collection-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-collection-form"
diff --git a/packages/vendor/src/pages/collections/create/index.tsx b/packages/vendor/src/pages/collections/create/index.tsx
new file mode 100644
index 000000000..a0c1cc7a3
--- /dev/null
+++ b/packages/vendor/src/pages/collections/create/index.tsx
@@ -0,0 +1,11 @@
+// Route: /collections/create
+import { RouteFocusModal } from "@components/modals"
+import { CreateCollectionForm } from "./create-collection-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreateCollectionForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/collections/index.tsx b/packages/vendor/src/pages/collections/index.tsx
new file mode 100644
index 000000000..f8542c5e4
--- /dev/null
+++ b/packages/vendor/src/pages/collections/index.tsx
@@ -0,0 +1,19 @@
+// Route: /collections
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { CollectionListTable } from "./_components/collection-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_collection.list.after"),
+ before: getWidgets("product_collection.list.before"),
+ }}
+ >
+ <CollectionListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/customer-group-customer-section.tsx b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/customer-group-customer-section.tsx
new file mode 100644
index 000000000..4171ecbc7
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/customer-group-customer-section.tsx
@@ -0,0 +1,241 @@
+import { Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox, Container, Heading, usePrompt } from "@medusajs/ui"
+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useRemoveCustomersFromGroup } from "@hooks/api/customer-groups"
+import { useCustomerTableColumns } from "@hooks/table/columns/use-customer-table-columns"
+import { useCustomerTableFilters } from "@hooks/table/filters/use-customer-table-filters"
+import { useCustomerTableQuery } from "@hooks/table/query/use-customer-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type CustomerGroupCustomerSectionProps = {
+ group: HttpTypes.AdminCustomerGroup
+}
+
+const PAGE_SIZE = 10
+
+export const CustomerGroupCustomerSection = ({
+ group,
+}: CustomerGroupCustomerSectionProps) => {
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { raw } = useCustomerTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const customers = group.customers
+ const count = customers.length
+
+ const columns = useColumns()
+ const filters = useCustomerTableFilters(["groups"])
+
+ const { table } = useDataTable({
+ data: customers ?? [],
+ columns,
+ count,
+ getRowId: (row) => row.id,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ meta: {
+ customerGroupId: group.id,
+ },
+ })
+
+ const { mutateAsync } = useRemoveCustomersFromGroup(group.id)
+
+ const handleRemove = async () => {
+ const keys = Object.keys(rowSelection)
+
+ const res = await prompt({
+ title: t("customerGroups.customers.remove.title", {
+ count: keys.length,
+ }),
+ description: t("customerGroups.customers.remove.description", {
+ count: keys.length,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(keys, {
+ onSuccess: () => {
+ setRowSelection({})
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("customers.domain")}</Heading>
+ <Link to={`/customer-groups/${group.id}/add-customers`}>
+ <Button variant="secondary" size="small">
+ {t("general.add")}
+ </Button>
+ </Link>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ navigateTo={(row) => `/customers/${row.id}`}
+ filters={filters}
+ search
+ pagination
+ orderBy={[
+ { key: "email", label: t("fields.email") },
+ {
+ key: "first_name",
+ label: t("fields.firstName"),
+ },
+ { key: "last_name", label: t("fields.lastName") },
+ {
+ key: "has_account",
+ label: t("customers.hasAccount"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ commands={[
+ {
+ action: handleRemove,
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ noRecords={{
+ message: t("customerGroups.customers.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const CustomerActions = ({
+ customer,
+ customerGroupId,
+}: {
+ customer: HttpTypes.AdminCustomer
+ customerGroupId: string
+}) => {
+ const { t } = useTranslation()
+ const { mutateAsync } = useRemoveCustomersFromGroup(customerGroupId)
+
+ const prompt = usePrompt()
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("customerGroups.customers.remove.title", {
+ count: 1,
+ }),
+ description: t("customerGroups.customers.remove.description", {
+ count: 1,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync([customer.id])
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.remove"),
+ onClick: handleRemove,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminCustomer>()
+
+const useColumns = () => {
+ const columns = useCustomerTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...columns,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row, table }) => {
+ const { customerGroupId } = table.options.meta as {
+ customerGroupId: string
+ }
+
+ return (
+ <CustomerActions
+ customer={row.original}
+ customerGroupId={customerGroupId}
+ />
+ )
+ },
+ }),
+ ],
+ [columns]
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/index.ts b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/index.ts
new file mode 100644
index 000000000..3098ff7ac
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-customer-section/index.ts
@@ -0,0 +1 @@
+export * from "./customer-group-customer-section"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/customer-group-general-section.tsx b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/customer-group-general-section.tsx
new file mode 100644
index 000000000..de4b901ef
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/customer-group-general-section.tsx
@@ -0,0 +1,90 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteCustomerGroup } from "@hooks/api/customer-groups"
+
+type CustomerGroupGeneralSectionProps = {
+ group: HttpTypes.AdminCustomerGroup
+}
+
+export const CustomerGroupGeneralSection = ({
+ group,
+}: CustomerGroupGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const { mutateAsync } = useDeleteCustomerGroup(group.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("customerGroups.delete.title"),
+ description: t("customerGroups.delete.description", {
+ name: group.name,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("customerGroups.delete.successToast", {
+ name: group.name,
+ })
+ )
+
+ navigate("/customer-groups", { replace: true })
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{group.name}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/customer-groups/${group.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("customers.domain")}
+ </Text>
+ <Text size="small" leading="compact">
+ {group.customers?.length || "-"}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/index.ts b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/index.ts
new file mode 100644
index 000000000..dfe709902
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/_components/customer-group-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./customer-group-general-section"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/_components/index.ts b/packages/vendor/src/pages/customer-groups/[id]/_components/index.ts
new file mode 100644
index 000000000..8a4283982
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/_components/index.ts
@@ -0,0 +1,2 @@
+export * from "./customer-group-customer-section"
+export * from "./customer-group-general-section"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/add-customers-form.tsx b/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/add-customers-form.tsx
new file mode 100644
index 000000000..97d64fdc8
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/add-customers-form.tsx
@@ -0,0 +1,259 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { HttpTypes } from "@medusajs/types"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useAddCustomersToGroup } from "@hooks/api/customer-groups"
+import { useCustomers } from "@hooks/api/customers"
+import { useCustomerTableColumns } from "@hooks/table/columns/use-customer-table-columns"
+import { useCustomerTableFilters } from "@hooks/table/filters/use-customer-table-filters"
+import { useCustomerTableQuery } from "@hooks/table/query/use-customer-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type AddCustomersFormProps = {
+ customerGroupId: string
+}
+
+export const AddCustomersSchema = zod.object({
+ customer_ids: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 10
+
+export const AddCustomersForm = ({
+ customerGroupId,
+}: AddCustomersFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof AddCustomersSchema>>({
+ defaultValues: {
+ customer_ids: [],
+ },
+ resolver: zodResolver(AddCustomersSchema),
+ })
+
+ const { setValue } = form
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ useEffect(() => {
+ setValue(
+ "customer_ids",
+ Object.keys(rowSelection).filter((k) => rowSelection[k]),
+ {
+ shouldDirty: true,
+ shouldTouch: true,
+ }
+ )
+ }, [rowSelection, setValue])
+
+ const { searchParams, raw } = useCustomerTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const filters = useCustomerTableFilters()
+
+ const { customers, count, isLoading, isError, error } = useCustomers({
+ ...searchParams,
+ })
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+
+ const ids = Object.keys(state)
+
+ setValue("customer_ids", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: customers ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: (row) => {
+ return !row.original.groups?.map((gc) => gc.id).includes(customerGroupId)
+ },
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ })
+
+ const { mutateAsync, isPending } = useAddCustomersToGroup(customerGroupId)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data.customer_ids, {
+ onSuccess: () => {
+ toast.success(
+ t("customerGroups.customers.add.successToast", {
+ count: data.customer_ids.length,
+ })
+ )
+
+ handleSuccess(`/customer-groups/${customerGroupId}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.customer_ids && (
+ <Hint variant="error">
+ {form.formState.errors.customer_ids.message}
+ </Hint>
+ )}
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isPending}
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ filters={filters}
+ orderBy={[
+ { key: "email", label: t("fields.email") },
+ {
+ key: "first_name",
+ label: t("fields.firstName"),
+ },
+ {
+ key: "last_name",
+ label: t("fields.lastName"),
+ },
+ {
+ key: "has_account",
+ label: t("customers.hasAccount"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ isLoading={isLoading}
+ layout="fill"
+ search="autofocus"
+ queryObject={raw}
+ noRecords={{
+ message: t("customerGroups.customers.add.list.noRecordsMessage"),
+ }}
+ />
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminCustomer>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const base = useCustomerTableColumns()
+
+ const columns = useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreSelected = !row.getCanSelect()
+ const isSelected = row.getIsSelected() || isPreSelected
+
+ const Component = (
+ <Checkbox
+ checked={isSelected}
+ disabled={isPreSelected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isPreSelected) {
+ return (
+ <Tooltip
+ content={t("customerGroups.customers.alreadyAddedTooltip")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ ...base,
+ ],
+ [t, base]
+ )
+
+ return columns
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/index.ts b/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/index.ts
new file mode 100644
index 000000000..512d1edf6
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/add-customers/add-customers-form/index.ts
@@ -0,0 +1 @@
+export * from "./add-customers-form"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/add-customers/index.tsx b/packages/vendor/src/pages/customer-groups/[id]/add-customers/index.tsx
new file mode 100644
index 000000000..c4f4e1f70
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/add-customers/index.tsx
@@ -0,0 +1,13 @@
+// Route: /customer-groups/:id/add-customers
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { AddCustomersForm } from "./add-customers-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ return (
+ <RouteFocusModal>
+ <AddCustomersForm customerGroupId={id!} />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/constants.ts b/packages/vendor/src/pages/customer-groups/[id]/constants.ts
new file mode 100644
index 000000000..c87c7a184
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/constants.ts
@@ -0,0 +1 @@
+export const CUSTOMER_GROUP_DETAIL_FIELDS = "*customers"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/edit-customer-group-form.tsx b/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/edit-customer-group-form.tsx
new file mode 100644
index 000000000..91b3f197d
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/edit-customer-group-form.tsx
@@ -0,0 +1,90 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as z from "zod"
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateCustomerGroup } from "@hooks/api/customer-groups"
+
+type EditCustomerGroupFormProps = {
+ group: HttpTypes.AdminCustomerGroup
+}
+
+export const EditCustomerGroupSchema = z.object({
+ name: z.string().min(1),
+})
+
+export const EditCustomerGroupForm = ({
+ group,
+}: EditCustomerGroupFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof EditCustomerGroupSchema>>({
+ defaultValues: {
+ name: group.name || "",
+ },
+ resolver: zodResolver(EditCustomerGroupSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateCustomerGroup(group.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: ({ customer_group }) => {
+ toast.success(
+ t("customerGroups.edit.successToast", {
+ name: customer_group.name,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} size="small" />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/index.ts b/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/index.ts
new file mode 100644
index 000000000..3062389f7
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/edit/edit-customer-group-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-customer-group-form"
diff --git a/packages/vendor/src/pages/customer-groups/[id]/edit/index.tsx b/packages/vendor/src/pages/customer-groups/[id]/edit/index.tsx
new file mode 100644
index 000000000..725d2cd91
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/edit/index.tsx
@@ -0,0 +1,24 @@
+// Route: /customer-groups/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCustomerGroup } from "@hooks/api/customer-groups"
+import { EditCustomerGroupForm } from "./edit-customer-group-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { customer_group, isLoading, isError, error } = useCustomerGroup(id!)
+ const { t } = useTranslation()
+
+ if (isError) throw error
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("customerGroups.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && customer_group && <EditCustomerGroupForm group={customer_group} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/index.tsx b/packages/vendor/src/pages/customer-groups/[id]/index.tsx
new file mode 100644
index 000000000..d0e07303c
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/index.tsx
@@ -0,0 +1,66 @@
+// Route: /customer-groups/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useCustomerGroup } from "@hooks/api/customer-groups"
+import { productsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { CustomerGroupCustomerSection } from "./_components/customer-group-customer-section"
+import { CustomerGroupGeneralSection } from "./_components/customer-group-general-section"
+import { CUSTOMER_GROUP_DETAIL_FIELDS } from "./constants"
+
+// Loader
+const customerGroupDetailQuery = (id: string) => ({
+ queryKey: productsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/customer-groups/${id}`, {
+ method: "GET",
+ query: { fields: CUSTOMER_GROUP_DETAIL_FIELDS },
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = customerGroupDetailQuery(id!)
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type CustomerGroupDetailBreadcrumbProps = UIMatch<HttpTypes.AdminCustomerGroupResponse>
+
+export const Breadcrumb = (props: CustomerGroupDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+ const { customer_group } = useCustomerGroup(id!, { fields: CUSTOMER_GROUP_DETAIL_FIELDS }, { initialData: props.data, enabled: Boolean(id) })
+
+ if (!customer_group) return null
+ return <span>{customer_group.name}</span>
+}
+
+// Main component
+export const Component = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+ const { id } = useParams()
+ const { customer_group, isLoading, isError, error } = useCustomerGroup(id!, { fields: CUSTOMER_GROUP_DETAIL_FIELDS }, { initialData })
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !customer_group) return <SingleColumnPageSkeleton sections={2} />
+ if (isError) throw error
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("customer_group.details.before"),
+ after: getWidgets("customer_group.details.after"),
+ }}
+ data={customer_group}
+ >
+ <CustomerGroupGeneralSection group={customer_group} />
+ <CustomerGroupCustomerSection group={customer_group} />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/[id]/metadata/index.tsx b/packages/vendor/src/pages/customer-groups/[id]/metadata/index.tsx
new file mode 100644
index 000000000..5d6a6c4b9
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/[id]/metadata/index.tsx
@@ -0,0 +1,21 @@
+// Route: /customer-groups/:id/metadata
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { useCustomerGroup, useUpdateCustomerGroup } from "@hooks/api/customer-groups"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { customer_group, isPending, isError, error } = useCustomerGroup(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateCustomerGroup(id!)
+
+ if (isError) throw error
+
+ return (
+ <MetadataForm
+ metadata={customer_group?.metadata}
+ hook={mutateAsync}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/customer-group-list-table.tsx b/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/customer-group-list-table.tsx
new file mode 100644
index 000000000..703cfcfd5
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/customer-group-list-table.tsx
@@ -0,0 +1,221 @@
+import { useCallback, useMemo } from 'react';
+
+import { PencilSquare, Trash } from '@medusajs/icons';
+import {
+ Button,
+ Container,
+ createDataTableColumnHelper,
+ DataTableRow,
+ Heading,
+ Text,
+ toast,
+ usePrompt
+} from '@medusajs/ui';
+import { useTranslation } from 'react-i18next';
+import { Link, useNavigate } from 'react-router-dom';
+
+import { ActionMenu } from "@components/common/action-menu"
+import { SingleColumnPage } from "@components/layout/pages"
+import { _DataTable } from "@components/table/data-table"
+import { DataTableQuery } from "@components/table/data-table/data-table-query"
+import { TextCell } from "@components/table/table-cells/common/text-cell"
+import { useDashboardExtension } from "@/extensions"
+import { useCustomerGroups, useDeleteCustomerGroupLazy } from "@hooks/api"
+import { useDataTable } from "@hooks/use-data-table"
+import { useDate } from "@hooks/use-date"
+import { CustomerGroupData } from '@pages/orders/common/customerGroupFiltering';
+import { customerGroupFilter } from '../../common/customer-group-filter';
+import { useCustomerGroupsTableQuery } from '../../common/use-customer-groups-table-query';
+
+const PAGE_SIZE = 10;
+
+export const CustomerGroupListTable = () => {
+ const { t } = useTranslation();
+ const { getWidgets } = useDashboardExtension();
+
+ const columns = useColumns();
+
+ const { searchParams } = useCustomerGroupsTableQuery({
+ pageSize: PAGE_SIZE
+ });
+
+ const { customer_groups, isPending, isError, error } = useCustomerGroups();
+
+ if (isError) {
+ throw error;
+ }
+
+ const filteredList = customerGroupFilter(
+ customer_groups ?? [],
+ searchParams.order,
+ searchParams.q ?? ''
+ );
+
+ const count = filteredList?.length || 0;
+
+ const { table } = useDataTable({
+ data: filteredList ?? [],
+ columns,
+ count: count,
+ enablePagination: true,
+ getRowId: row => row.customer_group_id,
+ pageSize: PAGE_SIZE
+ });
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets('customer_group.list.before'),
+ after: getWidgets('customer_group.list.after')
+ }}
+ >
+ <Container className="overflow-hidden p-0">
+ <div className="flex flex-col items-start justify-between gap-2 p-6 md:flex-row md:items-center">
+ <div className="items-center justify-between gap-2">
+ <Heading>{t('customerGroups.domain')}</Heading>
+ <Text
+ size="small"
+ className="text-ui-fg-subtle"
+ >
+ Organize customers into groups. Groups can have different promotions and prices.
+ </Text>
+ </div>
+ <div className="flex items-center">
+ <div className="-mx-4">
+ <DataTableQuery
+ search
+ orderBy={[
+ { key: 'name', label: t('fields.name') },
+ {
+ key: 'customers',
+ label: t('customers.domain')
+ }
+ ]}
+ />
+ </div>
+
+ <Link to="/customer-groups/create">
+ <Button
+ size="small"
+ variant="secondary"
+ >
+ {t('actions.create')}
+ </Button>
+ </Link>
+ </div>
+ </div>
+
+ <div className="border-t">
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ navigateTo={(row: DataTableRow<CustomerGroupData>) =>
+ `/customer-groups/${row.original.customer_group_id}`
+ }
+ noRecords={{
+ title: t('customerGroups.list.empty.heading'),
+ message: t('customerGroups.list.empty.description')
+ }}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ />
+ </div>
+ </Container>
+ </SingleColumnPage>
+ );
+};
+
+const columnHelper = createDataTableColumnHelper<CustomerGroupData>();
+
+const useColumns = () => {
+ const { t } = useTranslation();
+ const { getFullDate } = useDate();
+ const navigate = useNavigate();
+ const prompt = usePrompt();
+
+ const { mutateAsync: deleteCustomerGroup } = useDeleteCustomerGroupLazy();
+
+ const handleDeleteCustomerGroup = useCallback(
+ async ({ id, name }: { id: string; name: string }) => {
+ const res = await prompt({
+ title: t('customerGroups.delete.title'),
+ description: t('customerGroups.delete.description', {
+ name
+ }),
+ verificationText: name,
+ verificationInstruction: t('general.typeToConfirm'),
+ confirmText: t('actions.delete'),
+ cancelText: t('actions.cancel')
+ });
+
+ if (!res) {
+ return;
+ }
+
+ await deleteCustomerGroup(
+ { id },
+ {
+ onSuccess: () => {
+ toast.success(
+ t('customerGroups.delete.successToast', {
+ name
+ })
+ );
+ },
+ onError: e => {
+ toast.error(e.message);
+ }
+ }
+ );
+ },
+ [t, prompt, deleteCustomerGroup]
+ );
+
+ return useMemo(() => {
+ return [
+ columnHelper.accessor('customer_group.name', {
+ header: t('fields.name'),
+ cell: ({ row }) => {
+ return <TextCell text={row?.original?.customer_group?.name || '-'} />;
+ }
+ }),
+ columnHelper.accessor('customer_group.customers', {
+ header: t('customers.domain'),
+ cell: ({ row }) => {
+ return <span>{row?.original?.customer_group?.customers?.length ?? 0}</span>;
+ }
+ }),
+ columnHelper.display({
+ id: 'actions',
+ cell: ({ row }) => {
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t('actions.edit'),
+ to: `/customer-groups/${row.original.customer_group_id}/edit`
+ },
+ {
+ icon: <Trash />,
+ label: t('actions.delete'),
+ onClick: () => {
+ handleDeleteCustomerGroup({
+ id: row.original.customer_group_id,
+ name: row.original.customer_group.name ?? ''
+ });
+ }
+ }
+ ]
+ }
+ ]}
+ />
+ );
+ }
+ })
+ ];
+ }, [t, navigate, getFullDate, handleDeleteCustomerGroup]);
+};
diff --git a/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/index.ts b/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/index.ts
new file mode 100644
index 000000000..ead4d7474
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/_components/customer-group-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./customer-group-list-table"
diff --git a/packages/vendor/src/pages/customer-groups/_components/index.ts b/packages/vendor/src/pages/customer-groups/_components/index.ts
new file mode 100644
index 000000000..ead4d7474
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/_components/index.ts
@@ -0,0 +1 @@
+export * from "./customer-group-list-table"
diff --git a/packages/vendor/src/pages/customer-groups/common/customer-group-filter.ts b/packages/vendor/src/pages/customer-groups/common/customer-group-filter.ts
new file mode 100644
index 000000000..46f612564
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/common/customer-group-filter.ts
@@ -0,0 +1,37 @@
+import { CustomerGroupData } from "@pages/orders/common/customerGroupFiltering"
+
+export const customerGroupFilter = (
+ groups: CustomerGroupData[],
+ sortOrder?: string,
+ searchQuery?: string
+): CustomerGroupData[] => {
+ let filtered = groups
+
+ // Filter by search query
+ if (searchQuery) {
+ filtered = filtered.filter((group) => {
+ const name = group.customer_group?.name?.toLowerCase() || ""
+ return name.includes(searchQuery.toLowerCase())
+ })
+ }
+
+ // Sort by order
+ if (sortOrder) {
+ const isDescending = sortOrder.startsWith("-")
+ const field = isDescending ? sortOrder.slice(1) : sortOrder
+ const direction = isDescending ? -1 : 1
+
+ filtered = [...filtered].sort((a, b) => {
+ const aValue = a.customer_group?.[field as keyof typeof a.customer_group]
+ const bValue = b.customer_group?.[field as keyof typeof b.customer_group]
+
+ if (typeof aValue === "string" && typeof bValue === "string") {
+ return direction * aValue.localeCompare(bValue)
+ }
+
+ return 0
+ })
+ }
+
+ return filtered
+}
diff --git a/packages/vendor/src/pages/customer-groups/common/use-customer-groups-table-query.ts b/packages/vendor/src/pages/customer-groups/common/use-customer-groups-table-query.ts
new file mode 100644
index 000000000..50d1940f7
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/common/use-customer-groups-table-query.ts
@@ -0,0 +1,21 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useCustomerGroupsTableQuery = ({
+ pageSize = 10,
+}: {
+ pageSize?: number
+}) => {
+ const queryParams = useQueryParams(["q", "order", "offset"])
+
+ const searchParams = {
+ q: queryParams.q,
+ order: queryParams.order,
+ offset: queryParams.offset ? Number(queryParams.offset) : 0,
+ limit: pageSize,
+ }
+
+ return {
+ searchParams,
+ raw: queryParams,
+ }
+}
diff --git a/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/create-customer-group-form.tsx b/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/create-customer-group-form.tsx
new file mode 100644
index 000000000..49f734073
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/create-customer-group-form.tsx
@@ -0,0 +1,110 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateCustomerGroup } from "@hooks/api/customer-groups"
+
+export const CreateCustomerGroupSchema = zod.object({
+ name: zod.string().min(1),
+})
+
+export const CreateCustomerGroupForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof CreateCustomerGroupSchema>>({
+ defaultValues: {
+ name: "",
+ },
+ resolver: zodResolver(CreateCustomerGroupSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateCustomerGroup()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ name: data.name,
+ },
+ {
+ onSuccess: ({ customer_group }) => {
+ toast.success(
+ t("customerGroups.create.successToast", {
+ name: customer_group.name,
+ })
+ )
+
+ handleSuccess(`/customer-groups/${customer_group.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-col items-center pt-[72px]">
+ <div className="flex size-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <RouteFocusModal.Title asChild>
+ <Heading>{t("customerGroups.create.header")}</Heading>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("customerGroups.create.hint")}
+ </Text>
+ </RouteFocusModal.Description>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isPending}
+ >
+ {t("actions.create")}
+ </Button>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/index.ts b/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/index.ts
new file mode 100644
index 000000000..960232c9c
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/create/create-customer-group-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-customer-group-form"
diff --git a/packages/vendor/src/pages/customer-groups/create/index.tsx b/packages/vendor/src/pages/customer-groups/create/index.tsx
new file mode 100644
index 000000000..1c3776138
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/create/index.tsx
@@ -0,0 +1,11 @@
+// Route: /customer-groups/create
+import { RouteFocusModal } from "@components/modals"
+import { CreateCustomerGroupForm } from "./create-customer-group-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreateCustomerGroupForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/customer-groups/index.tsx b/packages/vendor/src/pages/customer-groups/index.tsx
new file mode 100644
index 000000000..6c1acca95
--- /dev/null
+++ b/packages/vendor/src/pages/customer-groups/index.tsx
@@ -0,0 +1,19 @@
+// Route: /customer-groups
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { CustomerGroupListTable } from "./_components/customer-group-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("customer_group.list.after"),
+ before: getWidgets("customer_group.list.before"),
+ }}
+ >
+ <CustomerGroupListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/customer-general-section.tsx b/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/customer-general-section.tsx
new file mode 100644
index 000000000..dac9bbff3
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/customer-general-section.tsx
@@ -0,0 +1,57 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+type CustomerGeneralSectionProps = {
+ customer: HttpTypes.AdminCustomer
+}
+
+export const CustomerGeneralSection = ({
+ customer,
+}: CustomerGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const name = [customer.first_name, customer.last_name]
+ .filter(Boolean)
+ .join(" ")
+
+ const statusColor = customer.has_account ? "green" : "orange"
+ const statusText = customer.has_account
+ ? t("customers.fields.registered")
+ : t("customers.fields.guest")
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{customer.email}</Heading>
+ <div className="flex items-center gap-x-2">
+ <StatusBadge color={statusColor}>{statusText}</StatusBadge>
+ </div>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.name")}
+ </Text>
+ <Text size="small" leading="compact">
+ {name || "-"}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.company")}
+ </Text>
+ <Text size="small" leading="compact">
+ {customer.company_name || "-"}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.phone")}
+ </Text>
+ <Text size="small" leading="compact">
+ {customer.phone || "-"}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/index.ts b/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/index.ts
new file mode 100644
index 000000000..ef9c4e73b
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./customer-general-section"
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/customer-group-section.tsx b/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/customer-group-section.tsx
new file mode 100644
index 000000000..c25d9691e
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/customer-group-section.tsx
@@ -0,0 +1,294 @@
+import { HttpTypes } from "@medusajs/types"
+import {
+ Button,
+ Checkbox,
+ Container,
+ Heading,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
+import { t } from "i18next"
+import { useMemo, useState } from "react"
+
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import {
+ TextCell,
+ TextHeader,
+} from "@components/table/table-cells/common/text-cell"
+import { useBatchCustomerCustomerGroups } from "@hooks/api"
+import {
+ useCustomerGroups,
+ useRemoveCustomersFromGroup,
+} from "@hooks/api/customer-groups"
+import { useCustomerGroupTableFilters } from "@hooks/table/filters/use-customer-group-table-filters"
+import { useCustomerGroupTableQuery } from "@hooks/table/query/use-customer-group-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type CustomerGroupSectionProps = {
+ customer: HttpTypes.AdminCustomer
+}
+
+const PAGE_SIZE = 10
+const PREFIX = "cusgr"
+
+export const CustomerGroupSection = ({
+ customer,
+}: CustomerGroupSectionProps) => {
+ const prompt = usePrompt()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+ const { raw, searchParams } = useCustomerGroupTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const {
+ customer_groups: customerGroups,
+ isLoading,
+ isError,
+ error,
+ } = useCustomerGroups(
+ {
+ ...searchParams,
+ fields: "+customers.id",
+ },
+ undefined,
+ {
+ created_at: searchParams.created_at,
+ updated_at: searchParams.updated_at,
+ sort: searchParams.order,
+ }
+ )
+
+ const filteredCustomerGroups = customerGroups?.filter((cg) =>
+ customer.groups?.some((g) => g.id === cg.customer_group_id)
+ )
+
+ const flatCustomerGroups = filteredCustomerGroups?.map((cg) => ({
+ ...cg.customer_group
+ }))
+
+ const { mutateAsync: batchCustomerCustomerGroups } =
+ useBatchCustomerCustomerGroups(customer.id)
+
+ const filters = useCustomerGroupTableFilters()
+ const columns = useColumns(customer.id)
+
+ const { table } = useDataTable({
+ data: flatCustomerGroups ?? [],
+ columns,
+ count: flatCustomerGroups?.length ?? 0,
+ getRowId: (row) => row.id,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ })
+
+ const handleRemove = async () => {
+ const selectedIds = Object.keys(rowSelection)
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("customers.groups.removeMany", {
+ groups: flatCustomerGroups
+ ?.filter((g) => selectedIds.includes(g.id))
+ .map((g) => g.name)
+ .join(","),
+ }),
+ confirmText: t("actions.remove"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ const customerGroupIds = flatCustomerGroups
+ ?.filter((g) => selectedIds.includes(g.id))
+ .map((g) => g.id) ?? []
+
+ await batchCustomerCustomerGroups(
+ { remove: customerGroupIds, add: [] },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("customers.groups.removed.success", {
+ groups: flatCustomerGroups
+ ?.filter((g) => selectedIds.includes(g.id))
+ .map((g) => g.name),
+ })
+ )
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("customerGroups.domain")}</Heading>
+ <Link to={`/customers/${customer.id}/add-customer-groups`}>
+ <Button variant="secondary" size="small">
+ {t("general.add")}
+ </Button>
+ </Link>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ count={flatCustomerGroups?.length ?? 0}
+ prefix={PREFIX}
+ navigateTo={(row) => `/customer-groups/${row.original.id}`}
+ filters={filters}
+ search
+ pagination
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ commands={[
+ {
+ action: handleRemove,
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ queryObject={raw}
+ noRecords={{
+ message: t("customers.groups.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const CustomerGroupRowActions = ({
+ group,
+ customerId,
+}: {
+ group: HttpTypes.AdminCustomerGroup
+ customerId: string
+}) => {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const { mutateAsync } = useRemoveCustomersFromGroup(group.id)
+
+ const onRemove = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("customers.groups.remove", {
+ name: group.name,
+ }),
+ confirmText: t("actions.remove"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync([customerId], {
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: `/customer-groups/${group.id}/edit`,
+ },
+ {
+ label: t("actions.remove"),
+ onClick: onRemove,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminCustomerGroup>()
+
+const useColumns = (customerId: string) => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ columnHelper.accessor("name", {
+ header: () => <TextHeader text={t("fields.name")} />,
+ cell: ({ row }) => {
+ return <TextCell text={row.original?.name || "-"} />
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => (
+ <CustomerGroupRowActions
+ group={row.original}
+ customerId={customerId}
+ />
+ ),
+ }),
+ ],
+ [customerId, t]
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/index.ts b/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/index.ts
new file mode 100644
index 000000000..421addaae
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-group-section/index.ts
@@ -0,0 +1 @@
+export * from "./customer-group-section"
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/customer-order-section.tsx b/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/customer-order-section.tsx
new file mode 100644
index 000000000..c0f61b71d
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/customer-order-section.tsx
@@ -0,0 +1,107 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useOrderTableColumns } from "@hooks/table/columns/use-order-table-columns"
+import { useOrderTableFilters } from "@hooks/table/filters/use-order-table-filters"
+import { useOrderTableQuery } from "@hooks/table/query/use-order-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { useCustomerOrders } from "@hooks/api"
+
+type CustomerGeneralSectionProps = {
+ customer: HttpTypes.AdminCustomer
+}
+
+const PREFIX = "cusord"
+const PAGE_SIZE = 10
+
+const DEFAULT_RELATIONS = "*customer,*items,*sales_channel"
+const DEFAULT_FIELDS =
+ "id,status,display_id,created_at,updated_at,email,fulfillment_status,payment_status,total,currency_code"
+
+export const CustomerOrderSection = ({
+ customer,
+}: CustomerGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useOrderTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { orders, isLoading, isError, error } = useCustomerOrders(
+ customer.id,
+ {
+ fields: DEFAULT_FIELDS + "," + DEFAULT_RELATIONS,
+ limit: searchParams.limit,
+ offset: searchParams.offset,
+ },
+ undefined,
+ {
+ created_at: searchParams.created_at,
+ updated_at: searchParams.updated_at,
+ sort: searchParams.order,
+ }
+ )
+
+ const columns = useColumns()
+ const filters = useOrderTableFilters()
+
+ const count = orders?.length || 0
+
+ const { table } = useDataTable({
+ data: orders ?? [],
+ columns,
+ enablePagination: true,
+ count,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("orders.domain")}</Heading>
+ </div>
+ <_DataTable
+ columns={columns}
+ table={table}
+ pagination
+ navigateTo={(row) => `/orders/${row.original.id}`}
+ filters={filters}
+ count={count}
+ isLoading={isLoading}
+ pageSize={PAGE_SIZE}
+ orderBy={[
+ {
+ key: "display_id",
+ label: t("orders.fields.displayId"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ prefix={PREFIX}
+ />
+ </Container>
+ )
+}
+
+const useColumns = () => {
+ const base = useOrderTableColumns({
+ exclude: ["customer"],
+ })
+
+ return useMemo(() => [...base], [base])
+}
diff --git a/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/index.ts b/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/index.ts
new file mode 100644
index 000000000..bd72160c5
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/customer-order-section/index.ts
@@ -0,0 +1 @@
+export * from "./customer-order-section"
diff --git a/packages/vendor/src/pages/customers/[id]/_components/index.ts b/packages/vendor/src/pages/customers/[id]/_components/index.ts
new file mode 100644
index 000000000..bde9afc69
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/_components/index.ts
@@ -0,0 +1,3 @@
+export * from "./customer-general-section"
+export * from "./customer-group-section"
+export * from "./customer-order-section"
diff --git a/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/add-customer-groups-form.tsx b/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/add-customer-groups-form.tsx
new file mode 100644
index 000000000..a0f14a69a
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/add-customer-groups-form.tsx
@@ -0,0 +1,264 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Checkbox, Hint, Tooltip, toast } from "@medusajs/ui"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import {
+ TextCell,
+ TextHeader,
+} from "@components/table/table-cells/common/text-cell"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useBatchCustomerCustomerGroups } from "@hooks/api"
+import { useCustomerGroups } from "@hooks/api/customer-groups"
+import { useCustomerGroupTableFilters } from "@hooks/table/filters/use-customer-group-table-filters"
+import { useCustomerGroupTableQuery } from "@hooks/table/query/use-customer-group-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { HttpTypes } from "@medusajs/types"
+
+type AddCustomerGroupsFormProps = {
+ customerId: string
+}
+
+export const AddCustomerGroupsSchema = zod.object({
+ customer_group_ids: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 10
+
+export const AddCustomerGroupsForm = ({
+ customerId,
+}: AddCustomerGroupsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const [isPending, setIsPending] = useState(false)
+
+ const { mutateAsync: batchCustomerCustomerGroups } =
+ useBatchCustomerCustomerGroups(customerId)
+
+ const form = useForm<zod.infer<typeof AddCustomerGroupsSchema>>({
+ defaultValues: {
+ customer_group_ids: [],
+ },
+ resolver: zodResolver(AddCustomerGroupsSchema),
+ })
+
+ const { setValue } = form
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+ useEffect(() => {
+ setValue(
+ "customer_group_ids",
+ Object.keys(rowSelection).filter((k) => rowSelection[k]),
+ {
+ shouldDirty: true,
+ shouldTouch: true,
+ }
+ )
+ }, [rowSelection, setValue])
+
+ const { searchParams, raw } = useCustomerGroupTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const filters = useCustomerGroupTableFilters()
+
+ const {
+ customer_groups,
+ count,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useCustomerGroups({
+ fields: "*customers",
+ ...searchParams,
+ })
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+
+ const ids = Object.keys(state)
+
+ setValue("customer_group_ids", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const columns = useColumns()
+
+
+ const flatCustomerGroups = customer_groups?.map((cg) => ({
+ ...cg.customer_group
+ }))
+
+ const { table } = useDataTable({
+ data: flatCustomerGroups ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: (row) => {
+ return !row.original.customers?.some((c) => c.id === customerId)
+ },
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ })
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ setIsPending(true)
+ try {
+ await batchCustomerCustomerGroups({
+ add: data.customer_group_ids,
+ remove: [],
+ })
+
+ toast.success("Customer groups added successfully")
+
+ handleSuccess(`/customers/${customerId}`)
+ } catch (e: any) {
+ toast.error(e.message)
+ } finally {
+ setIsPending(false)
+ }
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ {form.formState.errors.customer_group_ids && (
+ <Hint variant="error">
+ {form.formState.errors.customer_group_ids.message}
+ </Hint>
+ )}
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ filters={filters}
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ isLoading={isLoading}
+ layout="fill"
+ search="autofocus"
+ queryObject={raw}
+ noRecords={{
+ message: t("customers.groups.add.list.noRecordsMessage"),
+ }}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isPending}
+ >
+ {t("actions.save")}
+ </Button>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminCustomerGroup>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+
+ const columns = useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreSelected = !row.getCanSelect()
+ const isSelected = row.getIsSelected() || isPreSelected
+
+ const Component = (
+ <Checkbox
+ checked={isSelected}
+ disabled={isPreSelected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isPreSelected) {
+ return (
+ <Tooltip
+ content={t("customers.groups.alreadyAddedTooltip")}
+ side="right"
+ >
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ columnHelper.accessor("name", {
+ header: () => <TextHeader text={t("fields.name")} />,
+ cell: ({ row }) => {
+ return <TextCell text={row.original?.name || "-"} />
+ },
+ }),
+ ],
+ [t]
+ )
+
+ return columns
+}
diff --git a/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/index.ts b/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/index.ts
new file mode 100644
index 000000000..6bf7c0586
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/add-customer-groups/add-customers-form/index.ts
@@ -0,0 +1 @@
+export * from "./add-customer-groups-form"
diff --git a/packages/vendor/src/pages/customers/[id]/add-customer-groups/index.tsx b/packages/vendor/src/pages/customers/[id]/add-customer-groups/index.tsx
new file mode 100644
index 000000000..ab8680491
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/add-customer-groups/index.tsx
@@ -0,0 +1,13 @@
+// Route: /customers/:id/add-customer-groups
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { AddCustomerGroupsForm } from "./add-customers-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ return (
+ <RouteFocusModal>
+ <AddCustomerGroupsForm customerId={id!} />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/edit-customer-form.tsx b/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/edit-customer-form.tsx
new file mode 100644
index 000000000..0195ae2f7
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/edit-customer-form.tsx
@@ -0,0 +1,180 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { ConditionalTooltip } from "@components/common/conditional-tooltip/index.ts"
+import { Form } from "@components/common/form/index.ts"
+import {
+ RouteDrawer,
+ useRouteModal,
+} from "@components/modals/index.ts"
+import { KeyboundForm } from "@components/utilities/keybound-form/keybound-form.tsx"
+import { useUpdateCustomer } from "@hooks/api/customers.tsx"
+
+type EditCustomerFormProps = {
+ customer: HttpTypes.AdminCustomer
+}
+
+const EditCustomerSchema = zod.object({
+ email: zod.string().email(),
+ first_name: zod.string().optional(),
+ last_name: zod.string().optional(),
+ company_name: zod.string().optional(),
+ phone: zod.string().optional(),
+})
+
+export const EditCustomerForm = ({ customer }: EditCustomerFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditCustomerSchema>>({
+ defaultValues: {
+ email: customer.email || "",
+ first_name: customer.first_name || "",
+ last_name: customer.last_name || "",
+ company_name: customer.company_name || "",
+ phone: customer.phone || "",
+ },
+ resolver: zodResolver(EditCustomerSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateCustomer(customer.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ first_name: data.first_name,
+ last_name: data.last_name,
+ phone: data.phone,
+ company_name: data.company_name,
+ metadata: {
+ email: customer.has_account ? undefined : data.email,
+ },
+ },
+ {
+ onSuccess: ({ customer }) => {
+ toast.success(
+ t("customers.edit.successToast", {
+ email: customer.email,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.email")}</Form.Label>
+ <Form.Control>
+ <ConditionalTooltip
+ showTooltip={customer.has_account}
+ content={t("customers.edit.emailDisabledTooltip")}
+ >
+ <Input {...field} disabled={customer.has_account} />
+ </ConditionalTooltip>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="first_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.firstName")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="last_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.lastName")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="company_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.company")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="phone"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.phone")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button
+ isLoading={isPending}
+ type="submit"
+ variant="primary"
+ size="small"
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/index.ts b/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/index.ts
new file mode 100644
index 000000000..a8ded89ad
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/edit/edit-customer-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-customer-form"
diff --git a/packages/vendor/src/pages/customers/[id]/edit/index.tsx b/packages/vendor/src/pages/customers/[id]/edit/index.tsx
new file mode 100644
index 000000000..944ceb7ae
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/edit/index.tsx
@@ -0,0 +1,24 @@
+// Route: /customers/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCustomer } from "@hooks/api/customers"
+import { EditCustomerForm } from "./edit-customer-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+ const { customer, isLoading, isError, error } = useCustomer(id!)
+
+ if (isError) throw error
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("customers.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && customer && <EditCustomerForm customer={customer} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/index.tsx b/packages/vendor/src/pages/customers/[id]/index.tsx
new file mode 100644
index 000000000..f7fef739a
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/index.tsx
@@ -0,0 +1,70 @@
+// Route: /customers/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useCustomer } from "@hooks/api/customers"
+import { productsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { CustomerGeneralSection } from "./_components/customer-general-section"
+import { CustomerGroupSection } from "./_components/customer-group-section"
+import { CustomerOrderSection } from "./_components/customer-order-section"
+
+// Loader
+const customerDetailQuery = (id: string) => ({
+ queryKey: productsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/customers/${id}`, {
+ method: "GET",
+ query: { fields: "*groups, *groups.customers" },
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = customerDetailQuery(id!)
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type CustomerDetailBreadcrumbProps = UIMatch<HttpTypes.AdminCustomerResponse>
+
+export const Breadcrumb = (props: CustomerDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+ const { customer } = useCustomer(id!, undefined, { initialData: props.data, enabled: Boolean(id) })
+
+ if (!customer) return null
+
+ const name = [customer.first_name, customer.last_name].filter(Boolean).join(" ")
+ return <span>{name || customer.email}</span>
+}
+
+// Main component
+export const Component = () => {
+ const { id } = useParams()
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+ const { customer, isLoading, isError, error } = useCustomer(id!, { fields: "*groups, *groups.customers" }, { initialData })
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !customer) return <SingleColumnPageSkeleton sections={2} />
+ if (isError) throw error
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("customer.details.before"),
+ after: getWidgets("customer.details.after"),
+ }}
+ data={customer}
+ hasOutlet
+ >
+ <CustomerGeneralSection customer={customer} />
+ <CustomerOrderSection customer={customer} />
+ <CustomerGroupSection customer={customer} />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/[id]/metadata/index.tsx b/packages/vendor/src/pages/customers/[id]/metadata/index.tsx
new file mode 100644
index 000000000..8d3b55d9b
--- /dev/null
+++ b/packages/vendor/src/pages/customers/[id]/metadata/index.tsx
@@ -0,0 +1,30 @@
+// Route: /customers/:id/metadata
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { useCustomer, useUpdateCustomer } from "@hooks/api/customers"
+type FetchError = Error & { status?: number }
+
+export const Component = () => {
+ const { id } = useParams()
+ const { customer, isPending, isError, error } = useCustomer(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateCustomer(id!)
+
+ if (!id) throw new Error("Customer ID is required")
+ if (isError) throw error
+
+ const handleUpdate = async (
+ params: { metadata?: Record<string, any> | null },
+ callbacks: { onSuccess: () => void; onError: (error: FetchError) => void }
+ ) => {
+ return mutateAsync({ metadata: params.metadata ?? undefined }, callbacks)
+ }
+
+ return (
+ <MetadataForm
+ metadata={customer?.metadata}
+ hook={handleUpdate}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/customers/_components/customer-list-table/customer-list-table.tsx b/packages/vendor/src/pages/customers/_components/customer-list-table/customer-list-table.tsx
new file mode 100644
index 000000000..741d573b2
--- /dev/null
+++ b/packages/vendor/src/pages/customers/_components/customer-list-table/customer-list-table.tsx
@@ -0,0 +1,101 @@
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "@components/table/data-table"
+import { useCustomers } from "@hooks/api/customers"
+import { useCustomerTableColumns } from "@hooks/table/columns/use-customer-table-columns"
+import { useCustomerTableFilters } from "@hooks/table/filters/use-customer-table-filters"
+import { useCustomerTableQuery } from "@hooks/table/query/use-customer-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const CustomerListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useCustomerTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { customers, count, isLoading, isError, error } = useCustomers(
+ {
+ offset: searchParams.offset,
+ limit: searchParams.limit,
+ },
+ {
+ placeholderData: keepPreviousData,
+ },
+ {
+ groups: searchParams.groups,
+ has_account: searchParams.has_account,
+ order: searchParams.order,
+ q: searchParams.q,
+ }
+ )
+
+ const filters = useCustomerTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: customers ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("customers.domain")}</Heading>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ filters={filters}
+ orderBy={[
+ { key: "email", label: t("fields.email") },
+ {
+ key: "first_name",
+ label: t("fields.firstName"),
+ },
+ { key: "last_name", label: t("fields.lastName") },
+ {
+ key: "has_account",
+ label: t("customers.hasAccount"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ isLoading={isLoading}
+ navigateTo={(row) => row.original.id}
+ queryObject={raw}
+ search
+ noRecords={{
+ message: t("customers.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const useColumns = () => {
+ const columns = useCustomerTableColumns()
+
+ return useMemo(() => [...columns], [columns])
+}
diff --git a/packages/vendor/src/pages/customers/_components/customer-list-table/index.ts b/packages/vendor/src/pages/customers/_components/customer-list-table/index.ts
new file mode 100644
index 000000000..c2e0ca7b0
--- /dev/null
+++ b/packages/vendor/src/pages/customers/_components/customer-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./customer-list-table"
diff --git a/packages/vendor/src/pages/customers/_components/index.ts b/packages/vendor/src/pages/customers/_components/index.ts
new file mode 100644
index 000000000..c2e0ca7b0
--- /dev/null
+++ b/packages/vendor/src/pages/customers/_components/index.ts
@@ -0,0 +1 @@
+export * from "./customer-list-table"
diff --git a/packages/vendor/src/pages/customers/create/create-customer-form/create-customer-form.tsx b/packages/vendor/src/pages/customers/create/create-customer-form/create-customer-form.tsx
new file mode 100644
index 000000000..60bc304bd
--- /dev/null
+++ b/packages/vendor/src/pages/customers/create/create-customer-form/create-customer-form.tsx
@@ -0,0 +1,179 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateCustomer } from "@hooks/api/customers"
+
+const CreateCustomerSchema = zod.object({
+ email: zod.string().email(),
+ first_name: zod.string().optional(),
+ last_name: zod.string().optional(),
+ company_name: zod.string().optional(),
+ phone: zod.string().optional(),
+})
+
+export const CreateCustomerForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const { mutateAsync, isPending } = useCreateCustomer()
+
+ const form = useForm<zod.infer<typeof CreateCustomerSchema>>({
+ defaultValues: {
+ email: "",
+ first_name: "",
+ last_name: "",
+ phone: "",
+ company_name: "",
+ },
+ resolver: zodResolver(CreateCustomerSchema),
+ })
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ email: data.email,
+ first_name: data.first_name || undefined,
+ last_name: data.last_name || undefined,
+ company_name: data.company_name || undefined,
+ phone: data.phone || undefined,
+ },
+ {
+ onSuccess: ({ customer }) => {
+ toast.success(
+ t("customers.create.successToast", {
+ email: customer.email,
+ })
+ )
+ handleSuccess(`/customers/${customer.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col items-center overflow-y-auto py-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <Heading>{t("customers.create.header")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("customers.create.hint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="first_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.firstName")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="last_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.lastName")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.email")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="company_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.company")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="phone"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.phone")}</Form.Label>
+ <Form.Control>
+ <Input autoComplete="off" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ variant="primary"
+ type="submit"
+ isLoading={isPending}
+ >
+ {t("actions.create")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/create/create-customer-form/index.ts b/packages/vendor/src/pages/customers/create/create-customer-form/index.ts
new file mode 100644
index 000000000..e3a418be9
--- /dev/null
+++ b/packages/vendor/src/pages/customers/create/create-customer-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-customer-form"
diff --git a/packages/vendor/src/pages/customers/create/index.tsx b/packages/vendor/src/pages/customers/create/index.tsx
new file mode 100644
index 000000000..3d5d9af1f
--- /dev/null
+++ b/packages/vendor/src/pages/customers/create/index.tsx
@@ -0,0 +1,11 @@
+// Route: /customers/create
+import { RouteFocusModal } from "@components/modals"
+import { CreateCustomerForm } from "./create-customer-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreateCustomerForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/customers/index.tsx b/packages/vendor/src/pages/customers/index.tsx
new file mode 100644
index 000000000..c09859adc
--- /dev/null
+++ b/packages/vendor/src/pages/customers/index.tsx
@@ -0,0 +1,19 @@
+// Route: /customers
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { CustomerListTable } from "./_components/customer-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("customer.list.after"),
+ before: getWidgets("customer.list.before"),
+ }}
+ >
+ <CustomerListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/home/home.tsx b/packages/vendor/src/pages/home/home.tsx
new file mode 100644
index 000000000..c3550838b
--- /dev/null
+++ b/packages/vendor/src/pages/home/home.tsx
@@ -0,0 +1,12 @@
+import { useEffect } from "react"
+import { useNavigate } from "react-router-dom"
+
+export const Home = () => {
+ const navigate = useNavigate()
+
+ useEffect(() => {
+ navigate("/products", { replace: true })
+ }, [navigate])
+
+ return <div />
+}
diff --git a/packages/vendor/src/pages/home/index.ts b/packages/vendor/src/pages/home/index.ts
new file mode 100644
index 000000000..d4531ba93
--- /dev/null
+++ b/packages/vendor/src/pages/home/index.ts
@@ -0,0 +1 @@
+export { Home as Component } from "./home"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx
new file mode 100644
index 000000000..d872a99c3
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/adjust-inventory-drawer.tsx
@@ -0,0 +1,60 @@
+import { InventoryTypes } from "@medusajs/types"
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import {
+ useInventoryItem,
+ useInventoryItemLevels,
+} from "@hooks/api/inventory"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { AdjustInventoryForm } from "./components/adjust-inventory-form"
+
+export const AdjustInventoryDrawer = () => {
+ const { id, location_id } = useParams()
+ const { t } = useTranslation()
+
+ const {
+ inventory_item: inventoryItem,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInventoryItem(id!)
+
+ const { location_levels } = useInventoryItemLevels(id!)
+
+ const inventoryLevel = location_levels?.find(
+ (level: InventoryTypes.InventoryLevelDTO) =>
+ level.location_id === location_id
+ )
+
+ const { stock_location, isLoading: isLoadingLocation } = useStockLocation(
+ location_id!
+ )
+
+ const ready =
+ !isLoading &&
+ inventoryItem &&
+ inventoryLevel &&
+ !isLoadingLocation &&
+ stock_location
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("inventory.manageLocations")}</Heading>
+ </RouteDrawer.Header>
+ {ready && (
+ <AdjustInventoryForm
+ item={inventoryItem}
+ level={inventoryLevel}
+ location={stock_location}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/components/adjust-inventory-form.tsx b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/components/adjust-inventory-form.tsx
new file mode 100644
index 000000000..ef10e86eb
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/components/adjust-inventory-form.tsx
@@ -0,0 +1,181 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes, InventoryLevelDTO } from "@medusajs/types"
+import { Button, Input, Text, toast } from "@medusajs/ui"
+import { useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateInventoryLevel } from "@hooks/api/inventory"
+import { castNumber } from "@lib/cast-number"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+import { sanitizeNumberInput } from "@lib/sanitize-number-input"
+
+type AdjustInventoryFormProps = {
+ item: HttpTypes.AdminInventoryItem
+ level: InventoryLevelDTO
+ location: VendorExtendedAdminStockLocation
+}
+
+const AttributeGridRow = ({
+ title,
+ value,
+}: {
+ title: string
+ value: string | number
+}) => {
+ return (
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {title}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {value}
+ </Text>
+ </div>
+ )
+}
+
+export const AdjustInventoryForm = ({
+ item,
+ level,
+ location,
+}: AdjustInventoryFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const AdjustInventorySchema = z
+ .object({
+ stocked_quantity: z.union([z.number(), z.string()]),
+ })
+ .superRefine((data, ctx) => {
+ const quantity = data.stocked_quantity
+ ? castNumber(data.stocked_quantity)
+ : null
+
+ if (quantity === null) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.invalid_type,
+ expected: "number",
+ received: "undefined",
+ path: ["stocked_quantity"],
+ })
+
+ return
+ }
+
+ if (quantity < level.reserved_quantity) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: t("inventory.adjustInventory.errors.stockedQuantity", {
+ quantity: level.reserved_quantity,
+ }),
+ path: ["stocked_quantity"],
+ })
+ }
+ })
+
+ const form = useForm<z.infer<typeof AdjustInventorySchema>>({
+ defaultValues: {
+ stocked_quantity: level.stocked_quantity,
+ },
+ resolver: zodResolver(AdjustInventorySchema),
+ })
+
+ const stockedQuantityUpdate = useWatch({
+ control: form.control,
+ name: "stocked_quantity",
+ })
+
+ const availableQuantity = stockedQuantityUpdate
+ ? castNumber(stockedQuantityUpdate) - level.reserved_quantity
+ : 0 - level.reserved_quantity
+
+ const { mutateAsync, isPending: isLoading } = useUpdateInventoryLevel(
+ item.id,
+ level.location_id
+ )
+
+ const handleSubmit = form.handleSubmit(async (value) => {
+ await mutateAsync(
+ {
+ stocked_quantity: castNumber(value.stocked_quantity),
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("inventory.toast.updateLevel"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-auto">
+ <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-4 divide-y rounded-lg border">
+ <AttributeGridRow
+ title={t("fields.title")}
+ value={item.title ?? "-"}
+ />
+ <AttributeGridRow title={t("fields.sku")} value={item.sku!} />
+ <AttributeGridRow
+ title={t("locations.domain")}
+ value={location.name}
+ />
+ <AttributeGridRow
+ title={t("inventory.reserved")}
+ value={level.reserved_quantity}
+ />
+ <AttributeGridRow
+ title={t("inventory.available")}
+ value={availableQuantity}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="stocked_quantity"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.inStock")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ value={value}
+ onChange={onChange}
+ onKeyDown={(e) => sanitizeNumberInput(e, [",", "."])}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/index.ts b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/index.ts
new file mode 100644
index 000000000..63d0eec75
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/adjust-inventory/index.ts
@@ -0,0 +1 @@
+export { AdjustInventoryDrawer as Component } from "./adjust-inventory-drawer"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx
new file mode 100644
index 000000000..cc0dabd55
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/components/edit-item-attributes-form.tsx
@@ -0,0 +1,252 @@
+import * as zod from "zod"
+
+import { Button, Input, toast } from "@medusajs/ui"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateInventoryItem } from "@hooks/api/inventory"
+
+type EditInventoryItemAttributeFormProps = {
+ item: HttpTypes.AdminInventoryItem
+}
+
+const EditInventoryItemAttributesSchema = z.object({
+ height: z.number().positive().optional(),
+ width: z.number().positive().optional(),
+ length: z.number().positive().optional(),
+ weight: z.number().positive().optional(),
+ mid_code: z.string().optional(),
+ hs_code: z.string().optional(),
+ origin_country: z.string().optional(),
+})
+
+const getDefaultValues = (item: HttpTypes.AdminInventoryItem) => {
+ return {
+ height: item.height ?? undefined,
+ width: item.width ?? undefined,
+ length: item.length ?? undefined,
+ weight: item.weight ?? undefined,
+ mid_code: item.mid_code ?? undefined,
+ hs_code: item.hs_code ?? undefined,
+ origin_country: item.origin_country ?? undefined,
+ }
+}
+
+export const EditInventoryItemAttributesForm = ({
+ item,
+}: EditInventoryItemAttributeFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const form = useForm<zod.infer<typeof EditInventoryItemAttributesSchema>>({
+ defaultValues: getDefaultValues(item),
+ resolver: zodResolver(EditInventoryItemAttributesSchema),
+ })
+
+ const { mutateAsync, isPending: isLoading } = useUpdateInventoryItem(item.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(values, {
+ onSuccess: () => {
+ toast.success(t("inventory.toast.updateItem"))
+ handleSuccess()
+ },
+ onError: (error) => toast.error(error.message),
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.height")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="width"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.width")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.length")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.weight")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.midCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.hsCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("fields.countryOfOrigin")}
+ </Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/edit-item-attributes-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/edit-item-attributes-drawer.tsx
new file mode 100644
index 000000000..cb5814aa5
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/edit-item-attributes-drawer.tsx
@@ -0,0 +1,33 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useInventoryItem } from "@hooks/api/inventory"
+import { EditInventoryItemAttributesForm } from "./components/edit-item-attributes-form"
+
+export const InventoryItemAttributesEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const {
+ inventory_item: inventoryItem,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInventoryItem(id!)
+
+ const ready = !isLoading && inventoryItem
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("products.editAttributes")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <EditInventoryItemAttributesForm item={inventoryItem} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/index.ts b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/index.ts
new file mode 100644
index 000000000..75cf07cbd
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item-attributes/index.ts
@@ -0,0 +1 @@
+export { InventoryItemAttributesEdit as Component } from "./edit-item-attributes-drawer"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/components/edit-item-form.tsx b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/components/edit-item-form.tsx
new file mode 100644
index 000000000..6df14fe35
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/components/edit-item-form.tsx
@@ -0,0 +1,104 @@
+import * as zod from "zod"
+
+import { Button, Input, toast } from "@medusajs/ui"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateInventoryItem } from "@hooks/api/inventory"
+
+type EditInventoryItemFormProps = {
+ item: HttpTypes.AdminInventoryItem
+}
+
+const EditInventoryItemSchema = z.object({
+ title: z.string().optional(),
+ sku: z.string().min(1),
+})
+
+const getDefaultValues = (item: HttpTypes.AdminInventoryItem) => {
+ return {
+ title: item.title ?? undefined,
+ sku: item.sku ?? undefined,
+ }
+}
+
+export const EditInventoryItemForm = ({ item }: EditInventoryItemFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const form = useForm<zod.infer<typeof EditInventoryItemSchema>>({
+ defaultValues: getDefaultValues(item),
+ resolver: zodResolver(EditInventoryItemSchema),
+ })
+
+ const { mutateAsync, isPending: isLoading } = useUpdateInventoryItem(item.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ mutateAsync(values as any, {
+ onSuccess: () => {
+ toast.success(t("inventory.toast.updateItem"))
+ handleSuccess()
+ },
+ onError: (e) => toast.error(e.message),
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="sku"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.sku")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/edit-item-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/edit-item-drawer.tsx
new file mode 100644
index 000000000..d14746870
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/edit-item-drawer.tsx
@@ -0,0 +1,33 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useInventoryItem } from "@hooks/api/inventory"
+import { EditInventoryItemForm } from "./components/edit-item-form"
+
+export const InventoryItemEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const {
+ inventory_item: inventoryItem,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInventoryItem(id!)
+
+ const ready = !isLoading && inventoryItem
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("inventory.editItemDetails")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <EditInventoryItemForm item={inventoryItem} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/index.ts b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/index.ts
new file mode 100644
index 000000000..b278dc1e4
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/edit-inventory-item/index.ts
@@ -0,0 +1 @@
+export { InventoryItemEdit as Component } from "./edit-item-drawer"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/index.ts b/packages/vendor/src/pages/inventory/[id]/_components/index.ts
new file mode 100644
index 000000000..100ce5dae
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/index.ts
@@ -0,0 +1,11 @@
+export * from "./adjust-inventory"
+export * from "./edit-inventory-item"
+export * from "./edit-inventory-item-attributes"
+export * from "./inventory-item-attributes"
+export * from "./inventory-item-general-section"
+export * from "./inventory-item-location-levels"
+export * from "./inventory-item-reservations"
+export * from "./inventory-item-variants"
+export * from "./location-levels-table"
+export * from "./manage-locations"
+export * from "./reservations-table"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-attributes/attributes-section.tsx b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-attributes/attributes-section.tsx
new file mode 100644
index 000000000..bd8c9f11b
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-attributes/attributes-section.tsx
@@ -0,0 +1,49 @@
+import { Container, Heading } from "@medusajs/ui"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { InventoryTypes } from "@medusajs/types"
+import { PencilSquare } from "@medusajs/icons"
+import { SectionRow } from "@components/common/section"
+import { getFormattedCountry } from "@lib/addresses"
+import { useTranslation } from "react-i18next"
+
+type InventoryItemAttributeSectionProps = {
+ inventoryItem: InventoryTypes.InventoryItemDTO
+}
+
+export const InventoryItemAttributeSection = ({
+ inventoryItem,
+}: InventoryItemAttributeSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.attributes")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "attributes",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <SectionRow title={t("fields.height")} value={inventoryItem.height} />
+ <SectionRow title={t("fields.width")} value={inventoryItem.width} />
+ <SectionRow title={t("fields.length")} value={inventoryItem.length} />
+ <SectionRow title={t("fields.weight")} value={inventoryItem.weight} />
+ <SectionRow title={t("fields.midCode")} value={inventoryItem.mid_code} />
+ <SectionRow title={t("fields.hsCode")} value={inventoryItem.hs_code} />
+ <SectionRow
+ title={t("fields.countryOfOrigin")}
+ value={getFormattedCountry(inventoryItem.origin_country)}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-general-section.tsx b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-general-section.tsx
new file mode 100644
index 000000000..5b3ff459e
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-general-section.tsx
@@ -0,0 +1,82 @@
+import { Container, Heading } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { PencilSquare } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+
+type InventoryItemGeneralSectionProps = {
+ inventoryItem: HttpTypes.AdminInventoryItemResponse["inventory_item"]
+}
+export const InventoryItemGeneralSection = ({
+ inventoryItem,
+}: InventoryItemGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const stockedQuantity =
+ inventoryItem.location_levels?.reduce(
+ (acc, level) => acc + level.stocked_quantity,
+ 0
+ ) || 0
+ const reservedQuantity =
+ inventoryItem.location_levels?.reduce(
+ (acc, level) => acc + level.reserved_quantity,
+ 0
+ ) || 0
+ const availableQuantity = stockedQuantity - reservedQuantity
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>
+ {inventoryItem.title ?? inventoryItem.sku} {t("fields.details")}
+ </Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: "edit",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <SectionRow title={t("fields.sku")} value={inventoryItem.sku ?? "-"} />
+ <SectionRow
+ title={t("fields.inStock")}
+ value={getQuantityFormat(
+ stockedQuantity,
+ inventoryItem.location_levels?.length
+ )}
+ />
+
+ <SectionRow
+ title={t("inventory.reserved")}
+ value={getQuantityFormat(
+ reservedQuantity,
+ inventoryItem.location_levels?.length
+ )}
+ />
+ <SectionRow
+ title={t("inventory.available")}
+ value={getQuantityFormat(
+ availableQuantity,
+ inventoryItem.location_levels?.length
+ )}
+ />
+ </Container>
+ )
+}
+
+const getQuantityFormat = (quantity: number, locations?: number) => {
+ if (quantity !== undefined && !isNaN(quantity)) {
+ return `${quantity} across ${locations ?? "-"} locations`
+ }
+
+ return "-"
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-location-levels.tsx b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-location-levels.tsx
new file mode 100644
index 000000000..8904d645b
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-location-levels.tsx
@@ -0,0 +1,26 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { ItemLocationListTable } from "./location-levels-table/location-list-table"
+
+type InventoryItemLocationLevelsSectionProps = {
+ inventoryItem: HttpTypes.AdminInventoryItemResponse["inventory_item"]
+}
+export const InventoryItemLocationLevelsSection = ({
+ inventoryItem,
+}: InventoryItemLocationLevelsSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("inventory.locationLevels")}</Heading>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="locations">{t("inventory.manageLocations")}</Link>
+ </Button>
+ </div>
+ <ItemLocationListTable inventory_item_id={inventoryItem.id} />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-reservations.tsx b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-reservations.tsx
new file mode 100644
index 000000000..fce8a1290
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-reservations.tsx
@@ -0,0 +1,23 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ReservationItemTable } from "./reservations-table/reservation-list-table"
+
+type InventoryItemLocationLevelsSectionProps = {
+ inventoryItem: HttpTypes.AdminInventoryItemResponse["inventory_item"]
+}
+export const InventoryItemReservationsSection = ({
+ inventoryItem,
+}: InventoryItemLocationLevelsSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("reservations.domain")}</Heading>
+ </div>
+ <ReservationItemTable inventoryItem={inventoryItem} />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-variants/variants-section.tsx b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-variants/variants-section.tsx
new file mode 100644
index 000000000..d0fedbac0
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/inventory-item-variants/variants-section.tsx
@@ -0,0 +1,72 @@
+import { TriangleRightMini } from "@medusajs/icons"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ProductVariantDTO } from "@medusajs/types"
+import { Thumbnail } from "@components/common/thumbnail"
+
+type InventoryItemVariantsSectionProps = {
+ variants: ProductVariantDTO[]
+}
+
+export const InventoryItemVariantsSection = ({
+ variants,
+}: InventoryItemVariantsSectionProps) => {
+ const { t } = useTranslation()
+
+ if (!variants?.length) {
+ return null
+ }
+
+ return (
+ <Container className="p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("inventory.associatedVariants")}</Heading>
+ </div>
+
+ <div className="txt-small flex flex-col gap-2 px-2 pb-2">
+ {variants.map((variant) => {
+ const link = variant.product
+ ? `/products/${variant.product.id}/variants/${variant.id}`
+ : null
+
+ const Inner = (
+ <div className="shadow-elevation-card-rest bg-ui-bg-component rounded-md px-4 py-2 transition-colors">
+ <div className="flex items-center gap-3">
+ <div className="shadow-elevation-card-rest rounded-md">
+ <Thumbnail src={variant.product?.thumbnail} />
+ </div>
+ <div className="flex flex-1 flex-col">
+ <span className="text-ui-fg-base font-medium">
+ {variant.title}
+ </span>
+ <span className="text-ui-fg-subtle">
+ {variant.options.map((o) => o.value).join(" ⋅ ")}
+ </span>
+ </div>
+ <div className="size-7 flex items-center justify-center">
+ <TriangleRightMini className="text-ui-fg-muted" />
+ </div>
+ </div>
+ </div>
+ )
+
+ if (!link) {
+ return <div key={variant.id}>{Inner}</div>
+ }
+
+ return (
+ <Link
+ to={link}
+ key={variant.id}
+ className="outline-none focus-within:shadow-borders-interactive-with-focus rounded-md [&:hover>div]:bg-ui-bg-component-hover"
+ >
+ {Inner}
+ </Link>
+ )
+ })}
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-actions.tsx b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-actions.tsx
new file mode 100644
index 000000000..d282591eb
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-actions.tsx
@@ -0,0 +1,62 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+
+import { InventoryTypes } from "@medusajs/types"
+import { usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteInventoryItemLevel } from "@hooks/api/inventory"
+
+export const LocationActions = ({
+ level,
+}: {
+ level: InventoryTypes.InventoryLevelDTO
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteInventoryItemLevel(
+ level.inventory_item_id,
+ level.location_id
+ )
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("inventory.deleteWarning"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync()
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `locations/${level.location_id}`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ disabled:
+ level.reserved_quantity > 0 || level.stocked_quantity > 0,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx
new file mode 100644
index 000000000..a5cc6945a
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/location-list-table.tsx
@@ -0,0 +1,51 @@
+import { _DataTable } from "@components/table/data-table"
+import { useInventoryItemLevels } from "@hooks/api/inventory"
+import { useDataTable } from "@hooks/use-data-table"
+import { useLocationListTableColumns } from "./use-location-list-table-columns"
+import { useLocationLevelTableQuery } from "./use-location-list-table-query"
+
+const PAGE_SIZE = 20
+
+export const ItemLocationListTable = ({
+ inventory_item_id,
+}: {
+ inventory_item_id: string
+}) => {
+ const { searchParams, raw } = useLocationLevelTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { location_levels, count, isLoading } = useInventoryItemLevels(
+ inventory_item_id,
+ {
+ ...searchParams,
+ fields: "*stock_locations",
+ }
+ )
+ const columns = useLocationListTableColumns()
+
+ const filteredLocationLevels = location_levels?.filter(
+ (level) => level.stock_locations.length > 0
+ )
+
+ const { table } = useDataTable({
+ data: filteredLocationLevels ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={filteredLocationLevels?.length}
+ isLoading={isLoading}
+ pagination
+ queryObject={raw}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-columns.tsx b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-columns.tsx
new file mode 100644
index 000000000..8617353d5
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-columns.tsx
@@ -0,0 +1,98 @@
+import { InventoryTypes, StockLocationDTO } from "@medusajs/types"
+
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"
+import { LocationActions } from "./location-actions"
+
+/**
+ * Adds missing properties to the InventoryLevelDTO type.
+ */
+interface ExtendedLocationLevel extends InventoryTypes.InventoryLevelDTO {
+ stock_locations: StockLocationDTO[]
+ reserved_quantity: number
+ stocked_quantity: number
+ available_quantity: number
+}
+
+const columnHelper = createColumnHelper<ExtendedLocationLevel>()
+
+export const useLocationListTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "location",
+ header: t("fields.location"),
+ cell: ({ row }) => {
+ const locationName = row.original.stock_locations?.map((location) => location.name).join(", ")
+
+ if (!locationName) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{locationName.toString()}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("reserved_quantity", {
+ header: t("inventory.reserved"),
+ cell: ({ getValue }) => {
+ const quantity = getValue()
+
+ if (Number.isNaN(quantity)) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{quantity}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("stocked_quantity", {
+ header: t("fields.inStock"),
+ cell: ({ getValue }) => {
+ const stockedQuantity = getValue()
+
+ if (Number.isNaN(stockedQuantity)) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{stockedQuantity}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("available_quantity", {
+ header: t("inventory.available"),
+ cell: ({ getValue }) => {
+ const availableQuantity = getValue()
+
+ if (Number.isNaN(availableQuantity)) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{availableQuantity}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <LocationActions level={row.original} />,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-query.tsx b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-query.tsx
new file mode 100644
index 000000000..e829619d2
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/location-levels-table/use-location-list-table-query.tsx
@@ -0,0 +1,44 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useLocationLevelTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(
+ [
+ "id",
+ "location_id",
+ "stocked_quantity",
+ "reserved_quantity",
+ "incoming_quantity",
+ "available_quantity",
+ "*stock_locations",
+ ],
+ prefix
+ )
+
+ const { reserved_quantity, stocked_quantity, available_quantity, ...params } =
+ raw
+
+ const searchParams = {
+ limit: pageSize,
+ reserved_quantity: reserved_quantity
+ ? JSON.parse(reserved_quantity)
+ : undefined,
+ stocked_quantity: stocked_quantity
+ ? JSON.parse(stocked_quantity)
+ : undefined,
+ available_quantity: available_quantity
+ ? JSON.parse(available_quantity)
+ : undefined,
+ ...params,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/location-item.tsx b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/location-item.tsx
new file mode 100644
index 000000000..eadd4f108
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/location-item.tsx
@@ -0,0 +1,51 @@
+import { Checkbox, Text, clx } from "@medusajs/ui"
+
+import { StockLocationDTO } from "@medusajs/types"
+
+type LocationItemProps = {
+ selected: boolean
+ onSelect: (selected: boolean) => void
+ location: StockLocationDTO
+}
+
+export const LocationItem = ({
+ selected,
+ onSelect,
+ location,
+}: LocationItemProps) => {
+ return (
+ <div
+ className={clx(
+ "flex w-full cursor-pointer gap-x-2 rounded-lg border px-2 py-2",
+ {
+ "border-ui-border-interactive ": selected,
+ }
+ )}
+ onClick={() => onSelect(!selected)}
+ >
+ <div className="h-5 w-5">
+ <Checkbox
+ onClick={(e) => {
+ e.stopPropagation()
+ onSelect(!selected)
+ }}
+ checked={selected}
+ />
+ </div>
+ <div className="flex w-full flex-col">
+ <Text size="small" leading="compact" weight="plus">
+ {location.name}
+ </Text>
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {[
+ location.address?.address_1,
+ location.address?.city,
+ location.address?.country_code,
+ ]
+ .filter((el) => !!el)
+ .join(", ")}
+ </Text>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx
new file mode 100644
index 000000000..547bcaeed
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/components/manage-locations-form.tsx
@@ -0,0 +1,195 @@
+import * as zod from "zod"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminInventoryItem, AdminStockLocation } from "@medusajs/types"
+import { Button, Text, toast } from "@medusajs/ui"
+import { useFieldArray, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { useBatchInventoryItemLocationLevels } from "@hooks/api/inventory"
+
+import { useMemo } from "react"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { LocationItem } from "./location-item"
+
+type EditInventoryItemAttributeFormProps = {
+ item: AdminInventoryItem
+ locations: AdminStockLocation[]
+}
+
+const EditInventoryItemAttributesSchema = z.object({
+ locations: z.array(
+ z.object({
+ id: z.string(),
+ location_id: z.string().optional(),
+ selected: z.boolean(),
+ })
+ ),
+})
+
+const getDefaultValues = (
+ allLocations: AdminStockLocation[],
+ existingLevels: Set<string>
+) => {
+ return {
+ locations: allLocations.map((location) => ({
+ ...location,
+ location_id: location.id,
+ selected: existingLevels.has(location.id),
+ })),
+ }
+}
+
+export const ManageLocationsForm = ({
+ item,
+ locations,
+}: EditInventoryItemAttributeFormProps) => {
+ const existingLocationLevels = useMemo(
+ () => new Set(item.location_levels?.map((l) => l.location_id) ?? []),
+ [item.location_levels]
+ )
+
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditInventoryItemAttributesSchema>>({
+ defaultValues: getDefaultValues(locations, existingLocationLevels),
+ resolver: zodResolver(EditInventoryItemAttributesSchema),
+ })
+
+ const { fields: locationFields, update: updateField } = useFieldArray({
+ control: form.control,
+ name: "locations",
+ })
+
+ const { mutateAsync } = useBatchInventoryItemLocationLevels(item.id)
+
+ const handleSubmit = form.handleSubmit(async ({ locations }) => {
+ // Changes in selected locations
+
+ const [selectedLocations, unselectedLocations] = locations.reduce(
+ (acc, location) => {
+ if (!location.location_id) {
+ return acc
+ }
+
+ // If the location is not changed do nothing
+ if (
+ (!location.selected &&
+ !existingLocationLevels.has(location.location_id)) ||
+ (location.selected &&
+ existingLocationLevels.has(location.location_id))
+ ) {
+ return acc
+ }
+
+ if (location.selected) {
+ acc[0].push(location.location_id)
+ } else {
+ acc[1].push(location.location_id)
+ }
+ return acc
+ },
+ [[], []] as [string[], string[]]
+ )
+
+ if (selectedLocations.length === 0 && unselectedLocations.length === 0) {
+ return handleSuccess()
+ }
+
+ await mutateAsync(
+ {
+ create: selectedLocations.length
+ ? selectedLocations.map((item) => ({ location_id: item }))
+ : undefined,
+ // update: [],
+ delete: unselectedLocations,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("inventory.toast.updateLocations"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
+ <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-2 divide-y rounded-lg border">
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {t("fields.title")}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {item.title ?? "-"}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {t("fields.sku")}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {item.sku}
+ </Text>
+ </div>
+ </div>
+ <div className="flex flex-col">
+ <Text size="small" weight="plus" leading="compact">
+ {t("locations.domain")}
+ </Text>
+ <div className="text-ui-fg-subtle flex w-full justify-between">
+ <Text size="small" leading="compact">
+ {t("locations.selectLocations")}
+ </Text>
+ <Text size="small" leading="compact">
+ {"("}
+ {t("general.countOfTotalSelected", {
+ count: locationFields.filter((l) => l.selected).length,
+ total: locations.length,
+ })}
+ {")"}
+ </Text>
+ </div>
+ </div>
+ {locationFields.map((location, idx) => {
+ return (
+ <LocationItem
+ selected={location.selected}
+ location={location as any}
+ onSelect={() =>
+ updateField(idx, {
+ ...location,
+ selected: !location.selected,
+ })
+ }
+ key={location.id}
+ />
+ )
+ })}
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={false}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/index.ts b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/index.ts
new file mode 100644
index 000000000..e8b6358c3
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/index.ts
@@ -0,0 +1 @@
+export { ManageLocationsDrawer as Component } from "./manage-locations-drawer"
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx
new file mode 100644
index 000000000..c8180d804
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/manage-locations/manage-locations-drawer.tsx
@@ -0,0 +1,43 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useInventoryItem } from "@hooks/api/inventory"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { ManageLocationsForm } from "./components/manage-locations-form"
+import { INVENTORY_DETAIL_FIELDS } from "../../constants"
+
+export const ManageLocationsDrawer = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const {
+ inventory_item: inventoryItem,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInventoryItem(id!, {
+ fields: INVENTORY_DETAIL_FIELDS,
+ })
+
+ const { stock_locations, isLoading: loadingLocations } = useStockLocations()
+
+ const ready =
+ !isLoading && !loadingLocations && inventoryItem && stock_locations
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("inventory.manageLocations")}</Heading>
+ </RouteDrawer.Header>
+ {ready && (
+ <ManageLocationsForm item={inventoryItem} locations={stock_locations} />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-actions.tsx b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-actions.tsx
new file mode 100644
index 000000000..d2fc8af86
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-actions.tsx
@@ -0,0 +1,64 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { toast, usePrompt } from "@medusajs/ui"
+
+import { HttpTypes } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteReservationItem } from "@hooks/api/reservations"
+
+export const ReservationActions = ({
+ reservation,
+}: {
+ reservation: HttpTypes.AdminReservation
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteReservationItem(reservation.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("inventory.deleteWarning"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("inventory.reservation.deleteSuccessToast"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/reservations/${reservation.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-list-table.tsx b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-list-table.tsx
new file mode 100644
index 000000000..be3cd4461
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/reservation-list-table.tsx
@@ -0,0 +1,73 @@
+import { HttpTypes } from "@medusajs/types"
+import { useMemo } from "react"
+
+import { _DataTable } from "@components/table/data-table"
+import { useStockLocations } from "@hooks/api"
+import { useReservationItems } from "@hooks/api/reservations"
+import { useDataTable } from "@hooks/use-data-table"
+import {
+ ExtendedReservationItem,
+ useReservationTableColumn,
+} from "./use-reservation-list-table-columns"
+import { useReservationsTableQuery } from "./use-reservation-list-table-query"
+
+const PAGE_SIZE = 20
+
+export const ReservationItemTable = ({
+ inventoryItem,
+}: {
+ inventoryItem: HttpTypes.AdminInventoryItemResponse["inventory_item"]
+}) => {
+ const { searchParams, raw } = useReservationsTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { reservations, count, isPending, isError, error } =
+ useReservationItems(
+ {
+ ...searchParams,
+ },
+ undefined,
+ { inventory_item_id: [inventoryItem.id] }
+ )
+
+ const { stock_locations } = useStockLocations({
+ id: (reservations || []).map((r) => r.location_id),
+ })
+
+ const data = useMemo<ExtendedReservationItem[]>(() => {
+ const locationMap = new Map((stock_locations || []).map((l) => [l.id, l]))
+
+ return (reservations || []).map((r) => ({
+ ...r,
+ location: locationMap.get(r.location_id),
+ }))
+ }, [reservations, stock_locations])
+
+ const columns = useReservationTableColumn({ sku: inventoryItem.sku! })
+
+ const { table } = useDataTable({
+ data: data ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row: ExtendedReservationItem) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isPending}
+ pagination
+ queryObject={raw}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-columns.tsx b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-columns.tsx
new file mode 100644
index 000000000..53d6501cc
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-columns.tsx
@@ -0,0 +1,76 @@
+import { HttpTypes } from "@medusajs/types"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { CreatedAtCell } from "@components/table/table-cells/common/created-at-cell"
+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"
+import {
+ TextCell,
+ TextHeader,
+} from "@components/table/table-cells/common/text-cell"
+import { ReservationActions } from "./reservation-actions"
+
+/**
+ * Adds missing properties to the InventoryItemDTO type.
+ */
+export interface ExtendedReservationItem extends HttpTypes.AdminReservation {
+ line_item?: { order_id: string }
+ location?: HttpTypes.AdminStockLocation
+}
+
+const columnHelper = createColumnHelper<ExtendedReservationItem>()
+
+export const useReservationTableColumn = ({ sku }: { sku: string }) => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "sku",
+ header: () => <TextHeader text={t("fields.sku")} />,
+ cell: () => {
+ return <TextCell text={sku} />
+ },
+ }),
+ // columnHelper.accessor("line_item.order_id", {
+ // header: () => <TextHeader text={t("inventory.reservation.orderID")} />,
+ // cell: ({ getValue, row }) => {
+ // const orderId = getValue()
+
+ // if (!orderId) {
+ // return <PlaceholderCell />
+ // }
+
+ // return <TextCell text={orderId} />
+ // },
+ // }),
+ columnHelper.accessor("location.name", {
+ header: () => <TextHeader text={t("inventory.reservation.location")} />,
+ cell: ({ getValue }) => {
+ const location = getValue()
+
+ if (!location) {
+ return <PlaceholderCell />
+ }
+
+ return <TextCell text={location} />
+ },
+ }),
+ columnHelper.accessor("created_at", {
+ header: () => <TextHeader text={t("fields.createdAt")} />,
+ cell: ({ getValue }) => <CreatedAtCell date={getValue()} />,
+ }),
+ columnHelper.accessor("quantity", {
+ header: () => <TextHeader text={t("fields.quantity")} align="right" />,
+ cell: ({ getValue }) => {
+ return <TextCell text={getValue()} align="right" />
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <ReservationActions reservation={row.original} />,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-query.tsx b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-query.tsx
new file mode 100644
index 000000000..3fd30e13f
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/_components/reservations-table/use-reservation-list-table-query.tsx
@@ -0,0 +1,35 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useReservationsTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(
+ [
+ "id",
+ "location_id",
+ "inventory_item_id",
+ "quantity",
+ "line_item_id",
+ "description",
+ "created_by",
+ ],
+ prefix
+ )
+
+ const { quantity, ...params } = raw
+
+ const searchParams = {
+ limit: pageSize,
+ quantity: quantity ? JSON.parse(quantity) : undefined,
+ ...params,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/constants.ts b/packages/vendor/src/pages/inventory/[id]/constants.ts
new file mode 100644
index 000000000..dfcd5177e
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/constants.ts
@@ -0,0 +1,2 @@
+export const INVENTORY_DETAIL_FIELDS =
+ "*variants,*variants.product,*variants.options,+stocked_quantity,+reserved_quantity,*location_levels"
diff --git a/packages/vendor/src/pages/inventory/[id]/index.tsx b/packages/vendor/src/pages/inventory/[id]/index.tsx
new file mode 100644
index 000000000..663ca6d77
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/index.tsx
@@ -0,0 +1,78 @@
+// Route: /inventory/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useInventoryItem } from "@hooks/api/inventory"
+import { inventoryItemsQueryKeys } from "@hooks/api/inventory"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { InventoryItemAttributeSection } from "./_components/inventory-item-attributes/attributes-section"
+import { InventoryItemGeneralSection } from "./_components/inventory-item-general-section"
+import { InventoryItemLocationLevelsSection } from "./_components/inventory-item-location-levels"
+import { InventoryItemReservationsSection } from "./_components/inventory-item-reservations"
+import { InventoryItemVariantsSection } from "./_components/inventory-item-variants/variants-section"
+import { INVENTORY_DETAIL_FIELDS } from "./constants"
+
+// Loader
+const inventoryDetailQuery = (id: string) => ({
+ queryKey: inventoryItemsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/inventory-items/${id}?fields=${INVENTORY_DETAIL_FIELDS}`, { method: "GET" }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = inventoryDetailQuery(id!)
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type InventoryDetailBreadcrumbProps = UIMatch<HttpTypes.AdminInventoryItemResponse>
+
+export const Breadcrumb = (props: InventoryDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+ const { inventory_item } = useInventoryItem(id!, { fields: INVENTORY_DETAIL_FIELDS }, { initialData: props.data, enabled: Boolean(id) })
+
+ if (!inventory_item) return null
+ return <span>{inventory_item.title ?? inventory_item.sku ?? id}</span>
+}
+
+// Main component
+export const Component = () => {
+ const { id } = useParams()
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+ const { inventory_item, isPending: isLoading, isError, error } = useInventoryItem(id!, { fields: INVENTORY_DETAIL_FIELDS }, { initialData })
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !inventory_item) {
+ return <TwoColumnPageSkeleton showJSON mainSections={3} sidebarSections={2} showMetadata />
+ }
+
+ if (isError) throw error
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("inventory_item.details.after"),
+ before: getWidgets("inventory_item.details.before"),
+ sideAfter: getWidgets("inventory_item.details.side.after"),
+ sideBefore: getWidgets("inventory_item.details.side.before"),
+ }}
+ data={inventory_item}
+ >
+ <TwoColumnPage.Main>
+ <InventoryItemGeneralSection inventoryItem={inventory_item} />
+ <InventoryItemLocationLevelsSection inventoryItem={inventory_item} />
+ <InventoryItemReservationsSection inventoryItem={inventory_item} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <InventoryItemVariantsSection variants={(inventory_item as any).variants} />
+ <InventoryItemAttributeSection inventoryItem={inventory_item as any} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/metadata/index.tsx b/packages/vendor/src/pages/inventory/[id]/metadata/index.tsx
new file mode 100644
index 000000000..c73809fc4
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/metadata/index.tsx
@@ -0,0 +1,32 @@
+// Route: /inventory/:id/metadata
+import { useParams } from "react-router-dom"
+import { useInventoryItem, useUpdateInventoryItem } from "@hooks/api"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { RouteDrawer } from "@components/modals"
+type FetchError = Error & { status?: number }
+
+export const Component = () => {
+ const { id } = useParams()
+ const { inventory_item, isPending, isError, error } = useInventoryItem(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateInventoryItem(id!)
+
+ if (isError) throw error
+
+ const handleUpdate = async (
+ params: { metadata?: Record<string, any> | null },
+ callbacks: { onSuccess: () => void; onError: (error: FetchError) => void }
+ ) => {
+ return mutateAsync({ metadata: params.metadata ?? undefined }, callbacks)
+ }
+
+ return (
+ <RouteDrawer>
+ <MetadataForm
+ isPending={isPending}
+ isMutating={isMutating}
+ hook={handleUpdate}
+ metadata={inventory_item?.metadata}
+ />
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/schema.ts b/packages/vendor/src/pages/inventory/[id]/schema.ts
new file mode 100644
index 000000000..ebaaa63c6
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/schema.ts
@@ -0,0 +1,22 @@
+import { z } from "zod"
+
+const LocationQuantitySchema = z.object({
+ id: z.string().optional(),
+ quantity: z.union([z.number(), z.string()]),
+ checked: z.boolean(),
+ disabledToggle: z.boolean(),
+})
+
+const InventoryLocationsSchema = z.record(LocationQuantitySchema)
+
+const InventoryItemSchema = z.object({
+ locations: InventoryLocationsSchema,
+})
+
+export const InventoryStockSchema = z.object({
+ inventory_items: z.record(InventoryItemSchema),
+})
+
+export type InventoryLocationsSchema = z.infer<typeof InventoryLocationsSchema>
+export type InventoryItemSchema = z.infer<typeof InventoryItemSchema>
+export type InventoryStockSchema = z.infer<typeof InventoryStockSchema>
diff --git a/packages/vendor/src/pages/inventory/[id]/stock/index.tsx b/packages/vendor/src/pages/inventory/[id]/stock/index.tsx
new file mode 100644
index 000000000..02b74f6fd
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/stock/index.tsx
@@ -0,0 +1,39 @@
+// Route: /inventory/:id/stock
+import { useTranslation } from "react-i18next"
+import { useSearchParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useInventoryItems, useStockLocations } from "@hooks/api"
+import { InventoryStockForm } from "./inventory-stock-form"
+
+const INVENTORY_ITEM_IDS_KEY = "inventory_item_ids"
+
+export const Component = () => {
+ const { t } = useTranslation()
+ const [searchParams] = useSearchParams()
+ const inventoryItemIds = searchParams.get(INVENTORY_ITEM_IDS_KEY)?.split(",") || undefined
+
+ const { inventory_items, isPending, isError, error } = useInventoryItems(
+ { fields: "id,sku,title,*stock_locations,*location_levels" },
+ undefined,
+ { id: inventoryItemIds! }
+ )
+
+ const { stock_locations, isPending: isPendingStockLocations, isError: isErrorStockLocations, error: errorStockLocations } = useStockLocations({ limit: 9999, fields: "id,name" })
+
+ const ready = !isPending && !!inventory_items && !isPendingStockLocations && !!stock_locations
+
+ if (isError) throw error
+ if (isErrorStockLocations) throw errorStockLocations
+
+ return (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">{t("inventory.stock.title")}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <span className="sr-only">{t("inventory.stock.description")}</span>
+ </RouteFocusModal.Description>
+ {ready && <InventoryStockForm items={inventory_items} locations={stock_locations} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/index.ts b/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/index.ts
new file mode 100644
index 000000000..1f852d039
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/index.ts
@@ -0,0 +1 @@
+export * from "./inventory-stock-form"
diff --git a/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/inventory-stock-form.tsx b/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/inventory-stock-form.tsx
new file mode 100644
index 000000000..c55023eb4
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/stock/inventory-stock-form/inventory-stock-form.tsx
@@ -0,0 +1,165 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, toast } from "@medusajs/ui"
+import { useRef } from "react"
+import { DefaultValues, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { DataGrid } from "@components/data-grid"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useBatchInventoryItemsLocationLevels } from "@hooks/api"
+import { castNumber } from "@lib/cast-number"
+import { useInventoryStockColumns } from "../use-inventory-stock-columns"
+import {
+ InventoryItemSchema,
+ InventoryLocationsSchema,
+ InventoryStockSchema,
+} from "../../schema"
+
+type InventoryStockFormProps = {
+ items: HttpTypes.AdminInventoryItem[]
+ locations: HttpTypes.AdminStockLocation[]
+}
+
+export const InventoryStockForm = ({
+ items,
+ locations,
+}: InventoryStockFormProps) => {
+ const { t } = useTranslation()
+ const { setCloseOnEscape, handleSuccess } = useRouteModal()
+
+ const initialValues = useRef(getDefaultValues(items, locations))
+
+ const form = useForm<InventoryStockSchema>({
+ defaultValues: getDefaultValues(items, locations),
+ resolver: zodResolver(InventoryStockSchema),
+ })
+
+ const columns = useInventoryStockColumns(locations)
+
+ const { mutateAsync, isPending } = useBatchInventoryItemsLocationLevels()
+
+ const onSubmit = form.handleSubmit(async (data) => {
+ const payload: HttpTypes.AdminBatchInventoryItemsLocationLevels = {
+ create: [],
+ update: [],
+ delete: [],
+ force: true,
+ }
+
+ for (const [inventory_item_id, item] of Object.entries(
+ data.inventory_items
+ )) {
+ for (const [location_id, level] of Object.entries(item.locations)) {
+ if (level.id) {
+ const wasChecked =
+ initialValues.current?.inventory_items?.[inventory_item_id]
+ ?.locations?.[location_id]?.checked
+
+ if (wasChecked && !level.checked) {
+ payload.delete.push(level.id)
+ } else {
+ const newQuantity =
+ level.quantity !== "" ? castNumber(level.quantity) : 0
+ const originalQuantity =
+ initialValues.current?.inventory_items?.[inventory_item_id]
+ ?.locations?.[location_id]?.quantity
+
+ if (newQuantity !== originalQuantity) {
+ payload.update.push({
+ inventory_item_id,
+ location_id,
+ stocked_quantity: newQuantity,
+ })
+ }
+ }
+ }
+
+ if (!level.id && level.quantity !== "") {
+ payload.create.push({
+ inventory_item_id,
+ location_id,
+ stocked_quantity: castNumber(level.quantity),
+ })
+ }
+ }
+ }
+
+ await mutateAsync(payload, {
+ onSuccess: () => {
+ toast.success(t("inventory.stock.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={onSubmit} className="flex size-full flex-col">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="size-full flex-1 overflow-y-auto">
+ <DataGrid
+ columns={columns}
+ data={items}
+ state={form}
+ onEditingChange={(editing) => {
+ setCloseOnEscape(!editing)
+ }}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+function getDefaultValues(
+ items: HttpTypes.AdminInventoryItem[],
+ locations: HttpTypes.AdminStockLocation[]
+): DefaultValues<InventoryStockSchema> {
+ return {
+ inventory_items: items.reduce(
+ (acc, item) => {
+ const locationsMap = locations.reduce((locationAcc, location) => {
+ const level = item.location_levels?.find(
+ (level) => level.location_id === location.id
+ )
+
+ locationAcc[location.id] = {
+ id: level?.id,
+ quantity:
+ typeof level?.stocked_quantity === "number"
+ ? level?.stocked_quantity
+ : "",
+ checked: !!level,
+ disabledToggle:
+ (level?.incoming_quantity || 0) > 0 ||
+ (level?.reserved_quantity || 0) > 0,
+ }
+ return locationAcc
+ }, {} as InventoryLocationsSchema)
+
+ acc[item.id] = { locations: locationsMap }
+ return acc
+ },
+ {} as Record<string, InventoryItemSchema>
+ ),
+ }
+}
diff --git a/packages/vendor/src/pages/inventory/[id]/stock/use-inventory-stock-columns.tsx b/packages/vendor/src/pages/inventory/[id]/stock/use-inventory-stock-columns.tsx
new file mode 100644
index 000000000..1be23e8c1
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/[id]/stock/use-inventory-stock-columns.tsx
@@ -0,0 +1,76 @@
+import { HttpTypes } from "@medusajs/types"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { createDataGridHelper } from "@components/data-grid"
+import { DataGridReadOnlyCell } from "@components/data-grid/components"
+import { DataGridTogglableNumberCell } from "@components/data-grid/components/data-grid-toggleable-number-cell"
+import { InventoryStockSchema } from "../schema"
+
+const helper = createDataGridHelper<
+ HttpTypes.AdminInventoryItem,
+ InventoryStockSchema
+>()
+
+export const useInventoryStockColumns = (
+ locations: HttpTypes.AdminStockLocation[] = []
+) => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ helper.column({
+ id: "title",
+ name: "Title",
+ header: "Title",
+ cell: (context) => {
+ const item = context.row.original
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ <span title={item.title || undefined}>{item.title || "-"}</span>
+ </DataGridReadOnlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ helper.column({
+ id: "sku",
+ name: "SKU",
+ header: "SKU",
+ cell: (context) => {
+ const item = context.row.original
+
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ <span title={item.sku || undefined}>{item.sku || "-"}</span>
+ </DataGridReadOnlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ ...locations.map((location) =>
+ helper.column({
+ id: `location_${location.id}`,
+ name: location.name,
+ header: location.name,
+ field: (context) => {
+ const item = context.row.original
+
+ return `inventory_items.${item.id}.locations.${location.id}` as const
+ },
+ type: "togglable-number",
+ cell: (context) => {
+ return (
+ <DataGridTogglableNumberCell
+ context={context}
+ disabledToggleTooltip={t(
+ "inventory.stock.disabledToggleTooltip"
+ )}
+ />
+ )
+ },
+ })
+ ),
+ ],
+ [locations, t]
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/_components/index.ts b/packages/vendor/src/pages/inventory/_components/index.ts
new file mode 100644
index 000000000..a7535bdcb
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/index.ts
@@ -0,0 +1,5 @@
+export * from "./inventory-list-table"
+export * from "./use-inventory-table-columns"
+export * from "./use-inventory-table-filters"
+export * from "./use-inventory-table-query"
+export * from "./inventory-actions"
diff --git a/packages/vendor/src/pages/inventory/_components/inventory-actions.tsx b/packages/vendor/src/pages/inventory/_components/inventory-actions.tsx
new file mode 100644
index 000000000..cda9f3024
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/inventory-actions.tsx
@@ -0,0 +1,53 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { InventoryItemDTO } from "@medusajs/types"
+import { useDeleteInventoryItem } from "@hooks/api/inventory"
+import { usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+export const InventoryActions = ({ item }: { item: InventoryItemDTO }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteInventoryItem(item.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("inventory.deleteWarning"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync()
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `${item.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/_components/inventory-list-table.tsx b/packages/vendor/src/pages/inventory/_components/inventory-list-table.tsx
new file mode 100644
index 000000000..79830867c
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/inventory-list-table.tsx
@@ -0,0 +1,94 @@
+import { InventoryTypes } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+
+import { RowSelectionState } from "@tanstack/react-table"
+import { useState } from "react"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { _DataTable } from "@components/table/data-table"
+import { useInventoryItems } from "@hooks/api/inventory"
+import { useDataTable } from "@hooks/use-data-table"
+import { INVENTORY_ITEM_IDS_KEY } from "../common/constants"
+import { useInventoryTableColumns } from "./use-inventory-table-columns"
+import { useInventoryTableQuery } from "./use-inventory-table-query"
+
+const PAGE_SIZE = 20
+
+export const InventoryListTable = () => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+
+ const [selection, setSelection] = useState<RowSelectionState>({})
+
+ const { raw, searchParams } = useInventoryTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const {
+ inventory_items,
+ count,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInventoryItems({
+ limit: PAGE_SIZE,
+ offset: searchParams?.offset,
+ fields: "id,title,sku,*location_levels",
+ })
+
+ const columns = useInventoryTableColumns()
+
+ const { table } = useDataTable({
+ data: (inventory_items ?? []) as InventoryTypes.InventoryItemDTO[],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ enableRowSelection: true,
+ rowSelection: {
+ state: selection,
+ updater: setSelection,
+ },
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("inventory.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("inventory.subtitle")}
+ </Text>
+ </div>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ pagination
+ queryObject={raw}
+ navigateTo={(row) => `${row.id}`}
+ commands={[
+ {
+ action: async (selection) => {
+ navigate(
+ `stock?${INVENTORY_ITEM_IDS_KEY}=${Object.keys(selection).join(
+ ","
+ )}`
+ )
+ },
+ label: t("inventory.stock.action"),
+ shortcut: "i",
+ },
+ ]}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/_components/use-inventory-table-columns.tsx b/packages/vendor/src/pages/inventory/_components/use-inventory-table-columns.tsx
new file mode 100644
index 000000000..2688b9426
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/use-inventory-table-columns.tsx
@@ -0,0 +1,138 @@
+import { InventoryTypes, ProductVariantDTO } from "@medusajs/types"
+
+import { Checkbox } from "@medusajs/ui"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"
+import { InventoryActions } from "./inventory-actions"
+
+
+interface ExtendedInventoryItem extends InventoryTypes.InventoryItemDTO {
+ variants?: ProductVariantDTO[] | null
+ stocked_quantity?: number
+ reserved_quantity?: number
+ location_levels?: {
+ available_quantity: number
+ reserved_quantity: number
+ stocked_quantity?: number
+ location_id?: string
+ }[]
+}
+
+const columnHelper = createColumnHelper<ExtendedInventoryItem>()
+
+export const useInventoryTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ columnHelper.accessor("title", {
+ header: t("fields.title"),
+ cell: ({ getValue }) => {
+ const title = getValue()
+
+ if (!title) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{title}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("sku", {
+ header: t("fields.sku"),
+ cell: ({ getValue }) => {
+ const sku = getValue() as string
+
+ if (!sku) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{sku}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("location_levels", {
+ header: t("inventory.reserved"),
+ cell: ({ getValue }) => {
+ const locations = getValue() as any[]
+
+ const totalReserved = locations.reduce(
+ (sum: number, level: any) => sum + level.reserved_quantity,
+ 0
+ )
+
+ if (Number.isNaN(totalReserved)) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{totalReserved}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("location_levels", {
+ header: t("fields.inStock"),
+ cell: ({ getValue }) => {
+ const locations = getValue() as any[]
+ const totalAvailable = locations.reduce(
+ (sum: number, level: any) => sum + level.available_quantity,
+ 0
+ )
+
+ if (Number.isNaN(totalAvailable)) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{totalAvailable}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <InventoryActions item={row.original} />,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/_components/use-inventory-table-filters.tsx b/packages/vendor/src/pages/inventory/_components/use-inventory-table-filters.tsx
new file mode 100644
index 000000000..d535d19c1
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/use-inventory-table-filters.tsx
@@ -0,0 +1,82 @@
+import { Filter } from "@components/table/data-table"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { useTranslation } from "react-i18next"
+
+export const useInventoryTableFilters = () => {
+ const { t } = useTranslation()
+ const { stock_locations } = useStockLocations({
+ limit: 1000,
+ })
+
+ const filters: Filter[] = []
+
+ if (stock_locations) {
+ const stockLocationFilter: Filter = {
+ type: "select",
+ options: stock_locations.map((s) => ({
+ label: s.name,
+ value: s.id,
+ })),
+ key: "location_id",
+ searchable: true,
+ label: t("fields.location"),
+ }
+
+ filters.push(stockLocationFilter)
+ }
+
+ filters.push({
+ type: "string",
+ key: "material",
+ label: t("fields.material"),
+ })
+
+ filters.push({
+ type: "string",
+ key: "sku",
+ label: t("fields.sku"),
+ })
+
+ filters.push({
+ type: "string",
+ key: "mid_code",
+ label: t("fields.midCode"),
+ })
+
+ filters.push({
+ type: "number",
+ key: "height",
+ label: t("fields.height"),
+ })
+
+ filters.push({
+ type: "number",
+ key: "width",
+ label: t("fields.width"),
+ })
+
+ filters.push({
+ type: "number",
+ key: "length",
+ label: t("fields.length"),
+ })
+
+ filters.push({
+ type: "number",
+ key: "weight",
+ label: t("fields.weight"),
+ })
+
+ filters.push({
+ type: "select",
+ options: [
+ { label: t("fields.true"), value: "true" },
+ { label: t("fields.false"), value: "false" },
+ ],
+ key: "requires_shipping",
+ multiple: false,
+ label: t("fields.requiresShipping"),
+ })
+
+ return filters
+}
diff --git a/packages/vendor/src/pages/inventory/_components/use-inventory-table-query.tsx b/packages/vendor/src/pages/inventory/_components/use-inventory-table-query.tsx
new file mode 100644
index 000000000..b2dcb34ce
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/_components/use-inventory-table-query.tsx
@@ -0,0 +1,70 @@
+import { HttpTypes } from "@medusajs/types"
+
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useInventoryTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(
+ [
+ "id",
+ "location_id",
+ "q",
+ "order",
+ "requires_shipping",
+ "offset",
+ "sku",
+ "origin_country",
+ "material",
+ "mid_code",
+ "hs_code",
+ "order",
+ "weight",
+ "width",
+ "length",
+ "height",
+ ],
+ prefix
+ )
+
+ const {
+ offset,
+ weight,
+ width,
+ length,
+ height,
+ requires_shipping,
+ ...params
+ } = raw
+
+ const searchParams: HttpTypes.AdminInventoryItemParams = {
+ limit: pageSize,
+ offset: offset ? parseInt(offset) : undefined,
+ weight: weight ? JSON.parse(weight) : undefined,
+ width: width ? JSON.parse(width) : undefined,
+ length: length ? JSON.parse(length) : undefined,
+ height: height ? JSON.parse(height) : undefined,
+ requires_shipping: requires_shipping
+ ? JSON.parse(requires_shipping)
+ : undefined,
+ q: params.q,
+ sku: params.sku,
+ order: params.order,
+ mid_code: params.mid_code,
+ hs_code: params.hs_code,
+ material: params.material,
+ location_levels: {
+ location_id: params.location_id || [],
+ },
+ id: params.id ? params.id.split(",") : undefined,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/inventory/common/constants.ts b/packages/vendor/src/pages/inventory/common/constants.ts
new file mode 100644
index 000000000..81cf30017
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/common/constants.ts
@@ -0,0 +1 @@
+export const INVENTORY_ITEM_IDS_KEY = "inventory_item_ids"
diff --git a/packages/vendor/src/pages/inventory/create/index.tsx b/packages/vendor/src/pages/inventory/create/index.tsx
new file mode 100644
index 000000000..b2d0d920a
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/create/index.tsx
@@ -0,0 +1,17 @@
+// Route: /inventory/create
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocations } from "@hooks/api"
+import { InventoryCreateForm } from "./inventory-create-form"
+
+export const Component = () => {
+ const { isPending, stock_locations, isError, error } = useStockLocations({ limit: 9999, fields: "id,name" })
+ const ready = !isPending && !!stock_locations
+
+ if (isError) throw error
+
+ return (
+ <RouteFocusModal>
+ {ready && <InventoryCreateForm locations={stock_locations} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/create/inventory-create-form/index.ts b/packages/vendor/src/pages/inventory/create/inventory-create-form/index.ts
new file mode 100644
index 000000000..2322ccaff
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/create/inventory-create-form/index.ts
@@ -0,0 +1 @@
+export * from "./inventory-create-form.tsx"
diff --git a/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-availability-form.tsx b/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-availability-form.tsx
new file mode 100644
index 000000000..d3de01e59
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-availability-form.tsx
@@ -0,0 +1,78 @@
+import { HttpTypes } from "@medusajs/types"
+import { useMemo } from "react"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import {
+ DataGrid,
+ createDataGridHelper,
+} from "@components/data-grid"
+import { useRouteModal } from "@components/modals"
+import { CreateInventoryItemSchema } from "./schema"
+
+type InventoryAvailabilityFormProps = {
+ form: UseFormReturn<CreateInventoryItemSchema>
+ locations: HttpTypes.AdminStockLocation[]
+}
+
+export const InventoryAvailabilityForm = ({
+ form,
+ locations,
+}: InventoryAvailabilityFormProps) => {
+ const { setCloseOnEscape } = useRouteModal()
+
+ const columns = useColumns()
+
+ return (
+ <div className="size-full">
+ <DataGrid
+ columns={columns}
+ data={locations}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ </div>
+ )
+}
+
+const columnHelper = createDataGridHelper<
+ HttpTypes.AdminStockLocation,
+ CreateInventoryItemSchema
+>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.column({
+ id: "location",
+ header: () => (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{t("locations.domain")}</span>
+ </div>
+ ),
+ cell: (context) => {
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ {context.row.original.name}
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ columnHelper.column({
+ id: "in-stock",
+ name: t("fields.inStock"),
+ header: t("fields.inStock"),
+ field: (context) => `locations.${context.row.original.id}`,
+ type: "number",
+ cell: (context) => {
+ return <DataGrid.NumberCell placeholder="0" context={context} />
+ },
+ disableHiding: true,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-create-form.tsx b/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-create-form.tsx
new file mode 100644
index 000000000..ec67cbe17
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/create/inventory-create-form/inventory-create-form.tsx
@@ -0,0 +1,515 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import {
+ Button,
+ clx,
+ Divider,
+ Heading,
+ Input,
+ ProgressStatus,
+ ProgressTabs,
+ Textarea,
+ toast,
+} from "@medusajs/ui"
+import { useCallback, useEffect, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { HttpTypes } from "@medusajs/types"
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { CountrySelect } from "@components/inputs/country-select"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import {
+ inventoryItemsQueryKeys,
+ useCreateInventoryItem,
+} from "@hooks/api/inventory"
+import { sdk } from "@lib/client"
+import {
+ transformNullableFormData,
+ transformNullableFormNumber,
+ transformNullableFormNumbers,
+} from "@lib/form-helpers"
+import { queryClient } from "@lib/query-client"
+import { InventoryAvailabilityForm } from "./inventory-availability-form"
+import { CreateInventoryItemSchema } from "./schema"
+
+enum Tab {
+ DETAILS = "details",
+ AVAILABILITY = "availability",
+}
+
+type StepStatus = {
+ [key in Tab]: ProgressStatus
+}
+
+type InventoryCreateFormProps = {
+ locations: HttpTypes.AdminStockLocation[]
+}
+
+export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const [tab, setTab] = useState<Tab>(Tab.DETAILS)
+
+ const form = useForm<CreateInventoryItemSchema>({
+ defaultValues: {
+ title: "",
+ sku: "",
+ hs_code: "",
+ weight: "",
+ length: "",
+ height: "",
+ width: "",
+ origin_country: "",
+ mid_code: "",
+ material: "",
+ description: "",
+ requires_shipping: true,
+ thumbnail: "",
+ locations: Object.fromEntries(
+ locations.map((location) => [location.id, ""])
+ ),
+ },
+ resolver: zodResolver(CreateInventoryItemSchema),
+ })
+
+ const {
+ trigger,
+ formState: { isDirty },
+ } = form
+
+ const { mutateAsync: createInventoryItem, isPending: isLoading } =
+ useCreateInventoryItem()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const { locations, weight, length, height, width, ...payload } = data
+
+ const cleanData = transformNullableFormData(payload, false)
+ const cleanNumbers = transformNullableFormNumbers(
+ {
+ weight,
+ length,
+ height,
+ width,
+ },
+ false
+ )
+
+ const { inventory_item } = await createInventoryItem(
+ {
+ ...cleanData,
+ ...cleanNumbers,
+ },
+ {
+ onError: (e) => {
+ toast.error(e.message)
+ return
+ },
+ }
+ )
+
+ await sdk.admin.inventoryItem
+ .batchUpdateLevels(inventory_item.id, {
+ create: Object.entries(locations ?? {})
+ .filter(([_, quantiy]) => !!quantiy)
+ .map(([location_id, stocked_quantity]) => ({
+ location_id,
+ stocked_quantity: transformNullableFormNumber(
+ stocked_quantity,
+ false
+ ),
+ })),
+ })
+ .then(async () => {
+ await queryClient.invalidateQueries({
+ queryKey: inventoryItemsQueryKeys.lists(),
+ })
+ })
+ .catch((e) => {
+ // Since the inventory item is created, we only log the error,
+ // but still close the modal to prevent the user from trying to
+ // create the same item again.
+ toast.error(e.message)
+ })
+ .finally(() => {
+ handleSuccess()
+ toast.success(t("inventory.create.successToast"))
+ })
+ })
+
+ const [status, setStatus] = useState<StepStatus>({
+ [Tab.AVAILABILITY]: "not-started",
+ [Tab.DETAILS]: "not-started",
+ })
+
+ const onTabChange = useCallback(
+ async (value: Tab) => {
+ const result = await trigger()
+
+ if (!result) {
+ return
+ }
+
+ setTab(value)
+ },
+ [trigger]
+ )
+
+ const onNext = useCallback(async () => {
+ const result = await trigger()
+
+ if (!result) {
+ return
+ }
+
+ switch (tab) {
+ case Tab.DETAILS: {
+ setTab(Tab.AVAILABILITY)
+ break
+ }
+ case Tab.AVAILABILITY:
+ break
+ }
+ }, [tab, trigger])
+
+ useEffect(() => {
+ if (isDirty) {
+ setStatus((prev) => ({ ...prev, [Tab.DETAILS]: "in-progress" }))
+ } else {
+ setStatus((prev) => ({ ...prev, [Tab.DETAILS]: "not-started" }))
+ }
+ }, [isDirty])
+
+ useEffect(() => {
+ if (tab === Tab.DETAILS && isDirty) {
+ setStatus((prev) => ({ ...prev, [Tab.DETAILS]: "in-progress" }))
+ }
+
+ if (tab === Tab.AVAILABILITY) {
+ setStatus((prev) => ({
+ ...prev,
+ [Tab.DETAILS]: "completed",
+ [Tab.AVAILABILITY]: "in-progress",
+ }))
+ }
+ }, [tab, isDirty])
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <ProgressTabs
+ value={tab}
+ className="h-full"
+ onValueChange={(tab) => onTabChange(tab as Tab)}
+ >
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <ProgressTabs.List className="border-ui-border-base -my-2 ml-2 min-w-0 flex-1 border-l">
+ <ProgressTabs.Trigger
+ value={Tab.DETAILS}
+ status={status[Tab.DETAILS]}
+ className="w-full max-w-[200px]"
+ >
+ <span className="w-full cursor-auto overflow-hidden text-ellipsis whitespace-nowrap">
+ {t("inventory.create.details")}
+ </span>
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ value={Tab.AVAILABILITY}
+ className="w-full max-w-[200px]"
+ status={status[Tab.AVAILABILITY]}
+ >
+ <span className="w-full overflow-hidden text-ellipsis whitespace-nowrap">
+ {t("inventory.create.availability")}
+ </span>
+ </ProgressTabs.Trigger>
+ </ProgressTabs.List>
+ </RouteFocusModal.Header>
+
+ <RouteFocusModal.Body
+ className={clx(
+ "flex h-full w-full flex-col items-center divide-y overflow-hidden",
+ { "mx-auto": tab === Tab.DETAILS }
+ )}
+ >
+ <ProgressTabs.Content
+ value={Tab.DETAILS}
+ className="h-full w-full overflow-auto px-3"
+ >
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-px py-16">
+ <div className="flex flex-col gap-y-8">
+ <Heading>{t("inventory.create.title")}</Heading>
+ <div className="flex flex-col gap-y-6">
+ <div className="grid grid-cols-1 gap-4 lg:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t("fields.title")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="sku"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.sku")}</Form.Label>
+ <Form.Control>
+ <Input {...field} placeholder="sku-123" />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.description.label")}
+ </Form.Label>
+ <Form.Control>
+ <Textarea
+ {...field}
+ placeholder="The item description"
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <SwitchBox
+ control={form.control}
+ name="requires_shipping"
+ label={t("inventory.create.requiresShipping")}
+ description={t("inventory.create.requiresShippingHint")}
+ />
+ </div>
+
+ <Divider />
+
+ <div className="flex flex-col gap-y-6">
+ <Heading level="h2">
+ {t("inventory.create.attributes")}
+ </Heading>
+
+ <div className="grid grid-cols-1 gap-x-4 gap-y-4 lg:grid-cols-2 lg:gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="width"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.width.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ placeholder="100"
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.length.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ placeholder="100"
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.height.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ placeholder="100"
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.weight.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ type="number"
+ min={0}
+ placeholder="100"
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.mid_code.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.hs_code.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.countryOrigin.label")}
+ </Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="material"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.material.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </ProgressTabs.Content>
+
+ <ProgressTabs.Content
+ value={Tab.AVAILABILITY}
+ className="size-full"
+ >
+ <InventoryAvailabilityForm form={form} locations={locations} />
+ </ProgressTabs.Content>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ className="whitespace-nowrap"
+ isLoading={isLoading}
+ onClick={tab !== Tab.AVAILABILITY ? onNext : undefined}
+ key={tab === Tab.AVAILABILITY ? "details" : "pricing"}
+ type={tab === Tab.AVAILABILITY ? "submit" : "button"}
+ >
+ {tab === Tab.AVAILABILITY
+ ? t("actions.save")
+ : t("general.next")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </ProgressTabs>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/inventory/create/inventory-create-form/schema.ts b/packages/vendor/src/pages/inventory/create/inventory-create-form/schema.ts
new file mode 100644
index 000000000..3778e017f
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/create/inventory-create-form/schema.ts
@@ -0,0 +1,23 @@
+import { z } from "zod"
+import { optionalInt } from "@lib/validation"
+
+export const CreateInventoryItemSchema = z.object({
+ title: z.string().min(1),
+ description: z.string().optional(),
+ sku: z.string().optional(),
+ hs_code: z.string().optional(),
+ weight: optionalInt,
+ length: optionalInt,
+ height: optionalInt,
+ width: optionalInt,
+ origin_country: z.string().optional(),
+ mid_code: z.string().optional(),
+ material: z.string().optional(),
+ requires_shipping: z.boolean().optional(),
+ thumbnail: z.string().optional(),
+ locations: z.record(z.string(), optionalInt).optional(),
+})
+
+export type CreateInventoryItemSchema = z.infer<
+ typeof CreateInventoryItemSchema
+>
diff --git a/packages/vendor/src/pages/inventory/index.tsx b/packages/vendor/src/pages/inventory/index.tsx
new file mode 100644
index 000000000..499f70fd7
--- /dev/null
+++ b/packages/vendor/src/pages/inventory/index.tsx
@@ -0,0 +1,19 @@
+// Route: /inventory
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { InventoryListTable } from "./_components/inventory-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("inventory_item.list.after"),
+ before: getWidgets("inventory_item.list.before"),
+ }}
+ >
+ <InventoryListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/invite/index.ts b/packages/vendor/src/pages/invite/index.ts
new file mode 100644
index 000000000..b49eed973
--- /dev/null
+++ b/packages/vendor/src/pages/invite/index.ts
@@ -0,0 +1 @@
+export { Invite as Component } from "./invite"
diff --git a/packages/vendor/src/pages/invite/invite.tsx b/packages/vendor/src/pages/invite/invite.tsx
new file mode 100644
index 000000000..062c97914
--- /dev/null
+++ b/packages/vendor/src/pages/invite/invite.tsx
@@ -0,0 +1,410 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Alert, Button, Heading, Hint, Input, Text, toast } from "@medusajs/ui"
+import i18n from "i18next"
+import { AnimatePresence, motion } from "motion/react"
+import { useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { decodeToken } from "react-jwt"
+import { Link, useSearchParams } from "react-router-dom"
+import * as z from "zod"
+import { Form } from "@components/common/form"
+import AvatarBox from "@components/common/logo-box/avatar-box"
+import { useSignUpForInvite } from "@hooks/api/auth"
+import { useAcceptInvite } from "@hooks/api/invites"
+import { isFetchError } from "@lib/is-fetch-error"
+
+const CreateAccountSchema = z
+ .object({
+ email: z.string().email(),
+ first_name: z.string().min(1),
+ last_name: z.string().min(1),
+ password: z.string().min(1),
+ repeat_password: z.string().min(1),
+ })
+ .superRefine(({ password, repeat_password }, ctx) => {
+ if (password !== repeat_password) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: i18n.t("invite.passwordMismatch"),
+ path: ["repeat_password"],
+ })
+ }
+ })
+
+// TODO: Update to V2 format
+type DecodedInvite = {
+ id: string
+ jti: any
+ exp: string
+ iat: number
+ email: string
+}
+
+export const Invite = () => {
+ const [searchParams] = useSearchParams()
+ const [success, setSuccess] = useState(false)
+
+ const token = searchParams.get("token") || null
+ const invite: DecodedInvite | null = token ? decodeToken(token) : null
+ const isValidInvite = invite && validateDecodedInvite(invite)
+
+ return (
+ <div className="bg-ui-bg-subtle relative flex min-h-dvh w-dvw items-center justify-center p-4">
+ <div className="flex w-full max-w-[360px] flex-col items-center">
+ <AvatarBox checked={success} />
+ <div className="max-h-[557px] w-full will-change-contents">
+ {isValidInvite ? (
+ <AnimatePresence>
+ {!success ? (
+ <motion.div
+ key="create-account"
+ initial={false}
+ animate={{
+ height: "557px",
+ y: 0,
+ }}
+ exit={{
+ height: 0,
+ y: 40,
+ }}
+ transition={{
+ duration: 0.8,
+ delay: 0.6,
+ ease: [0, 0.71, 0.2, 1.01],
+ }}
+ className="w-full will-change-transform"
+ >
+ <motion.div
+ initial={false}
+ animate={{
+ opacity: 1,
+ scale: 1,
+ }}
+ exit={{
+ opacity: 0,
+ scale: 0.7,
+ }}
+ transition={{
+ duration: 0.6,
+ delay: 0,
+ ease: [0, 0.71, 0.2, 1.01],
+ }}
+ key="inner-create-account"
+ >
+ <CreateView
+ onSuccess={() => setSuccess(true)}
+ token={token!}
+ invite={invite}
+ />
+ </motion.div>
+ </motion.div>
+ ) : (
+ <motion.div
+ key="success-view"
+ initial={{
+ opacity: 0,
+ scale: 0.4,
+ }}
+ animate={{
+ opacity: 1,
+ scale: 1,
+ }}
+ transition={{
+ duration: 1,
+ delay: 0.6,
+ ease: [0, 0.71, 0.2, 1.01],
+ }}
+ className="w-full"
+ >
+ <SuccessView />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ ) : (
+ <InvalidView />
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+const LoginLink = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex w-full flex-col items-center">
+ <div className="my-6 h-px w-full border-b border-dotted" />
+ <Link
+ key="login-link"
+ to="/login"
+ className="txt-small text-ui-fg-base transition-fg hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover font-medium outline-none"
+ >
+ {t("invite.backToLogin")}
+ </Link>
+ </div>
+ )
+}
+
+const InvalidView = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex flex-col items-center">
+ <div className="flex flex-col items-center gap-y-1">
+ <Heading>{t("invite.invalidTokenTitle")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("invite.invalidTokenHint")}
+ </Text>
+ </div>
+ <LoginLink />
+ </div>
+ )
+}
+
+const CreateView = ({
+ onSuccess,
+ token,
+ invite,
+}: {
+ onSuccess: () => void
+ token: string
+ invite: DecodedInvite
+}) => {
+ const { t } = useTranslation()
+ const [invalid, setInvalid] = useState(false)
+
+ const [params] = useSearchParams()
+ const isFirstRun = params.get("first_run") === "true" // true when the invite page is open during a "create medusa app" run
+
+ const form = useForm<z.infer<typeof CreateAccountSchema>>({
+ resolver: zodResolver(CreateAccountSchema),
+ defaultValues: {
+ email: isFirstRun ? "" : invite.email || "",
+ first_name: "",
+ last_name: "",
+ password: "",
+ repeat_password: "",
+ },
+ })
+
+ const { mutateAsync: signUpEmailPass, isPending: isCreatingAuthUser } =
+ useSignUpForInvite()
+
+ const { mutateAsync: acceptInvite, isPending: isAcceptingInvite } =
+ useAcceptInvite(token)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ try {
+ const authToken = await signUpEmailPass({
+ email: data.email,
+ password: data.password,
+ })
+
+ const invitePayload = {
+ name: `${data.first_name} ${data.last_name}`,
+ }
+
+ await acceptInvite({
+ ...invitePayload,
+ auth_token: authToken,
+ })
+
+ toast.success(t("invite.toast.accepted"))
+
+ onSuccess()
+ } catch (error: any) {
+ toast.error(error.message)
+ if (isFetchError(error) && error.status === 400) {
+ form.setError("root", {
+ type: "manual",
+ message: t("invite.invalidInvite"),
+ })
+ setInvalid(true)
+ return
+ }
+ }
+ })
+
+ const serverError = form.formState.errors.root?.message
+ const validationError =
+ form.formState.errors.email?.message ||
+ form.formState.errors.password?.message ||
+ form.formState.errors.repeat_password?.message ||
+ form.formState.errors.first_name?.message ||
+ form.formState.errors.last_name?.message
+
+ return (
+ <div className="flex w-full flex-col items-center">
+ <div className="mb-4 flex flex-col items-center">
+ <Heading>{t("invite.title")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("invite.hint")}
+ </Text>
+ </div>
+ <Form {...form}>
+ <form onSubmit={handleSubmit} className="flex w-full flex-col gap-y-6">
+ <div className="flex flex-col gap-y-2">
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="off"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.email")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="first_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="given-name"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.firstName")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="last_name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="family-name"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.lastName")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="password"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="new-password"
+ type="password"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.password")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="repeat_password"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="off"
+ type="password"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.repeatPassword")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ {validationError && (
+ <div className="mt-6 text-center">
+ <Hint className="inline-flex" variant={"error"}>
+ {validationError}
+ </Hint>
+ </div>
+ )}
+ {serverError && (
+ <Alert
+ className="bg-ui-bg-base items-center p-2"
+ dismissible
+ variant="error"
+ >
+ {serverError}
+ </Alert>
+ )}
+ </div>
+ <Button
+ className="w-full"
+ type="submit"
+ isLoading={isCreatingAuthUser || isAcceptingInvite}
+ disabled={invalid}
+ >
+ {t("invite.createAccount")}
+ </Button>
+ </form>
+ </Form>
+ <LoginLink />
+ </div>
+ )
+}
+
+const SuccessView = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex w-full flex-col items-center gap-y-6">
+ <div className="flex flex-col items-center gap-y-1">
+ <Heading className="text-center">{t("invite.successTitle")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("invite.successHint")}
+ </Text>
+ </div>
+ <Button variant="secondary" asChild className="w-full">
+ <Link to="/login" replace>
+ {t("invite.successAction")}
+ </Link>
+ </Button>
+
+ <Link
+ key="login-link"
+ to="/login"
+ className="txt-small text-ui-fg-base transition-fg hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover font-medium outline-none"
+ >
+ {t("invite.backToLogin")}
+ </Link>
+ </div>
+ )
+}
+
+const InviteSchema = z.object({
+ id: z.string(),
+ // jti: z.string(),
+ exp: z.number(),
+ iat: z.number(),
+})
+
+const validateDecodedInvite = (decoded: any): decoded is DecodedInvite => {
+ return InviteSchema.safeParse(decoded).success
+}
diff --git a/packages/vendor/src/pages/login/index.ts b/packages/vendor/src/pages/login/index.ts
new file mode 100644
index 000000000..f1fc40c3a
--- /dev/null
+++ b/packages/vendor/src/pages/login/index.ts
@@ -0,0 +1 @@
+export { Login as Component } from "./login"
diff --git a/packages/vendor/src/pages/login/login.tsx b/packages/vendor/src/pages/login/login.tsx
new file mode 100644
index 000000000..d8856b63a
--- /dev/null
+++ b/packages/vendor/src/pages/login/login.tsx
@@ -0,0 +1,191 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Alert, Button, Heading, Hint, Input, Text } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { Trans, useTranslation } from "react-i18next"
+import { Link, useNavigate, useSearchParams } from "react-router-dom"
+import * as z from "zod"
+
+import { Form } from "@components/common/form"
+import AvatarBox from "@components/common/logo-box/avatar-box"
+import { useDashboardExtension } from "@/extensions"
+import { useSignInWithEmailPass } from "@hooks/api"
+import { isFetchError } from "@lib/is-fetch-error"
+
+const LoginSchema = z.object({
+ email: z.string().email(),
+ password: z.string(),
+})
+
+export const Login = () => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const [searchParams] = useSearchParams()
+
+ const reason = searchParams.get("reason") || ""
+ const reasonMessage = reason && reason.toLowerCase() === "unauthorized" ? "Session expired" : reason
+
+ const { getWidgets } = useDashboardExtension()
+
+ const from = "/"
+
+ const form = useForm<z.infer<typeof LoginSchema>>({
+ resolver: zodResolver(LoginSchema),
+ defaultValues: {
+ email: "",
+ password: "",
+ },
+ })
+
+ const { mutateAsync, isPending } = useSignInWithEmailPass()
+
+ const handleSubmit = form.handleSubmit(async ({ email, password }) => {
+ await mutateAsync(
+ {
+ email,
+ password,
+ },
+ {
+ onError: (error) => {
+ if (isFetchError(error)) {
+ if (error.status === 401) {
+ form.setError("email", {
+ type: "manual",
+ message: error.message,
+ })
+
+ return
+ }
+ }
+
+ form.setError("root.serverError", {
+ type: "manual",
+ message: error.message,
+ })
+ },
+ onSuccess: () => {
+ setTimeout(() => {
+ navigate(from, { replace: true })
+ }, 1000)
+ },
+ }
+ )
+ })
+
+ const serverError =
+ form.formState.errors?.root?.serverError?.message || reasonMessage
+ const validationError =
+ form.formState.errors.email?.message ||
+ form.formState.errors.password?.message
+
+ return (
+ <div className="bg-ui-bg-subtle flex min-h-dvh w-dvw items-center justify-center">
+ <div className="m-4 flex w-full max-w-[280px] flex-col items-center">
+ <AvatarBox />
+ <div className="mb-4 flex flex-col items-center">
+ <Heading>{t("login.title")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("login.hint")}
+ </Text>
+ </div>
+ <div className="flex w-full flex-col gap-y-3">
+ {getWidgets("login.before").map((Component, i) => {
+ return <Component key={i} />
+ })}
+ <Form {...form}>
+ <form
+ onSubmit={handleSubmit}
+ className="flex w-full flex-col gap-y-6"
+ >
+ <div className="flex flex-col gap-y-1">
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="email"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.email")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="password"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{}</Form.Label>
+ <Form.Control>
+ <Input
+ type="password"
+ autoComplete="current-password"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t("fields.password")}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {validationError && (
+ <div className="text-center">
+ <Hint className="inline-flex" variant={"error"}>
+ {validationError}
+ </Hint>
+ </div>
+ )}
+
+ {serverError && (
+ <Alert
+ className="bg-ui-bg-base items-center p-2"
+ dismissible
+ variant="error"
+ >
+ {serverError}
+ </Alert>
+ )}
+ <Button className="w-full" type="submit" isLoading={isPending}>
+ Sign In
+ </Button>
+ </form>
+ </Form>
+ {getWidgets("login.after").map((Component, i) => {
+ return <Component key={i} />
+ })}
+ </div>
+ <span className="text-ui-fg-muted txt-small my-6">
+ <Trans
+ i18nKey="login.forgotPassword"
+ components={[
+ <Link
+ key="reset-password-link"
+ to="/reset-password"
+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"
+ />,
+ ]}
+ />
+ </span>
+ <span className="text-ui-fg-muted txt-small">
+ <Trans
+ i18nKey="login.notSellerYet"
+ components={[
+ <Link
+ to="/register"
+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover font-medium outline-none"
+ />,
+ ]}
+ />
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/no-match/index.ts b/packages/vendor/src/pages/no-match/index.ts
new file mode 100644
index 000000000..fa8df0ab3
--- /dev/null
+++ b/packages/vendor/src/pages/no-match/index.ts
@@ -0,0 +1 @@
+export { NoMatch as Component } from "./no-match"
diff --git a/packages/vendor/src/pages/no-match/no-match.tsx b/packages/vendor/src/pages/no-match/no-match.tsx
new file mode 100644
index 000000000..1c1caacc3
--- /dev/null
+++ b/packages/vendor/src/pages/no-match/no-match.tsx
@@ -0,0 +1,36 @@
+import { ExclamationCircle } from "@medusajs/icons"
+import { Button, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+// TODO: Add 404 page
+export const NoMatch = () => {
+ const { t } = useTranslation()
+
+ const title = t("errorBoundary.notFoundTitle")
+ const message = t("errorBoundary.noMatchMessage")
+
+ return (
+ <div className="flex size-full min-h-screen items-center justify-center">
+ <div className="flex flex-col items-center gap-y-6">
+ <div className="text-ui-fg-subtle flex flex-col items-center gap-y-3">
+ <ExclamationCircle />
+ <div className="flex flex-col items-center justify-center gap-y-1">
+ <Text size="small" leading="compact" weight="plus">
+ {title}
+ </Text>
+ <Text
+ size="small"
+ className="text-ui-fg-muted text-balance text-center"
+ >
+ {message}
+ </Text>
+ </div>
+ </div>
+ <Button asChild size="small" variant="secondary">
+ <Link to="/">{t("errorBoundary.backToDashboard")}</Link>
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/copy-payment-link.tsx b/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/copy-payment-link.tsx
new file mode 100644
index 000000000..a181533ea
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/copy-payment-link.tsx
@@ -0,0 +1,78 @@
+import { CheckCircleSolid, SquareTwoStack } from "@medusajs/icons"
+import { Button, Tooltip } from "@medusajs/ui"
+import copy from "copy-to-clipboard"
+import React, { useState } from "react"
+import { useTranslation } from "react-i18next"
+import { getStylizedAmount } from "@lib/money-amount-helpers"
+import { MEDUSA_STOREFRONT_URL } from "@lib/storefront"
+import { ExtendedAdminOrder, ExtendedAdminPaymentCollection } from "@custom-types/order"
+
+type CopyPaymentLinkProps = {
+ paymentCollection: Partial<ExtendedAdminPaymentCollection>
+ order: ExtendedAdminOrder
+}
+
+/**
+ * This component is based on the `button` element and supports all of its props
+ */
+const CopyPaymentLink = React.forwardRef<any, CopyPaymentLinkProps>(
+ ({ paymentCollection, order }: CopyPaymentLinkProps, ref) => {
+ const [done, setDone] = useState(false)
+ const [open, setOpen] = useState(false)
+ const [text, setText] = useState("CopyPaymentLink")
+ const { t } = useTranslation()
+
+ const copyToClipboard = async (
+ e:
+ | React.MouseEvent<HTMLElement, MouseEvent>
+ | React.MouseEvent<HTMLButtonElement, MouseEvent>
+ ) => {
+ e.stopPropagation()
+
+ setDone(true)
+ copy(`${MEDUSA_STOREFRONT_URL}/payment-collection/${paymentCollection}`)
+
+ setTimeout(() => {
+ setDone(false)
+ }, 2000)
+ }
+
+ React.useEffect(() => {
+ if (done) {
+ setText(t("actions.copied"))
+ return
+ }
+
+ setTimeout(() => {
+ setText(t("actions.copy"))
+ }, 500)
+ }, [done])
+
+ return (
+ <Tooltip content={text} open={done || open} onOpenChange={setOpen}>
+ <Button
+ ref={ref}
+ variant="secondary"
+ size="small"
+ aria-label="CopyPaymentLink code snippet"
+ onClick={copyToClipboard}
+ >
+ {done ? (
+ <CheckCircleSolid className="inline" />
+ ) : (
+ <SquareTwoStack className="inline" />
+ )}
+ {t("orders.payment.paymentLink", {
+ amount: getStylizedAmount(
+ paymentCollection.amount as number,
+ order?.currency_code
+ ),
+ })}
+ </Button>
+ </Tooltip>
+ )
+ }
+)
+CopyPaymentLink.displayName = "CopyPaymentLink"
+
+export { CopyPaymentLink }
diff --git a/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/index.ts b/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/index.ts
new file mode 100644
index 000000000..e496ff07b
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/copy-payment-link/index.ts
@@ -0,0 +1 @@
+export * from "./copy-payment-link"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/index.ts b/packages/vendor/src/pages/orders/[id]/_components/index.ts
new file mode 100644
index 000000000..89aefd979
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/index.ts
@@ -0,0 +1,7 @@
+export * from "./copy-payment-link"
+export * from "./order-activity-section"
+export * from "./order-customer-section"
+export * from "./order-fulfillment-section"
+export * from "./order-general-section"
+export * from "./order-payment-section"
+export * from "./order-summary-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/activity-items.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/activity-items.tsx
new file mode 100644
index 000000000..7385e1b43
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/activity-items.tsx
@@ -0,0 +1,125 @@
+import {
+ AdminClaim,
+ AdminExchange,
+ AdminOrderLineItem,
+ AdminReturn,
+} from "@medusajs/types"
+import { Popover, Text } from "@medusajs/ui"
+import { useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Thumbnail } from "@components/common/thumbnail"
+
+type ActivityItemsProps = {
+ itemsToSend?:
+ | AdminClaim["additional_items"]
+ | AdminExchange["additional_items"]
+ itemsToReturn?: AdminReturn["items"]
+ itemsMap?: Map<string, AdminOrderLineItem>
+ title: string
+}
+
+function ActivityItems(props: ActivityItemsProps) {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const itemsToSend = props.itemsToSend
+ const itemsToReturn = props.itemsToReturn
+ const itemsMap = props.itemsMap
+ const title = props.title
+
+ const handleMouseEnter = () => {
+ setOpen(true)
+ }
+
+ const handleMouseLeave = () => {
+ setOpen(false)
+ }
+
+ if (!itemsToSend?.length && !itemsToReturn?.length) {
+ return
+ }
+
+ return (
+ <Popover open={open}>
+ <Popover.Trigger
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ autoFocus={false}
+ className="focus-visible:outline-none"
+ >
+ <Text size="small" leading="compact" weight="plus">
+ {title}
+ </Text>
+ </Popover.Trigger>
+
+ <Popover.Content
+ align="center"
+ side="top"
+ className="bg-ui-bg-component max-w-[200px] p-0 focus-visible:outline-none"
+ >
+ <div className="flex flex-col">
+ {!!itemsToSend?.length && (
+ <div className="p-3">
+ <div className="txt-compact-small-plus mb-1">
+ {t("orders.activity.events.common.toSend")}
+ </div>
+
+ <div className="flex flex-col">
+ {itemsToSend?.map((item) => {
+ const originalItem = itemsMap?.get(item.item_id)!
+
+ return (
+ <div className="flex items-center gap-x-3" key={item.id}>
+ <Text size="small" className="text-ui-fg-subtle">
+ {item.quantity}x
+ </Text>
+
+ <Thumbnail src={originalItem?.thumbnail} />
+
+ <Text className="txt-compact-small text-ui-fg-subtle truncate">
+ {`${originalItem?.variant_title} · ${originalItem?.product_title}`}
+ </Text>
+ </div>
+ )
+ })}
+
+ <div className="flex flex-1 flex-row items-center gap-2"></div>
+ </div>
+ </div>
+ )}
+
+ {!!itemsToReturn?.length && (
+ <div className="border-t-2 border-dotted p-3">
+ <div className="txt-compact-small-plus mb-1">
+ {t("orders.activity.events.common.toReturn")}
+ </div>
+
+ <div className="flex flex-col">
+ {itemsToReturn?.map((item) => {
+ const originalItem = itemsMap?.get(item.item_id)!
+
+ return (
+ <div className="flex items-center gap-x-3" key={item.id}>
+ <Text size="small" className="text-ui-fg-subtle">
+ {item.quantity}x
+ </Text>
+
+ <Thumbnail src={originalItem?.thumbnail} />
+
+ <Text className="txt-compact-small text-ui-fg-subtle truncate">
+ {`${originalItem?.variant_title} · ${originalItem?.product_title}`}
+ </Text>
+ </div>
+ )
+ })}
+
+ <div className="flex flex-1 flex-row items-center gap-2"></div>
+ </div>
+ </div>
+ )}
+ </div>
+ </Popover.Content>
+ </Popover>
+ )
+}
+
+export default ActivityItems
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/change-details-tooltip.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/change-details-tooltip.tsx
new file mode 100644
index 000000000..25ac34b4e
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/change-details-tooltip.tsx
@@ -0,0 +1,74 @@
+import { Popover, Text } from "@medusajs/ui"
+import { ReactNode, useState } from "react"
+import { useTranslation } from "react-i18next"
+
+type ChangeDetailsTooltipProps = {
+ previous: ReactNode
+ next: ReactNode
+ title: string
+}
+
+function ChangeDetailsTooltip(props: ChangeDetailsTooltipProps) {
+ const { t } = useTranslation()
+ const [open, setOpen] = useState(false)
+ const previous = props.previous
+ const next = props.next
+ const title = props.title
+
+ const handleMouseEnter = () => {
+ setOpen(true)
+ }
+
+ const handleMouseLeave = () => {
+ setOpen(false)
+ }
+
+ if (!previous && !next) {
+ return null
+ }
+
+ return (
+ <Popover open={open}>
+ <Popover.Trigger
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ autoFocus={false}
+ className="focus-visible:outline-none"
+ >
+ <Text size="small" leading="compact" weight="plus">
+ {title}
+ </Text>
+ </Popover.Trigger>
+
+ <Popover.Content
+ align="center"
+ side="top"
+ className="bg-ui-bg-component max-w-[200px] p-0 focus-visible:outline-none"
+ >
+ <div className="flex flex-col">
+ {!!previous && (
+ <div className="p-3">
+ <div className="txt-compact-small-plus mb-1">
+ {t("labels.from")}
+ </div>
+
+ <p className="txt-compact-small text-ui-fg-subtle">{previous}</p>
+ </div>
+ )}
+
+ {!!next && (
+ <div className="border-t-2 border-dotted p-3">
+ <div className="txt-compact-small-plus mb-1">
+ {t("labels.to")}
+ </div>
+
+ <p className="txt-compact-small text-ui-fg-subtle">{next}</p>
+ </div>
+ )}
+ </div>
+ </Popover.Content>
+ </Popover>
+ )
+}
+
+export default ChangeDetailsTooltip
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/claim-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/claim-body.tsx
new file mode 100644
index 000000000..ef0c79b78
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/claim-body.tsx
@@ -0,0 +1,78 @@
+import { Button, Text, usePrompt } from "@medusajs/ui"
+import { AdminClaim, AdminReturn } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { useCancelClaim } from "@hooks/api/claims"
+
+type ClaimBodyProps = {
+ claim: AdminClaim
+ claimReturn?: AdminReturn
+}
+
+export const ClaimBody = ({
+ claim,
+ claimReturn,
+}: ClaimBodyProps) => {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const isCanceled = !!claim.created_at
+
+ const { mutateAsync: cancelClaim } = useCancelClaim(claim.id, claim.order_id)
+
+ const onCancel = async () => {
+ const res = await prompt({
+ title: t("orders.claims.cancel.title"),
+ description: t("orders.claims.cancel.description"),
+ confirmText: t("actions.confirm"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await cancelClaim()
+ }
+
+ const outboundItems = (claim.additional_items || []).reduce(
+ (acc, item) => (acc + item.quantity) as number,
+ 0
+ )
+
+ const inboundItems = (claimReturn?.items || []).reduce(
+ (acc, item) => acc + item.quantity,
+ 0
+ )
+
+ return (
+ <div>
+ {outboundItems > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.claim.itemsInbound", {
+ count: outboundItems,
+ })}
+ </Text>
+ )}
+
+ {inboundItems > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.claim.itemsOutbound", {
+ count: inboundItems,
+ })}
+ </Text>
+ )}
+
+ {!isCanceled && (
+ <Button
+ onClick={onCancel}
+ className="text-ui-fg-subtle h-auto px-0 leading-none hover:bg-transparent"
+ variant="transparent"
+ size="small"
+ >
+ {t("actions.cancel")}
+ </Button>
+ )}
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/exchange-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/exchange-body.tsx
new file mode 100644
index 000000000..bbf3eb1f4
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/exchange-body.tsx
@@ -0,0 +1,81 @@
+import { Button, Text, usePrompt } from "@medusajs/ui"
+import { AdminExchange, AdminReturn } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { useCancelExchange } from "@hooks/api/exchanges"
+
+type ExchangeBodyProps = {
+ exchange: AdminExchange
+ exchangeReturn?: AdminReturn
+}
+
+export const ExchangeBody = ({
+ exchange,
+ exchangeReturn,
+}: ExchangeBodyProps) => {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const isCanceled = !!exchange.canceled_at
+
+ const { mutateAsync: cancelExchange } = useCancelExchange(
+ exchange.id,
+ exchange.order_id
+ )
+
+ const onCancel = async () => {
+ const res = await prompt({
+ title: t("orders.exchanges.cancel.title"),
+ description: t("orders.exchanges.cancel.description"),
+ confirmText: t("actions.confirm"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await cancelExchange()
+ }
+
+ const outboundItems = (exchange.additional_items || []).reduce(
+ (acc, item) => (acc + item.quantity) as number,
+ 0
+ )
+
+ const inboundItems = (exchangeReturn?.items || []).reduce(
+ (acc, item) => acc + item.quantity,
+ 0
+ )
+
+ return (
+ <div>
+ {outboundItems > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.exchange.itemsInbound", {
+ count: outboundItems,
+ })}
+ </Text>
+ )}
+
+ {inboundItems > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.exchange.itemsOutbound", {
+ count: inboundItems,
+ })}
+ </Text>
+ )}
+
+ {!isCanceled && (
+ <Button
+ onClick={onCancel}
+ className="text-ui-fg-subtle h-auto px-0 leading-none hover:bg-transparent"
+ variant="transparent"
+ size="small"
+ >
+ {t("actions.cancel")}
+ </Button>
+ )}
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/fulfillment-created-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/fulfillment-created-body.tsx
new file mode 100644
index 000000000..79b836f7e
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/fulfillment-created-body.tsx
@@ -0,0 +1,29 @@
+import { Text } from "@medusajs/ui"
+import { AdminFulfillment } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+
+type FulfillmentCreatedBodyProps = {
+ fulfillment: AdminFulfillment
+ isShipment?: boolean
+}
+
+export const FulfillmentCreatedBody = ({
+ fulfillment,
+}: FulfillmentCreatedBodyProps) => {
+ const { t } = useTranslation()
+
+ const numberOfItems = (fulfillment.items || []).reduce((acc, item) => {
+ return acc + (item.quantity || 0)
+ }, 0)
+
+ return (
+ <div>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.fulfillment.items", {
+ count: numberOfItems,
+ })}
+ </Text>
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/index.ts
new file mode 100644
index 000000000..f88ae0351
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/index.ts
@@ -0,0 +1,9 @@
+export * from "./fulfillment-created-body"
+export * from "./return-body"
+export * from "./claim-body"
+export * from "./exchange-body"
+export * from "./order-edit-body"
+export * from "./transfer-order-request-body"
+export * from "./order-activity-item"
+export * from "./order-activity-collapsible"
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-collapsible.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-collapsible.tsx
new file mode 100644
index 000000000..e220564b7
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-collapsible.tsx
@@ -0,0 +1,67 @@
+import { Text } from "@medusajs/ui"
+import { Collapsible as RadixCollapsible } from "radix-ui"
+import { useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Activity } from "../hooks/use-activity-items"
+import { OrderActivityItem } from "./order-activity-item"
+
+type OrderActivityCollapsibleProps = {
+ activities: Activity[]
+}
+
+export const OrderActivityCollapsible = ({
+ activities,
+}: OrderActivityCollapsibleProps) => {
+ const [open, setOpen] = useState(false)
+
+ const { t } = useTranslation()
+
+ if (!activities.length) {
+ return null
+ }
+
+ return (
+ <RadixCollapsible.Root open={open} onOpenChange={setOpen}>
+ {!open && (
+ <div className="grid grid-cols-[20px_1fr] items-start gap-2">
+ <div className="flex size-full flex-col items-center">
+ <div className="border-ui-border-strong w-px flex-1 bg-[linear-gradient(var(--border-strong)_33%,rgba(255,255,255,0)_0%)] bg-[length:1px_3px] bg-right bg-repeat-y" />
+ </div>
+ <div className="pb-4">
+ <RadixCollapsible.Trigger className="text-left">
+ <Text
+ size="small"
+ leading="compact"
+ weight="plus"
+ className="text-ui-fg-muted"
+ >
+ {t("orders.activity.showMoreActivities", {
+ count: activities.length,
+ })}
+ </Text>
+ </RadixCollapsible.Trigger>
+ </div>
+ </div>
+ )}
+ <RadixCollapsible.Content>
+ <div className="flex flex-col gap-y-0.5">
+ {activities.map((item, index) => {
+ return (
+ <OrderActivityItem
+ key={index}
+ title={item.title}
+ timestamp={item.timestamp}
+ itemsToSend={item.itemsToSend}
+ itemsToReturn={item.itemsToReturn}
+ itemsMap={item.itemsMap}
+ >
+ {item.children}
+ </OrderActivityItem>
+ )
+ })}
+ </div>
+ </RadixCollapsible.Content>
+ </RadixCollapsible.Root>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-item.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-item.tsx
new file mode 100644
index 000000000..d801c62bf
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-activity-item.tsx
@@ -0,0 +1,79 @@
+import { Text, Tooltip, clx } from "@medusajs/ui"
+import { PropsWithChildren } from "react"
+import { AdminClaim, AdminExchange, AdminReturn, AdminOrderLineItem } from "@medusajs/types"
+import { useDate } from "@hooks/use-date"
+import ActivityItems from "../activity-items"
+
+type OrderActivityItemProps = PropsWithChildren<{
+ title: string | React.ReactNode
+ timestamp: string | Date | null
+ isFirst?: boolean
+ itemsToSend?:
+ | AdminClaim["additional_items"]
+ | AdminExchange["additional_items"]
+ itemsToReturn?: AdminReturn["items"]
+ itemsMap?: Map<string, AdminOrderLineItem>
+}>
+
+export const OrderActivityItem = ({
+ title,
+ timestamp,
+ isFirst = false,
+ children,
+ itemsToSend,
+ itemsToReturn,
+ itemsMap,
+}: OrderActivityItemProps) => {
+ const { getFullDate, getRelativeDate } = useDate()
+
+ return (
+ <div className="grid grid-cols-[20px_1fr] items-start gap-2">
+ <div className="flex size-full flex-col items-center gap-y-0.5">
+ <div className="flex size-5 items-center justify-center">
+ <div className="bg-ui-bg-base shadow-borders-base flex size-2.5 items-center justify-center rounded-full">
+ <div className="bg-ui-tag-neutral-icon size-1.5 rounded-full" />
+ </div>
+ </div>
+ {!isFirst && <div className="bg-ui-border-base w-px flex-1" />}
+ </div>
+ <div
+ className={clx({
+ "pb-4": !isFirst,
+ })}
+ >
+ <div className="flex items-center justify-between">
+ {itemsToSend?.length || itemsToReturn?.length ? (
+ <ActivityItems
+ title={title as string}
+ itemsToSend={itemsToSend}
+ itemsToReturn={itemsToReturn}
+ itemsMap={itemsMap}
+ />
+ ) : (
+ <Text size="small" leading="compact" weight="plus">
+ {title}
+ </Text>
+ )}
+ {timestamp && (
+ <Tooltip
+ content={getFullDate({
+ date: timestamp,
+ includeTime: true,
+ })}
+ >
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle text-right"
+ >
+ {getRelativeDate(timestamp)}
+ </Text>
+ </Tooltip>
+ )}
+ </div>
+ <div>{children}</div>
+ </div>
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-edit-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-edit-body.tsx
new file mode 100644
index 000000000..bd683045a
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/order-edit-body.tsx
@@ -0,0 +1,35 @@
+import { Text } from "@medusajs/ui"
+import { AdminOrderChange } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { useMemo } from "react"
+import { countItemsChange } from "../utils/count-items-change"
+
+type OrderEditBodyProps = {
+ edit: AdminOrderChange
+}
+
+export const OrderEditBody = ({ edit }: OrderEditBodyProps) => {
+ const { t } = useTranslation()
+
+ const [itemsAdded, itemsRemoved] = useMemo(
+ () => countItemsChange(edit.actions),
+ [edit]
+ )
+
+ return (
+ <div>
+ {itemsAdded > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("labels.added")}: {itemsAdded}
+ </Text>
+ )}
+
+ {itemsRemoved > 0 && (
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("labels.removed")}: {itemsRemoved}
+ </Text>
+ )}
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/return-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/return-body.tsx
new file mode 100644
index 000000000..0b602890d
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/return-body.tsx
@@ -0,0 +1,67 @@
+import { Button, Text, usePrompt } from "@medusajs/ui"
+import { AdminReturn } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { useCancelReturn } from "@hooks/api/returns"
+
+type ReturnBodyProps = {
+ orderReturn: AdminReturn
+ isCreated: boolean
+ isReceived?: boolean
+}
+
+export const ReturnBody = ({
+ orderReturn,
+ isCreated,
+ isReceived,
+}: ReturnBodyProps) => {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const { mutateAsync: cancelReturnRequest } = useCancelReturn(
+ orderReturn.id,
+ orderReturn.order_id
+ )
+
+ const onCancel = async () => {
+ const res = await prompt({
+ title: t("orders.returns.cancel.title"),
+ description: t("orders.returns.cancel.description"),
+ confirmText: t("actions.confirm"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await cancelReturnRequest()
+ }
+
+ const numberOfItems = orderReturn.items.reduce((acc, item) => {
+ return acc + (isReceived ? item.received_quantity : item.quantity) // TODO: revisit when we add dismissed quantity on ReturnItem
+ }, 0)
+
+ return (
+ <div className="flex items-start gap-1">
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.events.return.items", {
+ count: numberOfItems,
+ })}
+ </Text>
+ {isCreated && (
+ <>
+ <div className="mt-[2px] flex items-center leading-none">⋅</div>
+ <Button
+ onClick={onCancel}
+ className="text-ui-fg-subtle h-auto px-0 leading-none hover:bg-transparent"
+ variant="transparent"
+ size="small"
+ >
+ {t("actions.cancel")}
+ </Button>
+ </>
+ )}
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/transfer-order-request-body.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/transfer-order-request-body.tsx
new file mode 100644
index 000000000..bfd019f67
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/components/transfer-order-request-body.tsx
@@ -0,0 +1,69 @@
+import { Button, Text, usePrompt } from "@medusajs/ui"
+import { AdminOrderChange } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { useCancelOrderTransfer, useCustomer } from "@hooks/api"
+
+type TransferOrderRequestBodyProps = {
+ transfer: AdminOrderChange
+}
+
+export const TransferOrderRequestBody = ({
+ transfer,
+}: TransferOrderRequestBodyProps) => {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const action = transfer.actions[0]
+ const { customer } = useCustomer(action.reference_id)
+
+ const isCompleted = !!transfer.confirmed_at
+
+ const { mutateAsync: cancelTransfer } = useCancelOrderTransfer(
+ transfer.order_id
+ )
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("actions.cannotUndo"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await cancelTransfer()
+ }
+
+ /**
+ * TODO: change original_email to customer info when action details is changed
+ */
+
+ return (
+ <div>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.from")}: {String(action.details?.original_email || "")}
+ </Text>
+
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.activity.to")}:{" "}
+ {customer?.first_name
+ ? `${customer?.first_name} ${customer?.last_name}`
+ : customer?.email}
+ </Text>
+ {!isCompleted && (
+ <Button
+ onClick={handleDelete}
+ className="text-ui-fg-subtle h-auto px-0 leading-none hover:bg-transparent"
+ variant="transparent"
+ size="small"
+ >
+ {t("actions.cancel")}
+ </Button>
+ )}
+ </div>
+ )
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/index.ts
new file mode 100644
index 000000000..d57b5eba5
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/index.ts
@@ -0,0 +1,2 @@
+export * from "./use-activity-items"
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/use-activity-items.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/use-activity-items.tsx
new file mode 100644
index 000000000..fbfd38de6
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/hooks/use-activity-items.tsx
@@ -0,0 +1,479 @@
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { AdminClaim, AdminExchange, AdminReturn } from "@medusajs/types"
+import { Text } from "@medusajs/ui"
+import { ReactNode } from "react"
+import { By } from "@components/common/user-link"
+import {
+ useOrderChanges,
+ useOrderLineItems,
+} from "@hooks/api"
+import { ExtendedAdminOrderLineItemWithInventory } from "@custom-types/order"
+import { ExtendedAdminOrder, ExtendedAdminOrderChange } from "@custom-types/order"
+import { getStylizedAmount } from "@lib/money-amount-helpers"
+import { getFormattedAddress } from "@lib/addresses"
+import { AdminOrderAddress, AdminStockLocationAddress } from "@medusajs/types"
+import ChangeDetailsTooltip from "../change-details-tooltip"
+import { FulfillmentCreatedBody } from "../components"
+import { ReturnBody } from "../components"
+import { ClaimBody } from "../components"
+import { ExchangeBody } from "../components"
+import { OrderEditBody } from "../components"
+import { TransferOrderRequestBody } from "../components"
+import { getMissingLineItemIds } from "../utils"
+
+/**
+ * Order Changes that are not related to RMA flows
+ */
+const NON_RMA_CHANGE_TYPES = ["transfer", "update_order"]
+
+export type Activity = {
+ title: string | ReactNode
+ timestamp: string | Date | null
+ children?: ReactNode
+ itemsToSend?: AdminClaim["additional_items"] | AdminExchange["additional_items"]
+ itemsToReturn?: AdminReturn["items"]
+ itemsMap?: Map<string, ExtendedAdminOrderLineItemWithInventory>
+}
+
+export const useActivityItems = (order: ExtendedAdminOrder): Activity[] => {
+ const { t } = useTranslation()
+
+ const { order_changes: orderChanges = [] } = useOrderChanges(order.id)
+
+ const rmaChanges = orderChanges.filter(
+ (oc) => oc.change_type && !NON_RMA_CHANGE_TYPES.includes(oc.change_type)
+ )
+
+ const missingLineItemIds = getMissingLineItemIds(order, rmaChanges)
+ const { order_items: removedLineItems = [] } = useOrderLineItems(
+ order.id,
+ {
+ fields: "+quantity",
+ item_id: missingLineItemIds.join(","),
+ },
+ {
+ enabled: !!rmaChanges.length,
+ }
+ )
+
+ const itemsMap = useMemo(() => {
+ const _itemsMap = new Map<string, ExtendedAdminOrderLineItemWithInventory>(
+ order?.items?.map((i) => [i.id, i])
+ )
+
+ // Add removed line items to the map
+ // These items won't have the extended inventory fields, but that's okay
+ // since they're not used for removed/historical items
+ for (const id of missingLineItemIds) {
+ const orderItem = removedLineItems.find((i) => i.item.id === id)
+
+ if (orderItem && orderItem.item) {
+ // Spread the item and override the variant to be undefined
+ // since removed items don't need variant inventory information
+ const lineItem: ExtendedAdminOrderLineItemWithInventory = {
+ ...orderItem.item,
+ variant: undefined, // Removed items don't need variant details
+ }
+ _itemsMap.set(id, lineItem)
+ }
+ }
+
+ return _itemsMap
+ }, [order.items, removedLineItems, missingLineItemIds])
+
+ const returns: AdminReturn[] = []
+ const claims: AdminClaim[] = []
+ const exchanges: AdminExchange[] = []
+
+ // const { returns = [] } = useReturns({
+ // order_id: order.id,
+ // fields: '+received_at,*items',
+ // });
+
+ // const { claims = [] } = useClaims({
+ // order_id: order.id,
+ // fields: '*additional_items',
+ // });
+
+ // const { exchanges = [] } = useExchanges({
+ // order_id: order.id,
+ // fields: '*additional_items',
+ // });
+
+
+ const notes: any[] = []
+ const isLoading = false
+ // const { notes, isLoading, isError, error } = useNotes(
+ // {
+ // resource_id: order.id,
+ // limit: NOTE_LIMIT,
+ // offset: 0,
+ // },
+ // {
+ // keepPreviousData: true,
+ // }
+ // )
+ //
+ // if (isError) {
+ // throw error
+ // }
+
+
+ // TODO: uncomment and fix payment related logic when backend returns data about payment cancel/capture/refund dates
+ const payments = order.split_order_payment
+
+ return useMemo(() => {
+ if (isLoading) {
+ return []
+ }
+
+ const items: Activity[] = []
+
+ // if (payment) {
+ // const amount = payment.authorized_amount
+
+ // items.push({
+ // title: t("orders.activity.events.payment.awaiting"),
+ // timestamp: payment?.created_at,
+ // children: (
+ // <Text size="small" className="text-ui-fg-subtle">
+ // {getStylizedAmount(amount, payment.currency_code)}
+ // </Text>
+ // ),
+ // })
+
+ // if (payment.canceled_at) {
+ // items.push({
+ // title: t("orders.activity.events.payment.canceled"),
+ // timestamp: payment.canceled_at,
+ // children: (
+ // <Text size="small" className="text-ui-fg-subtle">
+ // {getStylizedAmount(amount, payment.currency_code)}
+ // </Text>
+ // ),
+ // })
+ // }
+
+ // if (payment.captured_at) {
+ // items.push({
+ // title: t("orders.activity.events.payment.captured"),
+ // timestamp: payment.captured_at,
+ // children: (
+ // <Text size="small" className="text-ui-fg-subtle">
+ // {getStylizedAmount(amount, payment.currency_code)}
+ // </Text>
+ // ),
+ // })
+ // }
+
+ // for (const refund of payment.refunds || []) {
+ // items.push({
+ // title: t("orders.activity.events.payment.refunded"),
+ // timestamp: refund.created_at,
+ // children: (
+ // <Text size="small" className="text-ui-fg-subtle">
+ // {getStylizedAmount(
+ // refund.amount as number,
+ // payment.currency_code
+ // )}
+ // </Text>
+ // ),
+ // })
+ // }
+ // }
+
+ for (const fulfillment of order.fulfillments || []) {
+ items.push({
+ title: t("orders.activity.events.fulfillment.created"),
+ timestamp: fulfillment.created_at,
+ children: <FulfillmentCreatedBody fulfillment={fulfillment as any} />,
+ })
+
+ if (fulfillment.delivered_at) {
+ items.push({
+ title: t("orders.activity.events.fulfillment.delivered"),
+ timestamp: fulfillment.delivered_at,
+ children: <FulfillmentCreatedBody fulfillment={fulfillment as any} />,
+ })
+ }
+
+ if (fulfillment.shipped_at) {
+ items.push({
+ title: t("orders.activity.events.fulfillment.shipped"),
+ timestamp: fulfillment.shipped_at,
+ children: (
+ <FulfillmentCreatedBody fulfillment={fulfillment as any} isShipment />
+ ),
+ })
+ }
+
+ if (fulfillment.canceled_at) {
+ items.push({
+ title: t("orders.activity.events.fulfillment.canceled"),
+ timestamp: fulfillment.canceled_at,
+ })
+ }
+ }
+
+ const returnMap = new Map<string, AdminReturn>()
+
+ for (const ret of returns) {
+ returnMap.set(ret.id, ret)
+
+ if (ret.claim_id || ret.exchange_id) {
+ continue
+ }
+
+ // Always display created action
+ items.push({
+ title: t("orders.activity.events.return.created", {
+ returnId: ret.id.slice(-7),
+ }),
+ timestamp: ret.created_at,
+ itemsToReturn: ret?.items,
+ itemsMap,
+ children: <ReturnBody orderReturn={ret} isCreated={!ret.canceled_at} />,
+ })
+
+ if (ret.canceled_at) {
+ items.push({
+ title: t("orders.activity.events.return.canceled", {
+ returnId: ret.id.slice(-7),
+ }),
+ timestamp: ret.canceled_at,
+ })
+ }
+
+ if (ret.status === "received" || ret.status === "partially_received") {
+ items.push({
+ title: t("orders.activity.events.return.received", {
+ returnId: ret.id.slice(-7),
+ }),
+ timestamp: ret.received_at,
+ itemsToReturn: ret?.items,
+ itemsMap,
+ children: <ReturnBody orderReturn={ret} isCreated={false} isReceived />,
+ })
+ }
+ }
+
+ for (const claim of claims) {
+ const claimReturn = returnMap.get(claim.return_id!)
+
+ items.push({
+ title: t(
+ claim.canceled_at
+ ? "orders.activity.events.claim.canceled"
+ : "orders.activity.events.claim.created",
+ {
+ claimId: claim.id.slice(-7),
+ }
+ ),
+ timestamp: claim.canceled_at || claim.created_at,
+ itemsToSend: claim.additional_items,
+ itemsToReturn: claimReturn?.items,
+ itemsMap,
+ children: <ClaimBody claim={claim} claimReturn={claimReturn} />,
+ })
+ }
+
+ for (const exchange of exchanges) {
+ const exchangeReturn = returnMap.get(exchange.return_id!)
+
+ items.push({
+ title: t(
+ exchange.canceled_at
+ ? "orders.activity.events.exchange.canceled"
+ : "orders.activity.events.exchange.created",
+ {
+ exchangeId: exchange.id.slice(-7),
+ }
+ ),
+ timestamp: exchange.canceled_at || exchange.created_at,
+ itemsToSend: exchange.additional_items,
+ itemsToReturn: exchangeReturn?.items,
+ itemsMap,
+ children: (
+ <ExchangeBody exchange={exchange} exchangeReturn={exchangeReturn} />
+ ),
+ })
+ }
+
+ for (const edit of orderChanges.filter((oc) => oc.change_type === "edit")) {
+ const isConfirmed = edit.status === "confirmed"
+ const isPending = edit.status === "pending"
+
+ if (isPending) {
+ continue
+ }
+
+ const translationKey = `orders.activity.events.edit.${edit.status}` as const
+ items.push({
+ title: t(translationKey as any, {
+ editId: edit.id.slice(-7),
+ }),
+ timestamp:
+ edit.status === "requested"
+ ? edit.requested_at
+ : edit.status === "confirmed"
+ ? edit.confirmed_at
+ : edit.status === "declined"
+ ? edit.declined_at
+ : edit.status === "canceled"
+ ? edit.canceled_at
+ : edit.created_at,
+ children: isConfirmed ? <OrderEditBody edit={edit} /> : null,
+ })
+ }
+
+ for (const transfer of orderChanges.filter(
+ (oc) => oc.change_type === "transfer"
+ )) {
+ if (transfer.requested_at) {
+ items.push({
+ title: t(`orders.activity.events.transfer.requested`, {
+ transferId: transfer.id.slice(-7),
+ }),
+ timestamp: transfer.requested_at,
+ children: <TransferOrderRequestBody transfer={transfer} />,
+ })
+ }
+
+ if (transfer.confirmed_at) {
+ items.push({
+ title: t(`orders.activity.events.transfer.confirmed`, {
+ transferId: transfer.id.slice(-7),
+ }),
+ timestamp: transfer.confirmed_at,
+ })
+ }
+ if (transfer.declined_at) {
+ items.push({
+ title: t(`orders.activity.events.transfer.declined`, {
+ transferId: transfer.id.slice(-7),
+ }),
+ timestamp: transfer.declined_at,
+ })
+ }
+ }
+
+ for (const update of (orderChanges as ExtendedAdminOrderChange[]).filter(
+ (oc) => oc.change_type === "edit"
+ )) {
+ const updateType = update.actions[0]?.details?.type
+
+ if (updateType === "shipping_address") {
+ const oldAddress = update?.actions[0]?.details?.old as AdminOrderAddress | AdminStockLocationAddress | null | undefined
+ const newAddress = update?.actions[0]?.details?.new as AdminOrderAddress | AdminStockLocationAddress | null | undefined
+
+ items.push({
+ title: (
+ <ChangeDetailsTooltip
+ title={t(`orders.activity.events.update_order.shipping_address`)}
+ previous={getFormattedAddress({
+ address: oldAddress,
+ }).join(", ")}
+ next={getFormattedAddress({
+ address: newAddress,
+ }).join(", ")}
+ />
+ ),
+ timestamp: update.created_at,
+ children: update.created_by ? (
+ <div className="text-ui-fg-subtle mt-2 flex gap-x-2 text-sm">
+ {t("fields.by")} <By id={update.created_by} />
+ </div>
+ ) : null,
+ })
+ }
+
+ if (updateType === "billing_address") {
+ const oldAddress = update?.actions[0]?.details?.old as AdminOrderAddress | AdminStockLocationAddress | null | undefined
+ const newAddress = update?.actions[0]?.details?.new as AdminOrderAddress | AdminStockLocationAddress | null | undefined
+
+ items.push({
+ title: (
+ <ChangeDetailsTooltip
+ title={t(`orders.activity.events.update_order.billing_address`)}
+ previous={getFormattedAddress({
+ address: oldAddress,
+ }).join(", ")}
+ next={getFormattedAddress({
+ address: newAddress,
+ }).join(", ")}
+ />
+ ),
+ timestamp: update.created_at,
+ children: update.created_by ? (
+ <div className="text-ui-fg-subtle mt-2 flex gap-x-2 text-sm">
+ {t("fields.by")} <By id={update.created_by} />
+ </div>
+ ) : null,
+ })
+ }
+
+ if (updateType === "email") {
+ const oldEmail = update.actions[0]?.details?.old
+ const newEmail = update.actions[0]?.details?.new
+
+ items.push({
+ title: (
+ <ChangeDetailsTooltip
+ title={t(`orders.activity.events.update_order.email`)}
+ previous={oldEmail as ReactNode}
+ next={newEmail as ReactNode}
+ />
+ ),
+ timestamp: update.created_at,
+ children: update.created_by ? (
+ <div className="text-ui-fg-subtle mt-2 flex gap-x-2 text-sm">
+ {t("fields.by")} <By id={update.created_by} />
+ </div>
+ ) : null,
+ })
+ }
+ }
+
+ // for (const note of notes || []) {
+ // items.push({
+ // title: t("orders.activity.events.note.comment"),
+ // timestamp: note.created_at,
+ // children: <NoteBody note={note} />,
+ // })
+ // }
+
+ if (order.canceled_at) {
+ items.push({
+ title: t("orders.activity.events.canceled.title"),
+ timestamp: order.canceled_at,
+ })
+ }
+
+ const sortedActivities = items.sort((a, b) => {
+ return new Date(b.timestamp!).getTime() - new Date(a.timestamp!).getTime()
+ })
+
+ const createdAt = {
+ title: t("orders.activity.events.placed.title"),
+ timestamp: order.created_at,
+ children: (
+ <Text size="small" className="text-ui-fg-subtle">
+ {getStylizedAmount(order.total, order.currency_code)}
+ </Text>
+ ),
+ }
+
+ return [...sortedActivities, createdAt]
+ }, [
+ order,
+ payments,
+ returns,
+ exchanges,
+ orderChanges,
+ notes,
+ isLoading,
+ itemsMap,
+ ])
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/index.ts
new file mode 100644
index 000000000..9f94b9d3e
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-activity-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-activity-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-activity-section.tsx
new file mode 100644
index 000000000..893048584
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-activity-section.tsx
@@ -0,0 +1,22 @@
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ExtendedAdminOrder } from "@custom-types/order"
+import { OrderTimeline } from "./order-timeline"
+
+type OrderActivityProps = {
+ order: ExtendedAdminOrder
+}
+
+export const OrderActivitySection = ({ order }: OrderActivityProps) => {
+ const { t } = useTranslation()
+ return (
+ <Container className="flex flex-col gap-y-8 px-6 py-4">
+ <div className="flex flex-col gap-y-4">
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("orders.activity.header")}</Heading>
+ </div>
+ </div>
+ <OrderTimeline order={order} />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-timeline.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-timeline.tsx
new file mode 100644
index 000000000..d168a440c
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/order-timeline.tsx
@@ -0,0 +1,67 @@
+import { ExtendedAdminOrder } from "@custom-types/order"
+import { useActivityItems } from "./hooks"
+import { OrderActivityItem, OrderActivityCollapsible } from "./components"
+
+type OrderTimelineProps = {
+ order: ExtendedAdminOrder
+}
+
+export const OrderTimeline = ({ order }: OrderTimelineProps) => {
+ const items = useActivityItems(order)
+
+ if (items.length <= 3) {
+ return (
+ <div className="flex flex-col gap-y-0.5">
+ {items.map((item, index) => {
+ return (
+ <OrderActivityItem
+ key={index}
+ title={item.title}
+ timestamp={item.timestamp}
+ isFirst={index === items.length - 1}
+ itemsToSend={item.itemsToSend}
+ itemsToReturn={item.itemsToReturn}
+ itemsMap={item.itemsMap}
+ >
+ {item.children}
+ </OrderActivityItem>
+ )
+ })}
+ </div>
+ )
+ }
+
+ const lastItems = items.slice(0, 2)
+ const collapsibleItems = items.slice(2, items.length - 1)
+ const firstItem = items[items.length - 1]
+
+ return (
+ <div className="flex flex-col gap-y-0.5">
+ {lastItems.map((item, index) => {
+ return (
+ <OrderActivityItem
+ key={index}
+ title={item.title}
+ timestamp={item.timestamp}
+ itemsToSend={item.itemsToSend}
+ itemsToReturn={item.itemsToReturn}
+ itemsMap={item.itemsMap}
+ >
+ {item.children}
+ </OrderActivityItem>
+ )
+ })}
+ <OrderActivityCollapsible activities={collapsibleItems} />
+ <OrderActivityItem
+ title={firstItem.title}
+ timestamp={firstItem.timestamp}
+ isFirst
+ itemsToSend={firstItem.itemsToSend}
+ itemsToReturn={firstItem.itemsToReturn}
+ itemsMap={firstItem.itemsMap}
+ >
+ {firstItem.children}
+ </OrderActivityItem>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/count-items-change.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/count-items-change.ts
new file mode 100644
index 000000000..280f89020
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/count-items-change.ts
@@ -0,0 +1,24 @@
+import { AdminOrderChange } from "@medusajs/types"
+
+export function countItemsChange(actions: AdminOrderChange["actions"]) {
+ let added = 0
+ let removed = 0
+
+ actions.forEach((action) => {
+ if (action.action === "ITEM_ADD") {
+ added += action.details!.quantity as number
+ }
+ if (action.action === "ITEM_UPDATE") {
+ const quantityDiff = action.details!.quantity_diff as number
+
+ if (quantityDiff > 0) {
+ added += quantityDiff
+ } else {
+ removed += Math.abs(quantityDiff)
+ }
+ }
+ })
+
+ return [added, removed]
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/get-missing-line-item-ids.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/get-missing-line-item-ids.ts
new file mode 100644
index 000000000..a3fbcebf3
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/get-missing-line-item-ids.ts
@@ -0,0 +1,28 @@
+import { AdminOrder, AdminOrderChange } from "@medusajs/types"
+
+export function getMissingLineItemIds(order: AdminOrder, changes: AdminOrderChange[]) {
+ if (!changes?.length) {
+ return []
+ }
+
+ const retIds = new Set<string>()
+ const existingItemsMap = new Map(order.items.map((item) => [item.id, true]))
+
+ changes.forEach((change) => {
+ change.actions.forEach((action) => {
+ if (!action.details?.reference_id) {
+ return
+ }
+
+ if (
+ (action.details.reference_id as string).startsWith("ordli_") &&
+ !existingItemsMap.has(action.details.reference_id as string)
+ ) {
+ retIds.add(action.details.reference_id as string)
+ }
+ })
+ })
+
+ return Array.from(retIds)
+}
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/index.ts
new file mode 100644
index 000000000..12003ef9b
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-activity-section/utils/index.ts
@@ -0,0 +1,3 @@
+export * from "./count-items-change"
+export * from "./get-missing-line-item-ids"
+
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/index.ts
new file mode 100644
index 000000000..84cacaaae
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-customer-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/order-customer-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/order-customer-section.tsx
new file mode 100644
index 000000000..44b463cec
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-customer-section/order-customer-section.tsx
@@ -0,0 +1,30 @@
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { CustomerInfo } from "@components/common/customer-info"
+import { HttpTypes } from "@medusajs/types"
+
+type OrderCustomerSectionProps = {
+ order: HttpTypes.AdminOrder
+}
+
+export const OrderCustomerSection = ({ order }: OrderCustomerSectionProps) => {
+ return (
+ <Container className="divide-y p-0">
+ <Header />
+ <CustomerInfo.ID data={order} />
+ <CustomerInfo.Contact data={order} />
+ <CustomerInfo.Company data={order} />
+ <CustomerInfo.Addresses data={order} />
+ </Container>
+ )
+}
+
+const Header = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("fields.customer")}</Heading>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/index.ts
new file mode 100644
index 000000000..6945fbefa
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-fulfillment-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/order-fulfillment-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/order-fulfillment-section.tsx
new file mode 100644
index 000000000..b8f0ed2d3
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-fulfillment-section/order-fulfillment-section.tsx
@@ -0,0 +1,468 @@
+import { XCircle } from "@medusajs/icons"
+import { AdminOrderLineItem } from "@medusajs/types"
+import {
+ Button,
+ Container,
+ Copy,
+ Heading,
+ StatusBadge,
+ Text,
+ Tooltip,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { format } from "date-fns"
+import { useTranslation } from "react-i18next"
+import { Link, useNavigate } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { Skeleton } from "@components/common/skeleton"
+import { Thumbnail } from "@components/common/thumbnail"
+import {
+ useCancelOrderFulfillment,
+ useMarkOrderFulfillmentAsDelivered,
+} from "@hooks/api/orders"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { formatProvider } from "@lib/format-provider"
+import { getLocaleAmount } from "@lib/money-amount-helpers"
+import { FulfillmentSetType } from "@pages/settings/locations/_common/constants"
+import {
+ ExtendedAdminOrder,
+ ExtendedAdminOrderFulfillment,
+} from "@custom-types/order"
+
+type OrderFulfillmentSectionProps = {
+ order: ExtendedAdminOrder
+}
+
+export const OrderFulfillmentSection = ({
+ order,
+}: OrderFulfillmentSectionProps) => {
+ const fulfillments = order.fulfillments || []
+
+ return (
+ <div className="flex flex-col gap-y-3">
+ <UnfulfilledItemBreakdown order={order} />
+ {fulfillments.map((f, index) => (
+ <Fulfillment key={f.id} index={index} fulfillment={f} order={order} />
+ ))}
+ </div>
+ )
+}
+
+const UnfulfilledItem = ({
+ item,
+ currencyCode,
+}: {
+ item: AdminOrderLineItem
+ currencyCode: string
+}) => {
+ return (
+ <div
+ key={item.id}
+ className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4"
+ >
+ <div className="flex items-start gap-x-4">
+ <Thumbnail src={item.thumbnail} />
+ <div>
+ <Text
+ size="small"
+ leading="compact"
+ weight="plus"
+ className="text-ui-fg-base"
+ >
+ {item.title}
+ </Text>
+ {item.variant_sku && (
+ <div className="flex items-center gap-x-1">
+ <Text size="small">{item.variant_sku}</Text>
+ <Copy content={item.variant_sku} className="text-ui-fg-muted" />
+ </div>
+ )}
+ <Text size="small">
+ {item.variant?.options?.map((o) => o.value).join(" · ")}
+ </Text>
+ </div>
+ </div>
+ <div className="grid grid-cols-3 items-center gap-x-4">
+ <div className="flex items-center justify-end">
+ <Text size="small">
+ {getLocaleAmount(item.unit_price, currencyCode)}
+ </Text>
+ </div>
+ <div className="flex items-center justify-end">
+ <Text>
+ <span className="tabular-nums">
+ {item.quantity - item.detail.fulfilled_quantity}
+ </span>
+ x
+ </Text>
+ </div>
+ <div className="flex items-center justify-end">
+ <Text size="small">
+ {getLocaleAmount(item.subtotal || 0, currencyCode)}
+ </Text>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+const UnfulfilledItemBreakdown = ({ order }: { order: ExtendedAdminOrder }) => {
+ // Create an array of order items that haven't been fulfilled or at least not fully fulfilled
+ const unfulfilledItemsWithShipping = order.items!.filter(
+ (i) =>
+ i.requires_shipping &&
+ i.detail &&
+ i.quantity &&
+ i.detail.fulfilled_quantity < i.quantity
+ )
+
+ const unfulfilledItemsWithoutShipping = order.items!.filter(
+ (i) =>
+ !i.requires_shipping &&
+ i.detail &&
+ i.quantity &&
+ i.detail.fulfilled_quantity < i.quantity
+ )
+
+ return (
+ <>
+ {!!unfulfilledItemsWithShipping.length && (
+ <UnfulfilledItemDisplay
+ order={order}
+ unfulfilledItems={unfulfilledItemsWithShipping}
+ requiresShipping={true}
+ />
+ )}
+
+ {!!unfulfilledItemsWithoutShipping.length && (
+ <UnfulfilledItemDisplay
+ order={order}
+ unfulfilledItems={unfulfilledItemsWithoutShipping}
+ requiresShipping={false}
+ />
+ )}
+ </>
+ )
+}
+
+const UnfulfilledItemDisplay = ({
+ order,
+ unfulfilledItems,
+ requiresShipping = false,
+}: {
+ order: ExtendedAdminOrder
+ unfulfilledItems: AdminOrderLineItem[]
+ requiresShipping: boolean
+}) => {
+ const { t } = useTranslation()
+
+ if (order.status === "canceled") {
+ return
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("orders.fulfillment.unfulfilledItems")}</Heading>
+
+ <div className="flex items-center gap-x-4">
+ {requiresShipping && (
+ <StatusBadge color="red" className="text-nowrap">
+ {t("orders.fulfillment.requiresShipping")}
+ </StatusBadge>
+ )}
+
+ <StatusBadge color="red" className="text-nowrap">
+ {t("orders.fulfillment.awaitingFulfillmentBadge")}
+ </StatusBadge>
+ </div>
+ </div>
+ <div>
+ {unfulfilledItems.map((item: AdminOrderLineItem) => (
+ <UnfulfilledItem
+ key={item.id}
+ item={item}
+ currencyCode={order.currency_code}
+ />
+ ))}
+ </div>
+ <div className="px-6 py-4 flex justify-end">
+ <Link
+ to={`/orders/${order.id}/fulfillment?requires_shipping=${requiresShipping}`}
+ >
+ <Button>Fulfill items</Button>
+ </Link>
+ </div>
+ </Container>
+ )
+}
+
+const Fulfillment = ({
+ fulfillment,
+ order,
+ index,
+}: {
+ fulfillment: ExtendedAdminOrderFulfillment
+ order: ExtendedAdminOrder
+ index: number
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const showLocation = !!fulfillment.location_id
+
+ const isPickUpFulfillment =
+ fulfillment.shipping_option?.service_zone.fulfillment_set.type ===
+ FulfillmentSetType.Pickup
+
+ const { stock_location, isError, error } = useStockLocation(
+ fulfillment.location_id!,
+ undefined,
+ {
+ enabled: showLocation,
+ }
+ )
+
+ let statusText = fulfillment.requires_shipping
+ ? isPickUpFulfillment
+ ? "Awaiting pickup"
+ : "Awaiting shipping"
+ : "Awaiting delivery"
+ let statusColor: "blue" | "green" | "red" = "blue"
+ let statusTimestamp = fulfillment.created_at
+
+ if (fulfillment.canceled_at) {
+ statusText = "Canceled"
+ statusColor = "red"
+ statusTimestamp = fulfillment.canceled_at
+ } else if (fulfillment.delivered_at) {
+ statusText = "Delivered"
+ statusColor = "green"
+ statusTimestamp = fulfillment.delivered_at
+ } else if (fulfillment.shipped_at) {
+ statusText = "Shipped"
+ statusColor = "green"
+ statusTimestamp = fulfillment.shipped_at
+ }
+
+ const { mutateAsync } = useCancelOrderFulfillment(order.id, fulfillment.id)
+ const { mutateAsync: markAsDelivered } = useMarkOrderFulfillmentAsDelivered(
+ order.id,
+ fulfillment.id
+ )
+
+ const showShippingButton =
+ !fulfillment.canceled_at &&
+ !fulfillment.shipped_at &&
+ !fulfillment.delivered_at &&
+ fulfillment.requires_shipping &&
+ !isPickUpFulfillment
+
+ const showDeliveryButton =
+ !fulfillment.canceled_at && !fulfillment.delivered_at
+
+ const handleMarkAsDelivered = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("orders.fulfillment.markAsDeliveredWarning"),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ variant: "confirmation",
+ })
+
+ if (res) {
+ await markAsDelivered(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t(
+ isPickUpFulfillment
+ ? "orders.fulfillment.toast.fulfillmentPickedUp"
+ : "orders.fulfillment.toast.fulfillmentDelivered"
+ )
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+ }
+
+ const handleCancel = async () => {
+ if (fulfillment.shipped_at) {
+ toast.warning(t("orders.fulfillment.toast.fulfillmentShipped"))
+ return
+ }
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("orders.fulfillment.cancelWarning"),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (res) {
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("orders.fulfillment.toast.canceled"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">
+ {t("orders.fulfillment.number", {
+ number: index + 1,
+ })}
+ </Heading>
+ <div className="flex items-center gap-x-4">
+ <Tooltip
+ content={format(
+ new Date(statusTimestamp),
+ "dd MMM, yyyy, HH:mm:ss"
+ )}
+ >
+ <StatusBadge color={statusColor} className="text-nowrap">
+ {statusText}
+ </StatusBadge>
+ </Tooltip>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.cancel"),
+ icon: <XCircle />,
+ onClick: handleCancel,
+ disabled: !!fulfillment.canceled_at,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("orders.fulfillment.itemsLabel")}
+ </Text>
+ <ul>
+ {(fulfillment.items || []).map((f_item) => (
+ <li key={f_item.line_item_id}>
+ <Text size="small" leading="compact">
+ {f_item.quantity}x {f_item.title}
+ </Text>
+ </li>
+ ))}
+ </ul>
+ </div>
+ {showLocation && (
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("orders.fulfillment.shippingFromLabel")}
+ </Text>
+ {stock_location ? (
+ <Link
+ to={`/settings/locations/${stock_location.id}`}
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover transition-fg"
+ >
+ <Text size="small" leading="compact">
+ {stock_location.name}
+ </Text>
+ </Link>
+ ) : (
+ <Skeleton className="w-16" />
+ )}
+ </div>
+ )}
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.provider")}
+ </Text>
+
+ <Text size="small" leading="compact">
+ {formatProvider(fulfillment.provider_id)}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("orders.fulfillment.trackingLabel")}
+ </Text>
+ <div>
+ {fulfillment.labels && fulfillment.labels.length > 0 ? (
+ <ul>
+ {fulfillment.labels.map((tlink) => {
+ const hasUrl =
+ !!tlink.tracking_url?.length && tlink.tracking_url !== "#"
+
+ if (hasUrl) {
+ return (
+ <li key={tlink.tracking_number}>
+ <a
+ href={tlink.tracking_url || ""}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover transition-fg"
+ >
+ <Text size="small" leading="compact">
+ {tlink.tracking_number}
+ </Text>
+ </a>
+ </li>
+ )
+ }
+
+ return (
+ <li key={tlink.tracking_number}>
+ <Text size="small" leading="compact">
+ {tlink.tracking_number}
+ </Text>
+ </li>
+ )
+ })}
+ </ul>
+ ) : (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )}
+ </div>
+ </div>
+
+ {(showShippingButton || showDeliveryButton) && (
+ <div className="bg-ui-bg-subtle flex items-center justify-end gap-x-2 rounded-b-xl px-4 py-4">
+ {showDeliveryButton && (
+ <Button onClick={handleMarkAsDelivered} variant="secondary">
+ {t(
+ isPickUpFulfillment
+ ? "orders.fulfillment.markAsPickedUp"
+ : "orders.fulfillment.markAsDelivered"
+ )}
+ </Button>
+ )}
+
+ {showShippingButton && (
+ <Button
+ onClick={() => navigate(`./${fulfillment.id}/create-shipment`)}
+ variant="secondary"
+ >
+ {t("orders.fulfillment.markAsShipped")}
+ </Button>
+ )}
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-general-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-general-section/index.ts
new file mode 100644
index 000000000..583807cc1
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-general-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-general-section/order-general-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-general-section/order-general-section.tsx
new file mode 100644
index 000000000..458e16d92
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-general-section/order-general-section.tsx
@@ -0,0 +1,158 @@
+import { CheckCircle, XCircle } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Container,
+ Copy,
+ Heading,
+ StatusBadge,
+ Text,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import {
+ useCancelOrder,
+ useCompleteOrder,
+} from "@hooks/api/orders"
+import { useDate } from "@hooks/use-date"
+import {
+ getCanceledOrderStatus,
+ getOrderFulfillmentStatus,
+ getOrderPaymentStatus,
+} from "@lib/order-helpers"
+
+type OrderGeneralSectionProps = {
+ order: HttpTypes.AdminOrder
+}
+
+export const OrderGeneralSection = ({ order }: OrderGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { getFullDate } = useDate()
+
+ const { mutateAsync: cancelOrder } = useCancelOrder(order.id)
+ const { mutateAsync: completeOrder } = useCompleteOrder(order.id)
+
+ const handleComplete = async () => {
+ await completeOrder(undefined, {
+ onSuccess: () => {
+ toast.success("Order completed")
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ const handleCancel = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("orders.cancelWarning", {
+ id: `#${order.display_id}`,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await cancelOrder(undefined, {
+ onSuccess: () => {
+ toast.success(t("orders.orderCanceled"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <Container className="flex items-center justify-between px-6 py-4">
+ <div>
+ <div className="flex items-center gap-x-1">
+ <Heading>#{order.display_id}</Heading>
+ <Copy content={`#${order.display_id}`} className="text-ui-fg-muted" />
+ </div>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("orders.onDateFromSalesChannel", {
+ date: getFullDate({ date: order.created_at, includeTime: true }),
+ salesChannel: order.sales_channel?.name,
+ })}
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-4">
+ <div className="flex items-center gap-x-1.5">
+ <OrderBadge order={order} />
+ <PaymentBadge order={order} />
+ <FulfillmentBadge order={order} />
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.complete"),
+ onClick: handleComplete,
+ disabled: order.status !== "pending",
+ icon: <CheckCircle />,
+ },
+ {
+ label: t("actions.cancel"),
+ onClick: handleCancel,
+ //@ts-ignore
+ disabled: !!order.canceled_at,
+ icon: <XCircle />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </Container>
+ )
+}
+
+const FulfillmentBadge = ({ order }: { order: HttpTypes.AdminOrder }) => {
+ const { t } = useTranslation()
+
+ const { label, color } = getOrderFulfillmentStatus(
+ t,
+ order.fulfillment_status
+ )
+
+ return (
+ <StatusBadge color={color} className="text-nowrap">
+ {label}
+ </StatusBadge>
+ )
+}
+
+const PaymentBadge = ({ order }: { order: HttpTypes.AdminOrder }) => {
+ const { t } = useTranslation()
+
+ const { label, color } = getOrderPaymentStatus(t, order.payment_status)
+
+ return (
+ <StatusBadge color={color} className="text-nowrap">
+ {label}
+ </StatusBadge>
+ )
+}
+
+const OrderBadge = ({ order }: { order: HttpTypes.AdminOrder }) => {
+ const { t } = useTranslation()
+ const orderStatus = getCanceledOrderStatus(t, order.status)
+
+ if (!orderStatus) {
+ return null
+ }
+
+ return (
+ <StatusBadge color={orderStatus.color} className="text-nowrap">
+ {orderStatus.label}
+ </StatusBadge>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/index.ts
new file mode 100644
index 000000000..4b0c66897
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-payment-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/order-payment-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/order-payment-section.tsx
new file mode 100644
index 000000000..83c311544
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-payment-section/order-payment-section.tsx
@@ -0,0 +1,103 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
+
+import { useTranslation } from "react-i18next"
+
+import { getStylizedAmount } from "@lib/money-amount-helpers"
+import { getOrderPaymentStatus } from "@lib/order-helpers"
+import { ExtendedAdminOrder } from "@custom-types/order"
+
+type OrderPaymentSectionProps = {
+ order: ExtendedAdminOrder
+}
+
+export const getPaymentsFromOrder = (order: HttpTypes.AdminOrder | ExtendedAdminOrder) => {
+ return order.payment_collections
+ ?.map((collection: HttpTypes.AdminPaymentCollection) => collection.payments)
+ .flat(1)
+ .filter(Boolean) as HttpTypes.AdminPayment[]
+}
+
+export const OrderPaymentSection = ({ order }: OrderPaymentSectionProps) => {
+ return (
+ <Container className="divide-y divide-dashed p-0">
+ <Header order={order} />
+ <Total order={order} />
+ </Container>
+ )
+}
+
+const Header = ({ order }: { order: ExtendedAdminOrder }) => {
+ const { t } = useTranslation()
+ const { label, color } = getOrderPaymentStatus(t, order.payment_status)
+
+ return (
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("orders.payment.title")}</Heading>
+
+ <StatusBadge color={color} className="text-nowrap">
+ {label}
+ </StatusBadge>
+ </div>
+ )
+}
+
+const Total = ({ order }: { order: ExtendedAdminOrder }) => {
+ const { t } = useTranslation()
+
+ if (!order.split_order_payment) {
+ return null
+ }
+
+ const totalPending =
+ order.split_order_payment.authorized_amount -
+ order.split_order_payment.captured_amount
+
+ return (
+ <div>
+ <div className="flex items-center justify-between px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("orders.payment.totalPaidByCustomer")}
+ </Text>
+
+ <Text size="small" weight="plus" leading="compact">
+ {getStylizedAmount(
+ order.split_order_payment.captured_amount,
+ order.split_order_payment.currency_code
+ )}
+ </Text>
+ </div>
+
+ {(order.split_order_payment.status === "refunded" ||
+ order.split_order_payment.status === "partially_refunded") && (
+ <div className="flex items-center justify-between px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ Refunded
+ </Text>
+
+ <Text size="small" weight="plus" leading="compact">
+ {getStylizedAmount(
+ order.split_order_payment.refunded_amount,
+ order.split_order_payment.currency_code
+ )}
+ </Text>
+ </div>
+ )}
+
+ {order.status !== "canceled" && totalPending > 0 && (
+ <div className="flex items-center justify-between px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ Total pending
+ </Text>
+
+ <Text size="small" weight="plus" leading="compact">
+ {getStylizedAmount(
+ totalPending,
+ order.split_order_payment.currency_code
+ )}
+ </Text>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/index.ts b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/index.ts
new file mode 100644
index 000000000..65fbe542a
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/index.ts
@@ -0,0 +1 @@
+export * from "./order-summary-section"
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/order-summary-section.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/order-summary-section.tsx
new file mode 100644
index 000000000..345362007
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/order-summary-section.tsx
@@ -0,0 +1,672 @@
+import { ReactNode, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import {
+ ArrowLongRight,
+ TriangleDownMini,
+} from "@medusajs/icons"
+import {
+ AdminOrder,
+ AdminOrderLineItem,
+ AdminReservation,
+ PaymentStatus,
+} from "@medusajs/types"
+import {
+ ExtendedAdminOrder,
+ ExtendedAdminPaymentCollection,
+} from "@custom-types/order"
+import {
+ Button,
+ clx,
+ Container,
+ Copy,
+ Heading,
+ StatusBadge,
+ Text,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+
+import { ActionMenu } from "@components/common/action-menu"
+import {
+ useOrderCommission,
+} from "@hooks/api/orders"
+import { useMarkPaymentCollectionAsPaid } from "@hooks/api/payment-collections"
+import { useReservationItems } from "@hooks/api/reservations"
+import { formatCurrency } from "@lib/format-currency"
+import {
+ getLocaleAmount,
+ getStylizedAmount,
+ isAmountLessThenRoundingError,
+} from "@lib/money-amount-helpers"
+import { getTotalCaptured } from "@lib/payment"
+import { CopyPaymentLink } from "../copy-payment-link/copy-payment-link"
+import ShippingInfoPopover from "./shipping-info-popover"
+import { Thumbnail } from "@components/common/thumbnail"
+
+type OrderSummarySectionProps = {
+ order: ExtendedAdminOrder
+}
+
+export const OrderSummarySection = ({
+ order,
+}: OrderSummarySectionProps & { payment_status?: PaymentStatus }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { reservations } = useReservationItems(
+ {
+ // line_item_id: order?.items?.map((i) => i.id),
+ },
+ { enabled: Array.isArray(order?.items) }
+ )
+
+ const receivableReturns = useMemo(
+ () => order.returns?.filter((r) => !r.canceled_at),
+ [order]
+ )
+
+ const showReturns = !!receivableReturns?.length
+
+ /**
+ * Show Allocation button only if there are unfulfilled items that don't have reservations
+ */
+ const showAllocateButton = useMemo(() => {
+ if (!reservations) {
+ return false
+ }
+
+ const reservationsMap = new Map(
+ reservations.map((r) => [r.line_item_id, r.id])
+ )
+
+ return order.items.some((item) => {
+ const hasUnfulfilledQuantity =
+ item.quantity &&
+ item.detail &&
+ item.quantity - item.detail.fulfilled_quantity > 0
+
+ return (
+ item.variant?.manage_inventory &&
+ hasUnfulfilledQuantity &&
+ !reservationsMap.has(item.id)
+ )
+ })
+ }, [reservations, order.items])
+
+ const unpaidPaymentCollection: ExtendedAdminPaymentCollection | undefined =
+ order.split_order_payment && order.split_order_payment.status !== "captured"
+ ? {
+ id: order.split_order_payment.payment_collection_id,
+ amount: order.split_order_payment.authorized_amount,
+ currency_code: order.split_order_payment.currency_code,
+ authorized_amount: order.split_order_payment.authorized_amount,
+ captured_amount: order.split_order_payment.captured_amount,
+ refunded_amount: order.split_order_payment.refunded_amount,
+ status: order.split_order_payment.status,
+ }
+ : undefined
+
+ const { mutateAsync: markAsPaid } = useMarkPaymentCollectionAsPaid(
+ order.id,
+ unpaidPaymentCollection?.id!
+ )
+
+ const pendingDifference = order.summary?.pending_difference || 0
+ const isAmountSignificant = !isAmountLessThenRoundingError(
+ pendingDifference,
+ order.currency_code
+ )
+
+ const showPayment =
+ unpaidPaymentCollection && pendingDifference > 0 && isAmountSignificant
+ const showRefund =
+ unpaidPaymentCollection && pendingDifference < 0 && isAmountSignificant
+
+ const handleMarkAsPaid = async (
+ paymentCollection: Partial<ExtendedAdminPaymentCollection>
+ ) => {
+ const res = await prompt({
+ title: t("orders.payment.markAsPaid"),
+ description: t("orders.payment.markAsPaidPayment", {
+ amount: formatCurrency(
+ paymentCollection.amount as number,
+ order.currency_code
+ ),
+ }),
+ confirmText: t("actions.confirm"),
+ cancelText: t("actions.cancel"),
+ variant: "confirmation",
+ })
+
+ if (!res) {
+ return
+ }
+
+ await markAsPaid(
+ { order_id: order.id },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("orders.payment.markAsPaidPaymentSuccess", {
+ amount: formatCurrency(
+ paymentCollection.amount as number,
+ order.currency_code
+ ),
+ })
+ )
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <Container className="divide-y divide-dashed p-0">
+ <Header />
+ <ItemBreakdown order={order} reservations={reservations!} />
+ <CostBreakdown order={order} />
+ <Total order={order} />
+
+ {(showAllocateButton || showReturns || showPayment || showRefund) && (
+ <div className="bg-ui-bg-subtle flex items-center justify-end gap-x-2 rounded-b-xl px-4 py-4">
+ {showReturns &&
+ (receivableReturns?.length === 1 ? (
+ <Button asChild variant="secondary" size="small">
+ <Link
+ to={`/orders/${order.id}/returns/${receivableReturns[0].id}/receive`}
+ >
+ {t("orders.returns.receive.action")}
+ </Link>
+ </Button>
+ ) : (
+ <ActionMenu
+ groups={[
+ {
+ actions: receivableReturns?.map((r) => {
+ let id = r.id
+ let returnType = "Return"
+
+ if (r.exchange_id) {
+ id = r.exchange_id
+ returnType = "Exchange"
+ }
+
+ if (r.claim_id) {
+ id = r.claim_id
+ returnType = "Claim"
+ }
+
+ return {
+ label: t("orders.returns.receive.receiveItems", {
+ id: `#${id?.slice(-7)}`,
+ returnType,
+ }),
+ icon: <ArrowLongRight />,
+ to: `/orders/${order.id}/returns/${r.id}/receive`,
+ }
+ }),
+ },
+ ]}
+ >
+ <Button variant="secondary" size="small">
+ {t("orders.returns.receive.action")}
+ </Button>
+ </ActionMenu>
+ ))}
+
+ {showAllocateButton && (
+ <Button asChild variant="secondary" size="small">
+ <Link to="allocate-items">
+ {t("orders.allocateItems.action")}
+ </Link>
+ </Button>
+ )}
+
+ {showPayment && (
+ <CopyPaymentLink
+ paymentCollection={unpaidPaymentCollection}
+ order={order}
+ />
+ )}
+
+ {showPayment && (
+ <Button
+ size="small"
+ variant="secondary"
+ onClick={() => handleMarkAsPaid(unpaidPaymentCollection)}
+ >
+ {t("orders.payment.markAsPaid")}
+ </Button>
+ )}
+
+ {showRefund && (
+ <Button size="small" variant="secondary" asChild>
+ <Link to={`/orders/${order.id}/refund`}>
+ {t("orders.payment.refundAmount", {
+ amount: getStylizedAmount(
+ pendingDifference * -1,
+ order?.currency_code
+ ),
+ })}
+ </Link>
+ </Button>
+ )}
+ </div>
+ )}
+ </Container>
+ )
+}
+
+const Header = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("fields.summary")}</Heading>
+ </div>
+ )
+}
+
+const Item = ({
+ item,
+ currencyCode,
+ reservation,
+}: {
+ item: AdminOrderLineItem
+ currencyCode: string
+ reservation?: AdminReservation
+}) => {
+ const { t } = useTranslation()
+
+ const isInventoryManaged = item.variant?.manage_inventory
+ const hasUnfulfilledItems = item.quantity - item.detail.fulfilled_quantity > 0
+
+ const original_price =
+ item.variant?.prices?.find((price) => price.currency_code === currencyCode)
+ ?.amount || 0
+ const price = item.unit_price
+
+ return (
+ <>
+ <div
+ key={item.id}
+ className="text-ui-fg-subtle grid grid-cols-2 items-center gap-x-4 px-6 py-4"
+ >
+ <div className="flex items-start gap-x-4">
+ <Thumbnail src={item.thumbnail} size="large" />
+ <div>
+ <Text
+ size="small"
+ leading="compact"
+ weight="plus"
+ className="text-ui-fg-base"
+ >
+ {item.title || item.product_title}
+ </Text>
+
+ {item.variant_sku && (
+ <div className="flex items-center gap-x-1">
+ <Text size="small">{item.variant_sku}</Text>
+ <Copy content={item.variant_sku} className="text-ui-fg-muted" />
+ </div>
+ )}
+ <Text size="small">
+ {item.variant?.options?.map((o) => o.value).join(" · ")}
+ </Text>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-3 items-center gap-x-4">
+ <div className="flex items-center justify-end gap-x-4">
+ <Text size="small">
+ {original_price !== price && (
+ <span className="line-through text-ui-fg-muted text-xs mr-1">
+ {getLocaleAmount(original_price, currencyCode)}
+ </span>
+ )}
+ {getLocaleAmount(price, currencyCode)}
+ </Text>
+ </div>
+
+ <div className="flex items-center gap-x-2">
+ <div className="w-fit min-w-[27px]">
+ <Text size="small">
+ <span className="tabular-nums">{item.quantity}</span>x
+ </Text>
+ </div>
+
+ <div className="overflow-visible">
+ {isInventoryManaged && hasUnfulfilledItems && (
+ <StatusBadge
+ color={reservation ? "green" : "orange"}
+ className="text-nowrap"
+ >
+ {reservation
+ ? t("orders.reservations.allocatedLabel")
+ : t("orders.reservations.notAllocatedLabel")}
+ </StatusBadge>
+ )}
+ </div>
+ </div>
+
+ <div className="flex items-center justify-end">
+ <Text size="small" className="pt-[1px]">
+ {getLocaleAmount(item.original_total || 0, currencyCode)}
+ </Text>
+ </div>
+ </div>
+ </div>
+ </>
+ )
+}
+
+const ItemBreakdown = ({
+ order,
+ reservations,
+}: {
+ order: AdminOrder
+ reservations?: AdminReservation[]
+}) => {
+ const reservationsMap = useMemo(
+ () => new Map((reservations || []).map((r) => [r.line_item_id, r])),
+ [reservations]
+ )
+
+ return (
+ <div>
+ {order.items?.map((item) => {
+ const reservation = reservationsMap.get(item.id)
+
+ return (
+ <Item
+ key={item.id}
+ item={item}
+ currencyCode={order.currency_code}
+ reservation={reservation}
+ />
+ )
+ })}
+ </div>
+ )
+}
+
+const Cost = ({
+ label,
+ value,
+ secondaryValue,
+ tooltip,
+}: {
+ label: ReactNode
+ value: string | number
+ secondaryValue?: string
+ tooltip?: ReactNode
+}) => (
+ <div className="grid grid-cols-3 items-center">
+ <Text size="small" leading="compact">
+ {label} {tooltip}
+ </Text>
+ <div className="text-right">
+ <Text size="small" leading="compact">
+ {secondaryValue}
+ </Text>
+ </div>
+ <div className="text-right">
+ <Text size="small" leading="compact">
+ {value}
+ </Text>
+ </div>
+ </div>
+)
+
+const CostBreakdown = ({
+ order,
+}: {
+ order: ExtendedAdminOrder
+}) => {
+ const { t } = useTranslation()
+ const [isTaxOpen, setIsTaxOpen] = useState(false)
+ const [isShippingOpen, setIsShippingOpen] = useState(false)
+
+ const { commission } = useOrderCommission(order.id!)
+
+ const discountCodes = useMemo(() => {
+ const codes = new Set()
+ order.items.forEach((item) =>
+ item.adjustments?.forEach((adj) => {
+ codes.add(adj.code)
+ })
+ )
+
+ return Array.from(codes).sort()
+ }, [order])
+
+ const taxCodes = useMemo(() => {
+ const taxCodeMap: Record<string, number> = {}
+
+ order.items.forEach((item) => {
+ item.tax_lines?.forEach((line) => {
+ taxCodeMap[line.code] = (taxCodeMap[line.code] || 0) + line.total
+ })
+ })
+
+ order.shipping_methods.forEach((sm) => {
+ sm.tax_lines?.forEach((line) => {
+ taxCodeMap[line.code] = (taxCodeMap[line.code] || 0) + line.total
+ })
+ })
+
+ return taxCodeMap
+ }, [order])
+
+ const automaticTaxesOn = !!order.region?.automatic_taxes
+ const hasTaxLines = !!Object.keys(taxCodes).length
+
+ const discountTotal = automaticTaxesOn
+ ? order.discount_total
+ : order.discount_subtotal
+
+ return (
+ <div className="text-ui-fg-subtle flex flex-col gap-y-2 px-6 py-4">
+ <Cost
+ label={t(
+ automaticTaxesOn
+ ? "orders.summary.itemTotal"
+ : "orders.summary.itemSubtotal"
+ )}
+ value={getLocaleAmount(order.item_total, order.currency_code)}
+ />
+ <Cost
+ label={
+ <span
+ onClick={() => setIsShippingOpen((o) => !o)}
+ className="flex cursor-pointer items-center gap-1"
+ >
+ <span>
+ {t(
+ automaticTaxesOn
+ ? "orders.summary.shippingTotal"
+ : "orders.summary.shippingSubtotal"
+ )}
+ </span>
+ <TriangleDownMini
+ style={{
+ transform: `rotate(${isShippingOpen ? 0 : -90}deg)`,
+ }}
+ />
+ </span>
+ }
+ value={getLocaleAmount(
+ automaticTaxesOn ? order.shipping_total : order.shipping_subtotal,
+ order.currency_code
+ )}
+ />
+
+ {isShippingOpen && (
+ <div className="flex flex-col gap-1 pl-5">
+ {(order.shipping_methods || [])
+ .sort((m1, m2) =>
+ (m1.created_at as string).localeCompare(m2.created_at as string)
+ )
+ .map((sm, i) => {
+ return (
+ <div
+ key={sm.id}
+ className="flex items-center justify-between gap-x-2"
+ >
+ <div>
+ <span className="txt-small text-ui-fg-subtle font-medium">
+ {sm.name}
+ {sm.detail?.return_id &&
+ ` (${t("fields.returnShipping")})`}{" "}
+ <ShippingInfoPopover key={i} shippingMethod={sm} />
+ </span>
+ </div>
+ <div className="relative flex-1">
+ <div className="bottom-[calc(50% - 2px)] absolute h-[1px] w-full border-b border-dashed" />
+ </div>
+ <span className="txt-small text-ui-fg-muted">
+ {getLocaleAmount(
+ automaticTaxesOn ? sm.total : sm.subtotal,
+ order.currency_code
+ )}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ )}
+
+ <Cost
+ label={t(
+ automaticTaxesOn
+ ? "orders.summary.discountTotal"
+ : "orders.summary.discountSubtotal"
+ )}
+ secondaryValue={discountCodes.join(", ")}
+ value={
+ discountTotal > 0
+ ? `- ${getLocaleAmount(discountTotal, order.currency_code)}`
+ : "-"
+ }
+ />
+
+ <>
+ <div className="flex justify-between">
+ <div
+ onClick={() => hasTaxLines && setIsTaxOpen((o) => !o)}
+ className={clx("flex items-center gap-1", {
+ "cursor-pointer": hasTaxLines,
+ })}
+ >
+ <span className="txt-small select-none">
+ {t(
+ automaticTaxesOn
+ ? "orders.summary.taxTotalIncl"
+ : "orders.summary.taxTotal"
+ )}
+ </span>
+ {hasTaxLines && (
+ <TriangleDownMini
+ style={{
+ transform: `rotate(${isTaxOpen ? 0 : -90}deg)`,
+ }}
+ />
+ )}
+ </div>
+
+ <div className="text-right">
+ <Text size="small" leading="compact">
+ {getLocaleAmount(order.tax_total, order.currency_code)}
+ </Text>
+ </div>
+ </div>
+ {isTaxOpen && (
+ <div className="flex flex-col gap-1 pl-5">
+ {Object.entries(taxCodes).map(([code, total]) => {
+ return (
+ <div
+ key={code}
+ className="flex items-center justify-between gap-x-2"
+ >
+ <div>
+ <span className="txt-small text-ui-fg-subtle font-medium">
+ {code}
+ </span>
+ </div>
+ <div className="relative flex-1">
+ <div className="bottom-[calc(50% - 2px)] absolute h-[1px] w-full border-b border-dashed" />
+ </div>
+ <span className="txt-small text-ui-fg-muted">
+ {getLocaleAmount(total as number, order.currency_code)}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </>
+ {commission && (
+ <Cost
+ label={"Commission"}
+ value={getLocaleAmount(
+ parseFloat(commission.commission_value.amount),
+ commission.commission_value.currency_code
+ )}
+ />
+ )}
+ </div>
+ )
+}
+
+const Total = ({ order }: { order: AdminOrder }) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className=" flex flex-col gap-y-2 px-6 py-4">
+ <div className="text-ui-fg-base flex items-center justify-between">
+ <Text
+ weight="plus"
+ className="text-ui-fg-subtle"
+ size="small"
+ leading="compact"
+ >
+ {t("fields.total")}
+ </Text>
+ <Text
+ weight="plus"
+ className="text-ui-fg-subtle"
+ size="small"
+ leading="compact"
+ >
+ {getStylizedAmount(order.total, order.currency_code)}
+ </Text>
+ </div>
+
+ <div className="text-ui-fg-base flex items-center justify-between">
+ <Text
+ weight="plus"
+ className="text-ui-fg-subtle"
+ size="small"
+ leading="compact"
+ >
+ {t("fields.paidTotal")}
+ </Text>
+ <Text
+ weight="plus"
+ className="text-ui-fg-subtle"
+ size="small"
+ leading="compact"
+ >
+ {getStylizedAmount(
+ getTotalCaptured(order.payment_collections || []),
+ order.currency_code
+ )}
+ </Text>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/shipping-info-popover.tsx b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/shipping-info-popover.tsx
new file mode 100644
index 000000000..4b0bdca85
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/_components/order-summary-section/shipping-info-popover.tsx
@@ -0,0 +1,48 @@
+import { InformationCircleSolid } from "@medusajs/icons"
+import { AdminOrderShippingMethod } from "@medusajs/types"
+import { Badge, Tooltip } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+type ShippingInfoPopoverProps = {
+ shippingMethod: AdminOrderShippingMethod
+}
+
+function ShippingInfoPopover({ shippingMethod }: ShippingInfoPopoverProps) {
+ const { t } = useTranslation()
+ const shippingDetail = shippingMethod?.detail
+
+ if (!shippingDetail) {
+ return
+ }
+
+ let rmaType = t("orders.return")
+ let rmaId = shippingDetail.return_id
+
+ if (shippingDetail.claim_id) {
+ rmaType = t("orders.claim")
+ rmaId = shippingDetail.claim_id
+ }
+
+ if (shippingDetail.exchange_id) {
+ rmaType = t("orders.exchange")
+ rmaId = shippingDetail.exchange_id
+ }
+
+ if (!rmaId) {
+ return
+ }
+
+ return (
+ <Tooltip
+ content={
+ <Badge size="2xsmall" rounded="full">
+ {rmaType}: #{rmaId.slice(-7)}
+ </Badge>
+ }
+ >
+ <InformationCircleSolid className="inline-block text-ui-fg-muted ml-1" />
+ </Tooltip>
+ )
+}
+
+export default ShippingInfoPopover
diff --git a/packages/vendor/src/pages/orders/[id]/allocate-items/index.tsx b/packages/vendor/src/pages/orders/[id]/allocate-items/index.tsx
new file mode 100644
index 000000000..31fa113ed
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/allocate-items/index.tsx
@@ -0,0 +1,27 @@
+// Route: /orders/:id/allocate-items
+import { useParams } from "react-router-dom"
+
+import { useOrder } from "@hooks/api/orders"
+import { RouteFocusModal } from "@components/modals"
+import { OrderAllocateItemsForm } from "./order-create-fulfillment-form"
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { order, isLoading, isError, error } = useOrder(id!, {
+ fields:
+ "currency_code,*items,*items.variant,+items.variant.product.title,*items.variant.inventory,*items.variant.inventory.location_levels,*items.variant.inventory_items,*shipping_address",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ const ready = !isLoading && order
+
+ return (
+ <RouteFocusModal>
+ {ready && <OrderAllocateItemsForm order={order} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/constants.ts b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/constants.ts
new file mode 100644
index 000000000..73f62339c
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/constants.ts
@@ -0,0 +1,6 @@
+import { z } from "zod"
+
+export const AllocateItemsSchema = z.object({
+ location_id: z.string(),
+ quantity: z.record(z.string(), z.number().or(z.string())),
+})
diff --git a/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/index.ts b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/index.ts
new file mode 100644
index 000000000..779dd5dad
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/index.ts
@@ -0,0 +1 @@
+export * from "./order-allocate-items-form"
diff --git a/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-form.tsx b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-form.tsx
new file mode 100644
index 000000000..27c43b257
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-form.tsx
@@ -0,0 +1,333 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Alert, Button, Heading, Input, Select, toast } from "@medusajs/ui"
+import { useForm, useWatch } from "react-hook-form"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { ordersQueryKeys } from "@hooks/api/orders"
+import { useCreateReservationItem } from "@hooks/api/reservations"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { queryClient } from "@lib/query-client"
+import { AllocateItemsSchema } from "./constants"
+import { OrderAllocateItemsItem } from "./order-allocate-items-item"
+type FetchError = Error & { status?: number }
+import { ExtendedAdminOrder, ExtendedAdminOrderLineItemWithInventory, ExtendedAdminProductVariantInventory } from "@custom-types/order"
+
+type OrderAllocateItemsFormProps = {
+ order: ExtendedAdminOrder
+}
+
+export function OrderAllocateItemsForm({ order }: OrderAllocateItemsFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const [disableSubmit, setDisableSubmit] = useState(false)
+ const [filterTerm, setFilterTerm] = useState("")
+
+ const { mutateAsync: allocateItems, isPending: isMutating } =
+ useCreateReservationItem()
+
+ const itemsToAllocate = useMemo(
+ () =>
+ order.items.filter(
+ (item) =>
+ item.variant?.manage_inventory &&
+ !!item.variant.inventory?.length &&
+ item?.quantity - item.detail?.fulfilled_quantity > 0
+ ),
+ [order.items]
+ )
+
+ const filteredItems = useMemo(() => {
+ return itemsToAllocate.filter(
+ (i) =>
+ i.variant_title?.toLowerCase().includes(filterTerm) ||
+ i.product_title?.toLowerCase().includes(filterTerm)
+ )
+ }, [itemsToAllocate, filterTerm])
+
+ // TODO - empty state UI
+
+ const form = useForm<zod.infer<typeof AllocateItemsSchema>>({
+ defaultValues: {
+ location_id: "",
+ quantity: defaultAllocations(itemsToAllocate),
+ },
+ resolver: zodResolver(AllocateItemsSchema),
+ })
+
+ const { stock_locations = [] } = useStockLocations()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ try {
+ const payload = Object.entries(data.quantity)
+ .filter(([key]) => !key.endsWith("-"))
+ .map(([key, quantity]) => [...key.split("-"), quantity])
+
+ if (payload.some((d) => d[2] === "")) {
+ form.setError("root.quantityNotAllocated", {
+ type: "manual",
+ message: t("orders.allocateItems.error.quantityNotAllocated"),
+ })
+
+ return
+ }
+
+ const promises = payload.map(([itemId, inventoryId, quantity]) =>
+ allocateItems({
+ location_id: data.location_id,
+ inventory_item_id: String(inventoryId),
+ line_item_id: String(itemId),
+ quantity: typeof quantity === 'string' ? Number(quantity) : quantity,
+ })
+ )
+
+ /**
+ * TODO: we should have bulk endpoint for this so this is executed in a workflow and can be reverted
+ */
+ await Promise.all(promises)
+
+ // invalidate order details so we get new item.variant.inventory items
+ await queryClient.invalidateQueries({
+ queryKey: ordersQueryKeys.details(),
+ })
+
+ handleSuccess(`/orders/${order.id}`)
+
+ toast.success(t("general.success"), {
+ description: t("orders.allocateItems.toast.created"),
+ })
+ } catch (e) {
+ toast.error(t("general.error"), {
+ description: e instanceof FetchError ? e.message : "An unknown error occurred",
+ })
+ }
+ })
+
+ const onQuantityChange = (
+ inventoryItem: ExtendedAdminProductVariantInventory,
+ lineItem: ExtendedAdminOrderLineItemWithInventory,
+ hasInventoryKit: boolean,
+ value: number | null,
+ isRoot?: boolean
+ ) => {
+ let shouldDisableSubmit = false
+
+ const key =
+ isRoot && hasInventoryKit
+ ? `quantity.${lineItem.id}-`
+ : `quantity.${lineItem.id}-${inventoryItem.id}`
+
+ form.setValue(key as `quantity.${string}`, value ?? "")
+
+ if (value && inventoryItem.location_levels) {
+ const location = inventoryItem.location_levels.find(
+ (l) => l.location_id === selectedLocationId
+ )
+ if (location) {
+ if (location.available_quantity < value) {
+ shouldDisableSubmit = true
+ }
+ }
+ }
+
+ if (hasInventoryKit && !isRoot) {
+ // changed subitem in the kit -> we need to set parent to "-"
+ form.resetField(`quantity.${lineItem.id}-` as `quantity.${string}`, { defaultValue: "" })
+ }
+
+ if (hasInventoryKit && isRoot) {
+ // changed root -> we need to set items to parent quantity x required_quantity
+
+ const item = itemsToAllocate.find((i) => i.id === lineItem.id)
+
+ if (!item || !item.variant) return
+
+ item.variant.inventory_items?.forEach((ii, ind) => {
+ const num = value || 0
+ const inventory = item.variant?.inventory?.[ind]
+
+ if (!inventory) return
+
+ form.setValue(
+ `quantity.${lineItem.id}-${inventory.id}` as `quantity.${string}`,
+ num * ii.required_quantity
+ )
+
+ if (value && inventory.location_levels) {
+ const location = inventory.location_levels.find(
+ (l) => l.location_id === selectedLocationId
+ )
+ if (location) {
+ if (location.available_quantity < value) {
+ shouldDisableSubmit = true
+ }
+ }
+ }
+ })
+ }
+
+ form.clearErrors("root.quantityNotAllocated")
+ setDisableSubmit(shouldDisableSubmit)
+ }
+
+ const selectedLocationId = useWatch({
+ name: "location_id",
+ control: form.control,
+ })
+
+ useEffect(() => {
+ if (selectedLocationId) {
+ form.setValue("quantity", defaultAllocations(itemsToAllocate))
+ }
+ }, [selectedLocationId])
+
+ const allocationError =
+ form.formState.errors?.root?.quantityNotAllocated?.message
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex h-full w-full flex-col items-center divide-y overflow-y-auto">
+ <div className="flex size-full flex-col items-center overflow-auto p-16">
+ <div className="flex w-full max-w-[736px] flex-col justify-center px-2 pb-2">
+ <div className="flex flex-col gap-8 divide-y divide-dashed">
+ <Heading>{t("orders.allocateItems.title")}</Heading>
+ <div className="flex-1 divide-y divide-dashed pt-8">
+ <Form.Field
+ control={form.control}
+ name="location_id"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <div className="flex items-center gap-3">
+ <div className="flex-1">
+ <Form.Label>{t("fields.location")}</Form.Label>
+ <Form.Hint>
+ {t("orders.allocateItems.locationDescription")}
+ </Form.Hint>
+ </div>
+ <div className="flex-1">
+ <Form.Control>
+ <Select onValueChange={onChange} {...field}>
+ <Select.Trigger
+ className="bg-ui-bg-base"
+ ref={ref}
+ >
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {stock_locations.map((l) => (
+ <Select.Item key={l.id} value={l.id}>
+ {l.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ </div>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Item className="mt-8 pt-8">
+ <div className="flex flex-row items-center">
+ <div className="flex-1">
+ <Form.Label>
+ {t("orders.allocateItems.itemsToAllocate")}
+ </Form.Label>
+ <Form.Hint>
+ {t("orders.allocateItems.itemsToAllocateDesc")}
+ </Form.Hint>
+ </div>
+ <div className="flex-1">
+ <Input
+ value={filterTerm}
+ onChange={(e) => setFilterTerm(e.target.value)}
+ placeholder={t("orders.allocateItems.search")}
+ autoComplete="off"
+ type="search"
+ />
+ </div>
+ </div>
+
+ {allocationError && (
+ <Alert className="mb-4" dismissible variant="error">
+ {allocationError}
+ </Alert>
+ )}
+
+ <div className="flex flex-col gap-y-1">
+ {filteredItems.map((item) => (
+ <OrderAllocateItemsItem
+ key={item.id}
+ form={form}
+ item={item}
+ locationId={selectedLocationId}
+ onQuantityChange={onQuantityChange}
+ />
+ ))}
+ </div>
+ </Form.Item>
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ type="submit"
+ isLoading={isMutating}
+ disabled={!selectedLocationId || disableSubmit}
+ >
+ {t("orders.allocateItems.action")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+function defaultAllocations(items: ExtendedAdminOrderLineItemWithInventory[]) {
+ const ret: Record<string, string | number> = {}
+
+ items.forEach((item) => {
+ const hasInventoryKit = (item.variant?.inventory_items?.length || 0) > 1
+
+ ret[
+ hasInventoryKit
+ ? `${item.id}-`
+ : `${item.id}-${item.variant?.inventory?.[0]?.id || ''}`
+ ] = ""
+
+ if (hasInventoryKit && item.variant?.inventory) {
+ item.variant.inventory.forEach((i) => {
+ ret[`${item.id}-${i.id}`] = ""
+ })
+ }
+ })
+
+ return ret
+}
\ No newline at end of file
diff --git a/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-item.tsx b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-item.tsx
new file mode 100644
index 000000000..43dc1e86a
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/allocate-items/order-create-fulfillment-form/order-allocate-items-item.tsx
@@ -0,0 +1,350 @@
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import {
+ Component,
+ ExclamationCircleSolid,
+ TriangleDownMini,
+} from "@medusajs/icons"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { Input, Text, clx } from "@medusajs/ui"
+import * as zod from "zod"
+
+import { Thumbnail } from "@components/common/thumbnail"
+import { getFulfillableQuantity } from "@lib/order-item"
+import { Form } from "@components/common/form"
+import { AllocateItemsSchema } from "./constants"
+import { ExtendedAdminOrderLineItemWithInventory, ExtendedAdminProductVariantInventory } from "@custom-types/order"
+
+type OrderEditItemProps = {
+ item: ExtendedAdminOrderLineItemWithInventory
+ locationId?: string
+ form: UseFormReturn<zod.infer<typeof AllocateItemsSchema>>
+ onQuantityChange: (
+ inventoryItem: ExtendedAdminProductVariantInventory,
+ lineItem: ExtendedAdminOrderLineItemWithInventory,
+ hasInventoryKit: boolean,
+ value: number | null,
+ isRoot?: boolean
+ ) => void
+}
+export function OrderAllocateItemsItem({
+ item,
+ form,
+ locationId,
+ onQuantityChange,
+}: OrderEditItemProps) {
+ const { t } = useTranslation()
+ const variant = item.variant
+ const inventory = item.variant?.inventory || []
+
+ const [isOpen, setIsOpen] = useState(false)
+
+ const quantityField = useWatch({
+ control: form.control,
+ name: "quantity",
+ })
+
+ const hasInventoryKit =
+ !!variant?.inventory_items && variant.inventory_items.length > 1
+
+ const { availableQuantity, inStockQuantity } = useMemo(() => {
+ if (!variant || !locationId) {
+ return {}
+ }
+
+ const locationInventory = inventory[0]?.location_levels?.find(
+ (inv) => inv.location_id === locationId
+ )
+
+ if (!locationInventory) {
+ return {}
+ }
+
+ return {
+ availableQuantity: locationInventory.available_quantity,
+ inStockQuantity: locationInventory.stocked_quantity,
+ }
+ }, [variant, locationId])
+
+ const hasQuantityError =
+ !hasInventoryKit &&
+ availableQuantity &&
+ item.variant?.inventory?.[0]?.id &&
+ quantityField[`${item.id}-${item.variant.inventory[0].id}`] &&
+ Number(quantityField[`${item.id}-${item.variant.inventory[0].id}`]) >
+ availableQuantity
+
+ const minValue = 0
+ const maxValue = Math.min(
+ getFulfillableQuantity(item) ?? 0,
+ availableQuantity || Number.MAX_SAFE_INTEGER
+ )
+
+ return (
+ <div className="bg-ui-bg-subtle shadow-elevation-card-rest my-2 min-w-[720px] divide-y divide-dashed rounded-xl">
+ <div className="flex items-center gap-x-3 p-3 text-sm">
+ <div className="flex flex-1 items-center">
+ <div className="flex items-center gap-x-3">
+ {hasQuantityError && (
+ <ExclamationCircleSolid className="text-ui-fg-error" />
+ )}
+ <Thumbnail src={item.thumbnail} />
+ <div className="flex flex-col">
+ <div className="flex flex-row">
+ <Text className="txt-small flex" as="span" weight="plus">
+ {item.product_title}
+ </Text>
+ {item.variant_sku && (
+ <span className="text-ui-fg-subtle">
+ {" "}
+ ({item.variant_sku})
+ </span>
+ )}
+ {hasInventoryKit && (
+ <Component className="text-ui-fg-muted ml-2 overflow-visible pt-[2px]" />
+ )}
+ </div>
+ <Text as="div" className="text-ui-fg-subtle txt-small">
+ {item.title}
+ </Text>
+ </div>
+ </div>
+ </div>
+
+ <div
+ className={clx(
+ "flex flex-1 items-center gap-x-3",
+ hasInventoryKit ? "justify-end" : "justify-between"
+ )}
+ >
+ {!hasInventoryKit && (
+ <>
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="txt-small flex flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("labels.available")}
+ </span>
+ <span className="text-ui-fg-muted">
+ {availableQuantity || "-"}
+ {availableQuantity &&
+ !hasInventoryKit &&
+ item.variant?.inventory?.[0]?.id &&
+ quantityField[
+ `${item.id}-${item.variant.inventory[0].id}`
+ ] && (
+ <span className="text-ui-fg-error txt-small ml-1">
+ -
+ {
+ quantityField[
+ `${item.id}-${item.variant.inventory[0].id}`
+ ]
+ }
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="txt-small flex flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("labels.inStock")}
+ </span>
+ <span className="text-ui-fg-muted">
+ {inStockQuantity || "-"}
+ </span>
+ </div>
+ </div>
+ </>
+ )}
+
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="text-ui-fg-subtle txt-small mr-2 flex flex-row items-center gap-2">
+ <Form.Field
+ control={form.control}
+ name={
+ hasInventoryKit && item.variant?.inventory?.[0]?.id
+ ? (`quantity.${item.id}-`)
+ : (`quantity.${item.id}-${item.variant?.inventory?.[0].id}`) as `quantity.${string}`
+ }
+ rules={{
+ required: !hasInventoryKit,
+ min: !hasInventoryKit ? minValue : undefined,
+ max: maxValue > 0 ? maxValue : undefined,
+ }}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ className="bg-ui-bg-base txt-small w-[46px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ type="number"
+ {...field}
+ disabled={!locationId}
+ onChange={(e) => {
+ const val =
+ e.target.value === ""
+ ? null
+ : Number(e.target.value)
+
+ const firstInventory = item.variant?.inventory?.[0]
+ if (firstInventory) {
+ onQuantityChange(
+ firstInventory,
+ item,
+ hasInventoryKit,
+ val,
+ true
+ )
+ }
+ }}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />{" "}
+ / {item.quantity} {t("fields.qty")}
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {hasInventoryKit && (
+ <div className="px-4 py-2">
+ <div
+ onClick={() => setIsOpen((o) => !o)}
+ className="flex items-center gap-x-2"
+ >
+ <TriangleDownMini
+ style={{ transform: `rotate(${isOpen ? -90 : 0}deg)` }}
+ className="text-ui-fg-muted -mt-[1px]"
+ />
+ <span className="txt-small text-ui-fg-muted cursor-pointer">
+ {t("orders.allocateItems.consistsOf", {
+ num: inventory.length,
+ })}
+ </span>
+ </div>
+ </div>
+ )}
+
+ {isOpen &&
+ variant?.inventory?.map((i, ind) => {
+ const location = i.location_levels?.find(
+ (l) => l.location_id === locationId
+ )
+
+ const hasQuantityError =
+ !!quantityField[`${item.id}-${i.id}`] &&
+ location &&
+ Number(quantityField[`${item.id}-${i.id}`]) > location.available_quantity
+
+ return (
+ <div key={i.id} className="txt-small flex items-center gap-x-3 p-4">
+ <div className="flex flex-1 flex-row items-center gap-3">
+ {hasQuantityError && (
+ <ExclamationCircleSolid className="text-ui-fg-error" />
+ )}
+ <div className="flex flex-col">
+ <span className="text-ui-fg-subtle">{i?.title ?? i.sku ?? `Inventory Item ${ind + 1}`}</span>
+ <span className="text-ui-fg-muted">
+ {t("orders.allocateItems.requires", {
+ num: variant?.inventory_items?.[ind]?.required_quantity || 0,
+ })}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-1 flex-row justify-between">
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="txt-small flex flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("labels.available")}
+ </span>
+ <span className="text-ui-fg-muted">
+ {location?.available_quantity || "-"}
+ {location?.available_quantity &&
+ quantityField[`${item.id}-${i.id}`] && (
+ <span className="text-ui-fg-error txt-small ml-1">
+ -{quantityField[`${item.id}-${i.id}`]}
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="txt-small flex flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("labels.inStock")}
+ </span>
+ <span className="text-ui-fg-muted">
+ {location?.stocked_quantity || "-"}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex items-center gap-3">
+ <div className="bg-ui-border-strong block h-[12px] w-[1px]" />
+
+ <div className="text-ui-fg-subtle txt-small mr-1 flex flex-row items-center gap-2">
+ <Form.Field
+ control={form.control}
+ name={`quantity.${item.id}-${i.id}` as `quantity.${string}`}
+ rules={{
+ required: true,
+ min: 0,
+ max: location?.available_quantity,
+ }}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ className="bg-ui-bg-base txt-small w-[46px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ type="number"
+ {...field}
+ disabled={!locationId}
+ onChange={(e) => {
+ const val =
+ e.target.value === ""
+ ? null
+ : Number(e.target.value)
+
+ onQuantityChange(
+ i,
+ item,
+ hasInventoryKit,
+ val
+ )
+ }}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ /{" "}
+ {item.quantity *
+ (variant.inventory_items?.[ind]?.required_quantity ?? 0)}{" "}
+ {t("fields.qty")}
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/constants.ts b/packages/vendor/src/pages/orders/[id]/constants.ts
new file mode 100644
index 000000000..4c6628537
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/constants.ts
@@ -0,0 +1,54 @@
+const DEFAULT_PROPERTIES = [
+ "id",
+ "status",
+ "created_at",
+ "canceled_at",
+ "email",
+ "display_id",
+ "currency_code",
+ "metadata",
+ // --- TOTALS ---
+ "total",
+ "item_total",
+ "shipping_subtotal",
+ "subtotal",
+ "discount_total",
+ "discount_subtotal",
+ "shipping_total",
+ "shipping_tax_total",
+ "tax_total",
+ "refundable_total",
+ "order_change",
+ "commission_value",
+]
+
+const DEFAULT_RELATIONS = [
+ "*customer",
+ "*items", // -> we get LineItem here with added `quantity` and `detail` which is actually an OrderItem (which is a parent object to LineItem in the DB)
+ "*items.variant",
+ "*items.variant.product",
+ "*items.variant.options",
+ "+items.variant.manage_inventory",
+ "*items.variant.inventory_items.inventory",
+ "+items.variant.inventory_items.required_quantity",
+ "*items.variant.prices",
+ "+summary",
+ "*shipping_address",
+ "*billing_address",
+ "*sales_channel",
+ "*promotion",
+ "*shipping_methods",
+ "*fulfillments",
+ "+fulfillments.shipping_option.service_zone.fulfillment_set.type",
+ "*fulfillments.items",
+ "*fulfillments.labels",
+ "*fulfillments.labels",
+ "region.automatic_taxes",
+ "*split_order_payment",
+ "payment_status",
+ "*returns",
+]
+
+export const DEFAULT_FIELDS = `${DEFAULT_PROPERTIES.join(
+ ","
+)},${DEFAULT_RELATIONS.join(",")}`
diff --git a/packages/vendor/src/pages/orders/[id]/fulfillment/index.tsx b/packages/vendor/src/pages/orders/[id]/fulfillment/index.tsx
new file mode 100644
index 000000000..7ed88f300
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/fulfillment/index.tsx
@@ -0,0 +1,33 @@
+// Route: /orders/:id/fulfillment
+import { useParams, useSearchParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useOrder } from "@hooks/api/orders"
+import { OrderCreateFulfillmentForm } from "./order-create-fulfillment-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const [searchParams] = useSearchParams()
+ const requiresShipping = searchParams.get("requires_shipping") === "true"
+
+ const { order, isLoading, isError, error } = useOrder(id!, {
+ fields: "*items.variant.product.shipping_profile",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ const ready = !isLoading && order
+
+ return (
+ <RouteFocusModal>
+ {ready && (
+ <OrderCreateFulfillmentForm
+ order={order}
+ requiresShipping={requiresShipping}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/constants.ts b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/constants.ts
new file mode 100644
index 000000000..3b910980b
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/constants.ts
@@ -0,0 +1,8 @@
+import { z } from "zod"
+
+export const CreateFulfillmentSchema = z.object({
+ quantity: z.record(z.string(), z.number()),
+ location_id: z.string(),
+ shipping_option_id: z.string().optional(),
+ send_notification: z.boolean().optional(),
+})
diff --git a/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/index.ts b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/index.ts
new file mode 100644
index 000000000..81950c9e0
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/index.ts
@@ -0,0 +1 @@
+export * from "./order-create-fulfillment-form"
diff --git a/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-form.tsx b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-form.tsx
new file mode 100644
index 000000000..80c85fd51
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-form.tsx
@@ -0,0 +1,443 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { AdminOrder, HttpTypes } from "@medusajs/types"
+import { Alert, Button, Select, Switch, toast } from "@medusajs/ui"
+import { useForm, useWatch } from "react-hook-form"
+
+import { OrderLineItemDTO } from "@medusajs/types"
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateOrderFulfillment } from "@hooks/api/orders"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { getFulfillableQuantity } from "@lib/order-item"
+import { CreateFulfillmentSchema } from "./constants"
+import { OrderCreateFulfillmentItem } from "./order-create-fulfillment-item"
+import {
+ useReservationItems,
+ useShippingOptions,
+} from "@hooks/api"
+import {
+ isReturnOption,
+ isSameLocation,
+} from "@lib/shipping-options"
+
+type OrderCreateFulfillmentFormProps = {
+ order: AdminOrder
+ requiresShipping: boolean
+}
+
+export function OrderCreateFulfillmentForm({
+ order,
+ requiresShipping,
+}: OrderCreateFulfillmentFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const { mutateAsync: createOrderFulfillment, isPending: isMutating } =
+ useCreateOrderFulfillment(order.id)
+
+ const { reservations: reservationsRaw } = useReservationItems()
+
+ const reservations = reservationsRaw?.filter((r) =>
+ order.items.some((i) => i.id === r.line_item_id)
+ )
+
+ const itemReservedQuantitiesMap = useMemo(
+ () =>
+ new Map((reservations || []).map((r) => [r.line_item_id, r.quantity])),
+ [reservations]
+ )
+
+ const [fulfillableItems, setFulfillableItems] = useState(() =>
+ (order.items || []).filter(
+ (item) =>
+ item.requires_shipping === requiresShipping &&
+ getFulfillableQuantity(item as any) > 0
+ )
+ )
+
+ const form = useForm<zod.infer<typeof CreateFulfillmentSchema>>({
+ defaultValues: {
+ quantity: fulfillableItems.reduce(
+ (acc, item) => {
+ acc[item.id] = getFulfillableQuantity(item as any)
+ return acc
+ },
+ {} as Record<string, number>
+ ),
+ send_notification: true,
+ },
+ resolver: zodResolver(CreateFulfillmentSchema),
+ })
+
+ const selectedLocationId = useWatch({
+ name: "location_id",
+ control: form.control,
+ })
+
+ const { stock_locations = [] } = useStockLocations()
+
+ const { shipping_options = [], isLoading: isShippingOptionsLoading } =
+ useShippingOptions({
+ fields: "+service_zone.fulfillment_set.location.id,*rules",
+ })
+
+ const filteredShippingOptions = shipping_options.filter(
+ (o) =>
+ o !== null && !isReturnOption(o) && isSameLocation(o, selectedLocationId)
+ )
+
+ const shippingOptionId = useWatch({
+ name: "shipping_option_id",
+ control: form.control,
+ })
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const selectedShippingOption = shipping_options.find(
+ (o) => o?.id === shippingOptionId
+ )
+
+ if (!selectedShippingOption) {
+ form.setError("shipping_option_id", {
+ type: "manual",
+ message: t("orders.fulfillment.error.noShippingOption"),
+ })
+ return
+ }
+
+ if (!selectedLocationId) {
+ form.setError("location_id", {
+ type: "manual",
+ message: t("orders.fulfillment.error.noLocation"),
+ })
+ return
+ }
+
+ const selectedShippingProfileId =
+ selectedShippingOption?.shipping_profile_id
+
+ const itemShippingProfileMap = order.items.reduce(
+ (acc, item) => {
+ acc[item.id] = item.variant?.product?.shipping_profile?.id ?? null
+ return acc
+ },
+ {} as Record<string, string | null>
+ )
+
+ const payload: HttpTypes.AdminCreateOrderFulfillment & {
+ requires_shipping: boolean
+ } = {
+ location_id: selectedLocationId,
+ requires_shipping: true,
+ // shipping_option_id: shippingOptionId,
+ // no_notification: !data.send_notification,
+ items: Object.entries(data.quantity)
+ .filter(
+ ([id, value]) =>
+ !!value && itemShippingProfileMap[id] === selectedShippingProfileId
+ )
+ .map(([id, quantity]) => ({
+ id,
+ quantity,
+ })),
+ }
+
+ try {
+ await createOrderFulfillment(payload)
+
+ toast.success(t("orders.fulfillment.toast.created"))
+ handleSuccess(`/orders/${order.id}`)
+ } catch (e: any) {
+ toast.error(e.message)
+ }
+ })
+
+ useEffect(() => {
+ if (stock_locations?.length && shipping_options?.length) {
+ const initialShippingOptionId =
+ order.shipping_methods?.[0]?.shipping_option_id
+
+ if (initialShippingOptionId) {
+ const shippingOption = shipping_options.find(
+ (o) => o?.id === initialShippingOptionId
+ )
+
+ if (shippingOption) {
+ const locationId =
+ shippingOption.service_zone.fulfillment_set.location.id
+
+ form.setValue("location_id", locationId)
+ form.setValue(
+ "shipping_option_id",
+ initialShippingOptionId || undefined
+ )
+ } // else -> TODO: what if original shipping option is deleted?
+ }
+ }
+ }, [stock_locations?.length, shipping_options?.length])
+
+ const fulfilledQuantityArray = (order.items || []).map(
+ (item) =>
+ item.requires_shipping === requiresShipping &&
+ item.detail.fulfilled_quantity
+ )
+
+ useEffect(() => {
+ const itemsToFulfill =
+ order?.items?.filter(
+ (item) =>
+ item.requires_shipping === requiresShipping &&
+ getFulfillableQuantity(item as OrderLineItemDTO) > 0
+ ) || []
+
+ setFulfillableItems(itemsToFulfill)
+
+ if (itemsToFulfill.length) {
+ form.clearErrors("root")
+ } else {
+ form.setError("root", {
+ type: "manual",
+ message: t("orders.fulfillment.error.noItems"),
+ })
+ }
+
+ const quantityMap = itemsToFulfill.reduce(
+ (acc, item) => {
+ acc[item.id] = getFulfillableQuantity(item as OrderLineItemDTO)
+ return acc
+ },
+ {} as Record<string, number>
+ )
+
+ form.setValue("quantity", quantityMap)
+ }, [...fulfilledQuantityArray, requiresShipping])
+
+ const differentOptionSelected =
+ shippingOptionId &&
+ order.shipping_methods?.[0]?.shipping_option_id !== shippingOptionId
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+
+ <RouteFocusModal.Body className="flex h-full w-full flex-col items-center divide-y overflow-y-auto">
+ <div className="flex size-full flex-col items-center overflow-auto p-16">
+ <div className="flex w-full max-w-[736px] flex-col justify-center px-2 pb-2">
+ <div className="flex flex-col divide-y divide-dashed">
+ <div className="pb-8">
+ <Form.Field
+ control={form.control}
+ name="location_id"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-2 xl:flex-row xl:items-center">
+ <div className="flex-1">
+ <Form.Label>{t("fields.location")}</Form.Label>
+ <Form.Hint>
+ {t("orders.fulfillment.locationDescription")}
+ </Form.Hint>
+ </div>
+ <div className="flex-1">
+ <Form.Control>
+ <Select onValueChange={onChange} {...field}>
+ <Select.Trigger
+ className="bg-ui-bg-base"
+ ref={ref}
+ >
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {stock_locations.map((l) => (
+ <Select.Item key={l.id} value={l.id}>
+ {l.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ </div>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <div className="py-8">
+ <Form.Field
+ control={form.control}
+ name="shipping_option_id"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-2 xl:flex-row xl:items-center">
+ <div className="flex-1">
+ <Form.Label>
+ {t("fields.shippingMethod")}
+ </Form.Label>
+ <Form.Hint>
+ {t("orders.fulfillment.methodDescription")}
+ </Form.Hint>
+ </div>
+ <div className="flex-1">
+ <Form.Control>
+ <Select
+ onValueChange={onChange}
+ {...field}
+ disabled={!selectedLocationId}
+ >
+ <Select.Trigger
+ className="bg-ui-bg-base"
+ ref={ref}
+ >
+ {isShippingOptionsLoading ? (
+ <span className="text-right">
+ {t("labels.loading")}
+ ...
+ </span>
+ ) : (
+ <Select.Value />
+ )}
+ </Select.Trigger>
+ <Select.Content>
+ {filteredShippingOptions.map((o) => (
+ <Select.Item key={o?.id} value={o?.id}>
+ {o?.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ </div>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ {differentOptionSelected && (
+ <Alert className="mt-4 p-4" variant="warning">
+ <span className="-mt-[3px] block font-medium">
+ {t("labels.beaware")}
+ </span>
+ <span className="text-ui-fg-muted">
+ {t("orders.fulfillment.differentOptionSelected")}
+ </span>
+ </Alert>
+ )}
+ </div>
+ <div>
+ <Form.Item className="mt-8">
+ <Form.Label>
+ {t("orders.fulfillment.itemsToFulfill")}
+ </Form.Label>
+ <Form.Hint>
+ {t("orders.fulfillment.itemsToFulfillDesc")}
+ </Form.Hint>
+
+ <div className="flex flex-col gap-y-1">
+ {fulfillableItems.map((item) => {
+ const isShippingProfileMatching =
+ shipping_options.find(
+ (o) => o?.id === shippingOptionId
+ )?.shipping_profile_id ===
+ item.variant?.product?.shipping_profile?.id
+
+ return (
+ <OrderCreateFulfillmentItem
+ key={item.id}
+ form={form}
+ item={item}
+ locationId={selectedLocationId}
+ currencyCode={order.currency_code}
+ onItemRemove={() => {}}
+ disabled={!isShippingProfileMatching}
+ itemReservedQuantitiesMap={
+ itemReservedQuantitiesMap
+ }
+ />
+ )
+ })}
+ </div>
+ </Form.Item>
+ {form.formState.errors.root && (
+ <Alert
+ variant="error"
+ dismissible={false}
+ className="flex items-center"
+ // classNameInner="flex justify-between flex-1 items-center"
+ >
+ {form.formState.errors.root.message}
+ </Alert>
+ )}
+ </div>
+
+ <div className="mt-8 pt-8 ">
+ <Form.Field
+ control={form.control}
+ name="send_notification"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <div className="flex items-center justify-between">
+ <Form.Label>
+ {t("orders.returns.sendNotification")}
+ </Form.Label>
+ <Form.Control>
+ <Form.Control>
+ <Switch
+ checked={!!value}
+ onCheckedChange={onChange}
+ {...field}
+ />
+ </Form.Control>
+ </Form.Control>
+ </div>
+ <Form.Hint className="!mt-1">
+ {t("orders.fulfillment.sendNotificationHint")}
+ </Form.Hint>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ type="submit"
+ isLoading={isMutating}
+ disabled={!shippingOptionId}
+ >
+ {t("orders.fulfillment.create")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-item.tsx b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-item.tsx
new file mode 100644
index 000000000..7dcf93834
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/fulfillment/order-create-fulfillment-form/order-create-fulfillment-item.tsx
@@ -0,0 +1,202 @@
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { clx, Input, Text, Tooltip } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { HttpTypes } from "@medusajs/types"
+
+import { Form } from "@components/common/form/index"
+import { Thumbnail } from "@components/common/thumbnail/index"
+import { useProductVariant } from "@hooks/api/products"
+import { getFulfillableQuantity } from "@lib/order-item"
+import { CreateFulfillmentSchema } from "./constants"
+import { InformationCircleSolid } from "@medusajs/icons"
+
+type OrderEditItemProps = {
+ item: HttpTypes.AdminOrderLineItem
+ currencyCode: string
+ locationId?: string
+ onItemRemove: (itemId: string) => void
+ itemReservedQuantitiesMap: Map<string | null, number>
+ form: UseFormReturn<zod.infer<typeof CreateFulfillmentSchema>>
+ disabled: boolean
+}
+
+export function OrderCreateFulfillmentItem({
+ item,
+ form,
+ locationId,
+ itemReservedQuantitiesMap,
+ disabled,
+}: OrderEditItemProps) {
+ const { t } = useTranslation()
+
+ const { variant } = useProductVariant(
+ item.product_id!,
+ item.variant_id!,
+ {
+ fields: "*inventory,*inventory.location_levels",
+ },
+ {
+ enabled: !!item.variant,
+ }
+ )
+
+ const { availableQuantity, inStockQuantity } = useMemo(() => {
+ if (!variant || !locationId) {
+ return {}
+ }
+
+ const { inventory } = variant as any
+
+ const locationInventory = inventory?.[0]?.location_levels?.find(
+ (inv: any) => inv.location_id === locationId
+ )
+
+ if (!locationInventory) {
+ return {}
+ }
+
+ const reservedQuantityForItem = itemReservedQuantitiesMap.get(item.id) ?? 0
+
+ return {
+ availableQuantity:
+ locationInventory.available_quantity + reservedQuantityForItem,
+ inStockQuantity: locationInventory.stocked_quantity,
+ }
+ }, [variant, locationId, itemReservedQuantitiesMap])
+
+ const minValue = 0
+ const maxValue = Math.min(
+ getFulfillableQuantity(item as any),
+ availableQuantity || Number.MAX_SAFE_INTEGER
+ )
+
+ return (
+ <Form.Field
+ control={form.control}
+ name={`quantity.${item.id}`}
+ rules={{
+ required: true,
+ min: minValue,
+ max: maxValue,
+ }}
+ render={({ field }) => {
+ return (
+ <div className="bg-ui-bg-subtle shadow-elevation-card-rest my-2 rounded-xl">
+ <div className="flex flex-row items-center">
+ {disabled && (
+ <div className="inline-flex items-center ml-4">
+ <Tooltip
+ content={t("orders.fulfillment.disabledItemTooltip")}
+ side="top"
+ >
+ <InformationCircleSolid className="text-ui-tag-orange-icon" />
+ </Tooltip>
+ </div>
+ )}
+
+ <div
+ className={clx(
+ "flex flex-col flex-1 gap-x-2 gap-y-2 p-3 text-sm sm:flex-row",
+ disabled && "opacity-50 pointer-events-none"
+ )}
+ >
+ <div className="flex flex-1 items-center gap-x-3">
+ <Thumbnail src={item.thumbnail} />
+ <div className="flex flex-col">
+ <div>
+ <Text className="txt-small" as="span" weight="plus">
+ {item.title}
+ </Text>
+ {item.variant_sku && <span>({item.variant_sku})</span>}
+ </div>
+ <Text as="div" className="text-ui-fg-subtle txt-small">
+ {item.variant_title}
+ </Text>
+ </div>
+ </div>
+
+ <div className="flex flex-1 items-center gap-x-1">
+ <div className="mr-2 block h-[16px] w-[2px] bg-gray-200" />
+
+ <div className="text-small flex flex-1 flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("orders.fulfillment.available")}
+ </span>
+ <span className="text-ui-fg-subtle">
+ {availableQuantity || "N/A"}
+ </span>
+ </div>
+
+ <div className="flex flex-1 items-center gap-x-1">
+ <div className="mr-2 block h-[16px] w-[2px] bg-gray-200" />
+
+ <div className="flex flex-col">
+ <span className="text-ui-fg-subtle font-medium">
+ {t("orders.fulfillment.inStock")}
+ </span>
+ <span className="text-ui-fg-subtle">
+ {inStockQuantity || "N/A"}{" "}
+ {inStockQuantity && (
+ <span className="font-medium text-red-500">
+ -{form.getValues(`quantity.${item.id}`)}
+ </span>
+ )}
+ </span>
+ </div>
+ </div>
+
+ <div className="flex flex-1 items-center gap-1">
+
+ <Form.Item>
+ <Form.Control>
+ <Input
+ className="bg-ui-bg-base txt-small w-[50px] rounded-lg text-right [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
+ type="number"
+ {...field}
+ onChange={(e) => {
+ const val =
+ e.target.value === ""
+ ? null
+ : Number(e.target.value)
+
+ field.onChange(val)
+
+ if (val !== null && !isNaN(val ?? 0)) {
+ if (val < minValue || val > maxValue) {
+ form.setError(`quantity.${item.id}`, {
+ type: "manual",
+ message: t(
+ "orders.fulfillment.error.wrongQuantity",
+ {
+ count: maxValue,
+ number: maxValue,
+ }
+ ),
+ })
+ } else {
+ form.clearErrors(`quantity.${item.id}`)
+ }
+ }
+ }}
+ />
+ </Form.Control>
+ </Form.Item>
+
+
+ <span className="text-ui-fg-subtle">
+ / {item.quantity} {t("fields.qty")}
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <Form.ErrorMessage className="flex justify-end pr-3 pb-2" />
+ </div>
+ )
+ }}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/index.tsx b/packages/vendor/src/pages/orders/[id]/index.tsx
new file mode 100644
index 000000000..a385cbb4b
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/index.tsx
@@ -0,0 +1,124 @@
+// Route: /orders/:id
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useOrder } from "@hooks/api/orders"
+import { ordersQueryKeys } from "@hooks/api/orders"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { ExtendedAdminOrderResponse } from "@custom-types/order"
+
+import { OrderCustomerSection } from "./_components/order-customer-section"
+import { OrderFulfillmentSection } from "./_components/order-fulfillment-section"
+import { OrderGeneralSection } from "./_components/order-general-section"
+import { OrderPaymentSection } from "./_components/order-payment-section"
+import { OrderSummarySection } from "./_components/order-summary-section"
+import { DEFAULT_FIELDS } from "./constants"
+
+// Loader
+const orderDetailQuery = (id: string) => ({
+ queryKey: ordersQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/orders/${id}`, {
+ method: "GET",
+ query: { fields: DEFAULT_FIELDS },
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = orderDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
+
+// Breadcrumb
+type OrderDetailBreadcrumbProps = UIMatch<ExtendedAdminOrderResponse>
+
+export const Breadcrumb = (props: OrderDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { order } = useOrder(
+ id!,
+ {
+ fields: DEFAULT_FIELDS,
+ },
+ {
+ initialData: props.data,
+ enabled: Boolean(id),
+ }
+ )
+
+ if (!order) {
+ return null
+ }
+
+ return <span>#{order.display_id}</span>
+}
+
+// Main component
+export const Component = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+
+ const { id } = useParams()
+ const { getWidgets } = useDashboardExtension()
+
+ const { order, isLoading, isError, error } = useOrder(
+ id!,
+ {
+ fields: DEFAULT_FIELDS,
+ },
+ {
+ initialData,
+ }
+ )
+
+ if (order) {
+ order.items = order.items.sort((itemA: any, itemB: any) => {
+ if (itemA.created_at > itemB.created_at) {
+ return 1
+ }
+
+ if (itemA.created_at < itemB.created_at) {
+ return -1
+ }
+
+ return 0
+ })
+ }
+
+ if (isLoading || !order) {
+ return (
+ <TwoColumnPageSkeleton mainSections={4} sidebarSections={2} showJSON />
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("order.details.after"),
+ before: getWidgets("order.details.before"),
+ sideAfter: getWidgets("order.details.side.after"),
+ sideBefore: getWidgets("order.details.side.before"),
+ }}
+ data={order}
+ hasOutlet
+ >
+ <TwoColumnPage.Main>
+ <OrderGeneralSection order={order} />
+ <OrderSummarySection order={order} />
+ <OrderPaymentSection order={order} />
+ <OrderFulfillmentSection order={order} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <OrderCustomerSection order={order} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/shipment/index.tsx b/packages/vendor/src/pages/orders/[id]/shipment/index.tsx
new file mode 100644
index 000000000..7c8835c1d
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/shipment/index.tsx
@@ -0,0 +1,33 @@
+// Route: /orders/:id/fulfillments/:f_id/shipment
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useOrder } from "@hooks/api/orders"
+import { OrderCreateShipmentForm } from "./order-create-shipment-form"
+
+export const Component = () => {
+ const { id, f_id } = useParams()
+
+ const { order, isLoading, isError, error } = useOrder(id!, {
+ fields: "*fulfillments,*fulfillments.items,*fulfillments.labels",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ const ready = !isLoading && order
+
+ const fulfillment = order?.fulfillments?.find((f) => f.id === f_id)
+
+ return (
+ <RouteFocusModal>
+ {ready && fulfillment && (
+ <OrderCreateShipmentForm
+ order={order}
+ fulfillment={fulfillment}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/constants.ts b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/constants.ts
new file mode 100644
index 000000000..984ef5239
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/constants.ts
@@ -0,0 +1,12 @@
+import { z } from "zod"
+
+export const CreateShipmentSchema = z.object({
+ labels: z.array(
+ z.object({
+ tracking_number: z.string(),
+ // TODO: this 2 are not optional in the API
+ tracking_url: z.string().optional(),
+ label_url: z.string().optional(),
+ })
+ ),
+})
diff --git a/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/index.ts b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/index.ts
new file mode 100644
index 000000000..65ec3c1d1
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/index.ts
@@ -0,0 +1 @@
+export * from "./order-create-shipment-form.tsx"
diff --git a/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/order-create-shipment-form.tsx b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/order-create-shipment-form.tsx
new file mode 100644
index 000000000..b96467065
--- /dev/null
+++ b/packages/vendor/src/pages/orders/[id]/shipment/order-create-shipment-form/order-create-shipment-form.tsx
@@ -0,0 +1,141 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Button, Heading, Input, toast } from "@medusajs/ui"
+import { useFieldArray, useForm } from "react-hook-form"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateOrderShipment } from "@hooks/api"
+import {
+ ExtendedAdminOrder,
+ ExtendedAdminOrderFulfillment,
+} from "@custom-types/order"
+import { CreateShipmentSchema } from "./constants"
+
+type OrderCreateFulfillmentFormProps = {
+ order: ExtendedAdminOrder
+ fulfillment: ExtendedAdminOrderFulfillment
+}
+
+export function OrderCreateShipmentForm({
+ order,
+ fulfillment,
+}: OrderCreateFulfillmentFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const { mutateAsync: createShipment, isPending: isMutating } =
+ useCreateOrderShipment(order.id, fulfillment?.id)
+
+ const form = useForm<zod.infer<typeof CreateShipmentSchema>>({
+ defaultValues: {},
+ resolver: zodResolver(CreateShipmentSchema),
+ })
+
+ const { fields: labels, append } = useFieldArray({
+ name: "labels",
+ control: form.control,
+ })
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await createShipment(
+ {
+ items:
+ fulfillment?.items
+ ?.map((i) => ({ id: i?.line_item_id, quantity: i.quantity }))
+ .filter((item) => !!item.id) ?? [],
+ labels: data.labels
+ .filter((l) => !!l.tracking_number)
+ .map((l) => ({
+ tracking_number: l.tracking_number,
+ tracking_url: "#",
+ label_url: "#"
+ ,
+ })),
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("orders.shipment.toastCreated"))
+ handleSuccess(`/orders/${order.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isMutating}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex h-full w-full flex-col items-center divide-y overflow-y-auto">
+ <div className="flex size-full flex-col items-center overflow-auto p-16">
+ <div className="flex w-full max-w-[736px] flex-col justify-center px-2 pb-2">
+ <div className="flex flex-col divide-y">
+ <div className="flex flex-1 flex-col">
+ <Heading className="mb-4">
+ {t("orders.shipment.title")}
+ </Heading>
+
+ {labels.map((label, index) => (
+ <Form.Field
+ key={label.id}
+ control={form.control}
+ name={`labels.${index}.tracking_number`}
+ render={({ field }) => {
+ return (
+ <Form.Item className="mb-4">
+ {index === 0 && (
+ <Form.Label>Tracking URL</Form.Label>
+ )}
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder="https://www.dhl.com/shipment/1234567890"
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ ))}
+
+ <Button
+ type="button"
+ onClick={() => append({ tracking_number: "" })}
+ className="self-end"
+ variant="secondary"
+ >
+ Add tracking URL
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/_components/index.ts b/packages/vendor/src/pages/orders/_components/index.ts
new file mode 100644
index 000000000..f65207073
--- /dev/null
+++ b/packages/vendor/src/pages/orders/_components/index.ts
@@ -0,0 +1 @@
+export * from "./order-list-table"
diff --git a/packages/vendor/src/pages/orders/_components/order-list-table/index.ts b/packages/vendor/src/pages/orders/_components/order-list-table/index.ts
new file mode 100644
index 000000000..f65207073
--- /dev/null
+++ b/packages/vendor/src/pages/orders/_components/order-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./order-list-table"
diff --git a/packages/vendor/src/pages/orders/_components/order-list-table/order-list-table.tsx b/packages/vendor/src/pages/orders/_components/order-list-table/order-list-table.tsx
new file mode 100644
index 000000000..07fca8a12
--- /dev/null
+++ b/packages/vendor/src/pages/orders/_components/order-list-table/order-list-table.tsx
@@ -0,0 +1,91 @@
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "@components/table/data-table/data-table"
+import { useOrders } from "@hooks/api/orders"
+import { useOrderTableColumns } from "@hooks/table/columns/use-order-table-columns"
+import { useOrderTableQuery } from "@hooks/table/query/use-order-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { useSearchParams } from "react-router-dom"
+import { useOrderTableFilters } from "@hooks/table/filters"
+
+const PAGE_SIZE = 10
+
+export const OrderListTable = () => {
+ const { t } = useTranslation()
+ const { raw, searchParams } = useOrderTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const [params] = useSearchParams()
+ const order_status = params.get("order_status") || ""
+
+ const { orders, count, isError, error, isLoading } = useOrders(
+ {
+ fields: "*customer,+payment_status,*split_order_payment",
+ },
+ undefined,
+ {
+ order_status,
+ created_at: searchParams.created_at,
+ updated_at: searchParams.updated_at,
+ sort: searchParams.order,
+ }
+ )
+
+ const offset = searchParams.offset || 0
+
+ const processedOrders = orders?.slice(offset, offset + PAGE_SIZE)
+ const processedCount = count < orders?.length ? count : orders?.length || 0
+
+ const columns = useOrderTableColumns({})
+ const filters = useOrderTableFilters()
+
+ const { table } = useDataTable({
+ data: processedOrders ?? [],
+ columns,
+ enablePagination: true,
+ count: processedCount,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("orders.domain")}</Heading>
+ </div>
+ <_DataTable
+ columns={columns}
+ table={table}
+ pagination
+ filters={filters}
+ navigateTo={(row) => `/orders/${row.original.id}`}
+ count={processedCount}
+ isLoading={isLoading}
+ pageSize={PAGE_SIZE}
+ orderBy={[
+ {
+ key: "display_id",
+ label: t("orders.fields.displayId"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ noRecords={{
+ message: t("orders.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/common/customerGroupFiltering.tsx b/packages/vendor/src/pages/orders/common/customerGroupFiltering.tsx
new file mode 100644
index 000000000..1f6633406
--- /dev/null
+++ b/packages/vendor/src/pages/orders/common/customerGroupFiltering.tsx
@@ -0,0 +1,115 @@
+import { HttpTypes } from "@medusajs/types"
+
+export type CustomerGroupData = {
+ customer_group_id: string
+ customer_group: HttpTypes.AdminCustomerGroup
+}
+
+type SortField = "name" | "created_at" | "updated_at"
+type SortDirection = "asc" | "desc"
+
+const getSymbol = (a: string | Date, symbol: string, b: string | Date) => {
+ const dateA = new Date(a)
+ const dateB = new Date(b)
+
+ switch (symbol) {
+ case "$gte":
+ return dateA >= dateB
+ case "$lte":
+ return dateA <= dateB
+ case "$gt":
+ return dateA > dateB
+ case "$lt":
+ return dateA < dateB
+ default:
+ return dateA.getTime() === dateB.getTime()
+ }
+}
+
+const isString = (value: unknown): value is string => {
+ return typeof value === "string"
+}
+
+const sortCustomerGroups = (
+ groups: CustomerGroupData[],
+ sortField: SortField,
+ direction: SortDirection
+) => {
+ return [...groups].sort((a, b) => {
+ if (!a.customer_group || !b.customer_group) return 0
+
+ const aValue = a.customer_group[sortField]
+ const bValue = b.customer_group[sortField]
+
+ if (sortField === "name" && isString(aValue) && isString(bValue)) {
+ return direction === "asc"
+ ? aValue.localeCompare(bValue)
+ : bValue.localeCompare(aValue)
+ }
+
+ // For dates (created_at and updated_at)
+ if (isString(aValue) && isString(bValue)) {
+ const dateA = new Date(aValue)
+ const dateB = new Date(bValue)
+ return direction === "asc"
+ ? dateA.getTime() - dateB.getTime()
+ : dateB.getTime() - dateA.getTime()
+ }
+
+ return 0
+ })
+}
+
+export const filterCustomerGroups = (
+ groups?: CustomerGroupData[] | undefined,
+ filters?: Record<string, Record<string, string | Date>>,
+ sort?: string
+) => {
+ if (!groups || !filters) return groups
+
+ let filteredGroups = groups.filter((group) => {
+ // Ensure the group has a customer_group property
+ if (!group.customer_group) return false
+
+ return Object.keys(filters).every((key) => {
+ if (!filters[key]) return true
+
+ // Type guard to ensure key is a valid SortField
+ if (!["name", "created_at", "updated_at"].includes(key)) return true
+
+ const groupValue = group.customer_group[key as SortField]
+ if (!groupValue) return false
+
+ if (key === "created_at" || key === "updated_at") {
+ if (!isString(groupValue)) return false
+ return Object.entries(filters[key]).every(([operator, value]) => {
+ return getSymbol(groupValue, operator, value as string)
+ })
+ }
+
+ if (key === "name") {
+ if (!isString(groupValue)) return false
+ const searchValue = Object.values(filters[key])[0] as string
+ return groupValue.toLowerCase().includes(searchValue.toLowerCase())
+ }
+
+ return true
+ })
+ })
+
+ if (sort) {
+ const isDescending = sort.startsWith("-")
+ const field = isDescending ? sort.slice(1) : sort
+ const direction = isDescending ? "desc" : "asc"
+
+ if (["name", "created_at", "updated_at"].includes(field)) {
+ filteredGroups = sortCustomerGroups(
+ filteredGroups,
+ field as SortField,
+ direction as SortDirection
+ )
+ }
+ }
+
+ return filteredGroups
+}
diff --git a/packages/vendor/src/pages/orders/common/orderFiltering.tsx b/packages/vendor/src/pages/orders/common/orderFiltering.tsx
new file mode 100644
index 000000000..79d187989
--- /dev/null
+++ b/packages/vendor/src/pages/orders/common/orderFiltering.tsx
@@ -0,0 +1,86 @@
+import { HttpTypes } from "@medusajs/types"
+
+const getSymbol = (a: string | Date, symbol: string, b: string | Date) => {
+ const dateA = new Date(a)
+ const dateB = new Date(b)
+
+ switch (symbol) {
+ case "$gte":
+ return dateA >= dateB
+ case "$lte":
+ return dateA <= dateB
+ case "$gt":
+ return dateA > dateB
+ case "$lt":
+ return dateA < dateB
+ default:
+ return dateA.getTime() === dateB.getTime()
+ }
+}
+
+type SortField = "display_id" | "created_at" | "updated_at"
+type SortDirection = "asc" | "desc"
+
+const sortOrders = (
+ orders: HttpTypes.AdminOrder[],
+ sortField: SortField,
+ direction: SortDirection
+) => {
+ return [...orders].sort((a, b) => {
+ const aValue = a[sortField]
+ const bValue = b[sortField]
+
+ if (sortField === "display_id") {
+ return direction === "asc"
+ ? Number(aValue) - Number(bValue)
+ : Number(bValue) - Number(aValue)
+ }
+
+ // For dates
+ const dateA = new Date(aValue as string)
+ const dateB = new Date(bValue as string)
+ return direction === "asc"
+ ? dateA.getTime() - dateB.getTime()
+ : dateB.getTime() - dateA.getTime()
+ })
+}
+
+export const filterOrders = (
+ orders?: HttpTypes.AdminOrder[],
+ filters?: Record<string, Record<string, string | Date>>,
+ sort?: string
+) => {
+ if (!orders || !filters) return orders
+
+ let filteredOrders = orders.filter((order) => {
+ return Object.keys(filters).every((key: string) => {
+ if (!filters[key]) return true
+
+ const orderValue = order[key as keyof HttpTypes.AdminOrder]
+
+ if (key === "created_at" || key === "updated_at") {
+ return Object.entries(filters[key]).every(([operator, value]) => {
+ return getSymbol(orderValue as string, operator, value as string)
+ })
+ }
+
+ return true
+ })
+ })
+
+ if (sort) {
+ const isDescending = sort.startsWith("-")
+ const field = isDescending ? sort.slice(1) : sort
+ const direction = isDescending ? "desc" : "asc"
+
+ if (["display_id", "created_at", "updated_at"].includes(field)) {
+ filteredOrders = sortOrders(
+ filteredOrders,
+ field as SortField,
+ direction as SortDirection
+ )
+ }
+ }
+
+ return filteredOrders
+}
diff --git a/packages/vendor/src/pages/orders/common/placeholders.tsx b/packages/vendor/src/pages/orders/common/placeholders.tsx
new file mode 100644
index 000000000..66aa6a95d
--- /dev/null
+++ b/packages/vendor/src/pages/orders/common/placeholders.tsx
@@ -0,0 +1,48 @@
+import { Trans, useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+export const ReturnShippingPlaceholder = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex h-[120px] flex-col items-center justify-center gap-2 p-2 text-center">
+ <span className="txt-small text-ui-fg-subtle font-medium">
+ {t("orders.returns.placeholders.noReturnShippingOptions.title")}
+ </span>
+
+ <span className="txt-small text-ui-fg-muted">
+ <Trans
+ i18nKey="orders.returns.placeholders.noReturnShippingOptions.hint"
+ components={{
+ LinkComponent: (
+ <Link to={`/settings/locations`} className="text-blue-500" />
+ ),
+ }}
+ />
+ </span>
+ </div>
+ )
+}
+
+export const OutboundShippingPlaceholder = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex h-[120px] flex-col items-center justify-center gap-2 p-2 text-center">
+ <span className="txt-small text-ui-fg-subtle font-medium">
+ {t("orders.returns.placeholders.outboundShippingOptions.title")}
+ </span>
+
+ <span className="txt-small text-ui-fg-muted">
+ <Trans
+ i18nKey="orders.returns.placeholders.outboundShippingOptions.hint"
+ components={{
+ LinkComponent: (
+ <Link to={`/settings/locations`} className="text-blue-500" />
+ ),
+ }}
+ />
+ </span>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/orders/index.tsx b/packages/vendor/src/pages/orders/index.tsx
new file mode 100644
index 000000000..458b9e5d7
--- /dev/null
+++ b/packages/vendor/src/pages/orders/index.tsx
@@ -0,0 +1,20 @@
+// Route: /orders
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { OrderListTable } from "./_components/order-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("order.list.after"),
+ before: getWidgets("order.list.before"),
+ }}
+ hasOutlet={false}
+ >
+ <OrderListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/index.ts
new file mode 100644
index 000000000..98a489def
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/index.ts
@@ -0,0 +1,3 @@
+export * from "./price-list-configuration-section"
+export * from "./price-list-general-section"
+export * from "./price-list-product-section"
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/index.ts
new file mode 100644
index 000000000..821418354
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-configuration-section"
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx
new file mode 100644
index 000000000..ec58ab59f
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-configuration-section/price-list-configuration-section.tsx
@@ -0,0 +1,99 @@
+import { PencilSquare } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { DateRangeDisplay } from "@components/common/date-range-display"
+import { ListSummary } from "@components/common/list-summary"
+import { Skeleton } from "@components/common/skeleton"
+import { useCustomerGroups } from "@hooks/api/customer-groups"
+
+type PriceListConfigurationSectionProps = {
+ priceList: HttpTypes.AdminPriceList
+}
+
+export const PriceListConfigurationSection = ({
+ priceList,
+}: PriceListConfigurationSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex flex-col gap-y-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <Heading level="h2">{t("priceLists.configuration.header")}</Heading>
+ <CustomerGroupDisplay priceList={priceList as any} />
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "configuration",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <DateRangeDisplay
+ endsAt={priceList.ends_at}
+ startsAt={priceList.starts_at}
+ showTime
+ />
+ </Container>
+ )
+}
+
+const CustomerGroupDisplay = ({
+ priceList,
+}: {
+ priceList: HttpTypes.AdminPriceList & { price_list_rules: any[] }
+}) => {
+ const { t } = useTranslation()
+
+ const customerGroupIds =
+ priceList.price_list_rules.find(
+ (rule) => rule.attribute === "customer.groups.id"
+ )?.value || ([] as string[])
+
+ const { customer_groups: customerGroupsData, isPending, isError, error } = useCustomerGroups(
+ undefined,
+ {
+ enabled: !!customerGroupIds?.length,
+ }
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ if (!customerGroupIds?.length) {
+ return null
+ }
+
+ if (isPending || !customerGroupsData) {
+ return <Skeleton className="h-5 w-full max-w-48" />
+ }
+
+ const flatCustomerGroups = customerGroupsData.map((item) => item.customer_group)
+
+ const filteredCustomerGroups = flatCustomerGroups
+ .filter((group) => customerGroupIds.includes(group.id))
+
+ return (
+ <div className="txt-small-plus text-ui-fg-muted flex items-center gap-x-1.5">
+ <span className="text-ui-fg-subtle">
+ {t("priceLists.fields.customerAvailability.attribute")}
+ </span>
+ <span>·</span>
+ <ListSummary
+ list={filteredCustomerGroups.map((group) => group.name!)}
+ n={1}
+ className="txt-small-plus text-ui-fg-muted"
+ />
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/index.ts
new file mode 100644
index 000000000..819714e0d
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-general-section"
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx
new file mode 100644
index 000000000..2cd781914
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-general-section/price-list-general-section.tsx
@@ -0,0 +1,86 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, StatusBadge, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeletePriceListAction } from "../../../common/hooks/use-delete-price-list-action"
+import { getPriceListStatus } from "../../../common/utils"
+
+type PriceListGeneralSectionProps = {
+ priceList: HttpTypes.AdminPriceList
+}
+
+export const PriceListGeneralSection = ({
+ priceList,
+}: PriceListGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const overrideCount = priceList.prices?.length || 0
+
+ const { color, text } = getPriceListStatus(t, priceList)
+
+ const handleDelete = useDeletePriceListAction({ priceList })
+
+ const type =
+ priceList.type === "sale"
+ ? t("priceLists.fields.type.options.sale.label")
+ : t("priceLists.fields.type.options.override.label")
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{priceList.title}</Heading>
+ <div className="flex items-center gap-x-4">
+ <StatusBadge color={color}>{text}</StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "edit",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text leading="compact" size="small" weight="plus">
+ {t("fields.type")}
+ </Text>
+ <Text size="small" className="text-pretty">
+ {type}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text leading="compact" size="small" weight="plus">
+ {t("fields.description")}
+ </Text>
+ <Text size="small" className="text-pretty">
+ {priceList.description}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text leading="compact" size="small" weight="plus">
+ {t("priceLists.fields.priceOverrides.label")}
+ </Text>
+ <Text size="small" className="text-pretty">
+ {overrideCount || "-"}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/index.ts b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/index.ts
new file mode 100644
index 000000000..1dc742026
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-product-section"
diff --git a/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx
new file mode 100644
index 000000000..3968d1510
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/_components/price-list-product-section/price-list-product-section.tsx
@@ -0,0 +1,218 @@
+import { PencilSquare, Plus, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import {
+ usePriceListLinkProducts,
+ usePriceListProducts,
+} from "@hooks/api/price-lists"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type PriceListProductSectionProps = {
+ priceList: HttpTypes.AdminPriceList
+}
+
+const PAGE_SIZE = 10
+const PREFIX = "p"
+
+export const PriceListProductSection = ({
+ priceList,
+}: PriceListProductSectionProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { products, count, isLoading, isError, error } = usePriceListProducts(
+ priceList.id,
+ {
+ limit: searchParams.limit?.toString() ?? PAGE_SIZE,
+ offset: searchParams.offset?.toString() ?? 0,
+ }
+ )
+
+ const columns = useColumns(priceList)
+
+ const { table } = useDataTable({
+ data: products || [],
+ count,
+ columns,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("priceLists.products.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("priceLists.products.actions.addProducts"),
+ to: "products/add",
+ icon: <Plus />,
+ },
+ {
+ label: t("priceLists.products.actions.editPrices"),
+ to: "products/edit",
+ icon: <PencilSquare />,
+ disabled: count === 0,
+ disabledTooltip: t("priceLists.products.actions.editPricesDisabled"),
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ navigateTo={(row) => `/products/${row.original.id}`}
+ pagination
+ prefix={PREFIX}
+ queryObject={raw}
+ />
+ </Container>
+ )
+}
+
+const ProductRowAction = ({
+ product,
+ priceList,
+}: {
+ product: ExtendedAdminProduct
+ priceList: HttpTypes.AdminPriceList
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = usePriceListLinkProducts(priceList.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("priceLists.products.delete.confirmation", {
+ count: 1,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ mutateAsync(
+ {
+ remove: [product.id],
+ },
+ {
+ onSuccess: () => {
+ toast.success("Product removed from price list")
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("priceLists.products.actions.editPrices"),
+ to: `products/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.remove"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = (priceList: HttpTypes.AdminPriceList) => {
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => (
+ <ProductRowAction product={row.original} priceList={priceList} />
+ ),
+ }),
+ ],
+ [base, priceList]
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx b/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx
new file mode 100644
index 000000000..81bba2c07
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/configuration/index.tsx
@@ -0,0 +1,68 @@
+// Route: /price-lists/:id/configuration
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCustomerGroups } from "@hooks/api/customer-groups"
+import { usePriceList } from "@hooks/api/price-lists"
+import { PriceListConfigurationForm } from "./price-list-configuration-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+
+ const { price_list, isPending, isError, error } = usePriceList(id!)
+
+ const customerGroupIds =
+ price_list?.price_list_rules?.find(
+ (rule: any) => rule.attribute === "customer.groups.id"
+ )?.value || ([] as string[])
+
+ const {
+ customer_groups: customerGroupsData,
+ isPending: isCustomerGroupsPending,
+ isError: isCustomerGroupsError,
+ error: customerGroupsError,
+ } = useCustomerGroups(undefined, { enabled: !!customerGroupIds?.length })
+
+ const customerGroups = customerGroupsData?.map((item) => item.customer_group)
+
+ const initialCustomerGroups = (customerGroups || []).filter((group) =>
+ customerGroupIds.includes(group.id)
+ )
+
+ const isCustomerGroupsReady = isPending
+ ? false
+ : !!customerGroupIds?.length && isCustomerGroupsPending
+ ? false
+ : true
+
+ const ready = !isPending && !!price_list && isCustomerGroupsReady
+
+ if (isError) {
+ throw error
+ }
+
+ if (isCustomerGroupsError) {
+ throw customerGroupsError
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("priceLists.configuration.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+ {ready && (
+ <PriceListConfigurationForm
+ priceList={price_list}
+ customerGroups={initialCustomerGroups.map((group) => ({
+ id: group.id,
+ name: group.name || "",
+ }))}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/index.ts b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/index.ts
new file mode 100644
index 000000000..9f16da0fb
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-configuration-form"
diff --git a/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx
new file mode 100644
index 000000000..d507f1507
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/configuration/price-list-configuration-form/price-list-configuration-form.tsx
@@ -0,0 +1,311 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { MagnifyingGlass, XMark } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Button,
+ DatePicker,
+ Divider,
+ Heading,
+ IconButton,
+ Text,
+ clx,
+ toast,
+} from "@medusajs/ui"
+import { useFieldArray, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { StackedDrawer } from "@components/modals/stacked-drawer"
+import { useStackedModal } from "@components/modals/stacked-modal-provider"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdatePriceList } from "@hooks/api/price-lists"
+import { PriceListCustomerGroupRuleForm } from "../../../common/components/price-list-customer-group-rule-form"
+import { PricingCustomerGroupsArrayType } from "../../../price-list-create/components/price-list-create-form/schema"
+
+type PriceListConfigurationFormProps = {
+ priceList: HttpTypes.AdminPriceList
+ customerGroups: { id: string; name: string }[]
+}
+
+const PriceListConfigurationSchema = z.object({
+ ends_at: z.date().nullable(),
+ starts_at: z.date().nullable(),
+ customer_group_id: z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ })
+ ),
+})
+
+const STACKED_MODAL_ID = "cg"
+
+export const PriceListConfigurationForm = ({
+ priceList,
+ customerGroups,
+}: PriceListConfigurationFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { setIsOpen } = useStackedModal()
+
+ const form = useForm<z.infer<typeof PriceListConfigurationSchema>>({
+ defaultValues: {
+ ends_at: priceList.ends_at ? new Date(priceList.ends_at) : null,
+ starts_at: priceList.starts_at ? new Date(priceList.starts_at) : null,
+ customer_group_id: customerGroups,
+ },
+ resolver: zodResolver(PriceListConfigurationSchema),
+ })
+
+ const { fields, remove, append } = useFieldArray({
+ control: form.control,
+ name: "customer_group_id",
+ keyName: "cg_id",
+ })
+
+ const handleAddCustomerGroup = (groups: PricingCustomerGroupsArrayType) => {
+ if (!groups.length) {
+ form.setValue("customer_group_id", [])
+ setIsOpen(STACKED_MODAL_ID, false)
+ return
+ }
+
+ const newIds = groups.map((group) => group.id)
+
+ const fieldsToAdd = groups.filter(
+ (group) => !fields.some((field) => field.id === group.id)
+ )
+
+ for (const field of fields) {
+ if (!newIds.includes(field.id)) {
+ remove(fields.indexOf(field))
+ }
+ }
+
+ append(fieldsToAdd)
+ setIsOpen(STACKED_MODAL_ID, false)
+ }
+
+ const { mutateAsync } = useUpdatePriceList(priceList.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const groupIds = values.customer_group_id.map((group) => group.id)
+ const rules = { ...priceList.rules } // preserve other rules set on the PL
+
+ if (groupIds.length) {
+ rules["customer.groups.id"] = groupIds
+ } else {
+ delete rules["customer.groups.id"]
+ }
+
+ await mutateAsync(
+ {
+ starts_at: values.starts_at?.toISOString() || null,
+ ends_at: values.ends_at?.toISOString() || null,
+ rules: rules,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("priceLists.configuration.edit.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => toast.error(error.message),
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <RouteDrawer.Description className="sr-only">
+ {t("priceLists.configuration.edit.description")}
+ </RouteDrawer.Description>
+ <KeyboundForm
+ className="flex flex-1 flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="starts_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-1 gap-3">
+ <div className="flex flex-col">
+ <Form.Label optional>
+ {t("priceLists.fields.startsAt.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("priceLists.fields.startsAt.hint")}
+ </Form.Hint>
+ </div>
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="ends_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-1 gap-3">
+ <div className="flex flex-col">
+ <Form.Label optional>
+ {t("priceLists.fields.endsAt.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("priceLists.fields.endsAt.hint")}
+ </Form.Hint>
+ </div>
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="customer_group_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div>
+ <Form.Label optional>
+ {t("priceLists.fields.customerAvailability.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("priceLists.fields.customerAvailability.hint")}
+ </Form.Hint>
+ </div>
+ <Form.Control>
+ <div
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
+ "aria-[invalid='true']:shadow-borders-error"
+ )}
+ role="application"
+ ref={field.ref}
+ >
+ <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t(
+ "priceLists.fields.customerAvailability.attribute"
+ )}
+ </div>
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t("operators.in")}
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-1.5">
+ <StackedDrawer id={STACKED_MODAL_ID}>
+ <StackedDrawer.Trigger asChild>
+ <button
+ type="button"
+ className="bg-ui-bg-field shadow-borders-base txt-compact-small text-ui-fg-muted flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5"
+ >
+ <MagnifyingGlass />
+ {t(
+ "priceLists.fields.customerAvailability.placeholder"
+ )}
+ </button>
+ </StackedDrawer.Trigger>
+ <StackedDrawer.Trigger asChild>
+ <Button variant="secondary">
+ {t("actions.browse")}
+ </Button>
+ </StackedDrawer.Trigger>
+ <StackedDrawer.Content>
+ <StackedDrawer.Header>
+ <StackedDrawer.Title asChild>
+ <Heading>
+ {t(
+ "priceLists.fields.customerAvailability.header"
+ )}
+ </Heading>
+ </StackedDrawer.Title>
+ <StackedDrawer.Description className="sr-only">
+ {t(
+ "priceLists.fields.customerAvailability.hint"
+ )}
+ </StackedDrawer.Description>
+ </StackedDrawer.Header>
+ <PriceListCustomerGroupRuleForm
+ type="drawer"
+ setState={handleAddCustomerGroup}
+ state={fields}
+ />
+ </StackedDrawer.Content>
+ </StackedDrawer>
+ </div>
+ {fields.length > 0 ? (
+ <div className="flex flex-col gap-y-1.5">
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-1.5 px-1.5">
+ {fields.map((field, index) => {
+ return (
+ <div
+ key={field.cg_id}
+ className="bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5"
+ >
+ <Text size="small" leading="compact">
+ {field.name}
+ </Text>
+ <IconButton
+ size="small"
+ variant="transparent"
+ type="button"
+ onClick={() => remove(index)}
+ >
+ <XMark />
+ </IconButton>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer className="shrink-0">
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit">
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/edit/index.tsx b/packages/vendor/src/pages/price-lists/[id]/edit/index.tsx
new file mode 100644
index 000000000..3ca7d2382
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/edit/index.tsx
@@ -0,0 +1,29 @@
+// Route: /price-lists/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { usePriceList } from "@hooks/api/price-lists"
+import { PriceListEditForm } from "./price-list-edit-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+
+ const { price_list, isLoading, isError, error } = usePriceList(id!)
+
+ const ready = !isLoading && price_list
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("priceLists.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <PriceListEditForm priceList={price_list} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsx b/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsx
new file mode 100644
index 000000000..74f6fc20c
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/edit-price-list-form.tsx
@@ -0,0 +1,184 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Button,
+ Input,
+ RadioGroup,
+ Select,
+ Textarea,
+ toast,
+} from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdatePriceList } from "@hooks/api/price-lists"
+import { PriceListStatus, PriceListType } from "../../../common/constants"
+
+type PriceListEditFormProps = {
+ priceList: HttpTypes.AdminPriceList
+}
+
+const PriceListEditSchema = z.object({
+ status: z.nativeEnum(PriceListStatus),
+ type: z.nativeEnum(PriceListType),
+ title: z.string().min(1),
+ description: z.string().min(1),
+})
+
+export const PriceListEditForm = ({ priceList }: PriceListEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof PriceListEditSchema>>({
+ defaultValues: {
+ type: priceList.type as PriceListType,
+ title: priceList.title,
+ description: priceList.description,
+ status: priceList.status as PriceListStatus,
+ },
+ resolver: zodResolver(PriceListEditSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdatePriceList(priceList.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(values, {
+ onSuccess: ({ price_list }) => {
+ toast.success(
+ t("priceLists.edit.successToast", {
+ title: price_list.title,
+ })
+ )
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ className="flex flex-1 flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field: { onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div>
+ <Form.Label>{t("priceLists.fields.type.label")}</Form.Label>
+ <Form.Hint>{t("priceLists.fields.type.hint")}</Form.Hint>
+ </div>
+ <Form.Control>
+ <RadioGroup {...field} onValueChange={onChange}>
+ <RadioGroup.ChoiceBox
+ value={PriceListType.SALE}
+ label={t("priceLists.fields.type.options.sale.label")}
+ description={t(
+ "priceLists.fields.type.options.sale.description"
+ )}
+ />
+ <RadioGroup.ChoiceBox
+ value={PriceListType.OVERRIDE}
+ label={t(
+ "priceLists.fields.type.options.override.label"
+ )}
+ description={t(
+ "priceLists.fields.type.options.override.description"
+ )}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("priceLists.fields.status.label")}
+ </Form.Label>
+ <Form.Control>
+ <Select {...field} onValueChange={onChange}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value={PriceListStatus.ACTIVE}>
+ {t("priceLists.fields.status.options.active")}
+ </Select.Item>
+ <Select.Item value={PriceListStatus.DRAFT}>
+ {t("priceLists.fields.status.options.draft")}
+ </Select.Item>
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.description")}</Form.Label>
+ <Form.Control>
+ <Textarea {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer className="shrink-0">
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/index.ts b/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/index.ts
new file mode 100644
index 000000000..23de2b193
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/edit/price-list-edit-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-price-list-form"
diff --git a/packages/vendor/src/pages/price-lists/[id]/index.tsx b/packages/vendor/src/pages/price-lists/[id]/index.tsx
new file mode 100644
index 000000000..107a0405f
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/index.tsx
@@ -0,0 +1,83 @@
+// Route: /price-lists/:id
+import { useParams, LoaderFunctionArgs } from "react-router-dom"
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { usePriceList, priceListsQueryKeys } from "@hooks/api/price-lists"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { PriceListConfigurationSection } from "./_components/price-list-configuration-section"
+import { PriceListGeneralSection } from "./_components/price-list-general-section"
+import { PriceListProductSection } from "./_components/price-list-product-section"
+
+const pricingDetailQuery = (id: string) => ({
+ queryKey: priceListsQueryKeys.detail(id),
+ queryFn: async () =>
+ await fetchQuery(`/vendor/price-lists/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = pricingDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
+
+type PriceListDetailBreadcrumbProps = UIMatch<HttpTypes.AdminPriceListResponse>
+
+export const Breadcrumb = (props: PriceListDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { price_list } = usePriceList(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!price_list) {
+ return null
+ }
+
+ return <span>{price_list.title}</span>
+}
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { price_list, isLoading, isError, error } = usePriceList(id!)
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !price_list) {
+ return (
+ <TwoColumnPageSkeleton mainSections={2} sidebarSections={1} showJSON />
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("price_list.details.after"),
+ before: getWidgets("price_list.details.before"),
+ sideAfter: getWidgets("price_list.details.side.after"),
+ sideBefore: getWidgets("price_list.details.side.before"),
+ }}
+ data={price_list}
+ >
+ <TwoColumnPage.Main>
+ <PriceListGeneralSection priceList={price_list} />
+ <PriceListProductSection priceList={price_list} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <PriceListConfigurationSection priceList={price_list} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx
new file mode 100644
index 000000000..5d860b580
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/index.tsx
@@ -0,0 +1,53 @@
+// Route: /price-lists/:id/products/:variant_id/edit
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { usePriceList, usePriceListProducts } from "@hooks/api/price-lists"
+import { usePriceListCurrencyData } from "../../../../common/hooks/use-price-list-currency-data"
+import { PriceListPricesEditForm } from "./price-list-prices-edit-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { price_list, isLoading, isError, error } = usePriceList(id!)
+
+ const {
+ products,
+ isLoading: isProductsLoading,
+ isError: isProductsError,
+ error: productError,
+ } = usePriceListProducts(id!)
+
+ const priceListCurrencyData = usePriceListCurrencyData()
+
+ const ready =
+ !isLoading &&
+ !!price_list &&
+ !isProductsLoading &&
+ !!products &&
+ priceListCurrencyData.isReady
+
+ if (isError) {
+ throw error
+ }
+
+ if (isProductsError) {
+ throw productError
+ }
+
+ return (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">Edit Prices for {price_list?.title}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description className="sr-only">
+ Update prices for products in the price list
+ </RouteFocusModal.Description>
+ {ready && (
+ <PriceListPricesEditForm
+ priceList={price_list}
+ products={products}
+ {...priceListCurrencyData}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/index.ts b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/index.ts
new file mode 100644
index 000000000..7a562f1a7
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-prices-edit-form"
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx
new file mode 100644
index 000000000..459ae9858
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/[variant_id]/edit/price-list-prices-edit-form/price-list-prices-edit-form.tsx
@@ -0,0 +1,328 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, toast } from "@medusajs/ui"
+import { useRef } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { DataGrid } from "@components/data-grid"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { usePriceListLinkProducts } from "@hooks/api/price-lists"
+import { castNumber } from "@lib/cast-number"
+import { usePriceListGridColumns } from "@pages/price-lists/common/hooks/use-price-list-grid-columns"
+import {
+ PriceListUpdateProductVariantsSchema,
+ PriceListUpdateProductsSchema,
+} from "@pages/price-lists/common/schemas"
+import { isProductRow } from "@pages/price-lists/common/utils"
+import { ExtendedPriceList } from "@custom-types/price-list"
+
+type PriceListPricesEditFormProps = {
+ priceList: ExtendedPriceList
+ products: ExtendedAdminProduct[]
+ regions: HttpTypes.AdminRegion[]
+ currencies: HttpTypes.AdminStoreCurrency[]
+ pricePreferences: HttpTypes.AdminPricePreference[]
+}
+
+const PricingProductPricesSchema = z.object({
+ products: PriceListUpdateProductsSchema,
+})
+
+export const PriceListPricesEditForm = ({
+ priceList,
+ products,
+ regions,
+ currencies,
+ pricePreferences,
+}: PriceListPricesEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess, setCloseOnEscape } = useRouteModal()
+
+ const initialValue = useRef(initRecord(priceList, products))
+
+ const form = useForm<z.infer<typeof PricingProductPricesSchema>>({
+ defaultValues: {
+ products: initialValue.current,
+ },
+ // resolver: zodResolver(PricingProductPricesSchema),
+ })
+
+ const { mutateAsync, isPending } = usePriceListLinkProducts(priceList.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const { products } = values
+
+ const { pricesToDelete, pricesToCreate, pricesToUpdate } = sortPrices(
+ products,
+ initialValue.current,
+ regions
+ )
+
+ mutateAsync(
+ {
+ remove: pricesToDelete,
+ update: pricesToUpdate,
+ create: pricesToCreate,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("priceLists.products.edit.successToast"))
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const columns = usePriceListGridColumns({
+ currencies,
+ regions,
+ pricePreferences,
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex size-full flex-col">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-col overflow-hidden">
+ <DataGrid
+ columns={columns}
+ data={products}
+ getSubRows={(row) => {
+ if (isProductRow(row) && row.variants) {
+ return row.variants
+ }
+ }}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+function initRecord(
+ priceList: ExtendedPriceList,
+ products: ExtendedAdminProduct[]
+): PriceListUpdateProductsSchema {
+ const record: PriceListUpdateProductsSchema = {}
+
+ const variantPrices = priceList.prices?.reduce((variants, price) => {
+ const variantObject = variants[price.price_set.variant.id] || {}
+
+ const regionPrice = price.price_rules.find(
+ (item: { attribute: string }) => item.attribute === "region_id"
+ )
+
+ if (!!regionPrice) {
+ const regionId = regionPrice.value
+
+ variantObject.region_prices = {
+ ...variantObject.region_prices,
+ [regionId]: {
+ amount: price.amount.toString(),
+ id: price.id,
+ },
+ }
+ } else {
+ variantObject.currency_prices = {
+ ...variantObject.currency_prices,
+ [price.currency_code]: {
+ amount: price.amount.toString(),
+ id: price.id,
+ },
+ }
+ }
+
+ const variantId = price.price_set.variant.id
+
+ variants[variantId] = variantObject
+
+ return variants
+ }, {} as PriceListUpdateProductVariantsSchema)
+
+ for (const product of products) {
+ record[product.id] = {
+ variants:
+ product.variants?.reduce((variants, variant) => {
+ const prices = variantPrices?.[variant.id] || {}
+ variants[variant.id] = prices
+
+ return variants
+ }, {} as PriceListUpdateProductVariantsSchema) || {},
+ }
+ }
+
+ return record
+}
+
+type PriceObject = {
+ variantId: string
+ currencyCode: string
+ regionId?: string
+ amount: number
+ id?: string | null
+}
+
+function convertToPriceArray(
+ data: PriceListUpdateProductsSchema,
+ regions: HttpTypes.AdminRegion[]
+) {
+ const prices: PriceObject[] = []
+
+ const regionCurrencyMap = regions.reduce(
+ (map, region) => {
+ map[region.id] = region.currency_code
+ return map
+ },
+ {} as Record<string, string>
+ )
+
+ for (const [_productId, product] of Object.entries(data || {})) {
+ const { variants } = product || {}
+
+ for (const [variantId, variant] of Object.entries(variants || {})) {
+ const { currency_prices: currencyPrices, region_prices: regionPrices } =
+ variant || {}
+
+ for (const [currencyCode, currencyPrice] of Object.entries(
+ currencyPrices || {}
+ )) {
+ if (
+ currencyPrice?.amount !== "" &&
+ typeof currencyPrice?.amount !== "undefined"
+ ) {
+ prices.push({
+ variantId,
+ currencyCode,
+ amount: castNumber(currencyPrice.amount),
+ id: currencyPrice.id,
+ })
+ }
+ }
+
+ for (const [regionId, regionPrice] of Object.entries(
+ regionPrices || {}
+ )) {
+ if (
+ regionPrice?.amount !== "" &&
+ typeof regionPrice?.amount !== "undefined"
+ ) {
+ prices.push({
+ variantId,
+ regionId,
+ currencyCode: regionCurrencyMap[regionId],
+ amount: castNumber(regionPrice.amount),
+ id: regionPrice.id,
+ })
+ }
+ }
+ }
+ }
+
+ return prices
+}
+
+function createMapKey(obj: PriceObject) {
+ return `${obj.variantId}-${obj.currencyCode}-${obj.regionId || "none"}-${
+ obj.id || "none"
+ }`
+}
+
+function comparePrices(initialPrices: PriceObject[], newPrices: PriceObject[]) {
+ const pricesToUpdate: HttpTypes.AdminUpdatePriceListPrice[] = []
+ const pricesToCreate: HttpTypes.AdminCreatePriceListPrice[] = []
+ const pricesToDelete: string[] = []
+
+ const initialPriceMap = initialPrices.reduce(
+ (map, price) => {
+ map[createMapKey(price)] = price
+ return map
+ },
+ {} as Record<string, (typeof initialPrices)[0]>
+ )
+
+ const newPriceMap = newPrices.reduce(
+ (map, price) => {
+ map[createMapKey(price)] = price
+ return map
+ },
+ {} as Record<string, (typeof newPrices)[0]>
+ )
+
+ const keys = new Set([
+ ...Object.keys(initialPriceMap),
+ ...Object.keys(newPriceMap),
+ ])
+
+ for (const key of keys) {
+ const initialPrice = initialPriceMap[key]
+ const newPrice = newPriceMap[key]
+
+ if (initialPrice && newPrice) {
+ if (isNaN(newPrice.amount) && newPrice.id) {
+ pricesToDelete.push(newPrice.id)
+ }
+
+ if (initialPrice.amount !== newPrice.amount && newPrice.id) {
+ pricesToUpdate.push({
+ id: newPrice.id,
+ variant_id: newPrice.variantId,
+ currency_code: newPrice.currencyCode,
+ rules: newPrice.regionId
+ ? { region_id: newPrice.regionId }
+ : undefined,
+ amount: newPrice.amount,
+ })
+ }
+ }
+
+ if (!initialPrice && newPrice) {
+ pricesToCreate.push({
+ variant_id: newPrice.variantId,
+ currency_code: newPrice.currencyCode,
+ rules: newPrice.regionId ? { region_id: newPrice.regionId } : undefined,
+ amount: newPrice.amount,
+ })
+ }
+
+ if (initialPrice && !newPrice && initialPrice.id) {
+ pricesToDelete.push(initialPrice.id)
+ }
+ }
+
+ return { pricesToDelete, pricesToCreate, pricesToUpdate }
+}
+
+function sortPrices(
+ data: PriceListUpdateProductsSchema,
+ initialValue: PriceListUpdateProductsSchema,
+ regions: HttpTypes.AdminRegion[]
+) {
+ const initialPrices = convertToPriceArray(initialValue, regions)
+ const newPrices = convertToPriceArray(data, regions)
+
+ return comparePrices(initialPrices, newPrices)
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/index.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/index.tsx
new file mode 100644
index 000000000..8a74acc2c
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/index.tsx
@@ -0,0 +1,27 @@
+// Route: /price-lists/:id/products/add
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { usePriceList } from "@hooks/api/price-lists"
+import { usePriceListCurrencyData } from "../../../common/hooks/use-price-list-currency-data"
+import { PriceListPricesAddForm } from "./price-list-prices-add-form"
+
+export const Component = () => {
+ const { id } = useParams<{ id: string }>()
+
+ const { price_list, isPending, isError, error } = usePriceList(id!)
+ const currencyData = usePriceListCurrencyData()
+
+ const ready = currencyData.isReady && !isPending && !!price_list
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && (
+ <PriceListPricesAddForm priceList={price_list} {...currencyData} />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/index.ts b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/index.ts
new file mode 100644
index 000000000..cbc89a9e2
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-prices-add-form"
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx
new file mode 100644
index 000000000..c93b98553
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-form.tsx
@@ -0,0 +1,315 @@
+import { useState } from 'react';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import { HttpTypes } from '@medusajs/types';
+import { Button, ProgressStatus, ProgressTabs, toast } from '@medusajs/ui';
+import { FieldPath, useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+import { z } from 'zod';
+
+import { RouteFocusModal, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { usePriceListLinkProducts } from "@hooks/api/price-lists"
+import { exctractPricesFromProducts } from "../../../../common/utils"
+import { PriceListPricesAddPricesForm } from './price-list-prices-add-prices-form';
+import { PriceListPricesAddProductIdsForm } from './price-list-prices-add-product-ids-form';
+import {
+ PriceListPricesAddProductIdsSchema,
+ PriceListPricesAddProductsFields,
+ PriceListPricesAddProductsIdsFields,
+ PriceListPricesAddSchema
+} from './schema';
+
+type PriceListPricesAddFormProps = {
+ priceList: HttpTypes.AdminPriceList;
+ currencies: HttpTypes.AdminStoreCurrency[];
+ regions: HttpTypes.AdminRegion[];
+ pricePreferences: HttpTypes.AdminPricePreference[];
+};
+
+enum Tab {
+ PRODUCT = 'product',
+ PRICE = 'price'
+}
+
+const tabOrder = [Tab.PRODUCT, Tab.PRICE] as const;
+
+type TabState = Record<Tab, ProgressStatus>;
+
+const initialTabState: TabState = {
+ [Tab.PRODUCT]: 'in-progress',
+ [Tab.PRICE]: 'not-started'
+};
+
+export const PriceListPricesAddForm = ({
+ priceList,
+ regions,
+ currencies,
+ pricePreferences
+}: PriceListPricesAddFormProps) => {
+ const [tab, setTab] = useState<Tab>(Tab.PRODUCT);
+ const [tabState, setTabState] = useState<TabState>(initialTabState);
+
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+
+ const form = useForm<PriceListPricesAddSchema>({
+ defaultValues: {
+ products: {},
+ product_ids: []
+ },
+ resolver: zodResolver(PriceListPricesAddSchema)
+ });
+
+ const { mutateAsync, isPending } = usePriceListLinkProducts(priceList.id);
+ // const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id)
+
+ const handleSubmit = form.handleSubmit(
+ async values => {
+ const { products } = values;
+
+ const prices = exctractPricesFromProducts(products, regions);
+
+ await mutateAsync(
+ {
+ create: prices
+ },
+ {
+ onSuccess: () => {
+ toast.success(t('priceLists.products.add.successToast'));
+ handleSuccess();
+ },
+ onError: e => toast.error(e.message)
+ }
+ );
+ },
+ errors => {
+ if (errors.products) {
+ toast.error('At least one price must be added.');
+ }
+ }
+ );
+
+ const partialFormValidation = (
+ fields: FieldPath<PriceListPricesAddSchema>[],
+ schema: z.ZodSchema<any>
+ ) => {
+ form.clearErrors(fields);
+
+ const values = fields.reduce(
+ (acc, key) => {
+ acc[key] = form.getValues(key);
+ return acc;
+ },
+ {} as Record<string, unknown>
+ );
+
+ const validationResult = schema.safeParse(values);
+
+ if (!validationResult.success) {
+ validationResult.error.errors.forEach(({ path, message, code }) => {
+ form.setError(path.join('.') as keyof PriceListPricesAddSchema, {
+ type: code,
+ message
+ });
+ });
+
+ return false;
+ }
+
+ return true;
+ };
+
+ const isTabDirty = (tab: Tab) => {
+ switch (tab) {
+ case Tab.PRODUCT: {
+ const fields = PriceListPricesAddProductsIdsFields;
+
+ return fields.some(field => {
+ return form.getFieldState(field).isDirty;
+ });
+ }
+ case Tab.PRICE: {
+ const fields = PriceListPricesAddProductsFields;
+
+ return fields.some(field => {
+ return form.getFieldState(field).isDirty;
+ });
+ }
+ }
+ };
+
+ const handleChangeTab = (update: Tab) => {
+ if (tab === update) {
+ return;
+ }
+
+ if (tabOrder.indexOf(update) < tabOrder.indexOf(tab)) {
+ const isCurrentTabDirty = isTabDirty(tab);
+
+ setTabState(prev => ({
+ ...prev,
+ [tab]: isCurrentTabDirty ? prev[tab] : 'not-started',
+ [update]: 'in-progress'
+ }));
+
+ setTab(update);
+ return;
+ }
+
+ // get the tabs from the current tab to the update tab including the current tab
+ const tabs = tabOrder.slice(0, tabOrder.indexOf(update));
+
+ // validate all the tabs from the current tab to the update tab if it fails on any of tabs then set that tab as current tab
+ for (const tab of tabs) {
+ if (tab === Tab.PRODUCT) {
+ if (
+ !partialFormValidation(
+ PriceListPricesAddProductsIdsFields,
+ PriceListPricesAddProductIdsSchema
+ )
+ ) {
+ setTabState(prev => ({
+ ...prev,
+ [tab]: 'in-progress'
+ }));
+ setTab(tab);
+
+ return;
+ }
+
+ setTabState(prev => ({
+ ...prev,
+ [tab]: 'completed'
+ }));
+ }
+ }
+
+ setTabState(prev => ({
+ ...prev,
+ [tab]: 'completed',
+ [update]: 'in-progress'
+ }));
+ setTab(update);
+ };
+
+ const handleNextTab = (tab: Tab) => {
+ if (tabOrder.indexOf(tab) + 1 >= tabOrder.length) {
+ return;
+ }
+
+ const nextTab = tabOrder[tabOrder.indexOf(tab) + 1];
+ handleChangeTab(nextTab);
+ };
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <ProgressTabs
+ value={tab}
+ onValueChange={tab => handleChangeTab(tab as Tab)}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex w-full items-center justify-between gap-x-4">
+ <div className="-my-2 w-full max-w-[600px] border-l">
+ <ProgressTabs.List className="grid w-full grid-cols-3">
+ <ProgressTabs.Trigger
+ status={tabState.product}
+ value={Tab.PRODUCT}
+ >
+ {t('priceLists.create.tabs.products')}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState.price}
+ value={Tab.PRICE}
+ >
+ {t('priceLists.create.tabs.prices')}
+ </ProgressTabs.Trigger>
+ </ProgressTabs.List>
+ </div>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.PRODUCT}
+ >
+ <PriceListPricesAddProductIdsForm
+ form={form}
+ priceList={priceList}
+ />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-hidden"
+ value={Tab.PRICE}
+ >
+ <PriceListPricesAddPricesForm
+ form={form}
+ regions={regions}
+ currencies={currencies}
+ pricePreferences={pricePreferences}
+ />
+ </ProgressTabs.Content>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button
+ variant="secondary"
+ size="small"
+ >
+ {t('actions.cancel')}
+ </Button>
+ </RouteFocusModal.Close>
+ <PrimaryButton
+ tab={tab}
+ next={handleNextTab}
+ isLoading={isPending}
+ />
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </ProgressTabs>
+ </RouteFocusModal.Form>
+ );
+};
+
+type PrimaryButtonProps = {
+ tab: Tab;
+ next: (tab: Tab) => void;
+ isLoading?: boolean;
+};
+
+const PrimaryButton = ({ tab, next, isLoading }: PrimaryButtonProps) => {
+ const { t } = useTranslation();
+
+ if (tab === Tab.PRICE) {
+ return (
+ <Button
+ key="submit-button"
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isLoading}
+ >
+ {t('actions.save')}
+ </Button>
+ );
+ }
+
+ return (
+ <Button
+ key="next-button"
+ type="button"
+ variant="primary"
+ size="small"
+ onClick={() => next(tab)}
+ >
+ {t('actions.continue')}
+ </Button>
+ );
+};
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
new file mode 100644
index 000000000..965115aaf
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
@@ -0,0 +1,102 @@
+import { useEffect } from 'react';
+
+import { HttpTypes } from '@medusajs/types';
+import { UseFormReturn, useWatch } from 'react-hook-form';
+
+import { DataGrid } from "@components/data-grid"
+import { useRouteModal } from "@components/modals"
+import { useProducts } from "@hooks/api/products"
+import { usePriceListGridColumns } from "../../../../common/hooks/use-price-list-grid-columns"
+import { PriceListCreateProductVariantsSchema } from "../../../../common/schemas"
+import { isProductRow } from "../../../../common/utils"
+import { PriceListPricesAddSchema } from './schema';
+
+type PriceListPricesAddPricesFormProps = {
+ form: UseFormReturn<PriceListPricesAddSchema>;
+ currencies: HttpTypes.AdminStoreCurrency[];
+ regions: HttpTypes.AdminRegion[];
+ pricePreferences: HttpTypes.AdminPricePreference[];
+};
+
+export const PriceListPricesAddPricesForm = ({
+ form,
+ currencies,
+ regions,
+ pricePreferences
+}: PriceListPricesAddPricesFormProps) => {
+ const ids = useWatch({
+ control: form.control,
+ name: 'product_ids'
+ });
+
+ const existingProducts = useWatch({
+ control: form.control,
+ name: 'products'
+ });
+
+ const {
+ products: productsRaw,
+ isLoading,
+ isError,
+ error
+ } = useProducts({
+ fields: 'title,thumbnail,*variants,+status, *variants.prices'
+ });
+
+ const products = productsRaw?.filter(product => ids.some(id => id.id === product.id));
+
+ const { setValue } = form;
+
+ const { setCloseOnEscape } = useRouteModal();
+
+ useEffect(() => {
+ if (!isLoading && products) {
+ products.forEach(product => {
+ /**
+ * If the product already exists in the form, we don't want to overwrite it.
+ */
+ if (existingProducts[product.id] || !product.variants) {
+ return;
+ }
+
+ setValue(`products.${product.id}.variants`, {
+ ...product.variants.reduce((variants, variant) => {
+ variants[variant.id] = {
+ currency_prices: {},
+ region_prices: {}
+ };
+ return variants;
+ }, {} as PriceListCreateProductVariantsSchema)
+ });
+ });
+ }
+ }, [products, existingProducts, isLoading, setValue]);
+
+ const columns = usePriceListGridColumns({
+ currencies,
+ regions,
+ pricePreferences,
+ showCurrentPriceCell: true
+ });
+
+ if (isError) {
+ throw error;
+ }
+
+ return (
+ <div className="flex size-full flex-col divide-y overflow-hidden">
+ <DataGrid
+ isLoading={isLoading}
+ columns={columns}
+ data={products}
+ getSubRows={row => {
+ if (isProductRow(row) && row.variants) {
+ return row.variants;
+ }
+ }}
+ state={form}
+ onEditingChange={editing => setCloseOnEscape(!editing)}
+ />
+ </div>
+ );
+};
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
new file mode 100644
index 000000000..f0375b192
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
@@ -0,0 +1,242 @@
+import { HttpTypes } from "@medusajs/types"
+import { Checkbox, Tooltip } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { PriceListCreateProductsSchema } from "../../../common/schemas"
+import { PriceListPricesAddSchema } from "./schema"
+import { usePriceListProducts } from "@hooks/api"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type PriceListPricesAddProductIdsFormProps = {
+ form: UseFormReturn<PriceListPricesAddSchema>
+ priceList: HttpTypes.AdminPriceList
+}
+
+const PAGE_SIZE = 50
+const PREFIX = "p"
+
+function getInitialSelection(products: { id: string }[]) {
+ return products.reduce((acc, curr) => {
+ acc[curr.id] = true
+ return acc
+ }, {} as RowSelectionState)
+}
+
+export const PriceListPricesAddProductIdsForm = ({
+ priceList,
+ form,
+}: PriceListPricesAddProductIdsFormProps) => {
+ const { t } = useTranslation()
+ const { control, setValue } = form
+
+ const variantIdMap = useMemo(() => {
+ return priceList.prices.reduce(
+ (acc, curr) => {
+ acc[curr.variant_id] = true
+ return acc
+ },
+ {} as Record<string, boolean>
+ )
+ }, [priceList.prices])
+
+ const selectedIds = useWatch({
+ control,
+ name: "product_ids",
+ })
+
+ const productRecords = useWatch({
+ control,
+ name: "products",
+ })
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>(
+ getInitialSelection(selectedIds)
+ )
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { products, isLoading, isError, error } = useProducts(
+ { ...searchParams, fields: "+thumbnail" },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const { products: priceListProducts } = usePriceListProducts(priceList.id)
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+
+ const ids = Object.keys(state)
+ const productRecordKeys = Object.keys(productRecords)
+
+ const updatedRecords = productRecordKeys.reduce((acc, key) => {
+ if (ids.includes(key)) {
+ acc[key] = productRecords[key]
+ }
+
+ return acc
+ }, {} as PriceListCreateProductsSchema)
+
+ const update = ids.map((id) => ({ id }))
+
+ setValue("product_ids", update, { shouldDirty: true, shouldTouch: true })
+
+ /**
+ * Update the product records to ensure that all unselected products
+ * are removed from the form state.
+ */
+ setValue("products", updatedRecords, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const columns = useColumns()
+ const filters = useProductTableFilters()
+
+ const filteredProducts = useMemo(() => {
+ return products?.filter((product) => {
+ return !priceListProducts?.some(
+ (plProduct: { id: string }) => plProduct.id === product.id
+ )
+ })
+ }, [products, priceListProducts])
+
+ const { table } = useDataTable({
+ data: filteredProducts || [],
+ columns,
+ count: filteredProducts?.length || 0,
+ enablePagination: true,
+ enableRowSelection: (row) => {
+ return (
+ !!row.original.variants?.length &&
+ !row.original.variants?.some((v) => variantIdMap[v.id])
+ )
+ },
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ meta: {
+ variantIdMap,
+ },
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <div className="flex size-full flex-col">
+ <_DataTable
+ table={table}
+ columns={columns}
+ filters={filters}
+ pageSize={PAGE_SIZE}
+ prefix={PREFIX}
+ count={filteredProducts?.length || 0}
+ isLoading={isLoading}
+ layout="fill"
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "status", label: t("fields.status") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ pagination
+ search
+ queryObject={raw}
+ />
+ </div>
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row, table }) => {
+ const { variantIdMap } = table.options.meta as {
+ variantIdMap: Record<string, boolean>
+ }
+
+ const isPreselected = row.original.variants?.some(
+ (v) => variantIdMap[v.id]
+ )
+ const isDisabled = !row.getCanSelect() || isPreselected
+ const isChecked = row.getIsSelected() || isPreselected
+
+ const Component = (
+ <Checkbox
+ checked={isChecked}
+ disabled={isDisabled}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+
+ if (isPreselected) {
+ return (
+ <Tooltip content="This product is already in the price list">
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ if (isDisabled) {
+ return (
+ <Tooltip content="This product has no variants">
+ {Component}
+ </Tooltip>
+ )
+ }
+
+ return Component
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts
new file mode 100644
index 000000000..eaf5c21e1
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/add/price-list-prices-add-form/schema.ts
@@ -0,0 +1,73 @@
+import { z } from 'zod';
+
+import { PriceListCreateProductsSchema } from "../../../../common/schemas"
+
+const PriceListPricesAddBaseSchema = z.object({
+ product_ids: z.array(z.object({ id: z.string() })).min(1),
+ products: PriceListCreateProductsSchema
+});
+
+export const PriceListPricesAddProductIdsSchema = PriceListPricesAddBaseSchema.pick({
+ product_ids: true
+});
+
+export const PriceListPricesAddProductsIdsFields = Object.keys(
+ PriceListPricesAddProductIdsSchema.shape
+) as (keyof typeof PriceListPricesAddProductIdsSchema.shape)[];
+
+export const PriceListPricesAddProductsSchema = PriceListPricesAddBaseSchema.pick({
+ products: true
+});
+
+export const PriceListPricesAddProductsFields = Object.keys(
+ PriceListPricesAddProductsSchema.shape
+) as (keyof typeof PriceListPricesAddProductsSchema.shape)[];
+
+export const PriceListPricesAddSchema = PriceListPricesAddBaseSchema.refine(
+ data => {
+ // Check if at least one product has at least one price with an amount
+ const productIds = data.product_ids.map(p => p.id);
+
+ for (const productId of productIds) {
+ const product = data.products[productId];
+ if (!product) continue;
+
+ // Check all variants of this product
+ for (const variant of Object.values(product.variants || {})) {
+ // Check currency prices
+ const hasCurrencyPrice = Object.values(variant.currency_prices || {}).some(price => {
+ const amount = price?.amount;
+ return (
+ amount !== undefined &&
+ amount !== null &&
+ amount !== '' &&
+ (typeof amount === 'number' ? amount > 0 : String(amount).trim() !== '')
+ );
+ });
+
+ // Check region prices
+ const hasRegionPrice = Object.values(variant.region_prices || {}).some(price => {
+ const amount = price?.amount;
+ return (
+ amount !== undefined &&
+ amount !== null &&
+ amount !== '' &&
+ (typeof amount === 'number' ? amount > 0 : String(amount).trim() !== '')
+ );
+ });
+
+ if (hasCurrencyPrice || hasRegionPrice) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ },
+ {
+ message: 'At least one price must be added.',
+ path: ['products']
+ }
+);
+
+export type PriceListPricesAddSchema = z.infer<typeof PriceListPricesAddSchema>;
diff --git a/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx b/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx
new file mode 100644
index 000000000..405a2adc0
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/[id]/products/edit/index.tsx
@@ -0,0 +1,62 @@
+// Route: /price-lists/:id/products/edit
+import { useParams, useSearchParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { usePriceList, useProducts } from "@hooks/api"
+import { usePriceListCurrencyData } from "../../../common/hooks/use-price-list-currency-data"
+import { PriceListPricesEditForm } from "../[variant_id]/edit/price-list-prices-edit-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const [searchParams] = useSearchParams()
+ const ids = searchParams.get("ids[]")
+
+ const { price_list, isLoading, isError, error } = usePriceList(id!)
+ const productIds = ids?.split(",")
+
+ const {
+ products,
+ isLoading: isProductsLoading,
+ isError: isProductsError,
+ error: productError,
+ } = useProducts({
+ id: productIds,
+ limit: productIds?.length || 9999,
+ price_list_id: [id!],
+ fields: "title,thumbnail,*variants",
+ })
+
+ const priceListCurrencyData = usePriceListCurrencyData()
+
+ const ready =
+ !isLoading &&
+ !!price_list &&
+ !isProductsLoading &&
+ !!products &&
+ priceListCurrencyData.isReady
+
+ if (isError) {
+ throw error
+ }
+
+ if (isProductsError) {
+ throw productError
+ }
+
+ return (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">Edit Prices for {price_list?.title}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description className="sr-only">
+ Update prices for products in the price list
+ </RouteFocusModal.Description>
+ {ready && (
+ <PriceListPricesEditForm
+ priceList={price_list}
+ products={products}
+ {...priceListCurrencyData}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/_components/index.ts b/packages/vendor/src/pages/price-lists/_components/index.ts
new file mode 100644
index 000000000..1ca9698bc
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-list-table"
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/index.ts b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/index.ts
new file mode 100644
index 000000000..1ca9698bc
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-list-table"
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table-actions.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table-actions.tsx
new file mode 100644
index 000000000..197d4981a
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table-actions.tsx
@@ -0,0 +1,45 @@
+
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeletePriceListAction } from "@pages/price-lists/common/hooks/use-delete-price-list-action"
+
+type PriceListListTableActionsProps = {
+ priceList: HttpTypes.AdminPriceList
+}
+
+export const PriceListListTableActions = ({
+ priceList,
+}: PriceListListTableActionsProps) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeletePriceListAction({
+ priceList,
+ })
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: `${priceList.id}/edit`,
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table.tsx
new file mode 100644
index 000000000..a6ec4eeab
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/price-list-list-table.tsx
@@ -0,0 +1,82 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { _DataTable } from "@components/table/data-table"
+import { usePriceLists } from "@hooks/api/price-lists"
+import { useDataTable } from "@hooks/use-data-table"
+import { usePricingTableColumns } from "./use-pricing-table-columns"
+import { usePricingTableFilters } from "./use-pricing-table-filters"
+import { usePricingTableQuery } from "./use-pricing-table-query"
+
+const PAGE_SIZE = 20
+
+export const PriceListListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = usePricingTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { price_lists, count, isLoading, isError, error } = usePriceLists(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = usePricingTableFilters()
+ const columns = usePricingTableColumns()
+
+ const { table } = useDataTable({
+ data: price_lists || [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("priceLists.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("priceLists.subtitle")}
+ </Text>
+ </div>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "status", label: t("fields.status") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ queryObject={raw}
+ pageSize={PAGE_SIZE}
+ navigateTo={(row) => row.original.id}
+ isLoading={isLoading}
+ pagination
+ search
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx
new file mode 100644
index 000000000..dd04a85db
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-columns.tsx
@@ -0,0 +1,51 @@
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { StatusCell } from "@components/table/table-cells/common/status-cell"
+import {
+ TextCell,
+ TextHeader,
+} from "@components/table/table-cells/common/text-cell"
+import { getPriceListStatus } from "@pages/price-lists/common/utils"
+import { PriceListListTableActions } from "./price-list-list-table-actions"
+import { ExtendedPriceList } from "@custom-types/price-list"
+
+const columnHelper = createColumnHelper<ExtendedPriceList>()
+
+export const usePricingTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("title", {
+ header: () => <TextHeader text={t("fields.title")} />,
+ cell: ({ row }) => {
+ return row.original?.title || "-"
+ },
+ }),
+ columnHelper.accessor("status", {
+ header: t("priceLists.fields.status.label"),
+ cell: ({ row }) => {
+ const { color, text } = getPriceListStatus(t, row.original)
+
+ return <StatusCell color={color}>{text}</StatusCell>
+ },
+ }),
+ columnHelper.accessor("prices", {
+ header: t("priceLists.fields.priceOverrides.header"),
+ cell: ({ row }) => {
+ const prices = row.original?.prices?.length || "-"
+ return <TextCell text={prices} />
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => (
+ <PriceListListTableActions priceList={row.original} />
+ ),
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx
new file mode 100644
index 000000000..74807c987
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-filters.tsx
@@ -0,0 +1,7 @@
+import { useDateTableFilters } from "@hooks/table/filters/use-date-table-filters"
+
+export const usePricingTableFilters = () => {
+ const dateFilters = useDateTableFilters()
+
+ return dateFilters
+}
diff --git a/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx
new file mode 100644
index 000000000..a1cd546ca
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/_components/price-list-list-table/use-pricing-table-query.tsx
@@ -0,0 +1,25 @@
+import { HttpTypes, PriceListStatus } from "@medusajs/types"
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const usePricingTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(["offset", "q", "order", "status"], prefix)
+
+ const searchParams: HttpTypes.AdminPriceListListParams = {
+ limit: pageSize,
+ offset: raw.offset ? Number(raw.offset) : 0,
+ order: raw.order,
+ status: raw.status?.split(",") as PriceListStatus[],
+ q: raw.q,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/index.ts b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/index.ts
new file mode 100644
index 000000000..327680205
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-customer-group-rule-form"
diff --git a/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx
new file mode 100644
index 000000000..a0529a5e6
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/components/price-list-customer-group-rule-form/price-list-customer-group-rule-form.tsx
@@ -0,0 +1,218 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { StackedDrawer } from "@components/modals/stacked-drawer"
+import { StackedFocusModal } from "@components/modals/stacked-focus-modal"
+import { _DataTable } from "@components/table/data-table"
+import { useCustomerGroups } from "@hooks/api/customer-groups"
+import { useCustomerGroupTableFilters } from "@hooks/table/filters/use-customer-group-table-filters"
+import { useCustomerGroupTableQuery } from "@hooks/table/query/use-customer-group-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { PriceListCustomerGroup } from "../../schemas"
+import { TextCell, TextHeader } from "@components/table/table-cells/common/text-cell"
+
+const PAGE_SIZE = 50
+const PREFIX = "cg"
+
+type PriceListCustomerGroupRuleFormProps = {
+ type: "focus" | "drawer"
+ state: PriceListCustomerGroup[]
+ setState: (state: PriceListCustomerGroup[]) => void
+}
+
+const initRowSelection = (state: PriceListCustomerGroup[]) => {
+ return state.reduce((acc, group) => {
+ acc[group.id] = true
+ return acc
+ }, {} as RowSelectionState)
+}
+
+export const PriceListCustomerGroupRuleForm = ({
+ state,
+ setState,
+ type,
+}: PriceListCustomerGroupRuleFormProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>(
+ initRowSelection(state)
+ )
+ const [intermediate, setIntermediate] =
+ useState<PriceListCustomerGroup[]>(state)
+
+ useEffect(() => {
+ // If the selected customer groups change outside of the drawer,
+ // update the row selection state and intermediate state
+ setRowSelection(initRowSelection(state))
+ setIntermediate(state)
+ }, [state])
+
+ const { searchParams, raw } = useCustomerGroupTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ // Get the sort parameter from the raw object
+ const sortParam = raw.order
+ ? raw.order.startsWith("-")
+ ? raw.order
+ : raw.order
+ : undefined
+
+ const { customer_groups: customerGroupsData, count, isLoading, isError, error } =
+ useCustomerGroups(
+ { ...searchParams, fields: "id,name,customers.id" },
+ {
+ placeholderData: keepPreviousData,
+ },
+ sortParam ? { sort: sortParam } : undefined
+ )
+
+ const customerGroups = customerGroupsData
+ ?.map((item) => item.customer_group)
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newCustomerGroups =
+ customerGroups
+ ?.filter((cg) => newIds.includes(cg.id))
+ .map((cg) => ({
+ id: cg.id,
+ name: cg.name!,
+ })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (cg) => !removedIds.includes(cg.id)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newCustomerGroups])
+ setRowSelection(state)
+ }
+
+ const handleSave = () => {
+ setState(intermediate)
+ }
+
+ const filters = useCustomerGroupTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: customerGroups || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const Component = type === "focus" ? StackedFocusModal : StackedDrawer
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <div className="flex size-full flex-col overflow-hidden">
+ <Component.Body className="min-h-0 p-0">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX}
+ queryObject={raw}
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ />
+ </Component.Body>
+ <Component.Footer>
+ <Component.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </Component.Close>
+ <Button type="button" size="small" onClick={handleSave}>
+ {t("actions.save")}
+ </Button>
+ </Component.Footer>
+ </div>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminCustomerGroup>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ columnHelper.accessor("name", {
+ header: () => <TextHeader text={t("fields.name")} />,
+ cell: ({ row }) => {
+ return (
+ <TextCell
+ text={row.original?.name || "-"}
+ />
+ )
+ },
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/common/constants.ts b/packages/vendor/src/pages/price-lists/common/constants.ts
new file mode 100644
index 000000000..aecee622a
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/constants.ts
@@ -0,0 +1,20 @@
+/**
+ * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported
+ */
+export enum PriceListStatus {
+ ACTIVE = "active",
+ DRAFT = "draft",
+}
+
+export enum PriceListDateStatus {
+ SCHEDULED = "scheduled",
+ EXPIRED = "expired",
+}
+
+/**
+ * Re-implementation of enum from `@medusajs/medusa` as it cannot be imported
+ */
+export enum PriceListType {
+ SALE = "sale",
+ OVERRIDE = "override",
+}
diff --git a/packages/vendor/src/pages/price-lists/common/hooks/use-delete-price-list-action.tsx b/packages/vendor/src/pages/price-lists/common/hooks/use-delete-price-list-action.tsx
new file mode 100644
index 000000000..77e07e75c
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/hooks/use-delete-price-list-action.tsx
@@ -0,0 +1,50 @@
+import { HttpTypes } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { useDeletePriceList } from "@hooks/api/price-lists"
+
+export const useDeletePriceListAction = ({
+ priceList,
+}: {
+ priceList: HttpTypes.AdminPriceList
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const { mutateAsync } = useDeletePriceList(priceList.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("priceLists.delete.confirmation", {
+ title: priceList.title,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("priceLists.delete.successToast", {
+ title: priceList.title,
+ })
+ )
+
+ navigate("/price-lists")
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
diff --git a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx
new file mode 100644
index 000000000..98f863638
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-currency-data.tsx
@@ -0,0 +1,67 @@
+import { HttpTypes } from "@medusajs/types"
+import { useRegions } from "@hooks/api/regions"
+import { useStore } from "@hooks/api/store"
+
+type UsePriceListCurrencyDataReturn =
+ | {
+ isReady: false
+ currencies: undefined
+ regions: undefined
+ pricePreferences: undefined
+ }
+ | {
+ isReady: true
+ currencies: HttpTypes.AdminStoreCurrency[]
+ regions: HttpTypes.AdminRegion[]
+ pricePreferences: HttpTypes.AdminPricePreference[]
+ }
+
+export const usePriceListCurrencyData = (): UsePriceListCurrencyDataReturn => {
+ const {
+ store,
+ isPending: isStorePending,
+ isError: isStoreError,
+ error: storeError,
+ } = useStore({
+ fields: "+supported_currencies",
+ })
+
+ const currencies = store?.supported_currencies
+
+ const {
+ regions,
+ isPending: isRegionsPending,
+ isError: isRegionsError,
+ error: regionsError,
+ } = useRegions({
+ fields: "id,name,currency_code",
+ limit: 999,
+ })
+
+ const isReady =
+ !!currencies && !!regions && !isStorePending && !isRegionsPending
+
+ if (isRegionsError) {
+ throw regionsError
+ }
+
+ if (isStoreError) {
+ throw storeError
+ }
+
+ if (!isReady) {
+ return {
+ regions: undefined,
+ currencies: undefined,
+ pricePreferences: undefined,
+ isReady: false,
+ }
+ }
+
+ return {
+ regions,
+ currencies,
+ pricePreferences: [],
+ isReady,
+ }
+}
diff --git a/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx
new file mode 100644
index 000000000..53708a47e
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/hooks/use-price-list-grid-columns.tsx
@@ -0,0 +1,92 @@
+import { HttpTypes } from "@medusajs/types"
+import { ColumnDef } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { Thumbnail } from "@components/common/thumbnail"
+import {
+ createDataGridHelper,
+ DataGrid,
+} from "@components/data-grid"
+import { createDataGridPriceColumns } from "@components/data-grid/helpers/create-data-grid-price-columns"
+import { PricingCreateSchemaType } from "../../price-list-create/components/price-list-create-form/schema"
+import { isProductRow } from "../utils"
+import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"
+
+const columnHelper = createDataGridHelper<
+ ExtendedAdminProduct | ExtendedAdminProductVariant,
+ PricingCreateSchemaType
+>()
+
+export const usePriceListGridColumns = ({
+ currencies = [],
+ regions = [],
+ pricePreferences = [],
+}: {
+ currencies?: HttpTypes.AdminStoreCurrency[]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}) => {
+ const { t } = useTranslation()
+
+ const colDefs: ColumnDef<
+ ExtendedAdminProduct | ExtendedAdminProductVariant
+ >[] = useMemo(() => {
+ return [
+ columnHelper.column({
+ id: t("fields.title"),
+ header: t("fields.title"),
+ cell: (context) => {
+ const entity = context.row.original
+ if (isProductRow(entity)) {
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ <div className="flex h-full w-full items-center gap-x-2 overflow-hidden">
+ <Thumbnail src={entity.thumbnail} size="small" />
+ <span className="truncate">{entity.title}</span>
+ </div>
+ </DataGrid.ReadonlyCell>
+ )
+ }
+
+ return (
+ <DataGrid.ReadonlyCell context={context} color="normal">
+ <div className="flex h-full w-full items-center gap-x-2 overflow-hidden">
+ <span className="truncate">{entity.title}</span>
+ </div>
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ ...createDataGridPriceColumns<
+ ExtendedAdminProduct | ExtendedAdminProductVariant,
+ PricingCreateSchemaType
+ >({
+ currencies: currencies.map((c) => c.currency_code),
+ pricePreferences,
+ isReadyOnly: (context) => {
+ const entity = context.row.original
+ return isProductRow(entity)
+ },
+ getFieldName: (context, value) => {
+ const entity = context.row.original
+
+ if (isProductRow(entity)) {
+ return null
+ }
+
+ if (context.column.id?.startsWith("currency_prices")) {
+ return `products.${entity.product_id}.variants.${entity.id}.currency_prices.${value}.amount`
+ }
+
+ return `products.${entity.product_id}.variants.${entity.id}.region_prices.${value}.amount`
+ },
+ t,
+ showCurrentPriceCell: true,
+ }),
+ ]
+ }, [t, currencies, regions, pricePreferences])
+
+ return colDefs
+}
diff --git a/packages/vendor/src/pages/price-lists/common/schemas.ts b/packages/vendor/src/pages/price-lists/common/schemas.ts
new file mode 100644
index 000000000..dceda6eb8
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/schemas.ts
@@ -0,0 +1,96 @@
+import { z } from "zod"
+
+const PriceListCustomerGroupSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+})
+
+export type PriceListCustomerGroup = z.infer<
+ typeof PriceListCustomerGroupSchema
+>
+
+export const PriceListRulesSchema = z.object({
+ customer_group_id: z.array(PriceListCustomerGroupSchema).nullish(),
+})
+
+const PriceListCreateCurrencyPriceSchema = z.object({
+ amount: z.string().or(z.number()).optional(),
+})
+
+export type PriceListCreateCurrencyPrice = z.infer<
+ typeof PriceListCreateCurrencyPriceSchema
+>
+
+const PriceListCreateRegionPriceSchema = z.object({
+ amount: z.string().or(z.number()).optional(),
+})
+
+export type PriceListCreateRegionPriceSchema = z.infer<
+ typeof PriceListCreateRegionPriceSchema
+>
+
+const PriceListCreateProductVariantSchema = z.object({
+ currency_prices: z.record(PriceListCreateCurrencyPriceSchema.optional()),
+ region_prices: z.record(PriceListCreateRegionPriceSchema.optional()),
+})
+
+export type PriceListCreateProductVariantSchema = z.infer<
+ typeof PriceListCreateProductVariantSchema
+>
+
+const PriceListCreateProductVariantsSchema = z.record(
+ PriceListCreateProductVariantSchema
+)
+
+export type PriceListCreateProductVariantsSchema = z.infer<
+ typeof PriceListCreateProductVariantsSchema
+>
+
+export const PriceListCreateProductsSchema = z.record(
+ z.object({
+ variants: PriceListCreateProductVariantsSchema,
+ })
+)
+
+export type PriceListCreateProductsSchema = z.infer<
+ typeof PriceListCreateProductsSchema
+>
+
+export const PriceListUpdateCurrencyPriceSchema = z.object({
+ amount: z.string().or(z.number()).optional(),
+ id: z.string().nullish(),
+})
+
+export type PriceListUpdateCurrencyPrice = z.infer<
+ typeof PriceListUpdateCurrencyPriceSchema
+>
+
+export const PriceListUpdateRegionPriceSchema = z.object({
+ amount: z.string().or(z.number()).optional(),
+ id: z.string().nullish(),
+})
+
+export type PriceListUpdateRegionPrice = z.infer<
+ typeof PriceListUpdateRegionPriceSchema
+>
+
+export const PriceListUpdateProductVariantsSchema = z.record(
+ z.object({
+ currency_prices: z.record(PriceListUpdateCurrencyPriceSchema.optional()),
+ region_prices: z.record(PriceListUpdateRegionPriceSchema.optional()),
+ })
+)
+
+export type PriceListUpdateProductVariantsSchema = z.infer<
+ typeof PriceListUpdateProductVariantsSchema
+>
+
+export const PriceListUpdateProductsSchema = z.record(
+ z.object({
+ variants: PriceListUpdateProductVariantsSchema,
+ })
+)
+
+export type PriceListUpdateProductsSchema = z.infer<
+ typeof PriceListUpdateProductsSchema
+>
diff --git a/packages/vendor/src/pages/price-lists/common/utils.ts b/packages/vendor/src/pages/price-lists/common/utils.ts
new file mode 100644
index 000000000..3ffe4812e
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/common/utils.ts
@@ -0,0 +1,124 @@
+import { HttpTypes } from "@medusajs/types"
+import { TFunction } from "i18next"
+import { json } from "react-router-dom"
+import { castNumber } from "@lib/cast-number"
+import { PriceListDateStatus, PriceListStatus } from "./constants"
+import {
+ PriceListCreateCurrencyPrice,
+ PriceListCreateProductVariantSchema,
+ PriceListCreateProductsSchema,
+} from "./schemas"
+import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"
+
+const getValues = (priceList: HttpTypes.AdminPriceList) => {
+ const startsAt = priceList.starts_at
+ const endsAt = priceList.ends_at
+
+ const isExpired = endsAt ? new Date(endsAt) < new Date() : false
+ const isScheduled = startsAt ? new Date(startsAt) > new Date() : false
+ const isDraft = priceList.status === PriceListStatus.DRAFT
+
+ return {
+ isExpired,
+ isScheduled,
+ isDraft,
+ }
+}
+
+export const getPriceListStatus = (
+ t: TFunction<"translation">,
+ priceList: HttpTypes.AdminPriceList
+) => {
+ const { isExpired, isScheduled, isDraft } = getValues(priceList)
+
+ let text = t("priceLists.fields.status.options.active")
+ let color: "red" | "grey" | "orange" | "green" = "green"
+ let status: string = PriceListStatus.ACTIVE
+
+ if (isDraft) {
+ color = "grey"
+ text = t("priceLists.fields.status.options.draft")
+ status = PriceListStatus.DRAFT
+ }
+
+ if (isExpired) {
+ color = "red"
+ text = t("priceLists.fields.status.options.expired")
+ status = PriceListDateStatus.EXPIRED
+ }
+
+ if (isScheduled) {
+ color = "orange"
+ text = t("priceLists.fields.status.options.scheduled")
+ status = PriceListDateStatus.SCHEDULED
+ }
+
+ return {
+ color,
+ text,
+ status,
+ }
+}
+
+export const isProductRow = (
+ row: ExtendedAdminProduct | ExtendedAdminProductVariant
+): row is ExtendedAdminProduct => {
+ return "variants" in row
+}
+
+const extractPricesFromVariants = (
+ variantId: string,
+ variant: PriceListCreateProductVariantSchema,
+ regions: HttpTypes.AdminRegion[]
+) => {
+ const extractPriceDetails = (
+ price: PriceListCreateCurrencyPrice,
+ priceType: "region" | "currency",
+ id: string
+ ) => {
+ const currencyCode =
+ priceType === "currency"
+ ? id
+ : regions.find((r) => r.id === id)?.currency_code
+
+ if (!currencyCode) {
+ throw json({ message: "Currency code not found" }, 400)
+ }
+
+ return {
+ amount: castNumber(price.amount!),
+ ...(priceType === "region" ? { rules: { region_id: id } } : {}),
+ currency_code: currencyCode,
+ variant_id: variantId,
+ }
+ }
+
+ const currencyPrices = Object.entries(variant.currency_prices || {}).flatMap(
+ ([currencyCode, currencyPrice]) => {
+ return currencyPrice?.amount
+ ? [extractPriceDetails(currencyPrice, "currency", currencyCode)]
+ : []
+ }
+ )
+
+ const regionPrices = Object.entries(variant.region_prices || {}).flatMap(
+ ([regionId, regionPrice]) => {
+ return regionPrice?.amount
+ ? [extractPriceDetails(regionPrice, "region", regionId)]
+ : []
+ }
+ )
+
+ return [...currencyPrices, ...regionPrices]
+}
+
+export const exctractPricesFromProducts = (
+ products: PriceListCreateProductsSchema,
+ regions: HttpTypes.AdminRegion[]
+) => {
+ return Object.values(products).flatMap(({ variants }) =>
+ Object.entries(variants).flatMap(([variantId, variant]) =>
+ extractPricesFromVariants(variantId, variant, regions)
+ )
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/index.tsx b/packages/vendor/src/pages/price-lists/create/index.tsx
new file mode 100644
index 000000000..c803814cd
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/index.tsx
@@ -0,0 +1,21 @@
+// Route: /price-lists/create
+import { RouteFocusModal } from "@components/modals"
+import { usePriceListCurrencyData } from "../common/hooks/use-price-list-currency-data"
+import { PriceListCreateForm } from "./price-list-create-form"
+
+export const Component = () => {
+ const { isReady, regions, currencies, pricePreferences } =
+ usePriceListCurrencyData()
+
+ return (
+ <RouteFocusModal>
+ {isReady && (
+ <PriceListCreateForm
+ regions={regions}
+ currencies={currencies}
+ pricePreferences={pricePreferences}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/index.ts b/packages/vendor/src/pages/price-lists/create/price-list-create-form/index.ts
new file mode 100644
index 000000000..aa9655069
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/index.ts
@@ -0,0 +1 @@
+export * from "./price-list-create-form"
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx
new file mode 100644
index 000000000..43cf13b0d
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-create-form.tsx
@@ -0,0 +1,363 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
+import { FieldPath, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { HttpTypes, PriceListStatus, PriceListType } from "@medusajs/types"
+import { useState } from "react"
+import { z } from "zod"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreatePriceList } from "@hooks/api/price-lists"
+import { exctractPricesFromProducts } from "@pages/price-lists/common/utils"
+import { PriceListDetailsForm } from "./price-list-details-form"
+import { PriceListPricesForm } from "./price-list-prices-form"
+import { PriceListProductsForm } from "./price-list-products-form"
+import {
+ PricingCreateSchema,
+ PricingCreateSchemaType,
+ PricingDetailsFields,
+ PricingDetailsSchema,
+ PricingPricesFields,
+ PricingProductsFields,
+ PricingProductsSchema,
+} from "./schema"
+
+enum Tab {
+ DETAIL = "detail",
+ PRODUCT = "product",
+ PRICE = "price",
+}
+
+const tabOrder = [Tab.DETAIL, Tab.PRODUCT, Tab.PRICE] as const
+
+type TabState = Record<Tab, ProgressStatus>
+
+const initialTabState: TabState = {
+ [Tab.DETAIL]: "in-progress",
+ [Tab.PRODUCT]: "not-started",
+ [Tab.PRICE]: "not-started",
+}
+
+type PriceListCreateFormProps = {
+ regions: HttpTypes.AdminRegion[]
+ currencies: HttpTypes.AdminStoreCurrency[]
+ pricePreferences: HttpTypes.AdminPricePreference[]
+}
+
+export const PriceListCreateForm = ({
+ regions,
+ currencies,
+ pricePreferences,
+}: PriceListCreateFormProps) => {
+ const [tab, setTab] = useState<Tab>(Tab.DETAIL)
+ const [tabState, setTabState] = useState<TabState>(initialTabState)
+
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<PricingCreateSchemaType>({
+ defaultValues: {
+ type: "sale",
+ status: "active",
+ title: "",
+ description: "",
+ starts_at: null,
+ ends_at: null,
+ product_ids: [],
+ products: {},
+ rules: {
+ customer_group_id: [],
+ },
+ },
+ resolver: zodResolver(PricingCreateSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreatePriceList()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const { rules, products } = data
+
+ const rulesPayload = rules?.customer_group_id?.length
+ ? { "customer.groups.id": rules.customer_group_id.map((cg) => cg.id) }
+ : undefined
+
+ const prices = exctractPricesFromProducts(products, regions)
+
+ await mutateAsync(
+ {
+ title: data.title,
+ type: data.type as PriceListType,
+ status: data.status as PriceListStatus,
+ description: data.description,
+ starts_at: data.starts_at ? data.starts_at.toISOString() : null,
+ ends_at: data.ends_at ? data.ends_at.toISOString() : null,
+ rules: rulesPayload,
+ prices,
+ },
+ {
+ onSuccess: ({ price_list }) => {
+ toast.success(
+ t("priceLists.create.successToast", {
+ title: price_list.title,
+ })
+ )
+ handleSuccess(`../${price_list.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const partialFormValidation = (
+ fields: FieldPath<PricingCreateSchemaType>[],
+ schema: z.ZodSchema<any>
+ ) => {
+ form.clearErrors(fields)
+
+ const values = fields.reduce(
+ (acc, key) => {
+ acc[key] = form.getValues(key)
+ return acc
+ },
+ {} as Record<string, unknown>
+ )
+
+ const validationResult = schema.safeParse(values)
+
+ if (!validationResult.success) {
+ validationResult.error.errors.forEach(({ path, message, code }) => {
+ form.setError(path.join(".") as keyof PricingCreateSchemaType, {
+ type: code,
+ message,
+ })
+ })
+
+ return false
+ }
+
+ return true
+ }
+
+ const isTabDirty = (tab: Tab) => {
+ switch (tab) {
+ case Tab.DETAIL: {
+ const fields = PricingDetailsFields
+
+ return fields.some((field) => {
+ return form.getFieldState(field).isDirty
+ })
+ }
+ case Tab.PRODUCT: {
+ const fields = PricingProductsFields
+
+ return fields.some((field) => {
+ return form.getFieldState(field).isDirty
+ })
+ }
+ case Tab.PRICE: {
+ const fields = PricingPricesFields
+
+ return fields.some((field) => {
+ return form.getFieldState(field).isDirty
+ })
+ }
+ }
+ }
+
+ const handleChangeTab = (update: Tab) => {
+ if (tab === update) {
+ return
+ }
+
+ if (tabOrder.indexOf(update) < tabOrder.indexOf(tab)) {
+ const isCurrentTabDirty = isTabDirty(tab)
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: isCurrentTabDirty ? prev[tab] : "not-started",
+ [update]: "in-progress",
+ }))
+
+ setTab(update)
+ return
+ }
+
+ // get the tabs from the current tab to the update tab including the current tab
+ const tabs = tabOrder.slice(0, tabOrder.indexOf(update))
+
+ // validate all the tabs from the current tab to the update tab if it fails on any of tabs then set that tab as current tab
+ for (const tab of tabs) {
+ if (tab === Tab.DETAIL) {
+ if (
+ !partialFormValidation(PricingDetailsFields, PricingDetailsSchema)
+ ) {
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "in-progress",
+ }))
+ setTab(tab)
+ return
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ }))
+ } else if (tab === Tab.PRODUCT) {
+ if (
+ !partialFormValidation(PricingProductsFields, PricingProductsSchema)
+ ) {
+ toast.error(t("priceLists.create.products.errors.noProducts"))
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "in-progress",
+ }))
+ setTab(tab)
+
+ return
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ }))
+ }
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ [update]: "in-progress",
+ }))
+ setTab(update)
+ }
+
+ const handleNextTab = (tab: Tab) => {
+ if (tabOrder.indexOf(tab) + 1 >= tabOrder.length) {
+ return
+ }
+
+ const nextTab = tabOrder[tabOrder.indexOf(tab) + 1]
+ handleChangeTab(nextTab)
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <ProgressTabs
+ value={tab}
+ onValueChange={(tab) => handleChangeTab(tab as Tab)}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
+ <RouteFocusModal.Header>
+ <div className="flex w-full items-center justify-between gap-x-4">
+ <div className="-my-2 w-full max-w-[600px] border-l">
+ <ProgressTabs.List className="grid w-full grid-cols-3">
+ <ProgressTabs.Trigger
+ status={tabState.detail}
+ value={Tab.DETAIL}
+ >
+ {t("priceLists.create.tabs.details")}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState.product}
+ value={Tab.PRODUCT}
+ >
+ {t("priceLists.create.tabs.products")}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState.price}
+ value={Tab.PRICE}
+ >
+ {t("priceLists.create.tabs.prices")}
+ </ProgressTabs.Trigger>
+ </ProgressTabs.List>
+ </div>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.DETAIL}
+ >
+ <PriceListDetailsForm form={form} />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.PRODUCT}
+ >
+ <PriceListProductsForm form={form} />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-hidden"
+ value={Tab.PRICE}
+ >
+ <PriceListPricesForm
+ form={form}
+ regions={regions}
+ currencies={currencies}
+ pricePreferences={pricePreferences}
+ />
+ </ProgressTabs.Content>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <PrimaryButton
+ tab={tab}
+ next={handleNextTab}
+ isLoading={isPending}
+ />
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </ProgressTabs>
+ </RouteFocusModal.Form>
+ )
+}
+
+type PrimaryButtonProps = {
+ tab: Tab
+ next: (tab: Tab) => void
+ isLoading?: boolean
+}
+
+const PrimaryButton = ({ tab, next, isLoading }: PrimaryButtonProps) => {
+ const { t } = useTranslation()
+
+ if (tab === Tab.PRICE) {
+ return (
+ <Button
+ key="submit-button"
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isLoading}
+ >
+ {t("actions.save")}
+ </Button>
+ )
+ }
+
+ return (
+ <Button
+ key="next-button"
+ type="button"
+ variant="primary"
+ size="small"
+ onClick={() => next(tab)}
+ >
+ {t("actions.continue")}
+ </Button>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx
new file mode 100644
index 000000000..0cd591ea5
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-details-form.tsx
@@ -0,0 +1,325 @@
+import { MagnifyingGlass, XMarkMini } from "@medusajs/icons"
+import {
+ Button,
+ DatePicker,
+ Divider,
+ Heading,
+ IconButton,
+ Input,
+ RadioGroup,
+ Select,
+ Text,
+ Textarea,
+ clx,
+} from "@medusajs/ui"
+import { useFieldArray, type UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { StackedFocusModal } from "@components/modals/stacked-focus-modal"
+import { useStackedModal } from "@components/modals/stacked-modal-provider"
+import { PriceListCustomerGroupRuleForm } from "@pages/price-lists/common/components/price-list-customer-group-rule-form"
+import type {
+ PricingCreateSchemaType,
+ PricingCustomerGroupsArrayType,
+} from "./schema"
+
+type PriceListDetailsFormProps = {
+ form: UseFormReturn<PricingCreateSchemaType>
+}
+
+export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
+ const { t } = useTranslation()
+
+ const { fields, remove, append } = useFieldArray({
+ control: form.control,
+ name: "rules.customer_group_id",
+ keyName: "cg_id",
+ })
+
+ const { setIsOpen } = useStackedModal()
+
+ const handleAddCustomerGroup = (groups: PricingCustomerGroupsArrayType) => {
+ const newIds = groups.map((group) => group.id)
+
+ const fieldsToAdd = groups.filter(
+ (group) => !fields.some((field) => field.id === group.id)
+ )
+
+ for (const field of fields) {
+ if (!newIds.includes(field.id)) {
+ remove(fields.indexOf(field))
+ }
+ }
+
+ append(fieldsToAdd)
+ setIsOpen("cg", false)
+ }
+
+ return (
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-8 py-16">
+ <div>
+ <Heading>{t("priceLists.create.header")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("priceLists.create.subheader")}
+ </Text>
+ </div>
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field: { onChange, ...rest } }) => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-y-4">
+ <div>
+ <Form.Label>{t("priceLists.fields.type.label")}</Form.Label>
+ <Form.Hint>{t("priceLists.fields.type.hint")}</Form.Hint>
+ </div>
+ <Form.Control>
+ <RadioGroup
+ onValueChange={onChange}
+ {...rest}
+ className="grid grid-cols-1 gap-4 md:grid-cols-2"
+ >
+ <RadioGroup.ChoiceBox
+ value={"sale"}
+ label={t("priceLists.fields.type.options.sale.label")}
+ description={t(
+ "priceLists.fields.type.options.sale.description"
+ )}
+ />
+ <RadioGroup.ChoiceBox
+ value={"override"}
+ label={t(
+ "priceLists.fields.type.options.override.label"
+ )}
+ description={t(
+ "priceLists.fields.type.options.override.description"
+ )}
+ />
+ </RadioGroup>
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("priceLists.fields.status.label")}
+ </Form.Label>
+ <Form.Control>
+ <Select {...field} onValueChange={onChange}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="active">
+ {t("priceLists.fields.status.options.active")}
+ </Select.Item>
+ <Select.Item value="draft">
+ {t("priceLists.fields.status.options.draft")}
+ </Select.Item>
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.description")}</Form.Label>
+ <Form.Control>
+ <Textarea {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="starts_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <div className="flex flex-col">
+ <Form.Label optional>
+ {t("priceLists.fields.startsAt.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("priceLists.fields.startsAt.hint")}
+ </Form.Hint>
+ </div>
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="ends_at"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <div className="flex flex-col">
+ <Form.Label optional>
+ {t("priceLists.fields.endsAt.label")}
+ </Form.Label>
+ <Form.Hint>{t("priceLists.fields.endsAt.hint")}</Form.Hint>
+ </div>
+ <Form.Control>
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="rules.customer_group_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <div>
+ <Form.Label optional>
+ {t("priceLists.fields.customerAvailability.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("priceLists.fields.customerAvailability.hint")}
+ </Form.Hint>
+ </div>
+ <Form.Control>
+ <div
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
+ "aria-[invalid='true']:shadow-borders-error"
+ )}
+ role="application"
+ ref={field.ref}
+ >
+ <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t("priceLists.fields.customerAvailability.attribute")}
+ </div>
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t("operators.in")}
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-1.5">
+ <StackedFocusModal id="cg">
+ <StackedFocusModal.Trigger asChild>
+ <button
+ type="button"
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"
+ >
+ <MagnifyingGlass />
+ {t(
+ "priceLists.fields.customerAvailability.placeholder"
+ )}
+ </button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Trigger asChild>
+ <Button variant="secondary">
+ {t("actions.browse")}
+ </Button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Content>
+ <StackedFocusModal.Header />
+ <PriceListCustomerGroupRuleForm
+ state={fields}
+ setState={handleAddCustomerGroup}
+ type="focus"
+ />
+ </StackedFocusModal.Content>
+ </StackedFocusModal>
+ </div>
+ {fields.length > 0 ? (
+ <div className="flex flex-col gap-y-1.5">
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-1.5 px-1.5">
+ {fields.map((field, index) => {
+ return (
+ <div
+ key={field.cg_id}
+ className="bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5"
+ >
+ <Text size="small" leading="compact">
+ {field.name}
+ </Text>
+ <IconButton
+ size="small"
+ variant="transparent"
+ type="button"
+ onClick={() => remove(index)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx
new file mode 100644
index 000000000..620ffcf77
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-prices-form.tsx
@@ -0,0 +1,101 @@
+import { HttpTypes } from "@medusajs/types"
+import { useEffect } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { DataGrid } from "@components/data-grid"
+import { useRouteModal } from "@components/modals"
+import { useProducts } from "@hooks/api/products"
+import { usePriceListGridColumns } from "@pages/price-lists/common/hooks/use-price-list-grid-columns"
+import { PriceListCreateProductVariantsSchema } from "@pages/price-lists/common/schemas"
+import { isProductRow } from "@pages/price-lists/common/utils"
+import { PricingCreateSchemaType } from "./schema"
+
+type PriceListPricesFormProps = {
+ form: UseFormReturn<PricingCreateSchemaType>
+ currencies: HttpTypes.AdminStoreCurrency[]
+ regions: HttpTypes.AdminRegion[]
+ pricePreferences: HttpTypes.AdminPricePreference[]
+}
+
+export const PriceListPricesForm = ({
+ form,
+ currencies,
+ regions,
+ pricePreferences,
+}: PriceListPricesFormProps) => {
+ const ids = useWatch({
+ control: form.control,
+ name: "product_ids",
+ })
+
+ const existingProducts = useWatch({
+ control: form.control,
+ name: "products",
+ })
+
+ const {
+ products: productsRaw,
+ isLoading,
+ isError,
+ error,
+ } = useProducts({
+ fields: "title,thumbnail,*variants,+status,*variants.prices",
+ })
+
+ const products = productsRaw?.filter((product) =>
+ ids.some((id) => id.id === product.id)
+ )
+
+ const { setCloseOnEscape } = useRouteModal()
+
+ const { setValue } = form
+
+ useEffect(() => {
+ if (!isLoading && products) {
+ products.forEach((product) => {
+ /**
+ * If the product already exists in the form, we don't want to overwrite it.
+ */
+ if (existingProducts[product.id] || !product.variants) {
+ return
+ }
+
+ setValue(`products.${product.id}.variants`, {
+ ...product.variants.reduce((variants, variant) => {
+ variants[variant.id] = {
+ currency_prices: {},
+ region_prices: {},
+ }
+ return variants
+ }, {} as PriceListCreateProductVariantsSchema),
+ })
+ })
+ }
+ }, [products, existingProducts, isLoading, setValue])
+
+ const columns = usePriceListGridColumns({
+ currencies,
+ regions,
+ pricePreferences,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <div className="flex size-full flex-col divide-y overflow-hidden">
+ <DataGrid
+ isLoading={isLoading}
+ columns={columns}
+ data={products}
+ getSubRows={(row) => {
+ if (isProductRow(row) && row.variants) {
+ return row.variants
+ }
+ }}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx
new file mode 100644
index 000000000..f2e3acc7a
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/price-list-products-form.tsx
@@ -0,0 +1,195 @@
+import { Checkbox } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { PriceListCreateProductsSchema } from "../../../common/schemas"
+import { PricingCreateSchemaType } from "./schema"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type PriceListProductsFormProps = {
+ form: UseFormReturn<PricingCreateSchemaType>
+}
+
+const PAGE_SIZE = 50
+const PREFIX = "p"
+
+function getInitialSelection(products: { id: string }[]) {
+ return products.reduce((acc, curr) => {
+ acc[curr.id] = true
+ return acc
+ }, {} as RowSelectionState)
+}
+
+export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {
+ const { t } = useTranslation()
+ const { control, setValue } = form
+
+ const selectedIds = useWatch({
+ control,
+ name: "product_ids",
+ })
+
+ const productRecords = useWatch({
+ control,
+ name: "products",
+ })
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>(
+ getInitialSelection(selectedIds)
+ )
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { products, count, isLoading, isError, error } = useProducts(
+ { ...searchParams, fields: "+thumbnail" },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const state = typeof fn === "function" ? fn(rowSelection) : fn
+
+ const ids = Object.keys(state)
+ const productRecordKeys = Object.keys(productRecords)
+
+ const updatedRecords = productRecordKeys.reduce((acc, key) => {
+ if (ids.includes(key)) {
+ acc[key] = productRecords[key]
+ }
+
+ return acc
+ }, {} as PriceListCreateProductsSchema)
+
+ const update = ids.map((id) => ({ id }))
+
+ setValue("product_ids", update, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ /**
+ * Update the product records to ensure that all unselected products
+ * are removed from the form state.
+ */
+ setValue("products", updatedRecords, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(state)
+ }
+
+ const columns = useColumns()
+ const filters = useProductTableFilters()
+
+ const { table } = useDataTable({
+ data: products || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: (row) => {
+ return !!row.original.variants?.length
+ },
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <div className="flex size-full flex-col">
+ <_DataTable
+ table={table}
+ columns={columns}
+ filters={filters}
+ pageSize={PAGE_SIZE}
+ prefix={PREFIX}
+ count={count}
+ isLoading={isLoading}
+ layout="fill"
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "status", label: t("fields.status") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ pagination
+ search
+ queryObject={raw}
+ noRecords={{
+ message: t("priceLists.create.products.list.noRecordsMessage"),
+ }}
+ />
+ </div>
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ disabled={!row.getCanSelect()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts b/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts
new file mode 100644
index 000000000..4c3b64cdc
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/create/price-list-create-form/schema.ts
@@ -0,0 +1,59 @@
+import { z } from "zod"
+import {
+ PriceListCreateProductsSchema,
+ PriceListRulesSchema,
+} from "@pages/price-lists/common/schemas"
+
+const PricingCustomerGroupsArray = z.array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ })
+)
+
+export type PricingCustomerGroupsArrayType = z.infer<
+ typeof PricingCustomerGroupsArray
+>
+
+export const PricingCreateSchema = z.object({
+ type: z.enum(["sale", "override"]),
+ status: z.enum(["draft", "active"]),
+ title: z.string().min(1),
+ description: z.string().min(1),
+ starts_at: z.date().nullish(),
+ ends_at: z.date().nullish(),
+ product_ids: z.array(z.object({ id: z.string() })).min(1),
+ products: PriceListCreateProductsSchema,
+ rules: PriceListRulesSchema.nullish(),
+})
+
+export type PricingCreateSchemaType = z.infer<typeof PricingCreateSchema>
+
+export const PricingDetailsSchema = PricingCreateSchema.pick({
+ type: true,
+ title: true,
+ description: true,
+ starts_at: true,
+ ends_at: true,
+ customer_group_ids: true,
+})
+
+export const PricingDetailsFields = Object.keys(
+ PricingDetailsSchema.shape
+) as (keyof typeof PricingDetailsSchema.shape)[]
+
+export const PricingProductsSchema = PricingCreateSchema.pick({
+ product_ids: true,
+})
+
+export const PricingProductsFields = Object.keys(
+ PricingProductsSchema.shape
+) as (keyof typeof PricingProductsSchema.shape)[]
+
+export const PricingPricesSchema = PricingCreateSchema.pick({
+ products: true,
+})
+
+export const PricingPricesFields = Object.keys(
+ PricingPricesSchema.shape
+) as (keyof typeof PricingPricesSchema.shape)[]
diff --git a/packages/vendor/src/pages/price-lists/index.tsx b/packages/vendor/src/pages/price-lists/index.tsx
new file mode 100644
index 000000000..2ce6820b2
--- /dev/null
+++ b/packages/vendor/src/pages/price-lists/index.tsx
@@ -0,0 +1,19 @@
+// Route: /price-lists
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { PriceListListTable } from "./_components/price-list-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("price_list.list.after"),
+ before: getWidgets("price_list.list.before"),
+ }}
+ >
+ <PriceListListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/breadcrumb.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/breadcrumb.tsx
new file mode 100644
index 000000000..ef9935015
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/breadcrumb.tsx
@@ -0,0 +1,30 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { useProductVariant } from "@hooks/api"
+import { VARIANT_DETAIL_FIELDS } from "./constants"
+
+type ProductVariantDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminProductVariantResponse>
+
+export const ProductVariantDetailBreadcrumb = (
+ props: ProductVariantDetailBreadcrumbProps
+) => {
+ const { product_id, variant_id } = props.params || {}
+
+ const { variant } = useProductVariant(
+ product_id!,
+ variant_id!,
+ {
+ fields: VARIANT_DETAIL_FIELDS,
+ },
+ {
+ initialData: props.data,
+ enabled: Boolean(product_id) && Boolean(variant_id),
+ }
+ )
+ if (!variant) {
+ return null
+ }
+
+ return <span>{variant.title}</span>
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/index.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/index.ts
new file mode 100644
index 000000000..2ca370342
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./variant-general-section"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/variant-general-section.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/variant-general-section.tsx
new file mode 100644
index 000000000..9cf0f4d67
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-general-section/variant-general-section.tsx
@@ -0,0 +1,97 @@
+import { Component, PencilSquare, Trash } from "@medusajs/icons"
+import { Badge, Container, Heading, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDeleteVariant } from "@hooks/api/products"
+import { ExtendedAdminProductVariant } from "@custom-types/products"
+
+type VariantGeneralSectionProps = {
+ variant: ExtendedAdminProductVariant
+}
+
+export function VariantGeneralSection({ variant }: VariantGeneralSectionProps) {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const hasInventoryKit = variant.inventory && variant.inventory.length > 1
+
+ const { mutateAsync } = useDeleteVariant(variant.product_id!, variant.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("products.variant.deleteWarning", {
+ title: variant.title,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ navigate("..", { replace: true })
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <div className="flex items-center gap-2">
+ <Heading>{variant.title}</Heading>
+ {hasInventoryKit && (
+ <span className="text-ui-fg-muted font-normal">
+ <Component />
+ </span>
+ )}
+ </div>
+ <span className="text-ui-fg-subtle txt-small mt-2">
+ {t("labels.productVariant")}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-4">
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "edit",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+
+ <SectionRow title={t("fields.sku")} value={variant.sku} />
+ {variant.options?.map((o) => (
+ <SectionRow
+ key={o.id}
+ title={o.option?.title!}
+ value={<Badge size="2xsmall">{o.value}</Badge>}
+ />
+ ))}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/index.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/index.ts
new file mode 100644
index 000000000..0254a9eb0
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/index.ts
@@ -0,0 +1 @@
+export * from "./variant-inventory-section"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/inventory-actions.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/inventory-actions.tsx
new file mode 100644
index 000000000..07dc5b9e5
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/inventory-actions.tsx
@@ -0,0 +1,25 @@
+import { useTranslation } from "react-i18next"
+
+import { Buildings } from "@medusajs/icons"
+
+import { ActionMenu } from "@components/common/action-menu"
+
+export const InventoryActions = ({ item }: { item: string }) => {
+ const { t } = useTranslation()
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Buildings />,
+ label: t("products.variant.inventory.navigateToItem"),
+ to: `/inventory/${item}`,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/use-inventory-table-columns.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/use-inventory-table-columns.tsx
new file mode 100644
index 000000000..d8810bff4
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/use-inventory-table-columns.tsx
@@ -0,0 +1,55 @@
+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { ExtendedAdminProductVariant } from "@custom-types/products"
+
+export interface ExtendedInventoryItem {
+ id: string
+ required_quantity: number
+ variant: ExtendedAdminProductVariant
+}
+
+const columnHelper = createColumnHelper<ExtendedInventoryItem>()
+
+export const useInventoryTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("variant.title", {
+ header: t("fields.title"),
+ cell: ({ getValue }) => {
+ const title = getValue() as string
+
+ if (!title) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{title}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("variant.sku", {
+ header: t("fields.sku"),
+ cell: ({ getValue }) => {
+ const sku = getValue() as string
+
+ if (!sku) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{sku}</span>
+ </div>
+ )
+ },
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/variant-inventory-section.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/variant-inventory-section.tsx
new file mode 100644
index 000000000..5eaf3aa4b
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-inventory-section/variant-inventory-section.tsx
@@ -0,0 +1,73 @@
+import { useTranslation } from "react-i18next"
+
+import { Container, Heading } from "@medusajs/ui"
+
+import { _DataTable } from "@components/table/data-table"
+
+import { LinkButton } from "@components/common/link-button"
+import { useDataTable } from "@hooks/use-data-table"
+import {
+ ExtendedInventoryItem,
+ useInventoryTableColumns,
+} from "./use-inventory-table-columns"
+
+const PAGE_SIZE = 20
+
+type VariantInventorySectionProps = {
+ inventoryItems: ExtendedInventoryItem[]
+}
+
+export function VariantInventorySection({
+ inventoryItems,
+}: VariantInventorySectionProps) {
+ const { t } = useTranslation()
+
+ const columns = useInventoryTableColumns()
+
+ const { table } = useDataTable({
+ data: inventoryItems ?? [],
+ columns,
+ count: inventoryItems.length,
+ enablePagination: true,
+ getRowId: (row) => row?.variant?.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div className="flex items-center gap-2">
+ <Heading level="h2">{t("fields.inventoryItems")}</Heading>
+ </div>
+ </div>
+
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={inventoryItems.length}
+ navigateTo={(row) => `/inventory/${row.original.id}`}
+ />
+ </Container>
+ )
+}
+
+export function InventorySectionPlaceholder() {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div className="flex flex-col gap-1">
+ <Heading level="h2">{t("fields.inventoryItems")}</Heading>
+ <span className="txt-small text-ui-fg-subtle">
+ {t("products.variant.inventory.notManagedDesc")}
+ </span>
+ </div>
+ <div className="flex items-center gap-x-4">
+ <LinkButton to="edit">{t("products.variant.edit.header")}</LinkButton>
+ </div>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/index.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/index.ts
new file mode 100644
index 000000000..ff49335ae
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/index.ts
@@ -0,0 +1 @@
+export * from "./variant-prices-section"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/variant-prices-section.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/variant-prices-section.tsx
new file mode 100644
index 000000000..15364bc1a
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/components/variant-prices-section/variant-prices-section.tsx
@@ -0,0 +1,82 @@
+import { useState } from "react"
+import { useTranslation } from "react-i18next"
+
+import { CurrencyDollar } from "@medusajs/icons"
+import { Button, Container, Heading } from "@medusajs/ui"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { NoRecords } from "@components/common/empty-table-content"
+import { getLocaleAmount } from "@lib/money-amount-helpers"
+import { ExtendedAdminProductVariant } from "@custom-types/products"
+
+type VariantPricesSectionProps = {
+ variant: ExtendedAdminProductVariant
+}
+
+export function VariantPricesSection({ variant }: VariantPricesSectionProps) {
+ const { t } = useTranslation()
+ const prices = variant.prices
+ ?.filter((p) => !Object.keys(p.rules || {}).length)
+ .sort((p1, p2) => p1.currency_code?.localeCompare(p2.currency_code))
+
+ const hasPrices = !!prices?.length
+ const [pageSize, setPageSize] = useState(3)
+ const displayPrices = prices?.slice(0, pageSize)
+
+ const onShowMore = () => {
+ setPageSize(pageSize + 3)
+ }
+
+ return (
+ <Container className="flex flex-col divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("labels.prices")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: `/products/${variant.product_id}/variants/${variant.id}/prices`,
+ icon: <CurrencyDollar />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ {!hasPrices && <NoRecords className="h-60" />}
+ {displayPrices?.map((price) => {
+ return (
+ <div
+ key={price.id}
+ className="txt-small text-ui-fg-subtle flex justify-between px-6 py-4"
+ >
+ <span className="font-medium">
+ {price.currency_code.toUpperCase()}
+ </span>
+ <span>{getLocaleAmount(price.amount, price.currency_code)}</span>
+ </div>
+ )
+ })}
+ {hasPrices && (
+ <div className="txt-small text-ui-fg-subtle flex items-center justify-between px-6 py-4">
+ <span className="font-medium">
+ {t("products.variant.pricesPagination", {
+ total: prices.length,
+ current: Math.min(pageSize, prices.length),
+ })}
+ </span>
+ <Button
+ onClick={onShowMore}
+ disabled={pageSize >= prices.length}
+ className="-mr-3 text-blue-500"
+ variant="transparent"
+ >
+ {t("actions.showMore")}
+ </Button>
+ </div>
+ )}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/constants.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/constants.ts
new file mode 100644
index 000000000..f5304687a
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/constants.ts
@@ -0,0 +1,2 @@
+export const VARIANT_DETAIL_FIELDS =
+ "*inventory_items,*inventory_items.inventory,*inventory_items.inventory.location_levels,*options,*options.option,*prices,*prices.price_rules"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/index.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/index.ts
new file mode 100644
index 000000000..73598d513
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/index.ts
@@ -0,0 +1,3 @@
+export { ProductVariantDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
+export { variantLoader as loader } from "./loader"
+export { ProductVariantDetail as Component } from "./product-variant-detail"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/loader.ts b/packages/vendor/src/pages/product-variants/product-variant-detail/loader.ts
new file mode 100644
index 000000000..001508897
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/loader.ts
@@ -0,0 +1,26 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { variantsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { VARIANT_DETAIL_FIELDS } from "./constants"
+
+const variantDetailQuery = (productId: string, variantId: string) => ({
+ queryKey: variantsQueryKeys.detail(variantId, {
+ fields: VARIANT_DETAIL_FIELDS,
+ }),
+ queryFn: async () =>
+ await fetchQuery(`/vendor/products/${productId}`, {
+ method: "GET",
+ // query: { fields: VARIANT_DETAIL_FIELDS },
+ }),
+})
+
+export const variantLoader = async ({ params }: LoaderFunctionArgs) => {
+ const productId = params.product_id
+ const variantId = params.variant_id
+
+ const query = variantDetailQuery(productId!, variantId!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-detail/product-variant-detail.tsx b/packages/vendor/src/pages/product-variants/product-variant-detail/product-variant-detail.tsx
new file mode 100644
index 000000000..64608fd4e
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-detail/product-variant-detail.tsx
@@ -0,0 +1,66 @@
+import { useParams } from "react-router-dom"
+
+import { useProduct } from "@hooks/api/products"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { VariantGeneralSection } from "./components/variant-general-section"
+import {
+ InventorySectionPlaceholder,
+ VariantInventorySection,
+} from "./components/variant-inventory-section"
+import { VariantPricesSection } from "./components/variant-prices-section"
+
+export const ProductVariantDetail = () => {
+ const { product_id, variant_id } = useParams()
+ const { product, isLoading, isError, error } = useProduct(product_id!, {
+ fields: "*variants.inventory_items",
+ })
+
+ const variant = product?.variants?.find((item) => item.id === variant_id)
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !variant) {
+ return <TwoColumnPageSkeleton mainSections={2} sidebarSections={1} />
+ }
+
+ if (isError) {
+ throw error
+ }
+ return (
+ <TwoColumnPage
+ data={variant}
+ hasOutlet
+ widgets={{
+ after: getWidgets("product_variant.details.after"),
+ before: getWidgets("product_variant.details.before"),
+ sideAfter: getWidgets("product_variant.details.side.after"),
+ sideBefore: getWidgets("product_variant.details.side.before"),
+ }}
+ >
+ <TwoColumnPage.Main>
+ <VariantGeneralSection variant={variant} />
+ {!variant.manage_inventory ? (
+ <InventorySectionPlaceholder />
+ ) : (
+ variant.inventory_items && (
+ <VariantInventorySection
+ inventoryItems={variant.inventory_items.map((i) => {
+ return {
+ id: i.inventory_item_id,
+ required_quantity: i.required_quantity,
+ variant,
+ }
+ })}
+ />
+ )
+ )}
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <VariantPricesSection variant={variant} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/index.ts b/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/index.ts
new file mode 100644
index 000000000..3612fd815
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-edit-variant-form"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/product-edit-variant-form.tsx b/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/product-edit-variant-form.tsx
new file mode 100644
index 000000000..29aa92cfa
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-edit/components/product-edit-variant-form/product-edit-variant-form.tsx
@@ -0,0 +1,386 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Divider, Heading, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { CountrySelect } from "@components/inputs/country-select"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProductVariant } from "@hooks/api/products"
+import {
+ transformNullableFormData,
+ transformNullableFormNumber,
+} from "@lib/form-helpers"
+import { optionalInt } from "@lib/validation"
+import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"
+
+type ProductEditVariantFormProps = {
+ product: ExtendedAdminProduct
+ variant?: ExtendedAdminProductVariant
+}
+
+const ProductEditVariantSchema = z.object({
+ title: z.string().min(1),
+ material: z.string().optional(),
+ sku: z.string().optional(),
+ ean: z.string().optional(),
+ upc: z.string().optional(),
+ barcode: z.string().optional(),
+ manage_inventory: z.boolean(),
+ allow_backorder: z.boolean(),
+ weight: optionalInt,
+ height: optionalInt,
+ width: optionalInt,
+ length: optionalInt,
+ mid_code: z.string().optional(),
+ hs_code: z.string().optional(),
+ origin_country: z.string().optional(),
+ options: z.record(z.string()),
+})
+
+// TODO: Either pass option ID or make the backend handle options constraints differently to handle the lack of IDs
+export const ProductEditVariantForm = ({
+ variant,
+ product,
+}: ProductEditVariantFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const defaultOptions = product.options?.reduce((acc: any, option: any) => {
+ const varOpt = variant?.options?.find((o: any) => o.option_id === option.id)
+ acc[option.title] = varOpt?.value
+ return acc
+ }, {})
+
+ const form = useForm<z.infer<typeof ProductEditVariantSchema>>({
+ defaultValues: {
+ title: variant?.title || "",
+ material: variant?.material || "",
+ sku: variant?.sku || undefined,
+ ean: variant?.ean || "",
+ upc: variant?.upc || "",
+ barcode: variant?.barcode || "",
+ manage_inventory: true,
+ allow_backorder: true,
+ weight: variant?.weight || "",
+ height: variant?.height || "",
+ width: variant?.width || "",
+ length: variant?.length || "",
+ mid_code: variant?.mid_code || "",
+ hs_code: variant?.hs_code || "",
+ origin_country: variant?.origin_country || "",
+ options: defaultOptions,
+ },
+ resolver: zodResolver(ProductEditVariantSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateProductVariant(
+ variant?.product_id!,
+ variant?.id!
+ )
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const {
+ title,
+ weight,
+ height,
+ width,
+ length,
+ allow_backorder,
+ manage_inventory,
+ options,
+ ...optional
+ } = data
+
+ const nullableData = transformNullableFormData(optional)
+
+ await mutateAsync(
+ {
+ weight: transformNullableFormNumber(weight),
+ height: transformNullableFormNumber(height),
+ width: transformNullableFormNumber(width),
+ length: transformNullableFormNumber(length),
+ title,
+ allow_backorder,
+ manage_inventory,
+ options,
+ ...nullableData,
+ },
+ {
+ onSuccess: () => {
+ handleSuccess("../")
+ toast.success(t("products.variant.edit.success"))
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex size-full flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex size-full flex-col gap-y-8 overflow-auto">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="material"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.material")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ {product.options?.map((option: any) => {
+ return (
+ <Form.Field
+ key={option.id}
+ control={form.control}
+ name={`options.${option.title}`}
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{option.title}</Form.Label>
+ <Form.Control>
+ <Combobox
+ value={value}
+ onChange={(v) => {
+ onChange(v)
+ }}
+ {...field}
+ options={option.values.map((v: any) => ({
+ label: v.value,
+ value: v.value,
+ }))}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ )
+ })}
+ </div>
+ <Divider />
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-4">
+ <Heading level="h2">
+ {t("products.variant.inventory.header")}
+ </Heading>
+ <Form.Field
+ control={form.control}
+ name="sku"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.sku")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="ean"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.ean")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="upc"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.upc")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="barcode"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.barcode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <Divider />
+ <div className="flex flex-col gap-y-4">
+ <Heading level="h2">{t("products.attributes")}</Heading>
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.weight")}</Form.Label>
+ <Form.Control>
+ <Input type="number" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="width"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.width")}</Form.Label>
+ <Form.Control>
+ <Input type="number" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.length")}</Form.Label>
+ <Form.Control>
+ <Input type="number" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.height")}</Form.Label>
+ <Form.Control>
+ <Input type="number" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.midCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.hsCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("fields.countryOfOrigin")}
+ </Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-edit/index.ts b/packages/vendor/src/pages/product-variants/product-variant-edit/index.ts
new file mode 100644
index 000000000..68059d763
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-edit/index.ts
@@ -0,0 +1,2 @@
+export { ProductVariantEdit as Component } from "./product-variant-edit"
+export { editProductVariantLoader as loader } from "./loader"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-edit/loader.ts b/packages/vendor/src/pages/product-variants/product-variant-edit/loader.ts
new file mode 100644
index 000000000..2074716a3
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-edit/loader.ts
@@ -0,0 +1,42 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { productVariantQueryKeys } from "@hooks/api"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const queryFn = async (id: string, variantId: string) => {
+ const { product } = await fetchQuery(`/vendor/products/${id}`, {
+ method: "GET",
+ query: { fields: "*variants" },
+ })
+
+ const variant = product.variants.find(
+ ({ id }: { id: string }) => id === variantId
+ )
+
+ return { variant }
+}
+
+const editProductVariantQuery = (id: string, variantId: string) => ({
+ queryKey: productVariantQueryKeys.detail(variantId),
+ queryFn: async () => queryFn(id, variantId),
+})
+
+export const editProductVariantLoader = async ({
+ params,
+ request,
+}: LoaderFunctionArgs) => {
+ const id = params.product_id
+
+ const searchParams = new URL(request.url).searchParams
+ const searchVariantId = searchParams.get("variant_id")
+
+ const variantId = params.variant_id || searchVariantId
+
+ const query = editProductVariantQuery(id!, variantId || searchVariantId!)
+
+ return (
+ queryClient.getQueryData<ReturnType<typeof queryFn>>(query.queryKey) ??
+ (await queryClient.fetchQuery(query))
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-edit/product-variant-edit.tsx b/packages/vendor/src/pages/product-variants/product-variant-edit/product-variant-edit.tsx
new file mode 100644
index 000000000..4b62c81f6
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-edit/product-variant-edit.tsx
@@ -0,0 +1,39 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { ProductEditVariantForm } from "./components/product-edit-variant-form"
+
+export const ProductVariantEdit = () => {
+ const { t } = useTranslation()
+ const { product_id, variant_id } = useParams()
+
+ const {
+ product,
+ isPending: isProductPending,
+ isError: isProductError,
+ error: productError,
+ } = useProduct(product_id!, {
+ fields: "*variants",
+ })
+
+ const variant = product?.variants?.find(
+ (variant) => variant.id === variant_id
+ )
+
+ const ready = !isProductPending && !!product
+
+ if (isProductError) {
+ throw productError
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("products.variant.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <ProductEditVariantForm variant={variant} product={product} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/index.ts b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/index.ts
new file mode 100644
index 000000000..9abc2a0eb
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/index.ts
@@ -0,0 +1 @@
+export * from "./manage-variant-inventory-items-form"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/manage-variant-inventory-items-form.tsx b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/manage-variant-inventory-items-form.tsx
new file mode 100644
index 000000000..d8a1d4080
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/components/manage-variant-inventory-items-form/manage-variant-inventory-items-form.tsx
@@ -0,0 +1,305 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { XMarkMini } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Heading, IconButton, Input, Label, toast } from "@medusajs/ui"
+import i18next from "i18next"
+import { useFieldArray, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useProductVariantsInventoryItemsBatch } from "@hooks/api/products"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { castNumber } from "@lib/cast-number"
+import { sdk } from "@lib/client"
+import { ExtendedAdminProductVariant } from "@custom-types/products"
+
+type ManageVariantInventoryItemsFormProps = {
+ variant: ExtendedAdminProductVariant
+}
+
+const ManageVariantInventoryItemsSchema = zod.object({
+ inventory: zod.array(
+ zod
+ .object({
+ inventory_item_id: zod
+ .string()
+ .min(1, i18next.t("products.variant.inventory.validation.itemId")),
+ required_quantity: zod.union([zod.number(), zod.string()]),
+ })
+ .superRefine((data, ctx) => {
+ const quantity = data.required_quantity
+ ? castNumber(data.required_quantity)
+ : 0
+
+ if (quantity < 1) {
+ ctx.addIssue({
+ code: zod.ZodIssueCode.custom,
+ message: i18next.t(
+ "products.variant.inventory.validation.quantity"
+ ),
+ path: ["required_quantity"],
+ })
+ }
+ })
+ ),
+})
+
+export function ManageVariantInventoryItemsForm({
+ variant,
+}: ManageVariantInventoryItemsFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof ManageVariantInventoryItemsSchema>>({
+ defaultValues: {
+ inventory: variant.inventory_items?.length
+ ? variant.inventory_items!.map((i) => ({
+ required_quantity: i.required_quantity,
+ inventory_item_id: i.inventory?.id || i.inventory_item_id,
+ }))
+ : [
+ {
+ inventory_item_id: "",
+ required_quantity: "",
+ },
+ ],
+ },
+ resolver: zodResolver(ManageVariantInventoryItemsSchema),
+ })
+
+ const inventory = useFieldArray({
+ control: form.control,
+ name: `inventory`,
+ })
+
+ const hasKit = inventory.fields.length > 1
+
+ const items = useComboboxData({
+ queryKey: ["inventory_items"],
+ queryFn: (params) => sdk.admin.inventoryItem.list(params),
+ getOptions: (data) =>
+ data.inventory_items.map((item) => ({
+ label: item.title || item.sku!,
+ value: item.id!,
+ })),
+ defaultValue: variant.inventory_items?.[0]?.inventory_item_id,
+ })
+
+ const { mutateAsync, isPending } = useProductVariantsInventoryItemsBatch(
+ variant?.product_id!
+ )
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const existingItems: Record<string, number> = {}
+ const selectedItems: Record<string, boolean> = {}
+
+ variant.inventory_items?.forEach((i) => {
+ if (i.inventory?.id) {
+ existingItems[i.inventory.id] = i.required_quantity
+ }
+ })
+
+ values.inventory.forEach((i) => (selectedItems[i.inventory_item_id] = true))
+
+ const payload: HttpTypes.AdminBatchProductVariantInventoryItemRequest = {}
+
+ values.inventory.forEach((v) => {
+ if (v.inventory_item_id in existingItems) {
+ if (v.required_quantity !== existingItems[v.inventory_item_id]) {
+ payload.update = payload.update || []
+
+ payload.update.push({
+ required_quantity: castNumber(v.required_quantity),
+ inventory_item_id: v.inventory_item_id,
+ variant_id: variant.id,
+ })
+ }
+ } else {
+ payload.create = payload.create || []
+
+ payload.create.push({
+ required_quantity: castNumber(v.required_quantity),
+ inventory_item_id: v.inventory_item_id,
+ variant_id: variant.id,
+ })
+ }
+ })
+
+ variant.inventory_items?.forEach((i) => {
+ if (i.inventory?.id && !(i.inventory.id in selectedItems)) {
+ payload.delete = payload.delete || []
+
+ payload.delete.push({
+ inventory_item_id: i.inventory.id,
+ variant_id: variant.id,
+ })
+ }
+ })
+
+ await mutateAsync(payload, {
+ onSuccess: () => {
+ toast.success(t("products.variant.inventory.toast.itemsManageSuccess"))
+ handleSuccess()
+ },
+ onError: (err) => {
+ toast.error(err.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex justify-center">
+ <div className="flex w-full flex-col gap-y-8 px-6 pt-12 md:w-[720px] md:pt-24">
+ <Heading>
+ {t(
+ hasKit
+ ? "products.create.inventory.heading"
+ : "fields.inventoryItems"
+ )}
+ </Heading>
+
+ <div className="grid gap-y-4">
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex flex-col">
+ <Form.Label>{variant.title}</Form.Label>
+ <Form.Hint>
+ {t(
+ hasKit
+ ? "products.create.inventory.label"
+ : "fields.inventoryItem"
+ )}
+ </Form.Hint>
+ </div>
+ <Button
+ size="small"
+ variant="secondary"
+ type="button"
+ onClick={() => {
+ inventory.append({
+ inventory_item_id: "",
+ required_quantity: "",
+ })
+ }}
+ >
+ {t("actions.add")}
+ </Button>
+ </div>
+ {inventory.fields.map((inventoryItem, inventoryIndex) => (
+ <li
+ key={inventoryItem.id}
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-center gap-1.5 rounded-xl p-1.5"
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`inventory.${inventoryIndex}.inventory_item_id`}
+ >
+ {t("fields.item")}
+ </Label>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name={`inventory.${inventoryIndex}.inventory_item_id`}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={items.options}
+ searchValue={items.searchValue}
+ onSearchValueChange={items.onSearchValueChange}
+ fetchNextPage={items.fetchNextPage}
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ placeholder={t(
+ "products.create.inventory.itemPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`inventory.${inventoryIndex}.required_quantity`}
+ >
+ {t("fields.quantity")}
+ </Label>
+ </div>
+ <Form.Field
+ control={form.control}
+ name={`inventory.${inventoryIndex}.required_quantity`}
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ type="number"
+ className="bg-ui-bg-field-component"
+ min={0}
+ value={value}
+ onChange={onChange}
+ {...field}
+ placeholder={t(
+ "products.create.inventory.quantityPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ onClick={() => inventory.remove(inventoryIndex)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ ))}
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/index.ts b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/index.ts
new file mode 100644
index 000000000..0b36ceac0
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/index.ts
@@ -0,0 +1 @@
+export { ProductVariantManageInventoryItems as Component } from "./product-variant-manage-inventory-items"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/product-variant-manage-inventory-items.tsx b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/product-variant-manage-inventory-items.tsx
new file mode 100644
index 000000000..b43e13c38
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-manage-inventory-items/product-variant-manage-inventory-items.tsx
@@ -0,0 +1,34 @@
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useProductVariant } from "@hooks/api/products"
+import { ExtendedAdminProductVariant } from "@custom-types/products"
+import { VARIANT_DETAIL_FIELDS } from "../product-variant-detail/constants.ts"
+import { ManageVariantInventoryItemsForm } from "./components/manage-variant-inventory-items-form/index.ts"
+
+export function ProductVariantManageInventoryItems() {
+ const { id, variant_id } = useParams()
+
+ const {
+ variant,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useProductVariant(id!, variant_id!, {
+ fields: VARIANT_DETAIL_FIELDS,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ const extendedVariant = variant as ExtendedAdminProductVariant
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && variant && variant.inventory_items && (
+ <ManageVariantInventoryItemsForm variant={extendedVariant} />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/product-variants/product-variant-metadata/index.ts b/packages/vendor/src/pages/product-variants/product-variant-metadata/index.ts
new file mode 100644
index 000000000..b0e173a05
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-metadata/index.ts
@@ -0,0 +1 @@
+export { ProductVariantMetadata as Component } from "./product-variant-metadata"
diff --git a/packages/vendor/src/pages/product-variants/product-variant-metadata/product-variant-metadata.tsx b/packages/vendor/src/pages/product-variants/product-variant-metadata/product-variant-metadata.tsx
new file mode 100644
index 000000000..9f8c2e01a
--- /dev/null
+++ b/packages/vendor/src/pages/product-variants/product-variant-metadata/product-variant-metadata.tsx
@@ -0,0 +1,30 @@
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form/metadata-form"
+import { useProductVariant, useUpdateProductVariant } from "@hooks/api"
+
+export const ProductVariantMetadata = () => {
+ const { id, variant_id } = useParams()
+
+ const { variant, isPending, isError, error } = useProductVariant(
+ id!,
+ variant_id!
+ )
+
+ const { mutateAsync, isPending: isMutating } = useUpdateProductVariant(
+ id!,
+ variant_id!
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <MetadataForm
+ metadata={variant?.metadata}
+ hook={mutateAsync}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/index.ts b/packages/vendor/src/pages/products/[id]/_components/index.ts
new file mode 100644
index 000000000..082b63ff9
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/index.ts
@@ -0,0 +1,9 @@
+export * from "./product-additional-attribute-section"
+export * from "./product-attribute-section"
+export * from "./product-general-section"
+export * from "./product-media-section"
+export * from "./product-option-section"
+export * from "./product-organization-section"
+export * from "./product-sales-channel-section"
+export * from "./product-shipping-profile-section"
+export * from "./product-variant-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-additional-attribute-section/ProductAdditionalAttributesSection.tsx b/packages/vendor/src/pages/products/[id]/_components/product-additional-attribute-section/ProductAdditionalAttributesSection.tsx
new file mode 100644
index 000000000..e8c3f114a
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-additional-attribute-section/ProductAdditionalAttributesSection.tsx
@@ -0,0 +1,60 @@
+import { Container, Heading } from "@medusajs/ui"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { PencilSquare } from "@medusajs/icons"
+import { ActionMenu } from "@components/common/action-menu"
+import { useProductAttributes } from "@hooks/api/products"
+import { SectionRow } from "@components/common/section"
+import { useMemo } from "react"
+
+type ProductAttributeSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductAdditionalAttributesSection = ({
+ product,
+}: ProductAttributeSectionProps) => {
+ const { attributes, isLoading } = useProductAttributes(product.id)
+
+ const attributeList = useMemo(() => {
+ return attributes?.map((attribute) => {
+ const value =
+ product.attribute_values?.find((av) => av && av.attribute_id === attribute.id)
+ ?.value || "-"
+ return {
+ ...attribute,
+ value,
+ }
+ })
+ }, [attributes, product.attribute_values])
+
+ if (isLoading) return
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">Attributes</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: "Edit",
+ to: "additional-attributes",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ {attributeList?.map((attribute) => (
+ <SectionRow
+ key={attribute.id}
+ title={attribute.name}
+ value={attribute.value}
+ tooltip={attribute.description}
+ />
+ ))}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/index.ts
new file mode 100644
index 000000000..7619bb30d
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-attribute-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/product-attribute-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/product-attribute-section.tsx
new file mode 100644
index 000000000..21a1b01cf
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-attribute-section/product-attribute-section.tsx
@@ -0,0 +1,53 @@
+import { PencilSquare } from "@medusajs/icons"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDashboardExtension } from "@/extensions"
+import { getFormattedCountry } from "@lib/addresses"
+
+type ProductAttributeSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductAttributeSection = ({
+ product,
+}: ProductAttributeSectionProps) => {
+ const { t } = useTranslation()
+ const { getDisplays } = useDashboardExtension()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.attributes")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "attributes",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <SectionRow title={t("fields.height")} value={product.height} />
+ <SectionRow title={t("fields.width")} value={product.width} />
+ <SectionRow title={t("fields.length")} value={product.length} />
+ <SectionRow title={t("fields.weight")} value={product.weight} />
+ <SectionRow title={t("fields.midCode")} value={product.mid_code} />
+ <SectionRow title={t("fields.hsCode")} value={product.hs_code} />
+ <SectionRow
+ title={t("fields.countryOfOrigin")}
+ value={getFormattedCountry(product.origin_country)}
+ />
+ {getDisplays("product", "attributes").map((Component, i) => {
+ return <Component key={i} data={product} />
+ })}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-general-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-general-section/index.ts
new file mode 100644
index 000000000..77fb9614c
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-general-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-general-section/product-general-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-general-section/product-general-section.tsx
new file mode 100644
index 000000000..92df6a921
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-general-section/product-general-section.tsx
@@ -0,0 +1,109 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Container, Heading, StatusBadge, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDashboardExtension } from "@/extensions"
+import { useDeleteProduct } from "@hooks/api/products"
+
+const productStatusColor = (status: string) => {
+ switch (status) {
+ case "draft":
+ return "grey"
+ case "proposed":
+ return "orange"
+ case "published":
+ return "green"
+ case "rejected":
+ return "red"
+ default:
+ return "grey"
+ }
+}
+
+type ProductGeneralSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductGeneralSection = ({
+ product,
+}: ProductGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+ const { getDisplays } = useDashboardExtension()
+
+ const displays = getDisplays("product", "general")
+
+ const { mutateAsync } = useDeleteProduct(product.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("products.deleteWarning", {
+ title: product.title,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ navigate("..")
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{product.title}</Heading>
+ <div className="flex items-center gap-x-4">
+ <StatusBadge color={productStatusColor(product.status)}>
+ {t(`products.productStatus.${product.status}`)}
+ </StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "edit",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+
+ <SectionRow title={t("fields.description")} value={product.description} />
+ {/* <SectionRow title={t("fields.subtitle")} value={product.subtitle} /> */}
+ <SectionRow title={t("fields.handle")} value={`/${product.handle}`} />
+ <SectionRow
+ title={t("fields.discountable")}
+ value={product.discountable ? t("fields.true") : t("fields.false")}
+ />
+ {displays.map((Component, index) => {
+ return <Component key={index} data={product} />
+ })}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-media-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-media-section/index.ts
new file mode 100644
index 000000000..cd4b42690
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-media-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-media-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-media-section/product-media-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-media-section/product-media-section.tsx
new file mode 100644
index 000000000..1b4dd7d45
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-media-section/product-media-section.tsx
@@ -0,0 +1,214 @@
+import { useState } from 'react';
+
+import { PencilSquare, ThumbnailBadge } from '@medusajs/icons';
+import {
+ Button,
+ Checkbox,
+ clx,
+ CommandBar,
+ Container,
+ Heading,
+ Text,
+ Tooltip,
+ usePrompt
+} from '@medusajs/ui';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useUpdateProduct } from "@hooks/api/products"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type ProductMedisaSectionProps = {
+ product: ExtendedAdminProduct;
+};
+
+export const ProductMediaSection = ({ product }: ProductMedisaSectionProps) => {
+ const { t } = useTranslation();
+ const prompt = usePrompt();
+ const [selection, setSelection] = useState<Record<string, boolean>>({});
+
+ const media = getMedia(product);
+
+ const handleCheckedChange = (id: string) => {
+ setSelection(prev => {
+ if (prev[id]) {
+ const { [id]: _, ...rest } = prev;
+ return rest;
+ } else {
+ return { ...prev, [id]: true };
+ }
+ });
+ };
+
+ const { mutateAsync } = useUpdateProduct(product.id);
+
+ const handleDelete = async () => {
+ const ids = Object.keys(selection);
+ const includingThumbnail = ids.some(id => media.find(m => m.id === id)?.isThumbnail);
+
+ const res = await prompt({
+ title: t('general.areYouSure'),
+ description: includingThumbnail
+ ? t('products.media.deleteWarningWithThumbnail', {
+ count: ids.length
+ })
+ : t('products.media.deleteWarning', {
+ count: ids.length
+ }),
+ confirmText: t('actions.delete'),
+ cancelText: t('actions.cancel')
+ });
+
+ if (!res) {
+ return;
+ }
+
+ const mediaToKeep = product.images?.filter(i => !ids.includes(i.id)).map(i => ({ url: i.url }));
+
+ await mutateAsync(
+ {
+ images: mediaToKeep,
+ thumbnail: includingThumbnail ? '' : undefined
+ },
+ {
+ onSuccess: () => {
+ setSelection({});
+ }
+ }
+ );
+ };
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t('products.media.label')}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t('actions.edit'),
+ to: 'media?view=edit',
+ icon: <PencilSquare />
+ }
+ ]
+ }
+ ]}
+ />
+ </div>
+ {media.length > 0 ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(96px,1fr))] gap-4 px-6 py-4">
+ {media.map((i, index) => {
+ const isSelected = selection[i.id];
+
+ return (
+ <div
+ className="group relative aspect-square size-full cursor-pointer overflow-hidden rounded-[8px] shadow-elevation-card-rest transition-fg hover:shadow-elevation-card-hover"
+ key={i.id}
+ >
+ <div
+ className={clx(
+ 'invisible absolute right-2 top-2 opacity-0 transition-fg group-hover:visible group-hover:opacity-100',
+ {
+ 'visible opacity-100': isSelected
+ }
+ )}
+ >
+ <Checkbox
+ checked={selection[i.id] || false}
+ onCheckedChange={() => handleCheckedChange(i.id)}
+ />
+ </div>
+ {i.isThumbnail && (
+ <div className="absolute left-2 top-2">
+ <Tooltip content={t('fields.thumbnail')}>
+ <ThumbnailBadge />
+ </Tooltip>
+ </div>
+ )}
+ <Link
+ to={`media`}
+ state={{ curr: index }}
+ >
+ <img
+ src={i.url}
+ alt={`${product.title} image`}
+ className="size-full object-cover"
+ />
+ </Link>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="flex flex-col items-center gap-y-4 pb-8 pt-6">
+ <div className="flex flex-col items-center">
+ <Text
+ size="small"
+ leading="compact"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ >
+ {t('products.media.emptyState.header')}
+ </Text>
+ <Text
+ size="small"
+ className="text-ui-fg-muted"
+ >
+ {t('products.media.emptyState.description')}
+ </Text>
+ </div>
+ <Button
+ size="small"
+ variant="secondary"
+ asChild
+ >
+ <Link to="media?view=edit">{t('products.media.emptyState.action')}</Link>
+ </Button>
+ </div>
+ )}
+ <CommandBar open={!!Object.keys(selection).length}>
+ <CommandBar.Bar>
+ <CommandBar.Value>
+ {t('general.countSelected', {
+ count: Object.keys(selection).length
+ })}
+ </CommandBar.Value>
+ <CommandBar.Seperator />
+ <CommandBar.Command
+ action={handleDelete}
+ label={t('actions.delete')}
+ shortcut="d"
+ />
+ </CommandBar.Bar>
+ </CommandBar>
+ </Container>
+ );
+};
+
+type Media = {
+ id: string;
+ url: string;
+ isThumbnail: boolean;
+};
+
+const getMedia = (product: ExtendedAdminProduct) => {
+ const { images = [], thumbnail } = product;
+
+ const media: Media[] = (images || []).map(image => ({
+ id: image.id,
+ url: image.url,
+ isThumbnail: image.url === thumbnail
+ }));
+
+ if (thumbnail && !media.some(mediaItem => mediaItem.url === thumbnail)) {
+ media.unshift({
+ id: 'img_thumbnail',
+ url: thumbnail,
+ isThumbnail: true
+ });
+ }
+
+ return media;
+};
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-option-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-option-section/index.ts
new file mode 100644
index 000000000..cccdf5cd7
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-option-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-option-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-option-section/product-option-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-option-section/product-option-section.tsx
new file mode 100644
index 000000000..e25d99c7a
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-option-section/product-option-section.tsx
@@ -0,0 +1,114 @@
+import { PencilSquare, Plus, Trash } from "@medusajs/icons"
+import { Badge, Container, Heading, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDeleteProductOption } from "@hooks/api/products"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { HttpTypes } from "@medusajs/types"
+
+const OptionActions = ({
+ product,
+ option,
+}: {
+ product: ExtendedAdminProduct
+ option: HttpTypes.AdminProductOption
+}) => {
+ const { t } = useTranslation()
+ const { mutateAsync } = useDeleteProductOption(product.id, option.id)
+ const prompt = usePrompt()
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("products.options.deleteWarning", {
+ title: option.title,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync()
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: `options/${option.id}/edit`,
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+type ProductOptionSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductOptionSection = ({
+ product,
+}: ProductOptionSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.options.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.create"),
+ to: "options/create",
+ icon: <Plus />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ {product.options?.map((option) => {
+ return (
+ <SectionRow
+ title={option.title}
+ key={option.id}
+ value={option.values?.map((val) => {
+ return (
+ <Badge
+ key={val.value}
+ size="2xsmall"
+ className="flex min-w-[20px] items-center justify-center"
+ >
+ {val.value}
+ </Badge>
+ )
+ })}
+ actions={<OptionActions product={product} option={option} />}
+ />
+ )
+ })}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-organization-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-organization-section/index.ts
new file mode 100644
index 000000000..7457b7c87
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-organization-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-organization-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-organization-section/product-organization-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-organization-section/product-organization-section.tsx
new file mode 100644
index 000000000..906ad23b8
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-organization-section/product-organization-section.tsx
@@ -0,0 +1,107 @@
+import { PencilSquare } from "@medusajs/icons"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Badge, Container, Heading, Tooltip } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDashboardExtension } from "@/extensions"
+
+type ProductOrganizationSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductOrganizationSection = ({
+ product,
+}: ProductOrganizationSectionProps) => {
+ const { t } = useTranslation()
+ const { getDisplays } = useDashboardExtension()
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.organization.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "organization",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ <SectionRow
+ title={t("fields.tags")}
+ value={
+ product.tags?.length
+ ? product.tags.map((tag) => (
+ <OrganizationTag
+ key={tag.id}
+ label={tag.value}
+ to={`/settings/product-tags/${tag.id}`}
+ />
+ ))
+ : undefined
+ }
+ />
+ <SectionRow
+ title={t("fields.type")}
+ value={
+ product.type ? (
+ <OrganizationTag
+ label={product.type.value}
+ to={`/settings/product-types/${product.type_id}`}
+ />
+ ) : undefined
+ }
+ />
+
+ <SectionRow
+ title={t("fields.collection")}
+ value={
+ product.collection ? (
+ <OrganizationTag
+ label={product.collection.title}
+ to={`/collections/${product.collection.id}`}
+ />
+ ) : undefined
+ }
+ />
+
+ <SectionRow
+ title={t("fields.categories")}
+ value={
+ product.categories?.length
+ ? product.categories.map((pcat) => (
+ <OrganizationTag
+ key={pcat.id}
+ label={pcat.name}
+ to={`/categories/${pcat.id}`}
+ />
+ ))
+ : undefined
+ }
+ />
+
+ {getDisplays("product", "organize").map((Component, i) => {
+ return <Component key={i} data={product} />
+ })}
+ </Container>
+ )
+}
+
+const OrganizationTag = ({ label, to }: { label: string; to: string }) => {
+ return (
+ <Tooltip content={label}>
+ <Badge size="2xsmall" className="block w-fit truncate" asChild>
+ <Link to={to}>{label}</Link>
+ </Badge>
+ </Tooltip>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/index.ts
new file mode 100644
index 000000000..5dbf716e8
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-sales-channel-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/product-sales-channel-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/product-sales-channel-section.tsx
new file mode 100644
index 000000000..037b8eaed
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-sales-channel-section/product-sales-channel-section.tsx
@@ -0,0 +1,106 @@
+import { Channels, PencilSquare } from "@medusajs/icons"
+import { Container, Heading, Text, Tooltip } from "@medusajs/ui"
+import { Trans, useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useSalesChannels } from "@hooks/api/sales-channels"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type ProductSalesChannelSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+// TODO: The fetched sales channel doesn't contain all necessary info
+export const ProductSalesChannelSection = ({
+ product,
+}: ProductSalesChannelSectionProps) => {
+ const { count } = useSalesChannels()
+ const { t } = useTranslation()
+
+ const availableInSalesChannels =
+ product.sales_channels?.map((sc) => ({
+ id: sc.id,
+ name: sc.name,
+ })) ?? []
+
+ const firstChannels = availableInSalesChannels.slice(0, 3)
+ const restChannels = availableInSalesChannels.slice(3)
+
+ return (
+ <Container className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("fields.sales_channels")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "sales-channels",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <div className="grid grid-cols-[28px_1fr] items-center gap-x-3">
+ <div className="bg-ui-bg-base shadow-borders-base flex size-7 items-center justify-center rounded-md">
+ <div className="bg-ui-bg-component flex size-6 items-center justify-center rounded-[4px]">
+ <Channels className="text-ui-fg-subtle" />
+ </div>
+ </div>
+ {availableInSalesChannels.length > 0 ? (
+ <div className="flex items-center gap-x-1">
+ <Text size="small" leading="compact">
+ {firstChannels.map((sc) => sc.name).join(", ")}
+ </Text>
+ {restChannels.length > 0 && (
+ <Tooltip
+ content={
+ <ul>
+ {restChannels.map((sc) => (
+ <li key={sc.id}>{sc.name}</li>
+ ))}
+ </ul>
+ }
+ >
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ {`+${restChannels.length}`}
+ </Text>
+ </Tooltip>
+ )}
+ </div>
+ ) : (
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("products.noSalesChannels")}
+ </Text>
+ )}
+ </div>
+ <div>
+ <Text className="text-ui-fg-subtle" size="small" leading="compact">
+ <Trans
+ i18nKey="sales_channels.availableIn"
+ values={{
+ x: availableInSalesChannels.length,
+ y: count ?? 0,
+ }}
+ components={[
+ <span
+ key="x"
+ className="text-ui-fg-base txt-compact-medium-plus"
+ />,
+ <span
+ key="y"
+ className="text-ui-fg-base txt-compact-medium-plus"
+ />,
+ ]}
+ />
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/index.ts
new file mode 100644
index 000000000..9ff25fe9b
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-shipping-profile-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/product-shipping-profile-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/product-shipping-profile-section.tsx
new file mode 100644
index 000000000..30400d177
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-shipping-profile-section/product-shipping-profile-section.tsx
@@ -0,0 +1,49 @@
+import { PencilSquare, ShoppingBag } from "@medusajs/icons"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { SidebarLink } from "@components/common/sidebar-link/sidebar-link"
+import { ActionMenu } from "@components/common/action-menu"
+
+type ProductShippingProfileSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductShippingProfileSection = ({
+ product,
+}: ProductShippingProfileSectionProps) => {
+ const { t } = useTranslation()
+
+ const shippingProfile = product.shipping_profile
+
+ return (
+ <Container className="p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.shippingProfile.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "shipping-profile",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ {shippingProfile && (
+ <SidebarLink
+ to={`/settings/locations/shipping-profiles/${shippingProfile.id}`}
+ labelKey={shippingProfile.name}
+ descriptionKey={shippingProfile.type}
+ icon={<ShoppingBag />}
+ />
+ )}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-variant-section/index.ts b/packages/vendor/src/pages/products/[id]/_components/product-variant-section/index.ts
new file mode 100644
index 000000000..a92ad5b78
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-variant-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-variant-section"
diff --git a/packages/vendor/src/pages/products/[id]/_components/product-variant-section/product-variant-section.tsx b/packages/vendor/src/pages/products/[id]/_components/product-variant-section/product-variant-section.tsx
new file mode 100644
index 000000000..9b87c797f
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/_components/product-variant-section/product-variant-section.tsx
@@ -0,0 +1,201 @@
+import { Component } from "@medusajs/icons"
+import { ExtendedAdminProduct, ExtendedAdminProductVariant } from "@custom-types/products"
+import {
+ Badge,
+ clx,
+ Container,
+ Heading,
+ Tooltip,
+} from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useCallback, useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { createColumnHelper } from "@tanstack/react-table"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProductVariants } from "@hooks/api"
+import { useInventoryItemLevels } from "@hooks/api"
+import { useProductVariantsTableQuery } from "@hooks/table/query/use-product-variants-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type ProductVariantSectionProps = {
+ product: ExtendedAdminProduct
+}
+
+const PAGE_SIZE = 10
+
+export const ProductVariantSection = ({
+ product,
+}: ProductVariantSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useProductVariantsTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { variants, count, isLoading } = useProductVariants(
+ product.id,
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns(product)
+
+ const { table } = useDataTable({
+ data: variants || [],
+ columns,
+ count,
+ enablePagination: true,
+ pageSize: PAGE_SIZE,
+ getRowId: (row) => row?.id || "",
+ })
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.variants.header")}</Heading>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count || 0}
+ pageSize={PAGE_SIZE}
+ search
+ pagination
+ isLoading={isLoading}
+ queryObject={raw}
+ navigateTo={(row) => `variants/${row.original.id}`}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "sku", label: t("fields.sku") },
+ ]}
+ noRecords={{
+ title: t("products.variants.empty.heading"),
+ message: t("products.variants.empty.description"),
+ action: {
+ to: "variants/create",
+ label: t("actions.create"),
+ },
+ }}
+ />
+ </Container>
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProductVariant>()
+
+const useColumns = (product: ExtendedAdminProduct) => {
+ const { t } = useTranslation()
+
+ const optionColumns = useMemo(() => {
+ if (!product?.options) {
+ return []
+ }
+
+ return product.options.map((option) => {
+ return columnHelper.display({
+ id: option.id,
+ header: option.title,
+ cell: ({ row }) => {
+ const variantOpt = row.original.options?.find(
+ (opt) => opt.option_id === option.id
+ )
+
+ if (!variantOpt) {
+ return <span className="text-ui-fg-muted">-</span>
+ }
+
+ return (
+ <div className="flex items-center">
+ <Tooltip content={variantOpt.value}>
+ <Badge
+ size="2xsmall"
+ title={variantOpt.value}
+ className="inline-flex min-w-[20px] max-w-[140px] items-center justify-center overflow-hidden truncate"
+ >
+ {variantOpt.value}
+ </Badge>
+ </Tooltip>
+ </div>
+ )
+ },
+ })
+ })
+ }, [product])
+
+ const getInventory = useCallback(
+ (variant: ExtendedAdminProductVariant) => {
+ const inventoryItems = variant.inventory_items
+ ?.map((i) => i.inventory)
+ .filter(Boolean)
+
+ const hasInventoryKit = inventoryItems ? inventoryItems.length > 1 : false
+
+ const { location_levels } = useInventoryItemLevels(
+ variant?.inventory_items?.[0]?.inventory_item_id!
+ )
+
+ const quantity =
+ location_levels?.reduce(
+ (acc, curr) => acc + curr.available_quantity,
+ 0
+ ) || 0
+ const locationCount =
+ location_levels?.reduce(
+ (acc, curr) => acc + curr.stock_locations?.length,
+ 0
+ ) || 0
+
+ const text = hasInventoryKit
+ ? t("products.variant.tableItemAvailable", {
+ availableCount: quantity,
+ })
+ : t("products.variant.tableItem", {
+ availableCount: quantity,
+ locationCount,
+ count: locationCount,
+ })
+
+ return { text, hasInventoryKit, quantity }
+ },
+ [t]
+ )
+
+ return useMemo(() => {
+ return [
+ columnHelper.accessor("title", {
+ header: t("fields.title"),
+ cell: ({ getValue }) => getValue() || "-",
+ }),
+ columnHelper.accessor("sku", {
+ header: t("fields.sku"),
+ cell: ({ getValue }) => getValue() || "-",
+ }),
+ ...optionColumns,
+ columnHelper.display({
+ id: "inventory",
+ header: t("fields.inventory"),
+ cell: ({ row }) => {
+ const { text, hasInventoryKit, quantity } = getInventory(row.original)
+
+ return (
+ <Tooltip content={text}>
+ <div className="flex h-full w-full items-center gap-2 overflow-hidden">
+ {hasInventoryKit && <Component />}
+ <span
+ className={clx("truncate", {
+ "text-ui-fg-error": !quantity,
+ })}
+ >
+ {text}
+ </span>
+ </div>
+ </Tooltip>
+ )
+ },
+ }),
+ ]
+ }, [t, optionColumns, getInventory])
+}
diff --git a/packages/vendor/src/pages/products/[id]/additional-attributes/AttributeSelect.tsx b/packages/vendor/src/pages/products/[id]/additional-attributes/AttributeSelect.tsx
new file mode 100644
index 000000000..1b3b471df
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/additional-attributes/AttributeSelect.tsx
@@ -0,0 +1,33 @@
+import { Select } from "@medusajs/ui"
+import { ProductAttributePossibleValue } from "@custom-types/products"
+import { ControllerRenderProps } from "react-hook-form"
+
+export const AttributeSelect = ({
+ values,
+ field,
+}: {
+ values: ProductAttributePossibleValue[]
+ field: ControllerRenderProps<any, string>
+}) => {
+ const handleChange = (value: string) => {
+ field.onChange(value)
+ }
+
+ return (
+ <Select onValueChange={(value) => handleChange(value)} value={field.value}>
+ <Select.Trigger className="bg-ui-bg-base">
+ <Select.Value placeholder="Select value" />
+ </Select.Trigger>
+ <Select.Content>
+ {values.map(({ id, attribute_id, value }) => (
+ <Select.Item
+ key={`select-option-${attribute_id}-${id}`}
+ value={value}
+ >
+ {value}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/additional-attributes/Components.tsx b/packages/vendor/src/pages/products/[id]/additional-attributes/Components.tsx
new file mode 100644
index 000000000..6825ca456
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/additional-attributes/Components.tsx
@@ -0,0 +1,34 @@
+import { Input, Switch, Textarea } from "@medusajs/ui"
+import { AttributeSelect } from "./AttributeSelect"
+import { ProductAttribute } from "@custom-types/products"
+import { ControllerRenderProps } from "react-hook-form"
+
+export const Components = ({
+ attribute,
+ field,
+}: {
+ attribute: ProductAttribute
+ field: ControllerRenderProps<any, string>
+}) => {
+ const { ui_component, possible_values } = attribute
+
+ if (ui_component === "select")
+ return <AttributeSelect values={possible_values} field={field} />
+
+ if (ui_component === "toggle")
+ return (
+ <Switch
+ {...field}
+ onCheckedChange={field.onChange}
+ checked={field.value === "true" || field.value === true}
+ />
+ )
+
+ if (ui_component === "text_area") return <Textarea {...field} rows={4} />
+
+ if (ui_component === "unit") return <Input type="number" {...field} />
+
+ if (ui_component === "text") return <Input {...field} />
+
+ return <Input {...field} />
+}
diff --git a/packages/vendor/src/pages/products/[id]/additional-attributes/index.tsx b/packages/vendor/src/pages/products/[id]/additional-attributes/index.tsx
new file mode 100644
index 000000000..e7d78acce
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/additional-attributes/index.tsx
@@ -0,0 +1,31 @@
+// Route: /products/:id/additional-attributes
+import { useParams } from "react-router-dom"
+import { Heading } from "@medusajs/ui"
+import { Spinner } from "@medusajs/icons"
+import { useProduct, useProductAttributes } from "@hooks/api"
+import { RouteDrawer } from "@components/modals"
+import { ProductAdditionalAttributesForm } from "./product-additional-attributes-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { product, isLoading: isProductLoading } = useProduct(id!)
+
+ const { attributes, isLoading: isAttributesLoading } = useProductAttributes(
+ id!,
+ )
+
+ const isReady = !isAttributesLoading && attributes && !isProductLoading && product
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading level="h2">Edit Additional Attributes</Heading>
+ </RouteDrawer.Header>
+ {isReady ? (
+ <ProductAdditionalAttributesForm product={product} attributes={attributes} id={id!} />
+ ) : (
+ <Spinner className="text-ui-fg-interactive animate-spin" />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/additional-attributes/product-additional-attributes-form.tsx b/packages/vendor/src/pages/products/[id]/additional-attributes/product-additional-attributes-form.tsx
new file mode 100644
index 000000000..57e380feb
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/additional-attributes/product-additional-attributes-form.tsx
@@ -0,0 +1,127 @@
+'use client';
+
+import { InformationCircleSolid } from '@medusajs/icons';
+import { Button, toast, Tooltip } from '@medusajs/ui';
+import { useForm } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProduct } from "@hooks/api"
+import { ExtendedAdminProduct, ProductAttribute } from '../../../../types/products';
+import { Components } from './Components';
+
+interface Props {
+ product: ExtendedAdminProduct;
+ attributes: ProductAttribute[];
+ id: string;
+}
+
+export const ProductAdditionalAttributesForm = ({ product, attributes, id }: Props) => {
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+ const filteredAttributes = product?.attribute_values?.filter(a => !!a?.attribute_id);
+ const defaultValues = filteredAttributes?.reduce((acc: any, curr: any) => {
+ acc[curr.attribute_id] = curr.value;
+ return acc;
+ }, {});
+
+ const form = useForm({
+ defaultValues
+ });
+
+ const { mutate: updateProduct, isPending: isMutating } = useUpdateProduct(id);
+
+ const handleSubmit = form.handleSubmit(async (data: any) => {
+ const values = Object.keys(data).reduce((acc: Array<Record<string, string>>, key) => {
+ acc.push({ attribute_id: key, value: data[key] });
+ return acc;
+ }, []);
+
+ await updateProduct(
+ {
+ additional_data: { values }
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t('products.edit.successToast', {
+ title: product.title
+ })
+ );
+ handleSuccess(`/products/${id}`);
+ },
+ onError: error => {
+ toast.error(error.message);
+ }
+ }
+ );
+ });
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col"
+ >
+ <RouteDrawer.Body className="max-h-[calc(86vh)] overflow-y-auto py-2">
+ {attributes?.map((a: ProductAttribute) => (
+ <Form.Field
+ key={`form-field-${a.handle}-${a.id}`}
+ control={form.control}
+ name={a.id}
+ render={({ field }) => {
+ return (
+ <Form.Item
+ key={a.id}
+ className="mb-4 w-full"
+ >
+ <Form.Label className="flex w-full flex-col gap-y-2">
+ <span className="flex items-center gap-x-2">
+ {a.name}
+ {a.description && (
+ <Tooltip content={a.description}>
+ <InformationCircleSolid />
+ </Tooltip>
+ )}
+ </span>
+
+ <Form.Control>
+ <Components
+ attribute={a}
+ field={field}
+ />
+ </Form.Control>
+ </Form.Label>
+ </Form.Item>
+ );
+ }}
+ />
+ ))}
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button
+ size="small"
+ variant="secondary"
+ type="button"
+ disabled={isMutating}
+ >
+ {t('actions.cancel')}
+ </Button>
+ </RouteDrawer.Close>
+ <Button
+ size="small"
+ type="submit"
+ isLoading={isMutating}
+ >
+ {t('actions.save')}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ );
+};
diff --git a/packages/vendor/src/pages/products/[id]/attributes/index.tsx b/packages/vendor/src/pages/products/[id]/attributes/index.tsx
new file mode 100644
index 000000000..8c8d2cf74
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/attributes/index.tsx
@@ -0,0 +1,33 @@
+// Route: /products/:id/attributes
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { PRODUCT_DETAIL_FIELDS } from "../constants"
+import { ProductAttributesForm } from "./product-attributes-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product, isLoading, isError, error } = useProduct(id!, {
+ fields: PRODUCT_DETAIL_FIELDS,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.editAttributes")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+ {!isLoading && product && <ProductAttributesForm product={product} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/index.ts b/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/index.ts
new file mode 100644
index 000000000..0feeabbb9
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-attributes-form"
diff --git a/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/product-attributes-form.tsx b/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/product-attributes-form.tsx
new file mode 100644
index 000000000..c2a121767
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/attributes/product-attributes-form/product-attributes-form.tsx
@@ -0,0 +1,273 @@
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Button, Input } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import {
+ FormExtensionZone,
+ useDashboardExtension,
+ useExtendableForm,
+} from "@/extensions"
+import { useUpdateProduct } from "@hooks/api/products"
+
+type ProductAttributesFormProps = {
+ product: ExtendedAdminProduct
+}
+
+const dimension = zod
+ .union([zod.string(), zod.number()])
+ .transform((value) => {
+ if (value === "") {
+ return null
+ }
+ return Number(value)
+ })
+ .optional()
+ .nullable()
+
+const ProductAttributesSchema = zod.object({
+ weight: dimension,
+ length: dimension,
+ width: dimension,
+ height: dimension,
+ mid_code: zod.string().optional(),
+ hs_code: zod.string().optional(),
+ origin_country: zod.string().optional(),
+})
+
+export const ProductAttributesForm = ({
+ product,
+}: ProductAttributesFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { getFormConfigs, getFormFields } = useDashboardExtension()
+
+ const configs = getFormConfigs("product", "attributes")
+ const fields = getFormFields("product", "attributes")
+
+ const form = useExtendableForm({
+ defaultValues: {
+ height: product.height ? product.height : null,
+ width: product.width ? product.width : null,
+ length: product.length ? product.length : null,
+ weight: product.weight ? product.weight : null,
+ mid_code: product.mid_code || "",
+ hs_code: product.hs_code || "",
+ origin_country: product.origin_country || "",
+ },
+ schema: ProductAttributesSchema,
+ configs: configs,
+ data: product,
+ })
+
+ const { mutateAsync, isPending } = useUpdateProduct(product.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ weight: data.weight ? data.weight : undefined,
+ length: data.length ? data.length : undefined,
+ width: data.width ? data.width : undefined,
+ height: data.height ? data.height : undefined,
+ mid_code: data.mid_code,
+ hs_code: data.hs_code,
+ origin_country: data.origin_country,
+ },
+ {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
+ <RouteDrawer.Body>
+ <div className="flex h-full flex-col gap-y-8">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="width"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.width")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.height")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(Number(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.length")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(Number(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.weight")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(Number(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.midCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.hsCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.countryOfOrigin")}</Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <FormExtensionZone fields={fields} form={form} />
+ </div>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/constants.ts b/packages/vendor/src/pages/products/[id]/constants.ts
new file mode 100644
index 000000000..bea3f0961
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/constants.ts
@@ -0,0 +1 @@
+export const PRODUCT_DETAIL_FIELDS = ""
diff --git a/packages/vendor/src/pages/products/[id]/edit/edit-product-form/edit-product-form.tsx b/packages/vendor/src/pages/products/[id]/edit/edit-product-form/edit-product-form.tsx
new file mode 100644
index 000000000..9ad7450d1
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/edit/edit-product-form/edit-product-form.tsx
@@ -0,0 +1,239 @@
+import { Button, Input, Text, Textarea, toast } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { useExtendableForm } from "@/extensions/forms/hooks"
+import { useUpdateProduct } from "@hooks/api/products"
+
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import {
+ FormExtensionZone,
+ useDashboardExtension,
+} from "@/extensions"
+
+type EditProductFormProps = {
+ product: ExtendedAdminProduct
+}
+
+const EditProductSchema = zod.object({
+ title: zod.string().min(1),
+ handle: zod.string().min(1),
+ description: zod.string().optional(),
+ discountable: zod.boolean(),
+})
+
+export const EditProductForm = ({ product }: EditProductFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const { getFormFields, getFormConfigs } = useDashboardExtension()
+ const fields = getFormFields("product", "edit")
+ const configs = getFormConfigs("product", "edit")
+
+ const form = useExtendableForm({
+ defaultValues: {
+ title: product.title,
+ handle: product.handle || "",
+ description: product.description || "",
+ discountable: product.discountable,
+ },
+ schema: EditProductSchema,
+ configs: configs,
+ data: product,
+ })
+
+ const { mutateAsync, isPending } = useUpdateProduct(product.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const { description, discountable, handle, title } = data
+
+ await mutateAsync(
+ {
+ description,
+ discountable,
+ handle,
+ title,
+ },
+ {
+ onSuccess: ({ product }) => {
+ toast.success(
+ t("products.edit.successToast", {
+ title: product.title,
+ })
+ )
+ handleSuccess(`/products/${product.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-y-auto">
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-4">
+ {/* <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.status")}</Form.Label>
+ <Form.Control>
+ <Select {...field} onValueChange={onChange}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {(
+ [
+ "draft",
+ "published",
+ "proposed",
+ "rejected",
+ ] as const
+ ).map((status) => {
+ return (
+ <Select.Item key={status} value={status}>
+ {t(`products.productStatus.${status}`)}
+ </Select.Item>
+ )
+ })}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ /> */}
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ {/* <Form.Field
+ control={form.control}
+ name='subtitle'
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t('fields.subtitle')}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ /> */}
+ <Form.Field
+ control={form.control}
+ name="handle"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.handle")}</Form.Label>
+ <Form.Control>
+ <div className="relative">
+ <div className="absolute inset-y-0 left-0 z-10 flex w-8 items-center justify-center border-r">
+ <Text
+ className="text-ui-fg-muted"
+ size="small"
+ leading="compact"
+ weight="plus"
+ >
+ /
+ </Text>
+ </div>
+ <Input {...field} className="pl-10" />
+ </div>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ {/* <Form.Field
+ control={form.control}
+ name='material'
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t('fields.material')}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ /> */}
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("fields.description")}
+ </Form.Label>
+ <Form.Control>
+ <Textarea {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <SwitchBox
+ control={form.control}
+ name="discountable"
+ label={t("fields.discountable")}
+ description={t("products.discountableHint")}
+ />
+ <FormExtensionZone fields={fields} form={form} />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/edit/edit-product-form/index.ts b/packages/vendor/src/pages/products/[id]/edit/edit-product-form/index.ts
new file mode 100644
index 000000000..c0a3a488b
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/edit/edit-product-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-product-form"
diff --git a/packages/vendor/src/pages/products/[id]/edit/index.tsx b/packages/vendor/src/pages/products/[id]/edit/index.tsx
new file mode 100644
index 000000000..6f7ec7205
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/edit/index.tsx
@@ -0,0 +1,36 @@
+// Route: /products/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { PRODUCT_DETAIL_FIELDS } from "../constants"
+import { EditProductForm } from "./edit-product-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product, isLoading, isError, error } = useProduct(id!, {
+ fields: PRODUCT_DETAIL_FIELDS,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("products.edit.description")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {!isLoading && product && <EditProductForm product={product} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/index.tsx b/packages/vendor/src/pages/products/[id]/index.tsx
new file mode 100644
index 000000000..a7b30d834
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/index.tsx
@@ -0,0 +1,117 @@
+// Route: /products/:id
+import { UIMatch } from "react-router-dom"
+import { useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useProduct } from "@hooks/api"
+import { productsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { useDashboardExtension } from "@/extensions"
+import { ExtendedAdminProductResponse } from "@custom-types/products"
+
+import { ProductGeneralSection } from "./_components/product-general-section"
+import { ProductMediaSection } from "./_components/product-media-section"
+import { ProductOptionSection } from "./_components/product-option-section"
+import { ProductOrganizationSection } from "./_components/product-organization-section"
+import { ProductVariantSection } from "./_components/product-variant-section"
+import { ProductAdditionalAttributesSection } from "./_components/product-additional-attribute-section/ProductAdditionalAttributesSection"
+import { PRODUCT_DETAIL_FIELDS } from "./constants"
+
+// Loader
+const productDetailQuery = (id: string) => ({
+ queryKey: productsQueryKeys.detail(id, {
+ fields: PRODUCT_DETAIL_FIELDS,
+ }),
+ queryFn: async () =>
+ fetchQuery(`/vendor/products/${id}`, {
+ method: "GET",
+ query: {
+ fields:
+ "*variants.inventory_items,*categories,attribute_values.*,attribute_values.attribute.*",
+ },
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = productDetailQuery(id!)
+
+ const response = await queryClient.ensureQueryData({
+ ...query,
+ staleTime: 90000,
+ })
+
+ return response
+}
+
+// Breadcrumb
+type ProductDetailBreadcrumbProps = UIMatch<ExtendedAdminProductResponse>
+
+export const Breadcrumb = (props: ProductDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { product } = useProduct(
+ id!,
+ {
+ fields: PRODUCT_DETAIL_FIELDS,
+ },
+ {
+ enabled: Boolean(id),
+ }
+ )
+
+ if (!product) {
+ return null
+ }
+
+ return <span>{product?.title}</span>
+}
+
+// Main component
+export const Component = () => {
+ const { id } = useParams()
+ const { product, isLoading, isError, error } = useProduct(id!, {
+ fields:
+ "*categories,attribute_values.*,attribute_values.attribute.*,*options",
+ })
+
+ const { getWidgets } = useDashboardExtension()
+
+ const after = getWidgets("product.details.after")
+ const before = getWidgets("product.details.before")
+ const sideAfter = getWidgets("product.details.side.after")
+ const sideBefore = getWidgets("product.details.side.before")
+
+ if (isLoading || !product) {
+ return <TwoColumnPageSkeleton mainSections={4} sidebarSections={3} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after,
+ before,
+ sideAfter,
+ sideBefore,
+ }}
+ data={product}
+ >
+ <TwoColumnPage.Main>
+ <ProductGeneralSection product={product} />
+ <ProductMediaSection product={product} />
+ <ProductOptionSection product={product} />
+ <ProductVariantSection product={product} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <ProductOrganizationSection product={product} />
+ <ProductAdditionalAttributesSection product={product} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/edit-product-media-form.tsx b/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/edit-product-media-form.tsx
new file mode 100644
index 000000000..ecf810338
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/edit-product-media-form.tsx
@@ -0,0 +1,464 @@
+import {
+ defaultDropAnimationSideEffects,
+ DndContext,
+ DragEndEvent,
+ DragOverlay,
+ DragStartEvent,
+ DropAnimation,
+ KeyboardSensor,
+ PointerSensor,
+ UniqueIdentifier,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core"
+import {
+ arrayMove,
+ rectSortingStrategy,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+} from "@dnd-kit/sortable"
+import { CSS } from "@dnd-kit/utilities"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { ThumbnailBadge } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Button, Checkbox, clx, CommandBar, toast, Tooltip } from "@medusajs/ui"
+import { Fragment, useCallback, useState } from "react"
+import { useFieldArray, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { z } from "zod"
+
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProduct } from "@hooks/api/products"
+import { uploadFilesQuery } from "@lib/client"
+import { UploadMediaFormItem } from "../../../common/components/upload-media-form-item"
+import {
+ EditProductMediaSchema,
+ MediaSchema,
+} from "../../../create/constants"
+import { EditProductMediaSchemaType } from "../../../create/types"
+
+type ProductMediaViewProps = {
+ product: ExtendedAdminProduct
+}
+
+type Media = z.infer<typeof MediaSchema>
+
+export const EditProductMediaForm = ({ product }: ProductMediaViewProps) => {
+ const [selection, setSelection] = useState<Record<string, true>>({})
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<EditProductMediaSchemaType>({
+ defaultValues: {
+ media: getDefaultValues(product.images, product.thumbnail),
+ },
+ resolver: zodResolver(EditProductMediaSchema),
+ })
+
+ const { fields, append, remove, update } = useFieldArray({
+ name: "media",
+ control: form.control,
+ keyName: "field_id",
+ })
+
+ const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ )
+
+ const handleDragStart = (event: DragStartEvent) => {
+ setActiveId(event.active.id)
+ }
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ setActiveId(null)
+ const { active, over } = event
+
+ if (active.id !== over?.id) {
+ const oldIndex = fields.findIndex((item) => item.field_id === active.id)
+ const newIndex = fields.findIndex((item) => item.field_id === over?.id)
+
+ form.setValue("media", arrayMove(fields, oldIndex, newIndex), {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ }
+ }
+
+ const handleDragCancel = () => {
+ setActiveId(null)
+ }
+
+ const { mutateAsync, isPending } = useUpdateProduct(product.id!)
+
+ const handleSubmit = form.handleSubmit(async ({ media }) => {
+ const filesToUpload = media
+ .map((m, i) => ({ file: m.file, index: i }))
+ .filter((m) => !!m.file)
+
+ let uploaded: HttpTypes.AdminFile[] = []
+
+ if (filesToUpload.length) {
+ const { files } = await uploadFilesQuery(filesToUpload)
+ // .then((res) => res.json())
+ .catch(() => {
+ form.setError("media", {
+ type: "invalid_file",
+ message: t("products.media.failedToUpload"),
+ })
+ return { files: [] }
+ })
+ uploaded = files
+ }
+
+ const withUpdatedUrls = media.map((entry, i) => {
+ const toUploadIndex = filesToUpload.findIndex((m) => m.index === i)
+ if (toUploadIndex > -1) {
+ return {
+ ...entry,
+ url: uploaded[toUploadIndex]?.url,
+ }
+ }
+ return entry
+ })
+
+ const thumbnail = withUpdatedUrls.find((m) => m.isThumbnail)?.url
+
+ await mutateAsync(
+ {
+ images: withUpdatedUrls.map((file) => ({
+ url: file.url,
+ id: file.id,
+ })),
+ thumbnail: thumbnail || null,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("products.media.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const handleCheckedChange = useCallback(
+ (id: string) => {
+ return (val: boolean) => {
+ if (!val) {
+ const { [id]: _, ...rest } = selection
+ setSelection(rest)
+ } else {
+ setSelection((prev) => ({ ...prev, [id]: true }))
+ }
+ }
+ },
+ [selection]
+ )
+
+ const handleDelete = () => {
+ const ids = Object.keys(selection)
+ const indices = ids.map((id) => fields.findIndex((m) => m.id === id))
+
+ remove(indices)
+ setSelection({})
+ }
+
+ const handlePromoteToThumbnail = () => {
+ const ids = Object.keys(selection)
+
+ if (!ids.length) {
+ return
+ }
+
+ const currentThumbnailIndex = fields.findIndex((m) => m.isThumbnail)
+
+ if (currentThumbnailIndex > -1) {
+ update(currentThumbnailIndex, {
+ ...fields[currentThumbnailIndex],
+ isThumbnail: false,
+ })
+ }
+
+ const index = fields.findIndex((m) => m.id === ids[0])
+
+ update(index, {
+ ...fields[index],
+ isThumbnail: true,
+ })
+
+ setSelection({})
+ }
+
+ const selectionCount = Object.keys(selection).length
+
+ return (
+ <RouteFocusModal.Form blockSearchParams form={form}>
+ <KeyboundForm
+ className="flex size-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <Button variant="secondary" size="small" asChild>
+ <Link to={{ pathname: ".", search: undefined }}>
+ {t("products.media.galleryLabel")}
+ </Link>
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex flex-col overflow-hidden">
+ <div className="flex size-full flex-col-reverse lg:grid lg:grid-cols-[1fr_560px]">
+ <DndContext
+ sensors={sensors}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ onDragCancel={handleDragCancel}
+ >
+ <div className="bg-ui-bg-subtle size-full overflow-auto">
+ <div className="grid h-fit auto-rows-auto grid-cols-4 gap-6 p-6">
+ <SortableContext
+ items={fields.map((m) => m.field_id)}
+ strategy={rectSortingStrategy}
+ >
+ {fields.map((m) => {
+ return (
+ <MediaGridItem
+ onCheckedChange={handleCheckedChange(m.id!)}
+ checked={!!selection[m.id!]}
+ key={m.field_id}
+ media={m}
+ />
+ )
+ })}
+ </SortableContext>
+ <DragOverlay dropAnimation={dropAnimationConfig}>
+ {activeId ? (
+ <MediaGridItemOverlay
+ media={fields.find((m) => m.field_id === activeId)!}
+ checked={
+ !!selection[
+ fields.find((m) => m.field_id === activeId)!.id!
+ ]
+ }
+ />
+ ) : null}
+ </DragOverlay>
+ </div>
+ </div>
+ </DndContext>
+ <div className="bg-ui-bg-base overflow-auto border-b px-6 py-4 lg:border-b-0 lg:border-l">
+ <UploadMediaFormItem form={form} append={append} />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <CommandBar open={!!selectionCount}>
+ <CommandBar.Bar>
+ <CommandBar.Value>
+ {t("general.countSelected", {
+ count: selectionCount,
+ })}
+ </CommandBar.Value>
+ <CommandBar.Seperator />
+ {selectionCount === 1 && (
+ <Fragment>
+ <CommandBar.Command
+ action={handlePromoteToThumbnail}
+ label={t("products.media.makeThumbnail")}
+ shortcut="t"
+ />
+ <CommandBar.Seperator />
+ </Fragment>
+ )}
+ <CommandBar.Command
+ action={handleDelete}
+ label={t("actions.delete")}
+ shortcut="d"
+ />
+ </CommandBar.Bar>
+ </CommandBar>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const getDefaultValues = (
+ images: HttpTypes.AdminProductImage[] | null | undefined,
+ thumbnail: string | null | undefined
+) => {
+ const media: Media[] =
+ images?.map((image) => ({
+ id: image.id!,
+ url: image.url!,
+ isThumbnail: image.url === thumbnail,
+ file: null,
+ })) || []
+
+ if (thumbnail && !media.some((mediaItem) => mediaItem.url === thumbnail)) {
+ const id = Math.random().toString(36).substring(7)
+
+ media.unshift({
+ id: id,
+ url: thumbnail,
+ isThumbnail: true,
+ file: null,
+ })
+ }
+
+ return media
+}
+
+interface MediaView {
+ id?: string
+ field_id: string
+ url: string
+ isThumbnail: boolean
+}
+
+const dropAnimationConfig: DropAnimation = {
+ sideEffects: defaultDropAnimationSideEffects({
+ styles: {
+ active: {
+ opacity: "0.4",
+ },
+ },
+ }),
+}
+
+interface MediaGridItemProps {
+ media: MediaView
+ checked: boolean
+ onCheckedChange: (value: boolean) => void
+}
+
+const MediaGridItem = ({
+ media,
+ checked,
+ onCheckedChange,
+}: MediaGridItemProps) => {
+ const { t } = useTranslation()
+
+ const handleToggle = useCallback(
+ (value: boolean) => {
+ onCheckedChange(value)
+ },
+ [onCheckedChange]
+ )
+
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ setActivatorNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: media.field_id })
+
+ const style = {
+ opacity: isDragging ? 0.4 : undefined,
+ transform: CSS.Transform.toString(transform),
+ transition,
+ }
+
+ return (
+ <div
+ className={clx(
+ "shadow-elevation-card-rest hover:shadow-elevation-card-hover focus-visible:shadow-borders-focus bg-ui-bg-subtle-hover group relative aspect-square h-auto max-w-full overflow-hidden rounded-lg outline-none"
+ )}
+ style={style}
+ ref={setNodeRef}
+ >
+ {media.isThumbnail && (
+ <div className="absolute left-2 top-2">
+ <Tooltip content={t("products.media.thumbnailTooltip")}>
+ <ThumbnailBadge />
+ </Tooltip>
+ </div>
+ )}
+ <div
+ className={clx("absolute inset-0 cursor-grab touch-none outline-none", {
+ "cursor-grabbing": isDragging,
+ })}
+ ref={setActivatorNodeRef}
+ {...attributes}
+ {...listeners}
+ />
+ <div
+ className={clx("transition-fg absolute right-2 top-2 opacity-0", {
+ "group-focus-within:opacity-100 group-hover:opacity-100 group-focus:opacity-100":
+ !isDragging && !checked,
+ "opacity-100": checked,
+ })}
+ >
+ <Checkbox
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ checked={checked}
+ onCheckedChange={handleToggle}
+ />
+ </div>
+ <img
+ src={media.url}
+ alt=""
+ className="size-full object-cover object-center"
+ />
+ </div>
+ )
+}
+
+export const MediaGridItemOverlay = ({
+ media,
+ checked,
+}: {
+ media: MediaView
+ checked: boolean
+}) => {
+ return (
+ <div className="shadow-elevation-card-rest hover:shadow-elevation-card-hover focus-visible:shadow-borders-focus bg-ui-bg-subtle-hover group relative aspect-square h-auto max-w-full cursor-grabbing overflow-hidden rounded-lg outline-none">
+ {media.isThumbnail && (
+ <div className="absolute left-2 top-2">
+ <ThumbnailBadge />
+ </div>
+ )}
+ <div
+ className={clx("transition-fg absolute right-2 top-2 opacity-0", {
+ "opacity-100": checked,
+ })}
+ >
+ <Checkbox checked={checked} />
+ </div>
+ <img
+ src={media.url}
+ alt=""
+ className="size-full object-cover object-center"
+ />
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/index.ts b/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/index.ts
new file mode 100644
index 000000000..725f426a2
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/edit-product-media-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-product-media-form"
diff --git a/packages/vendor/src/pages/products/[id]/media/index.tsx b/packages/vendor/src/pages/products/[id]/media/index.tsx
new file mode 100644
index 000000000..7d19e1c52
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/index.tsx
@@ -0,0 +1,31 @@
+// Route: /products/:id/media
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { ProductMediaView } from "./product-media-view"
+
+export const Component = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+
+ const { product, isLoading, isError, error } = useProduct(id!)
+
+ const ready = !isLoading && product
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">{t("products.media.label")}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <span className="sr-only">{t("products.media.editHint")}</span>
+ </RouteFocusModal.Description>
+ {ready && <ProductMediaView product={product} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-gallery/index.ts b/packages/vendor/src/pages/products/[id]/media/product-media-gallery/index.ts
new file mode 100644
index 000000000..254191a05
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-gallery/index.ts
@@ -0,0 +1 @@
+export * from "./product-media-gallery"
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-gallery/product-media-gallery.tsx b/packages/vendor/src/pages/products/[id]/media/product-media-gallery/product-media-gallery.tsx
new file mode 100644
index 000000000..fe65fe0ac
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-gallery/product-media-gallery.tsx
@@ -0,0 +1,328 @@
+import {
+ ArrowDownTray,
+ ThumbnailBadge,
+ Trash,
+ TriangleLeftMini,
+ TriangleRightMini,
+} from "@medusajs/icons"
+import { Button, IconButton, Text, Tooltip, clx, usePrompt } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useCallback, useEffect, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link, useLocation } from "react-router-dom"
+
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { RouteFocusModal } from "@components/modals"
+import { useUpdateProduct } from "@hooks/api/products"
+
+type ProductMediaGalleryProps = {
+ product: ExtendedAdminProduct
+}
+
+export const ProductMediaGallery = ({ product }: ProductMediaGalleryProps) => {
+ const { state } = useLocation()
+ const [curr, setCurr] = useState<number>(state?.curr || 0)
+
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync, isPending } = useUpdateProduct(product.id)
+
+ const media = getMedia(product.images, product.thumbnail)
+
+ const next = useCallback(() => {
+ if (isPending) {
+ return
+ }
+
+ setCurr((prev) => (prev + 1) % media.length)
+ }, [media, isPending])
+
+ const prev = useCallback(() => {
+ if (isPending) {
+ return
+ }
+
+ setCurr((prev) => (prev - 1 + media.length) % media.length)
+ }, [media, isPending])
+
+ const goTo = useCallback(
+ (index: number) => {
+ if (isPending) {
+ return
+ }
+
+ setCurr(index)
+ },
+ [isPending]
+ )
+
+ const handleDownloadCurrent = () => {
+ if (isPending) {
+ return
+ }
+
+ const a = document.createElement("a") as HTMLAnchorElement & {
+ download: string
+ }
+
+ a.href = media[curr].url
+ a.download = "image"
+ a.target = "_blank"
+
+ a.click()
+ }
+
+ const handleDeleteCurrent = async () => {
+ const current = media[curr]
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: current.isThumbnail
+ ? t("products.media.deleteWarningWithThumbnail", { count: 1 })
+ : t("products.media.deleteWarning", { count: 1 }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ const mediaToKeep =
+ product.images
+ ?.filter((i) => i.id !== current.id)
+ .map((i) => ({ url: i.url })) || []
+
+ if (curr === media.length - 1) {
+ setCurr((prev) => prev - 1)
+ }
+
+ await mutateAsync({
+ images: mediaToKeep,
+ thumbnail: current.isThumbnail ? "" : undefined,
+ })
+ }
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "ArrowRight") {
+ next()
+ } else if (e.key === "ArrowLeft") {
+ prev()
+ }
+ }
+
+ document.addEventListener("keydown", handleKeyDown)
+
+ return () => {
+ document.removeEventListener("keydown", handleKeyDown)
+ }
+ }, [next, prev])
+
+ const noMedia = !media.length
+
+ return (
+ <div className="flex size-full flex-col overflow-hidden">
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <IconButton
+ size="small"
+ type="button"
+ onClick={handleDeleteCurrent}
+ disabled={noMedia}
+ >
+ <Trash />
+ <span className="sr-only">
+ {t("products.media.deleteImageLabel")}
+ </span>
+ </IconButton>
+ <IconButton
+ size="small"
+ type="button"
+ onClick={handleDownloadCurrent}
+ disabled={noMedia}
+ >
+ <ArrowDownTray />
+ <span className="sr-only">
+ {t("products.media.downloadImageLabel")}
+ </span>
+ </IconButton>
+ <Button variant="secondary" size="small" asChild>
+ <Link to={{ pathname: ".", search: "view=edit" }}>
+ {t("actions.edit")}
+ </Link>
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex flex-col overflow-hidden">
+ <Canvas curr={curr} media={media} />
+ <Preview
+ curr={curr}
+ media={media}
+ prev={prev}
+ next={next}
+ goTo={goTo}
+ />
+ </RouteFocusModal.Body>
+ </div>
+ )
+}
+
+const Canvas = ({ media, curr }: { media: Media[]; curr: number }) => {
+ const { t } = useTranslation()
+
+ if (media.length === 0) {
+ return (
+ <div className="bg-ui-bg-subtle flex size-full flex-col items-center justify-center gap-y-4 pb-8 pt-6">
+ <div className="flex flex-col items-center">
+ <Text
+ size="small"
+ leading="compact"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ >
+ {t("products.media.emptyState.header")}
+ </Text>
+ <Text size="small" className="text-ui-fg-muted">
+ {t("products.media.emptyState.description")}
+ </Text>
+ </div>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="?view=edit">{t("products.media.emptyState.action")}</Link>
+ </Button>
+ </div>
+ )
+ }
+
+ return (
+ <div className="bg-ui-bg-subtle relative size-full overflow-hidden">
+ <div className="flex size-full items-center justify-center p-6">
+ <div className="relative inline-block max-h-full max-w-full">
+ {media[curr].isThumbnail && (
+ <div className="absolute left-2 top-2">
+ <Tooltip content={t("products.media.thumbnailTooltip")}>
+ <ThumbnailBadge />
+ </Tooltip>
+ </div>
+ )}
+ <img
+ src={media[curr].url}
+ alt=""
+ className="object-fit shadow-elevation-card-rest max-h-[calc(100vh-200px)] w-auto rounded-xl object-contain"
+ />
+ </div>
+ </div>
+ </div>
+ )
+}
+
+const MAX_VISIBLE_ITEMS = 8
+
+const Preview = ({
+ media,
+ curr,
+ prev,
+ next,
+ goTo,
+}: {
+ media: Media[]
+ curr: number
+ prev: () => void
+ next: () => void
+ goTo: (index: number) => void
+}) => {
+ if (!media.length) {
+ return null
+ }
+
+ const getVisibleItems = (media: Media[], index: number) => {
+ if (media.length <= MAX_VISIBLE_ITEMS) {
+ return media
+ }
+
+ const half = Math.floor(MAX_VISIBLE_ITEMS / 2)
+ const start = (index - half + media.length) % media.length
+ const end = (start + MAX_VISIBLE_ITEMS) % media.length
+
+ if (end < start) {
+ return [...media.slice(start), ...media.slice(0, end)]
+ } else {
+ return media.slice(start, end)
+ }
+ }
+
+ const visibleItems = getVisibleItems(media, curr)
+
+ return (
+ <div className="flex shrink-0 items-center justify-center gap-x-2 border-t p-3">
+ <IconButton
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ type="button"
+ onClick={prev}
+ >
+ <TriangleLeftMini />
+ </IconButton>
+ <div className="flex items-center gap-x-2">
+ {visibleItems.map((item) => {
+ const isCurrentImage = item.id === media[curr].id
+ const originalIndex = media.findIndex((i) => i.id === item.id)
+
+ return (
+ <button
+ type="button"
+ onClick={() => goTo(originalIndex)}
+ className={clx(
+ "transition-fg size-7 overflow-hidden rounded-[4px] outline-none",
+ {
+ "shadow-borders-focus": isCurrentImage,
+ }
+ )}
+ key={item.id}
+ >
+ <img src={item.url} alt="" className="size-full object-cover" />
+ </button>
+ )
+ })}
+ </div>
+ <IconButton
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ type="button"
+ onClick={next}
+ >
+ <TriangleRightMini />
+ </IconButton>
+ </div>
+ )
+}
+
+type Media = {
+ id: string
+ url: string
+ isThumbnail: boolean
+}
+
+const getMedia = (
+ images: HttpTypes.AdminProductImage[] | null,
+ thumbnail: string | null
+) => {
+ const media: Media[] =
+ images?.map((image) => ({
+ id: image.id,
+ url: image.url,
+ isThumbnail: image.url === thumbnail,
+ })) || []
+
+ if (thumbnail && !media.some((mediaItem) => mediaItem.isThumbnail)) {
+ media.unshift({
+ id: "thumbnail_only",
+ url: thumbnail,
+ isThumbnail: true,
+ })
+ }
+
+ return media
+}
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-view/index.ts b/packages/vendor/src/pages/products/[id]/media/product-media-view/index.ts
new file mode 100644
index 000000000..da348356f
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-view/index.ts
@@ -0,0 +1 @@
+export * from "./product-media-view"
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view-context.tsx b/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view-context.tsx
new file mode 100644
index 000000000..c1eda4eb3
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view-context.tsx
@@ -0,0 +1,9 @@
+import { createContext } from "react"
+
+type ProductMediaViewContextValue = {
+ goToGallery: () => void
+ goToEdit: () => void
+}
+
+export const ProductMediaViewContext =
+ createContext<ProductMediaViewContextValue | null>(null)
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view.tsx b/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view.tsx
new file mode 100644
index 000000000..d1fcf6891
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-view/product-media-view.tsx
@@ -0,0 +1,54 @@
+import { useSearchParams } from "react-router-dom"
+import { EditProductMediaForm } from "../edit-product-media-form"
+import { ProductMediaGallery } from "../product-media-gallery"
+import { ProductMediaViewContext } from "./product-media-view-context"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+type ProductMediaViewProps = {
+ product: ExtendedAdminProduct
+}
+
+enum View {
+ GALLERY = "gallery",
+ EDIT = "edit",
+}
+
+const getView = (searchParams: URLSearchParams) => {
+ const view = searchParams.get("view")
+ if (view === View.EDIT) {
+ return View.EDIT
+ }
+
+ return View.GALLERY
+}
+
+export const ProductMediaView = ({ product }: ProductMediaViewProps) => {
+ const [searchParams, setSearchParams] = useSearchParams()
+ const view = getView(searchParams)
+
+ const handleGoToView = (view: View) => {
+ return () => {
+ setSearchParams({ view })
+ }
+ }
+
+ return (
+ <ProductMediaViewContext.Provider
+ value={{
+ goToGallery: handleGoToView(View.GALLERY),
+ goToEdit: handleGoToView(View.EDIT),
+ }}
+ >
+ {renderView(view, product)}
+ </ProductMediaViewContext.Provider>
+ )
+}
+
+const renderView = (view: View, product: ExtendedAdminProduct) => {
+ switch (view) {
+ case View.GALLERY:
+ return <ProductMediaGallery product={product} />
+ case View.EDIT:
+ return <EditProductMediaForm product={product} />
+ }
+}
diff --git a/packages/vendor/src/pages/products/[id]/media/product-media-view/use-product-media-view.tsx b/packages/vendor/src/pages/products/[id]/media/product-media-view/use-product-media-view.tsx
new file mode 100644
index 000000000..0e513d0d6
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/media/product-media-view/use-product-media-view.tsx
@@ -0,0 +1,14 @@
+import { useContext } from "react"
+import { ProductMediaViewContext } from "./product-media-view-context"
+
+export const useProductMediaView = () => {
+ const context = useContext(ProductMediaViewContext)
+
+ if (!context) {
+ throw new Error(
+ "useProductMediaView must be used within a ProductMediaViewProvider"
+ )
+ }
+
+ return context
+}
diff --git a/packages/vendor/src/pages/products/[id]/metadata/index.tsx b/packages/vendor/src/pages/products/[id]/metadata/index.tsx
new file mode 100644
index 000000000..4e15bd650
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/metadata/index.tsx
@@ -0,0 +1,27 @@
+// Route: /products/:id/metadata
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form/metadata-form"
+import { useProduct, useUpdateProduct } from "@hooks/api"
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { product, isPending, isError, error } = useProduct(id!)
+
+ const { mutateAsync, isPending: isMutating } = useUpdateProduct(
+ product?.id || id!
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <MetadataForm
+ metadata={product?.metadata}
+ hook={mutateAsync}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/create-product-option-form.tsx b/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/create-product-option-form.tsx
new file mode 100644
index 000000000..283a655af
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/create-product-option-form.tsx
@@ -0,0 +1,126 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Form } from "@components/common/form"
+import { ChipInput } from "@components/inputs/chip-input"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateProductOption } from "@hooks/api/products"
+
+type EditProductOptionsFormProps = {
+ product: ExtendedAdminProduct
+}
+
+const CreateProductOptionSchema = z.object({
+ title: z.string().min(1),
+ values: z.array(z.string()).optional(),
+})
+
+export const CreateProductOptionForm = ({
+ product,
+}: EditProductOptionsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof CreateProductOptionSchema>>({
+ defaultValues: {
+ title: "",
+ values: [],
+ },
+ resolver: zodResolver(CreateProductOptionSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateProductOption(product.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const payload = {
+ title: values.title,
+ values: values.values || [],
+ }
+
+ mutateAsync(payload, {
+ onSuccess: () => {
+ toast.success(
+ t("products.options.create.successToast", {
+ title: values.title,
+ })
+ )
+ handleSuccess()
+ },
+ onError: async (err) => {
+ toast.error(err.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("products.fields.options.optionTitle")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t(
+ "products.fields.options.optionTitlePlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="values"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("products.fields.options.variations")}
+ </Form.Label>
+ <Form.Control>
+ <ChipInput
+ {...field}
+ placeholder={t(
+ "products.fields.options.variantionsPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/index.ts b/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/index.ts
new file mode 100644
index 000000000..72faecda0
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/options/create/create-product-option-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-product-option-form"
diff --git a/packages/vendor/src/pages/products/[id]/options/create/index.tsx b/packages/vendor/src/pages/products/[id]/options/create/index.tsx
new file mode 100644
index 000000000..19b473306
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/options/create/index.tsx
@@ -0,0 +1,27 @@
+// Route: /products/:id/options/create
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { CreateProductOptionForm } from "./create-product-option-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product, isLoading, isError, error } = useProduct(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("products.options.create.header")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && product && <CreateProductOptionForm product={product} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/organization/index.tsx b/packages/vendor/src/pages/products/[id]/organization/index.tsx
new file mode 100644
index 000000000..efd6ab118
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/organization/index.tsx
@@ -0,0 +1,32 @@
+// Route: /products/:id/organization
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { ProductOrganizationForm } from "./product-organization-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product, isLoading, isError, error } = useProduct(id!, {
+ fields: "*categories",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.organization.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+ {!isLoading && product && <ProductOrganizationForm product={product} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/organization/product-organization-form/index.ts b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/index.ts
new file mode 100644
index 000000000..7562195f5
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-organization-form"
diff --git a/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx
new file mode 100644
index 000000000..68c44ba8f
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/organization/product-organization-form/product-organization-form.tsx
@@ -0,0 +1,251 @@
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Button, toast } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import {
+ FormExtensionZone,
+ useDashboardExtension,
+ useExtendableForm,
+} from "@/extensions"
+import { useUpdateProduct } from "@hooks/api/products"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { fetchQuery } from "@lib/client"
+
+type ProductOrganizationFormProps = {
+ product: ExtendedAdminProduct
+}
+
+const ProductOrganizationSchema = zod.object({
+ type_id: zod.string().nullable(),
+ collection_id: zod.string().nullable(),
+ category_ids: zod.string().nullable(),
+ // category_ids: zod.array(zod.string()),
+ tag_ids: zod.array(zod.string()),
+})
+
+export const ProductOrganizationForm = ({
+ product,
+}: ProductOrganizationFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { getFormConfigs, getFormFields } = useDashboardExtension()
+
+ const configs = getFormConfigs("product", "organize")
+ const fields = getFormFields("product", "organize")
+
+ const categories = useComboboxData({
+ queryKey: ["product_categories"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-categories", {
+ method: "GET",
+ query: params as Record<string, string | number>,
+ }),
+ getOptions: (data) =>
+ data.product_categories.map((category: any) => ({
+ label: category.name!,
+ value: category.id!,
+ })),
+ })
+
+ const collections = useComboboxData({
+ queryKey: ["product_collections"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-collections", {
+ method: "GET",
+ query: params as Record<string, string | number>,
+ }),
+ getOptions: (data) =>
+ data.product_collections.map((collection: any) => ({
+ label: collection.title!,
+ value: collection.id!,
+ })),
+ })
+
+ const types = useComboboxData({
+ queryKey: ["product_types"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-types", {
+ method: "GET",
+ query: params as { [key: string]: string | number },
+ }),
+ getOptions: (data) =>
+ data.product_types.map((type: any) => ({
+ label: type.value,
+ value: type.id,
+ })),
+ })
+
+ const tags = useComboboxData({
+ queryKey: ["product_tags"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-tags", {
+ method: "GET",
+ query: params as { [key: string]: string | number },
+ }),
+ getOptions: (data) =>
+ data.product_tags.map((tag: any) => ({
+ label: tag.value,
+ value: tag.id,
+ })),
+ })
+
+ const form = useExtendableForm({
+ defaultValues: {
+ type_id: product.type_id ?? "",
+ collection_id: product.collection_id ?? "",
+ category_ids: product.categories?.[0]?.id || "",
+ tag_ids: product.tags?.map((t) => t.id) || [],
+ },
+ schema: ProductOrganizationSchema,
+ configs: configs,
+ data: product,
+ })
+
+ const { mutateAsync, isPending } = useUpdateProduct(product.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ type_id: data.type_id ? data.type_id : undefined,
+ collection_id: data.collection_id ? data.collection_id : undefined,
+ categories: data.category_ids ? [{ id: data.category_ids }] : [],
+ tags: data.tag_ids?.map((t) => ({ id: t })) ?? [],
+ },
+ {
+ onSuccess: ({ product }) => {
+ toast.success(
+ t("products.organization.edit.toasts.success", {
+ title: product.title,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
+ <RouteDrawer.Body>
+ <div className="flex h-full flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="type_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.type.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={types.options}
+ searchValue={types.searchValue}
+ onSearchValueChange={types.onSearchValueChange}
+ fetchNextPage={types.fetchNextPage}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="collection_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.collection.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ multiple={false}
+ options={collections.options}
+ onSearchValueChange={collections.onSearchValueChange}
+ searchValue={collections.searchValue}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="category_ids"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.categories.label")}
+ </Form.Label>
+ <Form.Control>
+ {/* <CategoryCombobox {...field} /> */}
+ <Combobox
+ {...field}
+ multiple={false}
+ options={categories.options}
+ onSearchValueChange={categories.onSearchValueChange}
+ searchValue={categories.searchValue}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="tag_ids"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.tags.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ multiple
+ options={tags.options}
+ onSearchValueChange={tags.onSearchValueChange}
+ searchValue={tags.searchValue}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <FormExtensionZone fields={fields} form={form} />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/prices/index.tsx b/packages/vendor/src/pages/products/[id]/prices/index.tsx
new file mode 100644
index 000000000..76b4bb03d
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/prices/index.tsx
@@ -0,0 +1,25 @@
+// Route: /products/:id/prices OR /products/:product_id/variants/:variant_id/prices
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { PricingEdit } from "./pricing-edit"
+
+export const Component = () => {
+ const { id, product_id, variant_id } = useParams()
+ const productId = id || product_id
+
+ const { product, isLoading, isError, error } = useProduct(productId!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && product && (
+ <PricingEdit product={product} variantId={variant_id} />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/prices/pricing-edit.tsx b/packages/vendor/src/pages/products/[id]/prices/pricing-edit.tsx
new file mode 100644
index 000000000..c70a3c572
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/prices/pricing-edit.tsx
@@ -0,0 +1,190 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useMemo } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { RouteFocusModal, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProductVariant } from "@hooks/api/products"
+import { useRegions } from "@hooks/api/regions"
+import { castNumber } from "@lib/cast-number"
+import { VariantPricingForm } from "../../common/variant-pricing-form"
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+export const UpdateVariantPricesSchema = zod.object({
+ variants: zod.array(
+ zod.object({
+ prices: zod
+ .record(zod.string(), zod.string().or(zod.number()).optional())
+ .optional(),
+ })
+ ),
+})
+
+export type UpdateVariantPricesSchemaType = zod.infer<
+ typeof UpdateVariantPricesSchema
+>
+
+export const PricingEdit = ({
+ product,
+ variantId,
+}: {
+ product: ExtendedAdminProduct
+ variantId?: string
+}) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ // const { mutateAsync, isPending } = useUpdateProductVariantsBatch(product.id)
+ const { mutateAsync, isPending } = useUpdateProductVariant(
+ product.id,
+ variantId!
+ )
+
+ const { regions } = useRegions({ limit: 9999 })
+ const regionsCurrencyMap = useMemo(() => {
+ if (!regions?.length) {
+ return {}
+ }
+
+ return regions.reduce(
+ (acc, reg) => {
+ acc[reg.id] = reg.currency_code
+ return acc
+ },
+ {} as Record<string, string>
+ )
+ }, [regions])
+
+ const variants = variantId
+ ? product.variants?.filter((v) => v.id === variantId)
+ : product.variants
+
+ const form = useForm<UpdateVariantPricesSchemaType>({
+ defaultValues: {
+ variants: variants?.map((variant) => ({
+ title: variant.title,
+ prices:
+ variant.prices?.reduce(
+ (acc, price) => {
+ const priceWithRules = price as HttpTypes.AdminPrice & {
+ rules?: { region_id?: string; [key: string]: unknown }
+ }
+ if (priceWithRules.rules?.region_id) {
+ acc[priceWithRules.rules.region_id] = price.amount
+ } else {
+ acc[price.currency_code] = price.amount
+ }
+ return acc
+ },
+ {} as Record<string, number>
+ ) || {},
+ })),
+ },
+
+ resolver: zodResolver(UpdateVariantPricesSchema, {}),
+ })
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const reqData = values.variants.map((variant, ind) => {
+ const currentVariant = variants?.[ind]
+ if (!currentVariant) {
+ return null
+ }
+
+ return {
+ ...currentVariant,
+ prices: Object.entries(variant.prices || {})
+ .filter(
+ ([_, value]) => value !== "" && typeof value !== "undefined" // deleted cells
+ )
+ .map(([currencyCodeOrRegionId, value]) => {
+ const regionId = currencyCodeOrRegionId.startsWith("reg_")
+ ? currencyCodeOrRegionId
+ : undefined
+ const currencyCode = currencyCodeOrRegionId.startsWith("reg_")
+ ? regionsCurrencyMap[regionId as string]
+ : currencyCodeOrRegionId
+
+ let existingId: string | undefined
+
+ if (regionId && currentVariant.prices) {
+ existingId = currentVariant.prices.find((p) => {
+ const priceWithRules = p as HttpTypes.AdminPrice & {
+ rules?: { region_id?: string; [key: string]: unknown }
+ }
+ return priceWithRules.rules?.region_id === regionId
+ })?.id
+ } else if (currentVariant.prices) {
+ existingId = currentVariant.prices.find((p) => {
+ const priceWithRules = p as HttpTypes.AdminPrice & {
+ rules?: { region_id?: string; [key: string]: unknown }
+ }
+ return (
+ p.currency_code === currencyCode &&
+ Object.keys(priceWithRules.rules ?? {}).length === 0
+ )
+ })?.id
+ }
+
+ const amount = castNumber(value!)
+
+ return {
+ id: existingId,
+ currency_code: currencyCode || "",
+ amount,
+ ...(regionId ? { rules: { region_id: regionId } } : {}),
+ }
+ }),
+ }
+ })
+
+ const data = reqData[0]
+
+ if (!data) {
+ return
+ }
+
+ const cleanData: HttpTypes.AdminUpdateProductVariant = {
+ title: data.title || undefined,
+ sku: data.sku || undefined,
+ prices: data.prices,
+ }
+
+ await mutateAsync(cleanData, {
+ onSuccess: () => {
+ handleSuccess("..")
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex size-full flex-col">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-col overflow-hidden">
+ <VariantPricingForm form={form as any} product={product} />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex w-full items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isPending}
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/edit-sales-channels-form.tsx b/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/edit-sales-channels-form.tsx
new file mode 100644
index 000000000..a30717d78
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/edit-sales-channels-form.tsx
@@ -0,0 +1,156 @@
+import { Button, createDataTableColumnHelper } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { RowSelectionState } from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useForm } from "react-hook-form"
+import { DataTable } from "@components/data-table"
+import * as hooks from "@components/data-table/helpers/sales-channels"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { useUpdateProduct } from "@hooks/api/products"
+import { useSalesChannels } from "@hooks/api/sales-channels"
+
+type EditSalesChannelsFormProps = {
+ product: ExtendedAdminProduct
+}
+
+const EditSalesChannelsSchema = zod.object({
+ sales_channels: zod.array(zod.string()).optional(),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "sc"
+
+export const EditSalesChannelsForm = ({
+ product,
+}: EditSalesChannelsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditSalesChannelsSchema>>({
+ defaultValues: {
+ sales_channels: product.sales_channels?.map((sc) => sc.id) ?? [],
+ },
+ resolver: zodResolver(EditSalesChannelsSchema),
+ })
+
+ const { setValue } = form
+
+ const initialState =
+ product.sales_channels?.reduce((acc, curr) => {
+ acc[curr.id] = true
+ return acc
+ }, {} as RowSelectionState) ?? {}
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialState)
+
+ useEffect(() => {
+ const ids = Object.keys(rowSelection)
+ setValue("sales_channels", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ }, [rowSelection, setValue])
+
+ const searchParams = hooks.useSalesChannelTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { sales_channels, count, isLoading, isError, error } = useSalesChannels(
+ {
+ ...searchParams,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = hooks.useSalesChannelTableFilters()
+ const emptyState = hooks.useSalesChannelTableEmptyState()
+ const columns = useColumns()
+
+ const { mutateAsync, isPending: isMutating } = useUpdateProduct(product.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const arr = data.sales_channels ?? []
+
+ const sales_channels = arr.map((id) => {
+ return {
+ id,
+ }
+ })
+
+ await mutateAsync(
+ {
+ sales_channels,
+ },
+ {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ }
+ )
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <div className="flex h-full flex-col overflow-hidden">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex-1 overflow-hidden">
+ <DataTable
+ data={sales_channels}
+ columns={columns}
+ getRowId={(row) => row.id}
+ rowCount={count}
+ isLoading={isLoading}
+ filters={filters}
+ rowSelection={{
+ state: rowSelection,
+ onRowSelectionChange: setRowSelection,
+ }}
+ autoFocusSearch
+ layout="fill"
+ emptyState={emptyState}
+ prefix={PREFIX}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" isLoading={isMutating} onClick={handleSubmit}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </div>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper =
+ createDataTableColumnHelper<
+ HttpTypes.AdminSalesChannelResponse["sales_channel"]
+ >()
+
+const useColumns = () => {
+ const columns = hooks.useSalesChannelTableColumns()
+
+ return useMemo(() => [columnHelper.select(), ...columns], [columns])
+}
diff --git a/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/index.ts b/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/index.ts
new file mode 100644
index 000000000..812e22843
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/sales-channels/edit-sales-channels-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-sales-channels-form"
diff --git a/packages/vendor/src/pages/products/[id]/sales-channels/index.tsx b/packages/vendor/src/pages/products/[id]/sales-channels/index.tsx
new file mode 100644
index 000000000..3dcf63c1a
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/sales-channels/index.tsx
@@ -0,0 +1,21 @@
+// Route: /products/:id/sales-channels
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { EditSalesChannelsForm } from "./edit-sales-channels-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { product, isLoading, isError, error } = useProduct(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && product && <EditSalesChannelsForm product={product} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/shipping-profile/index.tsx b/packages/vendor/src/pages/products/[id]/shipping-profile/index.tsx
new file mode 100644
index 000000000..e4588d23e
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/shipping-profile/index.tsx
@@ -0,0 +1,35 @@
+// Route: /products/:id/shipping-profile
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { PRODUCT_DETAIL_FIELDS } from "../constants"
+import { ProductShippingProfileForm } from "./product-organization-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product, isLoading, isError, error } = useProduct(id!, {
+ fields: PRODUCT_DETAIL_FIELDS,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.shippingProfile.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+ {!isLoading && product && (
+ <ProductShippingProfileForm product={product} />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/index.ts b/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/index.ts
new file mode 100644
index 000000000..7f9da9dba
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-shipping-profile-form"
diff --git a/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/product-shipping-profile-form.tsx b/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/product-shipping-profile-form.tsx
new file mode 100644
index 000000000..f4c8d2529
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/shipping-profile/product-organization-form/product-shipping-profile-form.tsx
@@ -0,0 +1,133 @@
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { Button, toast } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProduct } from "@hooks/api/products"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { sdk } from "@lib/client"
+import { useForm } from "react-hook-form"
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useEffect } from "react"
+
+type ProductShippingProfileFormProps = {
+ product: ExtendedAdminProduct & {
+ shipping_profile?: HttpTypes.AdminShippingProfile
+ }
+}
+
+const ProductShippingProfileSchema = zod.object({
+ shipping_profile_id: zod.string(),
+})
+
+export const ProductShippingProfileForm = ({
+ product,
+}: ProductShippingProfileFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const shippingProfiles = useComboboxData({
+ queryKey: ["shipping_profiles"],
+ queryFn: (params) => sdk.admin.shippingProfile.list(params),
+ getOptions: (data) =>
+ data.shipping_profiles.map((shippingProfile) => ({
+ label: shippingProfile.name,
+ value: shippingProfile.id,
+ })),
+ })
+
+ const form = useForm({
+ defaultValues: {
+ shipping_profile_id: product.shipping_profile?.id ?? "",
+ },
+ resolver: zodResolver(ProductShippingProfileSchema),
+ })
+
+ const selectedShippingProfile = form.watch("shipping_profile_id")
+
+ const { mutateAsync, isPending } = useUpdateProduct(product.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ shipping_profile_id:
+ data.shipping_profile_id === "" ? null : data.shipping_profile_id,
+ },
+ {
+ onSuccess: ({ product }) => {
+ toast.success(
+ t("products.shippingProfile.edit.toasts.success", {
+ title: product.title,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ useEffect(() => {
+ if (typeof selectedShippingProfile === "undefined") {
+ form.setValue("shipping_profile_id", "")
+ }
+ }, [selectedShippingProfile])
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
+ <RouteDrawer.Body>
+ <div className="flex h-full flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="shipping_profile_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("products.fields.shipping_profile.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ allowClear
+ options={shippingProfiles.options}
+ searchValue={shippingProfiles.searchValue}
+ onSearchValueChange={
+ shippingProfiles.onSearchValueChange
+ }
+ fetchNextPage={shippingProfiles.fetchNextPage}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ {/* <FormExtensionZone fields={fields} form={form} /> */}
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/stock/index.tsx b/packages/vendor/src/pages/products/[id]/stock/index.tsx
new file mode 100644
index 000000000..b5d975ed3
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/index.tsx
@@ -0,0 +1,106 @@
+// Route: /products/:id/stock
+import { AnimatePresence } from "motion/react"
+import { Suspense, useEffect, useRef, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Await, useParams } from "react-router-dom"
+
+import { ColumnDef } from "@tanstack/react-table"
+import { ProgressBar } from "@components/common/progress-bar"
+import { Skeleton } from "@components/common/skeleton"
+import { DataGridSkeleton } from "@components/data-grid/components"
+import { RouteFocusModal } from "@components/modals"
+import { ProductStockForm } from "./product-stock-form"
+import { useProduct, useStockLocations } from "@hooks/api"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ const { id } = useParams()
+
+ const { product, isLoading: isProductLoading } = useProduct(id!)
+ const { stock_locations, isLoading: isStockLoading } = useStockLocations()
+
+ const allVariants = product?.variants?.map((variant) => ({
+ ...variant,
+ inventory_items: variant.inventory_items?.map((item) => ({
+ ...item,
+ inventory: item.inventory,
+ })),
+ }))
+
+ const [isLoading, setIsLoading] = useState(false)
+ const timeoutRef = useRef<ReturnType<typeof setTimeout>>()
+
+ useEffect(() => {
+ timeoutRef.current = setTimeout(() => {
+ setIsLoading(true)
+ }, 200)
+
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current)
+ }
+ }
+ }, [])
+
+ const onLoaded = () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current)
+ }
+ setIsLoading(false)
+ }
+
+ return (
+ <div>
+ <div className="fixed inset-x-0 top-0 z-50 h-1">
+ <AnimatePresence>
+ {isLoading || isProductLoading || isStockLoading ? (
+ <ProgressBar duration={5} />
+ ) : null}
+ </AnimatePresence>
+ </div>
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">{t("products.stock.heading")}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <span className="sr-only">{t("products.stock.description")}</span>
+ </RouteFocusModal.Description>
+ <Suspense fallback={<ProductStockFallback />}>
+ <Await resolve={{ allVariants, locations: stock_locations }}>
+ {() => {
+ return (
+ <ProductStockForm
+ variants={allVariants || []}
+ locations={stock_locations || []}
+ onLoaded={onLoaded}
+ />
+ )
+ }}
+ </Await>
+ </Suspense>
+ </RouteFocusModal>
+ </div>
+ )
+}
+
+const ProductStockFallback = () => {
+ return (
+ <div className="relative flex size-full flex-col items-center justify-center divide-y">
+ <div className="flex size-full flex-col divide-y">
+ <div className="px-4 py-2">
+ <Skeleton className="h-7 w-7" />
+ </div>
+ <div className="flex-1 overflow-auto">
+ <DataGridSkeleton
+ columns={Array.from({ length: 10 }) as ColumnDef<any>[]}
+ />
+ </div>
+ <div className="bg-ui-bg-base flex items-center justify-end gap-x-2 p-4">
+ <Skeleton className="h-7 w-[59px]" />
+ <Skeleton className="h-7 w-[46px]" />
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/stock/product-stock-form/index.ts b/packages/vendor/src/pages/products/[id]/stock/product-stock-form/index.ts
new file mode 100644
index 000000000..d65f902d5
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/product-stock-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-stock-form"
diff --git a/packages/vendor/src/pages/products/[id]/stock/product-stock-form/product-stock-form.tsx b/packages/vendor/src/pages/products/[id]/stock/product-stock-form/product-stock-form.tsx
new file mode 100644
index 000000000..289b6d091
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/product-stock-form/product-stock-form.tsx
@@ -0,0 +1,223 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, toast, usePrompt } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useEffect, useMemo, useRef, useState } from "react"
+import { DefaultValues, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { DataGrid } from "@components/data-grid"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useBatchInventoryItemsLocationLevels } from "@hooks/api"
+import { castNumber } from "@lib/cast-number"
+import { useProductStockColumns } from "../use-product-stock-columns"
+import {
+ ProductStockInventoryItemSchema,
+ ProductStockLocationSchema,
+ ProductStockSchema,
+ ProductStockVariantSchema,
+} from "../schema"
+import {
+ getDisabledInventoryRows,
+ isProductVariantWithInventoryPivot,
+} from "../utils"
+import {
+ ExtendedAdminProductVariant,
+ ProductStockGridRow,
+} from "@custom-types/products"
+
+type ProductStockFormProps = {
+ variants: ExtendedAdminProductVariant[]
+ locations: HttpTypes.AdminStockLocation[]
+ onLoaded: () => void
+}
+
+export const ProductStockForm = ({
+ variants,
+ locations,
+ onLoaded,
+}: ProductStockFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess, setCloseOnEscape } = useRouteModal()
+ const prompt = usePrompt()
+
+ useEffect(() => {
+ onLoaded()
+ }, [onLoaded])
+
+ const [isPromptOpen, setIsPromptOpen] = useState(false)
+
+ const form = useForm<ProductStockSchema>({
+ defaultValues: getDefaultValue(variants, locations),
+ resolver: zodResolver(ProductStockSchema),
+ })
+
+ const initialValues = useRef(getDefaultValue(variants, locations))
+
+ const disabled = useMemo(() => getDisabledInventoryRows(variants), [variants])
+ const columns = useProductStockColumns(locations, disabled)
+
+ const { mutateAsync, isPending } = useBatchInventoryItemsLocationLevels()
+
+ const onSubmit = form.handleSubmit(async (data) => {
+ const payload: HttpTypes.AdminBatchInventoryItemsLocationLevels = {
+ create: [],
+ update: [],
+ delete: [],
+ force: true,
+ }
+
+ for (const [variantId, variant] of Object.entries(data.variants)) {
+ for (const [inventory_item_id, item] of Object.entries(
+ variant.inventory_items
+ )) {
+ for (const [location_id, level] of Object.entries(item.locations)) {
+ if (level.id) {
+ const wasChecked =
+ initialValues.current?.variants?.[variantId]?.inventory_items?.[
+ inventory_item_id
+ ]?.locations?.[location_id]?.checked
+
+ if (wasChecked && !level.checked) {
+ payload.delete.push(level.id)
+ } else {
+ const newQuantity =
+ level.quantity !== "" ? castNumber(level.quantity) : 0
+ const originalQuantity =
+ initialValues.current?.variants?.[variantId]?.inventory_items?.[
+ inventory_item_id
+ ]?.locations?.[location_id]?.quantity
+
+ if (newQuantity !== originalQuantity) {
+ payload.update.push({
+ inventory_item_id,
+ location_id,
+ stocked_quantity: newQuantity,
+ })
+ }
+ }
+ }
+
+ if (!level.id && level.quantity !== "") {
+ payload.create.push({
+ inventory_item_id,
+ location_id,
+ stocked_quantity: castNumber(level.quantity),
+ })
+ }
+ }
+ }
+ }
+
+ if (payload.delete.length > 0) {
+ setIsPromptOpen(true)
+ const confirm = await prompt({
+ title: t("general.areYouSure"),
+ description: t("inventory.stock.disablePrompt", {
+ count: payload.delete.length,
+ }),
+ confirmText: t("actions.continue"),
+ cancelText: t("actions.cancel"),
+ variant: "confirmation",
+ })
+
+ setIsPromptOpen(false)
+
+ if (!confirm) {
+ return
+ }
+ }
+
+ await mutateAsync(payload, {
+ onSuccess: () => {
+ toast.success(t("inventory.stock.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={onSubmit} className="flex h-full flex-col">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex-1">
+ <DataGrid
+ state={form}
+ columns={columns}
+ data={variants as ProductStockGridRow[]}
+ getSubRows={getSubRows}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ disableInteractions={isPending || isPromptOpen}
+ multiColumnSelection={true}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+function getSubRows(row: ProductStockGridRow): ProductStockGridRow[] | undefined {
+ if (isProductVariantWithInventoryPivot(row)) {
+ return row.inventory_items
+ }
+}
+
+function getDefaultValue(
+ variants: ExtendedAdminProductVariant[],
+ locations: HttpTypes.AdminStockLocation[]
+): DefaultValues<ProductStockSchema> {
+ return {
+ variants: variants?.reduce(
+ (variantAcc, variant) => {
+ const inventoryItems = variant.inventory_items?.reduce(
+ (itemAcc, item) => {
+ const locationsMap = locations.reduce((locationAcc, location) => {
+ const level = item.inventory?.location_levels?.find(
+ (level) => level.location_id === location.id
+ )
+
+ locationAcc[location.id] = {
+ id: level?.id,
+ quantity:
+ level?.stocked_quantity !== undefined
+ ? level?.stocked_quantity
+ : "",
+ checked: !!level,
+ disabledToggle:
+ (level?.incoming_quantity || 0) > 0 ||
+ (level?.reserved_quantity || 0) > 0,
+ }
+ return locationAcc
+ }, {} as ProductStockLocationSchema)
+
+ itemAcc[item.inventory_item_id] = { locations: locationsMap }
+ return itemAcc
+ },
+ {} as Record<string, ProductStockInventoryItemSchema>
+ )
+
+ variantAcc[variant.id] = { inventory_items: inventoryItems || {} }
+ return variantAcc
+ },
+ {} as Record<string, ProductStockVariantSchema>
+ ),
+ }
+}
diff --git a/packages/vendor/src/pages/products/[id]/stock/schema.ts b/packages/vendor/src/pages/products/[id]/stock/schema.ts
new file mode 100644
index 000000000..4bb3363ed
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/schema.ts
@@ -0,0 +1,25 @@
+import { z } from "zod"
+
+export const ProductStockLocationSchema = z.object({
+ id: z.string().optional(),
+ quantity: z.union([z.number(), z.string()]),
+ checked: z.boolean(),
+ disabledToggle: z.boolean().optional(),
+})
+
+export const ProductStockInventoryItemSchema = z.object({
+ locations: z.record(ProductStockLocationSchema),
+})
+
+export const ProductStockVariantSchema = z.object({
+ inventory_items: z.record(ProductStockInventoryItemSchema),
+})
+
+export const ProductStockSchema = z.object({
+ variants: z.record(ProductStockVariantSchema),
+})
+
+export type ProductStockLocationSchema = z.infer<typeof ProductStockLocationSchema>
+export type ProductStockInventoryItemSchema = z.infer<typeof ProductStockInventoryItemSchema>
+export type ProductStockVariantSchema = z.infer<typeof ProductStockVariantSchema>
+export type ProductStockSchema = z.infer<typeof ProductStockSchema>
diff --git a/packages/vendor/src/pages/products/[id]/stock/use-product-stock-columns.tsx b/packages/vendor/src/pages/products/[id]/stock/use-product-stock-columns.tsx
new file mode 100644
index 000000000..ed4860e15
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/use-product-stock-columns.tsx
@@ -0,0 +1,227 @@
+import { InformationCircle } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Switch, Tooltip } from "@medusajs/ui"
+import { useCallback, useMemo } from "react"
+
+import { useTranslation } from "react-i18next"
+import { Thumbnail } from "@components/common/thumbnail"
+import { createDataGridHelper } from "@components/data-grid"
+import { DataGridReadOnlyCell } from "@components/data-grid/components"
+import { DataGridDuplicateCell } from "@components/data-grid/components/data-grid-duplicate-cell"
+import { DataGridTogglableNumberCell } from "@components/data-grid/components/data-grid-toggleable-number-cell"
+import { ProductStockSchema } from "./schema"
+import { isProductVariant } from "./utils"
+
+const helper = createDataGridHelper<
+ | HttpTypes.AdminProductVariant
+ | HttpTypes.AdminProductVariantInventoryItemLink,
+ ProductStockSchema
+>()
+
+type DisabledItem = { id: string; title: string; sku: string }
+type DisabledResult =
+ | {
+ isDisabled: true
+ item: DisabledItem
+ }
+ | {
+ isDisabled: false
+ item: undefined
+ }
+
+export const useProductStockColumns = (
+ locations: HttpTypes.AdminStockLocation[] = [],
+ disabled: Record<string, DisabledItem> = {}
+) => {
+ const { t } = useTranslation()
+ const getIsDisabled = useCallback(
+ (item: HttpTypes.AdminProductVariantInventoryItemLink): DisabledResult => {
+ const disabledItem = disabled[item.inventory_item_id]
+ const isDisabled = !!disabledItem && disabledItem.id !== item.variant_id
+
+ if (!isDisabled) {
+ return {
+ isDisabled: false,
+ item: undefined,
+ }
+ }
+
+ return {
+ isDisabled,
+ item: disabledItem,
+ }
+ },
+ [disabled]
+ )
+
+ return useMemo(
+ () => [
+ helper.column({
+ id: "title",
+ name: "Title",
+ header: "Title",
+ cell: (context) => {
+ const item = context.row.original
+
+ if (isProductVariant(item)) {
+ return (
+ <DataGridReadOnlyCell context={context}>
+ <div className="flex items-center gap-x-2">
+ <Thumbnail size="small" src={item.product?.thumbnail} />
+ <span>{item.title || "-"}</span>
+ </div>
+ </DataGridReadOnlyCell>
+ )
+ }
+
+ const { isDisabled, item: disabledItem } = getIsDisabled(item)
+
+ if (isDisabled) {
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ <div className="flex size-full items-center justify-between gap-x-2">
+ <span
+ title={item.inventory?.title || undefined}
+ className="text-ui-fg-disabled"
+ >
+ {item.inventory?.title || "-"}
+ </span>
+ <Tooltip
+ content={
+ disabledItem.sku
+ ? t("products.stock.tooltips.alreadyManagedWithSku", {
+ title: disabledItem.title,
+ sku: disabledItem.sku,
+ })
+ : t("products.stock.tooltips.alreadyManaged", {
+ title: disabledItem.title,
+ })
+ }
+ >
+ <InformationCircle />
+ </Tooltip>
+ </div>
+ </DataGridReadOnlyCell>
+ )
+ }
+
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ {item.inventory?.title || "-"}
+ </DataGridReadOnlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ helper.column({
+ id: "sku",
+ name: "SKU",
+ header: "SKU",
+ cell: (context) => {
+ const item = context.row.original
+
+ if (isProductVariant(item)) {
+ return (
+ <DataGridReadOnlyCell context={context}>
+ {item.sku || "-"}
+ </DataGridReadOnlyCell>
+ )
+ }
+
+ const { isDisabled } = getIsDisabled(item)
+
+ if (isDisabled) {
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ <span className="text-ui-fg-disabled">
+ {item.inventory?.sku || "-"}
+ </span>
+ </DataGridReadOnlyCell>
+ )
+ }
+
+ return (
+ <DataGridReadOnlyCell context={context} color="normal">
+ {item.inventory?.sku || "-"}
+ </DataGridReadOnlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ ...locations.map((location) =>
+ helper.column({
+ id: `location_${location.id}`,
+ name: location.name,
+ header: location.name,
+ field: (context) => {
+ const item = context.row.original
+
+ if (isProductVariant(item)) {
+ return null
+ }
+
+ const { isDisabled } = getIsDisabled(item)
+
+ if (isDisabled) {
+ return null
+ }
+
+ return `variants.${item.variant_id}.inventory_items.${item.inventory_item_id}.locations.${location.id}` as const
+ },
+ type: "togglable-number",
+ cell: (context) => {
+ const item = context.row.original
+
+ if (isProductVariant(item)) {
+ return <DataGridReadOnlyCell context={context} />
+ }
+
+ const { isDisabled, item: disabledItem } = getIsDisabled(item)
+
+ if (isDisabled) {
+ return (
+ <DataGridDuplicateCell
+ duplicateOf={`variants.${disabledItem.id}.inventory_items.${item.inventory_item_id}.locations.${location.id}`}
+ >
+ {({ value }) => {
+ const { checked, quantity } = value as {
+ checked: boolean
+ quantity: number | string
+ }
+
+ return (
+ <div className="flex size-full items-center gap-x-2">
+ <Switch
+ dir="ltr"
+ className="shrink-0 cursor-not-allowed rtl:rotate-180"
+ tabIndex={-1}
+ size="small"
+ checked={checked}
+ disabled
+ />
+ <span className="text-ui-fg-disabled flex size-full items-center justify-end">
+ {quantity}
+ </span>
+ </div>
+ )
+ }}
+ </DataGridDuplicateCell>
+ )
+ }
+
+ return (
+ <DataGridTogglableNumberCell
+ context={context}
+ disabledToggleTooltip={t(
+ "inventory.stock.disabledToggleTooltip"
+ )}
+ placeholder={t("inventory.stock.placeholder")}
+ />
+ )
+ },
+ })
+ ),
+ ],
+ [locations, getIsDisabled, t]
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/stock/utils.ts b/packages/vendor/src/pages/products/[id]/stock/utils.ts
new file mode 100644
index 000000000..815b5a97b
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/stock/utils.ts
@@ -0,0 +1,63 @@
+import { HttpTypes } from "@medusajs/types"
+
+/**
+ * Type guard to check if an item is a ProductVariant
+ */
+export function isProductVariant(
+ item: HttpTypes.AdminProductVariant | HttpTypes.AdminProductVariantInventoryItemLink
+): item is HttpTypes.AdminProductVariant {
+ return "product" in item || "product_id" in item
+}
+
+/**
+ * Type guard to check if a variant has inventory items (for sub-row expansion)
+ */
+export function isProductVariantWithInventoryPivot(
+ row: HttpTypes.AdminProductVariant | HttpTypes.AdminProductVariantInventoryItemLink
+): row is HttpTypes.AdminProductVariant & {
+ inventory_items: HttpTypes.AdminProductVariantInventoryItemLink[]
+} {
+ return isProductVariant(row) && Array.isArray(row.inventory_items)
+}
+
+type DisabledItem = { id: string; title: string; sku: string }
+
+/**
+ * Returns a map of inventory items that are already managed by another variant,
+ * used to disable editing for those rows
+ */
+export function getDisabledInventoryRows(
+ variants: HttpTypes.AdminProductVariant[]
+): Record<string, DisabledItem> {
+ const disabled: Record<string, DisabledItem> = {}
+ const inventoryItemToVariant: Record<
+ string,
+ { variantId: string; title: string; sku: string }
+ > = {}
+
+ for (const variant of variants) {
+ if (!variant.inventory_items) continue
+
+ for (const item of variant.inventory_items) {
+ const existingMapping = inventoryItemToVariant[item.inventory_item_id]
+
+ if (existingMapping && existingMapping.variantId !== variant.id) {
+ // This inventory item is already managed by another variant
+ disabled[item.inventory_item_id] = {
+ id: existingMapping.variantId,
+ title: existingMapping.title,
+ sku: existingMapping.sku,
+ }
+ } else if (!existingMapping) {
+ // Record which variant manages this inventory item
+ inventoryItemToVariant[item.inventory_item_id] = {
+ variantId: variant.id,
+ title: variant.title || "",
+ sku: variant.sku || "",
+ }
+ }
+ }
+ }
+
+ return disabled
+}
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/constants.ts b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/constants.ts
new file mode 100644
index 000000000..27802c9b4
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/constants.ts
@@ -0,0 +1,44 @@
+import { z } from "zod"
+import * as zod from "zod"
+import { optionalInt } from "@lib/validation"
+
+export const CreateProductVariantSchema = z.object({
+ title: z.string().min(1),
+ sku: z.string().optional(),
+ manage_inventory: z.boolean().optional(),
+ allow_backorder: z.boolean().optional(),
+ inventory_kit: z.boolean().optional(),
+ options: z.record(z.string()),
+ prices: zod
+ .record(zod.string(), zod.string().or(zod.number()).optional())
+ .optional(),
+ inventory: z
+ .array(
+ z.object({
+ inventory_item_id: z.string(),
+ required_quantity: optionalInt,
+ })
+ )
+ .optional(),
+})
+
+export const CreateVariantDetailsSchema = CreateProductVariantSchema.pick({
+ title: true,
+ sku: true,
+ manage_inventory: true,
+ allow_backorder: true,
+ inventory_kit: true,
+ options: true,
+})
+
+export const CreateVariantDetailsFields = Object.keys(
+ CreateVariantDetailsSchema.shape
+) as (keyof typeof CreateVariantDetailsSchema.shape)[]
+
+export const CreateVariantPriceSchema = CreateProductVariantSchema.pick({
+ prices: true,
+})
+
+export const CreateVariantPriceFields = Object.keys(
+ CreateVariantPriceSchema.shape
+) as (keyof typeof CreateVariantPriceSchema.shape)[]
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/create-product-variant-form.tsx b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/create-product-variant-form.tsx
new file mode 100644
index 000000000..a0bb59813
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/create-product-variant-form.tsx
@@ -0,0 +1,379 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
+import { useEffect, useMemo, useState } from "react"
+import { useFieldArray, useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { AdminCreateProductVariantPrice } from "@medusajs/types"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import {
+ RouteDrawer,
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useRegions } from "@hooks/api"
+import { useCreateProductVariant } from "@hooks/api/products"
+import { castNumber } from "@lib/cast-number"
+import { partialFormValidation } from "@lib/validation"
+import {
+ CreateProductVariantSchema,
+ CreateVariantDetailsFields,
+ CreateVariantDetailsSchema,
+ CreateVariantPriceFields,
+ CreateVariantPriceSchema,
+} from "./constants"
+import DetailsTab from "./details-tab"
+import InventoryKitTab from "./inventory-kit-tab"
+import PricingTab from "./pricing-tab"
+
+enum Tab {
+ DETAIL = "detail",
+ PRICE = "price",
+ INVENTORY = "inventory",
+}
+
+type TabState = Record<Tab, ProgressStatus>
+
+const initialTabState: TabState = {
+ [Tab.DETAIL]: "in-progress",
+ [Tab.PRICE]: "not-started",
+ [Tab.INVENTORY]: "not-started",
+}
+
+type CreateProductVariantFormProps = {
+ product: ExtendedAdminProduct
+}
+
+export const CreateProductVariantForm = ({
+ product,
+}: CreateProductVariantFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const [tab, setTab] = useState<Tab.DETAIL | Tab.PRICE | Tab.INVENTORY>(
+ Tab.DETAIL
+ )
+ const [tabState, setTabState] = useState<TabState>(initialTabState)
+
+ const form = useForm<z.infer<typeof CreateProductVariantSchema>>({
+ defaultValues: {
+ sku: "",
+ title: "",
+ manage_inventory: false,
+ allow_backorder: false,
+ inventory_kit: false,
+ options: {},
+ },
+ resolver: zodResolver(CreateProductVariantSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateProductVariant(product.id)
+
+ const { regions } = useRegions({ limit: 9999 })
+
+ const regionsCurrencyMap = useMemo(() => {
+ if (!regions?.length) {
+ return {}
+ }
+
+ return regions.reduce(
+ (acc, reg) => {
+ acc[reg.id] = reg.currency_code
+ return acc
+ },
+ {} as Record<string, string>
+ )
+ }, [regions])
+
+ const isManageInventoryEnabled = useWatch({
+ control: form.control,
+ name: "manage_inventory",
+ })
+
+ const isInventoryKitEnabled = useWatch({
+ control: form.control,
+ name: "inventory_kit",
+ })
+
+ const inventoryField = useFieldArray({
+ control: form.control,
+ name: `inventory`,
+ })
+
+ const inventoryTabEnabled = isManageInventoryEnabled && isInventoryKitEnabled
+
+ const tabOrder = useMemo(() => {
+ if (inventoryTabEnabled) {
+ return [Tab.DETAIL, Tab.PRICE, Tab.INVENTORY] as const
+ }
+
+ return [Tab.DETAIL, Tab.PRICE, Tab.INVENTORY] as const
+ }, [inventoryTabEnabled])
+
+ useEffect(() => {
+ if (isInventoryKitEnabled && inventoryField.fields.length === 0) {
+ inventoryField.append({
+ inventory_item_id: "",
+ required_quantity: undefined,
+ })
+ }
+ }, [isInventoryKitEnabled])
+
+ const handleChangeTab = (update: Tab.DETAIL | Tab.PRICE | Tab.INVENTORY) => {
+ if (tab === update) {
+ return
+ }
+
+ if (tabOrder.indexOf(update) < tabOrder.indexOf(tab)) {
+ const isCurrentTabDirty = false // isTabDirty(tab) TODO
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: isCurrentTabDirty ? prev[tab] : "not-started",
+ [update]: "in-progress",
+ }))
+
+ setTab(update)
+ return
+ }
+
+ // get the tabs from the current tab to the update tab including the current tab
+ const tabs = tabOrder.slice(0, tabOrder.indexOf(update))
+
+ // validate all the tabs from the current tab to the update tab if it fails on any of tabs then set that tab as current tab
+ for (const tab of tabs) {
+ if (tab === Tab.DETAIL) {
+ if (
+ !partialFormValidation<z.infer<typeof CreateProductVariantSchema>>(
+ form,
+ CreateVariantDetailsFields,
+ CreateVariantDetailsSchema
+ )
+ ) {
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "in-progress",
+ }))
+ setTab(tab)
+ return
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ }))
+ } else if (tab === Tab.PRICE) {
+ if (
+ !partialFormValidation<z.infer<typeof CreateProductVariantSchema>>(
+ form,
+ CreateVariantPriceFields,
+ CreateVariantPriceSchema
+ )
+ ) {
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "in-progress",
+ }))
+ setTab(tab)
+
+ return
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ }))
+ }
+ }
+
+ setTabState((prev) => ({
+ ...prev,
+ [tab]: "completed",
+ [update]: "in-progress",
+ }))
+ setTab(update)
+ }
+
+ const handleNextTab = (tab: Tab.DETAIL | Tab.PRICE | Tab.INVENTORY) => {
+ if (tabOrder.indexOf(tab) + 1 >= tabOrder.length) {
+ return
+ }
+
+ const nextTab = tabOrder[tabOrder.indexOf(tab) + 1]
+ handleChangeTab(nextTab)
+ }
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const { sku, title } = data
+
+ await mutateAsync(
+ {
+ title,
+ sku: sku || undefined,
+ allow_backorder: false,
+ manage_inventory: true,
+ options: data.options,
+ prices: Object.entries(data.prices ?? {})
+ .map(([currencyOrRegion, value]) => {
+ if (value === "" || value === undefined) {
+ return undefined
+ }
+
+ const amount = castNumber(value)
+
+ if (currencyOrRegion.startsWith("reg_")) {
+ return {
+ rules: { region_id: currencyOrRegion },
+ currency_code: regionsCurrencyMap[currencyOrRegion],
+ amount,
+ } as AdminCreateProductVariantPrice
+ } else {
+ return {
+ currency_code: currencyOrRegion,
+ amount,
+ } as AdminCreateProductVariantPrice
+ }
+ })
+ .filter(
+ (price) => !!price
+ ),
+ },
+ {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <ProgressTabs
+ value={tab}
+ onValueChange={(tab) => handleChangeTab(tab as Tab)}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex w-full items-center justify-between gap-x-4">
+ <div className="-my-2 w-full max-w-[600px] border-l">
+ <ProgressTabs.List className="grid w-full grid-cols-3">
+ <ProgressTabs.Trigger
+ status={tabState.detail}
+ value={Tab.DETAIL}
+ >
+ {t("priceLists.create.tabs.details")}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState.price}
+ value={Tab.PRICE}
+ >
+ {t("priceLists.create.tabs.prices")}
+ </ProgressTabs.Trigger>
+ {!!inventoryTabEnabled && (
+ <ProgressTabs.Trigger
+ status={tabState.inventory}
+ value={Tab.INVENTORY}
+ >
+ {t("products.create.tabs.inventory")}
+ </ProgressTabs.Trigger>
+ )}
+ </ProgressTabs.List>
+ </div>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.DETAIL}
+ >
+ <DetailsTab form={form} product={product} />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.PRICE}
+ >
+ <PricingTab form={form} />
+ </ProgressTabs.Content>
+ {!!inventoryTabEnabled && (
+ <ProgressTabs.Content
+ className="size-full overflow-hidden"
+ value={Tab.INVENTORY}
+ >
+ <InventoryKitTab form={form} />
+ </ProgressTabs.Content>
+ )}
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <PrimaryButton
+ tab={tab}
+ next={handleNextTab}
+ isLoading={isPending}
+ inventoryTabEnabled={!!inventoryTabEnabled}
+ />
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </ProgressTabs>
+ </RouteFocusModal.Form>
+ )
+}
+
+type PrimaryButtonProps = {
+ tab: Tab
+ next: (tab: Tab) => void
+ isLoading?: boolean
+ inventoryTabEnabled: boolean
+}
+
+const PrimaryButton = ({
+ tab,
+ next,
+ isLoading,
+ inventoryTabEnabled,
+}: PrimaryButtonProps) => {
+ const { t } = useTranslation()
+
+ if (
+ (inventoryTabEnabled && tab === Tab.INVENTORY) ||
+ (!inventoryTabEnabled && tab === Tab.PRICE)
+ ) {
+ return (
+ <Button
+ key="submit-button"
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isLoading}
+ >
+ {t("actions.save")}
+ </Button>
+ )
+ }
+
+ return (
+ <Button
+ key="next-button"
+ type="button"
+ variant="primary"
+ size="small"
+ onClick={() => next(tab)}
+ >
+ {t("actions.continue")}
+ </Button>
+ )
+}
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/details-tab.tsx b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/details-tab.tsx
new file mode 100644
index 000000000..2283ff260
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/details-tab.tsx
@@ -0,0 +1,122 @@
+import { Heading, Input } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { ExtendedAdminProduct } from "@custom-types/products"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { CreateProductVariantSchema } from "./constants"
+
+type DetailsTabProps = {
+ product: ExtendedAdminProduct
+ form: UseFormReturn<z.infer<typeof CreateProductVariantSchema>>
+}
+
+function DetailsTab({ form, product }: DetailsTabProps) {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-8 py-16">
+ <Heading level="h1">{t("products.variant.create.header")}</Heading>
+
+ <div className="my-8 grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.title")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="sku"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.sku")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ {(product.options || []).map((option: any) => (
+ <Form.Field
+ key={option.id}
+ control={form.control}
+ name={`options.${option.title}`}
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{option.title}</Form.Label>
+ <Form.Control>
+ <Combobox
+ value={value}
+ onChange={(v) => {
+ onChange(v)
+ }}
+ {...field}
+ options={option.values.map((v: any) => ({
+ label: v.value,
+ value: v.value,
+ }))}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ ))}
+ </div>
+ {/* <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="inventory_kit"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div className="bg-ui-bg-component shadow-elevation-card-rest flex gap-x-3 rounded-lg p-4">
+ <Form.Control>
+ <Switch
+ checked={value}
+ onCheckedChange={(checked) => onChange(!!checked)}
+ {...field}
+ disabled={!manageInventoryEnabled}
+ />
+ </Form.Control>
+ <div className="flex flex-col">
+ <Form.Label>
+ {t("products.variant.inventory.inventoryKit")}
+ </Form.Label>
+ <Form.Hint>
+ {t("products.variant.inventory.inventoryKitHint")}
+ </Form.Hint>
+ </div>
+ </div>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div> */}
+ </div>
+ </div>
+ )
+}
+
+export default DetailsTab
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/index.ts b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/index.ts
new file mode 100644
index 000000000..968410fc7
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-product-variant-form"
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/inventory-kit-tab.tsx b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/inventory-kit-tab.tsx
new file mode 100644
index 000000000..6d35c409e
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/inventory-kit-tab.tsx
@@ -0,0 +1,187 @@
+import { z } from "zod"
+import { useFieldArray, UseFormReturn } from "react-hook-form"
+import { Button, Heading, IconButton, Input, Label } from "@medusajs/ui"
+
+import { CreateProductVariantSchema } from "./constants"
+import { XMarkMini } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { sdk } from "@lib/client"
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+
+type InventoryKitTabProps = {
+ form: UseFormReturn<z.infer<typeof CreateProductVariantSchema>>
+}
+
+function InventoryKitTab({ form }: InventoryKitTabProps) {
+ const { t } = useTranslation()
+
+ const inventory = useFieldArray({
+ control: form.control,
+ name: `inventory`,
+ })
+
+ const inventoryFormData = inventory.fields
+
+ const items = useComboboxData({
+ queryKey: ["inventory_items"],
+ queryFn: (params) => sdk.admin.inventoryItem.list(params),
+ getOptions: (data) =>
+ data.inventory_items.map((item) => ({
+ label: item.title || item.sku || item.id,
+ value: item.id,
+ })),
+ })
+
+ /**
+ * Will mark an option as disabled if another input already selected that option
+ * @param option
+ * @param inventoryIndex
+ */
+ const isItemOptionDisabled = (
+ option: (typeof items.options)[0],
+ inventoryIndex: number
+ ) => {
+ return inventoryFormData?.some(
+ (i, index) =>
+ index != inventoryIndex && i.inventory_item_id === option.value
+ )
+ }
+
+ return (
+ <div className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div id="organize" className="flex flex-col gap-y-8">
+ <Heading>{t("products.create.inventory.heading")}</Heading>
+
+ <div className="grid gap-y-4">
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex flex-col">
+ <Form.Label>{form.getValues("title")}</Form.Label>
+ <Form.Hint>{t("products.create.inventory.label")}</Form.Hint>
+ </div>
+ <Button
+ size="small"
+ variant="secondary"
+ type="button"
+ onClick={() => {
+ inventory.append({
+ inventory_item_id: "",
+ required_quantity: "",
+ })
+ }}
+ >
+ {t("actions.add")}
+ </Button>
+ </div>
+ {inventory.fields.map((inventoryItem, inventoryIndex) => (
+ <li
+ key={inventoryItem.id}
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-center gap-1.5 rounded-xl p-1.5"
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`inventory.${inventoryIndex}.inventory_item_id`}
+ >
+ {t("fields.item")}
+ </Label>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name={`inventory.${inventoryIndex}.inventory_item_id`}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={items.options.map((o) => ({
+ ...o,
+ disabled: isItemOptionDisabled(
+ o,
+ inventoryIndex
+ ),
+ }))}
+ searchValue={items.searchValue}
+ onSearchValueChange={items.onSearchValueChange}
+ fetchNextPage={items.fetchNextPage}
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ placeholder={t(
+ "products.create.inventory.itemPlaceholder"
+ )}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`inventory.${inventoryIndex}.required_quantity`}
+ >
+ {t("fields.quantity")}
+ </Label>
+ </div>
+ <Form.Field
+ control={form.control}
+ name={`inventory.${inventoryIndex}.required_quantity`}
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ type="number"
+ className="bg-ui-bg-field-component"
+ min={0}
+ value={value}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(Number(value))
+ }
+ }}
+ {...field}
+ placeholder={t(
+ "products.create.inventory.quantityPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ onClick={() => inventory.remove(inventoryIndex)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ ))}
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default InventoryKitTab
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/pricing-tab.tsx b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/pricing-tab.tsx
new file mode 100644
index 000000000..e92ff7125
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/create-product-variant-form/pricing-tab.tsx
@@ -0,0 +1,99 @@
+import { useMemo } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { HttpTypes } from "@medusajs/types"
+import { z } from "zod"
+
+import { CreateProductVariantSchema } from "./constants"
+import { useRegions, useStore } from "@hooks/api"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+import { useRouteModal } from "@components/modals"
+import {
+ createDataGridHelper,
+ createDataGridPriceColumns,
+ DataGrid,
+} from "@components/data-grid"
+
+type PricingTabProps = {
+ form: UseFormReturn<z.infer<typeof CreateProductVariantSchema>>
+}
+
+function PricingTab({ form }: PricingTabProps) {
+ const { store } = useStore()
+ const { regions } = useRegions({ limit: 9999 })
+ const { price_preferences: pricePreferences } = usePricePreferences({})
+
+ const { setCloseOnEscape } = useRouteModal()
+
+ const columns = useVariantPriceGridColumns({
+ currencies: store?.supported_currencies,
+ regions,
+ pricePreferences,
+ })
+
+ const variant = useWatch({
+ control: form.control,
+ }) as any
+
+ return (
+ <DataGrid
+ columns={columns}
+ data={[variant]}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ )
+}
+
+const columnHelper = createDataGridHelper<
+ HttpTypes.AdminProductVariant,
+ z.infer<typeof CreateProductVariantSchema>
+>()
+
+const useVariantPriceGridColumns = ({
+ currencies = [],
+ regions = [],
+ pricePreferences = [],
+}: {
+ currencies?: HttpTypes.AdminStore["supported_currencies"]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}) => {
+ const { t } = useTranslation()
+
+ return useMemo(() => {
+ return [
+ columnHelper.column({
+ id: t("fields.title"),
+ header: t("fields.title"),
+ cell: (context) => {
+ const entity = context.row.original
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ <div className="flex h-full w-full items-center gap-x-2 overflow-hidden">
+ <span className="truncate">{entity.title}</span>
+ </div>
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ ...createDataGridPriceColumns<
+ HttpTypes.AdminProductVariant,
+ z.infer<typeof CreateProductVariantSchema>
+ >({
+ currencies: currencies.map((c) => c.currency_code),
+ pricePreferences,
+ getFieldName: (context, value) => {
+ if (context.column.id?.startsWith("currency_prices")) {
+ return `prices.${value}`
+ }
+ return `prices.${value}`
+ },
+ t,
+ }),
+ ]
+ }, [t, currencies, regions, pricePreferences])
+}
+
+export default PricingTab
diff --git a/packages/vendor/src/pages/products/[id]/variants/create/index.tsx b/packages/vendor/src/pages/products/[id]/variants/create/index.tsx
new file mode 100644
index 000000000..0ecc6b50a
--- /dev/null
+++ b/packages/vendor/src/pages/products/[id]/variants/create/index.tsx
@@ -0,0 +1,21 @@
+// Route: /products/:id/variants/create
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useProduct } from "@hooks/api/products"
+import { CreateProductVariantForm } from "./create-product-variant-form"
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { product, isLoading, isError, error } = useProduct(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && product && <CreateProductVariantForm product={product} />}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/_components/index.ts b/packages/vendor/src/pages/products/_components/index.ts
new file mode 100644
index 000000000..ee665245d
--- /dev/null
+++ b/packages/vendor/src/pages/products/_components/index.ts
@@ -0,0 +1 @@
+export * from "./product-list-table"
diff --git a/packages/vendor/src/pages/products/_components/product-list-table/index.ts b/packages/vendor/src/pages/products/_components/product-list-table/index.ts
new file mode 100644
index 000000000..ee665245d
--- /dev/null
+++ b/packages/vendor/src/pages/products/_components/product-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./product-list-table"
diff --git a/packages/vendor/src/pages/products/_components/product-list-table/product-list-table.tsx b/packages/vendor/src/pages/products/_components/product-list-table/product-list-table.tsx
new file mode 100644
index 000000000..bc86ecaf2
--- /dev/null
+++ b/packages/vendor/src/pages/products/_components/product-list-table/product-list-table.tsx
@@ -0,0 +1,282 @@
+import { Trash } from "@medusajs/icons"
+import {
+ Button,
+ Container,
+ Heading,
+ toast,
+ usePrompt,
+ Checkbox,
+} from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ createColumnHelper,
+ OnChangeFn,
+ RowSelectionState,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { Link, Outlet } from "react-router-dom"
+
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import {
+ useDeleteProduct,
+ useBulkDeleteProducts,
+ useProducts,
+} from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+export const PAGE_SIZE = 10
+
+export const ProductListTable = () => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const updater: OnChangeFn<RowSelectionState> = (newSelection) => {
+ const update =
+ typeof newSelection === "function"
+ ? newSelection(rowSelection)
+ : newSelection
+
+ setRowSelection(update)
+ }
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const options = {
+ placeholderData: keepPreviousData,
+ }
+
+ const { products, count, isLoading, isError, error } = useProducts(
+ searchParams,
+ options
+ )
+
+ const filters = useProductTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: products,
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ pageSize: PAGE_SIZE,
+ getRowId: (row) => row?.id || "",
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ })
+
+ const { mutateAsync } = useBulkDeleteProducts()
+ const prompt = usePrompt()
+
+ const handleDelete = async () => {
+ const keys = Object.keys(rowSelection)
+
+ if (keys.length === 0) {
+ return
+ }
+
+ const res = await prompt({
+ title: t("products.bulkDelete.title"),
+ description: t("products.bulkDelete.description", {
+ count: keys.length,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(keys, {
+ onSuccess: () => {
+ setRowSelection({})
+ toast.success(
+ t("products.bulkDelete.success", {
+ count: keys.length,
+ })
+ )
+ },
+ onError: (error) => {
+ toast.error(t("products.bulkDelete.error"), {
+ description: error.message,
+ })
+ },
+ })
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("products.domain")}</Heading>
+ <div className="flex items-center justify-center gap-x-2">
+ <Button size="small" variant="secondary" asChild>
+ <Link to={`export${location.search}`}>{t("actions.export")}</Link>
+ </Button>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="import">{t("actions.import")}</Link>
+ </Button>
+ <Button size="small" variant="primary" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ filters={filters}
+ search
+ pagination
+ isLoading={isLoading}
+ queryObject={raw}
+ navigateTo={(row) => `${row.original.id}`}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ commands={[
+ {
+ action: handleDelete,
+ label: t("actions.delete"),
+ shortcut: "d",
+ },
+ ]}
+ noRecords={{
+ title: t("products.list.noRecordsTitle"),
+ message: t("products.list.noRecordsMessage"),
+ action: {
+ to: "/products/create",
+ label: t("actions.add"),
+ },
+ }}
+ />
+ <Outlet />
+ </Container>
+ )
+}
+
+const ProductActions = ({ product }: { product: ExtendedAdminProduct }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteProduct(product.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("products.deleteWarning", {
+ title: product.title,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("products.toasts.delete.success.header"), {
+ description: t("products.toasts.delete.success.description", {
+ title: product.title,
+ }),
+ })
+ },
+ onError: (e) => {
+ toast.error(t("products.toasts.delete.error.header"), {
+ description: e.message,
+ })
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const base = useProductTableColumns()
+
+ const columns = useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <ProductActions product={row.original} />
+ },
+ }),
+ ],
+ [base, t]
+ )
+
+ return columns
+}
diff --git a/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx b/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx
new file mode 100644
index 000000000..0ba8bf4f0
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/components/category-combobox/category-combobox.tsx
@@ -0,0 +1,498 @@
+import {
+ ArrowUturnLeft,
+ EllipseMiniSolid,
+ TriangleRightMini,
+ TrianglesMini,
+ XMarkMini,
+} from "@medusajs/icons"
+import { AdminProductCategoryResponse } from "@medusajs/types"
+import { Divider, Text, clx } from "@medusajs/ui"
+import { Popover as RadixPopover } from "radix-ui"
+import {
+ CSSProperties,
+ ComponentPropsWithoutRef,
+ Fragment,
+ MouseEvent,
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react"
+import { Trans, useTranslation } from "react-i18next"
+import { TextSkeleton } from "@components/common/skeleton"
+import { useProductCategories } from "@hooks/api/categories"
+import { useDebouncedSearch } from "@hooks/use-debounced-search"
+
+interface CategoryComboboxProps
+ extends Omit<
+ ComponentPropsWithoutRef<"input">,
+ "value" | "defaultValue" | "onChange"
+ > {
+ value: string[]
+ onChange: (value: string[]) => void
+}
+
+type Level = {
+ id: string
+ label: string
+}
+
+const TABLUAR_NUM_WIDTH = 8
+const TAG_BASE_WIDTH = 28
+
+export const CategoryCombobox = forwardRef<
+ HTMLInputElement,
+ CategoryComboboxProps
+>(({ value, onChange, className, ...props }, ref) => {
+ const innerRef = useRef<HTMLInputElement>(null)
+
+ useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
+ ref,
+ () => innerRef.current,
+ []
+ )
+
+ const [open, setOpen] = useState(false)
+
+ const { i18n, t } = useTranslation()
+
+ const [level, setLevel] = useState<Level[]>([])
+ const { searchValue, onSearchValueChange, query } = useDebouncedSearch()
+
+ const queryParams = {
+ q: query,
+ parent_category_id: !searchValue ? getParentId(level) : undefined,
+ include_descendants_tree: !searchValue ? true : false,
+ }
+
+ const { product_categories, isPending, isError, error } =
+ useProductCategories(queryParams, {
+ enabled: open,
+ })
+
+ const [showLoading, setShowLoading] = useState(false)
+
+ /**
+ * We add a small artificial delay to the end of the loading state,
+ * this is done to prevent the popover from flickering too much when
+ * navigating between levels or searching.
+ */
+ useEffect(() => {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined
+
+ if (isPending) {
+ setShowLoading(true)
+ } else {
+ timeoutId = setTimeout(() => {
+ setShowLoading(false)
+ }, 150)
+ }
+
+ return () => {
+ clearTimeout(timeoutId)
+ }
+ }, [isPending])
+
+ useEffect(() => {
+ if (searchValue) {
+ setLevel([])
+ }
+ }, [searchValue])
+
+ function handleLevelUp(e: MouseEvent<HTMLButtonElement>) {
+ e.preventDefault()
+ e.stopPropagation()
+
+ setLevel(level.slice(0, level.length - 1))
+
+ innerRef.current?.focus()
+ }
+
+ function handleLevelDown(option: ProductCategoryOption) {
+ return (e: MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ setLevel([...level, { id: option.value, label: option.label }])
+
+ innerRef.current?.focus()
+ }
+ }
+
+ const handleSelect = useCallback(
+ (option: ProductCategoryOption) => {
+ return (e: MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault()
+ e.stopPropagation()
+
+ if (isSelected(value, option.value)) {
+ onChange(value.filter((v) => v !== option.value))
+ } else {
+ onChange([...value, option.value])
+ }
+
+ innerRef.current?.focus()
+ }
+ },
+ [value, onChange]
+ )
+
+ function handleOpenChange(open: boolean) {
+ if (!open) {
+ onSearchValueChange("")
+ setLevel([])
+ }
+
+ if (open) {
+ requestAnimationFrame(() => {
+ innerRef.current?.focus()
+ })
+ }
+
+ setOpen(open)
+ }
+
+ const options = getOptions(product_categories || [])
+
+ const showTag = value.length > 0
+ const showSelected = !open && value.length > 0
+
+ const tagWidth = useMemo(() => {
+ const count = value.length
+ const digits = count.toString().length
+
+ return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH
+ }, [value])
+
+ const showLevelUp = !searchValue && level.length > 0
+
+ const [focusedIndex, setFocusedIndex] = useState<number>(-1)
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent) => {
+ if (!open) {
+ return
+ }
+
+ const optionsLength = showLevelUp ? options.length + 1 : options.length
+
+ if (e.key === "ArrowDown") {
+ e.preventDefault()
+ setFocusedIndex((prev) => {
+ const nextIndex = prev < optionsLength - 1 ? prev + 1 : prev
+ return nextIndex
+ })
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault()
+ setFocusedIndex((prev) => {
+ return prev > 0 ? prev - 1 : prev
+ })
+ } else if (e.key === "ArrowRight") {
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex
+ const hasChildren = options[index]?.has_children
+
+ if (!hasChildren || !!searchValue) {
+ return
+ }
+
+ e.preventDefault()
+ setLevel([
+ ...level,
+ {
+ id: options[index].value,
+ label: options[index].label,
+ },
+ ])
+ setFocusedIndex(0)
+ } else if (e.key === "Enter" && focusedIndex !== -1) {
+ e.preventDefault()
+
+ if (showLevelUp && focusedIndex === 0) {
+ setLevel(level.slice(0, level.length - 1))
+ setFocusedIndex(0)
+ return
+ }
+
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex
+
+ handleSelect(options[index])(e as unknown as MouseEvent<HTMLButtonElement>)
+ }
+ },
+ [open, focusedIndex, options, level, handleSelect, searchValue, showLevelUp]
+ )
+
+ useEffect(() => {
+ window.addEventListener("keydown", handleKeyDown)
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown)
+ }
+ }, [handleKeyDown])
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RadixPopover.Root open={open} onOpenChange={handleOpenChange}>
+ <RadixPopover.Anchor
+ asChild
+ onClick={() => {
+ if (!open) {
+ handleOpenChange(true)
+ }
+ }}
+ >
+ <div
+ data-anchor
+ className={clx(
+ "relative flex cursor-pointer items-center gap-x-2 overflow-hidden",
+ "h-8 w-full rounded-md",
+ "bg-ui-bg-field transition-fg shadow-borders-base",
+ "has-[input:focus]:shadow-borders-interactive-with-active",
+ "has-[:invalid]:shadow-borders-error has-[[aria-invalid=true]]:shadow-borders-error",
+ "has-[:disabled]:bg-ui-bg-disabled has-[:disabled]:text-ui-fg-disabled has-[:disabled]:cursor-not-allowed",
+ {
+ // Fake the focus state as long as the popover is open,
+ // this prevents the styling from flickering when navigating
+ // between levels.
+ "shadow-borders-interactive-with-active": open,
+ },
+ className
+ )}
+ style={
+ {
+ "--tag-width": `${tagWidth}px`,
+ } as CSSProperties
+ }
+ >
+ {showTag && (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.preventDefault()
+ onChange([])
+ }}
+ className="bg-ui-bg-base hover:bg-ui-bg-base-hover txt-compact-small-plus text-ui-fg-subtle focus-within:border-ui-fg-interactive transition-fg absolute left-0.5 top-0.5 flex h-[28px] items-center rounded-[4px] border py-[3px] pl-1.5 pr-1 outline-none"
+ >
+ <span className="tabular-nums">{value.length}</span>
+ <XMarkMini className="text-ui-fg-muted" />
+ </button>
+ )}
+ {showSelected && (
+ <div className="pointer-events-none absolute inset-y-0 left-[calc(var(--tag-width)+8px)] flex size-full items-center">
+ <Text size="small" leading="compact">
+ {t("general.selected")}
+ </Text>
+ </div>
+ )}
+ <input
+ ref={innerRef}
+ value={searchValue}
+ onChange={(e) => {
+ onSearchValueChange(e.target.value)
+ }}
+ className={clx(
+ "txt-compact-small size-full cursor-pointer appearance-none bg-transparent pr-8 outline-none",
+ "hover:bg-ui-bg-field-hover",
+ "focus:cursor-text",
+ "placeholder:text-ui-fg-muted",
+ {
+ "pl-2": !showTag,
+ "pl-[calc(var(--tag-width)+8px)]": showTag,
+ }
+ )}
+ {...props}
+ />
+ <button
+ type="button"
+ onClick={() => handleOpenChange(true)}
+ className="text-ui-fg-muted transition-fg hover:bg-ui-bg-field-hover absolute right-0 flex size-8 items-center justify-center rounded-r outline-none"
+ >
+ <TrianglesMini className="text-ui-fg-muted" />
+ </button>
+ </div>
+ </RadixPopover.Anchor>
+ <RadixPopover.Content
+ sideOffset={4}
+ role="listbox"
+ className={clx(
+ "shadow-elevation-flyout bg-ui-bg-base -left-2 z-50 w-[var(--radix-popper-anchor-width)] rounded-[8px]",
+ "max-h-[200px] overflow-y-auto",
+ "data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
+ "data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",
+ "data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2"
+ )}
+ onInteractOutside={(e) => {
+ e.preventDefault()
+
+ const target = e.target as HTMLElement
+
+ if (target.closest("[data-anchor]")) {
+ return
+ }
+
+ handleOpenChange(false)
+ }}
+ >
+ {showLevelUp && (
+ <Fragment>
+ <div className="p-1">
+ <button
+ data-active={focusedIndex === 0}
+ role="button"
+ className={clx(
+ "transition-fg grid w-full appearance-none grid-cols-[20px_1fr] items-center justify-center gap-2 rounded-md px-2 py-1.5 text-left outline-none",
+ "data-[active=true]:bg-ui-bg-field-hover"
+ )}
+ type="button"
+ onClick={handleLevelUp}
+ onMouseEnter={() => setFocusedIndex(0)}
+ onMouseLeave={() => setFocusedIndex(-1)}
+ tabIndex={-1}
+ >
+ <ArrowUturnLeft className="text-ui-fg-muted" />
+ <Text size="small" leading="compact">
+ {getParentLabel(level)}
+ </Text>
+ </button>
+ </div>
+ <Divider />
+ </Fragment>
+ )}
+ <div className="p-1">
+ {options.length > 0 &&
+ !showLoading &&
+ options.map((option, index) => (
+ <div
+ key={option.value}
+ className={clx(
+ "transition-fg bg-ui-bg-base grid cursor-pointer grid-cols-1 items-center gap-2 overflow-hidden",
+ {
+ "grid-cols-[1fr_32px]": option.has_children && !searchValue,
+ }
+ )}
+ >
+ <button
+ data-active={
+ showLevelUp
+ ? focusedIndex === index + 1
+ : focusedIndex === index
+ }
+ type="button"
+ role="option"
+ className={clx(
+ "grid h-full w-full appearance-none grid-cols-[20px_1fr] items-center gap-2 overflow-hidden rounded-md px-2 py-1.5 text-left outline-none",
+ "data-[active=true]:bg-ui-bg-field-hover"
+ )}
+ onClick={handleSelect(option)}
+ onMouseEnter={() =>
+ setFocusedIndex(showLevelUp ? index + 1 : index)
+ }
+ onMouseLeave={() => setFocusedIndex(-1)}
+ tabIndex={-1}
+ >
+ <div className="flex size-5 items-center justify-center">
+ {isSelected(value, option.value) && <EllipseMiniSolid />}
+ </div>
+ <Text
+ as="span"
+ size="small"
+ leading="compact"
+ className="w-full truncate"
+ >
+ {option.label}
+ </Text>
+ </button>
+ {option.has_children && !searchValue && (
+ <button
+ className={clx(
+ "text-ui-fg-muted flex size-8 appearance-none items-center justify-center rounded-md outline-none",
+ "hover:bg-ui-bg-base-hover active:bg-ui-bg-base-pressed"
+ )}
+ type="button"
+ onClick={handleLevelDown(option)}
+ tabIndex={-1}
+ >
+ <TriangleRightMini />
+ </button>
+ )}
+ </div>
+ ))}
+ {showLoading &&
+ Array.from({ length: 5 }).map((_, index) => (
+ <div
+ key={index}
+ className="grid grid-cols-[20px_1fr_20px] gap-2 px-2 py-1.5"
+ >
+ <div />
+ <TextSkeleton size="small" leading="compact" />
+ <div />
+ </div>
+ ))}
+ {options.length === 0 && !showLoading && (
+ <div className="px-2 py-1.5">
+ <Text size="small" leading="compact">
+ {query ? (
+ <Trans
+ i18n={i18n}
+ i18nKey={"general.noResultsTitle"}
+ tOptions={{
+ query: query,
+ }}
+ components={[<span className="font-medium" key="query" />]}
+ />
+ ) : (
+ t("general.noResultsTitle")
+ )}
+ </Text>
+ </div>
+ )}
+ </div>
+ </RadixPopover.Content>
+ </RadixPopover.Root>
+ )
+})
+
+CategoryCombobox.displayName = "CategoryCombobox"
+
+type ProductCategoryOption = {
+ value: string
+ label: string
+ has_children: boolean
+}
+
+function getParentId(level: Level[]): string {
+ if (!level.length) {
+ return "null"
+ }
+
+ return level[level.length - 1].id
+}
+
+function getParentLabel(level: Level[]): string | null {
+ if (!level.length) {
+ return null
+ }
+
+ return level[level.length - 1].label
+}
+
+function getOptions(
+ categories: AdminProductCategoryResponse["product_category"][]
+): ProductCategoryOption[] {
+ return categories.map((cat) => {
+ return {
+ value: cat.id,
+ label: cat.name,
+ has_children: cat.category_children?.length > 0,
+ }
+ })
+}
+
+function isSelected(values: string[], value: string): boolean {
+ return values.includes(value)
+}
diff --git a/packages/vendor/src/pages/products/common/components/category-combobox/category-select.tsx b/packages/vendor/src/pages/products/common/components/category-combobox/category-select.tsx
new file mode 100644
index 000000000..07e98e81b
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/components/category-combobox/category-select.tsx
@@ -0,0 +1,283 @@
+import { Check, TrianglesMini } from "@medusajs/icons"
+import { AdminProductCategoryResponse } from "@medusajs/types"
+import { Text, clx } from "@medusajs/ui"
+import { Select } from "radix-ui"
+import {
+ CSSProperties,
+ ComponentPropsWithoutRef,
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
+} from "react"
+
+import { useProductCategories } from "@hooks/api/categories"
+import { useDebouncedSearch } from "@hooks/use-debounced-search"
+
+interface CategoryComboboxProps
+ extends Omit<
+ ComponentPropsWithoutRef<"input">,
+ "value" | "defaultValue" | "onChange"
+ > {
+ value: string[]
+ onChange: (value: string[]) => void
+}
+
+type Level = {
+ id: string
+ label: string
+}
+
+const TABLUAR_NUM_WIDTH = 8
+const TAG_BASE_WIDTH = 28
+
+export const CategorySelect = forwardRef<
+ HTMLInputElement,
+ CategoryComboboxProps
+>(({ value, onChange, className }, ref) => {
+ const innerRef = useRef<HTMLInputElement>(null)
+
+ useImperativeHandle<HTMLInputElement | null, HTMLInputElement | null>(
+ ref,
+ () => innerRef.current,
+ []
+ )
+
+ const [open] = useState(false)
+
+ const [level, setLevel] = useState<Level[]>([])
+ const { searchValue } = useDebouncedSearch()
+
+ const { product_categories, isPending, isError, error } =
+ useProductCategories()
+
+ const [showLoading, setShowLoading] = useState(false)
+
+ /**
+ * We add a small artificial delay to the end of the loading state,
+ * this is done to prevent the popover from flickering too much when
+ * navigating between levels or searching.
+ */
+ useEffect(() => {
+ let timeoutId: ReturnType<typeof setTimeout> | undefined
+
+ if (isPending) {
+ setShowLoading(true)
+ } else {
+ timeoutId = setTimeout(() => {
+ setShowLoading(false)
+ }, 150)
+ }
+
+ return () => {
+ clearTimeout(timeoutId)
+ }
+ }, [isPending])
+
+ useEffect(() => {
+ if (searchValue) {
+ setLevel([])
+ }
+ }, [searchValue])
+
+ const handleSelect = (option: string) => {
+ if (value.includes(option)) {
+ onChange([])
+ } else {
+ onChange([option])
+ }
+
+ innerRef.current?.focus()
+ }
+
+ const options = getOptions(product_categories || [])
+
+ const tagWidth = useMemo(() => {
+ const count = value.length
+ const digits = count.toString().length
+
+ return TAG_BASE_WIDTH + digits * TABLUAR_NUM_WIDTH
+ }, [value])
+
+ const showLevelUp = !searchValue && level.length > 0
+
+ const [focusedIndex, setFocusedIndex] = useState<number>(-1)
+
+ const handleKeyDown = useCallback(
+ (e: KeyboardEvent) => {
+ if (!open) {
+ return
+ }
+
+ const optionsLength = showLevelUp ? options.length + 1 : options.length
+
+ if (e.key === "ArrowDown") {
+ e.preventDefault()
+ setFocusedIndex((prev) => {
+ const nextIndex = prev < optionsLength - 1 ? prev + 1 : prev
+ return nextIndex
+ })
+ } else if (e.key === "ArrowUp") {
+ e.preventDefault()
+ setFocusedIndex((prev) => {
+ return prev > 0 ? prev - 1 : prev
+ })
+ } else if (e.key === "ArrowRight") {
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex
+ const hasChildren = options[index]?.has_children
+
+ if (!hasChildren || !!searchValue) {
+ return
+ }
+
+ e.preventDefault()
+ setLevel([
+ ...level,
+ {
+ id: options[index].value,
+ label: options[index].label,
+ },
+ ])
+ setFocusedIndex(0)
+ } else if (e.key === "Enter" && focusedIndex !== -1) {
+ e.preventDefault()
+
+ if (showLevelUp && focusedIndex === 0) {
+ setLevel(level.slice(0, level.length - 1))
+ setFocusedIndex(0)
+ return
+ }
+
+ const index = showLevelUp ? focusedIndex - 1 : focusedIndex
+
+ handleSelect(options[index].value)
+ }
+ },
+ [open, focusedIndex, options, level, handleSelect, searchValue, showLevelUp]
+ )
+
+ useEffect(() => {
+ window.addEventListener("keydown", handleKeyDown)
+
+ return () => {
+ window.removeEventListener("keydown", handleKeyDown)
+ }
+ }, [handleKeyDown])
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Select.Root onValueChange={handleSelect}>
+ <Select.Trigger
+ className={clx(
+ "relative flex cursor-pointer items-center gap-x-2 overflow-hidden px-2",
+ "h-8 w-full rounded-md",
+ "bg-ui-bg-field transition-fg shadow-borders-base",
+ "has-[input:focus]:shadow-borders-interactive-with-active",
+ "has-[:invalid]:shadow-borders-error has-[[aria-invalid=true]]:shadow-borders-error",
+ "has-[:disabled]:bg-ui-bg-disabled has-[:disabled]:text-ui-fg-disabled has-[:disabled]:cursor-not-allowed",
+ {
+ "shadow-borders-interactive-with-active": open,
+ },
+ className
+ )}
+ style={
+ {
+ "--tag-width": `${tagWidth}px`,
+ } as CSSProperties
+ }
+ >
+ <Select.Value aria-label={value[0]} />
+ <Select.Icon className="ml-auto">
+ <TrianglesMini className="text-ui-fg-muted" />
+ </Select.Icon>
+ </Select.Trigger>
+
+ <Select.Portal>
+ <Select.Content className="bg-white border shadow-lg rounded-md">
+ <Select.Viewport className="p-2">
+ {options.length > 0 &&
+ !showLoading &&
+ options.map((option, index) => (
+ <SelectItem value={option.value} key={option.value}>
+ <button
+ data-active={
+ showLevelUp
+ ? focusedIndex === index + 1
+ : focusedIndex === index
+ }
+ type="button"
+ role="option"
+ className={clx(
+ "flex h-full w-full appearance-none items-center gap-2 overflow-hidden rounded-md px-2 py-1.5 text-left outline-none"
+ )}
+ onMouseEnter={() =>
+ setFocusedIndex(showLevelUp ? index + 1 : index)
+ }
+ onMouseLeave={() => setFocusedIndex(-1)}
+ tabIndex={-1}
+ >
+ <Text
+ as="span"
+ size="small"
+ leading="compact"
+ className="flex w-full truncate"
+ >
+ {option.label}
+ </Text>
+ </button>
+ </SelectItem>
+ ))}
+ </Select.Viewport>
+ </Select.Content>
+ </Select.Portal>
+ </Select.Root>
+ )
+})
+
+CategorySelect.displayName = "CategorySelect"
+
+type ProductCategoryOption = {
+ value: string
+ label: string
+ has_children: boolean
+}
+
+const SelectItem = ({
+ value,
+ children,
+}: {
+ value: string
+ children: React.ReactNode
+}) => {
+ return (
+ <Select.Item
+ value={value}
+ className={clx(
+ "transition-fg bg-ui-bg-base flex cursor-pointer items-center gap-2 overflow-hidden hover:bg-ui-bg-field-hover"
+ )}
+ >
+ <Select.ItemText>{children}</Select.ItemText>
+ <Select.ItemIndicator className="ml-auto">
+ <Check />
+ </Select.ItemIndicator>
+ </Select.Item>
+ )
+}
+
+function getOptions(
+ categories: AdminProductCategoryResponse["product_category"][]
+): ProductCategoryOption[] {
+ return categories.map((cat) => {
+ return {
+ value: cat.id,
+ label: cat.name,
+ has_children: cat.category_children?.length > 0,
+ }
+ })
+}
diff --git a/packages/vendor/src/pages/products/common/components/category-combobox/index.ts b/packages/vendor/src/pages/products/common/components/category-combobox/index.ts
new file mode 100644
index 000000000..d858c7ce3
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/components/category-combobox/index.ts
@@ -0,0 +1 @@
+export * from "./category-combobox"
diff --git a/packages/vendor/src/pages/products/common/components/upload-media-form-item/index.ts b/packages/vendor/src/pages/products/common/components/upload-media-form-item/index.ts
new file mode 100644
index 000000000..c1d85fa8d
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/components/upload-media-form-item/index.ts
@@ -0,0 +1 @@
+export * from "./upload-media-form-item"
diff --git a/packages/vendor/src/pages/products/common/components/upload-media-form-item/upload-media-form-item.tsx b/packages/vendor/src/pages/products/common/components/upload-media-form-item/upload-media-form-item.tsx
new file mode 100644
index 000000000..49c40d77a
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/components/upload-media-form-item/upload-media-form-item.tsx
@@ -0,0 +1,110 @@
+import { useCallback } from 'react';
+
+import { UseFormReturn } from 'react-hook-form';
+import { useTranslation } from 'react-i18next';
+import { z } from 'zod';
+
+import { FileType, FileUpload } from "@components/common/file-upload"
+import { Form } from "@components/common/form"
+import { EditStoreSchema } from '../../../../store/store-edit/components/edit-store-form/edit-store-form';
+import { MediaSchema } from '../../../create/constants'
+import { EditProductMediaSchemaType, ProductCreateSchemaType } from '../../../create/types'
+
+type Media = z.infer<typeof MediaSchema>;
+
+const SUPPORTED_FORMATS = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/svg+xml'];
+
+const SUPPORTED_FORMATS_FILE_EXTENSIONS = ['.jpeg', '.png', '.webp', '.heic', '.svg'];
+
+const MAX_FILE_SIZE = 2 * 1024 * 1024;
+
+export const UploadMediaFormItem = ({
+ form,
+ append,
+ showHint = true
+}: {
+ form:
+ | UseFormReturn<ProductCreateSchemaType>
+ | UseFormReturn<EditProductMediaSchemaType>
+ | UseFormReturn<z.infer<typeof EditStoreSchema>>;
+ append: (value: Media) => void;
+ showHint?: boolean;
+}) => {
+ const { t } = useTranslation();
+
+ const hasInvalidFiles = useCallback(
+ (fileList: FileType[]) => {
+ const invalidTypeFile = fileList.find(f => !SUPPORTED_FORMATS.includes(f.file.type));
+
+ if (invalidTypeFile) {
+ form.setError('media', {
+ type: 'invalid_file',
+ message: t('products.media.invalidFileType', {
+ name: invalidTypeFile.file.name,
+ types: SUPPORTED_FORMATS_FILE_EXTENSIONS.join(', ')
+ })
+ });
+
+ return true;
+ }
+
+ const oversizedFile = fileList.find(f => f.file.size > MAX_FILE_SIZE);
+
+ if (oversizedFile) {
+ form.setError('media', {
+ type: 'invalid_file',
+ message: t('products.media.fileTooLarge', {
+ name: oversizedFile.file.name,
+ maxSize: '2MB'
+ })
+ });
+
+ return true;
+ }
+
+ return false;
+ },
+ [form, t]
+ );
+
+ const onUploaded = useCallback(
+ (files: FileType[]) => {
+ form.clearErrors('media');
+ if (hasInvalidFiles(files)) {
+ return;
+ }
+
+ files.forEach(f => append({ ...f, isThumbnail: false }));
+ },
+ [form, append, hasInvalidFiles]
+ );
+
+ return (
+ <Form.Field
+ control={form.control as UseFormReturn<EditProductMediaSchemaType>['control']}
+ name="media"
+ render={() => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-y-2">
+ <div className="flex flex-col gap-y-1">
+ <Form.Label optional>{t('products.media.label')}</Form.Label>
+ {showHint && <Form.Hint>{t('products.media.editHint')}</Form.Hint>}
+ </div>
+ <Form.Control>
+ <FileUpload
+ label={t('products.media.uploadImagesLabel')}
+ hint={t('products.media.uploadImagesHint')}
+ hasError={!!form.formState.errors.media}
+ formats={SUPPORTED_FORMATS}
+ onUploaded={onUploaded}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ );
+ }}
+ />
+ );
+};
diff --git a/packages/vendor/src/pages/products/common/constants.ts b/packages/vendor/src/pages/products/common/constants.ts
new file mode 100644
index 000000000..7d1a0b103
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/constants.ts
@@ -0,0 +1 @@
+export const PRODUCT_VARIANT_IDS_KEY = "product_variant_ids"
diff --git a/packages/vendor/src/pages/products/common/variant-pricing-form.tsx b/packages/vendor/src/pages/products/common/variant-pricing-form.tsx
new file mode 100644
index 000000000..785d63753
--- /dev/null
+++ b/packages/vendor/src/pages/products/common/variant-pricing-form.tsx
@@ -0,0 +1,127 @@
+import { useMemo } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { HttpTypes } from "@medusajs/types"
+import { Text } from "@medusajs/ui"
+
+import {
+ DataGrid,
+ createDataGridHelper,
+ createDataGridPriceColumns,
+} from "@components/data-grid"
+import { useRouteModal } from "@components/modals/index"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+import { useRegions } from "@hooks/api/regions.tsx"
+import { useStore } from "@hooks/api/store"
+import { ProductCreateSchemaType } from "../create/types"
+import { ExtendedAdminProduct } from "@custom-types/products.ts"
+
+type VariantPricingFormProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+ product: ExtendedAdminProduct
+}
+
+export const VariantPricingForm = ({
+ form,
+ product,
+}: VariantPricingFormProps) => {
+ const { store } = useStore()
+ const { regions } = useRegions({ limit: 9999 })
+ const { price_preferences: pricePreferences } = usePricePreferences({})
+
+ const { setCloseOnEscape } = useRouteModal()
+
+ const columns = useVariantPriceGridColumns({
+ currencies: store?.supported_currencies,
+ regions,
+ pricePreferences,
+ })
+
+ const variants = useWatch({
+ control: form.control,
+ name: "variants",
+ }) as any
+
+ const dataWithProductInfo = useMemo(() => {
+ if (!variants?.length) return []
+
+ const productInfoRow = {
+ id: `product-info-${product.id}`,
+ title: product.title,
+ isProductInfo: true,
+ prices: {},
+ }
+
+ return [productInfoRow, ...variants]
+ }, [variants, product.title, product.id])
+
+ return (
+ <DataGrid
+ columns={columns}
+ data={dataWithProductInfo}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ )
+}
+
+const columnHelper = createDataGridHelper<
+ HttpTypes.AdminProductVariant,
+ ProductCreateSchemaType
+>()
+
+const useVariantPriceGridColumns = ({
+ currencies = [],
+ regions = [],
+ pricePreferences = [],
+}: {
+ currencies?: HttpTypes.AdminStore["supported_currencies"]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}) => {
+ const { t } = useTranslation()
+
+ return useMemo(() => {
+ return [
+ columnHelper.column({
+ id: t("fields.title"),
+ header: t("fields.title"),
+ cell: (context) => {
+ const entity = context.row.original
+ const isProductInfo = (entity as any).isProductInfo
+
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ <div
+ className={`flex h-full w-full items-center gap-x-2 overflow-hidden ${
+ isProductInfo
+ ? "bg-ui-bg-field text-ui-fg-disabled"
+ : "text-ui-fg-subtle"
+ }`}
+ >
+ <Text as="span" className="truncate">
+ {entity.title}
+ </Text>
+ </div>
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ ...createDataGridPriceColumns<
+ HttpTypes.AdminProductVariant,
+ ProductCreateSchemaType
+ >({
+ currencies: currencies.map((c) => c.currency_code),
+ pricePreferences,
+ isReadyOnly: (context) => (context.row.original as any).isProductInfo,
+ getFieldName: (context, value) => {
+ const entity = context.row.original as any
+ if (entity.isProductInfo) return null
+ return `variants.${context.row.index - 1}.prices.${value}`
+ },
+ t,
+ }),
+ ]
+ }, [t, currencies, regions, pricePreferences])
+}
diff --git a/packages/vendor/src/pages/products/create/constants.ts b/packages/vendor/src/pages/products/create/constants.ts
new file mode 100644
index 000000000..b1bc321ef
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/constants.ts
@@ -0,0 +1,163 @@
+import { z } from "zod"
+import { i18n } from "@components/utilities/i18n/i18n"
+import { optionalFloat, optionalInt } from "@lib/validation"
+import { decorateVariantsWithDefaultValues } from "./utils"
+
+export const MediaSchema = z.object({
+ id: z.string().optional(),
+ url: z.string(),
+ isThumbnail: z.boolean(),
+ file: z.any().nullable(), // File
+})
+
+const ProductCreateVariantSchema = z.object({
+ should_create: z.boolean(),
+ is_default: z.boolean().optional(),
+ title: z.string(),
+ upc: z.string().optional(),
+ ean: z.string().optional(),
+ barcode: z.string().optional(),
+ mid_code: z.string().optional(),
+ hs_code: z.string().optional(),
+ width: optionalInt,
+ height: optionalInt,
+ length: optionalInt,
+ weight: optionalInt,
+ material: z.string().optional(),
+ origin_country: z.string().optional(),
+ sku: z.string().optional(),
+ manage_inventory: z.boolean().optional(),
+ allow_backorder: z.boolean().optional(),
+ inventory_kit: z.boolean().optional(),
+ options: z.record(z.string(), z.string()),
+ variant_rank: z.number(),
+ prices: z.record(z.string(), optionalFloat).optional(),
+ inventory: z
+ .array(
+ z.object({
+ inventory_item_id: z.string(),
+ required_quantity: optionalInt,
+ })
+ )
+ .optional(),
+})
+
+export type ProductCreateVariantSchema = z.infer<
+ typeof ProductCreateVariantSchema
+>
+
+const ProductCreateOptionSchema = z.object({
+ title: z.string(),
+ values: z.array(z.string()).min(1),
+})
+
+export type ProductCreateOptionSchema = z.infer<
+ typeof ProductCreateOptionSchema
+>
+
+export const ProductCreateSchema = z
+ .object({
+ title: z.string().min(1),
+ subtitle: z.string().optional(),
+ handle: z.string().optional(),
+ description: z.string().optional(),
+ discountable: z.boolean(),
+ type_id: z.string().optional(),
+ collection_id: z.string().optional(),
+ shipping_profile_id: z.string().optional(),
+ categories: z.array(z.string()),
+ tags: z.array(z.string()).optional(),
+ sales_channels: z
+ .array(
+ z.object({
+ id: z.string(),
+ name: z.string(),
+ })
+ )
+ .optional(),
+ origin_country: z.string().optional(),
+ material: z.string().optional(),
+ width: z.string().optional(),
+ length: z.string().optional(),
+ height: z.string().optional(),
+ weight: z.string().optional(),
+ mid_code: z.string().optional(),
+ hs_code: z.string().optional(),
+ options: z.array(ProductCreateOptionSchema).min(1),
+ enable_variants: z.boolean(),
+ variants: z.array(ProductCreateVariantSchema).min(1),
+ media: z.array(MediaSchema).optional(),
+ })
+ .superRefine((data, ctx) => {
+ if (data.variants.every((v) => !v.should_create)) {
+ return ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["variants"],
+ message: "invalid_length",
+ })
+ }
+
+ const skus = new Set<string>()
+
+ data.variants.forEach((v, index) => {
+ if (v.sku) {
+ if (skus.has(v.sku)) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: [`variants.${index}.sku`],
+ message: i18n.t("products.create.errors.uniqueSku"),
+ })
+ }
+
+ skus.add(v.sku)
+ }
+ })
+ })
+
+export const EditProductMediaSchema = z.object({
+ media: z.array(MediaSchema),
+})
+
+export const PRODUCT_CREATE_FORM_DEFAULTS: Partial<
+ z.infer<typeof ProductCreateSchema>
+> = {
+ discountable: true,
+ tags: [],
+ sales_channels: [],
+ options: [
+ {
+ title: "Default option",
+ values: ["Default option value"],
+ },
+ ],
+ variants: decorateVariantsWithDefaultValues([
+ {
+ title: "Default variant",
+ should_create: true,
+ variant_rank: 0,
+ options: {
+ "Default option": "Default option value",
+ },
+ inventory: [{ inventory_item_id: "", required_quantity: "" }],
+ is_default: true,
+ },
+ ]),
+ enable_variants: false,
+ media: [],
+ categories: [],
+ collection_id: "",
+ shipping_profile_id: "",
+ description: "",
+ handle: "",
+ height: "",
+ hs_code: "",
+ length: "",
+ material: "",
+ mid_code: "",
+ origin_country: "",
+ subtitle: "",
+ title: "",
+ type_id: "",
+ weight: "",
+ width: "",
+}
diff --git a/packages/vendor/src/pages/products/create/index.tsx b/packages/vendor/src/pages/products/create/index.tsx
new file mode 100644
index 000000000..7901c7a04
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/index.tsx
@@ -0,0 +1,32 @@
+// Route: /products/create
+import { useTranslation } from "react-i18next"
+import { RouteFocusModal } from "@components/modals"
+import { useSalesChannels } from "@hooks/api"
+import { useStore } from "@hooks/api/store"
+import { ProductCreateForm } from "./product-create-form/product-create-form"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ const { store, isPending: isStorePending } = useStore()
+
+ const { sales_channels, isPending: isSalesChannelPending } =
+ useSalesChannels()
+
+ const ready =
+ !!store && !isStorePending && !!sales_channels && !isSalesChannelPending
+
+ return (
+ <RouteFocusModal>
+ <RouteFocusModal.Title asChild>
+ <span className="sr-only">{t("products.create.title")}</span>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <span className="sr-only">{t("products.create.description")}</span>
+ </RouteFocusModal.Description>
+ {ready && (
+ <ProductCreateForm defaultChannel={sales_channels[0]} store={store} />
+ )}
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/index.ts b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/index.ts
new file mode 100644
index 000000000..f3e3a6460
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-general-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/product-create-general-section.tsx b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/product-create-general-section.tsx
new file mode 100644
index 000000000..84826993a
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-general-section/product-create-general-section.tsx
@@ -0,0 +1,91 @@
+import { Input, Textarea } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { HandleInput } from "@components/inputs/handle-input"
+import { ProductCreateSchemaType } from "../../../../types"
+
+type ProductCreateGeneralSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateGeneralSection = ({
+ form,
+}: ProductCreateGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div id="general" className="flex flex-col gap-y-6">
+ <div className="flex flex-col gap-y-2">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-3">
+ <Form.Field
+ control={form.control}
+ name="title"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("products.fields.title.label")}</Form.Label>
+ <Form.Control>
+ <Input {...field} placeholder="Winter jacket" />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="subtitle"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.subtitle.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} placeholder="Warm and cosy" />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="handle"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={t("products.fields.handle.tooltip")}
+ optional
+ >
+ {t("fields.handle")}
+ </Form.Label>
+ <Form.Control>
+ <HandleInput {...field} placeholder="winter-jacket" />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.description.label")}
+ </Form.Label>
+ <Form.Control>
+ <Textarea {...field} placeholder="A warm and cozy jacket" />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/index.ts b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/index.ts
new file mode 100644
index 000000000..aa052ffdc
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-details-media-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/product-create-details-media-section.tsx b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/product-create-details-media-section.tsx
new file mode 100644
index 000000000..7ce64ecf0
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-media-section/product-create-details-media-section.tsx
@@ -0,0 +1,338 @@
+import {
+ defaultDropAnimationSideEffects,
+ DndContext,
+ DragEndEvent,
+ DragOverlay,
+ DragStartEvent,
+ DropAnimation,
+ KeyboardSensor,
+ PointerSensor,
+ UniqueIdentifier,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core"
+import {
+ arrayMove,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+} from "@dnd-kit/sortable"
+import { CSS } from "@dnd-kit/utilities"
+import {
+ DotsSix,
+ StackPerspective,
+ ThumbnailBadge,
+ Trash,
+ XMark,
+} from "@medusajs/icons"
+import { IconButton, Text } from "@medusajs/ui"
+import { useState } from "react"
+import { useFieldArray, UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { UploadMediaFormItem } from "@pages/products/common/components/upload-media-form-item"
+import { ProductCreateSchemaType } from "../../../../types"
+
+type ProductCreateMediaSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+const dropAnimationConfig: DropAnimation = {
+ sideEffects: defaultDropAnimationSideEffects({
+ styles: {
+ active: {
+ opacity: "0.4",
+ },
+ },
+ }),
+}
+
+export const ProductCreateMediaSection = ({
+ form,
+}: ProductCreateMediaSectionProps) => {
+ const { fields, append, remove } = useFieldArray({
+ name: "media",
+ control: form.control,
+ keyName: "field_id",
+ })
+
+ const [activeId, setActiveId] = useState<UniqueIdentifier | null>(null)
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor, {
+ coordinateGetter: sortableKeyboardCoordinates,
+ })
+ )
+
+ const handleDragStart = (event: DragStartEvent) => {
+ setActiveId(event.active.id)
+ }
+
+ const handleDragEnd = (event: DragEndEvent) => {
+ setActiveId(null)
+ const { active, over } = event
+
+ if (active.id !== over?.id) {
+ const oldIndex = fields.findIndex((item) => item.field_id === active.id)
+ const newIndex = fields.findIndex((item) => item.field_id === over?.id)
+
+ form.setValue("media", arrayMove(fields, oldIndex, newIndex), {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ }
+ }
+
+ const handleDragCancel = () => {
+ setActiveId(null)
+ }
+
+ const getOnDelete = (index: number) => {
+ return () => {
+ remove(index)
+ }
+ }
+
+ const getMakeThumbnail = (index: number) => {
+ return () => {
+ const newFields = fields.map((field, i) => {
+ return {
+ ...field,
+ isThumbnail: i === index,
+ }
+ })
+
+ form.setValue("media", newFields, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ }
+ }
+
+ const getItemHandlers = (index: number) => {
+ return {
+ onDelete: getOnDelete(index),
+ onMakeThumbnail: getMakeThumbnail(index),
+ }
+ }
+
+ return (
+ <div id="media" className="flex flex-col gap-y-2">
+ <UploadMediaFormItem form={form} append={append} showHint={false} />
+ <DndContext
+ sensors={sensors}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ onDragCancel={handleDragCancel}
+ >
+ <DragOverlay dropAnimation={dropAnimationConfig}>
+ {activeId ? (
+ <MediaGridItemOverlay
+ field={fields.find((m) => m.field_id === activeId)!}
+ />
+ ) : null}
+ </DragOverlay>
+ <ul className="flex flex-col gap-y-2">
+ <SortableContext items={fields.map((field) => field.field_id)}>
+ {fields.map((field, index) => {
+ const { onDelete, onMakeThumbnail } = getItemHandlers(index)
+
+ return (
+ <MediaItem
+ key={field.field_id}
+ field={field}
+ onDelete={onDelete}
+ onMakeThumbnail={onMakeThumbnail}
+ />
+ )
+ })}
+ </SortableContext>
+ </ul>
+ </DndContext>
+ </div>
+ )
+}
+
+type MediaField = {
+ isThumbnail: boolean
+ url: string
+ id?: string | undefined
+ file?: File
+ field_id: string
+}
+
+type MediaItemProps = {
+ field: MediaField
+ onDelete: () => void
+ onMakeThumbnail: () => void
+}
+
+const MediaItem = ({ field, onDelete, onMakeThumbnail }: MediaItemProps) => {
+ const { t } = useTranslation()
+
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ setActivatorNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: field.field_id })
+
+ const style = {
+ opacity: isDragging ? 0.4 : undefined,
+ transform: CSS.Translate.toString(transform),
+ transition,
+ }
+
+ if (!field.file) {
+ return null
+ }
+
+ return (
+ <li
+ className="bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2"
+ ref={setNodeRef}
+ style={style}
+ >
+ <div className="flex items-center gap-x-2">
+ <IconButton
+ variant="transparent"
+ type="button"
+ size="small"
+ {...attributes}
+ {...listeners}
+ ref={setActivatorNodeRef}
+ className="cursor-grab touch-none active:cursor-grabbing"
+ >
+ <DotsSix className="text-ui-fg-muted" />
+ </IconButton>
+ <div className="flex items-center gap-x-3">
+ <div className="bg-ui-bg-base h-10 w-[30px] overflow-hidden rounded-md">
+ <ThumbnailPreview url={field.url} />
+ </div>
+ <div className="flex flex-col">
+ <Text size="small" leading="compact">
+ {field.file.name}
+ </Text>
+ <div className="flex items-center gap-x-1">
+ {field.isThumbnail && <ThumbnailBadge />}
+ <Text
+ size="xsmall"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ {formatFileSize(field.file.size)}
+ </Text>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-x-1">
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("products.media.makeThumbnail"),
+ icon: <StackPerspective />,
+ onClick: onMakeThumbnail,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: onDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ onClick={onDelete}
+ >
+ <XMark />
+ </IconButton>
+ </div>
+ </li>
+ )
+}
+
+const MediaGridItemOverlay = ({ field }: { field: MediaField }) => {
+ return (
+ <li className="bg-ui-bg-component shadow-elevation-card-rest flex items-center justify-between rounded-lg px-3 py-2">
+ <div className="flex items-center gap-x-2">
+ <IconButton
+ variant="transparent"
+ size="small"
+ className="cursor-grab touch-none active:cursor-grabbing"
+ >
+ <DotsSix className="text-ui-fg-muted" />
+ </IconButton>
+ <div className="flex items-center gap-x-3">
+ <div className="bg-ui-bg-base h-10 w-[30px] overflow-hidden rounded-md">
+ <ThumbnailPreview url={field.url} />
+ </div>
+ <div className="flex flex-col">
+ <Text size="small" leading="compact">
+ {field.file?.name}
+ </Text>
+ <div className="flex items-center gap-x-1">
+ {field.isThumbnail && <ThumbnailBadge />}
+ <Text
+ size="xsmall"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ {formatFileSize(field.file?.size ?? 0)}
+ </Text>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="flex items-center gap-x-1">
+ <ActionMenu groups={[]} />
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ onClick={() => {}}
+ >
+ <XMark />
+ </IconButton>
+ </div>
+ </li>
+ )
+}
+
+const ThumbnailPreview = ({ url }: { url?: string | null }) => {
+ if (!url) {
+ return null
+ }
+
+ return (
+ <img src={url} alt="" className="size-full object-cover object-center" />
+ )
+}
+
+function formatFileSize(bytes: number, decimalPlaces: number = 2): string {
+ if (bytes === 0) {
+ return "0 Bytes"
+ }
+
+ const k = 1024
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+
+ return (
+ parseFloat((bytes / Math.pow(k, i)).toFixed(decimalPlaces)) + " " + sizes[i]
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/index.ts b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/index.ts
new file mode 100644
index 000000000..f5371ce81
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-details-variant-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/product-create-details-variant-section.tsx b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/product-create-details-variant-section.tsx
new file mode 100644
index 000000000..110e9c3d9
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/components/product-create-details-variant-section/product-create-details-variant-section.tsx
@@ -0,0 +1,541 @@
+import { XMarkMini } from "@medusajs/icons"
+import {
+ Alert,
+ Button,
+ Checkbox,
+ Heading,
+ Hint,
+ IconButton,
+ InlineTip,
+ Input,
+ Label,
+ Text,
+ clx,
+} from "@medusajs/ui"
+import {
+ Controller,
+ FieldArrayWithId,
+ UseFormReturn,
+ useFieldArray,
+ useWatch,
+} from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { SortableList } from "@components/common/sortable-list"
+import { SwitchBox } from "@components/common/switch-box"
+import { ChipInput } from "@components/inputs/chip-input"
+import { ProductCreateSchemaType } from "../../../../types"
+import { decorateVariantsWithDefaultValues } from "@pages/products/create/utils"
+
+type ProductCreateVariantsSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+const getPermutations = (
+ data: { title: string; values: string[] }[]
+): { [key: string]: string }[] => {
+ if (data.length === 0) {
+ return []
+ }
+
+ if (data.length === 1) {
+ return data[0].values.map((value) => ({ [data[0].title]: value }))
+ }
+
+ const toProcess = data[0]
+ const rest = data.slice(1)
+
+ return toProcess.values.flatMap((value) => {
+ return getPermutations(rest).map((permutation) => {
+ return {
+ [toProcess.title]: value,
+ ...permutation,
+ }
+ })
+ })
+}
+
+const getVariantName = (options: Record<string, string>) => {
+ return Object.values(options).join(" / ")
+}
+
+export const ProductCreateVariantsSection = ({
+ form,
+}: ProductCreateVariantsSectionProps) => {
+ const { t } = useTranslation()
+
+ const options = useFieldArray({
+ control: form.control,
+ name: "options",
+ })
+
+ const variants = useFieldArray({
+ control: form.control,
+ name: "variants",
+ })
+
+ const watchedAreVariantsEnabled = useWatch({
+ control: form.control,
+ name: "enable_variants",
+ defaultValue: false,
+ })
+
+ const watchedOptions = useWatch({
+ control: form.control,
+ name: "options",
+ defaultValue: [],
+ })
+
+ const watchedVariants = useWatch({
+ control: form.control,
+ name: "variants",
+ defaultValue: [],
+ })
+
+ const showInvalidOptionsMessage = !!form.formState.errors.options?.length
+ const showInvalidVariantsMessage =
+ form.formState.errors.variants?.root?.message === "invalid_length"
+
+ const handleOptionValueUpdate = (index: number, value: string[]) => {
+ const { isTouched: hasUserSelectedVariants } =
+ form.getFieldState("variants")
+
+ const newOptions = [...watchedOptions]
+ newOptions[index].values = value
+
+ const permutations = getPermutations(newOptions)
+ const oldVariants = [...watchedVariants]
+
+ const findMatchingPermutation = (options: Record<string, string>) => {
+ return permutations.find((permutation) =>
+ Object.keys(options).every((key) => options[key] === permutation[key])
+ )
+ }
+
+ const newVariants = oldVariants.reduce(
+ (variants, variant) => {
+ const match = findMatchingPermutation(variant.options)
+
+ if (match) {
+ variants.push({
+ ...variant,
+ title: getVariantName(match),
+ options: match,
+ })
+ }
+
+ return variants
+ },
+ [] as typeof oldVariants
+ )
+
+ const usedPermutations = new Set(
+ newVariants.map((variant) => variant.options)
+ )
+ const unusedPermutations = permutations.filter(
+ (permutation) => !usedPermutations.has(permutation)
+ )
+
+ unusedPermutations.forEach((permutation) => {
+ newVariants.push({
+ title: getVariantName(permutation),
+ options: permutation,
+ should_create: hasUserSelectedVariants ? false : true,
+ variant_rank: newVariants.length,
+ // NOTE - prepare inventory array here for now so we prevent rendering issue if we append the items later
+ inventory: [{ inventory_item_id: "", required_quantity: "" }],
+ })
+ })
+
+ form.setValue("variants", newVariants)
+ }
+
+ const handleRemoveOption = (index: number) => {
+ if (index === 0) {
+ return
+ }
+
+ options.remove(index)
+
+ const newOptions = [...watchedOptions]
+ newOptions.splice(index, 1)
+
+ const permutations = getPermutations(newOptions)
+ const oldVariants = [...watchedVariants]
+
+ const findMatchingPermutation = (options: Record<string, string>) => {
+ return permutations.find((permutation) =>
+ Object.keys(options).every((key) => options[key] === permutation[key])
+ )
+ }
+
+ const newVariants = oldVariants.reduce(
+ (variants, variant) => {
+ const match = findMatchingPermutation(variant.options)
+
+ if (match) {
+ variants.push({
+ ...variant,
+ title: getVariantName(match),
+ options: match,
+ })
+ }
+
+ return variants
+ },
+ [] as typeof oldVariants
+ )
+
+ const usedPermutations = new Set(
+ newVariants.map((variant) => variant.options)
+ )
+ const unusedPermutations = permutations.filter(
+ (permutation) => !usedPermutations.has(permutation)
+ )
+
+ unusedPermutations.forEach((permutation) => {
+ newVariants.push({
+ title: getVariantName(permutation),
+ options: permutation,
+ should_create: false,
+ variant_rank: newVariants.length,
+ })
+ })
+
+ form.setValue("variants", newVariants)
+ }
+
+ const handleRankChange = (
+ items: FieldArrayWithId<ProductCreateSchemaType, "variants">[]
+ ) => {
+ // Items in the SortableList are memorised, so we need to find the current
+ // value to preserve any changes that have been made to `should_create`.
+ const update = items.map((item, index) => {
+ const variant = watchedVariants.find((v) => v.title === item.title)
+
+ return {
+ id: item.id,
+ ...(variant || item),
+ variant_rank: index,
+ }
+ })
+
+ variants.replace(update)
+ }
+
+ const getCheckboxState = (variants: ProductCreateSchemaType["variants"]) => {
+ if (variants.every((variant) => variant.should_create)) {
+ return true
+ }
+
+ if (variants.some((variant) => variant.should_create)) {
+ return "indeterminate"
+ }
+
+ return false
+ }
+
+ const onCheckboxChange = (value: boolean | "indeterminate") => {
+ switch (value) {
+ case true: {
+ const update = watchedVariants.map((variant) => {
+ return {
+ ...variant,
+ should_create: true,
+ }
+ })
+
+ form.setValue("variants", update)
+ break
+ }
+ case false: {
+ const update = watchedVariants.map((variant) => {
+ return {
+ ...variant,
+ should_create: false,
+ }
+ })
+
+ form.setValue("variants", decorateVariantsWithDefaultValues(update))
+ break
+ }
+ case "indeterminate":
+ break
+ }
+ }
+
+ const createDefaultOptionAndVariant = () => {
+ form.setValue("options", [
+ {
+ title: "Default option",
+ values: ["Default option value"],
+ },
+ ])
+ form.setValue(
+ "variants",
+ decorateVariantsWithDefaultValues([
+ {
+ title: "Default variant",
+ should_create: true,
+ variant_rank: 0,
+ options: {
+ "Default option": "Default option value",
+ },
+ inventory: [{ inventory_item_id: "", required_quantity: "" }],
+ is_default: true,
+ },
+ ])
+ )
+ }
+
+ return (
+ <div id="variants" className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-6">
+ <Heading level="h2">{t("products.create.variants.header")}</Heading>
+ <SwitchBox
+ control={form.control}
+ name="enable_variants"
+ label={t("products.create.variants.subHeadingTitle")}
+ description={t("products.create.variants.subHeadingDescription")}
+ onCheckedChange={(checked) => {
+ if (checked) {
+ form.setValue("options", [
+ {
+ title: "",
+ values: [],
+ },
+ ])
+ form.setValue("variants", [])
+ } else {
+ createDefaultOptionAndVariant()
+ }
+ }}
+ />
+ </div>
+ {watchedAreVariantsEnabled && (
+ <>
+ <div className="flex flex-col gap-y-6">
+ <Form.Field
+ control={form.control}
+ name="options"
+ render={() => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-y-6">
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex flex-col">
+ <Form.Label>
+ {t("products.create.variants.productOptions.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("products.create.variants.productOptions.hint")}
+ </Form.Hint>
+ </div>
+ <Button
+ size="small"
+ variant="secondary"
+ type="button"
+ onClick={() => {
+ options.append({
+ title: "",
+ values: [],
+ })
+ }}
+ >
+ {t("actions.add")}
+ </Button>
+ </div>
+ {showInvalidOptionsMessage && (
+ <Alert dismissible variant="error">
+ {t("products.create.errors.options")}
+ </Alert>
+ )}
+ <ul className="flex flex-col gap-y-4">
+ {options.fields.map((option, index) => {
+ return (
+ <li
+ key={option.id}
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-center gap-1.5 rounded-xl p-1.5"
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`options.${index}.title`}
+ >
+ {t("fields.title")}
+ </Label>
+ </div>
+ <Input
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ {...form.register(
+ `options.${index}.title` as const
+ )}
+ placeholder={t(
+ "products.fields.options.optionTitlePlaceholder"
+ )}
+ />
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`options.${index}.values`}
+ >
+ {t("fields.values")}
+ </Label>
+ </div>
+ <Controller
+ control={form.control}
+ name={`options.${index}.values` as const}
+ render={({
+ field: { onChange, ...field },
+ }) => {
+ const handleValueChange = (
+ value: string[]
+ ) => {
+ handleOptionValueUpdate(index, value)
+ onChange(value)
+ }
+
+ return (
+ <ChipInput
+ {...field}
+ variant="contrast"
+ onChange={handleValueChange}
+ placeholder={t(
+ "products.fields.options.variantionsPlaceholder"
+ )}
+ />
+ )
+ }}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ disabled={index === 0}
+ onClick={() => handleRemoveOption(index)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ )
+ })}
+ </ul>
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="grid grid-cols-1 gap-x-4 gap-y-8">
+ <div className="flex flex-col gap-y-6">
+ <div className="flex flex-col">
+ <Label weight="plus">
+ {t("products.create.variants.productVariants.label")}
+ </Label>
+ <Hint>
+ {t("products.create.variants.productVariants.hint")}
+ </Hint>
+ </div>
+ {!showInvalidOptionsMessage && showInvalidVariantsMessage && (
+ <Alert dismissible variant="error">
+ {t("products.create.errors.variants")}
+ </Alert>
+ )}
+ {variants.fields.length > 0 ? (
+ <div className="overflow-hidden rounded-xl border">
+ <div
+ className="bg-ui-bg-component text-ui-fg-subtle grid items-center gap-3 border-b px-6 py-2.5"
+ style={{
+ gridTemplateColumns: `20px 28px repeat(${watchedOptions.length}, 1fr)`,
+ }}
+ >
+ <div>
+ <Checkbox
+ className="relative"
+ checked={getCheckboxState(watchedVariants)}
+ onCheckedChange={onCheckboxChange}
+ />
+ </div>
+ <div />
+ {watchedOptions.map((option, index) => (
+ <div key={index}>
+ <Text size="small" leading="compact" weight="plus">
+ {option.title}
+ </Text>
+ </div>
+ ))}
+ </div>
+ <SortableList
+ items={variants.fields}
+ onChange={handleRankChange}
+ renderItem={(item, index) => {
+ return (
+ <SortableList.Item
+ id={item.id}
+ className={clx("bg-ui-bg-base border-b", {
+ "border-b-0": index === variants.fields.length - 1,
+ })}
+ >
+ <div
+ className="text-ui-fg-subtle grid w-full items-center gap-3 px-6 py-2.5"
+ style={{
+ gridTemplateColumns: `20px 28px repeat(${watchedOptions.length}, 1fr)`,
+ }}
+ >
+ <Form.Field
+ control={form.control}
+ name={`variants.${index}.should_create` as const}
+ render={({
+ field: { value, onChange, ...field },
+ }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Checkbox
+ className="relative"
+ {...field}
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <SortableList.DragHandle />
+ {Object.values(item.options).map((value, index) => (
+ <Text key={index} size="small" leading="compact">
+ {value}
+ </Text>
+ ))}
+ </div>
+ </SortableList.Item>
+ )
+ }}
+ />
+ </div>
+ ) : (
+ <Alert>
+ {t("products.create.variants.productVariants.alert")}
+ </Alert>
+ )}
+ {variants.fields.length > 0 && (
+ <InlineTip label={t("general.tip")}>
+ {t("products.create.variants.productVariants.tip")}
+ </InlineTip>
+ )}
+ </div>
+ </div>
+ </>
+ )}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/index.ts b/packages/vendor/src/pages/products/create/product-create-details-form/index.ts
new file mode 100644
index 000000000..16da6a1b8
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-details-form"
diff --git a/packages/vendor/src/pages/products/create/product-create-details-form/product-create-details-form.tsx b/packages/vendor/src/pages/products/create/product-create-details-form/product-create-details-form.tsx
new file mode 100644
index 000000000..fd5f5c9f0
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-details-form/product-create-details-form.tsx
@@ -0,0 +1,46 @@
+import { Divider, Heading } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import {
+ FormExtensionZone,
+ useDashboardExtension,
+} from "@/extensions"
+import { ProductCreateSchemaType } from "../../types"
+import { ProductCreateGeneralSection } from "./components/product-create-details-general-section"
+import { ProductCreateMediaSection } from "./components/product-create-details-media-section"
+import { ProductCreateVariantsSection } from "./components/product-create-details-variant-section"
+
+type ProductAttributesProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateDetailsForm = ({ form }: ProductAttributesProps) => {
+ const { getFormFields } = useDashboardExtension()
+ const fields = getFormFields("product", "create", "general")
+
+ return (
+ <div className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <Header />
+ <div className="flex flex-col gap-y-6">
+ <ProductCreateGeneralSection form={form} />
+ <FormExtensionZone fields={fields} form={form} />
+ <ProductCreateMediaSection form={form} />
+ </div>
+ <Divider />
+ <ProductCreateVariantsSection form={form} />
+ </div>
+ </div>
+ )
+}
+
+const Header = () => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="flex flex-col">
+ <Heading>{t("products.create.header")}</Heading>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-form/index.ts b/packages/vendor/src/pages/products/create/product-create-form/index.ts
new file mode 100644
index 000000000..cbd67cb00
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-form"
diff --git a/packages/vendor/src/pages/products/create/product-create-form/product-create-form.tsx b/packages/vendor/src/pages/products/create/product-create-form/product-create-form.tsx
new file mode 100644
index 000000000..52907e4ef
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-form/product-create-form.tsx
@@ -0,0 +1,434 @@
+import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useEffect, useMemo, useState } from "react"
+import { useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import {
+ useDashboardExtension,
+ useExtendableForm,
+} from "@/extensions"
+import { useCreateProduct } from "@hooks/api/products"
+import { uploadFilesQuery } from "@lib/client"
+import {
+ PRODUCT_CREATE_FORM_DEFAULTS,
+ ProductCreateSchema,
+} from "@pages/products/create/constants"
+import { ProductCreateDetailsForm } from "../product-create-details-form"
+import { ProductCreateInventoryKitForm } from "../product-create-inventory-kit-form"
+import { ProductCreateOrganizeForm } from "../product-create-organize-form"
+import { ProductCreateVariantsForm } from "../product-create-variants-form"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+import { useRegions } from "@hooks/api"
+
+enum Tab {
+ DETAILS = "details",
+ ORGANIZE = "organize",
+ VARIANTS = "variants",
+ INVENTORY = "inventory",
+}
+
+type TabState = Record<Tab, ProgressStatus>
+
+const SAVE_DRAFT_BUTTON = "save-draft-button"
+
+type ProductCreateFormProps = {
+ defaultChannel?: HttpTypes.AdminSalesChannel
+ store?: HttpTypes.AdminStore
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}
+
+export const ProductCreateForm = ({
+ defaultChannel,
+ store,
+}: ProductCreateFormProps) => {
+ const [tab, setTab] = useState<Tab>(Tab.DETAILS)
+ const [tabState, setTabState] = useState<TabState>({
+ [Tab.DETAILS]: "in-progress",
+ [Tab.ORGANIZE]: "not-started",
+ [Tab.VARIANTS]: "not-started",
+ [Tab.INVENTORY]: "not-started",
+ })
+
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { getFormConfigs } = useDashboardExtension()
+ const configs = getFormConfigs("product", "create")
+
+ const { regions } = useRegions({ limit: 9999 })
+ const { price_preferences: pricePreferences } = usePricePreferences({
+ limit: 9999,
+ })
+
+ const form = useExtendableForm({
+ defaultValues: {
+ ...PRODUCT_CREATE_FORM_DEFAULTS,
+ sales_channels: defaultChannel
+ ? [
+ {
+ id: defaultChannel.id,
+ name: defaultChannel.name,
+ },
+ ]
+ : [],
+ },
+ schema: ProductCreateSchema,
+ configs,
+ })
+
+ const { mutateAsync, isPending } = useCreateProduct()
+
+ /**
+ * TODO: Important to revisit this - use variants watch so high in the tree can cause needless rerenders of the entire page
+ * which is suboptimal when rerenders are caused by bulk editor changes
+ */
+
+ const watchedVariants = useWatch({
+ control: form.control,
+ name: "variants",
+ })
+
+ const showInventoryTab = useMemo(
+ () => watchedVariants.some((v) => v.manage_inventory && v.inventory_kit),
+ [watchedVariants]
+ )
+
+ const handleSubmit = form.handleSubmit(async (values, e) => {
+ let isDraftSubmission = false
+
+ if (e?.nativeEvent instanceof SubmitEvent) {
+ const submitter = e?.nativeEvent?.submitter as HTMLButtonElement
+ isDraftSubmission = submitter.dataset.name === SAVE_DRAFT_BUTTON
+ }
+
+ const media = values.media || []
+ const payload = { ...values, media: undefined }
+
+ let uploadedMedia: (HttpTypes.AdminFile & {
+ isThumbnail: boolean
+ })[] = []
+ try {
+ if (media.length) {
+ const thumbnailReq = media.filter((m) => m.isThumbnail)
+ const otherMediaReq = media.filter((m) => !m.isThumbnail)
+
+ const fileReqs = []
+ if (thumbnailReq?.length) {
+ fileReqs.push(
+ uploadFilesQuery(thumbnailReq).then((r: any) =>
+ r.files.map((f: any) => ({
+ ...f,
+ isThumbnail: true,
+ }))
+ )
+ )
+ }
+ if (otherMediaReq?.length) {
+ fileReqs.push(
+ uploadFilesQuery(otherMediaReq).then((r: any) =>
+ r.files.map((f: any) => ({
+ ...f,
+ isThumbnail: false,
+ }))
+ )
+ )
+ }
+
+ uploadedMedia = (await Promise.all(fileReqs)).flat()
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ toast.error(error.message)
+ }
+ }
+
+ await mutateAsync(
+ {
+ ...payload,
+ status: isDraftSubmission ? "draft" : "proposed",
+ images: uploadedMedia,
+ weight: parseInt(payload.weight || "") || undefined,
+ length: parseInt(payload.length || "") || undefined,
+ height: parseInt(payload.height || "") || undefined,
+ width: parseInt(payload.width || "") || undefined,
+ type_id: payload.type_id || undefined,
+ tags:
+ payload.tags?.map((tag) => ({
+ id: tag,
+ })) || [],
+ collection_id: payload.collection_id || undefined,
+ shipping_profile_id: undefined,
+ enable_variants: undefined,
+ additional_data: undefined,
+ categories: payload.categories.map((cat) => ({
+ id: cat,
+ })),
+ variants: payload.variants.map((variant) => ({
+ ...variant,
+ sku: variant.sku === "" ? undefined : variant.sku,
+ manage_inventory: true,
+ allow_backorder: false,
+ should_create: undefined,
+ is_default: undefined,
+ inventory_kit: undefined,
+ inventory: undefined,
+ prices: Object.keys(variant.prices || {}).map((key) => ({
+ currency_code: key,
+ amount: parseFloat(variant.prices?.[key] as string),
+ })),
+ })),
+ },
+ {
+ onSuccess: (data) => {
+ toast.success(
+ t("products.create.successToast", {
+ title: data.product.title,
+ })
+ )
+
+ handleSuccess(`../${data.product.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const onNext = async (currentTab: Tab) => {
+ const valid = await form.trigger()
+
+ if (!valid) {
+ return
+ }
+
+ if (currentTab === Tab.DETAILS) {
+ setTab(Tab.ORGANIZE)
+ }
+
+ if (currentTab === Tab.ORGANIZE) {
+ setTab(Tab.VARIANTS)
+ }
+
+ if (currentTab === Tab.VARIANTS) {
+ setTab(Tab.INVENTORY)
+ }
+ }
+
+ useEffect(() => {
+ const currentState = { ...tabState }
+ if (tab === Tab.DETAILS) {
+ currentState[Tab.DETAILS] = "in-progress"
+ }
+ if (tab === Tab.ORGANIZE) {
+ currentState[Tab.DETAILS] = "completed"
+ currentState[Tab.ORGANIZE] = "in-progress"
+ }
+ if (tab === Tab.VARIANTS) {
+ currentState[Tab.DETAILS] = "completed"
+ currentState[Tab.ORGANIZE] = "completed"
+ currentState[Tab.VARIANTS] = "in-progress"
+ }
+ if (tab === Tab.INVENTORY) {
+ currentState[Tab.DETAILS] = "completed"
+ currentState[Tab.ORGANIZE] = "completed"
+ currentState[Tab.VARIANTS] = "completed"
+ currentState[Tab.INVENTORY] = "in-progress"
+ }
+
+ setTabState({ ...currentState })
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- we only want this effect to run when the tab changes
+ }, [tab])
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onKeyDown={(e) => {
+ // We want to continue to the next tab on enter instead of saving as draft immediately
+ if (e.key === "Enter") {
+ if (
+ e.target instanceof HTMLTextAreaElement &&
+ !(e.metaKey || e.ctrlKey)
+ ) {
+ return
+ }
+
+ e.preventDefault()
+
+ if (e.metaKey || e.ctrlKey) {
+ if (tab !== Tab.VARIANTS) {
+ e.preventDefault()
+ e.stopPropagation()
+ onNext(tab)
+
+ return
+ }
+
+ handleSubmit()
+ }
+ }
+ }}
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col"
+ >
+ <ProgressTabs
+ value={tab}
+ onValueChange={async (tab) => {
+ const valid = await form.trigger()
+
+ if (!valid) {
+ return
+ }
+
+ setTab(tab as Tab)
+ }}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="-my-2 w-full border-l">
+ <ProgressTabs.List className="justify-start-start flex w-full items-center">
+ <ProgressTabs.Trigger
+ status={tabState[Tab.DETAILS]}
+ value={Tab.DETAILS}
+ className="max-w-[200px] truncate"
+ >
+ {t("products.create.tabs.details")}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState[Tab.ORGANIZE]}
+ value={Tab.ORGANIZE}
+ className="max-w-[200px] truncate"
+ >
+ {t("products.create.tabs.organize")}
+ </ProgressTabs.Trigger>
+ <ProgressTabs.Trigger
+ status={tabState[Tab.VARIANTS]}
+ value={Tab.VARIANTS}
+ className="max-w-[200px] truncate"
+ >
+ {t("products.create.tabs.variants")}
+ </ProgressTabs.Trigger>
+ {showInventoryTab && (
+ <ProgressTabs.Trigger
+ status={tabState[Tab.INVENTORY]}
+ value={Tab.INVENTORY}
+ className="max-w-[200px] truncate"
+ >
+ {t("products.create.tabs.inventory")}
+ </ProgressTabs.Trigger>
+ )}
+ </ProgressTabs.List>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.DETAILS}
+ >
+ <ProductCreateDetailsForm form={form} />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.ORGANIZE}
+ >
+ <ProductCreateOrganizeForm form={form} />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.VARIANTS}
+ >
+ <ProductCreateVariantsForm
+ form={form}
+ store={store}
+ regions={regions}
+ pricePreferences={pricePreferences}
+ />
+ </ProgressTabs.Content>
+ {showInventoryTab && (
+ <ProgressTabs.Content
+ className="size-full overflow-y-auto"
+ value={Tab.INVENTORY}
+ >
+ <ProductCreateInventoryKitForm form={form} />
+ </ProgressTabs.Content>
+ )}
+ </RouteFocusModal.Body>
+ </ProgressTabs>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ data-name={SAVE_DRAFT_BUTTON}
+ size="small"
+ type="submit"
+ isLoading={isPending}
+ className="whitespace-nowrap"
+ >
+ Draft
+ </Button>
+ <PrimaryButton
+ tab={tab}
+ next={onNext}
+ isLoading={isPending}
+ showInventoryTab={showInventoryTab}
+ />
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+type PrimaryButtonProps = {
+ tab: Tab
+ next: (tab: Tab) => void
+ isLoading?: boolean
+ showInventoryTab: boolean
+}
+
+const PrimaryButton = ({
+ tab,
+ next,
+ isLoading,
+ showInventoryTab,
+}: PrimaryButtonProps) => {
+ const { t } = useTranslation()
+
+ if (
+ (tab === Tab.VARIANTS && !showInventoryTab) ||
+ (tab === Tab.INVENTORY && showInventoryTab)
+ ) {
+ return (
+ <Button
+ data-name="publish-button"
+ key="submit-button"
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isLoading}
+ >
+ Create Product
+ </Button>
+ )
+ }
+
+ return (
+ <Button
+ key="next-button"
+ type="button"
+ variant="primary"
+ size="small"
+ onClick={() => next(tab)}
+ >
+ {t("actions.continue")}
+ </Button>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/index.ts b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/index.ts
new file mode 100644
index 000000000..fcbd72fe0
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-inventory-kit-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/product-create-inventory-kit-section.tsx b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/product-create-inventory-kit-section.tsx
new file mode 100644
index 000000000..fd0b75d91
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/components/product-create-inventory-kit-section/product-create-inventory-kit-section.tsx
@@ -0,0 +1,209 @@
+import { Button, Heading, IconButton, Input, Label } from "@medusajs/ui"
+import { useFieldArray, UseFormReturn, useWatch } from "react-hook-form"
+import { XMarkMini } from "@medusajs/icons"
+import { useTranslation } from "react-i18next"
+
+import { ProductCreateSchemaType } from "../../../../types"
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { sdk } from "@lib/client"
+
+type VariantSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+ variant: ProductCreateSchemaType["variants"][0]
+ index: number
+}
+
+function VariantSection({ form, variant, index }: VariantSectionProps) {
+ const { t } = useTranslation()
+
+ const inventory = useFieldArray({
+ control: form.control,
+ name: `variants.${index}.inventory`,
+ })
+
+ const inventoryFormData = useWatch({
+ control: form.control,
+ name: `variants.${index}.inventory`,
+ })
+
+ const items = useComboboxData({
+ queryKey: ["inventory_items"],
+ queryFn: (params) => sdk.admin.inventoryItem.list(params),
+ getOptions: (data) =>
+ data.inventory_items.map((item) => ({
+ label: item.title || item.sku || item.id,
+ value: item.id,
+ })),
+ })
+
+ /**
+ * Will mark an option as disabled if another input already selected that option
+ * @param option
+ * @param inventoryIndex
+ */
+ const isItemOptionDisabled = (
+ option: (typeof items.options)[0],
+ inventoryIndex: number
+ ) => {
+ return inventoryFormData?.some(
+ (i, index) =>
+ index != inventoryIndex && i.inventory_item_id === option.value
+ )
+ }
+
+ return (
+ <div className="grid gap-y-4">
+ <div className="flex items-start justify-between gap-x-4">
+ <div className="flex flex-col">
+ <Form.Label>{variant.title}</Form.Label>
+ <Form.Hint>{t("products.create.inventory.label")}</Form.Hint>
+ </div>
+ <Button
+ size="small"
+ variant="secondary"
+ type="button"
+ onClick={() => {
+ inventory.append({
+ inventory_item_id: "",
+ required_quantity: "",
+ })
+ }}
+ >
+ {t("actions.add")}
+ </Button>
+ </div>
+ {inventory.fields.map((inventoryItem, inventoryIndex) => (
+ <li
+ key={inventoryItem.id}
+ className="bg-ui-bg-component shadow-elevation-card-rest grid grid-cols-[1fr_28px] items-center gap-1.5 rounded-xl p-1.5"
+ >
+ <div className="grid grid-cols-[min-content,1fr] items-center gap-1.5">
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`variants.${index}.inventory.${inventoryIndex}.inventory_item_id`}
+ >
+ {t("fields.item")}
+ </Label>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name={`variants.${index}.inventory.${inventoryIndex}.inventory_item_id`}
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={items.options.map((o) => ({
+ ...o,
+ disabled: isItemOptionDisabled(o, inventoryIndex),
+ }))}
+ searchValue={items.searchValue}
+ onSearchValueChange={items.onSearchValueChange}
+ fetchNextPage={items.fetchNextPage}
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover"
+ placeholder={t(
+ "products.create.inventory.itemPlaceholder"
+ )}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="flex items-center px-2 py-1.5">
+ <Label
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ htmlFor={`variants.${index}.inventory.${inventoryIndex}.required_quantity`}
+ >
+ {t("fields.quantity")}
+ </Label>
+ </div>
+ <Form.Field
+ control={form.control}
+ name={`variants.${index}.inventory.${inventoryIndex}.required_quantity`}
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ type="number"
+ className="bg-ui-bg-field-component"
+ min={0}
+ value={value}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(Number(value))
+ }
+ }}
+ {...field}
+ placeholder={t(
+ "products.create.inventory.quantityPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <IconButton
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ onClick={() => inventory.remove(inventoryIndex)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </li>
+ ))}
+ </div>
+ )
+}
+
+type ProductCreateInventoryKitSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateInventoryKitSection = ({
+ form,
+}: ProductCreateInventoryKitSectionProps) => {
+ const { t } = useTranslation()
+
+ const variants = useFieldArray({
+ control: form.control,
+ name: "variants",
+ })
+
+ return (
+ <div id="organize" className="flex flex-col gap-y-8">
+ <Heading>{t("products.create.inventory.heading")}</Heading>
+
+ {variants.fields
+ .filter((v) => v.inventory_kit)
+ .map((variant, variantIndex) => (
+ <VariantSection
+ key={variant.id}
+ form={form}
+ variant={variant}
+ index={variantIndex}
+ />
+ ))}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/index.ts b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/index.ts
new file mode 100644
index 000000000..e1b2d64cc
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-inventory-kit-form"
diff --git a/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/product-create-inventory-kit-form.tsx b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/product-create-inventory-kit-form.tsx
new file mode 100644
index 000000000..a89918370
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-inventory-kit-form/product-create-inventory-kit-form.tsx
@@ -0,0 +1,20 @@
+import { UseFormReturn } from "react-hook-form"
+
+import { ProductCreateSchemaType } from "../../types"
+import { ProductCreateInventoryKitSection } from "./components/product-create-inventory-kit-section/product-create-inventory-kit-section"
+
+type ProductAttributesProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateInventoryKitForm = ({
+ form,
+}: ProductAttributesProps) => {
+ return (
+ <div className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <ProductCreateInventoryKitSection form={form} />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/index.ts b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/index.ts
new file mode 100644
index 000000000..224e2c794
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-details-attribute-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/product-create-details-attribute-section.tsx b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/product-create-details-attribute-section.tsx
new file mode 100644
index 000000000..c3e6345f5
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-attribute-section/product-create-details-attribute-section.tsx
@@ -0,0 +1,155 @@
+import { Heading, Input } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import { ProductCreateSchemaType } from "../../../../types"
+
+type ProductCreateAttributeSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateAttributeSection = ({
+ form,
+}: ProductCreateAttributeSectionProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div id="attributes" className="flex flex-col gap-y-8">
+ <Heading level="h2">{t("products.attributes")}</Heading>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.countryOrigin.label")}
+ </Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="material"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.material.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="grid grid-cols-2 gap-x-4 gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="width"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.width.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} type="number" min={0} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.length.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} type="number" min={0} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.height.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} type="number" min={0} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.weight.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} type="number" min={0} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.mid_code.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.hs_code.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/index.ts b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/index.ts
new file mode 100644
index 000000000..82e499dd6
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-details-organize-section"
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/product-create-details-organize-section.tsx b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/product-create-details-organize-section.tsx
new file mode 100644
index 000000000..5371b5113
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-organize-section/product-create-details-organize-section.tsx
@@ -0,0 +1,169 @@
+import { Heading } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { Combobox } from "@components/inputs/combobox"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { fetchQuery } from "@lib/client"
+import { ProductCreateSchemaType } from "../../../../types"
+import { CategoryCombobox } from "@pages/products/common/components/category-combobox"
+
+type ProductCreateOrganizationSectionProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateOrganizationSection = ({
+ form,
+}: ProductCreateOrganizationSectionProps) => {
+ const { t } = useTranslation()
+
+ const collections = useComboboxData({
+ queryKey: ["product_collections"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-collections", {
+ method: "GET",
+ query: params,
+ }),
+ getOptions: (data) =>
+ data.product_collections.map((collection: any) => ({
+ label: collection.title!,
+ value: collection.id!,
+ })),
+ })
+
+ const types = useComboboxData({
+ queryKey: ["product_types", "creating"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-types", {
+ method: "GET",
+ query: params,
+ }),
+ getOptions: (data) =>
+ data.product_types.map((type: any) => ({
+ label: type.value,
+ value: type.id,
+ })),
+ })
+
+ const tags = useComboboxData({
+ queryKey: ["product_tags", "creating"],
+ queryFn: (params) =>
+ fetchQuery("/vendor/product-tags", {
+ method: "GET",
+ query: params,
+ }),
+ getOptions: (data) =>
+ data.product_tags.map((tag: any) => ({
+ label: tag.value,
+ value: tag.id,
+ })),
+ })
+
+ return (
+ <div id="organize" className="flex flex-col gap-y-8">
+ <Heading>{t("products.organization.header")}</Heading>
+ <SwitchBox
+ control={form.control}
+ name="discountable"
+ label={t("products.fields.discountable.label")}
+ description={t("products.fields.discountable.hint")}
+ optional
+ />
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="type_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.type.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={types.options}
+ searchValue={types.searchValue}
+ onSearchValueChange={types.onSearchValueChange}
+ fetchNextPage={types.fetchNextPage}
+ allowClear
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="collection_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.collection.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={collections.options}
+ searchValue={collections.searchValue}
+ onSearchValueChange={collections.onSearchValueChange}
+ fetchNextPage={collections.fetchNextPage}
+ allowClear
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="categories"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.categories.label")}
+ </Form.Label>
+ <Form.Control>
+ <CategoryCombobox {...field} />
+ {/* <CategorySelect /> */}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="tags"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("products.fields.tags.label")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={tags.options}
+ searchValue={tags.searchValue}
+ onSearchValueChange={tags.onSearchValueChange}
+ fetchNextPage={tags.fetchNextPage}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/index.ts b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/index.ts
new file mode 100644
index 000000000..4b7932912
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-sales-channel-drawer"
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/product-create-sales-channel-drawer.tsx b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/product-create-sales-channel-drawer.tsx
new file mode 100644
index 000000000..034e96a20
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/components/product-create-sales-channel-stacked-modal/product-create-sales-channel-drawer.tsx
@@ -0,0 +1,160 @@
+import {
+ Button,
+ createDataTableColumnHelper,
+ DataTableRowSelectionState,
+} from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useEffect, useMemo, useState } from "react"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { keepPreviousData } from "@tanstack/react-query"
+import { DataTable } from "@components/data-table"
+import * as hooks from "@components/data-table/helpers/sales-channels"
+import {
+ StackedFocusModal,
+ useStackedModal,
+} from "@components/modals"
+import { useSalesChannels } from "@hooks/api/sales-channels"
+import { ProductCreateSchemaType } from "../../../../types"
+import { SC_STACKED_MODAL_ID } from "../../constants"
+
+type ProductCreateSalesChannelStackedModalProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+const PAGE_SIZE = 50
+
+export const ProductCreateSalesChannelStackedModal = ({
+ form,
+}: ProductCreateSalesChannelStackedModalProps) => {
+ const { t } = useTranslation()
+ const { getValues, setValue } = form
+ const { setIsOpen, getIsOpen } = useStackedModal()
+
+ const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>(
+ {}
+ )
+ const [state, setState] = useState<{ id: string; name: string }[]>([])
+
+ const searchParams = hooks.useSalesChannelTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: SC_STACKED_MODAL_ID,
+ })
+ const { sales_channels, count, isLoading, isError, error } = useSalesChannels(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const open = getIsOpen(SC_STACKED_MODAL_ID)
+
+ useEffect(() => {
+ if (!open) {
+ return
+ }
+
+ const salesChannels = getValues("sales_channels")
+
+ if (salesChannels) {
+ setState(
+ salesChannels.map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ }))
+ )
+
+ setRowSelection(
+ salesChannels.reduce(
+ (acc, channel) => ({
+ ...acc,
+ [channel.id]: true,
+ }),
+ {}
+ )
+ )
+ }
+ }, [open, getValues])
+
+ const onRowSelectionChange = (state: DataTableRowSelectionState) => {
+ const ids = Object.keys(state)
+
+ const addedIdsSet = new Set(
+ ids.filter((id) => state[id] && !rowSelection[id])
+ )
+
+ let addedSalesChannels: { id: string; name: string }[] = []
+
+ if (addedIdsSet.size > 0) {
+ addedSalesChannels =
+ sales_channels?.filter((channel) => addedIdsSet.has(channel.id)) ?? []
+ }
+
+ setState((prev) => {
+ const filteredPrev = prev.filter((channel) => state[channel.id])
+ return Array.from(new Set([...filteredPrev, ...addedSalesChannels]))
+ })
+ setRowSelection(state)
+ }
+
+ const handleAdd = () => {
+ setValue("sales_channels", state, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ setIsOpen(SC_STACKED_MODAL_ID, false)
+ }
+
+ const filters = hooks.useSalesChannelTableFilters()
+ const columns = useColumns()
+ const emptyState = hooks.useSalesChannelTableEmptyState()
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <StackedFocusModal.Content className="flex flex-col overflow-hidden">
+ <StackedFocusModal.Header />
+ <StackedFocusModal.Body className="flex-1 overflow-hidden">
+ <DataTable
+ data={sales_channels}
+ columns={columns}
+ filters={filters}
+ emptyState={emptyState}
+ rowCount={count}
+ pageSize={PAGE_SIZE}
+ getRowId={(row) => row.id}
+ rowSelection={{
+ state: rowSelection,
+ onRowSelectionChange,
+ }}
+ isLoading={isLoading}
+ layout="fill"
+ prefix={SC_STACKED_MODAL_ID}
+ />
+ </StackedFocusModal.Body>
+ <StackedFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <StackedFocusModal.Close asChild>
+ <Button size="small" variant="secondary" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </StackedFocusModal.Close>
+ <Button size="small" onClick={handleAdd} type="button">
+ {t("actions.save")}
+ </Button>
+ </div>
+ </StackedFocusModal.Footer>
+ </StackedFocusModal.Content>
+ )
+}
+
+const columnHelper = createDataTableColumnHelper<HttpTypes.AdminSalesChannel>()
+
+const useColumns = () => {
+ const base = hooks.useSalesChannelTableColumns()
+
+ return useMemo(() => [columnHelper.select(), ...base], [base])
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/constants.ts b/packages/vendor/src/pages/products/create/product-create-organize-form/constants.ts
new file mode 100644
index 000000000..1bdf2746d
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/constants.ts
@@ -0,0 +1 @@
+export const SC_STACKED_MODAL_ID = "sc"
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/index.ts b/packages/vendor/src/pages/products/create/product-create-organize-form/index.ts
new file mode 100644
index 000000000..7a8263948
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-organize-form"
diff --git a/packages/vendor/src/pages/products/create/product-create-organize-form/product-create-organize-form.tsx b/packages/vendor/src/pages/products/create/product-create-organize-form/product-create-organize-form.tsx
new file mode 100644
index 000000000..e8048a9fd
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-organize-form/product-create-organize-form.tsx
@@ -0,0 +1,32 @@
+import { UseFormReturn } from "react-hook-form"
+
+import { StackedFocusModal } from "@components/modals"
+import {
+ FormExtensionZone,
+ useDashboardExtension,
+} from "@/extensions"
+import { ProductCreateSchemaType } from "../../types"
+import { ProductCreateOrganizationSection } from "./components/product-create-organize-section"
+import { ProductCreateSalesChannelStackedModal } from "./components/product-create-sales-channel-stacked-modal"
+import { SC_STACKED_MODAL_ID } from "./constants"
+
+type ProductAttributesProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+}
+
+export const ProductCreateOrganizeForm = ({ form }: ProductAttributesProps) => {
+ const { getFormFields } = useDashboardExtension()
+ const fields = getFormFields("product", "create", "organize")
+
+ return (
+ <StackedFocusModal id={SC_STACKED_MODAL_ID}>
+ <div className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <ProductCreateOrganizationSection form={form} />
+ <FormExtensionZone fields={fields} form={form} />
+ </div>
+ </div>
+ <ProductCreateSalesChannelStackedModal form={form} />
+ </StackedFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/product-create-variants-form/index.ts b/packages/vendor/src/pages/products/create/product-create-variants-form/index.ts
new file mode 100644
index 000000000..442f05574
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-variants-form/index.ts
@@ -0,0 +1 @@
+export * from "./product-create-variants-form"
diff --git a/packages/vendor/src/pages/products/create/product-create-variants-form/product-create-variants-form.tsx b/packages/vendor/src/pages/products/create/product-create-variants-form/product-create-variants-form.tsx
new file mode 100644
index 000000000..47e98f0bb
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/product-create-variants-form/product-create-variants-form.tsx
@@ -0,0 +1,165 @@
+import { useMemo } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { HttpTypes } from "@medusajs/types"
+
+import {
+ createDataGridHelper,
+ createDataGridPriceColumns,
+ DataGrid,
+} from "@components/data-grid"
+import { useRouteModal } from "@components/modals"
+import {
+ ProductCreateOptionSchema,
+ ProductCreateVariantSchema,
+} from "../../constants"
+import { ProductCreateSchemaType } from "../../types"
+
+type ProductCreateVariantsFormProps = {
+ form: UseFormReturn<ProductCreateSchemaType>
+ regions?: HttpTypes.AdminRegion[]
+ store?: HttpTypes.AdminStore
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}
+
+type VariantWithIndex = ProductCreateVariantSchema & {
+ originalIndex: number
+}
+
+export const ProductCreateVariantsForm = ({
+ form,
+ regions,
+ store,
+ pricePreferences,
+}: ProductCreateVariantsFormProps) => {
+ const { setCloseOnEscape } = useRouteModal()
+
+ const currencyCodes = useMemo(
+ () => store?.supported_currencies?.map((c) => c.currency_code) || [],
+ [store]
+ )
+
+ const variants = useWatch({
+ control: form.control,
+ name: "variants",
+ defaultValue: [],
+ })
+
+ const options = useWatch({
+ control: form.control,
+ name: "options",
+ defaultValue: [],
+ })
+
+ /**
+ * NOTE: anything that goes to the datagrid component needs to be memoised otherwise DataGrid will rerender and inputs will loose focus
+ */
+ const columns = useColumns({
+ options,
+ currencies: currencyCodes,
+ regions,
+ pricePreferences,
+ })
+
+ const variantData = useMemo(() => {
+ const ret: VariantWithIndex[] = []
+
+ variants.forEach((v, i) => {
+ if (v.should_create) {
+ ret.push({ ...v, originalIndex: i })
+ }
+ })
+
+ return ret
+ }, [variants])
+
+ return (
+ <div className="flex size-full flex-col divide-y overflow-hidden">
+ <DataGrid
+ columns={columns}
+ data={variantData}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ />
+ </div>
+ )
+}
+
+const columnHelper = createDataGridHelper<
+ VariantWithIndex,
+ ProductCreateSchemaType
+>()
+
+const useColumns = ({
+ options,
+ currencies = [],
+ regions = [],
+ pricePreferences = [],
+}: {
+ options: ProductCreateOptionSchema[]
+ currencies?: string[]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}) => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.column({
+ id: "options",
+ header: () => (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">
+ {options.map((o) => o.title).join(" / ")}
+ </span>
+ </div>
+ ),
+ cell: (context) => {
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ {options
+ .map((o) => context.row.original.options[o.title])
+ .join(" / ")}
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ disableHiding: true,
+ }),
+ columnHelper.column({
+ id: "title",
+ name: t("fields.title"),
+ header: t("fields.title"),
+ field: (context) =>
+ `variants.${context.row.original.originalIndex}.title`,
+ type: "text",
+ cell: (context) => {
+ return <DataGrid.TextCell context={context} />
+ },
+ }),
+ columnHelper.column({
+ id: "sku",
+ name: t("fields.sku"),
+ header: t("fields.sku"),
+ field: (context) =>
+ `variants.${context.row.original.originalIndex}.sku`,
+ type: "text",
+ cell: (context) => {
+ return <DataGrid.TextCell context={context} />
+ },
+ }),
+
+ ...createDataGridPriceColumns<VariantWithIndex, ProductCreateSchemaType>({
+ currencies,
+ pricePreferences,
+ getFieldName: (context, value) => {
+ if (context.column.id?.startsWith("currency_prices")) {
+ return `variants.${context.row.original.originalIndex}.prices.${value}`
+ }
+ return `variants.${context.row.original.originalIndex}.prices.${value}`
+ },
+ t,
+ }),
+ ],
+ [currencies, regions, options, pricePreferences, t]
+ )
+}
diff --git a/packages/vendor/src/pages/products/create/utils.ts b/packages/vendor/src/pages/products/create/utils.ts
new file mode 100644
index 000000000..5769d17ee
--- /dev/null
+++ b/packages/vendor/src/pages/products/create/utils.ts
@@ -0,0 +1,14 @@
+import { ProductCreateVariantSchema } from "./constants"
+
+export const decorateVariantsWithDefaultValues = (
+ variants: ProductCreateVariantSchema[]
+) => {
+ return variants.map((variant) => ({
+ ...variant,
+ title: variant.title || "",
+ sku: variant.sku || "",
+ manage_inventory: variant.manage_inventory || false,
+ allow_backorder: variant.allow_backorder || false,
+ inventory_kit: variant.inventory_kit || false,
+ }))
+}
diff --git a/packages/vendor/src/pages/products/export/export-filters.tsx b/packages/vendor/src/pages/products/export/export-filters.tsx
new file mode 100644
index 000000000..c94e4487c
--- /dev/null
+++ b/packages/vendor/src/pages/products/export/export-filters.tsx
@@ -0,0 +1,22 @@
+import { Heading, Text } from "@medusajs/ui"
+import { DataTableFilter } from "@components/table/data-table/data-table-filter"
+import { useTranslation } from "react-i18next"
+import { useProductTableFilters } from "@hooks/table/filters"
+
+export const ExportFilters = () => {
+ const { t } = useTranslation()
+ const filters = useProductTableFilters()
+
+ return (
+ <div>
+ <Heading level="h2">{t("products.export.filters.title")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("products.export.filters.description")}
+ </Text>
+
+ <div className="mt-4">
+ <DataTableFilter filters={filters} readonly />
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/export/index.tsx b/packages/vendor/src/pages/products/export/index.tsx
new file mode 100644
index 000000000..1f905f5dc
--- /dev/null
+++ b/packages/vendor/src/pages/products/export/index.tsx
@@ -0,0 +1,66 @@
+// Route: /products/export
+import { Button, Heading, toast } from "@medusajs/ui"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { useTranslation } from "react-i18next"
+import { ExportFilters } from "./export-filters"
+import { useExportProducts } from "@hooks/api"
+import { useProductTableQuery } from "@hooks/table/query"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.export.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("products.export.description")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <ProductExportContent />
+ </RouteDrawer>
+ )
+}
+
+const ProductExportContent = () => {
+ const { t } = useTranslation()
+ const { searchParams } = useProductTableQuery({})
+ const { mutateAsync } = useExportProducts(searchParams)
+ const { handleSuccess } = useRouteModal()
+
+ const handleExportRequest = async () => {
+ await mutateAsync(
+ {},
+ {
+ onSuccess: ({ url }) => {
+ toast.info(t("products.export.success.title"))
+
+ const link = document.createElement("a")
+ link.href = url
+ link.setAttribute("download", `products-export.csv`)
+ document.body.appendChild(link)
+ link.click()
+ link.parentNode?.removeChild(link)
+
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <RouteDrawer.Body className="flex flex-1 flex-col overflow-hidden px-6 py-4">
+ <ExportFilters />
+ <RouteDrawer.Footer className="px-0">
+ <Button onClick={handleExportRequest}>
+ {t("products.export.action")}
+ </Button>
+ </RouteDrawer.Footer>
+ </RouteDrawer.Body>
+ )
+}
diff --git a/packages/vendor/src/pages/products/import/helpers/import-template.ts b/packages/vendor/src/pages/products/import/helpers/import-template.ts
new file mode 100644
index 000000000..ba29b691d
--- /dev/null
+++ b/packages/vendor/src/pages/products/import/helpers/import-template.ts
@@ -0,0 +1,13 @@
+const ProductImportCSV =
+ "data:text/csv;charset=utf-8," +
+ `Product Id;Product Handle;Product Title;Product Subtitle;Product Description;Product Status;Product Thumbnail;Product Weight;Product Length;Product Width;Product Height;Product HS Code;Product Origin Country;Product MID Code;Product Material;Product Collection Title;Product Collection Handle;Product Type;Product Tags;Product Discountable;Product External Id;Product Profile Name;Product Profile Type;Variant Id;Variant Title;Variant SKU;Variant Barcode;Variant Inventory Quantity;Variant Allow Backorder;Variant Manage Inventory;Variant Weight;Variant Length;Variant Width;Variant Height;Variant HS Code;Variant Origin Country;Variant MID Code;Variant Material;Price EUR;Price USD;Option 1 Name;Option 1 Value;Image 1 Url;Image 2 Url
+;coffee-mug-v2;Medusa Coffee Mug;;Every programmer's best friend.;published;https://medusa-public-images.s3.eu-west-1.amazonaws.com/coffee-mug.png;400;;;;;;;;;;;;true;;;;;One Size;;;100;false;true;;;;;;;;;1000;1200;Size;One Size;https://medusa-public-images.s3.eu-west-1.amazonaws.com/coffee-mug.png;
+;sweatpants-v2;Medusa Sweatpants;;Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.;published;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;400;;;;;;;;;;;;true;;;;;S;;;100;false;true;;;;;;;;;2950;3350;Size;S;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-back.png
+;sweatpants-v2;Medusa Sweatpants;;Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.;published;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;400;;;;;;;;;;;;true;;;;;M;;;100;false;true;;;;;;;;;2950;3350;Size;M;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-back.png
+;sweatpants-v2;Medusa Sweatpants;;Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.;published;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;400;;;;;;;;;;;;true;;;;;L;;;100;false;true;;;;;;;;;2950;3350;Size;L;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-back.png
+;sweatpants-v2;Medusa Sweatpants;;Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.;published;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;400;;;;;;;;;;;;true;;;;;XL;;;100;false;true;;;;;;;;;2950;3350;Size;XL;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png;https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-back.png
+`
+
+export const getProductImportCsvTemplate = () => {
+ return encodeURI(ProductImportCSV)
+}
diff --git a/packages/vendor/src/pages/products/import/import-summary.tsx b/packages/vendor/src/pages/products/import/import-summary.tsx
new file mode 100644
index 000000000..376c960d9
--- /dev/null
+++ b/packages/vendor/src/pages/products/import/import-summary.tsx
@@ -0,0 +1,50 @@
+import { Divider, Text } from "@medusajs/ui"
+import { HttpTypes } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+
+export const ImportSummary = ({
+ summary,
+}: {
+ summary: HttpTypes.AdminImportProductResponse["summary"]
+}) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="shadow-elevation-card-rest bg-ui-bg-component transition-fg flex flex-row rounded-md px-3 py-2">
+ <Stat
+ title={summary.toCreate.toLocaleString()}
+ description={t("products.import.upload.productsToCreate")}
+ />
+ <Divider orientation="vertical" className="h-10 px-3" />
+ <Stat
+ title={summary.toUpdate.toLocaleString()}
+ description={t("products.import.upload.productsToUpdate")}
+ />
+ </div>
+ )
+}
+
+const Stat = ({
+ title,
+ description,
+}: {
+ title: string
+ description: string
+}) => {
+ return (
+ <div className="flex flex-1 flex-col justify-center">
+ <Text size="xlarge" className="font-sans font-medium">
+ {title}
+ </Text>
+
+ <Text
+ leading="compact"
+ size="xsmall"
+ weight="plus"
+ className="text-ui-fg-subtle"
+ >
+ {description}
+ </Text>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/import/index.tsx b/packages/vendor/src/pages/products/import/index.tsx
new file mode 100644
index 000000000..03fc18f1e
--- /dev/null
+++ b/packages/vendor/src/pages/products/import/index.tsx
@@ -0,0 +1,113 @@
+// Route: /products/import
+import { Button, Heading, Text, toast } from "@medusajs/ui"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { useTranslation } from "react-i18next"
+import { useMemo, useState } from "react"
+import { useImportProducts } from "@hooks/api"
+import { UploadImport } from "./upload-import"
+import { ImportSummary } from "./import-summary"
+import { Trash } from "@medusajs/icons"
+import { FilePreview } from "@components/common/file-preview"
+import { getProductImportCsvTemplate } from "./helpers/import-template"
+
+export const Component = () => {
+ const { t } = useTranslation()
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("products.import.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("products.import.description")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <ProductImportContent />
+ </RouteDrawer>
+ )
+}
+
+const ProductImportContent = () => {
+ const { t } = useTranslation()
+ const [filename, setFilename] = useState<string>()
+
+ const { mutateAsync: importProducts, isPending, data } = useImportProducts()
+ const { handleSuccess } = useRouteModal()
+
+ const summary = useMemo(() => data?.summary, [data])
+
+ const handleUploaded = async (file: File) => {
+ setFilename(file.name)
+ await importProducts({ file })
+ }
+
+ const handleConfirm = async () => {
+ handleSuccess()
+ toast.success(t("products.import.success.title"), {
+ description: t("products.import.success.description"),
+ })
+ }
+
+ const handleClear = () => {
+ setFilename(undefined)
+ }
+
+ const csvTemplate = useMemo(() => getProductImportCsvTemplate(), [])
+
+ return (
+ <RouteDrawer.Body className="px-6 py-4">
+ {!filename && (
+ <div className="flex flex-col gap-y-4">
+ <UploadImport onUploaded={handleUploaded} />
+ <div className="bg-ui-bg-subtle flex items-center gap-x-3 rounded-xl p-4">
+ <div className="flex flex-col">
+ <Text size="small" leading="compact" weight="plus">
+ {t("products.import.template.title")}
+ </Text>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("products.import.template.description")}
+ </Text>
+ </div>
+ <div className="flex-1" />
+ <Button variant="secondary" asChild>
+ <a
+ href={`data:text/csv;charset=utf-8,${encodeURIComponent(csvTemplate)}`}
+ download="product-import-template.csv"
+ >
+ {t("actions.download")}
+ </a>
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {filename && (
+ <div className="flex flex-col gap-y-4">
+ <div className="shadow-elevation-card-rest bg-ui-bg-component rounded-xl p-4">
+ <div className="flex items-center gap-x-3">
+ <FilePreview filename={filename} loading={isPending} />
+ <div className="flex-1" />
+ <Button
+ variant="secondary"
+ onClick={handleClear}
+ disabled={isPending}
+ >
+ <Trash />
+ {t("actions.delete")}
+ </Button>
+ </div>
+ </div>
+
+ {summary && <ImportSummary summary={summary} />}
+
+ <div className="flex justify-end">
+ <Button onClick={handleConfirm} disabled={isPending}>
+ {t("actions.import")}
+ </Button>
+ </div>
+ </div>
+ )}
+ </RouteDrawer.Body>
+ )
+}
diff --git a/packages/vendor/src/pages/products/import/upload-import.tsx b/packages/vendor/src/pages/products/import/upload-import.tsx
new file mode 100644
index 000000000..ff3c86c99
--- /dev/null
+++ b/packages/vendor/src/pages/products/import/upload-import.tsx
@@ -0,0 +1,60 @@
+import { useState } from "react"
+import { FileType, FileUpload } from "@components/common/file-upload"
+import { Hint } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+const SUPPORTED_FORMATS = ["text/csv"]
+const SUPPORTED_FORMATS_FILE_EXTENSIONS = [".csv"]
+
+export const UploadImport = ({
+ onUploaded,
+}: {
+ onUploaded: (file: File) => void
+}) => {
+ const { t } = useTranslation()
+ const [error, setError] = useState<string>()
+
+ const hasInvalidFiles = (fileList: FileType[]) => {
+ const invalidFile = fileList.find(
+ (f) => !SUPPORTED_FORMATS.includes(f.file.type)
+ )
+
+ if (invalidFile) {
+ setError(
+ t("products.media.invalidFileType", {
+ name: invalidFile.file.name,
+ types: SUPPORTED_FORMATS_FILE_EXTENSIONS.join(", "),
+ })
+ )
+
+ return true
+ }
+
+ return false
+ }
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ <FileUpload
+ label={t("products.import.uploadLabel")}
+ hint={t("products.import.uploadHint")}
+ multiple={false}
+ hasError={!!error}
+ formats={SUPPORTED_FORMATS}
+ onUploaded={(files) => {
+ setError(undefined)
+ if (hasInvalidFiles(files)) {
+ return
+ }
+ onUploaded(files[0].file)
+ }}
+ />
+
+ {error && (
+ <div>
+ <Hint variant="error">{error}</Hint>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/products/index.tsx b/packages/vendor/src/pages/products/index.tsx
new file mode 100644
index 000000000..c0fcf55af
--- /dev/null
+++ b/packages/vendor/src/pages/products/index.tsx
@@ -0,0 +1,54 @@
+// Route: /products
+import { QueryClient } from "@tanstack/react-query"
+import { HttpTypes } from "@medusajs/types"
+import { productsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ProductListTable, PAGE_SIZE } from "./_components/product-list-table"
+
+// Loader for pre-fetching data
+const productsListQuery = () => ({
+ queryKey: productsQueryKeys.list({
+ limit: PAGE_SIZE,
+ offset: 0,
+ }),
+ queryFn: async () =>
+ fetchQuery("/vendor/products", {
+ method: "GET",
+ query: {
+ limit: PAGE_SIZE,
+ offset: 0,
+ fields: "+thumbnail,*categories,+status",
+ },
+ }),
+})
+
+export const loader = (client: QueryClient) => {
+ return async () => {
+ const query = productsListQuery()
+
+ return (
+ queryClient.getQueryData<HttpTypes.AdminProductListResponse>(
+ query.queryKey
+ ) ?? (await client.fetchQuery(query))
+ )
+ }
+}
+
+// Main component
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product.list.after"),
+ before: getWidgets("product.list.before"),
+ }}
+ >
+ <ProductListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/campaign-section.tsx b/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/campaign-section.tsx
new file mode 100644
index 000000000..55a5f0f5c
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/campaign-section.tsx
@@ -0,0 +1,92 @@
+import { ArrowUpRightOnBox, PencilSquare } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { DateRangeDisplay } from "@components/common/date-range-display"
+import { NoRecords } from "@components/common/empty-table-content"
+
+const CampaignDetailSection = ({
+ campaign,
+}: {
+ campaign: HttpTypes.AdminCampaign
+}) => {
+ return (
+ <div className="flex flex-col gap-y-3">
+ <div className="text-ui-fg-muted flex items-center gap-x-1.5">
+ <Text size="small" weight="plus" className="text-ui-fg-base">
+ {campaign.name}
+ </Text>
+ <Text size="small" weight="plus">
+ ·
+ </Text>
+ <Text size="small" weight="plus">
+ {campaign.campaign_identifier}
+ </Text>
+ </div>
+ <DateRangeDisplay
+ startsAt={campaign.starts_at}
+ endsAt={campaign.ends_at}
+ showTime
+ />
+ </div>
+ )
+}
+
+export const CampaignSection = ({
+ campaign,
+}: {
+ campaign: HttpTypes.AdminCampaign | null
+}) => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+
+ const actions = [
+ {
+ label: t("actions.edit"),
+ to: "add-to-campaign",
+ icon: <PencilSquare />,
+ },
+ ]
+
+ if (campaign) {
+ actions.unshift({
+ label: t("promotions.campaign.actions.goToCampaign"),
+ to: `/campaigns/${campaign.id}`,
+ icon: <ArrowUpRightOnBox />,
+ })
+ }
+
+ return (
+ <Container>
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("promotions.fields.campaign")}</Heading>
+
+ <ActionMenu
+ groups={[
+ {
+ actions,
+ },
+ ]}
+ />
+ </div>
+
+ {campaign ? (
+ <CampaignDetailSection campaign={campaign} />
+ ) : (
+ <NoRecords
+ className="h-[180px] pt-4 text-center"
+ title="Not part of a campaign"
+ message="Add this promotion to an existing campaign"
+ action={{
+ to: `/promotions/${id}/add-to-campaign`,
+ label: "Add to Campaign",
+ }}
+ buttonVariant="transparentIconLeft"
+ />
+ )}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/index.ts b/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/index.ts
new file mode 100644
index 000000000..52b96902a
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/campaign-section/index.ts
@@ -0,0 +1 @@
+export * from "./campaign-section.tsx"
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/index.ts b/packages/vendor/src/pages/promotions/[id]/_components/index.ts
new file mode 100644
index 000000000..6c4e6f046
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/index.ts
@@ -0,0 +1,3 @@
+export * from "./campaign-section"
+export * from "./promotion-conditions-section"
+export * from "./promotion-general-section"
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/index.ts b/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/index.ts
new file mode 100644
index 000000000..260e4a4ff
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/index.ts
@@ -0,0 +1 @@
+export * from "./promotion-conditions-section"
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/promotion-conditions-section.tsx b/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/promotion-conditions-section.tsx
new file mode 100644
index 000000000..e67ff64d7
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/promotion-conditions-section/promotion-conditions-section.tsx
@@ -0,0 +1,104 @@
+import { PencilSquare } from "@medusajs/icons"
+import { Badge, Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { BadgeListSummary } from "@components/common/badge-list-summary"
+import { NoRecords } from "@components/common/empty-table-content"
+import { ExtendedPromotionRuleWithValues, FormattedPromotionRuleTypes } from "@custom-types/promotion"
+
+type RuleProps = {
+ rule: ExtendedPromotionRuleWithValues
+}
+function RuleBlock({ rule }: RuleProps) {
+ const getValuesList = (): string[] => {
+ if (rule.field_type === "number") {
+ return Array.isArray(rule.values)
+ ? rule.values.map((v) => String(v.value || v))
+ : [String(rule.values)]
+ }
+ return rule.values?.map((v) => v.label || v.value || String(v)).filter(Boolean) || []
+ }
+
+ return (
+ <div className="bg-ui-bg-subtle shadow-borders-base align-center flex justify-around rounded-md p-2">
+ <div className="text-ui-fg-subtle txt-compact-xsmall flex items-center whitespace-nowrap">
+ <Badge
+ size="2xsmall"
+ key="rule-attribute"
+ className="txt-compact-xsmall-plus tag-neutral-text mx-1 inline-block truncate"
+ >
+ {rule.attribute_label}
+ </Badge>
+
+ <span className="txt-compact-2xsmall mx-1 inline-block">
+ {rule.operator_label}
+ </span>
+
+ <BadgeListSummary
+ inline
+ className="!txt-compact-small-plus"
+ list={getValuesList()}
+ />
+ </div>
+ </div>
+ )
+}
+
+type PromotionConditionsSectionProps = {
+ rules: ExtendedPromotionRuleWithValues[]
+ ruleType: FormattedPromotionRuleTypes
+}
+
+export const PromotionConditionsSection = ({
+ rules,
+ ruleType,
+}: PromotionConditionsSectionProps) => {
+ const { t } = useTranslation()
+ const translationKey = `promotions.fields.conditions.${ruleType}.title` as const
+
+ return (
+ <Container className="p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div className="flex flex-col">
+ <Heading>
+ {t(translationKey)}
+ </Heading>
+ </div>
+
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `${ruleType}/edit`,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ <div className="text-ui-fg-subtle flex flex-col gap-2 px-6 pb-4 pt-2">
+ {!rules.length && (
+ <NoRecords
+ className="h-[180px]"
+ title={t("general.noRecordsTitle")}
+ message={t("promotions.conditions.list.noRecordsMessage")}
+ action={{
+ to: `${ruleType}/edit`,
+ label: t("promotions.conditions.add"),
+ }}
+ buttonVariant="transparentIconLeft"
+ />
+ )}
+
+ {rules.map((rule) => (
+ <RuleBlock key={`${rule.id}-${rule.attribute}`} rule={rule} />
+ ))}
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/index.ts b/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/index.ts
new file mode 100644
index 000000000..555494d37
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./promotion-general-section.tsx"
diff --git a/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/promotion-general-section.tsx b/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/promotion-general-section.tsx
new file mode 100644
index 000000000..59174ec14
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/_components/promotion-general-section/promotion-general-section.tsx
@@ -0,0 +1,176 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Badge, Container, Copy, Heading, Text, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeletePromotion } from "@hooks/api/promotions"
+import { formatCurrency } from "@lib/format-currency"
+import { formatPercentage } from "@lib/percentage-helpers"
+import { StatusCell } from "@components/table/table-cells/promotion/status-cell"
+
+type PromotionGeneralSectionProps = {
+ promotion: HttpTypes.AdminPromotion
+}
+
+function getDisplayValue(promotion: HttpTypes.AdminPromotion) {
+ const value = promotion.application_method?.value
+
+ if (!value) {
+ return null
+ }
+
+ if (promotion.application_method?.type === "fixed") {
+ const currency = promotion.application_method?.currency_code
+
+ if (!currency) {
+ return null
+ }
+
+ return formatCurrency(value, currency)
+ } else if (promotion.application_method?.type === "percentage") {
+ return formatPercentage(value)
+ }
+
+ return null
+}
+
+export const PromotionGeneralSection = ({
+ promotion,
+}: PromotionGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+ const { mutateAsync } = useDeletePromotion(promotion.id)
+
+ const handleDelete = async () => {
+ const confirm = await prompt({
+ title: t("general.areYouSure"),
+ description: t("promotions.deleteWarning", {
+ code: promotion.code,
+ }),
+ verificationInstruction: t("general.typeToConfirm"),
+ verificationText: promotion.code,
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!confirm) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ navigate("/promotions", { replace: true })
+ },
+ })
+ }
+
+ const displayValue = getDisplayValue(promotion)
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div className="flex flex-col">
+ <Heading>{promotion.code}</Heading>
+ </div>
+
+ <div className="flex items-center gap-x-2">
+ <StatusCell promotion={promotion} />
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/promotions/${promotion.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("promotions.fields.method")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty">
+ {promotion.is_automatic
+ ? t("promotions.form.method.automatic.title")
+ : t("promotions.form.method.code.title")}
+ </Text>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("fields.code")}
+ </Text>
+
+ <Copy
+ content={promotion.code!}
+ className="text-ui-tag-neutral-text"
+ asChild
+ >
+ <Badge
+ size="2xsmall"
+ rounded="full"
+ className="cursor-pointer text-pretty"
+ >
+ {promotion.code}
+ </Badge>
+ </Copy>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("promotions.fields.type")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty capitalize">
+ {promotion.type}
+ </Text>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("promotions.fields.value")}
+ </Text>
+
+ <div className="flex items-center gap-x-2">
+ <Text className="inline" size="small" leading="compact">
+ {displayValue || "-"}
+ </Text>
+ {promotion?.application_method?.type === "fixed" && (
+ <Badge size="2xsmall" rounded="full">
+ {promotion?.application_method?.currency_code?.toUpperCase()}
+ </Badge>
+ )}
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-start px-6 py-4">
+ <Text size="small" weight="plus" leading="compact">
+ {t("promotions.fields.allocation")}
+ </Text>
+
+ <Text size="small" leading="compact" className="text-pretty capitalize">
+ {promotion.application_method?.allocation!}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/add-campaign-promotion-form.tsx b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/add-campaign-promotion-form.tsx
new file mode 100644
index 000000000..dca3d01bb
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/add-campaign-promotion-form.tsx
@@ -0,0 +1,245 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { AdminCampaign, AdminPromotion } from "@medusajs/types"
+import { Button, RadioGroup, Select, Text, toast } from "@medusajs/ui"
+import { useEffect } from "react"
+import { useForm, useWatch } from "react-hook-form"
+import { Trans, useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdatePromotion } from "@hooks/api/promotions"
+import { CreateCampaignFormFields } from "../../../../campaigns/common/components/create-campaign-form-fields"
+import { CampaignDetails } from "./campaign-details"
+
+type EditPromotionFormProps = {
+ promotion: AdminPromotion
+ campaigns: AdminCampaign[]
+}
+
+const EditPromotionSchema = zod.object({
+ campaign_id: zod.string().optional().nullable(),
+ campaign_choice: zod.enum(["none", "existing"]).optional(),
+})
+
+export const AddCampaignPromotionFields = ({
+ form,
+ campaigns,
+ withNewCampaign = true,
+}: {
+ form: any
+ campaigns: AdminCampaign[]
+ withNewCampaign?: boolean
+}) => {
+ const { t } = useTranslation()
+ const watchCampaignId = useWatch({
+ control: form.control,
+ name: "campaign_id",
+ })
+
+ const watchCampaignChoice = useWatch({
+ control: form.control,
+ name: "campaign_choice",
+ })
+
+ const selectedCampaign = campaigns.find((c) => c.id === watchCampaignId)
+
+ return (
+ <div className="flex flex-col gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="campaign_choice"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("promotions.fields.campaign")}</Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ className="grid grid-cols-1 gap-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={"none"}
+ label={t("promotions.form.campaign.none.title")}
+ description={t("promotions.form.campaign.none.description")}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={"existing"}
+ label={t("promotions.form.campaign.existing.title")}
+ description={t(
+ "promotions.form.campaign.existing.description"
+ )}
+ />
+
+ {withNewCampaign && (
+ <RadioGroup.ChoiceBox
+ value={"new"}
+ label={t("promotions.form.campaign.new.title")}
+ description={t(
+ "promotions.form.campaign.new.description"
+ )}
+ />
+ )}
+ </RadioGroup>
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ {watchCampaignChoice === "existing" && (
+ <Form.Field
+ control={form.control}
+ name="campaign_id"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("promotions.form.campaign.existing.title")}
+ </Form.Label>
+
+ <Form.Control>
+ <Select onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+
+ <Select.Content>
+ {!campaigns.length && (
+ <div className="flex h-[120px] flex-col items-center justify-center gap-2 p-2">
+ <span className="txt-small text-ui-fg-subtle font-medium">
+ {t(
+ "promotions.form.campaign.existing.placeholder.title"
+ )}
+ </span>
+ <span className="txt-small text-ui-fg-muted">
+ {t(
+ "promotions.form.campaign.existing.placeholder.desc"
+ )}
+ </span>
+ </div>
+ )}
+ {campaigns.map((c) => (
+ <Select.Item key={c.id} value={c.id}>
+ {c.name?.toUpperCase()}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey="campaigns.fields.campaign_id.hint"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ {watchCampaignChoice === "new" && (
+ <CreateCampaignFormFields form={form} fieldScope="campaign." />
+ )}
+
+ <CampaignDetails campaign={selectedCampaign} />
+ </div>
+ )
+}
+
+export const AddCampaignPromotionForm = ({
+ promotion,
+ campaigns,
+}: EditPromotionFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { campaign } = promotion
+
+ const originalId = campaign?.id
+
+ const form = useForm<zod.infer<typeof EditPromotionSchema>>({
+ defaultValues: {
+ campaign_id: campaign?.id,
+ campaign_choice: campaign?.id ? "existing" : "none",
+ },
+ resolver: zodResolver(EditPromotionSchema),
+ })
+
+ const { setValue } = form
+
+ const { mutateAsync, isPending } = useUpdatePromotion(promotion.id)
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ { campaign_id: data.campaign_id },
+ {
+ onSuccess: () => {
+ toast.success(t("promotions.campaign.edit.successToast"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ const watchCampaignChoice = useWatch({
+ control: form.control,
+ name: "campaign_choice",
+ })
+
+ useEffect(() => {
+ if (watchCampaignChoice === "none") {
+ setValue("campaign_id", null)
+ }
+
+ if (watchCampaignChoice === "existing") {
+ setValue("campaign_id", originalId)
+ }
+ }, [watchCampaignChoice, setValue, originalId])
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex size-full flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="size-full overflow-auto">
+ <AddCampaignPromotionFields
+ form={form}
+ campaigns={campaigns}
+ withNewCampaign={false}
+ />
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/campaign-details.tsx b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/campaign-details.tsx
new file mode 100644
index 000000000..2a3fd306d
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/campaign-details.tsx
@@ -0,0 +1,118 @@
+import { AdminCampaign } from "@medusajs/types"
+import { Heading, Text } from "@medusajs/ui"
+import { Fragment } from "react"
+import { useTranslation } from "react-i18next"
+
+type CampaignDetailsProps = {
+ campaign?: AdminCampaign
+}
+
+export const CampaignDetails = ({ campaign }: CampaignDetailsProps) => {
+ const { t } = useTranslation()
+
+ if (!campaign) {
+ return
+ }
+
+ return (
+ <Fragment>
+ <div>
+ <Heading level="h2" className="mb-4">
+ {t("campaigns.details")}
+ </Heading>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus font-">
+ {t("campaigns.fields.identifier")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">
+ {campaign.campaign_identifier || "-"}
+ </Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">{t("fields.description")}</Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">{campaign.description || "-"}</Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">
+ {t("campaigns.fields.start_date")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">
+ {campaign.starts_at?.toString() || "-"}
+ </Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">
+ {t("campaigns.fields.end_date")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">
+ {campaign.ends_at?.toString() || "-"}
+ </Text>
+ </div>
+ </div>
+ </div>
+
+ <div>
+ <Heading level="h2" className="mb-4">
+ {t("campaigns.budget.details")}
+ </Heading>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus font-">
+ {t("campaigns.budget.fields.type")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">{campaign.budget?.type || "-"}</Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">
+ {t("campaigns.budget.fields.currency")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">
+ {campaign?.budget?.currency_code || "-"}
+ </Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">
+ {t("campaigns.budget.fields.limit")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">{campaign.budget?.limit || "-"}</Text>
+ </div>
+ </div>
+
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center py-1">
+ <Text className="txt-small-plus">
+ {t("campaigns.budget.fields.used")}
+ </Text>
+
+ <div className="flex items-center gap-1">
+ <Text className="txt-small">{campaign.budget?.used || "-"}</Text>
+ </div>
+ </div>
+ </div>
+ </Fragment>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/index.ts b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/index.ts
new file mode 100644
index 000000000..c7fb969a7
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form/index.ts
@@ -0,0 +1 @@
+export * from "./add-campaign-promotion-form"
diff --git a/packages/vendor/src/pages/promotions/[id]/add-to-campaign/index.tsx b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/index.tsx
new file mode 100644
index 000000000..b37b649c4
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/add-to-campaign/index.tsx
@@ -0,0 +1,34 @@
+// Route: /promotions/:id/add-to-campaign
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useCampaigns } from "@hooks/api/campaigns"
+import { usePromotion } from "@hooks/api/promotions"
+import { AddCampaignPromotionForm } from "./add-campaign-promotion-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+ const { promotion, isPending, isError, error } = usePromotion(id!)
+
+ let campaignQuery = {}
+ if (promotion?.application_method?.currency_code) {
+ campaignQuery = { budget: { currency_code: promotion?.application_method?.currency_code } }
+ }
+
+ const { campaigns, isPending: areCampaignsLoading, isError: isCampaignError, error: campaignError } = useCampaigns(campaignQuery)
+
+ if (isError || isCampaignError) throw error || campaignError
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("promotions.campaign.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {!isPending && !areCampaignsLoading && promotion && campaigns && (
+ <AddCampaignPromotionForm promotion={promotion} campaigns={campaigns} />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx
new file mode 100644
index 000000000..628bd6b8b
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx
@@ -0,0 +1,259 @@
+import { zodResolver } from '@hookform/resolvers/zod';
+import { AdminPromotion } from '@medusajs/types';
+import { Button, Input, RadioGroup, Text } from '@medusajs/ui';
+import { useForm } from 'react-hook-form';
+import { Trans, useTranslation } from 'react-i18next';
+import * as zod from 'zod';
+
+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"
+
+type EditPromotionFormProps = {
+ promotion: AdminPromotion;
+};
+
+const EditPromotionSchema = zod.object({
+ is_automatic: zod.string().toLowerCase(),
+ code: zod.string().min(1),
+ status: zod.enum(['active', 'inactive', 'draft']),
+ value_type: zod.enum(['fixed', 'percentage']),
+ value: zod.number(),
+ max_quantity: zod.number().min(1).optional().nullable()
+});
+
+export const EditPromotionDetailsForm = ({ promotion }: EditPromotionFormProps) => {
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+
+ const form = useForm<zod.infer<typeof EditPromotionSchema>>({
+ defaultValues: {
+ is_automatic: promotion.is_automatic!.toString(),
+ code: promotion.code,
+ status: promotion.status,
+ value: promotion.application_method!.value,
+ value_type: promotion.application_method!.type,
+ max_quantity: promotion.application_method?.max_quantity ?? 1
+ },
+ resolver: zodResolver(EditPromotionSchema)
+ });
+
+ const { mutateAsync, isPending } = useUpdatePromotion(promotion.id);
+
+ const handleSubmit = form.handleSubmit(async data => {
+ await mutateAsync(
+ {
+ is_automatic: data.is_automatic === 'true',
+ code: data.code,
+ status: data.status,
+ application_method: {
+ value: data.value,
+ max_quantity: data.max_quantity
+ }
+ },
+ {
+ onSuccess: () => {
+ handleSuccess();
+ }
+ }
+ );
+ });
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-y-auto">
+ <div className="flex flex-col gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.status.label')}</Form.Label>
+ <Form.Control>
+ <RadioGroup
+ className="flex-col gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'draft'}
+ label={t('promotions.form.status.draft.title')}
+ description={t('promotions.form.status.draft.description')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'active'}
+ label={t('promotions.form.status.active.title')}
+ description={t('promotions.form.status.active.description')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'inactive'}
+ label={t('promotions.form.status.inactive.title')}
+ description={t('promotions.form.status.inactive.description')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="is_automatic"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.method.label')}</Form.Label>
+ <Form.Control>
+ <RadioGroup
+ className="flex-col gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'false'}
+ label={t('promotions.form.method.code.title')}
+ description={t('promotions.form.method.code.description')}
+ />
+ <RadioGroup.ChoiceBox
+ value={'true'}
+ label={t('promotions.form.method.automatic.title')}
+ description={t('promotions.form.method.automatic.description')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.code.title')}</Form.Label>
+
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ </Form.Item>
+ );
+ }}
+ />
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.code.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ </div>
+
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field: { onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('fields.percentage')}</Form.Label>
+ <Form.Control>
+ <DeprecatedPercentageInput
+ key="amount"
+ min={0}
+ max={100}
+ {...field}
+ value={field.value || ''}
+ onChange={e => {
+ onChange(e.target.value === '' ? null : parseInt(e.target.value));
+ }}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ {promotion.application_method?.allocation === 'each' && (
+ <Form.Field
+ control={form.control}
+ name="max_quantity"
+ render={() => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.max_quantity.title')}</Form.Label>
+ <Form.Control>
+ <Input
+ {...form.register('max_quantity', {
+ valueAsNumber: true
+ })}
+ type="number"
+ min={1}
+ placeholder="999"
+ />
+ </Form.Control>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.max_quantity.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+ </div>
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button
+ size="small"
+ variant="secondary"
+ >
+ {t('actions.cancel')}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button
+ size="small"
+ type="submit"
+ isLoading={isPending}
+ >
+ {t('actions.save')}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ );
+};
diff --git a/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/index.ts b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/index.ts
new file mode 100644
index 000000000..94c686f95
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-promotion-details-form"
diff --git a/packages/vendor/src/pages/promotions/[id]/edit/index.tsx b/packages/vendor/src/pages/promotions/[id]/edit/index.tsx
new file mode 100644
index 000000000..6ae8b549a
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/edit/index.tsx
@@ -0,0 +1,24 @@
+// Route: /promotions/:id/edit
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { usePromotion } from "@hooks/api/promotions"
+import { EditPromotionDetailsForm } from "./edit-promotion-form"
+
+export const Component = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+ const { promotion, isLoading, isError, error } = usePromotion(id!)
+
+ if (isError) throw error
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("promotions.edit.title")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && promotion && <EditPromotionDetailsForm promotion={promotion} />}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/[id]/index.tsx b/packages/vendor/src/pages/promotions/[id]/index.tsx
new file mode 100644
index 000000000..875f8cf54
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/[id]/index.tsx
@@ -0,0 +1,75 @@
+// Route: /promotions/:id
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch, useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { usePromotion, usePromotionRules } from "@hooks/api/promotions"
+import { promotionsQueryKeys } from "@hooks/api/promotions"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+import { CampaignSection } from "./_components/campaign-section"
+import { PromotionConditionsSection } from "./_components/promotion-conditions-section"
+import { PromotionGeneralSection } from "./_components/promotion-general-section"
+
+// Loader
+const promotionDetailQuery = (id: string) => ({
+ queryKey: promotionsQueryKeys.detail(id),
+ queryFn: async () => fetchQuery(`/vendor/promotions/${id}`, { method: "GET", query: { fields: "+status" } }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ return queryClient.ensureQueryData(promotionDetailQuery(id!))
+}
+
+// Breadcrumb
+type PromotionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminPromotionResponse>
+
+export const Breadcrumb = (props: PromotionDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+ const { promotion } = usePromotion(id!, { initialData: props.data, enabled: Boolean(id) })
+ if (!promotion) return null
+ return <span>{promotion.code}</span>
+}
+
+// Main component
+export const Component = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+ const { id } = useParams()
+ const { promotion, isLoading } = usePromotion(id!, { initialData })
+ const query: Record<string, string> = {}
+ if (promotion?.type === "buyget") query.promotion_type = promotion.type
+
+ const { rules } = usePromotionRules(id!, "rules", query)
+ const { rules: targetRules } = usePromotionRules(id!, "target-rules", query)
+ const { rules: buyRules } = usePromotionRules(id!, "buy-rules", query)
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !promotion) return <TwoColumnPageSkeleton mainSections={3} sidebarSections={1} showJSON />
+
+ return (
+ <TwoColumnPage
+ data={promotion}
+ widgets={{
+ after: getWidgets("promotion.details.after"),
+ before: getWidgets("promotion.details.before"),
+ sideAfter: getWidgets("promotion.details.side.after"),
+ sideBefore: getWidgets("promotion.details.side.before"),
+ }}
+ hasOutlet
+ >
+ <TwoColumnPage.Main>
+ <PromotionGeneralSection promotion={promotion} />
+ <PromotionConditionsSection rules={rules || []} ruleType="rules" />
+ <PromotionConditionsSection rules={targetRules || []} ruleType="target-rules" />
+ {promotion.type === "buyget" && <PromotionConditionsSection rules={buyRules || []} ruleType="buy-rules" />}
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <CampaignSection campaign={promotion.campaign!} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/_components/index.ts b/packages/vendor/src/pages/promotions/_components/index.ts
new file mode 100644
index 000000000..aae0291b3
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/_components/index.ts
@@ -0,0 +1 @@
+export * from "./promotion-list-table"
diff --git a/packages/vendor/src/pages/promotions/_components/promotion-list-table/index.ts b/packages/vendor/src/pages/promotions/_components/promotion-list-table/index.ts
new file mode 100644
index 000000000..aae0291b3
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/_components/promotion-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./promotion-list-table"
diff --git a/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-table.tsx b/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-table.tsx
new file mode 100644
index 000000000..9f0e820a4
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-table.tsx
@@ -0,0 +1,168 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Container, Heading, usePrompt } from "@medusajs/ui"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link, Outlet, useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import {
+ useDeletePromotion,
+ usePromotions,
+} from "@hooks/api/promotions"
+import { usePromotionTableColumns } from "@hooks/table/columns/use-promotion-table-columns"
+import { usePromotionTableFilters } from "@hooks/table/filters/use-promotion-table-filters"
+import { usePromotionTableQuery } from "@hooks/table/query/use-promotion-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const PromotionListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = usePromotionTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const {
+ promotions: data,
+ count,
+ isLoading,
+ isError,
+ error,
+ } = usePromotions({
+ fields: "+status",
+ ...searchParams,
+ })
+
+ const promotions = data?.filter((item) => item !== null)
+
+ const filters = usePromotionTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: (promotions ?? []) as HttpTypes.AdminPromotion[],
+ columns: columns as any,
+ count,
+ enablePagination: true,
+ pageSize: PAGE_SIZE,
+ getRowId: (row) => row.id,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("promotions.domain")}</Heading>
+
+ <Button size="small" variant="secondary" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ filters={filters}
+ search
+ pagination
+ isLoading={isLoading}
+ queryObject={raw}
+ navigateTo={(row) => `${row.original.id}`}
+ orderBy={[
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ />
+ <Outlet />
+ </Container>
+ )
+}
+
+const PromotionActions = ({ promotion }: { promotion: HttpTypes.AdminPromotion }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+ const { mutateAsync } = useDeletePromotion(promotion.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("promotions.deleteWarning", {
+ code: promotion.code!,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ verificationInstruction: t("general.typeToConfirm"),
+ verificationText: promotion.code,
+ })
+
+ if (!res) {
+ return
+ }
+
+ try {
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ navigate("/promotions", { replace: true })
+ },
+ })
+ } catch {
+ throw new Error(
+ `Promotion with code ${promotion.code} could not be deleted`
+ )
+ }
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/promotions/${promotion.id}/edit`,
+ },
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminPromotion>()
+
+const useColumns = () => {
+ const base = usePromotionTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <PromotionActions promotion={row.original} />
+ },
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/edit-rules-form.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/edit-rules-form.tsx
new file mode 100644
index 000000000..7d3233763
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/edit-rules-form.tsx
@@ -0,0 +1,74 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes, PromotionRuleDTO } from "@medusajs/types"
+import { Button } from "@medusajs/ui"
+import { useRef, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { RouteDrawer } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { RuleTypeValues } from "../../edit-rules"
+import { RulesFormField } from "../rules-form-field"
+import { EditRules, EditRulesType } from "./form-schema"
+
+type EditPromotionFormProps = {
+ promotion: HttpTypes.AdminPromotion
+ rules: PromotionRuleDTO[]
+ ruleType: RuleTypeValues
+ handleSubmit: any
+ isSubmitting: boolean
+}
+
+export const EditRulesForm = ({
+ promotion,
+ ruleType,
+ handleSubmit,
+ isSubmitting,
+}: EditPromotionFormProps) => {
+ const { t } = useTranslation()
+ const [rulesToRemove, setRulesToRemove] = useState([])
+ const rulesToRemoveRef = useRef(rulesToRemove)
+
+ rulesToRemoveRef.current = rulesToRemove
+
+ const form = useForm<EditRulesType>({
+ defaultValues: { rules: [], type: promotion.type },
+ resolver: zodResolver(EditRules),
+ })
+
+ const handleFormSubmit = form.handleSubmit((data) => {
+ return handleSubmit(rulesToRemoveRef.current)(data)
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleFormSubmit}
+ className="flex flex-col overflow-hidden h-full"
+ >
+ <RouteDrawer.Body className="flex-1 overflow-y-auto">
+ <RulesFormField
+ form={form as any}
+ ruleType={ruleType}
+ setRulesToRemove={setRulesToRemove}
+ rulesToRemove={rulesToRemove}
+ promotion={promotion}
+ />
+ </RouteDrawer.Body>
+
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary" disabled={isSubmitting}>
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+
+ <Button size="small" type="submit" isLoading={isSubmitting}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/form-schema.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/form-schema.ts
new file mode 100644
index 000000000..23369e686
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/form-schema.ts
@@ -0,0 +1,32 @@
+import i18n from "i18next"
+import { z } from "zod"
+
+export const EditRules = z.object({
+ type: z.string().optional(),
+ rules: z.array(
+ z.object({
+ id: z.string().optional(),
+ attribute: z
+ .string()
+ .min(1, { message: i18n.t("promotions.form.required") }),
+ operator: z.preprocess(
+ (val) => (val === "" ? undefined : val),
+ z.enum(["gt", "lt", "eq", "ne", "in", "lte", "gte"], {
+ required_error: i18n.t("promotions.form.required"),
+ invalid_type_error: i18n.t("promotions.form.required"),
+ })
+ ),
+ values: z.union([
+ z.string().min(1, { message: i18n.t("promotions.form.required") }),
+ z
+ .array(z.string())
+ .min(1, { message: i18n.t("promotions.form.required") }),
+ ]),
+ required: z.boolean().optional(),
+ disguised: z.boolean().optional(),
+ field_type: z.string().optional(),
+ })
+ ),
+})
+
+export type EditRulesType = z.infer<typeof EditRules>
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/index.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/index.ts
new file mode 100644
index 000000000..b3e299840
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/index.ts
@@ -0,0 +1 @@
+export * from "./edit-rules-form"
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/utils.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/utils.ts
new file mode 100644
index 000000000..c69faf615
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-form/utils.ts
@@ -0,0 +1,34 @@
+import {
+ ExtendedPromotionRule,
+ PromotionRuleFormData,
+} from "@custom-types/promotion"
+
+export const generateRuleAttributes = (
+ rules?: ExtendedPromotionRule[]
+): PromotionRuleFormData[] =>
+ (rules || []).map((rule): PromotionRuleFormData => {
+ let values: string | string[]
+ const firstValue = Array.isArray(rule.values)
+ ? rule.values[0]?.value
+ : rule.values
+
+ if (rule.field_type === "number") {
+ values = firstValue ? String(firstValue) : ""
+ } else if (rule.operator === "eq") {
+ values = firstValue ? String(firstValue) : ""
+ } else {
+ values = Array.isArray(rule.values)
+ ? rule.values.map((v) => String(v.value || "")).filter(Boolean)
+ : []
+ }
+
+ return {
+ id: rule.id,
+ required: rule.required,
+ field_type: rule.field_type,
+ disguised: rule.disguised,
+ attribute: rule.attribute || "",
+ operator: rule.operator || "",
+ values,
+ }
+ })
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx
new file mode 100644
index 000000000..5f5ee1e52
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx
@@ -0,0 +1,156 @@
+import {
+ CreatePromotionRuleDTO,
+ HttpTypes,
+ PromotionRuleDTO,
+} from "@medusajs/types"
+import { useRouteModal } from "@components/modals"
+import {
+ usePromotionAddRules,
+ usePromotionRemoveRules,
+ usePromotionUpdateRules,
+ useUpdatePromotion,
+} from "@hooks/api/promotions"
+import { RuleTypeValues } from "../../edit-rules"
+import { EditRulesForm } from "../edit-rules-form"
+import { EditRulesType } from "../edit-rules-form/form-schema"
+
+type EditPromotionFormProps = {
+ promotion: HttpTypes.AdminPromotion
+ rules: PromotionRuleDTO[]
+ ruleType: RuleTypeValues
+}
+
+export const EditRulesWrapper = ({
+ promotion,
+ rules,
+ ruleType,
+}: EditPromotionFormProps) => {
+ const { handleSuccess } = useRouteModal()
+ const { mutateAsync: updatePromotion } = useUpdatePromotion(promotion.id)
+ const { mutateAsync: addPromotionRules } = usePromotionAddRules(
+ promotion.id,
+ ruleType
+ )
+
+ const { mutateAsync: removePromotionRules } = usePromotionRemoveRules(
+ promotion.id,
+ ruleType
+ )
+
+ const { mutateAsync: updatePromotionRules, isPending } =
+ usePromotionUpdateRules(promotion.id, ruleType)
+
+ const handleSubmit = (
+ rulesToRemove?: { id: string; disguised?: boolean; attribute: string }[]
+ ) => {
+ return async function (data: EditRulesType) {
+ const applicationMethodData: Record<string, string | number | null> = {}
+ const { rules: allRules = [] } = data
+ const disguisedRules = allRules.filter((rule) => rule.disguised)
+ const disguisedRulesToRemove =
+ rulesToRemove?.filter((r) => r.disguised) || []
+
+ for (const rule of disguisedRules) {
+ const value = Array.isArray(rule.values)
+ ? rule.values[0] || null
+ : rule.values || null
+
+ applicationMethodData[rule.attribute!] =
+ rule.field_type === "number" && value ? Number(value) : value
+ }
+
+ for (const rule of disguisedRulesToRemove) {
+ applicationMethodData[rule.attribute] = null
+ }
+
+ const rulesData = allRules.filter((rule) => !rule.disguised)
+
+ const rulesToCreate: CreatePromotionRuleDTO[] = []
+ const rulesToUpdate: EditRulesType["rules"] = []
+
+ for (const rule of rulesData) {
+ if ("id" in rule && typeof rule.id === "string") {
+ rulesToUpdate.push(rule)
+ } else {
+ const createRule: CreatePromotionRuleDTO = {
+ attribute: rule.attribute!,
+ operator: rule.operator,
+ values: rule.values,
+ }
+ rulesToCreate.push(createRule)
+ }
+ }
+
+ if (Object.keys(applicationMethodData).length) {
+ await updatePromotion({
+ application_method: applicationMethodData,
+ })
+ }
+
+ if (rulesToCreate.length > 0) {
+ const rulesToUpdateIds = rulesToUpdate
+ .map((r) => r.id)
+ .filter((id): id is string => Boolean(id))
+ if (rulesToUpdateIds.length > 0) {
+ await removePromotionRules({
+ rules: rulesToUpdateIds,
+ })
+ }
+
+ if (rulesToRemove?.length) {
+ const removeIds = rulesToRemove
+ .map((r) => r.id)
+ .filter((id): id is string => Boolean(id))
+ await removePromotionRules({
+ rules: removeIds,
+ })
+ }
+
+ const allRulesToAdd = [
+ ...rulesToCreate,
+ ...rulesToUpdate.map((rule) => ({
+ attribute: rule.attribute!,
+ operator: rule.operator,
+ values: rule.values,
+ })),
+ ]
+ await addPromotionRules({
+ rules: allRulesToAdd,
+ })
+ } else {
+ if (rulesToRemove?.length) {
+ const removeIds = rulesToRemove
+ .map((r) => r.id)
+ .filter((id): id is string => Boolean(id))
+ await removePromotionRules({
+ rules: removeIds,
+ })
+ }
+
+ if (rulesToUpdate.length) {
+ const updateRules = rulesToUpdate.map((rule) => ({
+ id: rule.id!,
+ attribute: rule.attribute,
+ operator: rule.operator,
+ values: rule.values,
+ }))
+ await updatePromotionRules({
+ rules: updateRules,
+ })
+ }
+ }
+
+ handleSuccess()
+ }
+ }
+
+ return (
+ <EditRulesForm
+ promotion={promotion}
+ rules={rules}
+ ruleType={ruleType}
+ handleSubmit={handleSubmit}
+ isSubmitting={isPending}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/index.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/index.ts
new file mode 100644
index 000000000..f8a67aac9
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/index.ts
@@ -0,0 +1 @@
+export * from "./edit-rules-wrapper"
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/utils.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/utils.ts
new file mode 100644
index 000000000..3b9742472
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/utils.ts
@@ -0,0 +1,9 @@
+import { ExtendedPromotionRule } from "@custom-types/promotion"
+
+export const getRuleValue = (rule: ExtendedPromotionRule) => {
+ if (rule.field_type === "number") {
+ return parseInt(rule.values as unknown as string)
+ }
+
+ return rule.values
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/index.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/index.ts
new file mode 100644
index 000000000..c05c1d5be
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/index.ts
@@ -0,0 +1 @@
+export * from "./rule-value-form-field"
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
new file mode 100644
index 000000000..dc63bc276
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rule-value-form-field/rule-value-form-field.tsx
@@ -0,0 +1,186 @@
+import { HttpTypes } from '@medusajs/types';
+import { Input, Select } from '@medusajs/ui';
+import { useWatch } from 'react-hook-form';
+
+import { Form } from '../../../../../../components/common/form';
+import { Combobox } from '../../../../../../components/inputs/combobox';
+import { usePromotionRuleValues } from '../../../../../../hooks/api/promotions';
+import { useStore } from '../../../../../../hooks/api/store';
+import { useEffect } from 'react';
+
+type RuleValueFormFieldType = {
+ form: any;
+ identifier: string;
+ scope: 'application_method.buy_rules' | 'rules' | 'application_method.target_rules';
+ name: string;
+ operator: string;
+ fieldRule: any;
+ attributes: HttpTypes.AdminRuleAttributeOption[];
+ ruleType: 'rules' | 'target-rules' | 'buy-rules';
+};
+
+const buildFilters = (attribute?: string, store?: HttpTypes.AdminStore) => {
+ if (!attribute || !store) {
+ return {};
+ }
+
+ if (attribute === 'currency_code') {
+ return {
+ value: store.supported_currencies?.map(c => c.currency_code)
+ };
+ }
+
+ return {};
+};
+
+export const RuleValueFormField = ({
+ form,
+ identifier,
+ scope,
+ name,
+ operator,
+ fieldRule,
+ attributes,
+ ruleType
+}: RuleValueFormFieldType) => {
+ const attribute = attributes?.find(attr => attr.value === fieldRule.attribute);
+
+ const { store, isLoading: isStoreLoading } = useStore();
+
+ const promotionType = useWatch({
+ control: form.control,
+ name: 'type'
+ });
+
+ const applicationMethodType = useWatch({
+ control: form.control,
+ name: 'application_method.type'
+ });
+
+ const watchOperator = useWatch({
+ control: form.control,
+ name: operator
+ });
+
+ useEffect(() => {
+ const hasDirtyRules = Object.keys(form.formState.dirtyFields).length > 0;
+
+ if (!hasDirtyRules) {
+ return;
+ }
+
+ if (watchOperator === "eq") {
+ form.setValue(name, "");
+ } else {
+ form.setValue(name, []);
+ }
+ }, [watchOperator]);
+
+ const { values: options = [] } = usePromotionRuleValues(
+ ruleType,
+ attribute?.id!,
+ {
+ ...buildFilters(attribute?.id, store),
+ promotion_type: promotionType,
+ application_method_type: applicationMethodType
+ },
+ {
+ enabled:
+ !!attribute?.id &&
+ ['select', 'multiselect'].includes(attribute.field_type) &&
+ !isStoreLoading
+ }
+ );
+
+ return (
+ <Form.Field
+ key={`${identifier}.${scope}.${name}-${fieldRule.attribute}`}
+ name={name}
+ render={({ field: { onChange, ref, ...field } }) => {
+ if (attribute?.field_type === 'number') {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Control>
+ <Input
+ {...field}
+ type="number"
+ onChange={onChange}
+ className="bg-ui-bg-base"
+ ref={ref}
+ min={1}
+ disabled={!fieldRule.attribute}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ } else if (attribute?.field_type === 'text') {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Control>
+ <Input
+ {...field}
+ ref={ref}
+ onChange={onChange}
+ className="bg-ui-bg-base"
+ disabled={!fieldRule.attribute}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ } else if (watchOperator === 'eq') {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Control>
+ <Select
+ {...field}
+ value={Array.isArray(field.value) ? field.value[0] : field.value}
+ onValueChange={onChange}
+ disabled={!fieldRule.attribute}
+ >
+ <Select.Trigger
+ ref={ref}
+ className="bg-ui-bg-base"
+ >
+ <Select.Value placeholder="Select Value" />
+ </Select.Trigger>
+
+ <Select.Content>
+ {options?.map((option, i) => (
+ <Select.Item
+ key={`${identifier}-value-option-${i}`}
+ value={option.value}
+ >
+ <span className="text-ui-fg-subtle">{option.label}</span>
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ } else {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Control>
+ <Combobox
+ {...field}
+ ref={ref}
+ placeholder="Select Values"
+ options={options}
+ onChange={onChange}
+ className="bg-ui-bg-base"
+ disabled={!fieldRule.attribute}
+ />
+ </Form.Control>
+
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }
+ }}
+ />
+ );
+};
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
new file mode 100644
index 000000000..d63a53120
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/constants.ts
@@ -0,0 +1,13 @@
+import { ExtendedPromotionRule } from "@custom-types/promotion"
+
+export const requiredProductRule: ExtendedPromotionRule = {
+ id: "product",
+ attribute: "items.product.id",
+ attribute_label: "Product",
+ operator: "eq",
+ operator_label: "Equal",
+ values: [],
+ required: true,
+ field_type: "select",
+ disguised: false,
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/index.ts b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/index.ts
new file mode 100644
index 000000000..4b6b90c58
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/index.ts
@@ -0,0 +1 @@
+export * from "./rules-form-field"
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
new file mode 100644
index 000000000..49fb400d8
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/rules-form-field/rules-form-field.tsx
@@ -0,0 +1,466 @@
+import { XMarkMini } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Badge, Button, Heading, IconButton, Select, Text } from "@medusajs/ui"
+import { forwardRef, Fragment, useEffect, useRef } from "react"
+import {
+ ControllerRenderProps,
+ useFieldArray,
+ UseFormReturn,
+ useWatch,
+} from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { Form } from "@components/common/form"
+import {
+ usePromotionRuleAttributes,
+ usePromotionRules,
+} from '../../../../../../hooks/api'
+import { CreatePromotionSchemaType } from "../../../../promotion-create/components/create-promotion-form/form-schema"
+import { generateRuleAttributes } from "../edit-rules-form/utils"
+import { RuleValueFormField } from "../rule-value-form-field"
+import { requiredProductRule } from "./constants"
+
+type RulesFormFieldType = {
+ promotion?: HttpTypes.AdminPromotion
+ form: UseFormReturn<CreatePromotionSchemaType>
+ ruleType: "rules" | "target-rules" | "buy-rules"
+ setRulesToRemove?: any
+ rulesToRemove?: any
+ scope?:
+ | "application_method.buy_rules"
+ | "rules"
+ | "application_method.target_rules"
+}
+
+export const RulesFormField = ({
+ form,
+ ruleType,
+ setRulesToRemove,
+ scope = "rules",
+ promotion,
+}: RulesFormFieldType) => {
+ const { t } = useTranslation()
+ const formData = form.getValues()
+ const { attributes } = usePromotionRuleAttributes(ruleType, formData.type)
+
+ const filteredAttributes =
+ attributes?.filter(
+ ({ id }) =>
+ id === "customer_group" || id === "country" || id === "product"
+ ) || []
+
+ const { fields, append, remove, update, replace } = useFieldArray({
+ control: form.control,
+ name: scope,
+ keyName: scope,
+ })
+
+ const promotionType = useWatch({
+ control: form.control,
+ name: "type",
+ defaultValue: promotion?.type,
+ })
+
+ const applicationMethodType = useWatch({
+ control: form.control,
+ name: "application_method.type",
+ defaultValue: promotion?.application_method?.type,
+ })
+
+ const query: Record<string, string> = promotionType
+ ? {
+ promotion_type: promotionType,
+ application_method_type: applicationMethodType,
+ }
+ : {}
+
+ const { rules, isLoading } = usePromotionRules(
+ promotion?.id!,
+ ruleType,
+ query,
+ {
+ enabled: !!promotion?.id || (!!promotionType && !!applicationMethodType),
+ }
+ )
+
+ const rulesLoadedRef = useRef(false)
+
+ useEffect(() => {
+ if (isLoading) {
+ return
+ }
+
+ if (rulesLoadedRef.current) {
+ return
+ }
+
+ if (ruleType === "rules" && !fields.length) {
+ form.resetField("rules")
+
+ const formRules = generateRuleAttributes(rules)
+ replace(formRules)
+ rulesLoadedRef.current = true
+ }
+
+ if (ruleType === "buy-rules" && !fields.length) {
+ form.resetField("application_method.buy_rules")
+ const apiRules =
+ promotion?.id || promotionType === "standard"
+ ? rules || []
+ : [...(rules || []), requiredProductRule]
+
+ const formRules = generateRuleAttributes(apiRules)
+ replace(formRules)
+ rulesLoadedRef.current = true
+ }
+
+ if (ruleType === "target-rules" && !fields.length) {
+ form.resetField("application_method.target_rules")
+ const apiRules =
+ promotion?.id || promotionType === "standard"
+ ? rules || []
+ : [...(rules || []), requiredProductRule]
+
+ const formRules = generateRuleAttributes(apiRules)
+ replace(formRules)
+ rulesLoadedRef.current = true
+ }
+ }, [
+ promotionType,
+ isLoading,
+ ruleType,
+ fields.length,
+ form,
+ replace,
+ rules,
+ promotion?.id,
+ ])
+
+ return (
+ <div className="flex flex-col">
+ <Heading level="h2" className="mb-2">
+ {t(`promotions.fields.conditions.${ruleType}.title`)}
+ </Heading>
+
+ <Text className="text-ui-fg-subtle txt-small mb-6">
+ {t(`promotions.fields.conditions.${ruleType}.description`)}
+ </Text>
+
+ {fields.map((fieldRule: any, index) => {
+ const identifier = fieldRule.id
+
+ return (
+ <Fragment key={`${fieldRule.id}.${index}.${fieldRule.attribute}`}>
+ <div className="bg-ui-bg-subtle border-ui-border-base flex flex-row gap-2 rounded-xl border px-2 py-2">
+ <div className="grow">
+ <Form.Field
+ name={`${scope}.${index}.attribute`}
+ render={({ field }) => {
+ const { onChange, ref, ...fieldProps } = field
+
+ const existingAttributes =
+ fields?.map((field: any) => field.attribute) || []
+ const attributeOptions =
+ filteredAttributes?.filter((attr) => {
+ if (attr.value === fieldRule.attribute) {
+ return true
+ }
+
+ return !existingAttributes.includes(attr.value)
+ }) || []
+
+ const disabled = !!fieldRule.required
+ const onValueChange = (e: string) => {
+ const currentAttributeOption = attributeOptions.find(
+ (ao) => ao.id === e
+ )
+
+ update(index, {
+ ...fieldRule,
+ values: [],
+ disguised: currentAttributeOption?.disguised || false,
+ })
+ onChange(e)
+ }
+
+ return (
+ <Form.Item className="mb-2">
+ {fieldRule.required && (
+ <div className="flex items-center px-2">
+ <p className="text text-ui-fg-muted txt-small">
+ {t("promotions.form.required")}
+ </p>
+ </div>
+ )}
+
+ <Form.Control>
+ {!disabled ? (
+ <Select
+ {...fieldProps}
+ onValueChange={onValueChange}
+ disabled={fieldRule.required}
+ >
+ <Select.Trigger
+ ref={ref}
+ className="bg-ui-bg-base"
+ >
+ <Select.Value
+ placeholder={t(
+ "promotions.form.selectAttribute"
+ )}
+ />
+ </Select.Trigger>
+
+ <Select.Content>
+ {attributeOptions?.map((c, i) => (
+ <Select.Item
+ key={`${identifier}-attribute-option-${i}`}
+ value={c.value}
+ >
+ <span className="text-ui-fg-subtle">
+ {c.label}
+ </span>
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ ) : (
+ <DisabledField
+ label={
+ attributeOptions?.find(
+ (ao) => ao.value === fieldRule.attribute
+ )?.label || ""
+ }
+ field={field}
+ />
+ )}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="flex gap-2">
+ <Form.Field
+ name={`${scope}.${index}.operator`}
+ render={({ field }) => {
+ const { onChange, ref, ...fieldProps } = field
+
+ const currentAttributeOption = attributes?.find(
+ (attr) => attr.value === fieldRule.attribute
+ )
+
+ const options =
+ currentAttributeOption?.operators?.map((o, idx) => ({
+ label: o.label,
+ value: o.value,
+ key: `${identifier}-operator-option-${idx}`,
+ })) || []
+
+ const disabled =
+ !!fieldRule.attribute && options?.length <= 1
+
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Control>
+ {!disabled ? (
+ <Select
+ {...fieldProps}
+ disabled={!fieldRule.attribute}
+ onValueChange={onChange}
+ >
+ <Select.Trigger
+ ref={ref}
+ className="bg-ui-bg-base"
+ >
+ <Select.Value placeholder="Select Operator" />
+ </Select.Trigger>
+
+ <Select.Content>
+ {options?.map((c) => (
+ <Select.Item key={c.key} value={c.value}>
+ <span className="text-ui-fg-subtle">
+ {c.label}
+ </span>
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ ) : (
+ <DisabledField
+ label={
+ options.find(
+ (o) => o.value === fieldProps.value
+ )?.label || ""
+ }
+ field={field}
+ />
+ )}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <RuleValueFormField
+ form={form}
+ identifier={identifier}
+ scope={scope}
+ name={`${scope}.${index}.values`}
+ operator={`${scope}.${index}.operator`}
+ fieldRule={fieldRule}
+ attributes={attributes || []}
+ ruleType={ruleType}
+ />
+ </div>
+ </div>
+
+ <div className="size-7 flex-none self-center">
+ {!fieldRule.required && (
+ <IconButton
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted"
+ type="button"
+ onClick={() => {
+ if (!fieldRule.required) {
+ if (setRulesToRemove) {
+ setRulesToRemove(
+ (
+ prev: {
+ id: string
+ disguised?: boolean
+ attribute: string
+ }[]
+ ) => {
+ if (
+ fieldRule.id &&
+ !prev.find((r) => r.id === fieldRule.id)
+ ) {
+ return [
+ ...(prev || []),
+ fieldRule as {
+ id: string
+ disguised?: boolean
+ attribute: string
+ },
+ ]
+ }
+ return prev || []
+ }
+ )
+ }
+
+ remove(index)
+ }
+ }}
+ >
+ <XMarkMini />
+ </IconButton>
+ )}
+ </div>
+ </div>
+
+ {index < fields.length - 1 && (
+ <div className="relative px-6 py-3">
+ <div className="border-ui-border-strong absolute bottom-0 left-[40px] top-0 z-[-1] w-px bg-[linear-gradient(var(--border-strong)_33%,rgba(255,255,255,0)_0%)] bg-[length:1px_3px] bg-repeat-y"></div>
+
+ <Badge size="2xsmall" className=" text-xs">
+ {t("promotions.form.and")}
+ </Badge>
+ </div>
+ )}
+ </Fragment>
+ )
+ })}
+
+ <div className={fields.length ? "mt-6" : ""}>
+ <Button
+ type="button"
+ variant="secondary"
+ className="inline-block"
+ disabled={fields.length >= filteredAttributes.length}
+ onClick={() => {
+ const newRule = {
+ attribute: "",
+ operator: "",
+ values: [],
+ required: false,
+ } as any
+ append(newRule)
+ }}
+ >
+ {t("promotions.fields.addCondition")}
+ </Button>
+
+ {!!fields.length && (
+ <Button
+ type="button"
+ variant="transparent"
+ className="text-ui-fg-muted hover:text-ui-fg-subtle ml-2 inline-block"
+ onClick={() => {
+ const indicesToRemove = fields
+ .map((field: any, index) => (field.required ? null : index))
+ .filter((f) => f !== null)
+
+ setRulesToRemove &&
+ setRulesToRemove(fields.filter((field: any) => !field.required))
+ remove(indicesToRemove)
+ }}
+ >
+ {t("promotions.fields.clearAll")}
+ </Button>
+ )}
+ </div>
+ </div>
+ )
+}
+
+type DisabledAttributeProps = {
+ label: string
+ field:
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `rules.${number}.attribute`
+ >
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `rules.${number}.operator`
+ >
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `application_method.buy_rules.${number}.attribute`
+ >
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `application_method.buy_rules.${number}.operator`
+ >
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `application_method.target_rules.${number}.attribute`
+ >
+ | ControllerRenderProps<
+ CreatePromotionSchemaType,
+ `application_method.target_rules.${number}.operator`
+ >
+}
+
+/**
+ * Render this if an attribute is disabled, or
+ * if there is only one option available.
+ */
+const DisabledField = forwardRef<HTMLInputElement, DisabledAttributeProps>(
+ ({ label, field }, ref) => {
+ return (
+ <div>
+ <div className="txt-compact-small bg-ui-bg-component shadow-borders-base text-ui-fg-base h-8 rounded-md px-2 py-1.5">
+ {label}
+ </div>
+ <input {...field} ref={ref} disabled hidden />
+ </div>
+ )
+ }
+)
+
+DisabledField.displayName = "DisabledField"
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/edit-rules.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/edit-rules.tsx
new file mode 100644
index 000000000..722f2a878
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/edit-rules.tsx
@@ -0,0 +1,63 @@
+import { PromotionRuleDTO } from "@medusajs/types"
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { usePromotion } from "@hooks/api/promotions"
+import { EditRulesWrapper } from "./components/edit-rules-wrapper"
+
+export enum RuleType {
+ RULES = "rules",
+ BUY_RULES = "buy-rules",
+ TARGET_RULES = "target-rules",
+}
+export type RuleTypeValues = "rules" | "buy-rules" | "target-rules"
+
+export const EditRules = () => {
+ const params = useParams()
+ const allowedParams: string[] = [
+ RuleType.RULES,
+ RuleType.BUY_RULES,
+ RuleType.TARGET_RULES,
+ ]
+
+ if (!allowedParams.includes(params.ruleType!)) {
+ throw "invalid page"
+ }
+
+ const { t } = useTranslation()
+ const ruleType = params.ruleType as RuleTypeValues
+ const id = params.id as string
+ const rules: PromotionRuleDTO[] = []
+ const { promotion, isPending: isLoading, isError, error } = usePromotion(id)
+
+ if (promotion) {
+ if (ruleType === RuleType.RULES) {
+ rules.push(...(promotion.rules || []))
+ } else if (ruleType === RuleType.TARGET_RULES) {
+ rules.push(...(promotion?.application_method?.target_rules || []))
+ } else if (ruleType === RuleType.BUY_RULES) {
+ rules.push(...(promotion.application_method?.buy_rules || []))
+ }
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t(`promotions.edit.${ruleType}.title`)}</Heading>
+ </RouteDrawer.Header>
+
+ {!isLoading && promotion && (
+ <EditRulesWrapper
+ promotion={promotion}
+ rules={rules}
+ ruleType={ruleType}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/index.ts b/packages/vendor/src/pages/promotions/common/edit-rules/index.ts
new file mode 100644
index 000000000..f90598830
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/common/edit-rules/index.ts
@@ -0,0 +1 @@
+export { EditRules as Component } from "./edit-rules"
diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/constants.ts b/packages/vendor/src/pages/promotions/create/create-promotion-form/constants.ts
new file mode 100644
index 000000000..9ba8032be
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/constants.ts
@@ -0,0 +1,11 @@
+export enum View {
+ TEMPLATE = "template",
+ PROMOTION = "promotion",
+ CAMPAIGN = "campaign",
+}
+
+export enum Tab {
+ TYPE = "type",
+ PROMOTION = "promotion",
+ CAMPAIGN = "campaign",
+}
diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx b/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx
new file mode 100644
index 000000000..45b19ec13
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx
@@ -0,0 +1,899 @@
+import { useEffect, useMemo, useState } from 'react';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import {
+ ApplicationMethodAllocationValues,
+ ApplicationMethodTargetTypeValues,
+ ApplicationMethodTypeValues,
+ PromotionRuleOperatorValues,
+ PromotionStatusValues,
+ PromotionTypeValues
+} from '@medusajs/types';
+import {
+ Alert,
+ Badge,
+ Button,
+ clx,
+ CurrencyInput,
+ Divider,
+ Heading,
+ Input,
+ ProgressStatus,
+ ProgressTabs,
+ RadioGroup,
+ Text,
+ toast
+} from '@medusajs/ui';
+import { useForm, useWatch } from 'react-hook-form';
+import { Trans, useTranslation } from 'react-i18next';
+import { z } from 'zod';
+
+import { Form } from "@components/common/form"
+import { DeprecatedPercentageInput } from "@components/inputs/percentage-input"
+import { RouteFocusModal, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCampaigns } from "@hooks/api/campaigns"
+import { useCreatePromotion } from "@hooks/api/promotions"
+import { getCurrencySymbol } from "@lib/data/currencies"
+import { DEFAULT_CAMPAIGN_VALUES } from "@pages/campaigns/common/constants"
+import { RulesFormField } from "../../common/edit-rules/components/rules-form-field"
+import { AddCampaignPromotionFields } from "@pages/promotions/[id]/add-to-campaign/add-campaign-promotion-form"
+import { Tab } from './constants';
+import { CreatePromotionSchema } from './form-schema';
+import { templates } from './templates';
+
+const defaultValues = {
+ campaign_id: undefined,
+ template_id: templates[0].id!,
+ campaign_choice: 'none' as 'none',
+ is_automatic: 'false',
+ code: '',
+ type: 'standard' as PromotionTypeValues,
+ status: 'draft' as PromotionStatusValues,
+ rules: [],
+ application_method: {
+ allocation: 'each' as ApplicationMethodAllocationValues,
+ type: 'percentage' as ApplicationMethodTypeValues,
+ target_type: 'items' as ApplicationMethodTargetTypeValues,
+ max_quantity: 1,
+ target_rules: [],
+ buy_rules: []
+ },
+ campaign: undefined
+};
+
+type TabState = Record<Tab, ProgressStatus>;
+
+export const CreatePromotionForm = () => {
+ const [tab, setTab] = useState<Tab>(Tab.TYPE);
+ const [tabState, setTabState] = useState<TabState>({
+ [Tab.TYPE]: 'in-progress',
+ [Tab.PROMOTION]: 'not-started',
+ [Tab.CAMPAIGN]: 'not-started'
+ });
+
+ const { t } = useTranslation();
+ const { handleSuccess } = useRouteModal();
+
+ const form = useForm<z.infer<typeof CreatePromotionSchema>>({
+ defaultValues,
+ resolver: zodResolver(CreatePromotionSchema)
+ });
+ const { setValue, reset, getValues } = form;
+
+ const { mutateAsync: createPromotion } = useCreatePromotion();
+
+ const handleSubmit = form.handleSubmit(
+ async data => {
+ if (data.campaign_choice === 'existing' && !data.campaign_id) {
+ form.setError('campaign_id', { message: t('promotions.errors.requiredField') });
+ return;
+ }
+
+ const {
+ campaign_choice: _campaignChoice,
+ is_automatic,
+ template_id: _templateId,
+ application_method,
+ rules,
+ status,
+ ...promotionData
+ } = data;
+ const {
+ target_rules: targetRulesData = [],
+ buy_rules: buyRulesData = [],
+ ...applicationMethodData
+ } = application_method;
+
+ const disguisedRules = [
+ ...targetRulesData.filter(r => !!r.disguised),
+ ...buyRulesData.filter(r => !!r.disguised),
+ ...rules.filter(r => !!r.disguised)
+ ];
+
+ const applicationMethodRuleData: Record<any, any> = {};
+
+ for (const rule of disguisedRules) {
+ applicationMethodRuleData[rule.attribute] =
+ rule.field_type === 'number' ? parseInt(rule.values as string) : rule.values;
+ }
+
+ const buildRulesData = (
+ rules: {
+ operator: string;
+ attribute: string;
+ values: any[] | any;
+ disguised?: boolean;
+ }[]
+ ) => {
+ return rules
+ .filter(r => !r.disguised)
+ .map(rule => ({
+ operator: rule.operator as PromotionRuleOperatorValues,
+ attribute: rule.attribute,
+ values: rule.values
+ }));
+ };
+
+ createPromotion(
+ {
+ ...promotionData,
+ rules: buildRulesData(rules),
+ status,
+ application_method: {
+ ...applicationMethodData,
+ ...applicationMethodRuleData,
+ target_rules: buildRulesData(targetRulesData),
+ type: 'percentage'
+ },
+ is_automatic: is_automatic === 'true'
+ },
+ {
+ onSuccess: ({ promotion }) => {
+ toast.success(
+ t('promotions.toasts.promotionCreateSuccess', {
+ code: promotion.code
+ })
+ );
+
+ handleSuccess(`/promotions/${promotion.id}`);
+ },
+ onError: e => {
+ toast.error(e.message);
+ }
+ }
+ );
+ },
+ async error => {
+ const { campaign: _campaign, ...rest } = error || {};
+ const errorInPromotionTab = !!Object.keys(rest || {}).length;
+
+ if (errorInPromotionTab) {
+ toast.error(t('promotions.errors.promotionTabError'));
+ }
+ }
+ );
+
+ const handleTabChange = async (tab: Tab) => {
+ switch (tab) {
+ case Tab.TYPE:
+ setTabState(prev => ({
+ ...prev,
+ [Tab.TYPE]: 'in-progress'
+ }));
+ setTab(tab);
+ break;
+ case Tab.PROMOTION:
+ setTabState(prev => ({
+ ...prev,
+ [Tab.TYPE]: 'completed',
+ [Tab.PROMOTION]: 'in-progress'
+ }));
+ setTab(tab);
+ break;
+ case Tab.CAMPAIGN: {
+ const valid = await form.trigger(['code', 'application_method.value']);
+
+ if (!valid) {
+ setTabState({
+ [Tab.TYPE]: 'completed',
+ [Tab.PROMOTION]: 'in-progress',
+ [Tab.CAMPAIGN]: 'not-started'
+ });
+ setTab(Tab.PROMOTION);
+ break;
+ }
+
+ setTabState(prev => ({
+ ...prev,
+ [Tab.PROMOTION]: 'completed',
+ [Tab.CAMPAIGN]: 'in-progress'
+ }));
+ setTab(tab);
+ break;
+ }
+ }
+ };
+
+ const handleContinue = async () => {
+ switch (tab) {
+ case Tab.TYPE:
+ handleTabChange(Tab.PROMOTION);
+ break;
+ case Tab.PROMOTION: {
+ const valid = !!form.getValues('code') && !!form.getValues('application_method.value');
+
+ if (valid) {
+ handleTabChange(Tab.CAMPAIGN);
+ }
+
+ if (!form.getValues('code')) {
+ form.setError('code', {
+ message: t('promotions.errors.requiredField')
+ });
+ }
+
+ if (!form.getValues('application_method.value')) {
+ form.setError('application_method.value', {
+ message: t('promotions.errors.requiredField')
+ });
+ }
+
+ break;
+ }
+ case Tab.CAMPAIGN:
+ break;
+ }
+ };
+
+ const watchTemplateId = useWatch({
+ control: form.control,
+ name: 'template_id'
+ });
+
+ const currentTemplate = useMemo(() => {
+ const currentTemplate = templates.find(template => template.id === watchTemplateId);
+
+ if (!currentTemplate) {
+ return;
+ }
+
+ reset({
+ ...defaultValues,
+ template_id: watchTemplateId
+ });
+
+ for (const [key, value] of Object.entries(currentTemplate.defaults)) {
+ if (typeof value === 'object') {
+ for (const [subKey, subValue] of Object.entries(value)) {
+ setValue(`application_method.${subKey}` as keyof typeof defaultValues, subValue);
+ }
+ } else {
+ setValue(key as keyof typeof defaultValues, value);
+ }
+ }
+
+ return currentTemplate;
+ }, [watchTemplateId, setValue, reset]);
+
+ const watchValueType = useWatch({
+ control: form.control,
+ name: 'application_method.type'
+ });
+
+ const isFixedValueType = watchValueType === 'fixed';
+ const watchAllocation = useWatch({
+ control: form.control,
+ name: 'application_method.allocation'
+ });
+
+ useEffect(() => {
+ if (watchAllocation === 'across') {
+ setValue('application_method.max_quantity', null);
+ }
+ }, [watchAllocation, setValue]);
+
+ const watchType = useWatch({
+ control: form.control,
+ name: 'type'
+ });
+
+ const isTypeStandard = watchType === 'standard';
+
+ const targetType = useWatch({
+ control: form.control,
+ name: 'application_method.target_type'
+ });
+
+ const isTargetTypeOrder = targetType === 'order';
+
+ const formData = form.getValues();
+ let campaignQuery: object = {};
+
+ if (isFixedValueType && formData.application_method.currency_code) {
+ campaignQuery = {
+ budget: {
+ currency_code: formData.application_method.currency_code
+ }
+ };
+ }
+
+ const { campaigns } = useCampaigns(campaignQuery);
+
+ const watchCampaignChoice = useWatch({
+ control: form.control,
+ name: 'campaign_choice'
+ });
+
+ useEffect(() => {
+ const formData = getValues();
+
+ if (watchCampaignChoice !== 'existing') {
+ setValue('campaign_id', undefined);
+ form.clearErrors('campaign_id');
+ }
+
+ if (watchCampaignChoice !== 'new') {
+ setValue('campaign', undefined);
+ }
+
+ if (watchCampaignChoice === 'new') {
+ if (!formData.campaign || !formData.campaign?.budget?.type) {
+ setValue('campaign', {
+ ...DEFAULT_CAMPAIGN_VALUES,
+ budget: {
+ ...DEFAULT_CAMPAIGN_VALUES.budget,
+ currency_code: formData.application_method.currency_code
+ }
+ });
+ }
+ }
+ }, [watchCampaignChoice, getValues, setValue]);
+
+ const watchRules = useWatch({
+ control: form.control,
+ name: 'rules'
+ });
+
+ const watchCurrencyRule = watchRules.find(rule => rule.attribute === 'currency_code');
+
+ if (watchCurrencyRule) {
+ const formData = form.getValues();
+ const currencyCode = formData.application_method.currency_code;
+ const ruleValue = watchCurrencyRule.values;
+
+ if (!Array.isArray(ruleValue) && currencyCode !== ruleValue) {
+ form.setValue('application_method.currency_code', ruleValue as string);
+ }
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col"
+ onSubmit={handleSubmit}
+ >
+ <ProgressTabs
+ value={tab}
+ onValueChange={tab => handleTabChange(tab as Tab)}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex w-full items-center justify-between gap-x-4">
+ <div className="-my-2 w-full max-w-[600px] border-l">
+ <ProgressTabs.List className="grid w-full grid-cols-3">
+ <ProgressTabs.Trigger
+ className="w-full"
+ value={Tab.TYPE}
+ status={tabState[Tab.TYPE]}
+ >
+ {t('promotions.tabs.template')}
+ </ProgressTabs.Trigger>
+
+ <ProgressTabs.Trigger
+ className="w-full"
+ value={Tab.PROMOTION}
+ status={tabState[Tab.PROMOTION]}
+ >
+ {t('promotions.tabs.details')}
+ </ProgressTabs.Trigger>
+
+ <ProgressTabs.Trigger
+ className="w-full"
+ value={Tab.CAMPAIGN}
+ status={tabState[Tab.CAMPAIGN]}
+ >
+ {t('promotions.tabs.campaign')}
+ </ProgressTabs.Trigger>
+ </ProgressTabs.List>
+ </div>
+ </div>
+ </RouteFocusModal.Header>
+
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ value={Tab.TYPE}
+ className="size-full overflow-y-auto"
+ >
+ <div className="flex size-full flex-col items-center">
+ <div className="w-full max-w-[720px] py-16">
+ <Form.Field
+ control={form.control}
+ name="template_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.fields.type')}</Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ key={'template_id'}
+ className="flex-col gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ >
+ {templates.map(template => {
+ return (
+ <RadioGroup.ChoiceBox
+ key={template.id}
+ value={template.id}
+ label={template.title}
+ description={template.description}
+ />
+ );
+ })}
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ </div>
+ </div>
+ </ProgressTabs.Content>
+
+ <ProgressTabs.Content
+ value={Tab.PROMOTION}
+ className="size-full overflow-y-auto"
+ >
+ <div className="flex size-full flex-col items-center">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 py-16">
+ <Heading
+ level="h1"
+ className="text-fg-base"
+ >
+ {t(`promotions.sections.details`)}
+
+ {currentTemplate?.title && (
+ <Badge
+ className="ml-2 align-middle"
+ color="grey"
+ size="2xsmall"
+ rounded="full"
+ >
+ {currentTemplate?.title}
+ </Badge>
+ )}
+ </Heading>
+
+ {form.formState.errors.root && (
+ <Alert
+ variant="error"
+ dismissible={false}
+ className="text-balance"
+ >
+ {form.formState.errors.root.message}
+ </Alert>
+ )}
+
+ <Form.Field
+ control={form.control}
+ name="is_automatic"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.method.label')}</Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'false'}
+ label={t('promotions.form.method.code.title')}
+ description={t('promotions.form.method.code.description')}
+ className={clx('basis-1/2')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'true'}
+ label={t('promotions.form.method.automatic.title')}
+ description={t('promotions.form.method.automatic.description')}
+ className={clx('basis-1/2')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.form.status.label')}</Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'draft'}
+ label={t('promotions.form.status.draft.title')}
+ description={t('promotions.form.status.draft.description')}
+ className={clx('basis-1/2')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'active'}
+ label={t('promotions.form.status.active.title')}
+ description={t('promotions.form.status.active.description')}
+ className={clx('basis-1/2')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ <div className="flex gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Label>{t('promotions.form.code.title')}</Form.Label>
+
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder="SUMMER15"
+ />
+ </Form.Control>
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.code.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ </Form.Item>
+ );
+ }}
+ />
+ </div>
+
+ {!currentTemplate?.hiddenFields?.includes('type') && (
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.fields.type')}</Form.Label>
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'standard'}
+ label={t('promotions.form.type.standard.title')}
+ description={t('promotions.form.type.standard.description')}
+ className={clx('basis-1/2')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'buyget'}
+ label={t('promotions.form.type.buyget.title')}
+ description={t('promotions.form.type.buyget.description')}
+ className={clx('basis-1/2')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ <Divider />
+
+ <RulesFormField
+ form={form}
+ ruleType={'rules'}
+ />
+
+ <Divider />
+
+ {!currentTemplate?.hiddenFields?.includes('application_method.type') && (
+ <Form.Field
+ control={form.control}
+ name="application_method.type"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.fields.value_type')}</Form.Label>
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'fixed'}
+ label={t('promotions.form.value_type.fixed.title')}
+ description={t('promotions.form.value_type.fixed.description')}
+ className={clx('basis-1/2')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'percentage'}
+ label={t('promotions.form.value_type.percentage.title')}
+ description={t(
+ 'promotions.form.value_type.percentage.description'
+ )}
+ className={clx('basis-1/2')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ <div className="flex gap-x-2 gap-y-4">
+ {!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;
+
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Label
+ tooltip={
+ currencyCode || !isFixedValueType
+ ? undefined
+ : t('promotions.fields.amount.tooltip')
+ }
+ >
+ {t('promotions.form.value.title')}
+ </Form.Label>
+
+ <Form.Control>
+ {isFixedValueType ? (
+ <CurrencyInput
+ {...field}
+ min={0}
+ onValueChange={value => {
+ onChange(value ? parseInt(value) : '');
+ }}
+ code={currencyCode || 'USD'}
+ symbol={currencyCode ? getCurrencySymbol(currencyCode) : '$'}
+ value={value}
+ // disabled={!currencyCode}
+ />
+ ) : (
+ <DeprecatedPercentageInput
+ key="amount"
+ className="text-right"
+ min={0}
+ max={100}
+ {...field}
+ value={value}
+ onChange={e => {
+ onChange(
+ e.target.value === '' ? null : parseInt(e.target.value)
+ );
+ }}
+ />
+ )}
+ </Form.Control>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey={
+ isFixedValueType
+ ? 'promotions.form.value_type.fixed.description'
+ : 'promotions.form.value_type.percentage.description'
+ }
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ {isTypeStandard && watchAllocation === 'each' && (
+ <Form.Field
+ control={form.control}
+ name="application_method.max_quantity"
+ render={() => {
+ return (
+ <Form.Item className="basis-1/2">
+ <Form.Label>{t('promotions.form.max_quantity.title')}</Form.Label>
+
+ <Form.Control>
+ <Input
+ {...form.register('application_method.max_quantity', {
+ valueAsNumber: true
+ })}
+ type="number"
+ min={1}
+ placeholder="3"
+ />
+ </Form.Control>
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.max_quantity.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+ </div>
+
+ {isTypeStandard &&
+ !currentTemplate?.hiddenFields?.includes('application_method.allocation') && (
+ <Form.Field
+ control={form.control}
+ name="application_method.allocation"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t('promotions.fields.allocation')}</Form.Label>
+
+ <Form.Control>
+ <RadioGroup
+ className="flex gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ value={'each'}
+ label={t('promotions.form.allocation.each.title')}
+ description={t('promotions.form.allocation.each.description')}
+ className={clx('basis-1/2')}
+ />
+
+ <RadioGroup.ChoiceBox
+ value={'across'}
+ label={t('promotions.form.allocation.across.title')}
+ description={t('promotions.form.allocation.across.description')}
+ className={clx('basis-1/2')}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ )}
+
+ {!isTypeStandard && (
+ <>
+ <RulesFormField
+ form={form}
+ ruleType={'buy-rules'}
+ scope="application_method.buy_rules"
+ />
+ </>
+ )}
+
+ {!isTargetTypeOrder && (
+ <>
+ <Divider />
+ <RulesFormField
+ form={form}
+ ruleType={'target-rules'}
+ scope="application_method.target_rules"
+ />
+ </>
+ )}
+ </div>
+ </div>
+ </ProgressTabs.Content>
+
+ <ProgressTabs.Content
+ value={Tab.CAMPAIGN}
+ className="size-full overflow-auto"
+ >
+ <div className="flex flex-col items-center">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 py-16">
+ <AddCampaignPromotionFields
+ form={form}
+ campaigns={campaigns || []}
+ />
+ </div>
+ </div>
+ </ProgressTabs.Content>
+ </RouteFocusModal.Body>
+ </ProgressTabs>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button
+ variant="secondary"
+ size="small"
+ >
+ {t('actions.cancel')}
+ </Button>
+ </RouteFocusModal.Close>
+
+ {tab === Tab.CAMPAIGN ? (
+ <Button
+ key="save-btn"
+ type="submit"
+ size="small"
+ isLoading={false}
+ >
+ {t('actions.save')}
+ </Button>
+ ) : (
+ <Button
+ key="continue-btn"
+ type="button"
+ onClick={handleContinue}
+ size="small"
+ >
+ {t('actions.continue')}
+ </Button>
+ )}
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ );
+};
diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts b/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts
new file mode 100644
index 000000000..e6f096c2c
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts
@@ -0,0 +1,65 @@
+import { z } from "zod"
+import { CreateCampaignSchema } from "@pages/campaigns/create/create-campaign-form/create-campaign-form"
+
+const RuleSchema = z.array(
+ z.object({
+ id: z.string().optional(),
+ attribute: z.string().min(1, { message: "Required field" }),
+ operator: z.preprocess(
+ (val) => (val === "" ? undefined : val),
+ z.enum(["gt", "lt", "eq", "ne", "in", "lte", "gte"], {
+ required_error: "Required field",
+ invalid_type_error: "Required field",
+ })
+ ),
+ values: z.union([
+ z.number().min(1, { message: "Required field" }),
+ z.string().min(1, { message: "Required field" }),
+ z.array(z.string()).min(1, { message: "Required field" }),
+ ]),
+ required: z.boolean().optional(),
+ disguised: z.boolean().optional(),
+ field_type: z.string().optional(),
+ })
+)
+
+export const CreatePromotionSchema = z
+ .object({
+ template_id: z.string().optional(),
+ campaign_id: z.string().optional(),
+ campaign_choice: z.enum(["none", "existing", "new"]).optional(),
+ is_automatic: z.string().toLowerCase(),
+ code: z.string().min(1),
+ type: z.enum(["buyget", "standard"]),
+ status: z.enum(["draft", "active", "inactive"]),
+ rules: RuleSchema,
+ application_method: z.object({
+ allocation: z.enum(["each", "across"]),
+ value: z.number().min(0),
+ currency_code: z.string().optional(),
+ max_quantity: z.number().optional().nullable(),
+ target_rules: RuleSchema,
+ buy_rules: RuleSchema,
+ type: z.enum(["fixed", "percentage"]),
+ target_type: z.enum(["order", "shipping_methods", "items"]),
+ }),
+ campaign: CreateCampaignSchema.optional(),
+ })
+ .refine(
+ (data) => {
+ if (data.application_method.allocation === "across") {
+ return true
+ }
+
+ return (
+ data.application_method.allocation === "each" &&
+ typeof data.application_method.max_quantity === "number"
+ )
+ },
+ {
+ path: ["application_method.max_quantity"],
+ message: `required field`,
+ }
+ )
+
+export type CreatePromotionSchemaType = z.infer<typeof CreatePromotionSchema>
diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/index.ts b/packages/vendor/src/pages/promotions/create/create-promotion-form/index.ts
new file mode 100644
index 000000000..be0d550e0
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/index.ts
@@ -0,0 +1 @@
+export * from "./create-promotion-form"
diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/templates.ts b/packages/vendor/src/pages/promotions/create/create-promotion-form/templates.ts
new file mode 100644
index 000000000..f31dc87a4
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/templates.ts
@@ -0,0 +1,89 @@
+const commonHiddenFields = [
+ "type",
+ "application_method.type",
+ "application_method.allocation",
+]
+
+export const templates = [
+ // {
+ // id: "amount_off_products",
+ // type: "standard",
+ // title: "Amount off products",
+ // description: "Discount specific products or collection of products",
+ // hiddenFields: [...commonHiddenFields],
+ // defaults: {
+ // is_automatic: "false",
+ // type: "standard",
+ // application_method: {
+ // allocation: "each",
+ // target_type: "items",
+ // type: "fixed",
+ // },
+ // },
+ // },
+ // {
+ // id: "amount_off_order",
+ // type: "standard",
+ // title: "Amount off order",
+ // description: "Discounts the total order amount",
+ // hiddenFields: [...commonHiddenFields],
+ // defaults: {
+ // is_automatic: "false",
+ // type: "standard",
+ // application_method: {
+ // allocation: "across",
+ // target_type: "order",
+ // type: "fixed",
+ // },
+ // },
+ // },
+ {
+ id: "percentage_off_product",
+ type: "standard",
+ title: "Percentage off product",
+ description: "Discounts a percentage off selected products",
+ hiddenFields: [...commonHiddenFields],
+ defaults: {
+ is_automatic: "false",
+ type: "standard",
+ application_method: {
+ allocation: "each",
+ target_type: "items",
+ type: "percentage",
+ },
+ },
+ },
+ // {
+ // id: "percentage_off_order",
+ // type: "standard",
+ // title: "Percentage off order",
+ // description: "Discounts a percentage of the total order amount",
+ // hiddenFields: [...commonHiddenFields],
+ // defaults: {
+ // is_automatic: "false",
+ // type: "standard",
+ // application_method: {
+ // allocation: "across",
+ // target_type: "order",
+ // type: "percentage",
+ // },
+ // },
+ // },
+ // {
+ // id: "buy_get",
+ // type: "buy_get",
+ // title: "Buy X Get Y",
+ // description: "Buy X product(s), get Y product(s)",
+ // hiddenFields: [...commonHiddenFields, "application_method.value"],
+ // defaults: {
+ // is_automatic: "false",
+ // type: "buyget",
+ // application_method: {
+ // type: "percentage",
+ // value: 100,
+ // apply_to_quantity: 1,
+ // max_quantity: 1,
+ // },
+ // },
+ // },
+]
diff --git a/packages/vendor/src/pages/promotions/create/index.tsx b/packages/vendor/src/pages/promotions/create/index.tsx
new file mode 100644
index 000000000..4bc3a0593
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/create/index.tsx
@@ -0,0 +1,11 @@
+// Route: /promotions/create
+import { RouteFocusModal } from "@components/modals"
+import { CreatePromotionForm } from "./create-promotion-form/create-promotion-form"
+
+export const Component = () => {
+ return (
+ <RouteFocusModal>
+ <CreatePromotionForm />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/promotions/index.tsx b/packages/vendor/src/pages/promotions/index.tsx
new file mode 100644
index 000000000..c6b930056
--- /dev/null
+++ b/packages/vendor/src/pages/promotions/index.tsx
@@ -0,0 +1,19 @@
+// Route: /promotions
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { PromotionListTable } from "./_components/promotion-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("promotion.list.before"),
+ after: getWidgets("promotion.list.after"),
+ }}
+ >
+ <PromotionListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/register/index.ts b/packages/vendor/src/pages/register/index.ts
new file mode 100644
index 000000000..8952c795d
--- /dev/null
+++ b/packages/vendor/src/pages/register/index.ts
@@ -0,0 +1 @@
+export { Register as Component } from "./register"
diff --git a/packages/vendor/src/pages/register/password-hints.tsx b/packages/vendor/src/pages/register/password-hints.tsx
new file mode 100644
index 000000000..0e0133f8b
--- /dev/null
+++ b/packages/vendor/src/pages/register/password-hints.tsx
@@ -0,0 +1,92 @@
+import { useEffect, useMemo, type FC } from 'react';
+
+import { CheckCircleMiniSolid } from '@medusajs/icons';
+import { Container } from '@medusajs/ui';
+import { useTranslation } from 'react-i18next';
+
+function validatePassword(password: string) {
+ const errors = {
+ tooShort: password.length < 12,
+ noLower: !/[a-z]/.test(password),
+ noUpper: !/[A-Z]/.test(password),
+ noDigit: !/[0-9]/.test(password),
+ noSpecialChar: !/[!@#$%^&*(),.?":{}|<>_\-+=\[\]\\\/~`]/.test(password),
+ };
+
+ return {
+ isValid: !Object.values(errors).some(Boolean),
+ errors,
+ };
+}
+
+type ValidationState = {
+ isValid: boolean;
+ lower: boolean;
+ upper: boolean;
+ '12chars': boolean;
+ digit: boolean;
+ specialChar: boolean;
+};
+
+const ruleKeys = ['12chars', 'lower', 'upper', 'digit', 'specialChar'] as const;
+type RuleKey = (typeof ruleKeys)[number];
+
+const PasswordRule: FC<{ passed: boolean; label: string }> = ({
+ passed,
+ label,
+}) => {
+ return (
+ <p
+ className={`flex items-center gap-2 text-xs ${passed ? 'text-ui-fg-subtle' : 'text-ui-fg-muted'}`}
+ >
+ <CheckCircleMiniSolid
+ className={passed ? 'text-ui-tag-green-icon' : 'text-ui-fg-disabled'}
+ />
+ {label}
+ </p>
+ );
+};
+
+export const PasswordValidator = ({
+ password,
+ setError,
+}: {
+ password: string;
+ setError: (error: ValidationState) => void;
+}) => {
+ const { t } = useTranslation();
+
+ const validation = useMemo(() => validatePassword(password), [password]);
+
+ const state: ValidationState = useMemo(
+ () => ({
+ isValid: validation.isValid,
+ lower: !validation.errors.noLower,
+ upper: !validation.errors.noUpper,
+ '12chars': !validation.errors.tooShort,
+ digit: !validation.errors.noDigit,
+ specialChar: !validation.errors.noSpecialChar,
+ }),
+ [validation]
+ );
+
+ useEffect(() => {
+ setError(state);
+ }, [state, setError]);
+
+ const ruleLabels: Record<RuleKey, string> = {
+ '12chars': t('validation.rules.12chars'),
+ lower: t('validation.rules.lower'),
+ upper: t('validation.rules.upper'),
+ digit: t('validation.rules.digit'),
+ specialChar: t('validation.rules.specialChar'),
+ };
+
+ return (
+ <Container className="flex flex-col gap-y-1 p-2">
+ {ruleKeys.map((key) => (
+ <PasswordRule key={key} passed={state[key]} label={ruleLabels[key]} />
+ ))}
+ </Container>
+ );
+};
diff --git a/packages/vendor/src/pages/register/register-schema.ts b/packages/vendor/src/pages/register/register-schema.ts
new file mode 100644
index 000000000..262ac5a09
--- /dev/null
+++ b/packages/vendor/src/pages/register/register-schema.ts
@@ -0,0 +1,16 @@
+import * as z from 'zod';
+
+export const RegisterSchema = z.object({
+ name: z.string().min(2, { message: "Name should be a string" }),
+ email: z.string().email({ message: "Invalid email" }),
+ password: z.string()
+ .min(12, { message: "at least 12 characters" })
+ .regex(/[a-z]/, { message: "at least one lowercase case" })
+ .regex(/[A-Z]/, { message: "at least one upper case" })
+ .regex(/[0-9]/, { message: "at least one digit" })
+ .regex(/[!@#$%^&*(),.?":{}|<>_\-+=\[\]\\\/~`]/, { message: "at least one special character" }),
+ confirmPassword: z.string()
+}) .refine((data) => data.password === data.confirmPassword, {
+ message: "passwords don't match",
+ path: ['confirmPassword'],
+});
\ No newline at end of file
diff --git a/packages/vendor/src/pages/register/register.tsx b/packages/vendor/src/pages/register/register.tsx
new file mode 100644
index 000000000..8ab4b97c3
--- /dev/null
+++ b/packages/vendor/src/pages/register/register.tsx
@@ -0,0 +1,259 @@
+import { useState } from 'react';
+
+import { zodResolver } from '@hookform/resolvers/zod';
+import { Alert, Button, Heading, Hint, Input, Text } from '@medusajs/ui';
+import { useForm } from 'react-hook-form';
+import { Trans, useTranslation } from 'react-i18next';
+import { Link } from 'react-router-dom';
+import * as z from 'zod';
+
+import { Form } from '@components/common/form';
+import AvatarBox from '@components/common/logo-box/avatar-box';
+import { useSignUpWithEmailPass } from '@hooks/api';
+import { PasswordValidator } from './password-hints';
+import { RegisterSchema } from './register-schema';
+
+export const Register = () => {
+ const [success, setSuccess] = useState(false);
+ const { t } = useTranslation();
+
+ const form = useForm<z.infer<typeof RegisterSchema>>({
+ resolver: zodResolver(RegisterSchema),
+ defaultValues: {
+ name: '',
+ email: '',
+ password: '',
+ confirmPassword: ''
+ }
+ });
+
+ const [passwordValidation, setPasswordValidation] = useState({
+ isValid: false,
+ lower: false,
+ upper: false,
+ '12chars': false,
+ digit: false,
+ specialChar: false,
+ });
+
+ const { mutateAsync, isPending } = useSignUpWithEmailPass();
+
+ const handleSubmit = form.handleSubmit(async ({ name, email, password, confirmPassword }) => {
+ if (!passwordValidation.isValid) {
+ return;
+ }
+ if (password !== confirmPassword) {
+ form.setError('password', {
+ type: 'manual',
+ message: "Password and Confirm Password don't match"
+ });
+ form.setError('confirmPassword', {
+ type: 'manual',
+ message: "Password and Confirm Password don't match"
+ });
+
+ return null;
+ }
+
+ await mutateAsync(
+ {
+ name,
+ email,
+ password,
+ confirmPassword
+ },
+ {
+ onError: error => {
+ const status = 'status' in error ? error.status : undefined;
+
+ if (status === 401) {
+ form.setError('email', {
+ type: 'manual',
+ message: error.message
+ });
+
+ return;
+ }
+
+ if (status === 409) {
+ form.setError('email', {
+ type: 'manual',
+ message: 'Provided email is already taken'
+ });
+
+ return;
+ }
+
+ form.setError('root.serverError', {
+ type: 'manual',
+ message: error.message
+ });
+ },
+ onSuccess: () => {
+ setSuccess(true);
+ }
+ }
+ );
+ });
+
+ const serverError = form.formState.errors?.root?.serverError?.message;
+ const validationError =
+ form.formState.errors.email?.message ||
+ form.formState.errors.password?.message ||
+ form.formState.errors.name?.message ||
+ form.formState.errors.confirmPassword?.message;
+
+ if (success)
+ return (
+ <div className="flex min-h-dvh w-dvw items-center justify-center bg-ui-bg-subtle">
+ <div className="mb-4 flex flex-col items-center">
+ <Heading>Thank You for registering!</Heading>
+ <Text
+ size="small"
+ className="mt-2 max-w-[320px] text-center text-ui-fg-subtle"
+ >
+ You may need to wait for admin authorization before logging in. A confirmation email
+ will be sent to you shortly.
+ </Text>
+
+ <Link to="/login">
+ <Button className="mt-8">Back to login page</Button>
+ </Link>
+ </div>
+ </div>
+ );
+
+ return (
+ <div className="flex min-h-dvh w-dvw items-center justify-center bg-ui-bg-subtle">
+ <div className="m-4 flex w-full max-w-[280px] flex-col items-center">
+ <AvatarBox />
+ <div className="mb-4 flex flex-col items-center">
+ <Heading>{t('register.title')}</Heading>
+ <Text
+ size="small"
+ className="text-center text-ui-fg-subtle"
+ >
+ {t('register.hint')}
+ </Text>
+ </div>
+ <div className="flex w-full flex-col gap-y-3">
+ <Form {...form}>
+ <form
+ onSubmit={handleSubmit}
+ className="flex w-full flex-col gap-y-6"
+ >
+ <div className="flex flex-col gap-y-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ {...field}
+ className="mb-2 bg-ui-bg-field-component"
+ placeholder="Company name"
+ />
+ </Form.Control>
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t('fields.email')}
+ />
+ </Form.Control>
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="password"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>{}</Form.Label>
+ <Form.Control>
+ <Input
+ type="password"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder={t('fields.password')}
+ />
+ </Form.Control>
+ </Form.Item>
+ )}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="confirmPassword"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>{}</Form.Label>
+ <Form.Control>
+ <Input
+ type="password"
+ {...field}
+ className="bg-ui-bg-field-component"
+ placeholder="Confirm Password"
+ />
+ </Form.Control>
+ </Form.Item>
+ )}
+ />
+ <PasswordValidator
+ password={form.watch('password')}
+ setError={setPasswordValidation}
+ />
+ </div>
+ {validationError && (
+ <div className="text-center">
+ <Hint
+ className="inline-flex"
+ variant={'error'}
+ >
+ {validationError}
+ </Hint>
+ </div>
+ )}
+ {serverError && (
+ <Alert
+ className="items-center bg-ui-bg-base p-2"
+ dismissible
+ variant="error"
+ >
+ {serverError}
+ </Alert>
+ )}
+ <Button
+ className="w-full"
+ type="submit"
+ isLoading={isPending}
+ >
+ Sign up
+ </Button>
+ </form>
+ </Form>
+ </div>
+ <span className="txt-small my-6 text-ui-fg-muted">
+ <Trans
+ i18nKey="register.alreadySeller"
+ components={[
+ <Link
+ to="/login"
+ className="font-medium text-ui-fg-interactive outline-none transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover"
+ />
+ ]}
+ />
+ </span>
+ </div>
+ </div>
+ );
+};
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/edit-reservation-form.tsx b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/edit-reservation-form.tsx
new file mode 100644
index 000000000..904b19cb1
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/edit-reservation-form.tsx
@@ -0,0 +1,213 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, Select, Text, Textarea, toast } from "@medusajs/ui"
+import * as zod from "zod"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateReservationItem } from "@hooks/api/reservations"
+
+type EditReservationFormProps = {
+ reservation: HttpTypes.AdminReservationResponse["reservation"]
+ locations: HttpTypes.AdminStockLocation[]
+ item: HttpTypes.AdminInventoryItemResponse["inventory_item"]
+}
+
+const EditReservationSchema = z.object({
+ location_id: z.string(),
+ description: z.string().optional(),
+ quantity: z.number().min(1),
+})
+
+const AttributeGridRow = ({
+ title,
+ value,
+}: {
+ title: string
+ value: string | number
+}) => {
+ return (
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {title}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {value}
+ </Text>
+ </div>
+ )
+}
+
+const getDefaultValues = (
+ reservation: HttpTypes.AdminReservationResponse["reservation"]
+) => {
+ return {
+ quantity: reservation.quantity,
+ location_id: reservation.location_id,
+ description: reservation.description ?? undefined,
+ }
+}
+
+export const EditReservationForm = ({
+ reservation,
+ item,
+ locations = [],
+}: EditReservationFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditReservationSchema>>({
+ defaultValues: getDefaultValues(reservation),
+ resolver: zodResolver(EditReservationSchema),
+ })
+
+ const { mutateAsync } = useUpdateReservationItem(reservation.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ mutateAsync(values as any, {
+ onSuccess: () => {
+ toast.success(t("inventory.reservation.updateSuccessToast"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ })
+
+ const reservedQuantity = form.watch("quantity")
+ const locationId = form.watch("location_id")
+
+ const level = item.location_levels!.find(
+ (level: HttpTypes.AdminInventoryLevel) => level.location_id === locationId
+ )
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="location_id"
+ render={({ field: { onChange, value, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("inventory.reservation.location")}</Form.Label>
+ <Form.Control>
+ <Select
+ value={value}
+ onValueChange={(v) => {
+ onChange(v)
+ }}
+ {...field}
+ >
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {(locations || []).map((r) => (
+ <Select.Item key={r.id} value={r.id}>
+ {r.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-4 divide-y rounded-lg border">
+ <AttributeGridRow
+ title={t("fields.title")}
+ value={item.title ?? item.sku!}
+ />
+ <AttributeGridRow title={t("fields.sku")} value={item.sku!} />
+ <AttributeGridRow
+ title={t("fields.inStock")}
+ value={level!.stocked_quantity}
+ />
+ <AttributeGridRow
+ title={t("inventory.available")}
+ value={
+ level!.stocked_quantity -
+ (level!.reserved_quantity - reservation.quantity) -
+ reservedQuantity
+ }
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="quantity"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("inventory.reservation.reservedAmount")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ min={0}
+ max={
+ (level!.available_quantity || 0) +
+ (reservation.quantity || 0)
+ }
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.description")}</Form.Label>
+ <Form.Control>
+ <Textarea {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button type="submit" size="small" isLoading={false}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/index.tsx b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/index.tsx
new file mode 100644
index 000000000..c6ec6a4c9
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/components/index.tsx
@@ -0,0 +1 @@
+export { EditReservationForm as Component } from "./edit-reservation-form"
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/edit-reservation-modal.tsx b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/edit-reservation-modal.tsx
new file mode 100644
index 000000000..39b8505cf
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/edit-reservation-modal.tsx
@@ -0,0 +1,62 @@
+import { InventoryTypes } from "@medusajs/types"
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import {
+ useInventoryItem,
+ useInventoryItemLevels,
+} from "@hooks/api/inventory"
+import { useReservationItem } from "@hooks/api/reservations"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { EditReservationForm } from "./components/edit-reservation-form"
+
+export const ReservationEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { reservation, isPending, isError, error } = useReservationItem(id!)
+ const { inventory_item: inventoryItem } = useInventoryItem(
+ reservation?.inventory_item_id!,
+ undefined,
+ {
+ enabled: !!reservation?.inventory_item_id,
+ }
+ )
+
+ const { location_levels } = useInventoryItemLevels(inventoryItem?.id!, undefined, {
+ enabled: !!inventoryItem?.id,
+ })
+
+ const { stock_locations } = useStockLocations(
+ undefined,
+ {
+ enabled: !!location_levels,
+ },
+ {
+ id: location_levels?.map(
+ (l: InventoryTypes.InventoryLevelDTO) => l.location_id
+ ),
+ }
+ )
+
+ const ready = !isPending && reservation && inventoryItem && location_levels && stock_locations
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("inventory.reservation.editItemDetails")}</Heading>
+ </RouteDrawer.Header>
+ {ready && (
+ <EditReservationForm
+ locations={stock_locations}
+ reservation={reservation}
+ item={{ ...inventoryItem, location_levels }}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/index.ts b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/index.ts
new file mode 100644
index 000000000..5622216bc
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/edit-reservation/index.ts
@@ -0,0 +1 @@
+export { ReservationEdit as Component } from "./edit-reservation-modal"
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/index.ts b/packages/vendor/src/pages/reservations/[id]/_components/index.ts
new file mode 100644
index 000000000..d11e483be
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/index.ts
@@ -0,0 +1,2 @@
+export * from "./edit-reservation"
+export * from "./reservation-general-section"
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/index.ts b/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/index.ts
new file mode 100644
index 000000000..61935f829
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/index.ts
@@ -0,0 +1 @@
+export * from "./reservation-general-section"
diff --git a/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/reservation-general-section.tsx b/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/reservation-general-section.tsx
new file mode 100644
index 000000000..ae0b302cb
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/_components/reservation-general-section/reservation-general-section.tsx
@@ -0,0 +1,82 @@
+import { AdminReservationResponse, HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { PencilSquare } from "@medusajs/icons"
+import { SectionRow } from "@components/common/section"
+import { useInventoryItem } from "@hooks/api/inventory"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { useTranslation } from "react-i18next"
+
+type ReservationGeneralSectionProps = {
+ reservation: AdminReservationResponse["reservation"]
+}
+
+export const ReservationGeneralSection = ({
+ reservation,
+}: ReservationGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const { inventory_item: inventoryItem } = useInventoryItem(
+ reservation.inventory_item_id,
+ {
+ fields: "*location_levels",
+ }
+ )
+
+ const { stock_location: location } = useStockLocation(reservation.location_id)
+
+ const locationLevel = inventoryItem?.location_levels?.find(
+ (l: HttpTypes.AdminInventoryLevel) =>
+ l.location_id === reservation.location_id
+ )
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>
+ {t("inventory.reservation.header", {
+ itemName: inventoryItem?.title ?? inventoryItem?.sku,
+ })}
+ </Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `edit`,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <SectionRow
+ title={t("inventory.reservation.lineItemId")}
+ value={reservation.line_item_id} // TODO fetch order instead + add link
+ />
+ <SectionRow
+ title={t("inventory.reservation.description")}
+ value={reservation.description}
+ />
+ <SectionRow
+ title={t("inventory.reservation.location")}
+ value={location?.name}
+ />
+ <SectionRow
+ title={t("inventory.reservation.inStockAtLocation")}
+ value={locationLevel?.stocked_quantity}
+ />
+ <SectionRow
+ title={t("inventory.reservation.availableAtLocation")}
+ value={locationLevel?.available_quantity}
+ />
+ <SectionRow
+ title={t("inventory.reservation.reservedAtLocation")}
+ value={locationLevel?.reserved_quantity}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/[id]/index.tsx b/packages/vendor/src/pages/reservations/[id]/index.tsx
new file mode 100644
index 000000000..8f0fd2642
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/index.tsx
@@ -0,0 +1,109 @@
+// Route: /reservations/:id
+import { useLoaderData, useParams, LoaderFunctionArgs } from "react-router-dom"
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useReservationItem, reservationItemsQueryKeys } from "@hooks/api/reservations"
+import { useInventoryItem } from "@hooks/api"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { ReservationGeneralSection } from "./_components/reservation-general-section"
+import { InventoryItemGeneralSection } from "../../inventory/[id]/_components/inventory-item-general-section"
+
+const reservationDetailQuery = (id: string) => ({
+ queryKey: reservationItemsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/reservations/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const loader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = reservationDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
+
+type ReservationDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminReservationResponse>
+
+export const Breadcrumb = (props: ReservationDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { reservation } = useReservationItem(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!reservation) {
+ return null
+ }
+
+ const display =
+ reservation?.inventory_item?.title ??
+ reservation?.inventory_item?.sku ??
+ reservation.id
+
+ return <span>{display}</span>
+}
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof loader>>
+
+ const { reservation, isLoading, isError, error } = useReservationItem(
+ id!,
+ undefined,
+ {
+ initialData,
+ }
+ )
+
+ // TEMP: fetch directly since the fields are not populated with reservation call
+ const { inventory_item } = useInventoryItem(
+ reservation?.inventory_item?.id!,
+ { fields: "*location_levels" }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !reservation) {
+ return (
+ <TwoColumnPageSkeleton
+ mainSections={1}
+ sidebarSections={1}
+ showJSON
+ showMetadata
+ />
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ before: getWidgets("reservation.details.before"),
+ after: getWidgets("reservation.details.after"),
+ sideBefore: getWidgets("reservation.details.side.before"),
+ sideAfter: getWidgets("reservation.details.side.after"),
+ }}
+ data={reservation}
+ >
+ <TwoColumnPage.Main>
+ <ReservationGeneralSection reservation={reservation} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ {inventory_item && (
+ <InventoryItemGeneralSection inventoryItem={inventory_item!} />
+ )}
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/[id]/metadata/index.tsx b/packages/vendor/src/pages/reservations/[id]/metadata/index.tsx
new file mode 100644
index 000000000..98bf570e5
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/[id]/metadata/index.tsx
@@ -0,0 +1,27 @@
+// Route: /reservations/:id/metadata
+import { useParams } from "react-router-dom"
+import { useReservationItem, useUpdateReservationItem } from "@hooks/api"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { RouteDrawer } from "@components/modals"
+
+export const Component = () => {
+ const { id } = useParams()
+
+ const { reservation, isPending, isError, error } = useReservationItem(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateReservationItem(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <MetadataForm
+ isPending={isPending}
+ isMutating={isMutating}
+ hook={mutateAsync}
+ metadata={reservation?.metadata}
+ />
+ </RouteDrawer>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/_components/index.ts b/packages/vendor/src/pages/reservations/_components/index.ts
new file mode 100644
index 000000000..8248f5647
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/index.ts
@@ -0,0 +1 @@
+export * from "./reservation-list-table"
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/index.ts b/packages/vendor/src/pages/reservations/_components/reservation-list-table/index.ts
new file mode 100644
index 000000000..8248f5647
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/index.ts
@@ -0,0 +1 @@
+export * from "./reservation-list-table"
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-actions.tsx b/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-actions.tsx
new file mode 100644
index 000000000..256328ce1
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-actions.tsx
@@ -0,0 +1,64 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteReservationItem } from "@hooks/api/reservations"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ExtendedReservationItem } from "../../../../inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns"
+
+export const ReservationActions = ({
+ reservation,
+}: {
+ reservation: ExtendedReservationItem
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useDeleteReservationItem(reservation.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("reservations.deleteWarning"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("inventory.reservation.deleteSuccessToast"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: `${reservation.id}/edit`,
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-list-table.tsx b/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-list-table.tsx
new file mode 100644
index 000000000..748a6db00
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/reservation-list-table.tsx
@@ -0,0 +1,68 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useReservationItems } from "@hooks/api/reservations"
+import { useDataTable } from "@hooks/use-data-table"
+import { useReservationTableColumns } from "./use-reservation-table-columns"
+import { useReservationTableFilters } from "./use-reservation-table-filters"
+import { useReservationTableQuery } from "./use-reservation-table-query"
+import { Link } from "react-router-dom"
+
+const PAGE_SIZE = 20
+
+export const ReservationListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams } = useReservationTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { reservations, count, isPending, isError, error } =
+ useReservationItems({
+ ...searchParams,
+ })
+
+ const filters = useReservationTableFilters()
+ const columns = useReservationTableColumns()
+
+ const { table } = useDataTable({
+ data: reservations || [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("reservations.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("reservations.subtitle")}
+ </Text>
+ </div>
+ <Button variant="secondary" size="small" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isPending}
+ filters={filters}
+ pagination
+ navigateTo={(row) => row.id}
+ search={false}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-columns.tsx b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-columns.tsx
new file mode 100644
index 000000000..3e103c95a
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-columns.tsx
@@ -0,0 +1,106 @@
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { DateCell } from "@components/table/table-cells/common/date-cell"
+import { PlaceholderCell } from "@components/table/table-cells/common/placeholder-cell"
+import { ReservationActions } from "./reservation-actions"
+import { ExtendedReservationItem } from "../../../../inventory/inventory-detail/components/reservations-table/use-reservation-list-table-columns"
+
+const columnHelper = createColumnHelper<ExtendedReservationItem>()
+
+export const useReservationTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("inventory_item", {
+ header: t("fields.sku"),
+ cell: ({ getValue }) => {
+ const inventoryItem = getValue()
+
+ if (!inventoryItem || !inventoryItem.sku) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{inventoryItem.sku}</span>
+ </div>
+ )
+ },
+ }),
+ /**
+ * TEMP: hide this column until a link is added
+ */
+ // columnHelper.accessor("line_item", {
+ // header: t("fields.order"),
+ // cell: ({ getValue }) => {
+ // const inventoryItem = getValue()
+ //
+ // if (!inventoryItem || !inventoryItem.order?.display_id) {
+ // return <PlaceholderCell />
+ // }
+ //
+ // return (
+ // <div className="flex size-full items-center overflow-hidden">
+ // <LinkButton to={`/orders/${inventoryItem.order.id}`}>
+ // <span className="truncate">
+ // #{inventoryItem.order.display_id}
+ // </span>
+ // </LinkButton>
+ // </div>
+ // )
+ // },
+ // }),
+ columnHelper.accessor("description", {
+ header: t("fields.description"),
+ cell: ({ getValue }) => {
+ const description = getValue()
+
+ if (!description) {
+ return <PlaceholderCell />
+ }
+
+ return (
+ <div className="flex size-full items-center overflow-hidden">
+ <span className="truncate">{description}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.accessor("created_at", {
+ header: t("fields.created"),
+ cell: ({ getValue }) => {
+ const created = getValue()
+
+ return <DateCell date={created} />
+ },
+ }),
+ columnHelper.accessor("quantity", {
+ header: () => (
+ <div className="flex size-full items-center justify-end overflow-hidden text-right">
+ <span className="truncate">{t("fields.quantity")}</span>
+ </div>
+ ),
+ cell: ({ getValue }) => {
+ const quantity = getValue()
+
+ return (
+ <div className="flex size-full items-center justify-end overflow-hidden text-right">
+ <span className="truncate">{quantity}</span>
+ </div>
+ )
+ },
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ const reservation = row.original
+
+ return <ReservationActions reservation={reservation} />
+ },
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-filters.tsx b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-filters.tsx
new file mode 100644
index 000000000..9483c993e
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-filters.tsx
@@ -0,0 +1,35 @@
+import { Filter } from "@components/table/data-table"
+import { useStockLocations } from "@hooks/api/stock-locations"
+import { useTranslation } from "react-i18next"
+
+export const useReservationTableFilters = () => {
+ const { t } = useTranslation()
+ const { stock_locations } = useStockLocations({
+ limit: 1000,
+ })
+
+ const filters: Filter[] = []
+
+ if (stock_locations) {
+ const stockLocationFilter: Filter = {
+ type: "select",
+ options: stock_locations.map((s) => ({
+ label: s.name,
+ value: s.id,
+ })),
+ key: "location_id",
+ searchable: true,
+ label: t("fields.location"),
+ }
+
+ filters.push(stockLocationFilter)
+ }
+
+ filters.push({
+ type: "date",
+ key: "created_at",
+ label: t("fields.createdAt"),
+ })
+
+ return filters
+}
diff --git a/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-query.tsx b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-query.tsx
new file mode 100644
index 000000000..95e864a24
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/_components/reservation-list-table/use-reservation-table-query.tsx
@@ -0,0 +1,31 @@
+import { HttpTypes } from "@medusajs/types"
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useReservationTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(
+ ["location_id", "offset", "created_at", "quantity", "updated_at", "order"],
+ prefix
+ )
+
+ const { location_id, created_at, updated_at, quantity, offset, ...rest } = raw
+
+ const searchParams: HttpTypes.AdminGetReservationsParams = {
+ limit: pageSize,
+ offset: offset ? parseInt(offset) : undefined,
+ location_id: location_id,
+ created_at: created_at ? JSON.parse(created_at) : undefined,
+ updated_at: updated_at ? JSON.parse(updated_at) : undefined,
+ ...rest,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/reservations/create/index.tsx b/packages/vendor/src/pages/reservations/create/index.tsx
new file mode 100644
index 000000000..3f57ecc01
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/create/index.tsx
@@ -0,0 +1,16 @@
+// Route: /reservations/create
+import { useSearchParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { ReservationCreateForm } from "./reservation-create-from"
+
+export const Component = () => {
+ const [params] = useSearchParams()
+
+ const inventoryItemId = params.get("item_id")
+
+ return (
+ <RouteFocusModal>
+ <ReservationCreateForm inventoryItemId={inventoryItemId ?? undefined} />
+ </RouteFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/create/reservation-create-from/index.ts b/packages/vendor/src/pages/reservations/create/reservation-create-from/index.ts
new file mode 100644
index 000000000..de2475c5e
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/create/reservation-create-from/index.ts
@@ -0,0 +1 @@
+export * from "./reservation-create-from"
diff --git a/packages/vendor/src/pages/reservations/create/reservation-create-from/reservation-create-from.tsx b/packages/vendor/src/pages/reservations/create/reservation-create-from/reservation-create-from.tsx
new file mode 100644
index 000000000..9dcddad6c
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/create/reservation-create-from/reservation-create-from.tsx
@@ -0,0 +1,312 @@
+import * as zod from "zod"
+
+import { Button, Heading, Input, Text, Textarea, toast } from "@medusajs/ui"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import React from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useInventoryItems } from "@hooks/api/inventory"
+import { useCreateReservationItem } from "@hooks/api/reservations"
+import { useStockLocations } from "@hooks/api/stock-locations"
+
+export const CreateReservationSchema = zod.object({
+ inventory_item_id: zod.string().min(1),
+ location_id: zod.string().min(1),
+ quantity: zod.number().min(1),
+ description: zod.string().optional(),
+})
+
+const AttributeGridRow = ({
+ title,
+ value,
+}: {
+ title: string
+ value: string | number
+}) => {
+ return (
+ <div className="grid grid-cols-2 divide-x">
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {title}
+ </Text>
+ <Text className="px-2 py-1.5" size="small" leading="compact">
+ {value}
+ </Text>
+ </div>
+ )
+}
+
+export const ReservationCreateForm = (props: { inventoryItemId?: string }) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const [inventorySearch, setInventorySearch] = React.useState<string | null>(
+ null
+ )
+
+ const form = useForm<zod.infer<typeof CreateReservationSchema>>({
+ defaultValues: {
+ inventory_item_id: props.inventoryItemId || "",
+ location_id: "",
+ quantity: 0,
+ description: "",
+ },
+ resolver: zodResolver(CreateReservationSchema),
+ })
+
+ const { inventory_items } = useInventoryItems({
+ fields: "*location_levels",
+ q: inventorySearch ?? undefined,
+ })
+
+ const inventoryItemId = form.watch("inventory_item_id")
+ const selectedInventoryItem = inventory_items?.find(
+ (it) => it.id === inventoryItemId
+ ) as HttpTypes.AdminInventoryItemResponse["inventory_item"] | undefined
+
+ const locationId = form.watch("location_id")
+ const selectedLocationLevel = selectedInventoryItem?.location_levels?.find(
+ (it) => it.location_id === locationId
+ )
+
+ const quantity = form.watch("quantity")
+
+ const { stock_locations } = useStockLocations(
+ {
+ id:
+ selectedInventoryItem?.location_levels?.map(
+ (level: HttpTypes.AdminInventoryLevel) => level.location_id
+ ) ?? [],
+ },
+ {
+ enabled: !!selectedInventoryItem,
+ }
+ )
+
+ const { mutateAsync, isPending } = useCreateReservationItem()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const min = 1
+ const max = selectedLocationLevel?.available_quantity
+ ? selectedLocationLevel.available_quantity
+ : 0
+
+ if (!selectedLocationLevel?.available_quantity) {
+ form.setError("quantity", {
+ type: "manual",
+ message: t("inventory.reservation.errors.noAvaliableQuantity"),
+ })
+
+ return
+ }
+
+ if (data.quantity < min || data.quantity > max) {
+ form.setError("quantity", {
+ type: "manual",
+ message: t("inventory.reservation.errors.quantityOutOfRange", {
+ max: max,
+ }),
+ })
+
+ return
+ }
+
+ await mutateAsync(data, {
+ onSuccess: ({ reservation }) => {
+ toast.success(t("inventory.reservation.successToast"))
+ handleSuccess(
+ props.inventoryItemId
+ ? `/inventory/${props.inventoryItemId}`
+ : `/reservations/${reservation.id}`
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex size-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col items-center overflow-auto py-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <Heading>{t("inventory.reservation.create")}</Heading>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ key={"inventory_item_id"}
+ control={form.control}
+ name={"inventory_item_id"}
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("inventory.reservation.itemToReserve")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ onSearchValueChange={(value: string) =>
+ setInventorySearch(value)
+ }
+ value={value}
+ onChange={(v) => {
+ onChange(v)
+ }}
+ {...field}
+ disabled={!!props.inventoryItemId}
+ options={(inventory_items ?? []).map(
+ (inventoryItem) => ({
+ label: inventoryItem.title ?? inventoryItem.sku!,
+ value: inventoryItem.id,
+ })
+ )}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ key={"location_id"}
+ control={form.control}
+ name={"location_id"}
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.location")}</Form.Label>
+ <Form.Control>
+ <Combobox
+ value={value}
+ onChange={(v) => {
+ onChange(v)
+ }}
+ {...field}
+ disabled={!inventoryItemId}
+ options={(stock_locations ?? []).map(
+ (stockLocation) => ({
+ label: stockLocation.name,
+ value: stockLocation.id,
+ })
+ )}
+ />
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="text-ui-fg-subtle shadow-elevation-card-rest grid grid-rows-4 divide-y rounded-lg">
+ <AttributeGridRow
+ title={t("fields.title")}
+ value={
+ selectedInventoryItem?.title ??
+ selectedInventoryItem?.sku ??
+ "-"
+ }
+ />
+ <AttributeGridRow
+ title={t("fields.sku")}
+ value={selectedInventoryItem?.sku ?? "-"}
+ />
+ <AttributeGridRow
+ title={t("fields.inStock")}
+ value={selectedLocationLevel?.stocked_quantity ?? "-"}
+ />
+ <AttributeGridRow
+ title={t("inventory.available")}
+ value={
+ selectedLocationLevel?.available_quantity
+ ? selectedLocationLevel.available_quantity - (quantity || 0)
+ : "-"
+ }
+ />
+ </div>
+ <div className="w-full lg:w-1/2">
+ <Form.Field
+ control={form.control}
+ name="quantity"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.quantity")}</Form.Label>
+ <Form.Control>
+ <Input
+ type="number"
+ placeholder={t(
+ "inventory.reservation.quantityPlaceholder"
+ )}
+ value={value || ""}
+ onChange={(e) => {
+ const value = e.target.value
+
+ if (value === "") {
+ onChange(null)
+ } else {
+ onChange(parseFloat(value))
+ }
+ }}
+ {...field}
+ disabled={!inventoryItemId || !locationId}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.description")}</Form.Label>
+ <Form.Control>
+ <Textarea
+ {...field}
+ disabled={!inventoryItemId || !locationId}
+ placeholder={t(
+ "inventory.reservation.descriptionPlaceholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ type="submit"
+ variant="primary"
+ size="small"
+ isLoading={isPending}
+ >
+ {t("actions.create")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/reservations/index.tsx b/packages/vendor/src/pages/reservations/index.tsx
new file mode 100644
index 000000000..747472267
--- /dev/null
+++ b/packages/vendor/src/pages/reservations/index.tsx
@@ -0,0 +1,19 @@
+// Route: /reservations
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ReservationListTable } from "./_components/reservation-list-table"
+
+export const Component = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("reservation.list.before"),
+ after: getWidgets("reservation.list.after"),
+ }}
+ >
+ <ReservationListTable />
+ </SingleColumnPage>
+ )
+}
diff --git a/packages/vendor/src/pages/reset-password/index.ts b/packages/vendor/src/pages/reset-password/index.ts
new file mode 100644
index 000000000..6c284370f
--- /dev/null
+++ b/packages/vendor/src/pages/reset-password/index.ts
@@ -0,0 +1 @@
+export { ResetPassword as Component } from "./reset-password"
diff --git a/packages/vendor/src/pages/reset-password/reset-password.tsx b/packages/vendor/src/pages/reset-password/reset-password.tsx
new file mode 100644
index 000000000..54a6b411f
--- /dev/null
+++ b/packages/vendor/src/pages/reset-password/reset-password.tsx
@@ -0,0 +1,341 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Alert, Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { Trans, useTranslation } from "react-i18next"
+import { Link, useNavigate, useSearchParams } from "react-router-dom"
+import * as z from "zod"
+
+import { useState } from "react"
+import { decodeToken } from "react-jwt"
+import { Form } from "@components/common/form"
+import { LogoBox } from "@components/common/logo-box"
+import { i18n } from "@components/utilities/i18n"
+import {
+ useResetPasswordForEmailPass,
+ useUpdateProviderForEmailPass,
+} from "@hooks/api/auth"
+
+const ResetPasswordInstructionsSchema = z.object({
+ email: z.string().email(),
+})
+
+const ResetPasswordSchema = z
+ .object({
+ password: z.string().min(1),
+ repeat_password: z.string().min(1),
+ })
+ .superRefine(({ password, repeat_password }, ctx) => {
+ if (password !== repeat_password) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: i18n.t("resetPassword.passwordMismatch"),
+ path: ["repeat_password"],
+ })
+ }
+ })
+
+const ResetPasswordTokenSchema = z.object({
+ entity_id: z.string(),
+ provider: z.string(),
+ exp: z.number(),
+ iat: z.number(),
+})
+
+type DecodedResetPasswordToken = {
+ entity_id: string // -> email in here
+ provider: string
+ exp: string
+ iat: string
+}
+
+const validateDecodedResetPasswordToken = (
+ decoded: any
+): decoded is DecodedResetPasswordToken => {
+ return ResetPasswordTokenSchema.safeParse(decoded).success
+}
+
+const InvalidResetToken = () => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+
+ return (
+ <div className="bg-ui-bg-base flex min-h-dvh w-dvw items-center justify-center">
+ <div className="m-4 flex w-full max-w-[300px] flex-col items-center">
+ <LogoBox className="mb-4" />
+ <div className="mb-6 flex flex-col items-center">
+ <Heading>{t("resetPassword.invalidLinkTitle")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("resetPassword.invalidLinkHint")}
+ </Text>
+ </div>
+ <div className="flex w-full flex-col gap-y-3">
+ <Button
+ onClick={() => navigate("/reset-password", { replace: true })}
+ className="w-full"
+ type="submit"
+ >
+ {t("resetPassword.goToResetPassword")}
+ </Button>
+ </div>
+ <span className="txt-small my-6">
+ <Trans
+ i18nKey="resetPassword.backToLogin"
+ components={[
+ <Link
+ key="login-link"
+ to="/login"
+ className="text-ui-fg-interactive transition-fg hover:text-ui-fg-interactive-hover focus-visible:text-ui-fg-interactive-hover outline-none"
+ />,
+ ]}
+ />
+ </span>
+ </div>
+ </div>
+ )
+}
+
+const ChooseNewPassword = ({ token }: { token: string }) => {
+ const { t } = useTranslation()
+
+ const [showAlert, setShowAlert] = useState(false)
+
+ const invite: DecodedResetPasswordToken | null = token
+ ? decodeToken(token)
+ : null
+
+ const isValidResetPasswordToken =
+ invite && validateDecodedResetPasswordToken(invite)
+
+ const form = useForm<z.infer<typeof ResetPasswordSchema>>({
+ resolver: zodResolver(ResetPasswordSchema),
+ defaultValues: {
+ password: "",
+ repeat_password: "",
+ },
+ })
+
+ const { mutateAsync, isPending } = useUpdateProviderForEmailPass(token)
+
+ const handleSubmit = form.handleSubmit(async ({ password }) => {
+ if (!invite) {
+ return
+ }
+
+ await mutateAsync(
+ {
+ password,
+ },
+ {
+ onSuccess: () => {
+ form.setValue("password", "")
+ form.setValue("repeat_password", "")
+ setShowAlert(true)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ if (!isValidResetPasswordToken) {
+ return <InvalidResetToken />
+ }
+
+ return (
+ <div className="bg-ui-bg-subtle flex min-h-dvh w-dvw items-center justify-center">
+ <div className="m-4 flex w-full max-w-[280px] flex-col items-center">
+ <LogoBox className="mb-4" />
+ <div className="mb-6 flex flex-col items-center">
+ <Heading>{t("resetPassword.resetPassword")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("resetPassword.newPasswordHint")}
+ </Text>
+ </div>
+ <div className="flex w-full flex-col gap-y-3">
+ <Form {...form}>
+ <form
+ onSubmit={handleSubmit}
+ className="flex w-full flex-col gap-y-6"
+ >
+ <div className="flex flex-col gap-y-4">
+ <Input type="email" disabled value={invite?.entity_id} />
+ <Form.Field
+ control={form.control}
+ name="password"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="new-password"
+ type="password"
+ {...field}
+ placeholder={t("resetPassword.newPassword")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="repeat_password"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="off"
+ type="password"
+ {...field}
+ placeholder={t("resetPassword.repeatNewPassword")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {showAlert && (
+ <Alert dismissible variant="success">
+ <div className="flex flex-col">
+ <span className="text-ui-fg-base mb-1">
+ {t("resetPassword.successfulResetTitle")}
+ </span>
+ <span>{t("resetPassword.successfulReset")}</span>
+ </div>
+ </Alert>
+ )}
+ {!showAlert && (
+ <Button className="w-full" type="submit" isLoading={isPending}>
+ {t("resetPassword.resetPassword")}
+ </Button>
+ )}
+ </form>
+ </Form>
+ </div>
+ <span className="txt-small my-6">
+ <Trans
+ i18nKey="resetPassword.backToLogin"
+ components={[
+ <Link
+ key="login-link"
+ to="/login"
+ className="text-ui-fg-base transition-fg hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover outline-none"
+ />,
+ ]}
+ />
+ </span>
+ </div>
+ </div>
+ )
+}
+
+export const ResetPassword = () => {
+ const { t } = useTranslation()
+ const [searchParams] = useSearchParams()
+ const [showAlert, setShowAlert] = useState(false)
+
+ const token = searchParams.get("token")
+
+ const form = useForm<z.infer<typeof ResetPasswordInstructionsSchema>>({
+ resolver: zodResolver(ResetPasswordInstructionsSchema),
+ defaultValues: {
+ email: "",
+ },
+ })
+
+ const { mutateAsync, isPending } = useResetPasswordForEmailPass()
+
+ const handleSubmit = form.handleSubmit(async ({ email }) => {
+ await mutateAsync(
+ {
+ email,
+ },
+ {
+ onSuccess: () => {
+ form.setValue("email", "")
+ setShowAlert(true)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ if (token) {
+ return <ChooseNewPassword token={token} />
+ }
+
+ return (
+ <div className="bg-ui-bg-base flex min-h-dvh w-dvw items-center justify-center">
+ <div className="m-4 flex w-full max-w-[300px] flex-col items-center">
+ <LogoBox className="mb-4" />
+ <div className="mb-4 flex flex-col items-center">
+ <Heading>{t("resetPassword.resetPassword")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-center">
+ {t("resetPassword.hint")}
+ </Text>
+ </div>
+ <div className="flex w-full flex-col gap-y-3">
+ <Form {...form}>
+ <form
+ onSubmit={handleSubmit}
+ className="flex w-full flex-col gap-y-6"
+ >
+ <div className="mt-4 flex flex-col gap-y-3">
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Control>
+ <Input
+ autoComplete="email"
+ {...field}
+ placeholder={t("fields.email")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {showAlert && (
+ <Alert dismissible variant="success">
+ <div className="flex flex-col">
+ <span className="text-ui-fg-base mb-1">
+ {t("resetPassword.successfulRequestTitle")}
+ </span>
+ <span>{t("resetPassword.successfulRequest")}</span>
+ </div>
+ </Alert>
+ )}
+ <Button className="w-full" type="submit" isLoading={isPending}>
+ {t("resetPassword.sendResetInstructions")}
+ </Button>
+ </form>
+ </Form>
+ </div>
+ <span className="txt-small my-6">
+ <Trans
+ i18nKey="resetPassword.backToLogin"
+ components={[
+ <Link
+ key="login-link"
+ to="/login"
+ className="text-ui-fg-base transition-fg hover:text-ui-fg-base-hover focus-visible:text-ui-fg-base-hover outline-none"
+ />,
+ ]}
+ />
+ </span>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/index.ts b/packages/vendor/src/pages/settings/index.ts
new file mode 100644
index 000000000..3170af424
--- /dev/null
+++ b/packages/vendor/src/pages/settings/index.ts
@@ -0,0 +1 @@
+export { Settings as Component } from "./settings"
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-fulfillment-providers-section.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-fulfillment-providers-section.tsx
new file mode 100644
index 000000000..363656758
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-fulfillment-providers-section.tsx
@@ -0,0 +1,73 @@
+import { HandTruck, PencilSquare } from "@medusajs/icons"
+import { Container, Heading } from "@medusajs/ui"
+import { Fragment } from "react"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { NoRecords } from "@components/common/empty-table-content"
+import { IconAvatar } from "@components/common/icon-avatar"
+import { formatProvider } from "@lib/format-provider"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+
+function LocationsFulfillmentProvidersSection({
+ location,
+}: {
+ location: VendorExtendedAdminStockLocation
+}) {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex flex-col px-6 py-4">
+ <div className="flex items-center justify-between">
+ <Heading level="h2">
+ {t("stockLocations.fulfillmentProviders.header")}
+ </Heading>
+
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "fulfillment-providers",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+
+ {location.fulfillment_providers?.length ? (
+ <div className="flex flex-col gap-y-4 pt-4">
+ <div className="grid grid-cols-[28px_1fr] items-center gap-x-3 gap-y-3">
+ {location.fulfillment_providers?.map((fulfillmentProvider) => {
+ return (
+ <Fragment key={fulfillmentProvider.id}>
+ <IconAvatar>
+ <HandTruck className="text-ui-fg-subtle" />
+ </IconAvatar>
+
+ <div className="txt-compact-small">
+ {formatProvider(fulfillmentProvider.id)}
+ </div>
+ </Fragment>
+ )
+ })}
+ </div>
+ </div>
+ ) : (
+ <NoRecords
+ className="h-fit pb-2 pt-6 text-center"
+ action={{
+ label: t("stockLocations.fulfillmentProviders.action"),
+ to: "fulfillment-providers",
+ }}
+ message={t("stockLocations.fulfillmentProviders.noProviders")}
+ />
+ )}
+ </Container>
+ )
+}
+
+export default LocationsFulfillmentProvidersSection
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-general-section.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-general-section.tsx
new file mode 100644
index 000000000..4b96d0dbd
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/_components/location-general-section.tsx
@@ -0,0 +1,653 @@
+import {
+ ArchiveBox,
+ CurrencyDollar,
+ Map,
+ PencilSquare,
+ Plus,
+ Trash,
+ TriangleDownMini,
+} from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Container,
+ Divider,
+ Heading,
+ IconButton,
+ StatusBadge,
+ Text,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { NoRecords } from "@components/common/empty-table-content"
+import { IconAvatar } from "@components/common/icon-avatar"
+import { LinkButton } from "@components/common/link-button"
+import { ListSummary } from "@components/common/list-summary"
+import {
+ useDeleteFulfillmentServiceZone,
+ useDeleteFulfillmentSet,
+} from "@hooks/api/fulfillment-sets"
+import { useDeleteShippingOption } from "@hooks/api/shipping-options"
+import {
+ useCreateStockLocationFulfillmentSet,
+ useDeleteStockLocation,
+} from "@hooks/api/stock-locations"
+import { getFormattedAddress } from "@lib/addresses"
+import {
+ StaticCountry,
+ countries as staticCountries,
+} from "@lib/data/countries"
+import { formatProvider } from "@lib/format-provider"
+import {
+ getShippingProfileName,
+ isReturnOption,
+} from "@lib/shipping-options"
+import {
+ FulfillmentSetType,
+ ShippingOptionPriceType,
+} from "@pages/settings/locations/_common/constants"
+import { VendorExtendedAdminStockLocation, VendorExtendedAdminFulfillmentSet, VendorExtendedAdminServiceZone } from "@custom-types/stock-location"
+
+type LocationGeneralSectionProps = {
+ location: VendorExtendedAdminStockLocation
+}
+
+export const LocationGeneralSection = ({
+ location,
+}: LocationGeneralSectionProps) => {
+ return (
+ <>
+ <Container className="p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{location.name}</Heading>
+ <Text className="text-ui-fg-subtle txt-small">
+ {getFormattedAddress({
+ address: location.address,
+ }).join(", ")}
+ </Text>
+ </div>
+ <Actions location={location} />
+ </div>
+ </Container>
+
+ <FulfillmentSet
+ locationId={location.id}
+ locationName={location.name}
+ type={FulfillmentSetType.Pickup}
+ fulfillmentSet={location.fulfillment_sets?.find(
+ (f) => f.type === FulfillmentSetType.Pickup
+ )}
+ />
+
+ <FulfillmentSet
+ locationId={location.id}
+ locationName={location.name}
+ type={FulfillmentSetType.Shipping}
+ fulfillmentSet={location.fulfillment_sets?.find(
+ (f) => f.type === FulfillmentSetType.Shipping
+ )}
+ />
+ </>
+ )
+}
+
+type ShippingOptionProps = {
+ option: HttpTypes.AdminShippingOption
+ fulfillmentSetId: string
+ locationId: string
+}
+
+function ShippingOption({
+ option,
+ fulfillmentSetId,
+ locationId,
+}: ShippingOptionProps) {
+ const prompt = usePrompt()
+ const { t } = useTranslation()
+
+ const { mutateAsync } = useDeleteShippingOption(option.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("stockLocations.shippingOptions.delete.confirmation", {
+ name: option.name,
+ }),
+ verificationInstruction: t("general.typeToConfirm"),
+ verificationText: option.name,
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.shippingOptions.delete.successToast", {
+ name: option.name,
+ })
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <div className="flex items-center justify-between px-3 py-2">
+ <div className="flex-1">
+ <Text size="small" weight="plus">
+ {option.name} - {getShippingProfileName(option.shipping_profile.name)}{" "}
+ ({formatProvider(option.provider_id)})
+ </Text>
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("stockLocations.shippingOptions.edit.action"),
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${option.service_zone_id}/shipping-option/${option.id}/edit`,
+ },
+ {
+ label: t("stockLocations.shippingOptions.pricing.action"),
+ icon: <CurrencyDollar />,
+ disabled:
+ option.price_type === ShippingOptionPriceType.Calculated,
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${option.service_zone_id}/shipping-option/${option.id}/pricing`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ )
+}
+
+type ServiceZoneOptionsProps = {
+ zone: VendorExtendedAdminServiceZone
+ locationId: string
+ fulfillmentSetId: string
+ type: FulfillmentSetType
+}
+
+function ServiceZoneOptions({
+ zone,
+ locationId,
+ fulfillmentSetId,
+ type,
+}: ServiceZoneOptionsProps) {
+ const { t } = useTranslation()
+
+ const shippingOptions = zone.shipping_options.filter(
+ (o) => !isReturnOption(o)
+ )
+
+ const returnOptions = zone.shipping_options.filter((o) => isReturnOption(o))
+
+ return (
+ <div>
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="item-center flex justify-between">
+ <span className="text-ui-fg-subtle txt-small self-center font-medium">
+ {t(`stockLocations.shippingOptions.create.${type}.label`)}
+ </span>
+ <LinkButton
+ to={`/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/shipping-option/create`}
+ >
+ {t("stockLocations.shippingOptions.create.action")}
+ </LinkButton>
+ </div>
+
+ {!!shippingOptions?.length && (
+ <div className="shadow-elevation-card-rest bg-ui-bg-subtle grid divide-y rounded-md">
+ {shippingOptions.map((o) => (
+ <ShippingOption
+ key={o.id}
+ option={o}
+ locationId={locationId}
+ fulfillmentSetId={fulfillmentSetId}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+
+ <Divider variant="dashed" />
+
+ <div className="flex flex-col gap-y-4 px-6 py-4">
+ <div className="item-center flex justify-between">
+ <span className="text-ui-fg-subtle txt-small self-center font-medium">
+ {t("stockLocations.shippingOptions.create.returns.label")}
+ </span>
+ <LinkButton
+ to={`/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/shipping-option/create?is_return`}
+ >
+ {t("stockLocations.shippingOptions.create.action")}
+ </LinkButton>
+ </div>
+
+ {!!returnOptions?.length && (
+ <div className="shadow-elevation-card-rest bg-ui-bg-subtle grid divide-y rounded-md">
+ {returnOptions.map((o) => (
+ <ShippingOption
+ key={o.id}
+ option={o}
+ locationId={locationId}
+ fulfillmentSetId={fulfillmentSetId}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ )
+}
+
+type ServiceZoneProps = {
+ zone: VendorExtendedAdminServiceZone
+ locationId: string
+ fulfillmentSetId: string
+ type: FulfillmentSetType
+}
+
+function ServiceZone({
+ zone,
+ locationId,
+ fulfillmentSetId,
+ type,
+}: ServiceZoneProps) {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const [open, setOpen] = useState(true)
+
+ const { mutateAsync: deleteZone } = useDeleteFulfillmentServiceZone(
+ fulfillmentSetId,
+ zone.id
+ )
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("stockLocations.serviceZones.delete.confirmation", {
+ name: zone.name,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await deleteZone(undefined, {
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.serviceZones.delete.successToast", {
+ name: zone.name,
+ })
+ )
+ },
+ })
+ }
+
+ const countries = useMemo(() => {
+ const countryGeoZones = zone.geo_zones.filter((g) => g.type === "country")
+
+ const countries = countryGeoZones
+ .map(({ country_code }) =>
+ staticCountries.find((c) => c.iso_2 === country_code)
+ )
+ .filter((c) => !!c) as StaticCountry[]
+
+ if (
+ process.env.NODE_ENV === "development" &&
+ countryGeoZones?.length !== countries?.length
+ ) {
+ console.warn(
+ "Some countries are missing in the static countries list",
+ countryGeoZones
+ .filter((g) => !countries.find((c) => c.iso_2 === g.country_code))
+ .map((g) => g.country_code)
+ )
+ }
+
+ return countries.sort((c1, c2) => c1.name.localeCompare(c2.name))
+ }, [zone.geo_zones])
+
+ const [shippingOptionsCount, returnOptionsCount] = useMemo(() => {
+ const options = zone.shipping_options
+
+ const optionsCount = options.filter((o) => !isReturnOption(o))?.length
+
+ const returnOptionsCount = options.filter(isReturnOption)?.length
+
+ return [optionsCount, returnOptionsCount]
+ }, [zone.shipping_options])
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex flex-row items-center justify-between gap-x-4 px-6 py-4">
+ <IconAvatar>
+ <Map />
+ </IconAvatar>
+
+ <div className="grow-1 flex flex-1 flex-col">
+ <Text size="small" leading="compact" weight="plus">
+ {zone.name}
+ </Text>
+ <div className="flex items-center gap-2">
+ <ListSummary
+ variant="base"
+ list={countries.map((c) => c.display_name)}
+ inline
+ n={1}
+ />
+ <span>·</span>
+ <Text className="text-ui-fg-subtle txt-small">
+ {t(`stockLocations.shippingOptions.fields.count.${type}`, {
+ count: shippingOptionsCount,
+ })}
+ </Text>
+ <span>·</span>
+ <Text className="text-ui-fg-subtle txt-small">
+ {t("stockLocations.shippingOptions.fields.count.returns", {
+ count: returnOptionsCount,
+ })}
+ </Text>
+ </div>
+ </div>
+
+ <div className="flex grow-0 items-center gap-4">
+ <IconButton
+ size="small"
+ onClick={() => setOpen((s) => !s)}
+ variant="transparent"
+ >
+ <TriangleDownMini
+ style={{
+ transform: `rotate(${!open ? 0 : 180}deg)`,
+ transition: ".2s transform ease-in-out",
+ }}
+ />
+ </IconButton>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/edit`,
+ },
+ {
+ label: t("stockLocations.serviceZones.manageAreas.action"),
+ icon: <Map />,
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSetId}/service-zone/${zone.id}/areas`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ {open && (
+ <ServiceZoneOptions
+ fulfillmentSetId={fulfillmentSetId}
+ locationId={locationId}
+ type={type}
+ zone={zone}
+ />
+ )}
+ </div>
+ )
+}
+
+type FulfillmentSetProps = {
+ fulfillmentSet?: VendorExtendedAdminFulfillmentSet
+ locationName: string
+ locationId: string
+ type: FulfillmentSetType
+}
+
+function FulfillmentSet(props: FulfillmentSetProps) {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { fulfillmentSet, locationName, locationId, type } = props
+
+ const fulfillmentSetExists = !!fulfillmentSet
+
+ const hasServiceZones = !!fulfillmentSet?.service_zones?.length
+
+ const { mutateAsync: createFulfillmentSet } =
+ useCreateStockLocationFulfillmentSet(locationId)
+
+ const { mutateAsync: deleteFulfillmentSet } = useDeleteFulfillmentSet(
+ fulfillmentSet?.id!
+ )
+
+ const handleCreate = async () => {
+ await createFulfillmentSet(
+ {
+ name: `${locationName} ${
+ type === FulfillmentSetType.Pickup ? "pick up" : type
+ }`,
+ type,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t(`stockLocations.fulfillmentSets.enable.${type}`))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t(`stockLocations.fulfillmentSets.disable.confirmation`, {
+ name: fulfillmentSet?.name,
+ }),
+ confirmText: t("actions.disable"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await deleteFulfillmentSet(undefined, {
+ onSuccess: () => {
+ toast.success(t(`stockLocations.fulfillmentSets.disable.${type}`))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ const groups = fulfillmentSet
+ ? [
+ {
+ actions: [
+ {
+ icon: <Plus />,
+ label: t("stockLocations.serviceZones.create.action"),
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSet.id}/service-zones/create`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.disable"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]
+ : [
+ {
+ actions: [
+ {
+ icon: <Plus />,
+ label: t("actions.enable"),
+ onClick: handleCreate,
+ },
+ ],
+ },
+ ]
+
+ return (
+ <Container className="p-0">
+ <div className="flex flex-col divide-y">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">
+ {t(`stockLocations.fulfillmentSets.${type}.header`)}
+ </Heading>
+ <div className="flex items-center gap-4">
+ <StatusBadge color={fulfillmentSetExists ? "green" : "grey"}>
+ {t(
+ fulfillmentSetExists ? "statuses.enabled" : "statuses.disabled"
+ )}
+ </StatusBadge>
+
+ <ActionMenu groups={groups} />
+ </div>
+ </div>
+
+ {fulfillmentSetExists && !hasServiceZones && (
+ <div className="flex items-center justify-center py-8 pt-6">
+ <NoRecords
+ message={t("stockLocations.serviceZones.fields.noRecords")}
+ className="h-fit"
+ action={{
+ to: `/settings/locations/${locationId}/fulfillment-set/${fulfillmentSet.id}/service-zones/create`,
+ label: t("stockLocations.serviceZones.create.action"),
+ }}
+ />
+ </div>
+ )}
+
+ {hasServiceZones && (
+ <div className="flex flex-col divide-y">
+ {fulfillmentSet?.service_zones.map((zone) => (
+ <ServiceZone
+ zone={zone}
+ type={type}
+ key={zone.id}
+ locationId={locationId}
+ fulfillmentSetId={fulfillmentSet.id}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ </Container>
+ )
+}
+
+const Actions = ({ location }: { location: VendorExtendedAdminStockLocation }) => {
+ const navigate = useNavigate()
+ const { t } = useTranslation()
+ const { mutateAsync } = useDeleteStockLocation(location.id)
+ const prompt = usePrompt()
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("stockLocations.delete.confirmation", {
+ name: location.name,
+ }),
+ verificationText: location.name,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.create.successToast", {
+ name: location.name,
+ })
+ )
+ navigate("/settings/locations", { replace: true })
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `edit`,
+ },
+ {
+ icon: <ArchiveBox />,
+ label: t("stockLocations.edit.viewInventory"),
+ to: `/inventory?location_id=${location.id}`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/_components/locations-sales-channels-section.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/_components/locations-sales-channels-section.tsx
new file mode 100644
index 000000000..40bc99147
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/_components/locations-sales-channels-section.tsx
@@ -0,0 +1,76 @@
+import { Channels, PencilSquare } from "@medusajs/icons"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { NoRecords } from "@components/common/empty-table-content"
+import { IconAvatar } from "@components/common/icon-avatar"
+import { ListSummary } from "@components/common/list-summary"
+import { useSalesChannels } from "@hooks/api/sales-channels"
+
+type LocationsSalesChannelsSectionProps = {
+ location: VendorExtendedAdminStockLocation
+}
+
+function LocationsSalesChannelsSection({
+ location,
+}: LocationsSalesChannelsSectionProps) {
+ const { t } = useTranslation()
+ const { count } = useSalesChannels({ limit: 1, fields: "id" })
+
+ const hasConnectedChannels = !!location.sales_channels?.length
+
+ return (
+ <Container className="flex flex-col px-6 py-4">
+ <div className="flex items-center justify-between">
+ <Heading level="h2">{t("stockLocations.salesChannels.header")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "sales-channels",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ {hasConnectedChannels ? (
+ <div className="flex flex-col gap-y-4 pt-4">
+ <div className="grid grid-cols-[28px_1fr] items-center gap-x-3">
+ <IconAvatar>
+ <Channels className="text-ui-fg-subtle" />
+ </IconAvatar>
+ <ListSummary
+ n={3}
+ className="text-ui-fg-base"
+ inline
+ list={location.sales_channels?.map((sc) => sc.name) ?? []}
+ />
+ </div>
+ <Text className="text-ui-fg-subtle" size="small" leading="compact">
+ {t("stockLocations.salesChannels.connectedTo", {
+ count: location.sales_channels?.length,
+ total: count,
+ })}
+ </Text>
+ </div>
+ ) : (
+ <NoRecords
+ className="h-fit pb-2 pt-6"
+ action={{
+ label: t("stockLocations.salesChannels.action"),
+ to: "sales-channels",
+ }}
+ message={t("stockLocations.salesChannels.noChannels")}
+ />
+ )}
+ </Container>
+ )
+}
+
+export default LocationsSalesChannelsSection
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/breadcrumb.tsx
new file mode 100644
index 000000000..5758c1ce0
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/breadcrumb.tsx
@@ -0,0 +1,31 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { LOCATION_DETAILS_FIELD } from "./constants"
+
+type LocationDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminStockLocationResponse>
+
+export const LocationDetailBreadcrumb = (
+ props: LocationDetailBreadcrumbProps
+) => {
+ const { location_id } = props.params || {}
+
+ const { stock_location } = useStockLocation(
+ location_id!,
+ {
+ fields: LOCATION_DETAILS_FIELD,
+ },
+ {
+ initialData: props.data,
+ enabled: Boolean(location_id),
+ }
+ )
+
+ if (!stock_location) {
+ return null
+ }
+
+ return <span>{stock_location.name}</span>
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/constants.ts b/packages/vendor/src/pages/settings/locations/[location_id]/constants.ts
new file mode 100644
index 000000000..78f963317
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/constants.ts
@@ -0,0 +1,2 @@
+export const LOCATION_DETAILS_FIELD =
+ "name,*sales_channels,*address,fulfillment_sets.type,fulfillment_sets.name,*fulfillment_sets.service_zones.geo_zones,*fulfillment_sets.service_zones,*fulfillment_sets.service_zones.shipping_options,*fulfillment_sets.service_zones.shipping_options.rules,*fulfillment_sets.service_zones.shipping_options.shipping_profile,*fulfillment_providers"
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/edit/_components/edit-location-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/edit/_components/edit-location-form.tsx
new file mode 100644
index 000000000..8030cff67
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/edit/_components/edit-location-form.tsx
@@ -0,0 +1,235 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateStockLocation } from "@hooks/api/stock-locations"
+
+type EditLocationFormProps = {
+ location: VendorExtendedAdminStockLocation
+}
+
+const EditLocationSchema = zod.object({
+ name: zod.string().min(1),
+ address: zod.object({
+ address_1: zod.string().min(1),
+ address_2: zod.string().optional(),
+ country_code: zod.string().min(2).max(2),
+ city: zod.string().optional(),
+ postal_code: zod.string().optional(),
+ province: zod.string().optional(),
+ company: zod.string().optional(),
+ phone: zod.string().optional(), // TODO: Add validation
+ }),
+})
+
+export const EditLocationForm = ({ location }: EditLocationFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditLocationSchema>>({
+ defaultValues: {
+ name: location.name,
+ address: {
+ address_1: location.address?.address_1 || "",
+ address_2: location.address?.address_2 || "",
+ city: location.address?.city || "",
+ company: location.address?.company || "",
+ country_code: location.address?.country_code || "",
+ phone: location.address?.phone || "",
+ postal_code: location.address?.postal_code || "",
+ province: location.address?.province || "",
+ },
+ },
+ resolver: zodResolver(EditLocationSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateStockLocation(location.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const { name, address } = values
+
+ await mutateAsync(
+ {
+ name: name,
+ address: address,
+ },
+ {
+ onSuccess: () => {
+ toast.success("Stock location updated")
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-col gap-y-8 overflow-y-auto">
+ <div className="grid grid-cols-1 gap-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.address_1"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.address")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.address_2"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.address2")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.postal_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.postalCode")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.city"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.city")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.country_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.country")}</Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.province"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.state")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.company"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.company")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.phone"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.phone")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/edit/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/edit/index.tsx
new file mode 100644
index 000000000..d21a225df
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/edit/index.tsx
@@ -0,0 +1,35 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { EditLocationForm } from "./_components/edit-location-form"
+
+const LocationEdit = () => {
+ const { t } = useTranslation()
+ const { location_id } = useParams()
+
+ const { stock_location, isPending, isError, error } = useStockLocation(
+ location_id!,
+ {
+ fields: "*address",
+ }
+ )
+
+ const ready = !isPending && !!stock_location
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading className="capitalize">{t("locations.editLocation")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <EditLocationForm location={stock_location} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = LocationEdit
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/_components/edit-fulfillment-providers-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/_components/edit-fulfillment-providers-form.tsx
new file mode 100644
index 000000000..6ef7d569a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/_components/edit-fulfillment-providers-form.tsx
@@ -0,0 +1,203 @@
+import { HttpTypes } from "@medusajs/types"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+import { Button, Checkbox, toast } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ RowSelectionState,
+ Updater,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useFulfillmentProviders } from "@hooks/api/fulfillment-providers"
+import { useUpdateStockLocationFulfillmentProviders } from "@hooks/api/stock-locations"
+import { useFulfillmentProviderTableColumns } from "@hooks/table/columns/use-fulfillment-provider-table-columns"
+import { useDateTableFilters } from "@hooks/table/filters"
+import { useFulfillmentProvidersTableQuery } from "@hooks/table/query/use-fulfillment-providers-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type LocationEditFulfillmentProvidersFormProps = {
+ location: VendorExtendedAdminStockLocation
+}
+
+const EditFulfillmentProvidersFormSchema = zod.object({
+ fulfillment_providers: zod.array(zod.string()).optional(),
+})
+
+const PAGE_SIZE = 50
+
+export const LocationEditFulfillmentProvidersForm = ({
+ location,
+}: LocationEditFulfillmentProvidersFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditFulfillmentProvidersFormSchema>>({
+ defaultValues: {
+ fulfillment_providers:
+ location.fulfillment_providers?.map((fp) => fp.id) ?? [],
+ },
+ resolver: zodResolver(EditFulfillmentProvidersFormSchema),
+ })
+
+ const { setValue } = form
+
+ const initialState =
+ location.fulfillment_providers?.reduce((acc, curr) => {
+ acc[curr.id] = true
+ return acc
+ }, {} as RowSelectionState) ?? {}
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialState)
+
+ const handleRowSelectionChange = (updater: Updater<RowSelectionState>) => {
+ const ids = typeof updater === "function" ? updater(rowSelection) : updater
+
+ setValue("fulfillment_providers", Object.keys(ids), {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+
+ setRowSelection(ids)
+ }
+
+ const { raw } = useFulfillmentProvidersTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { fulfillment_providers, count, isLoading } = useFulfillmentProviders(
+ {},
+ { placeholderData: keepPreviousData }
+ )
+
+ const filters = useDateTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: fulfillment_providers ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ rowSelection: {
+ state: rowSelection,
+ updater: handleRowSelectionChange,
+ },
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ const { mutateAsync, isPending: isMutating } =
+ useUpdateStockLocationFulfillmentProviders(location.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const originalIds = location.fulfillment_providers?.map((sc) => sc.id)
+
+ const arr = data.fulfillment_providers ?? []
+
+ await mutateAsync(
+ {
+ add: arr.filter((i) => !originalIds?.includes(i)),
+ remove: originalIds?.filter((i) => !arr.includes(i)),
+ },
+ {
+ onSuccess: ({ stock_location }) => {
+ toast.success(t("stockLocations.fulfillmentProviders.successToast"))
+ handleSuccess(`/settings/locations/${stock_location.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex size-full flex-col">
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-auto">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ count={count}
+ filters={filters}
+ search="autofocus"
+ pagination
+ orderBy={[{ key: "id", label: t("fields.id") }]}
+ queryObject={raw}
+ layout="fill"
+ />
+ </RouteFocusModal.Body>
+
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+
+ <Button size="small" isLoading={isMutating} type="submit">
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminFulfillmentProvider>()
+
+const useColumns = () => {
+ const columns = useFulfillmentProviderTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...columns,
+ ],
+ [columns]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/index.tsx
new file mode 100644
index 000000000..0c26def64
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-providers/index.tsx
@@ -0,0 +1,29 @@
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { LocationEditFulfillmentProvidersForm } from "./_components/edit-fulfillment-providers-form"
+
+const LocationFulfillmentProviders = () => {
+ const { location_id } = useParams()
+ const { stock_location, isPending, isError, error } = useStockLocation(
+ location_id!,
+ { fields: "id,*fulfillment_providers" }
+ )
+
+ const ready = !isPending && !!stock_location
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && (
+ <LocationEditFulfillmentProvidersForm location={stock_location} />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationFulfillmentProviders
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/_components/edit-service-zone-areas-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/_components/edit-service-zone-areas-form.tsx
new file mode 100644
index 000000000..360e67522
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/_components/edit-service-zone-areas-form.tsx
@@ -0,0 +1,120 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { VendorExtendedAdminServiceZone } from "@custom-types/stock-location"
+import { Button, Heading, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateFulfillmentSetServiceZone } from "@hooks/api/fulfillment-sets"
+import { countries } from "@lib/data/countries"
+import { GeoZoneForm } from "@pages/settings/locations/_common/components/geo-zone-form"
+import { GEO_ZONE_STACKED_MODAL_ID } from "@pages/settings/locations/_common/constants"
+
+const EditeServiceZoneSchema = z.object({
+ countries: z
+ .array(z.object({ iso_2: z.string().min(2), display_name: z.string() }))
+ .min(1),
+})
+
+type EditServiceZoneAreasFormProps = {
+ fulfillmentSetId: string
+ locationId: string
+ zone: VendorExtendedAdminServiceZone
+}
+
+export function EditServiceZoneAreasForm({
+ fulfillmentSetId,
+ locationId,
+ zone,
+}: EditServiceZoneAreasFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof EditeServiceZoneSchema>>({
+ defaultValues: {
+ countries: zone.geo_zones.map((z) => {
+ const country = countries.find((c) => c.iso_2 === z.country_code)
+
+ return {
+ iso_2: z.country_code,
+ display_name: country?.display_name || z.country_code.toUpperCase(),
+ }
+ }),
+ },
+ resolver: zodResolver(EditeServiceZoneSchema),
+ })
+
+ const { mutateAsync: editServiceZone, isPending: isLoading } =
+ useUpdateFulfillmentSetServiceZone(fulfillmentSetId, zone.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await editServiceZone(
+ {
+ geo_zones: data.countries.map(({ iso_2 }) => ({
+ country_code: iso_2,
+ type: "country",
+ })),
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.serviceZones.manageAreas.successToast", {
+ name: zone.name,
+ })
+ )
+
+ handleSuccess(`/settings/locations/${locationId}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header />
+
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-auto">
+ <StackedFocusModal id={GEO_ZONE_STACKED_MODAL_ID}>
+ <div className="flex flex-col items-center p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <Heading>
+ {t("stockLocations.serviceZones.manageAreas.header", {
+ name: zone.name,
+ })}
+ </Heading>
+ <GeoZoneForm form={form} />
+ </div>
+ </div>
+
+ <GeoZoneForm.AreaDrawer form={form} />
+ </StackedFocusModal>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/index.tsx
new file mode 100644
index 000000000..53c311111
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/areas/index.tsx
@@ -0,0 +1,44 @@
+import { json, useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { EditServiceZoneAreasForm } from "./_components/edit-service-zone-areas-form"
+
+const LocationServiceZoneManageAreas = () => {
+ const { location_id, fset_id, zone_id } = useParams()
+
+ const { stock_location, isPending, isFetching, isError, error } =
+ useStockLocation(location_id!, {
+ fields:
+ "*fulfillment_sets.service_zones.geo_zones,fulfillment_sets.service_zones.name",
+ })
+
+ const zone = stock_location?.fulfillment_sets
+ ?.find((f) => f.id === fset_id)
+ ?.service_zones.find((z) => z.id === zone_id)
+
+ if (!isPending && !isFetching && !zone) {
+ throw json(
+ { message: `Service zone with ID ${zone_id} was not found` },
+ 404
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal prev={`/settings/locations/${location_id}`}>
+ {zone && (
+ <EditServiceZoneAreasForm
+ zone={zone}
+ fulfillmentSetId={fset_id!}
+ locationId={location_id!}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationServiceZoneManageAreas
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/_components/edit-service-zone-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/_components/edit-service-zone-form.tsx
new file mode 100644
index 000000000..6b813f5cf
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/_components/edit-service-zone-form.tsx
@@ -0,0 +1,105 @@
+import { VendorExtendedAdminServiceZone } from "@custom-types/stock-location"
+import { Button, InlineTip, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateFulfillmentSetServiceZone } from "@hooks/api/fulfillment-sets"
+
+type EditServiceZoneFormProps = {
+ zone: VendorExtendedAdminServiceZone
+ fulfillmentSetId: string
+ locationId: string
+}
+
+const EditServiceZoneSchema = zod.object({
+ name: zod.string().min(1),
+})
+
+export const EditServiceZoneForm = ({
+ zone,
+ fulfillmentSetId,
+ locationId,
+}: EditServiceZoneFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditServiceZoneSchema>>({
+ defaultValues: {
+ name: zone.name,
+ },
+ })
+
+ const { mutateAsync, isPending: isLoading } =
+ useUpdateFulfillmentSetServiceZone(fulfillmentSetId, zone.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ name: values.name,
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.serviceZones.edit.successToast", {
+ name: values.name,
+ })
+ )
+ handleSuccess(`/settings/locations/${locationId}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex size-full flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex-1 overflow-auto">
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <InlineTip label={t("general.tip")}>
+ {t("stockLocations.serviceZones.fields.tip")}
+ </InlineTip>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/index.tsx
new file mode 100644
index 000000000..bee662c15
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/edit/index.tsx
@@ -0,0 +1,51 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { json, useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { EditServiceZoneForm } from "./_components/edit-service-zone-form"
+
+const LocationServiceZoneEdit = () => {
+ const { t } = useTranslation()
+ const { location_id, fset_id, zone_id } = useParams()
+
+ const { stock_location, isPending, isFetching, isError, error } =
+ useStockLocation(location_id!, {
+ fields: "*fulfillment_sets.service_zones",
+ })
+
+ const serviceZone = stock_location?.fulfillment_sets
+ ?.find((f) => f.id === fset_id)
+ ?.service_zones.find((z) => z.id === zone_id)
+
+ if (!isPending && !isFetching && !serviceZone) {
+ throw json(
+ {
+ message: `Service zone with ID ${zone_id} was not found`,
+ },
+ 404
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer prev={`/settings/locations/${location_id}`}>
+ <RouteDrawer.Header>
+ <Heading>{t("stockLocations.serviceZones.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {serviceZone && (
+ <EditServiceZoneForm
+ zone={serviceZone}
+ fulfillmentSetId={fset_id!}
+ locationId={location_id!}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
+
+export const Component = LocationServiceZoneEdit
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/_components/edit-shipping-option-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/_components/edit-shipping-option-form.tsx
new file mode 100644
index 000000000..c58924bfb
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/_components/edit-shipping-option-form.tsx
@@ -0,0 +1,225 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, RadioGroup, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateShippingOptions } from "@hooks/api/shipping-options"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { fetchQuery } from "@lib/client"
+import {
+ getShippingProfileName,
+ isOptionEnabledInStore,
+} from "@lib/shipping-options"
+import {
+ FulfillmentSetType,
+ ShippingOptionPriceType,
+} from "@pages/settings/locations/_common/constants"
+
+type EditShippingOptionFormProps = {
+ locationId: string
+ shippingOption: HttpTypes.AdminShippingOption
+ type: FulfillmentSetType
+}
+
+const EditShippingOptionSchema = zod.object({
+ name: zod.string().min(1),
+ price_type: zod.nativeEnum(ShippingOptionPriceType),
+ enabled_in_store: zod.boolean().optional(),
+ shipping_profile_id: zod.string(),
+})
+
+export const EditShippingOptionForm = ({
+ locationId,
+ shippingOption,
+ type,
+}: EditShippingOptionFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const isPickup = type === FulfillmentSetType.Pickup
+
+ const shippingProfiles = useComboboxData({
+ queryFn: async () => {
+ const { shipping_profiles } = await fetchQuery(
+ "/vendor/shipping-profiles",
+ {
+ method: "GET",
+ }
+ )
+ return shipping_profiles
+ },
+ queryKey: ["shipping_profiles_edit_shipping_option"],
+ getOptions: (data) =>
+ data?.map((profile: any) => ({
+ label: getShippingProfileName(profile.shipping_profile.name),
+ value: profile.shipping_profile.id,
+ })),
+ defaultValue: shippingOption.shipping_profile_id,
+ })
+
+ const form = useForm<zod.infer<typeof EditShippingOptionSchema>>({
+ defaultValues: {
+ name: shippingOption.name,
+ price_type: shippingOption.price_type as ShippingOptionPriceType,
+ enabled_in_store: isOptionEnabledInStore(shippingOption),
+ shipping_profile_id: shippingOption.shipping_profile_id,
+ },
+ resolver: zodResolver(EditShippingOptionSchema),
+ })
+
+ const { mutateAsync, isPending: isLoading } = useUpdateShippingOptions(
+ shippingOption.id
+ )
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ name: values.name,
+ shipping_profile_id: values.shipping_profile_id,
+ provider_id: shippingOption.provider_id,
+ },
+ {
+ onSuccess: ({ shipping_option }) => {
+ toast.success(
+ t("stockLocations.shippingOptions.edit.successToast", {
+ name: shipping_option.name,
+ })
+ )
+ handleSuccess(`/settings/locations/${locationId}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-8">
+ {!isPickup && (
+ <Form.Field
+ control={form.control}
+ name="price_type"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t(
+ "stockLocations.shippingOptions.fields.priceType.label"
+ )}
+ </Form.Label>
+ <Form.Control>
+ <RadioGroup {...field} onValueChange={field.onChange}>
+ <RadioGroup.ChoiceBox
+ className="flex-1"
+ value={ShippingOptionPriceType.FlatRate}
+ label={t(
+ "stockLocations.shippingOptions.fields.priceType.options.fixed.label"
+ )}
+ description={t(
+ "stockLocations.shippingOptions.fields.priceType.options.fixed.hint"
+ )}
+ />
+ <RadioGroup.ChoiceBox
+ className="flex-1"
+ value={ShippingOptionPriceType.Calculated}
+ label={t(
+ "stockLocations.shippingOptions.fields.priceType.options.calculated.label"
+ )}
+ description={t(
+ "stockLocations.shippingOptions.fields.priceType.options.calculated.hint"
+ )}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ <div className="grid gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="shipping_profile_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("stockLocations.shippingOptions.fields.profile")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={shippingProfiles.options}
+ searchValue={shippingProfiles.searchValue}
+ onSearchValueChange={
+ shippingProfiles.onSearchValueChange
+ }
+ disabled={shippingProfiles.disabled}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ {/* <Divider />
+ <SwitchBox
+ control={form.control}
+ name="enabled_in_store"
+ label={t(
+ "stockLocations.shippingOptions.fields.enableInStore.label"
+ )}
+ description={t(
+ "stockLocations.shippingOptions.fields.enableInStore.hint"
+ )}
+ /> */}
+ </div>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isLoading}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/index.tsx
new file mode 100644
index 000000000..686cc6e0e
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/edit/index.tsx
@@ -0,0 +1,62 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { json, useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useShippingOptions } from "@hooks/api/shipping-options"
+import { EditShippingOptionForm } from "./_components/edit-shipping-option-form"
+import { FulfillmentSetType } from "@pages/settings/locations/_common/constants"
+
+const LocationServiceZoneShippingOptionEdit = () => {
+ const { t } = useTranslation()
+
+ const { location_id, so_id } = useParams()
+
+ const { shipping_options, isPending, isFetching, isError, error } =
+ useShippingOptions({
+ fields: "+service_zone.fulfillment_set.type",
+ })
+
+ const shippingOption = shipping_options?.find((so) => so?.id === so_id)
+
+ if (!isPending && !isFetching && !shippingOption) {
+ throw json(
+ {
+ message: `Shipping option with ID ${so_id} was not found`,
+ },
+ 404
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ const isPickup =
+ shippingOption?.service_zone.fulfillment_set.type ===
+ FulfillmentSetType.Pickup
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>
+ {t(
+ `stockLocations.${isPickup ? "pickupOptions" : "shippingOptions"}.edit.header`
+ )}
+ </Heading>
+ </RouteDrawer.Header>
+ {shippingOption && (
+ <EditShippingOptionForm
+ shippingOption={shippingOption}
+ locationId={location_id!}
+ type={
+ shippingOption.service_zone.fulfillment_set
+ .type as FulfillmentSetType
+ }
+ />
+ )}
+ </RouteDrawer>
+ )
+}
+
+export const Component = LocationServiceZoneShippingOptionEdit
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/_components/edit-shipping-options-pricing-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/_components/edit-shipping-options-pricing-form.tsx
new file mode 100644
index 000000000..7038f2e72
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/_components/edit-shipping-options-pricing-form.tsx
@@ -0,0 +1,357 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import * as zod from "zod"
+
+import { HttpTypes } from "@medusajs/types"
+import { Button, toast } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { DataGrid } from "@components/data-grid"
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals/index"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+import { useUpdateShippingOptions } from "@hooks/api/shipping-options"
+import { useStore } from "@hooks/api/store"
+import { castNumber } from "@lib/cast-number"
+import { ConditionalPriceForm } from "@pages/settings/locations/_common/components/conditional-price-form"
+import { ShippingOptionPriceProvider } from "@pages/settings/locations/_common/components/shipping-option-price-provider"
+import {
+ CONDITIONAL_PRICES_STACKED_MODAL_ID,
+ ITEM_TOTAL_ATTRIBUTE,
+ REGION_ID_ATTRIBUTE,
+} from "@pages/settings/locations/_common/constants"
+import { useShippingOptionPriceColumns } from "@pages/settings/locations/_common/hooks/use-shipping-option-price-columns"
+import {
+ UpdateConditionalPrice,
+ UpdateConditionalPriceSchema,
+} from "@pages/settings/locations/_common/schema"
+import { ConditionalPriceInfo } from "@pages/settings/locations/_common/types"
+import { useRegions } from "@hooks/api"
+
+type PriceRecord = {
+ id?: string
+ currency_code?: string
+ region_id?: string
+ amount: number
+}
+
+const EditShippingOptionPricingSchema = zod.object({
+ region_prices: zod.record(
+ zod.string(),
+ zod.string().or(zod.number()).optional()
+ ),
+ currency_prices: zod.record(
+ zod.string(),
+ zod.string().or(zod.number()).optional()
+ ),
+ conditional_region_prices: zod.record(
+ zod.string(),
+ zod.array(UpdateConditionalPriceSchema)
+ ),
+ conditional_currency_prices: zod.record(
+ zod.string(),
+ zod.array(UpdateConditionalPriceSchema)
+ ),
+})
+
+type EditShippingOptionPricingFormProps = {
+ shippingOption: HttpTypes.AdminShippingOption
+}
+
+export function EditShippingOptionsPricingForm({
+ shippingOption,
+}: EditShippingOptionPricingFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { getIsOpen, setIsOpen } = useStackedModal()
+ const [selectedPrice, setSelectedPrice] =
+ useState<ConditionalPriceInfo | null>(null)
+
+ const onOpenConditionalPricesModal = (info: ConditionalPriceInfo) => {
+ setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, true)
+ setSelectedPrice(info)
+ }
+
+ const onCloseConditionalPricesModal = () => {
+ setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, false)
+ setSelectedPrice(null)
+ }
+
+ const form = useForm<zod.infer<typeof EditShippingOptionPricingSchema>>({
+ defaultValues: getDefaultValues(shippingOption.prices),
+ resolver: zodResolver(EditShippingOptionPricingSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateShippingOptions(shippingOption.id)
+
+ const {
+ store,
+ isLoading: isStoreLoading,
+ isError: isStoreError,
+ error: storeError,
+ } = useStore()
+
+ const currencies = useMemo(
+ () => store?.supported_currencies?.map((c) => c.currency_code) || [],
+ [store]
+ )
+
+ const { price_preferences: pricePreferences } = usePricePreferences({})
+
+ const { regions } = useRegions({
+ fields: "id,name,currency_code",
+ limit: 999,
+ })
+
+ const { setCloseOnEscape } = useRouteModal()
+
+ const columns = useShippingOptionPriceColumns({
+ name: shippingOption.name,
+ currencies,
+ regions,
+ pricePreferences,
+ })
+
+ const data = useMemo(() => [[...(currencies || [])]], [currencies])
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ // const currencyPrices = Object.entries(data.currency_prices)
+ // .map(([code, value]) => {
+ // if (
+ // !value ||
+ // !currencies.some((c) => c.toLowerCase() === code.toLowerCase())
+ // ) {
+ // return undefined
+ // }
+
+ // const priceRecord: PriceRecord = {
+ // currency_code: code,
+ // amount: castNumber(value),
+ // }
+
+ // const existingPrice = shippingOption.prices.find(
+ // (p) => p.currency_code === code && !p.price_rules!.length
+ // )
+
+ // if (existingPrice) {
+ // priceRecord.id = existingPrice.id
+ // }
+
+ // return priceRecord
+ // })
+ // .filter((p): p is PriceRecord => !!p)
+
+ // const conditionalCurrencyPrices = Object.entries(
+ // data.conditional_currency_prices
+ // ).flatMap(([currency_code, value]) =>
+ // value?.map((rule) => ({
+ // id: rule.id,
+ // currency_code,
+ // amount: castNumber(rule.amount),
+ // rules: buildShippingOptionPriceRules(rule),
+ // }))
+ // )
+
+ /**
+ * TODO: If we try to update an existing region price the API throws an error.
+ * Instead we re-create region prices.
+ */
+ const regionPrices = Object.entries(data.region_prices)
+ .map(([region_id, value]) => {
+ const priceRecord: PriceRecord = {
+ region_id,
+ amount: castNumber(value || 0),
+ // currency_code: regions?.find((r) => r.id === region_id)
+ // ?.currency_code,
+ }
+
+ return priceRecord
+ })
+ .filter((p): p is PriceRecord => !!p)
+
+ // const conditionalRegionPrices = Object.entries(
+ // data.conditional_region_prices
+ // ).flatMap(([region_id, value]) =>
+ // value?.map((rule) => ({
+ // id: rule.id,
+ // region_id,
+ // amount: castNumber(rule.amount),
+ // rules: buildShippingOptionPriceRules(rule),
+ // }))
+ // )
+
+ const allPrices = [
+ // ...currencyPrices,
+ // ...conditionalCurrencyPrices,
+ ...regionPrices,
+ // ...conditionalRegionPrices,
+ ]
+
+ await mutateAsync(
+ { prices: allPrices },
+ {
+ onSuccess: () => {
+ toast.success(t("general.success"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ const isLoading = isStoreLoading || !currencies
+
+ if (isStoreError) {
+ throw storeError
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header />
+
+ <RouteFocusModal.Body>
+ <StackedFocusModal
+ id={CONDITIONAL_PRICES_STACKED_MODAL_ID}
+ onOpenChangeCallback={(open) => {
+ if (!open) {
+ setSelectedPrice(null)
+ }
+ }}
+ >
+ <ShippingOptionPriceProvider
+ onOpenConditionalPricesModal={onOpenConditionalPricesModal}
+ onCloseConditionalPricesModal={onCloseConditionalPricesModal}
+ >
+ <div className="flex size-full flex-col divide-y overflow-hidden">
+ <DataGrid
+ isLoading={isLoading}
+ data={data}
+ columns={columns}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ disableInteractions={getIsOpen(
+ CONDITIONAL_PRICES_STACKED_MODAL_ID
+ )}
+ />
+ </div>
+ {selectedPrice && (
+ <ConditionalPriceForm info={selectedPrice} variant="update" />
+ )}
+ </ShippingOptionPriceProvider>
+ </StackedFocusModal>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ className="whitespace-nowrap"
+ isLoading={isPending}
+ onClick={handleSubmit}
+ type="button"
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const findRuleValue = (
+ rules: HttpTypes.AdminShippingOptionPriceRule[],
+ operator: string
+) => {
+ const fallbackValue = ["eq", "gt", "lt"].includes(operator) ? undefined : null
+
+ return (
+ rules?.find(
+ (r) => r.attribute === ITEM_TOTAL_ATTRIBUTE && r.operator === operator
+ )?.value || fallbackValue
+ )
+}
+
+const mapToConditionalPrice = (
+ price: HttpTypes.AdminShippingOptionPrice
+): UpdateConditionalPrice => {
+ const rules = price.price_rules || []
+
+ return {
+ id: price.id,
+ amount: price.amount,
+ gte: findRuleValue(rules, "gte"),
+ lte: findRuleValue(rules, "lte"),
+ gt: findRuleValue(rules, "gt") as undefined | null,
+ lt: findRuleValue(rules, "lt") as undefined | null,
+ eq: findRuleValue(rules, "eq") as undefined | null,
+ }
+}
+
+const getDefaultValues = (prices: HttpTypes.AdminShippingOptionPrice[]) => {
+ const hasAttributes = (
+ price: HttpTypes.AdminShippingOptionPrice,
+ required: string[],
+ forbidden: string[] = []
+ ) => {
+ const attributes = price.price_rules?.map((r) => r.attribute) || []
+ return (
+ required.every((attr) => attributes.includes(attr)) &&
+ !forbidden.some((attr) => attributes.includes(attr))
+ )
+ }
+
+ const currency_prices: Record<string, number> = {}
+ const conditional_currency_prices: Record<string, UpdateConditionalPrice[]> =
+ {}
+ const region_prices: Record<string, number> = {}
+ const conditional_region_prices: Record<string, UpdateConditionalPrice[]> = {}
+
+ prices.forEach((price) => {
+ if (!price.price_rules?.length) {
+ currency_prices[price.currency_code!] = price.amount
+ return
+ }
+
+ const region_id = price.price_rules?.find(
+ (r) => r.attribute === REGION_ID_ATTRIBUTE
+ )?.value
+
+ if (region_id) {
+ region_prices[region_id] = price.amount
+ return
+ }
+
+ if (hasAttributes(price, [ITEM_TOTAL_ATTRIBUTE], [REGION_ID_ATTRIBUTE])) {
+ const code = price.currency_code!
+ if (!conditional_currency_prices[code]) {
+ conditional_currency_prices[code] = []
+ }
+ conditional_currency_prices[code].push(mapToConditionalPrice(price))
+ return
+ }
+ })
+
+ return {
+ currency_prices,
+ conditional_currency_prices,
+ region_prices,
+ conditional_region_prices,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/index.tsx
new file mode 100644
index 000000000..2fc40d027
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/[so_id]/pricing/index.tsx
@@ -0,0 +1,38 @@
+import { json, useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useShippingOption } from "@hooks/api/shipping-options"
+import { EditShippingOptionsPricingForm } from "./_components/edit-shipping-options-pricing-form"
+
+function LocationServiceZoneShippingOptionPricing() {
+ const { so_id, location_id } = useParams()
+
+ if (!so_id) {
+ throw json({
+ message: "Shipping Option ID paramater is missing",
+ status: 404,
+ })
+ }
+
+ const {
+ shipping_option: shippingOption,
+ isError,
+ error,
+ } = useShippingOption(so_id, {
+ fields: "*prices,*prices.price_rules",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal prev={`/settings/locations/${location_id}`}>
+ {shippingOption && (
+ <EditShippingOptionsPricingForm shippingOption={shippingOption} />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationServiceZoneShippingOptionPricing
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-option-details-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-option-details-form.tsx
new file mode 100644
index 000000000..22071f705
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-option-details-form.tsx
@@ -0,0 +1,274 @@
+import { Heading, Input, RadioGroup, Text } from "@medusajs/ui"
+import { UseFormReturn } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { VendorExtendedAdminServiceZone } from "@custom-types/stock-location"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { fetchQuery } from "@lib/client"
+import {
+ FulfillmentSetType,
+ ShippingOptionPriceType,
+} from "@pages/settings/locations/_common/constants"
+import { CreateShippingOptionSchema } from "./schema"
+
+type CreateShippingOptionDetailsFormProps = {
+ form: UseFormReturn<CreateShippingOptionSchema>
+ isReturn?: boolean
+ zone: VendorExtendedAdminServiceZone
+ type: FulfillmentSetType
+}
+
+export const CreateShippingOptionDetailsForm = ({
+ form,
+ isReturn = false,
+ zone,
+ type
+}: CreateShippingOptionDetailsFormProps) => {
+ const { t } = useTranslation()
+
+ const isPickup = type === FulfillmentSetType.Pickup
+
+ const shippingProfiles = useComboboxData({
+ queryFn: () =>
+ fetchQuery(`/vendor/shipping-profiles`, {
+ method: "GET",
+ }),
+ queryKey: ["shipping_profiles_create_shipping_option"],
+ getOptions: (data) =>
+ (data.shipping_profiles || []).map((profile: any) => ({
+ label: profile.shipping_profile.name.includes(":")
+ ? profile.shipping_profile.name.split(":")[1]
+ : profile.shipping_profile.name,
+ value: profile.shipping_profile.id,
+ })),
+ })
+
+ // const fulfillmentProviders = useComboboxData({
+ // queryFn: (params) =>
+ // sdk.admin.fulfillmentProvider.list({
+ // ...params,
+ // stock_location_id: locationId,
+ // }),
+ // queryKey: ['fulfillment_providers'],
+ // getOptions: (data) =>
+ // data.fulfillment_providers.map((provider) => ({
+ // label: formatProvider(provider.id),
+ // value: provider.id,
+ // })),
+ // });
+
+ return (
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-6 py-16">
+ <div>
+ <Heading>
+ {t(
+ `stockLocations.shippingOptions.create.${
+ isPickup ? "pickup" : isReturn ? "returns" : "shipping"
+ }.header`,
+ {
+ zone: zone.name,
+ }
+ )}
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t(
+ `stockLocations.shippingOptions.create.${
+ isReturn ? "returns" : isPickup ? "pickup" : "shipping"
+ }.hint`
+ )}
+ </Text>
+ </div>
+
+ {!isPickup && (
+ <Form.Field
+ control={form.control}
+ name="price_type"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("stockLocations.shippingOptions.fields.priceType.label")}
+ </Form.Label>
+ <Form.Control>
+ <RadioGroup
+ className="grid grid-cols-1 gap-4 md:grid-cols-2"
+ {...field}
+ onValueChange={field.onChange}
+ >
+ <RadioGroup.ChoiceBox
+ className="flex-1"
+ value={ShippingOptionPriceType.FlatRate}
+ label={t(
+ "stockLocations.shippingOptions.fields.priceType.options.fixed.label"
+ )}
+ description={t(
+ "stockLocations.shippingOptions.fields.priceType.options.fixed.hint"
+ )}
+ />
+ <RadioGroup.ChoiceBox
+ className="flex-1"
+ value={ShippingOptionPriceType.Calculated}
+ label={t(
+ "stockLocations.shippingOptions.fields.priceType.options.calculated.label"
+ )}
+ description={t(
+ "stockLocations.shippingOptions.fields.priceType.options.calculated.hint"
+ )}
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="shipping_profile_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("stockLocations.shippingOptions.fields.profile")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={shippingProfiles.options}
+ searchValue={shippingProfiles.searchValue}
+ onSearchValueChange={shippingProfiles.onSearchValueChange}
+ disabled={shippingProfiles.disabled}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ {/* <div className='grid grid-cols-1 gap-4 md:grid-cols-2'>
+ <Form.Field
+ control={form.control}
+ name='provider_id'
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={t(
+ 'stockLocations.fulfillmentProviders.shippingOptionsTooltip'
+ )}
+ >
+ {t(
+ 'stockLocations.shippingOptions.fields.provider'
+ )}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ onChange={(e) => {
+ field.onChange(e);
+ form.setValue(
+ 'fulfillment_option_id',
+ ''
+ );
+ }}
+ options={fulfillmentProviders.options}
+ searchValue={
+ fulfillmentProviders.searchValue
+ }
+ onSearchValueChange={
+ fulfillmentProviders.onSearchValueChange
+ }
+ disabled={
+ fulfillmentProviders.disabled
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name='fulfillment_option_id'
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t(
+ 'stockLocations.shippingOptions.fields.fulfillmentOption'
+ )}
+ </Form.Label>
+ <Form.Control>
+ <Select
+ {...field}
+ onValueChange={field.onChange}
+ disabled={!selectedProviderId}
+ key={selectedProviderId}
+ >
+ <Select.Trigger ref={field.ref}>
+ <Select.Value />
+ </Select.Trigger>
+
+ <Select.Content>
+ {fulfillmentProviderOptions
+ ?.filter(
+ (fo) =>
+ !!fo.is_return === isReturn
+ )
+ .map((option) => (
+ <Select.Item
+ value={option.id}
+ key={option.id}
+ >
+ {option.name || option.id}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ );
+ }}
+ />
+ </div> */}
+
+ {/* <Divider />
+ <SwitchBox
+ control={form.control}
+ name="enabled_in_store"
+ label={t("stockLocations.shippingOptions.fields.enableInStore.label")}
+ description={t(
+ "stockLocations.shippingOptions.fields.enableInStore.hint"
+ )}
+ /> */}
+ </div>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-form.tsx
new file mode 100644
index 000000000..7b8596120
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-form.tsx
@@ -0,0 +1,322 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { VendorExtendedAdminServiceZone } from "@custom-types/stock-location"
+import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
+import { useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+
+import { useState } from "react"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateShippingOptions } from "@hooks/api/shipping-options"
+import { castNumber } from "@lib/cast-number"
+import {
+ FulfillmentSetType,
+ ShippingOptionPriceType,
+} from "@pages/settings/locations/_common/constants"
+import { CreateShippingOptionDetailsForm } from "./create-shipping-option-details-form"
+import { CreateShippingOptionsPricesForm } from "./create-shipping-options-prices-form"
+import {
+ CreateShippingOptionDetailsSchema,
+ CreateShippingOptionSchema,
+} from "./schema"
+import { useFulfillmentProviderOptions } from "@hooks/api"
+
+enum Tab {
+ DETAILS = "details",
+ PRICING = "pricing",
+}
+
+type CreateShippingOptionFormProps = {
+ zone: VendorExtendedAdminServiceZone
+ locationId: string
+ isReturn?: boolean
+ type: FulfillmentSetType
+}
+
+export function CreateShippingOptionsForm({
+ zone,
+ isReturn,
+ locationId,
+ type,
+}: CreateShippingOptionFormProps) {
+ const [activeTab, setActiveTab] = useState<Tab>(Tab.DETAILS)
+ const [validDetails, setValidDetails] = useState(false)
+
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<CreateShippingOptionSchema>({
+ defaultValues: {
+ name: "",
+ price_type: ShippingOptionPriceType.FlatRate,
+ enabled_in_store: true,
+ shipping_profile_id: "",
+ provider_id: "manual_manual",
+ fulfillment_option_id: "",
+ region_prices: {},
+ currency_prices: {},
+ conditional_region_prices: {},
+ conditional_currency_prices: {},
+ },
+ resolver: zodResolver(CreateShippingOptionSchema),
+ })
+
+ const selectedProviderId = useWatch({
+ control: form.control,
+ name: "provider_id",
+ })
+
+ const { fulfillment_options: fulfillmentProviderOptions } =
+ useFulfillmentProviderOptions(selectedProviderId, {
+ enabled: !!selectedProviderId,
+ })
+
+ const isCalculatedPriceType =
+ form.watch("price_type") === ShippingOptionPriceType.Calculated
+
+ const { mutateAsync, isPending: isLoading } = useCreateShippingOptions()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const currencyPrices = Object.entries(data.currency_prices)
+ .map(([code, value]) => {
+ if (!value) {
+ return undefined
+ }
+
+ return {
+ currency_code: code,
+ amount: castNumber(value),
+ }
+ })
+ .filter((p): p is { currency_code: string; amount: number } => !!p)
+
+ const regionPrices = Object.entries(data.region_prices)
+ .map(([region, value]) => {
+ if (!value) {
+ return undefined
+ }
+
+ return {
+ region_id: region,
+ amount: castNumber(value),
+ }
+ })
+ .filter((p): p is { region_id: string; amount: number } => !!p)
+
+ const fulfillmentOptionData = fulfillmentProviderOptions?.find(
+ (fo) => fo.id === data.fulfillment_option_id
+ )!
+
+ await mutateAsync(
+ {
+ name: data.name,
+ service_zone_id: zone.id,
+ shipping_profile_id: data.shipping_profile_id,
+ provider_id: data.provider_id,
+ prices: [...currencyPrices, ...regionPrices],
+ data: fulfillmentOptionData as unknown as Record<string, unknown>,
+ rules: [
+ {
+ value: isReturn ? "true" : "false",
+ attribute: "is_return",
+ operator: "eq",
+ },
+ {
+ value: "true",
+ attribute: "enabled_in_store",
+ operator: "eq",
+ },
+ ],
+ type: {
+ // TODO: FETCH TYPES
+ label: "Type label",
+ description: "Type description",
+ code: "type-code",
+ },
+ },
+ {
+ onSuccess: ({ shipping_option }) => {
+ toast.success(
+ t(
+ `stockLocations.shippingOptions.create.${
+ isReturn ? "returns" : "shipping"
+ }.successToast`,
+ { name: shipping_option?.name }
+ )
+ )
+ handleSuccess(`/settings/locations/${locationId}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ const onTabChange = (tab: Tab) => {
+ if (tab === Tab.PRICING) {
+ form.clearErrors()
+
+ const result = CreateShippingOptionDetailsSchema.safeParse({
+ ...form.getValues(),
+ })
+
+ if (!result.success) {
+ const [firstError, ...rest] = result.error.errors
+
+ for (const error of rest) {
+ const _path = error.path.join(".") as keyof CreateShippingOptionSchema
+
+ form.setError(_path, {
+ message: error.message,
+ type: error.code,
+ })
+ }
+
+ // Focus the first error
+ form.setError(
+ firstError.path.join(".") as keyof CreateShippingOptionSchema,
+ {
+ message: firstError.message,
+ type: firstError.code,
+ },
+ {
+ shouldFocus: true,
+ }
+ )
+
+ setValidDetails(false)
+ return
+ }
+
+ setValidDetails(true)
+ }
+
+ setActiveTab(tab)
+ }
+
+ const pricesStatus: ProgressStatus =
+ form.getFieldState("currency_prices")?.isDirty ||
+ form.getFieldState("region_prices")?.isDirty ||
+ activeTab === Tab.PRICING
+ ? "in-progress"
+ : "not-started"
+
+ const detailsStatus: ProgressStatus = validDetails
+ ? "completed"
+ : "in-progress"
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col"
+ onSubmit={handleSubmit}
+ onKeyDown={(e) => {
+ const isEnterKey = e.key === "Enter"
+ const isModifierPressed = e.metaKey || e.ctrlKey
+ const shouldContinueToPricing =
+ activeTab !== Tab.PRICING && !isCalculatedPriceType
+
+ if (!isEnterKey) {
+ return
+ }
+ e.preventDefault()
+
+ if (!isModifierPressed) {
+ return
+ }
+
+ if (shouldContinueToPricing) {
+ e.stopPropagation()
+ onTabChange(Tab.PRICING)
+ return
+ }
+
+ handleSubmit()
+ }}
+ >
+ <ProgressTabs
+ value={activeTab}
+ className="flex h-full flex-col overflow-hidden"
+ onValueChange={(tab) => onTabChange(tab as Tab)}
+ >
+ <RouteFocusModal.Header>
+ <ProgressTabs.List className="border-ui-border-base -my-2 ml-2 min-w-0 flex-1 border-l">
+ <ProgressTabs.Trigger
+ value={Tab.DETAILS}
+ status={detailsStatus}
+ className="w-full max-w-[200px]"
+ >
+ <span className="w-full cursor-auto overflow-hidden text-ellipsis whitespace-nowrap">
+ {t("stockLocations.shippingOptions.create.tabs.details")}
+ </span>
+ </ProgressTabs.Trigger>
+ {!isCalculatedPriceType && (
+ <ProgressTabs.Trigger
+ value={Tab.PRICING}
+ status={pricesStatus}
+ className="w-full max-w-[200px]"
+ >
+ <span className="w-full overflow-hidden text-ellipsis whitespace-nowrap">
+ {t("stockLocations.shippingOptions.create.tabs.prices")}
+ </span>
+ </ProgressTabs.Trigger>
+ )}
+ </ProgressTabs.List>
+ </RouteFocusModal.Header>
+
+ <RouteFocusModal.Body className="size-full overflow-hidden">
+ <ProgressTabs.Content
+ value={Tab.DETAILS}
+ className="size-full overflow-y-auto"
+ >
+ <CreateShippingOptionDetailsForm
+ form={form}
+ zone={zone}
+ isReturn={isReturn}
+ type={type}
+ />
+ </ProgressTabs.Content>
+ <ProgressTabs.Content value={Tab.PRICING} className="size-full">
+ <CreateShippingOptionsPricesForm form={form} type={type} />
+ </ProgressTabs.Content>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ {activeTab === Tab.PRICING || isCalculatedPriceType ? (
+ <Button
+ size="small"
+ className="whitespace-nowrap"
+ isLoading={isLoading}
+ key="submit-btn"
+ type="submit"
+ >
+ {t("actions.save")}
+ </Button>
+ ) : (
+ <Button
+ size="small"
+ className="whitespace-nowrap"
+ isLoading={isLoading}
+ onClick={() => onTabChange(Tab.PRICING)}
+ key="continue-btn"
+ type="button"
+ >
+ {t("actions.continue")}
+ </Button>
+ )}
+ </div>
+ </RouteFocusModal.Footer>
+ </ProgressTabs>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-prices-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-prices-form.tsx
new file mode 100644
index 000000000..7417b8fe3
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/create-shipping-options-prices-form.tsx
@@ -0,0 +1,144 @@
+import { useEffect, useMemo, useState } from "react"
+import { UseFormReturn, useWatch } from "react-hook-form"
+
+import { DataGrid } from "@components/data-grid"
+import {
+ StackedFocusModal,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals"
+import { useRegions } from "@hooks/api/regions"
+import { useStore } from "@hooks/api/store"
+import { ConditionalPriceForm } from "@pages/settings/locations/_common/components/conditional-price-form"
+import { ShippingOptionPriceProvider } from "@pages/settings/locations/_common/components/shipping-option-price-provider"
+import {
+ FulfillmentSetType,
+ CONDITIONAL_PRICES_STACKED_MODAL_ID,
+} from "@pages/settings/locations/_common/constants"
+import { useShippingOptionPriceColumns } from "@pages/settings/locations/_common/hooks/use-shipping-option-price-columns"
+import { ConditionalPriceInfo } from "@pages/settings/locations/_common/types"
+import { CreateShippingOptionSchema } from "./schema"
+
+type PricingPricesFormProps = {
+ form: UseFormReturn<CreateShippingOptionSchema>
+ type: FulfillmentSetType
+}
+
+export const CreateShippingOptionsPricesForm = ({
+ form,
+ type,
+}: PricingPricesFormProps) => {
+ const isPickup = type === FulfillmentSetType.Pickup
+ const { getIsOpen, setIsOpen } = useStackedModal()
+ const [selectedPrice, setSelectedPrice] =
+ useState<ConditionalPriceInfo | null>(null)
+
+ const onOpenConditionalPricesModal = (info: ConditionalPriceInfo) => {
+ setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, true)
+ setSelectedPrice(info)
+ }
+
+ const onCloseConditionalPricesModal = () => {
+ setIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID, false)
+ setSelectedPrice(null)
+ }
+
+ const {
+ store,
+ isLoading: isStoreLoading,
+ isError: isStoreError,
+ error: storeError,
+ } = useStore()
+
+ const currencies = useMemo(
+ () => store?.supported_currencies?.map((c) => c.currency_code) || [],
+ [store]
+ )
+
+ const {
+ regions,
+ isLoading: isRegionsLoading,
+ isError: isRegionsError,
+ error: regionsError,
+ } = useRegions({
+ fields: "id,name,currency_code",
+ limit: 999,
+ })
+
+ const { setCloseOnEscape } = useRouteModal()
+
+ const name = useWatch({
+ control: form.control,
+ name: "name",
+ })
+
+ const columns = useShippingOptionPriceColumns({
+ name,
+ currencies,
+ regions,
+ })
+
+ const isLoading = isStoreLoading || !store || isRegionsLoading || !regions
+
+ const data = useMemo(
+ () => [[...(currencies || []), ...(regions || [])]],
+ [currencies, regions]
+ )
+
+ /**
+ * Prefill prices with 0 if createing a pickup (shipping) option
+ */
+ useEffect(() => {
+ if (!isLoading && isPickup) {
+ if (currencies.length > 0) {
+ currencies.forEach((currency) => {
+ form.setValue(`currency_prices.${currency}`, "0")
+ })
+ }
+
+ if (regions.length > 0) {
+ regions.forEach((region) => {
+ form.setValue(`region_prices.${region.id}`, "0")
+ })
+ }
+ }
+ }, [isLoading, isPickup])
+
+ if (isStoreError) {
+ throw storeError
+ }
+
+ if (isRegionsError) {
+ throw regionsError
+ }
+
+ return (
+ <StackedFocusModal
+ id={CONDITIONAL_PRICES_STACKED_MODAL_ID}
+ onOpenChangeCallback={(open) => {
+ if (!open) {
+ setSelectedPrice(null)
+ }
+ }}
+ >
+ <ShippingOptionPriceProvider
+ onOpenConditionalPricesModal={onOpenConditionalPricesModal}
+ onCloseConditionalPricesModal={onCloseConditionalPricesModal}
+ >
+ <div className="flex size-full flex-col divide-y overflow-hidden">
+ <DataGrid
+ isLoading={isLoading}
+ data={data}
+ columns={columns}
+ state={form}
+ onEditingChange={(editing) => setCloseOnEscape(!editing)}
+ disableInteractions={getIsOpen(CONDITIONAL_PRICES_STACKED_MODAL_ID)}
+ />
+ {selectedPrice && (
+ <ConditionalPriceForm info={selectedPrice} variant="create" />
+ )}
+ </div>
+ </ShippingOptionPriceProvider>
+ </StackedFocusModal>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/index.ts b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/index.ts
new file mode 100644
index 000000000..572f2b771
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/index.ts
@@ -0,0 +1 @@
+export * from "./create-shipping-options-form.tsx"
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/schema.ts b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/schema.ts
new file mode 100644
index 000000000..4bbd82ca3
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/_components/schema.ts
@@ -0,0 +1,43 @@
+import { z } from "zod"
+import { ShippingOptionPriceType } from "@pages/settings/locations/_common/constants"
+import { ConditionalPriceSchema } from "@pages/settings/locations/_common/schema"
+
+export type CreateShippingOptionSchema = z.infer<
+ typeof CreateShippingOptionSchema
+>
+
+export const CreateShippingOptionDetailsSchema = z.object({
+ name: z.string().min(1),
+ price_type: z.nativeEnum(ShippingOptionPriceType),
+ enabled_in_store: z.boolean(),
+ shipping_profile_id: z.string().min(1),
+ provider_id: z.string().min(1),
+ fulfillment_option_id: z.string().optional(),
+})
+
+export const ShippingOptionConditionalPriceSchema = z.object({
+ conditional_region_prices: z.record(
+ z.string(),
+ z.array(ConditionalPriceSchema).optional()
+ ),
+ conditional_currency_prices: z.record(
+ z.string(),
+ z.array(ConditionalPriceSchema).optional()
+ ),
+})
+
+export type ShippingOptionConditionalPriceSchemaType = z.infer<
+ typeof ShippingOptionConditionalPriceSchema
+>
+
+export const CreateShippingOptionSchema = z
+ .object({
+ region_prices: z.record(z.string(), z.string().optional()),
+ currency_prices: z.record(z.string(), z.string().optional()),
+ })
+ .merge(CreateShippingOptionDetailsSchema)
+ .merge(ShippingOptionConditionalPriceSchema)
+
+export type CreateShippingOptionSchemaType = z.infer<
+ typeof CreateShippingOptionSchema
+>
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/constants.ts b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/constants.ts
new file mode 100644
index 000000000..a616c286c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/constants.ts
@@ -0,0 +1,2 @@
+export const LOC_CREATE_SHIPPING_OPTION_FIELDS =
+ "*fulfillment_sets,*fulfillment_sets.service_zones,*fulfillment_sets.service_zones.shipping_options"
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/index.tsx
new file mode 100644
index 000000000..e40b465d8
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zone/[zone_id]/shipping-option/create/index.tsx
@@ -0,0 +1,61 @@
+import { json, useParams, useSearchParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { CreateShippingOptionsForm } from "./_components/create-shipping-options-form"
+import { LOC_CREATE_SHIPPING_OPTION_FIELDS } from "./constants"
+import { FulfillmentSetType } from "@pages/settings/locations/_common/constants"
+
+function LocationServiceZoneShippingOptionCreate() {
+ const { location_id, fset_id, zone_id } = useParams()
+ const [searchParams] = useSearchParams()
+ const isReturn = searchParams.has("is_return")
+
+ const { stock_location, isPending, isFetching, isError, error } =
+ useStockLocation(location_id!, {
+ fields: LOC_CREATE_SHIPPING_OPTION_FIELDS,
+ })
+
+ const fulfillmentSet = stock_location?.fulfillment_sets?.find(
+ (f) => f.id === fset_id
+ )
+
+ if (!isPending && !isFetching && !fulfillmentSet) {
+ throw json(
+ {
+ message: `Fulfillment set with ID ${fset_id} was not found`,
+ },
+ 404
+ )
+ }
+
+ const zone = fulfillmentSet?.service_zones?.find((z) => z.id === zone_id)
+
+ if (!isPending && !isFetching && !zone) {
+ throw json(
+ {
+ message: `Service zone with ID ${zone_id} was not found`,
+ },
+ 404
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal prev={`/settings/locations/${location_id}`}>
+ {zone && (
+ <CreateShippingOptionsForm
+ zone={zone}
+ isReturn={isReturn}
+ locationId={location_id!}
+ type={fulfillmentSet!.type as FulfillmentSetType}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationServiceZoneShippingOptionCreate
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/_components/create-service-zone-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/_components/create-service-zone-form.tsx
new file mode 100644
index 000000000..5d25e189e
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/_components/create-service-zone-form.tsx
@@ -0,0 +1,146 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { VendorExtendedAdminStockLocation, VendorExtendedAdminFulfillmentSet } from "@custom-types/stock-location"
+import { Button, Heading, InlineTip, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateFulfillmentSetServiceZone } from "@hooks/api/fulfillment-sets"
+import { GeoZoneForm } from "@pages/settings/locations/_common/components/geo-zone-form"
+import {
+ FulfillmentSetType,
+ GEO_ZONE_STACKED_MODAL_ID,
+} from "@pages/settings/locations/_common/constants"
+
+const CreateServiceZoneSchema = z.object({
+ name: z.string().min(1),
+ countries: z
+ .array(z.object({ iso_2: z.string().min(2), display_name: z.string() }))
+ .min(1),
+})
+
+type CreateServiceZoneFormProps = {
+ fulfillmentSet: VendorExtendedAdminFulfillmentSet
+ type: FulfillmentSetType
+ location: VendorExtendedAdminStockLocation
+}
+
+export function CreateServiceZoneForm({
+ fulfillmentSet,
+ type,
+ location,
+}: CreateServiceZoneFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof CreateServiceZoneSchema>>({
+ defaultValues: {
+ name: "",
+ countries: [],
+ },
+ resolver: zodResolver(CreateServiceZoneSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateFulfillmentSetServiceZone(
+ fulfillmentSet.id
+ )
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ name: data.name,
+ geo_zones: data.countries.map(({ iso_2 }) => ({
+ country_code: iso_2,
+ type: "country",
+ })),
+ },
+ {
+ onSuccess: () => {
+ toast.success(
+ t("stockLocations.serviceZones.create.successToast", {
+ name: data.name,
+ })
+ )
+
+ handleSuccess(`/settings/locations/${location.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col items-center overflow-auto">
+ <StackedFocusModal id={GEO_ZONE_STACKED_MODAL_ID}>
+ <div className="flex flex-1 flex-col items-center">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <Heading>
+ {type === FulfillmentSetType.Pickup
+ ? t("stockLocations.serviceZones.create.headerPickup", {
+ location: location.name,
+ })
+ : t("stockLocations.serviceZones.create.headerShipping", {
+ location: location.name,
+ })}
+ </Heading>
+
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ <InlineTip label={t("general.tip")}>
+ {t("stockLocations.serviceZones.fields.tip")}
+ </InlineTip>
+
+ <GeoZoneForm form={form} />
+ </div>
+ </div>
+ <GeoZoneForm.AreaDrawer form={form} />
+ </StackedFocusModal>
+ </RouteFocusModal.Body>
+
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/index.tsx
new file mode 100644
index 000000000..a1cf146e6
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/fulfillment-set/[fset_id]/service-zones/create/index.tsx
@@ -0,0 +1,49 @@
+import { json, useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { CreateServiceZoneForm } from "./_components/create-service-zone-form"
+import { FulfillmentSetType } from "@pages/settings/locations/_common/constants"
+
+function LocationCreateServiceZone() {
+ const { fset_id, location_id } = useParams()
+
+ const { stock_location, isPending, isFetching, isError, error } =
+ useStockLocation(location_id!, {
+ fields: "*fulfillment_sets",
+ })
+
+ const fulfillmentSet = stock_location?.fulfillment_sets?.find(
+ (f) => f.id === fset_id
+ )
+
+ const type: FulfillmentSetType =
+ fulfillmentSet?.type === FulfillmentSetType.Pickup
+ ? FulfillmentSetType.Pickup
+ : FulfillmentSetType.Shipping
+
+ if (!isPending && !isFetching && !fulfillmentSet) {
+ throw json(
+ { message: `Fulfillment set with ID: ${fset_id} was not found.` },
+ 404
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal prev={`/settings/locations/${location_id}`}>
+ {fulfillmentSet && (
+ <CreateServiceZoneForm
+ fulfillmentSet={fulfillmentSet}
+ location={stock_location!}
+ type={type}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationCreateServiceZone
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/index.tsx
new file mode 100644
index 000000000..0119695f3
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/index.tsx
@@ -0,0 +1,65 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { LocationGeneralSection } from "./_components/location-general-section"
+import { locationLoader } from "./loader"
+
+import { TwoColumnPageSkeleton } from "@components/common/skeleton"
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import LocationsFulfillmentProvidersSection from "./_components/location-fulfillment-providers-section"
+import { LOCATION_DETAILS_FIELD } from "./constants"
+
+const LocationDetail = () => {
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof locationLoader>
+ >
+
+ const { location_id } = useParams()
+ const {
+ stock_location: location,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useStockLocation(
+ location_id!,
+ { fields: LOCATION_DETAILS_FIELD },
+ { initialData }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !location) {
+ return (
+ <TwoColumnPageSkeleton mainSections={3} sidebarSections={2} showJSON />
+ )
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("location.details.after"),
+ before: getWidgets("location.details.before"),
+ sideAfter: getWidgets("location.details.side.after"),
+ sideBefore: getWidgets("location.details.side.before"),
+ }}
+ data={location}
+ hasOutlet
+ >
+ <TwoColumnPage.Main>
+ <LocationGeneralSection location={location} />
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <LocationsFulfillmentProvidersSection location={location} />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
+
+export const Component = LocationDetail
+export { locationLoader as loader } from "./loader"
+export { LocationDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/loader.ts b/packages/vendor/src/pages/settings/locations/[location_id]/loader.ts
new file mode 100644
index 000000000..6b29659ee
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/loader.ts
@@ -0,0 +1,24 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { stockLocationsQueryKeys } from "@hooks/api/stock-locations"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { LOCATION_DETAILS_FIELD } from "./constants"
+
+const locationQuery = (id: string) => ({
+ queryKey: stockLocationsQueryKeys.detail(id, {
+ fields: LOCATION_DETAILS_FIELD,
+ }),
+ queryFn: async () =>
+ fetchQuery(`/vendor/stock-locations/${id}`, {
+ method: "GET",
+ query: { fields: LOCATION_DETAILS_FIELD },
+ }),
+})
+
+export const locationLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.location_id
+ const query = locationQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/_components/edit-sales-channels-form.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/_components/edit-sales-channels-form.tsx
new file mode 100644
index 000000000..9a5197736
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/_components/edit-sales-channels-form.tsx
@@ -0,0 +1,178 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { VendorExtendedAdminStockLocation } from "@custom-types/stock-location"
+import {
+ Button,
+ createDataTableColumnHelper,
+ DataTableRowSelectionState,
+ toast,
+} from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { DataTable } from "@components/data-table"
+import * as hooks from "@components/data-table/helpers/sales-channels"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { VisuallyHidden } from "@components/utilities/visually-hidden"
+import { useSalesChannels } from "@hooks/api/sales-channels"
+import { useUpdateStockLocationSalesChannels } from "@hooks/api/stock-locations"
+
+type EditSalesChannelsFormProps = {
+ location: VendorExtendedAdminStockLocation
+}
+
+const EditSalesChannelsSchema = zod.object({
+ sales_channels: zod.array(zod.string()).optional(),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "sc"
+
+export const LocationEditSalesChannelsForm = ({
+ location,
+}: EditSalesChannelsFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditSalesChannelsSchema>>({
+ defaultValues: {
+ sales_channels: location.sales_channels?.map((sc) => sc.id) ?? [],
+ },
+ resolver: zodResolver(EditSalesChannelsSchema),
+ })
+
+ const { setValue } = form
+
+ const [rowSelection, setRowSelection] = useState<DataTableRowSelectionState>(
+ getInitialState(location)
+ )
+
+ const onRowSelectionChange = (selection: DataTableRowSelectionState) => {
+ const ids = Object.keys(selection)
+ setValue("sales_channels", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ setRowSelection(selection)
+ }
+
+ const searchParams = hooks.useSalesChannelTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { sales_channels, count, isPending, isError, error } = useSalesChannels(
+ {
+ ...searchParams,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = hooks.useSalesChannelTableFilters()
+ const columns = useColumns()
+ const emptyState = hooks.useSalesChannelTableEmptyState()
+
+ const { mutateAsync, isPending: isMutating } =
+ useUpdateStockLocationSalesChannels(location.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ const originalIds = location.sales_channels?.map((sc) => sc.id)
+
+ const arr = data.sales_channels ?? []
+
+ await mutateAsync(
+ {
+ add: arr.filter((i) => !originalIds?.includes(i)),
+ remove: originalIds?.filter((i) => !arr.includes(i)),
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("stockLocations.salesChannels.successToast"))
+ handleSuccess(`/settings/locations/${location.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
+ <RouteFocusModal.Header>
+ <RouteFocusModal.Title asChild>
+ <VisuallyHidden>
+ {t("stockLocations.salesChannels.header")}
+ </VisuallyHidden>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <VisuallyHidden>
+ {t("stockLocations.salesChannels.hint")}
+ </VisuallyHidden>
+ </RouteFocusModal.Description>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-auto">
+ <DataTable
+ data={sales_channels}
+ columns={columns}
+ filters={filters}
+ emptyState={emptyState}
+ prefix={PREFIX}
+ rowSelection={{
+ state: rowSelection,
+ onRowSelectionChange,
+ }}
+ pageSize={PAGE_SIZE}
+ isLoading={isPending}
+ rowCount={count}
+ layout="fill"
+ getRowId={(row) => row.id}
+ />
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" isLoading={isMutating} type="submit">
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createDataTableColumnHelper<HttpTypes.AdminSalesChannel>()
+
+const useColumns = () => {
+ const base = hooks.useSalesChannelTableColumns()
+
+ return useMemo(() => [columnHelper.select(), ...base], [base])
+}
+
+function getInitialState(location: VendorExtendedAdminStockLocation) {
+ return (
+ location.sales_channels?.reduce((acc, curr) => {
+ acc[curr.id] = true
+ return acc
+ }, {} as DataTableRowSelectionState) ?? {}
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/index.tsx b/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/index.tsx
new file mode 100644
index 000000000..9ba7a2169
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/[location_id]/sales-channels/index.tsx
@@ -0,0 +1,29 @@
+import { useParams } from "react-router-dom"
+
+import { RouteFocusModal } from "@components/modals"
+import { useStockLocation } from "@hooks/api/stock-locations"
+import { LocationEditSalesChannelsForm } from "./_components/edit-sales-channels-form"
+
+const LocationSalesChannels = () => {
+ const { location_id } = useParams()
+ const { stock_location, isPending, isError, error } = useStockLocation(
+ location_id!,
+ {
+ fields: "id,*sales_channels",
+ }
+ )
+
+ const ready = !isPending && !!stock_location
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && <LocationEditSalesChannelsForm location={stock_location} />}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationSalesChannels
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/conditional-price-form.tsx b/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/conditional-price-form.tsx
new file mode 100644
index 000000000..ba4eb1216
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/conditional-price-form.tsx
@@ -0,0 +1,712 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import {
+ InformationCircleSolid,
+ Plus,
+ TriangleDownMini,
+ XMark,
+ XMarkMini,
+} from "@medusajs/icons"
+import {
+ Badge,
+ Button,
+ clx,
+ CurrencyInput,
+ Divider,
+ Heading,
+ IconButton,
+ Label,
+ Text,
+ Tooltip,
+} from "@medusajs/ui"
+import { Accordion as RadixAccordion } from "radix-ui"
+import React, { Fragment, ReactNode, useRef, useState } from "react"
+import {
+ Control,
+ ControllerRenderProps,
+ useFieldArray,
+ useForm,
+ useFormContext,
+ useWatch,
+} from "react-hook-form"
+import { Trans, useTranslation } from "react-i18next"
+
+import { formatValue } from "react-currency-input-field"
+import { Form } from "@components/common/form"
+import { StackedFocusModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCombinedRefs } from "@hooks/use-combined-refs"
+import { castNumber } from "@lib/cast-number"
+import { CurrencyInfo } from "@lib/data/currencies"
+import { getLocaleAmount } from "@lib/money-amount-helpers"
+import { CreateShippingOptionSchemaType } from "../../../location-service-zone-shipping-option-create/components/create-shipping-options-form/schema"
+import {
+ CondtionalPriceRuleSchema,
+ CondtionalPriceRuleSchemaType,
+ UpdateConditionalPriceRuleSchema,
+ UpdateConditionalPriceRuleSchemaType,
+} from "../../schema"
+import { ConditionalPriceInfo } from "../../types"
+import { getCustomShippingOptionPriceFieldName } from "../../utils/get-custom-shipping-option-price-field-info"
+import { useShippingOptionPrice } from "../shipping-option-price-provider"
+
+const RULE_ITEM_PREFIX = "rule-item"
+
+const getRuleValue = (index: number) => `${RULE_ITEM_PREFIX}-${index}`
+
+interface ConditionalPriceFormProps {
+ info: ConditionalPriceInfo
+ variant: "create" | "update"
+}
+
+export const ConditionalPriceForm = ({
+ info,
+ variant,
+}: ConditionalPriceFormProps) => {
+ const { t } = useTranslation()
+ const { getValues, setValue: setFormValue } =
+ useFormContext<CreateShippingOptionSchemaType>()
+ const { onCloseConditionalPricesModal } = useShippingOptionPrice()
+
+ const [value, setValue] = useState<string[]>([getRuleValue(0)])
+
+ const { field, type, currency, name: header } = info
+
+ const name = getCustomShippingOptionPriceFieldName(field, type)
+
+ const conditionalPriceForm = useForm<
+ CondtionalPriceRuleSchemaType | UpdateConditionalPriceRuleSchemaType
+ >({
+ defaultValues: {
+ prices: getValues(name) || [
+ {
+ amount: "",
+ gte: "",
+ lte: null,
+ },
+ ],
+ },
+ resolver: zodResolver(
+ variant === "create"
+ ? CondtionalPriceRuleSchema
+ : UpdateConditionalPriceRuleSchema
+ ),
+ })
+
+ const { fields, append, remove } = useFieldArray({
+ control: conditionalPriceForm.control,
+ name: "prices",
+ })
+
+ const handleAdd = () => {
+ append({
+ amount: "",
+ gte: "",
+ lte: null,
+ })
+
+ setValue([...value, getRuleValue(fields.length)])
+ }
+
+ const handleRemove = (index: number) => {
+ remove(index)
+ }
+
+ const handleOnSubmit = conditionalPriceForm.handleSubmit(
+ (values) => {
+ setFormValue(name, values.prices, {
+ shouldDirty: true,
+ shouldValidate: true,
+ shouldTouch: true,
+ })
+ onCloseConditionalPricesModal()
+ },
+ (e) => {
+ const indexesWithErrors = Object.keys(e.prices || {})
+ setValue((prev) => {
+ const values = new Set(prev)
+
+ indexesWithErrors.forEach((index) => {
+ values.add(getRuleValue(Number(index)))
+ })
+
+ return Array.from(values)
+ })
+ }
+ )
+
+ // Intercept the Cmd + Enter key to only save the inner form.
+ const handleOnKeyDown = (event: React.KeyboardEvent<HTMLFormElement>) => {
+ if (event.key === "Enter" && (event.metaKey || event.ctrlKey)) {
+
+ event.preventDefault()
+ event.stopPropagation()
+
+ handleOnSubmit()
+ }
+ }
+
+ return (
+ <Form {...conditionalPriceForm}>
+ <KeyboundForm
+ onSubmit={handleOnSubmit}
+ onKeyDown={handleOnKeyDown}
+ className="flex h-full flex-col"
+ >
+ <StackedFocusModal.Content>
+ <StackedFocusModal.Header />
+ <StackedFocusModal.Body className="size-full overflow-hidden">
+ <div className="flex size-full flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-6 py-16">
+ <div className="flex w-full flex-col gap-y-6">
+ <div>
+ <StackedFocusModal.Title asChild>
+ <Heading>
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.header",
+ {
+ name: header,
+ }
+ )}
+ </Heading>
+ </StackedFocusModal.Title>
+ <StackedFocusModal.Description asChild>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.description"
+ )}
+ </Text>
+ </StackedFocusModal.Description>
+ </div>
+ <ConditionalPriceList value={value} onValueChange={setValue}>
+ {fields.map((field, index) => (
+ <ConditionalPriceItem
+ key={field.id}
+ index={index}
+ onRemove={handleRemove}
+ currency={currency}
+ control={conditionalPriceForm.control}
+ />
+ ))}
+ </ConditionalPriceList>
+ <div className="flex items-center justify-end">
+ <Button
+ variant="secondary"
+ size="small"
+ type="button"
+ onClick={handleAdd}
+ >
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.actions.addPrice"
+ )}
+ </Button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </StackedFocusModal.Body>
+ <StackedFocusModal.Footer>
+ <div className="flex items-center justify-end gap-2">
+ <StackedFocusModal.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </StackedFocusModal.Close>
+ <Button size="small" type="button" onClick={handleOnSubmit}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </StackedFocusModal.Footer>
+ </StackedFocusModal.Content>
+ </KeyboundForm>
+ </Form>
+ )
+}
+
+interface ConditionalPriceListProps {
+ children?: ReactNode
+ value: string[]
+ onValueChange: (value: string[]) => void
+}
+
+const ConditionalPriceList = ({
+ children,
+ value,
+ onValueChange,
+}: ConditionalPriceListProps) => {
+ return (
+ <RadixAccordion.Root
+ type="multiple"
+ defaultValue={[getRuleValue(0)]}
+ value={value}
+ onValueChange={onValueChange}
+ className="flex flex-col gap-y-3"
+ >
+ {children}
+ </RadixAccordion.Root>
+ )
+}
+
+interface ConditionalPriceItemProps {
+ index: number
+ currency: CurrencyInfo
+ onRemove: (index: number) => void
+ control: Control<CondtionalPriceRuleSchemaType>
+}
+
+const ConditionalPriceItem = ({
+ index,
+ currency,
+ onRemove,
+ control,
+}: ConditionalPriceItemProps) => {
+ const { t } = useTranslation()
+
+ const handleRemove = (e: React.MouseEvent<HTMLButtonElement>) => {
+ e.stopPropagation()
+ onRemove(index)
+ }
+
+ return (
+ <RadixAccordion.Item
+ value={getRuleValue(index)}
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest rounded-lg"
+ )}
+ >
+ <RadixAccordion.Trigger asChild>
+ <div className="group/trigger flex w-full cursor-pointer items-start justify-between gap-x-2 p-3">
+ <div className="flex flex-1 flex-wrap items-center justify-between gap-2">
+ <div className="flex h-7 items-center">
+ <AmountDisplay
+ index={index}
+ currency={currency}
+ control={control}
+ />
+ </div>
+ <div className="flex min-h-7 items-center">
+ <ConditionDisplay
+ index={index}
+ currency={currency}
+ control={control}
+ />
+ </div>
+ </div>
+ <div className="flex items-center gap-x-2">
+ <IconButton
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted hover:text-ui-fg-subtle focus-visible:text-ui-fg-subtle"
+ onClick={handleRemove}
+ >
+ <XMarkMini />
+ </IconButton>
+ <IconButton
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-muted hover:text-ui-fg-subtle focus-visible:text-ui-fg-subtle"
+ >
+ <TriangleDownMini className="transition-transform group-data-[state=open]/trigger:rotate-180" />
+ </IconButton>
+ </div>
+ </div>
+ </RadixAccordion.Trigger>
+ <RadixAccordion.Content className="text-ui-fg-subtle">
+ <Divider variant="dashed" />
+ <Form.Field
+ control={control}
+ name={`prices.${index}.amount`}
+ render={({ field: { value, onChange, ...props } }) => {
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-2 items-start gap-x-2 p-3">
+ <div className="flex h-8 items-center">
+ <Form.Label>
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.rules.amount"
+ )}
+ </Form.Label>
+ </div>
+ <div className="flex flex-col gap-y-1">
+ <Form.Control>
+ <CurrencyInput
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover focus-visible:bg-ui-bg-field-component-hover"
+ placeholder={formatValue({
+ value: "0",
+ decimalScale: currency.decimal_digits,
+ })}
+ decimalScale={currency.decimal_digits}
+ symbol={currency.symbol_native}
+ code={currency.code}
+ value={value}
+ onValueChange={(_value, _name, values) =>
+ onChange(values?.value ? values?.value : "")
+ }
+ {...props}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </div>
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+ <Divider variant="dashed" />
+ <Form.Field
+ control={control}
+ name={`prices.${index}.gte`}
+ render={({ field }) => {
+ return (
+ <OperatorInput
+ field={field}
+ label={t(
+ "stockLocations.shippingOptions.conditionalPrices.rules.gte"
+ )}
+ currency={currency}
+ placeholder="1000"
+ />
+ )
+ }}
+ />
+ <Divider variant="dashed" />
+ <Form.Field
+ control={control}
+ name={`prices.${index}.lte`}
+ render={({ field }) => {
+ return (
+ <OperatorInput
+ field={field}
+ label={t(
+ "stockLocations.shippingOptions.conditionalPrices.rules.lte"
+ )}
+ currency={currency}
+ placeholder="1000"
+ />
+ )
+ }}
+ />
+ <ReadOnlyConditions
+ index={index}
+ control={control}
+ currency={currency}
+ />
+ </RadixAccordion.Content>
+ </RadixAccordion.Item>
+ )
+}
+
+interface OperatorInputProps<
+ TName extends `prices.${number}.lte` | `prices.${number}.gte`
+> {
+ currency: CurrencyInfo
+ placeholder: string
+ label: string
+ field: ControllerRenderProps<CondtionalPriceRuleSchemaType, TName>
+}
+
+const OperatorInput = <
+ TName extends `prices.${number}.lte` | `prices.${number}.gte`
+>({
+ field,
+ label,
+ currency,
+ placeholder,
+}: OperatorInputProps<TName>) => {
+ const innerRef = useRef<HTMLInputElement>(null)
+
+ const { value, onChange, ref, ...props } = field
+
+ const refs = useCombinedRefs(innerRef, ref)
+
+ const action = () => {
+ if (value === null) {
+ onChange("")
+
+ requestAnimationFrame(() => {
+ innerRef.current?.focus()
+ })
+
+ return
+ }
+
+ onChange(null)
+ }
+
+ const isNull = value === null
+
+ return (
+ <Form.Item>
+ <div className="grid grid-cols-2 items-start gap-x-2 p-3">
+ <div className="flex h-8 items-center gap-x-1">
+ <IconButton size="2xsmall" variant="transparent" onClick={action}>
+ {isNull ? <Plus /> : <XMark />}
+ </IconButton>
+ <Form.Label>{label}</Form.Label>
+ </div>
+ {!isNull && (
+ <div className="flex flex-col gap-y-1">
+ <Form.Control>
+ <CurrencyInput
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover focus-visible:bg-ui-bg-field-component-hover"
+ placeholder={formatValue({
+ value: placeholder,
+ decimalScale: currency.decimal_digits,
+ })}
+ decimalScale={currency.decimal_digits}
+ symbol={currency.symbol_native}
+ code={currency.code}
+ value={value}
+ ref={refs}
+ onValueChange={(_value, _name, values) =>
+ onChange(values?.value ? values?.value : "")
+ }
+ {...props}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </div>
+ )}
+ </div>
+ </Form.Item>
+ )
+}
+
+const ReadOnlyConditions = ({
+ index,
+ control,
+ currency,
+}: {
+ index: number
+ control: Control<CondtionalPriceRuleSchemaType>
+ currency: CurrencyInfo
+}) => {
+ const { t } = useTranslation()
+
+ const item = useWatch({
+ control,
+ name: `prices.${index}`,
+ })
+
+ if (item.eq == null && item.gt == null && item.lt == null) {
+ return null
+ }
+
+ return (
+ <div>
+ <Divider variant="dashed" />
+ <div className="flex items-center gap-x-1 px-3 pt-3">
+ <Text size="small" leading="compact" weight="plus">
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.customRules.label"
+ )}
+ </Text>
+ <Tooltip
+ content={t(
+ "stockLocations.shippingOptions.conditionalPrices.customRules.tooltip"
+ )}
+ >
+ <InformationCircleSolid className="text-ui-fg-muted" />
+ </Tooltip>
+ </div>
+ <div>
+ {item.eq != null && (
+ <div className="grid grid-cols-2 items-start gap-x-2 p-3">
+ <div className="flex h-8 items-center">
+ <Label weight="plus" size="small">
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.customRules.eq"
+ )}
+ </Label>
+ </div>
+ <CurrencyInput
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover focus-visible:bg-ui-bg-field-component-hover"
+ symbol={currency.symbol_native}
+ code={currency.code}
+ value={item.eq}
+ disabled
+ />
+ </div>
+ )}
+ {item.gt != null && (
+ <Fragment>
+ <Divider variant="dashed" />
+ <div className="grid grid-cols-2 items-start gap-x-2 p-3">
+ <div className="flex h-8 items-center">
+ <Label weight="plus" size="small">
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.customRules.gt"
+ )}
+ </Label>
+ </div>
+ <CurrencyInput
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover focus-visible:bg-ui-bg-field-component-hover"
+ symbol={currency.symbol_native}
+ code={currency.code}
+ value={item.gt}
+ disabled
+ />
+ </div>
+ </Fragment>
+ )}
+ {item.lt != null && (
+ <Fragment>
+ <Divider variant="dashed" />
+ <div className="grid grid-cols-2 items-start gap-x-2 p-3">
+ <div className="flex h-8 items-center">
+ <Label weight="plus" size="small">
+ {t(
+ "stockLocations.shippingOptions.conditionalPrices.customRules.lt"
+ )}
+ </Label>
+ </div>
+ <CurrencyInput
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover focus-visible:bg-ui-bg-field-component-hover"
+ symbol={currency.symbol_native}
+ code={currency.code}
+ value={item.lt}
+ disabled
+ />
+ </div>
+ </Fragment>
+ )}
+ </div>
+ </div>
+ )
+}
+
+const AmountDisplay = ({
+ index,
+ currency,
+ control,
+}: {
+ index: number
+ currency: CurrencyInfo
+ control: Control<CondtionalPriceRuleSchemaType>
+}) => {
+ const amount = useWatch({
+ control,
+ name: `prices.${index}.amount`,
+ })
+
+ if (amount === "" || amount === undefined) {
+ return (
+ <Text size="small" weight="plus">
+ -
+ </Text>
+ )
+ }
+
+ const castAmount = castNumber(amount)
+
+ return (
+ <Text size="small" weight="plus">
+ {getLocaleAmount(castAmount, currency.code)}
+ </Text>
+ )
+}
+
+const ConditionContainer = ({ children }: { children: ReactNode }) => (
+ <div className="text-ui-fg-subtle txt-small flex flex-wrap items-center gap-1.5">
+ {children}
+ </div>
+)
+
+const ConditionDisplay = ({
+ index,
+ currency,
+ control,
+}: {
+ index: number
+ currency: CurrencyInfo
+ control: Control<CondtionalPriceRuleSchemaType>
+}) => {
+ const { t, i18n } = useTranslation()
+
+ const gte = useWatch({
+ control,
+ name: `prices.${index}.gte`,
+ })
+
+ const lte = useWatch({
+ control,
+ name: `prices.${index}.lte`,
+ })
+
+ const renderCondition = () => {
+ const castGte = gte ? castNumber(gte) : undefined
+ const castLte = lte ? castNumber(lte) : undefined
+
+ if (!castGte && !castLte) {
+ return null
+ }
+
+ if (castGte && !castLte) {
+ return (
+ <ConditionContainer>
+ <Trans
+ i18n={i18n}
+ i18nKey="stockLocations.shippingOptions.conditionalPrices.summaries.greaterThan"
+ components={[
+ <Badge size="2xsmall" key="attribute" />,
+ <Badge size="2xsmall" key="gte" />,
+ ]}
+ values={{
+ attribute: t(
+ "stockLocations.shippingOptions.conditionalPrices.attributes.cartItemTotal"
+ ),
+ gte: getLocaleAmount(castGte, currency.code),
+ }}
+ />
+ </ConditionContainer>
+ )
+ }
+
+ if (!castGte && castLte) {
+ return (
+ <ConditionContainer>
+ <Trans
+ i18n={i18n}
+ i18nKey="stockLocations.shippingOptions.conditionalPrices.summaries.lessThan"
+ components={[
+ <Badge size="2xsmall" key="attribute" />,
+ <Badge size="2xsmall" key="lte" />,
+ ]}
+ values={{
+ attribute: t(
+ "stockLocations.shippingOptions.conditionalPrices.attributes.cartItemTotal"
+ ),
+ lte: getLocaleAmount(castLte, currency.code),
+ }}
+ />
+ </ConditionContainer>
+ )
+ }
+
+ if (castGte && castLte) {
+ return (
+ <ConditionContainer>
+ <Trans
+ i18n={i18n}
+ i18nKey="stockLocations.shippingOptions.conditionalPrices.summaries.range"
+ components={[
+ <Badge size="2xsmall" key="attribute" />,
+ <Badge size="2xsmall" key="gte" />,
+ <Badge size="2xsmall" key="lte" />,
+ ]}
+ values={{
+ attribute: t(
+ "stockLocations.shippingOptions.conditionalPrices.attributes.cartItemTotal"
+ ),
+ gte: getLocaleAmount(castGte, currency.code),
+ lte: getLocaleAmount(castLte, currency.code),
+ }}
+ />
+ </ConditionContainer>
+ )
+ }
+
+ return null
+ }
+
+ return renderCondition()
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/index.ts b/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/index.ts
new file mode 100644
index 000000000..b184d947d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/conditional-price-form/index.ts
@@ -0,0 +1 @@
+export * from "./conditional-price-form"
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/geo-zone-form.tsx b/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/geo-zone-form.tsx
new file mode 100644
index 000000000..61cccef57
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/geo-zone-form.tsx
@@ -0,0 +1,327 @@
+import { Button, Checkbox } from "@medusajs/ui"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { UseFormReturn, useFieldArray } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { ChipGroup } from "@components/common/chip-group"
+import { Form } from "@components/common/form"
+import {
+ StackedFocusModal,
+ useStackedModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { useDataTable } from "@hooks/use-data-table"
+import {
+ StaticCountry,
+ countries as staticCountries,
+} from "@lib/data/countries"
+import { useCountries } from "@pages/settings/regions/_common/hooks/use-countries"
+import { useCountryTableColumns } from "@pages/settings/regions/_common/hooks/use-country-table-columns"
+import { useCountryTableQuery } from "@pages/settings/regions/_common/hooks/use-country-table-query"
+import { GEO_ZONE_STACKED_MODAL_ID } from "../../constants"
+
+const GeoZoneSchema = z.object({
+ countries: z.array(
+ z.object({ iso_2: z.string().min(2), display_name: z.string() })
+ ),
+})
+
+type GeoZoneFormImplProps<TForm extends UseFormReturn<any>> = {
+ form: TForm
+}
+
+const GeoZoneFormImpl = <TForm extends UseFormReturn<any>>({
+ form,
+}: GeoZoneFormImplProps<TForm>) => {
+ const castForm = form as unknown as UseFormReturn<
+ z.infer<typeof GeoZoneSchema>
+ >
+
+ const { t } = useTranslation()
+
+ const { fields, remove, replace } = useFieldArray({
+ control: castForm.control,
+ name: "countries",
+ keyName: "iso_2",
+ })
+
+ const handleClearAll = () => {
+ replace([])
+ }
+
+ validateForm(form)
+
+ return (
+ <Form.Field
+ control={form.control}
+ name="countries"
+ render={() => {
+ return (
+ <Form.Item>
+ <div className="flex items-center justify-between gap-x-4">
+ <div>
+ <Form.Label>
+ {t("stockLocations.serviceZones.manageAreas.label")}
+ </Form.Label>
+ <Form.Hint>
+ {t("stockLocations.serviceZones.manageAreas.hint")}
+ </Form.Hint>
+ </div>
+ <StackedFocusModal.Trigger asChild>
+ <Button size="small" variant="secondary" type="button">
+ {t("stockLocations.serviceZones.manageAreas.action")}
+ </Button>
+ </StackedFocusModal.Trigger>
+ </div>
+ <Form.ErrorMessage />
+ <Form.Control className="mt-0">
+ {fields.length > 0 && (
+ <ChipGroup
+ onClearAll={handleClearAll}
+ onRemove={remove}
+ className="py-4"
+ >
+ {fields.map((field, index) => (
+ <ChipGroup.Chip key={field.iso_2} index={index}>
+ {field.display_name}
+ </ChipGroup.Chip>
+ ))}
+ </ChipGroup>
+ )}
+ </Form.Control>
+ </Form.Item>
+ )
+ }}
+ />
+ )
+}
+
+type AreasStackedModalProps<TForm extends UseFormReturn<any>> = {
+ form: TForm
+}
+
+const PREFIX = "ac"
+const PAGE_SIZE = 50
+
+const AreaStackedModal = <TForm extends UseFormReturn<any>>({
+ form,
+}: AreasStackedModalProps<TForm>) => {
+ const castForm = form as unknown as UseFormReturn<
+ z.infer<typeof GeoZoneSchema>
+ >
+
+ const { t } = useTranslation()
+ const { getValues, setValue } = castForm
+ const { setIsOpen, getIsOpen } = useStackedModal()
+
+ const open = getIsOpen(GEO_ZONE_STACKED_MODAL_ID)
+
+ const [selection, setSelection] = useState<RowSelectionState>({})
+ const [state, setState] = useState<{ iso_2: string; display_name: string }[]>(
+ []
+ )
+
+ const { searchParams, raw } = useCountryTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { countries, count } = useCountries({
+ countries: staticCountries.map((c) => ({
+ display_name: c.display_name,
+ name: c.name,
+ iso_2: c.iso_2,
+ iso_3: c.iso_3,
+ num_code: c.num_code,
+ })),
+ ...searchParams,
+ })
+
+ useEffect(() => {
+ if (!open) {
+ return
+ }
+
+ const countries = getValues("countries")
+
+ if (countries) {
+ setState(
+ countries.map((country) => ({
+ iso_2: country.iso_2,
+ display_name: country.display_name,
+ }))
+ )
+
+ setSelection(
+ countries.reduce(
+ (acc, country) => ({
+ ...acc,
+ [country.iso_2]: true,
+ }),
+ {}
+ )
+ )
+ }
+ }, [open, getValues])
+
+ const updater: OnChangeFn<RowSelectionState> = (fn) => {
+ const value = typeof fn === "function" ? fn(selection) : fn
+ const ids = Object.keys(value)
+
+ const addedIdsSet = new Set(ids.filter((id) => value[id] && !selection[id]))
+
+ const addedCountries: { iso_2: string; display_name: string }[] = []
+
+ if (addedIdsSet.size > 0) {
+ const countriesToAdd =
+ countries?.filter((country) => addedIdsSet.has(country.iso_2!)) ?? []
+
+ for (const country of countriesToAdd) {
+ addedCountries.push({
+ iso_2: country.iso_2!,
+ display_name: country.display_name!,
+ })
+ }
+ }
+
+ setState((prev) => {
+ const filteredPrev = prev.filter((country) => value[country.iso_2])
+ return Array.from(new Set([...filteredPrev, ...addedCountries]))
+ })
+ setSelection(value)
+ }
+
+ const handleAdd = () => {
+ setValue("countries", state, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ setIsOpen(GEO_ZONE_STACKED_MODAL_ID, false)
+ }
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: countries || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.iso_2!,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: selection,
+ updater,
+ },
+ prefix: PREFIX,
+ })
+
+ validateForm(form)
+
+ return (
+ <StackedFocusModal.Content className="flex flex-col overflow-hidden">
+ <StackedFocusModal.Header>
+ <StackedFocusModal.Title asChild>
+ <span className="sr-only">
+ {t("stockLocations.serviceZones.manageAreas.label")}
+ </span>
+ </StackedFocusModal.Title>
+ <StackedFocusModal.Description asChild>
+ <span className="sr-only">
+ {t("stockLocations.serviceZones.manageAreas.hint")}
+ </span>
+ </StackedFocusModal.Description>
+ </StackedFocusModal.Header>
+ <StackedFocusModal.Body className="flex-1 overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ search
+ pagination
+ layout="fill"
+ orderBy={[
+ { key: "display_name", label: t("fields.name") },
+ { key: "iso_2", label: t("fields.code") },
+ ]}
+ queryObject={raw}
+ prefix={PREFIX}
+ />
+ </StackedFocusModal.Body>
+ <StackedFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <StackedFocusModal.Close type="button" asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </StackedFocusModal.Close>
+ <Button size="small" type="button" onClick={handleAdd}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </StackedFocusModal.Footer>
+ </StackedFocusModal.Content>
+ )
+}
+
+const columnHelper = createColumnHelper<StaticCountry>()
+
+const useColumns = () => {
+ const base = useCountryTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreselected = !row.getCanSelect()
+
+ return (
+ <Checkbox
+ checked={row.getIsSelected() || isPreselected}
+ disabled={isPreselected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+function validateForm(form: UseFormReturn) {
+ if (form.getValues("countries") === undefined) {
+ throw new Error(
+ "The form does not have a field named 'countries'. This field is required to use the GeoZoneForm component."
+ )
+ }
+}
+
+export const GeoZoneForm = Object.assign(GeoZoneFormImpl, {
+ AreaDrawer: AreaStackedModal,
+})
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/index.ts b/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/index.ts
new file mode 100644
index 000000000..b8a190ca5
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/geo-zone-form/index.ts
@@ -0,0 +1 @@
+export * from "./geo-zone-form"
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/index.ts b/packages/vendor/src/pages/settings/locations/_common/components/index.ts
new file mode 100644
index 000000000..2d0cdea4c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/index.ts
@@ -0,0 +1,2 @@
+export * from "./shipping-option-price-provider"
+export * from "./use-shipping-option-price"
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-cell.tsx b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-cell.tsx
new file mode 100644
index 000000000..427a7ba93
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-cell.tsx
@@ -0,0 +1,261 @@
+import { ArrowsPointingOut, CircleSliders } from "@medusajs/icons"
+import { clx } from "@medusajs/ui"
+import { useCallback, useEffect, useRef, useState } from "react"
+import CurrencyInput, {
+ CurrencyInputProps,
+ formatValue,
+} from "react-currency-input-field"
+import {
+ Control,
+ Controller,
+ ControllerRenderProps,
+ useWatch,
+} from "react-hook-form"
+import { DataGridCellContainer } from "@components/data-grid/components/data-grid-cell-container"
+import {
+ useDataGridCell,
+ useDataGridCellError,
+} from "@components/data-grid/hooks"
+import {
+ DataGridCellProps,
+ InputProps,
+} from "@components/data-grid/types"
+import { useCombinedRefs } from "@hooks/use-combined-refs"
+import { currencies, CurrencyInfo } from "@lib/data/currencies"
+import { getCustomShippingOptionPriceFieldName } from "../utils/get-custom-shipping-option-price-field-info"
+import { useShippingOptionPrice } from "./shipping-option-price-provider"
+
+interface ShippingOptionPriceCellProps<TData, TValue = any>
+ extends DataGridCellProps<TData, TValue> {
+ code: string
+ header: string
+ type: "currency" | "region"
+}
+
+export const ShippingOptionPriceCell = <TData, TValue = any>({
+ context,
+ code,
+ header,
+ type,
+}: ShippingOptionPriceCellProps<TData, TValue>) => {
+ const [symbolWidth, setSymbolWidth] = useState(0)
+
+ const measuredRef = useCallback((node: HTMLSpanElement) => {
+ if (node) {
+ const width = node.offsetWidth
+ setSymbolWidth(width)
+ }
+ }, [])
+
+ const { field, control, renderProps } = useDataGridCell({
+ context,
+ })
+
+ const errorProps = useDataGridCellError({ context })
+
+ const { container, input } = renderProps
+ const { isAnchor } = container
+
+ const currency = currencies[code.toUpperCase()]
+
+ return (
+ <Controller
+ control={control}
+ name={field}
+ render={({ field: props }) => {
+ return (
+ <DataGridCellContainer
+ {...container}
+ {...errorProps}
+ outerComponent={
+ <OuterComponent
+ header={header}
+ isAnchor={isAnchor}
+ field={field}
+ control={control}
+ symbolWidth={symbolWidth}
+ type={type}
+ currency={currency}
+ />
+ }
+ >
+ <Inner
+ field={props}
+ inputProps={input}
+ currencyInfo={currency}
+ onMeasureSymbol={measuredRef}
+ />
+ </DataGridCellContainer>
+ )
+ }}
+ />
+ )
+}
+
+const OuterComponent = ({
+ isAnchor,
+ header,
+ field,
+ control,
+ symbolWidth,
+ type,
+ currency,
+}: {
+ isAnchor: boolean
+ header: string
+ field: string
+ control: Control<any>
+ symbolWidth: number
+ type: "currency" | "region"
+ currency: CurrencyInfo
+}) => {
+ const { onOpenConditionalPricesModal } = useShippingOptionPrice()
+
+ const buttonRef = useRef<HTMLButtonElement>(null)
+
+ const name = getCustomShippingOptionPriceFieldName(field, type)
+ const price = useWatch({ control, name })
+
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (isAnchor && (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") {
+ e.preventDefault()
+ buttonRef.current?.click()
+ }
+ }
+
+ document.addEventListener("keydown", handleKeyDown)
+ return () => document.removeEventListener("keydown", handleKeyDown)
+ }, [isAnchor])
+
+ return (
+ <div
+ className="absolute inset-y-0 z-[3] flex w-fit items-center justify-center"
+ style={{
+ left: symbolWidth ? `${symbolWidth + 16 + 4}px` : undefined,
+ }}
+ >
+ {price?.length > 0 && !isAnchor && (
+ <div className="flex size-[15px] items-center justify-center group-hover/container:hidden">
+ <CircleSliders className="text-ui-fg-interactive" />
+ </div>
+ )}
+ <button
+ ref={buttonRef}
+ type="button"
+ className={clx(
+ "hover:text-ui-fg-subtle text-ui-fg-muted transition-fg hidden size-[15px] items-center justify-center rounded-md bg-transparent group-hover/container:flex",
+ { flex: isAnchor }
+ )}
+ onClick={() =>
+ onOpenConditionalPricesModal({
+ type,
+ field,
+ currency,
+ name: header,
+ })
+ }
+ >
+ <ArrowsPointingOut />
+ </button>
+ </div>
+ )
+}
+
+const Inner = ({
+ field,
+ onMeasureSymbol,
+ inputProps,
+ currencyInfo,
+}: {
+ field: ControllerRenderProps<any, string>
+ onMeasureSymbol: (node: HTMLSpanElement) => void
+ inputProps: InputProps
+ currencyInfo: CurrencyInfo
+}) => {
+ const { value, onChange: _, onBlur, ref, ...rest } = field
+ const {
+ ref: inputRef,
+ onBlur: onInputBlur,
+ onFocus,
+ onChange,
+ ...attributes
+ } = inputProps
+
+ const formatter = useCallback(
+ (value?: string | number) => {
+ const ensuredValue =
+ typeof value === "number" ? value.toString() : value || ""
+
+ return formatValue({
+ value: ensuredValue,
+ decimalScale: currencyInfo.decimal_digits,
+ disableGroupSeparators: true,
+ decimalSeparator: ".",
+ })
+ },
+ [currencyInfo]
+ )
+
+ const [localValue, setLocalValue] = useState<string | number>(value || "")
+
+ const handleValueChange: CurrencyInputProps["onValueChange"] = (
+ value,
+ _name,
+ _values
+ ) => {
+ if (!value) {
+ setLocalValue("")
+ return
+ }
+
+ setLocalValue(value)
+ }
+
+ useEffect(() => {
+ let update = value
+
+ // The component we use is a bit fidly when the value is updated externally
+ // so we need to ensure a format that will result in the cell being formatted correctly
+ // according to the users locale on the next render.
+ if (!isNaN(Number(value))) {
+ update = formatter(update)
+ }
+
+ setLocalValue(update)
+ }, [value, formatter])
+
+ const combinedRed = useCombinedRefs(inputRef, ref)
+
+ return (
+ <div className="relative flex size-full items-center">
+ <span
+ className="txt-compact-small text-ui-fg-muted pointer-events-none absolute left-0 w-fit min-w-4"
+ aria-hidden
+ ref={onMeasureSymbol}
+ >
+ {currencyInfo.symbol_native}
+ </span>
+ <CurrencyInput
+ {...rest}
+ {...attributes}
+ ref={combinedRed}
+ className="txt-compact-small w-full flex-1 cursor-default appearance-none bg-transparent pl-[60px] text-right outline-none"
+ value={localValue || undefined}
+ onValueChange={handleValueChange}
+ formatValueOnBlur
+ onBlur={() => {
+ onBlur()
+ onInputBlur()
+
+ onChange(localValue, value)
+ }}
+ onFocus={onFocus}
+ decimalScale={currencyInfo.decimal_digits}
+ decimalsLimit={currencyInfo.decimal_digits}
+ autoComplete="off"
+ tabIndex={-1}
+ />
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-context.tsx b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-context.tsx
new file mode 100644
index 000000000..8c80fc763
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-context.tsx
@@ -0,0 +1,10 @@
+import { createContext } from "react"
+import { ConditionalPriceInfo } from "../../types"
+
+type ShippingOptionPriceContextType = {
+ onOpenConditionalPricesModal: (info: ConditionalPriceInfo) => void
+ onCloseConditionalPricesModal: () => void
+}
+
+export const ShippingOptionPriceContext =
+ createContext<ShippingOptionPriceContextType | null>(null)
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-provider.tsx b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-provider.tsx
new file mode 100644
index 000000000..1397c54e3
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/shipping-option-price-provider.tsx
@@ -0,0 +1,24 @@
+import { ShippingOptionPriceContext } from "./shipping-option-price-context"
+import { PropsWithChildren } from "react"
+import { ConditionalPriceInfo } from "../../types"
+
+export { useShippingOptionPrice } from "./use-shipping-option-price"
+
+type ShippingOptionPriceProviderProps = PropsWithChildren<{
+ onOpenConditionalPricesModal: (info: ConditionalPriceInfo) => void
+ onCloseConditionalPricesModal: () => void
+}>
+
+export const ShippingOptionPriceProvider = ({
+ children,
+ onOpenConditionalPricesModal,
+ onCloseConditionalPricesModal,
+}: ShippingOptionPriceProviderProps) => {
+ return (
+ <ShippingOptionPriceContext.Provider
+ value={{ onOpenConditionalPricesModal, onCloseConditionalPricesModal }}
+ >
+ {children}
+ </ShippingOptionPriceContext.Provider>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/components/use-shipping-option-price.tsx b/packages/vendor/src/pages/settings/locations/_common/components/use-shipping-option-price.tsx
new file mode 100644
index 000000000..214ba4d89
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/components/use-shipping-option-price.tsx
@@ -0,0 +1,14 @@
+import { useContext } from "react"
+import { ShippingOptionPriceContext } from "./shipping-option-price-context"
+
+export const useShippingOptionPrice = () => {
+ const context = useContext(ShippingOptionPriceContext)
+
+ if (!context) {
+ throw new Error(
+ "useShippingOptionPrice must be used within a ShippingOptionPriceProvider"
+ )
+ }
+
+ return context
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/constants.ts b/packages/vendor/src/pages/settings/locations/_common/constants.ts
new file mode 100644
index 000000000..3d5e2e30e
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/constants.ts
@@ -0,0 +1,16 @@
+export enum FulfillmentSetType {
+ Shipping = "shipping",
+ Pickup = "pickup",
+}
+
+export enum ShippingOptionPriceType {
+ FlatRate = "flat",
+ Calculated = "calculated",
+}
+
+export const GEO_ZONE_STACKED_MODAL_ID = "geo-zone"
+
+export const CONDITIONAL_PRICES_STACKED_MODAL_ID = "conditional-prices"
+
+export const ITEM_TOTAL_ATTRIBUTE = "item_total"
+export const REGION_ID_ATTRIBUTE = "region_id"
diff --git a/packages/vendor/src/pages/settings/locations/_common/hooks/use-shipping-option-price-columns.tsx b/packages/vendor/src/pages/settings/locations/_common/hooks/use-shipping-option-price-columns.tsx
new file mode 100644
index 000000000..dcba11211
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/hooks/use-shipping-option-price-columns.tsx
@@ -0,0 +1,174 @@
+import { HttpTypes } from "@medusajs/types"
+import { ColumnDef } from "@tanstack/react-table"
+import { TFunction } from "i18next"
+import { useMemo } from "react"
+import { FieldPath, FieldValues } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { IncludesTaxTooltip } from "@components/common/tax-badge/tax-badge"
+import {
+ createDataGridHelper,
+ DataGrid,
+} from "@components/data-grid"
+import { FieldContext } from "@components/data-grid/types"
+import { ShippingOptionPriceCell } from "@pages/settings/locations/_common/components/shipping-option-price-cell"
+
+const columnHelper = createDataGridHelper()
+
+export const useShippingOptionPriceColumns = ({
+ name,
+ currencies = [],
+ regions = [],
+ pricePreferences = [],
+}: {
+ name: string
+ currencies?: string[]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+}) => {
+ const { t } = useTranslation()
+
+ return useMemo(() => {
+ return [
+ columnHelper.column({
+ id: "name",
+ name: t("fields.name"),
+ disableHiding: true,
+ header: t("fields.name"),
+ cell: (context) => {
+ return (
+ <DataGrid.ReadonlyCell context={context}>
+ {name}
+ </DataGrid.ReadonlyCell>
+ )
+ },
+ }),
+ ...createDataGridPriceColumns({
+ currencies,
+ regions,
+ pricePreferences,
+ getFieldName: (context, value) => {
+ if (context.column.id?.startsWith("currency_prices")) {
+ return `currency_prices.${value}`
+ }
+
+ return `region_prices.${value}`
+ },
+ t,
+ }),
+ ]
+ }, [t, currencies, regions, pricePreferences, name])
+}
+
+type CreateDataGridPriceColumnsProps<
+ TData,
+ TFieldValues extends FieldValues,
+> = {
+ currencies?: string[]
+ regions?: HttpTypes.AdminRegion[]
+ pricePreferences?: HttpTypes.AdminPricePreference[]
+ getFieldName: (
+ context: FieldContext<TData>,
+ value: string
+ ) => FieldPath<TFieldValues> | null
+ t: TFunction
+}
+
+export const createDataGridPriceColumns = <
+ TData,
+ TFieldValues extends FieldValues,
+>({
+ currencies,
+ regions,
+ pricePreferences,
+ getFieldName,
+ t,
+}: CreateDataGridPriceColumnsProps<TData, TFieldValues>): ColumnDef<
+ TData,
+ unknown
+>[] => {
+ const columnHelper = createDataGridHelper<TData, TFieldValues>()
+
+ return [
+ // ...(currencies?.map((currency) => {
+ // const preference = pricePreferences?.find(
+ // (p) => p.attribute === "currency_code" && p.value === currency
+ // )
+
+ // const translatedCurrencyName = t("fields.priceTemplate", {
+ // regionOrCurrency: currency.toUpperCase(),
+ // })
+
+ // return columnHelper.column({
+ // id: `currency_prices.${currency}`,
+ // name: t("fields.priceTemplate", {
+ // regionOrCurrency: currency.toUpperCase(),
+ // }),
+ // field: (context) => {
+ // return getFieldName(context, currency)
+ // },
+ // type: "number",
+ // header: () => (
+ // <div className="flex w-full items-center justify-between gap-3">
+ // <span className="truncate" title={translatedCurrencyName}>
+ // {translatedCurrencyName}
+ // </span>
+ // <IncludesTaxTooltip includesTax={preference?.is_tax_inclusive} />
+ // </div>
+ // ),
+ // cell: (context) => {
+ // return (
+ // <ShippingOptionPriceCell
+ // type="currency"
+ // header={translatedCurrencyName}
+ // code={currency}
+ // context={context}
+ // />
+ // )
+ // },
+ // })
+ // }) ?? []),
+ ...(regions?.map((region) => {
+ const preference = pricePreferences?.find(
+ (p) => p.attribute === "region_id" && p.value === region.id
+ )
+
+ const translatedRegionName = t("fields.priceTemplate", {
+ regionOrCurrency: region.name,
+ })
+
+ return columnHelper.column({
+ id: `region_prices.${region.id}`,
+ name: t("fields.priceTemplate", {
+ regionOrCurrency: region.name,
+ }),
+ field: (context) => {
+ return getFieldName(context, region.id)
+ },
+ type: "number",
+ header: () => (
+ <div className="flex w-full items-center justify-between gap-3">
+ <span className="truncate" title={translatedRegionName}>
+ {translatedRegionName}
+ </span>
+ <IncludesTaxTooltip includesTax={preference?.is_tax_inclusive} />
+ </div>
+ ),
+ cell: (context) => {
+ const currency = currencies?.find((c) => c === region.currency_code)
+ if (!currency) {
+ return null
+ }
+
+ return (
+ <ShippingOptionPriceCell
+ type="region"
+ header={translatedRegionName}
+ code={region.currency_code}
+ context={context}
+ />
+ )
+ },
+ })
+ }) ?? []),
+ ]
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/schema.ts b/packages/vendor/src/pages/settings/locations/_common/schema.ts
new file mode 100644
index 000000000..cd1891531
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/schema.ts
@@ -0,0 +1,192 @@
+import { t } from "i18next"
+import { z } from "zod"
+import { castNumber } from "@lib/cast-number"
+
+export const ConditionalPriceSchema = z
+ .object({
+ amount: z.union([z.string(), z.number()]),
+ gte: z.union([z.string(), z.number()]).nullish(),
+ lte: z.union([z.string(), z.number()]).nullish(),
+ lt: z.number().nullish(),
+ gt: z.number().nullish(),
+ eq: z.number().nullish(),
+ })
+ .refine((data) => data.amount !== "", {
+ message: t(
+ "stockLocations.shippingOptions.conditionalPrices.errors.amountRequired"
+ ),
+ path: ["amount"],
+ })
+ .refine(
+ (data) => {
+ const hasEqLtGt =
+ data.eq !== undefined || data.lt !== undefined || data.gt !== undefined
+
+ // The rule has operators that can only be managed using the API, so we should not validate this.
+ if (hasEqLtGt) {
+ return true
+ }
+
+ return (
+ (data.gte !== undefined && data.gte !== "") ||
+ (data.lte !== undefined && data.lte !== "")
+ )
+ },
+ {
+ message: t(
+ "stockLocations.shippingOptions.conditionalPrices.errors.minOrMaxRequired"
+ ),
+ path: ["gte"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (
+ data.gte != null &&
+ data.gte !== "" &&
+ data.lte != null &&
+ data.lte !== ""
+ ) {
+ const gte = castNumber(data.gte)
+ const lte = castNumber(data.lte)
+ return gte <= lte
+ }
+ return true
+ },
+ {
+ message: t(
+ "stockLocations.shippingOptions.conditionalPrices.errors.minGreaterThanMax"
+ ),
+ path: ["gte"],
+ }
+ )
+
+export type ConditionalPrice = z.infer<typeof ConditionalPriceSchema>
+
+export const UpdateConditionalPriceSchema = ConditionalPriceSchema.and(
+ z.object({
+ id: z.string().optional(),
+ })
+)
+
+export type UpdateConditionalPrice = z.infer<
+ typeof UpdateConditionalPriceSchema
+>
+
+function refineDuplicates(
+ data: {
+ prices: {
+ amount: string | number
+ gte?: string | number | null | undefined
+ lte?: string | number | null | undefined
+ lt?: number | null | undefined
+ gt?: number | null | undefined
+ eq?: number | null | undefined
+ }[]
+ },
+ ctx: z.RefinementCtx
+) {
+ const prices = data.prices
+
+ for (let i = 0; i < prices.length; i++) {
+ for (let j = i + 1; j < prices.length; j++) {
+ const price1 = prices[i]
+ const price2 = prices[j]
+
+ if (price1.amount === "" || price2.amount === "") {
+ continue
+ }
+
+ const price1Amount = castNumber(price1.amount)
+ const price2Amount = castNumber(price2.amount)
+
+ if (price1Amount === price2Amount) {
+ addDuplicateAmountError(ctx, j)
+ }
+
+ // Then check conditions separately
+ const conditions = [
+ { value: price1.gte, type: "gte" },
+ { value: price1.lte, type: "lte" },
+ { value: price1.eq, type: "eq" },
+ { value: price1.lt, type: "lt" },
+ { value: price1.gt, type: "gt" },
+ ] as const
+
+ conditions.forEach((condition1) => {
+ if (!condition1.value && condition1.value !== 0) {
+ return
+ }
+
+ const conditions2 = [
+ { value: price2.gte, type: "gte" },
+ { value: price2.lte, type: "lte" },
+ { value: price2.eq, type: "eq" },
+ { value: price2.lt, type: "lt" },
+ { value: price2.gt, type: "gt" },
+ ] as const
+
+ conditions2.forEach((condition2) => {
+ if (!condition2.value && condition2.value !== 0) {
+ return
+ }
+
+ const condition1Value = castNumber(
+ condition1.value as string | number
+ )
+ const condition2Value = castNumber(
+ condition2.value as string | number
+ )
+
+ if (condition1Value === condition2Value) {
+ addOverlappingConditionError(ctx, j, condition2.type)
+ }
+ })
+ })
+ }
+ }
+}
+
+export const CondtionalPriceRuleSchema = z
+ .object({
+ prices: z.array(ConditionalPriceSchema),
+ })
+ .superRefine(refineDuplicates)
+
+export type CondtionalPriceRuleSchemaType = z.infer<
+ typeof CondtionalPriceRuleSchema
+>
+
+export const UpdateConditionalPriceRuleSchema = z
+ .object({
+ prices: z.array(UpdateConditionalPriceSchema),
+ })
+ .superRefine(refineDuplicates)
+
+export type UpdateConditionalPriceRuleSchemaType = z.infer<
+ typeof UpdateConditionalPriceRuleSchema
+>
+
+const addDuplicateAmountError = (ctx: z.RefinementCtx, index: number) => {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: t(
+ "stockLocations.shippingOptions.conditionalPrices.errors.duplicateAmount"
+ ),
+ path: ["prices", index, "amount"],
+ })
+}
+
+const addOverlappingConditionError = (
+ ctx: z.RefinementCtx,
+ index: number,
+ type: "gte" | "lte" | "eq" | "lt" | "gt"
+) => {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: t(
+ "stockLocations.shippingOptions.conditionalPrices.errors.overlappingConditions"
+ ),
+ path: ["prices", index, type],
+ })
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/types.ts b/packages/vendor/src/pages/settings/locations/_common/types.ts
new file mode 100644
index 000000000..bb0943ece
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/types.ts
@@ -0,0 +1,12 @@
+import { CurrencyInfo } from "@lib/data/currencies"
+
+export type ConditionalShippingOptionPriceAccessor =
+ | `conditional_region_prices.${string}`
+ | `conditional_currency_prices.${string}`
+
+export type ConditionalPriceInfo = {
+ type: "currency" | "region"
+ field: string
+ name: string
+ currency: CurrencyInfo
+}
diff --git a/packages/vendor/src/pages/settings/locations/_common/utils/get-custom-shipping-option-price-field-info.ts b/packages/vendor/src/pages/settings/locations/_common/utils/get-custom-shipping-option-price-field-info.ts
new file mode 100644
index 000000000..1b2232fb8
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_common/utils/get-custom-shipping-option-price-field-info.ts
@@ -0,0 +1,19 @@
+import { ConditionalShippingOptionPriceAccessor } from "../types"
+
+export const getCustomShippingOptionPriceFieldName = (
+ field: string,
+ type: "region" | "currency"
+): ConditionalShippingOptionPriceAccessor => {
+ const prefix = type === "region" ? "region_prices" : "currency_prices"
+ const customPrefix =
+ type === "region"
+ ? "conditional_region_prices"
+ : "conditional_currency_prices"
+
+ const name = field.replace(
+ prefix,
+ customPrefix
+ ) as ConditionalShippingOptionPriceAccessor
+
+ return name
+}
diff --git a/packages/vendor/src/pages/settings/locations/_components/location-list-header.tsx b/packages/vendor/src/pages/settings/locations/_components/location-list-header.tsx
new file mode 100644
index 000000000..8747eeb11
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_components/location-list-header.tsx
@@ -0,0 +1,21 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+export const LocationListHeader = () => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="flex h-fit items-center justify-between gap-x-4 px-6 py-4">
+ <div>
+ <Heading>{t("stockLocations.domain")}</Heading>
+ <Text className="text-ui-fg-subtle txt-small">
+ {t("stockLocations.list.description")}
+ </Text>
+ </div>
+ <Button size="small" className="shrink-0" variant="secondary" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/_components/location-list-item.tsx b/packages/vendor/src/pages/settings/locations/_components/location-list-item.tsx
new file mode 100644
index 000000000..cc081a06d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/_components/location-list-item.tsx
@@ -0,0 +1,188 @@
+import { Buildings, PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, StatusBadge, Text, toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+// import { BadgeListSummary } from "@components/common/badge-list-summary"
+import { LinkButton } from "@components/common/link-button"
+import { useDeleteStockLocation } from "@hooks/api/stock-locations"
+import { getFormattedAddress } from "@lib/addresses"
+import { FulfillmentSetType } from "@pages/settings/locations/_common/constants"
+
+// type SalesChannelsProps = {
+// salesChannels?: HttpTypes.AdminSalesChannel[] | null
+// }
+
+// function SalesChannels(props: SalesChannelsProps) {
+// const { t } = useTranslation()
+// const { salesChannels } = props
+
+// return (
+// <div className="flex flex-col px-6 py-4">
+// <div className="flex items-center justify-between">
+// <Text
+// size="small"
+// weight="plus"
+// className="text-ui-fg-subtle flex-1"
+// as="div"
+// >
+// {t(`stockLocations.salesChannels.label`)}
+// </Text>
+// <div className="flex-1 text-left">
+// {salesChannels?.length ? (
+// <BadgeListSummary
+// rounded
+// inline
+// n={3}
+// list={salesChannels.map((s) => s.name)}
+// />
+// ) : (
+// "-"
+// )}
+// </div>
+// </div>
+// </div>
+// )
+// }
+
+type FulfillmentSetProps = {
+ fulfillmentSet?: HttpTypes.AdminFulfillmentSet
+ type: FulfillmentSetType
+}
+
+function FulfillmentSet(props: FulfillmentSetProps) {
+ const { t } = useTranslation()
+ const { fulfillmentSet, type } = props
+
+ const fulfillmentSetExists = !!fulfillmentSet
+
+ return (
+ <div className="flex flex-col px-6 py-4">
+ <div className="flex items-center justify-between">
+ <Text
+ size="small"
+ weight="plus"
+ className="text-ui-fg-subtle flex-1"
+ as="div"
+ >
+ {t(`stockLocations.fulfillmentSets.${type}.header`)}
+ </Text>
+ <div className="flex-1 text-left">
+ <StatusBadge color={fulfillmentSetExists ? "green" : "grey"}>
+ {t(fulfillmentSetExists ? "statuses.enabled" : "statuses.disabled")}
+ </StatusBadge>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+type LocationProps = {
+ location: HttpTypes.AdminStockLocation
+}
+
+function LocationListItem(props: LocationProps) {
+ const { location } = props
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync: deleteLocation } = useDeleteStockLocation(location.id)
+
+ const handleDelete = async () => {
+ const result = await prompt({
+ title: t("general.areYouSure"),
+ description: t("stockLocations.delete.confirmation", {
+ name: location.name,
+ }),
+ confirmText: t("actions.remove"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!result) {
+ return
+ }
+
+ await deleteLocation(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("shippingProfile.delete.successToast", {
+ name: location.name,
+ })
+ )
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <Container className="flex flex-col divide-y p-0">
+ <div className="px-6 py-4">
+ <div className="flex flex-row items-center justify-between gap-x-4">
+ <div className="shadow-borders-base flex size-7 items-center justify-center rounded-md">
+ <div className="bg-ui-bg-field flex size-6 items-center justify-center rounded-[4px]">
+ <Buildings className="text-ui-fg-subtle" />
+ </div>
+ </div>
+
+ <div className="grow-1 flex flex-1 flex-col">
+ <Text weight="plus">{location.name}</Text>
+ <Text className="text-ui-fg-subtle txt-small">
+ {getFormattedAddress({
+ address: location.address,
+ }).join(", ")}
+ </Text>
+ </div>
+
+ <div className="flex grow-0 items-center gap-4">
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: `/settings/locations/${location.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ <div className="bg-ui-border-strong h-[12px] w-[1px]" />
+ <LinkButton to={`/settings/locations/${location.id}`}>
+ {t("actions.viewDetails")}
+ </LinkButton>
+ </div>
+ </div>
+ </div>
+
+ {/* <SalesChannels salesChannels={location.sales_channels} /> */}
+
+ <FulfillmentSet
+ type={FulfillmentSetType.Pickup}
+ fulfillmentSet={location.fulfillment_sets?.find(
+ (f) => f.type === FulfillmentSetType.Pickup
+ )}
+ />
+ <FulfillmentSet
+ type={FulfillmentSetType.Shipping}
+ fulfillmentSet={location.fulfillment_sets?.find(
+ (f) => f.type === FulfillmentSetType.Shipping
+ )}
+ />
+ </Container>
+ )
+}
+
+export default LocationListItem
diff --git a/packages/vendor/src/pages/settings/locations/constants.ts b/packages/vendor/src/pages/settings/locations/constants.ts
new file mode 100644
index 000000000..201f2ef58
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/constants.ts
@@ -0,0 +1,3 @@
+// TODO: change this when RQ is fixed (address is not joined when *address)
+export const LOCATION_LIST_FIELDS =
+ "name,*sales_channels,*address,*fulfillment_sets,*fulfillment_sets.service_zones,*fulfillment_sets.service_zones.shipping_options,*fulfillment_sets.service_zones.shipping_options.shipping_profile"
diff --git a/packages/vendor/src/pages/settings/locations/create/_components/create-location-form.tsx b/packages/vendor/src/pages/settings/locations/create/_components/create-location-form.tsx
new file mode 100644
index 000000000..607fd9267
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/create/_components/create-location-form.tsx
@@ -0,0 +1,248 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateStockLocation } from "@hooks/api/stock-locations"
+
+const CreateLocationSchema = zod.object({
+ name: zod.string().min(1),
+ address: zod.object({
+ address_1: zod.string().min(1),
+ address_2: zod.string().optional(),
+ country_code: zod.string().min(2).max(2),
+ city: zod.string().optional(),
+ postal_code: zod.string().optional(),
+ province: zod.string().optional(),
+ company: zod.string().optional(),
+ phone: zod.string().optional(),
+ }),
+})
+
+export const CreateLocationForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof CreateLocationSchema>>({
+ defaultValues: {
+ name: "",
+ address: {
+ address_1: "",
+ address_2: "",
+ city: "",
+ company: "",
+ country_code: "",
+ phone: "",
+ postal_code: "",
+ province: "",
+ },
+ },
+ resolver: zodResolver(CreateLocationSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateStockLocation()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ name: values.name,
+ address: values.address,
+ },
+ {
+ onSuccess: ({ stock_location }) => {
+ toast.success(t("locations.toast.create"))
+
+ handleSuccess(`/settings/locations/${stock_location.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading className="capitalize">
+ {t("stockLocations.create.header")}
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("stockLocations.create.hint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ control={form.control}
+ name="address.address_1"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.address")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.address_2"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.address2")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.postal_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("fields.postalCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.city"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.city")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.country_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.country")}</Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.province"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.state")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.company"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.company")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="address.phone"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>{t("fields.phone")}</Form.Label>
+ <Form.Control>
+ <Input size="small" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/locations/create/index.tsx b/packages/vendor/src/pages/settings/locations/create/index.tsx
new file mode 100644
index 000000000..aa8f51501
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/create/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { CreateLocationForm } from "./_components/create-location-form"
+
+const LocationCreate = () => {
+ return (
+ <RouteFocusModal>
+ <CreateLocationForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = LocationCreate
diff --git a/packages/vendor/src/pages/settings/locations/index.tsx b/packages/vendor/src/pages/settings/locations/index.tsx
new file mode 100644
index 000000000..9cdbe2d36
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/index.tsx
@@ -0,0 +1,84 @@
+import { ShoppingBag } from "@medusajs/icons"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useLoaderData } from "react-router-dom"
+
+import { useStockLocations } from "@hooks/api/stock-locations"
+import LocationListItem from "./_components/location-list-item"
+import { LOCATION_LIST_FIELDS } from "./constants"
+import { shippingListLoader } from "./loader"
+
+import { TwoColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { LocationListHeader } from "./_components/location-list-header"
+import { SidebarLink } from "@components/common/sidebar-link/sidebar-link"
+
+function LocationList() {
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof shippingListLoader>
+ >
+
+ const {
+ stock_locations: stockLocations = [],
+ isError,
+ error,
+ } = useStockLocations(
+ {
+ fields: LOCATION_LIST_FIELDS,
+ },
+ { initialData }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <TwoColumnPage
+ widgets={{
+ after: getWidgets("location.details.after"),
+ before: getWidgets("location.details.before"),
+ sideAfter: getWidgets("location.details.side.after"),
+ sideBefore: getWidgets("location.details.side.before"),
+ }}
+ >
+ <TwoColumnPage.Main>
+ <LocationListHeader />
+ <div className="flex flex-col gap-3 lg:col-span-2">
+ {stockLocations.map((location) => (
+ <LocationListItem key={location.id} location={location} />
+ ))}
+ </div>
+ </TwoColumnPage.Main>
+ <TwoColumnPage.Sidebar>
+ <LinksSection />
+ </TwoColumnPage.Sidebar>
+ </TwoColumnPage>
+ )
+}
+
+const LinksSection = () => {
+ const { t } = useTranslation()
+
+ return (
+ <Container className="p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("stockLocations.sidebar.header")}</Heading>
+ </div>
+
+ <SidebarLink
+ to="/settings/locations/shipping-profiles"
+ labelKey={t("stockLocations.sidebar.shippingProfiles.label")}
+ descriptionKey={t(
+ "stockLocations.sidebar.shippingProfiles.description"
+ )}
+ icon={<ShoppingBag />}
+ />
+ </Container>
+ )
+}
+
+export const Component = LocationList
+export { shippingListLoader as loader } from "./loader"
diff --git a/packages/vendor/src/pages/settings/locations/loader.ts b/packages/vendor/src/pages/settings/locations/loader.ts
new file mode 100644
index 000000000..4f66a8755
--- /dev/null
+++ b/packages/vendor/src/pages/settings/locations/loader.ts
@@ -0,0 +1,27 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { HttpTypes } from "@medusajs/types"
+import { stockLocationsQueryKeys } from "@hooks/api/stock-locations"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { LOCATION_LIST_FIELDS } from "./constants"
+
+const shippingListQuery = () => ({
+ queryKey: stockLocationsQueryKeys.lists(),
+ queryFn: async () => {
+ return await fetchQuery("/vendor/stock-locations", {
+ method: "GET",
+ query: { fields: LOCATION_LIST_FIELDS },
+ })
+ },
+})
+
+export const shippingListLoader = async (_: LoaderFunctionArgs) => {
+ const query = shippingListQuery()
+
+ return (
+ queryClient.getQueryData<HttpTypes.AdminStockLocationListResponse>(
+ query.queryKey
+ ) ?? (await queryClient.fetchQuery(query))
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-general-section.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-general-section.tsx
new file mode 100644
index 000000000..78cd9ea51
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-general-section.tsx
@@ -0,0 +1,49 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteProductTagAction } from "@pages/settings/product-tags/_common/hooks/use-delete-product-tag-action"
+
+type ProductTagGeneralSectionProps = {
+ productTag: HttpTypes.AdminProductTag
+}
+
+export const ProductTagGeneralSection = ({
+ productTag,
+}: ProductTagGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeleteProductTagAction({ productTag })
+
+ return (
+ <Container className="flex items-center justify-between" data-testid="product-tag-general-section-container">
+ <div className="flex items-center gap-x-1.5" data-testid="product-tag-general-section-heading-container">
+ <span className="text-ui-fg-muted h1-core">#</span>
+ <Heading data-testid="product-tag-general-section-heading">{productTag.value}</Heading>
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: "edit",
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ data-testid="product-tag-general-section-action-menu"
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-product-section.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-product-section.tsx
new file mode 100644
index 000000000..c2f8e9b36
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/_components/product-tag-product-section.tsx
@@ -0,0 +1,77 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useProducts } from "@hooks/api"
+import { useProductTableColumns } from "@hooks/table/columns"
+import { useProductTableFilters } from "@hooks/table/filters"
+import { useProductTableQuery } from "@hooks/table/query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type ProductTagProductSectionProps = {
+ productTag: HttpTypes.AdminProductTag
+}
+
+const PAGE_SIZE = 10
+const PREFIX = "pt"
+
+export const ProductTagProductSection = ({
+ productTag,
+}: ProductTagProductSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { products, count, isPending, isError, error } = useProducts(
+ {
+ ...searchParams,
+ fields: "*tags",
+ tag_id: productTag.id!,
+ }
+ )
+
+ const filters = useProductTableFilters(["product_tags"])
+ const columns = useProductTableColumns()
+
+ const { table } = useDataTable({
+ data: products,
+ count,
+ columns,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y px-0 py-0">
+ <div className="px-6 py-4">
+ <Heading level="h2">{t("products.domain")}</Heading>
+ </div>
+ <_DataTable
+ table={table}
+ filters={filters}
+ queryObject={raw}
+ isLoading={isPending}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ navigateTo={(row) => `/products/${row.original.id}`}
+ search
+ pagination
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "status", label: t("fields.status") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..bedfa9997
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/breadcrumb.tsx
@@ -0,0 +1,23 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { useProductTag } from "@hooks/api"
+
+type ProductTagDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminProductTagResponse>
+
+export const ProductTagDetailBreadcrumb = (
+ props: ProductTagDetailBreadcrumbProps
+) => {
+ const { id } = props.params || {}
+
+ const { product_tag } = useProductTag(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!product_tag) {
+ return null
+ }
+
+ return <span>{product_tag.value}</span>
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/edit/_components/product-tag-edit-form.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/edit/_components/product-tag-edit-form.tsx
new file mode 100644
index 000000000..08e1dfb8d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/edit/_components/product-tag-edit-form.tsx
@@ -0,0 +1,88 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProductTag } from "@hooks/api"
+
+type ProductTagEditFormProps = {
+ productTag: HttpTypes.AdminProductTag
+}
+
+const ProductTagEditSchema = z.object({
+ value: z.string().min(1),
+})
+
+export const ProductTagEditForm = ({ productTag }: ProductTagEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof ProductTagEditSchema>>({
+ defaultValues: {
+ value: productTag.value,
+ },
+ resolver: zodResolver(ProductTagEditSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateProductTag(productTag.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: ({ product_tag }) => {
+ toast.success(
+ t("productTags.edit.successToast", {
+ value: product_tag.value,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ className="flex size-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("productTags.fields.value")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/edit/index.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/edit/index.tsx
new file mode 100644
index 000000000..2ee5a5efb
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/edit/index.tsx
@@ -0,0 +1,35 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useProductTag } from "@hooks/api"
+import { ProductTagEditForm } from "./_components/product-tag-edit-form"
+
+const ProductTagEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product_tag, isPending, isError, error } = useProductTag(id!)
+
+ const ready = !isPending && !!product_tag
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("productTags.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("productTags.edit.subtitle")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {ready && <ProductTagEditForm productTag={product_tag} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = ProductTagEdit
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/index.tsx b/packages/vendor/src/pages/settings/product-tags/[id]/index.tsx
new file mode 100644
index 000000000..0d8c3a60c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/index.tsx
@@ -0,0 +1,52 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useProductTag } from "@hooks/api"
+import { ProductTagGeneralSection } from "./_components/product-tag-general-section"
+import { ProductTagProductSection } from "./_components/product-tag-product-section"
+import { productTagLoader } from "./loader"
+
+const ProductTagDetail = () => {
+ const { id } = useParams()
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof productTagLoader>
+ >
+
+ const { getWidgets } = useDashboardExtension()
+
+ const { product_tag, isPending, isError, error } = useProductTag(
+ id!,
+ undefined,
+ {
+ initialData,
+ }
+ )
+
+ if (isPending || !product_tag) {
+ return <SingleColumnPageSkeleton showJSON sections={2} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_tag.details.after"),
+ before: getWidgets("product_tag.details.before"),
+ }}
+ data={product_tag}
+ >
+ <ProductTagGeneralSection productTag={product_tag} />
+ <ProductTagProductSection productTag={product_tag} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ProductTagDetail
+export { productTagLoader as loader } from "./loader"
+export { ProductTagDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/product-tags/[id]/loader.ts b/packages/vendor/src/pages/settings/product-tags/[id]/loader.ts
new file mode 100644
index 000000000..051d16d40
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/[id]/loader.ts
@@ -0,0 +1,20 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { productTagsQueryKeys } from "@hooks/api"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const productTagDetailQuery = (id: string) => ({
+ queryKey: productTagsQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/product-tags/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const productTagLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = productTagDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/_common/hooks/use-delete-product-tag-action.tsx b/packages/vendor/src/pages/settings/product-tags/_common/hooks/use-delete-product-tag-action.tsx
new file mode 100644
index 000000000..f2dec2a0f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/_common/hooks/use-delete-product-tag-action.tsx
@@ -0,0 +1,52 @@
+import { HttpTypes } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { useDeleteProductTag } from "@hooks/api"
+
+type UseDeleteProductTagActionProps = {
+ productTag: HttpTypes.AdminProductTag
+}
+
+export const useDeleteProductTagAction = ({
+ productTag,
+}: UseDeleteProductTagActionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const { mutateAsync } = useDeleteProductTag(productTag.id)
+
+ const handleDelete = async () => {
+ const confirmed = await prompt({
+ title: t("general.areYouSure"),
+ description: t("productTags.delete.confirmation", {
+ value: productTag.value,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!confirmed) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("productTags.delete.successToast", {
+ value: productTag.value,
+ })
+ )
+ navigate("/settings/product-tags", {
+ replace: true,
+ })
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/_components/product-tag-list-table.tsx b/packages/vendor/src/pages/settings/product-tags/_components/product-tag-list-table.tsx
new file mode 100644
index 000000000..2053afc51
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/_components/product-tag-list-table.tsx
@@ -0,0 +1,87 @@
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { useLoaderData } from "react-router-dom"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProductTags } from "@hooks/api"
+import { useProductTagTableColumns } from "@hooks/table/columns"
+import { useProductTagTableFilters } from "@hooks/table/filters"
+import { useProductTagTableQuery } from "@hooks/table/query"
+import { useDataTable } from "@hooks/use-data-table"
+import { productTagListLoader } from "../../loader"
+
+const PAGE_SIZE = 20
+
+export const ProductTagListTable = () => {
+ const { t } = useTranslation()
+ const { searchParams, raw } = useProductTagTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof productTagListLoader>
+ >
+
+ const { product_tags, count, isPending, isError, error } = useProductTags(
+ searchParams,
+ {
+ initialData,
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns()
+ const filters = useProductTagTableFilters()
+
+ const { table } = useDataTable({
+ data: product_tags,
+ count,
+ columns,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y px-0 py-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{t("productTags.domain")}</Heading>
+ </div>
+ <_DataTable
+ table={table}
+ filters={filters}
+ queryObject={raw}
+ isLoading={isPending}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ navigateTo={(row) => row.original.id}
+ search
+ pagination
+ orderBy={[
+ { key: "value", label: t("fields.value") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ />
+ </Container>
+ )
+}
+
+const useColumns = () => {
+ const base = useProductTagTableColumns()
+
+ return useMemo(() => [...base], [base])
+}
diff --git a/packages/vendor/src/pages/settings/product-tags/index.tsx b/packages/vendor/src/pages/settings/product-tags/index.tsx
new file mode 100644
index 000000000..375e6202a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-tags/index.tsx
@@ -0,0 +1,23 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ProductTagListTable } from "./_components/product-tag-list-table"
+
+const ProductTagList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ showMetadata={false}
+ showJSON={false}
+ hasOutlet
+ widgets={{
+ after: getWidgets("product_tag.list.after"),
+ before: getWidgets("product_tag.list.before"),
+ }}
+ >
+ <ProductTagListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ProductTagList
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-general-section.tsx b/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-general-section.tsx
new file mode 100644
index 000000000..62b5bb927
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-general-section.tsx
@@ -0,0 +1,45 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteProductTypeAction } from "@pages/settings/product-types/_common/hooks/use-delete-product-type-action"
+
+type ProductTypeGeneralSectionProps = {
+ productType: HttpTypes.AdminProductType
+}
+
+export const ProductTypeGeneralSection = ({
+ productType,
+}: ProductTypeGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeleteProductTypeAction(productType.id)
+
+ return (
+ <Container className="flex items-center justify-between">
+ <Heading>{productType.value}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: "edit",
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-product-section.tsx b/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-product-section.tsx
new file mode 100644
index 000000000..b4d08be97
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/_components/product-type-product-section.tsx
@@ -0,0 +1,71 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProducts } from "@hooks/api/products"
+import { useProductTableColumns } from "@hooks/table/columns/use-product-table-columns"
+import { useProductTableFilters } from "@hooks/table/filters/use-product-table-filters"
+import { useProductTableQuery } from "@hooks/table/query/use-product-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+type ProductTypeProductSectionProps = {
+ productType: HttpTypes.AdminProductType
+}
+
+const PAGE_SIZE = 10
+
+export const ProductTypeProductSection = ({
+ productType,
+}: ProductTypeProductSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { products, count, isPending, isError, error } = useProducts({
+ ...searchParams,
+ fields: "+type_id",
+ type_id: productType.id,
+ })
+
+ const filters = useProductTableFilters(["product_types"])
+ const columns = useProductTableColumns()
+
+ const { table } = useDataTable({
+ columns,
+ data: products,
+ count: products?.length || 0,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="px-6 py-4">
+ <Heading level="h2">{t("products.domain")}</Heading>
+ </div>
+ <_DataTable
+ table={table}
+ filters={filters}
+ isLoading={isPending}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ navigateTo={({ original }) => `/products/${original.id}`}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ queryObject={raw}
+ search
+ pagination
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/product-types/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..01e2a26ea
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/breadcrumb.tsx
@@ -0,0 +1,24 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+
+import { useProductType } from "@hooks/api"
+
+type ProductTypeDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminProductTypeResponse>
+
+export const ProductTypeDetailBreadcrumb = (
+ props: ProductTypeDetailBreadcrumbProps
+) => {
+ const { id } = props.params || {}
+
+ const { product_type } = useProductType(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!product_type) {
+ return null
+ }
+
+ return <span>{product_type.value}</span>
+}
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/edit/_components/edit-product-type-form.tsx b/packages/vendor/src/pages/settings/product-types/[id]/edit/_components/edit-product-type-form.tsx
new file mode 100644
index 000000000..8bbdcc19f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/edit/_components/edit-product-type-form.tsx
@@ -0,0 +1,94 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateProductType } from "@hooks/api/product-types"
+
+const EditProductTypeSchema = z.object({
+ value: z.string().min(1),
+})
+
+type EditProductTypeFormProps = {
+ productType: HttpTypes.AdminProductType
+}
+
+export const EditProductTypeForm = ({
+ productType,
+}: EditProductTypeFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof EditProductTypeSchema>>({
+ defaultValues: {
+ value: productType.value,
+ },
+ resolver: zodResolver(EditProductTypeSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateProductType(productType.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(
+ {
+ value: data.value,
+ },
+ {
+ onSuccess: ({ product_type }) => {
+ toast.success(
+ t("productTypes.edit.successToast", {
+ value: product_type.value,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-8 overflow-y-auto">
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("productTypes.fields.value")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/edit/index.tsx b/packages/vendor/src/pages/settings/product-types/[id]/edit/index.tsx
new file mode 100644
index 000000000..6d03efebb
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/edit/index.tsx
@@ -0,0 +1,30 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useProductType } from "@hooks/api/product-types"
+import { EditProductTypeForm } from "./_components/edit-product-type-form"
+
+const ProductTypeEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { product_type, isPending, isError, error } = useProductType(id!)
+
+ const ready = !isPending && !!product_type
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("productTypes.edit.header")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <EditProductTypeForm productType={product_type} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = ProductTypeEdit
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/index.tsx b/packages/vendor/src/pages/settings/product-types/[id]/index.tsx
new file mode 100644
index 000000000..fd8836f23
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/index.tsx
@@ -0,0 +1,51 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { useProductType } from "@hooks/api/product-types"
+import { ProductTypeGeneralSection } from "./_components/product-type-general-section"
+import { ProductTypeProductSection } from "./_components/product-type-product-section"
+import { productTypeLoader } from "./loader"
+
+const ProductTypeDetail = () => {
+ const { id } = useParams()
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof productTypeLoader>
+ >
+
+ const { product_type, isPending, isError, error } = useProductType(
+ id!,
+ undefined,
+ {
+ initialData,
+ }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isPending || !product_type) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_type.details.after"),
+ before: getWidgets("product_type.details.before"),
+ }}
+ data={product_type}
+ >
+ <ProductTypeGeneralSection productType={product_type} />
+ <ProductTypeProductSection productType={product_type} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ProductTypeDetail
+export { productTypeLoader as loader } from "./loader"
+export { ProductTypeDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/product-types/[id]/loader.ts b/packages/vendor/src/pages/settings/product-types/[id]/loader.ts
new file mode 100644
index 000000000..dc072dedd
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/[id]/loader.ts
@@ -0,0 +1,20 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { productTypesQueryKeys } from "@hooks/api/product-types"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const productTypeDetailQuery = (id: string) => ({
+ queryKey: productTypesQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/product-types/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const productTypeLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = productTypeDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/product-types/_common/hooks/use-delete-product-type-action.tsx b/packages/vendor/src/pages/settings/product-types/_common/hooks/use-delete-product-type-action.tsx
new file mode 100644
index 000000000..b33851d4c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/_common/hooks/use-delete-product-type-action.tsx
@@ -0,0 +1,35 @@
+import { toast, usePrompt } from '@medusajs/ui';
+import { useTranslation } from 'react-i18next';
+
+import { useDeleteProductType } from "@hooks/api/product-types"
+
+export const useDeleteProductTypeAction = (id: string, value: string) => {
+ const { t } = useTranslation();
+ const prompt = usePrompt();
+
+ const { mutateAsync } = useDeleteProductType(id);
+
+ const handleDelete = async () => {
+ const result = await prompt({
+ title: t('general.areYouSure'),
+ description: t('productTypes.delete.confirmation', { value }),
+ confirmText: t('actions.delete'),
+ cancelText: t('actions.cancel')
+ });
+
+ if (!result) {
+ return;
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t('productTypes.delete.successToast', { value }));
+ },
+ onError: e => {
+ toast.error(e.message);
+ }
+ });
+ };
+
+ return handleDelete;
+};
diff --git a/packages/vendor/src/pages/settings/product-types/_components/product-table-row-actions.tsx b/packages/vendor/src/pages/settings/product-types/_components/product-table-row-actions.tsx
new file mode 100644
index 000000000..200d7a72b
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/_components/product-table-row-actions.tsx
@@ -0,0 +1,40 @@
+import { PencilSquare, Trash } from '@medusajs/icons';
+import { HttpTypes } from '@medusajs/types';
+import { useTranslation } from 'react-i18next';
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteProductTypeAction } from "../_common/hooks/use-delete-product-type-action"
+
+type ProductTypeRowActionsProps = {
+ productType: HttpTypes.AdminProductType;
+};
+
+export const ProductTypeRowActions = ({ productType }: ProductTypeRowActionsProps) => {
+ const { t } = useTranslation();
+ const handleDelete = useDeleteProductTypeAction(productType.id, productType.value);
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t('actions.edit'),
+ icon: <PencilSquare />,
+ to: `/settings/product-types/${productType.id}/edit`
+ }
+ ]
+ },
+ {
+ actions: [
+ {
+ label: t('actions.delete'),
+ icon: <Trash />,
+ onClick: handleDelete
+ }
+ ]
+ }
+ ]}
+ />
+ );
+};
diff --git a/packages/vendor/src/pages/settings/product-types/_components/product-type-list-table.tsx b/packages/vendor/src/pages/settings/product-types/_components/product-type-list-table.tsx
new file mode 100644
index 000000000..f942143b9
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/_components/product-type-list-table.tsx
@@ -0,0 +1,104 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { _DataTable } from "@components/table/data-table"
+import { useProductTypes } from "@hooks/api/product-types"
+import { useProductTypeTableColumns } from "@hooks/table/columns/use-product-type-table-columns"
+import { useProductTypeTableFilters } from "@hooks/table/filters/use-product-type-table-filters"
+import { useProductTypeTableQuery } from "@hooks/table/query/use-product-type-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { ProductTypeRowActions } from "./product-table-row-actions"
+
+const PAGE_SIZE = 20
+
+export const ProductTypeListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useProductTypeTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { product_types, count, isLoading, isError, error } = useProductTypes(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = useProductTypeTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ columns,
+ data: product_types,
+ count,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("productTypes.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("productTypes.subtitle")}
+ </Text>
+ </div>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="create">Request Product Type</Link>
+ </Button>
+ </div>
+ <_DataTable
+ table={table}
+ filters={filters}
+ isLoading={isLoading}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ orderBy={[
+ { key: "value", label: t("fields.value") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ navigateTo={({ original }) => original.id}
+ queryObject={raw}
+ pagination
+ search
+ />
+ </Container>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminProductType>()
+
+const useColumns = () => {
+ const base = useProductTypeTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <ProductTypeRowActions productType={row.original} />
+ },
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-types/create/_components/create-product-type-form.tsx b/packages/vendor/src/pages/settings/product-types/create/_components/create-product-type-form.tsx
new file mode 100644
index 000000000..2e93269da
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/create/_components/create-product-type-form.tsx
@@ -0,0 +1,99 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateProductType } from "@hooks/api/product-types"
+
+const CreateProductTypeSchema = z.object({
+ value: z.string().min(1),
+})
+
+export const CreateProductTypeForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof CreateProductTypeSchema>>({
+ defaultValues: {
+ value: "",
+ },
+ resolver: zodResolver(CreateProductTypeSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateProductType()
+
+ const handleSubmit = form.handleSubmit(
+ async (values: z.infer<typeof CreateProductTypeSchema>) => {
+ await mutateAsync(values, {
+ onSuccess: () => {
+ toast.success("Product type requested successfully")
+
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+ )
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button
+ size="small"
+ variant="primary"
+ type="submit"
+ isLoading={isPending}
+ >
+ Request
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex flex-col items-center overflow-y-auto p-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <Heading>Request Product Type</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("productTypes.create.hint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("productTypes.fields.value")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/product-types/create/index.tsx b/packages/vendor/src/pages/settings/product-types/create/index.tsx
new file mode 100644
index 000000000..baab41c4b
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/create/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { CreateProductTypeForm } from "./_components/create-product-type-form"
+
+const ProductTypeCreate = () => {
+ return (
+ <RouteFocusModal>
+ <CreateProductTypeForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = ProductTypeCreate
diff --git a/packages/vendor/src/pages/settings/product-types/index.tsx b/packages/vendor/src/pages/settings/product-types/index.tsx
new file mode 100644
index 000000000..adec4e75c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/product-types/index.tsx
@@ -0,0 +1,20 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ProductTypeListTable } from "./_components/product-type-list-table"
+
+const ProductTypeList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("product_type.list.after"),
+ before: getWidgets("product_type.list.before"),
+ }}
+ >
+ <ProductTypeListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ProductTypeList
diff --git a/packages/vendor/src/pages/settings/profile/_components/profile-general-section.tsx b/packages/vendor/src/pages/settings/profile/_components/profile-general-section.tsx
new file mode 100644
index 000000000..6d286f624
--- /dev/null
+++ b/packages/vendor/src/pages/settings/profile/_components/profile-general-section.tsx
@@ -0,0 +1,81 @@
+import { PencilSquare } from "@medusajs/icons"
+import { Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { ImageAvatar } from "@components/common/image-avatar"
+import { TeamMemberProps } from "@custom-types/user"
+
+type ProfileGeneralSectionProps = {
+ user: TeamMemberProps
+}
+
+export const ProfileGeneralSection = ({ user }: ProfileGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const { name, email, photo, phone, bio } = user
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("profile.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("profile.manageYourProfileDetails")}
+ </Text>
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "edit",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ Photo
+ </Text>
+ <ImageAvatar src={photo || "/logo.svg"} size={8} rounded />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.name")}
+ </Text>
+ <Text size="small" leading="compact">
+ {name || "-"}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.email")}
+ </Text>
+ <Text size="small" leading="compact">
+ {email}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ Phone
+ </Text>
+ <Text size="small" leading="compact">
+ {phone}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ Bio
+ </Text>
+ <Text size="small" leading="compact">
+ {bio}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/profile/edit/_components/edit-profile-form.tsx b/packages/vendor/src/pages/settings/profile/edit/_components/edit-profile-form.tsx
new file mode 100644
index 000000000..108d874ab
--- /dev/null
+++ b/packages/vendor/src/pages/settings/profile/edit/_components/edit-profile-form.tsx
@@ -0,0 +1,235 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Input, Textarea, toast } from "@medusajs/ui"
+import { useFieldArray, useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+import { useCallback } from "react"
+import { HttpTypes } from "@medusajs/types"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateUser } from "@hooks/api/users"
+import { TeamMemberProps } from "@custom-types/user"
+import { MediaSchema } from "@pages/products/create/constants"
+import { FileType, FileUpload } from "@components/common/file-upload"
+import { uploadFilesQuery } from "@lib/client"
+
+type EditProfileProps = {
+ user: TeamMemberProps
+}
+
+const EditProfileSchema = zod.object({
+ name: zod.string().optional(),
+ media: zod.array(MediaSchema).optional(),
+ phone: zod.string().optional(),
+ bio: zod.string().optional(),
+})
+
+const SUPPORTED_FORMATS = [
+ "image/jpeg",
+ "image/png",
+ "image/gif",
+ "image/webp",
+ "image/heic",
+ "image/svg+xml",
+]
+
+const SUPPORTED_FORMATS_FILE_EXTENSIONS = [
+ ".jpeg",
+ ".png",
+ ".gif",
+ ".webp",
+ ".heic",
+ ".svg",
+]
+
+export const EditProfileForm = ({ user }: EditProfileProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditProfileSchema>>({
+ defaultValues: {
+ name: user.name ?? "",
+ phone: user.phone ?? "",
+ bio: user.bio ?? "",
+ media: [],
+ },
+ resolver: zodResolver(EditProfileSchema),
+ })
+
+ const { fields } = useFieldArray({
+ name: "media",
+ control: form.control,
+ keyName: "field_id",
+ })
+
+ const { mutateAsync, isPending } = useUpdateUser(user.id!)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ let uploadedMedia: (HttpTypes.AdminFile & {
+ isThumbnail: boolean
+ })[] = []
+ try {
+ if (values.media?.length) {
+ const fileReqs = []
+ fileReqs.push(
+ uploadFilesQuery(values.media).then((r: any) =>
+ r.files.map((f: any) => ({
+ ...f,
+ isThumbnail: false,
+ }))
+ )
+ )
+
+ uploadedMedia = (await Promise.all(fileReqs)).flat()
+ }
+ } catch (error) {
+ if (error instanceof Error) {
+ toast.error(error.message)
+ }
+ }
+
+ await mutateAsync(
+ {
+ name: values.name,
+ photo: uploadedMedia[0]?.url || user.photo || "",
+ phone: values.phone,
+ bio: values.bio,
+ },
+ {
+ onError: (error) => {
+ toast.error(error.message)
+ return
+ },
+ }
+ )
+
+ toast.success(t("profile.toast.edit"))
+ handleSuccess()
+ })
+
+ const hasInvalidFiles = useCallback(
+ (fileList: FileType[]) => {
+ const invalidFile = fileList.find(
+ (f) => !SUPPORTED_FORMATS.includes(f.file.type)
+ )
+
+ if (invalidFile) {
+ form.setError("media", {
+ type: "invalid_file",
+ message: t("products.media.invalidFileType", {
+ name: invalidFile.file.name,
+ types: SUPPORTED_FORMATS_FILE_EXTENSIONS.join(", "),
+ }),
+ })
+
+ return true
+ }
+
+ return false
+ },
+ [form, t]
+ )
+
+ const onUploaded = useCallback(
+ (files: FileType[]) => {
+ form.clearErrors("media")
+ if (hasInvalidFiles(files)) {
+ return
+ }
+
+ form.setValue("media", [{ ...files[0], isThumbnail: false }])
+ },
+ [form, hasInvalidFiles]
+ )
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-8">
+ <Form.Field
+ name="media"
+ control={form.control}
+ render={() => {
+ return (
+ <Form.Item>
+ <div className="flex flex-col gap-y-2">
+ <div className="flex flex-col gap-y-1">
+ <Form.Label>Profile picture</Form.Label>
+ </div>
+ <Form.Control>
+ <FileUpload
+ uploadedImage={fields[0]?.url || user.photo || ""}
+ multiple={false}
+ label={t("products.media.uploadImagesLabel")}
+ hint={t("products.media.uploadImagesHint")}
+ hasError={!!form.formState.errors.media}
+ formats={SUPPORTED_FORMATS}
+ onUploaded={onUploaded}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Name</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="phone"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Phone</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="bio"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>Bio</Form.Label>
+ <Form.Control>
+ <Textarea {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/profile/edit/index.tsx b/packages/vendor/src/pages/settings/profile/edit/index.tsx
new file mode 100644
index 000000000..df4594342
--- /dev/null
+++ b/packages/vendor/src/pages/settings/profile/edit/index.tsx
@@ -0,0 +1,28 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { RouteDrawer } from "@components/modals"
+import { useUserMe } from "@hooks/api/users"
+import { EditProfileForm } from "./_components/edit-profile-form"
+
+const ProfileEdit = () => {
+ const { member, isPending: isLoading, isError, error } = useUserMe()
+ const { t } = useTranslation()
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header className="capitalize">
+ <RouteDrawer.Title asChild>
+ <Heading>{t("profile.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ </RouteDrawer.Header>
+ {!isLoading && member && <EditProfileForm user={member} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = ProfileEdit
diff --git a/packages/vendor/src/pages/settings/profile/index.tsx b/packages/vendor/src/pages/settings/profile/index.tsx
new file mode 100644
index 000000000..fb7a9cd35
--- /dev/null
+++ b/packages/vendor/src/pages/settings/profile/index.tsx
@@ -0,0 +1,32 @@
+import { useUserMe } from "@hooks/api/users"
+import { ProfileGeneralSection } from "./_components/profile-general-section"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+
+const ProfileDetail = () => {
+ const { member, isPending: isLoading, isError, error } = useUserMe()
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !member) {
+ return <SingleColumnPageSkeleton sections={1} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("profile.details.after"),
+ before: getWidgets("profile.details.before"),
+ }}
+ >
+ <ProfileGeneralSection user={member} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ProfileDetail
diff --git a/packages/vendor/src/pages/settings/regions/[id]/_components/helpers.ts b/packages/vendor/src/pages/settings/regions/[id]/_components/helpers.ts
new file mode 100644
index 000000000..d714ab82e
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/_components/helpers.ts
@@ -0,0 +1,21 @@
+import { StaticCountry } from "@lib/data/countries"
+import { HttpTypes } from "@medusajs/types"
+
+/**
+ * Converts API region countries to static countries for use with useCountries hook.
+ * StaticCountry requires all fields to be non-optional (except id which is omitted).
+ */
+export const convertToStaticCountries = (
+ apiCountries: HttpTypes.AdminRegionCountry[] | undefined
+): StaticCountry[] => {
+ if (!apiCountries) return []
+
+ return apiCountries
+ .filter((c): c is Required<HttpTypes.AdminRegionCountry> => {
+ const requiredFields: (keyof HttpTypes.AdminRegionCountry)[] = [
+ 'iso_2', 'iso_3', 'num_code', 'name', 'display_name'
+ ]
+ return requiredFields.every(field => !!c[field])
+ })
+ .map(({ id, ...country }) => country as StaticCountry)
+}
\ No newline at end of file
diff --git a/packages/vendor/src/pages/settings/regions/[id]/_components/region-country-section.tsx b/packages/vendor/src/pages/settings/regions/[id]/_components/region-country-section.tsx
new file mode 100644
index 000000000..90c6f968f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/_components/region-country-section.tsx
@@ -0,0 +1,258 @@
+import { PlusMini, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Checkbox, Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import {
+ ColumnDef,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useUpdateRegion } from "@hooks/api/regions"
+import { useDataTable } from "@hooks/use-data-table"
+import { StaticCountry } from "@lib/data/countries"
+import { useCountries } from "@pages/settings/regions/_common/hooks/use-countries"
+import { useCountryTableColumns } from "@pages/settings/regions/_common/hooks/use-country-table-columns"
+import { useCountryTableQuery } from "@pages/settings/regions/_common/hooks/use-country-table-query"
+import { convertToStaticCountries } from "./helpers"
+
+type RegionCountrySectionProps = {
+ region: HttpTypes.AdminRegion
+}
+
+const PREFIX = "c"
+const PAGE_SIZE = 10
+
+export const RegionCountrySection = ({ region }: RegionCountrySectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const { searchParams, raw } = useCountryTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { countries, count } = useCountries({
+ countries: convertToStaticCountries(region.countries),
+ ...searchParams,
+ })
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: countries || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.iso_2,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ prefix: PREFIX,
+ meta: {
+ region,
+ },
+ })
+
+ const { mutateAsync } = useUpdateRegion(region.id)
+
+ const handleRemoveCountries = async () => {
+ const ids = Object.keys(rowSelection).filter((k) => rowSelection[k])
+
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.removeCountriesWarning", {
+ count: ids.length,
+ }),
+ verificationText: t("actions.remove"),
+ verificationInstruction: t("general.typeToConfirm"),
+ cancelText: t("actions.cancel"),
+ confirmText: t("actions.remove"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ const payload = region.countries
+ ?.filter((c) => !ids.includes(c.iso_2!))
+ .map((c) => c.iso_2!)
+
+ await mutateAsync(
+ {
+ countries: payload,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.toast.countries"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading level="h2">{t("fields.countries")}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("regions.addCountries"),
+ icon: <PlusMini />,
+ to: "countries/add",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ orderBy={[
+ { key: "display_name", label: t("fields.name") },
+ { key: "iso_2", label: t("fields.code") },
+ ]}
+ search
+ pagination
+ queryObject={raw}
+ prefix={PREFIX}
+ commands={[
+ {
+ action: handleRemoveCountries,
+ label: t("actions.remove"),
+ shortcut: "r",
+ },
+ ]}
+ />
+ </Container>
+ )
+}
+
+const CountryActions = ({
+ country,
+ region,
+}: {
+ country: StaticCountry
+ region: HttpTypes.AdminRegion
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const { mutateAsync } = useUpdateRegion(region.id)
+
+ const handleRemove = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.removeCountryWarning", {
+ name: country.display_name,
+ }),
+ verificationText: country.display_name,
+ verificationInstruction: t("general.typeToConfirm"),
+ cancelText: t("actions.cancel"),
+ confirmText: t("actions.remove"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ const payload = region.countries
+ ?.filter((c) => c.iso_2 !== country.iso_2)
+ .map((c) => c.iso_2)
+ .filter((iso): iso is string => iso !== undefined)
+
+ await mutateAsync(
+ {
+ countries: payload,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.toast.countries"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.remove"),
+ onClick: handleRemove,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<StaticCountry>()
+
+const useColumns = () => {
+ const base = useCountryTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row, table }) => {
+ const { region } = table.options.meta as {
+ region: HttpTypes.AdminRegion
+ }
+
+ return <CountryActions country={row.original} region={region} />
+ },
+ }),
+ ],
+ [base]
+ ) as ColumnDef<StaticCountry>[]
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/_components/region-general-section.tsx b/packages/vendor/src/pages/settings/regions/[id]/_components/region-general-section.tsx
new file mode 100644
index 000000000..f6bbb726a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/_components/region-general-section.tsx
@@ -0,0 +1,138 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { Badge, Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { HttpTypes } from "@medusajs/types"
+import { useNavigate } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu/index.ts"
+import { ListSummary } from "@components/common/list-summary/index.ts"
+import { useDeleteRegion } from "@hooks/api/regions.tsx"
+import { currencies } from "@lib/data/currencies.ts"
+import { formatProvider } from "@lib/format-provider.ts"
+import { SectionRow } from "@components/common/section/section-row.tsx"
+
+type RegionGeneralSectionProps = {
+ region: HttpTypes.AdminRegion
+ pricePreferences: HttpTypes.AdminPricePreference[]
+}
+
+export const RegionGeneralSection = ({
+ region,
+ pricePreferences,
+}: RegionGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const pricePreferenceForRegion = pricePreferences?.find(
+ (preference) =>
+ preference.attribute === "region_id" && preference.value === region.id
+ )
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{region.name}</Heading>
+ <RegionActions region={region} />
+ </div>
+ <SectionRow
+ title={t("fields.currency")}
+ value={
+ <div className="flex items-center gap-x-2">
+ <Badge size="2xsmall" className="uppercase">
+ {region.currency_code}
+ </Badge>
+ <Text size="small" leading="compact">
+ {currencies[region.currency_code.toUpperCase()].name}
+ </Text>
+ </div>
+ }
+ />
+
+ <SectionRow
+ title={t("fields.automaticTaxes")}
+ value={region.automatic_taxes ? t("fields.true") : t("fields.false")}
+ />
+
+ <SectionRow
+ title={t("fields.taxInclusivePricing")}
+ value={
+ pricePreferenceForRegion?.is_tax_inclusive
+ ? t("fields.true")
+ : t("fields.false")
+ }
+ />
+
+ <SectionRow
+ title={t("fields.paymentProviders")}
+ value={
+ <div className="inline-flex">
+ {region.payment_providers?.length ? (
+ <ListSummary
+ list={region.payment_providers.map((p) => formatProvider(p.id))}
+ />
+ ) : (
+ "-"
+ )}
+ </div>
+ }
+ />
+ </Container>
+ )
+}
+
+const RegionActions = ({ region }: { region: HttpTypes.AdminRegion }) => {
+ const navigate = useNavigate()
+ const { t } = useTranslation()
+ const { mutateAsync } = useDeleteRegion(region.id)
+ const prompt = usePrompt()
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.deleteRegionWarning", {
+ name: region.name,
+ }),
+ verificationText: region.name,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("regions.toast.delete"))
+ navigate("/settings/regions", { replace: true })
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `/settings/regions/${region.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/regions/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..644144e70
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/breadcrumb.tsx
@@ -0,0 +1,27 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { useRegion } from "@hooks/api/regions"
+import { REGION_DETAIL_FIELDS } from "./constants"
+
+type RegionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminRegionResponse>
+
+export const RegionDetailBreadcrumb = (props: RegionDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { region } = useRegion(
+ id!,
+ {
+ fields: REGION_DETAIL_FIELDS,
+ },
+ {
+ initialData: props.data,
+ enabled: Boolean(id),
+ }
+ )
+
+ if (!region) {
+ return null
+ }
+
+ return <span>{region.name}</span>
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/constants.ts b/packages/vendor/src/pages/settings/regions/[id]/constants.ts
new file mode 100644
index 000000000..f8b82634f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/constants.ts
@@ -0,0 +1,2 @@
+export const REGION_DETAIL_FIELDS =
+ "*payment_providers,*countries,+automatic_taxes"
diff --git a/packages/vendor/src/pages/settings/regions/[id]/countries/add/_components/add-countries-form.tsx b/packages/vendor/src/pages/settings/regions/[id]/countries/add/_components/add-countries-form.tsx
new file mode 100644
index 000000000..aec71ca41
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/countries/add/_components/add-countries-form.tsx
@@ -0,0 +1,207 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import {
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox, toast } from "@medusajs/ui"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateRegion } from "@hooks/api/regions"
+import { useDataTable } from "@hooks/use-data-table"
+import { countries as staticCountries, StaticCountry } from "@lib/data/countries"
+import { useCountries } from "@pages/settings/regions/_common/hooks/use-countries"
+import { useCountryTableColumns } from "@pages/settings/regions/_common/hooks/use-country-table-columns"
+import { useCountryTableQuery } from "@pages/settings/regions/_common/hooks/use-country-table-query"
+
+type AddCountriesFormProps = {
+ region: HttpTypes.AdminRegion
+}
+
+const AddCountriesSchema = zod.object({
+ countries: zod.array(zod.string()).min(1),
+})
+
+const PAGE_SIZE = 50
+const PREFIX = "ac"
+
+export const AddCountriesForm = ({ region }: AddCountriesFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+
+ const form = useForm<zod.infer<typeof AddCountriesSchema>>({
+ defaultValues: {
+ countries: [],
+ },
+ resolver: zodResolver(AddCountriesSchema),
+ })
+
+ const { setValue } = form
+
+ useEffect(() => {
+ const ids = Object.keys(rowSelection).filter((k) => rowSelection[k])
+
+ setValue("countries", ids, {
+ shouldDirty: true,
+ shouldTouch: true,
+ })
+ }, [rowSelection, setValue])
+
+ const { searchParams, raw } = useCountryTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { countries, count } = useCountries({
+ countries: staticCountries.map((c, i) => ({
+ display_name: c.display_name,
+ name: c.name,
+ id: i as any,
+ iso_2: c.iso_2,
+ iso_3: c.iso_3,
+ num_code: c.num_code,
+ region_id: null,
+ region: {} as HttpTypes.AdminRegion,
+ })),
+ ...searchParams,
+ })
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: countries || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: (row) => {
+ return (
+ region.countries?.findIndex((c) => c.iso_2 === row.original.iso_2) ===
+ -1
+ )
+ },
+ getRowId: (row) => row.iso_2,
+ pageSize: PAGE_SIZE,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ prefix: PREFIX,
+ })
+
+ const { mutateAsync, isPending: isLoading } = useUpdateRegion(region.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const payload = [
+ ...(region.countries?.map((c) => c.iso_2!) ?? []),
+ ...values.countries,
+ ]
+
+ await mutateAsync(
+ {
+ countries: payload,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.toast.countries"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" isLoading={isLoading} type="submit">
+ {t("actions.add")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ search="autofocus"
+ pagination
+ layout="fill"
+ orderBy={[
+ { key: "display_name", label: t("fields.name") },
+ { key: "iso_2", label: t("fields.code") },
+ ]}
+ queryObject={raw}
+ prefix={PREFIX}
+ />
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<StaticCountry>()
+
+const useColumns = () => {
+ const base = useCountryTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreselected = !row.getCanSelect()
+
+ return (
+ <Checkbox
+ checked={row.getIsSelected() || isPreselected}
+ disabled={isPreselected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/countries/add/index.tsx b/packages/vendor/src/pages/settings/regions/[id]/countries/add/index.tsx
new file mode 100644
index 000000000..42ee66db0
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/countries/add/index.tsx
@@ -0,0 +1,29 @@
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useRegion } from "@hooks/api/regions"
+import { AddCountriesForm } from "./_components/add-countries-form"
+
+const RegionAddCountries = () => {
+ const { id } = useParams()
+
+ const {
+ region,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useRegion(id!, {
+ fields: "*payment_providers",
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && region && <AddCountriesForm region={region} />}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = RegionAddCountries
diff --git a/packages/vendor/src/pages/settings/regions/[id]/edit/_components/edit-region-form.tsx b/packages/vendor/src/pages/settings/regions/[id]/edit/_components/edit-region-form.tsx
new file mode 100644
index 000000000..12e55007a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/edit/_components/edit-region-form.tsx
@@ -0,0 +1,229 @@
+import { HttpTypes, PaymentProviderDTO } from "@medusajs/types"
+import { Button, Input, Select, Switch, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form/index.ts"
+import { Combobox } from "@components/inputs/combobox/index.ts"
+import {
+ RouteDrawer,
+ useRouteModal,
+} from "@components/modals/index.ts"
+import { KeyboundForm } from "@components/utilities/keybound-form/keybound-form.tsx"
+import { useUpdateRegion } from "@hooks/api/regions.tsx"
+import { CurrencyInfo } from "@lib/data/currencies.ts"
+import { formatProvider } from "@lib/format-provider.ts"
+
+type EditRegionFormProps = {
+ region: HttpTypes.AdminRegion
+ currencies: CurrencyInfo[]
+ paymentProviders: PaymentProviderDTO[]
+ pricePreferences: HttpTypes.AdminPricePreference[]
+}
+
+const EditRegionSchema = zod.object({
+ name: zod.string().min(1),
+ currency_code: zod.string(),
+ payment_providers: zod.array(zod.string()),
+ automatic_taxes: zod.boolean(),
+ is_tax_inclusive: zod.boolean(),
+})
+
+export const EditRegionForm = ({
+ region,
+ currencies,
+ paymentProviders,
+ pricePreferences,
+}: EditRegionFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const pricePreferenceForRegion = pricePreferences?.find(
+ (preference) =>
+ preference.attribute === "region_id" && preference.value === region.id
+ )
+
+ const form = useForm<zod.infer<typeof EditRegionSchema>>({
+ defaultValues: {
+ name: region.name,
+ currency_code: region.currency_code.toUpperCase(),
+ payment_providers: region.payment_providers?.map((pp) => pp.id) || [],
+ automatic_taxes: region.automatic_taxes,
+ is_tax_inclusive: pricePreferenceForRegion?.is_tax_inclusive || false,
+ },
+ })
+
+ const { mutateAsync: updateRegion, isPending: isPendingRegion } =
+ useUpdateRegion(region.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await updateRegion(
+ {
+ name: values.name,
+ automatic_taxes: values.automatic_taxes,
+ currency_code: values.currency_code.toLowerCase(),
+ payment_providers: values.payment_providers,
+ is_tax_inclusive: values.is_tax_inclusive,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("regions.toast.edit"))
+ handleSuccess()
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex flex-1 flex-col">
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-8">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="currency_code"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.currency")}</Form.Label>
+ <Form.Control>
+ <Select onValueChange={onChange} {...field}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {currencies.map((c) => (
+ <Select.Item key={c.code} value={c.code}>
+ {c.code.toUpperCase()}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="automatic_taxes"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div>
+ <div className="flex items-start justify-between">
+ <Form.Label>{t("fields.automaticTaxes")}</Form.Label>
+ <Form.Control>
+ <Switch
+ {...field}
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ </div>
+ <Form.Hint>{t("regions.automaticTaxesHint")}</Form.Hint>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="is_tax_inclusive"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div>
+ <div className="flex items-start justify-between">
+ <Form.Label>
+ {t("fields.taxInclusivePricing")}
+ </Form.Label>
+ <Form.Control>
+ <Switch
+ {...field}
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ </div>
+ <Form.Hint>{t("regions.taxInclusiveHint")}</Form.Hint>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <div>
+ <Text size="small" leading="compact" weight="plus">
+ Providers
+ </Text>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("regions.providersHint")}
+ </Text>
+ </div>
+ <Form.Field
+ control={form.control}
+ name="payment_providers"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.paymentProviders")}</Form.Label>
+ <Form.Control>
+ <Combobox
+ options={paymentProviders.map((pp) => ({
+ label: formatProvider(pp.id),
+ value: pp.id,
+ }))}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPendingRegion}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/edit/index.tsx b/packages/vendor/src/pages/settings/regions/[id]/edit/index.tsx
new file mode 100644
index 000000000..9a7fa3144
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/edit/index.tsx
@@ -0,0 +1,85 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { usePaymentProviders } from "@hooks/api/payments"
+import { useRegion } from "@hooks/api/regions"
+import { useStore } from "@hooks/api/store"
+import { currencies } from "@lib/data/currencies"
+import { EditRegionForm } from "./_components/edit-region-form"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+
+const RegionEdit = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+
+ const {
+ region,
+ isPending: isRegionLoading,
+ isError: isRegionError,
+ error: regionError,
+ } = useRegion(id!, {
+ fields: "*payment_providers,*countries,+automatic_taxes",
+ })
+
+ const {
+ store,
+ isPending: isStoreLoading,
+ isError: isStoreError,
+ error: storeError,
+ } = useStore()
+
+ const {
+ price_preferences: pricePreferences = [],
+ isPending: isPreferenceLoading,
+ isError: isPreferenceError,
+ error: preferenceError,
+ } = usePricePreferences(
+ {
+ attribute: "region_id",
+ value: id,
+ },
+ { enabled: !!region }
+ )
+
+ const isLoading = isRegionLoading || isStoreLoading || isPreferenceLoading
+
+ const storeCurrencies = (store?.supported_currencies ?? []).map(
+ (c) => currencies[c.currency_code.toUpperCase()]
+ )
+ const { payment_providers: paymentProviders = [] } = usePaymentProviders({
+ limit: 999,
+ is_enabled: true,
+ })
+
+ if (isRegionError) {
+ throw regionError
+ }
+
+ if (isStoreError) {
+ throw storeError
+ }
+
+ if (isPreferenceError) {
+ throw preferenceError
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("regions.editRegion")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && region && (
+ <EditRegionForm
+ region={region}
+ currencies={storeCurrencies}
+ paymentProviders={paymentProviders}
+ pricePreferences={pricePreferences}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
+
+export const Component = RegionEdit
diff --git a/packages/vendor/src/pages/settings/regions/[id]/index.tsx b/packages/vendor/src/pages/settings/regions/[id]/index.tsx
new file mode 100644
index 000000000..8bdcb2472
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/index.tsx
@@ -0,0 +1,79 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { useRegion } from "@hooks/api/regions"
+import { RegionCountrySection } from "./_components/region-country-section"
+import { RegionGeneralSection } from "./_components/region-general-section"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { usePricePreferences } from "@hooks/api/price-preferences"
+import { REGION_DETAIL_FIELDS } from "./constants"
+
+export { regionLoader as loader } from "./loader"
+export { RegionDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
+
+const RegionDetail = () => {
+ const initialData = useLoaderData() as any
+
+ const { id } = useParams()
+ const {
+ region,
+ isPending: isLoading,
+ isError: isRegionError,
+ error: regionError,
+ } = useRegion(
+ id!,
+ { fields: REGION_DETAIL_FIELDS },
+ {
+ initialData,
+ }
+ )
+
+ const {
+ price_preferences: pricePreferences,
+ isPending: isLoadingPreferences,
+ isError: isPreferencesError,
+ error: preferencesError,
+ } = usePricePreferences(
+ {
+ attribute: "region_id",
+ value: id,
+ },
+ { enabled: !!region }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || isLoadingPreferences || !region) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ if (isRegionError) {
+ throw regionError
+ }
+
+ if (isPreferencesError) {
+ throw preferencesError
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("region.details.before"),
+ after: getWidgets("region.details.after"),
+ }}
+ data={region}
+ showMetadata
+ showJSON
+ >
+ <RegionGeneralSection
+ region={region}
+ pricePreferences={pricePreferences ?? []}
+ />
+ <RegionCountrySection region={region} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = RegionDetail
diff --git a/packages/vendor/src/pages/settings/regions/[id]/loader.ts b/packages/vendor/src/pages/settings/regions/[id]/loader.ts
new file mode 100644
index 000000000..c70938c37
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/loader.ts
@@ -0,0 +1,25 @@
+import { HttpTypes } from "@medusajs/types"
+import { LoaderFunctionArgs } from "react-router-dom"
+import { regionsQueryKeys } from "@hooks/api/regions"
+import { sdk } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+import { REGION_DETAIL_FIELDS } from "./constants"
+
+const regionQuery = (id: string) => ({
+ queryKey: regionsQueryKeys.detail(id),
+ queryFn: async () =>
+ sdk.admin.region.retrieve(id, {
+ fields: REGION_DETAIL_FIELDS,
+ }),
+})
+
+export const regionLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = regionQuery(id!)
+
+ return (
+ queryClient.getQueryData<{ region: HttpTypes.AdminRegion }>(
+ query.queryKey
+ ) ?? (await queryClient.fetchQuery(query))
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/[id]/metadata/index.tsx b/packages/vendor/src/pages/settings/regions/[id]/metadata/index.tsx
new file mode 100644
index 000000000..8cd4511fd
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/[id]/metadata/index.tsx
@@ -0,0 +1,29 @@
+import { useParams } from "react-router-dom"
+
+import { MetadataForm } from "@components/forms/metadata-form"
+import { RouteDrawer } from "@components/modals"
+import { useRegion, useUpdateRegion } from "@hooks/api"
+
+const RegionMetadata = () => {
+ const { id } = useParams()
+
+ const { region, isPending, isError, error } = useRegion(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateRegion(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <MetadataForm
+ isPending={isPending}
+ isMutating={isMutating}
+ hook={mutateAsync}
+ metadata={region?.metadata}
+ />
+ </RouteDrawer>
+ )
+}
+
+export const Component = RegionMetadata
diff --git a/packages/vendor/src/pages/settings/regions/_common/hooks/use-countries.tsx b/packages/vendor/src/pages/settings/regions/_common/hooks/use-countries.tsx
new file mode 100644
index 000000000..34267b893
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/_common/hooks/use-countries.tsx
@@ -0,0 +1,70 @@
+import type { StaticCountry } from "@lib/data/countries"
+import type { RegionCountryDTO } from "@medusajs/types"
+import { json } from "react-router-dom"
+
+const acceptedOrderKeys = ["name", "code"]
+
+/**
+ * Since countries cannot be retrieved from the API, we need to create a hook
+ * that can be used to filter and sort the static list of countries.
+ */
+export const useCountries = ({
+ countries,
+ q,
+ order = "name",
+ limit,
+ offset = 0,
+}: {
+ countries: StaticCountry[]
+ limit: number
+ offset?: number
+ order?: string
+ q?: string
+}) => {
+ const data = countries.slice(offset, offset + limit)
+
+ if (order) {
+ const direction = order.startsWith("-") ? -1 : 1
+ const key = order.replace("-", "")
+
+ if (!acceptedOrderKeys.includes(key)) {
+ console.log("The key ${key} is not a valid order key")
+ throw json(`The key ${key} is not a valid order key`, 500)
+ }
+
+ const sortKey: keyof RegionCountryDTO = key === "code" ? "iso_2" : "name"
+
+ data.sort((a, b) => {
+ if (a[sortKey] === null && b[sortKey] === null) {
+ return 0
+ }
+ if (a[sortKey] === null) {
+ return direction
+ }
+ if (b[sortKey] === null) {
+ return -direction
+ }
+
+ return a[sortKey]! > b[sortKey]! ? direction : -direction
+ })
+ }
+
+ if (q) {
+ const query = q.toLowerCase()
+ const results = countries.filter(
+ (c) =>
+ c.name.toLowerCase().includes(query) ||
+ c.iso_2.toLowerCase().includes(query)
+ )
+
+ return {
+ countries: results,
+ count: results.length,
+ }
+ }
+
+ return {
+ countries: data,
+ count: countries.length,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-columns.tsx b/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-columns.tsx
new file mode 100644
index 000000000..6d1b46b10
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-columns.tsx
@@ -0,0 +1,25 @@
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { StaticCountry } from "@lib/data/countries"
+
+const columnHelper = createColumnHelper<StaticCountry>()
+
+export const useCountryTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("display_name", {
+ header: t("fields.name"),
+ cell: ({ getValue }) => getValue(),
+ }),
+ columnHelper.accessor("iso_2", {
+ header: t("fields.code"),
+ cell: ({ getValue }) => <span className="uppercase">{getValue()}</span>,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-query.tsx b/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-query.tsx
new file mode 100644
index 000000000..fccfe1d14
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/_common/hooks/use-country-table-query.tsx
@@ -0,0 +1,25 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useCountryTableQuery = ({
+ pageSize,
+ prefix,
+}: {
+ pageSize: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(["order", "q", "offset"], prefix)
+
+ const { offset, order, q } = raw
+
+ const searchParams = {
+ limit: pageSize,
+ offset: offset ? parseInt(offset, 10) : 0,
+ order,
+ q,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/regions/_components/region-list-table.tsx b/packages/vendor/src/pages/settings/regions/_components/region-list-table.tsx
new file mode 100644
index 000000000..2b4e24069
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/_components/region-list-table.tsx
@@ -0,0 +1,178 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import type { HttpTypes } from "@medusajs/types"
+import {
+ Button,
+ Container,
+ Heading,
+ Text,
+ toast,
+ usePrompt,
+} from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useDeleteRegion, useRegions } from "@hooks/api/regions"
+import { useRegionTableColumns } from "@hooks/table/columns/use-region-table-columns"
+import { useRegionTableFilters } from "@hooks/table/filters/use-region-table-filters"
+import { useRegionTableQuery } from "@hooks/table/query/use-region-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+
+const PAGE_SIZE = 20
+
+export const RegionListTable = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useRegionTableQuery({ pageSize: PAGE_SIZE })
+ const {
+ regions,
+ count,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useRegions(
+ {
+ ...searchParams,
+ fields: "*payment_providers",
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const filters = useRegionTableFilters()
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: (regions ?? []) as HttpTypes.AdminRegion[],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("regions.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("regions.subtitle")}
+ </Text>
+ </div>
+ <Link to="/settings/regions/create">
+ <Button size="small" variant="secondary">
+ {t("actions.create")}
+ </Button>
+ </Link>
+ </div>
+
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ navigateTo={(row) => `${row.original.id}`}
+ pagination
+ search
+ queryObject={raw}
+ noRecords={{
+ message: t("regions.list.noRecordsMessage"),
+ }}
+ />
+ </Container>
+ )
+}
+
+const RegionActions = ({ region }: { region: HttpTypes.AdminRegion }) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteRegion(region.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("regions.deleteRegionWarning", {
+ name: region.name,
+ }),
+ verificationText: region.name,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("regions.toast.delete"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: `/settings/regions/${region.id}/edit`,
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminRegion>()
+
+const useColumns = () => {
+ const base = useRegionTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => {
+ return <RegionActions region={row.original} />
+ },
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/create/_components/create-region-form.tsx b/packages/vendor/src/pages/settings/regions/create/_components/create-region-form.tsx
new file mode 100644
index 000000000..32294aa37
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/create/_components/create-region-form.tsx
@@ -0,0 +1,507 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { XMarkMini } from "@medusajs/icons"
+import {
+ Button,
+ Checkbox,
+ Heading,
+ Input,
+ Select,
+ Switch,
+ Text,
+ clx,
+ toast,
+} from "@medusajs/ui"
+import { RowSelectionState, createColumnHelper } from "@tanstack/react-table"
+import { useMemo, useState } from "react"
+import { useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { PaymentProviderDTO } from "@medusajs/types"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateRegion } from "@hooks/api/regions"
+import { useDataTable } from "@hooks/use-data-table"
+import { countries as staticCountries, StaticCountry } from "@lib/data/countries"
+import { CurrencyInfo } from "@lib/data/currencies"
+import { formatProvider } from "@lib/format-provider"
+import { useCountries } from "@pages/settings/regions/_common/hooks/use-countries"
+import { useCountryTableColumns } from "@pages/settings/regions/_common/hooks/use-country-table-columns"
+import { useCountryTableQuery } from "@pages/settings/regions/_common/hooks/use-country-table-query"
+
+type CreateRegionFormProps = {
+ currencies: CurrencyInfo[]
+ paymentProviders: PaymentProviderDTO[]
+}
+
+const CreateRegionSchema = zod.object({
+ name: zod.string().min(1),
+ currency_code: zod.string().min(2, "Select a currency"),
+ automatic_taxes: zod.boolean(),
+ is_tax_inclusive: zod.boolean(),
+ countries: zod.array(zod.object({ code: zod.string(), name: zod.string() })),
+ payment_providers: zod.array(zod.string()).min(1),
+})
+
+const PREFIX = "cr"
+const PAGE_SIZE = 50
+
+const STACKED_MODAL_ID = "countries-modal"
+
+export const CreateRegionForm = ({
+ currencies,
+ paymentProviders,
+}: CreateRegionFormProps) => {
+ const { setIsOpen } = useStackedModal()
+ const [rowSelection, setRowSelection] = useState<RowSelectionState>({})
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof CreateRegionSchema>>({
+ defaultValues: {
+ name: "",
+ currency_code: "",
+ automatic_taxes: true,
+ is_tax_inclusive: false,
+ countries: [],
+ payment_providers: [],
+ },
+ resolver: zodResolver(CreateRegionSchema),
+ })
+
+ const selectedCountries = useWatch({
+ control: form.control,
+ name: "countries",
+ defaultValue: [],
+ })
+
+ const { t } = useTranslation()
+
+ const { mutateAsync: createRegion, isPending: isPendingRegion } =
+ useCreateRegion()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await createRegion(
+ {
+ name: values.name,
+ countries: values.countries.map((c) => c.code),
+ currency_code: values.currency_code,
+ payment_providers: values.payment_providers,
+ automatic_taxes: values.automatic_taxes,
+ is_tax_inclusive: values.is_tax_inclusive,
+ },
+ {
+ onSuccess: ({ region }) => {
+ toast.success(t("regions.toast.create"))
+ handleSuccess(`../${region.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ }
+ )
+ })
+
+ const { searchParams, raw } = useCountryTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { countries, count } = useCountries({
+ countries: staticCountries.map((c, i) => ({
+ display_name: c.display_name,
+ name: c.name,
+ id: i,
+ iso_2: c.iso_2,
+ iso_3: c.iso_3,
+ num_code: c.num_code,
+ region_id: null,
+ region: {} as any,
+ })),
+ ...searchParams,
+ })
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: countries || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ rowSelection: {
+ state: rowSelection,
+ updater: setRowSelection,
+ },
+ getRowId: (row) => row.iso_2,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const saveCountries = () => {
+ const selected = Object.keys(rowSelection).filter(
+ (key) => rowSelection[key]
+ )
+
+ form.setValue(
+ "countries",
+ selected.map((key) => ({
+ code: key,
+ name: staticCountries.find((c) => c.iso_2 === key)!.display_name,
+ })),
+ { shouldDirty: true, shouldTouch: true }
+ )
+
+ setIsOpen(STACKED_MODAL_ID, false)
+ }
+
+ const removeCountry = (code: string) => {
+ const update = selectedCountries.filter((c) => c.code !== code)
+ const ids = update
+ .map((c) => c.code)
+ .reduce((acc, c) => {
+ acc[c] = true
+ return acc
+ }, {} as RowSelectionState)
+
+ form.setValue("countries", update, { shouldDirty: true, shouldTouch: true })
+ setRowSelection(ids)
+ }
+
+ const clearCountries = () => {
+ form.setValue("countries", [], { shouldDirty: true, shouldTouch: true })
+ setRowSelection({})
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex h-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPendingRegion}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Header>
+ <RouteFocusModal.Body className="flex overflow-hidden">
+ <div
+ className={clx(
+ "flex h-full w-full flex-col items-center overflow-y-auto p-16"
+ )}
+ id="form-section"
+ >
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div>
+ <Heading>{t("regions.createRegion")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("regions.createRegionHint")}
+ </Text>
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="currency_code"
+ render={({ field: { onChange, ref, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.currency")}</Form.Label>
+ <Form.Control>
+ <Select {...field} onValueChange={onChange}>
+ <Select.Trigger ref={ref}>
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {currencies.map((currency) => (
+ <Select.Item
+ value={currency.code}
+ key={currency.code}
+ >
+ {currency.name}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <Form.Field
+ control={form.control}
+ name="automatic_taxes"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div>
+ <div className="flex items-start justify-between">
+ <Form.Label>{t("fields.automaticTaxes")}</Form.Label>
+ <Form.Control>
+ <Switch
+ {...field}
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ </div>
+ <Form.Hint>{t("regions.automaticTaxesHint")}</Form.Hint>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="is_tax_inclusive"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <div>
+ <div className="flex items-start justify-between">
+ <Form.Label>
+ {t("fields.taxInclusivePricing")}
+ </Form.Label>
+ <Form.Control>
+ <Switch
+ {...field}
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Form.Control>
+ </div>
+ <Form.Hint>{t("regions.taxInclusiveHint")}</Form.Hint>
+ <Form.ErrorMessage />
+ </div>
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="bg-ui-border-base h-px w-full" />
+ <div className="flex flex-col gap-y-4">
+ <div>
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.countries")}
+ </Text>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("regions.countriesHint")}
+ </Text>
+ </div>
+ {selectedCountries.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {selectedCountries.map((country) => (
+ <CountryTag
+ key={country.code}
+ country={country}
+ onRemove={removeCountry}
+ />
+ ))}
+ <Button
+ variant="transparent"
+ size="small"
+ className="text-ui-fg-muted hover:text-ui-fg-subtle"
+ onClick={clearCountries}
+ >
+ {t("actions.clearAll")}
+ </Button>
+ </div>
+ )}
+ <StackedFocusModal id={STACKED_MODAL_ID}>
+ <div className="flex items-center justify-end">
+ <StackedFocusModal.Trigger asChild>
+ <Button variant="secondary" size="small">
+ {t("regions.addCountries")}
+ </Button>
+ </StackedFocusModal.Trigger>
+ </div>
+ <StackedFocusModal.Content>
+ <div className="flex size-full flex-col overflow-hidden">
+ <StackedFocusModal.Header>
+ <StackedFocusModal.Title asChild>
+ <span className="sr-only">
+ {t("regions.addCountries")}
+ </span>
+ </StackedFocusModal.Title>
+ </StackedFocusModal.Header>
+ <StackedFocusModal.Body className="overflow-hidden">
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={count}
+ pageSize={PAGE_SIZE}
+ orderBy={[
+ { key: "display_name", label: t("fields.name") },
+ { key: "iso_2", label: t("fields.code") },
+ ]}
+ pagination
+ search="autofocus"
+ layout="fill"
+ queryObject={raw}
+ prefix={PREFIX}
+ />
+ </StackedFocusModal.Body>
+ <StackedFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <StackedFocusModal.Close asChild>
+ <Button variant="secondary" size="small">
+ {t("actions.cancel")}
+ </Button>
+ </StackedFocusModal.Close>
+ <Button
+ size="small"
+ type="button"
+ onClick={saveCountries}
+ >
+ {t("actions.save")}
+ </Button>
+ </div>
+ </StackedFocusModal.Footer>
+ </div>
+ </StackedFocusModal.Content>
+ </StackedFocusModal>
+ </div>
+ <div className="bg-ui-border-base h-px w-full" />
+ <div className="flex flex-col gap-y-4">
+ <div>
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.providers")}
+ </Text>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("regions.providersHint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="payment_providers"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("fields.paymentProviders")}
+ </Form.Label>
+ <Form.Control>
+ <Combobox
+ options={paymentProviders.map((pp) => ({
+ label: formatProvider(pp.id),
+ value: pp.id,
+ }))}
+ {...field}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<StaticCountry>()
+
+const useColumns = () => {
+ const base = useCountryTableColumns()
+
+ return useMemo(
+ () => [
+ columnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ const isPreselected = !row.getCanSelect()
+
+ return (
+ <Checkbox
+ checked={row.getIsSelected() || isPreselected}
+ disabled={isPreselected}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const CountryTag = ({
+ country,
+ onRemove,
+}: {
+ country: { code: string; name: string }
+ onRemove: (code: string) => void
+}) => {
+ return (
+ <div className="bg-ui-bg-field shadow-borders-base transition-fg hover:bg-ui-bg-field-hover flex h-7 items-center overflow-hidden rounded-md">
+ <div className="txt-compact-small-plus flex h-full select-none items-center justify-center px-2 py-0.5">
+ {country.name}
+ </div>
+ <button
+ type="button"
+ onClick={() => onRemove(country.code)}
+ className="focus-visible:bg-ui-bg-field-hover transition-fg hover:bg-ui-bg-field-hover flex h-full w-7 items-center justify-center border-l outline-none"
+ >
+ <XMarkMini className="text-ui-fg-muted" />
+ </button>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/regions/create/index.tsx b/packages/vendor/src/pages/settings/regions/create/index.tsx
new file mode 100644
index 000000000..ea8173f81
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/create/index.tsx
@@ -0,0 +1,33 @@
+import { RouteFocusModal } from "@components/modals/route-focus-modal"
+import { usePaymentProviders } from "@hooks/api/payments"
+import { useStore } from "@hooks/api/store"
+import { currencies } from "@lib/data/currencies"
+import { CreateRegionForm } from "./_components/create-region-form"
+
+const RegionCreate = () => {
+ const { store, isPending: isLoading, isError, error } = useStore()
+
+ const storeCurrencies = (store?.supported_currencies ?? []).map(
+ (c) => currencies[c.currency_code.toUpperCase()]
+ )
+ const { payment_providers: paymentProviders = [] } = usePaymentProviders({
+ is_enabled: true,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {!isLoading && store && (
+ <CreateRegionForm
+ currencies={storeCurrencies}
+ paymentProviders={paymentProviders}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = RegionCreate
diff --git a/packages/vendor/src/pages/settings/regions/index.tsx b/packages/vendor/src/pages/settings/regions/index.tsx
new file mode 100644
index 000000000..e21b14cc1
--- /dev/null
+++ b/packages/vendor/src/pages/settings/regions/index.tsx
@@ -0,0 +1,20 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { RegionListTable } from "./_components/region-list-table"
+
+const RegionList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("region.list.before"),
+ after: getWidgets("region.list.after"),
+ }}
+ >
+ <RegionListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = RegionList
diff --git a/packages/vendor/src/pages/settings/return-reasons/[id]/edit/_components/return-reason-edit-form.tsx b/packages/vendor/src/pages/settings/return-reasons/[id]/edit/_components/return-reason-edit-form.tsx
new file mode 100644
index 000000000..c5f0a9081
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/[id]/edit/_components/return-reason-edit-form.tsx
@@ -0,0 +1,141 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, Textarea, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateReturnReason } from "@hooks/api/return-reasons"
+
+type ReturnReasonEditFormProps = {
+ returnReason: HttpTypes.AdminReturnReason
+}
+
+const ReturnReasonEditSchema = z.object({
+ value: z.string().min(1),
+ label: z.string().min(1),
+ description: z.string().optional(),
+})
+
+export const ReturnReasonEditForm = ({
+ returnReason,
+}: ReturnReasonEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof ReturnReasonEditSchema>>({
+ defaultValues: {
+ value: returnReason.value,
+ label: returnReason.label,
+ description: returnReason.description ?? undefined,
+ },
+ resolver: zodResolver(ReturnReasonEditSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateReturnReason(returnReason.id)
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: ({ return_reason }) => {
+ toast.success(
+ t("returnReasons.edit.successToast", {
+ label: return_reason.label,
+ })
+ )
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ className="flex size-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-4 overflow-auto">
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label tooltip={t("returnReasons.fields.value.tooltip")}>
+ {t("returnReasons.fields.value.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t("returnReasons.fields.value.placeholder")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="label"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("returnReasons.fields.label.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t("returnReasons.fields.label.placeholder")}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("returnReasons.fields.description.label")}
+ </Form.Label>
+ <Form.Control>
+ <Textarea
+ {...field}
+ placeholder={t(
+ "returnReasons.fields.description.placeholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/return-reasons/[id]/edit/index.tsx b/packages/vendor/src/pages/settings/return-reasons/[id]/edit/index.tsx
new file mode 100644
index 000000000..43578d789
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/[id]/edit/index.tsx
@@ -0,0 +1,35 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useReturnReason } from "@hooks/api/return-reasons"
+import { ReturnReasonEditForm } from "./_components/return-reason-edit-form"
+
+const ReturnReasonEdit = () => {
+ const { id } = useParams()
+ const { t } = useTranslation()
+
+ const { return_reason, isPending, isError, error } = useReturnReason(id!)
+
+ const ready = !isPending && !!return_reason
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("returnReasons.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("returnReasons.edit.subtitle")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {ready && <ReturnReasonEditForm returnReason={return_reason} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = ReturnReasonEdit
diff --git a/packages/vendor/src/pages/settings/return-reasons/_common/hooks/use-delete-return-reason-action.tsx b/packages/vendor/src/pages/settings/return-reasons/_common/hooks/use-delete-return-reason-action.tsx
new file mode 100644
index 000000000..94740800c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/_common/hooks/use-delete-return-reason-action.tsx
@@ -0,0 +1,41 @@
+import { AdminReturnReason } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { useDeleteReturnReason } from "@hooks/api/return-reasons"
+
+export const useDeleteReturnReasonAction = ({
+ id,
+ label,
+}: AdminReturnReason) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteReturnReason(id)
+
+ const handleDelete = async () => {
+ const result = await prompt({
+ title: t("general.areYouSure"),
+ description: t("returnReasons.delete.confirmation", {
+ label,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!result) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("returnReasons.delete.successToast", { label }))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
diff --git a/packages/vendor/src/pages/settings/return-reasons/_components/return-reason-list-table.tsx b/packages/vendor/src/pages/settings/return-reasons/_components/return-reason-list-table.tsx
new file mode 100644
index 000000000..cb04d8dcf
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/_components/return-reason-list-table.tsx
@@ -0,0 +1,128 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { _DataTable } from "@components/table/data-table"
+import { useReturnReasons } from "@hooks/api/return-reasons"
+import { useReturnReasonTableColumns } from "@hooks/table/columns"
+import { useReturnReasonTableQuery } from "@hooks/table/query"
+import { useDataTable } from "@hooks/use-data-table"
+import { useDeleteReturnReasonAction } from "@pages/settings/return-reasons/_common/hooks/use-delete-return-reason-action"
+
+const PAGE_SIZE = 20
+
+export const ReturnReasonListTable = () => {
+ const { t } = useTranslation()
+ const { searchParams, raw } = useReturnReasonTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { return_reasons, count, isPending, isError, error } = useReturnReasons(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: return_reasons,
+ columns,
+ count,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y px-0 py-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("returnReasons.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("returnReasons.subtitle")}
+ </Text>
+ </div>
+ <Button variant="secondary" size="small" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+ <_DataTable
+ table={table}
+ queryObject={raw}
+ count={count}
+ isLoading={isPending}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ noHeader={true}
+ pagination
+ search
+ />
+ </Container>
+ )
+}
+
+type ReturnReasonRowActionsProps = {
+ returnReason: HttpTypes.AdminReturnReason
+}
+
+const ReturnReasonRowActions = ({
+ returnReason,
+}: ReturnReasonRowActionsProps) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeleteReturnReasonAction(returnReason)
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: `${returnReason.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminReturnReason>()
+
+const useColumns = () => {
+ const base = useReturnReasonTableColumns()
+
+ return useMemo(
+ () => [
+ ...base,
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => (
+ <ReturnReasonRowActions returnReason={row.original} />
+ ),
+ }),
+ ],
+ [base]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/return-reasons/create/_components/return-reason-create-form.tsx b/packages/vendor/src/pages/settings/return-reasons/create/_components/return-reason-create-form.tsx
new file mode 100644
index 000000000..3ca4ccd60
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/create/_components/return-reason-create-form.tsx
@@ -0,0 +1,157 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, Textarea, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateReturnReason } from "@hooks/api/return-reasons"
+
+const ReturnReasonCreateSchema = z.object({
+ value: z.string().min(1),
+ label: z.string().min(1),
+ description: z.string().optional(),
+})
+
+export const ReturnReasonCreateForm = () => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof ReturnReasonCreateSchema>>({
+ defaultValues: {
+ value: "",
+ label: "",
+ description: "",
+ },
+ resolver: zodResolver(ReturnReasonCreateSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateReturnReason()
+
+ const handleSubmit = form.handleSubmit(async (data) => {
+ await mutateAsync(data, {
+ onSuccess: ({ return_reason }) => {
+ toast.success(
+ t("returnReasons.create.successToast", {
+ label: return_reason.label,
+ })
+ )
+ handleSuccess(`../`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ className="flex size-full flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 justify-center overflow-auto px-6 py-16">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8">
+ <div className="flex flex-col gap-y-1">
+ <RouteFocusModal.Title asChild>
+ <Heading>{t("returnReasons.create.header")}</Heading>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("returnReasons.create.subtitle")}
+ </Text>
+ </RouteFocusModal.Description>
+ </div>
+ <div className="grid gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="value"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={t("returnReasons.fields.value.tooltip")}
+ >
+ {t("returnReasons.fields.value.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t(
+ "returnReasons.fields.value.placeholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="label"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("returnReasons.fields.label.label")}
+ </Form.Label>
+ <Form.Control>
+ <Input
+ {...field}
+ placeholder={t(
+ "returnReasons.fields.label.placeholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label optional>
+ {t("returnReasons.fields.description.label")}
+ </Form.Label>
+ <Form.Control>
+ <Textarea
+ {...field}
+ placeholder={t(
+ "returnReasons.fields.description.placeholder"
+ )}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/return-reasons/create/index.tsx b/packages/vendor/src/pages/settings/return-reasons/create/index.tsx
new file mode 100644
index 000000000..8b5304315
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/create/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { ReturnReasonCreateForm } from "./_components/return-reason-create-form"
+
+const ReturnReasonCreate = () => {
+ return (
+ <RouteFocusModal>
+ <ReturnReasonCreateForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = ReturnReasonCreate
diff --git a/packages/vendor/src/pages/settings/return-reasons/index.tsx b/packages/vendor/src/pages/settings/return-reasons/index.tsx
new file mode 100644
index 000000000..f73f7395c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/return-reasons/index.tsx
@@ -0,0 +1,23 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ReturnReasonListTable } from "./_components/return-reason-list-table"
+
+const ReturnReasonList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ showMetadata={false}
+ showJSON={false}
+ hasOutlet
+ widgets={{
+ after: getWidgets("return_reason.list.after"),
+ before: getWidgets("return_reason.list.before"),
+ }}
+ >
+ <ReturnReasonListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ReturnReasonList
diff --git a/packages/vendor/src/pages/settings/seller/_components/index.ts b/packages/vendor/src/pages/settings/seller/_components/index.ts
new file mode 100644
index 000000000..832f16b14
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/_components/index.ts
@@ -0,0 +1 @@
+export { SellerGeneralSection } from "./seller-general-section"
diff --git a/packages/vendor/src/pages/settings/seller/_components/seller-general-section.tsx b/packages/vendor/src/pages/settings/seller/_components/seller-general-section.tsx
new file mode 100644
index 000000000..0fb375fbf
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/_components/seller-general-section.tsx
@@ -0,0 +1,120 @@
+import { PencilSquare } from "@medusajs/icons"
+import { AdminStore } from "@medusajs/types"
+import { Badge, Container, Heading, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useRegion } from "@hooks/api/regions"
+import { useStockLocation } from "@hooks/api"
+
+type SellerGeneralSectionProps = {
+ seller: AdminStore
+}
+
+export const SellerGeneralSection = ({ seller }: SellerGeneralSectionProps) => {
+ const { t } = useTranslation()
+
+ const { region } = useRegion(seller.default_region_id!, undefined, {
+ enabled: !!seller.default_region_id,
+ })
+
+ const defaultCurrency = seller.supported_currencies?.find((c) => c.is_default)
+
+ const { stock_location } = useStockLocation(
+ seller.default_location_id!,
+ {
+ fields: "id,name",
+ },
+ {
+ enabled: !!seller.default_location_id,
+ }
+ )
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("seller.domain", "Seller")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("seller.manageDetails", "Manage your seller details")}
+ </Text>
+ </div>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <PencilSquare />,
+ label: t("actions.edit"),
+ to: "edit",
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.name")}
+ </Text>
+ <Text size="small" leading="compact">
+ {seller.name}
+ </Text>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("seller.defaultCurrency", "Default Currency")}
+ </Text>
+ {defaultCurrency ? (
+ <div className="flex items-center gap-x-2">
+ <Badge size="2xsmall">
+ {defaultCurrency.currency_code?.toUpperCase()}
+ </Badge>
+ <Text size="small" leading="compact">
+ {defaultCurrency.currency?.name}
+ </Text>
+ </div>
+ ) : (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )}
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("seller.defaultRegion", "Default Region")}
+ </Text>
+ <div className="flex items-center gap-x-2">
+ {region ? (
+ <Badge size="2xsmall" asChild>
+ <Link to={`/settings/regions/${region.id}`}>{region.name}</Link>
+ </Badge>
+ ) : (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )}
+ </div>
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("seller.defaultLocation", "Default Location")}
+ </Text>
+ <div className="flex items-center gap-x-2">
+ {stock_location ? (
+ <Badge size="2xsmall" asChild>
+ <Link to={`/settings/locations/${stock_location.id}`}>
+ {stock_location.name}
+ </Link>
+ </Badge>
+ ) : (
+ <Text size="small" leading="compact">
+ -
+ </Text>
+ )}
+ </div>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/seller/edit/_components/edit-seller-form.tsx b/packages/vendor/src/pages/settings/seller/edit/_components/edit-seller-form.tsx
new file mode 100644
index 000000000..a66dd81d0
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/edit/_components/edit-seller-form.tsx
@@ -0,0 +1,148 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { Combobox } from "@components/inputs/combobox"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateStore } from "@hooks/api/store"
+import { useComboboxData } from "@hooks/use-combobox-data"
+import { sdk } from "@lib/client"
+
+type EditSellerFormProps = {
+ seller: HttpTypes.AdminStore
+}
+
+const EditSellerSchema = z.object({
+ name: z.string().min(1),
+ default_region_id: z.string().optional(),
+ default_location_id: z.string().optional(),
+})
+
+export const EditSellerForm = ({ seller }: EditSellerFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof EditSellerSchema>>({
+ defaultValues: {
+ name: seller.name,
+ default_region_id: seller.default_region_id || undefined,
+ default_location_id: seller.default_location_id || undefined,
+ },
+ resolver: zodResolver(EditSellerSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateStore(seller.id)
+
+ const regionsCombobox = useComboboxData({
+ queryKey: ["regions", "default_region_id"],
+ queryFn: (params) =>
+ sdk.admin.region.list({ ...params, fields: "id,name" }),
+ defaultValue: seller.default_region_id || undefined,
+ getOptions: (data) =>
+ data.regions.map((r) => ({ label: r.name, value: r.id })),
+ })
+
+ const locationsCombobox = useComboboxData({
+ queryFn: (params) =>
+ sdk.admin.stockLocation.list({ ...params, fields: "id,name" }),
+ getOptions: (data) =>
+ data.stock_locations.map((l) => ({ label: l.name, value: l.id })),
+ queryKey: ["stock_locations", "default_location_id"],
+ defaultValue: seller.default_location_id || undefined,
+ })
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(values, {
+ onSuccess: () => {
+ toast.success(t("seller.toast.update", "Seller updated successfully"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col overflow-hidden">
+ <RouteDrawer.Body className="overflow-y-auto">
+ <div className="flex flex-col gap-y-8">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input placeholder="Company Name" {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="default_region_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("seller.defaultRegion", "Default Region")}</Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={regionsCombobox.options}
+ searchValue={regionsCombobox.searchValue}
+ onSearchValueChange={regionsCombobox.onSearchValueChange}
+ disabled={regionsCombobox.disabled}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="default_location_id"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("seller.defaultLocation", "Default Location")}</Form.Label>
+ <Form.Control>
+ <Combobox
+ {...field}
+ options={locationsCombobox.options}
+ searchValue={locationsCombobox.searchValue}
+ onSearchValueChange={locationsCombobox.onSearchValueChange}
+ disabled={locationsCombobox.disabled}
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" isLoading={isPending} type="submit">
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/seller/edit/_components/index.ts b/packages/vendor/src/pages/settings/seller/edit/_components/index.ts
new file mode 100644
index 000000000..e4713f9a2
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/edit/_components/index.ts
@@ -0,0 +1 @@
+export { EditSellerForm } from "./edit-seller-form"
diff --git a/packages/vendor/src/pages/settings/seller/edit/index.tsx b/packages/vendor/src/pages/settings/seller/edit/index.tsx
new file mode 100644
index 000000000..a0d7ef1c9
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/edit/index.tsx
@@ -0,0 +1,28 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { RouteDrawer } from "@components/modals"
+import { useStore } from "@hooks/api/store"
+import { EditSellerForm } from "./_components/edit-seller-form"
+
+const SellerEdit = () => {
+ const { t } = useTranslation()
+ const { store, isPending: isLoading, isError, error } = useStore()
+
+ if (isError) {
+ throw error
+ }
+
+ const ready = !!store && !isLoading
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("seller.edit.header", "Edit Seller")}</Heading>
+ </RouteDrawer.Header>
+ {ready && <EditSellerForm seller={store} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = SellerEdit
diff --git a/packages/vendor/src/pages/settings/seller/index.tsx b/packages/vendor/src/pages/settings/seller/index.tsx
new file mode 100644
index 000000000..989b7eaca
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/index.tsx
@@ -0,0 +1,45 @@
+import { useLoaderData } from "react-router-dom"
+
+import { useStore } from "@hooks/api/store"
+import { SellerGeneralSection } from "./_components/seller-general-section"
+import { sellerLoader } from "./loader"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+
+const SellerDetail = () => {
+ const initialData = useLoaderData() as Awaited<ReturnType<typeof sellerLoader>>
+
+ const { store, isPending, isError, error } = useStore(undefined, {
+ initialData,
+ })
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isPending || !store) {
+ return <SingleColumnPageSkeleton sections={1} showJSON showMetadata />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("seller.details.before"),
+ after: getWidgets("seller.details.after"),
+ }}
+ data={store}
+ hasOutlet
+ showMetadata
+ showJSON
+ >
+ <SellerGeneralSection seller={store} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = SellerDetail
+export { sellerLoader as loader } from "./loader"
diff --git a/packages/vendor/src/pages/settings/seller/loader.ts b/packages/vendor/src/pages/settings/seller/loader.ts
new file mode 100644
index 000000000..4b16b2a45
--- /dev/null
+++ b/packages/vendor/src/pages/settings/seller/loader.ts
@@ -0,0 +1,18 @@
+import { HttpTypes } from "@medusajs/types"
+
+import { retrieveActiveStore, storeQueryKeys } from "@hooks/api/store"
+import { queryClient } from "@lib/query-client"
+
+const sellerDetailQuery = () => ({
+ queryKey: storeQueryKeys.details(),
+ queryFn: async () => retrieveActiveStore(),
+})
+
+export const sellerLoader = async () => {
+ const query = sellerDetailQuery()
+
+ return (
+ queryClient.getQueryData<HttpTypes.AdminStoreResponse>(query.queryKey) ??
+ (await queryClient.fetchQuery(query))
+ )
+}
diff --git a/packages/vendor/src/pages/settings/settings.tsx b/packages/vendor/src/pages/settings/settings.tsx
new file mode 100644
index 000000000..1b908565c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/settings.tsx
@@ -0,0 +1,15 @@
+import { useEffect } from "react"
+import { Outlet, useLocation, useNavigate } from "react-router-dom"
+
+export const Settings = () => {
+ const navigate = useNavigate()
+ const location = useLocation()
+
+ useEffect(() => {
+ if (location.pathname === "/settings") {
+ navigate("/settings/seller", { replace: true })
+ }
+ }, [location.pathname, navigate])
+
+ return <Outlet />
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/[id]/_components/shipping-profile-general-section.tsx b/packages/vendor/src/pages/settings/shipping-profiles/[id]/_components/shipping-profile-general-section.tsx
new file mode 100644
index 000000000..41fb95948
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/[id]/_components/shipping-profile-general-section.tsx
@@ -0,0 +1,76 @@
+import { Trash } from "@medusajs/icons"
+import { AdminShippingProfileResponse } from "@medusajs/types"
+import { Container, Heading, toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { SectionRow } from "@components/common/section"
+import { useDeleteShippingProfile } from "@hooks/api/shipping-profiles"
+
+type ShippingProfileGeneralSectionProps = {
+ profile: AdminShippingProfileResponse["shipping_profile"]
+}
+
+export const ShippingProfileGeneralSection = ({
+ profile,
+}: ShippingProfileGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+ const navigate = useNavigate()
+
+ const { mutateAsync } = useDeleteShippingProfile(profile.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("shippingProfile.delete.title"),
+ description: t("shippingProfile.delete.description", {
+ name: profile.name,
+ }),
+ verificationText: profile.name,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("shippingProfile.delete.successToast", {
+ name: profile.name,
+ })
+ )
+
+ navigate("/settings/locations/shipping-profiles", { replace: true })
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{profile.name}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <SectionRow title={t("fields.type")} value={profile.type} />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/shipping-profiles/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..b98baa25e
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/[id]/breadcrumb.tsx
@@ -0,0 +1,27 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { useShippingProfile } from "@hooks/api/shipping-profiles"
+
+type ShippingProfileDetailBreadcrumbProps =
+ UIMatch<HttpTypes.AdminShippingProfileResponse>
+
+export const ShippingProfileDetailBreadcrumb = (
+ props: ShippingProfileDetailBreadcrumbProps
+) => {
+ const { shipping_profile_id } = props.params || {}
+
+ const { shipping_profile } = useShippingProfile(
+ shipping_profile_id!,
+ undefined,
+ {
+ initialData: props.data,
+ enabled: Boolean(shipping_profile_id),
+ }
+ )
+
+ if (!shipping_profile) {
+ return null
+ }
+
+ return <span>{shipping_profile.name}</span>
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/[id]/index.tsx b/packages/vendor/src/pages/settings/shipping-profiles/[id]/index.tsx
new file mode 100644
index 000000000..d713aa791
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/[id]/index.tsx
@@ -0,0 +1,51 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { useShippingProfile } from "@hooks/api/shipping-profiles"
+import { ShippingProfileGeneralSection } from "./_components/shipping-profile-general-section"
+
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { shippingProfileLoader } from "./loader"
+
+const ShippingProfileDetail = () => {
+ const { shipping_profile_id } = useParams()
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof shippingProfileLoader>
+ >
+
+ const { shipping_profile, isLoading, isError, error } = useShippingProfile(
+ shipping_profile_id!,
+ undefined,
+ {
+ initialData,
+ }
+ )
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !shipping_profile) {
+ return <SingleColumnPageSkeleton sections={1} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("shipping_profile.details.before"),
+ after: getWidgets("shipping_profile.details.after"),
+ }}
+ data={shipping_profile}
+ >
+ <ShippingProfileGeneralSection profile={shipping_profile} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ShippingProfileDetail
+export { shippingProfileLoader as loader } from "./loader"
+export { ShippingProfileDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/[id]/loader.ts b/packages/vendor/src/pages/settings/shipping-profiles/[id]/loader.ts
new file mode 100644
index 000000000..9c901f3df
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/[id]/loader.ts
@@ -0,0 +1,20 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { shippingProfileQueryKeys } from "@hooks/api/shipping-profiles"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const shippingProfileQuery = (id: string) => ({
+ queryKey: shippingProfileQueryKeys.detail(id),
+ queryFn: async () =>
+ fetchQuery(`/vendor/shipping-profiles/${id}`, {
+ method: "GET",
+ }),
+})
+
+export const shippingProfileLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.shipping_profile_id
+ const query = shippingProfileQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/[id]/metadata/index.tsx b/packages/vendor/src/pages/settings/shipping-profiles/[id]/metadata/index.tsx
new file mode 100644
index 000000000..e3ab90c21
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/[id]/metadata/index.tsx
@@ -0,0 +1,33 @@
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form/metadata-form"
+import {
+ useShippingProfile,
+ useUpdateShippingProfile,
+} from "@hooks/api"
+
+const ShippingProfileMetadata = () => {
+ const { shipping_profile_id } = useParams()
+
+ const { shipping_profile, isPending, isError, error } = useShippingProfile(
+ shipping_profile_id!
+ )
+
+ const { mutateAsync, isPending: isMutating } = useUpdateShippingProfile(
+ shipping_profile?.id!
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <MetadataForm
+ metadata={shipping_profile?.metadata}
+ hook={mutateAsync}
+ isPending={isPending}
+ isMutating={isMutating}
+ />
+ )
+}
+
+export const Component = ShippingProfileMetadata
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-options-row-actions.tsx b/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-options-row-actions.tsx
new file mode 100644
index 000000000..e003c823d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-options-row-actions.tsx
@@ -0,0 +1,64 @@
+import { Trash } from "@medusajs/icons"
+import { AdminShippingProfileResponse } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteShippingProfile } from "@hooks/api/shipping-profiles"
+
+export const ShippingOptionsRowActions = ({
+ profile,
+}: {
+ profile: AdminShippingProfileResponse["shipping_profile"]
+}) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteShippingProfile(profile.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("shippingProfile.delete.title"),
+ description: t("shippingProfile.delete.description", {
+ name: profile.name,
+ }),
+ verificationText: profile.name,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("shippingProfile.delete.successToast", {
+ name: profile.name,
+ })
+ )
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-profile-list-table.tsx b/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-profile-list-table.tsx
new file mode 100644
index 000000000..b17f58b0c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/_components/shipping-profile-list-table.tsx
@@ -0,0 +1,84 @@
+import { Button, Container, Heading, Text } from "@medusajs/ui"
+import { Link } from "react-router-dom"
+
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+import { _DataTable } from "@components/table/data-table"
+import { useShippingProfiles } from "@hooks/api"
+import { useDataTable } from "@hooks/use-data-table"
+import { useShippingProfileTableColumns } from "./use-shipping-profile-table-columns"
+import { useShippingProfileTableFilters } from "./use-shipping-profile-table-filters"
+import { useShippingProfileTableQuery } from "./use-shipping-profile-table-query"
+
+const PAGE_SIZE = 20
+
+export const ShippingProfileListTable = () => {
+ const { t } = useTranslation()
+
+ const { raw, searchParams } = useShippingProfileTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+
+ const { shipping_profiles, count, isLoading, isError, error } =
+ useShippingProfiles(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const columns = useShippingProfileTableColumns()
+ const filters = useShippingProfileTableFilters()
+
+ const { table } = useDataTable({
+ data: shipping_profiles ?? [],
+ columns,
+ count,
+ enablePagination: true,
+ getRowId: (row, index) => row?.id ?? `row-${index}`,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <div>
+ <Heading>{t("shippingProfile.domain")}</Heading>
+ <Text className="text-ui-fg-subtle" size="small">
+ {t("shippingProfile.subtitle")}
+ </Text>
+ </div>
+ <div>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="create">{t("actions.create")}</Link>
+ </Button>
+ </div>
+ </div>
+ <_DataTable
+ table={table}
+ pageSize={PAGE_SIZE}
+ count={count}
+ columns={columns}
+ filters={filters}
+ orderBy={[
+ { key: "name", label: t("fields.name") },
+ { key: "type", label: t("fields.type") },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ isLoading={isLoading}
+ navigateTo={(row) => row.id}
+ queryObject={raw}
+ search
+ pagination
+ />
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-columns.tsx b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-columns.tsx
new file mode 100644
index 000000000..caeeab161
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-columns.tsx
@@ -0,0 +1,31 @@
+import { AdminShippingProfileResponse } from "@medusajs/types"
+import { createColumnHelper } from "@tanstack/react-table"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+
+import { ShippingOptionsRowActions } from "./shipping-options-row-actions"
+
+const columnHelper =
+ createColumnHelper<AdminShippingProfileResponse["shipping_profile"]>()
+
+export const useShippingProfileTableColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("name", {
+ header: t("fields.name"),
+ cell: (cell) => cell.getValue(),
+ }),
+ columnHelper.accessor("type", {
+ header: t("fields.type"),
+ cell: (cell) => cell.getValue(),
+ }),
+ columnHelper.display({
+ id: "actions",
+ cell: ({ row }) => <ShippingOptionsRowActions profile={row.original} />,
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-filters.tsx b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-filters.tsx
new file mode 100644
index 000000000..ab5c85f1a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-filters.tsx
@@ -0,0 +1,33 @@
+import { useTranslation } from "react-i18next"
+import { Filter } from "@components/table/data-table"
+
+export const useShippingProfileTableFilters = () => {
+ const { t } = useTranslation()
+
+ let filters: Filter[] = []
+
+ filters.push({
+ key: "name",
+ label: t("fields.name"),
+ type: "string",
+ })
+
+ filters.push({
+ key: "type",
+ label: t("fields.type"),
+ type: "string",
+ })
+
+ const dateFilters: Filter[] = [
+ { label: t("fields.createdAt"), key: "created_at" },
+ { label: t("fields.updatedAt"), key: "updated_at" },
+ ].map((f) => ({
+ key: f.key,
+ label: f.label,
+ type: "date",
+ }))
+
+ filters = [...filters, ...dateFilters]
+
+ return filters
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-query.tsx b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-query.tsx
new file mode 100644
index 000000000..b21aac62f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/_components/use-shipping-profile-table-query.tsx
@@ -0,0 +1,30 @@
+import { useQueryParams } from "@hooks/use-query-params"
+
+export const useShippingProfileTableQuery = ({
+ pageSize = 20,
+ prefix,
+}: {
+ pageSize?: number
+ prefix?: string
+}) => {
+ const raw = useQueryParams(
+ ["offset", "q", "order", "created_at", "updated_at", "name", "type"],
+ prefix
+ )
+
+ const searchParams = {
+ limit: pageSize,
+ offset: raw.offset ? parseInt(raw.offset) : 0,
+ q: raw.q,
+ order: raw.order,
+ created_at: raw.created_at ? JSON.parse(raw.created_at) : undefined,
+ updated_at: raw.updated_at ? JSON.parse(raw.updated_at) : undefined,
+ name: raw.name,
+ type: raw.type,
+ }
+
+ return {
+ searchParams,
+ raw,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/create/_components/create-shipping-profile-form.tsx b/packages/vendor/src/pages/settings/shipping-profiles/create/_components/create-shipping-profile-form.tsx
new file mode 100644
index 000000000..eab283e51
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/create/_components/create-shipping-profile-form.tsx
@@ -0,0 +1,129 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateShippingProfile } from "@hooks/api/shipping-profiles"
+
+const CreateShippingOptionsSchema = zod.object({
+ name: zod.string().min(1),
+ type: zod.string().min(1),
+})
+
+export function CreateShippingProfileForm() {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof CreateShippingOptionsSchema>>({
+ defaultValues: {
+ name: "",
+ type: "",
+ },
+ resolver: zodResolver(CreateShippingOptionsSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateShippingProfile()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ name: values.name,
+ type: values.type,
+ },
+ {
+ onSuccess: ({ shipping_profile }) => {
+ toast.success(
+ t("shippingProfile.create.successToast", {
+ name: shipping_profile.name,
+ })
+ )
+
+ handleSuccess(
+ `/settings/locations/shipping-profiles/${shipping_profile.id}`
+ )
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading className="capitalize">
+ {t("shippingProfile.create.header")}
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("shippingProfile.create.hint")}
+ </Text>
+ </div>
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label tooltip={t("shippingProfile.tooltip.type")}>
+ {t("fields.type")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button type="submit" size="small" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/create/index.tsx b/packages/vendor/src/pages/settings/shipping-profiles/create/index.tsx
new file mode 100644
index 000000000..20411956d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/create/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { CreateShippingProfileForm } from "./_components/create-shipping-profile-form"
+
+function ShippingProfileCreate() {
+ return (
+ <RouteFocusModal>
+ <CreateShippingProfileForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = ShippingProfileCreate
diff --git a/packages/vendor/src/pages/settings/shipping-profiles/index.tsx b/packages/vendor/src/pages/settings/shipping-profiles/index.tsx
new file mode 100644
index 000000000..804fbbb17
--- /dev/null
+++ b/packages/vendor/src/pages/settings/shipping-profiles/index.tsx
@@ -0,0 +1,20 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { ShippingProfileListTable } from "./_components/shipping-profile-list-table"
+
+const ShippingProfileList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("shipping_profile.list.before"),
+ after: getWidgets("shipping_profile.list.after"),
+ }}
+ >
+ <ShippingProfileListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = ShippingProfileList
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-detail-section.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-detail-section.tsx
new file mode 100644
index 000000000..3757ee60d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-detail-section.tsx
@@ -0,0 +1,41 @@
+import { HttpTypes } from "@medusajs/types"
+import { Badge, Container, Tooltip } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { TaxRateLine } from "@pages/settings/tax-regions/_common/components/tax-rate-line"
+import { TaxRegionCard } from "@pages/settings/tax-regions/_common/components/tax-region-card"
+
+type TaxRegionDetailSectionProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+export const TaxRegionDetailSection = ({
+ taxRegion,
+}: TaxRegionDetailSectionProps) => {
+ const { t } = useTranslation()
+
+ const defaultRates = taxRegion.tax_rates.filter((r) => r.is_default === true)
+ const showBage = defaultRates.length === 0
+
+ return (
+ <Container className="divide-y p-0">
+ <TaxRegionCard
+ taxRegion={taxRegion}
+ type="header"
+ asLink={false}
+ badge={
+ showBage && (
+ <Tooltip content={t("taxRegions.fields.noDefaultRate.tooltip")}>
+ <Badge color="orange" size="2xsmall" className="cursor-default">
+ {t("taxRegions.fields.noDefaultRate.label")}
+ </Badge>
+ </Tooltip>
+ )
+ }
+ />
+ {defaultRates.map((rate) => {
+ return <TaxRateLine key={rate.id} taxRate={rate} />
+ })}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-override-section.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-override-section.tsx
new file mode 100644
index 000000000..61d1844a8
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-override-section.tsx
@@ -0,0 +1,66 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+
+import { useTaxRates } from "@hooks/api/tax-rates"
+import { useTaxRateTableQuery } from "@hooks/table/query/use-tax-rate-table-query"
+import { TaxOverrideTable } from "@pages/settings/tax-regions/_common/components/tax-override-table"
+import { useTaxOverrideTable } from "@pages/settings/tax-regions/_common/hooks/use-tax-override-table"
+
+type TaxRegionOverrideSectionProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+const PAGE_SIZE = 10
+const PREFIX = "o"
+
+export const TaxRegionOverrideSection = ({
+ taxRegion,
+}: TaxRegionOverrideSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useTaxRateTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { tax_rates, count, isPending, isError, error } = useTaxRates(
+ {
+ ...searchParams,
+ tax_region_id: taxRegion.id,
+ is_default: false,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const { table } = useTaxOverrideTable({
+ count,
+ data: tax_rates,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="p-0">
+ <TaxOverrideTable
+ isPending={isPending}
+ table={table}
+ count={count}
+ action={{
+ label: t("actions.create"),
+ to: "overrides/create",
+ }}
+ queryObject={raw}
+ prefix={PREFIX}
+ >
+ <Heading level="h2">{t("taxRegions.taxOverrides.header")}</Heading>
+ </TaxOverrideTable>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-province-section.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-province-section.tsx
new file mode 100644
index 000000000..ff2c8098b
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-province-section.tsx
@@ -0,0 +1,72 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+import { useTaxRegions } from "@hooks/api/tax-regions"
+import { useTaxRegionTableQuery } from "@hooks/table/query/use-tax-region-table-query"
+import { getCountryProvinceObjectByIso2 } from "@lib/data/country-states"
+import { TaxRegionTable } from "@pages/settings/tax-regions/_common/components/tax-region-table"
+import { useTaxRegionTable } from "@pages/settings/tax-regions/_common/hooks/use-tax-region-table"
+
+const PAGE_SIZE = 10
+const PREFIX = "p"
+
+type TaxRateListProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+ showSublevelRegions: boolean
+}
+
+export const TaxRegionProvinceSection = ({
+ taxRegion,
+ showSublevelRegions,
+}: TaxRateListProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useTaxRegionTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { tax_regions, count, isPending, isError, error } = useTaxRegions(
+ {
+ ...searchParams,
+ parent_id: taxRegion.id,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const { table } = useTaxRegionTable({
+ count,
+ data: tax_regions,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const provinceObject = getCountryProvinceObjectByIso2(taxRegion.country_code!)
+
+ if (!provinceObject && !showSublevelRegions && !taxRegion.children.length) {
+ return null
+ }
+
+ const type = provinceObject?.type || "sublevel"
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <TaxRegionTable
+ variant="province"
+ action={{ to: `provinces/create`, label: t("actions.create") }}
+ table={table}
+ isPending={isPending}
+ queryObject={raw}
+ count={count}
+ >
+ <Heading level="h2">{t(`taxRegions.${type}.header`)}</Heading>
+ </TaxRegionTable>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-sublevel-alert.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-sublevel-alert.tsx
new file mode 100644
index 000000000..4ed727221
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/_components/tax-region-sublevel-alert.tsx
@@ -0,0 +1,62 @@
+import { HttpTypes } from "@medusajs/types"
+import { Alert, Button, Text } from "@medusajs/ui"
+import { useState } from "react"
+import { useTranslation } from "react-i18next"
+import { getCountryProvinceObjectByIso2 } from "@lib/data/country-states"
+
+type TaxRegionSublevelAlertProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+ showSublevelRegions: boolean
+ setShowSublevelRegions: (state: boolean) => void
+}
+
+export const TaxRegionSublevelAlert = ({
+ taxRegion,
+ showSublevelRegions,
+ setShowSublevelRegions,
+}: TaxRegionSublevelAlertProps) => {
+ const { t } = useTranslation()
+
+ const [dismissed, setDismissed] = useState(false)
+ const provinceObject = getCountryProvinceObjectByIso2(taxRegion.country_code!)
+
+ if (
+ provinceObject ||
+ showSublevelRegions ||
+ dismissed ||
+ taxRegion.children.length
+ ) {
+ return null
+ }
+
+ return (
+ <Alert dismissible variant="info" className="bg-ui-bg-base">
+ <div className="flex flex-col gap-y-3">
+ <div className="flex flex-col">
+ <Text size="small" leading="compact" weight="plus" asChild>
+ <h2>{t("taxRegions.fields.sublevels.alert.header")}</h2>
+ </Text>
+ <Text size="small" leading="compact" className="text-pretty">
+ {t("taxRegions.fields.sublevels.alert.description")}
+ </Text>
+ </div>
+ <div className="flex items-center gap-x-3">
+ <Button
+ variant="secondary"
+ size="small"
+ onClick={() => setShowSublevelRegions(true)}
+ >
+ {t("taxRegions.fields.sublevels.alert.action")}
+ </Button>
+ <Button
+ variant="transparent"
+ size="small"
+ onClick={() => setDismissed(true)}
+ >
+ {t("actions.hide")}
+ </Button>
+ </div>
+ </div>
+ </Alert>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..be3d919c0
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/breadcrumb.tsx
@@ -0,0 +1,29 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+
+import { useTaxRegion } from "@hooks/api"
+import { getCountryByIso2 } from "@lib/data/countries"
+
+type TaxRegionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminTaxRegionResponse>
+
+export const TaxRegionDetailBreadcrumb = (
+ props: TaxRegionDetailBreadcrumbProps
+) => {
+ const { id } = props.params || {}
+
+ const { tax_region } = useTaxRegion(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!tax_region) {
+ return null
+ }
+
+ return (
+ <span>
+ {getCountryByIso2(tax_region.country_code)?.display_name ||
+ tax_region.country_code?.toUpperCase()}
+ </span>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/index.tsx
new file mode 100644
index 000000000..da19cacd5
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/index.tsx
@@ -0,0 +1,65 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { SingleColumnPage } from "@components/layout/pages"
+import { useTaxRegion } from "@hooks/api/tax-regions"
+import { TaxRegionDetailSection } from "./_components/tax-region-detail-section"
+import { TaxRegionProvinceSection } from "./_components/tax-region-province-section"
+
+import { useState } from "react"
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { useDashboardExtension } from "@/extensions"
+import { TaxRegionOverrideSection } from "./_components/tax-region-override-section"
+import { TaxRegionSublevelAlert } from "./_components/tax-region-sublevel-alert"
+import { taxRegionLoader } from "./loader"
+
+const TaxRegionDetail = () => {
+ const { id } = useParams()
+ const [showSublevelRegions, setShowSublevelRegions] = useState(false)
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof taxRegionLoader>
+ >
+
+ const {
+ tax_region: taxRegion,
+ isLoading,
+ isError,
+ error,
+ } = useTaxRegion(id!, undefined, { initialData })
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !taxRegion) {
+ return <SingleColumnPageSkeleton sections={4} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ data={taxRegion}
+ widgets={{
+ after: getWidgets("tax.details.after"),
+ before: getWidgets("tax.details.before"),
+ }}
+ >
+ <TaxRegionSublevelAlert
+ taxRegion={taxRegion}
+ showSublevelRegions={showSublevelRegions}
+ setShowSublevelRegions={setShowSublevelRegions}
+ />
+ <TaxRegionDetailSection taxRegion={taxRegion} />
+ <TaxRegionProvinceSection
+ taxRegion={taxRegion}
+ showSublevelRegions={showSublevelRegions}
+ />
+ <TaxRegionOverrideSection taxRegion={taxRegion} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = TaxRegionDetail
+export { taxRegionLoader as loader } from "./loader"
+export { TaxRegionDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/loader.ts b/packages/vendor/src/pages/settings/tax-regions/[id]/loader.ts
new file mode 100644
index 000000000..b4425ad0b
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/loader.ts
@@ -0,0 +1,16 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+import { taxRegionsQueryKeys } from "@hooks/api/tax-regions"
+import { sdk } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const taxRegionDetailQuery = (id: string) => ({
+ queryKey: taxRegionsQueryKeys.detail(id),
+ queryFn: async () => sdk.admin.taxRegion.retrieve(id),
+})
+
+export const taxRegionLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = taxRegionDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-detail-section.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-detail-section.tsx
new file mode 100644
index 000000000..9688bea4f
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-detail-section.tsx
@@ -0,0 +1,41 @@
+import { HttpTypes } from "@medusajs/types"
+import { Badge, Container, Tooltip } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { TaxRateLine } from "@pages/settings/tax-regions/_common/components/tax-rate-line"
+import { TaxRegionCard } from "@pages/settings/tax-regions/_common/components/tax-region-card"
+
+type TaxRegionProvinceDetailSectionProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+export const TaxRegionProvinceDetailSection = ({
+ taxRegion,
+}: TaxRegionProvinceDetailSectionProps) => {
+ const { t } = useTranslation()
+
+ const defaultRates = taxRegion.tax_rates.filter((r) => r.is_default === true)
+ const showBage = defaultRates.length === 0
+
+ return (
+ <Container className="divide-y p-0">
+ <TaxRegionCard
+ taxRegion={taxRegion}
+ type="header"
+ asLink={false}
+ badge={
+ showBage && (
+ <Tooltip content={t("taxRegions.fields.noDefaultRate.tooltip")}>
+ <Badge color="orange" size="2xsmall" className="cursor-default">
+ {t("taxRegions.fields.noDefaultRate.label")}
+ </Badge>
+ </Tooltip>
+ )
+ }
+ />
+ {defaultRates.map((rate) => {
+ return <TaxRateLine key={rate.id} taxRate={rate} isSublevelTaxRate />
+ })}
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-province-override-section.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-province-override-section.tsx
new file mode 100644
index 000000000..d4d97f0ba
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/_components/tax-region-province-override-section.tsx
@@ -0,0 +1,65 @@
+import { HttpTypes } from "@medusajs/types"
+import { Container, Heading } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+import { useTaxRates } from "@hooks/api/tax-rates"
+import { useTaxRateTableQuery } from "@hooks/table/query/use-tax-rate-table-query"
+import { TaxOverrideTable } from "@pages/settings/tax-regions/_common/components/tax-override-table"
+import { useTaxOverrideTable } from "@pages/settings/tax-regions/_common/hooks/use-tax-override-table"
+
+type TaxRegionProvinceOverrideSectionProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+const PAGE_SIZE = 10
+const PREFIX = "o"
+
+export const TaxRegionProvinceOverrideSection = ({
+ taxRegion,
+}: TaxRegionProvinceOverrideSectionProps) => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useTaxRateTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+ const { tax_rates, count, isPending, isError, error } = useTaxRates(
+ {
+ ...searchParams,
+ tax_region_id: taxRegion.id,
+ is_default: false,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const { table } = useTaxOverrideTable({
+ count,
+ data: tax_rates,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="p-0">
+ <TaxOverrideTable
+ isPending={isPending}
+ table={table}
+ count={count}
+ action={{
+ label: t("actions.create"),
+ to: "overrides/create",
+ }}
+ queryObject={raw}
+ prefix={PREFIX}
+ >
+ <Heading level="h2">{t("taxRegions.taxOverrides.header")}</Heading>
+ </TaxOverrideTable>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/breadcrumb.tsx
new file mode 100644
index 000000000..52145410d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/breadcrumb.tsx
@@ -0,0 +1,32 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+
+import { useTaxRegion } from "@hooks/api"
+import {
+ getProvinceByIso2,
+ isProvinceInCountry,
+} from "@lib/data/country-states"
+
+type TaxRegionDetailBreadcrumbProps = UIMatch<HttpTypes.AdminTaxRegionResponse>
+
+export const TaxRegionDetailBreadcrumb = (
+ props: TaxRegionDetailBreadcrumbProps
+) => {
+ const { province_id } = props.params || {}
+
+ const { tax_region } = useTaxRegion(province_id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(province_id),
+ })
+
+ if (!tax_region) {
+ return null
+ }
+
+ const countryCode = tax_region.country_code?.toUpperCase()
+ const provinceCode = tax_region.province_code?.toUpperCase()
+
+ const isValid = isProvinceInCountry(countryCode, provinceCode)
+
+ return <span>{isValid ? getProvinceByIso2(provinceCode) : provinceCode}</span>
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/index.tsx
new file mode 100644
index 000000000..e05db7ac2
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/index.tsx
@@ -0,0 +1,54 @@
+import { useLoaderData, useParams } from "react-router-dom"
+
+import { SingleColumnPage } from "@components/layout/pages"
+import { useTaxRegion } from "@hooks/api/tax-regions"
+import { TaxRegionProvinceDetailSection } from "./_components/tax-region-detail-section"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { useDashboardExtension } from "@/extensions"
+import { TaxRegionProvinceOverrideSection } from "./_components/tax-region-province-override-section"
+import { taxRegionLoader } from "./loader"
+
+const TaxRegionProvinceDetail = () => {
+ const { province_id } = useParams()
+
+ const initialData = useLoaderData() as Awaited<
+ ReturnType<typeof taxRegionLoader>
+ >
+
+ const {
+ tax_region: taxRegion,
+ isLoading,
+ isError,
+ error,
+ } = useTaxRegion(province_id!, undefined, {
+ initialData,
+ })
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !taxRegion) {
+ return <SingleColumnPageSkeleton sections={2} />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ data={taxRegion}
+ widgets={{
+ after: getWidgets("tax.details.after"),
+ before: getWidgets("tax.details.before"),
+ }}
+ >
+ <TaxRegionProvinceDetailSection taxRegion={taxRegion} />
+ <TaxRegionProvinceOverrideSection taxRegion={taxRegion} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = TaxRegionProvinceDetail
+export { taxRegionLoader as loader } from "./loader"
+export { TaxRegionDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/loader.ts b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/loader.ts
new file mode 100644
index 000000000..466ab6e3c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/[province_id]/loader.ts
@@ -0,0 +1,16 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+import { taxRegionsQueryKeys } from "@hooks/api/tax-regions"
+import { sdk } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const taxRegionDetailQuery = (id: string) => ({
+ queryKey: taxRegionsQueryKeys.detail(id),
+ queryFn: async () => sdk.admin.taxRegion.retrieve(id),
+})
+
+export const taxRegionLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.province_id
+ const query = taxRegionDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/_components/tax-region-province-create-form.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/_components/tax-region-province-create-form.tsx
new file mode 100644
index 000000000..e81d0e0c5
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/_components/tax-region-province-create-form.tsx
@@ -0,0 +1,248 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { InformationCircleSolid } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Heading, Input, Text, Tooltip, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import { ProvinceSelect } from "@components/inputs/province-select"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateTaxRegion } from "@hooks/api/tax-regions"
+import { getCountryProvinceObjectByIso2 } from "@lib/data/country-states"
+
+type TaxRegionProvinceCreateFormProps = {
+ parent: HttpTypes.AdminTaxRegion
+}
+
+const CreateTaxRegionProvinceSchema = z.object({
+ province_code: z.string().min(1),
+ name: z.string().optional(),
+ code: z.string().min(1),
+ rate: z
+ .object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ })
+ .optional(),
+ is_combinable: z.boolean().optional(),
+})
+
+export const TaxRegionProvinceCreateForm = ({
+ parent,
+}: TaxRegionProvinceCreateFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof CreateTaxRegionProvinceSchema>>({
+ defaultValues: {
+ province_code: "",
+ code: "",
+ is_combinable: false,
+ name: "",
+ rate: {
+ value: "",
+ },
+ },
+ resolver: zodResolver(CreateTaxRegionProvinceSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateTaxRegion()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const defaultRate =
+ values.name && values.rate?.float
+ ? {
+ name: values.name,
+ rate: values.rate.float,
+ code: values.code,
+ is_combinable: values.is_combinable,
+ }
+ : undefined
+
+ await mutateAsync(
+ {
+ country_code: parent.country_code!,
+ province_code: values.province_code,
+ parent_id: parent.id,
+ default_tax_rate: defaultRate,
+ },
+ {
+ onSuccess: ({ tax_region }) => {
+ toast.success(t("taxRegions.create.successToast"))
+ handleSuccess(
+ `/settings/tax-regions/${parent.id}/provinces/${tax_region.id}`
+ )
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const countryProvinceObject = getCountryProvinceObjectByIso2(
+ parent.country_code!
+ )
+
+ const type = countryProvinceObject?.type || "sublevel"
+ const label = t(`taxRegions.fields.sublevels.labels.${type}`)
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading>{t(`taxRegions.${type}.create.header`)}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t(`taxRegions.${type}.create.hint`)}
+ </Text>
+ </div>
+ <div className="grid gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="province_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label
+ tooltip={
+ !countryProvinceObject &&
+ t("taxRegions.fields.sublevels.tooltips.sublevel")
+ }
+ >
+ {label}
+ </Form.Label>
+ <Form.Control>
+ {countryProvinceObject ? (
+ <ProvinceSelect
+ country_code={parent.country_code!}
+ {...field}
+ />
+ ) : (
+ <Input {...field} placeholder="KR-26" />
+ )}
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center gap-x-1">
+ <Heading level="h2" className="!txt-compact-small-plus">
+ {t("taxRegions.fields.defaultTaxRate.label")}
+ </Heading>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-muted"
+ >
+ ({t("fields.optional")})
+ </Text>
+ <Tooltip
+ content={t("taxRegions.fields.defaultTaxRate.tooltip")}
+ >
+ <InformationCircleSolid className="text-ui-fg-muted" />
+ </Tooltip>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxRate")}
+ </Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/index.tsx
new file mode 100644
index 000000000..625f808eb
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/provinces/create/index.tsx
@@ -0,0 +1,24 @@
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useTaxRegion } from "@hooks/api/tax-regions"
+import { TaxRegionProvinceCreateForm } from "./_components/tax-region-province-create-form"
+
+const TaxProvinceCreate = () => {
+ const { id } = useParams()
+
+ const { tax_region, isPending, isError, error } = useTaxRegion(id!)
+
+ const ready = !isPending && !!tax_region
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && <TaxRegionProvinceCreateForm parent={tax_region} />}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = TaxProvinceCreate
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/_components/tax-region-tax-override-edit-form.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/_components/tax-region-tax-override-edit-form.tsx
new file mode 100644
index 000000000..4d044e238
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/_components/tax-region-tax-override-edit-form.tsx
@@ -0,0 +1,610 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { MagnifyingGlass } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Button,
+ Divider,
+ Heading,
+ Hint,
+ Input,
+ Label,
+ Select,
+ Text,
+ clx,
+ toast,
+} from "@medusajs/ui"
+import { useFieldArray, useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import {
+ RouteDrawer,
+ StackedDrawer,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateTaxRate } from "@hooks/api/tax-rates"
+import { TargetForm } from "@pages/settings/tax-regions/_common/components/target-form"
+import { TargetItem } from "@pages/settings/tax-regions/_common/components/target-item"
+import { TaxRateRuleReferenceType } from "@pages/settings/tax-regions/_common/constants"
+import {
+ TaxRateRuleReference,
+ TaxRateRuleReferenceSchema,
+} from "@pages/settings/tax-regions/_common/schemas"
+import { createTaxRulePayload } from "@pages/settings/tax-regions/_common/utils"
+import { InitialRuleValues } from "../../types"
+
+type TaxRegionTaxOverrideEditFormProps = {
+ taxRate: HttpTypes.AdminTaxRate
+ initialValues: InitialRuleValues
+ isCombinable?: boolean
+}
+const STACKED_MODAL_ID = "tr"
+const getStackedModalId = (type: TaxRateRuleReferenceType) =>
+ `${STACKED_MODAL_ID}-${type}`
+
+const TaxRegionTaxRateEditSchema = z.object({
+ name: z.string().min(1),
+ code: z.string().min(1),
+ rate: z.object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ }),
+ is_combinable: z.boolean().optional(),
+ enabled_rules: z.object({
+ product: z.boolean(),
+ product_type: z.boolean(),
+ // product_collection: z.boolean(),
+ // product_tag: z.boolean(),
+ // customer_group: z.boolean(),
+ }),
+ product: z.array(TaxRateRuleReferenceSchema).optional(),
+ product_type: z.array(TaxRateRuleReferenceSchema).optional(),
+ // product_collection: z.array(TaxRateRuleReferenceSchema).optional(),
+ // product_tag: z.array(TaxRateRuleReferenceSchema).optional(),
+ // customer_group: z.array(TaxRateRuleReferenceSchema).optional(),
+})
+
+export const TaxRegionTaxOverrideEditForm = ({
+ taxRate,
+ isCombinable = false,
+ initialValues,
+}: TaxRegionTaxOverrideEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { setIsOpen } = useStackedModal()
+
+ const form = useForm<z.infer<typeof TaxRegionTaxRateEditSchema>>({
+ defaultValues: {
+ name: taxRate.name,
+ code: taxRate.code,
+ rate: {
+ value: taxRate.rate?.toString() || "",
+ },
+ is_combinable: taxRate.is_combinable,
+ enabled_rules: {
+ product: initialValues.product.length > 0,
+ product_type: initialValues.product_type.length > 0,
+ // customer_groups: initialValues.customer_group.length > 0,
+ // product_collections:
+ // initialValues.product_collections.length > 0,
+ // product_tags: initialValues.product_tag.length > 0,
+ },
+ product: initialValues.product,
+ product_type: initialValues.product_type,
+ // product_collections: initialValues.product_collection,
+ // product_tags: initialValues.product_tag,
+ // customer_groups: initialValues.customer_group,
+ },
+ resolver: zodResolver(TaxRegionTaxRateEditSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateTaxRate(taxRate.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const {
+ product,
+ product_type,
+ // customer_groups,
+ // product_collections,
+ // product_tags,
+ } = values
+
+ const productRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT,
+ references: product || [],
+ })
+ const productTypeRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ references: product_type || [],
+ })
+ // const customerGroupRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // references: customer_groups || [],
+ // })
+ // const productCollectionRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // references: product_collections || [],
+ // })
+ // const productTagRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.PRODUCT_TAG,
+ // references: product_tags || [],
+ // })
+
+ const rules = [
+ productRules,
+ productTypeRules,
+ // customerGroupRules,
+ // productCollectionRules,
+ // productTagRules,
+ ]
+ .filter((rule) => Boolean(rule))
+ .flatMap((r) => r) as HttpTypes.AdminCreateTaxRate["rules"]
+
+ await mutateAsync(
+ {
+ name: values.name,
+ code: values.code,
+ rate: values.rate?.float,
+ is_combinable: values.is_combinable,
+ rules,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("taxRegions.taxRates.edit.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const products = useFieldArray({
+ control: form.control,
+ name: "product",
+ })
+
+ const productTypes = useFieldArray({
+ control: form.control,
+ name: "product_type",
+ })
+
+ // const productCollections = useFieldArray({
+ // control: form.control,
+ // name: "product_collection",
+ // })
+ //
+ // const productTags = useFieldArray({
+ // control: form.control,
+ // name: "product_tag",
+ // })
+ //
+ //
+ // const customerGroups = useFieldArray({
+ // control: form.control,
+ // name: "customer_group",
+ // })
+
+ const getControls = (type: TaxRateRuleReferenceType) => {
+ switch (type) {
+ case TaxRateRuleReferenceType.PRODUCT:
+ return products
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ return productTypes
+ // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
+ // return productCollections
+ // case TaxRateRuleReferenceType.PRODUCT_TAG:
+ // return productTags
+ // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
+ // return customerGroups
+ default:
+ return products
+ }
+ }
+
+ const referenceTypeOptions = [
+ {
+ value: TaxRateRuleReferenceType.PRODUCT,
+ label: t("taxRegions.fields.targets.options.product"),
+ },
+ {
+ value: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ label: t("taxRegions.fields.targets.options.productType"),
+ },
+ // {
+ // value: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // label: t("taxRegions.fields.targets.options.productCollection"),
+ // },
+ // {
+ // value: TaxRateRuleReferenceType.PRODUCT_TAG,
+ // label: t("taxRegions.fields.targets.options.productTag"),
+ // },
+ // {
+ // value: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // label: t("taxRegions.fields.targets.options.customerGroup"),
+ // },
+ ]
+
+ const searchPlaceholders: Record<TaxRateRuleReferenceType, string> = {
+ [TaxRateRuleReferenceType.PRODUCT]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_TYPE]: t(
+ "taxRegions.fields.targets.placeholders.productType"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_COLLECTION]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_TAG]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.CUSTOMER_GROUP]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ }
+
+ const getFieldHandler = (type: TaxRateRuleReferenceType) => {
+ const controls = getControls(type)
+ const { fields, remove, append } = controls
+ const modalId = getStackedModalId(type)
+
+ return (references: TaxRateRuleReference[]) => {
+ if (!references.length) {
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+ setIsOpen(modalId, false)
+ return
+ }
+
+ const newIds = references.map((reference) => reference.value)
+
+ const fieldsToAdd = references.filter(
+ (reference) => !fields.some((field) => field.value === reference.value)
+ )
+
+ for (const field of fields) {
+ if (!newIds.includes(field.value)) {
+ remove(fields.indexOf(field))
+ }
+ }
+
+ append(fieldsToAdd)
+ setIsOpen(modalId, false)
+ }
+ }
+
+ const displayOrder = new Set<TaxRateRuleReferenceType>([
+ TaxRateRuleReferenceType.PRODUCT,
+ ])
+
+ const disableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+ form.setValue(`enabled_rules.${type}` as "enabled_rules.product" | "enabled_rules.product_type", false, {
+ shouldDirty: true,
+ })
+
+ displayOrder.delete(type)
+ }
+
+ const enableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(`enabled_rules.${type}` as "enabled_rules.product" | "enabled_rules.product_type", true, {
+ shouldDirty: true,
+ })
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+
+ displayOrder.add(type)
+ }
+
+ const watchedEnabledRules = useWatch({
+ control: form.control,
+ name: "enabled_rules",
+ })
+
+ const addRule = () => {
+ const firstDisabledRule = Object.keys(watchedEnabledRules).find(
+ (key) => !watchedEnabledRules[key as keyof typeof watchedEnabledRules]
+ )
+
+ if (firstDisabledRule) {
+ enableRule(firstDisabledRule as TaxRateRuleReferenceType)
+ }
+ }
+
+ const visibleRuleTypes = referenceTypeOptions
+ .filter((option) => watchedEnabledRules[option.value as keyof typeof watchedEnabledRules])
+ .sort((a, b) => {
+ const orderArray = Array.from(displayOrder)
+ return orderArray.indexOf(a.value) - orderArray.indexOf(b.value)
+ })
+
+ const getAvailableRuleTypes = (type: TaxRateRuleReferenceType) => {
+ return referenceTypeOptions.filter((option) => {
+ return (
+ !visibleRuleTypes.some(
+ (visibleOption) => visibleOption.value === option.value
+ ) || option.value === type
+ )
+ })
+ }
+
+ const showAddButton = Object.values(watchedEnabledRules).some(
+ (value) => !value
+ )
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ className="flex flex-1 flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-auto">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("taxRegions.fields.taxCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("taxRegions.fields.taxRate")}</Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {isCombinable && (
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ )}
+ <div className="flex flex-col gap-y-3">
+ <div className="flex items-center justify-between gap-x-4">
+ <div className="flex flex-col">
+ <div className="flex items-center gap-x-1">
+ <Label id="tax_region_rules_label" htmlFor="tax_region_rules">
+ {t("taxRegions.fields.targets.label")}
+ </Label>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-muted"
+ >
+ ({t("fields.optional")})
+ </Text>
+ </div>
+ <Hint id="tax_region_rules_description" className="text-pretty">
+ {t("taxRegions.fields.targets.hint")}
+ </Hint>
+ </div>
+ {showAddButton && (
+ <Button
+ onClick={addRule}
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover flex-shrink-0"
+ >
+ {t("taxRegions.fields.targets.action")}
+ </Button>
+ )}
+ </div>
+ <div
+ id="tax_region_rules"
+ aria-labelledby="tax_region_rules_label"
+ aria-describedby="tax_region_rules_description"
+ role="application"
+ className="flex flex-col gap-y-3"
+ >
+ {visibleRuleTypes.map((ruleType, index) => {
+ const type = ruleType.value
+ const label = ruleType.label
+ const isLast = index === visibleRuleTypes.length - 1
+ const searchPlaceholder = searchPlaceholders[type]
+
+ const options = getAvailableRuleTypes(type)
+ const modalId = getStackedModalId(type)
+
+ const { fields, remove } = getControls(type)
+ const handler = getFieldHandler(type)
+
+ const handleChangeType = (value: TaxRateRuleReferenceType) => {
+ disableRule(type)
+ enableRule(value)
+ }
+
+ return (
+ <div key={type}>
+ <Form.Field
+ control={form.control}
+ name={ruleType.value as "product" | "product_type"}
+ render={({
+ field: { value: _value, onChange: _onChange, ...field },
+ }) => {
+ return (
+ <Form.Item className="space-y-0">
+ <Form.Label className="sr-only">{label}</Form.Label>
+ <div
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
+ "aria-[invalid='true']:shadow-borders-error"
+ )}
+ role="application"
+ {...field}
+ >
+ <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">
+ {isLast ? (
+ <Select
+ value={type}
+ onValueChange={handleChangeType}
+ >
+ <Select.Trigger className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {options.map((option) => {
+ return (
+ <Select.Item
+ key={option.value}
+ value={option.value}
+ >
+ {option.label}
+ </Select.Item>
+ )
+ })}
+ </Select.Content>
+ </Select>
+ ) : (
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {label}
+ </div>
+ )}
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t("taxRegions.fields.targets.operators.in")}
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-1.5">
+ <StackedDrawer id={modalId}>
+ <StackedDrawer.Trigger asChild>
+ <button
+ type="button"
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"
+ >
+ <MagnifyingGlass />
+ {searchPlaceholder}
+ </button>
+ </StackedDrawer.Trigger>
+ <StackedDrawer.Trigger asChild>
+ <Button variant="secondary">
+ {t("actions.browse")}
+ </Button>
+ </StackedDrawer.Trigger>
+ <StackedDrawer.Content>
+ <StackedDrawer.Header>
+ <StackedDrawer.Title asChild>
+ <Heading>
+ {t(
+ "taxRegions.fields.targets.modal.header"
+ )}
+ </Heading>
+ </StackedDrawer.Title>
+ <StackedDrawer.Description className="sr-only">
+ {t("taxRegions.fields.targets.hint")}
+ </StackedDrawer.Description>
+ </StackedDrawer.Header>
+ <TargetForm
+ type="drawer"
+ referenceType={type}
+ state={fields}
+ setState={handler}
+ />
+ </StackedDrawer.Content>
+ </StackedDrawer>
+ <Button
+ variant="secondary"
+ onClick={() => disableRule(type)}
+ type="button"
+ >
+ {t("actions.delete")}
+ </Button>
+ </div>
+ {fields.length > 0 ? (
+ <div className="flex flex-col gap-y-1.5">
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-1.5 px-1.5">
+ {fields.map((field, index) => {
+ return (
+ <TargetItem
+ key={field.id}
+ index={index}
+ label={field.label}
+ onRemove={remove}
+ />
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ <Form.ErrorMessage className="mt-2" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer className="shrink-0">
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/index.tsx
new file mode 100644
index 000000000..307b6a56b
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/[tax_rate_id]/edit/index.tsx
@@ -0,0 +1,169 @@
+import { HttpTypes } from "@medusajs/types"
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+
+import { RouteDrawer } from "@components/modals"
+import { useCollections } from "@hooks/api/collections"
+import { useCustomerGroups } from "@hooks/api/customer-groups"
+import { useProductTypes } from "@hooks/api/product-types"
+import { useProducts } from "@hooks/api/products"
+import { useProductTags } from "@hooks/api/tags"
+import { useTaxRate } from "@hooks/api/tax-rates"
+import { TaxRateRuleReferenceType } from "@pages/settings/tax-regions/_common/constants"
+import { TaxRegionTaxOverrideEditForm } from "./_components/tax-region-tax-override-edit-form"
+import { InitialRuleValues } from "./types"
+
+const TaxRegionTaxOverrideEdit = () => {
+ const { t } = useTranslation()
+ const { tax_rate_id } = useParams()
+
+ const { tax_rate, isPending, isError, error } = useTaxRate(tax_rate_id!)
+
+ const { initialValues, isPending: isInitializing } =
+ useDefaultRulesValues(tax_rate)
+
+ const ready = !isPending && !!tax_rate && !isInitializing && !!initialValues
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("taxRegions.taxOverrides.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("taxRegions.taxOverrides.edit.hint")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {ready && (
+ <TaxRegionTaxOverrideEditForm
+ taxRate={tax_rate}
+ isCombinable={true}
+ initialValues={initialValues}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
+
+const useDefaultRulesValues = (
+ taxRate?: HttpTypes.AdminTaxRate
+): { initialValues?: InitialRuleValues; isPending: boolean } => {
+ const rules = taxRate?.rules || []
+
+ const idsByReferenceType: {
+ [key in TaxRateRuleReferenceType]: string[]
+ } = {
+ [TaxRateRuleReferenceType.PRODUCT]: [],
+ [TaxRateRuleReferenceType.PRODUCT_COLLECTION]: [],
+ [TaxRateRuleReferenceType.PRODUCT_TAG]: [],
+ [TaxRateRuleReferenceType.PRODUCT_TYPE]: [],
+ [TaxRateRuleReferenceType.CUSTOMER_GROUP]: [],
+ }
+
+ rules.forEach((rule) => {
+ const reference = rule.reference as TaxRateRuleReferenceType
+ idsByReferenceType[reference]?.push(rule.reference_id)
+ })
+
+ const queries = [
+ {
+ ids: idsByReferenceType[TaxRateRuleReferenceType.PRODUCT],
+ hook: useProducts,
+ key: TaxRateRuleReferenceType.PRODUCT,
+ getResult: (result: HttpTypes.AdminProductListResponse) =>
+ result.products.map((product) => ({
+ label: product.title,
+ value: product.id,
+ })),
+ },
+ {
+ ids: idsByReferenceType[TaxRateRuleReferenceType.PRODUCT_COLLECTION],
+ hook: useCollections,
+ key: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ getResult: (result: HttpTypes.AdminCollectionListResponse) =>
+ result.collections.map((collection) => ({
+ label: collection.title!,
+ value: collection.id!,
+ })),
+ },
+ {
+ ids: idsByReferenceType[TaxRateRuleReferenceType.PRODUCT_TAG],
+ hook: useProductTags,
+ key: TaxRateRuleReferenceType.PRODUCT_TAG,
+ getResult: (result: any) =>
+ result.tags.map((tag: any) => ({
+ label: tag.value,
+ value: tag.id,
+ })),
+ },
+ {
+ ids: idsByReferenceType[TaxRateRuleReferenceType.PRODUCT_TYPE],
+ hook: useProductTypes,
+ key: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ getResult: (result: HttpTypes.AdminProductTypeListResponse) =>
+ result.product_types.map((productType) => ({
+ label: productType.value,
+ value: productType.id,
+ })),
+ },
+ {
+ ids: idsByReferenceType[TaxRateRuleReferenceType.CUSTOMER_GROUP],
+ hook: useCustomerGroups,
+ key: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ getResult: (
+ result: HttpTypes.PaginatedResponse<{
+ customer_groups: HttpTypes.AdminCustomerGroup[]
+ }>
+ ) =>
+ result.customer_groups.map((customerGroup) => ({
+ label: customerGroup.name!,
+ value: customerGroup.id,
+ })),
+ },
+ ]
+
+ const queryResults = queries.map(({ ids, hook }) => {
+ const enabled = ids.length > 0
+ return {
+ result: hook({ id: ids, limit: ids.length }, { enabled }),
+ enabled,
+ }
+ })
+
+ if (!taxRate) {
+ return { isPending: true }
+ }
+
+ const isPending = queryResults.some(
+ ({ result, enabled }) => enabled && result.isPending
+ )
+
+ if (isPending) {
+ return { isPending }
+ }
+
+ queryResults.forEach(({ result, enabled }) => {
+ if (enabled && result.isError) {
+ throw result.error
+ }
+ })
+
+ const initialRulesValues: InitialRuleValues = queries.reduce(
+ (acc, { key, getResult }, index) => ({
+ ...acc,
+ [key]: queryResults[index].enabled
+ ? getResult(queryResults[index].result)
+ : [],
+ }),
+ {} as InitialRuleValues
+ )
+
+ return { initialValues: initialRulesValues, isPending: false }
+}
+
+export const Component = TaxRegionTaxOverrideEdit
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-override-create-form.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-override-create-form.tsx
new file mode 100644
index 000000000..f17838ce1
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-override-create-form.tsx
@@ -0,0 +1,599 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import {
+ Button,
+ clx,
+ Divider,
+ Heading,
+ Hint,
+ Input,
+ Label,
+ Select,
+ Text,
+ toast,
+} from "@medusajs/ui"
+import { useFieldArray, useForm, useWatch } from "react-hook-form"
+import { z } from "zod"
+
+import { MagnifyingGlass } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateTaxRate } from "@hooks/api/tax-rates"
+import { TargetForm } from "@pages/settings/tax-regions/_common/components/target-form"
+import { TargetItem } from "@pages/settings/tax-regions/_common/components/target-item"
+import { TaxRateRuleReferenceType } from "@pages/settings/tax-regions/_common/constants"
+import {
+ TaxRateRuleReference,
+ TaxRateRuleReferenceSchema,
+} from "@pages/settings/tax-regions/_common/schemas"
+import { createTaxRulePayload } from "@pages/settings/tax-regions/_common/utils"
+import { useDocumentDirection } from "@hooks/use-document-direction"
+
+const TaxRegionCreateTaxOverrideSchema = z.object({
+ name: z.string().min(1),
+ code: z.string().min(1),
+ rate: z
+ .object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ })
+ .optional(),
+ is_combinable: z.boolean().optional(),
+ enabled_rules: z.object({
+ product: z.boolean(),
+ product_type: z.boolean(),
+ shipping_option: z.boolean(),
+ }),
+ product: z.array(TaxRateRuleReferenceSchema).optional(),
+ product_type: z.array(TaxRateRuleReferenceSchema).optional(),
+ shipping_option: z.array(TaxRateRuleReferenceSchema).optional(),
+})
+
+type TaxRegionCreateTaxOverrideFormProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+const STACKED_MODAL_ID = "tr"
+const getStackedModalId = (type: TaxRateRuleReferenceType) =>
+ `${STACKED_MODAL_ID}-${type}`
+
+export const TaxRegionCreateTaxOverrideForm = ({
+ taxRegion,
+}: TaxRegionCreateTaxOverrideFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { setIsOpen } = useStackedModal()
+ const direction = useDocumentDirection()
+ const form = useForm<z.infer<typeof TaxRegionCreateTaxOverrideSchema>>({
+ defaultValues: {
+ name: "",
+ code: "",
+ is_combinable: false,
+ rate: {
+ value: "",
+ },
+ enabled_rules: {
+ product: true,
+ product_type: false,
+ shipping_option: false,
+ },
+ product: [],
+ product_type: [],
+ shipping_option: [],
+ },
+ resolver: zodResolver(TaxRegionCreateTaxOverrideSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateTaxRate()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const {
+ product,
+ product_type,
+ shipping_option,
+ } = values
+
+ const productRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT,
+ references: product || [],
+ })
+ const productTypeRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ references: product_type || [],
+ })
+ const shippingOptionRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.SHIPPING_OPTION,
+ references: shipping_option || [],
+ })
+
+ const rules = [
+ productRules,
+ productTypeRules,
+ shippingOptionRules,
+ ]
+ .filter((rule) => Boolean(rule))
+ .flatMap((r) => r) as HttpTypes.AdminCreateTaxRate["rules"]
+
+ mutateAsync(
+ {
+ name: values.name,
+ tax_region_id: taxRegion.id,
+ rate: values.rate?.float,
+ code: values.code,
+ is_combinable: values.is_combinable,
+ rules: rules,
+ is_default: false,
+ },
+ {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const products = useFieldArray({
+ control: form.control,
+ name: TaxRateRuleReferenceType.PRODUCT,
+ })
+
+ const productTypes = useFieldArray({
+ control: form.control,
+ name: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ })
+
+ const shippingOptions = useFieldArray({
+ control: form.control,
+ name: TaxRateRuleReferenceType.SHIPPING_OPTION,
+ })
+
+ const getControls = (type: TaxRateRuleReferenceType) => {
+ switch (type) {
+ case TaxRateRuleReferenceType.PRODUCT:
+ return products
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ return productTypes
+ case TaxRateRuleReferenceType.SHIPPING_OPTION:
+ return shippingOptions
+ }
+ }
+
+ const referenceTypeOptions = [
+ {
+ value: TaxRateRuleReferenceType.PRODUCT,
+ label: t("taxRegions.fields.targets.options.product"),
+ },
+ {
+ value: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ label: t("taxRegions.fields.targets.options.productType"),
+ },
+ {
+ value: TaxRateRuleReferenceType.SHIPPING_OPTION,
+ label: t("taxRegions.fields.targets.options.shippingOption"),
+ },
+ ]
+
+ const searchPlaceholders = {
+ [TaxRateRuleReferenceType.PRODUCT]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_TYPE]: t(
+ "taxRegions.fields.targets.placeholders.productType"
+ ),
+ [TaxRateRuleReferenceType.SHIPPING_OPTION]: t(
+ "taxRegions.fields.targets.placeholders.shippingOption"
+ ),
+ }
+
+ const getFieldHandler = (type: TaxRateRuleReferenceType) => {
+ const { fields, remove, append } = getControls(type)
+ const modalId = getStackedModalId(type)
+
+ return (references: TaxRateRuleReference[]) => {
+ if (!references.length) {
+ form.setValue(type, [], {
+ shouldDirty: true,
+ })
+ setIsOpen(modalId, false)
+
+ return
+ }
+
+ const newIds = references.map((reference) => reference.value)
+
+ const fieldsToAdd = references.filter(
+ (reference) => !fields.some((field) => field.value === reference.value)
+ )
+
+ for (const field of fields) {
+ if (!newIds.includes(field.value)) {
+ remove(fields.indexOf(field))
+ }
+ }
+
+ append(fieldsToAdd)
+ setIsOpen(modalId, false)
+ }
+ }
+
+ const displayOrder = new Set<TaxRateRuleReferenceType>([
+ TaxRateRuleReferenceType.PRODUCT,
+ ])
+
+ const disableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(type, [], {
+ shouldDirty: true,
+ })
+ form.setValue(`enabled_rules.${type}`, false, {
+ shouldDirty: true,
+ })
+
+ displayOrder.delete(type)
+ }
+
+ const enableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(`enabled_rules.${type}`, true, {
+ shouldDirty: true,
+ })
+ form.setValue(type, [], {
+ shouldDirty: true,
+ })
+
+ displayOrder.add(type)
+ }
+
+ const watchedEnabledRules = useWatch({
+ control: form.control,
+ name: "enabled_rules",
+ })
+
+ const addRule = () => {
+ const firstDisabledRule = Object.keys(watchedEnabledRules).find(
+ (key) => !watchedEnabledRules[key as TaxRateRuleReferenceType]
+ )
+
+ if (firstDisabledRule) {
+ enableRule(firstDisabledRule as TaxRateRuleReferenceType)
+ }
+ }
+
+ const visibleRuleTypes = referenceTypeOptions
+ .filter((option) => watchedEnabledRules[option.value])
+ .sort((a, b) => {
+ const orderArray = Array.from(displayOrder)
+
+ return orderArray.indexOf(b.value) - orderArray.indexOf(a.value)
+ })
+
+ const getAvailableRuleTypes = (type: TaxRateRuleReferenceType) => {
+ return referenceTypeOptions.filter((option) => {
+ return (
+ !visibleRuleTypes.some(
+ (visibleOption) => visibleOption.value === option.value
+ ) || option.value === type
+ )
+ })
+ }
+
+ const showAddButton = Object.values(watchedEnabledRules).some(
+ (value) => !value
+ )
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <RouteFocusModal.Title asChild>
+ <Heading>
+ {t("taxRegions.taxOverrides.create.header")}
+ </Heading>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("taxRegions.taxOverrides.create.hint")}
+ </Text>
+ </RouteFocusModal.Description>
+ </div>
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxRate")}
+ </Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ placeholder="0.00"
+ decimalsLimit={4}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ <div className="flex flex-col gap-y-3">
+ <div className="flex items-center justify-between gap-x-4">
+ <div className="flex flex-col">
+ <div className="flex items-center gap-x-1">
+ <Label
+ id="tax_region_rules_label"
+ htmlFor="tax_region_rules"
+ >
+ {t("taxRegions.fields.targets.label")}
+ </Label>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-muted"
+ >
+ ({t("fields.optional")})
+ </Text>
+ </div>
+ <Hint
+ id="tax_region_rules_description"
+ className="text-pretty"
+ >
+ {t("taxRegions.fields.targets.hint")}
+ </Hint>
+ </div>
+ {showAddButton && (
+ <Button
+ onClick={addRule}
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover flex-shrink-0"
+ >
+ {t("taxRegions.fields.targets.action")}
+ </Button>
+ )}
+ </div>
+ <div
+ id="tax_region_rules"
+ aria-labelledby="tax_region_rules_label"
+ aria-describedby="tax_region_rules_description"
+ role="application"
+ className="flex flex-col gap-y-3"
+ >
+ {visibleRuleTypes.map((ruleType, index) => {
+ const type = ruleType.value
+ const label = ruleType.label
+ const isLast = index === visibleRuleTypes.length - 1
+ const searchPlaceholder = searchPlaceholders[type]
+
+ const options = getAvailableRuleTypes(type)
+
+ const { fields, remove } = getControls(type)
+ const handler = getFieldHandler(type)
+
+ const modalId = getStackedModalId(type)
+
+ const handleChangeType = (
+ value: TaxRateRuleReferenceType
+ ) => {
+ disableRule(type)
+ enableRule(value)
+ }
+
+ return (
+ <div key={type}>
+ <Form.Field
+ control={form.control}
+ name={ruleType.value}
+ render={({ field }) => {
+ return (
+ <Form.Item className="space-y-0">
+ <Form.Label className="sr-only">
+ {label}
+ </Form.Label>
+ <div
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
+ "aria-[invalid='true']:shadow-borders-error"
+ )}
+ role="application"
+ {...field}
+ >
+ <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">
+ {isLast ? (
+ <Select
+ dir={direction}
+ value={type}
+ onValueChange={handleChangeType}
+ >
+ <Select.Trigger className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {options.map((option) => {
+ return (
+ <Select.Item
+ key={option.value}
+ value={option.value}
+ >
+ {option.label}
+ </Select.Item>
+ )
+ })}
+ </Select.Content>
+ </Select>
+ ) : (
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {label}
+ </div>
+ )}
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t(
+ "taxRegions.fields.targets.operators.in"
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-1.5">
+ <StackedFocusModal id={modalId}>
+ <StackedFocusModal.Trigger asChild>
+ <button
+ type="button"
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"
+ >
+ <MagnifyingGlass />
+ {searchPlaceholder}
+ </button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Trigger asChild>
+ <Button variant="secondary">
+ {t("actions.browse")}
+ </Button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Content>
+ <StackedFocusModal.Header>
+ <StackedFocusModal.Title asChild>
+ <Heading className="sr-only">
+ {t(
+ "taxRegions.fields.targets.modal.header"
+ )}
+ </Heading>
+ </StackedFocusModal.Title>
+ <StackedFocusModal.Description className="sr-only">
+ {t(
+ "taxRegions.fields.targets.hint"
+ )}
+ </StackedFocusModal.Description>
+ </StackedFocusModal.Header>
+ <TargetForm
+ type="focus"
+ referenceType={type}
+ state={fields}
+ setState={handler}
+ />
+ </StackedFocusModal.Content>
+ </StackedFocusModal>
+ <Button
+ variant="secondary"
+ onClick={() => disableRule(type)}
+ type="button"
+ >
+ {t("actions.delete")}
+ </Button>
+ </div>
+ {fields.length > 0 ? (
+ <div className="flex flex-col gap-y-1.5">
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-1.5 px-1.5">
+ {fields.map((field, index) => {
+ return (
+ <TargetItem
+ key={field.id}
+ index={index}
+ label={field.label}
+ onRemove={remove}
+ value={field.value}
+ />
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ <Form.ErrorMessage className="mt-2" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-tax-override-create.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-tax-override-create.tsx
new file mode 100644
index 000000000..5e42c4641
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/_components/tax-region-tax-override-create.tsx
@@ -0,0 +1,652 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import {
+ Button,
+ Divider,
+ Heading,
+ Hint,
+ Input,
+ Label,
+ Select,
+ Text,
+ clx,
+ toast,
+} from "@medusajs/ui"
+import { useFieldArray, useForm, useWatch } from "react-hook-form"
+import { z } from "zod"
+
+import { MagnifyingGlass } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { useTranslation } from "react-i18next"
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import {
+ RouteFocusModal,
+ StackedFocusModal,
+ useRouteModal,
+ useStackedModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateTaxRate } from "@hooks/api/tax-rates"
+import { TargetForm } from "@pages/settings/tax-regions/_common/components/target-form"
+import { TargetItem } from "@pages/settings/tax-regions/_common/components/target-item"
+import { TaxRateRuleReferenceType } from "@pages/settings/tax-regions/_common/constants"
+import {
+ TaxRateRuleReference,
+ TaxRateRuleReferenceSchema,
+} from "@pages/settings/tax-regions/_common/schemas"
+import { createTaxRulePayload } from "@pages/settings/tax-regions/_common/utils"
+
+const TaxRegionCreateTaxOverrideSchema = z.object({
+ name: z.string().min(1),
+ code: z.string().min(1),
+ rate: z
+ .object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ })
+ .optional(),
+ is_combinable: z.boolean().optional(),
+ enabled_rules: z.object({
+ product: z.boolean(),
+ product_type: z.boolean(),
+ // product_collection: z.boolean(),
+ // product_tag: z.boolean(),
+ // customer_group: z.boolean(),
+ }),
+ product: z.array(TaxRateRuleReferenceSchema).optional(),
+ product_type: z.array(TaxRateRuleReferenceSchema).optional(),
+ // product_collection: z.array(TaxRateRuleReferenceSchema).optional(),
+ // product_tag: z.array(TaxRateRuleReferenceSchema).optional(),
+ // customer_group: z.array(TaxRateRuleReferenceSchema).optional(),
+})
+
+type TaxRegionCreateTaxOverrideFormProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+}
+
+const STACKED_MODAL_ID = "tr"
+const getStackedModalId = (type: TaxRateRuleReferenceType) =>
+ `${STACKED_MODAL_ID}-${type}`
+
+export const TaxRegionCreateTaxOverrideForm = ({
+ taxRegion,
+}: TaxRegionCreateTaxOverrideFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+ const { setIsOpen } = useStackedModal()
+
+ const form = useForm<z.infer<typeof TaxRegionCreateTaxOverrideSchema>>({
+ defaultValues: {
+ name: "",
+ code: "",
+ is_combinable: false,
+ rate: {
+ value: "",
+ },
+ enabled_rules: {
+ product: true,
+ product_type: false,
+ // product_collection: false,
+ // product_tag: false,
+ // customer_group: false,
+ },
+ product: [],
+ product_type: [],
+ // product_collection: [],
+ // product_tag: [],
+ // customer_group: [],
+ },
+ resolver: zodResolver(TaxRegionCreateTaxOverrideSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateTaxRate()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const {
+ product,
+ product_type,
+ // customer_group,
+ // product_collection,
+ // product_tag,
+ } = values
+
+ const productRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT,
+ references: product || [],
+ })
+ const productTypeRules = createTaxRulePayload({
+ reference_type: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ references: product_type || [],
+ })
+ // const customerGroupRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // references: customer_group || [],
+ // })
+ // const productCollectionRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // references: product_collection || [],
+ // })
+ // const productTagRules = createTaxRulePayload({
+ // reference_type: TaxRateRuleReferenceType.PRODUCT_TAG,
+ // references: product_tag || [],
+ // })
+
+ const rules = [
+ productRules,
+ productTypeRules,
+ // customerGroupRules,
+ // productCollectionRules,
+ // productTagRules,
+ ]
+ .filter((rule) => Boolean(rule))
+ .flatMap((r) => r) as HttpTypes.AdminCreateTaxRate["rules"]
+
+ mutateAsync(
+ {
+ name: values.name,
+ tax_region_id: taxRegion.id,
+ rate: values.rate?.float,
+ code: values.code,
+ is_combinable: values.is_combinable,
+ rules: rules,
+ is_default: false,
+ },
+ {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ const products = useFieldArray({
+ control: form.control,
+ name: TaxRateRuleReferenceType.PRODUCT,
+ })
+
+ const productTypes = useFieldArray({
+ control: form.control,
+ name: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ })
+
+ // const productCollections = useFieldArray({
+ // control: form.control,
+ // name: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // })
+ //
+ // const productTags = useFieldArray({
+ // control: form.control,
+ // name: TaxRateRuleReferenceType.PRODUCT_TAG,
+ // })
+ //
+ //
+ // const customerGroups = useFieldArray({
+ // control: form.control,
+ // name: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // })
+
+ const getControls = (type: TaxRateRuleReferenceType) => {
+ switch (type) {
+ case TaxRateRuleReferenceType.PRODUCT:
+ return products
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ return productTypes
+ // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
+ // return productCollections
+ // case TaxRateRuleReferenceType.PRODUCT_TAG:
+ // return productTags
+ // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
+ // return customerGroups
+ default:
+ return products
+ }
+ }
+
+ const referenceTypeOptions = [
+ {
+ value: TaxRateRuleReferenceType.PRODUCT,
+ label: t("taxRegions.fields.targets.options.product"),
+ },
+ {
+ value: TaxRateRuleReferenceType.PRODUCT_TYPE,
+ label: t("taxRegions.fields.targets.options.productType"),
+ },
+ // {
+ // value: TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // label: t("taxRegions.fields.targets.options.productCollection"),
+ // },
+ // {
+ // value: TaxRateRuleReferenceType.PRODUCT_TAG,
+ // label: t("taxRegions.fields.targets.options.productTag"),
+ // },
+ // {
+ // value: TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // label: t("taxRegions.fields.targets.options.customerGroup"),
+ // },
+ ]
+
+ const searchPlaceholders: Record<TaxRateRuleReferenceType, string> = {
+ [TaxRateRuleReferenceType.PRODUCT]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_TYPE]: t(
+ "taxRegions.fields.targets.placeholders.productType"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_COLLECTION]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.PRODUCT_TAG]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ [TaxRateRuleReferenceType.CUSTOMER_GROUP]: t(
+ "taxRegions.fields.targets.placeholders.product"
+ ),
+ }
+
+ const getFieldHandler = (type: TaxRateRuleReferenceType) => {
+ const controls = getControls(type)
+ const { fields, remove, append } = controls
+ const modalId = getStackedModalId(type)
+
+ return (references: TaxRateRuleReference[]) => {
+ if (!references.length) {
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+ setIsOpen(modalId, false)
+ return
+ }
+
+ const newIds = references.map((reference) => reference.value)
+
+ const fieldsToAdd = references.filter(
+ (reference) => !fields.some((field) => field.value === reference.value)
+ )
+
+ for (const field of fields) {
+ if (!newIds.includes(field.value)) {
+ remove(fields.indexOf(field))
+ }
+ }
+
+ append(fieldsToAdd)
+ setIsOpen(modalId, false)
+ }
+ }
+
+ const displayOrder = new Set<TaxRateRuleReferenceType>([
+ TaxRateRuleReferenceType.PRODUCT,
+ ])
+
+ const disableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+
+ form.setValue(`enabled_rules.${type}` as "enabled_rules.product" | "enabled_rules.product_type", false, {
+ shouldDirty: true,
+ })
+
+ displayOrder.delete(type)
+ }
+
+ const enableRule = (type: TaxRateRuleReferenceType) => {
+ form.setValue(`enabled_rules.${type}` as "enabled_rules.product" | "enabled_rules.product_type", true, {
+ shouldDirty: true,
+ })
+ form.setValue(type as "product" | "product_type", [], {
+ shouldDirty: true,
+ })
+
+ displayOrder.add(type)
+ }
+
+ const watchedEnabledRules = useWatch({
+ control: form.control,
+ name: "enabled_rules",
+ })
+
+ const addRule = () => {
+ const firstDisabledRule = Object.keys(watchedEnabledRules).find(
+ (key) => !watchedEnabledRules[key as keyof typeof watchedEnabledRules]
+ )
+
+ if (firstDisabledRule) {
+ enableRule(firstDisabledRule as TaxRateRuleReferenceType)
+ }
+ }
+
+ const visibleRuleTypes = referenceTypeOptions
+ .filter((option) => watchedEnabledRules[option.value as keyof typeof watchedEnabledRules])
+ .sort((a, b) => {
+ const orderArray = Array.from(displayOrder)
+ return orderArray.indexOf(b.value) - orderArray.indexOf(a.value)
+ })
+
+ const getAvailableRuleTypes = (type: TaxRateRuleReferenceType) => {
+ return referenceTypeOptions.filter((option) => {
+ return (
+ !visibleRuleTypes.some(
+ (visibleOption) => visibleOption.value === option.value
+ ) || option.value === type
+ )
+ })
+ }
+
+ const showAddButton = Object.values(watchedEnabledRules).some(
+ (value) => !value
+ )
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <RouteFocusModal.Title asChild>
+ <Heading>
+ {t("taxRegions.taxOverrides.create.header")}
+ </Heading>
+ </RouteFocusModal.Title>
+ <RouteFocusModal.Description asChild>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("taxRegions.taxOverrides.create.hint")}
+ </Text>
+ </RouteFocusModal.Description>
+ </div>
+ <div className="flex flex-col gap-4">
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxRate")}
+ </Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ placeholder="0.00"
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ <div className="flex flex-col gap-y-3">
+ <div className="flex items-center justify-between gap-x-4">
+ <div className="flex flex-col">
+ <div className="flex items-center gap-x-1">
+ <Label
+ id="tax_region_rules_label"
+ htmlFor="tax_region_rules"
+ >
+ {t("taxRegions.fields.targets.label")}
+ </Label>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-muted"
+ >
+ ({t("fields.optional")})
+ </Text>
+ </div>
+ <Hint
+ id="tax_region_rules_description"
+ className="text-pretty"
+ >
+ {t("taxRegions.fields.targets.hint")}
+ </Hint>
+ </div>
+ {showAddButton && (
+ <Button
+ onClick={addRule}
+ type="button"
+ size="small"
+ variant="transparent"
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover flex-shrink-0"
+ >
+ {t("taxRegions.fields.targets.action")}
+ </Button>
+ )}
+ </div>
+ <div
+ id="tax_region_rules"
+ aria-labelledby="tax_region_rules_label"
+ aria-describedby="tax_region_rules_description"
+ role="application"
+ className="flex flex-col gap-y-3"
+ >
+ {visibleRuleTypes.map((ruleType, index) => {
+ const type = ruleType.value
+ const label = ruleType.label
+ const isLast = index === visibleRuleTypes.length - 1
+ const searchPlaceholder = searchPlaceholders[type]
+
+ const options = getAvailableRuleTypes(type)
+
+ const { fields, remove } = getControls(type)
+ const handler = getFieldHandler(type)
+
+ const modalId = getStackedModalId(type)
+
+ const handleChangeType = (
+ value: TaxRateRuleReferenceType
+ ) => {
+ disableRule(type)
+ enableRule(value)
+ }
+
+ return (
+ <div key={type}>
+ <Form.Field
+ control={form.control}
+ name={ruleType.value as "product" | "product_type"}
+ render={({
+ field: {
+ value: _value,
+ onChange: _onChange,
+ ...field
+ },
+ }) => {
+ return (
+ <Form.Item className="space-y-0">
+ <Form.Label className="sr-only">
+ {label}
+ </Form.Label>
+ <div
+ className={clx(
+ "bg-ui-bg-component shadow-elevation-card-rest transition-fg grid gap-1.5 rounded-xl py-1.5",
+ "aria-[invalid='true']:shadow-borders-error"
+ )}
+ role="application"
+ {...field}
+ >
+ <div className="text-ui-fg-subtle grid gap-1.5 px-1.5 md:grid-cols-2">
+ {isLast ? (
+ <Select
+ value={type}
+ onValueChange={handleChangeType}
+ >
+ <Select.Trigger className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content>
+ {options.map((option) => {
+ return (
+ <Select.Item
+ key={option.value}
+ value={option.value}
+ >
+ {option.label}
+ </Select.Item>
+ )
+ })}
+ </Select.Content>
+ </Select>
+ ) : (
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {label}
+ </div>
+ )}
+ <div className="bg-ui-bg-field shadow-borders-base txt-compact-small rounded-md px-2 py-1.5">
+ {t(
+ "taxRegions.fields.targets.operators.in"
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-1.5 px-1.5">
+ <StackedFocusModal id={modalId}>
+ <StackedFocusModal.Trigger asChild>
+ <button
+ type="button"
+ className="bg-ui-bg-field-component hover:bg-ui-bg-field-component-hover shadow-borders-base txt-compact-small text-ui-fg-muted transition-fg focus-visible:shadow-borders-interactive-with-active flex flex-1 items-center gap-x-2 rounded-md px-2 py-1.5 outline-none"
+ >
+ <MagnifyingGlass />
+ {searchPlaceholder}
+ </button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Trigger asChild>
+ <Button variant="secondary">
+ {t("actions.browse")}
+ </Button>
+ </StackedFocusModal.Trigger>
+ <StackedFocusModal.Content>
+ <StackedFocusModal.Header>
+ <StackedFocusModal.Title asChild>
+ <Heading className="sr-only">
+ {t(
+ "taxRegions.fields.targets.modal.header"
+ )}
+ </Heading>
+ </StackedFocusModal.Title>
+ <StackedFocusModal.Description className="sr-only">
+ {t(
+ "taxRegions.fields.targets.hint"
+ )}
+ </StackedFocusModal.Description>
+ </StackedFocusModal.Header>
+ <TargetForm
+ type="focus"
+ referenceType={type}
+ state={fields}
+ setState={handler}
+ />
+ </StackedFocusModal.Content>
+ </StackedFocusModal>
+ <Button
+ variant="secondary"
+ onClick={() => disableRule(type)}
+ type="button"
+ >
+ {t("actions.delete")}
+ </Button>
+ </div>
+ {fields.length > 0 ? (
+ <div className="flex flex-col gap-y-1.5">
+ <Divider variant="dashed" />
+ <div className="flex flex-col gap-y-1.5 px-1.5">
+ {fields.map((field, index) => {
+ return (
+ <TargetItem
+ key={field.id}
+ index={index}
+ label={field.label}
+ onRemove={remove}
+ />
+ )
+ })}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ <Form.ErrorMessage className="mt-2" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/index.tsx
new file mode 100644
index 000000000..44735df6d
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-overrides/create/index.tsx
@@ -0,0 +1,26 @@
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useTaxRegion } from "@hooks/api/tax-regions"
+import { TaxRegionCreateTaxOverrideForm } from "./_components/tax-region-override-create-form"
+
+const TaxRegionCreateTaxOverride = () => {
+ const { id, province_id } = useParams()
+
+ const { tax_region, isPending, isError, error } = useTaxRegion(
+ province_id || id!
+ )
+
+ const ready = !isPending && !!tax_region
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && <TaxRegionCreateTaxOverrideForm taxRegion={tax_region} />}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = TaxRegionCreateTaxOverride
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/_components/tax-region-tax-rate-edit-form.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/_components/tax-region-tax-rate-edit-form.tsx
new file mode 100644
index 000000000..dc73506f5
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/_components/tax-region-tax-rate-edit-form.tsx
@@ -0,0 +1,158 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Input, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateTaxRate } from "@hooks/api/tax-rates"
+
+type TaxRegionTaxRateEditFormProps = {
+ taxRate: HttpTypes.AdminTaxRate
+ isSublevel?: boolean
+}
+
+const TaxRegionTaxRateEditSchema = z.object({
+ name: z.string().min(1),
+ code: z.string().optional(),
+ rate: z.object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ }),
+ is_combinable: z.boolean().optional(),
+})
+
+export const TaxRegionTaxRateEditForm = ({
+ taxRate,
+ isSublevel = false,
+}: TaxRegionTaxRateEditFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof TaxRegionTaxRateEditSchema>>({
+ defaultValues: {
+ name: taxRate.name,
+ code: taxRate.code,
+ rate: {
+ value: taxRate.rate?.toString() || "",
+ },
+ is_combinable: taxRate.is_combinable,
+ },
+ resolver: zodResolver(TaxRegionTaxRateEditSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateTaxRate(taxRate.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ name: values.name,
+ code: values.code || taxRate.code,
+ rate: values.rate?.float,
+ is_combinable: values.is_combinable,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("taxRegions.taxRates.edit.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ className="flex flex-1 flex-col overflow-hidden"
+ onSubmit={handleSubmit}
+ >
+ <RouteDrawer.Body className="flex flex-1 flex-col gap-y-6 overflow-auto">
+ <div className="flex flex-col gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("taxRegions.fields.taxCode")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("taxRegions.fields.taxRate")}</Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {isSublevel && (
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ )}
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer className="shrink-0">
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/index.tsx
new file mode 100644
index 000000000..e7856f9fb
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/[tax_rate_id]/edit/index.tsx
@@ -0,0 +1,40 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useTaxRate } from "@hooks/api/tax-rates"
+import { TaxRegionTaxRateEditForm } from "./_components/tax-region-tax-rate-edit-form"
+
+const TaxRegionTaxRateEdit = () => {
+ const { t } = useTranslation()
+ const { province_id, tax_rate_id } = useParams()
+
+ const { tax_rate, isPending, isError, error } = useTaxRate(tax_rate_id!)
+
+ const ready = !isPending && !!tax_rate
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>{t("taxRegions.taxRates.edit.header")}</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description className="sr-only">
+ {t("taxRegions.taxRates.edit.hint")}
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ {ready && (
+ <TaxRegionTaxRateEditForm
+ taxRate={tax_rate}
+ isSublevel={!!province_id}
+ />
+ )}
+ </RouteDrawer>
+ )
+}
+
+export const Component = TaxRegionTaxRateEdit
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/_components/tax-region-tax-rate-create-form.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/_components/tax-region-tax-rate-create-form.tsx
new file mode 100644
index 000000000..a679dce98
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/_components/tax-region-tax-rate-create-form.tsx
@@ -0,0 +1,179 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import { Button, Heading, Input, Text, toast } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+import { Form } from "@components/common/form"
+import { SwitchBox } from "@components/common/switch-box"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateTaxRate } from "@hooks/api/tax-rates"
+
+type TaxRegionTaxRateCreateFormProps = {
+ taxRegion: HttpTypes.AdminTaxRegion
+ isSublevel?: boolean
+}
+
+const TaxRegionTaxRateCreateSchema = z.object({
+ name: z.string().min(1),
+ code: z.string().min(1),
+ rate: z
+ .object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ })
+ .optional(),
+ is_combinable: z.boolean().optional(),
+})
+
+export const TaxRegionTaxRateCreateForm = ({
+ taxRegion,
+ isSublevel = false,
+}: TaxRegionTaxRateCreateFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof TaxRegionTaxRateCreateSchema>>({
+ defaultValues: {
+ name: "",
+ code: "",
+ rate: {
+ value: "",
+ },
+ is_combinable: false,
+ },
+ resolver: zodResolver(TaxRegionTaxRateCreateSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateTaxRate()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(
+ {
+ tax_region_id: taxRegion.id,
+ is_default: true,
+ name: values.name,
+ code: values.code,
+ rate: values.rate?.float,
+ is_combinable: values.is_combinable,
+ },
+ {
+ onSuccess: () => {
+ toast.success(t("taxRegions.taxRates.create.successToast"))
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading>{t(`taxRegions.taxRates.create.header`)}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t(`taxRegions.taxRates.create.hint`)}
+ </Text>
+ </div>
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxRate")}
+ </Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ {isSublevel && (
+ <SwitchBox
+ control={form.control}
+ name="is_combinable"
+ label={t("taxRegions.fields.isCombinable.label")}
+ description={t("taxRegions.fields.isCombinable.hint")}
+ />
+ )}
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/index.tsx b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/index.tsx
new file mode 100644
index 000000000..46434e751
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/[id]/tax-rates/create/index.tsx
@@ -0,0 +1,31 @@
+import { useParams } from "react-router-dom"
+import { RouteFocusModal } from "@components/modals"
+import { useTaxRegion } from "@hooks/api/tax-regions"
+import { TaxRegionTaxRateCreateForm } from "./_components/tax-region-tax-rate-create-form"
+
+const TaxRegionTaxRateCreate = () => {
+ const { id, province_id } = useParams()
+
+ const { tax_region, isPending, isError, error } = useTaxRegion(
+ province_id || id!
+ )
+
+ const ready = !isPending && !!tax_region
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal>
+ {ready && (
+ <TaxRegionTaxRateCreateForm
+ taxRegion={tax_region}
+ isSublevel={!!province_id}
+ />
+ )}
+ </RouteFocusModal>
+ )
+}
+
+export const Component = TaxRegionTaxRateCreate
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/target-form.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/target-form.tsx
new file mode 100644
index 000000000..a7a408340
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/target-form.tsx
@@ -0,0 +1,814 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button, Checkbox } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import {
+ OnChangeFn,
+ RowSelectionState,
+ createColumnHelper,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useTranslation } from "react-i18next"
+
+import { useSearchParams } from "react-router-dom"
+import {
+ StackedDrawer,
+ StackedFocusModal,
+} from "@components/modals"
+import { _DataTable } from "@components/table/data-table"
+import {
+ useCollections,
+ useCustomerGroups,
+ useProductTags,
+ useProductTypes,
+ useProducts,
+} from "@hooks/api"
+import {
+ useCollectionTableColumns,
+ useCustomerGroupTableColumns,
+ useProductTableColumns,
+ useProductTagTableColumns,
+ useProductTypeTableColumns,
+} from "@hooks/table/columns"
+import {
+ useCollectionTableFilters,
+ useCustomerGroupTableFilters,
+ useProductTableFilters,
+ useProductTagTableFilters,
+ useProductTypeTableFilters,
+} from "@hooks/table/filters"
+import {
+ useCollectionTableQuery,
+ useCustomerGroupTableQuery,
+ useProductTableQuery,
+ useProductTagTableQuery,
+ useProductTypeTableQuery,
+} from "@hooks/table/query"
+import { useDataTable } from "@hooks/use-data-table"
+import { ExtendedAdminProduct } from "@custom-types/products"
+import { TaxRateRuleReferenceType } from "../constants"
+import { TaxRateRuleReference } from "../schemas"
+import { CustomerGroupData } from "../../../../orders/common/customerGroupFiltering"
+
+type TargetFormProps = {
+ referenceType: TaxRateRuleReferenceType
+ type: "focus" | "drawer"
+ state: TaxRateRuleReference[]
+ setState: (state: TaxRateRuleReference[]) => void
+}
+
+function initRowSelection(state: TaxRateRuleReference[]) {
+ return state.reduce((acc, reference) => {
+ acc[reference.value] = true
+ return acc
+ }, {} as RowSelectionState)
+}
+
+export const TargetForm = ({
+ referenceType,
+ type,
+ setState,
+ state,
+}: TargetFormProps) => {
+ const { t } = useTranslation()
+ const Component = type === "focus" ? StackedFocusModal : StackedDrawer
+
+ const [intermediate, setIntermediate] =
+ useState<TaxRateRuleReference[]>(state)
+
+ const handleSave = () => {
+ setState(intermediate)
+ }
+
+ return (
+ <div className="flex size-full flex-col overflow-hidden">
+ <Component.Body className="min-h-0 p-0">
+ <Table
+ referenceType={referenceType}
+ initialRowState={initRowSelection(state)}
+ intermediate={intermediate}
+ setIntermediate={setIntermediate}
+ />
+ </Component.Body>
+ <Component.Footer>
+ <Component.Close asChild>
+ <Button variant="secondary" size="small" type="button">
+ {t("actions.cancel")}
+ </Button>
+ </Component.Close>
+ <Button type="button" size="small" onClick={handleSave}>
+ {t("actions.save")}
+ </Button>
+ </Component.Footer>
+ </div>
+ )
+}
+
+type TableProps = {
+ referenceType: TaxRateRuleReferenceType
+ initialRowState: RowSelectionState
+ intermediate: TaxRateRuleReference[]
+ setIntermediate: (state: TaxRateRuleReference[]) => void
+}
+
+const Table = ({ referenceType, ...props }: TableProps) => {
+ switch (referenceType) {
+ case TaxRateRuleReferenceType.CUSTOMER_GROUP:
+ return <CustomerGroupTable {...props} />
+ case TaxRateRuleReferenceType.PRODUCT:
+ return <ProductTable {...props} />
+ case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
+ return <ProductCollectionTable {...props} />
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ return <ProductTypeTable {...props} />
+ case TaxRateRuleReferenceType.PRODUCT_TAG:
+ return <ProductTagTable {...props} />
+ default:
+ return null
+ }
+}
+
+type TableImplementationProps = {
+ initialRowState: RowSelectionState
+ intermediate: TaxRateRuleReference[]
+ setIntermediate: (state: TaxRateRuleReference[]) => void
+}
+
+const PAGE_SIZE = 50
+
+const PREFIX_CUSTOMER_GROUP = "cg"
+
+const CustomerGroupTable = ({
+ initialRowState,
+ intermediate,
+ setIntermediate,
+}: TableImplementationProps) => {
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialRowState)
+
+ useCleanupSearchParams()
+
+ const { searchParams, raw } = useCustomerGroupTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_CUSTOMER_GROUP,
+ })
+ const { customer_groups, count, isLoading, isError, error } =
+ useCustomerGroups(searchParams, {
+ placeholderData: keepPreviousData,
+ })
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newCustomerGroups =
+ customer_groups
+ ?.filter((cg) => newIds.includes(cg.customer_group_id))
+ .flatMap((cg) => ({ value: cg.customer_group_id, label: cg.customer_group.name! })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (cg) => !removedIds.includes(cg.value)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newCustomerGroups])
+ setRowSelection(state)
+ }
+
+ const filters = useCustomerGroupTableFilters()
+ const columns = useGroupColumns()
+
+ const { table } = useDataTable({
+ data: customer_groups || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.customer_group_id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_CUSTOMER_GROUP,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX_CUSTOMER_GROUP}
+ queryObject={raw}
+ />
+ )
+}
+
+const cgColumnHelper = createColumnHelper<CustomerGroupData>()
+
+const useGroupColumns = () => {
+ const base = useCustomerGroupTableColumns()
+
+ return useMemo(
+ () => [
+ cgColumnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const PREFIX_PRODUCT = "p"
+
+const ProductTable = ({
+ initialRowState,
+ intermediate,
+ setIntermediate,
+}: TableImplementationProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialRowState)
+
+ useCleanupSearchParams()
+
+ const { searchParams, raw } = useProductTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT,
+ })
+
+ const { products, count, isLoading, isError, error } = useProducts(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newProducts =
+ products
+ ?.filter((p) => newIds.includes(p.id))
+ .map((p) => ({
+ value: p.id,
+ label: p.title!,
+ })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (p) => !removedIds.includes(p.value)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newProducts])
+ setRowSelection(state)
+ }
+
+ const filters = useProductTableFilters()
+ const columns = useProductColumns()
+
+ const { table } = useDataTable({
+ data: products || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX_PRODUCT}
+ queryObject={raw}
+ />
+ )
+}
+
+const pColumnHelper = createColumnHelper<ExtendedAdminProduct>()
+
+const useProductColumns = () => {
+ const base = useProductTableColumns()
+
+ return useMemo(
+ () => [
+ pColumnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const PREFIX_PRODUCT_COLLECTION = "pc"
+
+const ProductCollectionTable = ({
+ initialRowState,
+ intermediate,
+ setIntermediate,
+}: TableImplementationProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialRowState)
+
+ useCleanupSearchParams()
+
+ const { searchParams, raw } = useCollectionTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_COLLECTION,
+ })
+
+ const { product_collections: collections, count, isLoading, isError, error } = useCollections(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newCollections =
+ collections
+ ?.filter((p) => newIds.includes(p.id))
+ .map((p) => ({
+ value: p.id,
+ label: p.title,
+ })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (p) => !removedIds.includes(p.value)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newCollections])
+ setRowSelection(state)
+ }
+
+ const filters = useCollectionTableFilters()
+ const columns = useCollectionColumns()
+
+ const { table } = useDataTable({
+ data: collections || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_COLLECTION,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "title", label: t("fields.title") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX_PRODUCT_COLLECTION}
+ queryObject={raw}
+ />
+ )
+}
+
+const pcColumnHelper = createColumnHelper<HttpTypes.AdminCollection>()
+
+const useCollectionColumns = () => {
+ const base = useCollectionTableColumns()
+
+ return useMemo(
+ () => [
+ pcColumnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const PREFIX_PRODUCT_TYPE = "pt"
+
+const ProductTypeTable = ({
+ initialRowState,
+ intermediate,
+ setIntermediate,
+}: TableImplementationProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialRowState)
+
+ useCleanupSearchParams()
+
+ const { searchParams, raw } = useProductTypeTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_TYPE,
+ })
+
+ const { product_types, count, isLoading, isError, error } = useProductTypes(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newTypes =
+ product_types
+ ?.filter((p) => newIds.includes(p.id))
+ .map((p) => ({
+ value: p.id,
+ label: p.value,
+ })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (p) => !removedIds.includes(p.value)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newTypes])
+ setRowSelection(state)
+ }
+
+ const filters = useProductTypeTableFilters()
+ const columns = useProductTypeColumns()
+
+ const { table } = useDataTable({
+ data: product_types || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_TYPE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "value", label: t("fields.value") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX_PRODUCT_TYPE}
+ queryObject={raw}
+ />
+ )
+}
+
+const ptColumnHelper = createColumnHelper<HttpTypes.AdminProductType>()
+
+const useProductTypeColumns = () => {
+ const base = useProductTypeTableColumns()
+
+ return useMemo(
+ () => [
+ ptColumnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const PREFIX_PRODUCT_TAG = "ptag"
+
+const ProductTagTable = ({
+ initialRowState,
+ intermediate,
+ setIntermediate,
+}: TableImplementationProps) => {
+ const { t } = useTranslation()
+
+ const [rowSelection, setRowSelection] =
+ useState<RowSelectionState>(initialRowState)
+
+ useCleanupSearchParams()
+
+ const { searchParams, raw } = useProductTagTableQuery({
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_TAG,
+ })
+
+ const { product_tags, count, isLoading, isError, error } = useProductTags(
+ searchParams,
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const updater: OnChangeFn<RowSelectionState> = (value) => {
+ const state = typeof value === "function" ? value(rowSelection) : value
+ const currentIds = Object.keys(rowSelection)
+
+ const ids = Object.keys(state)
+
+ const newIds = ids.filter((id) => !currentIds.includes(id))
+ const removedIds = currentIds.filter((id) => !ids.includes(id))
+
+ const newTags =
+ product_tags
+ ?.filter((p) => newIds.includes(p.id))
+ .map((p) => ({
+ value: p.id,
+ label: p.value,
+ })) || []
+
+ const filteredIntermediate = intermediate.filter(
+ (p) => !removedIds.includes(p.value)
+ )
+
+ setIntermediate([...filteredIntermediate, ...newTags])
+ setRowSelection(state)
+ }
+
+ const filters = useProductTagTableFilters()
+ const columns = useProductTagColumns()
+
+ const { table } = useDataTable({
+ data: product_tags || [],
+ columns,
+ count,
+ enablePagination: true,
+ enableRowSelection: true,
+ getRowId: (row) => row.id,
+ rowSelection: {
+ state: rowSelection,
+ updater,
+ },
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX_PRODUCT_TAG,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <_DataTable
+ table={table}
+ columns={columns}
+ pageSize={PAGE_SIZE}
+ count={count}
+ isLoading={isLoading}
+ filters={filters}
+ orderBy={[
+ { key: "value", label: t("fields.value") },
+ { key: "created_at", label: t("fields.createdAt") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ ]}
+ layout="fill"
+ pagination
+ search
+ prefix={PREFIX_PRODUCT_TAG}
+ queryObject={raw}
+ />
+ )
+}
+
+const ptagColumnHelper = createColumnHelper<HttpTypes.AdminProductTag>()
+
+const useProductTagColumns = () => {
+ const base = useProductTagTableColumns()
+
+ return useMemo(
+ () => [
+ ptagColumnHelper.display({
+ id: "select",
+ header: ({ table }) => {
+ return (
+ <Checkbox
+ checked={
+ table.getIsSomePageRowsSelected()
+ ? "indeterminate"
+ : table.getIsAllPageRowsSelected()
+ }
+ onCheckedChange={(value) =>
+ table.toggleAllPageRowsSelected(!!value)
+ }
+ />
+ )
+ },
+ cell: ({ row }) => {
+ return (
+ <Checkbox
+ checked={row.getIsSelected()}
+ onCheckedChange={(value) => row.toggleSelected(!!value)}
+ onClick={(e) => {
+ e.stopPropagation()
+ }}
+ />
+ )
+ },
+ }),
+ ...base,
+ ],
+ [base]
+ )
+}
+
+const useCleanupSearchParams = () => {
+ const [_, setSearchParams] = useSearchParams()
+
+ useEffect(() => {
+ return () => {
+ setSearchParams({})
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [])
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/target-item.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/target-item.tsx
new file mode 100644
index 000000000..4f30b0fd4
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/target-item.tsx
@@ -0,0 +1,26 @@
+import { XMarkMini } from "@medusajs/icons"
+import { IconButton, Text } from "@medusajs/ui"
+
+type TargetItemProps = {
+ index: number
+ onRemove: (index: number) => void
+ label: string
+}
+
+export const TargetItem = ({ index, label, onRemove }: TargetItemProps) => {
+ return (
+ <div className="bg-ui-bg-field-component shadow-borders-base flex items-center justify-between gap-2 rounded-md px-2 py-0.5">
+ <Text size="small" leading="compact">
+ {label}
+ </Text>
+ <IconButton
+ size="small"
+ variant="transparent"
+ type="button"
+ onClick={() => onRemove(index)}
+ >
+ <XMarkMini />
+ </IconButton>
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-card.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-card.tsx
new file mode 100644
index 000000000..1c62ecd84
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-card.tsx
@@ -0,0 +1,390 @@
+import {
+ ArrowDownRightMini,
+ PencilSquare,
+ Trash,
+ TriangleRightMini,
+} from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Badge,
+ Divider,
+ IconButton,
+ StatusBadge,
+ Text,
+ Tooltip,
+} from "@medusajs/ui"
+import { Collapsible as RadixCollapsible } from "radix-ui"
+import { ComponentPropsWithoutRef } from "react"
+import { useTranslation } from "react-i18next"
+
+type FetchError = Error & { status?: number }
+import { ActionMenu } from "@components/common/action-menu"
+import { useProductTypes } from "@hooks/api/product-types"
+import { useProducts } from "@hooks/api/products"
+import { formatPercentage } from "@lib/percentage-helpers"
+import { TaxRateRuleReferenceType } from "../constants"
+import { useDeleteTaxRateAction } from "../hooks"
+
+interface TaxOverrideCardProps extends ComponentPropsWithoutRef<"div"> {
+ taxRate: HttpTypes.AdminTaxRate
+}
+
+export const TaxOverrideCard = ({ taxRate }: TaxOverrideCardProps) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeleteTaxRateAction(taxRate)
+
+ if (taxRate.is_default) {
+ return null
+ }
+
+ const groupedRules = taxRate.rules.reduce(
+ (acc, rule) => {
+ if (!acc[rule.reference]) {
+ acc[rule.reference] = []
+ }
+
+ acc[rule.reference].push(rule.reference_id)
+
+ return acc
+ },
+ {} as Record<string, string[]>
+ )
+
+ const validKeys = Object.values(TaxRateRuleReferenceType)
+ const numberOfTargets = Object.keys(groupedRules).map((key) =>
+ validKeys.includes(key as TaxRateRuleReferenceType)
+ ).length
+
+ return (
+ <RadixCollapsible.Root>
+ <div className="flex items-center justify-between px-6 py-3">
+ <div className="flex items-center gap-x-2">
+ <RadixCollapsible.Trigger asChild>
+ <IconButton size="2xsmall" variant="transparent" className="group">
+ <TriangleRightMini className="text-ui-fg-muted transition-transform group-data-[state='open']:rotate-90" />
+ </IconButton>
+ </RadixCollapsible.Trigger>
+ <div className="flex items-center gap-x-1.5">
+ <Text size="small" weight="plus" leading="compact">
+ {taxRate.name}
+ </Text>
+ {taxRate.code && (
+ <div className="text-ui-fg-subtle flex items-center gap-x-1.5">
+ <Text size="small" leading="compact">
+ ·
+ </Text>
+ <Text size="small" leading="compact">
+ {taxRate.code}
+ </Text>
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="flex items-center gap-x-3">
+ <Text size="small" leading="compact" className="text-ui-fg-subtle">
+ {t("taxRegions.fields.targets.numberOfTargets", {
+ count: numberOfTargets,
+ })}
+ </Text>
+ <div className="bg-ui-border-base h-3 w-px" />
+ <StatusBadge color={taxRate.is_combinable ? "green" : "grey"}>
+ {taxRate.is_combinable
+ ? t("taxRegions.fields.isCombinable.true")
+ : t("taxRegions.fields.isCombinable.false")}
+ </StatusBadge>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: `overrides/${taxRate.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ </div>
+ <RadixCollapsible.Content>
+ <div className="bg-ui-bg-subtle">
+ <Divider variant="dashed" />
+ <div className="px-6 py-3">
+ <div className="flex items-center gap-x-3">
+ <div className="text-ui-fg-muted flex size-5 items-center justify-center">
+ <ArrowDownRightMini />
+ </div>
+ <div className="flex flex-wrap items-center gap-x-1.5 gap-y-2">
+ <Badge size="2xsmall">{formatPercentage(taxRate.rate)}</Badge>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ {t("taxRegions.fields.targets.operators.on")}
+ </Text>
+ {Object.entries(groupedRules).map(([reference, ids], index) => {
+ return (
+ <div
+ key={reference}
+ className="flex items-center gap-x-1.5"
+ >
+ <Reference
+ key={reference}
+ reference={reference as TaxRateRuleReferenceType}
+ ids={ids}
+ />
+ {index < Object.keys(groupedRules).length - 1 && (
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ >
+ {t("taxRegions.fields.targets.operators.and")}
+ </Text>
+ )}
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ </div>
+ </div>
+ </RadixCollapsible.Content>
+ </RadixCollapsible.Root>
+ )
+}
+
+const Reference = ({
+ reference,
+ ids,
+}: {
+ reference: TaxRateRuleReferenceType
+ ids: string[]
+}) => {
+ return (
+ <div className="flex items-center gap-x-1.5">
+ <ReferenceBadge reference={reference} />
+ <ReferenceValues type={reference} ids={ids} />
+ </div>
+ )
+}
+
+const ReferenceBadge = ({
+ reference,
+}: {
+ reference: TaxRateRuleReferenceType
+}) => {
+ const { t } = useTranslation()
+ let label: string | null = null
+
+ switch (reference) {
+ case TaxRateRuleReferenceType.PRODUCT:
+ label = t("taxRegions.fields.targets.tags.product")
+ break
+ // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
+ // label = t("taxRegions.fields.targets.tags.productCollection")
+ // break
+ // case TaxRateRuleReferenceType.PRODUCT_TAG:
+ // label = t("taxRegions.fields.targets.tags.productTag")
+ // break
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ label = t("taxRegions.fields.targets.tags.productType")
+ break
+ // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
+ // label = t("taxRegions.fields.targets.tags.customerGroup")
+ // break
+ }
+
+ if (!label) {
+ return null
+ }
+
+ return <Badge size="2xsmall">{label}</Badge>
+}
+
+const ReferenceValues = ({
+ type,
+ ids,
+}: {
+ type: TaxRateRuleReferenceType
+ ids: string[]
+}) => {
+ const { t } = useTranslation()
+
+ const { isPending, additional, labels, isError, error } = useReferenceValues(
+ type,
+ ids
+ )
+
+ if (isError) {
+ throw error
+ }
+
+ if (isPending) {
+ return (
+ <div className="bg-ui-tag-neutral-bg border-ui-tag-neutral-border h-5 w-14 animate-pulse rounded-md" />
+ )
+ }
+
+ return (
+ <Tooltip
+ content={
+ <ul>
+ {labels?.map((label: string, index) => <li key={index}>{label}</li>)}
+ {additional > 0 && (
+ <li>
+ {t("taxRegions.fields.targets.additionalValues", {
+ count: additional,
+ })}
+ </li>
+ )}
+ </ul>
+ }
+ >
+ <Badge size="2xsmall">
+ {t("taxRegions.fields.targets.values", {
+ count: ids.length,
+ })}
+ </Badge>
+ </Tooltip>
+ )
+}
+
+const useReferenceValues = (
+ type: TaxRateRuleReferenceType,
+ ids: string[]
+): {
+ labels: string[] | undefined
+ isPending: boolean
+ additional: number
+ isError: boolean
+ error: FetchError | null
+} => {
+ const products = useProducts(
+ {
+ id: ids,
+ limit: 10,
+ },
+ {
+ enabled: !!ids.length && type === TaxRateRuleReferenceType.PRODUCT,
+ }
+ )
+
+ // const tags = useProductTags(
+ // {
+ // id: ids,
+ // limit: 10,
+ // },
+ // {
+ // enabled: !!ids.length && type === TaxRateRuleReferenceType.PRODUCT_TAG,
+ // }
+ // )
+
+ const productTypes = useProductTypes(
+ {
+ id: ids,
+ limit: 10,
+ },
+ {
+ enabled: !!ids.length && type === TaxRateRuleReferenceType.PRODUCT_TYPE,
+ }
+ )
+
+ // const collections = useCollections(
+ // {
+ // id: ids,
+ // limit: 10,
+ // },
+ // {
+ // enabled:
+ // !!ids.length && type === TaxRateRuleReferenceType.PRODUCT_COLLECTION,
+ // }
+ // )
+
+ // const customerGroups = useCustomerGroups(
+ // {
+ // id: ids,
+ // limit: 10,
+ // },
+ // {
+ // enabled: !!ids.length && type === TaxRateRuleReferenceType.CUSTOMER_GROUP,
+ // }
+ // )
+
+ switch (type) {
+ case TaxRateRuleReferenceType.PRODUCT:
+ return {
+ labels: products.products?.map((product) => product.title),
+ isPending: products.isPending,
+ additional:
+ products.products && products.count
+ ? products.count - (products.products?.length ?? 0)
+ : 0,
+ isError: products.isError,
+ error: products.error,
+ }
+ // case TaxRateRuleReferenceType.PRODUCT_TAG:
+ // return {
+ // labels: tags.product_tags?.map((tag: any) => tag.value),
+ // isPending: tags.isPending,
+ // additional:
+ // tags.product_tags && tags.count
+ // ? tags.count - tags.product_tags.length
+ // : 0,
+ // isError: tags.isError,
+ // error: tags.error,
+ // }
+ case TaxRateRuleReferenceType.PRODUCT_TYPE:
+ return {
+ labels: productTypes.product_types?.map((type) => type.value),
+ isPending: productTypes.isPending,
+ additional:
+ productTypes.product_types && productTypes.count
+ ? productTypes.count - productTypes.product_types.length
+ : 0,
+ isError: productTypes.isError,
+ error: productTypes.error,
+ }
+ // case TaxRateRuleReferenceType.PRODUCT_COLLECTION:
+ // return {
+ // labels: collections.collections?.map((collection) => collection.title!),
+ // isPending: collections.isPending,
+ // additional:
+ // collections.collections && collections.count
+ // ? collections.count - collections.collections.length
+ // : 0,
+ // isError: collections.isError,
+ // error: collections.error,
+ // }
+ // case TaxRateRuleReferenceType.CUSTOMER_GROUP:
+ // return {
+ // labels: customerGroups.customer_groups?.map((group) => group.name!),
+ // isPending: customerGroups.isPending,
+ // additional:
+ // customerGroups.customer_groups && customerGroups.count
+ // ? customerGroups.count - customerGroups.customer_groups.length
+ // : 0,
+ // isError: customerGroups.isError,
+ // error: customerGroups.error,
+ // }
+ default:
+ return {
+ labels: undefined,
+ isPending: false,
+ additional: 0,
+ isError: false,
+ error: null,
+ }
+ }
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-table.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-table.tsx
new file mode 100644
index 000000000..dda0b3b3a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-override-table.tsx
@@ -0,0 +1,133 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button } from "@medusajs/ui"
+import { Table } from "@tanstack/react-table"
+import { ReactNode, useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import {
+ NoRecords,
+ NoResults,
+} from "@components/common/empty-table-content"
+import { TableFooterSkeleton } from "@components/common/skeleton"
+import { LocalizedTablePagination } from "@components/localization/localized-table-pagination"
+import { DataTableOrderBy } from "@components/table/data-table/data-table-order-by"
+import { DataTableSearch } from "@components/table/data-table/data-table-search"
+import { TaxOverrideCard } from "@pages/settings/tax-regions/_common/components/tax-override-card"
+
+type TaxOverrideTableProps = {
+ isPending: boolean
+ queryObject: Record<string, any>
+ count?: number
+ table: Table<HttpTypes.AdminTaxRate>
+ action: { label: string; to: string }
+ prefix?: string
+ children?: ReactNode
+}
+
+export const TaxOverrideTable = ({
+ isPending,
+ action,
+ count = 0,
+ table,
+ queryObject,
+ prefix,
+ children,
+}: TaxOverrideTableProps) => {
+ const { t } = useTranslation()
+
+ const orderByKeys = useMemo(
+ () => [
+ { key: "name", label: t("fields.name") },
+ { key: "rate", label: t("fields.rate") },
+ { key: "code", label: t("fields.code") },
+ { key: "updated_at", label: t("fields.updatedAt") },
+ { key: "created_at", label: t("fields.createdAt") },
+ ],
+ [t]
+ )
+
+ if (isPending) {
+ return (
+ <div className="flex flex-col divide-y">
+ {Array.from({ length: 3 }).map((_, index) => {
+ return (
+ <div
+ key={index}
+ className="bg-ui-bg-field-component h-[52px] w-full animate-pulse"
+ />
+ )
+ })}
+ <TableFooterSkeleton layout="fit" />
+ </div>
+ )
+ }
+
+ const noQuery =
+ Object.values(queryObject).filter((v) => Boolean(v)).length === 0
+ const noResults = !isPending && count === 0 && !noQuery
+ const noRecords = !isPending && count === 0 && noQuery
+
+ const { pageIndex, pageSize } = table.getState().pagination
+
+ return (
+ <div className="flex flex-col divide-y">
+ <div className="flex flex-col justify-between gap-x-4 gap-y-3 px-6 py-4 md:flex-row md:items-center">
+ <div>{children}</div>
+ <div className="flex items-center gap-x-2">
+ {!noRecords && (
+ <div className="flex w-full items-center gap-x-2 md:w-fit">
+ <div className="w-full md:w-fit">
+ <DataTableSearch prefix={prefix} />
+ </div>
+ <DataTableOrderBy
+ keys={orderByKeys}
+ prefix={prefix}
+ />
+ </div>
+ )}
+ <Link to={action.to}>
+ <Button size="small" variant="secondary">
+ {action.label}
+ </Button>
+ </Link>
+ </div>
+ </div>
+ {noResults && <NoResults />}
+ {noRecords && <NoRecords />}
+ {!noRecords && !noResults
+ ? !isPending
+ ? table.getRowModel().rows.map((row) => {
+ return (
+ <TaxOverrideCard
+ key={row.id}
+ taxRate={row.original}
+ role="row"
+ aria-rowindex={row.index}
+ />
+ )
+ })
+ : Array.from({ length: 3 }).map((_, index) => {
+ return (
+ <div
+ key={index}
+ className="bg-ui-bg-field-component h-[60px] w-full animate-pulse"
+ />
+ )
+ })
+ : null}
+ {!noRecords && (
+ <LocalizedTablePagination
+ prefix={prefix}
+ canNextPage={table.getCanNextPage()}
+ canPreviousPage={table.getCanPreviousPage()}
+ count={count}
+ nextPage={table.nextPage}
+ previousPage={table.previousPage}
+ pageCount={table.getPageCount()}
+ pageIndex={pageIndex}
+ pageSize={pageSize}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-rate-line.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-rate-line.tsx
new file mode 100644
index 000000000..72a67e599
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-rate-line.tsx
@@ -0,0 +1,82 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { HttpTypes } from "@medusajs/types"
+import { StatusBadge, Text } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { ActionMenu } from "@components/common/action-menu"
+import { formatPercentage } from "@lib/percentage-helpers"
+import { useDeleteTaxRateAction } from "../hooks"
+
+type TaxRateLineProps = {
+ taxRate: HttpTypes.AdminTaxRate
+ isSublevelTaxRate?: boolean
+}
+
+export const TaxRateLine = ({
+ taxRate,
+ isSublevelTaxRate,
+}: TaxRateLineProps) => {
+ const { t } = useTranslation()
+
+ return (
+ <div className="text-ui-fg-subtle grid grid-cols-[1fr_1fr_auto] items-center gap-4 px-6 py-4">
+ <div className="flex items-center gap-x-1.5">
+ <Text size="small" weight="plus" leading="compact">
+ {taxRate.name}
+ </Text>
+ {taxRate.code && (
+ <div className="flex items-center gap-x-1.5">
+ <Text size="small" leading="compact">
+ ·
+ </Text>
+ <Text size="small" leading="compact">
+ {taxRate.code}
+ </Text>
+ </div>
+ )}
+ </div>
+ <Text size="small" leading="compact">
+ {formatPercentage(taxRate.rate)}
+ </Text>
+ <div className="flex items-center justify-end gap-x-2">
+ {isSublevelTaxRate && (
+ <StatusBadge color={taxRate.is_combinable ? "green" : "grey"}>
+ {taxRate.is_combinable
+ ? t("taxRegions.fields.isCombinable.true")
+ : t("taxRegions.fields.isCombinable.false")}
+ </StatusBadge>
+ )}
+ <TaxRateActions taxRate={taxRate} />
+ </div>
+ </div>
+ )
+}
+
+const TaxRateActions = ({ taxRate }: { taxRate: HttpTypes.AdminTaxRate }) => {
+ const { t } = useTranslation()
+ const handleDelete = useDeleteTaxRateAction(taxRate)
+
+ return (
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ to: `tax-rates/${taxRate.id}/edit`,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ icon: <Trash />,
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-card.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-card.tsx
new file mode 100644
index 000000000..f8f8f9a3c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-card.tsx
@@ -0,0 +1,200 @@
+import { HttpTypes } from "@medusajs/types"
+import { Heading, Text, Tooltip, clx } from "@medusajs/ui"
+import ReactCountryFlag from "react-country-flag"
+
+import { ExclamationCircle, MapPin, Plus, Trash } from "@medusajs/icons"
+import { ComponentPropsWithoutRef, ReactNode } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { IconAvatar } from "@components/common/icon-avatar"
+import { getCountryByIso2 } from "@lib/data/countries"
+import {
+ getProvinceByIso2,
+ isProvinceInCountry,
+} from "@lib/data/country-states"
+import { useDeleteTaxRegionAction } from "../hooks"
+
+interface TaxRegionCardProps extends ComponentPropsWithoutRef<"div"> {
+ taxRegion: HttpTypes.AdminTaxRegion
+ type?: "header" | "list"
+ variant?: "country" | "province"
+ asLink?: boolean
+ badge?: ReactNode
+}
+
+export const TaxRegionCard = ({
+ taxRegion,
+ type = "list",
+ variant = "country",
+ asLink = true,
+ badge,
+}: TaxRegionCardProps) => {
+ const { t } = useTranslation()
+ const { id, country_code, province_code } = taxRegion
+
+ const country = getCountryByIso2(country_code)
+ const province = getProvinceByIso2(province_code)
+
+ let name = "N/A"
+ let misconfiguredSublevelTooltip: string | null = null
+
+ if (province || province_code) {
+ name = province ? province : province_code!.toUpperCase()
+ } else if (country || country_code) {
+ name = country ? country.display_name : country_code!.toUpperCase()
+ }
+
+ if (
+ country_code &&
+ province_code &&
+ !isProvinceInCountry(country_code, province_code)
+ ) {
+ name = province_code.toUpperCase()
+ misconfiguredSublevelTooltip = t(
+ "taxRegions.fields.sublevels.tooltips.notPartOfCountry",
+ {
+ country: country?.display_name,
+ province: province_code.toUpperCase(),
+ }
+ )
+ }
+
+ const showCreateDefaultTaxRate =
+ !taxRegion.tax_rates.filter((tr) => tr.is_default).length &&
+ type === "header"
+
+ const Component = (
+ <div
+ className={clx(
+ "group-data-[link=true]:hover:bg-ui-bg-base-hover transition-fg flex flex-col justify-between gap-y-4 px-6 md:flex-row md:items-center md:gap-y-0",
+ {
+ "py-4": type === "header",
+ "py-3": type === "list",
+ }
+ )}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-x-4">
+ <IconAvatar size={type === "list" ? "small" : "large"}>
+ {country_code && !province_code ? (
+ <div
+ className={clx(
+ "flex size-fit items-center justify-center overflow-hidden rounded-[1px]",
+ {
+ "rounded-sm": type === "header",
+ }
+ )}
+ >
+ <ReactCountryFlag
+ countryCode={country_code}
+ svg
+ style={
+ type === "list"
+ ? { width: "12px", height: "9px" }
+ : { width: "16px", height: "12px" }
+ }
+ aria-label={country?.display_name}
+ />
+ </div>
+ ) : (
+ <MapPin className="text-ui-fg-subtle" />
+ )}
+ </IconAvatar>
+ <div>
+ {type === "list" ? (
+ <Text size="small" weight="plus" leading="compact">
+ {name}
+ </Text>
+ ) : (
+ <Heading>{name}</Heading>
+ )}
+ </div>
+ </div>
+ <div className="flex size-fit items-center gap-x-2 md:hidden">
+ {misconfiguredSublevelTooltip && (
+ <Tooltip content={misconfiguredSublevelTooltip}>
+ <ExclamationCircle className="text-ui-tag-orange-icon" />
+ </Tooltip>
+ )}
+ {badge}
+ <TaxRegionCardActions
+ taxRegion={taxRegion}
+ showCreateDefaultTaxRate={showCreateDefaultTaxRate}
+ />
+ </div>
+ </div>
+
+ <div className="hidden size-fit items-center gap-x-2 md:flex">
+ {misconfiguredSublevelTooltip && (
+ <Tooltip content={misconfiguredSublevelTooltip}>
+ <ExclamationCircle className="text-ui-tag-orange-icon" />
+ </Tooltip>
+ )}
+ {badge}
+ <TaxRegionCardActions
+ taxRegion={taxRegion}
+ showCreateDefaultTaxRate={showCreateDefaultTaxRate}
+ />
+ </div>
+ </div>
+ )
+
+ if (asLink) {
+ return (
+ <Link
+ to={variant === "country" ? `${id}` : `provinces/${id}`}
+ data-link="true"
+ className="group block"
+ >
+ {Component}
+ </Link>
+ )
+ }
+
+ return Component
+}
+
+const TaxRegionCardActions = ({
+ taxRegion,
+ showCreateDefaultTaxRate,
+}: {
+ taxRegion: HttpTypes.AdminTaxRegion
+ showCreateDefaultTaxRate?: boolean
+}) => {
+ const { t } = useTranslation()
+
+ const to = taxRegion.parent_id
+ ? `/settings/tax-regions/${taxRegion.parent_id}`
+ : undefined
+ const handleDelete = useDeleteTaxRegionAction({ taxRegion, to })
+
+ return (
+ <ActionMenu
+ groups={[
+ ...(showCreateDefaultTaxRate
+ ? [
+ {
+ actions: [
+ {
+ icon: <Plus />,
+ label: t("taxRegions.fields.defaultTaxRate.action"),
+ to: `tax-rates/create`,
+ },
+ ],
+ },
+ ]
+ : []),
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: t("actions.delete"),
+ onClick: handleDelete,
+ },
+ ],
+ },
+ ]}
+ />
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-table.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-table.tsx
new file mode 100644
index 000000000..cf35dd234
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/components/tax-region-table.tsx
@@ -0,0 +1,133 @@
+import { HttpTypes } from "@medusajs/types"
+import { Button } from "@medusajs/ui"
+import { Table } from "@tanstack/react-table"
+import { ReactNode, useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { Link } from "react-router-dom"
+import {
+ NoRecords,
+ NoResults,
+} from "@components/common/empty-table-content"
+import { TableFooterSkeleton } from "@components/common/skeleton"
+import { LocalizedTablePagination } from "@components/localization/localized-table-pagination"
+import { DataTableOrderBy } from "@components/table/data-table/data-table-order-by"
+import { TaxRegionCard } from "@pages/settings/tax-regions/_common/components/tax-region-card"
+
+type TaxRegionTableProps = {
+ variant?: "country" | "province"
+ isPending: boolean
+ queryObject: Record<string, any>
+ count?: number
+ table: Table<HttpTypes.AdminTaxRegion>
+ action: { label: string; to: string }
+ prefix?: string
+ children?: ReactNode
+}
+
+export const TaxRegionTable = ({
+ variant = "country",
+ isPending,
+ action,
+ count = 0,
+ table,
+ queryObject,
+ prefix,
+ children,
+}: TaxRegionTableProps) => {
+ const { t } = useTranslation()
+
+ const orderByKeys = useMemo(
+ () => [
+ { key: "updated_at", label: t("fields.updatedAt") },
+ { key: "created_at", label: t("fields.createdAt") },
+ ],
+ [t]
+ )
+
+ if (isPending) {
+ return (
+ <div className="flex flex-col divide-y">
+ {Array.from({ length: 3 }).map((_, index) => {
+ return (
+ <div
+ key={index}
+ className="bg-ui-bg-field-component h-[52px] w-full animate-pulse"
+ />
+ )
+ })}
+ <TableFooterSkeleton layout="fit" />
+ </div>
+ )
+ }
+
+ const noQuery =
+ Object.values(queryObject).filter((v) => Boolean(v)).length === 0
+ const noResults = !isPending && count === 0 && !noQuery
+ const noRecords = !isPending && count === 0 && noQuery
+
+ const { pageIndex, pageSize } = table.getState().pagination
+
+ return (
+ <div className="flex flex-col divide-y">
+ <div className="flex flex-col justify-between gap-x-4 gap-y-3 px-6 py-4 md:flex-row md:items-center">
+ <div>{children}</div>
+ <div className="flex items-center gap-x-2">
+ {!noRecords && (
+ <div className="flex w-full items-center gap-x-2 md:w-fit">
+ {/* Re-enable when we allow searching tax regions by country name rather than country_code */}
+ {/* <div className="w-full md:w-fit">
+ <DataTableSearch prefix={prefix} />
+ </div> */}
+ <DataTableOrderBy
+ keys={orderByKeys}
+ prefix={prefix}
+ />
+ </div>
+ )}
+ <Link to={action.to}>
+ <Button size="small" variant="secondary">
+ {action.label}
+ </Button>
+ </Link>
+ </div>
+ </div>
+ {noResults && <NoResults />}
+ {noRecords && <NoRecords />}
+ {!noRecords && !noResults
+ ? !isPending
+ ? table.getRowModel().rows.map((row) => {
+ return (
+ <TaxRegionCard
+ variant={variant}
+ key={row.id}
+ taxRegion={row.original}
+ role="row"
+ aria-rowindex={row.index}
+ />
+ )
+ })
+ : Array.from({ length: 3 }).map((_, index) => {
+ return (
+ <div
+ key={index}
+ className="bg-ui-bg-field-component h-[60px] w-full animate-pulse"
+ />
+ )
+ })
+ : null}
+ {!noRecords && (
+ <LocalizedTablePagination
+ prefix={prefix}
+ canNextPage={table.getCanNextPage()}
+ canPreviousPage={table.getCanPreviousPage()}
+ count={count}
+ nextPage={table.nextPage}
+ previousPage={table.previousPage}
+ pageCount={table.getPageCount()}
+ pageIndex={pageIndex}
+ pageSize={pageSize}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/constants.ts b/packages/vendor/src/pages/settings/tax-regions/_common/constants.ts
new file mode 100644
index 000000000..7bdb5b0ef
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/constants.ts
@@ -0,0 +1,8 @@
+export enum TaxRateRuleReferenceType {
+ PRODUCT = "product",
+ PRODUCT_TYPE = "product_type",
+ SHIPPING_OPTION = "shipping_option",
+ PRODUCT_COLLECTION = "product_collection",
+ PRODUCT_TAG = "product_tag",
+ CUSTOMER_GROUP = "customer_group",
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/hooks.ts b/packages/vendor/src/pages/settings/tax-regions/_common/hooks.ts
new file mode 100644
index 000000000..687ce35fa
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/hooks.ts
@@ -0,0 +1,79 @@
+import { HttpTypes } from "@medusajs/types"
+import { toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { useDeleteTaxRate } from "@hooks/api/tax-rates"
+import { useDeleteTaxRegion } from "@hooks/api/tax-regions"
+
+export const useDeleteTaxRegionAction = ({
+ taxRegion,
+ to = "/settings/tax-regions",
+}: {
+ taxRegion: HttpTypes.AdminTaxRegion
+ to?: string
+}) => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteTaxRegion(taxRegion.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("taxRegions.delete.confirmation"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("taxRegions.delete.successToast"))
+
+ navigate(to, { replace: true })
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
+
+export const useDeleteTaxRateAction = (taxRate: HttpTypes.AdminTaxRate) => {
+ const { t } = useTranslation()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteTaxRate(taxRate.id)
+
+ const handleDelete = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("taxRegions.taxRates.delete.confirmation", {
+ name: taxRate.name,
+ }),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(t("taxRegions.taxRates.delete.successToast"))
+ },
+ onError: (e) => {
+ toast.error(e.message)
+ },
+ })
+ }
+
+ return handleDelete
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-override-table.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-override-table.tsx
new file mode 100644
index 000000000..0a346f72c
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-override-table.tsx
@@ -0,0 +1,92 @@
+import { HttpTypes } from "@medusajs/types"
+import {
+ OnChangeFn,
+ PaginationState,
+ getCoreRowModel,
+ getPaginationRowModel,
+ useReactTable,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useSearchParams } from "react-router-dom"
+
+type UseTaxRegionTableProps = {
+ data?: HttpTypes.AdminTaxRate[]
+ count?: number
+ pageSize?: number
+ prefix?: string
+}
+
+export const useTaxOverrideTable = ({
+ data = [],
+ count = 0,
+ pageSize: _pageSize = 10,
+ prefix,
+}: UseTaxRegionTableProps) => {
+ const [searchParams, setSearchParams] = useSearchParams()
+ const offsetKey = `${prefix ? `${prefix}_` : ""}offset`
+ const offset = searchParams.get(offsetKey)
+
+ const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
+ pageIndex: offset ? Math.ceil(Number(offset) / _pageSize) : 0,
+ pageSize: _pageSize,
+ })
+ const pagination = useMemo(
+ () => ({
+ pageIndex,
+ pageSize,
+ }),
+ [pageIndex, pageSize]
+ )
+
+ useEffect(() => {
+ const index = offset ? Math.ceil(Number(offset) / _pageSize) : 0
+
+ if (index === pageIndex) {
+ return
+ }
+
+ setPagination((prev) => ({
+ ...prev,
+ pageIndex: index,
+ }))
+ }, [offset, _pageSize, pageIndex])
+
+ const onPaginationChange = (
+ updater: (old: PaginationState) => PaginationState
+ ) => {
+ const state = updater(pagination)
+ const { pageIndex, pageSize } = state
+
+ setSearchParams((prev) => {
+ if (!pageIndex) {
+ prev.delete(offsetKey)
+ return prev
+ }
+
+ const newSearch = new URLSearchParams(prev)
+ newSearch.set(offsetKey, String(pageIndex * pageSize))
+
+ return newSearch
+ })
+
+ setPagination(state)
+ return state
+ }
+
+ const table = useReactTable({
+ data,
+ columns: [], // We don't actually want to render any columns
+ pageCount: Math.ceil(count / pageSize),
+ state: {
+ pagination,
+ },
+ getCoreRowModel: getCoreRowModel(),
+ onPaginationChange: onPaginationChange as OnChangeFn<PaginationState>,
+ getPaginationRowModel: getPaginationRowModel(),
+ manualPagination: true,
+ })
+
+ return {
+ table,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-region-table.tsx b/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-region-table.tsx
new file mode 100644
index 000000000..12c982762
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/hooks/use-tax-region-table.tsx
@@ -0,0 +1,92 @@
+import { HttpTypes } from "@medusajs/types"
+import {
+ OnChangeFn,
+ PaginationState,
+ getCoreRowModel,
+ getPaginationRowModel,
+ useReactTable,
+} from "@tanstack/react-table"
+import { useEffect, useMemo, useState } from "react"
+import { useSearchParams } from "react-router-dom"
+
+type UseTaxRegionTableProps = {
+ data?: HttpTypes.AdminTaxRegion[]
+ count?: number
+ pageSize?: number
+ prefix?: string
+}
+
+export const useTaxRegionTable = ({
+ data = [],
+ count = 0,
+ pageSize: _pageSize = 10,
+ prefix,
+}: UseTaxRegionTableProps) => {
+ const [searchParams, setSearchParams] = useSearchParams()
+ const offsetKey = `${prefix ? `${prefix}_` : ""}offset`
+ const offset = searchParams.get(offsetKey)
+
+ const [{ pageIndex, pageSize }, setPagination] = useState<PaginationState>({
+ pageIndex: offset ? Math.ceil(Number(offset) / _pageSize) : 0,
+ pageSize: _pageSize,
+ })
+ const pagination = useMemo(
+ () => ({
+ pageIndex,
+ pageSize,
+ }),
+ [pageIndex, pageSize]
+ )
+
+ useEffect(() => {
+ const index = offset ? Math.ceil(Number(offset) / _pageSize) : 0
+
+ if (index === pageIndex) {
+ return
+ }
+
+ setPagination((prev) => ({
+ ...prev,
+ pageIndex: index,
+ }))
+ }, [offset, _pageSize, pageIndex])
+
+ const onPaginationChange = (
+ updater: (old: PaginationState) => PaginationState
+ ) => {
+ const state = updater(pagination)
+ const { pageIndex, pageSize } = state
+
+ setSearchParams((prev) => {
+ if (!pageIndex) {
+ prev.delete(offsetKey)
+ return prev
+ }
+
+ const newSearch = new URLSearchParams(prev)
+ newSearch.set(offsetKey, String(pageIndex * pageSize))
+
+ return newSearch
+ })
+
+ setPagination(state)
+ return state
+ }
+
+ const table = useReactTable({
+ data,
+ columns: [], // We don't actually want to render any columns
+ pageCount: Math.ceil(count / pageSize),
+ state: {
+ pagination,
+ },
+ getCoreRowModel: getCoreRowModel(),
+ onPaginationChange: onPaginationChange as OnChangeFn<PaginationState>,
+ getPaginationRowModel: getPaginationRowModel(),
+ manualPagination: true,
+ })
+
+ return {
+ table,
+ }
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/schemas.ts b/packages/vendor/src/pages/settings/tax-regions/_common/schemas.ts
new file mode 100644
index 000000000..b705c70ee
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/schemas.ts
@@ -0,0 +1,16 @@
+import { z } from "zod"
+import { TaxRateRuleReferenceType } from "./constants"
+
+export const TaxRateRuleReferenceSchema = z.object({
+ value: z.string(),
+ label: z.string(),
+})
+
+export type TaxRateRuleReference = z.infer<typeof TaxRateRuleReferenceSchema>
+
+export const TaxRateRuleTargetSchema = z.object({
+ reference_type: z.nativeEnum(TaxRateRuleReferenceType),
+ references: z.array(TaxRateRuleReferenceSchema),
+})
+
+export type TaxRateRuleTarget = z.infer<typeof TaxRateRuleTargetSchema>
diff --git a/packages/vendor/src/pages/settings/tax-regions/_common/utils.ts b/packages/vendor/src/pages/settings/tax-regions/_common/utils.ts
new file mode 100644
index 000000000..7f0535e12
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_common/utils.ts
@@ -0,0 +1,12 @@
+import { HttpTypes } from "@medusajs/types"
+
+import { TaxRateRuleTarget } from "./schemas"
+
+export const createTaxRulePayload = (
+ target: TaxRateRuleTarget
+): HttpTypes.AdminCreateTaxRate["rules"] => {
+ return target.references.map((reference) => ({
+ reference: target.reference_type,
+ reference_id: reference.value,
+ }))
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/_components/tax-region-list-view.tsx b/packages/vendor/src/pages/settings/tax-regions/_components/tax-region-list-view.tsx
new file mode 100644
index 000000000..3809e28cd
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/_components/tax-region-list-view.tsx
@@ -0,0 +1,58 @@
+import { Container, Heading, Text } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useTranslation } from "react-i18next"
+
+import { useTaxRegions } from "@hooks/api/tax-regions"
+import { useTaxRegionTableQuery } from "@hooks/table/query/use-tax-region-table-query"
+import { TaxRegionTable } from "@pages/settings/tax-regions/_common/components/tax-region-table"
+import { useTaxRegionTable } from "@pages/settings/tax-regions/_common/hooks/use-tax-region-table"
+
+const PAGE_SIZE = 20
+
+export const TaxRegionListView = () => {
+ const { t } = useTranslation()
+
+ const { searchParams, raw } = useTaxRegionTableQuery({
+ pageSize: PAGE_SIZE,
+ })
+ const { tax_regions, count, isPending, isError, error } = useTaxRegions(
+ {
+ ...searchParams,
+ order: "country_code",
+ parent_id: "null",
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const { table } = useTaxRegionTable({
+ count,
+ data: tax_regions,
+ pageSize: PAGE_SIZE,
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <TaxRegionTable
+ action={{
+ to: "create",
+ label: t("actions.create"),
+ }}
+ isPending={isPending}
+ queryObject={raw}
+ table={table}
+ count={count}
+ >
+ <Heading>{t("taxes.domain")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle text-pretty">
+ {t("taxRegions.list.hint")}
+ </Text>
+ </TaxRegionTable>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/create/_components/tax-region-create-form.tsx b/packages/vendor/src/pages/settings/tax-regions/create/_components/tax-region-create-form.tsx
new file mode 100644
index 000000000..5ccb86871
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/create/_components/tax-region-create-form.tsx
@@ -0,0 +1,216 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { useForm } from "react-hook-form"
+import { z } from "zod"
+
+import { InformationCircleSolid } from "@medusajs/icons"
+import { Button, Heading, Input, Text, Tooltip, toast } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { Form } from "@components/common/form"
+import { CountrySelect } from "@components/inputs/country-select"
+import { PercentageInput } from "@components/inputs/percentage-input"
+import {
+ RouteFocusModal,
+ useRouteModal,
+} from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useCreateTaxRegion } from "@hooks/api"
+
+type TaxRegionCreateFormProps = {
+ parentId?: string
+}
+
+const TaxRegionCreateSchema = z.object({
+ name: z.string().optional(),
+ code: z.string().optional(),
+ rate: z.object({
+ float: z.number().optional(),
+ value: z.string().optional(),
+ }),
+ country_code: z.string().min(1),
+})
+
+export const TaxRegionCreateForm = ({ parentId }: TaxRegionCreateFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<z.infer<typeof TaxRegionCreateSchema>>({
+ defaultValues: {
+ name: "",
+ rate: {
+ value: "",
+ },
+ code: "",
+ country_code: "",
+ },
+ resolver: zodResolver(TaxRegionCreateSchema),
+ })
+
+ const { mutateAsync, isPending } = useCreateTaxRegion()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ const defaultRate = values.name
+ ? {
+ name: values.name,
+ rate:
+ values.rate?.value === ""
+ ? undefined
+ : parseFloat(values.rate.value!),
+ code: values.code || "",
+ }
+ : undefined
+
+ await mutateAsync(
+ {
+ country_code: values.country_code,
+ parent_id: parentId,
+ default_tax_rate: defaultRate,
+ },
+ {
+ onSuccess: ({ tax_region }) => {
+ toast.success(t("taxRegions.create.successToast"))
+ handleSuccess(`../${tax_region.id}`)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ }
+ )
+ })
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading className="capitalize">
+ {t("taxRegions.create.header")}
+ </Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("taxRegions.create.hint")}
+ </Text>
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="country_code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.country")}</Form.Label>
+ <Form.Control>
+ <CountrySelect {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ <div className="flex flex-col gap-4">
+ <div className="flex items-center gap-x-1">
+ <Heading level="h2" className="!txt-compact-small-plus">
+ {t("taxRegions.fields.defaultTaxRate.label")}
+ </Heading>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-muted"
+ >
+ ({t("fields.optional")})
+ </Text>
+ <Tooltip
+ content={t("taxRegions.fields.defaultTaxRate.tooltip")}
+ >
+ <InformationCircleSolid className="text-ui-fg-muted" />
+ </Tooltip>
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.name")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="rate"
+ render={({ field: { value, onChange, ...field } }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxRate")}
+ </Form.Label>
+ <Form.Control>
+ <PercentageInput
+ {...field}
+ value={value?.value}
+ onValueChange={(value, _name, values) =>
+ onChange({
+ value: value,
+ float: values?.float,
+ })
+ }
+ />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>
+ {t("taxRegions.fields.taxCode")}
+ </Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ <RouteFocusModal.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteFocusModal.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteFocusModal.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteFocusModal.Footer>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/tax-regions/create/index.tsx b/packages/vendor/src/pages/settings/tax-regions/create/index.tsx
new file mode 100644
index 000000000..8c79e93c6
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/create/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { TaxRegionCreateForm } from "./_components/tax-region-create-form"
+
+const TaxRegionCreate = () => {
+ return (
+ <RouteFocusModal>
+ <TaxRegionCreateForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = TaxRegionCreate
diff --git a/packages/vendor/src/pages/settings/tax-regions/index.tsx b/packages/vendor/src/pages/settings/tax-regions/index.tsx
new file mode 100644
index 000000000..a5146fda1
--- /dev/null
+++ b/packages/vendor/src/pages/settings/tax-regions/index.tsx
@@ -0,0 +1,21 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { TaxRegionListView } from "./_components/tax-region-list-view"
+
+const TaxRegionsList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ before: getWidgets("tax.list.before"),
+ after: getWidgets("tax.list.after"),
+ }}
+ hasOutlet
+ >
+ <TaxRegionListView />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = TaxRegionsList
diff --git a/packages/vendor/src/pages/settings/users/[id]/_components/user-general-section.tsx b/packages/vendor/src/pages/settings/users/[id]/_components/user-general-section.tsx
new file mode 100644
index 000000000..c74b146d4
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/_components/user-general-section.tsx
@@ -0,0 +1,88 @@
+import { PencilSquare, Trash } from "@medusajs/icons"
+import { Container, Heading, Text, toast, usePrompt } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+import { ActionMenu } from "@components/common/action-menu"
+import { useDeleteUser } from "@hooks/api/users"
+import { TeamMemberProps } from "@custom-types/user"
+
+type UserGeneralSectionProps = {
+ member: TeamMemberProps
+}
+
+export const UserGeneralSection = ({ member }: UserGeneralSectionProps) => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+ const prompt = usePrompt()
+
+ const { mutateAsync } = useDeleteUser(member.id)
+
+ const handleDeleteUser = async () => {
+ const res = await prompt({
+ title: t("general.areYouSure"),
+ description: t("users.deleteUserWarning", {
+ name: member.name ?? member.email,
+ }),
+ verificationText: member.name ?? member.email,
+ verificationInstruction: t("general.typeToConfirm"),
+ confirmText: t("actions.delete"),
+ cancelText: t("actions.cancel"),
+ })
+
+ if (!res) {
+ return
+ }
+
+ await mutateAsync(undefined, {
+ onSuccess: () => {
+ toast.success(
+ t("users.deleteUserSuccess", {
+ name: member.email,
+ })
+ )
+ navigate("..")
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <div className="flex items-center justify-between px-6 py-4">
+ <Heading>{member.email}</Heading>
+ <ActionMenu
+ groups={[
+ {
+ actions: [
+ {
+ label: t("actions.edit"),
+ to: "edit",
+ icon: <PencilSquare />,
+ },
+ ],
+ },
+ {
+ actions: [
+ {
+ label: t("actions.delete"),
+ onClick: handleDeleteUser,
+ icon: <Trash />,
+ },
+ ],
+ },
+ ]}
+ />
+ </div>
+ <div className="text-ui-fg-subtle grid grid-cols-2 items-center px-6 py-4">
+ <Text size="small" leading="compact" weight="plus">
+ {t("fields.name")}
+ </Text>
+ <Text size="small" leading="compact">
+ {member.name ?? "-"}
+ </Text>
+ </div>
+ </Container>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/users/[id]/breadcrumb.tsx b/packages/vendor/src/pages/settings/users/[id]/breadcrumb.tsx
new file mode 100644
index 000000000..3eafe4cc9
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/breadcrumb.tsx
@@ -0,0 +1,24 @@
+import { HttpTypes } from "@medusajs/types"
+import { UIMatch } from "react-router-dom"
+import { useUser } from "@hooks/api/users"
+
+type UserDetailBreadcrumbProps = UIMatch<HttpTypes.AdminUserResponse>
+
+export const UserDetailBreadcrumb = (props: UserDetailBreadcrumbProps) => {
+ const { id } = props.params || {}
+
+ const { user } = useUser(id!, undefined, {
+ initialData: props.data,
+ enabled: Boolean(id),
+ })
+
+ if (!user) {
+ return null
+ }
+
+ const name = [user.first_name, user.last_name].filter(Boolean).join(" ")
+
+ const display = name || user.email
+
+ return <span>{display}</span>
+}
diff --git a/packages/vendor/src/pages/settings/users/[id]/edit/_components/edit-user-form.tsx b/packages/vendor/src/pages/settings/users/[id]/edit/_components/edit-user-form.tsx
new file mode 100644
index 000000000..50241eb1a
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/edit/_components/edit-user-form.tsx
@@ -0,0 +1,80 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { Button, Input } from "@medusajs/ui"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteDrawer, useRouteModal } from "@components/modals"
+import { KeyboundForm } from "@components/utilities/keybound-form"
+import { useUpdateUser } from "@hooks/api/users"
+import { TeamMemberProps } from "@custom-types/user"
+
+type EditUserFormProps = {
+ member: TeamMemberProps
+}
+
+const EditUserFormSchema = zod.object({
+ name: zod.string().min(1),
+})
+
+export const EditUserForm = ({ member }: EditUserFormProps) => {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<zod.infer<typeof EditUserFormSchema>>({
+ defaultValues: {
+ name: member.name || "",
+ },
+ resolver: zodResolver(EditUserFormSchema),
+ })
+
+ const { mutateAsync, isPending } = useUpdateUser(member.id)
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ await mutateAsync(values, {
+ onSuccess: () => {
+ handleSuccess()
+ },
+ })
+ })
+
+ return (
+ <RouteDrawer.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex flex-1 flex-col overflow-hidden"
+ >
+ <RouteDrawer.Body className="flex max-w-full flex-1 flex-col gap-y-8 overflow-y-auto">
+ <Form.Field
+ control={form.control}
+ name="name"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>Name</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <div className="flex items-center justify-end gap-x-2">
+ <RouteDrawer.Close asChild>
+ <Button size="small" variant="secondary">
+ {t("actions.cancel")}
+ </Button>
+ </RouteDrawer.Close>
+ <Button size="small" type="submit" isLoading={isPending}>
+ {t("actions.save")}
+ </Button>
+ </div>
+ </RouteDrawer.Footer>
+ </KeyboundForm>
+ </RouteDrawer.Form>
+ )
+}
diff --git a/packages/vendor/src/pages/settings/users/[id]/edit/index.tsx b/packages/vendor/src/pages/settings/users/[id]/edit/index.tsx
new file mode 100644
index 000000000..9278a17b8
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/edit/index.tsx
@@ -0,0 +1,27 @@
+import { Heading } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+import { useParams } from "react-router-dom"
+import { RouteDrawer } from "@components/modals"
+import { useUser } from "@hooks/api/users"
+import { EditUserForm } from "./_components/edit-user-form"
+
+const UserEdit = () => {
+ const { t } = useTranslation()
+ const { id } = useParams()
+ const { member, isPending: isLoading, isError, error } = useUser(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <Heading>{t("users.editUser")}</Heading>
+ </RouteDrawer.Header>
+ {!isLoading && member && <EditUserForm member={member} />}
+ </RouteDrawer>
+ )
+}
+
+export const Component = UserEdit
diff --git a/packages/vendor/src/pages/settings/users/[id]/index.tsx b/packages/vendor/src/pages/settings/users/[id]/index.tsx
new file mode 100644
index 000000000..1faf285d4
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/index.tsx
@@ -0,0 +1,39 @@
+import { useParams } from "react-router-dom"
+
+import { useUser } from "@hooks/api/users"
+import { UserGeneralSection } from "./_components/user-general-section"
+
+import { SingleColumnPageSkeleton } from "@components/common/skeleton"
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+
+const UserDetail = () => {
+ const { id } = useParams()
+ const { member, isPending: isLoading, isError, error } = useUser(id!)
+
+ const { getWidgets } = useDashboardExtension()
+
+ if (isLoading || !member) {
+ return <SingleColumnPageSkeleton />
+ }
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <SingleColumnPage
+ data={member}
+ widgets={{
+ after: getWidgets("user.details.after"),
+ before: getWidgets("user.details.before"),
+ }}
+ >
+ <UserGeneralSection member={member} />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = UserDetail
+export { userLoader as loader } from "./loader"
+export { UserDetailBreadcrumb as Breadcrumb } from "./breadcrumb"
diff --git a/packages/vendor/src/pages/settings/users/[id]/loader.ts b/packages/vendor/src/pages/settings/users/[id]/loader.ts
new file mode 100644
index 000000000..6847477ed
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/loader.ts
@@ -0,0 +1,17 @@
+import { LoaderFunctionArgs } from "react-router-dom"
+
+import { productsQueryKeys } from "@hooks/api/products"
+import { fetchQuery } from "@lib/client"
+import { queryClient } from "@lib/query-client"
+
+const userDetailQuery = (id: string) => ({
+ queryKey: productsQueryKeys.detail(id),
+ queryFn: async () => fetchQuery(`/vendor/members/${id}`, { method: "GET" }),
+})
+
+export const userLoader = async ({ params }: LoaderFunctionArgs) => {
+ const id = params.id
+ const query = userDetailQuery(id!)
+
+ return queryClient.ensureQueryData(query)
+}
diff --git a/packages/vendor/src/pages/settings/users/[id]/metadata/index.tsx b/packages/vendor/src/pages/settings/users/[id]/metadata/index.tsx
new file mode 100644
index 000000000..e798804b1
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/[id]/metadata/index.tsx
@@ -0,0 +1,39 @@
+import { useParams } from "react-router-dom"
+import { MetadataForm } from "@components/forms/metadata-form"
+import { RouteDrawer } from "@components/modals"
+import { useUpdateUser, useUser } from "@hooks/api"
+type FetchError = Error & { status?: number }
+
+const UserMetadata = () => {
+ const { id } = useParams()
+
+ const { user, isPending, isError, error } = useUser(id!)
+ const { mutateAsync, isPending: isMutating } = useUpdateUser(id!)
+
+ if (isError) {
+ throw error
+ }
+
+ const handleUpdate = async (
+ params: { metadata?: Record<string, any> | null },
+ callbacks: { onSuccess: () => void; onError: (error: FetchError) => void }
+ ) => {
+ return mutateAsync(
+ { metadata: params.metadata ?? undefined },
+ callbacks
+ )
+ }
+
+ return (
+ <RouteDrawer>
+ <MetadataForm
+ isPending={isPending}
+ isMutating={isMutating}
+ hook={handleUpdate}
+ metadata={user?.metadata}
+ />
+ </RouteDrawer>
+ )
+}
+
+export const Component = UserMetadata
diff --git a/packages/vendor/src/pages/settings/users/_components/user-list-table.tsx b/packages/vendor/src/pages/settings/users/_components/user-list-table.tsx
new file mode 100644
index 000000000..ba876d0d4
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/_components/user-list-table.tsx
@@ -0,0 +1,131 @@
+import { Container, createDataTableColumnHelper } from "@medusajs/ui"
+import { keepPreviousData } from "@tanstack/react-query"
+import { useMemo } from "react"
+import { useTranslation } from "react-i18next"
+import { useNavigate } from "react-router-dom"
+
+import { PencilSquare } from "@medusajs/icons"
+import { DataTable } from "@components/data-table"
+// import { useDataTableDateFilters } from "@components/data-table/helpers/general/use-data-table-date-filters"
+import { useUsers } from "@hooks/api/users"
+import { useQueryParams } from "@hooks/use-query-params"
+import { TeamMemberProps } from "@custom-types/user"
+
+const PAGE_SIZE = 20
+
+export const UserListTable = () => {
+ const { q, order, offset } = useQueryParams(["q", "order", "offset"])
+ const { members, isPending, isError, error } = useUsers(
+ {
+ limit: 9999,
+ order,
+ },
+ {
+ placeholderData: keepPreviousData,
+ }
+ )
+
+ const processedMembers = useMemo(() => {
+ if (q) {
+ return members?.filter((member) =>
+ member.email.toLowerCase().includes(q.toLowerCase())
+ )
+ }
+ return members
+ }, [members, q])
+
+ const count = processedMembers?.length ?? 0
+ const membersOffset = offset ? parseInt(offset) : 0
+
+ const columns = useColumns()
+ // const filters = useFilters()
+
+ const { t } = useTranslation()
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <Container className="divide-y p-0">
+ <DataTable
+ data={
+ processedMembers?.slice(membersOffset, membersOffset + PAGE_SIZE) ??
+ []
+ }
+ columns={columns}
+ // filters={filters}
+ getRowId={(row) => row.id}
+ rowCount={count}
+ pageSize={PAGE_SIZE}
+ heading={t("users.domain")}
+ rowHref={(row) => `${row.id}`}
+ isLoading={isPending}
+ action={{
+ label: t("users.invite"),
+ to: "invite",
+ }}
+ emptyState={{
+ empty: {
+ heading: t("users.list.empty.heading"),
+ description: t("users.list.empty.description"),
+ },
+ filtered: {
+ heading: t("users.list.filtered.heading"),
+ description: t("users.list.filtered.description"),
+ },
+ }}
+ />
+ </Container>
+ )
+}
+
+const columnHelper = createDataTableColumnHelper<TeamMemberProps>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+ const navigate = useNavigate()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("email", {
+ header: "Email",
+ cell: ({ row }) => {
+ return row.original.email
+ },
+ enableSorting: true,
+ sortAscLabel: t("filters.sorting.alphabeticallyAsc"),
+ sortDescLabel: t("filters.sorting.alphabeticallyDesc"),
+ }),
+ columnHelper.accessor("name", {
+ header: "Name",
+ cell: ({ row }) => {
+ return row.original.name || "-"
+ },
+ enableSorting: true,
+ sortAscLabel: t("filters.sorting.alphabeticallyAsc"),
+ sortDescLabel: t("filters.sorting.alphabeticallyDesc"),
+ }),
+ columnHelper.action({
+ actions: [
+ {
+ label: t("actions.edit"),
+ icon: <PencilSquare />,
+ onClick: (ctx) => {
+ navigate(`${ctx.row.original.id}/edit`)
+ },
+ },
+ ],
+ }),
+ ],
+ [t, navigate]
+ )
+}
+
+// const useFilters = () => {
+// const dateFilters = useDataTableDateFilters()
+
+// return useMemo(() => {
+// return dateFilters
+// }, [dateFilters])
+// }
diff --git a/packages/vendor/src/pages/settings/users/index.tsx b/packages/vendor/src/pages/settings/users/index.tsx
new file mode 100644
index 000000000..b8c9d24b2
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/index.tsx
@@ -0,0 +1,20 @@
+import { SingleColumnPage } from "@components/layout/pages"
+import { useDashboardExtension } from "@/extensions"
+import { UserListTable } from "./_components/user-list-table"
+
+const UserList = () => {
+ const { getWidgets } = useDashboardExtension()
+
+ return (
+ <SingleColumnPage
+ widgets={{
+ after: getWidgets("user.list.after"),
+ before: getWidgets("user.list.before"),
+ }}
+ >
+ <UserListTable />
+ </SingleColumnPage>
+ )
+}
+
+export const Component = UserList
diff --git a/packages/vendor/src/pages/settings/users/invite/_components/invite-user-form.tsx b/packages/vendor/src/pages/settings/users/invite/_components/invite-user-form.tsx
new file mode 100644
index 000000000..9f54f63ce
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/invite/_components/invite-user-form.tsx
@@ -0,0 +1,263 @@
+import { zodResolver } from "@hookform/resolvers/zod"
+import { HttpTypes } from "@medusajs/types"
+import {
+ Alert,
+ Button,
+ Container,
+ Heading,
+ Input,
+ StatusBadge,
+ Text,
+ Tooltip,
+} from "@medusajs/ui"
+import { createColumnHelper } from "@tanstack/react-table"
+// import copy from 'copy-to-clipboard';
+import { format } from "date-fns"
+import { useMemo } from "react"
+import { useForm } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import * as zod from "zod"
+
+import { Form } from "@components/common/form"
+import { RouteFocusModal } from "@components/modals/index.ts"
+import { _DataTable } from "@components/table/data-table"
+import { KeyboundForm } from "@components/utilities/keybound-form/keybound-form.tsx"
+import { useCreateInvite, useInvites } from "@hooks/api/invites"
+import { useUserInviteTableQuery } from "@hooks/table/query/use-user-invite-table-query"
+import { useDataTable } from "@hooks/use-data-table"
+import { isFetchError } from "@lib/is-fetch-error"
+
+const InviteUserSchema = zod.object({
+ email: zod.string().email(),
+})
+
+const PAGE_SIZE = 10
+const PREFIX = "usr_invite"
+
+export const InviteUserForm = () => {
+ const { t } = useTranslation()
+
+ const form = useForm<zod.infer<typeof InviteUserSchema>>({
+ defaultValues: {
+ email: "",
+ },
+ resolver: zodResolver(InviteUserSchema),
+ })
+
+ const { raw, searchParams } = useUserInviteTableQuery({
+ prefix: PREFIX,
+ pageSize: PAGE_SIZE,
+ })
+
+ const {
+ invites,
+ isPending: isLoading,
+ isError,
+ error,
+ } = useInvites({
+ limit: 9999,
+ order: searchParams.order,
+ })
+
+ const processedInvites = useMemo(() => {
+ if (searchParams?.q) {
+ return invites?.filter((invite) =>
+ invite.email
+ .toLowerCase()
+ .includes(searchParams?.q?.toLowerCase() ?? "")
+ )
+ }
+ return invites
+ }, [invites, searchParams])
+
+ const offset = searchParams.offset ?? 0
+
+ const columns = useColumns()
+
+ const { table } = useDataTable({
+ data: processedInvites?.slice(offset, offset + PAGE_SIZE) ?? [],
+ columns,
+ count: processedInvites?.length ?? 0,
+ enablePagination: true,
+ getRowId: (row) => row.id,
+ pageSize: PAGE_SIZE,
+ prefix: PREFIX,
+ })
+
+ const { mutateAsync, isPending } = useCreateInvite()
+
+ const handleSubmit = form.handleSubmit(async (values) => {
+ try {
+ await mutateAsync({ email: values.email })
+ form.reset()
+ } catch (error) {
+ if (isFetchError(error) && error.status === 400) {
+ form.setError("root", {
+ type: "manual",
+ message: error.message,
+ })
+ return
+ }
+ }
+ })
+
+ if (isError) {
+ throw error
+ }
+
+ return (
+ <RouteFocusModal.Form form={form}>
+ <KeyboundForm
+ onSubmit={handleSubmit}
+ className="flex h-full flex-col overflow-hidden"
+ >
+ <RouteFocusModal.Header />
+ <RouteFocusModal.Body className="flex flex-1 flex-col overflow-hidden">
+ <div className="flex flex-1 flex-col items-center overflow-y-auto">
+ <div className="flex w-full max-w-[720px] flex-col gap-y-8 px-2 py-16">
+ <div>
+ <Heading>{t("users.inviteUser")}</Heading>
+ <Text size="small" className="text-ui-fg-subtle">
+ {t("users.inviteUserHint")}
+ </Text>
+ </div>
+
+ {form.formState.errors.root && (
+ <Alert
+ variant="error"
+ dismissible={false}
+ className="text-balance"
+ >
+ {form.formState.errors.root.message}
+ </Alert>
+ )}
+
+ <div className="flex flex-col gap-y-4">
+ <div className="grid grid-cols-2 gap-4">
+ <Form.Field
+ control={form.control}
+ name="email"
+ render={({ field }) => {
+ return (
+ <Form.Item>
+ <Form.Label>{t("fields.email")}</Form.Label>
+ <Form.Control>
+ <Input {...field} />
+ </Form.Control>
+ <Form.ErrorMessage />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ <div className="flex items-center justify-end">
+ <Button
+ size="small"
+ variant="secondary"
+ type="submit"
+ isLoading={isPending}
+ >
+ {t("users.sendInvite")}
+ </Button>
+ </div>
+ </div>
+ <div className="flex flex-col gap-y-4">
+ <Heading level="h2">{t("users.pendingInvites")}</Heading>
+ <Container className="overflow-hidden p-0">
+ <_DataTable
+ table={table}
+ columns={columns}
+ count={processedInvites?.length ?? 0}
+ pageSize={PAGE_SIZE}
+ pagination
+ search="autofocus"
+ isLoading={isLoading}
+ queryObject={raw}
+ prefix={PREFIX}
+ orderBy={[
+ {
+ key: "email",
+ label: t("fields.email"),
+ },
+ {
+ key: "created_at",
+ label: t("fields.createdAt"),
+ },
+ {
+ key: "updated_at",
+ label: t("fields.updatedAt"),
+ },
+ ]}
+ />
+ </Container>
+ </div>
+ </div>
+ </div>
+ </RouteFocusModal.Body>
+ </KeyboundForm>
+ </RouteFocusModal.Form>
+ )
+}
+
+const columnHelper = createColumnHelper<HttpTypes.AdminInvite>()
+
+const useColumns = () => {
+ const { t } = useTranslation()
+
+ return useMemo(
+ () => [
+ columnHelper.accessor("email", {
+ header: t("fields.email"),
+ cell: ({ getValue }) => {
+ return getValue()
+ },
+ }),
+ columnHelper.accessor("accepted", {
+ header: t("fields.status"),
+ cell: ({ getValue, row }) => {
+ const accepted = getValue()
+
+ const expired = new Date(row.original.expires_at) < new Date()
+ if (accepted) {
+ return (
+ <Tooltip
+ content={t("users.acceptedOnDate", {
+ date: format(
+ new Date(row.original.updated_at),
+ "dd MMM, yyyy"
+ ),
+ })}
+ >
+ <StatusBadge color="green">
+ {t("users.inviteStatus.accepted")}
+ </StatusBadge>
+ </Tooltip>
+ )
+ }
+ if (expired) {
+ return (
+ <Tooltip
+ content={t("users.expiredOnDate", {
+ date: format(
+ new Date(row.original.expires_at),
+ "dd MMM, yyyy"
+ ),
+ })}
+ >
+ <StatusBadge color="red">
+ {t("users.inviteStatus.expired")}
+ </StatusBadge>
+ </Tooltip>
+ )
+ }
+ return (
+ <StatusBadge color="orange">
+ {t("users.inviteStatus.pending")}
+ </StatusBadge>
+ )
+ },
+ }),
+ ],
+ [t]
+ )
+}
diff --git a/packages/vendor/src/pages/settings/users/invite/index.tsx b/packages/vendor/src/pages/settings/users/invite/index.tsx
new file mode 100644
index 000000000..c3968f7a4
--- /dev/null
+++ b/packages/vendor/src/pages/settings/users/invite/index.tsx
@@ -0,0 +1,12 @@
+import { RouteFocusModal } from "@components/modals"
+import { InviteUserForm } from "./_components/invite-user-form"
+
+const UserInvite = () => {
+ return (
+ <RouteFocusModal>
+ <InviteUserForm />
+ </RouteFocusModal>
+ )
+}
+
+export const Component = UserInvite
diff --git a/packages/vendor/src/utils/images-conventer.ts b/packages/vendor/src/utils/images-conventer.ts
new file mode 100644
index 000000000..1323c16ca
--- /dev/null
+++ b/packages/vendor/src/utils/images-conventer.ts
@@ -0,0 +1,15 @@
+import { backendUrl } from "../lib/client"
+
+export default function imagesConverter(images: string) {
+ const isLocalhost =
+ images.startsWith("http://localhost:9000") ||
+ images.startsWith("https://localhost:9000")
+
+ if (isLocalhost) {
+ return images
+ .replace("http://localhost:9000", backendUrl)
+ .replace("https://localhost:9000", backendUrl)
+ }
+
+ return images
+}
diff --git a/packages/vendor/tsconfig.json b/packages/vendor/tsconfig.json
index 6300299de..498d49468 100644
--- a/packages/vendor/tsconfig.json
+++ b/packages/vendor/tsconfig.json
@@ -18,14 +18,21 @@
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
- "noFallthroughCasesInSwitch": true
+ "noFallthroughCasesInSwitch": true,
+ "baseUrl": ".",
+ "paths": {
+ "@/*": ["src/*"],
+ "@components/*": ["src/components/*"],
+ "@hooks/*": ["src/hooks/*"],
+ "@lib/*": ["src/lib/*"],
+ "@pages/*": ["src/pages/*"],
+ "@providers/*": ["src/providers/*"],
+ "@assets/*": ["src/assets/*"]
+ }
},
"include": [
"src"
],
"composite": false,
- "skipLibCheck": true,
- "module": "ESNext",
- "moduleResolution": "bundler",
"allowSyntheticDefaultImports": true
}
\ No newline at end of file
diff --git a/packages/vendor/tsup.config.ts b/packages/vendor/tsup.config.ts
index 6d0940714..abfd420be 100644
--- a/packages/vendor/tsup.config.ts
+++ b/packages/vendor/tsup.config.ts
@@ -1,9 +1,25 @@
import { defineConfig } from "tsup";
+import { resolve } from "path";
+import { fileURLToPath } from "url";
+import { dirname } from "path";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
export default defineConfig({
clean: true,
dts: true,
entry: ["src/index.ts", "src/index.css"],
format: ["esm"],
- external: ["react", "react-dom", "virtual:mercur/config"],
+ external: ["react", "react-dom", "virtual:mercur/config", "virtual:medusa/links", "@medusajs/admin-shared", "virtual:mercur/routes", "virtual:mercur/components"],
+ esbuildOptions(options) {
+ options.alias = {
+ "@": resolve(__dirname, "src"),
+ "@components": resolve(__dirname, "src/components"),
+ "@hooks": resolve(__dirname, "src/hooks"),
+ "@lib": resolve(__dirname, "src/lib"),
+ "@pages": resolve(__dirname, "src/pages"),
+ "@providers": resolve(__dirname, "src/providers"),
+ "@assets": resolve(__dirname, "src/assets"),
+ };
+ },
});