report_memory.js 41 KB

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