코딩하는 털보

11 to 9, Day 7 본문

Diary/Eleven to Nine

11 to 9, Day 7

이정인 2021. 3. 4. 00:00

Today, ToDoList

Toy Project - NGMA

  • 짝꿍 찾기 페이지

짝꿍 찾기 페이지

Lover 관련 테스트

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void showCouple() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");
        accountService.pickLover(account, lover);

        mvc.perform(MockMvcRequestBuilders.get("/account/lover"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(content().string(containsString("sjlee@example.com")));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void showNoCouple() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");

        mvc.perform(MockMvcRequestBuilders.get("/account/lover"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(""));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void getLoverStateNoWaiterNothing() throws Exception {

        mvc.perform(MockMvcRequestBuilders.get("/account/loverState"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name").value("NOTHING"))
                .andExpect(jsonPath("$.hasWaiters").value(false));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void getLoverStateNoWaiterWaiting() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");
        accountService.pickLover(account, lover);

        mvc.perform(MockMvcRequestBuilders.get("/account/loverState"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name").value("WAITING"))
                .andExpect(jsonPath("$.hasWaiters").value(false));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void getLoverStateHasWaiterNothing() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");
        accountService.pickLover(lover, account);

        mvc.perform(MockMvcRequestBuilders.get("/account/loverState"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name").value("NOTHING"))
                .andExpect(jsonPath("$.hasWaiters").value(true));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void getLoverStateHasWaiterWaiting() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");
        accountService.pickLover(lover, account);
        accountService.pickLover(account, lover);

        mvc.perform(MockMvcRequestBuilders.get("/account/loverState"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name").value("WAITING"))
                .andExpect(jsonPath("$.hasWaiters").value(true));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void getLoverStateCoupled() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");
        accountService.pickLover(account, lover);
        accountService.checkLover(lover, "jilee@example.com");

        mvc.perform(MockMvcRequestBuilders.get("/account/loverState"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON))
                .andExpect(jsonPath("$.name").value("COUPLED"))
                .andExpect(jsonPath("$.hasWaiters").value(false));
    }

    @Test
    @WithUserDetails(value = "jilee@example.com", setupBefore = TestExecutionEvent.TEST_EXECUTION)
    public void pick() throws Exception {
        Account account = accountService.getUserByEmail("jilee@example.com");
        Account lover = accountService.getUserByEmail("sjlee@example.com");

        mvc.perform(post("/account/pick")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{\"email\": \"rockintuna@daum.net\"}"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

핸들러 추가

    @GetMapping("/loverState")
    @ResponseBody
    public LoverState getLoverState(@AuthenticationPrincipal UserAccount userAccount) {
        return accountService.getLoverState(userAccount.getAccount());
    }

    @GetMapping("/lover")
    @ResponseBody
    public Account lover(@AuthenticationPrincipal UserAccount userAccount) {
        return userAccount.getAccount().getLover();
    }

    @GetMapping("/waiter")
    @ResponseBody
    public List<Account> getWaiters(@AuthenticationPrincipal UserAccount userAccount) {
        return userAccount.getAccount().getWaiter();
    }

    @PostMapping("/pick")
    @ResponseBody
    public ResponseEntity<?> pick(@AuthenticationPrincipal UserAccount userAccount,
                                  @RequestBody String loverEmail) {
        Account lover = accountService.getUserByEmail(loverEmail);
        accountService.pickLover(userAccount.getAccount(), lover);
        return ResponseEntity.ok().build();
    }

자바 스크립트 함수 추가

serializeObject : Json String 변환 용 메소드

$(document).ready(function () {
    $(document).on("click","#accountSubmit",function (event) {
        submitAccountForm();
        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(){
            alert("Error");
        }
    });
}

$.fn.serializeObject =  function() {
    var obj = null;
    try {
        if(this[0].tagName && this[0].tagName.toUpperCase() === "FORM" ) {
            var arr = this.serializeArray();
            if(arr){
                obj = {};
                jQuery.each(arr, function() {
                    obj[this.name] = this.value;
                });
            }
        }
    } catch(e) {
        alert(e.message);
    } finally {}
    return obj;
}

function fetchPage(name) {
    fetch(name).then(function(response) {
        response.text().then(function(text) {
            document.querySelector('#main').innerHTML = text;
        })
    });
}

function loadCoupleState() {
    $.ajax({
        url: "http://localhost:8080/account/loverState",
        type: "GET",
        dataType: "json",
        success: function(data) {
            checkLoverState(data);
        },
        error: function(e) {
            alert("loverstate 값을 가져오지 못했습니다.");
        }
    });
}

function checkLoverState(loverState) {
    printWaiterTable(loverState.hasWaiters);
    loverStateResult(loverState.name);
}

function printWaiterTable(hasWaiters) {
    if ( hasWaiters == true ) {
        $("table#coupleTable").empty();
        $("table#coupleTable").html('/main-part/waiter-main.html');
        loadWaiters();
    }
}

function loadWaiters() {
    $.ajax({
        url: "http://localhost:8080/account/waiter",
        type: "GET",
        dataType: "json",
        success: function(data) {
            addWaiterRow(data);
        },
        error: function(e) {
            alert("waiters 값을 가져오지 못했습니다.");
        }
    });
}

function addWaiterRow(lover) {
    var tableBody = $("tbody#coupleTable");
    $(tableBody).children("tr").remove();
    $.each(lover, function (i, item) {
        var newRow = $("<tr></tr>").appendTo(tableBody);
        $(newRow).append("<td>"+item.name+"</td>");
        $(newRow).append("<td>"+item.email+"</td>");
        $(newRow).append("<td>"+"<a class=\"btn btn-outline-primary\" type=\"button\" id=\"waiterReject\" data-bs-toggle=\"modal\" data-bs-target=\"#waiterModal\">거절</a>"+"</td>");
        $(newRow).append("<td>"+"<a class=\"btn btn-outline-primary\" type=\"button\" id=\"waiterCheck\" data-bs-toggle=\"modal\" data-bs-target=\"#waiterModal\">확인</a>"+"</td>");
    });
}

function loverStateResult(state) {
    var name;
    $("div#loverStateResult").empty();
    if ( state == "NOTHING" ) {
        $("div#loverStateResult").append("<p class=\"text-sm-start\">아직 연결된 짝꿍이 없으시네요, 나의 짝꿍에게 신청해보세요!</p><a class=\"btn btn-outline-primary\" type=\"button\" id=\"couple\" data-bs-toggle=\"modal\" data-bs-target=\"#coupleModal\">짝꿍 요청하기</a>");
    } else if ( state == "WAITING" ) {
        name = loadLover();
        $("div#loverStateResult").append("<p class=\"text-sm-start\">아직 "+name+"님으로부터 대기중입니다. 상대방의 확인이 끝날 때 까지 기다려주세요.</p>");
    } else {
        name = loadLover();
        $("div#loverStateResult").append("<p class=\"text-sm-start\">"+name+"님과 짝꿍입니다!</p>");
    }
}

function loadLover() {
    var email;
    var name;

    $.ajax({
        url: "http://localhost:8080/account/lover",
        type: "GET",
        dataType: "json",
        success: function(data) {
            email = data.email;
            name = data.name;
        },
        error: function(e) {
            alert("lover 값을 가져오지 못했습니다.");
        }
    });

    return name;
}

짝꿍 페이지 main 부분

Modal을 이용해서 요청하고 요청을 거절/확인 할 수 있도록 할 예정.

<div class="container" id="main_container">
    <main>
        <div class="py-5 text-center">
            <h2>나의 짝꿍</h2>
        </div>

        <div id="loverStateResult">
        </div>

        <table class="table table-hover" id="coupleTable" >
        </table>

    </main>
</div>

<div class="modal fade" id="coupleModal" tabindex="-1" aria-labelledby="coupleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="coupleModalLabel">짝꿍 요청하기</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="coupleForm">
                <div class="modal-body">
                    <form class="needs-validation" novalidate>
                        <div class="col-sm-10">
                            <label for="email" class="form-label">상대방의 Email 주소를 입력해주세요.</label>
                            <input type="email" class="form-control" id="email" name="email" placeholder="" value="" required>
                            <div class="invalid-feedback">
                                상대방의 Email 주소를 입력해 주세요.
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <a type="button" class="btn btn-primary" id="coupleSubmit">요청</a>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="waiterModal" tabindex="-1" aria-labelledby="waiterModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="waiterModalLabel">요청 확인</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">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
                <a type="button" class="btn btn-primary" id="waiterSubmit">확인</a>
            </div>
        </div>
    </div>
</div>

짝꿍 요청 Modal JS

$(document).ready(function () {
    $(document).on("click","#coupleSubmit",function (event) {
        submitCoupleForm();
        return false;
    });
});

function submitCoupleForm(){
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/account/pick",
        contentType: "application/json",
        dataType: "json",
        cache:false,
        data: JSON.stringify($("form#coupleForm").serializeObject()),
        success: function(response){
            $("#coupleModal").modal('hide');
            loadCoupleState();
        },
        error: function(){
            alert("submitCouple Error");
        }
    });
}
Comments