template_controller.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. /**
  3. * 指标模板控制器
  4. *
  5. * @author Mai
  6. * @data 2018/4/19
  7. * @version
  8. */
  9. // excel解析
  10. const excel = require('node-xlsx');
  11. const sendToWormhole = require('stream-wormhole');
  12. module.exports = app => {
  13. class TemplateController extends app.BaseController {
  14. /**
  15. * 指标模板页面
  16. *
  17. * @param {object} ctx - egg全局context
  18. * @return {void}
  19. */
  20. async index (ctx) {
  21. const id = ctx.queries.id ? ctx.queries.id[0] : 1;
  22. const node = await ctx.service.templateNode.getAllDataByCondition({template_id: 1});
  23. for (const n of node) {
  24. n.url = '/template?id=' + n.node_id;
  25. n.target = '_self';
  26. }
  27. const treeNode = ctx.helper.convertData(node, true, 'node_id', 'node_pid');
  28. const condition = {template_id: 1, node_id: id};
  29. const selectNode = await ctx.service.templateNode.getDataByCondition(condition);
  30. const selectIndex = await ctx.service.templateIndex.getAllDataByCondition({ where: condition });
  31. const renderData = {
  32. nodes: JSON.stringify(treeNode),
  33. selectNode: selectNode,
  34. selectIndex: selectIndex,
  35. }
  36. await this.layout('template/index.ejs', renderData, 'template/modal.ejs');
  37. }
  38. async uploadExcel(ctx) {
  39. let stream;
  40. try {
  41. stream = await ctx.getFileStream();
  42. const fileName = this.app.baseDir + '/app/public/template/uploads/' + stream.filename;
  43. // 保存文件
  44. await ctx.helper.saveStreamFile(stream, fileName);
  45. // 读取文件
  46. const sheet = excel.parse(fileName);
  47. if (!sheet || sheet.length === 0 || sheet[0] === undefined || sheet[0].data === undefined) {
  48. throw 'excel没有对应数据';
  49. }
  50. const result = await ctx.service.templateNode.importData(sheet);
  51. if (!result) {
  52. throw '导入数据失败';
  53. }
  54. ctx.redirect('/template');
  55. } catch (err) {
  56. console.log(err);
  57. // 失败需要消耗掉stream 以防卡死
  58. if (stream) {
  59. await sendToWormhole(stream);
  60. }
  61. //this.setMessage(err.toString(), this.messageType.ERROR);
  62. ctx.redirect('/template');
  63. }
  64. }
  65. }
  66. return TemplateController;
  67. }