student.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  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. const moment = require('moment');
  8. class StudentService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'student');
  11. this.model = this.ctx.model.Student;
  12. this.umodel = this.ctx.model.User;
  13. this.tmodel = this.ctx.model.Trainplan;
  14. this.clamodel = this.ctx.model.Class;
  15. this.upmodel = this.ctx.model.Uploadtask;
  16. this.gmodel = this.ctx.model.Group;
  17. this.psmodel = this.ctx.model.Personalscore;
  18. this.gsmodel = this.ctx.model.Groupscore;
  19. this.uqmodel = this.ctx.model.Uploadquestion;
  20. this.scoremodel = this.ctx.model.Score;
  21. this.leavemodel = this.ctx.model.Leave;
  22. this.attendmodel = this.ctx.model.Attendance;
  23. }
  24. async create(data) {
  25. const { name, phone: mobile, gender } = data;
  26. const res = await this.model.create(data);
  27. if (res) {
  28. const obj = {
  29. name,
  30. mobile,
  31. gender,
  32. type: '4',
  33. passwd: '12345678',
  34. uid: res._id,
  35. };
  36. const user = await this.ctx.service.user.create(obj);
  37. }
  38. return res;
  39. }
  40. async delete({ id }) {
  41. // 删除小组中的这个人,作业表,问卷表,评分,考勤,用户表,学生表
  42. await this.gmodel.update({ 'students.stuid': id }, { $pull: { students: { stuid: id } } });
  43. await this.upmodel.deleteMany({ studentid: id });
  44. await this.uqmodel.deleteMany({ studentid: id });
  45. await this.scoremodel.deleteMany({ stuid: id });
  46. await this.attendmodel.deleteMany({ studentid: id });
  47. await this.umodel.deleteOne({ uid: id });
  48. await this.model.deleteOne({ _id: ObjectId(id) });
  49. }
  50. async update({ id }, data) {
  51. const student = await this.model.findByIdAndUpdate(id, data);
  52. if (student) {
  53. const { phone, name } = data;
  54. await this.umodel.findOneAndUpdate({ uid: id }, { mobile: phone, name });
  55. }
  56. return student;
  57. }
  58. // 查询
  59. async query({ skip, limit, ...info }) {
  60. const total = await this.model.count(info);
  61. const res = await this.model
  62. .find(info)
  63. .skip(Number(skip))
  64. .limit(Number(limit));
  65. const data = [];
  66. for (const elm of res) {
  67. const plan = await this.tmodel.findOne({
  68. 'termnum._id': ObjectId(elm.termid),
  69. });
  70. const newdata = { ...JSON.parse(JSON.stringify(elm)) };
  71. if (plan) {
  72. const term = await plan.termnum.id(elm.termid);
  73. newdata.termname = term.term;
  74. if (elm.batchid) {
  75. const _batch = await term.batchnum.id(elm.batchid);
  76. newdata.batchname = _batch.batch;
  77. }
  78. }
  79. if (elm.classid) {
  80. const classs = await this.clamodel.findById(elm.classid);
  81. if (classs) {
  82. newdata.classname = classs.name;
  83. }
  84. }
  85. data.push(newdata);
  86. }
  87. const result = { total, data };
  88. return result;
  89. }
  90. // 查询
  91. async seek({ termid, type, batchid, skip, limit }) {
  92. const total = await this.model.count({
  93. termid,
  94. type,
  95. batchid,
  96. $or: [{ classid: null }, { classid: '' }],
  97. });
  98. const data = await this.model
  99. .find({
  100. termid,
  101. type,
  102. batchid,
  103. $or: [{ classid: null }, { classid: '' }],
  104. })
  105. .skip(Number(skip))
  106. .limit(Number(limit));
  107. const result = { total, data };
  108. return result;
  109. }
  110. async findbedroom(data) {
  111. const { batchid, classid } = data;
  112. const result = [];
  113. // 如果传的是批次id
  114. if (batchid) {
  115. // 查询该批次下的所有学生
  116. const students = await this.model.find({ batchid });
  117. const bedroomList = new Set();
  118. // 查询该批次的所有寝室号
  119. for (const student of students) {
  120. bedroomList.add(student.bedroom);
  121. }
  122. let studentList = [];
  123. // 查询该批次所有寝室下的学生名单
  124. for (const bedroom of bedroomList) {
  125. const newstudents = await this.model.find({ bedroom });
  126. for (const newstudent of newstudents) {
  127. studentList.push(newstudent.name);
  128. }
  129. result.push({ bedroom, studentList });
  130. studentList = [];
  131. }
  132. }
  133. // 如果传的是班级id
  134. if (classid) {
  135. // 查询该班级所有学生
  136. const students = await this.model.find({ classid });
  137. const bedroomList = new Set();
  138. // 查询该班级所有寝室号
  139. for (const student of students) {
  140. bedroomList.add(student.bedroom);
  141. }
  142. let studentList = [];
  143. // 查询该班级所有寝室的学生名单
  144. for (const bedroom of bedroomList) {
  145. const newstudents = await this.model.find({ bedroom });
  146. for (const newstudent of newstudents) {
  147. // 如果寝室中有非本班级学生(混寝),则过滤掉不予显示
  148. if (newstudent.classid === classid) {
  149. studentList.push(newstudent.name);
  150. }
  151. }
  152. result.push({ bedroom, studentList });
  153. studentList = [];
  154. }
  155. }
  156. return result;
  157. }
  158. async upjob(data) {
  159. const { stuid, job } = data;
  160. const student = await this.model.findById(stuid);
  161. student.job = job;
  162. if (job === '班长' || job === '学委') {
  163. const user = await this.umodel.findOne({ uid: stuid, type: '4' });
  164. const date = await this.ctx.service.util.updatedate();
  165. const openid = user.openid;
  166. const detail = '你已被班主任设置为' + job + ',请及时登录查看';
  167. const remark = '感谢您的使用';
  168. if (openid) {
  169. this.ctx.service.weixin.sendTemplateMsg(
  170. this.ctx.app.config.REVIEW_TEMPLATE_ID,
  171. openid,
  172. '您有一个新的通知',
  173. detail,
  174. date,
  175. remark
  176. );
  177. }
  178. }
  179. return await student.save();
  180. }
  181. // 根据学生id删除班级
  182. async deleteclass(data) {
  183. for (const el of data) {
  184. const student = await this.model.findById(el);
  185. if (student) {
  186. student.classid = '';
  187. await student.save();
  188. }
  189. }
  190. }
  191. // 根据班级id查出班级各个学生的分数
  192. async findscore({ skip, limit, ...info }) {
  193. const { classid } = info;
  194. const total = await this.model.count(info);
  195. const students = await this.model
  196. .find(info)
  197. .skip(Number(skip))
  198. .limit(Number(limit));
  199. const data = [];
  200. const groups = await this.gmodel.find({ classid });
  201. for (const student of students) {
  202. const _student = JSON.parse(JSON.stringify(student));
  203. const group = groups.find(item =>
  204. item.students.find(stuinfo => stuinfo.stuid === _student.id)
  205. );
  206. console.log(group);
  207. if (group) {
  208. _student.groupscore = group.score;
  209. }
  210. const tasks = await this.upmodel.find({ studentid: _student.id });
  211. _student.tasks = tasks;
  212. data.push(_student);
  213. }
  214. return { total, data };
  215. }
  216. async findbystuids({ data }) {
  217. const res = [];
  218. for (const stuid of data) {
  219. const stu = await this.model.findById(stuid);
  220. if (stu) res.push(stu);
  221. }
  222. return res;
  223. }
  224. // 根据学生id删除学生
  225. async deletestus(data) {
  226. throw new BusinessError(
  227. ErrorCode.BUSINESS,
  228. '此功能暂不开放,待确定好会出现的以外情况后,再次开放'
  229. );
  230. // for (const id of data) {
  231. // await this.model.deleteOne({ _id: ObjectId(id) });
  232. // await this.umodel.deleteOne({ uid: id });
  233. // await this.upmodel.deleteMany({ studentid: id });
  234. // await this.uqmodel.deleteMany({ studentid: id });
  235. // await this.scoremodel.deleteMany({ stuid: id });
  236. // await this.attendmodel.deleteMany({ studentid: id });
  237. // }
  238. }
  239. // 批量更新寝室号
  240. async updatabedroom(data) {
  241. for (const el of data) {
  242. const student = await this.model.findById(el.id);
  243. if (student) {
  244. student.bedroom = el.bedroom;
  245. await student.save();
  246. }
  247. }
  248. }
  249. /**
  250. * 计算班级的优秀学生
  251. * 规则:班级干部(学生的job!=='普通学生'),检查是否有评优资格(is_fine_status==='0'可以评优),全部评优;
  252. * 普通学生取总成绩前10的人评优(非10位并列时,名额该占用就占用;第10名若有并列,就全都要)
  253. * @param {String} param0 {id=>班级id}
  254. */
  255. async getFineStudent({ id: classid }) {
  256. // 获取班级学生列表
  257. let studentList = await this.model.find({ classid });
  258. // 重置评优,干部全优秀
  259. studentList = studentList.map(i => {
  260. if (i.job.includes('普通')) i.is_fine = '0';
  261. else i.is_fine = '1';
  262. return i;
  263. });
  264. // 初始化后取出不需要算的人,他们就这样,没必要算
  265. const reverseList = studentList.filter(
  266. f => !(f.is_fine !== '2' && f.job.includes('普通'))
  267. );
  268. // 过滤出取消评优资格的学生和干部;干部就是优秀;被取消资格就别凑热闹了
  269. studentList = studentList.filter(
  270. f => f.is_fine !== '2' && f.job.includes('普通')
  271. );
  272. // 获取平时分
  273. const dailyScoreList = await this.psmodel.find({ classid });
  274. studentList = this.dealScoreList(dailyScoreList, studentList);
  275. // 获取作业分
  276. const taskScoreList = await this.upmodel.find({ classid });
  277. studentList = this.dealScoreList(taskScoreList, studentList);
  278. // 获取小组分,小组
  279. const groupList = await this.gmodel.find({ classid });
  280. const groupScoreList = await this.gsmodel.find({ classid });
  281. studentList = this.dealGroupScoreList(
  282. groupList,
  283. groupScoreList,
  284. studentList
  285. );
  286. studentList = studentList.sort(
  287. (a, b) => (b.score * 1 || 0) - (a.score * 1 || 0)
  288. );
  289. // 排名
  290. // eslint-disable-next-line no-unused-vars
  291. let num = 0;
  292. for (const student of studentList) {
  293. // 先判断是否超过第10位,超过就跳出
  294. if (num > 10) break;
  295. const { score, is_fine } = student;
  296. // 最开始初始化过所有人的状态,并且将干部和不能评优的人都过滤出去,所以正常学生应该都是没有评优,如果此处已经是优秀,那么就是和前人同分改的,直接跳过就好
  297. if (is_fine === '1') continue;
  298. // 没有分凑什么热闹
  299. if (!score) continue;
  300. let plus = 1; // 这轮有多少人,到这了,这个人肯定是要改了,所以默认1
  301. // 评优
  302. student.is_fine = '1';
  303. const rlist = studentList.filter(f => f.score === score);
  304. // 处理同分的人也都变成is_fine
  305. for (const stud of rlist) {
  306. stud.is_fine = '1';
  307. const sindex = studentList.findIndex(f =>
  308. ObjectId(stud._id).equals(f._id)
  309. );
  310. if (sindex >= 0) {
  311. studentList[sindex] = stud;
  312. plus++;
  313. }
  314. }
  315. // num+plus,算下num
  316. num = num + plus;
  317. }
  318. // 算完的和不用算的合并,提交
  319. const lastList = [ ...studentList, ...reverseList ];
  320. for (const student of lastList) {
  321. const res = await student.save();
  322. // const { meta, ...data } = student;
  323. // const r = await this.model.findByIdAndUpdate(
  324. // { _id: ObjectId(student._id) },
  325. // data
  326. // );
  327. console.log(res);
  328. }
  329. }
  330. /**
  331. * 将分数放到学生身上
  332. * @param {Array} scoreList 班级的分数列表
  333. * @param {Array} studentList 学生列表
  334. */
  335. dealScoreList(scoreList, studentList) {
  336. scoreList = _.groupBy(scoreList, 'studentid');
  337. studentList = studentList.map(i => {
  338. const slist = scoreList[i._id];
  339. if (slist) {
  340. i.score =
  341. (i.score * 1 || 0) +
  342. slist.reduce((p, n) => p + (n.score * 1 || 0), 0);
  343. }
  344. return i;
  345. });
  346. return studentList;
  347. }
  348. /**
  349. * 将 学生所在 组的 团队平均分 + 到学生身上
  350. * @param {Array} groupList 班级的小组的列表
  351. * @param {Array} scoreList 所有小组的分数列表
  352. * @param {Array} studentList 学生列表
  353. */
  354. dealGroupScoreList(groupList, scoreList, studentList) {
  355. // console.log(groupList);
  356. scoreList = _.groupBy(scoreList, 'groupid');
  357. // 算出每组的平均分,之后加给学生
  358. groupList = groupList.map(i => {
  359. const { students } = i;
  360. if (students.length > 0) {
  361. const slist = scoreList[i._id];
  362. if (slist) {
  363. i.score = slist.reduce((p, n) => p + (n.score * 1 || 0), 0);
  364. i.score = _.floor(_.divide(i.score, students.length), 2);
  365. }
  366. }
  367. return i;
  368. });
  369. // 每个学生加自己的组的平均分
  370. studentList = studentList.map(i => {
  371. const r = groupList.find(f =>
  372. f.students.find(sf => ObjectId(sf.stuid).equals(i._id))
  373. );
  374. if (r) i.score = (i.score * 1 || 0) + (r.score * 1 || 0);
  375. return i;
  376. });
  377. return studentList;
  378. }
  379. // 将学生排号
  380. async arrangeNumber({ classid }) {
  381. const studList = await this.model.find({ classid });
  382. let number = 1;
  383. // 查每个学生的编号,如果没有,就给赋上值;有,就给number赋上值,然后继续下一位
  384. for (const stu of studList) {
  385. if (!stu.number) {
  386. if (number * 1 < 10) stu.number = `0${number}`;
  387. else stu.number = number;
  388. await stu.save();
  389. } else {
  390. number = stu.number * 1;
  391. }
  392. number = number * 1 + 1;
  393. }
  394. number = 1;
  395. }
  396. // 导出学生 目前:拓展训练保险用
  397. async exportStudent({ type = 'insurance', ...data }) {
  398. console.log(type, data);
  399. let { data: studentList } = await this.query(data);
  400. studentList = JSON.parse(JSON.stringify(studentList));
  401. let ids = studentList.map(i => i.classid);
  402. ids = _.uniq(ids);
  403. const classList = [];
  404. // 此处可以优化,将班级整理,查出来,循环中find
  405. for (const id of ids) {
  406. const cla = await this.ctx.service.class.fetch({ id });
  407. if (!cla) continue;
  408. if (type === 'insurance') { cla.date = moment(cla.startdate).add(1, 'd').format('YYYY-MM-DD'); }
  409. classList.push(cla);
  410. }
  411. studentList = studentList.map(i => {
  412. const c = classList.find(f => ObjectId(i.classid).equals(f._id));
  413. if (c) i.date = c.date;
  414. return i;
  415. });
  416. const meta = this.metaBx(type);
  417. let fn = '学生名单';
  418. const head = _.head(classList);
  419. if (head) {
  420. if (type === 'class') { fn = `${head.term}期-${head.batch}批-${head.name}${fn}`; } else fn = `${head.term}期-${head.batch}批${fn}`;
  421. }
  422. return await this.ctx.service.util.toExcel(studentList, meta, fn);
  423. }
  424. metaBx(type) {
  425. const header = [
  426. {
  427. header: '姓名',
  428. key: 'name',
  429. width: 20,
  430. },
  431. {
  432. header: '性别',
  433. key: 'gender',
  434. width: 10,
  435. },
  436. {
  437. header: '民族',
  438. key: 'nation',
  439. width: 20,
  440. },
  441. {
  442. header: '身份证号',
  443. key: 'id_number',
  444. width: 20,
  445. },
  446. {
  447. header: '期',
  448. key: 'termname',
  449. width: 20,
  450. },
  451. {
  452. header: '批次',
  453. key: 'batchname',
  454. width: 20,
  455. },
  456. {
  457. header: '班级',
  458. key: 'classname',
  459. width: 20,
  460. },
  461. {
  462. header: '学校',
  463. key: 'school_name',
  464. width: 20,
  465. },
  466. {
  467. header: '院系',
  468. key: 'faculty',
  469. width: 20,
  470. },
  471. {
  472. header: '专业',
  473. key: 'major',
  474. width: 20,
  475. },
  476. {
  477. header: '手机号',
  478. key: 'phone',
  479. width: 20,
  480. },
  481. ];
  482. if (type === 'insurance') {
  483. header.splice(1, 0, {
  484. header: '拓训日期',
  485. key: 'date',
  486. width: 20,
  487. });
  488. }
  489. return header;
  490. }
  491. }
  492. module.exports = StudentService;