change.js 63 KB

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