UserController.java 19.7 KB
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
package com.aigeo.company.controller;

import com.aigeo.company.entity.User;
import com.aigeo.company.service.UserService;
import com.aigeo.common.result.Result;
import com.aigeo.common.result.ResultCode;
import com.aigeo.common.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理控制器
 * 
 * @author AIGEO Team
 * @since 1.0.0
 */
@Tag(name = "用户管理", description = "用户信息管理接口,支持用户的创建、查询、更新和删除操作")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
@Slf4j
public class UserController {
    
    private final UserService userService;

    @Operation(
        summary = "分页查询用户列表", 
        description = "支持按用户名、邮箱、角色等条件分页查询用户列表,默认按创建时间倒序排列"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/list")
    public Result<Page<User>> listUsers(
        @Parameter(description = "页码,从0开始", example = "0") 
        @RequestParam(defaultValue = "0") int page,
        
        @Parameter(description = "页大小,默认10条", example = "10") 
        @RequestParam(defaultValue = "10") int size,
        
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId,
        
        @Parameter(description = "用户名(模糊查询)") 
        @RequestParam(required = false) String username,
        
        @Parameter(description = "邮箱(模糊查询)") 
        @RequestParam(required = false) String email,
        
        @Parameter(description = "用户角色(ADMIN/USER/EDITOR)") 
        @RequestParam(required = false) String role,
        
        @Parameter(description = "用户状态(true为活跃,false为禁用)") 
        @RequestParam(required = false) Boolean isActive
    ) {
        try {
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            Page<User> users = userService.searchUsers(companyId, username, email, role, isActive, pageable);
            return Result.success("查询成功", users);
        } catch (Exception e) {
            log.error("分页查询用户列表失败", e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "获取所有用户(简化版)", 
        description = "获取所有用户的基本信息,用于下拉选择等场景"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping
    public Result<List<User>> getAllUsers() {
        try {
            List<User> users = userService.getAllUsers();
            return Result.success("查询成功", users);
        } catch (Exception e) {
            log.error("获取所有用户失败", e);
            return Result.error("查询失败");
        }
    }
    
    @Operation(
        summary = "根据ID查询用户详情", 
        description = "通过用户ID获取用户的详细信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/{id}")
    public Result<User> getUserById(
        @Parameter(description = "用户ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            User user = userService.getUserById(id);
            return Result.success("查询成功", user);
        } catch (BusinessException e) {
            log.warn("根据ID查询用户失败, id: {}, error: {}", id, e.getMessage());
            return Result.error(ResultCode.getByCode(e.getResultCode()));


        } catch (Exception e) {
            log.error("根据ID查询用户详情失败, id: {}", id, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据公司ID查询用户列表", 
        description = "获取指定公司下的所有用户"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "公司不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/company/{companyId}")
    public Result<List<User>> getUsersByCompanyId(
        @Parameter(description = "公司ID", required = true, example = "1") 
        @PathVariable @NotNull Integer companyId
    ) {
        try {
            List<User> users = userService.getUsersByCompanyId(companyId);
            return Result.success("查询成功", users);
        } catch (Exception e) {
            log.error("根据公司ID查询用户列表失败, companyId: {}", companyId, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据用户名查询用户", 
        description = "通过用户名获取用户信息,用于登录验证等场景"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/username/{username}")
    public Result<User> getUserByUsername(
        @Parameter(description = "用户名", required = true, example = "admin") 
        @PathVariable @NotNull String username
    ) {
        try {
            User user = userService.getUserByUsername(username);
            return Result.success("查询成功", user);
        } catch (BusinessException e) {
            log.warn("根据用户名查询用户失败, username: {}, error: {}", username, e.getMessage());
            return Result.error(ResultCode.getByCode(e.getResultCode()));

        } catch (Exception e) {
            log.error("根据用户名查询用户失败, username: {}", username, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "根据邮箱查询用户", 
        description = "通过邮箱获取用户信息,用于找回密码等场景"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/email/{email}")
    public Result<User> getUserByEmail(
        @Parameter(description = "用户邮箱", required = true, example = "admin@aigeo.com") 
        @PathVariable @NotNull String email
    ) {
        try {
            User user = userService.getUserByEmail(email);
            return Result.success("查询成功", user);
        } catch (BusinessException e) {
            log.warn("根据邮箱查询用户失败, email: {}, error: {}", email, e.getMessage());
            return Result.error(ResultCode.getByCode(e.getResultCode()));

        } catch (Exception e) {
            log.error("根据邮箱查询用户失败, email: {}", email, e);
            return Result.error("查询失败");
        }
    }

    @Operation(
        summary = "查询活跃用户列表", 
        description = "获取所有状态为活跃的用户列表"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "查询成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/active")
    public Result<List<User>> getActiveUsers(
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId
    ) {
        try {
            List<User> users = userService.getActiveUsers(companyId);
            return Result.success("查询成功", users);
        } catch (Exception e) {
            log.error("查询活跃用户列表失败", e);
            return Result.error("查询失败");
        }
    }
    
    @Operation(
        summary = "创建新用户", 
        description = "创建一个新的用户记录,包含基本信息和权限配置"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "创建成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "409", description = "用户名或邮箱已存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping
    public Result<User> createUser(
        @Parameter(description = "用户信息", required = true) 
        @Valid @RequestBody User user
    ) {
        try {
            // 检查用户名是否已存在
            if (userService.existsByUsername(user.getUsername())) {
                return Result.error(ResultCode.USERNAME_EXISTS);
            }
            
            // 检查邮箱是否已存在
            if (userService.existsByEmail(user.getEmail())) {
                return Result.error(ResultCode.EMAIL_EXISTS);
            }
            
            User savedUser = userService.saveUser(user);
            log.info("成功创建用户: {}", savedUser.getUsername());
            return Result.success("创建成功", savedUser);
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return Result.error("创建失败");
        }
    }
    
    @Operation(
        summary = "更新用户信息", 
        description = "根据ID更新用户的详细信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "409", description = "用户名或邮箱冲突"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PutMapping("/{id}")
    public Result<User> updateUser(
        @Parameter(description = "用户ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id,
        
        @Parameter(description = "更新的用户信息", required = true) 
        @Valid @RequestBody User userDetails
    ) {
        try {
            User existingUser = userService.getUserById(id);
            
            // 检查用户名冲突(排除当前用户)
            if (!existingUser.getUsername().equals(userDetails.getUsername()) 
                && userService.existsByUsername(userDetails.getUsername())) {
                return Result.error(ResultCode.USERNAME_EXISTS);
            }
            
            // 检查邮箱冲突(排除当前用户)
            if (!existingUser.getEmail().equals(userDetails.getEmail()) 
                && userService.existsByEmail(userDetails.getEmail())) {
                return Result.error(ResultCode.EMAIL_EXISTS);
            }
            
            // 更新字段
            existingUser.setUsername(userDetails.getUsername());
            existingUser.setEmail(userDetails.getEmail());
            existingUser.setFullName(userDetails.getFullName());
            existingUser.setRole(userDetails.getRole());
            existingUser.setIsActive(userDetails.getIsActive());
            
            User savedUser = userService.saveUser(existingUser);
            log.info("成功更新用户: {}", savedUser.getUsername());
            return Result.success("更新成功", savedUser);
        } catch (Exception e) {
            log.error("更新用户失败, id: {}", id, e);
            return Result.error("更新失败");
        }
    }

    @Operation(
        summary = "批量更新用户状态", 
        description = "批量更新多个用户的激活状态"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "更新成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PutMapping("/batch-status")
    public Result<String> batchUpdateStatus(
        @Parameter(description = "用户ID列表", required = true) 
        @RequestParam @NotNull List<Integer> ids,
        
        @Parameter(description = "新状态(true为激活,false为禁用)", required = true) 
        @RequestParam @NotNull Boolean isActive
    ) {
        try {
            int updatedCount = userService.batchUpdateStatus(ids, isActive);
            log.info("批量更新用户状态成功,更新数量: {}", updatedCount);
            return Result.success(String.format("成功更新 %d 个用户状态", updatedCount));
        } catch (Exception e) {
            log.error("批量更新用户状态失败", e);
            return Result.error("批量更新失败");
        }
    }

    @Operation(
        summary = "重置用户密码", 
        description = "管理员重置用户密码,生成临时密码"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "重置成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @PostMapping("/{id}/reset-password")
    public Result<String> resetPassword(
        @Parameter(description = "用户ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!userService.existsById(id)) {
                return Result.error(ResultCode.USER_NOT_FOUND);
            }
            
            String tempPassword = userService.resetPassword(id);
            log.info("成功重置用户密码, id: {}", id);
            return Result.success("密码重置成功,临时密码已生成", tempPassword);
        } catch (Exception e) {
            log.error("重置用户密码失败, id: {}", id, e);
            return Result.error("密码重置失败");
        }
    }
    
    @Operation(
        summary = "删除用户", 
        description = "根据ID删除用户记录(软删除)"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "删除成功"),
        @ApiResponse(responseCode = "404", description = "用户不存在"),
        @ApiResponse(responseCode = "409", description = "用户有关联数据,无法删除"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(
        @Parameter(description = "用户ID", required = true, example = "1") 
        @PathVariable @NotNull Integer id
    ) {
        try {
            if (!userService.existsById(id)) {
                return Result.error(ResultCode.USER_NOT_FOUND);
            }
            
            // 检查是否有关联数据
            if (userService.hasAssociatedData(id)) {
                return Result.error(ResultCode.CONFLICT, "用户有关联数据,无法删除");
            }
            
            userService.deleteUser(id);
            log.info("成功删除用户, id: {}", id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除用户失败, id: {}", id, e);
            return Result.error("删除失败");
        }
    }

    @Operation(
        summary = "搜索用户", 
        description = "根据关键词搜索用户名、邮箱或全名"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "搜索成功"),
        @ApiResponse(responseCode = "400", description = "请求参数错误"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/search")
    public Result<List<User>> searchUsers(
        @Parameter(description = "搜索关键词", required = true, example = "admin") 
        @RequestParam @NotNull String keyword,
        
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId,
        
        @Parameter(description = "最大返回数量", example = "20") 
        @RequestParam(defaultValue = "20") int limit
    ) {
        try {
            List<User> users = userService.searchByKeyword(keyword, companyId, limit);
            return Result.success("搜索成功", users);
        } catch (Exception e) {
            log.error("搜索用户失败, keyword: {}", keyword, e);
            return Result.error("搜索失败");
        }
    }

    @Operation(
        summary = "统计用户数据", 
        description = "获取用户相关的统计信息"
    )
    @ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "统计成功"),
        @ApiResponse(responseCode = "500", description = "服务器内部错误")
    })
    @GetMapping("/statistics")
    public Result<UserStatistics> getUserStatistics(
        @Parameter(description = "公司ID(可选)") 
        @RequestParam(required = false) Integer companyId
    ) {
        try {
            UserStatistics statistics = userService.getUserStatistics(companyId);
            return Result.success("统计成功", statistics);
        } catch (Exception e) {
            log.error("获取用户统计信息失败", e);
            return Result.error("统计失败");
        }
    }

    /**
     * 用户统计信息DTO
     */
    public static class UserStatistics {
        private long totalUsers;
        private long activeUsers;
        private long inactiveUsers;
        private long adminUsers;
        private long regularUsers;
        
        // constructors, getters and setters
        public UserStatistics(long totalUsers, long activeUsers, long inactiveUsers, 
                            long adminUsers, long regularUsers) {
            this.totalUsers = totalUsers;
            this.activeUsers = activeUsers;
            this.inactiveUsers = inactiveUsers;
            this.adminUsers = adminUsers;
            this.regularUsers = regularUsers;
        }
        
        // getters and setters
        public long getTotalUsers() { return totalUsers; }
        public void setTotalUsers(long totalUsers) { this.totalUsers = totalUsers; }
        
        public long getActiveUsers() { return activeUsers; }
        public void setActiveUsers(long activeUsers) { this.activeUsers = activeUsers; }
        
        public long getInactiveUsers() { return inactiveUsers; }
        public void setInactiveUsers(long inactiveUsers) { this.inactiveUsers = inactiveUsers; }
        
        public long getAdminUsers() { return adminUsers; }
        public void setAdminUsers(long adminUsers) { this.adminUsers = adminUsers; }
        
        public long getRegularUsers() { return regularUsers; }
        public void setRegularUsers(long regularUsers) { this.regularUsers = regularUsers; }
    }
}