stage.js 38 KB

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