change.js 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834
  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, plan_code, name, delimit = 100) {
  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. plan_code,
  101. state: 3,
  102. delimit,
  103. // tp_decimal: this.ctx.tender.info.decimal.tp,
  104. // up_decimal: this.ctx.tender.info.decimal.up,
  105. };
  106. if (plan_code) {
  107. const planInfo = await this.ctx.service.changePlan.getDataByCondition({ tid: tenderId, code: plan_code });
  108. if (planInfo) {
  109. change.org_name = planInfo.org_name;
  110. change.peg = planInfo.peg;
  111. change.org_code = planInfo.new_code;
  112. change.new_code = planInfo.c_new_code;
  113. change.new_name = planInfo.design_name;
  114. // 工程变更类别读取
  115. const projectData = await this.ctx.service.project.getDataById(this.ctx.session.sessionProject.id);
  116. const fun_set = await this.ctx.service.project.getFunSet(projectData.fun_set);
  117. const classInfo = this._.find(fun_set.change_class, function(item) {
  118. return item.name === planInfo.class || (item.checked && item.new_name === planInfo.class);
  119. });
  120. change.class = classInfo ? classInfo.value : this._.find(fun_set.change_class, { checked: true }).value;
  121. const qualityIndex = planInfo.quality && this._.indexOf(changeConst.qualityName, planInfo.quality) !== -1 ? this._.indexOf(changeConst.qualityName, planInfo.quality) : 0;
  122. change.quality = qualityIndex ? qualityIndex : changeConst.quality.common.value;
  123. let content = planInfo.reason ? planInfo.reason.replace(/[\r\n]/g, '\r\n') : '';
  124. content = content + (planInfo.content ? (planInfo.reason ? '\r\n' : '') + planInfo.content.replace(/[\r\n]/g, '\r\n') : '');
  125. change.content = content ? content : null;
  126. change.expr = planInfo.expr;
  127. }
  128. }
  129. const operate = await this.transaction.insert(this.tableName, change);
  130. if (operate.affectedRows <= 0) {
  131. throw '新建变更令数据失败';
  132. }
  133. // 把提交人信息添加到zh_change_audit
  134. const userInfo = await this.ctx.service.projectAccount.getDataById(userId);
  135. const changeaudit = [
  136. {
  137. tid: tenderId,
  138. cid,
  139. uid: userId,
  140. name: userInfo.name,
  141. jobs: userInfo.role,
  142. company: userInfo.company,
  143. times: 1,
  144. usite: 0,
  145. usort: 0,
  146. status: 2,
  147. },
  148. ];
  149. // 并把之前存在的变更令审批人添加到zh_change_audit
  150. // 先找出标段最近存在的变更令审批人的变更令info
  151. const changeInfo = await this.ctx.service.change.getHaveAuditLastInfo(tenderId);
  152. if (changeInfo) {
  153. // 再获取非原报审批人
  154. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  155. let sort = 1;
  156. for (const audit of auditList) {
  157. if (audit.usite !== 0) {
  158. const oneaudit = {
  159. tid: tenderId,
  160. cid,
  161. uid: audit.uid,
  162. name: audit.name,
  163. jobs: audit.jobs,
  164. company: audit.company,
  165. times: 1,
  166. usite: audit.usite,
  167. usort: sort++,
  168. status: 1,
  169. };
  170. changeaudit.push(oneaudit);
  171. }
  172. }
  173. }
  174. await this.transaction.insert(this.ctx.service.changeAudit.tableName, changeaudit);
  175. result = change;
  176. this.transaction.commit();
  177. } catch (error) {
  178. console.log(error);
  179. // 回滚
  180. await this.transaction.rollback();
  181. }
  182. return result;
  183. }
  184. async getHaveAuditLastInfo(tenderId) {
  185. const sql = 'SELECT a.* 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';
  186. const sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId];
  187. return await this.db.queryOne(sql, sqlParam);
  188. }
  189. async pendingDatas(tenderId, userId) {
  190. return await this.getAllDataByCondition({
  191. tid: tenderId,
  192. uid: userId,
  193. status: audit.flow.status.checking,
  194. });
  195. }
  196. async uncheckDatas(tenderId, userId) {
  197. return await this.getAllDataByCondition({
  198. tid: tenderId,
  199. uid: userId,
  200. status: audit.flow.status.uncheck,
  201. });
  202. }
  203. async checkingDatas(tenderId, userId) {
  204. return await this.getAllDataByCondition({
  205. tid: tenderId,
  206. uid: userId,
  207. status: audit.flow.status.checking,
  208. });
  209. }
  210. async checkedDatas(tenderId, userId) {
  211. return await this.getAllDataByCondition({
  212. tid: tenderId,
  213. uid: userId,
  214. status: audit.flow.status.checked,
  215. });
  216. }
  217. async checkNoDatas(tenderId, userId) {
  218. return await this.getAllDataByCondition({
  219. tid: tenderId,
  220. uid: userId,
  221. status: audit.flow.status.checkNo,
  222. });
  223. }
  224. async checkNoCount(tenderId, userId) {
  225. return await this.count({
  226. tid: tenderId,
  227. uid: userId,
  228. status: audit.flow.status.checkNo,
  229. });
  230. }
  231. /**
  232. * 获取变更令列表
  233. * @param {int} tenderId - 标段id
  234. * @param {int} status - 状态
  235. * @param {int} hadlimit - 分页
  236. * @return {object} list - 列表
  237. */
  238. async getListByStatus(tenderId, status = 0, hadlimit = 1, sortBy = '', orderBy = '', state = 0) {
  239. let sql = '';
  240. let sqlParam = '';
  241. const stateSql = state ? ' AND a.state = ' + state : '';
  242. if (this.ctx.tender.isTourist && status === 0) {
  243. sql = 'SELECT a.* FROM ?? As a WHERE a.tid = ?' + stateSql;
  244. sqlParam = [this.tableName, tenderId];
  245. } else {
  246. switch (status) {
  247. case 0: // 包含你的所有变更令
  248. sql =
  249. 'SELECT a.* FROM ?? AS a WHERE a.tid = ? AND ' +
  250. '(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 = ? )' + stateSql;
  251. sqlParam = [
  252. this.tableName,
  253. tenderId,
  254. this.ctx.session.sessionUser.accountId,
  255. audit.flow.status.uncheck,
  256. this.ctx.service.changeAudit.tableName,
  257. this.ctx.session.sessionUser.accountId,
  258. audit.flow.status.checked,
  259. ];
  260. break;
  261. case 1: // 待处理(你的)
  262. sql = 'SELECT a.* FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)' + stateSql;
  263. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  264. break;
  265. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  266. sql =
  267. 'SELECT a.* FROM ?? AS a WHERE ' +
  268. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? GROUP BY b.cid) AND ' +
  269. '(a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?' + stateSql;
  270. sqlParam = [
  271. this.tableName,
  272. this.ctx.service.changeAudit.tableName,
  273. this.ctx.session.sessionUser.accountId,
  274. audit.flow.status.uncheck,
  275. audit.flow.status.back,
  276. audit.flow.status.revise,
  277. tenderId,
  278. ];
  279. break;
  280. case 2: // 进行中(所有的)
  281. case 4: // 终止(所有的)
  282. sql =
  283. 'SELECT a.* FROM ?? AS a WHERE ' +
  284. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) AND ' +
  285. 'a.status = ? AND a.tid = ?' + stateSql;
  286. sqlParam = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  287. break;
  288. case 3: // 已完成(所有的)
  289. sql = 'SELECT a.* FROM ?? AS a WHERE a.status = ? AND a.tid = ?' + stateSql;
  290. sqlParam = [this.tableName, status, tenderId];
  291. break;
  292. default:
  293. break;
  294. }
  295. }
  296. if (sortBy && orderBy) {
  297. if (sortBy === 'code') {
  298. sql += ' ORDER BY CHAR_LENGTH(a.code) ' + orderBy + ',convert(a.code using gbk) ' + orderBy;
  299. } else {
  300. sql += ' ORDER BY a.in_time ' + orderBy;
  301. }
  302. } else {
  303. sql += ' ORDER BY a.in_time DESC';
  304. }
  305. if (hadlimit) {
  306. const limit = this.ctx.pageSize ? this.ctx.pageSize : this.app.config.pageSize;
  307. const offset = limit * (this.ctx.page - 1);
  308. const limitString = offset >= 0 ? offset + ',' + limit : limit;
  309. sql += ' LIMIT ' + limitString;
  310. }
  311. const list = await this.db.query(sql, sqlParam);
  312. return list;
  313. }
  314. /**
  315. * 获取变更令个数
  316. * @param {int} tenderId - 标段id
  317. * @param {int} status - 状态
  318. * @return {void}
  319. */
  320. async getCountByStatus(tenderId, status, state = 0) {
  321. const stateSql = state ? ' AND a.state = ' + state : '';
  322. if (this.ctx.tender.isTourist && status === 0) {
  323. const sql5 = 'SELECT count(*) AS count FROM ?? AS a WHERE a.tid = ?' + stateSql + ' ORDER BY a.in_time DESC';
  324. const sqlParam5 = [this.tableName, tenderId];
  325. const result5 = await this.db.query(sql5, sqlParam5);
  326. return result5[0].count;
  327. }
  328. switch (status) {
  329. case 0: // 包含你的所有变更令
  330. const sql =
  331. 'SELECT count(*) AS count FROM ?? AS a WHERE a.tid = ? AND ' +
  332. '(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 = ? )' + stateSql;
  333. const sqlParam = [
  334. this.tableName,
  335. tenderId,
  336. this.ctx.session.sessionUser.accountId,
  337. audit.flow.status.uncheck,
  338. this.ctx.service.changeAudit.tableName,
  339. this.ctx.session.sessionUser.accountId,
  340. audit.flow.status.checked,
  341. ];
  342. const result = await this.db.query(sql, sqlParam);
  343. return result[0].count;
  344. case 1: // 待处理(你的)
  345. // return await this.ctx.service.changeAudit.count({
  346. // tid: tenderId,
  347. // uid: this.ctx.session.sessionUser.accountId,
  348. // status: 2,
  349. // });
  350. const sql6 = 'SELECT count(*) AS count FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)' + stateSql;
  351. const sqlParam6 = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  352. const result6 = await this.db.query(sql6, sqlParam6);
  353. return result6[0].count;
  354. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  355. const sql2 =
  356. 'SELECT count(*) AS count FROM ?? AS a WHERE ' +
  357. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) ' +
  358. 'AND (a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?' + stateSql;
  359. const sqlParam2 = [
  360. this.tableName,
  361. this.ctx.service.changeAudit.tableName,
  362. this.ctx.session.sessionUser.accountId,
  363. audit.flow.status.uncheck,
  364. audit.flow.status.back,
  365. audit.flow.status.revise,
  366. tenderId,
  367. ];
  368. const result2 = await this.db.query(sql2, sqlParam2);
  369. return result2[0].count;
  370. case 2: // 进行中(所有的)
  371. case 4: // 终止(所有的)
  372. const sql3 =
  373. 'SELECT count(*) AS count FROM ?? AS a WHERE ' +
  374. '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 = ?' + stateSql;
  375. const sqlParam3 = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  376. const result3 = await this.db.query(sql3, sqlParam3);
  377. return result3[0].count;
  378. case 3: // 已完成(所有的)
  379. const sql4 = 'SELECT count(*) AS count FROM ?? AS a WHERE a.status = ? AND a.tid = ?' + stateSql;
  380. const sqlParam4 = [this.tableName, status, tenderId];
  381. const result4 = await this.db.query(sql4, sqlParam4);
  382. return result4[0].count;
  383. default:
  384. break;
  385. }
  386. }
  387. async getTp(tenderId, status) {
  388. if (this.ctx.tender.isTourist && status === 0) {
  389. const sql5 = 'SELECT SUM(cast (total_price as decimal(18,6))) AS total_price FROM ?? WHERE tid = ?';
  390. const sqlParam5 = [this.tableName, tenderId];
  391. const result5 = await this.db.query(sql5, sqlParam5);
  392. return result5[0].total_price ? result5[0].total_price : 0;
  393. }
  394. switch (status) {
  395. case 0: // 包含你的所有变更令
  396. const sql =
  397. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE a.tid = ? AND ' +
  398. '(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 = ? )';
  399. const sqlParam = [
  400. this.tableName,
  401. tenderId,
  402. this.ctx.session.sessionUser.accountId,
  403. audit.flow.status.uncheck,
  404. this.ctx.service.changeAudit.tableName,
  405. this.ctx.session.sessionUser.accountId,
  406. audit.flow.status.checked,
  407. ];
  408. const result = await this.db.query(sql, sqlParam);
  409. return result[0].total_price ? result[0].total_price : 0;
  410. case 1: // 待处理(你的)
  411. const sql6 = 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? as a WHERE cid in(SELECT b.cid FROM ?? as b WHERE tid = ? AND uid = ? AND status = ?)';
  412. const sqlParam6 = [this.tableName, this.ctx.service.changeAudit.tableName, tenderId, this.ctx.session.sessionUser.accountId, audit.flow.auditStatus.checking];
  413. const result6 = await this.db.query(sql6, sqlParam6);
  414. return result6[0].total_price ? result6[0].total_price : 0;
  415. case 5: // 待上报(所有的)PS:取未上报,退回,修订的变更令
  416. const sql2 =
  417. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE ' +
  418. 'a.cid IN (SELECT b.cid FROM ?? AS b WHERE b.uid = ? AND a.times = b.times GROUP BY b.cid) ' +
  419. 'AND (a.status = ? OR a.status = ? OR a.status = ?) AND a.tid = ?';
  420. const sqlParam2 = [
  421. this.tableName,
  422. this.ctx.service.changeAudit.tableName,
  423. this.ctx.session.sessionUser.accountId,
  424. audit.flow.status.uncheck,
  425. audit.flow.status.back,
  426. audit.flow.status.revise,
  427. tenderId,
  428. ];
  429. const result2 = await this.db.query(sql2, sqlParam2);
  430. return result2[0].total_price ? result2[0].total_price : 0;
  431. case 2: // 进行中(所有的)
  432. case 4: // 终止(所有的)
  433. const sql3 =
  434. 'SELECT SUM(cast (a.total_price as decimal(18,6))) AS total_price FROM ?? AS a WHERE ' +
  435. '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 = ?';
  436. const sqlParam3 = [this.tableName, this.ctx.service.changeAudit.tableName, this.ctx.session.sessionUser.accountId, status, tenderId];
  437. const result3 = await this.db.query(sql3, sqlParam3);
  438. return result3[0].total_price ? result3[0].total_price : 0;
  439. case 3: // 已完成(所有的)
  440. const sql4 = 'SELECT SUM(cast (total_price as decimal(18,6))) AS total_price FROM ?? WHERE status = ? AND tid = ?';
  441. const sqlParam4 = [this.tableName, status, tenderId];
  442. const result4 = await this.db.query(sql4, sqlParam4);
  443. return result4[0].total_price ? result4[0].total_price : 0;
  444. default:
  445. break;
  446. }
  447. }
  448. /**
  449. * 获取变更令个数
  450. * @param {int} tenderId - 标段id
  451. * @param {int} quality - 变更性质
  452. * @return {void}
  453. */
  454. async getCountByQuality(tenderId, quality) {
  455. return await this.db.count(this.tableName, { tid: tenderId, quality });
  456. }
  457. /**
  458. * 获取变更令个数
  459. * @param {int} tenderId - 标段id
  460. * @param {int} status - 状态
  461. * @return {void}
  462. */
  463. async getCountByStatus2(tenderId, status) {
  464. if (status === audit.filter.status.uncheck) {
  465. const sql =
  466. 'SELECT count(*) AS count FROM ?? WHERE ' +
  467. 'tid = ? AND (status = ? OR status = ? OR status = ?)';
  468. const sqlParam = [
  469. this.tableName,
  470. tenderId,
  471. audit.flow.status.uncheck,
  472. audit.flow.status.back,
  473. audit.flow.status.revise,
  474. ];
  475. const result = await this.db.queryOne(sql, sqlParam);
  476. return result ? result.count : 0;
  477. }
  478. return await this.db.count(this.tableName, { tid: tenderId, status });
  479. }
  480. /**
  481. * 获取已批复变更令的总金额
  482. * @param {int} tenderId - 标段id
  483. * @param {int} quality - 变更性质
  484. * @return {void}
  485. */
  486. async getChangeTp(tenderId) {
  487. const sql = 'SELECT SUM(`total_price`) AS tp, SUM(`positive_tp`) AS p_tp, SUM(`negative_tp`) AS n_tp FROM ?? WHERE tid = ? AND status = ?';
  488. const sqlParam = [this.tableName, tenderId, audit.flow.status.checked];
  489. const result = await this.db.queryOne(sql, sqlParam);
  490. return result ? [result.tp, result.p_tp, result.n_tp] : [0, 0, 0];
  491. }
  492. /**
  493. * 上报或重新上报或保存修改功能
  494. * @param {int} postData - 表单提交的数据
  495. * @param {int} tenderId - 标段id
  496. * @return {void}
  497. */
  498. async save(postData, tenderId) {
  499. // 初始化事务
  500. this.transaction = await this.db.beginTransaction();
  501. let result = false;
  502. try {
  503. // 变更令信息
  504. const changeInfo = await this.getDataByCondition({ cid: postData.cid });
  505. // 该变更令原报人信息
  506. const lastUser = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 0);
  507. // 先删除本次原有的变更审批人和清单
  508. await this.ctx.service.changeAudit.deleteAuditData(this.transaction, changeInfo.cid, changeInfo.times);
  509. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid: changeInfo.cid });
  510. let change_status = false;
  511. // 获取变更令提交状态
  512. if (postData.changestatus !== undefined && parseInt(postData.changestatus) === 1) {
  513. change_status = true;
  514. // 更新原报人审批状态
  515. await this.transaction.update(this.ctx.service.changeAudit.tableName, {
  516. id: lastUser.id,
  517. status: audit.flow.auditStatus.checked,
  518. sin_time: new Date(),
  519. });
  520. }
  521. // 再插入postData里的变更审批人和清单
  522. if (postData.changeaudit !== undefined && postData.changeaudit !== '') {
  523. const changeAudit = postData.changeaudit.split(',');
  524. const insertCA = [];
  525. let uSite = 1;
  526. let uSort = parseInt(lastUser.usort) + 1;
  527. for (const [index, ca] of changeAudit.entries()) {
  528. const auditInfo = ca.split('/%/');
  529. const uStatus = change_status && index === 0 ? audit.flow.auditStatus.checking : audit.flow.auditStatus.uncheck;
  530. const sin_time = change_status && index === 0 ? new Date() : null;
  531. const caArray = {
  532. tid: tenderId,
  533. cid: changeInfo.cid,
  534. uid: auditInfo[0],
  535. name: auditInfo[1],
  536. jobs: auditInfo[2],
  537. company: auditInfo[3],
  538. times: changeInfo.times,
  539. usite: uSite,
  540. usort: uSort,
  541. status: uStatus,
  542. sin_time,
  543. };
  544. uSite++;
  545. uSort++;
  546. insertCA.push(caArray);
  547. // 添加短信通知-需要审批提醒功能
  548. if (change_status && index === 0) {
  549. const sms = new SMS(this.ctx);
  550. const code = await sms.contentChange(changeInfo.code);
  551. const shenpiUrl = await this.ctx.helper.urlToShort(
  552. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  553. );
  554. await this.ctx.helper.sendAliSms(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  555. biangeng: code,
  556. code: shenpiUrl,
  557. });
  558. // 微信模板通知
  559. const wechatData = {
  560. wap_url: shenpiUrl,
  561. status: wxConst.status.check,
  562. tips: wxConst.tips.check,
  563. code: this.ctx.session.sessionProject.code,
  564. c_name: changeInfo.name,
  565. };
  566. await this.ctx.helper.sendWechat(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  567. }
  568. }
  569. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insertCA);
  570. }
  571. let changeList = [];
  572. if (postData.changelist !== undefined && postData.changelist !== '') {
  573. changeList = postData.changelist.split('^_^');
  574. }
  575. let changeWhiteList = [];
  576. if (postData.changewhitelist !== undefined && postData.changewhitelist !== '') {
  577. changeWhiteList = postData.changewhitelist.split('^_^');
  578. }
  579. changeList.push.apply(changeList, changeWhiteList);
  580. const insertCL = [];
  581. let total_price = 0;
  582. if (changeList.length > 0) {
  583. for (const cl of changeList) {
  584. const clInfo = cl.split('*;*');
  585. const clArray = {
  586. tid: tenderId,
  587. cid: changeInfo.cid,
  588. lid: clInfo[8],
  589. code: clInfo[0],
  590. name: clInfo[1],
  591. bwmx: clInfo[2],
  592. unit: clInfo[3],
  593. unit_price: clInfo[4],
  594. oamount: clInfo[5],
  595. camount: clInfo[6],
  596. samount: '',
  597. detail: clInfo[7],
  598. spamount: clInfo[6],
  599. xmj_code: clInfo[9] !== '' ? clInfo[9] : null,
  600. xmj_jldy: clInfo[10] !== '' ? clInfo[10] : null,
  601. gcl_id: clInfo[11] !== '' ? clInfo[11] : '',
  602. };
  603. if (clInfo[4] === '') {
  604. delete clArray.unit_price;
  605. }
  606. insertCL.push(clArray);
  607. total_price = this.ctx.helper.accAdd(total_price, this.ctx.helper.mul(clArray.unit_price, clArray.spamount, this.ctx.tender.info.decimal.tp));
  608. }
  609. await this.transaction.insert(this.ctx.service.changeAuditList.tableName, insertCL);
  610. }
  611. // 修改变更令基本数据
  612. const cArray = {
  613. code: postData.code,
  614. name: postData.name,
  615. peg: postData.peg,
  616. org_name: postData.org_name,
  617. org_code: postData.org_code,
  618. new_name: postData.new_name,
  619. new_code: postData.new_code,
  620. content: postData.content,
  621. basis: postData.basis,
  622. expr: postData.expr,
  623. memo: postData.memo,
  624. type: postData.type.join(','),
  625. class: postData.class,
  626. quality: postData.quality,
  627. company: postData.company,
  628. charge: postData.charge,
  629. w_code: postData.w_code,
  630. total_price,
  631. // tp_decimal: this.ctx.tender.info.decimal.tp,
  632. };
  633. const options = {
  634. where: {
  635. cid: changeInfo.cid,
  636. },
  637. };
  638. if (change_status) {
  639. cArray.tp_decimal = this.ctx.tender.info.decimal.tp;
  640. cArray.up_decimal = this.ctx.tender.info.decimal.up;
  641. cArray.status = audit.flow.status.checking;
  642. cArray.cin_time = Date.parse(new Date()) / 1000;
  643. }
  644. await this.transaction.update(this.tableName, cArray, options);
  645. await this.transaction.commit();
  646. result = true;
  647. } catch (error) {
  648. await this.transaction.rollback();
  649. result = false;
  650. }
  651. return result;
  652. }
  653. /**
  654. * 保存变更信息
  655. * @param {int} postData - 表单提交的数据
  656. * @param {int} tenderId - 标段id
  657. * @return {void}
  658. */
  659. async saveInfo(postData, delimit = 100) {
  660. // 初始化事务
  661. const transaction = await this.db.beginTransaction();
  662. let result = false;
  663. try {
  664. result = {};
  665. const options = {
  666. where: {
  667. cid: this.ctx.change.cid,
  668. },
  669. };
  670. if (postData.state && parseInt(postData.state) !== this.ctx.change.state) {
  671. // 变更清单需要同步设置计量上限值
  672. // 判断是否存在已调用清单,并判断新上限值是否比它小,更新计量上限值
  673. const changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid);
  674. // 获取是否已存在调用变更令
  675. let changeUsedData = await this.ctx.service.stageChange.getFinalUsedData(this.ctx.tender.id, this.ctx.change.cid);
  676. changeUsedData = this._.orderBy(this._.filter(changeUsedData, function(item) {
  677. return item.qty !== null;
  678. }), ['sorder'], ['desc']);
  679. const useChangeUsedData = [];
  680. if (changeUsedData.length > 0) { // 防止未创建期时调用
  681. for (const cu of changeUsedData) {
  682. const index = this._.findIndex(useChangeUsedData, { cbid: cu.cbid });
  683. if (index !== -1) {
  684. useChangeUsedData[index].qty = this.ctx.helper.add(useChangeUsedData[index].qty, cu.qty);
  685. } else {
  686. useChangeUsedData.push(cu);
  687. }
  688. }
  689. }
  690. const updateList = [];
  691. for (const cl of changeList) {
  692. const one = {
  693. id: cl.id,
  694. };
  695. if (useChangeUsedData.length > 0 && this._.findIndex(useChangeUsedData, { cbid: cl.id }) !== -1) {
  696. // 获取比例值
  697. const uc = this._.find(useChangeUsedData, { cbid: cl.id });
  698. const minLimit = Math.ceil(this.ctx.helper.div(uc.qty, cl.camount) * 100);
  699. if (minLimit < delimit) {
  700. one.delimit = delimit;
  701. cl.delimit = delimit;
  702. }
  703. } else if (cl.delimit !== delimit) {
  704. one.delimit = delimit;
  705. cl.delimit = delimit;
  706. }
  707. if (!this._.isEqual(one, { id: cl.id })) updateList.push(one);
  708. }
  709. if (updateList.length > 0) await transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateList);
  710. result.changeList = changeList;
  711. result.deLimit = delimit;
  712. if (this.ctx.change.delimit !== delimit) postData.delimit = delimit;
  713. }
  714. await transaction.update(this.tableName, postData, options);
  715. await transaction.commit();
  716. result.msg = '保存成功';
  717. } catch (error) {
  718. await transaction.rollback();
  719. result = false;
  720. }
  721. return result;
  722. }
  723. /**
  724. * 保存变更信息
  725. * @param {int} order_by - 表单提交的数据
  726. * @return {void}
  727. */
  728. async saveOrderBy(order_by, newLedgerList = []) {
  729. const transaction = await this.db.beginTransaction();
  730. let result = [];
  731. try {
  732. const postData = { order_by };
  733. let changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid);
  734. if (order_by) {
  735. let i = 1;
  736. const updateArray = [];
  737. for (const cl of changeList) {
  738. updateArray.push({
  739. id: cl.id,
  740. order: i,
  741. });
  742. cl.order = i;
  743. i++;
  744. }
  745. if (updateArray.length > 0) await transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateArray);
  746. } else {
  747. await this.ctx.service.changeAuditList.saveLedgerListDatas(newLedgerList, null, order_by);
  748. changeList = await this.ctx.service.changeAuditList.getList(this.ctx.change.cid, order_by);
  749. }
  750. const options = {
  751. where: {
  752. cid: this.ctx.change.cid,
  753. },
  754. };
  755. await transaction.update(this.tableName, postData, options);
  756. await transaction.commit();
  757. result = { changeList,
  758. usedList: await this.ctx.service.stageChange.getFinalUsedData(this.ctx.tender.id, this.ctx.change.cid) };
  759. } catch (error) {
  760. await transaction.rollback();
  761. result = false;
  762. }
  763. return result;
  764. }
  765. /**
  766. * 审批通过
  767. * @param {Number} pid 项目id
  768. * @param {int} postData - 表单提交的数据
  769. * @param {int} changeData - 变更令的数据
  770. * @return {void}
  771. */
  772. async approvalSuccess(pid, postData, changeData) {
  773. // 初始化事务
  774. this.transaction = await this.db.beginTransaction();
  775. let result = false;
  776. try {
  777. // 获取所有审核人列表
  778. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  779. // console.log('auditors', auditors);
  780. // console.log('postData', postData);
  781. // 添加到消息推送表
  782. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  783. const records = [];
  784. auditors.forEach(auditor => {
  785. records.push({
  786. pid,
  787. type: pushType.change,
  788. uid: auditor.uid,
  789. status: audit.flow.status.checked,
  790. content: noticeContent,
  791. });
  792. });
  793. await this.transaction.insert('zh_notice', records);
  794. // 设置审批人通过
  795. const audit_update = {
  796. id: postData.audit_id,
  797. sdesc: postData.sdesc,
  798. status: audit.flow.auditStatus.checked,
  799. sin_time: new Date(),
  800. };
  801. const change_update = {
  802. w_code: postData.w_code,
  803. status: audit.flow.status.checking,
  804. cin_time: Date.parse(new Date()) / 1000,
  805. };
  806. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  807. // 清单数据更新
  808. const bills_list = postData.bills_list.split(',');
  809. let total_price = 0;
  810. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  811. for (const bl of bills_list) {
  812. const listInfo = bl.split('_');
  813. const lid = listInfo[0];
  814. const amount = listInfo[1] !== 'null' && listInfo[1] !== '' ? listInfo[1] : null;
  815. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  816. if (changeListInfo !== undefined) {
  817. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, tp_decimal));
  818. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  819. audit_amount.push(amount);
  820. const list_update = {
  821. id: lid,
  822. audit_amount: audit_amount.join(','),
  823. spamount: amount !== null ? parseFloat(amount) : null,
  824. };
  825. if (postData.audit_next_id === undefined) {
  826. list_update.samount = amount !== null ? amount : '';
  827. }
  828. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  829. }
  830. }
  831. if (postData.audit_next_id === undefined) {
  832. // 变更令审批完成
  833. change_update.status = audit.flow.status.checked;
  834. change_update.p_code = postData.p_code;
  835. change_update.sin_time = Date.parse(new Date()) / 1000;
  836. change_update.is_revise = 0;
  837. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  838. await this.ctx.service.changeAuditList.updateToLedger(this.transaction, changeData.tid, changeData.cid);
  839. // 添加短信通知-审批通过提醒功能
  840. // const mobile_array = [];
  841. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  842. const users = this._.map(auditList, 'uid');
  843. const sms = new SMS(this.ctx);
  844. const code = await sms.contentChange(changeData.code);
  845. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  846. biangeng: code,
  847. status: SmsAliConst.status.success,
  848. });
  849. // 微信模板通知
  850. const shenpiUrl = await this.ctx.helper.urlToShort(
  851. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  852. );
  853. const wechatData = {
  854. wap_url: shenpiUrl,
  855. status: wxConst.status.success,
  856. tips: wxConst.tips.success,
  857. code: this.ctx.session.sessionProject.code,
  858. c_name: changeData.name,
  859. };
  860. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  861. } else {
  862. // 设置下一个审批人为审批状态
  863. const nextAudit_update = {
  864. id: postData.audit_next_id,
  865. status: audit.flow.auditStatus.checking,
  866. sin_time: new Date(),
  867. };
  868. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  869. // 添加短信通知-需要审批提醒功能
  870. const nextAuditData = await this.ctx.service.changeAudit.getDataById(postData.audit_next_id);
  871. const sms = new SMS(this.ctx);
  872. const code = await sms.contentChange(changeData.code);
  873. const shenpiUrl = await this.ctx.helper.urlToShort(
  874. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  875. );
  876. await this.ctx.helper.sendAliSms(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  877. biangeng: code,
  878. code: shenpiUrl,
  879. });
  880. // 微信模板通知
  881. const wechatData = {
  882. wap_url: shenpiUrl,
  883. status: wxConst.status.check,
  884. tips: wxConst.tips.check,
  885. code: this.ctx.session.sessionProject.code,
  886. c_name: changeData.name,
  887. };
  888. await this.ctx.helper.sendWechat(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  889. }
  890. change_update.total_price = total_price;
  891. const options = {
  892. where: {
  893. cid: postData.change_id,
  894. },
  895. };
  896. await this.transaction.update(this.tableName, change_update, options);
  897. await this.transaction.commit();
  898. result = true;
  899. } catch (error) {
  900. console.log(error);
  901. await this.transaction.rollback();
  902. result = false;
  903. }
  904. return result;
  905. }
  906. /**
  907. * 审批终止
  908. * @param {int} postData - 表单提交的数据
  909. * @return {void}
  910. */
  911. async approvalStop(postData) {
  912. // 初始化事务
  913. this.transaction = await this.db.beginTransaction();
  914. let result = false;
  915. try {
  916. // 设置审批人终止
  917. const audit_update = {
  918. id: postData.audit_id,
  919. sdesc: postData.sdesc,
  920. status: 4,
  921. sin_time: new Date(),
  922. };
  923. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  924. // 设置变更令终止
  925. const change_update = {
  926. w_code: postData.w_code,
  927. status: 4,
  928. cin_time: Date.parse(new Date()) / 1000,
  929. };
  930. const options = {
  931. where: {
  932. cid: postData.change_id,
  933. },
  934. };
  935. await this.transaction.update(this.tableName, change_update, options);
  936. await this.transaction.commit();
  937. result = true;
  938. } catch (error) {
  939. await this.transaction.rollback();
  940. result = false;
  941. }
  942. return result;
  943. }
  944. /**
  945. * 审批退回到原报人
  946. * @param {Number} pid 项目id
  947. * @param {int} postData - 表单提交的数据
  948. * @param {int} changeData - 变更令的数据
  949. * @return {void}
  950. */
  951. async approvalBack(pid, postData, changeData) {
  952. // 初始化事务
  953. this.transaction = await this.db.beginTransaction();
  954. let result = false;
  955. try {
  956. // 获取所有审核人列表
  957. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  958. // 添加到消息推送表
  959. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  960. const records = [];
  961. auditors.forEach(auditor => {
  962. records.push({
  963. pid,
  964. type: pushType.change,
  965. uid: auditor.uid,
  966. status: audit.flow.status.backnew,
  967. content: noticeContent,
  968. });
  969. });
  970. await this.transaction.insert('zh_notice', records);
  971. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  972. // 设置审批人退回
  973. const audit_update = {
  974. id: postData.audit_id,
  975. sdesc: postData.sdesc,
  976. status: audit.flow.auditStatus.back,
  977. sin_time: new Date(),
  978. };
  979. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  980. // 新增新一次的审批人列表
  981. // 获取当前次数审批人列表
  982. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  983. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  984. let usort = lastauditInfo.usort + 1;
  985. const newTimes = changeInfo.times + 1;
  986. const insert_audit_array = [];
  987. for (const al of auditList) {
  988. const insert_audit = {
  989. tid: al.tid,
  990. cid: al.cid,
  991. uid: al.uid,
  992. name: al.name,
  993. jobs: al.jobs,
  994. company: al.company,
  995. times: newTimes,
  996. usite: al.usite,
  997. usort,
  998. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  999. };
  1000. insert_audit_array.push(insert_audit);
  1001. usort++;
  1002. }
  1003. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1004. // 变更金额也退回
  1005. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1006. where: { cid: changeInfo.cid },
  1007. });
  1008. let total_price = 0;
  1009. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1010. for (const cl of changeList) {
  1011. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1012. }
  1013. // 设置变更令退回
  1014. const change_update = {
  1015. w_code: postData.w_code,
  1016. status: audit.flow.status.back,
  1017. times: newTimes,
  1018. cin_time: Date.parse(new Date()) / 1000,
  1019. total_price,
  1020. tp_decimal: null,
  1021. up_decimal: null,
  1022. };
  1023. const options = {
  1024. where: {
  1025. cid: postData.change_id,
  1026. },
  1027. };
  1028. await this.transaction.update(this.tableName, change_update, options);
  1029. await this.transaction.commit();
  1030. result = true;
  1031. const users = this._.map(insert_audit_array, 'uid');
  1032. const sms = new SMS(this.ctx);
  1033. const code = await sms.contentChange(changeData.code);
  1034. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  1035. biangeng: code,
  1036. status: SmsAliConst.status.back,
  1037. });
  1038. // 微信模板通知
  1039. const shenpiUrl = await this.ctx.helper.urlToShort(
  1040. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1041. );
  1042. const wechatData = {
  1043. wap_url: shenpiUrl,
  1044. status: wxConst.status.back,
  1045. tips: wxConst.tips.back,
  1046. code: this.ctx.session.sessionProject.code,
  1047. c_name: changeInfo.name,
  1048. };
  1049. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  1050. } catch (error) {
  1051. await this.transaction.rollback();
  1052. result = false;
  1053. }
  1054. return result;
  1055. }
  1056. /**
  1057. * 审批退回到上一个审批人
  1058. * @param {Number} pid 项目id
  1059. * @param {int} postData - 表单提交的数据
  1060. * @param {int} changeData - 变更令的数据
  1061. * @return {void}
  1062. */
  1063. async approvalBackNew(pid, postData, changeData) {
  1064. // 初始化事务
  1065. this.transaction = await this.db.beginTransaction();
  1066. let result = false;
  1067. try {
  1068. // 获取所有审核人列表
  1069. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1070. // 添加到消息推送表
  1071. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  1072. const records = [];
  1073. auditors.forEach(auditor => {
  1074. records.push({
  1075. pid,
  1076. type: pushType.change,
  1077. uid: auditor.uid,
  1078. status: audit.flow.status.back,
  1079. content: noticeContent,
  1080. });
  1081. });
  1082. await this.transaction.insert('zh_notice', records);
  1083. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  1084. // 设置审批人退回
  1085. const audit_update = {
  1086. id: postData.audit_id,
  1087. sdesc: postData.sdesc,
  1088. status: audit.flow.auditStatus.backnew,
  1089. sin_time: new Date(),
  1090. };
  1091. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1092. // 获取当前审批人信息
  1093. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  1094. // 获取当前次数审批人列表
  1095. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  1096. let usort = auditInfo.usort + 1;
  1097. // 获取上一个审批人信息
  1098. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  1099. // 新增2个审批人到审批列表中
  1100. const insert_audit1 = {
  1101. tid: lastauditInfo.tid,
  1102. cid: lastauditInfo.cid,
  1103. uid: lastauditInfo.uid,
  1104. name: lastauditInfo.name,
  1105. jobs: lastauditInfo.jobs,
  1106. company: lastauditInfo.company,
  1107. times: lastauditInfo.times,
  1108. usite: lastauditInfo.usite,
  1109. usort,
  1110. status: audit.flow.auditStatus.checking,
  1111. sin_time: new Date(),
  1112. };
  1113. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1114. usort++;
  1115. // 新增2个审批人到审批列表中
  1116. const insert_audit2 = {
  1117. tid: auditInfo.tid,
  1118. cid: auditInfo.cid,
  1119. uid: auditInfo.uid,
  1120. name: auditInfo.name,
  1121. jobs: auditInfo.jobs,
  1122. company: auditInfo.company,
  1123. times: auditInfo.times,
  1124. usite: auditInfo.usite,
  1125. usort,
  1126. status: audit.flow.auditStatus.uncheck,
  1127. };
  1128. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1129. // 把接下未审批的审批人排序都加2
  1130. for (const al of auditList) {
  1131. const audit_update = {
  1132. id: al.id,
  1133. usort: al.usort + 2,
  1134. };
  1135. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1136. }
  1137. // 审批列表数据也要回退
  1138. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1139. where: { cid: changeInfo.cid },
  1140. });
  1141. let total_price = 0;
  1142. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1143. for (const cl of changeList) {
  1144. const audit_amount = cl.audit_amount.split(',');
  1145. const last_amount = audit_amount[audit_amount.length - 1];
  1146. audit_amount.splice(-1, 1);
  1147. const list_update = {
  1148. id: cl.id,
  1149. audit_amount: audit_amount.join(','),
  1150. spamount: parseFloat(last_amount),
  1151. };
  1152. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1153. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1154. }
  1155. // 设置变更令退回
  1156. const change_update = {
  1157. w_code: postData.w_code,
  1158. status: audit.flow.status.backnew,
  1159. cin_time: Date.parse(new Date()) / 1000,
  1160. total_price,
  1161. };
  1162. const options = {
  1163. where: {
  1164. cid: postData.change_id,
  1165. },
  1166. };
  1167. await this.transaction.update(this.tableName, change_update, options);
  1168. await this.transaction.commit();
  1169. result = true;
  1170. const sms = new SMS(this.ctx);
  1171. const code = await sms.contentChange(changeData.code);
  1172. const shenpiUrl = await this.ctx.helper.urlToShort(
  1173. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  1174. );
  1175. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1176. biangeng: code,
  1177. code: shenpiUrl,
  1178. });
  1179. // 微信模板通知
  1180. const wechatData = {
  1181. wap_url: shenpiUrl,
  1182. status: wxConst.status.check,
  1183. tips: wxConst.tips.check,
  1184. code: this.ctx.session.sessionProject.code,
  1185. c_name: changeInfo.name,
  1186. };
  1187. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1188. } catch (error) {
  1189. await this.transaction.rollback();
  1190. result = false;
  1191. }
  1192. return result;
  1193. }
  1194. /**
  1195. * 查询可用的变更令
  1196. * @param bills - 查询的清单
  1197. * @param pos - 查询的部位
  1198. * @return {Promise<*>} - 可用的变更令列表
  1199. */
  1200. async getValidChanges(tender, stage, data, noValue) {
  1201. const bills = data.bills, pos = data.pos;
  1202. const self = this;
  1203. const getFilterPart = function(field, value) {
  1204. return value
  1205. ? field + ' = ' + self.db.escape(value)
  1206. : self.db.format("(?? = null or ?? = '')", [field, field]);
  1207. };
  1208. let filter = getFilterPart('cb.code', bills.b_code) +
  1209. ' And ' + getFilterPart('cb.name', bills.name) +
  1210. ' And ' + getFilterPart('cb.unit', bills.unit) +
  1211. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price);
  1212. // if (data.pos) filter = filter + ' And ' + getFilterPart('cb.bwmx', pos.name);
  1213. const sql =
  1214. '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,' +
  1215. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge,' +
  1216. ' 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, cb.gcl_id, cb.is_valuation, cb.delimit,' +
  1217. ' scb.used_amount' +
  1218. ' FROM ' + this.tableName + ' As c ' +
  1219. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1220. ' Left Join (' +
  1221. ' SELECT SUM(qty) As used_amount, cbid' +
  1222. ' FROM ' + this.ctx.service.stageChangeFinal.tableName +
  1223. ' WHERE tid = ? and sorder < ?' +
  1224. ' GROUP BY cbid' +
  1225. ' ) As scb ON cb.id = scb.cbid' +
  1226. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1227. ' ORDER BY c.in_time';
  1228. const sqlParam = [tender.id, stage.order, tender.id, audit.flow.status.checked];
  1229. let changes = await this.db.query(sql, sqlParam);
  1230. if (noValue) {
  1231. if (data.noValue) {
  1232. changes = changes.filter(c => {
  1233. return !c.is_valuation;
  1234. });
  1235. } else {
  1236. changes = changes.filter(c => {
  1237. return c.is_valuation;
  1238. });
  1239. }
  1240. }
  1241. for (const c of changes) {
  1242. let sSql = 'SELECT * FROM ' + this.ctx.service.stageChange.tableName + ' WHERE sid = ? and cbid = ?';
  1243. const sSqlParam = [stage.id, c.cbid];
  1244. if (stage.readOnly) {
  1245. sSql = sSql + ' and (stimes < ? or (stimes = ? and sorder <= ?))';
  1246. sSqlParam.push(stage.curTimes, stage.curTimes, stage.curOrder);
  1247. }
  1248. const stageUsedData = await this.db.query(sSql, sSqlParam);
  1249. const filter = this.ctx.helper.filterLastestData(stageUsedData, ['pid', 'lid', 'no_value'], 'stimes', 'sorder');
  1250. c.stage_used_amount = this.ctx.helper.sum(filter.map(x => { return x.qty }));
  1251. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1252. ' FROM ?? As ca ' +
  1253. ' Left Join ?? As pa ' +
  1254. ' On ca.uid = pa.id ' +
  1255. ' Where ca.cid = ?';
  1256. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1257. c.attachments = await this.db.query(aSql, aSqlParam);
  1258. }
  1259. return changes;
  1260. }
  1261. /**
  1262. * 查询变更令 + 变更令执行
  1263. * @param tid
  1264. * @return {Promise<void>}
  1265. */
  1266. async getChangeAndUsedInfo(tid) {
  1267. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1268. let filter;
  1269. if (lastStage.id === this.ctx.stage.id) {
  1270. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1271. lastStage.order,
  1272. lastStage.order,
  1273. this.ctx.stage.curTimes,
  1274. this.ctx.stage.curTimes,
  1275. this.ctx.stage.curOrder,
  1276. ]);
  1277. } else {
  1278. if (lastStage.status === audit.stage.status.uncheck) {
  1279. filter = ' And s.order < ' + lastStage.order;
  1280. } else if (lastStage.status === audit.stage.status.checked) {
  1281. filter = '';
  1282. } else if (lastStage.status === audit.stage.status.checkNo) {
  1283. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1284. } else {
  1285. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1286. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1287. lastStage.order,
  1288. lastStage.order,
  1289. lastStage.times,
  1290. lastStage.times,
  1291. curAuditor.order - 1,
  1292. ]);
  1293. }
  1294. }
  1295. const sql =
  1296. 'SELECT C.*, Sum(U.utp) As used_tp, TRUNCATE(Sum(U.utp) / C.total_price * 100 + 0.005, 2) As used_pt' +
  1297. ' FROM ' + this.tableName + ' As C' +
  1298. ' LEFT JOIN (SELECT sc.tid, sc.cid, sc.cbid, IF(SUM(sc.qty) > 0, TRUNCATE(SUM(sc.qty) * cb.unit_price + ?, ?), TRUNCATE(SUM(sc.qty) * cb.unit_price - ?, ?)) As utp,' +
  1299. ' IF(SUM(sc.qty) > 0, TRUNCATE(SUM(sc.qty) * cb.unit_price + ?, ?), 0, ?)) As utp_po, IF(SUM(sc.qty) > 0, 0, TRUNCATE(SUM(sc.qty) * cb.unit_price - ?, ?)) As utp_ne' +
  1300. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1301. ' INNER JOIN (' +
  1302. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1303. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sChange ' +
  1304. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' As s' +
  1305. ' ON sChange.sid = s.id' +
  1306. ' WHERE sChange.tid = ?' + filter +
  1307. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1308. ' ) As m' +
  1309. ' 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`' +
  1310. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName +
  1311. ' As cb ON sc.cbid = cb.id' +
  1312. ' GROUP By sc.`cbid`' +
  1313. ' ) As U ON C.cid = U.cid' +
  1314. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1315. ' GROUP By C.cid' +
  1316. ' ORDER By in_time';
  1317. // 舍入步长
  1318. const step = parseFloat('0.' + '0000000'.substr(0, this.ctx.tender.info.decimal.tp) + '5');
  1319. const sqlParam = [step, this.ctx.tender.info.decimal.tp, step, this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1320. const data = await this.db.query(sql, sqlParam);
  1321. return data;
  1322. }
  1323. /**
  1324. * 查询可用的变更令
  1325. * @param { string } cid - 查询的清单
  1326. * @return {Promise<*>} - 可用的变更令列表
  1327. */
  1328. async delete(cid) {
  1329. // 初始化事务
  1330. this.transaction = await this.db.beginTransaction();
  1331. let result = false;
  1332. try {
  1333. const changeInfo = await this.getDataByCondition({ cid });
  1334. // 先删除清单,审批人列表
  1335. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1336. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1337. // 再删除附件和附件文件ni zuo
  1338. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1339. await this.ctx.helper.delFiles(attList);
  1340. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1341. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1342. // if (attList.length !== 0) {
  1343. // for (const att of attList) {
  1344. // await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1345. // }
  1346. // await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1347. // }
  1348. // 最后删除变更令
  1349. await this.transaction.delete(this.tableName, { cid });
  1350. // 记录删除日志
  1351. await this.ctx.service.projectLog.addProjectLog(this.transaction, projectLogConst.type.change, projectLogConst.status.delete, changeInfo.code);
  1352. await this.transaction.commit();
  1353. result = true;
  1354. } catch (e) {
  1355. await this.transaction.rollback();
  1356. result = false;
  1357. }
  1358. return result;
  1359. }
  1360. /**
  1361. * 重新审批变更令
  1362. * @param { string } cid - 查询的清单
  1363. * @return {Promise<*>} - 可用的变更令列表
  1364. */
  1365. async checkRevise(cid) {
  1366. // 初始化事务
  1367. this.transaction = await this.db.beginTransaction();
  1368. let result = false;
  1369. try {
  1370. const changeData = await this.getDataByCondition({ cid });
  1371. const pid = this.ctx.session.sessionProject.id;
  1372. // 获取所有审核人列表
  1373. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1374. // 添加到消息推送表
  1375. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '发起重新审批');
  1376. const records = [];
  1377. auditors.forEach(auditor => {
  1378. records.push({
  1379. pid,
  1380. type: pushType.change,
  1381. uid: auditor.uid,
  1382. status: audit.flow.status.revise,
  1383. content: noticeContent,
  1384. });
  1385. });
  1386. await this.transaction.insert('zh_notice', records);
  1387. // 获取当前次数审批人列表
  1388. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  1389. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeData.cid, changeData.times, 1, 0);
  1390. let usort = lastauditInfo.usort + 1;
  1391. const newTimes = changeData.times + 1;
  1392. const insert_audit_array = [];
  1393. // 新增一个发起修订状态到审批流程中
  1394. const revise_audit = {
  1395. tid: auditList[0].tid,
  1396. cid: auditList[0].cid,
  1397. uid: auditList[0].uid,
  1398. name: auditList[0].name,
  1399. jobs: auditList[0].jobs,
  1400. company: auditList[0].company,
  1401. times: changeData.times,
  1402. usite: 0,
  1403. usort,
  1404. status: audit.flow.auditStatus.revise,
  1405. sin_time: new Date(),
  1406. };
  1407. insert_audit_array.push(revise_audit);
  1408. usort++;
  1409. // 新增新一次的审批人列表
  1410. for (const al of auditList) {
  1411. const insert_audit = {
  1412. tid: al.tid,
  1413. cid: al.cid,
  1414. uid: al.uid,
  1415. name: al.name,
  1416. jobs: al.jobs,
  1417. company: al.company,
  1418. times: newTimes,
  1419. usite: al.usite,
  1420. usort,
  1421. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1422. };
  1423. insert_audit_array.push(insert_audit);
  1424. usort++;
  1425. }
  1426. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1427. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1428. where: { cid: changeData.cid },
  1429. });
  1430. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  1431. await this.ctx.service.changeHistory.saveHistory(this.transaction, changeData, changeList);
  1432. // 申请变更金额更新为上一次审批审批变更后数量,清空audit_amount值
  1433. const updateTpList = [];
  1434. for (const cl of changeList) {
  1435. updateTpList.push({ id: cl.id, camount: cl.spamount, audit_amount: null, samount: '' });
  1436. }
  1437. if (updateTpList.length > 0) {
  1438. await this.transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateTpList);
  1439. }
  1440. // let total_price = 0;
  1441. // const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1442. // for (const cl of changeList) {
  1443. // total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1444. // }
  1445. // 设置变更令修订状态
  1446. const change_update = {
  1447. w_code: changeData.w_code,
  1448. status: audit.flow.status.revise,
  1449. times: newTimes,
  1450. cin_time: Date.parse(new Date()) / 1000,
  1451. // total_price,
  1452. tp_decimal: null,
  1453. up_decimal: null,
  1454. is_revise: 1,
  1455. };
  1456. const options = {
  1457. where: {
  1458. cid: changeData.cid,
  1459. },
  1460. };
  1461. await this.transaction.update(this.tableName, change_update, options);
  1462. await this.transaction.commit();
  1463. result = true;
  1464. } catch (error) {
  1465. await this.transaction.rollback();
  1466. result = false;
  1467. }
  1468. return result;
  1469. }
  1470. /**
  1471. * 撤销修订变更令
  1472. * @param { string } cid - 查询的清单
  1473. * @return {Promise<*>} - 可用的变更令列表
  1474. */
  1475. async cancelRevise(cid, times) {
  1476. // 初始化事务
  1477. this.transaction = await this.db.beginTransaction();
  1478. let result = false;
  1479. try {
  1480. const changeData = await this.getDataByCondition({ cid });
  1481. const pid = this.ctx.session.sessionProject.id;
  1482. // 获取所有审核人列表
  1483. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1484. // 添加到消息推送表
  1485. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '撤销重新审批');
  1486. const records = [];
  1487. auditors.forEach(auditor => {
  1488. records.push({
  1489. pid,
  1490. type: pushType.change,
  1491. uid: auditor.uid,
  1492. status: audit.flow.status.checked,
  1493. content: noticeContent,
  1494. });
  1495. });
  1496. await this.transaction.insert('zh_notice', records);
  1497. await this.ctx.service.changeHistory.returnHistory(this.transaction, cid);
  1498. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid, times });
  1499. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1500. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(cid, times - 1, 1, 0);
  1501. // 新增一个撤销修订状态到审批流程中
  1502. const revise_audit = {
  1503. tid: lastauditInfo.tid,
  1504. cid,
  1505. uid: this.ctx.session.sessionUser.accountId,
  1506. name: lastauditInfo.name,
  1507. jobs: lastauditInfo.jobs,
  1508. company: lastauditInfo.company,
  1509. times: times - 1,
  1510. usite: 0,
  1511. usort: lastauditInfo.usort + 1,
  1512. status: audit.flow.auditStatus.cancelRevise,
  1513. sin_time: new Date(),
  1514. };
  1515. await this.transaction.insert(this.ctx.service.changeAudit.tableName, revise_audit);
  1516. await this.transaction.commit();
  1517. result = true;
  1518. } catch (error) {
  1519. console.log(error);
  1520. await this.transaction.rollback();
  1521. result = false;
  1522. }
  1523. return result;
  1524. }
  1525. /**
  1526. * 重新审批变更令
  1527. * @param { string } cid - 查询的清单
  1528. * @return {Promise<*>} - 可用的变更令列表
  1529. */
  1530. async checkAgain(cid) {
  1531. // 初始化事务
  1532. this.transaction = await this.db.beginTransaction();
  1533. let result = false;
  1534. try {
  1535. const changeInfo = await this.getDataByCondition({ cid });
  1536. // 获取终审
  1537. const auditInfo = (
  1538. await this.ctx.service.changeAudit.getAllDataByCondition({
  1539. where: { cid },
  1540. orders: [['usort', 'desc']],
  1541. limit: 1,
  1542. offset: 0,
  1543. })
  1544. )[0];
  1545. let usort = auditInfo.usort + 1;
  1546. // 新增2个审批状态到审批列表中
  1547. const insert_audit1 = {
  1548. tid: auditInfo.tid,
  1549. cid: auditInfo.cid,
  1550. uid: auditInfo.uid,
  1551. name: auditInfo.name,
  1552. jobs: auditInfo.jobs,
  1553. company: auditInfo.company,
  1554. times: auditInfo.times,
  1555. usite: auditInfo.usite,
  1556. usort,
  1557. sin_time: new Date(),
  1558. status: audit.flow.auditStatus.checkAgain,
  1559. };
  1560. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1561. usort++;
  1562. // 新增2个审批人到审批列表中
  1563. const insert_audit2 = {
  1564. tid: auditInfo.tid,
  1565. cid: auditInfo.cid,
  1566. uid: auditInfo.uid,
  1567. name: auditInfo.name,
  1568. jobs: auditInfo.jobs,
  1569. company: auditInfo.company,
  1570. times: auditInfo.times,
  1571. usite: auditInfo.usite,
  1572. usort,
  1573. status: audit.flow.auditStatus.checking,
  1574. sin_time: new Date(),
  1575. };
  1576. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1577. // 审批列表数据也要回退
  1578. let total_price = 0;
  1579. const tp_decimal = changeInfo.tp_decimal ? changeInfo.tp_decimal : this.ctx.tender.info.decimal.tp;
  1580. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1581. where: { cid: changeInfo.cid },
  1582. });
  1583. for (const cl of changeList) {
  1584. const audit_amount = cl.audit_amount.split(',');
  1585. const last_amount = audit_amount[audit_amount.length - 1];
  1586. audit_amount.splice(-1, 1);
  1587. const list_update = {
  1588. id: cl.id,
  1589. audit_amount: audit_amount.join(','),
  1590. samount: '',
  1591. };
  1592. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1593. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1594. }
  1595. // 设置变更令审批中
  1596. const change_update = {
  1597. p_code: null,
  1598. status: audit.flow.status.checking,
  1599. cin_time: Date.parse(new Date()) / 1000,
  1600. sin_time: null,
  1601. total_price,
  1602. };
  1603. const options = {
  1604. where: {
  1605. cid: changeInfo.cid,
  1606. },
  1607. };
  1608. await this.transaction.update(this.tableName, change_update, options);
  1609. await this.transaction.commit();
  1610. result = true;
  1611. const sms = new SMS(this.ctx);
  1612. const code = await sms.contentChange(changeInfo.code);
  1613. const shenpiUrl = await this.ctx.helper.urlToShort(
  1614. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1615. );
  1616. await this.ctx.helper.sendAliSms(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1617. biangeng: code,
  1618. code: shenpiUrl,
  1619. });
  1620. // 微信模板通知
  1621. const wechatData = {
  1622. wap_url: shenpiUrl,
  1623. status: wxConst.status.check,
  1624. tips: wxConst.tips.check,
  1625. code: this.ctx.session.sessionProject.code,
  1626. c_name: changeInfo.name,
  1627. };
  1628. await this.ctx.helper.sendWechat(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1629. } catch (error) {
  1630. await this.transaction.rollback();
  1631. result = false;
  1632. }
  1633. return result;
  1634. }
  1635. /**
  1636. * 判断是否有重名的变更令
  1637. * @param cid
  1638. * @param code
  1639. * @param tid
  1640. * @return {Promise<void>}
  1641. */
  1642. async isRepeat(cid, code, tid) {
  1643. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1644. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1645. const result = await this.db.queryOne(sql, sqlParam);
  1646. return result.count !== 0;
  1647. }
  1648. async getAllCheckedChanges(tid) {
  1649. return await this.getAllDataByCondition({
  1650. where: { tid, status: audit.flow.status.checked },
  1651. orders: [['in_time', 'desc']],
  1652. });
  1653. }
  1654. /**
  1655. * 用于添加推送所需的content内容
  1656. * @param {Number} pid 项目id
  1657. * @param {Number} tid 台账id
  1658. * @param {Number} cid 变更id
  1659. * @param {Number} uid 审核人id
  1660. */
  1661. async getNoticeContent(pid, tid, cid, uid, opinion = '') {
  1662. const noticeSql =
  1663. 'SELECT * FROM (SELECT ' +
  1664. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1665. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1666. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1667. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1668. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1669. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1670. const content = await this.db.query(noticeSql, noticeSqlParam);
  1671. if (content.length) {
  1672. content[0].opinion = opinion;
  1673. }
  1674. return content.length ? JSON.stringify(content[0]) : '';
  1675. }
  1676. /**
  1677. * 获取当前标段其他变更令
  1678. * @param {Number} tid - 标段id
  1679. * @param {Number} cid - 当前变更令
  1680. */
  1681. async getOthersChange(tid, cid) {
  1682. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1683. const sqlParam = [this.tableName, tid, cid];
  1684. const data = await this.db.query(sql, sqlParam);
  1685. const changeClassObj = {};
  1686. for (const c in changeConst.class) {
  1687. if (changeConst.class.hasOwnProperty(c)) {
  1688. const item = changeConst.class[c];
  1689. changeClassObj[item.value] = item.name;
  1690. }
  1691. }
  1692. for (let i = 0; i < data.length; i++) {
  1693. data[i].class = changeClassObj[data[i].class];
  1694. }
  1695. return data;
  1696. }
  1697. /**
  1698. * 拷贝变更令至当前变更令
  1699. * @param {String} cid - 当前变更令
  1700. * @param {String} copy_cid - 要拷贝的变更令
  1701. */
  1702. async handleCopyChange(cid, copy_cid) {
  1703. // const change = await this.getDataByCondition({ cid });
  1704. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1705. 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,
  1706. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1707. cid,
  1708. });
  1709. }
  1710. async updateDecimalAndTp() {
  1711. // 判断是否可修改
  1712. // 判断t_type是否为费用
  1713. const transaction = await this.db.beginTransaction();
  1714. try {
  1715. await this.ctx.service.changeAuditList.calcCamountSum(transaction, true);
  1716. await transaction.commit();
  1717. return true;
  1718. } catch (err) {
  1719. await transaction.rollback();
  1720. throw err;
  1721. }
  1722. }
  1723. async updateChangeSelect(data) {
  1724. const conn = await this.db.beginTransaction();
  1725. try {
  1726. for (const d of data) {
  1727. await conn.update(this.tableName, { selected: d.selected }, { where: { cid: d.cid } });
  1728. }
  1729. await conn.commit();
  1730. } catch (err) {
  1731. await conn.rollback();
  1732. throw err;
  1733. }
  1734. }
  1735. async getAllChangeHasMinus(tenderId) {
  1736. const sql = `SELECT * FROM ${this.tableName} WHERE tid = ? AND negative_tp < 0 ORDER BY code asc`;
  1737. return this.db.query(sql, [tenderId]);
  1738. }
  1739. async getListByBudgetInfo(tenders) {
  1740. if (tenders) {
  1741. const sql = 'SELECT * FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ') ORDER BY `total_price` DESC LIMIT 0, 10';
  1742. const params = [this.tableName, audit.flow.status.checked];
  1743. return await this.db.query(sql, params);
  1744. }
  1745. return [];
  1746. }
  1747. async getTotalTpByBudgetInfo(tenders) {
  1748. if (tenders) {
  1749. const sql = 'SELECT SUM(`total_price`) AS tp FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ')';
  1750. const sqlParam = [this.tableName, audit.flow.status.checked];
  1751. const result = await this.db.queryOne(sql, sqlParam);
  1752. return result && result.tp ? result.tp : 0;
  1753. }
  1754. return 0;
  1755. }
  1756. }
  1757. return Change;
  1758. };