report_memory.js 85 KB

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