disclosure.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const Path = require('path');
  5. const _ = require('lodash');
  6. const moment = require('moment');
  7. const assert = require('assert');
  8. const { ObjectId } = require('mongoose').Types;
  9. const Excel = require('exceljs');
  10. const { sep } = require('path');
  11. const fs = require('fs');
  12. // 交底书
  13. class DisclosureService extends CrudService {
  14. constructor(ctx) {
  15. super(ctx, 'disclosure');
  16. this.model = this.ctx.model.Patent.Disclosure;
  17. this.notice = this.ctx.model.Patent.Notice;
  18. this.patent = this.ctx.model.Dock.Patent;
  19. this.personalModel = this.ctx.model.Personal;
  20. this.organizationModel = this.ctx.model.Organization;
  21. this.itemp = this.ctx.model.Patent.ImportTemp;
  22. this.root_path = _.get(this.ctx.app.config.export, 'root_path');
  23. if (!fs.existsSync(`${this.root_path}`)) {
  24. // 如果不存在文件夹,就创建
  25. fs.mkdirSync(`${this.root_path}`);
  26. }
  27. this.excel_path = `${sep}excel${sep}`;
  28. this.domain = _.get(this.ctx.app.config.export, 'domain');
  29. this.export_limit = 50;
  30. }
  31. /**
  32. * 查询有评估报告的交底书
  33. * @param {Object} param0 条件
  34. */
  35. async haveReport({ skip, limit, ...query }) {
  36. const { user_id, admin_id, mechanism_id } = query;
  37. if (user_id) query.user_id = ObjectId(user_id);
  38. if (admin_id) query.admin_id = ObjectId(admin_id);
  39. if (mechanism_id) query.mechanism_id = ObjectId(mechanism_id);
  40. const condition = [
  41. { $match: { ...query } },
  42. {
  43. $lookup: {
  44. from: 'disclosure_report',
  45. localField: '_id',
  46. foreignField: 'disclosure_id',
  47. as: 'report',
  48. },
  49. },
  50. { $match: { 'report.0': { $exists: true } } },
  51. { $sort: { 'meta.createdAt': -1 } },
  52. { $project: { report: 0 } },
  53. { $addFields: { has_report: true } },
  54. ];
  55. const ctotal = [
  56. ...condition,
  57. { $group: { _id: '', total: { $sum: 1 } } },
  58. ];
  59. const tres = await this.model.aggregate(ctotal);
  60. const total = _.get(_.head(tres), 'total', 0);
  61. if (skip && limit) {
  62. condition.push({ $skip: parseInt(skip) });
  63. condition.push({ $limit: parseInt(limit) });
  64. }
  65. const res = await this.model.aggregate(condition);
  66. return { data: res, total };
  67. }
  68. /**
  69. * 交底书审核
  70. * @param {body} body 参数
  71. * @property id 数据id
  72. * @property status 交底书要改变成的状态
  73. * @property info 其他数据,当做多个备注,记录使用
  74. */
  75. async check({ id, status, remark }) {
  76. const data = { status };
  77. if (status === '4') data['meta.state'] = 1;
  78. await this.model.updateOne({ _id: ObjectId(id) }, data);
  79. // 换成对应的状态码,record在下面
  80. return await this.record({ id, method: status, remark });
  81. }
  82. async record({ id, method, remark }) {
  83. let word = '';
  84. switch (`${method}`) {
  85. case 'create':
  86. word = '已申请';
  87. break;
  88. case 'update':
  89. word = '修改';
  90. break;
  91. case '1':
  92. word = '机构审核';
  93. break;
  94. case '-1':
  95. word = '机构审核未通过';
  96. break;
  97. case '2':
  98. word = '管理员评估';
  99. break;
  100. case '-2':
  101. word = '管理员评估未通过';
  102. break;
  103. case '3':
  104. word = '管理员评估通过,等待上传至国家库';
  105. break;
  106. case '4':
  107. word = '上传完成';
  108. break;
  109. default:
  110. word = '未知状态';
  111. break;
  112. }
  113. const data = await this.model.findById(id);
  114. if (!data) {
  115. throw new BusinessError(
  116. ErrorCode.DATA_NOT_EXIST,
  117. '添加记录----未找到数据'
  118. );
  119. }
  120. const obj = {
  121. time: moment().format('YYYY-MM-DD HH:mm:ss'),
  122. word,
  123. remark,
  124. };
  125. data.record.push(obj);
  126. const res = await data.save();
  127. this.toNotice(id, method);
  128. return res;
  129. }
  130. async toNotice(id, code) {
  131. const data = await this.model.findById(id);
  132. if (!data) return;
  133. const { user_id, admin_id, mechanism_id, status, name, apply_name } = data;
  134. const arr = [];
  135. let content = '';
  136. let to = '';
  137. switch (code) {
  138. case 'create':
  139. content = `${apply_name}提交了专利申请书(${name})的申报,请及时前往申请管理进行处理`;
  140. if (status === '1') {
  141. to = mechanism_id;
  142. } else {
  143. to = admin_id;
  144. }
  145. break;
  146. case 'update':
  147. content = `${apply_name}重新提交了专利申请书(${name})的申报,请及时前往申请管理进行处理`;
  148. if (status === '1') {
  149. to = mechanism_id;
  150. } else {
  151. to = admin_id;
  152. }
  153. break;
  154. case '-1':
  155. content = `您的专利申请书(${name})未通过机构的审核,请您及时修改,重新申请`;
  156. to = user_id;
  157. break;
  158. case '-2':
  159. content = `您的专利申请书(${name})未通过管理员的评估,请您及时修改,重新申请`;
  160. to = user_id;
  161. break;
  162. case '2':
  163. arr.push({
  164. content: `您的专利申请书(${name})已通过机构的审核,请您耐心等待管理员评估`,
  165. to: user_id,
  166. });
  167. arr.push({
  168. content: `${apply_name}的专利申请书(${name})已通过机构的审核,请您尽快对其进行评估`,
  169. to: admin_id,
  170. });
  171. break;
  172. case '3':
  173. content = `您的专利申请书(${name})已通过机构的审核,请您耐心等待上传至国家专利库中`;
  174. to = user_id;
  175. break;
  176. case '4':
  177. content = `您的专利申请书(${name})已上传至国家专利库中`;
  178. to = user_id;
  179. break;
  180. default:
  181. break;
  182. }
  183. if (code !== '2') {
  184. const obj = { to, content };
  185. await this.notice.create(obj);
  186. } else {
  187. await this.notice.insertMany(arr);
  188. }
  189. }
  190. // 导入
  191. async import({ uri }) {
  192. assert(uri, '未获取到文件地址');
  193. const file = await this.ctx.curl(`${this.domain}${uri}`);
  194. if (!(file && file.data)) {
  195. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  196. }
  197. const workbook = new Excel.Workbook();
  198. await workbook.xlsx.load(file.data);
  199. const sheet = workbook.getWorksheet(1);
  200. const arr = [];
  201. const allNotice = [];
  202. const sheetImageInfo = sheet.getImages();
  203. const imgids = _.compact(sheetImageInfo.map(i => {
  204. const { imageId, range } = i;
  205. const row = _.get(range, 'tl.nativeRow');
  206. if (row) return { row, imageId };
  207. }));
  208. sheet.eachRow((row, rindex) => {
  209. if (rindex !== 1) {
  210. // 组织数据,图片的索引和行索引不一致,准确的说是:图片索引比行索引少1
  211. // 原因:图片在工作簿中获取,按照1,2,3...顺序排序,但是行的第一行是表头(当前文件),所以当前行数需要减掉表头那一行
  212. const imgid = imgids.find(f => f.row === rindex - 1);
  213. let img_url;
  214. if (imgid) { img_url = this.turnImageToBase64(workbook.getImage(imgid.imageId)); }
  215. const create_number = row.getCell(2).value || undefined,
  216. create_date =
  217. moment(row.getCell(3).value).format('YYYY-MM-DD') || undefined,
  218. success_number = row.getCell(4).value || undefined,
  219. success_date =
  220. moment(row.getCell(5).value).format('YYYY-MM-DD') || undefined,
  221. inventor = row.getCell(6).value || undefined,
  222. agent = row.getCell(7).value || undefined,
  223. agent_personal = row.getCell(8).value || undefined,
  224. abstract = row.getCell(9).value || undefined,
  225. address = row.getCell(10).value || undefined,
  226. name = row.getCell(11).value || undefined,
  227. apply_personal = row.getCell(12).value || undefined,
  228. term = row.getCell(13).value || undefined,
  229. type = row.getCell(14).value || undefined,
  230. number = row.getCell(1).value || undefined;
  231. const obj = {
  232. create_number,
  233. create_date,
  234. success_number,
  235. success_date,
  236. inventor,
  237. agent,
  238. agent_personal,
  239. abstract,
  240. address,
  241. name,
  242. apply_personal,
  243. term,
  244. type,
  245. img_url,
  246. number,
  247. user_id: [],
  248. };
  249. // 此处添加判断条件,不限制则不需要加,直接放过即可
  250. const { result, notice } = this.tocheckData(obj);
  251. if (result) {
  252. arr.push(obj);
  253. } else {
  254. allNotice.push(notice);
  255. }
  256. }
  257. });
  258. if (allNotice.length > 0) return { data: allNotice, errcode: '1' };
  259. // 信息合格后,将发明人分出来,然后在个人/企业查出来,如果不是一个人,那就返回给前端,让前端选择后进行存储
  260. // 提取出所有人,分割,放到数组里(重不重复无所谓,这个地方无所谓);然后用人名去查出来所有的用户(企业/个人),如果有重复的,那就提出来返回给前端
  261. let nameList = [];
  262. for (const i of arr) {
  263. const { inventor } = i;
  264. const midList = inventor.split(/[,;/]/);
  265. nameList = [ ...nameList, ...midList ];
  266. }
  267. const l1 = await this.personalModel.find({ name: nameList });
  268. const l2 = await this.organizationModel.find({ name: nameList });
  269. // 查出来的所有人
  270. const nList = [ ...l1, ...l2 ];
  271. const groups = _.groupBy(nList, 'name');
  272. // 重复的名单
  273. const rList = {};
  274. for (const key in groups) {
  275. if (groups[key].length > 1) {
  276. rList[key] = groups[key];
  277. } else {
  278. // 剩下的都是1个的,直接找所有项目里有没有这个人,有就扔进去
  279. for (const i of arr) {
  280. const { inventor } = i;
  281. if (inventor.includes(key)) {
  282. const acct = _.head(groups[key]);
  283. if (acct) i.user_id.push(acct._id);
  284. }
  285. }
  286. }
  287. }
  288. // 将有这些重复人名的专利找到,返回前端
  289. const errorArr = [];
  290. const dealList = [];
  291. for (const i of arr) {
  292. const { inventor } = i;
  293. const key = Object.keys(rList).find(i => inventor.includes(i));
  294. if (key) errorArr.push({ ...i, nameList: rList[key] });
  295. else dealList.push(i);
  296. }
  297. // 不导入,缓存
  298. if (errorArr.length > 0) {
  299. const tempRes = await this.itemp.create({ data: dealList });
  300. const { _id } = tempRes;
  301. return { data: errorArr, errcode: '2', temp_id: _id };
  302. }
  303. await this.importAction(dealList);
  304. }
  305. // 继续导入
  306. async cacheImport({ data, temp_id }) {
  307. data = data.map(i => {
  308. const acct = i.nameList.find(f => f.is_select);
  309. if (acct) {
  310. const { _id } = acct;
  311. i.user_id.push(_id);
  312. }
  313. delete i.nameList;
  314. return i;
  315. });
  316. const tempList = await this.itemp.findById(temp_id);
  317. data = [ ...data, ...tempList.data ];
  318. await this.importAction(data);
  319. await this.itemp.deleteOne({ _id: temp_id });
  320. }
  321. async importAction(data) {
  322. await this.patent.insertMany(data);
  323. }
  324. /**
  325. * 检查数据是否没填 必填项
  326. * @param {Object} object 每行数据,已转换成model的字段名
  327. */
  328. tocheckData(object) {
  329. let result = true;
  330. const { number } = object;
  331. let notice;
  332. const arr = [
  333. { column: 'create_number', zh: '申请号' },
  334. { column: 'create_date', zh: '申请日' },
  335. { column: 'success_number', zh: '公开(公告)号' },
  336. { column: 'success_date', zh: '公开(公告)日' },
  337. { column: 'inventor', zh: '发明人' },
  338. { column: 'apply_personal', zh: '申请人' },
  339. { column: 'name', zh: '标题' },
  340. ];
  341. const word = [];
  342. for (const o of arr) {
  343. const { column, zh } = o;
  344. if (!_.get(object, column)) {
  345. result = false;
  346. word.push(`${zh}`);
  347. }
  348. }
  349. if (!result) {
  350. notice = `序号${number}缺少:${word.join(';')}`;
  351. }
  352. return { result, notice };
  353. }
  354. /**
  355. * 转换图片为base64
  356. * @param {Object} object excel获取的图片object
  357. * @property extension 后缀,文件类型
  358. * @property buffer 图片内容,不含头部信息的,
  359. */
  360. turnImageToBase64(object = {}) {
  361. const { extension, buffer } = object;
  362. if (extension && buffer) {
  363. const suffix = object.extension;
  364. const ib = object.buffer.toString('base64');
  365. const base64 = `data:image/${suffix};base64,${ib}`;
  366. return base64;
  367. }
  368. }
  369. async toExport({ id, ...others }) {
  370. const data = {
  371. title: '专利运营-专利导出',
  372. params: {
  373. project: 'market',
  374. service: 'patent.disclosure',
  375. method: 'exportAction',
  376. body: { ...others },
  377. },
  378. tenant: 'disclosure.export',
  379. user: id,
  380. };
  381. try {
  382. await this.ctx.service.util.httpUtil.cpost('/api/mission', 'mission', data);
  383. } catch (error) {
  384. console.log(error);
  385. throw new BusinessError(ErrorCode.SERVICE_FAULT, '任务创建失败');
  386. }
  387. }
  388. async exportAction({ missionid, ...body }) {
  389. const nowDate = new Date().getTime();
  390. const filename = `专利运营-专利导出-${nowDate}.xlsx`;
  391. const path = `${this.root_path}${this.excel_path}`;
  392. if (!path) {
  393. throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
  394. }
  395. if (!fs.existsSync(path)) {
  396. // 如果不存在文件夹,就创建
  397. fs.mkdirSync(path);
  398. }
  399. // 整理条件
  400. const total = await this.ctx.service.dock.patent.count(body);
  401. console.log(total);
  402. if (total === 0) {
  403. try {
  404. const data = {
  405. progress: 0,
  406. status: '3',
  407. remark: '未查到任何数据,无法导出',
  408. };
  409. await this.ctx.service.util.httpUtil.cpost(`/api/mission/update/${missionid}`, 'mission', data);
  410. } catch (error) {
  411. this.logger.error(`任务id:${missionid},更新失败操作 失败`);
  412. }
  413. return;
  414. }
  415. let skip = 0;
  416. let downloadPath;
  417. // 将数据分割,否则容易直接把js堆栈干满了,服务就炸了
  418. for (let i = 0; i < total; i = i + this.export_limit) {
  419. const list = await this.ctx.service.dock.patent.query(body, { skip, limit: this.export_limit });
  420. skip = skip + this.export_limit;
  421. downloadPath = await this.asyncExport(list, filename, path, downloadPath);
  422. try {
  423. const data = {
  424. progress: _.ceil((skip / total) * 100),
  425. status: '1',
  426. id: missionid,
  427. };
  428. this.ctx.service.util.httpUtil.cpost('/api/mission/progress', 'mission', data);
  429. } catch (error) {
  430. this.logger.error(`任务id:${missionid},进度更新失败`);
  431. }
  432. }
  433. try {
  434. const data = {
  435. progress: 100,
  436. status: '2',
  437. uri: downloadPath,
  438. };
  439. await this.ctx.service.util.httpUtil.cpost(`/api/mission/update/${missionid}`, 'mission', data);
  440. } catch (error) {
  441. this.logger.error(`任务id:${missionid},已完成更新失败`);
  442. }
  443. return downloadPath;
  444. }
  445. async asyncExport(list, filename, path, downloadPath) {
  446. const workbook = new Excel.Workbook();
  447. let sheet;
  448. if (!downloadPath) {
  449. sheet = workbook.addWorksheet('sheet');
  450. } else {
  451. const file = await this.ctx.curl(`${this.domain}${downloadPath}`);
  452. if (!(file && file.data)) {
  453. throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
  454. }
  455. await workbook.xlsx.load(file.data);
  456. sheet = workbook.getWorksheet('sheet');
  457. }
  458. const rowNumber = sheet.rowCount || 1;
  459. const meta = this.getHeader();
  460. sheet.columns = meta;
  461. sheet.addRows(list);
  462. for (let i = 0; i < list.length; i++) {
  463. const e = list[i];
  464. const { img_url, _id } = e;
  465. try {
  466. if (img_url) {
  467. const is_base64 = img_url.includes('base64,');
  468. let imgid;
  469. if (is_base64) {
  470. imgid = workbook.addImage({
  471. base64: img_url,
  472. extension: 'jpeg',
  473. });
  474. } else if (img_url.includes('/files')) {
  475. const prefix = `${this.root_path}`;
  476. const new_url = img_url.replace('/files', prefix);
  477. const suffix = Path.extname(img_url).substring(1);
  478. imgid = workbook.addImage({
  479. filename: new_url,
  480. extension: suffix,
  481. });
  482. } else {
  483. // 什么都不是,那就下一个
  484. continue;
  485. }
  486. sheet.addImage(imgid, {
  487. tl: { col: 13.2, row: i + rowNumber + 0.2 },
  488. br: { col: 14, row: i + rowNumber + 1 },
  489. });
  490. }
  491. } catch (error) {
  492. this.ctx.logger.error(`导出,id为:${_id}的图片处理出现错误!`);
  493. }
  494. }
  495. const filepath = `${path}${filename}`;
  496. if (list.length <= 0) return;
  497. await workbook.xlsx.writeFile(filepath);
  498. return `/files/excel/${filename}`;
  499. }
  500. getHeader() {
  501. const arr = [
  502. { header: '申请号', key: 'create_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  503. { header: '申请日', key: 'create_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  504. { header: '公开(公告)号', key: 'success_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  505. { header: '公开(公告)日', key: 'success_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  506. { header: '发明人', key: 'inventor', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  507. { header: '代理机构', key: 'agent', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  508. { header: '代理人', key: 'agent_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  509. { header: '摘要', key: 'abstract', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  510. { header: '发明人地址', key: 'address', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  511. { header: '标题', key: 'name', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  512. { header: '申请人', key: 'apply_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  513. { header: '专利有效性', key: 'term', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  514. { header: '专利类型', key: 'type', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  515. { header: '首页附图(压缩图)', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
  516. ];
  517. return arr;
  518. }
  519. }
  520. module.exports = DisclosureService;