stage.js 21 KB

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