Browse Source

老河口批量登录代码完整版提交

1037015548@qq.com 10 months ago
parent
commit
bf5510f6fd

+ 2 - 2
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysIndexController.java

@@ -226,10 +226,10 @@ public class SysIndexController extends BaseController
         mmap.put("rightOneList",rightOneList);
         mmap.put("rightTwoList",rightTwoList);
         mmap.put("rightThreeList",rightThreeList);
-//        return "mainLhk";
+        return "mainLhk";
 //        return "main";
 //        return "mainYining";
-        return "mainDangyang";
+//        return "mainDangyang";
     }
 
 

+ 2 - 2
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysLoginController.java

@@ -75,9 +75,9 @@ public class SysLoginController extends BaseController
         mmap.put("codeUrl", yiningCodeUrl);
         // 是否开启用户注册
         mmap.put("isAllowRegister", Convert.toBool(configService.getKey("sys.account.registerUser"), false));
-//        return "login";
+        return "login";
 //        return "loginYining";
-        return "loginDangyang";
+//        return "loginDangyang";
     }
 
     @PostMapping("/login")

+ 180 - 6
ruoyi-admin/src/main/java/com/ruoyi/web/controller/system/SysUserController.java

@@ -1,23 +1,36 @@
 package com.ruoyi.web.controller.system;
 
-import java.util.List;
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.text.DecimalFormat;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 
 import com.ruoyi.system.domain.Dangan;
+import com.ruoyi.system.mapper.SysDeptMapper;
+import com.ruoyi.system.mapper.SysUserMapper;
 import com.ruoyi.system.service.*;
 import org.apache.commons.lang3.ArrayUtils;
 import org.apache.commons.lang3.ObjectUtils;
+import org.apache.poi.ss.usermodel.*;
+import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 import org.apache.shiro.authz.annotation.RequiresPermissions;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.io.Resource;
+import org.springframework.core.io.UrlResource;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Controller;
 import org.springframework.ui.ModelMap;
 import org.springframework.util.CollectionUtils;
 import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.PathVariable;
-import org.springframework.web.bind.annotation.PostMapping;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.ResponseBody;
+import org.springframework.web.bind.annotation.*;
 import org.springframework.web.multipart.MultipartFile;
 import com.ruoyi.common.annotation.Log;
 import com.ruoyi.common.constant.UserConstants;
@@ -36,6 +49,8 @@ import com.ruoyi.common.utils.poi.ExcelUtil;
 import com.ruoyi.framework.shiro.service.SysPasswordService;
 import com.ruoyi.framework.shiro.util.AuthorizationUtils;
 
