BAOLH
2026-05-18 c6d960f0e2d094c86a8e7eb0802e7bae86de63ed
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
/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;
 
import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.DataService;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.vo.UserPassVo;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.DeptUserNodeDto;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import me.zhengjie.modules.system.service.VerifyService;
import me.zhengjie.utils.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.enums.CodeEnum;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;
 
/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Api(tags = "系统:用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {
 
    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final DataService dataService;
    private final DeptService deptService;
    private final RoleService roleService;
    private final VerifyService verificationCodeService;
 
    @ApiOperation("导出用户数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:download')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
        userService.download(userService.queryAll(criteria), response);
    }
    
    @GetMapping(value = "/dept/{deptId}")
    @AnonymousAccess
    public ResponseEntity<Object> queryDeptUserByDeptId(@PathVariable Long deptId) {
        return new ResponseEntity<>(userService.queryDeptUserByDeptId(deptId), HttpStatus.OK);
    }
 
    @GetMapping(value = "/all")
    @Log("查询用户")
    @ApiOperation("查询用户")
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> queryUserAll(UserQueryCriteria criteria){
        return new ResponseEntity<>(userService.queryAll(criteria),HttpStatus.OK);
    }
 
    @GetMapping(value = "/approval")
    @Log("查询用户")
    @ApiOperation("查询用户")
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> queryApprovalUser(UserQueryCriteria criteria) {
        // 当前用户
        UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
        List<Long> deptList = new ArrayList<Long>();
        // 当前部门
        DeptDto deptDto = deptService.findById(user.getDept().getId());
        // 然后把父节点的ID都加入到集合中
        deptList.addAll(deptService.getSuperior(deptDto, new ArrayList<Dept>()).stream().map(dept -> dept.getId()).collect(Collectors.toList()));
        // 父部门加入检索条件
        criteria.getDeptIds().addAll(deptList);
 
        RoleSmallDto role = user.getRoles().stream().findFirst().orElseGet(RoleSmallDto::new);
        // 数据权限是全体的场合,包含自己,否则不包含自己
        if ("全部".equals(role.getDataScope())) {
            criteria.setLevel(role.getLevel());
        } else {
            criteria.setLevelNq(role.getLevel());
        }
        return new ResponseEntity<>(userService.queryAll(criteria),HttpStatus.OK);
    }
 
    @ApiOperation("查询用户")
    @GetMapping
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> queryUser(UserQueryCriteria criteria, Pageable pageable){
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        List<Long> totalScopes = new ArrayList<Long>(dataScopes);
        for (Long dataScope : dataScopes) {
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(dataScope);
            // 然后把子节点的ID都加入到集合中
            totalScopes.addAll(deptService.getDeptChildren(data));
        }
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(totalScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(totalScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(totalScopes);
            return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
        }
        return new ResponseEntity<>(PageUtil.toPage(null,0),HttpStatus.OK);
    }
 
//    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){
        checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }
 
    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
 
    @Log("修改用户:个人中心")
    @ApiOperation("修改用户:个人中心")
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
 
    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
        for (Long id : ids) {
            Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            if (currentLevel > optLevel) {
                throw new BadRequestException("角色权限不足,不能删除:" + userService.findById(id).getUsername());
            }
        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
 
    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
        UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败,旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }
 
    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }
 
    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
        UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(password, userDto.getPassword())){
            throw new BadRequestException("密码错误");
        }
        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
        userService.updateEmail(userDto.getUsername(),user.getEmail());
        return new ResponseEntity<>(HttpStatus.OK);
    }
 
    /**
     * 如果当前用户的角色级别低于创建用户的角色级别,则抛出权限不足的错误
     * @param resources /
     */
    private void checkLevel(User resources) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        Integer optLevel = roleService.findByRoles(resources.getRoles());
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足");
        }
    }
 
    /**
     * 获取用户日历信息
     * @param month
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/getUserCalendarInfo/{month}")
    @Log("获取用户日历信息")
    @ApiOperation("获取用户日历信息")
    public ResponseEntity<Object> getUserCalendarInfo(@PathVariable String month) throws Exception {
        return new ResponseEntity<>(userService.getUserCalendarInfo(month), HttpStatus.OK);
    }
 
    @GetMapping(value = "/getUserBaseInfo/{yearMonth}")
    @Log("获取用户基础信息")
    @ApiOperation("获取用户日历信息")
    public ResponseEntity<Object> getUserBaseInfo(@PathVariable Date yearMonth) throws ParseException {
        return new ResponseEntity<>(userService.getUserBaseInfo(yearMonth), HttpStatus.OK);
    }
 
    @GetMapping("/getProjectUser")
    public ResponseEntity<Object> getUserByTaskId(String taskId){
        return new ResponseEntity<>(userService.getUserByTaskId(taskId),HttpStatus.OK);
    }
 
    @GetMapping("/getAllUser")
    public ResponseEntity<Object> getAllUserByTaskId(String taskId){
        return new ResponseEntity<>(userService.getAllUserByTaskId(taskId),HttpStatus.OK);
    }
 
 
    @GetMapping("/getUserDept")
    public ResponseEntity<Object> getAllUserDetail(){
        return new ResponseEntity<>(userService.getUserDept(),HttpStatus.OK);
    }
 
 
    @GetMapping("/getUserPidDept")
    public ResponseEntity<Object> getUserPidDept(Long[] ids) {
        List<Long[]> result = new ArrayList<>();
        for (Long id : ids) {
            result.add(userService.getUserPidDept(id));
        }
        return new ResponseEntity<>(result,HttpStatus.OK);
    }
 
    @GetMapping("/getPerformanceDetail")
    public ResponseEntity<Object> getPerformanceDetail(Long nextMonth) throws ParseException {
        return new ResponseEntity<>(HttpStatus.OK); // userService.getPerformanceDetail(nextMonth),
 
    }
 
    @GetMapping(value = "/getUserInfose")
    @Log("查询用户信息")
    @ApiOperation("查询用户信息")
    public ResponseEntity<Object> getUserInfos() {
        return new ResponseEntity<>(userService.getUserInfose(), HttpStatus.OK);
    }
}