util.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. console.log(meta);
  121. // 导出excel
  122. const { app } = this;
  123. const nowDate = new Date().getTime();
  124. const filename = `${fn}-${nowDate}.xlsx`;
  125. // 取出预设存储地址
  126. const rootPath = `${app.config.cdn.repos_root_path}`;
  127. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  128. let path = `${rootPath}${rooturl}`;
  129. if (!path) {
  130. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  131. }
  132. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  133. if (!fs.existsSync(path)) {
  134. // 如果不存在文件夹,就创建
  135. fs.mkdirSync(path);
  136. }
  137. // 生成文件
  138. const filepath = `${path}${filename}`;
  139. fs.createWriteStream(filepath);
  140. const workbook = new Excel.Workbook();
  141. const sheet = workbook.addWorksheet('sheet');
  142. sheet.columns = meta;
  143. sheet.addRows(dataList);
  144. await workbook.xlsx.writeFile(filepath);
  145. return `/files/excel/${filename}`;
  146. }
  147. /**
  148. * 导出docx
  149. * @param {Array} data 数据[{title,content([]),author}]
  150. * @param {String} fn 文件名
  151. */
  152. async toDocx(data, fn = '培训心得') {
  153. const {
  154. Document,
  155. Packer,
  156. Paragraph,
  157. TextRun,
  158. HeadingLevel,
  159. AlignmentType,
  160. } = docx;
  161. const doc = new Document();
  162. const children = [];
  163. // 整理数据
  164. for (let i = 0; i < data.length; i++) {
  165. const obj = data[i];
  166. const { title, content, author } = obj;
  167. const c = [];
  168. if (title) {
  169. const tit = new Paragraph({
  170. children: [ new TextRun({ text: title, bold: true }) ],
  171. heading: HeadingLevel.TITLE,
  172. alignment: AlignmentType.CENTER,
  173. });
  174. c.push(tit);
  175. }
  176. if (author) {
  177. const auth = new Paragraph({
  178. children: [ new TextRun({ color: '#000000', text: author }) ],
  179. heading: HeadingLevel.HEADING_2,
  180. alignment: AlignmentType.RIGHT,
  181. });
  182. c.push(auth);
  183. }
  184. if (content && _.isArray(content) && content.length > 0) {
  185. for (const cont of content) {
  186. const p = new Paragraph({
  187. children: [ new TextRun({ text: cont, bold: true }) ],
  188. });
  189. c.push(p);
  190. }
  191. }
  192. if (i !== data.length - 1) {
  193. // 换页
  194. const last = new Paragraph({
  195. pageBreakBefore: true,
  196. });
  197. c.push(last);
  198. }
  199. if (c.length > 0) children.push(...c);
  200. }
  201. doc.addSection({
  202. properties: {},
  203. children,
  204. });
  205. const { app } = this;
  206. const rootPath = `${app.config.cdn.repos_root_path}`;
  207. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  208. const path = `${rootPath}${rooturl}`;
  209. // 如果不存在文件夹,就创建
  210. if (!fs.existsSync(path)) {
  211. fs.mkdirSync(path);
  212. }
  213. const num = new Date().getTime();
  214. const buffer = await Packer.toBuffer(doc);
  215. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  216. // Packer.toBuffer(doc).then(buffer => {
  217. // fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  218. // });
  219. return `/files${rooturl}${fn}-${num}.docx`;
  220. }
  221. /**
  222. * 将选择的文件导出到zip压缩包中,提供下载
  223. * @param {*} fileList 需要导入到zip中的列表,格式有2中: [{url:""}]或[String]
  224. * @param {*} fn 文件名,默认为 "导出结果"
  225. */
  226. async toZip(fileList, fn = '导出结果') {
  227. if (!_.isArray(fileList)) {
  228. throw new BusinessError(ErrorCode.DATA_INVALID, '需要压缩的文件数据格式错误');
  229. }
  230. fn = `${fn}.zip`;
  231. // zip文件夹创建
  232. const { app } = this;
  233. const rootPath = `${app.config.cdn.repos_root_path}`;
  234. const zipPath = `${app.config.cdn.repos_root_url_zip}`;
  235. const path = `${rootPath}${zipPath}`;
  236. if (!fs.existsSync(path)) {
  237. fs.mkdirSync(path);
  238. }
  239. // 文件请求后将数据整理到这里
  240. const resetFileList = [];
  241. for (const file of fileList) {
  242. let uri = '';
  243. let filename = '';
  244. if (_.isString(file)) {
  245. uri = file;
  246. const arr = file.split('/');
  247. const last = _.last(arr);
  248. if (last) filename = last;
  249. } else if (_.isObject(file)) {
  250. const { uri: furi, url: furl, name } = file;
  251. if (furi) uri = furi;
  252. else if (furl) uri = furl;
  253. if (name) filename = name;
  254. else {
  255. const arr = uri.split('/');
  256. const last = _.last(arr);
  257. if (last) filename = last;
  258. }
  259. }
  260. if (uri && filename) resetFileList.push({ uri, filename });
  261. }
  262. // 导出
  263. const output = fs.createWriteStream(`${path}${fn}`);
  264. const archive = archiver('zip', {
  265. zlib: { level: 9 },
  266. });
  267. archive.pipe(output);
  268. // 请求文件,追加进压缩包
  269. for (const file of resetFileList) {
  270. const { uri, filename } = file;
  271. const res = await this.ctx.curl(`http://127.0.0.1${uri}`);
  272. if (res && res.data) {
  273. archive.append(res.data, { name: filename });
  274. }
  275. }
  276. archive.finalize();
  277. return `/files${zipPath}${fn}`;
  278. }
  279. }
  280. module.exports = UtilService;