patentinfo.js 21 KB

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