2021与蓝度共同重构项目,服务端
liuhaonan
2022-09-20 045dcbf340bb5311223ba6b021fe8aa790e94086
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
package com.sandu.ximon.admin.service;
 
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sandu.common.enums.RoleLevelStatus;
import com.sandu.common.execption.BusinessException;
import com.sandu.common.redis.RedisService;
import com.sandu.common.security.LoginUserInfo;
import com.sandu.common.security.token.TokenProvider;
import com.sandu.common.service.impl.BaseServiceImpl;
import com.sandu.common.util.IpUtil;
import com.sandu.common.util.SpringContextHolder;
import com.sandu.ximon.admin.dto.ClientDto;
import com.sandu.ximon.admin.dto.ClientDtoNode;
import com.sandu.ximon.admin.param.AddClientPrarm;
import com.sandu.ximon.admin.param.PwdParam;
import com.sandu.ximon.admin.param.UpdateClientPrarm;
import com.sandu.ximon.admin.param.UserPwsParm;
import com.sandu.ximon.admin.security.SecurityUtils;
import com.sandu.ximon.admin.utils.StoreOperationRecordsUtils;
import com.sandu.ximon.dao.bo.MenuNode;
import com.sandu.ximon.dao.domain.*;
import com.sandu.ximon.dao.enums.AdministratorEnums;
import com.sandu.ximon.dao.enums.OrderByEnums;
import com.sandu.ximon.dao.mapper.ClientMapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
 
@Service
@AllArgsConstructor
public class ClientService extends BaseServiceImpl<ClientMapper, Client> {
 
    private final PasswordEncoder passwordEncoder;
    private final ClientRoleRelationService clientRoleRelationService;
    private final RoleService roleService;
    private final TokenProvider tokenProvider;
 
 
    public boolean addClient(AddClientPrarm addClientPrarm) {
 
        if (getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getClientName, addClientPrarm.getClientName().trim())) != null) {
            throw new BusinessException("该用户名已存在!");
        }
        Long userId = SecurityUtils.getUserId();
        boolean clientId = findClientId();
        //判断是否为二级客户  如果是二级客户则不能继续添加   一级客户为FALSE
        if (SecurityUtils.getClientId() != null && clientId) {
            throw new BusinessException("权限不足,二级客户不能新增用户!");
        }
 
 
        Client client = new Client();
 
        if (SecurityUtils.getClientId() != null && !clientId) {
            //一级客户新增用户时 默认为自己名下的二级客户
            client.setSuperiorId(SecurityUtils.getUserId());
            client.setClientSuperior(addClientPrarm.getClientSuperior());
        } else if (addClientPrarm.getClientSuperior() != null && !"".equals(addClientPrarm.getClientSuperior())) {
            //超管
            Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getClientName, addClientPrarm.getClientSuperior()));
            if (one != null) {
                if (one.getSuperiorId() == null) {
                    client.setSuperiorId(one.getId());
                    client.setClientSuperior(addClientPrarm.getClientSuperior());
                } else {
                    throw new BusinessException("上级客户不能为二级用户");
                }
            } else {
                throw new BusinessException("上级客户不存在");
            }
        }
 
        Role role = roleService.getById(addClientPrarm.getRoleId());
        if (role == null) {
            throw new BusinessException("角色不存在");
        }
        if (RoleLevelStatus.SUPER.getCode().equals(role.getLevel())) {
            throw new BusinessException("无法添加超级管理员");
        }
 
 
        client.setClientName(addClientPrarm.getClientName());
        client.setLinkMan(addClientPrarm.getLinkMan());
