report_memory.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date
  7. * @version
  8. */
  9. const _ = require('lodash');
  10. const StageIm = require('../lib/stage_im');
  11. const imType = require('../const/tender').imType;
  12. const audit = require('../const/audit');
  13. // const path = require('path');
  14. // const fs = require('fs');
  15. const stageImTz = 'mem_stage_im_tz';
  16. const stageImTzBills = 'mem_stage_im_tz_bills';
  17. const stageImZl = 'mem_stage_im_zl';
  18. const stageImVersion = '1.0';
  19. const Ledger = require('../lib/ledger');
  20. const curFields = ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'gather_qty', 'gather_tp', 'postil'];
  21. const preFields = ['pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp'];
  22. const endFields = ['end_contract_qty', 'end_contract_tp', 'end_qc_qty', 'end_qc_tp', 'end_gather_qty', 'end_gather_tp'];
  23. const finalFields = ['final_tp', 'final_ratio'];
  24. const stageFields = curFields.concat(preFields, endFields, finalFields);
  25. const stageEndFields = preFields.concat(endFields, finalFields);
  26. const bglFields = ['qc_bgl_code'];
  27. module.exports = app => {
  28. class ReportMemory extends app.BaseService {
  29. /**
  30. * 构造函数
  31. *
  32. * @param {Object} ctx - egg全局context
  33. * @return {void}
  34. */
  35. constructor(ctx) {
  36. super(ctx);
  37. const self = this;
  38. this.tableName = 'report_memory';
  39. // 基础数据类
  40. // mainData
  41. this.billsTree = new Ledger.billsTree(this.ctx, {
  42. id: 'ledger_id',
  43. pid: 'ledger_pid',
  44. order: 'order',
  45. level: 'level',
  46. rootId: -1,
  47. keys: ['id', 'tender_id', 'ledger_id'],
  48. stageId: 'id',
  49. calcFields: ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp', 'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp'],
  50. calc: function (node) {
  51. if (node.children && node.children.length === 0) {
  52. node.pre_gather_qty = self.ctx.helper.add(node.pre_contract_qty, node.pre_qc_qty);
  53. node.gather_qty = self.ctx.helper.add(node.contract_qty, node.qc_qty);
  54. node.end_contract_qty = self.ctx.helper.add(node.pre_contract_qty, node.contract_qty);
  55. node.end_qc_qty = self.ctx.helper.add(node.pre_qc_qty, node.qc_qty);
  56. node.end_gather_qty = self.ctx.helper.add(node.pre_gather_qty, node.gather_qty);
  57. }
  58. node.pre_gather_tp = self.ctx.helper.add(node.pre_contract_tp, node.pre_qc_tp);
  59. node.gather_tp = self.ctx.helper.add(node.contract_tp, node.qc_tp);
  60. node.end_contract_tp = self.ctx.helper.add(node.pre_contract_tp, node.contract_tp);
  61. node.end_qc_tp = self.ctx.helper.add(node.pre_qc_tp, node.qc_tp);
  62. node.end_gather_tp = self.ctx.helper.add(node.pre_gather_tp, node.gather_tp);
  63. node.final_tp = self.ctx.helper.add(node.total_price, node.end_qc_tp);
  64. node.final_ratio = self.ctx.helper.mul(self.ctx.helper.div(node.end_gather_tp, node.final_tp, 4), 100);
  65. }
  66. });
  67. this.pos = new Ledger.pos({
  68. id: 'id', ledgerId: 'lid',
  69. updateFields: ['contract_qty', 'qc_qty', 'postil'],
  70. calc: function (p) {
  71. p.pre_gather_qty = ctx.helper.add(p.pre_contract_qty, p.pre_qc_qty);
  72. p.gather_qty = ctx.helper.add(p.contract_qty, p.qc_qty);
  73. p.end_contract_qty = self.ctx.helper.add(p.pre_contract_qty, p.contract_qty);
  74. p.end_qc_qty = self.ctx.helper.add(p.pre_qc_qty, p.qc_qty);
  75. p.end_gather_qty = self.ctx.helper.add(p.pre_gather_qty, p.gather_qty);
  76. }
  77. });
  78. // 需要缓存的数据
  79. this.stageImData = null;
  80. this.changeData = null;
  81. }
  82. _checkFieldsExist(source, check) {
  83. for (const s of source) {
  84. if (check.indexOf(s) >= 0) {
  85. return true;
  86. }
  87. }
  88. return false;
  89. }
  90. _checkFieldsExistReg(source, regStr) {
  91. const reg = new RegExp(regStr, 'igm');
  92. for (const s of source) {
  93. if (reg.test(s)) {
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. // build-time: 162-384ms, redis-cache: 0-41ms, mysql + IO: 116-146ms
  100. // 一定程度上算是大Value缓存,数据多了以后:
  101. // 1. 达到redis内存阈值时,数据会swap到磁盘,此时将消耗IO时间
  102. // 2. redis单独服务器
  103. // 3. redis集群
  104. async _getReportMemoryCache(name, tid, sid, time, version = '') {
  105. // redis
  106. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  107. const data = await this.cache.get(cacheKey);
  108. if (data) {
  109. return eval(data);
  110. } else {
  111. return null;
  112. }
  113. // mysql + IO
  114. // const rm = await this.getDataByCondition({
  115. // tid: tid, sid: sid, name: name, time: time
  116. // });
  117. // if (rm && rm.file) {
  118. // const file = path.join(this.ctx.app.config.filePath, 'report', 'cache', rm.file);
  119. // if (fs.existsSync(file)) {
  120. // const data = await fs.readFileSync(file, 'utf8');
  121. // return eval(data);
  122. // } else {
  123. // return null;
  124. // }
  125. // }
  126. }
  127. async _setReportMemoryCache(name, tid, sid, time, data, version = '') {
  128. // redis
  129. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  130. this.cache.set(cacheKey, JSON.stringify(data), 'EX', this.ctx.app.config.cacheTime);
  131. // mysql + IO
  132. // const file = path.join('report', 'cache', 'rm' + (new Date()).getTime() + '.json');
  133. // await this.ctx.helper.saveBufferFile(JSON.stringify(data), path.join(this.ctx.app.config.filePath, file));
  134. // const rm = await this.getDataByCondition({
  135. // tid: tid, sid: sid, name: name, time: time
  136. // });
  137. // if (rm) {
  138. // await this.db.update(this.tableName, {id: rm.id, file: file});
  139. // } else {
  140. // await this.db.insert(this.tableName, {tid: tid, sid: sid, name: name, time: time, file: file});
  141. // }
  142. }
  143. async _generateStageIm(tid, sid, isTz = true) {
  144. if (isTz && this.ctx.stage.im_type !== imType.tz.value) {
  145. throw '您查看的报表跟设置不符,请查看“总量控制”的报表';
  146. } else if (!isTz && this.ctx.stage.im_type === imType.tz.value) {
  147. throw '您查看的报表跟设置不符,请查看“0号台账”的报表';
  148. }
  149. const stageIm = new StageIm(this.ctx);
  150. await stageIm.buildImData();
  151. this.stageImData.main = stageIm.ImData;
  152. if (isTz) {
  153. this.stageImData.bills = stageIm.ImBillsData;
  154. await this._setReportMemoryCache(stageImTz, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  155. await this._setReportMemoryCache(stageImTzBills, tid, sid, this.ctx.stage.cacheTime, this.stageImData.bills, stageImVersion);
  156. } else {
  157. await this._setReportMemoryCache(stageImZl, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  158. }
  159. }
  160. async getStageImTzNoReturn(tid, sid) {
  161. // 备注:单独拎出以下几行代码一个是为了提高效率(跟getStageImTzDataDirectlyByKey方法协作使用)
  162. // 二是如果出现并行查询(台账及台账清单)情况下,会出现干扰(已验证过),导致数据丢失
  163. if (!this.stageImData) {
  164. this.stageImData = {};
  165. }
  166. try {
  167. await this._generateStageIm(tid, sid);
  168. } catch (err) {
  169. this.stageImData.main = [];
  170. this.stageImData.bills = [];
  171. }
  172. }
  173. getStageImTzDataDirectlyByKey(key) {
  174. let rst = [];
  175. if (key === 'mem_stage_im_tz') {
  176. rst = this.stageImData.main;
  177. } else {
  178. rst = this.stageImData.bills;
  179. }
  180. return rst;
  181. }
  182. async getStageImTzData(tid, sid, fields) {
  183. await this.ctx.service.tender.checkTender(tid);
  184. await this.ctx.service.stage.checkStage(sid);
  185. const cache = await this._getReportMemoryCache('mem_stage_im_tz', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  186. if (cache) {
  187. // console.log('cache');
  188. return cache;
  189. }
  190. // console.log('build');
  191. if (!this.stageImData) {
  192. this.stageImData = {};
  193. try {
  194. await this._generateStageIm(tid, sid);
  195. } catch (err) {
  196. if (err.statck) {
  197. this.ctx.logger.error(err);
  198. }
  199. this.stageImData.main = err.statck ? '数据错误' : err;
  200. this.stageImData.bills = this.stageImData.main;
  201. }
  202. }
  203. return this.stageImData.main;
  204. }
  205. async getStageImTzBillsData(tid, sid, fields) {
  206. await this.ctx.service.tender.checkTender(tid);
  207. await this.ctx.service.stage.checkStage(sid);
  208. const cache = await this._getReportMemoryCache('mem_stage_im_tz_bills', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  209. if (cache) return cache;
  210. if (!this.stageImData) {
  211. this.stageImData = {};
  212. try {
  213. await this._generateStageIm(tid, sid);
  214. } catch (err) {
  215. if (err.statck) {
  216. this.ctx.logger.error(err);
  217. }
  218. this.stageImData.main = err.statck ? '数据错误' : err;
  219. this.stageImData.bills = this.stageImData.main;
  220. }
  221. }
  222. return this.stageImData.bills;
  223. }
  224. async getStageImZlData(tid, sid, fields) {
  225. await this.ctx.service.tender.checkTender(tid);
  226. await this.ctx.service.stage.checkStage(sid);
  227. const cache = await this._getReportMemoryCache('mem_stage_im_zl', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  228. if (cache) return cache;
  229. this.stageImData = {};
  230. try {
  231. await this._generateStageIm(tid, sid, false);
  232. } catch (err) {
  233. if (err.statck) {
  234. this.ctx.logger.error(err);
  235. }
  236. this.stageImData.main = err.statck ? '数据错误' : err;
  237. }
  238. return this.stageImData.main;
  239. }
  240. async getMonthProgress(tid, fields) {
  241. const helper = this.ctx.helper;
  242. await this.ctx.service.tender.checkTender(tid);
  243. const tender = this.ctx.tender;
  244. const stages = await this.ctx.service.stage.getValidStages(tender.id);
  245. const lastStage = stages.length > 0 ? stages[0] : null;
  246. if (lastStage) {
  247. await this.ctx.service.stage.checkStageGatherData(lastStage);
  248. tender.gather_tp = helper.add(lastStage.contract_tp, lastStage.qc_tp);
  249. tender.end_contract_tp = helper.add(lastStage.contract_tp, lastStage.pre_contract_tp);
  250. tender.end_qc_tp = helper.add(lastStage.qc_tp, lastStage.pre_qc_tp);
  251. tender.end_gather_tp = helper.add(tender.end_contract_tp, tender.end_qc_tp);
  252. tender.pre_gather_tp = helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);
  253. tender.yf_tp = lastStage.yf_tp;
  254. tender.qc_ratio = helper.mul(helper.div(tender.end_qc_tp, tender.info.deal_param.contractPrice, 2), 100);
  255. tender.sum = helper.add(tender.total_price, tender.end_qc_tp);
  256. tender.pre_ratio = helper.mul(helper.div(tender.pre_gather_tp, tender.sum, 2), 100);
  257. tender.cur_ratio = helper.mul(helper.div(tender.gather_tp, tender.sum, 2), 100);
  258. tender.other_tp = helper.sub(helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);
  259. tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);
  260. }
  261. const monthProgress = [];
  262. for (const s of stages) {
  263. if (s.s_time) {
  264. let progress = monthProgress.find(function (x) {
  265. return x.month === s.s_time;
  266. });
  267. if (!progress) {
  268. progress = {month: s.s_time};
  269. monthProgress.push(progress);
  270. }
  271. progress.tp = helper.add(helper.add(progress.tp, s.contract_tp), s.qc_tp);
  272. }
  273. }
  274. monthProgress.sort(function (x, y) {
  275. return Date.parse(x.month) - Date.parse(y.month);
  276. });
  277. let sum = 0;
  278. for (const p of monthProgress) {
  279. p.ratio = helper.mul(helper.div(p.tp, tender.sum, 4), 100);
  280. sum = helper.add(sum, p.tp);
  281. p.end_tp = sum;
  282. p.end_ratio = helper.mul(helper.div(p.end_tp, tender.sum, 4), 100);
  283. }
  284. return monthProgress;
  285. }
  286. async _calcBillsBgl() {
  287. if (!this.ctx.stage) return;
  288. const helper = this.ctx.helper;
  289. const tender = this.ctx.tender;
  290. const stage = this.ctx.stage;
  291. const bglData = this.ctx.stage.readOnly
  292. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  293. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  294. for (const node of this.billsTree.nodes) {
  295. node.qc_bgl_code = '';
  296. if (node.children && node.children.length > 0) continue;
  297. const nodeBgl = helper._.filter(bglData, {lid: node.id});
  298. if (nodeBgl.length === 0) continue;
  299. helper._.pullAll(bglData, nodeBgl);
  300. const validBgl = helper._.filter(nodeBgl, function (x) {
  301. return !helper.checkZero(x.qty);
  302. });
  303. node.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  304. }
  305. }
  306. async getStageBillsData(tid, sid, fields) {
  307. await this.ctx.service.tender.checkTender(tid);
  308. if (sid) {
  309. await this.ctx.service.stage.checkStage(sid);
  310. }
  311. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  312. if (this._checkFieldsExist(fields, stageFields)) {
  313. if (this.ctx.stage.readOnly) {
  314. const curStage = await this.ctx.service.stageBills.getAuditorStageData(this.ctx.tender.id,
  315. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  316. this.ctx.helper.assignRelaData(billsData, [
  317. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  318. ]);
  319. } else {
  320. const curStage = await this.ctx.service.stageBills.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id);
  321. this.ctx.helper.assignRelaData(billsData, [
  322. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  323. ]);
  324. }
  325. }
  326. if (this._checkFieldsExist(fields, preFields.concat(endFields, finalFields))) {
  327. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  328. this.ctx.helper.assignRelaData(billsData, [
  329. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  330. ]);
  331. }
  332. this.billsTree.loadDatas(billsData);
  333. this.billsTree.calculateAll();
  334. if (this._checkFieldsExist(fields, bglFields)) {
  335. await this._calcBillsBgl();
  336. }
  337. return this.billsTree.getDatas([
  338. 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
  339. 'code', 'b_code', 'name', 'unit', 'unit_price',
  340. 'deal_qty', 'deal_tp',
  341. 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'quantity', 'total_price',
  342. 'dgn_qty1', 'dgn_qty2',
  343. 'drawing_code', 'memo', 'node_type', 'is_tp',
  344. 'contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'gather_qty', 'gather_tp', 'postil',
  345. 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  346. 'end_contract_qty', 'end_contract_tp', 'end_qc_qty', 'end_qc_tp', 'end_gather_qty', 'end_gather_tp',
  347. 'final_tp', 'final_ratio',
  348. 'qc_bgl_code',
  349. 'chapter',
  350. ]);
  351. }
  352. async getStagePosData(tid, sid, fields) {
  353. await this.ctx.service.tender.checkTender(tid);
  354. await this.ctx.service.stage.checkStage(sid);
  355. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  356. if (this.ctx.stage.readOnly) {
  357. const curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  358. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  359. this.ctx.helper.assignRelaData(posData, [
  360. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  361. ]);
  362. } else {
  363. const curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  364. this.ctx.helper.assignRelaData(posData, [
  365. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  366. ]);
  367. }
  368. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  369. this.ctx.helper.assignRelaData(posData, [
  370. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  371. ]);
  372. this.pos.loadDatas(posData);
  373. this.pos.calculateAll();
  374. return this.pos.getDatas();
  375. }
  376. _getStageValidRole () {
  377. if (!this.ctx.stage) throw '期数据错误,请重试';
  378. const result = [{dataOrder: 0, flowOrder: 0, uid: this.ctx.stage.user_id}];
  379. for (const auditor of this.ctx.stage.auditors) {
  380. if (auditor.status === audit.stage.status.checked ||
  381. (auditor.status === audit.stage.status.checking && !this.ctx.stage.readOnly)) {
  382. const role = result.find(function (r) {
  383. return r.uid === auditor.aid;
  384. });
  385. if (role) {
  386. role.dataOrder = auditor.order;
  387. } else {
  388. result.push({
  389. dataOrder: auditor.order,
  390. flowOrder: result.length,
  391. uid: auditor.aid
  392. })
  393. }
  394. }
  395. }
  396. return result;
  397. };
  398. async getStageBillsCompareData(tid, sid, fields) {
  399. await this.ctx.service.tender.checkTender(tid);
  400. await this.ctx.service.stage.checkStage(sid);
  401. const stage = this.ctx.stage, helper = this.ctx.helper;
  402. const validRole = this._getStageValidRole();
  403. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  404. const allStageBills = await this.ctx.service.stageBills.getAllDataByCondition({where: {sid: sid}});
  405. const stageBillsIndex = {}, timesLen = 100;
  406. for (const role of validRole) {
  407. const stageBills = this.ctx.helper._.filter(allStageBills, function (x) {
  408. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  409. });
  410. this.ctx.helper._.pullAll(allStageBills, stageBills);
  411. for (const sb of stageBills) {
  412. const key = 'sb-' + sb.lid;
  413. const sbi = stageBillsIndex[key];
  414. if (sbi) {
  415. if ((sbi.times * timesLen + sbi.order) < (sb.times * timesLen + sb.order)) stageBillsIndex[key] = sb;
  416. } else {
  417. stageBillsIndex[key] = sb;
  418. }
  419. }
  420. const filterStageBills = [];
  421. for (const prop in stageBillsIndex) {
  422. filterStageBills.push(stageBillsIndex[prop]);
  423. }
  424. this.ctx.helper.assignRelaData(billsData, [
  425. {data: filterStageBills, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'r' + role.flowOrder + '_', relaId: 'lid'}
  426. ]);
  427. }
  428. if (this._checkFieldsExist(fields, preFields.concat(endFields, finalFields))) {
  429. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  430. this.ctx.helper.assignRelaData(billsData, [
  431. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  432. ]);
  433. }
  434. this.billsTree.loadDatas(billsData);
  435. this.billsTree.setting.calcFields = ['deal_tp', 'total_price', 'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp'];
  436. for (const role of validRole) {
  437. const prefix = 'r' + role.flowOrder + '_';
  438. this.billsTree.setting.calcFields.push(prefix + 'contract_tp', prefix + 'qc_tp', prefix + 'gather_tp');
  439. }
  440. this.billsTree.calculateAll(function(node) {
  441. let prefix = '';
  442. if (node.children && node.children.length === 0) {
  443. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  444. for (const role of validRole) {
  445. prefix = 'r' + role.flowOrder + '_';
  446. node[prefix + 'gather_qty'] = helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  447. }
  448. }
  449. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  450. for (const role of validRole) {
  451. prefix = 'r' + role.flowOrder + '_';
  452. node[prefix + 'gather_tp'] = helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  453. }
  454. });
  455. return this.billsTree.getDefaultDatas();
  456. // return this.billsTree.getDatas([
  457. // 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', //8
  458. // 'code', 'b_code', 'name', 'unit', 'unit_price', //5
  459. // 'deal_qty', 'deal_tp', 'quantity', 'total_price', 'dgn_qty1', 'dgn_qty2', //6
  460. // 'drawing_code', 'memo', 'node_type', 'is_tp', //4
  461. // 'r0_contract_qty', 'r0_contract_tp', 'r0_qc_qty', 'r0_qc_tp', 'r0_gather_qty', 'r0_gather_tp', //6
  462. // 'r1_contract_qty', 'r1_contract_tp', 'r1_qc_qty', 'r1_qc_tp', 'r1_gather_qty', 'r1_gather_tp',
  463. // 'r2_contract_qty', 'r2_contract_tp', 'r2_qc_qty', 'r2_qc_tp', 'r2_gather_qty', 'r2_gather_tp',
  464. // 'r3_contract_qty', 'r3_contract_tp', 'r3_qc_qty', 'r3_qc_tp', 'r3_gather_qty', 'r3_gather_tp',
  465. // 'r4_contract_qty', 'r4_contract_tp', 'r4_qc_qty', 'r4_qc_tp', 'r4_gather_qty', 'r4_gather_tp',
  466. // 'r5_contract_qty', 'r5_contract_tp', 'r5_qc_qty', 'r5_qc_tp', 'r5_gather_qty', 'r5_gather_tp',
  467. // 'r6_contract_qty', 'r6_contract_tp', 'r6_qc_qty', 'r6_qc_tp', 'r6_gather_qty', 'r6_gather_tp',
  468. // 'r7_contract_qty', 'r7_contract_tp', 'r7_qc_qty', 'r7_qc_tp', 'r7_gather_qty', 'r7_gather_tp',
  469. // 'r8_contract_qty', 'r8_contract_tp', 'r8_qc_qty', 'r8_qc_tp', 'r8_gather_qty', 'r8_gather_tp',
  470. // 'r9_contract_qty', 'r9_contract_tp', 'r9_qc_qty', 'r9_qc_tp', 'r9_gather_qty', 'r9_gather_tp',
  471. // 'r10_contract_qty', 'r10_contract_tp', 'r10_qc_qty', 'r10_qc_tp', 'r10_gather_qty', 'r10_gather_tp',
  472. // 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  473. // 'chapter', //1
  474. // ]);
  475. }
  476. async getStagePayData(tid, sid, fields) {
  477. await this.ctx.service.tender.checkTender(tid);
  478. await this.ctx.service.stage.checkStage(sid);
  479. const stage = this.ctx.stage;
  480. const dealPay = await this.ctx.service.stagePay.getStagePays(this.ctx.stage);
  481. if (!this.ctx.stage.readOnly) {
  482. // 计算 本期金额
  483. const PayCalculator = require('../lib/pay_calc');
  484. const payCalculator = new PayCalculator(this.ctx, this.ctx.stage, this.ctx.tender.info);
  485. await payCalculator.calculateAll(dealPay);
  486. }
  487. if (this._checkFieldsExistReg(fields, 'r[0-9]+_tp')) {
  488. const validRole = this._getStageValidRole();
  489. const allStagePays = await this.ctx.service.stagePay.getAllDataByCondition({
  490. where: {sid: stage.id, stimes: stage.curTimes}
  491. });
  492. for (const [i, role] of validRole.entries()) {
  493. if (i < validRole.length - 1) {
  494. const stagePays = this.ctx.helper._.filter(allStagePays, function (x) {
  495. return x.stimes === stage.curTimes && x.sorder === role.dataOrder;
  496. });
  497. this.ctx.helper._.pullAll(allStagePays, stagePays);
  498. for (const sp of stagePays) {
  499. const dp = dealPay.find(function (x) {return x.pid === sp.pid});
  500. if (dp) {
  501. dp['r' + role.flowOrder + '_tp'] = sp.tp;
  502. }
  503. }
  504. } else {
  505. for (const dp of dealPay) {
  506. dp['r' + role.flowOrder + '_tp'] = dp.tp;
  507. }
  508. }
  509. }
  510. }
  511. return dealPay;
  512. }
  513. async _generateChange(tid) {
  514. if (this.changeData !== null) return;
  515. try {
  516. const decimal = this.ctx.tender.info.decimal, ctx = this.ctx;
  517. const change = await this.ctx.service.change.getListByStatus(tid, 3);
  518. const changeBills = await this.ctx.service.changeAuditList.getChangeAuditBills(tid);
  519. for (const d of changeBills) {
  520. //const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, d.unit);
  521. d.o_qty = d.oamount;
  522. d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  523. d.c_qty = d.camount;
  524. d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  525. d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  526. d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  527. const auditAmount = d.audit_amount.split(',');
  528. const relaChange = ctx.helper._.find(change, {cid: d.cid});
  529. for (const [i, aa] of auditAmount.entries()) {
  530. const amountField = 'amount_' + (i+1), tpField = 'tp_' + (i+1);
  531. d[amountField] = aa ? parseFloat(aa) : 0;
  532. d[tpField] = ctx.helper.mul(d[amountField], d.unit_price, decimal.tp);
  533. if (relaChange) {
  534. relaChange[tpField] = ctx.helper.add(relaChange[tpField], d[tpField]);
  535. }
  536. }
  537. }
  538. change.sort(function (a, b) {
  539. return a.code.localeCompare(b.code);
  540. });
  541. changeBills.sort(function (a, b) {
  542. const aCIndex = change.findIndex(function (c) {
  543. return c.cid === a.cid;
  544. });
  545. const bCIndex = change.findIndex(function (c) {
  546. return c.cid === b.cid;
  547. });
  548. return aCIndex === bCIndex
  549. ? ctx.helper.compareCode(a.code, b.code)
  550. : aCIndex - bCIndex;
  551. });
  552. this.changeData = {change: change, bills: changeBills};
  553. } catch(err) {
  554. this.ctx.helper.log(err);
  555. throw err;
  556. this.changeData = {change: [], bills: []};
  557. }
  558. }
  559. async getChangeData(tid, sid, fields) {
  560. await this.ctx.service.tender.checkTender(tid);
  561. await this._generateChange(tid);
  562. return this.changeData.change;
  563. }
  564. async getChangeBillsData(tid, sid, fields) {
  565. await this.ctx.service.tender.checkTender(tid);
  566. await this._generateChange(tid);
  567. return this.changeData.bills;
  568. // const data = await this.ctx.service.changeAuditList.getChangeAuditBills(tid);
  569. // for (const d of data) {
  570. // //const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, d.unit);
  571. // d.o_qty = d.oamount;
  572. // d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  573. // d.c_qty = d.camount;
  574. // d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  575. // d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  576. // d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  577. //
  578. // const auditAmount = d.audit_amount.split(',');
  579. // for (const [i, aa] of auditAmount.entries()) {
  580. // d['amount_' + (i + 1)] = aa ? parseFloat(aa) : 0;
  581. // d['tp_' + (i + 1)] = this.ctx.helper.mul(d['amount_' + i], d.unit_price, decimal.tp);
  582. // }
  583. // }
  584. //return data;
  585. }
  586. async getStageJgcl(tid, sid, fields) {
  587. await this.ctx.service.tender.checkTender(tid);
  588. await this.ctx.service.stage.checkStage(sid);
  589. const data = await this.ctx.service.stageJgcl.getStageData(this.ctx.stage.id);
  590. const preData = await this.ctx.service.stageJgcl.getPreStageData(this.ctx.stage.order);
  591. for (const d of data) {
  592. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  593. if (pd) {
  594. d.pre_arrive_qty = pd.arrive_qty;
  595. d.pre_arrive_tp = pd.arrive_tp;
  596. d.pre_deduct_qty = pd.deduct_qty;
  597. d.pre_deduct_tp = pd.deduct_tp;
  598. }
  599. }
  600. return data;
  601. }
  602. async getStageBonus(tid, sid, fields) {
  603. await this.ctx.service.tender.checkTender(tid);
  604. await this.ctx.service.stage.checkStage(sid);
  605. const data = await ctx.service.stageBonus.getEndStageData(this.ctx.stage.order);
  606. return data;
  607. }
  608. async getStageOther(tid, sid, fields) {
  609. await this.ctx.service.tender.checkTender(tid);
  610. await this.ctx.service.stage.checkStage(sid);
  611. const data = await this.ctx.service.stageOther.getStageData(this.ctx.stage.id);
  612. const preData = await this.ctx.service.stageOther.getPreStageData(this.ctx.stage.order);
  613. for (const d of data) {
  614. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  615. if (pd) {
  616. d.pre_tp = pd.tp;
  617. }
  618. }
  619. return data;
  620. }
  621. }
  622. return ReportMemory;
  623. };