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

[NguyenHCP] feat: send order to mail of customer #125

Merged
merged 1 commit into from
Oct 31, 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 @@ -6,13 +6,15 @@
import com.swp.PodBookingSystem.dto.respone.Account.AccountOrderResponse;
import com.swp.PodBookingSystem.dto.respone.ApiResponse;
import com.swp.PodBookingSystem.dto.respone.AccountResponse;
import com.swp.PodBookingSystem.dto.respone.Order.OrderManagementResponse;
import com.swp.PodBookingSystem.dto.respone.PaginationResponse;
import com.swp.PodBookingSystem.entity.Account;
import com.swp.PodBookingSystem.enums.AccountRole;
import com.swp.PodBookingSystem.exception.AppException;
import com.swp.PodBookingSystem.exception.ErrorCode;
import com.swp.PodBookingSystem.mapper.AccountMapper;
import com.swp.PodBookingSystem.service.AccountService;
import com.swp.PodBookingSystem.service.OrderService;
import com.swp.PodBookingSystem.service.SendEmailService;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletRequest;
Expand Down Expand Up @@ -45,6 +47,7 @@ public class AccountController {
AccountMapper accountMapper;
SendEmailService sendEmailService;
JwtDecoder jwtDecoder;
OrderService orderService;

@PostMapping
ApiResponse<AccountResponse> createAccount(@RequestBody @Valid AccountCreationRequest request) {
Expand Down Expand Up @@ -124,6 +127,16 @@ ApiResponse sendEmail(@RequestBody SendMailRequest request) throws MessagingExce
.build();
}

@PostMapping("/send-email-order")
ApiResponse sendEmailOrder(@RequestBody SendMailOrderRequest request) throws MessagingException, IOException {
OrderManagementResponse order = orderService.getInfoOrder(request.getOrderId());
sendEmailService.sendMailTemplate(request.getEmail(), order, "Hóa đơn tại FlexiPod");
return ApiResponse.builder()
.message("Gửi lời mời đặt lịch thành công")
.code(200)
.build();
}

@GetMapping("/staff")
public ResponseEntity<List<AccountOrderResponse>> getAllStaffAccounts() {
return ResponseEntity.status(HttpStatus.OK).body(accountService.getAllStaffAccounts());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.swp.PodBookingSystem.dto.request.Account;

import lombok.*;
import lombok.experimental.FieldDefaults;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@FieldDefaults(level = AccessLevel.PRIVATE)
public class SendMailOrderRequest {
String email;
String orderId;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import biweekly.property.Method;
import biweekly.util.Duration;
import com.swp.PodBookingSystem.dto.request.CalendarRequest;
import com.swp.PodBookingSystem.dto.respone.Order.OrderManagementResponse;
import com.swp.PodBookingSystem.entity.OrderDetail;
import jakarta.activation.DataHandler;
import jakarta.activation.DataSource;
Expand All @@ -21,18 +22,25 @@
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
Expand All @@ -57,6 +65,56 @@ public void sendEmail(String recipient, String body, String subject) throws Mess
helper.setSubject(subject);
helper.setText(body, true);

javaMailSender.send(mimeMessage);
}

public void sendMailTemplate(String recipient, OrderManagementResponse order, String subject) throws MessagingException, IOException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
ClassPathResource resource = new ClassPathResource("templates/emailTemplate.html");
String content;
try (var inputStream = resource.getInputStream()) {
content = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
}
var roomHaveAmenities = order.getOrderDetails().stream()
.filter(od -> !od.getAmenities().isEmpty())
.collect(Collectors.toList());
double totalPriceRoom = order.getOrderDetails().stream()
.mapToDouble(orderDetail -> orderDetail.getRoomPrice())
.sum();
double totalPriceAmenity = order.getOrderDetails().stream()
.mapToDouble(orderDetail -> orderDetail.getAmenities().stream()
.mapToDouble(amenity -> amenity.getPrice() * amenity.getQuantity())
.sum()
)
.sum();

double priceBeforeDiscount = totalPriceRoom + totalPriceAmenity;
double discountPercentage = order.getOrderDetails().get(0).getServicePackage().getDiscountPercentage();
double finalPrice = priceBeforeDiscount * (1 - discountPercentage / 100);
int integerAmount = (int) Math.round(finalPrice);
String formattedAmount = String.format("%,d", integerAmount).replace(",", ".");
String status;
if (order.getOrderDetails().getFirst().getStatus().equals("Successfully")) {
status = "Đã thanh toán";
} else if (order.getOrderDetails().getFirst().getStatus().equals("Rejected")) {
status = "Đã hủy";
} else {
status = "Đang chờ xử lí";
}

content = content.replace("{{orderId}}", order.getId())
.replace("{{orderStartTime}}", order.getCreatedAt().format(DateTimeFormatter.ofPattern("HH:mm:ss dd-MM-yyyy")))
.replace("{{roomName}}", order.getOrderDetails().getFirst().getRoomTypeName())
.replace("{{status}}", status)
.replace("{{amenity}}", roomHaveAmenities.isEmpty() ? "Không có" : "Có")
.replace("{{totalPrice}}", formattedAmount + " VND");

helper.setFrom(fromEmailId);
helper.setTo(recipient);
helper.setSubject(subject);
helper.setText(content, true);

javaMailSender.send(mimeMessage);
log.info("Send email successfully");
}
Expand Down
118 changes: 118 additions & 0 deletions src/main/resources/templates/emailTemplate.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>FlexiPod Email</title>
<style>
body,
p,
div,
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
</style>
</head>
<body style="background-color: #f4f4f4; margin: 0; padding: 0">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td>
<!-- Header -->
<table
align="center"
border="0"
cellpadding="0"
cellspacing="0"
width="600"
style="border-collapse: collapse; background-color: #ffffff"
>
<tr>
<td align="left" style="padding: 20px">
<h1 style="color: #1976d2; font-size: 24px; font-weight: bold">FlexiPod</h1>
</td>
</tr>
</table>

<!-- Email Content -->
<table
align="center"
border="0"
cellpadding="0"
cellspacing="0"
width="600"
style="border-collapse: collapse; background-color: #ffffff"
>
<tr>
<td style="padding: 40px">
<h2 style="color: #333333; font-size: 20px; margin-bottom: 20px">Hóa đơn của bạn tại
FlexiPod</h2>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Mã đơn: {{orderId}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Ngày đặt: {{orderStartTime}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Trạng thái: {{status}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Loại phòng đặt: {{roomName}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Tiện tích đặt thêm: {{amenity}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5">
Tổng tiền: {{totalPrice}}
</p>
<p style="color: #666666; font-size: 16px; line-height: 1.5; margin-top: 20px">
Cảm ơn vì đã chọn FlexiPod!
</p>
</td>
</tr>
</table>

<!-- Footer -->
<table
align="center"
border="0"
cellpadding="0"
cellspacing="0"
width="600"
style="border-collapse: collapse; background-color: #1976d2"
>
<tr>
<td style="padding: 20px">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr>
<td style="color: #ffffff; font-size: 14px; padding-bottom: 10px">
<strong>FlexiPod</strong>
</td>
</tr>
<tr>
<td style="color: #ffffff; font-size: 12px">Copyright © 2024</td>
</tr>
</table>
</td>
<td align="right" style="padding: 20px">
<a href="#" style="color: #ffffff; text-decoration: none; font-size: 12px; margin-left: 10px"
>Điều khoản và chính sách</a
>
<a href="#" style="color: #ffffff; text-decoration: none; font-size: 12px; margin-left: 10px"
>Liên hệ</a
>

</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>