report_memory.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const StageIm = require('../lib/stage_im');
  10. const imType = require('../const/tender').imType;
  11. const audit = require('../const/audit');
  12. // const path = require('path');
  13. // const fs = require('fs');
  14. const stageImTz = 'mem_stage_im_tz';
  15. const stageImTzBills = 'mem_stage_im_tz_bills';
  16. const stageImZl = 'mem_stage_im_zl';
  17. const stageImVersion = '1.0';
  18. const Ledger = require('../lib/ledger');
  19. module.exports = app => {
  20. class ReportMemory extends app.BaseService {
  21. /**
  22. * 构造函数
  23. *
  24. * @param {Object} ctx - egg全局context
  25. * @return {void}
  26. */
  27. constructor(ctx) {
  28. super(ctx);
  29. const self = this;
  30. this.tableName = 'report_memory';
  31. // 基础数据类
  32. // mainData
  33. this.billsTree = new Ledger.billsTree(this.ctx, {
  34. id: 'ledger_id',
  35. pid: 'ledger_pid',
  36. order: 'order',
  37. level: 'level',
  38. rootId: -1,
  39. keys: ['id', 'tender_id', 'ledger_id'],
  40. stageId: 'id',
  41. calcFields: ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp'],
  42. calc: function (node) {
  43. if (node.children && node.children.length === 0) {
  44. node.pre_gather_qty = self.ctx.helper.add(node.pre_contract_qty, node.pre_qc_qty);
  45. node.gather_qty = self.ctx.helper.add(node.contract_qty, node.qc_qty);
  46. node.end_contract_qty = self.ctx.helper.add(node.pre_contract_qty, node.contract_qty);
  47. node.end_qc_qty = self.ctx.helper.add(node.pre_qc_qty, node.qc_qty);
  48. node.end_gather_qty = self.ctx.helper.add(node.pre_gather_qty, node.gather_qty);
  49. }
  50. node.pre_gather_tp = self.ctx.helper.add(node.pre_contract_tp, node.pre_qc_tp);
  51. node.gather_tp = self.ctx.helper.add(node.contract_tp, node.qc_tp);
  52. node.end_contract_tp = self.ctx.helper.add(node.pre_contract_tp, node.contract_tp);
  53. node.end_qc_tp = self.ctx.helper.add(node.pre_qc_tp, node.qc_tp);
  54. node.end_gather_tp = self.ctx.helper.add(node.pre_gather_tp, node.gather_tp);
  55. node.final_tp = self.ctx.helper.add(node.total_price, node.end_qc_tp);
  56. node.final_ratio = self.ctx.helper.mul(self.ctx.helper.div(node.end_gather_tp, node.final_tp, 4), 100);
  57. }
  58. });
  59. this.pos = new Ledger.pos({
  60. id: 'id', ledgerId: 'lid',
  61. updateFields: ['contract_qty', 'qc_qty', 'postil'],
  62. calc: function (p) {
  63. p.pre_gather_qty = ctx.helper.add(p.pre_contract_qty, p.pre_qc_qty);
  64. p.gather_qty = ctx.helper.add(p.contract_qty, p.qc_qty);
  65. p.end_contract_qty = self.ctx.helper.add(p.pre_contract_qty, p.contract_qty);
  66. p.end_qc_qty = self.ctx.helper.add(p.pre_qc_qty, p.qc_qty);
  67. p.end_gather_qty = self.ctx.helper.add(p.pre_gather_qty, p.gather_qty);
  68. }
  69. });
  70. // 需要缓存的数据
  71. this.stageImData = null;
  72. }
  73. // build-time: 162-384ms, redis-cache: 0-41ms, mysql + IO: 116-146ms
  74. // 一定程度上算是大Value缓存,数据多了以后:
  75. // 1. 达到redis内存阈值时,数据会swap到磁盘,此时将消耗IO时间
  76. // 2. redis单独服务器
  77. // 3. redis集群
  78. async _getReportMemoryCache(name, tid, sid, time, version = '') {
  79. // redis
  80. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  81. const data = await this.cache.get(cacheKey);
  82. if (data) {
  83. return eval(data);
  84. } else {
  85. return null;
  86. }
  87. // mysql + IO
  88. // const rm = await this.getDataByCondition({
  89. // tid: tid, sid: sid, name: name, time: time
  90. // });
  91. // if (rm && rm.file) {
  92. // const file = path.join(this.ctx.app.config.filePath, 'report', 'cache', rm.file);
  93. // if (fs.existsSync(file)) {
  94. // const data = await fs.readFileSync(file, 'utf8');
  95. // return eval(data);
  96. // } else {
  97. // return null;
  98. // }
  99. // }
  100. }
  101. async _setReportMemoryCache(name, tid, sid, time, data, version = '') {
  102. // redis
  103. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  104. this.cache.set(cacheKey, JSON.stringify(data), 'EX', this.ctx.app.config.cacheTime);
  105. // mysql + IO
  106. // const file = path.join('report', 'cache', 'rm' + (new Date()).getTime() + '.json');
  107. // await this.ctx.helper.saveBufferFile(JSON.stringify(data), path.join(this.ctx.app.config.filePath, file));
  108. // const rm = await this.getDataByCondition({
  109. // tid: tid, sid: sid, name: name, time: time
  110. // });
  111. // if (rm) {
  112. // await this.db.update(this.tableName, {id: rm.id, file: file});
  113. // } else {
  114. // await this.db.insert(this.tableName, {tid: tid, sid: sid, name: name, time: time, file: file});
  115. // }
  116. }
  117. async _generateStageIm(tid, sid, isTz = true) {
  118. if (isTz && this.ctx.stage.im_type !== imType.tz.value) {
  119. throw '您查看的报表跟设置不符,请查看“总量控制”的报表';
  120. } else if (!isTz && this.ctx.stage.im_type === imType.tz.value) {
  121. throw '您查看的报表跟设置不符,请查看“0号台账”的报表';
  122. }
  123. const stageIm = new StageIm(this.ctx);
  124. await stageIm.buildImData();
  125. this.stageImData.main = stageIm.ImData;
  126. if (isTz) {
  127. this.stageImData.bills = stageIm.ImBillsData;
  128. await this._setReportMemoryCache(stageImTz, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  129. await this._setReportMemoryCache(stageImTzBills, tid, sid, this.ctx.stage.cacheTime, this.stageImData.bills, stageImVersion);
  130. } else {
  131. await this._setReportMemoryCache(stageImZl, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  132. }
  133. }
  134. async getStageImTzNoReturn(tid, sid) {
  135. // 备注:单独拎出以下几行代码一个是为了提高效率(跟getStageImTzDataDirectlyByKey方法协作使用)
  136. // 二是如果出现并行查询(台账及台账清单)情况下,会出现干扰(已验证过),导致数据丢失
  137. if (!this.stageImData) {
  138. this.stageImData = {};
  139. }
  140. try {
  141. await this._generateStageIm(tid, sid);
  142. } catch (err) {
  143. this.stageImData.main = [];
  144. this.stageImData.bills = [];
  145. }
  146. }
  147. getStageImTzDataDirectlyByKey(key) {
  148. let rst = [];
  149. if (key === 'mem_stage_im_tz') {
  150. rst = this.stageImData.main;
  151. } else {
  152. rst = this.stageImData.bills;
  153. }
  154. return rst;
  155. }
  156. async getStageImTzData(tid, sid, fields) {
  157. await this.ctx.service.tender.checkTender(tid);
  158. await this.ctx.service.stage.checkStage(sid);
  159. const cache = await this._getReportMemoryCache('mem_stage_im_tz', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  160. if (cache) {
  161. // console.log('cache');
  162. return cache;
  163. }
  164. // console.log('build');
  165. if (!this.stageImData) {
  166. this.stageImData = {};
  167. try {
  168. await this._generateStageIm(tid, sid);
  169. } catch (err) {
  170. if (err.statck) {
  171. this.ctx.logger.error(err);
  172. }
  173. this.stageImData.main = err.statck ? '数据错误' : err;
  174. this.stageImData.bills = this.stageImData.main;
  175. }
  176. }
  177. return this.stageImData.main;
  178. }
  179. async getStageImTzBillsData(tid, sid, fields) {
  180. await this.ctx.service.tender.checkTender(tid);
  181. await this.ctx.service.stage.checkStage(sid);
  182. const cache = await this._getReportMemoryCache('mem_stage_im_tz_bills', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  183. if (cache) return cache;
  184. if (!this.stageImData) {
  185. this.stageImData = {};
  186. try {
  187. await this._generateStageIm(tid, sid);
  188. } catch (err) {
  189. if (err.statck) {
  190. this.ctx.logger.error(err);
  191. }
  192. this.stageImData.main = err.statck ? '数据错误' : err;
  193. this.stageImData.bills = this.stageImData.main;
  194. }
  195. }
  196. return this.stageImData.bills;
  197. }
  198. async getStageImZlData(tid, sid, fields) {
  199. await this.ctx.service.tender.checkTender(tid);
  200. await this.ctx.service.stage.checkStage(sid);
  201. const cache = await this._getReportMemoryCache('mem_stage_im_zl', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  202. if (cache) return cache;
  203. this.stageImData = {};
  204. try {
  205. await this._generateStageIm(tid, sid, false);
  206. } catch (err) {
  207. if (err.statck) {
  208. this.ctx.logger.error(err);
  209. }
  210. this.stageImData.main = err.statck ? '数据错误' : err;
  211. }
  212. return this.stageImData.main;
  213. }
  214. async getMonthProgress(tid, fields) {
  215. const helper = this.ctx.helper;
  216. await this.ctx.service.tender.checkTender(tid);
  217. const tender = this.ctx.tender;
  218. const stages = await this.ctx.service.stage.getValidStages(tender.id);
  219. const lastStage = stages.length > 0 ? stages[0] : null;
  220. if (lastStage) {
  221. await this.ctx.service.stage.checkStageGatherData(lastStage);
  222. tender.gather_tp = helper.add(lastStage.contract_tp, lastStage.qc_tp);
  223. tender.end_contract_tp = helper.add(lastStage.contract_tp, lastStage.pre_contract_tp);
  224. tender.end_qc_tp = helper.add(lastStage.qc_tp, lastStage.pre_qc_tp);
  225. tender.end_gather_tp = helper.add(tender.end_contract_tp, tender.end_qc_tp);
  226. tender.pre_gather_tp = helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);
  227. tender.yf_tp = lastStage.yf_tp;
  228. tender.qc_ratio = helper.mul(helper.div(tender.end_qc_tp, tender.info.deal_param.contractPrice, 2), 100);
  229. tender.sum = helper.add(tender.total_price, tender.end_qc_tp);
  230. tender.pre_ratio = helper.mul(helper.div(tender.pre_gather_tp, tender.sum, 2), 100);
  231. tender.cur_ratio = helper.mul(helper.div(tender.gather_tp, tender.sum, 2), 100);
  232. tender.other_tp = helper.sub(helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);
  233. tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);
  234. }
  235. const monthProgress = [];
  236. for (const s of stages) {
  237. if (s.s_time) {
  238. let progress = monthProgress.find(function (x) {
  239. return x.month === s.s_time;
  240. });
  241. if (!progress) {
  242. progress = {month: s.s_time};
  243. monthProgress.push(progress);
  244. }
  245. progress.tp = helper.add(helper.add(progress.tp, s.contract_tp), s.qc_tp);
  246. }
  247. }
  248. monthProgress.sort(function (x, y) {
  249. return Date.parse(x.month) - Date.parse(y.month);
  250. });
  251. let sum = 0;
  252. for (const p of monthProgress) {
  253. p.ratio = helper.mul(helper.div(p.tp, tender.sum, 4), 100);
  254. sum = helper.add(sum, p.tp);
  255. p.end_tp = sum;
  256. p.end_ratio = helper.mul(helper.div(p.end_tp, tender.sum, 4), 100);
  257. }
  258. return monthProgress;
  259. }
  260. async getStageBillsData(tid, sid, fields) {
  261. await this.ctx.service.tender.checkTender(tid);
  262. await this.ctx.service.stage.checkStage(sid);
  263. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  264. if (this.ctx.stage.readOnly) {
  265. const curStage = await this.ctx.service.stageBills.getAuditorStageData(this.ctx.tender.id,
  266. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  267. this.ctx.helper.assignRelaData(billsData, [
  268. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  269. ]);
  270. } else {
  271. const curStage = await this.ctx.service.stageBills.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id);
  272. this.ctx.helper.assignRelaData(billsData, [
  273. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  274. ]);
  275. }
  276. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  277. this.ctx.helper.assignRelaData(billsData, [
  278. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  279. ]);
  280. this.billsTree.loadDatas(billsData);
  281. this.billsTree.calculateAll();
  282. return this.billsTree.getDatas([
  283. 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
  284. 'code', 'b_code', 'name', 'unit', 'unit_price',
  285. 'deal_qty', 'deal_tp',
  286. 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'quantity', 'total_price',
  287. 'dgn_qty1', 'dgn_qty2',
  288. 'drawing_code', 'memo', 'node_type', 'is_tp',
  289. 'contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'gather_qty', 'gather_tp', 'postil',
  290. 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  291. 'end_contract_qty', 'end_contract_tp', 'end_qc_qty', 'end_qc_tp', 'end_gather_qty', 'end_gather_tp',
  292. 'final_tp', 'final_ratio',
  293. ]);
  294. }
  295. async getStagePosData(tid, sid, fields) {
  296. await this.ctx.service.tender.checkTender(tid);
  297. await this.ctx.service.stage.checkStage(sid);
  298. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  299. if (this.ctx.stage.readOnly) {
  300. const curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  301. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  302. this.ctx.helper.assignRelaData(posData, [
  303. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  304. ]);
  305. } else {
  306. const curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  307. this.ctx.helper.assignRelaData(posData, [
  308. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  309. ]);
  310. }
  311. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  312. this.ctx.helper.assignRelaData(posData, [
  313. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  314. ]);
  315. this.pos.loadDatas(posData);
  316. this.pos.calculateAll();
  317. return this.pos.getDatas();
  318. }
  319. }
  320. return ReportMemory;
  321. };