stage.js 54 KB

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