class.js 27 KB

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