stage.js 17 KB

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