change.js 113 KB

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