util.js 16 KB

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