stage.js 37 KB

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