fix(medusa): calculate sales channel availability correctly for variants (#10448)
* fix: calculate inventory quantities based on sales channel and locations * Update packages/medusa/src/api/utils/middlewares/products/variant-inventory-quantity.ts Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com> * Update packages/medusa/src/api/utils/middlewares/products/variant-inventory-quantity.ts Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com> * Update packages/core/core-flows/src/product/steps/get-variant-availability.ts Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com> * fix: crk --------- Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com>
This commit is contained in:
co-authored by
Carlos R. L. Rodrigues
parent
b160fd3cbf
commit
7ff3f15d6d
@@ -4,7 +4,7 @@ import {
|
||||
refetchEntities,
|
||||
} from "@medusajs/framework/http"
|
||||
import { HttpTypes } from "@medusajs/framework/types"
|
||||
import { wrapVariantsWithInventoryQuantity } from "../../utils/middlewares"
|
||||
import { wrapVariantsWithTotalInventoryQuantity } from "../../utils/middlewares"
|
||||
import { remapKeysForVariant, remapVariantResponse } from "../products/helpers"
|
||||
|
||||
export const GET = async (
|
||||
@@ -30,7 +30,7 @@ export const GET = async (
|
||||
)
|
||||
|
||||
if (withInventoryQuantity) {
|
||||
await wrapVariantsWithInventoryQuantity(req, variants || [])
|
||||
await wrapVariantsWithTotalInventoryQuantity(req, variants || [])
|
||||
}
|
||||
|
||||
res.json({
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
AuthenticatedMedusaRequest,
|
||||
MedusaResponse,
|
||||
} from "@medusajs/framework/http"
|
||||
import { wrapVariantsWithInventoryQuantity } from "../../../../utils/middlewares"
|
||||
import { wrapVariantsWithTotalInventoryQuantity } from "../../../../utils/middlewares"
|
||||
import { refetchEntities, refetchEntity } from "@medusajs/framework/http"
|
||||
import {
|
||||
remapKeysForProduct,
|
||||
@@ -38,7 +38,7 @@ export const GET = async (
|
||||
)
|
||||
|
||||
if (withInventoryQuantity) {
|
||||
await wrapVariantsWithInventoryQuantity(req, variants || [])
|
||||
await wrapVariantsWithTotalInventoryQuantity(req, variants || [])
|
||||
}
|
||||
|
||||
res.json({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { isPresent, MedusaError } from "@medusajs/framework/utils"
|
||||
import { MedusaResponse } from "@medusajs/framework/http"
|
||||
import { wrapVariantsWithInventoryQuantity } from "../../../utils/middlewares"
|
||||
import { wrapVariantsWithInventoryQuantityForSalesChannel } from "../../../utils/middlewares"
|
||||
import {
|
||||
refetchProduct,
|
||||
RequestWithContext,
|
||||
@@ -48,7 +48,10 @@ export const GET = async (
|
||||
}
|
||||
|
||||
if (withInventoryQuantity) {
|
||||
await wrapVariantsWithInventoryQuantity(req, product.variants || [])
|
||||
await wrapVariantsWithInventoryQuantityForSalesChannel(
|
||||
req,
|
||||
product.variants || []
|
||||
)
|
||||
}
|
||||
|
||||
await wrapProductsWithTaxPrices(req, [product])
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
MedusaRequest,
|
||||
refetchEntities,
|
||||
refetchEntity,
|
||||
} from "@medusajs/framework/http"
|
||||
import { MedusaStoreRequest, refetchEntity } from "@medusajs/framework/http"
|
||||
import {
|
||||
HttpTypes,
|
||||
ItemTaxLineDTO,
|
||||
@@ -13,7 +9,7 @@ import {
|
||||
import { calculateAmountsWithTax, Modules } from "@medusajs/framework/utils"
|
||||
import { TaxModuleService } from "@medusajs/tax/dist/services"
|
||||
|
||||
export type RequestWithContext<T> = MedusaRequest<T> & {
|
||||
export type RequestWithContext<T> = MedusaStoreRequest<T> & {
|
||||
taxContext: {
|
||||
taxLineContext?: TaxCalculationContext
|
||||
taxInclusivityContext?: {
|
||||
@@ -30,27 +26,6 @@ export const refetchProduct = async (
|
||||
return await refetchEntity("product", idOrFilter, scope, fields)
|
||||
}
|
||||
|
||||
export const maybeApplyStockLocationId = async (req: MedusaRequest, ctx) => {
|
||||
const withInventoryQuantity = req.remoteQueryConfig.fields.some((field) =>
|
||||
field.includes("variants.inventory_quantity")
|
||||
)
|
||||
|
||||
if (!withInventoryQuantity) {
|
||||
return
|
||||
}
|
||||
|
||||
const salesChannelId = req.filterableFields.sales_channel_id || []
|
||||
|
||||
const entities = await refetchEntities(
|
||||
"sales_channel_location",
|
||||
{ sales_channel_id: salesChannelId },
|
||||
req.scope,
|
||||
["stock_location_id"]
|
||||
)
|
||||
|
||||
return entities.map((entity) => entity.stock_location_id)
|
||||
}
|
||||
|
||||
export const wrapProductsWithTaxPrices = async <T>(
|
||||
req: RequestWithContext<T>,
|
||||
products: HttpTypes.StoreProduct[]
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
clearFiltersByKey,
|
||||
maybeApplyLinkFilter,
|
||||
MiddlewareRoute,
|
||||
setContext,
|
||||
} from "@medusajs/framework/http"
|
||||
import { isPresent, ProductStatus } from "@medusajs/framework/utils"
|
||||
import {
|
||||
@@ -15,7 +14,6 @@ import {
|
||||
setPricingContext,
|
||||
setTaxContext,
|
||||
} from "../../utils/middlewares"
|
||||
import { maybeApplyStockLocationId } from "./helpers"
|
||||
import * as QueryConfig from "./query-config"
|
||||
import { StoreGetProductsParams } from "./validators"
|
||||
|
||||
@@ -32,9 +30,6 @@ export const storeProductRoutesMiddlewares: MiddlewareRoute[] = [
|
||||
QueryConfig.listProductQueryConfig
|
||||
),
|
||||
filterByValidSalesChannels(),
|
||||
setContext({
|
||||
stock_location_id: maybeApplyStockLocationId,
|
||||
}),
|
||||
maybeApplyLinkFilter({
|
||||
entryPoint: "product_sales_channel",
|
||||
resourceId: "product_id",
|
||||
@@ -73,9 +68,6 @@ export const storeProductRoutesMiddlewares: MiddlewareRoute[] = [
|
||||
),
|
||||
applyParamsAsFilters({ id: "id" }),
|
||||
filterByValidSalesChannels(),
|
||||
setContext({
|
||||
stock_location_id: maybeApplyStockLocationId,
|
||||
}),
|
||||
maybeApplyLinkFilter({
|
||||
entryPoint: "product_sales_channel",
|
||||
resourceId: "product_id",
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
remoteQueryObjectFromString,
|
||||
} from "@medusajs/framework/utils"
|
||||
import { MedusaResponse } from "@medusajs/framework/http"
|
||||
import { wrapVariantsWithInventoryQuantity } from "../../utils/middlewares"
|
||||
import { wrapVariantsWithInventoryQuantityForSalesChannel } from "../../utils/middlewares"
|
||||
import { RequestWithContext, wrapProductsWithTaxPrices } from "./helpers"
|
||||
import { HttpTypes } from "@medusajs/framework/types"
|
||||
|
||||
@@ -43,7 +43,7 @@ export const GET = async (
|
||||
const { rows: products, metadata } = await remoteQuery(queryObject)
|
||||
|
||||
if (withInventoryQuantity) {
|
||||
await wrapVariantsWithInventoryQuantity(
|
||||
await wrapVariantsWithInventoryQuantityForSalesChannel(
|
||||
req,
|
||||
products.map((product) => product.variants).flat(1)
|
||||
)
|
||||
|
||||
@@ -1,89 +1,55 @@
|
||||
import {
|
||||
ContainerRegistrationKeys,
|
||||
LINKS,
|
||||
remoteQueryObjectFromString,
|
||||
getTotalVariantAvailability,
|
||||
getVariantAvailability,
|
||||
MedusaError,
|
||||
} from "@medusajs/framework/utils"
|
||||
import { MedusaRequest } from "@medusajs/framework/http"
|
||||
import { MedusaRequest, MedusaStoreRequest } from "@medusajs/framework/http"
|
||||
|
||||
export async function getVariantInventoryItems({
|
||||
req,
|
||||
variantIds,
|
||||
additionalFilters = {},
|
||||
asMap = true,
|
||||
}) {
|
||||
const remoteQuery = req.scope.resolve(ContainerRegistrationKeys.REMOTE_QUERY)
|
||||
export const wrapVariantsWithTotalInventoryQuantity = async (
|
||||
req: MedusaRequest,
|
||||
variants: VariantInput[]
|
||||
) => {
|
||||
const variantIds = (variants ?? []).map((variant) => variant.id).flat(1)
|
||||
|
||||
const linkQuery = remoteQueryObjectFromString({
|
||||
service: LINKS.ProductVariantInventoryItem,
|
||||
variables: {
|
||||
filters: {
|
||||
variant_id: variantIds,
|
||||
},
|
||||
...additionalFilters,
|
||||
},
|
||||
fields: [
|
||||
"variant_id",
|
||||
"variant.manage_inventory",
|
||||
"variant.allow_backorder",
|
||||
"required_quantity",
|
||||
"inventory.*",
|
||||
"inventory.location_levels.*",
|
||||
],
|
||||
} as any)
|
||||
|
||||
const links = await remoteQuery(linkQuery)
|
||||
|
||||
if (!asMap) {
|
||||
return links
|
||||
if (!variantIds.length) {
|
||||
return
|
||||
}
|
||||
|
||||
const variantInventoriesMap = new Map()
|
||||
|
||||
links.forEach((link) => {
|
||||
const array = variantInventoriesMap.get(link.variant_id) || []
|
||||
|
||||
array.push(link)
|
||||
|
||||
variantInventoriesMap.set(link.variant_id, array)
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
|
||||
const availability = await getTotalVariantAvailability(query, {
|
||||
variant_ids: variantIds,
|
||||
})
|
||||
|
||||
return variantInventoriesMap
|
||||
wrapVariants(variants, availability)
|
||||
}
|
||||
|
||||
export async function computeVariantInventoryQuantity({
|
||||
variantInventoryItems,
|
||||
}) {
|
||||
const links = variantInventoryItems
|
||||
const inventoryQuantities: number[] = []
|
||||
export const wrapVariantsWithInventoryQuantityForSalesChannel = async (
|
||||
req: MedusaStoreRequest<unknown>,
|
||||
variants: VariantInput[]
|
||||
) => {
|
||||
const salesChannelId = req.filterableFields.sales_channel_id as
|
||||
| string
|
||||
| string[]
|
||||
const { sales_channel_ids: idsFromPublishableKey = [] } =
|
||||
req.publishable_key_context
|
||||
|
||||
for (const link of links) {
|
||||
const requiredQuantity = link.required_quantity
|
||||
const availableQuantity = (link.inventory?.location_levels || []).reduce(
|
||||
(sum, level) => sum + (level?.available_quantity || 0),
|
||||
0
|
||||
)
|
||||
|
||||
// This will give us the maximum deliverable quantities for each inventory item
|
||||
const maxInventoryQuantity = Math.floor(
|
||||
availableQuantity / requiredQuantity
|
||||
)
|
||||
|
||||
inventoryQuantities.push(maxInventoryQuantity)
|
||||
let channelToUse: string | undefined
|
||||
if (salesChannelId && !Array.isArray(salesChannelId)) {
|
||||
channelToUse = salesChannelId
|
||||
}
|
||||
|
||||
// Since each of these inventory items need to be available to perform an order,
|
||||
// we pick the smallest of the deliverable quantities as the total inventory quantity.
|
||||
return inventoryQuantities.length ? Math.min(...inventoryQuantities) : 0
|
||||
}
|
||||
if (idsFromPublishableKey.length === 1) {
|
||||
channelToUse = idsFromPublishableKey[0]
|
||||
}
|
||||
|
||||
if (!channelToUse) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
`Inventory availability cannot be calculated in the given context. Either provide a sales channel id or configure a single sales channel in the publishable key`
|
||||
)
|
||||
}
|
||||
|
||||
export const wrapVariantsWithInventoryQuantity = async (
|
||||
req: MedusaRequest,
|
||||
variants: {
|
||||
id: string
|
||||
inventory_quantity?: number
|
||||
manage_inventory?: boolean
|
||||
}[]
|
||||
) => {
|
||||
variants ??= []
|
||||
const variantIds = variants.map((variant) => variant.id).flat(1)
|
||||
|
||||
@@ -91,19 +57,34 @@ export const wrapVariantsWithInventoryQuantity = async (
|
||||
return
|
||||
}
|
||||
|
||||
const variantInventoriesMap = await getVariantInventoryItems({
|
||||
req,
|
||||
variantIds,
|
||||
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
|
||||
const availability = await getVariantAvailability(query, {
|
||||
variant_ids: variantIds,
|
||||
sales_channel_id: channelToUse,
|
||||
})
|
||||
|
||||
wrapVariants(variants, availability)
|
||||
}
|
||||
|
||||
type VariantInput = {
|
||||
id: string
|
||||
inventory_quantity?: number
|
||||
manage_inventory?: boolean
|
||||
}
|
||||
|
||||
type VariantAvailability = Awaited<
|
||||
ReturnType<typeof getTotalVariantAvailability>
|
||||
>
|
||||
|
||||
const wrapVariants = (
|
||||
variants: VariantInput[],
|
||||
availability: VariantAvailability
|
||||
) => {
|
||||
for (const variant of variants) {
|
||||
if (!variant.manage_inventory) {
|
||||
continue
|
||||
}
|
||||
|
||||
const links = variantInventoriesMap.get(variant.id) || []
|
||||
variant.inventory_quantity = await computeVariantInventoryQuantity({
|
||||
variantInventoryItems: links,
|
||||
})
|
||||
variant.inventory_quantity = availability[variant.id].availability
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user