Prechádzať zdrojové kódy

修改商户模块,增加支付方式,货币单位,商户费率等

test 10 mesiacov pred
rodič
commit
45f7428afe

+ 2 - 0
package.json

@@ -22,6 +22,7 @@
     "@midwayjs/upload": "^3.15.2",
     "@midwayjs/validate": "^3.15.2",
     "@midwayjs/view-ejs": "^3.15.2",
+    "@types/speakeasy": "^2.0.10",
     "@types/uuid": "^10.0.0",
     "alipay-sdk": "^4.11.0",
     "axios": "^1.6.7",
@@ -37,6 +38,7 @@
     "moment": "^2.30.1",
     "mysql2": "^3.9.2",
     "node-rsa": "^1.1.1",
+    "speakeasy": "^2.0.0",
     "svg-captcha": "^1.4.0",
     "svg2png-wasm": "^1.4.1",
     "typeorm": "^0.3.20",

+ 14 - 0
src/comm/utils.ts

@@ -5,6 +5,7 @@ import * as _ from 'lodash';
 import * as moment from 'moment';
 import * as NodeRSA from 'node-rsa';
 import * as crypto from 'crypto'
+import * as  speakeasy from 'speakeasy';
 
 /**
  * 帮助类
@@ -237,4 +238,17 @@ export class Utils {
     // 生成哈希值
     return hmac.digest('base64');
   }
+
+  getGoogleSecret() {
+    return speakeasy.generateSecret({ length: 20 })
+  }
+
+  validGoogleSecret(secret, code) {
+    return speakeasy.totp.verify({
+      secret: secret,
+      encoding: 'base32',
+      token: code,
+      algorithm: 'sha1'
+    })
+  }
 }

+ 1 - 9
src/modules/dj/controller/admin/balance.ts

@@ -1,5 +1,5 @@
 import { BalanceEntity } from '../../entity/balance';
-import { Post, Inject, Provide } from '@midwayjs/decorator';
+import { Provide } from '@midwayjs/decorator';
 import { CoolController, BaseController } from '@cool-midway/core';
 import { BalanceService } from '../../service/balance';
 
@@ -10,12 +10,4 @@ import { BalanceService } from '../../service/balance';
   service: BalanceService,
 })
 export class BalanceController extends BaseController {
-  @Inject()
-  balanceService: BalanceService;
-
-  @Post('/summary', { summary: '统计' })
-  async summary() {
-    const { body } = this.baseCtx.request;
-    return this.ok(await this.balanceService.summary(body));
-  }
 }

+ 26 - 7
src/modules/dj/controller/admin/comm.ts

@@ -2,7 +2,9 @@ import { Inject, Post, Provide, Body, ALL } from '@midwayjs/decorator';
 import { CoolController, BaseController } from '@cool-midway/core';
 import { OrderService } from '../../service/order';
 import { BaseSysConfService } from '../../../base/service/sys/conf';
-import { BalanceService } from '../../service/balance';
+import { CurrencyService } from '../../service/currency';
+import { MerchantService } from '../../service/merchant';
+import { PayTypeService } from '../../service/payType';
 
 @Provide()
 @CoolController()
@@ -11,23 +13,40 @@ export class OrdertController extends BaseController {
   orderService: OrderService;
 
   @Inject()
-  baseSysConfService: BaseSysConfService;
+  currencyService: CurrencyService;
+
+  @Inject()
+  merchantService: MerchantService;
+  
+  @Inject()
+  payTypeService: PayTypeService;
 
   @Inject()
-  balanceService: BalanceService;
+  baseSysConfService: BaseSysConfService;
 
   @Post('/dashboard', { summary: '统计' })
   async dashboard(@Body(ALL) payload: any) {
     return this.ok(await this.orderService.dashboard(payload));
   }
 
-  @Post('/queryBalance', { summary: '统计' })
-  async queryBalance(@Body(ALL) payload: any) {
-    return this.ok(await this.balanceService.queryBalance(payload));
-  }
 
   @Post('/chartData', { summary: '报表' })
   async chartData(@Body(ALL) payload: any) {
     return this.ok(await this.orderService.chartData(payload));
   }
+
+  @Post('/getCurrency', { summary: '货币列表' })
+  async getCurrency() {
+    return this.ok(await this.currencyService.getCurrencyList());
+  }
+
+  @Post('/getMerchants', { summary: '商户列表' })
+  async getMerchants() {
+    return this.ok(await this.merchantService.getMerchantList());
+  }
+
+  @Post('/getPayTypes', { summary: '支付类型列表' })
+  async getPayTypes() {
+    return this.ok(await this.payTypeService.getPayTypeList());
+  }
 }

+ 15 - 0
src/modules/dj/controller/admin/currency.ts

@@ -0,0 +1,15 @@
+import { CurrencyEntity } from '../../entity/currency';
+import { Provide } from '@midwayjs/decorator';
+import { CoolController, BaseController } from '@cool-midway/core';
+import { CurrencyService } from '../../service/currency';
+
+@Provide()
+@CoolController({
+  api: ['add', 'delete', 'update', 'info', 'page', 'list'],
+  entity: CurrencyEntity,
+  service: CurrencyService,
+  pageQueryOp: {
+    keyWordLikeFields: ['currency'],
+  },
+})
+export class CurrencyController extends BaseController {}

+ 0 - 13
src/modules/dj/controller/admin/mchBalance.ts

@@ -1,13 +0,0 @@
-import { MchBalanceEntity } from '../../entity/mchBalance';
-import { Post, Inject, Provide } from '@midwayjs/decorator';
-import { CoolController, BaseController } from '@cool-midway/core';
-
-@Provide()
-@CoolController({
-  api: ['list', 'info'],
-  entity: MchBalanceEntity,
-  listQueryOp: {
-    keyWordLikeFields: ['mchId'],
-  },
-})
-export class McjBalanceController extends BaseController {}

+ 20 - 3
src/modules/dj/controller/admin/merchant.ts

@@ -1,15 +1,32 @@
 import { MerchantEntity } from './../../entity/merchant';
-import { Provide } from '@midwayjs/decorator';
+import { Body, Get, Inject, Post, Provide } from '@midwayjs/decorator';
 import { CoolController, BaseController } from '@cool-midway/core';
 import { MerchantService } from '../../service/merchant';
+import { Utils } from '../../../../comm/utils';
 
 @Provide()
 @CoolController({
   api: ['add', 'delete', 'update', 'info', 'page', 'list'],
   entity: MerchantEntity,
   service: MerchantService,
-  listQueryOp: {
+  pageQueryOp: {
     keyWordLikeFields: ['mchId'],
+    select: ['a.id', 'a.userId', 'a.name', 'a.mchId', 'a.email', 'a.status', 'a.whiteIp', 'a.remark', 'a.createTime', 'a.key', 'a.secret', 'a.currency']
   },
+  infoIgnoreProperty: ['fundPwd']
 })
-export class MerchantController extends BaseController {}
+export class MerchantController extends BaseController {
+  @Inject()
+  utils: Utils;
+
+  @Get('/createSecret', { summary: '生成谷歌验证码' })
+  async createSecret() {
+    return this.ok(this.utils.getGoogleSecret().base32);
+  }
+
+  @Post('/validSecret', { summary: '校验谷歌验证码' })
+  async validSecret(@Body('secret') secret, @Body('code') code) {
+    return this.ok(this.utils.validGoogleSecret(secret, code));
+  }
+
+}

+ 15 - 0
src/modules/dj/controller/admin/payType.ts

@@ -0,0 +1,15 @@
+import { PayTypeEntity } from '../../entity/payType';
+import { Provide } from '@midwayjs/decorator';
+import { CoolController, BaseController } from '@cool-midway/core';
+import { PayTypeService } from '../../service/payType';
+
+@Provide()
+@CoolController({
+  api: ['add', 'delete', 'update', 'info', 'page', 'list'],
+  entity: PayTypeEntity,
+  service: PayTypeService,
+  pageQueryOp: {
+    keyWordLikeFields: ['payType'],
+  },
+})
+export class PayTypeController extends BaseController {}

+ 12 - 0
src/modules/dj/controller/admin/rate.ts

@@ -0,0 +1,12 @@
+import { RateEntity } from '../../entity/rate';
+import { Provide } from '@midwayjs/decorator';
+import { CoolController, BaseController } from '@cool-midway/core';
+import { RateService } from '../../service/rate';
+
+@Provide()
+@CoolController({
+  api: ['add', 'delete', 'update', 'info', 'page', 'list'],
+  entity: RateEntity,
+  service: RateService,
+})
+export class RateController extends BaseController {}

+ 12 - 0
src/modules/dj/controller/admin/wallet.ts

@@ -0,0 +1,12 @@
+import { WalletEntity } from '../../entity/wallet';
+import { Provide } from '@midwayjs/decorator';
+import { CoolController, BaseController } from '@cool-midway/core';
+import { WalletService } from '../../service/wallet';
+
+@Provide()
+@CoolController({
+  api: ['delete', 'update', 'info', 'page', 'list'],
+  entity: WalletEntity,
+  service: WalletService,
+})
+export class WalletController extends BaseController {}

+ 3 - 0
src/modules/dj/entity/balance.ts

@@ -20,6 +20,9 @@ export class BalanceEntity extends BaseEntity {
   })
   type: number;
 
+  @Column({ comment: '货币单位' })
+  currency: string;
+
   @Column({
     comment: '金额',
     type: 'decimal',

+ 17 - 0
src/modules/dj/entity/currency.ts

@@ -0,0 +1,17 @@
+import { BaseEntity } from '@cool-midway/core';
+import { Column, Entity, Index } from 'typeorm';
+
+/**
+ * 描述
+ */
+@Entity('dj_currency')
+export class CurrencyEntity extends BaseEntity {
+  @Column({ comment: '货币' })
+  currency: string;
+
+  @Column({ comment: '描述', nullable: true })
+  desc: string;
+
+  @Column({ comment: 'icon', nullable: true })
+  icon: string;
+}

