관리자 등록 ,목록 수정

This commit is contained in:
주수현
2025-06-19 20:27:47 +09:00
parent 2402be3b44
commit 68b396921f
31 changed files with 400 additions and 112 deletions

View File

@@ -0,0 +1,23 @@
package app.module.admin.usecase.admin.checkAdminId.adapters.web;
import app.module.core.usecase.admin.checkAdminId.ports.CheckAdminIdPortIn;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequiredArgsConstructor
class AdminIdDuplicateCheckPostController {
private final CheckAdminIdPortIn checkAdminIdPortIn;
@GetMapping("/api/settings/admin/idCheck")
ResponseEntity<?> updateMappingHousehold(@RequestParam String id ) {
return ResponseEntity.status(HttpStatus.OK).body(checkAdminIdPortIn.connect(id));
}
}

View File

@@ -42,6 +42,7 @@ class AdminListController {
model.addAttribute("listOutput", listOutput);
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
model.addAttribute("pageRows", uiCodeListPortIn.connect("code.pageable.rows"));
model.addAttribute("regionMainCode", uiCodeListPortIn.connect("code.region.main"));
return "admin/adminList";
}

View File

@@ -18,8 +18,10 @@ public class AdminCreateGetController {
private final UICodeListPortIn uiCodeListPortIn;
@GetMapping(path = "/settings/admins/create")
String operate(Model model, @ModelAttribute("bindingVO") AdminCreateBindingVO bindingVO) {
String operate(Model model) {
AdminCreateBindingVO bindingVO = new AdminCreateBindingVO();
model.addAttribute("bindingVO", bindingVO);
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
model.addAttribute("regionMainCode", uiCodeListPortIn.connect("code.region.main"));

View File

@@ -9,49 +9,44 @@ import app.module.core.usecase.role.list.ports.RoleListPortIn;
import app.module.core.usecase.uicode.list.ports.UICodeListPortIn;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@Slf4j
@RestController
@RequiredArgsConstructor
public class AdminCreatePostController {
private final RoleListPortIn roleListPortIn;
private final MessageUtil messageUtil;
private final SaveAdminPortIn savePortIn;
private final UICodeListPortIn uiCodeListPortIn;
private final AdminCreateValidator adminCreateValidator;
@PostMapping(path = "/settings/admins/create")
String operate(
RedirectAttributes redirectAttributes,
Model model,
@Valid @ModelAttribute("bindingVO") AdminCreateBindingVO bindingVO,
BindingResult bindingResult) {
@PostMapping(path = "/api/settings/admin/create")
ResponseEntity<?> operate(@RequestBody AdminCreateBindingVO bindingVO, BindingResult bindingResult ) {
adminCreateValidator.validate(bindingVO, bindingResult);
if (bindingResult.hasErrors()) {
model.addAttribute("roles", roleListPortIn.connect(AppType.ADMIN));
model.addAttribute("regionMainCode", uiCodeListPortIn.connect("code.region.main"));
return "admin/adminCreateForm";
log.info("############Binding errors: {}", bindingResult.getAllErrors());
log.info("Binding 메세지 errors: {}", bindingResult.getAllErrors().get(0).getDefaultMessage());
return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY)
.body(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
savePortIn.connect(
bindingVO.getSeq(),
bindingVO.getId(),
bindingVO.getPassword(),
bindingVO.getRegionMainCode(),
bindingVO.getAccountDisabled(),
bindingVO.getRoleIds());
redirectAttributes.addFlashAttribute(
"operationMessage",
messageUtil.getMessage("operation.settings.admin.created", bindingVO.getId()));
return "redirect:/settings/admins";
return ResponseEntity.status(HttpStatus.OK).body(
savePortIn.apiConnect(bindingVO.getSeq(),
bindingVO.getId(),
bindingVO.getPassword(),
bindingVO.getName(),
"010"+bindingVO.getPhone1()+bindingVO.getPhone2(),
bindingVO.getRegionMainCode(),
bindingVO.getAccountDisabled(),
bindingVO.getRoleId()));
}
}

View File

@@ -53,6 +53,8 @@ class AdminUpdateGetController {
output.getSeq(),
output.getId(),
null,
output.getName(),
output.getPhone(),
output.getRegionMainCode(),
output.getPasswordUpdatedAt(),
output.getAccountDisabled(),

View File

@@ -16,6 +16,8 @@ import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.stream.Collectors;
@Controller
@RequiredArgsConstructor
class AdminUpdatePostController {
@@ -40,13 +42,15 @@ class AdminUpdatePostController {
return "admin/adminUpdateForm";
}
saveAdminPortIn.connect(
saveAdminPortIn.apiConnect(
bindingVO.getSeq(),
bindingVO.getId(),
bindingVO.getUpdatePassword(),
bindingVO.getName(),
bindingVO.getPhone(),
bindingVO.getRegionMainCode(),
bindingVO.getAccountDisabled(),
bindingVO.getRoleIds());
bindingVO.getRoleIds().stream().collect(Collectors.joining()));
redirectAttributes.addFlashAttribute(
"operationMessage",

View File

@@ -1,20 +1,23 @@
package app.module.admin.usecase.admin.saveAdmin.adapters.web.model;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class AdminCreateBindingVO {
private Long seq;
private String id;
private String password;
private String name;
private String phone1;
private String phone2;
private String regionMainCode;
/* @NotBlank(message = "{valid.common.required}")
@Pattern(
regexp =
@@ -24,6 +27,5 @@ public class AdminCreateBindingVO {
private Boolean accountDisabled;
/* private Boolean accountLocked;*/
private List<String> roleIds;
private String regionMainCode;
private String roleId;
}

View File

@@ -32,6 +32,8 @@ public class AdminUpdateBindingVO implements AuditOutput {
"^[\\w!#$%&’*+/=?`{|}~^-]+(?:\\.[\\w!#$%&’*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$",
message = "{valid.common.email.wrong}")
private String email;*/
private String name;
private String phone;
private String regionMainCode;
private LocalDateTime passwordUpdatedAt;

View File

@@ -10,7 +10,10 @@ import org.springframework.validation.Validator;
@Component
public class AdminCreateValidator implements Validator {
private final String PASSWORD_REGEX = "^((?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%_\\-])\\S{6,15})$";
// 아이디: 4~15자, 영문/숫자/한글/특수문자(_,-) 허용
private final String ID_REGEX = "^[a-zA-Z0-9가-힣_-]{4,15}$";
// 비밀번호: 5자, 숫자 + 특수문자(!@#$%_-) 1개 이상
private final String PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[!@#$%_\\-]).{5}$";
@Override
public boolean supports(Class<?> clazz) {
@@ -21,25 +24,47 @@ public class AdminCreateValidator implements Validator {
public void validate(Object target, Errors errors) {
AdminCreateBindingVO vo = (AdminCreateBindingVO) target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "valid.common.required");
if (vo.getRoleId() == null || vo.getRoleId().isEmpty()) {
errors.rejectValue("roleId", "error.roleId", "권한을 선택해주세요.");
}
if (vo.getAccountDisabled() == null ) {
errors.rejectValue("accountDisabled", "error.accountDisabled", "사용여부를 선택해주세요.");
}
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id", "valid.common.required","아이디는 필수입력값입니다.");
Optional.ofNullable(vo.getId())
.filter(id -> !id.matches(ID_REGEX))
.ifPresent(id -> errors.rejectValue("id", "valid.common.id.wrong","아이디를 4~15자, 영문/숫자/한글/특수문자(_,-) 입니다."));
// 비밀번호 유효성 검사
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "valid.common.required","비밀번호는 필수입력값입니다.");
Optional.ofNullable(vo.getPassword())
.filter(password -> !password.matches(PASSWORD_REGEX))
.ifPresent(password -> errors.rejectValue("password", "valid.common.password.wrong"));
Optional.ofNullable(vo.getRoleIds())
.filter(ids -> ids.size() < 1)
.ifPresent(
ids ->
errors.rejectValue(
"roleIds", "valid.common.required.size.min", new Object[]{1}, ""));
.ifPresent(password -> errors.rejectValue("password", "valid.common.password.wrong","비밀번호는 5자, 숫자 + 특수문자(!@#$%_-) 1개 이상입니다."));
if (vo.getRoleId() != null && "ROLE_RESEARCHER".equals(vo.getRoleId())) {
if (vo.getName() == null || vo.getName().isBlank()) {
errors.rejectValue("name", "error.name", "이름을 입력해주세요.");
}
if (vo.getPhone1() == null || vo.getPhone1().isBlank()) {
errors.rejectValue("phone1", "error.phone1", "전화번호 앞자리를 입력해주세요.");
} else if (!vo.getPhone1().matches("^\\d{4}$")) {
errors.rejectValue("phone1", "error.phone1", "전화번호 앞자리는 4자리 숫자여야 합니다.");
}
if (vo.getPhone2() == null || vo.getPhone2().isBlank()) {
errors.rejectValue("phone2", "error.phone2", "전화번호 뒷자리를 입력해주세요.");
} else if (!vo.getPhone2().matches("^\\d{4}$")) {
errors.rejectValue("phone2", "error.phone2", "전화번호 뒷자리는 4자리 숫자여야 합니다.");
}
}
// ROLE_ADMIN이 아닌 경우 regionMainCode null체크
Optional.ofNullable(vo.getRoleIds())
.filter(ids -> ids.stream().noneMatch(role -> role.equals("ROLE_ADMIN")))
Optional.ofNullable(vo.getRoleId())
.filter(id -> !id.equals("ROLE_ADMIN"))
.ifPresent(nonAdmins -> {
if (vo.getRegionMainCode() == null || vo.getRegionMainCode().isBlank()) {
errors.rejectValue("regionMainCode", "valid.common.required");
errors.rejectValue("regionMainCode", "valid.common.required","실사지역은 필수입력값입니다.");
}
});
}

View File

@@ -7,27 +7,28 @@
<form
method="post"
th:action="@{/settings/admins/create}"
th:object="${bindingVO}">
th:object="${bindingVO}"
name="adminCreateForm">
<table class="type-form">
<tbody>
<tr>
<th><label for="roleIds">권한<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
<th><label for="roleId">권한<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
<td>
<div class="d-flex">
<div class="component-input">
<div class="component-select">
<select class="select-list" id="roleIds"
th:classappend="${#fields.hasErrors('roleIds')} ? 'is-invalid'"
th:field="*{roleIds}"
<select class="select-list" id="roleId"
th:classappend="${#fields.hasErrors('roleId')} ? 'is-invalid'"
th:field="*{roleId}"
onchange="onRoleChange(this);">
<option value="">선택</option>
<option th:each="role : ${roles}" th:text="${role.description}"
th:value="${role.id}"></option>
</select>
</div>
<div class="invalid-feedback fw-bold" th:errors="*{roleIds}"
th:if="${#fields.hasErrors('roleIds')}">
<div class="invalid-feedback fw-bold" th:errors="*{roleId}"
th:if="${#fields.hasErrors('roleId')}">
에러 메세지
</div>
</div>
@@ -40,13 +41,18 @@
<div class="component-input">
<div class="input-field">
<input id="id"
name="id"
th:classappend="${#fields.hasErrors('id')} ? 'is-invalid'"
th:field="*{id}"/>
<button type="button" class="btn btn-primary" onclick="adminIdCheckDuplicate();">
<span class="btn-txt">중복확인</span>
</button>
<div class="invalid-feedback fw-bold" th:errors="*{id}"
th:if="${#fields.hasErrors('id')}">
에러 메세지
</div>
</div>
<span>4~15자 / 영문,숫자,한글 가능/ 특수문자 _,- 사용가능</span>
</div>
</td>
<th><label for="password">Password<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
@@ -61,11 +67,51 @@
에러 메세지
</div>
</div>
<span>총 5자 / 숫자 + 특수문자 1개 이상 (!,@,#,$,%,_,-)</span>
</div>
</td>
</tr>
<tr class="researcherArea"
th:classappend="${bindingVO.roleId == 'ROLE_LOCAL_INSPECTOR'} ? 'd-none'">
<th><label for="name">이름<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
<td>
<div class="component-input">
<div class="input-field">
<input id="name" type="text" name="name"
th:classappend="${#fields.hasErrors('name')} ? 'is-invalid'"
th:field="*{name}"/>
<div class="invalid-feedback fw-bold"
th:if="${#fields.hasErrors('name')}">
에러 메세지
</div>
</div>
</div>
</td>
<th><label for="name">전화번호<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
<td>
010-
<div class="component-input">
<div class="input-field">
<input id="phone1" name="phone1" type="number" maxlength="4" th:field="*{phone1}"
th:classappend="${#fields.hasErrors('name')} ? 'is-invalid'"
/>
</div>
</div>
<div class="component-input">
<div class="input-field">
<input id="phone2" name="phone2" type="number" maxlength="4" th:field="*{phone2}"
th:classappend="${#fields.hasErrors('name')} ? 'is-invalid'"
/>
</div>
</div>
<div class="invalid-feedback fw-bold"
th:if="${#fields.hasErrors('phone1')}">
에러 메세지
</div>
</td>
</tr>
<tr class="regionMainCodeArea"
th:classappend="${#lists.isEmpty(bindingVO.roleIds) or #lists.contains(bindingVO.roleIds, 'ROLE_ADMIN')} ? 'd-none'">
th:classappend="${bindingVO.roleId != 'ROLE_ADMIN'} ? 'd-none'">
<th><label for="regionMainCode">실사<i class="ico-required-mark" role="img" aria-label="필수">*</i></label></th>
<td>
<div class="component-select">
@@ -118,7 +164,7 @@
<button type="button" class="btn btn-secondary" onclick="gotoList();return false;">
<span class="btn-txt">목록으로 이동</span>
</button>
<button type="submit" class="btn btn-primary">
<button type="button" class="btn btn-primary" onclick="createAdmin();">
<span class="btn-txt">저장</span>
</button>
</div>
@@ -137,14 +183,69 @@
}
$(document).ready(() => {
const roleSelect = document.getElementById('roleIds');
const roleSelect = document.getElementById('roleId');
onRoleChange(roleSelect);
});
const onRoleChange = (el) => {
const selectedValues = Array.from(el.selectedOptions).map(option => option.value);
const isAdmin = !selectedValues.length || selectedValues.includes('ROLE_ADMIN');
const idResearcher = !selectedValues.length || selectedValues.includes('ROLE_RESEARCHER');
$('.regionMainCodeArea').toggle(!isAdmin);
$('.researcherArea').toggle(idResearcher);
};
let checkDuplicate = false;
const adminIdCheckDuplicate = () => {
const f = document.adminCreateForm;
if (!f.id.value) {
alert("아이디를 입력해주세요.");
return;
}
ajaxUtil._ajaxMethod(
'/api/settings/admin/idCheck',
{ id : f.id.value },
function(response) { // 성공
const message = response > 0
? "이미 사용하고 있는 아이디 입니다. 아이디를 입력해주세요."
: "사용 가능한 아이디입니다.";
alert(message);
checkDuplicate = response <= 0;
},
function (code, rstData) {
console.log("error : ", code);
if(code == 400) alert("아이디를 입력해주세요.");
},
'get',
'json'
);
}
const createAdmin = () => {
if (!checkDuplicate) {
alert("아이디 중복 확인을 해주세요.");
return false;
}
const f = document.adminCreateForm;
let dataOj = $(f).serializeObject();
ajaxUtil._ajaxMethod(
'/api/settings/admin/create',
JSON.stringify(dataOj),
function(response) { // 성공
alert("등록이 완료되었습니다.");
location.href = '/settings/admins';
},
function (code, rstData) {
if(code == 422) alert(rstData.responseText);
if(code == 400) alert(rstData.responseJSON.message);
},
'post',
'json',
{ handle422Type: 'alert' }
);
}
</script>
</th:block>

View File

@@ -17,14 +17,26 @@
<div class="form-area">
<div class="input-group">
<div class="input-label">
<p class="label-txt"><label for="searchField">검색필드</label></p>
<p class="label-txt">권한</p>
</div>
<div class="component-select">
<select class="select-list" id="searchRole" th:field="*{searchRole}">
<option selected value="">전체</option>
<option th:each="role : ${roles}" th:text="${role.description}"
th:value="${role.id}"></option>
</select>
</div>
</div>
<div class="input-group">
<div class="input-label">
<p class="label-txt"><label for="searchField">정보</label></p>
</div>
<div class="d-flex">
<div class="component-select">
<select class="select-list" id="searchField" th:field="*{searchField}">
<option selected value="">선택</option>
<option selected value="">전체</option>
<option value="id">ID</option>
<option value="email">Email</option>
<option value="name">이름</option>
</select>
</div>
<div class="component-input">
@@ -38,13 +50,25 @@
</div>
<div class="input-group">
<div class="input-label">
<p class="label-txt">권한</p>
<p class="label-txt">실사</p>
</div>
<div class="component-select">
<select class="select-list" id="searchRole" th:field="*{searchRole}">
<select class="select-list" id="searchArea" th:field="*{searchRole}">
<option selected value="">전체</option>
<option th:each="role : ${roles}" th:text="${role.id}"
th:value="${role.id}"></option>
<option th:each="region : ${regionMainCode}" th:text="${region.codeText}"
th:value="${region.id}"></option>
</select>
</div>
</div>
<div class="input-group">
<div class="input-label">
<p class="label-txt">계정사용여부</p>
</div>
<div class="component-select">
<select class="select-list" id="searchDisabled" th:field="*{searchRole}">
<option selected value="">전체</option>
<option value="false">사용</option>
<option value="true">미사용</option>
</select>
</div>
</div>

View File

@@ -32,7 +32,11 @@
<tr>
<th>내용</th>
<td>
<textarea id="content" name="content" rows="5" cols="50"></textarea>
<div class="component-input">
<div class="input-textarea-field">
<textarea id="content" name="content" class="textarea" placeholder=""></textarea>
</div>
</div>
</td>
</tr>
<tr>