stage.js 52 KB

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