stage.js 37 KB

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