report_memory.js 85 KB

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