lrf 2 年 前
コミット
79b721c255
53 ファイル変更1850 行追加0 行削除
  1. 29 0
      .autod.conf.js
  2. 1 0
      .eslintignore
  3. 3 0
      .eslintrc
  4. 46 0
      .github/workflows/nodejs.yml
  5. 14 0
      .gitignore
  6. 12 0
      .travis.yml
  7. 5 0
      README.md
  8. 363 0
      app.js
  9. 64 0
      app/controller/home.js
  10. 13 0
      app/controller/user/coach.js
  11. 40 0
      app/controller/user/config/.coach.js
  12. 39 0
      app/controller/user/config/.school.js
  13. 40 0
      app/controller/user/config/.student.js
  14. 42 0
      app/controller/user/config/.user.js
  15. 13 0
      app/controller/user/school.js
  16. 13 0
      app/controller/user/student.js
  17. 13 0
      app/controller/user/user.js
  18. 53 0
      app/middleware/request-log.js
  19. 40 0
      app/model/model.md
  20. 18 0
      app/model/role.js
  21. 27 0
      app/model/user/coach.js
  22. 22 0
      app/model/user/school.js
  23. 26 0
      app/model/user/student.js
  24. 24 0
      app/model/user/user.js
  25. 27 0
      app/public/routerRegister.js
  26. 31 0
      app/router.js
  27. 15 0
      app/service/user/coach.js
  28. 15 0
      app/service/user/school.js
  29. 15 0
      app/service/user/student.js
  30. 56 0
      app/service/user/user.js
  31. 83 0
      app/service/util/http-util.js
  32. 35 0
      app/service/util/install.js
  33. 18 0
      app/service/util/jwt.js
  34. 74 0
      app/service/util/rabbitMq.js
  35. 67 0
      app/service/wxpay.js
  36. 19 0
      app/z_router/user/coach.js
  37. 19 0
      app/z_router/user/school.js
  38. 19 0
      app/z_router/user/student.js
  39. 20 0
      app/z_router/user/user.js
  40. 16 0
      app/z_router/utils.js
  41. 14 0
      appveyor.yml
  42. 132 0
      config/config.default.js
  43. 46 0
      config/config.prod.js
  44. 7 0
      config/config.secret.js
  45. 11 0
      config/plugin.js
  46. 18 0
      ecosystem.config.js
  47. 53 0
      package.json
  48. 2 0
      readme/admin.md
  49. 13 0
      readme/user.md
  50. 7 0
      readme/业务.md
  51. 10 0
      server.js
  52. 20 0
      test/app/controller/home.test.js
  53. 28 0
      test/test.js

+ 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

+ 5 - 0
README.md

@@ -0,0 +1,5 @@
+# server-new
+
+## 与用户有关联的全用 openid进行查询
+
+## 数据修改仍然用数据id:_id

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

+ 64 - 0
app/controller/home.js

