@medusajs/pricing 0.1.12-snapshot-20240328221015 → 0.2.0-next-20240429170320

Sign up to get free protection for your applications and to get access to all the features.
@@ -4,6 +4,7 @@ export declare const LinkableKeys: {
4
4
  price_set_id: string;
5
5
  price_list_id: string;
6
6
  price_id: string;
7
+ rule_type_id: string;
7
8
  };
8
9
  export declare const entityNameToLinkableKeysMap: MapToConfig;
9
10
  export declare const joinerConfig: ModuleJoinerConfig;
@@ -11,6 +11,7 @@ exports.LinkableKeys = {
11
11
  price_set_id: _models_1.PriceSet.name,
12
12
  price_list_id: _models_1.PriceList.name,
13
13
  price_id: _models_1.Price.name,
14
+ rule_type_id: _models_1.RuleType.name,
14
15
  };
15
16
  const entityLinkableKeysMap = {};
16
17
  Object.entries(exports.LinkableKeys).forEach(([key, value]) => {
@@ -39,5 +40,17 @@ exports.joinerConfig = {
39
40
  methodSuffix: "PriceLists",
40
41
  },
41
42
  },
43
+ {
44
+ name: ["price", "prices"],
45
+ args: {
46
+ methodSuffix: "Prices",
47
+ },
48
+ },
49
+ {
50
+ name: ["rule_type", "rule_types"],
51
+ args: {
52
+ methodSuffix: "RuleTypes",
53
+ },
54
+ },
42
55
  ],
43
56
  };
