stage.js 55 KB

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