trainplan.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. 'use strict';
  2. const _ = require('lodash');
  3. const { CrudService } = require('naf-framework-mongoose/lib/service');
  4. const assert = require('assert');
  5. const { BusinessError, ErrorCode } = require('naf-core').Error;
  6. const XLSX = require('xlsx');
  7. const utils = require('../utils/utils.js');
  8. const moment = require('moment');
  9. const XLSXStyle = require('xlsx-style');
  10. const Excel = require('exceljs');
  11. const { sep } = require('path');
  12. const { ObjectId } = require('mongoose').Types;
  13. class TrainplanService extends CrudService {
  14. constructor(ctx) {
  15. super(ctx, 'trainplan');
  16. this.model = this.ctx.model.Trainplan;
  17. this.clamodel = this.ctx.model.Class;
  18. this.umodel = this.ctx.model.User;
  19. this.smodel = this.ctx.model.School;
  20. this.tmodel = this.ctx.model.Teacher;
  21. this.stumodel = this.ctx.model.Student;
  22. this.schmodel = this.ctx.model.Schtime;
  23. this.lmmodel = this.ctx.model.Lessonmode;
  24. this.ctmodel = this.ctx.model.Classtype;
  25. }
  26. async create(data) {
  27. const { planyearid, year, title } = data;
  28. assert(planyearid, '缺少大批次信息');
  29. assert(year, '缺少年度');
  30. assert(title, '缺少标题');
  31. const res = await this.model.create(data);
  32. let planid = '';
  33. if (res) planid = res._id;
  34. const schoolList = await this.smodel.find();
  35. const schtimeArr = [];
  36. // 为学校创建不可以培训的数据
  37. for (const sch of schoolList) {
  38. const { code } = sch;
  39. // 没有学校编码就下一个
  40. if (!code) continue;
  41. const obj = { schid: code, year, planid };
  42. let schtimeres;
  43. schtimeres = await this.schmodel.findOne(obj);
  44. if (!schtimeres) schtimeres = await this.schmodel.create(obj);
  45. if (schtimeres) schtimeArr.push(schtimeres);
  46. }
  47. // if (!schtimeArr.every((e) => e)) {
  48. // throw new BusinessError(ErrorCode.DATA_INVALID, '学校计划生成失败');
  49. // } else
  50. return res;
  51. }
  52. async update({ id }, data) {
  53. const trainplan = await this.model.findById(id);
  54. // 保存原数据
  55. const trainplanold = _.cloneDeep(trainplan);
  56. const { year, title, termnum, festivals, status, school } = data;
  57. if (year) {
  58. trainplan.year = year;
  59. }
  60. if (title) {
  61. trainplan.title = title;
  62. }
  63. if (termnum) {
  64. trainplan.termnum = termnum;
  65. }
  66. if (school) {
  67. trainplan.school = school;
  68. }
  69. if (festivals) {
  70. trainplan.festivals = festivals;
  71. }
  72. if (status === '1') {
  73. trainplan.status = status;
  74. }
  75. // 日历安排中添加课表信息,查询每种班级类型的课表,然后显示
  76. if (trainplan.termnum) {
  77. // trainplan.termnum =
  78. trainplan.termnum = await this.termGetLesson(trainplan.termnum);
  79. // 重新查看每个班级是否有课程
  80. trainplan.termnum = this.setClassLesson(trainplan.termnum);
  81. }
  82. // 如果培训计划状态改为发布,发送培训计划信息,并自动生成班级
  83. const res = await trainplan.save();
  84. if (res) {
  85. if (status === '1') {
  86. // 自动生成班级
  87. // await this.autoclass(res, trainplanold);
  88. // await this.autoclassNew(res, trainplanold);
  89. // 将生成的班级重新将班级排班名
  90. // await this.autoclassname(res);
  91. // 发送培训计划信息通知给相应人员
  92. // 查询所有入库的教师
  93. // 不需要给教师发信息
  94. // const teachers = await this.tmodel.find({ status: '4' });
  95. // for (const teacher of teachers) {
  96. // const teacherid = teacher._id;
  97. // const _teacher = await this.umodel.findOne({
  98. // uid: teacherid,
  99. // type: '3',
  100. // });
  101. // const openid = _teacher.openid;
  102. // const detail = trainplan.title + '已发布,请注意查收!';
  103. // const date = await this.ctx.service.util.updatedate();
  104. // const remark = '感谢您的使用';
  105. // if (openid) {
  106. // this.ctx.service.weixin.sendTemplateMsg(
  107. // this.ctx.app.config.REVIEW_TEMPLATE_ID,
  108. // openid,
  109. // '您有一个新的通知',
  110. // detail,
  111. // date,
  112. // remark
  113. // );
  114. // }
  115. // }
  116. // 查询所有学校用户
  117. // const schools = await this.umodel.find({ type: '2' });
  118. // for (const school of schools) {
  119. // const openid = school.openid;
  120. // const detail = trainplan.title + '已发布,请注意查收!';
  121. // const date = await this.ctx.service.util.updatedate();
  122. // const remark = '感谢您的使用';
  123. // if (openid) {
  124. // this.ctx.service.weixin.sendTemplateMsg(
  125. // this.ctx.app.config.REVIEW_TEMPLATE_ID,
  126. // openid,
  127. // '您有一个新的通知',
  128. // detail,
  129. // date,
  130. // remark
  131. // );
  132. // }
  133. // }
  134. }
  135. // 查哪个学校schtime表没有生成,就给生成了
  136. const schoolList = await this.smodel.find();
  137. for (const school of schoolList) {
  138. const r = await this.schmodel.findOne({ year: trainplan.year, planid: id, schid: school.code });
  139. if (r) continue;
  140. // 学校没有编码直接跳过
  141. if (!school.code) continue;
  142. const obj = { schid: school.code, year: trainplan.year, planid: id };
  143. await this.schmodel.create(obj);
  144. }
  145. }
  146. return res;
  147. }
  148. async termGetLesson(termnum) {
  149. const lessonModelList = await this.lmmodel.find();
  150. for (const term of termnum) {
  151. for (const batch of term.batchnum) {
  152. const { class: classes, startdate, enddate } = batch;
  153. // 获取每批次下每个班的班级类型
  154. const typeList = _.uniq(classes.map((i) => i.type));
  155. const h = _.head(typeList);
  156. if (!h) continue;
  157. const tem = lessonModelList.find((f) => f.type === h);
  158. if (!tem) continue;
  159. let { lessons } = tem;
  160. if (!lessons) continue;
  161. lessons = JSON.parse(lessons);
  162. // 过滤出上课的时间段
  163. lessons = lessons.filter((f) => {
  164. const keys = Object.keys(f).filter((f) => f.includes('subid'));
  165. return keys.length > 0;
  166. });
  167. // 记录上课的时间
  168. const times = [];
  169. // 记录所有的科目
  170. let subject = [];
  171. lessons.map((i) => {
  172. times.push(i.time);
  173. const keys = Object.keys(i);
  174. let arr = [];
  175. for (const key of keys) {
  176. if (key.match(/\d/g)) arr.push(_.head(key.match(/\d/g)));
  177. }
  178. arr = _.uniq(arr);
  179. for (const ai of arr) {
  180. if (i[`day${ai}subid`]) {
  181. subject.push({
  182. subname: i[`day${ai}`],
  183. subid: i[`day${ai}subid`],
  184. day: ai,
  185. });
  186. }
  187. }
  188. return i;
  189. });
  190. // 去重
  191. subject = _.uniqBy(subject, 'subid');
  192. // 获得天列表
  193. const dnum = moment(enddate).diff(moment(startdate), 'days') + 1;
  194. const dayList = [];
  195. for (let ind = 0; ind < dnum; ind++) {
  196. dayList.push(moment(startdate).add(ind, 'd').format('YYYY-MM-DD'));
  197. }
  198. // 将subject中的day换成日期
  199. for (const sub of subject) {
  200. sub.day = dayList[sub.day * 1 - 1];
  201. sub.time = times;
  202. }
  203. batch.lessons = subject;
  204. }
  205. }
  206. return termnum;
  207. }
  208. // 设置课表模板到班级上
  209. setClassLesson(termnum) {
  210. // 为班级设置lessons,有的就不设置了
  211. for (const t of termnum) {
  212. const { batchnum } = t;
  213. if (!batchnum || !_.isArray(batchnum)) {
  214. this.$message.error(`第${t.term}期的批次数据错误!`);
  215. continue;
  216. }
  217. for (const b of t.batchnum) {
  218. const { class: cla, lessons: ltemplate } = b;
  219. if (!cla) {
  220. console.warn(`${t.term}期${b.batch}批次没有班级列表`);
  221. continue;
  222. }
  223. if (!ltemplate) {
  224. console.warn(`${t.term}期${b.batch}批次没有课表`);
  225. continue;
  226. }
  227. for (const c of b.class) {
  228. const { lessons } = c;
  229. if (lessons) {
  230. if (lessons.length <= 0) c.lessons = ltemplate;
  231. }
  232. }
  233. }
  234. }
  235. return termnum;
  236. }
  237. // 自动生成班级私有方法
  238. async autoclassNew(res) {
  239. // 删除所有计划下的班级
  240. await this.clamodel.deleteMany({ planid: res.id });
  241. // 循环出所有班级进行添加操作
  242. for (const term of res.termnum) {
  243. for (const batch of term.batchnum) {
  244. const classs = await batch.class;
  245. for (const cla of classs) {
  246. const newdata = {
  247. name: cla.name,
  248. number: cla.number,
  249. batchid: batch.id,
  250. termid: term.id,
  251. planid: res.id,
  252. type: cla.type,
  253. headteacherid: cla.headteacherid,
  254. };
  255. await this.clamodel.create(newdata);
  256. }
  257. }
  258. }
  259. }
  260. // 自动生成班级私有方法
  261. async autoclass(res, trainplanold) {
  262. // 首先比较当前数据和原数据的值是否有不同
  263. // 保存后所有期id
  264. const tremid_res = _.map(res.termnum, 'id');
  265. // 保存前所有期id
  266. const tremid_old = _.map(trainplanold.termnum, 'id');
  267. // 取得要删除的期id,进行班级中删除已删除期的班级
  268. const deltrem = _.difference(tremid_old, tremid_res);
  269. // 循环删除已经删除期的所有班级
  270. for (const elm of deltrem) {
  271. await this.clamodel.deleteMany({ termid: elm });
  272. }
  273. // 取得所有新加期id
  274. const addtrem = _.difference(tremid_res, tremid_old);
  275. // 清空后循环取得所有期进行批次操作
  276. const terms = res.termnum;
  277. for (const el of terms) {
  278. // 判断是否新加期
  279. if (_.indexOf(addtrem, el.id) !== -1) {
  280. // 循环当前新加期的批次列表,根据批次id和班级数生成班级信息
  281. const batchnums = el.batchnum;
  282. for (const batchnum of batchnums) {
  283. // 取得当前批次的班级数
  284. const classnum = batchnum.class;
  285. for (const cla of classnum) {
  286. const newdata = {
  287. name: cla.name,
  288. number: cla.number,
  289. batchid: batchnum.id,
  290. termid: el.id,
  291. planid: res.id,
  292. type: cla.type,
  293. };
  294. await this.clamodel.create(newdata);
  295. }
  296. }
  297. } else {
  298. // 不是新加期,更新期信息
  299. // 保存后所有期id
  300. const batchid_res = _.map(el.batchnum, 'id');
  301. // 保存前所有期id
  302. const batchid_old = _.map(trainplanold.termnum.id(el.id).batchnum, 'id');
  303. // 取得要删除的期id,进行班级中删除已删除期的班级
  304. const delbatchs = _.difference(batchid_old, batchid_res);
  305. // 循环删除已经删除期的所有班级
  306. for (const delba of delbatchs) {
  307. await this.clamodel.deleteMany({ termid: el.id, batchid: delba });
  308. }
  309. // 取得所有新加期id
  310. const addbatch = _.difference(batchid_res, batchid_old);
  311. const batchnums = el.batchnum;
  312. for (const batchnum of batchnums) {
  313. // 取得当前批次是否有删除
  314. // 判断是否新加期
  315. if (_.indexOf(addbatch, batchnum.id) !== -1) {
  316. // 取得当前批次的班级数
  317. const classnum = batchnum.class;
  318. for (const cla of classnum) {
  319. const newdata = {
  320. name: cla.name,
  321. number: cla.number,
  322. batchid: batchnum.id,
  323. termid: el.id,
  324. planid: res.id,
  325. type: cla.type,
  326. };
  327. await this.clamodel.create(newdata);
  328. }
  329. } else {
  330. if (batchnum.class === trainplanold.termnum.id(el.id).batchnum.id(batchnum.id).class) {
  331. // 编辑只会针对班级人数进行修改。
  332. const _class = await this.clamodel.find({
  333. termid: el.id,
  334. batchid: batchnum.id,
  335. });
  336. if (_class.length !== 0) {
  337. for (const ee of _class) {
  338. ee.number = batchnum.number;
  339. await ee.save();
  340. }
  341. } else {
  342. const classnum = batchnum.class;
  343. for (const cla of classnum) {
  344. const newdata = {
  345. name: cla.name,
  346. number: cla.number,
  347. batchid: batchnum.id,
  348. termid: el.id,
  349. planid: res.id,
  350. type: cla.type,
  351. };
  352. await this.clamodel.create(newdata);
  353. }
  354. }
  355. } else {
  356. // 当班级数有更改时
  357. // 删除所有班级 并重新生成班级
  358. await this.clamodel.deleteMany({
  359. termid: el.id,
  360. batchid: batchnum.id,
  361. });
  362. const classnum = batchnum.class;
  363. for (const cla of classnum) {
  364. const newdata = {
  365. name: cla.name,
  366. number: cla.number,
  367. batchid: batchnum.id,
  368. termid: el.id,
  369. planid: res.id,
  370. type: cla.type,
  371. };
  372. await this.clamodel.create(newdata);
  373. }
  374. }
  375. }
  376. }
  377. }
  378. }
  379. }
  380. // // 将分好的班级重新编排名字
  381. // async autoclassname(res) {
  382. // // 取得所有期id
  383. // const tremid_res = _.map(res.termnum, 'id');
  384. // for (const termid of tremid_res) {
  385. // const classs = await this.clamodel.find({ planid: res.id, termid });
  386. // let i = 0;
  387. // for (const cla of classs) {
  388. // i = i + 1;
  389. // cla.name = i;
  390. // await cla.save();
  391. // }
  392. // }
  393. // }
  394. async exportExcel({ trainplanIds }) {
  395. const nowDate = new Date().getTime();
  396. const { repos_root_path: rp } = this.ctx.app.config.cdn;
  397. const { baseUrl: bu } = this.ctx.app.config;
  398. const path = `${rp}${sep}train${sep}${nowDate}.xlsx`;
  399. const respath = `${bu}/files/train/${nowDate}.xlsx`;
  400. const wb = {
  401. SheetNames: [],
  402. Sheets: {},
  403. };
  404. for (let i = 0; i < trainplanIds.length; i++) {
  405. // 批次期次都在这里面
  406. const trainplan = await this.model.findOne({ _id: trainplanIds[i] });
  407. // 这个计划下所有的学生
  408. const studentList = await this.stumodel.find({ planid: trainplanIds[i] });
  409. // 计划名称
  410. const trainplandName = trainplan.title;
  411. // 在计划中找到这个学生在哪期以及哪期下的哪批次
  412. for (const student of studentList) {
  413. student.isComming = utils.getIsNot(student.isComming);
  414. student.trainplandName = trainplandName;
  415. // 期次
  416. const term = trainplan.termnum.filter((term) => {
  417. return term.id === student.termid;
  418. });
  419. if (term.length > 0) {
  420. student.termName = term[0].term;
  421. }
  422. // 批次
  423. if (term.length !== 0) {
  424. const batch = term[0].batchnum.filter((batch) => {
  425. return batch.id === student.batchid;
  426. });
  427. if (batch.length > 0) {
  428. student.batchName = JSON.parse(JSON.stringify(batch[0])).name;
  429. }
  430. }
  431. student.is_fine = utils.getIsNot(student.is_fine);
  432. }
  433. const _headers = [
  434. { key: 'trainplandName', title: '计划标题' },
  435. { key: 'termName', title: '期次' },
  436. { key: 'batchName', title: '批次' },
  437. { key: 'school_name', title: '学校' },
  438. { key: 'faculty', title: '院系' },
  439. { key: 'major', title: '专业' },
  440. { key: 'name', title: '姓名' },
  441. { key: 'id_number', title: '身份证号' },
  442. { key: 'phone', title: '手机号' },
  443. { key: 'gender', title: '性别' },
  444. { key: 'nation', title: '民族' },
  445. { key: 'edua_level', title: '学历层次' },
  446. { key: 'edua_system', title: '学制' },
  447. { key: 'entry_year', title: '入学年份' },
  448. { key: 'finish_year', title: '毕业年份' },
  449. { key: 'school_job', title: '在校职务' },
  450. { key: 'qq', title: 'QQ号' },
  451. { key: 'email', title: '邮箱' },
  452. // { key: 'openid', title: '微信openid' },
  453. { key: 'family_place', title: '家庭位置' },
  454. { key: 'family_is_hard', title: '是否困难' },
  455. { key: 'have_grant', title: ' 是否获得过助学金' },
  456. // { key: 'job', title: '职务' },
  457. // { key: 'bedroom', title: '寝室号' },
  458. { key: 'is_fine', title: '是否优秀' },
  459. { key: 'isComming', title: '是否签到' },
  460. { key: 'selfscore', title: '个人分' },
  461. { key: 'score', title: '总分' },
  462. ];
  463. // 需要打出的列表
  464. const _data = studentList;
  465. const headers = _headers
  466. .map(({ title }) => title)
  467. .map((v, i) => Object.assign({}, { v, position: String.fromCharCode(65 + i) + 1 }))
  468. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});
  469. const data = _data
  470. .map((v, i) => _headers.map(({ key }, j) => Object.assign({}, { v: v[key], position: String.fromCharCode(65 + j) + (i + 2) })))
  471. .reduce((prev, next) => prev.concat(next))
  472. .reduce((prev, next) => Object.assign({}, prev, { [next.position]: { v: next.v } }), {});
  473. // 合并 headers 和 data
  474. const output = Object.assign({}, headers, data);
  475. // 获取所有单元格的位置
  476. const outputPos = Object.keys(output);
  477. // 计算出范围
  478. const ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
  479. // 构建 workbook 对象
  480. wb.SheetNames.push('sheet' + i);
  481. wb.Sheets['sheet' + i] = Object.assign({}, output, { '!ref': ref });
  482. }
  483. // 导出 Excel
  484. XLSX.writeFile(wb, path);
  485. return respath;
  486. }
  487. // 导出学校大表
  488. async exportSchool({ trainplanId }) {
  489. const rows = [
  490. ['学校名称', '期数'],
  491. [' ', '班级数'],
  492. [' ', '时间'],
  493. [' ', '备注'],
  494. ];
  495. // 操作
  496. const operaList = [{ startRow: 1, startCol: 1, endRow: 5, endCol: 1 }];
  497. // 操作:
  498. // step1: 班级类型的动态列
  499. // step2: 1行:期数需要合并列:需要合并的列数根据下面的批次决定
  500. // step3: 2行:输出批次的班级类型及班级数
  501. // step4: 3行:显示每批次的事件(开始-结束)
  502. // step5: 4行:每批次的备注,和5行同列合并
  503. // 批次期次都在这里面
  504. let trainplan = await this.model.findById(trainplanId);
  505. if (trainplan) trainplan = JSON.parse(JSON.stringify(trainplan));
  506. const fn = trainplan.title; // 文件名
  507. let classType = await this.ctmodel.find();
  508. if (classType) classType = JSON.parse(JSON.stringify(classType));
  509. let schtime = await this.schmodel.find({ planid: trainplanId });
  510. if (schtime) schtime = JSON.parse(JSON.stringify(schtime));
  511. // step1
  512. // 整理班级类型的顺序
  513. if (_.isArray(classType) && classType.length > 0) {
  514. classType = classType.map((i) => {
  515. i.sort = parseInt(i.code);
  516. return i;
  517. });
  518. classType = _.orderBy(classType, ['sort'], ['desc']);
  519. }
  520. const row5 = [''];
  521. for (const ct of classType) {
  522. const { name } = ct;
  523. row5.push(name);
  524. }
  525. row5.push('总人数', '实际分配总人数');
  526. // 整理opera
  527. for (let i = 0; i < rows.length; i++) {
  528. // 结束列-2: -1=> 第二列,有个班级类型,与上面位于同列,需要减掉; -1=>row5初始有个'',占了学校的列,重复了
  529. const opera = { startRow: i + 1, startCol: 2, endRow: i + 1, endCol: rows[i].length + row5.length - 2 };
  530. operaList.push(opera);
  531. for (let k = 1; k < row5.length - 1; k++) {
  532. rows[i].push('');
  533. }
  534. }
  535. rows.push(row5);
  536. // step2:处理计划
  537. let { termnum, school } = trainplan;
  538. termnum = this.sortPlan(termnum);
  539. const batchs = this.getListForBatch(termnum);
  540. // 期数变的是行,不是列
  541. const termRow = 1;
  542. // 因班级类型可能增加,所以此处是动态的
  543. let col = rows[termRow - 1].length + 1;
  544. const classRow = 2;
  545. const timeRow = 3;
  546. const remarkRow = 4;
  547. for (const term of termnum) {
  548. const { term: termstr, batchnum } = term;
  549. // 处理期数据
  550. rows[termRow - 1].push(termstr);
  551. const obj = { startRow: 1, startCol: col, endRow: 1, endCol: col + batchnum.length - 1 };
  552. operaList.push(obj);
  553. // step3,4:
  554. for (const b of batchnum) {
  555. const { startdate, enddate } = b;
  556. const word = this.setClassColunmWord(b, classType);
  557. // 填充班级列数据
  558. rows[classRow - 1].push(word);
  559. // 填充批次的时间
  560. const timeword = `${moment(startdate).format('M.D')} - ${moment(enddate).format('M.D')}`;
  561. rows[timeRow - 1].push(timeword);
  562. // 数据,进行填充
  563. rows[termRow - 1].push('');
  564. // 随之更新列
  565. col++;
  566. }
  567. // 因为期数需要占一个格子,所以得把在循环批次的时候加进去的-1
  568. rows[termRow - 1].pop();
  569. }
  570. // 整理注释
  571. const { data, opera } = this.setRemark(batchs, schtime, rows[remarkRow - 1], remarkRow, 1);
  572. rows[remarkRow - 1] = data;
  573. operaList.push(...opera);
  574. // 整理数据
  575. // ['学校名称','特殊班剩余人数','普通班剩余人数','总人数(预设)','实际分配总人数',...'对应批次的人数,没有就填充']
  576. const schData = await this.setSchoolData(schtime, batchs, school, classType);
  577. rows.push(...schData);
  578. return await this.ctx.service.util.toExcel(rows, null, fn, operaList);
  579. }
  580. /**
  581. * 计划排序
  582. * @param {Array} termnum 计划列表
  583. */
  584. sortPlan(termnum) {
  585. if (_.isArray(termnum) && termnum.length > 0) {
  586. // 数据排序
  587. termnum = termnum.map((t) => {
  588. const { batchnum, term } = t;
  589. t.termnum = parseInt(term);
  590. t.batchnum = batchnum.map((b) => {
  591. const { batch, class: classes } = b;
  592. b.batchnum = _.isNumber(parseInt(batch)) ? parseInt(batch) : batch;
  593. b.class = classes.map((c) => {
  594. const { name } = c;
  595. c.classnum = _.isNumber(parseInt(name)) ? parseInt(name) : name;
  596. return c;
  597. });
  598. b.class = _.orderBy(b.class, ['classnum'], ['asc']);
  599. return b;
  600. });
  601. return t;
  602. });
  603. termnum = _.orderBy(termnum, ['termnum'], ['asc']);
  604. }
  605. return termnum;
  606. }
  607. /**
  608. * 整理班级列的输出文字
  609. * @param {Object} b batch,批次数据
  610. * @param {Array} classType 班级类型列表
  611. */
  612. setClassColunmWord(b, classType) {
  613. const { class: classes } = b;
  614. const c = _.head(classes);
  615. let word = '';
  616. if (c) {
  617. const { type } = c;
  618. const r = classType.find((f) => f.code === type);
  619. word = classes.length;
  620. if (r) word = `${word}(${r.name})`;
  621. }
  622. return word;
  623. }
  624. /**
  625. * 整理备注
  626. * @param {Array} batchs 批次为元素的计划列表
  627. * @param {Array} schtime 学校计划
  628. * @param {Array} remarkRowData 备注行数据
  629. * @param {Number} remarkRow 备注开始行
  630. * @param {Number} mergeRow 备注要合并的行数
  631. */
  632. setRemark(batchs, schtime, remarkRowData, remarkRow, mergeRow) {
  633. let arr = [];
  634. for (const sp of schtime) {
  635. for (const arrange of sp.arrange) {
  636. if (_.get(arrange, 'remark')) arr.push(arrange);
  637. }
  638. }
  639. arr = _.uniqBy(arr, 'batchid');
  640. // 整理完备注,按照顺序,依次去找,是否有备注,有就推进去备注,没有推空
  641. const remarks = _.cloneDeep(remarkRowData);
  642. for (const b of batchs) {
  643. const r = arr.find((f) => ObjectId(f.batchid).equals(b._id));
  644. if (r) remarks.push(r.remark);
  645. else remarks.push('');
  646. }
  647. // 站位填充满
  648. // 整理操作, 主要是行的合并
  649. const opera = [];
  650. for (let i = remarkRowData.length; i < remarks.length; i++) {
  651. // i+1=>i为原数据的最后一个数据的位置,然而要处理的是后面的新添的数据
  652. opera.push({ startRow: remarkRow, startCol: i + 1, endRow: remarkRow + mergeRow, endCol: i + 1 });
  653. }
  654. return { data: remarks, opera };
  655. }
  656. /**
  657. * 整理学校安排的数据
  658. * @param {Array} schtime 学校安排的计划
  659. * @param {Array} batchs 以批次为元素的计划列表
  660. * @param {Array} schPlan 学校的预计划
  661. * @param {Array} classType 班级类型
  662. */
  663. async setSchoolData(schtime, batchs, schPlan, classType) {
  664. let schoolList = await this.smodel.find();
  665. const result = [];
  666. // 学校按code排序
  667. if (schoolList && schoolList.length > 0) {
  668. schoolList = JSON.parse(JSON.stringify(schoolList));
  669. schoolList = schoolList.map((i) => {
  670. i.schnum = this.toParseInt(i.code);
  671. return i;
  672. });
  673. schoolList = _.orderBy(schoolList, ['schnum'], ['asc']);
  674. }
  675. // 实际安排的学校计划
  676. const schArrange = [];
  677. for (const aobj of schtime) {
  678. const { schid, arrange } = aobj;
  679. if (!schid) continue;
  680. if (!_.isArray(arrange)) continue;
  681. for (const arrObj of arrange) {
  682. schArrange.push({ ...arrObj, schid });
  683. }
  684. }
  685. // 计算各个班级类型剩余人数,总人数,实际分配总人数
  686. for (const sch of schoolList) {
  687. const { name, code } = sch;
  688. // 该学校的数据
  689. const arr = [name];
  690. // 学校实际分配的计划, 先不管别的,先把计划的问题处理了
  691. const reaFRes = schArrange.filter((f) => f.schid === code);
  692. // 过滤出来学校已经分配的数据后,需要知道是什么类型的
  693. const reaObj = { total: 0, reaTotal: 0 }; // key:班级类型, value:为实际分配的人数
  694. for (const rr of reaFRes) {
  695. const { batchid, number } = rr;
  696. const r = batchs.find((f) => f._id === batchid);
  697. if (r) {
  698. const { type } = r;
  699. reaObj[type] = (this.toParseInt(reaObj[type]) || 0) + this.toParseInt(number); // 计划人数累加
  700. reaObj.reaTotal = _.add(this.toParseInt(reaObj.reaTotal), this.toParseInt(number)); // 实际人数累加
  701. }
  702. }
  703. // 先查预计划有没有
  704. const p = schPlan.find((f) => f.code === code);
  705. if (p) {
  706. // 获取到预设的学校计划
  707. const { classnum } = p;
  708. // 班级类型对应的计划
  709. for (const ct of classType) {
  710. const { code } = ct;
  711. const r = classnum.find((f) => f.code === code);
  712. // n为要求的人数
  713. let n = 0;
  714. if (r) {
  715. // 找到对应类型的计划了,计算这个班级类型是否分配完毕
  716. const { number } = r;
  717. if (number) n = this.toParseInt(number);
  718. }
  719. // 用code去reaObj中提取实际分配的人数,就可以算处的值
  720. const rea = this.toParseInt(reaObj[code]) || 0;
  721. let word = _.subtract(n - rea);
  722. // n===0:表示原来计划里没有这个类型,word再为0,说明实际上也没有这个类型,就不需要显示了
  723. if (n === 0 && word === 0) word = '';
  724. reaObj.total = _.add(reaObj.total, n); // 计划人数累加
  725. arr.push(word);
  726. }
  727. } else {
  728. // 如果没有这个学校的计划,就得看看reaObj中有没有分配,有分配还得处理;没分配就跳过下一个
  729. const keys = Object.keys(reaObj);
  730. for (const ct of classType) {
  731. if (keys.length <= 0) {
  732. // 没分配,填充,下一个
  733. arr.push('');
  734. } else {
  735. // 没计划但是实际分配了,就需要体现出来了
  736. const word = reaObj[ct.code];
  737. if (word && word !== 0) {
  738. arr.push(`-${word}`);
  739. } else {
  740. arr.push('');
  741. }
  742. }
  743. }
  744. }
  745. // 处理总人数和实际分配人数
  746. arr.push(reaObj.total);
  747. arr.push(reaObj.reaTotal);
  748. // 循环学校列表,找到学校的所有安排,然后找到对应的索引,进行数据整理
  749. for (const rea of reaFRes) {
  750. const index = batchs.findIndex((f) => f._id === rea.batchid);
  751. if (index < 0) continue;
  752. arr[index + 5] = rea.number;
  753. }
  754. result.push(arr);
  755. }
  756. // 合计行:只有学校列不计算,其他的列全部计算=>批次列(batchs.length)+班级类型列(classType.length)+总人数列(1)+实际分配人数列(1)
  757. const colTotal = batchs.length + classType.length + 1 + 1;
  758. const count = ['合计'];
  759. // 第一列不需要,是学校/合计列
  760. for (let i = 1; i <= colTotal; i++) {
  761. const cmid = [];
  762. for (const arr of result) {
  763. let number = this.toParseInt(_.get(arr, i, 0));
  764. if (_.isNaN(number)) number = 0;
  765. cmid.push(number);
  766. }
  767. const colCount = cmid.reduce((p, n) => p + n, 0);
  768. count.push(colCount);
  769. }
  770. result.push(count);
  771. return result;
  772. }
  773. toParseInt(number) {
  774. let num = parseInt(number);
  775. if (_.isNaN(num)) num = 0;
  776. return num;
  777. }
  778. /**
  779. * 获取批次列表(排完顺序了,直接拿出来)
  780. * @param {Array} termnum 计划列表
  781. */
  782. getListForBatch(termnum) {
  783. const arr = [];
  784. for (const t of termnum) {
  785. for (const b of t.batchnum) {
  786. const obj = { ...b };
  787. const { class: classes } = b;
  788. if (_.isArray(classes)) {
  789. const head = _.head(classes);
  790. if (head) {
  791. const { type } = head;
  792. if (type) obj.type = type;
  793. }
  794. const all = classes.reduce((p, n) => p + (parseInt(n.number) || 0), 0);
  795. if (_.isNumber(all)) b.all = all;
  796. }
  797. arr.push(obj);
  798. }
  799. }
  800. return arr;
  801. }
  802. // 导出学校大表
  803. async exportPlan({ trainplanId }) {
  804. const wscols = [
  805. { wpx: 50 }, // 第一列宽度设置单位px
  806. ];
  807. const monthList = [];
  808. // 月份合并单元格
  809. const colzb = 0;
  810. let rowzb = 1;
  811. // 头部合并单元格
  812. const coltb = 0;
  813. let rowtb = 0;
  814. // 人数合并单元格
  815. const colrs = 0;
  816. let rowrs = 1;
  817. // 人数数量合并单元格
  818. const colrssl = 0;
  819. let rowrssl = 3;
  820. // 班级数合并单元格
  821. const colbjs = 0;
  822. let rowbjs = 1;
  823. // 班级数数量合并单元格
  824. const colbjssl = 0;
  825. let rowbjssl = 3;
  826. // 数据
  827. const data = [];
  828. let colRowBJSSL = {};
  829. // 这里是头部颜色
  830. const tatleCell = { v: '', s: { fill: { fgColor: { rgb: '191970' } } } };
  831. // 坐标
  832. const tatleCellstyle = 0;
  833. let tatleRowstyle = 0;
  834. const styleTatle = [];
  835. // 这里是月份颜色
  836. const monthCell = [
  837. { v: '一月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  838. { v: '二月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  839. { v: '三月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  840. { v: '四月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  841. { v: '五月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  842. { v: '六月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  843. { v: '七月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  844. { v: '八月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  845. { v: '九月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  846. { v: '十月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  847. { v: '十一月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  848. { v: '十二月', s: { fill: { fgColor: { rgb: 'B0E2FF' } } } },
  849. ];
  850. // 坐标
  851. const monthCellstyle = 0;
  852. let monthRowstyle = 1;
  853. const styleMonth = [];
  854. // 这里是假期颜色
  855. const festivalsCell = {
  856. v: '',
  857. s: { fill: { fgColor: { rgb: 'A2CD5A' } } },
  858. };
  859. // 坐标
  860. const festivalsCellstyle = 0;
  861. let festivalsRowstyle = 0;
  862. const stylefestivals = [];
  863. // 计划表
  864. const trainplan = await this.model.findOne({ _id: trainplanId });
  865. const termnum = trainplan.termnum;
  866. let classNum = 0;
  867. // 获取最大的班级数,也就是月份的高
  868. for (const term of termnum) {
  869. if (term.classnum > classNum) {
  870. classNum = parseInt(term.classnum);
  871. }
  872. }
  873. // 得到所有的节日日期的数组,然后循环时注意得到一个删除一个
  874. const festivals = trainplan.festivals;
  875. const festivalList = this.getfestivalList(festivals);
  876. const termnumList = this.gettermnumList(termnum);
  877. // 得到所有班级的数组,然后循环时注意得到一个删除一个
  878. // 循环12个月,得到12个月以及每个月的数据
  879. for (let index = 1; index < 13; index++) {
  880. // 这里增加表格头部下标
  881. const tatleCells = XLSX.utils.encode_cell({
  882. c: tatleCellstyle,
  883. r: tatleRowstyle,
  884. });
  885. tatleRowstyle = tatleRowstyle + classNum + 3;
  886. styleTatle.push(tatleCells);
  887. // 这里是月份颜色
  888. const monthCells = XLSX.utils.encode_cell({
  889. c: monthCellstyle,
  890. r: monthRowstyle,
  891. });
  892. monthRowstyle = monthRowstyle + classNum + 3;
  893. styleMonth.push(monthCells);
  894. for (let j = 0; j < festivalList.length; j++) {
  895. const festival = festivalList[j];
  896. // 如果月份相同时才会增加
  897. const yue = parseInt(festival.substr(5, 2));
  898. const lie = parseInt(festival.substr(8, 2));
  899. if (index === yue) {
  900. // 这里是假期颜色这一列列7行都是这个颜色
  901. for (let k = 0; k < classNum; k++) {
  902. const festivalsCells = XLSX.utils.encode_cell({
  903. // 列
  904. c: festivalsCellstyle + lie,
  905. r: festivalsRowstyle + k + 3,
  906. });
  907. stylefestivals.push(festivalsCells);
  908. }
  909. }
  910. }
  911. festivalsRowstyle = festivalsRowstyle + classNum + 3;
  912. // 添加月份坐标
  913. const colRow = {
  914. s: { c: colzb, r: rowzb },
  915. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  916. e: { c: colzb, r: rowzb + classNum + 1 },
  917. };
  918. // rowzb为上一次终止,那么起始需+1,这里加3,代表头部+月份+星期,所以+3
  919. rowzb = rowzb + classNum + 3;
  920. monthList.push(colRow);
  921. // 添加头部坐标
  922. const colRowTB = {
  923. s: { c: coltb, r: rowtb },
  924. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  925. e: { c: coltb + 33, r: rowtb },
  926. };
  927. // rowzb为上一次终止,那么起始需+1,
  928. rowtb = rowtb + classNum + 3;
  929. monthList.push(colRowTB);
  930. // 添加人数坐标
  931. const colRowRS = {
  932. s: { c: colrs + 32, r: rowrs },
  933. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  934. e: { c: colrs + 32, r: rowrs + 1 },
  935. };
  936. // rowzb为上一次终止,那么起始需+1,
  937. rowrs = rowrs + classNum + 3;
  938. monthList.push(colRowRS);
  939. // 添加人数数量坐标
  940. const colRowRSSL = {
  941. s: { c: colrssl + 32, r: rowrssl },
  942. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  943. e: { c: colrssl + 32, r: rowrssl + classNum - 1 },
  944. };
  945. // rowzb为上一次终止,那么起始需+1,
  946. rowrssl = rowrssl + classNum + 3;
  947. monthList.push(colRowRSSL);
  948. // 添加班级数坐标
  949. const colRowBJS = {
  950. s: { c: colbjs + 33, r: rowbjs },
  951. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  952. e: { c: colbjs + 33, r: rowbjs + 1 },
  953. };
  954. // rowzb为上一次终止,那么起始需+1,
  955. rowbjs = rowbjs + classNum + 3;
  956. monthList.push(colRowBJS);
  957. // 添加班级数数量坐标
  958. colRowBJSSL = {
  959. s: { c: colbjssl + 33, r: rowbjssl },
  960. // 保证留下7个空行,如果需要在上面加值,直接在下面加入即可第几空行加入就行
  961. e: { c: colbjssl + 33, r: rowbjssl + classNum - 1 },
  962. };
  963. // rowzb为上一次终止,那么起始需+1,
  964. rowbjssl = rowbjssl + classNum + 3;
  965. monthList.push(colRowBJSSL);
  966. const resDate = this.makeCalendar(trainplan.year, index);
  967. data.push(['']);
  968. data.push([[this.getBigMonth(index) + '月']].concat(resDate.dlist).concat(['人数'].concat(['班级数'])));
  969. data.push([''].concat(resDate.tlist));
  970. // 加列数组
  971. for (let i = 0; i < classNum; i++) {
  972. data.push('');
  973. }
  974. }
  975. // ...以此类推即可
  976. /** 头部-行列信息*/
  977. const ws = XLSX.utils.aoa_to_sheet(data);
  978. // 构建 workbook 对象
  979. const nowDate = new Date().getTime();
  980. const path = 'D:\\wwwroot\\service\\service-file\\upload\\train\\' + nowDate + '.xlsx';
  981. const respath = 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
  982. // 导出
  983. const wb = XLSX.utils.book_new();
  984. XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  985. ws['!cols'] = wscols;
  986. ws['!merges'] = monthList;
  987. // 头部赋值颜色需要计算出坐标
  988. for (const tatlezb of styleTatle) {
  989. ws[tatlezb] = tatleCell;
  990. }
  991. // 月份赋值颜色需要计算出坐标
  992. for (let index = 0; index < styleMonth.length; index++) {
  993. ws[styleMonth[index]] = monthCell[index];
  994. }
  995. // 假期赋值颜色需要计算出坐标
  996. for (const festivals of stylefestivals) {
  997. ws[festivals] = festivalsCell;
  998. }
  999. XLSXStyle.writeFile(wb, path);
  1000. return respath;
  1001. }
  1002. // 获取批次日期列表
  1003. gettermnumList(termnums) {
  1004. const termnumList = [];
  1005. for (const termnum of termnums) {
  1006. termnum.term;
  1007. termnum.classnum;
  1008. for (const batchnum of termnum.batchnum) {
  1009. batchnum.batch;
  1010. batchnum.class.length;
  1011. batchnum.startdate;
  1012. batchnum.enddate;
  1013. }
  1014. }
  1015. return termnumList;
  1016. }
  1017. // 获取节假日集合
  1018. getfestivalList(festivals) {
  1019. let dateList = [];
  1020. for (let index = 0; index < festivals.length; index++) {
  1021. dateList = [...dateList, ...utils.begindateEnddateSum(festivals[index].begindate, festivals[index].finishdate)];
  1022. }
  1023. return dateList;
  1024. }
  1025. // 获取大月份传过来的值是以1月份开始的
  1026. getBigMonth(index) {
  1027. const monthBig = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二'];
  1028. return monthBig[index - 1];
  1029. }
  1030. // 获取这个月份的所有日期1~30号或者31或者28,或者29
  1031. makeCalendar(year, month = 1, month0) {
  1032. month0 = month;
  1033. if (month * 1 < 10) month = '0' + month;
  1034. // 获取这个月份的最大值
  1035. const days = moment(year + '-' + month).daysInMonth();
  1036. const dlist = this.getDayList(year, month, days, month0);
  1037. while (dlist.dlist.length < 31) {
  1038. dlist.dlist.push('');
  1039. }
  1040. return dlist;
  1041. }
  1042. // 获取这个月份的1-30号经过加工的
  1043. getDayList(year, month, days, month0) {
  1044. const dlist = [];
  1045. const tlist = [];
  1046. const all = {};
  1047. for (let index = 0; index < days; index++) {
  1048. dlist.push(
  1049. month0 +
  1050. '月' +
  1051. moment(year + '-' + month)
  1052. .add(index, 'days')
  1053. .format('D') +
  1054. '日'
  1055. );
  1056. let dayy = parseInt(index + 1);
  1057. if (dayy * 1 < 10) dayy = '0' + dayy;
  1058. tlist.push(this.getWeekDay(year + '-' + month + '-' + dayy));
  1059. }
  1060. all.dlist = dlist;
  1061. all.tlist = tlist;
  1062. return all;
  1063. }
  1064. // 获取星期几
  1065. getWeekDay(datestr) {
  1066. const weekday = moment(datestr).weekday();
  1067. if (weekday || weekday === 0) {
  1068. const arr = ['日', '一', '二', '三', '四', '五', '六'];
  1069. return '星期' + arr[weekday];
  1070. }
  1071. return '';
  1072. }
  1073. // async updateclass({ trainplanid, classid, rightHeader }) {
  1074. // assert(trainplanid && classid && rightHeader, '缺少参数项');
  1075. async updateclass({ trainplanid, termid, batchid, classid, rightHeader }) {
  1076. assert(trainplanid && termid && batchid && classid && rightHeader, '缺少参数项');
  1077. // 根据全年计划表id查出对应的全年计划详细信息
  1078. const trainplan = await this.model.findById(trainplanid);
  1079. if (!trainplan) {
  1080. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  1081. }
  1082. const term = trainplan.termnum.id(termid);
  1083. if (!term) {
  1084. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '期信息不存在');
  1085. }
  1086. const batch = term.batchnum.id(batchid);
  1087. if (!batch) {
  1088. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '批次信息不存在');
  1089. }
  1090. const class_ = await batch.class.id(classid);
  1091. if (class_) {
  1092. class_.headteacherid = rightHeader;
  1093. }
  1094. const res = await trainplan.save();
  1095. if (res) {
  1096. const cla_ = await this.clamodel.findOne({
  1097. termid,
  1098. batchid,
  1099. name: class_.name,
  1100. });
  1101. if (cla_) {
  1102. cla_.headteacherid = rightHeader;
  1103. await cla_.save();
  1104. }
  1105. }
  1106. return res;
  1107. }
  1108. async updatereteacher({ trainplanid, termid, placereteacher }) {
  1109. assert(trainplanid && termid && placereteacher, '缺少参数项');
  1110. // 根据全年计划表id查出对应的全年计划详细信息
  1111. const trainplan = await this.model.findById(trainplanid);
  1112. if (!trainplan) {
  1113. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  1114. }
  1115. const termnum = trainplan.termnum.find((f) => ObjectId(termid).equals(f._id));
  1116. if (termnum) {
  1117. termnum.placereteacher = placereteacher;
  1118. }
  1119. await this.model.updateOne({ _id: trainplanid }, trainplan);
  1120. }
  1121. }
  1122. module.exports = TrainplanService;