report_memory.js 46 KB

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