|
|
@@ -0,0 +1,91 @@
|
|
|
+import { Injectable, Logger } from '@nestjs/common'
|
|
|
+import { Repository } from 'typeorm'
|
|
|
+import { Balance } from './entities/balance.entities'
|
|
|
+import { InjectRepository } from '@nestjs/typeorm'
|
|
|
+import { BalanceRecord, BalanceType } from './entities/balance-record.entities'
|
|
|
+import { UsersService } from '../users/users.service'
|
|
|
+
|
|
|
+@Injectable()
|
|
|
+export class BalanceService {
|
|
|
+
|
|
|
+ constructor(
|
|
|
+ @InjectRepository(Balance)
|
|
|
+ private balanceRepository: Repository<Balance>,
|
|
|
+ @InjectRepository(BalanceRecord)
|
|
|
+ private recordRepository: Repository<BalanceRecord>,
|
|
|
+ private readonly usersService: UsersService
|
|
|
+ ) {
|
|
|
+ }
|
|
|
+
|
|
|
+ async findBalanceByUserId(userId: number): Promise<Balance> {
|
|
|
+ return await this.balanceRepository.findOne({
|
|
|
+ select: {
|
|
|
+ userId: true,
|
|
|
+ currentBalance: true
|
|
|
+ },
|
|
|
+ where: {
|
|
|
+ userId: userId
|
|
|
+ }
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ async rechargeBalance(userId: number, amount: number): Promise<string> {
|
|
|
+ try {
|
|
|
+ // 获取余额
|
|
|
+ const balance = await this.balanceRepository.findOne({
|
|
|
+ where: {
|
|
|
+ userId: userId
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ const currentBalanceNum = parseFloat(String(balance.currentBalance))
|
|
|
+
|
|
|
+ balance.currentBalance = currentBalanceNum + amount
|
|
|
+ balance.totalBalance = parseFloat(String(balance.totalBalance)) + amount
|
|
|
+
|
|
|
+ console.log('balance:', balance)
|
|
|
+ await this.balanceRepository.save(balance)
|
|
|
+
|
|
|
+ // 充值记录
|
|
|
+ const record = new BalanceRecord()
|
|
|
+ record.userId = userId
|
|
|
+ record.balanceId = balance.id
|
|
|
+ record.amount = amount
|
|
|
+ record.type = BalanceType.RECHARGE
|
|
|
+ await this.recordRepository.save(record)
|
|
|
+
|
|
|
+ return 'recharge success!'
|
|
|
+ } catch (e) {
|
|
|
+ Logger.error('Error recharge ', e, 'RcsService')
|
|
|
+ return 'recharge fail!'
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ async findRecordsByUserId(userId: number): Promise<BalanceRecord[]> {
|
|
|
+ return await this.recordRepository.find({
|
|
|
+ where: {
|
|
|
+ userId: userId
|
|
|
+ }
|
|
|
+ })
|
|
|
+ }
|
|
|
+
|
|
|
+ async updateRate(userId: number, rate: number): Promise<string> {
|
|
|
+ try {
|
|
|
+ const balance = await this.balanceRepository.findOne({
|
|
|
+ where: {
|
|
|
+ userId: userId
|
|
|
+ }
|
|
|
+ })
|
|
|
+
|
|
|
+ balance.rate = rate
|
|
|
+ await this.balanceRepository.save(balance)
|
|
|
+
|
|
|
+ return 'update rate success!'
|
|
|
+ } catch (e) {
|
|
|
+ Logger.error('Error rate ', e, 'RcsService')
|
|
|
+ return 'update rate fail!'
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|