SysDeptController.java 11.8 KB
package com.bs.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bs.common.annotation.Log;
import com.bs.common.constant.Constants;
import com.bs.common.constant.UserConstants;
import com.bs.common.context.SecurityContextHolder;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.domain.entity.SysDept;
import com.bs.common.core.domain.entity.SysUser;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.SecurityUtils;
import com.bs.common.utils.StringUtils;
import com.bs.web.mapper.SysUserMapper;
import com.bs.web.service.ISysDeptService;
import com.bs.web.domain.vo.DeptCreateReq;
import com.bs.web.domain.vo.DeptSortReq;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import com.bs.common.utils.SnowFlakeUtil;

/**
 * 部门信息
 *
 * @author system
 */
@RestController
@RequestMapping("/system/dept")
@Tag(name = "组织管理")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    @Resource
    private SysUserMapper userMapper;

    @Value("${system.dept.excludeIds:}")
    private String deptExcludeIds;

    /**
     * 获取部门列表
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    @Operation(summary = "部门列表")
    public AjaxResult list(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        if (StringUtils.isNotEmpty(deptExcludeIds)) {
            Set<Long> exclude = Arrays.stream(deptExcludeIds.split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotEmpty)
                    .map(Long::valueOf)
                    .collect(Collectors.toSet());
            depts = depts.stream()
                    .filter(d -> d.getDeptId() == null || !exclude.contains(d.getDeptId()))
                    .collect(Collectors.toList());
        }
        return AjaxResult.success(depts);
    }


    /**
     * 根据部门id批量获取部门
     *
     * @param deptIds
     * @return
     */
    @GetMapping("/findSysDeptByIds")
    @Operation(summary = "根据部门id批量获取部门")
    public AjaxResult<List<SysDept>> findSysDeptByIds(@RequestParam(value = "deptIds") String deptIds) {


        return AjaxResult.success(
                deptService.findSysDeptByIds(
                        Arrays.asList(deptIds.split(","))
                )
        );
    }

    /**
     * 查询部门列表(排除节点)
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    @Operation(summary = "部门列表(排除节点)")
    public AjaxResult excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        Iterator<SysDept> it = depts.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","),
                    deptId + "")) {
                it.remove();
            }
        }
        return AjaxResult.success(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    @Operation(summary = "根据部门编号获取详细信息")
    public AjaxResult getInfo(@PathVariable Long deptId) {
        return AjaxResult.success(deptService.selectDeptById(deptId));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    @Operation(summary = "获取部门下拉树列表")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 根据当前登录用户获取对应角色菜单树
     *
     * @return
     */
    @GetMapping("/roleDeptTreeselect")
    @Operation(summary = "获取部门下拉树列表")
    public AjaxResult roleDeptTreeselect() {
        SysUser user = userMapper.selectUserById(SecurityContextHolder.getUserId());
        List<SysDept> depts = deptService.selectUserDeptList(user.getOpenUserid());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    @Operation(summary = "加载对应角色部门列表树")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Operation(summary = "新增部门")
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getUserName());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @Operation(summary = "修改部门")
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败,上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.error("该部门包含未停用的子部门!");
        }
        dept.setUpdateBy(SecurityUtils.getUserName());
        dept.setUpdateById(SecurityContextHolder.getUserId());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove/{deptId}")
    @Operation(summary = "删除部门")
    public AjaxResult remove(@PathVariable Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.error("部门存在用户,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 部门排序
     * 入参:父部门ID + 部门ID有序列表
     * 逻辑:
     * 1. 校验父部门是否存在,不存在则返回错误
     * 2. 按传入顺序从1开始递增设置排序字段order_num
     * 3. 更新对应部门的排序字段
     */
    @PostMapping("/sort")
    @Operation(summary = "部门排序")
    public AjaxResult sort(@RequestBody DeptSortReq req) {
        if (req.getParentId() == null) {
            return AjaxResult.error("父部门ID不能为空");
        }
        SysDept parent = deptService.selectDeptById(req.getParentId());
        if (parent == null) {
            return AjaxResult.error("父部门不存在");
        }
        if (req.getDeptIds() == null || req.getDeptIds().isEmpty()) {
            return AjaxResult.error("部门ID列表不能为空");
        }
        long order = 1L;
        for (Long id : req.getDeptIds()) {
            SysDept child = deptService.selectDeptById(id);
            if (child == null) {
                return AjaxResult.error("部门不存在: " + id);
            }
            if (!req.getParentId().equals(child.getParentId())) {
                return AjaxResult.error("部门不属于指定父部门: " + id);
            }
            SysDept toUpdate = new SysDept();
            toUpdate.setDeptId(id);
            toUpdate.setOrderNum(order++);
            toUpdate.setUpdateBy(SecurityUtils.getUserName());
            toUpdate.setUpdateById(SecurityContextHolder.getUserId());
            deptService.updateDept(toUpdate);
        }
        return AjaxResult.success();
    }

    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping("/external/create")
    @Operation(summary = "对外创建部门")
    public AjaxResult<Long> externalCreate(@RequestBody DeptCreateReq req) {
        /**
         * 外部创建部门:
         * - 生成部门ID(当前表最大ID + 1)
         * - 校验同父级下部门名称唯一
         * - 写入创建人信息
         * - 调用服务层 insertDept,服务层负责 ancestors 构建与父节点状态校验
         * 返回:成功时返回新部门ID
         */
        SysDept dept = new SysDept();
        SysDept maxDept = deptService.getOne(Wrappers.lambdaQuery(SysDept.class)
                .select(SysDept::getDeptId)
                .orderByDesc(SysDept::getDeptId)
                .last("limit 1"));
        Long nextId = (maxDept != null && maxDept.getDeptId() != null) ? maxDept.getDeptId() + 1 : 1L;
        dept.setDeptId(nextId);
        dept.setParentId(req.getParentId());
        dept.setDeptName(req.getDeptName());
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("部门名称已存在");
        }
        dept.setOrderNum(1L);// 设置部门排序号为1,
        dept.setCreateBy(SecurityUtils.getUserName());
        dept.setCreateById(SecurityContextHolder.getUserId());
        dept.setUpdateBy(SecurityUtils.getUserName());
        dept.setUpdateById(SecurityContextHolder.getUserId());
        int rows = deptService.insertDept(dept);
        if (rows > 0) {
            return AjaxResult.success(dept.getDeptId());
        }
        return AjaxResult.error("部门创建失败");
    }

    /**
     * 获取部门列表,不做数据权限校验
     *
     * @param
     * @return {@link AjaxResult}
     * @author WangYX
     * @date 2023/07/17 9:59
     */
    @PostMapping("/list/without/permission")
    @Operation(summary = "企业企微部门列表-不做数据权限校验")
    public AjaxResult getListWithOutPermission(@RequestBody SysDept dept) {
        LambdaQueryWrapper<SysDept> queryWrapper = Wrappers.lambdaQuery(SysDept.class);
        queryWrapper.eq(SysDept::getDelFlag, Constants.COMMON_STATE);
        //查询条件扩展
        queryWrapper.eq(dept.getDeptId() != null, SysDept::getDeptId, dept.getDeptId());
        List<SysDept> list = deptService.list(queryWrapper);
        return AjaxResult.success(list);
    }


}