//        client.setClientSuperior(addClientPrarm.getClientSuperior());
        client.setMobile(addClientPrarm.getMobile());
        if (SecurityUtils.getClientId() != null && clientId) {
            client.setClientSuperior(SecurityUtils.getUsername());
        }
        client.setPassword(passwordEncoder.encode(addClientPrarm.getPassword()));
        boolean flag = save(client);
 
        ClientRoleRelation clientRoleRelation = new ClientRoleRelation();
        clientRoleRelation.setClientId(client.getId());
        clientRoleRelation.setRoleId(addClientPrarm.getRoleId());
        if (!clientRoleRelationService.save(clientRoleRelation)) {
            throw new BusinessException("添加管理员角色失败");
        }
 
        /**
         * 添加普通用户 日志记录开始
         */
        String content = "新注册用户:" + addClientPrarm.getClientName();
        StoreOperationRecordsUtils.storeOperationData(null, null, "添加普通用户", content);
        /**
         * 添加普通用户 日志记录结束
         */
 
        return flag;
    }
 
 
    public boolean updateClient(Long id, UpdateClientPrarm updateClientPrarm) {
        //判断用户是否存在
        Client one = getById(id);
        if (one == null) {
            throw new BusinessException("该客户不存在");
        }
 
        //判断用户名是否重复
        Client client1 = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getClientName, updateClientPrarm.getClientName().trim()));
        if (client1 != null && !client1.getId().equals(one.getId())) {
            throw new BusinessException("该用户名已存在!");
        }
 
        //判断上级用户是否存在
        boolean clientId = findClientId();
        Long userId = SecurityUtils.getUserId();
        //判断更改的用户是否是属于自己名下的二级客户
        if (SecurityUtils.getClientId() != null && !clientId) {
            if (SecurityUtils.getUserId() != one.getSuperiorId()) {
                throw new BusinessException("权限不足,不能更改其他客户的所属客户信息!");
            }
        }
 
        Client client = new Client();
        client.setClientName(updateClientPrarm.getClientName());
        if (SecurityUtils.getClientId() != null && clientId) {
            //一级客户新增用户时 默认为自己名下的二级客户
            client.setSuperiorId(SecurityUtils.getUserId());
            client.setClientSuperior(updateClientPrarm.getClientSuperior());
        } else if (updateClientPrarm.getClientSuperior() != null && updateClientPrarm.getClientSuperior().trim().length() != 0) {
            //超管
            Client superior = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getClientName, updateClientPrarm.getClientSuperior()));
            if (superior != null) {
                if (superior.getId().equals(one.getId())) {
                    throw new BusinessException("上级客户为本账户!");
                } else {
                    client.setSuperiorId(superior.getId());
                    client.setClientSuperior(updateClientPrarm.getClientSuperior());
                }
            } else {
                throw new BusinessException("上级客户不存在");
            }
        }
        client.setId(id);
