change.js 64 KB

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