stage.js 24 KB

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