report_memory.js 68 KB

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