report_archive_controller.js 41 KB

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