change.js 121 KB

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