wuyi 1 год назад
Родитель
Сommit
6df5dcf2c7

+ 6 - 1
src/balance/balance.controller.ts

@@ -20,7 +20,7 @@ export class BalanceController {
         if (req.user.roles.includes('user')) {
             return
         }
-        return await this.balanceService.rechargeBalance(parseInt(id), amount)
+        return await this.balanceService.rechargeBalance(req.user.userId, parseInt(id), amount)
     }
 
     @Get('/transfer/:id/:amount')
@@ -44,4 +44,9 @@ export class BalanceController {
         return await this.balanceService.updateRate(parseInt(id), rate)
     }
 
+    @Post('/export')
+    async exportTask(@Req() req, @Body() data) {
+        return await this.balanceService.exportTask(req, data)
+    }
+
 }

+ 2 - 1
src/balance/balance.module.ts

@@ -7,10 +7,11 @@ import { BalanceService } from './balance.service'
 import { UsersModule } from '../users/users.module'
 import { Users } from '../users/entities/users.entity'
 import { SysConfigModule } from '../sys-config/sys-config.module'
+import { Task } from '../task/entities/task.entity'
 
 @Module({
     imports: [
-        TypeOrmModule.forFeature([Balance, BalanceRecord, Users]),
+        TypeOrmModule.forFeature([Balance, BalanceRecord, Users, Task]),
         UsersModule,
         SysConfigModule
     ],

+ 81 - 5
src/balance/balance.service.ts

@@ -1,5 +1,5 @@
 import { Injectable, Logger } from '@nestjs/common'
-import { In, Repository } from 'typeorm'
+import { Between, In, Repository } from 'typeorm'
 import { Balance } from './entities/balance.entities'
 import { InjectRepository } from '@nestjs/typeorm'
 import { BalanceRecord, BalanceType } from './entities/balance-record.entities'
@@ -9,6 +9,9 @@ import { PageRequest } from '../common/dto/page-request'
 import { paginate, Pagination } from 'nestjs-typeorm-paginate'
 import Decimal from 'decimal.js'
 import { SysConfigService } from '../sys-config/sys-config.service'
+import * as ExcelJS from 'exceljs'
+import * as moment from 'moment/moment'
+import { Task } from '../task/entities/task.entity'
 
 @Injectable()
 export class BalanceService {
@@ -19,9 +22,12 @@ export class BalanceService {
         private recordRepository: Repository<BalanceRecord>,
         @InjectRepository(Users)
         private userRepository: Repository<Users>,
+        @InjectRepository(Task)
+        private taskRepository: Repository<Task>,
         private readonly usersService: UsersService,
         private readonly sysConfigService: SysConfigService
-    ) {}
+    ) {
+    }
 
     async findBalanceByUserId(userId: number): Promise<Balance> {
         return await this.balanceRepository.findOne({
@@ -35,7 +41,7 @@ export class BalanceService {
         })
     }
 
-    async rechargeBalance(userId: number, amount: number): Promise<string> {
+    async rechargeBalance(supervisorId: number, userId: number, amount: number): Promise<string> {
         try {
             // 获取余额
             let balance = await this.balanceRepository.findOne({
@@ -66,6 +72,7 @@ export class BalanceService {
             // 充值记录
             const record = new BalanceRecord()
             record.userId = userId
+            record.supervisorId = supervisorId
             record.balanceId = balance.id
             record.amount = amount
             record.type = BalanceType.RECHARGE
@@ -131,6 +138,7 @@ export class BalanceService {
                 // 划转记录
                 const record = new BalanceRecord()
                 record.userId = userId
+                record.targetId = targetUserId
                 record.balanceId = balance.id
                 record.amount = amount
                 record.type = BalanceType.TRANSFER
@@ -138,6 +146,7 @@ export class BalanceService {
 
                 const tarRecord = new BalanceRecord()
                 tarRecord.userId = targetUserId
+                tarRecord.supervisorId = userId
                 tarRecord.balanceId = targetBalance.id
                 tarRecord.amount = amount
                 tarRecord.type = BalanceType.RECHARGE
@@ -169,7 +178,7 @@ export class BalanceService {
     async changeScreenBalance(userId: number, amount: number) {
         const amountDecimal = new Decimal(amount)
         const users = await this.usersService.findById(userId)
-        if (users.screenBalance < amountDecimal.toNumber()){
+        if (users.screenBalance < amountDecimal.toNumber()) {
             return false
         }
         const newScreenBalance = new Decimal(String(users.screenBalance)).sub(amountDecimal)
@@ -178,7 +187,7 @@ export class BalanceService {
         return true
     }
 
-    async feeDeduction(userId: number, cost: number) {
+    async feeDeduction(userId: number, cost: number, taskId: number) {
         try {
             const user = await this.usersService.findById(userId)
             // 获取余额
@@ -200,6 +209,7 @@ export class BalanceService {
             const record = new BalanceRecord()
             record.userId = userId
             record.balanceId = balance.id
+            record.taskId = taskId
             record.amount = cost
             record.type = BalanceType.CONSUMPTION
             await this.recordRepository.save(record)
@@ -272,4 +282,70 @@ export class BalanceService {
             return 'update rate fail!'
         }
     }
+
+    async exportTask(req: any, data: any) {
+        if (!data.startDate || !data.endDate) {
+            throw new Error('请选择日期')
+        }
+        if (!req.user.roles.includes('user')) {
+            const where = {
+                userId: data.userId,
+                createdAt: Between(data.startDate, data.endDate)
+            }
+
+            const balanceRecords = await this.recordRepository.find({
+                where,
+                order: {
+                    createdAt: 'DESC'
+                }
+            })
+
+            if (balanceRecords.length == 0) {
+                throw new Error('暂无日期内数据')
+            }
+
+            const workbook = new ExcelJS.Workbook()
+            const worksheet = workbook.addWorksheet('Sheet1')
+            // 设置列头
+            worksheet.columns = [
+                { header: '#', key: 'id', width: 30, style: { alignment: { horizontal: 'center' } } },
+                { header: '金额', key: 'amount', width: 15, style: { alignment: { horizontal: 'center' } } },
+                { header: '类型', key: 'type', width: 15, style: { alignment: { horizontal: 'center' } } },
+                { header: '任务id', key: 'taskId', width: 15, style: { alignment: { horizontal: 'center' } } },
+                { header: '任务名称', key: 'taskName', width: 15, style: { alignment: { horizontal: 'center' } } },
+                {
+                    header: '创建时间',
+                    key: 'createdAt',
+                    width: 30,
+                    style: { alignment: { horizontal: 'center' }, numFmt: 'YYYY-MM-DD HH:mm:ss' }
+                }
+            ]
+
+            const taskIds = balanceRecords.map((item) => item.taskId)
+            let tasks = []
+            if (taskIds.length > 0) {
+                tasks = await this.taskRepository.findBy({
+                    id: In(taskIds)
+                })
+            }
+
+            balanceRecords.forEach((record) => {
+                const task = tasks.find((task) => task.id === record.taskId)
+                worksheet.addRow({
+                    id: record.id,
+                    amount: record.amount,
+                    type: record.type === BalanceType.RECHARGE ? '充值' : (record.type === BalanceType.CONSUMPTION ? '消费' : (record.type === BalanceType.TRANSFER ? '划转' : '其他')),
+                    taskId: task ? task.id : '-',
+                    taskName: task ? task.name : '-',
+                    createdAt: record.createdAt ? moment(record.createdAt).format('YYYY-MM-DD HH:mm:ss') : ''
+                })
+            })
+
+            return await workbook.xlsx.writeBuffer()
+
+        } else {
+            throw new Error('Permission denied!')
+        }
+    }
+
 }

+ 9 - 0
src/balance/entities/balance-record.entities.ts

@@ -19,9 +19,18 @@ export class BalanceRecord {
     @Column()
     userId: number
 
+    @Column({ nullable: true })
+    supervisorId: number
+
+    @Column({ nullable: true })
+    targetId: number
+
     @Column({ nullable: true })
     balanceId: number
 
+    @Column({ nullable: true })
+    taskId: number
+
     @Column({ type: 'enum', enum: BalanceType, nullable: false, default: BalanceType.RECHARGE })
     type: BalanceType
 

+ 3 - 2
src/task/task.service.ts

@@ -238,7 +238,7 @@ export class TaskService implements OnModuleInit {
                 if (cost > (user.balance || 0)) {
                     throw new Error('Insufficient balance!')
                 }
-                await this.balanceService.feeDeduction(task.userId, cost)
+                await this.balanceService.feeDeduction(task.userId, cost, task.id)
                 await this.taskRepository.update({ id }, { paid: true })
             }
         }
@@ -572,7 +572,8 @@ export class TaskService implements OnModuleInit {
             if (durianRes.data.code === 200) {
                 res.durian = durianRes.data.data.score
             }
-        } catch (e) {}
+        } catch (e) {
+        }
 
         try {
             const cloudInstance = axios.create({