lrf 2 éve
commit
b75373bd48

+ 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

+ 363 - 0
app.js

@@ -0,0 +1,363 @@
+'use strict';
+const _ = require('lodash');
+const colors = require('colors');
+class AppBootHook {
+  constructor(app) {
+    this.app = app;
+  }
+
+  async willReady() {
+    // await this.initAdmin();
+    // await this.initMenu();
+  }
+
+  async serverDidReady() {
+    // 应用已经启动完毕
+    const ctx = await this.app.createAnonymousContext();
+    ctx.service.util.install.init();
+    // await this.initAdmin(ctx);
+    // await this.initMenu(ctx);
+    // await this.initRole(ctx);
+    // 检查种子
+    // await ctx.service.install.index();
+    // await ctx.service.util.rabbitMq.mission();
+  }
+
+
+  async initRole(ctx) {
+    console.log('开始=>初始化角色'.blue);
+    const data = await ctx.model.Role.findOne();
+    if (!data) {
+      // 没有管理员,初始化一个
+      const data = {
+        default: true,
+        _tenant: 'master',
+        name: '管理员角色',
+      };
+      console.log('正在初始化角色'.blue);
+      await ctx.model.Role.create(data);
+      console.log('初始化角色=>结束'.green);
+    } else console.log('无需再次初始化角色'.yellow);
+  }
+
+  async initMenu(ctx) {
+    console.log('开始=>初始化总管理员菜单'.blue);
+    const data = await ctx.model.Menu.count();
+    if (data <= 0) {
+      console.log('正在初始化总管理员菜单'.blue);
+      console.log(colors.bgBlue.italic('菜单=>初始化 首页'));
+      // 首页初始化
+      const indexPage = {
+        name: '首页',
+        icon: 'icon-shouye',
+        order_num: 1,
+        path: '/admin/homeIndex',
+        status: '0',
+        type: '1',
+        no_delete: true,
+        _tenant: 'master',
+      };
+      await ctx.model.Menu.create(indexPage);
+      console.log(colors.bgGreen.italic('菜单=>初始化 首页'));
+
+      console.log(colors.bgBlue.italic('菜单=>初始化 系统菜单'));
+      // 系统菜单初始化
+      const sys = {
+        name: '系统设置',
+        icon: 'icon-shouye',
+        order_num: 2,
+        type: '0',
+        status: '0',
+        no_delete: true,
+        _tenant: 'master',
+      };
+      const sysData = await ctx.model.Menu.create(sys);
+      let sys_id = _.get(sysData, '_id');
+      if (sys_id) sys_id = JSON.parse(JSON.stringify(sys_id));
+      console.log(colors.bgBlue.italic('菜单=>系统菜单=>初始化 菜单管理'));
+      // 系统-菜单管理
+      const sys_menu = {
+        name: '菜单设置',
+        icon: 'icon-shouye',
+        order_num: 1,
+        parent_id: sys_id,
+        path: '/admin/menu',
+        status: '0',
+        type: '1',
+        no_delete: true,
+        _tenant: 'master',
+      };
+      await ctx.model.Menu.create(sys_menu);
+      console.log(colors.bgGreen.italic('菜单=>系统菜单=>初始化 菜单管理'));
+      console.log(colors.bgBlue.italic('菜单=>系统菜单=>初始化 角色管理'));
+      // 系统-角色
+      const sys_role = {
+        name: '角色管理',
+        icon: 'icon-shouye',
+        order_num: 2,
+        parent_id: sys_id,
+        path: '/admin/role',
+        status: '0',
+        type: '1',
+        no_delete: true,
+        _tenant: 'master',
+      };
+      const sr = await ctx.model.Menu.create(sys_role);
+      let role_id = _.get(sr, '_id');
+      if (role_id) role_id = JSON.parse(JSON.stringify(role_id));
+      const sys_role_child = {
+        status: '0',
+        icon: 'icon-shouye',
+        name: '角色信息',
+        parent_id: role_id,
+        path: '/admin/role/detail',
+        type: '2',
+        config: {
+          api: [],
+          table_btn: [],
+          btn_area: [],
+        },
+        no_delete: true,
+        _tenant: 'master',
+      };
+      await ctx.model.Menu.create(sys_role_child);
+      console.log(colors.bgGreen.italic('菜单=>系统菜单=>初始化 角色管理'));
+
+      console.log(colors.bgBlue.italic('菜单=>系统菜单=>初始化 分站管理'));
+      // 系统-分站
+      const sys_tenant = {
+        status: '0',
+        icon: 'icon-shouye',
+        no_delete: true,
+        _tenant: 'master',
+        page_type: 'list',
+        name: '分站管理',
+        parent_id: sys_id,
+        order_num: 3,
+        path: '/list/v1/tenant',
+        type: '1',
+        config: {
+          api: [
+            {
+              is_use: true,
+              module: 'tenant',
+              func: 'query',
+              opera: 'search',
+              desc: '查询列表',
+            },
+            {
+              is_use: true,
+              module: 'tenant',
+              func: 'delete',
+              opera: 'delete',
+              desc: '删除',
+            },
+          ],
+          table_btn: [
+            {
+              confirm: false,
+              label: '修改',
+              type: 'primary',
+              api: 'writeBySelf',
+              selfFunction: '(i)=>this.$router.push({name:"v1_detail",params:{service:this.service},query:{id:i._id}})',
+            },
+            {
+              confirm: false,
+              label: '删除',
+              type: 'danger',
+              api: 'delete',
+            },
+          ],
+          btn_area: [
+            {
+              label: '添加',
+              type: 'primary',
+              api: 'writeBySelf',
+              selfFunction: '(i)=>this.$router.push({name:"v1_detail",params:{service:this.service}})',
+              confirm: false,
+            },
+          ],
+        },
+      };
+      const st = await ctx.model.Menu.create(sys_tenant);
+      let tenant_id = _.get(st, '_id');
+      if (tenant_id) tenant_id = JSON.parse(JSON.stringify(tenant_id));
+      const sys_tenant_child = {
+        status: '0',
+        icon: 'icon-shouye',
+        no_delete: true,
+        _tenant: 'master',
+        page_type: 'detail',
+        name: '分站编辑',
+        parent_id: tenant_id,
+        path: '/detail/v1/tenant',
+        type: '2',
+        config: {
+          api: [
+            {
+              is_use: true,
+              module: 'tenant',
+              func: 'fetch',
+              opera: 'search',
+              desc: '查询',
+            },
+            {
+              is_use: true,
+              module: 'tenant',
+              func: 'create',
+              opera: 'create',
+              desc: '创建',
+            },
+            {
+              is_use: true,
+              module: 'tenant',
+              func: 'update',
+              opera: 'update',
+              desc: '修改',
+            },
+          ],
+          table_btn: [],
+          btn_area: [],
+        },
+      };
+      await ctx.model.Menu.create(sys_tenant_child);
+      console.log(colors.bgGreen.italic('菜单=>系统菜单=>初始化 分站管理'));
+      console.log(colors.bgBlue.italic('菜单=>系统菜单=>初始化 管理员管理'));
+      // 系统-管理员
+      const sys_admin = {
+        status: '0',
+        icon: 'icon-shouye',
+        no_delete: true,
+        _tenant: 'master',
+        name: '管理员用户',
+        parent_id: sys_id,
+        order_num: 4,
+        path: '/list/v1/admin',
+        type: '1',
+        __v: 0,
+        config: {
+          api: [
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'query',
+              opera: 'search',
+              desc: '查询列表',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'create',
+              opera: 'create',
+              desc: '创建',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'update',
+              opera: 'update',
+              desc: '修改',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'delete',
+              opera: 'toDelete',
+              desc: '删除',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'fetch',
+              opera: 'toFetch',
+              desc: '单项数据查询',
+            },
+          ],
+          table_btn: [
+            {
+              confirm: false,
+              label: '修改',
+              type: 'primary',
+              api: 'writeBySelf',
+              methodZh: '',
+              display: '',
+              selfFunction: '(i)=>this.$router.push({name:"v1_detail", query:{id:i._id},params:{service:this.service}})',
+            },
+            {
+              confirm: true,
+              label: '删除',
+              type: 'danger',
+              api: 'toDelete',
+              display: '(i)=>i.is_super !== true',
+              methodZh: '确认是否删除该用户',
+            },
+            {
+              confirm: false,
+              label: '查看',
+              type: 'primary',
+              api: 'writeBySelf',
+              selfFunction: '(i)=>this.$router.push({name:"v1_info" , query:{id:i._id},params:{service:this.service}})',
+            },
+          ],
+          btn_area: [
+            {
+              label: '添加',
+              type: 'primary',
+              api: 'writeBySelf',
+              selfFunction: '(i)=>this.$router.push({name:"v1_detail",params:{service:this.service}})',
+              confirm: false,
+            },
+          ],
+        },
+        page_type: 'list',
+      };
+      const sa = await ctx.model.Menu.create(sys_admin);
+      let admin_id = _.get(sa, '_id');
+      if (admin_id) admin_id = JSON.parse(JSON.stringify(admin_id));
+      const sys_admin_child = {
+        status: '0',
+        icon: 'icon-shouye',
+        no_delete: true,
+        _tenant: 'master',
+        name: '管理员信息',
+        parent_id: admin_id,
+        path: '/detail/v1/admin',
+        type: '2',
+        config: {
+          api: [
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'fetch',
+              opera: 'search',
+              desc: '单数据查询',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'create',
+              opera: 'create',
+              desc: '创建',
+            },
+            {
+              is_use: true,
+              module: 'admin',
+              func: 'update',
+              opera: 'update',
+              desc: '修改',
+            },
+          ],
+          table_btn: [],
+          btn_area: [],
+        },
+        page_type: 'detail',
+      };
+      await ctx.model.Menu.create(sys_admin_child);
+      console.log(colors.bgGreen.italic('菜单=>系统菜单=>初始化 管理员管理'));
+      console.log(colors.bgGreen.italic('菜单=>初始化 系统菜单'));
+
+      console.log('初始化总管理员菜单结束'.green);
+    } else console.log('无需初始化总管理员菜单'.yellow);
+  }
+}
+module.exports = AppBootHook;

