report_memory.js 69 KB

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