report_memory.js 70 KB

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