report_memory.js 63 KB

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