report_memory.js 70 KB

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