change.js 69 KB

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