report_memory.js 41 KB

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