wangzhibo
6 天以前 3f249e399659dcd09d3fe58071b146e50e45c17f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import { Provide } from '@midwayjs/core';
import { BaseService, CoolCommException, CoolTransaction } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { QueryRunner, Repository } from 'typeorm';
import { RecycleTransactionEntity } from '../entity/transaction';
import { UserInfoEntity } from '../../user/entity/info';
 
/**
 * 碳积分流转记录
 */
@Provide()
export class RecycleTransactionService extends BaseService {
  @InjectEntityModel(RecycleTransactionEntity)
  recycleTransactionEntity: Repository<RecycleTransactionEntity>;
 
  @InjectEntityModel(UserInfoEntity)
  userInfoEntity: Repository<UserInfoEntity>;
 
  /**
   * App 端分页:转赠 tab 只看赠送/接受,收支 tab 看其余类型
   */
  async page(query: any) {
    const { userId, tab, page = 1, size = 10 } = query || {};
    const find = this.recycleTransactionEntity.createQueryBuilder('a');
 
    if (userId) {
      find.andWhere('a.userId = :uid', { uid: String(userId) });
    }
 
    if (tab === 'io') {
      find.andWhere('(a.sourceType != :t1 AND a.sourceType != :t2)', {
        t1: '赠送',
        t2: '接受',
      });
    } else {
      find.andWhere('(a.sourceType = :t1 OR a.sourceType = :t2)', {
        t1: '赠送',
        t2: '接受',
      });
    }
 
    find.orderBy('a.createTime', 'DESC');
    find.addOrderBy('a.id', 'DESC');
 
    console.log(find)
 
    return this.entityRenderPage(find, { ...query, page, size }, false);
  }
 
  async checkUser(unionid: string) {
    if (!unionid) {
      throw new CoolCommException('请选择系统用户作为接受转赠对象');
    }
    const user = await this.userInfoEntity.findOneBy({ unionid });
    if (!user) {
      throw new CoolCommException('请选择系统用户作为接受转赠对象');
    }
    return {
      unionid: user.unionid,
      nickName: user.nickName,
      phone: user.phone,
    };
  }
 
  @CoolTransaction()
  async transfer(
    param: { fromUnionid: string; toUnionid: string; amount: number },
    queryRunner?: QueryRunner
  ) {
    if (!queryRunner) {
      throw new CoolCommException('事务启动失败');
    }
 
    const fromUnionid = String(param.fromUnionid || '').trim();
    const toUnionid = String(param.toUnionid || '').trim();
    const amount = Number(param.amount);
 
    if (!fromUnionid || !toUnionid) {
      throw new CoolCommException('转赠参数不完整');
    }
    if (fromUnionid === toUnionid) {
      throw new CoolCommException('不能转赠给自己');
    }
    if (!amount || amount <= 0) {
      throw new CoolCommException('转赠金额必须大于0');
    }
 
    const manager = queryRunner.manager;
    const fromUser = await manager.findOne(UserInfoEntity, {
      where: { unionid: fromUnionid },
    });
    const toUser = await manager.findOne(UserInfoEntity, {
      where: { unionid: toUnionid },
    });
 
    if (!toUser) {
      throw new CoolCommException('请选择系统用户作为接受转赠对象');
    }
    if (!fromUser) {
      throw new CoolCommException('当前用户不存在');
    }
    if (Number(fromUser.carbonBalance || 0) < amount) {
      throw new CoolCommException('碳积分不足');
    }
 
    const dec = await manager
      .createQueryBuilder()
      .update(UserInfoEntity)
      .set({ carbonBalance: () => `carbonBalance - ${amount}` })
      .where('unionid = :unionid AND carbonBalance >= :amount', {
        unionid: fromUnionid,
        amount,
      })
      .execute();
 
    if (!dec.affected) {
      throw new CoolCommException('碳积分不足');
    }
 
    await manager
      .createQueryBuilder()
      .update(UserInfoEntity)
      .set({ carbonBalance: () => `carbonBalance + ${amount}` })
      .where('unionid = :unionid', { unionid: toUnionid })
      .execute();
 
    const fromName = fromUser.nickName || fromUser.phone || fromUnionid;
    const toName = toUser.nickName || toUser.phone || toUnionid;
 
    await manager.save(RecycleTransactionEntity, [
      {
        userId: fromUnionid,
        departmentId: fromUser.departmentId,
        type: '支出',
        amount,
        sourceType: '赠送',
        remark: `转赠给${toName}`,
      },
      {
        userId: toUnionid,
        departmentId: toUser.departmentId,
        type: '收入',
        amount,
        sourceType: '接受',
        remark: `从${fromName}获赠`,
      },
    ]);
 
    return true;
  }
}