stage.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. 'use strict';
  2. /**
  3. * 期计量 数据模型
  4. *
  5. * @author Mai
  6. * @date 2018/8/13
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').stage;
  10. const payConst = require('../const/deal_pay.js');
  11. const fs = require('fs');
  12. const path = require('path');
  13. const _ = require('lodash');
  14. module.exports = app => {
  15. class Stage extends app.BaseService {
  16. /**
  17. * 构造函数
  18. *
  19. * @param {Object} ctx - egg全局变量
  20. * @return {void}
  21. */
  22. constructor(ctx) {
  23. super(ctx);
  24. this.tableName = 'stage';
  25. }
  26. async checkStage(sid) {
  27. if (!this.ctx.stage) {
  28. const status = auditConst.status;
  29. const stage = await this.ctx.service.stage.getDataById(sid);
  30. stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);
  31. stage.curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);
  32. const accountId = this.ctx.session.sessionUser.accountId, auditorIds = this._.map(stage.auditors, 'aid'), shareIds = [];
  33. if (accountId === stage.user_id) { // 原报
  34. if (stage.curAuditor) {
  35. stage.readOnly = stage.curAuditor.aid !== accountId;
  36. } else {
  37. stage.readOnly = stage.status !== status.uncheck && stage.status !== status.checkNo;
  38. }
  39. stage.curTimes = stage.times;
  40. if (stage.status === status.uncheck || stage.status === status.checkNo) {
  41. stage.curOrder = 0;
  42. } else if (stage.status === status.checked) {
  43. stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));
  44. } else {
  45. stage.curOrder = stage.curAuditor.aid === accountId ? stage.curAuditor.order : stage.curAuditor.order - 1;
  46. }
  47. } else if (auditorIds.indexOf(accountId) !== -1) { // 审批人
  48. if (stage.status === status.uncheck) {
  49. throw '您无权查看该数据';
  50. }
  51. stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
  52. if (stage.status === status.checked) {
  53. stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));
  54. } else if (stage.status === status.checkNo) {
  55. const audit = await this.service.stageAudit.getDataByCondition({
  56. sid: stage.id, times: stage.times - 1, status: status.checkNo
  57. });
  58. stage.curOrder = audit.order;
  59. } else {
  60. stage.curOrder = accountId === stage.curAuditor.aid ? stage.curAuditor.order : stage.curAuditor.order - 1;
  61. }
  62. } else if (shareIds.indexOf(accountId) !== -1) { // 分享人
  63. if (stage.status === status.uncheck) {
  64. throw '您无权查看该数据';
  65. }
  66. stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
  67. stage.curOrder = stage.status === status.checked ? this._.max(this._.map(stage.auditors, 'order')) : stage.curAuditor.order - 1;
  68. }
  69. this.ctx.stage = stage;
  70. let time = this.ctx.stage.readOnly ? this.ctx.stage.cache_time_r : this.ctx.stage.cache_time_l;
  71. if (!time) {
  72. time = this.ctx.stage.in_time ? this.ctx.stage.in_time : new Date();
  73. }
  74. this.ctx.stage.cacheTime = time.getTime();//this.ctx.stage.readOnly ? (this.ctx.stage.cache_time_r).getTime(): (this.ctx.stage.cache_time_l).getTime();
  75. }
  76. }
  77. /**
  78. * 获取 最新一期 期计量
  79. * @param tenderId
  80. * @param includeUnCheck
  81. * @returns {Promise<*>}
  82. */
  83. async getLastestStage(tenderId, includeUnCheck = false) {
  84. this.initSqlBuilder();
  85. this.sqlBuilder.setAndWhere('tid', {
  86. value: tenderId,
  87. operate: '=',
  88. });
  89. if (!includeUnCheck) {
  90. this.sqlBuilder.setAndWhere('status', {
  91. value: auditConst.status.uncheck,
  92. operate: '!=',
  93. });
  94. }
  95. this.sqlBuilder.orderBy = [['order', 'desc']];
  96. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  97. const stage = await this.db.queryOne(sql, sqlParam);
  98. return stage;
  99. }
  100. /**
  101. * 获取 最新一期 审批完成的 期计量
  102. * @param tenderId
  103. * @returns {Promise<*>}
  104. */
  105. async getLastestCompleteStage(tenderId) {
  106. this.initSqlBuilder();
  107. this.sqlBuilder.setAndWhere('tid', {
  108. value: tenderId,
  109. operate: '=',
  110. });
  111. this.sqlBuilder.setAndWhere('status', {
  112. value: auditConst.status.checked,
  113. operate: '=',
  114. });
  115. this.sqlBuilder.orderBy = [['order', 'desc']];
  116. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  117. const stage = await this.db.queryOne(sql, sqlParam);
  118. return stage;
  119. }
  120. /**
  121. * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)
  122. * @param tenderId
  123. * @returns {Promise<void>}
  124. */
  125. async getValidStagesShort(tenderId) {
  126. const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';
  127. const sqlParam = [tenderId];
  128. return await this.db.query(sql, sqlParam);
  129. }
  130. /**
  131. * 获取某一期信息(报表用)
  132. * @param stageId
  133. * @returns {Promise<void>}
  134. */
  135. async getStageById(stageId) {
  136. const sql = 'select * from zh_stage where id = ? order by zh_stage.order';
  137. const sqlParam = [stageId];
  138. return await this.db.query(sql, sqlParam);
  139. }
  140. async checkStageGatherData(stage) {
  141. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  142. if (stage.status !== auditConst.status.checked && stage.check_calc) {
  143. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);
  144. const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : stage.user_id === this.ctx.session.sessionUser.accountId;
  145. stage.curTimes = stage.status === auditConst.status.checkNo ? stage.times - 1 : stage.times;
  146. stage.curOrder = curAuditor ? curAuditor.order : 0;
  147. if (isActive) {
  148. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  149. stage.contract_tp = tpData.contract_tp;
  150. stage.qc_tp = tpData.qc_tp;
  151. stage.yf_tp = await this.ctx.service.stagePay.getYfTotalPrice(stage);
  152. }
  153. }
  154. }
  155. /**
  156. * 获取标段下的全部计量期,按倒序
  157. * @param tenderId
  158. * @returns {Promise<void>}
  159. */
  160. async getValidStages(tenderId) {
  161. const stages = await this.db.select(this.tableName, {
  162. where: {tid: tenderId},
  163. orders: [['order', 'desc']],
  164. });
  165. for (const s of stages) {
  166. s.tp = this.ctx.helper.add(s.contract_tp, s.qc_tp);
  167. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  168. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  169. }
  170. if (stages.length !== 0) {
  171. const lastStage = stages[stages.length - 1];
  172. if (lastStage.status === auditConst.status.uncheck && lastStage.user_id !== this.ctx.session.sessionUser.accountId) {
  173. stages.splice(stages.length - 1, 1);
  174. }
  175. }
  176. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  177. if (stages.length > 0 && stages[0].status !== auditConst.status.checked) {
  178. const stage = stages[0];
  179. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);
  180. const isActive = curAuditor ? curAuditor.id === this.ctx.session.sessionUser.accountId : stage.user_id === this.ctx.session.sessionUser.accountId;
  181. if (isActive) {
  182. stage.curTimes = stage.times;
  183. stage.curOrder = curAuditor ? curAuditor.order : 0;
  184. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  185. stage.contract_tp = tpData.contract_tp;
  186. stage.qc_tp = tpData.qc_tp;
  187. stage.yf_tp = await this.ctx.service.stagePay.getYfTotalPrice(stage);
  188. stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp);
  189. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  190. }
  191. }
  192. return stages;
  193. }
  194. /**
  195. *
  196. * @param tenderId - 标段id
  197. * @param date - 计量年月
  198. * @param period - 开始-截止日期
  199. * @returns {Promise<void>}
  200. */
  201. async addStage(tenderId, date, period) {
  202. const stages = await this.getAllDataByCondition({
  203. where: {tid: tenderId},
  204. order: ['order'],
  205. });
  206. const preStage = stages[stages.length - 1];
  207. if (stages.length > 0 && stages[stages.length - 1].status !== auditConst.status.checked) {
  208. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  209. };
  210. const order = stages.length + 1;
  211. const newStage = {
  212. sid: this.uuid.v4(),
  213. tid: tenderId,
  214. order: order,
  215. in_time: new Date(),
  216. s_time: date,
  217. period: period,
  218. times: 1,
  219. status: auditConst.status.uncheck,
  220. user_id: this.ctx.session.sessionUser.accountId,
  221. check_calc: false,
  222. };
  223. newStage.cache_time_l = newStage.in_time;
  224. newStage.cache_time_r = newStage.in_time;
  225. if (preStage) {
  226. newStage.im_type = preStage.im_type;
  227. newStage.im_pre = preStage.im_pre;
  228. newStage.im_gather = preStage.im_gather;
  229. newStage.im_gather_node = preStage.im_gather_node;
  230. newStage.pre_contract_tp = this.ctx.helper.add(preStage.pre_contract_tp, preStage.contract_tp);
  231. newStage.pre_qc_tp = this.ctx.helper.add(preStage.pre_qc_tp, preStage.qc_tp);
  232. newStage.pre_yf_tp = this.ctx.helper.add(preStage.pre_yf_tp, preStage.yf_tp);
  233. }
  234. const transaction = await this.db.beginTransaction();
  235. try {
  236. // 新增期记录
  237. const result = await transaction.insert(this.tableName, newStage);
  238. if (result.affectedRows === 1) {
  239. newStage.id = result.insertId;
  240. } else {
  241. throw '新增期数据失败';
  242. }
  243. // 存在上一期时,复制上一期审批流程
  244. if (preStage) {
  245. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  246. if (!auditResult) {
  247. throw '复制上一期审批流程失败';
  248. }
  249. }
  250. // 新增期合同支付数据
  251. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  252. if (!dealResult) {
  253. throw '新增期合同支付数据失败';
  254. }
  255. await transaction.commit();
  256. return newStage;
  257. } catch (err) {
  258. await transaction.rollback();
  259. throw err;
  260. }
  261. }
  262. /**
  263. * 编辑计量期
  264. *
  265. * @param {Number} tenderId - 标段Id
  266. * @param {Number} order - 第N期
  267. * @param {String} date - 计量年月
  268. * @param {String} period - 开始-截止时间
  269. * @returns {Promise<void>}
  270. */
  271. async saveStage(tenderId, order, date, period) {
  272. await this.db.update(this.tableName, {
  273. s_time: date,
  274. period: period,
  275. }, { where: { tid: tenderId, order: order } });
  276. }
  277. /**
  278. * 设置 中间计量 生成规则,并生成数据
  279. * @param {Number} tenderId - 标段id
  280. * @param {Number} order - 期序号
  281. * @param {Number} data - 中间计量生成规则
  282. * @returns {Promise<void>}
  283. */
  284. async buildDetailData(tenderId, order, data) {
  285. const conn = await this.db.beginTransaction();
  286. try {
  287. await conn.update(this.tableName, { im_type: data.im_type, im_pre: data.im_pre }, { where: { tid: tenderId, order: order } });
  288. // to do 生成中间计量数据
  289. await conn.commit();
  290. } catch (err) {
  291. await conn.rollback();
  292. throw err;
  293. }
  294. }
  295. /**
  296. * 获取 当期的 计算基数
  297. * @returns {Promise<any>}
  298. */
  299. async getStagePayCalcBase(stage, tenderInfo) {
  300. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  301. const param = tenderInfo.deal_param;
  302. for (const cb of calcBase) {
  303. switch (cb.code) {
  304. case 'htj':
  305. cb.value = param.contractPrice;
  306. break;
  307. case 'zlje':
  308. cb.value = param.zanLiePrice;
  309. break;
  310. case 'htjszl':
  311. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  312. break;
  313. case 'kgyfk':
  314. cb.value = param.startAdvance;
  315. break;
  316. case 'clyfk':
  317. cb.value = param.materialAdvance;
  318. break;
  319. case 'bqwc':
  320. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  321. cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp);
  322. break;
  323. case 'ybbqwc':
  324. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^1[0-9]{2}-');
  325. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  326. break;
  327. default:
  328. cb.value = 0;
  329. }
  330. }
  331. return calcBase;
  332. }
  333. async updateCheckCalcFlag(sid, check) {
  334. const result = await this.db.update(this.tableName, {id: sid, check_calc: check});
  335. return result.affectedRows === 1;
  336. }
  337. async updateCacheTime(sid) {
  338. const result = await this.db.update(this.tableName, {id: sid, cache_time_l: new Date()});
  339. return result.affectedRows === 1;
  340. }
  341. /**
  342. * 删除计量期
  343. *
  344. * @param {Number} id - 期Id
  345. * @returns {Promise<void>}
  346. */
  347. async deleteStage(id) {
  348. const transaction = await this.db.beginTransaction();
  349. try {
  350. await transaction.delete(this.tableName, { id });
  351. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  352. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  353. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  354. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  355. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  356. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  357. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  358. // 删除计量合同支付附件
  359. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  360. if (payList) {
  361. for (const pt of payList) {
  362. if (pt.attachment !== null && pt.attachment !== '') {
  363. const payAttList = JSON.parse(pt.attachment);
  364. for (const pat of payAttList) {
  365. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  366. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  367. }
  368. }
  369. }
  370. }
  371. }
  372. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  373. await transaction.delete(this.ctx.service.pay.tableName, { csid: id });
  374. // 删除计量附件文件
  375. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { sid: id } });
  376. if (attList.length !== 0) {
  377. for (const att of attList) {
  378. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  379. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  380. }
  381. }
  382. }
  383. await transaction.delete(this.ctx.service.stageAtt.tableName, { sid: id });
  384. await transaction.commit();
  385. return true;
  386. } catch (err) {
  387. await transaction.rollback();
  388. throw err;
  389. }
  390. }
  391. /**
  392. * 获取 多期的 计算基数 -(材料调差调用)
  393. * @returns {Promise<any>}
  394. */
  395. async getMaterialCalcBase(stage_list, tenderInfo) {
  396. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  397. const param = tenderInfo.deal_param;
  398. for (const cb of calcBase) {
  399. switch (cb.code) {
  400. case 'htj':
  401. cb.value = param.contractPrice;
  402. break;
  403. case 'zlje':
  404. cb.value = param.zanLiePrice;
  405. break;
  406. case 'htjszl':
  407. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  408. break;
  409. case 'kgyfk':
  410. cb.value = param.startAdvance;
  411. break;
  412. case 'clyfk':
  413. cb.value = param.materialAdvance;
  414. break;
  415. case 'bqwc':
  416. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  417. cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp);
  418. break;
  419. case 'ybbqwc':
  420. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^1[0-9]{2}-');
  421. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  422. break;
  423. default:
  424. cb.value = 0;
  425. }
  426. }
  427. return calcBase;
  428. }
  429. /**
  430. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  431. * @param stage_id_list
  432. * @returns {Promise<void>}
  433. */
  434. async getStageMsgByStageId(stage_id_list) {
  435. const list = [];
  436. stage_id_list = stage_id_list.split(',');
  437. for (const sid of stage_id_list) {
  438. const stage = await this.getDataById(sid);
  439. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  440. stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  441. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  442. stage.curTimes = stage.times;
  443. list.push(stage);
  444. }
  445. return list;
  446. }
  447. }
  448. return Stage;
  449. };