lrf 3 years ago
commit
51b39961a0

+ 29 - 0
.autod.conf.js

@@ -0,0 +1,29 @@
+'use strict';
+
+module.exports = {
+  write: true,
+  prefix: '^',
+  plugin: 'autod-egg',
+  test: [
+    'test',
+    'benchmark',
+  ],
+  dep: [
+    'egg',
+    'egg-scripts',
+  ],
+  devdep: [
+    'egg-ci',
+    'egg-bin',
+    'egg-mock',
+    'autod',
+    'autod-egg',
+    'eslint',
+    'eslint-config-egg',
+  ],
+  exclude: [
+    './test/fixtures',
+    './dist',
+  ],
+};
+

+ 1 - 0
.eslintignore

@@ -0,0 +1 @@
+coverage

+ 3 - 0
.eslintrc

@@ -0,0 +1,3 @@
+{
+  "extends": "eslint-config-egg"
+}

+ 46 - 0
.github/workflows/nodejs.yml

@@ -0,0 +1,46 @@
+# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
+
+name: Node.js CI
+
+on:
+  push:
+    branches:
+      - main
+      - master
+  pull_request:
+    branches:
+      - main
+      - master
+  schedule:
+    - cron: '0 2 * * *'
+
+jobs:
+  build:
+    runs-on: ${{ matrix.os }}
+
+    strategy:
+      fail-fast: false
+      matrix:
+        node-version: [10]
+        os: [ubuntu-latest, windows-latest, macos-latest]
+
+    steps:
+    - name: Checkout Git Source
+      uses: actions/checkout@v2
+
+    - name: Use Node.js ${{ matrix.node-version }}
+      uses: actions/setup-node@v1
+      with:
+        node-version: ${{ matrix.node-version }}
+
+    - name: Install Dependencies
+      run: npm i -g npminstall && npminstall
+
+    - name: Continuous Integration
+      run: npm run ci
+
+    - name: Code Coverage
+      uses: codecov/codecov-action@v1
+      with:
+        token: ${{ secrets.CODECOV_TOKEN }}

+ 14 - 0
.gitignore

@@ -0,0 +1,14 @@
+logs/
+npm-debug.log
+yarn-error.log
+node_modules/
+package-lock.json
+yarn.lock
+coverage/
+.idea/
+run/
+.DS_Store
+*.sw*
+*.un~
+typings/
+.nyc_output/

+ 12 - 0
.travis.yml

@@ -0,0 +1,12 @@
+
+language: node_js
+node_js:
+  - '10'
+before_install:
+  - npm i npminstall -g
+install:
+  - npminstall
+script:
+  - npm run ci
+after_script:
+  - npminstall codecov && codecov

+ 33 - 0
README.md

@@ -0,0 +1,33 @@
+# server-user
+
+服务-用户管理
+
+## QuickStart
+
+<!-- add docs here for user -->
+
+see [egg docs][egg] for more detail.
+
+### Development
+
+```bash
+$ npm i
+$ npm run dev
+$ open http://localhost:7001/
+```
+
+### Deploy
+
+```bash
+$ npm start
+$ npm stop
+```
+
+### npm scripts
+
+- Use `npm run lint` to check code style.
+- Use `npm test` to run unit test.
+- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
+
+
+[egg]: https://eggjs.org

+ 17 - 0
app.js

@@ -0,0 +1,17 @@
+'use strict';
+class AppBootHook {
+  constructor(app) {
+    this.app = app;
+  }
+
+
+  async serverDidReady() {
+    // 应用已经启动完毕
+    const ctx = await this.app.createAnonymousContext();
+    // 检查种子
+    // await ctx.service.install.index();
+    // await ctx.service.util.rabbitMq.mission();
+  }
+
+}
+module.exports = AppBootHook;

+ 37 - 0
app/controller/.achievement-setting.js

