123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538 |
- 'use strict';
- const { CrudService } = require('naf-framework-mongoose/lib/service');
- const { BusinessError, ErrorCode } = require('naf-core').Error;
- const Path = require('path');
- const _ = require('lodash');
- const moment = require('moment');
- const assert = require('assert');
- const { ObjectId } = require('mongoose').Types;
- const Excel = require('exceljs');
- const { sep } = require('path');
- const fs = require('fs');
- // 交底书
- class DisclosureService extends CrudService {
- constructor(ctx) {
- super(ctx, 'disclosure');
- this.model = this.ctx.model.Patent.Disclosure;
- this.notice = this.ctx.model.Patent.Notice;
- this.patent = this.ctx.model.Dock.Patent;
- this.personalModel = this.ctx.model.Personal;
- this.organizationModel = this.ctx.model.Organization;
- this.itemp = this.ctx.model.Patent.ImportTemp;
- this.root_path = _.get(this.ctx.app.config.export, 'root_path');
- if (!fs.existsSync(`${this.root_path}`)) {
- // 如果不存在文件夹,就创建
- fs.mkdirSync(`${this.root_path}`);
- }
- this.excel_path = `${sep}excel${sep}`;
- this.domain = _.get(this.ctx.app.config.export, 'domain');
- this.export_limit = 50;
- }
- /**
- * 查询有评估报告的交底书
- * @param {Object} param0 条件
- */
- async haveReport({ skip, limit, ...query }) {
- const { user_id, admin_id, mechanism_id } = query;
- if (user_id) query.user_id = ObjectId(user_id);
- if (admin_id) query.admin_id = ObjectId(admin_id);
- if (mechanism_id) query.mechanism_id = ObjectId(mechanism_id);
- const condition = [
- { $match: { ...query } },
- {
- $lookup: {
- from: 'disclosure_report',
- localField: '_id',
- foreignField: 'disclosure_id',
- as: 'report',
- },
- },
- { $match: { 'report.0': { $exists: true } } },
- { $sort: { 'meta.createdAt': -1 } },
- { $project: { report: 0 } },
- { $addFields: { has_report: true } },
- ];
- const ctotal = [
- ...condition,
- { $group: { _id: '', total: { $sum: 1 } } },
- ];
- const tres = await this.model.aggregate(ctotal);
- const total = _.get(_.head(tres), 'total', 0);
- if (skip && limit) {
- condition.push({ $skip: parseInt(skip) });
- condition.push({ $limit: parseInt(limit) });
- }
- const res = await this.model.aggregate(condition);
- return { data: res, total };
- }
- /**
- * 交底书审核
- * @param {body} body 参数
- * @property id 数据id
- * @property status 交底书要改变成的状态
- * @property info 其他数据,当做多个备注,记录使用
- */
- async check({ id, status, remark }) {
- const data = { status };
- if (status === '4') data['meta.state'] = 1;
- await this.model.updateOne({ _id: ObjectId(id) }, data);
- // 换成对应的状态码,record在下面
- return await this.record({ id, method: status, remark });
- }
- async record({ id, method, remark }) {
- let word = '';
- switch (`${method}`) {
- case 'create':
- word = '已申请';
- break;
- case 'update':
- word = '修改';
- break;
- case '1':
- word = '机构审核';
- break;
- case '-1':
- word = '机构审核未通过';
- break;
- case '2':
- word = '管理员评估';
- break;
- case '-2':
- word = '管理员评估未通过';
- break;
- case '3':
- word = '管理员评估通过,等待上传至国家库';
- break;
- case '4':
- word = '上传完成';
- break;
- default:
- word = '未知状态';
- break;
- }
- const data = await this.model.findById(id);
- if (!data) {
- throw new BusinessError(
- ErrorCode.DATA_NOT_EXIST,
- '添加记录----未找到数据'
- );
- }
- const obj = {
- time: moment().format('YYYY-MM-DD HH:mm:ss'),
- word,
- remark,
- };
- data.record.push(obj);
- const res = await data.save();
- this.toNotice(id, method);
- return res;
- }
- async toNotice(id, code) {
- const data = await this.model.findById(id);
- if (!data) return;
- const { user_id, admin_id, mechanism_id, status, name, apply_name } = data;
- const arr = [];
- let content = '';
- let to = '';
- switch (code) {
- case 'create':
- content = `${apply_name}提交了专利申请书(${name})的申报,请及时前往申请管理进行处理`;
- if (status === '1') {
- to = mechanism_id;
- } else {
- to = admin_id;
- }
- break;
- case 'update':
- content = `${apply_name}重新提交了专利申请书(${name})的申报,请及时前往申请管理进行处理`;
- if (status === '1') {
- to = mechanism_id;
- } else {
- to = admin_id;
- }
- break;
- case '-1':
- content = `您的专利申请书(${name})未通过机构的审核,请您及时修改,重新申请`;
- to = user_id;
- break;
- case '-2':
- content = `您的专利申请书(${name})未通过管理员的评估,请您及时修改,重新申请`;
- to = user_id;
- break;
- case '2':
- arr.push({
- content: `您的专利申请书(${name})已通过机构的审核,请您耐心等待管理员评估`,
- to: user_id,
- });
- arr.push({
- content: `${apply_name}的专利申请书(${name})已通过机构的审核,请您尽快对其进行评估`,
- to: admin_id,
- });
- break;
- case '3':
- content = `您的专利申请书(${name})已通过机构的审核,请您耐心等待上传至国家专利库中`;
- to = user_id;
- break;
- case '4':
- content = `您的专利申请书(${name})已上传至国家专利库中`;
- to = user_id;
- break;
- default:
- break;
- }
- if (code !== '2') {
- const obj = { to, content };
- await this.notice.create(obj);
- } else {
- await this.notice.insertMany(arr);
- }
- }
- // 导入
- async import({ uri }) {
- assert(uri, '未获取到文件地址');
- const file = await this.ctx.curl(`${this.domain}${uri}`);
- if (!(file && file.data)) {
- throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
- }
- const workbook = new Excel.Workbook();
- await workbook.xlsx.load(file.data);
- const sheet = workbook.getWorksheet(1);
- const arr = [];
- const allNotice = [];
- const sheetImageInfo = sheet.getImages();
- const imgids = _.compact(sheetImageInfo.map(i => {
- const { imageId, range } = i;
- const row = _.get(range, 'tl.nativeRow');
- if (row) return { row, imageId };
- }));
- sheet.eachRow((row, rindex) => {
- if (rindex !== 1) {
- // 组织数据,图片的索引和行索引不一致,准确的说是:图片索引比行索引少1
- // 原因:图片在工作簿中获取,按照1,2,3...顺序排序,但是行的第一行是表头(当前文件),所以当前行数需要减掉表头那一行
- const imgid = imgids.find(f => f.row === rindex - 1);
- let img_url;
- if (imgid) { img_url = this.turnImageToBase64(workbook.getImage(imgid.imageId)); }
- const create_number = row.getCell(2).value || undefined,
- create_date =
- moment(row.getCell(3).value).format('YYYY-MM-DD') || undefined,
- success_number = row.getCell(4).value || undefined,
- success_date =
- moment(row.getCell(5).value).format('YYYY-MM-DD') || undefined,
- inventor = row.getCell(6).value || undefined,
- agent = row.getCell(7).value || undefined,
- agent_personal = row.getCell(8).value || undefined,
- abstract = row.getCell(9).value || undefined,
- address = row.getCell(10).value || undefined,
- name = row.getCell(11).value || undefined,
- apply_personal = row.getCell(12).value || undefined,
- term = row.getCell(13).value || undefined,
- type = row.getCell(14).value || undefined,
- number = row.getCell(1).value || undefined;
- const obj = {
- create_number,
- create_date,
- success_number,
- success_date,
- inventor,
- agent,
- agent_personal,
- abstract,
- address,
- name,
- apply_personal,
- term,
- type,
- img_url,
- number,
- user_id: [],
- };
- // 此处添加判断条件,不限制则不需要加,直接放过即可
- const { result, notice } = this.tocheckData(obj);
- if (result) {
- arr.push(obj);
- } else {
- allNotice.push(notice);
- }
- }
- });
- if (allNotice.length > 0) return { data: allNotice, errcode: '1' };
- // 信息合格后,将发明人分出来,然后在个人/企业查出来,如果不是一个人,那就返回给前端,让前端选择后进行存储
- // 提取出所有人,分割,放到数组里(重不重复无所谓,这个地方无所谓);然后用人名去查出来所有的用户(企业/个人),如果有重复的,那就提出来返回给前端
- let nameList = [];
- for (const i of arr) {
- const { inventor } = i;
- const midList = inventor.split(/[,;/]/);
- nameList = [ ...nameList, ...midList ];
- }
- const l1 = await this.personalModel.find({ name: nameList });
- const l2 = await this.organizationModel.find({ name: nameList });
- // 查出来的所有人
- const nList = [ ...l1, ...l2 ];
- const groups = _.groupBy(nList, 'name');
- // 重复的名单
- const rList = {};
- for (const key in groups) {
- if (groups[key].length > 1) {
- rList[key] = groups[key];
- } else {
- // 剩下的都是1个的,直接找所有项目里有没有这个人,有就扔进去
- for (const i of arr) {
- const { inventor } = i;
- if (inventor.includes(key)) {
- const acct = _.head(groups[key]);
- if (acct) i.user_id.push(acct._id);
- }
- }
- }
- }
- // 将有这些重复人名的专利找到,返回前端
- const errorArr = [];
- const dealList = [];
- for (const i of arr) {
- const { inventor } = i;
- const key = Object.keys(rList).find(i => inventor.includes(i));
- if (key) errorArr.push({ ...i, nameList: rList[key] });
- else dealList.push(i);
- }
- // 不导入,缓存
- if (errorArr.length > 0) {
- const tempRes = await this.itemp.create({ data: dealList });
- const { _id } = tempRes;
- return { data: errorArr, errcode: '2', temp_id: _id };
- }
- await this.importAction(dealList);
- }
- // 继续导入
- async cacheImport({ data, temp_id }) {
- data = data.map(i => {
- const acct = i.nameList.find(f => f.is_select);
- if (acct) {
- const { _id } = acct;
- i.user_id.push(_id);
- }
- delete i.nameList;
- return i;
- });
- const tempList = await this.itemp.findById(temp_id);
- data = [ ...data, ...tempList.data ];
- await this.importAction(data);
- await this.itemp.deleteOne({ _id: temp_id });
- }
- async importAction(data) {
- await this.patent.insertMany(data);
- }
- /**
- * 检查数据是否没填 必填项
- * @param {Object} object 每行数据,已转换成model的字段名
- */
- tocheckData(object) {
- let result = true;
- const { number } = object;
- let notice;
- const arr = [
- { column: 'create_number', zh: '申请号' },
- { column: 'create_date', zh: '申请日' },
- { column: 'success_number', zh: '公开(公告)号' },
- { column: 'success_date', zh: '公开(公告)日' },
- { column: 'inventor', zh: '发明人' },
- { column: 'apply_personal', zh: '申请人' },
- { column: 'name', zh: '标题' },
- ];
- const word = [];
- for (const o of arr) {
- const { column, zh } = o;
- if (!_.get(object, column)) {
- result = false;
- word.push(`${zh}`);
- }
- }
- if (!result) {
- notice = `序号${number}缺少:${word.join(';')}`;
- }
- return { result, notice };
- }
- /**
- * 转换图片为base64
- * @param {Object} object excel获取的图片object
- * @property extension 后缀,文件类型
- * @property buffer 图片内容,不含头部信息的,
- */
- turnImageToBase64(object = {}) {
- const { extension, buffer } = object;
- if (extension && buffer) {
- const suffix = object.extension;
- const ib = object.buffer.toString('base64');
- const base64 = `data:image/${suffix};base64,${ib}`;
- return base64;
- }
- }
- async toExport({ id, ...others }) {
- const data = {
- title: '专利运营-专利导出',
- params: {
- project: 'market',
- service: 'patent.disclosure',
- method: 'exportAction',
- body: { ...others },
- },
- tenant: 'disclosure.export',
- user: id,
- };
- try {
- await this.ctx.service.util.httpUtil.cpost('/api/mission', 'mission', data);
- } catch (error) {
- console.log(error);
- throw new BusinessError(ErrorCode.SERVICE_FAULT, '任务创建失败');
- }
- }
- async exportAction({ missionid, ...body }) {
- const nowDate = new Date().getTime();
- const filename = `专利运营-专利导出-${nowDate}.xlsx`;
- const path = `${this.root_path}${this.excel_path}`;
- if (!path) {
- throw new BusinessError(ErrorCode.BUSINESS, '服务端没有设置存储路径');
- }
- if (!fs.existsSync(path)) {
- // 如果不存在文件夹,就创建
- fs.mkdirSync(path);
- }
- // 整理条件
- const total = await this.ctx.service.dock.patent.count(body);
- console.log(total);
- if (total === 0) {
- try {
- const data = {
- progress: 0,
- status: '3',
- remark: '未查到任何数据,无法导出',
- };
- await this.ctx.service.util.httpUtil.cpost(`/api/mission/update/${missionid}`, 'mission', data);
- } catch (error) {
- this.logger.error(`任务id:${missionid},更新失败操作 失败`);
- }
- return;
- }
- let skip = 0;
- let downloadPath;
- // 将数据分割,否则容易直接把js堆栈干满了,服务就炸了
- for (let i = 0; i < total; i = i + this.export_limit) {
- const list = await this.ctx.service.dock.patent.query(body, { skip, limit: this.export_limit });
- skip = skip + this.export_limit;
- downloadPath = await this.asyncExport(list, filename, path, downloadPath);
- try {
- const data = {
- progress: _.ceil((skip / total) * 100),
- status: '1',
- id: missionid,
- };
- this.ctx.service.util.httpUtil.cpost('/api/mission/progress', 'mission', data);
- } catch (error) {
- this.logger.error(`任务id:${missionid},进度更新失败`);
- }
- }
- try {
- const data = {
- progress: 100,
- status: '2',
- uri: downloadPath,
- };
- await this.ctx.service.util.httpUtil.cpost(`/api/mission/update/${missionid}`, 'mission', data);
- } catch (error) {
- this.logger.error(`任务id:${missionid},已完成更新失败`);
- }
- return downloadPath;
- }
- async asyncExport(list, filename, path, downloadPath) {
- const workbook = new Excel.Workbook();
- let sheet;
- if (!downloadPath) {
- sheet = workbook.addWorksheet('sheet');
- } else {
- const file = await this.ctx.curl(`${this.domain}${downloadPath}`);
- if (!(file && file.data)) {
- throw new BusinessError(ErrorCode.DATA_NOT_EXIST, '未找到指定文件');
- }
- await workbook.xlsx.load(file.data);
- sheet = workbook.getWorksheet('sheet');
- }
- const rowNumber = sheet.rowCount || 1;
- const meta = this.getHeader();
- sheet.columns = meta;
- sheet.addRows(list);
- for (let i = 0; i < list.length; i++) {
- const e = list[i];
- const { img_url, _id } = e;
- try {
- if (img_url) {
- const is_base64 = img_url.includes('base64,');
- let imgid;
- if (is_base64) {
- imgid = workbook.addImage({
- base64: img_url,
- extension: 'jpeg',
- });
- } else if (img_url.includes('/files')) {
- const prefix = `${this.root_path}`;
- const new_url = img_url.replace('/files', prefix);
- const suffix = Path.extname(img_url).substring(1);
- imgid = workbook.addImage({
- filename: new_url,
- extension: suffix,
- });
- } else {
- // 什么都不是,那就下一个
- continue;
- }
- sheet.addImage(imgid, {
- tl: { col: 13.2, row: i + rowNumber + 0.2 },
- br: { col: 14, row: i + rowNumber + 1 },
- });
- }
- } catch (error) {
- this.ctx.logger.error(`导出,id为:${_id}的图片处理出现错误!`);
- }
- }
- const filepath = `${path}${filename}`;
- if (list.length <= 0) return;
- await workbook.xlsx.writeFile(filepath);
- return `/files/excel/${filename}`;
- }
- getHeader() {
- const arr = [
- { header: '申请号', key: 'create_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '申请日', key: 'create_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '公开(公告)号', key: 'success_number', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '公开(公告)日', key: 'success_date', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '发明人', key: 'inventor', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '代理机构', key: 'agent', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '代理人', key: 'agent_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '摘要', key: 'abstract', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '发明人地址', key: 'address', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '标题', key: 'name', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '申请人', key: 'apply_personal', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '专利有效性', key: 'term', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '专利类型', key: 'type', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- { header: '首页附图(压缩图)', width: 30, style: { alignment: { wrapText: true, vertical: 'middle', horizontal: 'center' } } },
- ];
- return arr;
- }
- }
- module.exports = DisclosureService;
|