school.js 13 KB

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