+ 23 - 0
app/controller/admin.js

@@ -0,0 +1,23 @@
+'use strict';
+const meta = require('./config/.admin.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+//
+class AdminController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.admin;
+  }
+
+  async wxAppLogin() {
+    await this.service.wxAppLogin(this.ctx.request.body);
+    this.ctx.ok();
+  }
+
+  async wxAppBind() {
+    await this.service.wxAppBind(this.ctx.request.body);
+    this.ctx.ok();
+  }
+}
+module.exports = CrudController(AdminController, meta);

+ 39 - 0
app/controller/config/.admin.js

@@ -0,0 +1,39 @@
+module.exports = {
+  create: {
+    requestBody: ['role', 'name', 'account', 'password', '_tenant'],
+  },
+  destroy: {
+    params: ['!id'],
+    service: 'delete',
+  },
+  update: {
+    params: ['!id'],
+    requestBody: ['role', 'name', 'account', 'password', '_tenant'],
+  },
+  show: {
+    parameters: {
+      params: ['!id'],
+    },
+    service: 'fetch',
+  },
+  index: {
+    parameters: {
+      query: {
+        name: '%name%',
+        account: 'account',
+        '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,
+    },
+  },
+};

+ 44 - 0
app/controller/config/.user.js

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

+ 11 - 0
app/controller/config/.utils.js

@@ -0,0 +1,11 @@
+module.exports = {
+  readModel: {
+    params: ['!model'],
+  },
+  readFields: {
+    params: ['!model'],
+  },
+  getPageMeta: {
+    requestBody: ['!path'],
+  },
+};

+ 38 - 0
app/controller/home.js

@@ -0,0 +1,38 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+
+// 项目测试及管理员登陆
+class HomeController extends Controller {
+  async index() {
+    const { ctx } = this;
+    ctx.body = 'hi, egg';
+  }
+  /**
+   * 系统管理员登陆
+   * 太简单了,就不写service了,直接在这处理完完事了
+   */
+  async login() {
+    const { account, password } = this.ctx.request.body;
+    let admin = await this.ctx.model.Admin.findOne({ account }, '+password').exec();
+    if (!account) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户账号');
+    if (!password) throw new BusinessError(ErrorCode.BADPARAM, '未找到要登陆用户密码');
+    if (admin.password.secret !== password) throw new BusinessError(ErrorCode.BAD_PASSWORD, '密码错误');
+    admin = JSON.parse(JSON.stringify(admin));
+    delete admin.password;
+    delete admin.meta;
+    delete admin.__v;
+    const { is_super } = admin;
+    if (!is_super) {
+      // 获取角色
+      const roleRes = await this.ctx.model.Role.findOne({ _id: admin.role });
+      if (roleRes) {
+        admin.role_id = roleRes._id;
+      }
+    }
+    const token = this.ctx.service.util.jwt.encrypt(admin);
+    this.ctx.ok({ data: token });
+  }
+}
+module.exports = CrudController(HomeController, {});

+ 13 - 0
app/controller/user.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./config/.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;
+  }
+}
+module.exports = CrudController(UserController, meta);

