@medusajs/pricing 0.1.13-preview-20240701060617 → 0.1.13-preview-20240701074916

Sign up to get free protection for your applications and to get access to all the features.
@@ -17,32 +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
20
  const generateMethodForModels = {
23
21
  PriceSet: _models_1.PriceSet,
24
22
  PriceList: _models_1.PriceList,
25
23
  PriceListRule: _models_1.PriceListRule,
26
- PriceListRuleValue: _models_1.PriceListRuleValue,
27
24
  PriceRule: _models_1.PriceRule,
28
25
  Price: _models_1.Price,
29
- RuleType: _models_1.RuleType,
30
26
  };
31
27
  class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generateMethodForModels, joiner_config_1.entityNameToLinkableKeysMap) {
32
- constructor({ baseRepository, pricingRepository, ruleTypeService, priceSetService, priceRuleService, priceService, priceListService, priceListRuleService, priceListRuleValueService, }, moduleDeclaration) {
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
36
  this.priceService_ = priceService;
43
37
  this.priceListService_ = priceListService;
44
38
  this.priceListRuleService_ = priceListRuleService;
45
- this.priceListRuleValueService_ = priceListRuleValueService;
46
39
  }
47
40
  __joinerConfig() {
48
41
  return joiner_config_1.joinerConfig;
@@ -63,18 +56,19 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
63
56
  async listPriceSets(filters = {}, config = {}, sharedContext = {}) {
64
57
  const pricingContext = this.setupCalculatedPriceConfig_(filters, config);
65
58
  const priceSets = await super.listPriceSets(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
- }
59
+ if (!pricingContext || !priceSets.length) {
60
+ return priceSets;
61
+ }
62
+ const priceSetIds = [];
63
+ const priceSetMap = new Map();
64
+ for (const priceSet of priceSets) {
65
+ priceSetIds.push(priceSet.id);
66
+ priceSetMap.set(priceSet.id, priceSet);
67
+ }
68
+ const calculatedPrices = await this.calculatePrices({ id: priceSetIds }, { context: pricingContext }, sharedContext);
69
+ for (const calculatedPrice of calculatedPrices) {
70
+ const priceSet = priceSetMap.get(calculatedPrice.id);
71
+ priceSet.calculated_price = calculatedPrice;
78
72
  }
79
73
  return priceSets;
80
74
  }
@@ -82,18 +76,19 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
82
76
  async listAndCountPriceSets(filters = {}, config = {}, sharedContext = {}) {
83
77
  const pricingContext = this.setupCalculatedPriceConfig_(filters, config);
84
78
  const [priceSets, count] = await super.listAndCountPriceSets(filters, config, sharedContext);
85
- if (pricingContext && priceSets.length) {
86
- const priceSetIds = [];
87
- const priceSetMap = new Map();
88
- for (const priceSet of priceSets) {
89
- priceSetIds.push(priceSet.id);
90
- priceSetMap.set(priceSet.id, priceSet);
91
- }
92
- const calculatedPrices = await this.calculatePrices({ id: priceSets.map((p) => p.id) }, { context: pricingContext }, sharedContext);
93
- for (const calculatedPrice of calculatedPrices) {
94
- const priceSet = priceSetMap.get(calculatedPrice.id);
95
- priceSet.calculated_price = calculatedPrice;
96
- }
79
+ if (!pricingContext || !priceSets.length) {
80
+ return [priceSets, count];
81
+ }
82
+ const priceSetIds = [];
83
+ const priceSetMap = new Map();
84
+ for (const priceSet of priceSets) {
85
+ priceSetIds.push(priceSet.id);
86
+ priceSetMap.set(priceSet.id, priceSet);
87
+ }
88
+ const calculatedPrices = await this.calculatePrices({ id: priceSetIds }, { context: pricingContext }, sharedContext);
89
+ for (const calculatedPrice of calculatedPrices) {
90
+ const priceSet = priceSetMap.get(calculatedPrice.id);
91
+ priceSet.calculated_price = calculatedPrice;
97
92
  }
98
93
  return [priceSets, count];
99
94
  }
@@ -145,12 +140,7 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
145
140
  const priceSets = await this.createPriceSets_(input, sharedContext);
146
141
  // TODO: Remove the need to refetch the data here
147
142
  const dbPriceSets = await this.listPriceSets({ id: priceSets.map((p) => p.id) }, {
148
- relations: [
149
- "rule_types",
150
- "prices",
151
- "price_rules",
152
- "prices.price_rules",
153
- ],
143
+ relations: ["prices", "prices.price_rules"],
154
144
  }, sharedContext);
155
145
  // Ensure the output to be in the same order as the input
156
146
  const results = priceSets.map((priceSet) => {
@@ -190,22 +180,12 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
190
180
  const priceSets = await this.baseRepository_.serialize(updateResult);
191
181
  return (0, utils_1.isString)(idOrSelector) ? priceSets[0] : priceSets;
192
182
  }
193
- async normalizeUpdateData(data, sharedContext) {
194
- const ruleAttributes = data
195
- .map((d) => d.prices?.map((p) => Object.keys(p.rules ?? [])) ?? [])
196
- .flat(Infinity)
197
- .filter(Boolean);
198
- const ruleTypes = await this.ruleTypeService_.list({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
199
- const ruleTypeMap = ruleTypes.reduce((acc, curr) => {
200
- acc.set(curr.rule_attribute, curr);
201
- return acc;
202
- }, new Map());
183
+ async normalizeUpdateData(data) {
203
184
  return data.map((priceSet) => {
204
185
  const prices = priceSet.prices?.map((price) => {
205
186
  const rules = Object.entries(price.rules ?? {}).map(([attribute, value]) => {
206
187
  return {
207
- price_set_id: priceSet.id,
208
- rule_type_id: ruleTypeMap.get(attribute).id,
188
+ attribute,
209
189
  value,
210
190
  };
211
191
  });
@@ -225,10 +205,9 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
225
205
  });
226
206
  }
227
207
  async updatePriceSets_(data, sharedContext = {}) {
228
- // TODO: We are not handling rule types, rules, etc. here, add support after data models are finalized
229
208
  // TODO: Since money IDs are rarely passed, this will delete all previous data and insert new entries.
230
209
  // We can make the `insert` inside upsertWithReplace do an `upsert` instead to avoid this
231
- const normalizedData = await this.normalizeUpdateData(data, sharedContext);
210
+ const normalizedData = await this.normalizeUpdateData(data);
232
211
  const prices = normalizedData.flatMap((priceSet) => priceSet.prices || []);
233
212
  const { entities: upsertedPrices } = await this.priceService_.upsertWithReplace(prices, { relations: ["price_rules"] }, sharedContext);
234
213
  const priceSetsToUpsert = normalizedData.map((priceSet) => {
@@ -287,49 +266,34 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
287
266
  }
288
267
  async createPriceSets_(data, sharedContext = {}) {
289
268
  const input = Array.isArray(data) ? data : [data];
290
- const ruleAttributes = (0, utils_1.deduplicate)(data
291
- .map((d) => d.prices?.map((ma) => Object.keys(ma?.rules ?? {})).flat() ?? [])
292
- .flat());
293
- const ruleTypes = await this.ruleTypeService_.list({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
294
- const ruleTypeMap = ruleTypes.reduce((acc, curr) => {
295
- acc.set(curr.rule_attribute, curr);
296
- return acc;
297
- }, new Map());
298
- const invalidRuleAttributes = ruleAttributes.filter((r) => !ruleTypeMap.has(r));
299
- if (invalidRuleAttributes.length > 0) {
300
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, `Rule types don't exist for prices with rule attribute: ${invalidRuleAttributes.join(", ")}`);
301
- }
302
269
  const toCreate = input.map((inputData) => {
303
- const id = (0, utils_1.generateEntityId)(inputData.id, price_set_1.PriceSetIdPrefix);
304
- const { prices, ...rest } = inputData;
305
- let pricesData = [];
306
- if (inputData.prices) {
307
- pricesData = inputData.prices.map((price) => {
308
- let { rules: priceRules = {}, ...rest } = price;
309
- const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
310
- const numberOfRules = Object.keys(cleanRules).length;
311
- const rulesDataMap = new Map();
312
- Object.entries(priceRules).map(([attribute, value]) => {
313
- const rule = {
314
- price_set_id: id,
315
- rule_type_id: ruleTypeMap.get(attribute).id,
316
- value,
317
- };
318
- rulesDataMap.set(JSON.stringify(rule), rule);
319
- });
320
- return {
321
- ...rest,
322
- title: "", // TODO: accept title
323
- rules_count: numberOfRules,
324
- price_rules: Array.from(rulesDataMap.values()),
270
+ const entry = {
271
+ ...inputData,
272
+ };
273
+ if (!inputData.prices) {
274
+ return entry;
275
+ }
276
+ const pricesData = inputData.prices.map((price) => {
277
+ let { rules: priceRules = {}, ...rest } = price;
278
+ const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
279
+ const rules = Object.entries(cleanRules);
280
+ const numberOfRules = rules.length;
281
+ const rulesDataMap = new Map();
282
+ rules.map(([attribute, value]) => {
283
+ const rule = {
284
+ attribute,
285
+ value,
325
286
  };
287
+ rulesDataMap.set(JSON.stringify(rule), rule);
326
288
  });
327
- }
328
- return {
329
- ...rest,
330
- id,
331
- prices: pricesData,
332
- };
289
+ return {
290
+ ...rest,
291
+ rules_count: numberOfRules,
292
+ price_rules: Array.from(rulesDataMap.values()),
293
+ };
294
+ });
295
+ entry.prices = pricesData;
296
+ return entry;
333
297
  });
334
298
  // Bulk create price sets
335
299
  const createdPriceSets = await this.priceSetService_.create(toCreate, sharedContext);
@@ -368,36 +332,24 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
368
332
  return createdPriceSets;
369
333
  }
370
334
  async addPrices_(input, sharedContext = {}) {
371
- const priceSets = await this.listPriceSets({ id: input.map((d) => d.priceSetId) }, { relations: ["rule_types"] }, sharedContext);
335
+ const priceSets = await this.listPriceSets({ id: input.map((d) => d.priceSetId) }, {}, sharedContext);
372
336
  const priceSetMap = new Map(priceSets.map((p) => [p.id, p]));
373
- const ruleTypeMap = new Map(priceSets.map((priceSet) => [
374
- priceSet.id,
375
- new Map(priceSet.rule_types?.map((rt) => [rt.rule_attribute, rt]) ?? []),
376
- ]));
377
- input.forEach(({ priceSetId, prices }) => {
337
+ input.forEach(({ priceSetId }) => {
378
338
  const priceSet = priceSetMap.get(priceSetId);
379
339
  if (!priceSet) {
380
340
  throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price set with id: ${priceSetId} not found`);
381
341
  }
382
- const ruleAttributes = prices
383
- .map((d) => (d.rules ? Object.keys(d.rules) : []))
384
- .flat();
385
- const invalidRuleAttributes = ruleAttributes.filter((r) => !ruleTypeMap.get(priceSetId).has(r));
386
- if (invalidRuleAttributes.length > 0) {
387
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.NOT_FOUND, `Rule types don't exist for: ${invalidRuleAttributes.join(", ")}`);
388
- }
389
342
  });
390
343
  const pricesToCreate = input.flatMap(({ priceSetId, prices }) => prices.map((price) => {
391
344
  const numberOfRules = Object.entries(price?.rules ?? {}).length;
392
345
  const priceRules = Object.entries(price.rules ?? {}).map(([attribute, value]) => ({
393
- rule_type_id: ruleTypeMap.get(priceSetId).get(attribute).id,
394
346
  price_set_id: priceSetId,
347
+ attribute: attribute,
395
348
  value,
396
349
  }));
397
350
  return {
398
351
  ...price,
399
352
  price_set_id: priceSetId,
400
- title: "test", // TODO: accept title
401
353
  rules_count: numberOfRules,
402
354
  price_rules: priceRules,
403
355
  };
@@ -434,56 +386,52 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
434
386
  return prices;
435
387
  }
436
388
  async createPriceLists_(data, sharedContext = {}) {
437
- const ruleTypeAttributes = [];
438
- for (const priceListData of data) {
439
- const { prices = [], rules: priceListRules = {} } = priceListData;
440
- ruleTypeAttributes.push(...Object.keys(priceListRules));
441
- for (const price of prices) {
442
- const { rules: priceListPriceRules = {} } = price;
443
- ruleTypeAttributes.push(...Object.keys(priceListPriceRules));
444
- }
445
- }
446
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
447
- const invalidRuleTypes = (0, utils_1.arrayDifference)((0, utils_1.deduplicate)(ruleTypeAttributes), ruleTypes.map((ruleType) => ruleType.rule_attribute));
448
- if (invalidRuleTypes.length) {
449
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Cannot find RuleTypes with rule_attribute - ${invalidRuleTypes.join(", ")}`);
450
- }
451
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
452
- const priceListsToCreate = data.map((priceListData) => {
453
- const id = (0, utils_1.generateEntityId)(priceListData.id, price_list_1.PriceListIdPrefix);
454
- const { prices = [], rules = {}, ...rest } = priceListData;
455
- (0, _utils_1.validatePriceListDates)(priceListData);
456
- const priceListRules = Object.entries(rules).map(([attribute, value]) => {
457
- const ruleType = ruleTypeMap.get(attribute);
458
- return {
459
- price_list_id: id,
460
- rule_type_id: ruleType.id,
461
- price_list_rule_values: value.map((v) => ({ value: v })),
462
- };
463
- });
464
- const pricesData = prices.map((price) => {
465
- const priceRules = Object.entries(price.rules ?? {}).map(([ruleAttribute, ruleValue]) => {
389
+ const normalized = this.normalizePriceListDate(data);
390
+ const priceListsToCreate = normalized.map((priceListData) => {
391
+ const entry = {
392
+ ...priceListData,
393
+ rules: undefined,
394
+ };
395
+ if (priceListData.prices) {
396
+ const pricesData = priceListData.prices.map((price) => {
397
+ let { rules: priceRules = {}, ...rest } = price;
398
+ const cleanRules = priceRules ? (0, utils_1.removeNullish)(priceRules) : {};
399
+ const rules = Object.entries(cleanRules);
400
+ const numberOfRules = rules.length;
401
+ const rulesDataMap = new Map();
402
+ rules.map(([attribute, value]) => {
403
+ const rule = {
404
+ attribute,
405
+ value,
406
+ };
407
+ rulesDataMap.set(JSON.stringify(rule), rule);
408
+ });
466
409
  return {
467
- price_set_id: price.price_set_id,
468
- rule_type_id: ruleTypeMap.get(ruleAttribute)?.id,
469
- value: ruleValue,
410
+ ...rest,
411
+ rules_count: numberOfRules,
412
+ price_rules: Array.from(rulesDataMap.values()),
470
413
  };
471
414
  });
472
- return {
473
- price_list_id: id,
474
- title: "test",
475
- rules_count: Object.keys(price.rules ?? {}).length,
476
- price_rules: priceRules,
477
- ...price,
478
- };
479
- });
480
- return {
481
- id,
482
- ...rest,
483
- rules_count: Object.keys(rules).length,
484
- price_list_rules: priceListRules,
485
- prices: pricesData,
486
- };
415
+ entry.prices = pricesData;
416
+ }
417
+ if (priceListData.rules) {
418
+ const cleanRules = priceListData.rules
419
+ ? (0, utils_1.removeNullish)(priceListData.rules)
420
+ : {};
421
+ const rules = Object.entries(cleanRules);
422
+ const numberOfRules = rules.length;
423
+ const rulesDataMap = new Map();
424
+ rules.map(([attribute, value]) => {
425
+ const rule = {
426
+ attribute,
427
+ value,
428
+ };
429
+ rulesDataMap.set(JSON.stringify(rule), rule);
430
+ });
431
+ entry.price_list_rules = Array.from(rulesDataMap.values());
432
+ entry.rules_count = numberOfRules;
433
+ }
434
+ return entry;
487
435
  });
488
436
  const priceLists = await this.priceListService_.create(priceListsToCreate, sharedContext);
489
437
  /**
@@ -537,71 +485,52 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
537
485
  return priceLists;
538
486
  }
539
487
  async updatePriceLists_(data, sharedContext = {}) {
540
- const updatedPriceLists = [];
541
- const ruleAttributes = [];
542
- const priceListIds = [];
543
- for (const priceListData of data) {
544
- if (typeof priceListData.rules === "object") {
545
- ruleAttributes.push(...Object.keys(priceListData.rules));
546
- priceListIds.push(priceListData.id);
547
- }
548
- }
549
- const existingPriceLists = await this.listPriceLists({ id: priceListIds }, { relations: ["price_list_rules"] }, sharedContext);
550
- const priceListRuleIds = existingPriceLists
551
- .map((pl) => (pl.price_list_rules || []).map((plr) => plr.id))
552
- .flat();
553
- const existingPriceListRules = await this.listPriceListRules({ id: priceListRuleIds }, {}, sharedContext);
554
- if (existingPriceListRules.length) {
555
- await this.deletePriceListRules(existingPriceListRules.map((plr) => plr.id), sharedContext);
488
+ const existingPriceLists = await this.priceListService_.list({ id: data.map((d) => d.id) }, {}, sharedContext);
489
+ if (existingPriceLists.length !== data.length) {
490
+ const diff = (0, utils_1.arrayDifference)(data.map((d) => d.id), existingPriceLists.map((p) => p.id));
491
+ throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price lists with ids: '${diff.join(", ")}' not found`);
556
492
  }
557
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
558
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
559
- for (const priceListData of data) {
560
- const { rules, ...priceListOnlyData } = priceListData;
561
- const updatePriceListData = {
562
- ...priceListOnlyData,
493
+ const normalizedData = this.normalizePriceListDate(data).map((priceList) => {
494
+ const entry = {
495
+ ...priceList,
496
+ rules: undefined,
497
+ price_list_rules: undefined,
563
498
  };
564
- (0, _utils_1.validatePriceListDates)(updatePriceListData);
565
- if (typeof rules === "object") {
566
- updatePriceListData.rules_count = Object.keys(rules).length;
567
- }
568
- const [updatedPriceList] = (await this.priceListService_.update([updatePriceListData], sharedContext));
569
- updatedPriceLists.push(updatedPriceList);
570
- for (const [ruleAttribute, ruleValues = []] of Object.entries(rules || {})) {
571
- let ruleType = ruleTypeMap.get(ruleAttribute);
572
- if (!ruleType) {
573
- ;
574
- [ruleType] = await this.createRuleTypes([{ name: ruleAttribute, rule_attribute: ruleAttribute }], sharedContext);
575
- ruleTypeMap.set(ruleAttribute, ruleType);
576
- }
577
- const [priceListRule] = await this.priceListRuleService_.create([
578
- {
579
- price_list_id: updatedPriceList.id,
580
- rule_type_id: ruleType?.id,
581
- },
582
- ], sharedContext);
583
- for (const ruleValue of ruleValues) {
584
- await this.priceListRuleValueService_.create([{ price_list_rule_id: priceListRule.id, value: ruleValue }], sharedContext);
585
- }
499
+ if (typeof priceList.rules === "object") {
500
+ const cleanRules = priceList.rules
501
+ ? (0, utils_1.removeNullish)(priceList.rules)
502
+ : {};
503
+ const rules = Object.entries(cleanRules);
504
+ const numberOfRules = rules.length;
505
+ const rulesDataMap = new Map();
506
+ rules.map(([attribute, value]) => {
507
+ const rule = {
508
+ attribute,
509
+ value,
510
+ };
511
+ rulesDataMap.set(JSON.stringify(rule), rule);
512
+ });
513
+ entry.price_list_rules = Array.from(rulesDataMap.values());
514
+ entry.rules_count = numberOfRules;
586
515
  }
587
- }
588
- return updatedPriceLists;
516
+ return entry;
517
+ });
518
+ const { entities } = await this.priceListService_.upsertWithReplace(normalizedData, {
519
+ relations: ["price_list_rules"],
520
+ });
521
+ return entities;
589
522
  }
590
523
  async updatePriceListPrices_(data, sharedContext = {}) {
591
- const ruleTypeAttributes = [];
592
524
  const priceListIds = [];
593
525
  const priceIds = [];
594
526
  for (const priceListData of data) {
595
527
  priceListIds.push(priceListData.price_list_id);
596
528
  for (const price of priceListData.prices) {
597
529
  priceIds.push(price.id);
598
- ruleTypeAttributes.push(...Object.keys(price.rules || {}));
599
530
  }
600
531
  }
601
532
  const prices = await this.listPrices({ id: priceIds }, { take: null, relations: ["price_rules"] }, sharedContext);
602
533
  const priceMap = new Map(prices.map((price) => [price.id, price]));
603
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
604
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
605
534
  const priceLists = await this.listPriceLists({ id: priceListIds }, { take: null }, sharedContext);
606
535
  const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
607
536
  const pricesToUpdate = [];
@@ -618,7 +547,7 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
618
547
  const priceRules = price.price_rules;
619
548
  priceRulesToCreate.push(...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
620
549
  price_set_id,
621
- rule_type_id: ruleTypeMap.get(ruleAttribute).id,
550
+ attribute: ruleAttribute,
622
551
  value: ruleValue,
623
552
  price_id: price.id,
624
553
  })));
@@ -640,18 +569,10 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
640
569
  await this.priceService_.delete(ids, sharedContext);
641
570
  }
642
571
  async addPriceListPrices_(data, sharedContext = {}) {
643
- const ruleTypeAttributes = [];
644
572
  const priceListIds = [];
645
- const priceSetIds = [];
646
573
  for (const priceListData of data) {
647
574
  priceListIds.push(priceListData.price_list_id);
648
- for (const price of priceListData.prices) {
649
- ruleTypeAttributes.push(...Object.keys(price.rules || {}));
650
- priceSetIds.push(price.price_set_id);
651
- }
652
575
  }
653
- const ruleTypes = await this.listRuleTypes({ rule_attribute: ruleTypeAttributes }, { take: null }, sharedContext);
654
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
655
576
  const priceLists = await this.listPriceLists({ id: priceListIds }, {}, sharedContext);
656
577
  const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
657
578
  const pricesToCreate = [];
@@ -665,8 +586,8 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
665
586
  const noOfRules = Object.keys(priceRules).length;
666
587
  const priceRulesToCreate = Object.entries(priceRules).map(([ruleAttribute, ruleValue]) => {
667
588
  return {
668
- price_set_id: priceData.price_set_id,
669
- rule_type_id: ruleTypeMap.get(ruleAttribute)?.id,
589
+ price_list_id: priceData.price_set_id,
590
+ attribute: ruleAttribute,
670
591
  value: ruleValue,
671
592
  };
672
593
  });
@@ -708,85 +629,95 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.MedusaService(generat
708
629
  }
709
630
  async setPriceListRules_(data, sharedContext = {}) {
710
631
  // TODO: re think this method
711
- const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, { relations: ["price_list_rules", "price_list_rules.rule_type"] }, sharedContext);
712
- const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
713
- const ruleTypes = await this.listRuleTypes({ rule_attribute: data.map((d) => Object.keys(d.rules)).flat() }, { take: null });
714
- const ruleTypeMap = new Map(ruleTypes.map((rt) => [rt.rule_attribute, rt]));
715
- const ruleIdsToUpdate = [];
716
- const rulesToCreate = [];
717
- const priceRuleValues = new Map();
718
- for (const { price_list_id: priceListId, rules } of data) {
719
- const priceList = priceListMap.get(priceListId);
720
- if (!priceList) {
721
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price list with id: ${priceListId} not found`);
632
+ const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, {
633
+ relations: ["price_list_rules"],
634
+ }, sharedContext);
635
+ const rulesMap = new Map();
636
+ data.forEach((rule) => {
637
+ if (!rulesMap.has(rule.price_list_id)) {
638
+ rulesMap.set(rule.price_list_id, []);
722
639
  }
723
- const priceListRulesMap = new Map(priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p]));
724
- const priceListRuleValues = new Map();
725
- Object.entries(rules).map(async ([key, value]) => {
726
- const ruleType = ruleTypeMap.get(key);
727
- if (!ruleType) {
728
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Rule type with attribute: ${key} not found`);
729
- }
730
- const rule = priceListRulesMap.get(key);
731
- priceListRuleValues.set(ruleType.id, Array.isArray(value) ? value : [value]);
732
- if (!rule) {
733
- rulesToCreate.push({
734
- rule_type_id: ruleType.id,
735
- price_list_id: priceListId,
736
- });
737
- }
738
- else {
739
- ruleIdsToUpdate.push(rule.id);
740
- }
640
+ Object.entries(rule.rules).forEach(([key, value]) => {
641
+ rulesMap.get(rule.price_list_id).push([key, value]);
741
642
  });
742
- priceRuleValues.set(priceListId, priceListRuleValues);
743
- }
744
- const [createdRules, priceListValuesToDelete] = await (0, utils_1.promiseAll)([
745
- this.priceListRuleService_.create(rulesToCreate),
746
- this.priceListRuleValueService_.list({ price_list_rule_id: ruleIdsToUpdate }, { take: null }),
747
- ]);
748
- const priceListRuleValuesToCreate = [];
749
- for (const { id, price_list_id, rule_type_id } of createdRules) {
750
- const ruleValues = priceRuleValues.get(price_list_id);
751
- if (!ruleValues) {
752
- continue;
753
- }
754
- const values = ruleValues.get(rule_type_id);
755
- if (!values) {
756
- continue;
643
+ });
644
+ const priceListsUpsert = priceLists
645
+ .map((priceList) => {
646
+ const allRules = new Map(priceList.price_list_rules
647
+ .toArray()
648
+ .map((r) => [r.attribute, r.value]));
649
+ const rules = rulesMap.get(priceList.id);
650
+ if (!rules?.length) {
651
+ return;
757
652
  }
758
- values.forEach((v) => {
759
- priceListRuleValuesToCreate.push({
760
- price_list_rule_id: id,
761
- value: v,
762
- });
653
+ rules.forEach(([key, value]) => {
654
+ allRules.set(key, value);
763
655
  });
764
- }
765
- await (0, utils_1.promiseAll)([
766
- this.priceListRuleValueService_.delete(priceListValuesToDelete.map((p) => p.id), sharedContext),
767
- this.priceListRuleValueService_.create(priceListRuleValuesToCreate, sharedContext),
768
- ]);
769
- return priceLists;
656
+ return {
657
+ ...priceList,
658
+ rules_count: allRules.size,
659
+ price_list_rules: Array.from(allRules).map(([attribute, value]) => ({
660
+ attribute,
661
+ value,
662
+ })),
663
+ };
664
+ })
665
+ .filter(Boolean);
666
+ const { entities } = await this.priceListService_.upsertWithReplace(priceListsUpsert, { relations: ["price_list_rules"] }, sharedContext);
667
+ return entities;
770
668
  }
771
669
  async removePriceListRules_(data, sharedContext = {}) {
772
- const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, { relations: ["price_list_rules", "price_list_rules.rule_type"] }, sharedContext);
773
- const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
774
- const idsToDelete = [];
775
- for (const { price_list_id: priceListId, rules } of data) {
776
- const priceList = priceListMap.get(priceListId);
777
- if (!priceList) {
778
- throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price list with id: ${priceListId} not found`);
670
+ // TODO: re think this method
671
+ const priceLists = await this.priceListService_.list({ id: data.map((d) => d.price_list_id) }, {
672
+ relations: ["price_list_rules"],
673
+ }, sharedContext);
674
+ const rulesMap = new Map();
675
+ data.forEach((rule) => {
676
+ if (!rulesMap.has(rule.price_list_id)) {
677
+ rulesMap.set(rule.price_list_id, []);
779
678
  }
780
- const priceListRulesMap = new Map(priceList.price_list_rules.map((p) => [p.rule_type.rule_attribute, p]));
781
- rules.map(async (rule_attribute) => {
782
- const rule = priceListRulesMap.get(rule_attribute);
783
- if (rule) {
784
- idsToDelete.push(rule.id);
785
- }
679
+ rule.rules.forEach((key) => {
680
+ rulesMap.get(rule.price_list_id).push([key, undefined]);
786
681
  });
787
- }
788
- await this.priceListRuleService_.delete(idsToDelete);
789
- return priceLists;
682
+ });
683
+ const priceListsUpsert = priceLists
684
+ .map((priceList) => {
685
+ const allRules = new Map(priceList.price_list_rules
686
+ .toArray()
687
+ .map((r) => [r.attribute, r.value]));
688
+ const rules = rulesMap.get(priceList.id);
689
+ if (!rules?.length) {
690
+ return;
691
+ }
692
+ rules.forEach(([key, value]) => {
693
+ allRules.set(key, value);
694
+ });
695
+ return {
696
+ ...priceList,
697
+ rules_count: allRules.size,
698
+ price_list_rules: Array.from(allRules)
699
+ .map(([attribute, value]) => ({
700
+ attribute,
701
+ value,
702
+ }))
703
+ .filter((r) => !!r.value),
704
+ };
705
+ })
706
+ .filter(Boolean);
707
+ const { entities } = await this.priceListService_.upsertWithReplace(priceListsUpsert, { relations: ["price_list_rules"] }, sharedContext);
708
+ return entities;
709
+ }
710
+ normalizePriceListDate(data) {
711
+ return data.map((priceListData) => {
712
+ (0, _utils_1.validatePriceListDates)(priceListData);
713
+ if (!!priceListData.starts_at) {
714
+ priceListData.starts_at = (0, utils_1.GetIsoStringFromDate)(priceListData.starts_at);
715
+ }
716
+ if (!!priceListData.ends_at) {
717
+ priceListData.ends_at = (0, utils_1.GetIsoStringFromDate)(priceListData.ends_at);
718
+ }
719
+ return priceListData;
720
+ });
790
721
  }
791
722
  }
792
723
  exports.default = PricingModuleService;