change.js 121 KB

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