stage.js 34 KB

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