//        client.setClientName(updateClientPrarm.getClientName());
        client.setLinkMan(updateClientPrarm.getLinkMan());
        client.setMobile(updateClientPrarm.getMobile());
 
        /**
         * 编辑普通用户 日志记录开始
         */
        String content = "编辑普通用户:" + client.getClientName() + "用户id:" + id;
        StoreOperationRecordsUtils.storeOperationData(null, null, "编辑普通用户", content);
        /**
         * 编辑普通用户 日志记录结束
         */
        return updateById(client);
    }
 
    /**
     * 修改当前登录用户密码
     *
     * @param param
     * @return
     */
    public boolean resetPassword(PwdParam param) {
 
        Client client = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, SecurityUtils.getUserDetails().getUserId()));
 
        if (client == null) {
            throw new BusinessException("该用户不存在!");
        }
 
        //判断旧密码与数据库是否一致
        if (passwordEncoder.matches(param.getOldPass(), client.getPassword())) {
            //加密新密码
            String encode = passwordEncoder.encode(param.getNewPass());
            client.setPassword(encode);
            return updateById(client);
        } else {
            throw new BusinessException("旧密码不正确,请重新确认密码!");
        }
    }
 
    /**
     * 修改管理员的密码
     *
     * @param param
     * @return
     */
    public boolean updateAdminPassword(UserPwsParm param) {
        Client client = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, param.getUserid()));
        if (client == null) {
            throw new BusinessException("用户不存在");
        }
 
        //加密新密码
        client.setPassword(passwordEncoder.encode(param.getNewPass()));
        return updateById(client);
    }
 
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteClient(Long id) {
        boolean flag = false;
        //判断删除用户是否存在
        Client client = getById(id);
        if (client == null) {
            throw new BusinessException("该客户不存在");
        }
 
        //只有超管能删除  或  上级客户删除自己的下级用户
        if (!AdministratorEnums.ADMIN.getCode().equals(SecurityUtils.getUserDetails().getAdministratorType())) {
            Client temp = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getSuperiorId, SecurityUtils.getUserId()).eq(Client::getId, id));
            if (temp == null) {
                throw new BusinessException("删除的用户不存在或该用户不是你的下级用户");
            }
        }
 
        //判断删除的用户有无下级用户
        LambdaQueryWrapper<Client> lambdaQueryWrapper = Wrappers.lambdaQuery(Client.class).eq(Client::getSuperiorId, id);
        List<Client> list = list(lambdaQueryWrapper);
        if (list != null && list.size() != 0) {
            throw new BusinessException("删除的用户下有下级用户,不允许删除");
        }
 
        //管理员角色关系表
        ClientRoleRelationService clientRoleRelationService = SpringContextHolder.getBean(ClientRoleRelationService.class);
        //有用户必定有用户与角色的关系数据
        ClientRoleRelation one = clientRoleRelationService.getOne(Wrappers.lambdaQuery(ClientRoleRelation.class).eq(ClientRoleRelation::getClientId, client.getId()));
 
        //删用户
        if (removeById(id)) {
            //删角色关系表信息
            flag = clientRoleRelationService.removeById(one);
            List<Pole> poles = SpringContextHolder.getBean(PoleService.class).list(Wrappers.lambdaQuery(Pole.class).eq(Pole::getClientId, id));
            poles.forEach(
                    pole -> {
                        pole.setClientId(-1L);
                    }
            );
            flag = SpringContextHolder.getBean(PoleService.class).updateBatchById(poles);
            //删除失败回滚数据
            if (!flag) {
                throw new BusinessException("删除用户失败!");
            }
        }
 
        /**
         * 删除普通用户 日志记录开始
         */
        String content = "删除普通用户:" + client.getClientName() + "用户id:" + id;
        StoreOperationRecordsUtils.storeOperationData(null, null, "删除普通用户", content);
        /**
         * 删除普通用户 日志记录结束
         */
 
        return flag;
    }
 
    /**
     * 用户列表
     *
     * @param keyword
     * @param order
     * @param seq
     * @return
     */
    public List<ClientDtoNode> listLikeClient(String keyword, Integer order, Integer seq) {
 
 
        LambdaQueryWrapper<Client> wrapper = Wrappers.lambdaQuery(Client.class);
        if (AdministratorEnums.NORMAL.getCode().equals(SecurityUtils.getAdministratorIdentity())) {
            wrapper.eq(Client::getSuperiorId, SecurityUtils.getUserId()).or(w -> w.eq(
                    Client::getId, SecurityUtils.getUserId()
            ));
        }
        if (keyword != null && !keyword.isEmpty()) {
            wrapper.like(Client::getClientName, keyword)
                    .or(w1 -> w1.like(Client::getMobile, keyword))
                    .or(w2 -> w2.like(Client::getLinkMan, keyword));
        }
        //排序字段
        String orderByResult = "id";
        //正序、倒叙
        String orderBySeq = OrderByEnums.ASC.getCode();
        if (order != null) {
            switch (order) {
                case 1:
                    orderByResult = OrderByEnums.CLIENT_CREATE_TIME.getCode();
                    break;
                default:
            }
        }
        if (seq != null) {
            switch (seq) {
                case 1:
                    orderBySeq = OrderByEnums.ASC.getCode();
                    break;
                case 2:
                    orderBySeq = OrderByEnums.DESC.getCode();
                    break;
                default:
                    break;
            }
        }
        //排序方式
        String orderBy = orderByResult + " " + orderBySeq;
 
//        if (baseConditionVO != null) {
//            PageHelper.startPage(baseConditionVO.getPageNo(), baseConditionVO.getPageSize(), orderBy);
//        }
 
        List<Client> clientList = list(wrapper);
 
        List<ClientDto> clientDtoList = new ArrayList<>();
        for (Client demo : clientList) {
            ClientDto clientDto = new ClientDto();
            BeanUtil.copyProperties(demo, clientDto);
            ClientRoleRelation one = clientRoleRelationService.getOne(Wrappers.lambdaQuery(ClientRoleRelation.class)
                    .eq(ClientRoleRelation::getClientId, demo.getId()));
 
            if (one != null) {
                clientDto.setRoleId(one.getRoleId());
            }
            clientDtoList.add(clientDto);
        }
 
        return clientDtoList.stream()
                .filter(bean -> null == bean.getSuperiorId())
                .map(bean -> covertClientDtoNode(bean, clientDtoList)).collect(Collectors.toList());
    }
 
    /**
     * 数据整理成树状图
     *
     * @param clientDto
     * @param clientDtoList
     * @return
     */
    private ClientDtoNode covertClientDtoNode(ClientDto clientDto, List<ClientDto> clientDtoList) {
        ClientDtoNode node = new ClientDtoNode();
        BeanUtils.copyProperties(clientDto, node);
        List<ClientDtoNode> children = clientDtoList.stream()
                .filter(subClientDto -> (subClientDto.getSuperiorId() != null && subClientDto.getSuperiorId().equals(clientDto.getId())))
                .map(subClientDto -> covertClientDtoNode(subClientDto, clientDtoList)).collect(Collectors.toList());
        node.setChildren(children);
        return node;
    }
 
    public Client findByPhone(String phone) {
        return getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getMobile, phone).last("limit 1"));
    }
 
    /**
     * \
     * 其他类用来查找客户id使用  如果没有上级客户 这返回用户ID
     *
     * @param
     * @return
     */
    public Long getClientId() {
        Long userId = SecurityUtils.getUserId();
        Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (one != null && one.getSuperiorId() != null) {
            return one.getSuperiorId();
        } else {
            return userId;
        }
 
    }
 
    /**
     * \
     * 其他类用来查找客户id使用  如果没有上级客户 返回-1
     *
     * @param
     * @return
     */
    public Long getClientId(Long userId) {
        Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (one != null && one.getSuperiorId() != null) {
            return one.getSuperiorId();
        } else {
            return -1L;
        }
 
    }
 
    /**
     * 一级客户返回false  二级客户返回true
     *
     * @return
     */
    public boolean findClientId() {
        Long userId = SecurityUtils.getUserId();
        Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (one != null && one.getSuperiorId() != null) {
            return true;
        } else {
            return false;
        }
 
    }
 
    /**
     * 一级客户返回false  二级客户返回true
     *
     * @return
     */
    public boolean findClientId(Long userId) {
        Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (one != null && one.getSuperiorId() != null) {
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * 修改普通用户头像
     *
     * @param userId
     * @param IconUrl
     * @return
     */
    public boolean updateIcon(Long userId, String IconUrl) {
        Client one = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getId, userId));
        if (one == null) {
            throw new BusinessException("用户不存在");
        }
        one.setIcon(IconUrl);
        return updateById(one);
    }
 
    /**
     * 获取用户权限列表地
     */
    public List<MenuNode> getUserPermissionList() {
        //通过用户UserID获取用户角色
        ClientRoleRelation one = SpringContextHolder.getBean(ClientRoleRelationService.class).
                getOne(Wrappers.lambdaQuery(ClientRoleRelation.class).eq(ClientRoleRelation::getClientId, SecurityUtils.getUserId()));
        //判空
        if (one == null) {
            throw new BusinessException("该用户未绑定角色");
        }
 
        //通过RoleID获取MeunId列表
        List<RoleMenuRelation> menuIdList = SpringContextHolder.getBean(RoleMenuRelationService.class)
                .list(Wrappers.lambdaQuery(RoleMenuRelation.class).eq(RoleMenuRelation::getRoleId, one.getRoleId()));
 
        //判空
        if (menuIdList.isEmpty()) {
            return new ArrayList<>();
        }
 
        List<Long> menuIds = new ArrayList<>(menuIdList.size());
        for (RoleMenuRelation bean : menuIdList) {
            menuIds.add(bean.getMenuId());
        }
 
        List<MenuNode> resultList = SpringContextHolder.getBean(MenuService.class).getUserPermissionListById(menuIds);
        return resultList;
    }
 
    /**
     * 生成便捷登录KEY
     */
    public String creatKeyByLogin(String keyValue) {
        if (keyValue == null) {
            throw new BusinessException("key不能为空!");
        }
 
        Object object = SpringContextHolder.getBean(RedisService.class).get(keyValue);
 
        if (object != null) {
            return object.toString();
        } else {
            Client client = getOne(Wrappers.lambdaQuery(Client.class).eq(Client::getUserKey, keyValue));
            if (client == null) {
                throw new BusinessException("用户不存在或key过期,请联系管理员重新获取最新key!");
            }
 
            Collection<GrantedAuthority> grantedAuthorities = roleService.mapToGrantedAuthorities(client.getId(), false);
 
            LoginUserInfo loginUserInfo = new LoginUserInfo();
            loginUserInfo.setUserId(client.getId());
            loginUserInfo.setAccount(client.getClientName());
            loginUserInfo.setIp(IpUtil.getRealIp());
            loginUserInfo.setAdministratorType(AdministratorEnums.NORMAL.getCode());
            loginUserInfo.setPermission(grantedAuthorities.stream().map(GrantedAuthority::getAuthority).collect(Collectors.joining(",")));
 
            // 生成令牌
            String token = tokenProvider.createToken(loginUserInfo);
            return token;
        }
    }
}