util.js 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. 'use strict';
  2. const assert = require('assert');
  3. const _ = require('lodash');
  4. const fs = require('fs');
  5. const Excel = require('exceljs');
  6. const { ObjectId } = require('mongoose').Types;
  7. const { CrudService } = require('naf-framework-mongoose/lib/service');
  8. const { BusinessError, ErrorCode } = require('naf-core').Error;
  9. const moment = require('moment');
  10. const nodemailer = require('nodemailer');
  11. const { template } = require('lodash');
  12. const docx = require('docx');
  13. class UtilService extends CrudService {
  14. async updatedate() {
  15. let date = new Date();
  16. date = moment(date).format('YYYY-MM-DD HH:mm:ss');
  17. return date;
  18. }
  19. async sendMail(email, subject, text, html) {
  20. const setting = await this.ctx.model.Setting.findOne();
  21. let user_email = this.ctx.app.config.user_email;
  22. let auth_code = this.ctx.app.config.auth_code;
  23. if (setting) {
  24. user_email = setting.user_email;
  25. auth_code = setting.auth_code;
  26. }
  27. const transporter = nodemailer.createTransport({
  28. host: 'smtp.exmail.qq.com',
  29. secureConnection: true,
  30. port: 465,
  31. auth: {
  32. user: user_email, // 账号
  33. pass: auth_code, // 授权码
  34. },
  35. });
  36. const mailOptions = {
  37. from: user_email, // 发送者,与上面的user一致
  38. to: email, // 接收者,可以同时发送多个,以逗号隔开
  39. subject, // 标题
  40. text, // 文本
  41. html,
  42. };
  43. try {
  44. await transporter.sendMail(mailOptions);
  45. return true;
  46. } catch (err) {
  47. return false;
  48. }
  49. }
  50. async findone({ modelname }, data) {
  51. // 查询单条
  52. const _model = _.capitalize(modelname);
  53. const res = await this.ctx.model[_model].findOne({ ...data });
  54. return res;
  55. }
  56. async findbyids({ modelname }, { data }) {
  57. // 共通批量查询方法
  58. const _model = _.capitalize(modelname);
  59. const res = [];
  60. for (const elm of data) {
  61. const result = await this.ctx.model[_model].findById(elm);
  62. res.push(result);
  63. }
  64. return res;
  65. }
  66. async findmodel({ modelname }) {
  67. const _model = _.capitalize(modelname);
  68. const data = this.ctx.model[_model].prototype.schema.obj;
  69. return data;
  70. }
  71. async utilMethod(data, body) {
  72. console.log(data, body);
  73. }
  74. async toExcel(dataList, meta, fn = '导出结果') {
  75. // 导出excel
  76. const { app } = this;
  77. const nowDate = new Date().getTime();
  78. const filename = `${fn}-${nowDate}.xlsx`;
  79. // 取出预设存储地址
  80. const rootPath = `${app.config.cdn.repos_root_path}`;
  81. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  82. const path = `${rootPath}${rooturl}`;
  83. if (!path) {
  84. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  85. }
  86. // 如果不存在文件夹,就创建
  87. if (!fs.existsSync(path)) {
  88. fs.mkdirSync(path);
  89. }
  90. // 生成文件
  91. const filepath = `${path}${filename}`;
  92. fs.createWriteStream(filepath);
  93. const workbook = new Excel.Workbook();
  94. const sheet = workbook.addWorksheet('sheet');
  95. sheet.columns = meta;
  96. sheet.addRows(dataList);
  97. await workbook.xlsx.writeFile(filepath);
  98. return `/files/excel/${filename}`;
  99. }
  100. /**
  101. * 导出docx
  102. * @param {Array} data 数据[{title,content([]),author}]
  103. * @param {String} fn 文件名
  104. */
  105. async toDocx(data, fn = '培训心得') {
  106. const {
  107. Document,
  108. Packer,
  109. Paragraph,
  110. TextRun,
  111. HeadingLevel,
  112. AlignmentType,
  113. } = docx;
  114. const doc = new Document();
  115. const children = [];
  116. // 整理数据
  117. for (let i = 0; i < data.length; i++) {
  118. const obj = data[i];
  119. const { title, content, author } = obj;
  120. const c = [];
  121. if (title) {
  122. const tit = new Paragraph({
  123. children: [ new TextRun({ text: title, bold: true }) ],
  124. heading: HeadingLevel.TITLE,
  125. alignment: AlignmentType.CENTER,
  126. });
  127. c.push(tit);
  128. }
  129. if (author) {
  130. const auth = new Paragraph({
  131. children: [ new TextRun({ color: '#000000', text: author }) ],
  132. heading: HeadingLevel.HEADING_2,
  133. alignment: AlignmentType.RIGHT,
  134. });
  135. c.push(auth);
  136. }
  137. if (content && _.isArray(content) && content.length > 0) {
  138. for (const cont of content) {
  139. const p = new Paragraph({
  140. children: [ new TextRun({ text: cont, bold: true }) ],
  141. });
  142. c.push(p);
  143. }
  144. }
  145. if (i !== data.length - 1) {
  146. // 换页
  147. const last = new Paragraph({
  148. pageBreakBefore: true,
  149. });
  150. c.push(last);
  151. }
  152. if (c.length > 0) children.push(...c);
  153. }
  154. doc.addSection({
  155. properties: {},
  156. children,
  157. });
  158. const { app } = this;
  159. const rootPath = `${app.config.cdn.repos_root_path}`;
  160. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  161. const path = `${rootPath}${rooturl}`;
  162. // 如果不存在文件夹,就创建
  163. if (!fs.existsSync(path)) {
  164. fs.mkdirSync(path);
  165. }
  166. const num = new Date().getTime();
  167. Packer.toBuffer(doc).then(buffer => {
  168. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  169. });
  170. return `/files${rooturl}${fn}-${num}.docx`;
  171. }
  172. }
  173. module.exports = UtilService;