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
feat(search): PostgreSQL faceted search module (#1242)
Viktor Holik216d76a4467e
diff --git a/integration-tests/http/search/store/search.spec.ts b/integration-tests/http/search/store/search.spec.tsnew file mode 100644index 000000000..a3c414624--- /dev/null+++ b/integration-tests/http/search/store/search.spec.ts@@ -0,0 +1,124 @@+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/cli/routes-manifest.json b/packages/cli/routes-manifest.jsonindex 76b21f2b0..d07dfcf5d 100644--- a/packages/cli/routes-manifest.json+++ b/packages/cli/routes-manifest.json@@ -366,6 +366,7 @@"/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 ce633a143..3c0788ccb 100644--- a/packages/core/.mercur/routes.d.ts+++ b/packages/core/.mercur/routes.d.ts@@ -628,7 +628,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("@mercurjs/core/api/store/search/route");+ search: typeof import("../src/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 0366c99a5..87e2706ef 100644--- a/packages/core/src/api/store/middlewares.ts+++ b/packages/core/src/api/store/middlewares.ts@@ -6,6 +6,7 @@ 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[] = [@@ -15,5 +16,6 @@ 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.tsnew file mode 100644index 000000000..774f768ea--- /dev/null+++ b/packages/core/src/api/store/search/middlewares.ts@@ -0,0 +1,21 @@+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.tsnew file mode 100644index 000000000..6a9485598--- /dev/null+++ b/packages/core/src/api/store/search/query-config.ts@@ -0,0 +1,25 @@+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.tsnew file mode 100644index 000000000..4ac51502c--- /dev/null+++ b/packages/core/src/api/store/search/route.ts@@ -0,0 +1,52 @@+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.tsnew file mode 100644index 000000000..b81841330--- /dev/null+++ b/packages/core/src/api/store/search/validators.ts@@ -0,0 +1,10 @@+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.tsnew file mode 100644index 000000000..32e4a33ca--- /dev/null+++ b/packages/core/src/jobs/sync-search-index.ts@@ -0,0 +1,40 @@+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.tsnew file mode 100644index 000000000..0f4986a8f--- /dev/null+++ b/packages/core/src/modules/search/__tests__/search.spec.ts@@ -0,0 +1,170 @@+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.tsnew file mode 100644index 000000000..423dae391--- /dev/null+++ b/packages/core/src/modules/search/index.ts@@ -0,0 +1,8 @@+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.tsnew file mode 100644index 000000000..72f49870e--- /dev/null+++ b/packages/core/src/modules/search/joiner-config.ts@@ -0,0 +1,12 @@+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.tsnew file mode 100644index 000000000..5fdeb9674--- /dev/null+++ b/packages/core/src/modules/search/migrations/Migration20260710151923.ts@@ -0,0 +1,60 @@+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.tsnew file mode 100644index 000000000..5ad7d44fc--- /dev/null+++ b/packages/core/src/modules/search/models/index.ts@@ -0,0 +1,2 @@+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.tsnew file mode 100644index 000000000..6e9a4c86e--- /dev/null+++ b/packages/core/src/modules/search/models/search-product-price.ts@@ -0,0 +1,30 @@+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.tsnew file mode 100644index 000000000..a10d9eca9--- /dev/null+++ b/packages/core/src/modules/search/models/search-product.ts@@ -0,0 +1,56 @@+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.tsnew file mode 100644index 000000000..ce8cb216e--- /dev/null+++ b/packages/core/src/modules/search/repositories/search.ts@@ -0,0 +1,372 @@+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.tsnew file mode 100644index 000000000..526633af0--- /dev/null+++ b/packages/core/src/modules/search/service.ts@@ -0,0 +1,170 @@+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.tsnew file mode 100644index 000000000..9becb39d1--- /dev/null+++ b/packages/core/src/modules/search/types.ts@@ -0,0 +1,121 @@+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.tsnew file mode 100644index 000000000..248fb3304--- /dev/null+++ b/packages/core/src/modules/search/utils.ts@@ -0,0 +1,81 @@+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.tsnew file mode 100644index 000000000..02385a343--- /dev/null+++ b/packages/core/src/modules/search/validators.ts@@ -0,0 +1,18 @@+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.tsnew file mode 100644index 000000000..79fe339a9--- /dev/null+++ b/packages/core/src/subscribers/search-index-sync.ts@@ -0,0 +1,36 @@+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.tsnew file mode 100644index 000000000..670e1004d--- /dev/null+++ b/packages/core/src/utils/search/sync-search-products.ts@@ -0,0 +1,231 @@+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/tsconfig.json b/packages/core/tsconfig.jsonindex f235cf02b..3df6392cc 100644--- a/packages/core/tsconfig.json+++ b/packages/core/tsconfig.json@@ -31,6 +31,8 @@".medusa/server",".medusa/admin","src/admin",- ".cache"+ ".cache",+ "**/__tests__/**",+ "**/*.spec.ts"]}\ No newline at end of file