report_memory.js 64 KB

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