change.js 111 KB

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