report_controller.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  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 accountGroup = require('../const/account_group').group;
  8. const JpcEx = require('../reports/rpt_component/jpc_ex');
  9. const JV = require('../reports/rpt_component/jpc_value_define');
  10. const rpt_xl_util = require('../reports/util/rpt_excel_util');
  11. const rptDataExtractor = require('../reports/util/rpt_calculation_data_util');
  12. const fsUtil = require('../public/js/fsUtil');
  13. const fs = require('fs');
  14. const rptCronJob = require('../reports/util/rpt_tmp_file_sweep');
  15. const RPT_DEF_PROPERTIES = require('../const/report_defined_properties');
  16. module.exports = app => {
  17. class ReportController extends app.BaseController {
  18. /**
  19. * 报表显示页面
  20. *
  21. * @param {Object} ctx - egg全局context
  22. * @return {void}
  23. */
  24. async index(ctx) {
  25. try {
  26. const tender = ctx.tender;
  27. const stage = ctx.stage;
  28. // console.log(tender.data);
  29. // console.log(tender.info);
  30. let stage_id = -1;
  31. let stage_order = -1;
  32. let sorder = -1;
  33. let stage_times = -1;
  34. let stage_status = -1;
  35. const treeNodes = await ctx.service.rptTreeNode.getNodesByProjectId([-1, tender.data.project_id]);
  36. const custCfg = await ctx.service.rptCustomizeCfg.getCustomizeCfgByUserId('Administrator');
  37. const stageList = await ctx.service.stage.getValidStagesShort(tender.id);
  38. const prjAccList = await ctx.service.projectAccount.getAllAccountByProjectId(tender.data.project_id);
  39. const roleList = await ctx.service.signatureRole.getSignatureRolesByTenderId(tender.id);
  40. // const allTpls = await ctx.service.rptTpl.getAllTplByIds(tmpRptIds);
  41. // for (const tpl of allTpls) {
  42. // const fName = tpl.id + '_' + tpl.rpt_tpl_name + '.js';
  43. // console.log('fName: ' + fName);
  44. // fsUtil.writeObjToFile(tpl, 'D:/Temp/计量临时/' + fName);
  45. // }
  46. // 完成历史任务,下一批
  47. // const filePath = 'D:/Temp/计量临时/';
  48. // const tplFiles = [];
  49. // fs.readdir(filePath, (err, files) => {
  50. // if (err) throw err;
  51. // files.forEach(file => {
  52. // const fPath = filePath + file;
  53. // // console.log('\'' + fPath + '\'');
  54. // tplFiles.push(fPath);
  55. // });
  56. // });
  57. //
  58. // setTimeout(function() {
  59. // console.log(tplFiles);
  60. // }, 2000);
  61. // 下一批
  62. // let cnt = 0;
  63. // for (const file of rptFiles) {
  64. // const tplObj = JSON.parse(fs.readFileSync(file, 'utf-8'));
  65. // const rst = await ctx.service.rptTpl.insertRptTpl(tplObj);
  66. // cnt++;
  67. // console.log(file);
  68. // }
  69. // console.log(cnt + ' 完成!');
  70. // console.log(maxStageAmt[0].maxAmt);
  71. // if ((stage === null || stage === undefined) && stageList.length > 0) {
  72. // await ctx.service.stage.checkStage(stageList[stageList.length - 1].id);
  73. // stage = ctx.stage;
  74. // }
  75. if (stage !== null && stage !== undefined) {
  76. stage_id = stage.id;
  77. stage_order = stage.order;
  78. sorder = stage.curOrder;
  79. stage_times = stage.times;
  80. stage_status = stage.status;
  81. }
  82. for (const prjAcc of prjAccList) {
  83. prjAcc.account_group = accountGroup[prjAcc.account_group];
  84. }
  85. const renderData = {
  86. tender: tender.data,
  87. tenderInfo: tender.info,
  88. rpt_tpl_data: JSON.stringify(treeNodes),
  89. cust_cfg: JSON.stringify(custCfg),
  90. project_id: tender.data.project_id,
  91. tender_id: tender.id,
  92. tender_name: tender.data.name,
  93. stg_id: stage_id,
  94. stg_order: stage_order,
  95. cur_order: sorder,
  96. stg_times: stage_times,
  97. stg_status: stage_status,
  98. stage_list: JSON.stringify(stageList),
  99. prj_account_list: JSON.stringify(prjAccList),
  100. role_list: JSON.stringify(roleList),
  101. tenderMenu,
  102. preUrl: '/tender/' + tender.id,
  103. measureType,
  104. // jsFiles: this.app.jsFiles.common.concat(this.app.jsFiles.ledger.explode),
  105. };
  106. await this.layout('report/index.ejs', renderData, 'report/rpt_all_popup.ejs');
  107. // await this.layout('report/index.ejs', renderData);
  108. // 在这里启动一个cron job,删除临时创建的excel文件
  109. if (!rptCronJob.started) {
  110. try {
  111. // console.log('rptCronJob.started: ' + rptCronJob.started);
  112. rptCronJob.started = true;
  113. rptCronJob.createJob(null, this.app.baseDir + '/app/public/download');
  114. } catch (ex) {
  115. rptCronJob.started = false;
  116. }
  117. }
  118. } catch (err) {
  119. this.log(err);
  120. console.log(err);
  121. // ctx.redirect('/tender/' + ctx.tender.id);
  122. }
  123. }
  124. /**
  125. * 报表打印页面
  126. *
  127. * @param {Object} ctx - egg全局context
  128. * @return {void}
  129. */
  130. async showPrintPage(ctx) {
  131. try {
  132. // const params = JSON.parse(ctx.request.body.params);
  133. const pageSize = ctx.params.size;
  134. // console.log('pageSize: ' + pageSize);
  135. const renderData = {
  136. size: pageSize,
  137. // orientation: params.orientation,
  138. };
  139. if (pageSize === 'A3') {
  140. await ctx.render('report/rpt_printA3.ejs', renderData);
  141. } else {
  142. await ctx.render('report/rpt_print.ejs', renderData);
  143. }
  144. } catch (err) {
  145. this.log(err);
  146. console.log(err);
  147. }
  148. }
  149. /**
  150. * 获取报表数据
  151. *
  152. * @param {Object} ctx - egg全局context
  153. * @return {void}
  154. */
  155. async getReport(ctx) {
  156. try {
  157. // console.log('in getReport');
  158. const params = JSON.parse(ctx.request.body.params);
  159. // console.log(params);
  160. let rptTpl = await ctx.service.rptTpl.getTplById(params.rpt_tpl_id);
  161. if (!rptTpl || rptTpl.length !== 1) {
  162. throw '获取模板失败';
  163. }
  164. rptTpl = JSON.parse(rptTpl[0].rpt_content);
  165. // console.log('get the template!');
  166. const pageRst = await getAllPagesCommon(ctx, rptTpl, params, JV.PAGING_OPTION_NORMAL, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  167. // console.log(pageRst);
  168. const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  169. const stgAudit = await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times);
  170. // console.log('after role stage!');
  171. // console.log(roleRel);
  172. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  173. await encodeDummySignatureDataUri(pageRst, this.app.baseDir);
  174. // console.log('encodeSignatureDataUri!');
  175. ctx.body = { data: pageRst, signatureRelInfo: roleRel, stageAudit: stgAudit };
  176. // ctx.body = { data: { msg: 'test the network' } };
  177. ctx.status = 201;
  178. } catch (ex) {
  179. console.log(ex);
  180. this.setMessage(ex.toString(), this.messageType.ERROR);
  181. }
  182. }
  183. /**
  184. * 获取多批次报表数据
  185. *
  186. * @param {Object} ctx - egg全局context
  187. * @return {void}
  188. */
  189. async getMultiReportsEx(ctx) {
  190. // 原则说明:把所有报表模板集中获取,统一filter,只读一次数据!
  191. const params = JSON.parse(ctx.request.body.params);
  192. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  193. const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  194. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  195. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  196. for (const pageRst of pageRstArr) {
  197. await encodeDummySignatureDataUri(pageRst, this.app.baseDir);
  198. }
  199. // console.log(pageRstArr);
  200. ctx.body = { data: pageRstArr, signatureRelInfo: roleRel };
  201. ctx.status = 201;
  202. }
  203. async createExcelFilesEx(ctx) {
  204. const params = JSON.parse(ctx.request.body.params);
  205. const baseDir = this.app.baseDir;
  206. function getExcelByPageData(pageRst, rpt_name, innerRoleRel) {
  207. return new Promise(function(resolve, reject) {
  208. rpt_xl_util.exportExcel(pageRst, params.pageSize, rpt_name, params.isOneSheet, null, null, baseDir, innerRoleRel,
  209. (err, uuidName) => {
  210. if (err) return reject(err);
  211. const fileRst = { uuid: uuidName, reportName: rpt_name };
  212. resolve(fileRst);
  213. }
  214. );
  215. });
  216. }
  217. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  218. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  219. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  220. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  221. const runnableRst = [];
  222. for (let idx = 0; idx < pageRstArr.length; idx++) {
  223. let roleRel = null;
  224. for (const roleR of roleRelArr) {
  225. if (roleR.rpt_id === params.rpt_ids[idx]) {
  226. roleRel = JSON.parse(roleR.rel_content);
  227. break;
  228. }
  229. }
  230. // console.log('roleRel.rel_content: ' + roleRel.rel_content);
  231. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/testBuiltPageResult.jsp');
  232. runnableRst.push(getExcelByPageData(pageRstArr[idx], params.rpt_names[idx], roleRel));
  233. }
  234. const uuidRst = await Promise.all(runnableRst);
  235. ctx.body = { data: uuidRst };
  236. ctx.status = 201;
  237. }
  238. async createExcelFilesInOneBookEx(ctx) {
  239. const params = JSON.parse(ctx.request.body.params);
  240. const baseDir = this.app.baseDir;
  241. function getExcelByPageData(pageRstArr, rpt_name, innerRoleRel) {
  242. return new Promise(function(resolve, reject) {
  243. rpt_xl_util.exportExcelInOneBook(pageRstArr, params.pageSize, rpt_name, baseDir, innerRoleRel,
  244. (err, uuidName) => {
  245. if (err) return reject(err);
  246. const fileRst = { uuid: uuidName, reportName: rpt_name };
  247. resolve(fileRst);
  248. }
  249. );
  250. });
  251. }
  252. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  253. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  254. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  255. const runnableRst = [];
  256. let rptRoleRelArr = [];
  257. const reAssignSignatureName = function(pageData, roleRel, rpt_name_key) {
  258. const keyMap = {};
  259. for (const pageItem of pageData.items) {
  260. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  261. if (!keyMap.hasOwnProperty(signCell.signature_name)) {
  262. keyMap[signCell.signature_name] = rpt_name_key + '_' + signCell.signature_name;
  263. }
  264. }
  265. }
  266. for (const pageItem of pageData.items) {
  267. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  268. if (keyMap.hasOwnProperty(signCell.signature_name)) {
  269. signCell.signature_name = keyMap[signCell.signature_name];
  270. }
  271. }
  272. }
  273. for (const roleSign of roleRel) {
  274. if (keyMap.hasOwnProperty(roleSign.signature_name)) {
  275. roleSign.signature_name = keyMap[roleSign.signature_name];
  276. }
  277. }
  278. // console.log('keyMap of : ' + rpt_name_key);
  279. // console.log(keyMap);
  280. };
  281. for (let idx = 0; idx < pageRstArr.length; idx++) {
  282. let roleRel = null;
  283. for (const roleR of roleRelArr) {
  284. if (roleR.rpt_id === params.rpt_ids[idx]) {
  285. roleRel = JSON.parse(roleR.rel_content);
  286. // 这里要做些电子签名的signature_name转换,以防重名
  287. reAssignSignatureName(pageRstArr[idx], roleRel, params.rpt_names[idx]);
  288. rptRoleRelArr = rptRoleRelArr.concat(roleRel);
  289. break;
  290. }
  291. }
  292. }
  293. runnableRst.push(getExcelByPageData(pageRstArr, params.rptName, rptRoleRelArr));
  294. const uuidRst = await Promise.all(runnableRst);
  295. ctx.body = { data: uuidRst };
  296. ctx.status = 201;
  297. }
  298. async getFileByUUID(ctx) {
  299. // console.log('downloading : ' + ctx.params.uuid);
  300. const uuid = ctx.params.uuid;
  301. const rptName = ctx.params.rptName;
  302. const suffix = '.' + ctx.params.suffix;
  303. function getUuidFile(filestream) {
  304. return new Promise(function(resolve, reject) {
  305. filestream.on('data', function(chunk) {
  306. resolve(chunk);
  307. });
  308. });
  309. }
  310. try {
  311. const rptNameURI = encodeURI(rptName);
  312. const filePath = this.app.baseDir + '/app/public/download/';
  313. // console.log('filePath: ' + filePath);
  314. // await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  315. const filestream = fs.createReadStream(filePath + uuid + suffix);
  316. const chunk = await getUuidFile(filestream);
  317. ctx.set({
  318. 'Content-Type': 'application/vnd.openxmlformats',
  319. 'Content-Disposition': 'attachment; filename="' + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix,
  320. 'Content-Length': chunk.length,
  321. });
  322. ctx.body = chunk;
  323. } catch (e) {
  324. console.log(e);
  325. }
  326. }
  327. }
  328. return ReportController;
  329. };
  330. async function checkStg(ctx, params) {
  331. if (ctx.stage === null || ctx.stage === undefined || parseInt(ctx.stage.id) !== parseInt(params.stage_id)) {
  332. await ctx.service.stage.checkStage(params.stage_id);
  333. if (ctx.stage) {
  334. params.stage_order = ctx.stage.curOrder;
  335. }
  336. }
  337. }
  338. async function getReportData(ctx, params, filters, memFieldKeys) {
  339. const rst = {};
  340. const runnableRst = [];
  341. const runnableKey = []; // 这个配合runnableRst用,未来考虑并行查询优化
  342. // console.log('params');
  343. // console.log(params);
  344. // console.log('memFieldKeys');
  345. // console.log(memFieldKeys);
  346. for (const filter of filters) {
  347. if (runnableKey.indexOf(filter) < 0) {
  348. switch (filter) {
  349. case 'project' :
  350. runnableRst.push(ctx.service.project.getProjectById(params.project_id));
  351. runnableKey.push('project');
  352. break;
  353. case 'tender_info' :
  354. runnableRst.push(ctx.service.tenderInfo.getTenderInfo(params.tender_id));
  355. runnableKey.push('tender_info');
  356. break;
  357. case 'ledger' :
  358. runnableRst.push(ctx.service.ledger.getData(params.tender_id, 0));
  359. runnableKey.push('ledger');
  360. break;
  361. case 'deal_bills' :
  362. // console.log('has push deal_bills! ' + params.tender_id);
  363. runnableRst.push(ctx.service.dealBills.getDataByTenderId(params.tender_id));
  364. runnableKey.push('deal_bills');
  365. break;
  366. case 'stage_bills':
  367. runnableRst.push(ctx.service.stageBills.getLastestStageData(params.tender_id, params.stage_id));
  368. runnableKey.push('stage_bills');
  369. break;
  370. case 'stage_bills_final':
  371. await checkStg(ctx, params);
  372. const stage = ctx.stage;
  373. // runnableRst.push(ctx.service.stageBillsFinal.getFinalDataEx(params.tender_id, params.stage_order));
  374. runnableRst.push(ctx.service.stageBillsFinal.getFinalDataEx(params.tender_id, stage.order));
  375. runnableKey.push('stage_bills_final');
  376. break;
  377. case 'stage':
  378. runnableRst.push(ctx.service.stage.getStageById(params.stage_id));
  379. runnableKey.push('stage');
  380. break;
  381. case 'stage_pay':
  382. await checkStg(ctx, params);
  383. const stage2 = ctx.stage;
  384. // runnableRst.push(ctx.service.stagePay.getAuditorStageData(params.stage_id, params.stage_times, params.stage_order));
  385. runnableRst.push(ctx.service.stagePay.getAuditorStageData(params.stage_id, stage2.times, stage2.order));
  386. runnableKey.push('stage_pay');
  387. break;
  388. case 'mem_stage_im_zl':
  389. // memFieldKeys[filter]
  390. runnableRst.push(ctx.service.reportMemory.getStageImZlData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  391. runnableKey.push(filter);
  392. break;
  393. case 'mem_month_progress':
  394. runnableRst.push(ctx.service.reportMemory.getMonthProgress(params.tender_id, memFieldKeys[filter]));
  395. runnableKey.push(filter);
  396. break;
  397. case 'mem_stage_bills':
  398. runnableRst.push(ctx.service.reportMemory.getStageBillsData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  399. runnableKey.push(filter);
  400. break;
  401. case 'mem_stage_pos':
  402. runnableRst.push(ctx.service.reportMemory.getStagePosData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  403. runnableKey.push(filter);
  404. break;
  405. case 'mem_stage_bills_compare':
  406. runnableRst.push(ctx.service.reportMemory.getStagePosData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  407. runnableKey.push(filter);
  408. break;
  409. case 'change':
  410. runnableRst.push(ctx.service.change.getListByStatus(params.tender_id, 3)); // 获取所有审核通过的变更主信息
  411. runnableKey.push('change');
  412. break;
  413. case 'change_audit_list':
  414. runnableRst.push(ctx.service.changeAuditList.getChangeAuditBills(params.tender_id)); // 获取所有审核通过的变更清单
  415. runnableKey.push('change_audit_list');
  416. break;
  417. default:
  418. break;
  419. }
  420. }
  421. }
  422. const queryRst = await Promise.all(runnableRst);
  423. for (let idx = 0; idx < runnableKey.length; idx++) {
  424. rst[runnableKey[idx]] = queryRst[idx];
  425. }
  426. for (const filter of filters) {
  427. switch (filter) {
  428. case 'mem_stage_im_tz':
  429. rst[filter] = await ctx.service.reportMemory.getStageImTzData(params.tender_id, params.stage_id, memFieldKeys[filter]);
  430. break;
  431. case 'mem_stage_im_tz_bills':
  432. rst[filter] = await ctx.service.reportMemory.getStageImTzBillsData(params.tender_id, params.stage_id, memFieldKeys[filter]);
  433. break;
  434. default:
  435. break;
  436. }
  437. }
  438. return rst;
  439. }
  440. async function getAllPagesCommon(ctx, rptTpl, params, option, outputType, baseDir) {
  441. // let rptTpl = null;
  442. const rptDataUtil = new rptDataExtractor();
  443. rptDataUtil.initialize(rptTpl);
  444. // console.log(rptTpl);
  445. const filter = rptDataUtil.getDataRequestFilter();
  446. // console.log(filter.tables);
  447. const rawDataObj = await ctx.service.report.getReportData(params, filter.tables, filter.memFieldKeys);
  448. // console.log(rawDataObj);
  449. try {
  450. const printCom = JpcEx.createNew();
  451. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  452. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  453. // let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  454. // defProperties = JSON.parse(defProperties[0].defined_content);
  455. const defProperties = RPT_DEF_PROPERTIES;
  456. // console.log('defProperties: ');
  457. // console.log(defProperties);
  458. if (params.custCfg) {
  459. setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  460. } else {
  461. // setupCustomizeCfg(defProperties, rptTpl, defProperties);
  462. }
  463. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  464. printCom.initialize(rptTpl);
  465. // console.log('before assemble');
  466. const tplData = rptDataUtil.assembleData(ctx, rawDataObj, baseDir, printCom);
  467. // console.log(tplData);
  468. // ctx.helper
  469. printCom.analyzeData(ctx.helper, rptTpl, tplData, defProperties, dftOption, outputType);
  470. const maxPages = printCom.totalPages;
  471. let pageRst = null;
  472. if (maxPages > 0) {
  473. pageRst = printCom.outputAsSimpleJSONPageArray(ctx.helper, rptTpl, tplData, 1, maxPages, defProperties, params.custCfg);
  474. } else {
  475. pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
  476. }
  477. if (pageRst) {
  478. // fsUtil.writeObjToFile(pageRst, 'D:/GitHome/temp/testBuiltPageResult.jsp');
  479. } else {
  480. //
  481. }
  482. // console.log(pageRst);
  483. return pageRst;
  484. } catch (ex) {
  485. // console.log("报表数据异常: userId " + user_id + ", project id: " + prj_id);
  486. console.log(ex);
  487. }
  488. }
  489. async function getMultiRptsCommon(ctx, params, outputType, baseDir) {
  490. for (let idx = 0; idx < params.rpt_ids.length; idx++) {
  491. params.rpt_ids[idx] = parseInt(params.rpt_ids[idx]); // 转换一下,以防万一
  492. }
  493. const rptTpls = await ctx.service.rptTpl.getAllTplByIds(params.rpt_ids);
  494. // console.log(rptTpls);
  495. for (let rtIdx = 0; rtIdx < rptTpls.length; rtIdx++) {
  496. rptTpls[rtIdx] = JSON.parse(rptTpls[rtIdx].rpt_content);
  497. }
  498. const rptDataUtil = new rptDataExtractor();
  499. const filterTables = [];
  500. const memFieldKeys = {};
  501. if (rptTpls.length > 1) {
  502. rptTpls.sort(function(item1, item2) {
  503. const i1 = (item1._doc) ? item1._doc : item1;
  504. const i2 = (item2._doc) ? item2._doc : item2;
  505. const ID1 = params.rpt_ids.indexOf(i1[JV.PROP_ID]);
  506. const ID2 = params.rpt_ids.indexOf(i2[JV.PROP_ID]);
  507. return ID1 - ID2;
  508. });
  509. }
  510. for (const rptTpl of rptTpls) {
  511. rptDataUtil.initialize(rptTpl);
  512. const filter = rptDataUtil.getDataRequestFilter();
  513. // console.log(filter);
  514. for (const table of filter.tables) {
  515. if (filterTables.indexOf(table) < 0) {
  516. filterTables.push(table);
  517. }
  518. // memFieldKeys[table] = [];
  519. }
  520. for (const tableKeyProp in filter.memFieldKeys) {
  521. if (!memFieldKeys.hasOwnProperty(tableKeyProp)) {
  522. memFieldKeys[tableKeyProp] = [];
  523. }
  524. for (const mfKey of filter.memFieldKeys[tableKeyProp]) {
  525. if (memFieldKeys[tableKeyProp].indexOf(mfKey) < 0) {
  526. memFieldKeys[tableKeyProp].push(mfKey);
  527. }
  528. }
  529. }
  530. }
  531. const rawDataObj = await ctx.service.report.getReportData(params, filterTables, memFieldKeys);
  532. try {
  533. const rptPageRstArray = [];
  534. // 1. 这里只用一份数据,根据实际应用情况,先备份
  535. const backupData = {};
  536. for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  537. backupData[filterTables[filterIdx]] = [];
  538. Object.assign(backupData[filterTables[filterIdx]], rawDataObj[filterTables[filterIdx]]);
  539. }
  540. // 2. 一个一个模板创建数据
  541. let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  542. // console.log('defProperties: ');
  543. // console.log(defProperties[0].defined_content);
  544. defProperties = JSON.parse(defProperties[0].defined_content);
  545. for (let tplIdx = 0; tplIdx < rptTpls.length; tplIdx++) {
  546. const rptTpl = (rptTpls[tplIdx]._doc) ? rptTpls[tplIdx]._doc : rptTpls[tplIdx];
  547. rptDataUtil.initialize(rptTpl);
  548. const tplData = rptDataUtil.assembleData(ctx, rawDataObj, baseDir);
  549. const printCom = JpcEx.createNew();
  550. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  551. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  552. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  553. if (params.custCfg) setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  554. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  555. printCom.initialize(rptTpl);
  556. printCom.analyzeData(rptTpl, tplData, defProperties, dftOption, outputType);
  557. const maxPages = printCom.totalPages;
  558. let pageRst = null;
  559. if (maxPages > 0) {
  560. pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties, params.custCfg);
  561. } else {
  562. pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
  563. }
  564. rptPageRstArray.push(pageRst);
  565. // 注意:这里需要把备份数据assign回去!!!
  566. if (tplIdx < rptTpls.length - 1) {
  567. for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  568. backupData[filterTables[filterIdx]] = [];
  569. Object.assign(rawDataObj[filterTables[filterIdx]], backupData[filterTables[filterIdx]]);
  570. }
  571. }
  572. }
  573. return rptPageRstArray;
  574. } catch (ex) {
  575. console.log('报表数据异常(getMultiRptsCommon): project_id ' + params.project_id + ', tender_id: ' + params.tender_id + ', stage_id: ' + params.stage_id);
  576. console.log(ex);
  577. } finally {
  578. //
  579. }
  580. }
  581. function setupCustomizeCfg(customizeCfg, rptTpl, defProperties) {
  582. const tmpObj = {};
  583. // 1. 字体
  584. const newFonts = [];
  585. for (const font of defProperties.fonts) {
  586. const copyFont = {};
  587. copyFont.ID = font.ID;
  588. for (const fontProp of JV.FONT_PROPS) {
  589. copyFont[fontProp] = font[fontProp];
  590. }
  591. newFonts.push(copyFont);
  592. tmpObj[font.ID] = copyFont;
  593. }
  594. const private_setup_font = function(propStr, newFont) {
  595. if (tmpObj[propStr]) {
  596. tmpObj[propStr].Name = newFont.Name;
  597. tmpObj[propStr].FontHeight = String(newFont.FontHeight);
  598. tmpObj[propStr].FontBold = newFont.FontBold;
  599. tmpObj[propStr].FontItalic = newFont.FontItalic;
  600. tmpObj[propStr].FontUnderline = newFont.FontUnderline;
  601. }
  602. };
  603. for (const custFont of customizeCfg.fonts) {
  604. switch (custFont.CfgDispName) {
  605. case '表标题':
  606. private_setup_font('ReportTitle_Main', custFont);
  607. break;
  608. case '列标题':
  609. private_setup_font('HeaderColumn', custFont);
  610. private_setup_font('FooterColumn', custFont);
  611. break;
  612. case '正文内容':
  613. private_setup_font('Content', custFont);
  614. break;
  615. case '合计':
  616. private_setup_font('GrandTotal', custFont);
  617. private_setup_font('SectionTotal', custFont);
  618. break;
  619. case '表眉/表脚':
  620. private_setup_font('Header', custFont);
  621. private_setup_font('Footer', custFont);
  622. break;
  623. default:
  624. break;
  625. }
  626. }
  627. // 1.1 窄体
  628. if (tmpObj.Content_Narrow) {
  629. if (customizeCfg.isNarrow) {
  630. tmpObj.Content_Narrow.Name = 'Arial Narrow';
  631. } else {
  632. if (tmpObj.Content) {
  633. tmpObj.Content_Narrow.Name = tmpObj.Content.Name;
  634. } else {
  635. tmpObj.Content_Narrow.Name = '宋体';
  636. }
  637. }
  638. }
  639. defProperties.fonts = newFonts;
  640. // 2. 页边距
  641. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT] = customizeCfg.margins[JV.PROP_LEFT] / 10;
  642. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT] = customizeCfg.margins[JV.PROP_RIGHT] / 10;
  643. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_TOP] = customizeCfg.margins[JV.PROP_TOP] / 10;
  644. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM] = customizeCfg.margins[JV.PROP_BOTTOM] / 10;
  645. // 3. 边框宽度
  646. if (customizeCfg.hasOwnProperty('borderThick')) {
  647. for (let i = 0; i < defProperties.styles.length; i++) {
  648. const style = defProperties.styles[i];
  649. if (style.ID === 'BORDER_ALL_AROUND') {
  650. for (const border of style.border_style) {
  651. border.LineWeight = customizeCfg.borderThick;
  652. }
  653. }
  654. }
  655. }
  656. // 4. 边框竖线
  657. if (!(customizeCfg.showVerticalLine)) {
  658. const private_copy_border = function(src) {
  659. const rst = {};
  660. rst.Position = src.Position;
  661. rst.LineWeight = src.LineWeight;
  662. rst.DashStyle = src.DashStyle;
  663. rst.Color = src.Color;
  664. return rst;
  665. };
  666. const newStyles = [];
  667. for (let i = 0; i < defProperties.styles.length; i++) {
  668. const style = defProperties.styles[i];
  669. newStyles.push(style);
  670. if (style.ID === 'BORDER_ALL_AROUND') {
  671. const newStyle = {};
  672. newStyle.ID = style.ID;
  673. newStyle.CfgDispName = style.CfgDispName;
  674. newStyle.border_style = [];
  675. for (const border of style.border_style) {
  676. const newBorder = private_copy_border(border);
  677. newStyle.border_style.push(newBorder);
  678. if (border.Position === 'Left' || border.Position === 'Right') {
  679. newBorder.LineWeight = 0;
  680. }
  681. }
  682. newStyles[newStyles.length - 1] = newStyle;
  683. }
  684. }
  685. defProperties.styles = newStyles;
  686. }
  687. // 5. 补0
  688. const private_Setup_Format = function(tabFields) {
  689. if (tabFields) {
  690. for (const tabField of tabFields) {
  691. if (tabField[JV.PROP_FORMAT]) {
  692. tabField[JV.PROP_FORMAT] = tabField[JV.PROP_FORMAT].replace(new RegExp('#', 'gm'), '0');
  693. }
  694. }
  695. }
  696. };
  697. if (customizeCfg.fillZero) {
  698. if (rptTpl[JV.NODE_FLOW_INFO]) {
  699. 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]);
  700. 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]);
  701. 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]);
  702. 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]);
  703. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  704. for (const discrete of rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  705. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  706. }
  707. }
  708. if (rptTpl[JV.NODE_FLOW_INFO_EX]) {
  709. 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]);
  710. 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]);
  711. 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]);
  712. 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]);
  713. 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]);
  714. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  715. for (const discrete of rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  716. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  717. }
  718. }
  719. }
  720. } else if (rptTpl[JV.NODE_BILL_INFO]) {
  721. 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]);
  722. if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  723. for (const discrete of rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  724. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  725. }
  726. }
  727. } else if (rptTpl[JV.NODE_CROSS_INFO]) {
  728. 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]);
  729. 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]);
  730. 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]);
  731. 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]);
  732. 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]);
  733. 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]);
  734. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  735. for (const discrete of rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  736. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  737. }
  738. }
  739. }
  740. }
  741. }
  742. function isFileExisted(file) {
  743. return new Promise(function(resolve, reject) {
  744. fs.access(file, err => {
  745. if (err) {
  746. reject(false);
  747. } else {
  748. resolve(true);
  749. }
  750. });
  751. });
  752. }
  753. async function encodeSignatureDataUri(roleRel, baseDir) {
  754. if (roleRel) {
  755. for (const singleRoleRel of roleRel) {
  756. const roleRelContent = JSON.parse(singleRoleRel.rel_content);
  757. for (const role of roleRelContent) {
  758. // console.log(role);
  759. if (role.sign_path !== '') {
  760. const filePath = baseDir + '/app' + role.sign_path;
  761. try {
  762. const res = await isFileExisted(filePath);
  763. if (res) {
  764. const bData = fs.readFileSync(filePath);
  765. const base64Str = bData.toString('base64');
  766. const datauri = 'data:image/png;base64,' + base64Str;
  767. role.sign_pic = datauri;
  768. } else {
  769. console.log('文件不存在:' + filePath);
  770. }
  771. } catch (err) {
  772. console.error(err);
  773. }
  774. }
  775. }
  776. singleRoleRel.rel_content = JSON.stringify(roleRelContent);
  777. }
  778. }
  779. }
  780. async function encodeDummySignatureDataUri(pageRst, baseDir) {
  781. if (pageRst) {
  782. for (const page of pageRst.items) {
  783. for (const signature of page.signature_cells) {
  784. if (signature.signature_name === JV.SIGNATURE_NAME_DUMMY) {
  785. if (signature.path !== '') {
  786. const filePath = baseDir + '/app' + signature.path;
  787. try {
  788. const res = await isFileExisted(filePath);
  789. if (res) {
  790. const bData = fs.readFileSync(filePath);
  791. const base64Str = bData.toString('base64');
  792. const datauri = 'data:image/png;base64,' + base64Str;
  793. signature.pic = datauri;
  794. signature.path = '';
  795. } else {
  796. console.log('文件不存在:' + filePath);
  797. }
  798. } catch (err) {
  799. console.error(err);
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }
  806. }