@@ -0,0 +1,64 @@
+'use strict';
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const { ObjectId } = require('mongoose').Types;
+
+// 项目测试及管理员登陆
+class HomeController extends Controller {
+  async index() {
+    const { ctx } = this;
+    const enrollModel = this.ctx.model.Enroll;
+    const teamApply = this.ctx.model.TeamApply;
+    const enrollQuery = { project_id: '62e5fff82dc7343e137ffef5', grouping_id: '62e601c72dc7343e137fff6f', status: { $ne: '0' } };
+    const teamApplyQuery = { project_id: '62e5fff82dc7343e137ffef5', grouping_id: '62e601c72dc7343e137fff6f' };
+    // 报名数据
+    const eData = await enrollModel.find(enrollQuery);
+    // 组队申请数据
+    const taData = await teamApply.find(teamApplyQuery);
+    // 查看每个申请组队的人,是否有报名数据
+    for (const ta of taData) {
+      const { applyuser_id, teammate_id } = ta;
+      const ar = eData.find(f => f.openid === applyuser_id);
+      const tr = eData.find(f => f.openid === teammate_id);
+      if (!ar) {
+        console.log('没有申请人');
+        console.log(ta);
+      } else if (!tr) {
+        console.log('没有队友');
+        console.log(ta);
+      } else if (!ar && !tr) {
+        console.log('都没有');
+        console.log(ta);
+      }
+    }
+
+    ctx.body = { eData, taData };
+  }
+  /**
+   * 系统管理员登陆
+   * 太简单了,就不写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/coach.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./config/.coach.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+//
+class CoachController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.user.coach;
+  }
+}
+module.exports = CrudController(CoachController, meta);

+ 40 - 0
app/controller/user/config/.coach.js

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

+ 39 - 0
app/controller/user/config/.school.js

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

+ 40 - 0
app/controller/user/config/.student.js

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

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

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

+ 13 - 0
app/controller/user/school.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./config/.school.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+//
+class SchoolController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.user.school;
+  }
+}
+module.exports = CrudController(SchoolController, meta);

+ 13 - 0
app/controller/user/student.js

@@ -0,0 +1,13 @@
+'use strict';
+const meta = require('./config/.student.js');
+const Controller = require('egg').Controller;
+const { CrudController } = require('naf-framework-mongoose-free/lib/controller');
+
+//
+class StudentController extends Controller {
+  constructor(ctx) {
+    super(ctx);
+    this.service = this.ctx.service.user.student;
+  }
+}
+module.exports = CrudController(StudentController, meta);

+ 13 - 0
app/controller/user/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.user;
+  }
+}
+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) {
+      // 没啥可输出,别中断就行
+    }
+
+
+  };

+ 40 - 0
app/model/model.md

@@ -0,0 +1,40 @@
+# 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}'/['${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|是否显示在修改的表单中|
+|getProp|显示|String/Array|ref关联表,取出的属性,在查询时使用|

+ 18 - 0
app/model/role.js

@@ -0,0 +1,18 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+const { ObjectId } = require('mongoose').Types;
+// 角色表
+const role = {
+  name: { type: String, zh: '名称' },
+  code: { type: String, zh: '编码' },
+  remark: { type: String },
+};
+const schema = new Schema(role, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Role', schema, 'role');
+};

+ 27 - 0
app/model/user/coach.js

@@ -0,0 +1,27 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+
+// 教练
+const coach = {
+  icon: { type: String, required: false, zh: '头像' }, //
+  name: { type: String, required: false, zh: '姓名' }, //
+  card: { type: String, required: false, zh: '身份证号' }, //
+  age: { type: Number, required: false, zh: '年龄' }, //
+  phone: { type: String, required: false, zh: '联系电话' }, //
+  skill: { type: String, required: false, zh: '专业技能' }, //
+  user_id: { type: String, required: false, zh: '用户id', ref: 'User', getProp: [ 'name' ] }, //
+  gender: { type: String, required: false, zh: '性别' }, //
+};
+const schema = new Schema(coach, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.index({ name: 1 });
+schema.index({ card: 1 });
+schema.index({ user_id: 1 });
+
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Coach', schema, 'coach');
+};

+ 22 - 0
app/model/user/school.js

@@ -0,0 +1,22 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+
+// 学校
+const school = {
+  name: { type: String, required: false, zh: '名称' }, //
+  brief: { type: String, required: false, zh: '简介' }, //
+  img_url: { type: Array, required: false, zh: '图片' }, //
+  user_id: { type: String, required: false, zh: '用户表信息', ref: 'User', getProp: [ 'name' ] }, //
+};
+const schema = new Schema(school, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.index({ name: 1 });
+schema.index({ user_id: 1 });
+
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('School', schema, 'school');
+};

+ 26 - 0
app/model/user/student.js

@@ -0,0 +1,26 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+
+// 学员
+const student = {
+  icon: { type: String, required: false, zh: '头像' }, //
+  name: { type: String, required: false, zh: '姓名' }, //
+  card: { type: String, required: false, zh: '身份证号' }, //
+  gender: { type: String, required: false, zh: '性别' }, //
+  age: { type: Number, required: false, zh: '年龄' }, //
+  phone: { type: String, required: false, zh: '联系电话' }, //
+  user_id: { type: String, required: false, zh: '用户id', ref: 'User' }, //
+};
+const schema = new Schema(student, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.index({ name: 1 });
+schema.index({ card: 1 });
+schema.index({ user_id: 1 });
+
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('Student', schema, 'student');
+};

+ 24 - 0
app/model/user/user.js

@@ -0,0 +1,24 @@
+'use strict';
+const Schema = require('mongoose').Schema;
+const metaPlugin = require('naf-framework-mongoose-free/lib/model/meta-plugin');
+
+// 微信用户表
+const user = {
+  openid: { type: String, required: true, zh: 'openid ' }, //
+  name: { type: String, required: false, zh: '用户名' }, //
+  gender: { type: String, required: false, zh: '性别' }, //
+  phone: { type: String, required: false, zh: '手机号' }, //
+  icon: { type: Array, required: false, zh: '头像' }, //
+  type: { type: String, required: false, default: '0', zh: '用户类别' }, // -1:超级管理员;0:普通用户;1-学院管理员;2-教练;3-学员;10-游客
+};
+const schema = new Schema(user, { toJSON: { virtuals: true } });
+schema.index({ id: 1 });
+schema.index({ 'meta.createdAt': 1 });
+schema.index({ openid: 1 });
+schema.index({ name: 1 });
+
+schema.plugin(metaPlugin);
+module.exports = app => {
+  const { mongoose } = app;
+  return mongoose.model('User', schema, 'user');
+};

+ 27 - 0
app/public/routerRegister.js

@@ -0,0 +1,27 @@
+'use strict';
+/**
+ * 注册路由
+ * @param {App} app 全局变量
+ * @param {Array} routes 路由数组
+ * @param {String} keyZh 路由主题
+ * @param {String} rkey 路由主位置的标识
+ * @param {String} ckey 路由对应的controller的标识
+ */
+const _ = require('lodash');
+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 => _.get(mwares, i)({ enable: true, model: ckey || rkey }));
+    // 注册路由
+    router[method](zh, allPath, ...middleware, ctl);
+  }
+};

