report_memory.js 34 KB

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