Просмотр исходного кода

1.向中台拉取组织用户数据(已单元测试)
2.中台单点登录(未测试,需要中台提供code)

zzw 1 месяц назад
Родитель
Сommit
4e56f33dd9

+ 7 - 0
assistMg/pom.xml

@@ -34,6 +34,13 @@
             <version>${parent.version}</version>
         </dependency>
 
+        <!--中台对接数据初始化依赖-->
+        <dependency>
+            <groupId>com.integration</groupId>
+            <artifactId>oauth2-sdk</artifactId>
+            <version>1.0</version>
+        </dependency>
+
         <!-- 依赖 uc 模块获取用户信息 -->
         <dependency>
             <groupId>com.hotent</groupId>

+ 99 - 0
assistMg/src/main/java/com/hotent/dataMiddlePlatform/controller/DataMiddlePlatformController.java

@@ -0,0 +1,99 @@
+package com.hotent.dataMiddlePlatform.controller;
+
+import com.alibaba.fastjson.JSON;
+import com.hotent.base.annotation.ApiGroup;
+import com.hotent.base.constants.ApiGroupConsts;
+import com.hotent.base.model.CommonResult;
+import com.hotent.baseInfo.resp.AuditedUnitDetailResp;
+import com.hotent.dataMiddlePlatform.manager.DataMiddlePlatformManager;
+import com.hotent.uc.params.org.OrgVo;
+import com.integration.oauth2.sdk.OAuth2Client;
+import com.integration.oauth2.sdk.method.OAuth2ToMethod;
+import com.integration.oauth2.sdk.model.Org;
+import com.integration.oauth2.sdk.model.UserDetail;
+import com.integration.oauth2.sdk.model.UserInfo;
+import com.integration.oauth2.sdk.response.AccessTokenResponse;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ *@author: zhao yue yue
+ *@create: 2025-11-06 11:35
+ */
+@Api(tags = "中台组织用户数据同步")
+@RestController
+@RequestMapping("/api/data-middle-platform")
+public class DataMiddlePlatformController {
+
+    @Autowired
+    private DataMiddlePlatformManager dataMiddlePlatformManager;
+
+
+
+    @GetMapping("/sync")
+    @ApiOperation(value = "同步中台数据", notes = "初始化同步中台数据")
+    public CommonResult<String> sync() {
+        try {
+            dataMiddlePlatformManager.sync();
+            return CommonResult.<String>ok().message("同步成功");
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+
+    @GetMapping("/sso/dmp")
+    @ApiOperation(value = "中台系统单点登录", notes = "中台系统单点登录")
+    public ResponseEntity<?> ssoDataMiddlePlatform(
+            @ApiParam(name="code",value="随机码", required = true)
+            @RequestParam (value="code",required=true) String code) {
+        try {
+            return dataMiddlePlatformManager.ssoDataMiddlePlatform(code);
+            //dataMiddlePlatformManager.sync();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static void main(String[] args) {
+        OAuth2Client oAuth2Client = OAuth2ToMethod.OAuth2Method.initClient( "http://10.7.14.236:8280/stage-api/",
+                "cbjsxt",
+                "cbjsxt",
+                "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnhQ99yP-eEU2jXdQWc6j-wWbqNLqOLinEGBY11WJUCmzHiEycDXPc6-3YMOvrdAiHZcjkMCzU_eRnBLUqkcNw9nhQrCak-sTpEVlAV21LskD6KMf-6PsfttUvpXeCO5g3Hg48F_vbLKxb8s_lcvQgCpKBIpsUdYRcp_PgSg8BQIDAQAB"
+                , 30);
+        System.err.println("初始化参数:"+JSON.toJSON(oAuth2Client));
+        //AccessTokenResponse accessTokenWithCode = OAuth2ToMethod.getAccessTokenWithCode("前端传入", "序号1的地址");
+        //System.err.println("免登录:"+JSON.toJSON(accessTokenWithCode));
+        //String accessToken = accessTokenWithCode.getValue().getAccess_token();
+        //UserInfo userInfo = OAuth2ToMethod.getUserInfo(accessToken);
+        //System.err.println("用户信息:"+JSON.toJSON(userInfo));
+        String openApiToken = OAuth2ToMethod.getOpenApiToken("");
+        //System.err.println(openApiToken);
+        List<Org> orgsAll = OAuth2ToMethod.getOrgsAll(openApiToken, "");
+        List<UserDetail> usersAll = OAuth2ToMethod.getUsersAll(openApiToken, "1", "10");
+        List<OrgVo> orgVoList = orgsAll.stream().map(o -> {
+            OrgVo orgVo = new OrgVo();
+                /*orgVo.setId(o.getId());
+                orgVo.setCode(o.getCode());
+                orgVo.setName(o.getName());
+                orgVo.setDemId(o.getDemId());
+                orgVo.setParentId(o.getParentId());*/
+            BeanUtils.copyProperties(orgVo,o);
+            return orgVo;
+        }).collect(Collectors.toList());
+    System.out.println(JSON.toJSON(orgVoList));
+    }
+
+
+}

+ 18 - 0
assistMg/src/main/java/com/hotent/dataMiddlePlatform/manager/DataMiddlePlatformManager.java

@@ -0,0 +1,18 @@
+package com.hotent.dataMiddlePlatform.manager;/**
+ * @program: cbjs-mvue-master
+ * @description:
+ * @author: zhao yue yue
+ * @create: 2025-11-06 11:36
+ */
+
+import org.springframework.http.ResponseEntity;
+
+/**
+ *@author: zhao yue yue
+ *@create: 2025-11-06 11:36
+ */
+public interface DataMiddlePlatformManager {
+    void sync() throws Exception;
+
+    ResponseEntity<?> ssoDataMiddlePlatform(String code) throws Exception;
+}

+ 208 - 0
assistMg/src/main/java/com/hotent/dataMiddlePlatform/manager/impl/DataMiddlePlatformManagerImpl.java

@@ -0,0 +1,208 @@
+package com.hotent.dataMiddlePlatform.manager.impl;
+
+import com.alibaba.fastjson.JSON;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.hotent.base.conf.JwtConfig;
+import com.hotent.base.conf.SaaSConfig;
+import com.hotent.base.conf.SsoConfig;
+import com.hotent.base.feign.UCFeignService;
+import com.hotent.base.jwt.JwtAuthenticationResponse;
+import com.hotent.base.jwt.JwtTokenHandler;
+import com.hotent.base.service.PwdStrategyService;
+import com.hotent.base.util.*;
+import com.hotent.baseInfo.manager.AuditedUnitManager;
+import com.hotent.dataMiddlePlatform.manager.DataMiddlePlatformManager;
+import com.hotent.uc.api.model.IUser;
+import com.hotent.uc.manager.OrgManager;
+import com.hotent.uc.manager.UserManager;
+import com.hotent.uc.model.User;
+import com.hotent.uc.params.org.OrgVo;
+import com.hotent.uc.params.user.UserVo;
+import com.integration.oauth2.sdk.OAuth2Client;
+import com.integration.oauth2.sdk.method.OAuth2ToMethod;
+import com.integration.oauth2.sdk.model.Org;
+import com.integration.oauth2.sdk.model.UserDetail;
+import com.integration.oauth2.sdk.model.UserInfo;
+import com.integration.oauth2.sdk.response.AccessTokenResponse;
+import oracle.net.ano.AuthenticationService;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.security.core.userdetails.UserDetailsService;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import javax.servlet.http.HttpServletRequest;
+import java.time.LocalDateTime;
+import java.util.*;
+import java.util.stream.Collectors;
+
+/**
+ *@author: zhao yue yue
+ *@create: 2025-11-06 11:37
+ */
+@Service
+public class DataMiddlePlatformManagerImpl implements DataMiddlePlatformManager {
+
+
+    private static final String baseUrl = "http://10.7.14.236:8280/stage-api/";
+    private static final String clientId = "cbjsxt";
+    private static final String clientSecret = "cbjsxt";
+    private static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCMnhQ99yP-eEU2jXdQWc6j-wWbqNLqOLinEGBY11WJUCmzHiEycDXPc6-3YMOvrdAiHZcjkMCzU_eRnBLUqkcNw9nhQrCak-sTpEVlAV21LskD6KMf-6PsfttUvpXeCO5g3Hg48F_vbLKxb8s_lcvQgCpKBIpsUdYRcp_PgSg8BQIDAQAB";
+   /* private static final String code="前端传入";
+    private static final String redirectUri="序号1的地址";*/
+
+    @Autowired
+    private OrgManager orgManager;
+
+    @Autowired
+    private UserManager userService;
+
+    @Autowired
+    JwtTokenHandler jwtTokenHandler;
+
+    @Resource
+    UserDetailsService userDetailsService;
+
+    @Autowired
+    JwtConfig jwtConfig;
+
+    @Autowired
+    SaaSConfig saasConfig;
+
+    @Autowired
+    UCFeignService uCFeignService;
+
+    @Override
+    public void sync() throws Exception {
+        try {
+            OAuth2Client oAuth2Client = OAuth2ToMethod.OAuth2Method.initClient( baseUrl,
+                    clientId,
+                    clientSecret,
+                    publicKey
+                    , 30);
+            System.err.println("oAuth2Client:"+ JSON.toJSONString(oAuth2Client));
+            String openApiToken = OAuth2ToMethod.getOpenApiToken("");
+            System.err.println("openApiToken:"+ JSON.toJSONString(openApiToken));
+            //1.拉去中台组织数据,2.组装组织数据,3.并批量添加
+            List<Org> orgsAll = OAuth2ToMethod.getOrgsAll(openApiToken, "");
+            List<OrgVo> orgVoList = orgsAll.stream().map(o -> {
+                OrgVo orgVo = new OrgVo();
+                /*orgVo.setId(o.getId());
+                orgVo.setCode(o.getCode());
+                orgVo.setName(o.getName());
+                orgVo.setDemId(o.getDemId());
+                orgVo.setParentId(o.getParentId());*/
+                BeanUtils.copyProperties(o,orgVo);
+                return orgVo;
+            }).collect(Collectors.toList());
+            orgManager.addOrgs(orgVoList);
+            //1.拉取中台用户数据,2.组装用户数据,3.批量添加
+            int j=1;
+            List<UserDetail> usersAll =new ArrayList<>();
+            for (int i = 1; i==j ; i++) {
+                usersAll = OAuth2ToMethod.getUsersAll(openApiToken, Integer.toString(i), "100");
+                List<UserVo> userVos = usersAll.stream().map(u -> {
+                    UserVo userVo = new UserVo();
+                    BeanUtils.copyProperties(u,userVo);
+                    return userVo;
+                }).collect(Collectors.toList());
+                userService.addUsers(userVos);
+                if (usersAll.size()==100) {
+                    j++;
+                }
+            }
+
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public ResponseEntity<?> ssoDataMiddlePlatform(String code) throws Exception {
+        OAuth2Client oAuth2Client = OAuth2ToMethod.OAuth2Method.initClient( baseUrl,
+                clientId,
+                clientSecret,
+                publicKey
+                , 30);
+        AccessTokenResponse accessTokenWithCode = OAuth2ToMethod.getAccessTokenWithCode(code, "");
+        System.err.println("免登录:"+JSON.toJSON(accessTokenWithCode));
+        String accessToken = accessTokenWithCode.getValue().getAccess_token();
+        UserInfo userInfo = OAuth2ToMethod.getUserInfo(accessToken);
+        System.err.println("用户信息:"+JSON.toJSON(userInfo));
+
+        // 当前切中的方法
+        HttpServletRequest request = HttpUtil.getRequest();
+        boolean isMobile = HttpUtil.isMobile(request);
+        final UserDetails userDetails = userDetailsService.loadUserByUsername(userInfo.getName());
+        final String token = jwtTokenHandler.generateToken(userDetails);
+        String userName = userDetails.getUsername();
+        String account = "";
+        String userId = "";
+        Map<String, Object> userAttrs = new HashMap<String, Object>();
+        if (userDetails instanceof IUser) {
+            IUser user = ((IUser) userDetails);
+            userName = user.getFullname();
+            account = user.getAccount();
+            userId = user.getUserId();
+            request.setAttribute("loginUser", String.format("%s[%s]", userName, account));
+            userAttrs.put("tenantId", user.getTenantId());
+        }
+        //获取超时时间
+        //logger.debug("通过单点认证登录成功。");
+        //处理单用户登录
+        //if (!(code.isPresent() && SsoConfig.MODE_JWT.equals(mode))) {
+            handleSingleLogin(isMobile, MapUtil.getString(userAttrs, "tenantId"), account, token);
+        //}
+        // Return the token
+        return ResponseEntity.ok(new JwtAuthenticationResponse(token, userName, account, userId, jwtConfig.getExpirationLong(), userAttrs));
+
+       /* User user = userService.getByAccount(userInfo.getName());
+        CacheEvictUtil.deleteUserDetailsCache(user.getAccount());*/
+
+
+
+        //return null;
+    }
+
+
+    /**
+     * 处理单用户登录
+     *
+     * @param isMobile
+     * @param username
+     * @param token
+     */
+    private Map<String,Object> handleSingleLogin(boolean isMobile, String tenantId, String username, String token) {
+        Map<String,Object> result=new HashMap<>();
+        //如果是单用户登录
+        if (jwtConfig.isSingle()) {
+            String userAgent = isMobile ? "mobile" : "pc";
+            // 非SaaS模式
+            if (StringUtil.isEmpty(tenantId) && !saasConfig.isEnable()) {
+                tenantId = "-1";
+            }
+            UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
+            // 从缓存中获取token
+            String oldToken = jwtTokenHandler.getTokenFromCache(userAgent, tenantId, username, jwtConfig.getExpiration());
+            if(StringUtil.isNotEmpty(oldToken)) {
+                if(jwtTokenHandler.validateToken(oldToken, userDetails) && !oldToken.equals(token)){
+//                    throw new BaseException(ResponseErrorEnums.KICK_OFF_BY_ANOTHER);
+                    System.out.println(username+":"+userAgent+"端重复登录了");
+                    result.put("flag",true);
+                    result.put("msg","当前账号已在另一地方登录,若不是本人操作,请注意账号安全");
+                }
+            }else{
+                result.put("flag",false);
+                result.put("msg","无多处登录");
+            }
+            // 以当前登录设备、租户ID、用户账号为key将token存放到缓存中
+            jwtTokenHandler.putTokenInCache(userAgent, tenantId, username, jwtConfig.getExpiration(), token);
+        }
+        //处理用户登录日志
+        uCFeignService.loginLog(username, isMobile ? "mobile" : "pc");
+        return result;
+    }
+
+}

+ 47 - 0
assistMg/src/main/java/com/hotent/enterpriseDeclare/controller/CostAuditTaskController.java

@@ -32,6 +32,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
 import java.util.List;
+import java.util.stream.Collectors;
 
 @Api(tags = "成本监审任务填报")
 @RestController
@@ -81,4 +82,50 @@ public class CostAuditTaskController {
     public CommonResult<String> yjsave(@RequestBody CostProjectTaskPreliminaryOpinion costProjectTaskPreliminaryOpinion) throws Exception{
         return CommonResult.<String>ok().value(costProjectTaskManager.saveYjTask(costProjectTaskPreliminaryOpinion));
     }
+
+    /**
+     * 获取子任务的所有监审单位
+     * @param taskId 主任务ID
+     * @return 监审单位列表
+     */
+    @GetMapping(value = "/getChildTaskUnits")
+    @ApiOperation(value = "获取子任务的所有监审单位", httpMethod = "GET", notes = "根据主任务ID查询所有子任务,获取子任务的监审单位字段,然后查询单位表返回所有单位")
+    public CommonResult<List<AuditedUnit>> getChildTaskUnits(
+            @ApiParam(name = "taskId", value = "主任务ID", required = true)
+            @RequestParam(required = true) String taskId) {
+        
+        // 1. 查询该主任务下的所有子任务(pid等于主任务ID)
+        LambdaQueryWrapper<CostProjectTask> taskQueryWrapper = new LambdaQueryWrapper<>();
+        taskQueryWrapper.eq(CostProjectTask::getPid, taskId)
+                .eq(CostProjectTask::getIsDeleted, "0")
+                .isNotNull(CostProjectTask::getAuditedUnitId)
+                .ne(CostProjectTask::getAuditedUnitId, "");
+        
+        List<CostProjectTask> childTasks = costProjectTaskManager.list(taskQueryWrapper);
+        
+        // 如果没有子任务,返回空列表
+        if (childTasks == null || childTasks.isEmpty()) {
+            return CommonResult.<List<AuditedUnit>>ok().value(java.util.Collections.emptyList());
+        }
+        
+        // 2. 提取所有不重复的监审单位ID
+        List<String> auditedUnitIds = childTasks.stream()
+                .map(CostProjectTask::getAuditedUnitId)
+                .filter(StringUtil::isNotEmpty)
+                .distinct()
+                .collect(Collectors.toList());
+        
+        if (auditedUnitIds.isEmpty()) {
+            return CommonResult.<List<AuditedUnit>>ok().value(java.util.Collections.emptyList());
+        }
+        
+        // 3. 根据单位ID列表查询单位表
+        LambdaQueryWrapper<AuditedUnit> unitQueryWrapper = new LambdaQueryWrapper<>();
+        unitQueryWrapper.in(AuditedUnit::getUnitId, auditedUnitIds)
+                .eq(AuditedUnit::getIsDeleted, "0");
+        
+        List<AuditedUnit> units = auditedUnitManager.list(unitQueryWrapper);
+        
+        return CommonResult.<List<AuditedUnit>>ok().value(units);
+    }
 }

+ 3 - 0
assistMg/src/main/java/com/hotent/enterpriseDeclare/req/CostTaskPageReq.java

@@ -24,4 +24,7 @@ public class CostTaskPageReq {
 
     @ApiModelProperty(value = "意见")
     private String content;
+
+    @ApiModelProperty(value = "子任务ID(集体审议节点补充材料时,指定具体单位对应的子任务)")
+    private String childTaskId;
 }

+ 42 - 11
assistMg/src/main/java/com/hotent/project/manager/impl/CostProjectTaskManagerImpl.java

@@ -437,19 +437,50 @@ public class CostProjectTaskManagerImpl extends BaseManagerImpl<CostProjectTaskD
      * 补充材料,发送通知+修改任务状态
      */
     private String supplementMaterial(CostProjectTask task, CostTaskPageReq req) {
-
-        // 更新任务状态为
-        task.setStatus(TaskStatusConstant.BCCL.getStatusCode());
-        costProjectTaskManager.updateById(task);
-
-        // 通知内容组装
-        String title = NodeConstant.getNodeValueByKey(task.getCurrentNode())+TaskStatusConstant.BCCL.getStatusName();
-        String enterpriseId = task.getAuditedUnitId() == null ? "" : task.getAuditedUnitId();
+        String currentNode = task.getCurrentNode();
+        String title = NodeConstant.getNodeValueByKey(currentNode) + TaskStatusConstant.BCCL.getStatusName();
         String noticeSource = "系统";
-        String sendTarget = task.getCreateBy() == null ? "" : task.getCreateBy();
-        costNoticeManager.sendNotice(task.getProjectId(), "1", title, req.getContent(), enterpriseId, noticeSource, sendTarget);
 
-        return title;
+        switch (currentNode) {
+            // 集体审议节点:支持指定多个子任务补充材料
+            case "jtsy":
+                if (StringUtil.isNotEmpty(req.getChildTaskId())) {
+                    String[] childTaskIdArray = req.getChildTaskId().split(",");
+                    List<String> unitNames = new java.util.ArrayList<>();
+
+                    for (String childTaskId : childTaskIdArray) {
+                        CostProjectTask childTask = costProjectTaskManager.getById(childTaskId);
+                        if (childTask == null) {
+                            throw new RuntimeException("子任务不存在:" + childTaskId);
+                        }
+                        // 验证子任务是否属于当前主任务
+                        if (!childTask.getPid().equals(task.getId())) {
+                            throw new RuntimeException("子任务不属于当前主任务:" + childTaskId);
+                        }
+                        // 更新子任务状态为补充材料
+                        childTask.setStatus(TaskStatusConstant.BCCL.getStatusCode());
+                        costProjectTaskManager.updateById(childTask);
+                        // 通知内容组装(针对子任务对应的单位)
+                        String childEnterpriseId = childTask.getAuditedUnitId() == null ? "" : childTask.getAuditedUnitId();
+                        String childSendTarget = childTask.getCreateBy() == null ? "" : childTask.getCreateBy();
+                        costNoticeManager.sendNotice(task.getProjectId(), "1", title, req.getContent(), childEnterpriseId, noticeSource, childSendTarget);
+                        // 收集单位名称
+                        if (StringUtil.isNotEmpty(childTask.getAuditedUnitName())) {
+                            unitNames.add(childTask.getAuditedUnitName());
+                        }
+                    }
+                    // 返回结果,包含所有单位名称
+                    String unitNamesStr = unitNames.isEmpty() ? "" : String.join("、", unitNames);
+                    return title + "(单位:" + unitNamesStr + ")";
+                }
+            default:
+                task.setStatus(TaskStatusConstant.BCCL.getStatusCode());
+                costProjectTaskManager.updateById(task);
+                String enterpriseId = task.getAuditedUnitId() == null ? "" : task.getAuditedUnitId();
+                String sendTarget = task.getCreateBy() == null ? "" : task.getCreateBy();
+                costNoticeManager.sendNotice(task.getProjectId(), "1", title, req.getContent(), enterpriseId, noticeSource, sendTarget);
+                return title;
+        }
     }
 
     /**

+ 1 - 0
base/src/main/java/com/hotent/base/conf/WebSecurityConfig.java

@@ -148,6 +148,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
 		.antMatchers(denyAlls).denyAll()
 		.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
 		.antMatchers("/auth/**").permitAll()
+		.antMatchers("/api/data-middle-platform/**").permitAll()
 		.antMatchers("/ueditor/**","/apiManager/getToken").permitAll()
 		.anyRequest().authenticated()
 		.accessDecisionManager(accessDecisionManager());

+ 11 - 1
uc/src/main/java/com/hotent/uc/manager/OrgManager.java

@@ -167,7 +167,17 @@ public interface OrgManager extends BaseManager<Org>{
 	 * @throws Exception
 	 */
 	CommonResult<String> addOrg(OrgVo orgVo) throws Exception;
-	
+
+
+	/**
+	 * 添加组织集合
+	 * @param orgVos
+	 * @return
+	 * @throws Exception
+	 */
+	CommonResult<String> addOrgs(List<OrgVo> orgVos) throws Exception;
+
+
 	/**
 	 * 根据组织代码删除组织
 	 * @param codes 组织编码

+ 7 - 0
uc/src/main/java/com/hotent/uc/manager/UserManager.java

@@ -56,6 +56,13 @@ public interface UserManager extends BaseManager<User>{
 	 * @return 
 	 */
 	User addUser(UserVo user) throws Exception ;
+
+	/**
+	 * 添加用户集合
+	 * @param users
+	 * @return
+	 */
+	CommonResult<String> addUsers(List<UserVo> users) throws Exception ;
 	
 	/**
 	 * 保存用户

+ 108 - 0
uc/src/main/java/com/hotent/uc/manager/impl/OrgManagerImpl.java

@@ -460,6 +460,114 @@ public class OrgManagerImpl extends BaseManagerImpl<OrgDao, Org> implements OrgM
 	}
 
 	@Override
+	//@Transactional
+	public CommonResult<String> addOrgs(List<OrgVo> orgVos) throws Exception {
+		//获取组织集合code,查询已存在的组织信息
+        try {
+            List<String> codes = orgVos.stream().map(o -> o.getCode()).distinct().collect(Collectors.toList());
+            List<Org> orgList = this.getOrgListByCodes(codes);
+
+            //List<Org> list = new ArrayList<>();
+            for (OrgVo orgVo: orgVos ){
+                Org or = orgList.stream().filter(org -> org.getCode().equals(orgVo.getCode())).findAny().orElse(null);
+                //当前组织信息若存在则不添加
+                if (or==null) {
+                    if (StringUtil.isEmpty(orgVo.getName())) {
+                        throw new BaseException("添加组织失败,组织名称【name】不能为空!");
+                    }
+                    if (StringUtil.isEmpty(orgVo.getCode())) {
+                        throw new BaseException("添加组织失败,组织编码【code】不能为空!");
+                    }
+                    if (orgVo.getCode().contains(",")) {
+                        throw new BaseException("组织编码中不能包含英文逗号‘,’");
+                    }
+                    if (StringUtil.isEmpty(orgVo.getDemId())) {
+                        throw new BaseException("添加组织失败,维度id【demId】不能为空!");
+                    }
+                    if (baseMapper.getCountByCode(orgVo.getCode())>0) {
+                        throw new BaseException("添加组织失败,组织编码[" + orgVo.getCode() + "]已存在!");
+                    }
+                    Demension dem = demensionService.get(orgVo.getDemId());
+                    if (BeanUtils.isEmpty(dem)) {
+                        throw new BaseException("添加组织失败,根据输入的demId[" + orgVo.getDemId() + "]没有找到对应的维度信息!");
+                    }
+                    Org pOrg = null;
+                    if (!"0".equals(orgVo.getParentId()) && StringUtil.isNotEmpty(orgVo.getParentId())) {
+                        pOrg = this.get(orgVo.getParentId());
+                        if (BeanUtils.isEmpty(pOrg)) {
+                            throw new BaseException("添加组织失败,根据输入的parentId[" + orgVo.getParentId() + "]没有找到对应的组织信息!");
+                        }
+                        if (BeanUtils.isEmpty(pOrg) && !pOrg.getDemId().equals(orgVo.getDemId())) {
+                            throw new BaseException("添加组织失败,根据输入demId与所输入的父组织所对应的维度id不一致!");
+                        }
+                    }
+                    String orgTypeStr = "";
+                    if(orgVo.getOrgType().equals(0) || orgVo.getOrgType().equals(2) || orgVo.getOrgType().equals(3)) {
+                        orgTypeStr = "0,2,3";
+                    }
+                    boolean sameNameFlag = false;
+                    try {
+                        sameNameFlag = this.queryExistsNameBySameLevel(orgVo.getId(), orgVo.getParentId(), orgVo.getName(), orgTypeStr);
+                    } catch (Exception e) {
+                        throw new RuntimeException(e);
+                    }
+                    if(sameNameFlag) {
+                        throw new RuntimeException("更新组织失败,在本层已经包含相同的组织名称,组织名称【" + orgVo.getName() + "】!");
+                    }
+                    Org o = new Org();
+                    if(orgVo.getId()!=null){
+                        o.setId(orgVo.getId());
+                    }else{
+                        o.setId(UniqueIdUtil.getSuid());
+                    }
+                    o.setCode(orgVo.getCode());
+                    o.setName(orgVo.getName());
+                    o.setDemId(orgVo.getDemId());
+                    o.setJoinExtSystemType(orgVo.getJoinExtSystemType());
+                    if(!StringUtils.isEmpty(orgVo.getJoinExtSystemSyndir())){
+                        o.setJoinExtSystemSyndir(orgVo.getJoinExtSystemSyndir());
+                    }
+                    if (StringUtils.isEmpty(orgVo.getParentId())) {
+                        o.setParentId("0");
+                    } else {
+                        o.setParentId(orgVo.getParentId());
+                    }
+                    if (StringUtil.isNotEmpty(orgVo.getGrade())) {
+                        o.setGrade(orgVo.getGrade());
+                    }
+                    if (BeanUtils.isNotEmpty(orgVo.getOrderNo())) {
+                        o.setOrderNo(orgVo.getOrderNo());
+                    }
+                    if (BeanUtils.isEmpty(pOrg)) {
+                        o.setPathName("/" + orgVo.getName());
+                        o.setPath(orgVo.getDemId() + "." + o.getId() + ".");
+                    } else {
+                        o.setPath(pOrg.getPath() + o.getId() + ".");
+                        o.setPathName(pOrg.getPathName() + "/" + orgVo.getName());
+                    }
+                    o.setLimitNum(orgVo.getLimitNum().intValue());
+                    o.setExceedLimitNum(orgVo.getExceedLimitNum().intValue());
+                    o.setOrgType(orgVo.getOrgType());
+                    //查询上级组织类型
+                    Org parentOrg = getById(orgVo.getParentId());
+                    if(parentOrg!=null) {
+                        if(Org.ORG_TYPE_DEP.equals(parentOrg.getOrgType())) {
+                            o.setSuperiorOrgId(parentOrg.getSuperiorOrgId());
+                            o.setSuperiorDepId(orgVo.getParentId());
+                        } else {
+                            o.setSuperiorOrgId(orgVo.getParentId());
+                        }
+                    }
+                    this.save(o);
+                }
+            }
+        } catch (RuntimeException e) {
+            throw new RuntimeException(e);
+        }
+        return new CommonResult<String>(true, "批量添加组织成功!", null);
+	}
+
+	@Override
 	@Transactional
 	public CommonResult<String> deleteOrg(String codes) throws Exception {
 		if (StringUtils.isEmpty(codes)) {

+ 91 - 0
uc/src/main/java/com/hotent/uc/manager/impl/UserManagerImpl.java

@@ -10,6 +10,7 @@ import java.nio.file.Paths;
 import java.security.NoSuchAlgorithmException;
 import java.security.spec.InvalidKeySpecException;
 import java.sql.SQLException;
+import java.text.ParseException;
 import java.time.LocalDateTime;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -38,6 +39,7 @@ import com.baomidou.mybatisplus.core.conditions.Wrapper;
 import com.baomidou.mybatisplus.core.toolkit.Constants;
 import com.hotent.base.util.*;
 import com.hotent.uc.manager.*;
+import com.hotent.uc.params.org.OrgVo;
 import org.apache.ibatis.annotations.Param;
 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 import org.apache.poi.ss.formula.functions.T;
@@ -323,6 +325,95 @@ public class UserManagerImpl extends BaseManagerImpl <UserDao, User> implements
 	 }
 
 	@Override
+	public CommonResult<String> addUsers(List<UserVo> users) throws Exception {
+        try {
+			List<String> accounts = users.stream().map(UserVo::getAccount).collect(Collectors.toList());
+			List<User> userList = this.getByAccounts(accounts);
+			for (UserVo user: users ){
+				User use = userList.stream().filter(u -> u.getAccount().equals(user.getAccount())).findAny().orElse(null);
+				if (use==null) {
+					if(StringUtil.isEmpty(user.getAccount())){
+						throw new RequiredException("添加用户失败,用户帐号【account】必填!");
+					}
+					if(StringUtil.isEmpty(user.getFullname())){
+						throw new RequiredException("添加用户失败,用户名称【fullname】必填!");
+					}
+					if(StringUtil.isEmpty(user.getPassword())){
+						user.setPassword(user.getAccount());
+					}
+					if(baseMapper.getCountByAccount(user.getAccount())>0){
+						throw new RuntimeException("添加用户失败,帐号【"+user.getAccount()+"】已存在,请重新输入!");
+					}
+
+                /*User u = this.getByNumber(user.getUserNumber());
+                if(BeanUtils.isNotEmpty(u)){
+                    throw new RuntimeException("添加用户失败,工号【"+user.getUserNumber()+"】已存在,请重新输入!");
+                }
+
+                if(StringUtil.isNotEmpty(user.getMobile())){
+                    u = this.getByMobile(user.getMobile());
+                    if(BeanUtils.isNotEmpty(u)){
+                        throw new RuntimeException("添加用户失败,手机号【"+user.getMobile()+"】已存在,请重新输入!");
+                    }
+                }*/
+                /*if (!checkEmail(user.getEmail()) && !StringUtil.isEmpty(user.getEmail())){
+                    throw new RuntimeException("添加用户失败,邮箱格式不正确!");
+                }*/
+
+					User newUser = null;
+					newUser = UserVo.parser(user);
+					newUser.setStatus(User.STATUS_NORMAL);
+					newUser.setId(UniqueIdUtil.getSuid());
+					newUser.setCreateTime(LocalDateTime.now());
+					newUser.setFrom(User.FROM_RESTFUL);
+					String password = user.getPassword();
+					if (StringUtil.isEmpty(user.getPassword())) {
+						password = pwdStrategyManager.getDefault().getInitPwd();
+					}
+					newUser.setPassword(passwordEncoder.encode(password));
+					newUser.setPwdCreateTime(LocalDateTime.now());
+					Integer status = BeanUtils.isNotEmpty(user.getStatus())? user.getStatus():1;
+					if(status!=1&&status!=-1&&status!=-2&&status!=0){
+						status = 1;
+					}
+					newUser.setStatus(status);
+					//try {
+					this.create(newUser);
+					//将用户加入一般用户角色中
+					Role role = roleManager.getByAlias("ybyh");
+					String roleId = "1";
+					if(BeanUtils.isNotEmpty(role)){
+						roleId = role.getId();
+					}
+					UserRole userRole = new UserRole();
+					userRole.setId(UniqueIdUtil.getSuid());
+					userRole.setRoleId(roleId);
+					userRole.setUserId(newUser.getId());
+					userRoleManager.save(userRole);
+					if(user.getMobile()!=null){
+						//User userIndex=this.get(newUser.ge);
+						List<Org> orgList=orgManager.getOrgListByUserId(newUser.getId());
+						if(orgList.size()>0){
+							String pathName=orgList.get(0).getPathName();
+							String pathTemp="/"+pathName.split("/")[1];
+							List<Org>  orgListIndex=orgManager.getByPathName(pathTemp);
+							if(orgListIndex.size()>0){
+								dingUserManager.systemToDingUser(orgListIndex.get(0).getId(),newUser);
+							}
+						}
+					}
+                /*} catch (Exception e) {
+                    throw new RuntimeException(e.getMessage());
+                }*/
+				}
+            }
+        } catch (RuntimeException e) {
+            throw new RuntimeException(e);
+        }
+        return new CommonResult<String>(true, "批量用户添加成功!", "");
+	}
+
+	@Override
     @Transactional
 	public void updateUser(UserVo user)throws Exception {
 //		if(demoMode) {