feat(core-flows,medusa): adds inventory kit creation to variants endpoint (#7599)

what:

When creating a variant, we can now create inventory as a part of the product and variants create endpoint.

This applies only to variants where `manage_inventory=true`. 2 cases present itself:

1. When inventory_items are present
  - Link an inventory item with required_quantity to the variant
  - the inventory item already needs to be present
2. When inventory_items are not present
  - A default inventory item will be created
  - links the created item to the variant with a default required_quantity
  
  
RESOLVES CORE-2220
This commit is contained in:
Riqwan Thamir
2024-06-04 13:49:31 +00:00
committed by GitHub
parent 6646a203df
commit e7005a0aac
9 changed files with 521 additions and 179 deletions
@@ -0,0 +1,36 @@
import {
ContainerRegistrationKeys,
MedusaError,
arrayDifference,
remoteQueryObjectFromString,
} from "@medusajs/utils"
import { createStep } from "@medusajs/workflows-sdk"
export const validateInventoryItemsId = "validate-inventory-items-step"
export const validateInventoryItems = createStep(
validateInventoryItemsId,
async (id: string[], { container }) => {
const remoteQuery = container.resolve(
ContainerRegistrationKeys.REMOTE_QUERY
)
const query = remoteQueryObjectFromString({
entryPoint: "inventory_item",
variables: { id },
fields: ["id"],
})
const items = await remoteQuery(query)
const diff = arrayDifference(
id,
items.map(({ id }) => id)
)
if (diff.length > 0) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Inventory Items with ids: ${diff.join(", ")} was not found`
)
}
}
)
@@ -1,9 +1,13 @@
import { PricingTypes, ProductTypes } from "@medusajs/types"
import { LinkDefinition, Modules } from "@medusajs/modules-sdk"
import { InventoryNext, PricingTypes, ProductTypes } from "@medusajs/types"
import {
WorkflowData,
createWorkflow,
transform,
} from "@medusajs/workflows-sdk"
import { createLinksWorkflow } from "../../common/workflows/create-links"
import { validateInventoryItems } from "../../inventory/steps/validate-inventory-items"
import { createInventoryItemsWorkflow } from "../../inventory/workflows/create-inventory-items"
import { createPriceSetsStep } from "../../pricing"
import { createProductVariantsStep } from "../steps/create-product-variants"
import { createVariantPricingLinkStep } from "../steps/create-variant-pricing-link"
@@ -12,9 +16,105 @@ import { createVariantPricingLinkStep } from "../steps/create-variant-pricing-li
type WorkflowInput = {
product_variants: (ProductTypes.CreateProductVariantDTO & {
prices?: PricingTypes.CreateMoneyAmountDTO[]
} & {
inventory_items?: {
inventory_item_id: string
required_quantity?: number
}[]
})[]
}
const buildLink = (
variant_id: string,
inventory_item_id: string,
required_quantity: number
) => {
const link: LinkDefinition = {
[Modules.PRODUCT]: { variant_id },
[Modules.INVENTORY]: { inventory_item_id: inventory_item_id },
data: { required_quantity: required_quantity },
}
return link
}
const buildLinksToCreate = (data: {
createdVariants: ProductTypes.ProductVariantDTO[]
inventoryIndexMap: Record<number, InventoryNext.InventoryItemDTO>
input: WorkflowInput
}) => {
let index = 0
const linksToCreate: LinkDefinition[] = []
for (const variant of data.createdVariants) {
const variantInput = data.input.product_variants[index]
const shouldManageInventory = variant.manage_inventory
const hasInventoryItems = variantInput.inventory_items?.length
index += 1
if (!shouldManageInventory) {
continue
}
if (!hasInventoryItems) {
const inventoryItem = data.inventoryIndexMap[index]
linksToCreate.push(buildLink(variant.id, inventoryItem.id, 1))
continue
}
for (const inventoryInput of variantInput.inventory_items || []) {
linksToCreate.push(
buildLink(
variant.id,
inventoryInput.inventory_item_id,
inventoryInput.required_quantity ?? 1
)
)
}
}
return linksToCreate
}
const buildVariantItemCreateMap = (data: {
createdVariants: ProductTypes.ProductVariantDTO[]
input: WorkflowInput
}) => {
let index = 0
const map: Record<number, InventoryNext.CreateInventoryItemInput> = {}
for (const variant of data.createdVariants || []) {
const variantInput = data.input.product_variants[index]
const shouldManageInventory = variant.manage_inventory
const hasInventoryItems = variantInput.inventory_items?.length
index += 1
if (!shouldManageInventory || hasInventoryItems) {
continue
}
// Create a default inventory item if the above conditions arent met
map[index] = {
sku: variantInput.sku,
origin_country: variantInput.origin_country,
mid_code: variantInput.mid_code,
material: variantInput.material,
weight: variantInput.weight,
length: variantInput.length,
height: variantInput.height,
width: variantInput.width,
title: variantInput.title,
description: variantInput.title,
hs_code: variantInput.hs_code,
requires_shipping: true,
}
}
return map
}
export const createProductVariantsWorkflowId = "create-product-variants"
export const createProductVariantsWorkflow = createWorkflow(
createProductVariantsWorkflowId,
@@ -31,6 +131,50 @@ export const createProductVariantsWorkflow = createWorkflow(
const createdVariants = createProductVariantsStep(variantsWithoutPrices)
// Setup variants inventory
const inventoryItemIds = transform(input, (data) => {
return data.product_variants
.map((variant) => variant.inventory_items || [])
.flat()
.map((item) => item.inventory_item_id)
.flat()
})
validateInventoryItems(inventoryItemIds)
const variantItemCreateMap = transform(
{ createdVariants, input },
buildVariantItemCreateMap
)
const createdInventoryItems = createInventoryItemsWorkflow.runAsStep({
input: {
items: transform(variantItemCreateMap, (data) => Object.values(data)),
},
})
const inventoryIndexMap = transform(
{ createdInventoryItems, variantItemCreateMap },
(data) => {
const map: Record<number, InventoryNext.InventoryItemDTO> = {}
let inventoryIndex = 0
for (const variantIndex of Object.keys(data.variantItemCreateMap)) {
map[variantIndex] = data.createdInventoryItems[inventoryIndex]
inventoryIndex += 1
}
return map
}
)
const linksToCreate = transform(
{ createdVariants, inventoryIndexMap, input },
buildLinksToCreate
)
createLinksWorkflow.runAsStep({ input: linksToCreate })
// Note: We rely on the same order of input and output when creating variants here, make sure that assumption holds
const pricesToCreate = transform({ input, createdVariants }, (data) =>
data.createdVariants.map((v, i) => {
@@ -40,7 +184,6 @@ export const createProductVariantsWorkflow = createWorkflow(
})
)
// TODO: From here until the final transform the code is the same as when creating a product, we can probably refactor
const createdPriceSets = createPriceSetsStep(pricesToCreate)
const variantAndPriceSets = transform(