stage.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. const projectLogConst = require('../const/project_log');
  16. const syncApiConst = require('../const/sync_api');
  17. const RevisePrice = require('../lib/revise_price');
  18. module.exports = app => {
  19. class Stage extends app.BaseService {
  20. /**
  21. * 构造函数
  22. *
  23. * @param {Object} ctx - egg全局变量
  24. * @return {void}
  25. */
  26. constructor(ctx) {
  27. super(ctx);
  28. this.tableName = 'stage';
  29. }
  30. /**
  31. * 根据id查找数据
  32. *
  33. * @param {Number} id - 数据库中的id
  34. * @return {Object} - 返回单条数据
  35. */
  36. async getDataById(id) {
  37. const result = await this.db.get(this.tableName, { id });
  38. if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }
  39. return result;
  40. }
  41. /**
  42. * 根据条件查找单条数据
  43. *
  44. * @param {Object} condition - 筛选条件
  45. * @return {Object} - 返回单条数据
  46. */
  47. async getDataByCondition(condition) {
  48. const result = await this.db.get(this.tableName, condition);
  49. if (result) { result.tp_history = result.tp_history ? JSON.parse(result.tp_history) : []; }
  50. return result;
  51. }
  52. /**
  53. * 根据条件查找列表数据
  54. *
  55. * @param {Object} condition - 筛选条件
  56. * @return {Array} - 返回数据
  57. */
  58. async getAllDataByCondition(condition) {
  59. const result = await this.db.select(this.tableName, condition);
  60. for (const r of result) {
  61. r.tp_history = r.tp_history ? JSON.parse(r.tp_history) : [];
  62. }
  63. return result;
  64. }
  65. async doCheckStage(stage, force = false) {
  66. const status = auditConst.status;
  67. stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);
  68. stage.curAuditor = await this.ctx.service.stageAudit.getCurAuditor(stage.id, stage.times);
  69. const accountId = this.ctx.session.sessionUser.accountId,
  70. auditorIds = this._.map(stage.auditors, 'aid'),
  71. shareIds = [];
  72. const isTenderTourist = await this.service.tenderTourist.getDataByCondition({ tid: stage.tid, user_id: accountId });
  73. const permission = this.ctx.session.sessionUser.permission;
  74. if (accountId === stage.user_id) { // 原报
  75. if (stage.curAuditor) {
  76. stage.readOnly = stage.curAuditor.aid !== accountId;
  77. } else {
  78. stage.readOnly = stage.status !== status.uncheck && stage.status !== status.checkNo;
  79. }
  80. stage.curTimes = stage.times;
  81. if (stage.status === status.uncheck || stage.status === status.checkNo) {
  82. stage.curOrder = 0;
  83. } else if (stage.status === status.checked) {
  84. stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));
  85. } else {
  86. stage.curOrder = stage.curAuditor.aid === accountId ? stage.curAuditor.order : stage.curAuditor.order - 1;
  87. }
  88. } else if (!!isTenderTourist || force) { // 游客
  89. stage.readOnly = true;
  90. stage.curTimes = stage.times;
  91. if (stage.status === status.uncheck || stage.status === status.checkNo) {
  92. stage.curOrder = 0;
  93. } else if (stage.status === status.checked) {
  94. stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));
  95. } else {
  96. stage.curOrder = stage.curAuditor.order;
  97. }
  98. } else if (auditorIds.indexOf(accountId) !== -1) { // 审批人
  99. if (stage.status === status.uncheck) {
  100. throw '您无权查看该数据';
  101. }
  102. stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
  103. if (stage.status === status.checked) {
  104. stage.curOrder = this._.max(this._.map(stage.auditors, 'order'));
  105. } else if (stage.status === status.checkNo) {
  106. const audit = await this.service.stageAudit.getDataByCondition({
  107. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  108. });
  109. stage.curOrder = audit.order;
  110. } else {
  111. stage.curOrder = accountId === stage.curAuditor.aid ? stage.curAuditor.order : stage.curAuditor.order - 1;
  112. }
  113. stage.readOnly = (stage.status !== status.checking && stage.status !== status.checkNoPre) || accountId !== stage.curAuditor.aid;
  114. } else if (shareIds.indexOf(accountId) !== -1 || (permission !== null && permission.tender !== undefined && permission.tender.indexOf('2') !== -1)) { // 分享人
  115. if (stage.status === status.uncheck) {
  116. throw '您无权查看该数据';
  117. }
  118. stage.readOnly = true;
  119. stage.curTimes = stage.status === status.checkNo ? stage.times - 1 : stage.times;
  120. if (stage.status === status.checkNo) {
  121. const audit = await this.service.stageAudit.getDataByCondition({
  122. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  123. });
  124. stage.curOrder = audit.order;
  125. } else {
  126. stage.curOrder = stage.status === status.checked ? this._.max(this._.map(stage.auditors, 'order')) : stage.curAuditor.order - 1;
  127. }
  128. }
  129. let time = stage.readOnly ? stage.cache_time_r : stage.cache_time_l;
  130. if (!time) time = stage.in_time ? stage.in_time : new Date();
  131. stage.cacheTime = time.getTime();
  132. return stage;
  133. }
  134. async checkStage(sid) {
  135. if (!this.ctx.stage) {
  136. const stage = await this.ctx.service.stage.getDataById(sid);
  137. if (!stage) throw '校验的期数据不存在';
  138. await this.doCheckStage(stage);
  139. this.ctx.stage = stage;
  140. }
  141. }
  142. /**
  143. * 获取 最新一期 期计量
  144. * @param tenderId
  145. * @param includeUnCheck
  146. * @return {Promise<*>}
  147. */
  148. async getLastestStage(tenderId, includeUnCheck = false) {
  149. this.initSqlBuilder();
  150. this.sqlBuilder.setAndWhere('tid', {
  151. value: tenderId,
  152. operate: '=',
  153. });
  154. if (!includeUnCheck) {
  155. this.sqlBuilder.setAndWhere('status', {
  156. value: auditConst.status.uncheck,
  157. operate: '!=',
  158. });
  159. }
  160. this.sqlBuilder.orderBy = [['order', 'desc']];
  161. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  162. const stage = await this.db.queryOne(sql, sqlParam);
  163. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  164. return stage;
  165. }
  166. /**
  167. * 获取 最新一期 审批完成的 期计量
  168. * @param tenderId
  169. * @return {Promise<*>}
  170. */
  171. async getLastestCompleteStage(tenderId) {
  172. this.initSqlBuilder();
  173. this.sqlBuilder.setAndWhere('tid', {
  174. value: tenderId,
  175. operate: '=',
  176. });
  177. this.sqlBuilder.setAndWhere('status', {
  178. value: auditConst.status.checked,
  179. operate: '=',
  180. });
  181. this.sqlBuilder.orderBy = [['order', 'desc']];
  182. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  183. const stage = await this.db.queryOne(sql, sqlParam);
  184. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  185. return stage;
  186. }
  187. /**
  188. * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)
  189. * @param tenderId
  190. * @return {Promise<void>}
  191. */
  192. async getValidStagesShort(tenderId) {
  193. const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';
  194. const sqlParam = [tenderId];
  195. return await this.db.query(sql, sqlParam);
  196. }
  197. /**
  198. * 获取某一期信息(报表用)
  199. * @param stageId
  200. * @return {Promise<void>}
  201. */
  202. async getStageById(stageId) {
  203. const sql = 'select * from zh_stage where id = ? order by zh_stage.order';
  204. const sqlParam = [stageId];
  205. return await this.db.query(sql, sqlParam);
  206. }
  207. async checkStageGatherData(stage, force = false) {
  208. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  209. if (stage.status !== auditConst.status.checked) {
  210. await this.doCheckStage(stage, force);
  211. if (!stage.readOnly && stage.check_calc) {
  212. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  213. stage.contract_tp = tpData.contract_tp;
  214. stage.qc_tp = tpData.qc_tp;
  215. stage.tp =this.ctx.helper.add(stage.contract_tp, stage.qc_tp);
  216. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  217. stage.yf_tp = tp.yf;
  218. stage.sf_tp = tp.sf;
  219. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  220. await this.update({
  221. check_calc: false,
  222. contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,
  223. yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,
  224. }, { id: stage.id });
  225. } else if (stage.tp_history) {
  226. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  227. if (his) {
  228. stage.contract_tp = his.contract_tp;
  229. stage.qc_tp = his.qc_tp;
  230. stage.yf_tp = his.yf_tp;
  231. stage.sf_tp = his.sf_tp;
  232. stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp);
  233. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. * 获取标段下的全部计量期,按倒序
  240. * @param tenderId
  241. * @return {Promise<void>}
  242. */
  243. async getValidStages(tenderId) {
  244. const stages = await this.db.select(this.tableName, {
  245. where: { tid: tenderId },
  246. orders: [['order', 'desc']],
  247. });
  248. for (const s of stages) {
  249. s.tp = this.ctx.helper.add(s.contract_tp, s.qc_tp);
  250. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  251. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  252. s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];
  253. }
  254. if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {
  255. const lastStage = stages[0];
  256. if (lastStage.status === auditConst.status.uncheck && lastStage.user_id !== this.ctx.session.sessionUser.accountId && !this.ctx.tender.isTourist) {
  257. stages.splice(0, 1);
  258. }
  259. }
  260. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  261. if (stages.length === 0) return stages;
  262. await this.checkStageGatherData(stages[0], true);
  263. for (const s of stages) {
  264. if (s.yf_tp && s.sf_tp === 0) {
  265. const sf = await this.ctx.service.stagePay.getHistorySf(s);
  266. if (sf && s.readOnly) {
  267. await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });
  268. }
  269. s.sf_tp = sf.tp;
  270. }
  271. }
  272. return stages;
  273. }
  274. async _getSumTp(condition, ...field) {
  275. const fieldSql = [];
  276. for (const f of field) {
  277. fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');
  278. }
  279. const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);
  280. return await this.db.queryOne(sql);
  281. }
  282. /**
  283. *
  284. * @param tenderId - 标段id
  285. * @param date - 计量年月
  286. * @param period - 开始-截止日期
  287. * @return {Promise<void>}
  288. */
  289. async addStage(tenderId, date, period) {
  290. const stages = await this.getAllDataByCondition({
  291. where: { tid: tenderId },
  292. order: ['order'],
  293. });
  294. const preStage = stages[stages.length - 1];
  295. if (stages.length > 0 && stages[stages.length - 1].status !== auditConst.status.checked) {
  296. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  297. }
  298. const order = stages.length + 1;
  299. const newStage = {
  300. sid: this.uuid.v4(),
  301. tid: tenderId,
  302. order,
  303. in_time: new Date(),
  304. s_time: date,
  305. period,
  306. times: 1,
  307. status: auditConst.status.uncheck,
  308. user_id: this.ctx.session.sessionUser.accountId,
  309. check_calc: false,
  310. };
  311. newStage.cache_time_l = newStage.in_time;
  312. newStage.cache_time_r = newStage.in_time;
  313. if (preStage) {
  314. newStage.im_type = preStage.im_type;
  315. newStage.im_pre = preStage.im_pre;
  316. newStage.im_gather = preStage.im_gather;
  317. newStage.im_gather_node = preStage.im_gather_node;
  318. newStage.pre_contract_tp = this.ctx.helper.add(preStage.pre_contract_tp, preStage.contract_tp);
  319. newStage.pre_qc_tp = this.ctx.helper.add(preStage.pre_qc_tp, preStage.qc_tp);
  320. newStage.pre_yf_tp = this.ctx.helper.add(preStage.pre_yf_tp, preStage.yf_tp);
  321. if (preStage.order === 1 || preStage.pre_sf_tp) {
  322. newStage.pre_sf_tp = this.ctx.helper.add(preStage.pre_sf_tp, preStage.sf_tp);
  323. } else {
  324. const sumTp = await this._getSumTp({tid: preStage.tid}, 'sf_tp');
  325. newStage.pre_sf_tp = sumTp.sf_tp || 0;
  326. }
  327. } else {
  328. const projFunRela = await this.ctx.service.project.getFunRela(this.ctx.session.sessionProject.id);
  329. newStage.im_type = projFunRela.imType;
  330. }
  331. const transaction = await this.db.beginTransaction();
  332. try {
  333. // 新增期记录
  334. const result = await transaction.insert(this.tableName, newStage);
  335. if (result.affectedRows === 1) {
  336. newStage.id = result.insertId;
  337. } else {
  338. throw '新增期数据失败';
  339. }
  340. // 存在上一期时,复制上一期审批流程
  341. if (preStage) {
  342. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  343. if (!auditResult) {
  344. throw '复制上一期审批流程失败';
  345. }
  346. }
  347. // 新增期合同支付数据
  348. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  349. if (!dealResult) {
  350. throw '新增期合同支付数据失败';
  351. }
  352. // 新增期其他台账数据
  353. if (preStage) {
  354. const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preStage, transaction);
  355. if (!jgclResult) throw '初始化甲供材料数据失败';
  356. const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preStage, transaction);
  357. if (!otherResult) throw '初始化其他台账数据失败';
  358. const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preStage, transaction);
  359. if (!safeResult) throw '初始化其他台账数据失败';
  360. const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preStage, transaction);
  361. if (!tempResult) throw '初始化其他台账数据失败';
  362. const priceCalc = new RevisePrice(this.ctx);
  363. await priceCalc.newStagePriceChange(newStage, preStage, transaction);
  364. }
  365. // 新增期拷贝报表相关配置/签名角色 等
  366. if (preStage) {
  367. const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);
  368. await this.ctx.service.roleRptRel.addInitialStageData(tenderId, newStage, preStage);
  369. }
  370. await transaction.commit();
  371. // 通知发送 - 第三方更新
  372. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  373. const base_data = {
  374. tid: tenderId,
  375. sid: result.insertId,
  376. op: 'insert',
  377. };
  378. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  379. // 存在上一期时
  380. base_data.op = preStage ? 'update' : 'insert';
  381. base_data.sid = -1;
  382. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  383. }
  384. return newStage;
  385. } catch (err) {
  386. await transaction.rollback();
  387. throw err;
  388. }
  389. }
  390. /**
  391. * 编辑计量期
  392. *
  393. * @param {Number} tenderId - 标段Id
  394. * @param {Number} order - 第N期
  395. * @param {String} date - 计量年月
  396. * @param {String} period - 开始-截止时间
  397. * @return {Promise<void>}
  398. */
  399. async saveStage(tenderId, order, date, period) {
  400. await this.db.update(this.tableName, {
  401. s_time: date,
  402. period,
  403. }, { where: { tid: tenderId, order } });
  404. }
  405. /**
  406. * 设置 中间计量 生成规则,并生成数据
  407. * @param {Number} tenderId - 标段id
  408. * @param {Number} order - 期序号
  409. * @param {Number} data - 中间计量生成规则
  410. * @return {Promise<void>}
  411. */
  412. async buildDetailData(tenderId, order, data) {
  413. const conn = await this.db.beginTransaction();
  414. try {
  415. await conn.update(this.tableName, { im_type: data.im_type, im_pre: data.im_pre , im_start_num: data.im_start_num }, { where: { tid: tenderId, order } });
  416. // to do 生成中间计量数据
  417. await conn.commit();
  418. } catch (err) {
  419. await conn.rollback();
  420. throw err;
  421. }
  422. }
  423. async getChangeSubtotal(stage) {
  424. const result = {};
  425. const bg = await this.ctx.service.stageChange.getSubtotal(stage);
  426. const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);
  427. result.common = this.ctx.helper.add(bg.common, importBg.common);
  428. result.great = this.ctx.helper.add(bg.great, importBg.great);
  429. result.more = this.ctx.helper.add(bg.more, importBg.more);
  430. return result;
  431. }
  432. /**
  433. * 获取 当期的 计算基数
  434. * @return {Promise<any>}
  435. */
  436. async getStagePayCalcBase(stage, tenderInfo) {
  437. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  438. const param = tenderInfo.deal_param;
  439. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  440. const bg = await this.getChangeSubtotal(stage);
  441. for (const cb of calcBase) {
  442. switch (cb.code) {
  443. case 'htj':
  444. cb.value = param.contractPrice;
  445. break;
  446. case 'zlje':
  447. cb.value = param.zanLiePrice;
  448. break;
  449. case 'htjszl':
  450. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  451. break;
  452. case 'kgyfk':
  453. cb.value = param.startAdvance;
  454. break;
  455. case 'clyfk':
  456. cb.value = param.materialAdvance;
  457. break;
  458. case 'bqwc':
  459. cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp);
  460. break;
  461. case 'bqht':
  462. cb.value = sum.contract_tp;
  463. break;
  464. case 'bqbg':
  465. cb.value = sum.qc_tp;
  466. break;
  467. case 'ybbqwc':
  468. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');
  469. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  470. break;
  471. case 'ybbqbg':
  472. cb.value = bg.common;
  473. break;
  474. case 'jdbqbg':
  475. cb.value = bg.more;
  476. break;
  477. case 'zdbqbg':
  478. cb.value = bg.great;
  479. break;
  480. default:
  481. cb.value = 0;
  482. }
  483. }
  484. return calcBase;
  485. }
  486. async updateCheckCalcFlag(stage, check) {
  487. const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check });
  488. return result.affectedRows === 1;
  489. }
  490. async updateCacheTime(sid) {
  491. const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });
  492. return result.affectedRows === 1;
  493. }
  494. /**
  495. * 删除计量期
  496. *
  497. * @param {Number} id - 期Id
  498. * @return {Promise<void>}
  499. */
  500. async deleteStage(id) {
  501. const transaction = await this.db.beginTransaction();
  502. try {
  503. const stageInfo = await this.getDataById(id);
  504. // 通知发送 - 第三方更新
  505. // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  506. // const base_data = {
  507. // tid: this.ctx.tender.id,
  508. // sid: id,
  509. // op: 'delete',
  510. // };
  511. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  512. // // 是否还存在其他期
  513. // base_data.op = stageInfo.order === 1 ? 'delete' : 'update';
  514. // base_data.sid = -1;
  515. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  516. // }
  517. await transaction.delete(this.tableName, { id });
  518. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });
  519. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  520. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  521. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  522. await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });
  523. await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });
  524. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  525. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  526. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  527. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  528. await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });
  529. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });
  530. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });
  531. await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });
  532. await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });
  533. // 删除计量合同支付附件
  534. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  535. if (payList) {
  536. for (const pt of payList) {
  537. if (pt.attachment !== null && pt.attachment !== '') {
  538. const payAttList = JSON.parse(pt.attachment);
  539. for (const pat of payAttList) {
  540. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  541. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  542. }
  543. }
  544. }
  545. }
  546. }
  547. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  548. await transaction.delete(this.ctx.service.pay.tableName, { csid: id });
  549. // 删除计量附件文件
  550. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });
  551. if (attList.length !== 0) {
  552. for (const att of attList) {
  553. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  554. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  555. }
  556. }
  557. }
  558. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });
  559. // 其他台账
  560. await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });
  561. const bonus = await this.ctx.service.stageBonus.getStageData(id);
  562. if (bonus && bonus.length > 0) {
  563. for (const b of bonus) {
  564. for (const f of b.proof_file) {
  565. if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {
  566. await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));
  567. }
  568. }
  569. }
  570. }
  571. await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });
  572. await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });
  573. // 同步删除进度里所选的期
  574. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });
  575. const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });
  576. if (detailAtt && detailAtt.length > 0) {
  577. for (const da of detailAtt) {
  578. da.attachment = da.attachment ? JSON.parse(da.attachment) : [];
  579. for (const daa of da.attachment) {
  580. if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {
  581. await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));
  582. }
  583. }
  584. }
  585. }
  586. await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });
  587. // 重算进度计量总金额
  588. await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);
  589. // 删除收方单及附件
  590. const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });
  591. if (shoufangAttList.length !== 0) {
  592. for (const att of shoufangAttList) {
  593. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  594. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  595. }
  596. }
  597. }
  598. await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });
  599. const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });
  600. if (shoufangList.length !== 0) {
  601. for (const att of shoufangList) {
  602. if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {
  603. await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));
  604. }
  605. }
  606. }
  607. await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });
  608. // 记录删除日志
  609. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');
  610. await transaction.commit();
  611. return true;
  612. } catch (err) {
  613. await transaction.rollback();
  614. throw err;
  615. }
  616. }
  617. /**
  618. * 获取 多期的 计算基数 -(材料调差调用)
  619. * @return {Promise<any>}
  620. */
  621. async getMaterialCalcBase(stage_list, tenderInfo) {
  622. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  623. const param = tenderInfo.deal_param;
  624. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  625. for (const cb of calcBase) {
  626. switch (cb.code) {
  627. case 'htj':
  628. cb.value = param.contractPrice;
  629. break;
  630. case 'zlje':
  631. cb.value = param.zanLiePrice;
  632. break;
  633. case 'htjszl':
  634. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  635. break;
  636. case 'kgyfk':
  637. cb.value = param.startAdvance;
  638. break;
  639. case 'clyfk':
  640. cb.value = param.materialAdvance;
  641. break;
  642. case 'bqwc':
  643. cb.value = this.ctx.helper.add(sum.contract_tp, sum.qc_tp);
  644. break;
  645. case 'bqht':
  646. cb.value = sum.contract_tp;
  647. break;
  648. case 'bqbg':
  649. cb.value = sum.qc_tp;
  650. break;
  651. case 'ybbqwc':
  652. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^[^0-9]*1[0-9]{2}(-|$)');
  653. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  654. break;
  655. case 'bqyf':
  656. cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);
  657. break;
  658. default:
  659. cb.value = 0;
  660. }
  661. }
  662. return calcBase;
  663. }
  664. /**
  665. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  666. * @param stage_id_list
  667. * @return {Promise<void>}
  668. */
  669. async getStageMsgByStageId(stage_id_list) {
  670. const list = [];
  671. stage_id_list = stage_id_list.toString().split(',');
  672. for (const sid of stage_id_list) {
  673. const stage = await this.getDataById(sid);
  674. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  675. stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  676. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  677. stage.curTimes = stage.times;
  678. list.push(stage);
  679. }
  680. return list;
  681. }
  682. async getStageByDataCollect(tenderId) {
  683. const stages = await this.db.select(this.tableName, {
  684. columns: ['s_time', 'contract_tp', 'qc_tp', 'pre_contract_tp', 'pre_qc_tp'],
  685. where: { tid: tenderId },
  686. orders: [['order', 'desc']],
  687. });
  688. for (const s of stages) {
  689. s.tp = this.ctx.helper.add(s.contract_tp, s.qc_tp);
  690. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  691. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  692. }
  693. return stages;
  694. }
  695. async isLastStage(tid, sid) {
  696. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  697. return lastStage ? lastStage.id === sid : false;
  698. }
  699. }
  700. return Stage;
  701. };