report_memory.js 38 KB

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