코딩하는 털보

11 to 9, Day 12,13 본문

Diary/Eleven to Nine

11 to 9, Day 12,13

이정인 2021. 3. 17. 21:37

Today, ToDoList

  • 자바 라이브 스터디 후기 작성
  • Toy Project - NGMA
    • 계정 정보 변경
    • 일정 변경 및 제거

스터디 후기 작성

https://rockintuna.tistory.com/112


계정 정보 변경

컨트롤러 테스트

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void modifyAccount() throws Exception {
        AccountDto accountDto = new AccountDto();
        accountDto.setName("jileee");
        accountDto.setPassword("jilee321");
        String accountDtoJson = objectMapper.writeValueAsString(accountDto);

        mvc.perform(post("/account/update")
                .contentType(MediaType.APPLICATION_JSON)
                .content(accountDtoJson))
                .andDo(print())
                .andExpect(status().is3xxRedirection());

        assertThat(accountService.getUserByEmail("jilee@example.com").getName())
                .isEqualTo("jileee");
        assertThat(accountService.getUserByEmail("jilee@example.com").getPassword())
                .isNotNull();
    }

핸들러

    @PostMapping("/update")
    public String modify(@RequestBody AccountDto accountDto,
                         @AuthenticationPrincipal UserAccount userAccount) {
        accountService.modifyAccount(userAccount, accountDto);
        return "redirect:/login";
    }

서비스

    public void modifyAccount(UserAccount userAccount, AccountDto accountDto) {

        Account account = accountRepository.findByEmail(userAccount.getUsername())
                .orElseThrow(() -> new UsernameNotFoundException(userAccount.getUsername()));
        account.modifyByDto(accountDto);
        account.encodePassword(passwordEncoder);
    }

정보 변경 메인페이지

<div class="container" id="main_container">
    <main>
        <div class="py-5 text-center">
            <h2>회원 정보 변경</h2>
        </div>

        <div class="col-md-7 col-lg-8">
            <h4 class="mb-3">정보 입력</h4>
            <form class="needs-validation" id="accountModifyForm" novalidate>

                <div class="col-sm-6">
                    <label for="firstName" class="form-label">이름</label>
                    <input type="text" class="form-control" id="firstName" name="name" placeholder="" value="" required>
                    <div class="invalid-feedback">
                        새로운 이름을 입력해 주세요.
                    </div>
                </div>

                <div class="col-sm-6">
                    <label for="firstName" class="form-label">비밀번호</label>
                    <input type="password" class="form-control" id="password" name="password" placeholder="" value="" required>
                    <div class="invalid-feedback">
                        사용할 비밀번호를 입력해 주세요.
                    </div>
                </div>
                <hr class="my-4 center">
                <a class="btn btn-primary" type="button"data-bs-toggle="modal" data-bs-target="#accountModifyModal">계정변경</a>
                <a class="btn btn-secondary" type="button"data-bs-toggle="modal" data-bs-target="#accountDeleteModal">계정삭제</a>
            </form>
        </div>
    </main>
</div>

<div class="modal fade" id="accountModifyModal" tabindex="-1" aria-labelledby="accountModifyModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="accountModifyModalLabel">변경 확인</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>정말 변경하시겠습니까?</p>
            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-primary" id="accountModify">확인</a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="accountDeleteModal" tabindex="-1" aria-labelledby="accountDeleteModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="accountDeleteModalLabel">삭제 확인</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>정말 삭제하시겠습니까?</p>
            </div>
            <div class="modal-footer">
                <a type="button" class="btn btn-primary" id="accountDelete">확인</a>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
            </div>
        </div>
    </div>
</div>

변경작성하는 김에 제거도 추가

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void deleteAccount() throws Exception {
        mvc.perform(delete("/account/delete"))
                .andDo(print())
                .andExpect(status().is3xxRedirection());

        assertThrows(UsernameNotFoundException.class, () -> {
            accountService.getUserByEmail("jilee@example.com");
        });
    }
    @DeleteMapping("/delete")
    public ResponseEntity<?> delete(@AuthenticationPrincipal UserAccount userAccount) {
        accountService.deleteAccount(userAccount);
        return ResponseEntity.ok("{}");
    }
    public void deleteAccount(UserAccount userAccount) {
        Account account = getUserById(userAccount.getAccountId());
        if ( account.getLoverState() == LoverState.COUPLED ) {
            account.getLover().setLover(null);
            account.getLover().setLoverState(LoverState.NOTHING);
        }
        clearWaiter(account);
        scheduleService.clearSchedule(account);
        accountRepository.deleteById(userAccount.getAccountId());
    }
    public void clearWaiter(Account account) {
        List<Account> waiterList = account.getWaiters();
        for (Account waiter : waiterList) {
            waiter.setLover(null);
            waiter.setLoverState(LoverState.NOTHING);
        }
        waiterList.clear();
        account.setLoverStateHasWaiters(false);
    }
