Skip to content

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

feat(offers): serve store offer lists through the Medusa index engine (#1747)

Viktor Holik98634748eaf4
diff --git a/apps/docs/platform/offer/concepts/what-is-an-offer.mdx b/apps/docs/platform/offer/concepts/what-is-an-offer.mdx
index 457cfa467..f360bddc8 100644
--- a/apps/docs/platform/offer/concepts/what-is-an-offer.mdx
+++ b/apps/docs/platform/offer/concepts/what-is-an-offer.mdx
@@ -26,7 +26,7 @@ const { data: [offer] } = await query.graph({
})
```
-This query reads one offer with its store and master variant. `seller` and `product_variant` resolve through read-only links on `seller_id` and `variant_id`.
+This query reads one offer with its store and master variant. `seller` resolves through the `offer_seller` link table, which `createOffersWorkflow` writes next to `seller_id`; `product_variant` resolves through a read-only link on `variant_id`.
## Offers and master products
diff --git a/apps/docs/platform/offer/reference/links.mdx b/apps/docs/platform/offer/reference/links.mdx
index 6cfbd6319..838d4ac9d 100644
--- a/apps/docs/platform/offer/reference/links.mdx
+++ b/apps/docs/platform/offer/reference/links.mdx
@@ -8,8 +8,8 @@ The Offer module never references another module directly. Eight module links in
| Link | Other side | Kind | File |
| --- | --- | --- | --- |
-| Offer to store | `Seller` | Read-only, on `seller_id` | `offer-seller-link.ts` |
-| Offer to product | `Product` | Read-only, on `product_id` | `offer-product-link.ts` |
+| Offer to store | `Seller` | Writable, many offers to one store, table `offer_seller` | `offer-seller-link.ts` |
+| Offer to product | `Product` | Writable, many offers to one product, table `offer_product` | `offer-product-link.ts` |
| Offer to variant | `ProductVariant` | Read-only, on `variant_id` | `offer-variant-link.ts` |
| Offer to shipping profile | `ShippingProfile` | Read-only, on `shipping_profile_id` | `offer-shipping-profile-link.ts` |
| Offer to price | `Price` | Writable, one offer to many prices | `offer-price-link.ts` |
@@ -19,7 +19,7 @@ The Offer module never references another module directly. Eight module links in
## Offer to store
-Each offer belongs to one store. The link reads `offer.seller_id`, so you write the store by setting that field, not through the link.
+Each offer belongs to one store. The offer row keeps `seller_id` for filters and the unique SKU index, and the `offer_seller` link table mirrors it so the Medusa index engine can join offers to stores. `createOffersWorkflow` writes both; set `seller_id` and let the workflow create the link.
```ts
const { data: offers } = await query.graph({
@@ -31,7 +31,7 @@ const { data: offers } = await query.graph({
## Offer to product and variant
-Each offer points at one master product and one master variant. Both links are read-only and read `offer.product_id` and `offer.variant_id`.
+Each offer points at one master product and one master variant. The product link is a writable `offer_product` table, mirrored from `offer.product_id` by `createOffersWorkflow`, so the index engine can filter offers by product status. The variant link is read-only and reads `offer.variant_id`.
```ts
const { data: offers } = await query.graph({
diff --git a/claude-progress.md b/claude-progress.md
index 934920222..f3d0f5984 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,23 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Store offers on the Medusa index engine (2026-11-03), branch `feat/index-engine-store-offers`
+
+`GET /store/offers` goes through `api/utils/list-offers.ts` `listOffers()`: `query.index` with seller visibility
+(`seller.status = open`, scheduled-closure dates) and `product.status = published` as index filters, `query.graph`
+with the previous id-list prefetch when a filter isn't indexed (`q`) or the index is off. The index can only join
+across modules through link tables, so `offer_seller` and `offer_product` are now writable links (`isList` on the
+offer side) that `createOffersWorkflow` writes next to `offer.seller_id` / `product_id`; migration script
+`backfill-offer-links.ts` seeds rows for existing offers after `db:migrate` syncs the tables. `withMercur` passes
+`utils/index-schema.ts` (Medusa's product schema + `Offer` + `Seller`) as the index module's `schema` option. Shared
+index helpers moved to `api/utils/index-engine.ts`. The detail route checks seller/product visibility from the
+database (the index is async). Tests: store `store-offers.spec` 16/16 with `helpers/wait-for-indexed-offers.ts`;
+`http/offer` vendor + store specs pass; `order.spec` / `multi-seller-shipping-methods.spec` 500 locally with the
+nested-worktree awilix leak, not this change (CI is the source of truth).
+
+Pre-existing, unchanged: the seller visibility rule hides a seller whenever `closed_to` is in the future, even
+before `closed_from`, in both `resolveVisibleSellerIds` and `store/sellers/middlewares.ts`.
+
## Session — Product lists on the Medusa index engine (2026-11-03), branch `feat/index-engine-product-lists`
`GET /admin|/vendor|/store/products` now go through `api/utils/list-products.ts` `listProducts()`. It uses
diff --git a/integration-tests/helpers/wait-for-indexed-offers.ts b/integration-tests/helpers/wait-for-indexed-offers.ts
new file mode 100644
index 000000000..49b8adf79
--- /dev/null
+++ b/integration-tests/helpers/wait-for-indexed-offers.ts
@@ -0,0 +1,36 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { eventually } from "./eventually"
+
+// The index syncs asynchronously after writes.
+export const waitForIndexedOffers = async (
+ container: MedusaContainer,
+ expected: { id: string; visible: boolean }[]
+) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ await eventually(
+ async () => {
+ for (const entry of expected) {
+ const { data } = await query.index({
+ entity: "offer",
+ fields: ["id"],
+ filters: {
+ id: entry.id,
+ ...(entry.visible
+ ? {
+ seller: { status: "open" },
+ product: { status: "published" },
+ }
+ : {}),
+ },
+ })
+ if (data.length !== 1) {
+ throw new Error(`Offer ${entry.id} is not indexed yet`)
+ }
+ }
+ },
+ { timeout: 15000, interval: 100 }
+ )
+}
diff --git a/integration-tests/http/offer/store/store-offers.spec.ts b/integration-tests/http/offer/store/store-offers.spec.ts
index 83da53af0..840fc6298 100644
--- a/integration-tests/http/offer/store/store-offers.spec.ts
+++ b/integration-tests/http/offer/store/store-offers.spec.ts
@@ -8,7 +8,11 @@ import {
ContainerRegistrationKeys,
Modules,
} from "@medusajs/framework/utils"
-import { MercurModules, SellerStatus } from "@mercurjs/types"
+import {
+ ISellerModuleService,
+ MercurModules,
+ SellerStatus,
+} from "@mercurjs/types"
import { createSellerUser } from "../../../helpers/create-seller-user"
import { createShippingProfile } from "../../../helpers/create-shipping-profile"
import { createVendorProduct } from "../../../helpers/create-product"
@@ -16,6 +20,8 @@ import {
generatePublishableKey,
generateStoreHeaders,
} from "../../../helpers/create-admin-user"
+import { eventually } from "../../../helpers/eventually"
+import { waitForIndexedOffers } from "../../../helpers/wait-for-indexed-offers"
const approveSeller = async (container: MedusaContainer, sellerId: string) => {
const sellerModule: any = container.resolve(MercurModules.SELLER)
@@ -127,6 +133,14 @@ medusaIntegrationTestRunner({
)
).data.offer
+ await waitForIndexedOffers(appContainer, [
+ {
+ id: offer.id,
+ visible:
+ opts.approve !== false && opts.published !== false,
+ },
+ ])
+
return {
headers,
sellerId: result.seller.id as string,
@@ -347,6 +361,103 @@ medusaIntegrationTestRunner({
expect(response.data.offers).toHaveLength(0)
})
+ it("excludes offers from sellers inside a scheduled closure", async () => {
+ const seed = await seedSellerOffer({
+ email: "[email protected]",
+ name: "Closed",
+ stocked: 10,
+ offerPrice: 1000,
+ })
+ const sellerModule = appContainer.resolve<ISellerModuleService>(
+ MercurModules.SELLER
+ )
+ const hour = 60 * 60 * 1000
+
+ await sellerModule.updateSellers({
+ id: seed.sellerId,
+ closed_from: new Date(Date.now() - hour),
+ closed_to: new Date(Date.now() + hour),
+ })
+ await eventually(async () => {
+ const response = await api.get(
+ `/store/offers?product_id=${seed.productId}`,
+ storeHeaders
+ )
+ expect(response.data.offers).toHaveLength(0)
+ })
+
+ await sellerModule.updateSellers({
+ id: seed.sellerId,
+ closed_from: null,
+ closed_to: null,
+ })
+ await eventually(async () => {
+ const response = await api.get(
+ `/store/offers?product_id=${seed.productId}`,
+ storeHeaders
+ )
+ expect(response.data.offers).toHaveLength(1)
+ })
+ })
+
+ it("never widens a seller_id filter beyond visible sellers", async () => {
+ const hidden = await seedSellerOffer({
+ email: "[email protected]",
+ name: "HiddenFilter",
+ stocked: 10,
+ offerPrice: 1000,
+ approve: false,
+ })
+ const open = await seedSellerOffer({
+ email: "[email protected]",
+ name: "OpenFilter",
+ stocked: 10,
+ offerPrice: 1000,
+ productId: hidden.productId,
+ variantId: hidden.variantId,
+ })
+
+ const response = await api.get(
+ `/store/offers?seller_id[]=${hidden.sellerId}&seller_id[]=${open.sellerId}`,
+ storeHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(typeof response.data.estimate_count).toBe("number")
+ expect(
+ response.data.offers.map((o: { id: string }) => o.id)
+ ).toEqual([open.offer.id])
+ })
+
+ it("keeps visibility on the search path, which bypasses the index", async () => {
+ const hidden = await seedSellerOffer({
+ email: "[email protected]",
+ name: "HiddenQ",
+ stocked: 10,
+ offerPrice: 1000,
+ approve: false,
+ })
+ const open = await seedSellerOffer({
+ email: "[email protected]",
+ name: "OpenQ",
+ stocked: 10,
+ offerPrice: 1000,
+ productId: hidden.productId,
+ variantId: hidden.variantId,
+ })
+
+ const response = await api.get(
+ `/store/offers?q=OFFER-&product_id=${hidden.productId}`,
+ storeHeaders
+ )
+
+ expect(response.status).toEqual(200)
+ expect(
+ response.data.offers.map((o: { id: string }) => o.id)
+ ).toEqual([open.offer.id])
+ expect(response.data.estimate_count).toBeUndefined()
+ })
+
it("computes inventory_quantity as floor(stocked / required_quantity)", async () => {
const seed = await seedSellerOffer({
@@ -463,6 +574,22 @@ medusaIntegrationTestRunner({
).toEqual(3300)
})
+ it("404s for an offer on an unpublished product", async () => {
+ const seed = await seedSellerOffer({
+ email: "[email protected]",
+ name: "HiddenDraft",
+ stocked: 4,
+ offerPrice: 3300,
+ published: false,
+ })
+
+ const error = await api
+ .get(`/store/offers/${seed.offer.id}`, storeHeaders)
+ .catch((e) => e)
+
+ expect(error.response.status).toEqual(404)
+ })
+
it("404s for an offer whose seller is not open", async () => {
const seed = await seedSellerOffer({
diff --git a/packages/core/src/api/store/offers/[id]/route.ts b/packages/core/src/api/store/offers/[id]/route.ts
index 4d07d6d0f..1d5c07cf8 100644
--- a/packages/core/src/api/store/offers/[id]/route.ts
+++ b/packages/core/src/api/store/offers/[id]/route.ts
@@ -15,6 +15,14 @@ import {
wrapOffersWithTaxPrices,
} from "../helpers"
import { StoreGetOfferParamsType } from "../validators"
+import { isOfferVisibleInStore } from "../../../utils/list-offers"
+
+const VISIBILITY_FIELDS = [
+ "seller.status",
+ "seller.closed_from",
+ "seller.closed_to",
+ "product.status",
+]
export const GET = async (
req: MedusaStoreRequest<StoreGetOfferParamsType>,
@@ -29,17 +37,28 @@ export const GET = async (
data: [offer],
} = await query.graph({
entity: "offer",
- fields: fields,
+ fields: Array.from(new Set([...fields, ...VISIBILITY_FIELDS])),
filters: { ...req.filterableFields, id: req.params.id },
})
- if (!offer) {
+ if (!offer || !isOfferVisibleInStore(offer)) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Offer with id ${req.params.id} was not found`
)
}
+ for (const path of VISIBILITY_FIELDS) {
+ const [relation, column] = path.split(".")
+ if (fields.some((field) => field === relation || field.startsWith(`${relation}.`))) {
+ if (!fields.includes(path) && !fields.includes(`${relation}.*`)) {
+ delete offer[relation]?.[column]
+ }
+ } else {
+ delete offer[relation]
+ }
+ }
+
const offers = [offer]
if (withCalculatedPrice) {
await wrapOffersWithCalculatedPrices(
diff --git a/packages/core/src/api/store/offers/helpers.ts b/packages/core/src/api/store/offers/helpers.ts
index 031cd69c3..3b97c0e84 100644
--- a/packages/core/src/api/store/offers/helpers.ts
+++ b/packages/core/src/api/store/offers/helpers.ts
@@ -346,7 +346,7 @@ export const splitComputedOfferFields = (fields: string[]) => {
export const EFFECTIVE_LEADTIME_FIELD = "effective_leadtime_to_ship"
-type LeadtimeOffer = {
+export type LeadtimeOffer = {
seller_id?: string | null
leadtime_to_ship?: number | null
effective_leadtime_to_ship?: number | null
diff --git a/packages/core/src/api/store/offers/middlewares.ts b/packages/core/src/api/store/offers/middlewares.ts
index a1d0115c3..7fe8d18b9 100644
--- a/packages/core/src/api/store/offers/middlewares.ts
+++ b/packages/core/src/api/store/offers/middlewares.ts
@@ -1,14 +1,9 @@
import {
authenticate,
clearFiltersByKey,
- MedusaNextFunction,
- MedusaRequest,
- MedusaResponse,
MiddlewareRoute,
} from "@medusajs/framework/http"
import { validateAndTransformQuery } from "@medusajs/framework"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-import { ProductStatus } from "@mercurjs/types"
import {
normalizeDataForContext,
setPricingContext,
@@ -17,60 +12,6 @@ import {
import { storeOfferQueryConfig } from "./query-config"
import { StoreGetOfferParams, StoreGetOffersParams } from "./validators"
-import { resolveVisibleSellerIds } from "../../utils/sellers"
-
-async function applyVisibleSellerIdsFilter(
- req: MedusaRequest,
- _res: MedusaResponse,
- next: MedusaNextFunction
-) {
- req.filterableFields ??= {}
-
- const visibleSellerIds = await resolveVisibleSellerIds(req.scope)
- const requested = req.filterableFields.seller_id as
- | string
- | string[]
- | undefined
-
- // Honor a client-supplied `seller_id` filter, but never let it widen scope
- // beyond the visible sellers — intersect the two instead of overwriting.
- if (requested) {
- const requestedIds = Array.isArray(requested) ? requested : [requested]
- const visibleSet = new Set(visibleSellerIds)
- req.filterableFields.seller_id = requestedIds.filter((id) =>
- visibleSet.has(id)
- )
- } else {
- req.filterableFields.seller_id = visibleSellerIds
- }
-
- next()
-}
-
-async function applyPublishedProductFilter(
- req: MedusaRequest,
- _res: MedusaResponse,
- next: MedusaNextFunction
-) {
- req.filterableFields ??= {}
- const requested = req.filterableFields.product_id as
- | string
- | string[]
- | undefined
-
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: products } = await query.graph({
- entity: "product",
- fields: ["id"],
- filters: {
- status: ProductStatus.PUBLISHED,
- ...(requested ? { id: requested } : {}),
- },
- })
-
- req.filterableFields.product_id = products.map((p: { id: string }) => p.id)
- next()
-}
const pricingMiddlewares = [
normalizeDataForContext({ priceFieldPaths: ["calculated_price"] }),
@@ -82,8 +23,6 @@ const offerMiddlewares = [
authenticate("customer", ["session", "bearer"], {
allowUnauthenticated: true,
}),
- applyVisibleSellerIdsFilter,
- applyPublishedProductFilter,
...pricingMiddlewares,
clearFiltersByKey(["region_id", "country_code", "province", "cart_id"]),
]
diff --git a/packages/core/src/api/store/offers/route.ts b/packages/core/src/api/store/offers/route.ts
index a719d59fa..5b2f8c690 100644
--- a/packages/core/src/api/store/offers/route.ts
+++ b/packages/core/src/api/store/offers/route.ts
@@ -2,9 +2,10 @@ import {
MedusaResponse,
MedusaStoreRequest,
} from "@medusajs/framework/http"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import {
+ type EnrichableOffer,
+ type LeadtimeOffer,
splitComputedOfferFields,
wrapOffersWithCalculatedPrices,
wrapOffersWithEffectiveLeadtime,
@@ -12,20 +13,21 @@ import {
wrapOffersWithTaxPrices,
} from "./helpers"
import { StoreGetOffersParamsType } from "./validators"
+import { getStoreOfferVisibility, listOffers } from "../../utils/list-offers"
export const GET = async (
req: MedusaStoreRequest<StoreGetOffersParamsType>,
res: MedusaResponse
) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
-
const { fields, withCalculatedPrice, withInventoryQuantity, withEffectiveLeadtime } =
splitComputedOfferFields(req.queryConfig.fields)
- const { data: offers, metadata } = await query.graph({
- entity: "offer",
- fields: fields,
+ const { offers, count, estimate_count, offset, limit } = await listOffers<
+ EnrichableOffer & LeadtimeOffer
+ >(req.scope, {
+ fields,
filters: req.filterableFields,
+ visibility: getStoreOfferVisibility(req.scope),
pagination: req.queryConfig.pagination,
})
@@ -47,8 +49,9 @@ export const GET = async (
res.json({
offers,
- count: metadata?.count ?? 0,
- offset: metadata?.skip ?? 0,
- limit: metadata?.take ?? 0,
+ count,
+ ...(estimate_count !== undefined ? { estimate_count } : {}),
+ offset,
+ limit,
})
}
diff --git a/packages/core/src/api/store/sellers/middlewares.ts b/packages/core/src/api/store/sellers/middlewares.ts
index c664f1983..30377c1c3 100644
--- a/packages/core/src/api/store/sellers/middlewares.ts
+++ b/packages/core/src/api/store/sellers/middlewares.ts
@@ -5,25 +5,23 @@ import {
MedusaResponse,
} from "@medusajs/framework/http"
import { MiddlewareRoute } from "@medusajs/medusa"
-import { SellerStatus } from "@mercurjs/types"
import * as QueryConfig from "./query-config"
import { StoreGetSellersParams, StoreGetSellerParams } from "./validators"
+import { storeSellerVisibilityFilter } from "../../utils/sellers"
function applySellerOpenFilters(
req: MedusaRequest,
_res: MedusaResponse,
next: MedusaNextFunction
) {
- const now = new Date()
+ const { status, $and } = storeSellerVisibilityFilter(new Date())
- req.filterableFields.status ??= SellerStatus.OPEN
-
- req.filterableFields.$and ??= []
- ; (req.filterableFields.$and as any[]).push(
- { $or: [{ closed_from: null }, { closed_from: { $gt: now } }] },
- { $or: [{ closed_to: null }, { closed_to: { $lt: now } }] }
- )
+ req.filterableFields.status ??= status
+ req.filterableFields.$and = [
+ ...((req.filterableFields.$and as unknown[] | undefined) ?? []),
+ ...$and,
+ ]
next()
}
diff --git a/packages/core/src/api/utils/index-engine.ts b/packages/core/src/api/utils/index-engine.ts
new file mode 100644
index 000000000..3e8dc81b5
--- /dev/null
+++ b/packages/core/src/api/utils/index-engine.ts
@@ -0,0 +1,116 @@
+import { Modules } from "@medusajs/framework/utils"
+import type { MedusaContainer } from "@medusajs/framework/types"
+
+export type IndexedShape = { [key: string]: true | IndexedShape }
+
+export const LOGICAL_OPERATORS = ["$and", "$or", "$not"]
+
+// The operators the index query builder compiles; the rest throw there, where
+// query.graph would accept them.
+const INDEX_OPERATORS = [
+ "$eq",
+ "$ne",
+ "$lt",
+ "$lte",
+ "$gt",
+ "$gte",
+ "$in",
+ "$nin",
+ "$is",
+ "$like",
+ "$ilike",
+]
+
+export type Pagination = {
+ skip?: number
+ take?: number
+ order?: Record<string, unknown>
+}
+
+export const isPlainObject = (
+ value: unknown
+): value is Record<string, unknown> =>
+ typeof value === "object" &&
+ value !== null &&
+ !Array.isArray(value) &&
+ !(value instanceof Date)
+
+// The index rejects any key outside its schema, so filters are checked against
+// the indexed shape before the engine is chosen.
+export const isIndexable = (
+ filters: Record<string, unknown>,
+ shape: IndexedShape
+): boolean =>
+ Object.entries(filters).every(([key, value]) => {
+ if (value === undefined) {
+ return true
+ }
+
+ if (LOGICAL_OPERATORS.includes(key)) {
+ const entries = Array.isArray(value) ? value : [value]
+ return entries.every(
+ (entry) => isPlainObject(entry) && isIndexable(entry, shape)
+ )
+ }
+
+ const node = shape[key]
+ if (!node) {
+ return false
+ }
+ if (node === true) {
+ return (
+ !isPlainObject(value) ||
+ Object.keys(value).every((operator) =>
+ INDEX_OPERATORS.includes(operator)
+ )
+ )
+ }
+
+ return isPlainObject(value) && isIndexable(value, node)
+ })
+
+export const isOrderIndexable = (
+ order: Record<string, unknown> | undefined,
+ shape: IndexedShape
+) =>
+ !order ||
+ Object.keys(order).every((path) => {
+ let node: true | IndexedShape | undefined = shape
+ for (const segment of path.split(".")) {
+ if (!node || node === true) {
+ return false
+ }
+ node = node[segment]
+ }
+ return node === true
+ })
+
+// Checked through the container, not FeatureFlag: core and the host can load
+// separate @medusajs/framework copies with separate flag routers.
+export const isIndexEngineEnabled = (scope: MedusaContainer) =>
+ !!scope.resolve(Modules.INDEX, { allowUnregistered: true })
+
+export const withClause = (
+ filters: Record<string, unknown>,
+ clause: Record<string, unknown> | undefined
+) => {
+ if (!clause) {
+ return filters
+ }
+ const existing = Array.isArray(filters.$and) ? filters.$and : []
+ return { ...filters, $and: [...existing, clause] }
+}
+
+// The index only reports the planner's estimate; a page that isn't full pins
+// the count exactly, as Medusa's store product list does.
+export const reconcileCount = (
+ estimate: number,
+ skip: number,
+ take: number | undefined,
+ returned: number
+) => {
+ if (take === undefined || returned < take) {
+ return skip + returned
+ }
+ return Math.max(estimate, skip + returned + 1)
+}
diff --git a/packages/core/src/api/utils/index.ts b/packages/core/src/api/utils/index.ts
index f2343f3f8..9bf71e730 100644
--- a/packages/core/src/api/utils/index.ts
+++ b/packages/core/src/api/utils/index.ts
@@ -12,3 +12,4 @@ export * from "./offers"
export * from "./list-products"
export * from "./split-order-payment-status"
export * from "./restrict-vendor-fields"
+export * from "./list-offers"
diff --git a/packages/core/src/api/utils/list-offers.ts b/packages/core/src/api/utils/list-offers.ts
new file mode 100644
index 000000000..bc70c1627
--- /dev/null
+++ b/packages/core/src/api/utils/list-offers.ts
@@ -0,0 +1,156 @@
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import type { MedusaContainer } from "@medusajs/framework/types"
+import { ProductStatus } from "@mercurjs/types"
+
+import {
+ type IndexedShape,
+ type Pagination,
+ isIndexable,
+ isIndexEngineEnabled,
+ isOrderIndexable,
+ reconcileCount,
+ withClause,
+} from "./index-engine"
+import {
+ isSellerVisibleInStore,
+ resolveVisibleSellerIds,
+ storeSellerVisibilityFilter,
+} from "./sellers"
+
+// `q` is left out on purpose, see INDEXED_PRODUCT in list-products.ts.
+const INDEXED_OFFER: IndexedShape = {
+ id: true,
+ seller_id: true,
+ product_id: true,
+ variant_id: true,
+ sku: true,
+ condition_id: true,
+ created_at: true,
+ updated_at: true,
+ seller: { id: true, status: true, closed_from: true, closed_to: true },
+ product: { id: true, status: true },
+}
+
+// query.graph cannot filter on linked-module fields, hence one shape per engine.
+export type OfferVisibility = {
+ index: Record<string, unknown>
+ graph: (filters: Record<string, unknown>) => Promise<Record<string, unknown>>
+}
+
+export const getStoreOfferVisibility = (
+ scope: MedusaContainer
+): OfferVisibility => ({
+ index: {
+ seller: storeSellerVisibilityFilter(),
+ product: { status: ProductStatus.PUBLISHED },
+ },
+ graph: async (filters) => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+ const requestedProductIds = filters.product_id as
+ | string
+ | string[]
+ | undefined
+
+ const [sellerIds, { data: products }] = await Promise.all([
+ resolveVisibleSellerIds(scope),
+ query.graph({
+ entity: "product",
+ fields: ["id"],
+ filters: {
+ status: ProductStatus.PUBLISHED,
+ ...(requestedProductIds ? { id: requestedProductIds } : {}),
+ },
+ }),
+ ])
+
+ return {
+ seller_id: sellerIds,
+ product_id: products.map((product: { id: string }) => product.id),
+ }
+ },
+})
+
+type ListOffersInput = {
+ fields: string[]
+ filters?: Record<string, unknown>
+ visibility?: OfferVisibility
+ pagination?: Pagination
+}
+
+type ListOffersResult<T> = {
+ offers: T[]
+ count: number
+ estimate_count?: number
+ offset: number
+ limit: number
+}
+
+export const listOffers = async <T = Record<string, unknown>>(
+ scope: MedusaContainer,
+ { fields, filters = {}, visibility, pagination }: ListOffersInput
+): Promise<ListOffersResult<T>> => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const indexFilters = withClause(
+ Object.fromEntries(
+ Object.entries(filters).filter(([, value]) => value !== undefined)
+ ),
+ visibility?.index
+ )
+
+ if (
+ isIndexEngineEnabled(scope) &&
+ isIndexable(indexFilters, INDEXED_OFFER) &&
+ isOrderIndexable(pagination?.order, INDEXED_OFFER)
+ ) {
+ const { data, metadata } = await query.index({
+ entity: "offer",
+ fields,
+ filters: indexFilters,
+ pagination,
+ })
+
+ const skip = metadata?.skip ?? pagination?.skip ?? 0
+ const take = metadata?.take ?? pagination?.take
+ const estimate = metadata?.estimate_count ?? 0
+
+ return {
+ offers: data as T[],
+ count: reconcileCount(estimate, skip, take, data.length),
+ estimate_count: estimate,
+ offset: skip,
+ limit: take ?? data.length,
+ }
+ }
+
+ const graphFilters = withClause(
+ filters,
+ visibility ? await visibility.graph(filters) : undefined
+ )
+
+ const { data, metadata } = await query.graph({
+ entity: "offer",
+ fields,
+ filters: graphFilters,
+ pagination,
+ })
+
+ return {
+ offers: data as T[],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ }
+}
+
+type VisibilityOffer = {
+ seller?: Parameters<typeof isSellerVisibleInStore>[0] | null
+ product?: { status?: string | null } | null
+}
+
+// Read from the database, not the index: the index syncs asynchronously and
+// must not decide a 404.
+export const isOfferVisibleInStore = (offer: VisibilityOffer) =>
+ !!offer.seller &&
+ isSellerVisibleInStore(offer.seller) &&
+ offer.product?.status === ProductStatus.PUBLISHED
diff --git a/packages/core/src/api/utils/list-products.ts b/packages/core/src/api/utils/list-products.ts
index 9f801d310..4697916fe 100644
--- a/packages/core/src/api/utils/list-products.ts
+++ b/packages/core/src/api/utils/list-products.ts
@@ -11,7 +11,17 @@ import type {
MedusaContainer,
} from "@medusajs/framework/types"
-type IndexedShape = { [key: string]: true | IndexedShape }
+import {
+ type IndexedShape,
+ type Pagination,
+ isIndexable,
+ isIndexEngineEnabled,
+ isOrderIndexable,
+ isPlainObject,
+ LOGICAL_OPERATORS,
+ reconcileCount,
+ withClause,
+} from "./index-engine"
// The index rejects any key outside its schema, so only these reach it. `q` is
// left out on purpose: the index matches whole tokens (plainto_tsquery) where
@@ -44,15 +54,8 @@ const INDEXED_PRODUCT: IndexedShape = {
const CROSS_MODULE_KEYS = ["product_seller", "sales_channels"]
const CROSS_MODULE_VARIANT_KEYS = ["prices"]
-const LOGICAL_OPERATORS = ["$and", "$or", "$not"]
const INDEX_LIST_CACHE_TTL = 5
-const isPlainObject = (value: unknown): value is Record<string, unknown> =>
- typeof value === "object" &&
- value !== null &&
- !Array.isArray(value) &&
- !(value instanceof Date)
-
const needsIndex = (filters: Record<string, unknown>): boolean =>
Object.entries(filters).some(([key, value]) => {
if (LOGICAL_OPERATORS.includes(key)) {
@@ -69,46 +72,6 @@ const needsIndex = (filters: Record<string, unknown>): boolean =>
)
})
-const isIndexable = (
- filters: Record<string, unknown>,
- shape: IndexedShape
-): boolean =>
- Object.entries(filters).every(([key, value]) => {
- if (value === undefined) {
- return true
- }
-
- if (LOGICAL_OPERATORS.includes(key)) {
- const entries = Array.isArray(value) ? value : [value]
- return entries.every(
- (entry) => isPlainObject(entry) && isIndexable(entry, shape)
- )
- }
-
- const node = shape[key]
- if (!node) {
- return false
- }
- if (node === true) {
- return true
- }
-
- return isPlainObject(value) && isIndexable(value, node)
- })
-
-const isOrderIndexable = (order: Record<string, unknown> | undefined) =>
- !order ||
- Object.keys(order).every((path) => {
- let node: true | IndexedShape | undefined = INDEXED_PRODUCT
- for (const segment of path.split(".")) {
- if (!node || node === true) {
- return false
- }
- node = node[segment]
- }
- return node === true
- })
-
const toIndexFilters = (
filters: Record<string, unknown>
): Record<string, unknown> => {
@@ -136,34 +99,12 @@ const toIndexFilters = (
return next
}
-// Checked through the container, not FeatureFlag: core and the host can load
-// separate @medusajs/framework copies with separate flag routers.
-const isIndexEngineEnabled = (scope: MedusaContainer) =>
- !!scope.resolve(Modules.INDEX, { allowUnregistered: true })
-
-type Pagination = {
- skip?: number
- take?: number
- order?: Record<string, unknown>
-}
-
// query.graph cannot filter on linked-module fields, hence one shape per engine.
export type ProductVisibility = {
index: Record<string, unknown>
graph: () => Promise<Record<string, unknown>>
}
-const withClause = (
- filters: Record<string, unknown>,
- clause: Record<string, unknown> | undefined
-) => {
- if (!clause) {
- return filters
- }
- const existing = Array.isArray(filters.$and) ? filters.$and : []
- return { ...filters, $and: [...existing, clause] }
-}
-
type ListProductsCache = {
ttl?: number
tags?: string[]
@@ -214,18 +155,6 @@ const toQueryOptions = (
...(locale ? { locale } : {}),
})
-const reconcileCount = (
- estimate: number,
- skip: number,
- take: number | undefined,
- returned: number
-) => {
- if (take === undefined || returned < take) {
- return skip + returned
- }
- return Math.max(estimate, skip + returned + 1)
-}
-
// query.index only reports the planner estimate, which undercounts JSONB
// filters badly. This is the ids-only call query.index makes, without paging.
const countIndexedProducts = async (
@@ -278,7 +207,7 @@ export const listProducts = async <T = Record<string, unknown>>(
needsIndex(indexFilters) &&
isIndexEngineEnabled(scope) &&
isIndexable(indexFilters, INDEXED_PRODUCT) &&
- isOrderIndexable(pagination?.order)
+ isOrderIndexable(pagination?.order, INDEXED_PRODUCT)
) {
// One event clears the cache and starts the async index sync, so a request
// in between re-caches pre-write index state; the TTL bounds that.
diff --git a/packages/core/src/api/utils/sellers.ts b/packages/core/src/api/utils/sellers.ts
index 1bf9f42cb..d2bd9acba 100644
--- a/packages/core/src/api/utils/sellers.ts
+++ b/packages/core/src/api/utils/sellers.ts
@@ -2,33 +2,60 @@ import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import type { MedusaContainer } from "@medusajs/framework/types"
import { SellerStatus } from "@mercurjs/types"
+// Truncated to the minute: `now` is part of the cache key, so requests within
+// the same minute share one cached entry.
+export const sellerVisibilityNow = () =>
+ new Date(Math.floor(Date.now() / 60_000) * 60_000)
+
+export const storeSellerVisibilityFilter = (
+ now: Date = sellerVisibilityNow()
+) => ({
+ status: SellerStatus.OPEN,
+ $and: [
+ { $or: [{ closed_from: { $eq: null } }, { closed_from: { $gt: now } }] },
+ { $or: [{ closed_to: { $eq: null } }, { closed_to: { $lt: now } }] },
+ ],
+})
+
+type VisibilitySeller = {
+ status?: string | null
+ closed_from?: string | Date | null
+ closed_to?: string | Date | null
+}
+
+export const isSellerVisibleInStore = (
+ seller: VisibilitySeller,
+ now: Date = sellerVisibilityNow()
+) => {
+ if (seller.status !== SellerStatus.OPEN) {
+ return false
+ }
+ const closedFrom = seller.closed_from ? new Date(seller.closed_from) : null
+ const closedTo = seller.closed_to ? new Date(seller.closed_to) : null
+ return (!closedFrom || closedFrom > now) && (!closedTo || closedTo < now)
+}
+
export const resolveVisibleSellerIds = async (
scope: MedusaContainer
): Promise<string[]> => {
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
- // `now` is part of the cache key, so it is truncated to the minute to let
- // requests within the same minute share one cached entry.
- const now = new Date(Math.floor(Date.now() / 60_000) * 60_000)
- const { data: visibleSellers } = await query.graph({
- entity: "seller",
- fields: ["id"],
- filters: {
- status: SellerStatus.OPEN,
- $and: [
- { $or: [{ closed_from: null }, { closed_from: { $gt: now } }] },
- { $or: [{ closed_to: null }, { closed_to: { $lt: now } }] },
- ],
- },
- }, {
- cache: {
- enable: true,
- // An empty result carries no automatic tags, so without the list tag it
- // would survive the next seller approval until its TTL.
- tags: ["Seller:list:*"],
- computeAutomaticTags: true,
+ const { data: visibleSellers } = await query.graph(
+ {
+ entity: "seller",
+ fields: ["id"],
+ filters: storeSellerVisibilityFilter(),
},
- })
+ // Automatic tags come from the returned rows, so an empty result would
+ // never be invalidated without the explicit list tag.
+ {
+ cache: {
+ enable: true,
+ tags: ["Seller:list:*"],
+ computeAutomaticTags: true,
+ },
+ }
+ )
return visibleSellers.map((s: { id: string }) => s.id)
}
diff --git a/packages/core/src/links/offer-product-link.ts b/packages/core/src/links/offer-product-link.ts
index debf4a315..01e415dda 100644
--- a/packages/core/src/links/offer-product-link.ts
+++ b/packages/core/src/links/offer-product-link.ts
@@ -5,10 +5,12 @@ import OfferModule from "../modules/offer"
export default defineLink(
{
linkable: OfferModule.linkable.offer,
- field: "product_id",
+ isList: true,
},
ProductModule.linkable.product,
{
- readOnly: true,
+ database: {
+ table: "offer_product",
+ },
}
)
diff --git a/packages/core/src/links/offer-seller-link.ts b/packages/core/src/links/offer-seller-link.ts
index 2bd3f1ece..4080e6030 100644
--- a/packages/core/src/links/offer-seller-link.ts
+++ b/packages/core/src/links/offer-seller-link.ts
@@ -5,10 +5,12 @@ import SellerModule from "../modules/seller"
export default defineLink(
{
linkable: OfferModule.linkable.offer,
- field: "seller_id",
+ isList: true,
},
SellerModule.linkable.seller,
{
- readOnly: true,
+ database: {
+ table: "offer_seller",
+ },
}
)
diff --git a/packages/core/src/migration-scripts/backfill-offer-links.ts b/packages/core/src/migration-scripts/backfill-offer-links.ts
new file mode 100644
index 000000000..7801b2c2e
--- /dev/null
+++ b/packages/core/src/migration-scripts/backfill-offer-links.ts
@@ -0,0 +1,39 @@
+import { ExecArgs } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+type PgConnection = {
+ transaction: (
+ work: (trx: { raw: (sql: string) => Promise<unknown> }) => Promise<void>
+ ) => Promise<void>
+}
+
+const LINK_TABLES = [
+ { table: "offer_seller", column: "seller_id" },
+ { table: "offer_product", column: "product_id" },
+] as const
+
+// `offer_seller` and `offer_product` used to be read-only links resolved from
+// the offer's own columns. Offers created before they became link tables have
+// no rows there, so this seeds them. Runs after `db:migrate` syncs the links.
+export default async function backfillOfferLinks({ container }: ExecArgs) {
+ const knex = container.resolve<PgConnection>(
+ ContainerRegistrationKeys.PG_CONNECTION
+ )
+
+ await knex.transaction(async (trx) => {
+ for (const { table, column } of LINK_TABLES) {
+ await trx.raw(
+ `INSERT INTO "${table}" (id, offer_id, "${column}", created_at, updated_at)
+ SELECT 'link_' || replace(gen_random_uuid()::text, '-', ''),
+ o.id, o."${column}", now(), now()
+ FROM "offer" o
+ WHERE o.deleted_at IS NULL
+ AND o."${column}" IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM "${table}" l
+ WHERE l.offer_id = o.id AND l."${column}" = o."${column}"
+ )`
+ )
+ }
+ })
+}
diff --git a/packages/core/src/utils/index-schema.ts b/packages/core/src/utils/index-schema.ts
new file mode 100644
index 000000000..4e62aeab7
--- /dev/null
+++ b/packages/core/src/utils/index-schema.ts
@@ -0,0 +1,70 @@
+import { Modules } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+const listeners = (module: string, entity: string) =>
+ `@Listeners(values: [${["created", "updated", "deleted", "restored"]
+ .map((action) => `"${module}.${entity}.${action}"`)
+ .join(", ")}])`
+
+// The index module replaces its default schema with the `schema` option, so the
+// Medusa product types are repeated here (@medusajs/index keeps them private)
+// with the Mercur entities added. Offer -> Seller and Offer -> Product resolve
+// through the `offer_seller` / `offer_product` link tables.
+export const mercurIndexSchema = `
+ type Product ${listeners(Modules.PRODUCT, "product")} {
+ id: ID
+ title: String
+ handle: String
+ status: String
+ type_id: String
+ collection_id: String
+ is_giftcard: Boolean
+ external_id: String
+ created_at: DateTime
+ updated_at: DateTime
+
+ variants: [ProductVariant]
+ sales_channels: [SalesChannel]
+ }
+
+ type ProductVariant ${listeners(Modules.PRODUCT, "product-variant")} {
+ id: ID
+ product_id: String
+ sku: String
+
+ prices: [Price]
+ }
+
+ type Price ${listeners(Modules.PRICING, "price")} {
+ id: ID
+ amount: Float
+ currency_code: String
+ price_list_id: String
+ }
+
+ type SalesChannel ${listeners(Modules.SALES_CHANNEL, "sales-channel")} {
+ id: ID
+ is_disabled: Boolean
+ }
+
+ type Offer ${listeners(MercurModules.OFFER, "offer")} {
+ id: ID
+ seller_id: String
+ product_id: String
+ variant_id: String
+ sku: String
+ condition_id: String
+ created_at: DateTime
+ updated_at: DateTime
+
+ seller: Seller
+ product: Product
+ }
+
+ type Seller ${listeners(MercurModules.SELLER, "seller")} {
+ id: ID
+ status: String
+ closed_from: DateTime
+ closed_to: DateTime
+ }
+`
diff --git a/packages/core/src/with-mercur.ts b/packages/core/src/with-mercur.ts
index 55cd64651..68c8d52ac 100644
--- a/packages/core/src/with-mercur.ts
+++ b/packages/core/src/with-mercur.ts
@@ -8,6 +8,7 @@ import {
} from '@medusajs/framework/utils'
import { assertPatchesDisabled } from "./patches"
import { disableMedusaMiddlewares } from "./utils/disable-medusa-middlewares"
+import { mercurIndexSchema } from "./utils/index-schema"
type HttpConfig = NonNullable<NonNullable<InputConfigWithArrayModules["projectConfig"]>["http"]>
@@ -81,7 +82,12 @@ export function withMercur(config: MercurInputConfig = {}): InputConfigWithArray
// entry wins, so any registration (or `disable`) in the project overrides them.
const modules = [
...(featureFlags.index_engine
- ? [{ resolve: MODULE_PACKAGE_NAMES[Modules.INDEX] }]
+ ? [
+ {
+ resolve: MODULE_PACKAGE_NAMES[Modules.INDEX],
+ options: { schema: mercurIndexSchema },
+ },
+ ]
: []),
...(featureFlags.caching ? [cachingModule] : []),
...(config.modules ?? []),
diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.ts
index 658a68b23..7b29008ed 100644
--- a/packages/core/src/workflows/offer/workflows/create-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts
@@ -218,6 +218,27 @@ export const createOffersWorkflow: ReturnWorkflow<
const offers = createOffersStep(stripped)
+ const offerOwnershipLinks = transform({ offers }, ({ offers }) => {
+ const links: LinkDefinition[] = []
+ for (const offer of offers) {
+ links.push({
+ [MercurModules.OFFER]: { offer_id: offer.id },
+ [MercurModules.SELLER]: { seller_id: offer.seller_id },
+ })
+ if (offer.product_id) {
+ links.push({
+ [MercurModules.OFFER]: { offer_id: offer.id },
+ [Modules.PRODUCT]: { product_id: offer.product_id },
+ })
+ }
+ }
+ return links
+ })
+
+ createRemoteLinkStep(offerOwnershipLinks).config({
+ name: "create-offer-ownership-links",
+ })
+
// Link each offer's product to the offer's shipping profile. Medusa's
// cart-refresh keeps a shipping method only when its option's profile
// matches a profile on the cart's products (`item.variant.product
diff --git a/packages/core/src/workflows/offer/workflows/delete-offers.ts b/packages/core/src/workflows/offer/workflows/delete-offers.ts
index 1679b13c3..b5475b6d2 100644
--- a/packages/core/src/workflows/offer/workflows/delete-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/delete-offers.ts
@@ -6,9 +6,14 @@ import {
type Hook,
type ReturnWorkflow,
} from "@medusajs/framework/workflows-sdk"
-import { AdditionalData } from "@medusajs/framework/types"
-import { emitEventStep, useQueryGraphStep } from "@medusajs/medusa/core-flows"
-import { OfferDTO } from "@mercurjs/types"
+import { AdditionalData, LinkDefinition } from "@medusajs/framework/types"
+import {
+ dismissRemoteLinkStep,
+ emitEventStep,
+ useQueryGraphStep,
+} from "@medusajs/medusa/core-flows"
+import { Modules } from "@medusajs/framework/utils"
+import { MercurModules, OfferDTO } from "@mercurjs/types"
import { deleteOffersStep } from "../steps"
import { OfferWorkflowEvents } from "../../events"
@@ -45,6 +50,27 @@ export const deleteOffersWorkflow: ReturnWorkflow<
deleteOffersStep({ ids: input.ids })
+ const ownershipLinks = transform({ offers }, ({ offers }) => {
+ const links: LinkDefinition[] = []
+ for (const offer of offers) {
+ links.push({
+ [MercurModules.OFFER]: { offer_id: offer.id },
+ [MercurModules.SELLER]: { seller_id: offer.seller_id },
+ })
+ if (offer.product_id) {
+ links.push({
+ [MercurModules.OFFER]: { offer_id: offer.id },
+ [Modules.PRODUCT]: { product_id: offer.product_id },
+ })
+ }
+ }
+ return links
+ })
+
+ dismissRemoteLinkStep(ownershipLinks).config({
+ name: "dismiss-offer-ownership-links",
+ })
+
const eventData = transform({ offers }, ({ offers }) =>
offers.map((o) => ({ id: o.id, product_id: o.product_id })),
)