change_plan_audit.js 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const auditConst = require('../const/audit').changePlan;
  10. const auditType = require('../const/audit').auditType;
  11. const pushType = require('../const/audit').pushType;
  12. const pushOperate = require('../const/spec_3f').pushOperate;
  13. const shenpiConst = require('../const/shenpi');
  14. const smsTypeConst = require('../const/sms_type');
  15. const SMS = require('../lib/sms');
  16. const SmsAliConst = require('../const/sms_alitemplate');
  17. const wxConst = require('../const/wechat_template');
  18. module.exports = app => {
  19. class ChangePlanAudit extends app.BaseService {
  20. /**
  21. * 构造函数
  22. *
  23. * @param {Object} ctx - egg全局变量
  24. * @return {void}
  25. */
  26. constructor(ctx) {
  27. super(ctx);
  28. this.tableName = 'change_plan_audit';
  29. }
  30. /**
  31. * 获取 审核列表信息
  32. *
  33. * @param {Number} cpId - 变更立项id
  34. * @param {Number} times - 第几次审批
  35. * @return {Promise<*>}
  36. */
  37. async getAuditors(cpId, times = 1, order_sort = 'asc', noYB = false) {
  38. // const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, g.`sort` ' +
  39. // 'FROM ?? AS la, ?? AS pa, (SELECT t1.`aid`,(@i:=@i+1) as `sort` FROM (SELECT t.`aid`, t.`order` FROM (select `aid`, `order` from ?? WHERE `cpid` = ? AND `times` = ? ORDER BY `order` LIMIT 200) t GROUP BY t.`aid` ORDER BY t.`order`) t1, (select @i:=0) as it) as g ' +
  40. // 'WHERE la.`cpid` = ? and la.`times` = ? and la.`aid` = pa.`id` and g.`aid` = la.`aid` order by la.`order`';
  41. // const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, this.tableName, cpId, times, cpId, times];
  42. // const result = await this.db.query(sql, sqlParam);
  43. // const sql2 = 'SELECT COUNT(a.`aid`) as num FROM (SELECT `aid` FROM ?? WHERE `cpid` = ? AND `times` = ? GROUP BY `aid`) as a';
  44. // const sqlParam2 = [this.tableName, cpId, times];
  45. // const count = await this.db.queryOne(sql2, sqlParam2);
  46. // for (const i in result) {
  47. // result[i].max_sort = count.num;
  48. // }
  49. const ybSql = noYB ? ' AND la.audit_order != 0' : '';
  50. const sql = 'SELECT la.id, la.aid, la.times, la.order, la.status, la.opinion, la.begin_time, la.end_time, la.audit_type, la.audit_order,' +
  51. ' pa.name, pa.company, pa.role, pa.mobile, pa.telephone' +
  52. ` FROM ${this.tableName} la LEFT JOIN ${this.ctx.service.projectAccount.tableName} pa ON la.aid = pa.id` +
  53. ' WHERE la.cpid = ? AND la.times = ?' + ybSql +
  54. ' ORDER BY la.order ' + order_sort;
  55. const sqlParam = [cpId, times];
  56. const result = await this.db.query(sql, sqlParam);
  57. const max_sort = this._.max(result.map(x => { return x.audit_order; }));
  58. for (const i in result) {
  59. result[i].max_sort = max_sort;
  60. }
  61. return result;
  62. }
  63. /**
  64. * 获取 当前审核人
  65. *
  66. * @param {Number} cpId - 变更立项id
  67. * @param {Number} times - 第几次审批
  68. * @return {Promise<*>}
  69. */
  70. async getCurAuditor(cpId, times = 1) {
  71. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time` ' +
  72. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  73. ' WHERE la.`cpid` = ? and la.`status` = ? and la.`times` = ?';
  74. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, auditConst.status.checking, times];
  75. return await this.db.queryOne(sql, sqlParam);
  76. }
  77. async getCurAuditors(cpId, times = 1) {
  78. const sql =
  79. 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, pa.`mobile`, pa.`telephone`, la.`times`, la.`order`, la.`status`, la.`opinion`, la.`begin_time`, la.`end_time`, la.audit_type, la.audit_order ' +
  80. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  81. ' WHERE la.`cpid` = ? and la.`status` = ? and la.`times` = ?';
  82. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, auditConst.status.checking, times];
  83. return await this.db.query(sql, sqlParam);
  84. }
  85. /**
  86. * 获取审核人流程列表
  87. *
  88. * @param auditorId
  89. * @return {Promise<*>}
  90. */
  91. async getAuditGroupByList(changeId, times, transaction = false) {
  92. const sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`cpid`, la.`aid`, la.`order`, la.`status`, la.audit_type, la.audit_order ' +
  93. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  94. ' WHERE la.`cpid` = ? and la.`times` = ? and la.`status` != ? and la.`status` != ? GROUP BY la.`aid` ORDER BY la.`order`';
  95. const sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, changeId, times, auditConst.status.revise, auditConst.status.cancelRevise];
  96. return transaction !== false ? await transaction.query(sql, sqlParam) : await this.db.query(sql, sqlParam);
  97. }
  98. /**
  99. * 移除审核人
  100. *
  101. * @param {Number} materialId - 材料调差期id
  102. * @param {Number} status - 期状态
  103. * @param {Number} status - 期次数
  104. * @return {Promise<boolean>}
  105. */
  106. async getAuditorByStatus(cpId, status, times = 1) {
  107. let auditor = null;
  108. let sql = '';
  109. let sqlParam = '';
  110. switch (status) {
  111. case auditConst.status.checking :
  112. case auditConst.status.checked :
  113. case auditConst.status.revise :
  114. case auditConst.status.cancelRevise :
  115. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`cpid`, la.`aid`, la.`order`, la.`status` ' +
  116. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  117. ' WHERE la.`cpid` = ? and la.`status` = ? ' +
  118. ' ORDER BY la.`times` desc, la.`order` desc';
  119. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, status];
  120. auditor = await this.db.queryOne(sql, sqlParam);
  121. break;
  122. case auditConst.status.checkNo :
  123. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`cpid`, la.`aid`, la.`order`, la.`status` ' +
  124. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id`' +
  125. ' WHERE la.`cpid` = ? and la.`status` = ? and la.`times` = ?' +
  126. ' ORDER BY la.`times` desc, la.`order` desc';
  127. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, auditConst.status.checkNo, parseInt(times) - 1];
  128. auditor = await this.db.queryOne(sql, sqlParam);
  129. break;
  130. case auditConst.status.uncheck :
  131. break;
  132. default:break;
  133. }
  134. return auditor;
  135. }
  136. async getAuditorsByStatus(cpId, status, times = 1) {
  137. let auditor = [];
  138. let sql = '';
  139. let sqlParam = '';
  140. let cur;
  141. switch (status) {
  142. case auditConst.status.checking :
  143. case auditConst.status.checked :
  144. case auditConst.status.revise :
  145. case auditConst.status.cancelRevise :
  146. cur = await this.db.queryOne('SELECT * From ?? where cpid = ? AND times = ? AND status = ? ORDER By times DESC, `order` DESC', [this.tableName, cpId, times, status]);
  147. if (!cur) return [];
  148. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`cpid`, la.`order`, la.`status`, la.`audit_order`, la.`audit_type` ' +
  149. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  150. ' WHERE la.`cpid` = ? and la.`order` = ? and times = ?';
  151. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, cur.order, times];
  152. auditor = await this.db.query(sql, sqlParam);
  153. break;
  154. case auditConst.status.checkNo :
  155. cur = await this.db.queryOne('SELECT * From ?? where cpid = ? AND times = ? AND status = ? ORDER By times DESC, `order` DESC', [this.tableName, cpId, parseInt(times) - 1, status]);
  156. if (!cur) return [];
  157. sql = 'SELECT la.`aid`, pa.`name`, pa.`company`, pa.`role`, la.`times`, la.`cpid`, la.`order`, la.`status`, la.`audit_order`, la.`audit_type` ' +
  158. ' FROM ?? AS la Left Join ?? AS pa On la.`aid` = pa.`id` ' +
  159. ' WHERE la.`cpid` = ? and la.`order` = ? and la.`times` = ?';
  160. sqlParam = [this.tableName, this.ctx.service.projectAccount.tableName, cpId, cur.order, parseInt(times) - 1];
  161. auditor = await this.db.query(sql, sqlParam);
  162. break;
  163. case auditConst.status.uncheck:
  164. default:
  165. break;
  166. }
  167. return auditor;
  168. }
  169. async getLastAudit(cpid, times, transaction = null) {
  170. const sql = 'SELECT * FROM ?? WHERE `cpid` = ? AND `times` = ? ORDER BY `order` DESC';
  171. const sqlParam = [this.tableName, cpid, times];
  172. return transaction ? await transaction.queryOne(sql, sqlParam) : await this.db.queryOne(sql, sqlParam);
  173. }
  174. /**
  175. * 获取审核人流程列表(包括原报)
  176. * @param {Number} materialId 调差id
  177. * @param {Number} times 审核次数
  178. * @return {Promise<Array>} 查询结果集(包括原报)
  179. */
  180. async getAuditorsWithOwner(cpId, times = 1) {
  181. const result = await this.getAuditGroupByList(cpId, times);
  182. const sql =
  183. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As cpid, 0 As `order`' +
  184. ' FROM ' +
  185. this.ctx.service.changePlan.tableName +
  186. ' As s' +
  187. ' LEFT JOIN ' +
  188. this.ctx.service.projectAccount.tableName +
  189. ' As pa' +
  190. ' ON s.uid = pa.id' +
  191. ' WHERE s.id = ?';
  192. const sqlParam = [times, cpId, cpId];
  193. const user = await this.db.queryOne(sql, sqlParam);
  194. result.unshift(user);
  195. return result;
  196. }
  197. /**
  198. * 新增审核人
  199. *
  200. * @param {Number} cpId - 方案id
  201. * @param {Number} auditorId - 审核人id
  202. * @param {Number} times - 第几次审批
  203. * @return {Promise<number>}
  204. */
  205. async addAuditor(cpId, auditorId, times = 1, is_gdzs = 0) {
  206. const transaction = await this.db.beginTransaction();
  207. let flag = false;
  208. try {
  209. let [newOrder, newAuditOrder] = await this.getNewOrder(cpId, times);
  210. // 判断是否存在固定终审,存在则newOrder - 1并使终审order+1
  211. newOrder = is_gdzs === 1 ? newOrder - 1 : newOrder;
  212. newAuditOrder = is_gdzs === 1 ? newAuditOrder - 1 : newAuditOrder;
  213. if (is_gdzs) await this._syncOrderByDelete(transaction, cpId, newOrder, times, '+');
  214. const data = {
  215. tid: this.ctx.tender.id,
  216. cpid: cpId,
  217. aid: auditorId,
  218. times,
  219. order: newOrder,
  220. status: auditConst.status.uncheck,
  221. audit_order: newAuditOrder,
  222. };
  223. const result = await transaction.insert(this.tableName, data);
  224. await transaction.commit();
  225. flag = result.effectRows = 1;
  226. } catch (err) {
  227. await transaction.rollback();
  228. throw err;
  229. }
  230. return flag;
  231. }
  232. /**
  233. * 获取 最新审核顺序
  234. *
  235. * @param {Number} cpId - 方案id
  236. * @param {Number} times - 第几次审批
  237. * @return {Promise<number>}
  238. */
  239. async getNewOrder(cpId, times = 1) {
  240. const sql = 'SELECT Max(`order`) As max_order, Max(audit_order) As max_audit_order FROM ?? Where `cpid` = ? and `times` = ?';
  241. const sqlParam = [this.tableName, cpId, times];
  242. const result = await this.db.queryOne(sql, sqlParam);
  243. return result && result.max_order ? [result.max_order + 1, result.max_audit_order + 1] : [1, 1];
  244. }
  245. /**
  246. * 移除审核人
  247. *
  248. * @param {Number} cpId - 变更方案id
  249. * @param {Number} auditorId - 审核人id
  250. * @param {Number} times - 第几次审批
  251. * @return {Promise<boolean>}
  252. */
  253. async deleteAuditor(cpId, auditorId, times = 1) {
  254. const transaction = await this.db.beginTransaction();
  255. try {
  256. const condition = { cpid: cpId, aid: auditorId, times };
  257. const auditor = await this.getDataByCondition(condition);
  258. if (!auditor) {
  259. throw '该审核人不存在';
  260. }
  261. await transaction.delete(this.tableName, { cpid: cpId, order: auditor.order, times });
  262. await this._syncOrderByDelete(transaction, cpId, auditor.order, times);
  263. await transaction.commit();
  264. } catch (err) {
  265. await transaction.rollback();
  266. throw err;
  267. }
  268. return true;
  269. }
  270. /**
  271. * 移除审核人时,同步其后审核人order
  272. * @param transaction - 事务
  273. * @param {Number} cpId - 变更方案id
  274. * @param {Number} auditorId - 审核人id
  275. * @param {Number} times - 第几次审批
  276. * @return {Promise<*>}
  277. * @private
  278. */
  279. async _syncOrderByDelete(transaction, cpId, order, times, selfOperate = '-') {
  280. this.initSqlBuilder();
  281. this.sqlBuilder.setAndWhere('cpid', {
  282. value: cpId,
  283. operate: '=',
  284. });
  285. this.sqlBuilder.setAndWhere('order', {
  286. value: order,
  287. operate: '>=',
  288. });
  289. this.sqlBuilder.setAndWhere('times', {
  290. value: times,
  291. operate: '=',
  292. });
  293. this.sqlBuilder.setUpdateData('order', {
  294. value: 1,
  295. selfOperate,
  296. });
  297. this.sqlBuilder.setUpdateData('audit_order', {
  298. value: 1,
  299. selfOperate,
  300. });
  301. const [sql, sqlParam] = this.sqlBuilder.build(this.tableName, 'update');
  302. const data = await transaction.query(sql, sqlParam);
  303. return data;
  304. }
  305. /**
  306. * 开始审批
  307. * @param {Number} cpId - 方案id
  308. * @param {Number} times - 第几次审批
  309. * @return {Promise<boolean>}
  310. */
  311. async start(cpId, times = 1) {
  312. const audits = await this.getAllDataByCondition({ where: { cpid: cpId, times, order: 1 } });
  313. if (audits.length === 0) {
  314. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  315. throw '请联系管理员添加审批人';
  316. } else {
  317. throw '请先选择审批人,再上报数据';
  318. }
  319. }
  320. const transaction = await this.db.beginTransaction();
  321. try {
  322. const begin_time = new Date();
  323. const updateData = audits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time }; });
  324. await transaction.updateRows(this.tableName, updateData);
  325. await transaction.update(this.ctx.service.changePlan.tableName, {
  326. id: cpId, status: auditConst.status.checking,
  327. });
  328. // 微信模板通知
  329. const shenpiUrl = await this.ctx.helper.urlToShort(
  330. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/plan/' + cpId + '/information#shenpi'
  331. );
  332. const wechatData = {
  333. type: 'plan',
  334. wap_url: shenpiUrl,
  335. status: wxConst.status.check,
  336. tips: wxConst.tips.check,
  337. code: this.ctx.session.sessionProject.code,
  338. c_name: this.ctx.change.name,
  339. };
  340. await this.ctx.helper.sendWechat(this._.map(audits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  341. for (const audit of audits) {
  342. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  343. pid: this.ctx.session.sessionProject.id,
  344. tid: this.ctx.tender.id,
  345. uid: audit.aid,
  346. sp_type: 'change',
  347. sp_id: audit.id,
  348. table_name: this.tableName,
  349. template: wxConst.template.change,
  350. wx_data: wechatData,
  351. });
  352. }
  353. // 检查三方特殊推送
  354. await this.ctx.service.specMsg.addChangePlanMsg(transaction, this.ctx.session.sessionProject.id, this.ctx.change, pushOperate.change_plan.flow);
  355. await transaction.delete(this.ctx.service.changePlanHistory.tableName, { cpid: cpId });
  356. // todo 更新标段tender状态 ?
  357. await transaction.commit();
  358. } catch (err) {
  359. await transaction.rollback();
  360. throw err;
  361. }
  362. return true;
  363. }
  364. /**
  365. * 获取审核人需要审核的期列表
  366. *
  367. * @param auditorId
  368. * @return {Promise<*>}
  369. */
  370. async getAuditChangePlan(auditorId) {
  371. const sql = 'SELECT ma.`aid`, ma.`times`, ma.`order`, ma.`begin_time`, ma.`end_time`, ma.`tid`, ma.`cpid`,' +
  372. ' m.`status` As `mstatus`, m.`code` As `mcode`,' +
  373. ' t.`name`, t.`project_id`, t.`type`, t.`user_id` ' +
  374. ' FROM ?? AS ma LEFT JOIN ?? AS m ON ma.`cpid` = m.`id` LEFT JOIN ?? As t ON ma.`tid` = t.`id`' +
  375. ' WHERE ((ma.`aid` = ? and ma.`status` = ?) OR (m.`uid` = ? and ma.`status` = ? and m.`status` = ? and ma.`times` = (m.`times`-1)))' +
  376. ' ORDER BY ma.`begin_time` DESC';
  377. const sqlParam = [this.tableName, this.ctx.service.changePlan.tableName, this.ctx.service.tender.tableName, auditorId, auditConst.status.checking, auditorId, auditConst.status.checkNo, auditConst.status.checkNo];
  378. const result = await this.db.query(sql, sqlParam);
  379. // 过滤result中存在重复sid的值, 保留最新的一条
  380. const filterResult = [];
  381. const cpidArr = [];
  382. for (const r of result) {
  383. if (cpidArr.indexOf(r.cpid) === -1) {
  384. filterResult.push(r);
  385. cpidArr.push(r.cpid);
  386. }
  387. }
  388. return filterResult;
  389. }
  390. /**
  391. * 获取审核人审核的次数
  392. *
  393. * @param auditorId
  394. * @return {Promise<*>}
  395. */
  396. async getCountByChecked(auditorId) {
  397. return await this.db.count(this.tableName, { aid: auditorId, status: [auditConst.status.checked, auditConst.status.checkNo] });
  398. }
  399. /**
  400. * 获取最近一次审批结束时间
  401. *
  402. * @param auditorId
  403. * @return {Promise<*>}
  404. */
  405. async getLastEndTimeByChecked(auditorId) {
  406. const sql = 'SELECT `end_time` FROM ?? WHERE `aid` = ? ' +
  407. 'AND `status` in (' + this.ctx.helper.getInArrStrSqlFilter([auditConst.status.checked, auditConst.status.checkNo]) + ') ORDER BY `end_time` DESC';
  408. const sqlParam = [this.tableName, auditorId];
  409. const result = await this.db.queryOne(sql, sqlParam);
  410. return result ? result.end_time : null;
  411. }
  412. /**
  413. * 用于添加推送所需的content内容
  414. * @param {Number} pid 项目id
  415. * @param {Number} tid 台账id
  416. * @param {Number} cpId 方案id
  417. * @param {Number} uid 审批人id
  418. */
  419. async getNoticeContent(pid, tid, cpId, uid, opinion = '') {
  420. const noticeSql = 'SELECT * FROM (SELECT ' +
  421. ' t.`id` As `tid`, ma.`cpid`, m.`code` as `c_code`, t.`name`, pa.`name` As `su_name`, pa.role As `su_role`' +
  422. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  423. ' LEFT JOIN ?? As m On t.`id` = m.`tid` AND m.`id` = ?' +
  424. ' LEFT JOIN ?? As ma ON m.`id` = ma.`cpid`' +
  425. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  426. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  427. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.changePlan.tableName, cpId, this.tableName, this.ctx.service.projectAccount.tableName, uid, pid];
  428. const content = await this.db.query(noticeSql, noticeSqlParam);
  429. if (content.length) {
  430. content[0].opinion = opinion;
  431. }
  432. return content.length ? JSON.stringify(content[0]) : '';
  433. }
  434. /**
  435. * 审批
  436. * @param {Number} cpId - 方案id
  437. * @param {auditConst.status.checked|auditConst.status.checkNo} checkType - 审批结果
  438. * @param {Number} times - 第几次审批
  439. * @return {Promise<void>}
  440. */
  441. async check(cpId, checkData, times = 1) {
  442. if (checkData.checkType !== auditConst.status.checked && checkData.checkType !== auditConst.status.checkNo) {
  443. throw '提交数据错误';
  444. }
  445. const pid = this.ctx.session.sessionProject.id;
  446. switch (checkData.checkType) {
  447. case auditConst.status.checked:
  448. await this._checked(pid, cpId, checkData, times);
  449. break;
  450. case auditConst.status.checkNo:
  451. await this._checkNo(pid, cpId, checkData, times);
  452. break;
  453. default:
  454. throw '无效审批操作';
  455. }
  456. }
  457. async _checked(pid, cpId, checkData, times) {
  458. const accountId = this.ctx.session.sessionUser.accountId;
  459. const time = new Date();
  460. // 整理当前流程审核人状态更新
  461. const audits = await this.getAllDataByCondition({ where: { cpid: cpId, times, status: auditConst.status.checking } });
  462. if (audits.length === 0) throw '审核数据错误';
  463. const selfAudit = audits.find(x => { return x.aid === accountId; });
  464. if (!selfAudit) throw '当前标段您无权审批';
  465. // const flowAudits = await this.getAllDataByCondition({ where: { cpid: cpId, times, order: selfAudit.order } });
  466. const nextAudits = await this.getAllDataByCondition({ where: { cpid: cpId, times, order: selfAudit.order + 1 } });
  467. const transaction = await this.db.beginTransaction();
  468. try {
  469. // 更新本人审批状态
  470. await transaction.update(this.tableName, {
  471. id: selfAudit.id,
  472. status: checkData.checkType,
  473. opinion: checkData.opinion,
  474. end_time: time,
  475. });
  476. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, selfAudit.id);
  477. // 获取推送必要信息
  478. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, cpId, selfAudit.aid, checkData.opinion);
  479. // 添加推送
  480. const records = [];
  481. const auditors = await this.getAuditorsWithOwner(cpId, times);
  482. auditors.forEach(audit => {
  483. records.push({ pid, type: pushType.changePlan, uid: audit.aid, status: auditConst.status.checked, content: noticeContent });
  484. });
  485. await transaction.insert('zh_notice', records);
  486. if (audits.length === 1 || selfAudit.audit_type !== auditType.key.and) {
  487. // 或签更新他人审批状态
  488. if (selfAudit.audit_type === auditType.key.or) {
  489. const updateOther = [];
  490. for (const audit of audits) {
  491. if (audit.aid === selfAudit.aid) continue;
  492. updateOther.push({
  493. id: audit.id,
  494. status: auditConst.status.checkSkip,
  495. opinion: '',
  496. end_time: time,
  497. });
  498. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, audit.id);
  499. }
  500. if (updateOther.length > 0) transaction.updateRows(this.tableName, updateOther);
  501. }
  502. // 清单审批流程修改的数据插入到audit_amount中,审批完成则最后一位并插入到审批后变更值中
  503. await this.ctx.service.changePlanList.insertAuditAmount(transaction, cpId, nextAudits.length === 0);
  504. // 无下一审核人表示,审核结束
  505. if (nextAudits.length > 0) {
  506. // 流程至下一审批人
  507. const updateData = nextAudits.map(x => { return { id: x.id, status: auditConst.status.checking, begin_time: time }; });
  508. await transaction.updateRows(this.tableName, updateData);
  509. // 同步 期信息
  510. await transaction.update(this.ctx.service.changePlan.tableName, {
  511. id: cpId, status: auditConst.status.checking,
  512. });
  513. // 微信模板通知
  514. const shenpiUrl = await this.ctx.helper.urlToShort(
  515. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/plan/' + cpId + '/information#shenpi'
  516. );
  517. const wechatData = {
  518. type: 'plan',
  519. wap_url: shenpiUrl,
  520. status: wxConst.status.check,
  521. tips: wxConst.tips.check,
  522. code: this.ctx.session.sessionProject.code,
  523. c_name: this.ctx.change.name,
  524. };
  525. await this.ctx.helper.sendWechat(this._.map(nextAudits, 'aid'), smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  526. for (const nextAudit of nextAudits) {
  527. await this.ctx.service.noticeAgain.addNoticeAgain(transaction, smsTypeConst.const.BG, {
  528. pid: this.ctx.session.sessionProject.id,
  529. tid: this.ctx.tender.id,
  530. uid: nextAudit.aid,
  531. sp_type: 'change',
  532. sp_id: nextAudit.id,
  533. table_name: this.tableName,
  534. template: wxConst.template.change,
  535. wx_data: wechatData,
  536. });
  537. }
  538. // 检查三方特殊推送
  539. await this.ctx.service.specMsg.addChangePlanMsg(transaction, pid, this.ctx.change, pushOperate.change_plan.flow);
  540. } else {
  541. // 本期结束
  542. // 生成截止本期数据 final数据
  543. // 同步 期信息
  544. await transaction.update(this.ctx.service.changePlan.tableName, {
  545. id: cpId, status: checkData.checkType,
  546. decimal: JSON.stringify(this.ctx.change.decimal),
  547. });
  548. // 微信模板通知
  549. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  550. const shenpiUrl = await this.ctx.helper.urlToShort(
  551. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/plan/' + cpId + '/information#shenpi'
  552. );
  553. const wechatData = {
  554. type: 'plan',
  555. wap_url: shenpiUrl,
  556. status: wxConst.status.success,
  557. tips: wxConst.tips.success,
  558. code: this.ctx.session.sessionProject.code,
  559. c_name: this.ctx.change.name,
  560. };
  561. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  562. // 检查三方特殊推送
  563. await this.ctx.service.specMsg.addChangePlanMsg(transaction, pid, this.ctx.change, pushOperate.change_plan.flow);
  564. }
  565. } else {
  566. // 同步 期信息
  567. await transaction.update(this.ctx.service.changePlan.tableName, {
  568. id: cpId,
  569. status: auditConst.status.checking,
  570. });
  571. }
  572. await transaction.commit();
  573. } catch (err) {
  574. await transaction.rollback();
  575. throw err;
  576. }
  577. }
  578. async _checkNo(pid, cpId, checkData, times) {
  579. const accountId = this.ctx.session.sessionUser.accountId;
  580. const time = new Date();
  581. const changeData = await this.ctx.service.changePlan.getDataById(cpId);
  582. const audits = await this.getAllDataByCondition({ where: { cpid: cpId, times, status: auditConst.status.checking } });
  583. if (!audits) throw '审核数据错误';
  584. const selfAudit = audits.find(x => { return x.aid === accountId; });
  585. if (!selfAudit) throw '当前标段您无权审批';
  586. // const flowAudits = await this.getAllDataByCondition({ where: { cpid: cpId, times: selfAudit.times, order: selfAudit.order } });
  587. const auditors = await this.getUniqAuditor(cpId, times); // 全部参与的审批人
  588. const newAuditors = auditors.map(x => {
  589. return {
  590. aid: x.aid, tid: selfAudit.tid, cpid: selfAudit.cpid,
  591. times: times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  592. audit_type: x.audit_type, audit_order: x.audit_order,
  593. };
  594. });
  595. const transaction = await this.db.beginTransaction();
  596. try {
  597. const updateData = [];
  598. audits.forEach(x => {
  599. updateData.push({
  600. id: x.id,
  601. status: x.aid === selfAudit.aid ? checkData.checkType : auditConst.status.checkSkip,
  602. opinion: x.aid === selfAudit.aid ? checkData.opinion : '',
  603. end_time: x.aid === selfAudit.aid ? time : null,
  604. });
  605. });
  606. await transaction.updateRows(this.tableName, updateData);
  607. await this.ctx.service.noticeAgain.stopNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  608. // 添加到消息推送表
  609. const noticeContent = await this.getNoticeContent(pid, selfAudit.tid, cpId, selfAudit.aid, checkData.opinion);
  610. const records = [{ pid, type: pushType.changePlan, uid: this.ctx.change.uid, status: auditConst.status.checkNo, content: noticeContent }];
  611. auditors.forEach(audit => {
  612. records.push({ pid, type: pushType.changePlan, uid: audit.aid, status: auditConst.status.checkNo, content: noticeContent });
  613. });
  614. await transaction.insert(this.ctx.service.noticePush.tableName, records);
  615. // 同步期信息
  616. await transaction.update(this.ctx.service.changePlan.tableName, {
  617. id: cpId, status: checkData.checkType,
  618. times: times + 1,
  619. });
  620. // 拷贝新一次审核流程列表
  621. await transaction.insert(this.tableName, newAuditors);
  622. // 清单审批值删除并重算变更金额
  623. await this.ctx.service.changePlanList.delAuditAmount(transaction, cpId);
  624. // 微信模板通知
  625. const users = this._.uniq(this._.concat(this._.map(auditors, 'aid'), this.ctx.change.uid));
  626. const shenpiUrl = await this.ctx.helper.urlToShort(
  627. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + this.ctx.tender.id + '/change/plan/' + cpId + '/information#shenpi'
  628. );
  629. const wechatData = {
  630. type: 'plan',
  631. wap_url: shenpiUrl,
  632. status: wxConst.status.back,
  633. tips: wxConst.tips.back,
  634. code: this.ctx.session.sessionProject.code,
  635. c_name: this.ctx.change.name,
  636. };
  637. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  638. // 检查三方特殊推送
  639. await this.ctx.service.specMsg.addChangePlanMsg(transaction, pid, this.ctx.change, pushOperate.change_plan.flow);
  640. // 生成内容保存表至zh_change_project_history中,用于撤回
  641. // 回退spamount值数据
  642. const changeList = await this.ctx.service.changePlanList.getAllDataByCondition({
  643. where: { cpid: cpId },
  644. });
  645. await this.ctx.service.changePlanHistory.saveHistory(transaction, changeData, changeList);
  646. await transaction.commit();
  647. } catch (err) {
  648. await transaction.rollback();
  649. throw err;
  650. }
  651. }
  652. /**
  653. * 复制上一期的审批人列表给最新一期
  654. *
  655. * @param transaction - 新增一期的事务
  656. * @param {Object} preMaterial - 上一期
  657. * @param {Object} newaMaterial - 最新一期
  658. * @return {Promise<*>}
  659. */
  660. async copyPreChangePlanAuditors(transaction, preChange, newChange) {
  661. const auditList = await this.getUniqAuditor(preChange.id, preChange.times); // 全部参与的审批人
  662. const newAuditors = [];
  663. for (const x of auditList) {
  664. if (x.audit_order !== 0) {
  665. newAuditors.push({
  666. tid: preChange.tid, cpid: newChange.id, aid: x.aid,
  667. times: 1, order: x.audit_order, status: auditConst.status.uncheck,
  668. audit_type: x.audit_type, audit_order: x.audit_order,
  669. });
  670. }
  671. }
  672. const result = newAuditors.length > 0 ? await transaction.insert(this.tableName, newAuditors) : null;
  673. return result ? result.affectedRows === newAuditors.length : true;
  674. }
  675. async getAllAuditors(tenderId) {
  676. const sql = 'SELECT ma.aid, ma.tid FROM ' + this.tableName + ' ma' +
  677. ' LEFT JOIN ' + this.ctx.service.tender.tableName + ' t On ma.tid = t.id' +
  678. ' WHERE t.id = ?' +
  679. ' GROUP BY ma.aid';
  680. const sqlParam = [tenderId];
  681. return this.db.query(sql, sqlParam);
  682. }
  683. /**
  684. * 取待审批期列表(wap用)
  685. *
  686. * @param auditorId
  687. * @return {Promise<*>}
  688. */
  689. async getAuditChangePlanByWap(auditorId) {
  690. const sql =
  691. 'SELECT sa.`aid`, sa.`times`, sa.`begin_time`, sa.`end_time`, sa.`tid`, sa.`cpid`,' +
  692. ' s.*,' +
  693. ' t.`name` as `t_name`, t.`project_id`, t.`type`, t.`user_id`,' +
  694. ' ti.`deal_info`, ti.`decimal` ' +
  695. ' FROM ?? AS sa' +
  696. ' Left Join ?? AS s On sa.`cpid` = s.`id`' +
  697. ' Left Join ?? As t On sa.`tid` = t.`id`' +
  698. ' Left Join ?? AS ti ON ti.`tid` = t.`id`' +
  699. ' WHERE sa.`aid` = ? and sa.`status` = ?';
  700. const sqlParam = [
  701. this.tableName,
  702. this.ctx.service.changePlan.tableName,
  703. this.ctx.service.tender.tableName,
  704. this.ctx.service.tenderInfo.tableName,
  705. auditorId,
  706. auditConst.status.checking,
  707. ];
  708. return await this.db.query(sql, sqlParam);
  709. }
  710. /**
  711. * 审批撤回
  712. * @param {Number} stageId - 标段id
  713. * @param {Number} times - 第几次审批
  714. * @return {Promise<void>}
  715. */
  716. async checkCancel(change) {
  717. // 分4种情况,根据ctx.cancancel值判断:
  718. // 1.原报发起撤回,当前流程删除,并回到待上报
  719. // 2.审批人撤回审批通过,增加流程,并回到它审批中
  720. // 4.审批人撤回退回原报操作,删除新增的审批流,增加流程,回滚到它审批中
  721. // 5.会签审批人撤回审批通过(还有其他审批人未审批通过),仅修改本人流程状态
  722. switch (change.cancancel) {
  723. case 1: await this._userCheckCancel(change); break;
  724. case 2: await this._auditCheckCancel(change); break;
  725. case 4: await this._auditCheckCancelNo(change); break;
  726. case 5: await this._auditCheckCancelAnd(change); break;
  727. default: throw '不可撤回,请刷新页面重试';
  728. }
  729. }
  730. /**
  731. * 原报撤回,直接改动审批人状态
  732. * 如果存在审批人数据,将其改为原报流程数据,但保留原提交人
  733. *
  734. * 一审 1 A checking -> A uncheck status改 pay/jl:删0(jl为增量数据,只删重复部分) 1->0 删1
  735. * ...
  736. *
  737. * @param stage
  738. * @returns {Promise<void>}
  739. * @private
  740. */
  741. async _userCheckCancel(change) {
  742. const transaction = await this.db.beginTransaction();
  743. try {
  744. // 整理当前流程审核人状态更新
  745. // 审批人变成待审批状态
  746. const updateData = change.curAuditors.map(x => {
  747. return {
  748. id: x.id,
  749. status: auditConst.status.uncheck,
  750. begin_time: null, opinion: null,
  751. };
  752. });
  753. await transaction.updateRows(this.tableName, updateData);
  754. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(updateData, 'id'));
  755. // 清单审批值删除并重算变更金额
  756. await this.ctx.service.changePlanList.delAuditAmount(transaction, change.id);
  757. // 变成待上报状态
  758. await transaction.update(this.ctx.service.changePlan.tableName, {
  759. id: change.id,
  760. status: change.times === 1 ? auditConst.status.uncheck : auditConst.status.checkNo,
  761. });
  762. await transaction.commit();
  763. } catch (err) {
  764. await transaction.rollback();
  765. throw err;
  766. }
  767. }
  768. /**
  769. * 审批人撤回审批通过,插入两条数据
  770. *
  771. * 一审 1 A checked 一审 1 A checked
  772. * 二审 2 B checked pre -> 二审 2 B checked
  773. * 三审 3 C checking cur 二审 3 B checkCancel 增 增extra_his 增tp_his
  774. * 四审 4 D uncheck 二审 4 B checking 增 增pay_cur
  775. * 三审 5 C uncheck order、status改
  776. * 四审 6 D uncheck order改
  777. *
  778. * @param stage
  779. * @returns {Promise<void>}
  780. * @private
  781. */
  782. async _auditCheckCancel(change) {
  783. if (change.curAuditors.length === 0 || change.curAuditors[0].order <= 1) {
  784. throw '撤回用户数据错误';
  785. }
  786. const accountId = this.ctx.session.sessionUser.accountId;
  787. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId; });
  788. if (!selfAuditor) throw '撤回用户数据错误';
  789. const time = new Date();
  790. const transaction = await this.db.beginTransaction();
  791. try {
  792. // 顺移其后审核人流程顺序
  793. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE cpid = ? AND times = ? AND `order` > ?';
  794. await transaction.query(sql, [change.id, selfAuditor.times, change.curAuditors[0].order]);
  795. // 当前审批人2次添加至流程中
  796. const checkCancelAuditors = [],
  797. checkingAuditors = [];
  798. change.preAuditors.forEach(x => {
  799. checkCancelAuditors.push({
  800. tid: change.tid, cpid: change.id, aid: x.aid,
  801. times: x.times, order: x.order + 1,
  802. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  803. begin_time: time, end_time: time, opinion: '',
  804. audit_type: x.audit_type, audit_order: x.audit_order,
  805. });
  806. });
  807. change.preAuditors.forEach(x => {
  808. checkingAuditors.push({
  809. tid: change.tid, cpid: change.id, aid: x.aid,
  810. times: x.times, order: x.order + 2,
  811. status: auditConst.status.checking,
  812. begin_time: time, end_time: time, opinion: '',
  813. audit_type: x.audit_type, audit_order: x.audit_order,
  814. });
  815. });
  816. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  817. // 当前审批人变成待审批
  818. await transaction.updateRows(this.tableName, change.curAuditors.map(x => {
  819. return { id: x.id, begin_time: null, status: auditConst.status.uncheck, order: x.order + 2 };
  820. }));
  821. await this.ctx.service.noticeAgain.deleteNoticeAgain(transaction, this.tableName, this._.map(change.curAuditors, 'id'));
  822. // 清除上一人的值并调整spamount值
  823. const updateList = [];
  824. const changeList = await this.ctx.service.changePlanList.getAllDataByCondition({
  825. where: { cpid: change.id },
  826. });
  827. for (const cl of changeList) {
  828. const audit_amount = cl.audit_amount.split(',');
  829. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  830. audit_amount.splice(-1, 1);
  831. const list_update = {
  832. id: cl.id,
  833. audit_amount: audit_amount.join(','),
  834. spamount: parseFloat(last_amount),
  835. };
  836. updateList.push(list_update);
  837. }
  838. if (updateList.length > 0) await transaction.updateRows(this.ctx.service.changePlanList.tableName, updateList);
  839. // 更新total_price
  840. await this.ctx.service.changePlanList.calcCamountSum(transaction);
  841. await transaction.commit();
  842. } catch (err) {
  843. await transaction.rollback();
  844. throw err;
  845. }
  846. }
  847. /**
  848. * 审批人撤回审批退回原报
  849. *
  850. * 1# 一审 1 A checked 1# 一审 1 A checked
  851. * 二审 2 B checkNo pre -> 二审 2 B checkNo
  852. * 三审 3 C uncheck 二审 3 B checkCancel 增 pay: 2#0 -> 1#3 jl: 2#0 -> 1#3 增tp_his 增extra_his
  853. * 二审 4 B checking 增 pay: 2#0 -> 1#4
  854. * 三审 5 C uncheck order改
  855. *
  856. * 2# 一审 1 A uncheck 2# 删 pay: 2#0删 jl: 2#0删
  857. * 二审 2 B uncheck
  858. * 三审 3 C uncheck
  859. *
  860. * @param stage
  861. * @returns {Promise<void>}
  862. * @private
  863. */
  864. async _auditCheckCancelNo(change) {
  865. const accountId = this.ctx.session.sessionUser.accountId;
  866. const selfAuditor = change.preAuditors.find(x => { return x.aid === accountId && x.status === auditConst.status.checkNo; });
  867. if (!selfAuditor) throw '该标段由他人审批退回,您不可撤回';
  868. const time = new Date();
  869. const transaction = await this.db.beginTransaction();
  870. try {
  871. // 整理上一个流程审核人状态更新
  872. // 顺移其后审核人流程顺序
  873. const sql = 'UPDATE ' + this.tableName + ' SET `order` = `order` + 2 WHERE cpid = ? AND times = ? AND `order` > ?';
  874. await transaction.query(sql, [change.id, selfAuditor.times, selfAuditor.order]);
  875. // 当前审批人2次添加至流程中
  876. const checkCancelAuditors = [],
  877. checkingAuditors = [];
  878. change.preAuditors.forEach(x => {
  879. checkCancelAuditors.push({
  880. tid: change.tid, cpid: change.id, aid: x.aid,
  881. times: x.times, order: x.order + 1,
  882. status: x.aid === selfAuditor.aid ? auditConst.status.checkCancel : auditConst.status.checkSkip,
  883. begin_time: time, end_time: time, opinion: '',
  884. audit_type: x.audit_type, audit_order: x.audit_order,
  885. });
  886. });
  887. change.preAuditors.forEach(x => {
  888. checkingAuditors.push({
  889. tid: change.tid, cpid: change.id, aid: x.aid,
  890. times: x.times, order: x.order + 2,
  891. status: auditConst.status.checking,
  892. begin_time: time, end_time: time, opinion: '',
  893. audit_type: x.audit_type, audit_order: x.audit_order,
  894. });
  895. });
  896. await transaction.insert(this.tableName, [...checkCancelAuditors, ...checkingAuditors]);
  897. // 删除当前次审批流
  898. await transaction.delete(this.tableName, { cpid: change.id, times: change.times });
  899. // 回退数据
  900. await this.ctx.service.changePlanHistory.returnHistory(transaction, change.id);
  901. await transaction.delete(this.ctx.service.changePlanHistory.tableName, { cpid: change.id });
  902. // // 设置变更立项为审批中
  903. // await transaction.update(this.ctx.service.changeProject.tableName, {
  904. // id: change.id,
  905. // time: change.times - 1,
  906. // status: auditConst.status.checking,
  907. // });
  908. await transaction.commit();
  909. } catch (err) {
  910. await transaction.rollback();
  911. throw err;
  912. }
  913. }
  914. /**
  915. * 会签未全部审批通过时,撤回仅修改本人状态
  916. *
  917. * @param stage
  918. * @returns {Promise<void>}
  919. * @private
  920. */
  921. async _auditCheckCancelAnd(change) {
  922. const accountId = this.ctx.session.sessionUser.accountId;
  923. const selfAuditor = change.flowAuditors.find(x => { return x.aid === accountId; });
  924. if (!selfAuditor || selfAuditor.status !== auditConst.status.checked) throw '不可撤回';
  925. const transaction = await this.db.beginTransaction();
  926. try {
  927. await transaction.update(this.tableName, {
  928. id: selfAuditor.id, status: auditConst.status.checking, opinion: '', end_time: null,
  929. });
  930. await transaction.commit();
  931. } catch (err) {
  932. await transaction.rollback();
  933. throw err;
  934. }
  935. }
  936. /**
  937. * 重新审批变更令
  938. * @param { string } cid - 查询的清单
  939. * @return {Promise<*>} - 可用的变更令列表
  940. */
  941. async checkRevise(change) {
  942. const accountId = this.ctx.session.sessionUser.accountId;
  943. const time = new Date();
  944. // 初始化事务
  945. const transaction = await this.db.beginTransaction();
  946. let result = false;
  947. try {
  948. const pid = this.ctx.session.sessionProject.id;
  949. // 获取审核人列表
  950. const auditors = await this.getUniqAuditor(change.id, change.times); // 全部参与的审批人
  951. // const sql = 'SELECT `tid`, `cpid`, `aid`, `order` FROM ?? WHERE `cpid` = ? and `times` = ? GROUP BY `aid` ORDER BY `id` ASC';
  952. // const sqlParam = [this.tableName, change.id, change.times];
  953. // const auditors = await this.db.query(sql, sqlParam);
  954. // 添加到消息推送表
  955. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '发起修订');
  956. const records = [{ pid, type: pushType.changePlan, uid: change.uid, status: auditConst.status.revise, content: noticeContent }];
  957. auditors.forEach(auditor => {
  958. records.push({
  959. pid,
  960. type: pushType.changePlan,
  961. uid: auditor.aid,
  962. status: auditConst.status.revise,
  963. content: noticeContent,
  964. });
  965. });
  966. await transaction.insert('zh_notice', records);
  967. const order = change.auditors.length > 0 ? change.auditors.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  968. // 当前审批人添加至流程中
  969. const checkReviseAuditor = {
  970. tid: change.tid, cpid: change.id, aid: change.uid,
  971. times: change.times, order,
  972. status: auditConst.status.revise,
  973. begin_time: time, end_time: time, opinion: '',
  974. audit_type: auditType.key.common, audit_order: 0,
  975. };
  976. await transaction.insert(this.tableName, checkReviseAuditor);
  977. // 修订人加入审批流程
  978. const newAuditors = auditors.map(x => {
  979. return {
  980. aid: x.aid, tid: change.tid, cpid: change.id,
  981. times: change.times + 1, order: x.audit_order, status: auditConst.status.uncheck,
  982. audit_type: x.audit_type, audit_order: x.audit_order,
  983. };
  984. });
  985. await transaction.insert(this.tableName, newAuditors);
  986. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  987. const changeData = await transaction.get(this.ctx.service.changePlan.tableName, { id: change.id });
  988. const changeList = await this.ctx.service.changePlanList.getAllDataByCondition({
  989. where: { cpid: change.id },
  990. });
  991. await this.ctx.service.changePlanHistory.saveHistory(transaction, changeData, changeList);
  992. // 清单审批值删除并重算变更金额
  993. await this.ctx.service.changePlanList.delAuditAmount(transaction, change.id);
  994. // 设置变更立项修订状态
  995. await transaction.update(this.ctx.service.changePlan.tableName, {
  996. id: change.id,
  997. decimal: null,
  998. status: auditConst.status.revise,
  999. times: change.times + 1,
  1000. final_auditor_str: '',
  1001. });
  1002. await transaction.commit();
  1003. result = true;
  1004. } catch (error) {
  1005. console.log(error);
  1006. await transaction.rollback();
  1007. result = false;
  1008. }
  1009. return result;
  1010. }
  1011. /**
  1012. * 撤销修订变更令
  1013. * @param { string } cid - 查询的清单
  1014. * @return {Promise<*>} - 可用的变更令列表
  1015. */
  1016. async cancelRevise(change) {
  1017. const time = new Date();
  1018. // 初始化事务
  1019. const transaction = await this.db.beginTransaction();
  1020. let result = false;
  1021. try {
  1022. const pid = this.ctx.session.sessionProject.id;
  1023. // 获取审核人列表
  1024. const auditors = await this.getUniqAuditor(change.id, change.times - 1); // 全部参与的审批人
  1025. // 添加到消息推送表
  1026. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '撤销修订');
  1027. const records = [{ pid, type: pushType.changePlan, uid: change.uid, status: auditConst.status.cancelRevise, content: noticeContent }];
  1028. auditors.forEach(auditor => {
  1029. records.push({
  1030. pid,
  1031. type: pushType.changePlan,
  1032. uid: auditor.aid,
  1033. status: auditConst.status.cancelRevise,
  1034. content: noticeContent,
  1035. });
  1036. });
  1037. await transaction.insert('zh_notice', records);
  1038. const lastAudit = await this.getLastAudit(change.id, change.times - 1);
  1039. // 新增一个撤销修订状态到审批流程中
  1040. const revise_audit = {
  1041. tid: change.tid, cpid: change.id, aid: this.ctx.session.sessionUser.accountId,
  1042. times: change.times - 1, order: lastAudit.order + 1, status: auditConst.status.cancelRevise,
  1043. begin_time: time, end_time: time, opinion: '',
  1044. audit_type: lastAudit.audit_type, audit_order: lastAudit.audit_order,
  1045. };
  1046. await transaction.insert(this.tableName, revise_audit);
  1047. await transaction.delete(this.tableName, { cpid: change.id, times: change.times });
  1048. await this.ctx.service.changePlanHistory.returnHistory(transaction, change.id);
  1049. await transaction.delete(this.ctx.service.changePlanHistory.tableName, { cpid: change.id });
  1050. await transaction.commit();
  1051. result = true;
  1052. } catch (error) {
  1053. console.log(error);
  1054. await transaction.rollback();
  1055. result = false;
  1056. }
  1057. return result;
  1058. }
  1059. /**
  1060. * 重新审批变更方案
  1061. * @param { string } cid - 查询的清单
  1062. * @return {Promise<*>} - 可用的变更令列表
  1063. */
  1064. async checkAgain(change) {
  1065. const accountId = this.ctx.session.sessionUser.accountId;
  1066. // 初始化事务
  1067. const time = new Date();
  1068. const transaction = await this.db.beginTransaction();
  1069. let result = false;
  1070. try {
  1071. const noYbAuditors = change.auditors.filter(x => { return x.audit_order !== 0; });
  1072. const noYbMaxOrder = noYbAuditors[noYbAuditors.length - 1].order;
  1073. const maxOrder = change.auditors[change.auditors.length - 1].order;
  1074. const audits = change.auditors.filter(x => { return x.order === noYbMaxOrder; });
  1075. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  1076. const selfAudit = audits.find(x => { return x.aid === accountId; });
  1077. if (!selfAudit) throw '当前标段您无权审批';
  1078. // 当前审批人2次添加至流程中
  1079. const checkAgainAuditors = [];
  1080. audits.forEach(x => {
  1081. checkAgainAuditors.push({
  1082. tid: change.tid, cpid: change.id, aid: x.aid,
  1083. times: x.times, order: maxOrder + 1,
  1084. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  1085. begin_time: time, end_time: time, opinion: '',
  1086. audit_type: x.audit_type, audit_order: x.audit_order,
  1087. });
  1088. });
  1089. const checkingAuditors = [];
  1090. audits.forEach(x => {
  1091. checkingAuditors.push({
  1092. tid: change.tid, cpid: change.id, aid: x.aid,
  1093. times: x.times, order: maxOrder + 2,
  1094. status: auditConst.status.checking,
  1095. begin_time: time,
  1096. audit_type: x.audit_type, audit_order: x.audit_order,
  1097. });
  1098. });
  1099. await transaction.insert(this.tableName, checkAgainAuditors);
  1100. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  1101. // 获取刚批量添加的所有list
  1102. // for (let j = 0; j < checkingAuditors.length; j++) {
  1103. // checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  1104. // }
  1105. // 设置变更令审批中
  1106. await transaction.update(this.ctx.service.changePlan.tableName, {
  1107. id: change.id,
  1108. status: auditConst.status.checking,
  1109. final_auditor_str: '',
  1110. });
  1111. // 清除上一人的值并调整spamount值
  1112. const updateList = [];
  1113. const changeList = await this.ctx.service.changePlanList.getAllDataByCondition({
  1114. where: { cpid: change.id },
  1115. });
  1116. for (const cl of changeList) {
  1117. const audit_amount = cl.audit_amount.split(',');
  1118. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  1119. audit_amount.splice(-1, 1);
  1120. const list_update = {
  1121. id: cl.id,
  1122. audit_amount: audit_amount.join(','),
  1123. spamount: parseFloat(last_amount),
  1124. };
  1125. updateList.push(list_update);
  1126. }
  1127. if (updateList.length > 0) await transaction.updateRows(this.ctx.service.changePlanList.tableName, updateList);
  1128. // 更新total_price
  1129. await this.ctx.service.changePlanList.calcCamountSum(transaction);
  1130. await transaction.commit();
  1131. result = true;
  1132. } catch (error) {
  1133. await transaction.rollback();
  1134. result = false;
  1135. }
  1136. return result;
  1137. }
  1138. async getAuditorGroup(cpId, times) {
  1139. const auditors = await this.getAuditors(cpId, times); // 全部参与的审批人
  1140. return this.ctx.helper.groupAuditors(auditors, 'order', true);
  1141. }
  1142. async getUserGroup(cpId, times) {
  1143. const group = await this.getAuditorGroup(cpId, times);
  1144. const sql =
  1145. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As cpid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1146. ' FROM ' + this.ctx.service.changePlan.tableName + ' As s' +
  1147. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1148. ' ON s.uid = pa.id' +
  1149. ' WHERE s.id = ?';
  1150. const sqlParam = [times, cpId, cpId];
  1151. const user = await this.db.queryOne(sql, sqlParam);
  1152. user.audit_order = 0;
  1153. group.unshift([ user ]);
  1154. return group;
  1155. }
  1156. async getUniqUserGroup(cpId, times) {
  1157. const group = await this.getAuditorGroup(cpId, times);
  1158. const sql =
  1159. 'SELECT pa.`id` As aid, pa.`name`, pa.`company`, pa.`role`, ? As times, ? As cpid, 0 As `order`, 1 As audit_type, 0 As audit_order' +
  1160. ' FROM ' + this.ctx.service.changePlan.tableName + ' As s' +
  1161. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1162. ' ON s.uid = pa.id' +
  1163. ' WHERE s.id = ?';
  1164. const sqlParam = [times, cpId, cpId];
  1165. const user = await this.db.queryOne(sql, sqlParam);
  1166. user.audit_order = 0;
  1167. group.unshift([ user ]);
  1168. return this.ctx.helper.groupAuditorsUniq(group);
  1169. }
  1170. async getAuditorHistory(cpId, times, reverse = false) {
  1171. const history = [];
  1172. if (times >= 1) {
  1173. for (let i = 1; i <= times; i++) {
  1174. const auditors = await this.getAuditors(cpId, i);
  1175. const group = this.ctx.helper.groupAuditors(auditors);
  1176. const historyGroup = [];
  1177. // 找出group里audit_order最大值
  1178. const max_info = group.length > 0 ? this._.maxBy(group, function(item) {
  1179. return item && item[0] && item[0].audit_order;
  1180. }) : null;
  1181. const max_order = max_info ? max_info[0].audit_order : -1;
  1182. for (const g of group) {
  1183. const his = {
  1184. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1185. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1186. auditors: g,
  1187. };
  1188. if (his.audit_type === auditType.key.common) {
  1189. his.name = g[0].name;
  1190. } else {
  1191. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1192. }
  1193. his.is_final = his.audit_order === max_order;
  1194. if (g[0].begin_time) {
  1195. his.begin_time = g[0].begin_time;
  1196. const beginTime = this.ctx.moment(g[0].begin_time);
  1197. his.beginYear = beginTime.format('YYYY');
  1198. his.beginDate = beginTime.format('MM-DD');
  1199. his.beginTime = beginTime.format('HH:mm:ss');
  1200. }
  1201. let end_time;
  1202. g.forEach(x => {
  1203. if (x.status === auditConst.status.checkSkip) return;
  1204. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1205. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1206. end_time = x.end_time;
  1207. if (his.status !== auditConst.status.checking) his.status = x.status;
  1208. }
  1209. });
  1210. if (end_time) {
  1211. his.end_time = end_time;
  1212. const endTime = this.ctx.moment(end_time);
  1213. his.endYear = endTime.format('YYYY');
  1214. his.endDate = endTime.format('MM-DD');
  1215. his.endTime = endTime.format('HH:mm:ss');
  1216. }
  1217. historyGroup.push(his);
  1218. }
  1219. if (reverse) {
  1220. history.push(historyGroup.reverse());
  1221. } else {
  1222. history.push(historyGroup);
  1223. }
  1224. }
  1225. }
  1226. return history;
  1227. }
  1228. async getUniqAuditor(cpId, times) {
  1229. const auditors = await this.getAuditors(cpId, times); // 全部参与的审批人
  1230. const result = [];
  1231. auditors.forEach(x => {
  1232. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1233. result.push(x);
  1234. }
  1235. });
  1236. return result;
  1237. }
  1238. async saveAudit(cpId, times, sp_group, data) {
  1239. const transaction = await this.db.beginTransaction();
  1240. try {
  1241. const auditors = await this.getAuditGroupByList(cpId, times);
  1242. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1243. if (data.operate !== 'del') {
  1244. const exist = await this.getDataByCondition({ cpid: cpId, times, aid: data.new_aid });
  1245. if (exist) throw '该审核人已存在,请勿重复添加';
  1246. }
  1247. if (data.operate === 'add') {
  1248. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1249. throw '当前人下无法操作新增';
  1250. }
  1251. const newAudit = {
  1252. tid: this.ctx.tender.id, cpid: cpId, aid: data.new_aid,
  1253. order: now_audit.order + 1,
  1254. audit_order: now_audit.audit_order + 1, audit_type: auditType.key.common,
  1255. times, status: auditConst.status.uncheck,
  1256. };
  1257. // order+1
  1258. await this._syncOrderByDelete(transaction, cpId, now_audit.order + 1, times, '+');
  1259. await transaction.insert(this.tableName, newAudit);
  1260. // 更新审批流程页数据,如果存在
  1261. } else if (data.operate === 'add-sibling') {
  1262. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1263. throw '当前人下无法操作新增';
  1264. }
  1265. const newAudit = {
  1266. tid: this.ctx.tender.id, cpid: cpId, aid: data.new_aid,
  1267. order: now_audit.order,
  1268. audit_order: now_audit.audit_order, audit_type: now_audit.audit_type,
  1269. times, status: auditConst.status.uncheck,
  1270. };
  1271. await transaction.insert(this.tableName, newAudit);
  1272. } else if (data.operate === 'del') {
  1273. if (now_audit.status !== auditConst.status.uncheck) {
  1274. throw '当前人无法操作删除';
  1275. }
  1276. const flowAuditors = auditors.filter(x => { return x.audit_order === now_audit.audit_order; });
  1277. await transaction.delete(this.tableName, { cpid: cpId, times, aid: now_audit.aid, order: now_audit.order });
  1278. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, cpId, now_audit.order, times);
  1279. // 旧的更新为is_old为1
  1280. // await transaction.update(this.tableName, { is_old: 1 }, {
  1281. // where: {
  1282. // sid: stageId,
  1283. // times,
  1284. // aid: data.old_aid,
  1285. // }
  1286. // });
  1287. } else if (data.operate === 'change') {
  1288. const nowAudit = await this.getDataByCondition({ cpid: cpId, times, aid: now_audit.aid, order: now_audit.order });
  1289. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1290. throw '当前人无法操作替换';
  1291. }
  1292. nowAudit.aid = data.new_aid;
  1293. await transaction.update(this.tableName, nowAudit);
  1294. // 旧的更新为is_old为1
  1295. // await transaction.update(this.tableName, { is_old: 1 }, {
  1296. // where: {
  1297. // sid: stageId,
  1298. // times,
  1299. // aid: data.old_aid,
  1300. // }
  1301. // });
  1302. }
  1303. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  1304. const newAuditors = await transaction.select(this.tableName, { where: { cpid: cpId, times }, orders: [['order', 'asc']] });
  1305. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors, 'order', true);
  1306. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1307. // await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, uniqNewAuditorGroup, sp_group);
  1308. } else if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs) {
  1309. const newAuditors = await this.getAuditGroupByList(cpId, times, transaction);
  1310. await this.ctx.service.shenpiAudit.updateAuditList(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, this._.map(newAuditors, 'aid'));
  1311. }
  1312. // 更新到审批流程方法
  1313. await transaction.commit();
  1314. } catch (err) {
  1315. await transaction.rollback();
  1316. throw err;
  1317. }
  1318. }
  1319. async changeSpGroup(change, sp_group) {
  1320. const transaction = await this.db.beginTransaction();
  1321. try {
  1322. const group = await this.ctx.service.shenpiGroup.getDataById(sp_group);
  1323. if (!group) {
  1324. throw '该固定审批组不存在,请刷新页面重新获取';
  1325. }
  1326. const shenpiList = await this.ctx.service.shenpiAudit.getAllDataByCondition({ where: { tid: this.ctx.tender.id, sp_type: shenpiConst.sp_type.change, sp_status: shenpiConst.sp_status.gdspl, sp_group: group.id } });
  1327. await this.ctx.service.shenpiAudit.noYbShenpiList(change.uid, shenpiList);
  1328. await this.updateNewAuditors(change, shenpiList, transaction);
  1329. await transaction.update(this.ctx.service.changePlan.tableName, { id: change.id, sp_group: group.id });
  1330. await transaction.commit();
  1331. } catch (err) {
  1332. await transaction.rollback();
  1333. throw err;
  1334. }
  1335. return true;
  1336. }
  1337. async updateNewAuditList(change, newList) {
  1338. const transaction = await this.db.beginTransaction();
  1339. try {
  1340. await this.updateNewAuditors(change, newList, transaction);
  1341. await transaction.commit();
  1342. } catch (err) {
  1343. await transaction.rollback();
  1344. throw err;
  1345. }
  1346. }
  1347. async updateNewAuditors(change, newList, transaction) {
  1348. // 先删除旧的审批流,再添加新的
  1349. await transaction.delete(this.tableName, { cpid: change.id, times: change.times });
  1350. const newAuditors = [];
  1351. for (const auditor of newList) {
  1352. newAuditors.push({
  1353. tid: change.tid, cpid: change.id, aid: auditor.audit_id,
  1354. times: change.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1355. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1356. });
  1357. }
  1358. if (newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1359. }
  1360. async updateLastAudit(change, auditList, lastId) {
  1361. const transaction = await this.db.beginTransaction();
  1362. try {
  1363. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1364. const existAudit = auditList.find(x => { return x.aid === lastId; });
  1365. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  1366. if (existAudit) {
  1367. await transaction.delete(this.tableName, { cpid: change.id, times: change.times, aid: lastId });
  1368. const sameOrder = auditList.filter(x => { return x.order === existAudit.order; });
  1369. if (sameOrder.length === 1) {
  1370. const updateData = [];
  1371. auditList.forEach(x => {
  1372. if (x.order <= existAudit.order) return;
  1373. updateData.push({ id: x.id, order: x.order - 1, audit_order: x.audit_order - 1 });
  1374. });
  1375. if (updateData.length > 0) {
  1376. await transaction.updateRows(updateData);
  1377. }
  1378. order = order - 1;
  1379. }
  1380. }
  1381. // 添加终审
  1382. const newAuditor = {
  1383. tid: change.tid, cpid: change.id, aid: lastId,
  1384. times: change.times, order, status: auditConst.status.uncheck,
  1385. audit_type: auditType.key.common, audit_order: order,
  1386. };
  1387. await transaction.insert(this.tableName, newAuditor);
  1388. await transaction.commit();
  1389. } catch (err) {
  1390. await transaction.rollback();
  1391. throw err;
  1392. }
  1393. }
  1394. }
  1395. return ChangePlanAudit;
  1396. };