@@ -6,7 +6,7 @@ class Migration20230929122253 extends migrations_1.Migration {
6
6
  async up() {
7
7
  this.addSql('create table if not exists "money_amount" ("id" text not null, "currency_code" text not null, "amount" numeric not null, "min_quantity" numeric null, "max_quantity" numeric null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "money_amount_pkey" primary key ("id"));');
8
8
  this.addSql('create table "price_set" ("id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_set_pkey" primary key ("id"));');
9
- this.addSql('create table "price" ("id" text not null, "title" text, "price_set_id" text not null, "money_amount_id" text not null, "rules_count" integer not null default 0, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_pkey" primary key ("id"));');
9
+ this.addSql('create table "price" ("id" text not null, "title" text, "price_set_id" text not null, "money_amount_id" text not null, "raw_amount" jsonb not null, "rules_count" integer not null default 0, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_pkey" primary key ("id"));');
10
10
  this.addSql('alter table "price" add constraint "price_money_amount_id_unique" unique ("money_amount_id");');
11
11
  this.addSql('create table "rule_type" ("id" text not null, "name" text not null, "rule_attribute" text not null, "default_priority" integer not null default 0, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "rule_type_pkey" primary key ("id"));');
12
12
  this.addSql('create table "price_set_rule_type" ("id" text not null, "price_set_id" text not null, "rule_type_id" text not null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "price_set_rule_type_pkey" primary key ("id"));');
@@ -47,10 +47,12 @@ __decorate([
47
47
  __metadata("design:type", String)
48
48
  ], PriceList.prototype, "id", void 0);
49
49
  __decorate([
50
+ (0, utils_1.Searchable)(),
50
51
  (0, core_1.Property)({ columnType: "text" }),
51
52
  __metadata("design:type", String)
52
53
  ], PriceList.prototype, "title", void 0);
53
54
  __decorate([
55
+ (0, utils_1.Searchable)(),
54
56
  (0, core_1.Property)({ columnType: "text" }),
55
57
  __metadata("design:type", String)
56
58
  ], PriceList.prototype, "description", void 0);
@@ -1,4 +1,5 @@
1
1
  import { DAL } from "@medusajs/types";
2
+ import { BigNumber } from "@medusajs/utils";
2
3
  import { Collection, OptionalProps } from "@mikro-orm/core";
3
4
  import PriceList from "./price-list";
4
5
  import PriceRule from "./price-rule";
@@ -9,7 +10,8 @@ export default class Price {
9
10
  id: string;
10
11
  title: string | null;
11
12
  currency_code: string;
12
- amount: number;
13
+ amount: BigNumber | number;
14
+ raw_amount: Record<string, unknown>;
13
15
  min_quantity: number | null;
14
16
  max_quantity: number | null;
15
17
  price_set_id: string;
@@ -74,9 +74,13 @@ __decorate([
74
74
  __metadata("design:type", String)
75
75
  ], Price.prototype, "currency_code", void 0);
76
76
  __decorate([
77
- (0, core_1.Property)({ columnType: "numeric", serializer: Number }),
78
- __metadata("design:type", Number)
77
+ (0, utils_1.MikroOrmBigNumberProperty)(),
78
+ __metadata("design:type", Object)
79
79
  ], Price.prototype, "amount", void 0);
80
+ __decorate([
81
+ (0, core_1.Property)({ columnType: "jsonb" }),
82
+ __metadata("design:type", Object)
83
+ ], Price.prototype, "raw_amount", void 0);
80
84
  __decorate([
81
85
  (0, core_1.Property)({ columnType: "numeric", nullable: true }),
82
86
  __metadata("design:type", Object)
File without changes
@@ -1,7 +1,8 @@
1
- import { AddPricesDTO, Context, DAL, InternalModuleDeclaration, ModuleJoinerConfig, ModulesSdkTypes, PriceSetDTO, PricingContext, PricingFilters, PricingRepositoryService, PricingTypes, RuleTypeDTO } from "@medusajs/types";
1
+ import { AddPricesDTO, Context, CreatePriceRuleDTO, DAL, FindConfig, InternalModuleDeclaration, ModuleJoinerConfig, ModulesSdkTypes, PriceSetDTO, PricingContext, PricingFilters, PricingRepositoryService, PricingTypes, RuleTypeDTO, UpsertPriceSetDTO } from "@medusajs/types";
2
2
  import { ModulesSdkUtils } from "@medusajs/utils";
3
3
  import { Price, PriceList, PriceListRule, PriceListRuleValue, PriceRule, PriceSet, PriceSetRuleType, RuleType } from "../models";
4
4
  import { PriceListService, RuleTypeService } from ".";
5
+ import { UpdatePriceSetInput } from "src/types/services";
5
6
  type InjectedDependencies = {
6
7
  baseRepository: DAL.RepositoryService;
7
8
  pricingRepository: PricingRepositoryService;
@@ -49,23 +50,31 @@ export default class PricingModuleService<TPriceSet extends PriceSet = PriceSet,
49
50
  protected readonly priceListRuleValueService_: ModulesSdkTypes.InternalModuleService<TPriceListRuleValue>;
50
51
  constructor({ baseRepository, pricingRepository, ruleTypeService, priceSetService, priceRuleService, priceSetRuleTypeService, priceService, priceListService, priceListRuleService, priceListRuleValueService, }: InjectedDependencies, moduleDeclaration: InternalModuleDeclaration);
51
52
  __joinerConfig(): ModuleJoinerConfig;
53
+ private setupCalculatedPriceConfig_;
54
+ list(filters?: PricingTypes.FilterablePriceSetProps, config?: FindConfig<PricingTypes.PriceSetDTO>, sharedContext?: Context): Promise<PriceSetDTO[]>;
55
+ listAndCount(filters?: PricingTypes.FilterablePriceSetProps, config?: FindConfig<PricingTypes.PriceSetDTO>, sharedContext?: Context): Promise<[PriceSetDTO[], number]>;
52
56
  calculatePrices(pricingFilters: PricingFilters, pricingContext?: PricingContext, sharedContext?: Context): Promise<PricingTypes.CalculatedPriceSet[]>;
53
57
  create(data: PricingTypes.CreatePriceSetDTO, sharedContext?: Context): Promise<PriceSetDTO>;
54
58
  create(data: PricingTypes.CreatePriceSetDTO[], sharedContext?: Context): Promise<PriceSetDTO[]>;
59
+ upsert(data: UpsertPriceSetDTO[], sharedContext?: Context): Promise<PriceSetDTO[]>;
60
+ upsert(data: UpsertPriceSetDTO, sharedContext?: Context): Promise<PriceSetDTO>;
61
+ update(id: string, data: PricingTypes.UpdatePriceSetDTO, sharedContext?: Context): Promise<PriceSetDTO>;
62
+ update(selector: PricingTypes.FilterablePriceSetProps, data: PricingTypes.UpdatePriceSetDTO, sharedContext?: Context): Promise<PriceSetDTO[]>;
63
+ private normalizeUpdateData;
64
+ protected update_(data: UpdatePriceSetInput[], sharedContext?: Context): Promise<PriceSet[]>;
55
65
  addRules(data: PricingTypes.AddRulesDTO, sharedContext?: Context): Promise<PricingTypes.PriceSetDTO>;
56
66
  addRules(data: PricingTypes.AddRulesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceSetDTO[]>;
57
67
  addPrices(data: AddPricesDTO, sharedContext?: Context): Promise<PricingTypes.PriceSetDTO>;
58
68
  addPrices(data: AddPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceSetDTO[]>;
59
69
  removeRules(data: PricingTypes.RemovePriceSetRulesDTO[], sharedContext?: Context): Promise<void>;
60
- update(data: PricingTypes.UpdatePriceSetDTO[], sharedContext?: Context): Promise<PriceSetDTO[]>;
61
70
  createPriceLists(data: PricingTypes.CreatePriceListDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
62
71
  updatePriceLists(data: PricingTypes.UpdatePriceListDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
63
72
  createPriceListRules(data: PricingTypes.CreatePriceListRuleDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListRuleDTO[]>;
64
73
  createPriceListRules_(data: PricingTypes.CreatePriceListRuleDTO[], sharedContext?: Context): Promise<TPriceListRule[]>;
65
74
  updatePriceListRules(data: PricingTypes.UpdatePriceListRuleDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListRuleDTO[]>;
66
- updatePriceListPrices(data: PricingTypes.UpdatePriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
75
+ updatePriceListPrices(data: PricingTypes.UpdatePriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceDTO[]>;
67
76
  removePrices(ids: string[], sharedContext?: Context): Promise<void>;
68
- addPriceListPrices(data: PricingTypes.AddPriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
77
+ addPriceListPrices(data: PricingTypes.AddPriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceDTO[]>;
69
78
  setPriceListRules(data: PricingTypes.SetPriceListRulesDTO, sharedContext?: Context): Promise<PricingTypes.PriceListDTO>;
70
79
  removePriceListRules(data: PricingTypes.RemovePriceListRulesDTO, sharedContext?: Context): Promise<PricingTypes.PriceListDTO>;
71
80
  protected create_(data: PricingTypes.CreatePriceSetDTO[], sharedContext?: Context): Promise<TPriceSet[]>;
@@ -73,9 +82,9 @@ export default class PricingModuleService<TPriceSet extends PriceSet = PriceSet,
73
82
  protected addPrices_(input: AddPricesDTO[], sharedContext?: Context): Promise<void>;
74
83
  protected createPriceLists_(data: PricingTypes.CreatePriceListDTO[], sharedContext?: Context): Promise<TPriceList[]>;
75
84
  protected updatePriceLists_(data: PricingTypes.UpdatePriceListDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
76
- protected updatePriceListPrices_(data: PricingTypes.UpdatePriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
85
+ protected updatePriceListPrices_(data: PricingTypes.UpdatePriceListPricesDTO[], sharedContext?: Context): Promise<TPrice[]>;
77
86
  protected removePrices_(ids: string[], sharedContext?: Context): Promise<void>;
78
- protected addPriceListPrices_(data: PricingTypes.AddPriceListPricesDTO[], sharedContext?: Context): Promise<PricingTypes.PriceListDTO[]>;
87
+ protected addPriceListPrices_(data: PricingTypes.AddPriceListPricesDTO[], sharedContext?: Context): Promise<TPrice[]>;
79
88
  protected setPriceListRules_(data: PricingTypes.SetPriceListRulesDTO[], sharedContext?: Context): Promise<TPriceList[]>;
80
89
  protected removePriceListRules_(data: PricingTypes.RemovePriceListRulesDTO[], sharedContext?: Context): Promise<TPriceList[]>;
81
90
  }
@@ -17,8 +17,8 @@ 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_set_1 = require("../models/price-set");
21
20
  const price_list_1 = require("../models/price-list");
21
+ const price_set_1 = require("../models/price-set");
22
22
  const generateMethodForModels = [
23
23
  _models_1.PriceList,
24
24
  _models_1.PriceListRule,
@@ -48,13 +48,61 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
48
48
  __joinerConfig() {
49
49
  return joiner_config_1.joinerConfig;
50
50
  }
51
+ setupCalculatedPriceConfig_(filters, config) {
52
+ const fieldIdx = config.relations?.indexOf("calculated_price");
53
+ const shouldCalculatePrice = fieldIdx > -1;
54
+ if (!shouldCalculatePrice) {
55
+ return;
56
+ }
57
+ let pricingContext = filters.context ?? {};
58
+ // cleanup virtual field "calculated_price"
59
+ config.relations?.splice(fieldIdx, 1);
60
+ delete filters.context;
61
+ return pricingContext;
62
+ }
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
+ }
78
+ }
79
+ return priceSets;
80
+ }
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
+ }
96
+ }
97
+ return [priceSets, count];
98
+ }
51
99
  async calculatePrices(pricingFilters, pricingContext = { context: {} }, sharedContext = {}) {
52
100
  const results = await this.pricingRepository_.calculatePrices(pricingFilters, pricingContext, sharedContext);
53
101
  const pricesSetPricesMap = (0, utils_1.groupBy)(results, "price_set_id");
54
102
  const calculatedPrices = pricingFilters.id.map((priceSetId) => {
55
103
  // This is where we select prices, for now we just do a first match based on the database results
56
104
  // which is prioritized by rules_count first for exact match and then deafult_priority of the rule_type
57
- // inject custom price selection here
105
+ // TODO: inject custom price selection here
58
106
  const prices = pricesSetPricesMap.get(priceSetId) || [];
59
107
  const priceListPrice = prices.find((p) => p.price_list_id);
60
108
  const defaultPrice = prices?.find((p) => !p.price_list_id);
@@ -94,12 +142,103 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
94
142
  async create(data, sharedContext = {}) {
95
143
  const input = Array.isArray(data) ? data : [data];
96
144
  const priceSets = await this.create_(input, sharedContext);
145
+ // TODO: Remove the need to refetch the data here
97
146
  const dbPriceSets = await this.list({ id: priceSets.map((p) => p.id) }, { relations: ["rule_types", "prices", "price_rules"] }, sharedContext);
98
147
  // Ensure the output to be in the same order as the input
99
148
  const results = priceSets.map((priceSet) => {
100
149
  return dbPriceSets.find((p) => p.id === priceSet.id);
101
150
  });
102
- return Array.isArray(data) ? results : results[0];
151
+ return await this.baseRepository_.serialize(Array.isArray(data) ? results : results[0]);
152
+ }
153
+ async upsert(data, sharedContext = {}) {
154
+ const input = Array.isArray(data) ? data : [data];
155
+ const forUpdate = input.filter((priceSet) => !!priceSet.id);
156
+ const forCreate = input.filter((priceSet) => !priceSet.id);
157
+ const operations = [];
158
+ if (forCreate.length) {
159
+ operations.push(this.create_(forCreate, sharedContext));
160
+ }
161
+ if (forUpdate.length) {
162
+ operations.push(this.update_(forUpdate, sharedContext));
163
+ }
164
+ const result = (await (0, utils_1.promiseAll)(operations)).flat();
165
+ return await this.baseRepository_.serialize(Array.isArray(data) ? result : result[0]);
166
+ }
167
+ async update(idOrSelector, data, sharedContext = {}) {
168
+ let normalizedInput = [];
169
+ if ((0, utils_1.isString)(idOrSelector)) {
170
+ // Check if the ID exists, it will throw if not.
171
+ await this.priceSetService_.retrieve(idOrSelector, {}, sharedContext);
172
+ normalizedInput = [{ id: idOrSelector, ...data }];
173
+ }
174
+ else {
175
+ const priceSets = await this.priceSetService_.list(idOrSelector, {}, sharedContext);
176
+ normalizedInput = priceSets.map((priceSet) => ({
177
+ id: priceSet.id,
178
+ ...data,
179
+ }));
180
+ }
181
+ const updateResult = await this.update_(normalizedInput, sharedContext);
182
+ const priceSets = await this.baseRepository_.serialize(updateResult);
183
+ return (0, utils_1.isString)(idOrSelector) ? priceSets[0] : priceSets;
184
+ }
185
+ async normalizeUpdateData(data, sharedContext) {
186
+ const ruleAttributes = data
187
+ .map((d) => d.prices?.map((p) => Object.keys(p.rules ?? [])) ?? [])
188
+ .flat(Infinity)
189
+ .filter(Boolean);
190
+ const ruleTypes = await this.ruleTypeService_.list({ rule_attribute: ruleAttributes }, { take: null }, sharedContext);
191
+ const ruleTypeMap = ruleTypes.reduce((acc, curr) => {
192
+ acc.set(curr.rule_attribute, curr);
193
+ return acc;
194
+ }, new Map());
195
+ return data.map((priceSet) => {
196
+ const prices = priceSet.prices?.map((price) => {
197
+ const rules = Object.entries(price.rules ?? {}).map(([attribute, value]) => {
198
+ return {
199
+ price_set_id: priceSet.id,
200
+ rule_type_id: ruleTypeMap.get(attribute).id,
201
+ value,
202
+ };
203
+ });
204
+ const hasRulesInput = (0, utils_1.isPresent)(price.rules);
205
+ delete price.rules;
206
+ return {
207
+ ...price,
208
+ price_set_id: priceSet.id,
209
+ price_rules: hasRulesInput ? rules : undefined,
210
+ rules_count: hasRulesInput ? rules.length : undefined,
211
+ };
212
+ });
213
+ return {
214
+ ...priceSet,
215
+ prices,
216
+ };
217
+ });
218
+ }
219
+ async update_(data, sharedContext = {}) {
220
+ // TODO: We are not handling rule types, rules, etc. here, add support after data models are finalized
221
+ // TODO: Since money IDs are rarely passed, this will delete all previous data and insert new entries.
222
+ // We can make the `insert` inside upsertWithReplace do an `upsert` instead to avoid this
223
+ const normalizedData = await this.normalizeUpdateData(data, sharedContext);
224
+ const prices = normalizedData.flatMap((priceSet) => priceSet.prices || []);
225
+ const upsertedPrices = await this.priceService_.upsertWithReplace(prices, {
226
+ relations: ["price_rules"],
227
+ }, sharedContext);
228
+ const priceSetsToUpsert = normalizedData.map((priceSet) => {
229
+ const { prices, ...rest } = priceSet;
230
+ return {
231
+ ...rest,
232
+ prices: upsertedPrices
233
+ .filter((p) => p.price_set_id === priceSet.id)
234
+ .map((price) => {
235
+ // @ts-ignore
236
+ delete price.price_rules;
237
+ return price;
238
+ }),
239
+ };
240
+ });
241
+ return await this.priceSetService_.upsertWithReplace(priceSetsToUpsert, { relations: ["prices"] }, sharedContext);
103
242
  }
104
243
  async addRules(data, sharedContext = {}) {
105
244
  const inputs = Array.isArray(data) ? data : [data];
@@ -131,10 +270,6 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
131
270
  await this.priceSetRuleTypeService_.delete(priceSetRuleTypes.map((psrt) => psrt.id), sharedContext);
132
271
  await this.priceService_.delete(priceRules.map((pr) => pr.price.id), sharedContext);
133
272
  }
134
- async update(data, sharedContext = {}) {
135
- const priceSets = await this.priceSetService_.update(data, sharedContext);
136
- return await this.baseRepository_.serialize(priceSets);
137
- }
138
273
  async createPriceLists(data, sharedContext = {}) {
139
274
  const priceLists = await this.createPriceLists_(data, sharedContext);
140
275
  return await this.baseRepository_.serialize(priceLists);
@@ -159,13 +294,15 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
159
294
  });
160
295
  }
161
296
  async updatePriceListPrices(data, sharedContext = {}) {
162
- return await this.updatePriceListPrices_(data, sharedContext);
297
+ const prices = await this.updatePriceListPrices_(data, sharedContext);
298
+ return await this.baseRepository_.serialize(prices);
163
299
  }
164
300
  async removePrices(ids, sharedContext = {}) {
165
301
  await this.removePrices_(ids, sharedContext);
166
302
  }
167
303
  async addPriceListPrices(data, sharedContext = {}) {
168
- return await this.addPriceListPrices_(data, sharedContext);
304
+ const prices = await this.addPriceListPrices_(data, sharedContext);
305
+ return await this.baseRepository_.serialize(prices);
169
306
  }
170
307
  async setPriceListRules(data, sharedContext = {}) {
171
308
  const [priceList] = await this.setPriceListRules_([data], sharedContext);
@@ -229,7 +366,7 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
229
366
  });
230
367
  return {
231
368
  ...rest,
232
- title: "test",
369
+ title: "",
233
370
  rules_count: numberOfRules,
234
371
  price_rules: Array.from(rulesDataMap.values()),
235
372
  };
@@ -475,40 +612,37 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
475
612
  }
476
613
  const priceLists = await this.listPriceLists({ id: priceListIds }, { take: null }, sharedContext);
477
614
  const priceListMap = new Map(priceLists.map((p) => [p.id, p]));
615
+ const pricesToUpdate = [];
616
+ const priceRuleIdsToDelete = [];
617
+ const priceRulesToCreate = [];
478
618
  for (const { price_list_id: priceListId, prices } of data) {
479
619
  const priceList = priceListMap.get(priceListId);
480
620
  if (!priceList) {
481
621
  throw new utils_1.MedusaError(utils_1.MedusaError.Types.INVALID_DATA, `Price list with id: ${priceListId} not found`);
482
622
  }
483
- const priceRuleIdsToDelete = [];
484
- const priceRulesToCreate = [];
485
- const pricesToUpdate = [];
486
623
  for (const priceData of prices) {
487
- const { rules, price_set_id, ...rest } = priceData;
624
+ const { rules = {}, price_set_id, ...rest } = priceData;
488
625
  const price = priceMap.get(rest.id);
489
626
  const priceRules = price.price_rules;
490
- if (!(0, utils_1.isDefined)(rules)) {
491
- continue;
492
- }
627
+ priceRulesToCreate.push(...Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
628
+ price_set_id,
629
+ rule_type_id: ruleTypeMap.get(ruleAttribute).id,
630
+ value: ruleValue,
631
+ price_id: price.id,
632
+ })));
493
633
  pricesToUpdate.push({
494
634
  ...rest,
495
635
  rules_count: Object.keys(rules).length,
496
- price_rules: Object.entries(rules).map(([ruleAttribute, ruleValue]) => ({
497
- price_set_id,
498
- rule_type_id: ruleTypeMap.get(ruleAttribute).id,
499
- value: ruleValue,
500
- price_id: price.id,
501
- })),
502
636
  });
503
637
  priceRuleIdsToDelete.push(...priceRules.map((pr) => pr.id));
504
638
  }
505
- await (0, utils_1.promiseAll)([
506
- this.priceRuleService_.delete(priceRuleIdsToDelete),
507
- this.priceRuleService_.create(priceRulesToCreate),
508
- this.priceService_.update(pricesToUpdate),
509
- ]);
510
639
  }
511
- return priceLists;
640
+ const [_deletedPriceRule, _createdPriceRule, updatedPrices] = await (0, utils_1.promiseAll)([
641
+ this.priceRuleService_.delete(priceRuleIdsToDelete),
642
+ this.priceRuleService_.create(priceRulesToCreate),
643
+ this.priceService_.update(pricesToUpdate),
644
+ ]);
645
+ return updatedPrices;
512
646
  }
513
647
  async removePrices_(ids, sharedContext = {}) {
514
648
  await this.priceService_.delete(ids, sharedContext);
@@ -577,8 +711,7 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
577
711
  });
578
712
  pricesToCreate.push(...priceListPricesToCreate);
579
713
  }
580
- await this.priceService_.create(pricesToCreate, sharedContext);
581
- return priceLists;
714
+ return await this.priceService_.create(pricesToCreate, sharedContext);
582
715
  }
583
716
  async setPriceListRules_(data, sharedContext = {}) {
584
717
  // TODO: re think this method
@@ -664,6 +797,20 @@ class PricingModuleService extends utils_1.ModulesSdkUtils.abstractModuleService
664
797
  }
665
798
  }
666
799
  exports.default = PricingModuleService;
800
+ __decorate([
801
+ (0, utils_1.InjectManager)("baseRepository_"),
802
+ __param(2, (0, utils_1.MedusaContext)()),
803
+ __metadata("design:type", Function),
804
+ __metadata("design:paramtypes", [Object, Object, Object]),
805
+ __metadata("design:returntype", Promise)
806
+ ], PricingModuleService.prototype, "list", null);
807
+ __decorate([
808
+ (0, utils_1.InjectManager)("baseRepository_"),
809
+ __param(2, (0, utils_1.MedusaContext)()),
810
+ __metadata("design:type", Function),
811
+ __metadata("design:paramtypes", [Object, Object, Object]),
812
+ __metadata("design:returntype", Promise)
813
+ ], PricingModuleService.prototype, "listAndCount", null);
667
814
  __decorate([
668
815
  (0, utils_1.InjectManager)("baseRepository_"),
669
816
  __param(2, (0, utils_1.MedusaContext)()),
@@ -684,28 +831,42 @@ __decorate([
684
831
  __metadata("design:type", Function),
685
832
  __metadata("design:paramtypes", [Object, Object]),
686
833
  __metadata("design:returntype", Promise)
687
- ], PricingModuleService.prototype, "addRules", null);
834
+ ], PricingModuleService.prototype, "upsert", null);
688
835
  __decorate([
689
836
  (0, utils_1.InjectManager)("baseRepository_"),
690
- __param(1, (0, utils_1.MedusaContext)()),
837
+ __param(2, (0, utils_1.MedusaContext)()),
691
838
  __metadata("design:type", Function),
692
- __metadata("design:paramtypes", [Object, Object]),
839
+ __metadata("design:paramtypes", [Object, Object, Object]),
693
840
  __metadata("design:returntype", Promise)
694
- ], PricingModuleService.prototype, "addPrices", null);
841
+ ], PricingModuleService.prototype, "update", null);
695
842
  __decorate([
696
843
  (0, utils_1.InjectTransactionManager)("baseRepository_"),
697
844
  __param(1, (0, utils_1.MedusaContext)()),
698
845
  __metadata("design:type", Function),
699
846
  __metadata("design:paramtypes", [Array, Object]),
700
847
  __metadata("design:returntype", Promise)
701
- ], PricingModuleService.prototype, "removeRules", null);
848
+ ], PricingModuleService.prototype, "update_", null);
849
+ __decorate([
850
+ (0, utils_1.InjectManager)("baseRepository_"),
851
+ __param(1, (0, utils_1.MedusaContext)()),
852
+ __metadata("design:type", Function),
853
+ __metadata("design:paramtypes", [Object, Object]),
854
+ __metadata("design:returntype", Promise)
855
+ ], PricingModuleService.prototype, "addRules", null);
856
+ __decorate([
857
+ (0, utils_1.InjectManager)("baseRepository_"),
858
+ __param(1, (0, utils_1.MedusaContext)()),
859
+ __metadata("design:type", Function),
860
+ __metadata("design:paramtypes", [Object, Object]),
861
+ __metadata("design:returntype", Promise)
862
+ ], PricingModuleService.prototype, "addPrices", null);
702
863
  __decorate([
703
864
  (0, utils_1.InjectTransactionManager)("baseRepository_"),
704
865
  __param(1, (0, utils_1.MedusaContext)()),
705
866
  __metadata("design:type", Function),
706
867
  __metadata("design:paramtypes", [Array, Object]),
707
868
  __metadata("design:returntype", Promise)
708
- ], PricingModuleService.prototype, "update", null);
869
+ ], PricingModuleService.prototype, "removeRules", null);
709
870
  __decorate([
710
871
  (0, utils_1.InjectManager)("baseRepository_"),
711
872
  __param(1, (0, utils_1.MedusaContext)()),
@@ -1 +1,2 @@
1
1
  export * from "./price-list";
2
+ export * from "./price-set";
@@ -15,3 +15,4 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./price-list"), exports);
18
+ __exportStar(require("./price-set"), exports);
@@ -0,0 +1,4 @@
1
+ import { UpdatePriceSetDTO } from "@medusajs/types";
2
+ export interface UpdatePriceSetInput extends UpdatePriceSetDTO {
3
+ id: string;
4
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@medusajs/pricing",
3
- "version": "0.1.12-snapshot-20240328221015",
3
+ "version": "0.2.0-next-20240429170320",
4
4
  "description": "Medusa Pricing module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -40,7 +40,7 @@
40
40
  "@mikro-orm/cli": "5.9.7",
41
41
  "cross-env": "^5.2.1",
42
42
  "jest": "^29.6.3",
43
- "medusa-test-utils": "1.1.44-snapshot-20240328221015",
43
+ "medusa-test-utils": "1.1.44-next-20240429170320",
44
44
  "rimraf": "^3.0.2",
45
45
  "ts-jest": "^29.1.1",
46
46
  "ts-node": "^10.9.1",
@@ -48,9 +48,9 @@
48
48
  "typescript": "^5.1.6"
49
49
  },
50
50
  "dependencies": {
51
- "@medusajs/modules-sdk": "^1.12.10",
52
- "@medusajs/types": "1.12.0-snapshot-20240328221015",
53
- "@medusajs/utils": "1.12.0-snapshot-20240328221015",
51
+ "@medusajs/modules-sdk": "1.12.11-next-20240429170320",
52
+ "@medusajs/types": "1.12.0-next-20240429170320",
53
+ "@medusajs/utils": "1.12.0-next-20240429170320",
54
54
  "@mikro-orm/core": "5.9.7",
55
55
  "@mikro-orm/migrations": "5.9.7",
56
56
  "@mikro-orm/postgresql": "5.9.7",