Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(medusa): Allow to filter customer groups by discount condition id #2346

Merged
merged 5 commits into from
Oct 11, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
274 changes: 149 additions & 125 deletions integration-tests/api/__tests__/admin/customer-groups.js

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
103 changes: 101 additions & 2 deletions packages/medusa/src/repositories/customer-group.ts
Original file line number Diff line number Diff line change
@@ -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> {
Expand Down Expand Up @@ -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]
}
}
47 changes: 26 additions & 21 deletions packages/medusa/src/services/customer-group.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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
adrien2p marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand All @@ -214,29 +214,34 @@ 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(
this.customerGroupRepository_
)

let q
if ("q" in selector) {
if (isString(selector.q)) {
q = selector.q
delete selector.q
}

const query = buildQuery(selector, config)

if (q) {
const where = query.where

delete where.name
query.where.name = ILike(`%${q}%`)
}

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)
Expand Down
1 change: 1 addition & 0 deletions packages/medusa/src/types/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export type PartialPick<T, K extends keyof T> = {
export type Writable<T> = {
-readonly [key in keyof T]:
| T[key]
| FindOperator<T[key]>
| FindOperator<T[key][]>
| FindOperator<string[]>
}
Expand Down
4 changes: 4 additions & 0 deletions packages/medusa/src/types/customer-groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ export class FilterableCustomerGroupProps {
@ValidateNested()
@Type(() => DateComparisonOperator)
created_at?: DateComparisonOperator

@IsString()
@IsOptional()
discount_condition_id?: string
}

export class CustomerGroupsBatchCustomer {
Expand Down
1 change: 1 addition & 0 deletions packages/medusa/src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export * from "./validate-id"
export * from "./generate-entity-id"
export * from "./remove-undefined-properties"
export * from "./is-defined"
export * from "./is-string"
export * from "./calculate-price-tax-amount"
export * from "./csv-cell-content-formatter"
export * from "./exception-formatter"
3 changes: 3 additions & 0 deletions packages/medusa/src/utils/is-string.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function isString(val: any): val is string {
return val != null && typeof val === "string"
}