@medusajs/pricing 0.1.13-snapshot-20240607093839 → 0.1.13-snapshot-20240703074611

Sign up to get free protection for your applications and to get access to all the features.
Files changed (43) hide show
  1. package/dist/index.d.ts +2 -3
  2. package/dist/index.js +7 -4
  3. package/dist/joiner-config.d.ts +1 -8
  4. package/dist/joiner-config.js +10 -52
  5. package/dist/migrations/Migration20240626133555.d.ts +4 -0
  6. package/dist/migrations/Migration20240626133555.js +33 -0
  7. package/dist/models/index.d.ts +0 -3
  8. package/dist/models/index.js +1 -7
  9. package/dist/models/price-list-rule.d.ts +4 -7
  10. package/dist/models/price-list-rule.js +6 -27
  11. package/dist/models/price-list.d.ts +0 -2
  12. package/dist/models/price-list.js +0 -9
  13. package/dist/models/price-rule.d.ts +3 -8
  14. package/dist/models/price-rule.js +4 -43
  15. package/dist/models/price-set.d.ts +0 -4
  16. package/dist/models/price-set.js +0 -19
  17. package/dist/models/price.d.ts +3 -3
  18. package/dist/models/price.js +1 -1
  19. package/dist/repositories/pricing.js +25 -30
  20. package/dist/services/index.d.ts +0 -2
  21. package/dist/services/index.js +1 -5
  22. package/dist/services/pricing-module.d.ts +50 -48
  23. package/dist/services/pricing-module.js +293 -482
  24. package/dist/types/services/price-list.d.ts +9 -9
  25. package/dist/utils/events.d.ts +0 -6
  26. package/dist/utils/events.js +6 -12
  27. package/package.json +7 -10
  28. package/dist/models/price-list-rule-value.d.ts +0 -17
  29. package/dist/models/price-list-rule-value.js +0 -102
  30. package/dist/models/price-set-rule-type.d.ts +0 -10
  31. package/dist/models/price-set-rule-type.js +0 -108
  32. package/dist/models/rule-type.d.ts +0 -17
  33. package/dist/models/rule-type.js +0 -100
  34. package/dist/module-definition.d.ts +0 -2
  35. package/dist/module-definition.js +0 -8
  36. package/dist/scripts/bin/run-seed.d.ts +0 -3
  37. package/dist/scripts/bin/run-seed.js +0 -38
  38. package/dist/scripts/seed.d.ts +0 -4
  39. package/dist/scripts/seed.js +0 -67
  40. package/dist/services/price-list.d.ts +0 -16
  41. package/dist/services/price-list.js +0 -34
  42. package/dist/services/rule-type.d.ts +0 -15
  43. package/dist/services/rule-type.js +0 -53
@@ -17,33 +17,25 @@ const utils_1 = require("@medusajs/utils");
17
17
  const _models_1 = require("../models");
18
18
  const _utils_1 = require("../utils");
19
19
  const joiner_config_1 = require("../joiner-config");