+ 13 - 13
src/modules/dj/entity/merchant.ts

@@ -16,27 +16,27 @@ export class MerchantEntity extends BaseEntity {
   @Column({ comment: '商户号' })
   mchId: string;
 
-  @Column({ comment: '手续费', type: 'decimal', precision: 10, scale: 2 })
-  rate: string;
-
-  @Column({ comment: '代付手续费', type: 'decimal', precision: 10, scale: 2 })
-  withdrawRate: string;
-
-  @Column({ comment: '代付单笔固定费用', type: 'decimal', precision: 10, scale: 2 })
-  withdrawBasicFee: string;
-
-  @Column({ comment: '代付单笔最低费用', type: 'decimal', precision: 10, scale: 2 })
-  withdrawFeeMin: number;
+  @Column({ comment: '邮箱' })
+  email: string;
 
   @Column({ comment: '状态 0-禁用 1-启用', default: 1 })
   status: number;
 
-  @Column({ comment: '代付状态 0-禁用 1-启用', default: 1 })
-  withdrawStatus: number;
+  @Column({ comment: '资金密码' })
+  fundPwd: string;
 
   @Column({ comment: 'MD5Key' })
   key: string;
 
+  @Column({ comment: 'secret' })
+  secret: string;
+
+  @Column({ comment: '可用币种' })
+  currency: string;
+
+  @Column({ comment: 'IP白名单', length: 1000, nullable: true })
+  whiteIp: string;
+
   @Column({ comment: '备注', nullable: true })
   remark: string;
 }