+ 13 - 0
app/controller/utils.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./config/.utils.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+// 工具
+class UtilsController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.utils;
+  }
+}
+module.exports = CrudController(UtilsController, 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) {
+      // 没啥可输出,别中断就行
+    }
+
+
+  };

+ 23 - 0
app/model/admin.js

@@ -0,0 +1,23 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');
+// 系统管理员表
+const admin = {
+  name: { type: String, default: '系统管理员', zh: '管理员名称', listFilter: true }, // 显示名称
+  account: { type: String, zh: '登陆账号' }, // 账号
+  password: { type: Secret, select: false, isShowList: false, zh: '登陆密码', formType: 'password', showUpdate: false }, // 密码
+  is_super: { type: Boolean, default: false, isShowList: false, isShowDetail: false }, // 超级管理员
+  _tenant: { type: String, zh: '所属分站', formType: 'select', ref: 'tenant', selectList: { module: 'tenant', func: 'query', label: 'name', value: 'tenant' } },
+  role: { type: String, zh: '角色', formType: 'select', ref: 'role', selectList: { module: 'role', func: 'query', label: 'name', value: '_id' } },
+  openid: { type: String, zh: '微信小程序id' },
+  remark: { type: String },
+};
+const schema = new Schema(admin, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Admin', schema, 'admin');
+};

