util.js 11 KB

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