report_archive_controller.js 40 KB

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