school.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. const XLSX = require('xlsx');
  9. class SchoolService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'schoolctrl');
  12. this.model = this.ctx.model.School;
  13. this.smodel = this.ctx.model.Student;
  14. this.umodel = this.ctx.model.User;
  15. this.tmodel = this.ctx.model.Trainplan;
  16. this.jmodel = this.ctx.model.Job;
  17. this.schmodel = this.ctx.model.Schtime;
  18. }
  19. async create(data) {
  20. const { code, name } = data;
  21. assert(code, '缺少学校代码');
  22. assert(name, '缺少学校名称');
  23. const res = await this.model.create(data);
  24. if (res) {
  25. const obj = { mobile: code, name, type: '2', uid: res._id, passwd: { secret: '12345678' } };
  26. await this.umodel.create(obj);
  27. }
  28. return res;
  29. }
  30. async stuimport(data) {
  31. const { filepath, termid, schid, type, batchid } = data;
  32. assert(filepath, 'filepath不能为空');
  33. assert(termid, 'termid不能为空');
  34. assert(schid, 'schid不能为空');
  35. // 根据termid取得计划信息
  36. const plan = await this.tmodel.findOne({ 'termnum._id': ObjectId(termid) });
  37. if (!plan) {
  38. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '计划信息不存在');
  39. }
  40. // 取得学校预计人数
  41. const num_ = await this.getschnum(plan, type, schid, termid);
  42. console.log('*******************');
  43. console.log(num_);
  44. console.log('*******************');
  45. const planid = plan.id;
  46. const planyearid = plan.planyearid;
  47. // 取得excle中数据
  48. const _filepath = this.ctx.app.config.baseUrl + filepath;
  49. console.log(_filepath);
  50. const studatas = await this.getImportXLSXData(
  51. _filepath,
  52. termid,
  53. schid,
  54. planid,
  55. planyearid,
  56. type,
  57. batchid
  58. );
  59. // 将得到的数据校验
  60. const datacheck = await this.datacheck(studatas);
  61. if (datacheck.errorcode === '1') {
  62. return datacheck;
  63. }
  64. const school_ = await this.model.findOne({ code: schid });
  65. let schname = '';
  66. if (school_) {
  67. schname = school_.name;
  68. }
  69. const trem_ = await plan.termnum.id(termid);
  70. if (!trem_) {
  71. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '期信息不存在');
  72. }
  73. const nowtime = moment().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss');
  74. if (studatas.length > num_) {
  75. const jobdata = {
  76. code: schid,
  77. name: schname,
  78. planid: plan.id,
  79. termid,
  80. term: trem_.term,
  81. batchid,
  82. filepath,
  83. studs: JSON.stringify(studatas),
  84. plannum: num_,
  85. schnum: studatas.length,
  86. isstore: '0',
  87. createtime: nowtime,
  88. type,
  89. reason: '学校上传人数超过预期人数,请联系中心管理员',
  90. };
  91. await this.jmodel.create(jobdata);
  92. throw new BusinessError(
  93. ErrorCode.SERVICE_FAULT,
  94. '学校上传人数超过预期人数,请联系中心管理员'
  95. );
  96. } else if (studatas.length < num_) {
  97. const jobdata = {
  98. code: schid,
  99. name: schname,
  100. planid: plan.id,
  101. termid,
  102. term: trem_.term,
  103. batchid,
  104. filepath,
  105. studs: JSON.stringify(studatas),
  106. plannum: num_,
  107. schnum: studatas.length,
  108. isstore: '0',
  109. createtime: nowtime,
  110. type,
  111. reason: '学校上传人数少于预期人数,请联系中心管理员',
  112. };
  113. await this.jmodel.create(jobdata);
  114. throw new BusinessError(
  115. ErrorCode.SERVICE_FAULT,
  116. '学校上传人数少于预期人数,请联系中心管理员'
  117. );
  118. }
  119. // 将数据存入数据库中
  120. for (const stu of studatas) {
  121. const res = await this.smodel.create(stu);
  122. // if (res) {
  123. // const newdata = { name: stu.name, mobile: stu.phone, type: '4', uid: res.id };
  124. // newdata.passwd = { secret: '12345678' };
  125. // await this.umodel.create(newdata);
  126. // }
  127. }
  128. return datacheck;
  129. }
  130. // 取得学校预计人数
  131. async getschnum(plan, type, schid, termid) {
  132. const schtime = await this.schmodel.findOne({ schid, planid: plan.id });
  133. let { arrange } = schtime;
  134. const { termnum } = plan;
  135. arrange = _.groupBy(arrange, 'term');
  136. const keys = Object.keys(arrange);
  137. let arr = keys.map(key => {
  138. const rt = termnum.find(f => f.term === key);
  139. let ar = arrange[key];
  140. ar = ar.map(a => {
  141. const rb = rt.batchnum.find(f => f.batch === a.batch);
  142. if (rb) {
  143. const bh = _.head(rb.class);
  144. const { type } = bh;
  145. a.type = type;
  146. return a;
  147. }
  148. });
  149. let garr = _.groupBy(ar, 'type');
  150. const gks = Object.keys(garr);
  151. garr = gks.map(gk => {
  152. const { term, termid } = _.head(garr[gk]);
  153. const number = garr[gk].reduce((p, n) => p + n.number * 1, 0);
  154. return { term, termid, number, type: gk };
  155. });
  156. return garr;
  157. });
  158. arr = arr.flat();
  159. const obj_ = _.find(arr, { termid, type });
  160. return obj_.number;
  161. }
  162. // 获取导入的XLSX文件中的数据
  163. async getImportXLSXData(filepath, termid, schid, planid, planyearid, type, batchid) {
  164. console.log(filepath);
  165. const file = await this.ctx.curl(filepath);
  166. const workbook = XLSX.read(file.data);
  167. // 读取内容
  168. let exceldata = [];
  169. const sheetNames = workbook.SheetNames; // 获取表名
  170. const sheet = workbook.Sheets[sheetNames[0]]; // 通过表名得到表对象
  171. // 遍历26个字母
  172. const theadRule = [];
  173. const range = XLSX.utils.decode_range(sheet['!ref']);
  174. const col_start = range.s.c;
  175. const col_end = range.e.c;
  176. for (let i = col_start; i <= col_end; i++) {
  177. const addr = XLSX.utils.encode_col(i) + XLSX.utils.encode_row(0);
  178. theadRule.push(sheet[addr].v);
  179. }
  180. // const theadRule = [ sheet.A1.v, sheet.B1.v, sheet.C1.v, sheet.D1.v, sheet.E1.v, sheet.F1.v, sheet.G1.v, sheet.H1.v, sheet.I1.v, sheet.J1.v, sheet.K1.v, sheet.L1.v, sheet.M1.v, sheet.N1.v, sheet.O1.v, sheet.P1.v, sheet.Q1.v, sheet.R1.v ];
  181. const params = XLSX.utils.sheet_to_json(sheet); // 通过工具将表对象的数据读出来并转成json
  182. // const theadRule = [ '序号', '姓名', '性别', '民族', '身份证号', '学校名称', '院系', '专业', '入学年份', '毕业年份', '在校曾担任何种职务', '手机号', 'QQ号', '家庭所在地', '家庭是否困难', '是否获得过助学金' ];
  183. if (!params) return [];
  184. let i = 0;
  185. const length = params.length;
  186. const _datas = [];
  187. let data = {};
  188. for (i; i < length; i++) {
  189. data = params[i];
  190. const diy_ = [];
  191. if (theadRule.length > 18) {
  192. for (let j = 18; j < theadRule.length; j++) {
  193. const newdata = {
  194. itemname: theadRule[j],
  195. itemvalue: data[theadRule[j]],
  196. };
  197. diy_.push(newdata);
  198. }
  199. }
  200. _datas.push({
  201. name: data[theadRule[1]],
  202. gender: data[theadRule[2]],
  203. nation: data[theadRule[3]],
  204. id_number: data[theadRule[4]],
  205. school_name: data[theadRule[5]],
  206. faculty: data[theadRule[6]],
  207. major: data[theadRule[7]],
  208. entry_year: data[theadRule[8]],
  209. finish_year: data[theadRule[9]],
  210. school_job: data[theadRule[10]],
  211. phone: data[theadRule[11]],
  212. qq: data[theadRule[12]],
  213. family_place: data[theadRule[13]],
  214. family_is_hard: data[theadRule[14]],
  215. have_grant: data[theadRule[15]],
  216. edua_level: data[theadRule[16]],
  217. edua_system: data[theadRule[17]],
  218. diy: diy_,
  219. termid,
  220. batchid,
  221. schid,
  222. planid,
  223. planyearid,
  224. type,
  225. });
  226. }
  227. exceldata = [ ...exceldata, ..._datas ];
  228. return exceldata;
  229. }
  230. // 获取导入的XLSX文件中的数据
  231. async datacheck(studatas) {
  232. let errorcode = '0';
  233. const errormsg = [];
  234. for (const data of studatas) {
  235. // 判断是否为空
  236. if (!data.name) {
  237. errorcode = '1';
  238. data.msg = data.msg + '姓名不允许为空,';
  239. }
  240. if (!data.gender) {
  241. errorcode = '1';
  242. data.msg = data.msg + '性别不允许为空,';
  243. }
  244. if (!data.nation) {
  245. errorcode = '1';
  246. data.msg = data.msg + '民族不允许为空,';
  247. }
  248. if (!data.id_number) {
  249. errorcode = '1';
  250. data.msg = data.msg + '身份证号不允许为空,';
  251. }
  252. if (!data.school_name) {
  253. errorcode = '1';
  254. data.msg = data.msg + '学校名称不允许为空,';
  255. }
  256. if (!data.phone) {
  257. errorcode = '1';
  258. data.msg = data.msg + '手机号不允许为空,';
  259. }
  260. if (!data.faculty) {
  261. errorcode = '1';
  262. data.msg = data.msg + '院系不允许为空,';
  263. }
  264. if (!data.major) {
  265. errorcode = '1';
  266. data.msg = data.msg + '专业不允许为空,';
  267. }
  268. if (!data.entry_year) {
  269. errorcode = '1';
  270. data.msg = data.msg + '入学年份不允许为空,';
  271. }
  272. if (!data.finish_year) {
  273. errorcode = '1';
  274. data.msg = data.msg + '毕业年份不允许为空,';
  275. }
  276. if (!data.school_job) {
  277. errorcode = '1';
  278. data.msg = data.msg + '职务不允许为空,';
  279. }
  280. if (!data.qq) {
  281. errorcode = '1';
  282. data.msg = data.msg + 'QQ号不允许为空,';
  283. }
  284. if (!data.family_place) {
  285. errorcode = '1';
  286. data.msg = data.msg + '家庭所在地不允许为空,';
  287. }
  288. if (!data.family_is_hard) {
  289. errorcode = '1';
  290. data.msg = data.msg + '家庭是否困难不允许为空,';
  291. }
  292. if (!data.have_grant) {
  293. errorcode = '1';
  294. data.msg = data.msg + '是否获得过助学金不允许为空,';
  295. }
  296. if (!/^\d{11}$/i.test(data.phone)) {
  297. errorcode = '1';
  298. data.msg = data.msg + '手机号不正确,';
  299. }
  300. const res = await this.smodel.findOne({ id_number: data.id_number });
  301. if (res) {
  302. errorcode = '1';
  303. data.msg = data.msg + '学生已经存在请检查,';
  304. }
  305. if (errorcode === '1') {
  306. errormsg.push(data);
  307. }
  308. }
  309. return { errorcode, errormsg };
  310. }
  311. // 导出学校名单
  312. async exportSchool({ trainplanId }) {
  313. // 批次期次都在这里面
  314. const trainplan = await this.tmodel.find({ _id: trainplanId });
  315. console.log(trainplan);
  316. const _headers = [
  317. { key: 'title', title: '计划标题' },
  318. ];
  319. // 需要打出的列表
  320. const _data = trainplan;
  321. const headers = _headers.map(({ title }) =>
  322. title).map((v, i) =>
  323. Object.assign({}, { v, position: String.fromCharCode(65 + i) + 1 })
  324. ).reduce(
  325. (prev, next) =>
  326. Object.assign({}, prev, { [next.position]: { v: next.v } }),
  327. {}
  328. );
  329. const data = _data.map((v, i) =>
  330. _headers.map(({ key }, j) =>
  331. Object.assign(
  332. {},
  333. { v: v[key], position: String.fromCharCode(65 + j) + (i + 2) }
  334. )
  335. )
  336. )
  337. .reduce((prev, next) => prev.concat(next))
  338. .reduce(
  339. (prev, next) =>
  340. Object.assign({}, prev, { [next.position]: { v: next.v } }),
  341. {}
  342. );
  343. // 合并 headers 和 data
  344. const output = Object.assign({}, headers, data);
  345. // 获取所有单元格的位置
  346. const outputPos = Object.keys(output);
  347. // 计算出范围
  348. const ref = outputPos[0] + ':' + outputPos[outputPos.length - 1];
  349. // 构建 workbook 对象
  350. const nowDate = new Date().getTime();
  351. const path =
  352. 'D:\\wwwroot\\service\\service-file\\upload\\train\\' +
  353. nowDate +
  354. '.xlsx';
  355. const respath =
  356. 'http://free.liaoningdoupo.com:80/files/train/' + nowDate + '.xlsx';
  357. const wb = {
  358. SheetNames: [ 'sheet0' ],
  359. Sheets: { sheet0: Object.assign({}, output, { '!ref': ref }) },
  360. };
  361. // 导出 Excel
  362. XLSX.writeFile(wb, path);
  363. return respath;
  364. }
  365. async updateclass({ trainplanid, classid, rightHeader }) {
  366. assert(trainplanid && classid && rightHeader, '缺少参数项');
  367. // 根据全年计划表id查出对应的全年计划详细信息
  368. const trainplan = await this.model.findById(trainplanid);
  369. if (!trainplan) {
  370. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  371. }
  372. for (const term of trainplan.termnum) {
  373. for (const batch of term.batchnum) {
  374. const class_ = await batch.class.id(classid);
  375. if (class_) {
  376. class_.headteacherid = rightHeader;
  377. }
  378. }
  379. }
  380. return await trainplan.save();
  381. }
  382. async updatereteacher({ trainplanid, termid, reteacher }) {
  383. assert(trainplanid && termid && reteacher, '缺少参数项');
  384. // 根据全年计划表id查出对应的全年计划详细信息
  385. const trainplan = await this.model.findById(trainplanid);
  386. if (!trainplan) {
  387. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '全年计划信息不存在');
  388. }
  389. const term = await trainplan.termnum.id(termid);
  390. if (term) {
  391. term.reteacher = reteacher;
  392. }
  393. return await trainplan.save();
  394. }
  395. }
  396. module.exports = SchoolService;