test há 8 meses atrás
pai
commit
b33687cf2b

+ 4 - 0
src/comm/utils.ts

@@ -190,6 +190,10 @@ export class Utils {
     return roleIds.findIndex(item => +item === 2) > -1;
   }
 
+  isAgent(roleIds) {
+    return roleIds.findIndex(item => +item === 4) > -1;
+  }
+
   stringToHex(str) {
     let hex = '';
     for (let i = 0; i < str.length; i++) {

+ 1 - 0
src/modules/base/service/sys/department.ts

@@ -39,6 +39,7 @@ export class BaseSysDepartmentService extends BaseService {
 
     // 过滤部门权限
     const find = this.baseSysDepartmentEntity.createQueryBuilder('a');
+    find.andWhere('a.id != 2 && a.id != 3')
     if (this.ctx.admin.username !== 'admin')
       find.andWhere('a.id in (:...ids)', {
         ids: !_.isEmpty(permsDepartmentArr) ? permsDepartmentArr : [null],

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

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

+ 22 - 0
src/modules/dj/controller/admin/agentOrder.ts

@@ -0,0 +1,22 @@
+import { Inject, Post, Provide } from '@midwayjs/decorator';
+import { CoolController, BaseController } from '@cool-midway/core';
+import { OrderEntity } from '../../entity/order';
+import { AgentOrderService } from '../../service/agentOrder';
+
+@Provide()
+@CoolController({
+  api: ['page'],
+  entity: OrderEntity,
+  service: AgentOrderService,
+})
+export class AgentOrderController extends BaseController {
+
+  @Inject()
+  agentOrderService: AgentOrderService;
+
+  @Post('/summary', { summary: '统计' })
+  async summary() {
+    const { body } = this.baseCtx.request;
+    return this.ok(await this.agentOrderService.summary(body));
+  }
+}

+ 4 - 4
src/modules/dj/controller/admin/comm.ts

@@ -1,6 +1,6 @@
 import { Inject, Post, Provide, Body, ALL } from '@midwayjs/decorator';
 import { CoolController, BaseController } from '@cool-midway/core';
-import { OrderService } from '../../service/order';
+import { DashboardService } from '../../service/dashboard';
 import { BaseSysConfService } from '../../../base/service/sys/conf';
 import { CurrencyService } from '../../service/currency';
 import { MerchantService } from '../../service/merchant';
@@ -12,7 +12,7 @@ import { WithdrawChannelService } from '../../service/withdrawChannel';
 @CoolController()
 export class OrdertController extends BaseController {
   @Inject()
-  orderService: OrderService;
+  dashboardService: DashboardService;
 
   @Inject()
   currencyService: CurrencyService;
@@ -34,13 +34,13 @@ export class OrdertController extends BaseController {
 
   @Post('/dashboard', { summary: '统计' })
   async dashboard(@Body(ALL) payload: any) {
-    return this.ok(await this.orderService.dashboard(payload));
+    return this.ok(await this.dashboardService.dashboard(payload));
   }
 
 
   @Post('/chartData', { summary: '报表' })
   async chartData(@Body(ALL) payload: any) {
-    return this.ok(await this.orderService.chartData(payload));
+    return this.ok(await this.dashboardService.chartData(payload));
   }
 
   @Post('/getCurrency', { summary: '货币列表' })

+ 24 - 0
src/modules/dj/entity/agent.ts

@@ -0,0 +1,24 @@
+import { BaseEntity } from '@cool-midway/core';
+import { Column, Entity, Index } from 'typeorm';
+
+/**
+ * 描述
+ */
+@Entity('dj_agent')
+export class AgentEntity extends BaseEntity {
+  @Column({ comment: '系统用户Id' })
+  userId: string;
+
+  @Column({ comment: '名称' })
+  name: string;
+
+  @Index({ unique: true })
+  @Column({ comment: '登录账号' })
+  username: string;
+
+  @Column({ comment: '状态 0-禁用 1-启用', default: 1 })
+  status: number;
+
+  @Column({ comment: '备注', nullable: true })
+  remark: string;
+}

+ 14 - 0
src/modules/dj/entity/agentMerchant.ts

@@ -0,0 +1,14 @@
+import { BaseEntity } from '@cool-midway/core';
+import { Column, Entity, Index } from 'typeorm';
+
+/**
+ * 描述
+ */
+@Entity('dj_agent_mch')
+export class AgentMerchantEntity extends BaseEntity {
+  @Column({ comment: '代理ID' })
+  agentId: string;
+
+  @Column({ comment: '商户号' })
+  mchId: string;
+}

+ 135 - 0
src/modules/dj/service/agent.ts

@@ -0,0 +1,135 @@
+import { Inject, Provide } from '@midwayjs/decorator';
+import { BaseService, CoolCommException } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository, In } from 'typeorm';
+import * as _ from 'lodash';
+import { AgentEntity } from '../entity/agent';
+import { BaseSysUserEntity } from '../../base/entity/sys/user';
+import { BaseSysUserService } from '../../base/service/sys/user';
+import { AgentMerchantEntity } from '../entity/agentMerchant';
+
+@Provide()
+export class AgentService extends BaseService {
+
+  @InjectEntityModel(AgentEntity)
+  agentEntity: Repository<AgentEntity>;
+
+  @InjectEntityModel(AgentMerchantEntity)
+  agentMerchantEntity: Repository<AgentMerchantEntity>;
+
+  @InjectEntityModel(BaseSysUserEntity)
+  baseSysUserEntity: Repository<BaseSysUserEntity>;
+
+  @Inject()
+  baseSysUserService: BaseSysUserService;
+
+  async page(query) {
+    let { keyWord = '' } = query;
+    const sql = `SELECT * FROM dj_agent a WHERE 1=1
+      ${this.setSql(keyWord, 'and a.name like ?', [`%${keyWord}%`])}
+      ${this.setSql(keyWord, 'and a.username like ?', [`%${keyWord}%`])}
+    `;
+    const result = await this.sqlRenderPage(sql, query);
+    // 匹配角色
+    if (!_.isEmpty(result.list)) {
+      const agentIds = result.list.map(e => e.id);
+      const mchIds = await this.nativeQuery(
+        'SELECT a.agentId, a.mchId FROM dj_agent_mch a WHERE a.agentId in (?) ',
+        [agentIds]
+      );
+      result.list.forEach(e => {
+        e['mchIds'] = mchIds
+          .filter(mch => mch.agentId == e.id)
+          .map(mch => mch.mchId)
+      });
+    }
+    return result;
+  }
+
+  public async info(id) {
+    const info = await this.agentEntity.findOneBy({ id });
+    const mchIds = await this.nativeQuery(
+      'select a.mchId from dj_agent_mch a where a.agentId = ?',
+      [id]
+    );
+    if (mchIds) {
+      info['mchIds'] = mchIds.map(e => {
+        return e.mchId
+      });
+    }
+    return info;
+  }
+
+  async add(param) {
+    const exists = await this.baseSysUserEntity.findOneBy({
+      username: param.username,
+    });
+    if (!_.isEmpty(exists)) {
+      throw new CoolCommException('该登录号不能使用~');
+    }
+
+    const userId = await this.baseSysUserService.add({
+      name: param.name,
+      nickName: param.name,
+      username: param.username,
+      password: param.password,
+      roleIdList: [4],
+      status: param.status,
+      departmentId: 3,
+    });
+
+    const newAgent = await this.agentEntity.save({
+      ...param,
+      userId,
+    });
+
+    await Promise.all(
+      param.mchIds.map(async e => {
+        return await this.agentMerchantEntity.save({
+          agentId: newAgent.id,
+          mchId: e,
+        });
+      })
+    );
+
+    return param.id;
+  }
+
+  async update(param) {
+    await this.agentEntity.save(param);
+    const user = await this.baseSysUserEntity.findOneBy({ id: param.userId });
+    await this.baseSysUserService.update({
+      ...user,
+      name: param.name,
+      nickName: param.name,
+      username: param.username,
+      password: param.password,
+      status: param.status,
+    });
+    await this.agentMerchantEntity.delete({
+      agentId: param.id
+    })
+    await Promise.all(
+      param.mchIds.map(async e => {
+        return await this.agentMerchantEntity.save({
+          agentId: param.id,
+          mchId: e,
+        });
+      })
+    );
+  }
+
+  async delete(ids) {
+    const merchants = await this.agentEntity.findBy({
+      id: In(ids),
+    });
+    await this.agentEntity.delete(ids);
+    await this.baseSysUserEntity.delete({
+      id: In(merchants.map(item => item.userId)),
+    });
+    await this.agentMerchantEntity.delete({
+      agentId: In(ids)
+    })
+  }
+
+}

+ 145 - 0
src/modules/dj/service/agentOrder.ts

@@ -0,0 +1,145 @@
+import { Inject, Provide } from '@midwayjs/decorator';
+import { BaseService, CoolCommException } from '@cool-midway/core';
+import { InjectEntityModel } from '@midwayjs/typeorm';
+import { Repository } from 'typeorm';
+import * as _ from 'lodash';
+import { AgentMerchantEntity } from '../entity/agentMerchant';
+import * as moment from 'moment';
+import { AgentEntity } from '../entity/agent';
+
+@Provide()
+export class AgentOrderService extends BaseService {
+
+  @InjectEntityModel(AgentEntity)
+  agentEntity: Repository<AgentEntity>;
+
+
+  @InjectEntityModel(AgentMerchantEntity)
+  agentMerchantEntity: Repository<AgentMerchantEntity>;
+
+  @Inject()
+  ctx;
+
+  async summary(query) {
+    let {
+      orderNo = '',
+      outOrderNo = '',
+      mchId = '',
+      payType = '',
+      status = '',
+      createTime = [],
+    } = query;
+    if (!createTime || createTime.length !== 2) {
+      return {
+        num1: 0,
+        num2: 0,
+        num3: 0,
+        num4: 0,
+        num5: 0,
+      };
+    }
+    if (moment(createTime[1]).diff(moment(createTime[0]), 'days') > 30) {
+      return {
+        num1: 0,
+        num2: 0,
+        num3: 0,
+        num4: 0,
+        num5: 0,
+      };
+    }
+    const { userId } = this.ctx.admin;
+    const agent = await this.agentEntity.findOne({
+      where: {
+        userId: userId
+      }
+    })
+    if (!agent) {
+      return {
+        num1: 0,
+        num2: 0,
+        num3: 0,
+        num4: 0,
+        num5: 0,
+      };
+    }
+    const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
+    let mchIds = agentMchs.map(item => {
+      return "'" + item.mchId + "'";
+    })
+    if (!mchIds || mchIds.length === 0) {
+      return {
+        num1: 0,
+        num2: 0,
+        num3: 0,
+        num4: 0,
+        num5: 0,
+      };
+    }
+    const sql = `SELECT 
+    SUM(IF(a.status = 1, a.amount, 0)) as num1,
+    SUM(IF(a.status = 1, a.charge, 0)) as num2,
+    SUM(IF(a.status = 1, 1, 0)) as num3,
+    count(*) as num4
+    FROM dj_order a WHERE 1=1
+    and a.mchId in (${mchIds.join(',')})
+    ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
+    ${this.setSql(outOrderNo, 'and a.outOrderNo like ?', [`%${outOrderNo}%`])}
+    ${this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])}
+    ${this.setSql(payType, 'and a.payType = ?', [payType])}
+    ${this.setSql(status, 'and a.status = ?', [status])}
+    ${this.setSql(
+      createTime && createTime.length === 2,
+      'and (a.createTime between ? and ?)',
+      createTime
+    )}
+    `;
+    return this.nativeQuery(sql);
+  }
+
+  async page(query) {
+    let {
+      orderNo = '',
+      outOrderNo = '',
+      mchId = '',
+      payType = '',
+      status = '',
+      createTime = [],
+    } = query;
+    if (!createTime || createTime.length !== 2) {
+      throw new CoolCommException('请选择日期范围');
+    }
+    if (moment(createTime[1]).diff(moment(createTime[0]), 'days') > 30) {
+      throw new CoolCommException('日期范围最大只能30天');
+    }
+    const { userId } = this.ctx.admin;
+    const agent = await this.agentEntity.findOne({
+      where: {
+        userId: userId
+      }
+    })
+    if (!agent) {
+      return []
+    }
+    const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
+    const mchIds = agentMchs.map(item => {
+      return "'" + item.mchId + "'";
+    })
+    if (!mchIds || mchIds.length === 0) {
+      return [];
+    }
+    const sql = `SELECT a.id, a.orderNo, a.outOrderNo, a.mchId, a.payType, a.amount, a.charge, a.status, a.currency, a.remark, a.createTime FROM dj_order a WHERE 1=1
+      and a.mchId in (${mchIds.join(',')})
+      ${this.setSql(orderNo, 'and a.orderNo like ?', [`%${orderNo}%`])}
+      ${this.setSql(outOrderNo, 'and a.outOrderNo like ?', [`%${outOrderNo}%`])}
+      ${this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])}
+      ${this.setSql(payType, 'and a.payType = ?', [payType])}
+      ${this.setSql(status, 'and a.status = ?', [status])}
+      ${this.setSql(
+      createTime && createTime.length === 2,
+      'and (a.createTime between ? and ?)',
+      createTime
+    )}
+    `;
+    return this.sqlRenderPage(sql, query);
+  }
+}

+ 154 - 0
src/modules/dj/service/dashboard.ts

@@ -0,0 +1,154 @@
+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 * as moment from 'moment';
+import { MerchantEntity } from '../entity/merchant';
+import { Utils } from '../../../comm/utils';
+import { AgentEntity } from '../entity/agent';
+import { AgentMerchantEntity } from '../entity/agentMerchant';
+
+@Provide()
+export class DashboardService extends BaseService {
+  @InjectEntityModel(MerchantEntity)
+  merchantEntity: Repository<MerchantEntity>;
+
+  @InjectEntityModel(AgentEntity)
+  agentEntity: Repository<AgentEntity>;
+
+  @InjectEntityModel(AgentMerchantEntity)
+  agentMerchantEntity: Repository<AgentMerchantEntity>;
+
+  @Inject()
+  ctx;
+
+  @Inject()
+  utils: Utils;
+
+  async dashboard(query) {
+    let { mchId = '' } = query;
+    let mchIds = [];
+    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';
+      }
+    } else if (this.utils.isAgent(roleIds)) {
+      const agent = await this.agentEntity.findOne({
+        where: {
+          userId: userId
+        }
+      })
+      const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
+      mchIds = agentMchs.map(item => {
+        return "'" + item.mchId + "'";
+      })
+      if (mchIds.length === 0) {
+        mchIds = ["'-1'"]
+      }
+    }
+    const todayTime = [
+      moment().format('YYYY-MM-DD') + ' 00:00:00',
+      moment().format('YYYY-MM-DD') + ' 23:59:59',
+    ];
+    const data = await Promise.all(
+      [todayTime].map(item => {
+        return this.nativeQuery(
+          `SELECT 
+        count(*) as num1,
+        SUM(IF(a.status = 1, 1, 0)) as num2,
+        SUM(IF(a.status = 1, a.amount, 0)) as num3
+        FROM dj_order a WHERE 1=1
+        ${this.utils.isMerchant(roleIds)
+            ? this.setSql(mchId, 'and a.mchId = ?', [`${mchId}`])
+            : this.setSql(mchId, 'and a.mchId like ?', [`%${mchId}%`])
+          }
+        ${mchIds.length > 0 ? `and a.mchId in (${mchIds.join(',')})` : ''}
+        ${this.setSql(true, 'and (a.createTime between ? and ?)', item)}
+      `
+        );
+      })
+    );
+    return data.map(item => {
+      return item[0];
+    });
+  }
+
+  async chartData(query) {
+    let { mchId = '', date = [], dateType = '1d', type = '0' } = query;
+    let mchIds = [];
+    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';
+      }
+    } else if (this.utils.isAgent(roleIds)) {
+      const agent = await this.agentEntity.findOne({
+        where: {
+          userId: userId
+        }
+      })
+      const agentMchs = await this.agentMerchantEntity.findBy({ agentId: agent.id + '' })
+      mchIds = agentMchs.map(item => {
+        return "'" + item.mchId + "'";
+      })
+      if (mchIds.length === 0) {
+        mchIds = ["'-1'"]
+      }
+    }
+
+    let sql = 'SELECT ';
+    switch (dateType) {
+      case '1m':
+        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 60) * 60) AS time, '
+        break;
+      case '5m':
+        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 300) * 300) AS time, '
+        break;
+      case '10m':
+        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 300) * 300) AS time, '
+        break;
+      case '1h':
+        sql += `DATE_FORMAT(createTime, '%Y-%m-%d %H:00:00') AS time, `
+        break;
+      default:
+        sql += 'DATE(createTime) as time, '
+        break;
+    }
+    switch (type) {
+      case '1':
+        sql += 'SUM(IF(status=1, 1, 0)) as num '
+        break;
+      case '2':
+        sql += 'SUM(IF(status=1, amount, 0)) as num '
+        break;
+      case '3':
+        sql += 'sum(1) as num, SUM(IF(status=1, 1, 0)) as num1 '
+        break;
+      default:
+        sql += 'sum(1) as num '
+        break;
+    }
+
+    sql += `FROM dj_order WHERE 1=1
+    ${this.utils.isMerchant(roleIds)
+        ? this.setSql(mchId, ' and mchId = ?', [`${mchId}`])
+        : this.setSql(mchId, ' and mchId like ?', [`%${mchId}%`])
+      }
+      ${mchIds.length > 0 ? `and mchId in (${mchIds.join(',')})` : ''}
+    ${this.setSql(
+        date && date.length === 2,
+        ' and (createTime between ? and ?)',
+        date
+      )}
+     GROUP BY time ORDER BY time`
+    return this.nativeQuery(sql);
+  }
+}

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

