report_memory.js 81 KB

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