stage.js 37 KB

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