change.js 61 KB

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