|
1
|
import { |
|
2
|
flattenObjectToKeyValuePairs, |
|
3
|
isPresent, |
|
4
|
MedusaError, |
|
5
|
MikroOrmBase, |
|
6
|
normalizeCurrencyCode, |
|
7
|
PriceListStatus, |
|
8
|
} from "@medusajs/framework/utils" |
|
9
|
|
|
10
|
import { |
|
11
|
Knex, |
|
12
|
SqlEntityManager, |
|
13
|
} from "@medusajs/framework/mikro-orm/postgresql" |
|
14
|
import { |
|
15
|
CalculatedPriceSetDTO, |
|
16
|
Context, |
|
17
|
PricingContext, |
|
18
|
PricingFilters, |
|
19
|
PricingRepositoryService, |
|
20
|
} from "@medusajs/framework/types" |
|
21
|
|
|
22
|
export class PricingRepository |
|
23
|
extends MikroOrmBase |
|
24
|
implements PricingRepositoryService |
|
25
|
{ |
|
26
|
#availableAttributes: Set<string> = new Set() |
|
27
|
|
|
28
|
constructor() { |
|
29
|
// @ts-ignore |
|
30
|
// eslint-disable-next-line prefer-rest-params |
|
31
|
super(...arguments) |
|
32
|
} |
|
33
|
|
|
34
|
clearAvailableAttributes() { |
|
35
|
this.#availableAttributes.clear() |
|
36
|
} |
|
37
|
|
|
38
|
async #cacheAvailableAttributes() { |
|
39
|
const manager = this.getActiveManager<SqlEntityManager>() |
|
40
|
const knex = manager.getKnex() |
|
41
|
|
|
42
|
const { rows } = await knex.raw( |
|
43
|
` |
|
44
|
SELECT DISTINCT attribute |
|
45
|
FROM ( |
|
46
|
SELECT attribute |
|
47
|
FROM price_rule |
|
48
|
UNION ALL |
|
49
|
SELECT attribute |
|
50
|
FROM price_list_rule |
|
51
|
) as combined_rules_attributes |
|
52
|
` |
|
53
|
) |
|
54
|
this.#availableAttributes.clear() |
|
55
|
rows.forEach(({ attribute }: { attribute: string }) => { |
|
56
|
this.#availableAttributes.add(attribute) |
|
57
|
}) |
|
58
|
} |
|
59
|
|
|
60
|
async #cacheAvailableAttributesIfNecessary() { |
|
61
|
if (this.#availableAttributes.size === 0) { |
|
62
|
await this.#cacheAvailableAttributes() |
|
63
|
} |
|
64
|
} |
|
65
|
|
|
66
|
async calculatePrices( |
|
67
|
pricingFilters: PricingFilters, |
|
68
|
pricingContext: PricingContext = { context: {} }, |
|
69
|
sharedContext: Context = {} |
|
70
|
): Promise<CalculatedPriceSetDTO[]> { |
|
71
|
const manager = this.getActiveManager<SqlEntityManager>(sharedContext) |
|
72
|
const knex = manager.getKnex() |
|
73
|
const context = { ...(pricingContext.context || {}) } |
|
74
|
|
|
75
|
// Extract quantity and currency from context |
|
76
|
const quantity = context.quantity as number | undefined |
|
77
|
delete context.quantity |
|
78
|
|
|
79
|
// Currency code is required |
|
80
|
const currencyCode = context.currency_code as string | undefined |
|
81
|
delete context.currency_code |
|
82
|
|
|
83
|
if (!currencyCode) { |
|
84
|
throw new MedusaError( |
|
85
|
MedusaError.Types.INVALID_DATA, |
|
86
|
`Method calculatePrices requires currency_code in the pricing context` |
|
87
|
) |
|
88
|
} |
|
89
|
|
|
90
|
// Generate flatten key-value pairs for rule matching |
|
91
|
const flattenedKeyValuePairs = flattenObjectToKeyValuePairs(context) |
|
92
|
|
|
93
|
// First filter by value presence |
|
94
|
let flattenedContext = Object.entries(flattenedKeyValuePairs).filter( |
|
95
|
([, value]) => { |
|
96
|
const isValuePresent = !Array.isArray(value) && isPresent(value) |
|
97
|
const isArrayPresent = Array.isArray(value) && value.flat(1).length |
|
98
|
|
|
99
|
return isValuePresent || isArrayPresent |
|
100
|
} |
|
101
|
) |
|
102
|
|
|
103
|
if (flattenedContext.length > 10) { |
|
104
|
await this.#cacheAvailableAttributesIfNecessary() |
|
105
|
flattenedContext = flattenedContext.filter(([key]) => |
|
106
|
this.#availableAttributes.has(key) |
|
107
|
) |
|
108
|
} |
|
109
|
|
|
110
|
const hasComplexContext = flattenedContext.length > 0 |
|
111
|
|
|
112
|
const query = knex |
|
113
|
.select({ |
|
114
|
id: "price.id", |
|
115
|
price_set_id: "price.price_set_id", |
|
116
|
amount: "price.amount", |
|
117
|
raw_amount: "price.raw_amount", |
|
118
|
min_quantity: "price.min_quantity", |
|
119
|
max_quantity: "price.max_quantity", |
|
120
|
currency_code: "price.currency_code", |
|
121
|
price_list_id: "price.price_list_id", |
|
122
|
price_list_type: "pl.type", |
|
123
|
rules_count: "price.rules_count", |
|
124
|
price_list_rules_count: "pl.rules_count", |
|
125
|
}) |
|
126
|
.from("price") |
|
127
|
.whereIn("price.price_set_id", pricingFilters.id) |
|
128
|
.andWhere( |
|
129
|
"price.currency_code", |
|
130
|
normalizeCurrencyCode(currencyCode ?? "") |
|
131
|
) |
|
132
|
.whereNull("price.deleted_at") |
|
133
|
|
|
134
|
if (quantity !== undefined) { |
|
135
|
query.andWhere(function (this: Knex.QueryBuilder) { |
|
136
|
this.orWhere(function (this: Knex.QueryBuilder) { |
|
137
|
this.where("price.min_quantity", "<=", quantity).andWhere( |
|
138
|
"price.max_quantity", |
|
139
|
">=", |
|
140
|
quantity |
|
141
|
) |
|
142
|
|
|
143
|
this.orWhere("price.min_quantity", "<=", quantity).whereNull( |
|
144
|
"price.max_quantity" |
|
145
|
) |
|
146
|
|
|
147
|
this.orWhereNull("price.min_quantity").whereNull("price.max_quantity") |
|
148
|
|
|
149
|
this.orWhereNull("price.min_quantity").andWhere( |
|
150
|
"price.max_quantity", |
|
151
|
">=", |
|
152
|
quantity |
|
153
|
) |
|
154
|
}) |
|
155
|
}) |
|
156
|
} else { |
|
157
|
query.andWhere(function (this: Knex.QueryBuilder) { |
|
158
|
this.where("price.min_quantity", "<=", 1).orWhereNull( |
|
159
|
"price.min_quantity" |
|
160
|
) |
|
161
|
}) |
|
162
|
} |
|
163
|
|
|
164
|
if (hasComplexContext) { |
|
165
|
// Build match conditions for LATERAL join |
|
166
|
const priceRuleMatchConditions = flattenedContext |
|
167
|
.map(([_key, value]) => { |
|
168
|
if (typeof value === "number") { |
|
169
|
return ` |
|
170
|
(pr.attribute = ? AND ( |
|
171
|
(pr.operator = 'eq' AND pr.value = ?) OR |
|
172
|
(pr.operator = 'gt' AND ? > pr.value::numeric) OR |
|
173
|
(pr.operator = 'gte' AND ? >= pr.value::numeric) OR |
|
174
|
(pr.operator = 'lt' AND ? < pr.value::numeric) OR |
|
175
|
(pr.operator = 'lte' AND ? <= pr.value::numeric) |
|
176
|
)) |
|
177
|
` |
|
178
|
} else { |
|
179
|
const normalizeValue = Array.isArray(value) ? value : [value] |
|
180
|
const placeholders = normalizeValue.map(() => "?").join(",") |
|
181
|
return `(pr.attribute = ? AND pr.value IN (${placeholders}))` |
|
182
|
} |
|
183
|
}) |
|
184
|
.join(" OR ") |
|
185
|
|
|
186
|
const priceRuleMatchParams = flattenedContext.flatMap(([key, value]) => { |
|
187
|
if (typeof value === "number") { |
|
188
|
return [key, value.toString(), value, value, value, value] |
|
189
|
} else { |
|
190
|
const normalizeValue = Array.isArray(value) ? value : [value] |
|
191
|
return [key, ...normalizeValue] |
|
192
|
} |
|
193
|
}) |
|
194
|
|
|
195
|
const priceListRuleMatchConditions = flattenedContext |
|
196
|
.map(([_key, value]) => { |
|
197
|
if (Array.isArray(value)) { |
|
198
|
return value |
|
199
|
.map((_v) => `(plr.attribute = ? AND plr.value @> ?)`) |
|
200
|
.join(" OR ") |
|
201
|
} |
|
202
|
return `(plr.attribute = ? AND plr.value @> ?)` |
|
203
|
}) |
|
204
|
.join(" OR ") |
|
205
|
|
|
206
|
const priceListRuleMatchParams = flattenedContext.flatMap( |
|
207
|
([key, value]) => { |
|
208
|
const valueAsArray = Array.isArray(value) ? value : [value] |
|
209
|
return valueAsArray.flatMap((v) => [key, JSON.stringify(v)]) |
|
210
|
} |
|
211
|
) |
|
212
|
|
|
213
|
// Pre-resolve the active price lists whose rules all match the context |
|
214
|
// in a single pass over price_list/price_list_rule, instead of running |
|
215
|
// a LATERAL scan of price_list_rule for every candidate price row. With |
|
216
|
// N price lists, the per-row LATERAL costs O(candidate prices x N); |
|
217
|
// this derived table stays flat because prices of non-matching price |
|
218
|
// lists are dropped by the join before rule evaluation. |
|
219
|
query.leftJoin( |
|
220
|
knex.raw( |
|
221
|
`( |
|
222
|
SELECT pl.id, pl.type, pl.rules_count |
|
223
|
FROM price_list pl |
|
224
|
WHERE pl.status = ? |
|
225
|
AND pl.deleted_at IS NULL |
|
226
|
AND (pl.starts_at IS NULL OR pl.starts_at <= now()) |
|
227
|
AND (pl.ends_at IS NULL OR pl.ends_at >= now()) |
|
228
|
AND ( |
|
229
|
pl.rules_count = 0 |
|
230
|
OR pl.rules_count = ( |
|
231
|
SELECT COUNT(*) FILTER (WHERE ${priceListRuleMatchConditions}) |
|
232
|
FROM price_list_rule plr |
|
233
|
WHERE plr.price_list_id = pl.id |
|
234
|
AND plr.deleted_at IS NULL |
|
235
|
) |
|
236
|
) |
|
237
|
) as pl`, |
|
238
|
[PriceListStatus.ACTIVE, ...priceListRuleMatchParams] |
|
239
|
), |
|
240
|
"pl.id", |
|
241
|
"price.price_list_id" |
|
242
|
) |
|
243
|
|
|
244
|
// Use a LATERAL join to compute matched and total counts in one go |
|
245
|
query.leftJoin( |
|
246
|
knex.raw( |
|
247
|
`LATERAL ( |
|
248
|
SELECT |
|
249
|
COUNT(*) FILTER (WHERE ${priceRuleMatchConditions}) as matched_count, |
|
250
|
COUNT(*) as total_count |
|
251
|
FROM price_rule pr |
|
252
|
WHERE pr.price_id = price.id |
|
253
|
AND pr.deleted_at IS NULL |
|
254
|
) pr_stats`, |
|
255
|
priceRuleMatchParams |
|
256
|
), |
|
257
|
knex.raw("true") |
|
258
|
) |
|
259
|
|
|
260
|
query.where((qb) => { |
|
261
|
qb.where((qb2) => { |
|
262
|
// No price list: price rules must match or be zero |
|
263
|
qb2.whereNull("price.price_list_id").andWhere((qb3) => { |
|
264
|
qb3 |
|
265
|
.where("price.rules_count", 0) |
|
266
|
.orWhereRaw("pr_stats.matched_count = price.rules_count") |
|
267
|
}) |
|
268
|
}).orWhere((qb2) => { |
|
269
|
// Has price list: the list must have survived the pre-filtered join |
|
270
|
// (all of its rules matched) and price rules must match or be zero |
|
271
|
qb2 |
|
272
|
.whereNotNull("price.price_list_id") |
|
273
|
.whereNotNull("pl.id") |
|
274
|
.andWhere((qb3) => { |
|
275
|
qb3 |
|
276
|
.where("price.rules_count", 0) |
|
277
|
.orWhereRaw("pr_stats.matched_count = price.rules_count") |
|
278
|
}) |
|
279
|
}) |
|
280
|
}) |
|
281
|
} else { |
|
282
|
query.leftJoin("price_list as pl", function (this: Knex.JoinClause) { |
|
283
|
this.on("pl.id", "=", "price.price_list_id") |
|
284
|
.andOn("pl.status", "=", knex.raw("?", [PriceListStatus.ACTIVE])) |
|
285
|
.andOn(function (this: Knex.JoinClause) { |
|
286
|
this.onNull("pl.deleted_at") |
|
287
|
}) |
|
288
|
.andOn(function (this: Knex.JoinClause) { |
|
289
|
this.onNull("pl.starts_at").orOn( |
|
290
|
"pl.starts_at", |
|
291
|
"<=", |
|
292
|
knex.fn.now() |
|
293
|
) |
|
294
|
}) |
|
295
|
.andOn(function (this: Knex.JoinClause) { |
|
296
|
this.onNull("pl.ends_at").orOn("pl.ends_at", ">=", knex.fn.now()) |
|
297
|
}) |
|
298
|
}) |
|
299
|
|
|
300
|
query.where(function (this: Knex.QueryBuilder) { |
|
301
|
this.where(function (this: Knex.QueryBuilder) { |
|
302
|
this.whereNull("price.price_list_id").where("price.rules_count", 0) |
|
303
|
}).orWhere(function (this: Knex.QueryBuilder) { |
|
304
|
this.whereNotNull("price.price_list_id").where("price.rules_count", 0).where("pl.rules_count", 0) |
|
305
|
}) |
|
306
|
}) |
|
307
|
} |
|
308
|
|
|
309
|
query |
|
310
|
.orderByRaw("price.price_list_id IS NOT NULL DESC") |
|
311
|
.orderByRaw("price.rules_count + COALESCE(pl.rules_count, 0) DESC") |
|
312
|
.orderBy("price.amount", "asc") |
|
313
|
|
|
314
|
return await query |
|
315
|
} |
|
316
|
} |