change.js 71 KB

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