+import static com.ruoyi.common.utils.CacheUtils.put;
+
 /**
  * 用户信息
  * 
@@ -65,6 +80,11 @@ public class SysUserController extends BaseController
     @Autowired
     private IDanganService danganService;
 
+    @Autowired
+    private SysDeptMapper sysDeptMapper;
+    @Autowired
+    private SysUserMapper sysUserMapper;
+
     @RequiresPermissions("system:user:view")
     @GetMapping()
     public String user(ModelMap modelMap)
@@ -92,6 +112,160 @@ public class SysUserController extends BaseController
         return getDataTable(list);
     }
 
+    @PostMapping("/upload")
+    @ResponseBody
+    public ResponseEntity<Map<String,Object>> uploadFile(@RequestParam("excel") MultipartFile file) {
+        // 检查文件是否为空
+        if (file.isEmpty()) {
+            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new HashMap<String,Object>(){{
+                put("message", "请上传文件!");
+            }});
+        }
+
+        // 检查文件类型
+        if (!file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")) {
+            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new HashMap<String,Object>(){{
+                put("message", "请上传Excel文件!");
+            }});
+        }
+
+        try {
+            // 将上传的文件转换为POI的工作簿对象以便处理
+            Workbook workbook = new XSSFWorkbook(file.getInputStream());
+            // 处理工作簿...
+            // 例如,可以读取工作簿中的数据
+// 2.得到表。
+            Sheet sheet = workbook.getSheetAt(0);
+//            // 3.得到行。
+//            Row row = sheet.getRow(0);
+//            // 4.得到列。
+//            Cell cell = row.getCell(0);
+//            // 读取值。一定要注意类型,否则会读取失败
+//            System.out.println(cell.getStringCellValue());// 字符串类型
+//            Cell cell1 = row.getCell(1);
+//            System.out.println(cell1.getNumericCellValue());// 数字类型
+            Integer success = 0;//成功数
+            List<String> unDept = new ArrayList<>();//不存在的部门
+            List<String> unUser = new ArrayList<>();//未成功用户
+            List<String> unDoubleUser = new ArrayList<>();//双手机用户
+            for (int i = 0; i < sheet.getPhysicalNumberOfRows()-1; i++) {
+                // 3.得到行。
+                Row row = sheet.getRow(i+1);
+                row.getCell(2).setCellType(CellType.STRING);
+                row.getCell(3).setCellType(CellType.STRING);
+                // 4.得到列。
+                Cell cell = row.getCell(0);//归属机构
+                Cell cell2 = row.getCell(1);//用户姓名
+                Cell cell3 = row.getCell(2);//登录名称
+                Cell cell4 = row.getCell(3);//手机号码
+
+                //TODO 查询归属机构的deptId
+                SysDept sysDept = null;
+                String text = cell.getStringCellValue();
+                if(text.indexOf("(")>=0) {
+                    Pattern pattern = Pattern.compile("\\((.*?)\\)");
+                    Matcher matcher = pattern.matcher(text);
+                    while (matcher.find()) {
+                        text = matcher.group(1);
+                    }
+                }
+                sysDept = sysDeptMapper.selectDeptByName(text);
+                if(sysDept!=null){
+                    try {
+                        //TODO 插入用户信息接口, 并建立关联
+                        SysUser sysUser = new SysUser();
+                        sysUser.setUserName(cell2.getStringCellValue());
+                        DecimalFormat df = new DecimalFormat("0");
+                        sysUser.setLoginName(cell3.getStringCellValue());
+                        sysUser.setPhonenumber(cell4.getStringCellValue());
+                        sysUser.setPassword("Lhk" + cell4 + "@2024!");
+                        sysUser.setDeptId(sysDept.getDeptId());
+                        sysUser.setParentId(sysDept.getParentId());
+                        sysUser.setUserType("00");
+                        sysUser.setSex("2");
+                        sysUser.setUsbkey("1");
+                        Integer result = saveUser(sysUser);
+                        if (result > 0) {
+                            success = success + 1;
+                        }
+                    }catch(Exception ex){
+                        unDoubleUser.add(cell2.getStringCellValue());
+                    }
+                }else{
+                    if(!unDept.contains(text)){
+                        unDept.add(text);
+                    }
+                    if(!unUser.contains(cell2.getStringCellValue())){
+                        unUser.add(cell2.getStringCellValue());
+                    }
+                }
+            }
+            System.out.println("未找到部门:"+ Arrays.toString(unDept.toArray()));
+            System.out.println("成功数:"+success);
+            System.out.println("未成功数:"+unUser.size());
+            System.out.println("未成功用户:"+Arrays.toString(unUser.toArray()));
+            System.out.println("双手机未成功用户:"+Arrays.toString(unDoubleUser.toArray()));
+
+            // 5.关闭流。
+            file.getInputStream().close();
+            String message = "成功数:"+success+"未成功数:"+unUser.size()+
+                    "未成功用户:"+Arrays.toString(unUser.toArray());
+            return ResponseEntity.status(HttpStatus.OK)
+                    .body(new HashMap<String,Object>(){{
+                            put("message", message);
+                    }});
+        } catch (IOException e) {
+            e.printStackTrace();
+            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new HashMap<String,Object>(){{
+                put("message", "上传文件失败!");
+            }});
+        }
+    }
+    private int saveUser(SysUser user){
+        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user)))
+        {
+//            return error("新增用户'" + user.getLoginName() + "'失败,登录账号已存在");
+            return -1;
+        }
+        else if (StringUtils.isNotEmpty(user.getPhonenumber())
+                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
+        {
+//            return error("新增用户'" + user.getLoginName() + "'失败,手机号码已存在");
+            return -1;
+        }
+        else if (StringUtils.isNotEmpty(user.getEmail())
+                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
+        {
+//            return error("新增用户'" + user.getLoginName() + "'失败,邮箱账号已存在").get("code");
+            return -1;
+        }
+        user.setSalt(ShiroUtils.randomSalt());
+        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
+        user.setCreateBy("admin");
+        return userService.insertUser(user);
+    }
+
+    @GetMapping("/download-file")
+    @ResponseBody
+    public ResponseEntity<Resource> downloadFile() {
+        // 指定文件路径,这里假设文件位于项目根目录下
+        Path path = Paths.get("人员导入模版.xlsx"); // 修改为你的文件名
+        Resource resource;
+        try {
+            resource = new UrlResource(path.toUri());
+            if (resource.exists() || resource.isReadable()) {
+                return ResponseEntity.ok()
+                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
+                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
+                        .body(resource);
+            } else {
+                throw new RuntimeException("Could not read the file!");
+            }
+        } catch (MalformedURLException e) {
+            throw new RuntimeException("Error: " + e.getMessage());
+        }
+    }
+
     @Log(title = "用户管理", businessType = BusinessType.EXPORT)
     @RequiresPermissions("system:user:export")
     @PostMapping("/export")

File diff suppressed because it is too large
+ 1 - 1
ruoyi-admin/src/main/resources/static/css/login.min.css


+ 1 - 1
ruoyi-admin/src/main/resources/static/ruoyi/index.js

@@ -12,7 +12,7 @@ var sidebarHeight = isMobile ? '100%' : '96%';
 
 
 // 设置超时时间为10分钟(600000毫秒)
-var TIMEOUT = 600000;
+var TIMEOUT = 600000*6;
 // var TIMEOUT = 10000;
 var timeoutId;
 var ifExit = false;

+ 6 - 1
ruoyi-admin/src/main/resources/templates/system/role/add.html

@@ -68,7 +68,12 @@
 		    };
 			$.tree.init(options);
 		});
-		
+
+        setTimeout(function() {
+            $._tree.expandAll(true);
+            $("a[title='系统管理']").next().find("li a:not([title='日志管理'])").parent().hide();
+        }, 500);
+
 		$("#form-role-add").validate({
 			rules:{
 				onkeyup: false,

+ 7 - 2
ruoyi-admin/src/main/resources/templates/system/role/edit.html

@@ -46,7 +46,7 @@
 				<label class="col-sm-3 control-label">菜单权限:</label>
 				<div class="col-sm-8">
 				    <label class="check-box">
-				        <input type="checkbox" value="1">展开/折叠</label>
+				        <input type="checkbox" value="1" checked>展开/折叠</label>
 				    <label class="check-box">
 				        <input type="checkbox" value="2">全选/全不选</label>
 				    <label class="check-box">
@@ -69,7 +69,12 @@
 		    };
 			$.tree.init(options);
 		});
-	
+
+        setTimeout(function() {
+            $._tree.expandAll(true);
+            $("a[title='系统管理']").next().find("li a:not([title='日志管理'])").parent().hide();
+        }, 500);
+
 		$("#form-role-edit").validate({
 			onkeyup: false,
 			rules:{

+ 7 - 3
ruoyi-admin/src/main/resources/templates/system/role/role.html

@@ -112,16 +112,20 @@
 		            title: '操作',
 		            align: 'center',
 		            formatter: function(value, row, index) {
-		            	if (row.roleId != 1) {
+		            	if (row.roleId != 1&&((row.roleName !== "管理员"||row.roleName !== "\u7ba1\u7406\u5458"))) {
 		                    var actions = [];
 		                    actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.roleId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
 		                    actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.roleId + '\')"><i class="fa fa-remove"></i>删除</a> ');
 		                    var more = [];
-		                    more.push("<a class='btn btn-default btn-xs " + editFlag + "' href='javascript:void(0)' onclick='authDataScope(" + row.roleId + ")'><i class='fa fa-check-square-o'></i>数据权限</a> ");
+		                    // more.push("<a class='btn btn-default btn-xs " + editFlag + "' href='javascript:void(0)' onclick='authDataScope(" + row.roleId + ")'><i class='fa fa-check-square-o'></i>数据权限</a> ");
 		                    more.push("<a class='btn btn-default btn-xs " + editFlag + "' href='javascript:void(0)' onclick='authUser(" + row.roleId + ")'><i class='fa fa-user'></i>分配用户</a>");
 		                    actions.push('<a tabindex="0" class="btn btn-info btn-xs" role="button" data-container="body" data-placement="left" data-toggle="popover" data-html="true" data-trigger="hover" data-content="' + more.join('') + '"><i class="fa fa-chevron-circle-right"></i>更多操作</a>');
 		                    return actions.join('');
-		            	} else {
+		            	} else if(row.roleName === "管理员"||row.roleName === "\u7ba1\u7406\u5458"){
+                            var actions = [];
+                            actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="javascript:void(0)" onclick="$.operate.edit(\'' + row.roleId + '\')"><i class="fa fa-edit"></i>编辑</a> ');
+                            return actions.join('');
+		            	}else {
 		                    return "";
 		                }
 		            }

+ 64 - 3
ruoyi-admin/src/main/resources/templates/system/user/user.html

@@ -68,6 +68,13 @@
 				<a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()" shiro:hasPermission="system:user:remove">
 					<i class="fa fa-remove"></i> 删除
 				</a>
+				<input type="file" id="excelFile" accept=".xls,.xlsx">
+				<a class="btn btn-sm" onclick="uploadFile()">
+					<i class="fa fa-upload"></i> 批量导入
+				</a>
+				<a class="btn btn-sm" onclick="downloadFile()">
+					<i class="fa fa-download"></i> 下载模版
+				</a>
 				<!--<a class="btn btn-info" onclick="$.table.importExcel()" shiro:hasPermission="system:user:import">-->
 				<!--<i class="fa fa-upload"></i> 导入-->
 				<!--</a>-->
@@ -94,7 +101,54 @@
 
 	var prefix = ctx + "system/user";
 
-	$(function() {
+    function downloadFile() {
+        // 调用Spring Boot后端提供的下载接口
+        fetch(prefix+'/download-file')
+            .then(response => response.blob()) // 转换响应为Blob
+    .then(blob => {
+            // 创建一个链接并模拟点击进行下载
+            const url = window.URL.createObjectURL(blob);
+        const a = document.createElement('a');
+        a.style.display = 'none';
+        a.href = url;
+        a.download = '人员导入模版.xlsx'; // 指定下载的文件名
+        document.body.appendChild(a);
+        a.click();
+        window.URL.revokeObjectURL(url); // 清理资源
+    })
+    .catch(e => console.error('Error during file download:', e));
+    }
+
+    function uploadFile() {
+        const fileInput = document.getElementById('excelFile');
+        const file = fileInput.files[0]; // 获取选中的文件
+
+        if (!file) {
+            alert('请先选择一个文件!');
+            return;
+        }
+
+        const formData = new FormData();
+        formData.append('excel', file); // 'excel' 是后台接口预期的字段名
+
+        // 使用 Fetch API 上传文件
+        fetch(prefix+'/upload', { // 替换为你的后台接口 URL
+            method: 'POST',
+            body: formData,
+        })
+            .then(response => response.json())
+		.then(data => {
+			alert('文件上传成功!'+data.message);
+        	refreshTab();
+		})
+		.catch((error) => {
+				console.error('Error:', error);
+			alert('文件上传失败!'+data.message);
+		});
+    }
+
+
+    $(function() {
 		var panehHidden = false;
 		if ($(this).width() < 769) {
 			panehHidden = true;
@@ -164,8 +218,15 @@
 						actions.push("<a class='btn btn-info btn-xs " + editFlag + "' href='javascript:void(0)' onclick='authRole(" + row.userId + ")'><i class='fa fa-check-square-o'></i>分配角色</a> ");
 						actions.push("<a class='btn btn-warning btn-xs " + editFlag + "' href='javascript:void(0)' onclick='authChild("+row.userId+")'><i class='fa fa-edit'></i>添加子账号</a> ");
 						actions.push("<a class='btn btn-default btn-xs " + editFlag + "' href='javascript:void(0)' onclick='findChild("+row.userId+")'><i class='fa fa-eye'></i>查看子账号</a>");
-						if(currentUser!==null&&currentUser.loginName=="adminCzy"){
-                            actions.push("<a class='btn btn-link btn-xs " + editFlag + "' href='javascript:void(0)' onclick='resetPwd("+row.userId+")'><i class='fa fa-plane'></i>重置密码</a>");
+						if(currentUser!==null){
+						    if(currentUser.roles!=null&&currentUser.roles.length>0){
+						        for(let i=0;i<currentUser.roles.length;i++){
+						            if(currentUser.roles[i].roleName==="\u7ba1\u7406\u5458"||currentUser.roles[i].roleName==="管理员"||
+                                        currentUser.roles[i].roleName==="\u8d85\u7ea7\u7ba1\u7406\u5458"||currentUser.roles[i].roleName==="超级管理员"){
+                                        actions.push("<a class='btn btn-link btn-xs " + editFlag + "' href='javascript:void(0)' onclick='resetPwd("+row.userId+")'><i class='fa fa-plane'></i>重置密码</a>");
+						            }
+								}
+							}
 						}
 						return actions.join('');
 					}

BIN
人员导入模版.xlsx