report_controller.js 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693
  1. 'use strict';
  2. /**
  3. * Created by Tony on 2019/7/5.
  4. */
  5. const tenderMenu = require('../../config/menu').tenderMenu;
  6. const measureType = require('../const/tender').measureType;
  7. const auditConst = require('../const/audit');
  8. const shenpiConst = require('../const/shenpi');
  9. const accountGroup = require('../const/account_group').group;
  10. const JpcEx = require('../reports/rpt_component/jpc_ex');
  11. const JV = require('../reports/rpt_component/jpc_value_define');
  12. const rpt_xl_util = require('../reports/util/rpt_excel_util');
  13. const rptDataExtractor = require('../reports/util/rpt_calculation_data_util');
  14. const fsUtil = require('../public/js/fsUtil');
  15. const fs = require('fs');
  16. const rptCronJob = require('../reports/util/rpt_tmp_file_sweep');
  17. const RPT_DEF_PROPERTIES = require('../const/report_defined_properties');
  18. const reportConst = require('../const/report');
  19. // const stringUtil = require('../public/js/string_util_light');
  20. const needCustomTables = [
  21. 'mem_custom_select',
  22. 'mem_gather_stage_bills', 'mem_gather_deal_bills', 'mem_gather_stage_pay', 'mem_gather_tender_info',
  23. 'mem_stage_sum_bills', 'mem_stage_sum_pay',
  24. 'mem_jh_gather_im_change', 'mem_jh_im_change', 'mem_jh_gather_stage_bills_compare',
  25. ];
  26. module.exports = app => {
  27. class ReportController extends app.BaseController {
  28. /**
  29. * 获取审批界面所需的 原报、审批人数据等
  30. * @param ctx
  31. * @return {Promise<void>}
  32. * @private
  33. */
  34. async _getStageAuditViewData(ctx) {
  35. if (!ctx.stage) return;
  36. const times = ctx.stage.status === auditConst.stage.status.checkNo ? ctx.stage.times - 1 : ctx.stage.times;
  37. ctx.stage.user = await ctx.service.projectAccount.getAccountInfoById(ctx.stage.user_id);
  38. ctx.stage.auditHistory = [];
  39. if (times >= 1) {
  40. for (let i = 1; i <= times; i++) {
  41. ctx.stage.auditHistory.push(await ctx.service.stageAudit.getAuditors(ctx.stage.id, i));
  42. }
  43. }
  44. // 获取审批流程中左边列表
  45. ctx.stage.auditors2 = await ctx.service.stageAudit.getAuditGroupByListWithOwner(ctx.stage.id, times);
  46. if (ctx.stage.status === auditConst.stage.status.uncheck || ctx.stage.status === auditConst.stage.status.checkNo) {
  47. ctx.stage.auditorList = await ctx.service.stageAudit.getAuditors(ctx.stage.id, ctx.stage.times);
  48. }
  49. }
  50. async _chkIfStageAuditor(ctx, stage) {
  51. //
  52. }
  53. async _filterStageList(ctx, stageList) {
  54. //
  55. // throw
  56. }
  57. /**
  58. * 报表显示页面
  59. *
  60. * @param {Object} ctx - egg全局context
  61. * @return {void}
  62. */
  63. async index(ctx) {
  64. try {
  65. await this._getStageAuditViewData(ctx);
  66. const pageShow = ctx.session.sessionProject.page_show;
  67. pageShow.showArchive = 1;
  68. const tender = ctx.tender;
  69. const stage = ctx.stage;
  70. let stage_id = -1;
  71. let stage_order = -1;
  72. let sorder = -1;
  73. let stage_times = -1;
  74. let stage_status = -1;
  75. const treeNodes = await ctx.service.rptTreeNode.getNodesByProjectId([-1, tender.data.project_id]);
  76. const custTreeNodes = await ctx.service.rptTreeNodeCust.getCustFoldersByUserId(this.ctx.session.sessionUser.accountId);
  77. const custCfg = await ctx.service.rptCustomizeCfg.getCustomizeCfgByUserId('Administrator');
  78. const stageList = await ctx.service.stage.getValidStagesShort(tender.id);
  79. // console.log(stage);
  80. // console.log(stageList);
  81. // console.log('ctx.stage.id: ' + ctx.stage.id);
  82. // console.log('ctx.stage.stage_id: ' + ctx.stage.stage_id);
  83. // console.log('this.ctx.session.sessionUser.accountId: ' + this.ctx.session.sessionUser.accountId);
  84. if (stage && stage.status === auditConst.stage.status.uncheck) {
  85. // 得判断账号是否在审核人列表中(不含原报)
  86. if (stage.auditorList === undefined || stage.auditorList === null) {
  87. stage.auditorList = await ctx.service.stageAudit.getAuditors(ctx.stage.id, ctx.stage.times);
  88. }
  89. let isAudit = false;
  90. // console.log('stage.auditorList');
  91. // console.log(stage.auditorList);
  92. for (const audit of stage.auditorList) {
  93. if (audit.aid === this.ctx.session.sessionUser.accountId) {
  94. isAudit = true;
  95. break;
  96. }
  97. }
  98. if (isAudit) {
  99. throw '未上报!';
  100. }
  101. } else {
  102. // 剔除未上报期(审核人(非原报人)才需要判断)
  103. for (let idx = stageList.length - 1; idx >= 0; idx--) {
  104. if (stageList[idx].status === auditConst.stage.status.uncheck) {
  105. if (stageList[idx].auditorList === undefined || stageList[idx].auditorList === null) {
  106. stageList[idx].auditorList = await ctx.service.stageAudit.getAuditors(stageList[idx].id, stageList[idx].times);
  107. }
  108. let isAudit = false;
  109. // console.log('stageList[idx].auditorList');
  110. // console.log(stageList[idx].auditorList);
  111. for (const audit of stageList[idx].auditorList) {
  112. if (audit.aid === this.ctx.session.sessionUser.accountId) {
  113. isAudit = true;
  114. break;
  115. }
  116. }
  117. if (isAudit) {
  118. stageList.splice(idx, 1);
  119. }
  120. }
  121. }
  122. }
  123. let lastAuditor = null;
  124. if (stage) {
  125. lastAuditor = await ctx.service.stageAudit.getLastestAuditor(ctx.stage.id, ctx.stage.times, auditConst.stage.status.checked);
  126. } else {
  127. lastAuditor = stageList.length > 0 ? await ctx.service.stageAudit.getLastestAuditor(stageList[stageList.length - 1].id, stageList[stageList.length - 1].times, auditConst.stage.status.checked) : null;
  128. }
  129. let archiveList = [];
  130. if (stage) {
  131. const archives = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, ctx.stage.id);
  132. if (archives.length > 0) {
  133. archiveList = JSON.parse(archives[0].content);
  134. }
  135. } else {
  136. const archives = stageList.length > 0 ? await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, stageList[stageList.length - 1].id) : [];
  137. // console.log(archives);
  138. if (archives && archives.length > 0) {
  139. archiveList = JSON.parse(archives[0].content);
  140. }
  141. }
  142. // const archiveList = await ctx.service.rptArchive.getPrjStgArchive(tender.data.project_id, ctx.stage.id);
  143. let prjAccList = await ctx.service.projectAccount.getAllAccountByProjectId(tender.data.project_id);
  144. const roleList = await ctx.service.signatureRole.getSignatureRolesByTenderId(tender.id);
  145. const usedList = await ctx.service.signatureUsed.getSignatureUsedByTenderId(tender.id);
  146. // ctx.session.sessionUser.is_admin
  147. // const pageShow = ctx.session.sessionProject.page_show;
  148. // 根据需求,如果开启了‘开启个人「签字」’功能,则只能是本身用户签名,管理员例外
  149. if (!ctx.session.sessionUser.is_admin && pageShow.individualSign === 1) {
  150. // 削减其他account
  151. const newAccList = [];
  152. for (const acc of prjAccList) {
  153. if (acc.id === this.ctx.session.sessionUser.accountId) {
  154. newAccList.push(acc);
  155. }
  156. }
  157. prjAccList = newAccList;
  158. }
  159. // 分类列表
  160. const categoryData = await this.ctx.service.category.getAllCategory(this.ctx.session.sessionProject.id);
  161. // 获取用户权限
  162. const accountInfo = await this.ctx.service.projectAccount.getDataById(this.ctx.session.sessionUser.accountId);
  163. const userPermission = accountInfo !== undefined && accountInfo.permission !== '' ? JSON.parse(accountInfo.permission) : null;
  164. // 获取用户可查看的标段
  165. const tenderList = await this.ctx.service.tender.getList('', userPermission);
  166. for (const t of tenderList) {
  167. if (t.ledger_status === auditConst.ledger.status.checked) {
  168. t.lastStage = await this.ctx.service.stage.getLastestStage(t.id, true);
  169. // if (t.lastStage) {
  170. // await this.ctx.service.stage.checkStageGatherData(t.lastStage);
  171. // }
  172. }
  173. }
  174. // 获取汇总表,历史选择
  175. const cid = this.ctx.helper._.map(treeNodes, 'id');
  176. const customSelects = {};
  177. if (ctx.stage) {
  178. customSelects.audit_select = await ctx.service.rptCustomDefine.getCustomSelectByRpt(cid,
  179. reportConst.rptCustomType[JV.NODE_CUS_AUDIT_SELECT], ctx.tender.id, ctx.stage.id);
  180. customSelects.stageFlow = await ctx.service.stageAudit.getAuditGroupByListWithOwner(
  181. ctx.stage.stage_id, ctx.stage.stage_times);
  182. } else {
  183. customSelects.audit_select = [];
  184. }
  185. customSelects.gather_select = await ctx.service.rptCustomDefine.getCustomSelectByRpt(cid,
  186. reportConst.rptCustomType[JV.NODE_CUS_GATHER_SELECT], ctx.tender.id, -1);
  187. customSelects.stage_select = await ctx.service.rptCustomDefine.getCustomSelectByRpt(cid,
  188. reportConst.rptCustomType[JV.NODE_CUS_STAGE_SELECT], ctx.tender.id, -1);
  189. customSelects.change_select = await ctx.service.rptCustomDefine.getCustomSelectByRpt(cid,
  190. reportConst.rptCustomType[JV.NODE_CUS_CHANGE_SELECT], ctx.tender.id, -1);
  191. const dataSelects = {};
  192. dataSelects.material_select = await ctx.service.rptCustomDefine.getDataSelectByRpt(cid,
  193. reportConst.rptDataType[JV.NODE_CUS_MATERIAL_SELECT]);
  194. const materialList = await ctx.service.material.getValidMaterials(ctx.tender.id);
  195. // const allTpls = await ctx.service.rptTpl.getAllTplByIds(tmpRptIds);
  196. // for (const tpl of allTpls) {
  197. // const fName = tpl.id + '_' + tpl.rpt_tpl_name + '.js';
  198. // console.log('fName: ' + fName);
  199. // fsUtil.writeObjToFile(tpl, 'D:/Temp/计量临时/' + fName);
  200. // }
  201. // 完成历史任务,下一批
  202. // const filePath = 'D:/Temp/计量临时/';
  203. // const tplFiles = [];
  204. // fs.readdir(filePath, (err, files) => {
  205. // if (err) throw err;
  206. // files.forEach(file => {
  207. // const fPath = filePath + file;
  208. // // console.log('\'' + fPath + '\'');
  209. // tplFiles.push(fPath);
  210. // });
  211. // });
  212. //
  213. // setTimeout(function() {
  214. // console.log(tplFiles);
  215. // }, 2000);
  216. // 下一批
  217. // let cnt = 0;
  218. // for (const file of rptFiles) {
  219. // const tplObj = JSON.parse(fs.readFileSync(file, 'utf-8'));
  220. // const rst = await ctx.service.rptTpl.insertRptTpl(tplObj);
  221. // cnt++;
  222. // console.log(file);
  223. // }
  224. // console.log(cnt + ' 完成!');
  225. // console.log(maxStageAmt[0].maxAmt);
  226. // 备注:在报表界面初始化的时候,暂时不需要check stage,只有在点中某张表的时候才需要(签名交互需要)
  227. // if ((stage === null || stage === undefined) && stageList.length > 0) {
  228. // await ctx.service.stage.checkStage(stageList[stageList.length - 1].id);
  229. // stage = ctx.stage;
  230. // console.log(stage);
  231. // }
  232. if (stage !== null && stage !== undefined) {
  233. stage_id = stage.id;
  234. stage_order = stage.order;
  235. sorder = stage.curOrder;
  236. stage_times = stage.times;
  237. stage_status = stage.status;
  238. }
  239. for (const prjAcc of prjAccList) {
  240. prjAcc.account_group = accountGroup[prjAcc.account_group];
  241. }
  242. let rpt_tpl_items = '{ customize: [], common: [] }';
  243. if (custTreeNodes.length > 0) {
  244. rpt_tpl_items = custTreeNodes[0].rpt_tpl_items;
  245. }
  246. // 获取所有项目参与者
  247. const accountList = await ctx.service.projectAccount.getAllDataByCondition({
  248. where: { project_id: ctx.session.sessionProject.id, enable: 1 },
  249. columns: ['id', 'name', 'company', 'role', 'enable', 'is_admin', 'account_group', 'mobile'],
  250. });
  251. const newAccountGroup = accountGroup.map((item, idx) => {
  252. const groupList = accountList.filter(item => item.account_group === idx);
  253. return { groupName: item, groupList };
  254. });
  255. const renderData = {
  256. accountGroup: newAccountGroup,
  257. accountList,
  258. tender: tender.data,
  259. tenderInfo: tender.info,
  260. rpt_tpl_data: JSON.stringify(treeNodes),
  261. cust_tpl_data: rpt_tpl_items,
  262. cust_cfg: JSON.stringify(custCfg),
  263. project_id: tender.data.project_id,
  264. tender_id: tender.id,
  265. tender_name: tender.data.name,
  266. stg_id: stage_id,
  267. stg_order: stage_order,
  268. cur_order: sorder,
  269. stg_times: stage_times,
  270. stg_status: stage_status,
  271. stage_list: JSON.stringify(stageList),
  272. prj_account_list: JSON.stringify(prjAccList),
  273. role_list: JSON.stringify(roleList),
  274. used_list: JSON.stringify(usedList),
  275. tenderMenu,
  276. preUrl: '/tender/' + ctx.tender.id + '/measure/stage/' + ctx.params.order,
  277. measureType,
  278. categoryData,
  279. tenderList,
  280. auditConst: auditConst.stage,
  281. ledgerAuditConst: auditConst.ledger,
  282. jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.report.main),
  283. customSelects,
  284. rptCustomType: reportConst.rptCustomType,
  285. materialList,
  286. stages: stageList,
  287. dataSelects,
  288. // pageShow: JSON.stringify(pageShow),
  289. pageShow,
  290. authMobile: accountInfo.auth_mobile,
  291. shenpiConst,
  292. archiveList,
  293. lastAuditor,
  294. rpt_id: ctx.query.rpt_id,
  295. };
  296. await this.layout('report/index.ejs', renderData, 'report/rpt_all_popup.ejs');
  297. // await this.layout('report/index.ejs', renderData);
  298. // 在这里启动一个cron job,删除临时创建的excel文件
  299. if (!rptCronJob.started) {
  300. try {
  301. // console.log('rptCronJob.started: ' + rptCronJob.started);
  302. rptCronJob.started = true;
  303. // console.log('this.app.baseDir: ' + this.app.baseDir);
  304. rptCronJob.createJob(null, this.app.baseDir + '/app/public/download');
  305. } catch (ex) {
  306. rptCronJob.started = false;
  307. }
  308. }
  309. } catch (err) {
  310. this.log(err);
  311. ctx.redirect('/tender/' + ctx.tender.id + '/measure/stage');
  312. }
  313. }
  314. /**
  315. * 报表打印页面
  316. *
  317. * @param {Object} ctx - egg全局context
  318. * @return {void}
  319. */
  320. async showPrintPage(ctx) {
  321. try {
  322. // const params = JSON.parse(ctx.request.body.params);
  323. const pageSize = ctx.params.size;
  324. // console.log('pageSize: ' + pageSize);
  325. const renderData = {
  326. size: pageSize,
  327. // orientation: params.orientation,
  328. };
  329. await ctx.render('report/rpt_print.ejs', renderData);
  330. } catch (err) {
  331. this.log(err);
  332. console.log(err);
  333. }
  334. }
  335. async showIndividualPage(ctx) {
  336. try {
  337. // const params = JSON.parse(ctx.request.body.params);
  338. const pageSize = ctx.params.size;
  339. // console.log('pageSize: ' + pageSize);
  340. const renderData = {
  341. size: pageSize,
  342. // orientation: params.orientation,
  343. };
  344. await ctx.render('report/rpt_individual.ejs', renderData);
  345. } catch (err) {
  346. this.log(err);
  347. console.log(err);
  348. }
  349. }
  350. async _getReport(ctx, params) {
  351. // console.log('in getReport');
  352. // console.log(params);
  353. let rptTpl = await ctx.service.rptTpl.getTplById(params.rpt_tpl_id);
  354. if (!rptTpl || rptTpl.length !== 1) {
  355. throw '获取模板失败';
  356. }
  357. rptTpl = JSON.parse(rptTpl[0].rpt_content);
  358. // console.log('get the template!');
  359. const customSelect = rptTpl[JV.NODE_CUSTOM_DEFINE] && rptTpl[JV.NODE_CUSTOM_DEFINE][JV.NODE_CUS_AUDIT_SELECT].enable
  360. ? await ctx.service.rptCustomDefine.getCustomDefine(params.tender_id, params.stage_id, params.rpt_tpl_id)
  361. : await ctx.service.rptCustomDefine.getCustomDefine(params.tender_id, -1, params.rpt_tpl_id);
  362. console.log(customSelect);
  363. let copyCustomSelect = this.ctx.helper.clone(customSelect);
  364. if (!params.gather_select && copyCustomSelect) delete copyCustomSelect.gather_select;
  365. if (!params.stage_select && copyCustomSelect) delete copyCustomSelect.stage_select;
  366. if (params.change_select) {
  367. copyCustomSelect = { tid: params.tender_id, rid: params.rpt_tpl_id, sid: -1, change_select: params.change_select};
  368. }
  369. const pageRst = await getAllPagesCommon(ctx, rptTpl, params, JV.PAGING_OPTION_NORMAL, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir, copyCustomSelect);
  370. for (const page of pageRst.items) {
  371. page[JV.PROP_WATERMARK_CELLS] = [];
  372. }
  373. let waterMarkStr = null;
  374. if (params.stage_status !== 3 && params.closeWatermark === 0) {
  375. // 加水印
  376. fillWaterMark([pageRst]);
  377. if (params.needWaterMark) {
  378. waterMarkStr = await getWatermarkPicData(pageRst, this.app.baseDir);
  379. }
  380. }
  381. // console.log(pageRst);
  382. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  383. const roleRel = await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id, params.stage_id); // 新需求中,允许在非审核状态下设置签名
  384. const stgAudit = await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times);
  385. const stgAuditForOrg = await ctx.service.stageAudit.getStageAudit(params.stage_id, 1);
  386. // console.log('after role stage!');
  387. // console.log(roleRel);
  388. mergeTextSignature(params.isTextSignature, params.stage_status, pageRst, roleRel[0]);
  389. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  390. if (params.getPicFlag) {
  391. await encodeDummySignatureDataUri(pageRst, this.app.baseDir); // 注意草图数据量问题!
  392. }
  393. const stageFlow = await ctx.service.stageAudit.getAuditGroupByListWithOwner(params.stage_id, params.stage_times);
  394. // console.log('encodeSignatureDataUri!');
  395. return {
  396. data: pageRst,
  397. signatureRelInfo: roleRel,
  398. stageAudit: stgAudit,
  399. stageAuditOrg: stgAuditForOrg,
  400. debugInfo: ctx.app.config.is_debug ? ctx.debugInfo : null,
  401. customDefine: rptTpl[JV.NODE_CUSTOM_DEFINE],
  402. stageFlow,
  403. customSelect,
  404. waterMarkStr,
  405. };
  406. }
  407. /**
  408. * 获取报表数据
  409. *
  410. * @param {Object} ctx - egg全局context
  411. * @return {void}
  412. */
  413. async getReport(ctx) {
  414. try {
  415. // console.log('in getReport');
  416. const params = JSON.parse(ctx.request.body.params);
  417. ctx.body = await this._getReport(ctx, params);
  418. // // console.log(params);
  419. // let rptTpl = await ctx.service.rptTpl.getTplById(params.rpt_tpl_id);
  420. // if (!rptTpl || rptTpl.length !== 1) {
  421. // throw '获取模板失败';
  422. // }
  423. // rptTpl = JSON.parse(rptTpl[0].rpt_content);
  424. // // console.log('get the template!');
  425. // const pageRst = await getAllPagesCommon(ctx, rptTpl, params, JV.PAGING_OPTION_NORMAL, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  426. // // console.log(pageRst);
  427. // // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  428. // const roleRel = await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id); // 新需求中,允许在非审核状态下设置签名
  429. // const stgAudit = await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times);
  430. // // console.log('after role stage!');
  431. // // console.log(roleRel);
  432. // await encodeSignatureDataUri(roleRel, this.app.baseDir);
  433. // await encodeDummySignatureDataUri(pageRst, this.app.baseDir);
  434. // const stageFlow = await ctx.service.stageAudit.getAuditGroupByListWithOwner(params.stage_id, params.stage_times);
  435. // const customSelect = await ctx.service.rptCustomDefine.getDataByCondition({
  436. // tid: params.tender_id, sid: params.stage_id, rid: params.rpt_tpl_id
  437. // });
  438. //
  439. // // console.log('encodeSignatureDataUri!');
  440. // ctx.body = {
  441. // data: pageRst,
  442. // signatureRelInfo: roleRel,
  443. // stageAudit: stgAudit,
  444. // debugInfo: ctx.app.config.is_debug ? ctx.debugInfo : null,
  445. // customDefine: rptTpl[JV.NODE_CUSTOM_DEFINE],
  446. // stageFlow,
  447. // customSelect,
  448. // };
  449. // // ctx.body = { data: { msg: 'test the network' } };
  450. ctx.status = 201;
  451. } catch (ex) {
  452. console.log(ex);
  453. this.setMessage(ex.toString(), this.messageType.ERROR);
  454. }
  455. }
  456. /**
  457. * 获取多批次报表数据
  458. *
  459. * @param {Object} ctx - egg全局context
  460. * @return {void}
  461. */
  462. async getMultiReportsEx(ctx) {
  463. // 原则说明:把所有报表模板集中获取,统一filter,只读一次数据!
  464. const params = JSON.parse(ctx.request.body.params);
  465. const pageShow = ctx.session.sessionProject.page_show;
  466. if (pageShow !== null && pageShow !== undefined && parseInt(pageShow.closeExportPdf) === 1) {
  467. ctx.body = { data: [], signatureRelInfo: [], stageAudit: [] };
  468. ctx.status = 201;
  469. return;
  470. }
  471. await this._saveCustomSelects(params);
  472. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir) || [];
  473. for (const pageRst of pageRstArr) {
  474. for (const page of pageRst.items) {
  475. page[JV.PROP_WATERMARK_CELLS] = [];
  476. }
  477. }
  478. let waterMarkStr = null;
  479. if (params.stage_status !== 3 && params.closeWatermark === 0) {
  480. // 加水印
  481. fillWaterMark(pageRstArr);
  482. if (params.needWaterMark) {
  483. waterMarkStr = await getWatermarkPicData(pageRstArr[0], this.app.baseDir);
  484. }
  485. }
  486. const stgAudit = await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times);
  487. const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids, params.stage_id)) : [];
  488. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  489. roleRel.sort(function(rr1, rr2) {
  490. return params.rpt_ids.indexOf(parseInt(rr1.rpt_id)) - params.rpt_ids.indexOf(parseInt(rr2.rpt_id));
  491. });
  492. // console.log('roleRel: ');
  493. // console.log(roleRel);
  494. mergeTextSignature(params.isTextSignature, params.stage_status, pageRstArr, roleRel, params.rpt_ids);
  495. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  496. if (params.getPicFlag) {
  497. for (const pageRst of pageRstArr) {
  498. await encodeDummySignatureDataUri(pageRst, this.app.baseDir); // 注意草图数据量问题!
  499. }
  500. }
  501. // console.log(pageRstArr);
  502. ctx.body = { data: pageRstArr, signatureRelInfo: roleRel, stageAudit: stgAudit, waterMarkStr };
  503. ctx.status = 201;
  504. }
  505. async _saveCustomSelects(params) {
  506. for (const [i, cs] of params.customSelect.entries()) {
  507. if (!cs) continue;
  508. cs.tender_id = params.tender_id;
  509. cs.stage_id = params.stage_id;
  510. cs.rpt_tpl_id = params.rpt_ids[i];
  511. await this.ctx.service.rptCustomDefine.saveCustomSelect(cs);
  512. }
  513. }
  514. async createExcelFilesEx(ctx) {
  515. const params = JSON.parse(ctx.request.body.params);
  516. const pageShow = ctx.session.sessionProject.page_show;
  517. if (pageShow !== null && pageShow !== undefined && parseInt(pageShow.closeExportExcel) === 1) {
  518. ctx.body = { data: [] };
  519. ctx.status = 201;
  520. return;
  521. }
  522. await this._saveCustomSelects(params);
  523. const baseDir = this.app.baseDir;
  524. function getExcelByPageData(pageRst, rpt_name, innerRoleRel) {
  525. return new Promise(function(resolve, reject) {
  526. rpt_xl_util.exportExcel(pageRst, params.pageSize, rpt_name, params.isOneSheet, null, null, baseDir, innerRoleRel,
  527. (err, uuidName) => {
  528. if (err) return reject(err);
  529. const fileRst = { uuid: uuidName, reportName: rpt_name.replace(new RegExp('%', 'gm'), '_') };
  530. resolve(fileRst);
  531. }
  532. );
  533. });
  534. }
  535. const stgAudit = (params.stage_status === 3) ? (await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times)) : [];
  536. const stgAuditForOrg = (params.stage_status === 3) ? (await ctx.service.stageAudit.getStageAudit(params.stage_id, 1)) : [];
  537. const stageList = (params.stage_status === 3) ? (await ctx.service.stage.getValidStagesShort(params.tender_id)) : [];
  538. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids, params.stage_id)) : [];
  539. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  540. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, baseDir);
  541. // console.log('params.stage_status: ' + params.stage_status);
  542. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/testBuiltPageResult1.js');
  543. for (const pageRst of pageRstArr) {
  544. for (const page of pageRst.items) {
  545. page[JV.PROP_WATERMARK_CELLS] = [];
  546. }
  547. }
  548. let waterMarkStr = null;
  549. if (params.stage_status !== 3 && params.closeWatermark === 0) {
  550. // if (params.stage_status !== 3 && params.closeWatermark === 0 && params.option === JV.PAGING_OPTION_NORMAL) {
  551. // 加水印(注意:还得看用户设置是否需要加水印)
  552. fillWaterMark(pageRstArr);
  553. if (params.needWaterMark) {
  554. waterMarkStr = await getWatermarkPicData(pageRstArr[0], baseDir);
  555. }
  556. }
  557. mergeTextSignature(params.isTextSignature, params.stage_status, pageRstArr, roleRelArr, params.rpt_ids);
  558. await this.ctx.helper.recursiveMkdirSync(baseDir + '/app/public/download');
  559. const runnableRst = [];
  560. /*
  561. for (let idx = 0; idx < pageRstArr.length; idx++) {
  562. let roleRel = null;
  563. for (const roleR of roleRelArr) {
  564. if (roleR.rpt_id === params.rpt_ids[idx]) {
  565. roleRel = JSON.parse(roleR.rel_content);
  566. break;
  567. }
  568. }
  569. // console.log('roleRel.rel_content: ' + roleRel.rel_content);
  570. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/testBuiltPageResult.jsp');
  571. if (params.stage_status === 3) {
  572. mergeSignAudit(pageRstArr[idx], roleRel, stgAudit);
  573. mergeSignDate(pageRstArr[idx], params.stage_id, roleRel, stgAudit, stgAuditForOrg, stageList);
  574. }
  575. runnableRst.push(getExcelByPageData(pageRstArr[idx], params.rpt_names[idx], roleRel));
  576. }
  577. /*/
  578. // 1. merge签名相关信息
  579. // const pageBrkSize = 6291456; // 6M, 1024*1024*6
  580. const pageBrkSize = 62914560; // 60M, 1024*1024*6*10
  581. for (let idx = 0; idx < pageRstArr.length; idx++) {
  582. let roleRel = null;
  583. for (const roleR of roleRelArr) {
  584. if (roleR.rpt_id === params.rpt_ids[idx]) {
  585. roleRel = JSON.parse(roleR.rel_content);
  586. break;
  587. }
  588. }
  589. if (params.stage_status === 3) {
  590. mergeSignAudit(pageRstArr[idx], roleRel, stgAudit);
  591. mergeSignDate(pageRstArr[idx], params.stage_id, roleRel, stgAudit, stgAuditForOrg, stageList);
  592. }
  593. // 2. 判断草图大小是否需要分页
  594. const picSize = await _chkRawPicSize(pageRstArr[idx], baseDir);
  595. // const picSize = 262914560; // 测试用,强制分页
  596. if (picSize > pageBrkSize) {
  597. // let pageBrkAmt = Math.ceil(picSize / pageBrkSize);
  598. let pageBrkAmt = Math.floor(pageRstArr[idx].items.length / Math.ceil(picSize / pageBrkSize));
  599. if (pageBrkAmt < 10) {
  600. // 不用管
  601. } else if (pageBrkAmt < 100) {
  602. pageBrkAmt = Math.floor(pageBrkAmt / 10) * 10;
  603. } else if (pageBrkAmt < 1000) {
  604. pageBrkAmt = Math.floor(pageBrkAmt / 100) * 100;
  605. } else {
  606. // 暂时不管
  607. }
  608. const newRptNames = []; // 这个为导出控制分页用
  609. const newPageDataRst = _resetPageDataByBreaks([pageRstArr[idx]], pageBrkAmt, [params.rpt_names[idx]], newRptNames);
  610. for (let dtlIdx = 0; dtlIdx < newPageDataRst.length; dtlIdx++) {
  611. runnableRst.push(getExcelByPageData(newPageDataRst[dtlIdx], newRptNames[dtlIdx], roleRel));
  612. }
  613. } else {
  614. runnableRst.push(getExcelByPageData(pageRstArr[idx], params.rpt_names[idx], roleRel));
  615. }
  616. }
  617. // */
  618. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/计量导出pageArr.js');
  619. const uuidRst = await Promise.all(runnableRst);
  620. ctx.body = { data: uuidRst, waterMarkStr };
  621. ctx.status = 201;
  622. }
  623. _getExcelByPageData(pageRst, rpt_name, pageSize, baseDir, innerRoleRel) {
  624. return new Promise(function(resolve, reject) {
  625. rpt_xl_util.exportExcel(pageRst, pageSize, rpt_name, true, null, null, baseDir, innerRoleRel,
  626. (err, uuidName) => {
  627. if (err) return reject(err);
  628. const fileRst = { uuid: uuidName, reportName: rpt_name.replace(new RegExp('%', 'gm'), '_') };
  629. resolve(fileRst);
  630. }
  631. );
  632. });
  633. }
  634. async createExcelFilesFromDirectData(ctx) {
  635. const params = JSON.parse(ctx.request.body.params);
  636. const names = params.rptNames;
  637. const pageDataArr = params.pageData;
  638. const runnableRst = [];
  639. for (let idx = 0; idx < names.length; idx++) {
  640. runnableRst.push(this._getExcelByPageData(pageDataArr[idx], names[idx], 'A4', this.app.baseDir, null));
  641. }
  642. const uuidRst = await Promise.all(runnableRst);
  643. ctx.body = { data: uuidRst, waterMarkStr: null };
  644. ctx.status = 201;
  645. }
  646. async createExcelFilesFromLocal(ctx) {
  647. const baseDir = this.app.baseDir;
  648. function getExcelByPageData(pageRst, rpt_name, innerRoleRel) {
  649. return new Promise(function(resolve, reject) {
  650. rpt_xl_util.exportExcel(pageRst, 'A4', rpt_name, true, null, null, baseDir, innerRoleRel,
  651. (err, uuidName) => {
  652. if (err) return reject(err);
  653. const fileRst = { uuid: uuidName, reportName: rpt_name.replace(new RegExp('%', 'gm'), '_') };
  654. resolve(fileRst);
  655. }
  656. );
  657. });
  658. }
  659. try {
  660. console.log('start:');
  661. const pageRst = JSON.parse(fs.readFileSync('D:/GitHome/temp/计量excel原始数据_A3BZ6_5384_112表(清单).js', 'utf-8'));
  662. console.log('read it');
  663. const runnableRst = [];
  664. const pageBrkSize = 6291456; // 6M, 1024*1024*6
  665. // const pageBrkSize = 1048576; // 1M, 1024*1024*1
  666. console.log('pageBrkSize:' + pageBrkSize);
  667. const picSize = await _chkRawPicSize(pageRst, baseDir);
  668. console.log('picSize:' + picSize);
  669. if (picSize > pageBrkSize) {
  670. let pageBrkAmt = Math.floor(pageRst.items.length / Math.ceil(picSize / pageBrkSize));
  671. console.log('pageBrkAmt:' + pageBrkAmt);
  672. if (pageBrkAmt < 10) {
  673. // 不用管
  674. } else if (pageBrkAmt < 100) {
  675. pageBrkAmt = Math.floor(pageBrkAmt / 10) * 10;
  676. } else if (pageBrkAmt < 1000) {
  677. pageBrkAmt = Math.floor(pageBrkAmt / 100) * 100;
  678. } else {
  679. // 暂时不管
  680. }
  681. const newRptNames = []; // 这个为导出控制分页用
  682. const newPageDataRst = _resetPageDataByBreaks([pageRst], pageBrkAmt, ['工程计量表(计量单元-清单)'], newRptNames);
  683. for (let dtlIdx = 0; dtlIdx < newPageDataRst.length; dtlIdx++) {
  684. runnableRst.push(getExcelByPageData(newPageDataRst[dtlIdx], newRptNames[dtlIdx], null));
  685. }
  686. } else {
  687. runnableRst.push(getExcelByPageData(pageRst, '工程计量表(计量单元-清单)', null));
  688. }
  689. const uuidRst = await Promise.all(runnableRst);
  690. ctx.body = { data: uuidRst, waterMarkStr: null };
  691. ctx.status = 201;
  692. } catch (ex) {
  693. console.log(ex.toString());
  694. ctx.status = 500;
  695. }
  696. }
  697. async createExcelFilesInOneBookEx(ctx) {
  698. const params = JSON.parse(ctx.request.body.params);
  699. const baseDir = this.app.baseDir;
  700. function getExcelByPageData(pageRstArr, rpt_name, innerRoleRel) {
  701. return new Promise(function(resolve, reject) {
  702. rpt_xl_util.exportExcelInOneBook(pageRstArr, params.pageSize, rpt_name, baseDir, innerRoleRel,
  703. (err, uuidName) => {
  704. if (err) return reject(err);
  705. const fileRst = { uuid: uuidName, reportName: rpt_name };
  706. resolve(fileRst);
  707. }
  708. );
  709. });
  710. }
  711. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids, params.stage_id)) : [];
  712. // console.log(`baseDir: ${baseDir}`);
  713. // fsUtil.writeObjToFile(roleRelArr, 'D:/GitHome/temp/签名信息.js');
  714. const stgAudit = (params.stage_status === 3) ? (await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times)) : [];
  715. const stgAuditForOrg = (params.stage_status === 3) ? (await ctx.service.stageAudit.getStageAudit(params.stage_id, 1)) : [];
  716. const stageList = (params.stage_status === 3) ? (await ctx.service.stage.getValidStagesShort(params.tender_id)) : [];
  717. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  718. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/pageRstArrForExcel.js');
  719. for (const pageRst of pageRstArr) {
  720. for (const page of pageRst.items) {
  721. page[JV.PROP_WATERMARK_CELLS] = [];
  722. }
  723. }
  724. let waterMarkStr = null;
  725. if (params.stage_status !== 3 && params.closeWatermark === 0) {
  726. // if (params.stage_status !== 3 && params.closeWatermark === 0 && params.option === JV.PAGING_OPTION_NORMAL) {
  727. // 加水印
  728. fillWaterMark(pageRstArr);
  729. if (params.needWaterMark) {
  730. waterMarkStr = await getWatermarkPicData(pageRstArr[0], this.app.baseDir);
  731. }
  732. }
  733. mergeTextSignature(params.isTextSignature, params.stage_status, pageRstArr, roleRelArr, params.rpt_ids);
  734. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  735. const runnableRst = [];
  736. let rptRoleRelArr = [];
  737. const reAssignSignatureName = function(pageData, roleRel, rpt_name_key) {
  738. const keyMap = {};
  739. for (const pageItem of pageData.items) {
  740. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  741. if (!keyMap.hasOwnProperty(signCell.signature_name)) {
  742. keyMap[signCell.signature_name] = rpt_name_key + '_' + signCell.signature_name;
  743. }
  744. }
  745. }
  746. for (const pageItem of pageData.items) {
  747. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  748. if (keyMap.hasOwnProperty(signCell.signature_name)) {
  749. signCell.signature_name = keyMap[signCell.signature_name];
  750. }
  751. }
  752. }
  753. for (const roleSign of roleRel) {
  754. if (keyMap.hasOwnProperty(roleSign.signature_name)) {
  755. roleSign.signature_name = keyMap[roleSign.signature_name];
  756. }
  757. }
  758. // console.log('keyMap of : ' + rpt_name_key);
  759. // console.log(keyMap);
  760. };
  761. for (let idx = 0; idx < pageRstArr.length; idx++) {
  762. let roleRel = null;
  763. for (const roleR of roleRelArr) {
  764. if (roleR.rpt_id === params.rpt_ids[idx]) {
  765. roleRel = JSON.parse(roleR.rel_content);
  766. if (params.stage_status === 3) {
  767. mergeSignAudit(pageRstArr[idx], roleRel, stgAudit);
  768. mergeSignDate(pageRstArr[idx], params.stage_id, roleRel, stgAudit, stgAuditForOrg, stageList);
  769. }
  770. // 这里要做些电子签名的signature_name转换,以防重名
  771. reAssignSignatureName(pageRstArr[idx], roleRel, params.rpt_names[idx]);
  772. rptRoleRelArr = rptRoleRelArr.concat(roleRel);
  773. break;
  774. }
  775. }
  776. }
  777. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/pageRstArrForExcelAfterReAssign.js');
  778. // fsUtil.writeObjToFile(rptRoleRelArr, 'D:/GitHome/temp/签名信息_新.js');
  779. runnableRst.push(getExcelByPageData(pageRstArr, params.rptName, rptRoleRelArr));
  780. const uuidRst = await Promise.all(runnableRst);
  781. ctx.body = { data: uuidRst, waterMarkStr };
  782. ctx.status = 201;
  783. }
  784. async getFileByUUID(ctx) {
  785. // console.log('downloading : ' + ctx.params.uuid);
  786. const uuid = ctx.params.uuid;
  787. const rptName = ctx.params.rptName;
  788. const suffix = '.' + ctx.params.suffix;
  789. try {
  790. const rptNameURI = encodeURI(rptName);
  791. const filePath = this.app.baseDir + '/app/public/download/';
  792. // console.log('filePath: ' + filePath);
  793. // await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  794. ctx.set({
  795. 'Content-Type': 'application/vnd.openxmlformats',
  796. 'Content-Disposition': 'attachment; filename="' + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix,
  797. });
  798. ctx.body = await fs.readFileSync(filePath + uuid + suffix);
  799. } catch (e) {
  800. console.log(e);
  801. }
  802. }
  803. /**
  804. * 更新用户通用报表显示配置
  805. *
  806. * @param {Object} ctx - egg全局context
  807. * @return {void}
  808. */
  809. async updateCustNode(ctx) {
  810. const params = JSON.parse(ctx.request.body.params);
  811. // console.log(params);
  812. const custId = this.ctx.session.sessionUser.accountId;
  813. const newNodeItems = JSON.stringify(params.nodeItems);
  814. const rst = await ctx.service.rptTreeNodeCust.updateCustNode(custId, newNodeItems);
  815. // console.log(rst);
  816. ctx.body = { data: rst };
  817. // ctx.body = { data: { msg: 'test the network' } };
  818. ctx.status = 201;
  819. }
  820. async setCustomDefine(ctx) {
  821. try {
  822. const data = JSON.parse(ctx.request.body.data);
  823. await this.ctx.service.rptCustomDefine.saveCustomSelect(data);
  824. // const sid = data.gather_select ? -1 : data.stage_id;
  825. // const filter = {tid: data.tender_id, sid: sid, rid: data.rpt_tpl_id};
  826. // const count = await ctx.service.rptCustomDefine.count(filter);
  827. // const updateData = {};
  828. // if (data.audit_select) updateData.audit_select = JSON.stringify(data.audit_select);
  829. // if (data.gather_select) updateData.gather_select = JSON.stringify(data.gather_select);
  830. // if (count > 0) {
  831. // await ctx.service.rptCustomDefine.update(updateData, filter);
  832. // } else {
  833. // updateData.tid = data.tender_id;
  834. // updateData.sid = sid;
  835. // updateData.rid = data.rpt_tpl_id;
  836. // await ctx.service.rptCustomDefine.db.insert(ctx.service.rptCustomDefine.tableName, updateData);
  837. // }
  838. const result = await this._getReport(ctx, data);
  839. ctx.body = { err: 0, msg: '', data: result };
  840. } catch (err) {
  841. ctx.helper.log(err);
  842. ctx.body = this.ajaxErrorBody(err, '保存数据出错');
  843. }
  844. }
  845. }
  846. return ReportController;
  847. };
  848. async function checkStg(ctx, params) {
  849. if (ctx.stage === null || ctx.stage === undefined || parseInt(ctx.stage.id) !== parseInt(params.stage_id)) {
  850. await ctx.service.stage.checkStage(params.stage_id);
  851. if (ctx.stage) {
  852. params.stage_order = ctx.stage.curOrder;
  853. }
  854. }
  855. }
  856. async function getAllPagesCommon(ctx, rptTpl, params, option, outputType, baseDir, customSelect) {
  857. const rptDataUtil = new rptDataExtractor();
  858. rptDataUtil.initialize(rptTpl);
  859. const filter = rptDataUtil.getDataRequestFilter();
  860. const rawDataObj = await ctx.service.report.getReportData(params, filter.tables, filter.memFieldKeys,
  861. rptTpl[JV.NODE_CUSTOM_DEFINE], customSelect);
  862. // console.log(rawDataObj);
  863. try {
  864. const printCom = JpcEx.createNew();
  865. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  866. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  867. // let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  868. // defProperties = JSON.parse(defProperties[0].defined_content);
  869. const defProperties = RPT_DEF_PROPERTIES;
  870. // console.log('defProperties: ');
  871. // console.log(defProperties);
  872. // console.log('before assemble');
  873. // fsUtil.writeObjToFile(rawDataObj, 'D:/GitHome/temp/JL_Assemble_RawDataDataBefore' + (new Date()).getTime() + '.js');
  874. const tplData = rptDataUtil.assembleData(ctx, rawDataObj, baseDir, printCom, customSelect);
  875. // console.log(tplData);
  876. if (params.custCfg) {
  877. setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  878. } else {
  879. // setupCustomizeCfg(defProperties, rptTpl, defProperties);
  880. }
  881. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  882. printCom.initialize(rptTpl);
  883. // 在ctx.helper里夹带私货,增加当前期status及times
  884. // ctx.helper.current_stage_status = params.stage_status;
  885. // ctx.helper.current_stage_times = params.stage_times;
  886. printCom.analyzeData(ctx.helper, rptTpl, tplData, defProperties, dftOption, outputType, customSelect);
  887. // console.log(JSON.stringify(rptTpl));
  888. const maxPages = printCom.totalPages;
  889. let pageRst = null;
  890. if (maxPages > 0) {
  891. pageRst = printCom.outputAsSimpleJSONPageArray(ctx.helper, rptTpl, tplData, 1, maxPages, defProperties, params.custCfg, customSelect);
  892. } else {
  893. pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
  894. }
  895. // fsUtil.writeObjToFile(pageRst, 'D:/GitHome/temp/计量testBuiltPageResult.jsp');
  896. // console.log(pageRst);
  897. return pageRst;
  898. } catch (ex) {
  899. console.log('报表数据异常, tender id: ' + params.tender_id);
  900. console.log(ex);
  901. }
  902. }
  903. async function getMultiRptsCommon(ctx, params, outputType, baseDir) {
  904. for (let idx = 0; idx < params.rpt_ids.length; idx++) {
  905. params.rpt_ids[idx] = parseInt(params.rpt_ids[idx]); // 转换一下,以防万一
  906. }
  907. const rptTpls = await ctx.service.rptTpl.getAllTplByIds(params.rpt_ids);
  908. rptTpls.sort(function(rpt1, rpt2) {
  909. return params.rpt_ids.indexOf(rpt1.id) - params.rpt_ids.indexOf(rpt2.id);
  910. });
  911. for (let rtIdx = 0; rtIdx < rptTpls.length; rtIdx++) {
  912. const id = rptTpls[rtIdx].id;
  913. rptTpls[rtIdx] = JSON.parse(rptTpls[rtIdx].rpt_content);
  914. rptTpls[rtIdx].id = id;
  915. }
  916. const rptDataUtil = new rptDataExtractor();
  917. const filterTables = [];
  918. const memFieldKeys = {};
  919. for (const rptTpl of rptTpls) {
  920. rptDataUtil.initialize(rptTpl);
  921. const filter = rptDataUtil.getDataRequestFilter();
  922. // console.log(filter);
  923. for (const table of filter.tables) {
  924. if (filterTables.indexOf(table) < 0 && needCustomTables.indexOf(table) < 0) {
  925. filterTables.push(table);
  926. }
  927. // memFieldKeys[table] = [];
  928. }
  929. for (const tableKeyProp in filter.memFieldKeys) {
  930. if (needCustomTables.indexOf(tableKeyProp) >= 0) continue;
  931. if (!memFieldKeys.hasOwnProperty(tableKeyProp)) {
  932. memFieldKeys[tableKeyProp] = [];
  933. }
  934. for (const mfKey of filter.memFieldKeys[tableKeyProp]) {
  935. if (memFieldKeys[tableKeyProp].indexOf(mfKey) < 0) {
  936. memFieldKeys[tableKeyProp].push(mfKey);
  937. }
  938. }
  939. }
  940. }
  941. const rawDataObj = await ctx.service.report.getReportData(params, filterTables, memFieldKeys, {}, {});
  942. try {
  943. const rptPageRstArray = [];
  944. // 1. 这里只用一份数据,根据实际应用情况,先备份
  945. // const backupData = {};
  946. // for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  947. // backupData[filterTables[filterIdx]] = [];
  948. // Object.assign(backupData[filterTables[filterIdx]], rawDataObj[filterTables[filterIdx]]);
  949. // }
  950. // 2. 一个一个模板创建数据
  951. // let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  952. // defProperties = JSON.parse(defProperties[0].defined_content);
  953. const defProperties = RPT_DEF_PROPERTIES;
  954. for (let tplIdx = 0; tplIdx < rptTpls.length; tplIdx++) {
  955. const rptTpl = (rptTpls[tplIdx]._doc) ? rptTpls[tplIdx]._doc : rptTpls[tplIdx];
  956. rptDataUtil.initialize(rptTpl);
  957. let customSelect = rptTpl[JV.NODE_CUSTOM_DEFINE] && rptTpl[JV.NODE_CUSTOM_DEFINE][JV.NODE_CUS_AUDIT_SELECT].enable
  958. ? await ctx.service.rptCustomDefine.getCustomDefine(params.tender_id, params.stage_id, rptTpl.id)
  959. : await ctx.service.rptCustomDefine.getCustomDefine(params.tender_id, -1, rptTpl.id);
  960. if (rptTpl[JV.NODE_CUSTOM_DEFINE] && rptTpl[JV.NODE_CUSTOM_DEFINE][JV.NODE_CUS_CHANGE_SELECT]) {
  961. customSelect = { tid: params.tender_id, rid: params.rpt_tpl_id, sid: -1, change_select: params.customSelect[tplIdx].change_select };
  962. }
  963. // 从汇总的rawDataObj中拷贝所需数据表至curRawDataObj,以供后续使用
  964. const curRawDataObj = {};
  965. const filter = rptDataUtil.getDataRequestFilter();
  966. for (const table of filter.tables) {
  967. curRawDataObj[table] = ctx.helper.clone(rawDataObj[table]);
  968. }
  969. // 如果是用户交互类型的表,则应该单独获取数据
  970. if ((params.customSelect && params.customSelect[tplIdx]) || rptTpl[JV.NODE_CUSTOM_DEFINE][JV.NODE_CUS_OPTION]) {
  971. const cfTables = [],
  972. cmFieldKeys = [];
  973. const curFilter = rptDataUtil.getDataRequestFilter();
  974. for (const table of curFilter.tables) {
  975. if (needCustomTables.indexOf(table) >= 0) {
  976. cfTables.push(table);
  977. }
  978. }
  979. for (const tableKeyProp in filter.memFieldKeys) {
  980. if (needCustomTables.indexOf(tableKeyProp) < 0) continue;
  981. if (!cmFieldKeys.hasOwnProperty(tableKeyProp)) {
  982. cmFieldKeys[tableKeyProp] = [];
  983. }
  984. for (const mfKey of filter.memFieldKeys[tableKeyProp]) {
  985. if (cmFieldKeys[tableKeyProp].indexOf(mfKey) < 0) {
  986. cmFieldKeys[tableKeyProp].push(mfKey);
  987. }
  988. }
  989. }
  990. const customRawDataObj = await ctx.service.report.getReportData(params, cfTables, cmFieldKeys,
  991. rptTpl[JV.NODE_CUSTOM_DEFINE], customSelect);
  992. for (const prop in customRawDataObj) {
  993. curRawDataObj[prop] = customRawDataObj[prop];
  994. }
  995. }
  996. const tplData = rptDataUtil.assembleData(ctx, curRawDataObj, baseDir, null, customSelect);
  997. const printCom = JpcEx.createNew();
  998. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  999. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  1000. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  1001. if (params.custCfg) setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  1002. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  1003. printCom.initialize(rptTpl);
  1004. // console.log(rptTpl);
  1005. printCom.analyzeData(ctx.helper, rptTpl, tplData, defProperties, dftOption, outputType, customSelect);
  1006. const maxPages = printCom.totalPages;
  1007. let pageRst = null;
  1008. // console.log(maxPages);
  1009. if (maxPages > 0) {
  1010. pageRst = printCom.outputAsSimpleJSONPageArray(ctx.helper, rptTpl, tplData, 1, maxPages, defProperties, params.custCfg, customSelect);
  1011. } else {
  1012. pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
  1013. }
  1014. rptPageRstArray.push(pageRst);
  1015. // 注意:这里需要把备份数据assign回去!!!
  1016. // if (tplIdx < rptTpls.length - 1) {
  1017. // for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  1018. // backupData[filterTables[filterIdx]] = [];
  1019. // Object.assign(rawDataObj[filterTables[filterIdx]], backupData[filterTables[filterIdx]]);
  1020. // }
  1021. // }
  1022. }
  1023. return rptPageRstArray;
  1024. } catch (ex) {
  1025. console.log('报表数据异常(getMultiRptsCommon): project_id ' + params.project_id + ', tender_id: ' + params.tender_id + ', stage_id: ' + params.stage_id);
  1026. console.log(ex);
  1027. } finally {
  1028. //
  1029. }
  1030. }
  1031. function setupCustomizeCfg(customizeCfg, rptTpl, defProperties) {
  1032. const tmpObj = {};
  1033. // 1. 字体
  1034. const newFonts = [];
  1035. for (const font of defProperties.fonts) {
  1036. const copyFont = {};
  1037. copyFont.ID = font.ID;
  1038. for (const fontProp of JV.FONT_PROPS) {
  1039. copyFont[fontProp] = font[fontProp];
  1040. }
  1041. newFonts.push(copyFont);
  1042. tmpObj[font.ID] = copyFont;
  1043. }
  1044. const private_setup_font = function(propStr, newFont) {
  1045. if (tmpObj[propStr]) {
  1046. tmpObj[propStr].Name = newFont.Name;
  1047. tmpObj[propStr].FontHeight = String(newFont.FontHeight);
  1048. tmpObj[propStr].FontBold = newFont.FontBold;
  1049. tmpObj[propStr].FontItalic = newFont.FontItalic;
  1050. tmpObj[propStr].FontUnderline = newFont.FontUnderline;
  1051. }
  1052. };
  1053. for (const custFont of customizeCfg.fonts) {
  1054. switch (custFont.CfgDispName) {
  1055. case '表标题':
  1056. private_setup_font('ReportTitle_Main', custFont);
  1057. break;
  1058. case '列标题':
  1059. private_setup_font('HeaderColumn', custFont);
  1060. private_setup_font('FooterColumn', custFont);
  1061. break;
  1062. case '正文内容':
  1063. private_setup_font('Content', custFont);
  1064. break;
  1065. case '合计':
  1066. private_setup_font('GrandTotal', custFont);
  1067. private_setup_font('SectionTotal', custFont);
  1068. break;
  1069. case '表眉/表脚':
  1070. private_setup_font('Header', custFont);
  1071. private_setup_font('Footer', custFont);
  1072. break;
  1073. default:
  1074. break;
  1075. }
  1076. }
  1077. // 1.1 窄体
  1078. if (tmpObj.Content_Narrow) {
  1079. if (customizeCfg.isNarrow) {
  1080. tmpObj.Content_Narrow.Name = 'Arial Narrow';
  1081. } else {
  1082. if (tmpObj.Content) {
  1083. tmpObj.Content_Narrow.Name = tmpObj.Content.Name;
  1084. } else {
  1085. tmpObj.Content_Narrow.Name = '宋体';
  1086. }
  1087. }
  1088. }
  1089. defProperties.fonts = newFonts;
  1090. // 2. 页边距
  1091. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT] = customizeCfg.margins[JV.PROP_LEFT] / 10;
  1092. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT] = customizeCfg.margins[JV.PROP_RIGHT] / 10;
  1093. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_TOP] = customizeCfg.margins[JV.PROP_TOP] / 10;
  1094. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM] = customizeCfg.margins[JV.PROP_BOTTOM] / 10;
  1095. // 3. 边框宽度
  1096. if (customizeCfg.hasOwnProperty('borderThick')) {
  1097. for (let i = 0; i < defProperties.styles.length; i++) {
  1098. const style = defProperties.styles[i];
  1099. if (style.ID === 'BORDER_ALL_AROUND') {
  1100. for (const border of style.border_style) {
  1101. border.LineWeight = customizeCfg.borderThick;
  1102. }
  1103. }
  1104. }
  1105. }
  1106. // 4. 边框竖线
  1107. if (!(customizeCfg.showVerticalLine)) {
  1108. const private_copy_border = function(src) {
  1109. const rst = {};
  1110. rst.Position = src.Position;
  1111. rst.LineWeight = src.LineWeight;
  1112. rst.DashStyle = src.DashStyle;
  1113. rst.Color = src.Color;
  1114. return rst;
  1115. };
  1116. const newStyles = [];
  1117. for (let i = 0; i < defProperties.styles.length; i++) {
  1118. const style = defProperties.styles[i];
  1119. newStyles.push(style);
  1120. if (style.ID === 'BORDER_ALL_AROUND') {
  1121. const newStyle = {};
  1122. newStyle.ID = style.ID;
  1123. newStyle.CfgDispName = style.CfgDispName;
  1124. newStyle.border_style = [];
  1125. for (const border of style.border_style) {
  1126. const newBorder = private_copy_border(border);
  1127. newStyle.border_style.push(newBorder);
  1128. if (border.Position === 'Left' || border.Position === 'Right') {
  1129. newBorder.LineWeight = 0;
  1130. }
  1131. }
  1132. newStyles[newStyles.length - 1] = newStyle;
  1133. }
  1134. }
  1135. defProperties.styles = newStyles;
  1136. }
  1137. // 5. 补0
  1138. const private_Setup_Format = function(tabFields) {
  1139. if (tabFields) {
  1140. for (const tabField of tabFields) {
  1141. if (tabField[JV.PROP_FORMAT]) {
  1142. tabField[JV.PROP_FORMAT] = tabField[JV.PROP_FORMAT].replace(new RegExp('#', 'gm'), '0');
  1143. }
  1144. }
  1145. }
  1146. };
  1147. if (customizeCfg.fillZero) {
  1148. if (rptTpl[JV.NODE_FLOW_INFO]) {
  1149. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS]);
  1150. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_PAGE_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS]);
  1151. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS]);
  1152. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP] && rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES][JV.PROP_SUM_FIELDS]);
  1153. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  1154. for (const discrete of rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  1155. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  1156. }
  1157. }
  1158. if (rptTpl[JV.NODE_FLOW_INFO_EX]) {
  1159. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS]);
  1160. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_PAGE_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS]);
  1161. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_SEG_SUM]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS]);
  1162. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_SUM_FIELDS]);
  1163. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP] && rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES]) private_Setup_Format(rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_LINES][JV.PROP_SUM_FIELDS]);
  1164. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  1165. for (const discrete of rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  1166. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  1167. }
  1168. }
  1169. }
  1170. } else if (rptTpl[JV.NODE_BILL_INFO]) {
  1171. if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_BILL_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_BILL_INFO][JV.NODE_BILL_CONTENT][JV.PROP_BILL_FIELDS]);
  1172. if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  1173. for (const discrete of rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  1174. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  1175. }
  1176. }
  1177. } else if (rptTpl[JV.NODE_CROSS_INFO]) {
  1178. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_CONTENT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_CONTENT][JV.TAB_CROSS_FIELDS]);
  1179. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW][JV.TAB_CROSS_FIELDS]);
  1180. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL][JV.TAB_CROSS_FIELDS]);
  1181. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL_SUM]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_COL_SUM][JV.TAB_CROSS_FIELDS]);
  1182. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_EXT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_EXT][JV.TAB_CROSS_FIELDS]);
  1183. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_SUM_EXT]) private_Setup_Format(rptTpl[JV.NODE_CROSS_INFO][JV.NODE_CROSS_ROW_SUM_EXT][JV.TAB_CROSS_FIELDS]);
  1184. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  1185. for (const discrete of rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  1186. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  1187. }
  1188. }
  1189. }
  1190. }
  1191. }
  1192. function isFileExisted(file) {
  1193. return new Promise(function(resolve, reject) {
  1194. fs.access(file, err => {
  1195. if (err) {
  1196. reject(false);
  1197. } else {
  1198. resolve(true);
  1199. }
  1200. });
  1201. });
  1202. }
  1203. function fillWaterMark(pageRstArray) {
  1204. const orgWaterMarkWidth = 600;
  1205. const orgWaterMarkHeight = 288;
  1206. const createWaterCell = function(area) {
  1207. const w = area[JV.PROP_RIGHT] - area[JV.PROP_LEFT];
  1208. const h = area[JV.PROP_BOTTOM] - area[JV.PROP_TOP];
  1209. const left = Math.round(area[JV.PROP_LEFT] + w / 2 - orgWaterMarkWidth / 2);
  1210. const right = left + orgWaterMarkWidth;
  1211. const top = Math.round(area[JV.PROP_TOP] + h / 2 - orgWaterMarkHeight / 2);
  1212. const bottom = top + orgWaterMarkHeight;
  1213. return {
  1214. signature_name: JV.SIGNATURE_NAME_DUMMY_WATER_MARK,
  1215. path: '/public/images/not_Approve.png',
  1216. sign_path: '/public/images/not_Approve.png',
  1217. pic: null,
  1218. control: 'Title',
  1219. style: 'Default_None',
  1220. area: {
  1221. Left: left,
  1222. Right: right,
  1223. Top: top,
  1224. Bottom: bottom,
  1225. },
  1226. };
  1227. };
  1228. for (const pageRst of pageRstArray) {
  1229. for (const page of pageRst.items) {
  1230. page[JV.PROP_WATERMARK_CELLS] = [];
  1231. if (page[JV.PROP_PAGE_MERGE_BORDER]) {
  1232. const wmCell = createWaterCell(page[JV.PROP_PAGE_MERGE_BORDER]);
  1233. page[JV.PROP_WATERMARK_CELLS].push(wmCell);
  1234. } else if (page[JV.PAGE_SPECIAL_MERGE_POS]) {
  1235. if (page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_LEFT]) {
  1236. for (let i = 0; i < page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_LEFT].length; i++) {
  1237. const area = {};
  1238. area[JV.PROP_LEFT] = page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_LEFT][i];
  1239. area[JV.PROP_RIGHT] = page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_RIGHT][i];
  1240. area[JV.PROP_TOP] = page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_TOP][i];
  1241. area[JV.PROP_BOTTOM] = page[JV.PAGE_SPECIAL_MERGE_POS][JV.PROP_BOTTOM][i];
  1242. const wmCell = createWaterCell(area);
  1243. page[JV.PROP_WATERMARK_CELLS].push(wmCell);
  1244. }
  1245. }
  1246. }
  1247. }
  1248. }
  1249. }
  1250. async function encodeSignatureDataUri(roleRel, baseDir) {
  1251. if (roleRel) {
  1252. for (const singleRoleRel of roleRel) {
  1253. if (singleRoleRel.rel_content !== null && singleRoleRel.rel_content !== undefined && singleRoleRel.rel_content !== '') {
  1254. const roleRelContent = JSON.parse(singleRoleRel.rel_content);
  1255. for (const role of roleRelContent) {
  1256. // console.log(role);
  1257. if (role.sign_path !== '') {
  1258. const filePath = baseDir + '/app' + role.sign_path;
  1259. try {
  1260. const res = await isFileExisted(filePath);
  1261. if (res) {
  1262. const bData = fs.readFileSync(filePath);
  1263. const base64Str = bData.toString('base64');
  1264. const datauri = 'data:image/png;base64,' + base64Str;
  1265. role.sign_pic = datauri;
  1266. } else {
  1267. console.log('文件不存在:' + filePath);
  1268. }
  1269. } catch (err) {
  1270. console.error(err);
  1271. }
  1272. }
  1273. }
  1274. singleRoleRel.rel_content = JSON.stringify(roleRelContent);
  1275. } else {
  1276. singleRoleRel.rel_content = [];
  1277. }
  1278. }
  1279. }
  1280. }
  1281. async function encodeDummySignatureDataUri(pageRst, baseDir) {
  1282. if (pageRst) {
  1283. for (const page of pageRst.items) {
  1284. for (const signature of page[JV.PROP_SIGNATURE_CELLS]) {
  1285. if (signature.signature_name === JV.SIGNATURE_NAME_DUMMY) {
  1286. if (signature.path !== '') {
  1287. const filePath = baseDir + '/app' + signature.path;
  1288. try {
  1289. const res = await isFileExisted(filePath);
  1290. if (res) {
  1291. const bData = fs.readFileSync(filePath);
  1292. const base64Str = bData.toString('base64');
  1293. const datauri = 'data:image/png;base64,' + base64Str;
  1294. signature.pic = datauri;
  1295. signature.path = '';
  1296. } else {
  1297. console.log('文件不存在:' + filePath);
  1298. }
  1299. } catch (err) {
  1300. console.error(err);
  1301. }
  1302. }
  1303. }
  1304. }
  1305. // 考虑优化,水印只需要一张即可,不需要每页都设置
  1306. // for (const signature of page[JV.PROP_WATERMARK_CELLS]) {
  1307. // if (signature.path !== '') {
  1308. // const filePath = baseDir + '/app' + signature.path;
  1309. // try {
  1310. // const res = await isFileExisted(filePath);
  1311. // if (res) {
  1312. // const bData = fs.readFileSync(filePath);
  1313. // const base64Str = bData.toString('base64');
  1314. // const datauri = 'data:image/png;base64,' + base64Str;
  1315. // signature.pic = datauri;
  1316. // signature.path = '';
  1317. // } else {
  1318. // console.log('文件不存在:' + filePath);
  1319. // }
  1320. // } catch (err) {
  1321. // console.error(err);
  1322. // }
  1323. // }
  1324. // }
  1325. }
  1326. }
  1327. }
  1328. async function getWatermarkPicData(pageRst, baseDir) {
  1329. let rst = '';
  1330. if (pageRst) {
  1331. for (const page of pageRst.items) {
  1332. for (const signature of page[JV.PROP_WATERMARK_CELLS]) {
  1333. if (signature.path !== '') {
  1334. const filePath = baseDir + '/app' + signature.path;
  1335. try {
  1336. const res = await isFileExisted(filePath);
  1337. if (res) {
  1338. const bData = fs.readFileSync(filePath);
  1339. const base64Str = bData.toString('base64');
  1340. rst = 'data:image/png;base64,' + base64Str;
  1341. break;
  1342. } else {
  1343. console.log('文件不存在:' + filePath);
  1344. }
  1345. } catch (err) {
  1346. console.error(err);
  1347. }
  1348. }
  1349. if (rst !== null) break;
  1350. }
  1351. }
  1352. }
  1353. return rst;
  1354. }
  1355. async function createExportRequestJob(ctx) {
  1356. const params = JSON.parse(ctx.request.body.params);
  1357. // const uuidArr = params.uuidArr;
  1358. const baseDir = this.app.baseDir;
  1359. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids, params.stage_id)) : [];
  1360. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  1361. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  1362. for (let idx = 0; idx < pageRstArr.length; idx++) {
  1363. let roleRel = null;
  1364. for (const roleR of roleRelArr) {
  1365. if (roleR.rpt_id === params.rpt_ids[idx]) {
  1366. roleRel = JSON.parse(roleR.rel_content);
  1367. break;
  1368. }
  1369. }
  1370. if (params.exportType === 'xlsx') {
  1371. const zip = rpt_xl_util.exportExcel(pageRstArr[idx], params.pageSize, null, params.isOneSheet, null, null, baseDir, roleRel, null); // 给个null报表名称,返回zip对象自己处理,这样就不用改接口结构了
  1372. zip.generateNodeStream({ type: 'nodebuffer', streamFiles: true })
  1373. .pipe(fs.createWriteStream(baseDir + '/app/public/download/' + params.uuidArr[idx] + '.xlsx'));
  1374. } else if (params.exportType === 'pdf') {
  1375. // PDF的后期补上
  1376. }
  1377. }
  1378. }
  1379. function mergeTextSignature(isTxtSignature, status, pageData, singleRoleRel, rpt_ids) {
  1380. // 依据需求,有些用户不需要签名图片,那么从源头上把签名从signature_cells转移到cells下,省得后续 预览、打印、导出PDF、导出EXCEL每个地方都改动
  1381. const _mergeSingle = function(_page, _roleRelList, isDeleteSignCell) {
  1382. // console.log(_roleRelList);
  1383. let roleRelContent = [];
  1384. if (_roleRelList && _roleRelList.rel_content !== null && _roleRelList.rel_content !== undefined && _roleRelList.rel_content !== '') {
  1385. roleRelContent = JSON.parse(_roleRelList.rel_content);
  1386. };
  1387. for (const page of _page.items) {
  1388. if (page.signature_cells) {
  1389. const deleteSCellsIdx = [];
  1390. for (let scIdx = 0; scIdx < page.signature_cells.length; scIdx++) {
  1391. const sCell = page.signature_cells[scIdx];
  1392. sCell.Value = ''; // 这里要先清除原有信息
  1393. if (sCell.signature_name !== JV.SIGNATURE_NAME_DUMMY) {
  1394. // console.log(sCell);
  1395. sCell.path = '';
  1396. sCell.pic = '';
  1397. }
  1398. for (const role_rel of roleRelContent) {
  1399. if (sCell.signature_name === role_rel.signature_name) {
  1400. if (status === 3) {
  1401. sCell.Value = role_rel.user_name; // 只有审核通过了才需要文本签名内容,但不管如何,都不影响迁移
  1402. }
  1403. const newCell = {
  1404. font: 'Footer',
  1405. control: sCell.control,
  1406. style: sCell.style,
  1407. Value: sCell.Value,
  1408. area: { Left: sCell.area.Left, Right: sCell.area.Right, Top: sCell.area.Top, Bottom: sCell.area.Bottom },
  1409. };
  1410. page.cells.push(newCell); // 迁移
  1411. deleteSCellsIdx.push(scIdx);
  1412. break;
  1413. }
  1414. }
  1415. }
  1416. // 删除 page.signature_cells 签名(草图不能删);
  1417. if (isDeleteSignCell) {
  1418. for (let dIdx = deleteSCellsIdx.length - 1; dIdx >= 0; dIdx--) {
  1419. page.signature_cells.splice(deleteSCellsIdx[dIdx], 1);
  1420. }
  1421. }
  1422. }
  1423. }
  1424. };
  1425. if (isTxtSignature) {
  1426. if (pageData instanceof Array) {
  1427. pageData.forEach((dtlPage, index) => {
  1428. let dftRolRel = [];
  1429. const rpt_id = rpt_ids[index];
  1430. for (let roleRel of singleRoleRel) {
  1431. if (roleRel.rpt_id === rpt_id) {
  1432. dftRolRel = roleRel;
  1433. }
  1434. }
  1435. // console.log(rptTpls[rtIdx].id)
  1436. _mergeSingle(dtlPage, dftRolRel, true);
  1437. });
  1438. } else {
  1439. _mergeSingle(pageData, singleRoleRel, false);
  1440. }
  1441. }
  1442. }
  1443. function mergeSignAudit(pageData, currRoleRelList, currAuditList) {
  1444. for (const page of pageData.items) {
  1445. if (page.signature_audit_cells) {
  1446. for (const sCell of page.signature_audit_cells) {
  1447. sCell.Value = ''; // 这里要先清除原有信息
  1448. if (currRoleRelList && currRoleRelList.length > 0) {
  1449. for (const role_rel of currRoleRelList) {
  1450. if (sCell.signature_name === role_rel.signature_name + '_审核意见') {
  1451. let preDate = '';
  1452. sCell.Value = '同意'; // 只有选择了签名的,才需要初始化一个默认的意见(之前的逻辑在有多个签名,哪怕只选择了一个,其他的意见都会有默认意见)
  1453. if (currAuditList && currAuditList.length > 0) {
  1454. for (const audit_rel of currAuditList) {
  1455. if (role_rel.acc_id === audit_rel.aid) {
  1456. if (audit_rel.end_time > preDate && audit_rel.status === 3) {
  1457. sCell.Value = audit_rel.opinion;
  1458. preDate = audit_rel.end_time;
  1459. }
  1460. // 不能break,实际会有多个审核意见,以最后一个为准
  1461. }
  1462. }
  1463. }
  1464. break;
  1465. }
  1466. }
  1467. }
  1468. }
  1469. }
  1470. }
  1471. }
  1472. function mergeSignDate(pageData, current_stage_id, currRoleRelList, STAGE_AUDIT, STAGE_AUDIT_ORG, STAGE_LIST) {
  1473. if (currRoleRelList && currRoleRelList.length > 0 && STAGE_AUDIT && STAGE_AUDIT.length > 0) {
  1474. for (let rridx = 0; rridx < currRoleRelList.length; rridx++) {
  1475. const role_rel = currRoleRelList[rridx];
  1476. if (role_rel.sign_date === undefined || role_rel.sign_date === null || role_rel.sign_date === '') {
  1477. const dftDate = _getSignDateByAllScenarios(role_rel.acc_id, current_stage_id, STAGE_AUDIT, STAGE_AUDIT_ORG, STAGE_LIST);
  1478. role_rel.sign_date = dftDate;
  1479. }
  1480. }
  1481. }
  1482. if (currRoleRelList && currRoleRelList.length > 0) {
  1483. for (const page of pageData.items) {
  1484. if (page.signature_date_cells) {
  1485. for (const sCell of page.signature_date_cells) {
  1486. sCell.Value = _getSignDateDftName();
  1487. for (const role_rel of currRoleRelList) {
  1488. if (sCell.signature_name === role_rel.signature_name + '_签字日期') {
  1489. if (role_rel.sign_date !== '') {
  1490. if (typeof role_rel.sign_date === 'string') {
  1491. role_rel.sign_date = new Date(role_rel.sign_date);
  1492. }
  1493. sCell.Value = role_rel.sign_date.Format(role_rel.sign_date_format);
  1494. }
  1495. break;
  1496. }
  1497. }
  1498. }
  1499. }
  1500. }
  1501. }
  1502. }
  1503. function _getSignDateByAllScenarios(userAccId, current_stage_id, STAGE_AUDIT, STAGE_AUDIT_ORG, STAGE_LIST) {
  1504. let rst = '';
  1505. let hasAudit = false;
  1506. for (const stg_audit of STAGE_AUDIT) {
  1507. if (stg_audit.aid === userAccId) {
  1508. hasAudit = true;
  1509. if (stg_audit.status === 3) {
  1510. rst = stg_audit.end_time;
  1511. } else {
  1512. rst = '';
  1513. }
  1514. // break; //因为实际业务中会有反复,所以就不break了,一直判断,以最后一个为准
  1515. }
  1516. }
  1517. let isOrgRpt = false;
  1518. for (const stg of STAGE_LIST) {
  1519. if (stg.id === current_stage_id) {
  1520. if (stg.user_id === userAccId) {
  1521. isOrgRpt = true;
  1522. }
  1523. break;
  1524. }
  1525. }
  1526. if (isOrgRpt && !hasAudit && STAGE_AUDIT_ORG && STAGE_AUDIT_ORG.length > 0) {
  1527. if (STAGE_AUDIT_ORG[0].begin_time && STAGE_AUDIT_ORG[0].begin_time !== '' && STAGE_AUDIT_ORG[0].begin_time.length > 20) {
  1528. rst = STAGE_AUDIT_ORG[0].begin_time;
  1529. }
  1530. }
  1531. if (!isOrgRpt && !hasAudit) {
  1532. // 非审批流程人员以及非原报,则显示期截至时间
  1533. for (const stg of STAGE_LIST) {
  1534. if (stg.id === current_stage_id && stg.period) {
  1535. const period = stg.period.split(' ~ ');
  1536. if (period.length === 2) {
  1537. rst = period[1];
  1538. }
  1539. }
  1540. }
  1541. }
  1542. return rst;
  1543. }
  1544. function _getSignDateDftName() {
  1545. return ' 年 月 日';
  1546. }
  1547. async function _chkRawPicSize(pageData, baseDir) {
  1548. let rst = 0;
  1549. const picKeys = [];
  1550. for (let pi = 0; pi < pageData.items.length; pi++) {
  1551. // 每页判断
  1552. for (let ci = 0; ci < pageData.items[pi][JV.PROP_SIGNATURE_CELLS].length; ci++) {
  1553. const picPath = pageData.items[pi][JV.PROP_SIGNATURE_CELLS][ci].path;
  1554. // if (picPath && picPath.indexOf('/sign') < 0 && picKeys.indexOf(picPath) < 0) {
  1555. if (picPath && picPath !== '' && picKeys.indexOf(picPath) < 0) {
  1556. // 签名图片也要计算在内,反正不重复
  1557. picKeys.push(picPath);
  1558. }
  1559. // signature_cells PROP_SIGNATURE_CELLS
  1560. }
  1561. }
  1562. // console.log(picKeys);
  1563. for (const pKey of picKeys) {
  1564. const filePath = `${baseDir}/app${pKey}`;
  1565. console.log('filePath: ' + filePath);
  1566. let isExist = false;
  1567. try {
  1568. isExist = await isFileExisted(filePath);
  1569. } catch (ex) {
  1570. isExist = false;
  1571. }
  1572. console.log('isExist: ' + isExist);
  1573. if (isExist) {
  1574. const obj = fs.statSync(filePath);
  1575. if (obj) {
  1576. rst += obj.size;
  1577. } else {
  1578. console.log('no statSync resutl: ' + filePath);
  1579. }
  1580. // rst += fs.statSync(filePath).size;
  1581. } else {
  1582. console.log(`${pKey} not exists!`);
  1583. }
  1584. }
  1585. return rst;
  1586. }
  1587. function _resetPageDataByBreaks(pageDataArr, breakAmt, rpt_names, newRptNames) {
  1588. const rst = [];
  1589. for (let pi = 0; pi < pageDataArr.length; pi++) {
  1590. const pageItem = pageDataArr[pi];
  1591. const currentRptName = rpt_names[pi];
  1592. if (pageItem.items.length > breakAmt) {
  1593. let pa = Math.floor(pageItem.items.length / breakAmt);
  1594. if (pageItem.items.length % breakAmt > 0) {
  1595. pa++;
  1596. }
  1597. for (let idx = 0; idx < pa; idx++) {
  1598. const newPageDataObj = { items: [] };
  1599. // newPageDataObj[JV.NODE_PAGE_INFO] = JSON.parse(JSON.stringify(pageItem[JV.NODE_PAGE_INFO]));
  1600. newPageDataObj[JV.NODE_PAGE_INFO] = pageItem[JV.NODE_PAGE_INFO];
  1601. // newPageDataObj[JV.BAND_PROP_MERGE_BAND] = JSON.parse(JSON.stringify(pageItem[JV.BAND_PROP_MERGE_BAND]));
  1602. newPageDataObj[JV.BAND_PROP_MERGE_BAND] = pageItem[JV.BAND_PROP_MERGE_BAND];
  1603. newPageDataObj[JV.NODE_FONT_COLLECTION] = pageItem[JV.NODE_FONT_COLLECTION];
  1604. newPageDataObj[JV.NODE_STYLE_COLLECTION] = pageItem[JV.NODE_STYLE_COLLECTION];
  1605. newPageDataObj[JV.NODE_CONTROL_COLLECTION] = pageItem[JV.NODE_CONTROL_COLLECTION];
  1606. for (let dIdx = idx * breakAmt; dIdx < (Math.min((idx + 1) * breakAmt, pageItem.items.length)); dIdx++) {
  1607. newPageDataObj.items.push(pageItem.items[dIdx]);
  1608. }
  1609. rst.push(newPageDataObj);
  1610. newRptNames.push(currentRptName + '_' + (idx + 1));
  1611. }
  1612. } else {
  1613. rst.push(pageItem);
  1614. newRptNames.push(currentRptName);
  1615. }
  1616. }
  1617. return rst;
  1618. };