@@ -0,0 +1,37 @@
+module.exports = {
+  create: {
+    requestBody: ['relation'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['relation'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        'meta.createdAt@start': 'meta.createdAt@start',
+        'meta.createdAt@end': 'meta.createdAt@end',
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: 'query',
+    options: {
+      query: ['skip', 'limit'],
+      sort: ['meta.createdAt'],
+      desc: true,
+      count: true,
+    },
+  },
+};

+ 35 - 0
app/controller/.user.js

@@ -0,0 +1,35 @@
+module.exports = {
+  // 是创建关系,正常用户信息处理都用原接口
+  create: {
+    requestBody: ['!user_id', '!superior_id'],
+  },
+  // 删除删除关系,正常用户信息处理都用原接口
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  // show: {
+  //   parameters: {
+  //     params: ['!id'],
+  //   },
+  //   service: 'fetch',
+  // },
+  index: {
+    parameters: {
+      query: {
+        'meta.createdAt@start': 'meta.createdAt@start',
+        'meta.createdAt@end': 'meta.createdAt@end',
+      },
+      // options: {
+      //   "meta.state": 0 // 默认条件
+      // },
+    },
+    service: 'query',
+    options: {
+      query: ['skip', 'limit'],
+      sort: ['meta.createdAt'],
+      desc: true,
+      count: true,
+    },
+  },
+};

+ 17 - 0
app/controller/achievement-setting.js

@@ -0,0 +1,17 @@
+'use strict';
+const meta = require('./.achievement-setting.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 绩效设置
+class AchievementSettingController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.setting;
+  }
+  async index() {
+    const data = await this.service.index();
+    this.ctx.ok({ data });
+  }
+}
+module.exports = CrudController(AchievementSettingController, meta);

+ 25 - 0
app/controller/home.js

@@ -0,0 +1,25 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+const _ = require('lodash');
+class HomeController extends Controller {
+  async index() {
+    const { ctx } = this;
+    ctx.body = 'hi, egg';
+  }
+
+
+  async util() {
+    const result = await this.ctx.service.util.index();
+    let data;
+    if (_.isArray(result)) {
+      data = { data: result };
+    } else if (_.isObject(result)) {
+      data = { ...result };
+    } else {
+      data = { data: result };
+    }
+    this.ctx.ok(data);
+  }
+}
+module.exports = CrudController(HomeController, {});

+ 18 - 0
app/controller/user.js

@@ -0,0 +1,18 @@
+'use strict';
+const meta = require('./.user.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 绩效用户相关
+class UserController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.user;
+  }
+  async index() {
+    const { skip, limit, ...query } = this.ctx.query;
+    const data = await this.service.query(query, { skip, limit });
+    this.ctx.ok({ ...data });
+  }
+}
+module.exports = CrudController(UserController, meta);

+ 53 - 0
app/middleware/request-log.js

@@ -0,0 +1,53 @@
+'use strict';
+module.exports = ({ toMongoDB = false }) =>
+  async function requestLog(ctx, next) {
+    await next();
+    try {
+      const request = ctx.request;
+      // 请求路由
+      const url = request.url;
+      // 请求方法
+      const method = request.method;
+      // get 请求不发日志
+      if (method === 'GET') return;
+      // 请求的分站标识
+      const tenant = ctx.tenant || 'master';
+      // 请求的用户
+      const user = ctx.user;
+      // 当前模块
+      const module = ctx.app.config.module;
+      // 所有的请求路由
+      const routers = ctx.router.stack;
+      // 匹配路由及http请求方法
+      const route = routers.find(route => {
+        const reg = new RegExp(route.regexp);
+        // 正则验证
+        const regResult = reg.test(url);
+        // http方法验证
+        const methodResult = route.methods.includes(method);
+        if (regResult && methodResult) return true;
+        return false;
+      });
+      if (!route) return;
+      // 不往数据库里写,就回去
+      if (!toMongoDB) return;
+      // 组织数据,给MQ,让日志服务去写
+      const { id: user_id, account, name } = user;
+      const logData = { user_id, account, name, _tenant: tenant, opera: route.name, path: url, module };
+      // 先用mq发送,不行再用http发
+      if (ctx.mq) {
+        ctx.service.util.rabbitMq.sendToMqQueue(logData, 'logs');
+      } else {
+        // http请求
+        const httpPrefix = ctx.app.config.httpPrefix;
+        if (httpPrefix && httpPrefix.logs) {
+          const uri = `${httpPrefix.logs}/logs`;
+          ctx.service.util.httpUtil.cpost(uri, logData);
+        }
+      }
+    } catch (error) {
+      // 没啥可输出,别中断就行
+    }
+
+
+  };

