stage.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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.status === auditConst.stage.status.uncheck ? firstFlowStage : stages[flowStages.length];
  301. } else {
  302. stage = firstFlowStage.status === auditConst.stage.status.uncheck ? stages[flowStages.length] : firstFlowStage;
  303. }
  304. }
  305. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  306. return stage;
  307. }
  308. /**
  309. * 获取 最新一期 审批完成的 期计量
  310. * @param tenderId
  311. * @return {Promise<*>}
  312. */
  313. async getLastestCompleteStage(tenderId) {
  314. this.initSqlBuilder();
  315. this.sqlBuilder.setAndWhere('tid', {
  316. value: tenderId,
  317. operate: '=',
  318. });
  319. this.sqlBuilder.setAndWhere('status', {
  320. value: auditConst.stage.status.checked,
  321. operate: '=',
  322. });
  323. this.sqlBuilder.orderBy = [['order', 'desc']];
  324. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName);
  325. const stage = await this.db.queryOne(sql, sqlParam);
  326. if (stage) stage.tp_history = stage.tp_history ? JSON.parse(stage.tp_history) : [];
  327. return stage;
  328. }
  329. /**
  330. * 获取标段下的期列表(报表选择用,只需要一些key信息,不需要计算详细数据,也懒得一个个字段写了,用*来处理)
  331. * @param tenderId
  332. * @return {Promise<void>}
  333. */
  334. async getValidStagesShort(tenderId) {
  335. const sql = 'select * from zh_stage where tid = ? order by zh_stage.order';
  336. const sqlParam = [tenderId];
  337. return await this.db.query(sql, sqlParam);
  338. }
  339. /**
  340. * 获取某一期信息(报表用)
  341. * @param stageId
  342. * @return {Promise<void>}
  343. */
  344. async getStageById(stageId) {
  345. const sql = 'select * from zh_stage where id = ? order by zh_stage.order';
  346. const sqlParam = [stageId];
  347. return await this.db.query(sql, sqlParam);
  348. }
  349. async checkStageGatherData(stage, force = false) {
  350. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  351. if (stage.status !== auditConst.stage.status.checked) {
  352. await this.doCheckStage(stage, force);
  353. if (!stage.readOnly && stage.check_calc) {
  354. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  355. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  356. stage.contract_tp = tpData.contract_tp;
  357. stage.qc_tp = tpData.qc_tp;
  358. stage.positive_qc_tp = tpData.positive_qc_tp;
  359. stage.negative_qc_tp = tpData.negative_qc_tp;
  360. stage.contract_pc_tp = pcSum.contract_pc_tp;
  361. stage.qc_pc_tp = pcSum.qc_pc_tp;
  362. stage.pc_tp = pcSum.pc_tp;
  363. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  364. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  365. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  366. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  367. stage.yf_tp = tp.yf;
  368. stage.sf_tp = tp.sf;
  369. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  370. await this.update({
  371. check_calc: false,
  372. contract_tp: stage.contract_tp, qc_tp: stage.qc_tp,
  373. positive_qc_tp: stage.positive_qc_tp, negative_qc_tp: stage.negative_qc_tp,
  374. contract_pc_tp: stage.contract_pc_tp || 0, qc_pc_tp: stage.qc_pc_tp || 0, pc_tp: stage.pc_tp || 0,
  375. positive_qc_pc_tp: stage.positive_qc_pc_tp || 0, negative_qc_pc_tp: stage.negative_qc_pc_tp || 0,
  376. yf_tp: stage.yf_tp, sf_tp: stage.sf_tp,
  377. }, { id: stage.id });
  378. } else if (stage.tp_history) {
  379. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  380. if (his) {
  381. stage.contract_tp = his.contract_tp;
  382. stage.qc_tp = his.qc_tp;
  383. stage.positive_qc_tp = his.positive_qc_tp;
  384. stage.negative_qc_tp = his.negative_qc_tp;
  385. stage.yf_tp = his.yf_tp;
  386. stage.sf_tp = his.sf_tp;
  387. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  388. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  389. }
  390. }
  391. }
  392. }
  393. async _checkStageValid(stage) {
  394. if (stage.status === auditConst.stage.status.uncheck && !this.ctx.tender.isTourist) {
  395. const assist = await this.ctx.service.auditAss.getAllDataByCondition({ where: { tid: stage.tid, user_id: stage.user_id } });
  396. const assistId = assist.map(x => { return x.ass_user_id });
  397. return stage.user_id === this.ctx.session.sessionUser.accountId || assistId.indexOf(this.ctx.session.sessionUser.accountId) >= 0;
  398. } else {
  399. return true;
  400. }
  401. }
  402. /**
  403. * 获取标段下的全部计量期,按倒序
  404. * @param tenderId
  405. * @return {Promise<void>}
  406. */
  407. async getValidStages(tenderId, force = false) {
  408. let stages = await this.db.select(this.tableName, {
  409. where: { tid: tenderId },
  410. orders: [['order', 'desc']],
  411. });
  412. for (const s of stages) {
  413. s.tp_history = s.tp_history ? JSON.parse(s.tp_history) : [];
  414. s.valid = await this._checkStageValid(s);
  415. }
  416. if (stages.length !== 0 && !this.ctx.session.sessionUser.is_admin) {
  417. stages = stages.filter(x => { return x.valid; });
  418. }
  419. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  420. if (stages.length === 0) return stages;
  421. for (const s of stages) {
  422. if (s.status !== auditConst.stage.status.checked) await this.checkStageGatherData(s, force);
  423. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  424. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  425. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  426. if (s.yf_tp && s.sf_tp === 0) {
  427. const sf = await this.ctx.service.stagePay.getHistorySf(s);
  428. if (sf && s.readOnly) {
  429. await this.ctx.service.stage.update({ sf_tp: sf.tp, pre_sf_tp: sf.pre_tp }, { id: s.id });
  430. }
  431. s.sf_tp = sf ? sf.tp : 0;
  432. }
  433. }
  434. return stages;
  435. }
  436. async getNextStages(tenderId, order) {
  437. const sql = 'SELECT * FROM ?? WHERE tid = ? AND `order` > ?';
  438. return await this.db.query(sql, [this.tableName, tenderId, order]);
  439. }
  440. async _getSumTp(condition, ...field) {
  441. const fieldSql = [];
  442. for (const f of field) {
  443. fieldSql.push('SUM(`' + f + '`) as ' + '`' + f + '`');
  444. }
  445. const sql = 'SELECT ' + fieldSql.join(', ') + ' FROM ' + this.tableName + ' ' + this.ctx.helper.whereSql(condition);
  446. return await this.db.queryOne(sql);
  447. }
  448. /**
  449. *
  450. * @param tenderId - 标段id
  451. * @param date - 计量年月
  452. * @param period - 开始-截止日期
  453. * @return {Promise<void>}
  454. */
  455. async addStage(tenderId, date, period) {
  456. const stages = await this.getAllDataByCondition({
  457. where: { tid: tenderId },
  458. orders: [['order', 'DESC']],
  459. });
  460. const preStage = stages[0];
  461. const preCheckedStage = stages.find(x => { return x.status === auditConst.stage.status.checked; });
  462. const order = stages.length + 1;
  463. const newStage = {
  464. sid: this.uuid.v4(),
  465. tid: tenderId,
  466. order,
  467. in_time: new Date(),
  468. s_time: date,
  469. period,
  470. times: 1,
  471. status: auditConst.stage.status.uncheck,
  472. user_id: this.ctx.session.sessionUser.accountId,
  473. check_calc: false,
  474. };
  475. newStage.cache_time_l = newStage.in_time;
  476. newStage.cache_time_r = newStage.in_time;
  477. if (preStage) {
  478. newStage.im_type = preStage.im_type;
  479. newStage.im_pre = preStage.im_pre;
  480. newStage.im_gather = preStage.im_gather;
  481. newStage.im_gather_node = preStage.im_gather_node;
  482. if (preCheckedStage) {
  483. newStage.pre_contract_tp = this.ctx.helper.sum([preCheckedStage.pre_contract_tp, preCheckedStage.contract_tp, preCheckedStage.contract_pc_tp]);
  484. newStage.pre_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_qc_tp, preCheckedStage.qc_tp, preCheckedStage.qc_pc_tp]);
  485. newStage.pre_positive_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_positive_qc_tp, preCheckedStage.positive_qc_tp, preCheckedStage.positive_qc_pc_tp]);
  486. newStage.pre_negative_qc_tp = this.ctx.helper.sum([preCheckedStage.pre_negative_qc_tp, preCheckedStage.negative_qc_tp, preCheckedStage.negative_qc_pc_tp]);
  487. newStage.pre_yf_tp = this.ctx.helper.add(preCheckedStage.pre_yf_tp, preCheckedStage.yf_tp);
  488. if (preCheckedStage.order === 1 || preCheckedStage.pre_sf_tp) {
  489. newStage.pre_sf_tp = this.ctx.helper.add(preCheckedStage.pre_sf_tp, preCheckedStage.sf_tp);
  490. } else {
  491. const sumTp = await this._getSumTp({tid: preCheckedStage.tid}, 'sf_tp');
  492. newStage.pre_sf_tp = sumTp.sf_tp || 0;
  493. }
  494. }
  495. } else {
  496. const projFunRela = await this.ctx.service.project.getFunRela(this.ctx.session.sessionProject.id);
  497. newStage.im_type = projFunRela.imType;
  498. }
  499. const transaction = await this.db.beginTransaction();
  500. try {
  501. // 新增期记录
  502. const result = await transaction.insert(this.tableName, newStage);
  503. if (result.affectedRows === 1) {
  504. newStage.id = result.insertId;
  505. newStage.preCheckedStage = preCheckedStage;
  506. } else {
  507. throw '新增期数据失败';
  508. }
  509. // 存在上一期时,复制上一期审批流程
  510. if (preStage) {
  511. const auditResult = await this.ctx.service.stageAudit.copyPreStageAuditors(transaction, preStage, newStage);
  512. if (!auditResult) {
  513. throw '复制上一期审批流程失败';
  514. }
  515. }
  516. // 新增期合同支付数据
  517. const dealResult = await this.ctx.service.stagePay.addInitialStageData(newStage, transaction);
  518. if (!dealResult) {
  519. throw '新增期合同支付数据失败';
  520. }
  521. // 新增期其他台账数据
  522. let pcTp = { contract_pc_tp: 0, qc_pc_tp: 0, pc_tp: 0, positive_qc_pc_tp: 0, negative_qc_pc_tp: 0 };
  523. if (preCheckedStage) {
  524. const jgclResult = await this.ctx.service.stageJgcl.addInitialStageData(newStage, preCheckedStage, transaction);
  525. if (!jgclResult) throw '初始化甲供材料数据失败';
  526. const otherResult = await this.ctx.service.stageOther.addInitialStageData(newStage, preCheckedStage, transaction);
  527. if (!otherResult) throw '初始化其他台账数据失败';
  528. const safeResult = await this.ctx.service.stageSafeProd.addInitialStageData(newStage, preCheckedStage, transaction);
  529. if (!safeResult) throw '初始化其他台账数据失败';
  530. const tempResult = await this.ctx.service.stageTempLand.addInitialStageData(newStage, preCheckedStage, transaction);
  531. if (!tempResult) throw '初始化其他台账数据失败';
  532. }
  533. if (preStage && preCheckedStage && preStage.order === preCheckedStage.order) {
  534. const priceCalc = new RevisePrice(this.ctx);
  535. pcTp = await priceCalc.newStagePriceChange(newStage, preStage, transaction);
  536. }
  537. if (order === 1 || (preStage && preCheckedStage && preStage.order === preCheckedStage.order)) {
  538. await this.ctx.service.tenderCache.updateStageCache4Add(transaction, newStage, pcTp);
  539. }
  540. // 新增期拷贝报表相关配置/签名角色 等
  541. if (preStage) {
  542. const rptResult = await this.ctx.service.rptCustomDefine.addInitialStageData(newStage, preStage, transaction);
  543. await this.ctx.service.roleRptRel.addInitialStageData(tenderId, newStage, preStage);
  544. }
  545. await transaction.commit();
  546. // 通知发送 - 第三方更新
  547. if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  548. const base_data = {
  549. tid: tenderId,
  550. sid: result.insertId,
  551. op: 'insert',
  552. };
  553. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  554. // 存在上一期时
  555. base_data.op = preStage ? 'update' : 'insert';
  556. base_data.sid = -1;
  557. this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  558. }
  559. return newStage;
  560. } catch (err) {
  561. await transaction.rollback();
  562. throw err;
  563. }
  564. }
  565. /**
  566. * 编辑计量期
  567. *
  568. * @param {Number} tenderId - 标段Id
  569. * @param {Number} order - 第N期
  570. * @param {String} date - 计量年月
  571. * @param {String} period - 开始-截止时间
  572. * @return {Promise<void>}
  573. */
  574. async saveStage(tenderId, order, date, period) {
  575. await this.db.update(this.tableName, {
  576. s_time: date,
  577. period,
  578. }, { where: { tid: tenderId, order } });
  579. }
  580. /**
  581. * 设置 中间计量 生成规则,并生成数据
  582. * @param {Number} tenderId - 标段id
  583. * @param {Number} order - 期序号
  584. * @param {Number} data - 中间计量生成规则
  585. * @return {Promise<void>}
  586. */
  587. async buildDetailData(tenderId, order, data) {
  588. const conn = await this.db.beginTransaction();
  589. try {
  590. 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 } });
  591. // to do 生成中间计量数据
  592. await conn.commit();
  593. } catch (err) {
  594. await conn.rollback();
  595. throw err;
  596. }
  597. }
  598. async getChangeSubtotal(stage) {
  599. const result = {};
  600. const bg = await this.ctx.service.stageChange.getSubtotal(stage);
  601. const importBg = await this.ctx.service.stageImportChange.getSubtotal(stage);
  602. result.common = this.ctx.helper.add(bg.common, importBg.common);
  603. result.great = this.ctx.helper.add(bg.great, importBg.great);
  604. result.more = this.ctx.helper.add(bg.more, importBg.more);
  605. return result;
  606. }
  607. /**
  608. * 获取 当期的 计算基数
  609. * @return {Promise<any>}
  610. */
  611. async getStagePayCalcBase(stage, tenderInfo) {
  612. const calcBase = JSON.parse(JSON.stringify(payConst.calcBase));
  613. const param = tenderInfo.deal_param;
  614. const sum = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  615. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  616. const bg = await this.getChangeSubtotal(stage);
  617. for (const cb of calcBase) {
  618. switch (cb.code) {
  619. case 'htj':
  620. cb.value = param.contractPrice;
  621. break;
  622. case 'zlje':
  623. cb.value = param.zanLiePrice;
  624. break;
  625. case 'htjszl':
  626. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  627. break;
  628. case 'kgyfk':
  629. cb.value = param.startAdvance;
  630. break;
  631. case 'clyfk':
  632. cb.value = param.materialAdvance;
  633. break;
  634. case 'bqwc':
  635. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  636. break;
  637. case 'bqht':
  638. cb.value = sum.contract_tp; //this.ctx.helper.add(sum.contract_tp, pcSum.contract_pc_tp);
  639. break;
  640. case 'bqbg':
  641. cb.value = sum.qc_tp; //this.ctx.helper.add(sum.qc_tp, pcSum.qc_pc_tp);
  642. break;
  643. case 'ybbqwc':
  644. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');
  645. const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGcl(stage, '^[^0-9]*1[0-9]{2}(-|$)');
  646. cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_tp]);
  647. break;
  648. case 'ybbqbg':
  649. cb.value = bg.common;
  650. break;
  651. case 'jdbqbg':
  652. cb.value = bg.more;
  653. break;
  654. case 'zdbqbg':
  655. cb.value = bg.great;
  656. break;
  657. default:
  658. cb.value = 0;
  659. }
  660. }
  661. return calcBase;
  662. }
  663. async updateCheckCalcFlag(stage, check) {
  664. const result = await this.db.update(this.tableName, { id: stage.id, check_calc: check });
  665. return result.affectedRows === 1;
  666. }
  667. async updateCacheTime(sid) {
  668. const result = await this.db.update(this.tableName, { id: sid, cache_time_l: new Date() });
  669. return result.affectedRows === 1;
  670. }
  671. /**
  672. * 删除计量期
  673. *
  674. * @param {Number} id - 期Id
  675. * @return {Promise<void>}
  676. */
  677. async deleteStage(id) {
  678. const stageInfo = await this.getDataById(id);
  679. await this.loadPreCheckedStage(stageInfo);
  680. const transaction = await this.db.beginTransaction();
  681. try {
  682. // 通知发送 - 第三方更新
  683. // if (this.ctx.session.sessionProject.custom && syncApiConst.notice_type.indexOf(this.ctx.session.sessionProject.customType) !== -1) {
  684. // const base_data = {
  685. // tid: this.ctx.tender.id,
  686. // sid: id,
  687. // op: 'delete',
  688. // };
  689. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  690. // // 是否还存在其他期
  691. // base_data.op = stageInfo.order === 1 ? 'delete' : 'update';
  692. // base_data.sid = -1;
  693. // await this.ctx.helper.syncNoticeSend(this.ctx.session.sessionProject.customType, JSON.stringify(base_data));
  694. // }
  695. await transaction.delete(this.tableName, { id });
  696. if (stageInfo.isCheckFirst) await this.ctx.service.tenderCache.updateStageCache4Del(transaction, stageInfo);
  697. await transaction.delete(this.ctx.service.pos.tableName, { add_stage: id });
  698. await transaction.delete(this.ctx.service.stageAudit.tableName, { sid: id });
  699. await transaction.delete(this.ctx.service.stageBills.tableName, { sid: id });
  700. await transaction.delete(this.ctx.service.stageChange.tableName, { sid: id });
  701. await transaction.delete(this.ctx.service.stageChangeFinal.tableName, { sid: id });
  702. await transaction.delete(this.ctx.service.stageImportChange.tableName, { sid: id });
  703. await transaction.delete(this.ctx.service.stagePos.tableName, { sid: id });
  704. await transaction.delete(this.ctx.service.stageDetail.tableName, { sid: id });
  705. await transaction.delete(this.ctx.service.stagePosFinal.tableName, { sid: id });
  706. await transaction.delete(this.ctx.service.stageBillsFinal.tableName, { sid: id });
  707. await transaction.delete(this.ctx.service.stageRela.tableName, { sid: id });
  708. await transaction.delete(this.ctx.service.stageRelaBills.tableName, { sid: id });
  709. await transaction.delete(this.ctx.service.stageRelaBillsFinal.tableName, { sid: id });
  710. await transaction.delete(this.ctx.service.stageRelaIm.tableName, { sid: id });
  711. await transaction.delete(this.ctx.service.stageRelaImBills.tableName, { sid: id });
  712. await transaction.delete(this.ctx.service.stageAuditAss.tableName, { sid: id });
  713. // 删除计量合同支付附件
  714. const payList = await this.ctx.service.stagePay.getAllDataByCondition({ where: { sid: id } });
  715. if (payList) {
  716. for (const pt of payList) {
  717. if (pt.attachment !== null && pt.attachment !== '') {
  718. const payAttList = JSON.parse(pt.attachment);
  719. for (const pat of payAttList) {
  720. if (fs.existsSync(path.join(this.app.baseDir, pat.filepath))) {
  721. await fs.unlinkSync(path.join(this.app.baseDir, pat.filepath));
  722. }
  723. }
  724. }
  725. }
  726. }
  727. await transaction.delete(this.ctx.service.stagePay.tableName, { sid: id });
  728. await this.ctx.service.pay.doDeleteStage(stageInfo, transaction);
  729. // 删除计量附件文件
  730. const attList = await this.ctx.service.stageAtt.getAllDataByCondition({ where: { tid: stageInfo.tid, sid: stageInfo.order } });
  731. if (attList.length !== 0) {
  732. for (const att of attList) {
  733. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  734. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  735. }
  736. }
  737. }
  738. await transaction.delete(this.ctx.service.stageAtt.tableName, { tid: stageInfo.tid, sid: stageInfo.order });
  739. // 其他台账
  740. await transaction.delete(this.ctx.service.stageJgcl.tableName, { sid: id });
  741. const bonus = await this.ctx.service.stageBonus.getStageData(id);
  742. if (bonus && bonus.length > 0) {
  743. for (const b of bonus) {
  744. for (const f of b.proof_file) {
  745. if (fs.existsSync(path.join(this.app.baseDir, f.filepath))) {
  746. await fs.unlinkSync(path.join(this.app.baseDir, f.filepath));
  747. }
  748. }
  749. }
  750. }
  751. await transaction.delete(this.ctx.service.stageBonus.tableName, { sid: id });
  752. await transaction.delete(this.ctx.service.stageOther.tableName, { sid: id });
  753. // 同步删除进度里所选的期
  754. await transaction.delete(this.ctx.service.scheduleStage.tableName, { tid: stageInfo.tid, order: stageInfo.order });
  755. const detailAtt = await this.ctx.service.stageDetailAtt.getAllDataByCondition({ where: { sid: id } });
  756. if (detailAtt && detailAtt.length > 0) {
  757. for (const da of detailAtt) {
  758. da.attachment = da.attachment ? JSON.parse(da.attachment) : [];
  759. for (const daa of da.attachment) {
  760. if (fs.existsSync(path.join(this.app.baseDir, daa.filepath))) {
  761. await fs.unlinkSync(path.join(this.app.baseDir, daa.filepath));
  762. }
  763. }
  764. }
  765. }
  766. await transaction.delete(this.ctx.service.stageDetailAtt.tableName, { sid: id });
  767. // 重算进度计量总金额
  768. await this.ctx.service.scheduleStage.calcStageSjTp(transaction, stageInfo.tid);
  769. // 删除收方单及附件
  770. const shoufangAttList = await this.ctx.service.stageShoufangAtt.getAllDataByCondition({ where: { sid: id } });
  771. if (shoufangAttList.length !== 0) {
  772. for (const att of shoufangAttList) {
  773. if (fs.existsSync(path.join(this.app.baseDir, att.filepath))) {
  774. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  775. }
  776. }
  777. }
  778. await transaction.delete(this.ctx.service.stageShoufangAtt.tableName, { sid: id });
  779. const shoufangList = await this.ctx.service.stageShoufang.getAllDataByCondition({ where: { sid: id } });
  780. if (shoufangList.length !== 0) {
  781. for (const att of shoufangList) {
  782. if (fs.existsSync(path.join(this.app.baseDir, 'app/' + att.qrcode))) {
  783. await fs.unlinkSync(path.join(this.app.baseDir, 'app/' + att.qrcode));
  784. }
  785. }
  786. }
  787. await transaction.delete(this.ctx.service.stageShoufang.tableName, { sid: id });
  788. await transaction.delete(this.ctx.service.cooperationConfirm.tableName, { sid: id });
  789. // 记录删除日志
  790. await this.ctx.service.projectLog.addProjectLog(transaction, projectLogConst.type.stage, projectLogConst.status.delete, '第' + stageInfo.order + '期');
  791. await transaction.commit();
  792. return true;
  793. } catch (err) {
  794. await transaction.rollback();
  795. throw err;
  796. }
  797. }
  798. /**
  799. * 获取 多期的 计算基数 -(材料调差调用)
  800. * @return {Promise<any>}
  801. */
  802. async getMaterialCalcBase(stage_list, tenderInfo) {
  803. const calcBase = JSON.parse(JSON.stringify(payConst.materialCalcBase));
  804. const param = tenderInfo.deal_param;
  805. const sum = await this.ctx.service.stageBills.getSumTotalPriceByMaterial(stage_list);
  806. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPriceByMaterial(stage_list);
  807. for (const cb of calcBase) {
  808. switch (cb.code) {
  809. case 'htj':
  810. cb.value = param.contractPrice;
  811. break;
  812. case 'zlje':
  813. cb.value = param.zanLiePrice;
  814. break;
  815. case 'htjszl':
  816. cb.value = this.ctx.helper.sub(param.contractPrice, param.zanLiePrice);
  817. break;
  818. case 'kgyfk':
  819. cb.value = param.startAdvance;
  820. break;
  821. case 'clyfk':
  822. cb.value = param.materialAdvance;
  823. break;
  824. case 'bqwc':
  825. cb.value = this.ctx.helper.sum([sum.contract_tp, sum.qc_tp, pcSum.pc_tp]);
  826. break;
  827. case 'bqht':
  828. cb.value = sum.contract_tp;
  829. break;
  830. case 'bqbg':
  831. cb.value = sum.qc_tp;
  832. break;
  833. case 'yib':
  834. case 'erb':
  835. case 'sanb':
  836. case 'sib':
  837. case 'wub':
  838. case 'liub':
  839. case 'qib':
  840. case 'bab':
  841. case 'jiub':
  842. const sumGcl = await this.ctx.service.stageBills.getSumTotalPriceGclByMaterial(stage_list, cb.filter);
  843. const sumPc = await this.ctx.service.stageBillsPc.getSumTotalPriceGclByMaterial(stage_list, cb.filter);
  844. cb.value = this.ctx.helper.sum([sumGcl.contract_tp, sumGcl.qc_tp, sumPc.pc_tp]);
  845. break;
  846. case 'bqyf':
  847. cb.value = this.ctx.helper.roundNum(this._.sumBy(stage_list, 'yf_tp'), 2);
  848. break;
  849. default:
  850. cb.value = 0;
  851. }
  852. }
  853. return calcBase;
  854. }
  855. /**
  856. * 获取必要的stage信息调用curTimes, curOrder, id , times, curAuditor(材料调差)
  857. * @param stage_id_list
  858. * @return {Promise<void>}
  859. */
  860. async getStageMsgByStageId(stage_id_list) {
  861. const list = [];
  862. stage_id_list = stage_id_list.toString().split(',');
  863. for (const sid of stage_id_list) {
  864. const stage = await this.getDataById(sid);
  865. stage.auditors = await this.service.stageAudit.getAuditors(stage.id, stage.times);
  866. // todo 不确定是否使用,暂时注释,待测试验证
  867. // stage.curAuditor = await this.service.stageAudit.getCurAuditor(stage.id, stage.times);
  868. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  869. stage.curTimes = stage.times;
  870. list.push(stage);
  871. }
  872. return list;
  873. }
  874. async getStageByDataCollect(tenderId, stage_tp) {
  875. const stages = await this.db.select(this.tableName, {
  876. columns: ['id', 'user_id', 'times', 'status', 's_time', 'contract_tp', 'qc_tp', 'pc_tp', 'pre_contract_tp', 'pre_qc_tp', 'tp_history'],
  877. where: { tid: tenderId },
  878. orders: [['order', 'desc']],
  879. });
  880. if (stages.length > 0 && stages[0].status === auditConst.stage.status.uncheck) {
  881. stages.splice(0, 1);
  882. }
  883. // 最新一期计量(未审批完成),取上一个人的期详细数据,应实时计算
  884. const stage = stages[0];
  885. if (stages.length === 0) return stages;
  886. // await this.checkStageGatherDataByDataCollect(stage);
  887. if (stage.status !== auditConst.stage.status.checked) {
  888. // 批量把stage_tp的值赋值给stage
  889. _.forEach(stage_tp, function(value, key) {
  890. stage[key] = stage_tp[key] ? stage_tp[key] : null;
  891. });
  892. }
  893. for (const s of stages) {
  894. s.tp = this.ctx.helper.sum([s.contract_tp, s.qc_tp, s.pc_tp]);
  895. s.pre_tp = this.ctx.helper.add(s.pre_contract_tp, s.pre_qc_tp);
  896. s.end_tp = this.ctx.helper.add(s.pre_tp, s.tp);
  897. }
  898. return stages;
  899. }
  900. async doCheckStageByDataCollect(stage) {
  901. const status = auditConst.stage.status;
  902. await this.loadStageUser(stage);
  903. if (stage.status === status.checkNo) {
  904. stage.readOnly = false;
  905. const checkNoAudit = await this.service.stageAudit.getDataByCondition({
  906. sid: stage.id, times: stage.times - 1, status: status.checkNo,
  907. });
  908. stage.curTimes = stage.times - 1;
  909. stage.curOrder = checkNoAudit.order;
  910. } else if (stage.status === status.checked) {
  911. stage.readOnly = true;
  912. stage.curTimes = stage.times;
  913. stage.curOrder = _.max(_.map(stage.auditors, 'order'));
  914. } else {
  915. stage.readOnly = false;
  916. stage.curTimes = stage.times;
  917. stage.curOrder = stage.curAuditors[0].order - 1;
  918. }
  919. return stage;
  920. }
  921. async checkStageGatherDataByDataCollect(stage) {
  922. // 最新一期计量(未审批完成),当前操作人的期详细数据,应实时计算
  923. if (stage.status !== auditConst.stage.status.checked) {
  924. await this.doCheckStageByDataCollect(stage);
  925. if (!stage.readOnly && stage.check_calc) {
  926. const tpData = await this.ctx.service.stageBills.getSumTotalPrice(stage);
  927. const pcSum = await this.ctx.service.stageBillsPc.getSumTotalPrice(stage);
  928. stage.contract_tp = tpData.contract_tp;
  929. stage.qc_tp = tpData.qc_tp;
  930. stage.positive_qc_tp = tpData.positive_qc_tp;
  931. stage.negative_qc_tp = tpData.negative_qc_tp;
  932. stage.contract_pc_tp = pcSum.contract_pc_tp;
  933. stage.qc_pc_tp = pcSum.qc_pc_tp;
  934. stage.pc_tp = pcSum.pc_tp;
  935. stage.positive_qc_pc_tp = pcSum.positive_qc_pc_tp;
  936. stage.negative_qc_pc_tp = pcSum.negative_qc_pc_tp;
  937. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  938. const tp = await this.ctx.service.stagePay.getSpecialTotalPrice(stage);
  939. stage.yf_tp = tp.yf;
  940. stage.sf_tp = tp.sf;
  941. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  942. } else if (stage.tp_history) {
  943. const his = this.ctx.helper._.find(stage.tp_history, { times: stage.curTimes, order: stage.curOrder });
  944. if (his) {
  945. stage.contract_tp = his.contract_tp;
  946. stage.qc_tp = his.qc_tp;
  947. stage.positive_qc_tp = his.positive_qc_tp;
  948. stage.negative_qc_tp = his.negative_qc_tp;
  949. stage.yf_tp = his.yf_tp;
  950. stage.sf_tp = his.sf_tp;
  951. stage.tp = this.ctx.helper.sum([stage.contract_tp, stage.qc_tp, stage.pc_tp]);
  952. stage.end_tp = this.ctx.helper.add(stage.pre_tp, stage.tp);
  953. }
  954. }
  955. }
  956. }
  957. async isLastStage(tid, sid) {
  958. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  959. return lastStage ? lastStage.id === sid : false;
  960. }
  961. }
  962. return Stage;
  963. };