change.js 104 KB

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