util.js 9.3 KB

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