feat(medusa): Allow to filter customer groups by discount condition id (#2346)
This commit is contained in:
@@ -15,6 +15,7 @@ import { Type } from "class-transformer"
|
||||
* - (query) q {string} Query used for searching customer group names.
|
||||
* - (query) offset=0 {integer} How many groups to skip in the result.
|
||||
* - (query) order {string} the field used to order the customer groups.
|
||||
* - (query) discount_condition_id {string} The discount condition id on which to filter the customer groups.
|
||||
* - in: query
|
||||
* name: id
|
||||
* style: form
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
import { DeleteResult, EntityRepository, In, Repository } from "typeorm"
|
||||
import { CustomerGroup } from "../models/customer-group"
|
||||
import {
|
||||
DeleteResult,
|
||||
EntityRepository,
|
||||
FindOperator,
|
||||
In,
|
||||
Repository,
|
||||
SelectQueryBuilder,
|
||||
} from "typeorm"
|
||||
import { CustomerGroup } from "../models"
|
||||
import { ExtendedFindConfig, Writable } from "../types/common"
|
||||
import {
|
||||
getGroupedRelations,
|
||||
mergeEntitiesWithRelations,
|
||||
queryEntityWithIds,
|
||||
queryEntityWithoutRelations,
|
||||
} from "../utils/repository"
|
||||
|
||||
export type DefaultWithoutRelations = Omit<
|
||||
ExtendedFindConfig<CustomerGroup, Partial<Writable<CustomerGroup>>>,
|
||||
"relations"
|
||||
>
|
||||
|
||||
export type FindWithoutRelationsOptions = DefaultWithoutRelations & {
|
||||
where: DefaultWithoutRelations["where"] & {
|
||||
discount_condition_id?: string | FindOperator<string>
|
||||
}
|
||||
}
|
||||
|
||||
@EntityRepository(CustomerGroup)
|
||||
export class CustomerGroupRepository extends Repository<CustomerGroup> {
|
||||
@@ -37,4 +62,78 @@ export class CustomerGroupRepository extends Repository<CustomerGroup> {
|
||||
})
|
||||
.execute()
|
||||
}
|
||||
|
||||
public async findWithRelationsAndCount(
|
||||
relations: string[] = [],
|
||||
idsOrOptionsWithoutRelations: FindWithoutRelationsOptions = { where: {} }
|
||||
): Promise<[CustomerGroup[], number]> {
|
||||
let count: number
|
||||
let entities: CustomerGroup[]
|
||||
if (Array.isArray(idsOrOptionsWithoutRelations)) {
|
||||
entities = await this.findByIds(idsOrOptionsWithoutRelations, {
|
||||
withDeleted: idsOrOptionsWithoutRelations.withDeleted ?? false,
|
||||
})
|
||||
count = entities.length
|
||||
} else {
|
||||
const customJoinsBuilders: ((
|
||||
qb: SelectQueryBuilder<CustomerGroup>,
|
||||
alias: string
|
||||
) => void)[] = []
|
||||
|
||||
if (idsOrOptionsWithoutRelations?.where?.discount_condition_id) {
|
||||
const discountConditionId =
|
||||
idsOrOptionsWithoutRelations?.where?.discount_condition_id
|
||||
delete idsOrOptionsWithoutRelations?.where?.discount_condition_id
|
||||
|
||||
customJoinsBuilders.push(
|
||||
(qb: SelectQueryBuilder<CustomerGroup>, alias: string) => {
|
||||
qb.innerJoin(
|
||||
"discount_condition_customer_group",
|
||||
"dc_cg",
|
||||
`dc_cg.customer_group_id = ${alias}.id AND dc_cg.condition_id = :dcId`,
|
||||
{ dcId: discountConditionId }
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
const result = await queryEntityWithoutRelations(
|
||||
this,
|
||||
idsOrOptionsWithoutRelations,
|
||||
true,
|
||||
customJoinsBuilders
|
||||
)
|
||||
entities = result[0]
|
||||
count = result[1]
|
||||
}
|
||||
const entitiesIds = entities.map(({ id }) => id)
|
||||
|
||||
if (entitiesIds.length === 0) {
|
||||
// no need to continue
|
||||
return [[], count]
|
||||
}
|
||||
|
||||
if (relations.length === 0) {
|
||||
const toReturn = await this.findByIds(
|
||||
entitiesIds,
|
||||
idsOrOptionsWithoutRelations
|
||||
)
|
||||
return [toReturn, toReturn.length]
|
||||
}
|
||||
|
||||
const groupedRelations = getGroupedRelations(relations)
|
||||
const entitiesIdsWithRelations = await queryEntityWithIds(
|
||||
this,
|
||||
entitiesIds,
|
||||
groupedRelations,
|
||||
idsOrOptionsWithoutRelations.withDeleted,
|
||||
idsOrOptionsWithoutRelations.select
|
||||
)
|
||||
|
||||
const entitiesAndRelations = entitiesIdsWithRelations.concat(entities)
|
||||
const entitiesToReturn =
|
||||
mergeEntitiesWithRelations<CustomerGroup>(entitiesAndRelations)
|
||||
|
||||
return [entitiesToReturn, count]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import { MedusaError } from "medusa-core-utils"
|
||||
import { DeepPartial, EntityManager, ILike, SelectQueryBuilder } from "typeorm"
|
||||
import { DeepPartial, EntityManager, ILike } from "typeorm"
|
||||
import { CustomerService } from "."
|
||||
import { CustomerGroup } from ".."
|
||||
import { CustomerGroupRepository } from "../repositories/customer-group"
|
||||
import { FindConfig } from "../types/common"
|
||||
import {
|
||||
CustomerGroupUpdate,
|
||||
FilterableCustomerGroupProps,
|
||||
} from "../types/customer-groups"
|
||||
CustomerGroupRepository,
|
||||
FindWithoutRelationsOptions,
|
||||
} from "../repositories/customer-group"
|
||||
import { FindConfig } from "../types/common"
|
||||
import { CustomerGroupUpdate } from "../types/customer-groups"
|
||||
import {
|
||||
buildQuery,
|
||||
formatException,
|
||||
isDefined,
|
||||
isString,
|
||||
PostgresError,
|
||||
setMetadata,
|
||||
} from "../utils"
|
||||
@@ -195,15 +196,14 @@ class CustomerGroupService extends TransactionBaseService {
|
||||
* @return the result of the find operation
|
||||
*/
|
||||
async list(
|
||||
selector: FilterableCustomerGroupProps = {},
|
||||
selector: Partial<CustomerGroup> & {
|
||||
q?: string
|
||||
discount_condition_id?: string
|
||||
} = {},
|
||||
config: FindConfig<CustomerGroup>
|
||||
): Promise<CustomerGroup[]> {
|
||||
const cgRepo: CustomerGroupRepository = this.manager_.getCustomRepository(
|
||||
this.customerGroupRepository_
|
||||
)
|
||||
|
||||
const query = buildQuery(selector, config)
|
||||
return await cgRepo.find(query)
|
||||
const [customerGroups] = await this.listAndCount(selector, config)
|
||||
return customerGroups
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -214,7 +214,10 @@ class CustomerGroupService extends TransactionBaseService {
|
||||
* @return the result of the find operation
|
||||
*/
|
||||
async listAndCount(
|
||||
selector: FilterableCustomerGroupProps = {},
|
||||
selector: Partial<CustomerGroup> & {
|
||||
q?: string
|
||||
discount_condition_id?: string
|
||||
} = {},
|
||||
config: FindConfig<CustomerGroup>
|
||||
): Promise<[CustomerGroup[], number]> {
|
||||
const cgRepo: CustomerGroupRepository = this.manager_.getCustomRepository(
|
||||
@@ -222,7 +225,7 @@ class CustomerGroupService extends TransactionBaseService {
|
||||
)
|
||||
|
||||
let q
|
||||
if ("q" in selector) {
|
||||
if (isString(selector.q)) {
|
||||
q = selector.q
|
||||
delete selector.q
|
||||
}
|
||||
@@ -230,13 +233,15 @@ class CustomerGroupService extends TransactionBaseService {
|
||||
const query = buildQuery(selector, config)
|
||||
|
||||
if (q) {
|
||||
const where = query.where
|
||||
query.where.name = ILike(`%${q}%`)
|
||||
}
|
||||
|
||||
delete where.name
|
||||
|
||||
query.where = ((qb: SelectQueryBuilder<CustomerGroup>): void => {
|
||||
qb.where(where).andWhere([{ name: ILike(`%${q}%`) }])
|
||||
}) as any
|
||||
if (query.where.discount_condition_id) {
|
||||
const { relations, ...query_ } = query
|
||||
return await cgRepo.findWithRelationsAndCount(
|
||||
relations,
|
||||
query_ as FindWithoutRelationsOptions
|
||||
)
|
||||
}
|
||||
|
||||
return await cgRepo.findAndCount(query)
|
||||
|
||||
@@ -28,6 +28,10 @@ export class FilterableCustomerGroupProps {
|
||||
@ValidateNested()
|
||||
@Type(() => DateComparisonOperator)
|
||||
created_at?: DateComparisonOperator
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
discount_condition_id?: string
|
||||
}
|
||||
|
||||
export class CustomerGroupsBatchCustomer {
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { flatten, groupBy, map, merge } from "lodash"
|
||||
import { Repository, SelectQueryBuilder } from "typeorm"
|
||||
import { FindWithoutRelationsOptions } from "../repositories/customer-group"
|
||||
|
||||
/**
|
||||
* Custom query entity, it is part of the creation of a custom findWithRelationsAndCount needs.
|
||||
* Allow to query the relations for the specified entity ids
|
||||
* @param repository
|
||||
* @param entityIds
|
||||
* @param groupedRelations
|
||||
* @param withDeleted
|
||||
* @param select
|
||||
*/
|
||||
export async function queryEntityWithIds<T>(
|
||||
repository: Repository<T>,
|
||||
entityIds: string[],
|
||||
groupedRelations: { [toplevel: string]: string[] },
|
||||
withDeleted = false,
|
||||
select: (keyof T)[] = []
|
||||
): Promise<T[]> {
|
||||
const alias = repository.constructor.name
|
||||
return await Promise.all(
|
||||
Object.entries(groupedRelations).map(async ([toplevel, rels]) => {
|
||||
let querybuilder = repository.createQueryBuilder(`${alias}`)
|
||||
|
||||
if (select && select.length) {
|
||||
querybuilder.select(select.map((f) => `${alias}.${f as string}`))
|
||||
}
|
||||
|
||||
querybuilder = querybuilder.leftJoinAndSelect(
|
||||
`${alias}.${toplevel}`,
|
||||
toplevel
|
||||
)
|
||||
|
||||
for (const rel of rels) {
|
||||
const [_, rest] = rel.split(".")
|
||||
if (!rest) {
|
||||
continue
|
||||
}
|
||||
// Regex matches all '.' except the rightmost
|
||||
querybuilder = querybuilder.leftJoinAndSelect(
|
||||
rel.replace(/\.(?=[^.]*\.)/g, "__"),
|
||||
rel.replace(".", "__")
|
||||
)
|
||||
}
|
||||
|
||||
if (withDeleted) {
|
||||
querybuilder = querybuilder
|
||||
.where(`${alias}.id IN (:...entitiesIds)`, {
|
||||
entitiesIds: entityIds,
|
||||
})
|
||||
.withDeleted()
|
||||
} else {
|
||||
querybuilder = querybuilder.where(
|
||||
`${alias}.deleted_at IS NULL AND products.id IN (:...entitiesIds)`,
|
||||
{
|
||||
entitiesIds: entityIds,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return querybuilder.getMany()
|
||||
})
|
||||
).then(flatten)
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom query entity without relations, it is part of the creation of a custom findWithRelationsAndCount needs.
|
||||
* Allow to query the entities without taking into account the relations. The relations will be queried separately
|
||||
* using the queryEntityWithIds util
|
||||
* @param repository
|
||||
* @param optionsWithoutRelations
|
||||
* @param shouldCount
|
||||
* @param customJoinBuilders
|
||||
*/
|
||||
export async function queryEntityWithoutRelations<T>(
|
||||
repository: Repository<T>,
|
||||
optionsWithoutRelations: FindWithoutRelationsOptions,
|
||||
shouldCount = false,
|
||||
customJoinBuilders: ((
|
||||
qb: SelectQueryBuilder<T>,
|
||||
alias: string
|
||||
) => void)[] = []
|
||||
): Promise<[T[], number]> {
|
||||
const alias = repository.constructor.name
|
||||
|
||||
const qb = repository
|
||||
.createQueryBuilder(alias)
|
||||
.select([`${alias}.id`])
|
||||
.skip(optionsWithoutRelations.skip)
|
||||
.take(optionsWithoutRelations.take)
|
||||
|
||||
if (optionsWithoutRelations.where) {
|
||||
qb.where(optionsWithoutRelations.where)
|
||||
}
|
||||
|
||||
if (optionsWithoutRelations.order) {
|
||||
const toSelect: string[] = []
|
||||
const parsed = Object.entries(optionsWithoutRelations.order).reduce(
|
||||
(acc, [k, v]) => {
|
||||
const key = `${alias}.${k}`
|
||||
toSelect.push(key)
|
||||
acc[key] = v
|
||||
return acc
|
||||
},
|
||||
{}
|
||||
)
|
||||
qb.addSelect(toSelect)
|
||||
qb.orderBy(parsed)
|
||||
}
|
||||
|
||||
for (const customJoinBuilder of customJoinBuilders) {
|
||||
customJoinBuilder(qb, alias)
|
||||
}
|
||||
|
||||
if (optionsWithoutRelations.withDeleted) {
|
||||
qb.withDeleted()
|
||||
}
|
||||
|
||||
let entities: T[]
|
||||
let count = 0
|
||||
if (shouldCount) {
|
||||
const result = await qb.getManyAndCount()
|
||||
entities = result[0]
|
||||
count = result[1]
|
||||
} else {
|
||||
entities = await qb.getMany()
|
||||
}
|
||||
|
||||
return [entities, count]
|
||||
}
|
||||
|
||||
/**
|
||||
* Grouped the relation to the top level entity
|
||||
* @param relations
|
||||
*/
|
||||
export function getGroupedRelations(relations: string[]): {
|
||||
[toplevel: string]: string[]
|
||||
} {
|
||||
const groupedRelations: { [toplevel: string]: string[] } = {}
|
||||
for (const rel of relations) {
|
||||
const [topLevel] = rel.split(".")
|
||||
if (groupedRelations[topLevel]) {
|
||||
groupedRelations[topLevel].push(rel)
|
||||
} else {
|
||||
groupedRelations[topLevel] = [rel]
|
||||
}
|
||||
}
|
||||
|
||||
return groupedRelations
|
||||
}
|
||||
|
||||
/**
|
||||
* Merged the entities and relations that composed by the result of queryEntityWithIds and queryEntityWithoutRelations
|
||||
* call
|
||||
* @param entitiesAndRelations
|
||||
*/
|
||||
export function mergeEntitiesWithRelations<T>(
|
||||
entitiesAndRelations: Array<Partial<T>>
|
||||
): T[] {
|
||||
const entitiesAndRelationsById = groupBy(entitiesAndRelations, "id")
|
||||
return map(entitiesAndRelationsById, (entityAndRelations) =>
|
||||
merge({}, ...entityAndRelations)
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user