stage.js 48 KB

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