change.js 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490
  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 * 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} postData - 表单提交的数据
  354. * @param {int} tenderId - 标段id
  355. * @return {void}
  356. */
  357. async save(postData, tenderId) {
  358. // 初始化事务
  359. this.transaction = await this.db.beginTransaction();
  360. let result = false;
  361. try {
  362. // 变更令信息
  363. const changeInfo = await this.getDataByCondition({ cid: postData.cid });
  364. // 该变更令原报人信息
  365. const lastUser = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 0);
  366. // 先删除本次原有的变更审批人和清单
  367. await this.ctx.service.changeAudit.deleteAuditData(this.transaction, changeInfo.cid, changeInfo.times);
  368. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid: changeInfo.cid });
  369. let change_status = false;
  370. // 获取变更令提交状态
  371. if (postData.changestatus !== undefined && parseInt(postData.changestatus) === 1) {
  372. change_status = true;
  373. // 更新原报人审批状态
  374. await this.transaction.update(this.ctx.service.changeAudit.tableName, {
  375. id: lastUser.id,
  376. status: audit.flow.auditStatus.checked,
  377. sin_time: new Date(),
  378. });
  379. }
  380. // 再插入postData里的变更审批人和清单
  381. if (postData.changeaudit !== undefined && postData.changeaudit !== '') {
  382. const changeAudit = postData.changeaudit.split(',');
  383. const insertCA = [];
  384. let uSite = 1;
  385. let uSort = parseInt(lastUser.usort) + 1;
  386. for (const [index, ca] of changeAudit.entries()) {
  387. const auditInfo = ca.split('/%/');
  388. const uStatus = change_status && index === 0 ? audit.flow.auditStatus.checking : audit.flow.auditStatus.uncheck;
  389. const sin_time = change_status && index === 0 ? new Date() : null;
  390. const caArray = {
  391. tid: tenderId,
  392. cid: changeInfo.cid,
  393. uid: auditInfo[0],
  394. name: auditInfo[1],
  395. jobs: auditInfo[2],
  396. company: auditInfo[3],
  397. times: changeInfo.times,
  398. usite: uSite,
  399. usort: uSort,
  400. status: uStatus,
  401. sin_time,
  402. };
  403. uSite++;
  404. uSort++;
  405. insertCA.push(caArray);
  406. // 添加短信通知-需要审批提醒功能
  407. if (change_status && index === 0) {
  408. const sms = new SMS(this.ctx);
  409. const code = await sms.contentChange(changeInfo.code);
  410. const shenpiUrl = await this.ctx.helper.urlToShort(
  411. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  412. );
  413. await this.ctx.helper.sendAliSms(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  414. biangeng: code,
  415. code: shenpiUrl,
  416. });
  417. // 微信模板通知
  418. const wechatData = {
  419. wap_url: shenpiUrl,
  420. status: wxConst.status.check,
  421. tips: wxConst.tips.check,
  422. code: this.ctx.session.sessionProject.code,
  423. c_name: changeInfo.name,
  424. };
  425. await this.ctx.helper.sendWechat(auditInfo[0], smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  426. }
  427. }
  428. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insertCA);
  429. }
  430. let changeList = [];
  431. if (postData.changelist !== undefined && postData.changelist !== '') {
  432. changeList = postData.changelist.split('^_^');
  433. }
  434. let changeWhiteList = [];
  435. if (postData.changewhitelist !== undefined && postData.changewhitelist !== '') {
  436. changeWhiteList = postData.changewhitelist.split('^_^');
  437. }
  438. changeList.push.apply(changeList, changeWhiteList);
  439. const insertCL = [];
  440. let total_price = 0;
  441. if (changeList.length > 0) {
  442. for (const cl of changeList) {
  443. const clInfo = cl.split('*;*');
  444. const clArray = {
  445. tid: tenderId,
  446. cid: changeInfo.cid,
  447. lid: clInfo[8],
  448. code: clInfo[0],
  449. name: clInfo[1],
  450. bwmx: clInfo[2],
  451. unit: clInfo[3],
  452. unit_price: clInfo[4],
  453. oamount: clInfo[5],
  454. camount: clInfo[6],
  455. samount: '',
  456. detail: clInfo[7],
  457. spamount: clInfo[6],
  458. xmj_code: clInfo[9] !== '' ? clInfo[9] : null,
  459. xmj_jldy: clInfo[10] !== '' ? clInfo[10] : null,
  460. gcl_id: clInfo[11] !== '' ? clInfo[11] : '',
  461. };
  462. if (clInfo[4] === '') {
  463. delete clArray.unit_price;
  464. }
  465. insertCL.push(clArray);
  466. total_price = this.ctx.helper.accAdd(total_price, this.ctx.helper.mul(clArray.unit_price, clArray.spamount, this.ctx.tender.info.decimal.tp));
  467. }
  468. await this.transaction.insert(this.ctx.service.changeAuditList.tableName, insertCL);
  469. }
  470. // 修改变更令基本数据
  471. const cArray = {
  472. code: postData.code,
  473. name: postData.name,
  474. peg: postData.peg,
  475. org_name: postData.org_name,
  476. org_code: postData.org_code,
  477. new_name: postData.new_name,
  478. new_code: postData.new_code,
  479. content: postData.content,
  480. basis: postData.basis,
  481. expr: postData.expr,
  482. memo: postData.memo,
  483. type: postData.type.join(','),
  484. class: postData.class,
  485. quality: postData.quality,
  486. company: postData.company,
  487. charge: postData.charge,
  488. w_code: postData.w_code,
  489. total_price,
  490. tp_decimal: this.ctx.tender.info.decimal.tp,
  491. };
  492. const options = {
  493. where: {
  494. cid: changeInfo.cid,
  495. },
  496. };
  497. if (change_status) {
  498. cArray.status = audit.flow.status.checking;
  499. cArray.cin_time = Date.parse(new Date()) / 1000;
  500. }
  501. await this.transaction.update(this.tableName, cArray, options);
  502. await this.transaction.commit();
  503. result = true;
  504. } catch (error) {
  505. await this.transaction.rollback();
  506. result = false;
  507. }
  508. return result;
  509. }
  510. /**
  511. * 保存变更信息
  512. * @param {int} postData - 表单提交的数据
  513. * @param {int} tenderId - 标段id
  514. * @return {void}
  515. */
  516. async saveInfo(postData) {
  517. // 初始化事务
  518. const transaction = await this.db.beginTransaction();
  519. let result = false;
  520. try {
  521. const options = {
  522. where: {
  523. cid: this.ctx.change.cid,
  524. },
  525. };
  526. await transaction.update(this.tableName, postData, options);
  527. await transaction.commit();
  528. result = true;
  529. } catch (error) {
  530. await transaction.rollback();
  531. result = false;
  532. }
  533. return result;
  534. }
  535. /**
  536. * 审批通过
  537. * @param {Number} pid 项目id
  538. * @param {int} postData - 表单提交的数据
  539. * @param {int} changeData - 变更令的数据
  540. * @return {void}
  541. */
  542. async approvalSuccess(pid, postData, changeData) {
  543. // 初始化事务
  544. this.transaction = await this.db.beginTransaction();
  545. let result = false;
  546. try {
  547. // 获取所有审核人列表
  548. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  549. // console.log('auditors', auditors);
  550. // console.log('postData', postData);
  551. // 添加到消息推送表
  552. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  553. const records = [];
  554. auditors.forEach(auditor => {
  555. records.push({
  556. pid,
  557. type: pushType.change,
  558. uid: auditor.uid,
  559. status: audit.flow.status.checked,
  560. content: noticeContent,
  561. });
  562. });
  563. await this.transaction.insert('zh_notice', records);
  564. // 设置审批人通过
  565. const audit_update = {
  566. id: postData.audit_id,
  567. sdesc: postData.sdesc,
  568. status: audit.flow.auditStatus.checked,
  569. sin_time: new Date(),
  570. };
  571. const change_update = {
  572. w_code: postData.w_code,
  573. status: audit.flow.status.checking,
  574. cin_time: Date.parse(new Date()) / 1000,
  575. };
  576. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  577. // 清单数据更新
  578. const bills_list = postData.bills_list.split(',');
  579. let total_price = 0;
  580. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  581. for (const bl of bills_list) {
  582. const listInfo = bl.split('_');
  583. const lid = listInfo[0];
  584. const amount = listInfo[1];
  585. const changeListInfo = await this.ctx.service.changeAuditList.getDataById(lid);
  586. if (changeListInfo !== undefined) {
  587. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(changeListInfo.unit_price, amount, tp_decimal));
  588. const audit_amount = changeListInfo.audit_amount !== null && changeListInfo.audit_amount !== '' ? changeListInfo.audit_amount.split(',') : [];
  589. audit_amount.push(amount);
  590. const list_update = {
  591. id: lid,
  592. audit_amount: audit_amount.join(','),
  593. spamount: parseFloat(amount),
  594. };
  595. if (postData.audit_next_id === undefined) {
  596. list_update.samount = amount;
  597. }
  598. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  599. }
  600. }
  601. if (postData.audit_next_id === undefined) {
  602. // 变更令审批完成
  603. change_update.status = audit.flow.status.checked;
  604. change_update.p_code = postData.p_code;
  605. change_update.sin_time = Date.parse(new Date()) / 1000;
  606. await this.ctx.service.tenderTag.saveTenderTag(changeData.tid, { bgl_time: new Date() }, this.transaction);
  607. // 添加短信通知-审批通过提醒功能
  608. // const mobile_array = [];
  609. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  610. const users = this._.map(auditList, 'uid');
  611. const sms = new SMS(this.ctx);
  612. const code = await sms.contentChange(changeData.code);
  613. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  614. biangeng: code,
  615. status: SmsAliConst.status.success,
  616. });
  617. // 微信模板通知
  618. const shenpiUrl = await this.ctx.helper.urlToShort(
  619. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  620. );
  621. const wechatData = {
  622. wap_url: shenpiUrl,
  623. status: wxConst.status.success,
  624. tips: wxConst.tips.success,
  625. code: this.ctx.session.sessionProject.code,
  626. c_name: changeData.name,
  627. };
  628. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  629. } else {
  630. // 设置下一个审批人为审批状态
  631. const nextAudit_update = {
  632. id: postData.audit_next_id,
  633. status: audit.flow.auditStatus.checking,
  634. sin_time: new Date(),
  635. };
  636. await this.transaction.update(this.ctx.service.changeAudit.tableName, nextAudit_update);
  637. // 添加短信通知-需要审批提醒功能
  638. const nextAuditData = await this.ctx.service.changeAudit.getDataById(postData.audit_next_id);
  639. const sms = new SMS(this.ctx);
  640. const code = await sms.contentChange(changeData.code);
  641. const shenpiUrl = await this.ctx.helper.urlToShort(
  642. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  643. );
  644. await this.ctx.helper.sendAliSms(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  645. biangeng: code,
  646. code: shenpiUrl,
  647. });
  648. // 微信模板通知
  649. const wechatData = {
  650. wap_url: shenpiUrl,
  651. status: wxConst.status.check,
  652. tips: wxConst.tips.check,
  653. code: this.ctx.session.sessionProject.code,
  654. c_name: changeData.name,
  655. };
  656. await this.ctx.helper.sendWechat(nextAuditData.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  657. }
  658. change_update.total_price = total_price;
  659. const options = {
  660. where: {
  661. cid: postData.change_id,
  662. },
  663. };
  664. await this.transaction.update(this.tableName, change_update, options);
  665. await this.transaction.commit();
  666. result = true;
  667. } catch (error) {
  668. console.log(error);
  669. await this.transaction.rollback();
  670. result = false;
  671. }
  672. return result;
  673. }
  674. /**
  675. * 审批终止
  676. * @param {int} postData - 表单提交的数据
  677. * @return {void}
  678. */
  679. async approvalStop(postData) {
  680. // 初始化事务
  681. this.transaction = await this.db.beginTransaction();
  682. let result = false;
  683. try {
  684. // 设置审批人终止
  685. const audit_update = {
  686. id: postData.audit_id,
  687. sdesc: postData.sdesc,
  688. status: 4,
  689. sin_time: new Date(),
  690. };
  691. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  692. // 设置变更令终止
  693. const change_update = {
  694. w_code: postData.w_code,
  695. status: 4,
  696. cin_time: Date.parse(new Date()) / 1000,
  697. };
  698. const options = {
  699. where: {
  700. cid: postData.change_id,
  701. },
  702. };
  703. await this.transaction.update(this.tableName, change_update, options);
  704. await this.transaction.commit();
  705. result = true;
  706. } catch (error) {
  707. await this.transaction.rollback();
  708. result = false;
  709. }
  710. return result;
  711. }
  712. /**
  713. * 审批退回到原报人
  714. * @param {Number} pid 项目id
  715. * @param {int} postData - 表单提交的数据
  716. * @param {int} changeData - 变更令的数据
  717. * @return {void}
  718. */
  719. async approvalBack(pid, postData, changeData) {
  720. // 初始化事务
  721. this.transaction = await this.db.beginTransaction();
  722. let result = false;
  723. try {
  724. // 获取所有审核人列表
  725. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  726. // 添加到消息推送表
  727. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  728. const records = [];
  729. auditors.forEach(auditor => {
  730. records.push({
  731. pid,
  732. type: pushType.change,
  733. uid: auditor.uid,
  734. status: audit.flow.status.backnew,
  735. content: noticeContent,
  736. });
  737. });
  738. await this.transaction.insert('zh_notice', records);
  739. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  740. // 设置审批人退回
  741. const audit_update = {
  742. id: postData.audit_id,
  743. sdesc: postData.sdesc,
  744. status: audit.flow.auditStatus.back,
  745. sin_time: new Date(),
  746. };
  747. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  748. // 新增新一次的审批人列表
  749. // 获取当前次数审批人列表
  750. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeInfo.cid, changeInfo.times);
  751. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeInfo.cid, changeInfo.times, 1, 0);
  752. let usort = lastauditInfo.usort + 1;
  753. const newTimes = changeInfo.times + 1;
  754. const insert_audit_array = [];
  755. for (const al of auditList) {
  756. const insert_audit = {
  757. tid: al.tid,
  758. cid: al.cid,
  759. uid: al.uid,
  760. name: al.name,
  761. jobs: al.jobs,
  762. company: al.company,
  763. times: newTimes,
  764. usite: al.usite,
  765. usort,
  766. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  767. };
  768. insert_audit_array.push(insert_audit);
  769. usort++;
  770. }
  771. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  772. // 变更金额也退回
  773. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  774. where: { cid: changeInfo.cid },
  775. });
  776. let total_price = 0;
  777. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  778. for (const cl of changeList) {
  779. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  780. }
  781. // 设置变更令退回
  782. const change_update = {
  783. w_code: postData.w_code,
  784. status: audit.flow.status.back,
  785. times: newTimes,
  786. cin_time: Date.parse(new Date()) / 1000,
  787. total_price,
  788. tp_decimal: null,
  789. };
  790. const options = {
  791. where: {
  792. cid: postData.change_id,
  793. },
  794. };
  795. await this.transaction.update(this.tableName, change_update, options);
  796. await this.transaction.commit();
  797. result = true;
  798. const users = this._.map(insert_audit_array, 'uid');
  799. const sms = new SMS(this.ctx);
  800. const code = await sms.contentChange(changeData.code);
  801. await this.ctx.helper.sendAliSms(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), SmsAliConst.template.change_result, {
  802. biangeng: code,
  803. status: SmsAliConst.status.back,
  804. });
  805. // 微信模板通知
  806. const shenpiUrl = await this.ctx.helper.urlToShort(
  807. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  808. );
  809. const wechatData = {
  810. wap_url: shenpiUrl,
  811. status: wxConst.status.back,
  812. tips: wxConst.tips.back,
  813. code: this.ctx.session.sessionProject.code,
  814. c_name: changeInfo.name,
  815. };
  816. await this.ctx.helper.sendWechat(users, smsTypeConst.const.BG, smsTypeConst.judge.result.toString(), wxConst.template.change, wechatData);
  817. } catch (error) {
  818. await this.transaction.rollback();
  819. result = false;
  820. }
  821. return result;
  822. }
  823. /**
  824. * 审批退回到上一个审批人
  825. * @param {Number} pid 项目id
  826. * @param {int} postData - 表单提交的数据
  827. * @param {int} changeData - 变更令的数据
  828. * @return {void}
  829. */
  830. async approvalBackNew(pid, postData, changeData) {
  831. // 初始化事务
  832. this.transaction = await this.db.beginTransaction();
  833. let result = false;
  834. try {
  835. // 获取所有审核人列表
  836. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  837. // 添加到消息推送表
  838. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  839. const records = [];
  840. auditors.forEach(auditor => {
  841. records.push({
  842. pid,
  843. type: pushType.change,
  844. uid: auditor.uid,
  845. status: audit.flow.status.back,
  846. content: noticeContent,
  847. });
  848. });
  849. await this.transaction.insert('zh_notice', records);
  850. const changeInfo = await this.getDataByCondition({ cid: postData.change_id });
  851. // 设置审批人退回
  852. const audit_update = {
  853. id: postData.audit_id,
  854. sdesc: postData.sdesc,
  855. status: audit.flow.auditStatus.backnew,
  856. sin_time: new Date(),
  857. };
  858. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  859. // 获取当前审批人信息
  860. const auditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_id);
  861. // 获取当前次数审批人列表
  862. const auditList = await this.ctx.service.changeAudit.getNextAuditList(changeInfo.cid, auditInfo.usort);
  863. let usort = auditInfo.usort + 1;
  864. // 获取上一个审批人信息
  865. const lastauditInfo = await this.ctx.service.changeAudit.getDataById(postData.audit_last_id);
  866. // 新增2个审批人到审批列表中
  867. const insert_audit1 = {
  868. tid: lastauditInfo.tid,
  869. cid: lastauditInfo.cid,
  870. uid: lastauditInfo.uid,
  871. name: lastauditInfo.name,
  872. jobs: lastauditInfo.jobs,
  873. company: lastauditInfo.company,
  874. times: lastauditInfo.times,
  875. usite: lastauditInfo.usite,
  876. usort,
  877. status: audit.flow.auditStatus.checking,
  878. sin_time: new Date(),
  879. };
  880. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  881. usort++;
  882. // 新增2个审批人到审批列表中
  883. const insert_audit2 = {
  884. tid: auditInfo.tid,
  885. cid: auditInfo.cid,
  886. uid: auditInfo.uid,
  887. name: auditInfo.name,
  888. jobs: auditInfo.jobs,
  889. company: auditInfo.company,
  890. times: auditInfo.times,
  891. usite: auditInfo.usite,
  892. usort,
  893. status: audit.flow.auditStatus.uncheck,
  894. };
  895. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  896. // 把接下未审批的审批人排序都加2
  897. for (const al of auditList) {
  898. const audit_update = {
  899. id: al.id,
  900. usort: al.usort + 2,
  901. };
  902. await this.transaction.update(this.ctx.service.changeAudit.tableName, audit_update);
  903. }
  904. // 审批列表数据也要回退
  905. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  906. where: { cid: changeInfo.cid },
  907. });
  908. let total_price = 0;
  909. const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  910. for (const cl of changeList) {
  911. const audit_amount = cl.audit_amount.split(',');
  912. const last_amount = audit_amount[audit_amount.length - 1];
  913. audit_amount.splice(-1, 1);
  914. const list_update = {
  915. id: cl.id,
  916. audit_amount: audit_amount.join(','),
  917. spamount: parseFloat(last_amount),
  918. };
  919. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  920. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  921. }
  922. // 设置变更令退回
  923. const change_update = {
  924. w_code: postData.w_code,
  925. status: audit.flow.status.backnew,
  926. cin_time: Date.parse(new Date()) / 1000,
  927. total_price,
  928. };
  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. const sms = new SMS(this.ctx);
  938. const code = await sms.contentChange(changeData.code);
  939. const shenpiUrl = await this.ctx.helper.urlToShort(
  940. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeData.tid + '/change/' + changeData.cid + '/info#shenpi'
  941. );
  942. await this.ctx.helper.sendAliSms(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  943. biangeng: code,
  944. code: shenpiUrl,
  945. });
  946. // 微信模板通知
  947. const wechatData = {
  948. wap_url: shenpiUrl,
  949. status: wxConst.status.check,
  950. tips: wxConst.tips.check,
  951. code: this.ctx.session.sessionProject.code,
  952. c_name: changeInfo.name,
  953. };
  954. await this.ctx.helper.sendWechat(lastauditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  955. } catch (error) {
  956. await this.transaction.rollback();
  957. result = false;
  958. }
  959. return result;
  960. }
  961. /**
  962. * 查询可用的变更令
  963. * @param bills - 查询的清单
  964. * @param pos - 查询的部位
  965. * @return {Promise<*>} - 可用的变更令列表
  966. */
  967. async getValidChanges(tid, bills, pos) {
  968. const self = this;
  969. const getFilterPart = function(field, value) {
  970. return value
  971. ? field + ' = ' + self.db.escape(value)
  972. : self.db.format("(?? = null or ?? = '')", [field, field]);
  973. };
  974. const timesLen = 100;
  975. const filter = getFilterPart('cb.code', bills.b_code) +
  976. ' And ' + getFilterPart('cb.name', bills.name) +
  977. ' And ' + getFilterPart('cb.unit', bills.unit) +
  978. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  979. (pos ? getFilterPart('cb.bwmx', pos.name) : '');
  980. const sql =
  981. '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,' +
  982. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  983. ' 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, ' +
  984. ' scb.used_amount' +
  985. ' FROM ' + this.tableName + ' As c ' +
  986. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  987. ' Left Join (' +
  988. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  989. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  990. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  991. ' FROM ' + this.ctx.service.stageChange.tableName +
  992. ' WHERE tid = ?' +
  993. ' GROUP BY cbid, sid' +
  994. ' ) As MF' +
  995. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  996. ' GROUP BY sc.cbid' +
  997. ' ) As scb ON cb.id = scb.cbid' +
  998. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  999. ' ORDER BY c.in_time';
  1000. const sqlParam = [tid, tid, audit.flow.status.checked];
  1001. const changes = await this.db.query(sql, sqlParam);
  1002. for (const c of changes) {
  1003. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1004. ' FROM ?? As ca ' +
  1005. ' Left Join ?? As pa ' +
  1006. ' On ca.uid = pa.id ' +
  1007. ' Where ca.cid = ?';
  1008. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1009. c.attachments = await this.db.query(aSql, aSqlParam);
  1010. }
  1011. return changes;
  1012. }
  1013. /**
  1014. * 查询审批人可用的变更令
  1015. * @param bills - 查询的清单
  1016. * @param pos - 查询的部位
  1017. * @return {Promise<*>} - 可用的变更令列表
  1018. */
  1019. async getAuditValidChanges(tid, bills, pos, times, order) {
  1020. const timesLen = 100;
  1021. const filter =
  1022. 'cb.`code` = ' + this.db.escape(bills.b_code) +
  1023. ' And cb.`name` = ' + this.db.escape(bills.name) +
  1024. ' And cb.`unit` = ' + this.db.escape(bills.unit) +
  1025. ' And cb.`unit_price` = ' + this.db.escape(bills.unit_price) +
  1026. (pos ? ' And cb.`bwmx` = ' + this.db.escape(pos.name) : '');
  1027. const sql =
  1028. '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,' +
  1029. ' c.content, c.basis, c.memo, c.type, c.class, c.quality, c.company, c.charge, ' +
  1030. ' 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, ' +
  1031. ' scb.used_amount' +
  1032. ' FROM ' + this.tableName + ' As c ' +
  1033. ' Left Join ' + this.ctx.service.changeAuditList.tableName + ' As cb On c.cid = cb.cid ' +
  1034. ' Left Join (' +
  1035. ' SELECT SUM(sc.qty) As used_amount, sc.cbid' +
  1036. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1037. ' INNER JOIN (SELECT MAX(`stimes` * ' + timesLen + ' + `sorder`) As `flow`, cbid, sid ' +
  1038. ' FROM ' + this.ctx.service.stageChange.tableName +
  1039. ' WHERE tid = ? And (`stimes` < ? OR (`stimes` = ? AND `sorder` <= ?)) ' +
  1040. ' GROUP BY cbid, sid' +
  1041. ' ) As MF' +
  1042. ' ON (sc.stimes * ' + timesLen + ' + sc.sorder) = MF.flow And sc.cbid = MF.cbid And sc.sid = MF.sid' +
  1043. ' GROUP BY sc.cbid' +
  1044. ' ) As scb ON cb.id = scb.cbid' +
  1045. ' WHERE c.tid = ? And c.status = ? And c.valid And ' + filter +
  1046. ' ORDER BY c.in_time';
  1047. const sqlParam = [tid, times, times, order, tid, audit.flow.status.checked];
  1048. const changes = await this.db.query(sql, sqlParam);
  1049. for (const c of changes) {
  1050. const aSql = 'SELECT ca.*, pa.name As u_name, pa.role As u_role ' +
  1051. ' FROM ?? As ca ' +
  1052. ' Left Join ?? As pa ' +
  1053. ' On ca.uid = pa.id ' +
  1054. ' Where ca.cid = ?';
  1055. const aSqlParam = [this.ctx.service.changeAtt.tableName, this.ctx.service.projectAccount.tableName, c.cid];
  1056. c.attachments = await this.db.query(aSql, aSqlParam);
  1057. }
  1058. return changes;
  1059. }
  1060. /**
  1061. * 查询变更令 + 变更令执行
  1062. * @param tid
  1063. * @return {Promise<void>}
  1064. */
  1065. async getChangeAndUsedInfo(tid) {
  1066. const lastStage = await this.ctx.service.stage.getLastestStage(tid, true);
  1067. let filter;
  1068. if (lastStage.id === this.ctx.stage.id) {
  1069. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1070. lastStage.order,
  1071. lastStage.order,
  1072. this.ctx.stage.curTimes,
  1073. this.ctx.stage.curTimes,
  1074. this.ctx.stage.curOrder,
  1075. ]);
  1076. } else {
  1077. if (lastStage.status === audit.stage.status.uncheck) {
  1078. filter = ' And s.order < ' + lastStage.order;
  1079. } else if (lastStage.status === audit.stage.status.checked) {
  1080. filter = '';
  1081. } else if (lastStage.status === audit.stage.status.checkNo) {
  1082. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And sChange.`stimes` <= ?))', [lastStage.order, lastStage.order, lastStage.times]);
  1083. } else {
  1084. const curAuditor = await this.ctx.service.stageAudit.getCurAuditor(lastStage.id, lastStage.times);
  1085. filter = this.db.format(' And (s.`order` < ? OR (s.`order` = ? And (sChange.`stimes` < ? OR (sChange.`stimes` = ? And sChange.`sorder` <= ?))))', [
  1086. lastStage.order,
  1087. lastStage.order,
  1088. lastStage.times,
  1089. lastStage.times,
  1090. curAuditor.order - 1,
  1091. ]);
  1092. }
  1093. }
  1094. const sql =
  1095. 'SELECT C.*, Sum(U.utp) As used_tp, TRUNCATE(Sum(U.utp) / C.total_price * 100 + 0.005, 2) As used_pt' +
  1096. ' FROM ' + this.tableName + ' As C' +
  1097. ' LEFT JOIN (SELECT sc.tid, sc.cid, sc.cbid, IF(SUM(sc.qty) > 0, TRUNCATE(SUM(sc.qty) * cb.unit_price + ?, 0), TRUNCATE(SUM(sc.qty) * cb.unit_price - ?, ?)) As utp' +
  1098. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sc' +
  1099. ' INNER JOIN (' +
  1100. ' SELECT MAX(`stimes`) As `stimes`, MAX(`sorder`) As `sorder`, `lid`, `pid`, `cbid`, sChange.`sid` ' +
  1101. ' FROM ' + this.ctx.service.stageChange.tableName + ' As sChange ' +
  1102. ' LEFT JOIN ' + this.ctx.service.stage.tableName + ' As s' +
  1103. ' ON sChange.sid = s.id' +
  1104. ' WHERE sChange.tid = ?' + filter +
  1105. ' GROUP By `lid`, `pid`, `cbid`, `sid`' +
  1106. ' ) As m' +
  1107. ' 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`' +
  1108. ' LEFT JOIN ' + this.ctx.service.changeAuditList.tableName +
  1109. ' As cb ON sc.cbid = cb.id' +
  1110. ' GROUP By sc.`cbid`' +
  1111. ' ) As U ON C.cid = U.cid' +
  1112. ' WHERE C.tid = ? And C.status = ? And C.valid' +
  1113. ' GROUP By C.cid' +
  1114. ' ORDER By in_time';
  1115. // 舍入步长
  1116. const step = parseFloat('0.' + '0000000'.substr(0, this.ctx.tender.info.decimal.tp) + '5');
  1117. const sqlParam = [step, step, this.ctx.tender.info.decimal.tp, tid, tid, audit.flow.status.checked];
  1118. return await this.db.query(sql, sqlParam);
  1119. }
  1120. /**
  1121. * 查询可用的变更令
  1122. * @param { string } cid - 查询的清单
  1123. * @return {Promise<*>} - 可用的变更令列表
  1124. */
  1125. async delete(cid) {
  1126. // 初始化事务
  1127. this.transaction = await this.db.beginTransaction();
  1128. let result = false;
  1129. try {
  1130. const changeInfo = await this.getDataByCondition({ cid });
  1131. // 先删除清单,审批人列表
  1132. await this.transaction.delete(this.ctx.service.changeAuditList.tableName, { cid });
  1133. await this.transaction.delete(this.ctx.service.changeAudit.tableName, { cid });
  1134. // 再删除附件和附件文件ni zuo
  1135. const attList = await this.ctx.service.changeAtt.getAllDataByCondition({ where: { cid } });
  1136. if (attList.length !== 0) {
  1137. for (const att of attList) {
  1138. await fs.unlinkSync(path.join(this.app.baseDir, att.filepath));
  1139. }
  1140. await this.transaction.delete(this.ctx.service.changeAtt.tableName, { cid });
  1141. }
  1142. // 最后删除变更令
  1143. await this.transaction.delete(this.tableName, { cid });
  1144. // 记录删除日志
  1145. await this.ctx.service.projectLog.addProjectLog(this.transaction, projectLogConst.type.change, projectLogConst.status.delete, changeInfo.code);
  1146. await this.transaction.commit();
  1147. result = true;
  1148. } catch (e) {
  1149. await this.transaction.rollback();
  1150. result = false;
  1151. }
  1152. return result;
  1153. }
  1154. /**
  1155. * 重新审批变更令
  1156. * @param { string } cid - 查询的清单
  1157. * @return {Promise<*>} - 可用的变更令列表
  1158. */
  1159. async checkRevise(cid) {
  1160. // 初始化事务
  1161. this.transaction = await this.db.beginTransaction();
  1162. let result = false;
  1163. try {
  1164. const changeData = await this.getDataByCondition({ cid });
  1165. const pid = this.ctx.session.sessionProject.id;
  1166. // 获取所有审核人列表
  1167. const auditors = await this.ctx.service.changeAudit.getAllAuditors(changeData.tid);
  1168. // 添加到消息推送表
  1169. const noticeContent = await this.getNoticeContent(pid, changeData.tid, changeData.cid, this.ctx.session.sessionUser.accountId);
  1170. const records = [];
  1171. auditors.forEach(auditor => {
  1172. records.push({
  1173. pid,
  1174. type: pushType.change,
  1175. uid: auditor.uid,
  1176. status: audit.flow.status.revise,
  1177. content: noticeContent,
  1178. });
  1179. });
  1180. await this.transaction.insert('zh_notice', records);
  1181. // 新增新一次的审批人列表
  1182. // 获取当前次数审批人列表
  1183. const auditList = await this.ctx.service.changeAudit.getListGroupByTimes(changeData.cid, changeData.times);
  1184. const lastauditInfo = await this.ctx.service.changeAudit.getLastUser(changeData.cid, changeData.times, 1, 0);
  1185. let usort = lastauditInfo.usort + 1;
  1186. const newTimes = changeData.times + 1;
  1187. const insert_audit_array = [];
  1188. for (const al of auditList) {
  1189. const insert_audit = {
  1190. tid: al.tid,
  1191. cid: al.cid,
  1192. uid: al.uid,
  1193. name: al.name,
  1194. jobs: al.jobs,
  1195. company: al.company,
  1196. times: newTimes,
  1197. usite: al.usite,
  1198. usort,
  1199. status: al.usite !== 0 ? audit.flow.auditStatus.uncheck : audit.flow.auditStatus.checking,
  1200. };
  1201. insert_audit_array.push(insert_audit);
  1202. usort++;
  1203. }
  1204. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit_array);
  1205. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1206. where: { cid: changeData.cid },
  1207. });
  1208. // 申请变更金额更新为上一次审批审批变更后数量,清空audit_amount值
  1209. const updateTpList = [];
  1210. for (const cl of changeList) {
  1211. updateTpList.push({ id: cl.id, camount: cl.spamount, audit_amount: null });
  1212. }
  1213. if (updateTpList.length > 0) {
  1214. await this.transaction.updateRows(this.ctx.service.changeAuditList.tableName, updateTpList);
  1215. }
  1216. // let total_price = 0;
  1217. // const tp_decimal = changeData.tp_decimal ? changeData.tp_decimal : this.ctx.tender.info.decimal.tp;
  1218. // for (const cl of changeList) {
  1219. // total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, cl.camount, tp_decimal));
  1220. // }
  1221. // 设置变更令修订状态
  1222. const change_update = {
  1223. w_code: changeData.w_code,
  1224. status: audit.flow.status.revise,
  1225. times: newTimes,
  1226. cin_time: Date.parse(new Date()) / 1000,
  1227. // total_price,
  1228. tp_decimal: null,
  1229. };
  1230. const options = {
  1231. where: {
  1232. cid: changeData.cid,
  1233. },
  1234. };
  1235. await this.transaction.update(this.tableName, change_update, options);
  1236. await this.transaction.commit();
  1237. result = true;
  1238. } catch (error) {
  1239. await this.transaction.rollback();
  1240. result = false;
  1241. }
  1242. return result;
  1243. }
  1244. /**
  1245. * 重新审批变更令
  1246. * @param { string } cid - 查询的清单
  1247. * @return {Promise<*>} - 可用的变更令列表
  1248. */
  1249. async checkAgain(cid) {
  1250. // 初始化事务
  1251. this.transaction = await this.db.beginTransaction();
  1252. let result = false;
  1253. try {
  1254. const changeInfo = await this.getDataByCondition({ cid });
  1255. // 获取终审
  1256. const auditInfo = (
  1257. await this.ctx.service.changeAudit.getAllDataByCondition({
  1258. where: { cid },
  1259. orders: [['usort', 'desc']],
  1260. limit: 1,
  1261. offset: 0,
  1262. })
  1263. )[0];
  1264. let usort = auditInfo.usort + 1;
  1265. // 新增2个审批状态到审批列表中
  1266. const insert_audit1 = {
  1267. tid: auditInfo.tid,
  1268. cid: auditInfo.cid,
  1269. uid: auditInfo.uid,
  1270. name: auditInfo.name,
  1271. jobs: auditInfo.jobs,
  1272. company: auditInfo.company,
  1273. times: auditInfo.times,
  1274. usite: auditInfo.usite,
  1275. usort,
  1276. sin_time: new Date(),
  1277. status: audit.flow.auditStatus.checkAgain,
  1278. };
  1279. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit1);
  1280. usort++;
  1281. // 新增2个审批人到审批列表中
  1282. const insert_audit2 = {
  1283. tid: auditInfo.tid,
  1284. cid: auditInfo.cid,
  1285. uid: auditInfo.uid,
  1286. name: auditInfo.name,
  1287. jobs: auditInfo.jobs,
  1288. company: auditInfo.company,
  1289. times: auditInfo.times,
  1290. usite: auditInfo.usite,
  1291. usort,
  1292. status: audit.flow.auditStatus.checking,
  1293. sin_time: new Date(),
  1294. };
  1295. await this.transaction.insert(this.ctx.service.changeAudit.tableName, insert_audit2);
  1296. // 审批列表数据也要回退
  1297. let total_price = 0;
  1298. const tp_decimal = changeInfo.tp_decimal ? changeInfo.tp_decimal : this.ctx.tender.info.decimal.tp;
  1299. const changeList = await this.ctx.service.changeAuditList.getAllDataByCondition({
  1300. where: { cid: changeInfo.cid },
  1301. });
  1302. for (const cl of changeList) {
  1303. const audit_amount = cl.audit_amount.split(',');
  1304. const last_amount = audit_amount[audit_amount.length - 1];
  1305. audit_amount.splice(-1, 1);
  1306. const list_update = {
  1307. id: cl.id,
  1308. audit_amount: audit_amount.join(','),
  1309. samount: '',
  1310. };
  1311. total_price = this.ctx.helper.add(total_price, this.ctx.helper.mul(cl.unit_price, parseFloat(last_amount), tp_decimal));
  1312. await this.transaction.update(this.ctx.service.changeAuditList.tableName, list_update);
  1313. }
  1314. // 设置变更令审批中
  1315. const change_update = {
  1316. p_code: null,
  1317. status: audit.flow.status.checking,
  1318. cin_time: Date.parse(new Date()) / 1000,
  1319. sin_time: null,
  1320. total_price,
  1321. };
  1322. const options = {
  1323. where: {
  1324. cid: changeInfo.cid,
  1325. },
  1326. };
  1327. await this.transaction.update(this.tableName, change_update, options);
  1328. await this.transaction.commit();
  1329. result = true;
  1330. const sms = new SMS(this.ctx);
  1331. const code = await sms.contentChange(changeInfo.code);
  1332. const shenpiUrl = await this.ctx.helper.urlToShort(
  1333. this.ctx.protocol + '://' + this.ctx.host + '/wap/tender/' + changeInfo.tid + '/change/' + changeInfo.cid + '/info#shenpi'
  1334. );
  1335. await this.ctx.helper.sendAliSms(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), SmsAliConst.template.change_check, {
  1336. biangeng: code,
  1337. code: shenpiUrl,
  1338. });
  1339. // 微信模板通知
  1340. const wechatData = {
  1341. wap_url: shenpiUrl,
  1342. status: wxConst.status.check,
  1343. tips: wxConst.tips.check,
  1344. code: this.ctx.session.sessionProject.code,
  1345. c_name: changeInfo.name,
  1346. };
  1347. await this.ctx.helper.sendWechat(auditInfo.uid, smsTypeConst.const.BG, smsTypeConst.judge.approval.toString(), wxConst.template.change, wechatData);
  1348. } catch (error) {
  1349. await this.transaction.rollback();
  1350. result = false;
  1351. }
  1352. return result;
  1353. }
  1354. /**
  1355. * 判断是否有重名的变更令
  1356. * @param cid
  1357. * @param code
  1358. * @param tid
  1359. * @return {Promise<void>}
  1360. */
  1361. async isRepeat(cid, code, tid) {
  1362. const sql = 'SELECT COUNT(*) as count FROM ?? WHERE ((`code` = ? AND `status` != ?) OR (`p_code` = ? AND `status` = ?)) AND `cid` != ? AND `tid` = ?';
  1363. const sqlParam = [this.tableName, code, audit.flow.status.checked, code, audit.flow.status.checked, cid, tid];
  1364. const result = await this.db.queryOne(sql, sqlParam);
  1365. return result.count !== 0;
  1366. }
  1367. async getAllCheckedChanges(tid) {
  1368. return await this.getAllDataByCondition({
  1369. where: { tid, status: audit.flow.status.checked },
  1370. orders: [['in_time', 'desc']],
  1371. });
  1372. }
  1373. /**
  1374. * 用于添加推送所需的content内容
  1375. * @param {Number} pid 项目id
  1376. * @param {Number} tid 台账id
  1377. * @param {Number} cid 变更id
  1378. * @param {Number} uid 审核人id
  1379. */
  1380. async getNoticeContent(pid, tid, cid, uid) {
  1381. const noticeSql =
  1382. 'SELECT * FROM (SELECT ' +
  1383. ' t.`id` As `tid`, t.`name`, c.`cid`, c.`code` As `c_code`, pa.`name` As `su_name`, pa.role As `su_role`' +
  1384. ' FROM (SELECT * FROM ?? WHERE `id` = ? ) As t' +
  1385. ' LEFT JOIN ?? As c ON c.`cid` = ?' +
  1386. ' LEFT JOIN ?? As pa ON pa.`id` = ?' +
  1387. ' WHERE t.`project_id` = ? ) as new_t GROUP BY new_t.`tid`';
  1388. const noticeSqlParam = [this.ctx.service.tender.tableName, tid, this.ctx.service.change.tableName, cid, this.ctx.service.projectAccount.tableName, uid, pid];
  1389. const content = await this.db.query(noticeSql, noticeSqlParam);
  1390. return content.length ? JSON.stringify(content[0]) : '';
  1391. }
  1392. /**
  1393. * 获取当前标段其他变更令
  1394. * @param {Number} tid - 标段id
  1395. * @param {Number} cid - 当前变更令
  1396. */
  1397. async getOthersChange(tid, cid) {
  1398. const sql = 'SELECT * FROM ?? WHERE tid = ? AND cid != ? ORDER By `in_time` desc ';
  1399. const sqlParam = [this.tableName, tid, cid];
  1400. const data = await this.db.query(sql, sqlParam);
  1401. const changeClassObj = {};
  1402. for (const c in changeConst.class) {
  1403. if (changeConst.class.hasOwnProperty(c)) {
  1404. const item = changeConst.class[c];
  1405. changeClassObj[item.value] = item.name;
  1406. }
  1407. }
  1408. for (let i = 0; i < data.length; i++) {
  1409. data[i].class = changeClassObj[data[i].class];
  1410. }
  1411. return data;
  1412. }
  1413. /**
  1414. * 拷贝变更令至当前变更令
  1415. * @param {String} cid - 当前变更令
  1416. * @param {String} copy_cid - 要拷贝的变更令
  1417. */
  1418. async handleCopyChange(cid, copy_cid) {
  1419. // const change = await this.getDataByCondition({ cid });
  1420. const copyChange = await this.getDataByCondition({ cid: copy_cid });
  1421. 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,
  1422. class: copyChange.class, quality: copyChange.quality, company: copyChange.company, charge: copyChange.charge, new_code: copyChange.new_code }, {
  1423. cid,
  1424. });
  1425. }
  1426. }
  1427. return Change;
  1428. };