report_controller.js 84 KB

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