questionnaire.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const moment = require('moment');
  5. const { ObjectId } = require('mongoose').Types;
  6. const { CrudService } = require('naf-framework-mongoose/lib/service');
  7. const { BusinessError, ErrorCode } = require('naf-core').Error;
  8. class QuestionnaireService extends CrudService {
  9. constructor(ctx) {
  10. super(ctx, 'qusetionnaire');
  11. this.questionnairemodel = this.ctx.model.Questionnaire;
  12. this.questionmodel = this.ctx.model.Question;
  13. const { baseUrl } = _.get(this.ctx.app.config, 'mission');
  14. if (baseUrl) this.missionBase = baseUrl;
  15. }
  16. // 插入问卷
  17. async create(data) {
  18. const { name, num, type, question } = data;
  19. assert(name, '问卷名称不能为空');
  20. assert(num, '问卷序号不能为空');
  21. assert(type, '问卷类型不能为空');
  22. const quedata = [];
  23. for (const elm of question) {
  24. const ques = await this.questionmodel.findById(elm);
  25. if (ques) {
  26. quedata.push(ques);
  27. }
  28. }
  29. data.question = quedata;
  30. return await this.questionnairemodel.create(data);
  31. }
  32. // 根据id删除问卷
  33. async delete({ id }) {
  34. await this.questionnairemodel.findByIdAndDelete(id);
  35. return 'deleted';
  36. }
  37. // 根据id更新问卷信息
  38. async update({ id }, data) {
  39. const { name, num, type, question, status } = data;
  40. const questionnaire = await this.questionnairemodel.findById(id);
  41. if (name) {
  42. questionnaire.name = name;
  43. }
  44. if (num) {
  45. questionnaire.num = num;
  46. }
  47. if (type) {
  48. questionnaire.type = type;
  49. }
  50. if (status) {
  51. questionnaire.status = status;
  52. }
  53. if (question) {
  54. const quedata = [];
  55. for (const elm of question) {
  56. if (elm && !_.isObject(elm)) {
  57. const ques = await this.questionmodel.findById(elm);
  58. if (ques) {
  59. quedata.push(ques);
  60. }
  61. } else if (elm) quedata.push(elm);
  62. }
  63. questionnaire.question = quedata;
  64. }
  65. return await questionnaire.save();
  66. }
  67. // 查询
  68. async query({ skip, limit, ...num }) {
  69. const total = await this.questionnairemodel.count(num);
  70. const data = await this.questionnairemodel.find(num).skip(Number(skip)).limit(Number(limit));
  71. const result = { total, data };
  72. return result;
  73. }
  74. // 查询详情
  75. async show({ id }) {
  76. const questionnaire = await this.questionnairemodel.findById(id);
  77. return questionnaire;
  78. }
  79. // 建立任务
  80. async toExport(body) {
  81. const { range, questionnaireid } = body;
  82. const questionnaire = await this.questionnairemodel.findById(questionnaireid);
  83. if (!questionnaire) {
  84. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到问卷信息');
  85. }
  86. const fn = await this.toSetFileName(questionnaire.name, range);
  87. const data = {
  88. title: fn,
  89. params: {
  90. project: 'center',
  91. service: 'questionnaire',
  92. method: 'export',
  93. body,
  94. },
  95. };
  96. if (this.missionBase) {
  97. const url = `${this.missionBase}/api/mission`;
  98. const res = await this.ctx.curl(url, {
  99. method: 'post',
  100. headers: {
  101. 'content-type': 'application/json',
  102. },
  103. data,
  104. dataType: 'json',
  105. });
  106. if (res.status !== 200 || res.data.errcode !== 0) {
  107. throw new BusinessError(ErrorCode.SERVICE_FAULT, '创建任务失败');
  108. }
  109. } else {
  110. throw new BusinessError(ErrorCode.SERVICE_FAULT, '未找到任务项目设置');
  111. }
  112. }
  113. /**
  114. * 导出问卷
  115. * @param {Object} { range, direction, questionnaireid, modelList, missionid } 数据集合
  116. * @property Object range 学生的查询范围
  117. * @property String direction horizontal横向/vertical纵向
  118. * @property String questionnaireid 问卷id
  119. * @property Array modelList 要导出的字段,学生和问卷都在这里, 学生的table:student, 问卷的table:questionnaire
  120. * @property String missionid 任务id
  121. */
  122. async export({ range, direction, questionnaireid, modelList, missionid }) {
  123. assert(missionid, '缺少任务信息,无法执行任务');
  124. try {
  125. // 将期批班转换
  126. modelList = modelList.map(i => {
  127. const { model } = i;
  128. if (model === 'termid') i.model = 'termname';
  129. else if (model === 'batchid') i.model = 'batchname';
  130. else if (model === 'classid') i.model = 'classname';
  131. return i;
  132. });
  133. // 获取问卷
  134. const questionnaire = await this.questionnairemodel.findById(questionnaireid);
  135. if (!questionnaire) {
  136. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到问卷信息');
  137. }
  138. let fn = await this.toSetFileName(questionnaire.name, range);
  139. // this.ctx.service.util.updateProcess(missionid, '25');
  140. // 修改条件,termid变成数组了,需要一个一个查出来
  141. const { planid, batchid, classid } = range;
  142. let { termid } = range;
  143. const queryObject = {};
  144. if (planid) queryObject.planid = planid;
  145. if (batchid) queryObject.batchid = batchid;
  146. if (classid) queryObject.classid = classid;
  147. let count = 0;
  148. let dp;
  149. const qkeys = Object.keys(range);
  150. if (qkeys.length === 2 && termid.length <= 0) {
  151. // 说明只有planid
  152. const plan = await this.ctx.model.Trainplan.findOne({ _id: ObjectId(planid) });
  153. if (!plan) throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定年度计划');
  154. termid = plan.termnum.map(i => JSON.parse(JSON.stringify(i._id)));
  155. }
  156. for (const t of termid) {
  157. queryObject.termid = t;
  158. let data = await this.toGetData(queryObject, questionnaireid, direction, modelList);
  159. if (!data) continue;
  160. if (count !== 0 && direction === 'horizontal') data.shift();
  161. if (count !== 0 && direction === 'vertical') {
  162. data = data.map(i => {
  163. i.shift();
  164. return i;
  165. });
  166. }
  167. const { downloadPath, fn: newFileName } = await this.ctx.service.util.toAsyncExcel(data, fn, dp, direction);
  168. dp = downloadPath;
  169. fn = newFileName;
  170. count++;
  171. }
  172. this.ctx.service.util.updateProcess(missionid, '100', '2', {
  173. uri: dp,
  174. });
  175. } catch (error) {
  176. console.log(error);
  177. this.ctx.service.util.updateProcess(missionid, undefined, '3');
  178. }
  179. }
  180. /**
  181. * 获取学生与学生回答的问卷
  182. * @param {Object} condition 查询学生和学生回答问卷的条件
  183. * @param {String} questionnaireid 问卷id
  184. * @param {String} direction 方向
  185. * @param {Array} modelList 导出字段
  186. */
  187. async toGetData(condition, questionnaireid, direction, modelList) {
  188. // 获取学生
  189. let studentList = await this.ctx.service.student.query(condition);
  190. if (studentList.length <= 0) {
  191. this.ctx.logger.error(`${JSON.stringify(condition)}条件下,未找到任何信息`);
  192. return;
  193. // throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到任何学生信息');
  194. }
  195. studentList = JSON.parse(JSON.stringify(studentList));
  196. // 再获取问卷答案
  197. const questAnswerList = await this.ctx.model.Uploadquestion.find({
  198. ...condition,
  199. questionnaireid,
  200. });
  201. if (!questAnswerList) {
  202. this.ctx.logger.error(`${JSON.stringify(condition)}&${questionnaireid}条件下,未找到任何完成的问卷`);
  203. return;
  204. }
  205. let res = [];
  206. let data = [];
  207. if (direction === 'horizontal') {
  208. const head = this.getHead(direction, modelList, studentList.length);
  209. data = this.horizontalSetData(studentList, questAnswerList, modelList);
  210. res.push(head.map(i => i.header));
  211. for (const d of data) {
  212. const mid = [];
  213. for (const h of head) {
  214. const { key } = h;
  215. mid.push(_.get(d, key, ''));
  216. }
  217. res.push(mid);
  218. }
  219. } else if (direction === 'vertical') {
  220. data = this.verticaSetData(studentList, questAnswerList, modelList);
  221. res = data.map(i => Object.values(i));
  222. } else {
  223. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到excel的表头排列方式');
  224. }
  225. return res;
  226. }
  227. /**
  228. * 获得导出文件的文件名
  229. * @param {String} questName 问卷名
  230. * @param {Object} range 范围(计划-期-批-班)
  231. * @return {String} fn 文件名
  232. */
  233. async toSetFileName(questName, range) {
  234. let fn = `-${questName}`;
  235. const { planid, termid, batchid, classid } = range;
  236. if (classid) {
  237. const cla = await this.ctx.service.class.fetch({ id: classid });
  238. if (cla) {
  239. const { name, term } = cla;
  240. if (name) fn = `${name.includes('班') ? name : `${name}班`}${fn}`;
  241. if (term) fn = `第${term}期${fn}`;
  242. }
  243. } else if (batchid) {
  244. const tid = _.head(termid);
  245. const obj = await this.toGetFn(tid, batchid);
  246. if (obj) {
  247. const { term, batch } = obj;
  248. if (batch) fn = `第${batch}批${fn}`;
  249. if (term) fn = `第${term}期${fn}`;
  250. }
  251. } else if (termid) {
  252. if (termid.length === 1) {
  253. const obj = await this.toGetFn(_.head(termid));
  254. if (obj) {
  255. const { term } = obj;
  256. if (term) fn = `第${term}期${fn}`;
  257. }
  258. } else {
  259. let tStr = '';
  260. for (let i = 0; i < termid.length; i++) {
  261. const tid = termid[i];
  262. const obj = await this.toGetFn(tid);
  263. if (obj) {
  264. const { term } = obj;
  265. if (term) {
  266. if (i === 0) {
  267. tStr += `${term}期`;
  268. } else {
  269. tStr += `,${term}期`;
  270. }
  271. }
  272. }
  273. }
  274. fn = `${tStr}${fn}`;
  275. }
  276. } else {
  277. const trainPlan = await this.ctx.model.Trainplan.findById(planid);
  278. if (trainPlan) {
  279. const { title } = trainPlan;
  280. if (title) fn = `${title}${fn}`;
  281. }
  282. }
  283. return fn;
  284. }
  285. /**
  286. * 获取文件的期/期批
  287. * @param {String} termid 期id
  288. * @param {String} batchid 批id
  289. */
  290. async toGetFn(termid, batchid) {
  291. const trainPlan = await this.ctx.model.Trainplan.findOne({
  292. 'termnum._id': ObjectId(termid),
  293. });
  294. if (!trainPlan) {
  295. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到年度计划信息');
  296. }
  297. const { termnum } = trainPlan;
  298. if (!termnum) {
  299. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到年度计划的期信息');
  300. }
  301. const obj = {};
  302. if (termid) {
  303. const term = termnum.id(termid);
  304. if (term) obj.term = term.term;
  305. if (batchid) {
  306. const { batchnum } = term;
  307. const batch = batchnum.id(batchid);
  308. if (batch) obj.batch = batch.batch;
  309. }
  310. }
  311. return obj;
  312. }
  313. /**
  314. * 取出对应方向的表头
  315. * @param {String} type 横纵向类型
  316. * @param {Array} modelList 导出字段
  317. * @param {Number} studentList count的学生数量
  318. */
  319. getHead(type, modelList, studentList) {
  320. let head = [];
  321. if (type === 'horizontal') {
  322. // 横向头
  323. head = modelList.map(i => {
  324. const { zh, model, _id } = i;
  325. const headObj = { header: zh };
  326. if (model) headObj.key = model;
  327. else if (_id) headObj.key = _id;
  328. headObj.width = 20;
  329. return headObj;
  330. });
  331. } else {
  332. // 纵向头
  333. const head = [{ key: 'c', width: 20 }];
  334. for (let i = 1; i <= studentList.length; i++) {
  335. head.push({ key: `c${i}`, width: 20 });
  336. }
  337. }
  338. return head;
  339. }
  340. /**
  341. * 横向组织数据
  342. * @param {Array} studentList 学生列表
  343. * @param {Array} questAnswerList 学生回答问卷列表
  344. * @param {Array} modelList 需要导出的字段
  345. */
  346. horizontalSetData(studentList, questAnswerList, modelList) {
  347. // 组织数据需要按照modelList的顺序进行整理
  348. const data = [];
  349. for (const stu of studentList) {
  350. const obj = {};
  351. for (const m of modelList) {
  352. const { model, table, _id } = m;
  353. if (table === 'student') {
  354. const prop = _.get(stu, model, '');
  355. obj[model] = prop;
  356. } else if (table === 'questionnaire') {
  357. const qar = questAnswerList.find(f => f.studentid === stu._id);
  358. // 没找到该学生的问卷,下一个
  359. if (!qar) continue;
  360. const { answers } = qar;
  361. // 回答的数据不存在/不是数组,数据格式不对,下一个
  362. if (!(answers && _.isArray(answers))) continue;
  363. const ar = answers.find(f => f.questionid === _id);
  364. // 没找到答案,下个
  365. if (!ar) continue;
  366. const { answer } = ar;
  367. // 没有答案,下个
  368. if (!answer) continue;
  369. obj[_id] = _.trim(answer, '"');
  370. }
  371. }
  372. data.push(obj);
  373. }
  374. // const obj = {};
  375. // if (head) obj.head = head;
  376. // if (data) obj.data = data;
  377. return data;
  378. }
  379. /**
  380. * 纵向组织数据
  381. * @param {Array} studentList 学生列表
  382. * @param {Array} questAnswerList 学生回答问卷列表
  383. * @param {Array} modelList 需要导出的字段
  384. */
  385. verticaSetData(studentList, questAnswerList, modelList) {
  386. // 整理数据
  387. const data = [];
  388. for (const m of modelList) {
  389. const { table, model, _id, zh } = m;
  390. const obj = { c: zh };
  391. if (table === 'student') {
  392. for (let i = 0; i < studentList.length; i++) {
  393. const stu = studentList[i];
  394. const value = _.get(stu, model, '');
  395. if (value) obj[`c${i + 1}`] = value;
  396. }
  397. } else if (table === 'questionnaire') {
  398. for (let i = 0; i < studentList.length; i++) {
  399. const stu = studentList[i];
  400. const qar = questAnswerList.find(f => f.studentid === stu._id);
  401. // 没找到该学生的问卷,下一个
  402. if (!qar) continue;
  403. const { answers } = qar;
  404. // 回答的数据不存在/不是数组,数据格式不对,下一个
  405. if (!(answers && _.isArray(answers))) continue;
  406. const ar = answers.find(f => f.questionid === _id);
  407. // 没找到答案,下个
  408. if (!ar) continue;
  409. const { answer } = ar;
  410. // 没有答案,下个
  411. if (!answer) continue;
  412. obj[`c${i + 1}`] = _.trim(answer, '"');
  413. }
  414. }
  415. data.push(obj);
  416. }
  417. return data;
  418. }
  419. }
  420. module.exports = QuestionnaireService;