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 roleRel = await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id); // 新需求中,允许在非审核状态下设置签名
  170. const stgAudit = await ctx.service.stageAudit.getStageAudit(params.stage_id, params.stage_times);
  171. // console.log('after role stage!');
  172. // console.log(roleRel);
  173. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  174. await encodeDummySignatureDataUri(pageRst, this.app.baseDir);
  175. // console.log('encodeSignatureDataUri!');
  176. ctx.body = { data: pageRst, signatureRelInfo: roleRel, stageAudit: stgAudit, debugInfo: ctx.app.config.is_debug ? ctx.debugInfo : null };
  177. // ctx.body = { data: { msg: 'test the network' } };
  178. ctx.status = 201;
  179. } catch (ex) {
  180. console.log(ex);
  181. this.setMessage(ex.toString(), this.messageType.ERROR);
  182. }
  183. }
  184. /**
  185. * 获取多批次报表数据
  186. *
  187. * @param {Object} ctx - egg全局context
  188. * @return {void}
  189. */
  190. async getMultiReportsEx(ctx) {
  191. // 原则说明:把所有报表模板集中获取,统一filter,只读一次数据!
  192. const params = JSON.parse(ctx.request.body.params);
  193. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  194. const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  195. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  196. await encodeSignatureDataUri(roleRel, this.app.baseDir);
  197. for (const pageRst of pageRstArr) {
  198. await encodeDummySignatureDataUri(pageRst, this.app.baseDir);
  199. }
  200. // console.log(pageRstArr);
  201. ctx.body = { data: pageRstArr, signatureRelInfo: roleRel };
  202. ctx.status = 201;
  203. }
  204. async createExcelFilesEx(ctx) {
  205. const params = JSON.parse(ctx.request.body.params);
  206. const baseDir = this.app.baseDir;
  207. function getExcelByPageData(pageRst, rpt_name, innerRoleRel) {
  208. return new Promise(function(resolve, reject) {
  209. rpt_xl_util.exportExcel(pageRst, params.pageSize, rpt_name, params.isOneSheet, null, null, baseDir, innerRoleRel,
  210. (err, uuidName) => {
  211. if (err) return reject(err);
  212. const fileRst = { uuid: uuidName, reportName: rpt_name };
  213. resolve(fileRst);
  214. }
  215. );
  216. });
  217. }
  218. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  219. // const roleRel = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_tpl_id)) : [];
  220. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  221. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  222. const runnableRst = [];
  223. for (let idx = 0; idx < pageRstArr.length; idx++) {
  224. let roleRel = null;
  225. for (const roleR of roleRelArr) {
  226. if (roleR.rpt_id === params.rpt_ids[idx]) {
  227. roleRel = JSON.parse(roleR.rel_content);
  228. break;
  229. }
  230. }
  231. // console.log('roleRel.rel_content: ' + roleRel.rel_content);
  232. // fsUtil.writeObjToFile(pageRstArr, 'D:/GitHome/temp/testBuiltPageResult.jsp');
  233. runnableRst.push(getExcelByPageData(pageRstArr[idx], params.rpt_names[idx], roleRel));
  234. }
  235. const uuidRst = await Promise.all(runnableRst);
  236. ctx.body = { data: uuidRst };
  237. ctx.status = 201;
  238. }
  239. async createExcelFilesInOneBookEx(ctx) {
  240. const params = JSON.parse(ctx.request.body.params);
  241. const baseDir = this.app.baseDir;
  242. function getExcelByPageData(pageRstArr, rpt_name, innerRoleRel) {
  243. return new Promise(function(resolve, reject) {
  244. rpt_xl_util.exportExcelInOneBook(pageRstArr, params.pageSize, rpt_name, baseDir, innerRoleRel,
  245. (err, uuidName) => {
  246. if (err) return reject(err);
  247. const fileRst = { uuid: uuidName, reportName: rpt_name };
  248. resolve(fileRst);
  249. }
  250. );
  251. });
  252. }
  253. const roleRelArr = (params.stage_status === 3) ? (await ctx.service.roleRptRel.getRoleRptRelByDetailIds(params.tender_id, params.rpt_ids)) : [];
  254. const pageRstArr = await getMultiRptsCommon(ctx, params, JV.OUTPUT_TYPE_NORMAL, this.app.baseDir);
  255. await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  256. const runnableRst = [];
  257. let rptRoleRelArr = [];
  258. const reAssignSignatureName = function(pageData, roleRel, rpt_name_key) {
  259. const keyMap = {};
  260. for (const pageItem of pageData.items) {
  261. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  262. if (!keyMap.hasOwnProperty(signCell.signature_name)) {
  263. keyMap[signCell.signature_name] = rpt_name_key + '_' + signCell.signature_name;
  264. }
  265. }
  266. }
  267. for (const pageItem of pageData.items) {
  268. for (const signCell of pageItem[JV.PROP_SIGNATURE_CELLS]) {
  269. if (keyMap.hasOwnProperty(signCell.signature_name)) {
  270. signCell.signature_name = keyMap[signCell.signature_name];
  271. }
  272. }
  273. }
  274. for (const roleSign of roleRel) {
  275. if (keyMap.hasOwnProperty(roleSign.signature_name)) {
  276. roleSign.signature_name = keyMap[roleSign.signature_name];
  277. }
  278. }
  279. // console.log('keyMap of : ' + rpt_name_key);
  280. // console.log(keyMap);
  281. };
  282. for (let idx = 0; idx < pageRstArr.length; idx++) {
  283. let roleRel = null;
  284. for (const roleR of roleRelArr) {
  285. if (roleR.rpt_id === params.rpt_ids[idx]) {
  286. roleRel = JSON.parse(roleR.rel_content);
  287. // 这里要做些电子签名的signature_name转换,以防重名
  288. reAssignSignatureName(pageRstArr[idx], roleRel, params.rpt_names[idx]);
  289. rptRoleRelArr = rptRoleRelArr.concat(roleRel);
  290. break;
  291. }
  292. }
  293. }
  294. runnableRst.push(getExcelByPageData(pageRstArr, params.rptName, rptRoleRelArr));
  295. const uuidRst = await Promise.all(runnableRst);
  296. ctx.body = { data: uuidRst };
  297. ctx.status = 201;
  298. }
  299. async getFileByUUID(ctx) {
  300. // console.log('downloading : ' + ctx.params.uuid);
  301. const uuid = ctx.params.uuid;
  302. const rptName = ctx.params.rptName;
  303. const suffix = '.' + ctx.params.suffix;
  304. function getUuidFile(filestream) {
  305. return new Promise(function(resolve, reject) {
  306. filestream.on('data', function(chunk) {
  307. resolve(chunk);
  308. });
  309. });
  310. }
  311. try {
  312. const rptNameURI = encodeURI(rptName);
  313. const filePath = this.app.baseDir + '/app/public/download/';
  314. // console.log('filePath: ' + filePath);
  315. // await this.ctx.helper.recursiveMkdirSync(this.app.baseDir + '/app/public/download');
  316. const filestream = fs.createReadStream(filePath + uuid + suffix);
  317. const chunk = await getUuidFile(filestream);
  318. ctx.set({
  319. 'Content-Type': 'application/vnd.openxmlformats',
  320. 'Content-Disposition': 'attachment; filename="' + rptNameURI + suffix + "\"; filename*=utf-8''" + rptNameURI + suffix,
  321. 'Content-Length': chunk.length,
  322. });
  323. ctx.body = chunk;
  324. } catch (e) {
  325. console.log(e);
  326. }
  327. }
  328. }
  329. return ReportController;
  330. };
  331. async function checkStg(ctx, params) {
  332. if (ctx.stage === null || ctx.stage === undefined || parseInt(ctx.stage.id) !== parseInt(params.stage_id)) {
  333. await ctx.service.stage.checkStage(params.stage_id);
  334. if (ctx.stage) {
  335. params.stage_order = ctx.stage.curOrder;
  336. }
  337. }
  338. }
  339. async function getReportData(ctx, params, filters, memFieldKeys) {
  340. const rst = {};
  341. const runnableRst = [];
  342. const runnableKey = []; // 这个配合runnableRst用,未来考虑并行查询优化
  343. // console.log('params');
  344. // console.log(params);
  345. // console.log('memFieldKeys');
  346. // console.log(memFieldKeys);
  347. for (const filter of filters) {
  348. if (runnableKey.indexOf(filter) < 0) {
  349. switch (filter) {
  350. case 'project' :
  351. runnableRst.push(ctx.service.project.getProjectById(params.project_id));
  352. runnableKey.push('project');
  353. break;
  354. case 'tender_info' :
  355. runnableRst.push(ctx.service.tenderInfo.getTenderInfo(params.tender_id));
  356. runnableKey.push('tender_info');
  357. break;
  358. case 'ledger' :
  359. runnableRst.push(ctx.service.ledger.getData(params.tender_id, 0));
  360. runnableKey.push('ledger');
  361. break;
  362. case 'deal_bills' :
  363. // console.log('has push deal_bills! ' + params.tender_id);
  364. runnableRst.push(ctx.service.dealBills.getDataByTenderId(params.tender_id));
  365. runnableKey.push('deal_bills');
  366. break;
  367. case 'stage_bills':
  368. runnableRst.push(ctx.service.stageBills.getLastestStageData(params.tender_id, params.stage_id));
  369. runnableKey.push('stage_bills');
  370. break;
  371. case 'stage_bills_final':
  372. await checkStg(ctx, params);
  373. // const stage = ctx.stage;
  374. // runnableRst.push(ctx.service.stageBillsFinal.getFinalDataEx(params.tender_id, params.stage_order));
  375. runnableRst.push(ctx.service.stageBillsFinal.getFinalDataEx(params.tender_id, ctx.stage.order));
  376. runnableKey.push('stage_bills_final');
  377. break;
  378. case 'stage':
  379. runnableRst.push(ctx.service.stage.getStageById(params.stage_id));
  380. runnableKey.push('stage');
  381. break;
  382. case 'stage_pay':
  383. await checkStg(ctx, params);
  384. // const stage2 = ctx.stage;
  385. // runnableRst.push(ctx.service.stagePay.getAuditorStageData(params.stage_id, params.stage_times, params.stage_order));
  386. runnableRst.push(ctx.service.stagePay.getAuditorStageData(params.stage_id, ctx.stage.times, ctx.stage.order));
  387. runnableKey.push('stage_pay');
  388. break;
  389. case 'mem_stage_im_zl':
  390. // memFieldKeys[filter]
  391. runnableRst.push(ctx.service.reportMemory.getStageImZlData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  392. runnableKey.push(filter);
  393. break;
  394. case 'mem_month_progress':
  395. runnableRst.push(ctx.service.reportMemory.getMonthProgress(params.tender_id, memFieldKeys[filter]));
  396. runnableKey.push(filter);
  397. break;
  398. case 'mem_stage_bills':
  399. runnableRst.push(ctx.service.reportMemory.getStageBillsData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  400. runnableKey.push(filter);
  401. break;
  402. case 'mem_stage_pos':
  403. runnableRst.push(ctx.service.reportMemory.getStagePosData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  404. runnableKey.push(filter);
  405. break;
  406. case 'mem_stage_bills_compare':
  407. runnableRst.push(ctx.service.reportMemory.getStagePosData(params.tender_id, params.stage_id, memFieldKeys[filter]));
  408. runnableKey.push(filter);
  409. break;
  410. case 'change':
  411. runnableRst.push(ctx.service.change.getListByStatus(params.tender_id, 3)); // 获取所有审核通过的变更主信息
  412. runnableKey.push('change');
  413. break;
  414. case 'change_audit_list':
  415. runnableRst.push(ctx.service.changeAuditList.getChangeAuditBills(params.tender_id)); // 获取所有审核通过的变更清单
  416. runnableKey.push('change_audit_list');
  417. break;
  418. default:
  419. break;
  420. }
  421. }
  422. }
  423. const queryRst = await Promise.all(runnableRst);
  424. for (let idx = 0; idx < runnableKey.length; idx++) {
  425. rst[runnableKey[idx]] = queryRst[idx];
  426. }
  427. for (const filter of filters) {
  428. switch (filter) {
  429. case 'mem_stage_im_tz':
  430. rst[filter] = await ctx.service.reportMemory.getStageImTzData(params.tender_id, params.stage_id, memFieldKeys[filter]);
  431. break;
  432. case 'mem_stage_im_tz_bills':
  433. rst[filter] = await ctx.service.reportMemory.getStageImTzBillsData(params.tender_id, params.stage_id, memFieldKeys[filter]);
  434. break;
  435. default:
  436. break;
  437. }
  438. }
  439. return rst;
  440. }
  441. async function getAllPagesCommon(ctx, rptTpl, params, option, outputType, baseDir) {
  442. const rptDataUtil = new rptDataExtractor();
  443. rptDataUtil.initialize(rptTpl);
  444. const filter = rptDataUtil.getDataRequestFilter();
  445. // console.log(filter.tables);
  446. const rawDataObj = await ctx.service.report.getReportData(params, filter.tables, filter.memFieldKeys);
  447. // console.log(rawDataObj);
  448. try {
  449. const printCom = JpcEx.createNew();
  450. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  451. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  452. // let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  453. // defProperties = JSON.parse(defProperties[0].defined_content);
  454. const defProperties = RPT_DEF_PROPERTIES;
  455. // console.log('defProperties: ');
  456. // console.log(defProperties);
  457. // console.log('before assemble');
  458. const tplData = rptDataUtil.assembleData(ctx, rawDataObj, baseDir, printCom);
  459. // console.log(tplData);
  460. if (params.custCfg) {
  461. setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  462. } else {
  463. // setupCustomizeCfg(defProperties, rptTpl, defProperties);
  464. }
  465. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  466. printCom.initialize(rptTpl);
  467. // ctx.helper
  468. printCom.analyzeData(ctx.helper, rptTpl, tplData, defProperties, dftOption, outputType);
  469. // console.log(JSON.stringify(rptTpl));
  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. // fsUtil.writeObjToFile(pageRst, 'D:/GitHome/temp/testBuiltPageResult.jsp');
  478. // console.log(pageRst);
  479. return pageRst;
  480. } catch (ex) {
  481. console.log("报表数据异常, tender id: " + params.tender_id);
  482. console.log(ex);
  483. }
  484. }
  485. async function getMultiRptsCommon(ctx, params, outputType, baseDir) {
  486. for (let idx = 0; idx < params.rpt_ids.length; idx++) {
  487. params.rpt_ids[idx] = parseInt(params.rpt_ids[idx]); // 转换一下,以防万一
  488. }
  489. const rptTpls = await ctx.service.rptTpl.getAllTplByIds(params.rpt_ids);
  490. rptTpls.sort(function(rpt1, rpt2) {
  491. return params.rpt_ids.indexOf(rpt1.id) - params.rpt_ids.indexOf(rpt2.id);
  492. });
  493. for (let rtIdx = 0; rtIdx < rptTpls.length; rtIdx++) {
  494. rptTpls[rtIdx] = JSON.parse(rptTpls[rtIdx].rpt_content);
  495. }
  496. const rptDataUtil = new rptDataExtractor();
  497. const filterTables = [];
  498. const memFieldKeys = {};
  499. if (rptTpls.length > 1) {
  500. rptTpls.sort(function(item1, item2) {
  501. const i1 = (item1._doc) ? item1._doc : item1;
  502. const i2 = (item2._doc) ? item2._doc : item2;
  503. const ID1 = params.rpt_ids.indexOf(i1[JV.PROP_ID]);
  504. const ID2 = params.rpt_ids.indexOf(i2[JV.PROP_ID]);
  505. return ID1 - ID2;
  506. });
  507. }
  508. for (const rptTpl of rptTpls) {
  509. rptDataUtil.initialize(rptTpl);
  510. const filter = rptDataUtil.getDataRequestFilter();
  511. // console.log(filter);
  512. for (const table of filter.tables) {
  513. if (filterTables.indexOf(table) < 0) {
  514. filterTables.push(table);
  515. }
  516. // memFieldKeys[table] = [];
  517. }
  518. for (const tableKeyProp in filter.memFieldKeys) {
  519. if (!memFieldKeys.hasOwnProperty(tableKeyProp)) {
  520. memFieldKeys[tableKeyProp] = [];
  521. }
  522. for (const mfKey of filter.memFieldKeys[tableKeyProp]) {
  523. if (memFieldKeys[tableKeyProp].indexOf(mfKey) < 0) {
  524. memFieldKeys[tableKeyProp].push(mfKey);
  525. }
  526. }
  527. }
  528. }
  529. const rawDataObj = await ctx.service.report.getReportData(params, filterTables, memFieldKeys);
  530. try {
  531. const rptPageRstArray = [];
  532. // 1. 这里只用一份数据,根据实际应用情况,先备份
  533. const backupData = {};
  534. for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  535. backupData[filterTables[filterIdx]] = [];
  536. Object.assign(backupData[filterTables[filterIdx]], rawDataObj[filterTables[filterIdx]]);
  537. }
  538. // 2. 一个一个模板创建数据
  539. // let defProperties = await ctx.service.rptPreDefineCfg.getCfgById('Administrator');
  540. // defProperties = JSON.parse(defProperties[0].defined_content);
  541. const defProperties = RPT_DEF_PROPERTIES;
  542. for (let tplIdx = 0; tplIdx < rptTpls.length; tplIdx++) {
  543. const rptTpl = (rptTpls[tplIdx]._doc) ? rptTpls[tplIdx]._doc : rptTpls[tplIdx];
  544. rptDataUtil.initialize(rptTpl);
  545. const tplData = rptDataUtil.assembleData(ctx, rawDataObj, baseDir);
  546. const printCom = JpcEx.createNew();
  547. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  548. if (params.pageSize) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = params.pageSize;
  549. if (params.orientation && (params.orientation !== 'null')) rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_ORIENTATION] = params.orientation;
  550. if (params.custCfg) setupCustomizeCfg(params.custCfg, rptTpl, defProperties);
  551. const dftOption = params.option || JV.PAGING_OPTION_NORMAL;
  552. printCom.initialize(rptTpl);
  553. // console.log(rptTpl);
  554. printCom.analyzeData(ctx.helper, rptTpl, tplData, defProperties, dftOption, outputType);
  555. const maxPages = printCom.totalPages;
  556. let pageRst = null;
  557. // console.log(maxPages);
  558. if (maxPages > 0) {
  559. pageRst = printCom.outputAsSimpleJSONPageArray(ctx.helper, rptTpl, tplData, 1, maxPages, defProperties, params.custCfg);
  560. } else {
  561. pageRst = printCom.outputAsPreviewPage(rptTpl, defProperties);
  562. }
  563. rptPageRstArray.push(pageRst);
  564. // 注意:这里需要把备份数据assign回去!!!
  565. if (tplIdx < rptTpls.length - 1) {
  566. for (let filterIdx = 0; filterIdx < filterTables.length; filterIdx++) {
  567. backupData[filterTables[filterIdx]] = [];
  568. Object.assign(rawDataObj[filterTables[filterIdx]], backupData[filterTables[filterIdx]]);
  569. }
  570. }
  571. }
  572. return rptPageRstArray;
  573. } catch (ex) {
  574. console.log('报表数据异常(getMultiRptsCommon): project_id ' + params.project_id + ', tender_id: ' + params.tender_id + ', stage_id: ' + params.stage_id);
  575. console.log(ex);
  576. } finally {
  577. //
  578. }
  579. }
  580. function setupCustomizeCfg(customizeCfg, rptTpl, defProperties) {
  581. const tmpObj = {};
  582. // 1. 字体
  583. const newFonts = [];
  584. for (const font of defProperties.fonts) {
  585. const copyFont = {};
  586. copyFont.ID = font.ID;
  587. for (const fontProp of JV.FONT_PROPS) {
  588. copyFont[fontProp] = font[fontProp];
  589. }
  590. newFonts.push(copyFont);
  591. tmpObj[font.ID] = copyFont;
  592. }
  593. const private_setup_font = function(propStr, newFont) {
  594. if (tmpObj[propStr]) {
  595. tmpObj[propStr].Name = newFont.Name;
  596. tmpObj[propStr].FontHeight = String(newFont.FontHeight);
  597. tmpObj[propStr].FontBold = newFont.FontBold;
  598. tmpObj[propStr].FontItalic = newFont.FontItalic;
  599. tmpObj[propStr].FontUnderline = newFont.FontUnderline;
  600. }
  601. };
  602. for (const custFont of customizeCfg.fonts) {
  603. switch (custFont.CfgDispName) {
  604. case '表标题':
  605. private_setup_font('ReportTitle_Main', custFont);
  606. break;
  607. case '列标题':
  608. private_setup_font('HeaderColumn', custFont);
  609. private_setup_font('FooterColumn', custFont);
  610. break;
  611. case '正文内容':
  612. private_setup_font('Content', custFont);
  613. break;
  614. case '合计':
  615. private_setup_font('GrandTotal', custFont);
  616. private_setup_font('SectionTotal', custFont);
  617. break;
  618. case '表眉/表脚':
  619. private_setup_font('Header', custFont);
  620. private_setup_font('Footer', custFont);
  621. break;
  622. default:
  623. break;
  624. }
  625. }
  626. // 1.1 窄体
  627. if (tmpObj.Content_Narrow) {
  628. if (customizeCfg.isNarrow) {
  629. tmpObj.Content_Narrow.Name = 'Arial Narrow';
  630. } else {
  631. if (tmpObj.Content) {
  632. tmpObj.Content_Narrow.Name = tmpObj.Content.Name;
  633. } else {
  634. tmpObj.Content_Narrow.Name = '宋体';
  635. }
  636. }
  637. }
  638. defProperties.fonts = newFonts;
  639. // 2. 页边距
  640. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_LEFT] = customizeCfg.margins[JV.PROP_LEFT] / 10;
  641. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_RIGHT] = customizeCfg.margins[JV.PROP_RIGHT] / 10;
  642. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_TOP] = customizeCfg.margins[JV.PROP_TOP] / 10;
  643. rptTpl[JV.NODE_MAIN_INFO][JV.NODE_MARGINS][JV.PROP_BOTTOM] = customizeCfg.margins[JV.PROP_BOTTOM] / 10;
  644. // 3. 边框宽度
  645. if (customizeCfg.hasOwnProperty('borderThick')) {
  646. for (let i = 0; i < defProperties.styles.length; i++) {
  647. const style = defProperties.styles[i];
  648. if (style.ID === 'BORDER_ALL_AROUND') {
  649. for (const border of style.border_style) {
  650. border.LineWeight = customizeCfg.borderThick;
  651. }
  652. }
  653. }
  654. }
  655. // 4. 边框竖线
  656. if (!(customizeCfg.showVerticalLine)) {
  657. const private_copy_border = function(src) {
  658. const rst = {};
  659. rst.Position = src.Position;
  660. rst.LineWeight = src.LineWeight;
  661. rst.DashStyle = src.DashStyle;
  662. rst.Color = src.Color;
  663. return rst;
  664. };
  665. const newStyles = [];
  666. for (let i = 0; i < defProperties.styles.length; i++) {
  667. const style = defProperties.styles[i];
  668. newStyles.push(style);
  669. if (style.ID === 'BORDER_ALL_AROUND') {
  670. const newStyle = {};
  671. newStyle.ID = style.ID;
  672. newStyle.CfgDispName = style.CfgDispName;
  673. newStyle.border_style = [];
  674. for (const border of style.border_style) {
  675. const newBorder = private_copy_border(border);
  676. newStyle.border_style.push(newBorder);
  677. if (border.Position === 'Left' || border.Position === 'Right') {
  678. newBorder.LineWeight = 0;
  679. }
  680. }
  681. newStyles[newStyles.length - 1] = newStyle;
  682. }
  683. }
  684. defProperties.styles = newStyles;
  685. }
  686. // 5. 补0
  687. const private_Setup_Format = function(tabFields) {
  688. if (tabFields) {
  689. for (const tabField of tabFields) {
  690. if (tabField[JV.PROP_FORMAT]) {
  691. tabField[JV.PROP_FORMAT] = tabField[JV.PROP_FORMAT].replace(new RegExp('#', 'gm'), '0');
  692. }
  693. }
  694. }
  695. };
  696. if (customizeCfg.fillZero) {
  697. if (rptTpl[JV.NODE_FLOW_INFO]) {
  698. 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]);
  699. 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]);
  700. 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]);
  701. 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]);
  702. if (rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  703. for (const discrete of rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO]) {
  704. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  705. }
  706. }
  707. if (rptTpl[JV.NODE_FLOW_INFO_EX]) {
  708. 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]);
  709. 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]);
  710. 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]);
  711. 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]);
  712. 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]);
  713. if (rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  714. for (const discrete of rptTpl[JV.NODE_FLOW_INFO_EX][JV.NODE_DISCRETE_INFO]) {
  715. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  716. }
  717. }
  718. }
  719. } else if (rptTpl[JV.NODE_BILL_INFO]) {
  720. 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]);
  721. if (rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  722. for (const discrete of rptTpl[JV.NODE_BILL_INFO][JV.NODE_DISCRETE_INFO]) {
  723. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  724. }
  725. }
  726. } else if (rptTpl[JV.NODE_CROSS_INFO]) {
  727. 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]);
  728. 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]);
  729. 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]);
  730. 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]);
  731. 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]);
  732. 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]);
  733. if (rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  734. for (const discrete of rptTpl[JV.NODE_CROSS_INFO][JV.NODE_DISCRETE_INFO]) {
  735. private_Setup_Format(discrete[JV.PROP_DISCRETE_FIELDS]);
  736. }
  737. }
  738. }
  739. }
  740. }
  741. function isFileExisted(file) {
  742. return new Promise(function(resolve, reject) {
  743. fs.access(file, err => {
  744. if (err) {
  745. reject(false);
  746. } else {
  747. resolve(true);
  748. }
  749. });
  750. });
  751. }
  752. async function encodeSignatureDataUri(roleRel, baseDir) {
  753. if (roleRel) {
  754. for (const singleRoleRel of roleRel) {
  755. const roleRelContent = JSON.parse(singleRoleRel.rel_content);
  756. for (const role of roleRelContent) {
  757. // console.log(role);
  758. if (role.sign_path !== '') {
  759. const filePath = baseDir + '/app' + role.sign_path;
  760. try {
  761. const res = await isFileExisted(filePath);
  762. if (res) {
  763. const bData = fs.readFileSync(filePath);
  764. const base64Str = bData.toString('base64');
  765. const datauri = 'data:image/png;base64,' + base64Str;
  766. role.sign_pic = datauri;
  767. } else {
  768. console.log('文件不存在:' + filePath);
  769. }
  770. } catch (err) {
  771. console.error(err);
  772. }
  773. }
  774. }
  775. singleRoleRel.rel_content = JSON.stringify(roleRelContent);
  776. }
  777. }
  778. }
  779. async function encodeDummySignatureDataUri(pageRst, baseDir) {
  780. if (pageRst) {
  781. for (const page of pageRst.items) {
  782. for (const signature of page.signature_cells) {
  783. if (signature.signature_name === JV.SIGNATURE_NAME_DUMMY) {
  784. if (signature.path !== '') {
  785. const filePath = baseDir + '/app' + signature.path;
  786. try {
  787. const res = await isFileExisted(filePath);
  788. if (res) {
  789. const bData = fs.readFileSync(filePath);
  790. const base64Str = bData.toString('base64');
  791. const datauri = 'data:image/png;base64,' + base64Str;
  792. signature.pic = datauri;
  793. signature.path = '';
  794. } else {
  795. console.log('文件不存在:' + filePath);
  796. }
  797. } catch (err) {
  798. console.error(err);
  799. }
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }