change.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372
  1. 'use strict';
  2. /**
  3. *
  4. *
  5. * @author Mai
  6. * @date 2018/8/14
  7. * @version
  8. */
  9. const audit = require('../const/audit');
  10. const fs = require('fs');
  11. const path = require('path');
  12. const changeConst = require('../const/change');
  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. const pushType = require('../const/audit').pushType;
  18. module.exports = app => {
  19. class Change 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';
  29. }
  30. /**
  31. * 查找数据
  32. *
  33. * @param {Object} data - 筛选表单中的get数据
  34. * @return {void}
  35. */
  36. searchFilter(data) {
  37. this.initSqlBuilder();
  38. // this.sqlBuilder.columns = ['id', 'username', 'real_name', 'create_time', 'last_login', 'login_ip',
  39. // 'group_id', 'token', 'can_login'];
  40. data.type = parseInt(data.status);
  41. if (data.keyword !== undefined) {
  42. switch (data.type) {
  43. // 用户名
  44. case 1:
  45. this.sqlBuilder.setAndWhere('username', {
  46. value: this.db.escape(data.keyword + '%'),
  47. operate: 'like',
  48. });
  49. break;
  50. // 姓名
  51. case 2:
  52. this.sqlBuilder.setAndWhere('real_name', {
  53. value: this.db.escape(data.keyword + '%'),
  54. operate: 'like',
  55. });
  56. break;
  57. // 联系电话
  58. case 3:
  59. this.sqlBuilder.setAndWhere('telephone', {
  60. value: this.db.escape(data.keyword + '%'),
  61. operate: 'like',
  62. });
  63. break;
  64. default:
  65. break;
  66. }
  67. }
  68. // 办事处筛选
  69. if (data.office !== undefined && data.office !== '') {
  70. this.sqlBuilder.setAndWhere('office', {
  71. value: this.db.escape(data.office),
  72. operate: '=',
  73. });
  74. }
  75. }
  76. async add(tenderId, userId, code, name) {
  77. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE `tid` = ? AND ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?))';
  78. const sqlParam = [this.tableName, tenderId, code, audit.flow.status.checked, code, audit.flow.status.checked];
  79. const codeCount = await this.db.queryOne(sql, sqlParam);
  80. const count = codeCount.count;
  81. if (count > 0) {
  82. throw '变更令号重复';
  83. }
  84. // 初始化事务
  85. this.transaction = await this.db.beginTransaction();
  86. let result = false;
  87. try {
  88. const cid = this.uuid.v4();
  89. const change = {
  90. cid,
  91. tid: tenderId,
  92. uid: userId,
  93. status: audit.flow.status.uncheck,
  94. times: 1,
  95. valid: true,
  96. in_time: new Date(),
  97. code,
  98. name,
  99. };
  100. const operate = await this.transaction.insert(this.tableName, change);
  101. if (operate.affectedRows <= 0) {
  102. throw '新建变更令数据失败';
  103. }
  104. // 把提交人信息添加到zh_change_audit
  105. const userInfo = await this.ctx.service.projectAccount.getDataById(userId);
  106. const changeaudit = [
  107. {
  108. tid: tenderId,
  109. cid,
  110. uid: userId,
  111. name: userInfo.name,
  112. jobs: userInfo.role,
  113. company: userInfo.company,
  114. times: 1,
  115. usite: 0,
  116. usort: 0,
  117. status: 2,
  118. },
  119. ];
  120. // 并把之前存在的变更令审批人添加到zh_change_audit
  121. // 先找出标段最近存在的变更令审批人的变更令info
  122. const changeInfo = await this.ctx.service.change.getHaveAuditLastInfo(tenderId);
  123. if (changeInfo) {
  124. // 再获取非原报审批人
  125. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  126. let sort = 1;
  127. for (const audit of auditList) {
  128. if (audit.usite !== 0) {
  129. const oneaudit = {
  130. tid: tenderId,
  131. cid,
  132. uid: audit.uid,
  133. name: audit.name,
  134. jobs: audit.jobs,
  135. company: audit.company,
  136. times: 1,
  137. usite: audit.usite,
  138. usort: sort++,
  139. status: 1,
  140. };
  141. changeaudit.push(oneaudit);
  142. }
  143. }
  144. }
  145. await this.transaction.insert(this.ctx.service.changeAudit.tableName, changeaudit);
  146. result = change;
  147. this.transaction.commit();
  148. } catch (error) {
  149. console.log(error);
  150. // 回滚
  151. await this.transaction.rollback();
  152. }
  153. return result;
  154. }
  155. async getHaveAuditLastInfo(tenderId) {
  156. const sql = 'SELECT * FROM ?? as a LEFT JOIN ?? as b ON a.`cid` = b.`cid` WHERE a.`tid` = ? AND b.`usite` > 0 ORDER BY a.`in_time` DESC';
  157. const sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId];
  158. return await this.db.queryOne(sql, sqlParam);
  159. }
  160. async pendingDatas(tenderId, userId) {
  161. return await this.getAllDataByCondition({
  162. tid: tenderId,
  163. uid: userId,
  164. status: audit.flow.status.checking,
  165. });
  166. }
  167. async uncheckDatas(tenderId, userId) {
  168. return await this.getAllDataByCondition({
  169. tid: tenderId,
  170. uid: userId,
  171. status: audit.flow.status.uncheck,
  172. });
  173. }
  174. async checkingDatas(tenderId, userId) {
  175. return await this.getAllDataByCondition({
  176. tid: tenderId,
  177. uid: userId,
  178. status: audit.flow.status.checking,
  179. });
  180. }
  181. async checkedDatas(tenderId, userId) {
  182. return await this.getAllDataByCondition({
  183. tid: tenderId,
  184. uid: userId,
  185. status: audit.flow.status.checked,
  186. });
  187. }
  188. async checkNoDatas(tenderId, userId) {
  189. return await this.getAllDataByCondition({
  190. tid: tenderId,
  191. uid: userId,
  192. status: audit.flow.status.checkNo,
  193. });
  194. }
  195. async checkNoCount(tenderId, userId) {
  196. return await this.count({
  197. tid: tenderId,
  198. uid: userId,
  199. status: audit.flow.status.checkNo,
  200. });
  201. }
  202. /**
  203. * 获取变更令列表
  204. * @param {int} tenderId - 标段id
  205. * @param {int} status - 状态
  206. * @param {int} hadlimit - 分页
  207. * @return {object} list - 列表
  208. */
  209. async getListByStatus(tenderId, status = 0, hadlimit = 1) {
  210. let sql = '';
  211. let sqlParam = '';
  212. switch (status) {
  213. case 0: // 包含你的所有变更令
  214. sql =
  215. 'SELECT a.* FROM ?? AS a WHERE a.tid = ? AND ' +
  216. '(a.uid = ? OR (a.status != ? AND a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid)) OR a.status = ? ) ORDER BY a.in_time DESC';
  217. sqlParam = [
  218. this.tableName,
  219. tenderId,
  220. this.ctx.session.sessionUser.accountId,
  221. audit.flow.status.uncheck,
  222. this.ctx.service.changeAudit.tableName,
  223. this.ctx.session.sessionUser.accountId,
  224. audit.flow.status.checked,
  225. ];
  226. break;
  227. case 1: // 待处理(你的)
  228. sql = 'SELECT a.* FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?) ORDER BY in_time DESC';
  229. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  230. break;
  231. case 5: // 待上报(所有的)PS:取未上报和退回的变更令
  232. sql =
  233. 'SELECT a.* FROM ?? AS a WHERE ' +
  234. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? GROUP BY b.cid) AND ' +
  235. '(a.status = ? OR a.status = ?) AND a.tid = ? ORDER BY a.in_time DESC';
  236. sqlParam = [
  237. this.tableName,
  238. this.ctx.service.changeAudit.tableName,
  239. this.ctx.session.sessionUser.accountId,
  240. audit.flow.status.uncheck,
  241. audit.flow.status.back,
  242. tenderId,
  243. ];
  244. break;
  245. case 2: // 进行中(所有的)
  246. case 4: // 终止(所有的)
  247. sql =
  248. 'SELECT a.* FROM ?? AS a WHERE ' +
  249. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND ' +
  250. 'a.status = ? AND a.tid = ? ORDER BY a.in_time DESC';
  251. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  252. break;
  253. case 3: // 已完成(所有的)
  254. sql = 'SELECT a.* FROM ?? AS a WHERE a.status = ? AND a.tid = ? ORDER BY a.in_time DESC';
  255. sqlParam = [this.tableName, status, tenderId];
  256. break;
  257. default:
  258. break;
  259. }
  260. if (hadlimit) {
  261. const limit = this.app.config.pageSize;
  262. const offset = limit * (this.ctx.page - 1);
  263. const limitString = offset >= 0 ? offset + ',' + limit : limit;
  264. sql += ' LIMIT ' + limitString;
  265. }
  266. const list = await this.db.query(sql, sqlParam);
  267. return list;
  268. }
  269. /**
  270. * 获取变更令个数
  271. * @param {int} tenderId - 标段id
  272. * @param {int} status - 状态
  273. * @return {void}
  274. */
  275. async getCountByStatus(tenderId, status) {
  276. switch (status) {
  277. case 0: // 包含你的所有变更令
  278. const sql =
  279. 'SELECT count(*) AS count FROM ?? AS a WHERE a.tid = ? AND ' +
  280. '(a.uid = ? OR a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid))';
  281. const sqlParam = [
  282. this.tableName,
  283. tenderId,
  284. this.ctx.session.sessionUser.accountId,
  285. this.ctx.service.changeAudit.tableName,
  286. this.ctx.session.sessionUser.accountId,
  287. ];
  288. const result = await this.db.query(sql, sqlParam);
  289. return result[0].count;
  290. case 1: // 待处理(你的)
  291. return await this.ctx.service.changeAudit.count({
  292. tid: tenderId,
  293. uid: this.ctx.session.sessionUser.accountId,
  294. status: 2,
  295. });
  296. case 5: // 待上报(所有的)PS:取未上报和退回的变更令
  297. const sql2 =
  298. 'SELECT count(*) AS count FROM ?? AS a WHERE ' +
  299. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) ' +
  300. 'AND (a.status = ? OR a.status = ?) AND a.tid = ?';
  301. const sqlParam2 = [
  302. this.tableName,
  303. this.ctx.service.changeAudit.tableName,
  304. this.ctx.session.sessionUser.accountId,
  305. audit.flow.status.uncheck,
  306. audit.flow.status.back,
  307. tenderId,
  308. ];
  309. const result2 = await this.db.query(sql2, sqlParam2);
  310. return result2[0].count;
  311. case 2: // 进行中(所有的)
  312. case 4: // 终止(所有的)
  313. const sql3 =
  314. 'SELECT count(*) AS count FROM ?? AS a WHERE ' +
  315. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND a.status = ? AND a.tid = ?';
  316. const sqlParam3 = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  317. const result3 = await this.db.query(sql3, sqlParam3);
  318. return result3[0].count;
  319. case 3: // 已完成(所有的)
  320. const sql4 = 'SELECT count(*) AS count FROM ?? WHERE status = ? AND tid = ?';
  321. const sqlParam4 = [this.tableName, status, tenderId];
  322. const result4 = await this.db.query(sql4, sqlParam4);
  323. return result4[0].count;
  324. default:
  325. break;
  326. }
  327. }
  328. /**
  329. * 上报或重新上报或保存修改功能
  330. * @param {int} postData - 表单提交的数据
  331. * @param {int} tenderId - 标段id
  332. * @return {void}
  333. */
  334. async save(postData, tenderId) {
  335. // 初始化事务
  336. this.transaction = await this.db.beginTransaction();
  337. let result = false;
  338. try {
  339. // 变更令信息
  340. const changeInfo = await this.getDataByCondition({ cid: postData.cid });
  341. // 该变更令原报人信息
  342. const lastUser = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 0);
  343. // 先删除本次原有的变更审批人和清单
  344. await this.ctx.service.changeAudit.deleteAuditData(this.transaction, changeInfo.cid, changeInfo.times);
  345. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid: changeInfo.cid });
  346. let change_status = false;
  347. // 获取变更令提交状态
  348. if (postData.changestatus !== undefined && parseInt(postData.changestatus) === 1) {
  349. change_status = true;
  350. // 更新原报人审批状态
  351. await this.transaction.update(this.ctx.service.changeAudit.tableName, {
  352. id: lastUser.id,
  353. status: audit.flow.auditStatus.checked,
  354. sin_time: new Date(),
  355. });
  356. }
  357. // 再插入postData里的变更审批人和清单
  358. if (postData.changeaudit !== undefined && postData.changeaudit !== '') {
  359. const changeAudit = postData.changeaudit.split(',');
  360. const insertCA = [];
  361. let uSite = 1;
  362. let uSort = parseInt(lastUser.usort) + 1;
  363. for (const [index, ca] of changeAudit.entries()) {
  364. const auditInfo = ca.split('/%/');
  365. const uStatus = change_status && index === 0 ? audit.flow.auditStatus.checking : audit.flow.auditStatus.uncheck;
  366. const sin_time = change_status && index === 0 ? new Date() : null;
  367. const caArray = {
  368. tid: tenderId,
  369. cid: changeInfo.cid,
  370. uid: auditInfo[0],
  371. name: auditInfo[1],
  372. jobs: auditInfo[2],
  373. company: auditInfo[3],
  374. times: changeInfo.times,
  375. usite: uSite,
  376. usort: uSort,
  377. status: uStatus,
  378. sin_time,
  379. };
  380. uSite++;
  381. uSort++;
  382. insertCA.push(caArray);
  383. // 添加短信通知-需要审批提醒功能
  384. if (change_status && index === 0) {
  385. const sms = new SMS(this.ctx);
  386. const code = await sms.contentChange(changeInfo.code);
  387. const shenpiUrl = await this.ctx.helper.urlToShort(
  388. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  389. );
  390. await this.ctx.helper.sendAliSms(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  391. biangeng: code,
  392. code: shenpiUrl,
  393. });
  394. // 微信模板通知
  395. const wechatData = {
  396. wap_url: shenpiUrl,
  397. status: wxConst.status.check,
  398. tips: wxConst.tips.check,
  399. code: this.ctx.session.sessionProject.code,
  400. c_name: changeInfo.name,
  401. };
  402. await this.ctx.helper.sendWechat(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  403. }
  404. }
  405. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insertCA);
  406. }
  407. let changeList = [];
  408. if (postData.changelist !== undefined && postData.changelist !== '') {
  409. changeList = postData.changelist.split('^_^');
  410. }
  411. let changeWhiteList = [];
  412. if (postData.changewhitelist !== undefined && postData.changewhitelist !== '') {
  413. changeWhiteList = postData.changewhitelist.split('^_^');
  414. }
  415. changeList.push.apply(changeList, changeWhiteList);
  416. const insertCL = [];
  417. let total_price = 0;
  418. if (changeList.length > 0) {
  419. for (const cl of changeList) {
  420. const clInfo = cl.split('*;*');
  421. const clArray = {
  422. tid: tenderId,
  423. cid: changeInfo.cid,
  424. lid: clInfo[8],
  425. code: clInfo[0],
  426. name: clInfo[1],
  427. bwmx: clInfo[2],
  428. unit: clInfo[3],
  429. unit_price: clInfo[4],
  430. oamount: clInfo[5],
  431. camount: clInfo[6],
  432. samount: '',
  433. detail: clInfo[7],
  434. spamount: clInfo[6],
  435. xmj_code: clInfo[9] !== '' ? clInfo[9] : null,
  436. xmj_jldy: clInfo[10] !== '' ? clInfo[10] : null,
  437. gcl_id: clInfo[11] !== '' ? clInfo[11] : '',
  438. };
  439. if (clInfo[4] === '') {
  440. delete clArray.unit_price;
  441. }
  442. insertCL.push(clArray);
  443. total_price = this.ctx.helper.accAdd(total_price, this.ctx.helper.mul(clArray.unit_price, clArray.spamount, this.ctx.tender.info.decimal.tp));
  444. }
  445. await this.transaction.insert(this.ctx.service.changeAuditList.tableName, insertCL);
  446. }
  447. // 修改变更令基本数据
  448. const cArray = {
  449. code: postData.code,
  450. name: postData.name,
  451. peg: postData.peg,
  452. org_name: postData.org_name,
  453. org_code: postData.org_code,
  454. new_name: postData.new_name,
  455. new_code: postData.new_code,
  456. content: postData.content,
  457. basis: postData.basis,
  458. expr: postData.expr,
  459. memo: postData.memo,
  460. type: postData.type.join(','),
  461. class: postData.class,
  462. quality: postData.quality,
  463. company: postData.company,
  464. charge: postData.charge,
  465. w_code: postData.w_code,
  466. total_price,
  467. };
  468. const options = {
  469. where: {
  470. cid: changeInfo.cid,
  471. },
  472. };
  473. if (change_status) {
  474. cArray.status = audit.flow.status.checking;
  475. cArray.cin_time = Date.parse(new Date()) / 1000;
  476. }
  477. await this.transaction.update(this.tableName, cArray, options);
  478. await this.transaction.commit();
  479. result = true;
  480. } catch (error) {
  481. await this.transaction.rollback();
  482. result = false;
  483. }
  484. return result;
  485. }
  486. /**
  487. * 保存变更信息
  488. * @param {int} postData - 表单提交的数据
  489. * @param {int} tenderId - 标段id
  490. * @return {void}
  491. */
  492. async saveInfo(postData) {
  493. // 初始化事务
  494. const transaction = await this.db.beginTransaction();
  495. let result = false;
  496. try {
  497. const options = {
  498. where: {
  499. cid: this.ctx.change.cid,
  500. },
  501. };
  502. await transaction.update(this.tableName, postData, options);
  503. await transaction.commit();
  504. result = true;
  505. } catch (error) {
  506. await transaction.rollback();
  507. result = false;
  508. }
  509. return result;
  510. }
  511. /**
  512. * 审批通过
  513. * @param {Number} pid 项目id
  514. * @param {int} postData - 表单提交的数据
  515. * @param {int} changeData - 变更令的数据
  516. * @return {void}
  517. */
  518. async approvalSuccess(pid, postData, changeData) {
  519. // 初始化事务
  520. this.transaction = await this.db.beginTransaction();
  521. let result = false;
  522. try {
  523. // 获取所有审核人列表
  524. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  525. // console.log('auditors', auditors);
  526. // console.log('postData', postData);
  527. // 添加到消息推送表
  528. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  529. const records = [];
  530. auditors.forEach(auditor => {
  531. records.push({
  532. pid,
  533. type: pushType.change,
  534. uid: auditor.uid,
  535. status: audit.flow.status.checked,
  536. content: noticeContent,
  537. });
  538. });
  539. await this.transaction.insert('zh_notice', records);
  540. // 设置审批人通过
  541. const audit_update = {
  542. id: postData.audit_id,
  543. sdesc: postData.sdesc,
  544. status: audit.flow.auditStatus.checked,
  545. sin_time: new Date(),
  546. };
  547. const change_update = {
  548. w_code: postData.w_code,
  549. status: audit.flow.status.checking,
  550. cin_time: Date.parse(new Date()) / 1000,
  551. };
  552. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  553. // 清单数据更新
  554. const bills_list = postData.bills_list.split(',');
  555. let total_price = 0;
  556. for (const bl of bills_list) {
  557. const listInfo = bl.split('_');
  558. const lid = listInfo[0];
  559. const amount = listInfo[1];
  560. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  561. if (changeListInfo !== undefined) {
  562. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, this.ctx.tender.info.decimal.tp));
  563. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  564. audit_amount.push(amount);
  565. const list_update = {
  566. id: lid,
  567. audit_amount: audit_amount.join(','),
  568. spamount: parseFloat(amount),
  569. };
  570. if (postData.audit_next_id === undefined) {
  571. list_update.samount = amount;
  572. }
  573. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  574. }
  575. }
  576. if (postData.audit_next_id === undefined) {
  577. // 变更令审批完成
  578. change_update.status = audit.flow.status.checked;
  579. change_update.p_code = postData.p_code;
  580. change_update.sin_time = Date.parse(new Date()) / 1000;
  581. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  582. // 添加短信通知-审批通过提醒功能
  583. // const mobile_array = [];
  584. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  585. const users = this._.map(auditList, 'uid');
  586. const sms = new SMS(this.ctx);
  587. const code = await sms.contentChange(changeData.code);
  588. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  589. biangeng: code,
  590. status: SmsAliConst.status.success,
  591. });
  592. // 微信模板通知
  593. const shenpiUrl = await this.ctx.helper.urlToShort(
  594. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  595. );
  596. const wechatData = {
  597. wap_url: shenpiUrl,
  598. status: wxConst.status.success,
  599. tips: wxConst.tips.success,
  600. code: this.ctx.session.sessionProject.code,
  601. c_name: changeData.name,
  602. };
  603. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  604. } else {
  605. // 设置下一个审批人为审批状态
  606. const nextAudit_update = {
  607. id: postData.audit_next_id,
  608. status: audit.flow.auditStatus.checking,
  609. sin_time: new Date(),
  610. };
  611. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  612. // 添加短信通知-需要审批提醒功能
  613. const nextAuditData = await this.ctx.service.changeAudit.getDataById(postData.audit_next_id);
  614. const sms = new SMS(this.ctx);
  615. const code = await sms.contentChange(changeData.code);
  616. const shenpiUrl = await this.ctx.helper.urlToShort(
  617. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  618. );
  619. await this.ctx.helper.sendAliSms(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  620. biangeng: code,
  621. code: shenpiUrl,
  622. });
  623. // 微信模板通知
  624. const wechatData = {
  625. wap_url: shenpiUrl,
  626. status: wxConst.status.check,
  627. tips: wxConst.tips.check,
  628. code: this.ctx.session.sessionProject.code,
  629. c_name: changeData.name,
  630. };
  631. await this.ctx.helper.sendWechat(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  632. }
  633. change_update.total_price = total_price;
  634. const options = {
  635. where: {
  636. cid: postData.change_id,
  637. },
  638. };
  639. await this.transaction.update(this.tableName, change_update, options);
  640. await this.transaction.commit();
  641. result = true;
  642. } catch (error) {
  643. console.log(error);
  644. await this.transaction.rollback();
  645. result = false;
  646. }
  647. return result;
  648. }
  649. /**
  650. * 审批终止
  651. * @param {int} postData - 表单提交的数据
  652. * @return {void}
  653. */
  654. async approvalStop(postData) {
  655. // 初始化事务
  656. this.transaction = await this.db.beginTransaction();
  657. let result = false;
  658. try {
  659. // 设置审批人终止
  660. const audit_update = {
  661. id: postData.audit_id,
  662. sdesc: postData.sdesc,
  663. status: 4,
  664. sin_time: new Date(),
  665. };
  666. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  667. // 设置变更令终止
  668. const change_update = {
  669. w_code: postData.w_code,
  670. status: 4,
  671. cin_time: Date.parse(new Date()) / 1000,
  672. };
  673. const options = {
  674. where: {
  675. cid: postData.change_id,
  676. },
  677. };
  678. await this.transaction.update(this.tableName, change_update, options);
  679. await this.transaction.commit();
  680. result = true;
  681. } catch (error) {
  682. await this.transaction.rollback();
  683. result = false;
  684. }
  685. return result;
  686. }
  687. /**
  688. * 审批退回到原报人
  689. * @param {Number} pid 项目id
  690. * @param {int} postData - 表单提交的数据
  691. * @param {int} changeData - 变更令的数据
  692. * @return {void}
  693. */
  694. async approvalBack(pid, postData, changeData) {
  695. // 初始化事务
  696. this.transaction = await this.db.beginTransaction();
  697. let result = false;
  698. try {
  699. // 获取所有审核人列表
  700. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  701. // 添加到消息推送表
  702. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  703. const records = [];
  704. auditors.forEach(auditor => {
  705. records.push({
  706. pid,
  707. type: pushType.change,
  708. uid: auditor.uid,
  709. status: audit.flow.status.backnew,
  710. content: noticeContent,
  711. });
  712. });
  713. await this.transaction.insert('zh_notice', records);
  714. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  715. // 设置审批人退回
  716. const audit_update = {
  717. id: postData.audit_id,
  718. sdesc: postData.sdesc,
  719. status: audit.flow.auditStatus.back,
  720. sin_time: new Date(),
  721. };
  722. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  723. // 新增新一次的审批人列表
  724. // 获取当前次数审批人列表
  725. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  726. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  727. let usort = lastauditInfo.usort + 1;
  728. const newTimes = changeInfo.times + 1;
  729. const insert_audit_array = [];
  730. for (const al of auditList) {
  731. const insert_audit = {
  732. tid: al.tid,
  733. cid: al.cid,
  734. uid: al.uid,
  735. name: al.name,
  736. jobs: al.jobs,
  737. company: al.company,
  738. times: newTimes,
  739. usite: al.usite,
  740. usort,
  741. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  742. };
  743. insert_audit_array.push(insert_audit);
  744. usort++;
  745. }
  746. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  747. // 变更金额也退回
  748. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  749. where: { cid: changeInfo.cid },
  750. });
  751. let total_price = 0;
  752. for (const cl of changeList) {
  753. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, this.ctx.tender.info.decimal.tp));
  754. }
  755. // 设置变更令退回
  756. const change_update = {
  757. w_code: postData.w_code,
  758. status: audit.flow.status.back,
  759. times: newTimes,
  760. cin_time: Date.parse(new Date()) / 1000,
  761. total_price,
  762. };
  763. const options = {
  764. where: {
  765. cid: postData.change_id,
  766. },
  767. };
  768. await this.transaction.update(this.tableName, change_update, options);
  769. await this.transaction.commit();
  770. result = true;
  771. const users = this._.map(insert_audit_array, 'uid');
  772. const sms = new SMS(this.ctx);
  773. const code = await sms.contentChange(changeData.code);
  774. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  775. biangeng: code,
  776. status: SmsAliConst.status.back,
  777. });
  778. // 微信模板通知
  779. const shenpiUrl = await this.ctx.helper.urlToShort(
  780. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  781. );
  782. const wechatData = {
  783. wap_url: shenpiUrl,
  784. status: wxConst.status.back,
  785. tips: wxConst.tips.back,
  786. code: this.ctx.session.sessionProject.code,
  787. c_name: changeInfo.name,
  788. };
  789. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  790. } catch (error) {
  791. await this.transaction.rollback();
  792. result = false;
  793. }
  794. return result;
  795. }
  796. /**
  797. * 审批退回到上一个审批人
  798. * @param {Number} pid 项目id
  799. * @param {int} postData - 表单提交的数据
  800. * @param {int} changeData - 变更令的数据
  801. * @return {void}
  802. */
  803. async approvalBackNew(pid, postData, changeData) {
  804. // 初始化事务
  805. this.transaction = await this.db.beginTransaction();
  806. let result = false;
  807. try {
  808. // 获取所有审核人列表
  809. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  810. // 添加到消息推送表
  811. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  812. const records = [];
  813. auditors.forEach(auditor => {
  814. records.push({
  815. pid,
  816. type: pushType.change,
  817. uid: auditor.uid,
  818. status: audit.flow.status.back,
  819. content: noticeContent,
  820. });
  821. });
  822. await this.transaction.insert('zh_notice', records);
  823. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  824. // 设置审批人退回
  825. const audit_update = {
  826. id: postData.audit_id,
  827. sdesc: postData.sdesc,
  828. status: audit.flow.auditStatus.backnew,
  829. sin_time: new Date(),
  830. };
  831. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  832. // 获取当前审批人信息
  833. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  834. // 获取当前次数审批人列表
  835. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  836. let usort = auditInfo.usort + 1;
  837. // 获取上一个审批人信息
  838. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  839. // 新增2个审批人到审批列表中
  840. const insert_audit1 = {
  841. tid: lastauditInfo.tid,
  842. cid: lastauditInfo.cid,
  843. uid: lastauditInfo.uid,
  844. name: lastauditInfo.name,
  845. jobs: lastauditInfo.jobs,
  846. company: lastauditInfo.company,
  847. times: lastauditInfo.times,
  848. usite: lastauditInfo.usite,
  849. usort,
  850. status: audit.flow.auditStatus.checking,
  851. sin_time: new Date(),
  852. };
  853. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  854. usort++;
  855. // 新增2个审批人到审批列表中
  856. const insert_audit2 = {
  857. tid: auditInfo.tid,
  858. cid: auditInfo.cid,
  859. uid: auditInfo.uid,
  860. name: auditInfo.name,
  861. jobs: auditInfo.jobs,
  862. company: auditInfo.company,
  863. times: auditInfo.times,
  864. usite: auditInfo.usite,
  865. usort,
  866. status: audit.flow.auditStatus.uncheck,
  867. };
  868. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  869. // 把接下未审批的审批人排序都加2
  870. for (const al of auditList) {
  871. const audit_update = {
  872. id: al.id,
  873. usort: al.usort + 2,
  874. };
  875. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  876. }
  877. // 审批列表数据也要回退
  878. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  879. where: { cid: changeInfo.cid },
  880. });
  881. let total_price = 0;
  882. for (const cl of changeList) {
  883. const audit_amount = cl.audit_amount.split(',');
  884. const last_amount = audit_amount[audit_amount.length - 1];
  885. audit_amount.splice(-1, 1);
  886. const list_update = {
  887. id: cl.id,
  888. audit_amount: audit_amount.join(','),
  889. spamount: parseFloat(last_amount),
  890. };
  891. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), this.ctx.tender.info.decimal.tp));
  892. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  893. }
  894. // 设置变更令退回
  895. const change_update = {
  896. w_code: postData.w_code,
  897. status: audit.flow.status.backnew,
  898. cin_time: Date.parse(new Date()) / 1000,
  899. total_price,
  900. };
  901. const options = {
  902. where: {
  903. cid: postData.change_id,
  904. },
  905. };
  906. await this.transaction.update(this.tableName, change_update, options);
  907. await this.transaction.commit();
  908. result = true;
  909. const sms = new SMS(this.ctx);
  910. const code = await sms.contentChange(changeData.code);
  911. const shenpiUrl = await this.ctx.helper.urlToShort(
  912. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  913. );
  914. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  915. biangeng: code,
  916. code: shenpiUrl,
  917. });
  918. // 微信模板通知
  919. const wechatData = {
  920. wap_url: shenpiUrl,
  921. status: wxConst.status.check,
  922. tips: wxConst.tips.check,
  923. code: this.ctx.session.sessionProject.code,
  924. c_name: changeInfo.name,
  925. };
  926. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  927. } catch (error) {
  928. await this.transaction.rollback();
  929. result = false;
  930. }
  931. return result;
  932. }
  933. /**
  934. * 查询可用的变更令
  935. * @param bills - 查询的清单
  936. * @param pos - 查询的部位
  937. * @return {Promise<*>} - 可用的变更令列表
  938. */
  939. async getValidChanges(tid, bills, pos) {
  940. const self = this;
  941. const getFilterPart = function(field, value) {
  942. return value
  943. ? field + ' = ' + self.db.escape(value)
  944. : self.db.format("(?? = null or ?? = '')", [field, field]);
  945. };
  946. const timesLen = 100;
  947. const filter = getFilterPart('cb.code', bills.b_code) +
  948. ' And ' + getFilterPart('cb.name', bills.name) +
  949. ' And ' + getFilterPart('cb.unit', bills.unit) +
  950. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  951. (pos ? getFilterPart('cb.bwmx', pos.name) : '');
  952. const sql =
  953. 'SELECT c.cid, c.code, c.name, c.w_code, c.p_code, c.peg, c.org_name, c.org_code, c.new_name, c.new_code,' +
  954. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  955. ' cb.id As cbid, cb.code As b_code, cb.name As b_name, cb.unit As b_unit, cb.samount As b_amount, cb.detail As b_detail, cb.bwmx As b_bwmx, ' +
  956. ' scb.used_amount' +
  957. ' FROM ' + this.tableName + ' As c ' +
  958. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  959. ' Left Join (' +
  960. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  961. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  962. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  963. ' FROM ' + this.ctx.service.stageChange.tableName +
  964. ' WHERE tid = ?' +
  965. ' GROUP BY cbid, sid' +
  966. ' ) As MF' +
  967. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  968. ' GROUP BY sc.cbid' +
  969. ' ) As scb ON cb.id = scb.cbid' +
  970. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  971. ' ORDER BY c.in_time';
  972. const sqlParam = [tid, tid, audit.flow.status.checked];
  973. const changes = await this.db.query(sql, sqlParam);
  974. for (const c of changes) {
  975. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  976. ' FROM ?? As ca ' +
  977. ' Left Join ?? As pa ' +
  978. ' On ca.uid = pa.id ' +
  979. ' Where ca.cid = ?';
  980. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  981. c.attachments = await this.db.query(aSql, aSqlParam);
  982. }
  983. return changes;
  984. }
  985. /**
  986. * 查询审批人可用的变更令
  987. * @param bills - 查询的清单
  988. * @param pos - 查询的部位
  989. * @return {Promise<*>} - 可用的变更令列表
  990. */
  991. async getAuditValidChanges(tid, bills, pos, times, order) {
  992. const timesLen = 100;
  993. const filter =
  994. 'cb.`code` = ' + this.db.escape(bills.b_code) +
  995. ' And cb.`name` = ' + this.db.escape(bills.name) +
  996. ' And cb.`unit` = ' + this.db.escape(bills.unit) +
  997. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  998. (pos ? ' And cb.`bwmx` = ' + this.db.escape(pos.name) : '');
  999. const sql =
  1000. 'SELECT c.cid, c.code, c.name, c.w_code, c.p_code, c.peg, c.org_name, c.org_code, c.new_name, c.new_code,' +
  1001. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  1002. ' cb.id As cbid, cb.code As b_code, cb.name As b_name, cb.unit As b_unit, cb.samount As b_amount, cb.detail As b_detail, cb.bwmx As b_bwmx, ' +
  1003. ' scb.used_amount' +
  1004. ' FROM ' + this.tableName + ' As c ' +
  1005. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1006. ' Left Join (' +
  1007. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  1008. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1009. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  1010. ' FROM ' + this.ctx.service.stageChange.tableName +
  1011. ' WHERE tid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) ' +
  1012. ' GROUP BY cbid, sid' +
  1013. ' ) As MF' +
  1014. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  1015. ' GROUP BY sc.cbid' +
  1016. ' ) As scb ON cb.id = scb.cbid' +
  1017. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1018. ' ORDER BY c.in_time';
  1019. const sqlParam = [tid, times, times, order, tid, audit.flow.status.checked];
  1020. const changes = await this.db.query(sql, sqlParam);
  1021. for (const c of changes) {
  1022. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1023. ' FROM ?? As ca ' +
  1024. ' Left Join ?? As pa ' +
  1025. ' On ca.uid = pa.id ' +
  1026. ' Where ca.cid = ?';
  1027. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1028. c.attachments = await this.db.query(aSql, aSqlParam);
  1029. }
  1030. return changes;
  1031. }
  1032. /**
  1033. * 查询变更令 + 变更令执行
  1034. * @param tid
  1035. * @return {Promise<void>}
  1036. */
  1037. async getChangeAndUsedInfo(tid) {
  1038. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1039. let filter;
  1040. if (lastStage.id === this.ctx.stage.id) {
  1041. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1042. lastStage.order,
  1043. lastStage.order,
  1044. this.ctx.stage.curTimes,
  1045. this.ctx.stage.curTimes,
  1046. this.ctx.stage.curOrder,
  1047. ]);
  1048. } else {
  1049. if (lastStage.status === audit.stage.status.uncheck) {
  1050. filter = ' And s.order < ' + lastStage.order;
  1051. } else if (lastStage.status === audit.stage.status.checked) {
  1052. filter = '';
  1053. } else if (lastStage.status === audit.stage.status.checkNo) {
  1054. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1055. } else {
  1056. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1057. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1058. lastStage.order,
  1059. lastStage.order,
  1060. lastStage.times,
  1061. lastStage.times,
  1062. curAuditor.order - 1,
  1063. ]);
  1064. }
  1065. }
  1066. const sql =
  1067. 'SELECT C.*, Sum(U.utp) As used_tp, Round(Sum(U.utp) / C.total_price * 100, 2) As used_pt' +
  1068. ' FROM ' +
  1069. this.tableName +
  1070. ' As C' +
  1071. ' LEFT JOIN (SELECT sc.tid, sc.cid, sc.cbid, Round(SUM(sc.qty) * cb.unit_price, ?) As utp' +
  1072. ' FROM ' +
  1073. this.ctx.service.stageChange.tableName +
  1074. ' As sc' +
  1075. ' INNER JOIN (' +
  1076. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1077. ' FROM ' +
  1078. this.ctx.service.stageChange.tableName +
  1079. ' As sChange ' +
  1080. ' LEFT JOIN ' +
  1081. this.ctx.service.stage.tableName +
  1082. ' As s' +
  1083. ' ON sChange.sid = s.id' +
  1084. ' WHERE sChange.tid = ?' +
  1085. filter +
  1086. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1087. ' ) As m' +
  1088. ' ON sc.stimes = m.stimes And sc.sorder = m.sorder And sc.`cbid` = m.`cbid` AND sc.`sid` = m.`sid` And sc.`lid` = m.`lid` And sc.`pid` = m.`pid`' +
  1089. ' LEFT JOIN ' +
  1090. this.ctx.service.changeAuditList.tableName +
  1091. ' As cb ON sc.cbid = cb.id' +
  1092. ' GROUP By sc.`cbid`' +
  1093. ' ) As U ON C.cid = U.cid' +
  1094. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1095. ' GROUP By C.cid' +
  1096. ' ORDER By in_time';
  1097. const sqlParam = [this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1098. return await this.db.query(sql, sqlParam);
  1099. }
  1100. /**
  1101. * 查询可用的变更令
  1102. * @param { string } cid - 查询的清单
  1103. * @return {Promise<*>} - 可用的变更令列表
  1104. */
  1105. async delete(cid) {
  1106. // 初始化事务
  1107. this.transaction = await this.db.beginTransaction();
  1108. let result = false;
  1109. try {
  1110. // 先删除清单,审批人列表
  1111. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1112. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1113. // 再删除附件和附件文件ni zuo
  1114. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1115. if (attList.length !== 0) {
  1116. for (const att of attList) {
  1117. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1118. }
  1119. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1120. }
  1121. // 最后删除变更令
  1122. await this.transaction.delete(this.tableName, { cid });
  1123. await this.transaction.commit();
  1124. result = true;
  1125. } catch (e) {
  1126. await this.transaction.rollback();
  1127. result = false;
  1128. }
  1129. return result;
  1130. }
  1131. /**
  1132. * 重新审批变更令
  1133. * @param { string } cid - 查询的清单
  1134. * @return {Promise<*>} - 可用的变更令列表
  1135. */
  1136. async checkAgain(cid) {
  1137. // 初始化事务
  1138. this.transaction = await this.db.beginTransaction();
  1139. let result = false;
  1140. try {
  1141. const changeInfo = await this.getDataByCondition({ cid });
  1142. // 获取终审
  1143. const auditInfo = (
  1144. await this.ctx.service.changeAudit.getAllDataByCondition({
  1145. where: { cid },
  1146. orders: [['usort', 'desc']],
  1147. limit: 1,
  1148. offset: 0,
  1149. })
  1150. )[0];
  1151. let usort = auditInfo.usort + 1;
  1152. // 新增2个审批状态到审批列表中
  1153. const insert_audit1 = {
  1154. tid: auditInfo.tid,
  1155. cid: auditInfo.cid,
  1156. uid: auditInfo.uid,
  1157. name: auditInfo.name,
  1158. jobs: auditInfo.jobs,
  1159. company: auditInfo.company,
  1160. times: auditInfo.times,
  1161. usite: auditInfo.usite,
  1162. usort,
  1163. sin_time: new Date(),
  1164. status: audit.flow.auditStatus.checkAgain,
  1165. };
  1166. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1167. usort++;
  1168. // 新增2个审批人到审批列表中
  1169. const insert_audit2 = {
  1170. tid: auditInfo.tid,
  1171. cid: auditInfo.cid,
  1172. uid: auditInfo.uid,
  1173. name: auditInfo.name,
  1174. jobs: auditInfo.jobs,
  1175. company: auditInfo.company,
  1176. times: auditInfo.times,
  1177. usite: auditInfo.usite,
  1178. usort,
  1179. status: audit.flow.auditStatus.checking,
  1180. sin_time: new Date(),
  1181. };
  1182. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1183. // 审批列表数据也要回退
  1184. let total_price = 0;
  1185. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1186. where: { cid: changeInfo.cid },
  1187. });
  1188. for (const cl of changeList) {
  1189. const audit_amount = cl.audit_amount.split(',');
  1190. const last_amount = audit_amount[audit_amount.length - 1];
  1191. audit_amount.splice(-1, 1);
  1192. const list_update = {
  1193. id: cl.id,
  1194. audit_amount: audit_amount.join(','),
  1195. samount: '',
  1196. };
  1197. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), this.ctx.tender.info.decimal.tp));
  1198. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1199. }
  1200. // 设置变更令审批中
  1201. const change_update = {
  1202. p_code: null,
  1203. status: audit.flow.status.checking,
  1204. cin_time: Date.parse(new Date()) / 1000,
  1205. sin_time: null,
  1206. total_price,
  1207. };
  1208. const options = {
  1209. where: {
  1210. cid: changeInfo.cid,
  1211. },
  1212. };
  1213. await this.transaction.update(this.tableName, change_update, options);
  1214. await this.transaction.commit();
  1215. result = true;
  1216. const sms = new SMS(this.ctx);
  1217. const code = await sms.contentChange(changeInfo.code);
  1218. const shenpiUrl = await this.ctx.helper.urlToShort(
  1219. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  1220. );
  1221. await this.ctx.helper.sendAliSms(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1222. biangeng: code,
  1223. code: shenpiUrl,
  1224. });
  1225. // 微信模板通知
  1226. const wechatData = {
  1227. wap_url: shenpiUrl,
  1228. status: wxConst.status.check,
  1229. tips: wxConst.tips.check,
  1230. code: this.ctx.session.sessionProject.code,
  1231. c_name: changeInfo.name,
  1232. };
  1233. await this.ctx.helper.sendWechat(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1234. } catch (error) {
  1235. await this.transaction.rollback();
  1236. result = false;
  1237. }
  1238. return result;
  1239. }
  1240. /**
  1241. * 判断是否有重名的变更令
  1242. * @param cid
  1243. * @param code
  1244. * @param tid
  1245. * @return {Promise<void>}
  1246. */
  1247. async isRepeat(cid, code, tid) {
  1248. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1249. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1250. const result = await this.db.queryOne(sql, sqlParam);
  1251. return result.count !== 0;
  1252. }
  1253. async getAllCheckedChanges(tid) {
  1254. return await this.getAllDataByCondition({
  1255. where: { tid, status: audit.flow.status.checked },
  1256. orders: [['in_time', 'desc']],
  1257. });
  1258. }
  1259. /**
  1260. * 用于添加推送所需的content内容
  1261. * @param {Number} pid 项目id
  1262. * @param {Number} tid 台账id
  1263. * @param {Number} cid 变更id
  1264. * @param {Number} uid 审核人id
  1265. */
  1266. async getNoticeContent(pid, tid, cid, uid) {
  1267. const noticeSql =
  1268. 'SELECT * FROM (SELECT ' +
  1269. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1270. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1271. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1272. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1273. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1274. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1275. const content = await this.db.query(noticeSql, noticeSqlParam);
  1276. return content.length ? JSON.stringify(content[0]) : '';
  1277. }
  1278. /**
  1279. * 获取当前标段其他变更令
  1280. * @param {Number} tid - 标段id
  1281. * @param {Number} cid - 当前变更令
  1282. */
  1283. async getOthersChange(tid, cid) {
  1284. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1285. const sqlParam = [this.tableName, tid, cid];
  1286. const data = await this.db.query(sql, sqlParam);
  1287. const changeClassObj = {};
  1288. for (const c in changeConst.class) {
  1289. if (changeConst.class.hasOwnProperty(c)) {
  1290. const item = changeConst.class[c];
  1291. changeClassObj[item.value] = item.name;
  1292. }
  1293. }
  1294. for (let i = 0; i < data.length; i++) {
  1295. data[i].class = changeClassObj[data[i].class];
  1296. }
  1297. return data;
  1298. }
  1299. /**
  1300. * 拷贝变更令至当前变更令
  1301. * @param {String} cid - 当前变更令
  1302. * @param {String} copy_cid - 要拷贝的变更令
  1303. */
  1304. async handleCopyChange(cid, copy_cid) {
  1305. // const change = await this.getDataByCondition({ cid });
  1306. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1307. return await this.update({ peg: copyChange.peg, org_name: copyChange.org_name, org_code: copyChange.org_code, new_name: copyChange.new_name, content: copyChange.content, basis: copyChange.basis, expr: copyChange.expr, memo: copyChange.memo, type: copyChange.type,
  1308. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1309. cid,
  1310. });
  1311. }
  1312. }
  1313. return Change;
  1314. };