20
- const price_list_1 = require("../models/price-list");
21
- const price_set_1 = require("../models/price-set");
22
- const generateMethodForModels = [
23
- _models_1.PriceList,
24
- _models_1.PriceListRule,
25
- _models_1.PriceListRuleValue,
26
- _models_1.PriceRule,
27
- _models_1.Price,
28
- _models_1.PriceSetRuleType,
29
- _models_1.RuleType,
30
- ];
31
- class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleServiceFactory(_models_1.PriceSet, generateMethodForModels, joiner_config_1.entityNameToLinkableKeysMap) {
32
- constructor({ baseRepository, pricingRepository, ruleTypeService, priceSetService, priceRuleService, priceSetRuleTypeService, priceService, priceListService, priceListRuleService, priceListRuleValueService, }, moduleDeclaration) {
20
+ const generateMethodForModels = {
21
+ PriceSet: _models_1.PriceSet,
22
+ PriceList: _models_1.PriceList,
23
+ PriceListRule: _models_1.PriceListRule,
24
+ PriceRule: _models_1.PriceRule,
25
+ Price: _models_1.Price,
26
+ };
27
+ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generateMethodForModels, joiner_config_1.entityNameToLinkableKeysMap) {
28
+ constructor({ baseRepository, pricingRepository, priceSetService, priceRuleService, priceService, priceListService, priceListRuleService, }, moduleDeclaration) {
33
29
  // @ts-ignore
34
30
  super(...arguments);
35
31
  this.moduleDeclaration = moduleDeclaration;
36
32
  this.baseRepository_ = baseRepository;
37
33
  this.pricingRepository_ = pricingRepository;
38
- this.ruleTypeService_ = ruleTypeService;
39
34
  this.priceSetService_ = priceSetService;
40
- this.ruleTypeService_ = ruleTypeService;
41
35
  this.priceRuleService_ = priceRuleService;
42
- this.priceSetRuleTypeService_ = priceSetRuleTypeService;
43
36
  this.priceService_ = priceService;
44
37
  this.priceListService_ = priceListService;
45
38
  this.priceListRuleService_ = priceListRuleService;
46
- this.priceListRuleValueService_ = priceListRuleValueService;
47
39
  }
48
40
  __joinerConfig() {
49
41
  return joiner_config_1.joinerConfig;
@@ -60,50 +52,61 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
60
52
  config.relations?.splice(fieldIdx, 1);
61
53
  return pricingContext;
62
54
  }
63
- async list(filters = {}, config = {}, sharedContext = {}) {
64
- const pricingContext = this.setupCalculatedPriceConfig_(filters, config);
65
- const priceSets = await super.list(filters, config, sharedContext);
66
- if (pricingContext && priceSets.length) {
67
- const priceSetIds = [];
68
- const priceSetMap = new Map();
69
- for (const priceSet of priceSets) {
70
- priceSetIds.push(priceSet.id);
71
- priceSetMap.set(priceSet.id, priceSet);
72
- }
73
- const calculatedPrices = await this.calculatePrices({ id: priceSets.map((p) => p.id) }, { context: pricingContext }, sharedContext);
74
- for (const calculatedPrice of calculatedPrices) {
75
- const priceSet = priceSetMap.get(calculatedPrice.id);
76
- priceSet.calculated_price = calculatedPrice;
77
- }
55
+ // @ts-expect-error
56
+ async retrievePriceSet(id, config, sharedContext) {
57
+ const priceSet = await this.priceSetService_.retrieve(id, this.normalizePriceSetConfig(config), sharedContext);
58
+ return await this.baseRepository_.serialize(priceSet);
59
+ }
60
+ // @ts-expect-error
61
+ async listPriceSets(filters = {}, config = {}, sharedContext = {}) {
62
+ const normalizedConfig = this.normalizePriceSetConfig(config);
63
+ const pricingContext = this.setupCalculatedPriceConfig_(filters, normalizedConfig);
64
+ const priceSets = await super.listPriceSets(filters, normalizedConfig, sharedContext);
65
+ if (!pricingContext || !priceSets.length) {
66
+ return priceSets;
67
+ }
68
+ const calculatedPrices = await this.calculatePrices({ id: priceSets.map((p) => p.id) }, { context: pricingContext }, sharedContext);
69
+ const calculatedPricesMap = new Map();
70
+ for (const calculatedPrice of calculatedPrices) {
71
+ calculatedPricesMap.set(calculatedPrice.id, calculatedPrice);
72
+ }
73
+ for (const priceSet of priceSets) {
74
+ const calculatedPrice = calculatedPricesMap.get(priceSet.id);
75
+ priceSet.calculated_price = calculatedPrice ?? null;
78
76
  }
79
77
  return priceSets;
80
78
  }
81
- async listAndCount(filters = {}, config = {}, sharedContext = {}) {
82
- const pricingContext = this.setupCalculatedPriceConfig_(filters, config);
83
- const [priceSets, count] = await super.listAndCount(filters, config, sharedContext);
84
- if (pricingContext && priceSets.length) {
85
- const priceSetIds = [];
86
- const priceSetMap = new Map();
87
- for (const priceSet of priceSets) {
88
- priceSetIds.push(priceSet.id);
89
- priceSetMap.set(priceSet.id, priceSet);
90
- }
91
- const calculatedPrices = await this.calculatePrices({ id: priceSets.map((p) => p.id) }, { context: pricingContext }, sharedContext);
92
- for (const calculatedPrice of calculatedPrices) {
93
- const priceSet = priceSetMap.get(calculatedPrice.id);
94
- priceSet.calculated_price = calculatedPrice;
95
- }
79
+ // @ts-expect-error
80
+ async listAndCountPriceSets(filters = {}, config = {}, sharedContext = {}) {
81
+ const normalizedConfig = this.normalizePriceSetConfig(config);
82
+ const pricingContext = this.setupCalculatedPriceConfig_(filters, normalizedConfig);
83
+ const [priceSets, count] = await super.listAndCountPriceSets(filters, normalizedConfig, sharedContext);
84
+ if (!pricingContext || !priceSets.length) {
85
+ return [priceSets, count];
86
+ }
87
+ const calculatedPrices = await this.calculatePrices({ id: priceSets.map((p) => p.id) }, { context: pricingContext }, sharedContext);
88
+ const calculatedPricesMap = new Map();
89
+ for (const calculatedPrice of calculatedPrices) {
90
+ calculatedPricesMap.set(calculatedPrice.id, calculatedPrice);
91
+ }
92
+ for (const priceSet of priceSets) {
93
+ const calculatedPrice = calculatedPricesMap.get(priceSet.id);
94
+ priceSet.calculated_price = calculatedPrice ?? null;
96
95
  }
97
96
  return [priceSets, count];
98
97
  }
99
98
  async calculatePrices(pricingFilters, pricingContext = { context: {} }, sharedContext = {}) {
100
99
  const results = await this.pricingRepository_.calculatePrices(pricingFilters, pricingContext, sharedContext);
101
100
  const pricesSetPricesMap = (0, utils_1.groupBy)(results, "price_set_id");
102
- const calculatedPrices = pricingFilters.id.map((priceSetId) => {
101
+ const calculatedPrices = pricingFilters.id
102
+ .map((priceSetId) => {
103
103
  // This is where we select prices, for now we just do a first match based on the database results
104
104
  // which is prioritized by rules_count first for exact match and then deafult_priority of the rule_type
105
105
  // TODO: inject custom price selection here
106
106
  const prices = pricesSetPricesMap.get(priceSetId) || [];
107
+ if (!prices.length) {
108
+ return null;
109
+ }
107
110
  const priceListPrice = prices.find((p) => p.price_list_id);
108
111
  const defaultPrice = prices?.find((p) => !p.price_list_id);
109
112
  let calculatedPrice = defaultPrice;
@@ -136,42 +139,38 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
136
139
  max_quantity: parseInt(originalPrice?.max_quantity || "") || null,
137
140
  },
138
141
  };
139
- });
142
+ })
143
+ .filter(Boolean);
140
144
  return JSON.parse(JSON.stringify(calculatedPrices));
141
145
  }
142
- async create(data, sharedContext = {}) {
146
+ async createPriceSets(data, sharedContext = {}) {
143
147
  const input = Array.isArray(data) ? data : [data];
144
- const priceSets = await this.create_(input, sharedContext);
148
+ const priceSets = await this.createPriceSets_(input, sharedContext);
145
149
  // TODO: Remove the need to refetch the data here
146
- const dbPriceSets = await this.list({ id: priceSets.map((p) => p.id) }, {
147
- relations: [
148
- "rule_types",
149
- "prices",
150
- "price_rules",
151
- "prices.price_rules",
152
- ],
153
- }, sharedContext);
150
+ const dbPriceSets = await this.listPriceSets({ id: priceSets.map((p) => p.id) }, this.normalizePriceSetConfig({
151
+ relations: ["prices", "prices.price_rules"],
152
+ }), sharedContext);
154
153
  // Ensure the output to be in the same order as the input
155
154
  const results = priceSets.map((priceSet) => {
156
155
  return dbPriceSets.find((p) => p.id === priceSet.id);
157
156
  });
158
157
  return await this.baseRepository_.serialize(Array.isArray(data) ? results : results[0]);
159
158
  }
160
- async upsert(data, sharedContext = {}) {
159
+ async upsertPriceSets(data, sharedContext = {}) {
161
160
  const input = Array.isArray(data) ? data : [data];
162
161
  const forUpdate = input.filter((priceSet) => !!priceSet.id);
163
162
  const forCreate = input.filter((priceSet) => !priceSet.id);
164
163
  const operations = [];
165
164
  if (forCreate.length) {
166
- operations.push(this.create_(forCreate, sharedContext));
165
+ operations.push(this.createPriceSets_(forCreate, sharedContext));
167
166
  }
168
167
  if (forUpdate.length) {
169
- operations.push(this.update_(forUpdate, sharedContext));
168
+ operations.push(this.updatePriceSets_(forUpdate, sharedContext));
170
169
  }
171
170
  const result = (await (0, utils_1.promiseAll)(operations)).flat();
172
171
  return await this.baseRepository_.serialize(Array.isArray(data) ? result : result[0]);
173
172
  }
174
- async update(idOrSelector, data, sharedContext = {}) {
173
+ async updatePriceSets(idOrSelector, data, sharedContext = {}) {
175
174
  let normalizedInput = [];
176
175
  if ((0, utils_1.isString)(idOrSelector)) {
177
176
  // Check if the ID exists, it will throw if not.
@@ -185,26 +184,16 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
185
184
  ...data,
186
185
  }));
187
186
  }
188
- const updateResult = await this.update_(normalizedInput, sharedContext);
187
+ const updateResult = await this.updatePriceSets_(normalizedInput, sharedContext);
189
188
  const priceSets = await this.baseRepository_.serialize(updateResult);
190
189
  return (0, utils_1.isString)(idOrSelector) ? priceSets[0] : priceSets;
191
190
  }
192
- async normalizeUpdateData(data, sharedContext) {
193
- const ruleAttributes = data
194
- .map((d) => d.prices?.map((p) => Object.keys(p.rules ?? [])) ?? [])
195
- .flat(Infinity)
196
- .filter(Boolean);
197
- const ruleTypes = await this.ruleTypeService_.list({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
198
- const ruleTypeMap = ruleTypes.reduce((acc, curr) => {
199
- acc.set(curr.rule_attribute, curr);
200
- return acc;
201
- }, new Map());
191
+ async normalizeUpdateData(data) {
202
192
  return data.map((priceSet) => {
203
193
  const prices = priceSet.prices?.map((price) => {
204
194
  const rules = Object.entries(price.rules ?? {}).map(([attribute, value]) => {
205
195
  return {
206
- price_set_id: priceSet.id,
207
- rule_type_id: ruleTypeMap.get(attribute).id,
196
+ attribute,
208
197
  value,
209
198
  };
210
199
  });
@@ -223,15 +212,12 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
223
212
  };
224
213
  });
225
214
  }
226
- async update_(data, sharedContext = {}) {
227
- // TODO: We are not handling rule types, rules, etc. here, add support after data models are finalized
215
+ async updatePriceSets_(data, sharedContext = {}) {
228
216
  // TODO: Since money IDs are rarely passed, this will delete all previous data and insert new entries.
229
217
  // We can make the `insert` inside upsertWithReplace do an `upsert` instead to avoid this
230
- const normalizedData = await this.normalizeUpdateData(data, sharedContext);
218
+ const normalizedData = await this.normalizeUpdateData(data);
231
219
  const prices = normalizedData.flatMap((priceSet) => priceSet.prices || []);
232
- const { entities: upsertedPrices } = await this.priceService_.upsertWithReplace(prices, {
233
- relations: ["price_rules"],
234
- }, sharedContext);
220
+ const { entities: upsertedPrices } = await this.priceService_.upsertWithReplace(prices, { relations: ["price_rules"] }, sharedContext);
235
221
  const priceSetsToUpsert = normalizedData.map((priceSet) => {
236
222
  const { prices, ...rest } = priceSet;
237
223
  return {
@@ -248,40 +234,21 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
248
234
  const { entities: priceSets } = await this.priceSetService_.upsertWithReplace(priceSetsToUpsert, { relations: ["prices"] }, sharedContext);
249
235
  return priceSets;
250
236
  }
251
- async addRules(data, sharedContext = {}) {
252
- const inputs = Array.isArray(data) ? data : [data];
253
- const priceSets = await this.addRules_(inputs, sharedContext);
254
- const dbPriceSets = await this.list({ id: priceSets.map(({ id }) => id) }, { relations: ["rule_types"] });
255
- const orderedPriceSets = priceSets.map((priceSet) => {
256
- return dbPriceSets.find((p) => p.id === priceSet.id);
257
- });
258
- return Array.isArray(data) ? orderedPriceSets : orderedPriceSets[0];
259
- }
260
237
  async addPrices(data, sharedContext = {}) {
261
238
  const input = Array.isArray(data) ? data : [data];
262
239
  await this.addPrices_(input, sharedContext);
263
- const dbPrices = await this.list({ id: input.map((d) => d.priceSetId) }, { relations: ["prices"] }, sharedContext);
240
+ const dbPrices = await this.listPriceSets({ id: input.map((d) => d.priceSetId) }, { relations: ["prices"] }, sharedContext);
264
241
  const orderedPriceSets = input.map((inputItem) => {
265
242
  return dbPrices.find((p) => p.id === inputItem.priceSetId);
266
243
  });
267
244
  return Array.isArray(data) ? orderedPriceSets : orderedPriceSets[0];
268
245
  }
269
- async removeRules(data, sharedContext = {}) {
270
- const priceSets = await this.priceSetService_.list({ id: data.map((d) => d.id) }, {}, sharedContext);
271
- const priceSetIds = priceSets.map((ps) => ps.id);
272
- const ruleTypes = await this.ruleTypeService_.list({
273
- rule_attribute: data.map((d) => d.rules || []).flat(),
274
- }, { take: null }, sharedContext);
275
- const ruleTypeIds = ruleTypes.map((rt) => rt.id);
276
- const priceSetRuleTypes = await this.priceSetRuleTypeService_.list({ price_set_id: priceSetIds, rule_type_id: ruleTypeIds }, { take: null }, sharedContext);
277
- const priceRules = await this.priceRuleService_.list({ price_set_id: priceSetIds, rule_type_id: ruleTypeIds }, { select: ["price"], take: null }, sharedContext);
278
- await this.priceSetRuleTypeService_.delete(priceSetRuleTypes.map((psrt) => psrt.id), sharedContext);
279
- await this.priceService_.delete(priceRules.map((pr) => pr.price.id), sharedContext);
280
- }
246
+ // @ts-ignore
281
247
  async createPriceLists(data, sharedContext = {}) {
282
248
  const priceLists = await this.createPriceLists_(data, sharedContext);
283
249
  return await this.baseRepository_.serialize(priceLists);
284
250
  }
251
+ // @ts-ignore
285
252
  async updatePriceLists(data, sharedContext = {}) {
286
253
  const priceLists = await this.updatePriceLists_(data, sharedContext);
287
254
  return await this.baseRepository_.serialize(priceLists);
@@ -305,69 +272,36 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
305
272
  const [priceList] = await this.removePriceListRules_([data], sharedContext);
306
273
  return await this.baseRepository_.serialize(priceList);
307
274
  }
308
- async create_(data, sharedContext = {}) {
275
+ async createPriceSets_(data, sharedContext = {}) {
309
276
  const input = Array.isArray(data) ? data : [data];
310
- const ruleAttributes = (0, utils_1.deduplicate)(data.map((d) => d.rules?.map((r) => r.rule_attribute) ?? []).flat());
311
- const ruleTypes = await this.ruleTypeService_.list({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
312
- const ruleTypeMap = ruleTypes.reduce((acc, curr) => {
313
- acc.set(curr.rule_attribute, curr);
314
- return acc;
315
- }, new Map());
316
- const invalidRuleAttributes = ruleAttributes.filter((r) => !ruleTypeMap.has(r));
317
- if (invalidRuleAttributes.length > 0) {
318
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, `Rule types don't exist for: ${invalidRuleAttributes.join(", ")}`);
319
- }
320
- const invalidMoneyAmountRule = data
321
- .map((d) => d.prices?.map((ma) => Object.keys(ma?.rules ?? {})).flat() ?? [])
322
- .flat()
323
- .filter((r) => !ruleTypeMap.has(r));
324
- if (invalidMoneyAmountRule.length > 0) {
325
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Rule types don't exist for money amounts with rule attribute: ${invalidMoneyAmountRule.join(", ")}`);
326
- }
327
- const ruleSetRuleTypeToCreateMap = new Map();
328
277
  const toCreate = input.map((inputData) => {
329
- const id = (0, utils_1.generateEntityId)(inputData.id, price_set_1.PriceSetIdPrefix);
330
- const { prices, rules = [], ...rest } = inputData;
331
- let pricesData = [];
332
- rules.forEach((rule) => {
333
- const priceSetRuleType = {
334
- rule_type_id: ruleTypeMap.get(rule.rule_attribute).id,
335
- price_set_id: id,
336
- };
337
- ruleSetRuleTypeToCreateMap.set(JSON.stringify(priceSetRuleType), priceSetRuleType);
338
- });
339
- if (inputData.prices) {
340
- pricesData = inputData.prices.map((price) => {
341
- let { rules: priceRules = {}, ...rest } = price;
342
- const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
343
- const numberOfRules = Object.keys(cleanRules).length;
344
- const rulesDataMap = new Map();
345
- Object.entries(priceRules).map(([attribute, value]) => {
346
- const rule = {
347
- price_set_id: id,
348
- rule_type_id: ruleTypeMap.get(attribute).id,
349
- value,
350
- };
351
- rulesDataMap.set(JSON.stringify(rule), rule);
352
- const priceSetRuleType = {
353
- rule_type_id: ruleTypeMap.get(attribute).id,
354
- price_set_id: id,
355
- };
356
- ruleSetRuleTypeToCreateMap.set(JSON.stringify(priceSetRuleType), priceSetRuleType);
357
- });
358
- return {
359
- ...rest,
360
- title: "", // TODO: accept title
361
- rules_count: numberOfRules,
362
- price_rules: Array.from(rulesDataMap.values()),
278
+ const entry = {
279
+ ...inputData,
280
+ };
281
+ if (!inputData.prices) {
282
+ return entry;
283
+ }
284
+ const pricesData = inputData.prices.map((price) => {
285
+ let { rules: priceRules = {}, ...rest } = price;
286
+ const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
287
+ const rules = Object.entries(cleanRules);
288
+ const numberOfRules = rules.length;
289
+ const rulesDataMap = new Map();
290
+ rules.map(([attribute, value]) => {
291
+ const rule = {
292
+ attribute,
293
+ value,
363
294
  };
295
+ rulesDataMap.set(JSON.stringify(rule), rule);
364
296
  });
365
- }
366
- return {
367
- ...rest,
368
- id,
369
- prices: pricesData,
370
- };
297
+ return {
298
+ ...rest,
299
+ rules_count: numberOfRules,
300
+ price_rules: Array.from(rulesDataMap.values()),
301
+ };
302
+ });
303
+ entry.prices = pricesData;
304
+ return entry;
371
305
  });
372
306
  // Bulk create price sets
373
307
  const createdPriceSets = await this.priceSetService_.create(toCreate, sharedContext);
@@ -403,85 +337,27 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
403
337
  data: eventsData.priceRules,
404
338
  sharedContext,
405
339
  });
406
- if (ruleSetRuleTypeToCreateMap.size) {
407
- await this.priceSetRuleTypeService_.create(Array.from(ruleSetRuleTypeToCreateMap.values()), sharedContext);
408
- }
409
340
  return createdPriceSets;
410
341
  }
411
- async addRules_(inputs, sharedContext = {}) {
412
- const priceSets = await this.priceSetService_.list({ id: inputs.map((d) => d.priceSetId) }, { relations: ["rule_types"] }, sharedContext);
413
- const priceSetRuleTypeMap = new Map(priceSets.map((priceSet) => [
414
- priceSet.id,
415
- new Map([...priceSet.rule_types].map((rt) => [rt.rule_attribute, rt])),
416
- ]));
417
- const priceSetMap = new Map(priceSets.map((p) => [p.id, p]));
418
- const invalidPriceSetInputs = inputs.filter((d) => !priceSetMap.has(d.priceSetId));
419
- if (invalidPriceSetInputs.length) {
420
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `PriceSets with ids: ${invalidPriceSetInputs
421
- .map((d) => d.priceSetId)
422
- .join(", ")} was not found`);
423
- }
424
- const ruleTypes = await this.ruleTypeService_.list({
425
- rule_attribute: inputs
426
- .map((data) => data.rules.map((r) => r.attribute))
427
- .flat(),
428
- }, { take: null }, sharedContext);
429
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
430
- const invalidRuleAttributeInputs = inputs
431
- .map((d) => d.rules.map((r) => r.attribute))
432
- .flat()
433
- .filter((r) => !ruleTypeMap.has(r));
434
- if (invalidRuleAttributeInputs.length) {
435
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Rule types don't exist for attributes: ${[
436
- ...new Set(invalidRuleAttributeInputs),
437
- ].join(", ")}`);
438
- }
439
- const priceSetRuleTypesCreate = [];
440
- inputs.forEach((data) => {
441
- for (const rule of data.rules) {
442
- if (priceSetRuleTypeMap.get(data.priceSetId).has(rule.attribute)) {
443
- continue;
444
- }
445
- priceSetRuleTypesCreate.push({
446
- rule_type_id: ruleTypeMap.get(rule.attribute).id,
447
- price_set_id: priceSetMap.get(data.priceSetId).id,
448
- });
449
- }
450
- });
451
- await this.priceSetRuleTypeService_.create(priceSetRuleTypesCreate, sharedContext);
452
- return priceSets;
453
- }
454
342
  async addPrices_(input, sharedContext = {}) {
455
- const priceSets = await this.list({ id: input.map((d) => d.priceSetId) }, { relations: ["rule_types"] }, sharedContext);
343
+ const priceSets = await this.listPriceSets({ id: input.map((d) => d.priceSetId) }, {}, sharedContext);
456
344
  const priceSetMap = new Map(priceSets.map((p) => [p.id, p]));
457
- const ruleTypeMap = new Map(priceSets.map((priceSet) => [
458
- priceSet.id,
459
- new Map(priceSet.rule_types?.map((rt) => [rt.rule_attribute, rt]) ?? []),
460
- ]));
461
- input.forEach(({ priceSetId, prices }) => {
345
+ input.forEach(({ priceSetId }) => {
462
346
  const priceSet = priceSetMap.get(priceSetId);
463
347
  if (!priceSet) {
464
348
  throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price set with id: ${priceSetId} not found`);
465
349
  }
466
- const ruleAttributes = prices
467
- .map((d) => (d.rules ? Object.keys(d.rules) : []))
468
- .flat();
469
- const invalidRuleAttributes = ruleAttributes.filter((r) => !ruleTypeMap.get(priceSetId).has(r));
470
- if (invalidRuleAttributes.length > 0) {
471
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, `Rule types don't exist for: ${invalidRuleAttributes.join(", ")}`);
472
- }
473
350
  });
474
351
  const pricesToCreate = input.flatMap(({ priceSetId, prices }) => prices.map((price) => {
475
352
  const numberOfRules = Object.entries(price?.rules ?? {}).length;
476
353
  const priceRules = Object.entries(price.rules ?? {}).map(([attribute, value]) => ({
477
- rule_type_id: ruleTypeMap.get(priceSetId).get(attribute).id,
478
354
  price_set_id: priceSetId,
355
+ attribute: attribute,
479
356
  value,
480
357
  }));
481
358
  return {
482
359
  ...price,
483
360
  price_set_id: priceSetId,
484
- title: "test", // TODO: accept title
485
361
  rules_count: numberOfRules,
486
362
  price_rules: priceRules,
487
363
  };
@@ -518,56 +394,52 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
518
394
  return prices;
519
395
  }
520
396
  async createPriceLists_(data, sharedContext = {}) {
521
- const ruleTypeAttributes = [];
522
- for (const priceListData of data) {
523
- const { prices = [], rules: priceListRules = {} } = priceListData;
524
- ruleTypeAttributes.push(...Object.keys(priceListRules));
525
- for (const price of prices) {
526
- const { rules: priceListPriceRules = {} } = price;
527
- ruleTypeAttributes.push(...Object.keys(priceListPriceRules));
528
- }
529
- }
530
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
531
- const invalidRuleTypes = (0, utils_1.arrayDifference)((0, utils_1.deduplicate)(ruleTypeAttributes), ruleTypes.map((ruleType) => ruleType.rule_attribute));
532
- if (invalidRuleTypes.length) {
533
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Cannot find RuleTypes with rule_attribute - ${invalidRuleTypes.join(", ")}`);
534
- }
535
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
536
- const priceListsToCreate = data.map((priceListData) => {
537
- const id = (0, utils_1.generateEntityId)(priceListData.id, price_list_1.PriceListIdPrefix);
538
- const { prices = [], rules = {}, ...rest } = priceListData;
539
- (0, _utils_1.validatePriceListDates)(priceListData);
540
- const priceListRules = Object.entries(rules).map(([attribute, value]) => {
541
- const ruleType = ruleTypeMap.get(attribute);
542
- return {
543
- price_list_id: id,
544
- rule_type_id: ruleType.id,
545
- price_list_rule_values: value.map((v) => ({ value: v })),
546
- };
547
- });
548
- const pricesData = prices.map((price) => {
549
- const priceRules = Object.entries(price.rules ?? {}).map(([ruleAttribute, ruleValue]) => {
397
+ const normalized = this.normalizePriceListDate(data);
398
+ const priceListsToCreate = normalized.map((priceListData) => {
399
+ const entry = {
400
+ ...priceListData,
401
+ rules: undefined,
402
+ };
403
+ if (priceListData.prices) {
404
+ const pricesData = priceListData.prices.map((price) => {
405
+ let { rules: priceRules = {}, ...rest } = price;
406
+ const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
407
+ const rules = Object.entries(cleanRules);
408
+ const numberOfRules = rules.length;
409
+ const rulesDataMap = new Map();
410
+ rules.map(([attribute, value]) => {
411
+ const rule = {
412
+ attribute,
413
+ value,
414
+ };
415
+ rulesDataMap.set(JSON.stringify(rule), rule);
416
+ });
550
417
  return {
551
- price_set_id: price.price_set_id,
552
- rule_type_id: ruleTypeMap.get(ruleAttribute)?.id,
553
- value: ruleValue,
418
+ ...rest,
419
+ rules_count: numberOfRules,
420
+ price_rules: Array.from(rulesDataMap.values()),
554
421
  };
555
422
  });
556
- return {
557
- price_list_id: id,
558
- title: "test",
559
- rules_count: Object.keys(price.rules ?? {}).length,
560
- price_rules: priceRules,
561
- ...price,
562
- };
563
- });
564
- return {
565
- id,
566
- ...rest,
567
- rules_count: Object.keys(rules).length,
568
- price_list_rules: priceListRules,
569
- prices: pricesData,
570
- };
423
+ entry.prices = pricesData;
424
+ }
425
+ if (priceListData.rules) {
426
+ const cleanRules = priceListData.rules
427
+ ? (0, utils_1.removeNullish)(priceListData.rules)
428
+ : {};
429
+ const rules = Object.entries(cleanRules);
430
+ const numberOfRules = rules.length;
431
+ const rulesDataMap = new Map();
432
+ rules.map(([attribute, value]) => {
433
+ const rule = {
434
+ attribute,
435
+ value,
436
+ };
437
+ rulesDataMap.set(JSON.stringify(rule), rule);
438
+ });
439
+ entry.price_list_rules = Array.from(rulesDataMap.values());
440
+ entry.rules_count = numberOfRules;
441
+ }
442
+ return entry;
571
443
  });
572
444
  const priceLists = await this.priceListService_.create(priceListsToCreate, sharedContext);
573
445
  /**
@@ -621,96 +493,52 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
621
493
  return priceLists;
622
494
  }
623
495
  async updatePriceLists_(data, sharedContext = {}) {
624
- const updatedPriceLists = [];
625
- const ruleAttributes = [];
626
- const priceListIds = [];
627
- for (const priceListData of data) {
628
- if (typeof priceListData.rules === "object") {
629
- ruleAttributes.push(...Object.keys(priceListData.rules));
630
- priceListIds.push(priceListData.id);
631
- }
632
- }
633
- const existingPriceLists = await this.listPriceLists({ id: priceListIds }, { relations: ["price_list_rules"] }, sharedContext);
634
- const priceListRuleIds = existingPriceLists
635
- .map((pl) => (pl.price_list_rules || []).map((plr) => plr.id))
636
- .flat();
637
- const existingPriceListRules = await this.listPriceListRules({ id: priceListRuleIds }, {}, sharedContext);
638
- if (existingPriceListRules.length) {
639
- await this.deletePriceListRules(existingPriceListRules.map((plr) => plr.id), sharedContext);
496
+ const existingPriceLists = await this.priceListService_.list({ id: data.map((d) => d.id) }, {}, sharedContext);
497
+ if (existingPriceLists.length !== data.length) {
498
+ const diff = (0, utils_1.arrayDifference)(data.map((d) => d.id), existingPriceLists.map((p) => p.id));
499
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price lists with ids: '${diff.join(", ")}' not found`);
640
500
  }
641
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
642
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
643
- for (const priceListData of data) {
644
- const { rules, ...priceListOnlyData } = priceListData;
645
- const updatePriceListData = {
646
- ...priceListOnlyData,
501
+ const normalizedData = this.normalizePriceListDate(data).map((priceList) => {
502
+ const entry = {
503
+ ...priceList,
504
+ rules: undefined,
505
+ price_list_rules: undefined,
647
506
  };
648
- (0, _utils_1.validatePriceListDates)(updatePriceListData);
649
- if (typeof rules === "object") {
650
- updatePriceListData.rules_count = Object.keys(rules).length;
651
- }
652
- const [updatedPriceList] = (await this.priceListService_.update([updatePriceListData], sharedContext));
653
- updatedPriceLists.push(updatedPriceList);
654
- for (const [ruleAttribute, ruleValues = []] of Object.entries(rules || {})) {
655
- let ruleType = ruleTypeMap.get(ruleAttribute);
656
- if (!ruleType) {
657
- ;
658
- [ruleType] = await this.createRuleTypes([{ name: ruleAttribute, rule_attribute: ruleAttribute }], sharedContext);
659
- ruleTypeMap.set(ruleAttribute, ruleType);
660
- }
661
- const [priceListRule] = await this.priceListRuleService_.create([
662
- {
663
- price_list_id: updatedPriceList.id,
664
- rule_type_id: ruleType?.id,
665
- },
666
- ], sharedContext);
667
- for (const ruleValue of ruleValues) {
668
- await this.priceListRuleValueService_.create([{ price_list_rule_id: priceListRule.id, value: ruleValue }], sharedContext);
669
- }
507
+ if (typeof priceList.rules === "object") {
508
+ const cleanRules = priceList.rules
509
+ ? (0, utils_1.removeNullish)(priceList.rules)
510
+ : {};
511
+ const rules = Object.entries(cleanRules);
512
+ const numberOfRules = rules.length;
513
+ const rulesDataMap = new Map();
514
+ rules.map(([attribute, value]) => {
515
+ const rule = {
516
+ attribute,
517
+ value,
518
+ };
519
+ rulesDataMap.set(JSON.stringify(rule), rule);
520
+ });
521
+ entry.price_list_rules = Array.from(rulesDataMap.values());
522
+ entry.rules_count = numberOfRules;
670
523
  }
671
- }
672
- return updatedPriceLists;
524
+ return entry;
525
+ });
526
+ const { entities } = await this.priceListService_.upsertWithReplace(normalizedData, {
527
+ relations: ["price_list_rules"],
528
+ });
529
+ return entities;
673
530
  }
674
531
  async updatePriceListPrices_(data, sharedContext = {}) {
675
- const ruleTypeAttributes = [];
676
532
  const priceListIds = [];
677
533
  const priceIds = [];
678
- const priceSetIds = data
679
- .map((d) => d.prices.map((price) => price.price_set_id))
680
- .flat();
681
534
  for (const priceListData of data) {
682
535
  priceListIds.push(priceListData.price_list_id);
683
536
  for (const price of priceListData.prices) {
684
537
  priceIds.push(price.id);
685
- ruleTypeAttributes.push(...Object.keys(price.rules || {}));
686
538
  }
687
539
  }
688
540
  const prices = await this.listPrices({ id: priceIds }, { take: null, relations: ["price_rules"] }, sharedContext);
689
541
  const priceMap = new Map(prices.map((price) => [price.id, price]));
690
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
691
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
692
- const priceSets = await this.list({ id: priceSetIds }, { relations: ["rule_types"] }, sharedContext);
693
- const priceSetRuleTypeMap = priceSets.reduce((acc, curr) => {
694
- const priceSetRuleAttributeSet = acc.get(curr.id) || new Set();
695
- for (const rt of curr.rule_types ?? []) {
696
- priceSetRuleAttributeSet.add(rt.rule_attribute);
697
- }
698
- acc.set(curr.id, priceSetRuleAttributeSet);
699
- return acc;
700
- }, new Map());
701
- const ruleTypeErrors = [];
702
- for (const priceListData of data) {
703
- for (const price of priceListData.prices) {
704
- for (const ruleAttribute of Object.keys(price.rules ?? {})) {
705
- if (!priceSetRuleTypeMap.get(price.price_set_id)?.has(ruleAttribute)) {
706
- ruleTypeErrors.push(`rule_attribute "${ruleAttribute}" in price set ${price.price_set_id}`);
707
- }
708
- }
709
- }
710
- }
711
- if (ruleTypeErrors.length) {
712
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Invalid rule type configuration: Price set rules doesn't exist for ${ruleTypeErrors.join(", ")}`);
713
- }
714
542
  const priceLists = await this.listPriceLists({ id: priceListIds }, { take: null }, sharedContext);
715
543
  const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
716
544
  const pricesToUpdate = [];
@@ -727,7 +555,7 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
727
555
  const priceRules = price.price_rules;
728
556
  priceRulesToCreate.push(...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
729
557
  price_set_id,
730
- rule_type_id: ruleTypeMap.get(ruleAttribute).id,
558
+ attribute: ruleAttribute,
731
559
  value: ruleValue,
732
560
  price_id: price.id,
733
561
  })));
@@ -749,40 +577,10 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
749
577
  await this.priceService_.delete(ids, sharedContext);
750
578
  }
751
579
  async addPriceListPrices_(data, sharedContext = {}) {
752
- const ruleTypeAttributes = [];
753
580
  const priceListIds = [];
754
- const priceSetIds = [];
755
581
  for (const priceListData of data) {
756
582
  priceListIds.push(priceListData.price_list_id);
757
- for (const price of priceListData.prices) {
758
- ruleTypeAttributes.push(...Object.keys(price.rules || {}));
759
- priceSetIds.push(price.price_set_id);
760
- }
761
- }
762
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
763
- const priceSets = await this.list({ id: priceSetIds }, { relations: ["rule_types"] }, sharedContext);
764
- const priceSetRuleTypeMap = priceSets.reduce((acc, curr) => {
765
- const priceSetRuleAttributeSet = acc.get(curr.id) || new Set();
766
- for (const rt of curr.rule_types ?? []) {
767
- priceSetRuleAttributeSet.add(rt.rule_attribute);
768
- }
769
- acc.set(curr.id, priceSetRuleAttributeSet);
770
- return acc;
771
- }, new Map());
772
- const ruleTypeErrors = [];
773
- for (const priceListData of data) {
774
- for (const price of priceListData.prices) {
775
- for (const rule_attribute of Object.keys(price.rules ?? {})) {
776
- if (!priceSetRuleTypeMap.get(price.price_set_id)?.has(rule_attribute)) {
777
- ruleTypeErrors.push(`rule_attribute "${rule_attribute}" in price set ${price.price_set_id}`);
778
- }
779
- }
780
- }
781
- }
782
- if (ruleTypeErrors.length) {
783
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Invalid rule type configuration: Price set rules doesn't exist for ${ruleTypeErrors.join(", ")}`);
784
583
  }
785
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
786
584
  const priceLists = await this.listPriceLists({ id: priceListIds }, {}, sharedContext);
787
585
  const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
788
586
  const pricesToCreate = [];
@@ -796,8 +594,8 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
796
594
  const noOfRules = Object.keys(priceRules).length;
797
595
  const priceRulesToCreate = Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => {
798
596
  return {
799
- price_set_id: priceData.price_set_id,
800
- rule_type_id: ruleTypeMap.get(ruleAttribute)?.id,
597
+ price_list_id: priceData.price_set_id,
598
+ attribute: ruleAttribute,
801
599
  value: ruleValue,
802
600
  };
803
601
  });
@@ -839,102 +637,132 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
839
637
  }
840
638
  async setPriceListRules_(data, sharedContext = {}) {
841
639
  // TODO: re think this method
842
- const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, { relations: ["price_list_rules", "price_list_rules.rule_type"] }, sharedContext);
843
- const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
844
- const ruleTypes = await this.listRuleTypes({ rule_attribute: data.map((d) => Object.keys(d.rules)).flat() }, { take: null });
845
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
846
- const ruleIdsToUpdate = [];
847
- const rulesToCreate = [];
848
- const priceRuleValues = new Map();
849
- for (const { price_list_id: priceListId, rules } of data) {
850
- const priceList = priceListMap.get(priceListId);
851
- if (!priceList) {
852
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price list with id: ${priceListId} not found`);
640
+ const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, {
641
+ relations: ["price_list_rules"],
642
+ }, sharedContext);
643
+ const rulesMap = new Map();
644
+ data.forEach((rule) => {
645
+ if (!rulesMap.has(rule.price_list_id)) {
646
+ rulesMap.set(rule.price_list_id, []);
853
647
  }
854
- const priceListRulesMap = new Map(priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p]));
855
- const priceListRuleValues = new Map();
856
- Object.entries(rules).map(async ([key, value]) => {
857
- const ruleType = ruleTypeMap.get(key);
858
- if (!ruleType) {
859
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Rule type with attribute: ${key} not found`);
860
- }
861
- const rule = priceListRulesMap.get(key);
862
- priceListRuleValues.set(ruleType.id, Array.isArray(value) ? value : [value]);
863
- if (!rule) {
864
- rulesToCreate.push({
865
- rule_type_id: ruleType.id,
866
- price_list_id: priceListId,
867
- });
868
- }
869
- else {
870
- ruleIdsToUpdate.push(rule.id);
871
- }
648
+ Object.entries(rule.rules).forEach(([key, value]) => {
649
+ rulesMap.get(rule.price_list_id).push([key, value]);
872
650
  });
873
- priceRuleValues.set(priceListId, priceListRuleValues);
874
- }
875
- const [createdRules, priceListValuesToDelete] = await (0, utils_1.promiseAll)([
876
- this.priceListRuleService_.create(rulesToCreate),
877
- this.priceListRuleValueService_.list({ price_list_rule_id: ruleIdsToUpdate }, { take: null }),
878
- ]);
879
- const priceListRuleValuesToCreate = [];
880
- for (const { id, price_list_id, rule_type_id } of createdRules) {
881
- const ruleValues = priceRuleValues.get(price_list_id);
882
- if (!ruleValues) {
883
- continue;
884
- }
885
- const values = ruleValues.get(rule_type_id);
886
- if (!values) {
887
- continue;
651
+ });
652
+ const priceListsUpsert = priceLists
653
+ .map((priceList) => {
654
+ const allRules = new Map(priceList.price_list_rules
655
+ .toArray()
656
+ .map((r) => [r.attribute, r.value]));
657
+ const rules = rulesMap.get(priceList.id);
658
+ if (!rules?.length) {
659
+ return;
888
660
  }
889
- values.forEach((v) => {
890
- priceListRuleValuesToCreate.push({
891
- price_list_rule_id: id,
892
- value: v,
893
- });
661
+ rules.forEach(([key, value]) => {
662
+ allRules.set(key, value);
894
663
  });
895
- }
896
- await (0, utils_1.promiseAll)([
897
- this.priceListRuleValueService_.delete(priceListValuesToDelete.map((p) => p.id), sharedContext),
898
- this.priceListRuleValueService_.create(priceListRuleValuesToCreate, sharedContext),
899
- ]);
900
- return priceLists;
664
+ return {
665
+ ...priceList,
666
+ rules_count: allRules.size,
667
+ price_list_rules: Array.from(allRules).map(([attribute, value]) => ({
668
+ attribute,
669
+ value,
670
+ })),
671
+ };
672
+ })
673
+ .filter(Boolean);
674
+ const { entities } = await this.priceListService_.upsertWithReplace(priceListsUpsert, { relations: ["price_list_rules"] }, sharedContext);
675
+ return entities;
901
676
  }
902
677
  async removePriceListRules_(data, sharedContext = {}) {
903
- const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, { relations: ["price_list_rules", "price_list_rules.rule_type"] }, sharedContext);
904
- const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
905
- const idsToDelete = [];
906
- for (const { price_list_id: priceListId, rules } of data) {
907
- const priceList = priceListMap.get(priceListId);
908
- if (!priceList) {
909
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price list with id: ${priceListId} not found`);
678
+ // TODO: re think this method
679
+ const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, {
680
+ relations: ["price_list_rules"],
681
+ }, sharedContext);
682
+ const rulesMap = new Map();
683
+ data.forEach((rule) => {
684
+ if (!rulesMap.has(rule.price_list_id)) {
685
+ rulesMap.set(rule.price_list_id, []);
910
686
  }
911
- const priceListRulesMap = new Map(priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p]));
912
- rules.map(async (rule_attribute) => {
913
- const rule = priceListRulesMap.get(rule_attribute);
914
- if (rule) {
915
- idsToDelete.push(rule.id);
916
- }
687
+ rule.rules.forEach((key) => {
688
+ rulesMap.get(rule.price_list_id).push([key, undefined]);
917
689
  });
918
- }
919
- await this.priceListRuleService_.delete(idsToDelete);
920
- return priceLists;
690
+ });
691
+ const priceListsUpsert = priceLists
692
+ .map((priceList) => {
693
+ const allRules = new Map(priceList.price_list_rules
694
+ .toArray()
695
+ .map((r) => [r.attribute, r.value]));
696
+ const rules = rulesMap.get(priceList.id);
697
+ if (!rules?.length) {
698
+ return;
699
+ }
700
+ rules.forEach(([key, value]) => {
701
+ allRules.set(key, value);
702
+ });
703
+ return {
704
+ ...priceList,
705
+ rules_count: allRules.size,
706
+ price_list_rules: Array.from(allRules)
707
+ .map(([attribute, value]) => ({
708
+ attribute,
709
+ value,
710
+ }))
711
+ .filter((r) => !!r.value),
712
+ };
713
+ })
714
+ .filter(Boolean);
715
+ const { entities } = await this.priceListService_.upsertWithReplace(priceListsUpsert, { relations: ["price_list_rules"] }, sharedContext);
716
+ return entities;
717
+ }
718
+ normalizePriceListDate(data) {
719
+ return data.map((priceListData) => {
720
+ (0, _utils_1.validatePriceListDates)(priceListData);
721
+ if (!!priceListData.starts_at) {
722
+ priceListData.starts_at = (0, utils_1.GetIsoStringFromDate)(priceListData.starts_at);
723
+ }
724
+ if (!!priceListData.ends_at) {
725
+ priceListData.ends_at = (0, utils_1.GetIsoStringFromDate)(priceListData.ends_at);
726
+ }
727
+ return priceListData;
728
+ });
729
+ }
730
+ normalizePriceSetConfig(config) {
731
+ return {
732
+ options: {
733
+ populateWhere: { prices: { price_list_id: null } },
734
+ },
735
+ ...config,
736
+ };
921
737
  }
922
738
  }
923
739
  exports.default = PricingModuleService;
924
740
  __decorate([
925
- (0, utils_1.InjectManager)("baseRepository_"),
741
+ (0, utils_1.InjectManager)("baseRepository_")
742
+ // @ts-expect-error
743
+ ,
744
+ __metadata("design:type", Function),
745
+ __metadata("design:paramtypes", [String, Object, Object]),
746
+ __metadata("design:returntype", Promise)
747
+ ], PricingModuleService.prototype, "retrievePriceSet", null);
748
+ __decorate([
749
+ (0, utils_1.InjectManager)("baseRepository_")
750
+ // @ts-expect-error
751
+ ,
926
752
  __param(2, (0, utils_1.MedusaContext)()),
927
753
  __metadata("design:type", Function),
928
754
  __metadata("design:paramtypes", [Object, Object, Object]),
929
755
  __metadata("design:returntype", Promise)
930
- ], PricingModuleService.prototype, "list", null);
756
+ ], PricingModuleService.prototype, "listPriceSets", null);
931
757
  __decorate([
932
- (0, utils_1.InjectManager)("baseRepository_"),
758
+ (0, utils_1.InjectManager)("baseRepository_")
759
+ // @ts-expect-error
760
+ ,
933
761
  __param(2, (0, utils_1.MedusaContext)()),
934
762
  __metadata("design:type", Function),
935
763
  __metadata("design:paramtypes", [Object, Object, Object]),
936
764
  __metadata("design:returntype", Promise)
937
- ], PricingModuleService.prototype, "listAndCount", null);
765
+ ], PricingModuleService.prototype, "listAndCountPriceSets", null);
938
766
  __decorate([
939
767
  (0, utils_1.InjectManager)("baseRepository_"),
940
768
  __param(2, (0, utils_1.MedusaContext)()),
@@ -949,35 +777,28 @@ __decorate([
949
777
  __metadata("design:type", Function),
950
778
  __metadata("design:paramtypes", [Object, Object]),
951
779
  __metadata("design:returntype", Promise)
952
- ], PricingModuleService.prototype, "create", null);
780
+ ], PricingModuleService.prototype, "createPriceSets", null);
953
781
  __decorate([
954
782
  (0, utils_1.InjectManager)("baseRepository_"),
955
783
  __param(1, (0, utils_1.MedusaContext)()),
956
784
  __metadata("design:type", Function),
957
785
  __metadata("design:paramtypes", [Object, Object]),
958
786
  __metadata("design:returntype", Promise)
959
- ], PricingModuleService.prototype, "upsert", null);
787
+ ], PricingModuleService.prototype, "upsertPriceSets", null);
960
788
  __decorate([
961
789
  (0, utils_1.InjectManager)("baseRepository_"),
962
790
  __param(2, (0, utils_1.MedusaContext)()),
963
791
  __metadata("design:type", Function),
964
792
  __metadata("design:paramtypes", [Object, Object, Object]),
965
793
  __metadata("design:returntype", Promise)
966
- ], PricingModuleService.prototype, "update", null);
794
+ ], PricingModuleService.prototype, "updatePriceSets", null);
967
795
  __decorate([
968
796
  (0, utils_1.InjectTransactionManager)("baseRepository_"),
969
797
  __param(1, (0, utils_1.MedusaContext)()),
970
798
  __metadata("design:type", Function),
971
799
  __metadata("design:paramtypes", [Array, Object]),
972
800
  __metadata("design:returntype", Promise)
973
- ], PricingModuleService.prototype, "update_", null);
974
- __decorate([
975
- (0, utils_1.InjectManager)("baseRepository_"),
976
- __param(1, (0, utils_1.MedusaContext)()),
977
- __metadata("design:type", Function),
978
- __metadata("design:paramtypes", [Object, Object]),
979
- __metadata("design:returntype", Promise)
980
- ], PricingModuleService.prototype, "addRules", null);
801
+ ], PricingModuleService.prototype, "updatePriceSets_", null);
981
802
  __decorate([
982
803
  (0, utils_1.InjectManager)("baseRepository_"),
983
804
  (0, utils_1.EmitEvents)(),
@@ -986,23 +807,20 @@ __decorate([
986
807
  __metadata("design:paramtypes", [Object, Object]),
987
808
  __metadata("design:returntype", Promise)
988
809
  ], PricingModuleService.prototype, "addPrices", null);
989
- __decorate([
990
- (0, utils_1.InjectTransactionManager)("baseRepository_"),
991
- __param(1, (0, utils_1.MedusaContext)()),
992
- __metadata("design:type", Function),
993
- __metadata("design:paramtypes", [Array, Object]),
994
- __metadata("design:returntype", Promise)
995
- ], PricingModuleService.prototype, "removeRules", null);
996
810
  __decorate([
997
811
  (0, utils_1.InjectManager)("baseRepository_"),
998
- (0, utils_1.EmitEvents)(),
812
+ (0, utils_1.EmitEvents)()
813
+ // @ts-ignore
814
+ ,
999
815
  __param(1, (0, utils_1.MedusaContext)()),
1000
816
  __metadata("design:type", Function),
1001
817
  __metadata("design:paramtypes", [Array, Object]),
1002
818
  __metadata("design:returntype", Promise)
1003
819
  ], PricingModuleService.prototype, "createPriceLists", null);
1004
820
  __decorate([
1005
- (0, utils_1.InjectTransactionManager)("baseRepository_"),
821
+ (0, utils_1.InjectTransactionManager)("baseRepository_")
822
+ // @ts-ignore
823
+ ,
1006
824
  __param(1, (0, utils_1.MedusaContext)()),
1007
825
  __metadata("design:type", Function),
1008
826
  __metadata("design:paramtypes", [Array, Object]),
@@ -1050,14 +868,7 @@ __decorate([
1050
868
  __metadata("design:type", Function),
1051
869
  __metadata("design:paramtypes", [Array, Object]),
1052
870
  __metadata("design:returntype", Promise)
1053
- ], PricingModuleService.prototype, "create_", null);
1054
- __decorate([
1055
- (0, utils_1.InjectTransactionManager)("baseRepository_"),
1056
- __param(1, (0, utils_1.MedusaContext)()),
1057
- __metadata("design:type", Function),
1058
- __metadata("design:paramtypes", [Array, Object]),
1059
- __metadata("design:returntype", Promise)
1060
- ], PricingModuleService.prototype, "addRules_", null);
871
+ ], PricingModuleService.prototype, "createPriceSets_", null);
1061
872
  __decorate([
1062
873
  (0, utils_1.InjectTransactionManager)("baseRepository_"),
1063
874
  __param(1, (0, utils_1.MedusaContext)()),