change.js 95 KB

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