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(offer): add operator-defined offer conditions (#1645)

Viktor Holik97932be6de5b
diff --git a/integration-tests/http/offer/admin/offer-conditions.spec.ts b/integration-tests/http/offer/admin/offer-conditions.spec.ts
new file mode 100644
index 000000000..13e79978e
--- /dev/null
+++ b/integration-tests/http/offer/admin/offer-conditions.spec.ts
@@ -0,0 +1,196 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createShippingProfile } from "../../../helpers/create-shipping-profile"
+import { createVendorProduct } from "../../../helpers/create-product"
+import {
+ adminHeaders,
+ createAdminUser,
+} from "../../../helpers/create-admin-user"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api, dbConnection }) => {
+ describe("Admin - Offer Conditions", () => {
+ let appContainer: MedusaContainer
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ await createAdminUser(dbConnection, adminHeaders, appContainer)
+ })
+
+ const createCondition = async (
+ body: Record<string, unknown>
+ ) => {
+ const response = await api.post(
+ "/admin/offer-conditions",
+ body,
+ adminHeaders
+ )
+ expect(response.status).toEqual(201)
+ return response.data.offer_condition
+ }
+
+ it("creates, retrieves, updates and deletes an offer condition", async () => {
+ const created = await createCondition({
+ code: "refurbished",
+ label: "Refurbished",
+ rank: 2,
+ })
+
+ expect(created).toEqual(
+ expect.objectContaining({
+ id: expect.stringMatching(/^ofcond_/),
+ code: "refurbished",
+ label: "Refurbished",
+ is_active: true,
+ rank: 2,
+ })
+ )
+
+ const retrieved = await api.get(
+ `/admin/offer-conditions/${created.id}`,
+ adminHeaders
+ )
+ expect(retrieved.status).toEqual(200)
+ expect(retrieved.data.offer_condition.id).toEqual(created.id)
+
+ const updated = await api.post(
+ `/admin/offer-conditions/${created.id}`,
+ { label: "Renewed", is_active: false },
+ adminHeaders
+ )
+ expect(updated.status).toEqual(200)
+ expect(updated.data.offer_condition).toEqual(
+ expect.objectContaining({
+ code: "refurbished",
+ label: "Renewed",
+ is_active: false,
+ })
+ )
+
+ const deleted = await api.delete(
+ `/admin/offer-conditions/${created.id}`,
+ adminHeaders
+ )
+ expect(deleted.status).toEqual(200)
+ expect(deleted.data).toEqual({
+ id: created.id,
+ object: "offer_condition",
+ deleted: true,
+ })
+
+ const missing = await api
+ .get(`/admin/offer-conditions/${created.id}`, adminHeaders)
+ .catch((e: any) => e.response)
+ expect(missing.status).toEqual(404)
+ })
+
+ it("lists conditions ordered by rank and filters by is_active", async () => {
+ await createCondition({ code: "used_good", label: "Used - Good", rank: 5 })
+ await createCondition({
+ code: "used_like_new",
+ label: "Used - Like New",
+ rank: 1,
+ })
+ await createCondition({
+ code: "collectible",
+ label: "Collectible",
+ rank: 3,
+ is_active: false,
+ })
+
+ const all = await api.get("/admin/offer-conditions", adminHeaders)
+ expect(all.status).toEqual(200)
+ const codes = all.data.offer_conditions.map((c: any) => c.code)
+ expect(codes.indexOf("used_like_new")).toBeLessThan(
+ codes.indexOf("collectible")
+ )
+ expect(codes.indexOf("collectible")).toBeLessThan(
+ codes.indexOf("used_good")
+ )
+
+ const active = await api.get(
+ "/admin/offer-conditions?is_active=false",
+ adminHeaders
+ )
+ expect(active.data.offer_conditions.map((c: any) => c.code)).toEqual([
+ "collectible",
+ ])
+ })
+
+ it("rejects a duplicate code", async () => {
+ await createCondition({ code: "open_box", label: "Open box" })
+
+ const duplicate = await api
+ .post(
+ "/admin/offer-conditions",
+ { code: "open_box", label: "Open box again" },
+ adminHeaders
+ )
+ .catch((e: any) => e.response)
+
+ expect(duplicate.status).toEqual(400)
+ })
+
+ it("refuses to delete a condition that offers are listed under", async () => {
+ const condition = await createCondition({
+ code: "used_acceptable",
+ label: "Used - Acceptable",
+ })
+
+ const { headers } = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Condition Seller",
+ })
+ const product = await createVendorProduct(api, headers, {
+ title: "Condition Product",
+ variants: [{ title: "Default" }],
+ })
+ const profile = await createShippingProfile(appContainer, {
+ name: "Condition Profile",
+ })
+
+ const offer = await api.post(
+ "/vendor/offers",
+ {
+ sku: "COND-SKU-1",
+ variant_id: product.variants[0].id,
+ shipping_profile_id: profile.id,
+ inventory_items: [{ required_quantity: 1 }],
+ prices: [{ amount: 1000, currency_code: "usd" }],
+ condition_id: condition.id,
+ },
+ headers
+ )
+ expect(offer.status).toEqual(201)
+
+ const deleted = await api
+ .delete(`/admin/offer-conditions/${condition.id}`, adminHeaders)
+ .catch((e: any) => e.response)
+ expect(deleted.status).toEqual(400)
+ expect(deleted.data.message).toContain("cannot be deleted")
+
+ const listed = await api.get(
+ `/admin/offers?condition_id=${condition.id}`,
+ adminHeaders
+ )
+ expect(listed.data.offers).toHaveLength(1)
+ expect(listed.data.offers[0]).toEqual(
+ expect.objectContaining({
+ id: offer.data.offer.id,
+ condition_id: condition.id,
+ condition: expect.objectContaining({
+ code: "used_acceptable",
+ label: "Used - Acceptable",
+ }),
+ })
+ )
+ })
+ })
+ },
+})
diff --git a/integration-tests/http/offer/vendor/offer-conditions.spec.ts b/integration-tests/http/offer/vendor/offer-conditions.spec.ts
new file mode 100644
index 000000000..2e0e2550c
--- /dev/null
+++ b/integration-tests/http/offer/vendor/offer-conditions.spec.ts
@@ -0,0 +1,171 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import { MedusaContainer } from "@medusajs/framework/types"
+import { MercurModules } from "@mercurjs/types"
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createShippingProfile } from "../../../helpers/create-shipping-profile"
+import { createVendorProduct } from "../../../helpers/create-product"
+
+jest.setTimeout(60000)
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Vendor - Offer Conditions", () => {
+ let appContainer: MedusaContainer
+ let headers: any
+ let activeCondition: any
+ let inactiveCondition: any
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ const result = await createSellerUser(appContainer, {
+ email: "[email protected]",
+ name: "Conditions Seller",
+ })
+ headers = result.headers
+
+ const service = appContainer.resolve(MercurModules.OFFER)
+ ;[activeCondition, inactiveCondition] =
+ await service.createOfferConditions([
+ { code: "used_like_new", label: "Used - Like New", rank: 1 },
+ {
+ code: "retired",
+ label: "Retired",
+ rank: 2,
+ is_active: false,
+ },
+ ])
+ })
+
+ const seedOfferDeps = async () => {
+ const tag = `${Date.now()}${Math.floor(Math.random() * 1000)}`
+ const product = await createVendorProduct(api, headers, {
+ title: `Product ${tag}`,
+ variants: [{ title: "Default" }],
+ })
+ const profile = await createShippingProfile(appContainer, {
+ name: `Profile ${tag}`,
+ })
+ return {
+ sku: `SKU-${tag}`,
+ variant_id: product.variants[0].id,
+ shipping_profile_id: profile.id,
+ inventory_items: [{ required_quantity: 1 }],
+ prices: [{ amount: 1500, currency_code: "usd" }],
+ }
+ }
+
+ it("lists only active conditions", async () => {
+ const response = await api.get("/vendor/offer-conditions", headers)
+
+ expect(response.status).toEqual(200)
+ const codes = response.data.offer_conditions.map((c: any) => c.code)
+ expect(codes).toContain("used_like_new")
+ expect(codes).not.toContain("retired")
+ expect(response.data.offer_conditions[0]).not.toHaveProperty(
+ "is_active"
+ )
+ })
+
+ it("retrieves an active condition and hides an inactive one", async () => {
+ const active = await api.get(
+ `/vendor/offer-conditions/${activeCondition.id}`,
+ headers
+ )
+ expect(active.status).toEqual(200)
+ expect(active.data.offer_condition.code).toEqual("used_like_new")
+
+ const inactive = await api
+ .get(`/vendor/offer-conditions/${inactiveCondition.id}`, headers)
+ .catch((e: any) => e.response)
+ expect(inactive.status).toEqual(404)
+ })
+
+ it("creates an offer under an active condition and exposes it on the offer", async () => {
+ const deps = await seedOfferDeps()
+
+ const response = await api.post(
+ "/vendor/offers",
+ { ...deps, condition_id: activeCondition.id },
+ headers
+ )
+
+ expect(response.status).toEqual(201)
+ expect(response.data.offer).toEqual(
+ expect.objectContaining({
+ condition_id: activeCondition.id,
+ condition: expect.objectContaining({
+ id: activeCondition.id,
+ code: "used_like_new",
+ label: "Used - Like New",
+ }),
+ })
+ )
+
+ const listed = await api.get(
+ `/vendor/offers?condition_id=${activeCondition.id}`,
+ headers
+ )
+ expect(listed.data.offers.map((o: any) => o.id)).toEqual([
+ response.data.offer.id,
+ ])
+ })
+
+ it("rejects an inactive or unknown condition on create", async () => {
+ const deps = await seedOfferDeps()
+
+ const inactive = await api
+ .post(
+ "/vendor/offers",
+ { ...deps, condition_id: inactiveCondition.id },
+ headers
+ )
+ .catch((e: any) => e.response)
+ expect(inactive.status).toEqual(400)
+ expect(inactive.data.message).toContain("not active")
+
+ const unknown = await api
+ .post(
+ "/vendor/offers",
+ { ...deps, condition_id: "ofcond_does_not_exist" },
+ headers
+ )
+ .catch((e: any) => e.response)
+ expect(unknown.status).toEqual(404)
+ })
+
+ it("updates and clears the condition on an existing offer", async () => {
+ const deps = await seedOfferDeps()
+ const created = await api.post("/vendor/offers", deps, headers)
+ expect(created.data.offer.condition_id).toBeNull()
+
+ const assigned = await api.post(
+ `/vendor/offers/${created.data.offer.id}`,
+ { condition_id: activeCondition.id },
+ headers
+ )
+ expect(assigned.status).toEqual(200)
+ expect(assigned.data.offer.condition_id).toEqual(activeCondition.id)
+
+ const rejected = await api
+ .post(
+ `/vendor/offers/${created.data.offer.id}`,
+ { condition_id: inactiveCondition.id },
+ headers
+ )
+ .catch((e: any) => e.response)
+ expect(rejected.status).toEqual(400)
+
+ const cleared = await api.post(
+ `/vendor/offers/${created.data.offer.id}`,
+ { condition_id: null },
+ headers
+ )
+ expect(cleared.status).toEqual(200)
+ expect(cleared.data.offer.condition_id).toBeNull()
+ })
+ })
+ },
+})
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index 86df9a9f6..0deddbda8 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -90,6 +90,8 @@
"/admin/members": "typeof import(\"@mercurjs/core/api/admin/members/route\")",
"/admin/notifications": "typeof import(\"@medusajs/medusa/api/admin/notifications/route\")",
"/admin/notifications/:id": "typeof import(\"@medusajs/medusa/api/admin/notifications/[id]/route\")",
+ "/admin/offer-conditions": "typeof import(\"@mercurjs/core/api/admin/offer-conditions/route\")",
+ "/admin/offer-conditions/:id": "typeof import(\"@mercurjs/core/api/admin/offer-conditions/[id]/route\")",
"/admin/offers": "typeof import(\"@mercurjs/core/api/admin/offers/route\")",
"/admin/offers/:id": "typeof import(\"@mercurjs/core/api/admin/offers/[id]/route\")",
"/admin/offers/batch": "typeof import(\"@mercurjs/core/api/admin/offers/batch/route\")",
@@ -439,6 +441,8 @@
"/vendor/inventory-items/location-levels/batch": "typeof import(\"@mercurjs/core/api/vendor/inventory-items/location-levels/batch/route\")",
"/vendor/members/invites/accept": "typeof import(\"@mercurjs/core/api/vendor/members/invites/accept/route\")",
"/vendor/members/me": "typeof import(\"@mercurjs/core/api/vendor/members/me/route\")",
+ "/vendor/offer-conditions": "typeof import(\"@mercurjs/core/api/vendor/offer-conditions/route\")",
+ "/vendor/offer-conditions/:id": "typeof import(\"@mercurjs/core/api/vendor/offer-conditions/[id]/route\")",
"/vendor/offers": "typeof import(\"@mercurjs/core/api/vendor/offers/route\")",
"/vendor/offers/:id": "typeof import(\"@mercurjs/core/api/vendor/offers/[id]/route\")",
"/vendor/offers/:id/inventory-items/batch": "typeof import(\"@mercurjs/core/api/vendor/offers/[id]/inventory-items/batch/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 8e68a3d46..2666d7eb9 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -509,6 +509,9 @@ export type Routes = {
subscribe: typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/subscribe/route");
};
};
+ offerConditions: typeof import("../src/api/admin/offer-conditions/route") & {
+ $id: typeof import("../src/api/admin/offer-conditions/[id]/route");
+ };
reviews: typeof import("../src/api/admin/reviews/route") & {
$id: typeof import("../src/api/admin/reviews/[id]/route") & {
respond: typeof import("../src/api/admin/reviews/[id]/respond/route");
@@ -931,6 +934,9 @@ export type Routes = {
};
stores: typeof import("../src/api/vendor/stores/route");
uploads: typeof import("../src/api/vendor/uploads/route");
+ offerConditions: typeof import("../src/api/vendor/offer-conditions/route") & {
+ $id: typeof import("../src/api/vendor/offer-conditions/[id]/route");
+ };
reviews: typeof import("../src/api/vendor/reviews/route") & {
$id: typeof import("../src/api/vendor/reviews/[id]/route");
};
diff --git a/packages/core/src/api/admin/middlewares.ts b/packages/core/src/api/admin/middlewares.ts
index 12f42857e..6764a072a 100644
--- a/packages/core/src/api/admin/middlewares.ts
+++ b/packages/core/src/api/admin/middlewares.ts
@@ -9,6 +9,7 @@ import { AdminGetOrderGroupParams } from "./order-groups/validators"
import { adminOrdersMiddlewares } from "./orders/middlewares"
import { adminCustomerGroupsMiddlewares } from "./customer-groups/middlewares"
import { adminOffersMiddlewares } from "./offers/middlewares"
+import { adminOfferConditionsMiddlewares } from "./offer-conditions/middlewares"
import { adminPayoutsMiddlewares } from "./payouts/middlewares"
import { adminSellersMiddlewares } from "./sellers/middlewares"
import { adminMembersMiddlewares } from "./members/middlewares"
@@ -52,6 +53,7 @@ export const adminMiddlewares: MiddlewareRoute[] = [
...adminOrdersMiddlewares,
...adminCustomerGroupsMiddlewares,
...adminOffersMiddlewares,
+ ...adminOfferConditionsMiddlewares,
...adminPayoutsMiddlewares,
...adminSellersMiddlewares,
...adminMembersMiddlewares,
diff --git a/packages/core/src/api/admin/offer-conditions/[id]/route.ts b/packages/core/src/api/admin/offer-conditions/[id]/route.ts
new file mode 100644
index 000000000..e172188a6
--- /dev/null
+++ b/packages/core/src/api/admin/offer-conditions/[id]/route.ts
@@ -0,0 +1,90 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+} from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+import {
+ deleteOfferConditionsWorkflow,
+ updateOfferConditionsWorkflow,
+} from "../../../../workflows/offer"
+import { AdminUpdateOfferConditionType } from "../validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminOfferConditionResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [offer_condition],
+ } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: { id: req.params.id },
+ })
+
+ if (!offer_condition) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer condition with id ${req.params.id} was not found`
+ )
+ }
+
+ res.json({ offer_condition })
+}
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminUpdateOfferConditionType>,
+ res: MedusaResponse<HttpTypes.AdminOfferConditionResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [existing],
+ } = await query.graph({
+ entity: "offer_condition",
+ fields: ["id"],
+ filters: { id: req.params.id },
+ })
+
+ if (!existing) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer condition with id ${req.params.id} was not found`
+ )
+ }
+
+ await updateOfferConditionsWorkflow(req.scope).run({
+ input: { offer_conditions: [{ id: req.params.id, ...req.validatedBody }] },
+ })
+
+ const {
+ data: [offer_condition],
+ } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: { id: req.params.id },
+ })
+
+ res.json({ offer_condition })
+}
+
+export const DELETE = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.AdminOfferConditionDeleteResponse>
+) => {
+ await deleteOfferConditionsWorkflow(req.scope).run({
+ input: { ids: [req.params.id] },
+ })
+
+ res.json({
+ id: req.params.id,
+ object: "offer_condition",
+ deleted: true,
+ })
+}
diff --git a/packages/core/src/api/admin/offer-conditions/middlewares.ts b/packages/core/src/api/admin/offer-conditions/middlewares.ts
new file mode 100644
index 000000000..16e13a055
--- /dev/null
+++ b/packages/core/src/api/admin/offer-conditions/middlewares.ts
@@ -0,0 +1,68 @@
+import { MiddlewareRoute } from "@medusajs/framework/http"
+import {
+ validateAndTransformBody,
+ validateAndTransformQuery,
+} from "@medusajs/framework"
+
+import { requirePermission } from "../../utils"
+import { adminOfferConditionQueryConfig } from "./query-config"
+import {
+ AdminCreateOfferCondition,
+ AdminGetOfferConditionParams,
+ AdminGetOfferConditionsParams,
+ AdminUpdateOfferCondition,
+} from "./validators"
+
+export const adminOfferConditionsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["GET"],
+ matcher: "/admin/offer-conditions",
+ middlewares: [
+ requirePermission("offers", "view"),
+ validateAndTransformQuery(
+ AdminGetOfferConditionsParams,
+ adminOfferConditionQueryConfig.list
+ ),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/offer-conditions",
+ middlewares: [
+ requirePermission("offers", "manage"),
+ validateAndTransformBody(AdminCreateOfferCondition),
+ validateAndTransformQuery(
+ AdminGetOfferConditionParams,
+ adminOfferConditionQueryConfig.retrieve
+ ),
+ ],
+ },
+ {
+ method: ["GET"],
+ matcher: "/admin/offer-conditions/:id",
+ middlewares: [
+ requirePermission("offers", "view"),
+ validateAndTransformQuery(
+ AdminGetOfferConditionParams,
+ adminOfferConditionQueryConfig.retrieve
+ ),
+ ],
+ },
+ {
+ method: ["POST"],
+ matcher: "/admin/offer-conditions/:id",
+ middlewares: [
+ requirePermission("offers", "manage"),
+ validateAndTransformBody(AdminUpdateOfferCondition),
+ validateAndTransformQuery(
+ AdminGetOfferConditionParams,
+ adminOfferConditionQueryConfig.retrieve
+ ),
+ ],
+ },
+ {
+ method: ["DELETE"],
+ matcher: "/admin/offer-conditions/:id",
+ middlewares: [requirePermission("offers", "manage")],
+ },
+]
diff --git a/packages/core/src/api/admin/offer-conditions/query-config.ts b/packages/core/src/api/admin/offer-conditions/query-config.ts
new file mode 100644
index 000000000..4afdf7ea3
--- /dev/null
+++ b/packages/core/src/api/admin/offer-conditions/query-config.ts
@@ -0,0 +1,22 @@
+export const defaultAdminOfferConditionFields = [
+ "id",
+ "code",
+ "label",
+ "is_active",
+ "rank",
+ "metadata",
+ "created_at",
+ "updated_at",
+ "deleted_at",
+]
+
+export const adminOfferConditionQueryConfig = {
+ list: {
+ defaults: defaultAdminOfferConditionFields,
+ isList: true,
+ },
+ retrieve: {
+ defaults: defaultAdminOfferConditionFields,
+ isList: false,
+ },
+}
diff --git a/packages/core/src/api/admin/offer-conditions/route.ts b/packages/core/src/api/admin/offer-conditions/route.ts
new file mode 100644
index 000000000..28c34e656
--- /dev/null
+++ b/packages/core/src/api/admin/offer-conditions/route.ts
@@ -0,0 +1,54 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+import { createOfferConditionsWorkflow } from "../../../workflows/offer"
+import {
+ AdminCreateOfferConditionType,
+ AdminGetOfferConditionsParamsType,
+} from "./validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<AdminGetOfferConditionsParamsType>,
+ res: MedusaResponse<HttpTypes.AdminOfferConditionListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: offer_conditions, metadata } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ offer_conditions,
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
+
+export const POST = async (
+ req: AuthenticatedMedusaRequest<AdminCreateOfferConditionType>,
+ res: MedusaResponse<HttpTypes.AdminOfferConditionResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { result } = await createOfferConditionsWorkflow(req.scope).run({
+ input: { offer_conditions: [req.validatedBody] },
+ })
+
+ const {
+ data: [offer_condition],
+ } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: { id: result[0].id },
+ })
+
+ res.status(201).json({ offer_condition })
+}
diff --git a/packages/core/src/api/admin/offer-conditions/validators.ts b/packages/core/src/api/admin/offer-conditions/validators.ts
new file mode 100644
index 000000000..c7c342ad9
--- /dev/null
+++ b/packages/core/src/api/admin/offer-conditions/validators.ts
@@ -0,0 +1,56 @@
+import { z } from "zod"
+import {
+ createFindParams,
+ createOperatorMap,
+ createSelectParams,
+} from "@medusajs/medusa/api/utils/validators"
+import { booleanString } from "@medusajs/medusa/api/utils/common-validators/common"
+
+export type AdminGetOfferConditionParamsType = z.infer<
+ typeof AdminGetOfferConditionParams
+>
+export const AdminGetOfferConditionParams = createSelectParams()
+
+export type AdminGetOfferConditionsParamsType = z.infer<
+ typeof AdminGetOfferConditionsParams
+>
+export const AdminGetOfferConditionsParams = createFindParams({
+ offset: 0,
+ limit: 50,
+ order: "rank",
+}).merge(
+ z.object({
+ q: z.string().optional(),
+ id: z.union([z.string(), z.array(z.string())]).optional(),
+ code: z.union([z.string(), z.array(z.string())]).optional(),
+ is_active: booleanString().optional(),
+ created_at: createOperatorMap().optional(),
+ updated_at: createOperatorMap().optional(),
+ })
+)
+
+export type AdminCreateOfferConditionType = z.infer<
+ typeof AdminCreateOfferCondition
+>
+export const AdminCreateOfferCondition = z
+ .object({
+ code: z.string().min(1),
+ label: z.string().min(1),
+ is_active: z.boolean().optional(),
+ rank: z.number().int().min(0).optional(),
+ metadata: z.record(z.string(), z.unknown()).nullish(),
+ })
+ .strict()
+
+export type AdminUpdateOfferConditionType = z.infer<
+ typeof AdminUpdateOfferCondition
+>
+export const AdminUpdateOfferCondition = z
+ .object({
+ code: z.string().min(1).optional(),
+ label: z.string().min(1).optional(),
+ is_active: z.boolean().optional(),
+ rank: z.number().int().min(0).optional(),
+ metadata: z.record(z.string(), z.unknown()).nullish(),
+ })
+ .strict()
diff --git a/packages/core/src/api/admin/offers/batch/route.ts b/packages/core/src/api/admin/offers/batch/route.ts
index 849af69b7..14fe33bff 100644
--- a/packages/core/src/api/admin/offers/batch/route.ts
+++ b/packages/core/src/api/admin/offers/batch/route.ts
@@ -40,6 +40,7 @@ export const POST = async (
ean: o.ean ?? null,
upc: o.upc ?? null,
leadtime_to_ship: o.leadtime_to_ship ?? null,
+ condition_id: o.condition_id ?? null,
metadata: o.metadata ?? null,
}))
diff --git a/packages/core/src/api/admin/offers/query-config.ts b/packages/core/src/api/admin/offers/query-config.ts
index e60eeeda6..090741611 100644
--- a/packages/core/src/api/admin/offers/query-config.ts
+++ b/packages/core/src/api/admin/offers/query-config.ts
@@ -8,12 +8,16 @@ export const defaultAdminOfferFields = [
"ean",
"upc",
"leadtime_to_ship",
+ "condition_id",
"created_by",
"variant_count",
"metadata",
"created_at",
"updated_at",
"deleted_at",
+ "condition.id",
+ "condition.code",
+ "condition.label",
"seller.id",
"seller.name",
"seller.handle",
diff --git a/packages/core/src/api/admin/offers/validators.ts b/packages/core/src/api/admin/offers/validators.ts
index 7e99a88c0..399b18b82 100644
--- a/packages/core/src/api/admin/offers/validators.ts
+++ b/packages/core/src/api/admin/offers/validators.ts
@@ -27,6 +27,7 @@ export const AdminGetOffersParams = createFindParams({
sku: z.union([z.string(), z.array(z.string())]).optional(),
ean: z.union([z.string(), z.array(z.string())]).optional(),
upc: z.union([z.string(), z.array(z.string())]).optional(),
+ condition_id: z.union([z.string(), z.array(z.string())]).optional(),
group_by_seller: booleanString().optional(),
status: z.union([z.string(), z.array(z.string())]).optional(),
category_id: z.union([z.string(), z.array(z.string())]).optional(),
@@ -74,6 +75,7 @@ const AdminCreateOffersBatchItem = z
ean: z.string().min(1).nullish(),
upc: z.string().min(1).nullish(),
leadtime_to_ship: z.number().int().min(0).nullish(),
+ condition_id: z.string().min(1).nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
})
.strict()
diff --git a/packages/core/src/api/store/offers/query-config.ts b/packages/core/src/api/store/offers/query-config.ts
index 8683652a4..d5c7872c9 100644
--- a/packages/core/src/api/store/offers/query-config.ts
+++ b/packages/core/src/api/store/offers/query-config.ts
@@ -8,9 +8,13 @@ export const defaultStoreOfferFields = [
"ean",
"upc",
"leadtime_to_ship",
+ "condition_id",
"metadata",
"created_at",
"updated_at",
+ "condition.id",
+ "condition.code",
+ "condition.label",
"seller.id",
"seller.name",
"seller.handle",
diff --git a/packages/core/src/api/store/offers/validators.ts b/packages/core/src/api/store/offers/validators.ts
index 84cc51f35..edb495d7d 100644
--- a/packages/core/src/api/store/offers/validators.ts
+++ b/packages/core/src/api/store/offers/validators.ts
@@ -19,6 +19,7 @@ const StoreOfferFilterFields = z.object({
variant_id: z.union([z.string(), z.array(z.string())]).optional(),
seller_id: z.union([z.string(), z.array(z.string())]).optional(),
sku: z.union([z.string(), z.array(z.string())]).optional(),
+ condition_id: z.union([z.string(), z.array(z.string())]).optional(),
created_at: createOperatorMap().optional(),
updated_at: createOperatorMap().optional(),
})
diff --git a/packages/core/src/api/vendor/middlewares.ts b/packages/core/src/api/vendor/middlewares.ts
index 716e0c2eb..b3798a232 100644
--- a/packages/core/src/api/vendor/middlewares.ts
+++ b/packages/core/src/api/vendor/middlewares.ts
@@ -16,6 +16,7 @@ import { vendorFulfillmentProvidersMiddlewares } from "./fulfillment-providers/m
import { vendorFulfillmentSetsMiddlewares } from "./fulfillment-sets/middlewares"
import { vendorInventoryItemsMiddlewares } from "./inventory-items/middlewares"
import { vendorOffersMiddlewares } from "./offers/middlewares"
+import { vendorOfferConditionsMiddlewares } from "./offer-conditions/middlewares"
import { vendorOrderEditsMiddlewares } from "./order-edits/middlewares"
import { vendorOrdersMiddlewares } from "./orders/middlewares"
import { vendorPaymentsMiddlewares } from "./payments/middlewares"
@@ -124,6 +125,7 @@ export const vendorMiddlewares: MiddlewareRoute[] = [
...vendorFulfillmentSetsMiddlewares,
...vendorInventoryItemsMiddlewares,
...vendorOffersMiddlewares,
+ ...vendorOfferConditionsMiddlewares,
...vendorOrderEditsMiddlewares,
...vendorOrdersMiddlewares,
...vendorPaymentsMiddlewares,
diff --git a/packages/core/src/api/vendor/offer-conditions/[id]/route.ts b/packages/core/src/api/vendor/offer-conditions/[id]/route.ts
new file mode 100644
index 000000000..646d0dff7
--- /dev/null
+++ b/packages/core/src/api/vendor/offer-conditions/[id]/route.ts
@@ -0,0 +1,33 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import {
+ ContainerRegistrationKeys,
+ MedusaError,
+} from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest,
+ res: MedusaResponse<HttpTypes.VendorOfferConditionResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const {
+ data: [offer_condition],
+ } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: { id: req.params.id, is_active: true },
+ })
+
+ if (!offer_condition) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer condition with id ${req.params.id} was not found`
+ )
+ }
+
+ res.json({ offer_condition })
+}
diff --git a/packages/core/src/api/vendor/offer-conditions/middlewares.ts b/packages/core/src/api/vendor/offer-conditions/middlewares.ts
new file mode 100644
index 000000000..87a444c24
--- /dev/null
+++ b/packages/core/src/api/vendor/offer-conditions/middlewares.ts
@@ -0,0 +1,49 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaNextFunction,
+ MedusaResponse,
+ MiddlewareRoute,
+} from "@medusajs/framework/http"
+import { validateAndTransformQuery } from "@medusajs/framework"
+
+import { requirePermission } from "../../utils"
+import { vendorOfferConditionQueryConfig } from "./query-config"
+import {
+ VendorGetOfferConditionParams,
+ VendorGetOfferConditionsParams,
+} from "./validators"
+
+const applyActiveConditionFilter = (
+ req: AuthenticatedMedusaRequest,
+ _res: MedusaResponse,
+ next: MedusaNextFunction
+) => {
+ req.filterableFields.is_active = true
+ next()
+}
+
+export const vendorOfferConditionsMiddlewares: MiddlewareRoute[] = [
+ {
+ method: ["GET"],
+ matcher: "/vendor/offer-conditions",
+ middlewares: [
+ requirePermission("offers", "view"),
+ validateAndTransformQuery(
+ VendorGetOfferConditionsParams,
+ vendorOfferConditionQueryConfig.list
+ ),
+ applyActiveConditionFilter,
+ ],
+ },
+ {
+ method: ["GET"],
+ matcher: "/vendor/offer-conditions/:id",
+ middlewares: [
+ requirePermission("offers", "view"),
+ validateAndTransformQuery(
+ VendorGetOfferConditionParams,
+ vendorOfferConditionQueryConfig.retrieve
+ ),
+ ],
+ },
+]
diff --git a/packages/core/src/api/vendor/offer-conditions/query-config.ts b/packages/core/src/api/vendor/offer-conditions/query-config.ts
new file mode 100644
index 000000000..aa39d0aaa
--- /dev/null
+++ b/packages/core/src/api/vendor/offer-conditions/query-config.ts
@@ -0,0 +1,20 @@
+export const defaultVendorOfferConditionFields = [
+ "id",
+ "code",
+ "label",
+ "rank",
+ "metadata",
+ "created_at",
+ "updated_at",
+]
+
+export const vendorOfferConditionQueryConfig = {
+ list: {
+ defaults: defaultVendorOfferConditionFields,
+ isList: true,
+ },
+ retrieve: {
+ defaults: defaultVendorOfferConditionFields,
+ isList: false,
+ },
+}
diff --git a/packages/core/src/api/vendor/offer-conditions/route.ts b/packages/core/src/api/vendor/offer-conditions/route.ts
new file mode 100644
index 000000000..eb30d6a1b
--- /dev/null
+++ b/packages/core/src/api/vendor/offer-conditions/route.ts
@@ -0,0 +1,29 @@
+import {
+ AuthenticatedMedusaRequest,
+ MedusaResponse,
+} from "@medusajs/framework/http"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { HttpTypes } from "@mercurjs/types"
+
+import { VendorGetOfferConditionsParamsType } from "./validators"
+
+export const GET = async (
+ req: AuthenticatedMedusaRequest<VendorGetOfferConditionsParamsType>,
+ res: MedusaResponse<HttpTypes.VendorOfferConditionListResponse>
+) => {
+ const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const { data: offer_conditions, metadata } = await query.graph({
+ entity: "offer_condition",
+ fields: req.queryConfig.fields,
+ filters: req.filterableFields,
+ pagination: req.queryConfig.pagination,
+ })
+
+ res.json({
+ offer_conditions,
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ })
+}
diff --git a/packages/core/src/api/vendor/offer-conditions/validators.ts b/packages/core/src/api/vendor/offer-conditions/validators.ts
new file mode 100644
index 000000000..ca340f652
--- /dev/null
+++ b/packages/core/src/api/vendor/offer-conditions/validators.ts
@@ -0,0 +1,25 @@
+import { z } from "zod"
+import {
+ createFindParams,
+ createSelectParams,
+} from "@medusajs/medusa/api/utils/validators"
+
+export type VendorGetOfferConditionParamsType = z.infer<
+ typeof VendorGetOfferConditionParams
+>
+export const VendorGetOfferConditionParams = createSelectParams()
+
+export type VendorGetOfferConditionsParamsType = z.infer<
+ typeof VendorGetOfferConditionsParams
+>
+export const VendorGetOfferConditionsParams = createFindParams({
+ offset: 0,
+ limit: 50,
+ order: "rank",
+}).merge(
+ z.object({
+ q: z.string().optional(),
+ id: z.union([z.string(), z.array(z.string())]).optional(),
+ code: z.union([z.string(), z.array(z.string())]).optional(),
+ })
+)
diff --git a/packages/core/src/api/vendor/offers/query-config.ts b/packages/core/src/api/vendor/offers/query-config.ts
index 2e063c236..a2ee30338 100644
--- a/packages/core/src/api/vendor/offers/query-config.ts
+++ b/packages/core/src/api/vendor/offers/query-config.ts
@@ -10,11 +10,15 @@ export const defaultVendorOfferFields = [
"manage_inventory",
"allow_backorder",
"leadtime_to_ship",
+ "condition_id",
"created_by",
"metadata",
"created_at",
"updated_at",
"deleted_at",
+ "condition.id",
+ "condition.code",
+ "condition.label",
"seller.id",
"seller.name",
"seller.handle",
diff --git a/packages/core/src/api/vendor/offers/validators.ts b/packages/core/src/api/vendor/offers/validators.ts
index db638fe00..eaec949c6 100644
--- a/packages/core/src/api/vendor/offers/validators.ts
+++ b/packages/core/src/api/vendor/offers/validators.ts
@@ -21,6 +21,7 @@ export const VendorGetOffersParamsFields = z
sku: z.union([z.string(), z.array(z.string())]).optional(),
ean: z.union([z.string(), z.array(z.string())]).optional(),
upc: z.union([z.string(), z.array(z.string())]).optional(),
+ condition_id: z.union([z.string(), z.array(z.string())]).optional(),
created_at: createOperatorMap().optional(),
updated_at: createOperatorMap().optional(),
})
@@ -81,6 +82,7 @@ const CreateOffer = z
manage_inventory: z.boolean().optional(),
allow_backorder: z.boolean().optional(),
leadtime_to_ship: z.number().int().min(0).nullish(),
+ condition_id: z.string().min(1).nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
})
.strict()
@@ -95,6 +97,7 @@ const UpdateOffer = z
manage_inventory: z.boolean().optional(),
allow_backorder: z.boolean().optional(),
leadtime_to_ship: z.number().int().min(0).nullish(),
+ condition_id: z.string().min(1).nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
prices: z.array(VendorOfferUpsertPrice).optional(),
})
@@ -145,6 +148,7 @@ const VendorCreateOffersBatchItem = z
manage_inventory: z.boolean().optional(),
allow_backorder: z.boolean().optional(),
leadtime_to_ship: z.number().int().min(0).nullish(),
+ condition_id: z.string().min(1).nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
})
.strict()
diff --git a/packages/core/src/modules/offer/migrations/Migration20261007000000.ts b/packages/core/src/modules/offer/migrations/Migration20261007000000.ts
new file mode 100644
index 000000000..1df0b1ff4
--- /dev/null
+++ b/packages/core/src/modules/offer/migrations/Migration20261007000000.ts
@@ -0,0 +1,38 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261007000000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(
+ `create table if not exists "offer_condition" ("id" text not null, "code" text not null, "label" text not null, "is_active" boolean not null default true, "rank" integer not null default 0, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "offer_condition_pkey" primary key ("id"));`
+ )
+ this.addSql(
+ `CREATE UNIQUE INDEX IF NOT EXISTS "IDX_offer_condition_code_unique" ON "offer_condition" ("code") WHERE deleted_at IS NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_offer_condition_deleted_at" ON "offer_condition" ("deleted_at") WHERE deleted_at IS NULL;`
+ )
+
+ this.addSql(
+ `ALTER TABLE "offer" ADD COLUMN IF NOT EXISTS "condition_id" text NULL;`
+ )
+ this.addSql(
+ `CREATE INDEX IF NOT EXISTS "IDX_offer_condition_id" ON "offer" ("condition_id") WHERE deleted_at IS NULL AND condition_id IS NOT NULL;`
+ )
+ this.addSql(
+ `alter table if exists "offer" add constraint "offer_condition_id_foreign" foreign key ("condition_id") references "offer_condition" ("id") on update cascade on delete set null;`
+ )
+
+ this.addSql(
+ `insert into "offer_condition" ("id", "code", "label", "is_active", "rank") values ('ofcond_new', 'new', 'New', true, 0) on conflict ("id") do nothing;`
+ )
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(
+ `alter table if exists "offer" drop constraint if exists "offer_condition_id_foreign";`
+ )
+ this.addSql(`DROP INDEX IF EXISTS "IDX_offer_condition_id";`)
+ this.addSql(`ALTER TABLE "offer" DROP COLUMN IF EXISTS "condition_id";`)
+ this.addSql(`drop table if exists "offer_condition" cascade;`)
+ }
+}
diff --git a/packages/core/src/modules/offer/models/index.ts b/packages/core/src/modules/offer/models/index.ts
index 2f1c4541a..4475fc64f 100644
--- a/packages/core/src/modules/offer/models/index.ts
+++ b/packages/core/src/modules/offer/models/index.ts
@@ -1 +1,2 @@
export { default as Offer } from "./offer"
+export { default as OfferCondition } from "./offer-condition"
diff --git a/packages/core/src/modules/offer/models/offer-condition.ts b/packages/core/src/modules/offer/models/offer-condition.ts
new file mode 100644
index 000000000..0fbc9db07
--- /dev/null
+++ b/packages/core/src/modules/offer/models/offer-condition.ts
@@ -0,0 +1,24 @@
+import { model } from "@medusajs/framework/utils"
+
+import Offer from "./offer"
+
+const OfferCondition = model
+ .define("OfferCondition", {
+ id: model.id({ prefix: "ofcond" }).primaryKey(),
+ code: model.text().searchable(),
+ label: model.text().searchable(),
+ is_active: model.boolean().default(true),
+ rank: model.number().default(0),
+ metadata: model.json().nullable(),
+ offers: model.hasMany(() => Offer, { mappedBy: "condition" }),
+ })
+ .indexes([
+ {
+ name: "IDX_offer_condition_code_unique",
+ on: ["code"],
+ unique: true,
+ where: "deleted_at IS NULL",
+ },
+ ])
+
+export default OfferCondition
diff --git a/packages/core/src/modules/offer/models/offer.ts b/packages/core/src/modules/offer/models/offer.ts
index c0677983d..e102dea92 100644
--- a/packages/core/src/modules/offer/models/offer.ts
+++ b/packages/core/src/modules/offer/models/offer.ts
@@ -1,5 +1,7 @@
import { model } from "@medusajs/framework/utils"
+import OfferCondition from "./offer-condition"
+
const Offer = model
.define("Offer", {
id: model.id({ prefix: "offer" }).primaryKey(),
@@ -16,6 +18,9 @@ const Offer = model
created_by: model.text(),
variant_count: model.number().computed(),
metadata: model.json().nullable(),
+ condition: model
+ .belongsTo(() => OfferCondition, { mappedBy: "offers" })
+ .nullable(),
})
.indexes([
{
@@ -49,6 +54,11 @@ const Offer = model
on: ["ean"],
where: "deleted_at IS NULL AND ean IS NOT NULL",
},
+ {
+ name: "IDX_offer_condition_id",
+ on: ["condition_id"],
+ where: "deleted_at IS NULL AND condition_id IS NOT NULL",
+ },
{
name: "IDX_offer_upc",
on: ["upc"],
diff --git a/packages/core/src/modules/offer/service.ts b/packages/core/src/modules/offer/service.ts
index a74d58f75..fb271c4d1 100644
--- a/packages/core/src/modules/offer/service.ts
+++ b/packages/core/src/modules/offer/service.ts
@@ -7,7 +7,7 @@ import { Context, FindConfig } from "@medusajs/framework/types"
import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql"
import { OfferDTO } from "@mercurjs/types"
-import { Offer } from "./models"
+import { Offer, OfferCondition } from "./models"
type OfferFilters = Record<string, unknown> & { group_by_seller?: boolean }
@@ -16,6 +16,7 @@ const toArray = (value: unknown): string[] =>
class OfferModuleService extends MedusaService({
Offer,
+ OfferCondition,
}) {
@InjectManager()
// @ts-ignore - override narrows the generated signature
diff --git a/packages/core/src/workflows/events.ts b/packages/core/src/workflows/events.ts
index cacfb7a00..d1df89bd1 100644
--- a/packages/core/src/workflows/events.ts
+++ b/packages/core/src/workflows/events.ts
@@ -43,6 +43,12 @@ export const OfferWorkflowEvents = {
UPDATED: "offer.updated",
DELETED: "offer.deleted",
}
+
+export const OfferConditionWorkflowEvents = {
+ CREATED: "offer_condition.created",
+ UPDATED: "offer_condition.updated",
+ DELETED: "offer_condition.deleted",
+}
export const PaymentWebhookEvents = {
/**
* Emitted when a payment provider webhook reaches `/hooks/payment/:provider`.
diff --git a/packages/core/src/workflows/offer/steps/create-offer-conditions.ts b/packages/core/src/workflows/offer/steps/create-offer-conditions.ts
new file mode 100644
index 000000000..26743e1da
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/create-offer-conditions.ts
@@ -0,0 +1,25 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { CreateOfferConditionDTO, MercurModules } from "@mercurjs/types"
+
+import OfferModuleService from "../../../modules/offer/service"
+
+export const createOfferConditionsStepId = "create-offer-conditions"
+
+export const createOfferConditionsStep = createStep(
+ createOfferConditionsStepId,
+ async (input: CreateOfferConditionDTO[], { container }) => {
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ const conditions = await service.createOfferConditions(input)
+ return new StepResponse(
+ conditions,
+ conditions.map((c) => c.id)
+ )
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ await service.deleteOfferConditions(ids)
+ }
+)
diff --git a/packages/core/src/workflows/offer/steps/delete-offer-conditions.ts b/packages/core/src/workflows/offer/steps/delete-offer-conditions.ts
new file mode 100644
index 000000000..ff653d95f
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/delete-offer-conditions.ts
@@ -0,0 +1,22 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { MercurModules } from "@mercurjs/types"
+
+import OfferModuleService from "../../../modules/offer/service"
+
+export const deleteOfferConditionsStepId = "delete-offer-conditions"
+
+export const deleteOfferConditionsStep = createStep(
+ deleteOfferConditionsStepId,
+ async (ids: string[], { container }) => {
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ await service.softDeleteOfferConditions(ids)
+ return new StepResponse(void 0, ids)
+ },
+ async (ids, { container }) => {
+ if (!ids?.length) {
+ return
+ }
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ await service.restoreOfferConditions(ids)
+ }
+)
diff --git a/packages/core/src/workflows/offer/steps/index.ts b/packages/core/src/workflows/offer/steps/index.ts
index a9a93b55f..e0aeead72 100644
--- a/packages/core/src/workflows/offer/steps/index.ts
+++ b/packages/core/src/workflows/offer/steps/index.ts
@@ -4,3 +4,8 @@ export * from "./delete-offers"
export * from "./ensure-variant-price-sets"
export * from "./remove-offer-prices"
export * from "./update-offers"
+export * from "./create-offer-conditions"
+export * from "./update-offer-conditions"
+export * from "./delete-offer-conditions"
+export * from "./validate-offer-conditions"
+export * from "./validate-offer-conditions-deletable"
diff --git a/packages/core/src/workflows/offer/steps/update-offer-conditions.ts b/packages/core/src/workflows/offer/steps/update-offer-conditions.ts
new file mode 100644
index 000000000..aaa8e438e
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/update-offer-conditions.ts
@@ -0,0 +1,40 @@
+import { StepResponse, createStep } from "@medusajs/framework/workflows-sdk"
+import { MercurModules, UpdateOfferConditionDTO } from "@mercurjs/types"
+
+import OfferModuleService from "../../../modules/offer/service"
+
+export const updateOfferConditionsStepId = "update-offer-conditions"
+
+export const updateOfferConditionsStep = createStep(
+ updateOfferConditionsStepId,
+ async (input: UpdateOfferConditionDTO[], { container }) => {
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+
+ const ids = input.map((c) => c.id)
+ const before = await service.listOfferConditions({ id: ids })
+
+ const conditions = await service.updateOfferConditions(
+ input.map(({ id, ...data }) => ({ selector: { id }, data }))
+ )
+
+ const compensation = before.map((prev) => ({
+ id: prev.id,
+ code: prev.code,
+ label: prev.label,
+ is_active: prev.is_active,
+ rank: prev.rank,
+ metadata: prev.metadata ?? null,
+ }))
+
+ return new StepResponse(conditions, compensation)
+ },
+ async (compensation, { container }) => {
+ if (!compensation?.length) {
+ return
+ }
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ await service.updateOfferConditions(
+ compensation.map(({ id, ...data }) => ({ selector: { id }, data }))
+ )
+ }
+)
diff --git a/packages/core/src/workflows/offer/steps/update-offers.ts b/packages/core/src/workflows/offer/steps/update-offers.ts
index e69aaedfe..846504639 100644
--- a/packages/core/src/workflows/offer/steps/update-offers.ts
+++ b/packages/core/src/workflows/offer/steps/update-offers.ts
@@ -10,6 +10,7 @@ export type UpdateOffersStepInput = Array<{
manage_inventory?: boolean
allow_backorder?: boolean
leadtime_to_ship?: number | null
+ condition_id?: string | null
metadata?: Record<string, unknown> | null
}>
@@ -38,6 +39,7 @@ export const updateOffersStep = createStep(
manage_inventory: prev?.manage_inventory,
allow_backorder: prev?.allow_backorder,
leadtime_to_ship: prev?.leadtime_to_ship ?? null,
+ condition_id: prev?.condition_id ?? null,
metadata: prev?.metadata ?? null,
}
})
diff --git a/packages/core/src/workflows/offer/steps/validate-offer-conditions-deletable.ts b/packages/core/src/workflows/offer/steps/validate-offer-conditions-deletable.ts
new file mode 100644
index 000000000..d677d8baa
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/validate-offer-conditions-deletable.ts
@@ -0,0 +1,39 @@
+import { createStep } from "@medusajs/framework/workflows-sdk"
+import { MedusaError } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+import OfferModuleService from "../../../modules/offer/service"
+
+export const validateOfferConditionsDeletableStepId =
+ "validate-offer-conditions-deletable"
+
+export const validateOfferConditionsDeletableStep = createStep(
+ validateOfferConditionsDeletableStepId,
+ async (ids: string[], { container }) => {
+ if (!ids?.length) {
+ return
+ }
+
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+
+ const conditions = await service.listOfferConditions({ id: ids })
+ const missing = ids.find((id) => !conditions.some((c) => c.id === id))
+ if (missing) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer condition with id ${missing} was not found`
+ )
+ }
+
+ const [, inUse] = await service.listAndCountOffers(
+ { condition_id: ids },
+ { select: ["id"], take: 1 }
+ )
+ if (inUse > 0) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_ALLOWED,
+ "Offer conditions that are assigned to offers cannot be deleted"
+ )
+ }
+ }
+)
diff --git a/packages/core/src/workflows/offer/steps/validate-offer-conditions.ts b/packages/core/src/workflows/offer/steps/validate-offer-conditions.ts
new file mode 100644
index 000000000..b5d94e528
--- /dev/null
+++ b/packages/core/src/workflows/offer/steps/validate-offer-conditions.ts
@@ -0,0 +1,41 @@
+import { createStep } from "@medusajs/framework/workflows-sdk"
+import { MedusaError } from "@medusajs/framework/utils"
+import { MercurModules } from "@mercurjs/types"
+
+import OfferModuleService from "../../../modules/offer/service"
+
+export const validateOfferConditionsStepId = "validate-offer-conditions"
+
+export type ValidateOfferConditionsStepInput = {
+ condition_ids: string[]
+}
+
+export const validateOfferConditionsStep = createStep(
+ validateOfferConditionsStepId,
+ async ({ condition_ids }: ValidateOfferConditionsStepInput, { container }) => {
+ const ids = Array.from(new Set(condition_ids))
+ if (!ids.length) {
+ return
+ }
+
+ const service = container.resolve<OfferModuleService>(MercurModules.OFFER)
+ const conditions = await service.listOfferConditions({ id: ids })
+ const byId = new Map(conditions.map((c) => [c.id, c]))
+
+ for (const id of ids) {
+ const condition = byId.get(id)
+ if (!condition) {
+ throw new MedusaError(
+ MedusaError.Types.NOT_FOUND,
+ `Offer condition with id ${id} was not found`
+ )
+ }
+ if (!condition.is_active) {
+ throw new MedusaError(
+ MedusaError.Types.INVALID_DATA,
+ `Offer condition ${condition.code} is not active`
+ )
+ }
+ }
+ }
+)
diff --git a/packages/core/src/workflows/offer/workflows/create-offer-conditions.ts b/packages/core/src/workflows/offer/workflows/create-offer-conditions.ts
new file mode 100644
index 000000000..16cce48ae
--- /dev/null
+++ b/packages/core/src/workflows/offer/workflows/create-offer-conditions.ts
@@ -0,0 +1,51 @@
+import {
+ createHook,
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+ type Hook,
+ type ReturnWorkflow,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { CreateOfferConditionDTO, OfferConditionDTO } from "@mercurjs/types"
+
+import { createOfferConditionsStep } from "../steps"
+import { OfferConditionWorkflowEvents } from "../../events"
+
+export type CreateOfferConditionsWorkflowInput = {
+ offer_conditions: CreateOfferConditionDTO[]
+}
+
+export type CreateOfferConditionsWorkflowHooks = [
+ Hook<"offerConditionsCreated", { offer_conditions: OfferConditionDTO[] }, unknown>,
+]
+
+export const createOfferConditionsWorkflowId = "create-offer-conditions"
+
+export const createOfferConditionsWorkflow: ReturnWorkflow<
+ CreateOfferConditionsWorkflowInput,
+ OfferConditionDTO[],
+ CreateOfferConditionsWorkflowHooks
+> = createWorkflow(
+ createOfferConditionsWorkflowId,
+ function (input: CreateOfferConditionsWorkflowInput) {
+ const conditions = createOfferConditionsStep(input.offer_conditions)
+
+ const eventData = transform({ conditions }, ({ conditions }) =>
+ conditions.map((c) => ({ id: c.id }))
+ )
+
+ emitEventStep({
+ eventName: OfferConditionWorkflowEvents.CREATED,
+ data: eventData,
+ })
+
+ const offerConditionsCreated = createHook("offerConditionsCreated", {
+ offer_conditions: conditions,
+ })
+
+ return new WorkflowResponse(conditions, {
+ hooks: [offerConditionsCreated],
+ })
+ }
+)
diff --git a/packages/core/src/workflows/offer/workflows/create-offers.ts b/packages/core/src/workflows/offer/workflows/create-offers.ts
index 31eb5ccc4..1d60ddca8 100644
--- a/packages/core/src/workflows/offer/workflows/create-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/create-offers.ts
@@ -25,6 +25,7 @@ import {
addOfferPricesStep,
createOffersStep,
ensureVariantPriceSetsStep,
+ validateOfferConditionsStep,
} from "../steps"
import { linkSellerInventoryItemStep } from "../../inventory-item/steps"
import { OfferWorkflowEvents } from "../../events"
@@ -71,6 +72,14 @@ export const createOffersWorkflow: ReturnWorkflow<
Array.from(new Set(input.offers.map((o) => o.variant_id))),
)
+ const conditionIds = transform({ input }, ({ input }) =>
+ input.offers
+ .map((o) => o.condition_id)
+ .filter((id): id is string => !!id),
+ )
+
+ validateOfferConditionsStep({ condition_ids: conditionIds })
+
const { data: variants } = useQueryGraphStep({
entity: "product_variant",
fields: [
@@ -182,6 +191,7 @@ export const createOffersWorkflow: ReturnWorkflow<
manage_inventory: offer.manage_inventory ?? true,
allow_backorder: offer.allow_backorder ?? false,
leadtime_to_ship: offer.leadtime_to_ship ?? null,
+ condition_id: offer.condition_id ?? null,
created_by: offer.created_by,
metadata: offer.metadata ?? null,
}
diff --git a/packages/core/src/workflows/offer/workflows/delete-offer-conditions.ts b/packages/core/src/workflows/offer/workflows/delete-offer-conditions.ts
new file mode 100644
index 000000000..5e447621e
--- /dev/null
+++ b/packages/core/src/workflows/offer/workflows/delete-offer-conditions.ts
@@ -0,0 +1,55 @@
+import {
+ createHook,
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+ type Hook,
+ type ReturnWorkflow,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+
+import {
+ deleteOfferConditionsStep,
+ validateOfferConditionsDeletableStep,
+} from "../steps"
+import { OfferConditionWorkflowEvents } from "../../events"
+
+export type DeleteOfferConditionsWorkflowInput = {
+ ids: string[]
+}
+
+export type DeleteOfferConditionsWorkflowHooks = [
+ Hook<"offerConditionsDeleted", { ids: string[] }, unknown>,
+]
+
+export const deleteOfferConditionsWorkflowId = "delete-offer-conditions"
+
+export const deleteOfferConditionsWorkflow: ReturnWorkflow<
+ DeleteOfferConditionsWorkflowInput,
+ void,
+ DeleteOfferConditionsWorkflowHooks
+> = createWorkflow(
+ deleteOfferConditionsWorkflowId,
+ function (input: DeleteOfferConditionsWorkflowInput) {
+ validateOfferConditionsDeletableStep(input.ids)
+
+ deleteOfferConditionsStep(input.ids)
+
+ const eventData = transform({ input }, ({ input }) =>
+ input.ids.map((id) => ({ id }))
+ )
+
+ emitEventStep({
+ eventName: OfferConditionWorkflowEvents.DELETED,
+ data: eventData,
+ })
+
+ const offerConditionsDeleted = createHook("offerConditionsDeleted", {
+ ids: input.ids,
+ })
+
+ return new WorkflowResponse(void 0, {
+ hooks: [offerConditionsDeleted],
+ })
+ }
+)
diff --git a/packages/core/src/workflows/offer/workflows/index.ts b/packages/core/src/workflows/offer/workflows/index.ts
index 30079f739..6f907dd3d 100644
--- a/packages/core/src/workflows/offer/workflows/index.ts
+++ b/packages/core/src/workflows/offer/workflows/index.ts
@@ -3,3 +3,6 @@ export * from "./update-offers"
export * from "./upsert-offer-prices"
export * from "./delete-offers"
export * from "./batch-offer-inventory-items"
+export * from "./create-offer-conditions"
+export * from "./update-offer-conditions"
+export * from "./delete-offer-conditions"
diff --git a/packages/core/src/workflows/offer/workflows/update-offer-conditions.ts b/packages/core/src/workflows/offer/workflows/update-offer-conditions.ts
new file mode 100644
index 000000000..31c33688d
--- /dev/null
+++ b/packages/core/src/workflows/offer/workflows/update-offer-conditions.ts
@@ -0,0 +1,51 @@
+import {
+ createHook,
+ createWorkflow,
+ transform,
+ WorkflowResponse,
+ type Hook,
+ type ReturnWorkflow,
+} from "@medusajs/framework/workflows-sdk"
+import { emitEventStep } from "@medusajs/medusa/core-flows"
+import { OfferConditionDTO, UpdateOfferConditionDTO } from "@mercurjs/types"
+
+import { updateOfferConditionsStep } from "../steps"
+import { OfferConditionWorkflowEvents } from "../../events"
+
+export type UpdateOfferConditionsWorkflowInput = {
+ offer_conditions: UpdateOfferConditionDTO[]
+}
+
+export type UpdateOfferConditionsWorkflowHooks = [
+ Hook<"offerConditionsUpdated", { offer_conditions: OfferConditionDTO[] }, unknown>,
+]
+
+export const updateOfferConditionsWorkflowId = "update-offer-conditions"
+
+export const updateOfferConditionsWorkflow: ReturnWorkflow<
+ UpdateOfferConditionsWorkflowInput,
+ OfferConditionDTO[],
+ UpdateOfferConditionsWorkflowHooks
+> = createWorkflow(
+ updateOfferConditionsWorkflowId,
+ function (input: UpdateOfferConditionsWorkflowInput) {
+ const conditions = updateOfferConditionsStep(input.offer_conditions)
+
+ const eventData = transform({ conditions }, ({ conditions }) =>
+ conditions.map((c) => ({ id: c.id }))
+ )
+
+ emitEventStep({
+ eventName: OfferConditionWorkflowEvents.UPDATED,
+ data: eventData,
+ })
+
+ const offerConditionsUpdated = createHook("offerConditionsUpdated", {
+ offer_conditions: conditions,
+ })
+
+ return new WorkflowResponse(conditions, {
+ hooks: [offerConditionsUpdated],
+ })
+ }
+)
diff --git a/packages/core/src/workflows/offer/workflows/update-offers.ts b/packages/core/src/workflows/offer/workflows/update-offers.ts
index 526522c0b..c2615f236 100644
--- a/packages/core/src/workflows/offer/workflows/update-offers.ts
+++ b/packages/core/src/workflows/offer/workflows/update-offers.ts
@@ -11,7 +11,7 @@ import { AdditionalData } from "@medusajs/framework/types"
import { emitEventStep } from "@medusajs/medusa/core-flows"
import { UpdateOfferDTO, OfferDTO } from "@mercurjs/types"
-import { updateOffersStep } from "../steps"
+import { updateOffersStep, validateOfferConditionsStep } from "../steps"
import { upsertOfferPricesWorkflow } from "./upsert-offer-prices"
import { OfferWorkflowEvents } from "../../events"
@@ -42,6 +42,14 @@ export const updateOffersWorkflow: ReturnWorkflow<
function (input: UpdateOffersWorkflowInput) {
const validate = createHook("validate", { input })
+ const conditionIds = transform(input, ({ offers }) =>
+ offers
+ .map((o) => o.condition_id)
+ .filter((id): id is string => !!id),
+ )
+
+ validateOfferConditionsStep({ condition_ids: conditionIds })
+
const rowUpdates = transform(input, ({ offers }) =>
offers.map((o) => ({
id: o.id,
@@ -50,6 +58,7 @@ export const updateOffersWorkflow: ReturnWorkflow<
manage_inventory: o.manage_inventory,
allow_backorder: o.allow_backorder,
leadtime_to_ship: o.leadtime_to_ship,
+ condition_id: o.condition_id,
metadata: o.metadata,
})),
)
diff --git a/packages/types/src/http/offer.ts b/packages/types/src/http/offer.ts
index f98cab772..135cb326e 100644
--- a/packages/types/src/http/offer.ts
+++ b/packages/types/src/http/offer.ts
@@ -2,6 +2,7 @@ import { DeleteResponse, PaginatedResponse } from "@medusajs/types"
import {
CreateOfferInventoryItemDTO,
CreateOfferPriceDTO,
+ OfferConditionDTO,
OfferDTO,
UpsertOfferPriceDTO,
} from "../offer"
@@ -23,6 +24,7 @@ export interface VendorCreateOfferReq {
shipping_profile_id: string
inventory_items: CreateOfferInventoryItemDTO[]
prices: CreateOfferPriceDTO[]
+ condition_id?: string | null
metadata?: Record<string, unknown> | null
}
@@ -33,6 +35,7 @@ export interface VendorCreateOfferReq {
export interface VendorUpdateOfferReq {
sku?: string
shipping_profile_id?: string
+ condition_id?: string | null
metadata?: Record<string, unknown> | null
prices?: UpsertOfferPriceDTO[]
}
@@ -90,3 +93,43 @@ export interface AdminOfferResponse {
export type AdminOfferListResponse = PaginatedResponse<{
offers: OfferDTO[]
}>
+
+/*
+ * --------------------------------------------------------------------
+ * Offer conditions
+ * --------------------------------------------------------------------
+ */
+
+export interface AdminCreateOfferConditionReq {
+ code: string
+ label: string
+ is_active?: boolean
+ rank?: number
+ metadata?: Record<string, unknown> | null
+}
+
+export interface AdminUpdateOfferConditionReq {
+ code?: string
+ label?: string
+ is_active?: boolean
+ rank?: number
+ metadata?: Record<string, unknown> | null
+}
+
+export interface AdminOfferConditionResponse {
+ offer_condition: OfferConditionDTO
+}
+
+export type AdminOfferConditionListResponse = PaginatedResponse<{
+ offer_conditions: OfferConditionDTO[]
+}>
+
+export type AdminOfferConditionDeleteResponse = DeleteResponse<"offer_condition">
+
+export interface VendorOfferConditionResponse {
+ offer_condition: OfferConditionDTO
+}
+
+export type VendorOfferConditionListResponse = PaginatedResponse<{
+ offer_conditions: OfferConditionDTO[]
+}>
diff --git a/packages/types/src/offer/common.ts b/packages/types/src/offer/common.ts
index 3d2811b27..d3f03f824 100644
--- a/packages/types/src/offer/common.ts
+++ b/packages/types/src/offer/common.ts
@@ -32,6 +32,24 @@ export interface OfferInventoryItemLinkDTO {
*/
export type OfferPriceDTO = MoneyAmountDTO
+/**
+ * An operator-defined physical condition an offer can be listed under
+ * (e.g. `new`, `refurbished`, `used_like_new`). Sellers pick from the active
+ * conditions when creating or updating an offer; the same seller can hold one
+ * offer per condition on the same variant. `rank` drives the display order.
+ */
+export interface OfferConditionDTO {
+ id: string
+ code: string
+ label: string
+ is_active: boolean
+ rank: number
+ metadata: Record<string, unknown> | null
+ created_at: Date
+ updated_at: Date
+ deleted_at: Date | null
+}
+
/**
* The marketplace's per-vendor sellable. An offer is the thin marketplace-side
* record that points at a Medusa `ProductVariant` (which owns the shared
@@ -54,6 +72,7 @@ export interface OfferDTO {
manage_inventory: boolean
allow_backorder: boolean
leadtime_to_ship: number | null
+ condition_id: string | null
created_by: string
metadata: Record<string, unknown> | null
created_at: Date
@@ -84,6 +103,8 @@ export interface OfferDTO {
* `InventoryItem` when requested.
*/
inventory_items?: OfferInventoryItemLinkDTO[]
+ /** The condition the offer is listed under, when one was assigned. */
+ condition?: OfferConditionDTO | null
/** The seller that owns this offer (joined through `offer ↔ seller`). */
seller?: SellerDTO
/** The product this offer points at (joined through `offer ↔ product`). */
diff --git a/packages/types/src/offer/mutations.ts b/packages/types/src/offer/mutations.ts
index 4022fe11d..13a97bc7f 100644
--- a/packages/types/src/offer/mutations.ts
+++ b/packages/types/src/offer/mutations.ts
@@ -68,6 +68,7 @@ export interface CreateOfferDTO {
manage_inventory?: boolean
allow_backorder?: boolean
leadtime_to_ship?: number | null
+ condition_id?: string | null
metadata?: Record<string, unknown> | null
}
@@ -90,6 +91,7 @@ export interface CreateOfferRowDTO {
manage_inventory?: boolean
allow_backorder?: boolean
leadtime_to_ship?: number | null
+ condition_id?: string | null
created_by: string
metadata?: Record<string, unknown> | null
}
@@ -107,6 +109,7 @@ export interface UpdateOfferDTO {
manage_inventory?: boolean
allow_backorder?: boolean
leadtime_to_ship?: number | null
+ condition_id?: string | null
metadata?: Record<string, unknown> | null
prices?: UpsertOfferPriceDTO[]
}
@@ -128,3 +131,29 @@ export interface BatchOfferInventoryItemsDTO {
}>
delete?: string[]
}
+
+/**
+ * Input to `createOfferConditionsWorkflow`. `code` must be unique across
+ * non-deleted conditions; `rank` orders the list sellers see.
+ */
+export interface CreateOfferConditionDTO {
+ code: string
+ label: string
+ is_active?: boolean
+ rank?: number
+ metadata?: Record<string, unknown> | null
+}
+
+/**
+ * Input to `updateOfferConditionsWorkflow`, keyed by `id`. Deactivating a
+ * condition keeps the offers already listed under it, but blocks new
+ * assignments.
+ */
+export interface UpdateOfferConditionDTO {
+ id: string
+ code?: string
+ label?: string
+ is_active?: boolean
+ rank?: number
+ metadata?: Record<string, unknown> | null
+}