From 0f1f472adbe6cff3cf4ebd1306150c30d5c63d32 Mon Sep 17 00:00:00 2001 From: morteza-mortezai Date: Mon, 29 Dec 2025 21:31:01 +0330 Subject: [PATCH] rerfactor user wallet ans user points --- src/modules/cart/cart.module.ts | 8 ++- .../cart/providers/cart-validation.service.ts | 19 +++---- .../orders/listeners/order.listeners.ts | 41 ++++++++++---- .../payments/services/payments.service.ts | 23 ++++---- ....entity.ts => point-transaction.entity.ts} | 27 +++++---- .../entities/wallet-transaction.entity.ts | 12 +++- src/modules/users/interface/point.ts | 10 ++++ src/modules/users/interface/wallet.ts | 1 - src/modules/users/providers/user.service.ts | 56 ++++++++++++------- src/modules/users/providers/wallet.service.ts | 35 ++++++------ .../point-transaction.repository.ts | 17 ++++++ .../repositories/user-wallet.repository.ts | 10 ---- .../wallet-transaction.repository.ts | 7 +++ src/modules/users/user.module.ts | 16 ++++-- src/seeders/data/admins.data.ts | 12 ++-- src/seeders/data/restaurants.data.ts | 2 +- src/seeders/user-wallets.seeder.ts | 13 +++-- 17 files changed, 193 insertions(+), 116 deletions(-) rename src/modules/users/entities/{user-wallet.entity.ts => point-transaction.entity.ts} (51%) create mode 100644 src/modules/users/interface/point.ts create mode 100644 src/modules/users/repositories/point-transaction.repository.ts delete mode 100644 src/modules/users/repositories/user-wallet.repository.ts diff --git a/src/modules/cart/cart.module.ts b/src/modules/cart/cart.module.ts index 00005fb..8d0da8b 100644 --- a/src/modules/cart/cart.module.ts +++ b/src/modules/cart/cart.module.ts @@ -7,7 +7,6 @@ import { Restaurant } from '../restaurants/entities/restaurant.entity'; import { PaymentMethod } from '../payments/entities/payment-method.entity'; import { UserAddress } from '../users/entities/user-address.entity'; import { User } from '../users/entities/user.entity'; -import { UserWallet } from '../users/entities/user-wallet.entity'; import { Delivery } from '../delivery/entities/delivery.entity'; import { Order } from '../orders/entities/order.entity'; import { AuthModule } from '../auth/auth.module'; @@ -18,6 +17,8 @@ import { CartRepository } from './repositories/cart.repository'; import { CartValidationService } from './providers/cart-validation.service'; import { CartCalculationService } from './providers/cart-calculation.service'; import { CartItemService } from './providers/cart-item.service'; +import { PointTransaction } from '../users/entities/point-transaction.entity'; +import { WalletTransaction } from '../users/entities/wallet-transaction.entity'; @Module({ imports: [ @@ -27,7 +28,8 @@ import { CartItemService } from './providers/cart-item.service'; PaymentMethod, UserAddress, User, - UserWallet, + PointTransaction, + WalletTransaction, Delivery, Order, ]), @@ -46,4 +48,4 @@ import { CartItemService } from './providers/cart-item.service'; ], exports: [CartService], }) -export class CartModule {} +export class CartModule { } diff --git a/src/modules/cart/providers/cart-validation.service.ts b/src/modules/cart/providers/cart-validation.service.ts index 3a7a9c1..6af1065 100644 --- a/src/modules/cart/providers/cart-validation.service.ts +++ b/src/modules/cart/providers/cart-validation.service.ts @@ -7,17 +7,21 @@ import { User } from '../../users/entities/user.entity'; import { PaymentMethod } from '../../payments/entities/payment-method.entity'; import { Delivery } from '../../delivery/entities/delivery.entity'; import { DeliveryMethodEnum } from '../../delivery/interface/delivery'; -import { UserWallet } from '../../users/entities/user-wallet.entity'; +import { PointTransaction } from '../../users/entities/point-transaction.entity'; import { Order } from '../../orders/entities/order.entity'; import { OrderStatus } from '../../orders/interface/order.interface'; import { Cart } from '../interfaces/cart.interface'; import { GeographicUtils } from '../utils/geographic.utils'; import { MealType } from '../../foods/interface/food.interface'; import { CartMessage } from 'src/common/enums/message.enum'; +import { WalletTransactionRepository } from 'src/modules/users/repositories/wallet-transaction.repository'; @Injectable() export class CartValidationService { - constructor(private readonly em: EntityManager) { } + constructor( + private readonly em: EntityManager, + private readonly walletTransactionRepository: WalletTransactionRepository, + ) { } /** * Validate food exists, belongs to restaurant, has inventory, and check stock @@ -216,16 +220,9 @@ export class CartValidationService { * Assert wallet has enough balance */ async assertWalletHasEnoughBalance(userId: string, restaurantId: string, amount: number): Promise { - const wallet = await this.em.findOne(UserWallet, { - user: { id: userId }, - restaurant: { id: restaurantId }, - }); + const balance = await this.walletTransactionRepository.getCurrentWalletBalance(userId, restaurantId); - if (!wallet) { - throw new BadRequestException(CartMessage.WALLET_NOT_FOUND); - } - - if (wallet.wallet < amount) { + if (balance < amount) { throw new BadRequestException(CartMessage.WALLET_INSUFFICIENT); } } diff --git a/src/modules/orders/listeners/order.listeners.ts b/src/modules/orders/listeners/order.listeners.ts index 0a3a6fb..4495d74 100644 --- a/src/modules/orders/listeners/order.listeners.ts +++ b/src/modules/orders/listeners/order.listeners.ts @@ -117,18 +117,35 @@ export class OrderListeners { `User not found for order: ${event.orderId} for restaurant: ${event.restaurantId} and order number: ${event.orderNumber}`, ); } - const order = await this.OrderRepository.findOne(event.orderId); - if (!order) { - this.logger.log( - `Order not found for order: ${event.orderId} for restaurant: ${event.restaurantId} and order number: ${event.orderNumber}`, - ); - return; - } - this.userService.createWalletTransaction(event.userId, event.restaurantId, { - amount: order.subTotal, - type: WalletTransactionType.CREDIT, - reason: WalletTransactionReason.ORDER_COMPLETED_DEPOSIT, - }); + + // const restaurant = await this.RestaurantRepository.findOne(event.restaurantId); + // if (!restaurant) { + // this.logger.log( + // `Restaurant not found for order: ${event.orderId} for restaurant: ${event.restaurantId} and order number: ${event.orderNumber}`, + // ); + // return; + // } + // const score = restaurant.score; + // if (!score) { + // this.logger.log( + // `Score not found for restaurant: ${event.restaurantId} and order number: ${event.orderNumber}`, + // ); + // return; + // } + + // increase score for user + // const order = await this.OrderRepository.findOne(event.orderId); + // if (!order) { + // this.logger.log( + // `Order not found for order: ${event.orderId} for restaurant: ${event.restaurantId} and order number: ${event.orderNumber}`, + // ); + // return; + // } + // this.userService.createWalletTransaction(event.userId, event.restaurantId, { + // amount: order.subTotal, + // type: WalletTransactionType.CREDIT, + // reason: WalletTransactionReason.ORDER_COMPLETED_DEPOSIT, + // }); await this.notificationService.sendNotification({ restaurantId: event.restaurantId, diff --git a/src/modules/payments/services/payments.service.ts b/src/modules/payments/services/payments.service.ts index 35673a9..1733710 100644 --- a/src/modules/payments/services/payments.service.ts +++ b/src/modules/payments/services/payments.service.ts @@ -5,14 +5,13 @@ import { EntityManager } from '@mikro-orm/postgresql'; import { Order } from '../../orders/entities/order.entity'; import { Logger } from '@nestjs/common'; import { GatewayManager } from '../gateways/gateway.manager'; -import { UserWallet } from 'src/modules/users/entities/user-wallet.entity'; +import { WalletTransaction } from 'src/modules/users/entities/wallet-transaction.entity'; import { OrderPaymentContext } from '../interface/payment'; import { OrderStatus } from 'src/modules/orders/interface/order.interface'; import { ChartPeriodEnum, PaymentChartDto } from '../dto/payment-chart.dto'; import { PaymentMessage, OrderMessage } from 'src/common/enums/message.enum'; import { EventEmitter2 } from '@nestjs/event-emitter'; import { onlinePaymentSucceedEvent, paymentSucceedEvent } from '../events/payment.events'; -import { WalletTransaction } from 'src/modules/users/entities/wallet-transaction.entity'; import { WalletTransactionReason, WalletTransactionType } from 'src/modules/users/interface/wallet'; @Injectable() @@ -104,20 +103,23 @@ export class PaymentsService { return; } - const wallet = await em.findOne(UserWallet, { + const walletTransaction = await em.findOne(WalletTransaction, { user: { id: order.user.id }, restaurant: { id: order.restaurant.id }, + }, { + orderBy: { createdAt: 'DESC' } }); - if (!wallet) { + if (!walletTransaction) { throw new NotFoundException('User wallet not found'); } - if (wallet.wallet < ctx.amount) { + if (walletTransaction.balance < ctx.amount) { throw new BadRequestException('Insufficient wallet balance'); } - wallet.wallet -= ctx.amount; + const newBalance = walletTransaction.balance - ctx.amount; + const payment = await this.getOrCreateLatestPendingPayment(order.id, { em, @@ -126,19 +128,20 @@ export class PaymentsService { gateway: null, }); - const walletTransaction = this.em.create(WalletTransaction, { - userWallet: wallet, + const newWalletTransaction = em.create(WalletTransaction, { + user: order.user, + restaurant: order.restaurant, amount: ctx.amount, type: WalletTransactionType.DEBIT, reason: WalletTransactionReason.ORDER_PAYMENT, - balance: wallet.wallet - ctx.amount, + balance: newBalance, }); payment.status = PaymentStatusEnum.Paid; payment.paidAt = new Date(); order.status = OrderStatus.PAID; - em.persist([wallet, payment, order, walletTransaction]); + em.persist([ payment, order, newWalletTransaction]); await em.flush(); }); this.eventEmitter.emit( diff --git a/src/modules/users/entities/user-wallet.entity.ts b/src/modules/users/entities/point-transaction.entity.ts similarity index 51% rename from src/modules/users/entities/user-wallet.entity.ts rename to src/modules/users/entities/point-transaction.entity.ts index fd328ef..8c2a186 100644 --- a/src/modules/users/entities/user-wallet.entity.ts +++ b/src/modules/users/entities/point-transaction.entity.ts @@ -1,23 +1,30 @@ -import { Entity, Property, ManyToOne, Index, Unique } from '@mikro-orm/core'; +import { Entity, Property, ManyToOne, Index, Unique, Enum } from '@mikro-orm/core'; import { BaseEntity } from '../../../common/entities/base.entity'; import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity'; import { User } from './user.entity'; +import { PointTransactionReason } from '../interface/point'; +import { PointTransactionType } from '../interface/point'; @Entity({ tableName: 'user_wallets' }) -@Unique({ properties: ['user', 'restaurant'], name: 'unique_user_restaurant' }) @Index({ properties: ['user', 'restaurant'] }) // Composite index for most common query: find wallet by user and restaurant @Index({ properties: ['user'] }) // Index for queries finding all wallets for a user @Index({ properties: ['restaurant'] }) // Index for queries finding all wallets for a restaurant -export class UserWallet extends BaseEntity { - @ManyToOne(() => Restaurant) - restaurant!: Restaurant; - +export class PointTransaction extends BaseEntity { @ManyToOne(() => User) user!: User; - @Property({ default: 0, type: 'int' }) - wallet: number = 0; + @ManyToOne(() => User) + restaurant!: Restaurant; - @Property({ default: 0, type: 'int' }) - points: number = 0; + @Property({ type: 'decimal', precision: 10, scale: 0 }) + amount!: number; + + @Property({ type: 'decimal', precision: 10, scale: 0 }) + balance!: number; + + @Enum(() => PointTransaction) + type!: PointTransactionType; + + @Enum(() => PointTransactionReason) + reason!: PointTransactionReason; } diff --git a/src/modules/users/entities/wallet-transaction.entity.ts b/src/modules/users/entities/wallet-transaction.entity.ts index 037f786..c517e5f 100644 --- a/src/modules/users/entities/wallet-transaction.entity.ts +++ b/src/modules/users/entities/wallet-transaction.entity.ts @@ -2,12 +2,18 @@ import { Entity, Index, Property, OneToMany, Collection, Cascade, ManyToOne, Enu import { BaseEntity } from '../../../common/entities/base.entity'; import { User } from './user.entity'; import { WalletTransactionReason, WalletTransactionType } from '../interface/wallet'; -import { UserWallet } from './user-wallet.entity'; +import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity'; @Entity({ tableName: 'wallet_transactions' }) +@Index({ properties: ['user', 'restaurant'] }) +@Index({ properties: ['user'] }) +@Index({ properties: ['restaurant'] }) export class WalletTransaction extends BaseEntity { - @ManyToOne(() => UserWallet) - userWallet!: UserWallet; + @ManyToOne(() => User) + user!: User; + + @ManyToOne(() => User) + restaurant!: Restaurant; @Property({ type: 'decimal', precision: 10, scale: 0 }) amount!: number; diff --git a/src/modules/users/interface/point.ts b/src/modules/users/interface/point.ts new file mode 100644 index 0000000..fa8a1c5 --- /dev/null +++ b/src/modules/users/interface/point.ts @@ -0,0 +1,10 @@ +export enum PointTransactionType { + CREDIT = 'credit', + DEBIT = 'debit', +} + + +export enum PointTransactionReason { + ORDER_COMPLETED_DEPOSIT = 'order_completed_deposit', + CONVERT_SCORE_TO_POINT = 'convert_score_to_point', +} \ No newline at end of file diff --git a/src/modules/users/interface/wallet.ts b/src/modules/users/interface/wallet.ts index b6383d2..ad91490 100644 --- a/src/modules/users/interface/wallet.ts +++ b/src/modules/users/interface/wallet.ts @@ -10,5 +10,4 @@ export enum WalletTransactionReason { CONVERT_SCORE_TO_WALLET = 'convert_score_to_wallet', WITHDRAW = 'withdraw', DEPOSIT = 'deposit', - ORDER_COMPLETED_DEPOSIT = 'order_completed_deposit', } \ No newline at end of file diff --git a/src/modules/users/providers/user.service.ts b/src/modules/users/providers/user.service.ts index bb8509c..94c8a3f 100644 --- a/src/modules/users/providers/user.service.ts +++ b/src/modules/users/providers/user.service.ts @@ -14,8 +14,7 @@ import { PaginatedResult } from 'src/common/interfaces/pagination.interface'; import { UserRepository } from '../repositories/user.repository'; import { normalizePhone } from '../../utils/phone.util'; import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository'; -import { UserWallet } from '../entities/user-wallet.entity'; -import { UserWalletRepository } from '../repositories/user-wallet.repository'; +import { WalletTransactionRepository } from '../repositories/wallet-transaction.repository'; import { WalletService } from './wallet.service'; import { WalletTransactionReason, WalletTransactionType } from '../interface/wallet'; import { WalletTransaction } from '../entities/wallet-transaction.entity'; @@ -25,7 +24,7 @@ export class UserService { constructor( private readonly userRepository: UserRepository, private readonly restaurantRepository: RestRepository, - private readonly userWalletRepository: UserWalletRepository, + private readonly walletTransactionRepository: WalletTransactionRepository, private readonly walletService: WalletService, private readonly em: EntityManager, ) { } @@ -75,7 +74,7 @@ export class UserService { async findById(id: string): Promise { return this.userRepository.findOne({ id }); } - + // todo : transaction code here async create(phone: string, restId: string): Promise { const normalizedPhone = normalizePhone(phone); const _raw = { @@ -93,8 +92,15 @@ export class UserService { const createData = _raw as unknown as RequiredEntityData; const user = this.userRepository.create(createData); - this.userWalletRepository.create({ user: user, restaurant: restaurant, wallet: 0, points: points }); - await this.em.persistAndFlush(user); + const newWalletTransaction = this.walletTransactionRepository.create({ + user: user, + restaurant: restaurant, + balance: 0, + amount: points, + type: WalletTransactionType.CREDIT, + reason: WalletTransactionReason.DEPOSIT + }); + await this.em.persistAndFlush([user, newWalletTransaction]); return user; } @@ -310,13 +316,23 @@ export class UserService { if (!restaurant) { throw new NotFoundException(`Restaurant with ID ${restId} not found.`); } - let userWallet = await em.findOne(UserWallet, { user: { id: userId }, restaurant: { id: restId } }); - if (!userWallet) { - userWallet = em.create(UserWallet, { user: user, restaurant, wallet: 0, points: 0 }); - await em.persistAndFlush(userWallet); + let walletTransaction = await em.findOne(WalletTransaction, { user: { id: userId }, restaurant: { id: restId } }, + { orderBy: { createdAt: 'DESC' } }); + + if (!walletTransaction) { + walletTransaction = em.create(WalletTransaction, + { + user: user, + restaurant, + balance: 0, + amount: 0, + type: WalletTransactionType.CREDIT, + reason: WalletTransactionReason.DEPOSIT + }); + await em.persistAndFlush(walletTransaction); } // Determine how many points to convert - const pointsToConvert = userWallet.points; + const pointsToConvert = walletTransaction.balance; // Validate points to convert if (pointsToConvert <= 0) { @@ -336,18 +352,17 @@ export class UserService { (Number(pointsToConvert) * Number(restaurant.score.purchaseAmount)) / Number(restaurant.score.purchaseScore); // Convert points to wallet (1:1 ratio - can be made configurable) - const walletTransaction = em.create(WalletTransaction, { - userWallet: userWallet, + const newWalletTransaction = em.create(WalletTransaction, { + user: user, + restaurant: restaurant, amount: walletIncreaseAmount, type: WalletTransactionType.CREDIT, reason: WalletTransactionReason.CONVERT_SCORE_TO_WALLET, - balance: userWallet.wallet + walletIncreaseAmount, + balance: walletTransaction.balance + walletIncreaseAmount, }); // Update user's wallet and points - userWallet.wallet = (userWallet.wallet || 0) + walletIncreaseAmount; - userWallet.points = (userWallet.points || 0) - pointsToConvert; - - em.persist([userWallet, walletTransaction]); + walletTransaction.balance = walletTransaction.balance + walletIncreaseAmount; + em.persist([newWalletTransaction]); await em.flush(); @@ -355,8 +370,9 @@ export class UserService { }); } - getUserWallet(userId: string, restId: string): Promise { - return this.walletService.getUserWallet(userId, restId); + getUserWallet(userId: string, restId: string): Promise { + return this.walletTransactionRepository.findOne({ user: { id: userId }, restaurant: { id: restId } }, + { orderBy: { createdAt: 'DESC' } }); } getUserWalletTransactions(userId: string, restId: string, dto: FindWalletTransactionsDto) { diff --git a/src/modules/users/providers/wallet.service.ts b/src/modules/users/providers/wallet.service.ts index 18fd4ff..9c67e99 100644 --- a/src/modules/users/providers/wallet.service.ts +++ b/src/modules/users/providers/wallet.service.ts @@ -2,9 +2,7 @@ import { Injectable, NotFoundException, BadRequestException } from '@nestjs/comm import { FilterQuery } from '@mikro-orm/core'; import { EntityManager } from '@mikro-orm/postgresql'; import { WalletTransaction } from '../entities/wallet-transaction.entity'; -import { UserWallet } from '../entities/user-wallet.entity'; import { WalletTransactionRepository } from '../repositories/wallet-transaction.repository'; -import { UserWalletRepository } from '../repositories/user-wallet.repository'; import { FindWalletTransactionsDto } from '../dto/find-wallet-transactions.dto'; import { CreateWalletTransactionDto } from '../dto/create-wallet-transaction.dto'; import { PaginatedResult } from 'src/common/interfaces/pagination.interface'; @@ -14,7 +12,6 @@ import { WalletTransactionType } from '../interface/wallet'; export class WalletService { constructor( private readonly walletTransactionRepository: WalletTransactionRepository, - private readonly userWalletRepository: UserWalletRepository, private readonly em: EntityManager, ) { } @@ -40,18 +37,19 @@ export class WalletService { const offset = (page - 1) * limit; // Find the user's wallet for this restaurant - const userWallet = await this.userWalletRepository.findOne({ + const walletTransaction = await this.walletTransactionRepository.findOne({ user: { id: userId }, restaurant: { id: restId }, }); - if (!userWallet) { + if (!walletTransaction) { throw new NotFoundException(`User wallet not found for user ${userId} and restaurant ${restId}.`); } // Build the 'where' filter query const where: FilterQuery = { - userWallet: { id: userWallet.id }, + user: { id: userId }, + restaurant: { id: restId }, }; // Add type filter @@ -108,8 +106,10 @@ export class WalletService { }; } - getUserWallet(userId: string, restId: string): Promise { - return this.userWalletRepository.findOne({ user: { id: userId }, restaurant: { id: restId } }); + getUserWallet(userId: string, restId: string): Promise { + return this.walletTransactionRepository.findOne({ user: { id: userId }, + restaurant: { id: restId } }, + { orderBy: { createdAt: 'DESC' } }); } async createTransaction( @@ -126,17 +126,17 @@ export class WalletService { } // Find the user's wallet for this restaurant - const userWallet = await em.findOne(UserWallet, { + const walletTransaction = await em.findOne(WalletTransaction, { user: { id: userId }, restaurant: { id: restId }, }); - if (!userWallet) { + if (!walletTransaction) { throw new NotFoundException(`User wallet not found for user ${userId} and restaurant ${restId}.`); } // Calculate new balance - const currentBalance = userWallet.wallet || 0; + const currentBalance = walletTransaction.balance || 0; let newBalance: number; if (type === WalletTransactionType.CREDIT) { @@ -153,20 +153,19 @@ export class WalletService { } // Update wallet balance - userWallet.wallet = newBalance; - await em.persistAndFlush(userWallet); + walletTransaction.balance = newBalance; + await em.persistAndFlush(walletTransaction); // Create transaction record const transaction = em.create(WalletTransaction, { - userWallet, + user: walletTransaction.user, + restaurant: walletTransaction.restaurant, amount, - balance: newBalance, type, reason, + balance: newBalance, }); - - await em.persistAndFlush(transaction); - + await em.persistAndFlush([walletTransaction, transaction]); return transaction; } } diff --git a/src/modules/users/repositories/point-transaction.repository.ts b/src/modules/users/repositories/point-transaction.repository.ts new file mode 100644 index 0000000..bbdaa66 --- /dev/null +++ b/src/modules/users/repositories/point-transaction.repository.ts @@ -0,0 +1,17 @@ +import { Injectable } from '@nestjs/common'; +import { EntityManager, EntityRepository } from '@mikro-orm/postgresql'; +import { PointTransaction } from '../entities/point-transaction.entity'; + +@Injectable() +export class PointTransactionRepository extends EntityRepository { + constructor(readonly em: EntityManager) { + super(em, PointTransaction); + } + async getcurrentPointBalance(userId: string, restaurantId: string): Promise { + const pointTransaction = await this.em.findOne(PointTransaction, { + user: { id: userId }, + restaurant: { id: restaurantId }, + }); + return pointTransaction?.balance || 0; + } +} diff --git a/src/modules/users/repositories/user-wallet.repository.ts b/src/modules/users/repositories/user-wallet.repository.ts deleted file mode 100644 index edf2875..0000000 --- a/src/modules/users/repositories/user-wallet.repository.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { Injectable } from '@nestjs/common'; -import { EntityManager, EntityRepository } from '@mikro-orm/postgresql'; -import { UserWallet } from '../entities/user-wallet.entity'; - -@Injectable() -export class UserWalletRepository extends EntityRepository { - constructor(readonly em: EntityManager) { - super(em, UserWallet); - } -} diff --git a/src/modules/users/repositories/wallet-transaction.repository.ts b/src/modules/users/repositories/wallet-transaction.repository.ts index 391f20d..f58650f 100644 --- a/src/modules/users/repositories/wallet-transaction.repository.ts +++ b/src/modules/users/repositories/wallet-transaction.repository.ts @@ -7,4 +7,11 @@ export class WalletTransactionRepository extends EntityRepository { + const walletTransaction = await this.em.findOne(WalletTransaction, { + user: { id: userId }, + restaurant: { id: restaurantId }, + }, { orderBy: { createdAt: 'desc' } }); + return walletTransaction?.balance || 0; + } } diff --git a/src/modules/users/user.module.ts b/src/modules/users/user.module.ts index 301fcce..bfcfefc 100644 --- a/src/modules/users/user.module.ts +++ b/src/modules/users/user.module.ts @@ -7,17 +7,21 @@ import { UserAddress } from './entities/user-address.entity'; import { JwtModule } from '@nestjs/jwt'; import { UserRepository } from './repositories/user.repository'; import { RestaurantsModule } from '../restaurants/restaurants.module'; -import { UserWalletRepository } from './repositories/user-wallet.repository'; import { WalletTransactionRepository } from './repositories/wallet-transaction.repository'; import { WalletService } from './providers/wallet.service'; -import { UserWallet } from './entities/user-wallet.entity'; import { WalletTransaction } from './entities/wallet-transaction.entity'; +import { PointTransaction } from './entities/point-transaction.entity'; @Module({ - providers: [UserService, WalletService, UserRepository, UserWalletRepository, WalletTransactionRepository], + providers: [UserService, WalletService, UserRepository, WalletTransactionRepository], controllers: [UsersController], - imports: [MikroOrmModule.forFeature([User, UserAddress, UserWallet, - WalletTransaction]), JwtModule, RestaurantsModule], - exports: [UserService, WalletService, UserRepository, UserWalletRepository, WalletTransactionRepository], + imports: [MikroOrmModule.forFeature([ + User, + UserAddress, + WalletTransaction, + PointTransaction + ]), + JwtModule, RestaurantsModule, WalletTransactionRepository], + exports: [UserService, WalletService, UserRepository, WalletTransactionRepository], }) export class UserModule { } diff --git a/src/seeders/data/admins.data.ts b/src/seeders/data/admins.data.ts index 9e5ec90..046d332 100644 --- a/src/seeders/data/admins.data.ts +++ b/src/seeders/data/admins.data.ts @@ -12,27 +12,27 @@ export const adminsData: AdminData[] = [ firstName: 'مرتضی', lastName: 'مرتضایی', roleName: 'مدیر ( پلن ویژه)', - restaurantSlug: 'zhivan', + restaurantSlug: 'boote', }, { phone: '09185290775', firstName: 'حمید', lastName: 'ضرقامی', - roleName: 'مدیر (پلن پایه)', + roleName: 'مدیر ( پلن ویژه)', restaurantSlug: 'boote', }, { phone: '09129283395', firstName: 'مهرداد', lastName: 'مظفری', - roleName: 'superAdmin', - restaurantSlug: null, + roleName: 'مدیر ( پلن ویژه)', + restaurantSlug: 'boote', }, { phone: '09184317567', firstName: 'ادمین', lastName: 'هنر', - roleName: 'مدیر (پلن پایه)', - restaurantSlug: 'honar', + roleName: 'مدیر ( پلن ویژه)', + restaurantSlug: 'boote', }, ]; diff --git a/src/seeders/data/restaurants.data.ts b/src/seeders/data/restaurants.data.ts index f1447c4..158ce2d 100644 --- a/src/seeders/data/restaurants.data.ts +++ b/src/seeders/data/restaurants.data.ts @@ -119,7 +119,7 @@ export const restaurantsData: RestaurantData[] = [ marriageDateScore: '2', referrerScore: '2', }, - plan: PlanEnum.Base, + plan: PlanEnum.Premium, subscriptionId: 'sub_seed_boote_001', }, // { diff --git a/src/seeders/user-wallets.seeder.ts b/src/seeders/user-wallets.seeder.ts index fa2bab7..ba266ef 100644 --- a/src/seeders/user-wallets.seeder.ts +++ b/src/seeders/user-wallets.seeder.ts @@ -1,7 +1,8 @@ import type { EntityManager } from '@mikro-orm/core'; import { User } from '../modules/users/entities/user.entity'; import { Restaurant } from '../modules/restaurants/entities/restaurant.entity'; -import { UserWallet } from '../modules/users/entities/user-wallet.entity'; +import { WalletTransaction } from '../modules/users/entities/wallet-transaction.entity'; +import { WalletTransactionReason, WalletTransactionType } from 'src/modules/users/interface/wallet'; export class UserWalletsSeeder { async run(em: EntityManager): Promise { @@ -11,17 +12,19 @@ export class UserWalletsSeeder { for (const user of users) { for (const restaurant of restaurants) { // Check if wallet already exists for this user-restaurant combination - const existingWallet = await em.findOne(UserWallet, { + const existingWallet = await em.findOne(WalletTransaction, { user: { id: user.id }, restaurant: { id: restaurant.id }, }); if (!existingWallet) { - const wallet = em.create(UserWallet, { + const wallet = em.create(WalletTransaction, { user, restaurant, - wallet: 150000000, - points: 1250, + balance: 150000000, + amount: 1250, + type: WalletTransactionType.CREDIT, + reason: WalletTransactionReason.DEPOSIT, }); em.persist(wallet); }