@@ -140,104 +140,6 @@ export class OrderService extends BaseService {
     return await this.orderEntity.findOneBy({ orderNo: orderNo });
   }
 
-  async dashboard(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 todayTime = [
-      moment().format('YYYY-MM-DD') + ' 00:00:00',
-      moment().format('YYYY-MM-DD') + ' 23:59:59',
-    ];
-    const data = await Promise.all(
-      [todayTime].map(item => {
-        return this.nativeQuery(
-          `SELECT 
-        count(*) as num1,
-        SUM(IF(a.status = 1, 1, 0)) as num2,
-        SUM(IF(a.status = 1, a.amount, 0)) as num3
-        FROM dj_order 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(true, 'and (a.createTime between ? and ?)', item)}
-      `
-        );
-      })
-    );
-    return data.map(item => {
-      return item[0];
-    });
-  }
-
-  async chartData(query) {
-    let { mchId = '', date = [], dateType = '1d', type = '0' } = 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';
-      }
-    }
-
-    let sql = 'SELECT ';
-    switch (dateType) {
-      case '1m':
-        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 60) * 60) AS time, '
-        break;
-      case '5m':
-        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 300) * 300) AS time, '
-        break;
-      case '10m':
-        sql += 'FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(createTime) / 300) * 300) AS time, '
-        break;
-      case '1h':
-        sql += `DATE_FORMAT(createTime, '%Y-%m-%d %H:00:00') AS time, `
-        break;
-      default:
-        sql += 'DATE(createTime) as time, '
-        break;
-    }
-    switch (type) {
-      case '1':
-        sql += 'SUM(IF(status=1, 1, 0)) as num '
-        break;
-      case '2':
-        sql += 'SUM(IF(status=1, amount, 0)) as num '
-        break;
-      case '3':
-        sql += 'sum(1) as num, SUM(IF(status=1, 1, 0)) as num1 '
-        break;
-      default:
-        sql += 'sum(1) as num '
-        break;
-    }
-
-    sql += `FROM dj_order WHERE 1=1
-    ${
-      this.utils.isMerchant(roleIds)
-        ? this.setSql(mchId, ' and mchId = ?', [`${mchId}`])
-        : this.setSql(mchId, ' and mchId like ?', [`%${mchId}%`])
-    }
-    ${this.setSql(
-      date && date.length === 2,
-      ' and (createTime between ? and ?)',
-      date
-    )}
-     GROUP BY time ORDER BY time`
-     return this.nativeQuery(sql);
-  }
-
   async summary(query) {
     let {
       orderNo = '',