report_memory.js 40 KB

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