change.js 64 KB

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