+ 35 - 0
app/model/model.md

@@ -0,0 +1,35 @@
+## Model 说明
+
+#### 1. `const schema = new Schema(${tableName}, { toJSON: { virtuals: true } });`
+#### 这行代码是生成mongodb的Schemas,相当于建表;
+---
+#### 2. 
+```
+const ${tableName}(表名) = {
+    column(字段名):{
+      type:TYPE,
+      required:Boolean,
+      default:TYPE,
+      ref:model,
+      ------------以上为mongoose的常用属性,还有别的自己找----------------
+      ------------以下为自定义属性,写进去也不会错(没写错的话)-------------
+      zh:'中文',
+      getProp:'${prop}'
+    }
+}
+```
+|属性|使用场景|类型|说明|
+|:-:|:-:|:-:|:-:|
+|type|建表|基础数据类型|mongodb数据类型|
+|required|建表|Boolean|是否必填,不必填可以不写这个字段|
+|default|建表|Any|默认值|
+|ref|建表|String|与哪个model关联|
+|zh|导入/出;显示|String|该字段中文|
+|getProp|导入/出;显示|String|字符串:属性,取出后使用zh中文,与ref配合使用,会将当前字段添加 showModel:`${ref}.${getProp}` 属性|
+|selectList|显示;表单选项/显示|Array/Object|选择列表,数组直接使用;Object是做请求|
+|formType|表单|String|表单中是什么类型,不写默认text|
+|isShowList|显示|Boolean|是否显示在列表中|
+|isShowDetail|显示|Boolean|是否显示在详情中|
+|listFilter|显示|Boolean|是否显示在列表中作为查询项|
+|showCreate|显示|Boolean|是否显示在创建的表单中|
+|showUpdate|显示|Boolean|是否显示在修改的表单中|

+ 29 - 0
app/model/user.js

