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(core): add product-variant-created hook to link inventory items to seller

vholike55cc1b40692
diff --git a/packages/core-plugin/src/workflows/hooks/product-variant-created.ts b/packages/core-plugin/src/workflows/hooks/product-variant-created.ts
new file mode 100644
index 000000000..b1f3701c2
--- /dev/null
+++ b/packages/core-plugin/src/workflows/hooks/product-variant-created.ts
@@ -0,0 +1,68 @@
+import { createProductVariantsWorkflow } from "@medusajs/medusa/core-flows"
+import { StepResponse } from "@medusajs/framework/workflows-sdk"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { LinkDefinition } from "@medusajs/framework/types"
+import { MercurModules } from "@mercurjs/types"
+
+createProductVariantsWorkflow.hooks.productVariantsCreated(
+ async ({ product_variants, additional_data }, { container }) => {
+ if (!additional_data?.seller_id) {
+ return new StepResponse(
+ { inventoryLinks: [] as LinkDefinition[] },
+ { inventoryLinks: [] as LinkDefinition[] }
+ )
+ }
+
+ const link = container.resolve(ContainerRegistrationKeys.LINK)
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ const inventoryLinks: LinkDefinition[] = []
+
+ const variantIds = product_variants
+ .filter((v) => v.manage_inventory)
+ .map((v) => v.id)
+
+ if (variantIds.length) {
+ const { data: variants } = await query.graph({
+ entity: "variant",
+ fields: ["inventory_items.inventory_item_id"],
+ filters: { id: variantIds },
+ })
+
+ for (const variant of variants) {
+ for (const inventoryItem of variant.inventory_items || []) {
+ inventoryLinks.push({
+ [Modules.INVENTORY]: {
+ inventory_item_id: inventoryItem.inventory_item_id,
+ },
+ [MercurModules.SELLER]: {
+ seller_id: additional_data.seller_id,
+ },
+ })
+ }
+ }
+ }
+
+ if (inventoryLinks.length) {
+ await link.create(inventoryLinks)
+ }
+
+ return new StepResponse(
+ { inventoryLinks },
+ { inventoryLinks }
+ )
+ },
+ async (data, { container }) => {
+ if (!data) {
+ return
+ }
+
+ const { inventoryLinks } = data
+
+ const link = container.resolve(ContainerRegistrationKeys.LINK)
+
+ if (inventoryLinks?.length) {
+ await link.dismiss(inventoryLinks)
+ }
+ }
+)