+ 13 - 0
app/middleware/turn-response.js

@@ -0,0 +1,13 @@
+'use strict';
+const _ = require('lodash');
+module.exports = options => {
+  return async function turnResponse(ctx, next) {
+    await next();
+    const body = ctx.response.body;
+    if (!body) return;
+    const { errcode, errmsg, ...others } = body;
+    const code = errcode === 0 ? 200 : 500;
+    const msg = errmsg === 'ok' ? '操作成功' : '操作失败';
+    ctx.response.body = { code, msg, ...others };
+  };
+};

+ 22 - 0
app/model/achievement-setting.js

@@ -0,0 +1,22 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+const relation = {
+  role: { type: String }, // 角色信息
+  level: { type: String }, // 账号等级
+};
+// 绩效设置表-关系表,只用model就行
+const achievementSetting = {
+  relation: { type: Array }, // 角色与等级关系
+  remark: { type: String },
+};
+const schema = new Schema(achievementSetting, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('AchievementSetting', schema, 'achievementSetting');
+};

+ 17 - 0
app/model/apply-update.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 绩效修改申请表
+const applyUpdate = {
+  remark: { type: String },
+};
+const schema = new Schema(applyUpdate, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('applyUpdate', schema, 'applyUpdate');
+};

+ 17 - 0
app/model/apply.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 绩效申请表
+const apply = {
+  remark: { type: String },
+};
+const schema = new Schema(apply, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Apply', schema, 'apply');
+};

+ 17 - 0
app/model/check.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 审查记录表
+const check = {
+  remark: { type: String },
+};
+const schema = new Schema(check, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Check', schema, 'check');
+};

+ 17 - 0
app/model/flow.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 绩效申请流程表
+const flow = {
+  remark: { type: String },
+};
+const schema = new Schema(flow, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Flow', schema, 'flow');
+};

+ 17 - 0
app/model/template.js

@@ -0,0 +1,17 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 模板表
+const template = {
+  remark: { type: String },
+};
+const schema = new Schema(template, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Template', schema, 'template');
+};

+ 20 - 0
app/model/user-relation.js

@@ -0,0 +1,20 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const moment = require('moment');
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 绩效:用户关系表-关系表,只用model就行
+const userRelation = {
+  user_id: { type: String }, // 用户id
+  superior_id: { type: String }, // 上级id
+  remark: { type: String },
+};
+const schema = new Schema(userRelation, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ superior_id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('UserRelation', schema, 'userRelation');
+};

+ 12 - 0
app/router.js

@@ -0,0 +1,12 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+module.exports = app => {
+  const { router, controller } = app;
+  router.get('/', controller.home.index);
+  router.post('/util', controller.home.util);
+  require('./z_router/setting')(app); // 绩效设置
+  require('./z_router/user')(app); // 用户关系
+};

+ 46 - 0
app/service/mysql.js

@@ -0,0 +1,46 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// mysql数据库操作,针对单表
+class MysqlService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'mysql');
+    this.db = this.app.mysql;
+  }
+  async create(table, data) {
+    const res = await this.db.insert(table, data);
+    return res;
+  }
+  async delete(table, query = {}) {
+    const res = await this.db.delete(table, query);
+    return res;
+  }
+  async updateById(table, id, data) {
+    const res = await this.db.update(table, { ...data, id });
+    return res;
+  }
+  async query(table, query = {}, { skip, limit, sort = [], desc } = {}) {
+    const queryParams = {};
+    if (_.isNumber(skip) || _.isNumber(parseInt(skip))) queryParams.offset = skip;
+    if (_.isNumber(limit) || _.isNumber(parseInt(limit))) queryParams.limit = limit;
+    if (sort) {
+      const orders = [];
+      for (const s of sort) {
+        const item = [ s, desc ? 'desc' : 'asc' ];
+        orders.push(item);
+      }
+    }
+    const data = await this.db.select(table, { where: query, ...queryParams });
+    const total = await this.db.count(table, query);
+    return { data, total };
+  }
+  async fetch(table, query) {
+    const data = await this.db.get(table, query);
+    return data;
+  }
+}
+
+module.exports = MysqlService;

