trainplan.js 42 KB

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