report_memory.js 63 KB

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