stage.js 22 KB

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