+ 20 - 0
src/modules/dj/entity/payType.ts

@@ -0,0 +1,20 @@
+import { BaseEntity } from '@cool-midway/core';
+import { Column, Entity, Index } from 'typeorm';
+
+/**
+ * 描述
+ */
+@Entity('dj_pay_type')
+export class PayTypeEntity extends BaseEntity {
+  @Column({ comment: '支付方式' })
+  payType: string;
+
+  @Column({ comment: '类型 1-代收 2-代付', default: 1 })
+  type: number;
+
+  @Column({ comment: '货币', default: '', length: 300 })
+  currencies: string;
+
+  @Column({ comment: '描述', nullable: true })
+  remark: string;
+}

+ 29 - 0
src/modules/dj/entity/rate.ts

@@ -0,0 +1,29 @@
+import { BaseEntity } from '@cool-midway/core';
+import { Column, Entity, Index } from 'typeorm';
+
+/**
+ * 描述
+ */
+@Entity('dj_rate')
+export class RateEntity extends BaseEntity {
+  @Column({ comment: '商户号' })
+  mchId: string;
+
+  @Column({ comment: '货币单位' })
+  currency: string;
+
+  @Column({ comment: '类型 1-代收 2-代付', default: 1 })
+  type: number;
+
+  @Column({ comment: '支付方式'})
+  payType: string;
+
+  @Column({ comment: '费率', type: 'decimal', precision: 10, scale: 2 })
+  rate: number;
+
+  @Column({ comment: '单笔固定费用', type: 'decimal', precision: 10, scale: 2 })
+  basicFee: number;
+
+  @Column({ comment: '单笔最低费用', type: 'decimal', precision: 10, scale: 2 })
+  feeMin: number;
+}

