report_memory.js 70 KB

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