+ 25 - 0
app/service/setting.js

@@ -0,0 +1,25 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+// 绩效设置
+class SettingService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'setting');
+    this.model = this.ctx.model.AchievementSetting;
+  }
+  /**
+   * 只有一个数据,没有就创建
+   * @return data
+   */
+  async index() {
+    let data = await this.model.findOne();
+    if (data) return data;
+    data = await this.model.create({});
+    return data;
+  }
+}
+
+module.exports = SettingService;

+ 41 - 0
app/service/user.js

@@ -0,0 +1,41 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+//
+class UserService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'user');
+    this.mysql = this.ctx.service.mysql;
+    this.userRelation = this.ctx.model.UserRelation;
+  }
+  async query({ superior_id, ...others }, { skip = 0, limit = 0 } = {}) {
+    assert(superior_id, '缺少查询信息');
+    // 通过上级id找关系
+    const relation = await this.userRelation.find({ superior_id }).skip(parseInt(skip)).limit(parseInt(limit));
+    const total = await this.userRelation.count({ superior_id });
+    // 确定好是哪些用户,然后拿id换用户信息
+    const ids = relation.map(i => i.user_id);
+    if (ids.length <= 0) return { data: [], total };
+    const table = 'sys_user';
+    let { data } = await this.mysql.query(table, { user_id: ids, ...others });
+    data = data.map(i => _.omit(i, [ 'password' ]));
+    return { data, total };
+
+  }
+
+  // 创建上下级用户关系
+  async create(body) {
+    const data = await this.userRelation.create(body);
+    return data;
+  }
+  // 删除上下级用户关系
+  async delete({ id }) {
+    const result = await this.userRelation.deleteOne({ user_id: id });
+    return result;
+  }
+}
+
+module.exports = UserService;

+ 19 - 0
app/service/util.js

@@ -0,0 +1,19 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+
+class UtilService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'util');
+  }
+  async index() {
+    // const res = await this.app.mysql.select('jcc_activities_times', {});
+    const res = await this.ctx.service.mysql.query('jcc_activities_times');
+    // const res = await this.app.mysql.insert('jcc_activities_times', { id: '123321123', title: '测试2', start_time: '2022-02-01', end_time: '2022-02-20', is_open: 0 });
+    return res;
+  }
+}
+
+module.exports = UtilService;

+ 87 - 0
app/service/util/http-util.js

@@ -0,0 +1,87 @@
+'use strict';
+const { AxiosService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const { isNullOrUndefined } = require('naf-core').Util;
+const _ = require('lodash');
+
+//
+class HttpUtilService extends AxiosService {
+  constructor(ctx) {
+    super(ctx, {}, {});
+  }
+
+
+  // 替换uri中的参数变量
+  merge(uri, query = {}) {
+    const keys = Object.keys(query);
+    const arr = [];
+    for (const k of keys) {
+      arr.push(`${k}=${query[k]}`);
+    }
+    if (arr.length > 0) {
+      uri = `${uri}?${arr.join('&')}`;
+    }
+    return uri;
+  }
+
+  /**
+   * curl-get请求
+   * @param {String} uri 接口地址
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async cget(uri, query, options) {
+    return this.toRequest(uri, null, query, options);
+  }
+
+  /**
+   * curl-post请求
+   * @param {String} uri 接口地址
+   * @param {Object} data post的body
+   * @param {Object} query 地址栏参数
+   * @param {Object} options 额外参数
+   */
+  async cpost(uri, data = {}, query, options) {
+    return this.toRequest(uri, data, query, options);
+  }
+
+  async toRequest(uri, data, query, options) {
+    query = _.pickBy(
+      query,
+      val => val !== '' && val !== 'undefined' && val !== 'null'
+    );
+    if (!uri) console.error('uri不能为空');
+    if (_.isObject(query) && _.isObject(options)) {
+      const params = query.params ? query.params : query;
+      options = { ...options, params };
+    } else if (_.isObject(query) && !query.params) {
+      options = { params: query };
+    } else if (_.isObject(query) && query.params) {
+      options = query;
+    }
+    const headers = { 'content-type': 'application/json' };
+    console.log(uri);
+    const url = this.merge(`${uri}`, options.params);
+    let res = await this.ctx.curl(url, {
+      method: isNullOrUndefined(data) ? 'get' : 'post',
+      url,
+      data,
+      dataType: 'json',
+      headers,
+      ...options,
+    });
+    if (res.status === 200) {
+      res = res.data || {};
+      const { errcode, errmsg, details } = res;
+      if (errcode) {
+        console.warn(`[${uri}] fail: ${errcode}-${errmsg} ${details}`);
+        return { errcode, errmsg };
+      }
+      return res.data;
+    }
+    const { status } = res;
+    console.warn(`[${uri}] fail: ${status}-${res.data.message} `);
+  }
+}
+
+module.exports = HttpUtilService;

+ 18 - 0
app/service/util/jwt.js

@@ -0,0 +1,18 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const jwt = require('jsonwebtoken');
+
+// jsonWebToken处理
+class JwtService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'jwt');
+  }
+
+  encrypt(data) {
+    const { secret } = this.config.jwt;
+    const token = jwt.sign(data, secret);
+    return token;
+  }
+}
+
+module.exports = JwtService;

