util.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. const keys = Object.keys(data);
  75. const res = {};
  76. for (const k of keys) {
  77. const obj = data[k];
  78. if (_.get(obj, 'zh')) res[k] = obj;
  79. }
  80. return res;
  81. }
  82. async utilMethod(query, body) {
  83. const { planid, termid, batchid, classid } = query;
  84. const filters = {};
  85. if (classid) filters.classid = classid;
  86. else if (batchid)filters.batchid = batchid;
  87. else if (termid)filters.termid = termid;
  88. else if (planid)filters.planid = planid;
  89. await this.ctx.model.Student.updateMany(filters, { classid: undefined });
  90. // const ch = await this.ctx.amqp.conn.createChannel();
  91. // const queue = 'hello';
  92. // ch.consume(
  93. // queue,
  94. // msg => {
  95. // console.log(' [x] Received %s', msg.content.toString());
  96. // },
  97. // { noAck: true }
  98. // );
  99. // // ch.close();
  100. }
  101. async getQueryOptions({ skip, limit, sort, desc } = {}) {
  102. if (sort && _.isString(sort)) {
  103. sort = { [sort]: desc ? -1 : 1 };
  104. } else if (sort && _.isArray(sort)) {
  105. sort = sort
  106. .map(f => ({ [f]: desc ? -1 : 1 }))
  107. .reduce((p, c) => ({ ...p, ...c }), {});
  108. }
  109. return { skip, limit, sort };
  110. }
  111. /**
  112. * 更新进度,状态 不存在/完成以外(不是2的值)的数值, 不添加参数,只更新进度
  113. * @param {String} missionid 任务id
  114. * @param {String} progress 进度(人为划分)
  115. * @param {String} status 状态
  116. * @param {Object} params 参数
  117. */
  118. async updateProcess(missionid, progress, status, params) {
  119. try {
  120. if (!missionid) return;
  121. const { baseUrl } = _.get(this.ctx.app.config, 'mission');
  122. let url = `${baseUrl}`;
  123. let data;
  124. if (!baseUrl) return;
  125. if (!status || status !== '2') {
  126. url = `${url}/api/mission/progress`;
  127. data = { id: missionid, progress };
  128. } else if (status === '3') {
  129. url = `${url}/api/mission/update/${missionid}`;
  130. data = { status };
  131. } else {
  132. url = `${url}/api/mission/update/${missionid}`;
  133. data = { progress: '100', params, status };
  134. }
  135. await this.ctx.curl(url, {
  136. method: 'post',
  137. headers: {
  138. 'content-type': 'application/json',
  139. },
  140. data,
  141. dataType: 'json',
  142. });
  143. } catch (error) {
  144. console.error(`任务更新进度报错,missionid:${missionid}\n`);
  145. }
  146. }
  147. async teacherImport() {
  148. // const filepath = './teacherlist.xlsx';
  149. // const workbook = new Excel.Workbook();
  150. // await workbook.xlsx.readFile(filepath);
  151. // const worksheet = workbook.getWorksheet(1);
  152. // if (!worksheet) return;
  153. // let arr = [];
  154. // worksheet.eachRow((row, ri) => {
  155. // if (ri !== 1) {
  156. // const obj = {};
  157. // obj.name = row.getCell(3).value || undefined;
  158. // obj.department = row.getCell(4).value || undefined;
  159. // if (row.getCell(5).value) obj.job = row.getCell(5).value;
  160. // obj.phone = row.getCell(6).value || undefined;
  161. // obj.status = '4';
  162. // arr.push(obj);
  163. // }
  164. // });
  165. // // 检查谁生成过了, user表和teacher表
  166. // let ur = await this.ctx.model.User.find({ mobile: { $in: arr.map(i => i.phone) }, type: '3' });
  167. // let tr = await this.ctx.model.Teacher.find({ phone: { $in: arr.map(i => i.phone) } });
  168. // // 将有的老师过滤出去
  169. // if (ur) {
  170. // ur = JSON.parse(JSON.stringify(ur));
  171. // arr = arr.filter(f => !ur.find(uf => `${uf.mobile}` === `${f.phone}`));
  172. // }
  173. // if (tr) {
  174. // tr = JSON.parse(JSON.stringify(tr));
  175. // arr = arr.filter(f => !(tr.find(tf => `${tf.phone}` === `${f.phone}`)));
  176. // }
  177. // for (const tea of arr) {
  178. // const ctr = await this.ctx.model.Teacher.create(tea);
  179. // if (ctr) {
  180. // const obj = { name: tea.name, mobile: tea.phone, type: '3', uid: ctr._id };
  181. // const cur = await this.ctx.model.User.create(obj);
  182. // }
  183. // }
  184. // const user = await this.ctx.model.User.find({ passwd: { $exists: false } });
  185. // for (const u of user) {
  186. // u.passwd = { secret: '12345678' };
  187. // u.save();
  188. // }
  189. }
  190. /**
  191. * 导出excel
  192. * @param {Array} dataList 数据集合
  193. * @param {Array} meta 表头(可以没有)
  194. * @param {String} fn 文件名
  195. * @param {Array} opera 单元格操作
  196. */
  197. async toExcel(dataList, meta, fn = '导出结果', opera) {
  198. // 导出excel
  199. const { app } = this;
  200. const nowDate = new Date().getTime();
  201. const filename = `${fn}-${nowDate}.xlsx`;
  202. // 取出预设存储地址
  203. const rootPath = `${app.config.cdn.repos_root_path}`;
  204. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  205. let path = `${rootPath}${rooturl}`;
  206. if (!path) {
  207. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  208. }
  209. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  210. if (!fs.existsSync(path)) {
  211. // 如果不存在文件夹,就创建
  212. fs.mkdirSync(path);
  213. }
  214. // 生成文件
  215. const filepath = `${path}${filename}`;
  216. fs.createWriteStream(filepath);
  217. const workbook = new Excel.Workbook();
  218. const sheet = workbook.addWorksheet('sheet');
  219. if (meta)sheet.columns = meta;
  220. sheet.addRows(dataList);
  221. if (_.isArray(opera)) {
  222. for (const o of opera) {
  223. const { startRow, startCol, endRow, endCol } = o;
  224. sheet.mergeCells(startRow, startCol, endRow, endCol);
  225. }
  226. }
  227. // 垂直居中
  228. const length = dataList.length;
  229. const alignment = { vertical: 'middle', horizontal: 'center' };
  230. for (let i = 1; i <= length; i++) {
  231. sheet.getRow(i).alignment = alignment;
  232. }
  233. await workbook.xlsx.writeFile(filepath);
  234. return `/files/excel/${filename}`;
  235. }
  236. /**
  237. * 创建/重复写入excel
  238. * @param {Array} dataList 数据
  239. * @param {String} fn 文件名, 第一次进入时,只是单纯的名,第二次开始,有后缀与时间戳
  240. * @param {String} downloadPath 下载文件路径
  241. * @param {String} type 方向,没有默认横向
  242. */
  243. async toAsyncExcel(dataList, fn = '导出结果', downloadPath, type) {
  244. const { app } = this;
  245. const workbook = new Excel.Workbook();
  246. let sheet;
  247. // 取出预设存储地址
  248. const rootPath = `${app.config.cdn.repos_root_path}`;
  249. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  250. let path = `${rootPath}${rooturl}`;
  251. let filepath = '';
  252. if (!path) {
  253. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  254. }
  255. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\excel\\';
  256. if (!fs.existsSync(path)) {
  257. // 如果不存在文件夹,就创建
  258. fs.mkdirSync(path);
  259. }
  260. if (!downloadPath) {
  261. // 第一次进入,文件还未生成
  262. const nowDate = new Date().getTime();
  263. fn = `${fn}-${nowDate}.xlsx`;
  264. sheet = workbook.addWorksheet('sheet');
  265. } else {
  266. let domain = 'http://127.0.0.1';
  267. if (process.env.NODE_ENV === 'development')domain = `${domain}:8000`;
  268. const file = await this.ctx.curl(`${domain}${downloadPath}`);
  269. if (!(file && file.data)) {
  270. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找导出的excel');
  271. }
  272. // 读取文件
  273. await workbook.xlsx.load(file.data);
  274. sheet = workbook.getWorksheet('sheet');
  275. }
  276. if (!type || type === 'horizontal') sheet.addRows(dataList);
  277. else if (type === 'vertical') {
  278. for (let i = 1; i <= dataList.length; i++) {
  279. const element = dataList[i - 1];
  280. const rows = sheet.getRow(i);
  281. if (rows.values.length <= 0) rows.values = element;
  282. else rows.values = rows.values.concat(element);
  283. rows.commit();
  284. }
  285. }
  286. filepath = `${path}${fn}`;
  287. await workbook.xlsx.writeFile(filepath);
  288. return { downloadPath: `/files/excel/${fn}`, fn };
  289. }
  290. /**
  291. * 导出docx
  292. * @param {Array} data 数据[{title,content([]),author}]
  293. * @param {String} fn 文件名
  294. */
  295. async toDocx(data, fn = '培训心得') {
  296. const {
  297. Document,
  298. Packer,
  299. Paragraph,
  300. TextRun,
  301. HeadingLevel,
  302. AlignmentType,
  303. } = docx;
  304. const doc = new Document();
  305. const children = [];
  306. // 整理数据
  307. for (let i = 0; i < data.length; i++) {
  308. const obj = data[i];
  309. const { title, content, author } = obj;
  310. const c = [];
  311. if (title) {
  312. const tit = new Paragraph({
  313. children: [ new TextRun({ text: title, bold: true }) ],
  314. heading: HeadingLevel.TITLE,
  315. alignment: AlignmentType.CENTER,
  316. });
  317. c.push(tit);
  318. }
  319. if (author) {
  320. const auth = new Paragraph({
  321. children: [ new TextRun({ color: '#000000', text: author }) ],
  322. heading: HeadingLevel.HEADING_2,
  323. alignment: AlignmentType.RIGHT,
  324. });
  325. c.push(auth);
  326. }
  327. if (content && _.isArray(content) && content.length > 0) {
  328. for (const cont of content) {
  329. const p = new Paragraph({
  330. children: [ new TextRun({ text: cont, bold: true }) ],
  331. });
  332. c.push(p);
  333. }
  334. }
  335. if (i !== data.length - 1) {
  336. // 换页
  337. const last = new Paragraph({
  338. pageBreakBefore: true,
  339. });
  340. c.push(last);
  341. }
  342. if (c.length > 0) children.push(...c);
  343. }
  344. doc.addSection({
  345. properties: {},
  346. children,
  347. });
  348. const { app } = this;
  349. const rootPath = `${app.config.cdn.repos_root_path}`;
  350. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  351. let path = `${rootPath}${rooturl}`;
  352. // 如果不存在文件夹,就创建
  353. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  354. if (!fs.existsSync(path)) {
  355. fs.mkdirSync(path);
  356. }
  357. const num = new Date().getTime();
  358. const buffer = await Packer.toBuffer(doc);
  359. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  360. // Packer.toBuffer(doc).then(buffer => {
  361. // fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  362. // });
  363. return `/files${rooturl}${fn}-${num}.docx`;
  364. }
  365. /**
  366. * 将选择的文件导出到zip压缩包中,提供下载
  367. * @param {*} fileList 需要导入到zip中的列表,格式有2中: [{url:""}]或[String]
  368. * @param {*} fn 文件名,默认为 "导出结果"
  369. */
  370. async toZip(fileList, fn = '导出结果') {
  371. if (!_.isArray(fileList)) {
  372. throw new BusinessError(
  373. ErrorCode.DATA_INVALID,
  374. '需要压缩的文件数据格式错误'
  375. );
  376. }
  377. fn = `${fn}.zip`;
  378. // zip文件夹创建
  379. const { app } = this;
  380. const rootPath = `${app.config.cdn.repos_root_path}`;
  381. const zipPath = `${app.config.cdn.repos_root_url_zip}`;
  382. let path = `${rootPath}${zipPath}`;
  383. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  384. if (!fs.existsSync(path)) {
  385. fs.mkdirSync(path);
  386. }
  387. // 文件请求后将数据整理到这里
  388. const resetFileList = [];
  389. for (const file of fileList) {
  390. let uri = '';
  391. let filename = '';
  392. let prefixs;
  393. if (_.isString(file)) {
  394. uri = file;
  395. const arr = file.split('/');
  396. const last = _.last(arr);
  397. if (last) filename = last;
  398. } else if (_.isObject(file)) {
  399. const { uri: furi, url: furl, name, prefix } = file;
  400. if (furi) uri = furi;
  401. else if (furl) uri = furl;
  402. if (name) filename = name;
  403. else {
  404. const arr = uri.split('/');
  405. const last = _.last(arr);
  406. if (last) filename = last;
  407. }
  408. if (prefix) prefixs = prefix;
  409. }
  410. const obj = {};
  411. if (uri) obj.uri = uri;
  412. if (filename) obj.filename = filename;
  413. if (prefixs) obj.prefix = prefixs;
  414. resetFileList.push(obj);
  415. }
  416. // 导出
  417. const output = fs.createWriteStream(`${path}${fn}`);
  418. const archive = archiver('zip', {
  419. zlib: { level: 9 },
  420. });
  421. archive.pipe(output);
  422. // 请求文件,追加进压缩包
  423. for (const file of resetFileList) {
  424. const { uri, filename, prefix } = file;
  425. const res = await this.ctx.curl(`http://127.0.0.1${uri}`);
  426. if (res && res.data) {
  427. const options = {};
  428. if (filename) options.name = filename;
  429. if (prefix) options.prefix = prefix;
  430. if (filename) {
  431. archive.append(res.data, options);
  432. }
  433. }
  434. }
  435. await archive.finalize();
  436. return `/files${zipPath}${fn}`;
  437. }
  438. }
  439. module.exports = UtilService;