$(document).ready(function () {
    $(document).on("click","#accountSubmit",function (event) {
        submitAccountForm();
        return false;
    });
    $(document).on("click","#accountModify",function (event) {
        modifyAccountForm();
        return false;
    });
    $(document).on("click","#accountDelete",function (event) {
        deleteAccountForm();
        return false;
    });
});

function submitAccountForm(){
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/account",
        contentType: "application/json",
        dataType: "html",
        cache:false,
        data: JSON.stringify($("form#accountForm").serializeObject()),
        success: function(response){
            window.location.href = "http://localhost:8080/login";
        },
        error: function(e){
            alert(e);
        }
    });
}

function modifyAccountForm(){
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/account/update",
        contentType: "application/json",
        dataType: "html",
        cache:false,
        data: JSON.stringify($("form#accountModifyForm").serializeObject()),
        success: function(response){
            window.location.href = "http://localhost:8080/login";
        },
        error: function(e){
            alert(e.responseText);
        }
    });
}

function deleteAccountForm(){
    $.ajax({
        type: "DELETE",
        url: "http://localhost:8080/account/delete",
        cache:false,
        success: function(response){
            window.location.href = "http://localhost:8080/";
        },
        error: function(e){
            alert(e.responseText);
        }
    });
}

일정 변경 및 제거

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void modifySchedule() throws Exception {
        ScheduleDto scheduleDto = new ScheduleDto();
        scheduleDto.setId(1l);
        scheduleDto.setTitle("meeting");
        String scheduleDtoString = objectMapper.writeValueAsString(scheduleDto);

        mvc.perform(post("/schedule/modify")
                .contentType(MediaType.APPLICATION_JSON)
                .content(scheduleDtoString))
                .andDo(print())
                .andExpect(status().isOk());

        assertThat(scheduleService.getSchedule(1l).getTitle()).isEqualTo("meeting");
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void deleteSchedule() throws Exception {
        Long[] scheduleIdList = new Long[2];
        scheduleIdList[0] = 1L;
        scheduleIdList[1] = 2L;
        System.out.println(scheduleIdList);

        mvc.perform(delete("/schedule")
                .contentType(MediaType.APPLICATION_JSON)
                .content(Arrays.toString(scheduleIdList)))
                .andDo(print())
                .andExpect(status().isOk());
    }
    @PostMapping("/schedule/modify")
    @ResponseBody
    public ResponseEntity<?> modifySchedule(@RequestBody ScheduleDto scheduleDto) {
        scheduleService.modifySchedule(scheduleDto.getId(), scheduleDto);
        return ResponseEntity.ok("{}");
    }

    @DeleteMapping("/schedule")
    @ResponseBody
    public ResponseEntity<?> deleteSchedule(@RequestBody Long[] scheduleIdList) {
        for (Long id : scheduleIdList) {
            scheduleService.deleteSchedule(id);
        }
        return ResponseEntity.ok("{}");
    }
    public Schedule modifySchedule(Long id, ScheduleDto scheduleDto) {
        Schedule schedule = getSchedule(id);
        schedule.modifyByDto(scheduleDto);
        return schedule;
    }

    public void deleteSchedule(Long id) {
        scheduleRepository.deleteById(id);
    }
$(document).ready(function () {
    $(document).on("click","#scheduleSubmit",function (event) {
        submitScheduleForm();
        return false;
    });
    $(document).on("click","#scheduleModify",function (event) {
        modifyScheduleForm();
        return false;
    });
    $(document).on("click","#scheduleRemove",function (event) {
        removeScheduleForm();
        return false;
    });
});

function modifyScheduleForm(){
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/schedule/modify",
        contentType: "application/json",
        cache:false,
        data: JSON.stringify($("form#modifyScheduleForm").serializeObject()),
        success: function(response){
            $("#modifyScheduleModal").modal('hide');
            loadSchedules();
        },
        error: function(e){
            alert(e.responseText);
        }
    });
}

function removeScheduleForm(){
    $.ajax({
        type: "DELETE",
        url: "http://localhost:8080/schedule",
        contentType: "application/json",
        cache:false,
        data: JSON.stringify(checkedSchedules()),
        success: function(response){
            loadSchedules();
        },
        error: function(e){
            alert(e.responseText);
        }
    });
}

function checkedSchedules() {
    var checkedSchedules = [];
    $('input[name="scheduleId"]:checked').each(function(i){
        checkedSchedules.push($(this).val());
    });
    return checkedSchedules;
}

Jquery로 CheckBox에서 check된 value 만 배열에 집어넣는 부분에서 좀 오래걸린것 같다. 그리고 배열을 Json String으로 변환하지 않고 핸들러로 보내서 400 bad request가 계속 발생했었다.

내일은 전체 선택 및 일정 페이징 처리하기.

Comments