report_memory.js 62 KB

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