This commit is contained in:
2025-12-13 10:04:13 +03:30
parent c5c71491a4
commit 85b4e5bb6a
6 changed files with 101 additions and 5 deletions
+48 -1
View File
@@ -1,4 +1,4 @@
import { Injectable, NotFoundException } from '@nestjs/common';
import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
import { FilterQuery, RequiredEntityData } from '@mikro-orm/core';
import { User } from '../entities/user.entity';
import { UserAddress } from '../entities/user-address.entity';
@@ -10,11 +10,14 @@ import { UpdateUserAddressDto } from '../dto/update-user-address.dto';
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
import { UserRepository } from '../repositories/user.repository';
import { normalizePhone } from '../../utils/phone.util';
import { ConvertScoreToWalletDto } from '../dto/convert-score-to-wallet.dto';
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
@Injectable()
export class UserService {
constructor(
private readonly userRepository: UserRepository,
private readonly restaurantRepository: RestRepository,
private readonly em: EntityManager,
) {}
@@ -283,4 +286,48 @@ export class UserService {
return address;
}
async convertScoreToWallet(userId: string, restId: string, dto: ConvertScoreToWalletDto): Promise<User> {
const user = await this.userRepository.findOne({ id: userId });
if (!user) {
throw new NotFoundException(`User with ID ${userId} not found.`);
}
// Determine how many points to convert
const pointsToConvert = dto.points ?? user.points;
// Validate points to convert
if (pointsToConvert <= 0) {
throw new BadRequestException('Points to convert must be greater than 0.');
}
if (user.points < pointsToConvert) {
throw new BadRequestException(`Insufficient points. Available: ${user.points}, Requested: ${pointsToConvert}.`);
}
const restaurant = await this.restaurantRepository.findOne({ id: restId });
if (!restaurant) {
throw new NotFoundException(`Restaurant with ID ${restId} not found.`);
}
if (!restaurant.score) {
throw new BadRequestException('Restaurant score not found.');
}
if (!restaurant.score.purchaseScore) {
throw new BadRequestException('Restaurant purchase score not found.');
}
if (!restaurant.score.purchaseAmount) {
throw new BadRequestException('Restaurant purchase amount not found.');
}
const walletIncreaseAmount =
(Number(pointsToConvert) * Number(restaurant.score.purchaseAmount)) / Number(restaurant.score.purchaseScore);
// Convert points to wallet (1:1 ratio - can be made configurable)
// Update user's wallet and points
user.wallet = (user.wallet || 0) + walletIncreaseAmount;
user.points = user.points - pointsToConvert;
await this.em.flush();
return user;
}
}