+ 31 - 0
app/router.js

@@ -0,0 +1,31 @@
+'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/user/user')(app); // 用户
+  require('./z_router/user/coach')(app); // 教练
+  require('./z_router/user/school')(app); // 学院
+  require('./z_router/user/student')(app); // 学员
+};

+ 15 - 0
app/service/user/coach.js

@@ -0,0 +1,15 @@
+'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 CoachService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'coach');
+    this.model = this.ctx.model.User.Coach;
+  }
+}
+
+module.exports = CoachService;

+ 15 - 0
app/service/user/school.js

@@ -0,0 +1,15 @@
+'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 SchoolService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'school');
+    this.model = this.ctx.model.User.School;
+  }
+}
+
+module.exports = SchoolService;

+ 15 - 0
app/service/user/student.js

@@ -0,0 +1,15 @@
+'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 StudentService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'student');
+    this.model = this.ctx.model.User.Student;
+  }
+}
+
+module.exports = StudentService;

+ 56 - 0
app/service/user/user.js

@@ -0,0 +1,56 @@
+'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.User;
+    this.studentModel = this.ctx.model.User.Student;
+    this.schoolModel = this.ctx.model.User.School;
+    this.coachModel = this.ctx.model.User.Coach;
+  }
+
+  async fetch({ openid }) {
+    const res = await this.model.findOne({ openid });
+    return res;
+  }
+
+  /**
+   * 检查数据重复
+   */
+  async createCheck() {
+    const data = this.ctx.request.body;
+    const { card, phone, openid } = data;
+    let num = await this.model.count({ card });
+    if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该身份证号已被注册');
+    num = await this.model.count({ phone });
+    if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该手机号码已被注册');
+    num = await this.model.count({ openid });
+    if (num > 0) throw new BusinessError(ErrorCode.DATA_EXISTED, '该微信号码已被注册');
+    return true;
+  }
+
+  /**
+   * 微信小程序登录
+   * @param {String} openid 微信小程序的openid
+   */
+  async wxAppLogin({ openid }) {
+    const user = await this.model.findOne({ openid });
+    // 没注册的需要手动注册
+    if (!user) return user;
+    const { type, _id } = user;
+    // 超级管理员,普通用户,游客不需要其他信息,user里的就是
+    if ([ '-1', '0', '10' ].includes(type)) return user;
+    let infoModel;
+    if (type === '1') infoModel = this.schoolModel;
+    else if (type === '2') infoModel = this.coachModel;
+    else if (type === '3') infoModel = this.studentModel;
+    else throw new BusinessError(ErrorCode.USER_NOT_EXIST, '无法确定该用户的角色');
+    const info = await infoModel.findOne({ user_id: _id });
+    return { ...JSON.parse(JSON.stringify(user)), info };
+  }
+}
+
+module.exports = UserService;

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

