123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276 |
- 'use strict';
- const assert = require('assert');
- const _ = require('lodash');
- const { ObjectId } = require('mongoose').Types;
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- class QuestionnaireService extends CrudService {
- constructor(ctx) {
- super(ctx, 'qusetionnaire');
- this.questionnairemodel = this.ctx.model.Questionnaire;
- this.questionmodel = this.ctx.model.Question;
- }
- // 插入问卷
- async create(data) {
- const { name, num, type, question } = data;
- assert(name, '问卷名称不能为空');
- assert(num, '问卷序号不能为空');
- assert(type, '问卷类型不能为空');
- const quedata = [];
- for (const elm of question) {
- const ques = await this.questionmodel.findById(elm);
- if (ques) {
- quedata.push(ques);
- }
- }
- data.question = quedata;
- return await this.questionnairemodel.create(data);
- }
- // 根据id删除问卷
- async delete({ id }) {
- await this.questionnairemodel.findByIdAndDelete(id);
- return 'deleted';
- }
- // 根据id更新问卷信息
- async update({ id }, data) {
- const { name, num, type, question } = data;
- const questionnaire = await this.questionnairemodel.findById(id);
- if (name) {
- questionnaire.name = name;
- }
- if (num) {
- questionnaire.num = num;
- }
- if (type) {
- questionnaire.type = type;
- }
- if (question) {
- questionnaire.question = question;
- }
- return await questionnaire.save();
- }
- // 查询
- async query({ skip, limit, ...num }) {
- const total = await this.questionnairemodel.count(num);
- const data = await this.questionnairemodel
- .find(num)
- .skip(Number(skip))
- .limit(Number(limit));
- const result = { total, data };
- return result;
- }
- // 查询详情
- async show({ id }) {
- const questionnaire = await this.questionnairemodel.findById(id);
- return questionnaire;
- }
- /**
- * 导出问卷
- * @param {Object} Object 数据集合
- * @property Object range 学生的查询范围
- * @property String direction horizontal横向/vertical纵向
- * @property String questionnaireid 问卷id
- * @property Array modelList 要导出的字段,学生和问卷都在这里, 学生的table:student, 问卷的table:questionnaire
- */
- async export({ range, direction, questionnaireid, modelList }) {
- // 获取问卷
- let questionnaire = await this.questionnairemodel.findById(questionnaireid);
- if (!questionnaire) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到问卷信息'); }
- questionnaire = JSON.parse(JSON.stringify(questionnaire));
- // 获取学生
- let { data: studentList } = await this.ctx.service.student.query(range);
- if (studentList.length <= 0) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到任何学生信息'); }
- studentList = JSON.parse(JSON.stringify(studentList));
- // 再获取问卷
- let questAnswerList = await this.ctx.model.Uploadquestion.find({
- ...range,
- questionnaireid,
- });
- if (!questAnswerList) { throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到任何完成的问卷'); }
- questAnswerList = JSON.parse(JSON.stringify(questAnswerList));
- // fn,根据范围+问卷 得出文件名
- const fn = await this.toSetFileName(questionnaire.name, range);
- // 将期批班转换
- modelList = modelList.map(i => {
- const { model } = i;
- if (model === 'termid') i.model = 'termname';
- else if (model === 'batchid') i.model = 'batchname';
- else if (model === 'classid') i.model = 'classname';
- return i;
- });
- let excelData;
- if (direction === 'horizontal') {
- excelData = this.horizontalSetData(studentList, questAnswerList, modelList);
- } else if (direction === 'vertical') {
- excelData = this.verticaSetData(studentList, questAnswerList, modelList);
- } else {
- throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到excel的表头排列方式');
- }
- if (excelData) {
- const { head, data } = excelData;
- return await this.ctx.service.util.toExcel(data, head, fn);
- }
- }
- /**
- * 获得导出文件的文件名
- * @param {String} questName 问卷名
- * @param {Object} range 范围(计划-期-批-班)
- * @return {String} fn 文件名
- */
- async toSetFileName(questName, range) {
- let fn = `-${questName}`;
- const { planid, termid, batchid, classid } = range;
- const getData = (termid, batchid, termnum) => {
- let res = '';
- if (termid) {
- const termInfo = termnum.id(termid);
- if (!termInfo) return res;
- const { term, batchnum } = termInfo;
- if (term) res = `第${term}期${res}`;
- if (batchid && batchnum) {
- const batchInfo = batchnum.id(batchid);
- if (!batchInfo) return res;
- const { batch } = batchInfo;
- res = `${res}第${batch}批`;
- }
- }
- return res;
- };
- if (classid) {
- const cla = await this.ctx.service.class.fetch({ id: classid });
- if (cla) {
- const { name, term } = cla;
- if (name) fn = `${name.includes('班') ? name : `${name}班`}${fn}`;
- if (term) fn = `第${term}期${fn}`;
- }
- } else {
- const condition = {};
- if (planid) condition._id = ObjectId(planid);
- if (termid) condition['termnum._id'] = ObjectId(termid);
- if (batchid) condition['termnum.batchnum._id'] = ObjectId(batchid);
- const trainPlan = await this.ctx.model.Trainplan.findOne(condition);
- const { termnum, title } = trainPlan;
- if (!termnum) return;
- if (termid || batchid) {
- const r = getData(termid, batchid, termnum);
- fn = `${r}${fn}`;
- } else {
- fn = `${title}${fn}`;
- }
- }
- return fn;
- }
- /**
- * 横向组织数据
- * TODO 里面整理方法可以提取出来和纵向一起用
- * @param {Array} studentList 学生列表
- * @param {Array} questAnswerList 学生回答问卷列表
- * @param {Array} modelList 需要导出的字段
- */
- horizontalSetData(studentList, questAnswerList, modelList) {
- // 第一步,组织excel表头
- const head = modelList.map(i => {
- const { zh, model, _id } = i;
- const headObj = { header: zh };
- if (model) headObj.key = model;
- else if (_id) headObj.key = _id;
- headObj.width = 20;
- return headObj;
- });
- // 第二步,组织数据需要按照modelList的顺序进行整理
- const data = [];
- for (const stu of studentList) {
- const obj = {};
- for (const m of modelList) {
- const { model, table, _id } = m;
- if (table === 'student') {
- const prop = _.get(stu, model, '');
- obj[model] = prop;
- } else if (table === 'questionnaire') {
- const qar = questAnswerList.find(f => f.studentid === stu._id);
- // 没找到该学生的问卷,下一个
- if (!qar) continue;
- const { answers } = qar;
- // 回答的数据不存在/不是数组,数据格式不对,下一个
- if (!(answers && _.isArray(answers))) continue;
- const ar = answers.find(f => f.questionid === _id);
- // 没找到答案,下个
- if (!ar) continue;
- const { answer } = ar;
- // 没有答案,下个
- if (!answer) continue;
- obj[_id] = _.trim(answer, '"');
- }
- }
- data.push(obj);
- }
- const obj = {};
- if (head)obj.head = head;
- if (data) obj.data = data;
- return obj;
- }
- /**
- * 纵向组织数据
- * TODO 里面整理方法可以提取出来和横向一起用
- * @param {Array} studentList 学生列表
- * @param {Array} questAnswerList 学生回答问卷列表
- * @param {Array} modelList 需要导出的字段
- */
- verticaSetData(studentList, questAnswerList, modelList) {
- // 第一步,组织excel表头,纵向不需要第一行表头,开始就是数据,表头是第一列
- const head = [{ key: 'c', width: 20 }];
- for (let i = 1; i <= studentList.length; i++) {
- head.push({ key: `c${i}`, width: 20 });
- }
- // 第二部,整理数据
- const data = [];
- for (const m of modelList) {
- const { table, model, _id, zh } = m;
- const obj = { c: zh };
- if (table === 'student') {
- for (let i = 0; i < studentList.length; i++) {
- const stu = studentList[i];
- const value = _.get(stu, model, '');
- if (value) obj[`c${i + 1}`] = value;
- }
- } else if (table === 'questionnaire') {
- for (let i = 0; i < studentList.length; i++) {
- const stu = studentList[i];
- const qar = questAnswerList.find(f => f.studentid === stu._id);
- // 没找到该学生的问卷,下一个
- if (!qar) continue;
- const { answers } = qar;
- // 回答的数据不存在/不是数组,数据格式不对,下一个
- if (!(answers && _.isArray(answers))) continue;
- const ar = answers.find(f => f.questionid === _id);
- // 没找到答案,下个
- if (!ar) continue;
- const { answer } = ar;
- // 没有答案,下个
- if (!answer) continue;
- obj[`c${i + 1}`] = _.trim(answer, '"');
- }
- }
- data.push(obj);
- }
- const obj = {};
- if (head) obj.head = head;
- if (data) obj.data = data;
- return obj;
- }
- }
- module.exports = QuestionnaireService;
|