Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #113

Merged
merged 5 commits into from
Jul 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.requestMatchers(HttpMethod.POST, Endpoints.PUBLIC_POST_ENDPOINTS).permitAll()
.requestMatchers(HttpMethod.PUT, Endpoints.PUBLIC_PUT_ENDPOINTS).permitAll()

.requestMatchers(HttpMethod.GET, Endpoints.STAFF_GET_ENDPOINTS).hasAuthority(Role.STAFF.name())

.requestMatchers(HttpMethod.GET, Endpoints.MANAGER_GET_ENDPOINTS).hasAuthority(Role.MANAGER.name())
.requestMatchers(HttpMethod.POST, Endpoints.MANAGER_POST_ENDPOINTS).hasAuthority(Role.MANAGER.name())
.requestMatchers(HttpMethod.PUT, Endpoints.MANAGER_PUT_ENDPOINTS).hasAuthority(Role.MANAGER.name())
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package vn.webapp.backend.auction.controller;

import jakarta.mail.MessagingException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
Expand All @@ -12,6 +14,7 @@
import vn.webapp.backend.auction.enums.AuctionState;
import vn.webapp.backend.auction.model.Auction;
import vn.webapp.backend.auction.service.auction.AuctionService;
import vn.webapp.backend.auction.service.email.EmailService;

import java.util.List;

