class.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const { ObjectId } = require('mongoose').Types;
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. class ClassService extends CrudService {
  8. constructor(ctx) {
  9. super(ctx, 'class');
  10. this.model = this.ctx.model.Class;
  11. this.stumodel = this.ctx.model.Student;
  12. this.lessmodel = this.ctx.model.Lesson;
  13. this.umodel = this.ctx.model.User;
  14. this.tmodel = this.ctx.model.Trainplan;
  15. this.gmodel = this.ctx.model.Group;
  16. this.heamodel = this.ctx.model.Headteacher;
  17. this.teamodel = this.ctx.model.Teacher;
  18. this.locamodel = this.ctx.model.Location;
  19. }
  20. async divide(data) {
  21. // 21-04-27重做
  22. const { planid, termid } = data;
  23. assert(planid, '计划id为必填项');
  24. assert(termid, '期id为必填项');
  25. // 先自动生成班级 TODO:之后放开
  26. await this.autoclass(planid, termid);
  27. // 根据计划id与期id查询所有批次下的班级
  28. const newclass = await this.model.find({ planid, termid });
  29. if (!newclass) {
  30. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '班级信息不存在');
  31. }
  32. // 根据计划和期查询所有上报的学生 并按照学校排序
  33. const newstudent = await this.stumodel.find({ termid }).sort({ schid: 1 });
  34. if (!newstudent) {
  35. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '学生信息不存在');
  36. }
  37. // 按批次分组,每个批次处理自己的
  38. const claGroup = _.groupBy(newclass, 'batchid');
  39. const keys = Object.keys(claGroup);
  40. const result = {}; // key:班级id;value:学生id数组
  41. // 循环批次
  42. for (const bkey of keys) {
  43. const classList = claGroup[bkey]; // 该批次下的班级列表
  44. const batchStudentList = _.shuffle(newstudent.filter(f => f.batchid === bkey)); // shuffle:打乱顺序 该批次下的学生列表
  45. // 分为多个学校 男/女 数组
  46. // 按学校分组
  47. const sgroup = _.groupBy(batchStudentList, 'schid');
  48. // 学校代码key
  49. const schKeys = Object.keys(sgroup);
  50. let solve = {};
  51. const studentGroup = {}; // key:学校id-boy/girl;value:对应学校,性别的学生列表
  52. const classnum = classList.length; // 班级数
  53. const minClass = _.minBy(classList, i => parseInt(i.number)); // 该批次人数最少的班级
  54. let minNumber = 0;
  55. if (minClass) minNumber = parseInt(minClass.number);
  56. for (const skey of schKeys) {
  57. const schstus = sgroup[skey];
  58. // 获得每个学校的男/女人数
  59. const boys = schstus.filter(f => f.gender.includes('男'));
  60. const girls = schstus.filter(f => f.gender.includes('女'));
  61. studentGroup[`${skey}-boy`] = boys;
  62. studentGroup[`${skey}-girl`] = girls;
  63. // 算出平均分配解:每个 学校 固定向 每个班 派多少 男/女生
  64. // 需要验证最少的班级人数:因为平均后,可能造成人多了,要吐出来的
  65. const br = this.numDivide(boys.length, classnum);
  66. const gr = this.numDivide(girls.length, classnum);
  67. // 存入最佳计算结果,但是需要验证,看看这批次的计算结果是否<=班级最少人数;多了可是要吐人的.吐人的写法代码更多
  68. solve[`${skey}-boy`] = br;
  69. solve[`${skey}-girl`] = gr;
  70. }
  71. // 验证最佳结果是否超出班级的最少人数,不是,则处理
  72. // console.log('计算最优解');
  73. solve = this.checkSolve(solve, minNumber, classnum);
  74. // 塞人
  75. // console.log('塞人前');
  76. for (const c of classList) {
  77. const { _id } = c;
  78. if (!(result[_id] && _.isArray(result[_id]))) result[_id] = [];
  79. for (const key in solve) {
  80. const { res } = solve[key];
  81. let sList = studentGroup[key];
  82. // 取出指定人数
  83. const inputs = _.take(sList, res);
  84. // 放进结果里
  85. // .map(i => i._id)
  86. result[_id].push(...inputs);
  87. // 删除指定人数
  88. sList = _.drop(sList, res);
  89. // 赋值回去
  90. studentGroup[key] = sList;
  91. }
  92. }
  93. // console.log('塞人后');
  94. // console.log('补人前');
  95. // 检查是否有学生剩余,如果有学生剩余,都需要继续进行人的处理,无论是补人还是加人.
  96. let els = _.flatten(Object.values(studentGroup)).length;
  97. // 没有剩余的学生,下面也没法处理,结束了(跳过while了)
  98. while (els > 0) {
  99. // 还有学生,那就需要继续处理,看看是补人还是加人
  100. // 检查各个班级是否达到人数要求
  101. const { ok, not } = this.checkClassStatus(result, classList);
  102. // 如果not里有值,说明还有班级没满足人数要求->补人
  103. // 如果not没有值,说明参培人员多了->分到每个班里
  104. if (not.length > 0) {
  105. // 进行补人
  106. // not中的每个班进行补人,每个班补一个人(result[classid]加人),studentGroup[key]减人
  107. // 如果没人了,break;
  108. for (const c of not) {
  109. // 需要计算出这个班补人的最优解
  110. const { _id } = c;
  111. const stuList = result[_id];
  112. const claSolve = this.getClassSolve(stuList);
  113. // 根据solve结果,取对应的值,然后做加减
  114. for (const s of claSolve) {
  115. const { schid, gender } = s;
  116. let midList = studentGroup[`${schid}-${gender}`];
  117. if (midList.length <= 0) continue;
  118. const head = _.head(midList);
  119. result[_id].push(head);
  120. midList = _.drop(midList);
  121. studentGroup[`${schid}-${gender}`] = midList;
  122. break;// 一次,一班只补一个的重要关键词
  123. }
  124. }
  125. } else {
  126. // 额外加人
  127. // 说明下这里为什么要ok:因为在上面的solve,强制以班级最少的人数为均分标准
  128. // 所以在班级人数不均等的情况下,出现某班均分完是正好的人数,剩下的班少人,但这时还得先把少人的班先补上才能均摊多的人
  129. // 为什么要说明,因为下面代码除了循环的 数组 外,都一样啊
  130. for (const c of ok) {
  131. // 需要计算出这个班补人的最优解
  132. const { _id } = c;
  133. const stuList = result[_id];
  134. const claSolve = this.getClassSolve(stuList);
  135. // 根据solve结果,取对应的值,然后做加减
  136. for (const s of claSolve) {
  137. const { schid, gender } = s;
  138. let midList = studentGroup[`${schid}-${gender}`];
  139. if (midList.length <= 0) continue;
  140. const head = _.head(midList);
  141. result[_id].push(head);
  142. midList = _.drop(midList);
  143. studentGroup[`${schid}-${gender}`] = midList;
  144. break;
  145. }
  146. }
  147. }
  148. // 重新计算人数,就是上面的els计算再执行一次
  149. els = _.flatten(Object.values(studentGroup)).length;
  150. }
  151. }
  152. // for (const key in result) {
  153. // console.group(key);
  154. // const list = result[key];
  155. // const b = list.filter(f => f.gender === '男');
  156. // const g = list.filter(f => f.gender === '女');
  157. // console.log(list.length, b.length, g.length);
  158. // console.groupEnd();
  159. // }
  160. // 更新学生的班级
  161. const ckeys = Object.keys(result);
  162. for (const classid of ckeys) {
  163. await this.stumodel.updateMany({ _id: result[classid] }, { classid });
  164. }
  165. // 新添,给学生排序号
  166. const claList = await this.model.find({ termid });
  167. for (const cla of claList) {
  168. await this.ctx.service.student.arrangeNumber({ classid: cla._id });
  169. }
  170. }
  171. /**
  172. * 获取某班补人的最优解列表
  173. * @param {Array} list 某班级的学生列表
  174. */
  175. getClassSolve(list) {
  176. // 因为按总人数的最优解已经均分过了,所以此处只计算,如何让该班平衡的最优解,不考虑整体了
  177. const schGroup = _.groupBy(list, 'schid');
  178. const midArr = [];
  179. for (const key in schGroup) {
  180. const midList = schGroup[key];
  181. const bl = midList.filter(f => f.gender === '男');
  182. midArr.push({ schid: key, gender: 'boy', number: bl.length });
  183. const gl = midList.filter(f => f.gender === '女');
  184. midArr.push({ schid: key, gender: 'girl', number: gl.length });
  185. }
  186. // 按 人数升序, 性别先男后女
  187. return _.orderBy(midArr, [ 'number', 'gender' ], [ 'asc', 'desc' ]);
  188. }
  189. /**
  190. * 检查班级是否达到人数
  191. * @param {Array} alreadyList 已分配的列表
  192. * @param {Array} classList 班级列表
  193. */
  194. checkClassStatus(alreadyList, classList) {
  195. let ok = []; // 已经满足人数的班级
  196. const not = []; // 未满足人数的班级
  197. for (const c of classList) {
  198. const { _id, number } = c;
  199. const nowNum = alreadyList[_id].length;
  200. if (nowNum < number) not.push(c); else ok.push(c);
  201. }
  202. // 需要排序,需要按上限人数排列,把人少的放上面
  203. ok = _.orderBy(ok, [ 'number' ], [ 'asc' ]);
  204. return { ok, not };
  205. }
  206. /**
  207. * 算整除和取余
  208. * @param {Any} num1 性别人数
  209. * @param {Any} num2 班级人数
  210. * @property {Number} res 整除结果
  211. * @property {Number} el 余数
  212. */
  213. numDivide(num1, num2) {
  214. num1 = _.isNaN(parseInt(num1)) ? 0 : parseInt(num1);
  215. num2 = _.isNaN(parseInt(num2)) ? 0 : parseInt(num2);
  216. const res = _.floor(num1 / num2, 0);
  217. const el = num1 % num2;
  218. return { res, el };
  219. }
  220. /**
  221. * 验证计算结果是否 不超过 最少人数班级的人数
  222. * @param {Object} solve 计算结果:key:${schid}-${gender}
  223. * @param {Number} number 最少人数班级的人数
  224. * @param {Number} classnum 班级数量,如果需要减人数的话,是要将每班的人数减1,-1就意味着要 - 班级数 *1;余数+班级数*1
  225. */
  226. checkSolve(solve, number, classnum) {
  227. let countClassNum = 0;
  228. let ns = [];
  229. for (const key in solve) {
  230. const { res = 0, el = 0 } = _.get(solve, key, {});
  231. countClassNum += res;
  232. ns.push({ res, el, key });
  233. }
  234. if (countClassNum <= number) return solve;
  235. do {
  236. ns = _.orderBy(ns, [ 'res' ], [ 'desc' ]);
  237. const head = _.head(ns);
  238. head.res--;
  239. head.el += classnum;
  240. ns[0] = head;
  241. countClassNum = ns.reduce((p, n) => p + n.res, 0);
  242. } while (countClassNum > number);
  243. for (const i of ns) {
  244. const { key, ...others } = i;
  245. solve[key] = { ...others };
  246. }
  247. return solve;
  248. }
  249. // 取得同样类型的学生
  250. async getstutype(_students, type) {
  251. const data = [];
  252. for (const stuid of _students) {
  253. const student = await this.stumodel.findById(stuid);
  254. if (student && student.type === type) {
  255. data.push(stuid);
  256. }
  257. }
  258. return data;
  259. }
  260. // 自动生成班级私有方法
  261. async autoclass(planid, termid) {
  262. // 删除所有计划下的班级
  263. await this.model.deleteMany({ planid, termid });
  264. // 删除该期课表
  265. await this.lessmodel.deleteMany({ termid });
  266. // 根据批次id取得当前批次具体信息
  267. const res = await this.tmodel.findById(planid);
  268. if (!res) {
  269. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  270. }
  271. // 循环出所有班级进行添加操作
  272. const term = await res.termnum.id(termid);
  273. for (const batch of term.batchnum) {
  274. const classs = await batch.class;
  275. for (const cla of classs) {
  276. const newdata = { name: cla.name, number: cla.number, batchid: batch.id, termid: term.id, planid: res.id, type: cla.type };
  277. const rescla = await this.model.create(newdata);
  278. await this.toSetClassSetting({ classid: rescla._id });
  279. }
  280. }
  281. }
  282. // 根据传入的学生列表和班级id更新学生信息
  283. async studentup(classid, batchid, beforestu) {
  284. // 循环学生id
  285. for (const stuid of beforestu) {
  286. const student = await this.stumodel.findById(stuid);
  287. if (student) {
  288. student.classid = classid;
  289. student.batchid = batchid;
  290. await student.save();
  291. }
  292. }
  293. }
  294. // 自动分组
  295. async groupcreate(termid, batchid, classid) {
  296. const group = await this.gmodel.find({ termid, batchid, classid });
  297. if (group.length === 0) {
  298. for (let i = 1; i < 8; i++) {
  299. const name = i + '组';
  300. const newdata = { name, termid, batchid, classid };
  301. await this.gmodel.create(newdata);
  302. }
  303. }
  304. }
  305. // 根据传入的学生列表和班级id更新学生信息
  306. async studentupclass({ id }, data) {
  307. assert(id, '班级id为必填项');
  308. // 根据全年计划表id查出对应的全年计划详细信息
  309. const trainplan = await this.tmodel.findOne({ 'termnum.batchnum.class._id': ObjectId(id) });
  310. if (!trainplan) {
  311. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  312. }
  313. // 取得计划期批次信息
  314. let termid = '';
  315. let batchid = '';
  316. let classname = '';
  317. let class_ = {};
  318. for (const term of trainplan.termnum) {
  319. for (const batch of term.batchnum) {
  320. const _class = await batch.class.id(id);
  321. if (_class) {
  322. termid = term.id;
  323. batchid = batch.id;
  324. classname = _class.name;
  325. class_ = _class;
  326. break;
  327. }
  328. }
  329. }
  330. if (!class_) {
  331. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '班级信息不存在');
  332. }
  333. let classid_ = '';
  334. if (classname) {
  335. const cla_ = await this.model.findOne({ termid, batchid, name: classname });
  336. if (cla_) {
  337. classid_ = cla_.id;
  338. } else {
  339. const newdata = {
  340. name: class_.name,
  341. number: class_.number,
  342. batchid,
  343. termid,
  344. planid: trainplan.id,
  345. type: class_.type,
  346. headteacherid: class_.headteacherid,
  347. };
  348. const rescla = await this.model.create(newdata);
  349. if (rescla) {
  350. classid_ = rescla.id;
  351. }
  352. }
  353. }
  354. if (classid_) {
  355. // 循环学生id
  356. for (const stuid of data) {
  357. const student = await this.stumodel.findById(stuid);
  358. if (student) {
  359. student.classid = classid_;
  360. await student.save();
  361. }
  362. }
  363. }
  364. // 添加,给学生排序号
  365. await this.ctx.service.student.arrangeNumber({ classid: classid_ });
  366. // TODO 根据模板复制班级信息
  367. await this.toSetClassSetting({ classid: classid_ });
  368. }
  369. async notice(data) {
  370. for (const classid of data.classids) {
  371. // 根据班级id找到需要通知的班级
  372. const _class = await this.model.findById(classid);
  373. const { headteacherid } = _class;
  374. // 根据班级id找到对应的课程表
  375. const lesson = await this.lessmodel.findOne({ classid });
  376. if (lesson) {
  377. const lessons = lesson.lessons;
  378. const remark = '感谢您的使用';
  379. const date = await this.ctx.service.util.updatedate();
  380. const detail = '班级各项信息已确认,请注意查收';
  381. // 遍历班级授课教师发送通知
  382. for (const lessoninfo of lessons) {
  383. const teaid = lessoninfo.teaid;
  384. const _teacher = await this.umodel.findOne({ uid: teaid, type: '3' });
  385. if (_teacher) {
  386. const teaopenid = _teacher.openid;
  387. this.ctx.service.weixin.sendTemplateMsg(this.ctx.app.config.REVIEW_TEMPLATE_ID, teaopenid, '您有一个新的通知', detail, date, remark, classid);
  388. }
  389. }
  390. // 给班主任发送通知
  391. const _headteacher = await this.umodel.findOne({ uid: headteacherid, type: '1' });
  392. if (_headteacher) {
  393. const headteaopenid = _headteacher.openid;
  394. this.ctx.service.weixin.sendTemplateMsg(this.ctx.app.config.REVIEW_TEMPLATE_ID, headteaopenid, '您有一个新的通知', detail, date, remark, classid);
  395. }
  396. // 根据班级的期id查询对应的培训计划
  397. const trainplan = await this.tmodel.findOne({ 'termnum._id': _class.termid });
  398. const term = await trainplan.termnum.id(_class.termid);
  399. const batch = await term.batchnum.id(_class.batchid);
  400. const startdate = batch.startdate;
  401. const classname = _class.name;
  402. // 给班级所有学生发送邮件通知
  403. const students = await this.stumodel.find({ classid });
  404. for (const student of students) {
  405. const { email, name } = student;
  406. const subject = '吉林省高等学校毕业生就业指导中心通知';
  407. const text = name + '您好!\n欢迎参加由吉林省高等学校毕业生就业指导中心举办的“双困生培训会”。\n您所在的班级为:' + classname + '\n班级开课时间为:' + startdate;
  408. this.ctx.service.util.sendMail(email, subject, text);
  409. }
  410. }
  411. }
  412. }
  413. async uptea(data) {
  414. for (const _data of data) {
  415. const classInfo = await this.model.findById(_data.id);
  416. classInfo.headteacherid = _data.headteacherid;
  417. await classInfo.save();
  418. }
  419. }
  420. async query({ skip, limit, ...info }) {
  421. const classes = await this.model
  422. .find(info)
  423. .populate([
  424. {
  425. path: 'yclocationid',
  426. model: 'Location',
  427. select: 'name',
  428. },
  429. {
  430. path: 'kzjhlocationid',
  431. model: 'Location',
  432. select: 'name',
  433. },
  434. {
  435. path: 'kbyslocationid',
  436. model: 'Location',
  437. select: 'name',
  438. },
  439. {
  440. path: 'jslocationid',
  441. model: 'Location',
  442. select: 'name',
  443. },
  444. {
  445. path: 'headteacherid',
  446. model: 'Headteacher',
  447. select: 'name',
  448. },
  449. ])
  450. .skip(Number(skip))
  451. .limit(Number(limit));
  452. const data = [];
  453. let planids = classes.map(i => i.planid);
  454. planids = _.uniq(planids);
  455. const trainplan = await this.tmodel.find({ _id: { $in: planids } });
  456. for (const _class of classes) {
  457. let res = await this.setClassData(_class, trainplan);
  458. if (res) {
  459. res = this.setData(res);
  460. data.push(res);
  461. } else {
  462. data.push(_class);
  463. }
  464. }
  465. return data;
  466. }
  467. async fetch({ id }) {
  468. let classInfo = await this.model.findById(id).populate([
  469. {
  470. path: 'yclocationid',
  471. model: 'Location',
  472. select: 'name',
  473. },
  474. {
  475. path: 'kzjhlocationid',
  476. model: 'Location',
  477. select: 'name',
  478. },
  479. {
  480. path: 'kbyslocationid',
  481. model: 'Location',
  482. select: 'name',
  483. },
  484. {
  485. path: 'jslocationid',
  486. model: 'Location',
  487. select: 'name',
  488. },
  489. {
  490. path: 'headteacherid',
  491. model: 'Headteacher',
  492. select: 'name',
  493. },
  494. ]);
  495. const trainplan = await this.tmodel.findById(classInfo.planid);
  496. classInfo = await this.setClassData(classInfo, [ trainplan ]);
  497. classInfo = this.setData(classInfo);
  498. return classInfo;
  499. }
  500. // 整理数据,找礼仪教师
  501. async setClassData(cla, trainplan) {
  502. const { planid, termid, batchid } = cla;
  503. cla = JSON.parse(JSON.stringify(cla));
  504. const tpRes = trainplan.find(f => ObjectId(planid).equals(f._id));
  505. if (!tpRes) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级的计划信息');
  506. const t = tpRes.termnum.id(termid);
  507. if (!t) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级的期信息');
  508. const { term, batchnum } = t;
  509. if (!term) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级的期信息');
  510. else cla.term = term;
  511. if (!batchnum) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级的批次信息');
  512. const b = batchnum.id(batchid);
  513. if (!b) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级的批次信息');
  514. const { batch, startdate, enddate } = b;
  515. if (batch)cla.batch = batch;
  516. if (startdate) cla.startdate = startdate;
  517. if (enddate) cla.enddate = enddate;
  518. // 礼仪教师
  519. if (cla.lyteacherid) {
  520. let res = await this.teamodel.findById(cla.lyteacherid);
  521. if (!res) res = await this.heamodel.findById(cla.lyteacherid);
  522. if (res) cla.lyteacher = res.name;
  523. }
  524. return cla;
  525. }
  526. // 整理数据
  527. setData(cla) {
  528. const { headteacherid, yclocationid, kzjhlocationid, kbyslocationid, jslocationid } = cla;
  529. const arr = [];
  530. if (headteacherid && _.isObject(headteacherid)) arr.push({ headteacherid });
  531. if (yclocationid && _.isObject(yclocationid)) arr.push({ yclocationid });
  532. if (kzjhlocationid && _.isObject(kzjhlocationid)) arr.push({ kzjhlocationid });
  533. if (kbyslocationid && _.isObject(kbyslocationid)) arr.push({ kbyslocationid });
  534. if (jslocationid && _.isObject(jslocationid)) arr.push({ jslocationid });
  535. for (const kid of arr) {
  536. for (const key in kid) {
  537. if (kid.hasOwnProperty(key)) {
  538. const obj = kid[key];
  539. const { _id, name } = obj;
  540. const keynoids = key.split('id');
  541. cla[key] = _id;
  542. cla[_.get(keynoids, 0)] = name;
  543. }
  544. }
  545. }
  546. return cla;
  547. }
  548. async upclasses(data) {
  549. for (const _data of data) {
  550. await this.model.findByIdAndUpdate(_data.id, _data);
  551. }
  552. }
  553. async classinfo({ id: classid }) {
  554. const _classes = await this.model.findById(classid);
  555. // 班级信息
  556. const classes = _.cloneDeep(JSON.parse(JSON.stringify(_classes)));
  557. // 学生信息
  558. const students = await this.stumodel.find({ classid });
  559. // 所有用户信息
  560. const users = await this.umodel.find();
  561. if (students) {
  562. for (const stu of students) {
  563. const user = users.find(item => item.uid === stu.id);
  564. if (user && user.openid) {
  565. const _stu = _.cloneDeep(JSON.parse(JSON.stringify(stu)));
  566. _stu.hasuserinfo = '1';
  567. _.remove(students, stu);
  568. students.push(_stu);
  569. }
  570. }
  571. classes.students = students;
  572. }
  573. // 班主任信息
  574. let headteacher;
  575. if (classes.headteacherid) {
  576. headteacher = await this.heamodel.findById(classes.headteacherid);
  577. }
  578. // 礼仪课老师信息
  579. let lyteacher;
  580. if (classes.lyteacherid) {
  581. lyteacher = await this.heamodel.findById(classes.lyteacherid);
  582. if (!lyteacher) {
  583. lyteacher = await this.teamodel.findById(classes.lyteacherid);
  584. }
  585. }
  586. // 教课老师信息
  587. let teachers = [];
  588. const lessones = await this.lessmodel.findOne({ classid });
  589. if (lessones) {
  590. for (const lesson of lessones.lessons) {
  591. if (lesson.teaid) {
  592. const teacher = await this.teamodel.findById(lesson.teaid);
  593. teachers.push(teacher);
  594. }
  595. }
  596. }
  597. teachers.push(lyteacher);
  598. teachers.push(headteacher);
  599. teachers = _.uniq(_.compact(teachers));
  600. for (const tea of teachers) {
  601. const user = users.find(item => item.uid === tea.id);
  602. if (user && user.openid) {
  603. const _tea = _.cloneDeep(JSON.parse(JSON.stringify(tea)));
  604. _tea.hasuserinfo = '1';
  605. _.remove(teachers, tea);
  606. teachers.push(_tea);
  607. }
  608. }
  609. classes.teachers = teachers;
  610. return classes;
  611. }
  612. // 根据模板设置班级信息
  613. async toSetClassSetting({ classid }) {
  614. const setting = await this.ctx.model.Setting.findOne();
  615. if (!setting) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到系统设置');
  616. const { template_term } = setting;
  617. if (!template_term) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到班级模板设置');
  618. const templateList = await this.query({ termid: template_term });
  619. const tClass = await this.model.findById(classid);
  620. if (!tClass) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '班级不存在,无法复制设定的班级设置');
  621. const { name, termid, batchid } = tClass;
  622. const r = templateList.find(f => f.name === name);
  623. // 找到班主任全年计划
  624. const trainPlan = await this.tmodel.findById(tClass.planid);
  625. if (!trainPlan) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到该班所在的年度计划信息');
  626. const tpt = trainPlan.termnum.id(tClass.termid);
  627. if (!tpt) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到该班所在年度计划的期信息');
  628. const tpb = tpt.batchnum.id(tClass.batchid);
  629. if (!tpb) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到该班所在年度计划的批次信息');
  630. if (!tpb.class) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到该班所在年度计划批次下的班级');
  631. const tpc = tpb.class.find(f => f.name === tClass.name);
  632. if (!tpc) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到该班所在年度计划的班级信息');
  633. const { headteacherid } = tpc;
  634. if (r) {
  635. // 说明这个是正常班,且从模板中找得到; 除了礼仪教师外,都复制过来
  636. const { jslocationid, kbyslocationid, kzjhlocationid, yclocationid } = r;
  637. if (!tClass.jslocation && jslocationid) tClass.jslocationid = jslocationid;
  638. if (!tClass.kbyslocationid && kbyslocationid) tClass.kbyslocationid = kbyslocationid;
  639. if (!tClass.kzjhlocationid && kzjhlocationid) tClass.kzjhlocationid = kzjhlocationid;
  640. if (!tClass.yclocationid && yclocationid) tClass.yclocationid = yclocationid;
  641. if (!tClass.headteacherid && headteacherid) {
  642. tClass.headteacherid = headteacherid;
  643. // 默认班主任为礼仪教师
  644. tClass.lyteacherid = headteacherid;
  645. }
  646. await tClass.save();
  647. } else {
  648. // 没找到,有可能是普通班,也有可能是非普通班
  649. // 找这个班级的同批次
  650. const tClassBatch = await this.query({ termid, batchid });
  651. const r = tClassBatch.find(f => ObjectId(tClass._id).equals(f._id));
  652. const ri = tClassBatch.findIndex(f => ObjectId(tClass._id).equals(f._id));
  653. // TODO 特殊班需要判断,如果没有就没有
  654. // if (r) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '无法确定班级批次排序');
  655. if (!r) {
  656. const { batch: tAllClassBatch } = r;
  657. const templateBatchList = templateList.filter(f => f.batch === tAllClassBatch);
  658. // 根据该班级所在批次的顺序,找到对应模板,然后复制
  659. const copyTemplate = templateBatchList[ri];
  660. const { jslocationid, kbyslocationid, kzjhlocationid, yclocationid } = copyTemplate;
  661. if (!tClass.jslocation && jslocationid) tClass.jslocationid = jslocationid;
  662. if (!tClass.kbyslocationid && kbyslocationid) tClass.kbyslocationid = kbyslocationid;
  663. if (!tClass.kzjhlocationid && kzjhlocationid) tClass.kzjhlocationid = kzjhlocationid;
  664. if (!tClass.yclocationid && yclocationid) tClass.yclocationid = yclocationid;
  665. if (!tClass.headteacherid && headteacherid) tClass.headteacherid = headteacherid;
  666. await tClass.save();
  667. }
  668. }
  669. }
  670. }
  671. module.exports = ClassService;