patentinfo.js 13 KB

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