util.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. const archiver = require('archiver');
  14. class UtilService extends CrudService {
  15. async updatedate() {
  16. let date = new Date();
  17. date = moment(date).format('YYYY-MM-DD HH:mm:ss');
  18. return date;
  19. }
  20. async sendMail(email, subject, text, html) {
  21. const setting = await this.ctx.model.Setting.findOne();
  22. let user_email = this.ctx.app.config.user_email;
  23. let auth_code = this.ctx.app.config.auth_code;
  24. if (setting) {
  25. user_email = setting.user_email;
  26. auth_code = setting.auth_code;
  27. }
  28. const transporter = nodemailer.createTransport({
  29. host: 'smtp.exmail.qq.com',
  30. secureConnection: true,
  31. port: 465,
  32. auth: {
  33. user: user_email, // 账号
  34. pass: auth_code, // 授权码
  35. },
  36. });
  37. const mailOptions = {
  38. from: user_email, // 发送者,与上面的user一致
  39. to: email, // 接收者,可以同时发送多个,以逗号隔开
  40. subject, // 标题
  41. text, // 文本
  42. html,
  43. };
  44. try {
  45. await transporter.sendMail(mailOptions);
  46. return true;
  47. } catch (err) {
  48. return false;
  49. }
  50. }
  51. async findone({ modelname }, data) {
  52. // 查询单条
  53. const _model = _.capitalize(modelname);
  54. const res = await this.ctx.model[_model].findOne({ ...data });
  55. return res;
  56. }
  57. async findbyids({ modelname }, { data }) {
  58. // 共通批量查询方法
  59. const _model = _.capitalize(modelname);
  60. const res = [];
  61. for (const elm of data) {
  62. const result = await this.ctx.model[_model].findById(elm);
  63. res.push(result);
  64. }
  65. return res;
  66. }
  67. async findmodel({ modelname }) {
  68. const _model = _.capitalize(modelname);
  69. const data = this.ctx.model[_model].prototype.schema.obj;
  70. return data;
  71. }
  72. async utilMethod(data, body) {
  73. console.log();
  74. }
  75. async teacherImport() {
  76. // const filepath = './teacherlist.xlsx';
  77. // const workbook = new Excel.Workbook();
  78. // await workbook.xlsx.readFile(filepath);
  79. // const worksheet = workbook.getWorksheet(1);
  80. // if (!worksheet) return;
  81. // let arr = [];
  82. // worksheet.eachRow((row, ri) => {
  83. // if (ri !== 1) {
  84. // const obj = {};
  85. // obj.name = row.getCell(3).value || undefined;
  86. // obj.department = row.getCell(4).value || undefined;
  87. // if (row.getCell(5).value) obj.job = row.getCell(5).value;
  88. // obj.phone = row.getCell(6).value || undefined;
  89. // obj.status = '4';
  90. // arr.push(obj);
  91. // }
  92. // });
  93. // // 检查谁生成过了, user表和teacher表
  94. // let ur = await this.ctx.model.User.find({ mobile: { $in: arr.map(i => i.phone) }, type: '3' });
  95. // let tr = await this.ctx.model.Teacher.find({ phone: { $in: arr.map(i => i.phone) } });
  96. // // 将有的老师过滤出去
  97. // if (ur) {
  98. // ur = JSON.parse(JSON.stringify(ur));
  99. // arr = arr.filter(f => !ur.find(uf => `${uf.mobile}` === `${f.phone}`));
  100. // }
  101. // if (tr) {
  102. // tr = JSON.parse(JSON.stringify(tr));
  103. // arr = arr.filter(f => !(tr.find(tf => `${tf.phone}` === `${f.phone}`)));
  104. // }
  105. // for (const tea of arr) {
  106. // const ctr = await this.ctx.model.Teacher.create(tea);
  107. // if (ctr) {
  108. // const obj = { name: tea.name, mobile: tea.phone, type: '3', uid: ctr._id };
  109. // const cur = await this.ctx.model.User.create(obj);
  110. // }
  111. // }
  112. // const user = await this.ctx.model.User.find({ passwd: { $exists: false } });
  113. // console.log(user.length);
  114. // for (const u of user) {
  115. // u.passwd = { secret: '12345678' };
  116. // u.save();
  117. // }
  118. }
  119. async toExcel(dataList, meta, fn = '导出结果') {
  120. // 导出excel
  121. const { app } = this;
  122. const nowDate = new Date().getTime();
  123. const filename = `${fn}-${nowDate}.xlsx`;
  124. // 取出预设存储地址
  125. const rootPath = `${app.config.cdn.repos_root_path}`;
  126. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  127. let path = `${rootPath}${rooturl}`;
  128. if (!path) {
  129. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  130. }
  131. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  132. if (!fs.existsSync(path)) {
  133. // 如果不存在文件夹,就创建
  134. fs.mkdirSync(path);
  135. }
  136. // 生成文件
  137. const filepath = `${path}${filename}`;
  138. fs.createWriteStream(filepath);
  139. const workbook = new Excel.Workbook();
  140. const sheet = workbook.addWorksheet('sheet');
  141. sheet.columns = meta;
  142. sheet.addRows(dataList);
  143. await workbook.xlsx.writeFile(filepath);
  144. return `/files/excel/${filename}`;
  145. }
  146. /**
  147. * 导出docx
  148. * @param {Array} data 数据[{title,content([]),author}]
  149. * @param {String} fn 文件名
  150. */
  151. async toDocx(data, fn = '培训心得') {
  152. const {
  153. Document,
  154. Packer,
  155. Paragraph,
  156. TextRun,
  157. HeadingLevel,
  158. AlignmentType,
  159. } = docx;
  160. const doc = new Document();
  161. const children = [];
  162. // 整理数据
  163. for (let i = 0; i < data.length; i++) {
  164. const obj = data[i];
  165. const { title, content, author } = obj;
  166. const c = [];
  167. if (title) {
  168. const tit = new Paragraph({
  169. children: [ new TextRun({ text: title, bold: true }) ],
  170. heading: HeadingLevel.TITLE,
  171. alignment: AlignmentType.CENTER,
  172. });
  173. c.push(tit);
  174. }
  175. if (author) {
  176. const auth = new Paragraph({
  177. children: [ new TextRun({ color: '#000000', text: author }) ],
  178. heading: HeadingLevel.HEADING_2,
  179. alignment: AlignmentType.RIGHT,
  180. });
  181. c.push(auth);
  182. }
  183. if (content && _.isArray(content) && content.length > 0) {
  184. for (const cont of content) {
  185. const p = new Paragraph({
  186. children: [ new TextRun({ text: cont, bold: true }) ],
  187. });
  188. c.push(p);
  189. }
  190. }
  191. if (i !== data.length - 1) {
  192. // 换页
  193. const last = new Paragraph({
  194. pageBreakBefore: true,
  195. });
  196. c.push(last);
  197. }
  198. if (c.length > 0) children.push(...c);
  199. }
  200. doc.addSection({
  201. properties: {},
  202. children,
  203. });
  204. const { app } = this;
  205. const rootPath = `${app.config.cdn.repos_root_path}`;
  206. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  207. const path = `${rootPath}${rooturl}`;
  208. // 如果不存在文件夹,就创建
  209. if (!fs.existsSync(path)) {
  210. fs.mkdirSync(path);
  211. }
  212. const num = new Date().getTime();
  213. const buffer = await Packer.toBuffer(doc);
  214. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  215. // Packer.toBuffer(doc).then(buffer => {
  216. // fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  217. // });
  218. return `/files${rooturl}${fn}-${num}.docx`;
  219. }
  220. /**
  221. * 将选择的文件导出到zip压缩包中,提供下载
  222. * @param {*} fileList 需要导入到zip中的列表,格式有2中: [{url:""}]或[String]
  223. * @param {*} fn 文件名,默认为 "导出结果"
  224. */
  225. async toZip(fileList, fn = '导出结果') {
  226. if (!_.isArray(fileList)) {
  227. throw new BusinessError(ErrorCode.DATA_INVALID, '需要压缩的文件数据格式错误');
  228. }
  229. fn = `${fn}.zip`;
  230. // zip文件夹创建
  231. const { app } = this;
  232. const rootPath = `${app.config.cdn.repos_root_path}`;
  233. const zipPath = `${app.config.cdn.repos_root_url_zip}`;
  234. const path = `${rootPath}${zipPath}`;
  235. if (!fs.existsSync(path)) {
  236. fs.mkdirSync(path);
  237. }
  238. // 文件请求后将数据整理到这里
  239. const resetFileList = [];
  240. for (const file of fileList) {
  241. let uri = '';
  242. let filename = '';
  243. if (_.isString(file)) {
  244. uri = file;
  245. const arr = file.split('/');
  246. const last = _.last(arr);
  247. if (last) filename = last;
  248. } else if (_.isObject(file)) {
  249. const { uri: furi, url: furl, name } = file;
  250. if (furi) uri = furi;
  251. else if (furl) uri = furl;
  252. if (name) filename = name;
  253. else {
  254. const arr = uri.split('/');
  255. const last = _.last(arr);
  256. if (last) filename = last;
  257. }
  258. }
  259. if (uri && filename) resetFileList.push({ uri, filename });
  260. }
  261. // 导出
  262. const output = fs.createWriteStream(`${path}${fn}`);
  263. const archive = archiver('zip', {
  264. zlib: { level: 9 },
  265. });
  266. archive.pipe(output);
  267. // 请求文件,追加进压缩包
  268. for (const file of resetFileList) {
  269. const { uri, filename } = file;
  270. const res = await this.ctx.curl(`http://127.0.0.1${uri}`);
  271. if (res && res.data) {
  272. archive.append(res.data, { name: filename });
  273. }
  274. }
  275. archive.finalize();
  276. return `/files${zipPath}${fn}`;
  277. }
  278. }
  279. module.exports = UtilService;