change.js 119 KB

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