stage.js 36 KB

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