patentinfo.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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. const { ObjectId } = require('mongoose').Types;
  13. // 专利信息
  14. class PatentinfoService extends CrudService {
  15. constructor(ctx) {
  16. super(ctx, 'patentinfo');
  17. this.model = this.ctx.model.Patent.Patentinfo;
  18. this.personalModel = this.ctx.model.Personal;
  19. this.organizationModel = this.ctx.model.Organization;
  20. this.root_path = _.get(this.ctx.app.config.export, 'root_path');
  21. if (process.env.NODE_ENV === 'development') { this.root_path = 'E:\\exportFile\\'; }
  22. this.file_type = '';
  23. if (!fs.existsSync(`${this.root_path}${this.file_type}`)) {
  24. // 如果不存在文件夹,就创建
  25. fs.mkdirSync(`${this.root_path}${this.file_type}`);
  26. }
  27. this.excel_path = `${sep}excel${sep}`;
  28. this.domain = 'http://127.0.0.1';
  29. if (process.env.NODE_ENV === 'development') { this.domain = 'http://127.0.0.1:9999'; }
  30. this.export_limit = 50;
  31. }
  32. async query(query, { skip = 0, limit = 0 }) {
  33. const newquery = await this.resetCode(query);
  34. console.log(newquery);
  35. const res = await this.model
  36. .find(newquery)
  37. .skip(parseInt(skip))
  38. .limit(parseInt(limit))
  39. .sort({ 'meta.createdAt': -1 });
  40. return res;
  41. }
  42. async count(query) {
  43. const newquery = await this.resetCode(query);
  44. const res = await this.model.countDocuments(trimData(newquery)).exec();
  45. return res;
  46. }
  47. async resetCode(query) {
  48. let newquery = _.cloneDeep(query);
  49. newquery = this.ctx.service.util.util.dealQuery(newquery);
  50. const { type } = newquery;
  51. if (type === 'else') {
  52. newquery.$and = [
  53. { type: { $ne: '发明' } },
  54. { type: { $ne: '实用新型' } },
  55. ];
  56. delete newquery.type;
  57. }
  58. const { code, user_id } = newquery;
  59. let ids = [];
  60. if (code) {
  61. const plist = await this.personalModel.find({ code });
  62. ids = plist.map(i => i._id);
  63. if (ids.length > 0) {
  64. newquery['inventor.user_id'] = { $in: ids };
  65. delete newquery.code;
  66. }
  67. } else if (user_id) {
  68. newquery['inventor.user_id'] = ObjectId(user_id);
  69. delete newquery.user_id;
  70. }
  71. return newquery;
  72. }
  73. async queryByOrg({ code, status, term, skip = 0, limit = 0 }) {
  74. assert(code, '缺少机构信息');
  75. let pids = await this.personalModel.find({ code }, { _id: 1 });
  76. if (pids.length <= 0) return { data: [], total: 0 };
  77. pids = pids.map(i => i._id);
  78. const query = { 'inventor.user_id': { $in: pids } };
  79. if (status) query.status = status;
  80. if (term) query.term = term;
  81. console.log(query);
  82. const data = await this.model
  83. .find(query)
  84. .skip(parseInt(skip))
  85. .limit(parseInt(limit))
  86. .sort({ 'meta.createdAt': -1 });
  87. const total = await this.model.count(query);
  88. return { data, total };
  89. }
  90. async toImport({ uri, origin }) {
  91. assert(uri, '未获取到文件地址');
  92. const file = await this.ctx.curl(`${this.domain}${uri}`);
  93. if (!(file && file.data)) {
  94. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  95. }
  96. const workbook = new Excel.Workbook();
  97. await workbook.xlsx.load(file.data);
  98. const sheet = workbook.getWorksheet(1);
  99. const arr = [];
  100. const allNotice = [];
  101. const sheetImageInfo = sheet.getImages();
  102. const imgids = _.compact(
  103. sheetImageInfo.map(i => {
  104. const { imageId, range } = i;
  105. const row = _.get(range, 'tl.nativeRow');
  106. if (row) return { row, imageId };
  107. })
  108. );
  109. sheet.eachRow(async (row, rindex) => {
  110. if (rindex !== 1) {
  111. // 组织数据,图片的索引和行索引不一致,准确的说是:图片索引比行索引少1
  112. // 原因:图片在工作簿中获取,按照1,2,3...顺序排序,但是行的第一行是表头(当前文件),所以当前行数需要减掉表头那一行
  113. const imgid = imgids.find(f => f.row === rindex - 1);
  114. const img_url = [];
  115. if (imgid) {
  116. img_url.push({
  117. url: this.turnImageToBase64(workbook.getImage(imgid.imageId)),
  118. });
  119. }
  120. const create_number = row.getCell(2).value || undefined,
  121. create_date =
  122. moment(row.getCell(3).value).format('YYYY-MM-DD') || undefined,
  123. success_number = row.getCell(4).value || undefined,
  124. success_date =
  125. moment(row.getCell(5).value).format('YYYY-MM-DD') || undefined,
  126. inventor = row.getCell(6).value || undefined,
  127. agent = row.getCell(7).value || undefined,
  128. agent_personal = row.getCell(8).value || undefined,
  129. abstract = row.getCell(9).value || undefined,
  130. address = row.getCell(10).value || undefined,
  131. name = row.getCell(11).value || undefined,
  132. apply_personal = row.getCell(12).value || undefined,
  133. term = row.getCell(13).value || undefined,
  134. type = row.getCell(14).value || undefined,
  135. number = row.getCell(1).value || undefined,
  136. // 新增专利数据属性2021-09-06
  137. nationality = row.getCell(16).value || undefined,
  138. ipc_type = row.getCell(17).value || undefined,
  139. onlegal_status = row.getCell(18).value || undefined,
  140. legal_status = row.getCell(19).value || undefined,
  141. law_date =
  142. moment(row.getCell(20).value).format('YYYY-MM-DD') || undefined,
  143. on_obligee = row.getCell(21).value || undefined,
  144. apply_address = row.getCell(22).value || undefined,
  145. apply_other = row.getCell(23).value || undefined,
  146. law_num = row.getCell(24).value || undefined,
  147. first_opendate =
  148. moment(row.getCell(25).value).format('YYYY-MM-DD') || undefined,
  149. empower_date =
  150. moment(row.getCell(26).value).format('YYYY-MM-DD') || undefined,
  151. lose_date =
  152. moment(row.getCell(27).value).format('YYYY-MM-DD') || undefined,
  153. examine_date =
  154. moment(row.getCell(28).value).format('YYYY-MM-DD') || undefined,
  155. invention_design = row.getCell(29).value || undefined;
  156. const obj = {
  157. create_number,
  158. create_date,
  159. success_number,
  160. success_date,
  161. inventor,
  162. agent,
  163. agent_personal,
  164. abstract,
  165. address,
  166. name,
  167. apply_personal,
  168. term,
  169. type,
  170. img_url,
  171. number,
  172. origin,
  173. user_id: [],
  174. // 新增专利数据属性2021-09-06
  175. nationality,
  176. ipc_type,
  177. onlegal_status,
  178. legal_status,
  179. law_date,
  180. on_obligee,
  181. apply_address,
  182. apply_other,
  183. law_num,
  184. first_opendate,
  185. empower_date,
  186. lose_date,
  187. examine_date,
  188. invention_design,
  189. };
  190. // 此处添加判断条件,不限制则不需要加,直接放过即可
  191. const { result, notice } = this.tocheckData(obj);
  192. if (result) {
  193. arr.push(obj);
  194. } else {
  195. allNotice.push(notice);
  196. }
  197. }
  198. });
  199. if (allNotice.length > 0) return allNotice;
  200. let nameList = [];
  201. for (const i of arr) {
  202. const { inventor } = i;
  203. const midList = inventor.split(/[,;/]/);
  204. nameList = [ ...nameList, ...midList ];
  205. }
  206. nameList = nameList.map(i => _.trim(i));
  207. const l1 = await this.personalModel.find({ name: nameList });
  208. const l2 = await this.organizationModel.find({ name: nameList });
  209. // 查出来的所有人
  210. const nList = [ ...l1, ...l2 ];
  211. for (const i of arr) {
  212. const { inventor } = i;
  213. let midNameList = inventor.split(/[,;/]/);
  214. midNameList = midNameList.map(i => _.trim(i));
  215. const iList = [];
  216. if (!_.isArray(i.user_id)) i.inventor = iList;
  217. for (const name of midNameList) {
  218. const rList = nList.filter(f => f.name === name);
  219. if (rList && rList.length > 0) {
  220. for (const r of rList) {
  221. iList.push({ user_id: r._id, name: r.name });
  222. }
  223. }
  224. }
  225. i.inventor = iList;
  226. }
  227. const res = await this.model.insertMany(arr);
  228. return res;
  229. }
  230. async toExport({ user }) {
  231. const data = {
  232. title: '专利导出',
  233. params: {
  234. project: 'market',
  235. service: 'patent.patentinfo',
  236. method: 'export',
  237. },
  238. user,
  239. tenant: 'live',
  240. };
  241. try {
  242. await this.ctx.service.util.httpUtil.cpost(
  243. '/api/mission',
  244. 'mission',
  245. data
  246. );
  247. } catch (error) {
  248. console.log(error);
  249. throw new BusinessError(ErrorCode.SERVICE_FAULT, '任务创建失败');
  250. }
  251. }
  252. async export({ missionid }) {
  253. const nowDate = new Date().getTime();
  254. const filename = `导出结果-${nowDate}.xlsx`;
  255. const path = `${this.root_path}${this.file_type}${this.excel_path}`;
  256. if (!path) {
  257. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  258. }
  259. if (!fs.existsSync(path)) {
  260. // 如果不存在文件夹,就创建
  261. fs.mkdirSync(path);
  262. }
  263. const total = await this.model.count();
  264. let skip = 0;
  265. let downloadPath;
  266. // 将数据分割,否则容易直接把js堆栈干满了,服务就炸了
  267. for (let i = 0; i < total; i = i + this.export_limit) {
  268. const list = await this.model.find().skip(skip).limit(this.export_limit);
  269. skip = skip + this.export_limit;
  270. downloadPath = await this.asyncExport(list, filename, path, downloadPath);
  271. try {
  272. const data = {
  273. progress: _.ceil((skip / total) * 100),
  274. status: '1',
  275. id: missionid,
  276. };
  277. this.ctx.service.util.httpUtil.cpost(
  278. '/api/mission/progress',
  279. 'mission',
  280. data
  281. );
  282. } catch (error) {
  283. this.logger.error(`任务id:${missionid},进度更新失败`);
  284. }
  285. }
  286. try {
  287. const data = {
  288. progress: 100,
  289. status: '2',
  290. uri: downloadPath,
  291. };
  292. await this.ctx.service.util.httpUtil.cpost(
  293. `/api/mission/update/${missionid}`,
  294. 'mission',
  295. data
  296. );
  297. } catch (error) {
  298. this.logger.error(`任务id:${missionid},已完成更新失败`);
  299. }
  300. return downloadPath;
  301. }
  302. async asyncExport(list, filename, path, downloadPath) {
  303. const workbook = new Excel.Workbook();
  304. let sheet;
  305. if (!downloadPath) {
  306. sheet = workbook.addWorksheet('sheet');
  307. } else {
  308. const file = await this.ctx.curl(`${this.domain}${downloadPath}`);
  309. if (!(file && file.data)) {
  310. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  311. }
  312. await workbook.xlsx.load(file.data);
  313. sheet = workbook.getWorksheet('sheet');
  314. }
  315. const rowNumber = sheet.rowCount || 1;
  316. const meta = this.getHeader();
  317. sheet.columns = meta;
  318. sheet.addRows(list);
  319. for (let i = 0; i < list.length; i++) {
  320. const e = list[i];
  321. const { img_url, _id } = e;
  322. try {
  323. if (img_url) {
  324. const is_base64 = img_url.includes('base64,');
  325. let imgid;
  326. if (is_base64) {
  327. imgid = workbook.addImage({
  328. base64: img_url,
  329. extension: 'jpeg',
  330. });
  331. } else if (img_url.includes('/files')) {
  332. const prefix = `${this.root_path}`;
  333. const new_url = img_url.replace('/files', prefix);
  334. const suffix = Path.extname(img_url).substring(1);
  335. imgid = workbook.addImage({
  336. filename: new_url,
  337. extension: suffix,
  338. });
  339. } else {
  340. // 什么都不是,那就下一个
  341. continue;
  342. }
  343. sheet.addImage(imgid, {
  344. tl: { col: 13.2, row: i + rowNumber + 0.2 },
  345. br: { col: 14, row: i + rowNumber + 1 },
  346. });
  347. }
  348. } catch (error) {
  349. this.ctx.logger.error(`导出,id为:${_id}的图片处理出现错误!`);
  350. }
  351. }
  352. const filepath = `${path}${filename}`;
  353. if (list.length <= 0) return;
  354. await workbook.xlsx.writeFile(filepath);
  355. return `/files/excel/${filename}`;
  356. }
  357. /**
  358. * 检查数据是否没填 必填项
  359. * @param {Object} object 每行数据,已转换成model的字段名
  360. */
  361. tocheckData(object) {
  362. let result = true;
  363. const { number } = object;
  364. let notice;
  365. const arr = [
  366. { column: 'create_number', zh: '申请号' },
  367. { column: 'create_date', zh: '申请日' },
  368. { column: 'success_number', zh: '公开(公告)号' },
  369. { column: 'success_date', zh: '公开(公告)日' },
  370. { column: 'name', zh: '标题' },
  371. ];
  372. const word = [];
  373. for (const o of arr) {
  374. const { column, zh } = o;
  375. if (!_.get(object, column)) {
  376. result = false;
  377. word.push(`${zh}`);
  378. }
  379. }
  380. if (!result) {
  381. notice = `序号${number}缺少:${word.join(';')}`;
  382. }
  383. return { result, notice };
  384. }
  385. /**
  386. * 转换图片为base64
  387. * @param {Object} object excel获取的图片object
  388. * @property extension 后缀,文件类型
  389. * @property buffer 图片内容,不含头部信息的,
  390. */
  391. turnImageToBase64(object = {}) {
  392. const { extension, buffer } = object;
  393. if (extension && buffer) {
  394. const suffix = object.extension;
  395. const ib = object.buffer.toString('base64');
  396. const base64 = `data:image/${suffix};base64,${ib}`;
  397. return base64;
  398. }
  399. }
  400. getHeader() {
  401. const arr = [
  402. { header: '申请号', key: 'create_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  403. { header: '申请日', key: 'create_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  404. { header: '公开(公告)号', key: 'success_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  405. { header: '公开(公告)日', key: 'success_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  406. { header: '发明人', key: 'inventor', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  407. { header: '代理机构', key: 'agent', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  408. { header: '代理人', key: 'agent_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  409. { header: '摘要', key: 'abstract', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  410. { header: '发明人地址', key: 'address', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  411. { header: '标题', key: 'name', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  412. { header: '申请人', key: 'apply_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  413. { header: '专利有效性', key: 'term', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  414. { header: '专利类型', key: 'type', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  415. { header: '首页附图', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  416. { header: '公开国别', key: 'nationality', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  417. { header: 'IPC主分类', key: 'ipc_type', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  418. { header: '当前法律状态', key: 'onlegal_status', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  419. { header: '法律状态', key: 'legal_status', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  420. { header: '法律文书日期', key: 'law_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  421. { header: '当前权利人', key: 'on_obligee', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  422. { header: '申请人地址(其他)', key: 'apply_address', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  423. { header: '申请人(其他)', key: 'apply_other', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  424. { header: '法律文书编号', key: 'law_num', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  425. { header: '首次公开日', key: 'first_opendate', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  426. { header: '授权公告日', key: 'empower_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  427. { header: '失效日', key: 'lose_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  428. { header: '实际审查失效日', key: 'examine_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  429. { header: '发明人(设计)其他', key: 'invention_design', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  430. ];
  431. return arr;
  432. }
  433. async getByCreateNumber({ create_number }) {
  434. const data = await this.model.findOne({ create_number });
  435. return data;
  436. }
  437. async mechQuery({ skip = 0, limit = 0, ...query }) {
  438. const code = _.get(query, 'code');
  439. assert(code, '缺少机构信息!');
  440. const { empower_sort, ...others } = query;
  441. const newQuery = await this.toSetQuery(others);
  442. let sort = 'desc';
  443. if (empower_sort === '0') {
  444. sort = 'asc';
  445. }
  446. const data = await this.model.find(newQuery).sort({ empower_date: sort }).skip(parseInt(skip))
  447. .limit(parseInt(limit));
  448. const total = await this.model.count(newQuery);
  449. return { data, total };
  450. }
  451. async toSetQuery(query) {
  452. let queryObject = {};
  453. for (const key in query) {
  454. if (key === 'code') {
  455. const cquery = await this.dealCode(query[key]);
  456. queryObject = { ...queryObject, ...cquery };
  457. } else if (key === 'empower_year') {
  458. queryObject.empower_date = this.dealYearRange(query[key]);
  459. } else if (key === 'apply_year') {
  460. queryObject.create_date = this.dealYearRange(query[key]);
  461. } else if (key === 'ipc_type') {
  462. queryObject.ipc_type = new RegExp(`^${query[key]}`, 'i');
  463. } else if (key === 'field') {
  464. queryObject.abstract = new RegExp(query[key]);
  465. } else if (key === 'create_number') {
  466. queryObject.create_number = new RegExp(query[key]);
  467. } else if (key === 'first_inventor') {
  468. queryObject.inventor = new RegExp(`^${query[key]}`, 'i');
  469. } else if (key === 'on_obligee') {
  470. queryObject.on_obligee = new RegExp(`^${query[key]}`, 'i');
  471. } else if (key === 'type') {
  472. queryObject.type = new RegExp(`^${query[key]}`, 'i');
  473. } else if (key === 'is_empower') {
  474. let r = '';
  475. if (query[key] === '0') r = true;
  476. else r = false;
  477. queryObject.empower_date = { $exists: r };
  478. } else if (key === 'term') {
  479. queryObject.term = new RegExp(query[key]);
  480. } else if (key === 'is_lose') {
  481. const toDay = moment().format('YYYY-MM-DD');
  482. let r = '';
  483. if (query[key] === '0') r = { $gt: toDay };
  484. else r = { $lte: toDay };
  485. queryObject.lose_date = r;
  486. }
  487. }
  488. return queryObject;
  489. }
  490. async dealCode(code) {
  491. let pids = await this.personalModel.find({ code }, { _id: 1 });
  492. if (pids.length <= 0) return { data: [], total: 0 };
  493. pids = pids.map(i => i._id);
  494. const query = { user_id: { $elemMatch: { $in: pids } } };
  495. return query;
  496. }
  497. async dealYearRange(year) {
  498. const start = `${year}-01-01`;
  499. const end = `${year}-12-31`;
  500. const obj = { $gte: start, $lte: end };
  501. return obj;
  502. }
  503. /**
  504. * 根据人名数组查询每个人的数据.组织数据返回
  505. * @param {Array[String]} nameList 名单
  506. */
  507. async toGetUser(nameList) {
  508. const res = await this.personalModel.find({ name: { $in: nameList } });
  509. const result = [];
  510. if (res && res.length > 0) {
  511. for (const i of res) {
  512. const { _id: id, name } = i;
  513. result.push({ id, name });
  514. }
  515. }
  516. return result;
  517. }
  518. }
  519. module.exports = PatentinfoService;