report_memory.js 41 KB

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