Skip to content

Commit

Permalink
Merge pull request #67 from final-idea-rush/develop
Browse files Browse the repository at this point in the history
웹 화면 작성
  • Loading branch information
ironprayer committed Sep 4, 2023
2 parents a56ff85 + 50b519d commit bab36e8
Show file tree
Hide file tree
Showing 9 changed files with 209 additions and 81 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ public void updateOf(IdeaRequest ideaRequest, String imageName) {
this.category = ideaRequest.category();
this.imageName = imageName;
this.auctionStartTime = ideaRequest.auctionStartTime();
this.auctionEndTime = ideaRequest.auctionStartTime().plusMinutes(10);
this.minimumStartingPrice = ideaRequest.minimumStartingPrice();
}

Expand All @@ -82,4 +83,8 @@ public void updateBidFail(){
public boolean isAuthUser(Long userId) {
return userId.equals(this.users.getId());
}

public void changeImage(String imagePath) {
this.imageName = imagePath;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public Optional<IdeaOneResponse> findIdeaOne(Long ideaId) {
qUsers.nickname.as("writer"),
qIdea.title,
qIdea.content,
qIdea.imageName.concat(ServerIpAddress.s3Address).as("imageUrl"),
qIdea.imageName.prepend(ServerIpAddress.s3Address).as("imageUrl"),
qIdea.auctionStatus.as("status"),
qIdea.minimumStartingPrice,
qIdea.bidWinPrice,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,10 @@ public void update(Long userId, Long ideaId, IdeaRequest ideaRequest, MultipartF

imageName = image.getOriginalFilename();
s3Service.upload(IMAGE_BASE_PATH + "/" + idea.getId(), imageName, image);
idea.updateOf(ideaRequest, IMAGE_BASE_PATH + "/" + idea.getId() + "/" + imageName);
} else {
idea.updateOf(ideaRequest, imageName);
}

idea.updateOf(ideaRequest, imageName);
}

@Transactional
Expand All @@ -108,6 +109,7 @@ public void createIdea(IdeaRequest ideaRequest, MultipartFile image, Long userId

if (imageName != null) {
String uploadPath = IMAGE_BASE_PATH + "/" + newIdea.getId();
newIdea.changeImage(uploadPath + "/" + imageName);
s3Service.upload(uploadPath, imageName, image);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ServerIpAddress {

public final static String s3Address = "";
public final static String s3Address = "https://idea-rush-image.s3.ap-northeast-2.amazonaws.com/";
public final static String IMAGE_BASE_PATH = "idea/images";

}
2 changes: 2 additions & 0 deletions src/main/resources/static/js/ideaMain.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ function chatting() {
const logoutButton = document.createElement("button");
logoutButton.classList.add("button3"); // 적절한 클래스를 추가하세요
logoutButton.textContent = "Logout"; // 버튼 텍스트 설정
logoutButton.style.width = '300px';
logoutButton.style.height = '50px';
logoutButton.onclick = function () {
// 로그아웃 로직을 여기에 추가하세요.
localStorage.removeItem("authToken")
Expand Down
176 changes: 144 additions & 32 deletions src/main/resources/templates/page/ideaDetail.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
<head>
<meta charset="UTF-8">
<title>Idea Detail</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
<style>
/* Custom CSS */
#content {
Expand Down Expand Up @@ -33,13 +32,13 @@
<!--&lt;!&ndash; 네비게이션 바 &ndash;&gt;-->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<img src="/image/logo.svg" style="height: 35px; width: 35px"></img>
<a class="navbar-brand" href="/" style="margin-left: 5px">Idea Rush</a>
<a class="navbar-brand" href="/view/pageMain" style="margin-left: 5px">Idea Rush</a>
</nav>

<div class="container mt-4">
<div class="row">
<!-- Left Side (Image) -->
<div class="col-md-6">
<div class="col-lg-6">
<div class="card bordered-card" style="height: 550px;">
<div class="card-body d-flex align-items-center justify-content-center" style="height: 100%;">
<img id="image" class="img-fluid" style="object-fit: contain; width: 100%; height: 100%;">
Expand All @@ -58,20 +57,20 @@ <h3 id="title" class="card-title"></h3>
</div>

<!-- Right Side (SSE and Content) -->
<div class="col-md-6">
<div class="col-lg-6">
<!-- SSE Card -->
<div class="card bordered-card" style="height: 550px;">
<div class="card-header text-center">
<h3 class="card-title">실시간 입찰 현황</h3>
<h3 class="card-title" id="bid-streaming"></h3>
</div>
<div class="card-body d-flex flex-column" id="sse-data" style="height: calc(100% - 100px); overflow-y: auto;">
<!-- SSE data will be appended here -->
</div>
<div class="card-footer">
<div class="input-group">
<input type="number" class="form-control" id="bid-price" placeholder="입찰가격을 입력하세요">
<input type="number" class="form-control" id="bid-price" placeholder="Enter the bid price">
<div class="input-group-append">
<button class="btn btn-primary" id="bid-button">입찰</button>
<button class="btn btn-primary" id="bid-button">BID</button>
</div>
</div>
</div>
Expand All @@ -82,18 +81,22 @@ <h3 class="card-title">실시간 입찰 현황</h3>
<!-- Content will go here -->
</div>
</div>
</div>
<div class="col-lg-12"> &nbsp; </div>

<div class="text-right mt-2">
<button class="btn btn-secondary btn-sm" id="edit-button">수정</button>
</div>
<div class="col-lg-12" style="text-align: right">
<button id="delete-button" onclick="deleteIdea()" class="btn btn-dark">DELETE</button>
<button id="edit-button" onclick="updateIdea()" class="btn btn-dark">UPDATE</button>
</div>
<div class="col-lg-12"> &nbsp; </div>
</div>
</div>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<script>
const url = new URL(window.location.href);
Expand All @@ -113,23 +116,94 @@ <h3 class="card-title">실시간 입찰 현황</h3>
img.src = url;
}

function deleteBid() {
// let jwtToken = localStorage.getItem("authToken");
//
// $.ajax({
// url: sendUrl,
// method: "GET",

}

function updateIdea() {
const url = new URL(window.location.href);
const urlParams = url.searchParams;

let ideaId = urlParams.get('id');
window.location.href = "/view/pageUpdate?id=" + ideaId;
}

function parseJwt(token) {
try {
// 토큰을 '.' 으로 나누어 헤더, 페이로드, 시그니처를 얻습니다.
const base64Url = token.split('.')[1];

// base64Url을 디코딩하여 JSON 문자열을 얻습니다.
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));

// JSON 문자열을 파싱하여 JavaScript 객체를 얻습니다.
return JSON.parse(jsonPayload);
} catch (e) {
return null; // 올바르지 않은 토큰 형식의 경우 null을 반환
}
};

function deleteIdea() {
let jwtToken = localStorage.getItem("authToken");
let ideaId = urlParams.get('id');
let sendUrl = "/api/ideas/" + ideaId;

if (confirm('Are you sure you want to delete this idea?')) { // 삭제 확인
$.ajax({
url: sendUrl,
method: "DELETE",
headers: {
Authorization: `Bearer ${jwtToken}`
},
success: function(data) {
alert("Idea successfully deleted!");
window.location.href = '/view/pageMain'; // 삭제 성공 후 홈으로 리다이렉트
},
error: function(err) {
console.log("An error occurred:", err);
alert("Failed to delete idea!");
}
});
}
}


$(document).ready(function() {


let jwtToken = localStorage.getItem("authToken");
let payload = parseJwt(jwtToken)

$.ajax({
url: sendUrl,
method: "GET",
success: function(data) {
console.log("Received data:", data);
$("#title").text(data.title);
$("#writer").html("<strong>작성자:</strong> " + data.writer);
$("#status").html("<strong>경매 상태:</strong> " + data.status);
$("#writer").html("<strong>WRITER :</strong> " + data.writer);
$("#status").html("<strong>BID STATUS :</strong> " + data.status);
// BidLastPrice를 웹 페이지에 삽입
if (data.BidLastPrice) {
$("#bid-streaming").text("CURRENT BID PRICE: ₩ " + numberWithCommas(data.BidLastPrice));
} else {
$("#bid-streaming").text("CURRENT BID PRICE: ₩ " + numberWithCommas(data.minimumStartingPrice));
}

if (data.status === "END") {
$("#BidWinPrice").html("<strong>낙찰가:</strong> " + data.BidWinPrice);
$("#BidWinPrice").html("<strong>WINNING BID PRICE :</strong> " + numberWithCommas(data.BidWinPrice));
$("#BidWinPrice").show();
$("#minimumStartingPrice").hide();
} else {
$("#BidWinPrice").hide();
$("#minimumStartingPrice").html("<strong>최소 입찰 금액:</strong> " + data.minimumStartingPrice);
$("#minimumStartingPrice").html("<strong>MINIMUN BID PRICE :</strong> " + numberWithCommas(data.minimumStartingPrice));
$("#minimumStartingPrice").show();
}

Expand All @@ -142,13 +216,30 @@ <h3 class="card-title">실시간 입찰 현황</h3>
$("#image").attr("src", "/image/logo.svg");
}
});
//writerId를 response에서 받아와야 할 듯
// var loggedInUserId = localStorage.getItem('userId');
// if (data.writerId === loggedInUserId) {
// $("#edit-button").show(); // '수정' 버튼 보여주기
// } else {
// $("#edit-button").hide(); // '수정' 버튼 숨기기
// }

const bidPriceInput = document.getElementById("bid-price");
const bidButton = document.getElementById("bid-button");

if(data.status === "END" || data.status === "PREPARE") {
bidButton.disabled = true;
bidPriceInput.disabled = true;

}

if(payload){
var loggedInUserId = payload.userId;
console.log(loggedInUserId) // 현재 접속중인 사람 id
console.log(data.id) // 게시물의 주인 id
if (Number(data.id) === Number(loggedInUserId)) {
$("#edit-button").show(); // '수정' 버튼 보여주기
$("#delete-button").show(); // '삭제' 버튼 보여주기
} else {
$("#edit-button").hide(); // '수정' 버튼 숨기기
$("#delete-button").hide(); // '삭제' 버튼 숨기기
}
}


},
error: function(err) {
console.log("An error occurred:", err);
Expand All @@ -161,7 +252,12 @@ <h3 class="card-title">실시간 입찰 현황</h3>
console.log("Bid price update event received:", e.data);

var newElement = document.createElement('p');
newElement.textContent = e.data + '원에 입찰 되었습니다.';
newElement.textContent = "It was bid for " + numberWithCommas(e.data) + " won."

var element = document.getElementById("bid-streaming");

// 원하는 새 텍스트로 변경합니다.
element.innerHTML = "CURRENT BID PRICE: ₩ " + numberWithCommas(e.data);

var sseDataDiv = document.getElementById('sse-data');
sseDataDiv.appendChild(newElement);
Expand All @@ -173,41 +269,57 @@ <h3 class="card-title">실시간 입찰 현황</h3>

// 빈 값인지 검증
if (!bidPrice) {
alert("입찰 가격을 입력해주세요.");
alert("Please Input Bid Price");
return;
}

// BidRequest 객체 생성
// BidRequest 객체 생성찰
var bidRequest = {
"bidPrice": parseInt(bidPrice)
};

// 서버에 POST 요청 보내기
$.ajax({
url: "http://3.36.98.58:8080/api/ideas/" + ideaId + "/bid",
url: "/api/ideas/" + ideaId + "/bid",
method: "POST",
contentType: "application/json",
data: JSON.stringify(bidRequest),
// headers: {
// // 헤더에 토큰 추가
// },
headers: {
Authorization: `Bearer ${jwtToken}`
},
success: function(response) {
console.log("Bid successfully created:", response);
alert("입찰이 성공적으로 완료되었습니다.");
alert("Bid Success!");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("An error occurred while creating the bid:", jqXHR, textStatus, errorThrown);

// HTTP 상태 코드가 401인 경우 로그인 필요 알림 띄우기
if(jqXHR.status === 401) {
alert("로그인이 필요합니다.");
alert("Please Login!");
} else {
alert("유효하지 않은 입찰금액입니다.");
alert("UnValid Bid Price!");
}
}
});
});


function numberWithCommas(number) {
// 숫자를 문자열로 변환합니다.
var numberString = number.toString();

// 숫자 문자열을 배열로 나눕니다.
var parts = numberString.split(".");

// 정수 부분에 쉼표를 추가합니다.
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");

// 다시 합쳐서 포맷팅된 숫자를 반환합니다.
return parts.join(".");
}



});
</script>
9 changes: 5 additions & 4 deletions src/main/resources/templates/page/ideaMain.html
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,12 @@


.button3 {
float: left;
margin-left: 245px;
margin-top: 10px;
float: none;
margin-left: 55px;
margin-right: auto;
/*margin-top: 10px;*/
display: flex;
width: 160px;
/*width: 100px;*/
padding: 12px;
flex-direction: column;
justify-content: center;
Expand Down
Loading

0 comments on commit bab36e8

Please sign in to comment.