patent.js 12 KB

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