Skip to content

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

feat: add product import/export functionality for vendors (#734)

Jakub Sieradzki0069877c38f7
diff --git a/packages/registry/.mercur/_generated/index.ts b/packages/registry/.mercur/_generated/index.ts
index 2aeeee0cd..9872391a6 100644
--- a/packages/registry/.mercur/_generated/index.ts
+++ b/packages/registry/.mercur/_generated/index.ts
@@ -616,6 +616,8 @@ export type Routes = {
$variantId: typeof import("@mercurjs/core-plugin/api/vendor/products/[id]/variants/[variant_id]/route");
};
};
+ import: typeof import("../../src/product-import-export/api/vendor/products/import/route");
+ export: typeof import("../../src/product-import-export/api/vendor/products/export/route");
};
promotions: typeof import("@mercurjs/core-plugin/api/vendor/promotions/route") & {
$id: typeof import("@mercurjs/core-plugin/api/vendor/promotions/[id]/route") & {
diff --git a/packages/registry/package.json b/packages/registry/package.json
index d377a646d..23a3bbc7e 100644
--- a/packages/registry/package.json
+++ b/packages/registry/package.json
@@ -13,13 +13,16 @@
"@medusajs/medusa": "^2.13.0",
"@mercurjs/dashboard-shared": "*",
"@medusajs/ui": "4.1.1",
+ "@medusajs/icons": "2.13.1",
"@tanstack/react-query": "5.64.2",
"react-i18next": "13.5.0",
"react-router-dom": "6.30.3",
"@tanstack/react-table": "8.20.5",
"@mercurjs/client": "*",
"zod": "3.25.76",
- "@mercurjs/core-plugin": "*"
+ "@mercurjs/core-plugin": "*",
+ "@mercurjs/vendor": "*",
+ "@medusajs/core-flows": "^2.13.0"
},
"devDependencies": {
"@mercurjs/types": "*",
@@ -28,6 +31,7 @@
"@types/react-dom": "^18.2.22",
"@types/node": "^22",
"@types/unzipper": "^0.10.10",
- "@medusajs/cli": "^2.13.0"
+ "@medusajs/cli": "^2.13.0",
+ "@types/multer": "^2.0.0"
}
}
\ No newline at end of file
diff --git a/packages/registry/r/product-import-export.json b/packages/registry/r/product-import-export.json
new file mode 100644
index 000000000..5fa15a991
--- /dev/null
+++ b/packages/registry/r/product-import-export.json
@@ -0,0 +1,93 @@
+{
+ "$schema": "https://registry.mercurjs.com/registry-item.json",
+ "name": "product-import-export",
+ "description": "CSV product import & export for vendors. Includes API routes, workflows, and vendor portal drawers.",
+ "dependencies": [
+ "multer",
+ "@types/multer"
+ ],
+ "registryDependencies": [],
+ "docs": "## Product Import/Export Block\n\n### Configuration\n\nNo additional modules needed — uses built-in Medusa product CSV steps.\n\n### Middleware Setup\n\nAdd the import middleware to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from '@medusajs/medusa'\nimport { productImportExportMiddlewares } from './vendor/products/middlewares'\n\nexport default defineMiddlewares({\n routes: [...productImportExportMiddlewares],\n})\n```\n\n### Run codegen\n\nAfter installing the block, regenerate SDK types:\n\n```bash\nmercurjs codegen\n```\n\n### Vendor Navigation\n\nThe block includes a `products/page.tsx` that overrides the default product list page, adding Import and Export buttons in the header. The buttons open drawer routes at `/products/import` and `/products/export`.",
+ "categories": [
+ "api",
+ "workflow",
+ "vendor"
+ ],
+ "files": [
+ {
+ "path": "product-import-export/workflows/steps/get-seller-products.ts",
+ "content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\n\ntype GetSellerProductsStepInput = {\n seller_id: string\n}\n\nexport const getSellerProductsStep = createStep(\n \"get-seller-products\",\n async (input: GetSellerProductsStepInput, { container }) => {\n const query = container.resolve(ContainerRegistrationKeys.QUERY)\n\n const { data: relations } = await query.graph({\n entity: \"product_seller\",\n fields: [\n \"product.*\",\n \"product.variants.*\",\n \"product.variants.prices.*\",\n \"product.variants.options.*\",\n \"product.options.*\",\n \"product.collection.*\",\n \"product.categories.*\",\n \"product.sales_channels.*\",\n \"product.images.*\",\n \"product.tags.*\",\n \"product.type.*\",\n ],\n filters: {\n seller_id: input.seller_id,\n },\n })\n\n const products = relations.map((r: any) => r.product)\n\n return new StepResponse(products)\n }\n)\n",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/steps/validate-products-to-import.ts",
+ "content": "import { createStep, StepResponse } from \"@medusajs/framework/workflows-sdk\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\nimport { z } from \"zod\"\n\nconst CreateVariantPrice = z.object({\n currency_code: z.string(),\n amount: z.number(),\n})\n\nconst CreateProductOption = z.object({\n title: z.string(),\n values: z.array(z.string()).optional(),\n})\n\nconst CreateProductVariant = z.object({\n title: z.string(),\n sku: z.string().optional().nullable(),\n barcode: z.string().optional().nullable(),\n ean: z.string().optional().nullable(),\n upc: z.string().optional().nullable(),\n hs_code: z.string().optional().nullable(),\n mid_code: z.string().optional().nullable(),\n manage_inventory: z.boolean().optional(),\n allow_backorder: z.boolean().optional(),\n weight: z.number().optional().nullable(),\n length: z.number().optional().nullable(),\n height: z.number().optional().nullable(),\n width: z.number().optional().nullable(),\n material: z.string().optional().nullable(),\n origin_country: z.string().optional().nullable(),\n options: z.record(z.string()).optional(),\n prices: z.array(CreateVariantPrice).optional(),\n inventory_quantity: z.number().optional(),\n})\n\nconst CreateProduct = z.object({\n title: z.string(),\n subtitle: z.string().optional().nullable(),\n description: z.string().optional().nullable(),\n handle: z.string().optional(),\n status: z.enum([\"draft\", \"proposed\", \"published\", \"rejected\"]).optional(),\n thumbnail: z.string().optional().nullable(),\n weight: z.number().optional().nullable(),\n length: z.number().optional().nullable(),\n height: z.number().optional().nullable(),\n width: z.number().optional().nullable(),\n hs_code: z.string().optional().nullable(),\n mid_code: z.string().optional().nullable(),\n material: z.string().optional().nullable(),\n origin_country: z.string().optional().nullable(),\n collection_id: z.string().optional().nullable(),\n type_id: z.string().optional().nullable(),\n tags: z.array(z.object({ id: z.string() })).optional(),\n categories: z.array(z.object({ id: z.string() })).optional(),\n sales_channels: z.array(z.object({ id: z.string() })).optional(),\n images: z.array(z.object({ url: z.string() })).optional(),\n options: z.array(CreateProductOption).optional(),\n variants: z.array(CreateProductVariant).optional(),\n})\n\ntype ValidateProductsToImportStepInput = {\n products: Record<string, any>[]\n}\n\nexport const validateProductsToImportStep = createStep(\n \"validate-products-to-import\",\n async (input: ValidateProductsToImportStepInput) => {\n const errors: string[] = []\n\n for (let i = 0; i < input.products.length; i++) {\n const result = CreateProduct.safeParse(input.products[i])\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join(\".\")}: ${issue.message}`)\n .join(\"; \")\n errors.push(`Product ${i + 1}: ${issues}`)\n }\n }\n\n if (errors.length > 0) {\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n `Validation failed for ${errors.length} product(s):\\n${errors.join(\"\\n\")}`\n )\n }\n\n return new StepResponse(input.products)\n }\n)\n",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/import-seller-products.ts",
+ "content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport { parseProductCsvStep } from \"@medusajs/core-flows\"\nimport { createProductsWorkflow } from \"@medusajs/core-flows\"\nimport { validateProductsToImportStep } from \"./steps/validate-products-to-import\"\n\ntype ImportSellerProductsWorkflowInput = {\n file_content: string\n seller_id: string\n}\n\nexport const importSellerProductsWorkflow = createWorkflow(\n \"import-seller-products\",\n function (input: ImportSellerProductsWorkflowInput) {\n const parsedProducts = parseProductCsvStep(input.file_content)\n\n validateProductsToImportStep({ products: parsedProducts })\n\n const productsInput = transform(\n { parsedProducts },\n ({ parsedProducts }) => ({\n products: parsedProducts.map((p: any) => ({\n ...p,\n status: p.status || \"draft\",\n })),\n })\n )\n\n const createdProducts = createProductsWorkflow.runAsStep({\n input: productsInput,\n })\n\n return new WorkflowResponse(createdProducts)\n }\n)\n",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/export-seller-products.ts",
+ "content": "import {\n createWorkflow,\n transform,\n WorkflowResponse,\n} from \"@medusajs/framework/workflows-sdk\"\nimport {\n generateProductCsvStep,\n useQueryGraphStep,\n} from \"@medusajs/core-flows\"\nimport { getSellerProductsStep } from \"./steps/get-seller-products\"\n\ntype ExportSellerProductsWorkflowInput = {\n seller_id: string\n}\n\nexport const exportSellerProductsWorkflow = createWorkflow(\n \"export-seller-products\",\n function (input: ExportSellerProductsWorkflowInput) {\n const products = getSellerProductsStep({\n seller_id: input.seller_id,\n })\n\n const csvFile = generateProductCsvStep(products)\n\n const fileData = useQueryGraphStep({\n entity: \"file\",\n fields: [\"id\", \"url\"],\n filters: {\n id: csvFile.id,\n },\n options: {\n throwIfKeyNotFound: true,\n },\n })\n\n const result = transform({ fileData }, ({ fileData }) => {\n const file = fileData.data[0]\n return { url: file.url }\n })\n\n return new WorkflowResponse(result)\n }\n)\n",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/import/route.ts",
+ "content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework/http\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\nimport { importSellerProductsWorkflow } from \"../../../../workflows/import-seller-products\"\nimport { fetchSellerByAuthActorId } from \"../helpers/helpers\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest<{ file: Express.Multer.File }>,\n res: MedusaResponse<{ summary: { created: number } }>\n) => {\n const file = (req as any).file as Express.Multer.File | undefined\n\n if (!file) {\n throw new MedusaError(\n MedusaError.Types.INVALID_DATA,\n \"No file uploaded. Please upload a CSV file.\"\n )\n }\n\n const seller = await fetchSellerByAuthActorId(\n req.auth_context.actor_id,\n req.scope\n )\n\n if (!seller) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Seller not found for the current user.\"\n )\n }\n\n const fileContent = file.buffer.toString(\"utf-8\")\n\n const { result } = await importSellerProductsWorkflow(req.scope).run({\n input: {\n file_content: fileContent,\n seller_id: seller.id,\n },\n })\n\n res.status(200).json({\n summary: {\n created: Array.isArray(result) ? result.length : 0,\n },\n })\n}\n",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/export/route.ts",
+ "content": "import {\n AuthenticatedMedusaRequest,\n MedusaResponse,\n} from \"@medusajs/framework/http\"\nimport { MedusaError } from \"@medusajs/framework/utils\"\nimport { exportSellerProductsWorkflow } from \"../../../../workflows/export-seller-products\"\nimport { fetchSellerByAuthActorId } from \"../helpers/helpers\"\n\nexport const POST = async (\n req: AuthenticatedMedusaRequest,\n res: MedusaResponse<{ url: string }>\n) => {\n const seller = await fetchSellerByAuthActorId(\n req.auth_context.actor_id,\n req.scope\n )\n\n if (!seller) {\n throw new MedusaError(\n MedusaError.Types.NOT_FOUND,\n \"Seller not found for the current user.\"\n )\n }\n\n const { result } = await exportSellerProductsWorkflow(req.scope).run({\n input: {\n seller_id: seller.id,\n },\n })\n\n res.json(result)\n}\n",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/helpers/helpers.ts",
+ "content": "import { ContainerRegistrationKeys } from \"@medusajs/framework/utils\"\nimport { MedusaContainer } from \"@medusajs/framework/types\"\n\nexport const fetchSellerByAuthActorId = async (\n authActorId: string,\n scope: MedusaContainer,\n fields: string[] = [\"id\"]\n) => {\n const query = scope.resolve(ContainerRegistrationKeys.QUERY)\n\n const {\n data: [seller],\n } = await query.graph({\n entity: \"seller\",\n filters: { id: authActorId },\n fields,\n })\n\n return seller\n}\n",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/middlewares.ts",
+ "content": "import { MiddlewareRoute } from \"@medusajs/medusa\"\nimport multer from \"multer\"\n\nconst upload = multer({ storage: multer.memoryStorage() })\n\nexport const productImportExportMiddlewares: MiddlewareRoute[] = [\n {\n method: [\"POST\"],\n matcher: \"/vendor/products/import\",\n middlewares: [upload.single(\"file\")],\n },\n]\n",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/vendor/hooks/api/product-import-export.tsx",
+ "content": "import { useMutation, useQueryClient } from \"@tanstack/react-query\"\nimport type { UseMutationOptions } from \"@tanstack/react-query\"\nimport { queryKeysFactory } from \"@mercurjs/dashboard-shared\"\nimport { ClientError } from \"@mercurjs/client\"\nimport { client } from \"../../lib/client\"\n\nconst PRODUCTS_QUERY_KEY = \"vendor_products\" as const\nexport const productsQueryKeys = queryKeysFactory(PRODUCTS_QUERY_KEY)\n\ntype ImportProductsResponse = { summary: { created: number } }\ntype ExportProductsResponse = { url: string }\n\nexport const useImportProducts = (\n options?: UseMutationOptions<ImportProductsResponse, ClientError, File>\n) => {\n const queryClient = useQueryClient()\n\n return useMutation({\n mutationFn: async (file: any) => client.vendor.products.import.mutate({file, fetchOptions: {headers:{'Content-Type': 'multipart/form-data'}}}),\n onSuccess: (data, variables, context) => {\n queryClient.invalidateQueries({ queryKey: productsQueryKeys.lists() })\n options?.onSuccess?.(data, variables, context)\n },\n ...options,\n })\n}\n\nexport const useExportProducts = (\n options?: UseMutationOptions<ExportProductsResponse, ClientError, void>\n) => {\n return useMutation({\n mutationFn: async () =>\n client.vendor.products.export.mutate(),\n onSuccess: (data, variables, context) => {\n options?.onSuccess?.(data, variables, context)\n },\n ...options,\n })\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/page.tsx",
+ "content": "import { Link } from \"react-router-dom\"\nimport { Button } from \"@medusajs/ui\"\nimport { ArrowDownTray, ArrowUpTray } from \"@medusajs/icons\"\nimport { ProductListPage } from \"@mercurjs/vendor/pages\"\n\nexport default function ProductsWithImportExport() {\n return (\n <ProductListPage>\n <ProductListPage.Table>\n <ProductListPage.Header>\n <ProductListPage.HeaderTitle />\n <ProductListPage.HeaderActions>\n <Button size=\"small\" variant=\"secondary\" asChild>\n <Link to=\"import\">\n <ArrowUpTray />\n Import\n </Link>\n </Button>\n <Button size=\"small\" variant=\"secondary\" asChild>\n <Link to=\"export\">\n <ArrowDownTray />\n Export\n </Link>\n </Button>\n <ProductListPage.HeaderCreateButton />\n </ProductListPage.HeaderActions>\n </ProductListPage.Header>\n <ProductListPage.DataTable />\n </ProductListPage.Table>\n </ProductListPage>\n )\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/page.tsx",
+ "content": "import { useState } from \"react\"\nimport { Button, Heading } from \"@medusajs/ui\"\n\nimport { RouteDrawer } from \"@mercurjs/dashboard-shared\"\nimport { UploadImport } from \"./_components/upload-import\"\nimport { ImportSummary } from \"./_components/import-summary\"\n\nexport default function ProductImportPage() {\n const [summary, setSummary] = useState<{ created: number } | null>(null)\n\n return (\n <RouteDrawer>\n <RouteDrawer.Header>\n <RouteDrawer.Title asChild>\n <Heading>Import Products</Heading>\n </RouteDrawer.Title>\n <RouteDrawer.Description>\n Upload a CSV file to import products into your store.\n </RouteDrawer.Description>\n </RouteDrawer.Header>\n <RouteDrawer.Body>\n {summary ? (\n <ImportSummary created={summary.created} />\n ) : (\n <UploadImport onSuccess={setSummary} />\n )}\n </RouteDrawer.Body>\n <RouteDrawer.Footer>\n <RouteDrawer.Close asChild>\n <Button variant=\"secondary\">\n {summary ? \"Done\" : \"Cancel\"}\n </Button>\n </RouteDrawer.Close>\n </RouteDrawer.Footer>\n </RouteDrawer>\n )\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/upload-import.tsx",
+ "content": "import { useState } from \"react\"\nimport { Button, toast } from \"@medusajs/ui\"\nimport { Trash } from \"@medusajs/icons\"\n\nimport { FileUpload, FilePreview } from \"@mercurjs/dashboard-shared\"\nimport type { FileType } from \"@mercurjs/dashboard-shared\"\nimport { useImportProducts } from \"../../../../hooks/api/product-import-export\"\nimport { downloadImportTemplate } from \"../_helpers/import-template\"\n\ntype UploadImportProps = {\n onSuccess: (summary: { created: number }) => void\n}\n\nexport const UploadImport = ({ onSuccess }: UploadImportProps) => {\n const [file, setFile] = useState<FileType | null>(null)\n\n const { mutateAsync: importProducts, isPending } = useImportProducts({\n onSuccess: (data) => {\n toast.success(\n `Successfully imported ${data.summary?.created ?? 0} product(s).`\n )\n onSuccess(data.summary)\n },\n onError: (error) => {\n toast.error(error.message)\n },\n })\n\n const handleFileUpload = (files: FileType[]) => {\n if (files.length > 0) {\n setFile(files[0] ?? null)\n }\n }\n\n const handleImport = async () => {\n if (!file) return\n await importProducts(file.file)\n }\n\n const handleRemoveFile = () => {\n setFile(null)\n }\n\n return (\n <div className=\"flex flex-col gap-y-4\">\n <div className=\"rounded-lg border border-ui-border-base bg-ui-bg-subtle p-3\">\n <span className=\"text-ui-fg-subtle txt-small\">\n Upload a CSV file with your products. You can{\" \"}\n <button\n type=\"button\"\n className=\"text-ui-fg-interactive hover:text-ui-fg-interactive-hover underline\"\n onClick={downloadImportTemplate}\n >\n download the template\n </button>{\" \"}\n to get started.\n </span>\n </div>\n\n {!file ? (\n <FileUpload\n label=\"Upload CSV file\"\n hint=\"Only .csv files are supported\"\n formats={[\".csv\", \"text/csv\"]}\n onUploaded={handleFileUpload}\n multiple={false}\n />\n ) : (\n <FilePreview\n filename={file.file.name}\n loading={isPending}\n activity=\"Importing products...\"\n actions={[\n {\n actions: [\n {\n icon: <Trash />,\n label: \"Remove\",\n onClick: handleRemoveFile,\n },\n ],\n },\n ]}\n />\n )}\n\n {file && (\n <div className=\"flex justify-end\">\n <Button\n onClick={handleImport}\n isLoading={isPending}\n disabled={!file}\n >\n Import Products\n </Button>\n </div>\n )}\n </div>\n )\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/import-summary.tsx",
+ "content": "import { Text } from \"@medusajs/ui\"\nimport { CheckCircleSolid } from \"@medusajs/icons\"\n\ntype ImportSummaryProps = {\n created: number\n}\n\nexport const ImportSummary = ({ created }: ImportSummaryProps) => {\n return (\n <div className=\"flex flex-col items-center gap-y-4 py-8\">\n <CheckCircleSolid className=\"text-ui-fg-interactive\" />\n <div className=\"flex flex-col items-center gap-y-1\">\n <Text size=\"large\" weight=\"plus\">\n Import Complete\n </Text>\n <Text className=\"text-ui-fg-subtle\">\n {created} product(s) were successfully created.\n </Text>\n </div>\n </div>\n )\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/helpers/import-template.ts",
+ "content": "const IMPORT_TEMPLATE_HEADER = [\n \"Product Id\",\n \"Product Handle\",\n \"Product Title\",\n \"Product Subtitle\",\n \"Product Description\",\n \"Product Status\",\n \"Product Thumbnail\",\n \"Product Weight\",\n \"Product Length\",\n \"Product Width\",\n \"Product Height\",\n \"Product HS Code\",\n \"Product Origin Country\",\n \"Product MID Code\",\n \"Product Material\",\n \"Product Collection Id\",\n \"Product Collection Title\",\n \"Product Type Id\",\n \"Product Type\",\n \"Product Tags\",\n \"Product Discountable\",\n \"Product External Id\",\n \"Variant Id\",\n \"Variant Title\",\n \"Variant SKU\",\n \"Variant Barcode\",\n \"Variant Inventory Quantity\",\n \"Variant Allow Backorder\",\n \"Variant Manage Inventory\",\n \"Variant Weight\",\n \"Variant Length\",\n \"Variant Width\",\n \"Variant Height\",\n \"Variant HS Code\",\n \"Variant Origin Country\",\n \"Variant MID Code\",\n \"Variant Material\",\n \"Variant EAN\",\n \"Variant UPC\",\n \"Option 1 Name\",\n \"Option 1 Value\",\n \"Option 2 Name\",\n \"Option 2 Value\",\n \"Price USD\",\n \"Price EUR\",\n]\n\nexport const getImportTemplateContent = (): string => {\n return IMPORT_TEMPLATE_HEADER.join(\",\") + \"\\n\"\n}\n\nexport const downloadImportTemplate = () => {\n const content = getImportTemplateContent()\n const blob = new Blob([content], { type: \"text/csv\" })\n const url = URL.createObjectURL(blob)\n const a = document.createElement(\"a\")\n a.href = url\n a.download = \"product-import-template.csv\"\n a.click()\n URL.revokeObjectURL(url)\n}\n",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/export/page.tsx",
+ "content": "import { Button, Heading, Text, toast } from \"@medusajs/ui\"\n\nimport { RouteDrawer, useRouteModal } from \"@mercurjs/dashboard-shared\"\nimport { useExportProducts } from \"../../../hooks/api/product-import-export\"\n\nfunction ExportProductsContent() {\n const { handleSuccess } = useRouteModal()\n\n const { mutateAsync: exportProducts, isPending } = useExportProducts({\n onSuccess: (data) => {\n if (data.url) {\n const a = document.createElement(\"a\")\n a.href = data.url\n a.download = `products-export-${Date.now()}.csv`\n a.click()\n }\n toast.success(\"Products exported successfully.\")\n handleSuccess()\n },\n onError: (error) => {\n toast.error(error.message)\n },\n })\n\n const handleExport = async () => {\n await exportProducts()\n }\n\n return (\n <>\n <RouteDrawer.Header>\n <RouteDrawer.Title asChild>\n <Heading>Export Products</Heading>\n </RouteDrawer.Title>\n <RouteDrawer.Description>\n Export your products as a CSV file.\n </RouteDrawer.Description>\n </RouteDrawer.Header>\n <RouteDrawer.Body>\n <div className=\"flex flex-col gap-y-4\">\n <Text className=\"text-ui-fg-subtle\">\n This will export all your products to a CSV file. The download will\n start automatically when the export is ready.\n </Text>\n </div>\n </RouteDrawer.Body>\n <RouteDrawer.Footer>\n <RouteDrawer.Close asChild>\n <Button variant=\"secondary\">Cancel</Button>\n </RouteDrawer.Close>\n <Button onClick={handleExport} isLoading={isPending}>\n Export\n </Button>\n </RouteDrawer.Footer>\n </>\n )\n}\n\nexport default function ProductExportPage() {\n return (\n <RouteDrawer>\n <ExportProductsContent />\n </RouteDrawer>\n )\n}\n",
+ "type": "registry:vendor"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/packages/registry/r/registry.json b/packages/registry/r/registry.json
index 0a186cff1..ffbda86b1 100644
--- a/packages/registry/r/registry.json
+++ b/packages/registry/r/registry.json
@@ -8,7 +8,7 @@
"description": "A review system with product and seller reviews, ratings, customer/vendor/admin API routes, and workflows.",
"dependencies": [],
"registryDependencies": [],
- "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```",
+ "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```\n\n## Middlewares\n\nAdd the review middlewares to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from \"@medusajs/medusa\";\nimport { adminMiddlewares } from \"./admin/middlewares\";\nimport { vendorMiddlewares } from \"./vendor/middlewares\";\nimport { storeReviewMiddlewares } from \"./store/reviews/middlewares\";\n\nexport default defineMiddlewares({\n routes: [...adminMiddlewares, ...vendorMiddlewares, ...storeReviewMiddlewares],\n});\n```\n\nIf you already have a `middlewares.ts` file, merge the review middleware imports and spread them into your existing `routes` array.",
"files": [
{
"path": "reviews/modules/reviews/index.ts",
@@ -90,10 +90,6 @@
"path": "reviews/workflows/review/workflows/delete-review.ts",
"type": "registry:workflow"
},
- {
- "path": "reviews/api/middlewares.ts",
- "type": "registry:api"
- },
{
"path": "reviews/api/admin/middlewares.ts",
"type": "registry:api"
@@ -230,6 +226,80 @@
"categories": [
"reviews"
]
+ },
+ {
+ "name": "product-import-export",
+ "description": "CSV product import & export for vendors. Includes API routes, workflows, and vendor portal drawers.",
+ "dependencies": ["multer", "@types/multer"],
+ "registryDependencies": [],
+ "docs": "## Product Import/Export Block\n\n### Configuration\n\nNo additional modules needed — uses built-in Medusa product CSV steps.\n\n### Middleware Setup\n\nAdd the import middleware to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from '@medusajs/medusa'\nimport { productImportExportMiddlewares } from './vendor/products/middlewares'\n\nexport default defineMiddlewares({\n routes: [...productImportExportMiddlewares],\n})\n```\n\n### Run codegen\n\nAfter installing the block, regenerate SDK types:\n\n```bash\nmercurjs codegen\n```\n\n### Vendor Navigation\n\nThe block includes a `products/page.tsx` that overrides the default product list page, adding Import and Export buttons in the header. The buttons open drawer routes at `/products/import` and `/products/export`.",
+ "files": [
+ {
+ "path": "product-import-export/workflows/steps/get-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/steps/validate-products-to-import.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/import-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/export-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/import/route.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/export/route.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/helpers/helpers.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/middlewares.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/vendor/hooks/api/product-import-export.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/page.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/page.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/upload-import.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/import-summary.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/helpers/import-template.ts",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/export/page.tsx",
+ "type": "registry:vendor"
+ }
+ ],
+ "categories": [
+ "api",
+ "workflow",
+ "vendor"
+ ]
}
]
}
\ No newline at end of file
diff --git a/packages/registry/r/reviews.json b/packages/registry/r/reviews.json
index f1d528eee..336e5c703 100644
--- a/packages/registry/r/reviews.json
+++ b/packages/registry/r/reviews.json
@@ -4,7 +4,7 @@
"description": "A review system with product and seller reviews, ratings, customer/vendor/admin API routes, and workflows.",
"dependencies": [],
"registryDependencies": [],
- "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```",
+ "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```\n\n## Middlewares\n\nAdd the review middlewares to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from \"@medusajs/medusa\";\nimport { adminMiddlewares } from \"./admin/middlewares\";\nimport { vendorMiddlewares } from \"./vendor/middlewares\";\nimport { storeReviewMiddlewares } from \"./store/reviews/middlewares\";\n\nexport default defineMiddlewares({\n routes: [...adminMiddlewares, ...vendorMiddlewares, ...storeReviewMiddlewares],\n});\n```\n\nIf you already have a `middlewares.ts` file, merge the review middleware imports and spread them into your existing `routes` array.",
"categories": [
"reviews"
],
@@ -109,11 +109,6 @@
"content": "import {\n WorkflowResponse,\n createWorkflow,\n} from \"@medusajs/framework/workflows-sdk\";\n\nimport { deleteReviewStep } from \"../steps\";\n\nexport const deleteReviewWorkflow = createWorkflow(\n {\n name: \"delete-review\",\n },\n function (id: string) {\n deleteReviewStep(id);\n\n return new WorkflowResponse(id);\n }\n);\n",
"type": "registry:workflow"
},
- {
- "path": "reviews/api/middlewares.ts",
- "content": "import { defineMiddlewares } from \"@medusajs/medusa\";\n\nimport { adminMiddlewares } from \"./admin/middlewares\";\nimport { vendorMiddlewares } from \"./vendor/middlewares\";\nimport { storeReviewMiddlewares } from \"./store/reviews/middlewares\";\n\nexport default defineMiddlewares({\n routes: [...adminMiddlewares, ...vendorMiddlewares, ...storeReviewMiddlewares],\n});\n",
- "type": "registry:api"
- },
{
"path": "reviews/api/admin/middlewares.ts",
"content": "import { MiddlewareRoute } from \"@medusajs/framework\";\nimport { reviewsMiddlewares } from \"./reviews/middlewares\";\n\nexport const adminMiddlewares: MiddlewareRoute[] = [...reviewsMiddlewares];\n",
diff --git a/packages/registry/registry.json b/packages/registry/registry.json
index 292ad9e4c..ffbda86b1 100644
--- a/packages/registry/registry.json
+++ b/packages/registry/registry.json
@@ -8,7 +8,7 @@
"description": "A review system with product and seller reviews, ratings, customer/vendor/admin API routes, and workflows.",
"dependencies": [],
"registryDependencies": [],
- "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```\n\n## Middlewares\n\nAdd the review middlewares to your `src/api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from \"@medusajs/medusa\";\nimport { adminMiddlewares } from \"./admin/middlewares\";\nimport { vendorMiddlewares } from \"./vendor/middlewares\";\nimport { storeReviewMiddlewares } from \"./store/reviews/middlewares\";\n\nexport default defineMiddlewares({\n routes: [...adminMiddlewares, ...vendorMiddlewares, ...storeReviewMiddlewares],\n});\n```\n\nIf you already have a `middlewares.ts` file, merge the review middleware imports and spread them into your existing `routes` array.",
+ "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`:\n\n```ts\nmodules: [\n {\n resolve: './modules/reviews',\n },\n]\n```\n\n## Middlewares\n\nAdd the review middlewares to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from \"@medusajs/medusa\";\nimport { adminMiddlewares } from \"./admin/middlewares\";\nimport { vendorMiddlewares } from \"./vendor/middlewares\";\nimport { storeReviewMiddlewares } from \"./store/reviews/middlewares\";\n\nexport default defineMiddlewares({\n routes: [...adminMiddlewares, ...vendorMiddlewares, ...storeReviewMiddlewares],\n});\n```\n\nIf you already have a `middlewares.ts` file, merge the review middleware imports and spread them into your existing `routes` array.",
"files": [
{
"path": "reviews/modules/reviews/index.ts",
@@ -226,6 +226,80 @@
"categories": [
"reviews"
]
+ },
+ {
+ "name": "product-import-export",
+ "description": "CSV product import & export for vendors. Includes API routes, workflows, and vendor portal drawers.",
+ "dependencies": ["multer", "@types/multer"],
+ "registryDependencies": [],
+ "docs": "## Product Import/Export Block\n\n### Configuration\n\nNo additional modules needed — uses built-in Medusa product CSV steps.\n\n### Middleware Setup\n\nAdd the import middleware to your `api/middlewares.ts`:\n\n```ts\nimport { defineMiddlewares } from '@medusajs/medusa'\nimport { productImportExportMiddlewares } from './vendor/products/middlewares'\n\nexport default defineMiddlewares({\n routes: [...productImportExportMiddlewares],\n})\n```\n\n### Run codegen\n\nAfter installing the block, regenerate SDK types:\n\n```bash\nmercurjs codegen\n```\n\n### Vendor Navigation\n\nThe block includes a `products/page.tsx` that overrides the default product list page, adding Import and Export buttons in the header. The buttons open drawer routes at `/products/import` and `/products/export`.",
+ "files": [
+ {
+ "path": "product-import-export/workflows/steps/get-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/steps/validate-products-to-import.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/import-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/workflows/export-seller-products.ts",
+ "type": "registry:workflow"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/import/route.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/export/route.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/helpers/helpers.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/api/vendor/products/middlewares.ts",
+ "type": "registry:api"
+ },
+ {
+ "path": "product-import-export/vendor/hooks/api/product-import-export.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/page.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/page.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/upload-import.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/components/import-summary.tsx",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/import/helpers/import-template.ts",
+ "type": "registry:vendor"
+ },
+ {
+ "path": "product-import-export/vendor/pages/products/export/page.tsx",
+ "type": "registry:vendor"
+ }
+ ],
+ "categories": [
+ "api",
+ "workflow",
+ "vendor"
+ ]
}
]
}
\ No newline at end of file
diff --git a/packages/registry/src/product-import-export/api/vendor/products/export/route.ts b/packages/registry/src/product-import-export/api/vendor/products/export/route.ts
new file mode 100644
index 000000000..8e012861b
--- /dev/null
+++ b/packages/registry/src/product-import-export/api/vendor/products/export/route.ts
@@ -0,0 +1,32 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+import { exportSellerProductsWorkflow } from "../../../../workflows/export-seller-products"
+import { fetchSellerByAuthActorId } from "../helpers/helpers"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<{ url: string }>
+) => {
+ const seller = await fetchSellerByAuthActorId(
+ req.auth_context.actor_id,
+ req.scope
+ )
+
+ if (!seller) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ "Seller not found for the current user."
+ )
+ }
+
+ const { result } = await exportSellerProductsWorkflow(req.scope).run({
+ input: {
+ seller_id: seller.id,
+ },
+ })
+
+ res.json(result)
+}
diff --git a/packages/registry/src/product-import-export/api/vendor/products/helpers/helpers.ts b/packages/registry/src/product-import-export/api/vendor/products/helpers/helpers.ts
new file mode 100644
index 000000000..68901dc1d
--- /dev/null
+++ b/packages/registry/src/product-import-export/api/vendor/products/helpers/helpers.ts
@@ -0,0 +1,20 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+
+export const fetchSellerByAuthActorId = async (
+ authActorId: string,
+ scope: MedusaContainer,
+ fields: string[] = ["id"]
+) => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [seller],
+ } = await query.graph({
+ entity: "seller",
+ filters: { id: authActorId },
+ fields,
+ })
+
+ return seller
+}
diff --git a/packages/registry/src/product-import-export/api/vendor/products/import/route.ts b/packages/registry/src/product-import-export/api/vendor/products/import/route.ts
new file mode 100644
index 000000000..891a93df8
--- /dev/null
+++ b/packages/registry/src/product-import-export/api/vendor/products/import/route.ts
@@ -0,0 +1,48 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { MedusaError } from "@medusajs/framework/utils"
+import { importSellerProductsWorkflow } from "../../../../workflows/import-seller-products"
+import { fetchSellerByAuthActorId } from "../helpers/helpers"
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<{ file: Express.Multer.File }>,
+ res: MedusaResponse<{ summary: { created: number } }>
+) => {
+ const file = (req as any).file as Express.Multer.File | undefined
+
+ if (!file) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ "No file uploaded. Please upload a CSV file."
+ )
+ }
+
+ const seller = await fetchSellerByAuthActorId(
+ req.auth_context.actor_id,
+ req.scope
+ )
+
+ if (!seller) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ "Seller not found for the current user."
+ )
+ }
+
+ const fileContent = file.buffer.toString("utf-8")
+
+ const { result } = await importSellerProductsWorkflow(req.scope).run({
+ input: {
+ file_content: fileContent,
+ seller_id: seller.id,
+ },
+ })
+
+ res.status(200).json({
+ summary: {
+ created: Array.isArray(result) ? result.length : 0,
+ },
+ })
+}
diff --git a/packages/registry/src/product-import-export/api/vendor/products/middlewares.ts b/packages/registry/src/product-import-export/api/vendor/products/middlewares.ts
new file mode 100644
index 000000000..fda1706d7
--- /dev/null
+++ b/packages/registry/src/product-import-export/api/vendor/products/middlewares.ts
@@ -0,0 +1,12 @@
+import { MiddlewareRoute } from "@medusajs/medusa"
+import multer from "multer"
+
+const upload = multer({ storage: multer.memoryStorage() })
+
+export const productImportExportMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["POST"],
+ matcher: "/vendor/products/import",
+ middlewares: [upload.single("file")],
+ },
+]
diff --git a/packages/registry/src/product-import-export/vendor/hooks/api/product-import-export.tsx b/packages/registry/src/product-import-export/vendor/hooks/api/product-import-export.tsx
new file mode 100644
index 000000000..28df6ded7
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/hooks/api/product-import-export.tsx
@@ -0,0 +1,39 @@
+import { useMutation, useQueryClient } from "@tanstack/react-query"
+import type { UseMutationOptions } from "@tanstack/react-query"
+import { queryKeysFactory } from "@mercurjs/dashboard-shared"
+import { ClientError } from "@mercurjs/client"
+import { client } from "../../lib/client"
+
+const PRODUCTS_QUERY_KEY = "vendor_products" as const
+export const productsQueryKeys = queryKeysFactory(PRODUCTS_QUERY_KEY)
+
+type ImportProductsResponse = { summary: { created: number } }
+type ExportProductsResponse = { url: string }
+
+export const useImportProducts = (
+ options?: UseMutationOptions<ImportProductsResponse, ClientError, File>
+) => {
+ const queryClient = useQueryClient()
+
+ return useMutation({
+ mutationFn: async (file: any) => client.vendor.products.import.mutate({file, fetchOptions: {headers:{'Content-Type': 'multipart/form-data'}}}),
+ onSuccess: (data, variables, context) => {
+ queryClient.invalidateQueries({ queryKey: productsQueryKeys.lists() })
+ options?.onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
+
+export const useExportProducts = (
+ options?: UseMutationOptions<ExportProductsResponse, ClientError, void>
+) => {
+ return useMutation({
+ mutationFn: async () =>
+ client.vendor.products.export.mutate(),
+ onSuccess: (data, variables, context) => {
+ options?.onSuccess?.(data, variables, context)
+ },
+ ...options,
+ })
+}
diff --git a/packages/registry/src/product-import-export/vendor/lib/client.ts b/packages/registry/src/product-import-export/vendor/lib/client.ts
new file mode 100644
index 000000000..dc116052f
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/lib/client.ts
@@ -0,0 +1,8 @@
+import { createClient, InferClient } from "@mercurjs/client"
+import { Routes } from '../../../../.mercur/_generated'
+
+declare const __BACKEND_URL__: string
+
+export const client: InferClient<Routes> = createClient({
+ baseUrl: __BACKEND_URL__,
+})
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/export/page.tsx b/packages/registry/src/product-import-export/vendor/pages/products/export/page.tsx
new file mode 100644
index 000000000..fca5d5f06
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/export/page.tsx
@@ -0,0 +1,65 @@
+import { Button, Heading, Text, toast } from "@medusajs/ui"
+
+import { RouteDrawer, useRouteModal } from "@mercurjs/dashboard-shared"
+import { useExportProducts } from "../../../hooks/api/product-import-export"
+
+function ExportProductsContent() {
+ const { handleSuccess } = useRouteModal()
+
+ const { mutateAsync: exportProducts, isPending } = useExportProducts({
+ onSuccess: (data) => {
+ if (data.url) {
+ const a = document.createElement("a")
+ a.href = data.url
+ a.download = `products-export-${Date.now()}.csv`
+ a.click()
+ }
+ toast.success("Products exported successfully.")
+ handleSuccess()
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+
+ const handleExport = async () => {
+ await exportProducts()
+ }
+
+ return (
+ <>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>Export Products</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description>
+ Export your products as a CSV file.
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <RouteDrawer.Body>
+ <div className="flex flex-col gap-y-4">
+ <Text className="text-ui-fg-subtle">
+ This will export all your products to a CSV file. The download will
+ start automatically when the export is ready.
+ </Text>
+ </div>
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary">Cancel</Button>
+ </RouteDrawer.Close>
+ <Button onClick={handleExport} isLoading={isPending}>
+ Export
+ </Button>
+ </RouteDrawer.Footer>
+ </>
+ )
+}
+
+export default function ProductExportPage() {
+ return (
+ <RouteDrawer>
+ <ExportProductsContent />
+ </RouteDrawer>
+ )
+}
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/import/components/import-summary.tsx b/packages/registry/src/product-import-export/vendor/pages/products/import/components/import-summary.tsx
new file mode 100644
index 000000000..a789054fc
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/import/components/import-summary.tsx
@@ -0,0 +1,22 @@
+import { Text } from "@medusajs/ui"
+import { CheckCircleSolid } from "@medusajs/icons"
+
+type ImportSummaryProps = {
+ created: number
+}
+
+export const ImportSummary = ({ created }: ImportSummaryProps) => {
+ return (
+ <div className="flex flex-col items-center gap-y-4 py-8">
+ <CheckCircleSolid className="text-ui-fg-interactive" />
+ <div className="flex flex-col items-center gap-y-1">
+ <Text size="large" weight="plus">
+ Import Complete
+ </Text>
+ <Text className="text-ui-fg-subtle">
+ {created} product(s) were successfully created.
+ </Text>
+ </div>
+ </div>
+ )
+}
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/import/components/upload-import.tsx b/packages/registry/src/product-import-export/vendor/pages/products/import/components/upload-import.tsx
new file mode 100644
index 000000000..6ca9fed75
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/import/components/upload-import.tsx
@@ -0,0 +1,100 @@
+import { useState } from "react"
+import { Button, toast } from "@medusajs/ui"
+import { Trash } from "@medusajs/icons"
+
+import { FileUpload, FilePreview } from "@mercurjs/dashboard-shared"
+import type { FileType } from "@mercurjs/dashboard-shared"
+import { useImportProducts } from "../../../../hooks/api/product-import-export"
+import { downloadImportTemplate } from "../_helpers/import-template"
+
+type UploadImportProps = {
+ onSuccess: (summary: { created: number }) => void
+}
+
+export const UploadImport = ({ onSuccess }: UploadImportProps) => {
+ const [file, setFile] = useState<FileType | null>(null)
+
+ const { mutateAsync: importProducts, isPending } = useImportProducts({
+ onSuccess: (data) => {
+ toast.success(
+ `Successfully imported ${data.summary?.created ?? 0} product(s).`
+ )
+ onSuccess(data.summary)
+ },
+ onError: (error) => {
+ toast.error(error.message)
+ },
+ })
+
+ const handleFileUpload = (files: FileType[]) => {
+ if (files.length > 0) {
+ setFile(files[0] ?? null)
+ }
+ }
+
+ const handleImport = async () => {
+ if (!file) return
+ await importProducts(file.file)
+ }
+
+ const handleRemoveFile = () => {
+ setFile(null)
+ }
+
+ return (
+ <div className="flex flex-col gap-y-4">
+ <div className="rounded-lg border border-ui-border-base bg-ui-bg-subtle p-3">
+ <span className="text-ui-fg-subtle txt-small">
+ Upload a CSV file with your products. You can{" "}
+ <button
+ type="button"
+ className="text-ui-fg-interactive hover:text-ui-fg-interactive-hover underline"
+ onClick={downloadImportTemplate}
+ >
+ download the template
+ </button>{" "}
+ to get started.
+ </span>
+ </div>
+
+ {!file ? (
+ <FileUpload
+ label="Upload CSV file"
+ hint="Only .csv files are supported"
+ formats={[".csv", "text/csv"]}
+ onUploaded={handleFileUpload}
+ multiple={false}
+ />
+ ) : (
+ <FilePreview
+ filename={file.file.name}
+ loading={isPending}
+ activity="Importing products..."
+ actions={[
+ {
+ actions: [
+ {
+ icon: <Trash />,
+ label: "Remove",
+ onClick: handleRemoveFile,
+ },
+ ],
+ },
+ ]}
+ />
+ )}
+
+ {file && (
+ <div className="flex justify-end">
+ <Button
+ onClick={handleImport}
+ isLoading={isPending}
+ disabled={!file}
+ >
+ Import Products
+ </Button>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/import/helpers/import-template.ts b/packages/registry/src/product-import-export/vendor/pages/products/import/helpers/import-template.ts
new file mode 100644
index 000000000..d3701b6ec
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/import/helpers/import-template.ts
@@ -0,0 +1,62 @@
+const IMPORT_TEMPLATE_HEADER = [
+ "Product Id",
+ "Product Handle",
+ "Product Title",
+ "Product Subtitle",
+ "Product Description",
+ "Product Status",
+ "Product Thumbnail",
+ "Product Weight",
+ "Product Length",
+ "Product Width",
+ "Product Height",
+ "Product HS Code",
+ "Product Origin Country",
+ "Product MID Code",
+ "Product Material",
+ "Product Collection Id",
+ "Product Collection Title",
+ "Product Type Id",
+ "Product Type",
+ "Product Tags",
+ "Product Discountable",
+ "Product External Id",
+ "Variant Id",
+ "Variant Title",
+ "Variant SKU",
+ "Variant Barcode",
+ "Variant Inventory Quantity",
+ "Variant Allow Backorder",
+ "Variant Manage Inventory",
+ "Variant Weight",
+ "Variant Length",
+ "Variant Width",
+ "Variant Height",
+ "Variant HS Code",
+ "Variant Origin Country",
+ "Variant MID Code",
+ "Variant Material",
+ "Variant EAN",
+ "Variant UPC",
+ "Option 1 Name",
+ "Option 1 Value",
+ "Option 2 Name",
+ "Option 2 Value",
+ "Price USD",
+ "Price EUR",
+]
+
+export const getImportTemplateContent = (): string => {
+ return IMPORT_TEMPLATE_HEADER.join(",") + "\n"
+}
+
+export const downloadImportTemplate = () => {
+ const content = getImportTemplateContent()
+ const blob = new Blob([content], { type: "text/csv" })
+ const url = URL.createObjectURL(blob)
+ const a = document.createElement("a")
+ a.href = url
+ a.download = "product-import-template.csv"
+ a.click()
+ URL.revokeObjectURL(url)
+}
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/import/page.tsx b/packages/registry/src/product-import-export/vendor/pages/products/import/page.tsx
new file mode 100644
index 000000000..f3ec1c10c
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/import/page.tsx
@@ -0,0 +1,37 @@
+import { useState } from "react"
+import { Button, Heading } from "@medusajs/ui"
+
+import { RouteDrawer } from "@mercurjs/dashboard-shared"
+import { UploadImport } from "./_components/upload-import"
+import { ImportSummary } from "./_components/import-summary"
+
+export default function ProductImportPage() {
+ const [summary, setSummary] = useState<{ created: number } | null>(null)
+
+ return (
+ <RouteDrawer>
+ <RouteDrawer.Header>
+ <RouteDrawer.Title asChild>
+ <Heading>Import Products</Heading>
+ </RouteDrawer.Title>
+ <RouteDrawer.Description>
+ Upload a CSV file to import products into your store.
+ </RouteDrawer.Description>
+ </RouteDrawer.Header>
+ <RouteDrawer.Body>
+ {summary ? (
+ <ImportSummary created={summary.created} />
+ ) : (
+ <UploadImport onSuccess={setSummary} />
+ )}
+ </RouteDrawer.Body>
+ <RouteDrawer.Footer>
+ <RouteDrawer.Close asChild>
+ <Button variant="secondary">
+ {summary ? "Done" : "Cancel"}
+ </Button>
+ </RouteDrawer.Close>
+ </RouteDrawer.Footer>
+ </RouteDrawer>
+ )
+}
diff --git a/packages/registry/src/product-import-export/vendor/pages/products/page.tsx b/packages/registry/src/product-import-export/vendor/pages/products/page.tsx
new file mode 100644
index 000000000..d069d4de3
--- /dev/null
+++ b/packages/registry/src/product-import-export/vendor/pages/products/page.tsx
@@ -0,0 +1,32 @@
+import { Link } from "react-router-dom"
+import { Button } from "@medusajs/ui"
+import { ArrowDownTray, ArrowUpTray } from "@medusajs/icons"
+import { ProductListPage } from "@mercurjs/vendor/pages"
+
+export default function ProductsWithImportExport() {
+ return (
+ <ProductListPage>
+ <ProductListPage.Table>
+ <ProductListPage.Header>
+ <ProductListPage.HeaderTitle />
+ <ProductListPage.HeaderActions>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="import">
+ <ArrowUpTray />
+ Import
+ </Link>
+ </Button>
+ <Button size="small" variant="secondary" asChild>
+ <Link to="export">
+ <ArrowDownTray />
+ Export
+ </Link>
+ </Button>
+ <ProductListPage.HeaderCreateButton />
+ </ProductListPage.HeaderActions>
+ </ProductListPage.Header>
+ <ProductListPage.DataTable />
+ </ProductListPage.Table>
+ </ProductListPage>
+ )
+}
diff --git a/packages/registry/src/product-import-export/workflows/export-seller-products.ts b/packages/registry/src/product-import-export/workflows/export-seller-products.ts
new file mode 100644
index 000000000..636bd7c00
--- /dev/null
+++ b/packages/registry/src/product-import-export/workflows/export-seller-products.ts
@@ -0,0 +1,43 @@
+import {
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ generateProductCsvStep,
+ useQueryGraphStep,
+} from "@medusajs/core-flows"
+import { getSellerProductsStep } from "./steps/get-seller-products"
+
+type ExportSellerProductsWorkflowInput = {
+ seller_id: string
+}
+
+export const exportSellerProductsWorkflow = createWorkflow(
+ "export-seller-products",
+ function (input: ExportSellerProductsWorkflowInput) {
+ const products = getSellerProductsStep({
+ seller_id: input.seller_id,
+ })
+
+ const csvFile = generateProductCsvStep(products)
+
+ const fileData = useQueryGraphStep({
+ entity: "file",
+ fields: ["id", "url"],
+ filters: {
+ id: csvFile.id,
+ },
+ options: {
+ throwIfKeyNotFound: true,
+ },
+ })
+
+ const result = transform({ fileData }, ({ fileData }) => {
+ const file = fileData.data[0]
+ return { url: file.url }
+ })
+
+ return new WorkflowResponse(result)
+ }
+)
diff --git a/packages/registry/src/product-import-export/workflows/import-seller-products.ts b/packages/registry/src/product-import-export/workflows/import-seller-products.ts
new file mode 100644
index 000000000..e11e52b58
--- /dev/null
+++ b/packages/registry/src/product-import-export/workflows/import-seller-products.ts
@@ -0,0 +1,38 @@
+import {
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+} from "@medusajs/framework/workflows-sdk"
+import { parseProductCsvStep } from "@medusajs/core-flows"
+import { createProductsWorkflow } from "@medusajs/core-flows"
+import { validateProductsToImportStep } from "./steps/validate-products-to-import"
+
+type ImportSellerProductsWorkflowInput = {
+ file_content: string
+ seller_id: string
+}
+
+export const importSellerProductsWorkflow = createWorkflow(
+ "import-seller-products",
+ function (input: ImportSellerProductsWorkflowInput) {
+ const parsedProducts = parseProductCsvStep(input.file_content)
+
+ validateProductsToImportStep({ products: parsedProducts })
+
+ const productsInput = transform(
+ { parsedProducts },
+ ({ parsedProducts }) => ({
+ products: parsedProducts.map((p: any) => ({
+ ...p,
+ status: p.status || "draft",
+ })),
+ })
+ )
+
+ const createdProducts = createProductsWorkflow.runAsStep({
+ input: productsInput,
+ })
+
+ return new WorkflowResponse(createdProducts)
+ }
+)
diff --git a/packages/registry/src/product-import-export/workflows/steps/get-seller-products.ts b/packages/registry/src/product-import-export/workflows/steps/get-seller-products.ts
new file mode 100644
index 000000000..892da381a
--- /dev/null
+++ b/packages/registry/src/product-import-export/workflows/steps/get-seller-products.ts
@@ -0,0 +1,37 @@
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+type GetSellerProductsStepInput = {
+ seller_id: string
+}
+
+export const getSellerProductsStep = createStep(
+ "get-seller-products",
+ async (input: GetSellerProductsStepInput, { container }) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: relations } = await query.graph({
+ entity: "product_seller",
+ fields: [
+ "product.*",
+ "product.variants.*",
+ "product.variants.prices.*",
+ "product.variants.options.*",
+ "product.options.*",
+ "product.collection.*",
+ "product.categories.*",
+ "product.sales_channels.*",
+ "product.images.*",
+ "product.tags.*",
+ "product.type.*",
+ ],
+ filters: {
+ seller_id: input.seller_id,
+ },
+ })
+
+ const products = relations.map((r: any) => r.product)
+
+ return new StepResponse(products)
+ }
+)
diff --git a/packages/registry/src/product-import-export/workflows/steps/validate-products-to-import.ts b/packages/registry/src/product-import-export/workflows/steps/validate-products-to-import.ts
new file mode 100644
index 000000000..702a020e9
--- /dev/null
+++ b/packages/registry/src/product-import-export/workflows/steps/validate-products-to-import.ts
@@ -0,0 +1,89 @@
+import { createStep, StepResponse } from "@medusajs/framework/workflows-sdk"
+import { MedusaError } from "@medusajs/framework/utils"
+import { z } from "zod"
+
+const CreateVariantPrice = z.object({
+ currency_code: z.string(),
+ amount: z.number(),
+})
+
+const CreateProductOption = z.object({
+ title: z.string(),
+ values: z.array(z.string()).optional(),
+})
+
+const CreateProductVariant = z.object({
+ title: z.string(),
+ sku: z.string().optional().nullable(),
+ barcode: z.string().optional().nullable(),
+ ean: z.string().optional().nullable(),
+ upc: z.string().optional().nullable(),
+ hs_code: z.string().optional().nullable(),
+ mid_code: z.string().optional().nullable(),
+ manage_inventory: z.boolean().optional(),
+ allow_backorder: z.boolean().optional(),
+ weight: z.number().optional().nullable(),
+ length: z.number().optional().nullable(),
+ height: z.number().optional().nullable(),
+ width: z.number().optional().nullable(),
+ material: z.string().optional().nullable(),
+ origin_country: z.string().optional().nullable(),
+ options: z.record(z.string()).optional(),
+ prices: z.array(CreateVariantPrice).optional(),
+ inventory_quantity: z.number().optional(),
+})
+
+const CreateProduct = z.object({
+ title: z.string(),
+ subtitle: z.string().optional().nullable(),
+ description: z.string().optional().nullable(),
+ handle: z.string().optional(),
+ status: z.enum(["draft", "proposed", "published", "rejected"]).optional(),
+ thumbnail: z.string().optional().nullable(),
+ weight: z.number().optional().nullable(),
+ length: z.number().optional().nullable(),
+ height: z.number().optional().nullable(),
+ width: z.number().optional().nullable(),
+ hs_code: z.string().optional().nullable(),
+ mid_code: z.string().optional().nullable(),
+ material: z.string().optional().nullable(),
+ origin_country: z.string().optional().nullable(),
+ collection_id: z.string().optional().nullable(),
+ type_id: z.string().optional().nullable(),
+ tags: z.array(z.object({ id: z.string() })).optional(),
+ categories: z.array(z.object({ id: z.string() })).optional(),
+ sales_channels: z.array(z.object({ id: z.string() })).optional(),
+ images: z.array(z.object({ url: z.string() })).optional(),
+ options: z.array(CreateProductOption).optional(),
+ variants: z.array(CreateProductVariant).optional(),
+})
+
+type ValidateProductsToImportStepInput = {
+ products: Record<string, any>[]
+}
+
+export const validateProductsToImportStep = createStep(
+ "validate-products-to-import",
+ async (input: ValidateProductsToImportStepInput) => {
+ const errors: string[] = []
+
+ for (let i = 0; i < input.products.length; i++) {
+ const result = CreateProduct.safeParse(input.products[i])
+ if (!result.success) {
+ const issues = result.error.issues
+ .map((issue) => `${issue.path.join(".")}: ${issue.message}`)
+ .join("; ")
+ errors.push(`Product ${i + 1}: ${issues}`)
+ }
+ }
+
+ if (errors.length > 0) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Validation failed for ${errors.length} product(s):\n${errors.join("\n")}`
+ )
+ }
+
+ return new StepResponse(input.products)
+ }
+)