stage.js 55 KB

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