change.js 85 KB

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