report_memory.js 68 KB

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