change.js 120 KB

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