@@ -0,0 +1,29 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+const { Secret } = require('naf-framework-mongoose-free/lib/model/schema');
+
+// 用户表
+const user = {
+  openid: { type: String, required: false, zh: 'openid' }, // openid
+  name: { type: String, required: false, zh: '用户名' }, // 用户名
+  gender: { type: String, required: false, zh: '性别' }, // 性别
+  phone: { type: String, required: false, zh: '手机号' }, // 手机号
+  email: { type: String, required: false, zh: '邮箱' }, // 邮箱
+  type: { type: String, required: false, default: '0', zh: '用户类别。0:普通用户,1:裁判用户' }, // 用户类别。0:普通用户,1:裁判用户
+  icon: { type: Array, required: false, zh: '用户头像' }, // 用户头像
+};
+const schema = new Schema(user, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.index({ name: 1 });
+schema.index({ gender: 1 });
+schema.index({ phone: 1 });
+schema.index({ type: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('User', schema, 'user');
+};

+ 26 - 0
app/public/routerRegister.js

@@ -0,0 +1,26 @@
+'use strict';
+/**
+ * 注册路由
+ * @param {App} app 全局变量
+ * @param {Array} routes 路由数组
+ * @param {String} keyZh 路由主题
+ * @param {String} rkey 路由主位置的标识
+ * @param {String} ckey 路由对应的controller的标识
+ */
+module.exports = (app, routes, keyZh, rkey, ckey) => {
+  const { router, config } = app;
+  const mwares = app.middleware;
+  if (process.env.NODE_ENV === 'development') console.log(`${keyZh}:  ${rkey}`);
+  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 (process.env.NODE_ENV === 'development') console.log(`     ${zh}: ${allPath}`);
+    // 处理中间件
+    if (middleware.length > 0) middleware = middleware.map(i => mwares[i]({ enable: true, model: ckey || rkey }));
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 30 - 0
app/router.js

@@ -0,0 +1,30 @@
+'use strict';
+
+/**
+ * @param {Egg.Application} app - egg application
+ */
+
+const os = require('os');
+function getIPAdress() {
+  const interfaces = os.networkInterfaces();
+  for (const devName in interfaces) {
+    const iface = interfaces[devName];
+    for (let i = 0; i < iface.length; i++) {
+      const alias = iface[i];
+      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
+        return alias.address;
+      }
+    }
+  }
+}
+module.exports = app => {
+  const { router, controller } = app;
+  const { routePrefix, cluster } = app.config;
+  const ipAddress = getIPAdress();
+  console.log(`前缀:http://${ipAddress}:${cluster.listen.port}${routePrefix}`);
+  router.get('/', controller.home.index);
+  router.post(`${routePrefix}/login`, controller.home.login);
+  require('./z_router/admin')(app); // 管理员
+  require('./z_router/utils')(app); // 工具
+  require('./z_router/user')(app); // 用户
+};

+ 89 - 0
app/service/admin.js

@@ -0,0 +1,89 @@
+'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');
+const { ObjectId } = require('mongoose').Types;
+
+// 管理员
+class AdminService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'admin');
+    this.model = this.ctx.model.Admin;
+    this.httpUtil = this.ctx.service.util.httpUtil;
+    this.httpPrefix = this.ctx.app.config.httpPrefix;
+  }
+  /**
+   * 检查code是否过期;使用openid找到商家,用户信息送过去并提示登陆成功
+   * @param {Object} body 参数体
+   */
+  async wxAppLogin({ code, openid, route, path }) {
+    let msg = 'ok';
+    const uri = `/login/scan/checkCode?code=${code}`;
+    const { wechat } = this.httpPrefix;
+    const result = await this.httpUtil.cget(`${wechat}${uri}`);
+    if (!result) {
+      msg = '二维码已失效,请重新绑定';
+      this.sendMsg(path, route, msg, -1);
+      throw new BusinessError(ErrorCode.BusinessError, msg);
+    }
+    let admin = await this.model.findOne({ openid });
+    if (!admin) {
+      msg = '该微信用户没有绑定代理人员账号';
+      this.sendMsg(path, route, msg, -1);
+      throw new BusinessError(ErrorCode.DATA_NOT_EXIST, msg);
+    }
+    admin = JSON.parse(JSON.stringify(admin));
+    delete admin.password;
+    delete admin.meta;
+    delete admin.__v;
+    const { is_super } = admin;
+    if (!is_super) {
+      // 获取角色
+      const roleRes = await this.ctx.model.Role.findOne({ _id: admin.role });
+      if (roleRes) {
+        admin.role_id = roleRes._id;
+      }
+    }
+    const token = this.ctx.service.util.jwt.encrypt(admin);
+    // 发送消息
+    const res = await this.sendMsg(path, route, 'ok', 0, token);
+    if (res) return res;
+  }
+  /**
+   * 检查code是否过期;使用id查到指定用户,改openid,发消息
+   * @param {Object} body 参数体
+   */
+  async wxAppBind({ code, openid, route, path, id }) {
+    let msg = 'ok';
+    const { wechat } = this.httpPrefix;
+    const uri = `/login/scan/checkCode?code=${code}`;
+    const result = await this.httpUtil.cget(`${wechat}${uri}`);
+    if (!result) {
+      msg = '二维码已失效,请重新绑定';
+      this.sendMsg(path, route, msg, -1);
+      throw new BusinessError(ErrorCode.BusinessError, msg);
+    }
+    const admin = await this.model.findById(id);
+    if (!admin) {
+      msg = '用户不存在';
+      this.sendMsg(path, route, msg, -1);
+      throw new BusinessError(ErrorCode.DATA_NOT_EXIST, msg);
+    }
+    // 将该openid的用户全部置空,再修改该用户openid
+    await this.model.updateMany({ openid }, { openid: undefined });
+    await this.model.updateOne({ _id: ObjectId(id) }, { openid });
+    // 发送消息
+    const res = await this.sendMsg(path, route);
+    if (res) return res;
+  }
+
+  async sendMsg(path, route, errmsg = 'ok', errcode = 0, content) {
+    const { wechat } = this.httpPrefix;
+    const sendUri = '/mq/send';
+    const res = await this.httpUtil.cpost(`${wechat}${sendUri}`, { path, route, content: { errcode, errmsg, data: content } });
+    return res;
+  }
+}
+
+module.exports = AdminService;

+ 27 - 0
app/service/user.js

@@ -0,0 +1,27 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+
+// 用户管理
+class UserService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'user');
+    this.model = this.ctx.model.User;
+  }
+
+  /**
+   * 微信小程序登录
+   * @param {String} openid 微信小程序的openid
+   */
+  async wxAppLogin({ openid }) {
+    const user = await this.model.findOne({ openid });
+    return user;
+    // 没注册的需要手动注册
+    // if (user) return user;
+    // const newUser = await this.model.create({ openid });
+    // return newUser;
+  }
+
+}
+
+module.exports = UserService;

+ 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;

+ 35 - 0
app/service/util/install.js

@@ -0,0 +1,35 @@
+'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 InstallService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'install');
+    this.model = this.ctx.model.Install;
+  }
+  async init() {
+    this.initAdmin();
+  }
+
+  async initAdmin() {
+    console.log('开始=>初始化总管理员'.blue);
+    const data = await this.ctx.model.Admin.findOne();
+    if (!data) {
+      // 没有管理员,初始化一个
+      const data = {
+        account: 'admin',
+        is_super: true,
+        password: { secret: '111111' },
+        _tenant: 'master',
+      };
+      console.log('正在初始化总管理员'.blue);
+      await this.ctx.model.Admin.create(data);
+      console.log('初始化总管理员=>结束'.green);
+    } else console.log('无需再次初始化总管理员'.yellow);
+  }
+}
+
+module.exports = InstallService;