+ 15 - 4
src/modules/dj/entity/mchBalance.ts → src/modules/dj/entity/wallet.ts

@@ -2,14 +2,16 @@ import { BaseEntity } from '@cool-midway/core';
 import { Column, Entity, Index } from 'typeorm';
 
 /**
- * 字典信息
+ * 商户钱包
  */
-@Entity('dj_mch_balance')
-export class MchBalanceEntity extends BaseEntity {
-  @Index({ unique: true })
+@Entity('dj_wallet')
+export class WalletEntity extends BaseEntity {
   @Column({ comment: '商户号' })
   mchId: string;
 
+  @Column({ comment: '货币单位' })
+  currency: string;
+
   @Column({
     comment: '余额',
     type: 'decimal',
@@ -18,4 +20,13 @@ export class MchBalanceEntity extends BaseEntity {
     default: 0,
   })
   balance: number;
+
+  @Column({
+    comment: '冻结中余额',
+    type: 'decimal',
+    precision: 10,
+    scale: 2,
+    default: 0,
+  })
+  freeze: number;
 }

+ 3 - 3
src/modules/dj/queue/balanceQueue.ts

@@ -1,7 +1,7 @@
 import { BaseCoolQueue, CoolQueue } from '@cool-midway/task';
 import { ILogger, IMidwayApplication, Inject, Logger } from '@midwayjs/core';
 import { App } from '@midwayjs/decorator';
-import { MchBalanceService } from '../service/mchBalance';
+import { BalanceService } from '../service/balance';
 
 @CoolQueue()
 export class BalanceQueue extends BaseCoolQueue {
@@ -9,7 +9,7 @@ export class BalanceQueue extends BaseCoolQueue {
   app: IMidwayApplication;
 
   @Inject()
-  mchBalanceService: MchBalanceService;
+  balanceService: BalanceService;
 
   @Logger()
   logger: ILogger;
@@ -17,7 +17,7 @@ export class BalanceQueue extends BaseCoolQueue {
   async data(job: any, done: any): Promise<void> {
     try {
       this.logger.info('更新余额', job.data);
-      await this.mchBalanceService.update(job.data);
+      await this.balanceService.addBalance(job.data);
     } catch (err) {
       this.logger.error('更新余额失败', job.data, err.message);
     }

+ 26 - 95
src/modules/dj/service/balance.ts

@@ -1,5 +1,5 @@
 import { BalanceEntity } from '../entity/balance';
-import { Inject, Provide } from '@midwayjs/decorator';
+import { Inject, Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
 import { BaseService } from '@cool-midway/core';
 import { InjectEntityModel } from '@midwayjs/typeorm';
 import { Repository } from 'typeorm';
@@ -7,15 +7,14 @@ import * as _ from 'lodash';
 import { BalanceQueue } from '../queue/balanceQueue';
 import { Utils } from '../../../comm/utils';
 import { MerchantEntity } from '../entity/merchant';
+import { WalletEntity } from '../entity/wallet';
 
 @Provide()
+@Scope(ScopeEnum.Request, { allowDowngrade: true })
 export class BalanceService extends BaseService {
   @InjectEntityModel(BalanceEntity)
   balanceEntity: Repository<BalanceEntity>;
 
-  @Inject()
-  balanceQueue: BalanceQueue;
-
   @Inject()
   utils: Utils;
 
@@ -25,88 +24,32 @@ export class BalanceService extends BaseService {
   @InjectEntityModel(MerchantEntity)
   merchantEntity: Repository<MerchantEntity>;
 
-  async queryBalance(query) {
-    let { mchId = '' } = query;
-    const { roleIds, userId } = this.ctx.admin;
-    if (this.utils.isMerchant(roleIds)) {
-      const merchant = await this.merchantEntity.findOneBy({ userId });
-      if (merchant) {
-        mchId = merchant.mchId;
-      } else {
-        mchId = '-1';
-      }
-    }
-    const sql = `SELECT a.* FROM dj_mch_balance a
-    WHERE 1 = 1 
-    ${
-      this.utils.isMerchant(roleIds)
-        ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
-        : this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
-    }
-    `;
-    return this.nativeQuery(sql);
-  }
+  @InjectEntityModel(WalletEntity)
+  walletEntity: Repository<WalletEntity>;
 
-  async add(param) {
-    param.orderNo =
-      param.orderNo || this.utils.createOrderNo(this.getPrefix(param.type));
-    return new Promise(resolve => {
-      this.balanceQueue.add(param);
-      resolve(param);
+  async addBalance(param) {
+    const data = await this.walletEntity.findOneBy({
+      mchId: param.mchId,
+      currency: param.currency
     });
-  }
-
-  async summary(query) {
-    let { orderNo = '', mchId = '', type = '', createTime = [] } = query;
-    const { roleIds, userId } = this.ctx.admin;
-    if (this.utils.isMerchant(roleIds)) {
-      const merchant = await this.merchantEntity.findOneBy({ userId });
-      if (merchant) {
-        mchId = merchant.mchId;
-      } else {
-        mchId = '-1';
-      }
+    if (data) {
+      await this.balanceEntity.insert(param);
+      data.balance = +data.balance + +param.amount;
+      await this.walletEntity.save(data);
+    } else {
+      await this.balanceEntity.insert(param);
+      await this.walletEntity.save({
+        mchId: param.mchId,
+        currency: param.currency,
+        balance: +param.amount,
+        freeze: 0
+      })
     }
-    const sql = `SELECT 
-      SUM(IF(a.type=1, a.amount, 0)) as num1,
-      SUM(IF(a.type=2, a.amount, 0)) as num2,
-      SUM(IF(a.type=3, a.amount, 0)) as num3,
-      SUM(IF(a.type=4, a.amount, 0)) as num4
-      FROM dj_balance a WHERE 1=1
-      ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
-      ${
-        this.utils.isMerchant(roleIds)
-          ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
-          : this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
-      }
-      ${this.setSql(type, 'and a.type = ?', [type])}
-      ${this.setSql(
-        createTime && createTime.length === 2,
-        'and (a.createTime between ? and ?)',
-        createTime
-      )}
-    `;
-    const data = (await this.nativeQuery(sql))[0] || {
-      num1: 0,
-      num2: 0,
-      num3: 0,
-      num4: 0,
-      num5: 0,
-    };
-    const bsql = `SELECT 
-      SUM(a.balance) as balance
-      FROM pay_mch_balance a WHERE 1=1
-      ${this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])}
-      `;
-    const data2 = (await this.nativeQuery(bsql))[0] || { balance: 0 };
-    data.num5 = data2.balance;
-    return data;
   }
 
   async page(query) {
-    let { orderNo = '', mchId = '', type = '', createTime = [] } = query;
+    let { orderNo = '', mchId = '', type = '', currency = '', createTime = [] } = query;
     const { roleIds, userId } = this.ctx.admin;
-    console.log(userId, roleIds);
     if (this.utils.isMerchant(roleIds)) {
       const merchant = await this.merchantEntity.findOneBy({ userId });
       if (merchant) {
@@ -117,12 +60,12 @@ export class BalanceService extends BaseService {
     }
     const sql = `SELECT * FROM dj_balance a WHERE 1=1
       ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
-      ${
-        this.utils.isMerchant(roleIds)
-          ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
-          : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
+      ${this.utils.isMerchant(roleIds)
+        ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
+        : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
       }
       ${this.setSql(type, 'and a.type = ?', [type])}
+      ${this.setSql(currency, 'and a.currency like ?', [`%${currency}%`])}
       ${this.setSql(
         createTime && createTime.length === 2,
         'and (a.createTime between ? and ?)',
@@ -131,16 +74,4 @@ export class BalanceService extends BaseService {
     `;
     return this.sqlRenderPage(sql, query);
   }
-
-  getPrefix(type) {
-    if (+type === 2) {
-      return 'XF';
-    } else if (+type === 3) {
-      return 'CZ';
-    } else if (+type === 4) {
-      return 'NC';
-    } else {
-      return 'DS';
-    }
-  }
 }

+ 20 - 0
src/modules/dj/service/currency.ts

@@ -0,0 +1,20 @@
+import { Provide } from '@midwayjs/decorator';
+import { BaseService } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+import * as _ from 'lodash';
+import { CurrencyEntity } from '../entity/currency';
+
+@Provide()
+export class CurrencyService extends BaseService {
+
+  @InjectEntityModel(CurrencyEntity)
+  currencyEntity: Repository<CurrencyEntity>;
+
+  async getCurrencyList() {
+    const data = await this.currencyEntity.find({
+      select: ["currency"]
+    })
+    return data.map(item => item.currency);
+  }
+}

+ 0 - 34
src/modules/dj/service/mchBalance.ts

@@ -1,34 +0,0 @@
-import { Provide, Scope, ScopeEnum } from '@midwayjs/decorator';
-import { BaseService } from '@cool-midway/core';
-import { InjectEntityModel } from '@midwayjs/typeorm';
-import { Repository } from 'typeorm';
-import * as _ from 'lodash';
-import { MchBalanceEntity } from '../entity/mchBalance';
-import { BalanceEntity } from '../entity/balance';
-
-@Provide()
-@Scope(ScopeEnum.Request, { allowDowngrade: true })
-export class MchBalanceService extends BaseService {
-  @InjectEntityModel(MchBalanceEntity)
-  mchBalanceEntity: Repository<MchBalanceEntity>;
-
-  @InjectEntityModel(BalanceEntity)
-  balanceEntity: Repository<BalanceEntity>;
-
-  async update(param) {
-    await this.balanceEntity.insert(param);
-    const data = await this.mchBalanceEntity.findOneBy({
-      mchId: param.mchId,
-    });
-    if (data) {
-      data.balance = +data.balance + +param.amount;
-      await this.mchBalanceEntity.save(data);
-    }
-  }
-
-  async queryByMerchant(mchId) {
-    return this.mchBalanceEntity.findOneBy({
-      mchId
-    })
-  }
-}

+ 16 - 21
src/modules/dj/service/merchant.ts

@@ -6,7 +6,7 @@ import { Repository, In } from 'typeorm';
 import { BaseSysUserEntity } from '../../base/entity/sys/user';
 import * as _ from 'lodash';
 import { BaseSysUserService } from '../../base/service/sys/user';
-import { MchBalanceEntity } from '../entity/mchBalance';
+import * as md5 from 'md5';
 
 @Provide()
 export class MerchantService extends BaseService {
@@ -16,22 +16,9 @@ export class MerchantService extends BaseService {
   @InjectEntityModel(BaseSysUserEntity)
   baseSysUserEntity: Repository<BaseSysUserEntity>;
 
-  @InjectEntityModel(MchBalanceEntity)
-  mchBalanceEntity: Repository<MchBalanceEntity>;
-
   @Inject()
   baseSysUserService: BaseSysUserService;
 
-  async page(query) {
-    const { keyWord } = query;
-    const sql = `SELECT a.*, b.balance as balance FROM dj_mch a
-    LEFT JOIN dj_mch_balance b on b.mchId = a.mchId
-    WHERE 1 = 1 ${this.setSql(keyWord, 'and a.mchId LIKE ?', [
-      `%${keyWord}%`,
-    ])}`;
-    return this.sqlRenderPage(sql, query);
-  }
-
   async add(param) {
     const exists = await this.baseSysUserEntity.findOneBy({
       username: param.mchId,
@@ -52,17 +39,19 @@ export class MerchantService extends BaseService {
 
     await this.merchantEntity.save({
       ...param,
+      fundPwd: md5(param.fundPwd),
       userId,
     });
 
-    await this.mchBalanceEntity.save({
-      mchId: param.mchId,
-      balance: 0,
-    });
     return param.id;
   }
 
   async update(param) {
+    if (!_.isEmpty(param.fundPwd)) {
+      param.fundPwd = md5(param.fundPwd);
+    } else {
+      delete param.fundPwd;
+    }
     await this.merchantEntity.save(param);
     const user = await this.baseSysUserEntity.findOneBy({ id: param.userId });
     await this.baseSysUserService.update({
@@ -83,9 +72,6 @@ export class MerchantService extends BaseService {
     await this.baseSysUserEntity.delete({
       id: In(merchants.map(item => item.userId)),
     });
-    await this.mchBalanceEntity.delete({
-      mchId: In(merchants.map(item => item.mchId)),
-    });
   }
 
   async getByMchId(mchId) {
@@ -93,4 +79,13 @@ export class MerchantService extends BaseService {
       mchId: mchId,
     });
   }
+
+  async getMerchantList() {
+    return await this.merchantEntity.find({
+      where: {
+        status: 1
+      },
+      select: ["mchId", "name"]
+    })
+  }
 }

+ 3 - 3
src/modules/dj/service/order.ts

@@ -5,13 +5,13 @@ import { Repository } from 'typeorm';
 import * as _ from 'lodash';
 import { OrderEntity } from '../entity/order';
 import { CoolCommException } from '@cool-midway/core';
-import { BalanceService } from './balance';
 import { NotifyService } from './notify';
 import * as moment from 'moment';
 import { MerchantEntity } from '../entity/merchant';
 import { Utils } from '../../../comm/utils';
 import { DispatchService } from './channels/dispatch';
 import { ChannelService } from './channel';
+import { WalletService } from './wallet';
 
 @Provide()
 export class OrderService extends BaseService {
@@ -22,7 +22,7 @@ export class OrderService extends BaseService {
   merchantEntity: Repository<MerchantEntity>;
 
   @Inject()
-  balanceService: BalanceService;
+  walletService: WalletService;
 
   @Inject()
   notifyService: NotifyService;
@@ -105,7 +105,7 @@ export class OrderService extends BaseService {
     order.date = data.date || new Date();
     order.traceNo = data.traceNo;
     await this.orderEntity.update(order.id, order);
-    await this.balanceService.add({
+    await this.walletService.updateBalance({
       orderNo: order.orderNo,
       mchId: order.mchId,
       type: 1,

+ 18 - 0
src/modules/dj/service/payType.ts

@@ -0,0 +1,18 @@
+import { Provide } from '@midwayjs/decorator';
+import { BaseService } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+import * as _ from 'lodash';
+import { PayTypeEntity } from '../entity/payType';
+
+@Provide()
+export class PayTypeService extends BaseService {
+  @InjectEntityModel(PayTypeEntity)
+  payTypeEntity: Repository<PayTypeEntity>;
+
+  async getPayTypeList() {
+    return await this.payTypeEntity.find({
+      select: ['payType', 'type', 'currencies']
+    })
+  }
+}

+ 22 - 0
src/modules/dj/service/rate.ts

@@ -0,0 +1,22 @@
+import { Inject, Provide } from '@midwayjs/decorator';
+import { BaseService } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+import * as _ from 'lodash';
+import { RateEntity } from '../entity/rate';
+import { WalletService } from './wallet';
+
+@Provide()
+export class RateService extends BaseService {
+  @InjectEntityModel(RateEntity)
+  rateEntity: Repository<RateEntity>;
+
+  @Inject()
+  walletService: WalletService;
+
+  async add(param) {
+    await this.rateEntity.save(param);
+    await this.walletService.createWallet(param.mchId, param.currency)
+    return param.id;
+  }
+}

+ 4 - 4
src/modules/dj/service/repay.ts

@@ -10,7 +10,7 @@ import { DispatchService } from './channels/dispatch';
 import { Utils } from '../../../comm/utils';
 import * as md5 from 'md5';
 import { WithdrawService } from './withdraw';
-import { MchBalanceService } from './mchBalance';
+import { WalletService } from './wallet';
 
 @Provide()
 export class RepayService extends BaseService {
@@ -30,7 +30,7 @@ export class RepayService extends BaseService {
   dispatchService: DispatchService;
 
   @Inject()
-  mchBalanceService: MchBalanceService;
+  walletService: WalletService;
 
   @Logger()
   logger: ILogger;
@@ -231,8 +231,8 @@ export class RepayService extends BaseService {
   }
 
   async validBalance(merchant, data) {
-    const mchBalance = await this.mchBalanceService.queryByMerchant(merchant.mchId);
-    const { balance = 0 } = mchBalance;
+    const wallet = await this.walletService.queryByMerchant(merchant.mchId);
+    const { balance = 0 } = wallet;
     if(+data.amount > +balance) {
       throw new Error('当前商户余额不足,请确认!当前商户余额:' + balance);
     }

+ 98 - 0
src/modules/dj/service/wallet.ts

@@ -0,0 +1,98 @@
+import { Inject, Provide } from '@midwayjs/decorator';
+import { BaseService } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Equal, Repository, In } from 'typeorm';
+import * as _ from 'lodash';
+import { WalletEntity } from '../entity/wallet';
+import { BalanceEntity } from '../entity/balance';
+import { Utils } from '../../../comm/utils';
+import { MerchantEntity } from '../entity/merchant';
+import { BalanceQueue } from '../queue/balanceQueue';
+
+@Provide()
+export class WalletService extends BaseService {
+  @InjectEntityModel(WalletEntity)
+  walletEntity: Repository<WalletEntity>;
+
+  @InjectEntityModel(BalanceEntity)
+  balanceEntity: Repository<BalanceEntity>;
+
+  @InjectEntityModel(MerchantEntity)
+  merchantEntity: Repository<MerchantEntity>;
+
+  @Inject()
+  balanceQueue: BalanceQueue;
+
+  @Inject()
+  ctx;
+
+  @Inject()
+  utils: Utils;
+
+  async createWallet(mchId, currency) {
+    const data = await this.walletEntity.findOneBy({
+      mchId: mchId,
+      currency: currency,
+    });
+    if (!data) {
+      await this.walletEntity.save({
+        mchId: mchId,
+        currency: currency,
+        balance: 0,
+        freeze: 0
+      })
+    }
+  }
+
+  async page(query) {
+    let { mchId = '', currency = '' } = query;
+    const { roleIds, userId } = this.ctx.admin;
+    if (this.utils.isMerchant(roleIds)) {
+      const merchant = await this.merchantEntity.findOneBy({ userId });
+      if (merchant) {
+        mchId = merchant.mchId;
+      } else {
+        mchId = '-1';
+      }
+    }
+    const sql = `SELECT * FROM dj_wallet a WHERE 1=1
+      ${this.utils.isMerchant(roleIds)
+        ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
+        : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
+      }
+      ${this.setSql(currency, 'and a.currency like ?', [`%${currency}%`])}
+    `;
+    return this.sqlRenderPage(sql, query);
+  }
+
+  async update(param) {
+    await this.updateBalance(param);
+  }
+
+  async updateBalance(param) {
+    param.orderNo =
+      param.orderNo || this.utils.createOrderNo(this.getPrefix(param.type));
+    return new Promise(resolve => {
+      this.balanceQueue.add(param);
+      resolve(param);
+    })
+  }
+
+  getPrefix(type) {
+    if (+type === 2) {
+      return 'XF';
+    } else if (+type === 3) {
+      return 'CZ';
+    } else if (+type === 4) {
+      return 'NC';
+    } else {
+      return 'DS';
+    }
+  }
+
+  async queryByMerchant(mchId) {
+    return this.walletEntity.findOneBy({
+      mchId
+    })
+  }
+}

+ 3 - 3
src/modules/dj/service/withdraw.ts

@@ -7,7 +7,7 @@ import { WithdrawEntity } from '../entity/withdraw';
 import { DispatchService } from './channels/dispatch';
 import { CoolCommException } from '@cool-midway/core';
 import { Utils } from '../../../comm/utils';
-import { BalanceService } from './balance';
+import { WalletService } from './wallet';
 
 @Provide()
 export class WithdrawService extends BaseService {
@@ -21,7 +21,7 @@ export class WithdrawService extends BaseService {
   utils: Utils;
 
   @Inject()
-  balanceService: BalanceService;
+  walletService: WalletService;
 
   async create(withdraw: WithdrawEntity) {
     if (withdraw.id) {
@@ -90,7 +90,7 @@ export class WithdrawService extends BaseService {
     withdraw.traceNo = payload.traceNo;
     await this.withdrawEntity.update(withdraw.id, withdraw);
     if (withdraw.mchId && +withdraw.status === 1) {
-      await this.balanceService.add({
+      await this.walletService.updateBalance({
         orderNo: withdraw.orderNo,
         mchId: withdraw.mchId,
         type: 2,