report_memory.js 85 KB

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