report_archive_controller.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. 'use strict';
  2. /**
  3. * Created by Tony on 2021/3/31.
  4. */
  5. const path = require('path');
  6. const uuidV1 = require('uuid').v1;
  7. const fs = require('fs');
  8. const MAX_ARCHIVE = 3;
  9. const tenderMenu = require('../../config/menu').tenderMenu;
  10. const measureType = require('../const/tender').measureType;
  11. const fsUtil = require('../public/js/fsUtil');
  12. const auditConst = require('../const/audit');
  13. const signConst = require('../const/sign');
  14. const shenpiConst = require('../const/shenpi');
  15. const accountGroup = require('../const/account_group').group;
  16. const sendToWormhole = require('stream-wormhole');
  17. module.exports = app => {
  18. class ReportArchiveController extends app.BaseController {
  19. /**
  20. * 获取审批界面所需的 原报、审批人数据等
  21. * @param ctx
  22. * @return {Promise<void>}
  23. * @private
  24. */
  25. async _getStageAuditViewData(ctx) {
  26. if (!ctx.stage) return;
  27. const times = ctx.stage.status === auditConst.stage.status.checkNo ? ctx.stage.times - 1 : ctx.stage.times;
  28. ctx.stage.user = await ctx.service.projectAccount.getAccountInfoById(ctx.stage.user_id);
  29. ctx.stage.auditHistory = [];
  30. if (times >= 1) {
  31. for (let i = 1; i <= times; i++) {
  32. ctx.stage.auditHistory.push(await ctx.service.stageAudit.getAuditors(ctx.stage.id, i));
  33. }
  34. }
  35. // 获取审批流程中左边列表
  36. ctx.stage.auditors2 = await ctx.service.stageAudit.getAuditGroupByListWithOwner(ctx.stage.id, times);
  37. if (ctx.stage.status === auditConst.stage.status.uncheck || ctx.stage.status === auditConst.stage.status.checkNo) {
  38. ctx.stage.auditorList = await ctx.service.stageAudit.getAuditors(ctx.stage.id, ctx.stage.times);
  39. }
  40. }
  41. async index(ctx) {
  42. await this._getStageAuditViewData(ctx);
  43. const tender = ctx.tender;
  44. const stage = ctx.stage;
  45. let stage_id = -1;
  46. let stage_order = -1;
  47. let stage_times = -1;
  48. let stage_status = -1;
  49. const treeNodes = await ctx.service.rptTreeNode.getNodesByProjectId([-1, tender.data.project_id]);
  50. const custTreeNodes = await ctx.service.rptTreeNodeCust.getCustFoldersByUserId(this.ctx.session.sessionUser.accountId);
  51. const stageList = await ctx.service.stage.getValidStagesShort(tender.id);
  52. const isAdmin = ctx.session.sessionUser.is_admin;
  53. //
  54. // 。。。
  55. let archiveList = [];
  56. let archiveEncryptionList = [];
  57. // console.log('tender.data.project_id: ' + tender.data.project_id);
  58. if (stage) {
  59. // console.log('ctx.stage.id: ' + ctx.stage.id);
  60. const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, ctx.stage.id);
  61. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  62. stage_id = stage.id;
  63. stage_order = stage.order;
  64. stage_times = stage.times;
  65. stage_status = stage.status;
  66. if (archives.length > 0) {
  67. archiveList = JSON.parse(archives[0].content);
  68. }
  69. if (archiveEncryptions.length > 0) {
  70. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  71. }
  72. } else if (stageList.length > 0 && stageList[0].status === auditConst.stage.status.checked) {
  73. // console.log('stageList[0].id: ' + stageList[0].id);
  74. let archives = [];
  75. for (let sidx = stageList.length - 1; sidx >= 0; sidx--) {
  76. if (stageList[sidx].status === 3) {
  77. archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[sidx].id);
  78. ctx.stage = stageList[sidx]; // 为了sub menu用
  79. break;
  80. }
  81. }
  82. ctx.stage = ctx.stage ? ctx.stage : stageList[stageList.length - 1];
  83. // const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[stageList.length - 1].id);
  84. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  85. // stage_id = stageList[0].id;
  86. // stage_order = stageList[0].order;
  87. // stage_times = stageList[0].times;
  88. // stage_status = stageList[0].status;
  89. if (archives && archives.length > 0) {
  90. archiveList = JSON.parse(archives[0].content);
  91. }
  92. if (archiveEncryptions && archiveEncryptions.length > 0) {
  93. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  94. }
  95. }
  96. let rpt_tpl_items = '{ customize: [], common: [] }';
  97. if (custTreeNodes.length > 0) {
  98. rpt_tpl_items = custTreeNodes[0].rpt_tpl_items;
  99. }
  100. // 获取用户权限
  101. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  102. // 获取所有项目参与者
  103. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  104. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  105. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  106. });
  107. const newAccountGroup = accountGroup.map((item, idx) => {
  108. const groupList = accountList.filter(item => item.account_group === idx);
  109. return { groupName: item, groupList };
  110. });
  111. //
  112. const renderData = {
  113. tender: tender.data,
  114. rpt_tpl_data: JSON.stringify(treeNodes),
  115. cust_tpl_data: rpt_tpl_items,
  116. project_id: tender.data.project_id,
  117. tender_id: tender.id,
  118. stg_id: stage_id,
  119. stg_order: stage_order,
  120. stg_times: stage_times,
  121. stg_status: stage_status,
  122. stage_list: stageList.length > 0 && stageList[0].status === auditConst.stage.status.checked ? JSON.stringify(stageList) : JSON.stringify([]),
  123. tenderMenu,
  124. measureType,
  125. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.report.main),
  126. stages: stageList,
  127. auditConst: auditConst.stage,
  128. archiveList,
  129. archiveEncryptionList,
  130. can_netcasign: false,
  131. ossPath: signConst.path.oss,
  132. shenpiConst,
  133. preUrl: '/tender/' + ctx.tender.id + '/measure/stage/' + ctx.params.order,
  134. authMobile: accountInfo.auth_mobile,
  135. accountGroup: newAccountGroup,
  136. accountList,
  137. isAdmin,
  138. };
  139. if (stage_id === -1) {
  140. await this.layout('report/index_archive.ejs', renderData, 'report/archive_popup.ejs');
  141. } else {
  142. await this.layout('report/index_archive.ejs', renderData, 'report/stage_archive_modal.ejs');
  143. }
  144. }
  145. async getReportArchive(ctx) {
  146. const params = JSON.parse(ctx.request.body.params);
  147. // ctx.body = await this._getReport(ctx, params);
  148. const archives = await ctx.service.rptArchive.getPrjStgArchive(params.prjId, params.stgId);
  149. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(params.prjId, params.stgId);
  150. let archiveList = [];
  151. let archiveEncryptionList = [];
  152. if (archives.length > 0) {
  153. archiveList = JSON.parse(archives[0].content);
  154. }
  155. if (archiveEncryptions.length > 0) {
  156. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  157. }
  158. const lastAuditor = await ctx.service.stageAudit.getLastestAuditor(params.stgId, params.stgTimes, auditConst.stage.status.checked);
  159. ctx.body = {
  160. data: archiveList,
  161. encryptionData: archiveEncryptionList,
  162. lastAuditor,
  163. };
  164. }
  165. async _updateReportArchiveAdhocInfo(ctx, params) {
  166. const userId = ctx.session.sessionUser.accountId;
  167. const prjId = params.prjId;
  168. const stgId = params.stgId;
  169. const rptId = params.rptId;
  170. const ttlPgs = params.ttlPgs;
  171. const uuid = params.uuid;
  172. const reportName = params.reportName;
  173. const reportAreas = params.signatureAreas;
  174. // 这里要更新zh_rpt_archive表的相关数据
  175. const orgArchiveList = await ctx.service.rptArchive.getPrjStgArchive(prjId, stgId);
  176. if (orgArchiveList.length > 0) {
  177. const contentArr = JSON.parse(orgArchiveList[0].content);
  178. for (const item of contentArr) {
  179. if (parseInt(item.rpt_id) === parseInt(rptId)) {
  180. for (const rptItem of item.items) {
  181. if (rptItem.uuid === uuid) {
  182. rptItem.uid = userId;
  183. rptItem.reportName = reportName;
  184. rptItem.ttl_pages = ttlPgs;
  185. rptItem.signature_area = reportAreas;
  186. break;
  187. }
  188. }
  189. break;
  190. }
  191. }
  192. const updatedRst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, contentArr);
  193. } else {
  194. // 正常情况下不可能的分支
  195. }
  196. }
  197. async addReportArchiveEncryption(ctx) {
  198. const params = JSON.parse(ctx.request.body.params);
  199. const prjId = params.prjId;
  200. const stgId = params.stgId;
  201. const rptId = params.rptId;
  202. const ttlPgs = params.ttlPgs;
  203. const uuid = params.uuid;
  204. const reportName = params.reportName;
  205. const userId = ctx.session.sessionUser.accountId;
  206. const content = params.content;
  207. const orgArchiveList = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(prjId, stgId);
  208. if (orgArchiveList.length > 0) {
  209. const contentArr = JSON.parse(orgArchiveList[0].content);
  210. let hasArchive = false;
  211. for (const item of contentArr) {
  212. if (item.rpt_id === rptId) {
  213. // 考虑到报表模板的稳定性,只保留一项来记录位置就足够了,都不考虑用uuid了
  214. if (item.uuid === uuid) {
  215. // 最后打脸了,还真的要考虑不同的uuid,不早说,TNND
  216. item.encryption = content;
  217. item.total_page = ttlPgs;
  218. item.user_id = userId;
  219. item.report_name = reportName;
  220. hasArchive = true;
  221. break;
  222. }
  223. }
  224. }
  225. if (!hasArchive) {
  226. // 表示有新的要加
  227. contentArr.push({ rpt_id: rptId, uuid, total_page: ttlPgs, encryption: content, user_id: userId, report_name: reportName });
  228. } else {
  229. //
  230. }
  231. const updatedRst = await ctx.service.rptArchiveEncryption.updateArchiveEncryption(orgArchiveList[0].id, prjId, stgId, contentArr);
  232. // console.log(updatedRst);
  233. ctx.body = { err: 0, msg: '', data: { addedRst: contentArr } };
  234. } else {
  235. // 需要增加
  236. const archiveArr = [];
  237. archiveArr.push({ rpt_id: rptId, uuid, total_page: ttlPgs, encryption: content, user_id: userId, report_name: reportName });
  238. const addedRst = await ctx.service.rptArchiveEncryption.createArchiveEncryption(prjId, stgId, archiveArr);
  239. // console.log(addedRst);
  240. ctx.body = { err: 0, msg: '', data: { addedRst: archiveArr } };
  241. }
  242. }
  243. async addReportArchive(ctx) {
  244. try {
  245. const stream = await ctx.getFileStream();
  246. const prjId = ctx.params.prjId;
  247. const stgId = ctx.params.stgId;
  248. const rptId = ctx.params.rptId;
  249. const newUuidName = uuidV1();
  250. const fileName = newUuidName + '.PDF';
  251. // console.log('adding fileName: ' + fileName);
  252. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, 'app', 'public/archive', fileName));
  253. const oss_result = await ctx.app.signPdfOss.put('archive/' + fileName, stream);
  254. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  255. throw '上传文件失败';
  256. }
  257. // const url = await ctx.oss.delete('archive/52d3e7f0-c7fb-11eb-b8c2-51b890b95d23.PDF');
  258. // console.log(url);
  259. // const flag = true;
  260. // if (flag) {
  261. // throw 'ok';
  262. // }
  263. const updateDate = new Date();
  264. const montStr = (updateDate.getMonth() + 1) < 10 ? ('0' + (updateDate.getMonth() + 1)) : (updateDate.getMonth() + 1);
  265. const dateStr = (updateDate.getDate()) < 10 ? ('0' + updateDate.getDate()) : (updateDate.getDate());
  266. let hrStr = '' + updateDate.getHours();
  267. if (hrStr.length === 1) hrStr = '0' + hrStr;
  268. let minStr = '' + updateDate.getMinutes();
  269. if (minStr.length === 1) minStr = '0' + minStr;
  270. let secStr = '' + updateDate.getSeconds();
  271. if (secStr.length === 1) secStr = '0' + secStr;
  272. // const dtStr = updateDate.getFullYear() + '-' + montStr + '-' + dateStr;
  273. const dtStr = `${updateDate.getFullYear()}-${montStr}-${dateStr} ${hrStr}:${minStr}:${secStr}`;
  274. const orgArchiveList = await ctx.service.rptArchive.getPrjStgArchive(prjId, stgId);
  275. if (orgArchiveList.length > 0) {
  276. const contentArr = JSON.parse(orgArchiveList[0].content);
  277. let hasArchive = false;
  278. for (const item of contentArr) {
  279. if (item.rpt_id === rptId) {
  280. hasArchive = true;
  281. if (item.items.length >= MAX_ARCHIVE) {
  282. // 超出界限,需要删除时间最旧的那个
  283. let rmIdx = 0;
  284. for (let idx = 1; idx < item.items.length; idx++) {
  285. if (item.items[rmIdx].updateDate_time < item.items[idx].updateDate_time) {
  286. rmIdx = idx;
  287. }
  288. }
  289. // 同时删除oss文件
  290. await ctx.app.signPdfOss.delete('archive/' + item.items[rmIdx].uuid + '.PDF');
  291. item.items.splice(rmIdx, 1);
  292. }
  293. const newItem = { uuid: newUuidName, updateDate_time: dtStr };
  294. item.items.push(newItem);
  295. break;
  296. }
  297. }
  298. if (!hasArchive) {
  299. // 表示有新的模板需要添加
  300. contentArr.push({ rpt_id: rptId, items: [{ uuid: newUuidName, updateDate_time: dtStr }] });
  301. }
  302. const updatedRst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, contentArr);
  303. // console.log(updatedRst);
  304. ctx.body = { err: 0, msg: newUuidName, data: { uuid: newUuidName, fileName, updateDate, addedRst: contentArr } };
  305. } else {
  306. // 需要增加
  307. const archiveArr = [];
  308. archiveArr.push({ rpt_id: rptId, items: [{ uuid: newUuidName, updateDate_time: dtStr }] });
  309. const addedRst = await ctx.service.rptArchive.createArchive(prjId, stgId, archiveArr);
  310. // console.log(addedRst);
  311. ctx.body = { err: 0, msg: newUuidName, data: { uuid: newUuidName, fileName, updateDate, addedRst: archiveArr } };
  312. }
  313. } catch (err) {
  314. this.log(err);
  315. ctx.body = { err: 1, msg: err.toString(), data: null };
  316. }
  317. }
  318. async updateReportArchiveEncryption(ctx) {
  319. // 在add方法中已经处理
  320. await this.addReportArchiveEncryption(ctx);
  321. }
  322. async updateReportArchive(ctx) {
  323. try {
  324. const stream = await ctx.getFileStream();
  325. const prjId = ctx.params.prjId;
  326. const stgId = ctx.params.stgId;
  327. const rptId = ctx.params.rptId;
  328. const orgUuidName = ctx.params.orgName;
  329. const fileName = orgUuidName + '.PDF';
  330. console.log('updating fileName: ' + fileName);
  331. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, 'app', 'public/archive', fileName));
  332. const oss_result = await ctx.app.signPdfOss.put('archive/' + fileName, stream);
  333. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  334. throw '上传文件失败';
  335. }
  336. // 判断是否存在已签名文档,存在则删除文档并删除签名记录
  337. const pdfMsg = await ctx.curl(signConst.path.oss + '/sign/' + orgUuidName + '.PDF');
  338. if (pdfMsg && pdfMsg.status === 200) {
  339. const oss_reuslt = await ctx.app.signPdfOss.delete('archive/sign/' + fileName);
  340. if (oss_reuslt && oss_reuslt.res && oss_reuslt.res.status === 204) {
  341. const delSign_result = await ctx.service.netcasignLog.removeSign(orgUuidName);
  342. } else {
  343. throw '删除已签文档失败';
  344. }
  345. }
  346. const updateDate = new Date();
  347. const montStr = (updateDate.getMonth() + 1) < 10 ? ('0' + (updateDate.getMonth() + 1)) : ((updateDate.getMonth() + 1));
  348. const dateStr = (updateDate.getDate()) < 10 ? ('0' + (updateDate.getDate())) : ((updateDate.getDate()));
  349. let hrStr = '' + updateDate.getHours();
  350. if (hrStr.length === 1) hrStr = '0' + hrStr;
  351. let minStr = '' + updateDate.getMinutes();
  352. if (minStr.length === 1) minStr = '0' + minStr;
  353. let secStr = '' + updateDate.getSeconds();
  354. if (secStr.length === 1) secStr = '0' + secStr;
  355. // const dtStr = updateDate.getFullYear() + '-' + montStr + '-' + dateStr;
  356. const dtStr = `${updateDate.getFullYear()}-${montStr}-${dateStr} ${hrStr}:${minStr}:${secStr}`;
  357. const orgArchiveList = await ctx.service.rptArchive.getPrjStgArchive(prjId, stgId);
  358. if (orgArchiveList.length > 0) {
  359. const contentArr = JSON.parse(orgArchiveList[0].content);
  360. for (const item of contentArr) {
  361. if (item.rpt_id === rptId) {
  362. if (item.items && item.items.length > 0) {
  363. for (const subItem of item.items) {
  364. if (subItem.uuid === orgUuidName) {
  365. subItem.updateDate_time = dtStr;
  366. break;
  367. }
  368. }
  369. } else {
  370. item.items = [{ uuid: orgUuidName, updateDate_time: dtStr }];
  371. }
  372. break;
  373. }
  374. }
  375. const updatedRst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, contentArr);
  376. // console.log(updatedRst);
  377. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updateDate, updatedRst: contentArr } };
  378. } else {
  379. // 需要增加
  380. const archiveArr = [];
  381. archiveArr.push({ rpt_id: rptId, items: [{ uuid: orgUuidName, updateDate_time: dtStr }] });
  382. const updatedRst = await ctx.service.rptArchive.createArchive(prjId, stgId, archiveArr);
  383. // console.log(updatedRst);
  384. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updateDate, updatedRst: archiveArr } };
  385. }
  386. } catch (err) {
  387. this.log(err);
  388. ctx.body = { err: 1, msg: err.toString(), data: null };
  389. }
  390. }
  391. async _removeReportArchiveEncryption(ctx) {
  392. let rst = null;
  393. try {
  394. const prjId = ctx.params.prjId;
  395. const stgId = ctx.params.stgId;
  396. const rptId = parseInt(ctx.params.rptId);
  397. const uuid = ctx.params.orgName;
  398. const orgArchiveList = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(prjId, stgId);
  399. if (orgArchiveList.length > 0) {
  400. const contentArr = JSON.parse(orgArchiveList[0].content);
  401. for (let idx = contentArr.length - 1; idx >= 0; idx--) {
  402. if (contentArr[idx].rpt_id === rptId && contentArr[idx].uuid === uuid) {
  403. contentArr.splice(idx, 1);
  404. break;
  405. }
  406. }
  407. // const updatedRst = await ctx.service.rptArchive.updateArchive(prjId, stgId, contentArr);
  408. rst = await ctx.service.rptArchiveEncryption.updateArchiveEncryption(orgArchiveList[0].id, prjId, stgId, contentArr);
  409. }
  410. } catch (err) {
  411. this.log(err);
  412. }
  413. return rst;
  414. }
  415. async removeReportArchiveEncryption(ctx) {
  416. try {
  417. const rst = await this._removeReportArchiveEncryption(ctx);
  418. if (rst) {
  419. ctx.body = { err: 0, msg: '', data: { updatedRst: rst } };
  420. } else {
  421. ctx.body = { err: 0, msg: '', data: { updatedRst: null } };
  422. }
  423. } catch (err) {
  424. this.log(err);
  425. ctx.body = { err: 1, msg: err.toString(), data: null };
  426. }
  427. }
  428. async _removeReportArchive(ctx) {
  429. let rst = null;
  430. try {
  431. const prjId = ctx.params.prjId;
  432. const stgId = ctx.params.stgId;
  433. const rptId = ctx.params.rptId;
  434. const orgUuidName = ctx.params.orgName;
  435. // const fileName = orgUuidName + '.PDF';
  436. const orgArchiveList = await ctx.service.rptArchive.getPrjStgArchive(prjId, stgId);
  437. if (orgArchiveList.length > 0) {
  438. const contentArr = JSON.parse(orgArchiveList[0].content);
  439. for (let idx = contentArr.length - 1; idx >= 0; idx--) {
  440. const item = contentArr[idx];
  441. if (item.rpt_id === rptId) {
  442. if (item.items && item.items.length > 0) {
  443. for (const subIdx in item.items) {
  444. if (item.items[subIdx].uuid === orgUuidName) {
  445. item.items.splice(subIdx, 1);
  446. break;
  447. }
  448. }
  449. if (item.items.length === 0) {
  450. contentArr.splice(idx, 1);
  451. }
  452. }
  453. break;
  454. }
  455. }
  456. rst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, contentArr);
  457. }
  458. } catch (err) {
  459. this.log(err);
  460. }
  461. return rst;
  462. }
  463. async removeReportArchive(ctx) {
  464. try {
  465. const orgUuidName = ctx.params.orgName;
  466. const fileName = orgUuidName + '.PDF';
  467. // console.log(ctx.params);
  468. console.log('removing fileName: ' + fileName);
  469. // const fullName = path.join(this.app.baseDir, 'app', 'public/archive', fileName);
  470. const oss_sign_result = await ctx.app.signPdfOss.delete(`archive/sign/${fileName}`);
  471. if (oss_sign_result && oss_sign_result.res && oss_sign_result.res.status === 204) {
  472. // console.log('删除归档的签名信息成功!');
  473. const oss_result = await ctx.app.signPdfOss.delete(`archive/${fileName}`);
  474. if (!(oss_result && oss_result.res.status === 204)) {
  475. throw '删除归档文件失败';
  476. }
  477. } else {
  478. throw '删除归档签名文件失败';
  479. }
  480. // 还有加密签名信息
  481. const archiveSignRemovedRst = await this._removeReportArchiveEncryption(ctx);
  482. // console.log(archiveSignRemovedRst);
  483. const archiveRemovedRst = await this._removeReportArchive(ctx);
  484. if (archiveRemovedRst) {
  485. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updatedRst: archiveRemovedRst } };
  486. } else {
  487. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updatedRst: null } };
  488. }
  489. } catch (err) {
  490. this.log(err);
  491. ctx.body = { err: 1, msg: err.toString(), data: null };
  492. }
  493. }
  494. async addMultiReportArchive(ctx, params) {
  495. // 暂时不支持
  496. }
  497. async getArchivedFileByUUID(ctx) {
  498. // console.log('downloading : ' + ctx.params.uuid);
  499. const uuid = ctx.params.uuid;
  500. const rptName = ctx.params.rptName;
  501. const suffix = '.PDF';
  502. try {
  503. const rptNameURI = encodeURI(rptName);
  504. const filePath = this.app.baseDir + '/app/public/archive/';
  505. // console.log('filePath: ' + filePath);
  506. // await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  507. ctx.set({
  508. 'Content-Type': 'application/vnd.openxmlformats',
  509. 'Content-Disposition': 'attachment; filename="' + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix,
  510. });
  511. ctx.body = await fs.readFileSync(filePath + uuid + suffix);
  512. } catch (e) {
  513. console.log(e);
  514. }
  515. }
  516. async pdfShow(ctx) {
  517. // const renderData = {
  518. // can_netcasign: ctx.session.sessionProject.page_show.openNetCaSign === 1,
  519. // };
  520. await ctx.render('report/archive_pdf.ejs');
  521. }
  522. /*
  523. * 网证通电子签名页,(和归档报表页高度相似)
  524. */
  525. async signReport(ctx) {
  526. const tender = ctx.tender;
  527. const stage = ctx.stage;
  528. let stage_id = -1;
  529. let stage_order = -1;
  530. let stage_times = -1;
  531. let stage_status = -1;
  532. const treeNodes = await ctx.service.rptTreeNode.getNodesByProjectId([-1, tender.data.project_id]);
  533. const custTreeNodes = await ctx.service.rptTreeNodeCust.getCustFoldersByUserId(this.ctx.session.sessionUser.accountId);
  534. const stageList = await ctx.service.stage.getValidStagesShort(tender.id);
  535. //
  536. // 。。。
  537. let archiveList = [];
  538. let archiveEncryptionList = [];
  539. // console.log('tender.data.project_id: ' + tender.data.project_id);
  540. if (stage) {
  541. // console.log('ctx.stage.id: ' + ctx.stage.id);
  542. const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, ctx.stage.id);
  543. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  544. stage_id = stage.id;
  545. stage_order = stage.order;
  546. stage_times = stage.times;
  547. stage_status = stage.status;
  548. if (archives.length > 0) {
  549. archiveList = JSON.parse(archives[0].content);
  550. }
  551. console.log('2:', archiveEncryptions, ctx.stage.id);
  552. if (archiveEncryptions.length > 0) {
  553. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  554. }
  555. } else if (stageList.length > 0 && stageList[0].status === auditConst.stage.status.checked) {
  556. // console.log('stageList[0].id: ' + stageList[0].id);
  557. // const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[stageList.length - 1].id);
  558. let archives = [];
  559. for (let sidx = stageList.length - 1; sidx >= 0; sidx--) {
  560. if (stageList[sidx].status === 3) {
  561. archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[sidx].id);
  562. ctx.stage = stageList[sidx]; // 为了sub menu用
  563. break;
  564. }
  565. }
  566. ctx.stage = ctx.stage ? ctx.stage : stageList[stageList.length - 1];
  567. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  568. // stage_id = stageList[0].id;
  569. // stage_order = stageList[0].order;
  570. // stage_times = stageList[0].times;
  571. // stage_status = stageList[0].status;
  572. if (archives && archives.length > 0) {
  573. archiveList = JSON.parse(archives[0].content);
  574. }
  575. if (archiveEncryptions && archiveEncryptions.length > 0) {
  576. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  577. }
  578. }
  579. let rpt_tpl_items = '{ customize: [], common: [] }';
  580. if (custTreeNodes.length > 0) {
  581. rpt_tpl_items = custTreeNodes[0].rpt_tpl_items;
  582. }
  583. // 获取ukey绑定数据
  584. const netcaSignData = await ctx.service.netcasign.getDataByCondition({ uid: ctx.session.sessionUser.accountId });
  585. // 获取已签名数据
  586. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  587. const renderData = {
  588. tender: tender.data,
  589. rpt_tpl_data: JSON.stringify(treeNodes),
  590. cust_tpl_data: rpt_tpl_items,
  591. project_id: tender.data.project_id,
  592. tender_id: tender.id,
  593. stg_id: stage_id,
  594. stg_order: stage_order,
  595. stg_times: stage_times,
  596. stg_status: stage_status,
  597. stage_list: JSON.stringify(stageList),
  598. tenderMenu,
  599. measureType,
  600. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.report.main),
  601. stages: stageList,
  602. auditConst: auditConst.stage,
  603. archiveList,
  604. archiveEncryptionList,
  605. netcaSignData,
  606. can_netcasign: ctx.session.sessionProject.page_show.openNetCaSign === 1,
  607. ossPath: signConst.path.oss,
  608. signLogList,
  609. };
  610. await this.layout('report/index_sign.ejs', renderData, 'report/index_sign_modal.ejs');
  611. }
  612. /**
  613. * 网证通电子签名接口
  614. *
  615. * @param {object} ctx - egg全局变量
  616. * @return {void}
  617. */
  618. async signPost(ctx) {
  619. const response = {
  620. err: 0,
  621. msg: '',
  622. };
  623. try {
  624. const data = JSON.parse(ctx.request.body.data);
  625. let signData;
  626. const netcaSignApi = signConst.path.api;
  627. switch (data.type) {
  628. case 'getPdfBase64':
  629. const pdfResult = await ctx.app.signPdfOss.get(data.path);
  630. if (pdfResult.res.status !== 200) {
  631. throw '该文件不存在';
  632. }
  633. response.data = Buffer.from(pdfResult.content, 'binary').toString('base64');
  634. break;
  635. case 'pdfIsExist':
  636. const pdfMsg = await ctx.app.signPdfOss.head('archive/sign/' + data.uuid + '.PDF');
  637. response.data = pdfMsg.res.status === 200;
  638. break;
  639. // 获取摘要值
  640. case 'assemblyDigest':
  641. const postData = {
  642. requestJson: JSON.stringify(data.requestJson),
  643. };
  644. const result = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyDigest', postData, 'POST');
  645. response.data = result;
  646. break;
  647. // 生成签名pdf
  648. case 'assemblyPdf':
  649. const postData2 = {
  650. requestJson: JSON.stringify(data.requestJson),
  651. };
  652. const result3 = await this.roundNetcaSign(ctx, postData2);
  653. // const result2 = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyPdf', postData2, 'POST');
  654. // 上传到oss
  655. // console.log(result3);
  656. if (result3.code === 0) {
  657. // const result3 = await ctx.helper.sendMoreRequest(netcaSignApi + result2.data);
  658. const oss_result = await ctx.app.signPdfOss.put('archive/sign/' + data.requestJson.fileName + '.PDF', result3.data);
  659. if (oss_result && oss_result.res && oss_result.res.status === 200) {
  660. if (data.end) {
  661. const versionId = oss_result.res.headers['x-oss-version-id'];
  662. // 记录签名和保存
  663. await ctx.service.netcasignLog.add(data.requestJson.fileName, data.role, ctx.session.sessionUser.accountId, versionId);
  664. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  665. response.data = signLogList;
  666. } else {
  667. // next page
  668. }
  669. } else {
  670. throw '上传文件失败';
  671. }
  672. } else {
  673. throw result3.msg;
  674. }
  675. break;
  676. // 移除签名和已签移除pdf
  677. case 'removeSign':
  678. const oss_reuslt = await ctx.app.signPdfOss.delete('archive/sign/' + data.uuid + '.PDF');
  679. if (oss_reuslt && oss_reuslt.res && oss_reuslt.res.status === 204) {
  680. const delSign_result = await ctx.service.netcasignLog.removeSign(data.uuid);
  681. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  682. response.data = signLogList;
  683. } else {
  684. throw '删除文件失败';
  685. }
  686. break;
  687. default:throw '参数有误';
  688. }
  689. } catch (error) {
  690. response.err = 1;
  691. response.msg = error.toString();
  692. const data = JSON.parse(ctx.request.body.data);
  693. if (data && data.type === 'pdfIsExist') {
  694. response.err = 0;
  695. response.data = false;
  696. }
  697. }
  698. ctx.body = response;
  699. }
  700. /**
  701. * 网证通电子签名报表上传
  702. *
  703. * @param {object} ctx - egg全局变量
  704. * @return {void}
  705. */
  706. async signFile(ctx) {
  707. const stream = await ctx.getFileStream();
  708. try {
  709. const uuid = stream.fields.uuid;
  710. const role = stream.fields.role;
  711. const oss_result = await ctx.app.signPdfOss.put('archive/sign/' + uuid + '.PDF', stream);
  712. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  713. throw '上传文件失败';
  714. }
  715. const versionId = oss_result.res.headers['x-oss-version-id'];
  716. // 记录签名和保存
  717. await ctx.service.netcasignLog.add(uuid, role, ctx.session.sessionUser.accountId, versionId);
  718. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  719. ctx.body = { err: 0, msg: '', data: signLogList };
  720. } catch (err) {
  721. // 必须将上传的文件流消费掉,要不然浏览器响应会卡死
  722. await sendToWormhole(stream);
  723. this.log(err);
  724. ctx.body = { err: 1, msg: err.toString(), data: null };
  725. }
  726. }
  727. async roundNetcaSign(ctx, postData2, round = 3) {
  728. let response = {
  729. code: 0,
  730. data: '',
  731. };
  732. // 无法获取到result3,因为result2生成的pdf已损坏,请重复获取result2,直到获取成功或尝试3次失败后报错为止
  733. try {
  734. const netcaSignApi = signConst.path.api;
  735. const result2 = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyPdf', postData2, 'POST');
  736. if (result2.code === 0) {
  737. const result3 = await ctx.curl(netcaSignApi + result2.data, {
  738. timeout: 300000, // 超时 5分钟中
  739. });
  740. if (result3) {
  741. response.data = result3.data;
  742. } else {
  743. if (round > 0) {
  744. round = round - 1;
  745. response = await this.roundNetcaSign(ctx, postData2, round);
  746. } else {
  747. throw 'pdf获取失败,网证通接口无法生成pdf';
  748. }
  749. }
  750. }
  751. } catch (error) {
  752. response.code = 1;
  753. response.msg = error;
  754. }
  755. return response;
  756. }
  757. }
  758. return ReportArchiveController;
  759. };