report_memory.js 16 KB

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