The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
fix(cart): checkout crash with sellerless (admin) promotion (#1284)
Viktor Holike524f54d7ff6
diff --git a/integration-tests/http/promotions/store/admin-promotion-checkout.spec.ts b/integration-tests/http/promotions/store/admin-promotion-checkout.spec.tsnew file mode 100644index 000000000..dd8e0c485--- /dev/null+++ b/integration-tests/http/promotions/store/admin-promotion-checkout.spec.ts@@ -0,0 +1,302 @@+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"+import {+ IRegionModuleService,+ ISalesChannelModuleService,+ MedusaContainer,+} from "@medusajs/framework/types"+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"+import { MercurModules, SellerStatus } from "@mercurjs/types"+import { createSellerUser } from "../../../helpers/create-seller-user"+import { createCustomerUser } from "../../../helpers/create-customer-user"+import {+ adminHeaders,+ createAdminUser,+ generatePublishableKey,+ generateStoreHeaders,+} from "../../../helpers/create-admin-user"+import { createVendorProduct } from "../../../helpers/create-product"++jest.setTimeout(120000)++medusaIntegrationTestRunner({+ testSuite: ({ getContainer, api, dbConnection }) => {+ describe("Store - Checkout with admin (sellerless) promotion", () => {+ let appContainer: MedusaContainer+ let seller: any+ let sellerHeaders: any+ let storeHeaders: any+ let region: any+ let salesChannel: any+ let offer: any++ const approveSeller = async (sellerId: string) => {+ const sellerModule: any = appContainer.resolve(MercurModules.SELLER)+ await sellerModule.updateSellers({+ id: sellerId,+ status: SellerStatus.OPEN,+ })+ }++ const createShippingPrerequisites = async (headers: any, prefix: string) => {+ const uniqueSuffix = `_${prefix}_${Date.now()}`++ const stockLocation = (+ await api.post(+ `/vendor/stock-locations`,+ { name: `Warehouse${uniqueSuffix}` },+ headers+ )+ ).data.stock_location++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,+ { name: `Fulfillment Set${uniqueSuffix}`, type: "shipping" },+ headers+ )++ const updatedLocation = await api.get(+ `/vendor/stock-locations/${stockLocation.id}?fields=*fulfillment_sets`,+ headers+ )+ const fulfillmentSet =+ updatedLocation.data.stock_location.fulfillment_sets[0]++ const serviceZone = (+ await api.post(+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,+ {+ name: `Service Zone${uniqueSuffix}`,+ geo_zones: [{ type: "country", country_code: "us" }],+ },+ headers+ )+ ).data.fulfillment_set.service_zones.find(+ (z: any) => z.name === `Service Zone${uniqueSuffix}`+ )++ const shippingProfile = (+ await api.post(+ `/vendor/shipping-profiles`,+ { name: `Shipping Profile${uniqueSuffix}`, type: "default" },+ headers+ )+ ).data.shipping_profile++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,+ { add: ["manual_manual"] },+ headers+ )++ await api.post(+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,+ { add: [salesChannel.id] },+ headers+ )++ return { stockLocation, serviceZone, shippingProfile }+ }++ beforeAll(async () => {+ appContainer = getContainer()+ await createAdminUser(dbConnection, adminHeaders, appContainer)+ })++ beforeEach(async () => {+ const sellerResult = await createSellerUser(appContainer, {+ email: "[email protected]",+ name: "Admin Promo Seller",+ })+ seller = sellerResult.seller+ sellerHeaders = sellerResult.headers+ await approveSeller(seller.id)++ const customerResult = await createCustomerUser(appContainer, {+ email: "[email protected]",+ first_name: "Promo",+ last_name: "Customer",+ })++ const apiKey = await generatePublishableKey(appContainer)+ storeHeaders = generateStoreHeaders({ publishableKey: apiKey })+ storeHeaders = {+ headers: { ...storeHeaders.headers, ...customerResult.headers.headers },+ }++ salesChannel = await appContainer+ .resolve<ISalesChannelModuleService>(Modules.SALES_CHANNEL)+ .createSalesChannels({ name: "Test Store" })++ region = await appContainer+ .resolve<IRegionModuleService>(Modules.REGION)+ .createRegions({+ name: "Test Region",+ currency_code: "usd",+ countries: ["us"],+ })++ await appContainer.resolve(ContainerRegistrationKeys.LINK).create({+ [Modules.REGION]: { region_id: region.id },+ [Modules.PAYMENT]: { payment_provider_id: "pp_system_default" },+ })++ const prerequisites = await createShippingPrerequisites(+ sellerHeaders,+ "seller"+ )++ const product = await createVendorProduct(api, sellerHeaders, {+ title: "Admin Promo Product",+ sku: `ADMIN-PROMO-${Date.now()}`,+ })+ await api.post(+ `/vendor/sales-channels/${salesChannel.id}/products`,+ { add: [product.id] },+ sellerHeaders+ )++ await api.post(+ `/vendor/shipping-options`,+ {+ name: "Seller Shipping",+ service_zone_id: prerequisites.serviceZone.id,+ shipping_profile_id: prerequisites.shippingProfile.id,+ provider_id: "manual_manual",+ price_type: "flat",+ type: {+ label: "Standard",+ description: "Standard shipping",+ code: "standard",+ },+ prices: [{ currency_code: "usd", amount: 500 }],+ rules: [+ { attribute: "enabled_in_store", value: "true", operator: "eq" },+ ],+ },+ sellerHeaders+ )++ offer = (+ await api.post(+ `/vendor/offers`,+ {+ sku: `OF-ADMIN-PROMO-${Date.now()}`,+ variant_id: product.variants[0].id,+ shipping_profile_id: prerequisites.shippingProfile.id,+ inventory_items: [+ {+ title: "Admin Promo Inventory",+ required_quantity: 1,+ stock_levels: [+ {+ location_id: prerequisites.stockLocation.id,+ stocked_quantity: 100,+ },+ ],+ },+ ],+ prices: [{ amount: 2000, currency_code: "usd" }],+ },+ sellerHeaders+ )+ ).data.offer+ })++ it("completes checkout when an admin (sellerless) promotion is applied", async () => {+ // Admin/marketplace promotion — not associated with any seller.+ const promotion = (+ await api.post(+ `/admin/promotions`,+ {+ code: "PLATFORM10",+ type: "standard",+ status: "active",+ application_method: {+ type: "percentage",+ target_type: "order",+ allocation: "across",+ value: 10,+ },+ },+ adminHeaders+ )+ ).data.promotion++ // Confirm it really has no seller.+ const promotionDetail = await api.get(+ `/admin/promotions/${promotion.id}?fields=%2Bseller.id`,+ adminHeaders+ )+ expect(promotionDetail.data.promotion.seller ?? null).toBeNull()++ let cart = (+ await api.post(+ `/store/carts`,+ {+ region_id: region.id,+ sales_channel_id: salesChannel.id,+ currency_code: "usd",+ },+ storeHeaders+ )+ ).data.cart++ await api.post(+ `/store/carts/${cart.id}/line-items`,+ { offer_id: offer.id, quantity: 1 },+ storeHeaders+ )++ const promoResponse = await api.post(+ `/store/carts/${cart.id}/promotions`,+ { promo_codes: ["PLATFORM10"] },+ storeHeaders+ )+ expect(promoResponse.status).toEqual(200)+ expect(promoResponse.data.cart.promotions).toHaveLength(1)+ expect(promoResponse.data.cart.discount_total).toBeGreaterThan(0)++ const shippingOptions = (+ await api.get(+ `/store/shipping-options?cart_id=${cart.id}`,+ storeHeaders+ )+ ).data.shipping_options as Record<string, any[]>++ for (const [, options] of Object.entries(shippingOptions)) {+ if (options.length > 0) {+ await api.post(+ `/store/carts/${cart.id}/shipping-methods`,+ { option_id: options[0].id },+ storeHeaders+ )+ }+ }++ const paymentCollection = (+ await api.post(+ `/store/payment-collections`,+ { cart_id: cart.id },+ storeHeaders+ )+ ).data.payment_collection++ await api.post(+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,+ { provider_id: "pp_system_default" },+ storeHeaders+ )++ const completeResponse = await api.post(+ `/store/carts/${cart.id}/complete`,+ {},+ storeHeaders+ )++ expect(completeResponse.status).toEqual(200)+ expect(completeResponse.data.type).toEqual("order_group")+ expect(completeResponse.data.order_group?.id).toBeDefined()+ })+ })+ },+})diff --git a/integration-tests/http/search/store/search.spec.ts b/integration-tests/http/search/store/search.spec.tsdeleted file mode 100644index a3c414624..000000000--- a/integration-tests/http/search/store/search.spec.ts+++ /dev/null@@ -1,124 +0,0 @@-import { medusaIntegrationTestRunner } from "@medusajs/test-utils"-import { MedusaContainer } from "@medusajs/framework/types"-import { MercurModules } from "@mercurjs/types"--import {- generatePublishableKey,- generateStoreHeaders,-} from "../../../helpers/create-admin-user"--jest.setTimeout(120000)--const REGION = "reg_test"--const seedProducts = [- {- product_id: "prod_shoe",- title: "Running Shoe",- handle: "running-shoe",- description: "Lightweight trail running shoe",- status: "published",- collection_id: "col_sport",- type_id: "ptyp_footwear",- category_ids: ["cat_shoes"],- tag_ids: ["tag_new"],- seller_ids: ["sel_1"],- variant_skus: ["SHOE-01"],- attributes: { attr_color: ["red"] },- prices: [- { region_id: REGION, currency_code: "usd", min_amount: 80, max_amount: 120 },- ],- },- {- product_id: "prod_hat",- title: "Wool Hat",- handle: "wool-hat",- description: "Cozy winter hat",- status: "published",- collection_id: "col_accessories",- type_id: "ptyp_accessory",- category_ids: ["cat_accessories"],- tag_ids: ["tag_new"],- seller_ids: ["sel_1"],- variant_skus: ["HAT-01"],- attributes: { attr_color: ["red"] },- prices: [- { region_id: REGION, currency_code: "usd", min_amount: 20, max_amount: 20 },- ],- },-]--medusaIntegrationTestRunner({- testSuite: ({ getContainer, api }) => {- describe("Store - Search", () => {- let appContainer: MedusaContainer- let storeHeaders: { headers: Record<string, string> }-- beforeAll(async () => {- appContainer = getContainer()- })-- beforeEach(async () => {- const publishableKey = await generatePublishableKey(appContainer)- storeHeaders = generateStoreHeaders({ publishableKey })-- const search = appContainer.resolve(MercurModules.SEARCH)- await search.upsertProducts(seedProducts)- })-- it("full-text searches and returns region price", async () => {- const res = await api.get(- `/store/search?region_id=${REGION}&q=running`,- storeHeaders- )-- expect(res.status).toEqual(200)- expect(res.data.count).toEqual(1)- expect(res.data.products[0].product_id).toEqual("prod_shoe")- expect(res.data.products[0].calculated_price).toEqual({- region_id: REGION,- currency_code: "usd",- min_amount: 80,- max_amount: 120,- })- expect(res.data.offset).toEqual(0)- expect(res.data.limit).toEqual(20)- })-- it("filters by price range and sorts by price", async () => {- const res = await api.get(- `/store/search?region_id=${REGION}&max_price=50&order=price`,- storeHeaders- )-- expect(res.status).toEqual(200)- expect(res.data.products.map((p: { product_id: string }) => p.product_id)).toEqual([- "prod_hat",- ])- })-- it("always returns facet counts", async () => {- const res = await api.get(- `/store/search?region_id=${REGION}`,- storeHeaders- )-- expect(res.status).toEqual(200)- const colors = new Map(- (res.data.facets.attributes.attr_color ?? []).map(- (b: { value: string; count: number }) => [b.value, b.count]- )- )- expect(colors.get("red")).toEqual(2)- })-- it("400s when region_id is missing", async () => {- const err = await api- .get(`/store/search?q=running`, storeHeaders)- .catch((e) => e)-- expect(err.response.status).toEqual(400)- })- })- },-})diff --git a/packages/admin/src/i18n/translations/en.json b/packages/admin/src/i18n/translations/en.jsonindex 0f19fe40a..1551b7813 100644--- a/packages/admin/src/i18n/translations/en.json+++ b/packages/admin/src/i18n/translations/en.json@@ -2433,7 +2433,9 @@"promotionTabError": "Fix errors in Promotion Tab before proceeding"},"toasts": {- "promotionCreateSuccess": "Promotion ({{code}}) was successfully created."+ "promotionCreateSuccess": "Promotion ({{code}}) was successfully created.",+ "promotionUpdateSuccess": "Promotion was successfully updated.",+ "promotionDeleteSuccess": "Promotion was successfully deleted."},"create": {},"edit": {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.tsxindex f89494625..8944901b6 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@@ -8,6 +8,7 @@ import {Heading,StatusBadge,Text,+ toast,usePrompt,} from "@medusajs/ui"import { useTranslation } from "react-i18next"@@ -105,8 +106,12 @@ export const PromotionGeneralSection = ({await mutateAsync(undefined, {onSuccess: () => {+ toast.success(t("promotions.toasts.promotionDeleteSuccess"))navigate("/promotions", { replace: true })},+ onError: (e) => {+ toast.error((e as Error).message)+ },})}diff --git a/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx b/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsxindex 8d575cc04..2c13cb0d5 100644--- a/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx+++ b/packages/admin/src/pages/promotions/promotion-edit-details/components/edit-promotion-form/edit-promotion-details-form.tsx@@ -199,8 +199,12 @@ return}}+ toast.success(t("promotions.toasts.promotionUpdateSuccess"))handleSuccess()},+ onError: (e) => {+ toast.error((e as Error).message)+ },})})diff --git a/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx b/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsxindex 41375d8c6..76721eda6 100644--- a/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx+++ b/packages/admin/src/pages/promotions/promotion-list/components/promotion-list-table/promotion-list-table.tsx@@ -1,6 +1,6 @@import { PencilSquare, ReceiptPercent, Trash } from "@medusajs/icons"import { HttpTypes } from "@medusajs/types"-import { Button, Container, Heading, usePrompt } from "@medusajs/ui"+import { Button, Container, Heading, toast, usePrompt } from "@medusajs/ui"import { createColumnHelper, type ColumnDef } from "@tanstack/react-table"import { useExtendableTable, useLinkQuery } from "@mercurjs/dashboard-shared"import { Children, ReactNode, useMemo } from "react"@@ -165,17 +165,15 @@ const PromotionActions = ({ promotion }: { promotion: HttpTypes.AdminPromotion }return}- try {- await mutateAsync(undefined, {- onSuccess: () => {- navigate("/promotions", { replace: true })- },- })- } catch {- throw new Error(- `Promotion with code ${promotion.code} could not be deleted`- )- }+ await mutateAsync(undefined, {+ onSuccess: () => {+ toast.success(t("promotions.toasts.promotionDeleteSuccess"))+ navigate("/promotions", { replace: true })+ },+ onError: (e) => {+ toast.error((e as Error).message)+ },+ })}return (diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.jsonindex 47f3d0ee0..354c6ca8a 100644--- a/packages/cli/routes-manifest.json+++ b/packages/cli/routes-manifest.json@@ -367,7 +367,6 @@"/store/return-reasons": "typeof import(\"@medusajs/medusa/api/store/return-reasons/route\")","/store/return-reasons/:id": "typeof import(\"@medusajs/medusa/api/store/return-reasons/[id]/route\")","/store/returns": "typeof import(\"@medusajs/medusa/api/store/returns/route\")",- "/store/search": "typeof import(\"@mercurjs/core/api/store/search/route\")","/store/sellers": "typeof import(\"@mercurjs/core/api/store/sellers/route\")","/store/sellers/:id": "typeof import(\"@mercurjs/core/api/store/sellers/[id]/route\")","/store/shipping-options": "typeof import(\"@mercurjs/core/api/store/shipping-options/route\")",diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.tsindex 91d64e7bf..c2f85d56f 100644--- a/packages/core/.mercur/routes.d.ts+++ b/packages/core/.mercur/routes.d.ts@@ -629,7 +629,7 @@ export type Routes = {$id: typeof import("@medusajs/medusa/api/store/return-reasons/[id]/route");};returns: typeof import("@medusajs/medusa/api/store/returns/route");- search: typeof import("../src/api/store/search/route");+ search: typeof import("@mercurjs/core/api/store/search/route");sellers: typeof import("../src/api/store/sellers/route") & {$id: typeof import("../src/api/store/sellers/[id]/route");};diff --git a/packages/core/src/api/store/middlewares.ts b/packages/core/src/api/store/middlewares.tsindex 87e2706ef..0366c99a5 100644--- a/packages/core/src/api/store/middlewares.ts+++ b/packages/core/src/api/store/middlewares.ts@@ -6,7 +6,6 @@ import { storeOrderGroupsMiddlewares } from "./order-groups/middlewares"import { storeProductAttributesMiddlewares } from "./product-attributes/middlewares"import { storeProductCategoriesMiddlewares } from "./product-categories/middlewares"import { storeProductsMiddlewares } from "./products/middlewares"-import { storeSearchMiddlewares } from "./search/middlewares"import { storeSellersMiddlewares } from "./sellers/middlewares"export const storeMiddlewares: MiddlewareRoute[] = [@@ -16,6 +15,5 @@ export const storeMiddlewares: MiddlewareRoute[] = [...storeProductAttributesMiddlewares,...storeProductCategoriesMiddlewares,...storeProductsMiddlewares,- ...storeSearchMiddlewares,...storeSellersMiddlewares,]diff --git a/packages/core/src/api/store/search/middlewares.ts b/packages/core/src/api/store/search/middlewares.tsdeleted file mode 100644index 774f768ea..000000000--- a/packages/core/src/api/store/search/middlewares.ts+++ /dev/null@@ -1,21 +0,0 @@-import { authenticate, MiddlewareRoute } from "@medusajs/framework/http"-import { validateAndTransformQuery } from "@medusajs/framework"--import { storeSearchQueryConfig } from "./query-config"-import { StoreGetSearchParams } from "./validators"--export const storeSearchMiddlewares: MiddlewareRoute[] = [- {- method: ["GET"],- matcher: "/store/search",- middlewares: [- authenticate("customer", ["session", "bearer"], {- allowUnauthenticated: true,- }),- validateAndTransformQuery(- StoreGetSearchParams,- storeSearchQueryConfig.list- ),- ],- },-]diff --git a/packages/core/src/api/store/search/query-config.ts b/packages/core/src/api/store/search/query-config.tsdeleted file mode 100644index 6a9485598..000000000--- a/packages/core/src/api/store/search/query-config.ts+++ /dev/null@@ -1,25 +0,0 @@-export const defaultStoreSearchFields = [- "id",- "product_id",- "title",- "handle",- "description",- "thumbnail",- "status",- "collection_id",- "type_id",- "category_ids",- "tag_ids",- "seller_ids",- "attributes",- "metadata",- "calculated_price",-]--export const storeSearchQueryConfig = {- list: {- defaults: defaultStoreSearchFields,- defaultLimit: 20,- isList: true,- },-}diff --git a/packages/core/src/api/store/search/route.ts b/packages/core/src/api/store/search/route.tsdeleted file mode 100644index 4ac51502c..000000000--- a/packages/core/src/api/store/search/route.ts+++ /dev/null@@ -1,52 +0,0 @@-import { MedusaResponse, MedusaStoreRequest } from "@medusajs/framework/http"-import { promiseAll } from "@medusajs/framework/utils"-import { MercurModules } from "@mercurjs/types"--import type SearchModuleService from "../../../modules/search/service"-import {- buildSearchFilters,- buildSearchSort,-} from "../../../modules/search/utils"-import { SearchQueryFilters } from "../../../modules/search/validators"-import { StoreGetSearchParamsType } from "./validators"--export const GET = async (- req: MedusaStoreRequest<StoreGetSearchParamsType>,- res: MedusaResponse-) => {- const searchService = req.scope.resolve<SearchModuleService>(- MercurModules.SEARCH- )-- const query = req.filterableFields as unknown as SearchQueryFilters- const filters = buildSearchFilters(query)- const sort = buildSearchSort(req.queryConfig.pagination.order)-- const skip = req.queryConfig.pagination.skip ?? 0- const take = req.queryConfig.pagination.take ?? 20-- const searchResult = searchService.search({- q: query.q,- region_id: query.region_id,- filters,- sort,- pagination: { skip, take },- })- const facetsResult = searchService.getFacets({- q: query.q,- region_id: query.region_id,- filters,- })-- await promiseAll([searchResult, facetsResult])- const { products, count } = await searchResult- const facets = await facetsResult-- res.json({- products,- count,- offset: skip,- limit: take,- facets,- })-}diff --git a/packages/core/src/api/store/search/validators.ts b/packages/core/src/api/store/search/validators.tsdeleted file mode 100644index b81841330..000000000--- a/packages/core/src/api/store/search/validators.ts+++ /dev/null@@ -1,10 +0,0 @@-import { z } from "zod"-import { createFindParams } from "@medusajs/medusa/api/utils/validators"--import { SearchQueryFiltersSchema } from "../../../modules/search/validators"--export type StoreGetSearchParamsType = z.infer<typeof StoreGetSearchParams>-export const StoreGetSearchParams = createFindParams({- offset: 0,- limit: 20,-}).merge(SearchQueryFiltersSchema)diff --git a/packages/core/src/jobs/sync-search-index.ts b/packages/core/src/jobs/sync-search-index.tsdeleted file mode 100644index 32e4a33ca..000000000--- a/packages/core/src/jobs/sync-search-index.ts+++ /dev/null@@ -1,40 +0,0 @@-import { MedusaContainer } from "@medusajs/framework/types"-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"-import { ProductStatus } from "@mercurjs/types"--import { syncSearchProducts } from "../utils/search/sync-search-products"--const BATCH_SIZE = 200--export default async function syncSearchIndexJob(container: MedusaContainer) {- const query = container.resolve(ContainerRegistrationKeys.QUERY)-- let offset = 0- for (;;) {- const { data: products, metadata } = await query.graph({- entity: "product",- fields: ["id"],- filters: { status: ProductStatus.PUBLISHED },- pagination: { skip: offset, take: BATCH_SIZE },- })-- if (!products.length) {- break- }-- await syncSearchProducts(- container,- (products as { id: string }[]).map((p) => p.id)- )-- offset += BATCH_SIZE- if (offset >= (metadata?.count ?? 0)) {- break- }- }-}--export const config = {- name: "sync-search-index",- schedule: "0 * * * *",-}diff --git a/packages/core/src/modules/search/__tests__/search.spec.ts b/packages/core/src/modules/search/__tests__/search.spec.tsdeleted file mode 100644index 0f4986a8f..000000000--- a/packages/core/src/modules/search/__tests__/search.spec.ts+++ /dev/null@@ -1,170 +0,0 @@-import path from "path"--import { moduleIntegrationTestRunner } from "@medusajs/test-utils"-import { MercurModules } from "@mercurjs/types"--import { SearchProduct, SearchProductPrice } from "../models"-import SearchModuleService from "../service"-import { SearchProductInput } from "../types"--const REGION_EU = "reg_eu"-const REGION_US = "reg_us"--const products: SearchProductInput[] = [- {- product_id: "prod_shoe",- title: "Running Shoe",- handle: "running-shoe",- description: "Lightweight trail running shoe",- status: "published",- collection_id: "col_sport",- type_id: "ptyp_footwear",- category_ids: ["cat_shoes", "cat_sport"],- tag_ids: ["tag_new"],- seller_ids: ["sel_1"],- variant_skus: ["SHOE-01"],- attributes: { attr_color: ["red"], attr_size: ["42"] },- prices: [- { region_id: REGION_EU, currency_code: "eur", min_amount: 80, max_amount: 120 },- { region_id: REGION_US, currency_code: "usd", min_amount: 90, max_amount: 130 },- ],- },- {- product_id: "prod_boot",- title: "Winter Boot",- handle: "winter-boot",- description: "Warm waterproof boot",- status: "published",- collection_id: "col_sport",- type_id: "ptyp_footwear",- category_ids: ["cat_shoes"],- tag_ids: ["tag_sale"],- seller_ids: ["sel_2"],- variant_skus: ["BOOT-01"],- attributes: { attr_color: ["black"], attr_size: ["44"] },- prices: [- { region_id: REGION_EU, currency_code: "eur", min_amount: 200, max_amount: 200 },- { region_id: REGION_US, currency_code: "usd", min_amount: 220, max_amount: 220 },- ],- },- {- product_id: "prod_hat",- title: "Wool Hat",- handle: "wool-hat",- description: "Cozy winter hat",- status: "published",- collection_id: "col_accessories",- type_id: "ptyp_accessory",- category_ids: ["cat_accessories"],- tag_ids: ["tag_new"],- seller_ids: ["sel_1"],- variant_skus: ["HAT-01"],- attributes: { attr_color: ["red"] },- prices: [- { region_id: REGION_EU, currency_code: "eur", min_amount: 20, max_amount: 20 },- { region_id: REGION_US, currency_code: "usd", min_amount: 25, max_amount: 25 },- ],- },-]--moduleIntegrationTestRunner<SearchModuleService>({- moduleName: MercurModules.SEARCH,- moduleModels: [SearchProduct, SearchProductPrice],- resolve: path.join(__dirname, ".."),- testSuite: ({ service }) => {- describe("SearchModuleService", () => {- beforeEach(async () => {- await service.upsertProducts(products)- })-- it("full-text searches over title/description", async () => {- const { products: hits } = await service.search({- q: "running",- region_id: REGION_EU,- })- expect(hits.map((p) => p.product_id)).toEqual(["prod_shoe"])- })-- it("returns the region-scoped calculated price", async () => {- const { products: hits } = await service.search({- q: "wool hat",- region_id: REGION_US,- })- expect(hits[0].calculated_price).toEqual({- region_id: REGION_US,- currency_code: "usd",- min_amount: 25,- max_amount: 25,- })- })-- it("filters by region price range", async () => {- const { products: hits } = await service.search({- region_id: REGION_EU,- filters: { price: { lte: 50 } },- })- expect(hits.map((p) => p.product_id)).toEqual(["prod_hat"])- })-- it("filters by category and attribute", async () => {- const { products: hits } = await service.search({- region_id: REGION_EU,- filters: {- category_ids: ["cat_shoes"],- attributes: { attr_color: ["red"] },- },- })- expect(hits.map((p) => p.product_id)).toEqual(["prod_shoe"])- })-- it("computes facet counts", async () => {- const facets = await service.getFacets({- region_id: REGION_EU,- price_ranges: [- { lte: 50 },- { gte: 50, lte: 150 },- { gte: 150 },- ],- })-- const category = new Map(- facets.categories.map((b) => [b.value, b.count])- )- expect(category.get("cat_shoes")).toBe(2)- expect(category.get("cat_accessories")).toBe(1)-- const color = new Map(- (facets.attributes.attr_color ?? []).map((b) => [b.value, b.count])- )- expect(color.get("red")).toBe(2)- expect(color.get("black")).toBe(1)-- expect(facets.price_ranges.map((b) => b.count)).toEqual([1, 1, 1])- })-- it("excludes a facet's own selection from its counts (drill-down)", async () => {- const facets = await service.getFacets({- region_id: REGION_EU,- filters: { tag_ids: ["tag_sale"] },- })- const tags = new Map(facets.tags.map((b) => [b.value, b.count]))- expect(tags.get("tag_new")).toBe(2)- expect(tags.get("tag_sale")).toBe(1)- const category = new Map(- facets.categories.map((b) => [b.value, b.count])- )- expect(category.get("cat_shoes")).toBe(1)- expect(category.get("cat_accessories")).toBeUndefined()- })-- it("removes a product on delete", async () => {- await service.deleteProducts(["prod_shoe"])- const { count } = await service.search({- q: "running",- region_id: REGION_EU,- })- expect(count).toBe(0)- })- })- },-})diff --git a/packages/core/src/modules/search/index.ts b/packages/core/src/modules/search/index.tsdeleted file mode 100644index 423dae391..000000000--- a/packages/core/src/modules/search/index.ts+++ /dev/null@@ -1,8 +0,0 @@-import { Module } from "@medusajs/framework/utils"-import { MercurModules } from "@mercurjs/types"--import SearchModuleService from "./service"--export default Module(MercurModules.SEARCH, {- service: SearchModuleService,-})diff --git a/packages/core/src/modules/search/joiner-config.ts b/packages/core/src/modules/search/joiner-config.tsdeleted file mode 100644index 72f49870e..000000000--- a/packages/core/src/modules/search/joiner-config.ts+++ /dev/null@@ -1,12 +0,0 @@-import { defineJoinerConfig } from "@medusajs/framework/utils"-import { MercurModules } from "@mercurjs/types"--import SearchProduct from "./models/search-product"-import SearchProductPrice from "./models/search-product-price"--export const joinerConfig = defineJoinerConfig(MercurModules.SEARCH, {- linkableKeys: {- search_product_id: SearchProduct.name,- search_product_price_id: SearchProductPrice.name,- },-})diff --git a/packages/core/src/modules/search/migrations/Migration20260710151923.ts b/packages/core/src/modules/search/migrations/Migration20260710151923.tsdeleted file mode 100644index 5fdeb9674..000000000--- a/packages/core/src/modules/search/migrations/Migration20260710151923.ts+++ /dev/null@@ -1,60 +0,0 @@-import { Migration } from "@medusajs/framework/mikro-orm/migrations"--export class Migration20260710151923 extends Migration {- override async up(): Promise<void> {- this.addSql(- `create table if not exists "search_product" ("id" text not null, "product_id" text not null, "title" text not null, "handle" text not null, "description" text null, "thumbnail" text null, "status" text not null, "collection_id" text null, "type_id" text null, "category_ids" jsonb not null default '[]', "tag_ids" jsonb not null default '[]', "seller_ids" jsonb not null default '[]', "variant_skus" jsonb not null default '[]', "attributes" jsonb not null default '{}', "search_text" text null, "min_amount" numeric null, "raw_min_amount" jsonb null, "max_amount" numeric null, "raw_max_amount" jsonb null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "search_product_pkey" primary key ("id"));`- )-- this.addSql(- `create table if not exists "search_product_price" ("id" text not null, "region_id" text not null, "currency_code" text not null, "min_amount" numeric not null, "raw_min_amount" jsonb not null, "max_amount" numeric not null, "raw_max_amount" jsonb not null, "product_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "search_product_price_pkey" primary key ("id"));`- )-- // Generated full-text column over title, description and the flattened- // search_text (offer SKUs), queried via websearch_to_tsquery.- this.addSql(- `alter table if exists "search_product" add column if not exists "search_tsv" tsvector generated always as (to_tsvector('simple', coalesce("title", '') || ' ' || coalesce("description", '') || ' ' || coalesce("search_text", ''))) stored;`- )-- this.addSql(- `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_search_product_product_id_unique" ON "search_product" ("product_id") WHERE deleted_at IS NULL;`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_status" ON "search_product" ("status") WHERE deleted_at IS NULL;`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_collection_id" ON "search_product" ("collection_id") WHERE deleted_at IS NULL AND collection_id IS NOT NULL;`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_type_id" ON "search_product" ("type_id") WHERE deleted_at IS NULL AND type_id IS NOT NULL;`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_search_tsv" ON "search_product" USING GIN ("search_tsv");`- )- // Default jsonb_ops GIN so jsonb_exists_any (element membership) can use the index.- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_category_ids" ON "search_product" USING GIN ("category_ids");`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_tag_ids" ON "search_product" USING GIN ("tag_ids");`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_seller_ids" ON "search_product" USING GIN ("seller_ids");`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_attributes" ON "search_product" USING GIN ("attributes");`- )-- this.addSql(- `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_search_product_price_product_region_unique" ON "search_product_price" ("product_id", "region_id") WHERE deleted_at IS NULL;`- )- this.addSql(- `CREATE INDEX IF NOT EXISTS "IDX_search_product_price_region_min_amount" ON "search_product_price" ("region_id", "min_amount") WHERE deleted_at IS NULL;`- )- }-- override async down(): Promise<void> {- this.addSql(`drop table if exists "search_product_price" cascade;`)- this.addSql(`drop table if exists "search_product" cascade;`)- }-}diff --git a/packages/core/src/modules/search/models/index.ts b/packages/core/src/modules/search/models/index.tsdeleted file mode 100644index 5ad7d44fc..000000000--- a/packages/core/src/modules/search/models/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { default as SearchProduct } from "./search-product"-export { default as SearchProductPrice } from "./search-product-price"diff --git a/packages/core/src/modules/search/models/search-product-price.ts b/packages/core/src/modules/search/models/search-product-price.tsdeleted file mode 100644index 6e9a4c86e..000000000--- a/packages/core/src/modules/search/models/search-product-price.ts+++ /dev/null@@ -1,30 +0,0 @@-import { model } from "@medusajs/framework/utils"--import SearchProduct from "./search-product"--const SearchProductPrice = model- .define("search_product_price", {- id: model.id({ prefix: "srchprice" }).primaryKey(),- region_id: model.text(),- currency_code: model.text(),- min_amount: model.bigNumber(),- max_amount: model.bigNumber(),- product: model.belongsTo(() => SearchProduct, {- mappedBy: "prices",- }),- })- .indexes([- {- name: "IDX_search_product_price_product_region_unique",- on: ["product_id", "region_id"],- unique: true,- where: "deleted_at IS NULL",- },- {- name: "IDX_search_product_price_region_min_amount",- on: ["region_id", "min_amount"],- where: "deleted_at IS NULL",- },- ])--export default SearchProductPricediff --git a/packages/core/src/modules/search/models/search-product.ts b/packages/core/src/modules/search/models/search-product.tsdeleted file mode 100644index a10d9eca9..000000000--- a/packages/core/src/modules/search/models/search-product.ts+++ /dev/null@@ -1,56 +0,0 @@-import { model } from "@medusajs/framework/utils"--import SearchProductPrice from "./search-product-price"--const SearchProduct = model- .define("search_product", {- id: model.id({ prefix: "srchprod" }).primaryKey(),- product_id: model.text(),- title: model.text().searchable(),- handle: model.text(),- description: model.text().searchable().nullable(),- thumbnail: model.text().nullable(),- status: model.text(),- collection_id: model.text().nullable(),- type_id: model.text().nullable(),- category_ids: model.json(),- tag_ids: model.json(),- seller_ids: model.json(),- variant_skus: model.json(),- attributes: model.json(),- search_text: model.text().nullable(),- min_amount: model.bigNumber().nullable(),- max_amount: model.bigNumber().nullable(),- metadata: model.json().nullable(),- prices: model.hasMany(() => SearchProductPrice, {- mappedBy: "product",- }),- })- .cascades({- delete: ["prices"],- })- .indexes([- {- name: "IDX_search_product_product_id_unique",- on: ["product_id"],- unique: true,- where: "deleted_at IS NULL",- },- {- name: "IDX_search_product_status",- on: ["status"],- where: "deleted_at IS NULL",- },- {- name: "IDX_search_product_collection_id",- on: ["collection_id"],- where: "deleted_at IS NULL AND collection_id IS NOT NULL",- },- {- name: "IDX_search_product_type_id",- on: ["type_id"],- where: "deleted_at IS NULL AND type_id IS NOT NULL",- },- ])--export default SearchProductdiff --git a/packages/core/src/modules/search/repositories/search.ts b/packages/core/src/modules/search/repositories/search.tsdeleted file mode 100644index ce8cb216e..000000000--- a/packages/core/src/modules/search/repositories/search.ts+++ /dev/null@@ -1,372 +0,0 @@-import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"--import {- FacetParams,- FacetResult,- PriceRangeFacetBucket,- SearchFilters,- SearchParams,- SearchResult,- SearchResultProduct,-} from "../types"--type Knex = ReturnType<SqlEntityManager["getKnex"]>--type Binding = string | number--type WhereFragment = {- sql: string- bindings: Binding[]-}--type FilterDimension =- | "category"- | "collection"- | "type"- | "tag"- | "seller"- | "attributes"- | "price"--const TS_CONFIG = "simple"--const toArray = (value: string | string[] | undefined): string[] => {- if (value === undefined) {- return []- }- return Array.isArray(value) ? value : [value]-}--const arrayLiteral = (values: string[], bindings: Binding[]): string => {- const placeholders = values.map(() => "?").join(", ")- bindings.push(...values)- return `array[${placeholders}]::text[]`-}--// `omit` drops a single dimension so a facet's own selection is excluded from-// its own drill-down counts.-const buildWhere = (- params: { q?: string; filters?: SearchFilters },- omit?: FilterDimension-): WhereFragment => {- const filters = params.filters ?? {}- const clauses: string[] = ["sp.deleted_at IS NULL", "sp.status = ?"]- const bindings: Binding[] = ["published"]-- if (params.q) {- clauses.push(`sp.search_tsv @@ websearch_to_tsquery('${TS_CONFIG}', ?)`)- bindings.push(params.q)- }-- if (omit !== "category" && filters.category_ids?.length) {- clauses.push(- `jsonb_exists_any(sp.category_ids, ${arrayLiteral(filters.category_ids, bindings)})`- )- }-- if (omit !== "collection") {- const collections = toArray(filters.collection_id)- if (collections.length) {- clauses.push(`sp.collection_id = ANY(${arrayLiteral(collections, bindings)})`)- }- }-- if (omit !== "type") {- const types = toArray(filters.type_id)- if (types.length) {- clauses.push(`sp.type_id = ANY(${arrayLiteral(types, bindings)})`)- }- }-- if (omit !== "tag" && filters.tag_ids?.length) {- clauses.push(- `jsonb_exists_any(sp.tag_ids, ${arrayLiteral(filters.tag_ids, bindings)})`- )- }-- if (omit !== "seller" && filters.seller_ids?.length) {- clauses.push(- `jsonb_exists_any(sp.seller_ids, ${arrayLiteral(filters.seller_ids, bindings)})`- )- }-- if (omit !== "attributes" && filters.attributes) {- for (const [attributeId, values] of Object.entries(filters.attributes)) {- if (!values.length) {- continue- }- clauses.push(`jsonb_exists_any(sp.attributes -> ?, ${arrayLiteral(values, bindings)})`)- bindings.splice(bindings.length - values.length, 0, attributeId)- }- }-- if (omit !== "price" && filters.price) {- if (filters.price.gte !== undefined) {- clauses.push("pr.max_amount >= ?")- bindings.push(filters.price.gte)- }- if (filters.price.lte !== undefined) {- clauses.push("pr.min_amount <= ?")- bindings.push(filters.price.lte)- }- }-- return { sql: clauses.join(" AND "), bindings }-}--const priceJoin = (regionId: string): WhereFragment => ({- sql: "LEFT JOIN search_product_price pr ON pr.product_id = sp.id AND pr.region_id = ? AND pr.deleted_at IS NULL",- bindings: [regionId],-})--const requiresPriceRow = (filters?: SearchFilters, sortByPrice?: boolean): boolean =>- Boolean(sortByPrice || filters?.price)--type ProductRow = {- id: string- product_id: string- title: string- handle: string- description: string | null- thumbnail: string | null- status: string- collection_id: string | null- type_id: string | null- category_ids: string[] | null- tag_ids: string[] | null- seller_ids: string[] | null- attributes: Record<string, string[]> | null- metadata: Record<string, unknown> | null- pr_region_id: string | null- pr_currency_code: string | null- pr_min_amount: string | number | null- pr_max_amount: string | number | null-}--const mapProduct = (row: ProductRow): SearchResultProduct => ({- id: row.id,- product_id: row.product_id,- title: row.title,- handle: row.handle,- description: row.description,- thumbnail: row.thumbnail,- status: row.status,- collection_id: row.collection_id,- type_id: row.type_id,- category_ids: row.category_ids ?? [],- tag_ids: row.tag_ids ?? [],- seller_ids: row.seller_ids ?? [],- attributes: row.attributes ?? {},- metadata: row.metadata,- calculated_price:- row.pr_region_id && row.pr_currency_code- ? {- region_id: row.pr_region_id,- currency_code: row.pr_currency_code,- min_amount: Number(row.pr_min_amount),- max_amount: Number(row.pr_max_amount),- }- : null,-})--export const searchProducts = async (- knex: Knex,- params: SearchParams-): Promise<SearchResult> => {- const join = priceJoin(params.region_id)- const where = buildWhere(params)- const sortByPrice = params.sort?.field === "price"- const needsPriceRow = requiresPriceRow(params.filters, sortByPrice)-- const from = `FROM search_product sp ${join.sql} WHERE ${where.sql}${- needsPriceRow ? " AND pr.id IS NOT NULL" : ""- }`- const baseBindings = [...join.bindings, ...where.bindings]-- const order = (() => {- const dir = params.sort?.order === "asc" ? "ASC" : "DESC"- if (params.sort?.field === "price") {- return `ORDER BY pr.min_amount ${dir} NULLS LAST`- }- if (params.sort?.field === "relevance" && params.q) {- return `ORDER BY ts_rank(sp.search_tsv, websearch_to_tsquery('${TS_CONFIG}', ?)) DESC`- }- if (params.q && !params.sort) {- return `ORDER BY ts_rank(sp.search_tsv, websearch_to_tsquery('${TS_CONFIG}', ?)) DESC`- }- return `ORDER BY sp.created_at ${dir}`- })()-- const orderBindings: Binding[] =- order.includes("ts_rank") && params.q ? [params.q] : []-- const take = params.pagination?.take ?? 20- const skip = params.pagination?.skip ?? 0-- const dataSql = `SELECT sp.id, sp.product_id, sp.title, sp.handle, sp.description, sp.thumbnail, sp.status, sp.collection_id, sp.type_id, sp.category_ids, sp.tag_ids, sp.seller_ids, sp.attributes, sp.metadata, pr.region_id AS pr_region_id, pr.currency_code AS pr_currency_code, pr.min_amount AS pr_min_amount, pr.max_amount AS pr_max_amount ${from} ${order} LIMIT ? OFFSET ?`-- const dataResult = await knex.raw(dataSql, [- ...baseBindings,- ...orderBindings,- take,- skip,- ])-- const countSql = `SELECT count(*)::int AS count ${from}`- const countResult = await knex.raw(countSql, baseBindings)-- const rows = (dataResult.rows ?? []) as ProductRow[]- const count = Number(countResult.rows?.[0]?.count ?? 0)-- return { products: rows.map(mapProduct), count }-}--type FacetCountRow = { value: string; count: number }--const runFacet = async (- knex: Knex,- regionId: string,- params: FacetParams,- omit: FilterDimension,- selectExpr: string,- fromExtra: string,- groupBy: string,- extraWhere = ""-): Promise<FacetCountRow[]> => {- const join = priceJoin(regionId)- const where = buildWhere(params, omit)- const needsPriceRow = omit !== "price" && Boolean(params.filters?.price)- const sql = `SELECT ${selectExpr}, count(DISTINCT sp.id)::int AS count FROM search_product sp ${join.sql}${fromExtra} WHERE ${where.sql}${- needsPriceRow ? " AND pr.id IS NOT NULL" : ""- }${extraWhere} GROUP BY ${groupBy} ORDER BY count DESC`- const result = await knex.raw(sql, [...join.bindings, ...where.bindings])- return (result.rows ?? []) as FacetCountRow[]-}--export const computeFacets = async (- knex: Knex,- params: FacetParams-): Promise<FacetResult> => {- const regionId = params.region_id-- const categories = await runFacet(- knex,- regionId,- params,- "category",- "value",- ", jsonb_array_elements_text(sp.category_ids) AS value",- "value"- )-- const collections = await runFacet(- knex,- regionId,- params,- "collection",- "sp.collection_id AS value",- "",- "sp.collection_id",- " AND sp.collection_id IS NOT NULL"- )-- const types = await runFacet(- knex,- regionId,- params,- "type",- "sp.type_id AS value",- "",- "sp.type_id",- " AND sp.type_id IS NOT NULL"- )-- const tags = await runFacet(- knex,- regionId,- params,- "tag",- "value",- ", jsonb_array_elements_text(sp.tag_ids) AS value",- "value"- )-- const attributeRows = (await (async () => {- const join = priceJoin(regionId)- const where = buildWhere(params, "attributes")- const needsPriceRow = Boolean(params.filters?.price)- const sql = `SELECT kv.key AS attr_id, val AS value, count(DISTINCT sp.id)::int AS count FROM search_product sp ${join.sql}, jsonb_each(sp.attributes) AS kv, jsonb_array_elements_text(kv.value) AS val WHERE ${where.sql}${- needsPriceRow ? " AND pr.id IS NOT NULL" : ""- } GROUP BY kv.key, val ORDER BY count DESC`- const result = await knex.raw(sql, [...join.bindings, ...where.bindings])- return (result.rows ?? []) as Array<{- attr_id: string- value: string- count: number- }>- })())-- const attributes: FacetResult["attributes"] = {}- for (const row of attributeRows) {- if (!attributes[row.attr_id]) {- attributes[row.attr_id] = []- }- attributes[row.attr_id].push({ value: row.value, count: Number(row.count) })- }-- const price_ranges = await computePriceRangeFacets(knex, params)-- return {- categories: categories.map((r) => ({ value: r.value, count: Number(r.count) })),- collections: collections.map((r) => ({ value: r.value, count: Number(r.count) })),- types: types.map((r) => ({ value: r.value, count: Number(r.count) })),- tags: tags.map((r) => ({ value: r.value, count: Number(r.count) })),- attributes,- price_ranges,- }-}--const computePriceRangeFacets = async (- knex: Knex,- params: FacetParams-): Promise<PriceRangeFacetBucket[]> => {- const buckets = params.price_ranges ?? []- if (!buckets.length) {- return []- }-- const join = priceJoin(params.region_id)- const where = buildWhere(params, "price")-- const selects: string[] = []- const bucketBindings: Binding[] = []- buckets.forEach((bucket, index) => {- const conds: string[] = []- if (bucket.gte !== undefined) {- conds.push("pr.max_amount >= ?")- bucketBindings.push(bucket.gte)- }- if (bucket.lte !== undefined) {- conds.push("pr.min_amount <= ?")- bucketBindings.push(bucket.lte)- }- const cond = conds.length ? conds.join(" AND ") : "TRUE"- selects.push(- `(count(DISTINCT sp.id) FILTER (WHERE ${cond}))::int AS bucket_${index}`- )- })-- const sql = `SELECT ${selects.join(", ")} FROM search_product sp ${join.sql} WHERE ${where.sql} AND pr.id IS NOT NULL`- const result = await knex.raw(sql, [- ...bucketBindings,- ...join.bindings,- ...where.bindings,- ])- const row = (result.rows?.[0] ?? {}) as Record<string, number>-- return buckets.map((bucket, index) => ({- gte: bucket.gte ?? null,- lte: bucket.lte ?? null,- count: Number(row[`bucket_${index}`] ?? 0),- }))-}diff --git a/packages/core/src/modules/search/service.ts b/packages/core/src/modules/search/service.tsdeleted file mode 100644index 526633af0..000000000--- a/packages/core/src/modules/search/service.ts+++ /dev/null@@ -1,170 +0,0 @@-import {- InjectManager,- MedusaContext,- MedusaService,-} from "@medusajs/framework/utils"-import { Context } from "@medusajs/framework/types"-import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"--import { SearchProduct, SearchProductPrice } from "./models"-import { computeFacets, searchProducts } from "./repositories/search"-import {- FacetParams,- FacetResult,- SearchParams,- SearchProductInput,- SearchResult,-} from "./types"--// MedusaService types model.json() columns as Record<string, unknown>; our-// jsonb columns hold arrays/maps, so write payloads are cast through this shape.-type SearchProductWritePayload = Record<string, unknown>--class SearchModuleService extends MedusaService({- SearchProduct,- SearchProductPrice,-}) {- private getKnex(sharedContext: Context) {- const { baseRepository_ } = this as unknown as {- baseRepository_: { getActiveManager<T>(context?: Context): T }- }- const manager =- baseRepository_.getActiveManager<SqlEntityManager>(sharedContext)- return manager.getKnex()- }-- @InjectManager()- async search(- params: SearchParams,- @MedusaContext() sharedContext: Context = {}- ): Promise<SearchResult> {- return searchProducts(this.getKnex(sharedContext), params)- }-- @InjectManager()- async getFacets(- params: FacetParams,- @MedusaContext() sharedContext: Context = {}- ): Promise<FacetResult> {- return computeFacets(this.getKnex(sharedContext), params)- }-- @InjectManager()- async upsertProducts(- inputs: SearchProductInput[],- @MedusaContext() sharedContext: Context = {}- ): Promise<void> {- if (!inputs.length) {- return- }-- const productIds = inputs.map((input) => input.product_id)- const existing = await this.listSearchProducts(- { product_id: productIds },- { select: ["id", "product_id"] },- sharedContext- )- const existingByProductId = new Map(- existing.map((row) => [row.product_id, row.id])- )-- for (const input of inputs) {- const prices = input.prices ?? []- const amounts = prices.flatMap((p) => [p.min_amount, p.max_amount])- const doc = {- product_id: input.product_id,- title: input.title,- handle: input.handle,- description: input.description ?? null,- thumbnail: input.thumbnail ?? null,- status: input.status,- collection_id: input.collection_id ?? null,- type_id: input.type_id ?? null,- category_ids: input.category_ids ?? [],- tag_ids: input.tag_ids ?? [],- seller_ids: input.seller_ids ?? [],- variant_skus: input.variant_skus ?? [],- attributes: input.attributes ?? {},- search_text: (input.variant_skus ?? []).join(" "),- min_amount: amounts.length ? Math.min(...amounts) : null,- max_amount: amounts.length ? Math.max(...amounts) : null,- metadata: input.metadata ?? null,- }-- const existingId = existingByProductId.get(input.product_id)- let searchProductId: string-- if (existingId) {- await this.updateSearchProducts(- { id: existingId, ...doc } as unknown as SearchProductWritePayload,- sharedContext- )- searchProductId = existingId- await this.deleteSearchProductPricesByProductId_(- existingId,- sharedContext- )- } else {- const created = await this.createSearchProducts(- doc as unknown as SearchProductWritePayload,- sharedContext- )- searchProductId = created.id- }-- if (prices.length) {- await this.createSearchProductPrices(- prices.map((price) => ({- product_id: searchProductId,- region_id: price.region_id,- currency_code: price.currency_code,- min_amount: price.min_amount,- max_amount: price.max_amount,- })),- sharedContext- )- }- }- }-- @InjectManager()- async deleteProducts(- productIds: string[],- @MedusaContext() sharedContext: Context = {}- ): Promise<void> {- if (!productIds.length) {- return- }- const existing = await this.listSearchProducts(- { product_id: productIds },- { select: ["id"] },- sharedContext- )- if (!existing.length) {- return- }- await this.deleteSearchProducts(- existing.map((row) => row.id),- sharedContext- )- }-- private async deleteSearchProductPricesByProductId_(- searchProductId: string,- sharedContext: Context- ): Promise<void> {- const prices = await this.listSearchProductPrices(- { product_id: searchProductId },- { select: ["id"] },- sharedContext- )- if (prices.length) {- await this.deleteSearchProductPrices(- prices.map((row) => row.id),- sharedContext- )- }- }-}--export default SearchModuleServicediff --git a/packages/core/src/modules/search/types.ts b/packages/core/src/modules/search/types.tsdeleted file mode 100644index 9becb39d1..000000000--- a/packages/core/src/modules/search/types.ts+++ /dev/null@@ -1,121 +0,0 @@-export type SearchProductPriceInput = {- region_id: string- currency_code: string- min_amount: number- max_amount: number-}--export type SearchProductInput = {- product_id: string- title: string- handle: string- description?: string | null- thumbnail?: string | null- status: string- collection_id?: string | null- type_id?: string | null- category_ids?: string[]- tag_ids?: string[]- seller_ids?: string[]- variant_skus?: string[]- attributes?: Record<string, string[]>- metadata?: Record<string, unknown> | null- prices?: SearchProductPriceInput[]-}--export type SearchPriceRangeFilter = {- gte?: number- lte?: number-}--export type SearchFilters = {- category_ids?: string[]- collection_id?: string | string[]- type_id?: string | string[]- tag_ids?: string[]- seller_ids?: string[]- attributes?: Record<string, string[]>- price?: SearchPriceRangeFilter-}--export type SearchSortField = "price" | "created_at" | "relevance"--export type SearchSort = {- field: SearchSortField- order?: "asc" | "desc"-}--export type SearchPagination = {- skip?: number- take?: number-}--export type SearchParams = {- q?: string- region_id: string- filters?: SearchFilters- sort?: SearchSort- pagination?: SearchPagination-}--export type SearchResultPrice = {- region_id: string- currency_code: string- min_amount: number- max_amount: number-}--export type SearchResultProduct = {- id: string- product_id: string- title: string- handle: string- description: string | null- thumbnail: string | null- status: string- collection_id: string | null- type_id: string | null- category_ids: string[]- tag_ids: string[]- seller_ids: string[]- attributes: Record<string, string[]>- metadata: Record<string, unknown> | null- calculated_price: SearchResultPrice | null-}--export type SearchResult = {- products: SearchResultProduct[]- count: number-}--export type FacetBucket = {- value: string- count: number-}--export type PriceRangeBucketInput = {- gte?: number- lte?: number-}--export type PriceRangeFacetBucket = {- gte: number | null- lte: number | null- count: number-}--export type FacetParams = {- q?: string- region_id: string- filters?: SearchFilters- price_ranges?: PriceRangeBucketInput[]-}--export type FacetResult = {- categories: FacetBucket[]- collections: FacetBucket[]- types: FacetBucket[]- tags: FacetBucket[]- attributes: Record<string, FacetBucket[]>- price_ranges: PriceRangeFacetBucket[]-}diff --git a/packages/core/src/modules/search/utils.ts b/packages/core/src/modules/search/utils.tsdeleted file mode 100644index 248fb3304..000000000--- a/packages/core/src/modules/search/utils.ts+++ /dev/null@@ -1,81 +0,0 @@-import { MedusaError } from "@medusajs/framework/utils"--import { SearchFilters, SearchSort, SearchSortField } from "./types"-import { SearchQueryFilters } from "./validators"--const ALLOWED_SORT_FIELDS: Record<string, SearchSortField> = {- price: "price",- created_at: "created_at",- relevance: "relevance",-}--const toArray = (value: string | string[] | undefined): string[] | undefined => {- if (value === undefined) {- return undefined- }- return Array.isArray(value) ? value : [value]-}--export const buildSearchFilters = (- query: SearchQueryFilters-): SearchFilters => {- const filters: SearchFilters = {}-- const categoryIds = toArray(query.category_id)- if (categoryIds) {- filters.category_ids = categoryIds- }- const collectionId = toArray(query.collection_id)- if (collectionId) {- filters.collection_id = collectionId- }- const typeId = toArray(query.type_id)- if (typeId) {- filters.type_id = typeId- }- const tagIds = toArray(query.tag_id)- if (tagIds) {- filters.tag_ids = tagIds- }- const sellerIds = toArray(query.seller_id)- if (sellerIds) {- filters.seller_ids = sellerIds- }- if (query.attributes) {- filters.attributes = Object.fromEntries(- Object.entries(query.attributes).map(([key, value]) => [- key,- toArray(value) ?? [],- ])- )- }- if (query.min_price !== undefined || query.max_price !== undefined) {- filters.price = {}- if (query.min_price !== undefined) {- filters.price.gte = query.min_price- }- if (query.max_price !== undefined) {- filters.price.lte = query.max_price- }- }-- return filters-}--export const buildSearchSort = (- order: Record<string, string> | undefined-): SearchSort | undefined => {- const entry = order ? Object.entries(order)[0] : undefined- if (!entry) {- return undefined- }- const [field, direction] = entry- const mapped = ALLOWED_SORT_FIELDS[field]- if (!mapped) {- throw new MedusaError(- MedusaError.Types.INVALID_DATA,- `Order field ${field} is not valid`- )- }- return { field: mapped, order: direction === "DESC" ? "desc" : "asc" }-}diff --git a/packages/core/src/modules/search/validators.ts b/packages/core/src/modules/search/validators.tsdeleted file mode 100644index 02385a343..000000000--- a/packages/core/src/modules/search/validators.ts+++ /dev/null@@ -1,18 +0,0 @@-import { z } from "zod"--export const SearchQueryFiltersSchema = z.object({- q: z.string().optional(),- region_id: z.string(),- category_id: z.union([z.string(), z.array(z.string())]).optional(),- collection_id: z.union([z.string(), z.array(z.string())]).optional(),- type_id: z.union([z.string(), z.array(z.string())]).optional(),- tag_id: z.union([z.string(), z.array(z.string())]).optional(),- seller_id: z.union([z.string(), z.array(z.string())]).optional(),- attributes: z- .record(z.string(), z.union([z.string(), z.array(z.string())]))- .optional(),- min_price: z.coerce.number().optional(),- max_price: z.coerce.number().optional(),-})--export type SearchQueryFilters = z.infer<typeof SearchQueryFiltersSchema>diff --git a/packages/core/src/subscribers/search-index-sync.ts b/packages/core/src/subscribers/search-index-sync.tsdeleted file mode 100644index 79fe339a9..000000000--- a/packages/core/src/subscribers/search-index-sync.ts+++ /dev/null@@ -1,36 +0,0 @@-import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"--import { OfferWorkflowEvents, SellerWorkflowEvents } from "../workflows/events"-import { ProductWorkflowEvents } from "../workflows/product/events"-import {- resolveProductIds,- syncSearchProducts,-} from "../utils/search/sync-search-products"--export default async function searchIndexSyncHandler({- event,- container,-}: SubscriberArgs<unknown>) {- const productIds = await resolveProductIds(container, event.name, event.data)- await syncSearchProducts(container, productIds)-}--export const config: SubscriberConfig = {- event: [- OfferWorkflowEvents.CREATED,- OfferWorkflowEvents.UPDATED,- OfferWorkflowEvents.DELETED,- ProductWorkflowEvents.PUBLISHED,- ProductWorkflowEvents.REJECTED,- SellerWorkflowEvents.UPDATED,- SellerWorkflowEvents.SUSPENDED,- SellerWorkflowEvents.UNSUSPENDED,- SellerWorkflowEvents.APPROVED,- SellerWorkflowEvents.TERMINATED,- SellerWorkflowEvents.UNTERMINATED,- SellerWorkflowEvents.DELETED,- ],- context: {- subscriberId: "search-index-sync",- },-}diff --git a/packages/core/src/utils/search/sync-search-products.ts b/packages/core/src/utils/search/sync-search-products.tsdeleted file mode 100644index 670e1004d..000000000--- a/packages/core/src/utils/search/sync-search-products.ts+++ /dev/null@@ -1,231 +0,0 @@-import { MedusaContainer } from "@medusajs/framework/types"-import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"-import { MercurModules, ProductStatus, SellerStatus } from "@mercurjs/types"--import type SearchModuleService from "../../modules/search/service"-import { SearchProductInput } from "../../modules/search/types"--const PRODUCT_FIELDS = [- "id",- "status",- "title",- "handle",- "description",- "thumbnail",- "collection.id",- "type.id",- "categories.id",- "tags.id",- "product_attribute_values.id",- "product_attribute_values.attribute.id",- "product_attribute_values.attribute.is_filterable",-]--const OFFER_FIELDS = [- "id",- "product_id",- "seller_id",- "sku",- "seller.status",- "product_variant.price_set.id",-]--type GraphProduct = {- id: string- status: string- title: string- handle: string- description: string | null- thumbnail: string | null- collection?: { id: string } | null- type?: { id: string } | null- categories?: { id: string }[]- tags?: { id: string }[]- product_attribute_values?: {- id: string- attribute?: { id: string; is_filterable: boolean } | null- }[]-}--type GraphOffer = {- id: string- product_id: string- seller_id: string- sku: string | null- seller?: { status: string } | null- product_variant?: { price_set?: { id: string } | null } | null-}--type GraphRegion = { id: string; currency_code: string }--type CalculatedPrice = { id: string; calculated_amount: number | null }--const unique = (values: string[]): string[] => Array.from(new Set(values))--export const syncSearchProducts = async (- container: MedusaContainer,- productIds: string[]-): Promise<void> => {- const ids = unique(productIds).filter(Boolean)- if (!ids.length) {- return- }-- const query = container.resolve(ContainerRegistrationKeys.QUERY)- const pricing = container.resolve(Modules.PRICING)- const search = container.resolve<SearchModuleService>(MercurModules.SEARCH)-- const { data: products } = await query.graph({- entity: "product",- fields: PRODUCT_FIELDS,- filters: { id: ids },- })- const graphProducts = products as GraphProduct[]-- const found = new Set(graphProducts.map((p) => p.id))- const published = graphProducts.filter(- (p) => p.status === ProductStatus.PUBLISHED- )-- const deleteIds = [- ...ids.filter((id) => !found.has(id)),- ...graphProducts- .filter((p) => p.status !== ProductStatus.PUBLISHED)- .map((p) => p.id),- ]- if (deleteIds.length) {- await search.deleteProducts(deleteIds)- }- if (!published.length) {- return- }-- const publishedIds = published.map((p) => p.id)- const { data: offers } = await query.graph({- entity: "offer",- fields: OFFER_FIELDS,- filters: { product_id: publishedIds },- })- const offersByProduct = new Map<string, GraphOffer[]>()- for (const offer of offers as GraphOffer[]) {- if (- offer.seller?.status !== SellerStatus.OPEN ||- !offer.product_variant?.price_set?.id- ) {- continue- }- const group = offersByProduct.get(offer.product_id)- if (group) {- group.push(offer)- } else {- offersByProduct.set(offer.product_id, [offer])- }- }-- const { data: regions } = await query.graph({- entity: "region",- fields: ["id", "currency_code"],- })- const graphRegions = regions as GraphRegion[]-- const inputs: SearchProductInput[] = []-- for (const product of published) {- const productOffers = offersByProduct.get(product.id) ?? []- const priceSetIds = productOffers.map(- (o) => o.product_variant!.price_set!.id- )- const offerIds = productOffers.map((o) => o.id)-- const prices: SearchProductInput["prices"] = []- if (priceSetIds.length) {- for (const region of graphRegions) {- const context: Record<string, unknown> = {- region_id: region.id,- currency_code: region.currency_code,- offer_id: offerIds,- }- const calculated = (await pricing.calculatePrices(- { id: priceSetIds },- { context: context as Record<string, string | number> }- )) as unknown as CalculatedPrice[]-- const amounts = calculated- .map((c) => c.calculated_amount)- .filter((amount): amount is number => amount != null)- if (amounts.length) {- prices.push({- region_id: region.id,- currency_code: region.currency_code,- min_amount: Math.min(...amounts),- max_amount: Math.max(...amounts),- })- }- }- }-- const attributes: Record<string, string[]> = {}- for (const value of product.product_attribute_values ?? []) {- if (value.attribute?.is_filterable && value.attribute.id) {- ;(attributes[value.attribute.id] ??= []).push(value.id)- }- }-- inputs.push({- product_id: product.id,- title: product.title,- handle: product.handle,- description: product.description,- thumbnail: product.thumbnail,- status: ProductStatus.PUBLISHED,- collection_id: product.collection?.id ?? null,- type_id: product.type?.id ?? null,- category_ids: (product.categories ?? []).map((c) => c.id),- tag_ids: (product.tags ?? []).map((t) => t.id),- seller_ids: unique(productOffers.map((o) => o.seller_id)),- variant_skus: productOffers- .map((o) => o.sku)- .filter((sku): sku is string => Boolean(sku)),- attributes,- prices,- })- }-- if (inputs.length) {- await search.upsertProducts(inputs)- }-}--type EventData = { id?: string; product_id?: string }--const toEventItems = (data: unknown): EventData[] =>- (Array.isArray(data) ? data : [data]) as EventData[]--export const resolveProductIds = async (- container: MedusaContainer,- eventName: string,- data: unknown-): Promise<string[]> => {- const items = toEventItems(data)- const query = container.resolve(ContainerRegistrationKeys.QUERY)-- if (eventName.startsWith("offer.")) {- return items.map((i) => i.product_id).filter((id): id is string => !!id)- }-- if (eventName.startsWith("seller.")) {- const sellerIds = items.map((i) => i.id).filter((id): id is string => !!id)- if (!sellerIds.length) {- return []- }- const { data: sellerOffers } = await query.graph({- entity: "offer",- fields: ["product_id"],- filters: { seller_id: sellerIds },- })- return (sellerOffers as { product_id: string }[]).map((o) => o.product_id)- }-- // product.* events- return items.map((i) => i.id).filter((id): id is string => !!id)-}diff --git a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.tsindex f1af5605e..51e619f1a 100644--- a/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts+++ b/packages/core/src/workflows/cart/workflows/complete-cart-with-split-orders.ts@@ -477,9 +477,17 @@ export const completeCartWithSplitOrdersWorkflow = createWorkflow(}))if (cart.promotions?.length) {- cart.promotions.forEach((promotion: PromotionDTO & { seller: SellerDTO }) => {+ cart.promotions.forEach((promotion: PromotionDTO & { seller?: SellerDTO }) => {+ const orderId = promotion.seller?.id+ ? sellerOrdersMap[promotion.seller.id]+ : undefined+ // Sellerless (marketplace/admin) promotions are already+ // applied as cart adjustments; there is no seller order to link.+ if (!orderId) {+ return+ }links.push({- [Modules.ORDER]: { order_id: sellerOrdersMap[promotion.seller.id] },+ [Modules.ORDER]: { order_id: orderId },[Modules.PROMOTION]: { promotion_id: promotion.id },})})diff --git a/packages/types/src/modules.ts b/packages/types/src/modules.tsindex f12fafd8d..7706c7896 100644--- a/packages/types/src/modules.ts+++ b/packages/types/src/modules.ts@@ -10,6 +10,5 @@ export enum MercurModules {VENDOR_UI = "vendor_ui",ADMIN_UI = "admin_ui",CODEGEN = "codegen",- SEARCH = "search",PROMOTION_COST = "promotion_cost",}diff --git a/packages/vendor/src/i18n/translations/en.json b/packages/vendor/src/i18n/translations/en.jsonindex 3e9c3dc58..e11cefa6d 100644--- a/packages/vendor/src/i18n/translations/en.json+++ b/packages/vendor/src/i18n/translations/en.json@@ -2561,7 +2561,9 @@"promotionTabError": "Fix errors in Promotion Tab before proceeding"},"toasts": {- "promotionCreateSuccess": "Promotion ({{code}}) was successfully created."+ "promotionCreateSuccess": "Promotion ({{code}}) was successfully created.",+ "promotionUpdateSuccess": "Promotion was successfully updated.",+ "promotionDeleteSuccess": "Promotion ({{code}}) was successfully deleted."},"create": {},"edit": {diff --git a/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsxindex a784057d5..abac5f09f 100644--- a/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx+++ b/packages/vendor/src/pages/promotions/[id]/edit/edit-promotion-form/edit-promotion-details-form.tsx@@ -8,7 +8,9 @@ import {Input,RadioGroup,Text,+ toast,} from '@medusajs/ui';+import i18n from 'i18next';import { useWatch } from 'react-hook-form';import { Trans, useTranslation } from 'react-i18next';import * as zod from 'zod';@@ -32,11 +34,14 @@ type EditPromotionFormProps = {const EditPromotionSchema = zod.object({is_automatic: zod.string().toLowerCase(),- code: zod.string().min(1),+ code: zod.string().min(1, { message: i18n.t('validation.requiredField') }),is_tax_inclusive: zod.boolean().optional(),status: zod.enum(['active', 'inactive', 'draft']),value_type: zod.enum(['fixed', 'percentage']),- value: zod.number().min(0).or(zod.string().min(1)),+ value: zod+ .number()+ .min(0, { message: i18n.t('validation.requiredField') })+ .or(zod.string().min(1, { message: i18n.t('validation.requiredField') })),allocation: zod.enum(['each', 'across', 'once']),target_type: zod.enum(['order', 'shipping_methods', 'items']),max_quantity: zod.number().min(1).optional().nullable(),@@ -123,7 +128,11 @@ export const EditPromotionDetailsForm = ({ promotion }: EditPromotionFormProps)},{onSuccess: () => {+ toast.success(t('promotions.toasts.promotionUpdateSuccess'));handleSuccess();+ },+ onError: e => {+ toast.error(e.message);}});diff --git a/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-data-table.tsx b/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-data-table.tsxindex 144c3d88d..6e5a6bff0 100644--- a/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-data-table.tsx+++ b/packages/vendor/src/pages/promotions/_components/promotion-list-table/promotion-list-data-table.tsx@@ -1,6 +1,6 @@import { PencilSquare, ReceiptPercent, Trash } from "@medusajs/icons";import { HttpTypes } from "@medusajs/types";-import { usePrompt } from "@medusajs/ui";+import { toast, usePrompt } from "@medusajs/ui";import { createColumnHelper, type ColumnDef } from "@tanstack/react-table";import { useExtendableTable, useLinkQuery } from "@mercurjs/dashboard-shared";import { useMemo } from "react";@@ -122,17 +122,19 @@ const PromotionActions = ({return;}- try {- await mutateAsync(undefined, {- onSuccess: () => {- navigate("/promotions", { replace: true });- },- });- } catch {- throw new Error(- `Promotion with code ${promotion.code} could not be deleted`,- );- }+ await mutateAsync(undefined, {+ onSuccess: () => {+ toast.success(+ t("promotions.toasts.promotionDeleteSuccess", {+ code: promotion.code,+ }),+ );+ navigate("/promotions", { replace: true });+ },+ onError: (e) => {+ toast.error(e.message);+ },+ });};return (diff --git a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsxindex 8398af192..11baecbf5 100644--- a/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx+++ b/packages/vendor/src/pages/promotions/common/edit-rules/components/edit-rules-wrapper/edit-rules-wrapper.tsx@@ -4,6 +4,8 @@ import {PromotionRuleDTO,PromotionRuleResponse,} from "@medusajs/types";+import { toast } from "@medusajs/ui";+import { useTranslation } from "react-i18next";import { useRouteModal } from "../../../../../../components/modals";import {usePromotionAddRules,@@ -26,6 +28,7 @@ export const EditRulesWrapper = ({rules,ruleType,}: EditPromotionFormProps) => {+ const { t } = useTranslation();const { handleSuccess } = useRouteModal();const { mutateAsync: updatePromotion } = useUpdatePromotion(promotion.id);const { mutateAsync: addPromotionRules } = usePromotionAddRules(@@ -72,43 +75,49 @@ export const EditRulesWrapper = ({(rule: { id: string }) => typeof rule.id === "string",);- if (Object.keys(applicationMethodData).length) {- await updatePromotion({- application_method: applicationMethodData,- } as any);- }+ try {+ if (Object.keys(applicationMethodData).length) {+ await updatePromotion({+ application_method: applicationMethodData,+ } as any);+ }- if (rulesToCreate.length) {- await addPromotionRules({- create: rulesToCreate.map((rule) => {- return {- attribute: rule.attribute,- operator: rule.operator,- values: rule.values,- } as any;- }),- });- }+ if (rulesToCreate.length) {+ await addPromotionRules({+ create: rulesToCreate.map((rule) => {+ return {+ attribute: rule.attribute,+ operator: rule.operator,+ values: rule.values,+ } as any;+ }),+ });+ }- if (rulesToRemove?.length) {- await removePromotionRules({- delete: rulesToRemove.map((r) => r.id).filter(Boolean),- });- }+ if (rulesToRemove?.length) {+ await removePromotionRules({+ delete: rulesToRemove.map((r) => r.id).filter(Boolean),+ });+ }- if (rulesToUpdate.length) {- await updatePromotionRules({- update: rulesToUpdate.map((rule: PromotionRuleResponse) => {- return {- id: rule.id!,- attribute: rule.attribute,- operator: rule.operator,- values: rule.values as unknown as string | string[],- };- }),- });+ if (rulesToUpdate.length) {+ await updatePromotionRules({+ update: rulesToUpdate.map((rule: PromotionRuleResponse) => {+ return {+ id: rule.id!,+ attribute: rule.attribute,+ operator: rule.operator,+ values: rule.values as unknown as string | string[],+ };+ }),+ });+ }+ } catch (e) {+ toast.error((e as Error).message);+ return;}+ toast.success(t("promotions.toasts.promotionUpdateSuccess"));handleSuccess();};};diff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx b/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsxindex 88bf36a7c..ff4c86e09 100644--- a/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/create-promotion-form.tsx@@ -381,8 +381,6 @@ export const CreatePromotionForm = () => {}}- console.log(watchCurrencyRule, watchRules)-return (<RouteFocusModal.Form form={form}><KeyboundFormdiff --git a/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts b/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.tsindex e12f31516..afb00a2b3 100644--- a/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts+++ b/packages/vendor/src/pages/promotions/create/create-promotion-form/form-schema.ts@@ -30,7 +30,7 @@ export const CreatePromotionSchema = zcampaign_id: z.string().optional(),campaign_choice: z.enum(["none", "existing", "new"]).optional(),is_automatic: z.string().toLowerCase(),- code: z.string().min(1),+ code: z.string().min(1, { message: i18n.t("validation.requiredField") }),type: z.enum(["buyget", "standard"]),status: z.enum(["draft", "active", "inactive"]),is_tax_inclusive: z.boolean().optional(),@@ -38,7 +38,10 @@ export const CreatePromotionSchema = zrules: RuleSchema,application_method: z.object({allocation: z.enum(["each", "across", "once"]),- value: z.number().min(0).or(z.string().min(1)),+ value: z+ .number()+ .min(0, { message: i18n.t("validation.requiredField") })+ .or(z.string().min(1, { message: i18n.t("validation.requiredField") })),currency_code: z.string().optional(),max_quantity: z.number().optional().nullable(),target_rules: RuleSchema,diff --git a/scripts/deploy.sh b/scripts/deploy.shindex a017d55fa..0e4cb97b0 100755--- a/scripts/deploy.sh+++ b/scripts/deploy.sh@@ -2,35 +2,87 @@# Deploy Mercur to the VPS.# Runs locally; everything inside the heredoc executes on the remote host.#+# Multiple independent instances live side by side on one host. Each has its+# own deploy dir, systemd service, port, domain, Postgres database and Redis+# db-index. Select one with MERCUR_INSTANCE (default 1 = the original deploy).+# Instance 2 is bootstrapped on first deploy by cloning instance 1's host+# artifacts (.env, systemd unit, Caddy vhost) and swapping the instance-scoped+# bits — so a fresh `MERCUR_INSTANCE=2 ./deploy.sh` provisions everything.+## Usage:-# ./deploy.sh # default host+# ./deploy.sh # instance 1 (new.mercur.dev :9000)+# MERCUR_INSTANCE=2 ./deploy.sh # instance 2 (demo.mercur.dev :9001)# [email protected] ./deploy.sh# MERCUR_BRANCH=main ./deploy.sh+# MERCUR_BACKEND_URL=https://x.dev MERCUR_INSTANCE=2 ./deploy.sh # override domainset -euo pipefailHOST="${MERCUR_HOST:[email protected]}"BRANCH="${MERCUR_BRANCH:-main}"-BACKEND_URL="${MERCUR_BACKEND_URL:-https://new.mercur.dev}"--echo "→ Deploying $BRANCH to $HOST (backend: $BACKEND_URL)"+INSTANCE="${MERCUR_INSTANCE:-1}"++# Per-instance configuration. Everything instance-scoped is derived here and+# passed to the remote over the ssh env line. Instance 1 keeps the original+# values so `./deploy.sh` behaves exactly as before.+case "$INSTANCE" in+ 1)+ DEPLOY_DIR="/root/marketplace"+ SERVICE="mercur-api"+ PORT="9000"+ BACKEND_URL="${MERCUR_BACKEND_URL:-https://new.mercur.dev}"+ DB_NAME="" # existing DB — leave the .env DATABASE_URL untouched+ REDIS_DB="" # existing Redis db-index — leave REDIS_URL untouched+ ;;+ 2)+ DEPLOY_DIR="/root/public-demo"+ SERVICE="mercur-api-public-demo"+ PORT="9001"+ BACKEND_URL="${MERCUR_BACKEND_URL:-https://demo.mercur.dev}"+ DB_NAME="public-demo"+ REDIS_DB="1"+ ;;+ *)+ echo "Unknown MERCUR_INSTANCE='$INSTANCE' (expected 1 or 2)" >&2+ exit 1+ ;;+esac++DOMAIN="${BACKEND_URL#https://}"+DOMAIN="${DOMAIN#http://}"+DOMAIN="${DOMAIN%/}"++echo "→ Deploying $BRANCH to $HOST (instance $INSTANCE: $BACKEND_URL, :$PORT, $DEPLOY_DIR)"ssh -o ConnectTimeout=10 "$HOST" \BRANCH="$BRANCH" \+ INSTANCE="$INSTANCE" \+ DEPLOY_DIR="$DEPLOY_DIR" \+ SERVICE="$SERVICE" \+ PORT="$PORT" \+ DOMAIN="$DOMAIN" \MERCUR_BACKEND_URL="$BACKEND_URL" \+ DB_NAME="$DB_NAME" \+ REDIS_DB="$REDIS_DB" \bash -s <<'REMOTE'set -euo pipefailSOURCE_DIR="/root/mercur"-DEPLOY_DIR="/root/marketplace"-SERVICE="mercur-api"-LOCK="/tmp/mercur-deploy.lock"++# Instance 1 is the canonical template every other instance clones from.+BASE_DEPLOY_DIR="/root/marketplace"+BASE_SERVICE="mercur-api"+BASE_PORT="9000"+BASE_DOMAIN="new.mercur.dev"+BASE_ENV="$BASE_DEPLOY_DIR/packages/api/.env"++LOCK="/tmp/mercur-deploy-$INSTANCE.lock"exec 9>"$LOCK"-flock -n 9 || { echo "Another deploy is already running"; exit 1; }+flock -n 9 || { echo "Another deploy for instance $INSTANCE is already running"; exit 1; }-log() { echo "[$(date +'%F %T')] $*"; }+log() { echo "[$(date +'%F %T')] [i$INSTANCE] $*"; }-# 1. Pull upstream+# 1. Pull upstream (shared source checkout — all instances build from it)log "Fetching $BRANCH"cd "$SOURCE_DIR"# Explicit refspec so the remote-tracking ref updates (a bare@@ -39,7 +91,7 @@ git fetch --prune origin "+refs/heads/$BRANCH:refs/remotes/origin/$BRANCH"git reset --hard "origin/$BRANCH"log "Now at $(git rev-parse --short HEAD) — $(git log -1 --pretty=%s)"-# 2. Sync templates/basic → /root/marketplace.+# 2. Sync templates/basic → $DEPLOY_DIR.# Preserve .env files, the lockfile shim, and build output across runs.log "Syncing templates/basic → $DEPLOY_DIR"rsync -a --delete \@@ -53,6 +105,146 @@ rsync -a --delete \--exclude='yarn.lock' \"$SOURCE_DIR/templates/basic/" "$DEPLOY_DIR/"+# 2.5 Provision instance-scoped host artifacts. All steps are idempotent and+# no-op for instance 1 (its DB/env/service/vhost already exist), so this+# block is safe to run on every deploy.+ENV_FILE="$DEPLOY_DIR/packages/api/.env"++# set_env FILE KEY VALUE — upsert a KEY=VALUE line.+set_env() {+ local f="$1" k="$2" v="$3"+ if grep -q "^$k=" "$f"; then+ sed -i "s#^$k=.*#$k=$v#" "$f"+ else+ printf '%s=%s\n' "$k" "$v" >> "$f"+ fi+}++# (a) .env — clone instance 1's env, then swap the instance-scoped keys.+if [ ! -f "$ENV_FILE" ]; then+ log "Bootstrapping $ENV_FILE from $BASE_ENV"+ mkdir -p "$(dirname "$ENV_FILE")"+ cp "$BASE_ENV" "$ENV_FILE"++ # DATABASE_URL: keep host/creds, swap the database name to $DB_NAME.+ if [ -n "$DB_NAME" ]; then+ DB_NAME="$DB_NAME" python3 - "$ENV_FILE" <<'PY'+import os, re, sys+path, db = sys.argv[1], os.environ["DB_NAME"]+lines = open(path).read().splitlines()+out = []+for ln in lines:+ if ln.startswith("DATABASE_URL="):+ # scheme://user:pass@host:port/<db>[?params] -> swap <db>+ ln = re.sub(r"(DATABASE_URL=.*?/)[^/?]+(\?.*)?$", lambda m: f"{m.group(1)}{db}{m.group(2) or ''}", ln)+ out.append(ln)+open(path, "w").write("\n".join(out) + "\n")+PY+ fi++ # REDIS_URL: point at a dedicated db-index so instances don't share keys.+ if [ -n "$REDIS_DB" ]; then+ REDIS_DB="$REDIS_DB" python3 - "$ENV_FILE" <<'PY'+import os, re, sys+path, idx = sys.argv[1], os.environ["REDIS_DB"]+lines = open(path).read().splitlines()+out = []+for ln in lines:+ if ln.startswith("REDIS_URL="):+ base = ln.split("=", 1)[1]+ base = re.sub(r"/\d+$", "", base.rstrip("/"))+ ln = f"REDIS_URL={base}/{idx}"+ out.append(ln)+open(path, "w").write("\n".join(out) + "\n")+PY+ fi++ # Port + CORS + vendor URL for this instance's domain.+ set_env "$ENV_FILE" PORT "$PORT"+ set_env "$ENV_FILE" STORE_CORS "https://$DOMAIN"+ set_env "$ENV_FILE" ADMIN_CORS "https://$DOMAIN"+ set_env "$ENV_FILE" VENDOR_CORS "https://$DOMAIN"+ set_env "$ENV_FILE" AUTH_CORS "https://$DOMAIN"+ set_env "$ENV_FILE" MERCUR_VENDOR_URL "https://$DOMAIN/seller"+ log "Wrote instance .env (PORT=$PORT, DB=$DB_NAME, REDIS db $REDIS_DB)"+else+ # Existing instance: keep credentials, just ensure PORT matches.+ set_env "$ENV_FILE" PORT "$PORT"+fi++# (b) Postgres database — create if missing, reusing instance 1's credentials.+if [ -n "$DB_NAME" ] && command -v psql >/dev/null 2>&1; then+ ADMIN_URL=$(DB_NAME="$DB_NAME" python3 - "$ENV_FILE" <<'PY'+import re, sys+path = sys.argv[1]+url = ""+for ln in open(path):+ if ln.startswith("DATABASE_URL="):+ url = ln.split("=", 1)[1].strip()+# connect to the default `postgres` db to run CREATE DATABASE+print(re.sub(r"(/)[^/?]+(\?.*)?$", lambda m: f"{m.group(1)}postgres{m.group(2) or ''}", url))+PY+ )+ if ! psql "$ADMIN_URL" -tAc "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1; then+ log "Creating Postgres database $DB_NAME"+ psql "$ADMIN_URL" -c "CREATE DATABASE \"$DB_NAME\""+ else+ log "Postgres database $DB_NAME already exists"+ fi+fi++# (c) systemd unit — clone instance 1's unit, swap WorkingDirectory + PORT.+UNIT="/etc/systemd/system/$SERVICE.service"+if [ ! -f "$UNIT" ]; then+ BASE_UNIT="/etc/systemd/system/$BASE_SERVICE.service"+ log "Bootstrapping systemd unit $UNIT from $BASE_UNIT"+ # Retarget WorkingDirectory, drop any inherited PORT= env, then pin our PORT.+ sed -e "s#$BASE_DEPLOY_DIR#$DEPLOY_DIR#g" \+ -e "/^Environment=PORT=/d" \+ -e "/^Description=/s#\$# (instance $INSTANCE)#" \+ "$BASE_UNIT" > "$UNIT"+ # Insert a PORT env right after the [Service] header.+ sed -i "/^\[Service\]/a Environment=PORT=$PORT" "$UNIT"+ systemctl daemon-reload+ systemctl enable "$SERVICE"+fi++# (d) Caddy vhost — clone instance 1's block, swap domain + upstream port.+CADDYFILE="/etc/caddy/Caddyfile"+if [ -f "$CADDYFILE" ] && ! grep -q "^[[:space:]]*$DOMAIN[[:space:]]*{" "$CADDYFILE"; then+ log "Appending Caddy vhost for $DOMAIN → :$PORT"+ DOMAIN="$DOMAIN" PORT="$PORT" BASE_DOMAIN="$BASE_DOMAIN" BASE_PORT="$BASE_PORT" \+ python3 - "$CADDYFILE" <<'PY'+import os, re, sys+path = sys.argv[1]+dom, port = os.environ["DOMAIN"], os.environ["PORT"]+bdom, bport = os.environ["BASE_DOMAIN"], os.environ["BASE_PORT"]+text = open(path).read()+# Extract the base domain's top-level block by brace matching.+start = re.search(rf"(?m)^\s*{re.escape(bdom)}\s*\{{", text)+if not start:+ sys.exit(f"base vhost {bdom} not found in Caddyfile")+i = start.start()+depth = 0+j = i+while j < len(text):+ if text[j] == "{": depth += 1+ elif text[j] == "}":+ depth -= 1+ if depth == 0:+ j += 1+ break+ j += 1+block = text[i:j]+clone = block.replace(bdom, dom).replace(f":{bport}", f":{port}")+open(path, "a").write("\n\n" + clone.strip() + "\n")+PY+ if command -v caddy >/dev/null 2>&1; then+ caddy fmt --overwrite "$CADDYFILE" || true+ systemctl reload caddy || systemctl restart caddy || true+ fi+fi+# Re-seed the yarn lockfile shim (yarn refuses to install in templates/basic# without it because the parent of the original is a bun workspace).[ -f "$DEPLOY_DIR/yarn.lock" ] || touch "$DEPLOY_DIR/yarn.lock"@@ -291,13 +483,13 @@ rewrite_mercur_deps "$DEPLOY_DIR"# `.yarn/cache` so the next install re-fetches fresh metadata.log "Cleaning yarn cache"rm -rf "$DEPLOY_DIR/.yarn/cache" "$DEPLOY_DIR/.yarn/install-state.gz"-yarn cache clean --all >/tmp/mercur-yarn-cache.log 2>&1 || true+yarn cache clean --all >/tmp/mercur-yarn-cache-$INSTANCE.log 2>&1 || truelog "yarn install (workspace)"-yarn install >/tmp/mercur-yarn.log 2>&1 || { tail -n 40 /tmp/mercur-yarn.log; exit 1; }+yarn install >/tmp/mercur-yarn-$INSTANCE.log 2>&1 || { tail -n 40 /tmp/mercur-yarn-$INSTANCE.log; exit 1; }log "yarn build"-yarn build >/tmp/mercur-build.log 2>&1 || { tail -n 40 /tmp/mercur-build.log; exit 1; }+yarn build >/tmp/mercur-build-$INSTANCE.log 2>&1 || { tail -n 40 /tmp/mercur-build-$INSTANCE.log; exit 1; }# 4. Prepare the compiled server (`.medusa/server` is recreated by `medusa build`)PROD_DIR="$DEPLOY_DIR/packages/api/.medusa/server"@@ -311,7 +503,8 @@ cp "$DEPLOY_DIR/packages/api/.env" "$PROD_DIR/.env"# at /static; Caddy (the reverse proxy on the host) maps /dist/* onto that# /static/* route, so files resolve at $MERCUR_BACKEND_URL/dist/<key>.# That Caddy `handle_path /dist/*` rewrite is required for these URLs to-# resolve — it is maintained in /etc/caddy/Caddyfile on the host, not here.+# resolve — it is maintained in /etc/caddy/Caddyfile on the host (cloned+# per-instance in step 2.5).FILE_BACKEND_URL="${MERCUR_BACKEND_URL%/}/dist"if grep -q '^FILE_BACKEND_URL=' "$PROD_DIR/.env"; thensed -i "s#^FILE_BACKEND_URL=.*#FILE_BACKEND_URL=${FILE_BACKEND_URL}#" "$PROD_DIR/.env"@@ -329,10 +522,10 @@ rewrite_mercur_deps "$PROD_DIR"cd "$PROD_DIR"log "Cleaning yarn cache (prod)"rm -rf "$PROD_DIR/.yarn/cache" "$PROD_DIR/.yarn/install-state.gz"-yarn cache clean --all >/tmp/mercur-yarn-cache-prod.log 2>&1 || true+yarn cache clean --all >/tmp/mercur-yarn-cache-prod-$INSTANCE.log 2>&1 || truelog "yarn install (prod)"-yarn install >/tmp/mercur-yarn-prod.log 2>&1 || { tail -n 40 /tmp/mercur-yarn-prod.log; exit 1; }+yarn install >/tmp/mercur-yarn-prod-$INSTANCE.log 2>&1 || { tail -n 40 /tmp/mercur-yarn-prod-$INSTANCE.log; exit 1; }# 5. Run DB migrations (idempotent)log "DB migrate"@@ -345,8 +538,8 @@ systemctl restart "$SERVICE"# 7. Wait for it to become healthyfor i in $(seq 1 20); do- if curl -fsS http://127.0.0.1:9000/health >/dev/null 2>&1; then- log "API healthy ✓ ($(curl -s http://127.0.0.1:9000/health))"+ if curl -fsS "http://127.0.0.1:$PORT/health" >/dev/null 2>&1; then+ log "API healthy ✓ ($(curl -s http://127.0.0.1:$PORT/health))"exit 0fisleep 2@@ -356,6 +549,6 @@ log "API did not become healthy in 40s — inspect: journalctl -u $SERVICE -n 10exit 1REMOTE-echo "✓ Deploy finished"-echo " Admin: https://new.mercur.dev/dashboard"-echo " Vendor: https://new.mercur.dev/seller"\ No newline at end of file+echo "✓ Deploy finished (instance $INSTANCE)"+echo " Admin: $BACKEND_URL/dashboard"+echo " Vendor: $BACKEND_URL/seller"