util.js 11 KB

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