@@ -0,0 +1,49 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Restaurant } from '../entities/restaurant.entity';
|
||||
import { RestaurantCreditTransaction } from '../entities/restaurant-credit-transaction.entity';
|
||||
import {
|
||||
RestaurantCreditTransactionReason,
|
||||
RestaurantCreditTransactionType,
|
||||
} from '../interface/restaurant-credit-transaction.interface';
|
||||
|
||||
@Injectable()
|
||||
export class RestaurantWalletService {
|
||||
constructor(private readonly defaultEm: EntityManager) {}
|
||||
|
||||
async createTransaction(params: {
|
||||
restaurant: Restaurant;
|
||||
amount: number;
|
||||
type: RestaurantCreditTransactionType;
|
||||
reason: RestaurantCreditTransactionReason;
|
||||
insufficientBalanceMessage?: string;
|
||||
em?: EntityManager;
|
||||
}): Promise<void> {
|
||||
const { restaurant, amount, type, reason, insufficientBalanceMessage, em = this.defaultEm } = params;
|
||||
|
||||
if (amount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentCredit = Number(restaurant.credit ?? 0);
|
||||
if (type === RestaurantCreditTransactionType.DEBIT && currentCredit < amount) {
|
||||
throw new BadRequestException(insufficientBalanceMessage ?? 'اعتبار کیف پول رستوران کافی نیست');
|
||||
}
|
||||
|
||||
const newBalance =
|
||||
type === RestaurantCreditTransactionType.DEBIT ? currentCredit - amount : currentCredit + amount;
|
||||
|
||||
restaurant.credit = newBalance;
|
||||
|
||||
const creditTransaction = em.create(RestaurantCreditTransaction, {
|
||||
restaurant,
|
||||
amount,
|
||||
balance: newBalance,
|
||||
type,
|
||||
reason,
|
||||
});
|
||||
|
||||
await em.persistAndFlush([restaurant, creditTransaction]);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user