Bläddra i källkod

班主任,学校,教师.删除对应数据后,将用户信息也删除

lrf 1 år sedan
förälder
incheckning
e0370fe580
3 ändrade filer med 79 tillägg och 95 borttagningar
  1. 1 1
      app/service/headteacher.js
  2. 42 56
      app/service/school.js
  3. 36 38
      app/service/teacher.js

+ 1 - 1
app/service/headteacher.js

@@ -48,7 +48,7 @@ class HeadteacherService extends CrudService {
 
 
   async delete({ id }) {
   async delete({ id }) {
     const res = await this.model.findByIdAndDelete(id);
     const res = await this.model.findByIdAndDelete(id);
-    await this.umodel.deleteOne({ uid: id, thpe: '1' });
+    await this.umodel.deleteOne({ uid: id, type: '1' });
     return res;
     return res;
   }
   }
 
 

+ 42 - 56
app/service/school.js

@@ -38,6 +38,11 @@ class SchoolService extends CrudService {
     }
     }
     return res;
     return res;
   }
   }
+  async delete({ id }) {
+    const res = await this.model.findByIdAndDelete(id);
+    await this.umodel.deleteOne({ uid: id, type: '2' });
+    return res;
+  }
 
 
   async query({ name, ...data }, { skip, limit }) {
   async query({ name, ...data }, { skip, limit }) {
     const query = { ...data };
     const query = { ...data };
@@ -47,10 +52,10 @@ class SchoolService extends CrudService {
     let res = await this.model.find(query).skip(parseInt(skip)).limit(parseInt(limit));
     let res = await this.model.find(query).skip(parseInt(skip)).limit(parseInt(limit));
     if (res && res.length > 0) {
     if (res && res.length > 0) {
       res = JSON.parse(JSON.stringify(res));
       res = JSON.parse(JSON.stringify(res));
-      const ids = res.map(i => i._id);
+      const ids = res.map((i) => i._id);
       const users = await this.umodel.find({ uid: { $in: ids } }, '+passwd');
       const users = await this.umodel.find({ uid: { $in: ids } }, '+passwd');
       for (const tea of res) {
       for (const tea of res) {
-        const r = users.find(f => f.uid === tea._id);
+        const r = users.find((f) => f.uid === tea._id);
         if (r) {
         if (r) {
           const passwd = _.get(r.passwd, 'secret');
           const passwd = _.get(r.passwd, 'secret');
           if (passwd) tea.passwd = passwd;
           if (passwd) tea.passwd = passwd;
@@ -85,8 +90,12 @@ class SchoolService extends CrudService {
     let dbStuList = await this.ctx.model.Student.find({ termid, batchid, schid });
     let dbStuList = await this.ctx.model.Student.find({ termid, batchid, schid });
     if (dbStuList.length > 0) {
     if (dbStuList.length > 0) {
       // 查这个学校的这期学生是否修改过班级 或 寝室
       // 查这个学校的这期学生是否修改过班级 或 寝室
-      const is_change = dbStuList.find(f => f.classid || f.bedroomid);
-      if (is_change) throw new BusinessError(ErrorCode.BUSINESS, '上报过的学生已经安排班级或寝室!若需要替换学生,让同性别的学生直接来和班主任说,修改信息即可.若还是有疑问,请和中心负责人联系(最好联系下)');
+      const is_change = dbStuList.find((f) => f.classid || f.bedroomid);
+      if (is_change)
+        throw new BusinessError(
+          ErrorCode.BUSINESS,
+          '上报过的学生已经安排班级或寝室!若需要替换学生,让同性别的学生直接来和班主任说,修改信息即可.若还是有疑问,请和中心负责人联系(最好联系下)'
+        );
     }
     }
     // 2021-06-07 如果学生已经绑定,那也不允许修改名单了
     // 2021-06-07 如果学生已经绑定,那也不允许修改名单了
     const countOpenid = await this.ctx.model.Student.count({ termid, batchid, schid, openid: { $exists: true } });
     const countOpenid = await this.ctx.model.Student.count({ termid, batchid, schid, openid: { $exists: true } });
@@ -154,7 +163,7 @@ class SchoolService extends CrudService {
       // 复制,删除,添加
       // 复制,删除,添加
       if (dbStuList.length > 0) {
       if (dbStuList.length > 0) {
         dbStuList = JSON.parse(JSON.stringify(dbStuList));
         dbStuList = JSON.parse(JSON.stringify(dbStuList));
-        dbStuList = dbStuList.map(i => {
+        dbStuList = dbStuList.map((i) => {
           delete i.meta;
           delete i.meta;
           i.studentid = _.clone(i._id);
           i.studentid = _.clone(i._id);
           delete i.id;
           delete i.id;
@@ -201,8 +210,10 @@ class SchoolService extends CrudService {
   async getschnum(plan, schid, batchid) {
   async getschnum(plan, schid, batchid) {
     const schtime = await this.schmodel.findOne({ schid, planid: plan.id });
     const schtime = await this.schmodel.findOne({ schid, planid: plan.id });
     const { arrange } = schtime;
     const { arrange } = schtime;
-    const r = arrange.find(f => f.batchid === batchid);
-    if (!r) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '没有找到该学校的计划'); }
+    const r = arrange.find((f) => f.batchid === batchid);
+    if (!r) {
+      throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '没有找到该学校的计划');
+    }
     const { number } = r;
     const { number } = r;
     return parseInt(number);
     return parseInt(number);
   }
   }
@@ -228,9 +239,9 @@ class SchoolService extends CrudService {
     headRow.eachCell((cell, coli) => {
     headRow.eachCell((cell, coli) => {
       console.log(cell.value);
       console.log(cell.value);
       if (cell.value !== '序号') {
       if (cell.value !== '序号') {
-        const r = cols.find(f => f.key === cell.value);
+        const r = cols.find((f) => f.key === cell.value);
         if (r) {
         if (r) {
-          const ri = cols.findIndex(f => f.key === cell.value);
+          const ri = cols.findIndex((f) => f.key === cell.value);
           // 表头符合要求,做上标记
           // 表头符合要求,做上标记
           r.colIndex = coli;
           r.colIndex = coli;
           cols[ri] = r;
           cols[ri] = r;
@@ -240,14 +251,14 @@ class SchoolService extends CrudService {
       }
       }
     });
     });
     // 检查表头结果,如果有没有 colIndex,说明表头里有不符合要求的,退回去
     // 检查表头结果,如果有没有 colIndex,说明表头里有不符合要求的,退回去
-    const excelIsRigth = cols.every(f => f.colIndex);
+    const excelIsRigth = cols.every((f) => f.colIndex);
     if (!excelIsRigth) throw new BusinessError(ErrorCode.DATA_INVALID, 'Excel表格格式不正确,请使用系统提供的模板,或重新下载模板!');
     if (!excelIsRigth) throw new BusinessError(ErrorCode.DATA_INVALID, 'Excel表格格式不正确,请使用系统提供的模板,或重新下载模板!');
     // 删除掉第一行 表头行,这不是数据
     // 删除掉第一行 表头行,这不是数据
     worksheet.spliceRows(0, 1);
     worksheet.spliceRows(0, 1);
     const stuList = [];
     const stuList = [];
-    const noWhite = str => str.replace(/\s*/g, '');
+    const noWhite = (str) => str.replace(/\s*/g, '');
     // 整理数据,根据检查合格的表头行,获取每个格子的数据,制成[object]格式
     // 整理数据,根据检查合格的表头行,获取每个格子的数据,制成[object]格式
-    worksheet.eachRow(row => {
+    worksheet.eachRow((row) => {
       const stu = {};
       const stu = {};
       for (let i = 0; i < cols.length; i++) {
       for (let i = 0; i < cols.length; i++) {
         const col = cols[i];
         const col = cols[i];
@@ -260,7 +271,6 @@ class SchoolService extends CrudService {
       stuList.push(stu);
       stuList.push(stu);
     });
     });
     return stuList;
     return stuList;
-
   }
   }
   // 数据校验
   // 数据校验
   async checkData(stuList) {
   async checkData(stuList) {
@@ -304,7 +314,7 @@ class SchoolService extends CrudService {
           //   error = true;
           //   error = true;
           //   msg = `${msg}学生已存在`;
           //   msg = `${msg}学生已存在`;
           // }
           // }
-          const have_same = stuList.filter(f => f.id_number === val && f.name !== name);
+          const have_same = stuList.filter((f) => f.id_number === val && f.name !== name);
           if (have_same.length > 0) {
           if (have_same.length > 0) {
             error = true;
             error = true;
             const h = _.head(have_same);
             const h = _.head(have_same);
@@ -328,7 +338,7 @@ class SchoolService extends CrudService {
           //   error = true;
           //   error = true;
           //   msg = `${msg}学生库中已有该手机号,请检查手机号是否正确,若无误,请联系中心负责人`;
           //   msg = `${msg}学生库中已有该手机号,请检查手机号是否正确,若无误,请联系中心负责人`;
           // }
           // }
-          const have_same = stuList.filter(f => f.phone === val && f.name !== name);
+          const have_same = stuList.filter((f) => f.phone === val && f.name !== name);
           if (have_same.length > 0) {
           if (have_same.length > 0) {
             error = true;
             error = true;
             const h = _.head(have_same);
             const h = _.head(have_same);
@@ -393,15 +403,15 @@ class SchoolService extends CrudService {
   // 最后整合数据
   // 最后整合数据
   lastSetData(stuList, data) {
   lastSetData(stuList, data) {
     const cols = this.getStucolumn();
     const cols = this.getStucolumn();
-    const needChange = cols.filter(f => f.change);
-    stuList = stuList.map(i => {
+    const needChange = cols.filter((f) => f.change);
+    stuList = stuList.map((i) => {
       const d = { ...i, ...data };
       const d = { ...i, ...data };
       for (const col of needChange) {
       for (const col of needChange) {
         const { column, change } = col;
         const { column, change } = col;
         if (!column && change && _.isArray(change)) continue;
         if (!column && change && _.isArray(change)) continue;
         const val = _.get(d, column);
         const val = _.get(d, column);
         if (!val) continue;
         if (!val) continue;
-        const r = change.find(f => f.key === val);
+        const r = change.find((f) => f.key === val);
         if (!r) continue;
         if (!r) continue;
         const { value } = r;
         const { value } = r;
         d[column] = value;
         d[column] = value;
@@ -448,8 +458,7 @@ class SchoolService extends CrudService {
     return arr;
     return arr;
   }
   }
 
 
-
-  // 导出学校名单
+  // 导出学校名单 TODO:bug
   async exportSchool({ trainplanId }) {
   async exportSchool({ trainplanId }) {
     // 批次期次都在这里面
     // 批次期次都在这里面
     const trainplan = await this.tmodel.find({ _id: trainplanId });
     const trainplan = await this.tmodel.find({ _id: trainplanId });
@@ -458,30 +467,13 @@ class SchoolService extends CrudService {
     const _data = trainplan;
     const _data = trainplan;
     const headers = _headers
     const headers = _headers
       .map(({ title }) => title)
       .map(({ title }) => title)
-      .map((v, i) =>
-        Object.assign({}, { v, position: String.fromCharCode(65 + i) + 1 })
-      )
-      .reduce(
-        (prev, next) =>
-          Object.assign({}, prev, { [next.position]: { v: next.v } }),
-        {}
-      );
+      .map((v, i) => Object.assign({}, { v, position: String.fromCharCode(65 + i) + 1 }))
+      .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});
 
 
     const data = _data
     const data = _data
-      .map((v, i) =>
-        _headers.map(({ key }, j) =>
-          Object.assign(
-            {},
-            { v: v[key], position: String.fromCharCode(65 + j) + (i + 2) }
-          )
-        )
-      )
+      .map((v, i) => _headers.map(({ key }, j) => Object.assign({}, { v: v[key], position: String.fromCharCode(65 + j) + (i + 2) })))
       .reduce((prev, next) => prev.concat(next))
       .reduce((prev, next) => prev.concat(next))
-      .reduce(
-        (prev, next) =>
-          Object.assign({}, prev, { [next.position]: { v: next.v } }),
-        {}
-      );
+      .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});
 
 
     // 合并 headers 和 data
     // 合并 headers 和 data
     const output = Object.assign({}, headers, data);
     const output = Object.assign({}, headers, data);
@@ -494,12 +486,11 @@ class SchoolService extends CrudService {
 
 
     // 构建 workbook 对象
     // 构建 workbook 对象
     const nowDate = new Date().getTime();
     const nowDate = new Date().getTime();
-    const path =
-      'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
-    const respath =
-      'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
+    // TODO: 地址有问题,需要引用config变量
+    const path = 'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
+    const respath = 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
     const wb = {
     const wb = {
-      SheetNames: [ 'sheet0' ],
+      SheetNames: ['sheet0'],
       Sheets: { sheet0: Object.assign({}, output, { '!ref': ref }) },
       Sheets: { sheet0: Object.assign({}, output, { '!ref': ref }) },
     };
     };
     // 导出 Excel
     // 导出 Excel
@@ -584,12 +575,7 @@ class SchoolService extends CrudService {
       pass: true,
       pass: true,
       msg: '验证成功',
       msg: '验证成功',
     };
     };
-    if (
-      !code ||
-      !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(
-        code
-      )
-    ) {
+    if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(code)) {
       row = {
       row = {
         pass: false,
         pass: false,
         msg: '身份证号格式错误',
         msg: '身份证号格式错误',
@@ -601,13 +587,13 @@ class SchoolService extends CrudService {
       };
       };
     } else {
     } else {
       // 18位身份证需要验证最后一位校验位
       // 18位身份证需要验证最后一位校验位
-      if (code.length == 18) {
+      if (code.length === 18) {
         code = code.split('');
         code = code.split('');
         // ∑(ai×Wi)(mod 11)
         // ∑(ai×Wi)(mod 11)
         // 加权因子
         // 加权因子
-        const factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
+        const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
         // 校验位
         // 校验位
-        const parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
+        const parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
         let sum = 0;
         let sum = 0;
         let ai = 0;
         let ai = 0;
         let wi = 0;
         let wi = 0;
@@ -616,7 +602,7 @@ class SchoolService extends CrudService {
           wi = factor[i];
           wi = factor[i];
           sum += ai * wi;
           sum += ai * wi;
         }
         }
-        if (parity[sum % 11] != code[17].toUpperCase()) {
+        if (parity[sum % 11] !== code[17].toUpperCase()) {
           row = {
           row = {
             pass: false,
             pass: false,
             msg: '身份证号校验位错误',
             msg: '身份证号校验位错误',

+ 36 - 38
app/service/teacher.js

@@ -1,6 +1,5 @@
 'use strict';
 'use strict';
 
 
-
 const assert = require('assert');
 const assert = require('assert');
 const _ = require('lodash');
 const _ = require('lodash');
 const moment = require('moment');
 const moment = require('moment');
@@ -8,7 +7,7 @@ const XLSX = require('xlsx');
 const { CrudService } = require('naf-framework-mongoose/lib/service');
 const { CrudService } = require('naf-framework-mongoose/lib/service');
 const { BusinessError, ErrorCode } = require('naf-core').Error;
 const { BusinessError, ErrorCode } = require('naf-core').Error;
 const stringRandom = require('string-random');
 const stringRandom = require('string-random');
-
+const { ObjectId } = require('mongoose').Types;
 
 
 class TeacherService extends CrudService {
 class TeacherService extends CrudService {
   constructor(ctx) {
   constructor(ctx) {
@@ -24,10 +23,7 @@ class TeacherService extends CrudService {
     if (name) {
     if (name) {
       query.name = { $regex: name };
       query.name = { $regex: name };
     }
     }
-    let res = await this.model
-      .find(query)
-      .skip(Number(skip))
-      .limit(Number(limit));
+    let res = await this.model.find(query).skip(Number(skip)).limit(Number(limit));
     res = JSON.parse(JSON.stringify(res));
     res = JSON.parse(JSON.stringify(res));
     for (const tea of res) {
     for (const tea of res) {
       const r = await this.umodel.findOne({ uid: tea._id }, '+passwd');
       const r = await this.umodel.findOne({ uid: tea._id }, '+passwd');
@@ -58,6 +54,33 @@ class TeacherService extends CrudService {
     // 将文件拼到查询到的数据后
     // 将文件拼到查询到的数据后
     return await this.model.findById(id, '+file');
     return await this.model.findById(id, '+file');
   }
   }
+  async create(data) {
+    const { name, mobile } = data;
+    const user = await this.umodel.findOne({ mobile });
+    if (user) {
+      throw new BusinessError(ErrorCode.DATA_EXIST, '电话已经存在');
+    }
+    // 创建教师信息
+    const res = await this.model.create(data);
+    // 再创建教师用户
+    const passwd = stringRandom();
+    const newdata = {
+      name,
+      mobile,
+      type: '3',
+      uid: ObjectId(res.id || res._id).toString(),
+      passwd: { secret: passwd },
+    };
+    await this.umodel.create(newdata);
+    // 返回教师信息
+    return this.model.findById(res._id || res.id);
+  }
+
+  async delete({ id }) {
+    const res = await this.model.findByIdAndDelete(id);
+    await this.umodel.deleteOne({ uid: id, type: '3' });
+    return res;
+  }
 
 
   // 批量查询教师
   // 批量查询教师
   async fetchteachers({ ids }) {
   async fetchteachers({ ids }) {
@@ -80,21 +103,10 @@ class TeacherService extends CrudService {
       await teacher.save();
       await teacher.save();
       let detail = '';
       let detail = '';
       if (status === '1') {
       if (status === '1') {
-        const passwd = stringRandom();
-        detail =
-          '您的账号身份已确认,密码为:' +
-          passwd +
-          '请尽快登录账号上传课件资料附件';
-        // 状态更新后创建教师用户
-        const newdata = {
-          name: teacher.name,
-          mobile: teacher.phone,
-          type: '3',
-          uid: teacher.id,
-          gender: teacher.gender,
-          passwd,
-        };
-        await this.ctx.service.user.create(newdata);
+        const userInfo = await this.umodel.findOne({ uid: teacherid }, '+passwd');
+        if (!userInfo) continue;
+        const passwd = _.get(userInfo, 'passwd.secret');
+        detail = '您的账号身份已确认,密码为:' + passwd + '请尽快登录账号上传课件资料附件';
       } else if (status === '4') {
       } else if (status === '4') {
         detail = '您已通过审核被正式录入教师库';
         detail = '您已通过审核被正式录入教师库';
       }
       }
@@ -103,21 +115,9 @@ class TeacherService extends CrudService {
       const user = await this.umodel.findOne({ uid: teacher.id, type: '3' });
       const user = await this.umodel.findOne({ uid: teacher.id, type: '3' });
 
 
       if (user && user.openid) {
       if (user && user.openid) {
-        await this.ctx.service.weixin.sendTemplateMsg(
-          this.ctx.app.config.REVIEW_TEMPLATE_ID,
-          user.openid,
-          '您有一个新的通知',
-          detail,
-          date,
-          remark
-        );
+        await this.ctx.service.weixin.sendTemplateMsg(this.ctx.app.config.REVIEW_TEMPLATE_ID, user.openid, '您有一个新的通知', detail, date, remark);
       } else {
       } else {
-        await this.ctx.service.util.sendMail(
-          teacher.email,
-          '账号审核',
-          detail,
-          ''
-        );
+        await this.ctx.service.util.sendMail(teacher.email, '账号审核', detail, '');
       }
       }
     }
     }
   }
   }
@@ -258,9 +258,7 @@ class TeacherService extends CrudService {
       const res = await this.ctx.service.util.toExcel(data, head, fn);
       const res = await this.ctx.service.util.toExcel(data, head, fn);
       console.log(res);
       console.log(res);
       if (!res) {
       if (!res) {
-        console.error(
-          `${moment().format('YYYY-MM-DD HH:mm:ss')} ${fn} 导出失败`
-        );
+        console.error(`${moment().format('YYYY-MM-DD HH:mm:ss')} ${fn} 导出失败`);
         throw new BusinessError(ErrorCode.SERVICE_FAULT, `${fn}导出失败`);
         throw new BusinessError(ErrorCode.SERVICE_FAULT, `${fn}导出失败`);
       }
       }
       this.ctx.service.util.updateProcess(missionid, '100', '2', {
       this.ctx.service.util.updateProcess(missionid, '100', '2', {