report_memory.js 68 KB

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