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.

fix(admin): detail pages and form regressions (#762)

Jakub Sieradzki3055b34506be
diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.json
index 6d29d8333..2e254fbf0 100644
--- a/packages/admin/src/i18n/translations/en.json
+++ b/packages/admin/src/i18n/translations/en.json
@@ -2112,6 +2112,7 @@
"existing": {
"title": "Existing Campaign",
"description": "Add promotion to an existing campaign.",
+ "currencyHint": "Campaigns with a budget currency are disabled because this promotion has no currency set. Set a currency on the promotion first.",
"placeholder": {
"title": "No existing campaigns",
"desc": "You can create one to track multiple promotions and set budget limits."
diff --git a/packages/admin/src/index.ts b/packages/admin/src/index.ts
index c4f66c82e..f81c4e75e 100644
--- a/packages/admin/src/index.ts
+++ b/packages/admin/src/index.ts
@@ -3,6 +3,18 @@ export { default } from './app'
// Reusable form components
export { TabbedForm, useTabbedForm, defineTabMeta } from './components/tabbed-form'
export type { TabDefinition } from './components/tabbed-form'
+export { Form } from './components/common/form'
+export { SwitchBox } from './components/common/switch-box'
+export { FileUpload } from './components/common/file-upload'
+export type { FileType, FileUploadProps } from './components/common/file-upload'
+export { ChipInput } from './components/inputs/chip-input'
-// Layout components
+// Table components
+export { _DataTable as DataTable } from './components/table/data-table'
+export type { Filter } from './components/table/data-table'
+export { useDataTable } from './hooks/use-data-table'
+
+// Page layout components
+export { SingleColumnPage } from './components/layout/pages/single-column-page'
+export { ActionMenu } from './components/common/action-menu'
export { Notifications } from './components/layout/notifications/notifications'
\ No newline at end of file
diff --git a/packages/admin/src/lib/promotions.ts b/packages/admin/src/lib/promotions.ts
index bbf98a80c..001c8462b 100644
--- a/packages/admin/src/lib/promotions.ts
+++ b/packages/admin/src/lib/promotions.ts
@@ -10,8 +10,8 @@ export enum PromotionStatus {
}
export type StatusColors = "grey" | "orange" | "green" | "red" | "grey"
-export type StatusMap = Record<string, [StatusColors, string]>
-export const promotionStatusMap: StatusMap = {
+
+const getPromotionStatusMap = (): Record<string, [StatusColors, string]> => ({
[PromotionStatus.ACTIVE]: ["green", i18n.t("statuses.active")],
[PromotionStatus.INACTIVE]: ["red", i18n.t("statuses.inactive")],
[PromotionStatus.DRAFT]: ["grey", i18n.t("statuses.draft")],
@@ -23,18 +23,19 @@ export const promotionStatusMap: StatusMap = {
"red",
`${i18n.t("promotions.fields.campaign")} ${i18n.t("statuses.expired")?.toLowerCase()}`,
],
-}
+})
export const getPromotionStatus = (promotion: HttpTypes.AdminPromotion) => {
const date = new Date()
const campaign = promotion.campaign
+ const statusMap = getPromotionStatusMap()
if (!campaign) {
- return promotionStatusMap[promotion.status!.toUpperCase()]
+ return statusMap[promotion.status!.toUpperCase()]
}
if (campaign.starts_at && new Date(campaign.starts_at!) > date) {
- return promotionStatusMap[PromotionStatus.SCHEDULED]
+ return statusMap[PromotionStatus.SCHEDULED]
}
const campaignBudget = campaign.budget
@@ -44,8 +45,8 @@ export const getPromotionStatus = (promotion: HttpTypes.AdminPromotion) => {
campaignBudget.used! > campaignBudget.limit!
if ((campaign.ends_at && new Date(campaign.ends_at) < date) || overBudget) {
- return promotionStatusMap[PromotionStatus.EXPIRED]
+ return statusMap[PromotionStatus.EXPIRED]
}
- return promotionStatusMap[promotion.status!.toUpperCase()]
+ return statusMap[promotion.status!.toUpperCase()]
}
diff --git a/packages/admin/src/pages/categories/category-create/category-create.tsx b/packages/admin/src/pages/categories/category-create/category-create.tsx
index 2e87050a5..875f6b113 100644
--- a/packages/admin/src/pages/categories/category-create/category-create.tsx
+++ b/packages/admin/src/pages/categories/category-create/category-create.tsx
@@ -1,16 +1,40 @@
+import { Children, ReactNode } from "react"
import { useSearchParams } from "react-router-dom"
import { RouteFocusModal } from "../../../components/modals"
-import { CreateCategoryForm } from "./components/create-category-form/create-category-form"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
+import {
+ CreateCategoryForm,
+ CreateCategorySchemaType,
+} from "./components/create-category-form"
+import { CreateCategoryDetails } from "./components/create-category-form/create-category-details"
+import { CreateCategoryNesting } from "./components/create-category-form/create-category-nesting"
+import { CreateCategorySchema } from "./components/create-category-form/schema"
-export const CategoryCreate = () => {
+const Root = ({ children }: { children?: ReactNode }) => {
const [searchParams] = useSearchParams()
-
const parentCategoryId = searchParams.get("parent_category_id")
return (
<RouteFocusModal>
- <CreateCategoryForm parentCategoryId={parentCategoryId} />
+ {Children.count(children) > 0 ? (
+ children
+ ) : (
+ <CreateCategoryForm parentCategoryId={parentCategoryId} />
+ )}
</RouteFocusModal>
)
}
+
+export const CategoryCreatePage = Object.assign(Root, {
+ Form: CreateCategoryForm,
+ DetailsTab: CreateCategoryDetails,
+ OrganizeTab: CreateCategoryNesting,
+ Tab: TabbedForm.Tab,
+})
+
+export type { CreateCategorySchemaType }
+export { CreateCategorySchema }
+
+// Keep backward-compatible named export for route `Component`
+export const CategoryCreate = Root
diff --git a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-details.tsx b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-details.tsx
index 1cb902aea..373d25b61 100644
--- a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-details.tsx
+++ b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-details.tsx
@@ -1,19 +1,18 @@
import { Heading, Input, Select, Text, 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 { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
import { CreateCategorySchema } from "./schema"
-type CreateCategoryDetailsProps = {
- form: UseFormReturn<CreateCategorySchema>
-}
-
-export const CreateCategoryDetails = ({ form }: CreateCategoryDetailsProps) => {
+const Root = () => {
const { t } = useTranslation()
+ const form = useTabbedForm<CreateCategorySchema>()
const direction = useDocumentDirection()
+
return (
<div className="flex flex-col items-center p-16">
<div className="flex w-full max-w-[720px] flex-col gap-y-8" data-testid="category-create-form-content">
@@ -144,3 +143,11 @@ export const CreateCategoryDetails = ({ form }: CreateCategoryDetailsProps) => {
</div>
)
}
+
+Root._tabMeta = defineTabMeta<CreateCategorySchema>({
+ id: "details",
+ labelKey: "categories.create.tabs.details",
+ validationFields: ["name", "handle", "description", "status", "visibility"],
+})
+
+export const CreateCategoryDetails = Root
diff --git a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-form.tsx b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-form.tsx
index 14468c0f3..0d2b29ef6 100644
--- a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-form.tsx
+++ b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-form.tsx
@@ -1,41 +1,37 @@
import { zodResolver } from "@hookform/resolvers/zod"
-import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
-import { useForm } from "react-hook-form"
+import { toast } from "@medusajs/ui"
+import { Children, ReactNode, useMemo } from "react"
+import { DeepPartial, useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
+import { z } from "zod"
-import { useState } from "react"
-import {
- RouteFocusModal,
- useRouteModal,
-} from "../../../../../components/modals"
-import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
+import { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
import { useCreateProductCategory } from "../../../../../hooks/api/categories"
import { transformNullableFormData } from "../../../../../lib/form-helpers"
import { CreateCategoryDetails } from "./create-category-details"
import { CreateCategoryNesting } from "./create-category-nesting"
-import { CreateCategoryDetailsSchema, CreateCategorySchema } from "./schema"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
+import { CreateCategorySchema } from "./schema"
+
+export type CreateCategorySchemaType = z.infer<typeof CreateCategorySchema>
type CreateCategoryFormProps = {
parentCategoryId: string | null
-}
-
-enum Tab {
- DETAILS = "details",
- ORGANIZE = "organize",
+ children?: ReactNode
+ schema?: z.ZodType<CreateCategorySchemaType>
+ defaultValues?: DeepPartial<CreateCategorySchemaType>
}
export const CreateCategoryForm = ({
parentCategoryId,
+ children,
+ schema,
+ defaultValues: extraDefaults,
}: CreateCategoryFormProps) => {
const { t } = useTranslation()
const { handleSuccess } = useRouteModal()
- const direction = useDocumentDirection()
- const [activeTab, setActiveTab] = useState<Tab>(Tab.DETAILS)
- const [validDetails, setValidDetails] = useState(false)
- const [shouldFreeze, setShouldFreeze] = useState(false)
- const form = useForm<CreateCategorySchema>({
+ const form = useForm<CreateCategorySchemaType>({
defaultValues: {
name: "",
description: "",
@@ -44,49 +40,18 @@ export const CreateCategoryForm = ({
visibility: "public",
rank: parentCategoryId ? 0 : null,
parent_category_id: parentCategoryId,
- },
- resolver: zodResolver(CreateCategorySchema),
+ ...extraDefaults,
+ } as CreateCategorySchemaType,
+ resolver: zodResolver(schema ?? CreateCategorySchema),
})
- const handleTabChange = (tab: Tab) => {
- if (tab === Tab.ORGANIZE) {
- const { name, handle, description, status, visibility } = form.getValues()
-
- const result = CreateCategoryDetailsSchema.safeParse({
- name,
- handle,
- description,
- status,
- visibility,
- })
-
- if (!result.success) {
- result.error.errors.forEach((error) => {
- form.setError(error.path.join(".") as keyof CreateCategorySchema, {
- type: "manual",
- message: error.message,
- })
- })
-
- return
- }
-
- form.clearErrors()
- setValidDetails(true)
- }
-
- setActiveTab(tab)
- }
-
const { mutateAsync, isPending } = useCreateProductCategory()
- const handleSubmit = form.handleSubmit((data) => {
+ const handleSubmit = form.handleSubmit(async (data) => {
const { visibility, status, parent_category_id, rank, name, ...rest } = data
const parsedData = transformNullableFormData(rest, false)
- setShouldFreeze(true)
-
- mutateAsync(
+ await mutateAsync(
{
name: name,
...parsedData,
@@ -107,108 +72,28 @@ export const CreateCategoryForm = ({
},
onError: (error) => {
toast.error(error.message)
- setShouldFreeze(false)
},
}
)
})
- const nestingStatus: ProgressStatus =
- form.getFieldState("parent_category_id")?.isDirty ||
- form.getFieldState("rank")?.isDirty ||
- activeTab === Tab.ORGANIZE
- ? "in-progress"
- : "not-started"
+ const defaultTabs = useMemo(
+ () => [
+ <CreateCategoryDetails key="details" />,
+ <CreateCategoryNesting key="organize" />,
+ ],
+ []
+ )
- const detailsStatus: ProgressStatus = validDetails
- ? "completed"
- : "in-progress"
+ const hasCustomChildren = Children.count(children) > 0
return (
- <RouteFocusModal.Form form={form} data-testid="category-create-form">
- <KeyboundForm
- onSubmit={handleSubmit}
- className="flex size-full flex-col overflow-hidden"
- >
- <ProgressTabs
- dir={direction}value={activeTab}
- onValueChange={(tab) => handleTabChange(tab as Tab)}
- className="flex size-full flex-col"
- >
- <RouteFocusModal.Header data-testid="category-create-form-header">
- <div className="flex w-full items-center justify-between">
- <div className="-my-2 w-full max-w-[400px] border-l">
- <ProgressTabs.List className="grid w-full grid-cols-2" data-testid="category-create-form-tabs-list">
- <ProgressTabs.Trigger
- value={Tab.DETAILS}
- status={detailsStatus}
- className="w-full min-w-0 overflow-hidden"
- data-testid="category-create-form-tab-details"
- >
- <span className="truncate">
- {t("categories.create.tabs.details")}
- </span>
- </ProgressTabs.Trigger>
- <ProgressTabs.Trigger
- value={Tab.ORGANIZE}
- status={nestingStatus}
- className="w-full min-w-0 overflow-hidden"
- data-testid="category-create-form-tab-organize"
- >
- <span className="truncate">
- {t("categories.create.tabs.organize")}
- </span>
- </ProgressTabs.Trigger>
- </ProgressTabs.List>
- </div>
- </div>
- </RouteFocusModal.Header>
- <RouteFocusModal.Body className="flex size-full flex-col overflow-auto" data-testid="category-create-form-body">
- <ProgressTabs.Content value={Tab.DETAILS} data-testid="category-create-form-tab-details-content">
- <CreateCategoryDetails form={form} />
- </ProgressTabs.Content>
- <ProgressTabs.Content
- value={Tab.ORGANIZE}
- className="bg-ui-bg-subtle flex-1"
- data-testid="category-create-form-tab-organize-content"
- >
- <CreateCategoryNesting form={form} shouldFreeze={shouldFreeze} />
- </ProgressTabs.Content>
- </RouteFocusModal.Body>
- <RouteFocusModal.Footer data-testid="category-create-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button size="small" variant="secondary" data-testid="category-create-form-cancel-button">
- {t("actions.cancel")}
- </Button>
- </RouteFocusModal.Close>
- {activeTab === Tab.ORGANIZE ? (
- <Button
- key="submit-btn"
- size="small"
- variant="primary"
- type="submit"
- isLoading={isPending}
- data-testid="category-create-form-save-button"
- >
- {t("actions.save")}
- </Button>
- ) : (
- <Button
- key="continue-btn"
- size="small"
- variant="primary"
- type="button"
- onClick={() => handleTabChange(Tab.ORGANIZE)}
- data-testid="category-create-form-continue-button"
- >
- {t("actions.continue")}
- </Button>
- )}
- </div>
- </RouteFocusModal.Footer>
- </ProgressTabs>
- </KeyboundForm>
- </RouteFocusModal.Form>
+ <TabbedForm
+ form={form}
+ onSubmit={handleSubmit}
+ isLoading={isPending}
+ >
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
)
}
diff --git a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-nesting.tsx b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-nesting.tsx
index 1c0ff4b7c..fb7bf2638 100644
--- a/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-nesting.tsx
+++ b/packages/admin/src/pages/categories/category-create/components/create-category-form/create-category-nesting.tsx
@@ -1,29 +1,26 @@
import { UniqueIdentifier } from "@dnd-kit/core"
import { Badge } from "@medusajs/ui"
import { useMemo, useState } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { useTranslation } from "react-i18next"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { useProductCategories } from "../../../../../hooks/api/categories"
import { CategoryTree } from "../../../common/components/category-tree"
import { CategoryTreeItem } from "../../../common/types"
import { insertCategoryTreeItem } from "../../../common/utils"
import { CreateCategorySchema } from "./schema"
-type CreateCategoryNestingProps = {
- form: UseFormReturn<CreateCategorySchema>
- shouldFreeze?: boolean
-}
-
const ID = "new-item"
-export const CreateCategoryNesting = ({
- form,
- shouldFreeze,
-}: CreateCategoryNestingProps) => {
+const Root = () => {
const { t } = useTranslation()
+ const form = useTabbedForm<CreateCategorySchema>()
const [snapshot, setSnapshot] = useState<CategoryTreeItem[]>([])
+ const shouldFreeze = form.formState.isSubmitting
+
const { product_categories, isPending, isError, error } =
useProductCategories({
parent_category_id: "null",
@@ -90,7 +87,7 @@ export const CreateCategoryNesting = ({
const ready = !isPending && !!product_categories
return (
- <div data-testid="category-create-form-nesting">
+ <div className="bg-ui-bg-subtle flex-1" data-testid="category-create-form-nesting">
<CategoryTree
value={shouldFreeze ? snapshot : value}
enableDrag={(item) => item.id === ID}
@@ -114,3 +111,11 @@ export const CreateCategoryNesting = ({
</div>
)
}
+
+Root._tabMeta = defineTabMeta<CreateCategorySchema>({
+ id: "organize",
+ labelKey: "categories.create.tabs.organize",
+ validationFields: ["parent_category_id", "rank"],
+})
+
+export const CreateCategoryNesting = Root
diff --git a/packages/admin/src/pages/categories/index.ts b/packages/admin/src/pages/categories/index.ts
index 0316275a4..800728000 100644
--- a/packages/admin/src/pages/categories/index.ts
+++ b/packages/admin/src/pages/categories/index.ts
@@ -1,2 +1,3 @@
export { CategoryListPage } from "./category-list/category-list"
export { CategoryDetailPage } from "./category-detail/category-detail"
+export { CategoryCreatePage, CreateCategorySchema } from "./category-create/category-create"
diff --git a/packages/admin/src/pages/index.ts b/packages/admin/src/pages/index.ts
index b4b5aeca3..c7a1369d1 100644
--- a/packages/admin/src/pages/index.ts
+++ b/packages/admin/src/pages/index.ts
@@ -27,67 +27,3 @@ export * from "./shipping-option-types"
export * from "./shipping-profiles"
export * from "./tax-regions"
export * from "./users"
-
-// Non-Settings — Create pages
-export { ProductCreatePage } from "./products/product-create/product-create"
-export { ProductCreateSchema } from "./products/product-create/constants"
-
-// Non-Settings — Detail pages
-export { ProductDetailPage } from "./products/product-detail/product-detail"
-export { ProductVariantDetailPage } from "./product-variants/product-variant-detail/product-variant-detail"
-export { CustomerDetailPage } from "./customers/customer-detail/customer-detail"
-export { CustomerGroupDetailPage } from "./customer-groups/customer-group-detail/customer-group-detail"
-export { OrderDetailPage } from "./orders/order-detail/order-detail"
-export { CategoryDetailPage } from "./categories/category-detail/category-detail"
-export { CollectionDetailPage } from "./collections/collection-detail/collection-detail"
-export { PriceListDetailPage } from "./price-lists/price-list-detail/price-list-detail"
-export { SellerDetailPage } from "./sellers/seller-details/components/seller-details"
-export { CampaignDetailPage } from "./campaigns/campaign-detail/campaign-detail"
-export { PromotionDetailPage } from "./promotions/promotion-detail/promotion-detail"
-export { InventoryDetailPage } from "./inventory/inventory-detail/inventory-detail"
-export { PayoutDetailPage } from "./payouts/payout-detail/payout-detail"
-export { ReservationDetailPage } from "./reservations/reservation-detail/reservation-detail"
-
-// Non-Settings — List pages
-export { ProductListPage } from "./products/product-list/product-list"
-export { CustomerListPage } from "./customers/customer-list/customer-list"
-export { CustomerGroupListPage } from "./customer-groups/customer-group-list/customer-group-list"
-export { OrderListPage } from "./orders/order-list/order-list"
-export { CategoryListPage } from "./categories/category-list/category-list"
-export { CollectionListPage } from "./collections/collection-list/collection-list"
-export { PriceListListPage } from "./price-lists/price-list-list/price-list-list"
-export { SellerListPage } from "./sellers/seller-list/seller-list"
-export { CampaignListPage } from "./campaigns/campaign-list/campaign-list"
-export { PromotionListPage } from "./promotions/promotion-list/promotions-list"
-export { InventoryListPage } from "./inventory/inventory-list/inventory-list"
-export { PayoutListPage } from "./payouts/payout-list/payout-list"
-export { ReservationListPage } from "./reservations/reservation-list/reservation-list"
-
-// Settings — Detail pages
-export { ProfileDetailPage } from "./profile/profile-detail/profile-detail"
-export { UserDetailPage } from "./users/user-detail/user-detail"
-export { ShippingProfileDetailPage } from "./shipping-profiles/shipping-profile-detail/shipping-profile-detail"
-export { ShippingOptionTypeDetailPage } from "./shipping-option-types/shipping-option-type-detail/shipping-option-type-detail"
-export { RegionDetailPage } from "./regions/region-detail/region-detail"
-export { SalesChannelDetailPage } from "./sales-channels/sales-channel-detail/sales-channel-detail"
-export { ProductTagDetailPage } from "./product-tags/product-tag-detail/product-tag-detail"
-export { ProductTypeDetailPage } from "./product-types/product-type-detail/product-type-detail"
-export { ApiKeyManagementDetailPage } from "./api-key-management/api-key-management-detail/api-key-management-detail"
-export { MarketplaceDetailPage } from "./marketplace/marketplace-detail/marketplace-detail"
-export { CommissionRateDetailPage } from "./commission-rates/commission-rate-detail/commission-rate-detail"
-export { LocationDetailPage } from "./locations/location-detail/location-detail"
-export { TaxRegionDetailPage } from "./tax-regions/tax-region-detail/tax-region-detail"
-export { TaxRegionProvinceDetailPage } from "./tax-regions/tax-region-province-detail/tax-region-detail"
-
-// Settings — List pages
-export { RegionListPage } from "./regions/region-list/region-list"
-export { UserListPage } from "./users/user-list/user-list"
-export { SalesChannelListPage } from "./sales-channels/sales-channel-list/sales-channel-list"
-export { LocationListPage } from "./locations/location-list/location-list"
-export { ShippingProfileListPage } from "./shipping-profiles/shipping-profiles-list/shipping-profile-list"
-export { ShippingOptionTypeListPage } from "./shipping-option-types/shipping-option-type-list/shipping-option-type-list"
-export { ProductTagListPage } from "./product-tags/product-tag-list/product-tag-list"
-export { ProductTypeListPage } from "./product-types/product-type-list/product-type-list"
-export { ApiKeyManagementListPage } from "./api-key-management/api-key-management-list/api-key-management-list"
-export { TaxRegionListPage } from "./tax-regions/tax-region-list/tax-region-list"
-export { CommissionRateListPage } from "./commission-rates/commission-rate-list/commission-rate-list"
diff --git a/packages/admin/src/pages/inventory/index.ts b/packages/admin/src/pages/inventory/index.ts
index 5cb944984..133c66bca 100644
--- a/packages/admin/src/pages/inventory/index.ts
+++ b/packages/admin/src/pages/inventory/index.ts
@@ -1,2 +1,3 @@
export { InventoryListPage } from "./inventory-list/inventory-list"
export { InventoryDetailPage } from "./inventory-detail/inventory-detail"
+export { InventoryCreatePage, CreateInventoryItemSchema } from "./inventory-create/inventory-create"
diff --git a/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-availability-form.tsx b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-availability-form.tsx
index 8fd9ad430..b0947ae08 100644
--- a/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-availability-form.tsx
+++ b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-availability-form.tsx
@@ -1,6 +1,5 @@
import { HttpTypes } from "@medusajs/types"
import { useMemo } from "react"
-import { UseFormReturn } from "react-hook-form"
import { useTranslation } from "react-i18next"
import {
@@ -8,17 +7,16 @@ import {
createDataGridHelper,
} from "../../../../../components/data-grid"
import { useRouteModal } from "../../../../../components/modals"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { CreateInventoryItemSchema } from "./schema"
type InventoryAvailabilityFormProps = {
- form: UseFormReturn<CreateInventoryItemSchema>
locations: HttpTypes.AdminStockLocation[]
}
-export const InventoryAvailabilityForm = ({
- form,
- locations,
-}: InventoryAvailabilityFormProps) => {
+const Root = ({ locations }: InventoryAvailabilityFormProps) => {
+ const form = useTabbedForm<CreateInventoryItemSchema>()
const { setCloseOnEscape } = useRouteModal()
const columns = useColumns()
@@ -76,3 +74,11 @@ const useColumns = () => {
[t]
)
}
+
+Root._tabMeta = defineTabMeta<CreateInventoryItemSchema>({
+ id: "availability",
+ labelKey: "inventory.create.availability",
+ validationFields: ["locations"],
+})
+
+export const InventoryAvailabilityForm = Root
diff --git a/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-details-tab.tsx b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-details-tab.tsx
new file mode 100644
index 000000000..8950bc0a9
--- /dev/null
+++ b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-details-tab.tsx
@@ -0,0 +1,207 @@
+import {
+ Divider,
+ Heading,
+ Input,
+ Textarea,
+} from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "../../../../../components/common/form"
+import { SwitchBox } from "../../../../../components/common/switch-box"
+import { CountrySelect } from "../../../../../components/inputs/country-select"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
+import { CreateInventoryItemSchema } from "./schema"
+
+const Root = () => {
+ const { t } = useTranslation()
+ const form = useTabbedForm<CreateInventoryItemSchema>()
+
+ return (
+ <div className="flex flex-1 flex-col items-center overflow-y-auto px-3">
+ <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-px py-16" data-testid="inventory-create-form-content">
+ <div className="flex flex-col gap-y-8">
+ <div data-testid="inventory-create-form-header">
+ <Heading data-testid="inventory-create-form-heading">{t("inventory.create.title")}</Heading>
+ </div>
+ <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 }) => (
+ <Form.Item data-testid="inventory-create-form-title-item">
+ <Form.Label data-testid="inventory-create-form-title-label">{t("fields.title")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-title-control">
+ <Input {...field} placeholder={t("fields.title")} data-testid="inventory-create-form-title-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-title-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="sku"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-sku-item">
+ <Form.Label data-testid="inventory-create-form-sku-label">{t("fields.sku")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-sku-control">
+ <Input {...field} placeholder="sku-123" data-testid="inventory-create-form-sku-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-sku-error" />
+ </Form.Item>
+ )}
+ />
+ </div>
+ <Form.Field
+ control={form.control}
+ name="description"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-description-item">
+ <Form.Label optional data-testid="inventory-create-form-description-label">
+ {t("products.fields.description.label")}
+ </Form.Label>
+ <Form.Control data-testid="inventory-create-form-description-control">
+ <Textarea {...field} placeholder="The item description" data-testid="inventory-create-form-description-textarea" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-description-error" />
+ </Form.Item>
+ )}
+ />
+ </div>
+ <SwitchBox
+ control={form.control}
+ name="requires_shipping"
+ label={t("inventory.create.requiresShipping")}
+ description={t("inventory.create.requiresShippingHint")}
+ data-testid="inventory-create-form-requires-shipping"
+ />
+ </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 }) => (
+ <Form.Item data-testid="inventory-create-form-width-item">
+ <Form.Label optional data-testid="inventory-create-form-width-label">{t("products.fields.width.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-width-control">
+ <Input {...field} type="number" min={0} placeholder="100" data-testid="inventory-create-form-width-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-width-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="length"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-length-item">
+ <Form.Label optional data-testid="inventory-create-form-length-label">{t("products.fields.length.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-length-control">
+ <Input {...field} type="number" min={0} placeholder="100" data-testid="inventory-create-form-length-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-length-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="height"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-height-item">
+ <Form.Label optional data-testid="inventory-create-form-height-label">{t("products.fields.height.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-height-control">
+ <Input {...field} type="number" min={0} placeholder="100" data-testid="inventory-create-form-height-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-height-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="weight"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-weight-item">
+ <Form.Label optional data-testid="inventory-create-form-weight-label">{t("products.fields.weight.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-weight-control">
+ <Input {...field} type="number" min={0} placeholder="100" data-testid="inventory-create-form-weight-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-weight-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="mid_code"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-mid-code-item">
+ <Form.Label optional data-testid="inventory-create-form-mid-code-label">{t("products.fields.mid_code.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-mid-code-control">
+ <Input {...field} data-testid="inventory-create-form-mid-code-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-mid-code-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="hs_code"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-hs-code-item">
+ <Form.Label optional data-testid="inventory-create-form-hs-code-label">{t("products.fields.hs_code.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-hs-code-control">
+ <Input {...field} data-testid="inventory-create-form-hs-code-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-hs-code-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="origin_country"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-origin-country-item">
+ <Form.Label optional data-testid="inventory-create-form-origin-country-label">{t("products.fields.countryOrigin.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-origin-country-control">
+ <CountrySelect {...field} data-testid="inventory-create-form-origin-country-select" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-origin-country-error" />
+ </Form.Item>
+ )}
+ />
+ <Form.Field
+ control={form.control}
+ name="material"
+ render={({ field }) => (
+ <Form.Item data-testid="inventory-create-form-material-item">
+ <Form.Label optional data-testid="inventory-create-form-material-label">{t("products.fields.material.label")}</Form.Label>
+ <Form.Control data-testid="inventory-create-form-material-control">
+ <Input {...field} data-testid="inventory-create-form-material-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="inventory-create-form-material-error" />
+ </Form.Item>
+ )}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+Root._tabMeta = defineTabMeta<CreateInventoryItemSchema>({
+ id: "details",
+ labelKey: "inventory.create.details",
+ validationFields: [
+ "title", "sku", "description", "hs_code", "weight", "length",
+ "height", "width", "origin_country", "mid_code", "material",
+ "requires_shipping", "thumbnail",
+ ],
+})
+
+export const InventoryCreateDetailsTab = Root
diff --git a/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-form.tsx b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-form.tsx
index db692a30c..dafdcc937 100644
--- a/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-form.tsx
+++ b/packages/admin/src/pages/inventory/inventory-create/components/inventory-create-form/inventory-create-form.tsx
@@ -1,28 +1,13 @@
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 { toast } from "@medusajs/ui"
+import { Children, ReactNode, useMemo } from "react"
+import { DeepPartial, useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
+import { z } from "zod"
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 { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
import {
inventoryItemsQueryKeys,
useCreateInventoryItem,
@@ -35,28 +20,28 @@ import {
} from "../../../../../lib/form-helpers"
import { queryClient } from "../../../../../lib/query-client"
import { InventoryAvailabilityForm } from "./inventory-availability-form"
+import { InventoryCreateDetailsTab } from "./inventory-create-details-tab"
import { CreateInventoryItemSchema } from "./schema"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
-enum Tab {
- DETAILS = "details",
- AVAILABILITY = "availability",
-}
-
-type StepStatus = {
- [key in Tab]: ProgressStatus
-}
+export type CreateInventoryItemSchemaType = z.infer<typeof CreateInventoryItemSchema>
type InventoryCreateFormProps = {
locations: HttpTypes.AdminStockLocation[]
+ children?: ReactNode
+ schema?: z.ZodType<CreateInventoryItemSchemaType>
+ defaultValues?: DeepPartial<CreateInventoryItemSchemaType>
}
-export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
+export function InventoryCreateForm({
+ locations,
+ children,
+ schema,
+ defaultValues: extraDefaults,
+}: InventoryCreateFormProps) {
const { t } = useTranslation()
const { handleSuccess } = useRouteModal()
- const [tab, setTab] = useState<Tab>(Tab.DETAILS)
- const direction = useDocumentDirection()
- const form = useForm<CreateInventoryItemSchema>({
+
+ const form = useForm<CreateInventoryItemSchemaType>({
defaultValues: {
title: "",
sku: "",
@@ -74,29 +59,20 @@ export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
locations: Object.fromEntries(
locations.map((location) => [location.id, ""])
),
- },
- resolver: zodResolver(CreateInventoryItemSchema),
+ ...extraDefaults,
+ } as CreateInventoryItemSchemaType,
+ resolver: zodResolver(schema ?? 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 { locations: formLocations, weight, length, height, width, ...payload } = data
const cleanData = transformNullableFormData(payload, false)
const cleanNumbers = transformNullableFormNumbers(
- {
- weight,
- length,
- height,
- width,
- },
+ { weight, length, height, width },
false
)
@@ -113,9 +89,9 @@ export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
}
)
- await sdk.admin.inventoryItem
- .batchUpdateLevels(inventory_item.id, {
- create: Object.entries(locations ?? {})
+ // @ts-expect-error — Mercur SDK extension
+ await sdk.admin.inventoryItem.batchUpdateLevels(inventory_item.id, {
+ create: Object.entries(formLocations ?? {})
.filter(([_, quantiy]) => !!quantiy)
.map(([location_id, stocked_quantity]) => ({
location_id,
@@ -130,10 +106,7 @@ export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
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.
+ .catch((e: Error) => {
toast.error(e.message)
})
.finally(() => {
@@ -142,400 +115,23 @@ export function InventoryCreateForm({ locations }: InventoryCreateFormProps) {
})
})
- 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 defaultTabs = useMemo(
+ () => [
+ <InventoryCreateDetailsTab key="details" />,
+ <InventoryAvailabilityForm key="availability" locations={locations} />,
+ ],
+ [locations]
)
- 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])
+ const hasCustomChildren = Children.count(children) > 0
return (
- <RouteFocusModal.Form form={form} data-testid="inventory-create-form">
- <ProgressTabs
- dir={direction}
- value={tab}
- className="h-full"
- onValueChange={(tab) => onTabChange(tab as Tab)}
- >
- <KeyboundForm
- className="flex h-full flex-col overflow-hidden"
- onSubmit={handleSubmit}
- >
- <RouteFocusModal.Header data-testid="inventory-create-form-header">
- <ProgressTabs.List className="border-ui-border-base -my-2 ml-2 min-w-0 flex-1 border-l" data-testid="inventory-create-form-tabs-list">
- <ProgressTabs.Trigger
- value={Tab.DETAILS}
- status={status[Tab.DETAILS]}
- className="w-full max-w-[200px]"
- data-testid="inventory-create-form-tab-details"
- >
- <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]}
- data-testid="inventory-create-form-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 }
- )}
- data-testid="inventory-create-form-body"
- >
- <ProgressTabs.Content
- value={Tab.DETAILS}
- className="h-full w-full overflow-auto px-3"
- data-testid="inventory-create-form-tab-details-content"
- >
- <div className="mx-auto flex w-full max-w-[720px] flex-col gap-y-8 px-px py-16" data-testid="inventory-create-form-content">
- <div className="flex flex-col gap-y-8">
- <div data-testid="inventory-create-form-header">
- <Heading data-testid="inventory-create-form-heading">{t("inventory.create.title")}</Heading>
- </div>
- <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 data-testid="inventory-create-form-title-item">
- <Form.Label data-testid="inventory-create-form-title-label">{t("fields.title")}</Form.Label>
- <Form.Control data-testid="inventory-create-form-title-control">
- <Input
- {...field}
- placeholder={t("fields.title")}
- data-testid="inventory-create-form-title-input"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-title-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="sku"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-sku-item">
- <Form.Label data-testid="inventory-create-form-sku-label">{t("fields.sku")}</Form.Label>
- <Form.Control data-testid="inventory-create-form-sku-control">
- <Input {...field} placeholder="sku-123" data-testid="inventory-create-form-sku-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-sku-error" />
- </Form.Item>
- )
- }}
- />
- </div>
-
- <Form.Field
- control={form.control}
- name="description"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-description-item">
- <Form.Label optional data-testid="inventory-create-form-description-label">
- {t("products.fields.description.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-description-control">
- <Textarea
- {...field}
- placeholder="The item description"
- data-testid="inventory-create-form-description-textarea"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-description-error" />
- </Form.Item>
- )
- }}
- />
- </div>
-
- <SwitchBox
- control={form.control}
- name="requires_shipping"
- label={t("inventory.create.requiresShipping")}
- description={t("inventory.create.requiresShippingHint")}
- data-testid="inventory-create-form-requires-shipping"
- />
- </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 data-testid="inventory-create-form-width-item">
- <Form.Label optional data-testid="inventory-create-form-width-label">
- {t("products.fields.width.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-width-control">
- <Input
- {...field}
- type="number"
- min={0}
- placeholder="100"
- data-testid="inventory-create-form-width-input"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-width-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="length"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-length-item">
- <Form.Label optional data-testid="inventory-create-form-length-label">
- {t("products.fields.length.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-length-control">
- <Input
- {...field}
- type="number"
- min={0}
- placeholder="100"
- data-testid="inventory-create-form-length-input"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-length-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="height"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-height-item">
- <Form.Label optional data-testid="inventory-create-form-height-label">
- {t("products.fields.height.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-height-control">
- <Input
- {...field}
- type="number"
- min={0}
- placeholder="100"
- data-testid="inventory-create-form-height-input"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-height-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="weight"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-weight-item">
- <Form.Label optional data-testid="inventory-create-form-weight-label">
- {t("products.fields.weight.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-weight-control">
- <Input
- {...field}
- type="number"
- min={0}
- placeholder="100"
- data-testid="inventory-create-form-weight-input"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-weight-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="mid_code"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-mid-code-item">
- <Form.Label optional data-testid="inventory-create-form-mid-code-label">
- {t("products.fields.mid_code.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-mid-code-control">
- <Input {...field} data-testid="inventory-create-form-mid-code-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-mid-code-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="hs_code"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-hs-code-item">
- <Form.Label optional data-testid="inventory-create-form-hs-code-label">
- {t("products.fields.hs_code.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-hs-code-control">
- <Input {...field} data-testid="inventory-create-form-hs-code-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-hs-code-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="origin_country"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-origin-country-item">
- <Form.Label optional data-testid="inventory-create-form-origin-country-label">
- {t("products.fields.countryOrigin.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-origin-country-control">
- <CountrySelect {...field} data-testid="inventory-create-form-origin-country-select" />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-origin-country-error" />
- </Form.Item>
- )
- }}
- />
-
- <Form.Field
- control={form.control}
- name="material"
- render={({ field }) => {
- return (
- <Form.Item data-testid="inventory-create-form-material-item">
- <Form.Label optional data-testid="inventory-create-form-material-label">
- {t("products.fields.material.label")}
- </Form.Label>
- <Form.Control data-testid="inventory-create-form-material-control">
- <Input {...field} data-testid="inventory-create-form-material-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="inventory-create-form-material-error" />
- </Form.Item>
- )
- }}
- />
- </div>
- </div>
- </div>
- </ProgressTabs.Content>
-
- <ProgressTabs.Content
- value={Tab.AVAILABILITY}
- className="size-full"
- data-testid="inventory-create-form-tab-availability-content"
- >
- <InventoryAvailabilityForm form={form} locations={locations} />
- </ProgressTabs.Content>
- </RouteFocusModal.Body>
- <RouteFocusModal.Footer data-testid="inventory-create-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button variant="secondary" size="small" data-testid="inventory-create-form-cancel-button">
- {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"}
- data-testid={tab === Tab.AVAILABILITY ? "inventory-create-form-save-button" : "inventory-create-form-next-button"}
- >
- {tab === Tab.AVAILABILITY
- ? t("actions.save")
- : t("general.next")}
- </Button>
- </div>
- </RouteFocusModal.Footer>
- </KeyboundForm>
- </ProgressTabs>
- </RouteFocusModal.Form>
+ <TabbedForm
+ form={form}
+ onSubmit={handleSubmit}
+ isLoading={isLoading}
+ >
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
)
}
diff --git a/packages/admin/src/pages/inventory/inventory-create/inventory-create.tsx b/packages/admin/src/pages/inventory/inventory-create/inventory-create.tsx
index a5aeac3a0..99ababb11 100644
--- a/packages/admin/src/pages/inventory/inventory-create/inventory-create.tsx
+++ b/packages/admin/src/pages/inventory/inventory-create/inventory-create.tsx
@@ -1,12 +1,22 @@
+import { Children, ReactNode } from "react"
+
import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
import { useStockLocations } from "../../../hooks/api"
-import { InventoryCreateForm } from "./components/inventory-create-form"
+import {
+ InventoryCreateForm,
+ CreateInventoryItemSchemaType,
+} from "./components/inventory-create-form"
+import { InventoryCreateDetailsTab } from "./components/inventory-create-form/inventory-create-details-tab"
+import { InventoryAvailabilityForm } from "./components/inventory-create-form/inventory-availability-form"
+import { CreateInventoryItemSchema } from "./components/inventory-create-form/schema"
-export function InventoryCreate() {
+const Root = ({ children }: { children?: ReactNode }) => {
const { isPending, stock_locations, isError, error } = useStockLocations({
limit: 9999,
fields: "id,name",
})
+
const ready = !isPending && !!stock_locations
if (isError) {
@@ -15,7 +25,26 @@ export function InventoryCreate() {
return (
<RouteFocusModal>
- {ready && <InventoryCreateForm locations={stock_locations} />}
+ {ready && (
+ Children.count(children) > 0 ? (
+ children
+ ) : (
+ <InventoryCreateForm locations={stock_locations} />
+ )
+ )}
</RouteFocusModal>
)
}
+
+export const InventoryCreatePage = Object.assign(Root, {
+ Form: InventoryCreateForm,
+ DetailsTab: InventoryCreateDetailsTab,
+ AvailabilityTab: InventoryAvailabilityForm,
+ Tab: TabbedForm.Tab,
+})
+
+export type { CreateInventoryItemSchemaType }
+export { CreateInventoryItemSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const InventoryCreate = Root
diff --git a/packages/admin/src/pages/locations/index.ts b/packages/admin/src/pages/locations/index.ts
index f5842a8c8..2b939fe89 100644
--- a/packages/admin/src/pages/locations/index.ts
+++ b/packages/admin/src/pages/locations/index.ts
@@ -1,2 +1,3 @@
export { LocationListPage } from "./location-list/location-list"
export { LocationDetailPage } from "./location-detail/location-detail"
+export { ShippingOptionCreatePage, CreateShippingOptionSchema } from "./location-service-zone-shipping-option-create/location-service-zone-shipping-option-create"
diff --git a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-option-details-form.tsx b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-option-details-form.tsx
index 8e1690b78..fa08fd396 100644
--- a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-option-details-form.tsx
+++ b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-option-details-form.tsx
@@ -1,5 +1,4 @@
import { Divider, Heading, Input, RadioGroup, Select, Text } from "@medusajs/ui"
-import type { UseFormReturn } from "react-hook-form"
import { useTranslation } from "react-i18next"
import type { HttpTypes } from "@medusajs/types"
@@ -7,16 +6,17 @@ import type { HttpTypes } from "@medusajs/types"
import { Form } from "../../../../../components/common/form"
import { SwitchBox } from "../../../../../components/common/switch-box"
import { Combobox } from "../../../../../components/inputs/combobox"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { useComboboxData } from "../../../../../hooks/use-combobox-data"
import { sdk } from "../../../../../lib/client"
import { formatProvider } from "../../../../../lib/format-provider"
-import { FulfillmentSetType, ShippingOptionPriceType, } from "../../../common/constants"
+import { FulfillmentSetType, ShippingOptionPriceType } from "../../../common/constants"
import { CreateShippingOptionSchema } from "./schema"
import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
import type { ExtendedAdminFulfillmentProviderOption } from "@custom-types/fulfillment-providers/common"
type CreateShippingOptionDetailsFormProps = {
- form: UseFormReturn<CreateShippingOptionSchema>
isReturn?: boolean
zone: HttpTypes.AdminServiceZone
locationId: string
@@ -25,8 +25,7 @@ type CreateShippingOptionDetailsFormProps = {
type: FulfillmentSetType
}
-export const CreateShippingOptionDetailsForm = ({
- form,
+const Root = ({
isReturn = false,
zone,
locationId,
@@ -35,6 +34,7 @@ export const CreateShippingOptionDetailsForm = ({
type,
}: CreateShippingOptionDetailsFormProps) => {
const { t } = useTranslation()
+ const form = useTabbedForm<CreateShippingOptionSchema>()
const direction = useDocumentDirection()
const isPickup = type === FulfillmentSetType.Pickup
@@ -81,9 +81,7 @@ export const CreateShippingOptionDetailsForm = ({
`stockLocations.shippingOptions.create.${
isPickup ? "pickup" : isReturn ? "returns" : "shipping"
}.header`,
- {
- zone: zone.name,
- }
+ { zone: zone.name }
)}
</Heading>
<Text size="small" className="text-ui-fg-subtle" data-testid="location-shipping-option-create-details-form-hint">
@@ -99,48 +97,38 @@ export const CreateShippingOptionDetailsForm = ({
<Form.Field
control={form.control}
name="price_type"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-price-type-item">
- <Form.Label data-testid="location-shipping-option-create-details-form-price-type-label">
- {t("stockLocations.shippingOptions.fields.priceType.label")}
- </Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-price-type-control">
- <RadioGroup
- dir={direction}
- className="grid grid-cols-1 gap-4 md:grid-cols-2"
- {...field}
- onValueChange={field.onChange}
- data-testid="location-shipping-option-create-details-form-price-type-radio-group"
- >
- <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"
- )}
- data-testid="location-shipping-option-create-details-form-price-type-flat-rate"
- />
- <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"
- )}
- data-testid="location-shipping-option-create-details-form-price-type-calculated"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-price-type-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-price-type-item">
+ <Form.Label data-testid="location-shipping-option-create-details-form-price-type-label">
+ {t("stockLocations.shippingOptions.fields.priceType.label")}
+ </Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-price-type-control">
+ <RadioGroup
+ dir={direction}
+ className="grid grid-cols-1 gap-4 md:grid-cols-2"
+ {...field}
+ onValueChange={field.onChange}
+ data-testid="location-shipping-option-create-details-form-price-type-radio-group"
+ >
+ <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")}
+ data-testid="location-shipping-option-create-details-form-price-type-flat-rate"
+ />
+ <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")}
+ data-testid="location-shipping-option-create-details-form-price-type-calculated"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-price-type-error" />
+ </Form.Item>
+ )}
/>
)}
@@ -148,67 +136,59 @@ export const CreateShippingOptionDetailsForm = ({
<Form.Field
control={form.control}
name="name"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-name-item">
- <Form.Label data-testid="location-shipping-option-create-details-form-name-label">{t("fields.name")}</Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-name-control">
- <Input {...field} data-testid="location-shipping-option-create-details-form-name-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-name-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-name-item">
+ <Form.Label data-testid="location-shipping-option-create-details-form-name-label">{t("fields.name")}</Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-name-control">
+ <Input {...field} data-testid="location-shipping-option-create-details-form-name-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-name-error" />
+ </Form.Item>
+ )}
/>
<Form.Field
control={form.control}
name="shipping_profile_id"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-shipping-profile-item">
- <Form.Label data-testid="location-shipping-option-create-details-form-shipping-profile-label">
- {t("stockLocations.shippingOptions.fields.profile")}
- </Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-shipping-profile-control">
- <Combobox
- {...field}
- options={shippingProfiles.options}
- searchValue={shippingProfiles.searchValue}
- onSearchValueChange={shippingProfiles.onSearchValueChange}
- disabled={shippingProfiles.disabled}
- data-testid="location-shipping-option-create-details-form-shipping-profile-combobox"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-shipping-profile-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-shipping-profile-item">
+ <Form.Label data-testid="location-shipping-option-create-details-form-shipping-profile-label">
+ {t("stockLocations.shippingOptions.fields.profile")}
+ </Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-shipping-profile-control">
+ <Combobox
+ {...field}
+ options={shippingProfiles.options}
+ searchValue={shippingProfiles.searchValue}
+ onSearchValueChange={shippingProfiles.onSearchValueChange}
+ disabled={shippingProfiles.disabled}
+ data-testid="location-shipping-option-create-details-form-shipping-profile-combobox"
+ />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-shipping-profile-error" />
+ </Form.Item>
+ )}
/>
<Form.Field
control={form.control}
name="shipping_option_type_id"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-shipping-option-type-item">
- <Form.Label data-testid="location-shipping-option-create-details-form-shipping-option-type-label">
- {t("stockLocations.shippingOptions.fields.type")}
- </Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-shipping-option-type-control">
- <Combobox
- {...field}
- options={shippingOptionTypes.options}
- searchValue={shippingOptionTypes.searchValue}
- onSearchValueChange={
- shippingOptionTypes.onSearchValueChange
- }
- disabled={shippingOptionTypes.disabled}
- data-testid="location-shipping-option-create-details-form-shipping-option-type-combobox"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-shipping-option-type-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-shipping-option-type-item">
+ <Form.Label data-testid="location-shipping-option-create-details-form-shipping-option-type-label">
+ {t("stockLocations.shippingOptions.fields.type")}
+ </Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-shipping-option-type-control">
+ <Combobox
+ {...field}
+ options={shippingOptionTypes.options}
+ searchValue={shippingOptionTypes.searchValue}
+ onSearchValueChange={shippingOptionTypes.onSearchValueChange}
+ disabled={shippingOptionTypes.disabled}
+ data-testid="location-shipping-option-create-details-form-shipping-option-type-combobox"
+ />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-shipping-option-type-error" />
+ </Form.Item>
+ )}
/>
</div>
@@ -216,78 +196,67 @@ export const CreateShippingOptionDetailsForm = ({
<Form.Field
control={form.control}
name="provider_id"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-provider-item">
- <Form.Label
- tooltip={t(
- "stockLocations.fulfillmentProviders.shippingOptionsTooltip"
- )}
- data-testid="location-shipping-option-create-details-form-provider-label"
- >
- {t("stockLocations.shippingOptions.fields.provider")}
- </Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-provider-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}
- data-testid="location-shipping-option-create-details-form-provider-combobox"
- />
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-provider-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-provider-item">
+ <Form.Label
+ tooltip={t("stockLocations.fulfillmentProviders.shippingOptionsTooltip")}
+ data-testid="location-shipping-option-create-details-form-provider-label"
+ >
+ {t("stockLocations.shippingOptions.fields.provider")}
+ </Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-provider-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}
+ data-testid="location-shipping-option-create-details-form-provider-combobox"
+ />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-provider-error" />
+ </Form.Item>
+ )}
/>
<Form.Field
control={form.control}
name="fulfillment_option_id"
- render={({ field }) => {
- return (
- <Form.Item data-testid="location-shipping-option-create-details-form-fulfillment-option-item">
- <Form.Label data-testid="location-shipping-option-create-details-form-fulfillment-option-label">
- {t(
- "stockLocations.shippingOptions.fields.fulfillmentOption"
- )}
- </Form.Label>
- <Form.Control data-testid="location-shipping-option-create-details-form-fulfillment-option-control">
- <Select
- dir={direction}
- {...field}
- onValueChange={field.onChange}
- disabled={!selectedProviderId}
- key={selectedProviderId}
- data-testid="location-shipping-option-create-details-form-fulfillment-option-select"
- >
- <Select.Trigger ref={field.ref} data-testid="location-shipping-option-create-details-form-fulfillment-option-trigger">
- <Select.Value />
- </Select.Trigger>
-
- <Select.Content data-testid="location-shipping-option-create-details-form-fulfillment-option-content">
- {fulfillmentProviderOptions
- ?.filter((fo) => !!fo.is_return === isReturn)
- .map((option) => (
- <Select.Item value={option.id} key={option.id} data-testid={`location-shipping-option-create-details-form-fulfillment-option-option-${option.id}`}>
- {option.name || option.id}
- </Select.Item>
- ))}
- </Select.Content>
- </Select>
- </Form.Control>
- <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-fulfillment-option-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="location-shipping-option-create-details-form-fulfillment-option-item">
+ <Form.Label data-testid="location-shipping-option-create-details-form-fulfillment-option-label">
+ {t("stockLocations.shippingOptions.fields.fulfillmentOption")}
+ </Form.Label>
+ <Form.Control data-testid="location-shipping-option-create-details-form-fulfillment-option-control">
+ <Select
+ dir={direction}
+ {...field}
+ onValueChange={field.onChange}
+ disabled={!selectedProviderId}
+ key={selectedProviderId}
+ data-testid="location-shipping-option-create-details-form-fulfillment-option-select"
+ >
+ <Select.Trigger ref={field.ref} data-testid="location-shipping-option-create-details-form-fulfillment-option-trigger">
+ <Select.Value />
+ </Select.Trigger>
+ <Select.Content data-testid="location-shipping-option-create-details-form-fulfillment-option-content">
+ {fulfillmentProviderOptions
+ ?.filter((fo) => !!fo.is_return === isReturn)
+ .map((option) => (
+ <Select.Item value={option.id} key={option.id} data-testid={`location-shipping-option-create-details-form-fulfillment-option-option-${option.id}`}>
+ {option.name || option.id}
+ </Select.Item>
+ ))}
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="location-shipping-option-create-details-form-fulfillment-option-error" />
+ </Form.Item>
+ )}
/>
</div>
@@ -296,12 +265,21 @@ export const CreateShippingOptionDetailsForm = ({
control={form.control}
name="enabled_in_store"
label={t("stockLocations.shippingOptions.fields.enableInStore.label")}
- description={t(
- "stockLocations.shippingOptions.fields.enableInStore.hint"
- )}
+ description={t("stockLocations.shippingOptions.fields.enableInStore.hint")}
data-testid="location-shipping-option-create-details-form-enabled-in-store"
/>
</div>
</div>
)
}
+
+Root._tabMeta = defineTabMeta<CreateShippingOptionSchema>({
+ id: "details",
+ labelKey: "stockLocations.shippingOptions.create.tabs.details",
+ validationFields: [
+ "name", "price_type", "enabled_in_store", "shipping_profile_id",
+ "provider_id", "fulfillment_option_id", "shipping_option_type_id",
+ ],
+})
+
+export const CreateShippingOptionDetailsForm = Root
diff --git a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-form.tsx b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-form.tsx
index 13ebd2a0b..bbdaa4fc6 100644
--- a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-form.tsx
+++ b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-form.tsx
@@ -1,15 +1,15 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { HttpTypes } from "@medusajs/types"
-import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
-import { useForm, useWatch } from "react-hook-form"
+import { toast } from "@medusajs/ui"
+import { Children, ReactNode, useCallback, useMemo } from "react"
+import { DeepPartial, useForm, useWatch } from "react-hook-form"
import { useTranslation } from "react-i18next"
+import { z } from "zod"
-import { useState } from "react"
-import {
- RouteFocusModal,
- useRouteModal,
-} from "../../../../../components/modals"
-import { KeyboundForm } from "../../../../../components/utilities/keybound-form"
+import { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { TabDefinition } from "../../../../../components/tabbed-form/types"
+import { useFulfillmentProviderOptions } from "../../../../../hooks/api"
import { useCreateShippingOptions } from "../../../../../hooks/api/shipping-options"
import { castNumber } from "../../../../../lib/cast-number"
import {
@@ -19,23 +19,18 @@ import {
import { buildShippingOptionPriceRules } from "../../../common/utils/price-rule-helpers"
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"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
+import { CreateShippingOptionSchema } from "./schema"
-enum Tab {
- DETAILS = "details",
- PRICING = "pricing",
-}
+export type CreateShippingOptionSchemaType = z.infer<typeof CreateShippingOptionSchema>
type CreateShippingOptionFormProps = {
zone: HttpTypes.AdminServiceZone
locationId: string
isReturn?: boolean
type: FulfillmentSetType
+ children?: ReactNode
+ schema?: z.ZodType<CreateShippingOptionSchemaType>
+ defaultValues?: DeepPartial<CreateShippingOptionSchemaType>
}
export function CreateShippingOptionsForm({
@@ -43,14 +38,14 @@ export function CreateShippingOptionsForm({
isReturn,
locationId,
type,
+ children,
+ schema,
+ defaultValues: extraDefaults,
}: CreateShippingOptionFormProps) {
- const [activeTab, setActiveTab] = useState<Tab>(Tab.DETAILS)
- const [validDetails, setValidDetails] = useState(false)
-
const { t } = useTranslation()
const { handleSuccess } = useRouteModal()
- const direction = useDocumentDirection()
- const form = useForm<CreateShippingOptionSchema>({
+
+ const form = useForm<CreateShippingOptionSchemaType>({
defaultValues: {
name: "",
price_type: ShippingOptionPriceType.FlatRate,
@@ -62,8 +57,9 @@ export function CreateShippingOptionsForm({
currency_prices: {},
conditional_region_prices: {},
conditional_currency_prices: {},
- },
- resolver: zodResolver(CreateShippingOptionSchema),
+ ...extraDefaults,
+ } as CreateShippingOptionSchemaType,
+ resolver: zodResolver(schema ?? CreateShippingOptionSchema),
})
const selectedProviderId = useWatch({
@@ -76,8 +72,12 @@ export function CreateShippingOptionsForm({
enabled: !!selectedProviderId,
})
- const isCalculatedPriceType =
- form.watch("price_type") === ShippingOptionPriceType.Calculated
+ const watchedPriceType = useWatch({
+ control: form.control,
+ name: "price_type",
+ })
+
+ const isCalculatedPriceType = watchedPriceType === ShippingOptionPriceType.Calculated
const { mutateAsync, isPending: isLoading } = useCreateShippingOptions()
@@ -87,7 +87,6 @@ export function CreateShippingOptionsForm({
if (!value) {
return undefined
}
-
return {
currency_code: code,
amount: castNumber(value),
@@ -100,7 +99,6 @@ export function CreateShippingOptionsForm({
if (!value) {
return undefined
}
-
return {
region_id,
amount: castNumber(value),
@@ -111,27 +109,27 @@ export function CreateShippingOptionsForm({
const conditionalRegionPrices = Object.entries(
data.conditional_region_prices
).flatMap(([region_id, value]) => {
- const prices: HttpTypes.AdminCreateShippingOptionPriceWithRegion[] =
+ const prices =
value?.map((rule) => ({
region_id: region_id,
amount: castNumber(rule.amount),
rules: buildShippingOptionPriceRules(rule),
})) || []
- return prices?.filter(Boolean)
+ return prices?.filter(Boolean) as HttpTypes.AdminCreateShippingOptionPriceWithRegion[]
})
const conditionalCurrencyPrices = Object.entries(
data.conditional_currency_prices
).flatMap(([currency_code, value]) => {
- const prices: HttpTypes.AdminCreateShippingOptionPriceWithCurrency[] =
+ const prices =
value?.map((rule) => ({
currency_code,
amount: castNumber(rule.amount),
rules: buildShippingOptionPriceRules(rule),
})) || []
- return prices?.filter(Boolean)
+ return prices?.filter(Boolean) as HttpTypes.AdminCreateShippingOptionPriceWithCurrency[]
})
const allPrices = [
@@ -142,7 +140,7 @@ export function CreateShippingOptionsForm({
]
const fulfillmentOptionData = fulfillmentProviderOptions?.find(
- (fo) => fo.id === data.fulfillment_option_id
+ (fo: { id: string }) => fo.id === data.fulfillment_option_id
)
await mutateAsync(
@@ -156,13 +154,11 @@ export function CreateShippingOptionsForm({
data: fulfillmentOptionData as unknown as Record<string, unknown>,
rules: [
{
- // eslint-disable-next-line
value: isReturn ? "true" : "false",
attribute: "is_return",
operator: "eq",
},
{
- // eslint-disable-next-line
value: data.enabled_in_store ? "true" : "false",
attribute: "enabled_in_store",
operator: "eq",
@@ -189,179 +185,47 @@ export function CreateShippingOptionsForm({
)
})
- 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,
+ const transformTabs = useCallback(
+ (tabs: TabDefinition<CreateShippingOptionSchemaType>[]) => {
+ return tabs.map((tab) => {
+ if (tab.id === "pricing") {
+ return {
+ ...tab,
+ isVisible: () => !isCalculatedPriceType,
}
- )
-
- setValidDetails(false)
-
- return
- }
-
- setValidDetails(true)
- }
-
- setActiveTab(tab)
- }
+ }
+ return tab
+ })
+ },
+ [isCalculatedPriceType]
+ )
- const pricesStatus: ProgressStatus =
- form.getFieldState("currency_prices")?.isDirty ||
- form.getFieldState("region_prices")?.isDirty ||
- activeTab === Tab.PRICING
- ? "in-progress"
- : "not-started"
+ const defaultTabs = useMemo(
+ () => [
+ <CreateShippingOptionDetailsForm
+ key="details"
+ zone={zone}
+ isReturn={isReturn}
+ type={type}
+ locationId={locationId}
+ fulfillmentProviderOptions={fulfillmentProviderOptions || []}
+ selectedProviderId={selectedProviderId}
+ />,
+ <CreateShippingOptionsPricesForm key="pricing" type={type} />,
+ ],
+ [zone, isReturn, type, locationId, fulfillmentProviderOptions, selectedProviderId]
+ )
- const detailsStatus: ProgressStatus = validDetails
- ? "completed"
- : "in-progress"
+ const hasCustomChildren = Children.count(children) > 0
return (
- <RouteFocusModal.Form form={form} data-testid="location-shipping-option-create-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
- dir={direction}
- value={activeTab}
- className="flex h-full flex-col overflow-hidden"
- onValueChange={(tab) => onTabChange(tab as Tab)}
- data-testid="location-shipping-option-create-progress-tabs"
- >
- <RouteFocusModal.Header data-testid="location-shipping-option-create-form-header">
- <ProgressTabs.List className="border-ui-border-base -my-2 ml-2 min-w-0 flex-1 border-l" data-testid="location-shipping-option-create-progress-tabs-list">
- <ProgressTabs.Trigger
- value={Tab.DETAILS}
- status={detailsStatus}
- className="w-full max-w-[200px]"
- data-testid="location-shipping-option-create-details-tab"
- >
- <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]"
- data-testid="location-shipping-option-create-pricing-tab"
- >
- <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" data-testid="location-shipping-option-create-form-body">
- <ProgressTabs.Content
- value={Tab.DETAILS}
- className="size-full overflow-y-auto"
- data-testid="location-shipping-option-create-details-tab-content"
- >
- <CreateShippingOptionDetailsForm
- form={form}
- zone={zone}
- isReturn={isReturn}
- type={type}
- locationId={locationId}
- fulfillmentProviderOptions={fulfillmentProviderOptions || []}
- selectedProviderId={selectedProviderId}
- />
- </ProgressTabs.Content>
- <ProgressTabs.Content value={Tab.PRICING} className="size-full" data-testid="location-shipping-option-create-pricing-tab-content">
- <CreateShippingOptionsPricesForm form={form} type={type} />
- </ProgressTabs.Content>
- </RouteFocusModal.Body>
- <RouteFocusModal.Footer data-testid="location-shipping-option-create-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button variant="secondary" size="small" data-testid="location-shipping-option-create-form-cancel-button">
- {t("actions.cancel")}
- </Button>
- </RouteFocusModal.Close>
- {activeTab === Tab.PRICING || isCalculatedPriceType ? (
- <Button
- size="small"
- className="whitespace-nowrap"
- isLoading={isLoading}
- key="submit-btn"
- type="submit"
- data-testid="location-shipping-option-create-form-save-button"
- >
- {t("actions.save")}
- </Button>
- ) : (
- <Button
- size="small"
- className="whitespace-nowrap"
- isLoading={isLoading}
- onClick={() => onTabChange(Tab.PRICING)}
- key="continue-btn"
- type="button"
- data-testid="location-shipping-option-create-form-continue-button"
- >
- {t("actions.continue")}
- </Button>
- )}
- </div>
- </RouteFocusModal.Footer>
- </ProgressTabs>
- </KeyboundForm>
- </RouteFocusModal.Form>
+ <TabbedForm
+ form={form}
+ onSubmit={handleSubmit}
+ isLoading={isLoading}
+ transformTabs={transformTabs}
+ >
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
)
}
diff --git a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-prices-form.tsx b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-prices-form.tsx
index 315019378..54c1b647a 100644
--- a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-prices-form.tsx
+++ b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/components/create-shipping-options-form/create-shipping-options-prices-form.tsx
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { DataGrid } from "../../../../../components/data-grid"
import {
@@ -7,6 +7,8 @@ import {
useRouteModal,
useStackedModal,
} from "../../../../../components/modals"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { usePricePreferences } from "../../../../../hooks/api/price-preferences"
import { useRegions } from "../../../../../hooks/api/regions"
import { useStore } from "../../../../../hooks/api/store"
@@ -21,15 +23,12 @@ import { ConditionalPriceInfo } from "../../../common/types"
import { CreateShippingOptionSchema } from "./schema"
type PricingPricesFormProps = {
- form: UseFormReturn<CreateShippingOptionSchema>
type: FulfillmentSetType
}
-export const CreateShippingOptionsPricesForm = ({
- form,
- type,
-}: PricingPricesFormProps) => {
+const Root = ({ type }: PricingPricesFormProps) => {
const isPickup = type === FulfillmentSetType.Pickup
+ const form = useTabbedForm<CreateShippingOptionSchema>()
const { getIsOpen, setIsOpen } = useStackedModal()
const [selectedPrice, setSelectedPrice] =
useState<ConditionalPriceInfo | null>(null)
@@ -86,9 +85,6 @@ export const CreateShippingOptionsPricesForm = ({
[currencies, regions]
)
- /**
- * Prefill prices with 0 if createing a pickup (shipping) option
- */
useEffect(() => {
if (!isLoading && isPickup) {
if (currencies.length > 0) {
@@ -145,3 +141,11 @@ export const CreateShippingOptionsPricesForm = ({
</StackedFocusModal>
)
}
+
+Root._tabMeta = defineTabMeta<CreateShippingOptionSchema>({
+ id: "pricing",
+ labelKey: "stockLocations.shippingOptions.create.tabs.prices",
+ validationFields: ["region_prices", "currency_prices", "conditional_region_prices", "conditional_currency_prices"],
+})
+
+export const CreateShippingOptionsPricesForm = Root
diff --git a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/location-service-zone-shipping-option-create.tsx b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/location-service-zone-shipping-option-create.tsx
index daa8e6cb6..606f48f52 100644
--- a/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/location-service-zone-shipping-option-create.tsx
+++ b/packages/admin/src/pages/locations/location-service-zone-shipping-option-create/location-service-zone-shipping-option-create.tsx
@@ -1,12 +1,20 @@
+import { Children, ReactNode } from "react"
import { useParams, useSearchParams } from "react-router-dom"
import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
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 "../common/constants"
+import {
+ CreateShippingOptionsForm,
+ CreateShippingOptionSchemaType,
+} from "./components/create-shipping-options-form"
+import { CreateShippingOptionDetailsForm } from "./components/create-shipping-options-form/create-shipping-option-details-form"
+import { CreateShippingOptionsPricesForm } from "./components/create-shipping-options-form/create-shipping-options-prices-form"
+import { CreateShippingOptionSchema } from "./components/create-shipping-options-form/schema"
+import { LOC_CREATE_SHIPPING_OPTION_FIELDS } from "./constants"
-export function LocationServiceZoneShippingOptionCreate() {
+const Root = ({ children }: { children?: ReactNode }) => {
const { location_id, fset_id, zone_id } = useParams()
const [searchParams] = useSearchParams()
const isReturn = searchParams.has("is_return")
@@ -43,13 +51,30 @@ export function LocationServiceZoneShippingOptionCreate() {
return (
<RouteFocusModal prev={`/settings/locations/${location_id}`} data-testid="location-shipping-option-create-modal">
{zone && (
- <CreateShippingOptionsForm
- zone={zone}
- isReturn={isReturn}
- locationId={location_id!}
- type={fulfillmentSet!.type as FulfillmentSetType}
- />
+ Children.count(children) > 0 ? (
+ children
+ ) : (
+ <CreateShippingOptionsForm
+ zone={zone}
+ isReturn={isReturn}
+ locationId={location_id!}
+ type={fulfillmentSet!.type as FulfillmentSetType}
+ />
+ )
)}
</RouteFocusModal>
)
}
+
+export const ShippingOptionCreatePage = Object.assign(Root, {
+ Form: CreateShippingOptionsForm,
+ DetailsTab: CreateShippingOptionDetailsForm,
+ PricingTab: CreateShippingOptionsPricesForm,
+ Tab: TabbedForm.Tab,
+})
+
+export type { CreateShippingOptionSchemaType }
+export { CreateShippingOptionSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const LocationServiceZoneShippingOptionCreate = Root
diff --git a/packages/admin/src/pages/price-lists/index.ts b/packages/admin/src/pages/price-lists/index.ts
index 2b72a0a42..04b28cb90 100644
--- a/packages/admin/src/pages/price-lists/index.ts
+++ b/packages/admin/src/pages/price-lists/index.ts
@@ -1,2 +1,4 @@
export { PriceListListPage } from "./price-list-list/price-list-list"
export { PriceListDetailPage } from "./price-list-detail/price-list-detail"
+export { PriceListCreatePage, PricingCreateSchema } from "./price-list-create/price-list-create"
+export { PriceListPricesAddPage, PriceListPricesAddSchema } from "./price-list-prices-add/price-list-prices-add"
diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx
index 14d54e54e..3c224903d 100644
--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-create-form.tsx
@@ -1,65 +1,42 @@
import { zodResolver } from "@hookform/resolvers/zod"
-import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
-import { FieldPath, useForm } from "react-hook-form"
+import { toast } from "@medusajs/ui"
+import { Children, ReactNode, useMemo } from "react"
+import { DeepPartial, useForm } from "react-hook-form"
import { useTranslation } from "react-i18next"
+import { z } from "zod"
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 { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
import { useCreatePriceList } from "../../../../../hooks/api/price-lists"
import { exctractPricesFromProducts } from "../../../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"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
-
-enum Tab {
- DETAIL = "detail",
- PRODUCT = "product",
- PRICE = "price",
-}
-
-const tabOrder = [Tab.DETAIL, Tab.PRODUCT, Tab.PRICE] as const
+import { PricingCreateSchema, PricingCreateSchemaType } from "./schema"
-type TabState = Record<Tab, ProgressStatus>
-
-const initialTabState: TabState = {
- [Tab.DETAIL]: "in-progress",
- [Tab.PRODUCT]: "not-started",
- [Tab.PRICE]: "not-started",
-}
+export type { PricingCreateSchemaType }
type PriceListCreateFormProps = {
regions: HttpTypes.AdminRegion[]
currencies: HttpTypes.AdminStoreCurrency[]
pricePreferences: HttpTypes.AdminPricePreference[]
+ children?: ReactNode
+ schema?: z.ZodType<PricingCreateSchemaType>
+ defaultValues?: DeepPartial<PricingCreateSchemaType>
}
export const PriceListCreateForm = ({
regions,
currencies,
pricePreferences,
+ children,
+ schema,
+ defaultValues: extraDefaults,
}: PriceListCreateFormProps) => {
- const [tab, setTab] = useState<Tab>(Tab.DETAIL)
- const [tabState, setTabState] = useState<TabState>(initialTabState)
-
const { t } = useTranslation()
const { handleSuccess } = useRouteModal()
- const direction = useDocumentDirection()
+
const form = useForm<PricingCreateSchemaType>({
defaultValues: {
type: "sale",
@@ -73,8 +50,9 @@ export const PriceListCreateForm = ({
rules: {
customer_group_id: [],
},
- },
- resolver: zodResolver(PricingCreateSchema),
+ ...extraDefaults,
+ } as PricingCreateSchemaType,
+ resolver: zodResolver(schema ?? PricingCreateSchema),
})
const { mutateAsync, isPending } = useCreatePriceList()
@@ -115,259 +93,29 @@ export const PriceListCreateForm = ({
)
})
- 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)
- ) {
- 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} data-testid="price-list-create-form">
- <ProgressTabs
- dir={direction}
- value={tab}
- onValueChange={(tab) => handleChangeTab(tab as Tab)}
- className="flex h-full flex-col overflow-hidden"
- data-testid="price-list-create-form-tabs"
- >
- <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
- <RouteFocusModal.Header data-testid="price-list-create-form-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" data-testid="price-list-create-form-tabs-list">
- <ProgressTabs.Trigger
- status={tabState.detail}
- value={Tab.DETAIL}
- data-testid="price-list-create-form-tab-details"
- >
- {t("priceLists.create.tabs.details")}
- </ProgressTabs.Trigger>
- <ProgressTabs.Trigger
- status={tabState.product}
- value={Tab.PRODUCT}
- data-testid="price-list-create-form-tab-products"
- >
- {t("priceLists.create.tabs.products")}
- </ProgressTabs.Trigger>
- <ProgressTabs.Trigger
- status={tabState.price}
- value={Tab.PRICE}
- data-testid="price-list-create-form-tab-prices"
- >
- {t("priceLists.create.tabs.prices")}
- </ProgressTabs.Trigger>
- </ProgressTabs.List>
- </div>
- </div>
- </RouteFocusModal.Header>
- <RouteFocusModal.Body className="size-full overflow-hidden" data-testid="price-list-create-form-body">
- <ProgressTabs.Content
- className="size-full overflow-y-auto"
- value={Tab.DETAIL}
- data-testid="price-list-create-form-content-details"
- >
- <PriceListDetailsForm form={form} />
- </ProgressTabs.Content>
- <ProgressTabs.Content
- className="size-full overflow-y-auto"
- value={Tab.PRODUCT}
- data-testid="price-list-create-form-content-products"
- >
- <PriceListProductsForm form={form} />
- </ProgressTabs.Content>
- <ProgressTabs.Content
- className="size-full overflow-hidden"
- value={Tab.PRICE}
- data-testid="price-list-create-form-content-prices"
- >
- <PriceListPricesForm
- form={form}
- regions={regions}
- currencies={currencies}
- pricePreferences={pricePreferences}
- />
- </ProgressTabs.Content>
- </RouteFocusModal.Body>
- <RouteFocusModal.Footer data-testid="price-list-create-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button variant="secondary" size="small" data-testid="price-list-create-form-cancel-button">
- {t("actions.cancel")}
- </Button>
- </RouteFocusModal.Close>
- <PrimaryButton
- tab={tab}
- next={handleNextTab}
- isLoading={isPending}
- />
- </div>
- </RouteFocusModal.Footer>
- </KeyboundForm>
- </ProgressTabs>
- </RouteFocusModal.Form>
+ const defaultTabs = useMemo(
+ () => [
+ <PriceListDetailsForm key="detail" />,
+ <PriceListProductsForm key="product" />,
+ <PriceListPricesForm
+ key="price"
+ currencies={currencies}
+ regions={regions}
+ pricePreferences={pricePreferences}
+ />,
+ ],
+ [currencies, regions, pricePreferences]
)
-}
-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}
- data-testid="price-list-create-form-save-button"
- >
- {t("actions.save")}
- </Button>
- )
- }
+ const hasCustomChildren = Children.count(children) > 0
return (
- <Button
- key="next-button"
- type="button"
- variant="primary"
- size="small"
- onClick={() => next(tab)}
- data-testid="price-list-create-form-continue-button"
+ <TabbedForm
+ form={form}
+ onSubmit={handleSubmit}
+ isLoading={isPending}
>
- {t("actions.continue")}
- </Button>
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
)
}
diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx
index a2dfdf0df..1dd3f78c4 100644
--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-details-form.tsx
@@ -12,25 +12,24 @@ import {
Textarea,
clx,
} from "@medusajs/ui"
-import { useFieldArray, type UseFormReturn } from "react-hook-form"
+import { useFieldArray } 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 { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
+import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
import { PriceListCustomerGroupRuleForm } from "../../../common/components/price-list-customer-group-rule-form"
import type {
PricingCreateSchemaType,
PricingCustomerGroupsArrayType,
} from "./schema"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
-type PriceListDetailsFormProps = {
- form: UseFormReturn<PricingCreateSchemaType>
-}
-
-export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
+const Root = () => {
const { t } = useTranslation()
+ const form = useTabbedForm<PricingCreateSchemaType>()
const direction = useDocumentDirection()
const { fields, remove, append } = useFieldArray({
control: form.control,
@@ -88,19 +87,13 @@ export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
<RadioGroup.ChoiceBox
value={"sale"}
label={t("priceLists.fields.type.options.sale.label")}
- description={t(
- "priceLists.fields.type.options.sale.description"
- )}
+ description={t("priceLists.fields.type.options.sale.description")}
data-testid="price-list-details-form-type-option-sale"
/>
<RadioGroup.ChoiceBox
value={"override"}
- label={t(
- "priceLists.fields.type.options.override.label"
- )}
- description={t(
- "priceLists.fields.type.options.override.description"
- )}
+ label={t("priceLists.fields.type.options.override.label")}
+ description={t("priceLists.fields.type.options.override.description")}
data-testid="price-list-details-form-type-option-override"
/>
</RadioGroup>
@@ -116,126 +109,116 @@ export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
<Form.Field
control={form.control}
name="title"
- render={({ field }) => {
- return (
- <Form.Item data-testid="price-list-details-form-title-item">
- <Form.Label data-testid="price-list-details-form-title-label">{t("fields.title")}</Form.Label>
- <Form.Control data-testid="price-list-details-form-title-control">
- <Input {...field} data-testid="price-list-details-form-title-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="price-list-details-form-title-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="price-list-details-form-title-item">
+ <Form.Label data-testid="price-list-details-form-title-label">{t("fields.title")}</Form.Label>
+ <Form.Control data-testid="price-list-details-form-title-control">
+ <Input {...field} data-testid="price-list-details-form-title-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="price-list-details-form-title-error" />
+ </Form.Item>
+ )}
/>
<Form.Field
control={form.control}
name="status"
- render={({ field: { onChange, ref, ...field } }) => {
- return (
- <Form.Item data-testid="price-list-details-form-status-item">
- <Form.Label data-testid="price-list-details-form-status-label">
- {t("priceLists.fields.status.label")}
- </Form.Label>
- <Form.Control data-testid="price-list-details-form-status-control">
- <Select
- dir={direction}
- {...field}
- onValueChange={onChange}
- data-testid="price-list-details-form-status-select"
- >
- <Select.Trigger ref={ref} data-testid="price-list-details-form-status-trigger">
- <Select.Value data-testid="price-list-details-form-status-value" />
- </Select.Trigger>
- <Select.Content data-testid="price-list-details-form-status-content">
- <Select.Item value="active" data-testid="price-list-details-form-status-option-active">
- {t("priceLists.fields.status.options.active")}
- </Select.Item>
- <Select.Item value="draft" data-testid="price-list-details-form-status-option-draft">
- {t("priceLists.fields.status.options.draft")}
- </Select.Item>
- </Select.Content>
- </Select>
- </Form.Control>
- <Form.ErrorMessage data-testid="price-list-details-form-status-error" />
- </Form.Item>
- )
- }}
+ render={({ field: { onChange, ref, ...field } }) => (
+ <Form.Item data-testid="price-list-details-form-status-item">
+ <Form.Label data-testid="price-list-details-form-status-label">
+ {t("priceLists.fields.status.label")}
+ </Form.Label>
+ <Form.Control data-testid="price-list-details-form-status-control">
+ <Select
+ dir={direction}
+ {...field}
+ onValueChange={onChange}
+ data-testid="price-list-details-form-status-select"
+ >
+ <Select.Trigger ref={ref} data-testid="price-list-details-form-status-trigger">
+ <Select.Value data-testid="price-list-details-form-status-value" />
+ </Select.Trigger>
+ <Select.Content data-testid="price-list-details-form-status-content">
+ <Select.Item value="active" data-testid="price-list-details-form-status-option-active">
+ {t("priceLists.fields.status.options.active")}
+ </Select.Item>
+ <Select.Item value="draft" data-testid="price-list-details-form-status-option-draft">
+ {t("priceLists.fields.status.options.draft")}
+ </Select.Item>
+ </Select.Content>
+ </Select>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="price-list-details-form-status-error" />
+ </Form.Item>
+ )}
/>
</div>
<Form.Field
control={form.control}
name="description"
- render={({ field }) => {
- return (
- <Form.Item data-testid="price-list-details-form-description-item">
- <Form.Label data-testid="price-list-details-form-description-label">{t("fields.description")}</Form.Label>
- <Form.Control data-testid="price-list-details-form-description-control">
- <Textarea {...field} data-testid="price-list-details-form-description-input" />
- </Form.Control>
- <Form.ErrorMessage data-testid="price-list-details-form-description-error" />
- </Form.Item>
- )
- }}
+ render={({ field }) => (
+ <Form.Item data-testid="price-list-details-form-description-item">
+ <Form.Label data-testid="price-list-details-form-description-label">{t("fields.description")}</Form.Label>
+ <Form.Control data-testid="price-list-details-form-description-control">
+ <Textarea {...field} data-testid="price-list-details-form-description-input" />
+ </Form.Control>
+ <Form.ErrorMessage data-testid="price-list-details-form-description-error" />
+ </Form.Item>
+ )}
/>
</div>
<Divider />
<Form.Field
control={form.control}
name="starts_at"
- render={({ field }) => {
- return (
- <Form.Item data-testid="price-list-details-form-starts-at-item">
- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
- <div className="flex flex-col">
- <Form.Label optional data-testid="price-list-details-form-starts-at-label">
- {t("priceLists.fields.startsAt.label")}
- </Form.Label>
- <Form.Hint data-testid="price-list-details-form-starts-at-hint">
- {t("priceLists.fields.startsAt.hint")}
- </Form.Hint>
- </div>
- <Form.Control data-testid="price-list-details-form-starts-at-control">
- <DatePicker
- granularity="minute"
- shouldCloseOnSelect={false}
- {...field}
- data-testid="price-list-details-form-starts-at-input"
- />
- </Form.Control>
+ render={({ field }) => (
+ <Form.Item data-testid="price-list-details-form-starts-at-item">
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <div className="flex flex-col">
+ <Form.Label optional data-testid="price-list-details-form-starts-at-label">
+ {t("priceLists.fields.startsAt.label")}
+ </Form.Label>
+ <Form.Hint data-testid="price-list-details-form-starts-at-hint">
+ {t("priceLists.fields.startsAt.hint")}
+ </Form.Hint>
</div>
- <Form.ErrorMessage data-testid="price-list-details-form-starts-at-error" />
- </Form.Item>
- )
- }}
+ <Form.Control data-testid="price-list-details-form-starts-at-control">
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ data-testid="price-list-details-form-starts-at-input"
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage data-testid="price-list-details-form-starts-at-error" />
+ </Form.Item>
+ )}
/>
<Divider />
<Form.Field
control={form.control}
name="ends_at"
- render={({ field }) => {
- return (
- <Form.Item data-testid="price-list-details-form-ends-at-item">
- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
- <div className="flex flex-col">
- <Form.Label optional data-testid="price-list-details-form-ends-at-label">
- {t("priceLists.fields.endsAt.label")}
- </Form.Label>
- <Form.Hint data-testid="price-list-details-form-ends-at-hint">{t("priceLists.fields.endsAt.hint")}</Form.Hint>
- </div>
- <Form.Control data-testid="price-list-details-form-ends-at-control">
- <DatePicker
- granularity="minute"
- shouldCloseOnSelect={false}
- {...field}
- data-testid="price-list-details-form-ends-at-input"
- />
- </Form.Control>
+ render={({ field }) => (
+ <Form.Item data-testid="price-list-details-form-ends-at-item">
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <div className="flex flex-col">
+ <Form.Label optional data-testid="price-list-details-form-ends-at-label">
+ {t("priceLists.fields.endsAt.label")}
+ </Form.Label>
+ <Form.Hint data-testid="price-list-details-form-ends-at-hint">{t("priceLists.fields.endsAt.hint")}</Form.Hint>
</div>
- <Form.ErrorMessage data-testid="price-list-details-form-ends-at-error" />
- </Form.Item>
- )
- }}
+ <Form.Control data-testid="price-list-details-form-ends-at-control">
+ <DatePicker
+ granularity="minute"
+ shouldCloseOnSelect={false}
+ {...field}
+ data-testid="price-list-details-form-ends-at-input"
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage data-testid="price-list-details-form-ends-at-error" />
+ </Form.Item>
+ )}
/>
<Divider />
<Form.Field
@@ -279,9 +262,7 @@ export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
data-testid="price-list-details-form-customer-group-search-button"
>
<MagnifyingGlass />
- {t(
- "priceLists.fields.customerAvailability.placeholder"
- )}
+ {t("priceLists.fields.customerAvailability.placeholder")}
</button>
</StackedFocusModal.Trigger>
<StackedFocusModal.Trigger asChild>
@@ -339,3 +320,11 @@ export const PriceListDetailsForm = ({ form }: PriceListDetailsFormProps) => {
</div>
)
}
+
+Root._tabMeta = defineTabMeta<PricingCreateSchemaType>({
+ id: "detail",
+ labelKey: "priceLists.create.tabs.details",
+ validationFields: ["type", "title", "description", "starts_at", "ends_at"],
+})
+
+export const PriceListDetailsForm = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx
index 932222d3d..29243afc6 100644
--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-prices-form.tsx
@@ -1,8 +1,10 @@
import { HttpTypes } from "@medusajs/types"
import { useEffect } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { DataGrid } from "../../../../../components/data-grid"
import { useRouteModal } from "../../../../../components/modals"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { useProducts } from "../../../../../hooks/api/products"
import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"
import { PriceListCreateProductVariantsSchema } from "../../../common/schemas"
@@ -10,18 +12,18 @@ import { isProductRow } from "../../../common/utils"
import { PricingCreateSchemaType } from "./schema"
type PriceListPricesFormProps = {
- form: UseFormReturn<PricingCreateSchemaType>
currencies: HttpTypes.AdminStoreCurrency[]
regions: HttpTypes.AdminRegion[]
pricePreferences: HttpTypes.AdminPricePreference[]
}
-export const PriceListPricesForm = ({
- form,
+const Root = ({
currencies,
regions,
pricePreferences,
}: PriceListPricesFormProps) => {
+ const form = useTabbedForm<PricingCreateSchemaType>()
+
const ids = useWatch({
control: form.control,
name: "product_ids",
@@ -45,9 +47,6 @@ export const PriceListPricesForm = ({
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
}
@@ -92,3 +91,11 @@ export const PriceListPricesForm = ({
</div>
)
}
+
+Root._tabMeta = defineTabMeta<PricingCreateSchemaType>({
+ id: "price",
+ labelKey: "priceLists.create.tabs.prices",
+ validationFields: ["products"],
+})
+
+export const PriceListPricesForm = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx
index 0017b85f4..7767fc1c6 100644
--- a/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-create/components/price-list-create-form/price-list-products-form.tsx
@@ -7,10 +7,12 @@ import {
createColumnHelper,
} from "@tanstack/react-table"
import { useMemo, useState } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { _DataTable } from "../../../../../components/table/data-table"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
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"
@@ -19,23 +21,20 @@ import { useDataTable } from "../../../../../hooks/use-data-table"
import { PriceListCreateProductsSchema } from "../../../common/schemas"
import { PricingCreateSchemaType } from "./schema"
-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 Root = () => {
const { t } = useTranslation()
+ const form = useTabbedForm<PricingCreateSchemaType>()
const { control, setValue } = form
const selectedIds = useWatch({
@@ -81,10 +80,6 @@ export const PriceListProductsForm = ({ form }: PriceListProductsFormProps) => {
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,
@@ -186,3 +181,11 @@ const useColumns = () => {
[base]
)
}
+
+Root._tabMeta = defineTabMeta<PricingCreateSchemaType>({
+ id: "product",
+ labelKey: "priceLists.create.tabs.products",
+ validationFields: ["product_ids"],
+})
+
+export const PriceListProductsForm = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-create/price-list-create.tsx b/packages/admin/src/pages/price-lists/price-list-create/price-list-create.tsx
index 3ab775488..2b30ddd1e 100644
--- a/packages/admin/src/pages/price-lists/price-list-create/price-list-create.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-create/price-list-create.tsx
@@ -1,20 +1,45 @@
+import { Children, ReactNode } from "react"
+
import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
import { usePriceListCurrencyData } from "../common/hooks/use-price-list-currency-data"
import { PriceListCreateForm } from "./components/price-list-create-form"
+import { PriceListDetailsForm } from "./components/price-list-create-form/price-list-details-form"
+import { PriceListProductsForm } from "./components/price-list-create-form/price-list-products-form"
+import { PriceListPricesForm } from "./components/price-list-create-form/price-list-prices-form"
+import { PricingCreateSchema, PricingCreateSchemaType } from "./components/price-list-create-form/schema"
-export const PriceListCreate = () => {
+const Root = ({ children }: { children?: ReactNode }) => {
const { isReady, regions, currencies, pricePreferences } =
usePriceListCurrencyData()
return (
<RouteFocusModal>
{isReady && (
- <PriceListCreateForm
- regions={regions}
- currencies={currencies}
- pricePreferences={pricePreferences}
- />
+ Children.count(children) > 0 ? (
+ children
+ ) : (
+ <PriceListCreateForm
+ regions={regions}
+ currencies={currencies}
+ pricePreferences={pricePreferences}
+ />
+ )
)}
</RouteFocusModal>
)
}
+
+export const PriceListCreatePage = Object.assign(Root, {
+ Form: PriceListCreateForm,
+ DetailsTab: PriceListDetailsForm,
+ ProductsTab: PriceListProductsForm,
+ PricesTab: PriceListPricesForm,
+ Tab: TabbedForm.Tab,
+})
+
+export type { PricingCreateSchemaType }
+export { PricingCreateSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const PriceListCreate = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx
index 8621d1239..b2b877056 100644
--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-form.tsx
@@ -1,47 +1,29 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { HttpTypes } from "@medusajs/types"
-import { Button, ProgressStatus, ProgressTabs, toast } from "@medusajs/ui"
-import { useState } from "react"
-import { FieldPath, useForm } from "react-hook-form"
+import { toast } from "@medusajs/ui"
+import { Children, ReactNode, useMemo } from "react"
+import { DeepPartial, 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 { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
import { useBatchPriceListPrices } 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"
-import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
+import { PriceListPricesAddSchema } from "./schema"
+
+export type PriceListPricesAddSchemaType = z.infer<typeof PriceListPricesAddSchema>
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",
+ children?: ReactNode
+ schema?: z.ZodType<PriceListPricesAddSchemaType>
+ defaultValues?: DeepPartial<PriceListPricesAddSchemaType>
}
export const PriceListPricesAddForm = ({
@@ -49,19 +31,20 @@ export const PriceListPricesAddForm = ({
regions,
currencies,
pricePreferences,
+ children,
+ schema,
+ defaultValues: extraDefaults,
}: PriceListPricesAddFormProps) => {
- const [tab, setTab] = useState<Tab>(Tab.PRODUCT)
- const [tabState, setTabState] = useState<TabState>(initialTabState)
-
const { t } = useTranslation()
const { handleSuccess } = useRouteModal()
- const direction = useDocumentDirection()
- const form = useForm<PriceListPricesAddSchema>({
+
+ const form = useForm<PriceListPricesAddSchemaType>({
defaultValues: {
products: {},
product_ids: [],
- },
- resolver: zodResolver(PriceListPricesAddSchema),
+ ...extraDefaults,
+ } as PriceListPricesAddSchemaType,
+ resolver: zodResolver(schema ?? PriceListPricesAddSchema),
})
const { mutateAsync, isPending } = useBatchPriceListPrices(priceList.id)
@@ -85,230 +68,28 @@ export const PriceListPricesAddForm = ({
)
})
- const partialFormValidation = (
- fields: FieldPath<PriceListPricesAddSchema>[],
- schema: z.ZodSchema<unknown>
- ) => {
- 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} data-testid="price-list-prices-add-form">
- <ProgressTabs
- dir={direction}
- value={tab}
- onValueChange={(tab) => handleChangeTab(tab as Tab)}
- className="flex h-full flex-col overflow-hidden"
- data-testid="price-list-prices-add-form-tabs"
- >
- <KeyboundForm onSubmit={handleSubmit} className="flex h-full flex-col">
- <RouteFocusModal.Header data-testid="price-list-prices-add-form-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" data-testid="price-list-prices-add-form-tabs-list">
- <ProgressTabs.Trigger
- status={tabState.product}
- value={Tab.PRODUCT}
- data-testid="price-list-prices-add-form-tab-products"
- >
- {t("priceLists.create.tabs.products")}
- </ProgressTabs.Trigger>
- <ProgressTabs.Trigger
- status={tabState.price}
- value={Tab.PRICE}
- data-testid="price-list-prices-add-form-tab-prices"
- >
- {t("priceLists.create.tabs.prices")}
- </ProgressTabs.Trigger>
- </ProgressTabs.List>
- </div>
- </div>
- </RouteFocusModal.Header>
- <RouteFocusModal.Body className="size-full overflow-hidden" data-testid="price-list-prices-add-form-body">
- <ProgressTabs.Content
- className="size-full overflow-y-auto"
- value={Tab.PRODUCT}
- data-testid="price-list-prices-add-form-content-products"
- >
- <PriceListPricesAddProductIdsForm
- form={form}
- priceList={priceList}
- />
- </ProgressTabs.Content>
- <ProgressTabs.Content
- className="size-full overflow-hidden"
- value={Tab.PRICE}
- data-testid="price-list-prices-add-form-content-prices"
- >
- <PriceListPricesAddPricesForm
- form={form}
- regions={regions}
- currencies={currencies}
- pricePreferences={pricePreferences}
- />
- </ProgressTabs.Content>
- </RouteFocusModal.Body>
- <RouteFocusModal.Footer data-testid="price-list-prices-add-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button variant="secondary" size="small" data-testid="price-list-prices-add-form-cancel-button">
- {t("actions.cancel")}
- </Button>
- </RouteFocusModal.Close>
- <PrimaryButton
- tab={tab}
- next={handleNextTab}
- isLoading={isPending}
- />
- </div>
- </RouteFocusModal.Footer>
- </KeyboundForm>
- </ProgressTabs>
- </RouteFocusModal.Form>
+ const defaultTabs = useMemo(
+ () => [
+ <PriceListPricesAddProductIdsForm key="product" priceList={priceList} />,
+ <PriceListPricesAddPricesForm
+ key="price"
+ currencies={currencies}
+ regions={regions}
+ pricePreferences={pricePreferences}
+ />,
+ ],
+ [priceList, currencies, regions, pricePreferences]
)
-}
-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}
- data-testid="price-list-prices-add-form-save-button"
- >
- {t("actions.save")}
- </Button>
- )
- }
+ const hasCustomChildren = Children.count(children) > 0
return (
- <Button
- key="next-button"
- type="button"
- variant="primary"
- size="small"
- onClick={() => next(tab)}
- data-testid="price-list-prices-add-form-continue-button"
+ <TabbedForm
+ form={form}
+ onSubmit={handleSubmit}
+ isLoading={isPending}
>
- {t("actions.continue")}
- </Button>
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
)
}
diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
index 513fdf834..bd46fceb4 100644
--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-prices-form.tsx
@@ -1,9 +1,11 @@
import { HttpTypes } from "@medusajs/types"
import { useEffect } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { DataGrid } from "../../../../../components/data-grid"
import { useRouteModal } from "../../../../../components/modals"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
import { useProducts } from "../../../../../hooks/api/products"
import { usePriceListGridColumns } from "../../../common/hooks/use-price-list-grid-columns"
import { PriceListCreateProductVariantsSchema } from "../../../common/schemas"
@@ -11,18 +13,18 @@ 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,
+const Root = ({
currencies,
regions,
pricePreferences,
}: PriceListPricesAddPricesFormProps) => {
+ const form = useTabbedForm<PriceListPricesAddSchema>()
+
const ids = useWatch({
control: form.control,
name: "product_ids",
@@ -46,9 +48,6 @@ export const PriceListPricesAddPricesForm = ({
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
}
@@ -93,3 +92,11 @@ export const PriceListPricesAddPricesForm = ({
</div>
)
}
+
+Root._tabMeta = defineTabMeta<PriceListPricesAddSchema>({
+ id: "price",
+ labelKey: "priceLists.create.tabs.prices",
+ validationFields: ["products"],
+})
+
+export const PriceListPricesAddPricesForm = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
index 5237a3819..5437c28aa 100644
--- a/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/components/price-list-prices-add-form/price-list-prices-add-product-ids-form.tsx
@@ -7,9 +7,11 @@ import {
createColumnHelper,
} from "@tanstack/react-table"
import { useMemo, useState } from "react"
-import { UseFormReturn, useWatch } from "react-hook-form"
+import { useWatch } from "react-hook-form"
import { useTranslation } from "react-i18next"
import { _DataTable } from "../../../../../components/table/data-table"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
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"
@@ -19,7 +21,6 @@ import { PriceListCreateProductsSchema } from "../../../common/schemas"
import { PriceListPricesAddSchema } from "./schema"
type PriceListPricesAddProductIdsFormProps = {
- form: UseFormReturn<PriceListPricesAddSchema>
priceList: HttpTypes.AdminPriceList
}
@@ -29,16 +30,16 @@ const PREFIX = "p"
function getInitialSelection(products: { id: string }[]) {
return products.reduce((acc, curr) => {
acc[curr.id] = true
-
+
return acc
}, {} as RowSelectionState)
}
-export const PriceListPricesAddProductIdsForm = ({
+const Root = ({
priceList,
- form,
}: PriceListPricesAddProductIdsFormProps) => {
const { t } = useTranslation()
+ const form = useTabbedForm<PriceListPricesAddSchema>()
const { control, setValue } = form
const variantIdMap = useMemo(() => {
@@ -95,10 +96,6 @@ export const PriceListPricesAddProductIdsForm = ({
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,
@@ -231,3 +228,11 @@ const useColumns = () => {
[base]
)
}
+
+Root._tabMeta = defineTabMeta<PriceListPricesAddSchema>({
+ id: "product",
+ labelKey: "priceLists.create.tabs.products",
+ validationFields: ["product_ids"],
+})
+
+export const PriceListPricesAddProductIdsForm = Root
diff --git a/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx b/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx
index 8a342eb18..251ad9337 100644
--- a/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx
+++ b/packages/admin/src/pages/price-lists/price-list-prices-add/price-list-prices-add.tsx
@@ -1,10 +1,19 @@
-import { RouteFocusModal } from "@components/modals"
+import { Children, ReactNode } from "react"
import { useParams } from "react-router-dom"
-import { PriceListPricesAddForm } from "./components/price-list-prices-add-form"
+
+import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
+import { usePriceList } from "../../../hooks/api"
import { usePriceListCurrencyData } from "../common/hooks/use-price-list-currency-data"
-import { usePriceList } from "@hooks/api"
+import {
+ PriceListPricesAddForm,
+ PriceListPricesAddSchemaType,
+} from "./components/price-list-prices-add-form"
+import { PriceListPricesAddProductIdsForm } from "./components/price-list-prices-add-form/price-list-prices-add-product-ids-form"
+import { PriceListPricesAddPricesForm } from "./components/price-list-prices-add-form/price-list-prices-add-prices-form"
+import { PriceListPricesAddSchema } from "./components/price-list-prices-add-form/schema"
-export const PriceListProductsAdd = () => {
+const Root = ({ children }: { children?: ReactNode }) => {
const { id } = useParams<{ id: string }>()
const { price_list, isPending, isError, error } = usePriceList(id!)
@@ -15,15 +24,32 @@ export const PriceListProductsAdd = () => {
if (isError) {
throw error
}
-
+
return (
<RouteFocusModal>
{ready && (
- <PriceListPricesAddForm
- priceList={price_list}
- {...currencyData}
- />
+ Children.count(children) > 0 ? (
+ children
+ ) : (
+ <PriceListPricesAddForm
+ priceList={price_list}
+ {...currencyData}
+ />
+ )
)}
</RouteFocusModal>
)
}
+
+export const PriceListPricesAddPage = Object.assign(Root, {
+ Form: PriceListPricesAddForm,
+ ProductIdsTab: PriceListPricesAddProductIdsForm,
+ PricesTab: PriceListPricesAddPricesForm,
+ Tab: TabbedForm.Tab,
+})
+
+export type { PriceListPricesAddSchemaType }
+export { PriceListPricesAddSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const PriceListProductsAdd = Root
diff --git a/packages/admin/src/pages/products/index.ts b/packages/admin/src/pages/products/index.ts
index 27354189b..89e0b9077 100644
--- a/packages/admin/src/pages/products/index.ts
+++ b/packages/admin/src/pages/products/index.ts
@@ -1,2 +1,5 @@
export { ProductListPage } from "./product-list/product-list"
export { ProductDetailPage } from "./product-detail/product-detail"
+export { ProductCreatePage } from "./product-create/product-create"
+export { ProductCreateSchema } from "./product-create/constants"
+export { ProductCreateVariantPage, CreateProductVariantSchema } from "./product-create-variant/product-create-variant"
diff --git a/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/create-product-variant-form.tsx b/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/create-product-variant-form.tsx
index 6e167c593..279587780 100644
--- a/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/create-product-variant-form.tsx
+++ b/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/create-product-variant-form.tsx
@@ -1,7 +1,7 @@
import { zodResolver } from "@hookform/resolvers/zod"
import { toast } from "@medusajs/ui"
-import { useCallback, useEffect, useMemo } from "react"
-import { useFieldArray, useForm, useWatch } from "react-hook-form"
+import { Children, ReactNode, useCallback, useEffect, useMemo } from "react"
+import { DeepPartial, useFieldArray, useForm, useWatch } from "react-hook-form"
import { z } from "zod"
import { AdminCreateProductVariantPrice, HttpTypes } from "@medusajs/types"
@@ -16,25 +16,38 @@ import DetailsTab from "./details-tab"
import InventoryKitTab from "./inventory-kit-tab"
import PricingTab from "./pricing-tab"
+export type CreateProductVariantSchemaType = z.infer<typeof CreateProductVariantSchema>
+
type CreateProductVariantFormProps = {
product: HttpTypes.AdminProduct
+ children?: ReactNode
+ schema?: z.ZodType<CreateProductVariantSchemaType>
+ defaultValues?: DeepPartial<CreateProductVariantSchemaType>
+}
+
+const CREATE_VARIANT_DEFAULTS: DeepPartial<CreateProductVariantSchemaType> = {
+ sku: "",
+ title: "",
+ manage_inventory: false,
+ allow_backorder: false,
+ inventory_kit: false,
+ options: {},
}
export const CreateProductVariantForm = ({
product,
+ children,
+ schema,
+ defaultValues: extraDefaults,
}: CreateProductVariantFormProps) => {
const { handleSuccess } = useRouteModal()
- const form = useForm<z.infer<typeof CreateProductVariantSchema>>({
+ const form = useForm<CreateProductVariantSchemaType>({
defaultValues: {
- sku: "",
- title: "",
- manage_inventory: false,
- allow_backorder: false,
- inventory_kit: false,
- options: {},
- },
- resolver: zodResolver(CreateProductVariantSchema),
+ ...CREATE_VARIANT_DEFAULTS,
+ ...extraDefaults,
+ } as CreateProductVariantSchemaType,
+ resolver: zodResolver(schema ?? CreateProductVariantSchema),
})
const { mutateAsync, isPending } = useCreateProductVariant(product.id)
@@ -148,6 +161,17 @@ export const CreateProductVariantForm = ({
)
})
+ const defaultTabs = useMemo(
+ () => [
+ <DetailsTab key="details" product={product} />,
+ <PricingTab key="pricing" />,
+ <InventoryKitTab key="inventory" />,
+ ],
+ [product]
+ )
+
+ const hasCustomChildren = Children.count(children) > 0
+
return (
<TabbedForm
form={form}
@@ -155,9 +179,7 @@ export const CreateProductVariantForm = ({
isLoading={isPending}
transformTabs={transformTabs}
>
- <DetailsTab product={product} />
- <PricingTab />
- <InventoryKitTab />
+ {hasCustomChildren ? children : defaultTabs}
</TabbedForm>
)
}
diff --git a/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/inventory-kit-tab.tsx b/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/inventory-kit-tab.tsx
index f6cebf585..04086002b 100644
--- a/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/inventory-kit-tab.tsx
+++ b/packages/admin/src/pages/products/product-create-variant/components/create-product-variant-form/inventory-kit-tab.tsx
@@ -26,12 +26,15 @@ function InventoryKitTab() {
const items = useComboboxData({
queryKey: ["inventory_items"],
+ // @ts-expect-error — Mercur SDK extension
queryFn: (params) => sdk.admin.inventoryItem.list(params),
- getOptions: (data) =>
- data.inventory_items.map((item) => ({
+ getOptions: (data) => {
+ const items = (data as unknown as { inventory_items: Array<{ title: string; id: string }> }).inventory_items
+ return items.map((item) => ({
label: item.title,
value: item.id,
- })),
+ }))
+ },
})
/**
diff --git a/packages/admin/src/pages/products/product-create-variant/product-create-variant.tsx b/packages/admin/src/pages/products/product-create-variant/product-create-variant.tsx
index d37b61060..28ce60453 100644
--- a/packages/admin/src/pages/products/product-create-variant/product-create-variant.tsx
+++ b/packages/admin/src/pages/products/product-create-variant/product-create-variant.tsx
@@ -1,9 +1,18 @@
+import { Children, ReactNode } from "react"
import { useParams } from "react-router-dom"
import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
import { useProduct } from "../../../hooks/api/products"
-import { CreateProductVariantForm } from "./components/create-product-variant-form"
+import {
+ CreateProductVariantForm,
+ CreateProductVariantSchemaType,
+} from "./components/create-product-variant-form"
+import { CreateProductVariantSchema } from "./components/create-product-variant-form/constants"
+import DetailsTab from "./components/create-product-variant-form/details-tab"
+import PricingTab from "./components/create-product-variant-form/pricing-tab"
+import InventoryKitTab from "./components/create-product-variant-form/inventory-kit-tab"
-export const ProductCreateVariant = () => {
+const Root = ({ children }: { children?: ReactNode }) => {
const { id } = useParams()
const { product, isLoading, isError, error } = useProduct(id!)
@@ -13,8 +22,28 @@ export const ProductCreateVariant = () => {
}
return (
- <RouteFocusModal>
- {!isLoading && product && <CreateProductVariantForm product={product} />}
+ <RouteFocusModal prev="../..">
+ {!isLoading && product && (
+ Children.count(children) > 0 ? (
+ children
+ ) : (
+ <CreateProductVariantForm product={product} />
+ )
+ )}
</RouteFocusModal>
)
}
+
+export const ProductCreateVariantPage = Object.assign(Root, {
+ Form: CreateProductVariantForm,
+ DetailsTab,
+ PricingTab,
+ InventoryKitTab,
+ Tab: TabbedForm.Tab,
+})
+
+export type { CreateProductVariantSchemaType }
+export { CreateProductVariantSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const ProductCreateVariant = Root
diff --git a/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx b/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
index b7fa27805..ea3b3310c 100644
--- a/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
+++ b/packages/admin/src/pages/products/product-create/components/product-create-form/product-create-form.tsx
@@ -138,15 +138,12 @@ export const ProductCreateForm = ({
}
await mutateAsync(
- {
+ normalizeProductFormValues({
...payload,
- ...normalizeProductFormValues({
- ...payload,
- media: uploadedMedia,
- status: (isDraftSubmission ? "draft" : "published") as any,
- regionsCurrencyMap,
- }),
- } as any,
+ media: uploadedMedia,
+ status: (isDraftSubmission ? "draft" : "published") as any,
+ regionsCurrencyMap,
+ }) as any,
{
onSuccess: (data) => {
toast.success(
diff --git a/packages/admin/src/pages/promotions/index.ts b/packages/admin/src/pages/promotions/index.ts
index 2d574cb46..64f96c541 100644
--- a/packages/admin/src/pages/promotions/index.ts
+++ b/packages/admin/src/pages/promotions/index.ts
@@ -1,2 +1,3 @@
export { PromotionListPage } from "./promotion-list/promotions-list"
export { PromotionDetailPage } from "./promotion-detail/promotion-detail"
+export { PromotionCreatePage, CreatePromotionSchema } from "./promotion-create/promotion-create"
diff --git a/packages/admin/src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx b/packages/admin/src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx
index d8ea8278a..9277af994 100644
--- a/packages/admin/src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx
+++ b/packages/admin/src/pages/promotions/promotion-add-campaign/components/add-campaign-promotion-form/add-campaign-promotion-form.tsx
@@ -150,6 +150,11 @@ export const AddCampaignPromotionFields = ({
></Combobox>
</Form.Control>
+ {!promotionCurrencyCode && (
+ <Form.Hint data-testid="promotion-add-campaign-form-campaign-id-hint">
+ {t("promotions.form.campaign.existing.currencyHint")}
+ </Form.Hint>
+ )}
<Form.ErrorMessage data-testid="promotion-add-campaign-form-campaign-id-error" />
</Form.Item>
)
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
index 24ce74d41..5de7ffdf1 100644
--- a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/create-promotion-form.tsx
@@ -1,98 +1,83 @@
-import { useEffect, useMemo, useState } from 'react';
+import { Children, ReactNode, useEffect, useMemo } from "react"
-import { zodResolver } from '@hookform/resolvers/zod';
+import { zodResolver } from "@hookform/resolvers/zod"
import type {
ApplicationMethodAllocationValues,
ApplicationMethodTargetTypeValues,
ApplicationMethodTypeValues,
PromotionRuleOperatorValues,
PromotionStatusValues,
- PromotionTypeValues
-} from '@medusajs/types';
-import {
- Alert,
- Badge,
- Button,
- clx,
- CurrencyInput,
- Divider,
- Heading,
- Input,
- ProgressTabs,
- RadioGroup,
- Switch,
- Text,
- toast,
- type ProgressStatus
-} from '@medusajs/ui';
-import { useForm, useWatch } from 'react-hook-form';
-import { Trans, useTranslation } from 'react-i18next';
-import type { 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 { useDocumentDirection } from '../../../../../hooks/use-document-direction';
-import { currencies, getCurrencySymbol } from '../../../../../lib/data/currencies';
-import { DEFAULT_CAMPAIGN_VALUES } from '../../../../campaigns/common/constants';
-import { RulesFormField } from '../../../common/edit-rules/components/rules-form-field';
-import { AddCampaignPromotionFields } from '../../../promotion-add-campaign/components/add-campaign-promotion-form';
-import { Tab } from './constants';
-import { CreatePromotionSchema } from './form-schema';
-import { templates } from './templates';
-
-const defaultValues = {
+ PromotionTypeValues,
+} from "@medusajs/types"
+import { toast } from "@medusajs/ui"
+import { DeepPartial, useForm, useWatch } from "react-hook-form"
+import { useTranslation } from "react-i18next"
+import { z } from "zod"
+
+import { useRouteModal } from "../../../../../components/modals"
+import { TabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { useCreatePromotion } from "../../../../../hooks/api/promotions"
+import { DEFAULT_CAMPAIGN_VALUES } from "../../../../campaigns/common/constants"
+import { CreatePromotionSchema, CreatePromotionSchemaType } from "./form-schema"
+import { PromotionCampaignTab } from "./promotion-campaign-tab"
+import { PromotionDetailsTab } from "./promotion-details-tab"
+import { PromotionTemplateTab } from "./promotion-template-tab"
+import { templates } from "./templates"
+
+const PROMOTION_CREATE_DEFAULTS = {
campaign_id: undefined,
template_id: templates[0].id!,
- campaign_choice: 'none' as const,
- is_automatic: 'false',
- code: '',
- type: 'standard' as PromotionTypeValues,
- status: 'draft' as PromotionStatusValues,
+ campaign_choice: "none" as const,
+ is_automatic: "false",
+ code: "",
+ type: "standard" as PromotionTypeValues,
+ status: "draft" as PromotionStatusValues,
rules: [],
is_tax_inclusive: false,
application_method: {
- allocation: 'each' as ApplicationMethodAllocationValues,
- type: 'fixed' as ApplicationMethodTypeValues,
- target_type: 'items' as ApplicationMethodTargetTypeValues,
+ allocation: "each" as ApplicationMethodAllocationValues,
+ type: "fixed" as ApplicationMethodTypeValues,
+ target_type: "items" as ApplicationMethodTargetTypeValues,
max_quantity: 1,
target_rules: [],
- buy_rules: []
+ buy_rules: [],
},
- campaign: undefined
-};
-
-type TabState = Record<Tab, ProgressStatus>;
-type AllocationMode = 'each' | 'across' | 'once';
-
-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 direction = useDocumentDirection();
- const form = useForm<z.infer<typeof CreatePromotionSchema>>({
- defaultValues,
- resolver: zodResolver(CreatePromotionSchema)
- });
- const { setValue, reset, getValues } = form;
- const [allocationMode, setAllocationMode] = useState<AllocationMode>('each');
+ campaign: undefined,
+}
+
+type CreatePromotionFormProps = {
+ children?: ReactNode
+ schema?: z.ZodType<CreatePromotionSchemaType>
+ defaultValues?: DeepPartial<CreatePromotionSchemaType>
+}
+
+export function CreatePromotionForm({
+ children,
+ schema,
+ defaultValues: extraDefaults,
+}: CreatePromotionFormProps) {
+ const { t } = useTranslation()
+ const { handleSuccess } = useRouteModal()
+
+ const form = useForm<CreatePromotionSchemaType>({
+ defaultValues: {
+ ...PROMOTION_CREATE_DEFAULTS,
+ ...extraDefaults,
+ },
+ resolver: zodResolver(schema ?? CreatePromotionSchema),
+ })
+ const { setValue, reset, getValues } = form
- const { mutateAsync: createPromotion } = useCreatePromotion();
+ const { mutateAsync: createPromotion, isPending: isLoading } =
+ 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;
+ async (data) => {
+ if (data.campaign_choice === "existing" && !data.campaign_id) {
+ form.setError("campaign_id", {
+ message: t("promotions.errors.requiredField"),
+ })
+ return
}
const {
campaign_choice: _campaignChoice,
@@ -102,52 +87,59 @@ export const CreatePromotionForm = () => {
application_method,
rules,
...promotionData
- } = data;
+ } = data
const {
target_rules: targetRulesData = [],
buy_rules: buyRulesData = [],
...applicationMethodData
- } = application_method;
- const allocationTyped = applicationMethodData.allocation as ApplicationMethodAllocationValues;
+ } = application_method
+ const allocationTyped =
+ applicationMethodData.allocation as ApplicationMethodAllocationValues
const disguisedRules = [
- ...targetRulesData.filter(r => !!r.disguised),
- ...buyRulesData.filter(r => !!r.disguised),
- ...rules.filter(r => !!r.disguised)
- ];
+ ...targetRulesData.filter((r) => !!r.disguised),
+ ...buyRulesData.filter((r) => !!r.disguised),
+ ...rules.filter((r) => !!r.disguised),
+ ]
- const applicationMethodRuleData: Record<any, any> = {};
+ const applicationMethodRuleData: Record<
+ string,
+ string | number | string[]
+ > = {}
for (const rule of disguisedRules) {
applicationMethodRuleData[rule.attribute] =
- rule.field_type === 'number' ? parseInt(rule.values as string) : rule.values;
+ rule.field_type === "number"
+ ? parseInt(rule.values as string)
+ : rule.values
}
const buildRulesData = (
rules: {
- operator: string;
- attribute: string;
- values: any[] | any;
- disguised?: boolean;
+ operator: string
+ attribute: string
+ values: string[] | string | number
+ disguised?: boolean
}[]
) => {
return rules
- .filter(r => !r.disguised)
- .map(rule => ({
+ .filter((r) => !r.disguised)
+ .map((rule) => ({
operator: rule.operator as PromotionRuleOperatorValues,
attribute: rule.attribute,
- values: rule.values
- }));
- };
+ values: rule.values as string | string[],
+ }))
+ }
if (data.campaign) {
- data.campaign.budget.attribute = data.campaign.budget.attribute || null;
+ data.campaign.budget.attribute =
+ data.campaign.budget.attribute || null
data.campaign.budget.type = data.campaign.budget.attribute
- ? 'use_by_attribute'
- : data.campaign.budget.type;
+ ? "use_by_attribute"
+ : data.campaign.budget.type
}
- createPromotion(
+ await createPromotion(
{
...promotionData,
rules: buildRulesData(rules),
@@ -159,902 +151,150 @@ export const CreatePromotionForm = () => {
target_rules: buildRulesData(targetRulesData),
buy_rules: buildRulesData(buyRulesData),
max_quantity:
- allocationTyped === 'across' ? undefined : applicationMethodData.max_quantity
+ allocationTyped === "across"
+ ? undefined
+ : applicationMethodData.max_quantity,
},
is_tax_inclusive,
- is_automatic: is_automatic === 'true'
+ is_automatic: is_automatic === "true",
},
{
onSuccess: ({ promotion }) => {
toast.success(
- t('promotions.toasts.promotionCreateSuccess', {
- code: promotion.code
+ t("promotions.toasts.promotionCreateSuccess", {
+ code: promotion.code,
})
- );
+ )
- handleSuccess(`/promotions/${promotion.id}`);
+ handleSuccess(`/promotions/${promotion.id}`)
+ },
+ onError: (e) => {
+ toast.error(e.message)
},
- onError: e => {
- toast.error(e.message);
- }
}
- );
+ )
},
- async error => {
- const { campaign: _campaign, ...rest } = error || {};
- const errorInPromotionTab = !!Object.keys(rest || {}).length;
+ 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();
-
- if (!valid) {
- // If the promotion tab is not valid, we want to set the tab state to in-progress
- // and set the tab to the promotion tab
- 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 = await form.trigger();
-
- if (valid) {
- handleTabChange(Tab.CAMPAIGN);
- }
-
- break;
+ toast.error(t("promotions.errors.promotionTabError"))
}
- case Tab.CAMPAIGN:
- break;
}
- };
+ )
+ // Template selection: reset form and apply template defaults
const watchTemplateId = useWatch({
control: form.control,
- name: 'template_id'
- });
+ name: "template_id",
+ })
const currentTemplate = useMemo(() => {
- const currentTemplate = templates.find(template => template.id === watchTemplateId);
+ const currentTemplate = templates.find(
+ (template) => template.id === watchTemplateId
+ )
if (!currentTemplate) {
- return;
+ return
}
- reset({ ...defaultValues, template_id: watchTemplateId });
+ reset({
+ ...PROMOTION_CREATE_DEFAULTS,
+ ...extraDefaults,
+ 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}`, subValue);
+ if (typeof value === "object") {
+ for (const [subKey, subValue] of Object.entries(
+ value as Record<string, unknown>
+ )) {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ setValue(`application_method.${subKey}` as any, subValue as any)
}
} else {
- setValue(key, value);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ setValue(key as any, value as any)
}
}
- 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) {
- setAllocationMode(watchAllocation as AllocationMode);
- }
- }, [watchAllocation]);
-
- const watchType = useWatch({
- control: form.control,
- name: 'type'
- });
-
- const isTypeStandard = watchType === 'standard';
- const isTypeBuyGet = watchType === 'buyget';
-
- const targetType = useWatch({
- control: form.control,
- name: 'application_method.target_type'
- });
-
- const isTargetTypeOrder = targetType === 'order';
-
- const formData = form.getValues();
- let campaignQuery: object = {};
-
- if (formData.application_method.currency_code) {
- campaignQuery = {
- budget: { currency_code: formData.application_method.currency_code }
- };
- }
-
- const { campaigns } = useCampaigns(campaignQuery);
+ return currentTemplate
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [watchTemplateId, setValue, reset])
+ // Campaign choice effects
const watchCampaignChoice = useWatch({
control: form.control,
- name: 'campaign_choice'
- });
+ name: "campaign_choice",
+ })
useEffect(() => {
- const formData = getValues();
+ const formData = getValues()
- if (watchCampaignChoice !== 'existing') {
- setValue('campaign_id', undefined);
- form.clearErrors('campaign_id');
+ if (watchCampaignChoice !== "existing") {
+ setValue("campaign_id", undefined)
+ form.clearErrors("campaign_id")
}
- if (watchCampaignChoice !== 'new') {
- setValue('campaign', undefined);
+ if (watchCampaignChoice !== "new") {
+ setValue("campaign", undefined)
}
- if (watchCampaignChoice === 'new') {
+ if (watchCampaignChoice === "new") {
if (!formData.campaign || !formData.campaign?.budget?.type) {
- setValue('campaign', {
+ setValue("campaign", {
...DEFAULT_CAMPAIGN_VALUES,
budget: {
...DEFAULT_CAMPAIGN_VALUES.budget,
- currency_code: formData.application_method.currency_code
- }
- });
+ type: DEFAULT_CAMPAIGN_VALUES.budget.type as "spend" | "usage" | "use_by_attribute",
+ currency_code: formData.application_method.currency_code,
+ },
+ })
}
}
- }, [watchCampaignChoice, getValues, setValue]);
+ }, [watchCampaignChoice, getValues, setValue, form])
+ // Currency rule syncing
const watchRules = useWatch({
control: form.control,
- name: 'rules'
- });
+ name: "rules",
+ })
- const watchCurrencyRule = watchRules.find(rule => rule.attribute === 'currency_code');
+ 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;
+ 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);
+ form.setValue("application_method.currency_code", ruleValue as string)
}
}
+ const defaultTabs = useMemo(
+ () => [
+ <PromotionTemplateTab key="type" />,
+ <PromotionDetailsTab key="promotion" currentTemplate={currentTemplate} />,
+ <PromotionCampaignTab key="campaign" />,
+ ],
+ [currentTemplate]
+ )
+
+ const hasCustomChildren = Children.count(children) > 0
+
return (
- <RouteFocusModal.Form
+ <TabbedForm
form={form}
- data-testid="promotion-create-form"
+ onSubmit={handleSubmit}
+ isLoading={isLoading}
>
- <KeyboundForm
- className="flex h-full flex-col"
- onSubmit={handleSubmit}
- >
- <ProgressTabs
- dir={direction}
- value={tab}
- onValueChange={tab => handleTabChange(tab as Tab)}
- className="flex h-full flex-col overflow-hidden"
- data-testid="promotion-create-form-tabs"
- >
- <RouteFocusModal.Header data-testid="promotion-create-form-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"
- data-testid="promotion-create-form-tabs-list"
- >
- <ProgressTabs.Trigger
- className="w-full"
- value={Tab.TYPE}
- status={tabState[Tab.TYPE]}
- data-testid="promotion-create-form-tab-type"
- >
- {t('promotions.tabs.template')}
- </ProgressTabs.Trigger>
-
- <ProgressTabs.Trigger
- className="w-full"
- value={Tab.PROMOTION}
- status={tabState[Tab.PROMOTION]}
- data-testid="promotion-create-form-tab-promotion"
- >
- {t('promotions.tabs.details')}
- </ProgressTabs.Trigger>
-
- <ProgressTabs.Trigger
- className="w-full"
- value={Tab.CAMPAIGN}
- status={tabState[Tab.CAMPAIGN]}
- data-testid="promotion-create-form-tab-campaign"
- >
- {t('promotions.tabs.campaign')}
- </ProgressTabs.Trigger>
- </ProgressTabs.List>
- </div>
- </div>
- </RouteFocusModal.Header>
-
- <RouteFocusModal.Body
- className="size-full overflow-hidden"
- data-testid="promotion-create-form-body"
- >
- <ProgressTabs.Content
- value={Tab.TYPE}
- className="size-full overflow-y-auto"
- data-testid="promotion-create-form-content-type"
- >
- <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 data-testid="promotion-create-form-template-item">
- <Form.Label data-testid="promotion-create-form-template-label">
- {t('promotions.fields.type')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-template-control">
- <RadioGroup
- dir={direction}
- key="template_id"
- className="flex-col gap-y-3"
- {...field}
- onValueChange={field.onChange}
- data-testid="promotion-create-form-template-radio-group"
- >
- {templates.map(template => {
- return (
- <RadioGroup.ChoiceBox
- key={template.id}
- value={template.id}
- label={template.title}
- description={template.description}
- data-testid={`promotion-create-form-template-option-${template.id}`}
- />
- );
- })}
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-template-error" />
- </Form.Item>
- );
- }}
- />
- </div>
- </div>
- </ProgressTabs.Content>
-
- <ProgressTabs.Content
- value={Tab.PROMOTION}
- className="size-full overflow-y-auto"
- data-testid="promotion-create-form-content-promotion"
- >
- <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"
- data-testid="promotion-create-form-promotion-heading"
- >
- {t(`promotions.sections.details`)}
-
- {currentTemplate?.title && (
- <Badge
- className="ml-2 align-middle"
- color="grey"
- size="2xsmall"
- rounded="full"
- data-testid="promotion-create-form-promotion-template-badge"
- >
- {currentTemplate?.title}
- </Badge>
- )}
- </Heading>
-
- {form.formState.errors.root && (
- <Alert
- variant="error"
- dismissible={false}
- className="text-balance"
- data-testid="promotion-create-form-promotion-error-alert"
- >
- {form.formState.errors.root.message}
- </Alert>
- )}
-
- <Form.Field
- control={form.control}
- name="is_automatic"
- render={({ field }) => {
- return (
- <Form.Item data-testid="promotion-create-form-method-item">
- <Form.Label data-testid="promotion-create-form-method-label">
- {t('promotions.form.method.label')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-method-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- {...field}
- value={field.value}
- onValueChange={field.onChange}
- data-testid="promotion-create-form-method-radio-group"
- >
- <RadioGroup.ChoiceBox
- value="false"
- label={t('promotions.form.method.code.title')}
- description={t('promotions.form.method.code.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-method-option-code"
- />
-
- <RadioGroup.ChoiceBox
- value="true"
- label={t('promotions.form.method.automatic.title')}
- description={t('promotions.form.method.automatic.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-method-option-automatic"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-method-error" />
- </Form.Item>
- );
- }}
- />
-
- <Form.Field
- control={form.control}
- name="status"
- render={({ field }) => {
- return (
- <Form.Item data-testid="promotion-create-form-status-item">
- <Form.Label data-testid="promotion-create-form-status-label">
- {t('promotions.form.status.label')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-status-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- {...field}
- value={field.value}
- onValueChange={field.onChange}
- data-testid="promotion-create-form-status-radio-group"
- >
- <RadioGroup.ChoiceBox
- value="draft"
- label={t('promotions.form.status.draft.title')}
- description={t('promotions.form.status.draft.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-status-option-draft"
- />
-
- <RadioGroup.ChoiceBox
- value="active"
- label={t('promotions.form.status.active.title')}
- description={t('promotions.form.status.active.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-status-option-active"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-status-error" />
- </Form.Item>
- );
- }}
- />
-
- <div className="flex gap-y-4">
- <Form.Field
- control={form.control}
- name="code"
- render={({ field }) => {
- return (
- <Form.Item
- className="basis-1/2"
- data-testid="promotion-create-form-code-item"
- >
- <Form.Label data-testid="promotion-create-form-code-label">
- {t('promotions.form.code.title')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-code-control">
- <Input
- {...field}
- placeholder="SUMMER15"
- data-testid="promotion-create-form-code-input"
- />
- </Form.Control>
-
- <Text
- size="small"
- leading="compact"
- className="text-ui-fg-subtle"
- data-testid="promotion-create-form-code-description"
- >
- <Trans
- t={t}
- i18nKey="promotions.form.code.description"
- components={[<br key="break" />]}
- />
- </Text>
- <Form.ErrorMessage data-testid="promotion-create-form-code-error" />
- </Form.Item>
- );
- }}
- />
- </div>
-
- {!currentTemplate?.hiddenFields?.includes('is_tax_inclusive') && (
- <>
- <Divider />
- <div className="flex gap-x-2 gap-y-4">
- <Form.Field
- control={form.control}
- name="is_tax_inclusive"
- render={({ field: { onChange, value, ...field } }) => {
- return (
- <Form.Item
- className="basis-full"
- data-testid="promotion-create-form-tax-inclusive-item"
- >
- <div className="flex items-center justify-between">
- <div className="block">
- <Form.Label data-testid="promotion-create-form-tax-inclusive-label">
- {t('promotions.form.taxInclusive.title')}
- </Form.Label>
- <Form.Hint
- className="!mt-1"
- data-testid="promotion-create-form-tax-inclusive-hint"
- >
- {t('promotions.form.taxInclusive.description')}
- </Form.Hint>
- </div>
- <Form.Control
- className="mr-2 self-center"
- data-testid="promotion-create-form-tax-inclusive-control"
- >
- <Switch
- dir="ltr"
- className="mt-[2px] rtl:rotate-180"
- checked={!!value}
- onCheckedChange={onChange}
- {...field}
- data-testid="promotion-create-form-tax-inclusive-switch"
- />
- </Form.Control>
- </div>
- <Form.ErrorMessage data-testid="promotion-create-form-tax-inclusive-error" />
- </Form.Item>
- );
- }}
- />
- </div>
- </>
- )}
-
- {!currentTemplate?.hiddenFields?.includes('type') && (
- <Form.Field
- control={form.control}
- name="type"
- render={({ field }) => {
- return (
- <Form.Item data-testid="promotion-create-form-type-item">
- <Form.Label data-testid="promotion-create-form-type-label">
- {t('promotions.fields.type')}
- </Form.Label>
- <Form.Control data-testid="promotion-create-form-type-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- {...field}
- onValueChange={field.onChange}
- data-testid="promotion-create-form-type-radio-group"
- >
- <RadioGroup.ChoiceBox
- value="standard"
- label={t('promotions.form.type.standard.title')}
- description={t('promotions.form.type.standard.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-type-option-standard"
- />
-
- <RadioGroup.ChoiceBox
- value="buyget"
- label={t('promotions.form.type.buyget.title')}
- description={t('promotions.form.type.buyget.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-type-option-buyget"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-type-error" />
- </Form.Item>
- );
- }}
- />
- )}
-
- <Divider />
-
- <RulesFormField
- form={form}
- ruleType="rules"
- />
-
- {!currentTemplate?.hiddenFields?.includes('application_method.type') && (
- <>
- <Divider />
- <Form.Field
- control={form.control}
- name="application_method.type"
- render={({ field }) => {
- return (
- <Form.Item data-testid="promotion-create-form-value-type-item">
- <Form.Label data-testid="promotion-create-form-value-type-label">
- {t('promotions.fields.value_type')}
- </Form.Label>
- <Form.Control data-testid="promotion-create-form-value-type-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- {...field}
- onValueChange={field.onChange}
- data-testid="promotion-create-form-value-type-radio-group"
- >
- <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')}
- data-testid="promotion-create-form-value-type-option-fixed"
- />
-
- <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')}
- data-testid="promotion-create-form-value-type-option-percentage"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-value-type-error" />
- </Form.Item>
- );
- }}
- />
- </>
- )}
-
- {!currentTemplate?.hiddenFields?.includes('application_method.value') && (
- <>
- <Divider />
- <Form.Field
- control={form.control}
- name="application_method.value"
- render={({ field: { onChange, value, ...field } }) => {
- const currencyCode = form.getValues().application_method.currency_code;
-
- const currencyInfo = currencies[currencyCode?.toUpperCase() || 'USD'];
-
- return (
- <Form.Item
- className="basis-1/2"
- data-testid="promotion-create-form-value-item"
- >
- <Form.Label
- tooltip={
- currencyCode || !isFixedValueType
- ? undefined
- : t('promotions.fields.amount.tooltip')
- }
- data-testid="promotion-create-form-value-label"
- >
- {t('promotions.form.value.title')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-value-control">
- {isFixedValueType ? (
- <CurrencyInput
- {...field}
- min={0}
- code={currencyCode || 'USD'}
- onValueChange={(_value, _name, values) =>
- onChange(values?.value)
- }
- decimalScale={currencyInfo?.decimal_digits ?? 2}
- decimalsLimit={currencyInfo?.decimal_digits ?? 2}
- symbol={currencyCode ? getCurrencySymbol(currencyCode) : '$'}
- value={value}
- disabled={!currencyCode}
- data-testid="promotion-create-form-value-currency-input"
- />
- ) : (
- <DeprecatedPercentageInput
- key="amount"
- className="text-right"
- min={0}
- max={100}
- {...field}
- value={value}
- onChange={e => {
- onChange(
- e.target.value === '' ? null : parseFloat(e.target.value)
- );
- }}
- data-testid="promotion-create-form-value-percentage-input"
- />
- )}
- </Form.Control>
- <Text
- size="small"
- leading="compact"
- className="text-ui-fg-subtle"
- data-testid="promotion-create-form-value-description"
- >
- <Trans
- t={t}
- i18nKey={
- isFixedValueType
- ? 'promotions.form.value_type.fixed.description'
- : 'promotions.form.value_type.percentage.description'
- }
- components={[<br key="break" />]}
- />
- </Text>
- <Form.ErrorMessage data-testid="promotion-create-form-value-error" />
- </Form.Item>
- );
- }}
- />
- </>
- )}
-
- {(isTypeStandard || isTypeBuyGet) && allocationMode !== 'across' && (
- <>
- {isTypeBuyGet && (
- <>
- <Divider />
- </>
- )}
- <Form.Field
- control={form.control}
- name="application_method.max_quantity"
- render={() => {
- return (
- <Form.Item
- className="basis-1/2"
- data-testid="promotion-create-form-max-quantity-item"
- >
- <Form.Label data-testid="promotion-create-form-max-quantity-label">
- {t('promotions.form.max_quantity.title')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-max-quantity-control">
- <Input
- {...form.register('application_method.max_quantity', {
- valueAsNumber: true
- })}
- type="number"
- min={1}
- placeholder="3"
- data-testid="promotion-create-form-max-quantity-input"
- />
- </Form.Control>
-
- <Text
- size="small"
- leading="compact"
- className="text-ui-fg-subtle"
- data-testid="promotion-create-form-max-quantity-description"
- >
- <Trans
- t={t}
- i18nKey="promotions.form.max_quantity.description"
- components={[<br key="break" />]}
- />
- </Text>
- <Form.ErrorMessage data-testid="promotion-create-form-max-quantity-error" />
- </Form.Item>
- );
- }}
- />
- </>
- )}
-
- {!currentTemplate?.hiddenFields?.includes('application_method.allocation') && (
- <Form.Field
- control={form.control}
- name="application_method.allocation"
- render={({ field }) => {
- const handleAllocationChange = (value: AllocationMode) => {
- setAllocationMode(value);
- setValue(
- 'application_method.allocation',
- value as ApplicationMethodAllocationValues
- );
- field.onChange(value as ApplicationMethodAllocationValues);
-
- if (value === 'once') {
- setValue('application_method.max_quantity', 1);
- }
- };
-
- return (
- <Form.Item data-testid="promotion-create-form-allocation-item">
- <Form.Label data-testid="promotion-create-form-allocation-label">
- {t('promotions.fields.allocation')}
- </Form.Label>
-
- <Form.Control data-testid="promotion-create-form-allocation-control">
- <RadioGroup
- dir={direction}
- className="flex gap-y-3"
- value={allocationMode}
- onValueChange={val => handleAllocationChange(val as AllocationMode)}
- data-testid="promotion-create-form-allocation-radio-group"
- >
- <RadioGroup.ChoiceBox
- value="each"
- label={t('promotions.form.allocation.each.title')}
- description={t('promotions.form.allocation.each.description')}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-allocation-option-each"
- />
-
- <RadioGroup.ChoiceBox
- value="once"
- label={t('promotions.form.allocation.once.title', {
- defaultValue: 'Once'
- })}
- description={t('promotions.form.allocation.once.description', {
- defaultValue: 'Limit discount to max quantity'
- })}
- className={clx('basis-1/2')}
- data-testid="promotion-create-form-allocation-option-once"
- />
- </RadioGroup>
- </Form.Control>
- <Form.ErrorMessage data-testid="promotion-create-form-allocation-error" />
- </Form.Item>
- );
- }}
- />
- )}
-
- {!isTypeStandard && (
- <>
- <Divider />
- <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"
- data-testid="promotion-create-form-content-campaign"
- >
- <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 data-testid="promotion-create-form-footer">
- <div className="flex items-center justify-end gap-x-2">
- <RouteFocusModal.Close asChild>
- <Button
- variant="secondary"
- size="small"
- data-testid="promotion-create-form-cancel-button"
- >
- {t('actions.cancel')}
- </Button>
- </RouteFocusModal.Close>
+ {hasCustomChildren ? children : defaultTabs}
+ </TabbedForm>
+ )
+}
- {tab === Tab.CAMPAIGN ? (
- <Button
- key="save-btn"
- type="submit"
- size="small"
- isLoading={false}
- data-testid="promotion-create-form-save-button"
- >
- {t('actions.save')}
- </Button>
- ) : (
- <Button
- key="continue-btn"
- type="button"
- onClick={handleContinue}
- size="small"
- data-testid="promotion-create-form-continue-button"
- >
- {t('actions.continue')}
- </Button>
- )}
- </div>
- </RouteFocusModal.Footer>
- </KeyboundForm>
- </RouteFocusModal.Form>
- );
-};
+export type { CreatePromotionSchemaType }
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-campaign-tab.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-campaign-tab.tsx
new file mode 100644
index 000000000..7d74c8642
--- /dev/null
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-campaign-tab.tsx
@@ -0,0 +1,34 @@
+import { useWatch } from "react-hook-form"
+
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
+import { AddCampaignPromotionFields } from "../../../promotion-add-campaign/components/add-campaign-promotion-form"
+import { CreatePromotionSchemaType } from "./form-schema"
+
+const Root = () => {
+ const form = useTabbedForm<CreatePromotionSchemaType>()
+
+ const currencyCode = useWatch({
+ control: form.control,
+ name: "application_method.currency_code",
+ })
+
+ return (
+ <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}
+ promotionCurrencyCode={currencyCode}
+ />
+ </div>
+ </div>
+ )
+}
+
+Root._tabMeta = defineTabMeta<CreatePromotionSchemaType>({
+ id: "campaign",
+ labelKey: "promotions.tabs.campaign",
+ validationFields: ["campaign_id", "campaign_choice", "campaign"],
+})
+
+export const PromotionCampaignTab = Root
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
new file mode 100644
index 000000000..84eef0ff9
--- /dev/null
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-details-tab.tsx
@@ -0,0 +1,652 @@
+import { useEffect, useState } from "react"
+
+import type {
+ ApplicationMethodAllocationValues,
+} from "@medusajs/types"
+import {
+ Alert,
+ Badge,
+ clx,
+ CurrencyInput,
+ Divider,
+ Heading,
+ Input,
+ RadioGroup,
+ Switch,
+ Text,
+} from "@medusajs/ui"
+import { useWatch } from "react-hook-form"
+import { Trans, useTranslation } from "react-i18next"
+
+import { Form } from "../../../../../components/common/form"
+import { DeprecatedPercentageInput } from "../../../../../components/inputs/percentage-input"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
+import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
+import { currencies, getCurrencySymbol } from "../../../../../lib/data/currencies"
+import { RulesFormField } from "../../../common/edit-rules/components/rules-form-field"
+import { CreatePromotionSchemaType } from "./form-schema"
+
+type AllocationMode = "each" | "across" | "once"
+
+type PromotionDetailsTabProps = {
+ currentTemplate?: {
+ id: string
+ title: string
+ hiddenFields: string[]
+ }
+}
+
+const Root = ({ currentTemplate }: PromotionDetailsTabProps) => {
+ const { t } = useTranslation()
+ const direction = useDocumentDirection()
+ const form = useTabbedForm<CreatePromotionSchemaType>()
+ const { setValue } = form
+
+ const [allocationMode, setAllocationMode] = useState<AllocationMode>("each")
+
+ 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) {
+ setAllocationMode(watchAllocation as AllocationMode)
+ }
+ }, [watchAllocation])
+
+ const watchType = useWatch({
+ control: form.control,
+ name: "type",
+ })
+
+ const isTypeStandard = watchType === "standard"
+ const isTypeBuyGet = watchType === "buyget"
+
+ const targetType = useWatch({
+ control: form.control,
+ name: "application_method.target_type",
+ })
+
+ const isTargetTypeOrder = targetType === "order"
+
+ return (
+ <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"
+ data-testid="promotion-create-form-promotion-heading"
+ >
+ {t(`promotions.sections.details`)}
+
+ {currentTemplate?.title && (
+ <Badge
+ className="ml-2 align-middle"
+ color="grey"
+ size="2xsmall"
+ rounded="full"
+ data-testid="promotion-create-form-promotion-template-badge"
+ >
+ {currentTemplate?.title}
+ </Badge>
+ )}
+ </Heading>
+
+ {form.formState.errors.root && (
+ <Alert
+ variant="error"
+ dismissible={false}
+ className="text-balance"
+ data-testid="promotion-create-form-promotion-error-alert"
+ >
+ {form.formState.errors.root.message}
+ </Alert>
+ )}
+
+ <Form.Field
+ control={form.control}
+ name="is_automatic"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-create-form-method-item">
+ <Form.Label data-testid="promotion-create-form-method-label">
+ {t("promotions.form.method.label")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-method-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-method-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="false"
+ label={t("promotions.form.method.code.title")}
+ description={t("promotions.form.method.code.description")}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-method-option-code"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="true"
+ label={t("promotions.form.method.automatic.title")}
+ description={t(
+ "promotions.form.method.automatic.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-method-option-automatic"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-method-error" />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <Form.Field
+ control={form.control}
+ name="status"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-create-form-status-item">
+ <Form.Label data-testid="promotion-create-form-status-label">
+ {t("promotions.form.status.label")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-status-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ {...field}
+ value={field.value}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-status-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="draft"
+ label={t("promotions.form.status.draft.title")}
+ description={t(
+ "promotions.form.status.draft.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-status-option-draft"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="active"
+ label={t("promotions.form.status.active.title")}
+ description={t(
+ "promotions.form.status.active.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-status-option-active"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-status-error" />
+ </Form.Item>
+ )
+ }}
+ />
+
+ <div className="flex gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="code"
+ render={({ field }) => {
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-code-item"
+ >
+ <Form.Label data-testid="promotion-create-form-code-label">
+ {t("promotions.form.code.title")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-code-control">
+ <Input
+ {...field}
+ placeholder="SUMMER15"
+ data-testid="promotion-create-form-code-input"
+ />
+ </Form.Control>
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-create-form-code-description"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.code.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage data-testid="promotion-create-form-code-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+
+ {!currentTemplate?.hiddenFields?.includes("is_tax_inclusive") && (
+ <>
+ <Divider />
+ <div className="flex gap-x-2 gap-y-4">
+ <Form.Field
+ control={form.control}
+ name="is_tax_inclusive"
+ render={({ field: { onChange, value, ...field } }) => {
+ return (
+ <Form.Item
+ className="basis-full"
+ data-testid="promotion-create-form-tax-inclusive-item"
+ >
+ <div className="flex items-center justify-between">
+ <div className="block">
+ <Form.Label data-testid="promotion-create-form-tax-inclusive-label">
+ {t("promotions.form.taxInclusive.title")}
+ </Form.Label>
+ <Form.Hint
+ className="!mt-1"
+ data-testid="promotion-create-form-tax-inclusive-hint"
+ >
+ {t("promotions.form.taxInclusive.description")}
+ </Form.Hint>
+ </div>
+ <Form.Control
+ className="mr-2 self-center"
+ data-testid="promotion-create-form-tax-inclusive-control"
+ >
+ <Switch
+ dir="ltr"
+ className="mt-[2px] rtl:rotate-180"
+ checked={!!value}
+ onCheckedChange={onChange}
+ {...field}
+ data-testid="promotion-create-form-tax-inclusive-switch"
+ />
+ </Form.Control>
+ </div>
+ <Form.ErrorMessage data-testid="promotion-create-form-tax-inclusive-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </>
+ )}
+
+ {!currentTemplate?.hiddenFields?.includes("type") && (
+ <Form.Field
+ control={form.control}
+ name="type"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-create-form-type-item">
+ <Form.Label data-testid="promotion-create-form-type-label">
+ {t("promotions.fields.type")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-create-form-type-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-type-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="standard"
+ label={t("promotions.form.type.standard.title")}
+ description={t(
+ "promotions.form.type.standard.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-type-option-standard"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="buyget"
+ label={t("promotions.form.type.buyget.title")}
+ description={t(
+ "promotions.form.type.buyget.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-type-option-buyget"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-type-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ <Divider />
+
+ <RulesFormField form={form} ruleType="rules" />
+
+ {!currentTemplate?.hiddenFields?.includes("application_method.type") && (
+ <>
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="application_method.type"
+ render={({ field }) => {
+ return (
+ <Form.Item data-testid="promotion-create-form-value-type-item">
+ <Form.Label data-testid="promotion-create-form-value-type-label">
+ {t("promotions.fields.value_type")}
+ </Form.Label>
+ <Form.Control data-testid="promotion-create-form-value-type-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-value-type-radio-group"
+ >
+ <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")}
+ data-testid="promotion-create-form-value-type-option-fixed"
+ />
+
+ <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")}
+ data-testid="promotion-create-form-value-type-option-percentage"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-value-type-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </>
+ )}
+
+ {!currentTemplate?.hiddenFields?.includes(
+ "application_method.value"
+ ) && (
+ <>
+ <Divider />
+ <Form.Field
+ control={form.control}
+ name="application_method.value"
+ render={({ field: { onChange, value, ...field } }) => {
+ const currencyCode =
+ form.getValues().application_method.currency_code
+
+ const currencyInfo =
+ currencies[currencyCode?.toUpperCase() || "USD"]
+
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-value-item"
+ >
+ <Form.Label
+ tooltip={
+ currencyCode || !isFixedValueType
+ ? undefined
+ : t("promotions.fields.amount.tooltip")
+ }
+ data-testid="promotion-create-form-value-label"
+ >
+ {t("promotions.form.value.title")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-value-control">
+ {isFixedValueType ? (
+ <CurrencyInput
+ {...field}
+ min={0}
+ code={currencyCode || "USD"}
+ onValueChange={(_value, _name, values) =>
+ onChange(values?.value)
+ }
+ decimalScale={currencyInfo?.decimal_digits ?? 2}
+ decimalsLimit={currencyInfo?.decimal_digits ?? 2}
+ symbol={
+ currencyCode
+ ? getCurrencySymbol(currencyCode)
+ : "$"
+ }
+ value={value}
+ disabled={!currencyCode}
+ data-testid="promotion-create-form-value-currency-input"
+ />
+ ) : (
+ <DeprecatedPercentageInput
+ key="amount"
+ className="text-right"
+ min={0}
+ max={100}
+ {...field}
+ value={value}
+ onChange={(e) => {
+ onChange(
+ e.target.value === ""
+ ? null
+ : parseFloat(e.target.value)
+ )
+ }}
+ data-testid="promotion-create-form-value-percentage-input"
+ />
+ )}
+ </Form.Control>
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-create-form-value-description"
+ >
+ <Trans
+ t={t}
+ i18nKey={
+ isFixedValueType
+ ? "promotions.form.value_type.fixed.description"
+ : "promotions.form.value_type.percentage.description"
+ }
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage data-testid="promotion-create-form-value-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </>
+ )}
+
+ {(isTypeStandard || isTypeBuyGet) && allocationMode !== "across" && (
+ <>
+ {isTypeBuyGet && (
+ <>
+ <Divider />
+ </>
+ )}
+ <Form.Field
+ control={form.control}
+ name="application_method.max_quantity"
+ render={() => {
+ return (
+ <Form.Item
+ className="basis-1/2"
+ data-testid="promotion-create-form-max-quantity-item"
+ >
+ <Form.Label data-testid="promotion-create-form-max-quantity-label">
+ {t("promotions.form.max_quantity.title")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-max-quantity-control">
+ <Input
+ {...form.register("application_method.max_quantity", {
+ valueAsNumber: true,
+ })}
+ type="number"
+ min={1}
+ placeholder="3"
+ data-testid="promotion-create-form-max-quantity-input"
+ />
+ </Form.Control>
+
+ <Text
+ size="small"
+ leading="compact"
+ className="text-ui-fg-subtle"
+ data-testid="promotion-create-form-max-quantity-description"
+ >
+ <Trans
+ t={t}
+ i18nKey="promotions.form.max_quantity.description"
+ components={[<br key="break" />]}
+ />
+ </Text>
+ <Form.ErrorMessage data-testid="promotion-create-form-max-quantity-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </>
+ )}
+
+ {!currentTemplate?.hiddenFields?.includes(
+ "application_method.allocation"
+ ) && (
+ <Form.Field
+ control={form.control}
+ name="application_method.allocation"
+ render={({ field }) => {
+ const handleAllocationChange = (value: AllocationMode) => {
+ setAllocationMode(value)
+ setValue(
+ "application_method.allocation",
+ value as ApplicationMethodAllocationValues
+ )
+ field.onChange(value as ApplicationMethodAllocationValues)
+
+ if (value === "once") {
+ setValue("application_method.max_quantity", 1)
+ }
+ }
+
+ return (
+ <Form.Item data-testid="promotion-create-form-allocation-item">
+ <Form.Label data-testid="promotion-create-form-allocation-label">
+ {t("promotions.fields.allocation")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-allocation-control">
+ <RadioGroup
+ dir={direction}
+ className="flex gap-y-3"
+ value={allocationMode}
+ onValueChange={(val) =>
+ handleAllocationChange(val as AllocationMode)
+ }
+ data-testid="promotion-create-form-allocation-radio-group"
+ >
+ <RadioGroup.ChoiceBox
+ value="each"
+ label={t("promotions.form.allocation.each.title")}
+ description={t(
+ "promotions.form.allocation.each.description"
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-allocation-option-each"
+ />
+
+ <RadioGroup.ChoiceBox
+ value="once"
+ label={t("promotions.form.allocation.once.title", {
+ defaultValue: "Once",
+ })}
+ description={t(
+ "promotions.form.allocation.once.description",
+ {
+ defaultValue:
+ "Limit discount to max quantity",
+ }
+ )}
+ className={clx("basis-1/2")}
+ data-testid="promotion-create-form-allocation-option-once"
+ />
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-allocation-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ )}
+
+ {!isTypeStandard && (
+ <>
+ <Divider />
+ <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>
+ )
+}
+
+Root._tabMeta = defineTabMeta<CreatePromotionSchemaType>({
+ id: "promotion",
+ labelKey: "promotions.tabs.details",
+ validationFields: [
+ "is_automatic",
+ "code",
+ "type",
+ "status",
+ "rules",
+ "is_tax_inclusive",
+ "application_method",
+ ],
+})
+
+export const PromotionDetailsTab = Root
diff --git a/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-template-tab.tsx b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-template-tab.tsx
new file mode 100644
index 000000000..8fbc268ca
--- /dev/null
+++ b/packages/admin/src/pages/promotions/promotion-create/components/create-promotion-form/promotion-template-tab.tsx
@@ -0,0 +1,67 @@
+import { RadioGroup } from "@medusajs/ui"
+import { useTranslation } from "react-i18next"
+
+import { Form } from "../../../../../components/common/form"
+import { useTabbedForm } from "../../../../../components/tabbed-form/tabbed-form"
+import { defineTabMeta } from "../../../../../components/tabbed-form/types"
+import { useDocumentDirection } from "../../../../../hooks/use-document-direction"
+import { CreatePromotionSchemaType } from "./form-schema"
+import { templates } from "./templates"
+
+const Root = () => {
+ const { t } = useTranslation()
+ const direction = useDocumentDirection()
+ const form = useTabbedForm<CreatePromotionSchemaType>()
+
+ return (
+ <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 data-testid="promotion-create-form-template-item">
+ <Form.Label data-testid="promotion-create-form-template-label">
+ {t("promotions.fields.type")}
+ </Form.Label>
+
+ <Form.Control data-testid="promotion-create-form-template-control">
+ <RadioGroup
+ dir={direction}
+ key="template_id"
+ className="flex-col gap-y-3"
+ {...field}
+ onValueChange={field.onChange}
+ data-testid="promotion-create-form-template-radio-group"
+ >
+ {templates.map((template) => {
+ return (
+ <RadioGroup.ChoiceBox
+ key={template.id}
+ value={template.id}
+ label={template.title}
+ description={template.description}
+ data-testid={`promotion-create-form-template-option-${template.id}`}
+ />
+ )
+ })}
+ </RadioGroup>
+ </Form.Control>
+ <Form.ErrorMessage data-testid="promotion-create-form-template-error" />
+ </Form.Item>
+ )
+ }}
+ />
+ </div>
+ </div>
+ )
+}
+
+Root._tabMeta = defineTabMeta<CreatePromotionSchemaType>({
+ id: "type",
+ labelKey: "promotions.tabs.template",
+ validationFields: ["template_id"],
+})
+
+export const PromotionTemplateTab = Root
diff --git a/packages/admin/src/pages/promotions/promotion-create/promotion-create.tsx b/packages/admin/src/pages/promotions/promotion-create/promotion-create.tsx
index 90e683285..20265bf4c 100644
--- a/packages/admin/src/pages/promotions/promotion-create/promotion-create.tsx
+++ b/packages/admin/src/pages/promotions/promotion-create/promotion-create.tsx
@@ -1,10 +1,34 @@
+import { Children, ReactNode } from "react"
+
import { RouteFocusModal } from "../../../components/modals"
+import { TabbedForm } from "../../../components/tabbed-form/tabbed-form"
import { CreatePromotionForm } from "./components/create-promotion-form/create-promotion-form"
+import { PromotionCampaignTab } from "./components/create-promotion-form/promotion-campaign-tab"
+import { PromotionDetailsTab } from "./components/create-promotion-form/promotion-details-tab"
+import { PromotionTemplateTab } from "./components/create-promotion-form/promotion-template-tab"
+import { CreatePromotionSchema } from "./components/create-promotion-form/form-schema"
-export const PromotionCreate = () => {
+const Root = ({ children }: { children?: ReactNode }) => {
return (
- <RouteFocusModal>
- <CreatePromotionForm />
+ <RouteFocusModal data-testid="promotion-create-modal">
+ {Children.count(children) > 0 ? (
+ children
+ ) : (
+ <CreatePromotionForm />
+ )}
</RouteFocusModal>
)
}
+
+export const PromotionCreatePage = Object.assign(Root, {
+ Form: CreatePromotionForm,
+ TemplateTab: PromotionTemplateTab,
+ DetailsTab: PromotionDetailsTab,
+ CampaignTab: PromotionCampaignTab,
+ Tab: TabbedForm.Tab,
+})
+
+export { CreatePromotionSchema }
+
+// Keep backward-compatible named export for route `Component`
+export const PromotionCreate = Root
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
index c5f2f52cb..843c03387 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/campaign-section/campaign-section.tsx
@@ -7,6 +7,7 @@ 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"
+import { usePromotion } from "../../../../../hooks/api/promotions"
const CampaignDetailSection = ({
campaign,
@@ -36,12 +37,16 @@ const CampaignDetailSection = ({
}
export const CampaignSection = ({
- campaign,
+ campaign: campaignProp,
}: {
- campaign: HttpTypes.AdminCampaign | null
+ campaign?: HttpTypes.AdminCampaign | null
}) => {
const { t } = useTranslation()
const { id } = useParams()
+ const { promotion } = usePromotion(id!, {
+ enabled: campaignProp === undefined,
+ })
+ const campaign = campaignProp !== undefined ? campaignProp : (promotion?.campaign ?? null)
const actions = [
{
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
index 70b051c2f..12d02e84d 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-conditions-section/promotion-conditions-section.tsx
@@ -6,10 +6,12 @@ import {
} from "@medusajs/types";
import { Badge, Container, Heading } from "@medusajs/ui";
import { useTranslation } from "react-i18next";
+import { useParams } from "react-router-dom";
import { ActionMenu } from "../../../../../components/common/action-menu";
import { BadgeListSummary } from "../../../../../components/common/badge-list-summary";
import { NoRecords } from "../../../../../components/common/empty-table-content";
+import { usePromotion, usePromotionRules } from "../../../../../hooks/api/promotions";
type RuleProps = {
rule: HttpTypes.AdminPromotionRule;
@@ -46,17 +48,29 @@ function RuleBlock({ rule }: RuleProps) {
}
type PromotionConditionsSectionProps = {
- rules: HttpTypes.AdminPromotionRule[];
+ rules?: HttpTypes.AdminPromotionRule[];
ruleType: string;
applicationMethodTargetType?: ApplicationMethodTargetTypeValues;
};
export const PromotionConditionsSection = ({
- rules,
+ rules: rulesProp,
ruleType,
applicationMethodTargetType,
}: PromotionConditionsSectionProps) => {
const { t } = useTranslation();
+ const { id } = useParams();
+ const { promotion } = usePromotion(id!, {
+ enabled: rulesProp === undefined,
+ });
+ const query: Record<string, string> = {};
+ if (promotion?.type === "buyget") {
+ query.promotion_type = promotion.type;
+ }
+ const { rules: fetchedRules } = usePromotionRules(id!, ruleType, query, {
+ enabled: rulesProp === undefined,
+ });
+ const rules = rulesProp ?? fetchedRules ?? [];
return (
<Container
diff --git a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
index 5992663e1..1f45d80ad 100644
--- a/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
+++ b/packages/admin/src/pages/promotions/promotion-detail/components/promotion-general-section/promotion-general-section.tsx
@@ -12,14 +12,16 @@ import {
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router-dom"
+import { useParams } from "react-router-dom"
+
import { ActionMenu } from "../../../../../components/common/action-menu"
-import { useDeletePromotion } from "../../../../../hooks/api/promotions"
+import { useDeletePromotion, usePromotion } from "../../../../../hooks/api/promotions"
import { formatCurrency } from "../../../../../lib/format-currency"
import { formatPercentage } from "../../../../../lib/percentage-helpers"
import { getPromotionStatus } from "../../../../../lib/promotions"
type PromotionGeneralSectionProps = {
- promotion: HttpTypes.AdminPromotion
+ promotion?: HttpTypes.AdminPromotion
}
function getDisplayValue(promotion: HttpTypes.AdminPromotion) {
@@ -45,12 +47,22 @@ function getDisplayValue(promotion: HttpTypes.AdminPromotion) {
}
export const PromotionGeneralSection = ({
- promotion,
+ promotion: promotionProp,
}: PromotionGeneralSectionProps) => {
const { t } = useTranslation()
const prompt = usePrompt()
const navigate = useNavigate()
- const { mutateAsync } = useDeletePromotion(promotion.id)
+ const { id } = useParams()
+ const { promotion: fetched } = usePromotion(id!, {
+ enabled: !promotionProp,
+ })
+ const promotion = promotionProp ?? fetched
+
+ const { mutateAsync } = useDeletePromotion(promotion?.id!)
+
+ if (!promotion) {
+ return null
+ }
const handleDelete = async () => {
const confirm = await prompt({
diff --git a/packages/admin/src/pages/sellers/seller-details/components/seller-order-section.tsx b/packages/admin/src/pages/sellers/seller-details/components/seller-order-section.tsx
index 46931362a..106a8459e 100644
--- a/packages/admin/src/pages/sellers/seller-details/components/seller-order-section.tsx
+++ b/packages/admin/src/pages/sellers/seller-details/components/seller-order-section.tsx
@@ -1,4 +1,4 @@
-import { Container, Heading } from "@medusajs/ui"
+import { Container, Heading, Text } from "@medusajs/ui"
import { keepPreviousData } from "@tanstack/react-query"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
@@ -24,7 +24,7 @@ export const SellerOrderSection = ({ sellerId }: { sellerId: string }) => {
prefix: PREFIX,
})
- const { orders, count, isLoading, isError, error } = useOrders(
+ const { orders, count, isLoading, isError } = useOrders(
{
...searchParams,
seller_id: sellerId,
@@ -48,7 +48,18 @@ export const SellerOrderSection = ({ sellerId }: { sellerId: string }) => {
})
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>
+ <div className="flex items-center justify-center px-6 py-12">
+ <Text size="small" className="text-ui-fg-muted">
+ {t("general.error")}
+ </Text>
+ </div>
+ </Container>
+ )
}
return (
diff --git a/packages/admin/src/pages/sellers/seller-details/components/seller-product-section.tsx b/packages/admin/src/pages/sellers/seller-details/components/seller-product-section.tsx
index 52b064658..0681ba2ae 100644
--- a/packages/admin/src/pages/sellers/seller-details/components/seller-product-section.tsx
+++ b/packages/admin/src/pages/sellers/seller-details/components/seller-product-section.tsx
@@ -2,7 +2,7 @@ import { useMemo } from "react";
import { PencilSquare, Trash } from "@medusajs/icons";
import { HttpTypes } from "@medusajs/types";
-import { Container, Heading, toast, usePrompt } from "@medusajs/ui";
+import { Container, Heading, Text, toast, usePrompt } from "@medusajs/ui";
import { keepPreviousData } from "@tanstack/react-query";
import { createColumnHelper } from "@tanstack/react-table";
import { useTranslation } from "react-i18next";
@@ -19,8 +19,6 @@ import { useDataTable } from "@hooks/use-data-table";
const PAGE_SIZE = 10;
const PREFIX = "selprod";
-const DEFAULT_FIELDS =
- "*collection,+type_id,+tag_id,+sales_channel_id,+status,+created_at,+updated_at";
export const SellerProductSection = ({ sellerId }: { sellerId: string }) => {
const { t } = useTranslation();
@@ -30,7 +28,7 @@ export const SellerProductSection = ({ sellerId }: { sellerId: string }) => {
prefix: PREFIX,
});
- const { products, count, isLoading, isError, error } = useProducts(
+ const { products, count, isLoading, isError } = useProducts(
{
...searchParams,
seller_id: sellerId,
@@ -53,7 +51,18 @@ export const SellerProductSection = ({ sellerId }: { sellerId: string }) => {
});
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>
+ <div className="flex items-center justify-center px-6 py-12">
+ <Text size="small" className="text-ui-fg-muted">
+ {t("general.error")}
+ </Text>
+ </div>
+ </Container>
+ );
}
return (