+ 74 - 0
app/service/util/rabbitMq.js

@@ -0,0 +1,74 @@
+'use strict';
+
+const Service = require('egg').Service;
+const _ = require('lodash');
+
+class RabbitmqService extends Service {
+  // mission队列处理
+  async mission() {
+    const { mq } = this.ctx;
+    const { queue } = this.ctx.app.config;
+    if (mq && queue) {
+      const ch = await mq.conn.createChannel();
+      // const queue = 'freeAdmin/server-user';
+      try {
+        // 创建队列:在没有队列的情况,直接获取会导致程序无法启动
+        await ch.assertQueue(queue, { durable: false });
+        await ch.consume(queue, msg => this.dealMission(msg), { noAck: true });
+      } catch (error) {
+        this.ctx.logger.error('未找到订阅的队列');
+      }
+    } else {
+      this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
+    }
+  }
+  // 执行任务
+  async dealMission(bdata) {
+    //   if (!bdata) this.ctx.logger.error('mission队列中信息不存在');
+    //   let data = bdata.content.toString();
+    //   try {
+    //     data = JSON.parse(data);
+    //   } catch (error) {
+    //     this.ctx.logger.error('数据不是object');
+    //   }
+    //   const { service, method, project, ...others } = data;
+    //   const arr = service.split('.');
+    //   let s = this.ctx.service;
+    //   for (const key of arr) {
+    //     s = s[key];
+    //   }
+    //   s[method](others);
+  }
+
+  /**
+   * 发送队列消息
+   * @param {Any} data 消息队列数据
+   * @param {String} queueKey 消息队列可以
+   */
+  async sendToMqQueue(data, queueKey) {
+    const { mq } = this.ctx;
+    const { sendQueue } = this.ctx.app.config;
+    let queue;
+    // 获取队列名称
+    if (_.isObject(sendQueue)) {
+      queue = sendQueue[queueKey];
+    }
+    if (mq && queue) {
+      if (!_.isString(data)) data = JSON.stringify(data);
+      const ch = await mq.conn.createChannel();
+      try {
+        // 创建队列:在没有队列的情况,直接获取会导致程序无法启动
+        // await ch.assertQueue(queue, { durable: false });
+        await ch.sendToQueue(queue, Buffer.from(data));
+        await ch.close();
+      } catch (error) {
+        console.error(error);
+        this.ctx.logger.error('mq消息发送失败');
+      }
+    } else {
+      this.ctx.logger.error('!!!!!!没有配置MQ插件!!!!!!');
+    }
+  }
+}
+
+module.exports = RabbitmqService;

+ 24 - 0
app/z_router/setting.js

