stage.js 48 KB

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