report_controller.js 40 KB

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