util.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. // const output = fs.createWriteStream('E:\\exportFile\\test.zip');
  74. // const archive = archiver('zip', {
  75. // zlib: { level: 9 },
  76. // });
  77. // archive.pipe(output);
  78. // const res = await this.ctx.curl('http://jytz.jilinjobs.cn/files/task/20200914174650.jpg');
  79. // if (res && res.data) {
  80. // archive.append(res.data, { name: 'test.jpg', prefix: 'test/test2/test3' });
  81. // }
  82. // archive.finalize();
  83. }
  84. async teacherImport() {
  85. // const filepath = './teacherlist.xlsx';
  86. // const workbook = new Excel.Workbook();
  87. // await workbook.xlsx.readFile(filepath);
  88. // const worksheet = workbook.getWorksheet(1);
  89. // if (!worksheet) return;
  90. // let arr = [];
  91. // worksheet.eachRow((row, ri) => {
  92. // if (ri !== 1) {
  93. // const obj = {};
  94. // obj.name = row.getCell(3).value || undefined;
  95. // obj.department = row.getCell(4).value || undefined;
  96. // if (row.getCell(5).value) obj.job = row.getCell(5).value;
  97. // obj.phone = row.getCell(6).value || undefined;
  98. // obj.status = '4';
  99. // arr.push(obj);
  100. // }
  101. // });
  102. // // 检查谁生成过了, user表和teacher表
  103. // let ur = await this.ctx.model.User.find({ mobile: { $in: arr.map(i => i.phone) }, type: '3' });
  104. // let tr = await this.ctx.model.Teacher.find({ phone: { $in: arr.map(i => i.phone) } });
  105. // // 将有的老师过滤出去
  106. // if (ur) {
  107. // ur = JSON.parse(JSON.stringify(ur));
  108. // arr = arr.filter(f => !ur.find(uf => `${uf.mobile}` === `${f.phone}`));
  109. // }
  110. // if (tr) {
  111. // tr = JSON.parse(JSON.stringify(tr));
  112. // arr = arr.filter(f => !(tr.find(tf => `${tf.phone}` === `${f.phone}`)));
  113. // }
  114. // for (const tea of arr) {
  115. // const ctr = await this.ctx.model.Teacher.create(tea);
  116. // if (ctr) {
  117. // const obj = { name: tea.name, mobile: tea.phone, type: '3', uid: ctr._id };
  118. // const cur = await this.ctx.model.User.create(obj);
  119. // }
  120. // }
  121. // const user = await this.ctx.model.User.find({ passwd: { $exists: false } });
  122. // console.log(user.length);
  123. // for (const u of user) {
  124. // u.passwd = { secret: '12345678' };
  125. // u.save();
  126. // }
  127. }
  128. async toExcel(dataList, meta, fn = '导出结果') {
  129. console.log(meta);
  130. // 导出excel
  131. const { app } = this;
  132. const nowDate = new Date().getTime();
  133. const filename = `${fn}-${nowDate}.xlsx`;
  134. // 取出预设存储地址
  135. const rootPath = `${app.config.cdn.repos_root_path}`;
  136. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  137. let path = `${rootPath}${rooturl}`;
  138. if (!path) {
  139. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  140. }
  141. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  142. if (!fs.existsSync(path)) {
  143. // 如果不存在文件夹,就创建
  144. fs.mkdirSync(path);
  145. }
  146. // 生成文件
  147. const filepath = `${path}${filename}`;
  148. fs.createWriteStream(filepath);
  149. const workbook = new Excel.Workbook();
  150. const sheet = workbook.addWorksheet('sheet');
  151. sheet.columns = meta;
  152. sheet.addRows(dataList);
  153. await workbook.xlsx.writeFile(filepath);
  154. return `/files/excel/${filename}`;
  155. }
  156. /**
  157. * 导出docx
  158. * @param {Array} data 数据[{title,content([]),author}]
  159. * @param {String} fn 文件名
  160. */
  161. async toDocx(data, fn = '培训心得') {
  162. const {
  163. Document,
  164. Packer,
  165. Paragraph,
  166. TextRun,
  167. HeadingLevel,
  168. AlignmentType,
  169. } = docx;
  170. const doc = new Document();
  171. const children = [];
  172. // 整理数据
  173. for (let i = 0; i < data.length; i++) {
  174. const obj = data[i];
  175. const { title, content, author } = obj;
  176. const c = [];
  177. if (title) {
  178. const tit = new Paragraph({
  179. children: [ new TextRun({ text: title, bold: true }) ],
  180. heading: HeadingLevel.TITLE,
  181. alignment: AlignmentType.CENTER,
  182. });
  183. c.push(tit);
  184. }
  185. if (author) {
  186. const auth = new Paragraph({
  187. children: [ new TextRun({ color: '#000000', text: author }) ],
  188. heading: HeadingLevel.HEADING_2,
  189. alignment: AlignmentType.RIGHT,
  190. });
  191. c.push(auth);
  192. }
  193. if (content && _.isArray(content) && content.length > 0) {
  194. for (const cont of content) {
  195. const p = new Paragraph({
  196. children: [ new TextRun({ text: cont, bold: true }) ],
  197. });
  198. c.push(p);
  199. }
  200. }
  201. if (i !== data.length - 1) {
  202. // 换页
  203. const last = new Paragraph({
  204. pageBreakBefore: true,
  205. });
  206. c.push(last);
  207. }
  208. if (c.length > 0) children.push(...c);
  209. }
  210. doc.addSection({
  211. properties: {},
  212. children,
  213. });
  214. const { app } = this;
  215. const rootPath = `${app.config.cdn.repos_root_path}`;
  216. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  217. let path = `${rootPath}${rooturl}`;
  218. // 如果不存在文件夹,就创建
  219. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  220. if (!fs.existsSync(path)) {
  221. fs.mkdirSync(path);
  222. }
  223. const num = new Date().getTime();
  224. const buffer = await Packer.toBuffer(doc);
  225. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  226. // Packer.toBuffer(doc).then(buffer => {
  227. // fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  228. // });
  229. return `/files${rooturl}${fn}-${num}.docx`;
  230. }
  231. /**
  232. * 将选择的文件导出到zip压缩包中,提供下载
  233. * @param {*} fileList 需要导入到zip中的列表,格式有2中: [{url:""}]或[String]
  234. * @param {*} fn 文件名,默认为 "导出结果"
  235. */
  236. async toZip(fileList, fn = '导出结果') {
  237. if (!_.isArray(fileList)) {
  238. throw new BusinessError(ErrorCode.DATA_INVALID, '需要压缩的文件数据格式错误');
  239. }
  240. fn = `${fn}.zip`;
  241. // zip文件夹创建
  242. const { app } = this;
  243. const rootPath = `${app.config.cdn.repos_root_path}`;
  244. const zipPath = `${app.config.cdn.repos_root_url_zip}`;
  245. let path = `${rootPath}${zipPath}`;
  246. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  247. if (!fs.existsSync(path)) {
  248. fs.mkdirSync(path);
  249. }
  250. // 文件请求后将数据整理到这里
  251. const resetFileList = [];
  252. for (const file of fileList) {
  253. let uri = '';
  254. let filename = '';
  255. let prefixs;
  256. if (_.isString(file)) {
  257. uri = file;
  258. const arr = file.split('/');
  259. const last = _.last(arr);
  260. if (last) filename = last;
  261. } else if (_.isObject(file)) {
  262. const { uri: furi, url: furl, name, prefix } = file;
  263. if (furi) uri = furi;
  264. else if (furl) uri = furl;
  265. if (name) filename = name;
  266. else {
  267. const arr = uri.split('/');
  268. const last = _.last(arr);
  269. if (last) filename = last;
  270. }
  271. if (prefix) prefixs = prefix;
  272. }
  273. const obj = {};
  274. if (uri) obj.uri = uri;
  275. if (filename)obj.filename = filename;
  276. if (prefixs) obj.prefix = prefixs;
  277. resetFileList.push(obj);
  278. }
  279. // 导出
  280. const output = fs.createWriteStream(`${path}${fn}`);
  281. const archive = archiver('zip', {
  282. zlib: { level: 9 },
  283. });
  284. archive.pipe(output);
  285. // 请求文件,追加进压缩包
  286. for (const file of resetFileList) {
  287. const { uri, filename, prefix } = file;
  288. const res = await this.ctx.curl(`http://127.0.0.1${uri}`);
  289. if (res && res.data) {
  290. const options = {};
  291. if (filename)options.name = filename;
  292. if (prefix) options.prefix = prefix;
  293. if (filename) { archive.append(res.data, options); }
  294. }
  295. }
  296. await archive.finalize();
  297. return `/files${zipPath}${fn}`;
  298. }
  299. }
  300. module.exports = UtilService;