+ 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;

+ 115 - 0
app/service/utils.js

@@ -0,0 +1,115 @@
+'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');
+const { ObjectId } = require('mongoose').Types;
+
+// 工具
+class UtilsService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'utils');
+    this.showModelID = '__';
+  }
+  /**
+   * 根据路由查询菜单的设置
+   * @param {Object} path 查询路由
+   */
+  async getPageMeta({ path }) {
+    const data = await this.ctx.model.Menu.findOne({ path });
+    return data;
+  }
+
+  /**
+   * 读取model配置,并形成人可以读的数据格式
+   * @param {String} model 表名
+   */
+  async readModel({ model }) {
+    assert(model, '缺少表名');
+    const mod = this.getModelName(model);
+    let data = this.ctx.model[mod].prototype.schema.obj;
+    if (!(data && _.isObject(data))) throw new BusinessError(ErrorCode.DATABASE_FAULT, '无法读取表结构');
+    data = JSON.parse(JSON.stringify(data));
+    const keys = Object.keys(data);
+    let arr = [];
+    for (const key of keys) {
+      const obj = { key, ..._.omit(data[key], [ 'type' ]) };
+      arr.push(obj);
+    }
+    arr = arr.filter(f => _.has(f, 'zh'));
+    return arr;
+  }
+  /**
+   * 获取列表显示
+   * @param {String} model 表名
+   */
+  async readFields({ model }) {
+    let list = await this.readModel({ model });
+    list = list.map(i => {
+      const { key, zh, formType, ref, getProp, ...others } = i;
+      const obj = { label: zh, model: key, ...others };
+      if (formType) obj.type = formType;
+      if (ref && getProp) {
+        obj.showModel = `${ref}${this.showModelID}${getProp}`;
+      }
+      return obj;
+    });
+    return list;
+  }
+
+  /**
+   * 将各种格式的表名换成model的表名
+   * @param {String} str 表名(各种格式)
+   */
+  getModelName(str) {
+    const mods = Object.keys(this.ctx.model);
+    const r = mods.find(f => _.toLower(f) === _.toLower(str));
+    return r;
+  }
+
+  /**
+   * 拼接ref内容;直接针对body进行更改,而不是body的data部分.虽然只改body.data
+   * @param {String} model 表名
+   * @param {Object/Array} body 数据
+   */
+  async getRefData(model, body) {
+    let data = body.data;
+    if (_.isArray(data) && data.length <= 0) return body;
+    if (!body) return body;
+    // 将 数组 和 对象 的处理方法先声明好
+    let funcGetId,
+      funcMapData;
+    if (_.isArray(data)) {
+      funcGetId = (data, model) => data.map(i => i[model]);
+      funcMapData = (data, refData, model, showModel, prop) =>
+        (data = data.map(i => {
+          const r = refData.find(f => ObjectId(f._id).equals(i[model]));
+          if (r) i[showModel] = r[prop];
+          return i;
+        }));
+    } else {
+      funcGetId = (data, model) => data[model];
+      funcMapData = (data, refData, model, showModel, prop) => {
+        const r = refData.find(f => ObjectId(f._id).equals(data[model]));
+        if (r) data[showModel] = r[prop];
+        return data;
+      };
+    }
+    const fields = await this.readFields({ model });
+    const needDealFields = fields.filter(f => f.showModel);
+    for (const f of needDealFields) {
+      const { showModel, model } = f;
+      const arr = showModel.split(this.showModelID);
+      const ref = this.getModelName(_.head(arr));
+      const prop = _.last(arr);
+      // 获取id内容
+      const ids = funcGetId(data, model);
+      // 获取对应的内容
+      const refData = await this.ctx.model[ref].find({ _id: ids }, { [prop]: 1 });
+      data = funcMapData(data, refData, model, showModel, prop);
+    }
+    return body;
+  }
+}
+
+module.exports = UtilsService;

+ 19 - 0
app/z_router/admin.js

