report_memory.js 75 KB

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