stage.js 36 KB

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