util.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. 'use strict';
  2. const _ = require('lodash');
  3. const fs = require('fs');
  4. const Excel = require('exceljs');
  5. const { CrudService } = require('naf-framework-mongoose/lib/service');
  6. const { BusinessError, ErrorCode } = require('naf-core').Error;
  7. const moment = require('moment');
  8. const nodemailer = require('nodemailer');
  9. const docx = require('docx');
  10. const archiver = require('archiver');
  11. const { ObjectId } = require('mongoose').Types;
  12. class UtilService extends CrudService {
  13. constructor(ctx) {
  14. super(ctx);
  15. this.mq = this.ctx.mq;
  16. }
  17. async updatedate() {
  18. let date = new Date();
  19. date = moment(date).format('YYYY-MM-DD HH:mm:ss');
  20. return date;
  21. }
  22. async sendMail(email, subject, text, html) {
  23. const setting = await this.ctx.model.Setting.findOne();
  24. let user_email = this.ctx.app.config.user_email;
  25. let auth_code = this.ctx.app.config.auth_code;
  26. if (setting) {
  27. user_email = setting.user_email;
  28. auth_code = setting.auth_code;
  29. }
  30. const transporter = nodemailer.createTransport({
  31. host: 'smtp.exmail.qq.com',
  32. secureConnection: true,
  33. port: 465,
  34. auth: {
  35. user: user_email, // 账号
  36. pass: auth_code, // 授权码
  37. },
  38. });
  39. if (process.env.NODE_ENV === 'development') email = '402788946@qq.com';
  40. const mailOptions = {
  41. from: user_email, // 发送者,与上面的user一致
  42. to: email, // 接收者,可以同时发送多个,以逗号隔开
  43. subject, // 标题
  44. text, // 文本
  45. html,
  46. };
  47. try {
  48. await transporter.sendMail(mailOptions);
  49. return true;
  50. } catch (err) {
  51. return false;
  52. }
  53. }
  54. async findone({ modelname }, data) {
  55. // 查询单条
  56. const _model = _.capitalize(modelname);
  57. const res = await this.ctx.model[_model].findOne({ ...data });
  58. return res;
  59. }
  60. async findbyids({ modelname }, { data }) {
  61. // 共通批量查询方法
  62. const _model = _.capitalize(modelname);
  63. const res = [];
  64. for (const elm of data) {
  65. const result = await this.ctx.model[_model].findById(elm);
  66. res.push(result);
  67. }
  68. return res;
  69. }
  70. async findmodel({ modelname }) {
  71. const _model = _.capitalize(modelname);
  72. const data = this.ctx.model[_model].prototype.schema.obj;
  73. const keys = Object.keys(data);
  74. const res = {};
  75. for (const k of keys) {
  76. const obj = data[k];
  77. if (_.get(obj, 'zh')) res[k] = obj;
  78. }
  79. return res;
  80. }
  81. async utilMethod(query, body) {
  82. const arr = this.app.router.stack;
  83. const list = [];
  84. for (const i of arr) {
  85. const { name, methods, path } = i;
  86. list.push([ name, methods, path ]);
  87. }
  88. await this.toExcel(list);
  89. // for (const trainPlan of allTranPlan) {
  90. // const { termnum = [] } = trainPlan;
  91. // const termids = termnum.map(f => ObjectId(f._id).toString());
  92. // // 查出该期所有的申请
  93. // const termApplys = await applyModel.find({ termid: termids }).lean();
  94. // const needDeletes = termApplys.filter(f => !(allSubject.find(s => s._id === f.subid) && allTeacher.find(t => t._id === f.teacherid)));
  95. // const deleteIds = needDeletes.map(i => i._id);
  96. // console.log(deleteIds.length);
  97. // // await applyModel.deleteMany({ _id: deleteIds });
  98. // }
  99. // // // 重置班级
  100. // // 找到要删除的学生
  101. // const res = await this.ctx.model.Student.find({ school_name: '吉林职业技术学院', planid: '60769b703cead37068645fb2', termid: { $ne: '60779c0b2ec7ac704ce301ab' } });
  102. // // const test = res.map(f => {
  103. // // return { name: f.name, openid: f.openid, id: f._id };
  104. // // });
  105. // const ids = res.map(i => i._id);
  106. // await this.ctx.model.User.deleteMany({ uid: ids });
  107. // await this.ctx.model.Student.deleteMany({ school_name: '吉林职业技术学院', planid: '60769b703cead37068645fb2', termid: { $ne: '60779c0b2ec7ac704ce301ab' } });
  108. // const ids = res.map(i => i.openid);
  109. // // console.log(ids);
  110. //
  111. // console.log(userRes.length);
  112. // const { planid, termid, batchid, classid } = query;
  113. // const filters = {};
  114. // if (classid) filters.classid = classid;
  115. // else if (batchid)filters.batchid = batchid;
  116. // else if (termid)filters.termid = termid;
  117. // else if (planid)filters.planid = planid;
  118. // else throw new BusinessError(ErrorCode.BADPARAM, '需要重置范围');
  119. // await this.ctx.model.Student.updateMany(filters, { classid: undefined });
  120. // // 重置班级结束
  121. }
  122. async getQueryOptions({ skip, limit, sort, desc } = {}) {
  123. if (sort && _.isString(sort)) {
  124. sort = { [sort]: desc ? -1 : 1 };
  125. } else if (sort && _.isArray(sort)) {
  126. sort = sort.map(f => ({ [f]: desc ? -1 : 1 })).reduce((p, c) => ({ ...p, ...c }), {});
  127. }
  128. return { skip, limit, sort };
  129. }
  130. /**
  131. * 更新进度,状态 不存在/完成以外(不是2的值)的数值, 不添加参数,只更新进度
  132. * @param {String} missionid 任务id
  133. * @param {String} progress 进度(人为划分)
  134. * @param {String} status 状态
  135. * @param {Object} params 参数
  136. */
  137. async updateProcess(missionid, progress, status, params) {
  138. try {
  139. if (!missionid) return;
  140. const { baseUrl } = _.get(this.ctx.app.config, 'mission');
  141. let url = `${baseUrl}`;
  142. let data;
  143. if (!baseUrl) return;
  144. if (!status || status !== '2') {
  145. url = `${url}/api/mission/progress`;
  146. data = { id: missionid, progress };
  147. } else if (status === '3') {
  148. url = `${url}/api/mission/update/${missionid}`;
  149. data = { status };
  150. } else {
  151. url = `${url}/api/mission/update/${missionid}`;
  152. data = { progress: '100', params, status };
  153. }
  154. await this.ctx.curl(url, {
  155. method: 'post',
  156. headers: {
  157. 'content-type': 'application/json',
  158. },
  159. data,
  160. dataType: 'json',
  161. });
  162. } catch (error) {
  163. console.error(`任务更新进度报错,missionid:${missionid}\n`);
  164. }
  165. }
  166. async teacherImport() {
  167. // const filepath = './teacherlist.xlsx';
  168. // const workbook = new Excel.Workbook();
  169. // await workbook.xlsx.readFile(filepath);
  170. // const worksheet = workbook.getWorksheet(1);
  171. // if (!worksheet) return;
  172. // let arr = [];
  173. // worksheet.eachRow((row, ri) => {
  174. // if (ri !== 1) {
  175. // const obj = {};
  176. // obj.name = row.getCell(3).value || undefined;
  177. // obj.department = row.getCell(4).value || undefined;
  178. // if (row.getCell(5).value) obj.job = row.getCell(5).value;
  179. // obj.phone = row.getCell(6).value || undefined;
  180. // obj.status = '4';
  181. // arr.push(obj);
  182. // }
  183. // });
  184. // // 检查谁生成过了, user表和teacher表
  185. // let ur = await this.ctx.model.User.find({ mobile: { $in: arr.map(i => i.phone) }, type: '3' });
  186. // let tr = await this.ctx.model.Teacher.find({ phone: { $in: arr.map(i => i.phone) } });
  187. // // 将有的老师过滤出去
  188. // if (ur) {
  189. // ur = JSON.parse(JSON.stringify(ur));
  190. // arr = arr.filter(f => !ur.find(uf => `${uf.mobile}` === `${f.phone}`));
  191. // }
  192. // if (tr) {
  193. // tr = JSON.parse(JSON.stringify(tr));
  194. // arr = arr.filter(f => !(tr.find(tf => `${tf.phone}` === `${f.phone}`)));
  195. // }
  196. // for (const tea of arr) {
  197. // const ctr = await this.ctx.model.Teacher.create(tea);
  198. // if (ctr) {
  199. // const obj = { name: tea.name, mobile: tea.phone, type: '3', uid: ctr._id };
  200. // const cur = await this.ctx.model.User.create(obj);
  201. // }
  202. // }
  203. // const user = await this.ctx.model.User.find({ passwd: { $exists: false } });
  204. // for (const u of user) {
  205. // u.passwd = { secret: '12345678' };
  206. // u.save();
  207. // }
  208. }
  209. /**
  210. * 导出excel
  211. * @param {Array} dataList 数据集合
  212. * @param {Array} meta 表头(可以没有)
  213. * @param {String} fn 文件名
  214. * @param {Array} opera 单元格操作
  215. */
  216. async toExcel(dataList, meta, fn = '导出结果', opera) {
  217. // 导出excel
  218. const { app } = this;
  219. const nowDate = new Date().getTime();
  220. const filename = `${fn}-${nowDate}.xlsx`;
  221. // 取出预设存储地址
  222. const rootPath = `${app.config.cdn.repos_root_path}`;
  223. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  224. const path = `${rootPath}${rooturl}`;
  225. if (!path) {
  226. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  227. }
  228. // if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  229. if (!fs.existsSync(path)) {
  230. // 如果不存在文件夹,就创建
  231. fs.mkdirSync(path);
  232. }
  233. // 生成文件
  234. const filepath = `${path}${filename}`;
  235. fs.createWriteStream(filepath);
  236. const workbook = new Excel.Workbook();
  237. const sheet = workbook.addWorksheet('sheet');
  238. if (meta) sheet.columns = meta;
  239. sheet.addRows(dataList);
  240. if (_.isArray(opera)) {
  241. for (const o of opera) {
  242. const { startRow, startCol, endRow, endCol } = o;
  243. sheet.mergeCells(startRow, startCol, endRow, endCol);
  244. }
  245. }
  246. // 垂直居中
  247. const length = dataList.length;
  248. const alignment = { vertical: 'middle', horizontal: 'center' };
  249. for (let i = 1; i <= length; i++) {
  250. sheet.getRow(i).alignment = alignment;
  251. }
  252. await workbook.xlsx.writeFile(filepath);
  253. return `/files/excel/${filename}`;
  254. }
  255. /**
  256. * 创建/重复写入excel
  257. * @param {Array} dataList 数据
  258. * @param {String} fn 文件名, 第一次进入时,只是单纯的名,第二次开始,有后缀与时间戳
  259. * @param {String} downloadPath 下载文件路径
  260. * @param {String} type 方向,没有默认横向
  261. */
  262. async toAsyncExcel(dataList, fn = '导出结果', downloadPath, type) {
  263. const { app } = this;
  264. const workbook = new Excel.Workbook();
  265. let sheet;
  266. // 取出预设存储地址
  267. const rootPath = `${app.config.cdn.repos_root_path}`;
  268. const rooturl = `${app.config.cdn.repos_root_url_excel}`;
  269. let path = `${rootPath}${rooturl}`;
  270. let filepath = '';
  271. if (!path) {
  272. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  273. }
  274. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\excel\\';
  275. if (!fs.existsSync(path)) {
  276. // 如果不存在文件夹,就创建
  277. fs.mkdirSync(path);
  278. }
  279. if (!downloadPath) {
  280. // 第一次进入,文件还未生成
  281. const nowDate = new Date().getTime();
  282. fn = `${fn}-${nowDate}.xlsx`;
  283. sheet = workbook.addWorksheet('sheet');
  284. } else {
  285. let domain = 'http://127.0.0.1';
  286. if (process.env.NODE_ENV === 'development') domain = `${domain}:8000`;
  287. const file = await this.ctx.curl(`${domain}${downloadPath}`);
  288. if (!(file && file.data)) {
  289. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找导出的excel');
  290. }
  291. // 读取文件
  292. await workbook.xlsx.load(file.data);
  293. sheet = workbook.getWorksheet('sheet');
  294. }
  295. if (!type || type === 'horizontal') sheet.addRows(dataList);
  296. else if (type === 'vertical') {
  297. for (let i = 1; i <= dataList.length; i++) {
  298. const element = dataList[i - 1];
  299. const rows = sheet.getRow(i);
  300. if (rows.values.length <= 0) rows.values = element;
  301. else rows.values = rows.values.concat(element);
  302. rows.commit();
  303. }
  304. }
  305. filepath = `${path}${fn}`;
  306. await workbook.xlsx.writeFile(filepath);
  307. return { downloadPath: `/files/excel/${fn}`, fn };
  308. }
  309. /**
  310. * 导出docx
  311. * @param {Array} data 数据[{title,content([]),author}]
  312. * @param {String} fn 文件名
  313. */
  314. async toDocx(data, fn = '培训心得') {
  315. const { Document, Packer, Paragraph, TextRun, HeadingLevel, AlignmentType } = docx;
  316. const doc = new Document();
  317. const children = [];
  318. // 整理数据
  319. for (let i = 0; i < data.length; i++) {
  320. const obj = data[i];
  321. const { title, content, author } = obj;
  322. const c = [];
  323. if (title) {
  324. const tit = new Paragraph({
  325. children: [ new TextRun({ text: title, bold: true }) ],
  326. heading: HeadingLevel.TITLE,
  327. alignment: AlignmentType.CENTER,
  328. });
  329. c.push(tit);
  330. }
  331. if (author) {
  332. const auth = new Paragraph({
  333. children: [ new TextRun({ color: '#000000', text: author }) ],
  334. heading: HeadingLevel.HEADING_2,
  335. alignment: AlignmentType.RIGHT,
  336. });
  337. c.push(auth);
  338. }
  339. if (content && _.isArray(content) && content.length > 0) {
  340. for (const cont of content) {
  341. const p = new Paragraph({
  342. children: [ new TextRun({ text: cont, bold: true }) ],
  343. });
  344. c.push(p);
  345. }
  346. }
  347. if (i !== data.length - 1) {
  348. // 换页
  349. const last = new Paragraph({
  350. pageBreakBefore: true,
  351. });
  352. c.push(last);
  353. }
  354. if (c.length > 0) children.push(...c);
  355. }
  356. doc.addSection({
  357. properties: {},
  358. children,
  359. });
  360. const { app } = this;
  361. const rootPath = `${app.config.cdn.repos_root_path}`;
  362. const rooturl = `${app.config.cdn.repos_root_url_experience}`;
  363. const path = `${rootPath}${rooturl}`;
  364. // 如果不存在文件夹,就创建
  365. // if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  366. if (!fs.existsSync(path)) {
  367. fs.mkdirSync(path);
  368. }
  369. const num = new Date().getTime();
  370. const buffer = await Packer.toBuffer(doc);
  371. fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  372. // Packer.toBuffer(doc).then(buffer => {
  373. // fs.writeFileSync(`${path}${fn}-${num}.docx`, buffer);
  374. // });
  375. return `/files${rooturl}${fn}-${num}.docx`;
  376. }
  377. /**
  378. * 将选择的文件导出到zip压缩包中,提供下载
  379. * @param {*} fileList 需要导入到zip中的列表,格式有2中: [{url:""}]或[String]
  380. * @param {*} fn 文件名,默认为 "导出结果"
  381. */
  382. async toZip(fileList, fn = '导出结果') {
  383. if (!_.isArray(fileList)) {
  384. throw new BusinessError(ErrorCode.DATA_INVALID, '需要压缩的文件数据格式错误');
  385. }
  386. fn = `${fn}.zip`;
  387. // zip文件夹创建
  388. const { app } = this;
  389. const rootPath = `${app.config.cdn.repos_root_path}`;
  390. const zipPath = `${app.config.cdn.repos_root_url_zip}`;
  391. let path = `${rootPath}${zipPath}`;
  392. if (process.env.NODE_ENV === 'development') path = 'E:\\exportFile\\';
  393. if (!fs.existsSync(path)) {
  394. fs.mkdirSync(path);
  395. }
  396. // 文件请求后将数据整理到这里
  397. const resetFileList = [];
  398. for (const file of fileList) {
  399. let uri = '';
  400. let filename = '';
  401. let prefixs;
  402. if (_.isString(file)) {
  403. uri = file;
  404. const arr = file.split('/');
  405. const last = _.last(arr);
  406. if (last) filename = last;
  407. } else if (_.isObject(file)) {
  408. const { uri: furi, url: furl, name, prefix } = file;
  409. if (furi) uri = furi;
  410. else if (furl) uri = furl;
  411. if (name) filename = name;
  412. else {
  413. const arr = uri.split('/');
  414. const last = _.last(arr);
  415. if (last) filename = last;
  416. }
  417. if (prefix) prefixs = prefix;
  418. }
  419. const obj = {};
  420. if (uri) obj.uri = uri;
  421. if (filename) obj.filename = filename;
  422. if (prefixs) obj.prefix = prefixs;
  423. resetFileList.push(obj);
  424. }
  425. // 导出
  426. const output = fs.createWriteStream(`${path}${fn}`);
  427. const archive = archiver('zip', {
  428. zlib: { level: 9 },
  429. });
  430. archive.pipe(output);
  431. // 请求文件,追加进压缩包
  432. for (const file of resetFileList) {
  433. const { uri, filename, prefix } = file;
  434. const res = await this.ctx.curl(`http://127.0.0.1${uri}`);
  435. if (res && res.data) {
  436. const options = {};
  437. if (filename) options.name = filename;
  438. if (prefix) options.prefix = prefix;
  439. if (filename) {
  440. archive.append(res.data, options);
  441. }
  442. }
  443. }
  444. await archive.finalize();
  445. return `/files${zipPath}${fn}`;
  446. }
  447. }
  448. module.exports = UtilService;