change_apply_audit.js 74 KB

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