Expand All @@ -21,7 +24,8 @@
@RequestMapping("/api/v1/auction")
public class AuctionController {
private final AuctionService auctionService;

@Autowired
private EmailService emailService;
@GetMapping("/sorted-and-paged")
public ResponseEntity<Page<Auction>> getAllAuctionsSortedAndPaged(
@RequestParam(defaultValue = "startDate") String sortBy,
Expand Down Expand Up @@ -139,4 +143,10 @@ public ResponseEntity<Page<AuctionRegistrationDTO>> getAuctionRegistrations(
Pageable pageable = PageRequest.of(page, size, direction, sortBy);
return ResponseEntity.ok(auctionService.getAuctionRegistrations(auctionState, auctionName, pageable));
}

@GetMapping("/delete-result/{id}")
public ResponseEntity<Void> deleteResult(@PathVariable Integer id) throws MessagingException {
auctionService.deleteAuctionResult(id);
return ResponseEntity.ok().build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ public class AuctionRegistrationController {

private final AuctionRegistrationService auctionRegistrationService;

// API to retrieve all registrations for a specific auction
@GetMapping("/auction/{auctionId}")
public ResponseEntity<List<AuctionRegistration>> getRegistrationsForAuction(@PathVariable Integer auctionId) {
List<AuctionRegistration> registrations = auctionRegistrationService.findByAuctionIdAndValid(auctionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ private String handleTransactionPaymentCallback(Integer transactionId, String st
if (!status.equals("00")) {
redirectUrl += "?paymentStatus=failed";
} else {
transactionService.setTransactionState(transactionId, "SUCCEED");
transactionService.setTransactionMethod(transactionId, "BANKING");
transactionService.setTransactionAfterPaySuccess(transactionId);
redirectUrl += "?paymentStatus=success";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundExc
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(err);
}

@ExceptionHandler(UnauthorizedException.class)
@ExceptionHandler({UnauthorizedException.class, UserNotAllowedAccess.class})
public ResponseEntity<ErrorResponse> handleUnauthorizedException(UnauthorizedException ex) {
ErrorResponse err = new ErrorResponse(HttpStatus.FORBIDDEN.value(), ex.getMessage());
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(err);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package vn.webapp.backend.auction.exception;

public class UserNotAllowedAccess extends RuntimeException {
public UserNotAllowedAccess(String message) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

public class ErrorMessages {
public static final String USER_NOT_FOUND = "Không tìm thấy người dùng.";
public static final String USER_NOT_VERIFIED = "Người dùng chưa xác thực.";
public static final String USER_ALREADY_EXIST = "Người dùng đã tồn tại.";
public static final String REQUEST_APPROVAL_NOT_FOUND = "Không tìm thấy yêu cầu.";
public static final String JEWELRY_NOT_FOUND = "Không tìm thấy trang sức.";
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package vn.webapp.backend.auction.model;

public class ReasonMessages {
public static final String DO_NOT_PAY_ON_TIME = "Không thanh toán giao dịch đúng thời hạn quy định.";
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ public interface AuctionRepository extends JpaRepository<Auction, Integer> {
List<Auction> findByState(@Param("auctionState") AuctionState auctionState);

// @Query("SELECT a FROM Auction a WHERE a.state = :auctionState AND (:auctionName IS NULL OR a.name LIKE %:auctionName%)")
@Query("SELECT a FROM Auction a WHERE (:auctionState IS NULL AND a.state <> 'DELETED') OR (a.state = :auctionState) AND (:auctionName IS NULL OR a.name LIKE %:auctionName%)")
List<Auction> findByState(@Param("auctionState") AuctionState auctionState, @Param("auctionName") String auctionName, Pageable pageable);
@Query("SELECT a FROM Auction a WHERE ((:auctionState IS NULL AND a.state <> 'DELETED') OR (a.state = :auctionState)) AND (:auctionName IS NULL OR a.name LIKE %:auctionName%)")
List<Auction> findByState(@Param("auctionState") AuctionState auctionState, @Param("auctionName") String auctionName);

@Query("SELECT a FROM Auction a WHERE " +
"((:auctionState = 'DELETED' AND a.state != 'DELETED') " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,11 @@ public interface TransactionRepository extends JpaRepository<Transaction, Intege
"WHERE t.type = 'PAYMENT_TO_WINNER' " +
"AND t.state != 'SUCCEED' " +
"AND t.state != 'FAILED' " +
"AND t.createDate < :threeDaysAgo " +
"AND t.state != 'HIDDEN' " +
"AND t.createDate < :sevenDaysAgo " +
"AND (:userName IS NULL OR CONCAT(t.user.firstName, ' ', t.user.lastName) LIKE %:userName%)")
Page<Transaction> findOverdueTransactions(@Param("userName") String userName,
@Param("threeDaysAgo") LocalDateTime threeDaysAgo,
@Param("sevenDaysAgo") LocalDateTime sevenDaysAgo,
Pageable pageable);

@Query("SELECT SUM(t.totalPrice) FROM Transaction t WHERE t.type = 'PAYMENT_TO_WINNER' AND t.user.username = :username")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,10 @@ private Endpoints() {
"/api/v1/transaction/set-method/**", "/api/v1/jewelry/set-holding/**"
};

public static final String[] STAFF_GET_ENDPOINTS = {
"/api/v1/user/get-user-registration/**",
};

public static final String[] MANAGER_GET_ENDPOINTS = {
"/api/v1/transaction/get-handover"
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package vn.webapp.backend.auction.service.auction;

import jakarta.mail.MessagingException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import vn.webapp.backend.auction.dto.AuctionRegistrationDTO;
Expand All @@ -23,5 +24,6 @@ public interface AuctionService {
Page<Auction> getByStaffID(Integer id, String auctionName, Pageable pageable);
Auction getCurrentAuctionByJewelryId(Integer id);
Auction createNewAuction(AuctionRequest request);
void deleteAuctionResult(Integer transactionId) throws MessagingException;
Page<AuctionRegistrationDTO> getAuctionRegistrations(AuctionState state, String auctionName, Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package vn.webapp.backend.auction.service.auction;

import jakarta.mail.MessagingException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
Expand All @@ -8,17 +9,14 @@
import org.springframework.stereotype.Service;
import vn.webapp.backend.auction.dto.AuctionRegistrationDTO;
import vn.webapp.backend.auction.dto.AuctionRequest;
import vn.webapp.backend.auction.enums.AccountState;
import vn.webapp.backend.auction.enums.AuctionState;
import vn.webapp.backend.auction.enums.JewelryState;
import vn.webapp.backend.auction.enums.TransactionState;
import vn.webapp.backend.auction.exception.ResourceNotFoundException;
import vn.webapp.backend.auction.model.Auction;
import vn.webapp.backend.auction.model.ErrorMessages;
import vn.webapp.backend.auction.model.Jewelry;
import vn.webapp.backend.auction.model.User;
import vn.webapp.backend.auction.repository.AuctionRegistrationRepository;
import vn.webapp.backend.auction.repository.AuctionRepository;
import vn.webapp.backend.auction.repository.JewelryRepository;
import vn.webapp.backend.auction.repository.UserRepository;
import vn.webapp.backend.auction.model.*;
import vn.webapp.backend.auction.repository.*;
import vn.webapp.backend.auction.service.email.EmailService;

import java.sql.Timestamp;
import java.time.LocalDate;
Expand All @@ -38,7 +36,9 @@ public class AuctionServiceImpl implements AuctionService{
private final AuctionRepository auctionRepository;
private final UserRepository userRepository;
private final JewelryRepository jewelryRepository;
private final TransactionRepository transactionRepository;
private final AuctionRegistrationRepository auctionRegistrationRepository;
private final EmailService emailService;

@Override
public List<Auction> getAll() {
Expand Down Expand Up @@ -136,6 +136,34 @@ public void setAuctionState(Integer id, String state) {
existingAuction.setState(AuctionState.valueOf(state));
}

@Override
public void deleteAuctionResult(Integer transactionId) throws MessagingException {
var existingTransaction = transactionRepository.findById(transactionId)
.orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.TRANSACTION_NOT_FOUND));
Integer auctionId = existingTransaction.getAuction().getId();
Integer jewelryId = existingTransaction.getAuction().getJewelry().getId();
Integer userId = existingTransaction.getUser().getId();
var existingAuction = auctionRepository.findById(auctionId)
.orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.AUCTION_NOT_FOUND));
var existingJewelry = jewelryRepository.findById(jewelryId)
.orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.JEWELRY_NOT_FOUND));
var existingUser = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.USER_NOT_FOUND));

existingTransaction.setState(TransactionState.HIDDEN);
existingAuction.setState(AuctionState.FINISHED);
existingJewelry.setState(JewelryState.ACTIVE);
existingUser.setState(AccountState.DISABLE);

String reason = ReasonMessages.DO_NOT_PAY_ON_TIME;
emailService.sendBlockAccountEmail(
existingUser.getEmail(),
existingUser.getFullName(),
existingUser.getUsername(),
reason
);
}

@Override
public List<Auction> getAuctionByState(AuctionState state) {
return auctionRepository.findByState(state);
Expand All @@ -148,7 +176,7 @@ public Page<Auction> getAuctionsByStates(List<AuctionState> states, Pageable pag

@Override
public Page<AuctionRegistrationDTO> getAuctionRegistrations(AuctionState state, String auctionName, Pageable pageable) {
List<Auction> auctions = auctionRepository.findByState(state, auctionName, pageable);
List<Auction> auctions = auctionRepository.findByState(state, auctionName);
List<AuctionRegistrationDTO> list = auctions.stream()
.map(auction -> {
Integer numberOfParticipants = auctionRegistrationRepository.countValidParticipantsByAuctionId(auction.getId());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import vn.webapp.backend.auction.enums.AuctionRegistrationState;
import vn.webapp.backend.auction.enums.PaymentMethod;
import vn.webapp.backend.auction.enums.TransactionState;
import vn.webapp.backend.auction.enums.TransactionType;
import vn.webapp.backend.auction.enums.*;
import vn.webapp.backend.auction.exception.ResourceNotFoundException;
import vn.webapp.backend.auction.exception.UserNotAllowedAccess;
import vn.webapp.backend.auction.model.*;
import vn.webapp.backend.auction.repository.AuctionRegistrationRepository;
import vn.webapp.backend.auction.repository.AuctionRepository;
Expand All @@ -36,6 +34,10 @@ public void registerUserForAuction(String username, Integer auctionId) {
User user = userRepository.findByUsername(username).orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.USER_NOT_FOUND));
Auction auction = auctionRepository.findById(auctionId).orElseThrow(() -> new ResourceNotFoundException(ErrorMessages.AUCTION_NOT_FOUND));

if (user.getState() != AccountState.VERIFIED) {
throw new UserNotAllowedAccess(ErrorMessages.USER_NOT_VERIFIED);
}

double registrationFee = auction.getParticipationFee() + auction.getDeposit();

Transaction transaction = Transaction.builder()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,4 +159,80 @@ public String setHtmlConfirmHoldingContent(String fullName, String assetName
"</html>\n";
return content;
}

public String setHtmlBlockAccountContent(String fullName, String userName, String reason
) {
String imageUrl = "https://raw.githubusercontent.com/phuuthanh2003/AuctionWebApp_BE/main/logo.png";
String content = "<!DOCTYPE html>\n" +
"<html lang=\"en\">\n" +
"<head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n" +
" <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n" +
" <title>Activation Code</title>\n" +
" <style>\n" +
" body {\n" +
" font-family: Arial, sans-serif;\n" +
" background-color: #f4f4f4;\n" +
" padding: 20px;\n" +
" }\n" +
" .container {\n" +
" max-width: 600px;\n" +
" margin: 0 auto;\n" +
" background-color: #fff;\n" +
" padding: 40px;\n" +
" border-radius: 10px;\n" +
" box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);\n" +
" }\n" +
" h1 {\n" +
" color: #333!important;\n" +
" margin: 10px 0;\n" +
" }\n" +
" h3, h4, div {\n" +
" color: #000!important;" +
" margin: 10px 0;\n" +
" }\n" +
" .activation-code {\n" +
" background-color: #f0f0f0;\n" +
" padding: 10px;\n" +
" border-radius: 5px;\n" +
" font-size: 24px;\n" +
" font-weight: bold;\n" +
" text-align: center;\n" +
" margin: 10px 0;\n" +
" }\n" +
" .mt-20 {\n" +
" margin-top: 20px;\n" +
" }\n" +
" .btn {\n" +
" display: inline-block;\n" +
" padding: 15px 30px;\n" +
" font-size: 16px;\n" +
" color: #fff!important;\n" +
" background-color: #007BFF;\n" +
" border-radius: 5px;\n" +
" text-decoration: none;\n" +
" text-align: center;\n" +
" margin: 20px 0;\n" +
" }\n" +
" .logo {\n" +
" text-align: center;\n" +
" margin: 10px 0;\n" +
" }\n" +
" </style>\n" +
"</head>\n" +
"<body>\n" +
" <div class=\"container\">\n" +
" <div class=\"logo\">\n" +
" <img src=\"" + imageUrl + "\" alt=\"Company Logo\" width=\"200\">\n" +
" </div>\n" +
" <h3>Xin chào, " + fullName + "</h3>\n" +
" <h4>Rất tiếc phải thông báo Tài khoản " + userName + " đã bị khóa.</h4>\n" +
" <h4>Lý do: "+ reason +"</h4>\n" +
" <h5>Cảm ơn bạn đã tin tưởng và đồng hành cùng DGS. Mọi thắc mắc xin liên hệ (+84) 0123456789 để được hỗ trợ và tư vấn.</h5>\n" +
" </div>\n" +
"</body>\n" +
"</html>\n";
return content;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,26 @@ public void sendConfirmHoldingEmail(String to, String fullName, String assetName
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);


String html = emailContent.setHtmlConfirmHoldingContent(fullName,assetName);

helper.setFrom(emailUsername);
helper.setTo(to);
helper.setSubject("Xác nhận tài sản được gửi tới DGS thành công .");
helper.setText(html, true);
javaMailSender.send(message);
}

@Async
public void sendBlockAccountEmail(String to, String fullName, String userName, String reason) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);

String html = emailContent.setHtmlBlockAccountContent(fullName,userName,reason);

helper.setFrom(emailUsername);
helper.setTo(to);
helper.setSubject("Tài khoản DGS của bạn sẽ bị khóa!.");
helper.setText(html, true);

javaMailSender.send(message);
}
Expand Down
Loading
Loading