change.js 65 KB

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