report_memory.js 56 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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.pos = new Ledger.pos({
  59. id: 'id', ledgerId: 'lid',
  60. updateFields: ['contract_qty', 'qc_qty', 'postil'],
  61. calc: function (p) {
  62. p.pre_gather_qty = ctx.helper.add(p.pre_contract_qty, p.pre_qc_qty);
  63. p.gather_qty = ctx.helper.add(p.contract_qty, p.qc_qty);
  64. p.end_contract_qty = self.ctx.helper.add(p.pre_contract_qty, p.contract_qty);
  65. p.end_qc_qty = self.ctx.helper.add(p.pre_qc_qty, p.qc_qty);
  66. p.end_gather_qty = self.ctx.helper.add(p.pre_gather_qty, p.gather_qty);
  67. }
  68. });
  69. // 需要缓存的数据
  70. this.stageImData = null;
  71. this.changeData = null;
  72. this.stageValidRole = [];
  73. }
  74. _getNewBillsTree(calcFields) {
  75. return new Ledger.billsTree(this.ctx, {
  76. id: 'ledger_id',
  77. pid: 'ledger_pid',
  78. order: 'order',
  79. level: 'level',
  80. rootId: -1,
  81. keys: ['id', 'tender_id', 'ledger_id'],
  82. stageId: 'id',
  83. calcFields: calcFields || ['deal_tp', 'total_price', 'contract_tp', 'qc_tp', 'gather_tp', 'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp'],
  84. calc: function (node, helper) {
  85. if (node.children && node.children.length === 0) {
  86. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  87. node.gather_qty = helper.add(node.contract_qty, node.qc_qty);
  88. node.end_contract_qty = helper.add(node.pre_contract_qty, node.contract_qty);
  89. node.end_qc_qty = helper.add(node.pre_qc_qty, node.qc_qty);
  90. node.end_gather_qty = helper.add(node.pre_gather_qty, node.gather_qty);
  91. }
  92. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  93. node.gather_tp = helper.add(node.contract_tp, node.qc_tp);
  94. node.end_contract_tp = helper.add(node.pre_contract_tp, node.contract_tp);
  95. node.end_qc_tp = helper.add(node.pre_qc_tp, node.qc_tp);
  96. node.end_gather_tp = helper.add(node.pre_gather_tp, node.gather_tp);
  97. node.final_tp = helper.add(node.total_price, node.end_qc_tp);
  98. node.final_ratio = helper.mul(helper.div(node.end_gather_tp, node.final_tp, 4), 100);
  99. }
  100. });
  101. }
  102. _checkFieldsExist(source, check) {
  103. for (const s of source) {
  104. if (check.indexOf(s) >= 0) {
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. _checkFieldsExistReg(source, regStr) {
  111. const reg = new RegExp(regStr, 'igm');
  112. for (const s of source) {
  113. if (reg.test(s)) {
  114. return true;
  115. }
  116. }
  117. return false;
  118. }
  119. // build-time: 162-384ms, redis-cache: 0-41ms, mysql + IO: 116-146ms
  120. // 一定程度上算是大Value缓存,数据多了以后:
  121. // 1. 达到redis内存阈值时,数据会swap到磁盘,此时将消耗IO时间
  122. // 2. redis单独服务器
  123. // 3. redis集群
  124. async _getReportMemoryCache(name, tid, sid, time, version = '') {
  125. // redis
  126. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  127. const data = await this.cache.get(cacheKey);
  128. if (data) {
  129. return eval(data);
  130. } else {
  131. return null;
  132. }
  133. // mysql + IO
  134. // const rm = await this.getDataByCondition({
  135. // tid: tid, sid: sid, name: name, time: time
  136. // });
  137. // if (rm && rm.file) {
  138. // const file = path.join(this.ctx.app.config.filePath, 'report', 'cache', rm.file);
  139. // if (fs.existsSync(file)) {
  140. // const data = await fs.readFileSync(file, 'utf8');
  141. // return eval(data);
  142. // } else {
  143. // return null;
  144. // }
  145. // }
  146. }
  147. async _setReportMemoryCache(name, tid, sid, time, data, version = '') {
  148. // redis
  149. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  150. this.cache.set(cacheKey, JSON.stringify(data), 'EX', this.ctx.app.config.cacheTime);
  151. // mysql + IO
  152. // const file = path.join('report', 'cache', 'rm' + (new Date()).getTime() + '.json');
  153. // await this.ctx.helper.saveBufferFile(JSON.stringify(data), path.join(this.ctx.app.config.filePath, file));
  154. // const rm = await this.getDataByCondition({
  155. // tid: tid, sid: sid, name: name, time: time
  156. // });
  157. // if (rm) {
  158. // await this.db.update(this.tableName, {id: rm.id, file: file});
  159. // } else {
  160. // await this.db.insert(this.tableName, {tid: tid, sid: sid, name: name, time: time, file: file});
  161. // }
  162. }
  163. async _generateStageIm(tid, sid, isTz = true) {
  164. if (isTz && [imType.tz.value, imType.bb.value].indexOf(this.ctx.stage.im_type) === -1) {
  165. throw '您查看的报表跟设置不符,请查看“总量控制”的报表';
  166. } else if (!isTz && [imType.zl.value, imType.bw.value].indexOf(this.ctx.stage.im_type) === -1) {
  167. throw '您查看的报表跟设置不符,请查看“0号台账”的报表';
  168. }
  169. const stageIm = new StageIm(this.ctx);
  170. await stageIm.buildImData();
  171. this.stageImData.main = stageIm.ImData;
  172. if (isTz) {
  173. this.stageImData.bills = stageIm.ImBillsData;
  174. await this._setReportMemoryCache(stageImTz, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  175. await this._setReportMemoryCache(stageImTzBills, tid, sid, this.ctx.stage.cacheTime, this.stageImData.bills, stageImVersion);
  176. } else {
  177. await this._setReportMemoryCache(stageImZl, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  178. }
  179. }
  180. async getStageImTzData(tid, sid, fields, readCache = true) {
  181. try {
  182. await this.ctx.service.tender.checkTender(tid);
  183. await this.ctx.service.stage.checkStage(sid);
  184. if (readCache) {
  185. const cache = await this._getReportMemoryCache('mem_stage_im_tz', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  186. if (cache) return cache;
  187. }
  188. if (!this.stageImData) {
  189. this.stageImData = {};
  190. try {
  191. await this._generateStageIm(tid, sid);
  192. } catch (err) {
  193. if (err.stack) {
  194. this.ctx.logger.error(err);
  195. }
  196. this.stageImData.main = err.stack ? '数据错误' : err;
  197. this.stageImData.bills = this.stageImData.main;
  198. }
  199. }
  200. return this.stageImData.main;
  201. } catch (err) {
  202. return [];
  203. }
  204. }
  205. async getStageImTzBillsData(tid, sid, fields, readCache = true) {
  206. try {
  207. await this.ctx.service.tender.checkTender(tid);
  208. await this.ctx.service.stage.checkStage(sid);
  209. if (readCache) {
  210. const cache = await this._getReportMemoryCache('mem_stage_im_tz_bills', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  211. if (cache) return cache;
  212. }
  213. if (!this.stageImData) {
  214. this.stageImData = {};
  215. try {
  216. await this._generateStageIm(tid, sid);
  217. } catch (err) {
  218. if (err.stack) {
  219. this.ctx.logger.error(err);
  220. }
  221. this.stageImData.main = err.stack ? '数据错误' : err;
  222. this.stageImData.bills = this.stageImData.main;
  223. }
  224. }
  225. return this.stageImData.bills;
  226. } catch (err) {
  227. return [];
  228. }
  229. }
  230. async getStageImZlData(tid, sid, fields, readCache = true) {
  231. try {
  232. await this.ctx.service.tender.checkTender(tid);
  233. await this.ctx.service.stage.checkStage(sid);
  234. if (readCache) {
  235. const cache = await this._getReportMemoryCache('mem_stage_im_zl', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  236. if (cache) return cache;
  237. }
  238. this.stageImData = {};
  239. try {
  240. await this._generateStageIm(tid, sid, false);
  241. } catch (err) {
  242. if (err.stack) {
  243. this.ctx.logger.error(err);
  244. }
  245. this.stageImData.main = err.statck ? '数据错误' : err;
  246. }
  247. return this.stageImData.main;
  248. } catch (err) {
  249. return [];
  250. }
  251. }
  252. async getMonthProgress(tid, fields) {
  253. const helper = this.ctx.helper;
  254. await this.ctx.service.tender.checkTender(tid);
  255. const tender = this.ctx.tender;
  256. const stages = await this.ctx.service.stage.getValidStages(tender.id);
  257. const lastStage = stages.length > 0 ? stages[0] : null;
  258. if (lastStage) {
  259. await this.ctx.service.stage.checkStageGatherData(lastStage);
  260. tender.gather_tp = helper.add(lastStage.contract_tp, lastStage.qc_tp);
  261. tender.end_contract_tp = helper.add(lastStage.contract_tp, lastStage.pre_contract_tp);
  262. tender.end_qc_tp = helper.add(lastStage.qc_tp, lastStage.pre_qc_tp);
  263. tender.end_gather_tp = helper.add(tender.end_contract_tp, tender.end_qc_tp);
  264. tender.pre_gather_tp = helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);
  265. tender.yf_tp = lastStage.yf_tp;
  266. tender.qc_ratio = helper.mul(helper.div(tender.end_qc_tp, tender.info.deal_param.contractPrice, 2), 100);
  267. tender.sum = helper.add(tender.total_price, tender.end_qc_tp);
  268. tender.pre_ratio = helper.mul(helper.div(tender.pre_gather_tp, tender.sum, 2), 100);
  269. tender.cur_ratio = helper.mul(helper.div(tender.gather_tp, tender.sum, 2), 100);
  270. tender.other_tp = helper.sub(helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);
  271. tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);
  272. }
  273. const monthProgress = [];
  274. for (const s of stages) {
  275. if (s.s_time) {
  276. let progress = monthProgress.find(function (x) {
  277. return x.month === s.s_time;
  278. });
  279. if (!progress) {
  280. progress = {month: s.s_time};
  281. monthProgress.push(progress);
  282. }
  283. progress.tp = helper.add(helper.add(progress.tp, s.contract_tp), s.qc_tp);
  284. }
  285. }
  286. monthProgress.sort(function (x, y) {
  287. return Date.parse(x.month) - Date.parse(y.month);
  288. });
  289. let sum = 0;
  290. for (const p of monthProgress) {
  291. p.ratio = helper.mul(helper.div(p.tp, tender.sum, 4), 100);
  292. sum = helper.add(sum, p.tp);
  293. p.end_tp = sum;
  294. p.end_ratio = helper.mul(helper.div(p.end_tp, tender.sum, 4), 100);
  295. }
  296. return monthProgress;
  297. }
  298. async _calcBillsBgl(billsTree) {
  299. if (!this.ctx.stage) return;
  300. const helper = this.ctx.helper;
  301. const tender = this.ctx.tender;
  302. const stage = this.ctx.stage;
  303. const bglData = this.ctx.stage.readOnly
  304. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  305. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  306. for (const node of billsTree.nodes) {
  307. node.qc_bgl_code = '';
  308. if (node.children && node.children.length > 0) continue;
  309. const nodeBgl = helper._.filter(bglData, {lid: node.id});
  310. if (nodeBgl.length === 0) continue;
  311. helper._.pullAll(bglData, nodeBgl);
  312. const validBgl = helper._.filter(nodeBgl, function (x) {
  313. return !helper.checkZero(x.qty);
  314. });
  315. node.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  316. }
  317. }
  318. _calcLeafXmjRela(billsTree) {
  319. for (const node of billsTree.nodes) {
  320. if (node.b_code) {
  321. const leafXmj = billsTree.getLeafXmjParent(node);
  322. node.leaf_xmj_id = leafXmj ? leafXmj.id : -1;
  323. }
  324. }
  325. }
  326. async getStageBillsData(tid, sid, fields) {
  327. try {
  328. await this.ctx.service.tender.checkTender(tid);
  329. if (sid) {
  330. await this.ctx.service.stage.checkStage(sid);
  331. }
  332. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  333. if (this._checkFieldsExist(fields, billsFields.stageDgn)) {
  334. const dgnData = await this.ctx.service.stageBillsDgn.getDgnData(this.ctx.tender.id);
  335. for (const d of dgnData) {
  336. const l = this.ctx.helper._.find(billsData, {id: d.id});
  337. this.ctx.helper._.assignIn(l, d);
  338. }
  339. }
  340. if (this._checkFieldsExist(fields, billsFields.stage)) {
  341. if (this.ctx.stage.readOnly) {
  342. const curStage = await this.ctx.service.stageBills.getAuditorStageData2(this.ctx.tender.id,
  343. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  344. this.ctx.helper.assignRelaData(billsData, [
  345. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp', 'postil'], prefix: '', relaId: 'lid'}
  346. ]);
  347. } else {
  348. const curStage = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  349. this.ctx.helper.assignRelaData(billsData, [
  350. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp', 'postil'], prefix: '', relaId: 'lid'}
  351. ]);
  352. }
  353. }
  354. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  355. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  356. this.ctx.helper.assignRelaData(billsData, [
  357. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  358. ]);
  359. }
  360. const billsTree = this._getNewBillsTree();
  361. billsTree.loadDatas(billsData);
  362. billsTree.calculateAll();
  363. if (this._checkFieldsExist(fields, billsFields.bgl)) {
  364. await this._calcBillsBgl(billsTree);
  365. }
  366. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  367. this._calcLeafXmjRela(billsTree);
  368. }
  369. return billsTree.getDefaultDatas();
  370. } catch(err) {
  371. return []
  372. }
  373. }
  374. async _calcPosBgl() {
  375. if (!this.ctx.stage) return;
  376. const helper = this.ctx.helper;
  377. const tender = this.ctx.tender;
  378. const stage = this.ctx.stage;
  379. const bglData = this.ctx.stage.readOnly
  380. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  381. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  382. for (const p of this.pos.datas) {
  383. p.qc_bgl_code = '';
  384. const pBgl = helper._.filter(bglData, {lid: p.lid, pid: p.id});
  385. if (pBgl.length === 0) continue;
  386. helper._.pullAll(bglData, pBgl);
  387. const validBgl = helper._.filter(pBgl, function (x) {
  388. return !helper.checkZero(x.qty);
  389. });
  390. p.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  391. }
  392. }
  393. async getStagePosData(tid, sid, fields) {
  394. try {
  395. await this.ctx.service.tender.checkTender(tid);
  396. if (sid) {
  397. await this.ctx.service.stage.checkStage(sid);
  398. }
  399. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  400. if (this._checkFieldsExist(fields, posFields.stage)) {
  401. if (this.ctx.stage.readOnly) {
  402. const curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  403. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  404. this.ctx.helper.assignRelaData(posData, [
  405. {data: curPosStage, fields: ['contract_qty', 'qc_qty', 'contract_expr', 'postil'], prefix: '', relaId: 'pid'}
  406. ]);
  407. } else {
  408. const curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  409. this.ctx.helper.assignRelaData(posData, [
  410. {data: curPosStage, fields: ['contract_qty', 'qc_qty', 'contract_expr', 'postil'], prefix: '', relaId: 'pid'}
  411. ]);
  412. }
  413. }
  414. if (this._checkFieldsExist(fields, posFields.stageEnd)) {
  415. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  416. this.ctx.helper.assignRelaData(posData, [
  417. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  418. ]);
  419. }
  420. this.pos.loadDatas(posData);
  421. this.pos.calculateAll();
  422. if (this._checkFieldsExist(fields, posFields.bgl)) {
  423. await this._calcPosBgl();
  424. }
  425. return this.pos.getDatas();
  426. } catch (err) {
  427. return [];
  428. }
  429. }
  430. _getStageValidRole () {
  431. if (!this.ctx.stage) throw '期数据错误,请重试';
  432. if (this.stageValidRole && this.stageValidRole.length > 0) return;
  433. const result = [{dataOrder: 0, flowOrder: 0, uid: this.ctx.stage.user_id}];
  434. for (const auditor of this.ctx.stage.auditors) {
  435. if (auditor.status === audit.stage.status.checked ||
  436. (auditor.status === audit.stage.status.checking && !this.ctx.stage.readOnly)) {
  437. const role = result.find(function (r) {
  438. return r.uid === auditor.aid;
  439. });
  440. if (role) {
  441. role.dataOrder = auditor.order;
  442. } else {
  443. result.push({
  444. dataOrder: auditor.order,
  445. flowOrder: result.length,
  446. uid: auditor.aid
  447. })
  448. }
  449. }
  450. }
  451. this.stageValidRole = result;
  452. };
  453. async getStageBillsCompareData(tid, sid, fields) {
  454. try {
  455. await this.ctx.service.tender.checkTender(tid);
  456. await this.ctx.service.stage.checkStage(sid);
  457. await this._getStageValidRole();
  458. const stage = this.ctx.stage, helper = this.ctx.helper;
  459. const validRole = this.stageValidRole;
  460. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  461. const allStageBills = await this.ctx.service.stageBills.getAllDataByCondition({where: {sid: sid}});
  462. const stageBillsIndex = {}, timesLen = 100;
  463. for (const role of validRole) {
  464. const stageBills = this.ctx.helper._.filter(allStageBills, function (x) {
  465. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  466. });
  467. this.ctx.helper._.pullAll(allStageBills, stageBills);
  468. for (const sb of stageBills) {
  469. const key = 'sb-' + sb.lid;
  470. const sbi = stageBillsIndex[key];
  471. if (sbi) {
  472. if ((sbi.times * timesLen + sbi.order) < (sb.times * timesLen + sb.order)) stageBillsIndex[key] = sb;
  473. } else {
  474. stageBillsIndex[key] = sb;
  475. }
  476. }
  477. const filterStageBills = [];
  478. for (const prop in stageBillsIndex) {
  479. filterStageBills.push(stageBillsIndex[prop]);
  480. }
  481. this.ctx.helper.assignRelaData(billsData, [
  482. {data: filterStageBills, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'r' + role.flowOrder + '_', relaId: 'lid'}
  483. ]);
  484. }
  485. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  486. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  487. this.ctx.helper.assignRelaData(billsData, [
  488. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  489. ]);
  490. }
  491. const billsTree = this._getNewBillsTree();
  492. billsTree.loadDatas(billsData);
  493. for (const role of validRole) {
  494. const prefix = 'r' + role.flowOrder + '_';
  495. billsTree.setting.calcFields.push(prefix + 'contract_tp', prefix + 'qc_tp', prefix + 'gather_tp');
  496. }
  497. billsTree.calculateAll(function(node) {
  498. let prefix = '';
  499. if (node.children && node.children.length === 0) {
  500. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  501. for (const role of validRole) {
  502. prefix = 'r' + role.flowOrder + '_';
  503. node[prefix + 'gather_qty'] = helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  504. }
  505. }
  506. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  507. for (const role of validRole) {
  508. prefix = 'r' + role.flowOrder + '_';
  509. node[prefix + 'gather_tp'] = helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  510. }
  511. });
  512. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  513. this._calcLeafXmjRela(billsTree);
  514. }
  515. return billsTree.getDefaultDatas();
  516. // return billsTree.getDatas([
  517. // 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', //8
  518. // 'code', 'b_code', 'name', 'unit', 'unit_price', //5
  519. // 'deal_qty', 'deal_tp', 'quantity', 'total_price', 'dgn_qty1', 'dgn_qty2', //6
  520. // 'drawing_code', 'memo', 'node_type', 'is_tp', //4
  521. // 'r0_contract_qty', 'r0_contract_tp', 'r0_qc_qty', 'r0_qc_tp', 'r0_gather_qty', 'r0_gather_tp', //6
  522. // 'r1_contract_qty', 'r1_contract_tp', 'r1_qc_qty', 'r1_qc_tp', 'r1_gather_qty', 'r1_gather_tp',
  523. // 'r2_contract_qty', 'r2_contract_tp', 'r2_qc_qty', 'r2_qc_tp', 'r2_gather_qty', 'r2_gather_tp',
  524. // 'r3_contract_qty', 'r3_contract_tp', 'r3_qc_qty', 'r3_qc_tp', 'r3_gather_qty', 'r3_gather_tp',
  525. // 'r4_contract_qty', 'r4_contract_tp', 'r4_qc_qty', 'r4_qc_tp', 'r4_gather_qty', 'r4_gather_tp',
  526. // 'r5_contract_qty', 'r5_contract_tp', 'r5_qc_qty', 'r5_qc_tp', 'r5_gather_qty', 'r5_gather_tp',
  527. // 'r6_contract_qty', 'r6_contract_tp', 'r6_qc_qty', 'r6_qc_tp', 'r6_gather_qty', 'r6_gather_tp',
  528. // 'r7_contract_qty', 'r7_contract_tp', 'r7_qc_qty', 'r7_qc_tp', 'r7_gather_qty', 'r7_gather_tp',
  529. // 'r8_contract_qty', 'r8_contract_tp', 'r8_qc_qty', 'r8_qc_tp', 'r8_gather_qty', 'r8_gather_tp',
  530. // 'r9_contract_qty', 'r9_contract_tp', 'r9_qc_qty', 'r9_qc_tp', 'r9_gather_qty', 'r9_gather_tp',
  531. // 'r10_contract_qty', 'r10_contract_tp', 'r10_qc_qty', 'r10_qc_tp', 'r10_gather_qty', 'r10_gather_tp',
  532. // 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  533. // 'chapter', //1
  534. // ]);
  535. } catch (err) {
  536. return [];
  537. }
  538. }
  539. async getStagePosCompareData(tid, sid, fields) {
  540. try {
  541. await this.ctx.service.tender.checkTender(tid);
  542. await this.ctx.service.stage.checkStage(sid);
  543. await this._getStageValidRole();
  544. const stage = this.ctx.stage, helper = this.ctx.helper;
  545. const validRole = this.stageValidRole;
  546. const allStagePos = await this.ctx.service.stagePos.getAllDataByCondition({where: {sid: sid}});
  547. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  548. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  549. this.ctx.helper.assignRelaData(posData, [
  550. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  551. ]);
  552. const stagePosIndex = {}, timesLen = 100;
  553. for (const role of validRole) {
  554. const stagePos = this.ctx.helper._.filter(allStagePos, function (x) {
  555. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  556. });
  557. this.ctx.helper._.pullAll(allStagePos, stagePos);
  558. for (const sp of stagePos) {
  559. const key = 'sp-' + sp.pid;
  560. const spi = stagePosIndex[key];
  561. if (spi) {
  562. if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp;
  563. } else {
  564. stagePosIndex[key] = sp;
  565. }
  566. }
  567. const filterStagePos = [];
  568. for (const prop in stagePosIndex) {
  569. filterStagePos.push(stagePosIndex[prop]);
  570. }
  571. this.ctx.helper.assignRelaData(posData, [
  572. {data: filterStagePos, fields: ['contract_qty', 'qc_qty'], prefix: 'r' + role.flowOrder + '_', relaId: 'pid'}
  573. ]);
  574. }
  575. this.pos.loadDatas(posData);
  576. this.pos.calculateAll(function (p) {
  577. p.pre_gather_qty = helper.add(p.pre_contract_qty, p.pre_qc_qty);
  578. for (const role of validRole) {
  579. const prefix = 'r' + role.flowOrder + '_';
  580. p[prefix + 'gather_qty'] = helper.add(p[prefix + 'contract_qty'], p[prefix + 'qc_qty']);
  581. }
  582. });
  583. return this.pos.getDatas();
  584. } catch (err) {
  585. return [];
  586. }
  587. }
  588. async getStagePayData(tid, sid, fields) {
  589. try {
  590. await this.ctx.service.tender.checkTender(tid);
  591. await this.ctx.service.stage.checkStage(sid);
  592. const stage = this.ctx.stage;
  593. const dealPay = await this.ctx.service.stagePay.getStagePays(this.ctx.stage);
  594. if (!this.ctx.stage.readOnly) {
  595. // 计算 本期金额
  596. const PayCalculator = require('../lib/pay_calc');
  597. const payCalculator = new PayCalculator(this.ctx, this.ctx.stage, this.ctx.tender.info);
  598. await payCalculator.calculateAll(dealPay);
  599. }
  600. if (this._checkFieldsExist(fields, ['start_stage_order']) && this.ctx.stage.status !== audit.stage.status.checked) {
  601. for (const dp of dealPay) {
  602. if (!dp.start_stage_order || dp.start_stage_order === this.ctx.stage.order) {
  603. dp.start_stage_order = this.ctx.helper.checkZero(dp.tp) ? null : this.ctx.stage.order;
  604. }
  605. }
  606. }
  607. if (this._checkFieldsExistReg(fields, 'r[0-9]+_tp')) {
  608. this._getStageValidRole();
  609. const allStagePays = await this.ctx.service.stagePay.getAllDataByCondition({
  610. where: {sid: stage.id, stimes: stage.curTimes}
  611. });
  612. for (const [i, role] of this.stageValidRole.entries()) {
  613. if (i < this.stageValidRole.length - 1) {
  614. const stagePays = this.ctx.helper._.filter(allStagePays, function (x) {
  615. return x.stimes === stage.curTimes && x.sorder === role.dataOrder;
  616. });
  617. this.ctx.helper._.pullAll(allStagePays, stagePays);
  618. for (const sp of stagePays) {
  619. const dp = dealPay.find(function (x) {return x.pid === sp.pid});
  620. if (dp) {
  621. dp['r' + role.flowOrder + '_tp'] = sp.tp;
  622. }
  623. }
  624. } else {
  625. for (const dp of dealPay) {
  626. dp['r' + role.flowOrder + '_tp'] = dp.tp;
  627. }
  628. }
  629. }
  630. }
  631. return dealPay;
  632. } catch (err) {
  633. return [];
  634. }
  635. }
  636. async getStageChangeBillsData(tid, sid, fields) {
  637. try {
  638. await this.ctx.service.tender.checkTender(tid);
  639. await this.ctx.service.stage.checkStage(sid);
  640. if (this.ctx.stage.readOnly) {
  641. return await this.ctx.service.stageChange.getReportAuditorAllStageData(tid, sid,
  642. this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  643. } else {
  644. return await this.ctx.service.stageChange.getReportLastestAllStageData(tid, sid);
  645. }
  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. d.end_arrive_qty = this.ctx.helper.add(d.pre_arrive_qty, d.arrive_qty);
  751. d.end_arrive_tp = this.ctx.helper.add(d.pre_arrive_tp, d.arrive_tp);
  752. d.end_deduct_qty = this.ctx.helper.add(d.pre_deduct_qty, d.deduct_qty);
  753. d.end_deduct_tp = this.ctx.helper.add(d.pre_deduct_tp, d.deduct_tp);
  754. }
  755. return data;
  756. } catch (err) {
  757. return [];
  758. }
  759. }
  760. async getStageBonus(tid, sid, fields) {
  761. try {
  762. await this.ctx.service.tender.checkTender(tid);
  763. await this.ctx.service.stage.checkStage(sid);
  764. const data = await this.ctx.service.stageBonus.getEndStageData(this.ctx.stage.order);
  765. for (const d of data) {
  766. const names = this.ctx.helper._.map(d.proof_file, function (x) {
  767. return x.filename + x.fileext;
  768. });
  769. d.proof = names.join('\n');
  770. }
  771. return data;
  772. } catch (err) {
  773. return [];
  774. }
  775. }
  776. async getStageOther(tid, sid, fields) {
  777. try {
  778. await this.ctx.service.tender.checkTender(tid);
  779. await this.ctx.service.stage.checkStage(sid);
  780. const data = await this.ctx.service.stageOther.getStageData(this.ctx.stage);
  781. const preData = await this.ctx.service.stageOther.getPreStageData(this.ctx.stage.order);
  782. for (const d of data) {
  783. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  784. if (pd) {
  785. d.pre_tp = pd.tp;
  786. }
  787. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  788. }
  789. return data;
  790. } catch (err) {
  791. return [];
  792. }
  793. }
  794. async getStageSafeProd(tid, sid, fields) {
  795. try {
  796. await this.ctx.service.tender.checkTender(tid);
  797. await this.ctx.service.stage.checkStage(sid);
  798. const data = await this.ctx.service.stageSafeProd.getStageData(this.ctx.stage);
  799. const preData = await this.ctx.service.stageSafeProd.getPreStageData(this.ctx.stage.order);
  800. for (const d of data) {
  801. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  802. if (pd) {
  803. d.pre_qty = pd.qty;
  804. d.pre_tp = pd.tp;
  805. }
  806. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  807. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  808. }
  809. return data;
  810. } catch (err) {
  811. return [];
  812. }
  813. }
  814. async getStageTempLand(tid, sid, fields) {
  815. try {
  816. await this.ctx.service.tender.checkTender(tid);
  817. await this.ctx.service.stage.checkStage(sid);
  818. const data = await this.ctx.service.stageTempLand.getStageData(this.ctx.stage);
  819. const preData = await this.ctx.service.stageTempLand.getPreStageData(this.ctx.stage.order);
  820. for (const d of data) {
  821. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  822. if (pd) {
  823. d.pre_qty = pd.qty;
  824. d.pre_tp = pd.tp;
  825. }
  826. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  827. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  828. }
  829. return data;
  830. } catch (err) {
  831. return [];
  832. }
  833. }
  834. async getSelectMaterialAuditors(tid, material_order, fields) {
  835. await this.ctx.service.material.checkMaterial(tid, material_order);
  836. const auditors = await this.ctx.service.materialAudit.getFinalAuditGroup(this.ctx.material.id, this.ctx.material.curTimes);
  837. const user = await this.ctx.service.projectAccount.getDataById(this.ctx.material.user_id);
  838. const result = [{
  839. aid: user.id,
  840. name: user.name,
  841. company: user.company,
  842. role: user.role,
  843. mobile: user.mobile,
  844. telephone: user.telephone,
  845. sign_path: user.sign_path,
  846. opinion: user.opinion,
  847. end_time: auditors && auditors.length > 0 ? auditors[0].begin_time : null,
  848. sort: 0,
  849. }, ...auditors];
  850. return result;
  851. }
  852. async getMaterial(tender_id, material_order, fields) {
  853. const result = await this.ctx.service.material.getValidMaterials(tender_id);
  854. if (this._checkFieldsExist(fields, ['checked_time'])) {
  855. for (const r of result) {
  856. const auditors = await this.ctx.service.materialAudit.getFinalAuditGroup(r.id, r.curTimes || r.times);
  857. r.checked_time = !r.curTimes ? auditors[auditors.length - 1].end_time : null;
  858. }
  859. }
  860. return result;
  861. }
  862. _completeMaterialGl(materialGl) {
  863. const tTypeStr = [], mTypeStr = [];
  864. for (const t of materialConst.t_type) {
  865. tTypeStr[t.value] = t.text;
  866. }
  867. for (const m of materialConst.m_type) {
  868. mTypeStr[m.value] = m.text;
  869. }
  870. for (const gl of materialGl) {
  871. gl.tp = this.ctx.helper.mul(gl.quantity, gl.m_spread, 2);
  872. gl.t_type_str = tTypeStr[gl.t_type];
  873. gl.m_type_str = mTypeStr[gl.m_type];
  874. gl.end_tp = this.ctx.helper.add(gl.tp, gl.pre_tp);
  875. }
  876. }
  877. async getMaterialGl(tender_id, material_order, fields) {
  878. const materials = await this.ctx.service.material.getAllDataByCondition({
  879. where: {tid: tender_id},
  880. orders: [['order', 'desc']],
  881. });
  882. if (materials.length > 0) {
  883. let result;
  884. if (materials[0].order === material_order) {
  885. result = await this.ctx.service.materialBills.getAllDataByCondition({
  886. where: {tid: tender_id}
  887. });
  888. } else {
  889. const material = this.ctx.helper._.find(materials, {order: material_order});
  890. if (!material) return [];
  891. const sql = 'SELECT m.id, m.tid, m.mid, m.t_type, m.code, m.name, m.unit, m.spec, m.m_type,' +
  892. ' m.basic_price, m.basic_times, m.remark, m.in_time,' +
  893. ' mh.quantity, mh.expr, mh.msg_tp, mh.msg_times, mh.msg_spread, mh.m_up_risk, mh.m_down_risk, mh.m_spread' +
  894. ' FROM ' + this.ctx.service.materialBills.tableName + ' m' +
  895. ' LEFT JOIN ' + this.ctx.service.materialBillsHistory.tableName + ' mh' +
  896. ' ON m.id = mh.mb_id' +
  897. ' WHERE mh.mid = ?';
  898. const sqlParam = [material.id];
  899. result = await this.ctx.app.mysql.query(sql, sqlParam);
  900. }
  901. this._completeMaterialGl(result);
  902. return result;
  903. } else {
  904. return [];
  905. }
  906. }
  907. async getMaterialGlDetail(tender_id, material_order, fields) {
  908. const material = await this.ctx.service.material.getDataByCondition({tid: tender_id, order: material_order});
  909. return material ? await this.ctx.service.materialList.getMaterialData(tender_id, material.id) : [];
  910. }
  911. async getMaterialBills(tender_id, material_order, fields) {
  912. const material = await this.ctx.service.material.getDataByCondition({tid: tender_id, order: material_order});
  913. try {
  914. const billsData = await this.ctx.service.ledger.getData(tender_id);
  915. if (this._checkFieldsExist(fields, billsFields.stage)) {
  916. const curStage = await this.ctx.service.stageBills.getStagesData(tender_id, material.stage_id);
  917. this.ctx.helper.assignRelaData(billsData, [
  918. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp', 'postil'], prefix: '', relaId: 'lid'}
  919. ]);
  920. }
  921. const billsTree = this._getNewBillsTree();
  922. billsTree.loadDatas(billsData);
  923. billsTree.calculateAll();
  924. return billsTree.getDatas([
  925. 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf',
  926. 'code', 'b_code', 'name', 'unit', 'unit_price',
  927. 'deal_qty', 'deal_tp',
  928. 'sgfh_qty', 'sgfh_tp', 'sjcl_qty', 'sjcl_tp', 'qtcl_qty', 'qtcl_tp', 'quantity', 'total_price',
  929. 'dgn_qty1', 'dgn_qty2',
  930. 'drawing_code', 'memo', 'node_type', 'is_tp',
  931. 'contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'gather_qty', 'gather_tp', 'postil',
  932. 'sgfh_expr', 'sjcl_expr', 'qtcl_expr', 'contract_expr',
  933. ]);
  934. } catch(err) {
  935. this.ctx.helper.log(err);
  936. return [];
  937. }
  938. }
  939. async getMaterialPos(tender_id, material_order, fields) {
  940. const material = await this.ctx.service.material.getDataByCondition({tid: tender_id, order: material_order});
  941. try {
  942. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: tender_id }});
  943. if (this._checkFieldsExist(fields, posFields.stage)) {
  944. const curPosStage = await this.ctx.service.stagePos.getStagesData(tender_id, material.stage_id);
  945. this.ctx.helper.assignRelaData(posData, [
  946. {data: curPosStage, fields: ['contract_qty', 'qc_qty', 'contract_expr', 'postil'], prefix: '', relaId: 'pid'}
  947. ]);
  948. }
  949. this.pos.loadDatas(posData);
  950. this.pos.calculateAll();
  951. return this.pos.getDatas();
  952. } catch (err) {
  953. this.ctx.helper.log(err);
  954. return [];
  955. }
  956. }
  957. async getSumStageBillsData(tid, sid, fields) {
  958. try {
  959. await this.ctx.service.tender.checkTender(tid);
  960. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  961. const checkStageField = function (stageOrder) {
  962. for (const f of fields) {
  963. if (f.indexOf('s' + stageOrder + '_') >= 0) {
  964. return true;
  965. }
  966. }
  967. return false;
  968. };
  969. const calcFields = ['deal_tp', 'total_price'], calcPrefix = [];
  970. const stages = this.ctx.service.stage.getValidStages(this.ctx.tender.id);
  971. for (const stage of stages) {
  972. if (!checkStageField(stage.order)) return;
  973. await this.ctx.service.stage.doCheckStage(stage);
  974. calcFields.push('s' + stage.order + '_contract_tp');
  975. calcFields.push('s' + stage.order + '_qc_tp');
  976. calcFields.push('s' + stage.order + '_gather_tp');
  977. calcFields.push('s' + stage.order + '_');
  978. const curStage = stage.readOnly
  979. ? await this.ctx.service.stageBills.getAuditorStageData2(this.ctx.tender.id, stage.id, stage.curTimes, stage.curOrder)
  980. : await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, stage.id);
  981. this.ctx.helper.assignRelaData(billsData, [
  982. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp'], prefix: 's' + stage.order + '_', relaId: 'lid'}
  983. ]);
  984. }
  985. const billsTree = new Ledger.billsTree(this.ctx, {
  986. id: 'ledger_id',
  987. pid: 'ledger_pid',
  988. order: 'order',
  989. level: 'level',
  990. rootId: -1,
  991. keys: ['id', 'tender_id', 'ledger_id'],
  992. stageId: 'id',
  993. calcFields: calcFields,
  994. calc: function (node) {
  995. for (const prefix of calcPrefix) {
  996. if (node.children && node.children.length === 0) {
  997. node[prefix + 'gather_qty'] = self.ctx.helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  998. }
  999. node[prefix + 'gather_tp'] = self.ctx.helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  1000. }
  1001. }
  1002. });
  1003. billsTree.loadDatas(billsData);
  1004. billsTree.calculateAll();
  1005. return billsTree.getDefaultDatas();
  1006. } catch (err) {
  1007. return [];
  1008. }
  1009. }
  1010. async getStageAuditors(tid, sid) {
  1011. await this.ctx.service.tender.checkTender(tid);
  1012. await this.ctx.service.stage.checkStage(sid);
  1013. const auditors = await this.ctx.service.stageAudit.getFinalAuditGroup(this.ctx.stage.id, this.ctx.stage.curTimes);
  1014. const user = await this.ctx.service.projectAccount.getDataById(this.ctx.stage.user_id);
  1015. const result = [{
  1016. aid: user.id,
  1017. name: user.name,
  1018. company: user.company,
  1019. role: user.role,
  1020. mobile: user.mobile,
  1021. telephone: user.telephone,
  1022. sign_path: user.sign_path,
  1023. opinion: user.opinion,
  1024. end_time: auditors && auditors.length > 0 ? auditors[0].begin_time : null,
  1025. sort: 0,
  1026. }, ...auditors];
  1027. return result;
  1028. }
  1029. async getSignSelect(tid, sid, customSelect) {
  1030. await this.ctx.service.tender.checkTender(tid);
  1031. await this.ctx.service.stage.checkStage(sid);
  1032. const signSelect = customSelect.sign_select, result = {};
  1033. for (const [i, ss] of signSelect.entries()) {
  1034. const user = await this.ctx.service.projectAccount.getDataById(ss.id);
  1035. const sign = {
  1036. id: ss.id, name: user.name, company: user.company, role: user.role,
  1037. mobile: user.mobile, telephone: user.telephone,
  1038. };
  1039. if (ss.id !== this.ctx.stage.user_id) {
  1040. const audit = this.ctx.stage.auditors.find(x => {return x.aid === ss.id});
  1041. user.end_time = audit ? audit.end_time : ss.audit_time;
  1042. } else {
  1043. user.end_time = this.ctx.stage.auditors[0].end_time;
  1044. }
  1045. if (user.end_time) sign.sign_path = user.sign_path;
  1046. result['sign' + (i+1)] = sign;
  1047. }
  1048. return result;
  1049. }
  1050. async getChangeInfo(tid, sid) {
  1051. await this.ctx.service.tender.checkTender(tid);
  1052. await this.ctx.service.stage.checkStage(sid);
  1053. this.changeInfo = await this.ctx.service.change.getChangeAndUsedInfo(tid);
  1054. const usedChangesId = await this.ctx.service.stageChange.getStageUsedChangeId(sid);
  1055. for (const c of this.changeInfo) {
  1056. c.cur_used = usedChangesId.indexOf(c.cid) >= 0;
  1057. c.used_ratio = c.used_pt;
  1058. }
  1059. return this.changeInfo;
  1060. }
  1061. async getChangeInfoBills(tid, sid) {
  1062. if (!this.changeInfo) await this.getChangeInfo(tid, sid);
  1063. this.changeInfoBills = [];
  1064. for (const c of this.changeInfo) {
  1065. const cb = await this.ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: c.cid } });
  1066. const cbu = await this.ctx.service.stageChange.getUsedData(tid, c.cid);
  1067. const curUsedBills = await this.ctx.service.stageChange.getStageUsedData(sid, c.cid);
  1068. for (const b of cb) {
  1069. b.qty = this.ctx.helper._.toNumber(b.samount);
  1070. b.tp = this.ctx.helper.round(this.ctx.helper.mul(b.qty, b.unit_price), this.ctx.tender.info.decimal.tp);
  1071. const u = cbu.find(x => { return x.id === b.id; });
  1072. b.used_qty = u ? u.used_qty : 0;
  1073. b.valid_qty = this.ctx.helper.sub(b.qty, b.used_qty);
  1074. const cur = this.ctx.helper._.filter(curUsedBills, { cbid: b.id });
  1075. b.cur_qty = 0;
  1076. for (const cc of cur) {
  1077. b.cur_qty = this.ctx.helper.add(b.cur_qty, cc.qty);
  1078. }
  1079. b.cur_used = !!b.cur_qty;
  1080. this.changeInfoBills.push(b);
  1081. }
  1082. }
  1083. return this.changeInfoBills;
  1084. }
  1085. }
  1086. return ReportMemory;
  1087. };