report_memory.js 61 KB

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