change.js 69 KB

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