report_controller.js 84 KB

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