report_memory.js 73 KB

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