change.js 118 KB

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