feat(medusa, admin-ui): increase tree depth + scope categories on store + allow categories relation in products API (#3450)
What: - increase tree depth in react nestable - scope categories on store queries - allow categories relation in products API RESOLVES CORE-1238 RESOLVES CORE-1237 RESOLVES CORE-1236
This commit is contained in:
+4
@@ -78,6 +78,10 @@ function ProductCategoriesList(props: ProductCategoriesListProps) {
|
||||
items={categories}
|
||||
onChange={onItemDrop}
|
||||
childrenProp="category_children"
|
||||
// Adding an unreasonably high number here to prevent us from
|
||||
// setting a hard limit on category depth. This should be decided upon
|
||||
// by consumers of medusa after considering the pros and cons to the approach
|
||||
maxDepth={99}
|
||||
renderItem={({ item, depth, handler, collapseIcon }) => (
|
||||
<ProductCategoryListItemDetails
|
||||
item={item}
|
||||
|
||||
@@ -65,7 +65,6 @@ describe("GET /admin/products/:id", () => {
|
||||
"tags",
|
||||
"type",
|
||||
"collection",
|
||||
"categories",
|
||||
"sales_channels",
|
||||
],
|
||||
}
|
||||
|
||||
@@ -17,6 +17,10 @@ export default (app, featureFlagRouter: FlagRouter) => {
|
||||
defaultAdminProductRelations.push("sales_channels")
|
||||
}
|
||||
|
||||
if (featureFlagRouter.isFeatureEnabled("product_categories")) {
|
||||
defaultAdminProductRelations.push("categories")
|
||||
}
|
||||
|
||||
route.post(
|
||||
"/",
|
||||
validateSalesChannelsExist((req) => req.body?.sales_channels),
|
||||
@@ -100,7 +104,6 @@ export const defaultAdminProductRelations = [
|
||||
"tags",
|
||||
"type",
|
||||
"collection",
|
||||
"categories",
|
||||
]
|
||||
|
||||
export const defaultAdminProductFields: (keyof Product)[] = [
|
||||
|
||||
@@ -26,7 +26,9 @@ const route = Router()
|
||||
export default (app, container, config) => {
|
||||
app.use("/store", route)
|
||||
|
||||
const featureFlagRouter = container.resolve("featureFlagRouter")
|
||||
const storeCors = config.store_cors || ""
|
||||
|
||||
route.use(
|
||||
cors({
|
||||
origin: parseCorsOrigins(storeCors),
|
||||
@@ -39,7 +41,7 @@ export default (app, container, config) => {
|
||||
authRoutes(route)
|
||||
collectionRoutes(route)
|
||||
customerRoutes(route, container)
|
||||
productRoutes(route)
|
||||
productRoutes(route, featureFlagRouter)
|
||||
productTagsRoutes(route)
|
||||
productTypesRoutes(route)
|
||||
orderRoutes(route)
|
||||
|
||||
+3
-3
@@ -2,7 +2,7 @@ import { IdMap } from "medusa-test-utils"
|
||||
import { request } from "../../../../../helpers/test-request"
|
||||
import {
|
||||
defaultStoreProductCategoryRelations,
|
||||
defaultStoreScope,
|
||||
defaultStoreCategoryScope,
|
||||
defaultStoreProductCategoryFields
|
||||
} from ".."
|
||||
import {
|
||||
@@ -31,7 +31,7 @@ describe("GET /store/product-categories/:id", () => {
|
||||
relations: defaultStoreProductCategoryRelations,
|
||||
select: defaultStoreProductCategoryFields,
|
||||
},
|
||||
defaultStoreScope
|
||||
defaultStoreCategoryScope
|
||||
)
|
||||
})
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("GET /store/product-categories/:id", () => {
|
||||
relations: defaultStoreProductCategoryRelations,
|
||||
select: defaultStoreProductCategoryFields,
|
||||
},
|
||||
defaultStoreScope
|
||||
defaultStoreCategoryScope
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Request, Response } from "express"
|
||||
import ProductCategoryService from "../../../../services/product-category"
|
||||
import { FindParams } from "../../../../types/common"
|
||||
import { transformTreeNodesWithConfig } from "../../../../utils/transformers/tree"
|
||||
import { defaultStoreScope } from "."
|
||||
import { defaultStoreCategoryScope } from "."
|
||||
|
||||
/**
|
||||
* @oas [get] /store/product-categories/{id}
|
||||
@@ -70,7 +70,7 @@ export default async (req: Request, res: Response) => {
|
||||
const productCategory = await productCategoryService.retrieve(
|
||||
id,
|
||||
retrieveConfig,
|
||||
defaultStoreScope
|
||||
defaultStoreCategoryScope
|
||||
)
|
||||
|
||||
res.status(200).json({
|
||||
@@ -80,7 +80,7 @@ export default async (req: Request, res: Response) => {
|
||||
product_category: transformTreeNodesWithConfig(
|
||||
productCategory,
|
||||
retrieveConfig,
|
||||
defaultStoreScope
|
||||
defaultStoreCategoryScope
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ export const defaultStoreProductCategoryRelations = [
|
||||
"category_children",
|
||||
]
|
||||
|
||||
export const defaultStoreScope = {
|
||||
export const defaultStoreCategoryScope = {
|
||||
is_internal: false,
|
||||
is_active: true,
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { Transform } from "class-transformer"
|
||||
import { ProductCategoryService } from "../../../../services"
|
||||
import { extendedFindParamsMixin } from "../../../../types/common"
|
||||
import { optionalBooleanMapper } from "../../../../utils/validators/is-boolean"
|
||||
import { defaultStoreScope } from "."
|
||||
import { defaultStoreCategoryScope } from "."
|
||||
|
||||
/**
|
||||
* @oas [get] /store/product-categories
|
||||
@@ -68,14 +68,14 @@ export default async (req: Request, res: Response) => {
|
||||
)
|
||||
|
||||
const selectors = Object.assign(
|
||||
{ ...defaultStoreScope },
|
||||
{ ...defaultStoreCategoryScope },
|
||||
req.filterableFields
|
||||
)
|
||||
|
||||
const [data, count] = await productCategoryService.listAndCount(
|
||||
selectors,
|
||||
req.listConfig,
|
||||
defaultStoreScope
|
||||
defaultStoreCategoryScope
|
||||
)
|
||||
|
||||
const { limit, offset } = req.validatedQuery
|
||||
|
||||
@@ -18,7 +18,13 @@ describe("GET /store/products", () => {
|
||||
it("calls get product from productSerice", () => {
|
||||
expect(ProductServiceMock.listAndCount).toHaveBeenCalledTimes(1)
|
||||
expect(ProductServiceMock.listAndCount).toHaveBeenCalledWith(
|
||||
{ status: ["published"] },
|
||||
{
|
||||
status: ["published"],
|
||||
categories: {
|
||||
is_active: true,
|
||||
is_internal: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
relations: defaultStoreProductsRelations,
|
||||
select: defaultStoreProductsFields,
|
||||
@@ -49,7 +55,14 @@ describe("GET /store/products", () => {
|
||||
it("calls list from productSerice", () => {
|
||||
expect(ProductServiceMock.listAndCount).toHaveBeenCalledTimes(1)
|
||||
expect(ProductServiceMock.listAndCount).toHaveBeenCalledWith(
|
||||
{ is_giftcard: true, status: ["published"] },
|
||||
{
|
||||
is_giftcard: true,
|
||||
status: ["published"],
|
||||
categories: {
|
||||
is_active: true,
|
||||
is_internal: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
relations: defaultStoreProductsRelations,
|
||||
select: defaultStoreProductsFields,
|
||||
|
||||
@@ -9,10 +9,15 @@ import { validateProductSalesChannelAssociation } from "../../../middlewares/pub
|
||||
import { validateSalesChannelParam } from "../../../middlewares/publishable-api-key/validate-sales-channel-param"
|
||||
import { StoreGetProductsParams } from "./list-products"
|
||||
import { StoreGetProductsProductParams } from "./get-product"
|
||||
import { FlagRouter } from "../../../../utils/flag-router"
|
||||
|
||||
const route = Router()
|
||||
|
||||
export default (app) => {
|
||||
export default (app, featureFlagRouter: FlagRouter) => {
|
||||
if (featureFlagRouter.isFeatureEnabled("product_categories")) {
|
||||
allowedStoreProductsRelations.push("categories")
|
||||
}
|
||||
|
||||
app.use("/products", extendRequestParams, validateSalesChannelParam, route)
|
||||
|
||||
route.use("/:id", validateProductSalesChannelAssociation)
|
||||
|
||||
@@ -21,6 +21,7 @@ import { optionalBooleanMapper } from "../../../../utils/validators/is-boolean"
|
||||
import { IsType } from "../../../../utils/validators/is-type"
|
||||
import { cleanResponseData } from "../../../../utils/clean-response-data"
|
||||
import { Cart, Product } from "../../../../models"
|
||||
import { defaultStoreCategoryScope } from "../product-categories"
|
||||
|
||||
/**
|
||||
* @oas [get] /store/products
|
||||
@@ -199,6 +200,12 @@ export default async (req, res) => {
|
||||
|
||||
// get only published products for store endpoint
|
||||
filterableFields["status"] = ["published"]
|
||||
// store APIs only receive active and public categories to query from
|
||||
filterableFields["categories"] = {
|
||||
...(filterableFields.categories || {}),
|
||||
// Store APIs are only allowed to query active and public categories
|
||||
...defaultStoreCategoryScope
|
||||
}
|
||||
|
||||
if (req.publishableApiKeyScopes?.sales_channel_ids.length) {
|
||||
filterableFields.sales_channel_id =
|
||||
|
||||
@@ -16,7 +16,8 @@ export const ProductCategoryRepository = dataSource
|
||||
.getTreeRepository(ProductCategory)
|
||||
.extend({
|
||||
async findOneWithDescendants(
|
||||
query: FindOneOptions<ProductCategory>
|
||||
query: FindOneOptions<ProductCategory>,
|
||||
treeScope: QuerySelector<ProductCategory> = {}
|
||||
): Promise<ProductCategory | null> {
|
||||
const productCategory = await this.findOne(query)
|
||||
|
||||
@@ -26,7 +27,8 @@ export const ProductCategoryRepository = dataSource
|
||||
|
||||
return sortChildren(
|
||||
// Returns the productCategory with all of its descendants until the last child node
|
||||
await this.findDescendantsTree(productCategory)
|
||||
await this.findDescendantsTree(productCategory),
|
||||
treeScope
|
||||
)
|
||||
},
|
||||
|
||||
|
||||
@@ -9,7 +9,11 @@ import { Product, ProductCategory, ProductVariant } from "../models"
|
||||
import { ExtendedFindConfig } from "../types/common"
|
||||
import { dataSource } from "../loaders/database"
|
||||
import { ProductFilterOptions } from "../types/product"
|
||||
import { buildLegacyFieldsListFrom, isObject } from "../utils"
|
||||
import {
|
||||
buildLegacyFieldsListFrom,
|
||||
isObject,
|
||||
fetchCategoryDescendantsIds,
|
||||
} from "../utils"
|
||||
|
||||
export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
async bulkAddToCollection(
|
||||
@@ -106,6 +110,8 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
>
|
||||
const categoryId = options_.where.category_id as FindOperator<string[]>
|
||||
const discountConditionId = options_.where.discount_condition_id
|
||||
const categoriesQuery = (options_.where.categories ||
|
||||
{}) as FindOptionsWhere<ProductCategory>
|
||||
const includeCategoryChildren =
|
||||
options_.where.include_category_children ?? false
|
||||
|
||||
@@ -115,6 +121,7 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
delete options_.where.category_id
|
||||
delete options_.where.discount_condition_id
|
||||
delete options_.where.include_category_children
|
||||
delete options_.where.categories
|
||||
|
||||
// TODO: move back to the service layer
|
||||
if (q) {
|
||||
@@ -198,7 +205,7 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
}
|
||||
|
||||
if (salesChannelId) {
|
||||
const joinMethod = options_.relations.sales_channel_id
|
||||
const joinMethod = options_.relations.sales_channels
|
||||
? queryBuilder.innerJoinAndSelect.bind(queryBuilder)
|
||||
: queryBuilder.innerJoin.bind(queryBuilder)
|
||||
|
||||
@@ -215,7 +222,7 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
}
|
||||
|
||||
if (categoryId) {
|
||||
const joinMethod = options_.relations.category_id
|
||||
const joinMethod = options_.relations.categories
|
||||
? queryBuilder.innerJoinAndSelect.bind(queryBuilder)
|
||||
: queryBuilder.innerJoin.bind(queryBuilder)
|
||||
|
||||
@@ -224,40 +231,48 @@ export const ProductRepository = dataSource.getRepository(Product).extend({
|
||||
if (includeCategoryChildren) {
|
||||
const categoryRepository =
|
||||
this.manager.getTreeRepository(ProductCategory)
|
||||
|
||||
const categories = await categoryRepository.find({
|
||||
where: { id: In(categoryIds) },
|
||||
where: {
|
||||
id: In(categoryIds),
|
||||
...categoriesQuery,
|
||||
},
|
||||
})
|
||||
|
||||
categoryIds = []
|
||||
for (const category of categories) {
|
||||
const categoryChildren = await categoryRepository.findDescendantsTree(
|
||||
category
|
||||
)
|
||||
|
||||
const getAllIdsRecursively = (productCategory: ProductCategory) => {
|
||||
let result = [productCategory.id]
|
||||
|
||||
;(productCategory.category_children || []).forEach((child) => {
|
||||
result = result.concat(getAllIdsRecursively(child))
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
categoryIds = categoryIds.concat(
|
||||
getAllIdsRecursively(categoryChildren)
|
||||
fetchCategoryDescendantsIds(categoryChildren, categoriesQuery)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
joinMethod(
|
||||
`${productAlias}.categories`,
|
||||
"categories",
|
||||
"categories.id IN (:...categoryIds)",
|
||||
{
|
||||
categoryIds,
|
||||
if (categoryIds.length) {
|
||||
const categoryAlias = "categories"
|
||||
const joinScope = {
|
||||
...categoriesQuery,
|
||||
id: categoryIds,
|
||||
}
|
||||
)
|
||||
const joinWhere = Object.entries(joinScope)
|
||||
.map((entry) => {
|
||||
if (Array.isArray(entry[1])) {
|
||||
return `${categoryAlias}.${entry[0]} IN (:...${entry[0]})`
|
||||
} else {
|
||||
return `${categoryAlias}.${entry[0]} = :${entry[0]}`
|
||||
}
|
||||
})
|
||||
.join(" AND ")
|
||||
|
||||
joinMethod(
|
||||
`${productAlias}.${categoryAlias}`,
|
||||
categoryAlias,
|
||||
joinWhere,
|
||||
joinScope
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (discountConditionId) {
|
||||
|
||||
@@ -32,7 +32,7 @@ describe("ProductCategoryService", () => {
|
||||
expect(productCategoryRepository.findOneWithDescendants).toHaveBeenCalledTimes(1)
|
||||
expect(productCategoryRepository.findOneWithDescendants).toHaveBeenCalledWith({
|
||||
where: { id: validID },
|
||||
})
|
||||
}, {})
|
||||
})
|
||||
|
||||
it("fails on not-found product category id", async () => {
|
||||
|
||||
@@ -101,7 +101,8 @@ class ProductCategoryService extends TransactionBaseService {
|
||||
async retrieve(
|
||||
productCategoryId: string,
|
||||
config: FindConfig<ProductCategory> = {},
|
||||
selector: Selector<ProductCategory> = {}
|
||||
selector: Selector<ProductCategory> = {},
|
||||
treeSelector: QuerySelector<ProductCategory> = {}
|
||||
): Promise<ProductCategory> {
|
||||
if (!isDefined(productCategoryId)) {
|
||||
throw new MedusaError(
|
||||
@@ -116,7 +117,10 @@ class ProductCategoryService extends TransactionBaseService {
|
||||
this.productCategoryRepo_
|
||||
)
|
||||
|
||||
const productCategory = await productCategoryRepo.findOneWithDescendants(query)
|
||||
const productCategory = await productCategoryRepo.findOneWithDescendants(
|
||||
query,
|
||||
treeSelector
|
||||
)
|
||||
|
||||
if (!productCategory) {
|
||||
throw new MedusaError(
|
||||
@@ -306,8 +310,7 @@ class ProductCategoryService extends TransactionBaseService {
|
||||
const targetRank = input.rank
|
||||
const shouldChangeParent =
|
||||
targetParentId !== undefined && targetParentId !== originalParentId
|
||||
const shouldChangeRank =
|
||||
shouldChangeParent || originalRank !== targetRank
|
||||
const shouldChangeRank = shouldChangeParent || originalRank !== targetRank
|
||||
|
||||
return {
|
||||
targetCategoryId: productCategory.id,
|
||||
@@ -436,9 +439,7 @@ class ProductCategoryService extends TransactionBaseService {
|
||||
continue
|
||||
}
|
||||
|
||||
sibling.rank = shouldIncrementRank
|
||||
? sibling.rank + 1
|
||||
: sibling.rank - 1
|
||||
sibling.rank = shouldIncrementRank ? ++sibling.rank : --sibling.rank
|
||||
|
||||
await repository.save(sibling)
|
||||
}
|
||||
|
||||
@@ -10,3 +10,4 @@ export * from "./calculate-price-tax-amount"
|
||||
export * from "./csv-cell-content-formatter"
|
||||
export * from "./exception-formatter"
|
||||
export * from "./db-aware-column"
|
||||
export * from "./product-category"
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { FindOptionsWhere } from "typeorm"
|
||||
import { ProductCategory } from "../../models"
|
||||
import { isDefined } from "medusa-core-utils"
|
||||
|
||||
export const categoryMatchesScope = (
|
||||
category: ProductCategory,
|
||||
query: FindOptionsWhere<ProductCategory>
|
||||
): boolean => {
|
||||
return Object.keys(query ?? {}).every(key => category[key] === query[key])
|
||||
}
|
||||
|
||||
export const fetchCategoryDescendantsIds = (
|
||||
productCategory: ProductCategory,
|
||||
query: FindOptionsWhere<ProductCategory>
|
||||
) => {
|
||||
let result = [productCategory.id]
|
||||
|
||||
;(productCategory.category_children || []).forEach((child) => {
|
||||
if (categoryMatchesScope(child, query)) {
|
||||
result = result.concat(fetchCategoryDescendantsIds(child, query))
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user