report_archive_controller.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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 tdId = params.tenderId;
  194. const bzId = params.businessId;
  195. const rptId = params.rptId;
  196. const ttlPgs = params.ttlPgs;
  197. const uuid = params.uuid;
  198. const removeUuid = params.removeUuid;
  199. const childUuids = params.childUuids;
  200. const splitArcPages = params.splitArcPages;
  201. const reportName = params.reportName;
  202. const userId = ctx.session.sessionUser.accountId;
  203. const content = params.content;
  204. const orgArchiveList = await ctx.service.rptArchiveEncryption.getArchiveEncryptionByBzId(prjId, stgId, bzId);
  205. if (orgArchiveList.length > 0) {
  206. const contentArr = JSON.parse(orgArchiveList[0].content);
  207. let hasArchive = false;
  208. for (const item of contentArr) {
  209. if (item.rpt_id === rptId) {
  210. // 考虑到报表模板的稳定性,只保留一项来记录位置就足够了,都不考虑用uuid了
  211. if (item.uuid === uuid) {
  212. // 最后打脸了,还真的要考虑不同的uuid,不早说,TNND
  213. item.encryption = content;
  214. item.total_page = ttlPgs;
  215. item.user_id = userId;
  216. item.report_name = reportName;
  217. item.childUuids = childUuids;
  218. item.splitArcPages = splitArcPages;
  219. hasArchive = true;
  220. break;
  221. }
  222. }
  223. }
  224. if (!hasArchive) {
  225. // 表示有新的要加, 有加有减
  226. for (let idx = contentArr.length - 1; idx >= 0; idx--) {
  227. if (contentArr[idx].uuid === removeUuid) {
  228. contentArr.splice(idx, 1);
  229. break;
  230. }
  231. }
  232. contentArr.push({ rpt_id: rptId, uuid, total_page: ttlPgs, encryption: content, user_id: userId, report_name: reportName, childUuids, splitArcPages });
  233. } else {
  234. //
  235. }
  236. const updatedRst = await ctx.service.rptArchiveEncryption.updateArchiveEncryption(orgArchiveList[0].id, prjId, stgId, tdId, bzId, contentArr);
  237. // console.log(updatedRst);
  238. ctx.body = { err: 0, msg: '', data: { addedRst: contentArr } };
  239. } else {
  240. // 需要增加
  241. const archiveArr = [];
  242. archiveArr.push({ rpt_id: rptId, uuid, total_page: ttlPgs, encryption: content, user_id: userId, report_name: reportName, childUuids, splitArcPages });
  243. const addedRst = await ctx.service.rptArchiveEncryption.createArchiveEncryption(prjId, stgId, tdId, bzId, archiveArr);
  244. // console.log(addedRst);
  245. ctx.body = { err: 0, msg: '', data: { addedRst: archiveArr } };
  246. }
  247. }
  248. async _updateArchiveCommon(ctx, prjId, stgId, bzId, tdId, rptId, parentUuidName, childUuids) {
  249. const updateDate = new Date();
  250. const montStr = (updateDate.getMonth() + 1) < 10 ? ('0' + (updateDate.getMonth() + 1)) : (updateDate.getMonth() + 1);
  251. const dateStr = (updateDate.getDate()) < 10 ? ('0' + updateDate.getDate()) : (updateDate.getDate());
  252. let hrStr = '' + updateDate.getHours();
  253. if (hrStr.length === 1) hrStr = '0' + hrStr;
  254. let minStr = '' + updateDate.getMinutes();
  255. if (minStr.length === 1) minStr = '0' + minStr;
  256. let secStr = '' + updateDate.getSeconds();
  257. if (secStr.length === 1) secStr = '0' + secStr;
  258. const dtStr = `${updateDate.getFullYear()}-${montStr}-${dateStr} ${hrStr}:${minStr}:${secStr}`;
  259. let rst = null;
  260. const fileName = parentUuidName + '.PDF';
  261. let removeUuid = ''; // 因这里把增删功能做在一起,有可能要删除一个旧的uuid,需要返回,给加密处理用
  262. const orgArchiveList = await ctx.service.rptArchive.getArchiveByBzId(prjId, stgId, bzId);
  263. if (orgArchiveList.length > 0) {
  264. const contentArr = JSON.parse(orgArchiveList[0].content);
  265. let hasArchive = false;
  266. for (const item of contentArr) {
  267. if (item.rpt_id === rptId) {
  268. hasArchive = true;
  269. let updateRmIdx = -1;
  270. for (let idx = 0; idx < item.items.length; idx++) {
  271. if (parentUuidName === item.items[idx].uuid) {
  272. // 这里的判断是否是update archive逻辑(是否存在相同uuid的item)
  273. updateRmIdx = idx;
  274. break;
  275. }
  276. }
  277. if (updateRmIdx < 0 && item.items.length >= MAX_ARCHIVE) {
  278. updateRmIdx = 0;
  279. for (let idx = 1; idx < item.items.length; idx++) {
  280. if (item.items[updateRmIdx].updateDate_time > item.items[idx].updateDate_time) {
  281. updateRmIdx = idx;
  282. }
  283. }
  284. }
  285. if (updateRmIdx >= 0) {
  286. // 删除oss文件
  287. removeUuid = item.items[updateRmIdx].uuid;
  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. let uuid = '';
  293. if (typeof childUuid === 'string') {
  294. uuid = childUuid;
  295. } else {
  296. uuid = childUuid.uuid;
  297. }
  298. await ctx.app.signPdfOss.delete(`archive/${uuid}.PDF`);
  299. }
  300. }
  301. item.items.splice(updateRmIdx, 1);
  302. }
  303. const newItem = { uuid: parentUuidName, updateDate_time: dtStr, childUuids };
  304. item.items.push(newItem);
  305. break;
  306. }
  307. }
  308. if (!hasArchive) {
  309. // 表示有新的模板需要添加
  310. contentArr.push({ rpt_id: rptId, items: [{ uuid: parentUuidName, updateDate_time: dtStr, childUuids }] });
  311. }
  312. const updatedRst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, tdId, bzId, contentArr);
  313. // console.log(updatedRst);
  314. rst = { err: 0, msg: parentUuidName, data: { uuid: parentUuidName, childUuids, removeUuid, fileName, updateDate, updatedRst: contentArr } };
  315. } else {
  316. // 需要增加
  317. const archiveArr = [];
  318. archiveArr.push({ rpt_id: rptId, items: [{ uuid: parentUuidName, updateDate_time: dtStr, childUuids }] });
  319. const addedRst = await ctx.service.rptArchive.createArchive(prjId, stgId, tdId, bzId, archiveArr);
  320. rst = { err: 0, msg: parentUuidName, data: { uuid: parentUuidName, childUuids, removeUuid, fileName, updateDate, updatedRst: archiveArr } };
  321. }
  322. return rst;
  323. }
  324. async addParentChildrenArchiveReports(ctx) {
  325. // 接收多个子母PDF
  326. let stream;
  327. try {
  328. const prjId = ctx.params.prjId;
  329. const stgId = ctx.params.stgId;
  330. const bzId = ctx.params.bzId;
  331. const tdId = ctx.params.tdId;
  332. const rptId = ctx.params.rptId;
  333. // const childAmt = parseInt(ctx.params.childAmt); // 子分页数量
  334. const childInfo = ctx.params.splitInfo.split(';'); // 这个参数带比较多的信息,包含分割指标的:1. 名称 2. ID 3. 内容
  335. const splitArcPages = JSON.parse(childInfo[0]);
  336. // console.log(splitArcPages);
  337. const childAmt = splitArcPages.length;
  338. const splitFieldObj = JSON.parse(childInfo[1]);
  339. const ttlPages = parseInt(childInfo[2]); // 总页数
  340. // console.log(splitFieldObj);
  341. const parentUuid = uuidV1();
  342. const childUuids = [];
  343. // const newUuidName = uuidV1();
  344. const parts = ctx.multipart({ autoFields: true });
  345. stream = await parts();
  346. let index = 0;
  347. while (stream !== undefined) {
  348. /*
  349. // 测试保存文件
  350. await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, 'app/public/upload/', stream.filename));
  351. await sendToWormhole(stream);
  352. //*/
  353. let fileName = parentUuid + '.PDF';
  354. if (index > 0) {
  355. const cUuid = uuidV1();
  356. const startPage = splitArcPages[index - 1];
  357. // const endPage = splitArcPages[index - 1];
  358. let endPage = ttlPages;
  359. if (index < splitArcPages.length) {
  360. endPage = splitArcPages[index] - 1;
  361. }
  362. childUuids.push({ uuid: cUuid, totalPages: (endPage - startPage + 1), startPage, endPage, splitKeyValue: splitFieldObj.splitPageValues[index - 1] });
  363. fileName = cUuid + '.PDF';
  364. }
  365. const oss_result = await ctx.app.signPdfOss.put('archive/' + fileName, stream);
  366. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  367. throw '上传文件失败';
  368. }
  369. await sendToWormhole(stream);
  370. ++index;
  371. if (index <= childAmt) {
  372. stream = await parts();
  373. } else {
  374. stream = undefined;
  375. }
  376. // stream = await parts();
  377. }
  378. const body = await this._updateArchiveCommon(ctx, prjId, stgId, bzId, tdId, rptId, parentUuid, childUuids);
  379. ctx.body = body;
  380. } catch (error) {
  381. ctx.helper.log(error);
  382. // 失败需要消耗掉stream 以防卡死
  383. if (stream) {
  384. await sendToWormhole(stream);
  385. }
  386. ctx.body = this.ajaxErrorBody(error, '上传附件失败,请重试');
  387. }
  388. }
  389. async addReportArchive(ctx) {
  390. try {
  391. const stream = await ctx.getFileStream();
  392. const prjId = ctx.params.prjId;
  393. const stgId = ctx.params.stgId;
  394. const bzId = ctx.params.bzId;
  395. const tdId = ctx.params.tdId;
  396. const rptId = ctx.params.rptId;
  397. const newUuidName = uuidV1();
  398. const fileName = newUuidName + '.PDF';
  399. const oss_result = await ctx.app.signPdfOss.put('archive/' + fileName, stream);
  400. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  401. throw '上传文件失败';
  402. }
  403. const body = await this._updateArchiveCommon(ctx, prjId, stgId, bzId, tdId, rptId, newUuidName, []);
  404. // console.log(body);
  405. ctx.body = body;
  406. } catch (err) {
  407. this.log(err);
  408. ctx.body = { err: 1, msg: err.toString(), data: null };
  409. }
  410. }
  411. async updateReportArchiveEncryption(ctx) {
  412. // 在add方法中已经处理
  413. await this.addReportArchiveEncryption(ctx);
  414. }
  415. async updateReportArchive(ctx) {
  416. try {
  417. const stream = await ctx.getFileStream();
  418. const prjId = ctx.params.prjId;
  419. const stgId = ctx.params.stgId;
  420. const bzId = ctx.params.bzId;
  421. const tdId = ctx.params.tdId;
  422. const rptId = ctx.params.rptId;
  423. const orgUuidName = ctx.params.orgName;
  424. const orgFileName = orgUuidName + '.PDF';
  425. const newUuidName = uuidV1();
  426. const fileName = newUuidName + '.PDF'; // 要用新的uuid!!!
  427. console.log('updating fileName: ' + fileName);
  428. // await ctx.helper.saveStreamFile(stream, path.join(this.app.baseDir, 'app', 'public/archive', fileName));
  429. const oss_result = await ctx.app.signPdfOss.put('archive/' + fileName, stream);
  430. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  431. throw '上传文件失败';
  432. }
  433. // 判断是否存在已签名文档,存在则删除文档并删除签名记录
  434. const pdfMsg = await ctx.curl(signConst.path.oss + '/sign/' + orgUuidName + '.PDF');
  435. if (pdfMsg && pdfMsg.status === 200) {
  436. const oss_reuslt = await ctx.app.signPdfOss.delete('archive/sign/' + orgFileName);
  437. if (oss_reuslt && oss_reuslt.res && oss_reuslt.res.status === 204) {
  438. const delSign_result = await ctx.service.netcasignLog.removeSign(orgUuidName);
  439. } else {
  440. throw '删除已签文档失败';
  441. }
  442. }
  443. const body = await this._updateArchiveCommon(ctx, prjId, stgId, bzId, tdId, rptId, newUuidName, []); // 只管用新的uuid,此方法中会自动删除最旧的那个记录及相关PDF文档
  444. ctx.body = body;
  445. } catch (err) {
  446. this.log(err);
  447. ctx.body = { err: 1, msg: err.toString(), data: null };
  448. }
  449. }
  450. async _removeReportArchiveEncryption(ctx) {
  451. let rst = null;
  452. try {
  453. const prjId = ctx.params.prjId;
  454. const stgId = ctx.params.stgId;
  455. const bzId = ctx.params.bzId;
  456. const rptId = parseInt(ctx.params.rptId);
  457. const uuid = ctx.params.orgName;
  458. const orgArchiveList = await ctx.service.rptArchiveEncryption.getArchiveEncryptionByBzId(prjId, stgId, bzId);
  459. if (orgArchiveList.length > 0) {
  460. const contentArr = JSON.parse(orgArchiveList[0].content);
  461. for (let idx = contentArr.length - 1; idx >= 0; idx--) {
  462. if (contentArr[idx].rpt_id === rptId && contentArr[idx].uuid === uuid) {
  463. contentArr.splice(idx, 1);
  464. break;
  465. }
  466. }
  467. rst = await ctx.service.rptArchiveEncryption.updateArchiveEncryption(orgArchiveList[0].id, prjId, stgId, orgArchiveList[0].tender_id, bzId, contentArr);
  468. }
  469. } catch (err) {
  470. this.log(err);
  471. }
  472. return rst;
  473. }
  474. async removeReportArchiveEncryption(ctx) {
  475. try {
  476. const rst = await this._removeReportArchiveEncryption(ctx);
  477. if (rst) {
  478. ctx.body = { err: 0, msg: '', data: { updatedRst: rst } };
  479. } else {
  480. ctx.body = { err: 0, msg: '', data: { updatedRst: null } };
  481. }
  482. } catch (err) {
  483. this.log(err);
  484. ctx.body = { err: 1, msg: err.toString(), data: null };
  485. }
  486. }
  487. async _removeReportArchive(ctx) {
  488. let rst = null;
  489. try {
  490. const prjId = ctx.params.prjId;
  491. const stgId = ctx.params.stgId;
  492. const rptId = ctx.params.rptId;
  493. const bzId = ctx.params.bzId;
  494. const orgUuidName = ctx.params.orgName;
  495. // const fileName = orgUuidName + '.PDF';
  496. const orgArchiveList = await ctx.service.rptArchive.getArchiveByBzId(prjId, stgId, bzId);
  497. if (orgArchiveList.length > 0) {
  498. const contentArr = JSON.parse(orgArchiveList[0].content);
  499. for (let idx = contentArr.length - 1; idx >= 0; idx--) {
  500. const item = contentArr[idx];
  501. if (item.rpt_id === rptId) {
  502. if (item.items && item.items.length > 0) {
  503. for (const subIdx in item.items) {
  504. if (item.items[subIdx].uuid === orgUuidName) {
  505. if (item.items[subIdx].childUuids && item.items[subIdx].childUuids.length > 0) {
  506. // 如果有子分页,也得删除!
  507. for (const childUuid of item.items[subIdx].childUuids) {
  508. let childUuidName = '';
  509. if (typeof childUuid === 'string') {
  510. childUuidName = childUuid;
  511. } else {
  512. childUuidName = childUuid.uuid;
  513. }
  514. if (!childUuidName.includes('.PDF')) childUuidName = childUuidName + '.PDF';
  515. await ctx.app.signPdfOss.delete(`archive/${childUuidName}`);
  516. }
  517. }
  518. item.items.splice(subIdx, 1);
  519. break;
  520. }
  521. }
  522. if (item.items.length === 0) {
  523. contentArr.splice(idx, 1);
  524. }
  525. }
  526. break;
  527. }
  528. }
  529. rst = await ctx.service.rptArchive.updateArchive(orgArchiveList[0].id, prjId, stgId, orgArchiveList[0].tender_id, bzId, contentArr);
  530. }
  531. } catch (err) {
  532. this.log(err);
  533. }
  534. return rst;
  535. }
  536. async removeReportArchive(ctx) {
  537. try {
  538. const orgUuidName = ctx.params.orgName;
  539. const fileName = orgUuidName + '.PDF';
  540. // console.log(ctx.params);
  541. console.log('removing fileName: ' + fileName);
  542. // const fullName = path.join(this.app.baseDir, 'app', 'public/archive', fileName);
  543. const oss_sign_result = await ctx.app.signPdfOss.delete(`archive/sign/${fileName}`);
  544. if (oss_sign_result && oss_sign_result.res && oss_sign_result.res.status === 204) {
  545. // console.log('删除归档的签名信息成功!');
  546. const oss_result = await ctx.app.signPdfOss.delete(`archive/${fileName}`);
  547. if (!(oss_result && oss_result.res.status === 204)) {
  548. throw '删除归档文件失败';
  549. }
  550. } else {
  551. throw '删除归档签名文件失败';
  552. }
  553. // 还有加密签名信息
  554. const archiveSignRemovedRst = await this._removeReportArchiveEncryption(ctx);
  555. // console.log(archiveSignRemovedRst);
  556. const archiveRemovedRst = await this._removeReportArchive(ctx);
  557. if (archiveRemovedRst) {
  558. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updatedRst: archiveRemovedRst } };
  559. } else {
  560. ctx.body = { err: 0, msg: orgUuidName, data: { fileName, updatedRst: null } };
  561. }
  562. } catch (err) {
  563. this.log(err);
  564. ctx.body = { err: 1, msg: err.toString(), data: null };
  565. }
  566. }
  567. async addMultiReportArchive(ctx, params) {
  568. // 暂时不支持
  569. }
  570. async getArchivedFileByUUID(ctx) {
  571. // console.log('downloading : ' + ctx.params.uuid);
  572. const uuid = ctx.params.uuid;
  573. const rptName = ctx.params.rptName;
  574. const suffix = '.PDF';
  575. try {
  576. const rptNameURI = encodeURI(rptName);
  577. const filePath = this.app.baseDir + '/app/public/archive/';
  578. // console.log('filePath: ' + filePath);
  579. // await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  580. ctx.set({
  581. 'Content-Type': 'application/vnd.openxmlformats',
  582. 'Content-Disposition': 'attachment; filename="' + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix,
  583. });
  584. ctx.body = await fs.readFileSync(filePath + uuid + suffix);
  585. } catch (e) {
  586. console.log(e);
  587. }
  588. }
  589. async pdfShow(ctx) {
  590. // const renderData = {
  591. // can_netcasign: ctx.session.sessionProject.page_show.openNetCaSign === 1,
  592. // };
  593. await ctx.render('report/archive_pdf.ejs');
  594. }
  595. /*
  596. * 网证通电子签名页,(和归档报表页高度相似)
  597. */
  598. async signReport(ctx) {
  599. const tender = ctx.tender;
  600. const stage = ctx.stage;
  601. let stage_id = -1;
  602. let stage_order = -1;
  603. let stage_times = -1;
  604. let stage_status = -1;
  605. const treeNodes = await ctx.service.rptTreeNode.getNodesByProjectId([-1, tender.data.project_id]);
  606. const custTreeNodes = await ctx.service.rptTreeNodeCust.getCustFoldersByUserId(this.ctx.session.sessionUser.accountId);
  607. const stageList = await ctx.service.stage.getValidStagesShort(tender.id);
  608. //
  609. // 。。。
  610. let archiveList = [];
  611. let archiveEncryptionList = [];
  612. // console.log('tender.data.project_id: ' + tender.data.project_id);
  613. if (stage) {
  614. // console.log('ctx.stage.id: ' + ctx.stage.id);
  615. const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, ctx.stage.id);
  616. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  617. stage_id = stage.id;
  618. stage_order = stage.order;
  619. stage_times = stage.times;
  620. stage_status = stage.status;
  621. if (archives.length > 0) {
  622. archiveList = JSON.parse(archives[0].content);
  623. }
  624. console.log('2:', archiveEncryptions, ctx.stage.id);
  625. if (archiveEncryptions.length > 0) {
  626. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  627. }
  628. } else if (stageList.length > 0 && stageList[0].status === auditConst.stage.status.checked) {
  629. // console.log('stageList[0].id: ' + stageList[0].id);
  630. // const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[stageList.length - 1].id);
  631. let archives = [];
  632. for (let sidx = stageList.length - 1; sidx >= 0; sidx--) {
  633. if (stageList[sidx].status === 3) {
  634. archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[sidx].id);
  635. ctx.stage = stageList[sidx]; // 为了sub menu用
  636. break;
  637. }
  638. }
  639. ctx.stage = ctx.stage ? ctx.stage : stageList[stageList.length - 1];
  640. const archiveEncryptions = await ctx.service.rptArchiveEncryption.getPrjStgArchiveEncryption(tender.data.project_id, ctx.stage.id);
  641. // stage_id = stageList[0].id;
  642. // stage_order = stageList[0].order;
  643. // stage_times = stageList[0].times;
  644. // stage_status = stageList[0].status;
  645. if (archives && archives.length > 0) {
  646. archiveList = JSON.parse(archives[0].content);
  647. }
  648. if (archiveEncryptions && archiveEncryptions.length > 0) {
  649. archiveEncryptionList = JSON.parse(archiveEncryptions[0].content);
  650. }
  651. }
  652. let rpt_tpl_items = '{ customize: [], common: [] }';
  653. if (custTreeNodes.length > 0) {
  654. rpt_tpl_items = custTreeNodes[0].rpt_tpl_items;
  655. }
  656. // 获取ukey绑定数据
  657. const netcaSignData = await ctx.service.netcasign.getDataByCondition({ uid: ctx.session.sessionUser.accountId });
  658. // 获取已签名数据
  659. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  660. const renderData = {
  661. tender: tender.data,
  662. rpt_tpl_data: JSON.stringify(treeNodes),
  663. cust_tpl_data: rpt_tpl_items,
  664. project_id: tender.data.project_id,
  665. tender_id: tender.id,
  666. stg_id: stage_id,
  667. stg_order: stage_order,
  668. stg_times: stage_times,
  669. stg_status: stage_status,
  670. stage_list: JSON.stringify(stageList),
  671. tenderMenu,
  672. measureType,
  673. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.report.main),
  674. stages: stageList,
  675. auditConst: auditConst.stage,
  676. archiveList,
  677. archiveEncryptionList,
  678. netcaSignData,
  679. can_netcasign: ctx.session.sessionProject.page_show.openNetCaSign === 1,
  680. ossPath: signConst.path.oss,
  681. signLogList,
  682. };
  683. await this.layout('report/index_sign.ejs', renderData, 'report/index_sign_modal.ejs');
  684. }
  685. /**
  686. * 网证通电子签名接口
  687. *
  688. * @param {object} ctx - egg全局变量
  689. * @return {void}
  690. */
  691. async signPost(ctx) {
  692. const response = {
  693. err: 0,
  694. msg: '',
  695. };
  696. try {
  697. const data = JSON.parse(ctx.request.body.data);
  698. let signData;
  699. const netcaSignApi = signConst.path.api;
  700. switch (data.type) {
  701. case 'getPdfBase64':
  702. const pdfResult = await ctx.app.signPdfOss.get(data.path);
  703. if (pdfResult.res.status !== 200) {
  704. throw '该文件不存在';
  705. }
  706. response.data = Buffer.from(pdfResult.content, 'binary').toString('base64');
  707. break;
  708. case 'pdfIsExist':
  709. const pdfMsg = await ctx.app.signPdfOss.head('archive/sign/' + data.uuid + '.PDF');
  710. response.data = pdfMsg.res.status === 200;
  711. break;
  712. // 获取摘要值
  713. case 'assemblyDigest':
  714. const postData = {
  715. requestJson: JSON.stringify(data.requestJson),
  716. };
  717. const result = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyDigest', postData, 'POST');
  718. response.data = result;
  719. break;
  720. // 生成签名pdf
  721. case 'assemblyPdf':
  722. const postData2 = {
  723. requestJson: JSON.stringify(data.requestJson),
  724. };
  725. const result3 = await this.roundNetcaSign(ctx, postData2);
  726. // const result2 = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyPdf', postData2, 'POST');
  727. // 上传到oss
  728. // console.log(result3);
  729. if (result3.code === 0) {
  730. // const result3 = await ctx.helper.sendMoreRequest(netcaSignApi + result2.data);
  731. const oss_result = await ctx.app.signPdfOss.put('archive/sign/' + data.requestJson.fileName + '.PDF', result3.data);
  732. if (oss_result && oss_result.res && oss_result.res.status === 200) {
  733. if (data.end) {
  734. const versionId = oss_result.res.headers['x-oss-version-id'];
  735. // 记录签名和保存
  736. await ctx.service.netcasignLog.add(data.requestJson.fileName, data.role, ctx.session.sessionUser.accountId, versionId);
  737. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  738. response.data = signLogList;
  739. } else {
  740. // next page
  741. }
  742. } else {
  743. throw '上传文件失败';
  744. }
  745. } else {
  746. throw result3.msg;
  747. }
  748. break;
  749. // 移除签名和已签移除pdf
  750. case 'removeSign':
  751. const oss_reuslt = await ctx.app.signPdfOss.delete('archive/sign/' + data.uuid + '.PDF');
  752. if (oss_reuslt && oss_reuslt.res && oss_reuslt.res.status === 204) {
  753. const delSign_result = await ctx.service.netcasignLog.removeSign(data.uuid);
  754. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  755. response.data = signLogList;
  756. } else {
  757. throw '删除文件失败';
  758. }
  759. break;
  760. default:throw '参数有误';
  761. }
  762. } catch (error) {
  763. response.err = 1;
  764. response.msg = error.toString();
  765. const data = JSON.parse(ctx.request.body.data);
  766. if (data && data.type === 'pdfIsExist') {
  767. response.err = 0;
  768. response.data = false;
  769. }
  770. }
  771. ctx.body = response;
  772. }
  773. /**
  774. * 网证通电子签名报表上传
  775. *
  776. * @param {object} ctx - egg全局变量
  777. * @return {void}
  778. */
  779. async signFile(ctx) {
  780. const stream = await ctx.getFileStream();
  781. try {
  782. const uuid = stream.fields.uuid;
  783. const role = stream.fields.role;
  784. const oss_result = await ctx.app.signPdfOss.put('archive/sign/' + uuid + '.PDF', stream);
  785. if (!(oss_result && oss_result.url && oss_result.res.status === 200)) {
  786. throw '上传文件失败';
  787. }
  788. const versionId = oss_result.res.headers['x-oss-version-id'];
  789. // 记录签名和保存
  790. await ctx.service.netcasignLog.add(uuid, role, ctx.session.sessionUser.accountId, versionId);
  791. const signLogList = await ctx.service.netcasignLog.getLogList(ctx.tender.id);
  792. ctx.body = { err: 0, msg: '', data: signLogList };
  793. } catch (err) {
  794. // 必须将上传的文件流消费掉,要不然浏览器响应会卡死
  795. await sendToWormhole(stream);
  796. this.log(err);
  797. ctx.body = { err: 1, msg: err.toString(), data: null };
  798. }
  799. }
  800. async roundNetcaSign(ctx, postData2, round = 3) {
  801. let response = {
  802. code: 0,
  803. data: '',
  804. };
  805. // 无法获取到result3,因为result2生成的pdf已损坏,请重复获取result2,直到获取成功或尝试3次失败后报错为止
  806. try {
  807. const netcaSignApi = signConst.path.api;
  808. const result2 = await ctx.helper.sendMoreRequest(netcaSignApi + '/assemblyPdf', postData2, 'POST');
  809. if (result2.code === 0) {
  810. const result3 = await ctx.curl(netcaSignApi + result2.data, {
  811. timeout: 300000, // 超时 5分钟中
  812. });
  813. if (result3) {
  814. response.data = result3.data;
  815. } else {
  816. if (round > 0) {
  817. round = round - 1;
  818. response = await this.roundNetcaSign(ctx, postData2, round);
  819. } else {
  820. throw 'pdf获取失败,网证通接口无法生成pdf';
  821. }
  822. }
  823. }
  824. } catch (error) {
  825. response.code = 1;
  826. response.msg = error;
  827. }
  828. return response;
  829. }
  830. async sendFileMsg(ctx) {
  831. try {
  832. if (this.ctx.session.sessionUser.accountId !== ctx.tender.data.user_id) throw '您无权操作';
  833. const needFileMsg = await this.ctx.service.specMsg.tenderNeedMsg(this.ctx.session.sessionProject.id, this.ctx.tender.id, pushOperate.report.file);
  834. if (!needFileMsg) throw '该标段暂不可进行该操作';
  835. const waitingMsg = await this.ctx.service.specMsg.getDataByCondition({ tid: this.ctx.tender.id, timing: pushOperate.report.file, status: [0, 1] });
  836. if (waitingMsg) throw '上一次归档完成,未执行完毕,请稍后再试';
  837. const data = JSON.parse(ctx.request.body.data);
  838. const stage = await this.ctx.service.stage.getDataById(data.sid);
  839. await this.ctx.service.specMsg.addReportMsg(null, this.ctx.session.sessionProject.id, this.ctx.tender.data, stage, pushOperate.report.file);
  840. ctx.body = { err: 0, msg: '提交成功,稍后将同步至档案系统', data: null };
  841. } catch (err) {
  842. this.ctx.log(err);
  843. this.ctx.ajaxErrorBody(err, '操作失败');
  844. }
  845. }
  846. async sendOtherFileMsg(ctx) {
  847. try {
  848. if (this.ctx.session.sessionUser.accountId !== ctx.tender.data.user_id) throw '您无权操作';
  849. const data = JSON.parse(ctx.request.body.data);
  850. const needFileMsg = await this.ctx.service.specMsg.tenderNeedMsg(this.ctx.session.sessionProject.id, this.ctx.tender.id, data.msgType);
  851. if (!needFileMsg) throw '该标段暂不可进行该操作';
  852. const waitingMsg = await this.ctx.service.specMsg.getDataByCondition({ tid: this.ctx.tender.id, timing: data.msgType, status: [0, 1] });
  853. if (waitingMsg) throw '上一次归档完成,未执行完毕,请稍后再试';
  854. await this.ctx.service.specMsg.addOtherReportMsg(null, this.ctx.session.sessionProject.id, this.ctx.tender.data, data.id, data.msgType);
  855. ctx.body = { err: 0, msg: '提交成功,稍后将同步至档案系统', data: null };
  856. } catch (err) {
  857. this.ctx.log(err);
  858. this.ctx.ajaxErrorBody(err, '操作失败');
  859. }
  860. }
  861. }
  862. return ReportArchiveController;
  863. };