report_memory.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399
  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 path = require('path');
  15. // const fs = require('fs');
  16. const stageImTz = 'mem_stage_im_tz';
  17. const stageImTzBills = 'mem_stage_im_tz_bills';
  18. const stageImZl = 'mem_stage_im_zl';
  19. const stageImVersion = '1.3';
  20. const PermissionCheck = require('../const/account_permission').PermissionCheck;
  21. const Ledger = require('../lib/ledger');
  22. const billsFields = (function () {
  23. const cur = ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp', 'qc_minus_qty', 'qc_minus_tp', 'gather_qty', 'gather_tp', 'postil'];
  24. const pre = ['pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_qc_minus_qty', 'pre_qc_minus_tp', 'pre_gather_qty', 'pre_gather_tp'];
  25. const end = ['end_contract_qty', 'end_contract_tp', 'end_qc_qty', 'end_qc_tp', 'end_qc_minus_qty', 'end_qc_minus_tp', 'end_gather_qty', 'end_gather_tp'];
  26. const final = ['final_tp', 'final_ratio'];
  27. const final1 = [ 'final_1_qty', 'final_1_tp', 'final_1_ratio'];
  28. const stageDgn = ['deal_dgn_qty1', 'deal_dgn_qty2', 'c_dgn_qty1', 'c_dgn_qty2'];
  29. const stage = cur.concat(pre, end, final);
  30. const stageEnd = pre.concat(end, final);
  31. const bgl = ['qc_bgl_code'];
  32. const leafXmj = ['leaf_xmj_id'];
  33. return {cur, pre, end, final, final1, stageDgn, stage, stageEnd, bgl, leafXmj};
  34. })();
  35. const posFields = (function () {
  36. const cur = ['contract_qty', 'qc_qty', 'qc_minus_qty', 'gather_qty', 'postil'];
  37. const pre = ['pre_contract_qty', 'pre_qc_qty', 'pre_qc_minus_qty', 'pre_gather_qty'];
  38. const end = ['end_contract_qty', 'end_qc_qty', 'end_qc_minus_qty', 'end_gather_qty'];
  39. const final = ['final_ratio'];
  40. const final1 = ['final_1_qty', 'final_1_ratio'];
  41. const stage = cur.concat(pre, end, final);
  42. const stageEnd = pre.concat(end, final);
  43. const bgl = ['qc_bgl_code'];
  44. return {cur, pre, end, final, final1, stage, stageEnd, bgl};
  45. })();
  46. module.exports = app => {
  47. class ReportMemory extends app.BaseService {
  48. /**
  49. * 构造函数
  50. *
  51. * @param {Object} ctx - egg全局context
  52. * @return {void}
  53. */
  54. constructor(ctx) {
  55. super(ctx);
  56. const self = this;
  57. this.tableName = 'report_memory';
  58. // 基础数据类
  59. // mainData
  60. this.pos = new Ledger.pos({
  61. id: 'id', ledgerId: 'lid',
  62. updateFields: ['contract_qty', 'qc_qty', 'postil'],
  63. calc: function (p) {
  64. p.pre_gather_qty = ctx.helper.add(p.pre_contract_qty, p.pre_qc_qty);
  65. p.gather_qty = ctx.helper.add(p.contract_qty, p.qc_qty);
  66. p.end_contract_qty = self.ctx.helper.add(p.pre_contract_qty, p.contract_qty);
  67. p.end_qc_qty = self.ctx.helper.add(p.pre_qc_qty, p.qc_qty);
  68. p.end_gather_qty = self.ctx.helper.add(p.pre_gather_qty, p.gather_qty);
  69. p.final_qty = ctx.helper.add(p.end_qc_qty, p.quantity);
  70. p.final_ratio = ctx.helper.mul(ctx.helper.div(p.end_gather_qty, p.final_qty, 4), 100);
  71. p.end_qc_minus_qty = ctx.helper.add(p.pre_qc_minus_qty, p.qc_minus_qty);
  72. p.final_1_qty = ctx.helper.add(p.end_qc_minus_qty, p.quantity);
  73. p.end_final_1_qty = ctx.helper.add(p.end_qc_qty, p.final_1_qty);
  74. p.final_1_ratio = ctx.helper.mul(ctx.helper.div(p.end_gather_qty, p.end_final_1_qty, 4), 100);
  75. }
  76. });
  77. // 需要缓存的数据
  78. this.stageImData = null;
  79. this.changeData = null;
  80. this.changeApplyData = null;
  81. this.changeProjectData = null;
  82. this.stageValidRole = [];
  83. }
  84. _getNewBillsTree(calcFields) {
  85. return new Ledger.billsTree(this.ctx, {
  86. id: 'ledger_id',
  87. pid: 'ledger_pid',
  88. order: 'order',
  89. level: 'level',
  90. rootId: -1,
  91. keys: ['id', 'tender_id', 'ledger_id'],
  92. stageId: 'id',
  93. calcFields: calcFields || ['deal_tp', 'total_price',
  94. 'contract_tp', 'qc_tp', 'contract_pc_tp', 'qc_pc_tp', 'pc_tp', 'gather_tp',
  95. 'pre_contract_tp', 'pre_qc_tp', 'pre_gather_tp', 'final_1_tp',
  96. 'end_contract_pc_tp', 'end_qc_pc_tp', 'end_pc_tp',
  97. ],
  98. calc: function (node, helper, decimal) {
  99. if (node.children && node.children.length === 0) {
  100. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  101. node.gather_qty = helper.add(node.contract_qty, node.qc_qty);
  102. node.end_contract_qty = helper.add(node.pre_contract_qty, node.contract_qty);
  103. node.end_qc_qty = helper.add(node.pre_qc_qty, node.qc_qty);
  104. node.end_gather_qty = helper.add(node.pre_gather_qty, node.gather_qty);
  105. node.end_qc_minus_qty = helper.add(node.pre_qc_minus_qty, node.qc_minus_qty);
  106. node.final_1_qty = helper.add(node.quantity, node.end_qc_minus_qty);
  107. node.end_final_1_qty = helper.add(node.final_1_qty, node.end_qc_qty);
  108. }
  109. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  110. node.gather_tp = helper.sum([node.contract_tp, node.qc_tp, node.pc_tp]);
  111. node.end_contract_tp = helper.sum([node.pre_contract_tp, node.contract_tp, node.contract_pc_tp]);
  112. node.end_qc_tp = helper.sum([node.pre_qc_tp, node.qc_tp, node.qc_pc_tp]);
  113. node.end_gather_tp = helper.add(node.pre_gather_tp, node.gather_tp);
  114. node.final_tp = helper.add(node.total_price, node.end_qc_tp);
  115. node.final_ratio = helper.mul(helper.div(node.end_gather_tp, node.final_tp, 4), 100);
  116. node.final_1_tp = helper.mul(node.unit_price, node.final_1_qty, decimal.tp);
  117. node.end_final_1_tp = helper.add(node.final_1_tp, node.end_qc_tp);
  118. node.final_1_ratio = helper.mul(helper.div(node.end_gather_tp, node.end_final_1_tp, 4), 100);
  119. }
  120. });
  121. }
  122. _checkFieldsExist(source, check) {
  123. for (const s of source) {
  124. if (check.indexOf(s) >= 0) {
  125. return true;
  126. }
  127. }
  128. return false;
  129. }
  130. _checkFieldsExistReg(source, regStr) {
  131. const reg = new RegExp(regStr, 'igm');
  132. for (const s of source) {
  133. if (reg.test(s)) {
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. // build-time: 162-384ms, redis-cache: 0-41ms, mysql + IO: 116-146ms
  140. // 一定程度上算是大Value缓存,数据多了以后:
  141. // 1. 达到redis内存阈值时,数据会swap到磁盘,此时将消耗IO时间
  142. // 2. redis单独服务器
  143. // 3. redis集群
  144. async _getReportMemoryCache(name, tid, sid, time, version = '') {
  145. // redis
  146. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  147. const data = await this.cache.get(cacheKey);
  148. if (data) {
  149. return eval(data);
  150. } else {
  151. return null;
  152. }
  153. // mysql + IO
  154. // const rm = await this.getDataByCondition({
  155. // tid: tid, sid: sid, name: name, time: time
  156. // });
  157. // if (rm && rm.file) {
  158. // const file = path.join(this.ctx.app.config.filePath, 'report', 'cache', rm.file);
  159. // if (fs.existsSync(file)) {
  160. // const data = await fs.readFileSync(file, 'utf8');
  161. // return eval(data);
  162. // } else {
  163. // return null;
  164. // }
  165. // }
  166. }
  167. async _setReportMemoryCache(name, tid, sid, time, data, version = '') {
  168. // redis
  169. const cacheKey = name + '-t' + tid + (sid ? '-s' + sid : '') + (time ? '-' + time : '') + version;
  170. this.cache.set(cacheKey, JSON.stringify(data), 'EX', this.ctx.app.config.cacheTime);
  171. // mysql + IO
  172. // const file = path.join('report', 'cache', 'rm' + (new Date()).getTime() + '.json');
  173. // await this.ctx.helper.saveBufferFile(JSON.stringify(data), path.join(this.ctx.app.config.filePath, file));
  174. // const rm = await this.getDataByCondition({
  175. // tid: tid, sid: sid, name: name, time: time
  176. // });
  177. // if (rm) {
  178. // await this.db.update(this.tableName, {id: rm.id, file: file});
  179. // } else {
  180. // await this.db.insert(this.tableName, {tid: tid, sid: sid, name: name, time: time, file: file});
  181. // }
  182. }
  183. async _generateStageIm(tid, sid, isTz = true) {
  184. if (isTz && [imType.tz.value, imType.bb.value].indexOf(this.ctx.stage.im_type) === -1) {
  185. throw '您查看的报表跟设置不符,请查看“总量控制”的报表';
  186. } else if (!isTz && [imType.zl.value, imType.bw.value].indexOf(this.ctx.stage.im_type) === -1) {
  187. throw '您查看的报表跟设置不符,请查看“0号台账”的报表';
  188. }
  189. const stageIm = new StageIm(this.ctx);
  190. await stageIm.buildImData();
  191. this.stageImData.main = stageIm.ImData;
  192. if (isTz) {
  193. this.stageImData.bills = stageIm.ImBillsData;
  194. await this._setReportMemoryCache(stageImTz, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  195. await this._setReportMemoryCache(stageImTzBills, tid, sid, this.ctx.stage.cacheTime, this.stageImData.bills, stageImVersion);
  196. } else {
  197. await this._setReportMemoryCache(stageImZl, tid, sid, this.ctx.stage.cacheTime, this.stageImData.main, stageImVersion);
  198. }
  199. }
  200. async getStageImTzData(tid, sid, fields, readCache = true) {
  201. try {
  202. await this.ctx.service.tender.checkTender(tid);
  203. await this.ctx.service.stage.checkStage(sid);
  204. if (readCache) {
  205. const cache = await this._getReportMemoryCache('mem_stage_im_tz', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  206. if (cache) return cache;
  207. }
  208. if (!this.stageImData) {
  209. this.stageImData = {};
  210. try {
  211. await this._generateStageIm(tid, sid);
  212. } catch (err) {
  213. if (err.stack) {
  214. this.ctx.logger.error(err);
  215. }
  216. this.stageImData.main = err.stack ? '数据错误' : err;
  217. this.stageImData.bills = this.stageImData.main;
  218. }
  219. }
  220. return this.stageImData.main;
  221. } catch (err) {
  222. return [];
  223. }
  224. }
  225. async getStageImTzBillsData(tid, sid, fields, readCache = true) {
  226. try {
  227. await this.ctx.service.tender.checkTender(tid);
  228. await this.ctx.service.stage.checkStage(sid);
  229. if (readCache) {
  230. const cache = await this._getReportMemoryCache('mem_stage_im_tz_bills', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  231. if (cache) return cache;
  232. }
  233. if (!this.stageImData) {
  234. this.stageImData = {};
  235. try {
  236. await this._generateStageIm(tid, sid);
  237. } catch (err) {
  238. if (err.stack) {
  239. this.ctx.logger.error(err);
  240. }
  241. this.stageImData.main = err.stack ? '数据错误' : err;
  242. this.stageImData.bills = this.stageImData.main;
  243. }
  244. }
  245. return this.stageImData.bills;
  246. } catch (err) {
  247. return [];
  248. }
  249. }
  250. async getStageImZlData(tid, sid, fields, readCache = true) {
  251. try {
  252. await this.ctx.service.tender.checkTender(tid);
  253. await this.ctx.service.stage.checkStage(sid);
  254. if (readCache) {
  255. const cache = await this._getReportMemoryCache('mem_stage_im_zl', tid, sid, this.ctx.stage.cacheTime, stageImVersion);
  256. if (cache) return cache;
  257. }
  258. this.stageImData = {};
  259. try {
  260. await this._generateStageIm(tid, sid, false);
  261. } catch (err) {
  262. if (err.stack) {
  263. this.ctx.logger.error(err);
  264. }
  265. this.stageImData.main = err.statck ? '数据错误' : err;
  266. }
  267. return this.stageImData.main;
  268. } catch (err) {
  269. return [];
  270. }
  271. }
  272. async getMonthProgress(tid, fields) {
  273. const helper = this.ctx.helper;
  274. await this.ctx.service.tender.checkTender(tid);
  275. const tender = this.ctx.tender;
  276. const stages = await this.ctx.service.stage.getValidStages(tender.id);
  277. const lastStage = stages.length > 0 ? stages[0] : null;
  278. if (lastStage) {
  279. await this.ctx.service.stage.checkStageGatherData(lastStage, this.ctx.session.sessionUser.is_admin);
  280. tender.gather_tp = helper.add(lastStage.contract_tp, lastStage.qc_tp);
  281. tender.end_contract_tp = helper.add(lastStage.contract_tp, lastStage.pre_contract_tp);
  282. tender.end_qc_tp = helper.add(lastStage.qc_tp, lastStage.pre_qc_tp);
  283. tender.end_gather_tp = helper.add(tender.end_contract_tp, tender.end_qc_tp);
  284. tender.pre_gather_tp = helper.add(lastStage.pre_contract_tp, lastStage.pre_qc_tp);
  285. tender.yf_tp = lastStage.yf_tp;
  286. tender.qc_ratio = helper.mul(helper.div(tender.end_qc_tp, tender.info.deal_param.contractPrice, 2), 100);
  287. tender.sum = helper.add(tender.total_price, tender.end_qc_tp);
  288. tender.pre_ratio = helper.mul(helper.div(tender.pre_gather_tp, tender.sum, 2), 100);
  289. tender.cur_ratio = helper.mul(helper.div(tender.gather_tp, tender.sum, 2), 100);
  290. tender.other_tp = helper.sub(helper.sub(tender.sum, tender.pre_gather_tp), tender.gather_tp);
  291. tender.other_ratio = Math.max(0, 100 - tender.pre_ratio - tender.cur_ratio);
  292. }
  293. const monthProgress = [];
  294. for (const s of stages) {
  295. if (s.s_time) {
  296. let progress = monthProgress.find(function (x) {
  297. return x.month === s.s_time;
  298. });
  299. if (!progress) {
  300. progress = {month: s.s_time};
  301. monthProgress.push(progress);
  302. }
  303. progress.tp = helper.add(helper.add(progress.tp, s.contract_tp), s.qc_tp);
  304. }
  305. }
  306. monthProgress.sort(function (x, y) {
  307. return Date.parse(x.month) - Date.parse(y.month);
  308. });
  309. let sum = 0;
  310. for (const p of monthProgress) {
  311. p.ratio = helper.mul(helper.div(p.tp, tender.sum, 4), 100);
  312. sum = helper.add(sum, p.tp);
  313. p.end_tp = sum;
  314. p.end_ratio = helper.mul(helper.div(p.end_tp, tender.sum, 4), 100);
  315. }
  316. return monthProgress;
  317. }
  318. async _calcBillsBgl(billsTree) {
  319. if (!this.ctx.stage) return;
  320. const helper = this.ctx.helper;
  321. const tender = this.ctx.tender;
  322. const stage = this.ctx.stage;
  323. const bglData = this.ctx.stage.readOnly
  324. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  325. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  326. for (const node of billsTree.nodes) {
  327. node.qc_bgl_code = '';
  328. if (node.children && node.children.length > 0) continue;
  329. const nodeBgl = helper._.filter(bglData, {lid: node.id});
  330. if (nodeBgl.length === 0) continue;
  331. helper._.pullAll(bglData, nodeBgl);
  332. const validBgl = helper._.filter(nodeBgl, function (x) {
  333. return !helper.checkZero(x.qty);
  334. });
  335. node.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  336. }
  337. }
  338. _calcLeafXmjRela(billsTree) {
  339. for (const node of billsTree.nodes) {
  340. if (node.b_code) {
  341. const leafXmj = billsTree.getLeafXmjParent(node);
  342. node.leaf_xmj_id = leafXmj ? leafXmj.id : -1;
  343. }
  344. }
  345. }
  346. async getStageBillsData(tid, sid, fields) {
  347. try {
  348. await this.ctx.service.tender.checkTender(tid);
  349. if (sid) {
  350. await this.ctx.service.stage.checkStage(sid);
  351. }
  352. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  353. if (this._checkFieldsExist(fields, billsFields.stageDgn)) {
  354. const dgnData = await this.ctx.service.stageBillsDgn.getDgnData(this.ctx.tender.id);
  355. for (const d of dgnData) {
  356. const l = this.ctx.helper._.find(billsData, {id: d.id});
  357. this.ctx.helper._.assignIn(l, d);
  358. }
  359. }
  360. let preStage = [], curStage = [];
  361. if (this._checkFieldsExist(fields, billsFields.stage)) {
  362. if (this.ctx.stage.readOnly) {
  363. curStage = await this.ctx.service.stageBills.getAuditorStageData2(this.ctx.tender.id,
  364. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  365. } else {
  366. curStage = await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  367. }
  368. }
  369. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  370. preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  371. }
  372. const bpcStage = await this.ctx.service.stageBillsPc.getAllDataByCondition({ where: { sid: this.ctx.stage.id } });
  373. const endBpcStage = await this.ctx.service.stageBillsPc.getEndStageData(this.ctx.stage);
  374. this.ctx.helper.assignRelaData(billsData, [
  375. { data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp', 'qc_minus_qty', 'postil'], prefix: '', relaId: 'lid' },
  376. { data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'pre_', relaId: 'lid' },
  377. { data: bpcStage, fields: ['contract_pc_tp', 'qc_pc_tp', 'pc_tp', 'org_price'], prefix: '', relaId: 'lid' },
  378. { data: endBpcStage, fields: ['end_contract_pc_tp', 'end_qc_pc_tp', 'end_pc_tp', 'org_price_his'], prefix: '', relaId: 'lid' },
  379. ]);
  380. billsData.forEach(x => {
  381. if (x.org_price_his && x.org_price_his.length > 0) {
  382. for (const prop of x.org_price_his) {
  383. x[`org_price_${prop}`] = x.org_price_his[prop];
  384. }
  385. } else {
  386. x.org_price_0 = x.unit_price;
  387. }
  388. });
  389. const billsTree = this._getNewBillsTree();
  390. billsTree.loadDatas(billsData);
  391. billsTree.calculateAll();
  392. if (this._checkFieldsExist(fields, billsFields.bgl)) {
  393. await this._calcBillsBgl(billsTree);
  394. }
  395. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  396. this._calcLeafXmjRela(billsTree);
  397. }
  398. return billsTree.getDefaultDatas();
  399. } catch(err) {
  400. this.ctx.log(err);
  401. return [];
  402. }
  403. }
  404. async _calcPosBgl() {
  405. if (!this.ctx.stage) return;
  406. const helper = this.ctx.helper;
  407. const tender = this.ctx.tender;
  408. const stage = this.ctx.stage;
  409. const bglData = this.ctx.stage.readOnly
  410. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  411. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  412. for (const p of this.pos.datas) {
  413. p.qc_bgl_code = '';
  414. const pBgl = helper._.filter(bglData, {lid: p.lid, pid: p.id});
  415. if (pBgl.length === 0) continue;
  416. helper._.pullAll(bglData, pBgl);
  417. const validBgl = helper._.filter(pBgl, function (x) {
  418. return !helper.checkZero(x.qty);
  419. });
  420. p.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  421. }
  422. }
  423. async getStagePosData(tid, sid, fields) {
  424. try {
  425. await this.ctx.service.tender.checkTender(tid);
  426. if (sid) {
  427. await this.ctx.service.stage.checkStage(sid);
  428. }
  429. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  430. let curPosStage = [], prePosStage = [];
  431. if (this._checkFieldsExist(fields, posFields.stage)) {
  432. if (this.ctx.stage.readOnly) {
  433. curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  434. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  435. } else {
  436. curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  437. }
  438. }
  439. if (this._checkFieldsExist(fields, posFields.stageEnd)) {
  440. prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  441. }
  442. this.ctx.helper.assignRelaData(posData, [
  443. {data: curPosStage, fields: ['contract_qty', 'qc_qty', 'qc_minus_qty', 'contract_expr', 'postil'], prefix: '', relaId: 'pid'},
  444. {data: prePosStage, fields: ['contract_qty', 'qc_qty', 'qc_minus_qty'], prefix: 'pre_', relaId: 'pid'}
  445. ]);
  446. this.pos.loadDatas(posData);
  447. this.pos.calculateAll();
  448. if (this._checkFieldsExist(fields, posFields.bgl)) {
  449. await this._calcPosBgl();
  450. }
  451. return this.pos.getDatas();
  452. } catch (err) {
  453. return [];
  454. }
  455. }
  456. _getStageValidRole () {
  457. if (!this.ctx.stage) throw '期数据错误,请重试';
  458. if (this.stageValidRole && this.stageValidRole.length > 0) return;
  459. const result = [{dataOrder: 0, flowOrder: 0, uid: this.ctx.stage.user_id}];
  460. for (const auditor of this.ctx.stage.auditors) {
  461. if (auditor.status === audit.stage.status.checked ||
  462. (auditor.status === audit.stage.status.checking && !this.ctx.stage.readOnly)) {
  463. const role = result.find(function (r) {
  464. return r.uid === auditor.aid;
  465. });
  466. if (role) {
  467. role.dataOrder = auditor.order;
  468. } else {
  469. result.push({
  470. dataOrder: auditor.order,
  471. flowOrder: result.length,
  472. uid: auditor.aid
  473. })
  474. }
  475. }
  476. }
  477. this.stageValidRole = result;
  478. };
  479. async getStageBillsCompareData(tid, sid, fields) {
  480. try {
  481. await this.ctx.service.tender.checkTender(tid);
  482. await this.ctx.service.stage.checkStage(sid);
  483. await this._getStageValidRole();
  484. const stage = this.ctx.stage, helper = this.ctx.helper;
  485. const validRole = this.stageValidRole;
  486. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  487. const allStageBills = await this.ctx.service.stageBills.getAllDataByCondition({where: {sid: sid}});
  488. const stageBillsIndex = {}, timesLen = 100;
  489. for (const role of validRole) {
  490. const stageBills = this.ctx.helper._.filter(allStageBills, function (x) {
  491. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  492. });
  493. this.ctx.helper._.pullAll(allStageBills, stageBills);
  494. for (const sb of stageBills) {
  495. const key = 'sb-' + sb.lid;
  496. const sbi = stageBillsIndex[key];
  497. if (sbi) {
  498. if ((sbi.times * timesLen + sbi.order) < (sb.times * timesLen + sb.order)) stageBillsIndex[key] = sb;
  499. } else {
  500. stageBillsIndex[key] = sb;
  501. }
  502. }
  503. const filterStageBills = [];
  504. for (const prop in stageBillsIndex) {
  505. filterStageBills.push(stageBillsIndex[prop]);
  506. }
  507. this.ctx.helper.assignRelaData(billsData, [
  508. {data: filterStageBills, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'r' + role.flowOrder + '_', relaId: 'lid'}
  509. ]);
  510. }
  511. const bpcStage = await this.ctx.service.stageBillsPc.getAllDataByCondition({ where: { sid: this.ctx.stage.id } });
  512. const endBpcStage = await this.ctx.service.stageBillsPc.getEndStageData(this.ctx.stage);
  513. const preStage = this._checkFieldsExist(fields, billsFields.stageEnd) && this.ctx.stage.order > 1
  514. ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1)
  515. : [];
  516. this.ctx.helper.assignRelaData(billsData, [
  517. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp', 'qc_minus_qty'], prefix: 'pre_', relaId: 'lid'},
  518. { data: bpcStage, fields: ['contract_pc_tp', 'qc_pc_tp', 'pc_tp', 'org_price'], prefix: '', relaId: 'lid' },
  519. { data: endBpcStage, fields: ['end_contract_pc_tp', 'end_qc_pc_tp', 'end_pc_tp', 'org_price_his'], prefix: '', relaId: 'lid' },
  520. ]);
  521. billsData.forEach(x => {
  522. if (x.org_price_his && x.org_price_his.length > 0) {
  523. for (const prop of x.org_price_his) {
  524. x[`org_price_${prop}`] = x.org_price_his[prop];
  525. }
  526. } else {
  527. x.org_price_0 = x.unit_price;
  528. }
  529. });
  530. const billsTree = this._getNewBillsTree();
  531. billsTree.loadDatas(billsData);
  532. for (const role of validRole) {
  533. const prefix = 'r' + role.flowOrder + '_';
  534. billsTree.setting.calcFields.push(prefix + 'contract_tp', prefix + 'qc_tp', prefix + 'gather_tp');
  535. }
  536. billsTree.calculateAll(function(node) {
  537. let prefix = '';
  538. if (node.children && node.children.length === 0) {
  539. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  540. for (const role of validRole) {
  541. prefix = 'r' + role.flowOrder + '_';
  542. node[prefix + 'gather_qty'] = helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  543. }
  544. }
  545. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  546. for (const role of validRole) {
  547. prefix = 'r' + role.flowOrder + '_';
  548. node[prefix + 'gather_tp'] = helper.sum([node[prefix + 'contract_tp'], node[prefix + 'qc_tp'], node.pc_tp]);
  549. }
  550. });
  551. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  552. this._calcLeafXmjRela(billsTree);
  553. }
  554. return billsTree.getDefaultDatas();
  555. } catch (err) {
  556. return [];
  557. }
  558. }
  559. async getStagePosCompareData(tid, sid, fields) {
  560. try {
  561. await this.ctx.service.tender.checkTender(tid);
  562. await this.ctx.service.stage.checkStage(sid);
  563. await this._getStageValidRole();
  564. const stage = this.ctx.stage, helper = this.ctx.helper;
  565. const validRole = this.stageValidRole;
  566. const allStagePos = await this.ctx.service.stagePos.getAllDataByCondition({where: {sid: sid}});
  567. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  568. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  569. this.ctx.helper.assignRelaData(posData, [
  570. {data: prePosStage, fields: ['contract_qty', 'qc_qty', 'qc_minus_qty'], prefix: 'pre_', relaId: 'pid'}
  571. ]);
  572. const stagePosIndex = {}, timesLen = 100;
  573. for (const role of validRole) {
  574. const stagePos = this.ctx.helper._.filter(allStagePos, function (x) {
  575. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  576. });
  577. this.ctx.helper._.pullAll(allStagePos, stagePos);
  578. for (const sp of stagePos) {
  579. const key = 'sp-' + sp.pid;
  580. const spi = stagePosIndex[key];
  581. if (spi) {
  582. if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp;
  583. } else {
  584. stagePosIndex[key] = sp;
  585. }
  586. }
  587. const filterStagePos = [];
  588. for (const prop in stagePosIndex) {
  589. filterStagePos.push(stagePosIndex[prop]);
  590. }
  591. this.ctx.helper.assignRelaData(posData, [
  592. {data: filterStagePos, fields: ['contract_qty', 'qc_qty', 'qc_minus_qty'], prefix: 'r' + role.flowOrder + '_', relaId: 'pid'}
  593. ]);
  594. }
  595. this.pos.loadDatas(posData);
  596. this.pos.calculateAll(function (p) {
  597. p.pre_gather_qty = helper.add(p.pre_contract_qty, p.pre_qc_qty);
  598. for (const role of validRole) {
  599. const prefix = 'r' + role.flowOrder + '_';
  600. p[prefix + 'gather_qty'] = helper.add(p[prefix + 'contract_qty'], p[prefix + 'qc_qty']);
  601. }
  602. });
  603. return this.pos.getDatas();
  604. } catch (err) {
  605. return [];
  606. }
  607. }
  608. async getStagePayData(tid, sid, fields) {
  609. try {
  610. await this.ctx.service.tender.checkTender(tid);
  611. await this.ctx.service.stage.checkStage(sid);
  612. const stage = this.ctx.stage;
  613. const dealPay = await this.ctx.service.stagePay.getStagePays(this.ctx.stage);
  614. if (!this.ctx.stage.readOnly) {
  615. // 计算 本期金额
  616. const PayCalculator = require('../lib/pay_calc');
  617. const payCalculator = new PayCalculator(this.ctx, this.ctx.stage, this.ctx.tender.info);
  618. await payCalculator.calculateAll(dealPay);
  619. }
  620. if (this._checkFieldsExist(fields, ['start_stage_order']) && this.ctx.stage.status !== audit.stage.status.checked) {
  621. for (const dp of dealPay) {
  622. if (!dp.start_stage_order || dp.start_stage_order === this.ctx.stage.order) {
  623. dp.start_stage_order = this.ctx.helper.checkZero(dp.tp) ? null : this.ctx.stage.order;
  624. }
  625. }
  626. }
  627. if (this._checkFieldsExistReg(fields, 'r[0-9]+_tp')) {
  628. this._getStageValidRole();
  629. const allStagePays = await this.ctx.service.stagePay.getAllDataByCondition({
  630. where: {sid: stage.id, stimes: stage.curTimes}
  631. });
  632. for (const [i, role] of this.stageValidRole.entries()) {
  633. if (i < this.stageValidRole.length - 1) {
  634. const stagePays = this.ctx.helper._.filter(allStagePays, function (x) {
  635. return x.stimes === stage.curTimes && x.sorder === role.dataOrder;
  636. });
  637. this.ctx.helper._.pullAll(allStagePays, stagePays);
  638. for (const sp of stagePays) {
  639. const dp = dealPay.find(function (x) {return x.pid === sp.pid});
  640. if (dp) {
  641. dp['r' + role.flowOrder + '_tp'] = sp.tp;
  642. }
  643. }
  644. } else {
  645. for (const dp of dealPay) {
  646. dp['r' + role.flowOrder + '_tp'] = dp.tp;
  647. }
  648. }
  649. }
  650. }
  651. return dealPay;
  652. } catch (err) {
  653. return [];
  654. }
  655. }
  656. async getStageChangeBillsData(tid, sid, fields) {
  657. try {
  658. await this.ctx.service.tender.checkTender(tid);
  659. await this.ctx.service.stage.checkStage(sid);
  660. if (this.ctx.stage.readOnly) {
  661. return await this.ctx.service.stageChange.getReportAuditorAllStageData(tid, sid,
  662. this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  663. } else {
  664. return await this.ctx.service.stageChange.getReportLastestAllStageData(tid, sid);
  665. }
  666. } catch (err) {
  667. return [];
  668. }
  669. }
  670. _getChangeConstName(define, value) {
  671. for (const prop in define) {
  672. if (define[prop].value === value) {
  673. return define[prop].name;
  674. }
  675. }
  676. return '';
  677. }
  678. async _generateChange(tid) {
  679. if (this.changeData !== null) return;
  680. const self = this;
  681. try {
  682. const decimal = this.ctx.tender.info.decimal, ctx = this.ctx;
  683. const where = { tid, valid: 1 };
  684. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.flow.status.checked;
  685. const change = await this.ctx.service.change.getAllDataByCondition({ where, orders: [['in_time', 'desc']] });
  686. for (const c of change) {
  687. const types = ctx.helper._.map(c.type.split(','), function (t) {
  688. return self._getChangeConstName(changeConst.type, ctx.helper._.toInteger(t));
  689. });
  690. c.type = types.join(';');
  691. c.class = this._getChangeConstName(changeConst.class, c.class);
  692. c.quality = this._getChangeConstName(changeConst.quality, c.quality);
  693. c.charge = this._getChangeConstName(changeConst.charge, c.charge);
  694. c.attachments = await ctx.service.changeAtt.getChangeAttachment(c.cid);
  695. const names = ctx.helper._.map(c.attachments, function (x) {
  696. return x.filename + x.fileext;
  697. });
  698. c.attNames = names.join('\n');
  699. }
  700. const changeBills = await this.ctx.service.changeAuditList.getChangeAuditBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  701. for (const d of changeBills) {
  702. d.o_qty = d.oamount;
  703. d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  704. d.c_qty = d.camount;
  705. d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  706. d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  707. d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  708. d.sp_qty = d.spamount;
  709. d.sp_tp = this.ctx.helper.mul(d.sp_qty, d.unit_price, decimal.tp);
  710. const auditAmount = d.audit_amount ? d.audit_amount.split(',') : [];
  711. const relaChange = ctx.helper._.find(change, {cid: d.cid});
  712. for (const [i, aa] of auditAmount.entries()) {
  713. const amountField = 'qty_' + (i+1), tpField = 'tp_' + (i+1);
  714. d[amountField] = aa ? parseFloat(aa) : 0;
  715. d[tpField] = ctx.helper.mul(d[amountField], d.unit_price, decimal.tp);
  716. if (relaChange) {
  717. relaChange[tpField] = ctx.helper.add(relaChange[tpField], d[tpField]);
  718. }
  719. }
  720. }
  721. change.sort(function (a, b) {
  722. return a.code.localeCompare(b.code);
  723. });
  724. changeBills.sort(function (a, b) {
  725. const aCIndex = change.findIndex(function (c) {
  726. return c.cid === a.cid;
  727. });
  728. const bCIndex = change.findIndex(function (c) {
  729. return c.cid === b.cid;
  730. });
  731. return aCIndex === bCIndex
  732. ? ctx.helper.compareCode(a.code, b.code)
  733. : aCIndex - bCIndex;
  734. });
  735. this.changeData = {change: change, bills: changeBills};
  736. } catch(err) {
  737. this.ctx.helper.log(err);
  738. throw err;
  739. this.changeData = {change: [], bills: []};
  740. }
  741. }
  742. async _generateChangeAudit() {
  743. if (!!this.changeData.audit) return;
  744. this.changeData.audit = [];
  745. for (const c of this.changeData.change) {
  746. const changeAudit = await this.ctx.service.changeAudit.getListGroupByTimes(c.cid, c.times);
  747. this.changeData.audit.push(...changeAudit);
  748. }
  749. }
  750. async getChangeData(tid, sid, fields) {
  751. try {
  752. await this.ctx.service.tender.checkTender(tid);
  753. await this._generateChange(tid);
  754. return this.changeData.change;
  755. } catch (err) {
  756. return [];
  757. }
  758. }
  759. async getChangeBillsData(tid, sid, fields) {
  760. try {
  761. await this.ctx.service.tender.checkTender(tid);
  762. await this._generateChange(tid);
  763. return this.changeData.bills;
  764. } catch (err) {
  765. return [];
  766. }
  767. }
  768. async getChangeAuditData(tid, sid, fields) {
  769. try {
  770. await this.ctx.service.tender.checkTender(tid);
  771. await this._generateChange(tid);
  772. await this._generateChangeAudit();
  773. return this.changeData.audit;
  774. } catch (err) {
  775. return [];
  776. }
  777. }
  778. async _generateImportChange(sid) {
  779. if (this.importChange !== null) return;
  780. const self = this;
  781. try {
  782. const ctx = this.ctx;
  783. const change = await this.ctx.service.stageImportChange.getImportChange(sid);
  784. for (const c of change) {
  785. const types = ctx.helper._.map(c.type.split(','), function (t) {
  786. return self._getChangeConstName(changeConst.type, ctx.helper._.toInteger(t));
  787. });
  788. c.type = types.join(';');
  789. c.class = this._getChangeConstName(changeConst.class, c.class);
  790. c.quality = this._getChangeConstName(changeConst.quality, c.quality);
  791. c.charge = this._getChangeConstName(changeConst.charge, c.charge);
  792. }
  793. change.sort(function (a, b) {
  794. return a.code.localeCompare(b.code);
  795. });
  796. const changeBills = [];
  797. for (const c of change) {
  798. const bills = await this.ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: c.cid } });
  799. for (const b of bills) {
  800. b.o_qty = b.oamount;
  801. b.c_qty = b.camount;
  802. b.s_qty = b.samount ? parseFloat(b.samount) : 0;
  803. b.sp_qty = b.spamount;
  804. }
  805. bills.sort(function (a, b) {
  806. return ctx.helper.compareCode(a.code, b.code);
  807. });
  808. changeBills.push(...bills);
  809. }
  810. this.importChange = {change: change, bills: changeBills};
  811. } catch(err) {
  812. this.ctx.helper.log(err);
  813. throw err;
  814. this.importChange = {change: [], bills: []};
  815. }
  816. }
  817. async getImportChangeData(tid, sid, fields) {
  818. try {
  819. await this._generateImportChange(sid);
  820. return this.importChange.change;
  821. } catch (err) {
  822. return [];
  823. }
  824. }
  825. async getImportChangeBillsData(tid, sid, fields) {
  826. try {
  827. await this.ctx.service.tender.checkTender(tid);
  828. await this._generateImportChange(tid);
  829. return this.importChange.bills;
  830. } catch (err) {
  831. return [];
  832. }
  833. }
  834. async _generateChangeApply(tid) {
  835. if (!!this.changeApplyData) return;
  836. const helper = this.ctx.helper;
  837. const decimal = this.ctx.tender.info.decimal;
  838. const where = { tid };
  839. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeApply.status.checked;
  840. const apply = await this.ctx.service.changeApply.getAllDataByCondition({ where });
  841. const bills = await this.ctx.service.changeApplyList.getChangeBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  842. bills.forEach(x => {
  843. const a = apply.find(y => { return y.id === x.caid });
  844. const a_decimal = a.decimal ? JSON.stringify(a.decimal) : { tp: decimal.tp, up: decimal.up };
  845. x.o_tp = helper.mul(x.oamount, x.unit_price, a_decimal.tp);
  846. x.c_tp = helper.mul(x.camount, x.unit_price, a_decimal.tp);
  847. });
  848. bills.sort(function(a, b ) {
  849. const aCIndex = apply.findIndex(function (c) {
  850. return c.id === a.caid;
  851. });
  852. const bCIndex = apply.findIndex(function (c) {
  853. return c.id === b.caid;
  854. });
  855. return aCIndex === bCIndex
  856. ? helper.compareCode(a.code, b.code)
  857. : aCIndex - bCIndex;
  858. });
  859. this.changeApplyData = { data: apply, bills };
  860. }
  861. async _generateChangeApplyAudit() {
  862. if (!!this.changeApplyData.audit) return;
  863. this.changeApplyData.audit = [];
  864. for (const c of this.changeApplyData.data) {
  865. const changeAudit = await this.ctx.service.changeApplyAudit.getAllDataByCondition({ where: { caid: c.id, times: c.times }});
  866. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  867. this.changeApplyData.audit.push(...changeAuditFilter);
  868. }
  869. }
  870. async getChangeApplyData(tid, sid, fields) {
  871. try {
  872. await this._generateChangeApply(tid);
  873. return this.changeApplyData.data;
  874. } catch (err) {
  875. return [];
  876. }
  877. }
  878. async getChangeApplyBillsData(tid, sid, fields) {
  879. try {
  880. await this._generateChangeApply(tid);
  881. return this.changeApplyData.bills;
  882. } catch (err) {
  883. return [];
  884. }
  885. }
  886. async getChangeApplyAuditData(tid, sid, fields) {
  887. try {
  888. await this._generateChangeApply(tid);
  889. await this._generateChangeApplyAudit();
  890. return this.changeApplyData.audit;
  891. } catch (err) {
  892. this.ctx.log(err);
  893. return [];
  894. }
  895. }
  896. async _generateChangePlan(tid) {
  897. if (!!this.changePlanData) return;
  898. const helper = this.ctx.helper;
  899. const decimal = this.ctx.tender.info.decimal;
  900. this.changePlanData = {};
  901. const where = { tid };
  902. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeApply.status.checked;
  903. const data = await this.ctx.service.changePlan.getAllDataByCondition({ where });
  904. const bills = await this.ctx.service.changePlanList.getChangeBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  905. bills.forEach(x => {
  906. const plan = data.find(y => { return y.id === x.cpid });
  907. const p_decimal = plan.decimal ? JSON.stringify(plan.decimal) : { tp: decimal.tp, up: decimal.up };
  908. x.o_tp = helper.mul(x.oamount, x.unit_price, p_decimal.tp);
  909. x.c_tp = helper.mul(x.camount, x.unit_price, p_decimal.tp);
  910. x.s_tp = helper.mul(x.samount, x.unit_price, p_decimal.tp);
  911. x.sp_tp = helper.mul(x.spamount, x.unit_price, p_decimal.tp);
  912. const auditAmount = x.audit_amount ? x.audit_amount.split(',') : [];
  913. for (const [i, aa] of auditAmount.entries()) {
  914. const amountField = 'qty_' + (i+1), tpField = 'tp_' + (i+1);
  915. x[amountField] = aa ? parseFloat(aa) : 0;
  916. x[tpField] = helper.mul(x[amountField], x.unit_price, p_decimal.tp);
  917. if (plan) {
  918. plan[tpField] = helper.add(plan[tpField], x[tpField]);
  919. }
  920. }
  921. });
  922. bills.sort(function(a, b ) {
  923. const aCIndex = data.findIndex(function (c) {
  924. return c.id === a.cpid;
  925. });
  926. const bCIndex = data.findIndex(function (c) {
  927. return c.id === b.cpid;
  928. });
  929. return aCIndex === bCIndex
  930. ? helper.compareCode(a.code, b.code)
  931. : aCIndex - bCIndex;
  932. });
  933. this.changePlanData = { data, bills };
  934. }
  935. async _generateChangePlanAudit() {
  936. if (!!this.changePlanData.audit) return;
  937. this.changePlanData.audit = [];
  938. for (const c of this.changePlanData.data) {
  939. const changeAudit = await this.ctx.service.changePlanAudit.getAllDataByCondition({ where: { cpid: c.id, times: c.times }});
  940. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  941. this.changePlanData.audit.push(...changeAuditFilter);
  942. }
  943. }
  944. async getChangePlanData(tid, sid, fields) {
  945. try {
  946. await this._generateChangePlan(tid);
  947. return this.changePlanData.data;
  948. } catch (err) {
  949. return [];
  950. }
  951. }
  952. async getChangePlanBillsData(tid, sid, fields) {
  953. try {
  954. await this._generateChangePlan(tid);
  955. return this.changePlanData.bills;
  956. } catch (err) {
  957. return [];
  958. }
  959. }
  960. async getChangePlanAuditData(tid, sid, fields) {
  961. try {
  962. await this._generateChangePlan(tid);
  963. await this._generateChangePlanAudit();
  964. return this.changePlanData.audit;
  965. } catch (err) {
  966. this.ctx.log(err);
  967. return [];
  968. }
  969. }
  970. async _generateChangeProject(tid) {
  971. if (!!this.changeProjectData) return;
  972. const where = { tid };
  973. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeProject.status.checked;
  974. this.changeProjectData = { data: await this.ctx.service.changeProject.getAllDataByCondition({ where }) };
  975. }
  976. async _generateChangeProjectAudit() {
  977. if (!!this.changeProjectData.audit) return;
  978. this.changeProjectData.audit = [];
  979. for (const c of this.changeProjectData.data) {
  980. const changeAudit = await this.ctx.service.changeProjectAudit.getAllDataByCondition({ where: { cpid: c.id, times: c.times }});
  981. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  982. this.changeProjectData.audit.push(...changeAuditFilter);
  983. }
  984. }
  985. async getChangeProjectData(tid, sid, fields) {
  986. try {
  987. await this._generateChangeProject(tid);
  988. return this.changeProjectData.data;
  989. } catch (err) {
  990. this.ctx.log(err);
  991. return [];
  992. }
  993. }
  994. async getChangeProjectAuditData(tid, sid, fields) {
  995. try {
  996. await this._generateChangeProject(tid);
  997. await this._generateChangeProjectAudit();
  998. return this.changeProjectData.audit;
  999. } catch (err) {
  1000. return [];
  1001. }
  1002. }
  1003. async getStageJgcl(tid, sid, fields) {
  1004. try {
  1005. await this.ctx.service.tender.checkTender(tid);
  1006. await this.ctx.service.stage.checkStage(sid);
  1007. const data = await this.ctx.service.stageJgcl.getStageData(this.ctx.stage);
  1008. const preData = await this.ctx.service.stageJgcl.getPreStageData(this.ctx.stage.order);
  1009. for (const d of data) {
  1010. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1011. if (pd) {
  1012. d.pre_arrive_qty = pd.arrive_qty;
  1013. d.pre_arrive_tp = pd.arrive_tp;
  1014. d.pre_deduct_qty = pd.deduct_qty;
  1015. d.pre_deduct_tp = pd.deduct_tp;
  1016. }
  1017. d.end_arrive_qty = this.ctx.helper.add(d.pre_arrive_qty, d.arrive_qty);
  1018. d.end_arrive_tp = this.ctx.helper.add(d.pre_arrive_tp, d.arrive_tp);
  1019. d.end_deduct_qty = this.ctx.helper.add(d.pre_deduct_qty, d.deduct_qty);
  1020. d.end_deduct_tp = this.ctx.helper.add(d.pre_deduct_tp, d.deduct_tp);
  1021. }
  1022. return data;
  1023. } catch (err) {
  1024. return [];
  1025. }
  1026. }
  1027. async getStageBonus(tid, sid, fields) {
  1028. try {
  1029. await this.ctx.service.tender.checkTender(tid);
  1030. await this.ctx.service.stage.checkStage(sid);
  1031. const data = await this.ctx.service.stageBonus.getEndStageData(this.ctx.stage.order);
  1032. for (const d of data) {
  1033. const names = this.ctx.helper._.map(d.proof_file, function (x) {
  1034. return x.filename + x.fileext;
  1035. });
  1036. d.proof = names.join('\n');
  1037. }
  1038. return data;
  1039. } catch (err) {
  1040. return [];
  1041. }
  1042. }
  1043. async getStageOther(tid, sid, fields) {
  1044. try {
  1045. await this.ctx.service.tender.checkTender(tid);
  1046. await this.ctx.service.stage.checkStage(sid);
  1047. const data = await this.ctx.service.stageOther.getStageData(this.ctx.stage);
  1048. const preData = await this.ctx.service.stageOther.getPreStageData(this.ctx.stage.order);
  1049. for (const d of data) {
  1050. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1051. if (pd) {
  1052. d.pre_tp = pd.tp;
  1053. }
  1054. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1055. }
  1056. return data;
  1057. } catch (err) {
  1058. return [];
  1059. }
  1060. }
  1061. async getStageSafeProd(tid, sid, fields) {
  1062. try {
  1063. await this.ctx.service.tender.checkTender(tid);
  1064. await this.ctx.service.stage.checkStage(sid);
  1065. const data = await this.ctx.service.stageSafeProd.getStageData(this.ctx.stage);
  1066. const preData = await this.ctx.service.stageSafeProd.getPreStageData(this.ctx.stage.order);
  1067. for (const d of data) {
  1068. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1069. if (pd) {
  1070. d.pre_qty = pd.qty;
  1071. d.pre_tp = pd.tp;
  1072. }
  1073. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  1074. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1075. }
  1076. return data;
  1077. } catch (err) {
  1078. return [];
  1079. }
  1080. }
  1081. async getStageTempLand(tid, sid, fields) {
  1082. try {
  1083. await this.ctx.service.tender.checkTender(tid);
  1084. await this.ctx.service.stage.checkStage(sid);
  1085. const data = await this.ctx.service.stageTempLand.getStageData(this.ctx.stage);
  1086. const preData = await this.ctx.service.stageTempLand.getPreStageData(this.ctx.stage.order);
  1087. for (const d of data) {
  1088. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1089. if (pd) {
  1090. d.pre_qty = pd.qty;
  1091. d.pre_tp = pd.tp;
  1092. }
  1093. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  1094. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1095. }
  1096. return data;
  1097. } catch (err) {
  1098. return [];
  1099. }
  1100. }
  1101. async getSumStageBillsData(tid, sid, fields) {
  1102. try {
  1103. await this.ctx.service.tender.checkTender(tid);
  1104. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  1105. const checkStageField = function (stageOrder) {
  1106. for (const f of fields) {
  1107. if (f.indexOf('s' + stageOrder + '_') >= 0) {
  1108. return true;
  1109. }
  1110. }
  1111. return false;
  1112. };
  1113. const calcFields = ['deal_tp', 'total_price'], calcPrefix = [];
  1114. const stages = this.ctx.service.stage.getValidStages(this.ctx.tender.id);
  1115. for (const stage of stages) {
  1116. if (!checkStageField(stage.order)) return;
  1117. await this.ctx.service.stage.doCheckStage(stage);
  1118. calcFields.push('s' + stage.order + '_contract_tp');
  1119. calcFields.push('s' + stage.order + '_qc_tp');
  1120. calcFields.push('s' + stage.order + '_gather_tp');
  1121. calcFields.push('s' + stage.order + '_');
  1122. const curStage = stage.readOnly
  1123. ? await this.ctx.service.stageBills.getAuditorStageData2(this.ctx.tender.id, stage.id, stage.curTimes, stage.curOrder)
  1124. : await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, stage.id);
  1125. this.ctx.helper.assignRelaData(billsData, [
  1126. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp'], prefix: 's' + stage.order + '_', relaId: 'lid'}
  1127. ]);
  1128. }
  1129. const billsTree = new Ledger.billsTree(this.ctx, {
  1130. id: 'ledger_id',
  1131. pid: 'ledger_pid',
  1132. order: 'order',
  1133. level: 'level',
  1134. rootId: -1,
  1135. keys: ['id', 'tender_id', 'ledger_id'],
  1136. stageId: 'id',
  1137. calcFields: calcFields,
  1138. calc: function (node) {
  1139. for (const prefix of calcPrefix) {
  1140. if (node.children && node.children.length === 0) {
  1141. node[prefix + 'gather_qty'] = self.ctx.helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  1142. }
  1143. node[prefix + 'gather_tp'] = self.ctx.helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  1144. }
  1145. }
  1146. });
  1147. billsTree.loadDatas(billsData);
  1148. billsTree.calculateAll();
  1149. return billsTree.getDefaultDatas();
  1150. } catch (err) {
  1151. return [];
  1152. }
  1153. }
  1154. async getStageAuditors(tid, sid) {
  1155. await this.ctx.service.tender.checkTender(tid);
  1156. await this.ctx.service.stage.checkStage(sid);
  1157. const auditors = await this.ctx.service.stageAudit.getFinalAuditGroup(this.ctx.stage.id, this.ctx.stage.curTimes);
  1158. const user = await this.ctx.service.projectAccount.getDataById(this.ctx.stage.user_id);
  1159. const result = [{
  1160. aid: user.id,
  1161. name: user.name,
  1162. company: user.company,
  1163. role: user.role,
  1164. mobile: user.mobile,
  1165. telephone: user.telephone,
  1166. sign_path: user.sign_path,
  1167. opinion: user.opinion,
  1168. end_time: auditors && auditors.length > 0 ? auditors[0].begin_time : null,
  1169. sort: 0,
  1170. }, ...auditors];
  1171. return result;
  1172. }
  1173. async getSignSelect(tid, sid, customSelect) {
  1174. await this.ctx.service.tender.checkTender(tid);
  1175. await this.ctx.service.stage.checkStage(sid);
  1176. const signSelect = customSelect.sign_select, result = {};
  1177. for (const [i, ss] of signSelect.entries()) {
  1178. const user = await this.ctx.service.projectAccount.getDataById(ss.id);
  1179. const sign = {
  1180. id: ss.id, name: user.name, company: user.company, role: user.role,
  1181. mobile: user.mobile, telephone: user.telephone,
  1182. };
  1183. if (ss.id !== this.ctx.stage.user_id) {
  1184. const audit = this.ctx.stage.auditors.find(x => {return x.aid === ss.id});
  1185. user.end_time = audit ? audit.end_time : ss.audit_time;
  1186. } else {
  1187. user.end_time = this.ctx.stage.auditors[0].end_time;
  1188. }
  1189. if (user.end_time) sign.sign_path = user.sign_path;
  1190. result['sign' + (i+1)] = sign;
  1191. }
  1192. return result;
  1193. }
  1194. async getChangeInfo(tid, sid) {
  1195. await this.ctx.service.tender.checkTender(tid);
  1196. await this.ctx.service.stage.checkStage(sid);
  1197. this.changeInfo = await this.ctx.service.stageChange.getChangeWithUsedInfo(this.ctx.stage);
  1198. const usedChangesId = await this.ctx.service.stageChange.getStageUsedChangeId(sid);
  1199. for (const c of this.changeInfo) {
  1200. c.cur_used = usedChangesId.indexOf(c.cid) >= 0;
  1201. c.used_ratio = c.used_pt;
  1202. c.is_import = 0;
  1203. }
  1204. return this.changeInfo;
  1205. }
  1206. async getChangeInfoBills(tid, sid) {
  1207. if (!this.changeInfo) await this.getChangeInfo(tid, sid);
  1208. this.changeInfoBills = [];
  1209. for (const c of this.changeInfo) {
  1210. const cb = await this.ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: c.cid } });
  1211. const cbu = await this.ctx.service.stageChange.getUsedData(tid, c.cid);
  1212. const curUsedBills = await this.ctx.service.stageChange.getStageUsedData(sid, c.cid);
  1213. for (const b of cb) {
  1214. b.qty = this.ctx.helper._.toNumber(b.samount);
  1215. b.tp = this.ctx.helper.round(this.ctx.helper.mul(b.qty, b.unit_price), this.ctx.tender.info.decimal.tp);
  1216. const u = cbu.filter(x => { return x.cbid === b.id; });
  1217. b.used_qty = u.length > 0 ? this.ctx.helper.sum(u.map(x => { return x.qty})) : 0;
  1218. b.valid_qty = this.ctx.helper.sub(b.qty, b.used_qty);
  1219. const cur = this.ctx.helper._.filter(curUsedBills, { cbid: b.id });
  1220. b.cur_qty = 0;
  1221. for (const cc of cur) {
  1222. b.cur_qty = this.ctx.helper.add(b.cur_qty, cc.qty);
  1223. }
  1224. b.cur_used = !!b.cur_qty;
  1225. this.changeInfoBills.push(b);
  1226. }
  1227. }
  1228. return this.changeInfoBills;
  1229. }
  1230. async getPmDeal() {
  1231. let result = [];
  1232. if (!PermissionCheck.viewPmData(this.ctx.session.sessionUser.permission)) return result;
  1233. const selects = await this.ctx.service.project.getPmDealCache(this.ctx.session.sessionProject.id);
  1234. const pm = require('../lib/pm');
  1235. this.pmDeal = await pm.dealData(this.ctx, this.ctx.session.sessionProject.code, selects);
  1236. result = this.pmDeal.contracts ? this.pmDeal.contracts.filter(x => { return x.ContractsType === 2 }) : [];
  1237. const fields = ['Code', 'Name', 'ContractName', 'ContractCode', 'ContractPrice', 'ContractReturned', 'ContractsPaid', 'ContractStatus', 'ContractLocking', 'CreateTime'], self = this;
  1238. result.forEach(x => {
  1239. const treeNode = self.pmDeal.tree_contracts.find(y => { return x.TreeId === y.Id });
  1240. if (!treeNode) return;
  1241. for (const f of fields) {
  1242. x['Tree_' + f] = treeNode[f];
  1243. }
  1244. });
  1245. // 排序:标段-合同类别-创建时间
  1246. result.sort((x, y) => {
  1247. const bidSort = selects.indexOf(x.BidsectionId + '') - selects.indexOf(y.BidsectionId + '');
  1248. if (bidSort) return bidSort;
  1249. const typeSort = x.ContractsType - y.ContractsType;
  1250. if (typeSort) return typeSort;
  1251. return x.create_time - y.create_time;
  1252. });
  1253. return result;
  1254. }
  1255. }
  1256. return ReportMemory;
  1257. };