patent.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. 'use strict';
  2. const assert = require('assert');
  3. const moment = require('moment');
  4. const Excel = require('exceljs');
  5. const Path = require('path');
  6. const _ = require('lodash');
  7. const { sep } = require('path');
  8. const fs = require('fs');
  9. const { CrudService } = require('naf-framework-mongoose/lib/service');
  10. const { BusinessError, ErrorCode } = require('naf-core').Error;
  11. class PatentService extends CrudService {
  12. constructor(ctx) {
  13. super(ctx, 'patent');
  14. this.model = this.ctx.model.Patent;
  15. this.root_path = process.env.NODE_ENV === 'development' ? 'E:\\exportFile' : _.get(this.ctx.app.config.export, 'root_path');
  16. this.file_type = '';
  17. if (!fs.existsSync(`${this.root_path}${this.file_type}`)) {
  18. // 如果不存在文件夹,就创建
  19. fs.mkdirSync(`${this.root_path}${this.file_type}`);
  20. }
  21. this.excel_path = `${sep}excel${sep}`;
  22. this.domain = 'http://127.0.0.1';
  23. this.export_limit = 50;
  24. }
  25. async toImport({ uri, origin }) {
  26. assert(uri, '未获取到文件地址');
  27. const file = await this.ctx.curl(`${this.domain}${uri}`);
  28. if (!(file && file.data)) {
  29. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  30. }
  31. const workbook = new Excel.Workbook();
  32. await workbook.xlsx.load(file.data);
  33. const sheet = workbook.getWorksheet(1);
  34. const arr = [];
  35. const allNotice = [];
  36. const sheetImageInfo = sheet.getImages();
  37. const imgids = _.compact(sheetImageInfo.map(i => {
  38. const { imageId, range } = i;
  39. const row = _.get(range, 'tl.nativeRow');
  40. if (row) return { row, imageId };
  41. }));
  42. sheet.eachRow((row, rindex) => {
  43. if (rindex !== 1) {
  44. // 组织数据,图片的索引和行索引不一致,准确的说是:图片索引比行索引少1
  45. // 原因:图片在工作簿中获取,按照1,2,3...顺序排序,但是行的第一行是表头(当前文件),所以当前行数需要减掉表头那一行
  46. const imgid = imgids.find(f => f.row === rindex - 1);
  47. let img_url;
  48. if (imgid) { img_url = this.turnImageToBase64(workbook.getImage(imgid.imageId)); }
  49. const create_number = row.getCell(2).value || undefined,
  50. create_date =
  51. moment(row.getCell(3).value).format('YYYY-MM-DD') || undefined,
  52. success_number = row.getCell(4).value || undefined,
  53. success_date =
  54. moment(row.getCell(5).value).format('YYYY-MM-DD') || undefined,
  55. inventor = row.getCell(6).value || undefined,
  56. agent = row.getCell(7).value || undefined,
  57. agent_personal = row.getCell(8).value || undefined,
  58. abstract = row.getCell(9).value || undefined,
  59. address = row.getCell(10).value || undefined,
  60. name = row.getCell(11).value || undefined,
  61. apply_personal = row.getCell(12).value || undefined,
  62. term = row.getCell(13).value || undefined,
  63. type = row.getCell(14).value || undefined,
  64. number = row.getCell(1).value || undefined;
  65. const obj = {
  66. create_number,
  67. create_date,
  68. success_number,
  69. success_date,
  70. inventor,
  71. agent,
  72. agent_personal,
  73. abstract,
  74. address,
  75. name,
  76. apply_personal,
  77. term,
  78. type,
  79. img_url,
  80. number,
  81. origin,
  82. };
  83. // 此处添加判断条件,不限制则不需要加,直接放过即可
  84. const { result, notice } = this.tocheckData(obj);
  85. if (result) {
  86. arr.push(obj);
  87. } else {
  88. allNotice.push(notice);
  89. }
  90. }
  91. });
  92. if (allNotice.length > 0) return allNotice;
  93. await this.model.insertMany(arr);
  94. }
  95. async toExport({ user }) {
  96. const data = {
  97. title: '专利导出',
  98. params: {
  99. project: 'market',
  100. service: 'patent',
  101. method: 'export',
  102. },
  103. user,
  104. };
  105. try {
  106. await this.ctx.service.util.httpUtil.cpost('/api/mission', 'mission', data);
  107. } catch (error) {
  108. throw new BusinessError(ErrorCode.SERVICE_FAULT, '任务创建失败');
  109. }
  110. }
  111. async export({ missionid }) {
  112. const nowDate = new Date().getTime();
  113. const filename = `导出结果-${nowDate}.xlsx`;
  114. const path = `${this.root_path}${this.file_type}${this.excel_path}`;
  115. if (!path) {
  116. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  117. }
  118. if (!fs.existsSync(path)) {
  119. // 如果不存在文件夹,就创建
  120. fs.mkdirSync(path);
  121. }
  122. const total = await this.model.count();
  123. let skip = 0;
  124. let downloadPath;
  125. // 将数据分割,否则容易直接把js堆栈干满了,服务就炸了
  126. for (let i = 0; i < total; i = i + this.export_limit) {
  127. const list = await this.model.find().skip(skip).limit(this.export_limit);
  128. skip = skip + this.export_limit;
  129. downloadPath = await this.asyncExport(list, filename, path, downloadPath);
  130. try {
  131. const data = {
  132. progress: _.ceil((skip / total) * 100),
  133. status: '1',
  134. id: missionid,
  135. };
  136. this.ctx.service.util.httpUtil.cpost('/api/mission/progress', 'mission', data);
  137. } catch (error) {
  138. this.logger.error(`任务id:${missionid},进度更新失败`);
  139. }
  140. }
  141. try {
  142. const data = {
  143. progress: 100,
  144. status: '2',
  145. uri: downloadPath,
  146. };
  147. await this.ctx.service.util.httpUtil.cpost(`/api/mission/update/${missionid}`, 'mission', data);
  148. } catch (error) {
  149. this.logger.error(`任务id:${missionid},已完成更新失败`);
  150. }
  151. return downloadPath;
  152. }
  153. async asyncExport(list, filename, path, downloadPath) {
  154. const workbook = new Excel.Workbook();
  155. let sheet;
  156. if (!downloadPath) {
  157. sheet = workbook.addWorksheet('sheet');
  158. } else {
  159. const file = await this.ctx.curl(`${this.domain}${downloadPath}`);
  160. if (!(file && file.data)) {
  161. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  162. }
  163. await workbook.xlsx.load(file.data);
  164. sheet = workbook.getWorksheet('sheet');
  165. }
  166. const rowNumber = sheet.rowCount || 1;
  167. const meta = this.getHeader();
  168. sheet.columns = meta;
  169. sheet.addRows(list);
  170. for (let i = 0; i < list.length; i++) {
  171. const e = list[i];
  172. const { img_url, _id } = e;
  173. try {
  174. if (img_url) {
  175. const is_base64 = img_url.includes('base64,');
  176. let imgid;
  177. if (is_base64) {
  178. imgid = workbook.addImage({
  179. base64: img_url,
  180. extension: 'jpeg',
  181. });
  182. } else if (img_url.includes('/files')) {
  183. const prefix = `${this.root_path}`;
  184. const new_url = img_url.replace('/files', prefix);
  185. const suffix = Path.extname(img_url).substring(1);
  186. imgid = workbook.addImage({
  187. filename: new_url,
  188. extension: suffix,
  189. });
  190. } else {
  191. // 什么都不是,那就下一个
  192. continue;
  193. }
  194. sheet.addImage(imgid, {
  195. tl: { col: 13.2, row: i + rowNumber + 0.2 },
  196. br: { col: 14, row: i + rowNumber + 1 },
  197. });
  198. }
  199. } catch (error) {
  200. this.ctx.logger.error(`导出,id为:${_id}的图片处理出现错误!`);
  201. }
  202. }
  203. const filepath = `${path}${filename}`;
  204. if (list.length <= 0) return;
  205. await workbook.xlsx.writeFile(filepath);
  206. return `/files/excel/${filename}`;
  207. }
  208. /**
  209. * 检查数据是否没填 必填项
  210. * @param {Object} object 每行数据,已转换成model的字段名
  211. */
  212. tocheckData(object) {
  213. let result = true;
  214. const { number } = object;
  215. let notice;
  216. const arr = [
  217. { column: 'create_number', zh: '申请号' },
  218. { column: 'create_date', zh: '申请日' },
  219. { column: 'success_number', zh: '公开(公告)号' },
  220. { column: 'success_date', zh: '公开(公告)日' },
  221. { column: 'name', zh: '标题' },
  222. ];
  223. const word = [];
  224. for (const o of arr) {
  225. const { column, zh } = o;
  226. if (!_.get(object, column)) {
  227. result = false;
  228. word.push(`${zh}`);
  229. }
  230. }
  231. if (!result) {
  232. notice = `序号${number}缺少:${word.join(';')}`;
  233. }
  234. return { result, notice };
  235. }
  236. /**
  237. * 转换图片为base64
  238. * @param {Object} object excel获取的图片object
  239. * @property extension 后缀,文件类型
  240. * @property buffer 图片内容,不含头部信息的,
  241. */
  242. turnImageToBase64(object = {}) {
  243. const { extension, buffer } = object;
  244. if (extension && buffer) {
  245. const suffix = object.extension;
  246. const ib = object.buffer.toString('base64');
  247. const base64 = `data:image/${suffix};base64,${ib}`;
  248. return base64;
  249. }
  250. }
  251. getHeader() {
  252. const arr = [
  253. { header: '申请号', key: 'create_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  254. { header: '申请日', key: 'create_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  255. { header: '公开(公告)号', key: 'success_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  256. { header: '公开(公告)日', key: 'success_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  257. { header: '发明人', key: 'inventor', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  258. { header: '代理机构', key: 'agent', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  259. { header: '代理人', key: 'agent_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  260. { header: '摘要', key: 'abstract', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  261. { header: '发明人地址', key: 'address', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  262. { header: '标题', key: 'name', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  263. { header: '申请人', key: 'apply_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  264. { header: '专利有效性', key: 'term', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  265. { header: '专利类型', key: 'type', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  266. { header: '首页附图', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  267. ];
  268. return arr;
  269. }
  270. }
  271. module.exports = PatentService;