@@ -0,0 +1,83 @@
+'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;

+ 67 - 0
app/service/wxpay.js

@@ -0,0 +1,67 @@
+'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 WxpayService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'wxpay');
+    this.appConfig = 'newCourtApp';
+    this.httpUtil = this.ctx.service.util.httpUtil;
+    const { wechat } = this.app.config.httpPrefix;
+    this.wxDomain = wechat;
+  }
+  /**
+   * 查询订单
+   * @param {String} order_no 订单号
+   */
+  async search(order_no) {
+    assert(order_no, '缺少订单号,无法查询订单信息');
+    const params = { config: this.appConfig, order_no };
+    const url = `${this.wxDomain}/pay/searchOrderByOrderNo`;
+    const wxOrderReq = await this.httpUtil.cpost(url, params);
+    return wxOrderReq;
+  }
+
+  /**
+   * 创建订单,获取微信支付签名
+   * @param {Object} data 数据
+   */
+  async create(data) {
+    const { money, openid, order_no, desc } = data;
+    const wxOrderData = { config: this.appConfig, money, openid, order_no, desc };
+    const url = `${this.wxDomain}/pay/payOrder`;
+    const res = await this.httpUtil.cpost(url, wxOrderData);
+    if (res) return res;
+    throw new BusinessError(ErrorCode.SERVICE_FAULT, '微信下单失败!');
+  }
+
+  /**
+   * 关闭订单
+   * @param {String} order_no 订单号
+   */
+  async close(order_no) {
+    assert(order_no, '缺少订单号,无法查询订单信息');
+    const params = { config: this.appConfig, order_no };
+    const url = `${this.wxDomain}/pay/closeOrder`;
+    const res = await this.httpUtil.cpost(url, params);
+    return res || 'ok';
+  }
+
+  /**
+   * 退款
+   * @param {String} order_no 订单号
+   * @param {String} reason 原因
+   */
+  async refund(order_no, reason) {
+    assert(order_no, '缺少订单号,无法查询订单信息');
+    const url = `${this.wxDomain}/pay/refundOrder`;
+    const params = { config: this.appConfig, order_no, reason };
+    const wxRefundReq = await this.httpUtil.cpost(url, params);
+    return wxRefundReq || 'ok';
+  }
+}
+
+module.exports = WxpayService;

+ 19 - 0
app/z_router/user/coach.js

@@ -0,0 +1,19 @@
+'use strict';
+// 路由配置
+const path = require('path');
+const regPath = path.resolve('app', 'public', 'routerRegister');
+const routerRegister = require(regPath);
+const rkey = 'coach';
+const ckey = 'user.coach';
+const keyZh = '教练';
+const routes = [
+  { 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);
+};

+ 19 - 0
app/z_router/user/school.js

@@ -0,0 +1,19 @@
+'use strict';
+// 路由配置
+const path = require('path');
+const regPath = path.resolve('app', 'public', 'routerRegister');
+const routerRegister = require(regPath);
+const rkey = 'school';
+const ckey = 'user.school';
+const keyZh = '学院';
+const routes = [
+  { 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);
+};

+ 19 - 0
app/z_router/user/student.js

