change_plan_audit.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451
  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. });
  1001. await transaction.commit();
  1002. result = true;
  1003. } catch (error) {
  1004. console.log(error);
  1005. await transaction.rollback();
  1006. result = false;
  1007. }
  1008. return result;
  1009. }
  1010. /**
  1011. * 撤销修订变更令
  1012. * @param { string } cid - 查询的清单
  1013. * @return {Promise<*>} - 可用的变更令列表
  1014. */
  1015. async cancelRevise(change) {
  1016. const time = new Date();
  1017. // 初始化事务
  1018. const transaction = await this.db.beginTransaction();
  1019. let result = false;
  1020. try {
  1021. const pid = this.ctx.session.sessionProject.id;
  1022. // 获取审核人列表
  1023. const auditors = await this.getUniqAuditor(change.id, change.times - 1); // 全部参与的审批人
  1024. // 添加到消息推送表
  1025. const noticeContent = await this.getNoticeContent(pid, change.tid, change.id, this.ctx.session.sessionUser.accountId, '撤销修订');
  1026. const records = [{ pid, type: pushType.changePlan, uid: change.uid, status: auditConst.status.cancelRevise, content: noticeContent }];
  1027. auditors.forEach(auditor => {
  1028. records.push({
  1029. pid,
  1030. type: pushType.changePlan,
  1031. uid: auditor.aid,
  1032. status: auditConst.status.cancelRevise,
  1033. content: noticeContent,
  1034. });
  1035. });
  1036. await transaction.insert('zh_notice', records);
  1037. const lastAudit = await this.getLastAudit(change.id, change.times - 1);
  1038. // 新增一个撤销修订状态到审批流程中
  1039. const revise_audit = {
  1040. tid: change.tid, cpid: change.id, aid: this.ctx.session.sessionUser.accountId,
  1041. times: change.times - 1, order: lastAudit.order + 1, status: auditConst.status.cancelRevise,
  1042. begin_time: time, end_time: time, opinion: '',
  1043. audit_type: lastAudit.audit_type, audit_order: lastAudit.audit_order,
  1044. };
  1045. await transaction.insert(this.tableName, revise_audit);
  1046. await transaction.delete(this.tableName, { cpid: change.id, times: change.times });
  1047. await this.ctx.service.changePlanHistory.returnHistory(transaction, change.id);
  1048. await transaction.delete(this.ctx.service.changePlanHistory.tableName, { cpid: change.id });
  1049. await transaction.commit();
  1050. result = true;
  1051. } catch (error) {
  1052. console.log(error);
  1053. await transaction.rollback();
  1054. result = false;
  1055. }
  1056. return result;
  1057. }
  1058. /**
  1059. * 重新审批变更方案
  1060. * @param { string } cid - 查询的清单
  1061. * @return {Promise<*>} - 可用的变更令列表
  1062. */
  1063. async checkAgain(change) {
  1064. const accountId = this.ctx.session.sessionUser.accountId;
  1065. // 初始化事务
  1066. const time = new Date();
  1067. const transaction = await this.db.beginTransaction();
  1068. let result = false;
  1069. try {
  1070. const noYbAuditors = change.auditors.filter(x => { return x.audit_order !== 0; });
  1071. const noYbMaxOrder = noYbAuditors[noYbAuditors.length - 1].order;
  1072. const maxOrder = change.auditors[change.auditors.length - 1].order;
  1073. const audits = change.auditors.filter(x => { return x.order === noYbMaxOrder; });
  1074. if (!audits || audits.length === 0 || maxOrder < 1) throw '审核数据错误';
  1075. const selfAudit = audits.find(x => { return x.aid === accountId; });
  1076. if (!selfAudit) throw '当前标段您无权审批';
  1077. // 当前审批人2次添加至流程中
  1078. const checkAgainAuditors = [];
  1079. audits.forEach(x => {
  1080. checkAgainAuditors.push({
  1081. tid: change.tid, cpid: change.id, aid: x.aid,
  1082. times: x.times, order: maxOrder + 1,
  1083. status: !selfAudit || x.aid === selfAudit.aid ? auditConst.status.checkAgain : auditConst.status.checkSkip,
  1084. begin_time: time, end_time: time, opinion: '',
  1085. audit_type: x.audit_type, audit_order: x.audit_order,
  1086. });
  1087. });
  1088. const checkingAuditors = [];
  1089. audits.forEach(x => {
  1090. checkingAuditors.push({
  1091. tid: change.tid, cpid: change.id, aid: x.aid,
  1092. times: x.times, order: maxOrder + 2,
  1093. status: auditConst.status.checking,
  1094. begin_time: time,
  1095. audit_type: x.audit_type, audit_order: x.audit_order,
  1096. });
  1097. });
  1098. await transaction.insert(this.tableName, checkAgainAuditors);
  1099. const checkingAuditors_result = await transaction.insert(this.tableName, checkingAuditors);
  1100. // 获取刚批量添加的所有list
  1101. // for (let j = 0; j < checkingAuditors.length; j++) {
  1102. // checkingAuditors[j].id = checkingAuditors_result.insertId + j;
  1103. // }
  1104. // 设置变更令审批中
  1105. await transaction.update(this.ctx.service.changePlan.tableName, {
  1106. id: change.id,
  1107. status: auditConst.status.checking,
  1108. });
  1109. // 清除上一人的值并调整spamount值
  1110. const updateList = [];
  1111. const changeList = await this.ctx.service.changePlanList.getAllDataByCondition({
  1112. where: { cpid: change.id },
  1113. });
  1114. for (const cl of changeList) {
  1115. const audit_amount = cl.audit_amount.split(',');
  1116. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  1117. audit_amount.splice(-1, 1);
  1118. const list_update = {
  1119. id: cl.id,
  1120. audit_amount: audit_amount.join(','),
  1121. spamount: parseFloat(last_amount),
  1122. };
  1123. updateList.push(list_update);
  1124. }
  1125. if (updateList.length > 0) await transaction.updateRows(this.ctx.service.changePlanList.tableName, updateList);
  1126. // 更新total_price
  1127. await this.ctx.service.changePlanList.calcCamountSum(transaction);
  1128. await transaction.commit();
  1129. result = true;
  1130. } catch (error) {
  1131. await transaction.rollback();
  1132. result = false;
  1133. }
  1134. return result;
  1135. }
  1136. async getAuditorGroup(cpId, times) {
  1137. const auditors = await this.getAuditors(cpId, times); // 全部参与的审批人
  1138. return this.ctx.helper.groupAuditors(auditors, 'order', true);
  1139. }
  1140. async getUserGroup(cpId, times) {
  1141. const group = await this.getAuditorGroup(cpId, times);
  1142. const sql =
  1143. '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' +
  1144. ' FROM ' + this.ctx.service.changePlan.tableName + ' As s' +
  1145. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1146. ' ON s.uid = pa.id' +
  1147. ' WHERE s.id = ?';
  1148. const sqlParam = [times, cpId, cpId];
  1149. const user = await this.db.queryOne(sql, sqlParam);
  1150. user.audit_order = 0;
  1151. group.unshift([ user ]);
  1152. return group;
  1153. }
  1154. async getUniqUserGroup(cpId, times) {
  1155. const group = await this.getAuditorGroup(cpId, times);
  1156. const sql =
  1157. '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' +
  1158. ' FROM ' + this.ctx.service.changePlan.tableName + ' As s' +
  1159. ' LEFT JOIN ' + this.ctx.service.projectAccount.tableName + ' As pa' +
  1160. ' ON s.uid = pa.id' +
  1161. ' WHERE s.id = ?';
  1162. const sqlParam = [times, cpId, cpId];
  1163. const user = await this.db.queryOne(sql, sqlParam);
  1164. user.audit_order = 0;
  1165. group.unshift([ user ]);
  1166. return this.ctx.helper.groupAuditorsUniq(group);
  1167. }
  1168. async getAuditorHistory(cpId, times, reverse = false) {
  1169. const history = [];
  1170. if (times >= 1) {
  1171. for (let i = 1; i <= times; i++) {
  1172. const auditors = await this.getAuditors(cpId, i);
  1173. const group = this.ctx.helper.groupAuditors(auditors);
  1174. const historyGroup = [];
  1175. // 找出group里audit_order最大值
  1176. const max_info = group.length > 0 ? this._.maxBy(group, function(item) {
  1177. return item && item[0] && item[0].audit_order;
  1178. }) : null;
  1179. const max_order = max_info ? max_info[0].audit_order : -1;
  1180. for (const g of group) {
  1181. const his = {
  1182. beginYear: '', beginDate: '', beginTime: '', endYear: '', endDate: '', endTime: '', begin_time: null, end_time: null,
  1183. audit_type: g[0].audit_type, audit_order: g[0].audit_order,
  1184. auditors: g,
  1185. };
  1186. if (his.audit_type === auditType.key.common) {
  1187. his.name = g[0].name;
  1188. } else {
  1189. his.name = this.ctx.helper.transFormToChinese(his.audit_order) + '审';
  1190. }
  1191. his.is_final = his.audit_order === max_order;
  1192. if (g[0].begin_time) {
  1193. his.begin_time = g[0].begin_time;
  1194. const beginTime = this.ctx.moment(g[0].begin_time);
  1195. his.beginYear = beginTime.format('YYYY');
  1196. his.beginDate = beginTime.format('MM-DD');
  1197. his.beginTime = beginTime.format('HH:mm:ss');
  1198. }
  1199. let end_time;
  1200. g.forEach(x => {
  1201. if (x.status === auditConst.status.checkSkip) return;
  1202. if (!his.status || x.status === auditConst.status.checking) his.status = x.status;
  1203. if (x.end_time && (!end_time || x.end_time > end_time)) {
  1204. end_time = x.end_time;
  1205. if (his.status !== auditConst.status.checking) his.status = x.status;
  1206. }
  1207. });
  1208. if (end_time) {
  1209. his.end_time = end_time;
  1210. const endTime = this.ctx.moment(end_time);
  1211. his.endYear = endTime.format('YYYY');
  1212. his.endDate = endTime.format('MM-DD');
  1213. his.endTime = endTime.format('HH:mm:ss');
  1214. }
  1215. historyGroup.push(his);
  1216. }
  1217. if (reverse) {
  1218. history.push(historyGroup.reverse());
  1219. } else {
  1220. history.push(historyGroup);
  1221. }
  1222. }
  1223. }
  1224. return history;
  1225. }
  1226. async getUniqAuditor(cpId, times) {
  1227. const auditors = await this.getAuditors(cpId, times); // 全部参与的审批人
  1228. const result = [];
  1229. auditors.forEach(x => {
  1230. if (result.findIndex(r => { return x.aid === r.aid && x.audit_order === r.audit_order; }) < 0) {
  1231. result.push(x);
  1232. }
  1233. });
  1234. return result;
  1235. }
  1236. async saveAudit(cpId, times, sp_group, data) {
  1237. const transaction = await this.db.beginTransaction();
  1238. try {
  1239. const auditors = await this.getAuditGroupByList(cpId, times);
  1240. const now_audit = this._.find(auditors, { aid: data.old_aid });
  1241. if (data.operate !== 'del') {
  1242. const exist = await this.getDataByCondition({ cpid: cpId, times, aid: data.new_aid });
  1243. if (exist) throw '该审核人已存在,请勿重复添加';
  1244. }
  1245. if (data.operate === 'add') {
  1246. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1247. throw '当前人下无法操作新增';
  1248. }
  1249. const newAudit = {
  1250. tid: this.ctx.tender.id, cpid: cpId, aid: data.new_aid,
  1251. order: now_audit.order + 1,
  1252. audit_order: now_audit.audit_order + 1, audit_type: auditType.key.common,
  1253. times, status: auditConst.status.uncheck,
  1254. };
  1255. // order+1
  1256. await this._syncOrderByDelete(transaction, cpId, now_audit.order + 1, times, '+');
  1257. await transaction.insert(this.tableName, newAudit);
  1258. // 更新审批流程页数据,如果存在
  1259. } else if (data.operate === 'add-sibling') {
  1260. if (now_audit.status !== auditConst.status.uncheck && now_audit.status !== auditConst.status.checking) {
  1261. throw '当前人下无法操作新增';
  1262. }
  1263. const newAudit = {
  1264. tid: this.ctx.tender.id, cpid: cpId, aid: data.new_aid,
  1265. order: now_audit.order,
  1266. audit_order: now_audit.audit_order, audit_type: now_audit.audit_type,
  1267. times, status: auditConst.status.uncheck,
  1268. };
  1269. await transaction.insert(this.tableName, newAudit);
  1270. } else if (data.operate === 'del') {
  1271. if (now_audit.status !== auditConst.status.uncheck) {
  1272. throw '当前人无法操作删除';
  1273. }
  1274. const flowAuditors = auditors.filter(x => { return x.audit_order === now_audit.audit_order; });
  1275. await transaction.delete(this.tableName, { cpid: cpId, times, aid: now_audit.aid, order: now_audit.order });
  1276. if (flowAuditors.length === 1) await this._syncOrderByDelete(transaction, cpId, now_audit.order, times);
  1277. // 旧的更新为is_old为1
  1278. // await transaction.update(this.tableName, { is_old: 1 }, {
  1279. // where: {
  1280. // sid: stageId,
  1281. // times,
  1282. // aid: data.old_aid,
  1283. // }
  1284. // });
  1285. } else if (data.operate === 'change') {
  1286. const nowAudit = await this.getDataByCondition({ cpid: cpId, times, aid: now_audit.aid, order: now_audit.order });
  1287. if (now_audit.status !== auditConst.status.uncheck || !nowAudit) {
  1288. throw '当前人无法操作替换';
  1289. }
  1290. nowAudit.aid = data.new_aid;
  1291. await transaction.update(this.tableName, nowAudit);
  1292. // 旧的更新为is_old为1
  1293. // await transaction.update(this.tableName, { is_old: 1 }, {
  1294. // where: {
  1295. // sid: stageId,
  1296. // times,
  1297. // aid: data.old_aid,
  1298. // }
  1299. // });
  1300. }
  1301. if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdspl) {
  1302. const newAuditors = await transaction.select(this.tableName, { where: { cpid: cpId, times }, orders: [['order', 'asc']] });
  1303. const newAuditorGroup = this.ctx.helper.groupAuditors(newAuditors, 'order', true);
  1304. const uniqNewAuditorGroup = this.ctx.helper.groupAuditorsUniq(newAuditorGroup);
  1305. // await this.ctx.service.shenpiAudit.updateAuditListWithAuditType(transaction, this.ctx.tender.id, this.ctx.tender.info.shenpi.change, shenpiConst.sp_type.change, uniqNewAuditorGroup, sp_group);
  1306. } else if (this.ctx.tender.info.shenpi.change === shenpiConst.sp_status.gdzs) {
  1307. const newAuditors = await this.getAuditGroupByList(cpId, times, transaction);
  1308. 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'));
  1309. }
  1310. // 更新到审批流程方法
  1311. await transaction.commit();
  1312. } catch (err) {
  1313. await transaction.rollback();
  1314. throw err;
  1315. }
  1316. }
  1317. async changeSpGroup(change, sp_group) {
  1318. const transaction = await this.db.beginTransaction();
  1319. try {
  1320. const group = await this.ctx.service.shenpiGroup.getDataById(sp_group);
  1321. if (!group) {
  1322. throw '该固定审批组不存在,请刷新页面重新获取';
  1323. }
  1324. 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 } });
  1325. await this.ctx.service.shenpiAudit.noYbShenpiList(change.uid, shenpiList);
  1326. await this.updateNewAuditors(change, shenpiList, transaction);
  1327. await transaction.update(this.ctx.service.changePlan.tableName, { id: change.id, sp_group: group.id });
  1328. await transaction.commit();
  1329. } catch (err) {
  1330. await transaction.rollback();
  1331. throw err;
  1332. }
  1333. return true;
  1334. }
  1335. async updateNewAuditList(change, newList) {
  1336. const transaction = await this.db.beginTransaction();
  1337. try {
  1338. await this.updateNewAuditors(change, newList, transaction);
  1339. await transaction.commit();
  1340. } catch (err) {
  1341. await transaction.rollback();
  1342. throw err;
  1343. }
  1344. }
  1345. async updateNewAuditors(change, newList, transaction) {
  1346. // 先删除旧的审批流,再添加新的
  1347. await transaction.delete(this.tableName, { cpid: change.id, times: change.times });
  1348. const newAuditors = [];
  1349. for (const auditor of newList) {
  1350. newAuditors.push({
  1351. tid: change.tid, cpid: change.id, aid: auditor.audit_id,
  1352. times: change.times, order: auditor.audit_order, status: auditConst.status.uncheck,
  1353. audit_type: auditor.audit_type, audit_order: auditor.audit_order,
  1354. });
  1355. }
  1356. if (newAuditors.length > 0) await transaction.insert(this.tableName, newAuditors);
  1357. }
  1358. async updateLastAudit(change, auditList, lastId) {
  1359. const transaction = await this.db.beginTransaction();
  1360. try {
  1361. // 先判断auditList里的aid是否与lastId相同,相同则删除并重新更新order
  1362. const existAudit = auditList.find(x => { return x.aid === lastId; });
  1363. let order = auditList.length > 0 ? auditList.reduce((rst, a) => { return Math.max(rst, a.order); }, 0) + 1 : 1; // 最大值 + 1
  1364. if (existAudit) {
  1365. await transaction.delete(this.tableName, { cpid: change.id, times: change.times, aid: lastId });
  1366. const sameOrder = auditList.filter(x => { return x.order === existAudit.order; });
  1367. if (sameOrder.length === 1) {
  1368. const updateData = [];
  1369. auditList.forEach(x => {
  1370. if (x.order <= existAudit.order) return;
  1371. updateData.push({ id: x.id, order: x.order - 1, audit_order: x.audit_order - 1 });
  1372. });
  1373. if (updateData.length > 0) {
  1374. await transaction.updateRows(updateData);
  1375. }
  1376. order = order - 1;
  1377. }
  1378. }
  1379. // 添加终审
  1380. const newAuditor = {
  1381. tid: change.tid, cpid: change.id, aid: lastId,
  1382. times: change.times, order, status: auditConst.status.uncheck,
  1383. audit_type: auditType.key.common, audit_order: order,
  1384. };
  1385. await transaction.insert(this.tableName, newAuditor);
  1386. await transaction.commit();
  1387. } catch (err) {
  1388. await transaction.rollback();
  1389. throw err;
  1390. }
  1391. }
  1392. }
  1393. return ChangePlanAudit;
  1394. };