report_memory.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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 = this.ctx.stage.readOnly
  374. ? await this.ctx.service.stageChange.getAuditorAllStageData(this.ctx.tender.id, this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder)
  375. : await this.ctx.service.stageChange.getLastestAllStageData(this.ctx.tender.id, this.ctx.stage.id);
  376. const minusChange = changeData.filter(x => { return x.minus });
  377. this.ctx.helper.assignSumRelaData(billsData, 'id', [
  378. {data: preMinusChange, fields: [{source: 'qty', target: 'pre_minus_qc_qty'}], relaField: 'lid'},
  379. {data: minusChange, fields: [{source: 'qty', target: 'minus_qc_qty'}], relaField: 'lid'},
  380. ]);
  381. }
  382. const billsTree = this._getNewBillsTree();
  383. billsTree.loadDatas(billsData);
  384. billsTree.calculateAll();
  385. if (this._checkFieldsExist(fields, billsFields.bgl)) {
  386. await this._calcBillsBgl(billsTree);
  387. }
  388. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  389. this._calcLeafXmjRela(billsTree);
  390. }
  391. return billsTree.getDefaultDatas();
  392. } catch(err) {
  393. this.ctx.log(err);
  394. return [];
  395. }
  396. }
  397. async _calcPosBgl() {
  398. if (!this.ctx.stage) return;
  399. const helper = this.ctx.helper;
  400. const tender = this.ctx.tender;
  401. const stage = this.ctx.stage;
  402. const bglData = this.ctx.stage.readOnly
  403. ? await this.ctx.service.stageChange.getAuditorAllStageData(tender.id, stage.id, stage.curTimes, stage.curOrder)
  404. : await this.ctx.service.stageChange.getLastestAllStageData(tender.id, stage.id);
  405. for (const p of this.pos.datas) {
  406. p.qc_bgl_code = '';
  407. const pBgl = helper._.filter(bglData, {lid: p.lid, pid: p.id});
  408. if (pBgl.length === 0) continue;
  409. helper._.pullAll(bglData, pBgl);
  410. const validBgl = helper._.filter(pBgl, function (x) {
  411. return !helper.checkZero(x.qty);
  412. });
  413. p.qc_bgl_code = helper._.uniq(helper._.map(validBgl, 'c_code')).join(';');
  414. }
  415. }
  416. async getStagePosData(tid, sid, fields) {
  417. try {
  418. await this.ctx.service.tender.checkTender(tid);
  419. if (sid) {
  420. await this.ctx.service.stage.checkStage(sid);
  421. }
  422. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  423. let curPosStage = [], prePosStage = [];
  424. if (this._checkFieldsExist(fields, posFields.stage)) {
  425. if (this.ctx.stage.readOnly) {
  426. curPosStage = await this.ctx.service.stagePos.getAuditorStageData2(this.ctx.tender.id,
  427. this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  428. } else {
  429. curPosStage = await this.ctx.service.stagePos.getLastestStageData2(this.ctx.tender.id, this.ctx.stage.id);
  430. }
  431. }
  432. if (this._checkFieldsExist(fields, posFields.stageEnd)) {
  433. prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  434. }
  435. this.ctx.helper.assignRelaData(posData, [
  436. {data: curPosStage, fields: ['contract_qty', 'qc_qty', 'contract_expr', 'postil'], prefix: '', relaId: 'pid'},
  437. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  438. ]);
  439. if (this._checkFieldsExist(fields, posFields.final1)) {
  440. const preMinusChange = await this.ctx.service.stageChangeFinal.getPreMinusChange(this.ctx.stage.tid, this.ctx.stage.order);
  441. const changeData = this.ctx.stage.readOnly
  442. ? await this.ctx.service.stageChange.getAuditorAllStageData(this.ctx.tender.id, this.ctx.stage.id, this.ctx.stage.curTimes, this.ctx.stage.curOrder)
  443. : await this.ctx.service.stageChange.getLastestAllStageData(this.ctx.tender.id, this.ctx.stage.id);
  444. const minusChange = changeData.filter(x => { return x.minus });
  445. this.ctx.helper.assignSumRelaData(posData, 'id', [
  446. {data: preMinusChange, fields: [{source: 'qty', target: 'pre_minus_qc_qty'}], relaField: 'pid'},
  447. {data: minusChange, fields: [{source: 'qty', target: 'minus_qc_qty'}], relaField: 'pid'},
  448. ]);
  449. }
  450. this.pos.loadDatas(posData);
  451. this.pos.calculateAll();
  452. if (this._checkFieldsExist(fields, posFields.bgl)) {
  453. await this._calcPosBgl();
  454. }
  455. return this.pos.getDatas();
  456. } catch (err) {
  457. return [];
  458. }
  459. }
  460. _getStageValidRole () {
  461. if (!this.ctx.stage) throw '期数据错误,请重试';
  462. if (this.stageValidRole && this.stageValidRole.length > 0) return;
  463. const result = [{dataOrder: 0, flowOrder: 0, uid: this.ctx.stage.user_id}];
  464. for (const auditor of this.ctx.stage.auditors) {
  465. if (auditor.status === audit.stage.status.checked ||
  466. (auditor.status === audit.stage.status.checking && !this.ctx.stage.readOnly)) {
  467. const role = result.find(function (r) {
  468. return r.uid === auditor.aid;
  469. });
  470. if (role) {
  471. role.dataOrder = auditor.order;
  472. } else {
  473. result.push({
  474. dataOrder: auditor.order,
  475. flowOrder: result.length,
  476. uid: auditor.aid
  477. })
  478. }
  479. }
  480. }
  481. this.stageValidRole = result;
  482. };
  483. async getStageBillsCompareData(tid, sid, fields) {
  484. try {
  485. await this.ctx.service.tender.checkTender(tid);
  486. await this.ctx.service.stage.checkStage(sid);
  487. await this._getStageValidRole();
  488. const stage = this.ctx.stage, helper = this.ctx.helper;
  489. const validRole = this.stageValidRole;
  490. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  491. const allStageBills = await this.ctx.service.stageBills.getAllDataByCondition({where: {sid: sid}});
  492. const stageBillsIndex = {}, timesLen = 100;
  493. for (const role of validRole) {
  494. const stageBills = this.ctx.helper._.filter(allStageBills, function (x) {
  495. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  496. });
  497. this.ctx.helper._.pullAll(allStageBills, stageBills);
  498. for (const sb of stageBills) {
  499. const key = 'sb-' + sb.lid;
  500. const sbi = stageBillsIndex[key];
  501. if (sbi) {
  502. if ((sbi.times * timesLen + sbi.order) < (sb.times * timesLen + sb.order)) stageBillsIndex[key] = sb;
  503. } else {
  504. stageBillsIndex[key] = sb;
  505. }
  506. }
  507. const filterStageBills = [];
  508. for (const prop in stageBillsIndex) {
  509. filterStageBills.push(stageBillsIndex[prop]);
  510. }
  511. this.ctx.helper.assignRelaData(billsData, [
  512. {data: filterStageBills, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'r' + role.flowOrder + '_', relaId: 'lid'}
  513. ]);
  514. }
  515. if (this._checkFieldsExist(fields, billsFields.stageEnd)) {
  516. const preStage = this.ctx.stage.order > 1 ? await this.ctx.service.stageBillsFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  517. this.ctx.helper.assignRelaData(billsData, [
  518. {data: preStage, fields: ['contract_qty', 'contract_tp', 'qc_qty', 'qc_tp'], prefix: 'pre_', relaId: 'lid'}
  519. ]);
  520. }
  521. const billsTree = this._getNewBillsTree();
  522. billsTree.loadDatas(billsData);
  523. for (const role of validRole) {
  524. const prefix = 'r' + role.flowOrder + '_';
  525. billsTree.setting.calcFields.push(prefix + 'contract_tp', prefix + 'qc_tp', prefix + 'gather_tp');
  526. }
  527. billsTree.calculateAll(function(node) {
  528. let prefix = '';
  529. if (node.children && node.children.length === 0) {
  530. node.pre_gather_qty = helper.add(node.pre_contract_qty, node.pre_qc_qty);
  531. for (const role of validRole) {
  532. prefix = 'r' + role.flowOrder + '_';
  533. node[prefix + 'gather_qty'] = helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  534. }
  535. }
  536. node.pre_gather_tp = helper.add(node.pre_contract_tp, node.pre_qc_tp);
  537. for (const role of validRole) {
  538. prefix = 'r' + role.flowOrder + '_';
  539. node[prefix + 'gather_tp'] = helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  540. }
  541. });
  542. if (this._checkFieldsExist(fields, billsFields.leafXmj)) {
  543. this._calcLeafXmjRela(billsTree);
  544. }
  545. return billsTree.getDefaultDatas();
  546. // return billsTree.getDatas([
  547. // 'id', 'tender_id', 'ledger_id', 'ledger_pid', 'level', 'order', 'full_path', 'is_leaf', //8
  548. // 'code', 'b_code', 'name', 'unit', 'unit_price', //5
  549. // 'deal_qty', 'deal_tp', 'quantity', 'total_price', 'dgn_qty1', 'dgn_qty2', //6
  550. // 'drawing_code', 'memo', 'node_type', 'is_tp', //4
  551. // 'r0_contract_qty', 'r0_contract_tp', 'r0_qc_qty', 'r0_qc_tp', 'r0_gather_qty', 'r0_gather_tp', //6
  552. // 'r1_contract_qty', 'r1_contract_tp', 'r1_qc_qty', 'r1_qc_tp', 'r1_gather_qty', 'r1_gather_tp',
  553. // 'r2_contract_qty', 'r2_contract_tp', 'r2_qc_qty', 'r2_qc_tp', 'r2_gather_qty', 'r2_gather_tp',
  554. // 'r3_contract_qty', 'r3_contract_tp', 'r3_qc_qty', 'r3_qc_tp', 'r3_gather_qty', 'r3_gather_tp',
  555. // 'r4_contract_qty', 'r4_contract_tp', 'r4_qc_qty', 'r4_qc_tp', 'r4_gather_qty', 'r4_gather_tp',
  556. // 'r5_contract_qty', 'r5_contract_tp', 'r5_qc_qty', 'r5_qc_tp', 'r5_gather_qty', 'r5_gather_tp',
  557. // 'r6_contract_qty', 'r6_contract_tp', 'r6_qc_qty', 'r6_qc_tp', 'r6_gather_qty', 'r6_gather_tp',
  558. // 'r7_contract_qty', 'r7_contract_tp', 'r7_qc_qty', 'r7_qc_tp', 'r7_gather_qty', 'r7_gather_tp',
  559. // 'r8_contract_qty', 'r8_contract_tp', 'r8_qc_qty', 'r8_qc_tp', 'r8_gather_qty', 'r8_gather_tp',
  560. // 'r9_contract_qty', 'r9_contract_tp', 'r9_qc_qty', 'r9_qc_tp', 'r9_gather_qty', 'r9_gather_tp',
  561. // 'r10_contract_qty', 'r10_contract_tp', 'r10_qc_qty', 'r10_qc_tp', 'r10_gather_qty', 'r10_gather_tp',
  562. // 'pre_contract_qty', 'pre_contract_tp', 'pre_qc_qty', 'pre_qc_tp', 'pre_gather_qty', 'pre_gather_tp',
  563. // 'chapter', //1
  564. // ]);
  565. } catch (err) {
  566. return [];
  567. }
  568. }
  569. async getStagePosCompareData(tid, sid, fields) {
  570. try {
  571. await this.ctx.service.tender.checkTender(tid);
  572. await this.ctx.service.stage.checkStage(sid);
  573. await this._getStageValidRole();
  574. const stage = this.ctx.stage, helper = this.ctx.helper;
  575. const validRole = this.stageValidRole;
  576. const allStagePos = await this.ctx.service.stagePos.getAllDataByCondition({where: {sid: sid}});
  577. const posData = await this.ctx.service.pos.getAllDataByCondition({ where: {tid: this.ctx.tender.id }});
  578. const prePosStage = this.ctx.stage.order > 1 ? await this.ctx.service.stagePosFinal.getFinalData(this.ctx.tender, this.ctx.stage.order - 1) : [];
  579. this.ctx.helper.assignRelaData(posData, [
  580. {data: prePosStage, fields: ['contract_qty', 'qc_qty'], prefix: 'pre_', relaId: 'pid'}
  581. ]);
  582. const stagePosIndex = {}, timesLen = 100;
  583. for (const role of validRole) {
  584. const stagePos = this.ctx.helper._.filter(allStagePos, function (x) {
  585. return x.times < stage.curTimes || (x.times === stage.curTimes && x.order <= role.dataOrder);
  586. });
  587. this.ctx.helper._.pullAll(allStagePos, stagePos);
  588. for (const sp of stagePos) {
  589. const key = 'sp-' + sp.pid;
  590. const spi = stagePosIndex[key];
  591. if (spi) {
  592. if ((spi.times * timesLen + spi.order) < (sp.times * timesLen + sp.order)) stagePosIndex[key] = sp;
  593. } else {
  594. stagePosIndex[key] = sp;
  595. }
  596. }
  597. const filterStagePos = [];
  598. for (const prop in stagePosIndex) {
  599. filterStagePos.push(stagePosIndex[prop]);
  600. }
  601. this.ctx.helper.assignRelaData(posData, [
  602. {data: filterStagePos, fields: ['contract_qty', 'qc_qty'], prefix: 'r' + role.flowOrder + '_', relaId: 'pid'}
  603. ]);
  604. }
  605. this.pos.loadDatas(posData);
  606. this.pos.calculateAll(function (p) {
  607. p.pre_gather_qty = helper.add(p.pre_contract_qty, p.pre_qc_qty);
  608. for (const role of validRole) {
  609. const prefix = 'r' + role.flowOrder + '_';
  610. p[prefix + 'gather_qty'] = helper.add(p[prefix + 'contract_qty'], p[prefix + 'qc_qty']);
  611. }
  612. });
  613. return this.pos.getDatas();
  614. } catch (err) {
  615. return [];
  616. }
  617. }
  618. async getStagePayData(tid, sid, fields) {
  619. try {
  620. await this.ctx.service.tender.checkTender(tid);
  621. await this.ctx.service.stage.checkStage(sid);
  622. const stage = this.ctx.stage;
  623. const dealPay = await this.ctx.service.stagePay.getStagePays(this.ctx.stage);
  624. if (!this.ctx.stage.readOnly) {
  625. // 计算 本期金额
  626. const PayCalculator = require('../lib/pay_calc');
  627. const payCalculator = new PayCalculator(this.ctx, this.ctx.stage, this.ctx.tender.info);
  628. await payCalculator.calculateAll(dealPay);
  629. }
  630. if (this._checkFieldsExist(fields, ['start_stage_order']) && this.ctx.stage.status !== audit.stage.status.checked) {
  631. for (const dp of dealPay) {
  632. if (!dp.start_stage_order || dp.start_stage_order === this.ctx.stage.order) {
  633. dp.start_stage_order = this.ctx.helper.checkZero(dp.tp) ? null : this.ctx.stage.order;
  634. }
  635. }
  636. }
  637. if (this._checkFieldsExistReg(fields, 'r[0-9]+_tp')) {
  638. this._getStageValidRole();
  639. const allStagePays = await this.ctx.service.stagePay.getAllDataByCondition({
  640. where: {sid: stage.id, stimes: stage.curTimes}
  641. });
  642. for (const [i, role] of this.stageValidRole.entries()) {
  643. if (i < this.stageValidRole.length - 1) {
  644. const stagePays = this.ctx.helper._.filter(allStagePays, function (x) {
  645. return x.stimes === stage.curTimes && x.sorder === role.dataOrder;
  646. });
  647. this.ctx.helper._.pullAll(allStagePays, stagePays);
  648. for (const sp of stagePays) {
  649. const dp = dealPay.find(function (x) {return x.pid === sp.pid});
  650. if (dp) {
  651. dp['r' + role.flowOrder + '_tp'] = sp.tp;
  652. }
  653. }
  654. } else {
  655. for (const dp of dealPay) {
  656. dp['r' + role.flowOrder + '_tp'] = dp.tp;
  657. }
  658. }
  659. }
  660. }
  661. return dealPay;
  662. } catch (err) {
  663. return [];
  664. }
  665. }
  666. async getStageChangeBillsData(tid, sid, fields) {
  667. try {
  668. await this.ctx.service.tender.checkTender(tid);
  669. await this.ctx.service.stage.checkStage(sid);
  670. if (this.ctx.stage.readOnly) {
  671. return await this.ctx.service.stageChange.getReportAuditorAllStageData(tid, sid,
  672. this.ctx.stage.curTimes, this.ctx.stage.curOrder);
  673. } else {
  674. return await this.ctx.service.stageChange.getReportLastestAllStageData(tid, sid);
  675. }
  676. } catch (err) {
  677. return [];
  678. }
  679. }
  680. _getChangeConstName(define, value) {
  681. for (const prop in define) {
  682. if (define[prop].value === value) {
  683. return define[prop].name;
  684. }
  685. }
  686. return '';
  687. }
  688. async _generateChange(tid) {
  689. if (this.changeData !== null) return;
  690. const self = this;
  691. try {
  692. const decimal = this.ctx.tender.info.decimal, ctx = this.ctx;
  693. const where = { tid, valid: 1 };
  694. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.flow.status.checked;
  695. const change = await this.ctx.service.change.getAllDataByCondition({ where, orders: [['in_time', 'desc']] });
  696. for (const c of change) {
  697. const types = ctx.helper._.map(c.type.split(','), function (t) {
  698. return self._getChangeConstName(changeConst.type, ctx.helper._.toInteger(t));
  699. });
  700. c.type = types.join(';');
  701. c.class = this._getChangeConstName(changeConst.class, c.class);
  702. c.quality = this._getChangeConstName(changeConst.quality, c.quality);
  703. c.charge = this._getChangeConstName(changeConst.charge, c.charge);
  704. c.attachments = await ctx.service.changeAtt.getChangeAttachment(c.cid);
  705. const names = ctx.helper._.map(c.attachments, function (x) {
  706. return x.filename + x.fileext;
  707. });
  708. c.attNames = names.join('\n');
  709. }
  710. const changeBills = await this.ctx.service.changeAuditList.getChangeAuditBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  711. for (const d of changeBills) {
  712. d.o_qty = d.oamount;
  713. d.o_tp = this.ctx.helper.mul(d.o_qty, d.unit_price, decimal.tp);
  714. d.c_qty = d.camount;
  715. d.c_tp = this.ctx.helper.mul(d.c_qty, d.unit_price, decimal.tp);
  716. d.s_qty = d.samount ? parseFloat(d.samount) : 0;
  717. d.s_tp = this.ctx.helper.mul(d.s_qty, d.unit_price, decimal.tp);
  718. d.sp_qty = d.spamount;
  719. d.sp_tp = this.ctx.helper.mul(d.sp_qty, d.unit_price, decimal.tp);
  720. const auditAmount = d.audit_amount ? d.audit_amount.split(',') : [];
  721. const relaChange = ctx.helper._.find(change, {cid: d.cid});
  722. for (const [i, aa] of auditAmount.entries()) {
  723. const amountField = 'qty_' + (i+1), tpField = 'tp_' + (i+1);
  724. d[amountField] = aa ? parseFloat(aa) : 0;
  725. d[tpField] = ctx.helper.mul(d[amountField], d.unit_price, decimal.tp);
  726. if (relaChange) {
  727. relaChange[tpField] = ctx.helper.add(relaChange[tpField], d[tpField]);
  728. }
  729. }
  730. }
  731. change.sort(function (a, b) {
  732. return a.code.localeCompare(b.code);
  733. });
  734. changeBills.sort(function (a, b) {
  735. const aCIndex = change.findIndex(function (c) {
  736. return c.cid === a.cid;
  737. });
  738. const bCIndex = change.findIndex(function (c) {
  739. return c.cid === b.cid;
  740. });
  741. return aCIndex === bCIndex
  742. ? ctx.helper.compareCode(a.code, b.code)
  743. : aCIndex - bCIndex;
  744. });
  745. this.changeData = {change: change, bills: changeBills};
  746. } catch(err) {
  747. this.ctx.helper.log(err);
  748. throw err;
  749. this.changeData = {change: [], bills: []};
  750. }
  751. }
  752. async _generateChangeAudit() {
  753. if (!!this.changeData.audit) return;
  754. this.changeData.audit = [];
  755. for (const c of this.changeData.change) {
  756. const changeAudit = await this.ctx.service.changeAudit.getListGroupByTimes(c.cid, c.times);
  757. this.changeData.audit.push(...changeAudit);
  758. }
  759. }
  760. async getChangeData(tid, sid, fields) {
  761. try {
  762. await this.ctx.service.tender.checkTender(tid);
  763. await this._generateChange(tid);
  764. return this.changeData.change;
  765. } catch (err) {
  766. return [];
  767. }
  768. }
  769. async getChangeBillsData(tid, sid, fields) {
  770. try {
  771. await this.ctx.service.tender.checkTender(tid);
  772. await this._generateChange(tid);
  773. return this.changeData.bills;
  774. } catch (err) {
  775. return [];
  776. }
  777. }
  778. async getChangeAuditData(tid, sid, fields) {
  779. try {
  780. await this.ctx.service.tender.checkTender(tid);
  781. await this._generateChange(tid);
  782. await this._generateChangeAudit();
  783. return this.changeData.audit;
  784. } catch (err) {
  785. return [];
  786. }
  787. }
  788. async _generateImportChange(sid) {
  789. if (this.importChange !== null) return;
  790. const self = this;
  791. try {
  792. const ctx = this.ctx;
  793. const change = await this.ctx.service.stageImportChange.getImportChange(sid);
  794. for (const c of change) {
  795. const types = ctx.helper._.map(c.type.split(','), function (t) {
  796. return self._getChangeConstName(changeConst.type, ctx.helper._.toInteger(t));
  797. });
  798. c.type = types.join(';');
  799. c.class = this._getChangeConstName(changeConst.class, c.class);
  800. c.quality = this._getChangeConstName(changeConst.quality, c.quality);
  801. c.charge = this._getChangeConstName(changeConst.charge, c.charge);
  802. }
  803. change.sort(function (a, b) {
  804. return a.code.localeCompare(b.code);
  805. });
  806. const changeBills = [];
  807. for (const c of change) {
  808. const bills = await this.ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: c.cid } });
  809. for (const b of bills) {
  810. b.o_qty = b.oamount;
  811. b.c_qty = b.camount;
  812. b.s_qty = b.samount ? parseFloat(b.samount) : 0;
  813. b.sp_qty = b.spamount;
  814. }
  815. bills.sort(function (a, b) {
  816. return ctx.helper.compareCode(a.code, b.code);
  817. });
  818. changeBills.push(...bills);
  819. }
  820. this.importChange = {change: change, bills: changeBills};
  821. } catch(err) {
  822. this.ctx.helper.log(err);
  823. throw err;
  824. this.importChange = {change: [], bills: []};
  825. }
  826. }
  827. async getImportChangeData(tid, sid, fields) {
  828. try {
  829. await this._generateImportChange(sid);
  830. return this.importChange.change;
  831. } catch (err) {
  832. return [];
  833. }
  834. }
  835. async getImportChangeBillsData(tid, sid, fields) {
  836. try {
  837. await this.ctx.service.tender.checkTender(tid);
  838. await this._generateImportChange(tid);
  839. return this.importChange.bills;
  840. } catch (err) {
  841. return [];
  842. }
  843. }
  844. async _generateChangeApply(tid) {
  845. if (!!this.changeApplyData) return;
  846. const helper = this.ctx.helper;
  847. const decimal = this.ctx.tender.info.decimal;
  848. const where = { tid };
  849. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeApply.status.checked;
  850. const apply = await this.ctx.service.changeApply.getAllDataByCondition({ where });
  851. const bills = await this.ctx.service.changeApplyList.getChangeBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  852. bills.forEach(x => {
  853. const a = apply.find(y => { return y.id === x.caid });
  854. const a_decimal = a.decimal ? JSON.stringify(a.decimal) : { tp: decimal.tp, up: decimal.up };
  855. x.o_tp = helper.mul(x.oamount, x.unit_price, a_decimal.tp);
  856. x.c_tp = helper.mul(x.camount, x.unit_price, a_decimal.tp);
  857. });
  858. bills.sort(function(a, b ) {
  859. const aCIndex = apply.findIndex(function (c) {
  860. return c.id === a.caid;
  861. });
  862. const bCIndex = apply.findIndex(function (c) {
  863. return c.id === b.caid;
  864. });
  865. return aCIndex === bCIndex
  866. ? helper.compareCode(a.code, b.code)
  867. : aCIndex - bCIndex;
  868. });
  869. this.changeApplyData = { data: apply, bills };
  870. }
  871. async _generateChangeApplyAudit() {
  872. if (!!this.changeApplyData.audit) return;
  873. this.changeApplyData.audit = [];
  874. for (const c of this.changeApplyData.data) {
  875. const changeAudit = await this.ctx.service.changeApplyAudit.getAllDataByCondition({ where: { caid: c.id, times: c.times }});
  876. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  877. this.changeApplyData.audit.push(...changeAuditFilter);
  878. }
  879. }
  880. async getChangeApplyData(tid, sid, fields) {
  881. try {
  882. await this._generateChangeApply(tid);
  883. return this.changeApplyData.data;
  884. } catch (err) {
  885. return [];
  886. }
  887. }
  888. async getChangeApplyBillsData(tid, sid, fields) {
  889. try {
  890. await this._generateChangeApply(tid);
  891. return this.changeApplyData.bills;
  892. } catch (err) {
  893. return [];
  894. }
  895. }
  896. async getChangeApplyAuditData(tid, sid, fields) {
  897. try {
  898. await this._generateChangeApply(tid);
  899. await this._generateChangeApplyAudit();
  900. return this.changeApplyData.audit;
  901. } catch (err) {
  902. this.ctx.log(err);
  903. return [];
  904. }
  905. }
  906. async _generateChangePlan(tid) {
  907. if (!!this.changePlanData) return;
  908. const helper = this.ctx.helper;
  909. const decimal = this.ctx.tender.info.decimal;
  910. this.changePlanData = {};
  911. const where = { tid };
  912. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeApply.status.checked;
  913. const data = await this.ctx.service.changePlan.getAllDataByCondition({ where });
  914. const bills = await this.ctx.service.changePlanList.getChangeBills(tid, this.ctx.session.sessionProject.page_show.isOnlyChecked);
  915. bills.forEach(x => {
  916. const plan = data.find(y => { return y.id === x.cpid });
  917. const p_decimal = plan.decimal ? JSON.stringify(plan.decimal) : { tp: decimal.tp, up: decimal.up };
  918. x.o_tp = helper.mul(x.oamount, x.unit_price, p_decimal.tp);
  919. x.c_tp = helper.mul(x.camount, x.unit_price, p_decimal.tp);
  920. x.s_tp = helper.mul(x.samount, x.unit_price, p_decimal.tp);
  921. x.sp_tp = helper.mul(x.spamount, x.unit_price, p_decimal.tp);
  922. const auditAmount = x.audit_amount ? x.audit_amount.split(',') : [];
  923. for (const [i, aa] of auditAmount.entries()) {
  924. const amountField = 'qty_' + (i+1), tpField = 'tp_' + (i+1);
  925. x[amountField] = aa ? parseFloat(aa) : 0;
  926. x[tpField] = helper.mul(x[amountField], x.unit_price, p_decimal.tp);
  927. if (plan) {
  928. plan[tpField] = helper.add(plan[tpField], x[tpField]);
  929. }
  930. }
  931. });
  932. bills.sort(function(a, b ) {
  933. const aCIndex = data.findIndex(function (c) {
  934. return c.id === a.cpid;
  935. });
  936. const bCIndex = data.findIndex(function (c) {
  937. return c.id === b.cpid;
  938. });
  939. return aCIndex === bCIndex
  940. ? helper.compareCode(a.code, b.code)
  941. : aCIndex - bCIndex;
  942. });
  943. this.changePlanData = { data, bills };
  944. }
  945. async _generateChangePlanAudit() {
  946. if (!!this.changePlanData.audit) return;
  947. this.changePlanData.audit = [];
  948. for (const c of this.changePlanData.data) {
  949. const changeAudit = await this.ctx.service.changePlanAudit.getAllDataByCondition({ where: { cpid: c.id, times: c.times }});
  950. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  951. this.changePlanData.audit.push(...changeAuditFilter);
  952. }
  953. }
  954. async getChangePlanData(tid, sid, fields) {
  955. try {
  956. await this._generateChangePlan(tid);
  957. return this.changePlanData.data;
  958. } catch (err) {
  959. return [];
  960. }
  961. }
  962. async getChangePlanBillsData(tid, sid, fields) {
  963. try {
  964. await this._generateChangePlan(tid);
  965. return this.changePlanData.bills;
  966. } catch (err) {
  967. return [];
  968. }
  969. }
  970. async getChangePlanAuditData(tid, sid, fields) {
  971. try {
  972. await this._generateChangePlan(tid);
  973. await this._generateChangePlanAudit();
  974. return this.changePlanData.audit;
  975. } catch (err) {
  976. this.ctx.log(err);
  977. return [];
  978. }
  979. }
  980. async _generateChangeProject(tid) {
  981. if (!!this.changeProjectData) return;
  982. const where = { tid };
  983. if (this.ctx.session.sessionProject.page_show.isOnlyChecked) where.status = audit.changeProject.status.checked;
  984. this.changeProjectData = { data: await this.ctx.service.changeProject.getAllDataByCondition({ where }) };
  985. }
  986. async _generateChangeProjectAudit() {
  987. if (!!this.changeProjectData.audit) return;
  988. this.changeProjectData.audit = [];
  989. for (const c of this.changeProjectData.data) {
  990. const changeAudit = await this.ctx.service.changeProjectAudit.getAllDataByCondition({ where: { cpid: c.id, times: c.times }});
  991. const changeAuditFilter = this.ctx.helper.filterLastestData(changeAudit, ['aid']);
  992. this.changeProjectData.audit.push(...changeAuditFilter);
  993. }
  994. }
  995. async getChangeProjectData(tid, sid, fields) {
  996. try {
  997. await this._generateChangeProject(tid);
  998. return this.changeProjectData.data;
  999. } catch (err) {
  1000. this.ctx.log(err);
  1001. return [];
  1002. }
  1003. }
  1004. async getChangeProjectAuditData(tid, sid, fields) {
  1005. try {
  1006. await this._generateChangeProject(tid);
  1007. await this._generateChangeProjectAudit();
  1008. return this.changeProjectData.audit;
  1009. } catch (err) {
  1010. return [];
  1011. }
  1012. }
  1013. async getStageJgcl(tid, sid, fields) {
  1014. try {
  1015. await this.ctx.service.tender.checkTender(tid);
  1016. await this.ctx.service.stage.checkStage(sid);
  1017. const data = await this.ctx.service.stageJgcl.getStageData(this.ctx.stage);
  1018. const preData = await this.ctx.service.stageJgcl.getPreStageData(this.ctx.stage.order);
  1019. for (const d of data) {
  1020. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1021. if (pd) {
  1022. d.pre_arrive_qty = pd.arrive_qty;
  1023. d.pre_arrive_tp = pd.arrive_tp;
  1024. d.pre_deduct_qty = pd.deduct_qty;
  1025. d.pre_deduct_tp = pd.deduct_tp;
  1026. }
  1027. d.end_arrive_qty = this.ctx.helper.add(d.pre_arrive_qty, d.arrive_qty);
  1028. d.end_arrive_tp = this.ctx.helper.add(d.pre_arrive_tp, d.arrive_tp);
  1029. d.end_deduct_qty = this.ctx.helper.add(d.pre_deduct_qty, d.deduct_qty);
  1030. d.end_deduct_tp = this.ctx.helper.add(d.pre_deduct_tp, d.deduct_tp);
  1031. }
  1032. return data;
  1033. } catch (err) {
  1034. return [];
  1035. }
  1036. }
  1037. async getStageBonus(tid, sid, fields) {
  1038. try {
  1039. await this.ctx.service.tender.checkTender(tid);
  1040. await this.ctx.service.stage.checkStage(sid);
  1041. const data = await this.ctx.service.stageBonus.getEndStageData(this.ctx.stage.order);
  1042. for (const d of data) {
  1043. const names = this.ctx.helper._.map(d.proof_file, function (x) {
  1044. return x.filename + x.fileext;
  1045. });
  1046. d.proof = names.join('\n');
  1047. }
  1048. return data;
  1049. } catch (err) {
  1050. return [];
  1051. }
  1052. }
  1053. async getStageOther(tid, sid, fields) {
  1054. try {
  1055. await this.ctx.service.tender.checkTender(tid);
  1056. await this.ctx.service.stage.checkStage(sid);
  1057. const data = await this.ctx.service.stageOther.getStageData(this.ctx.stage);
  1058. const preData = await this.ctx.service.stageOther.getPreStageData(this.ctx.stage.order);
  1059. for (const d of data) {
  1060. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1061. if (pd) {
  1062. d.pre_tp = pd.tp;
  1063. }
  1064. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1065. }
  1066. return data;
  1067. } catch (err) {
  1068. return [];
  1069. }
  1070. }
  1071. async getStageSafeProd(tid, sid, fields) {
  1072. try {
  1073. await this.ctx.service.tender.checkTender(tid);
  1074. await this.ctx.service.stage.checkStage(sid);
  1075. const data = await this.ctx.service.stageSafeProd.getStageData(this.ctx.stage);
  1076. const preData = await this.ctx.service.stageSafeProd.getPreStageData(this.ctx.stage.order);
  1077. for (const d of data) {
  1078. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1079. if (pd) {
  1080. d.pre_qty = pd.qty;
  1081. d.pre_tp = pd.tp;
  1082. }
  1083. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  1084. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1085. }
  1086. return data;
  1087. } catch (err) {
  1088. return [];
  1089. }
  1090. }
  1091. async getStageTempLand(tid, sid, fields) {
  1092. try {
  1093. await this.ctx.service.tender.checkTender(tid);
  1094. await this.ctx.service.stage.checkStage(sid);
  1095. const data = await this.ctx.service.stageTempLand.getStageData(this.ctx.stage);
  1096. const preData = await this.ctx.service.stageTempLand.getPreStageData(this.ctx.stage.order);
  1097. for (const d of data) {
  1098. const pd = this.ctx.helper._.find(preData, {uuid: d.uuid});
  1099. if (pd) {
  1100. d.pre_qty = pd.qty;
  1101. d.pre_tp = pd.tp;
  1102. }
  1103. d.end_qty = this.ctx.helper.add(d.pre_qty, d.qty);
  1104. d.end_tp = this.ctx.helper.add(d.pre_tp, d.tp);
  1105. }
  1106. return data;
  1107. } catch (err) {
  1108. return [];
  1109. }
  1110. }
  1111. async getSumStageBillsData(tid, sid, fields) {
  1112. try {
  1113. await this.ctx.service.tender.checkTender(tid);
  1114. const billsData = await this.ctx.service.ledger.getData(this.ctx.tender.id);
  1115. const checkStageField = function (stageOrder) {
  1116. for (const f of fields) {
  1117. if (f.indexOf('s' + stageOrder + '_') >= 0) {
  1118. return true;
  1119. }
  1120. }
  1121. return false;
  1122. };
  1123. const calcFields = ['deal_tp', 'total_price'], calcPrefix = [];
  1124. const stages = this.ctx.service.stage.getValidStages(this.ctx.tender.id);
  1125. for (const stage of stages) {
  1126. if (!checkStageField(stage.order)) return;
  1127. await this.ctx.service.stage.doCheckStage(stage);
  1128. calcFields.push('s' + stage.order + '_contract_tp');
  1129. calcFields.push('s' + stage.order + '_qc_tp');
  1130. calcFields.push('s' + stage.order + '_gather_tp');
  1131. calcFields.push('s' + stage.order + '_');
  1132. const curStage = stage.readOnly
  1133. ? await this.ctx.service.stageBills.getAuditorStageData2(this.ctx.tender.id, stage.id, stage.curTimes, stage.curOrder)
  1134. : await this.ctx.service.stageBills.getLastestStageData2(this.ctx.tender.id, stage.id);
  1135. this.ctx.helper.assignRelaData(billsData, [
  1136. {data: curStage, fields: ['contract_qty', 'contract_tp', 'contract_expr', 'qc_qty', 'qc_tp'], prefix: 's' + stage.order + '_', relaId: 'lid'}
  1137. ]);
  1138. }
  1139. const billsTree = new Ledger.billsTree(this.ctx, {
  1140. id: 'ledger_id',
  1141. pid: 'ledger_pid',
  1142. order: 'order',
  1143. level: 'level',
  1144. rootId: -1,
  1145. keys: ['id', 'tender_id', 'ledger_id'],
  1146. stageId: 'id',
  1147. calcFields: calcFields,
  1148. calc: function (node) {
  1149. for (const prefix of calcPrefix) {
  1150. if (node.children && node.children.length === 0) {
  1151. node[prefix + 'gather_qty'] = self.ctx.helper.add(node[prefix + 'contract_qty'], node[prefix + 'qc_qty']);
  1152. }
  1153. node[prefix + 'gather_tp'] = self.ctx.helper.add(node[prefix + 'contract_tp'], node[prefix + 'qc_tp']);
  1154. }
  1155. }
  1156. });
  1157. billsTree.loadDatas(billsData);
  1158. billsTree.calculateAll();
  1159. return billsTree.getDefaultDatas();
  1160. } catch (err) {
  1161. return [];
  1162. }
  1163. }
  1164. async getStageAuditors(tid, sid) {
  1165. await this.ctx.service.tender.checkTender(tid);
  1166. await this.ctx.service.stage.checkStage(sid);
  1167. const auditors = await this.ctx.service.stageAudit.getFinalAuditGroup(this.ctx.stage.id, this.ctx.stage.curTimes);
  1168. const user = await this.ctx.service.projectAccount.getDataById(this.ctx.stage.user_id);
  1169. const result = [{
  1170. aid: user.id,
  1171. name: user.name,
  1172. company: user.company,
  1173. role: user.role,
  1174. mobile: user.mobile,
  1175. telephone: user.telephone,
  1176. sign_path: user.sign_path,
  1177. opinion: user.opinion,
  1178. end_time: auditors && auditors.length > 0 ? auditors[0].begin_time : null,
  1179. sort: 0,
  1180. }, ...auditors];
  1181. return result;
  1182. }
  1183. async getSignSelect(tid, sid, customSelect) {
  1184. await this.ctx.service.tender.checkTender(tid);
  1185. await this.ctx.service.stage.checkStage(sid);
  1186. const signSelect = customSelect.sign_select, result = {};
  1187. for (const [i, ss] of signSelect.entries()) {
  1188. const user = await this.ctx.service.projectAccount.getDataById(ss.id);
  1189. const sign = {
  1190. id: ss.id, name: user.name, company: user.company, role: user.role,
  1191. mobile: user.mobile, telephone: user.telephone,
  1192. };
  1193. if (ss.id !== this.ctx.stage.user_id) {
  1194. const audit = this.ctx.stage.auditors.find(x => {return x.aid === ss.id});
  1195. user.end_time = audit ? audit.end_time : ss.audit_time;
  1196. } else {
  1197. user.end_time = this.ctx.stage.auditors[0].end_time;
  1198. }
  1199. if (user.end_time) sign.sign_path = user.sign_path;
  1200. result['sign' + (i+1)] = sign;
  1201. }
  1202. return result;
  1203. }
  1204. async getChangeInfo(tid, sid) {
  1205. await this.ctx.service.tender.checkTender(tid);
  1206. await this.ctx.service.stage.checkStage(sid);
  1207. this.changeInfo = await this.ctx.service.stageChange.getChangeWithUsedInfo(this.ctx.stage);
  1208. const usedChangesId = await this.ctx.service.stageChange.getStageUsedChangeId(sid);
  1209. for (const c of this.changeInfo) {
  1210. c.cur_used = usedChangesId.indexOf(c.cid) >= 0;
  1211. c.used_ratio = c.used_pt;
  1212. c.is_import = 0;
  1213. }
  1214. return this.changeInfo;
  1215. }
  1216. async getChangeInfoBills(tid, sid) {
  1217. if (!this.changeInfo) await this.getChangeInfo(tid, sid);
  1218. this.changeInfoBills = [];
  1219. for (const c of this.changeInfo) {
  1220. const cb = await this.ctx.service.changeAuditList.getAllDataByCondition({ where: { cid: c.cid } });
  1221. const cbu = await this.ctx.service.stageChange.getUsedData(tid, c.cid);
  1222. const curUsedBills = await this.ctx.service.stageChange.getStageUsedData(sid, c.cid);
  1223. for (const b of cb) {
  1224. b.qty = this.ctx.helper._.toNumber(b.samount);
  1225. b.tp = this.ctx.helper.round(this.ctx.helper.mul(b.qty, b.unit_price), this.ctx.tender.info.decimal.tp);
  1226. const u = cbu.filter(x => { return x.cbid === b.id; });
  1227. b.used_qty = u.length > 0 ? this.ctx.helper.sum(u.map(x => { return x.qty})) : 0;
  1228. b.valid_qty = this.ctx.helper.sub(b.qty, b.used_qty);
  1229. const cur = this.ctx.helper._.filter(curUsedBills, { cbid: b.id });
  1230. b.cur_qty = 0;
  1231. for (const cc of cur) {
  1232. b.cur_qty = this.ctx.helper.add(b.cur_qty, cc.qty);
  1233. }
  1234. b.cur_used = !!b.cur_qty;
  1235. this.changeInfoBills.push(b);
  1236. }
  1237. }
  1238. return this.changeInfoBills;
  1239. }
  1240. }
  1241. return ReportMemory;
  1242. };