report_memory.js 63 KB

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