@@ -0,0 +1,19 @@
+'use strict';
+// 路由配置
+const path = require('path');
+const regPath = path.resolve('app', 'public', 'routerRegister');
+const routerRegister = require(regPath);
+const rkey = 'student';
+const ckey = 'user.student';
+const keyZh = '学员';
+const routes = [
+  { 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);
+};

+ 20 - 0
app/z_router/user/user.js

@@ -0,0 +1,20 @@
+'use strict';
+// 路由配置
+const path = require('path');
+const regPath = path.resolve('app', 'public', 'routerRegister');
+const routerRegister = require(regPath);
+const rkey = 'user';
+const ckey = 'user.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}/:openid`, 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);
+};

+ 16 - 0
app/z_router/utils.js

@@ -0,0 +1,16 @@
+'use strict';
+// 路由配置
+const routerRegister = require('../public/routerRegister');
+const rkey = 'utils';
+const ckey = 'utils';
+const keyZh = '工具';
+const routes = [
+  { method: 'post', path: `${rkey}`, controller: `${ckey}.index`, name: `${ckey}Index`, zh: '工具测试' },
+  { 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

+ 132 - 0
config/config.default.js

@@ -0,0 +1,132 @@
+/* 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://127.0.0.1:14001/wechat/api',
+    wechat: 'https://broadcast.waityou24.cn/wechat/api',
+  };
+  // 微信小程序消息模板
+  config.msgTemplate = {
+    exit: {
+      template_id: 'XC1Is016sqt09_3PsyySYKFtwdrLUqggdn5qIvOiSNI',
+      data: [
+        { key: 'thing1', value: { value: '活动名称' } },
+        { key: 'thing2', value: { value: '项目名称' } },
+        { key: 'time3', value: { value: '申请时间' } },
+        { key: 'amount4', value: { value: '退款金额' } },
+      ],
+    },
+    enroll: {
+      template_id: 'HClmobxtn7b4qunUBF5a5y68cwak8d7VSwqGY0vAx1U',
+      data: [
+        { key: 'thing1', value: { value: '比赛名称' } },
+        { key: 'thing4', value: { value: '赛事类型' } },
+        { key: 'thing5', value: { value: '参赛者姓名' } },
+        { key: 'thing8', value: { value: '报名审核结果' } },
+        { key: 'time2', value: { value: '报名时间' } },
+      ],
+    },
+    remind: {
+      template_id: 'cq3JPX9RMFdEGjH9dBn6n5P5CFCJJ9Q8LIljZlJgBlM',
+      data: [
+        { key: 'thing1', value: { value: '比赛名称' } },
+        { key: 'thing2', value: { value: '比赛时间' } },
+        { key: 'thing4', value: { value: '赛制' } },
+        { key: 'thing7', value: { value: '比赛地点' } },
+        { key: 'thing8', value: { value: '参赛选手' } },
+      ],
+    },
+  };
+
+  // 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 = 'court_v2';
+  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/v2/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 = '赛场-服务-v2';
+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-court-v2",
+  "version": "1.0.0",
+  "description": "新赛场v2",
+  "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.23"
+  },
+  "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);
+  });
+});

+ 28 - 0
test/test.js

@@ -0,0 +1,28 @@
+'use strict';
+const _ = require('lodash');
+
+// 获取总人数
+const number = 10;
+// 按照 一组 4人/5人 计算下有多少组
+const groupPersonNumbers = [ 4, 5 ];
+const result = [];
+console.group(`共:${number}人`);
+for (const num of groupPersonNumbers) {
+  // 商,向下取整
+  const r = _.floor(_.divide(number, num));
+  // 余数
+  const l = number % num;
+  result.push({ r, l, t: num });
+  console.log(`${num}人一组: 商:${r};余:${l}`);
+}
+console.groupEnd(`共:${number}人`);
+
+const res = _.orderBy(result, data => {
+  console.log(data);
+  const { t, l } = data;
+  // 没有余数的,说明恰好分完,先提上去
+  if (l === 0) return l;
+  // 有余数的,计算 余数越大越好
+}, 'asc');
+console.log(res);
+