@@ -0,0 +1,19 @@
+'use strict';
+// 路由配置
+const routerRegister = require('../public/routerRegister');
+const rkey = 'admin';
+const ckey = 'admin';
+const keyZh = '管理员';
+const routes = [
+  { method: 'post', path: `${rkey}/wxAppBind`, controller: `${ckey}.wxAppBind`, name: `${ckey}WxAppBind`, zh: `${keyZh}微信小程序绑定` },
+  { method: 'post', path: `${rkey}/wxAppLogin`, controller: `${ckey}.wxAppLogin`, name: `${ckey}WxAppLogin`, zh: `${keyZh}微信小程序登录` },
+  { method: 'get', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Query`, zh: `${keyZh}列表查询` },
+  { method: 'get', path: `${rkey}/:id`, controller: `${ckey}.show`, name: `${ckey}Show`, zh: `${keyZh}查询` },
+  { method: 'post', path: `${rkey}`, controller: `${ckey}.create`, middleware: [ 'password' ], name: `${ckey}Create`, zh: `创建${keyZh}` },
+  { method: 'post', path: `${rkey}/:id`, controller: `${ckey}.update`, name: `${ckey}Update`, zh: `修改${keyZh}` },
+  { method: 'delete', path: `${rkey}/:id`, controller: `${ckey}.destroy`, name: `${ckey}Delete`, zh: `删除${keyZh}` },
+];
+
+module.exports = app => {
+  routerRegister(app, routes, keyZh, rkey, ckey);
+};

+ 18 - 0
app/z_router/user.js

@@ -0,0 +1,18 @@
+'use strict';
+// 路由配置
+const routerRegister = require('../public/routerRegister');
+const rkey = 'user';
+const ckey = 'user';
+const keyZh = '用户';
+const routes = [
+  { method: 'post', path: `${rkey}/wxAppLogin`, controller: `${ckey}.wxAppLogin`, name: `${ckey}WxAppLogin`, zh: `${keyZh}-小程序登录` },
+  { method: 'get', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Query`, zh: `${keyZh}列表查询` },
+  { method: 'get', path: `${rkey}/:id`, controller: `${ckey}.show`, name: `${ckey}Show`, zh: `${keyZh}查询` },
+  { method: 'post', path: `${rkey}`, controller: `${ckey}.create`, middleware: [ 'password' ], name: `${ckey}Create`, zh: `创建${keyZh}` },
+  { method: 'post', path: `${rkey}/:id`, controller: `${ckey}.update`, name: `${ckey}Update`, zh: `修改${keyZh}` },
+  { method: 'delete', path: `${rkey}/:id`, controller: `${ckey}.destroy`, name: `${ckey}Delete`, zh: `删除${keyZh}` },
+];
+
+module.exports = app => {
+  routerRegister(app, routes, keyZh, rkey, ckey);
+};

+ 15 - 0
app/z_router/utils.js

@@ -0,0 +1,15 @@
+'use strict';
+// 路由配置
+const routerRegister = require('../public/routerRegister');
+const rkey = 'utils';
+const ckey = 'utils';
+const keyZh = '工具';
+const routes = [
+  { method: 'get', path: `${rkey}/readModel/:model`, controller: `${ckey}.readModel`, name: `${ckey}ReadModel`, zh: 'model查询' },
+  { method: 'get', path: `${rkey}/readFields/:model`, controller: `${ckey}.readFields`, name: `${ckey}ReadFields`, zh: 'fields查询' },
+  { method: 'post', path: `${rkey}/getPageMeta`, controller: `${ckey}.getPageMeta`, name: `${ckey}GetPageMeta`, zh: '查询页面元信息' },
+];
+
+module.exports = app => {
+  routerRegister(app, routes, keyZh, rkey, ckey);
+};

+ 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

+ 98 - 0
config/config.default.js

