util.js 15 KB

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