change_audit.js 69 KB

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