-
-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
customer-group.ts
284 lines (245 loc) · 7.72 KB
/
customer-group.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { isDefined, MedusaError } from "medusa-core-utils"
import { DeepPartial, EntityManager, FindOptionsWhere, ILike } from "typeorm"
import { CustomerService } from "."
import { CustomerGroup } from ".."
import {
CustomerGroupRepository,
FindWithoutRelationsOptions,
} from "../repositories/customer-group"
import { FindConfig, Selector } from "../types/common"
import { CustomerGroupUpdate } from "../types/customer-groups"
import { buildQuery, isString, PostgresError, setMetadata } from "../utils"
import { TransactionBaseService } from "../interfaces"
type CustomerGroupConstructorProps = {
manager: EntityManager
customerGroupRepository: typeof CustomerGroupRepository
customerService: CustomerService
}
class CustomerGroupService extends TransactionBaseService {
protected readonly customerGroupRepository_: typeof CustomerGroupRepository
protected readonly customerService_: CustomerService
constructor({
customerGroupRepository,
customerService,
}: CustomerGroupConstructorProps) {
// eslint-disable-next-line prefer-rest-params
super(arguments[0])
this.customerGroupRepository_ = customerGroupRepository
this.customerService_ = customerService
}
async retrieve(customerGroupId: string, config = {}): Promise<CustomerGroup> {
if (!isDefined(customerGroupId)) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`"customerGroupId" must be defined`
)
}
const cgRepo = this.activeManager_.withRepository(
this.customerGroupRepository_
)
const query = buildQuery({ id: customerGroupId }, config)
const customerGroup = await cgRepo.findOne(query)
if (!customerGroup) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`CustomerGroup with id ${customerGroupId} was not found`
)
}
return customerGroup
}
/**
* Creates a customer group with the provided data.
* @param group - the customer group to create
* @return the result of the create operation
*/
async create(group: DeepPartial<CustomerGroup>): Promise<CustomerGroup> {
return await this.atomicPhase_(async (manager) => {
try {
const cgRepo: typeof CustomerGroupRepository = manager.withRepository(
this.customerGroupRepository_
)
const created = cgRepo.create(group)
return await cgRepo.save(created)
} catch (err) {
if (err.code === PostgresError.DUPLICATE_ERROR) {
throw new MedusaError(MedusaError.Types.DUPLICATE_ERROR, err.detail)
}
throw err
}
})
}
/**
* Add a batch of customers to a customer group at once
* @param id id of the customer group to add customers to
* @param customerIds customer id's to add to the group
* @return the customer group after insertion
*/
async addCustomers(
id: string,
customerIds: string | string[]
): Promise<CustomerGroup> {
let ids: string[]
if (typeof customerIds === "string") {
ids = [customerIds]
} else {
ids = customerIds
}
return await this.atomicPhase_(
async (manager) => {
const cgRepo: typeof CustomerGroupRepository = manager.withRepository(
this.customerGroupRepository_
)
return await cgRepo.addCustomers(id, ids)
},
async (e: any) => {
await this.handleCreationFail(id, ids, e)
}
)
}
/**
* Update a customer group.
*
* @param customerGroupId - id of the customer group
* @param update - customer group partial data
* @returns resulting customer group
*/
async update(
customerGroupId: string,
update: CustomerGroupUpdate
): Promise<CustomerGroup> {
return await this.atomicPhase_(async (manager) => {
const { metadata, ...properties } = update
const cgRepo: typeof CustomerGroupRepository = manager.withRepository(
this.customerGroupRepository_
)
const customerGroup = await this.retrieve(customerGroupId)
for (const key in properties) {
if (isDefined(properties[key])) {
customerGroup[key] = properties[key]
}
}
if (isDefined(metadata)) {
customerGroup.metadata = setMetadata(customerGroup, metadata)
}
return await cgRepo.save(customerGroup)
})
}
/**
* Remove customer group
*
* @param groupId id of the customer group to delete
* @return a promise
*/
async delete(groupId: string): Promise<void> {
return await this.atomicPhase_(async (manager) => {
const cgRepo: typeof CustomerGroupRepository = manager.withRepository(
this.customerGroupRepository_
)
const customerGroup = await cgRepo.findOne({ where: { id: groupId } })
if (customerGroup) {
await cgRepo.remove(customerGroup)
}
return Promise.resolve()
})
}
/**
* List customer groups.
*
* @param selector - the query object for find
* @param config - the config to be used for find
* @return the result of the find operation
*/
async list(
selector: Selector<CustomerGroup> & {
q?: string
discount_condition_id?: string
} = {},
config: FindConfig<CustomerGroup>
): Promise<CustomerGroup[]> {
const [customerGroups] = await this.listAndCount(selector, config)
return customerGroups
}
/**
* Retrieve a list of customer groups and total count of records that match the query.
*
* @param selector - the query object for find
* @param config - the config to be used for find
* @return the result of the find operation
*/
async listAndCount(
selector: Selector<CustomerGroup> & {
q?: string
discount_condition_id?: string
} = {},
config: FindConfig<CustomerGroup>
): Promise<[CustomerGroup[], number]> {
const cgRepo = this.activeManager_.withRepository(
this.customerGroupRepository_
)
let q
if (isString(selector.q)) {
q = selector.q
delete selector.q
}
const query = buildQuery<Selector<CustomerGroup>, any>(selector, config)
query.where = query.where as FindOptionsWhere<CustomerGroup>
if (q) {
query.where.name = ILike(`%${q}%`)
}
if (query.where.discount_condition_id) {
const { relations, ...query_ } = query
return await cgRepo.findWithRelationsAndCount(
relations,
query_ as FindWithoutRelationsOptions
)
}
return await cgRepo.findAndCount(query)
}
/**
* Remove list of customers from a customergroup
*
* @param id id of the customer group from which the customers are removed
* @param customerIds id's of the customer to remove from group
* @return the customergroup with the provided id
*/
async removeCustomer(
id: string,
customerIds: string[] | string
): Promise<CustomerGroup> {
const cgRepo = this.activeManager_.withRepository(
this.customerGroupRepository_
)
let ids: string[]
if (typeof customerIds === "string") {
ids = [customerIds]
} else {
ids = customerIds
}
const customerGroup = await this.retrieve(id)
await cgRepo.removeCustomers(id, ids)
return customerGroup
}
private async handleCreationFail(
id: string,
ids: string[],
error: any
): Promise<never> {
if (error.code === PostgresError.FOREIGN_KEY_ERROR) {
await this.retrieve(id)
const existingCustomers = await this.customerService_.list({
id: ids,
})
const nonExistingCustomers = ids.filter(
(cId) => existingCustomers.findIndex((el) => el.id === cId) === -1
)
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`The following customer ids do not exist: ${JSON.stringify(
nonExistingCustomers.join(", ")
)}`
)
}
throw error
}
}
export default CustomerGroupService