stage.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  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. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  214. stage.contract_tp = tpData.contract_tp;
  215. stage.qc_tp = tpData.qc_tp;
  216. stage.contract_pc_tp = pcSum.contract_pc_tp;
  217. stage.qc_pc_tp = pcSum.qc_pc_tp;
  218. stage.pc_tp = pcSum.pc_tp;
  219. stage.tp =this.ctx.helper.add(stage.contract_tp, stage.qc_tp);
  220. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  221. stage.yf_tp = tp.yf;
  222. stage.sf_tp = tp.sf;
  223. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  224. await this.update({
  225. check_calc: false,
  226. contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,
  227. contract_pc_tp: stage.contract_pc_tp || 0, qc_pc_tp: stage.qc_pc_tp || 0, pc_tp: stage.pc_tp || 0,
  228. yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,
  229. }, { id: stage.id });
  230. } else if (stage.tp_history) {
  231. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  232. if (his) {
  233. stage.contract_tp = his.contract_tp;
  234. stage.qc_tp = his.qc_tp;
  235. stage.yf_tp = his.yf_tp;
  236. stage.sf_tp = his.sf_tp;
  237. stage.tp = this.ctx.helper.add(stage.contract_tp, stage.qc_tp);
  238. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * 获取标段下的全部计量期,按倒序
  245. * @param tenderId
  246. * @return {Promise<void>}
  247. */
  248. async getValidStages(tenderId) {
  249. const stages = await this.db.select(this.tableName, {
  250. where: { tid: tenderId },
  251. orders: [['order', 'desc']],
  252. });
  253. for (const s of stages) {
  254. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  255. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  256. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  257. s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];
  258. }
  259. if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {
  260. const lastStage = stages[0];
  261. if (lastStage.status === auditConst.status.uncheck && lastStage.user_id !== this.ctx.session.sessionUser.accountId && !this.ctx.tender.isTourist) {
  262. stages.splice(0, 1);
  263. }
  264. }
  265. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  266. if (stages.length === 0) return stages;
  267. await this.checkStageGatherData(stages[0], true);
  268. for (const s of stages) {
  269. if (s.yf_tp && s.sf_tp === 0) {
  270. const sf = await this.ctx.service.stagePay.getHistorySf(s);
  271. if (sf && s.readOnly) {
  272. await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });
  273. }
  274. s.sf_tp = sf.tp;
  275. }
  276. }
  277. return stages;
  278. }
  279. async _getSumTp(condition, ...field) {
  280. const fieldSql = [];
  281. for (const f of field) {
  282. fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');
  283. }
  284. const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);
  285. return await this.db.queryOne(sql);
  286. }
  287. /**
  288. *
  289. * @param tenderId - 标段id
  290. * @param date - 计量年月
  291. * @param period - 开始-截止日期
  292. * @return {Promise<void>}
  293. */
  294. async addStage(tenderId, date, period) {
  295. const stages = await this.getAllDataByCondition({
  296. where: { tid: tenderId },
  297. order: ['order'],
  298. });
  299. const preStage = stages[stages.length - 1];
  300. if (stages.length > 0 && stages[stages.length - 1].status !== auditConst.status.checked) {
  301. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  302. }
  303. const order = stages.length + 1;
  304. const newStage = {
  305. sid: this.uuid.v4(),
  306. tid: tenderId,
  307. order,
  308. in_time: new Date(),
  309. s_time: date,
  310. period,
  311. times: 1,
  312. status: auditConst.status.uncheck,
  313. user_id: this.ctx.session.sessionUser.accountId,
  314. check_calc: false,
  315. };
  316. newStage.cache_time_l = newStage.in_time;
  317. newStage.cache_time_r = newStage.in_time;
  318. if (preStage) {
  319. newStage.im_type = preStage.im_type;
  320. newStage.im_pre = preStage.im_pre;
  321. newStage.im_gather = preStage.im_gather;
  322. newStage.im_gather_node = preStage.im_gather_node;
  323. newStage.pre_contract_tp = this.ctx.helper.sum([preStage.pre_contract_tp, preStage.contract_tp, preStage.contract_pc_tp]);
  324. newStage.pre_qc_tp = this.ctx.helper.sum([preStage.pre_qc_tp, preStage.qc_tp, preStage.qc_pc_tp]);
  325. newStage.pre_yf_tp = this.ctx.helper.add(preStage.pre_yf_tp, preStage.yf_tp);
  326. if (preStage.order === 1 || preStage.pre_sf_tp) {
  327. newStage.pre_sf_tp = this.ctx.helper.add(preStage.pre_sf_tp, preStage.sf_tp);
  328. } else {
  329. const sumTp = await this._getSumTp({tid: preStage.tid}, 'sf_tp');
  330. newStage.pre_sf_tp = sumTp.sf_tp || 0;
  331. }
  332. } else {
  333. const projFunRela = await this.ctx.service.project.getFunRela(this.ctx.session.sessionProject.id);
  334. newStage.im_type = projFunRela.imType;
  335. }
  336. const transaction = await this.db.beginTransaction();
  337. try {
  338. // 新增期记录
  339. const result = await transaction.insert(this.tableName, newStage);
  340. if (result.affectedRows === 1) {
  341. newStage.id = result.insertId;
  342. } else {
  343. throw '新增期数据失败';
  344. }
  345. // 存在上一期时,复制上一期审批流程
  346. if (preStage) {
  347. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  348. if (!auditResult) {
  349. throw '复制上一期审批流程失败';
  350. }
  351. }
  352. // 新增期合同支付数据
  353. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  354. if (!dealResult) {
  355. throw '新增期合同支付数据失败';
  356. }
  357. // 新增期其他台账数据
  358. if (preStage) {
  359. const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preStage, transaction);
  360. if (!jgclResult) throw '初始化甲供材料数据失败';
  361. const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preStage, transaction);
  362. if (!otherResult) throw '初始化其他台账数据失败';
  363. const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preStage, transaction);
  364. if (!safeResult) throw '初始化其他台账数据失败';
  365. const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preStage, transaction);
  366. if (!tempResult) throw '初始化其他台账数据失败';
  367. const priceCalc = new RevisePrice(this.ctx);
  368. await priceCalc.newStagePriceChange(newStage, preStage, transaction);
  369. }
  370. // 新增期拷贝报表相关配置/签名角色 等
  371. if (preStage) {
  372. const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);
  373. await this.ctx.service.roleRptRel.addInitialStageData(tenderId, newStage, preStage);
  374. }
  375. await transaction.commit();
  376. // 通知发送 - 第三方更新
  377. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  378. const base_data = {
  379. tid: tenderId,
  380. sid: result.insertId,
  381. op: 'insert',
  382. };
  383. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  384. // 存在上一期时
  385. base_data.op = preStage ? 'update' : 'insert';
  386. base_data.sid = -1;
  387. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  388. }
  389. return newStage;
  390. } catch (err) {
  391. await transaction.rollback();
  392. throw err;
  393. }
  394. }
  395. /**
  396. * 编辑计量期
  397. *
  398. * @param {Number} tenderId - 标段Id
  399. * @param {Number} order - 第N期
  400. * @param {String} date - 计量年月
  401. * @param {String} period - 开始-截止时间
  402. * @return {Promise<void>}
  403. */
  404. async saveStage(tenderId, order, date, period) {
  405. await this.db.update(this.tableName, {
  406. s_time: date,
  407. period,
  408. }, { where: { tid: tenderId, order } });
  409. }
  410. /**
  411. * 设置 中间计量 生成规则,并生成数据
  412. * @param {Number} tenderId - 标段id
  413. * @param {Number} order - 期序号
  414. * @param {Number} data - 中间计量生成规则
  415. * @return {Promise<void>}
  416. */
  417. async buildDetailData(tenderId, order, data) {
  418. const conn = await this.db.beginTransaction();
  419. try {
  420. 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 } });
  421. // to do 生成中间计量数据
  422. await conn.commit();
  423. } catch (err) {
  424. await conn.rollback();
  425. throw err;
  426. }
  427. }
  428. async getChangeSubtotal(stage) {
  429. const result = {};
  430. const bg = await this.ctx.service.stageChange.getSubtotal(stage);
  431. const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);
  432. result.common = this.ctx.helper.add(bg.common, importBg.common);
  433. result.great = this.ctx.helper.add(bg.great, importBg.great);
  434. result.more = this.ctx.helper.add(bg.more, importBg.more);
  435. return result;
  436. }
  437. /**
  438. * 获取 当期的 计算基数
  439. * @return {Promise<any>}
  440. */
  441. async getStagePayCalcBase(stage, tenderInfo) {
  442. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  443. const param = tenderInfo.deal_param;
  444. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  445. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  446. const bg = await this.getChangeSubtotal(stage);
  447. for (const cb of calcBase) {
  448. switch (cb.code) {
  449. case 'htj':
  450. cb.value = param.contractPrice;
  451. break;
  452. case 'zlje':
  453. cb.value = param.zanLiePrice;
  454. break;
  455. case 'htjszl':
  456. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  457. break;
  458. case 'kgyfk':
  459. cb.value = param.startAdvance;
  460. break;
  461. case 'clyfk':
  462. cb.value = param.materialAdvance;
  463. break;
  464. case 'bqwc':
  465. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  466. break;
  467. case 'bqht':
  468. cb.value = sum.contract_tp; //this.ctx.helper.add(sum.contract_tp, pcSum.contract_pc_tp);
  469. break;
  470. case 'bqbg':
  471. cb.value = sum.qc_tp; //this.ctx.helper.add(sum.qc_tp, pcSum.qc_pc_tp);
  472. break;
  473. case 'ybbqwc':
  474. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');
  475. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  476. break;
  477. case 'ybbqbg':
  478. cb.value = bg.common;
  479. break;
  480. case 'jdbqbg':
  481. cb.value = bg.more;
  482. break;
  483. case 'zdbqbg':
  484. cb.value = bg.great;
  485. break;
  486. default:
  487. cb.value = 0;
  488. }
  489. }
  490. return calcBase;
  491. }
  492. async updateCheckCalcFlag(stage, check) {
  493. const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check });
  494. return result.affectedRows === 1;
  495. }
  496. async updateCacheTime(sid) {
  497. const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });
  498. return result.affectedRows === 1;
  499. }
  500. /**
  501. * 删除计量期
  502. *
  503. * @param {Number} id - 期Id
  504. * @return {Promise<void>}
  505. */
  506. async deleteStage(id) {
  507. const transaction = await this.db.beginTransaction();
  508. try {
  509. const stageInfo = await this.getDataById(id);
  510. // 通知发送 - 第三方更新
  511. // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  512. // const base_data = {
  513. // tid: this.ctx.tender.id,
  514. // sid: id,
  515. // op: 'delete',
  516. // };
  517. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  518. // // 是否还存在其他期
  519. // base_data.op = stageInfo.order === 1 ? 'delete' : 'update';
  520. // base_data.sid = -1;
  521. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  522. // }
  523. await transaction.delete(this.tableName, { id });
  524. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });
  525. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  526. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  527. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  528. await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });
  529. await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });
  530. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  531. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  532. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  533. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  534. await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });
  535. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });
  536. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });
  537. await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });
  538. await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });
  539. // 删除计量合同支付附件
  540. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  541. if (payList) {
  542. for (const pt of payList) {
  543. if (pt.attachment !== null && pt.attachment !== '') {
  544. const payAttList = JSON.parse(pt.attachment);
  545. for (const pat of payAttList) {
  546. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  547. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  548. }
  549. }
  550. }
  551. }
  552. }
  553. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  554. await transaction.delete(this.ctx.service.pay.tableName, { csid: id });
  555. // 删除计量附件文件
  556. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });
  557. if (attList.length !== 0) {
  558. for (const att of attList) {
  559. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  560. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  561. }
  562. }
  563. }
  564. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });
  565. // 其他台账
  566. await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });
  567. const bonus = await this.ctx.service.stageBonus.getStageData(id);
  568. if (bonus && bonus.length > 0) {
  569. for (const b of bonus) {
  570. for (const f of b.proof_file) {
  571. if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {
  572. await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));
  573. }
  574. }
  575. }
  576. }
  577. await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });
  578. await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });
  579. // 同步删除进度里所选的期
  580. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });
  581. const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });
  582. if (detailAtt && detailAtt.length > 0) {
  583. for (const da of detailAtt) {
  584. da.attachment = da.attachment ? JSON.parse(da.attachment) : [];
  585. for (const daa of da.attachment) {
  586. if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {
  587. await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));
  588. }
  589. }
  590. }
  591. }
  592. await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });
  593. // 重算进度计量总金额
  594. await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);
  595. // 删除收方单及附件
  596. const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });
  597. if (shoufangAttList.length !== 0) {
  598. for (const att of shoufangAttList) {
  599. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  600. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  601. }
  602. }
  603. }
  604. await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });
  605. const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });
  606. if (shoufangList.length !== 0) {
  607. for (const att of shoufangList) {
  608. if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {
  609. await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));
  610. }
  611. }
  612. }
  613. await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });
  614. // 记录删除日志
  615. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');
  616. await transaction.commit();
  617. return true;
  618. } catch (err) {
  619. await transaction.rollback();
  620. throw err;
  621. }
  622. }
  623. /**
  624. * 获取 多期的 计算基数 -(材料调差调用)
  625. * @return {Promise<any>}
  626. */
  627. async getMaterialCalcBase(stage_list, tenderInfo) {
  628. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  629. const param = tenderInfo.deal_param;
  630. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  631. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPriceByMaterial(stage_list);
  632. for (const cb of calcBase) {
  633. switch (cb.code) {
  634. case 'htj':
  635. cb.value = param.contractPrice;
  636. break;
  637. case 'zlje':
  638. cb.value = param.zanLiePrice;
  639. break;
  640. case 'htjszl':
  641. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  642. break;
  643. case 'kgyfk':
  644. cb.value = param.startAdvance;
  645. break;
  646. case 'clyfk':
  647. cb.value = param.materialAdvance;
  648. break;
  649. case 'bqwc':
  650. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  651. break;
  652. case 'bqht':
  653. cb.value = sum.contract_tp;
  654. break;
  655. case 'bqbg':
  656. cb.value = sum.qc_tp;
  657. break;
  658. case 'ybbqwc':
  659. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^[^0-9]*1[0-9]{2}(-|$)');
  660. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  661. break;
  662. case 'bqyf':
  663. cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);
  664. break;
  665. default:
  666. cb.value = 0;
  667. }
  668. }
  669. return calcBase;
  670. }
  671. /**
  672. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  673. * @param stage_id_list
  674. * @return {Promise<void>}
  675. */
  676. async getStageMsgByStageId(stage_id_list) {
  677. const list = [];
  678. stage_id_list = stage_id_list.toString().split(',');
  679. for (const sid of stage_id_list) {
  680. const stage = await this.getDataById(sid);
  681. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  682. stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  683. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  684. stage.curTimes = stage.times;
  685. list.push(stage);
  686. }
  687. return list;
  688. }
  689. async getStageByDataCollect(tenderId) {
  690. const stages = await this.db.select(this.tableName, {
  691. columns: ['s_time', 'contract_tp', 'qc_tp', 'pre_contract_tp', 'pre_qc_tp'],
  692. where: { tid: tenderId },
  693. orders: [['order', 'desc']],
  694. });
  695. for (const s of stages) {
  696. s.tp = this.ctx.helper.add(s.contract_tp, s.qc_tp);
  697. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  698. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  699. }
  700. return stages;
  701. }
  702. async isLastStage(tid, sid) {
  703. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  704. return lastStage ? lastStage.id === sid : false;
  705. }
  706. }
  707. return Stage;
  708. };