report_memory.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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 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. return this.stageImData.main;
  232. }
  233. async getMonthProgress(tid, fields) {
  234. const helper = this.ctx.helper;
  235. await this.ctx.service.tender.checkTender(tid);
  236. const tender = this.ctx.tender;
  237. const stages = await this.ctx.service.stage.getValidStages(tender.id);
  238. const lastStage = stages.length > 0 ? stages[0] : null;
  239. if (lastStage) {
  240. await this.ctx.service.stage.checkStageGatherData(lastStage);
  241. tender.gather_tp = helper.add(lastStage.contract_tp, lastStage.qc_tp);
  242. tender.end_contract_tp = helper.add(lastStage.contract_tp, lastStage.pre_contract_tp);
  243. tender.end_qc_tp = helper.add(lastStage.qc_tp, lastStage.pre_qc_tp);
  244. tender.end_gather_tp = helper.add(tender.end_contract_tp, tender.end_qc_tp);
  245. tender.pre_gather_tp = helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);
  246. tender.yf_tp = lastStage.yf_tp;
  247. tender.qc_ratio = helper.mul(helper.div(tender.end_qc_tp, tender.info.deal_param.contractPrice, 2), 100);
  248. tender.sum = helper.add(tender.total_price, tender.end_qc_tp);
  249. tender.pre_ratio = helper.mul(helper.div(tender.pre_gather_tp, tender.sum, 2), 100);
  250. tender.cur_ratio = helper.mul(helper.div(tender.gather_tp, tender.sum, 2), 100);
  251. tender.other_tp = helper.sub(helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);
  252. tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);
  253. }
  254. const monthProgress = [];
  255. for (const s of stages) {
  256. if (s.s_time) {
  257. let progress = monthProgress.find(function (x) {
  258. return x.month === s.s_time;
  259. });
  260. if (!progress) {
  261. progress = {month: s.s_time};
  262. monthProgress.push(progress);
  263. }
  264. progress.tp = helper.add(helper.add(progress.tp, s.contract_tp), s.qc_tp);
  265. }
  266. }
  267. monthProgress.sort(function (x, y) {
  268. return Date.parse(x.month) - Date.parse(y.month);
  269. });
  270. let sum = 0;
  271. for (const p of monthProgress) {
  272. p.ratio = helper.mul(helper.div(p.tp, tender.sum, 4), 100);
  273. sum = helper.add(sum, p.tp);
  274. p.end_tp = sum;
  275. p.end_ratio = helper.mul(helper.div(p.end_tp, tender.sum, 4), 100);
  276. }
  277. return monthProgress;
  278. }
  279. async _calcBillsBgl() {
  280. if (!this.ctx.stage) return;
  281. const helper = this.ctx.helper;
  282. const tender = this.ctx.tender;
  283. const stage = this.ctx.stage;
  284. const bglData = this.ctx.stage.readOnly
  285. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  286. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  287. for (const node of this.billsTree.nodes) {
  288. node.qc_bgl_code = '';
  289. if (node.children && node.children.length > 0) continue;
  290. const nodeBgl = helper._.filter(bglData, {lid: node.id});
  291. if (nodeBgl.length === 0) continue;
  292. helper._.pullAll(bglData, nodeBgl);
  293. const validBgl = helper._.filter(nodeBgl, function (x) {
  294. return !helper.checkZero(x.qty);
  295. });
  296. node.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  297. }
  298. }
  299. async getStageBillsData(tid, sid, fields) {
  300. await this.ctx.service.tender.checkTender(tid);
  301. if (sid) {
  302. await this.ctx.service.stage.checkStage(sid);
  303. }
  304. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  305. if (this._checkFieldsExist(fields, billsFields.stage)) {
  306. if (this.ctx.stage.readOnly) {
  307. const curStage = await this.ctx.service.stageBills.getAuditorStageData(this.ctx.tender.id,
  308. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  309. this.ctx.helper.assignRelaData(billsData, [
  310. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  311. ]);
  312. } else {
  313. const curStage = await this.ctx.service.stageBills.getLastestStageData(this.ctx.tender.id, this.ctx.stage.id);
  314. this.ctx.helper.assignRelaData(billsData, [
  315. {data: curStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: '', relaId: 'lid'}
  316. ]);
  317. }
  318. }
  319. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  320. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  321. this.ctx.helper.assignRelaData(billsData, [
  322. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  323. ]);
  324. }
  325. this.billsTree.loadDatas(billsData);
  326. this.billsTree.calculateAll();
  327. if (this._checkFieldsExist(fields, billsFields.bgl)) {
  328. await this._calcBillsBgl();
  329. }
  330. return this.billsTree.getDatas([
  331. 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
  332. 'code', 'b_code', 'name', 'unit', 'unit_price',
  333. 'deal_qty', 'deal_tp',
  334. 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'quantity', 'total_price',
  335. 'dgn_qty1', 'dgn_qty2',
  336. 'drawing_code', 'memo', 'node_type', 'is_tp',
  337. 'contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'gather_qty', 'gather_tp', 'postil',
  338. 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  339. 'end_contract_qty', 'end_contract_tp', 'end_qc_qty', 'end_qc_tp', 'end_gather_qty', 'end_gather_tp',
  340. 'final_tp', 'final_ratio',
  341. 'qc_bgl_code',
  342. 'chapter',
  343. ]);
  344. }
  345. async _calcPosBgl() {
  346. if (!this.ctx.stage) return;
  347. const helper = this.ctx.helper;
  348. const tender = this.ctx.tender;
  349. const stage = this.ctx.stage;
  350. const bglData = this.ctx.stage.readOnly
  351. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  352. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  353. for (const p of this.pos.datas) {
  354. p.qc_bgl_code = '';
  355. const pBgl = helper._.filter(bglData, {lid: p.lid, pid: p.id});
  356. if (pBgl.length === 0) continue;
  357. helper._.pullAll(bglData, pBgl);
  358. const validBgl = helper._.filter(pBgl, function (x) {
  359. return !helper.checkZero(x.qty);
  360. });
  361. p.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  362. }
  363. }
  364. async getStagePosData(tid, sid, fields) {
  365. await this.ctx.service.tender.checkTender(tid);
  366. await this.ctx.service.stage.checkStage(sid);
  367. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  368. if (this._checkFieldsExist(fields, posFields.stage)) {
  369. if (this.ctx.stage.readOnly) {
  370. const curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  371. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  372. this.ctx.helper.assignRelaData(posData, [
  373. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  374. ]);
  375. } else {
  376. const curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  377. this.ctx.helper.assignRelaData(posData, [
  378. {data: curPosStage, fields: ['contract_qty', 'qc_qty'], prefix: '', relaId: 'pid'}
  379. ]);
  380. }
  381. }
  382. if (this._checkFieldsExist(fields, posFields.stageEnd)) {
  383. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  384. this.ctx.helper.assignRelaData(posData, [
  385. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  386. ]);
  387. }
  388. this.pos.loadDatas(posData);
  389. this.pos.calculateAll();
  390. if (this._checkFieldsExist(fields, posFields.bgl)) {
  391. await this._calcPosBgl();
  392. }
  393. return this.pos.getDatas();
  394. }
  395. _getStageValidRole () {
  396. if (!this.ctx.stage) throw '期数据错误,请重试';
  397. if (this.stageValidRole && this.stageValidRole.length > 0) return;
  398. const result = [{dataOrder: 0, flowOrder: 0, uid: this.ctx.stage.user_id}];
  399. for (const auditor of this.ctx.stage.auditors) {
  400. if (auditor.status === audit.stage.status.checked ||
  401. (auditor.status === audit.stage.status.checking && !this.ctx.stage.readOnly)) {
  402. const role = result.find(function (r) {
  403. return r.uid === auditor.aid;
  404. });
  405. if (role) {
  406. role.dataOrder = auditor.order;
  407. } else {
  408. result.push({
  409. dataOrder: auditor.order,
  410. flowOrder: result.length,
  411. uid: auditor.aid
  412. })
  413. }
  414. }
  415. }
  416. this.stageValidRole = result;
  417. };
  418. async getStageBillsCompareData(tid, sid, fields) {
  419. await this.ctx.service.tender.checkTender(tid);
  420. await this.ctx.service.stage.checkStage(sid);
  421. await this._getStageValidRole();
  422. const stage = this.ctx.stage, helper = this.ctx.helper;
  423. const validRole = this.stageValidRole;
  424. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  425. const allStageBills = await this.ctx.service.stageBills.getAllDataByCondition({where: {sid: sid}});
  426. const stageBillsIndex = {}, timesLen = 100;
  427. for (const role of validRole) {
  428. const stageBills = this.ctx.helper._.filter(allStageBills, function (x) {
  429. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  430. });
  431. this.ctx.helper._.pullAll(allStageBills, stageBills);
  432. for (const sb of stageBills) {
  433. const key = 'sb-' + sb.lid;
  434. const sbi = stageBillsIndex[key];
  435. if (sbi) {
  436. if ((sbi.times * timesLen + sbi.order) < (sb.times * timesLen + sb.order)) stageBillsIndex[key] = sb;
  437. } else {
  438. stageBillsIndex[key] = sb;
  439. }
  440. }
  441. const filterStageBills = [];
  442. for (const prop in stageBillsIndex) {
  443. filterStageBills.push(stageBillsIndex[prop]);
  444. }
  445. this.ctx.helper.assignRelaData(billsData, [
  446. {data: filterStageBills, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'r' + role.flowOrder + '_', relaId: 'lid'}
  447. ]);
  448. }
  449. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  450. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  451. this.ctx.helper.assignRelaData(billsData, [
  452. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  453. ]);
  454. }
  455. this.billsTree.loadDatas(billsData);
  456. this.billsTree.setting.calcFields = ['deal_tp', 'total_price', 'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp'];
  457. for (const role of validRole) {
  458. const prefix = 'r' + role.flowOrder + '_';
  459. this.billsTree.setting.calcFields.push(prefix + 'contract_tp', prefix + 'qc_tp', prefix + 'gather_tp');
  460. }
  461. this.billsTree.calculateAll(function(node) {
  462. let prefix = '';
  463. if (node.children && node.children.length === 0) {
  464. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  465. for (const role of validRole) {
  466. prefix = 'r' + role.flowOrder + '_';
  467. node[prefix + 'gather_qty'] = helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  468. }
  469. }
  470. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  471. for (const role of validRole) {
  472. prefix = 'r' + role.flowOrder + '_';
  473. node[prefix + 'gather_tp'] = helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  474. }
  475. });
  476. return this.billsTree.getDefaultDatas();
  477. // return this.billsTree.getDatas([
  478. // 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', //8
  479. // 'code', 'b_code', 'name', 'unit', 'unit_price', //5
  480. // 'deal_qty', 'deal_tp', 'quantity', 'total_price', 'dgn_qty1', 'dgn_qty2', //6
  481. // 'drawing_code', 'memo', 'node_type', 'is_tp', //4
  482. // 'r0_contract_qty', 'r0_contract_tp', 'r0_qc_qty', 'r0_qc_tp', 'r0_gather_qty', 'r0_gather_tp', //6
  483. // 'r1_contract_qty', 'r1_contract_tp', 'r1_qc_qty', 'r1_qc_tp', 'r1_gather_qty', 'r1_gather_tp',
  484. // 'r2_contract_qty', 'r2_contract_tp', 'r2_qc_qty', 'r2_qc_tp', 'r2_gather_qty', 'r2_gather_tp',
  485. // 'r3_contract_qty', 'r3_contract_tp', 'r3_qc_qty', 'r3_qc_tp', 'r3_gather_qty', 'r3_gather_tp',
  486. // 'r4_contract_qty', 'r4_contract_tp', 'r4_qc_qty', 'r4_qc_tp', 'r4_gather_qty', 'r4_gather_tp',
  487. // 'r5_contract_qty', 'r5_contract_tp', 'r5_qc_qty', 'r5_qc_tp', 'r5_gather_qty', 'r5_gather_tp',
  488. // 'r6_contract_qty', 'r6_contract_tp', 'r6_qc_qty', 'r6_qc_tp', 'r6_gather_qty', 'r6_gather_tp',
  489. // 'r7_contract_qty', 'r7_contract_tp', 'r7_qc_qty', 'r7_qc_tp', 'r7_gather_qty', 'r7_gather_tp',
  490. // 'r8_contract_qty', 'r8_contract_tp', 'r8_qc_qty', 'r8_qc_tp', 'r8_gather_qty', 'r8_gather_tp',
  491. // 'r9_contract_qty', 'r9_contract_tp', 'r9_qc_qty', 'r9_qc_tp', 'r9_gather_qty', 'r9_gather_tp',
  492. // 'r10_contract_qty', 'r10_contract_tp', 'r10_qc_qty', 'r10_qc_tp', 'r10_gather_qty', 'r10_gather_tp',
  493. // 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  494. // 'chapter', //1
  495. // ]);
  496. }
  497. async getStagePosCompareData(tid, sid, fields) {
  498. await this.ctx.service.tender.checkTender(tid);
  499. await this.ctx.service.stage.checkStage(sid);
  500. await this._getStageValidRole();
  501. const stage = this.ctx.stage, helper = this.ctx.helper;
  502. const validRole = this.stageValidRole;
  503. const allStagePos = await this.ctx.service.stagePos.getAllDataByCondition({where: {sid: sid}});
  504. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  505. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  506. this.ctx.helper.assignRelaData(posData, [
  507. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  508. ]);
  509. const stagePosIndex = {}, timesLen = 100;
  510. for (const role of validRole) {
  511. const stagePos = this.ctx.helper._.filter(allStagePos, function (x) {
  512. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  513. });
  514. this.ctx.helper._.pullAll(allStagePos, stagePos);
  515. for (const sp of stagePos) {
  516. const key = 'sp-' + sp.pid;
  517. const spi = stagePosIndex[key];
  518. if (spi) {
  519. if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp;
  520. } else {
  521. stagePosIndex[key] = sp;
  522. }
  523. }
  524. const filterStagePos = [];
  525. for (const prop in stagePosIndex) {
  526. filterStagePos.push(stagePosIndex[prop]);
  527. }
  528. this.ctx.helper.assignRelaData(posData, [
  529. {data: filterStagePos, fields: ['contract_qty', 'qc_qty'], prefix: 'r' + role.flowOrder + '_', relaId: 'pid'}
  530. ]);
  531. }
  532. this.pos.loadDatas(posData);
  533. this.pos.calculateAll(function (p) {
  534. p.pre_gather_qty = helper.add(p.pre_contract_qty, p.pre_qc_qty);
  535. for (const role of validRole) {
  536. const prefix = 'r' + role.flowOrder + '_';
  537. p[prefix + 'gather_qty'] = helper.add(p[prefix + 'contract_qty'], p[prefix + 'qc_qty']);
  538. }
  539. });
  540. return this.pos.getDatas();
  541. }
  542. async getStagePayData(tid, sid, fields) {
  543. await this.ctx.service.tender.checkTender(tid);
  544. await this.ctx.service.stage.checkStage(sid);
  545. const stage = this.ctx.stage;
  546. const dealPay = await this.ctx.service.stagePay.getStagePays(this.ctx.stage);
  547. if (!this.ctx.stage.readOnly) {
  548. // 计算 本期金额
  549. const PayCalculator = require('../lib/pay_calc');
  550. const payCalculator = new PayCalculator(this.ctx, this.ctx.stage, this.ctx.tender.info);
  551. await payCalculator.calculateAll(dealPay);
  552. }
  553. if (this._checkFieldsExistReg(fields, 'r[0-9]+_tp')) {
  554. const validRole = this._getStageValidRole();
  555. const allStagePays = await this.ctx.service.stagePay.getAllDataByCondition({
  556. where: {sid: stage.id, stimes: stage.curTimes}
  557. });
  558. for (const [i, role] of validRole.entries()) {
  559. if (i < validRole.length - 1) {
  560. const stagePays = this.ctx.helper._.filter(allStagePays, function (x) {
  561. return x.stimes === stage.curTimes && x.sorder === role.dataOrder;
  562. });
  563. this.ctx.helper._.pullAll(allStagePays, stagePays);
  564. for (const sp of stagePays) {
  565. const dp = dealPay.find(function (x) {return x.pid === sp.pid});
  566. if (dp) {
  567. dp['r' + role.flowOrder + '_tp'] = sp.tp;
  568. }
  569. }
  570. } else {
  571. for (const dp of dealPay) {
  572. dp['r' + role.flowOrder + '_tp'] = dp.tp;
  573. }
  574. }
  575. }
  576. }
  577. return dealPay;
  578. }
  579. _getChangeConstName(define, value) {
  580. for (const prop in define) {
  581. if (define[prop].value === value) {
  582. return define[prop].name;
  583. }
  584. }
  585. return '';
  586. }
  587. async _generateChange(tid) {
  588. if (this.changeData !== null) return;
  589. const self = this;
  590. try {
  591. const decimal = this.ctx.tender.info.decimal, ctx = this.ctx;
  592. const change = await this.ctx.service.change.getAllCheckedChanges(tid);
  593. for (const c of change) {
  594. const types = ctx.helper._.map(c.type.split(','), function (t) {
  595. return self._getChangeConstName(changeConst.type, ctx.helper._.toInteger(t));
  596. });
  597. c.type = types.join(';');
  598. c.class = this._getChangeConstName(changeConst.class, c.class);
  599. c.quality = this._getChangeConstName(changeConst.quality, c.quality);
  600. c.charge = this._getChangeConstName(changeConst.charge, c.charge);
  601. c.attachments = await ctx.service.changeAtt.getChangeAttachment(c.cid);
  602. const names = ctx.helper._.map(c.attachments, function (x) {
  603. return x.filename + x.fileext;
  604. });
  605. c.attNames = names.join('\n');
  606. }
  607. const changeBills = await this.ctx.service.changeAuditList.getChangeAuditBills(tid);
  608. for (const d of changeBills) {
  609. //const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, d.unit);
  610. d.o_qty = d.oamount;
  611. d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  612. d.c_qty = d.camount;
  613. d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  614. d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  615. d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  616. const auditAmount = d.audit_amount.split(',');
  617. const relaChange = ctx.helper._.find(change, {cid: d.cid});
  618. for (const [i, aa] of auditAmount.entries()) {
  619. const amountField = 'qty_' + (i+1), tpField = 'tp_' + (i+1);
  620. d[amountField] = aa ? parseFloat(aa) : 0;
  621. d[tpField] = ctx.helper.mul(d[amountField], d.unit_price, decimal.tp);
  622. if (relaChange) {
  623. relaChange[tpField] = ctx.helper.add(relaChange[tpField], d[tpField]);
  624. }
  625. }
  626. }
  627. change.sort(function (a, b) {
  628. return a.code.localeCompare(b.code);
  629. });
  630. changeBills.sort(function (a, b) {
  631. const aCIndex = change.findIndex(function (c) {
  632. return c.cid === a.cid;
  633. });
  634. const bCIndex = change.findIndex(function (c) {
  635. return c.cid === b.cid;
  636. });
  637. return aCIndex === bCIndex
  638. ? ctx.helper.compareCode(a.code, b.code)
  639. : aCIndex - bCIndex;
  640. });
  641. this.changeData = {change: change, bills: changeBills};
  642. } catch(err) {
  643. this.ctx.helper.log(err);
  644. throw err;
  645. this.changeData = {change: [], bills: []};
  646. }
  647. }
  648. async getChangeData(tid, sid, fields) {
  649. await this.ctx.service.tender.checkTender(tid);
  650. await this._generateChange(tid);
  651. return this.changeData.change;
  652. }
  653. async getChangeBillsData(tid, sid, fields) {
  654. await this.ctx.service.tender.checkTender(tid);
  655. await this._generateChange(tid);
  656. return this.changeData.bills;
  657. // const data = await this.ctx.service.changeAuditList.getChangeAuditBills(tid);
  658. // for (const d of data) {
  659. // //const precision = this.ctx.helper.findPrecision(this.ctx.tender.info.precision, d.unit);
  660. // d.o_qty = d.oamount;
  661. // d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  662. // d.c_qty = d.camount;
  663. // d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  664. // d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  665. // d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  666. //
  667. // const auditAmount = d.audit_amount.split(',');
  668. // for (const [i, aa] of auditAmount.entries()) {
  669. // d['amount_' + (i + 1)] = aa ? parseFloat(aa) : 0;
  670. // d['tp_' + (i + 1)] = this.ctx.helper.mul(d['amount_' + i], d.unit_price, decimal.tp);
  671. // }
  672. // }
  673. //return data;
  674. }
  675. async getStageJgcl(tid, sid, fields) {
  676. await this.ctx.service.tender.checkTender(tid);
  677. await this.ctx.service.stage.checkStage(sid);
  678. const data = await this.ctx.service.stageJgcl.getStageData(this.ctx.stage.id);
  679. const preData = await this.ctx.service.stageJgcl.getPreStageData(this.ctx.stage.order);
  680. for (const d of data) {
  681. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  682. if (pd) {
  683. d.pre_arrive_qty = pd.arrive_qty;
  684. d.pre_arrive_tp = pd.arrive_tp;
  685. d.pre_deduct_qty = pd.deduct_qty;
  686. d.pre_deduct_tp = pd.deduct_tp;
  687. }
  688. }
  689. return data;
  690. }
  691. async getStageBonus(tid, sid, fields) {
  692. await this.ctx.service.tender.checkTender(tid);
  693. await this.ctx.service.stage.checkStage(sid);
  694. const data = await ctx.service.stageBonus.getEndStageData(this.ctx.stage.order);
  695. return data;
  696. }
  697. async getStageOther(tid, sid, fields) {
  698. await this.ctx.service.tender.checkTender(tid);
  699. await this.ctx.service.stage.checkStage(sid);
  700. const data = await this.ctx.service.stageOther.getStageData(this.ctx.stage.id);
  701. const preData = await this.ctx.service.stageOther.getPreStageData(this.ctx.stage.order);
  702. for (const d of data) {
  703. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  704. if (pd) {
  705. d.pre_tp = pd.tp;
  706. }
  707. }
  708. return data;
  709. }
  710. }
  711. return ReportMemory;
  712. };