util.js 15 KB

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