@@ -0,0 +1,24 @@
+'use strict';
+// 路由配置
+const routes = [
+  { method: 'get', path: '/setting', controller: 'achievementSetting.index', name: 'settingQuery', zh: '绩效设置列表查询' },
+  { method: 'post', path: '/setting', controller: 'achievementSetting.create', name: 'settingCreate', zh: '创建绩效设置' },
+  { method: 'post', path: '/setting/:id', controller: 'achievementSetting.update', name: 'settingUpdate', zh: '修改绩效设置' },
+  // { method: 'delete', path: '/setting/:id', controller: 'achievementSetting.destroy', name: 'settingDelete', zh: '删除绩效设置' },
+];
+
+module.exports = app => {
+  const { router, config } = app;
+  const mwares = app.middleware;
+  for (const route of routes) {
+    const { method, path, controller: ctl, zh } = route;
+    let { middleware = [] } = route;
+    if (!method || !path || !ctl) continue;
+    // 拼全路径
+    const allPath = `${config.routePrefix}${path}`;
+    // 处理中间件
+    if (middleware.length > 0) middleware = middleware.map(i => mwares[i]());
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 25 - 0
app/z_router/user.js

@@ -0,0 +1,25 @@
+'use strict';
+// 路由配置
+const routes = [
+  { method: 'get', path: '/user', controller: 'user.index', name: 'userQuery', zh: '用户关系列表查询' },
+  // { method: 'get', path: '/user/:id', controller: 'user.show', name: 'userShow', zh: '用户查询' },
+  { method: 'post', path: '/user', controller: 'user.create', name: 'userCreate', zh: '创建用户关系' },
+  // { method: 'post', path: '/user/:id', controller: 'user.update', middleware: [ 'password' ], name: 'userQuery', zh: '修改用户' },
+  { method: 'delete', path: '/user/:id', controller: 'user.destroy', name: 'userDelete', zh: '删除用户关系' },
+];
+
+module.exports = app => {
+  const { router, config } = app;
+  const mwares = app.middleware;
+  for (const route of routes) {
+    const { method, path, controller: ctl, zh } = route;
+    let { middleware = [] } = route;
+    if (!method || !path || !ctl) continue;
+    // 拼全路径
+    const allPath = `${config.routePrefix}${path}`;
+    // 处理中间件
+    if (middleware.length > 0) middleware = middleware.map(i => mwares[i]());
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 14 - 0
appveyor.yml

@@ -0,0 +1,14 @@
+environment:
+  matrix:
+    - nodejs_version: '10'
+
+install:
+  - ps: Install-Product node $env:nodejs_version
+  - npm i npminstall && node_modules\.bin\npminstall
+
+test_script:
+  - node --version
+  - npm --version
+  - npm run test
+
+build: off

+ 105 - 0
config/config.default.js

@@ -0,0 +1,105 @@
+/* eslint valid-jsdoc: "off" */
+
+'use strict';
+
+/**
+ * @param {Egg.EggAppInfo} appInfo app info
+ */
+const { jwt } = require('./config.secret');
+module.exports = appInfo => {
+  /**
+   * built-in config
+   * @type {Egg.EggAppConfig}
+   **/
+  const config = (exports = {});
+
+  // use for cookie sign key, should change to your own and keep security
+  config.keys = appInfo.name + '_1640765284662_2781';
+
+  // add your middleware config here
+  config.middleware = [ 'turnResponse' ];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+  // 日志
+  config.logger = {
+    level: 'DEBUG',
+    allowDebugAtProd: true,
+  };
+  // 发送队列名称
+  // config.sendQueue = {
+  //   logs: 'freeAdmin/server-logs',
+  // };
+  // http请求前缀
+  config.httpPrefix = {
+    logs: 'http://localhost:13002/freeAdminLog/api',
+  };
+  // redis设置
+  // config.redis = {
+  //   client: {
+  //     port: 6379, // Redis port
+  //     host: '127.0.0.1', // Redis host
+  //     password: '123456',
+  //     db: 0,
+  //   },
+  // };
+  // 进程设置
+  config.cluster = {
+    listen: {
+      port: 13001,
+    },
+  };
+
+  // jwt设置
+  config.jwt = {
+    ...jwt,
+    expiresIn: '1d',
+    issuer: 'lab',
+  };
+
+  // 数据库设置
+  config.dbName = 'label-achievement';
+  config.mongoose = {
+    url: `mongodb://localhost:27017/${config.dbName}`,
+    options: {
+      user: 'admin',
+      pass: 'admin',
+      authSource: 'admin',
+      useNewUrlParser: true,
+      useCreateIndex: true,
+    },
+  };
+  // mysql
+  config.mysql = {
+    client: {
+      // host
+      host: 'localhost',
+      // 端口号
+      port: '3307',
+      // 用户名
+      user: 'root',
+      // 密码
+      password: 'root',
+      // 数据库名
+      database: 'management_platform',
+    },
+    // 是否加载到 app 上,默认开启
+    app: true,
+    // 是否加载到 agent 上,默认关闭
+    agent: false,
+  };
+
+  // 路由设置
+  config.routePrefix = '/labelAchievement/api';
+
+  // 中间件
+  config.requestLog = {
+    toMongoDB: true,
+  };
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 7 - 0
config/config.secret.js

@@ -0,0 +1,7 @@
+'use strict';
+
+module.exports = {
+  jwt: {
+    secret: 'Ziyouyanfa!@#',
+  },
+};

+ 16 - 0
config/plugin.js

@@ -0,0 +1,16 @@
+'use strict';
+// rabbitMq
+// exports.amqp = {
+//   enable: true,
+//   package: 'egg-naf-amqp',
+// };
+// redis
+// exports.redis = {
+//   enable: true,
+//   package: 'egg-redis',
+// };
+
+exports.mysql = {
+  enable: true,
+  package: 'egg-mysql',
+};

+ 53 - 0
package.json

@@ -0,0 +1,53 @@
+{
+  "name": "server-user",
+  "version": "1.0.0",
+  "description": "服务-用户管理",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose-free"
+  },
+  "dependencies": {
+    "egg": "^2.15.1",
+    "egg-mysql": "^3.0.0",
+    "egg-naf-amqp": "0.0.13",
+    "egg-redis": "^2.4.0",
+    "egg-scripts": "^2.11.0",
+    "lodash": "^4.17.21",
+    "moment": "^2.29.1",
+    "naf-framework-mongoose-free": "^0.0.13"
+  },
+  "devDependencies": {
+    "autod": "^3.0.1",
+    "autod-egg": "^1.1.0",
+    "egg-bin": "^4.11.0",
+    "egg-ci": "^1.11.0",
+    "egg-mock": "^3.21.0",
+    "eslint": "^5.13.0",
+    "eslint-config-egg": "^7.1.0",
+    "jsonwebtoken": "^8.5.1"
+  },
+  "engines": {
+    "node": ">=10.0.0"
+  },
+  "scripts": {
+    "start": "egg-scripts start --daemon --title=egg-server-server-user",
+    "stop": "egg-scripts stop --title=egg-server-server-user",
+    "dev": "egg-bin dev",
+    "debug": "egg-bin debug",
+    "test": "npm run lint -- --fix && npm run test-local",
+    "test-local": "egg-bin test",
+    "cov": "egg-bin cov",
+    "lint": "eslint .",
+    "ci": "npm run lint && npm run cov",
+    "autod": "autod"
+  },
+  "ci": {
+    "version": "10"
+  },
+  "repository": {
+    "type": "git",
+    "url": ""
+  },
+  "author": "lrf",
+  "license": "MIT"
+}

+ 20 - 0
test/app/controller/home.test.js

@@ -0,0 +1,20 @@
+'use strict';
+
+const { app, assert } = require('egg-mock/bootstrap');
+
+describe('test/app/controller/home.test.js', () => {
+  it('should assert', () => {
+    const pkg = require('../../../package.json');
+    assert(app.config.keys.startsWith(pkg.name));
+
+    // const ctx = app.mockContext({});
+    // yield ctx.service.xx();
+  });
+
+  it('should GET /', () => {
+    return app.httpRequest()
+      .get('/')
+      .expect('hi, egg')
+      .expect(200);
+  });
+});