change.js 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916
  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 audit_update = {
  830. id: postData.audit_id,
  831. sdesc: postData.sdesc,
  832. status: audit.flow.auditStatus.checked,
  833. sin_time: new Date(),
  834. };
  835. const change_update = {
  836. w_code: postData.w_code,
  837. status: audit.flow.status.checking,
  838. cin_time: Date.parse(new Date()) / 1000,
  839. };
  840. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  841. // 清单数据更新
  842. const bills_list = postData.bills_list.split(',');
  843. let total_price = 0;
  844. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  845. for (const bl of bills_list) {
  846. const listInfo = bl.split('_');
  847. const lid = listInfo[0];
  848. const amount = listInfo[1] !== 'null' && listInfo[1] !== '' ? listInfo[1] : null;
  849. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  850. if (changeListInfo !== undefined) {
  851. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, tp_decimal));
  852. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  853. audit_amount.push(amount);
  854. const list_update = {
  855. id: lid,
  856. audit_amount: audit_amount.join(','),
  857. spamount: amount !== null ? parseFloat(amount) : null,
  858. };
  859. if (postData.audit_next_id === undefined) {
  860. list_update.samount = amount !== null ? amount : '';
  861. list_update.checked_amount = amount !== null ? parseFloat(amount) : 0;
  862. list_update.checked_price = amount !== null ? this.ctx.helper.mul(changeListInfo.unit_price, list_update.checked_amount, tp_decimal) : 0;
  863. }
  864. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  865. }
  866. }
  867. if (postData.audit_next_id === undefined) {
  868. // 变更令审批完成
  869. change_update.status = audit.flow.status.checked;
  870. change_update.p_code = postData.p_code;
  871. change_update.sin_time = Date.parse(new Date()) / 1000;
  872. change_update.is_revise = 0;
  873. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  874. await this.ctx.service.changeAuditList.updateToLedger(this.transaction, changeData.tid, changeData.cid);
  875. // 审批通过 - 检查三方特殊推送
  876. await this.ctx.service.specMsg.addChangeMsg(transaction, this.ctx.session.sessionProject.id, changeData, pushOperate.change.checked);
  877. // 添加短信通知-审批通过提醒功能
  878. // const mobile_array = [];
  879. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  880. const users = this._.map(auditList, 'uid');
  881. const sms = new SMS(this.ctx);
  882. const code = await sms.contentChange(changeData.code);
  883. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  884. biangeng: code,
  885. status: SmsAliConst.status.success,
  886. });
  887. // 微信模板通知
  888. const shenpiUrl = await this.ctx.helper.urlToShort(
  889. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  890. );
  891. const wechatData = {
  892. wap_url: shenpiUrl,
  893. status: wxConst.status.success,
  894. tips: wxConst.tips.success,
  895. code: this.ctx.session.sessionProject.code,
  896. c_name: changeData.name,
  897. };
  898. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  899. } else {
  900. // 设置下一个审批人为审批状态
  901. const nextAudit_update = {
  902. id: postData.audit_next_id,
  903. status: audit.flow.auditStatus.checking,
  904. sin_time: new Date(),
  905. };
  906. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  907. // 添加短信通知-需要审批提醒功能
  908. const nextAuditData = await this.ctx.service.changeAudit.getDataById(postData.audit_next_id);
  909. const sms = new SMS(this.ctx);
  910. const code = await sms.contentChange(changeData.code);
  911. const shenpiUrl = await this.ctx.helper.urlToShort(
  912. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  913. );
  914. await this.ctx.helper.sendAliSms(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  915. biangeng: code,
  916. code: shenpiUrl,
  917. });
  918. // 微信模板通知
  919. const wechatData = {
  920. wap_url: shenpiUrl,
  921. status: wxConst.status.check,
  922. tips: wxConst.tips.check,
  923. code: this.ctx.session.sessionProject.code,
  924. c_name: changeData.name,
  925. };
  926. await this.ctx.helper.sendWechat(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  927. }
  928. change_update.total_price = total_price;
  929. const options = {
  930. where: {
  931. cid: postData.change_id,
  932. },
  933. };
  934. await this.transaction.update(this.tableName, change_update, options);
  935. await this.transaction.commit();
  936. result = true;
  937. } catch (error) {
  938. console.log(error);
  939. await this.transaction.rollback();
  940. result = false;
  941. }
  942. return result;
  943. }
  944. /**
  945. * 审批终止
  946. * @param {int} postData - 表单提交的数据
  947. * @return {void}
  948. */
  949. async approvalStop(postData) {
  950. // 初始化事务
  951. this.transaction = await this.db.beginTransaction();
  952. let result = false;
  953. try {
  954. // 设置审批人终止
  955. const audit_update = {
  956. id: postData.audit_id,
  957. sdesc: postData.sdesc,
  958. status: 4,
  959. sin_time: new Date(),
  960. };
  961. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  962. // 设置变更令终止
  963. const change_update = {
  964. w_code: postData.w_code,
  965. status: 4,
  966. cin_time: Date.parse(new Date()) / 1000,
  967. };
  968. const options = {
  969. where: {
  970. cid: postData.change_id,
  971. },
  972. };
  973. await this.transaction.update(this.tableName, change_update, options);
  974. await this.transaction.commit();
  975. result = true;
  976. } catch (error) {
  977. await this.transaction.rollback();
  978. result = false;
  979. }
  980. return result;
  981. }
  982. /**
  983. * 审批退回到原报人
  984. * @param {Number} pid 项目id
  985. * @param {int} postData - 表单提交的数据
  986. * @param {int} changeData - 变更令的数据
  987. * @return {void}
  988. */
  989. async approvalBack(pid, postData, changeData) {
  990. // 初始化事务
  991. this.transaction = await this.db.beginTransaction();
  992. let result = false;
  993. try {
  994. // 获取所有审核人列表
  995. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  996. // 添加到消息推送表
  997. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  998. const records = [];
  999. auditors.forEach(auditor => {
  1000. records.push({
  1001. pid,
  1002. type: pushType.change,
  1003. uid: auditor.uid,
  1004. status: audit.flow.status.backnew,
  1005. content: noticeContent,
  1006. });
  1007. });
  1008. await this.transaction.insert('zh_notice', records);
  1009. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  1010. // 设置审批人退回
  1011. const audit_update = {
  1012. id: postData.audit_id,
  1013. sdesc: postData.sdesc,
  1014. status: audit.flow.auditStatus.back,
  1015. sin_time: new Date(),
  1016. };
  1017. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1018. // 新增新一次的审批人列表
  1019. // 获取当前次数审批人列表
  1020. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  1021. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  1022. let usort = lastauditInfo.usort + 1;
  1023. const newTimes = changeInfo.times + 1;
  1024. const insert_audit_array = [];
  1025. for (const al of auditList) {
  1026. const insert_audit = {
  1027. tid: al.tid,
  1028. cid: al.cid,
  1029. uid: al.uid,
  1030. name: al.name,
  1031. jobs: al.jobs,
  1032. company: al.company,
  1033. times: newTimes,
  1034. usite: al.usite,
  1035. usort,
  1036. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1037. };
  1038. insert_audit_array.push(insert_audit);
  1039. usort++;
  1040. }
  1041. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1042. // 变更金额也退回
  1043. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1044. where: { cid: changeInfo.cid },
  1045. });
  1046. // 生成内容保存表至zh_change_history中,用于撤回
  1047. await this.ctx.service.changeHistory.saveHistory(this.transaction, changeData, changeList);
  1048. let total_price = 0;
  1049. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1050. for (const cl of changeList) {
  1051. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1052. }
  1053. // 设置变更令退回
  1054. const change_update = {
  1055. w_code: postData.w_code,
  1056. status: audit.flow.status.back,
  1057. times: newTimes,
  1058. cin_time: Date.parse(new Date()) / 1000,
  1059. total_price,
  1060. tp_decimal: null,
  1061. up_decimal: null,
  1062. };
  1063. const options = {
  1064. where: {
  1065. cid: postData.change_id,
  1066. },
  1067. };
  1068. await this.transaction.update(this.tableName, change_update, options);
  1069. await this.transaction.commit();
  1070. result = true;
  1071. const users = this._.map(insert_audit_array, 'uid');
  1072. const sms = new SMS(this.ctx);
  1073. const code = await sms.contentChange(changeData.code);
  1074. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  1075. biangeng: code,
  1076. status: SmsAliConst.status.back,
  1077. });
  1078. // 微信模板通知
  1079. const shenpiUrl = await this.ctx.helper.urlToShort(
  1080. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1081. );
  1082. const wechatData = {
  1083. wap_url: shenpiUrl,
  1084. status: wxConst.status.back,
  1085. tips: wxConst.tips.back,
  1086. code: this.ctx.session.sessionProject.code,
  1087. c_name: changeInfo.name,
  1088. };
  1089. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  1090. } catch (error) {
  1091. await this.transaction.rollback();
  1092. result = false;
  1093. }
  1094. return result;
  1095. }
  1096. /**
  1097. * 审批退回到上一个审批人
  1098. * @param {Number} pid 项目id
  1099. * @param {int} postData - 表单提交的数据
  1100. * @param {int} changeData - 变更令的数据
  1101. * @return {void}
  1102. */
  1103. async approvalBackNew(pid, postData, changeData) {
  1104. // 初始化事务
  1105. this.transaction = await this.db.beginTransaction();
  1106. let result = false;
  1107. try {
  1108. // 获取所有审核人列表
  1109. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1110. // 添加到消息推送表
  1111. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, postData.sdesc);
  1112. const records = [];
  1113. auditors.forEach(auditor => {
  1114. records.push({
  1115. pid,
  1116. type: pushType.change,
  1117. uid: auditor.uid,
  1118. status: audit.flow.status.back,
  1119. content: noticeContent,
  1120. });
  1121. });
  1122. await this.transaction.insert('zh_notice', records);
  1123. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  1124. // 设置审批人退回
  1125. const audit_update = {
  1126. id: postData.audit_id,
  1127. sdesc: postData.sdesc,
  1128. status: audit.flow.auditStatus.backnew,
  1129. sin_time: new Date(),
  1130. };
  1131. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1132. // 获取当前审批人信息
  1133. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  1134. // 获取当前次数审批人列表
  1135. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  1136. let usort = auditInfo.usort + 1;
  1137. // 获取上一个审批人信息
  1138. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  1139. // 新增2个审批人到审批列表中
  1140. const insert_audit1 = {
  1141. tid: lastauditInfo.tid,
  1142. cid: lastauditInfo.cid,
  1143. uid: lastauditInfo.uid,
  1144. name: lastauditInfo.name,
  1145. jobs: lastauditInfo.jobs,
  1146. company: lastauditInfo.company,
  1147. times: lastauditInfo.times,
  1148. usite: lastauditInfo.usite,
  1149. usort,
  1150. status: audit.flow.auditStatus.checking,
  1151. sin_time: new Date(),
  1152. };
  1153. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1154. usort++;
  1155. // 新增2个审批人到审批列表中
  1156. const insert_audit2 = {
  1157. tid: auditInfo.tid,
  1158. cid: auditInfo.cid,
  1159. uid: auditInfo.uid,
  1160. name: auditInfo.name,
  1161. jobs: auditInfo.jobs,
  1162. company: auditInfo.company,
  1163. times: auditInfo.times,
  1164. usite: auditInfo.usite,
  1165. usort,
  1166. status: audit.flow.auditStatus.uncheck,
  1167. };
  1168. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1169. // 把接下未审批的审批人排序都加2
  1170. for (const al of auditList) {
  1171. const audit_update = {
  1172. id: al.id,
  1173. usort: al.usort + 2,
  1174. };
  1175. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  1176. }
  1177. // 审批列表数据也要回退
  1178. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1179. where: { cid: changeInfo.cid },
  1180. });
  1181. let total_price = 0;
  1182. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1183. for (const cl of changeList) {
  1184. const audit_amount = cl.audit_amount.split(',');
  1185. const last_amount = audit_amount[audit_amount.length - 1] ? audit_amount[audit_amount.length - 1] : 0;
  1186. audit_amount.splice(-1, 1);
  1187. const list_update = {
  1188. id: cl.id,
  1189. audit_amount: audit_amount.join(','),
  1190. spamount: parseFloat(last_amount),
  1191. };
  1192. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1193. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1194. }
  1195. // 设置变更令退回
  1196. const change_update = {
  1197. w_code: postData.w_code,
  1198. status: audit.flow.status.backnew,
  1199. cin_time: Date.parse(new Date()) / 1000,
  1200. total_price,
  1201. };
  1202. const options = {
  1203. where: {
  1204. cid: postData.change_id,
  1205. },
  1206. };
  1207. await this.transaction.update(this.tableName, change_update, options);
  1208. await this.transaction.commit();
  1209. result = true;
  1210. const sms = new SMS(this.ctx);
  1211. const code = await sms.contentChange(changeData.code);
  1212. const shenpiUrl = await this.ctx.helper.urlToShort(
  1213. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/information#shenpi'
  1214. );
  1215. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1216. biangeng: code,
  1217. code: shenpiUrl,
  1218. });
  1219. // 微信模板通知
  1220. const wechatData = {
  1221. wap_url: shenpiUrl,
  1222. status: wxConst.status.check,
  1223. tips: wxConst.tips.check,
  1224. code: this.ctx.session.sessionProject.code,
  1225. c_name: changeInfo.name,
  1226. };
  1227. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1228. } catch (error) {
  1229. console.log(error);
  1230. await this.transaction.rollback();
  1231. result = false;
  1232. }
  1233. return result;
  1234. }
  1235. /**
  1236. * 查询可用的变更令
  1237. * @param bills - 查询的清单
  1238. * @param pos - 查询的部位
  1239. * @return {Promise<*>} - 可用的变更令列表
  1240. */
  1241. async getValidChanges(tender, stage, data, noValue) {
  1242. const bills = data.bills, pos = data.pos;
  1243. const self = this;
  1244. const getFilterPart = function(field, value) {
  1245. return value
  1246. ? field + ' = ' + self.db.escape(value)
  1247. : self.db.format("(?? = null or ?? = '')", [field, field]);
  1248. };
  1249. let filter = getFilterPart('cb.code', bills.b_code) +
  1250. ' And ' + getFilterPart('cb.name', bills.name) +
  1251. ' And ' + getFilterPart('cb.unit', bills.unit) +
  1252. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price);
  1253. // if (data.pos) filter = filter + ' And ' + getFilterPart('cb.bwmx', pos.name);
  1254. const sql =
  1255. '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,' +
  1256. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge,' +
  1257. ' 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,' +
  1258. ' scb.used_amount' +
  1259. ' FROM ' + this.tableName + ' As c ' +
  1260. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1261. ' Left Join (' +
  1262. ' SELECT SUM(qty) As used_amount, cbid' +
  1263. ' FROM ' + this.ctx.service.stageChangeFinal.tableName +
  1264. ' WHERE tid = ? and sorder < ?' +
  1265. ' GROUP BY cbid' +
  1266. ' ) As scb ON cb.id = scb.cbid' +
  1267. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1268. ' ORDER BY c.in_time';
  1269. const sqlParam = [tender.id, stage.order, tender.id, audit.flow.status.checked];
  1270. let changes = await this.db.query(sql, sqlParam);
  1271. if (noValue) {
  1272. if (data.noValue) {
  1273. changes = changes.filter(c => {
  1274. return !c.is_valuation;
  1275. });
  1276. } else {
  1277. changes = changes.filter(c => {
  1278. return c.is_valuation;
  1279. });
  1280. }
  1281. }
  1282. for (const c of changes) {
  1283. let sSql = 'SELECT * FROM ' + this.ctx.service.stageChange.tableName + ' WHERE sid = ? and cbid = ?';
  1284. const sSqlParam = [stage.id, c.cbid];
  1285. if (stage.readOnly) {
  1286. sSql = sSql + ' and (stimes < ? or (stimes = ? and sorder <= ?))';
  1287. sSqlParam.push(stage.curTimes, stage.curTimes, stage.curOrder);
  1288. }
  1289. const stageUsedData = await this.db.query(sSql, sSqlParam);
  1290. const filter = this.ctx.helper.filterLastestData(stageUsedData, ['pid', 'lid', 'no_value'], 'stimes', 'sorder');
  1291. c.stage_used_amount = this.ctx.helper.sum(filter.map(x => { return x.qty }));
  1292. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1293. ' FROM ?? As ca ' +
  1294. ' Left Join ?? As pa ' +
  1295. ' On ca.uid = pa.id ' +
  1296. ' Where ca.cid = ?';
  1297. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1298. c.attachments = await this.db.query(aSql, aSqlParam);
  1299. }
  1300. return changes;
  1301. }
  1302. /**
  1303. * 查询变更令 + 变更令执行
  1304. * @param tid
  1305. * @return {Promise<void>}
  1306. */
  1307. async getChangeAndUsedInfo(tid) {
  1308. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1309. let filter;
  1310. if (lastStage.id === this.ctx.stage.id) {
  1311. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1312. lastStage.order,
  1313. lastStage.order,
  1314. this.ctx.stage.curTimes,
  1315. this.ctx.stage.curTimes,
  1316. this.ctx.stage.curOrder,
  1317. ]);
  1318. } else {
  1319. if (lastStage.status === audit.stage.status.uncheck) {
  1320. filter = ' And s.order < ' + lastStage.order;
  1321. } else if (lastStage.status === audit.stage.status.checked) {
  1322. filter = '';
  1323. } else if (lastStage.status === audit.stage.status.checkNo) {
  1324. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1325. } else {
  1326. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1327. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1328. lastStage.order,
  1329. lastStage.order,
  1330. lastStage.times,
  1331. lastStage.times,
  1332. curAuditor.order - 1,
  1333. ]);
  1334. }
  1335. }
  1336. const sql =
  1337. 'SELECT C.*, Sum(U.utp) As used_tp, TRUNCATE(Sum(U.utp) / C.total_price * 100 + 0.005, 2) As used_pt' +
  1338. ' FROM ' + this.tableName + ' As C' +
  1339. ' 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,' +
  1340. ' 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' +
  1341. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1342. ' INNER JOIN (' +
  1343. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1344. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sChange ' +
  1345. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' As s' +
  1346. ' ON sChange.sid = s.id' +
  1347. ' WHERE sChange.tid = ?' + filter +
  1348. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1349. ' ) As m' +
  1350. ' 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`' +
  1351. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName +
  1352. ' As cb ON sc.cbid = cb.id' +
  1353. ' GROUP By sc.`cbid`' +
  1354. ' ) As U ON C.cid = U.cid' +
  1355. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1356. ' GROUP By C.cid' +
  1357. ' ORDER By in_time';
  1358. // 舍入步长
  1359. const step = parseFloat('0.' + '0000000'.substr(0, this.ctx.tender.info.decimal.tp) + '5');
  1360. const sqlParam = [step, this.ctx.tender.info.decimal.tp, step, this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1361. const data = await this.db.query(sql, sqlParam);
  1362. return data;
  1363. }
  1364. /**
  1365. * 查询可用的变更令
  1366. * @param { string } cid - 查询的清单
  1367. * @return {Promise<*>} - 可用的变更令列表
  1368. */
  1369. async delete(cid) {
  1370. // 初始化事务
  1371. this.transaction = await this.db.beginTransaction();
  1372. let result = false;
  1373. try {
  1374. const changeInfo = await this.getDataByCondition({ cid });
  1375. // 先删除清单,审批人列表
  1376. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1377. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1378. // 再删除附件和附件文件ni zuo
  1379. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1380. await this.ctx.helper.delFiles(attList);
  1381. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1382. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1383. // if (attList.length !== 0) {
  1384. // for (const att of attList) {
  1385. // await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1386. // }
  1387. // await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1388. // }
  1389. // 最后删除变更令
  1390. await this.transaction.delete(this.tableName, { cid });
  1391. // 记录删除日志
  1392. await this.ctx.service.projectLog.addProjectLog(this.transaction, projectLogConst.type.change, projectLogConst.status.delete, changeInfo.code);
  1393. await this.transaction.commit();
  1394. result = true;
  1395. } catch (e) {
  1396. await this.transaction.rollback();
  1397. result = false;
  1398. }
  1399. return result;
  1400. }
  1401. /**
  1402. * 重新审批变更令
  1403. * @param { string } cid - 查询的清单
  1404. * @return {Promise<*>} - 可用的变更令列表
  1405. */
  1406. async checkRevise(cid) {
  1407. // 初始化事务
  1408. this.transaction = await this.db.beginTransaction();
  1409. let result = false;
  1410. try {
  1411. const changeData = await this.getDataByCondition({ cid });
  1412. const pid = this.ctx.session.sessionProject.id;
  1413. // 获取所有审核人列表
  1414. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1415. // 添加到消息推送表
  1416. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '发起重新审批');
  1417. const records = [];
  1418. auditors.forEach(auditor => {
  1419. records.push({
  1420. pid,
  1421. type: pushType.change,
  1422. uid: auditor.uid,
  1423. status: audit.flow.status.revise,
  1424. content: noticeContent,
  1425. });
  1426. });
  1427. await this.transaction.insert('zh_notice', records);
  1428. // 获取当前次数审批人列表
  1429. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  1430. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeData.cid, changeData.times, 1, 0);
  1431. let usort = lastauditInfo.usort + 1;
  1432. const newTimes = changeData.times + 1;
  1433. const insert_audit_array = [];
  1434. // 新增一个发起修订状态到审批流程中
  1435. const revise_audit = {
  1436. tid: auditList[0].tid,
  1437. cid: auditList[0].cid,
  1438. uid: auditList[0].uid,
  1439. name: auditList[0].name,
  1440. jobs: auditList[0].jobs,
  1441. company: auditList[0].company,
  1442. times: changeData.times,
  1443. usite: 0,
  1444. usort,
  1445. status: audit.flow.auditStatus.revise,
  1446. sin_time: new Date(),
  1447. };
  1448. insert_audit_array.push(revise_audit);
  1449. usort++;
  1450. // 新增新一次的审批人列表
  1451. for (const al of auditList) {
  1452. const insert_audit = {
  1453. tid: al.tid,
  1454. cid: al.cid,
  1455. uid: al.uid,
  1456. name: al.name,
  1457. jobs: al.jobs,
  1458. company: al.company,
  1459. times: newTimes,
  1460. usite: al.usite,
  1461. usort,
  1462. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1463. };
  1464. insert_audit_array.push(insert_audit);
  1465. usort++;
  1466. }
  1467. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1468. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1469. where: { cid: changeData.cid },
  1470. });
  1471. // 生成内容保存表至zh_change_history中,用于撤销修订回退
  1472. await this.ctx.service.changeHistory.saveHistory(this.transaction, changeData, changeList);
  1473. // 申请变更金额更新为上一次审批审批变更后数量,清空audit_amount值
  1474. const updateTpList = [];
  1475. for (const cl of changeList) {
  1476. updateTpList.push({ id: cl.id, camount: cl.spamount, audit_amount: null, samount: '' });
  1477. }
  1478. if (updateTpList.length > 0) {
  1479. await this.transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateTpList);
  1480. }
  1481. // let total_price = 0;
  1482. // const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1483. // for (const cl of changeList) {
  1484. // total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1485. // }
  1486. // 设置变更令修订状态
  1487. const change_update = {
  1488. w_code: changeData.w_code,
  1489. status: audit.flow.status.revise,
  1490. times: newTimes,
  1491. cin_time: Date.parse(new Date()) / 1000,
  1492. // total_price,
  1493. tp_decimal: null,
  1494. up_decimal: null,
  1495. is_revise: 1,
  1496. };
  1497. const options = {
  1498. where: {
  1499. cid: changeData.cid,
  1500. },
  1501. };
  1502. await this.transaction.update(this.tableName, change_update, options);
  1503. await this.transaction.commit();
  1504. result = true;
  1505. } catch (error) {
  1506. await this.transaction.rollback();
  1507. result = false;
  1508. }
  1509. return result;
  1510. }
  1511. /**
  1512. * 撤销修订变更令
  1513. * @param { string } cid - 查询的清单
  1514. * @return {Promise<*>} - 可用的变更令列表
  1515. */
  1516. async cancelRevise(cid, times) {
  1517. // 初始化事务
  1518. this.transaction = await this.db.beginTransaction();
  1519. let result = false;
  1520. try {
  1521. const changeData = await this.getDataByCondition({ cid });
  1522. const pid = this.ctx.session.sessionProject.id;
  1523. // 获取所有审核人列表
  1524. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1525. // 添加到消息推送表
  1526. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId, '撤销重新审批');
  1527. const records = [];
  1528. auditors.forEach(auditor => {
  1529. records.push({
  1530. pid,
  1531. type: pushType.change,
  1532. uid: auditor.uid,
  1533. status: audit.flow.status.checked,
  1534. content: noticeContent,
  1535. });
  1536. });
  1537. await this.transaction.insert('zh_notice', records);
  1538. await this.ctx.service.changeHistory.returnHistory(this.transaction, cid);
  1539. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid, times });
  1540. await this.transaction.delete(this.ctx.service.changeHistory.tableName, { cid });
  1541. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(cid, times - 1, 1, 0);
  1542. // 新增一个撤销修订状态到审批流程中
  1543. const revise_audit = {
  1544. tid: lastauditInfo.tid,
  1545. cid,
  1546. uid: this.ctx.session.sessionUser.accountId,
  1547. name: lastauditInfo.name,
  1548. jobs: lastauditInfo.jobs,
  1549. company: lastauditInfo.company,
  1550. times: times - 1,
  1551. usite: 0,
  1552. usort: lastauditInfo.usort + 1,
  1553. status: audit.flow.auditStatus.cancelRevise,
  1554. sin_time: new Date(),
  1555. };
  1556. await this.transaction.insert(this.ctx.service.changeAudit.tableName, revise_audit);
  1557. await this.transaction.commit();
  1558. result = true;
  1559. } catch (error) {
  1560. console.log(error);
  1561. await this.transaction.rollback();
  1562. result = false;
  1563. }
  1564. return result;
  1565. }
  1566. /**
  1567. * 重新审批变更令
  1568. * @param { string } cid - 查询的清单
  1569. * @return {Promise<*>} - 可用的变更令列表
  1570. */
  1571. async checkAgain(cid) {
  1572. // 初始化事务
  1573. this.transaction = await this.db.beginTransaction();
  1574. let result = false;
  1575. try {
  1576. const changeInfo = await this.getDataByCondition({ cid });
  1577. // 获取终审
  1578. const auditInfo = (
  1579. await this.ctx.service.changeAudit.getAllDataByCondition({
  1580. where: { cid },
  1581. orders: [['usort', 'desc']],
  1582. limit: 1,
  1583. offset: 0,
  1584. })
  1585. )[0];
  1586. let usort = auditInfo.usort + 1;
  1587. // 新增2个审批状态到审批列表中
  1588. const insert_audit1 = {
  1589. tid: auditInfo.tid,
  1590. cid: auditInfo.cid,
  1591. uid: auditInfo.uid,
  1592. name: auditInfo.name,
  1593. jobs: auditInfo.jobs,
  1594. company: auditInfo.company,
  1595. times: auditInfo.times,
  1596. usite: auditInfo.usite,
  1597. usort,
  1598. sin_time: new Date(),
  1599. status: audit.flow.auditStatus.checkAgain,
  1600. };
  1601. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1602. usort++;
  1603. // 新增2个审批人到审批列表中
  1604. const insert_audit2 = {
  1605. tid: auditInfo.tid,
  1606. cid: auditInfo.cid,
  1607. uid: auditInfo.uid,
  1608. name: auditInfo.name,
  1609. jobs: auditInfo.jobs,
  1610. company: auditInfo.company,
  1611. times: auditInfo.times,
  1612. usite: auditInfo.usite,
  1613. usort,
  1614. status: audit.flow.auditStatus.checking,
  1615. sin_time: new Date(),
  1616. };
  1617. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1618. // 审批列表数据也要回退
  1619. let total_price = 0;
  1620. const tp_decimal = changeInfo.tp_decimal ? changeInfo.tp_decimal : this.ctx.tender.info.decimal.tp;
  1621. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1622. where: { cid: changeInfo.cid },
  1623. });
  1624. for (const cl of changeList) {
  1625. const audit_amount = cl.audit_amount.split(',');
  1626. const last_amount = audit_amount[audit_amount.length - 1];
  1627. audit_amount.splice(-1, 1);
  1628. const list_update = {
  1629. id: cl.id,
  1630. audit_amount: audit_amount.join(','),
  1631. samount: '',
  1632. };
  1633. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1634. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1635. }
  1636. // 设置变更令审批中
  1637. const change_update = {
  1638. p_code: null,
  1639. status: audit.flow.status.checking,
  1640. cin_time: Date.parse(new Date()) / 1000,
  1641. sin_time: null,
  1642. total_price,
  1643. };
  1644. const options = {
  1645. where: {
  1646. cid: changeInfo.cid,
  1647. },
  1648. };
  1649. await this.transaction.update(this.tableName, change_update, options);
  1650. await this.transaction.commit();
  1651. result = true;
  1652. const sms = new SMS(this.ctx);
  1653. const code = await sms.contentChange(changeInfo.code);
  1654. const shenpiUrl = await this.ctx.helper.urlToShort(
  1655. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/information#shenpi'
  1656. );
  1657. await this.ctx.helper.sendAliSms(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1658. biangeng: code,
  1659. code: shenpiUrl,
  1660. });
  1661. // 微信模板通知
  1662. const wechatData = {
  1663. wap_url: shenpiUrl,
  1664. status: wxConst.status.check,
  1665. tips: wxConst.tips.check,
  1666. code: this.ctx.session.sessionProject.code,
  1667. c_name: changeInfo.name,
  1668. };
  1669. await this.ctx.helper.sendWechat(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1670. } catch (error) {
  1671. await this.transaction.rollback();
  1672. result = false;
  1673. }
  1674. return result;
  1675. }
  1676. /**
  1677. * 判断是否有重名的变更令
  1678. * @param cid
  1679. * @param code
  1680. * @param tid
  1681. * @return {Promise<void>}
  1682. */
  1683. async isRepeat(cid, code, tid) {
  1684. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1685. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1686. const result = await this.db.queryOne(sql, sqlParam);
  1687. return result.count !== 0;
  1688. }
  1689. async getAllCheckedChanges(tid) {
  1690. return await this.getAllDataByCondition({
  1691. where: { tid, status: audit.flow.status.checked },
  1692. orders: [['in_time', 'desc']],
  1693. });
  1694. }
  1695. /**
  1696. * 用于添加推送所需的content内容
  1697. * @param {Number} pid 项目id
  1698. * @param {Number} tid 台账id
  1699. * @param {Number} cid 变更id
  1700. * @param {Number} uid 审核人id
  1701. */
  1702. async getNoticeContent(pid, tid, cid, uid, opinion = '') {
  1703. const noticeSql =
  1704. 'SELECT * FROM (SELECT ' +
  1705. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1706. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1707. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1708. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1709. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1710. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1711. const content = await this.db.query(noticeSql, noticeSqlParam);
  1712. if (content.length) {
  1713. content[0].opinion = opinion;
  1714. }
  1715. return content.length ? JSON.stringify(content[0]) : '';
  1716. }
  1717. /**
  1718. * 获取当前标段其他变更令
  1719. * @param {Number} tid - 标段id
  1720. * @param {Number} cid - 当前变更令
  1721. */
  1722. async getOthersChange(tid, cid) {
  1723. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1724. const sqlParam = [this.tableName, tid, cid];
  1725. const data = await this.db.query(sql, sqlParam);
  1726. const changeClassObj = {};
  1727. for (const c in changeConst.class) {
  1728. if (changeConst.class.hasOwnProperty(c)) {
  1729. const item = changeConst.class[c];
  1730. changeClassObj[item.value] = item.name;
  1731. }
  1732. }
  1733. for (let i = 0; i < data.length; i++) {
  1734. data[i].class = changeClassObj[data[i].class];
  1735. }
  1736. return data;
  1737. }
  1738. /**
  1739. * 拷贝变更令至当前变更令
  1740. * @param {String} cid - 当前变更令
  1741. * @param {String} copy_cid - 要拷贝的变更令
  1742. */
  1743. async handleCopyChange(cid, copy_cid) {
  1744. // const change = await this.getDataByCondition({ cid });
  1745. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1746. 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,
  1747. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1748. cid,
  1749. });
  1750. }
  1751. async updateDecimalAndTp() {
  1752. // 判断是否可修改
  1753. // 判断t_type是否为费用
  1754. const transaction = await this.db.beginTransaction();
  1755. try {
  1756. await this.ctx.service.changeAuditList.calcCamountSum(transaction, true);
  1757. await transaction.commit();
  1758. return true;
  1759. } catch (err) {
  1760. await transaction.rollback();
  1761. throw err;
  1762. }
  1763. }
  1764. async updateChangeSelect(data) {
  1765. const conn = await this.db.beginTransaction();
  1766. try {
  1767. for (const d of data) {
  1768. await conn.update(this.tableName, { selected: d.selected }, { where: { cid: d.cid } });
  1769. }
  1770. await conn.commit();
  1771. } catch (err) {
  1772. await conn.rollback();
  1773. throw err;
  1774. }
  1775. }
  1776. async getAllChangeHasMinus(tenderId) {
  1777. const sql = `SELECT * FROM ${this.tableName} WHERE tid = ? AND negative_tp < 0 ORDER BY code asc`;
  1778. return this.db.query(sql, [tenderId]);
  1779. }
  1780. async getListByBudgetInfo(tenders) {
  1781. if (tenders) {
  1782. const sql = 'SELECT * FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ') ORDER BY `total_price` DESC LIMIT 0, 10';
  1783. const params = [this.tableName, audit.flow.status.checked];
  1784. return await this.db.query(sql, params);
  1785. }
  1786. return [];
  1787. }
  1788. async getTotalTpByBudgetInfo(tenders) {
  1789. if (tenders) {
  1790. const sql = 'SELECT SUM(`total_price`) AS tp FROM ?? WHERE `status` = ? AND `tid` in (' + this.ctx.helper.getInArrStrSqlFilter(tenders.split(',')) + ')';
  1791. const sqlParam = [this.tableName, audit.flow.status.checked];
  1792. const result = await this.db.queryOne(sql, sqlParam);
  1793. return result && result.tp ? result.tp : 0;
  1794. }
  1795. return 0;
  1796. }
  1797. async doCheckChangeCanCancel(change) {
  1798. // 获取当前审批人的上一个审批人,判断是否是当前登录人,并赋予撤回功能,(当审批人存在有审批过时,上一人不允许再撤回)
  1799. const status = audit.flow.status;
  1800. const auditStatus = audit.flow.auditStatus;
  1801. const accountId = this.ctx.session.sessionUser.accountId;
  1802. const auditors = await this.ctx.service.changeAudit.getListOrderByTimes(change.cid, change.times);
  1803. change.cancancel = 0;
  1804. if (change.status !== status.checked && change.status !== status.uncheck) {
  1805. if (change.status !== status.back) {
  1806. // 找出当前操作人上一个审批人,包括审批完成的和退回上一个审批人的,同时当前操作人为第一人时,就是则为原报
  1807. const onAuditor = this._.find(auditors, function(item) {
  1808. return item.uid === change.curAuditor.uid && item.status === auditStatus.checking;
  1809. });
  1810. const preAudit = onAuditor.usort > 1 ? this._.find(auditors, { usort: onAuditor.usort - 1 }) : false;
  1811. const preAid = preAudit ? (preAudit.status !== auditStatus.checkAgain ? preAudit.uid : false) : change.uid;
  1812. // console.log(onAuditor, preAudit, auditors);
  1813. if (onAuditor.uid === preAid && preAudit.status === auditStatus.checkCancel) {
  1814. return;// 不可以多次撤回
  1815. } else if (preAid === accountId && (preAid !== change.uid || (preAid === change.uid && preAudit.usite !== 0))) {
  1816. if (preAudit.status === auditStatus.checked) {
  1817. change.cancancel = 2;// 审批人撤回审批通过
  1818. } else if (preAudit.status === auditStatus.backnew) {
  1819. change.cancancel = 3;// 审批人撤回审批退回上一人
  1820. }
  1821. change.preAudit = preAudit;
  1822. } else if (preAid === accountId && preAid === change.uid && preAudit.usite === 0) {
  1823. change.cancancel = 1;// 原报撤回
  1824. }
  1825. } else {
  1826. const lastAuditors = await this.service.changeAudit.getAuditors(change.cid, change.times - 1);
  1827. const onAuditor = this._.findLast(lastAuditors, { status: auditStatus.back });
  1828. if (onAuditor.uid === accountId) {
  1829. change.cancancel = 4;// 审批人撤回退回原报
  1830. }
  1831. }
  1832. }
  1833. }
  1834. }
  1835. return Change;
  1836. };