stage.js 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. 'use strict';
  2. /**
  3. * 期计量 数据模型
  4. *
  5. * @author Mai
  6. * @date 2018/8/13
  7. * @version
  8. */
  9. const auditConst = require('../const/audit');
  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.stage.status;
  67. const accountId = this.ctx.session.sessionUser.accountId;
  68. stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id);
  69. stage.auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times); // 全部参与的审批人
  70. stage.auditorIds = this._.map(stage.auditors, 'aid');
  71. stage.curAuditors = stage.auditors.filter(x => { return x.status === status.checking; }); // 当前流程中审批中的审批人
  72. stage.curAuditorIds = this._.map(stage.curAuditors, 'aid');
  73. stage.flowAuditors = stage.curAuditors.length > 0 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order; }) : []; // 当前流程中参与的审批人(包含会签时,审批通过的人)
  74. stage.flowAuditorIds = this._.map(stage.flowAuditors, 'aid');
  75. stage.auditorGroups = this.ctx.helper.groupAuditors(stage.auditors);
  76. stage.userGroups = this.ctx.helper.groupAuditorsUniq(stage.auditorGroups);
  77. stage.userGroups.unshift([{
  78. aid: stage.user.id, order: 0, times: stage.times, audit_order: 0, audit_type: auditConst.auditType.key.common,
  79. name: stage.user.name, role: stage.user.role, company: stage.user.company
  80. }]);
  81. stage.finalAuditorIds = stage.userGroups[stage.userGroups.length - 1].map(x => { return x.aid; });
  82. stage.assists = await this.service.stageAuditAss.getData(stage); // 全部协同人
  83. stage.assists = stage.assists.filter(x => {
  84. return x.user_id === stage.user_id || stage.auditorIds.indexOf(x.user_id) >= 0;
  85. }); // 过滤无效协同人
  86. stage.userAssists = stage.assists.filter(x => { return x.user_id === stage.user_id; }); // 原报协同人
  87. stage.userAssistIds = this._.map(stage.userAssists, 'ass_user_id');
  88. stage.auditAssists = stage.assists.filter(x => { return x.user_id !== stage.user_id; }); // 审批协同人
  89. stage.auditAssistIds = this._.map(stage.auditAssists, 'ass_user_id');
  90. stage.relaAssists = stage.assists.filter(x => { return x.user_id === accountId }); // 登录人的协同人
  91. stage.userIds = stage.status === status.uncheck // 当前流程下全部参与人id
  92. ? [stage.user_id, ...stage.userAssistIds]
  93. : [stage.user_id, ...stage.userAssistIds, ...stage.auditorIds, ...stage.auditAssistIds];
  94. }
  95. async loadStageAuditViewData(stage) {
  96. const times = stage.status === auditConst.stage.status.checkNo ? stage.times - 1 : stage.times;
  97. if (!stage.user) stage.user = await this.ctx.service.projectAccount.getAccountInfoById(stage.user_id);
  98. stage.auditHistory = await this.ctx.service.stageAudit.getAuditorHistory(stage.id, times);
  99. // 获取审批流程中左边列表
  100. if (stage.status === auditConst.stage.status.checkNo && stage.user_id !== this.ctx.session.sessionUser.accountId) {
  101. stage.auditors2 = stage.userGroups;
  102. } else {
  103. const auditors = await this.ctx.service.stageAudit.getAuditors(stage.id, times); // 全部参与的审批人
  104. const auditorGroups = this.ctx.helper.groupAuditors(auditors);
  105. stage.auditors2 = this.ctx.helper.groupAuditorsUniq(auditorGroups);
  106. stage.auditors2.unshift([{
  107. aid: stage.user.id, order: 0, times: stage.times - 1, audit_order: 0, audit_type: auditConst.auditType.key.common,
  108. name: stage.user.name, role: stage.user.role, company: stage.user.company
  109. }]);
  110. }
  111. if (stage.status === auditConst.stage.status.uncheck || stage.status === auditConst.stage.status.checkNo) {
  112. stage.auditorList = await this.ctx.service.stageAudit.getAuditors(stage.id, stage.times);
  113. }
  114. }
  115. async doCheckStage(stage, force = false) {
  116. const status = auditConst.stage.status;
  117. await this.loadStageUser(stage);
  118. const accountId = this.ctx.session.sessionUser.accountId, shareIds = [];
  119. const isTenderTourist = await this.service.tenderTourist.getDataByCondition({ tid: stage.tid, user_id: accountId });
  120. const permission = this.ctx.session.sessionUser.permission;
  121. if (stage.status === status.uncheck) {
  122. stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;
  123. if (!stage.readOnly) {
  124. stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });
  125. }
  126. stage.curTimes = stage.times;
  127. stage.curOrder = 0;
  128. } else if (stage.status === status.checkNo) {
  129. stage.readOnly = accountId !== stage.user_id && stage.userAssistIds.indexOf(accountId) < 0;
  130. const checkNoAudit = await this.service.stageAudit.getDataByCondition({
  131. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  132. });
  133. if (!stage.readOnly) {
  134. stage.assist = stage.userAssists.find(x => { return x.ass_user_id === accountId; });
  135. stage.curTimes = stage.times;
  136. stage.curOrder = 0;
  137. } else {
  138. stage.curTimes = stage.times - 1;
  139. stage.curOrder = checkNoAudit.order;
  140. }
  141. } else if (stage.status === status.checked) {
  142. stage.readOnly = true;
  143. stage.curTimes = stage.times;
  144. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  145. } else {
  146. const ass = stage.auditAssists.find(x => { return stage.curAuditorIds.indexOf(x.user_id) >= 0 && x.ass_user_id === accountId; });
  147. stage.readOnly = stage.curAuditorIds.indexOf(accountId) >= 0 && !ass;
  148. stage.curTimes = stage.times;
  149. if (!stage.readOnly) {
  150. stage.assist = ass;
  151. stage.curOrder = stage.curAuditors[0].order;
  152. } else {
  153. stage.curOrder = stage.curAuditors[0].order - 1;
  154. }
  155. // 会签,会签人审批通过时,只读,但是curOrder需按原来的取值
  156. stage.readOnly = stage.readOnly && this._.isEqual(stage.flowAuditorIds, stage.curAuditorIds);
  157. }
  158. if (stage.readOnly) {
  159. stage.assist = accountId === stage.user_id || stage.auditorIds.indexOf(accountId) >= 0
  160. ? null
  161. : stage.assists.find(x => { return x.ass_user_id === accountId});
  162. }
  163. if (stage.userIds.indexOf(accountId) >= 0) {
  164. stage.filePermission = true;
  165. } else if (!!isTenderTourist || force) {
  166. stage.filePermission = this.tender && this.tender.touristPermission ? this.tender.touristPermission.file : false;
  167. } else {
  168. stage.filePermission = false;
  169. }
  170. let time = stage.readOnly ? stage.cache_time_r : stage.cache_time_l;
  171. if (!time) time = stage.in_time ? stage.in_time : new Date();
  172. stage.cacheTime = time.getTime();
  173. // 历史台账
  174. if (stage.status === status.checked) {
  175. stage.ledgerHis = await this.service.ledgerHistory.getDataById(stage.his_id);
  176. }
  177. // 是否台账修订中
  178. const lastRevise = await this.service.ledgerRevise.getLastestRevise(stage.tid);
  179. stage.revising = (lastRevise && lastRevise.status !== auditConst.revise.status.checked) || false;
  180. return stage;
  181. }
  182. async doCheckStageCanCancel(stage) {
  183. // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回)
  184. const status = auditConst.stage.status;
  185. const accountId = this.ctx.session.sessionUser.accountId;
  186. stage.cancancel = 0;
  187. if (stage.status !== status.checked && stage.status !== status.uncheck) {
  188. if (stage.status !== status.checkNo) {
  189. // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报
  190. if (stage.flowAuditors.find(x => { return x.status !== auditConst.stage.status.checking})) return; // 当前流程存在审批人审批通过时,不可撤回
  191. if (stage.curAuditorIds.indexOf(accountId) < 0 && stage.flowAuditorIds.indexOf(accountId) >= 0) {
  192. stage.cancancel = 5; // 会签未全部审批通过时,审批人撤回审批通过
  193. return;
  194. }
  195. const preAuditors = stage.curAuditors[0].order !== 1 ? stage.auditors.filter(x => { return x.order === stage.curAuditors[0].order - 1; }) : [];
  196. const preAuditorCheckAgain = preAuditors.find(pa => { return pa.status === status.checkAgain; });
  197. const preAuditorCheckCancel = preAuditors.find(pa => { return pa.status === status.checkCancel; });
  198. const preAuditorHasOld = preAuditors.find(pa => { return pa.is_old === 1; });
  199. const preAuditorIds = (preAuditorCheckAgain ? [] : preAuditors.map(x => { return x.aid })); // 重审不可撤回
  200. if ((this._.isEqual(stage.flowAuditorIds, preAuditorIds) && preAuditorCheckCancel) || preAuditorHasOld) {
  201. return; // 不可以多次撤回
  202. }
  203. const preAuditChecked = preAuditors.find(pa => { return pa.status === status.checked && pa.aid === accountId; });
  204. const preAuditCheckNoPre = preAuditors.find(pa => { return pa.status === status.checkNoPre && pa.aid === accountId; });
  205. if (preAuditorIds.indexOf(accountId) >= 0) {
  206. if (preAuditChecked) {
  207. stage.cancancel = 2;// 审批人撤回审批通过
  208. } else if (preAuditCheckNoPre) {
  209. stage.cancancel = 3;// 审批人撤回审批退回上一人
  210. }
  211. stage.preAuditors = preAuditors;
  212. } else if (preAuditors.length > 0 && accountId === stage.user_id) {
  213. stage.cancancel = 1;// 原报撤回
  214. }
  215. } else {
  216. const lastAuditors = await this.service.stageAudit.getAuditors(stage.id, stage.times - 1);
  217. const onAuditor = _.find(lastAuditors, { status: status.checkNo });
  218. if (onAuditor.aid === accountId) {
  219. stage.cancancel = 4;// 审批人撤回退回原报
  220. stage.preAuditors = lastAuditors.filter(x => { return x.order === onAuditor.order });
  221. }
  222. }
  223. }
  224. }
  225. async checkStage(sid) {
  226. if (!this.ctx.stage) {
  227. const stage = await this.ctx.service.stage.getDataById(sid);
  228. if (!stage) throw '校验的期数据不存在';
  229. await this.doCheckStage(stage);
  230. this.ctx.stage = stage;
  231. }
  232. }
  233. /**
  234. * 获取 最新一期 期计量
  235. * @param tenderId
  236. * @param includeUnCheck
  237. * @return {Promise<*>}
  238. */
  239. async getLastestStage(tenderId, includeUnCheck = false) {
  240. this.initSqlBuilder();
  241. this.sqlBuilder.setAndWhere('tid', {
  242. value: tenderId,
  243. operate: '=',
  244. });
  245. if (!includeUnCheck) {
  246. this.sqlBuilder.setAndWhere('status', {
  247. value: auditConst.stage.status.uncheck,
  248. operate: '!=',
  249. });
  250. }
  251. this.sqlBuilder.orderBy = [['order', 'desc']];
  252. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  253. const stage = await this.db.queryOne(sql, sqlParam);
  254. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  255. return stage;
  256. }
  257. /**
  258. * 获取 最新一期 审批完成的 期计量
  259. * @param tenderId
  260. * @return {Promise<*>}
  261. */
  262. async getLastestCompleteStage(tenderId) {
  263. this.initSqlBuilder();
  264. this.sqlBuilder.setAndWhere('tid', {
  265. value: tenderId,
  266. operate: '=',
  267. });
  268. this.sqlBuilder.setAndWhere('status', {
  269. value: auditConst.stage.status.checked,
  270. operate: '=',
  271. });
  272. this.sqlBuilder.orderBy = [['order', 'desc']];
  273. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  274. const stage = await this.db.queryOne(sql, sqlParam);
  275. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  276. return stage;
  277. }
  278. /**
  279. * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)
  280. * @param tenderId
  281. * @return {Promise<void>}
  282. */
  283. async getValidStagesShort(tenderId) {
  284. const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';
  285. const sqlParam = [tenderId];
  286. return await this.db.query(sql, sqlParam);
  287. }
  288. /**
  289. * 获取某一期信息(报表用)
  290. * @param stageId
  291. * @return {Promise<void>}
  292. */
  293. async getStageById(stageId) {
  294. const sql = 'select * from zh_stage where id = ? order by zh_stage.order';
  295. const sqlParam = [stageId];
  296. return await this.db.query(sql, sqlParam);
  297. }
  298. async checkStageGatherData(stage, force = false) {
  299. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  300. if (stage.status !== auditConst.stage.status.checked) {
  301. await this.doCheckStage(stage, force);
  302. if (!stage.readOnly && stage.check_calc) {
  303. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  304. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  305. stage.contract_tp = tpData.contract_tp;
  306. stage.qc_tp = tpData.qc_tp;
  307. stage.positive_qc_tp = tpData.positive_qc_tp;
  308. stage.negative_qc_tp = tpData.negative_qc_tp;
  309. stage.contract_pc_tp = pcSum.contract_pc_tp;
  310. stage.qc_pc_tp = pcSum.qc_pc_tp;
  311. stage.pc_tp = pcSum.pc_tp;
  312. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  313. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  314. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  315. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  316. stage.yf_tp = tp.yf;
  317. stage.sf_tp = tp.sf;
  318. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  319. await this.update({
  320. check_calc: false,
  321. contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,
  322. positive_qc_tp: stage.positive_qc_tp, negative_qc_tp: stage.negative_qc_tp,
  323. contract_pc_tp: stage.contract_pc_tp || 0, qc_pc_tp: stage.qc_pc_tp || 0, pc_tp: stage.pc_tp || 0,
  324. positive_qc_pc_tp: stage.positive_qc_pc_tp || 0, negative_qc_pc_tp: stage.negative_qc_pc_tp || 0,
  325. yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,
  326. }, { id: stage.id });
  327. } else if (stage.tp_history) {
  328. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  329. if (his) {
  330. stage.contract_tp = his.contract_tp;
  331. stage.qc_tp = his.qc_tp;
  332. stage.positive_qc_tp = his.positive_qc_tp;
  333. stage.negative_qc_tp = his.negative_qc_tp;
  334. stage.yf_tp = his.yf_tp;
  335. stage.sf_tp = his.sf_tp;
  336. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  337. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  338. }
  339. }
  340. }
  341. }
  342. /**
  343. * 获取标段下的全部计量期,按倒序
  344. * @param tenderId
  345. * @return {Promise<void>}
  346. */
  347. async getValidStages(tenderId) {
  348. const stages = await this.db.select(this.tableName, {
  349. where: { tid: tenderId },
  350. orders: [['order', 'desc']],
  351. });
  352. for (const s of stages) {
  353. s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];
  354. }
  355. if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {
  356. const lastStage = stages[0];
  357. if (lastStage.status === auditConst.stage.status.uncheck && !this.ctx.tender.isTourist) {
  358. const assist = await this.ctx.service.auditAss.getAllDataByCondition({ where: { tid: tenderId, user_id: lastStage.user_id } });
  359. const assistId = assist.map(x => { return x.ass_user_id });
  360. if (lastStage.user_id !== this.ctx.session.sessionUser.accountId && assistId.indexOf(this.ctx.session.sessionUser.accountId) < 0) {
  361. stages.splice(0, 1);
  362. }
  363. }
  364. }
  365. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  366. if (stages.length === 0) return stages;
  367. await this.checkStageGatherData(stages[0], true);
  368. for (const s of stages) {
  369. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  370. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  371. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  372. if (s.yf_tp && s.sf_tp === 0) {
  373. const sf = await this.ctx.service.stagePay.getHistorySf(s);
  374. if (sf && s.readOnly) {
  375. await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });
  376. }
  377. s.sf_tp = sf.tp;
  378. }
  379. }
  380. return stages;
  381. }
  382. async _getSumTp(condition, ...field) {
  383. const fieldSql = [];
  384. for (const f of field) {
  385. fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');
  386. }
  387. const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);
  388. return await this.db.queryOne(sql);
  389. }
  390. /**
  391. *
  392. * @param tenderId - 标段id
  393. * @param date - 计量年月
  394. * @param period - 开始-截止日期
  395. * @return {Promise<void>}
  396. */
  397. async addStage(tenderId, date, period) {
  398. const stages = await this.getAllDataByCondition({
  399. where: { tid: tenderId },
  400. order: ['order'],
  401. });
  402. const preStage = stages[stages.length - 1];
  403. if (stages.length > 0 && stages[stages.length - 1].status !== auditConst.stage.status.checked) {
  404. throw '上一期未审批通过,请等待上一期审批通过后,再新增数据';
  405. }
  406. const order = stages.length + 1;
  407. const newStage = {
  408. sid: this.uuid.v4(),
  409. tid: tenderId,
  410. order,
  411. in_time: new Date(),
  412. s_time: date,
  413. period,
  414. times: 1,
  415. status: auditConst.stage.status.uncheck,
  416. user_id: this.ctx.session.sessionUser.accountId,
  417. check_calc: false,
  418. };
  419. newStage.cache_time_l = newStage.in_time;
  420. newStage.cache_time_r = newStage.in_time;
  421. if (preStage) {
  422. newStage.im_type = preStage.im_type;
  423. newStage.im_pre = preStage.im_pre;
  424. newStage.im_gather = preStage.im_gather;
  425. newStage.im_gather_node = preStage.im_gather_node;
  426. newStage.pre_contract_tp = this.ctx.helper.sum([preStage.pre_contract_tp, preStage.contract_tp, preStage.contract_pc_tp]);
  427. newStage.pre_qc_tp = this.ctx.helper.sum([preStage.pre_qc_tp, preStage.qc_tp, preStage.qc_pc_tp]);
  428. newStage.pre_positive_qc_tp = this.ctx.helper.sum([preStage.pre_positive_qc_tp, preStage.positive_qc_tp, preStage.positive_qc_pc_tp]);
  429. newStage.pre_negative_qc_tp = this.ctx.helper.sum([preStage.pre_negative_qc_tp, preStage.negative_qc_tp, preStage.negative_qc_pc_tp]);
  430. newStage.pre_yf_tp = this.ctx.helper.add(preStage.pre_yf_tp, preStage.yf_tp);
  431. if (preStage.order === 1 || preStage.pre_sf_tp) {
  432. newStage.pre_sf_tp = this.ctx.helper.add(preStage.pre_sf_tp, preStage.sf_tp);
  433. } else {
  434. const sumTp = await this._getSumTp({tid: preStage.tid}, 'sf_tp');
  435. newStage.pre_sf_tp = sumTp.sf_tp || 0;
  436. }
  437. } else {
  438. const projFunRela = await this.ctx.service.project.getFunRela(this.ctx.session.sessionProject.id);
  439. newStage.im_type = projFunRela.imType;
  440. }
  441. const transaction = await this.db.beginTransaction();
  442. try {
  443. // 新增期记录
  444. const result = await transaction.insert(this.tableName, newStage);
  445. if (result.affectedRows === 1) {
  446. newStage.id = result.insertId;
  447. } else {
  448. throw '新增期数据失败';
  449. }
  450. // 存在上一期时,复制上一期审批流程
  451. if (preStage) {
  452. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  453. if (!auditResult) {
  454. throw '复制上一期审批流程失败';
  455. }
  456. }
  457. // 新增期合同支付数据
  458. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  459. if (!dealResult) {
  460. throw '新增期合同支付数据失败';
  461. }
  462. // 新增期其他台账数据
  463. let pcTp = { contract_pc_tp: 0, qc_pc_tp: 0, pc_tp: 0, positive_qc_pc_tp: 0, negative_qc_pc_tp: 0 };
  464. if (preStage) {
  465. const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preStage, transaction);
  466. if (!jgclResult) throw '初始化甲供材料数据失败';
  467. const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preStage, transaction);
  468. if (!otherResult) throw '初始化其他台账数据失败';
  469. const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preStage, transaction);
  470. if (!safeResult) throw '初始化其他台账数据失败';
  471. const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preStage, transaction);
  472. if (!tempResult) throw '初始化其他台账数据失败';
  473. const priceCalc = new RevisePrice(this.ctx);
  474. pcTp = await priceCalc.newStagePriceChange(newStage, preStage, transaction);
  475. }
  476. await this.ctx.service.tenderCache.updateStageCache4Add(transaction, newStage, pcTp);
  477. // 新增期拷贝报表相关配置/签名角色 等
  478. if (preStage) {
  479. const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);
  480. await this.ctx.service.roleRptRel.addInitialStageData(tenderId, newStage, preStage);
  481. }
  482. await transaction.commit();
  483. // 通知发送 - 第三方更新
  484. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  485. const base_data = {
  486. tid: tenderId,
  487. sid: result.insertId,
  488. op: 'insert',
  489. };
  490. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  491. // 存在上一期时
  492. base_data.op = preStage ? 'update' : 'insert';
  493. base_data.sid = -1;
  494. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  495. }
  496. return newStage;
  497. } catch (err) {
  498. await transaction.rollback();
  499. throw err;
  500. }
  501. }
  502. /**
  503. * 编辑计量期
  504. *
  505. * @param {Number} tenderId - 标段Id
  506. * @param {Number} order - 第N期
  507. * @param {String} date - 计量年月
  508. * @param {String} period - 开始-截止时间
  509. * @return {Promise<void>}
  510. */
  511. async saveStage(tenderId, order, date, period) {
  512. await this.db.update(this.tableName, {
  513. s_time: date,
  514. period,
  515. }, { where: { tid: tenderId, order } });
  516. }
  517. /**
  518. * 设置 中间计量 生成规则,并生成数据
  519. * @param {Number} tenderId - 标段id
  520. * @param {Number} order - 期序号
  521. * @param {Number} data - 中间计量生成规则
  522. * @return {Promise<void>}
  523. */
  524. async buildDetailData(tenderId, order, data) {
  525. const conn = await this.db.beginTransaction();
  526. try {
  527. 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 } });
  528. // to do 生成中间计量数据
  529. await conn.commit();
  530. } catch (err) {
  531. await conn.rollback();
  532. throw err;
  533. }
  534. }
  535. async getChangeSubtotal(stage) {
  536. const result = {};
  537. const bg = await this.ctx.service.stageChange.getSubtotal(stage);
  538. const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);
  539. result.common = this.ctx.helper.add(bg.common, importBg.common);
  540. result.great = this.ctx.helper.add(bg.great, importBg.great);
  541. result.more = this.ctx.helper.add(bg.more, importBg.more);
  542. return result;
  543. }
  544. /**
  545. * 获取 当期的 计算基数
  546. * @return {Promise<any>}
  547. */
  548. async getStagePayCalcBase(stage, tenderInfo) {
  549. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  550. const param = tenderInfo.deal_param;
  551. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  552. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  553. const bg = await this.getChangeSubtotal(stage);
  554. for (const cb of calcBase) {
  555. switch (cb.code) {
  556. case 'htj':
  557. cb.value = param.contractPrice;
  558. break;
  559. case 'zlje':
  560. cb.value = param.zanLiePrice;
  561. break;
  562. case 'htjszl':
  563. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  564. break;
  565. case 'kgyfk':
  566. cb.value = param.startAdvance;
  567. break;
  568. case 'clyfk':
  569. cb.value = param.materialAdvance;
  570. break;
  571. case 'bqwc':
  572. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  573. break;
  574. case 'bqht':
  575. cb.value = sum.contract_tp; //this.ctx.helper.add(sum.contract_tp, pcSum.contract_pc_tp);
  576. break;
  577. case 'bqbg':
  578. cb.value = sum.qc_tp; //this.ctx.helper.add(sum.qc_tp, pcSum.qc_pc_tp);
  579. break;
  580. case 'ybbqwc':
  581. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');
  582. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  583. break;
  584. case 'ybbqbg':
  585. cb.value = bg.common;
  586. break;
  587. case 'jdbqbg':
  588. cb.value = bg.more;
  589. break;
  590. case 'zdbqbg':
  591. cb.value = bg.great;
  592. break;
  593. default:
  594. cb.value = 0;
  595. }
  596. }
  597. return calcBase;
  598. }
  599. async updateCheckCalcFlag(stage, check) {
  600. const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check });
  601. return result.affectedRows === 1;
  602. }
  603. async updateCacheTime(sid) {
  604. const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });
  605. return result.affectedRows === 1;
  606. }
  607. /**
  608. * 删除计量期
  609. *
  610. * @param {Number} id - 期Id
  611. * @return {Promise<void>}
  612. */
  613. async deleteStage(id) {
  614. const transaction = await this.db.beginTransaction();
  615. try {
  616. const stageInfo = await this.getDataById(id);
  617. // 通知发送 - 第三方更新
  618. // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  619. // const base_data = {
  620. // tid: this.ctx.tender.id,
  621. // sid: id,
  622. // op: 'delete',
  623. // };
  624. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  625. // // 是否还存在其他期
  626. // base_data.op = stageInfo.order === 1 ? 'delete' : 'update';
  627. // base_data.sid = -1;
  628. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  629. // }
  630. await transaction.delete(this.tableName, { id });
  631. await this.ctx.service.tenderCache.updateStageCache4Del(transaction, stageInfo);
  632. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });
  633. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  634. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  635. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  636. await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });
  637. await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });
  638. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  639. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  640. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  641. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  642. await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });
  643. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });
  644. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });
  645. await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });
  646. await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });
  647. await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid: id });
  648. // 删除计量合同支付附件
  649. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  650. if (payList) {
  651. for (const pt of payList) {
  652. if (pt.attachment !== null && pt.attachment !== '') {
  653. const payAttList = JSON.parse(pt.attachment);
  654. for (const pat of payAttList) {
  655. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  656. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  657. }
  658. }
  659. }
  660. }
  661. }
  662. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  663. await this.ctx.service.pay.doDeleteStage(stageInfo, transaction);
  664. // 删除计量附件文件
  665. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });
  666. if (attList.length !== 0) {
  667. for (const att of attList) {
  668. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  669. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  670. }
  671. }
  672. }
  673. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });
  674. // 其他台账
  675. await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });
  676. const bonus = await this.ctx.service.stageBonus.getStageData(id);
  677. if (bonus && bonus.length > 0) {
  678. for (const b of bonus) {
  679. for (const f of b.proof_file) {
  680. if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {
  681. await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));
  682. }
  683. }
  684. }
  685. }
  686. await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });
  687. await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });
  688. // 同步删除进度里所选的期
  689. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });
  690. const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });
  691. if (detailAtt && detailAtt.length > 0) {
  692. for (const da of detailAtt) {
  693. da.attachment = da.attachment ? JSON.parse(da.attachment) : [];
  694. for (const daa of da.attachment) {
  695. if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {
  696. await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));
  697. }
  698. }
  699. }
  700. }
  701. await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });
  702. // 重算进度计量总金额
  703. await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);
  704. // 删除收方单及附件
  705. const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });
  706. if (shoufangAttList.length !== 0) {
  707. for (const att of shoufangAttList) {
  708. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  709. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  710. }
  711. }
  712. }
  713. await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });
  714. const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });
  715. if (shoufangList.length !== 0) {
  716. for (const att of shoufangList) {
  717. if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {
  718. await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));
  719. }
  720. }
  721. }
  722. await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });
  723. await transaction.delete(this.ctx.service.cooperationConfirm.tableName, { sid: id });
  724. // 记录删除日志
  725. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');
  726. await transaction.commit();
  727. return true;
  728. } catch (err) {
  729. await transaction.rollback();
  730. throw err;
  731. }
  732. }
  733. /**
  734. * 获取 多期的 计算基数 -(材料调差调用)
  735. * @return {Promise<any>}
  736. */
  737. async getMaterialCalcBase(stage_list, tenderInfo) {
  738. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  739. const param = tenderInfo.deal_param;
  740. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  741. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPriceByMaterial(stage_list);
  742. for (const cb of calcBase) {
  743. switch (cb.code) {
  744. case 'htj':
  745. cb.value = param.contractPrice;
  746. break;
  747. case 'zlje':
  748. cb.value = param.zanLiePrice;
  749. break;
  750. case 'htjszl':
  751. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  752. break;
  753. case 'kgyfk':
  754. cb.value = param.startAdvance;
  755. break;
  756. case 'clyfk':
  757. cb.value = param.materialAdvance;
  758. break;
  759. case 'bqwc':
  760. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  761. break;
  762. case 'bqht':
  763. cb.value = sum.contract_tp;
  764. break;
  765. case 'bqbg':
  766. cb.value = sum.qc_tp;
  767. break;
  768. case 'ybbqwc':
  769. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, '^[^0-9]*1[0-9]{2}(-|$)');
  770. cb.value = this.ctx.helper.add(sumGcl.contract_tp, sumGcl.qc_tp);
  771. break;
  772. case 'bqyf':
  773. cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);
  774. break;
  775. default:
  776. cb.value = 0;
  777. }
  778. }
  779. return calcBase;
  780. }
  781. /**
  782. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  783. * @param stage_id_list
  784. * @return {Promise<void>}
  785. */
  786. async getStageMsgByStageId(stage_id_list) {
  787. const list = [];
  788. stage_id_list = stage_id_list.toString().split(',');
  789. for (const sid of stage_id_list) {
  790. const stage = await this.getDataById(sid);
  791. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  792. stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  793. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  794. stage.curTimes = stage.times;
  795. list.push(stage);
  796. }
  797. return list;
  798. }
  799. async getStageByDataCollect(tenderId) {
  800. const stages = await this.db.select(this.tableName, {
  801. columns: ['id', 'user_id', 'times', 'status', 's_time', 'contract_tp', 'qc_tp', 'pc_tp', 'pre_contract_tp', 'pre_qc_tp', 'tp_history'],
  802. where: { tid: tenderId },
  803. orders: [['order', 'desc']],
  804. });
  805. if (stages.length > 0 && stages[0].status === auditConst.stage.status.uncheck) {
  806. stages.splice(0, 1);
  807. }
  808. // 最新一期计量(未审批完成),取上一个人的期详细数据,应实时计算
  809. const stage = stages[0];
  810. if (stages.length === 0) return stages;
  811. await this.checkStageGatherDataByDataCollect(stage);
  812. for (const s of stages) {
  813. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  814. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  815. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  816. }
  817. return stages;
  818. }
  819. async doCheckStageByDataCollect(stage) {
  820. const status = auditConst.stage.status;
  821. await this.loadStageUser(stage);
  822. if (stage.status === status.checkNo) {
  823. stage.readOnly = false;
  824. const checkNoAudit = await this.service.stageAudit.getDataByCondition({
  825. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  826. });
  827. stage.curTimes = stage.times - 1;
  828. stage.curOrder = checkNoAudit.order;
  829. } else if (stage.status === status.checked) {
  830. stage.readOnly = true;
  831. stage.curTimes = stage.times;
  832. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  833. } else {
  834. stage.readOnly = false;
  835. stage.curTimes = stage.times;
  836. stage.curOrder = stage.curAuditors[0].order - 1;
  837. }
  838. return stage;
  839. }
  840. async checkStageGatherDataByDataCollect(stage) {
  841. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  842. if (stage.status !== auditConst.stage.status.checked) {
  843. await this.doCheckStageByDataCollect(stage);
  844. if (!stage.readOnly && stage.check_calc) {
  845. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  846. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  847. stage.contract_tp = tpData.contract_tp;
  848. stage.qc_tp = tpData.qc_tp;
  849. stage.positive_qc_tp = tpData.positive_qc_tp;
  850. stage.negative_qc_tp = tpData.negative_qc_tp;
  851. stage.contract_pc_tp = pcSum.contract_pc_tp;
  852. stage.qc_pc_tp = pcSum.qc_pc_tp;
  853. stage.pc_tp = pcSum.pc_tp;
  854. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  855. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  856. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  857. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  858. stage.yf_tp = tp.yf;
  859. stage.sf_tp = tp.sf;
  860. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  861. } else if (stage.tp_history) {
  862. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  863. if (his) {
  864. stage.contract_tp = his.contract_tp;
  865. stage.qc_tp = his.qc_tp;
  866. stage.positive_qc_tp = his.positive_qc_tp;
  867. stage.negative_qc_tp = his.negative_qc_tp;
  868. stage.yf_tp = his.yf_tp;
  869. stage.sf_tp = his.sf_tp;
  870. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  871. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  872. }
  873. }
  874. }
  875. }
  876. async isLastStage(tid, sid) {
  877. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  878. return lastStage ? lastStage.id === sid : false;
  879. }
  880. }
  881. return Stage;
  882. };