change.js 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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. tp_decimal: this.ctx.tender.info.decimal.tp,
  468. };
  469. const options = {
  470. where: {
  471. cid: changeInfo.cid,
  472. },
  473. };
  474. if (change_status) {
  475. cArray.status = audit.flow.status.checking;
  476. cArray.cin_time = Date.parse(new Date()) / 1000;
  477. }
  478. await this.transaction.update(this.tableName, cArray, options);
  479. await this.transaction.commit();
  480. result = true;
  481. } catch (error) {
  482. await this.transaction.rollback();
  483. result = false;
  484. }
  485. return result;
  486. }
  487. /**
  488. * 保存变更信息
  489. * @param {int} postData - 表单提交的数据
  490. * @param {int} tenderId - 标段id
  491. * @return {void}
  492. */
  493. async saveInfo(postData) {
  494. // 初始化事务
  495. const transaction = await this.db.beginTransaction();
  496. let result = false;
  497. try {
  498. const options = {
  499. where: {
  500. cid: this.ctx.change.cid,
  501. },
  502. };
  503. await transaction.update(this.tableName, postData, options);
  504. await transaction.commit();
  505. result = true;
  506. } catch (error) {
  507. await transaction.rollback();
  508. result = false;
  509. }
  510. return result;
  511. }
  512. /**
  513. * 审批通过
  514. * @param {Number} pid 项目id
  515. * @param {int} postData - 表单提交的数据
  516. * @param {int} changeData - 变更令的数据
  517. * @return {void}
  518. */
  519. async approvalSuccess(pid, postData, changeData) {
  520. // 初始化事务
  521. this.transaction = await this.db.beginTransaction();
  522. let result = false;
  523. try {
  524. // 获取所有审核人列表
  525. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  526. // console.log('auditors', auditors);
  527. // console.log('postData', postData);
  528. // 添加到消息推送表
  529. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  530. const records = [];
  531. auditors.forEach(auditor => {
  532. records.push({
  533. pid,
  534. type: pushType.change,
  535. uid: auditor.uid,
  536. status: audit.flow.status.checked,
  537. content: noticeContent,
  538. });
  539. });
  540. await this.transaction.insert('zh_notice', records);
  541. // 设置审批人通过
  542. const audit_update = {
  543. id: postData.audit_id,
  544. sdesc: postData.sdesc,
  545. status: audit.flow.auditStatus.checked,
  546. sin_time: new Date(),
  547. };
  548. const change_update = {
  549. w_code: postData.w_code,
  550. status: audit.flow.status.checking,
  551. cin_time: Date.parse(new Date()) / 1000,
  552. };
  553. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  554. // 清单数据更新
  555. const bills_list = postData.bills_list.split(',');
  556. let total_price = 0;
  557. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  558. for (const bl of bills_list) {
  559. const listInfo = bl.split('_');
  560. const lid = listInfo[0];
  561. const amount = listInfo[1];
  562. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  563. if (changeListInfo !== undefined) {
  564. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, tp_decimal));
  565. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  566. audit_amount.push(amount);
  567. const list_update = {
  568. id: lid,
  569. audit_amount: audit_amount.join(','),
  570. spamount: parseFloat(amount),
  571. };
  572. if (postData.audit_next_id === undefined) {
  573. list_update.samount = amount;
  574. }
  575. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  576. }
  577. }
  578. if (postData.audit_next_id === undefined) {
  579. // 变更令审批完成
  580. change_update.status = audit.flow.status.checked;
  581. change_update.p_code = postData.p_code;
  582. change_update.sin_time = Date.parse(new Date()) / 1000;
  583. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  584. // 添加短信通知-审批通过提醒功能
  585. // const mobile_array = [];
  586. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  587. const users = this._.map(auditList, 'uid');
  588. const sms = new SMS(this.ctx);
  589. const code = await sms.contentChange(changeData.code);
  590. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  591. biangeng: code,
  592. status: SmsAliConst.status.success,
  593. });
  594. // 微信模板通知
  595. const shenpiUrl = await this.ctx.helper.urlToShort(
  596. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  597. );
  598. const wechatData = {
  599. wap_url: shenpiUrl,
  600. status: wxConst.status.success,
  601. tips: wxConst.tips.success,
  602. code: this.ctx.session.sessionProject.code,
  603. c_name: changeData.name,
  604. };
  605. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  606. } else {
  607. // 设置下一个审批人为审批状态
  608. const nextAudit_update = {
  609. id: postData.audit_next_id,
  610. status: audit.flow.auditStatus.checking,
  611. sin_time: new Date(),
  612. };
  613. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  614. // 添加短信通知-需要审批提醒功能
  615. const nextAuditData = await this.ctx.service.changeAudit.getDataById(postData.audit_next_id);
  616. const sms = new SMS(this.ctx);
  617. const code = await sms.contentChange(changeData.code);
  618. const shenpiUrl = await this.ctx.helper.urlToShort(
  619. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  620. );
  621. await this.ctx.helper.sendAliSms(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  622. biangeng: code,
  623. code: shenpiUrl,
  624. });
  625. // 微信模板通知
  626. const wechatData = {
  627. wap_url: shenpiUrl,
  628. status: wxConst.status.check,
  629. tips: wxConst.tips.check,
  630. code: this.ctx.session.sessionProject.code,
  631. c_name: changeData.name,
  632. };
  633. await this.ctx.helper.sendWechat(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  634. }
  635. change_update.total_price = total_price;
  636. const options = {
  637. where: {
  638. cid: postData.change_id,
  639. },
  640. };
  641. await this.transaction.update(this.tableName, change_update, options);
  642. await this.transaction.commit();
  643. result = true;
  644. } catch (error) {
  645. console.log(error);
  646. await this.transaction.rollback();
  647. result = false;
  648. }
  649. return result;
  650. }
  651. /**
  652. * 审批终止
  653. * @param {int} postData - 表单提交的数据
  654. * @return {void}
  655. */
  656. async approvalStop(postData) {
  657. // 初始化事务
  658. this.transaction = await this.db.beginTransaction();
  659. let result = false;
  660. try {
  661. // 设置审批人终止
  662. const audit_update = {
  663. id: postData.audit_id,
  664. sdesc: postData.sdesc,
  665. status: 4,
  666. sin_time: new Date(),
  667. };
  668. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  669. // 设置变更令终止
  670. const change_update = {
  671. w_code: postData.w_code,
  672. status: 4,
  673. cin_time: Date.parse(new Date()) / 1000,
  674. };
  675. const options = {
  676. where: {
  677. cid: postData.change_id,
  678. },
  679. };
  680. await this.transaction.update(this.tableName, change_update, options);
  681. await this.transaction.commit();
  682. result = true;
  683. } catch (error) {
  684. await this.transaction.rollback();
  685. result = false;
  686. }
  687. return result;
  688. }
  689. /**
  690. * 审批退回到原报人
  691. * @param {Number} pid 项目id
  692. * @param {int} postData - 表单提交的数据
  693. * @param {int} changeData - 变更令的数据
  694. * @return {void}
  695. */
  696. async approvalBack(pid, postData, changeData) {
  697. // 初始化事务
  698. this.transaction = await this.db.beginTransaction();
  699. let result = false;
  700. try {
  701. // 获取所有审核人列表
  702. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  703. // 添加到消息推送表
  704. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  705. const records = [];
  706. auditors.forEach(auditor => {
  707. records.push({
  708. pid,
  709. type: pushType.change,
  710. uid: auditor.uid,
  711. status: audit.flow.status.backnew,
  712. content: noticeContent,
  713. });
  714. });
  715. await this.transaction.insert('zh_notice', records);
  716. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  717. // 设置审批人退回
  718. const audit_update = {
  719. id: postData.audit_id,
  720. sdesc: postData.sdesc,
  721. status: audit.flow.auditStatus.back,
  722. sin_time: new Date(),
  723. };
  724. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  725. // 新增新一次的审批人列表
  726. // 获取当前次数审批人列表
  727. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  728. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  729. let usort = lastauditInfo.usort + 1;
  730. const newTimes = changeInfo.times + 1;
  731. const insert_audit_array = [];
  732. for (const al of auditList) {
  733. const insert_audit = {
  734. tid: al.tid,
  735. cid: al.cid,
  736. uid: al.uid,
  737. name: al.name,
  738. jobs: al.jobs,
  739. company: al.company,
  740. times: newTimes,
  741. usite: al.usite,
  742. usort,
  743. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  744. };
  745. insert_audit_array.push(insert_audit);
  746. usort++;
  747. }
  748. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  749. // 变更金额也退回
  750. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  751. where: { cid: changeInfo.cid },
  752. });
  753. let total_price = 0;
  754. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  755. for (const cl of changeList) {
  756. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  757. }
  758. // 设置变更令退回
  759. const change_update = {
  760. w_code: postData.w_code,
  761. status: audit.flow.status.back,
  762. times: newTimes,
  763. cin_time: Date.parse(new Date()) / 1000,
  764. total_price,
  765. tp_decimal: null,
  766. };
  767. const options = {
  768. where: {
  769. cid: postData.change_id,
  770. },
  771. };
  772. await this.transaction.update(this.tableName, change_update, options);
  773. await this.transaction.commit();
  774. result = true;
  775. const users = this._.map(insert_audit_array, 'uid');
  776. const sms = new SMS(this.ctx);
  777. const code = await sms.contentChange(changeData.code);
  778. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  779. biangeng: code,
  780. status: SmsAliConst.status.back,
  781. });
  782. // 微信模板通知
  783. const shenpiUrl = await this.ctx.helper.urlToShort(
  784. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  785. );
  786. const wechatData = {
  787. wap_url: shenpiUrl,
  788. status: wxConst.status.back,
  789. tips: wxConst.tips.back,
  790. code: this.ctx.session.sessionProject.code,
  791. c_name: changeInfo.name,
  792. };
  793. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  794. } catch (error) {
  795. await this.transaction.rollback();
  796. result = false;
  797. }
  798. return result;
  799. }
  800. /**
  801. * 审批退回到上一个审批人
  802. * @param {Number} pid 项目id
  803. * @param {int} postData - 表单提交的数据
  804. * @param {int} changeData - 变更令的数据
  805. * @return {void}
  806. */
  807. async approvalBackNew(pid, postData, changeData) {
  808. // 初始化事务
  809. this.transaction = await this.db.beginTransaction();
  810. let result = false;
  811. try {
  812. // 获取所有审核人列表
  813. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  814. // 添加到消息推送表
  815. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  816. const records = [];
  817. auditors.forEach(auditor => {
  818. records.push({
  819. pid,
  820. type: pushType.change,
  821. uid: auditor.uid,
  822. status: audit.flow.status.back,
  823. content: noticeContent,
  824. });
  825. });
  826. await this.transaction.insert('zh_notice', records);
  827. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  828. // 设置审批人退回
  829. const audit_update = {
  830. id: postData.audit_id,
  831. sdesc: postData.sdesc,
  832. status: audit.flow.auditStatus.backnew,
  833. sin_time: new Date(),
  834. };
  835. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  836. // 获取当前审批人信息
  837. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  838. // 获取当前次数审批人列表
  839. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  840. let usort = auditInfo.usort + 1;
  841. // 获取上一个审批人信息
  842. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  843. // 新增2个审批人到审批列表中
  844. const insert_audit1 = {
  845. tid: lastauditInfo.tid,
  846. cid: lastauditInfo.cid,
  847. uid: lastauditInfo.uid,
  848. name: lastauditInfo.name,
  849. jobs: lastauditInfo.jobs,
  850. company: lastauditInfo.company,
  851. times: lastauditInfo.times,
  852. usite: lastauditInfo.usite,
  853. usort,
  854. status: audit.flow.auditStatus.checking,
  855. sin_time: new Date(),
  856. };
  857. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  858. usort++;
  859. // 新增2个审批人到审批列表中
  860. const insert_audit2 = {
  861. tid: auditInfo.tid,
  862. cid: auditInfo.cid,
  863. uid: auditInfo.uid,
  864. name: auditInfo.name,
  865. jobs: auditInfo.jobs,
  866. company: auditInfo.company,
  867. times: auditInfo.times,
  868. usite: auditInfo.usite,
  869. usort,
  870. status: audit.flow.auditStatus.uncheck,
  871. };
  872. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  873. // 把接下未审批的审批人排序都加2
  874. for (const al of auditList) {
  875. const audit_update = {
  876. id: al.id,
  877. usort: al.usort + 2,
  878. };
  879. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  880. }
  881. // 审批列表数据也要回退
  882. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  883. where: { cid: changeInfo.cid },
  884. });
  885. let total_price = 0;
  886. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  887. for (const cl of changeList) {
  888. const audit_amount = cl.audit_amount.split(',');
  889. const last_amount = audit_amount[audit_amount.length - 1];
  890. audit_amount.splice(-1, 1);
  891. const list_update = {
  892. id: cl.id,
  893. audit_amount: audit_amount.join(','),
  894. spamount: parseFloat(last_amount),
  895. };
  896. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  897. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  898. }
  899. // 设置变更令退回
  900. const change_update = {
  901. w_code: postData.w_code,
  902. status: audit.flow.status.backnew,
  903. cin_time: Date.parse(new Date()) / 1000,
  904. total_price,
  905. };
  906. const options = {
  907. where: {
  908. cid: postData.change_id,
  909. },
  910. };
  911. await this.transaction.update(this.tableName, change_update, options);
  912. await this.transaction.commit();
  913. result = true;
  914. const sms = new SMS(this.ctx);
  915. const code = await sms.contentChange(changeData.code);
  916. const shenpiUrl = await this.ctx.helper.urlToShort(
  917. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  918. );
  919. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  920. biangeng: code,
  921. code: shenpiUrl,
  922. });
  923. // 微信模板通知
  924. const wechatData = {
  925. wap_url: shenpiUrl,
  926. status: wxConst.status.check,
  927. tips: wxConst.tips.check,
  928. code: this.ctx.session.sessionProject.code,
  929. c_name: changeInfo.name,
  930. };
  931. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  932. } catch (error) {
  933. await this.transaction.rollback();
  934. result = false;
  935. }
  936. return result;
  937. }
  938. /**
  939. * 查询可用的变更令
  940. * @param bills - 查询的清单
  941. * @param pos - 查询的部位
  942. * @return {Promise<*>} - 可用的变更令列表
  943. */
  944. async getValidChanges(tid, bills, pos) {
  945. const self = this;
  946. const getFilterPart = function(field, value) {
  947. return value
  948. ? field + ' = ' + self.db.escape(value)
  949. : self.db.format("(?? = null or ?? = '')", [field, field]);
  950. };
  951. const timesLen = 100;
  952. const filter = getFilterPart('cb.code', bills.b_code) +
  953. ' And ' + getFilterPart('cb.name', bills.name) +
  954. ' And ' + getFilterPart('cb.unit', bills.unit) +
  955. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  956. (pos ? getFilterPart('cb.bwmx', pos.name) : '');
  957. const sql =
  958. '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,' +
  959. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  960. ' 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, ' +
  961. ' scb.used_amount' +
  962. ' FROM ' + this.tableName + ' As c ' +
  963. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  964. ' Left Join (' +
  965. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  966. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  967. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  968. ' FROM ' + this.ctx.service.stageChange.tableName +
  969. ' WHERE tid = ?' +
  970. ' GROUP BY cbid, sid' +
  971. ' ) As MF' +
  972. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  973. ' GROUP BY sc.cbid' +
  974. ' ) As scb ON cb.id = scb.cbid' +
  975. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  976. ' ORDER BY c.in_time';
  977. const sqlParam = [tid, tid, audit.flow.status.checked];
  978. const changes = await this.db.query(sql, sqlParam);
  979. for (const c of changes) {
  980. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  981. ' FROM ?? As ca ' +
  982. ' Left Join ?? As pa ' +
  983. ' On ca.uid = pa.id ' +
  984. ' Where ca.cid = ?';
  985. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  986. c.attachments = await this.db.query(aSql, aSqlParam);
  987. }
  988. return changes;
  989. }
  990. /**
  991. * 查询审批人可用的变更令
  992. * @param bills - 查询的清单
  993. * @param pos - 查询的部位
  994. * @return {Promise<*>} - 可用的变更令列表
  995. */
  996. async getAuditValidChanges(tid, bills, pos, times, order) {
  997. const timesLen = 100;
  998. const filter =
  999. 'cb.`code` = ' + this.db.escape(bills.b_code) +
  1000. ' And cb.`name` = ' + this.db.escape(bills.name) +
  1001. ' And cb.`unit` = ' + this.db.escape(bills.unit) +
  1002. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  1003. (pos ? ' And cb.`bwmx` = ' + this.db.escape(pos.name) : '');
  1004. const sql =
  1005. '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,' +
  1006. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  1007. ' 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, ' +
  1008. ' scb.used_amount' +
  1009. ' FROM ' + this.tableName + ' As c ' +
  1010. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1011. ' Left Join (' +
  1012. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  1013. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1014. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  1015. ' FROM ' + this.ctx.service.stageChange.tableName +
  1016. ' WHERE tid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) ' +
  1017. ' GROUP BY cbid, sid' +
  1018. ' ) As MF' +
  1019. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  1020. ' GROUP BY sc.cbid' +
  1021. ' ) As scb ON cb.id = scb.cbid' +
  1022. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1023. ' ORDER BY c.in_time';
  1024. const sqlParam = [tid, times, times, order, tid, audit.flow.status.checked];
  1025. const changes = await this.db.query(sql, sqlParam);
  1026. for (const c of changes) {
  1027. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1028. ' FROM ?? As ca ' +
  1029. ' Left Join ?? As pa ' +
  1030. ' On ca.uid = pa.id ' +
  1031. ' Where ca.cid = ?';
  1032. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1033. c.attachments = await this.db.query(aSql, aSqlParam);
  1034. }
  1035. return changes;
  1036. }
  1037. /**
  1038. * 查询变更令 + 变更令执行
  1039. * @param tid
  1040. * @return {Promise<void>}
  1041. */
  1042. async getChangeAndUsedInfo(tid) {
  1043. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1044. let filter;
  1045. if (lastStage.id === this.ctx.stage.id) {
  1046. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1047. lastStage.order,
  1048. lastStage.order,
  1049. this.ctx.stage.curTimes,
  1050. this.ctx.stage.curTimes,
  1051. this.ctx.stage.curOrder,
  1052. ]);
  1053. } else {
  1054. if (lastStage.status === audit.stage.status.uncheck) {
  1055. filter = ' And s.order < ' + lastStage.order;
  1056. } else if (lastStage.status === audit.stage.status.checked) {
  1057. filter = '';
  1058. } else if (lastStage.status === audit.stage.status.checkNo) {
  1059. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1060. } else {
  1061. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1062. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1063. lastStage.order,
  1064. lastStage.order,
  1065. lastStage.times,
  1066. lastStage.times,
  1067. curAuditor.order - 1,
  1068. ]);
  1069. }
  1070. }
  1071. const sql =
  1072. 'SELECT C.*, Sum(U.utp) As used_tp, Round(Sum(U.utp) / C.total_price * 100, 2) As used_pt' +
  1073. ' FROM ' +
  1074. this.tableName +
  1075. ' As C' +
  1076. ' LEFT JOIN (SELECT sc.tid, sc.cid, sc.cbid, Round(SUM(sc.qty) * cb.unit_price, ?) As utp' +
  1077. ' FROM ' +
  1078. this.ctx.service.stageChange.tableName +
  1079. ' As sc' +
  1080. ' INNER JOIN (' +
  1081. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1082. ' FROM ' +
  1083. this.ctx.service.stageChange.tableName +
  1084. ' As sChange ' +
  1085. ' LEFT JOIN ' +
  1086. this.ctx.service.stage.tableName +
  1087. ' As s' +
  1088. ' ON sChange.sid = s.id' +
  1089. ' WHERE sChange.tid = ?' +
  1090. filter +
  1091. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1092. ' ) As m' +
  1093. ' 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`' +
  1094. ' LEFT JOIN ' +
  1095. this.ctx.service.changeAuditList.tableName +
  1096. ' As cb ON sc.cbid = cb.id' +
  1097. ' GROUP By sc.`cbid`' +
  1098. ' ) As U ON C.cid = U.cid' +
  1099. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1100. ' GROUP By C.cid' +
  1101. ' ORDER By in_time';
  1102. const sqlParam = [this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1103. return await this.db.query(sql, sqlParam);
  1104. }
  1105. /**
  1106. * 查询可用的变更令
  1107. * @param { string } cid - 查询的清单
  1108. * @return {Promise<*>} - 可用的变更令列表
  1109. */
  1110. async delete(cid) {
  1111. // 初始化事务
  1112. this.transaction = await this.db.beginTransaction();
  1113. let result = false;
  1114. try {
  1115. // 先删除清单,审批人列表
  1116. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1117. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1118. // 再删除附件和附件文件ni zuo
  1119. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1120. if (attList.length !== 0) {
  1121. for (const att of attList) {
  1122. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1123. }
  1124. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1125. }
  1126. // 最后删除变更令
  1127. await this.transaction.delete(this.tableName, { cid });
  1128. await this.transaction.commit();
  1129. result = true;
  1130. } catch (e) {
  1131. await this.transaction.rollback();
  1132. result = false;
  1133. }
  1134. return result;
  1135. }
  1136. /**
  1137. * 重新审批变更令
  1138. * @param { string } cid - 查询的清单
  1139. * @return {Promise<*>} - 可用的变更令列表
  1140. */
  1141. async checkAgain(cid) {
  1142. // 初始化事务
  1143. this.transaction = await this.db.beginTransaction();
  1144. let result = false;
  1145. try {
  1146. const changeInfo = await this.getDataByCondition({ cid });
  1147. // 获取终审
  1148. const auditInfo = (
  1149. await this.ctx.service.changeAudit.getAllDataByCondition({
  1150. where: { cid },
  1151. orders: [['usort', 'desc']],
  1152. limit: 1,
  1153. offset: 0,
  1154. })
  1155. )[0];
  1156. let usort = auditInfo.usort + 1;
  1157. // 新增2个审批状态到审批列表中
  1158. const insert_audit1 = {
  1159. tid: auditInfo.tid,
  1160. cid: auditInfo.cid,
  1161. uid: auditInfo.uid,
  1162. name: auditInfo.name,
  1163. jobs: auditInfo.jobs,
  1164. company: auditInfo.company,
  1165. times: auditInfo.times,
  1166. usite: auditInfo.usite,
  1167. usort,
  1168. sin_time: new Date(),
  1169. status: audit.flow.auditStatus.checkAgain,
  1170. };
  1171. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1172. usort++;
  1173. // 新增2个审批人到审批列表中
  1174. const insert_audit2 = {
  1175. tid: auditInfo.tid,
  1176. cid: auditInfo.cid,
  1177. uid: auditInfo.uid,
  1178. name: auditInfo.name,
  1179. jobs: auditInfo.jobs,
  1180. company: auditInfo.company,
  1181. times: auditInfo.times,
  1182. usite: auditInfo.usite,
  1183. usort,
  1184. status: audit.flow.auditStatus.checking,
  1185. sin_time: new Date(),
  1186. };
  1187. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1188. // 审批列表数据也要回退
  1189. let total_price = 0;
  1190. const tp_decimal = changeInfo.tp_decimal ? changeInfo.tp_decimal : this.ctx.tender.info.decimal.tp;
  1191. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1192. where: { cid: changeInfo.cid },
  1193. });
  1194. for (const cl of changeList) {
  1195. const audit_amount = cl.audit_amount.split(',');
  1196. const last_amount = audit_amount[audit_amount.length - 1];
  1197. audit_amount.splice(-1, 1);
  1198. const list_update = {
  1199. id: cl.id,
  1200. audit_amount: audit_amount.join(','),
  1201. samount: '',
  1202. };
  1203. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1204. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1205. }
  1206. // 设置变更令审批中
  1207. const change_update = {
  1208. p_code: null,
  1209. status: audit.flow.status.checking,
  1210. cin_time: Date.parse(new Date()) / 1000,
  1211. sin_time: null,
  1212. total_price,
  1213. };
  1214. const options = {
  1215. where: {
  1216. cid: changeInfo.cid,
  1217. },
  1218. };
  1219. await this.transaction.update(this.tableName, change_update, options);
  1220. await this.transaction.commit();
  1221. result = true;
  1222. const sms = new SMS(this.ctx);
  1223. const code = await sms.contentChange(changeInfo.code);
  1224. const shenpiUrl = await this.ctx.helper.urlToShort(
  1225. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  1226. );
  1227. await this.ctx.helper.sendAliSms(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1228. biangeng: code,
  1229. code: shenpiUrl,
  1230. });
  1231. // 微信模板通知
  1232. const wechatData = {
  1233. wap_url: shenpiUrl,
  1234. status: wxConst.status.check,
  1235. tips: wxConst.tips.check,
  1236. code: this.ctx.session.sessionProject.code,
  1237. c_name: changeInfo.name,
  1238. };
  1239. await this.ctx.helper.sendWechat(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1240. } catch (error) {
  1241. await this.transaction.rollback();
  1242. result = false;
  1243. }
  1244. return result;
  1245. }
  1246. /**
  1247. * 判断是否有重名的变更令
  1248. * @param cid
  1249. * @param code
  1250. * @param tid
  1251. * @return {Promise<void>}
  1252. */
  1253. async isRepeat(cid, code, tid) {
  1254. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1255. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1256. const result = await this.db.queryOne(sql, sqlParam);
  1257. return result.count !== 0;
  1258. }
  1259. async getAllCheckedChanges(tid) {
  1260. return await this.getAllDataByCondition({
  1261. where: { tid, status: audit.flow.status.checked },
  1262. orders: [['in_time', 'desc']],
  1263. });
  1264. }
  1265. /**
  1266. * 用于添加推送所需的content内容
  1267. * @param {Number} pid 项目id
  1268. * @param {Number} tid 台账id
  1269. * @param {Number} cid 变更id
  1270. * @param {Number} uid 审核人id
  1271. */
  1272. async getNoticeContent(pid, tid, cid, uid) {
  1273. const noticeSql =
  1274. 'SELECT * FROM (SELECT ' +
  1275. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1276. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1277. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1278. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1279. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1280. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1281. const content = await this.db.query(noticeSql, noticeSqlParam);
  1282. return content.length ? JSON.stringify(content[0]) : '';
  1283. }
  1284. /**
  1285. * 获取当前标段其他变更令
  1286. * @param {Number} tid - 标段id
  1287. * @param {Number} cid - 当前变更令
  1288. */
  1289. async getOthersChange(tid, cid) {
  1290. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1291. const sqlParam = [this.tableName, tid, cid];
  1292. const data = await this.db.query(sql, sqlParam);
  1293. const changeClassObj = {};
  1294. for (const c in changeConst.class) {
  1295. if (changeConst.class.hasOwnProperty(c)) {
  1296. const item = changeConst.class[c];
  1297. changeClassObj[item.value] = item.name;
  1298. }
  1299. }
  1300. for (let i = 0; i < data.length; i++) {
  1301. data[i].class = changeClassObj[data[i].class];
  1302. }
  1303. return data;
  1304. }
  1305. /**
  1306. * 拷贝变更令至当前变更令
  1307. * @param {String} cid - 当前变更令
  1308. * @param {String} copy_cid - 要拷贝的变更令
  1309. */
  1310. async handleCopyChange(cid, copy_cid) {
  1311. // const change = await this.getDataByCondition({ cid });
  1312. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1313. 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,
  1314. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1315. cid,
  1316. });
  1317. }
  1318. }
  1319. return Change;
  1320. };