change.js 64 KB

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