1 /* eslint-disable @medusajs/use-inject-manager-on-public-methods */
2 import {
3 BigNumberValue,
4 Context,
5 DAL,
6 FindConfig,
7 InferEntityType,
8 ModulesSdkTypes,
9 SoftDeleteReturn,
10 } from "@medusajs/framework/types";
11 import {
12 InjectManager,
13 InjectTransactionManager,
14 isDefined,
15 MathBN,
16 MedusaContext,
17 MedusaError,
18 MedusaService,
19 } from "@medusajs/framework/utils";
20 import { SqlEntityManager } from "@medusajs/framework/mikro-orm/postgresql";
21 import {
22 IStoreCreditModuleService,
23 ModuleAccountStats,
24 ModuleAccountTransaction,
25 ModuleCreditAccount,
26 ModuleDebitAccount,
27 ModuleRetrieveAccountStats,
28 ModuleStoreCreditAccount,
29 ModuleStoreCreditAccountFilters,
30 ModuleUpdateStoreCreditAccount,
31 TransactionType,
32 } from "../../types";
33 import AccountTransaction from "./models/account-transaction";
34 import StoreCreditAccount from "./models/store-credit-account";
35
36 type InjectedDependencies = {
37 baseRepository: DAL.RepositoryService;
38 accountTransactionService: ModulesSdkTypes.IMedusaInternalService<any>;
39 };
40
41 class StoreCreditService
42 extends MedusaService<{
43 StoreCreditAccount: { dto: ModuleStoreCreditAccount };
44 AccountTransaction: { dto: ModuleAccountTransaction };
45 }>({ StoreCreditAccount, AccountTransaction })
46 implements IStoreCreditModuleService
47 {
48 protected baseRepository_: DAL.RepositoryService;
49 protected readonly accountTransactionService_: ModulesSdkTypes.IMedusaInternalService<
50 InferEntityType<ModuleAccountTransaction>
51 >;
52
53 constructor({
54 baseRepository,
55 accountTransactionService,
56 }: InjectedDependencies) {
57 super(...arguments);
58
59 this.baseRepository_ = baseRepository;
60 this.accountTransactionService_ = accountTransactionService;
61 }
62
63 @InjectManager()
64 // @ts-expect-error
65 async listStoreCreditAccounts(
66 filters: ModuleStoreCreditAccountFilters,
67 config: FindConfig<ModuleStoreCreditAccount> = {},
68 @MedusaContext() sharedContext: Context = {}
69 ) {
70 const accounts = await super.listStoreCreditAccounts(
71 filters,
72 config,
73 sharedContext
74 );
75
76 for (const account of accounts) {
77 const stats = await this.retrieveAccountStats(
78 {
79 account_id: account.id,
80 },
81 sharedContext
82 );
83
84 account.balance = stats.balance;
85 account.credits = stats.credits;
86 account.debits = stats.debits;
87 }
88
89 return accounts;
90 }
91
92 /* Entity: StoreCreditAccount */
93
94 @InjectTransactionManager()
95 // @ts-expect-error
96 async updateStoreCreditAccounts(
97 data: ModuleUpdateStoreCreditAccount | ModuleUpdateStoreCreditAccount[],
98 @MedusaContext() sharedContext: Context = {}
99 ) {
100 /*
101 We should only allow updating the whitelisted fields for store credit accounts.
102 Changing the customer or currency code will lead to unexpected results where balances are not tracked correctly.
103 */
104 const whitelistedFields = ["id", "metadata"];
105 const normalizedData = Array.isArray(data) ? data : [data];
106
107 normalizedData.forEach((account) => {
108 Object.keys(account).forEach((key) => {
109 if (whitelistedFields.includes(key)) {
110 throw new Error(`Field ${key} is not allowed to be updated`);
111 }
112 });
113 });
114
115 return await super.updateStoreCreditAccounts(normalizedData, sharedContext);
116 }
117
118 @InjectTransactionManager()
119 // @ts-expect-error
120 async deleteStoreCreditAccounts(
121 ids: string | string[],
122 @MedusaContext() sharedContext: Context = {}
123 ) {
124 /*
125 TODO: Before deleting the accounts, we should check if the accounts have any transactions.
126 If they do, we should throw an error.
127
128 We should only allow deleting accounts that have no transactions.
129
130 We should not allow deleting accounts that have any transactions.
131 We should instead "close" an account only after balance is zero.
132 */
133
134 return await super.deleteStoreCreditAccounts(ids, sharedContext);
135 }
136
137 @InjectTransactionManager()
138 // @ts-expect-error
139 async softDeleteStoreCreditAccounts<
140 TReturnableLinkableKeys extends string = string
141 >(
142 ids: string | string[],
143 config?: SoftDeleteReturn<TReturnableLinkableKeys>,
144 @MedusaContext() sharedContext: Context = {}
145 ): Promise<Record<string, string[]> | void> {
146 /*
147 TODO: Before soft deleting the accounts, we should check if the accounts have any transactions.
148 If they do, we should throw an error.
149
150 We should only allow soft deleting accounts that have no transactions.
151
152 We should not allow soft deleting accounts that have any transactions.
153 We should instead "close" an account only after balance is zero.
154 */
155
156 return await super.softDeleteStoreCreditAccounts(
157 ids,
158 config,
159 sharedContext
160 );
161 }
162
163 /* Entity: AccountTransaction */
164
165 /**
166 * `MedusaService` derives its generated method names from the model name, so
167 * the transaction delete method is generated as `deleteAccountTransactions`.
168 * `IStoreCreditModuleService` however declares this method as
169 * `deleteTransactions`, which meant the declared method did not exist at
170 * runtime and every caller threw a `TypeError`.
171 *
172 * The declared name is part of the module's public API, so it is implemented
173 * here as a forwarder rather than renamed.
174 */
175 @InjectTransactionManager()
176 async deleteTransactions(
177 ids: string[],
178 @MedusaContext() sharedContext: Context = {}
179 ): Promise<void> {
180 await this.deleteAccountTransactions(ids, sharedContext);
181 }
182
183 @InjectManager()
184 async retrieveAccountStats(
185 data: ModuleRetrieveAccountStats,
186 @MedusaContext() sharedContext: Context = {}
187 ): Promise<ModuleAccountStats> {
188 const manager =
189 (sharedContext.transactionManager as SqlEntityManager) ??
190 (sharedContext.manager as SqlEntityManager);
191 const knex = manager.getTransactionContext() ?? manager.getKnex();
192 const { account_id } = data;
193
194 const account = await super.retrieveStoreCreditAccount(
195 account_id,
196 {},
197 sharedContext
198 );
199
200 // TODO: For higher accuracy and precision, we should run the transaction amounts through big number
201 // in memory and then use that value for the balance.
202 // We need to figure out clever ways to do this without running too many calculations in memory
203 const accountBalanceQuery = knex("store_credit_account as account")
204 .select({
205 id: "account.id",
206 credits: knex.raw(
207 `SUM(CASE WHEN at.type = 'credit' THEN at.amount ELSE 0 END)`
208 ),
209 debits: knex.raw(
210 `SUM(CASE WHEN at.type = 'debit' THEN at.amount ELSE 0 END)`
211 ),
212 balance: knex.raw(
213 `SUM(CASE WHEN at.type = 'credit' THEN at.amount::numeric ELSE -at.amount::numeric END)`
214 ),
215 })
216 .leftJoin("store_credit_account_transaction as at", function () {
217 this.on("at.account_id", "=", "account.id").andOnNull("at.deleted_at");
218 })
219 .where("account.id", account.id)
220 .groupBy("account.id");
221
222 const accountBalances: {
223 id: string;
224 balance: string;
225 debits: string;
226 credits: string;
227 }[] = await accountBalanceQuery;
228
229 const accountBalance = accountBalances[0];
230 const response = {
231 id: account.id,
232 balance: MathBN.convert(accountBalance.balance).toNumber(),
233 debits: MathBN.convert(accountBalance.debits).toNumber(),
234 credits: MathBN.convert(accountBalance.credits).toNumber(),
235 };
236
237 return await this.baseRepository_.serialize(response);
238 }
239
240 @InjectTransactionManager()
241 async creditAccounts_(
242 creditAccountsData: ModuleCreditAccount[],
243 @MedusaContext() sharedContext: Context = {}
244 ) {
245 const transactions: ModuleAccountTransaction[] = [];
246
247 for (const data of creditAccountsData) {
248 const { account_id, amount, reference, reference_id, note } = data;
249
250 if (!account_id) {
251 throw new MedusaError(
252 MedusaError.Types.INVALID_DATA,
253 "Account ID is required"
254 );
255 }
256
257 if (!isDefined(amount)) {
258 throw new MedusaError(
259 MedusaError.Types.INVALID_DATA,
260 "Amount is required"
261 );
262 }
263
264 const storeCreditAccount = await super.retrieveStoreCreditAccount(
265 account_id,
266 {},
267 sharedContext
268 );
269
270 const createdTransactions = await this.accountTransactionService_.create(
271 [
272 {
273 account_id: storeCreditAccount.id,
274 amount,
275 type: TransactionType.CREDIT,
276 reference,
277 reference_id,
278 note,
279 },
280 ],
281 sharedContext
282 );
283
284 transactions.push(...createdTransactions);
285 }
286
287 return transactions;
288 }
289
290 @InjectManager()
291 async creditAccounts(
292 data: ModuleCreditAccount[],
293 @MedusaContext() sharedContext: Context = {}
294 ) {
295 const transactions = await this.creditAccounts_(data, sharedContext);
296
297 return await this.baseRepository_.serialize<ModuleAccountTransaction[]>(
298 transactions
299 );
300 }
301
302 @InjectManager()
303 async debitAccounts(
304 debitAccountsData: ModuleDebitAccount[],
305 @MedusaContext() sharedContext: Context = {}
306 ) {
307 const transactions = await this.debitAccounts_(
308 debitAccountsData,
309 sharedContext
310 );
311
312 return await this.baseRepository_.serialize<ModuleAccountTransaction[]>(
313 transactions
314 );
315 }
316
317 /**
318 * Acquires a row-level lock on the given store credit accounts for the duration
319 * of the surrounding transaction.
320 *
321 * Balances are derived from the transaction ledger rather than stored on the
322 * account, so a debit is a check-then-insert: read the balance, verify it covers
323 * the amount, then insert the debit. Under Postgres' default READ COMMITTED
324 * isolation, concurrent transactions do not observe each other's uncommitted
325 * debits, so without a lock two checkouts can both pass the balance check and
326 * overspend the same stored value.
327 *
328 * Locking the account row serializes all debits for that account across
329 * processes. Accounts are locked in a deterministic order so that debits
330 * spanning multiple accounts cannot deadlock against each other.
331 */
332 @InjectTransactionManager()
333 protected async lockAccountsForUpdate_(
334 accountIds: string[],
335 @MedusaContext() sharedContext: Context = {}
336 ) {
337 const uniqueAccountIds = Array.from(new Set(accountIds)).sort();
338
339 if (!uniqueAccountIds.length) {
340 return;
341 }
342
343 const manager = sharedContext.transactionManager as SqlEntityManager;
344 const transactionContext = manager.getTransactionContext();
345
346 if (!transactionContext) {
347 /*
348 Falling back to a non-transactional connection would release the lock
349 immediately and silently reintroduce the double-spend race, so we fail
350 loudly instead.
351 */
352 throw new MedusaError(
353 MedusaError.Types.UNEXPECTED_STATE,
354 "Cannot lock store credit accounts outside of a transaction"
355 );
356 }
357
358 await transactionContext("store_credit_account")
359 .select("id")
360 .whereIn("id", uniqueAccountIds)
361 .forUpdate();
362 }
363
364 @InjectTransactionManager()
365 async debitAccounts_(
366 debitAccountsData: ModuleDebitAccount[],
367 @MedusaContext() sharedContext: Context = {}
368 ) {
369 const manager = sharedContext.transactionManager as SqlEntityManager;
370 const transactions: ModuleAccountTransaction[] = [];
371
372 /*
373 Lock every account up front, before any balance is read, so that the
374 check-then-insert below is serialized per account.
375 */
376 await this.lockAccountsForUpdate_(
377 debitAccountsData.map((data) => data.account_id).filter(Boolean),
378 sharedContext
379 );
380
381 for (const data of debitAccountsData) {
382 const { account_id, amount, reference, reference_id, note } = data;
383
384 const amountBN = MathBN.convert(amount);
385
386 if (!account_id) {
387 throw new MedusaError(
388 MedusaError.Types.INVALID_DATA,
389 "Account ID is required"
390 );
391 }
392
393 if (!isDefined(amount)) {
394 throw new MedusaError(
395 MedusaError.Types.INVALID_DATA,
396 "Amount is required"
397 );
398 }
399
400 if (amountBN.lte(0)) {
401 throw new MedusaError(
402 MedusaError.Types.INVALID_DATA,
403 "Amount must be greater than 0"
404 );
405 }
406
407 const accountStats = await this.retrieveAccountStats(
408 { account_id },
409 sharedContext
410 );
411
412 if (MathBN.convert(accountStats.balance).lt(amountBN)) {
413 throw new MedusaError(
414 MedusaError.Types.INVALID_DATA,
415 "Insufficient balance"
416 );
417 }
418
419 const createdTransaction = await this.accountTransactionService_.create(
420 {
421 account_id: accountStats.id,
422 amount: amountBN,
423 type: TransactionType.DEBIT,
424 reference,
425 reference_id,
426 note,
427 },
428 sharedContext
429 );
430
431 transactions.push(createdTransaction);
432
433 await manager.flush();
434 }
435
436 return transactions;
437 }
438 }
439
440 export default StoreCreditService;