@@ -0,0 +1,98 @@
+/* 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 = [ 'requestLog' ];
+
+  // add your user config here
+  const userConfig = {
+    // myAppName: 'egg',
+  };
+  // 日志
+  config.logger = {
+    level: 'DEBUG',
+    allowDebugAtProd: true,
+  };
+  // mq设置
+  // config.amqp = {
+  //   client: {
+  //     hostname: '127.0.0.1',
+  //     username: 'freeAdmin',
+  //     password: '1qaz2wsx',
+  //     vhost: 'freeAdmin',
+  //   },
+  //   app: true,
+  //   agent: true,
+  // };
+  // 接收队列名称
+  // config.queue = 'freeAdmin/server-haocai-new';
+  // 发送队列名称
+  // config.sendQueue = {
+  //   logs: 'freeAdmin/server-logs',
+  // };
+  // http请求前缀
+  config.httpPrefix = {
+    wechat: 'http://101.36.221.66:14001/wechat/api',
+  };
+  // redis设置
+  // config.redis = {
+  //   client: {
+  //     port: 6379, // Redis port
+  //     host: '127.0.0.1', // Redis host
+  //     password: '123456',
+  //     db: 0,
+  //   },
+  // };
+  // 进程设置
+  config.cluster = {
+    listen: {
+      port: 15000,
+    },
+  };
+
+  // jwt设置
+  config.jwt = {
+    ...jwt,
+    expiresIn: '1d',
+    issuer: 'new_court',
+  };
+
+  // 数据库设置
+  config.dbName = 'new_court';
+  config.mongoose = {
+    url: `mongodb://127.0.0.1:27017/${config.dbName}`,
+    options: {
+      user: 'admin',
+      pass: 'admin',
+      authSource: 'admin',
+      useNewUrlParser: true,
+      useCreateIndex: true,
+    },
+  };
+  // 路由设置
+  config.routePrefix = '/newCourt/api';
+
+  // 中间件
+  config.requestLog = {
+    toMongoDB: true,
+  };
+  return {
+    ...config,
+    ...userConfig,
+  };
+};

+ 46 - 0
config/config.prod.js

@@ -0,0 +1,46 @@
+'use strict';
+
+module.exports = () => {
+  const config = (exports = {});
+
+  config.logger = {
+    level: 'INFO',
+    consoleLevel: 'INFO',
+  };
+  // http请求前缀
+  config.httpPrefix = {
+    wechat: 'http://localhost:14001/wechat/api',
+  };
+  // config.dbName = 'new-platform';
+  // config.mongoose = {
+  //   url: `mongodb://localhost:27017/${config.dbName}`,
+  //   options: {
+  //     user: 'admin',
+  //     pass: 'admin',
+  //     authSource: 'admin',
+  //     useNewUrlParser: true,
+  //     useCreateIndex: true,
+  //   },
+  // };
+  // // redis config
+  // config.redis = {
+  //   client: {
+  //     port: 6379, // Redis port
+  //     host: '127.0.0.1', // Redis host
+  //     password: 123456,
+  //     db: 0,
+  //   },
+  // };
+
+  // config.export = {
+  //   root_path: 'D:\\free\\workspace\\server\\service-file\\upload',
+  //   export_path: 'D:\\free\\workspace\\server\\service-file\\upload\\export',
+  //   export_dir: 'export',
+  //   patentInfo_dir: 'patentInfo',
+  //   domain: 'http://127.0.0.1',
+  // };
+  // config.import = {
+  //   root_path: 'D:\\free\\workspace\\server\\service-file\\upload',
+  // };
+  return config;
+};

+ 7 - 0
config/config.secret.js

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

+ 11 - 0
config/plugin.js

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

+ 18 - 0
ecosystem.config.js

@@ -0,0 +1,18 @@
+'use strict';
+
+// const app = 'server-group-business';
+const app = '新赛场-服务';
+module.exports = {
+  apps: [{
+    name: app, // 应用名称
+    script: './server.js', // 实际启动脚本
+    out: `./logs/${app}.log`,
+    error: `./logs/${app}.err`,
+    watch: [ // 监控变化的目录,一旦变化,自动重启
+      'app', 'config',
+    ],
+    env: {
+      NODE_ENV: 'production', // 环境参数,当前指定为生产环境
+    },
+  }],
+};

+ 53 - 0
package.json

@@ -0,0 +1,53 @@
+{
+  "name": "server-new-court",
+  "version": "1.0.0",
+  "description": "新赛场",
+  "private": true,
+  "egg": {
+    "framework": "naf-framework-mongoose-free"
+  },
+  "dependencies": {
+    "colors": "^1.4.0",
+    "egg": "^2.15.1",
+    "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.21"
+  },
+  "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"
+}

+ 2 - 0
readme/admin.md

@@ -0,0 +1,2 @@
+# Admin 管理员相关
+### 没有设计成分站模式,为系统管理员,不管业务方面

+ 13 - 0
readme/user.md

@@ -0,0 +1,13 @@
+# User 相关
+### 设计为分站模式,目的是作为一个持续可使用的服务
+### 使用流程:
+
+|字段|类型|说明|
+|:-:|:-:|:-:|
+|account|String|账号|
+|password|Secret|密码|
+|uid|String|关联id,与各自业务有关的用户id|
+
+### 1. 创建: 各自业务创建账号时,走接口,在用户管理项目中可以保留任何信息,但是不能保留密码.目的是为了以最小的耦合性完成身份验证;
+### 2. 修改密码:用户登陆后,知道自己的分站,自己的id后可以过来修改密码
+### 3. 删除用户:要留底在各自的业务中留底,这边删除就是删除

+ 7 - 0
readme/业务.md

@@ -0,0 +1,7 @@
+## 表
+---
+### 用户表(user)
+记录使用微信登录过的用户, openid为每个用户的唯一标识
+type 区别 是单纯的购买用户 / 可以进行卖货的团长
+
+### 

+ 10 - 0
server.js

@@ -0,0 +1,10 @@
+
+// eslint-disable-next-line strict
+const egg = require('egg');
+// const l = process.argv[2] || require('os').cpus().length;
+const l = 1;
+const workers = Number(l);
+egg.startCluster({
+  workers,
+  baseDir: __dirname,
+});

+ 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);
+  });
+});