stage.js 54 KB

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